diff --git a/.Rbuildignore b/.Rbuildignore index d180bc0..4a01367 100644 --- a/.Rbuildignore +++ b/.Rbuildignore @@ -1,5 +1,6 @@ ^.*\.Rproj$ ^\.Rproj\.user$ +^\.vscode($|/) ^docs$ ^vignettes$ ^data-raw$ @@ -20,4 +21,5 @@ CLAUDE.md .DS_Store ^tools/check-save-map-integration\.R$ ^tmp$ +^private($|/) ^\.dockerignore$ diff --git a/.gitignore b/.gitignore index cbdcf3a..f1b7605 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,4 @@ CLAUDE.md .claude tmp/ examples/ +data-raw/flowmap-vendor/node_modules/ diff --git a/DESCRIPTION b/DESCRIPTION index 7b86010..d61ff3e 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -2,8 +2,11 @@ Package: mapgl Title: Interactive Maps with 'Mapbox GL JS' and 'MapLibre GL JS' Version: 0.4.9.9000 Date: 2026-05-14 -Authors@R: - person(given = "Kyle", family = "Walker", email = "kyle@walker-data.com", role = c("aut", "cre")) +Authors@R: c( + person(given = "Kyle", family = "Walker", email = "kyle@walker-data.com", role = c("aut", "cre")), + person(given = "Egor", family = "Kotov", email = "kotov.egor@gmail.com", role = c("aut", "ctb"), comment = c(ORCID = "0000-0001-6690-5345", "added Flowmap.gl, layer tuner, time control") + ) + ) Description: Provides an interface to the 'Mapbox GL JS' () and the 'MapLibre GL JS' () interactive mapping libraries to help users create custom interactive maps in R. Users can create interactive globe visualizations; layer 'sf' objects to create @@ -12,6 +15,7 @@ Description: Provides an interface to the 'Mapbox GL JS' ( 2}), +#' which reduces the rows from 213,227 to 6,092, and compresses the final size +#' to just **~22 KB**. +#' +#' @format A data frame with 6,092 rows and 4 variables: +#' \describe{ +#' \item{time}{Hourly timestamp (POSIXct, UTC)} +#' \item{origin}{Origin station ID (factor, matching \code{bixi_locations$id})} +#' \item{dest}{Destination station ID (factor, matching \code{bixi_locations$id})} +#' \item{count}{Aggregated number of bike sharing trips in that hour (integer)} +#' } +#' @source BIXI Montréal Open Data (\url{https://bixi.com/fr/donnees-ouvertes}). +#' Prepared for \url{https://github.com/FlowmapBlue/FlowmapBlue} by Ilya Boyandin (\url{https://twitter.com/ilyabo}). +#' Original interactive visualization on Flowmap.blue: +#' \url{https://www.flowmap.blue/1qTVOzkPB7U1ySI4g4uPtVBzzEDCI8n1WXAmQeZL15fE} +#' @seealso \code{\link{bixi_locations}} +#' @examples +#' # Check first few records +#' print(head(bixi_flows)) +"bixi_flows" diff --git a/R/flowmap.R b/R/flowmap.R new file mode 100644 index 0000000..b1fcdb0 --- /dev/null +++ b/R/flowmap.R @@ -0,0 +1,1332 @@ +#' FlowMapGL color scheme names +#' +#' Returns the FlowMapGL 9.3.0 preset color scheme names supported by +#' [add_flowmap()]. These names are case-sensitive. +#' +#' @details +#' The bundled FlowMapGL presets are: +#' `r flowmap_color_schemes_markdown()`. +#' +#' @return A character vector of FlowMapGL preset names. +#' @export +#' +#' @examples +#' flowmap_color_schemes() +flowmap_color_schemes <- function() { + flowmap_color_scheme_registry() +} + + + +#' Adds a FlowmapGL layer for visualizing origin-destination flows between +#' point locations. +#' +#' @param map A map object created by [mapboxgl()] or [maplibre()]. +#' @param id A unique layer ID. +#' @param locations A data frame or `sf` point object with location data. +#' Data frames must include `id`, `lat`, and `lon` columns. `sf` point +#' objects must include `id`; coordinates are transformed to EPSG:4326 and +#' serialized as `lon`/`lat`. +#' @param flows A data frame with `origin`, `dest`, and `count` columns. +#' @param flow_color_scheme FlowMapGL preset color scheme name, a character +#' vector of at least two CSS colors, or a `mapgl_continuous_scale` object +#' created by [interpolate_palette()]. Preset names are case-sensitive; use +#' [flowmap_color_schemes()] to list them. +#' @param flow_opacity Layer opacity between 0 and 1. +#' @param flow_dark_mode Logical (`TRUE` or `FALSE`), or `"auto"`; whether to use FlowMapGL dark-mode +#' colors. If `"auto"`, the mode is dynamically detected based on the map style. +#' @param flow_blend Logical (`TRUE` or `FALSE`), `"auto"`, or a character string specifying a CSS +#' mix-blend-mode. +#' +#' Valid modes are: `"normal"`, `"multiply"`, `"screen"`, `"overlay"`, `"darken"`, +#' `"lighten"`, `"color-dodge"`, `"color-burn"`, `"hard-light"`, `"soft-light"`, +#' `"difference"`, `"exclusion"`, `"hue"`, `"saturation"`, `"color"`, and `"luminosity"`. +#' +#' **Recommendations**: +#' * On **dark basemaps**: `"screen"` looks best, creating a glowing additive effect where flows overlap. +#' * On **light basemaps**: `"multiply"` or `"darken"` looks best, increasing contrast against the light background. +#' +#' If `"auto"`, automatically chooses `"screen"` for dark styles and `"multiply"` for light styles. +#' If `before_id` or `slot` is specified (interleaved mode), `"auto"` quietly disables blending (`FALSE`) +#' without throwing a warning. If `TRUE`, defaults to `"screen"` when `flow_dark_mode` is `TRUE`, +#' and `"multiply"` when `FALSE`. If `FALSE`, no blending is applied. Note: CSS blending requires +#' a standalone canvas overlay and is ignored when `before_id` or `slot` is specified. +#' @param flow_fade_amount Controls how much lower-magnitude flows fade compared to higher ones. Range: 0-100. +#' @param flow_highlight_color Color used for highlighting hovered elements. +#' @param flow_locations_enabled Whether to show location circles. +#' @param flow_location_totals_enabled Whether to show incoming/outgoing totals as concentric circles at each location. +#' @param flow_location_labels_enabled Whether to show text labels at locations. +#' @param flow_lines_rendering_mode Controls how flow lines are rendered: `"straight"`, `"animated-straight"`, or `"curved"`. +#' @param flow_line_thickness_scale Multiplier for flow line thickness. +#' @param flow_line_curviness Multiplier for flow line curviness (only used when `flow_lines_rendering_mode` is `"curved"`). +#' @param flow_clustering_enabled Whether to cluster nearby locations when zoomed out. +#' @param flow_clustering_auto Whether to automatically adjust clustering level based on zoom. +#' @param flow_clustering_level Fixed clustering zoom level. Only used when `flow_clustering_auto` is `FALSE`. +#' @param flow_fade_enabled Whether to apply color fading to lower-magnitude flows. +#' @param flow_fade_opacity_enabled Whether to also fade opacity for lower-magnitude flows. +#' @param flow_adaptive_scales_enabled Whether to adapt flow thickness and +#' color scales to the current viewport. This controls the spatial scale +#' domain while panning and zooming. +#' @param flow_temporal_scale_domain For temporal flowmaps, whether flow +#' thickness and color scales use only the currently selected time range +#' (`"selected"`) or all flow data across the full time extent (`"all"`). +#' @param flow_max_top_flows_display_num Maximum number of flows to display. +#' @param flow_endpoints_in_viewport_mode Controls when a flow is considered visible based on endpoint locations: `"any"` or `"both"`. +#' @param flow_time_column Optional column name in `flows` for time data. +#' @param flow_selected_time_range Optional vector of two dates (or strings) for initial time filtering. +#' @param flow_selected_locations Optional vector of location IDs to select. +#' @param flow_location_filter_mode Optional location filter mode: `"ALL"`, `"INCOMING"`, `"OUTGOING"`, or `"BETWEEN"`. +#' @param tooltip Tooltip configuration. Use `FALSE` or `NULL` to disable +#' tooltips, `TRUE` for default tooltips, a single template string, +#' a named list, or a [tooltip_options()] object. +#' @param popup Popup configuration. Use `FALSE` or `NULL` to disable +#' popups, `TRUE` for default popups, a single template string, +#' a named list, or a [popup_options()] object. +#' @param tooltip_style Tooltip rendering style: `"floating"` (cursor-following) +#' or `"anchored"` (fixed to feature). +#' @param popup_style Popup rendering style: `"floating"` (at click position) +#' or `"anchored"` (fixed to feature). +#' @param tooltip_theme Tooltip theme. `"auto"` follows `flow_dark_mode`; +#' `"light"` and `"dark"` force a theme. +#' @param popup_theme Popup theme. `"auto"` follows `flow_dark_mode`; +#' `"light"` and `"dark"` force a theme. +#' @param tooltip_options A named list of renderer-specific tooltip options. +#' @param popup_options A named list of renderer-specific popup options. +#' @param visibility Whether the layer is initially `"visible"` or `"none"`. +#' @param before_id Optional map layer ID to render before. +#' @param slot Optional Mapbox Standard slot. +#' +#' @return The modified map object with the flowmap layer added. +#' +#' @details +#' Mapbox and MapLibre layer paint arguments such as `fill_color`, +#' `circle_color`, and `line_color` require a scalar CSS color or a style +#' expression. Use `interpolate_palette(...)$expression` for data-driven layer +#' color ramps. FlowMapGL's `flow_color_scheme` accepts a preset name such as +#' `"Teal"`, a plain color ramp such as `c("red", "white", "blue")`, or an +#' `interpolate_palette(...)` scale object. +#' +#' Flow scale domains have separate spatial and temporal controls. +#' `flow_adaptive_scales_enabled = TRUE` rescales flow thickness and color for +#' the current viewport; `FALSE` keeps the scale tied to the broader map extent. +#' For temporal flowmaps, `flow_temporal_scale_domain = "selected"` rescales +#' within the selected time-control interval, while `"all"` keeps the scale +#' comparable across the full time extent. +#' @export +#' +#' @examples +#' # Create a flowmap centered on Montréal using the bundled datasets +#' maplibre( +#' style = carto_style("dark-matter"), +#' center = c(-73.58, 45.50), +#' zoom = 11, +#' projection = "mercator" +#' ) |> +#' add_flowmap( +#' id = "bixi-rides", +#' locations = bixi_locations, +#' flows = bixi_flows, +#' flow_time_column = "time", +#' flow_color_scheme = "Teal", +#' flow_dark_mode = TRUE +#' ) |> +#' add_time_control( +#' data = bixi_flows, +#' time_column = "time", +#' time_interval = "hour", +#' title = "BIXI Montréal Rides" +#' ) +add_flowmap <- function( + map, + id, + locations, + flows, + flow_color_scheme = "Teal", + flow_opacity = 1, + flow_dark_mode = "auto", + flow_blend = "auto", + flow_fade_amount = 50, + flow_highlight_color = "#ff9b29", + flow_locations_enabled = TRUE, + flow_location_totals_enabled = TRUE, + flow_location_labels_enabled = FALSE, + flow_lines_rendering_mode = c("straight", "animated-straight", "curved"), + flow_line_thickness_scale = 1, + flow_line_curviness = 1, + flow_clustering_enabled = TRUE, + flow_clustering_auto = TRUE, + flow_clustering_level = NULL, + flow_fade_enabled = TRUE, + flow_fade_opacity_enabled = FALSE, + flow_adaptive_scales_enabled = TRUE, + flow_temporal_scale_domain = c("selected", "all"), + flow_max_top_flows_display_num = 5000, + flow_endpoints_in_viewport_mode = c("any", "both"), + flow_time_column = NULL, + flow_selected_time_range = NULL, + flow_selected_locations = NULL, + flow_location_filter_mode = c("ALL", "INCOMING", "OUTGOING", "BETWEEN"), + tooltip = TRUE, + popup = FALSE, + tooltip_style = c("floating", "anchored"), + popup_style = c("floating", "anchored"), + tooltip_theme = c("auto", "light", "dark"), + popup_theme = c("auto", "light", "dark"), + tooltip_options = list(), + popup_options = list(), + visibility = c("visible", "none"), + before_id = NULL, + slot = NULL +) { + if (!inherits(map, "mapboxgl") && !inherits(map, "maplibregl")) { + rlang::abort("`map` must be created by `mapboxgl()` or `maplibre()`.") + } + + if (!is.character(id) || length(id) != 1 || is.na(id) || !nzchar(id)) { + rlang::abort("`id` must be a non-empty character string.") + } + + visibility <- match.arg(visibility) + flow_lines_rendering_mode <- match.arg(flow_lines_rendering_mode) + flow_temporal_scale_domain <- match.arg(flow_temporal_scale_domain) + flow_endpoints_in_viewport_mode <- match.arg(flow_endpoints_in_viewport_mode) + flow_location_filter_mode <- match.arg(flow_location_filter_mode) + tooltip_style <- match.arg(tooltip_style) + tooltip_theme <- match.arg(tooltip_theme) + + if ( + !is.numeric(flow_opacity) || + length(flow_opacity) != 1 || + is.na(flow_opacity) || + flow_opacity < 0 || + flow_opacity > 1 + ) { + rlang::abort("`flow_opacity` must be a number between 0 and 1.") + } + + # Determine dark mode if "auto" + if (identical(flow_dark_mode, "auto")) { + flow_dark_mode <- is_dark_style(map$x$style) + } + + flow_dark_mode <- flowmap_validate_dark_mode(flow_dark_mode) + + # Normalize interactions + tooltip_config <- flowmap_normalize_interaction( + tooltip, + style = tooltip_style, + theme = tooltip_theme, + popup_props = tooltip_options, + dark_mode = flow_dark_mode, + behavior = "hover", + default_enabled = TRUE, + locations_df = locations, + flows_df = flows + ) + + popup_config <- flowmap_normalize_interaction( + popup, + style = popup_style, + theme = popup_theme, + popup_props = popup_options, + dark_mode = flow_dark_mode, + behavior = "click", + default_enabled = FALSE, + locations_df = locations, + flows_df = flows + ) + + use_interleaved <- !is.null(before_id) || !is.null(slot) + + # Resolve blend mode if "auto" + if (identical(flow_blend, "auto")) { + if (use_interleaved) { + flow_blend <- FALSE + } else { + flow_blend <- if (flow_dark_mode) "screen" else "multiply" + } + } else if (isTRUE(flow_blend)) { + # If explicitly TRUE, we still resolve to the best blend mode + flow_blend <- if (flow_dark_mode) "screen" else "multiply" + } + + if (use_interleaved && (!is.logical(flow_blend) || flow_blend)) { + rlang::warn( + "`flow_blend` is ignored when `before_id` or `slot` is specified. CSS blending requires a separate canvas overlay, which is not supported in interleaved mode." + ) + } + + if (is.logical(flow_blend)) { + if (length(flow_blend) != 1 || is.na(flow_blend)) { + rlang::abort("`flow_blend` must be `TRUE` or `FALSE`.") + } + } else if (is.character(flow_blend)) { + if ( + length(flow_blend) != 1 || + is.na(flow_blend) || + !nzchar(trimws(flow_blend)) + ) { + rlang::abort("`flow_blend` must be a valid CSS blend mode name.") + } + valid_modes <- c( + "normal", + "multiply", + "screen", + "overlay", + "darken", + "lighten", + "color-dodge", + "color-burn", + "hard-light", + "soft-light", + "difference", + "exclusion", + "hue", + "saturation", + "color", + "luminosity" + ) + if (!flow_blend %in% valid_modes) { + rlang::abort(paste0( + "`flow_blend` must be one of the valid CSS mix-blend-mode values: ", + paste(paste0("\"", valid_modes, "\""), collapse = ", ") + )) + } + } else { + rlang::abort( + "`flow_blend` must be a logical (`TRUE` or `FALSE`) or a valid CSS blend mode string." + ) + } + + flowmap_validate_logical(flow_locations_enabled, "flow_locations_enabled") + flowmap_validate_logical( + flow_location_totals_enabled, + "flow_location_totals_enabled" + ) + flowmap_validate_logical( + flow_location_labels_enabled, + "flow_location_labels_enabled" + ) + flowmap_validate_logical(flow_clustering_enabled, "flow_clustering_enabled") + flowmap_validate_logical(flow_clustering_auto, "flow_clustering_auto") + flowmap_validate_logical(flow_fade_enabled, "flow_fade_enabled") + flowmap_validate_logical( + flow_fade_opacity_enabled, + "flow_fade_opacity_enabled" + ) + flowmap_validate_logical( + flow_adaptive_scales_enabled, + "flow_adaptive_scales_enabled" + ) + + if ( + !is.character(flow_highlight_color) || + length(flow_highlight_color) != 1 || + is.na(flow_highlight_color) + ) { + rlang::abort("`flow_highlight_color` must be a single string.") + } + + if ( + !is.numeric(flow_fade_amount) || + length(flow_fade_amount) != 1 || + is.na(flow_fade_amount) || + flow_fade_amount < 0 || + flow_fade_amount > 100 + ) { + rlang::abort("`flow_fade_amount` must be a number between 0 and 100.") + } + + if ( + !is.numeric(flow_max_top_flows_display_num) || + length(flow_max_top_flows_display_num) != 1 || + is.na(flow_max_top_flows_display_num) || + flow_max_top_flows_display_num <= 0 + ) { + rlang::abort("`flow_max_top_flows_display_num` must be a positive number.") + } + + if ( + !is.numeric(flow_line_thickness_scale) || + length(flow_line_thickness_scale) != 1 || + is.na(flow_line_thickness_scale) + ) { + rlang::abort("`flow_line_thickness_scale` must be a number.") + } + + if ( + !is.numeric(flow_line_curviness) || + length(flow_line_curviness) != 1 || + is.na(flow_line_curviness) + ) { + rlang::abort("`flow_line_curviness` must be a number.") + } + + if (!is.null(flow_clustering_level)) { + if ( + !is.numeric(flow_clustering_level) || + length(flow_clustering_level) != 1 || + is.na(flow_clustering_level) + ) { + rlang::abort("`flow_clustering_level` must be a number or NULL.") + } + } + + if (!is.null(flow_selected_time_range)) { + if (length(flow_selected_time_range) != 2) { + rlang::abort( + "`flow_selected_time_range` must be a vector of two elements (start and end)." + ) + } + } + + if (!is.null(flow_selected_locations)) { + flow_selected_locations <- as.character(flow_selected_locations) + } + + flow_color_scheme <- flowmap_normalize_color_scheme(flow_color_scheme) + before_id <- flowmap_validate_optional_string(before_id, "before_id") + slot <- flowmap_validate_optional_string(slot, "slot") + + locations <- flowmap_locations_to_df(locations) + flows <- flowmap_flows_to_df(flows, time_column = flow_time_column) + flowmap_validate_ids(locations, flows) + + flowmap_config <- list( + id = id, + data = list( + locations = locations, + flows = flows + ), + settings = list( + colorScheme = flow_color_scheme, + darkMode = flow_dark_mode, + opacity = flow_opacity, + flowBlend = flow_blend, + fadeAmount = flow_fade_amount, + highlightColor = flow_highlight_color, + locationsEnabled = flow_locations_enabled, + locationTotalsEnabled = flow_location_totals_enabled, + locationLabelsEnabled = flow_location_labels_enabled, + flowLinesRenderingMode = flow_lines_rendering_mode, + flowLineThicknessScale = flow_line_thickness_scale, + flowLineCurviness = flow_line_curviness, + clusteringEnabled = flow_clustering_enabled, + clusteringAuto = flow_clustering_auto, + clusteringLevel = flow_clustering_level, + fadeEnabled = flow_fade_enabled, + fadeOpacityEnabled = flow_fade_opacity_enabled, + adaptiveScalesEnabled = flow_adaptive_scales_enabled, + temporalScaleDomain = flow_temporal_scale_domain, + maxTopFlowsDisplayNum = flow_max_top_flows_display_num, + flowEndpointsInViewportMode = flow_endpoints_in_viewport_mode, + timeColumn = flow_time_column, + selectedTimeRange = flow_selected_time_range, + selectedLocations = flow_selected_locations, + locationFilterMode = flow_location_filter_mode + ), + visibility = visibility, + beforeId = before_id, + slot = slot + ) + + if (isTRUE(tooltip_config$enabled)) { + flowmap_config$tooltip <- tooltip_config + } + + if (isTRUE(popup_config$enabled)) { + flowmap_config$popup <- popup_config + } + + if (is.null(map$x$flowmaps)) { + map$x$flowmaps <- list() + } + + map$x$flowmaps <- c(map$x$flowmaps, list(flowmap_config)) + mapgl_record_flowmap_order( + map, + flowmap_index = length(map$x$flowmaps), + pending = is.null(before_id) && (is.logical(flow_blend) && !flow_blend) + ) +} + +#' Update flowmap filter +#' +#' Updates the filter state of a flowmap layer, including selected locations +#' and time range. +#' +#' @param proxy A map proxy object. +#' @param id The ID of the flowmap layer to update. +#' @param selected_locations Optional vector of location IDs to select. +#' @param location_filter_mode Optional location filter mode: `"ALL"`, `"INCOMING"`, `"OUTGOING"`, or `"BETWEEN"`. +#' @param selected_time_range Optional vector of two dates for time filtering. +#' +#' @return The modified map proxy. +#' @export +set_flowmap_filter <- function( + proxy, + id, + selected_locations = NULL, + location_filter_mode = NULL, + selected_time_range = NULL +) { + filter <- list() + if (!is.null(selected_locations)) { + filter$selectedLocations <- selected_locations + } + if (!is.null(location_filter_mode)) { + filter$locationFilterMode <- location_filter_mode + } + if (!is.null(selected_time_range)) { + if (length(selected_time_range) != 2) { + rlang::abort("`selected_time_range` must be a vector of two elements.") + } + filter$selectedTimeRange <- selected_time_range + } + + if (length(filter) == 0) { + return(proxy) + } + + flowmap_invoke_method(proxy, "set_flowmap_filter", id = id, filter = filter) +} + +#' Update a flowmap setting +#' +#' Updates one setting of a flowmap layer. +#' +#' @param map A map object created by [mapboxgl()] or [maplibre()], or a proxy +#' object created by [mapboxgl_proxy()] or [maplibre_proxy()]. +#' @param id The ID of the flowmap layer to update. +#' @param name The setting name to update. Supported canonical FlowMapGL +#' setting names are `opacity`, `colorScheme`, `darkMode`, `fadeAmount`, +#' `highlightColor`, `locationsEnabled`, `locationTotalsEnabled`, +#' `locationLabelsEnabled`, `flowLinesRenderingMode`, +#' `flowLineThicknessScale`, `flowLineCurviness`, `clusteringEnabled`, +#' `clusteringAuto`, `clusteringLevel`, `fadeEnabled`, +#' `fadeOpacityEnabled`, `adaptiveScalesEnabled`, `temporalScaleDomain`, +#' `maxTopFlowsDisplayNum`, and `flowEndpointsInViewportMode`. +#' Snake-case aliases such as `color_scheme`, `temporal_scale_domain`, and +#' `max_top_flows_display_num` are accepted and normalized internally. +#' Filter state (`selectedTimeRange`, `selectedLocations`, and +#' `locationFilterMode`) must be updated with [set_flowmap_filter()]. +#' @param value The setting value. +#' +#' @return The modified map object. +#' +#' @details +#' `colorScheme` accepts the same values as `flow_color_scheme` in +#' [add_flowmap()]: a FlowMapGL preset name, a character vector of at least two +#' CSS colors, or a `mapgl_continuous_scale` object from +#' [interpolate_palette()]. `opacity` must be between 0 and 1. `fadeAmount` +#' must be between 0 and 100. `maxTopFlowsDisplayNum` must be positive. +#' `clusteringLevel` must be numeric or `NULL`. `flowLinesRenderingMode` must +#' be `"straight"`, `"animated-straight"`, or `"curved"`. +#' `temporalScaleDomain` must be `"selected"` or `"all"`. +#' `flowEndpointsInViewportMode` must be `"any"` or `"both"`. Boolean +#' settings must be scalar `TRUE` or `FALSE`. +#' @export +set_flowmap_settings <- function(map, id, name, value) { + setting <- flowmap_normalize_setting(name, value) + settings <- stats::setNames(list(setting$value), setting$name) + + flowmap_invoke_method( + map, + "set_flowmap_settings", + id = id, + settings = settings + ) +} + +flowmap_invoke_method <- function(map, type, ...) { + args <- list(...) + if (any(inherits(map, "mapboxgl_proxy"), inherits(map, "maplibre_proxy"))) { + if ( + inherits(map, "mapboxgl_compare_proxy") || + inherits(map, "maplibre_compare_proxy") + ) { + proxy_class <- if (inherits(map, "mapboxgl_compare_proxy")) { + "mapboxgl-compare-proxy" + } else { + "maplibre-compare-proxy" + } + map$session$sendCustomMessage( + proxy_class, + list( + id = map$id, + message = c(list(type = type, map = map$map_side), args) + ) + ) + } else { + proxy_class <- if (inherits(map, "mapboxgl_proxy")) { + "mapboxgl-proxy" + } else { + "maplibre-proxy" + } + map$session$sendCustomMessage( + proxy_class, + list( + id = map$id, + message = c(list(type = type), args) + ) + ) + } + } else { + # Handle non-proxy case by updating map$x + # This ensures that if called on a map object, the settings are applied on first render + if (!is.null(map$x$flowmaps)) { + id <- args$id + for (i in seq_along(map$x$flowmaps)) { + if (map$x$flowmaps[[i]]$id == id) { + if (type == "set_flowmap_filter") { + # Merge filter into settings (JS init will pick it up) + if (!is.null(args$filter$selectedTimeRange)) { + map$x$flowmaps[[ + i + ]]$settings$selectedTimeRange <- args$filter$selectedTimeRange + } + if (!is.null(args$filter$selectedLocations)) { + map$x$flowmaps[[ + i + ]]$settings$selectedLocations <- args$filter$selectedLocations + } + if (!is.null(args$filter$locationFilterMode)) { + map$x$flowmaps[[ + i + ]]$settings$locationFilterMode <- args$filter$locationFilterMode + } + } else if (type == "set_flowmap_settings") { + # Merge settings + for (s in names(args$settings)) { + map$x$flowmaps[[i]]$settings[s] <- args$settings[s] + } + } + } + } + } + } + return(map) +} + +flowmap_validate_logical <- function(value, arg) { + if (!is.logical(value) || length(value) != 1 || is.na(value)) { + rlang::abort(paste0("`", arg, "` must be TRUE or FALSE.")) + } +} + +flowmap_setting_name_map <- c( + opacity = "opacity", + colorScheme = "colorScheme", + color_scheme = "colorScheme", + darkMode = "darkMode", + dark_mode = "darkMode", + fadeAmount = "fadeAmount", + fade_amount = "fadeAmount", + highlightColor = "highlightColor", + highlight_color = "highlightColor", + locationsEnabled = "locationsEnabled", + locations_enabled = "locationsEnabled", + locationTotalsEnabled = "locationTotalsEnabled", + location_totals_enabled = "locationTotalsEnabled", + locationLabelsEnabled = "locationLabelsEnabled", + location_labels_enabled = "locationLabelsEnabled", + flowLinesRenderingMode = "flowLinesRenderingMode", + flow_lines_rendering_mode = "flowLinesRenderingMode", + flowLineThicknessScale = "flowLineThicknessScale", + flow_line_thickness_scale = "flowLineThicknessScale", + flowLineCurviness = "flowLineCurviness", + flow_line_curviness = "flowLineCurviness", + clusteringEnabled = "clusteringEnabled", + clustering_enabled = "clusteringEnabled", + clusteringAuto = "clusteringAuto", + clustering_auto = "clusteringAuto", + clusteringLevel = "clusteringLevel", + clustering_level = "clusteringLevel", + fadeEnabled = "fadeEnabled", + fade_enabled = "fadeEnabled", + fadeOpacityEnabled = "fadeOpacityEnabled", + fade_opacity_enabled = "fadeOpacityEnabled", + adaptiveScalesEnabled = "adaptiveScalesEnabled", + adaptive_scales_enabled = "adaptiveScalesEnabled", + temporalScaleDomain = "temporalScaleDomain", + temporal_scale_domain = "temporalScaleDomain", + maxTopFlowsDisplayNum = "maxTopFlowsDisplayNum", + max_top_flows_display_num = "maxTopFlowsDisplayNum", + flowEndpointsInViewportMode = "flowEndpointsInViewportMode", + flow_endpoints_in_viewport_mode = "flowEndpointsInViewportMode" +) + +flowmap_filter_setting_names <- c( + "selectedTimeRange", + "selected_time_range", + "selectedLocations", + "selected_locations", + "locationFilterMode", + "location_filter_mode" +) + +flowmap_supported_setting_names <- function() { + unique(unname(flowmap_setting_name_map)) +} + +flowmap_normalize_setting <- function(name, value) { + if ( + !is.character(name) || + length(name) != 1 || + is.na(name) || + !nzchar(trimws(name)) + ) { + rlang::abort("`name` must be a non-empty character string.") + } + + if (name %in% flowmap_filter_setting_names) { + rlang::abort( + paste0( + "`", + name, + "` is flowmap filter state. Use `set_flowmap_filter()` instead." + ) + ) + } + + normalized_name <- unname(flowmap_setting_name_map[name]) + if (is.na(normalized_name)) { + supported <- paste0("`", flowmap_supported_setting_names(), "`") + rlang::abort(paste0( + "`name` must be a supported FlowMapGL setting. Supported names are ", + paste(supported, collapse = ", "), + "." + )) + } + + list( + name = normalized_name, + value = flowmap_validate_setting_value(normalized_name, value) + ) +} + +flowmap_validate_setting_value <- function(name, value) { + switch( + name, + opacity = flowmap_validate_numeric_range( + value, + "value", + min = 0, + max = 1 + ), + colorScheme = flowmap_normalize_color_scheme(value, arg = "value"), + darkMode = flowmap_validate_logical_setting(value), + fadeAmount = flowmap_validate_numeric_range( + value, + "value", + min = 0, + max = 100 + ), + highlightColor = flowmap_validate_single_string(value, "value"), + locationsEnabled = flowmap_validate_logical_setting(value), + locationTotalsEnabled = flowmap_validate_logical_setting(value), + locationLabelsEnabled = flowmap_validate_logical_setting(value), + flowLinesRenderingMode = flowmap_validate_choice( + value, + "value", + c("straight", "animated-straight", "curved") + ), + flowLineThicknessScale = flowmap_validate_numeric_scalar(value, "value"), + flowLineCurviness = flowmap_validate_numeric_scalar(value, "value"), + clusteringEnabled = flowmap_validate_logical_setting(value), + clusteringAuto = flowmap_validate_logical_setting(value), + clusteringLevel = flowmap_validate_nullable_numeric_scalar(value, "value"), + fadeEnabled = flowmap_validate_logical_setting(value), + fadeOpacityEnabled = flowmap_validate_logical_setting(value), + adaptiveScalesEnabled = flowmap_validate_logical_setting(value), + temporalScaleDomain = flowmap_validate_choice( + value, + "value", + c("selected", "all") + ), + maxTopFlowsDisplayNum = flowmap_validate_positive_numeric_scalar( + value, + "value" + ), + flowEndpointsInViewportMode = flowmap_validate_choice( + value, + "value", + c("any", "both") + ) + ) +} + +flowmap_validate_logical_setting <- function(value) { + flowmap_validate_logical(value, "value") + value +} + +flowmap_validate_numeric_scalar <- function(value, arg) { + if (!is.numeric(value) || length(value) != 1 || is.na(value)) { + rlang::abort(paste0("`", arg, "` must be a number.")) + } + + value +} + +flowmap_validate_nullable_numeric_scalar <- function(value, arg) { + if (is.null(value)) { + return(NULL) + } + + if (!is.numeric(value) || length(value) != 1 || is.na(value)) { + rlang::abort(paste0("`", arg, "` must be a number or NULL.")) + } + + value +} + +flowmap_validate_positive_numeric_scalar <- function(value, arg) { + if (!is.numeric(value) || length(value) != 1 || is.na(value) || value <= 0) { + rlang::abort(paste0("`", arg, "` must be a positive number.")) + } + + value +} + +flowmap_validate_numeric_range <- function(value, arg, min, max) { + if ( + !is.numeric(value) || + length(value) != 1 || + is.na(value) || + value < min || + value > max + ) { + rlang::abort(paste0( + "`", + arg, + "` must be a number between ", + min, + " and ", + max, + "." + )) + } + + value +} + +flowmap_validate_choice <- function(value, arg, choices) { + if ( + !is.character(value) || + length(value) != 1 || + is.na(value) || + !value %in% choices + ) { + quoted <- paste0("`", choices, "`", collapse = ", ") + rlang::abort(paste0("`", arg, "` must be one of ", quoted, ".")) + } + + value +} + +flowmap_validate_single_string <- function(value, arg) { + if (!is.character(value) || length(value) != 1 || is.na(value)) { + rlang::abort(paste0("`", arg, "` must be a single string.")) + } + + value +} + +flowmap_normalize_interaction <- function( + input, + style, + theme, + popup_props, + dark_mode, + behavior, + default_enabled, + locations_df, + flows_df +) { + option_name <- if (behavior == "hover") "tooltip_options" else "popup_options" + if (!is.list(popup_props)) { + rlang::abort(paste0("`", option_name, "` must be a named list.")) + } + if (length(popup_props) > 0 && (is.null(names(popup_props)) || any(!nzchar(names(popup_props))))) { + rlang::abort(paste0("`", option_name, "` must be a named list.")) + } + + if (is.null(input) || identical(input, FALSE)) { + return(list(enabled = FALSE)) + } + + # Promote simple inputs to a config list + if (isTRUE(input)) { + input <- list(location = TRUE, flow = TRUE) + } else if (is.character(input) && length(input) == 1 && !is.na(input)) { + input <- list(location = input, flow = input) + } else if (inherits(input, "mapgl_tooltip_popup_options")) { + # It's already a config object, but we need to handle the template if it's dual + if (is.character(input$template) || isTRUE(input$template) || is.null(input$template)) { + input$location <- input$template %||% TRUE + input$flow <- input$template %||% TRUE + } else if (is.list(input$template)) { + input$location <- input$template$location %||% TRUE + input$flow <- input$template$flow %||% TRUE + } + style <- input$render_mode + theme <- input$theme + popup_props <- input$popup_props + } + + if (!is.list(input) || is.null(names(input))) { + rlang::abort( + paste0( + "`", + behavior, + "` must be TRUE, FALSE, NULL, a template string, a named list, or a config object." + ) + ) + } + + # Final theme resolution + if (identical(theme, "auto")) { + theme <- if (dark_mode) "dark" else "light" + } + + # Normalize templates for both feature types + location_template <- flowmap_normalize_template( + input$location %||% default_enabled, + locations_df, + "location" + ) + flow_template <- flowmap_normalize_template( + input$flow %||% default_enabled, + flows_df, + "flow" + ) + + enabled <- !identical(location_template, FALSE) || !identical(flow_template, FALSE) + + list( + enabled = enabled, + style = style, + theme = theme, + location = location_template, + flow = flow_template, + popup_props = popup_props + ) +} + +flowmap_normalize_template <- function(value, df, type) { + if (is.null(value) || identical(value, FALSE)) { + return(FALSE) + } + + if (isTRUE(value)) { + return(list(kind = "template", value = TRUE)) + } + + if (!is.character(value) || length(value) != 1 || is.na(value) || !nzchar(trimws(value))) { + rlang::abort(paste0("Interaction templates for `", type, "` must be TRUE, FALSE, or a string.")) + } + + # Disambiguation logic + is_literal <- grepl("[{<>]", value) + + if (is_literal) { + return(list(kind = "template", value = value)) + } else { + # Column reference - validate + if (!value %in% names(df)) { + rlang::abort(paste0("Column `", value, "` not found in `", type, "s` table.")) + } + return(list(kind = "column", value = value)) + } +} + +mapgl_layer_order <- function(map) { + order <- attr(map, "mapgl_layer_order", exact = TRUE) + if (is.null(order)) { + order <- list(markers = list(), pending_flowmaps = integer()) + } + order +} + +mapgl_set_layer_order <- function(map, order) { + attr(map, "mapgl_layer_order") <- order + map +} + +mapgl_record_flowmap_order <- function(map, flowmap_index, pending) { + order <- mapgl_layer_order(map) + order$markers <- c( + order$markers, + list(list(type = "flowmap", index = flowmap_index)) + ) + + if (pending) { + order$pending_flowmaps <- c(order$pending_flowmaps, flowmap_index) + } + + mapgl_set_layer_order(map, order) +} + +mapgl_resolve_pending_flowmaps <- function(map, before_id) { + order <- mapgl_layer_order(map) + pending_flowmaps <- order$pending_flowmaps + + if (length(pending_flowmaps) == 0) { + return(map) + } + + for (flowmap_index in pending_flowmaps) { + if (flowmap_index > length(map$x$flowmaps)) { + next + } + + if (is.null(map$x$flowmaps[[flowmap_index]]$beforeId)) { + map$x$flowmaps[[flowmap_index]]$beforeId <- before_id + } + } + + order$pending_flowmaps <- integer() + mapgl_set_layer_order(map, order) +} + +mapgl_record_layer_order <- function(map, id) { + order <- mapgl_layer_order(map) + order$markers <- c(order$markers, list(list(type = "layer", id = id))) + mapgl_set_layer_order(map, order) +} + +flowmap_color_scheme_registry <- local({ + schemes <- NULL + + function() { + if (!is.null(schemes)) { + return(schemes) + } + + manifest_path <- system.file( + "htmlwidgets/lib/flowmap-gl/flowmap-gl-vendor-manifest.json", + package = "mapgl", + mustWork = TRUE + ) + manifest <- jsonlite::read_json(manifest_path, simplifyVector = TRUE) + names <- manifest$colorSchemes$names + + if ( + !is.character(names) || + length(names) == 0 || + anyNA(names) || + any(!nzchar(names)) + ) { + rlang::abort( + "FlowMapGL color scheme metadata is missing from the vendored manifest." + ) + } + + schemes <<- names + schemes + } +}) + +flowmap_color_schemes_markdown <- function() { + schemes <- paste0("`", flowmap_color_scheme_registry(), "`") + if (length(schemes) == 1) { + return(schemes) + } + + paste0( + paste(schemes[-length(schemes)], collapse = ", "), + ", and ", + schemes[[length(schemes)]] + ) +} + +flowmap_validate_dark_mode <- function(flow_dark_mode) { + if ( + !is.logical(flow_dark_mode) || + length(flow_dark_mode) != 1 || + is.na(flow_dark_mode) + ) { + rlang::abort("`flow_dark_mode` must be `TRUE` or `FALSE`.") + } + + flow_dark_mode +} + +flowmap_validate_optional_string <- function(value, arg) { + if (is.null(value)) { + return(NULL) + } + + if ( + !is.character(value) || + length(value) != 1 || + is.na(value) || + !nzchar(trimws(value)) + ) { + rlang::abort(paste0( + "`", + arg, + "` must be `NULL` or a non-empty character string." + )) + } + + value +} + +flowmap_normalize_color_scheme <- function( + flow_color_scheme, + arg = "flow_color_scheme" +) { + arg_label <- paste0("`", arg, "`") + + if (inherits(flow_color_scheme, "mapgl_continuous_scale")) { + colors <- flow_color_scheme$colors + if (is.null(colors)) { + rlang::abort( + paste0(arg_label, " scale objects must contain a `colors` vector.") + ) + } + colors_arg_label <- paste0("`", arg, "$colors`") + return(mapgl_validate_color_vector(colors, colors_arg_label)) + } + + if (!is.character(flow_color_scheme)) { + rlang::abort(paste0( + arg_label, + " must be a FlowMapGL preset name, a CSS color vector, or a mapgl_continuous_scale object." + )) + } + + if (length(flow_color_scheme) == 1) { + if (is.na(flow_color_scheme) || !nzchar(trimws(flow_color_scheme))) { + rlang::abort(paste0(arg_label, " must not be missing or empty.")) + } + + if (flow_color_scheme %in% flowmap_color_scheme_registry()) { + return(flow_color_scheme) + } + + rlang::abort(paste0( + arg_label, + " must be one of `flowmap_color_schemes()` or a ", + "character vector of at least two CSS colors. Scalar color strings ", + "such as \"", + flow_color_scheme, + "\" are not valid FlowMapGL preset names." + )) + } + + mapgl_validate_color_vector(flow_color_scheme, arg_label) +} + +flowmap_locations_to_df <- function(locations) { + if (inherits(locations, "sfc")) { + locations <- sf::st_as_sf( + data.frame(id = seq_along(locations)), + geometry = locations + ) + } + + if (inherits(locations, "sf")) { + geometry_type <- as.character(sf::st_geometry_type( + locations, + by_geometry = TRUE + )) + if (!all(geometry_type == "POINT")) { + rlang::abort("`locations` must contain only POINT geometries.") + } + + if ( + !is.na(sf::st_crs(locations)) && sf::st_crs(locations) != sf::st_crs(4326) + ) { + locations <- sf::st_transform(locations, crs = 4326) + } + + coords <- sf::st_coordinates(locations) + locations <- sf::st_drop_geometry(locations) + locations$lon <- coords[, "X"] + locations$lat <- coords[, "Y"] + } else if (!is.data.frame(locations)) { + rlang::abort("`locations` must be a data frame or an sf point object.") + } + + locations <- as.data.frame(locations) + required <- c("id", "lat", "lon") + missing <- setdiff(required, names(locations)) + if (length(missing) > 0) { + rlang::abort(paste0( + "`locations` is missing required column", + if (length(missing) == 1) "" else "s", + ": ", + paste(missing, collapse = ", ") + )) + } + + if (!is.numeric(locations$lat) || !is.numeric(locations$lon)) { + rlang::abort("`locations$lat` and `locations$lon` must be numeric.") + } + + if (anyNA(locations$id) || anyNA(locations$lat) || anyNA(locations$lon)) { + rlang::abort( + "`locations` must not contain missing values in `id`, `lat`, or `lon`." + ) + } + + if (any(!is.finite(locations$lat)) || any(!is.finite(locations$lon))) { + rlang::abort( + "`locations$lat` and `locations$lon` must contain finite values." + ) + } + + locations$id <- as.character(locations$id) + if (anyDuplicated(locations$id)) { + rlang::abort("`locations$id` values must be unique.") + } + + if (!"name" %in% names(locations)) { + locations$name <- locations$id + } else { + locations$name <- as.character(locations$name) + } + + locations[, + unique(c( + "id", + "lat", + "lon", + "name", + setdiff(names(locations), c("id", "lat", "lon", "name")) + )), + drop = FALSE + ] +} + +flowmap_flows_to_df <- function(flows, time_column = NULL) { + if (!is.data.frame(flows)) { + rlang::abort("`flows` must be a data frame.") + } + + flows <- as.data.frame(flows) + required <- c("origin", "dest", "count") + missing <- setdiff(required, names(flows)) + if (length(missing) > 0) { + rlang::abort(paste0( + "`flows` is missing required column", + if (length(missing) == 1) "" else "s", + ": ", + paste(missing, collapse = ", ") + )) + } + + if (!is.numeric(flows$count)) { + rlang::abort("`flows$count` must be numeric.") + } + + if (anyNA(flows$origin) || anyNA(flows$dest) || anyNA(flows$count)) { + rlang::abort( + "`flows` must not contain missing values in `origin`, `dest`, or `count`." + ) + } + + if (any(!is.finite(flows$count))) { + rlang::abort("`flows$count` must contain finite values.") + } + + if (!is.null(time_column)) { + if (!time_column %in% names(flows)) { + rlang::abort(paste0( + "Time column '", + time_column, + "' not found in `flows`." + )) + } + flows$time <- flows[[time_column]] + } + + flows$origin <- as.character(flows$origin) + flows$dest <- as.character(flows$dest) + flows[, + unique(c( + "origin", + "dest", + "count", + if (!is.null(time_column)) "time", + setdiff( + names(flows), + c("origin", "dest", "count", if (!is.null(time_column)) "time") + ) + )), + drop = FALSE + ] +} + +flowmap_validate_ids <- function(locations, flows) { + ids <- locations$id + invalid_origins <- setdiff(unique(flows$origin), ids) + invalid_dests <- setdiff(unique(flows$dest), ids) + invalid <- unique(c(invalid_origins, invalid_dests)) + + if (length(invalid) > 0) { + rlang::abort(paste0( + "`flows$origin` and `flows$dest` must match `locations$id`; unknown ID", + if (length(invalid) == 1) "" else "s", + ": ", + paste(utils::head(invalid, 5), collapse = ", "), + if (length(invalid) > 5) ", ..." else "" + )) + } +} + +is_dark_style <- function(style) { + if (is.null(style)) { + return(TRUE) # Fallback to TRUE as default + } + + if (!is.character(style) || length(style) != 1 || is.na(style)) { + # If it's a list (like from basemap_style) + if (is.list(style)) { + bg_layer <- Filter( + function(l) isTRUE(l$type == "background"), + style$layers + ) + if (length(bg_layer) > 0) { + color <- bg_layer[[1]]$paint$`background-color` + if (is.character(color) && length(color) == 1) { + if (grepl("white|light|grey|gray", color, ignore.case = TRUE)) { + return(FALSE) + } + if (grepl("black|dark", color, ignore.case = TRUE)) { + return(TRUE) + } + } + } + } + return(TRUE) # Safe fallback + } + + # Dark patterns + if ( + grepl( + "dark|night|midnight|satellite|hybrid|imagery|nova", + style, + ignore.case = TRUE + ) + ) { + return(TRUE) + } + + # Light patterns + if ( + grepl( + "light|day|positron|voyager|streets|outdoors|basic|bright|topo|terrain", + style, + ignore.case = TRUE + ) + ) { + return(FALSE) + } + + # Default fallback if unknown + TRUE +} diff --git a/R/layer_tuner.R b/R/layer_tuner.R new file mode 100644 index 0000000..cd4e695 --- /dev/null +++ b/R/layer_tuner.R @@ -0,0 +1,387 @@ +# Helper to check if a call expression contains any of our map constructors +call_contains_constructor <- function(call) { + if (!is.call(call)) { + return(FALSE) + } + fun <- tryCatch(deparse(call[[1]]), error = function(e) "") + if ( + fun %in% c("maplibre", "mapboxgl", "maplibre_compare", "mapboxgl_compare") + ) { + return(TRUE) + } + for (arg in as.list(call)[-1]) { + if (call_contains_constructor(arg)) { + return(TRUE) + } + } + return(FALSE) +} + +# Recursively parse the call stack expression into a list of R calls and their original deparsed arguments +parse_pipeline_calls <- function(call) { + if (!is.call(call)) { + return(list()) + } + fun <- tryCatch(deparse(call[[1]]), error = function(e) "") + if (fun == "") { + return(list()) + } + + # Stop parsing and treat constructors as terminal/base calls + if ( + fun %in% c("maplibre", "mapboxgl", "maplibre_compare", "mapboxgl_compare") + ) { + args_list <- list() + args <- tail(as.list(call), -1) + arg_names <- names(call)[-1] + for (i in seq_along(args)) { + name <- if (!is.null(arg_names) && arg_names[i] != "") { + arg_names[i] + } else { + "" + } + val <- paste(deparse(args[[i]]), collapse = "\n") + args_list[[length(args_list) + 1]] <- list(name = name, value = val) + } + return(list(list(fun = fun, args = args_list))) + } + + if (length(call) > 1) { + first_arg <- call[[2]] + parent_calls <- parse_pipeline_calls(first_arg) + + args_list <- list() + args <- tail(as.list(call), -2) + arg_names <- names(call)[-c(1, 2)] + for (i in seq_along(args)) { + name <- if (!is.null(arg_names) && arg_names[i] != "") { + arg_names[i] + } else { + "" + } + val <- paste(deparse(args[[i]]), collapse = "\n") + args_list[[length(args_list) + 1]] <- list(name = name, value = val) + } + + # Check for pipes + if (fun %in% c("|>", "%>%")) { + rhs <- call[[3]] + if (is.call(rhs)) { + rhs_fun <- deparse(rhs[[1]]) + rhs_args <- tail(as.list(rhs), -1) + rhs_arg_names <- names(rhs)[-1] + rhs_args_list <- list() + for (i in seq_along(rhs_args)) { + name <- if (!is.null(rhs_arg_names) && rhs_arg_names[i] != "") { + rhs_arg_names[i] + } else { + "" + } + val <- paste(deparse(rhs_args[[i]]), collapse = "\n") + rhs_args_list[[length(rhs_args_list) + 1]] <- list( + name = name, + value = val + ) + } + return(c(parent_calls, list(list(fun = rhs_fun, args = rhs_args_list)))) + } + } else { + return(c(parent_calls, list(list(fun = fun, args = args_list)))) + } + } + return(list(list(fun = fun, args = list()))) +} + +#' Add a Layer Tuner to a map +#' +#' This function adds an interactive live customization widget (using lil-gui) to the map. +#' It allows users to customize paint and layout properties of map layers in real-time. +#' +#' @param map A `mapboxgl` or `maplibre` object. +#' @param layers A character vector of layer IDs to include in the tuner, or `"all"` (default) +#' to include all compatible layers. +#' @param show_all_args A logical value. If `TRUE`, the exported R code will include all +#' whitelisted arguments for each layer (using current map values or defaults) even if they +#' were not explicitly customized in your original R code or during tuning. Default is `FALSE`. +#' @param title Optional title for the tuner panel. Defaults to the built-in +#' layer tuner title. +#' @param position Initial position of the tuner panel. One of `"top-left"`, +#' `"top-right"`, `"bottom-left"`, or `"bottom-right"`. Defaults to +#' `"top-left"`. +#' @param width Initial tuner panel width. Numeric values are interpreted as +#' pixels; character values are passed through as CSS lengths. Defaults to +#' `245`. +#' @param height Optional initial tuner panel height. Numeric values are +#' interpreted as pixels; character values are passed through as CSS lengths. +#' Defaults to `NULL`, which lets the panel size itself automatically. +#' @param collapsed Logical value indicating whether the tuner panel should be +#' collapsed initially. Defaults to `FALSE`. +#' +#' @return The modified map object with the layer tuner added. +#' @export +#' +#' @examples +#' # Create a flowmap centered on Montréal using the bundled datasets and add a layer tuner +#' maplibre( +#' style = carto_style("dark-matter"), +#' center = c(-73.58, 45.50), +#' zoom = 11, +#' projection = "mercator" +#' ) |> +#' add_flowmap( +#' id = "bixi-rides", +#' locations = bixi_locations, +#' flows = bixi_flows, +#' flow_time_column = "time", +#' flow_color_scheme = "Teal", +#' flow_dark_mode = TRUE +#' ) |> +#' add_layer_tuner(position = "top-right", width = 320) +add_layer_tuner <- function( + map, + layers = "all", + show_all_args = FALSE, + title = NULL, + position = "top-left", + width = 245, + height = NULL, + collapsed = FALSE +) { + position_choices <- c("top-left", "top-right", "bottom-left", "bottom-right") + if ( + !is.character(position) || + length(position) != 1 || + is.na(position) || + !position %in% position_choices + ) { + rlang::abort(paste0( + "`position` must be one of ", + paste0("`", position_choices, "`", collapse = ", "), + "." + )) + } + title <- layer_tuner_optional_string(title, "title") + width <- layer_tuner_css_length(width, "width") + height <- layer_tuner_css_length(height, "height", allow_null = TRUE) + + if (!is.logical(collapsed) || length(collapsed) != 1 || is.na(collapsed)) { + rlang::abort("`collapsed` must be `TRUE` or `FALSE`.") + } + + # Dynamically query flowmap color schemes so the widget is perfectly auto-populated + flowmap_schemes <- tryCatch( + { + flowmap_color_schemes() + }, + error = function(e) { + c( + "Teal", + "Blues", + "Burg", + "BurgYl", + "RedOr", + "Oranges", + "YlOrBr", + "YlOrRd", + "OrRd", + "Reds", + "RdPu", + "Purples", + "Purp", + "PurpOr", + "Muted", + "TealGrn", + "Gold", + "Peach", + "PinkYl", + "Mint", + "BlkYl", + "BlkOrange", + "Violet", + "TealBlues", + "YellowGreen", + "OrangePink", + "TealGold", + "GoldRed", + "Sunset", + "SunsetDark", + "Bny", + "BurgPink", + "TealMint", + "TealSilver", + "Onyx" + ) + } + ) + + # Capture original R pipeline calls dynamically from the R session! + original_calls <- NULL + tryCatch( + { + calls <- sys.calls() + pipeline_call <- NULL + for (c in calls) { + if (call_contains_constructor(c)) { + pipeline_call <- c + break + } + } + if (!is.null(pipeline_call)) { + original_calls <- parse_pipeline_calls(pipeline_call) + # Filter out add_layer_tuner call from the reconstructed code to avoid nesting it infinitely + original_calls <- Filter( + function(x) x$fun != "add_layer_tuner", + original_calls + ) + } + }, + error = function(e) { + # Silent fallback + } + ) + + map_type <- if ( + inherits(map, "mapboxgl") || + inherits(map, "mapboxgl_compare") || + inherits(map, "mapboxgl_compare_proxy") + ) { + "mapboxgl" + } else { + "maplibre" + } + + layer_tuner <- list( + enabled = TRUE, + layers = layers, + flowmap_color_schemes = flowmap_schemes, + map_type = map_type, + original_calls = original_calls, + show_all_args = show_all_args, + title = title, + position = position, + width = width, + height = height, + collapsed = collapsed + ) + map$x$layer_tuner <- layer_tuner + + if ( + inherits(map, "mapboxgl_compare") || inherits(map, "maplibregl_compare") + ) { + map$x$map1$layer_tuner <- layer_tuner + map$x$map2$layer_tuner <- layer_tuner + } + + lil_gui_dep <- htmltools::htmlDependency( + name = "lil-gui", + version = "0.19.0", + src = c(file = system.file("htmlwidgets/lib/lil-gui", package = "mapgl")), + script = "lil-gui.umd.min.js" + ) + + layer_tuner_dep <- htmltools::htmlDependency( + name = "layer-tuner", + version = "1.0.0", + src = c( + file = system.file("htmlwidgets/lib/layer-tuner", package = "mapgl") + ), + script = "layer-tuner.js" + ) + + map$dependencies <- c(map$dependencies, list(lil_gui_dep, layer_tuner_dep)) + + if (inherits(map, "mapboxgl_proxy") || inherits(map, "maplibre_proxy")) { + if ( + inherits(map, "mapboxgl_compare_proxy") || + inherits(map, "maplibre_compare_proxy") + ) { + proxy_class <- if (inherits(map, "mapboxgl_compare_proxy")) { + "mapboxgl-compare-proxy" + } else { + "maplibre-compare-proxy" + } + map$session$sendCustomMessage( + proxy_class, + list( + id = map$id, + message = list( + type = "add_layer_tuner", + layers = layers, + layer_tuner = map$x$layer_tuner, + map = map$map_side + ) + ) + ) + } else { + proxy_class <- if (inherits(map, "mapboxgl_proxy")) { + "mapboxgl-proxy" + } else { + "maplibre-proxy" + } + map$session$sendCustomMessage( + proxy_class, + list( + id = map$id, + message = list( + type = "add_layer_tuner", + layers = layers, + layer_tuner = map$x$layer_tuner + ) + ) + ) + } + } + + map +} + +layer_tuner_optional_string <- function(value, arg) { + if (is.null(value)) { + return(NULL) + } + if ( + !is.character(value) || + length(value) != 1 || + is.na(value) || + !nzchar(value) + ) { + rlang::abort(paste0("`", arg, "` must be a non-empty string or `NULL`.")) + } + value +} + +layer_tuner_css_length <- function(value, arg, allow_null = FALSE) { + if (is.null(value)) { + if (allow_null) { + return(NULL) + } + rlang::abort(paste0("`", arg, "` must be a positive number or CSS length.")) + } + + if (is.numeric(value)) { + if ( + length(value) != 1 || + is.na(value) || + !is.finite(value) || + value <= 0 + ) { + rlang::abort(paste0( + "`", + arg, + "` must be a positive number or CSS length." + )) + } + return(paste0(value, "px")) + } + + if ( + !is.character(value) || + length(value) != 1 || + is.na(value) || + !nzchar(trimws(value)) + ) { + rlang::abort(paste0("`", arg, "` must be a positive number or CSS length.")) + } + + value +} diff --git a/R/layers.R b/R/layers.R index 8ef1810..fea8214 100644 --- a/R/layers.R +++ b/R/layers.R @@ -95,6 +95,8 @@ add_layer <- function( ) } + map <- mapgl_resolve_pending_flowmaps(map, before_id = id) + map$x$layers <- c( map$x$layers, list(list( @@ -115,6 +117,8 @@ add_layer <- function( )) ) + map <- mapgl_record_layer_order(map, id) + if (inherits(map, "mapboxgl_proxy") || inherits(map, "maplibre_proxy")) { layer <- list( id = id, diff --git a/R/plugins.R b/R/plugins.R index 965b97d..5eb0c11 100644 --- a/R/plugins.R +++ b/R/plugins.R @@ -221,13 +221,15 @@ compare.mapboxgl <- function( stylesheet = "layers-control.css" ) + dependencies <- c(list(control_css), map1$dependencies, map2$dependencies) + widget <- htmlwidgets::createWidget( name = "mapboxgl_compare", x, width = width, height = height, package = "mapgl", - dependencies = list(control_css), + dependencies = dependencies, elementId = if (is.null(shiny::getDefaultReactiveDomain())) elementId else NULL, sizingPolicy = htmlwidgets::sizingPolicy( @@ -310,13 +312,15 @@ compare.maplibre <- function( stylesheet = "layers-control.css" ) + dependencies <- c(list(control_css), map1$dependencies, map2$dependencies) + widget <- htmlwidgets::createWidget( name = "maplibregl_compare", x, width = width, height = height, package = "mapgl", - dependencies = list(control_css), + dependencies = dependencies, elementId = if (is.null(shiny::getDefaultReactiveDomain())) elementId else NULL, sizingPolicy = htmlwidgets::sizingPolicy( diff --git a/R/style_helpers.R b/R/style_helpers.R index fbd8f2e..67dae54 100644 --- a/R/style_helpers.R +++ b/R/style_helpers.R @@ -67,6 +67,142 @@ normalize_color_ramps <- function(color_ramps, selected_ramp = NULL, n = NULL) { normalized } +mapgl_validate_color_vector <- function(colors, arg = "`colors`") { + if (!is.character(colors) || length(colors) < 2) { + rlang::abort(paste0( + arg, + " must be a character vector with at least two CSS colors." + )) + } + + if (anyNA(colors) || any(!nzchar(trimws(colors)))) { + rlang::abort(paste0(arg, " must not contain missing or empty values.")) + } + + valid <- vapply(colors, mapgl_is_css_color, logical(1)) + if (!all(valid)) { + rlang::abort(paste0( + arg, + " contains invalid CSS color", + if (sum(!valid) == 1) "" else "s", + ": ", + paste(utils::head(colors[!valid], 5), collapse = ", "), + if (sum(!valid) > 5) ", ..." else "" + )) + } + + colors +} + +mapgl_is_css_color <- function(color) { + color <- trimws(color) + + if (grepl( + "^#(?:[0-9A-Fa-f]{3}|[0-9A-Fa-f]{4}|[0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$", + color, + perl = TRUE + )) { + return(TRUE) + } + + if (mapgl_is_rgb_css_color(color)) { + return(TRUE) + } + + !inherits( + try(grDevices::col2rgb(color, alpha = TRUE), silent = TRUE), + "try-error" + ) +} + +mapgl_is_rgb_css_color <- function(color) { + parsed <- mapgl_parse_rgb_css_color(color) + !is.null(parsed) +} + +mapgl_parse_rgb_css_color <- function(color) { + match <- regexec( + "^(rgba?)\\((.*)\\)$", + trimws(color), + ignore.case = TRUE, + perl = TRUE + ) + parts <- regmatches(trimws(color), match)[[1]] + if (length(parts) != 3) { + return(NULL) + } + + fun <- tolower(parts[[2]]) + values <- trimws(strsplit(parts[[3]], ",", fixed = TRUE)[[1]]) + expected_length <- if (fun == "rgb") 3 else 4 + if (length(values) != expected_length) { + return(NULL) + } + + channels <- vapply(values[1:3], mapgl_parse_css_channel, numeric(1)) + if (anyNA(channels)) { + return(NULL) + } + + alpha <- 1 + if (fun == "rgba") { + alpha <- mapgl_parse_css_alpha(values[[4]]) + if (is.na(alpha)) { + return(NULL) + } + } + + c(channels, alpha) +} + +mapgl_parse_css_channel <- function(value) { + if (!grepl("^[-+]?(?:\\d+\\.?\\d*|\\.\\d+)%?$", value, perl = TRUE)) { + return(NA_real_) + } + + is_percent <- grepl("%$", value) + parsed <- as.numeric(sub("%$", "", value)) + if (!is.finite(parsed)) { + return(NA_real_) + } + + if (is_percent) { + if (parsed < 0 || parsed > 100) { + return(NA_real_) + } + parsed * 255 / 100 + } else { + if (parsed < 0 || parsed > 255) { + return(NA_real_) + } + parsed + } +} + +mapgl_parse_css_alpha <- function(value) { + if (!grepl("^[-+]?(?:\\d+\\.?\\d*|\\.\\d+)%?$", value, perl = TRUE)) { + return(NA_real_) + } + + is_percent <- grepl("%$", value) + parsed <- as.numeric(sub("%$", "", value)) + if (!is.finite(parsed)) { + return(NA_real_) + } + + if (is_percent) { + if (parsed < 0 || parsed > 100) { + return(NA_real_) + } + parsed / 100 + } else { + if (parsed < 0 || parsed > 1) { + return(NA_real_) + } + parsed + } +} + #' Create an interpolation expression #' #' This function generates an interpolation expression that can be used to style your data. diff --git a/R/time_control.R b/R/time_control.R new file mode 100644 index 0000000..3d76643 --- /dev/null +++ b/R/time_control.R @@ -0,0 +1,226 @@ +#' Add a time control with a histogram +#' +#' Adds an interactive time scrubber with a histogram to the map. The control +#' filters temporal data by dragging a range across a bar chart. It can drive +#' one or several layers at once — both flowmap layers and ordinary +#' Mapbox/MapLibre layers (circle, fill, line, symbol, etc.) whose source +#' features carry a time property. +#' +#' For ordinary layers, the control sets a Mapbox filter expression of the +#' form `[">=", ["get", feature_time_property], start] && ["<", ..., end]`. +#' The property is assumed to be an ISO 8601 timestamp string by default; pass +#' `feature_time_format = "epoch_ms"` (or `"epoch_s"`) if your source data +#' encodes time as numeric epoch milliseconds (or seconds). +#' +#' For flowmap layers the control updates the `selectedTimeRange` of the +#' flowmap filter via the flowmap.gl plugin. +#' +#' @param map A map object created by [mapboxgl()] or [maplibre()]. +#' @param data A data frame containing the temporal data used to build the +#' histogram (bin counts and extent). +#' @param time_column The name of the column in `data` containing timestamps +#' (POSIXct or Date). +#' @param layer_id Target layer ID(s) to filter. Either a character vector of +#' layer IDs (flowmap and/or ordinary layers), or `NULL` to filter every +#' flowmap layer in the map. To filter ordinary (non-flowmap) layers, list +#' them explicitly. +#' @param feature_time_property For ordinary (non-flowmap) target layers, the +#' name of the feature property holding the timestamp. Defaults to +#' `time_column`. +#' @param feature_time_format How the timestamp is stored on ordinary target +#' layers' source features: `"iso"` (ISO 8601 string, default), +#' `"epoch_ms"`, or `"epoch_s"`. +#' @param time_interval The aggregation interval for the histogram: `"hour"` +#' or `"day"`. +#' @param position The position of the control: `"top-right"`, `"top-left"`, +#' `"bottom-right"`, `"bottom-left"`, or `"bottom-center"`. +#' @param initial_range Optional vector of two dates/timestamps for the initial +#' time filter range. +#' @param loop Logical; whether to loop the playback. +#' @param speed Playback speed in milliseconds per step (default 500). +#' @param autoplay Logical; if `TRUE`, start playing the scrubber animation +#' immediately after the control mounts. Defaults to `FALSE`. +#' @param accent_color Color for the bars and selection handles. +#' @param dark_mode Logical; whether to use a dark theme for the widget. +#' @param draggable Logical; if `TRUE` (default) the widget is detached from +#' the map corner container and can be repositioned by dragging its header. +#' @param collapsible Logical; if `TRUE` the histogram body can be collapsed +#' to a compact bar. +#' @param collapsed Logical; whether to start in the collapsed state. Implies +#' `collapsible = TRUE`. +#' @param title Optional short title shown in the header (useful when the +#' control is draggable or collapsible). +#' +#' @details +#' Hold Shift while dragging on the histogram to add another selected time +#' range. Multiple ranges are combined with OR semantics when filtering target +#' layers. +#' +#' @examples +#' # Create a flowmap centered on Montréal using the bundled datasets +#' maplibre( +#' style = carto_style("dark-matter"), +#' center = c(-73.58, 45.50), +#' zoom = 11, +#' projection = "mercator" +#' ) |> +#' add_flowmap( +#' id = "bixi-rides", +#' locations = bixi_locations, +#' flows = bixi_flows, +#' flow_time_column = "time", +#' flow_color_scheme = "Teal", +#' flow_dark_mode = TRUE +#' ) |> +#' add_time_control( +#' data = bixi_flows, +#' time_column = "time", +#' time_interval = "hour", +#' title = "BIXI Montréal Rides" +#' ) +#' +#' @return The modified map object. +#' @export +add_time_control <- function( + map, + data, + time_column, + layer_id = NULL, + feature_time_property = NULL, + feature_time_format = c("iso", "epoch_ms", "epoch_s"), + time_interval = c("hour", "day"), + position = "bottom-left", + initial_range = NULL, + loop = TRUE, + speed = 500, + autoplay = FALSE, + accent_color = "#00bcd4", + dark_mode = TRUE, + draggable = TRUE, + collapsible = FALSE, + collapsed = FALSE, + title = NULL +) { + time_interval <- match.arg(time_interval) + feature_time_format <- match.arg(feature_time_format) + + if (!time_column %in% names(data)) { + rlang::abort(paste0("Time column '", time_column, "' not found in data.")) + } + + times <- data[[time_column]] + if (!inherits(times, "POSIXct") && !inherits(times, "Date")) { + rlang::abort("Time column must be POSIXct or Date.") + } + + if (!is.null(layer_id)) { + if (!is.character(layer_id) || length(layer_id) < 1) { + rlang::abort( + "`layer_id` must be a character vector of one or more layer IDs, or NULL for all flowmap layers." + ) + } + } + + if (is.null(feature_time_property)) { + feature_time_property <- time_column + } + + if (isTRUE(collapsed)) { + collapsible <- TRUE + } + + tzone <- attr(times, "tzone") + if (is.null(tzone) || tzone == "") { + tzone <- "UTC" + } + + if (time_interval == "hour") { + start_time <- as.POSIXct( + format(min(times), "%Y-%m-%d %H:00:00", tz = tzone), + tz = tzone + ) + end_time <- as.POSIXct( + format(max(times) + 3600, "%Y-%m-%d %H:00:00", tz = tzone), + tz = tzone + ) + breaks <- seq(from = start_time, to = end_time, by = "hour") + binned <- cut(times, breaks = breaks, include.lowest = TRUE) + } else { + breaks <- seq( + from = as.Date(min(times)), + to = as.Date(max(times) + 1), + by = "day" + ) + binned <- cut(times, breaks = breaks, include.lowest = TRUE) + } + + bin_counts <- table(binned) + + bins_df <- data.frame( + time = breaks[-length(breaks)], + count = as.numeric(bin_counts), + stringsAsFactors = FALSE + ) + + if (time_interval == "hour") { + bins_df$time <- format( + as.POSIXct(bins_df$time, tz = tzone), + "%Y-%m-%dT%H:%M:%SZ" + ) + } else { + bins_df$time <- format(as.Date(bins_df$time), "%Y-%m-%d") + } + + initial_range_iso <- NULL + if (!is.null(initial_range)) { + if (length(initial_range) != 2) { + rlang::abort( + "`initial_range` must be a length-2 vector of dates/timestamps." + ) + } + if (inherits(initial_range, "POSIXct")) { + initial_range_iso <- format( + initial_range, + "%Y-%m-%dT%H:%M:%SZ", + tz = "UTC" + ) + } else if (inherits(initial_range, "Date")) { + initial_range_iso <- format(initial_range, "%Y-%m-%d") + } else { + initial_range_iso <- as.character(initial_range) + } + } + + control_config <- list( + targetLayerIds = if (is.null(layer_id)) NULL else as.list(layer_id), + featureTimeProperty = feature_time_property, + featureTimeFormat = feature_time_format, + bins = bins_df, + interval = time_interval, + position = position, + initialRange = initial_range_iso, + loop = loop, + speed = speed, + autoplay = autoplay, + accentColor = accent_color, + darkMode = dark_mode, + draggable = draggable, + collapsible = collapsible, + collapsed = collapsed, + title = title + ) + + if (inherits(map, "mapboxgl_proxy") || inherits(map, "maplibre_proxy")) { + do.call( + mapgl_invoke_method, + c(list(map, "add_time_control"), control_config) + ) + } else { + if (is.null(map$x$time_controls)) { + map$x$time_controls <- list() + } + map$x$time_controls <- c(map$x$time_controls, list(control_config)) + } + + return(map) +} diff --git a/R/tooltips_popups.R b/R/tooltips_popups.R new file mode 100644 index 0000000..cc46278 --- /dev/null +++ b/R/tooltips_popups.R @@ -0,0 +1,58 @@ +#' Configure tooltip or popup options +#' +#' Internal helper to create a configuration object for tooltips or popups. +#' Use [tooltip_options()] or [popup_options()] for public usage. +#' +#' @param template Template string or a named list with `location` and/or `flow` keys. +#' @param theme Visual theme: `"auto"`, `"light"`, or `"dark"`. +#' @param behavior Interaction behavior: `"hover"`, or `"click"`. +#' @param render_mode Internal rendering mode: `"floating"` or `"anchored"`. +#' @param ... Additional properties passed to the Mapbox/MapLibre popup. +#' @noRd +tooltip_popup_options <- function( + template = NULL, + theme = c("auto", "light", "dark"), + behavior = c("hover", "click"), + render_mode = c("floating", "anchored"), + ... +) { + theme <- match.arg(theme) + behavior <- match.arg(behavior) + render_mode <- match.arg(render_mode) + popup_props <- list(...) + + if (length(popup_props) > 0 && (is.null(names(popup_props)) || any(!nzchar(names(popup_props))))) { + rlang::abort("Additional popup properties must be named.") + } + + structure( + list( + template = template, + theme = theme, + behavior = behavior, + popup_props = popup_props, + render_mode = render_mode + ), + class = "mapgl_tooltip_popup_options" + ) +} + +#' Configure tooltip options +#' +#' @param template Template string or a named list with `location` and/or `flow` keys. +#' @param theme Visual theme: `"auto"`, `"light"`, or `"dark"`. +#' @param ... Additional properties passed to the Mapbox/MapLibre popup, such as `className`, `css`, `maxWidth`, etc. +#' @export +tooltip_options <- function(template = NULL, theme = "auto", ...) { + tooltip_popup_options(template, theme, behavior = "hover", ...) +} + +#' Configure popup options +#' +#' @param template Template string or a named list with `location` and/or `flow` keys. +#' @param theme Visual theme: `"auto"`, `"light"`, or `"dark"`. +#' @param ... Additional properties passed to the Mapbox/MapLibre popup, such as `className`, `css`, `maxWidth`, etc. +#' @export +popup_options <- function(template = NULL, theme = "auto", ...) { + tooltip_popup_options(template, theme, behavior = "click", ...) +} diff --git a/R/utils.R b/R/utils.R index 9421825..8191e29 100644 --- a/R/utils.R +++ b/R/utils.R @@ -572,3 +572,35 @@ legend_style <- function( class(style_list) <- "mapgl_legend_style" return(style_list) } + +# Internal function to invoke a method on a map proxy +mapgl_invoke_method <- function(map, type, ...) { + args <- list(...) + if (any(inherits(map, "mapboxgl_proxy"), inherits(map, "maplibre_proxy"))) { + if ( + inherits(map, "mapboxgl_compare_proxy") || + inherits(map, "maplibre_compare_proxy") + ) { + proxy_class <- if (inherits(map, "mapboxgl_compare_proxy")) + "mapboxgl-compare-proxy" else "maplibre-compare-proxy" + map$session$sendCustomMessage( + proxy_class, + list( + id = map$id, + message = c(list(type = type, map = map$map_side), args) + ) + ) + } else { + proxy_class <- if (inherits(map, "mapboxgl_proxy")) "mapboxgl-proxy" else + "maplibre-proxy" + map$session$sendCustomMessage( + proxy_class, + list( + id = map$id, + message = c(list(type = type), args) + ) + ) + } + } + return(map) +} diff --git a/_pkgdown.yml b/_pkgdown.yml index ce3f834..6a714ec 100644 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -62,6 +62,7 @@ reference: - add_fill_extrusion_layer - add_raster_layer - add_symbol_layer + - add_flowmap - add_view - title: "Data Sources" @@ -90,6 +91,7 @@ reference: - add_geolocate_control - add_globe_control - add_screenshot_control + - add_time_control - add_coordinates_control - add_control - clear_controls @@ -127,6 +129,7 @@ reference: - interpolate - match_expr - step_expr + - flowmap_color_schemes - get_column - concat - number_format @@ -166,10 +169,14 @@ reference: desc: "Functions to modify and manage existing layers" contents: - set_filter + - set_flowmap_filter - set_paint_property - set_layout_property - set_tooltip + - tooltip_options - set_popup + - popup_options + - set_flowmap_settings - set_source - clear_layer - move_layer @@ -211,6 +218,7 @@ reference: desc: "Functions for advanced mapping features" contents: - compare + - add_layer_tuner - add_globe_minimap - add_image - get_drawn_features diff --git a/data-raw/flowmap-vendor/README.md b/data-raw/flowmap-vendor/README.md new file mode 100644 index 0000000..6293393 --- /dev/null +++ b/data-raw/flowmap-vendor/README.md @@ -0,0 +1,85 @@ +# FlowmapGL Vendoring + +This directory contains the reproducible npm workspace used to build the +vendored FlowmapGL browser asset shipped with mapgl. + +## Package Developer Workflow + +Most R package development does not need to touch FlowmapGL vendoring. The +package ships the already-built browser asset in +`inst/htmlwidgets/lib/flowmap-gl/`. + +Do not hand-edit files under `inst/htmlwidgets/lib/flowmap-gl/`. They are +generated outputs from this vendoring workspace. + +Run `check` before committing when you changed any FlowmapGL vendoring input, +or when you want to verify the checked-in asset still matches this workspace: + +```sh +data-raw/flowmap-vendor/build-flowmap.sh check +``` + +Run `build` only when intentionally regenerating the vendored FlowmapGL files, +for example after: + +- changing a pinned npm package version in `package.json` +- changing the FlowmapGL bundle entry point in `entry.js` +- changing a patch under `patches/` +- changing metadata or notice generation in `scripts/generate-vendor-metadata.mjs` +- refreshing the npm lockfile intentionally + +Run from the repository root: + +```sh +data-raw/flowmap-vendor/build-flowmap.sh build +data-raw/flowmap-vendor/build-flowmap.sh check +``` + +The build command runs `npm ci`, applies every `patches/*.patch` with +`git apply --check` first, bundles `entry.js` with esbuild, and writes: + +- `inst/htmlwidgets/lib/flowmap-gl/flowmap-gl-bundle.js` +- `inst/htmlwidgets/lib/flowmap-gl/flowmap-gl-bundle.js.map` +- `inst/htmlwidgets/lib/flowmap-gl/flowmap-gl-bundle.min.js` +- `inst/htmlwidgets/lib/flowmap-gl/flowmap-gl-bundle.min.js.map` +- `inst/htmlwidgets/lib/flowmap-gl/flowmap-gl-vendor-manifest.json` +- `LICENSE.note` + +The check command rebuilds those files in a temporary directory and fails if +the committed copies differ. + +Commit the vendoring workspace files, the generated files under +`inst/htmlwidgets/lib/flowmap-gl/`, and any tests that verify those outputs. +Do not commit `data-raw/flowmap-vendor/node_modules/`; it is recreated by +`npm ci`. + +The normal supported source for FlowmapGL is the npm release pinned in +`package.json` and `package-lock.json`. The manifest records package tarball +integrity values, npm `gitHead` values where available, and the SHA256 of the +generated browser bundle. + +## Local FlowmapGL Patch + +mapgl adds `flow_temporal_scale_domain` for temporal flowmaps. FlowmapGL 9.3.0 +only supports viewport-adaptive scaling, so mapgl carries +`patches/flowmap-temporal-scale-domain.patch` until upstream provides a native +temporal scale-domain control. + +`adaptiveScalesEnabled` remains spatial: when enabled, scale domains are limited +to flows with endpoints in the current viewport. `temporalScaleDomain` is +temporal: `"selected"` uses selected-time flows for width/color domains and +`"all"` uses all-time flows for comparable widths/colors across time. + +## Patch Failures + +If patch application fails after bumping FlowmapGL, inspect upstream for native +temporal scale-domain support. + +- If upstream supports it, remove the local patch and wire mapgl to the upstream + prop. +- If upstream does not support it, rebase the patch against the new + `FlowmapSelectors` and `FlowmapLayer` internals. + +The acceptance invariant is: rendered flows may remain time-filtered, but +width/color domains must use selected-time flows for `"selected"` and all-time +flows for `"all"`. diff --git a/data-raw/flowmap-vendor/build-flowmap.sh b/data-raw/flowmap-vendor/build-flowmap.sh new file mode 100755 index 0000000..d882dfe --- /dev/null +++ b/data-raw/flowmap-vendor/build-flowmap.sh @@ -0,0 +1,125 @@ +#!/usr/bin/env bash +set -euo pipefail + +VENDOR_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ROOT_DIR="$(cd "$VENDOR_DIR/../.." && pwd)" +OUTPUT_DIR="$ROOT_DIR/inst/htmlwidgets/lib/flowmap-gl" +LICENSE_NOTE_PATH="$ROOT_DIR/LICENSE.note" +COMMAND="${1:-build}" +BUNDLE_NAME="flowmap-gl-bundle.min.js" +DEBUG_BUNDLE_NAME="flowmap-gl-bundle.js" +MANIFEST_NAME="flowmap-gl-vendor-manifest.json" +GENERATED_FILES=( + "$DEBUG_BUNDLE_NAME" + "$DEBUG_BUNDLE_NAME.map" + "$BUNDLE_NAME" + "$BUNDLE_NAME.map" + "$MANIFEST_NAME" +) + +usage() { + cat <<'EOF' +Usage: data-raw/flowmap-vendor/build-flowmap.sh [build|check] + +Commands: + build Rebuild the committed FlowmapGL bundle, manifest, and license note. + check Rebuild in a temporary directory and fail if committed outputs differ. +EOF +} + +build_outputs() { + local output_dir="$1" + local license_note_path="$2" + + cd "$VENDOR_DIR" + npm ci --silent + apply_patches + + mkdir -p "$output_dir" + npx esbuild entry.js \ + --bundle \ + --format=iife \ + --outfile="$output_dir/$DEBUG_BUNDLE_NAME" \ + --sourcemap \ + --sources-content=true + normalize_sourcemap "$output_dir/$DEBUG_BUNDLE_NAME.map" + + npx esbuild entry.js \ + --bundle \ + --format=iife \ + --outfile="$output_dir/$BUNDLE_NAME" \ + --minify \ + --sourcemap \ + --sources-content=true + normalize_sourcemap "$output_dir/$BUNDLE_NAME.map" + + node scripts/generate-vendor-metadata.mjs "$output_dir" "$license_note_path" +} + +normalize_sourcemap() { + local sourcemap_path="$1" + + node - "$sourcemap_path" <<'NODE' +const {readFileSync, writeFileSync} = require('node:fs'); + +const sourcemapPath = process.argv[2]; +const marker = 'data-raw/flowmap-vendor/'; +const sourcemap = JSON.parse(readFileSync(sourcemapPath, 'utf8')); + +sourcemap.sources = sourcemap.sources.map((source) => { + const markerIndex = source.indexOf(marker); + if (markerIndex >= 0) { + return source.slice(markerIndex + marker.length); + } + return source; +}); + +writeFileSync(sourcemapPath, `${JSON.stringify(sourcemap)}\n`); +NODE +} + +apply_patches() { + local patches=() + shopt -s nullglob + patches=("$VENDOR_DIR"/patches/*.patch) + shopt -u nullglob + + if ((${#patches[@]} == 0)); then + return 0 + fi + + for patch in "${patches[@]}"; do + git -C "$ROOT_DIR" apply --check --directory="data-raw/flowmap-vendor" "$patch" + done + + for patch in "${patches[@]}"; do + git -C "$ROOT_DIR" apply --directory="data-raw/flowmap-vendor" "$patch" + done +} + +case "$COMMAND" in + build) + build_outputs "$OUTPUT_DIR" "$LICENSE_NOTE_PATH" + ls -lh "$OUTPUT_DIR/$DEBUG_BUNDLE_NAME" "$OUTPUT_DIR/$BUNDLE_NAME" + ;; + check) + TMP_DIR="$(mktemp -d)" + cleanup() { + rm -rf "$TMP_DIR" + } + trap cleanup EXIT + + build_outputs "$TMP_DIR" "$TMP_DIR/LICENSE.note" + for file in "${GENERATED_FILES[@]}"; do + diff -u "$OUTPUT_DIR/$file" "$TMP_DIR/$file" + done + diff -u "$LICENSE_NOTE_PATH" "$TMP_DIR/LICENSE.note" + ;; + -h|--help|help) + usage + ;; + *) + usage >&2 + exit 2 + ;; +esac diff --git a/data-raw/flowmap-vendor/entry.js b/data-raw/flowmap-vendor/entry.js new file mode 100644 index 0000000..1dae7df --- /dev/null +++ b/data-raw/flowmap-vendor/entry.js @@ -0,0 +1,9 @@ +import {Deck} from '@deck.gl/core'; +import {MapboxOverlay} from '@deck.gl/mapbox'; +import {FlowmapLayer} from '@flowmap.gl/layers'; + +window.FlowmapGL = { + Deck, + FlowmapLayer, + MapboxOverlay +}; diff --git a/data-raw/flowmap-vendor/package-lock.json b/data-raw/flowmap-vendor/package-lock.json new file mode 100644 index 0000000..a0371e4 --- /dev/null +++ b/data-raw/flowmap-vendor/package-lock.json @@ -0,0 +1,1193 @@ +{ + "name": "mapgl-flowmap-vendor", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "mapgl-flowmap-vendor", + "version": "1.0.0", + "license": "MIT", + "dependencies": { + "@deck.gl/core": "9.3.2", + "@deck.gl/layers": "9.3.2", + "@deck.gl/mapbox": "9.3.2", + "@flowmap.gl/data": "9.3.0", + "@flowmap.gl/layers": "9.3.0", + "@luma.gl/core": "9.3.3", + "@luma.gl/engine": "9.3.3", + "@luma.gl/shadertools": "9.3.3", + "esbuild": "0.28.0" + } + }, + "node_modules/@deck.gl/core": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/@deck.gl/core/-/core-9.3.2.tgz", + "integrity": "sha512-32Va3np0Zdlz/LBNtDWCs4EkKqdHmXcbGmVp4+7i1Cpdza8y8CFmJs2VPOmSX1fwHvNCGkAZV/SFZOfDb2INsg==", + "license": "MIT", + "dependencies": { + "@loaders.gl/core": "^4.4.1", + "@loaders.gl/images": "^4.4.1", + "@luma.gl/core": "^9.3.3", + "@luma.gl/engine": "^9.3.3", + "@luma.gl/shadertools": "^9.3.3", + "@luma.gl/webgl": "^9.3.3", + "@math.gl/core": "^4.1.0", + "@math.gl/sun": "^4.1.0", + "@math.gl/types": "^4.1.0", + "@math.gl/web-mercator": "^4.1.0", + "@probe.gl/env": "^4.1.1", + "@probe.gl/log": "^4.1.1", + "@probe.gl/stats": "^4.1.1", + "@types/offscreencanvas": "^2019.6.4", + "gl-matrix": "^3.0.0", + "mjolnir.js": "^3.0.0" + } + }, + "node_modules/@deck.gl/layers": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/@deck.gl/layers/-/layers-9.3.2.tgz", + "integrity": "sha512-TeVfhQ/cQU1oTlTn16mCp7268d1uBJ6dwfgmKXThe2TzW9hql3iJaxbYTKg2phDg5YSiGmeEOpXbeBh59jyUcA==", + "license": "MIT", + "dependencies": { + "@loaders.gl/images": "^4.4.1", + "@loaders.gl/schema": "^4.4.1", + "@luma.gl/shadertools": "^9.3.3", + "@mapbox/tiny-sdf": "^2.0.5", + "@math.gl/core": "^4.1.0", + "@math.gl/polygon": "^4.1.0", + "@math.gl/web-mercator": "^4.1.0", + "earcut": "^2.2.4" + }, + "peerDependencies": { + "@deck.gl/core": "~9.3.0", + "@loaders.gl/core": "^4.4.1", + "@luma.gl/core": "~9.3.3", + "@luma.gl/engine": "~9.3.3" + } + }, + "node_modules/@deck.gl/mapbox": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/@deck.gl/mapbox/-/mapbox-9.3.2.tgz", + "integrity": "sha512-+T9pJwsOXwjUxyGN6oiBMfIs28VtDIG1V1Rqz4qqn4TjjNEFFw+xO0olJIg8FO5IAqw2OtePdsrMj0tX8tHdGQ==", + "license": "MIT", + "dependencies": { + "@math.gl/web-mercator": "^4.1.0" + }, + "peerDependencies": { + "@deck.gl/core": "~9.3.0", + "@luma.gl/core": "~9.3.3", + "@math.gl/web-mercator": "^4.1.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.0.tgz", + "integrity": "sha512-lhRUCeuOyJQURhTxl4WkpFTjIsbDayJHih5kZC1giwE+MhIzAb7mEsQMqMf18rHLsrb5qI1tafG20mLxEWcWlA==", + "cpu": [ + "ppc64" + ], + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.0.tgz", + "integrity": "sha512-wqh0ByljabXLKHeWXYLqoJ5jKC4XBaw6Hk08OfMrCRd2nP2ZQ5eleDZC41XHyCNgktBGYMbqnrJKq/K/lzPMSQ==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.0.tgz", + "integrity": "sha512-+WzIXQOSaGs33tLEgYPYe/yQHf0WTU0X42Jca3y8NWMbUVhp7rUnw+vAsRC/QiDrdD31IszMrZy+qwPOPjd+rw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.0.tgz", + "integrity": "sha512-+VJggoaKhk2VNNqVL7f6S189UzShHC/mR9EE8rDdSkdpN0KflSwWY/gWjDrNxxisg8Fp1ZCD9jLMo4m0OUfeUA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.0.tgz", + "integrity": "sha512-0T+A9WZm+bZ84nZBtk1ckYsOvyA3x7e2Acj1KdVfV4/2tdG4fzUp91YHx+GArWLtwqp77pBXVCPn2We7Letr0Q==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.0.tgz", + "integrity": "sha512-fyzLm/DLDl/84OCfp2f/XQ4flmORsjU7VKt8HLjvIXChJoFFOIL6pLJPH4Yhd1n1gGFF9mPwtlN5Wf82DZs+LQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.0.tgz", + "integrity": "sha512-l9GeW5UZBT9k9brBYI+0WDffcRxgHQD8ShN2Ur4xWq/NFzUKm3k5lsH4PdaRgb2w7mI9u61nr2gI2mLI27Nh3Q==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.0.tgz", + "integrity": "sha512-BXoQai/A0wPO6Es3yFJ7APCiKGc1tdAEOgeTNy3SsB491S3aHn4S4r3e976eUnPdU+NbdtmBuLncYir2tMU9Nw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.0.tgz", + "integrity": "sha512-CjaaREJagqJp7iTaNQjjidaNbCKYcd4IDkzbwwxtSvjI7NZm79qiHc8HqciMddQ6CKvJT6aBd8lO9kN/ZudLlw==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.0.tgz", + "integrity": "sha512-RVyzfb3FWsGA55n6WY0MEIEPURL1FcbhFE6BffZEMEekfCzCIMtB5yyDcFnVbTnwk+CLAgTujmV/Lgvih56W+A==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.0.tgz", + "integrity": "sha512-KBnSTt1kxl9x70q+ydterVdl+Cn0H18ngRMRCEQfrbqdUuntQQ0LoMZv47uB97NljZFzY6HcfqEZ2SAyIUTQBQ==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.0.tgz", + "integrity": "sha512-zpSlUce1mnxzgBADvxKXX5sl8aYQHo2ezvMNI8I0lbblJtp8V4odlm3Yzlj7gPyt3T8ReksE6bK+pT3WD+aJRg==", + "cpu": [ + "loong64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.0.tgz", + "integrity": "sha512-2jIfP6mmjkdmeTlsX/9vmdmhBmKADrWqN7zcdtHIeNSCH1SqIoNI63cYsjQR8J+wGa4Y5izRcSHSm8K3QWmk3w==", + "cpu": [ + "mips64el" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.0.tgz", + "integrity": "sha512-bc0FE9wWeC0WBm49IQMPSPILRocGTQt3j5KPCA8os6VprfuJ7KD+5PzESSrJ6GmPIPJK965ZJHTUlSA6GNYEhg==", + "cpu": [ + "ppc64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.0.tgz", + "integrity": "sha512-SQPZOwoTTT/HXFXQJG/vBX8sOFagGqvZyXcgLA3NhIqcBv1BJU1d46c0rGcrij2B56Z2rNiSLaZOYW5cUk7yLQ==", + "cpu": [ + "riscv64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.0.tgz", + "integrity": "sha512-SCfR0HN8CEEjnYnySJTd2cw0k9OHB/YFzt5zgJEwa+wL/T/raGWYMBqwDNAC6dqFKmJYZoQBRfHjgwLHGSrn3Q==", + "cpu": [ + "s390x" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.0.tgz", + "integrity": "sha512-us0dSb9iFxIi8srnpl931Nvs65it/Jd2a2K3qs7fz2WfGPHqzfzZTfec7oxZJRNPXPnNYZtanmRc4AL/JwVzHQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.0.tgz", + "integrity": "sha512-CR/RYotgtCKwtftMwJlUU7xCVNg3lMYZ0RzTmAHSfLCXw3NtZtNpswLEj/Kkf6kEL3Gw+BpOekRX0BYCtklhUw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.0.tgz", + "integrity": "sha512-nU1yhmYutL+fQ71Kxnhg8uEOdC0pwEW9entHykTgEbna2pw2dkbFSMeqjjyHZoCmt8SBkOSvV+yNmm94aUrrqw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.0.tgz", + "integrity": "sha512-cXb5vApOsRsxsEl4mcZ1XY3D4DzcoMxR/nnc4IyqYs0rTI8ZKmW6kyyg+11Z8yvgMfAEldKzP7AdP64HnSC/6g==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.0.tgz", + "integrity": "sha512-8wZM2qqtv9UP3mzy7HiGYNH/zjTA355mpeuA+859TyR+e+Tc08IHYpLJuMsfpDJwoLo1ikIJI8jC3GFjnRClzA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.0.tgz", + "integrity": "sha512-FLGfyizszcef5C3YtoyQDACyg95+dndv79i2EekILBofh5wpCa1KuBqOWKrEHZg3zrL3t5ouE5jgr94vA+Wb2w==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.0.tgz", + "integrity": "sha512-1ZgjUoEdHZZl/YlV76TSCz9Hqj9h9YmMGAgAPYd+q4SicWNX3G5GCyx9uhQWSLcbvPW8Ni7lj4gDa1T40akdlw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.0.tgz", + "integrity": "sha512-Q9StnDmQ/enxnpxCCLSg0oo4+34B9TdXpuyPeTedN/6+iXBJ4J+zwfQI28u/Jl40nOYAxGoNi7mFP40RUtkmUA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.0.tgz", + "integrity": "sha512-zF3ag/gfiCe6U2iczcRzSYJKH1DCI+ByzSENHlM2FcDbEeo5Zd2C86Aq0tKUYAJJ1obRP84ymxIAksZUcdztHA==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.0.tgz", + "integrity": "sha512-pEl1bO9mfAmIC+tW5btTmrKaujg3zGtUmWNdCw/xs70FBjwAL3o9OEKNHvNmnyylD6ubxUERiEhdsL0xBQ9efw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@flowmap.gl/data": { + "version": "9.3.0", + "resolved": "https://registry.npmjs.org/@flowmap.gl/data/-/data-9.3.0.tgz", + "integrity": "sha512-1a4EZJdK13q5Mj3bVurFSpuYVBLSaByJJ9B4LMd7XvuD/ovB6JArDjdJetsA9jVHdA89lZli7f8ALX+oek+WtA==", + "license": "Apache-2.0", + "dependencies": { + "d3-array": "^3.2.4", + "d3-color": "^3.1.0", + "d3-geo": "^3.1.1", + "d3-interpolate": "^3.0.1", + "d3-scale": "^4.0.2", + "d3-scale-chromatic": "^3.1.0", + "d3-time": "^3.1.0", + "d3-time-format": "^4.1.0", + "kdbush": "^4.0.2", + "reselect": "^5.1.1", + "seedrandom": "^3.0.5" + } + }, + "node_modules/@flowmap.gl/layers": { + "version": "9.3.0", + "resolved": "https://registry.npmjs.org/@flowmap.gl/layers/-/layers-9.3.0.tgz", + "integrity": "sha512-kARLb28BYK58O4iuiZK0IdNO+W1EX4+MaLbufRU1O0LTMM0Aoe2lET7y4QcrOifQT0dV6cAjzjw4GDnbogOxJg==", + "license": "Apache-2.0", + "dependencies": { + "@flowmap.gl/data": "^9.3.0" + }, + "peerDependencies": { + "@deck.gl/core": "^9.0.0", + "@deck.gl/layers": "^9.0.0", + "@luma.gl/core": "^9.0.0", + "@luma.gl/engine": "^9.0.0", + "@luma.gl/shadertools": "^9.0.0" + } + }, + "node_modules/@loaders.gl/core": { + "version": "4.4.2", + "resolved": "https://registry.npmjs.org/@loaders.gl/core/-/core-4.4.2.tgz", + "integrity": "sha512-DZmsTwxdKh3q+mS1vSOW2EXFgwxZ4nIBte4H5g6e4VyQoQ6jAOkk0M6V+Asgy/eqjGTNjhfBA1HIkyBl0A9hcA==", + "license": "MIT", + "dependencies": { + "@loaders.gl/loader-utils": "4.4.2", + "@loaders.gl/schema": "4.4.2", + "@loaders.gl/schema-utils": "4.4.2", + "@loaders.gl/worker-utils": "4.4.2", + "@probe.gl/log": "^4.1.1" + } + }, + "node_modules/@loaders.gl/images": { + "version": "4.4.2", + "resolved": "https://registry.npmjs.org/@loaders.gl/images/-/images-4.4.2.tgz", + "integrity": "sha512-b+1keNvPlyLniWtX4ZaThz2dF2aohi8Q+OEsDF2hJNZYyZJOqP9b/72UhlVk+inxTJfTLRBNARs2TJ2ssBlelg==", + "license": "MIT", + "dependencies": { + "@loaders.gl/loader-utils": "4.4.2" + }, + "peerDependencies": { + "@loaders.gl/core": "~4.4.0" + } + }, + "node_modules/@loaders.gl/loader-utils": { + "version": "4.4.2", + "resolved": "https://registry.npmjs.org/@loaders.gl/loader-utils/-/loader-utils-4.4.2.tgz", + "integrity": "sha512-kqwBbyRC7rrQVsnJyKeoaig9hxaa5oj91OKqWm27HPuVn4q2dD67SEhiG0ND62eRp0tLY6jTqEcI5kDzHBZ6MA==", + "license": "MIT", + "dependencies": { + "@loaders.gl/schema": "4.4.2", + "@loaders.gl/worker-utils": "4.4.2", + "@probe.gl/log": "^4.1.1", + "@probe.gl/stats": "^4.1.1" + } + }, + "node_modules/@loaders.gl/schema": { + "version": "4.4.2", + "resolved": "https://registry.npmjs.org/@loaders.gl/schema/-/schema-4.4.2.tgz", + "integrity": "sha512-mJTZehTHIFl8ed+03nebuPAMnLP8Yp00DKTzCnKT2HNy/uV4+Sw+GrGIuhPHGU8tdQmtBXRURGM2ZxUAxMfGKg==", + "license": "MIT", + "dependencies": { + "@types/geojson": "^7946.0.7", + "apache-arrow": ">= 17.0.0" + } + }, + "node_modules/@loaders.gl/schema-utils": { + "version": "4.4.2", + "resolved": "https://registry.npmjs.org/@loaders.gl/schema-utils/-/schema-utils-4.4.2.tgz", + "integrity": "sha512-yYYRD/POBEO72rhIyLASrqKUUhfIOQuFk/fgInN6Td2qvFgsHbo5UaCM4sTqVUWwNxNvXDQi8ezpbnCa/yi+OQ==", + "license": "MIT", + "dependencies": { + "@loaders.gl/schema": "4.4.2", + "@types/geojson": "^7946.0.7", + "apache-arrow": ">= 17.0.0" + }, + "peerDependencies": { + "@loaders.gl/core": "~4.4.0" + } + }, + "node_modules/@loaders.gl/worker-utils": { + "version": "4.4.2", + "resolved": "https://registry.npmjs.org/@loaders.gl/worker-utils/-/worker-utils-4.4.2.tgz", + "integrity": "sha512-oiZ0SoC1QKrOkhYPlVZ6Q06CtmuFRyZw2rwzmT08ZyaGtOArIJHDjlhxzwWiv+6fdws47Ub5uIGsdI1Ab1xYsA==", + "license": "MIT", + "peerDependencies": { + "@loaders.gl/core": "~4.4.0" + } + }, + "node_modules/@luma.gl/core": { + "version": "9.3.3", + "resolved": "https://registry.npmjs.org/@luma.gl/core/-/core-9.3.3.tgz", + "integrity": "sha512-jCFm2htvrVpcXIy85TBTF1ROgMfknKnfw2OH+Vydr41hiCFd6nqr79gM3f2uhaNkal0BghFNqF3qDioKiUWtew==", + "license": "MIT", + "dependencies": { + "@math.gl/types": "^4.1.0", + "@probe.gl/env": "^4.1.1", + "@probe.gl/log": "^4.1.1", + "@probe.gl/stats": "^4.1.1", + "@types/offscreencanvas": "^2019.7.3" + } + }, + "node_modules/@luma.gl/engine": { + "version": "9.3.3", + "resolved": "https://registry.npmjs.org/@luma.gl/engine/-/engine-9.3.3.tgz", + "integrity": "sha512-StmMTzUcUlpKMU3wvWU48A6OQyphptD9zVGBsSkK6iHIBdtBKlOcmqRkyfvRouo8JHtlrnoJDHLVKhxorwhGAg==", + "license": "MIT", + "dependencies": { + "@math.gl/core": "^4.1.0", + "@math.gl/types": "^4.1.0", + "@probe.gl/log": "^4.1.1", + "@probe.gl/stats": "^4.1.1" + }, + "peerDependencies": { + "@luma.gl/core": "~9.3.0", + "@luma.gl/shadertools": "~9.3.0" + } + }, + "node_modules/@luma.gl/shadertools": { + "version": "9.3.3", + "resolved": "https://registry.npmjs.org/@luma.gl/shadertools/-/shadertools-9.3.3.tgz", + "integrity": "sha512-4ZfG4/Utix951vqyiG/JIx+Eg+GMNwOxgr/07/i0gf7bK1gJZIEQ5BxVcDw4MCQfdoVlGPGzl0cQKbdqBvaCAQ==", + "license": "MIT", + "dependencies": { + "@math.gl/core": "^4.1.0", + "@math.gl/types": "^4.1.0" + }, + "peerDependencies": { + "@luma.gl/core": "~9.3.0" + } + }, + "node_modules/@luma.gl/webgl": { + "version": "9.3.3", + "resolved": "https://registry.npmjs.org/@luma.gl/webgl/-/webgl-9.3.3.tgz", + "integrity": "sha512-X+aavdP5o6VFHSA0es9gKZTT145jfcFbhKJt/gwJrptnKNoIW4+Y37ZEpCo1AzAnr+FQCxjgcM2kOCpoWMfSVA==", + "license": "MIT", + "dependencies": { + "@math.gl/types": "^4.1.0", + "@probe.gl/env": "^4.1.1" + }, + "peerDependencies": { + "@luma.gl/core": "~9.3.0" + } + }, + "node_modules/@mapbox/tiny-sdf": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@mapbox/tiny-sdf/-/tiny-sdf-2.2.0.tgz", + "integrity": "sha512-LVL4wgI9YAum5V+LNVQO6QgFBPw7/MIIY4XJPNsPDMrjEwcE+JfKk1LuIl8GnF197ejVdC9QdPaxrx5gfgdGXg==", + "license": "BSD-2-Clause" + }, + "node_modules/@math.gl/core": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@math.gl/core/-/core-4.1.0.tgz", + "integrity": "sha512-FrdHBCVG3QdrworwrUSzXIaK+/9OCRLscxI2OUy6sLOHyHgBMyfnEGs99/m3KNvs+95BsnQLWklVfpKfQzfwKA==", + "license": "MIT", + "dependencies": { + "@math.gl/types": "4.1.0" + } + }, + "node_modules/@math.gl/polygon": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@math.gl/polygon/-/polygon-4.1.0.tgz", + "integrity": "sha512-YA/9PzaCRHbIP5/0E9uTYrqe+jsYTQoqoDWhf6/b0Ixz8bPZBaGDEafLg3z7ffBomZLacUty9U3TlPjqMtzPjA==", + "license": "MIT", + "dependencies": { + "@math.gl/core": "4.1.0" + } + }, + "node_modules/@math.gl/sun": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@math.gl/sun/-/sun-4.1.0.tgz", + "integrity": "sha512-i3q6OCBLSZ5wgZVhXg+X7gsjY/TUtuFW/2KBiq/U1ypLso3S4sEykoU/MGjxUv1xiiGtr+v8TeMbO1OBIh/HmA==", + "license": "MIT" + }, + "node_modules/@math.gl/types": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@math.gl/types/-/types-4.1.0.tgz", + "integrity": "sha512-clYZdHcmRvMzVK5fjeDkQlHUzXQSNdZ7s4xOqC3nJPgz4C/TZkUecTo9YS4PruZqtDda/ag4erndP0MIn40dGA==", + "license": "MIT" + }, + "node_modules/@math.gl/web-mercator": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@math.gl/web-mercator/-/web-mercator-4.1.0.tgz", + "integrity": "sha512-HZo3vO5GCMkXJThxRJ5/QYUYRr3XumfT8CzNNCwoJfinxy5NtKUd7dusNTXn7yJ40UoB8FMIwkVwNlqaiRZZAw==", + "license": "MIT", + "dependencies": { + "@math.gl/core": "4.1.0" + } + }, + "node_modules/@probe.gl/env": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@probe.gl/env/-/env-4.1.1.tgz", + "integrity": "sha512-+68seNDMVsEegRB47pFA/Ws1Fjy8agcFYXxzorKToyPcD6zd+gZ5uhwoLd7TzsSw6Ydns//2KEszWn+EnNHTbA==", + "license": "MIT" + }, + "node_modules/@probe.gl/log": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@probe.gl/log/-/log-4.1.1.tgz", + "integrity": "sha512-kcZs9BT44pL7hS1OkRGKYRXI/SN9KejUlPD+BY40DguRLzdC5tLG/28WGMyfKdn/51GT4a0p+0P8xvDn1Ez+Kg==", + "license": "MIT", + "dependencies": { + "@probe.gl/env": "4.1.1" + } + }, + "node_modules/@probe.gl/stats": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@probe.gl/stats/-/stats-4.1.1.tgz", + "integrity": "sha512-4VpAyMHOqydSvPlEyHwXaE+AkIdR03nX+Qhlxsk2D/IW4OVmDZgIsvJB1cDzyEEtcfKcnaEbfXeiPgejBceT6g==", + "license": "MIT" + }, + "node_modules/@swc/helpers": { + "version": "0.5.23", + "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.23.tgz", + "integrity": "sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.8.0" + } + }, + "node_modules/@types/command-line-args": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/command-line-args/-/command-line-args-5.2.3.tgz", + "integrity": "sha512-uv0aG6R0Y8WHZLTamZwtfsDLVRnOa+n+n5rEvFWL5Na5gZ8V2Teab/duDPFzIIIhs9qizDpcavCusCLJZu62Kw==", + "license": "MIT" + }, + "node_modules/@types/command-line-usage": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/@types/command-line-usage/-/command-line-usage-5.0.4.tgz", + "integrity": "sha512-BwR5KP3Es/CSht0xqBcUXS3qCAUVXwpRKsV2+arxeb65atasuXG9LykC9Ab10Cw3s2raH92ZqOeILaQbsB2ACg==", + "license": "MIT" + }, + "node_modules/@types/geojson": { + "version": "7946.0.16", + "resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz", + "integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==", + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "24.12.4", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.12.4.tgz", + "integrity": "sha512-GUUEShf+PBCGW2KaXwcIt3Yk+e3pkKwWKb9GSyM9WQVE+ep2jzmHdGsHzu4wgcZy5fN9FBdVzjpBQsYlpfpgLA==", + "license": "MIT", + "dependencies": { + "undici-types": "~7.16.0" + } + }, + "node_modules/@types/offscreencanvas": { + "version": "2019.7.3", + "resolved": "https://registry.npmjs.org/@types/offscreencanvas/-/offscreencanvas-2019.7.3.tgz", + "integrity": "sha512-ieXiYmgSRXUDeOntE1InxjWyvEelZGP63M+cGuquuRLuIKKT1osnkXjxev9B7d1nXSug5vpunx+gNlbVxMlC9A==", + "license": "MIT" + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/apache-arrow": { + "version": "21.1.0", + "resolved": "https://registry.npmjs.org/apache-arrow/-/apache-arrow-21.1.0.tgz", + "integrity": "sha512-kQrYLxhC+NTVVZ4CCzGF6L/uPVOzJmD1T3XgbiUnP7oTeVFOFgEUu6IKNwCDkpFoBVqDKQivlX4RUFqqnWFlEA==", + "license": "Apache-2.0", + "dependencies": { + "@swc/helpers": "^0.5.11", + "@types/command-line-args": "^5.2.3", + "@types/command-line-usage": "^5.0.4", + "@types/node": "^24.0.3", + "command-line-args": "^6.0.1", + "command-line-usage": "^7.0.1", + "flatbuffers": "^25.1.24", + "json-bignum": "^0.0.3", + "tslib": "^2.6.2" + }, + "bin": { + "arrow2csv": "bin/arrow2csv.js" + } + }, + "node_modules/array-back": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/array-back/-/array-back-6.2.3.tgz", + "integrity": "sha512-SGDvmg6QTYiTxCBkYVmThcoa67uLl35pyzRHdpCGBOcqFy6BtwnphoFPk7LhJshD+Yk1Kt35WGWeZPTgwR4Fhw==", + "license": "MIT", + "engines": { + "node": ">=12.17" + } + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/chalk-template": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/chalk-template/-/chalk-template-0.4.0.tgz", + "integrity": "sha512-/ghrgmhfY8RaSdeo43hNXxpoHAtxdbskUHjPpfqUWGttFgycUhYPGx3YZBCnUCvOa7Doivn1IZec3DEGFoMgLg==", + "license": "MIT", + "dependencies": { + "chalk": "^4.1.2" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/chalk-template?sponsor=1" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "license": "MIT" + }, + "node_modules/command-line-args": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/command-line-args/-/command-line-args-6.0.2.tgz", + "integrity": "sha512-AIjYVxrV9X752LmPDLbVYv8aMCuHPSLZJXEo2qo/xJfv+NYhaZ4sMSF01rM+gHPaMgvPM0l5D/F+Qx+i2WfSmQ==", + "license": "MIT", + "dependencies": { + "array-back": "^6.2.3", + "find-replace": "^5.0.2", + "lodash.camelcase": "^4.3.0", + "typical": "^7.3.0" + }, + "engines": { + "node": ">=12.20" + }, + "peerDependencies": { + "@75lb/nature": "latest" + }, + "peerDependenciesMeta": { + "@75lb/nature": { + "optional": true + } + } + }, + "node_modules/command-line-usage": { + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/command-line-usage/-/command-line-usage-7.0.4.tgz", + "integrity": "sha512-85UdvzTNx/+s5CkSgBm/0hzP80RFHAa7PsfeADE5ezZF3uHz3/Tqj9gIKGT9PTtpycc3Ua64T0oVulGfKxzfqg==", + "license": "MIT", + "dependencies": { + "array-back": "^6.2.2", + "chalk-template": "^0.4.0", + "table-layout": "^4.1.1", + "typical": "^7.3.0" + }, + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/d3-array": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz", + "integrity": "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==", + "license": "ISC", + "dependencies": { + "internmap": "1 - 2" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-color": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz", + "integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-format": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.2.tgz", + "integrity": "sha512-AJDdYOdnyRDV5b6ArilzCPPwc1ejkHcoyFarqlPqT7zRYjhavcT3uSrqcMvsgh2CgoPbK3RCwyHaVyxYcP2Arg==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-geo": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/d3-geo/-/d3-geo-3.1.1.tgz", + "integrity": "sha512-637ln3gXKXOwhalDzinUgY83KzNWZRKbYubaG+fGVuc/dxO64RRljtCTnf5ecMyE1RIdtqpkVcq0IbtU2S8j2Q==", + "license": "ISC", + "dependencies": { + "d3-array": "2.5.0 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-interpolate": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz", + "integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==", + "license": "ISC", + "dependencies": { + "d3-color": "1 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-scale": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.2.tgz", + "integrity": "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==", + "license": "ISC", + "dependencies": { + "d3-array": "2.10.0 - 3", + "d3-format": "1 - 3", + "d3-interpolate": "1.2.0 - 3", + "d3-time": "2.1.1 - 3", + "d3-time-format": "2 - 4" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-scale-chromatic": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/d3-scale-chromatic/-/d3-scale-chromatic-3.1.0.tgz", + "integrity": "sha512-A3s5PWiZ9YCXFye1o246KoscMWqf8BsD9eRiJ3He7C9OBaxKhAd5TFCdEx/7VbKtxxTsu//1mMJFrEt572cEyQ==", + "license": "ISC", + "dependencies": { + "d3-color": "1 - 3", + "d3-interpolate": "1 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-time": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/d3-time/-/d3-time-3.1.0.tgz", + "integrity": "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==", + "license": "ISC", + "dependencies": { + "d3-array": "2 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-time-format": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/d3-time-format/-/d3-time-format-4.1.0.tgz", + "integrity": "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==", + "license": "ISC", + "dependencies": { + "d3-time": "1 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/earcut": { + "version": "2.2.4", + "resolved": "https://registry.npmjs.org/earcut/-/earcut-2.2.4.tgz", + "integrity": "sha512-/pjZsA1b4RPHbeWZQn66SWS8nZZWLQQ23oE3Eam7aroEFGEvwKAsJfZ9ytiEMycfzXWpca4FA9QIOehf7PocBQ==", + "license": "ISC" + }, + "node_modules/esbuild": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.0.tgz", + "integrity": "sha512-sNR9MHpXSUV/XB4zmsFKN+QgVG82Cc7+/aaxJ8Adi8hyOac+EXptIp45QBPaVyX3N70664wRbTcLTOemCAnyqw==", + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.0", + "@esbuild/android-arm": "0.28.0", + "@esbuild/android-arm64": "0.28.0", + "@esbuild/android-x64": "0.28.0", + "@esbuild/darwin-arm64": "0.28.0", + "@esbuild/darwin-x64": "0.28.0", + "@esbuild/freebsd-arm64": "0.28.0", + "@esbuild/freebsd-x64": "0.28.0", + "@esbuild/linux-arm": "0.28.0", + "@esbuild/linux-arm64": "0.28.0", + "@esbuild/linux-ia32": "0.28.0", + "@esbuild/linux-loong64": "0.28.0", + "@esbuild/linux-mips64el": "0.28.0", + "@esbuild/linux-ppc64": "0.28.0", + "@esbuild/linux-riscv64": "0.28.0", + "@esbuild/linux-s390x": "0.28.0", + "@esbuild/linux-x64": "0.28.0", + "@esbuild/netbsd-arm64": "0.28.0", + "@esbuild/netbsd-x64": "0.28.0", + "@esbuild/openbsd-arm64": "0.28.0", + "@esbuild/openbsd-x64": "0.28.0", + "@esbuild/openharmony-arm64": "0.28.0", + "@esbuild/sunos-x64": "0.28.0", + "@esbuild/win32-arm64": "0.28.0", + "@esbuild/win32-ia32": "0.28.0", + "@esbuild/win32-x64": "0.28.0" + } + }, + "node_modules/find-replace": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/find-replace/-/find-replace-5.0.2.tgz", + "integrity": "sha512-Y45BAiE3mz2QsrN2fb5QEtO4qb44NcS7en/0y9PEVsg351HsLeVclP8QPMH79Le9sH3rs5RSwJu99W0WPZO43Q==", + "license": "MIT", + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@75lb/nature": "latest" + }, + "peerDependenciesMeta": { + "@75lb/nature": { + "optional": true + } + } + }, + "node_modules/flatbuffers": { + "version": "25.9.23", + "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-25.9.23.tgz", + "integrity": "sha512-MI1qs7Lo4Syw0EOzUl0xjs2lsoeqFku44KpngfIduHBYvzm8h2+7K8YMQh1JtVVVrUvhLpNwqVi4DERegUJhPQ==", + "license": "Apache-2.0" + }, + "node_modules/gl-matrix": { + "version": "3.4.4", + "resolved": "https://registry.npmjs.org/gl-matrix/-/gl-matrix-3.4.4.tgz", + "integrity": "sha512-latSnyDNt/8zYUB6VIJ6PCh2jBjJX6gnDsoCZ7LyW7GkqrD51EWwa9qCoGixj8YqBtETQK/xY7OmpTF8xz1DdQ==", + "license": "MIT" + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/internmap": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz", + "integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/json-bignum": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/json-bignum/-/json-bignum-0.0.3.tgz", + "integrity": "sha512-2WHyXj3OfHSgNyuzDbSxI1w2jgw5gkWSWhS7Qg4bWXx1nLk3jnbwfUeS0PSba3IzpTUWdHxBieELUzXRjQB2zg==", + "engines": { + "node": ">=0.8" + } + }, + "node_modules/kdbush": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/kdbush/-/kdbush-4.1.0.tgz", + "integrity": "sha512-e9vurzrXJQrFX6ckpHP3bvj5l+9CnYzkxDNnNQ1h2QTqdWsUAJgXiKdGNcOa1EY85dU8KbQ+z/FdQdB7P+9yfQ==", + "license": "ISC" + }, + "node_modules/lodash.camelcase": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", + "integrity": "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==", + "license": "MIT" + }, + "node_modules/mjolnir.js": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/mjolnir.js/-/mjolnir.js-3.0.0.tgz", + "integrity": "sha512-siX3YCG7N2HnmN1xMH3cK4JkUZJhbkhRFJL+G5N1vH0mh1t5088rJknIoqDFWDIU6NPGvRRgLnYW3ZHjSMEBLA==", + "license": "MIT" + }, + "node_modules/reselect": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/reselect/-/reselect-5.2.0.tgz", + "integrity": "sha512-AgZ3UOZm3YndfrJ4OYjgrT7bmCm/1iqkjvEfH/oYjzh6PD2qw4QuT3jjnXIrpdt4MTpMXclMT3lXbmRY+XRakw==", + "license": "MIT" + }, + "node_modules/seedrandom": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/seedrandom/-/seedrandom-3.0.5.tgz", + "integrity": "sha512-8OwmbklUNzwezjGInmZ+2clQmExQPvomqjL7LFqOYqtmuxRgQYqOD3mHaU+MvZn5FLUeVxVfQjwLZW/n/JFuqg==", + "license": "MIT" + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/table-layout": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/table-layout/-/table-layout-4.1.1.tgz", + "integrity": "sha512-iK5/YhZxq5GO5z8wb0bY1317uDF3Zjpha0QFFLA8/trAoiLbQD0HUbMesEaxyzUgDxi2QlcbM8IvqOlEjgoXBA==", + "license": "MIT", + "dependencies": { + "array-back": "^6.2.2", + "wordwrapjs": "^5.1.0" + }, + "engines": { + "node": ">=12.17" + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD" + }, + "node_modules/typical": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/typical/-/typical-7.3.0.tgz", + "integrity": "sha512-ya4mg/30vm+DOWfBg4YK3j2WD6TWtRkCbasOJr40CseYENzCUby/7rIvXA99JGsQHeNxLbnXdyLLxKSv3tauFw==", + "license": "MIT", + "engines": { + "node": ">=12.17" + } + }, + "node_modules/undici-types": { + "version": "7.16.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz", + "integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==", + "license": "MIT" + }, + "node_modules/wordwrapjs": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/wordwrapjs/-/wordwrapjs-5.1.1.tgz", + "integrity": "sha512-0yweIbkINJodk27gX9LBGMzyQdBDan3s/dEAiwBOj+Mf0PPyWL6/rikalkv8EeD0E8jm4o5RXEOrFTP3NXbhJg==", + "license": "MIT", + "engines": { + "node": ">=12.17" + } + } + } +} diff --git a/data-raw/flowmap-vendor/package.json b/data-raw/flowmap-vendor/package.json new file mode 100644 index 0000000..9d0d8fa --- /dev/null +++ b/data-raw/flowmap-vendor/package.json @@ -0,0 +1,23 @@ +{ + "name": "mapgl-flowmap-vendor", + "version": "1.0.0", + "private": true, + "description": "Reproducible vendoring workspace for the mapgl FlowmapGL browser bundle.", + "license": "MIT", + "type": "module", + "scripts": { + "build": "./build-flowmap.sh build", + "check": "./build-flowmap.sh check" + }, + "dependencies": { + "@deck.gl/core": "9.3.2", + "@deck.gl/layers": "9.3.2", + "@deck.gl/mapbox": "9.3.2", + "@flowmap.gl/data": "9.3.0", + "@flowmap.gl/layers": "9.3.0", + "@luma.gl/core": "9.3.3", + "@luma.gl/engine": "9.3.3", + "@luma.gl/shadertools": "9.3.3", + "esbuild": "0.28.0" + } +} diff --git a/data-raw/flowmap-vendor/patches/flowmap-temporal-scale-domain.patch b/data-raw/flowmap-vendor/patches/flowmap-temporal-scale-domain.patch new file mode 100644 index 0000000..886d79e --- /dev/null +++ b/data-raw/flowmap-vendor/patches/flowmap-temporal-scale-domain.patch @@ -0,0 +1,263 @@ +diff --git a/node_modules/@flowmap.gl/data/dist/FlowmapSelectors.d.ts b/node_modules/@flowmap.gl/data/dist/FlowmapSelectors.d.ts +index 92cc7ab..746013c 100644 +--- a/node_modules/@flowmap.gl/data/dist/FlowmapSelectors.d.ts ++++ b/node_modules/@flowmap.gl/data/dist/FlowmapSelectors.d.ts +@@ -1,6 +1,6 @@ + import { ScaleLinear } from 'd3-scale'; + import FlowmapAggregateAccessors from './FlowmapAggregateAccessors'; +-import { FlowmapState } from './FlowmapState'; ++import { FlowmapState, TemporalScaleDomain } from './FlowmapState'; + import { ClusterIndex, LocationWeightGetter } from './cluster/ClusterIndex'; + import { ColorsRGBA, DiffColorsRGBA } from './colors'; + import { TimeGranularityKey } from './time'; +@@ -25,6 +25,8 @@ export default class FlowmapSelectors, F extends R + getZoom: (state: FlowmapState, props: FlowmapData) => number | undefined; + getViewport: (state: FlowmapState, props: FlowmapData) => ViewportProps; + getSelectedTimeRange: (state: FlowmapState, props: FlowmapData) => [Date, Date] | undefined; ++ getSelectedTimeRanges: (state: FlowmapState, props: FlowmapData) => [Date, Date][] | undefined; ++ getTemporalScaleDomain: Selector; + getColorScheme: Selector; + getDarkMode: Selector; + getFadeEnabled: Selector; +@@ -134,7 +136,9 @@ export default class FlowmapSelectors, F extends R + memoize: typeof import("reselect").weakMapMemoize; + }; + getUnknownLocations: Selector | undefined>; ++ getSortedAggregatedFlows: Selector; + getSortedAggregatedFilteredFlows: Selector; ++ getFlowsForScaleDomain: Selector; + getExpandedSelectedLocationsSet: Selector | undefined>; + getTotalCountsByTime: Selector; + getMaxLocationCircleSize: Selector; +diff --git a/node_modules/@flowmap.gl/data/dist/FlowmapSelectors.js b/node_modules/@flowmap.gl/data/dist/FlowmapSelectors.js +index 3892964..0ba65cf 100644 +--- a/node_modules/@flowmap.gl/data/dist/FlowmapSelectors.js ++++ b/node_modules/@flowmap.gl/data/dist/FlowmapSelectors.js +@@ -33,6 +33,8 @@ export default class FlowmapSelectors { + this.getZoom = (state, props) => state.viewport.zoom; + this.getViewport = (state, props) => state.viewport; + this.getSelectedTimeRange = (state, props) => state.filter?.selectedTimeRange; ++ this.getSelectedTimeRanges = (state, props) => state.filter?.selectedTimeRanges; ++ this.getTemporalScaleDomain = (state, props) => state.settings.temporalScaleDomain; + this.getColorScheme = (state, props) => state.settings.colorScheme; + this.getDarkMode = (state, props) => state.settings.darkMode; + this.getFadeEnabled = (state, props) => state.settings.fadeEnabled; +@@ -131,17 +133,19 @@ export default class FlowmapSelectors { + const { interval } = timeGranularity; + return [timeExtent[0], interval.offset(interval.floor(timeExtent[1]), 1)]; + }); +- this.getSortedFlowsForKnownLocationsFilteredByTime = createSelector(this.getSortedFlowsForKnownLocations, this.getTimeExtent, this.getSelectedTimeRange, (flows, timeExtent, timeRange) => { ++ this.getSortedFlowsForKnownLocationsFilteredByTime = createSelector(this.getSortedFlowsForKnownLocations, this.getTimeExtent, this.getSelectedTimeRange, this.getSelectedTimeRanges, (flows, timeExtent, timeRange, timeRanges) => { + if (!flows) + return undefined; +- if (!timeExtent || +- !timeRange || +- (timeExtent[0] === timeRange[0] && timeExtent[1] === timeRange[1])) { ++ const selectedRanges = Array.isArray(timeRanges) && timeRanges.length > 0 ? timeRanges : timeRange ? [timeRange] : null; ++ if (!timeExtent || !selectedRanges || selectedRanges.length === 0) { ++ return flows; ++ } ++ if (selectedRanges.length === 1 && timeExtent[0] === selectedRanges[0][0] && timeExtent[1] === selectedRanges[0][1]) { + return flows; + } + return flows.filter((flow) => { + const time = this.accessors.getFlowTime(flow); +- return time && timeRange[0] <= time && time < timeRange[1]; ++ return time && selectedRanges.some((range) => range[0] <= time && time < range[1]); + }); + }); + this.getLocationsHavingFlows = createSelector(this.getSortedFlowsForKnownLocations, this.getLocations, (flows, locations) => { +@@ -296,6 +300,19 @@ export default class FlowmapSelectors { + } + return missing; + }); ++ this.getSortedAggregatedFlows = createSelector(this.getClusterIndex, this.getClusteringEnabled, this.getSortedFlowsForKnownLocations, this.getClusterZoom, (clusterTree, isClusteringEnabled, flows, clusterZoom) => { ++ if (!flows) ++ return undefined; ++ let aggregated; ++ if (isClusteringEnabled && clusterTree && clusterZoom != null) { ++ aggregated = clusterTree.aggregateFlows(flows, clusterZoom, this.accessors.getFlowmapDataAccessors()); ++ } ++ else { ++ aggregated = aggregateFlows(flows, this.accessors.getFlowmapDataAccessors()); ++ } ++ aggregated.sort((a, b) => descending(Math.abs(this.accessors.getFlowMagnitude(a)), Math.abs(this.accessors.getFlowMagnitude(b)))); ++ return aggregated; ++ }); + this.getSortedAggregatedFilteredFlows = createSelector(this.getClusterIndex, this.getClusteringEnabled, this.getSortedFlowsForKnownLocationsFilteredByTime, this.getClusterZoom, this.getTimeExtent, (clusterTree, isClusteringEnabled, flows, clusterZoom, timeExtent) => { + if (!flows) + return undefined; +@@ -314,6 +331,9 @@ export default class FlowmapSelectors { + aggregated.sort((a, b) => descending(Math.abs(this.accessors.getFlowMagnitude(a)), Math.abs(this.accessors.getFlowMagnitude(b)))); + return aggregated; + }); ++ this.getFlowsForScaleDomain = createSelector(this.getTemporalScaleDomain, this.getSortedAggregatedFlows, this.getSortedAggregatedFilteredFlows, (temporalScaleDomain, allFlows, selectedFlows) => { ++ return temporalScaleDomain === 'all' ? allFlows : selectedFlows; ++ }); + this.getExpandedSelectedLocationsSet = createSelector(this.getClusteringEnabled, this.getSelectedLocationsSet, this.getClusterIndex, (clusteringEnabled, selectedLocations, clusterIndex) => { + if (!selectedLocations || !clusterIndex) { + return selectedLocations; +@@ -497,7 +517,7 @@ export default class FlowmapSelectors { + // we need ascending for rendering + return picked.reverse(); + }); +- this._getFlowMagnitudeExtent = createSelector(this.getSortedAggregatedFilteredFlows, this.getSelectedLocationsSet, this.getLocationFilterMode, (flows, selectedLocationsSet, locationFilterMode) => { ++ this._getFlowMagnitudeExtent = createSelector(this.getFlowsForScaleDomain, this.getSelectedLocationsSet, this.getLocationFilterMode, (flows, selectedLocationsSet, locationFilterMode) => { + if (!flows) + return undefined; + let rv = undefined; +@@ -519,10 +539,31 @@ export default class FlowmapSelectors { + } + return rv; + }); +- this._getAdaptiveFlowMagnitudeExtent = createSelector(this.getFlowsForFlowmapLayer, (flows) => { +- if (!flows) ++ this._getAdaptiveFlowMagnitudeExtent = createSelector(this.getFlowsForScaleDomain, this.getLocationIdsInViewport, this.getSelectedLocationsSet, this.getLocationFilterMode, this.getMaxTopFlowsDisplayNum, this.getFlowEndpointsInViewportMode, (flows, locationIdsInViewport, selectedLocationsSet, locationFilterMode, maxTopFlowsDisplayNum, flowEndpointsInViewportMode) => { ++ if (!flows || !locationIdsInViewport) + return undefined; +- const rv = extent(flows, this.accessors.getFlowMagnitude); ++ const picked = []; ++ let pickedCount = 0; ++ for (const flow of flows) { ++ const origin = this.accessors.getFlowOriginId(flow); ++ const dest = this.accessors.getFlowDestId(flow); ++ const originInView = locationIdsInViewport.has(origin); ++ const destInView = locationIdsInViewport.has(dest); ++ const isInViewport = flowEndpointsInViewportMode === 'both' ++ ? originInView && destInView ++ : originInView || destInView; ++ if (isInViewport) { ++ if (this.isFlowInSelection(flow, selectedLocationsSet, locationFilterMode)) { ++ if (origin !== dest) { ++ picked.push(flow); ++ pickedCount++; ++ } ++ } ++ } ++ if (pickedCount > maxTopFlowsDisplayNum) ++ break; ++ } ++ const rv = extent(picked, this.accessors.getFlowMagnitude); + return rv[0] !== undefined && rv[1] !== undefined ? rv : undefined; + }); + this.getFlowMagnitudeExtent = (state, props) => { +@@ -613,8 +654,8 @@ export default class FlowmapSelectors { + this.getLocationOrClusterByIdGetter = createSelector(this.getClusterIndex, this.getLocationsById, (clusterIndex, locationsById) => { + return (id) => clusterIndex?.getClusterById(id) ?? locationsById?.get(id); + }); +- this.getLayersData = createSelector(this.getLocationsForFlowmapLayer, this.getFlowsForFlowmapLayer, this.getFlowmapColorsRGBA, this.getLocationsForFlowmapLayerById, this.getLocationIdsInViewport, this.getInCircleSizeGetter, this.getOutCircleSizeGetter, this.getFlowThicknessScale, this.getViewport, this.getFlowLinesRenderingMode, this.getLocationLabelsEnabled, (locations, flows, flowmapColors, locationsById, locationIdsInViewport, getInCircleSize, getOutCircleSize, flowThicknessScale, viewport, flowLinesRenderingMode, locationLabelsEnabled) => { +- return this._prepareLayersData(locations, flows, flowmapColors, locationsById, locationIdsInViewport, getInCircleSize, getOutCircleSize, flowThicknessScale, viewport, flowLinesRenderingMode, locationLabelsEnabled); ++ this.getLayersData = createSelector(this.getLocationsForFlowmapLayer, this.getFlowsForFlowmapLayer, this.getFlowmapColorsRGBA, this.getLocationsForFlowmapLayerById, this.getLocationIdsInViewport, this.getInCircleSizeGetter, this.getOutCircleSizeGetter, this.getFlowThicknessScale, this.getFlowMagnitudeExtent, this.getViewport, this.getFlowLinesRenderingMode, this.getLocationLabelsEnabled, (locations, flows, flowmapColors, locationsById, locationIdsInViewport, getInCircleSize, getOutCircleSize, flowThicknessScale, flowMagnitudeExtent, viewport, flowLinesRenderingMode, locationLabelsEnabled) => { ++ return this._prepareLayersData(locations, flows, flowmapColors, locationsById, locationIdsInViewport, getInCircleSize, getOutCircleSize, flowThicknessScale, flowMagnitudeExtent, viewport, flowLinesRenderingMode, locationLabelsEnabled); + }); + this.accessors = new FlowmapAggregateAccessors(accessors); + this.setAccessors(accessors); +@@ -634,17 +675,17 @@ export default class FlowmapSelectors { + const getInCircleSize = this.getInCircleSizeGetter(state, props); + const getOutCircleSize = this.getOutCircleSizeGetter(state, props); + const flowThicknessScale = this.getFlowThicknessScale(state, props); ++ const flowMagnitudeExtent = this.getFlowMagnitudeExtent(state, props); + const locationLabelsEnabled = this.getLocationLabelsEnabled(state, props); + const viewport = this.getViewport(state, props); +- return this._prepareLayersData(locations, flows, flowmapColors, locationsById, locationIdsInViewport, getInCircleSize, getOutCircleSize, flowThicknessScale, viewport, state.settings.flowLinesRenderingMode, locationLabelsEnabled); ++ return this._prepareLayersData(locations, flows, flowmapColors, locationsById, locationIdsInViewport, getInCircleSize, getOutCircleSize, flowThicknessScale, flowMagnitudeExtent, viewport, state.settings.flowLinesRenderingMode, locationLabelsEnabled); + } +- _prepareLayersData(locations, flows, flowmapColors, locationsById, locationIdsInViewport, getInCircleSize, getOutCircleSize, flowThicknessScale, viewport, flowLinesRenderingMode, locationLabelsEnabled) { ++ _prepareLayersData(locations, flows, flowmapColors, locationsById, locationIdsInViewport, getInCircleSize, getOutCircleSize, flowThicknessScale, flowMagnitudeExtent, viewport, flowLinesRenderingMode, locationLabelsEnabled) { + if (!locations) + locations = []; + if (!flows) + flows = []; + const { getFlowOriginId, getFlowDestId, getFlowMagnitude, getLocationId, getLocationLon, getLocationLat, getLocationName, } = this.accessors; +- const flowMagnitudeExtent = extent(flows, (f) => getFlowMagnitude(f)); + const flowColorScale = getFlowColorScale(flowmapColors, flowMagnitudeExtent, flowLinesRenderingMode === 'animated-straight'); + // Using a generator here helps to avoid creating intermediary arrays + const circlePositions = Float64Array.from((function* () { +diff --git a/node_modules/@flowmap.gl/data/dist/FlowmapState.d.ts b/node_modules/@flowmap.gl/data/dist/FlowmapState.d.ts +index 185b0ee..aeb99db 100644 +--- a/node_modules/@flowmap.gl/data/dist/FlowmapState.d.ts ++++ b/node_modules/@flowmap.gl/data/dist/FlowmapState.d.ts +@@ -1,9 +1,11 @@ + import { FlowLinesRenderingMode, LocationFilterMode, ViewportProps } from './types'; + export type FlowEndpointsInViewportMode = 'any' | 'both'; ++export type TemporalScaleDomain = 'selected' | 'all'; + export interface FilterState { + selectedLocations?: (string | number)[]; + locationFilterMode?: LocationFilterMode; + selectedTimeRange?: [Date, Date]; ++ selectedTimeRanges?: [Date, Date][]; + } + export interface SettingsState { + flowLinesRenderingMode: FlowLinesRenderingMode; +@@ -20,6 +22,7 @@ export interface SettingsState { + fadeAmount: number; + colorScheme: string | string[] | undefined; + highlightColor: string | number[]; ++ temporalScaleDomain: TemporalScaleDomain; + maxTopFlowsDisplayNum: number; + flowEndpointsInViewportMode: FlowEndpointsInViewportMode; + } +diff --git a/node_modules/@flowmap.gl/layers/dist/FlowmapLayer.d.ts b/node_modules/@flowmap.gl/layers/dist/FlowmapLayer.d.ts +index 3dacdf9..65351d1 100644 +--- a/node_modules/@flowmap.gl/layers/dist/FlowmapLayer.d.ts ++++ b/node_modules/@flowmap.gl/layers/dist/FlowmapLayer.d.ts +@@ -1,5 +1,5 @@ + import { CompositeLayer } from '@deck.gl/core'; +-import { FilterState, FlowEndpointsInViewportMode, FlowLinesLayerAttributes, FlowLinesRenderingMode, FlowmapAggregateAccessors, FlowmapData, FlowmapDataAccessors, FlowmapDataProvider, LayersData } from '@flowmap.gl/data'; ++import { FilterState, FlowEndpointsInViewportMode, FlowLinesLayerAttributes, FlowLinesRenderingMode, FlowmapAggregateAccessors, FlowmapData, FlowmapDataAccessors, FlowmapDataProvider, LayersData, TemporalScaleDomain } from '@flowmap.gl/data'; + import { FlowmapLayerPickingInfo, LayerProps } from './types'; + export type FlowmapLayerProps, F extends Record> = { + data?: FlowmapData; +@@ -22,6 +22,7 @@ export type FlowmapLayerProps, F extends Record | undefined, event: SourceEvent) => void; +@@ -68,6 +69,7 @@ export default class FlowmapLayer, F extends Recor + clusteringAuto: boolean; + clusteringLevel: undefined; + adaptiveScalesEnabled: boolean; ++ temporalScaleDomain: string; + flowLineThicknessScale: number; + flowLineCurviness: number; + colorScheme: string; +diff --git a/node_modules/@flowmap.gl/layers/dist/FlowmapLayer.js b/node_modules/@flowmap.gl/layers/dist/FlowmapLayer.js +index 404c7ed..7606439 100644 +--- a/node_modules/@flowmap.gl/layers/dist/FlowmapLayer.js ++++ b/node_modules/@flowmap.gl/layers/dist/FlowmapLayer.js +@@ -28,6 +28,7 @@ const PROPS_TO_CAUSE_LAYER_DATA_UPDATE = [ + 'fadeAmount', + 'colorScheme', + 'highlightColor', ++ 'temporalScaleDomain', + 'maxTopFlowsDisplayNum', + 'flowEndpointsInViewportMode', + ]; +@@ -171,7 +172,7 @@ class FlowmapLayer extends CompositeLayer { + _getSettingsState() { + const props = this.typedProps; + const defaults = FlowmapLayer.defaultProps; +- const { locationsEnabled, locationTotalsEnabled, locationLabelsEnabled, adaptiveScalesEnabled, flowLinesRenderingMode, clusteringEnabled, clusteringLevel, fadeEnabled, fadeOpacityEnabled, clusteringAuto, darkMode, fadeAmount, colorScheme, highlightColor, maxTopFlowsDisplayNum, flowEndpointsInViewportMode, } = props; ++ const { locationsEnabled, locationTotalsEnabled, locationLabelsEnabled, adaptiveScalesEnabled, flowLinesRenderingMode, clusteringEnabled, clusteringLevel, fadeEnabled, fadeOpacityEnabled, clusteringAuto, darkMode, fadeAmount, colorScheme, highlightColor, temporalScaleDomain, maxTopFlowsDisplayNum, flowEndpointsInViewportMode, } = props; + return { + locationsEnabled: locationsEnabled ?? defaults.locationsEnabled, + locationTotalsEnabled: locationTotalsEnabled ?? defaults.locationTotalsEnabled, +@@ -187,6 +188,7 @@ class FlowmapLayer extends CompositeLayer { + fadeAmount: fadeAmount ?? defaults.fadeAmount, + colorScheme, + highlightColor: highlightColor ?? defaults.highlightColor, ++ temporalScaleDomain: temporalScaleDomain ?? defaults.temporalScaleDomain, + maxTopFlowsDisplayNum: maxTopFlowsDisplayNum ?? defaults.maxTopFlowsDisplayNum, + flowEndpointsInViewportMode: (flowEndpointsInViewportMode ?? + defaults.flowEndpointsInViewportMode), +@@ -490,6 +492,7 @@ FlowmapLayer.defaultProps = { + clusteringAuto: true, + clusteringLevel: undefined, + adaptiveScalesEnabled: true, ++ temporalScaleDomain: 'selected', + flowLineThicknessScale: 1, + flowLineCurviness: 1, + colorScheme: 'Teal', diff --git a/data-raw/flowmap-vendor/scripts/generate-vendor-metadata.mjs b/data-raw/flowmap-vendor/scripts/generate-vendor-metadata.mjs new file mode 100644 index 0000000..0ad3754 --- /dev/null +++ b/data-raw/flowmap-vendor/scripts/generate-vendor-metadata.mjs @@ -0,0 +1,234 @@ +import {createHash} from 'node:crypto'; +import {access, readdir, readFile, writeFile} from 'node:fs/promises'; +import {execFileSync} from 'node:child_process'; +import path from 'node:path'; +import {fileURLToPath} from 'node:url'; + +const outputDir = process.argv[2]; +const licenseNotePath = process.argv[3]; + +if (!outputDir || !licenseNotePath) { + throw new Error( + 'Usage: node scripts/generate-vendor-metadata.mjs ' + ); +} + +const vendorDir = fileURLToPath(new URL('../', import.meta.url)); +const lockPath = path.join(vendorDir, 'package-lock.json'); +const packagePath = path.join(vendorDir, 'package.json'); +const patchesDir = path.join(vendorDir, 'patches'); +const bundleName = 'flowmap-gl-bundle.min.js'; +const manifestName = 'flowmap-gl-vendor-manifest.json'; +const additionalBundledPackages = [ + { + name: 'd3', + version: '7.9.0', + license: 'ISC', + repository: 'https://github.com/d3/d3.git' + }, + { + name: 'lil-gui', + version: '0.19.0', + license: 'MIT', + repository: 'https://github.com/georgealways/lil-gui' + } +]; +const patchPurposes = { + 'patches/flowmap-temporal-scale-domain.patch': + 'Add temporalScaleDomain so temporal flow width/color domains can use selected-time or all-time flows.' +}; + +const [lock, packageJson, bundle] = await Promise.all([ + readJson(lockPath), + readJson(packagePath), + readFile(path.join(outputDir, bundleName)) +]); +const colorSchemes = extractColorSchemes(bundle.toString('utf8')); +const patchMetadata = await getPatchMetadata(); + +const declaredDependencies = packageJson.dependencies; +const packages = await Promise.all( + Object.entries(lock.packages) + .filter(([packagePath]) => packagePath.startsWith('node_modules/')) + .map(async ([packagePath, metadata]) => { + const name = packagePath.replace(/^node_modules\//, ''); + const packageJsonPath = path.join(vendorDir, packagePath, 'package.json'); + if (!(await exists(packageJsonPath))) { + return null; + } + + const packageJson = await readJson(packageJsonPath); + return { + name, + version: metadata.version, + license: packageJson.license ?? packageJson.licenses ?? metadata.license ?? null, + integrity: metadata.integrity ?? null, + resolved: metadata.resolved ?? null, + gitHead: packageJson.gitHead ?? null, + homepage: packageJson.homepage ?? null, + repository: normalizeRepository(packageJson.repository) + }; + }) +); + +const installedPackages = packages.filter((pkg) => pkg !== null); +installedPackages.sort((a, b) => a.name.localeCompare(b.name)); + +const directPackages = Object.keys(declaredDependencies) + .sort() + .map((name) => { + const metadata = installedPackages.find((pkg) => pkg.name === name); + if (!metadata) { + throw new Error(`Missing lockfile metadata for ${name}`); + } + return metadata; + }); + +const manifest = { + schemaVersion: 1, + source: 'npm release packages', + build: { + command: 'data-raw/flowmap-vendor/build-flowmap.sh build', + node: execFileSync('node', ['--version'], {encoding: 'utf8'}).trim(), + npm: execFileSync('npm', ['--version'], {encoding: 'utf8'}).trim(), + esbuild: declaredDependencies.esbuild + }, + bundle: { + path: 'inst/htmlwidgets/lib/flowmap-gl/flowmap-gl-bundle.min.js', + sha256: createHash('sha256').update(bundle).digest('hex'), + bytes: bundle.byteLength + }, + patches: patchMetadata, + copyrights: { + path: 'LICENSE.note' + }, + colorSchemes: { + source: 'FlowMapGL 9.3.0 vendored bundle', + names: colorSchemes + }, + directDependencies: directPackages, + transitiveDependencies: installedPackages.filter( + (pkg) => !Object.hasOwn(declaredDependencies, pkg.name) + ) +}; + +await writeFile( + path.join(outputDir, manifestName), + `${JSON.stringify(manifest, null, 2)}\n` +); + +await writeFile(licenseNotePath, renderLicenseNote(installedPackages)); + +async function readJson(file) { + return JSON.parse(await readFile(file, 'utf8')); +} + +async function exists(file) { + try { + await access(file); + return true; + } catch { + return false; + } +} + +async function getPatchMetadata() { + if (!(await exists(patchesDir))) { + return []; + } + + const patchNames = (await readdir(patchesDir)) + .filter((name) => name.endsWith('.patch')) + .sort(); + + return Promise.all( + patchNames.map(async (name) => { + const patchPath = path.join(patchesDir, name); + const contents = await readFile(patchPath); + const relativePath = `data-raw/flowmap-vendor/patches/${name}`; + const purposeKey = `patches/${name}`; + return { + path: relativePath, + sha256: createHash('sha256').update(contents).digest('hex'), + bytes: contents.byteLength, + purpose: patchPurposes[purposeKey] ?? '' + }; + }) + ); +} + +function normalizeRepository(repository) { + if (!repository) { + return null; + } + + if (typeof repository === 'string') { + return repository; + } + + return repository.url ?? null; +} + +function extractColorSchemes(bundle) { + const match = bundle.match( + /(?:^|[;,])[$A-Z_a-z][\w$]*=\{(Blues:[\s\S]*?YlOrRd:[^}]+?)\},[$A-Z_a-z][\w$]*=Object\.keys\(/ + ); + + if (!match) { + throw new Error('Could not find FlowMapGL color schemes in the bundle'); + } + + const names = [...match[1].matchAll(/([A-Za-z][A-Za-z0-9]*):/g)].map( + (scheme) => scheme[1] + ); + + for (const required of ['Blues', 'Teal', 'Viridis', 'YlOrRd']) { + if (!names.includes(required)) { + throw new Error(`Missing expected FlowMapGL color scheme: ${required}`); + } + } + + return names; +} + +function renderLicenseNote(packages) { + return [ + 'This package as a whole is licensed under the MIT License (see LICENSE file).', + '', + 'It bundles several third-party JavaScript components. The FlowmapGL browser bundle shipped at `inst/htmlwidgets/lib/flowmap-gl/flowmap-gl-bundle.min.js` is generated from npm release packages by `data-raw/flowmap-vendor/build-flowmap.sh build`.', + '', + 'Below are the licenses of the individual bundled components:', + '', + '| Package | Version | License | Source |', + '| --- | --- | --- | --- |', + ...renderCopyrightRows(packages), + '' + ].join('\n'); +} + +function renderCopyrightRows(packages) { + const allPackages = [...packages, ...additionalBundledPackages]; + allPackages.sort((a, b) => a.name.localeCompare(b.name)); + + return allPackages.map((pkg) => { + const license = renderLicense(pkg.license); + const source = pkg.repository ?? pkg.homepage ?? pkg.resolved ?? ''; + return `| ${pkg.name} | ${pkg.version} | ${license} | ${source} |`; + }); +} + +function renderLicense(license) { + if (!license) { + return ''; + } + + if (typeof license === 'string') { + return license; + } + + if (Array.isArray(license)) { + return license.map(renderLicense).join(', '); + } + + return license.type ?? JSON.stringify(license); +} diff --git a/data-raw/get-d3.R b/data-raw/get-d3.R new file mode 100644 index 0000000..96c507d --- /dev/null +++ b/data-raw/get-d3.R @@ -0,0 +1,6 @@ +# Download D3.js assets for the Time Control +dir.create("inst/htmlwidgets/lib/d3", recursive = TRUE, showWarnings = FALSE) +download.file( + "https://cdn.jsdelivr.net/npm/d3@7.9.0/dist/d3.min.js", + destfile = "inst/htmlwidgets/lib/d3/d3.min.js" +) diff --git a/data-raw/get-maplibre.R b/data-raw/get-maplibre.R index 7ab53f3..ef916ef 100644 --- a/data-raw/get-maplibre.R +++ b/data-raw/get-maplibre.R @@ -55,7 +55,7 @@ download.file( destfile = "inst/htmlwidgets/lib/maptiler-geocoding-control/maplibregl.umd.js" ) download.file( - "https://unpkg.com/@maptiler/geocoding-control@2.1.7/style.css", + "https://unpkg.com/@maptiler/geocoding-control@2.1.7/style.css", destfile = "inst/htmlwidgets/lib/maptiler-geocoding-control/style.css" ) diff --git a/data-raw/get-tuner.R b/data-raw/get-tuner.R new file mode 100644 index 0000000..c68818d --- /dev/null +++ b/data-raw/get-tuner.R @@ -0,0 +1,10 @@ +# Download lil-gui assets for the layer tuner +dir.create( + "inst/htmlwidgets/lib/lil-gui", + recursive = TRUE, + showWarnings = FALSE +) +download.file( + "https://cdn.jsdelivr.net/npm/lil-gui@0.19/dist/lil-gui.umd.min.js", + destfile = "inst/htmlwidgets/lib/lil-gui/lil-gui.umd.min.js" +) diff --git a/data-raw/prepare-bixi-dataset.R b/data-raw/prepare-bixi-dataset.R new file mode 100644 index 0000000..ece1c77 --- /dev/null +++ b/data-raw/prepare-bixi-dataset.R @@ -0,0 +1,59 @@ +# data-raw/prepare-bixi-dataset.R +# Script to prepare the BIXI Montréal 2019 example dataset for the mapgl package. +# Downloads the data directly from the public Google Sheet provided by the user, +# cleans IDs and coordinates, and filters out low flows (minimum 3 trips, count > 2) to minimize footprint. + +library(readxl) +library(usethis) + +# 1. Sheet Details & Download +sheet_id <- "1qTVOzkPB7U1ySI4g4uPtVBzzEDCI8n1WXAmQeZL15fE" +xlsx_url <- paste0("https://docs.google.com/spreadsheets/d/", sheet_id, "/export?format=xlsx") + +tmp_xlsx <- tempfile(fileext = ".xlsx") +message("Downloading BIXI Montréal Google Sheet as Excel workbook...") +download.file(xlsx_url, tmp_xlsx, mode = "wb", quiet = TRUE) +message("Download complete!") + +# 2. Read Raw Sheets +locations_raw <- read_excel(tmp_xlsx, sheet = "locations") +flows_raw <- read_excel(tmp_xlsx, sheet = "flows") +unlink(tmp_xlsx) + +# Helper function to clean Excel float-like ID formatting (e.g. "4000.0" -> "4000") +clean_id <- function(x) { + num_val <- suppressWarnings(as.numeric(x)) + ifelse(!is.na(num_val) & num_val == floor(num_val), as.character(as.integer(num_val)), x) +} + +# 3. Clean Locations +message("Cleaning locations dataset...") +bixi_locations <- as.data.frame(locations_raw) +bixi_locations$id <- clean_id(bixi_locations$id) + +# 4. Clean Flows, Filter for Low Flows (count > 2), and Optimize Types +message("Cleaning and optimizing flows dataset (filtering for count > 2 to minimize package footprint)...") +bixi_flows <- as.data.frame(flows_raw) +bixi_flows$origin <- clean_id(bixi_flows$origin) +bixi_flows$dest <- clean_id(bixi_flows$dest) +bixi_flows$count <- as.integer(bixi_flows$count) + +# Clean matching (only keep flows that correspond to valid locations) +bixi_flows <- bixi_flows[bixi_flows$origin %in% bixi_locations$id & bixi_flows$dest %in% bixi_locations$id, ] + +# Filter count > 2 (retaining minimum 3 trips in an hour) +bixi_flows <- bixi_flows[bixi_flows$count > 2, ] + +# Convert origin/dest to factor types matching locations$id for optimal serialization and memory +bixi_flows$origin <- factor(bixi_flows$origin, levels = bixi_locations$id) +bixi_flows$dest <- factor(bixi_flows$dest, levels = bixi_locations$id) + +# 5. Save and Package +message("Packaging datasets into the package data/ folder using xz compression...") +usethis::use_data(bixi_locations, overwrite = TRUE, compress = "xz") +usethis::use_data(bixi_flows, overwrite = TRUE, compress = "xz") + +message("Data preparation and packaging completed successfully!") +message(" - bixi_locations: ", nrow(bixi_locations), " stations") +message(" - bixi_flows: ", nrow(bixi_flows), " flow paths (count > 2)") + diff --git a/data/bixi_flows.rda b/data/bixi_flows.rda new file mode 100644 index 0000000..000926d Binary files /dev/null and b/data/bixi_flows.rda differ diff --git a/data/bixi_locations.rda b/data/bixi_locations.rda new file mode 100644 index 0000000..8c05f64 Binary files /dev/null and b/data/bixi_locations.rda differ diff --git a/inst/htmlwidgets/flowmap.css b/inst/htmlwidgets/flowmap.css new file mode 100644 index 0000000..451a582 --- /dev/null +++ b/inst/htmlwidgets/flowmap.css @@ -0,0 +1,53 @@ +.mapgl-flowmap-tooltip.mapboxgl-popup .mapboxgl-popup-content, +.mapgl-flowmap-tooltip.maplibregl-popup .maplibregl-popup-content { + font-family: + -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, + Cantarell, "Helvetica Neue", Arial, sans-serif; + font-size: 12px; + line-height: 1.35; +} + +.mapgl-flowmap-tooltip--dark.mapboxgl-popup .mapboxgl-popup-content, +.mapgl-flowmap-tooltip--dark.maplibregl-popup .maplibregl-popup-content { + background: rgba(35, 35, 35, 0.94); + color: #fff; +} + +.mapgl-flowmap-tooltip--dark.mapboxgl-popup .mapboxgl-popup-tip, +.mapgl-flowmap-tooltip--dark.maplibregl-popup .maplibregl-popup-tip { + border-top-color: rgba(35, 35, 35, 0.94); + border-bottom-color: rgba(35, 35, 35, 0.94); +} + +.mapgl-flowmap-tooltip--light.mapboxgl-popup .mapboxgl-popup-content, +.mapgl-flowmap-tooltip--light.maplibregl-popup .maplibregl-popup-content { + background: rgba(255, 255, 255, 0.96); + color: #222; +} + +.mapgl-flowmap-example-tooltip { + position: absolute; + z-index: 5; + display: none; + max-width: 320px; + padding: 1em; + border-radius: 5px; + font-family: + -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, + Cantarell, "Helvetica Neue", Arial, sans-serif; + font-size: 10px; + line-height: 1.35; + pointer-events: none; +} + +.mapgl-flowmap-example-tooltip--dark { + background-color: rgba(150, 150, 150, 0.75); + color: #fff; +} + +.mapgl-flowmap-example-tooltip--light { + border: 1px solid rgba(0, 0, 0, 0.12); + background-color: rgba(255, 255, 255, 0.92); + color: #222; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.16); +} diff --git a/inst/htmlwidgets/flowmap.js b/inst/htmlwidgets/flowmap.js new file mode 100644 index 0000000..f15c0c1 --- /dev/null +++ b/inst/htmlwidgets/flowmap.js @@ -0,0 +1,1321 @@ +window.MapGLFlowmapPlugin = (function () { + const FLOWMAP_ATTRIBUTION_SELECTOR = + ".mapboxgl-ctrl-attrib-inner, .maplibregl-ctrl-attrib-inner"; + const FLOWMAP_ATTRIBUTION_LINK_SELECTOR = + 'a[data-mapgl-flowmap-attribution="true"]'; + const FLOWMAP_ATTRIBUTION_SEPARATOR_SELECTOR = + '[data-mapgl-flowmap-attribution-separator="true"]'; + const DEFAULT_LOCATION_TOOLTIP = + "{name}
Incoming trips: {totals.incomingCount}
Outgoing trips: {totals.outgoingCount}
Internal or round trips: {totals.internalCount}"; + const DEFAULT_FLOW_TOOLTIP = "{origin.id} -> {dest.id}
{count}"; + + function dataframeToRows(data, HTMLWidgets) { + if (!data || Array.isArray(data) || typeof data !== "object") { + return data; + } + + if (HTMLWidgets && typeof HTMLWidgets.dataframeToD3 === "function") { + return HTMLWidgets.dataframeToD3(data); + } + + return data; + } + + function attributionNodeHasContent(node) { + if (!node) { + return false; + } + + if ( + node.nodeType === 1 && + (node.matches(FLOWMAP_ATTRIBUTION_LINK_SELECTOR) || + node.matches(FLOWMAP_ATTRIBUTION_SEPARATOR_SELECTOR)) + ) { + return false; + } + + return node.textContent && node.textContent.trim() !== ""; + } + + function hasNativeAttributionContent(attributionInner) { + for (var i = 0; i < attributionInner.childNodes.length; i++) { + if (attributionNodeHasContent(attributionInner.childNodes[i])) { + return true; + } + } + + return false; + } + + function makeFlowmapAttributionLink() { + const link = document.createElement("a"); + link.href = "https://flowmap.gl/"; + link.target = "_blank"; + link.rel = "noopener noreferrer"; + link.setAttribute("data-mapgl-flowmap-attribution", "true"); + link.textContent = "Flowmap.gl"; + return link; + } + + function normalizeFlowmapAttributionLink(link) { + link.href = "https://flowmap.gl/"; + link.target = "_blank"; + link.rel = "noopener noreferrer"; + link.setAttribute("data-mapgl-flowmap-attribution", "true"); + link.textContent = "Flowmap.gl"; + } + + function ensureFlowmapAttribution(map) { + if (!map || typeof map.getContainer !== "function") { + return; + } + + const container = map.getContainer(); + if (!container || typeof container.querySelector !== "function") { + return; + } + + const attributionInner = container.querySelector( + FLOWMAP_ATTRIBUTION_SELECTOR + ); + if (!attributionInner) { + return; + } + + const existingLinks = attributionInner.querySelectorAll( + FLOWMAP_ATTRIBUTION_LINK_SELECTOR + ); + var link = existingLinks[0] || makeFlowmapAttributionLink(); + + normalizeFlowmapAttributionLink(link); + + for (var i = 1; i < existingLinks.length; i++) { + existingLinks[i].remove(); + } + + const separators = attributionInner.querySelectorAll( + FLOWMAP_ATTRIBUTION_SEPARATOR_SELECTOR + ); + for (var j = 0; j < separators.length; j++) { + separators[j].remove(); + } + + if (attributionInner.firstChild !== link) { + attributionInner.insertBefore(link, attributionInner.firstChild); + } + + if (hasNativeAttributionContent(attributionInner)) { + const separator = document.createElement("span"); + separator.setAttribute( + "data-mapgl-flowmap-attribution-separator", + "true" + ); + separator.textContent = " | "; + attributionInner.insertBefore(separator, link.nextSibling); + } + } + + function installFlowmapAttributionRefresh(map) { + if (!map || map._mapglFlowmapAttributionRefreshInstalled) { + return; + } + + var timer = null; + const refresh = function () { + if (timer) { + clearTimeout(timer); + } + timer = setTimeout(function () { + timer = null; + ensureFlowmapAttribution(map); + }, 50); + }; + + map._mapglFlowmapAttributionRefreshInstalled = true; + map._mapglFlowmapAttributionRefresh = refresh; + + map.on("styledata", refresh); + map.on("sourcedata", refresh); + map.on("idle", refresh); + map.once("remove", function () { + if (timer) { + clearTimeout(timer); + timer = null; + } + map.off("styledata", refresh); + map.off("sourcedata", refresh); + map.off("idle", refresh); + map._mapglFlowmapAttributionRefreshInstalled = false; + map._mapglFlowmapAttributionRefresh = null; + }); + + ensureFlowmapAttribution(map); + } + + function getTooltipStore(map) { + if (!map._mapglFlowmapTooltips) { + map._mapglFlowmapTooltips = {}; + } + return map._mapglFlowmapTooltips; + } + + function hideFlowmapTooltip(map, id) { + const store = getTooltipStore(map); + const tooltip = store[id]; + if (!tooltip) { + return; + } + if (tooltip.popup) { + tooltip.popup.remove(); + } + if (tooltip.element) { + tooltip.element.style.display = "none"; + } + } + + function hideAllFlowmapTooltips(map) { + const store = getTooltipStore(map); + Object.keys(store).forEach(function (id) { + hideFlowmapTooltip(map, id); + }); + } + + function hideOtherFlowmapTooltips(map, activeId) { + const store = getTooltipStore(map); + Object.keys(store).forEach(function (id) { + if (id !== activeId) { + hideFlowmapTooltip(map, id); + } + }); + } + + function getPopupConstructor() { + if (typeof mapboxgl !== "undefined" && mapboxgl.Popup) { + return mapboxgl.Popup; + } + if (typeof maplibregl !== "undefined" && maplibregl.Popup) { + return maplibregl.Popup; + } + return null; + } + + function escapeHTML(value) { + return String(value == null ? "" : value) + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """) + .replace(/'/g, "'"); + } + + function getPathValue(object, path) { + if (!object || !path) { + return undefined; + } + + return path.split(".").reduce(function (value, key) { + if (value == null) { + return undefined; + } + return value[key]; + }, object); + } + + function renderTooltipTemplate(template, object) { + return template.replace(/\{([^}]+)\}/g, function (match, path) { + const value = getPathValue(object, path.trim()); + return escapeHTML(value == null ? "" : value); + }); + } + + function getTooltipHTML(config, info, behavior) { + const interaction = config[behavior] || {}; + const object = info && info.object; + if (!object) { + return null; + } + + // Determine object type if missing + let objectType = object.type; + if (!objectType) { + if (object.lat != null && object.lon != null) { + objectType = "location"; + } else if (object.origin != null && object.dest != null) { + objectType = "flow"; + } + } + + if (!objectType) { + return null; + } + + const templateConfig = interaction[objectType]; + if (!templateConfig || templateConfig === false) { + return null; + } + + let template; + if (templateConfig.kind === "column") { + template = object[templateConfig.value] || ""; + } else { + if (templateConfig.value === true) { + template = objectType === "location" + ? DEFAULT_LOCATION_TOOLTIP + : DEFAULT_FLOW_TOOLTIP; + } else { + template = templateConfig.value; + } + } + + if (!template) { + return null; + } + + return renderTooltipTemplate(template, object); + } + + function getTooltipLngLat(map, info) { + if (info && info.lngLat) { + return info.lngLat; + } + if (info && Array.isArray(info.coordinate)) { + return info.coordinate; + } + + const object = info && info.object; + if (!object) { + return null; + } + + if (object.type === "location" && object.location) { + const location = object.location; + if (location.lon != null && location.lat != null) { + return [location.lon, location.lat]; + } + } + + if (object.type === "flow" && object.origin && object.dest) { + const origin = object.origin; + const dest = object.dest; + if ( + origin.lon != null && + origin.lat != null && + dest.lon != null && + dest.lat != null + ) { + return [(origin.lon + dest.lon) / 2, (origin.lat + dest.lat) / 2]; + } + } + + return null; + } + + function getTooltipPoint(map, info) { + if (info && Number.isFinite(info.x) && Number.isFinite(info.y)) { + return { x: info.x, y: info.y }; + } + + const lngLat = getTooltipLngLat(map, info); + if (lngLat && map && typeof map.project === "function") { + return map.project(lngLat); + } + + return null; + } + + function mergeClassName(base, extra) { + return extra ? base + " " + extra : base; + } + + function generateHash(str) { + let hash = 0; + for (let i = 0; i < str.length; i++) { + const char = str.charCodeAt(i); + hash = (hash << 5) - hash + char; + hash |= 0; + } + return Math.abs(hash).toString(36); + } + + function ensureCustomStyle(css, className) { + const selector = className || "mapgl-custom-" + generateHash(css); + const styleId = "style-" + selector; + if (!document.getElementById(styleId)) { + const style = document.createElement("style"); + style.id = styleId; + style.textContent = "." + selector + " { " + css + " }"; + document.head.appendChild(style); + } + return selector; + } + + function showInteractiveUI(map, config, info, behavior) { + const interaction = config[behavior]; + if (!interaction || !interaction.enabled) return; + + const html = getTooltipHTML(config, info, behavior); + if (!html) { + if (behavior === "tooltip") hideFlowmapTooltip(map, config.id); + return; + } + + const lngLat = getTooltipLngLat(map, info); + if (!lngLat) { + if (behavior === "tooltip") hideFlowmapTooltip(map, config.id); + return; + } + + // Dismiss existing interactions of other types if needed + if (behavior === "popup") { + hideFlowmapTooltip(map, config.id); + } + + const popupProps = interaction.popup_props || {}; + let className = [ + "mapgl-flowmap-tooltip", + "mapgl-flowmap-tooltip--" + (interaction.theme || "light"), + ].join(" "); + + if (interaction.style === "anchored") { + const Popup = getPopupConstructor(); + if (!Popup) return; + + if (popupProps.css) { + const customClass = ensureCustomStyle(popupProps.css, popupProps.className); + className = mergeClassName(className, customClass); + } else if (popupProps.className) { + className = mergeClassName(className, popupProps.className); + } + + const options = Object.assign( + { + closeButton: behavior === "popup", + closeOnClick: behavior === "popup" ? false : true, + maxWidth: "400px", + }, + popupProps, + { className: className } + ); + + const store = getTooltipStore(map); + if (!store[config.id]) store[config.id] = {}; + + const storeKey = behavior === "popup" ? "clickPopup" : "popup"; + + if (store[config.id][storeKey]) { + store[config.id][storeKey].remove(); + } + + store[config.id][storeKey] = new Popup(options) + .setLngLat(lngLat) + .setHTML(html) + .addTo(map); + + } else { + // Floating mode + const point = getTooltipPoint(map, info); + if (!point || !map || typeof map.getContainer !== "function") return; + + const store = getTooltipStore(map); + if (!store[config.id]) store[config.id] = {}; + + const storeKey = behavior === "popup" ? "clickElement" : "element"; + + if (!store[config.id][storeKey]) { + const element = document.createElement("div"); + element.style.position = "absolute"; + element.style.zIndex = "1000"; + map.getContainer().appendChild(element); + store[config.id][storeKey] = element; + } + + const element = store[config.id][storeKey]; + + // Use the example-tooltip classes for floating mode to get the background/border + let floatingClassName = [ + "mapgl-flowmap-example-tooltip", + "mapgl-flowmap-example-tooltip--" + (interaction.theme || "light"), + "flowmap-tooltip" + ].join(" "); + + if (popupProps.css) { + const customClass = ensureCustomStyle(popupProps.css, popupProps.className); + floatingClassName = mergeClassName(floatingClassName, customClass); + } else if (popupProps.className) { + floatingClassName = mergeClassName(floatingClassName, popupProps.className); + } + + element.className = floatingClassName; + element.innerHTML = html; + + const offset = getElementOffset(popupProps); + element.style.left = point.x + offset[0] + "px"; + element.style.top = point.y + offset[1] + "px"; + element.style.display = "block"; + element.style.pointerEvents = behavior === "popup" ? "auto" : "none"; + + if (behavior === "popup") { + // Delayed listener to avoid immediate dismissal from bubbling + setTimeout(() => { + const closeHandler = (e) => { + // Don't close if we clicked inside the popup element itself + if (element.contains(e.target)) return; + element.style.display = "none"; + map.off("click", closeHandler); + }; + map.on("click", closeHandler); + }, 100); + } + } + } + + function getElementOffset(options) { + const offset = options && options.offset; + if (Array.isArray(offset) && offset.length >= 2) { + return [Number(offset[0]) || 0, Number(offset[1]) || 0]; + } + if (typeof offset === "number") { + return [offset, offset]; + } + return [10, 10]; + } + + function ensureOverlay(map, interleaved, elId, settings) { + if (typeof FlowmapGL === "undefined") { + console.error("FlowmapGL is not loaded. Cannot add flowmap layers."); + return null; + } + + if (interleaved) { + // Interleaved mode (MapboxOverlay) for layer ordering (beforeId/slot) + if ( + map._mapglFlowmapOverlay && + map._mapglFlowmapOverlayInterleaved === true + ) { + return map._mapglFlowmapOverlay; + } + + // Cleanup standalone Deck if any + if (map._deckgl) { + try { + map._deckgl.finalize(); + } catch (e) {} + map._deckgl = null; + } + if (map._deckContainer) { + try { + map._deckContainer.remove(); + } catch (e) {} + map._deckContainer = null; + } + + if (map._mapglFlowmapOverlay) { + try { + map.removeControl(map._mapglFlowmapOverlay); + } catch (e) {} + } + + const overlay = new FlowmapGL.MapboxOverlay({ + interleaved: true, + layers: [], + }); + + map.addControl(overlay); + map._mapglFlowmapOverlay = overlay; + map._mapglFlowmapOverlayInterleaved = true; + + map.once("remove", function () { + map._mapglFlowmapOverlay = null; + map._mapglFlowmapLayers = []; + }); + + return overlay; + } else { + // Standalone mode: Create standalone Deck container to bypass nested control stacking context. + // This is crucial because CSS mix-blend-mode will not blend with sibling map canvas elements + // if nested deep inside Mapbox/MapLibre's .mapboxgl-control-container hierarchy. + if ( + map._deckgl && + map._mapglFlowmapOverlayInterleaved === false + ) { + // Update blending styles on the existing canvas during widget updates + // NOTE: blend must go on the canvas, not the container, to avoid + // stacking-context isolation that prevents cross-element blending. + const deckCanvas = map._deckCanvas; + if (deckCanvas) { + if (settings && settings.flowBlend) { + if (typeof settings.flowBlend === "string") { + deckCanvas.style.mixBlendMode = settings.flowBlend; + } else { + deckCanvas.style.mixBlendMode = settings.darkMode ? "screen" : "multiply"; + } + } else { + deckCanvas.style.mixBlendMode = ""; + } + } + return map._deckgl; + } + + // Cleanup MapboxOverlay if any + if (map._mapglFlowmapOverlay) { + try { + map.removeControl(map._mapglFlowmapOverlay); + } catch (e) {} + map._mapglFlowmapOverlay = null; + } + if (map._deckgl) { + try { + map._deckgl.finalize(); + } catch (e) {} + map._deckgl = null; + } + if (map._deckContainer) { + try { + map._deckContainer.remove(); + } catch (e) {} + map._deckContainer = null; + } + + const container = map.getContainer(); + + // Create overlay container div directly under map container (sibling of canvas container) + const deckContainer = document.createElement("div"); + deckContainer.id = "deck-container-" + elId; + deckContainer.style.cssText = "position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none;"; + container.appendChild(deckContainer); + + // Create standalone canvas + const deckCanvas = document.createElement("canvas"); + deckCanvas.id = "deck-canvas-" + elId; + deckCanvas.style.cssText = "width:100%;height:100%;"; + deckContainer.appendChild(deckCanvas); + + map._deckContainer = deckContainer; + map._deckCanvas = deckCanvas; + + const center = map.getCenter(); + const initialViewState = { + longitude: center.lng, + latitude: center.lat, + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing() + }; + + const deckInstance = new FlowmapGL.Deck({ + canvas: deckCanvas, + controller: false, // map controls the camera + _useDevicePixels: true, + initialViewState: initialViewState, + layers: [], + getTooltip: null, + pickingRadius: 5 + }); + + // Synchronize standalone Deck viewport state with map moves + const syncViewState = () => { + const center = map.getCenter(); + deckInstance.setProps({ + viewState: { + longitude: center.lng, + latitude: center.lat, + zoom: map.getZoom(), + pitch: map.getPitch(), + bearing: map.getBearing() + } + }); + }; + + map.on("move", syncViewState); + map.on("moveend", syncViewState); + syncViewState(); + + // Forward mouse events from Mapbox to standalone Deck for picking / hover tooltips. + // We manually delegate hover and click events to the deck.gl sublayers, which + // automatically propagates them up to the composite FlowmapLayer. This ensures + // that the composite layer's internal highlight state is updated synchronously, + // and its async picking info enrichment is executed before calling our custom handlers. + const onMapMouseMove = (e) => { + if (!deckInstance || !map._mapglFlowmapLayers || map._mapglFlowmapLayers.length === 0) return; + const { x, y } = e.point; + try { + const info = deckInstance.pickObject({ x, y, radius: 2 }); + map.getCanvas().style.cursor = info ? "pointer" : ""; + + if (info && info.layer) { + const event = { srcEvent: e.originalEvent || e }; + info.x = x; + info.y = y; + info.lngLat = e.lngLat; + if (e.lngLat) { + info.coordinate = [e.lngLat.lng, e.lngLat.lat]; + } + if (typeof info.layer.onHover === "function") { + info.layer.onHover(info, event); + } else if (info.layer.props && typeof info.layer.props.onHover === "function") { + info.layer.props.onHover(info, event); + } + } else { + hideAllFlowmapTooltips(map); + // Also notify active flowmap layers that hover has ended, to clear highlights + map._mapglFlowmapLayers.forEach((layer) => { + if (layer.props && typeof layer.props.onHover === "function") { + layer.props.onHover({ index: -1 }, {}); + } + }); + } + } catch (err) { + // Ignore deck.gl picking errors during init / rapid movement + } + }; + + const onMapClick = (e) => { + if (!deckInstance || !map._mapglFlowmapLayers || map._mapglFlowmapLayers.length === 0) return; + const { x, y } = e.point; + try { + const info = deckInstance.pickObject({ x, y, radius: 5 }); + if (info && info.layer) { + const event = { srcEvent: e.originalEvent || e }; + info.x = x; + info.y = y; + info.lngLat = e.lngLat; + if (e.lngLat) { + info.coordinate = [e.lngLat.lng, e.lngLat.lat]; + } + if (typeof info.layer.onClick === "function") { + info.layer.onClick(info, event); + } else if (info.layer.props && typeof info.layer.props.onClick === "function") { + info.layer.props.onClick(info, event); + } + } + } catch (err) { + // Ignore deck.gl picking errors + } + }; + + if (!map._hasDeckMoveListener) { + map.on("mousemove", onMapMouseMove); + map.on("click", onMapClick); + map.on("mouseout", function () { + hideAllFlowmapTooltips(map); + // Clear hover highlights on mouseout — directly update state to avoid async delay + let needsRedraw = false; + if (map._flowmapHoverTimers) { + Object.keys(map._flowmapHoverTimers).forEach(function(id) { + if (map._flowmapHoverTimers[id]) { + clearTimeout(map._flowmapHoverTimers[id]); + map._flowmapHoverTimers[id] = null; + } + }); + } + if (map._flowmapHoveredLocation) { + Object.keys(map._flowmapHoveredLocation).forEach(function(id) { + if (map._flowmapHoveredLocation[id] !== null) { + map._flowmapHoveredLocation[id] = null; + needsRedraw = true; + } + }); + } + if (needsRedraw) { + redrawFlowmaps(map, map._flowmapHTMLWidgets); + } + // Also notify via layer.props for any other listeners + if (map._mapglFlowmapLayers) { + map._mapglFlowmapLayers.forEach((layer) => { + if (layer.props && typeof layer.props.onHover === "function") { + layer.props.onHover({ index: -1 }, {}); + } + }); + } + }); + map._hasDeckMoveListener = true; + } + + map._deckgl = deckInstance; + map._mapglFlowmapOverlayInterleaved = false; + + // Apply CSS Blending directly to the canvas element. + // IMPORTANT: The container must NOT have a z-index (other than auto) + // because that creates a stacking context which isolates the canvas + // and prevents mix-blend-mode from blending with the underlying map. + if (settings && settings.flowBlend) { + if (typeof settings.flowBlend === "string") { + deckCanvas.style.mixBlendMode = settings.flowBlend; + } else { + deckCanvas.style.mixBlendMode = settings.darkMode ? "screen" : "multiply"; + } + } else { + deckCanvas.style.mixBlendMode = ""; + } + + map.once("remove", function () { + if (map._deckgl) { + try { + map._deckgl.finalize(); + } catch (e) {} + map._deckgl = null; + } + if (map._deckContainer) { + try { + map._deckContainer.remove(); + } catch (e) {} + map._deckContainer = null; + } + map._mapglFlowmapLayers = []; + hideAllFlowmapTooltips(map); + }); + + return deckInstance; + } + } + + function makeLayer(config, HTMLWidgets, map, customLocations, customFlows, customPickable) { + const settings = config.settings || {}; + + // Cache converted rows on the original config's data object (for the canonical id) + const canonicalId = config._canonicalId || config.id; + const canonical = map._flowmapsConfig && map._flowmapsConfig.find(function(c) { return c.id === canonicalId; }); + const dataTarget = canonical ? canonical.data : config.data; + + if (!dataTarget._locationsRows) { + dataTarget._locationsRows = dataframeToRows(dataTarget.locations, HTMLWidgets); + } + if (!dataTarget._flowsRows) { + dataTarget._flowsRows = dataframeToRows(dataTarget.flows, HTMLWidgets); + } + + const locations = customLocations !== undefined ? customLocations : dataTarget._locationsRows; + const flows = customFlows !== undefined ? customFlows : dataTarget._flowsRows; + const isPickable = customPickable !== undefined ? customPickable : true; + // When custom flows are provided we've already done the location filtering externally + const skipLocationFilter = customFlows !== undefined; + + const layerProps = { + id: config.id, + data: { + locations: locations, + flows: flows, + }, + beforeId: config.beforeId || undefined, + slot: config.slot || undefined, + pickable: isPickable, + visible: config.visibility !== "none", + opacity: settings.opacity == null ? 1 : settings.opacity, + colorScheme: settings.colorScheme, + darkMode: settings.darkMode, + fadeAmount: settings.fadeAmount, + highlightColor: settings.highlightColor, + locationsEnabled: settings.locationsEnabled, + locationTotalsEnabled: settings.locationTotalsEnabled, + locationLabelsEnabled: settings.locationLabelsEnabled, + flowLinesRenderingMode: settings.flowLinesRenderingMode, + flowLineThicknessScale: settings.flowLineThicknessScale == null ? 1 : settings.flowLineThicknessScale, + flowLineCurviness: settings.flowLineCurviness == null ? 1 : settings.flowLineCurviness, + clusteringEnabled: settings.clusteringEnabled, + clusteringAuto: settings.clusteringAuto, + clusteringLevel: settings.clusteringLevel === null ? undefined : settings.clusteringLevel, + fadeEnabled: settings.fadeEnabled, + fadeOpacityEnabled: settings.fadeOpacityEnabled, + adaptiveScalesEnabled: settings.adaptiveScalesEnabled, + temporalScaleDomain: settings.temporalScaleDomain || "selected", + maxTopFlowsDisplayNum: settings.maxTopFlowsDisplayNum, + flowEndpointsInViewportMode: settings.flowEndpointsInViewportMode, + getLocationId: function (location) { + return location.id; + }, + getLocationLat: function (location) { + return location.lat; + }, + getLocationLon: function (location) { + return location.lon; + }, + getLocationName: function (location) { + return location.name || location.id; + }, + getFlowOriginId: function (flow) { + return flow.origin; + }, + getFlowDestId: function (flow) { + return flow.dest; + }, + getFlowMagnitude: function (flow) { + return flow.count; + }, + }; + + if (settings.timeColumn) { + layerProps.getFlowTime = function (flow) { + return flow.time ? new Date(flow.time) : undefined; + }; + } + + if (settings.selectedTimeRange) { + layerProps.filter = { + ...layerProps.filter, + selectedTimeRange: [ + new Date(settings.selectedTimeRange[0]), + new Date(settings.selectedTimeRange[1]) + ] + }; + } + + if (settings.selectedTimeRanges) { + layerProps.filter = { + ...layerProps.filter, + selectedTimeRange: null, + selectedTimeRanges: normalizeTimeRanges(settings.selectedTimeRanges) + }; + } + + // Only apply location filter on the FlowmapLayer when we haven't pre-filtered externally. + // When customFlows is provided, the caller already filtered by selected locations. + if (!skipLocationFilter) { + let selectedLocs = settings.selectedLocations; + if (settings.clickToFilter && map._flowmapSelectedLocations && map._flowmapSelectedLocations[canonicalId]) { + selectedLocs = map._flowmapSelectedLocations[canonicalId]; + } + if (selectedLocs && selectedLocs.length > 0) { + layerProps.filter = { + ...layerProps.filter, + selectedLocations: selectedLocs + }; + } + } + + if (settings.locationFilterMode) { + layerProps.filter = { + ...layerProps.filter, + locationFilterMode: settings.locationFilterMode + }; + } + + // Only attach interactive handlers on the canonical (pickable) layer. + // The originalConfig is the root config from _flowmapsConfig for closures. + const originalConfig = (map._flowmapsConfig && map._flowmapsConfig.find(function(c) { return c.id === canonicalId; })) || config; + + const hasHoverHandler = (originalConfig.tooltip && originalConfig.tooltip.enabled) || settings.hoverToHighlight; + const hasClickHandler = (originalConfig.popup && originalConfig.popup.enabled) || settings.clickToFilter; + + if (isPickable && hasHoverHandler) { + layerProps.onHover = function (info) { + if (originalConfig.tooltip && originalConfig.tooltip.enabled) { + showInteractiveUI(map, originalConfig, info, "tooltip"); + } + if (settings.hoverToHighlight) { + handleHoverInteraction(map, originalConfig, info); + } + }; + } + + if (isPickable && hasClickHandler) { + layerProps.onClick = function (info) { + if (originalConfig.popup && originalConfig.popup.enabled) { + showInteractiveUI(map, originalConfig, info, "popup"); + } + if (settings.clickToFilter) { + handleClickInteraction(map, originalConfig, info); + } + }; + } + + return makeFlowmapLayer(layerProps); + } + + function makeFlowmapLayer(layerProps) { + const layer = new FlowmapGL.FlowmapLayer(layerProps); + layer._mapglOnHover = layerProps.onHover; + layer._mapglOnClick = layerProps.onClick; + return layer; + } + + function cloneFlowmapLayer(layer, props) { + const cloneProps = Object.assign({}, props); + + if (Object.prototype.hasOwnProperty.call(layer, "_mapglOnHover")) { + cloneProps.onHover = layer._mapglOnHover; + } + if (Object.prototype.hasOwnProperty.call(layer, "_mapglOnClick")) { + cloneProps.onClick = layer._mapglOnClick; + } + + const cloned = layer.clone(cloneProps); + cloned._mapglOnHover = layer._mapglOnHover; + cloned._mapglOnClick = layer._mapglOnClick; + return cloned; + } + + function init(map, x, el, HTMLWidgets) { + if (!x.flowmaps || x.flowmaps.length === 0) { + return; + } + + if (typeof FlowmapGL === "undefined" || !FlowmapGL.FlowmapLayer) { + console.error("FlowmapGL is not loaded. Cannot add flowmap layers."); + return; + } + + installFlowmapAttributionRefresh(map); + + const interleaved = x.flowmaps.some(function (flowmap) { + return Boolean(flowmap.beforeId || flowmap.slot); + }); + + var firstFlowmap = x.flowmaps[0]; + var settings = firstFlowmap.settings || {}; + + const overlay = ensureOverlay(map, interleaved, el.id, settings); + if (!overlay) { + return; + } + + // Initialize interaction state maps + if (!map._flowmapSelectedLocations) { + map._flowmapSelectedLocations = {}; + } + if (!map._flowmapHoveredLocation) { + map._flowmapHoveredLocation = {}; + } + if (!map._flowmapHoverTimers) { + map._flowmapHoverTimers = {}; + } + map._flowmapsConfig = x.flowmaps; + map._flowmapHTMLWidgets = HTMLWidgets; + + x.flowmaps.forEach(function (config) { + const id = config.id; + const cSettings = config.settings || {}; + if (map._flowmapSelectedLocations[id] === undefined) { + const initialLocs = cSettings.selectedLocations; + map._flowmapSelectedLocations[id] = Array.isArray(initialLocs) + ? [...initialLocs] + : (initialLocs ? [initialLocs] : []); + } + if (map._flowmapHoveredLocation[id] === undefined) { + map._flowmapHoveredLocation[id] = null; + } + if (map._flowmapHoverTimers[id] === undefined) { + map._flowmapHoverTimers[id] = null; + } + }); + + redrawFlowmaps(map, HTMLWidgets); + } + + function redrawFlowmaps(map, HTMLWidgets) { + if (!map._flowmapsConfig) return; + const HTMLWidgetsInstance = HTMLWidgets || map._flowmapHTMLWidgets; + const layers = []; + + map._flowmapsConfig.forEach(function (config) { + const id = config.id; + const settings = config.settings || {}; + const isVisible = config.visibility !== "none"; + + if (!isVisible) { + return; + } + + const hoverActive = settings.hoverToHighlight && map._flowmapHoveredLocation[id]; + + if (!config.data._locationsRows) { + config.data._locationsRows = dataframeToRows(config.data.locations, HTMLWidgetsInstance); + } + if (!config.data._flowsRows) { + config.data._flowsRows = dataframeToRows(config.data.flows, HTMLWidgetsInstance); + } + + let baseLocations = config.data._locationsRows; + let baseFlows = config.data._flowsRows; + + const selected = map._flowmapSelectedLocations[id] || []; + if (settings.clickToFilter && selected.length > 0) { + const selectedSet = new Set(selected.map(String)); + baseFlows = baseFlows.filter(function (flow) { + return selectedSet.has(String(flow.origin)) || selectedSet.has(String(flow.dest)); + }); + } + + if (hoverActive) { + const hovered = map._flowmapHoveredLocation[id]; + + // Build the full normal layer first, then clone it with dimmed opacity. + // Cloning reuses the FlowmapLayer's internal state and preserves handlers. + const layer = makeLayer(config, HTMLWidgetsInstance, map, baseLocations, baseFlows); + const dimOpacity = (settings.opacity == null ? 1.0 : settings.opacity) * 0.15; + const baseLayer = cloneFlowmapLayer(layer, { + id: id + "-dim", + opacity: dimOpacity, + pickable: true // Keep pickable so hover events pass through to handlers + }); + layers.push(baseLayer); + + let highlightFlows = []; + let highlightLocations = []; + const connectedLocationIds = new Set(); + + if (hovered.type === "location") { + const hoveredId = String(hovered.id); + connectedLocationIds.add(hoveredId); + highlightFlows = baseFlows.filter(function (flow) { + const isConnected = String(flow.origin) === hoveredId || String(flow.dest) === hoveredId; + if (isConnected) { + connectedLocationIds.add(String(flow.origin)); + connectedLocationIds.add(String(flow.dest)); + } + return isConnected; + }); + } else if (hovered.type === "flow") { + // For flow type, origin/dest IDs are in hovered.origin.id and hovered.dest.id + // (the picking info object has {type:'flow', flow:, origin:, dest:, count}) + const originId = hovered.origin ? String(hovered.origin.id) : null; + const destId = hovered.dest ? String(hovered.dest.id) : null; + if (originId && destId) { + connectedLocationIds.add(originId); + connectedLocationIds.add(destId); + highlightFlows = baseFlows.filter(function (flow) { + return String(flow.origin) === originId && String(flow.dest) === destId; + }); + } + } + + highlightLocations = baseLocations.filter(function (loc) { + return connectedLocationIds.has(String(loc.id)); + }); + + // Highlight overlay — not pickable so cursor passes through to dim base layer. + const hlLayerSettings = Object.assign({}, settings, { + opacity: settings.opacity == null ? 1.0 : settings.opacity, + clusteringEnabled: false // disable clustering so small highlight sets render correctly + }); + const highlightLayerConfig = { + _canonicalId: id, + id: id + "-highlight", + data: config.data, + settings: hlLayerSettings, + visibility: config.visibility, + beforeId: config.beforeId, + slot: config.slot, + tooltip: null, + popup: null, + }; + + const highlightLayer = makeLayer( + highlightLayerConfig, + HTMLWidgetsInstance, + map, + highlightLocations, + highlightFlows, + false // not pickable + ); + layers.push(highlightLayer); + } else { + const normalLayer = makeLayer(config, HTMLWidgetsInstance, map, baseLocations, baseFlows); + layers.push(normalLayer); + } + }); + + map._mapglFlowmapLayers = layers; + const overlay = map._mapglFlowmapOverlay || map._deckgl; + if (overlay) { + overlay.setProps({ layers: layers }); + } + } + + function handleHoverInteraction(map, config, info) { + const id = config.id; + const settings = config.settings || {}; + const hoveredObject = info && info.object; + + if (map._flowmapHoverTimers[id]) { + clearTimeout(map._flowmapHoverTimers[id]); + map._flowmapHoverTimers[id] = null; + } + + if (hoveredObject) { + const objectType = hoveredObject.type; // 'location' or 'flow' — set by FlowmapLayer + + if (objectType === "location" || objectType === "flow") { + const currentHovered = map._flowmapHoveredLocation[id]; + let isSame = false; + if (currentHovered && currentHovered.type === objectType) { + if (objectType === "location") { + isSame = String(currentHovered.id) === String(hoveredObject.id); + } else { + // For flows: use origin.id / dest.id from the enriched location objects + const curOrig = currentHovered.origin && String(currentHovered.origin.id); + const curDest = currentHovered.dest && String(currentHovered.dest.id); + const newOrig = hoveredObject.origin && String(hoveredObject.origin.id); + const newDest = hoveredObject.dest && String(hoveredObject.dest.id); + isSame = curOrig === newOrig && curDest === newDest; + } + } + + if (!isSame) { + const delay = settings.hoverHighlightDelay != null ? settings.hoverHighlightDelay : 500; + if (delay > 0) { + map._flowmapHoverTimers[id] = setTimeout(function () { + map._flowmapHoveredLocation[id] = hoveredObject; + map._flowmapHoverTimers[id] = null; + redrawFlowmaps(map, map._flowmapHTMLWidgets); + }, delay); + } else { + map._flowmapHoveredLocation[id] = hoveredObject; + redrawFlowmaps(map, map._flowmapHTMLWidgets); + } + } + return; + } + } + + // Mouse left the element — clear pending timer and reset highlight + if (map._flowmapHoveredLocation[id] !== null) { + map._flowmapHoveredLocation[id] = null; + redrawFlowmaps(map, map._flowmapHTMLWidgets); + } + } + + function handleClickInteraction(map, config, info) { + const id = config.id; + const clickedObject = info && info.object; + if (!clickedObject) { + return; + } + + const objectType = clickedObject.type; // 'location' or 'flow' + + if (objectType === "location") { + const locId = clickedObject.id; + const selected = map._flowmapSelectedLocations[id] || []; + const index = selected.indexOf(locId); + let newSelected; + if (index > -1) { + // Deselect + newSelected = selected.filter(function(s) { return s !== locId; }); + } else { + // Select — copy to avoid mutation + newSelected = selected.concat([locId]); + } + map._flowmapSelectedLocations[id] = newSelected; + // Clear hover highlight when selection changes + if (map._flowmapHoverTimers[id]) { + clearTimeout(map._flowmapHoverTimers[id]); + map._flowmapHoverTimers[id] = null; + } + map._flowmapHoveredLocation[id] = null; + redrawFlowmaps(map, map._flowmapHTMLWidgets); + } + } + + function hasLayer(map, id) { + // First check canonical config store (works even when hover replaces the layer id) + if (map && map._flowmapsConfig) { + return map._flowmapsConfig.some(function (c) { return c.id === id; }); + } + return Boolean( + map && + map._mapglFlowmapLayers && + map._mapglFlowmapLayers.some(function (layer) { + return layer.id === id; + }), + ); + } + + function getVisibility(map, id) { + if (!map._flowmapsConfig) return undefined; + const config = map._flowmapsConfig.find(function (c) { + return c.id === id; + }); + return config ? (config.visibility === "none" ? "none" : "visible") : undefined; + } + + function setVisibility(map, id, visibility) { + if (!map._flowmapsConfig) { + return false; + } + let found = false; + map._flowmapsConfig.forEach(function (config) { + if (config.id === id) { + config.visibility = visibility; + if (visibility === "none") { + hideFlowmapTooltip(map, id); + } + found = true; + } + }); + if (found) { + redrawFlowmaps(map, map._flowmapHTMLWidgets); + return true; + } + return false; + } + + function setFilter(map, id, filter) { + if (!map._flowmapsConfig) { + return false; + } + let found = false; + map._flowmapsConfig.forEach(function (config) { + if (config.id === id) { + if (!config.settings) { + config.settings = {}; + } + Object.assign(config.settings, filter); + + if (filter.selectedLocations) { + map._flowmapSelectedLocations[id] = filter.selectedLocations; + } + + found = true; + } + }); + if (found) { + redrawFlowmaps(map, map._flowmapHTMLWidgets); + return true; + } + return false; + } + + function normalizeTimeRanges(ranges) { + if (!Array.isArray(ranges)) { + return null; + } + + return ranges + .filter(function (range) { + return Array.isArray(range) && range.length === 2; + }) + .map(function (range) { + return [new Date(range[0]), new Date(range[1])]; + }); + } + + function setSettings(map, id, settings) { + if (!map._flowmapsConfig) { + return false; + } + let found = false; + map._flowmapsConfig.forEach(function (config) { + if (config.id === id) { + if (!config.settings) { + config.settings = {}; + } + Object.assign(config.settings, settings); + found = true; + } + }); + if (found) { + redrawFlowmaps(map, map._flowmapHTMLWidgets); + return true; + } + return false; + } + + return { + init: init, + hasLayer: hasLayer, + getVisibility: getVisibility, + setVisibility: setVisibility, + setFilter: setFilter, + setSettings: setSettings, + }; +})(); diff --git a/inst/htmlwidgets/lib/d3/d3.min.js b/inst/htmlwidgets/lib/d3/d3.min.js new file mode 100644 index 0000000..33bb880 --- /dev/null +++ b/inst/htmlwidgets/lib/d3/d3.min.js @@ -0,0 +1,2 @@ +// https://d3js.org v7.9.0 Copyright 2010-2023 Mike Bostock +!function(t,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n((t="undefined"!=typeof globalThis?globalThis:t||self).d3=t.d3||{})}(this,(function(t){"use strict";function n(t,n){return null==t||null==n?NaN:tn?1:t>=n?0:NaN}function e(t,n){return null==t||null==n?NaN:nt?1:n>=t?0:NaN}function r(t){let r,o,a;function u(t,n,e=0,i=t.length){if(e>>1;o(t[r],n)<0?e=r+1:i=r}while(en(t(e),r),a=(n,e)=>t(n)-e):(r=t===n||t===e?t:i,o=t,a=t),{left:u,center:function(t,n,e=0,r=t.length){const i=u(t,n,e,r-1);return i>e&&a(t[i-1],n)>-a(t[i],n)?i-1:i},right:function(t,n,e=0,i=t.length){if(e>>1;o(t[r],n)<=0?e=r+1:i=r}while(e{n(t,e,(r<<=2)+0,(i<<=2)+0,o<<=2),n(t,e,r+1,i+1,o),n(t,e,r+2,i+2,o),n(t,e,r+3,i+3,o)}}));function d(t){return function(n,e,r=e){if(!((e=+e)>=0))throw new RangeError("invalid rx");if(!((r=+r)>=0))throw new RangeError("invalid ry");let{data:i,width:o,height:a}=n;if(!((o=Math.floor(o))>=0))throw new RangeError("invalid width");if(!((a=Math.floor(void 0!==a?a:i.length/o))>=0))throw new RangeError("invalid height");if(!o||!a||!e&&!r)return n;const u=e&&t(e),c=r&&t(r),f=i.slice();return u&&c?(p(u,f,i,o,a),p(u,i,f,o,a),p(u,f,i,o,a),g(c,i,f,o,a),g(c,f,i,o,a),g(c,i,f,o,a)):u?(p(u,i,f,o,a),p(u,f,i,o,a),p(u,i,f,o,a)):c&&(g(c,i,f,o,a),g(c,f,i,o,a),g(c,i,f,o,a)),n}}function p(t,n,e,r,i){for(let o=0,a=r*i;o{if(!((o-=a)>=i))return;let u=t*r[i];const c=a*t;for(let t=i,n=i+c;t{if(!((a-=u)>=o))return;let c=n*i[o];const f=u*n,s=f+u;for(let t=o,n=o+f;t=n&&++e;else{let r=-1;for(let i of t)null!=(i=n(i,++r,t))&&(i=+i)>=i&&++e}return e}function _(t){return 0|t.length}function b(t){return!(t>0)}function m(t){return"object"!=typeof t||"length"in t?t:Array.from(t)}function x(t,n){let e,r=0,i=0,o=0;if(void 0===n)for(let n of t)null!=n&&(n=+n)>=n&&(e=n-i,i+=e/++r,o+=e*(n-i));else{let a=-1;for(let u of t)null!=(u=n(u,++a,t))&&(u=+u)>=u&&(e=u-i,i+=e/++r,o+=e*(u-i))}if(r>1)return o/(r-1)}function w(t,n){const e=x(t,n);return e?Math.sqrt(e):e}function M(t,n){let e,r;if(void 0===n)for(const n of t)null!=n&&(void 0===e?n>=n&&(e=r=n):(e>n&&(e=n),r=o&&(e=r=o):(e>o&&(e=o),r0){for(o=t[--i];i>0&&(n=o,e=t[--i],o=n+e,r=e-(o-n),!r););i>0&&(r<0&&t[i-1]<0||r>0&&t[i-1]>0)&&(e=2*r,n=o+e,e==n-o&&(o=n))}return o}}class InternMap extends Map{constructor(t,n=N){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:n}}),null!=t)for(const[n,e]of t)this.set(n,e)}get(t){return super.get(A(this,t))}has(t){return super.has(A(this,t))}set(t,n){return super.set(S(this,t),n)}delete(t){return super.delete(E(this,t))}}class InternSet extends Set{constructor(t,n=N){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:n}}),null!=t)for(const n of t)this.add(n)}has(t){return super.has(A(this,t))}add(t){return super.add(S(this,t))}delete(t){return super.delete(E(this,t))}}function A({_intern:t,_key:n},e){const r=n(e);return t.has(r)?t.get(r):e}function S({_intern:t,_key:n},e){const r=n(e);return t.has(r)?t.get(r):(t.set(r,e),e)}function E({_intern:t,_key:n},e){const r=n(e);return t.has(r)&&(e=t.get(r),t.delete(r)),e}function N(t){return null!==t&&"object"==typeof t?t.valueOf():t}function k(t){return t}function C(t,...n){return F(t,k,k,n)}function P(t,...n){return F(t,Array.from,k,n)}function z(t,n){for(let e=1,r=n.length;et.pop().map((([n,e])=>[...t,n,e]))));return t}function $(t,n,...e){return F(t,k,n,e)}function D(t,n,...e){return F(t,Array.from,n,e)}function R(t){if(1!==t.length)throw new Error("duplicate key");return t[0]}function F(t,n,e,r){return function t(i,o){if(o>=r.length)return e(i);const a=new InternMap,u=r[o++];let c=-1;for(const t of i){const n=u(t,++c,i),e=a.get(n);e?e.push(t):a.set(n,[t])}for(const[n,e]of a)a.set(n,t(e,o));return n(a)}(t,0)}function q(t,n){return Array.from(n,(n=>t[n]))}function U(t,...n){if("function"!=typeof t[Symbol.iterator])throw new TypeError("values is not iterable");t=Array.from(t);let[e]=n;if(e&&2!==e.length||n.length>1){const r=Uint32Array.from(t,((t,n)=>n));return n.length>1?(n=n.map((n=>t.map(n))),r.sort(((t,e)=>{for(const r of n){const n=O(r[t],r[e]);if(n)return n}}))):(e=t.map(e),r.sort(((t,n)=>O(e[t],e[n])))),q(t,r)}return t.sort(I(e))}function I(t=n){if(t===n)return O;if("function"!=typeof t)throw new TypeError("compare is not a function");return(n,e)=>{const r=t(n,e);return r||0===r?r:(0===t(e,e))-(0===t(n,n))}}function O(t,n){return(null==t||!(t>=t))-(null==n||!(n>=n))||(tn?1:0)}var B=Array.prototype.slice;function Y(t){return()=>t}const L=Math.sqrt(50),j=Math.sqrt(10),H=Math.sqrt(2);function X(t,n,e){const r=(n-t)/Math.max(0,e),i=Math.floor(Math.log10(r)),o=r/Math.pow(10,i),a=o>=L?10:o>=j?5:o>=H?2:1;let u,c,f;return i<0?(f=Math.pow(10,-i)/a,u=Math.round(t*f),c=Math.round(n*f),u/fn&&--c,f=-f):(f=Math.pow(10,i)*a,u=Math.round(t/f),c=Math.round(n/f),u*fn&&--c),c0))return[];if((t=+t)===(n=+n))return[t];const r=n=i))return[];const u=o-i+1,c=new Array(u);if(r)if(a<0)for(let t=0;t0?(t=Math.floor(t/i)*i,n=Math.ceil(n/i)*i):i<0&&(t=Math.ceil(t*i)/i,n=Math.floor(n*i)/i),r=i}}function K(t){return Math.max(1,Math.ceil(Math.log(v(t))/Math.LN2)+1)}function Q(){var t=k,n=M,e=K;function r(r){Array.isArray(r)||(r=Array.from(r));var i,o,a,u=r.length,c=new Array(u);for(i=0;i=h)if(t>=h&&n===M){const t=V(l,h,e);isFinite(t)&&(t>0?h=(Math.floor(h/t)+1)*t:t<0&&(h=(Math.ceil(h*-t)+1)/-t))}else d.pop()}for(var p=d.length,g=0,y=p;d[g]<=l;)++g;for(;d[y-1]>h;)--y;(g||y0?d[i-1]:l,v.x1=i0)for(i=0;i=n)&&(e=n);else{let r=-1;for(let i of t)null!=(i=n(i,++r,t))&&(e=i)&&(e=i)}return e}function tt(t,n){let e,r=-1,i=-1;if(void 0===n)for(const n of t)++i,null!=n&&(e=n)&&(e=n,r=i);else for(let o of t)null!=(o=n(o,++i,t))&&(e=o)&&(e=o,r=i);return r}function nt(t,n){let e;if(void 0===n)for(const n of t)null!=n&&(e>n||void 0===e&&n>=n)&&(e=n);else{let r=-1;for(let i of t)null!=(i=n(i,++r,t))&&(e>i||void 0===e&&i>=i)&&(e=i)}return e}function et(t,n){let e,r=-1,i=-1;if(void 0===n)for(const n of t)++i,null!=n&&(e>n||void 0===e&&n>=n)&&(e=n,r=i);else for(let o of t)null!=(o=n(o,++i,t))&&(e>o||void 0===e&&o>=o)&&(e=o,r=i);return r}function rt(t,n,e=0,r=1/0,i){if(n=Math.floor(n),e=Math.floor(Math.max(0,e)),r=Math.floor(Math.min(t.length-1,r)),!(e<=n&&n<=r))return t;for(i=void 0===i?O:I(i);r>e;){if(r-e>600){const o=r-e+1,a=n-e+1,u=Math.log(o),c=.5*Math.exp(2*u/3),f=.5*Math.sqrt(u*c*(o-c)/o)*(a-o/2<0?-1:1);rt(t,n,Math.max(e,Math.floor(n-a*c/o+f)),Math.min(r,Math.floor(n+(o-a)*c/o+f)),i)}const o=t[n];let a=e,u=r;for(it(t,e,n),i(t[r],o)>0&&it(t,e,r);a0;)--u}0===i(t[e],o)?it(t,e,u):(++u,it(t,u,r)),u<=n&&(e=u+1),n<=u&&(r=u-1)}return t}function it(t,n,e){const r=t[n];t[n]=t[e],t[e]=r}function ot(t,e=n){let r,i=!1;if(1===e.length){let o;for(const a of t){const t=e(a);(i?n(t,o)>0:0===n(t,t))&&(r=a,o=t,i=!0)}}else for(const n of t)(i?e(n,r)>0:0===e(n,n))&&(r=n,i=!0);return r}function at(t,n,e){if(t=Float64Array.from(function*(t,n){if(void 0===n)for(let n of t)null!=n&&(n=+n)>=n&&(yield n);else{let e=-1;for(let r of t)null!=(r=n(r,++e,t))&&(r=+r)>=r&&(yield r)}}(t,e)),(r=t.length)&&!isNaN(n=+n)){if(n<=0||r<2)return nt(t);if(n>=1)return J(t);var r,i=(r-1)*n,o=Math.floor(i),a=J(rt(t,o).subarray(0,o+1));return a+(nt(t.subarray(o+1))-a)*(i-o)}}function ut(t,n,e=o){if((r=t.length)&&!isNaN(n=+n)){if(n<=0||r<2)return+e(t[0],0,t);if(n>=1)return+e(t[r-1],r-1,t);var r,i=(r-1)*n,a=Math.floor(i),u=+e(t[a],a,t);return u+(+e(t[a+1],a+1,t)-u)*(i-a)}}function ct(t,n,e=o){if(!isNaN(n=+n)){if(r=Float64Array.from(t,((n,r)=>o(e(t[r],r,t)))),n<=0)return et(r);if(n>=1)return tt(r);var r,i=Uint32Array.from(t,((t,n)=>n)),a=r.length-1,u=Math.floor(a*n);return rt(i,u,0,a,((t,n)=>O(r[t],r[n]))),(u=ot(i.subarray(0,u+1),(t=>r[t])))>=0?u:-1}}function ft(t){return Array.from(function*(t){for(const n of t)yield*n}(t))}function st(t,n){return[t,n]}function lt(t,n,e){t=+t,n=+n,e=(i=arguments.length)<2?(n=t,t=0,1):i<3?1:+e;for(var r=-1,i=0|Math.max(0,Math.ceil((n-t)/e)),o=new Array(i);++r+t(n)}function kt(t,n){return n=Math.max(0,t.bandwidth()-2*n)/2,t.round()&&(n=Math.round(n)),e=>+t(e)+n}function Ct(){return!this.__axis}function Pt(t,n){var e=[],r=null,i=null,o=6,a=6,u=3,c="undefined"!=typeof window&&window.devicePixelRatio>1?0:.5,f=t===xt||t===Tt?-1:1,s=t===Tt||t===wt?"x":"y",l=t===xt||t===Mt?St:Et;function h(h){var d=null==r?n.ticks?n.ticks.apply(n,e):n.domain():r,p=null==i?n.tickFormat?n.tickFormat.apply(n,e):mt:i,g=Math.max(o,0)+u,y=n.range(),v=+y[0]+c,_=+y[y.length-1]+c,b=(n.bandwidth?kt:Nt)(n.copy(),c),m=h.selection?h.selection():h,x=m.selectAll(".domain").data([null]),w=m.selectAll(".tick").data(d,n).order(),M=w.exit(),T=w.enter().append("g").attr("class","tick"),A=w.select("line"),S=w.select("text");x=x.merge(x.enter().insert("path",".tick").attr("class","domain").attr("stroke","currentColor")),w=w.merge(T),A=A.merge(T.append("line").attr("stroke","currentColor").attr(s+"2",f*o)),S=S.merge(T.append("text").attr("fill","currentColor").attr(s,f*g).attr("dy",t===xt?"0em":t===Mt?"0.71em":"0.32em")),h!==m&&(x=x.transition(h),w=w.transition(h),A=A.transition(h),S=S.transition(h),M=M.transition(h).attr("opacity",At).attr("transform",(function(t){return isFinite(t=b(t))?l(t+c):this.getAttribute("transform")})),T.attr("opacity",At).attr("transform",(function(t){var n=this.parentNode.__axis;return l((n&&isFinite(n=n(t))?n:b(t))+c)}))),M.remove(),x.attr("d",t===Tt||t===wt?a?"M"+f*a+","+v+"H"+c+"V"+_+"H"+f*a:"M"+c+","+v+"V"+_:a?"M"+v+","+f*a+"V"+c+"H"+_+"V"+f*a:"M"+v+","+c+"H"+_),w.attr("opacity",1).attr("transform",(function(t){return l(b(t)+c)})),A.attr(s+"2",f*o),S.attr(s,f*g).text(p),m.filter(Ct).attr("fill","none").attr("font-size",10).attr("font-family","sans-serif").attr("text-anchor",t===wt?"start":t===Tt?"end":"middle"),m.each((function(){this.__axis=b}))}return h.scale=function(t){return arguments.length?(n=t,h):n},h.ticks=function(){return e=Array.from(arguments),h},h.tickArguments=function(t){return arguments.length?(e=null==t?[]:Array.from(t),h):e.slice()},h.tickValues=function(t){return arguments.length?(r=null==t?null:Array.from(t),h):r&&r.slice()},h.tickFormat=function(t){return arguments.length?(i=t,h):i},h.tickSize=function(t){return arguments.length?(o=a=+t,h):o},h.tickSizeInner=function(t){return arguments.length?(o=+t,h):o},h.tickSizeOuter=function(t){return arguments.length?(a=+t,h):a},h.tickPadding=function(t){return arguments.length?(u=+t,h):u},h.offset=function(t){return arguments.length?(c=+t,h):c},h}var zt={value:()=>{}};function $t(){for(var t,n=0,e=arguments.length,r={};n=0&&(n=t.slice(e+1),t=t.slice(0,e)),t&&!r.hasOwnProperty(t))throw new Error("unknown type: "+t);return{type:t,name:n}}))),a=-1,u=o.length;if(!(arguments.length<2)){if(null!=n&&"function"!=typeof n)throw new Error("invalid callback: "+n);for(;++a0)for(var e,r,i=new Array(e),o=0;o=0&&"xmlns"!==(n=t.slice(0,e))&&(t=t.slice(e+1)),Ut.hasOwnProperty(n)?{space:Ut[n],local:t}:t}function Ot(t){return function(){var n=this.ownerDocument,e=this.namespaceURI;return e===qt&&n.documentElement.namespaceURI===qt?n.createElement(t):n.createElementNS(e,t)}}function Bt(t){return function(){return this.ownerDocument.createElementNS(t.space,t.local)}}function Yt(t){var n=It(t);return(n.local?Bt:Ot)(n)}function Lt(){}function jt(t){return null==t?Lt:function(){return this.querySelector(t)}}function Ht(t){return null==t?[]:Array.isArray(t)?t:Array.from(t)}function Xt(){return[]}function Gt(t){return null==t?Xt:function(){return this.querySelectorAll(t)}}function Vt(t){return function(){return this.matches(t)}}function Wt(t){return function(n){return n.matches(t)}}var Zt=Array.prototype.find;function Kt(){return this.firstElementChild}var Qt=Array.prototype.filter;function Jt(){return Array.from(this.children)}function tn(t){return new Array(t.length)}function nn(t,n){this.ownerDocument=t.ownerDocument,this.namespaceURI=t.namespaceURI,this._next=null,this._parent=t,this.__data__=n}function en(t,n,e,r,i,o){for(var a,u=0,c=n.length,f=o.length;un?1:t>=n?0:NaN}function cn(t){return function(){this.removeAttribute(t)}}function fn(t){return function(){this.removeAttributeNS(t.space,t.local)}}function sn(t,n){return function(){this.setAttribute(t,n)}}function ln(t,n){return function(){this.setAttributeNS(t.space,t.local,n)}}function hn(t,n){return function(){var e=n.apply(this,arguments);null==e?this.removeAttribute(t):this.setAttribute(t,e)}}function dn(t,n){return function(){var e=n.apply(this,arguments);null==e?this.removeAttributeNS(t.space,t.local):this.setAttributeNS(t.space,t.local,e)}}function pn(t){return t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView}function gn(t){return function(){this.style.removeProperty(t)}}function yn(t,n,e){return function(){this.style.setProperty(t,n,e)}}function vn(t,n,e){return function(){var r=n.apply(this,arguments);null==r?this.style.removeProperty(t):this.style.setProperty(t,r,e)}}function _n(t,n){return t.style.getPropertyValue(n)||pn(t).getComputedStyle(t,null).getPropertyValue(n)}function bn(t){return function(){delete this[t]}}function mn(t,n){return function(){this[t]=n}}function xn(t,n){return function(){var e=n.apply(this,arguments);null==e?delete this[t]:this[t]=e}}function wn(t){return t.trim().split(/^|\s+/)}function Mn(t){return t.classList||new Tn(t)}function Tn(t){this._node=t,this._names=wn(t.getAttribute("class")||"")}function An(t,n){for(var e=Mn(t),r=-1,i=n.length;++r=0&&(this._names.splice(n,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(t){return this._names.indexOf(t)>=0}};var Gn=[null];function Vn(t,n){this._groups=t,this._parents=n}function Wn(){return new Vn([[document.documentElement]],Gn)}function Zn(t){return"string"==typeof t?new Vn([[document.querySelector(t)]],[document.documentElement]):new Vn([[t]],Gn)}Vn.prototype=Wn.prototype={constructor:Vn,select:function(t){"function"!=typeof t&&(t=jt(t));for(var n=this._groups,e=n.length,r=new Array(e),i=0;i=m&&(m=b+1);!(_=y[m])&&++m=0;)(r=i[o])&&(a&&4^r.compareDocumentPosition(a)&&a.parentNode.insertBefore(r,a),a=r);return this},sort:function(t){function n(n,e){return n&&e?t(n.__data__,e.__data__):!n-!e}t||(t=un);for(var e=this._groups,r=e.length,i=new Array(r),o=0;o1?this.each((null==n?gn:"function"==typeof n?vn:yn)(t,n,null==e?"":e)):_n(this.node(),t)},property:function(t,n){return arguments.length>1?this.each((null==n?bn:"function"==typeof n?xn:mn)(t,n)):this.node()[t]},classed:function(t,n){var e=wn(t+"");if(arguments.length<2){for(var r=Mn(this.node()),i=-1,o=e.length;++i=0&&(n=t.slice(e+1),t=t.slice(0,e)),{type:t,name:n}}))}(t+""),a=o.length;if(!(arguments.length<2)){for(u=n?Ln:Yn,r=0;r()=>t;function fe(t,{sourceEvent:n,subject:e,target:r,identifier:i,active:o,x:a,y:u,dx:c,dy:f,dispatch:s}){Object.defineProperties(this,{type:{value:t,enumerable:!0,configurable:!0},sourceEvent:{value:n,enumerable:!0,configurable:!0},subject:{value:e,enumerable:!0,configurable:!0},target:{value:r,enumerable:!0,configurable:!0},identifier:{value:i,enumerable:!0,configurable:!0},active:{value:o,enumerable:!0,configurable:!0},x:{value:a,enumerable:!0,configurable:!0},y:{value:u,enumerable:!0,configurable:!0},dx:{value:c,enumerable:!0,configurable:!0},dy:{value:f,enumerable:!0,configurable:!0},_:{value:s}})}function se(t){return!t.ctrlKey&&!t.button}function le(){return this.parentNode}function he(t,n){return null==n?{x:t.x,y:t.y}:n}function de(){return navigator.maxTouchPoints||"ontouchstart"in this}function pe(t,n,e){t.prototype=n.prototype=e,e.constructor=t}function ge(t,n){var e=Object.create(t.prototype);for(var r in n)e[r]=n[r];return e}function ye(){}fe.prototype.on=function(){var t=this._.on.apply(this._,arguments);return t===this._?this:t};var ve=.7,_e=1/ve,be="\\s*([+-]?\\d+)\\s*",me="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",xe="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",we=/^#([0-9a-f]{3,8})$/,Me=new RegExp(`^rgb\\(${be},${be},${be}\\)$`),Te=new RegExp(`^rgb\\(${xe},${xe},${xe}\\)$`),Ae=new RegExp(`^rgba\\(${be},${be},${be},${me}\\)$`),Se=new RegExp(`^rgba\\(${xe},${xe},${xe},${me}\\)$`),Ee=new RegExp(`^hsl\\(${me},${xe},${xe}\\)$`),Ne=new RegExp(`^hsla\\(${me},${xe},${xe},${me}\\)$`),ke={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};function Ce(){return this.rgb().formatHex()}function Pe(){return this.rgb().formatRgb()}function ze(t){var n,e;return t=(t+"").trim().toLowerCase(),(n=we.exec(t))?(e=n[1].length,n=parseInt(n[1],16),6===e?$e(n):3===e?new qe(n>>8&15|n>>4&240,n>>4&15|240&n,(15&n)<<4|15&n,1):8===e?De(n>>24&255,n>>16&255,n>>8&255,(255&n)/255):4===e?De(n>>12&15|n>>8&240,n>>8&15|n>>4&240,n>>4&15|240&n,((15&n)<<4|15&n)/255):null):(n=Me.exec(t))?new qe(n[1],n[2],n[3],1):(n=Te.exec(t))?new qe(255*n[1]/100,255*n[2]/100,255*n[3]/100,1):(n=Ae.exec(t))?De(n[1],n[2],n[3],n[4]):(n=Se.exec(t))?De(255*n[1]/100,255*n[2]/100,255*n[3]/100,n[4]):(n=Ee.exec(t))?Le(n[1],n[2]/100,n[3]/100,1):(n=Ne.exec(t))?Le(n[1],n[2]/100,n[3]/100,n[4]):ke.hasOwnProperty(t)?$e(ke[t]):"transparent"===t?new qe(NaN,NaN,NaN,0):null}function $e(t){return new qe(t>>16&255,t>>8&255,255&t,1)}function De(t,n,e,r){return r<=0&&(t=n=e=NaN),new qe(t,n,e,r)}function Re(t){return t instanceof ye||(t=ze(t)),t?new qe((t=t.rgb()).r,t.g,t.b,t.opacity):new qe}function Fe(t,n,e,r){return 1===arguments.length?Re(t):new qe(t,n,e,null==r?1:r)}function qe(t,n,e,r){this.r=+t,this.g=+n,this.b=+e,this.opacity=+r}function Ue(){return`#${Ye(this.r)}${Ye(this.g)}${Ye(this.b)}`}function Ie(){const t=Oe(this.opacity);return`${1===t?"rgb(":"rgba("}${Be(this.r)}, ${Be(this.g)}, ${Be(this.b)}${1===t?")":`, ${t})`}`}function Oe(t){return isNaN(t)?1:Math.max(0,Math.min(1,t))}function Be(t){return Math.max(0,Math.min(255,Math.round(t)||0))}function Ye(t){return((t=Be(t))<16?"0":"")+t.toString(16)}function Le(t,n,e,r){return r<=0?t=n=e=NaN:e<=0||e>=1?t=n=NaN:n<=0&&(t=NaN),new Xe(t,n,e,r)}function je(t){if(t instanceof Xe)return new Xe(t.h,t.s,t.l,t.opacity);if(t instanceof ye||(t=ze(t)),!t)return new Xe;if(t instanceof Xe)return t;var n=(t=t.rgb()).r/255,e=t.g/255,r=t.b/255,i=Math.min(n,e,r),o=Math.max(n,e,r),a=NaN,u=o-i,c=(o+i)/2;return u?(a=n===o?(e-r)/u+6*(e0&&c<1?0:a,new Xe(a,u,c,t.opacity)}function He(t,n,e,r){return 1===arguments.length?je(t):new Xe(t,n,e,null==r?1:r)}function Xe(t,n,e,r){this.h=+t,this.s=+n,this.l=+e,this.opacity=+r}function Ge(t){return(t=(t||0)%360)<0?t+360:t}function Ve(t){return Math.max(0,Math.min(1,t||0))}function We(t,n,e){return 255*(t<60?n+(e-n)*t/60:t<180?e:t<240?n+(e-n)*(240-t)/60:n)}pe(ye,ze,{copy(t){return Object.assign(new this.constructor,this,t)},displayable(){return this.rgb().displayable()},hex:Ce,formatHex:Ce,formatHex8:function(){return this.rgb().formatHex8()},formatHsl:function(){return je(this).formatHsl()},formatRgb:Pe,toString:Pe}),pe(qe,Fe,ge(ye,{brighter(t){return t=null==t?_e:Math.pow(_e,t),new qe(this.r*t,this.g*t,this.b*t,this.opacity)},darker(t){return t=null==t?ve:Math.pow(ve,t),new qe(this.r*t,this.g*t,this.b*t,this.opacity)},rgb(){return this},clamp(){return new qe(Be(this.r),Be(this.g),Be(this.b),Oe(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:Ue,formatHex:Ue,formatHex8:function(){return`#${Ye(this.r)}${Ye(this.g)}${Ye(this.b)}${Ye(255*(isNaN(this.opacity)?1:this.opacity))}`},formatRgb:Ie,toString:Ie})),pe(Xe,He,ge(ye,{brighter(t){return t=null==t?_e:Math.pow(_e,t),new Xe(this.h,this.s,this.l*t,this.opacity)},darker(t){return t=null==t?ve:Math.pow(ve,t),new Xe(this.h,this.s,this.l*t,this.opacity)},rgb(){var t=this.h%360+360*(this.h<0),n=isNaN(t)||isNaN(this.s)?0:this.s,e=this.l,r=e+(e<.5?e:1-e)*n,i=2*e-r;return new qe(We(t>=240?t-240:t+120,i,r),We(t,i,r),We(t<120?t+240:t-120,i,r),this.opacity)},clamp(){return new Xe(Ge(this.h),Ve(this.s),Ve(this.l),Oe(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const t=Oe(this.opacity);return`${1===t?"hsl(":"hsla("}${Ge(this.h)}, ${100*Ve(this.s)}%, ${100*Ve(this.l)}%${1===t?")":`, ${t})`}`}}));const Ze=Math.PI/180,Ke=180/Math.PI,Qe=.96422,Je=1,tr=.82521,nr=4/29,er=6/29,rr=3*er*er,ir=er*er*er;function or(t){if(t instanceof ur)return new ur(t.l,t.a,t.b,t.opacity);if(t instanceof pr)return gr(t);t instanceof qe||(t=Re(t));var n,e,r=lr(t.r),i=lr(t.g),o=lr(t.b),a=cr((.2225045*r+.7168786*i+.0606169*o)/Je);return r===i&&i===o?n=e=a:(n=cr((.4360747*r+.3850649*i+.1430804*o)/Qe),e=cr((.0139322*r+.0971045*i+.7141733*o)/tr)),new ur(116*a-16,500*(n-a),200*(a-e),t.opacity)}function ar(t,n,e,r){return 1===arguments.length?or(t):new ur(t,n,e,null==r?1:r)}function ur(t,n,e,r){this.l=+t,this.a=+n,this.b=+e,this.opacity=+r}function cr(t){return t>ir?Math.pow(t,1/3):t/rr+nr}function fr(t){return t>er?t*t*t:rr*(t-nr)}function sr(t){return 255*(t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055)}function lr(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function hr(t){if(t instanceof pr)return new pr(t.h,t.c,t.l,t.opacity);if(t instanceof ur||(t=or(t)),0===t.a&&0===t.b)return new pr(NaN,0=1?(e=1,n-1):Math.floor(e*n),i=t[r],o=t[r+1],a=r>0?t[r-1]:2*i-o,u=r()=>t;function Cr(t,n){return function(e){return t+e*n}}function Pr(t,n){var e=n-t;return e?Cr(t,e>180||e<-180?e-360*Math.round(e/360):e):kr(isNaN(t)?n:t)}function zr(t){return 1==(t=+t)?$r:function(n,e){return e-n?function(t,n,e){return t=Math.pow(t,e),n=Math.pow(n,e)-t,e=1/e,function(r){return Math.pow(t+r*n,e)}}(n,e,t):kr(isNaN(n)?e:n)}}function $r(t,n){var e=n-t;return e?Cr(t,e):kr(isNaN(t)?n:t)}var Dr=function t(n){var e=zr(n);function r(t,n){var r=e((t=Fe(t)).r,(n=Fe(n)).r),i=e(t.g,n.g),o=e(t.b,n.b),a=$r(t.opacity,n.opacity);return function(n){return t.r=r(n),t.g=i(n),t.b=o(n),t.opacity=a(n),t+""}}return r.gamma=t,r}(1);function Rr(t){return function(n){var e,r,i=n.length,o=new Array(i),a=new Array(i),u=new Array(i);for(e=0;eo&&(i=n.slice(o,i),u[a]?u[a]+=i:u[++a]=i),(e=e[0])===(r=r[0])?u[a]?u[a]+=r:u[++a]=r:(u[++a]=null,c.push({i:a,x:Yr(e,r)})),o=Hr.lastIndex;return o180?n+=360:n-t>180&&(t+=360),o.push({i:e.push(i(e)+"rotate(",null,r)-2,x:Yr(t,n)})):n&&e.push(i(e)+"rotate("+n+r)}(o.rotate,a.rotate,u,c),function(t,n,e,o){t!==n?o.push({i:e.push(i(e)+"skewX(",null,r)-2,x:Yr(t,n)}):n&&e.push(i(e)+"skewX("+n+r)}(o.skewX,a.skewX,u,c),function(t,n,e,r,o,a){if(t!==e||n!==r){var u=o.push(i(o)+"scale(",null,",",null,")");a.push({i:u-4,x:Yr(t,e)},{i:u-2,x:Yr(n,r)})}else 1===e&&1===r||o.push(i(o)+"scale("+e+","+r+")")}(o.scaleX,o.scaleY,a.scaleX,a.scaleY,u,c),o=a=null,function(t){for(var n,e=-1,r=c.length;++e=0&&n._call.call(void 0,t),n=n._next;--yi}function Ci(){xi=(mi=Mi.now())+wi,yi=vi=0;try{ki()}finally{yi=0,function(){var t,n,e=pi,r=1/0;for(;e;)e._call?(r>e._time&&(r=e._time),t=e,e=e._next):(n=e._next,e._next=null,e=t?t._next=n:pi=n);gi=t,zi(r)}(),xi=0}}function Pi(){var t=Mi.now(),n=t-mi;n>bi&&(wi-=n,mi=t)}function zi(t){yi||(vi&&(vi=clearTimeout(vi)),t-xi>24?(t<1/0&&(vi=setTimeout(Ci,t-Mi.now()-wi)),_i&&(_i=clearInterval(_i))):(_i||(mi=Mi.now(),_i=setInterval(Pi,bi)),yi=1,Ti(Ci)))}function $i(t,n,e){var r=new Ei;return n=null==n?0:+n,r.restart((e=>{r.stop(),t(e+n)}),n,e),r}Ei.prototype=Ni.prototype={constructor:Ei,restart:function(t,n,e){if("function"!=typeof t)throw new TypeError("callback is not a function");e=(null==e?Ai():+e)+(null==n?0:+n),this._next||gi===this||(gi?gi._next=this:pi=this,gi=this),this._call=t,this._time=e,zi()},stop:function(){this._call&&(this._call=null,this._time=1/0,zi())}};var Di=$t("start","end","cancel","interrupt"),Ri=[],Fi=0,qi=1,Ui=2,Ii=3,Oi=4,Bi=5,Yi=6;function Li(t,n,e,r,i,o){var a=t.__transition;if(a){if(e in a)return}else t.__transition={};!function(t,n,e){var r,i=t.__transition;function o(t){e.state=qi,e.timer.restart(a,e.delay,e.time),e.delay<=t&&a(t-e.delay)}function a(o){var f,s,l,h;if(e.state!==qi)return c();for(f in i)if((h=i[f]).name===e.name){if(h.state===Ii)return $i(a);h.state===Oi?(h.state=Yi,h.timer.stop(),h.on.call("interrupt",t,t.__data__,h.index,h.group),delete i[f]):+fFi)throw new Error("too late; already scheduled");return e}function Hi(t,n){var e=Xi(t,n);if(e.state>Ii)throw new Error("too late; already running");return e}function Xi(t,n){var e=t.__transition;if(!e||!(e=e[n]))throw new Error("transition not found");return e}function Gi(t,n){var e,r,i,o=t.__transition,a=!0;if(o){for(i in n=null==n?null:n+"",o)(e=o[i]).name===n?(r=e.state>Ui&&e.state=0&&(t=t.slice(0,n)),!t||"start"===t}))}(n)?ji:Hi;return function(){var a=o(this,t),u=a.on;u!==r&&(i=(r=u).copy()).on(n,e),a.on=i}}(e,t,n))},attr:function(t,n){var e=It(t),r="transform"===e?ni:Ki;return this.attrTween(t,"function"==typeof n?(e.local?ro:eo)(e,r,Zi(this,"attr."+t,n)):null==n?(e.local?Ji:Qi)(e):(e.local?no:to)(e,r,n))},attrTween:function(t,n){var e="attr."+t;if(arguments.length<2)return(e=this.tween(e))&&e._value;if(null==n)return this.tween(e,null);if("function"!=typeof n)throw new Error;var r=It(t);return this.tween(e,(r.local?io:oo)(r,n))},style:function(t,n,e){var r="transform"==(t+="")?ti:Ki;return null==n?this.styleTween(t,function(t,n){var e,r,i;return function(){var o=_n(this,t),a=(this.style.removeProperty(t),_n(this,t));return o===a?null:o===e&&a===r?i:i=n(e=o,r=a)}}(t,r)).on("end.style."+t,lo(t)):"function"==typeof n?this.styleTween(t,function(t,n,e){var r,i,o;return function(){var a=_n(this,t),u=e(this),c=u+"";return null==u&&(this.style.removeProperty(t),c=u=_n(this,t)),a===c?null:a===r&&c===i?o:(i=c,o=n(r=a,u))}}(t,r,Zi(this,"style."+t,n))).each(function(t,n){var e,r,i,o,a="style."+n,u="end."+a;return function(){var c=Hi(this,t),f=c.on,s=null==c.value[a]?o||(o=lo(n)):void 0;f===e&&i===s||(r=(e=f).copy()).on(u,i=s),c.on=r}}(this._id,t)):this.styleTween(t,function(t,n,e){var r,i,o=e+"";return function(){var a=_n(this,t);return a===o?null:a===r?i:i=n(r=a,e)}}(t,r,n),e).on("end.style."+t,null)},styleTween:function(t,n,e){var r="style."+(t+="");if(arguments.length<2)return(r=this.tween(r))&&r._value;if(null==n)return this.tween(r,null);if("function"!=typeof n)throw new Error;return this.tween(r,function(t,n,e){var r,i;function o(){var o=n.apply(this,arguments);return o!==i&&(r=(i=o)&&function(t,n,e){return function(r){this.style.setProperty(t,n.call(this,r),e)}}(t,o,e)),r}return o._value=n,o}(t,n,null==e?"":e))},text:function(t){return this.tween("text","function"==typeof t?function(t){return function(){var n=t(this);this.textContent=null==n?"":n}}(Zi(this,"text",t)):function(t){return function(){this.textContent=t}}(null==t?"":t+""))},textTween:function(t){var n="text";if(arguments.length<1)return(n=this.tween(n))&&n._value;if(null==t)return this.tween(n,null);if("function"!=typeof t)throw new Error;return this.tween(n,function(t){var n,e;function r(){var r=t.apply(this,arguments);return r!==e&&(n=(e=r)&&function(t){return function(n){this.textContent=t.call(this,n)}}(r)),n}return r._value=t,r}(t))},remove:function(){return this.on("end.remove",function(t){return function(){var n=this.parentNode;for(var e in this.__transition)if(+e!==t)return;n&&n.removeChild(this)}}(this._id))},tween:function(t,n){var e=this._id;if(t+="",arguments.length<2){for(var r,i=Xi(this.node(),e).tween,o=0,a=i.length;o()=>t;function Qo(t,{sourceEvent:n,target:e,selection:r,mode:i,dispatch:o}){Object.defineProperties(this,{type:{value:t,enumerable:!0,configurable:!0},sourceEvent:{value:n,enumerable:!0,configurable:!0},target:{value:e,enumerable:!0,configurable:!0},selection:{value:r,enumerable:!0,configurable:!0},mode:{value:i,enumerable:!0,configurable:!0},_:{value:o}})}function Jo(t){t.preventDefault(),t.stopImmediatePropagation()}var ta={name:"drag"},na={name:"space"},ea={name:"handle"},ra={name:"center"};const{abs:ia,max:oa,min:aa}=Math;function ua(t){return[+t[0],+t[1]]}function ca(t){return[ua(t[0]),ua(t[1])]}var fa={name:"x",handles:["w","e"].map(va),input:function(t,n){return null==t?null:[[+t[0],n[0][1]],[+t[1],n[1][1]]]},output:function(t){return t&&[t[0][0],t[1][0]]}},sa={name:"y",handles:["n","s"].map(va),input:function(t,n){return null==t?null:[[n[0][0],+t[0]],[n[1][0],+t[1]]]},output:function(t){return t&&[t[0][1],t[1][1]]}},la={name:"xy",handles:["n","w","e","s","nw","ne","sw","se"].map(va),input:function(t){return null==t?null:ca(t)},output:function(t){return t}},ha={overlay:"crosshair",selection:"move",n:"ns-resize",e:"ew-resize",s:"ns-resize",w:"ew-resize",nw:"nwse-resize",ne:"nesw-resize",se:"nwse-resize",sw:"nesw-resize"},da={e:"w",w:"e",nw:"ne",ne:"nw",se:"sw",sw:"se"},pa={n:"s",s:"n",nw:"sw",ne:"se",se:"ne",sw:"nw"},ga={overlay:1,selection:1,n:null,e:1,s:null,w:-1,nw:-1,ne:1,se:1,sw:-1},ya={overlay:1,selection:1,n:-1,e:null,s:1,w:null,nw:-1,ne:-1,se:1,sw:1};function va(t){return{type:t}}function _a(t){return!t.ctrlKey&&!t.button}function ba(){var t=this.ownerSVGElement||this;return t.hasAttribute("viewBox")?[[(t=t.viewBox.baseVal).x,t.y],[t.x+t.width,t.y+t.height]]:[[0,0],[t.width.baseVal.value,t.height.baseVal.value]]}function ma(){return navigator.maxTouchPoints||"ontouchstart"in this}function xa(t){for(;!t.__brush;)if(!(t=t.parentNode))return;return t.__brush}function wa(t){var n,e=ba,r=_a,i=ma,o=!0,a=$t("start","brush","end"),u=6;function c(n){var e=n.property("__brush",g).selectAll(".overlay").data([va("overlay")]);e.enter().append("rect").attr("class","overlay").attr("pointer-events","all").attr("cursor",ha.overlay).merge(e).each((function(){var t=xa(this).extent;Zn(this).attr("x",t[0][0]).attr("y",t[0][1]).attr("width",t[1][0]-t[0][0]).attr("height",t[1][1]-t[0][1])})),n.selectAll(".selection").data([va("selection")]).enter().append("rect").attr("class","selection").attr("cursor",ha.selection).attr("fill","#777").attr("fill-opacity",.3).attr("stroke","#fff").attr("shape-rendering","crispEdges");var r=n.selectAll(".handle").data(t.handles,(function(t){return t.type}));r.exit().remove(),r.enter().append("rect").attr("class",(function(t){return"handle handle--"+t.type})).attr("cursor",(function(t){return ha[t.type]})),n.each(f).attr("fill","none").attr("pointer-events","all").on("mousedown.brush",h).filter(i).on("touchstart.brush",h).on("touchmove.brush",d).on("touchend.brush touchcancel.brush",p).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function f(){var t=Zn(this),n=xa(this).selection;n?(t.selectAll(".selection").style("display",null).attr("x",n[0][0]).attr("y",n[0][1]).attr("width",n[1][0]-n[0][0]).attr("height",n[1][1]-n[0][1]),t.selectAll(".handle").style("display",null).attr("x",(function(t){return"e"===t.type[t.type.length-1]?n[1][0]-u/2:n[0][0]-u/2})).attr("y",(function(t){return"s"===t.type[0]?n[1][1]-u/2:n[0][1]-u/2})).attr("width",(function(t){return"n"===t.type||"s"===t.type?n[1][0]-n[0][0]+u:u})).attr("height",(function(t){return"e"===t.type||"w"===t.type?n[1][1]-n[0][1]+u:u}))):t.selectAll(".selection,.handle").style("display","none").attr("x",null).attr("y",null).attr("width",null).attr("height",null)}function s(t,n,e){var r=t.__brush.emitter;return!r||e&&r.clean?new l(t,n,e):r}function l(t,n,e){this.that=t,this.args=n,this.state=t.__brush,this.active=0,this.clean=e}function h(e){if((!n||e.touches)&&r.apply(this,arguments)){var i,a,u,c,l,h,d,p,g,y,v,_=this,b=e.target.__data__.type,m="selection"===(o&&e.metaKey?b="overlay":b)?ta:o&&e.altKey?ra:ea,x=t===sa?null:ga[b],w=t===fa?null:ya[b],M=xa(_),T=M.extent,A=M.selection,S=T[0][0],E=T[0][1],N=T[1][0],k=T[1][1],C=0,P=0,z=x&&w&&o&&e.shiftKey,$=Array.from(e.touches||[e],(t=>{const n=t.identifier;return(t=ne(t,_)).point0=t.slice(),t.identifier=n,t}));Gi(_);var D=s(_,arguments,!0).beforestart();if("overlay"===b){A&&(g=!0);const n=[$[0],$[1]||$[0]];M.selection=A=[[i=t===sa?S:aa(n[0][0],n[1][0]),u=t===fa?E:aa(n[0][1],n[1][1])],[l=t===sa?N:oa(n[0][0],n[1][0]),d=t===fa?k:oa(n[0][1],n[1][1])]],$.length>1&&I(e)}else i=A[0][0],u=A[0][1],l=A[1][0],d=A[1][1];a=i,c=u,h=l,p=d;var R=Zn(_).attr("pointer-events","none"),F=R.selectAll(".overlay").attr("cursor",ha[b]);if(e.touches)D.moved=U,D.ended=O;else{var q=Zn(e.view).on("mousemove.brush",U,!0).on("mouseup.brush",O,!0);o&&q.on("keydown.brush",(function(t){switch(t.keyCode){case 16:z=x&&w;break;case 18:m===ea&&(x&&(l=h-C*x,i=a+C*x),w&&(d=p-P*w,u=c+P*w),m=ra,I(t));break;case 32:m!==ea&&m!==ra||(x<0?l=h-C:x>0&&(i=a-C),w<0?d=p-P:w>0&&(u=c-P),m=na,F.attr("cursor",ha.selection),I(t));break;default:return}Jo(t)}),!0).on("keyup.brush",(function(t){switch(t.keyCode){case 16:z&&(y=v=z=!1,I(t));break;case 18:m===ra&&(x<0?l=h:x>0&&(i=a),w<0?d=p:w>0&&(u=c),m=ea,I(t));break;case 32:m===na&&(t.altKey?(x&&(l=h-C*x,i=a+C*x),w&&(d=p-P*w,u=c+P*w),m=ra):(x<0?l=h:x>0&&(i=a),w<0?d=p:w>0&&(u=c),m=ea),F.attr("cursor",ha[b]),I(t));break;default:return}Jo(t)}),!0),ae(e.view)}f.call(_),D.start(e,m.name)}function U(t){for(const n of t.changedTouches||[t])for(const t of $)t.identifier===n.identifier&&(t.cur=ne(n,_));if(z&&!y&&!v&&1===$.length){const t=$[0];ia(t.cur[0]-t[0])>ia(t.cur[1]-t[1])?v=!0:y=!0}for(const t of $)t.cur&&(t[0]=t.cur[0],t[1]=t.cur[1]);g=!0,Jo(t),I(t)}function I(t){const n=$[0],e=n.point0;var r;switch(C=n[0]-e[0],P=n[1]-e[1],m){case na:case ta:x&&(C=oa(S-i,aa(N-l,C)),a=i+C,h=l+C),w&&(P=oa(E-u,aa(k-d,P)),c=u+P,p=d+P);break;case ea:$[1]?(x&&(a=oa(S,aa(N,$[0][0])),h=oa(S,aa(N,$[1][0])),x=1),w&&(c=oa(E,aa(k,$[0][1])),p=oa(E,aa(k,$[1][1])),w=1)):(x<0?(C=oa(S-i,aa(N-i,C)),a=i+C,h=l):x>0&&(C=oa(S-l,aa(N-l,C)),a=i,h=l+C),w<0?(P=oa(E-u,aa(k-u,P)),c=u+P,p=d):w>0&&(P=oa(E-d,aa(k-d,P)),c=u,p=d+P));break;case ra:x&&(a=oa(S,aa(N,i-C*x)),h=oa(S,aa(N,l+C*x))),w&&(c=oa(E,aa(k,u-P*w)),p=oa(E,aa(k,d+P*w)))}ht+e))}function za(t,n){var e=0,r=null,i=null,o=null;function a(a){var u,c=a.length,f=new Array(c),s=Pa(0,c),l=new Array(c*c),h=new Array(c),d=0;a=Float64Array.from({length:c*c},n?(t,n)=>a[n%c][n/c|0]:(t,n)=>a[n/c|0][n%c]);for(let n=0;nr(f[t],f[n])));for(const e of s){const r=n;if(t){const t=Pa(1+~c,c).filter((t=>t<0?a[~t*c+e]:a[e*c+t]));i&&t.sort(((t,n)=>i(t<0?-a[~t*c+e]:a[e*c+t],n<0?-a[~n*c+e]:a[e*c+n])));for(const r of t)if(r<0){(l[~r*c+e]||(l[~r*c+e]={source:null,target:null})).target={index:e,startAngle:n,endAngle:n+=a[~r*c+e]*d,value:a[~r*c+e]}}else{(l[e*c+r]||(l[e*c+r]={source:null,target:null})).source={index:e,startAngle:n,endAngle:n+=a[e*c+r]*d,value:a[e*c+r]}}h[e]={index:e,startAngle:r,endAngle:n,value:f[e]}}else{const t=Pa(0,c).filter((t=>a[e*c+t]||a[t*c+e]));i&&t.sort(((t,n)=>i(a[e*c+t],a[e*c+n])));for(const r of t){let t;if(e=0))throw new Error(`invalid digits: ${t}`);if(n>15)return qa;const e=10**n;return function(t){this._+=t[0];for(let n=1,r=t.length;nRa)if(Math.abs(s*u-c*f)>Ra&&i){let h=e-o,d=r-a,p=u*u+c*c,g=h*h+d*d,y=Math.sqrt(p),v=Math.sqrt(l),_=i*Math.tan(($a-Math.acos((p+l-g)/(2*y*v)))/2),b=_/v,m=_/y;Math.abs(b-1)>Ra&&this._append`L${t+b*f},${n+b*s}`,this._append`A${i},${i},0,0,${+(s*h>f*d)},${this._x1=t+m*u},${this._y1=n+m*c}`}else this._append`L${this._x1=t},${this._y1=n}`;else;}arc(t,n,e,r,i,o){if(t=+t,n=+n,o=!!o,(e=+e)<0)throw new Error(`negative radius: ${e}`);let a=e*Math.cos(r),u=e*Math.sin(r),c=t+a,f=n+u,s=1^o,l=o?r-i:i-r;null===this._x1?this._append`M${c},${f}`:(Math.abs(this._x1-c)>Ra||Math.abs(this._y1-f)>Ra)&&this._append`L${c},${f}`,e&&(l<0&&(l=l%Da+Da),l>Fa?this._append`A${e},${e},0,1,${s},${t-a},${n-u}A${e},${e},0,1,${s},${this._x1=c},${this._y1=f}`:l>Ra&&this._append`A${e},${e},0,${+(l>=$a)},${s},${this._x1=t+e*Math.cos(i)},${this._y1=n+e*Math.sin(i)}`)}rect(t,n,e,r){this._append`M${this._x0=this._x1=+t},${this._y0=this._y1=+n}h${e=+e}v${+r}h${-e}Z`}toString(){return this._}};function Ia(){return new Ua}Ia.prototype=Ua.prototype;var Oa=Array.prototype.slice;function Ba(t){return function(){return t}}function Ya(t){return t.source}function La(t){return t.target}function ja(t){return t.radius}function Ha(t){return t.startAngle}function Xa(t){return t.endAngle}function Ga(){return 0}function Va(){return 10}function Wa(t){var n=Ya,e=La,r=ja,i=ja,o=Ha,a=Xa,u=Ga,c=null;function f(){var f,s=n.apply(this,arguments),l=e.apply(this,arguments),h=u.apply(this,arguments)/2,d=Oa.call(arguments),p=+r.apply(this,(d[0]=s,d)),g=o.apply(this,d)-Ea,y=a.apply(this,d)-Ea,v=+i.apply(this,(d[0]=l,d)),_=o.apply(this,d)-Ea,b=a.apply(this,d)-Ea;if(c||(c=f=Ia()),h>Ca&&(Ma(y-g)>2*h+Ca?y>g?(g+=h,y-=h):(g-=h,y+=h):g=y=(g+y)/2,Ma(b-_)>2*h+Ca?b>_?(_+=h,b-=h):(_-=h,b+=h):_=b=(_+b)/2),c.moveTo(p*Ta(g),p*Aa(g)),c.arc(0,0,p,g,y),g!==_||y!==b)if(t){var m=v-+t.apply(this,arguments),x=(_+b)/2;c.quadraticCurveTo(0,0,m*Ta(_),m*Aa(_)),c.lineTo(v*Ta(x),v*Aa(x)),c.lineTo(m*Ta(b),m*Aa(b))}else c.quadraticCurveTo(0,0,v*Ta(_),v*Aa(_)),c.arc(0,0,v,_,b);if(c.quadraticCurveTo(0,0,p*Ta(g),p*Aa(g)),c.closePath(),f)return c=null,f+""||null}return t&&(f.headRadius=function(n){return arguments.length?(t="function"==typeof n?n:Ba(+n),f):t}),f.radius=function(t){return arguments.length?(r=i="function"==typeof t?t:Ba(+t),f):r},f.sourceRadius=function(t){return arguments.length?(r="function"==typeof t?t:Ba(+t),f):r},f.targetRadius=function(t){return arguments.length?(i="function"==typeof t?t:Ba(+t),f):i},f.startAngle=function(t){return arguments.length?(o="function"==typeof t?t:Ba(+t),f):o},f.endAngle=function(t){return arguments.length?(a="function"==typeof t?t:Ba(+t),f):a},f.padAngle=function(t){return arguments.length?(u="function"==typeof t?t:Ba(+t),f):u},f.source=function(t){return arguments.length?(n=t,f):n},f.target=function(t){return arguments.length?(e=t,f):e},f.context=function(t){return arguments.length?(c=null==t?null:t,f):c},f}var Za=Array.prototype.slice;function Ka(t,n){return t-n}var Qa=t=>()=>t;function Ja(t,n){for(var e,r=-1,i=n.length;++rr!=d>r&&e<(h-f)*(r-s)/(d-s)+f&&(i=-i)}return i}function nu(t,n,e){var r,i,o,a;return function(t,n,e){return(n[0]-t[0])*(e[1]-t[1])==(e[0]-t[0])*(n[1]-t[1])}(t,n,e)&&(i=t[r=+(t[0]===n[0])],o=e[r],a=n[r],i<=o&&o<=a||a<=o&&o<=i)}function eu(){}var ru=[[],[[[1,1.5],[.5,1]]],[[[1.5,1],[1,1.5]]],[[[1.5,1],[.5,1]]],[[[1,.5],[1.5,1]]],[[[1,1.5],[.5,1]],[[1,.5],[1.5,1]]],[[[1,.5],[1,1.5]]],[[[1,.5],[.5,1]]],[[[.5,1],[1,.5]]],[[[1,1.5],[1,.5]]],[[[.5,1],[1,.5]],[[1.5,1],[1,1.5]]],[[[1.5,1],[1,.5]]],[[[.5,1],[1.5,1]]],[[[1,1.5],[1.5,1]]],[[[.5,1],[1,1.5]]],[]];function iu(){var t=1,n=1,e=K,r=u;function i(t){var n=e(t);if(Array.isArray(n))n=n.slice().sort(Ka);else{const e=M(t,ou);for(n=G(...Z(e[0],e[1],n),n);n[n.length-1]>=e[1];)n.pop();for(;n[1]o(t,n)))}function o(e,i){const o=null==i?NaN:+i;if(isNaN(o))throw new Error(`invalid value: ${i}`);var u=[],c=[];return function(e,r,i){var o,u,c,f,s,l,h=new Array,d=new Array;o=u=-1,f=au(e[0],r),ru[f<<1].forEach(p);for(;++o=r,ru[s<<2].forEach(p);for(;++o0?u.push([t]):c.push(t)})),c.forEach((function(t){for(var n,e=0,r=u.length;e0&&o0&&a=0&&o>=0))throw new Error("invalid size");return t=r,n=o,i},i.thresholds=function(t){return arguments.length?(e="function"==typeof t?t:Array.isArray(t)?Qa(Za.call(t)):Qa(t),i):e},i.smooth=function(t){return arguments.length?(r=t?u:eu,i):r===u},i}function ou(t){return isFinite(t)?t:NaN}function au(t,n){return null!=t&&+t>=n}function uu(t){return null==t||isNaN(t=+t)?-1/0:t}function cu(t,n,e,r){const i=r-n,o=e-n,a=isFinite(i)||isFinite(o)?i/o:Math.sign(i)/Math.sign(o);return isNaN(a)?t:t+a-.5}function fu(t){return t[0]}function su(t){return t[1]}function lu(){return 1}const hu=134217729,du=33306690738754706e-32;function pu(t,n,e,r,i){let o,a,u,c,f=n[0],s=r[0],l=0,h=0;s>f==s>-f?(o=f,f=n[++l]):(o=s,s=r[++h]);let d=0;if(lf==s>-f?(a=f+o,u=o-(a-f),f=n[++l]):(a=s+o,u=o-(a-s),s=r[++h]),o=a,0!==u&&(i[d++]=u);lf==s>-f?(a=o+f,c=a-o,u=o-(a-c)+(f-c),f=n[++l]):(a=o+s,c=a-o,u=o-(a-c)+(s-c),s=r[++h]),o=a,0!==u&&(i[d++]=u);for(;l=33306690738754716e-32*f?c:-function(t,n,e,r,i,o,a){let u,c,f,s,l,h,d,p,g,y,v,_,b,m,x,w,M,T;const A=t-i,S=e-i,E=n-o,N=r-o;m=A*N,h=hu*A,d=h-(h-A),p=A-d,h=hu*N,g=h-(h-N),y=N-g,x=p*y-(m-d*g-p*g-d*y),w=E*S,h=hu*E,d=h-(h-E),p=E-d,h=hu*S,g=h-(h-S),y=S-g,M=p*y-(w-d*g-p*g-d*y),v=x-M,l=x-v,_u[0]=x-(v+l)+(l-M),_=m+v,l=_-m,b=m-(_-l)+(v-l),v=b-w,l=b-v,_u[1]=b-(v+l)+(l-w),T=_+v,l=T-_,_u[2]=_-(T-l)+(v-l),_u[3]=T;let k=function(t,n){let e=n[0];for(let r=1;r=C||-k>=C)return k;if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xu);return xu[$-1]}(t,n,e,r,i,o,f)}const Tu=Math.pow(2,-52),Au=new Uint32Array(512);class Su{static from(t,n=zu,e=$u){const r=t.length,i=new Float64Array(2*r);for(let o=0;o>1;if(n>0&&"number"!=typeof t[0])throw new Error("Expected coords to contain numbers.");this.coords=t;const e=Math.max(2*n-5,0);this._triangles=new Uint32Array(3*e),this._halfedges=new Int32Array(3*e),this._hashSize=Math.ceil(Math.sqrt(n)),this._hullPrev=new Uint32Array(n),this._hullNext=new Uint32Array(n),this._hullTri=new Uint32Array(n),this._hullHash=new Int32Array(this._hashSize),this._ids=new Uint32Array(n),this._dists=new Float64Array(n),this.update()}update(){const{coords:t,_hullPrev:n,_hullNext:e,_hullTri:r,_hullHash:i}=this,o=t.length>>1;let a=1/0,u=1/0,c=-1/0,f=-1/0;for(let n=0;nc&&(c=e),r>f&&(f=r),this._ids[n]=n}const s=(a+c)/2,l=(u+f)/2;let h,d,p;for(let n=0,e=1/0;n0&&(d=n,e=r)}let v=t[2*d],_=t[2*d+1],b=1/0;for(let n=0;nr&&(n[e++]=i,r=o)}return this.hull=n.subarray(0,e),this.triangles=new Uint32Array(0),void(this.halfedges=new Uint32Array(0))}if(Mu(g,y,v,_,m,x)<0){const t=d,n=v,e=_;d=p,v=m,_=x,p=t,m=n,x=e}const w=function(t,n,e,r,i,o){const a=e-t,u=r-n,c=i-t,f=o-n,s=a*a+u*u,l=c*c+f*f,h=.5/(a*f-u*c),d=t+(f*s-u*l)*h,p=n+(a*l-c*s)*h;return{x:d,y:p}}(g,y,v,_,m,x);this._cx=w.x,this._cy=w.y;for(let n=0;n0&&Math.abs(f-o)<=Tu&&Math.abs(s-a)<=Tu)continue;if(o=f,a=s,c===h||c===d||c===p)continue;let l=0;for(let t=0,n=this._hashKey(f,s);t=0;)if(y=g,y===l){y=-1;break}if(-1===y)continue;let v=this._addTriangle(y,c,e[y],-1,-1,r[y]);r[c]=this._legalize(v+2),r[y]=v,M++;let _=e[y];for(;g=e[_],Mu(f,s,t[2*_],t[2*_+1],t[2*g],t[2*g+1])<0;)v=this._addTriangle(_,c,g,r[c],-1,r[_]),r[c]=this._legalize(v+2),e[_]=_,M--,_=g;if(y===l)for(;g=n[y],Mu(f,s,t[2*g],t[2*g+1],t[2*y],t[2*y+1])<0;)v=this._addTriangle(g,c,y,-1,r[y],r[g]),this._legalize(v+2),r[g]=v,e[y]=y,M--,y=g;this._hullStart=n[c]=y,e[y]=n[_]=c,e[c]=_,i[this._hashKey(f,s)]=c,i[this._hashKey(t[2*y],t[2*y+1])]=y}this.hull=new Uint32Array(M);for(let t=0,n=this._hullStart;t0?3-e:1+e)/4}(t-this._cx,n-this._cy)*this._hashSize)%this._hashSize}_legalize(t){const{_triangles:n,_halfedges:e,coords:r}=this;let i=0,o=0;for(;;){const a=e[t],u=t-t%3;if(o=u+(t+2)%3,-1===a){if(0===i)break;t=Au[--i];continue}const c=a-a%3,f=u+(t+1)%3,s=c+(a+2)%3,l=n[o],h=n[t],d=n[f],p=n[s];if(Nu(r[2*l],r[2*l+1],r[2*h],r[2*h+1],r[2*d],r[2*d+1],r[2*p],r[2*p+1])){n[t]=p,n[a]=l;const r=e[s];if(-1===r){let n=this._hullStart;do{if(this._hullTri[n]===s){this._hullTri[n]=t;break}n=this._hullPrev[n]}while(n!==this._hullStart)}this._link(t,r),this._link(a,e[o]),this._link(o,s);const u=c+(a+1)%3;i=e&&n[t[a]]>o;)t[a+1]=t[a--];t[a+1]=r}else{let i=e+1,o=r;Pu(t,e+r>>1,i),n[t[e]]>n[t[r]]&&Pu(t,e,r),n[t[i]]>n[t[r]]&&Pu(t,i,r),n[t[e]]>n[t[i]]&&Pu(t,e,i);const a=t[i],u=n[a];for(;;){do{i++}while(n[t[i]]u);if(o=o-e?(Cu(t,n,i,r),Cu(t,n,e,o-1)):(Cu(t,n,e,o-1),Cu(t,n,i,r))}}function Pu(t,n,e){const r=t[n];t[n]=t[e],t[e]=r}function zu(t){return t[0]}function $u(t){return t[1]}const Du=1e-6;class Ru{constructor(){this._x0=this._y0=this._x1=this._y1=null,this._=""}moveTo(t,n){this._+=`M${this._x0=this._x1=+t},${this._y0=this._y1=+n}`}closePath(){null!==this._x1&&(this._x1=this._x0,this._y1=this._y0,this._+="Z")}lineTo(t,n){this._+=`L${this._x1=+t},${this._y1=+n}`}arc(t,n,e){const r=(t=+t)+(e=+e),i=n=+n;if(e<0)throw new Error("negative radius");null===this._x1?this._+=`M${r},${i}`:(Math.abs(this._x1-r)>Du||Math.abs(this._y1-i)>Du)&&(this._+="L"+r+","+i),e&&(this._+=`A${e},${e},0,1,1,${t-e},${n}A${e},${e},0,1,1,${this._x1=r},${this._y1=i}`)}rect(t,n,e,r){this._+=`M${this._x0=this._x1=+t},${this._y0=this._y1=+n}h${+e}v${+r}h${-e}Z`}value(){return this._||null}}class Fu{constructor(){this._=[]}moveTo(t,n){this._.push([t,n])}closePath(){this._.push(this._[0].slice())}lineTo(t,n){this._.push([t,n])}value(){return this._.length?this._:null}}class qu{constructor(t,[n,e,r,i]=[0,0,960,500]){if(!((r=+r)>=(n=+n)&&(i=+i)>=(e=+e)))throw new Error("invalid bounds");this.delaunay=t,this._circumcenters=new Float64Array(2*t.points.length),this.vectors=new Float64Array(2*t.points.length),this.xmax=r,this.xmin=n,this.ymax=i,this.ymin=e,this._init()}update(){return this.delaunay.update(),this._init(),this}_init(){const{delaunay:{points:t,hull:n,triangles:e},vectors:r}=this;let i,o;const a=this.circumcenters=this._circumcenters.subarray(0,e.length/3*2);for(let r,u,c=0,f=0,s=e.length;c1;)i-=2;for(let t=2;t0){if(n>=this.ymax)return null;(i=(this.ymax-n)/r)0){if(t>=this.xmax)return null;(i=(this.xmax-t)/e)this.xmax?2:0)|(nthis.ymax?8:0)}_simplify(t){if(t&&t.length>4){for(let n=0;n2&&function(t){const{triangles:n,coords:e}=t;for(let t=0;t1e-10)return!1}return!0}(t)){this.collinear=Int32Array.from({length:n.length/2},((t,n)=>n)).sort(((t,e)=>n[2*t]-n[2*e]||n[2*t+1]-n[2*e+1]));const t=this.collinear[0],e=this.collinear[this.collinear.length-1],r=[n[2*t],n[2*t+1],n[2*e],n[2*e+1]],i=1e-8*Math.hypot(r[3]-r[1],r[2]-r[0]);for(let t=0,e=n.length/2;t0&&(this.triangles=new Int32Array(3).fill(-1),this.halfedges=new Int32Array(3).fill(-1),this.triangles[0]=r[0],o[r[0]]=1,2===r.length&&(o[r[1]]=0,this.triangles[1]=r[1],this.triangles[2]=r[1]))}voronoi(t){return new qu(this,t)}*neighbors(t){const{inedges:n,hull:e,_hullIndex:r,halfedges:i,triangles:o,collinear:a}=this;if(a){const n=a.indexOf(t);return n>0&&(yield a[n-1]),void(n=0&&i!==e&&i!==r;)e=i;return i}_step(t,n,e){const{inedges:r,hull:i,_hullIndex:o,halfedges:a,triangles:u,points:c}=this;if(-1===r[t]||!c.length)return(t+1)%(c.length>>1);let f=t,s=Iu(n-c[2*t],2)+Iu(e-c[2*t+1],2);const l=r[t];let h=l;do{let r=u[h];const l=Iu(n-c[2*r],2)+Iu(e-c[2*r+1],2);if(l9999?"+"+Ku(n,6):Ku(n,4))+"-"+Ku(t.getUTCMonth()+1,2)+"-"+Ku(t.getUTCDate(),2)+(o?"T"+Ku(e,2)+":"+Ku(r,2)+":"+Ku(i,2)+"."+Ku(o,3)+"Z":i?"T"+Ku(e,2)+":"+Ku(r,2)+":"+Ku(i,2)+"Z":r||e?"T"+Ku(e,2)+":"+Ku(r,2)+"Z":"")}function Ju(t){var n=new RegExp('["'+t+"\n\r]"),e=t.charCodeAt(0);function r(t,n){var r,i=[],o=t.length,a=0,u=0,c=o<=0,f=!1;function s(){if(c)return Hu;if(f)return f=!1,ju;var n,r,i=a;if(t.charCodeAt(i)===Xu){for(;a++=o?c=!0:(r=t.charCodeAt(a++))===Gu?f=!0:r===Vu&&(f=!0,t.charCodeAt(a)===Gu&&++a),t.slice(i+1,n-1).replace(/""/g,'"')}for(;amc(n,e).then((n=>(new DOMParser).parseFromString(n,t)))}var Sc=Ac("application/xml"),Ec=Ac("text/html"),Nc=Ac("image/svg+xml");function kc(t,n,e,r){if(isNaN(n)||isNaN(e))return t;var i,o,a,u,c,f,s,l,h,d=t._root,p={data:r},g=t._x0,y=t._y0,v=t._x1,_=t._y1;if(!d)return t._root=p,t;for(;d.length;)if((f=n>=(o=(g+v)/2))?g=o:v=o,(s=e>=(a=(y+_)/2))?y=a:_=a,i=d,!(d=d[l=s<<1|f]))return i[l]=p,t;if(u=+t._x.call(null,d.data),c=+t._y.call(null,d.data),n===u&&e===c)return p.next=d,i?i[l]=p:t._root=p,t;do{i=i?i[l]=new Array(4):t._root=new Array(4),(f=n>=(o=(g+v)/2))?g=o:v=o,(s=e>=(a=(y+_)/2))?y=a:_=a}while((l=s<<1|f)==(h=(c>=a)<<1|u>=o));return i[h]=d,i[l]=p,t}function Cc(t,n,e,r,i){this.node=t,this.x0=n,this.y0=e,this.x1=r,this.y1=i}function Pc(t){return t[0]}function zc(t){return t[1]}function $c(t,n,e){var r=new Dc(null==n?Pc:n,null==e?zc:e,NaN,NaN,NaN,NaN);return null==t?r:r.addAll(t)}function Dc(t,n,e,r,i,o){this._x=t,this._y=n,this._x0=e,this._y0=r,this._x1=i,this._y1=o,this._root=void 0}function Rc(t){for(var n={data:t.data},e=n;t=t.next;)e=e.next={data:t.data};return n}var Fc=$c.prototype=Dc.prototype;function qc(t){return function(){return t}}function Uc(t){return 1e-6*(t()-.5)}function Ic(t){return t.x+t.vx}function Oc(t){return t.y+t.vy}function Bc(t){return t.index}function Yc(t,n){var e=t.get(n);if(!e)throw new Error("node not found: "+n);return e}Fc.copy=function(){var t,n,e=new Dc(this._x,this._y,this._x0,this._y0,this._x1,this._y1),r=this._root;if(!r)return e;if(!r.length)return e._root=Rc(r),e;for(t=[{source:r,target:e._root=new Array(4)}];r=t.pop();)for(var i=0;i<4;++i)(n=r.source[i])&&(n.length?t.push({source:n,target:r.target[i]=new Array(4)}):r.target[i]=Rc(n));return e},Fc.add=function(t){const n=+this._x.call(null,t),e=+this._y.call(null,t);return kc(this.cover(n,e),n,e,t)},Fc.addAll=function(t){var n,e,r,i,o=t.length,a=new Array(o),u=new Array(o),c=1/0,f=1/0,s=-1/0,l=-1/0;for(e=0;es&&(s=r),il&&(l=i));if(c>s||f>l)return this;for(this.cover(c,f).cover(s,l),e=0;et||t>=i||r>n||n>=o;)switch(u=(nh||(o=c.y0)>d||(a=c.x1)=v)<<1|t>=y)&&(c=p[p.length-1],p[p.length-1]=p[p.length-1-f],p[p.length-1-f]=c)}else{var _=t-+this._x.call(null,g.data),b=n-+this._y.call(null,g.data),m=_*_+b*b;if(m=(u=(p+y)/2))?p=u:y=u,(s=a>=(c=(g+v)/2))?g=c:v=c,n=d,!(d=d[l=s<<1|f]))return this;if(!d.length)break;(n[l+1&3]||n[l+2&3]||n[l+3&3])&&(e=n,h=l)}for(;d.data!==t;)if(r=d,!(d=d.next))return this;return(i=d.next)&&delete d.next,r?(i?r.next=i:delete r.next,this):n?(i?n[l]=i:delete n[l],(d=n[0]||n[1]||n[2]||n[3])&&d===(n[3]||n[2]||n[1]||n[0])&&!d.length&&(e?e[h]=d:this._root=d),this):(this._root=i,this)},Fc.removeAll=function(t){for(var n=0,e=t.length;n1?r[0]+r.slice(2):r,+t.slice(e+1)]}function Zc(t){return(t=Wc(Math.abs(t)))?t[1]:NaN}var Kc,Qc=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function Jc(t){if(!(n=Qc.exec(t)))throw new Error("invalid format: "+t);var n;return new tf({fill:n[1],align:n[2],sign:n[3],symbol:n[4],zero:n[5],width:n[6],comma:n[7],precision:n[8]&&n[8].slice(1),trim:n[9],type:n[10]})}function tf(t){this.fill=void 0===t.fill?" ":t.fill+"",this.align=void 0===t.align?">":t.align+"",this.sign=void 0===t.sign?"-":t.sign+"",this.symbol=void 0===t.symbol?"":t.symbol+"",this.zero=!!t.zero,this.width=void 0===t.width?void 0:+t.width,this.comma=!!t.comma,this.precision=void 0===t.precision?void 0:+t.precision,this.trim=!!t.trim,this.type=void 0===t.type?"":t.type+""}function nf(t,n){var e=Wc(t,n);if(!e)return t+"";var r=e[0],i=e[1];return i<0?"0."+new Array(-i).join("0")+r:r.length>i+1?r.slice(0,i+1)+"."+r.slice(i+1):r+new Array(i-r.length+2).join("0")}Jc.prototype=tf.prototype,tf.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(void 0===this.width?"":Math.max(1,0|this.width))+(this.comma?",":"")+(void 0===this.precision?"":"."+Math.max(0,0|this.precision))+(this.trim?"~":"")+this.type};var ef={"%":(t,n)=>(100*t).toFixed(n),b:t=>Math.round(t).toString(2),c:t=>t+"",d:function(t){return Math.abs(t=Math.round(t))>=1e21?t.toLocaleString("en").replace(/,/g,""):t.toString(10)},e:(t,n)=>t.toExponential(n),f:(t,n)=>t.toFixed(n),g:(t,n)=>t.toPrecision(n),o:t=>Math.round(t).toString(8),p:(t,n)=>nf(100*t,n),r:nf,s:function(t,n){var e=Wc(t,n);if(!e)return t+"";var r=e[0],i=e[1],o=i-(Kc=3*Math.max(-8,Math.min(8,Math.floor(i/3))))+1,a=r.length;return o===a?r:o>a?r+new Array(o-a+1).join("0"):o>0?r.slice(0,o)+"."+r.slice(o):"0."+new Array(1-o).join("0")+Wc(t,Math.max(0,n+o-1))[0]},X:t=>Math.round(t).toString(16).toUpperCase(),x:t=>Math.round(t).toString(16)};function rf(t){return t}var of,af=Array.prototype.map,uf=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function cf(t){var n,e,r=void 0===t.grouping||void 0===t.thousands?rf:(n=af.call(t.grouping,Number),e=t.thousands+"",function(t,r){for(var i=t.length,o=[],a=0,u=n[0],c=0;i>0&&u>0&&(c+u+1>r&&(u=Math.max(1,r-c)),o.push(t.substring(i-=u,i+u)),!((c+=u+1)>r));)u=n[a=(a+1)%n.length];return o.reverse().join(e)}),i=void 0===t.currency?"":t.currency[0]+"",o=void 0===t.currency?"":t.currency[1]+"",a=void 0===t.decimal?".":t.decimal+"",u=void 0===t.numerals?rf:function(t){return function(n){return n.replace(/[0-9]/g,(function(n){return t[+n]}))}}(af.call(t.numerals,String)),c=void 0===t.percent?"%":t.percent+"",f=void 0===t.minus?"−":t.minus+"",s=void 0===t.nan?"NaN":t.nan+"";function l(t){var n=(t=Jc(t)).fill,e=t.align,l=t.sign,h=t.symbol,d=t.zero,p=t.width,g=t.comma,y=t.precision,v=t.trim,_=t.type;"n"===_?(g=!0,_="g"):ef[_]||(void 0===y&&(y=12),v=!0,_="g"),(d||"0"===n&&"="===e)&&(d=!0,n="0",e="=");var b="$"===h?i:"#"===h&&/[boxX]/.test(_)?"0"+_.toLowerCase():"",m="$"===h?o:/[%p]/.test(_)?c:"",x=ef[_],w=/[defgprs%]/.test(_);function M(t){var i,o,c,h=b,M=m;if("c"===_)M=x(t)+M,t="";else{var T=(t=+t)<0||1/t<0;if(t=isNaN(t)?s:x(Math.abs(t),y),v&&(t=function(t){t:for(var n,e=t.length,r=1,i=-1;r0&&(i=0)}return i>0?t.slice(0,i)+t.slice(n+1):t}(t)),T&&0==+t&&"+"!==l&&(T=!1),h=(T?"("===l?l:f:"-"===l||"("===l?"":l)+h,M=("s"===_?uf[8+Kc/3]:"")+M+(T&&"("===l?")":""),w)for(i=-1,o=t.length;++i(c=t.charCodeAt(i))||c>57){M=(46===c?a+t.slice(i+1):t.slice(i))+M,t=t.slice(0,i);break}}g&&!d&&(t=r(t,1/0));var A=h.length+t.length+M.length,S=A>1)+h+t+M+S.slice(A);break;default:t=S+h+t+M}return u(t)}return y=void 0===y?6:/[gprs]/.test(_)?Math.max(1,Math.min(21,y)):Math.max(0,Math.min(20,y)),M.toString=function(){return t+""},M}return{format:l,formatPrefix:function(t,n){var e=l(((t=Jc(t)).type="f",t)),r=3*Math.max(-8,Math.min(8,Math.floor(Zc(n)/3))),i=Math.pow(10,-r),o=uf[8+r/3];return function(t){return e(i*t)+o}}}}function ff(n){return of=cf(n),t.format=of.format,t.formatPrefix=of.formatPrefix,of}function sf(t){return Math.max(0,-Zc(Math.abs(t)))}function lf(t,n){return Math.max(0,3*Math.max(-8,Math.min(8,Math.floor(Zc(n)/3)))-Zc(Math.abs(t)))}function hf(t,n){return t=Math.abs(t),n=Math.abs(n)-t,Math.max(0,Zc(n)-Zc(t))+1}t.format=void 0,t.formatPrefix=void 0,ff({thousands:",",grouping:[3],currency:["$",""]});var df=1e-6,pf=1e-12,gf=Math.PI,yf=gf/2,vf=gf/4,_f=2*gf,bf=180/gf,mf=gf/180,xf=Math.abs,wf=Math.atan,Mf=Math.atan2,Tf=Math.cos,Af=Math.ceil,Sf=Math.exp,Ef=Math.hypot,Nf=Math.log,kf=Math.pow,Cf=Math.sin,Pf=Math.sign||function(t){return t>0?1:t<0?-1:0},zf=Math.sqrt,$f=Math.tan;function Df(t){return t>1?0:t<-1?gf:Math.acos(t)}function Rf(t){return t>1?yf:t<-1?-yf:Math.asin(t)}function Ff(t){return(t=Cf(t/2))*t}function qf(){}function Uf(t,n){t&&Of.hasOwnProperty(t.type)&&Of[t.type](t,n)}var If={Feature:function(t,n){Uf(t.geometry,n)},FeatureCollection:function(t,n){for(var e=t.features,r=-1,i=e.length;++r=0?1:-1,i=r*e,o=Tf(n=(n*=mf)/2+vf),a=Cf(n),u=Vf*a,c=Gf*o+u*Tf(i),f=u*r*Cf(i);as.add(Mf(f,c)),Xf=t,Gf=o,Vf=a}function ds(t){return[Mf(t[1],t[0]),Rf(t[2])]}function ps(t){var n=t[0],e=t[1],r=Tf(e);return[r*Tf(n),r*Cf(n),Cf(e)]}function gs(t,n){return t[0]*n[0]+t[1]*n[1]+t[2]*n[2]}function ys(t,n){return[t[1]*n[2]-t[2]*n[1],t[2]*n[0]-t[0]*n[2],t[0]*n[1]-t[1]*n[0]]}function vs(t,n){t[0]+=n[0],t[1]+=n[1],t[2]+=n[2]}function _s(t,n){return[t[0]*n,t[1]*n,t[2]*n]}function bs(t){var n=zf(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=n,t[1]/=n,t[2]/=n}var ms,xs,ws,Ms,Ts,As,Ss,Es,Ns,ks,Cs,Ps,zs,$s,Ds,Rs,Fs={point:qs,lineStart:Is,lineEnd:Os,polygonStart:function(){Fs.point=Bs,Fs.lineStart=Ys,Fs.lineEnd=Ls,rs=new T,cs.polygonStart()},polygonEnd:function(){cs.polygonEnd(),Fs.point=qs,Fs.lineStart=Is,Fs.lineEnd=Os,as<0?(Wf=-(Kf=180),Zf=-(Qf=90)):rs>df?Qf=90:rs<-df&&(Zf=-90),os[0]=Wf,os[1]=Kf},sphere:function(){Wf=-(Kf=180),Zf=-(Qf=90)}};function qs(t,n){is.push(os=[Wf=t,Kf=t]),nQf&&(Qf=n)}function Us(t,n){var e=ps([t*mf,n*mf]);if(es){var r=ys(es,e),i=ys([r[1],-r[0],0],r);bs(i),i=ds(i);var o,a=t-Jf,u=a>0?1:-1,c=i[0]*bf*u,f=xf(a)>180;f^(u*JfQf&&(Qf=o):f^(u*Jf<(c=(c+360)%360-180)&&cQf&&(Qf=n)),f?tjs(Wf,Kf)&&(Kf=t):js(t,Kf)>js(Wf,Kf)&&(Wf=t):Kf>=Wf?(tKf&&(Kf=t)):t>Jf?js(Wf,t)>js(Wf,Kf)&&(Kf=t):js(t,Kf)>js(Wf,Kf)&&(Wf=t)}else is.push(os=[Wf=t,Kf=t]);nQf&&(Qf=n),es=e,Jf=t}function Is(){Fs.point=Us}function Os(){os[0]=Wf,os[1]=Kf,Fs.point=qs,es=null}function Bs(t,n){if(es){var e=t-Jf;rs.add(xf(e)>180?e+(e>0?360:-360):e)}else ts=t,ns=n;cs.point(t,n),Us(t,n)}function Ys(){cs.lineStart()}function Ls(){Bs(ts,ns),cs.lineEnd(),xf(rs)>df&&(Wf=-(Kf=180)),os[0]=Wf,os[1]=Kf,es=null}function js(t,n){return(n-=t)<0?n+360:n}function Hs(t,n){return t[0]-n[0]}function Xs(t,n){return t[0]<=t[1]?t[0]<=n&&n<=t[1]:ngf&&(t-=Math.round(t/_f)*_f),[t,n]}function ul(t,n,e){return(t%=_f)?n||e?ol(fl(t),sl(n,e)):fl(t):n||e?sl(n,e):al}function cl(t){return function(n,e){return xf(n+=t)>gf&&(n-=Math.round(n/_f)*_f),[n,e]}}function fl(t){var n=cl(t);return n.invert=cl(-t),n}function sl(t,n){var e=Tf(t),r=Cf(t),i=Tf(n),o=Cf(n);function a(t,n){var a=Tf(n),u=Tf(t)*a,c=Cf(t)*a,f=Cf(n),s=f*e+u*r;return[Mf(c*i-s*o,u*e-f*r),Rf(s*i+c*o)]}return a.invert=function(t,n){var a=Tf(n),u=Tf(t)*a,c=Cf(t)*a,f=Cf(n),s=f*i-c*o;return[Mf(c*i+f*o,u*e+s*r),Rf(s*e-u*r)]},a}function ll(t){function n(n){return(n=t(n[0]*mf,n[1]*mf))[0]*=bf,n[1]*=bf,n}return t=ul(t[0]*mf,t[1]*mf,t.length>2?t[2]*mf:0),n.invert=function(n){return(n=t.invert(n[0]*mf,n[1]*mf))[0]*=bf,n[1]*=bf,n},n}function hl(t,n,e,r,i,o){if(e){var a=Tf(n),u=Cf(n),c=r*e;null==i?(i=n+r*_f,o=n-c/2):(i=dl(a,i),o=dl(a,o),(r>0?io)&&(i+=r*_f));for(var f,s=i;r>0?s>o:s1&&n.push(n.pop().concat(n.shift()))},result:function(){var e=n;return n=[],t=null,e}}}function gl(t,n){return xf(t[0]-n[0])=0;--o)i.point((s=f[o])[0],s[1]);else r(h.x,h.p.x,-1,i);h=h.p}f=(h=h.o).z,d=!d}while(!h.v);i.lineEnd()}}}function _l(t){if(n=t.length){for(var n,e,r=0,i=t[0];++r=0?1:-1,E=S*A,N=E>gf,k=y*w;if(c.add(Mf(k*S*Cf(E),v*M+k*Tf(E))),a+=N?A+S*_f:A,N^p>=e^m>=e){var C=ys(ps(d),ps(b));bs(C);var P=ys(o,C);bs(P);var z=(N^A>=0?-1:1)*Rf(P[2]);(r>z||r===z&&(C[0]||C[1]))&&(u+=N^A>=0?1:-1)}}return(a<-df||a0){for(l||(i.polygonStart(),l=!0),i.lineStart(),t=0;t1&&2&c&&h.push(h.pop().concat(h.shift())),a.push(h.filter(wl))}return h}}function wl(t){return t.length>1}function Ml(t,n){return((t=t.x)[0]<0?t[1]-yf-df:yf-t[1])-((n=n.x)[0]<0?n[1]-yf-df:yf-n[1])}al.invert=al;var Tl=xl((function(){return!0}),(function(t){var n,e=NaN,r=NaN,i=NaN;return{lineStart:function(){t.lineStart(),n=1},point:function(o,a){var u=o>0?gf:-gf,c=xf(o-e);xf(c-gf)0?yf:-yf),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(u,r),t.point(o,r),n=0):i!==u&&c>=gf&&(xf(e-i)df?wf((Cf(n)*(o=Tf(r))*Cf(e)-Cf(r)*(i=Tf(n))*Cf(t))/(i*o*a)):(n+r)/2}(e,r,o,a),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(u,r),n=0),t.point(e=o,r=a),i=u},lineEnd:function(){t.lineEnd(),e=r=NaN},clean:function(){return 2-n}}}),(function(t,n,e,r){var i;if(null==t)i=e*yf,r.point(-gf,i),r.point(0,i),r.point(gf,i),r.point(gf,0),r.point(gf,-i),r.point(0,-i),r.point(-gf,-i),r.point(-gf,0),r.point(-gf,i);else if(xf(t[0]-n[0])>df){var o=t[0]0,i=xf(n)>df;function o(t,e){return Tf(t)*Tf(e)>n}function a(t,e,r){var i=[1,0,0],o=ys(ps(t),ps(e)),a=gs(o,o),u=o[0],c=a-u*u;if(!c)return!r&&t;var f=n*a/c,s=-n*u/c,l=ys(i,o),h=_s(i,f);vs(h,_s(o,s));var d=l,p=gs(h,d),g=gs(d,d),y=p*p-g*(gs(h,h)-1);if(!(y<0)){var v=zf(y),_=_s(d,(-p-v)/g);if(vs(_,h),_=ds(_),!r)return _;var b,m=t[0],x=e[0],w=t[1],M=e[1];x0^_[1]<(xf(_[0]-m)gf^(m<=_[0]&&_[0]<=x)){var S=_s(d,(-p+v)/g);return vs(S,h),[_,ds(S)]}}}function u(n,e){var i=r?t:gf-t,o=0;return n<-i?o|=1:n>i&&(o|=2),e<-i?o|=4:e>i&&(o|=8),o}return xl(o,(function(t){var n,e,c,f,s;return{lineStart:function(){f=c=!1,s=1},point:function(l,h){var d,p=[l,h],g=o(l,h),y=r?g?0:u(l,h):g?u(l+(l<0?gf:-gf),h):0;if(!n&&(f=c=g)&&t.lineStart(),g!==c&&(!(d=a(n,p))||gl(n,d)||gl(p,d))&&(p[2]=1),g!==c)s=0,g?(t.lineStart(),d=a(p,n),t.point(d[0],d[1])):(d=a(n,p),t.point(d[0],d[1],2),t.lineEnd()),n=d;else if(i&&n&&r^g){var v;y&e||!(v=a(p,n,!0))||(s=0,r?(t.lineStart(),t.point(v[0][0],v[0][1]),t.point(v[1][0],v[1][1]),t.lineEnd()):(t.point(v[1][0],v[1][1]),t.lineEnd(),t.lineStart(),t.point(v[0][0],v[0][1],3)))}!g||n&&gl(n,p)||t.point(p[0],p[1]),n=p,c=g,e=y},lineEnd:function(){c&&t.lineEnd(),n=null},clean:function(){return s|(f&&c)<<1}}}),(function(n,r,i,o){hl(o,t,e,i,n,r)}),r?[0,-t]:[-gf,t-gf])}var Sl,El,Nl,kl,Cl=1e9,Pl=-Cl;function zl(t,n,e,r){function i(i,o){return t<=i&&i<=e&&n<=o&&o<=r}function o(i,o,u,f){var s=0,l=0;if(null==i||(s=a(i,u))!==(l=a(o,u))||c(i,o)<0^u>0)do{f.point(0===s||3===s?t:e,s>1?r:n)}while((s=(s+u+4)%4)!==l);else f.point(o[0],o[1])}function a(r,i){return xf(r[0]-t)0?0:3:xf(r[0]-e)0?2:1:xf(r[1]-n)0?1:0:i>0?3:2}function u(t,n){return c(t.x,n.x)}function c(t,n){var e=a(t,1),r=a(n,1);return e!==r?e-r:0===e?n[1]-t[1]:1===e?t[0]-n[0]:2===e?t[1]-n[1]:n[0]-t[0]}return function(a){var c,f,s,l,h,d,p,g,y,v,_,b=a,m=pl(),x={point:w,lineStart:function(){x.point=M,f&&f.push(s=[]);v=!0,y=!1,p=g=NaN},lineEnd:function(){c&&(M(l,h),d&&y&&m.rejoin(),c.push(m.result()));x.point=w,y&&b.lineEnd()},polygonStart:function(){b=m,c=[],f=[],_=!0},polygonEnd:function(){var n=function(){for(var n=0,e=0,i=f.length;er&&(h-o)*(r-a)>(d-a)*(t-o)&&++n:d<=r&&(h-o)*(r-a)<(d-a)*(t-o)&&--n;return n}(),e=_&&n,i=(c=ft(c)).length;(e||i)&&(a.polygonStart(),e&&(a.lineStart(),o(null,null,1,a),a.lineEnd()),i&&vl(c,u,n,o,a),a.polygonEnd());b=a,c=f=s=null}};function w(t,n){i(t,n)&&b.point(t,n)}function M(o,a){var u=i(o,a);if(f&&s.push([o,a]),v)l=o,h=a,d=u,v=!1,u&&(b.lineStart(),b.point(o,a));else if(u&&y)b.point(o,a);else{var c=[p=Math.max(Pl,Math.min(Cl,p)),g=Math.max(Pl,Math.min(Cl,g))],m=[o=Math.max(Pl,Math.min(Cl,o)),a=Math.max(Pl,Math.min(Cl,a))];!function(t,n,e,r,i,o){var a,u=t[0],c=t[1],f=0,s=1,l=n[0]-u,h=n[1]-c;if(a=e-u,l||!(a>0)){if(a/=l,l<0){if(a0){if(a>s)return;a>f&&(f=a)}if(a=i-u,l||!(a<0)){if(a/=l,l<0){if(a>s)return;a>f&&(f=a)}else if(l>0){if(a0)){if(a/=h,h<0){if(a0){if(a>s)return;a>f&&(f=a)}if(a=o-c,h||!(a<0)){if(a/=h,h<0){if(a>s)return;a>f&&(f=a)}else if(h>0){if(a0&&(t[0]=u+f*l,t[1]=c+f*h),s<1&&(n[0]=u+s*l,n[1]=c+s*h),!0}}}}}(c,m,t,n,e,r)?u&&(b.lineStart(),b.point(o,a),_=!1):(y||(b.lineStart(),b.point(c[0],c[1])),b.point(m[0],m[1]),u||b.lineEnd(),_=!1)}p=o,g=a,y=u}return x}}var $l={sphere:qf,point:qf,lineStart:function(){$l.point=Rl,$l.lineEnd=Dl},lineEnd:qf,polygonStart:qf,polygonEnd:qf};function Dl(){$l.point=$l.lineEnd=qf}function Rl(t,n){El=t*=mf,Nl=Cf(n*=mf),kl=Tf(n),$l.point=Fl}function Fl(t,n){t*=mf;var e=Cf(n*=mf),r=Tf(n),i=xf(t-El),o=Tf(i),a=r*Cf(i),u=kl*e-Nl*r*o,c=Nl*e+kl*r*o;Sl.add(Mf(zf(a*a+u*u),c)),El=t,Nl=e,kl=r}function ql(t){return Sl=new T,Lf(t,$l),+Sl}var Ul=[null,null],Il={type:"LineString",coordinates:Ul};function Ol(t,n){return Ul[0]=t,Ul[1]=n,ql(Il)}var Bl={Feature:function(t,n){return Ll(t.geometry,n)},FeatureCollection:function(t,n){for(var e=t.features,r=-1,i=e.length;++r0&&(i=Ol(t[o],t[o-1]))>0&&e<=i&&r<=i&&(e+r-i)*(1-Math.pow((e-r)/i,2))df})).map(c)).concat(lt(Af(o/d)*d,i,d).filter((function(t){return xf(t%g)>df})).map(f))}return v.lines=function(){return _().map((function(t){return{type:"LineString",coordinates:t}}))},v.outline=function(){return{type:"Polygon",coordinates:[s(r).concat(l(a).slice(1),s(e).reverse().slice(1),l(u).reverse().slice(1))]}},v.extent=function(t){return arguments.length?v.extentMajor(t).extentMinor(t):v.extentMinor()},v.extentMajor=function(t){return arguments.length?(r=+t[0][0],e=+t[1][0],u=+t[0][1],a=+t[1][1],r>e&&(t=r,r=e,e=t),u>a&&(t=u,u=a,a=t),v.precision(y)):[[r,u],[e,a]]},v.extentMinor=function(e){return arguments.length?(n=+e[0][0],t=+e[1][0],o=+e[0][1],i=+e[1][1],n>t&&(e=n,n=t,t=e),o>i&&(e=o,o=i,i=e),v.precision(y)):[[n,o],[t,i]]},v.step=function(t){return arguments.length?v.stepMajor(t).stepMinor(t):v.stepMinor()},v.stepMajor=function(t){return arguments.length?(p=+t[0],g=+t[1],v):[p,g]},v.stepMinor=function(t){return arguments.length?(h=+t[0],d=+t[1],v):[h,d]},v.precision=function(h){return arguments.length?(y=+h,c=Wl(o,i,90),f=Zl(n,t,y),s=Wl(u,a,90),l=Zl(r,e,y),v):y},v.extentMajor([[-180,-90+df],[180,90-df]]).extentMinor([[-180,-80-df],[180,80+df]])}var Ql,Jl,th,nh,eh=t=>t,rh=new T,ih=new T,oh={point:qf,lineStart:qf,lineEnd:qf,polygonStart:function(){oh.lineStart=ah,oh.lineEnd=fh},polygonEnd:function(){oh.lineStart=oh.lineEnd=oh.point=qf,rh.add(xf(ih)),ih=new T},result:function(){var t=rh/2;return rh=new T,t}};function ah(){oh.point=uh}function uh(t,n){oh.point=ch,Ql=th=t,Jl=nh=n}function ch(t,n){ih.add(nh*t-th*n),th=t,nh=n}function fh(){ch(Ql,Jl)}var sh=oh,lh=1/0,hh=lh,dh=-lh,ph=dh,gh={point:function(t,n){tdh&&(dh=t);nph&&(ph=n)},lineStart:qf,lineEnd:qf,polygonStart:qf,polygonEnd:qf,result:function(){var t=[[lh,hh],[dh,ph]];return dh=ph=-(hh=lh=1/0),t}};var yh,vh,_h,bh,mh=gh,xh=0,wh=0,Mh=0,Th=0,Ah=0,Sh=0,Eh=0,Nh=0,kh=0,Ch={point:Ph,lineStart:zh,lineEnd:Rh,polygonStart:function(){Ch.lineStart=Fh,Ch.lineEnd=qh},polygonEnd:function(){Ch.point=Ph,Ch.lineStart=zh,Ch.lineEnd=Rh},result:function(){var t=kh?[Eh/kh,Nh/kh]:Sh?[Th/Sh,Ah/Sh]:Mh?[xh/Mh,wh/Mh]:[NaN,NaN];return xh=wh=Mh=Th=Ah=Sh=Eh=Nh=kh=0,t}};function Ph(t,n){xh+=t,wh+=n,++Mh}function zh(){Ch.point=$h}function $h(t,n){Ch.point=Dh,Ph(_h=t,bh=n)}function Dh(t,n){var e=t-_h,r=n-bh,i=zf(e*e+r*r);Th+=i*(_h+t)/2,Ah+=i*(bh+n)/2,Sh+=i,Ph(_h=t,bh=n)}function Rh(){Ch.point=Ph}function Fh(){Ch.point=Uh}function qh(){Ih(yh,vh)}function Uh(t,n){Ch.point=Ih,Ph(yh=_h=t,vh=bh=n)}function Ih(t,n){var e=t-_h,r=n-bh,i=zf(e*e+r*r);Th+=i*(_h+t)/2,Ah+=i*(bh+n)/2,Sh+=i,Eh+=(i=bh*t-_h*n)*(_h+t),Nh+=i*(bh+n),kh+=3*i,Ph(_h=t,bh=n)}var Oh=Ch;function Bh(t){this._context=t}Bh.prototype={_radius:4.5,pointRadius:function(t){return this._radius=t,this},polygonStart:function(){this._line=0},polygonEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){0===this._line&&this._context.closePath(),this._point=NaN},point:function(t,n){switch(this._point){case 0:this._context.moveTo(t,n),this._point=1;break;case 1:this._context.lineTo(t,n);break;default:this._context.moveTo(t+this._radius,n),this._context.arc(t,n,this._radius,0,_f)}},result:qf};var Yh,Lh,jh,Hh,Xh,Gh=new T,Vh={point:qf,lineStart:function(){Vh.point=Wh},lineEnd:function(){Yh&&Zh(Lh,jh),Vh.point=qf},polygonStart:function(){Yh=!0},polygonEnd:function(){Yh=null},result:function(){var t=+Gh;return Gh=new T,t}};function Wh(t,n){Vh.point=Zh,Lh=Hh=t,jh=Xh=n}function Zh(t,n){Hh-=t,Xh-=n,Gh.add(zf(Hh*Hh+Xh*Xh)),Hh=t,Xh=n}var Kh=Vh;let Qh,Jh,td,nd;class ed{constructor(t){this._append=null==t?rd:function(t){const n=Math.floor(t);if(!(n>=0))throw new RangeError(`invalid digits: ${t}`);if(n>15)return rd;if(n!==Qh){const t=10**n;Qh=n,Jh=function(n){let e=1;this._+=n[0];for(const r=n.length;e4*n&&g--){var m=a+h,x=u+d,w=c+p,M=zf(m*m+x*x+w*w),T=Rf(w/=M),A=xf(xf(w)-1)n||xf((v*k+_*C)/b-.5)>.3||a*h+u*d+c*p2?t[2]%360*mf:0,k()):[y*bf,v*bf,_*bf]},E.angle=function(t){return arguments.length?(b=t%360*mf,k()):b*bf},E.reflectX=function(t){return arguments.length?(m=t?-1:1,k()):m<0},E.reflectY=function(t){return arguments.length?(x=t?-1:1,k()):x<0},E.precision=function(t){return arguments.length?(a=dd(u,S=t*t),C()):zf(S)},E.fitExtent=function(t,n){return ud(E,t,n)},E.fitSize=function(t,n){return cd(E,t,n)},E.fitWidth=function(t,n){return fd(E,t,n)},E.fitHeight=function(t,n){return sd(E,t,n)},function(){return n=t.apply(this,arguments),E.invert=n.invert&&N,k()}}function _d(t){var n=0,e=gf/3,r=vd(t),i=r(n,e);return i.parallels=function(t){return arguments.length?r(n=t[0]*mf,e=t[1]*mf):[n*bf,e*bf]},i}function bd(t,n){var e=Cf(t),r=(e+Cf(n))/2;if(xf(r)0?n<-yf+df&&(n=-yf+df):n>yf-df&&(n=yf-df);var e=i/kf(Nd(n),r);return[e*Cf(r*t),i-e*Tf(r*t)]}return o.invert=function(t,n){var e=i-n,o=Pf(r)*zf(t*t+e*e),a=Mf(t,xf(e))*Pf(e);return e*r<0&&(a-=gf*Pf(t)*Pf(e)),[a/r,2*wf(kf(i/o,1/r))-yf]},o}function Cd(t,n){return[t,n]}function Pd(t,n){var e=Tf(t),r=t===n?Cf(t):(e-Tf(n))/(n-t),i=e/r+t;if(xf(r)=0;)n+=e[r].value;else n=1;t.value=n}function Gd(t,n){t instanceof Map?(t=[void 0,t],void 0===n&&(n=Wd)):void 0===n&&(n=Vd);for(var e,r,i,o,a,u=new Qd(t),c=[u];e=c.pop();)if((i=n(e.data))&&(a=(i=Array.from(i)).length))for(e.children=i,o=a-1;o>=0;--o)c.push(r=i[o]=new Qd(i[o])),r.parent=e,r.depth=e.depth+1;return u.eachBefore(Kd)}function Vd(t){return t.children}function Wd(t){return Array.isArray(t)?t[1]:null}function Zd(t){void 0!==t.data.value&&(t.value=t.data.value),t.data=t.data.data}function Kd(t){var n=0;do{t.height=n}while((t=t.parent)&&t.height<++n)}function Qd(t){this.data=t,this.depth=this.height=0,this.parent=null}function Jd(t){return null==t?null:tp(t)}function tp(t){if("function"!=typeof t)throw new Error;return t}function np(){return 0}function ep(t){return function(){return t}}qd.invert=function(t,n){for(var e,r=n,i=r*r,o=i*i*i,a=0;a<12&&(o=(i=(r-=e=(r*(zd+$d*i+o*(Dd+Rd*i))-n)/(zd+3*$d*i+o*(7*Dd+9*Rd*i)))*r)*i*i,!(xf(e)df&&--i>0);return[t/(.8707+(o=r*r)*(o*(o*o*o*(.003971-.001529*o)-.013791)-.131979)),r]},Od.invert=Md(Rf),Bd.invert=Md((function(t){return 2*wf(t)})),Yd.invert=function(t,n){return[-n,2*wf(Sf(t))-yf]},Qd.prototype=Gd.prototype={constructor:Qd,count:function(){return this.eachAfter(Xd)},each:function(t,n){let e=-1;for(const r of this)t.call(n,r,++e,this);return this},eachAfter:function(t,n){for(var e,r,i,o=this,a=[o],u=[],c=-1;o=a.pop();)if(u.push(o),e=o.children)for(r=0,i=e.length;r=0;--r)o.push(e[r]);return this},find:function(t,n){let e=-1;for(const r of this)if(t.call(n,r,++e,this))return r},sum:function(t){return this.eachAfter((function(n){for(var e=+t(n.data)||0,r=n.children,i=r&&r.length;--i>=0;)e+=r[i].value;n.value=e}))},sort:function(t){return this.eachBefore((function(n){n.children&&n.children.sort(t)}))},path:function(t){for(var n=this,e=function(t,n){if(t===n)return t;var e=t.ancestors(),r=n.ancestors(),i=null;t=e.pop(),n=r.pop();for(;t===n;)i=t,t=e.pop(),n=r.pop();return i}(n,t),r=[n];n!==e;)n=n.parent,r.push(n);for(var i=r.length;t!==e;)r.splice(i,0,t),t=t.parent;return r},ancestors:function(){for(var t=this,n=[t];t=t.parent;)n.push(t);return n},descendants:function(){return Array.from(this)},leaves:function(){var t=[];return this.eachBefore((function(n){n.children||t.push(n)})),t},links:function(){var t=this,n=[];return t.each((function(e){e!==t&&n.push({source:e.parent,target:e})})),n},copy:function(){return Gd(this).eachBefore(Zd)},[Symbol.iterator]:function*(){var t,n,e,r,i=this,o=[i];do{for(t=o.reverse(),o=[];i=t.pop();)if(yield i,n=i.children)for(e=0,r=n.length;e(t=(rp*t+ip)%op)/op}function up(t,n){for(var e,r,i=0,o=(t=function(t,n){let e,r,i=t.length;for(;i;)r=n()*i--|0,e=t[i],t[i]=t[r],t[r]=e;return t}(Array.from(t),n)).length,a=[];i0&&e*e>r*r+i*i}function lp(t,n){for(var e=0;e1e-6?(E+Math.sqrt(E*E-4*S*N))/(2*S):N/E);return{x:r+w+M*k,y:i+T+A*k,r:k}}function gp(t,n,e){var r,i,o,a,u=t.x-n.x,c=t.y-n.y,f=u*u+c*c;f?(i=n.r+e.r,i*=i,a=t.r+e.r,i>(a*=a)?(r=(f+a-i)/(2*f),o=Math.sqrt(Math.max(0,a/f-r*r)),e.x=t.x-r*u-o*c,e.y=t.y-r*c+o*u):(r=(f+i-a)/(2*f),o=Math.sqrt(Math.max(0,i/f-r*r)),e.x=n.x+r*u-o*c,e.y=n.y+r*c+o*u)):(e.x=n.x+e.r,e.y=n.y)}function yp(t,n){var e=t.r+n.r-1e-6,r=n.x-t.x,i=n.y-t.y;return e>0&&e*e>r*r+i*i}function vp(t){var n=t._,e=t.next._,r=n.r+e.r,i=(n.x*e.r+e.x*n.r)/r,o=(n.y*e.r+e.y*n.r)/r;return i*i+o*o}function _p(t){this._=t,this.next=null,this.previous=null}function bp(t,n){if(!(o=(t=function(t){return"object"==typeof t&&"length"in t?t:Array.from(t)}(t)).length))return 0;var e,r,i,o,a,u,c,f,s,l,h;if((e=t[0]).x=0,e.y=0,!(o>1))return e.r;if(r=t[1],e.x=-r.r,r.x=e.r,r.y=0,!(o>2))return e.r+r.r;gp(r,e,i=t[2]),e=new _p(e),r=new _p(r),i=new _p(i),e.next=i.previous=r,r.next=e.previous=i,i.next=r.previous=e;t:for(c=3;c1&&!zp(t,n););return t.slice(0,n)}function zp(t,n){if("/"===t[n]){let e=0;for(;n>0&&"\\"===t[--n];)++e;if(!(1&e))return!0}return!1}function $p(t,n){return t.parent===n.parent?1:2}function Dp(t){var n=t.children;return n?n[0]:t.t}function Rp(t){var n=t.children;return n?n[n.length-1]:t.t}function Fp(t,n,e){var r=e/(n.i-t.i);n.c-=r,n.s+=e,t.c+=r,n.z+=e,n.m+=e}function qp(t,n,e){return t.a.parent===n.parent?t.a:e}function Up(t,n){this._=t,this.parent=null,this.children=null,this.A=null,this.a=this,this.z=0,this.m=0,this.c=0,this.s=0,this.t=null,this.i=n}function Ip(t,n,e,r,i){for(var o,a=t.children,u=-1,c=a.length,f=t.value&&(i-e)/t.value;++uh&&(h=u),y=s*s*g,(d=Math.max(h/y,y/l))>p){s-=u;break}p=d}v.push(a={value:s,dice:c1?n:1)},e}(Op);var Lp=function t(n){function e(t,e,r,i,o){if((a=t._squarify)&&a.ratio===n)for(var a,u,c,f,s,l=-1,h=a.length,d=t.value;++l1?n:1)},e}(Op);function jp(t,n,e){return(n[0]-t[0])*(e[1]-t[1])-(n[1]-t[1])*(e[0]-t[0])}function Hp(t,n){return t[0]-n[0]||t[1]-n[1]}function Xp(t){const n=t.length,e=[0,1];let r,i=2;for(r=2;r1&&jp(t[e[i-2]],t[e[i-1]],t[r])<=0;)--i;e[i++]=r}return e.slice(0,i)}var Gp=Math.random,Vp=function t(n){function e(t,e){return t=null==t?0:+t,e=null==e?1:+e,1===arguments.length?(e=t,t=0):e-=t,function(){return n()*e+t}}return e.source=t,e}(Gp),Wp=function t(n){function e(t,e){return arguments.length<2&&(e=t,t=0),t=Math.floor(t),e=Math.floor(e)-t,function(){return Math.floor(n()*e+t)}}return e.source=t,e}(Gp),Zp=function t(n){function e(t,e){var r,i;return t=null==t?0:+t,e=null==e?1:+e,function(){var o;if(null!=r)o=r,r=null;else do{r=2*n()-1,o=2*n()-1,i=r*r+o*o}while(!i||i>1);return t+e*o*Math.sqrt(-2*Math.log(i)/i)}}return e.source=t,e}(Gp),Kp=function t(n){var e=Zp.source(n);function r(){var t=e.apply(this,arguments);return function(){return Math.exp(t())}}return r.source=t,r}(Gp),Qp=function t(n){function e(t){return(t=+t)<=0?()=>0:function(){for(var e=0,r=t;r>1;--r)e+=n();return e+r*n()}}return e.source=t,e}(Gp),Jp=function t(n){var e=Qp.source(n);function r(t){if(0==(t=+t))return n;var r=e(t);return function(){return r()/t}}return r.source=t,r}(Gp),tg=function t(n){function e(t){return function(){return-Math.log1p(-n())/t}}return e.source=t,e}(Gp),ng=function t(n){function e(t){if((t=+t)<0)throw new RangeError("invalid alpha");return t=1/-t,function(){return Math.pow(1-n(),t)}}return e.source=t,e}(Gp),eg=function t(n){function e(t){if((t=+t)<0||t>1)throw new RangeError("invalid p");return function(){return Math.floor(n()+t)}}return e.source=t,e}(Gp),rg=function t(n){function e(t){if((t=+t)<0||t>1)throw new RangeError("invalid p");return 0===t?()=>1/0:1===t?()=>1:(t=Math.log1p(-t),function(){return 1+Math.floor(Math.log1p(-n())/t)})}return e.source=t,e}(Gp),ig=function t(n){var e=Zp.source(n)();function r(t,r){if((t=+t)<0)throw new RangeError("invalid k");if(0===t)return()=>0;if(r=null==r?1:+r,1===t)return()=>-Math.log1p(-n())*r;var i=(t<1?t+1:t)-1/3,o=1/(3*Math.sqrt(i)),a=t<1?()=>Math.pow(n(),1/t):()=>1;return function(){do{do{var t=e(),u=1+o*t}while(u<=0);u*=u*u;var c=1-n()}while(c>=1-.0331*t*t*t*t&&Math.log(c)>=.5*t*t+i*(1-u+Math.log(u)));return i*u*a()*r}}return r.source=t,r}(Gp),og=function t(n){var e=ig.source(n);function r(t,n){var r=e(t),i=e(n);return function(){var t=r();return 0===t?0:t/(t+i())}}return r.source=t,r}(Gp),ag=function t(n){var e=rg.source(n),r=og.source(n);function i(t,n){return t=+t,(n=+n)>=1?()=>t:n<=0?()=>0:function(){for(var i=0,o=t,a=n;o*a>16&&o*(1-a)>16;){var u=Math.floor((o+1)*a),c=r(u,o-u+1)();c<=a?(i+=u,o-=u,a=(a-c)/(1-c)):(o=u-1,a/=c)}for(var f=a<.5,s=e(f?a:1-a),l=s(),h=0;l<=o;++h)l+=s();return i+(f?h:o-h)}}return i.source=t,i}(Gp),ug=function t(n){function e(t,e,r){var i;return 0==(t=+t)?i=t=>-Math.log(t):(t=1/t,i=n=>Math.pow(n,t)),e=null==e?0:+e,r=null==r?1:+r,function(){return e+r*i(-Math.log1p(-n()))}}return e.source=t,e}(Gp),cg=function t(n){function e(t,e){return t=null==t?0:+t,e=null==e?1:+e,function(){return t+e*Math.tan(Math.PI*n())}}return e.source=t,e}(Gp),fg=function t(n){function e(t,e){return t=null==t?0:+t,e=null==e?1:+e,function(){var r=n();return t+e*Math.log(r/(1-r))}}return e.source=t,e}(Gp),sg=function t(n){var e=ig.source(n),r=ag.source(n);function i(t){return function(){for(var i=0,o=t;o>16;){var a=Math.floor(.875*o),u=e(a)();if(u>o)return i+r(a-1,o/u)();i+=a,o-=u}for(var c=-Math.log1p(-n()),f=0;c<=o;++f)c-=Math.log1p(-n());return i+f}}return i.source=t,i}(Gp);const lg=1/4294967296;function hg(t,n){switch(arguments.length){case 0:break;case 1:this.range(t);break;default:this.range(n).domain(t)}return this}function dg(t,n){switch(arguments.length){case 0:break;case 1:"function"==typeof t?this.interpolator(t):this.range(t);break;default:this.domain(t),"function"==typeof n?this.interpolator(n):this.range(n)}return this}const pg=Symbol("implicit");function gg(){var t=new InternMap,n=[],e=[],r=pg;function i(i){let o=t.get(i);if(void 0===o){if(r!==pg)return r;t.set(i,o=n.push(i)-1)}return e[o%e.length]}return i.domain=function(e){if(!arguments.length)return n.slice();n=[],t=new InternMap;for(const r of e)t.has(r)||t.set(r,n.push(r)-1);return i},i.range=function(t){return arguments.length?(e=Array.from(t),i):e.slice()},i.unknown=function(t){return arguments.length?(r=t,i):r},i.copy=function(){return gg(n,e).unknown(r)},hg.apply(i,arguments),i}function yg(){var t,n,e=gg().unknown(void 0),r=e.domain,i=e.range,o=0,a=1,u=!1,c=0,f=0,s=.5;function l(){var e=r().length,l=an&&(e=t,t=n,n=e),function(e){return Math.max(t,Math.min(n,e))}}(a[0],a[t-1])),r=t>2?Mg:wg,i=o=null,l}function l(n){return null==n||isNaN(n=+n)?e:(i||(i=r(a.map(t),u,c)))(t(f(n)))}return l.invert=function(e){return f(n((o||(o=r(u,a.map(t),Yr)))(e)))},l.domain=function(t){return arguments.length?(a=Array.from(t,_g),s()):a.slice()},l.range=function(t){return arguments.length?(u=Array.from(t),s()):u.slice()},l.rangeRound=function(t){return u=Array.from(t),c=Vr,s()},l.clamp=function(t){return arguments.length?(f=!!t||mg,s()):f!==mg},l.interpolate=function(t){return arguments.length?(c=t,s()):c},l.unknown=function(t){return arguments.length?(e=t,l):e},function(e,r){return t=e,n=r,s()}}function Sg(){return Ag()(mg,mg)}function Eg(n,e,r,i){var o,a=W(n,e,r);switch((i=Jc(null==i?",f":i)).type){case"s":var u=Math.max(Math.abs(n),Math.abs(e));return null!=i.precision||isNaN(o=lf(a,u))||(i.precision=o),t.formatPrefix(i,u);case"":case"e":case"g":case"p":case"r":null!=i.precision||isNaN(o=hf(a,Math.max(Math.abs(n),Math.abs(e))))||(i.precision=o-("e"===i.type));break;case"f":case"%":null!=i.precision||isNaN(o=sf(a))||(i.precision=o-2*("%"===i.type))}return t.format(i)}function Ng(t){var n=t.domain;return t.ticks=function(t){var e=n();return G(e[0],e[e.length-1],null==t?10:t)},t.tickFormat=function(t,e){var r=n();return Eg(r[0],r[r.length-1],null==t?10:t,e)},t.nice=function(e){null==e&&(e=10);var r,i,o=n(),a=0,u=o.length-1,c=o[a],f=o[u],s=10;for(f0;){if((i=V(c,f,e))===r)return o[a]=c,o[u]=f,n(o);if(i>0)c=Math.floor(c/i)*i,f=Math.ceil(f/i)*i;else{if(!(i<0))break;c=Math.ceil(c*i)/i,f=Math.floor(f*i)/i}r=i}return t},t}function kg(t,n){var e,r=0,i=(t=t.slice()).length-1,o=t[r],a=t[i];return a-t(-n,e)}function Fg(n){const e=n(Cg,Pg),r=e.domain;let i,o,a=10;function u(){return i=function(t){return t===Math.E?Math.log:10===t&&Math.log10||2===t&&Math.log2||(t=Math.log(t),n=>Math.log(n)/t)}(a),o=function(t){return 10===t?Dg:t===Math.E?Math.exp:n=>Math.pow(t,n)}(a),r()[0]<0?(i=Rg(i),o=Rg(o),n(zg,$g)):n(Cg,Pg),e}return e.base=function(t){return arguments.length?(a=+t,u()):a},e.domain=function(t){return arguments.length?(r(t),u()):r()},e.ticks=t=>{const n=r();let e=n[0],u=n[n.length-1];const c=u0){for(;l<=h;++l)for(f=1;fu)break;p.push(s)}}else for(;l<=h;++l)for(f=a-1;f>=1;--f)if(s=l>0?f/o(-l):f*o(l),!(su)break;p.push(s)}2*p.length{if(null==n&&(n=10),null==r&&(r=10===a?"s":","),"function"!=typeof r&&(a%1||null!=(r=Jc(r)).precision||(r.trim=!0),r=t.format(r)),n===1/0)return r;const u=Math.max(1,a*n/e.ticks().length);return t=>{let n=t/o(Math.round(i(t)));return n*ar(kg(r(),{floor:t=>o(Math.floor(i(t))),ceil:t=>o(Math.ceil(i(t)))})),e}function qg(t){return function(n){return Math.sign(n)*Math.log1p(Math.abs(n/t))}}function Ug(t){return function(n){return Math.sign(n)*Math.expm1(Math.abs(n))*t}}function Ig(t){var n=1,e=t(qg(n),Ug(n));return e.constant=function(e){return arguments.length?t(qg(n=+e),Ug(n)):n},Ng(e)}function Og(t){return function(n){return n<0?-Math.pow(-n,t):Math.pow(n,t)}}function Bg(t){return t<0?-Math.sqrt(-t):Math.sqrt(t)}function Yg(t){return t<0?-t*t:t*t}function Lg(t){var n=t(mg,mg),e=1;return n.exponent=function(n){return arguments.length?1===(e=+n)?t(mg,mg):.5===e?t(Bg,Yg):t(Og(e),Og(1/e)):e},Ng(n)}function jg(){var t=Lg(Ag());return t.copy=function(){return Tg(t,jg()).exponent(t.exponent())},hg.apply(t,arguments),t}function Hg(t){return Math.sign(t)*t*t}const Xg=new Date,Gg=new Date;function Vg(t,n,e,r){function i(n){return t(n=0===arguments.length?new Date:new Date(+n)),n}return i.floor=n=>(t(n=new Date(+n)),n),i.ceil=e=>(t(e=new Date(e-1)),n(e,1),t(e),e),i.round=t=>{const n=i(t),e=i.ceil(t);return t-n(n(t=new Date(+t),null==e?1:Math.floor(e)),t),i.range=(e,r,o)=>{const a=[];if(e=i.ceil(e),o=null==o?1:Math.floor(o),!(e0))return a;let u;do{a.push(u=new Date(+e)),n(e,o),t(e)}while(uVg((n=>{if(n>=n)for(;t(n),!e(n);)n.setTime(n-1)}),((t,r)=>{if(t>=t)if(r<0)for(;++r<=0;)for(;n(t,-1),!e(t););else for(;--r>=0;)for(;n(t,1),!e(t););})),e&&(i.count=(n,r)=>(Xg.setTime(+n),Gg.setTime(+r),t(Xg),t(Gg),Math.floor(e(Xg,Gg))),i.every=t=>(t=Math.floor(t),isFinite(t)&&t>0?t>1?i.filter(r?n=>r(n)%t==0:n=>i.count(0,n)%t==0):i:null)),i}const Wg=Vg((()=>{}),((t,n)=>{t.setTime(+t+n)}),((t,n)=>n-t));Wg.every=t=>(t=Math.floor(t),isFinite(t)&&t>0?t>1?Vg((n=>{n.setTime(Math.floor(n/t)*t)}),((n,e)=>{n.setTime(+n+e*t)}),((n,e)=>(e-n)/t)):Wg:null);const Zg=Wg.range,Kg=1e3,Qg=6e4,Jg=36e5,ty=864e5,ny=6048e5,ey=2592e6,ry=31536e6,iy=Vg((t=>{t.setTime(t-t.getMilliseconds())}),((t,n)=>{t.setTime(+t+n*Kg)}),((t,n)=>(n-t)/Kg),(t=>t.getUTCSeconds())),oy=iy.range,ay=Vg((t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*Kg)}),((t,n)=>{t.setTime(+t+n*Qg)}),((t,n)=>(n-t)/Qg),(t=>t.getMinutes())),uy=ay.range,cy=Vg((t=>{t.setUTCSeconds(0,0)}),((t,n)=>{t.setTime(+t+n*Qg)}),((t,n)=>(n-t)/Qg),(t=>t.getUTCMinutes())),fy=cy.range,sy=Vg((t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*Kg-t.getMinutes()*Qg)}),((t,n)=>{t.setTime(+t+n*Jg)}),((t,n)=>(n-t)/Jg),(t=>t.getHours())),ly=sy.range,hy=Vg((t=>{t.setUTCMinutes(0,0,0)}),((t,n)=>{t.setTime(+t+n*Jg)}),((t,n)=>(n-t)/Jg),(t=>t.getUTCHours())),dy=hy.range,py=Vg((t=>t.setHours(0,0,0,0)),((t,n)=>t.setDate(t.getDate()+n)),((t,n)=>(n-t-(n.getTimezoneOffset()-t.getTimezoneOffset())*Qg)/ty),(t=>t.getDate()-1)),gy=py.range,yy=Vg((t=>{t.setUTCHours(0,0,0,0)}),((t,n)=>{t.setUTCDate(t.getUTCDate()+n)}),((t,n)=>(n-t)/ty),(t=>t.getUTCDate()-1)),vy=yy.range,_y=Vg((t=>{t.setUTCHours(0,0,0,0)}),((t,n)=>{t.setUTCDate(t.getUTCDate()+n)}),((t,n)=>(n-t)/ty),(t=>Math.floor(t/ty))),by=_y.range;function my(t){return Vg((n=>{n.setDate(n.getDate()-(n.getDay()+7-t)%7),n.setHours(0,0,0,0)}),((t,n)=>{t.setDate(t.getDate()+7*n)}),((t,n)=>(n-t-(n.getTimezoneOffset()-t.getTimezoneOffset())*Qg)/ny))}const xy=my(0),wy=my(1),My=my(2),Ty=my(3),Ay=my(4),Sy=my(5),Ey=my(6),Ny=xy.range,ky=wy.range,Cy=My.range,Py=Ty.range,zy=Ay.range,$y=Sy.range,Dy=Ey.range;function Ry(t){return Vg((n=>{n.setUTCDate(n.getUTCDate()-(n.getUTCDay()+7-t)%7),n.setUTCHours(0,0,0,0)}),((t,n)=>{t.setUTCDate(t.getUTCDate()+7*n)}),((t,n)=>(n-t)/ny))}const Fy=Ry(0),qy=Ry(1),Uy=Ry(2),Iy=Ry(3),Oy=Ry(4),By=Ry(5),Yy=Ry(6),Ly=Fy.range,jy=qy.range,Hy=Uy.range,Xy=Iy.range,Gy=Oy.range,Vy=By.range,Wy=Yy.range,Zy=Vg((t=>{t.setDate(1),t.setHours(0,0,0,0)}),((t,n)=>{t.setMonth(t.getMonth()+n)}),((t,n)=>n.getMonth()-t.getMonth()+12*(n.getFullYear()-t.getFullYear())),(t=>t.getMonth())),Ky=Zy.range,Qy=Vg((t=>{t.setUTCDate(1),t.setUTCHours(0,0,0,0)}),((t,n)=>{t.setUTCMonth(t.getUTCMonth()+n)}),((t,n)=>n.getUTCMonth()-t.getUTCMonth()+12*(n.getUTCFullYear()-t.getUTCFullYear())),(t=>t.getUTCMonth())),Jy=Qy.range,tv=Vg((t=>{t.setMonth(0,1),t.setHours(0,0,0,0)}),((t,n)=>{t.setFullYear(t.getFullYear()+n)}),((t,n)=>n.getFullYear()-t.getFullYear()),(t=>t.getFullYear()));tv.every=t=>isFinite(t=Math.floor(t))&&t>0?Vg((n=>{n.setFullYear(Math.floor(n.getFullYear()/t)*t),n.setMonth(0,1),n.setHours(0,0,0,0)}),((n,e)=>{n.setFullYear(n.getFullYear()+e*t)})):null;const nv=tv.range,ev=Vg((t=>{t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)}),((t,n)=>{t.setUTCFullYear(t.getUTCFullYear()+n)}),((t,n)=>n.getUTCFullYear()-t.getUTCFullYear()),(t=>t.getUTCFullYear()));ev.every=t=>isFinite(t=Math.floor(t))&&t>0?Vg((n=>{n.setUTCFullYear(Math.floor(n.getUTCFullYear()/t)*t),n.setUTCMonth(0,1),n.setUTCHours(0,0,0,0)}),((n,e)=>{n.setUTCFullYear(n.getUTCFullYear()+e*t)})):null;const rv=ev.range;function iv(t,n,e,i,o,a){const u=[[iy,1,Kg],[iy,5,5e3],[iy,15,15e3],[iy,30,3e4],[a,1,Qg],[a,5,3e5],[a,15,9e5],[a,30,18e5],[o,1,Jg],[o,3,108e5],[o,6,216e5],[o,12,432e5],[i,1,ty],[i,2,1728e5],[e,1,ny],[n,1,ey],[n,3,7776e6],[t,1,ry]];function c(n,e,i){const o=Math.abs(e-n)/i,a=r((([,,t])=>t)).right(u,o);if(a===u.length)return t.every(W(n/ry,e/ry,i));if(0===a)return Wg.every(Math.max(W(n,e,i),1));const[c,f]=u[o/u[a-1][2]=12)]},q:function(t){return 1+~~(t.getMonth()/3)},Q:k_,s:C_,S:Zv,u:Kv,U:Qv,V:t_,w:n_,W:e_,x:null,X:null,y:r_,Y:o_,Z:u_,"%":N_},m={a:function(t){return a[t.getUTCDay()]},A:function(t){return o[t.getUTCDay()]},b:function(t){return c[t.getUTCMonth()]},B:function(t){return u[t.getUTCMonth()]},c:null,d:c_,e:c_,f:d_,g:T_,G:S_,H:f_,I:s_,j:l_,L:h_,m:p_,M:g_,p:function(t){return i[+(t.getUTCHours()>=12)]},q:function(t){return 1+~~(t.getUTCMonth()/3)},Q:k_,s:C_,S:y_,u:v_,U:__,V:m_,w:x_,W:w_,x:null,X:null,y:M_,Y:A_,Z:E_,"%":N_},x={a:function(t,n,e){var r=d.exec(n.slice(e));return r?(t.w=p.get(r[0].toLowerCase()),e+r[0].length):-1},A:function(t,n,e){var r=l.exec(n.slice(e));return r?(t.w=h.get(r[0].toLowerCase()),e+r[0].length):-1},b:function(t,n,e){var r=v.exec(n.slice(e));return r?(t.m=_.get(r[0].toLowerCase()),e+r[0].length):-1},B:function(t,n,e){var r=g.exec(n.slice(e));return r?(t.m=y.get(r[0].toLowerCase()),e+r[0].length):-1},c:function(t,e,r){return T(t,n,e,r)},d:zv,e:zv,f:Uv,g:Nv,G:Ev,H:Dv,I:Dv,j:$v,L:qv,m:Pv,M:Rv,p:function(t,n,e){var r=f.exec(n.slice(e));return r?(t.p=s.get(r[0].toLowerCase()),e+r[0].length):-1},q:Cv,Q:Ov,s:Bv,S:Fv,u:Mv,U:Tv,V:Av,w:wv,W:Sv,x:function(t,n,r){return T(t,e,n,r)},X:function(t,n,e){return T(t,r,n,e)},y:Nv,Y:Ev,Z:kv,"%":Iv};function w(t,n){return function(e){var r,i,o,a=[],u=-1,c=0,f=t.length;for(e instanceof Date||(e=new Date(+e));++u53)return null;"w"in o||(o.w=1),"Z"in o?(i=(r=sv(lv(o.y,0,1))).getUTCDay(),r=i>4||0===i?qy.ceil(r):qy(r),r=yy.offset(r,7*(o.V-1)),o.y=r.getUTCFullYear(),o.m=r.getUTCMonth(),o.d=r.getUTCDate()+(o.w+6)%7):(i=(r=fv(lv(o.y,0,1))).getDay(),r=i>4||0===i?wy.ceil(r):wy(r),r=py.offset(r,7*(o.V-1)),o.y=r.getFullYear(),o.m=r.getMonth(),o.d=r.getDate()+(o.w+6)%7)}else("W"in o||"U"in o)&&("w"in o||(o.w="u"in o?o.u%7:"W"in o?1:0),i="Z"in o?sv(lv(o.y,0,1)).getUTCDay():fv(lv(o.y,0,1)).getDay(),o.m=0,o.d="W"in o?(o.w+6)%7+7*o.W-(i+5)%7:o.w+7*o.U-(i+6)%7);return"Z"in o?(o.H+=o.Z/100|0,o.M+=o.Z%100,sv(o)):fv(o)}}function T(t,n,e,r){for(var i,o,a=0,u=n.length,c=e.length;a=c)return-1;if(37===(i=n.charCodeAt(a++))){if(i=n.charAt(a++),!(o=x[i in pv?n.charAt(a++):i])||(r=o(t,e,r))<0)return-1}else if(i!=e.charCodeAt(r++))return-1}return r}return b.x=w(e,b),b.X=w(r,b),b.c=w(n,b),m.x=w(e,m),m.X=w(r,m),m.c=w(n,m),{format:function(t){var n=w(t+="",b);return n.toString=function(){return t},n},parse:function(t){var n=M(t+="",!1);return n.toString=function(){return t},n},utcFormat:function(t){var n=w(t+="",m);return n.toString=function(){return t},n},utcParse:function(t){var n=M(t+="",!0);return n.toString=function(){return t},n}}}var dv,pv={"-":"",_:" ",0:"0"},gv=/^\s*\d+/,yv=/^%/,vv=/[\\^$*+?|[\]().{}]/g;function _v(t,n,e){var r=t<0?"-":"",i=(r?-t:t)+"",o=i.length;return r+(o[t.toLowerCase(),n])))}function wv(t,n,e){var r=gv.exec(n.slice(e,e+1));return r?(t.w=+r[0],e+r[0].length):-1}function Mv(t,n,e){var r=gv.exec(n.slice(e,e+1));return r?(t.u=+r[0],e+r[0].length):-1}function Tv(t,n,e){var r=gv.exec(n.slice(e,e+2));return r?(t.U=+r[0],e+r[0].length):-1}function Av(t,n,e){var r=gv.exec(n.slice(e,e+2));return r?(t.V=+r[0],e+r[0].length):-1}function Sv(t,n,e){var r=gv.exec(n.slice(e,e+2));return r?(t.W=+r[0],e+r[0].length):-1}function Ev(t,n,e){var r=gv.exec(n.slice(e,e+4));return r?(t.y=+r[0],e+r[0].length):-1}function Nv(t,n,e){var r=gv.exec(n.slice(e,e+2));return r?(t.y=+r[0]+(+r[0]>68?1900:2e3),e+r[0].length):-1}function kv(t,n,e){var r=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(n.slice(e,e+6));return r?(t.Z=r[1]?0:-(r[2]+(r[3]||"00")),e+r[0].length):-1}function Cv(t,n,e){var r=gv.exec(n.slice(e,e+1));return r?(t.q=3*r[0]-3,e+r[0].length):-1}function Pv(t,n,e){var r=gv.exec(n.slice(e,e+2));return r?(t.m=r[0]-1,e+r[0].length):-1}function zv(t,n,e){var r=gv.exec(n.slice(e,e+2));return r?(t.d=+r[0],e+r[0].length):-1}function $v(t,n,e){var r=gv.exec(n.slice(e,e+3));return r?(t.m=0,t.d=+r[0],e+r[0].length):-1}function Dv(t,n,e){var r=gv.exec(n.slice(e,e+2));return r?(t.H=+r[0],e+r[0].length):-1}function Rv(t,n,e){var r=gv.exec(n.slice(e,e+2));return r?(t.M=+r[0],e+r[0].length):-1}function Fv(t,n,e){var r=gv.exec(n.slice(e,e+2));return r?(t.S=+r[0],e+r[0].length):-1}function qv(t,n,e){var r=gv.exec(n.slice(e,e+3));return r?(t.L=+r[0],e+r[0].length):-1}function Uv(t,n,e){var r=gv.exec(n.slice(e,e+6));return r?(t.L=Math.floor(r[0]/1e3),e+r[0].length):-1}function Iv(t,n,e){var r=yv.exec(n.slice(e,e+1));return r?e+r[0].length:-1}function Ov(t,n,e){var r=gv.exec(n.slice(e));return r?(t.Q=+r[0],e+r[0].length):-1}function Bv(t,n,e){var r=gv.exec(n.slice(e));return r?(t.s=+r[0],e+r[0].length):-1}function Yv(t,n){return _v(t.getDate(),n,2)}function Lv(t,n){return _v(t.getHours(),n,2)}function jv(t,n){return _v(t.getHours()%12||12,n,2)}function Hv(t,n){return _v(1+py.count(tv(t),t),n,3)}function Xv(t,n){return _v(t.getMilliseconds(),n,3)}function Gv(t,n){return Xv(t,n)+"000"}function Vv(t,n){return _v(t.getMonth()+1,n,2)}function Wv(t,n){return _v(t.getMinutes(),n,2)}function Zv(t,n){return _v(t.getSeconds(),n,2)}function Kv(t){var n=t.getDay();return 0===n?7:n}function Qv(t,n){return _v(xy.count(tv(t)-1,t),n,2)}function Jv(t){var n=t.getDay();return n>=4||0===n?Ay(t):Ay.ceil(t)}function t_(t,n){return t=Jv(t),_v(Ay.count(tv(t),t)+(4===tv(t).getDay()),n,2)}function n_(t){return t.getDay()}function e_(t,n){return _v(wy.count(tv(t)-1,t),n,2)}function r_(t,n){return _v(t.getFullYear()%100,n,2)}function i_(t,n){return _v((t=Jv(t)).getFullYear()%100,n,2)}function o_(t,n){return _v(t.getFullYear()%1e4,n,4)}function a_(t,n){var e=t.getDay();return _v((t=e>=4||0===e?Ay(t):Ay.ceil(t)).getFullYear()%1e4,n,4)}function u_(t){var n=t.getTimezoneOffset();return(n>0?"-":(n*=-1,"+"))+_v(n/60|0,"0",2)+_v(n%60,"0",2)}function c_(t,n){return _v(t.getUTCDate(),n,2)}function f_(t,n){return _v(t.getUTCHours(),n,2)}function s_(t,n){return _v(t.getUTCHours()%12||12,n,2)}function l_(t,n){return _v(1+yy.count(ev(t),t),n,3)}function h_(t,n){return _v(t.getUTCMilliseconds(),n,3)}function d_(t,n){return h_(t,n)+"000"}function p_(t,n){return _v(t.getUTCMonth()+1,n,2)}function g_(t,n){return _v(t.getUTCMinutes(),n,2)}function y_(t,n){return _v(t.getUTCSeconds(),n,2)}function v_(t){var n=t.getUTCDay();return 0===n?7:n}function __(t,n){return _v(Fy.count(ev(t)-1,t),n,2)}function b_(t){var n=t.getUTCDay();return n>=4||0===n?Oy(t):Oy.ceil(t)}function m_(t,n){return t=b_(t),_v(Oy.count(ev(t),t)+(4===ev(t).getUTCDay()),n,2)}function x_(t){return t.getUTCDay()}function w_(t,n){return _v(qy.count(ev(t)-1,t),n,2)}function M_(t,n){return _v(t.getUTCFullYear()%100,n,2)}function T_(t,n){return _v((t=b_(t)).getUTCFullYear()%100,n,2)}function A_(t,n){return _v(t.getUTCFullYear()%1e4,n,4)}function S_(t,n){var e=t.getUTCDay();return _v((t=e>=4||0===e?Oy(t):Oy.ceil(t)).getUTCFullYear()%1e4,n,4)}function E_(){return"+0000"}function N_(){return"%"}function k_(t){return+t}function C_(t){return Math.floor(+t/1e3)}function P_(n){return dv=hv(n),t.timeFormat=dv.format,t.timeParse=dv.parse,t.utcFormat=dv.utcFormat,t.utcParse=dv.utcParse,dv}t.timeFormat=void 0,t.timeParse=void 0,t.utcFormat=void 0,t.utcParse=void 0,P_({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});var z_="%Y-%m-%dT%H:%M:%S.%LZ";var $_=Date.prototype.toISOString?function(t){return t.toISOString()}:t.utcFormat(z_),D_=$_;var R_=+new Date("2000-01-01T00:00:00.000Z")?function(t){var n=new Date(t);return isNaN(n)?null:n}:t.utcParse(z_),F_=R_;function q_(t){return new Date(t)}function U_(t){return t instanceof Date?+t:+new Date(+t)}function I_(t,n,e,r,i,o,a,u,c,f){var s=Sg(),l=s.invert,h=s.domain,d=f(".%L"),p=f(":%S"),g=f("%I:%M"),y=f("%I %p"),v=f("%a %d"),_=f("%b %d"),b=f("%B"),m=f("%Y");function x(t){return(c(t)Fr(t[t.length-1]),ib=new Array(3).concat("d8b365f5f5f55ab4ac","a6611adfc27d80cdc1018571","a6611adfc27df5f5f580cdc1018571","8c510ad8b365f6e8c3c7eae55ab4ac01665e","8c510ad8b365f6e8c3f5f5f5c7eae55ab4ac01665e","8c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e","8c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e","5430058c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e003c30","5430058c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e003c30").map(H_),ob=rb(ib),ab=new Array(3).concat("af8dc3f7f7f77fbf7b","7b3294c2a5cfa6dba0008837","7b3294c2a5cff7f7f7a6dba0008837","762a83af8dc3e7d4e8d9f0d37fbf7b1b7837","762a83af8dc3e7d4e8f7f7f7d9f0d37fbf7b1b7837","762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b7837","762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b7837","40004b762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b783700441b","40004b762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b783700441b").map(H_),ub=rb(ab),cb=new Array(3).concat("e9a3c9f7f7f7a1d76a","d01c8bf1b6dab8e1864dac26","d01c8bf1b6daf7f7f7b8e1864dac26","c51b7de9a3c9fde0efe6f5d0a1d76a4d9221","c51b7de9a3c9fde0eff7f7f7e6f5d0a1d76a4d9221","c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221","c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221","8e0152c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221276419","8e0152c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221276419").map(H_),fb=rb(cb),sb=new Array(3).concat("998ec3f7f7f7f1a340","5e3c99b2abd2fdb863e66101","5e3c99b2abd2f7f7f7fdb863e66101","542788998ec3d8daebfee0b6f1a340b35806","542788998ec3d8daebf7f7f7fee0b6f1a340b35806","5427888073acb2abd2d8daebfee0b6fdb863e08214b35806","5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b35806","2d004b5427888073acb2abd2d8daebfee0b6fdb863e08214b358067f3b08","2d004b5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b358067f3b08").map(H_),lb=rb(sb),hb=new Array(3).concat("ef8a62f7f7f767a9cf","ca0020f4a58292c5de0571b0","ca0020f4a582f7f7f792c5de0571b0","b2182bef8a62fddbc7d1e5f067a9cf2166ac","b2182bef8a62fddbc7f7f7f7d1e5f067a9cf2166ac","b2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac","b2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac","67001fb2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac053061","67001fb2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac053061").map(H_),db=rb(hb),pb=new Array(3).concat("ef8a62ffffff999999","ca0020f4a582bababa404040","ca0020f4a582ffffffbababa404040","b2182bef8a62fddbc7e0e0e09999994d4d4d","b2182bef8a62fddbc7ffffffe0e0e09999994d4d4d","b2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d","b2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d","67001fb2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d1a1a1a","67001fb2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d1a1a1a").map(H_),gb=rb(pb),yb=new Array(3).concat("fc8d59ffffbf91bfdb","d7191cfdae61abd9e92c7bb6","d7191cfdae61ffffbfabd9e92c7bb6","d73027fc8d59fee090e0f3f891bfdb4575b4","d73027fc8d59fee090ffffbfe0f3f891bfdb4575b4","d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4","d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4","a50026d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4313695","a50026d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4313695").map(H_),vb=rb(yb),_b=new Array(3).concat("fc8d59ffffbf91cf60","d7191cfdae61a6d96a1a9641","d7191cfdae61ffffbfa6d96a1a9641","d73027fc8d59fee08bd9ef8b91cf601a9850","d73027fc8d59fee08bffffbfd9ef8b91cf601a9850","d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850","d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850","a50026d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850006837","a50026d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850006837").map(H_),bb=rb(_b),mb=new Array(3).concat("fc8d59ffffbf99d594","d7191cfdae61abdda42b83ba","d7191cfdae61ffffbfabdda42b83ba","d53e4ffc8d59fee08be6f59899d5943288bd","d53e4ffc8d59fee08bffffbfe6f59899d5943288bd","d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd","d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd","9e0142d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd5e4fa2","9e0142d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd5e4fa2").map(H_),xb=rb(mb),wb=new Array(3).concat("e5f5f999d8c92ca25f","edf8fbb2e2e266c2a4238b45","edf8fbb2e2e266c2a42ca25f006d2c","edf8fbccece699d8c966c2a42ca25f006d2c","edf8fbccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45006d2c00441b").map(H_),Mb=rb(wb),Tb=new Array(3).concat("e0ecf49ebcda8856a7","edf8fbb3cde38c96c688419d","edf8fbb3cde38c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d810f7c4d004b").map(H_),Ab=rb(Tb),Sb=new Array(3).concat("e0f3dba8ddb543a2ca","f0f9e8bae4bc7bccc42b8cbe","f0f9e8bae4bc7bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe0868ac084081").map(H_),Eb=rb(Sb),Nb=new Array(3).concat("fee8c8fdbb84e34a33","fef0d9fdcc8afc8d59d7301f","fef0d9fdcc8afc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301fb300007f0000").map(H_),kb=rb(Nb),Cb=new Array(3).concat("ece2f0a6bddb1c9099","f6eff7bdc9e167a9cf02818a","f6eff7bdc9e167a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016c59014636").map(H_),Pb=rb(Cb),zb=new Array(3).concat("ece7f2a6bddb2b8cbe","f1eef6bdc9e174a9cf0570b0","f1eef6bdc9e174a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0045a8d023858").map(H_),$b=rb(zb),Db=new Array(3).concat("e7e1efc994c7dd1c77","f1eef6d7b5d8df65b0ce1256","f1eef6d7b5d8df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125698004367001f").map(H_),Rb=rb(Db),Fb=new Array(3).concat("fde0ddfa9fb5c51b8a","feebe2fbb4b9f768a1ae017e","feebe2fbb4b9f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a017749006a").map(H_),qb=rb(Fb),Ub=new Array(3).concat("edf8b17fcdbb2c7fb8","ffffcca1dab441b6c4225ea8","ffffcca1dab441b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea8253494081d58").map(H_),Ib=rb(Ub),Ob=new Array(3).concat("f7fcb9addd8e31a354","ffffccc2e69978c679238443","ffffccc2e69978c67931a354006837","ffffccd9f0a3addd8e78c67931a354006837","ffffccd9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443006837004529").map(H_),Bb=rb(Ob),Yb=new Array(3).concat("fff7bcfec44fd95f0e","ffffd4fed98efe9929cc4c02","ffffd4fed98efe9929d95f0e993404","ffffd4fee391fec44ffe9929d95f0e993404","ffffd4fee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c02993404662506").map(H_),Lb=rb(Yb),jb=new Array(3).concat("ffeda0feb24cf03b20","ffffb2fecc5cfd8d3ce31a1c","ffffb2fecc5cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cbd0026800026").map(H_),Hb=rb(jb),Xb=new Array(3).concat("deebf79ecae13182bd","eff3ffbdd7e76baed62171b5","eff3ffbdd7e76baed63182bd08519c","eff3ffc6dbef9ecae16baed63182bd08519c","eff3ffc6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b508519c08306b").map(H_),Gb=rb(Xb),Vb=new Array(3).concat("e5f5e0a1d99b31a354","edf8e9bae4b374c476238b45","edf8e9bae4b374c47631a354006d2c","edf8e9c7e9c0a1d99b74c47631a354006d2c","edf8e9c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45006d2c00441b").map(H_),Wb=rb(Vb),Zb=new Array(3).concat("f0f0f0bdbdbd636363","f7f7f7cccccc969696525252","f7f7f7cccccc969696636363252525","f7f7f7d9d9d9bdbdbd969696636363252525","f7f7f7d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525000000").map(H_),Kb=rb(Zb),Qb=new Array(3).concat("efedf5bcbddc756bb1","f2f0f7cbc9e29e9ac86a51a3","f2f0f7cbc9e29e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a354278f3f007d").map(H_),Jb=rb(Qb),tm=new Array(3).concat("fee0d2fc9272de2d26","fee5d9fcae91fb6a4acb181d","fee5d9fcae91fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181da50f1567000d").map(H_),nm=rb(tm),em=new Array(3).concat("fee6cefdae6be6550d","feeddefdbe85fd8d3cd94701","feeddefdbe85fd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d94801a636037f2704").map(H_),rm=rb(em);var im=hi(Tr(300,.5,0),Tr(-240,.5,1)),om=hi(Tr(-100,.75,.35),Tr(80,1.5,.8)),am=hi(Tr(260,.75,.35),Tr(80,1.5,.8)),um=Tr();var cm=Fe(),fm=Math.PI/3,sm=2*Math.PI/3;function lm(t){var n=t.length;return function(e){return t[Math.max(0,Math.min(n-1,Math.floor(e*n)))]}}var hm=lm(H_("44015444025645045745055946075a46085c460a5d460b5e470d60470e6147106347116447136548146748166848176948186a481a6c481b6d481c6e481d6f481f70482071482173482374482475482576482677482878482979472a7a472c7a472d7b472e7c472f7d46307e46327e46337f463480453581453781453882443983443a83443b84433d84433e85423f854240864241864142874144874045884046883f47883f48893e49893e4a893e4c8a3d4d8a3d4e8a3c4f8a3c508b3b518b3b528b3a538b3a548c39558c39568c38588c38598c375a8c375b8d365c8d365d8d355e8d355f8d34608d34618d33628d33638d32648e32658e31668e31678e31688e30698e306a8e2f6b8e2f6c8e2e6d8e2e6e8e2e6f8e2d708e2d718e2c718e2c728e2c738e2b748e2b758e2a768e2a778e2a788e29798e297a8e297b8e287c8e287d8e277e8e277f8e27808e26818e26828e26828e25838e25848e25858e24868e24878e23888e23898e238a8d228b8d228c8d228d8d218e8d218f8d21908d21918c20928c20928c20938c1f948c1f958b1f968b1f978b1f988b1f998a1f9a8a1e9b8a1e9c891e9d891f9e891f9f881fa0881fa1881fa1871fa28720a38620a48621a58521a68522a78522a88423a98324aa8325ab8225ac8226ad8127ad8128ae8029af7f2ab07f2cb17e2db27d2eb37c2fb47c31b57b32b67a34b67935b77937b87838b9773aba763bbb753dbc743fbc7340bd7242be7144bf7046c06f48c16e4ac16d4cc26c4ec36b50c46a52c56954c56856c66758c7655ac8645cc8635ec96260ca6063cb5f65cb5e67cc5c69cd5b6ccd5a6ece5870cf5773d05675d05477d1537ad1517cd2507fd34e81d34d84d44b86d54989d5488bd6468ed64590d74393d74195d84098d83e9bd93c9dd93ba0da39a2da37a5db36a8db34aadc32addc30b0dd2fb2dd2db5de2bb8de29bade28bddf26c0df25c2df23c5e021c8e020cae11fcde11dd0e11cd2e21bd5e21ad8e219dae319dde318dfe318e2e418e5e419e7e419eae51aece51befe51cf1e51df4e61ef6e620f8e621fbe723fde725")),dm=lm(H_("00000401000501010601010802010902020b02020d03030f03031204041405041606051806051a07061c08071e0907200a08220b09240c09260d0a290e0b2b100b2d110c2f120d31130d34140e36150e38160f3b180f3d19103f1a10421c10441d11471e114920114b21114e22115024125325125527125829115a2a115c2c115f2d11612f116331116533106734106936106b38106c390f6e3b0f703d0f713f0f72400f74420f75440f764510774710784910784a10794c117a4e117b4f127b51127c52137c54137d56147d57157e59157e5a167e5c167f5d177f5f187f601880621980641a80651a80671b80681c816a1c816b1d816d1d816e1e81701f81721f817320817521817621817822817922827b23827c23827e24828025828125818326818426818627818827818928818b29818c29818e2a81902a81912b81932b80942c80962c80982d80992d809b2e7f9c2e7f9e2f7fa02f7fa1307ea3307ea5317ea6317da8327daa337dab337cad347cae347bb0357bb2357bb3367ab5367ab73779b83779ba3878bc3978bd3977bf3a77c03a76c23b75c43c75c53c74c73d73c83e73ca3e72cc3f71cd4071cf4070d0416fd2426fd3436ed5446dd6456cd8456cd9466bdb476adc4869de4968df4a68e04c67e24d66e34e65e44f64e55064e75263e85362e95462ea5661eb5760ec5860ed5a5fee5b5eef5d5ef05f5ef1605df2625df2645cf3655cf4675cf4695cf56b5cf66c5cf66e5cf7705cf7725cf8745cf8765cf9785df9795df97b5dfa7d5efa7f5efa815ffb835ffb8560fb8761fc8961fc8a62fc8c63fc8e64fc9065fd9266fd9467fd9668fd9869fd9a6afd9b6bfe9d6cfe9f6dfea16efea36ffea571fea772fea973feaa74feac76feae77feb078feb27afeb47bfeb67cfeb77efeb97ffebb81febd82febf84fec185fec287fec488fec68afec88cfeca8dfecc8ffecd90fecf92fed194fed395fed597fed799fed89afdda9cfddc9efddea0fde0a1fde2a3fde3a5fde5a7fde7a9fde9aafdebacfcecaefceeb0fcf0b2fcf2b4fcf4b6fcf6b8fcf7b9fcf9bbfcfbbdfcfdbf")),pm=lm(H_("00000401000501010601010802010a02020c02020e03021004031204031405041706041907051b08051d09061f0a07220b07240c08260d08290e092b10092d110a30120a32140b34150b37160b39180c3c190c3e1b0c411c0c431e0c451f0c48210c4a230c4c240c4f260c51280b53290b552b0b572d0b592f0a5b310a5c320a5e340a5f3609613809623909633b09643d09653e0966400a67420a68440a68450a69470b6a490b6a4a0c6b4c0c6b4d0d6c4f0d6c510e6c520e6d540f6d550f6d57106e59106e5a116e5c126e5d126e5f136e61136e62146e64156e65156e67166e69166e6a176e6c186e6d186e6f196e71196e721a6e741a6e751b6e771c6d781c6d7a1d6d7c1d6d7d1e6d7f1e6c801f6c82206c84206b85216b87216b88226a8a226a8c23698d23698f24699025689225689326679526679727669827669a28659b29649d29649f2a63a02a63a22b62a32c61a52c60a62d60a82e5fa92e5eab2f5ead305dae305cb0315bb1325ab3325ab43359b63458b73557b93556ba3655bc3754bd3853bf3952c03a51c13a50c33b4fc43c4ec63d4dc73e4cc83f4bca404acb4149cc4248ce4347cf4446d04545d24644d34743d44842d54a41d74b3fd84c3ed94d3dda4e3cdb503bdd513ade5238df5337e05536e15635e25734e35933e45a31e55c30e65d2fe75e2ee8602de9612bea632aeb6429eb6628ec6726ed6925ee6a24ef6c23ef6e21f06f20f1711ff1731df2741cf3761bf37819f47918f57b17f57d15f67e14f68013f78212f78410f8850ff8870ef8890cf98b0bf98c0af98e09fa9008fa9207fa9407fb9606fb9706fb9906fb9b06fb9d07fc9f07fca108fca309fca50afca60cfca80dfcaa0ffcac11fcae12fcb014fcb216fcb418fbb61afbb81dfbba1ffbbc21fbbe23fac026fac228fac42afac62df9c72ff9c932f9cb35f8cd37f8cf3af7d13df7d340f6d543f6d746f5d949f5db4cf4dd4ff4df53f4e156f3e35af3e55df2e661f2e865f2ea69f1ec6df1ed71f1ef75f1f179f2f27df2f482f3f586f3f68af4f88ef5f992f6fa96f8fb9af9fc9dfafda1fcffa4")),gm=lm(H_("0d088710078813078916078a19068c1b068d1d068e20068f2206902406912605912805922a05932c05942e05952f059631059733059735049837049938049a3a049a3c049b3e049c3f049c41049d43039e44039e46039f48039f4903a04b03a14c02a14e02a25002a25102a35302a35502a45601a45801a45901a55b01a55c01a65e01a66001a66100a76300a76400a76600a76700a86900a86a00a86c00a86e00a86f00a87100a87201a87401a87501a87701a87801a87a02a87b02a87d03a87e03a88004a88104a78305a78405a78606a68707a68808a68a09a58b0aa58d0ba58e0ca48f0da4910ea3920fa39410a29511a19613a19814a099159f9a169f9c179e9d189d9e199da01a9ca11b9ba21d9aa31e9aa51f99a62098a72197a82296aa2395ab2494ac2694ad2793ae2892b02991b12a90b22b8fb32c8eb42e8db52f8cb6308bb7318ab83289ba3388bb3488bc3587bd3786be3885bf3984c03a83c13b82c23c81c33d80c43e7fc5407ec6417dc7427cc8437bc9447aca457acb4679cc4778cc4977cd4a76ce4b75cf4c74d04d73d14e72d24f71d35171d45270d5536fd5546ed6556dd7566cd8576bd9586ada5a6ada5b69db5c68dc5d67dd5e66de5f65de6164df6263e06363e16462e26561e26660e3685fe4695ee56a5de56b5de66c5ce76e5be76f5ae87059e97158e97257ea7457eb7556eb7655ec7754ed7953ed7a52ee7b51ef7c51ef7e50f07f4ff0804ef1814df1834cf2844bf3854bf3874af48849f48948f58b47f58c46f68d45f68f44f79044f79143f79342f89441f89540f9973ff9983ef99a3efa9b3dfa9c3cfa9e3bfb9f3afba139fba238fca338fca537fca636fca835fca934fdab33fdac33fdae32fdaf31fdb130fdb22ffdb42ffdb52efeb72dfeb82cfeba2cfebb2bfebd2afebe2afec029fdc229fdc328fdc527fdc627fdc827fdca26fdcb26fccd25fcce25fcd025fcd225fbd324fbd524fbd724fad824fada24f9dc24f9dd25f8df25f8e125f7e225f7e425f6e626f6e826f5e926f5eb27f4ed27f3ee27f3f027f2f227f1f426f1f525f0f724f0f921"));function ym(t){return function(){return t}}const vm=Math.abs,_m=Math.atan2,bm=Math.cos,mm=Math.max,xm=Math.min,wm=Math.sin,Mm=Math.sqrt,Tm=1e-12,Am=Math.PI,Sm=Am/2,Em=2*Am;function Nm(t){return t>=1?Sm:t<=-1?-Sm:Math.asin(t)}function km(t){let n=3;return t.digits=function(e){if(!arguments.length)return n;if(null==e)n=null;else{const t=Math.floor(e);if(!(t>=0))throw new RangeError(`invalid digits: ${e}`);n=t}return t},()=>new Ua(n)}function Cm(t){return t.innerRadius}function Pm(t){return t.outerRadius}function zm(t){return t.startAngle}function $m(t){return t.endAngle}function Dm(t){return t&&t.padAngle}function Rm(t,n,e,r,i,o,a){var u=t-e,c=n-r,f=(a?o:-o)/Mm(u*u+c*c),s=f*c,l=-f*u,h=t+s,d=n+l,p=e+s,g=r+l,y=(h+p)/2,v=(d+g)/2,_=p-h,b=g-d,m=_*_+b*b,x=i-o,w=h*g-p*d,M=(b<0?-1:1)*Mm(mm(0,x*x*m-w*w)),T=(w*b-_*M)/m,A=(-w*_-b*M)/m,S=(w*b+_*M)/m,E=(-w*_+b*M)/m,N=T-y,k=A-v,C=S-y,P=E-v;return N*N+k*k>C*C+P*P&&(T=S,A=E),{cx:T,cy:A,x01:-s,y01:-l,x11:T*(i/x-1),y11:A*(i/x-1)}}var Fm=Array.prototype.slice;function qm(t){return"object"==typeof t&&"length"in t?t:Array.from(t)}function Um(t){this._context=t}function Im(t){return new Um(t)}function Om(t){return t[0]}function Bm(t){return t[1]}function Ym(t,n){var e=ym(!0),r=null,i=Im,o=null,a=km(u);function u(u){var c,f,s,l=(u=qm(u)).length,h=!1;for(null==r&&(o=i(s=a())),c=0;c<=l;++c)!(c=l;--h)u.point(v[h],_[h]);u.lineEnd(),u.areaEnd()}y&&(v[s]=+t(d,s,f),_[s]=+n(d,s,f),u.point(r?+r(d,s,f):v[s],e?+e(d,s,f):_[s]))}if(p)return u=null,p+""||null}function s(){return Ym().defined(i).curve(a).context(o)}return t="function"==typeof t?t:void 0===t?Om:ym(+t),n="function"==typeof n?n:ym(void 0===n?0:+n),e="function"==typeof e?e:void 0===e?Bm:ym(+e),f.x=function(n){return arguments.length?(t="function"==typeof n?n:ym(+n),r=null,f):t},f.x0=function(n){return arguments.length?(t="function"==typeof n?n:ym(+n),f):t},f.x1=function(t){return arguments.length?(r=null==t?null:"function"==typeof t?t:ym(+t),f):r},f.y=function(t){return arguments.length?(n="function"==typeof t?t:ym(+t),e=null,f):n},f.y0=function(t){return arguments.length?(n="function"==typeof t?t:ym(+t),f):n},f.y1=function(t){return arguments.length?(e=null==t?null:"function"==typeof t?t:ym(+t),f):e},f.lineX0=f.lineY0=function(){return s().x(t).y(n)},f.lineY1=function(){return s().x(t).y(e)},f.lineX1=function(){return s().x(r).y(n)},f.defined=function(t){return arguments.length?(i="function"==typeof t?t:ym(!!t),f):i},f.curve=function(t){return arguments.length?(a=t,null!=o&&(u=a(o)),f):a},f.context=function(t){return arguments.length?(null==t?o=u=null:u=a(o=t),f):o},f}function jm(t,n){return nt?1:n>=t?0:NaN}function Hm(t){return t}Um.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2;default:this._context.lineTo(t,n)}}};var Xm=Vm(Im);function Gm(t){this._curve=t}function Vm(t){function n(n){return new Gm(t(n))}return n._curve=t,n}function Wm(t){var n=t.curve;return t.angle=t.x,delete t.x,t.radius=t.y,delete t.y,t.curve=function(t){return arguments.length?n(Vm(t)):n()._curve},t}function Zm(){return Wm(Ym().curve(Xm))}function Km(){var t=Lm().curve(Xm),n=t.curve,e=t.lineX0,r=t.lineX1,i=t.lineY0,o=t.lineY1;return t.angle=t.x,delete t.x,t.startAngle=t.x0,delete t.x0,t.endAngle=t.x1,delete t.x1,t.radius=t.y,delete t.y,t.innerRadius=t.y0,delete t.y0,t.outerRadius=t.y1,delete t.y1,t.lineStartAngle=function(){return Wm(e())},delete t.lineX0,t.lineEndAngle=function(){return Wm(r())},delete t.lineX1,t.lineInnerRadius=function(){return Wm(i())},delete t.lineY0,t.lineOuterRadius=function(){return Wm(o())},delete t.lineY1,t.curve=function(t){return arguments.length?n(Vm(t)):n()._curve},t}function Qm(t,n){return[(n=+n)*Math.cos(t-=Math.PI/2),n*Math.sin(t)]}Gm.prototype={areaStart:function(){this._curve.areaStart()},areaEnd:function(){this._curve.areaEnd()},lineStart:function(){this._curve.lineStart()},lineEnd:function(){this._curve.lineEnd()},point:function(t,n){this._curve.point(n*Math.sin(t),n*-Math.cos(t))}};class Jm{constructor(t,n){this._context=t,this._x=n}areaStart(){this._line=0}areaEnd(){this._line=NaN}lineStart(){this._point=0}lineEnd(){(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line}point(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2;default:this._x?this._context.bezierCurveTo(this._x0=(this._x0+t)/2,this._y0,this._x0,n,t,n):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+n)/2,t,this._y0,t,n)}this._x0=t,this._y0=n}}class tx{constructor(t){this._context=t}lineStart(){this._point=0}lineEnd(){}point(t,n){if(t=+t,n=+n,0===this._point)this._point=1;else{const e=Qm(this._x0,this._y0),r=Qm(this._x0,this._y0=(this._y0+n)/2),i=Qm(t,this._y0),o=Qm(t,n);this._context.moveTo(...e),this._context.bezierCurveTo(...r,...i,...o)}this._x0=t,this._y0=n}}function nx(t){return new Jm(t,!0)}function ex(t){return new Jm(t,!1)}function rx(t){return new tx(t)}function ix(t){return t.source}function ox(t){return t.target}function ax(t){let n=ix,e=ox,r=Om,i=Bm,o=null,a=null,u=km(c);function c(){let c;const f=Fm.call(arguments),s=n.apply(this,f),l=e.apply(this,f);if(null==o&&(a=t(c=u())),a.lineStart(),f[0]=s,a.point(+r.apply(this,f),+i.apply(this,f)),f[0]=l,a.point(+r.apply(this,f),+i.apply(this,f)),a.lineEnd(),c)return a=null,c+""||null}return c.source=function(t){return arguments.length?(n=t,c):n},c.target=function(t){return arguments.length?(e=t,c):e},c.x=function(t){return arguments.length?(r="function"==typeof t?t:ym(+t),c):r},c.y=function(t){return arguments.length?(i="function"==typeof t?t:ym(+t),c):i},c.context=function(n){return arguments.length?(null==n?o=a=null:a=t(o=n),c):o},c}const ux=Mm(3);var cx={draw(t,n){const e=.59436*Mm(n+xm(n/28,.75)),r=e/2,i=r*ux;t.moveTo(0,e),t.lineTo(0,-e),t.moveTo(-i,-r),t.lineTo(i,r),t.moveTo(-i,r),t.lineTo(i,-r)}},fx={draw(t,n){const e=Mm(n/Am);t.moveTo(e,0),t.arc(0,0,e,0,Em)}},sx={draw(t,n){const e=Mm(n/5)/2;t.moveTo(-3*e,-e),t.lineTo(-e,-e),t.lineTo(-e,-3*e),t.lineTo(e,-3*e),t.lineTo(e,-e),t.lineTo(3*e,-e),t.lineTo(3*e,e),t.lineTo(e,e),t.lineTo(e,3*e),t.lineTo(-e,3*e),t.lineTo(-e,e),t.lineTo(-3*e,e),t.closePath()}};const lx=Mm(1/3),hx=2*lx;var dx={draw(t,n){const e=Mm(n/hx),r=e*lx;t.moveTo(0,-e),t.lineTo(r,0),t.lineTo(0,e),t.lineTo(-r,0),t.closePath()}},px={draw(t,n){const e=.62625*Mm(n);t.moveTo(0,-e),t.lineTo(e,0),t.lineTo(0,e),t.lineTo(-e,0),t.closePath()}},gx={draw(t,n){const e=.87559*Mm(n-xm(n/7,2));t.moveTo(-e,0),t.lineTo(e,0),t.moveTo(0,e),t.lineTo(0,-e)}},yx={draw(t,n){const e=Mm(n),r=-e/2;t.rect(r,r,e,e)}},vx={draw(t,n){const e=.4431*Mm(n);t.moveTo(e,e),t.lineTo(e,-e),t.lineTo(-e,-e),t.lineTo(-e,e),t.closePath()}};const _x=wm(Am/10)/wm(7*Am/10),bx=wm(Em/10)*_x,mx=-bm(Em/10)*_x;var xx={draw(t,n){const e=Mm(.8908130915292852*n),r=bx*e,i=mx*e;t.moveTo(0,-e),t.lineTo(r,i);for(let n=1;n<5;++n){const o=Em*n/5,a=bm(o),u=wm(o);t.lineTo(u*e,-a*e),t.lineTo(a*r-u*i,u*r+a*i)}t.closePath()}};const wx=Mm(3);var Mx={draw(t,n){const e=-Mm(n/(3*wx));t.moveTo(0,2*e),t.lineTo(-wx*e,-e),t.lineTo(wx*e,-e),t.closePath()}};const Tx=Mm(3);var Ax={draw(t,n){const e=.6824*Mm(n),r=e/2,i=e*Tx/2;t.moveTo(0,-e),t.lineTo(i,r),t.lineTo(-i,r),t.closePath()}};const Sx=-.5,Ex=Mm(3)/2,Nx=1/Mm(12),kx=3*(Nx/2+1);var Cx={draw(t,n){const e=Mm(n/kx),r=e/2,i=e*Nx,o=r,a=e*Nx+e,u=-o,c=a;t.moveTo(r,i),t.lineTo(o,a),t.lineTo(u,c),t.lineTo(Sx*r-Ex*i,Ex*r+Sx*i),t.lineTo(Sx*o-Ex*a,Ex*o+Sx*a),t.lineTo(Sx*u-Ex*c,Ex*u+Sx*c),t.lineTo(Sx*r+Ex*i,Sx*i-Ex*r),t.lineTo(Sx*o+Ex*a,Sx*a-Ex*o),t.lineTo(Sx*u+Ex*c,Sx*c-Ex*u),t.closePath()}},Px={draw(t,n){const e=.6189*Mm(n-xm(n/6,1.7));t.moveTo(-e,-e),t.lineTo(e,e),t.moveTo(-e,e),t.lineTo(e,-e)}};const zx=[fx,sx,dx,yx,xx,Mx,Cx],$x=[fx,gx,Px,Ax,cx,vx,px];function Dx(){}function Rx(t,n,e){t._context.bezierCurveTo((2*t._x0+t._x1)/3,(2*t._y0+t._y1)/3,(t._x0+2*t._x1)/3,(t._y0+2*t._y1)/3,(t._x0+4*t._x1+n)/6,(t._y0+4*t._y1+e)/6)}function Fx(t){this._context=t}function qx(t){this._context=t}function Ux(t){this._context=t}function Ix(t,n){this._basis=new Fx(t),this._beta=n}Fx.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:Rx(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:Rx(this,t,n)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=n}},qx.prototype={areaStart:Dx,areaEnd:Dx,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x2,this._y2),this._context.closePath();break;case 2:this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break;case 3:this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4)}},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._x2=t,this._y2=n;break;case 1:this._point=2,this._x3=t,this._y3=n;break;case 2:this._point=3,this._x4=t,this._y4=n,this._context.moveTo((this._x0+4*this._x1+t)/6,(this._y0+4*this._y1+n)/6);break;default:Rx(this,t,n)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=n}},Ux.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var e=(this._x0+4*this._x1+t)/6,r=(this._y0+4*this._y1+n)/6;this._line?this._context.lineTo(e,r):this._context.moveTo(e,r);break;case 3:this._point=4;default:Rx(this,t,n)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=n}},Ix.prototype={lineStart:function(){this._x=[],this._y=[],this._basis.lineStart()},lineEnd:function(){var t=this._x,n=this._y,e=t.length-1;if(e>0)for(var r,i=t[0],o=n[0],a=t[e]-i,u=n[e]-o,c=-1;++c<=e;)r=c/e,this._basis.point(this._beta*t[c]+(1-this._beta)*(i+r*a),this._beta*n[c]+(1-this._beta)*(o+r*u));this._x=this._y=null,this._basis.lineEnd()},point:function(t,n){this._x.push(+t),this._y.push(+n)}};var Ox=function t(n){function e(t){return 1===n?new Fx(t):new Ix(t,n)}return e.beta=function(n){return t(+n)},e}(.85);function Bx(t,n,e){t._context.bezierCurveTo(t._x1+t._k*(t._x2-t._x0),t._y1+t._k*(t._y2-t._y0),t._x2+t._k*(t._x1-n),t._y2+t._k*(t._y1-e),t._x2,t._y2)}function Yx(t,n){this._context=t,this._k=(1-n)/6}Yx.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:Bx(this,this._x1,this._y1)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2,this._x1=t,this._y1=n;break;case 2:this._point=3;default:Bx(this,t,n)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var Lx=function t(n){function e(t){return new Yx(t,n)}return e.tension=function(n){return t(+n)},e}(0);function jx(t,n){this._context=t,this._k=(1-n)/6}jx.prototype={areaStart:Dx,areaEnd:Dx,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x3,this._y3),this._context.closePath();break;case 2:this._context.lineTo(this._x3,this._y3),this._context.closePath();break;case 3:this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5)}},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._x3=t,this._y3=n;break;case 1:this._point=2,this._context.moveTo(this._x4=t,this._y4=n);break;case 2:this._point=3,this._x5=t,this._y5=n;break;default:Bx(this,t,n)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var Hx=function t(n){function e(t){return new jx(t,n)}return e.tension=function(n){return t(+n)},e}(0);function Xx(t,n){this._context=t,this._k=(1-n)/6}Xx.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:Bx(this,t,n)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var Gx=function t(n){function e(t){return new Xx(t,n)}return e.tension=function(n){return t(+n)},e}(0);function Vx(t,n,e){var r=t._x1,i=t._y1,o=t._x2,a=t._y2;if(t._l01_a>Tm){var u=2*t._l01_2a+3*t._l01_a*t._l12_a+t._l12_2a,c=3*t._l01_a*(t._l01_a+t._l12_a);r=(r*u-t._x0*t._l12_2a+t._x2*t._l01_2a)/c,i=(i*u-t._y0*t._l12_2a+t._y2*t._l01_2a)/c}if(t._l23_a>Tm){var f=2*t._l23_2a+3*t._l23_a*t._l12_a+t._l12_2a,s=3*t._l23_a*(t._l23_a+t._l12_a);o=(o*f+t._x1*t._l23_2a-n*t._l12_2a)/s,a=(a*f+t._y1*t._l23_2a-e*t._l12_2a)/s}t._context.bezierCurveTo(r,i,o,a,t._x2,t._y2)}function Wx(t,n){this._context=t,this._alpha=n}Wx.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:this.point(this._x2,this._y2)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){if(t=+t,n=+n,this._point){var e=this._x2-t,r=this._y2-n;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(e*e+r*r,this._alpha))}switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2;break;case 2:this._point=3;default:Vx(this,t,n)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var Zx=function t(n){function e(t){return n?new Wx(t,n):new Yx(t,0)}return e.alpha=function(n){return t(+n)},e}(.5);function Kx(t,n){this._context=t,this._alpha=n}Kx.prototype={areaStart:Dx,areaEnd:Dx,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x3,this._y3),this._context.closePath();break;case 2:this._context.lineTo(this._x3,this._y3),this._context.closePath();break;case 3:this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5)}},point:function(t,n){if(t=+t,n=+n,this._point){var e=this._x2-t,r=this._y2-n;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(e*e+r*r,this._alpha))}switch(this._point){case 0:this._point=1,this._x3=t,this._y3=n;break;case 1:this._point=2,this._context.moveTo(this._x4=t,this._y4=n);break;case 2:this._point=3,this._x5=t,this._y5=n;break;default:Vx(this,t,n)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var Qx=function t(n){function e(t){return n?new Kx(t,n):new jx(t,0)}return e.alpha=function(n){return t(+n)},e}(.5);function Jx(t,n){this._context=t,this._alpha=n}Jx.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){if(t=+t,n=+n,this._point){var e=this._x2-t,r=this._y2-n;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(e*e+r*r,this._alpha))}switch(this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:Vx(this,t,n)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var tw=function t(n){function e(t){return n?new Jx(t,n):new Xx(t,0)}return e.alpha=function(n){return t(+n)},e}(.5);function nw(t){this._context=t}function ew(t){return t<0?-1:1}function rw(t,n,e){var r=t._x1-t._x0,i=n-t._x1,o=(t._y1-t._y0)/(r||i<0&&-0),a=(e-t._y1)/(i||r<0&&-0),u=(o*i+a*r)/(r+i);return(ew(o)+ew(a))*Math.min(Math.abs(o),Math.abs(a),.5*Math.abs(u))||0}function iw(t,n){var e=t._x1-t._x0;return e?(3*(t._y1-t._y0)/e-n)/2:n}function ow(t,n,e){var r=t._x0,i=t._y0,o=t._x1,a=t._y1,u=(o-r)/3;t._context.bezierCurveTo(r+u,i+u*n,o-u,a-u*e,o,a)}function aw(t){this._context=t}function uw(t){this._context=new cw(t)}function cw(t){this._context=t}function fw(t){this._context=t}function sw(t){var n,e,r=t.length-1,i=new Array(r),o=new Array(r),a=new Array(r);for(i[0]=0,o[0]=2,a[0]=t[0]+2*t[1],n=1;n=0;--n)i[n]=(a[n]-i[n+1])/o[n];for(o[r-1]=(t[r]+i[r-1])/2,n=0;n1)for(var e,r,i,o=1,a=t[n[0]],u=a.length;o=0;)e[n]=n;return e}function pw(t,n){return t[n]}function gw(t){const n=[];return n.key=t,n}function yw(t){var n=t.map(vw);return dw(t).sort((function(t,e){return n[t]-n[e]}))}function vw(t){for(var n,e=-1,r=0,i=t.length,o=-1/0;++eo&&(o=n,r=e);return r}function _w(t){var n=t.map(bw);return dw(t).sort((function(t,e){return n[t]-n[e]}))}function bw(t){for(var n,e=0,r=-1,i=t.length;++r=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2;default:if(this._t<=0)this._context.lineTo(this._x,n),this._context.lineTo(t,n);else{var e=this._x*(1-this._t)+t*this._t;this._context.lineTo(e,this._y),this._context.lineTo(e,n)}}this._x=t,this._y=n}};var mw=t=>()=>t;function xw(t,{sourceEvent:n,target:e,transform:r,dispatch:i}){Object.defineProperties(this,{type:{value:t,enumerable:!0,configurable:!0},sourceEvent:{value:n,enumerable:!0,configurable:!0},target:{value:e,enumerable:!0,configurable:!0},transform:{value:r,enumerable:!0,configurable:!0},_:{value:i}})}function ww(t,n,e){this.k=t,this.x=n,this.y=e}ww.prototype={constructor:ww,scale:function(t){return 1===t?this:new ww(this.k*t,this.x,this.y)},translate:function(t,n){return 0===t&0===n?this:new ww(this.k,this.x+this.k*t,this.y+this.k*n)},apply:function(t){return[t[0]*this.k+this.x,t[1]*this.k+this.y]},applyX:function(t){return t*this.k+this.x},applyY:function(t){return t*this.k+this.y},invert:function(t){return[(t[0]-this.x)/this.k,(t[1]-this.y)/this.k]},invertX:function(t){return(t-this.x)/this.k},invertY:function(t){return(t-this.y)/this.k},rescaleX:function(t){return t.copy().domain(t.range().map(this.invertX,this).map(t.invert,t))},rescaleY:function(t){return t.copy().domain(t.range().map(this.invertY,this).map(t.invert,t))},toString:function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"}};var Mw=new ww(1,0,0);function Tw(t){for(;!t.__zoom;)if(!(t=t.parentNode))return Mw;return t.__zoom}function Aw(t){t.stopImmediatePropagation()}function Sw(t){t.preventDefault(),t.stopImmediatePropagation()}function Ew(t){return!(t.ctrlKey&&"wheel"!==t.type||t.button)}function Nw(){var t=this;return t instanceof SVGElement?(t=t.ownerSVGElement||t).hasAttribute("viewBox")?[[(t=t.viewBox.baseVal).x,t.y],[t.x+t.width,t.y+t.height]]:[[0,0],[t.width.baseVal.value,t.height.baseVal.value]]:[[0,0],[t.clientWidth,t.clientHeight]]}function kw(){return this.__zoom||Mw}function Cw(t){return-t.deltaY*(1===t.deltaMode?.05:t.deltaMode?1:.002)*(t.ctrlKey?10:1)}function Pw(){return navigator.maxTouchPoints||"ontouchstart"in this}function zw(t,n,e){var r=t.invertX(n[0][0])-e[0][0],i=t.invertX(n[1][0])-e[1][0],o=t.invertY(n[0][1])-e[0][1],a=t.invertY(n[1][1])-e[1][1];return t.translate(i>r?(r+i)/2:Math.min(0,r)||Math.max(0,i),a>o?(o+a)/2:Math.min(0,o)||Math.max(0,a))}Tw.prototype=ww.prototype,t.Adder=T,t.Delaunay=Lu,t.FormatSpecifier=tf,t.InternMap=InternMap,t.InternSet=InternSet,t.Node=Qd,t.Path=Ua,t.Voronoi=qu,t.ZoomTransform=ww,t.active=function(t,n){var e,r,i=t.__transition;if(i)for(r in n=null==n?null:n+"",i)if((e=i[r]).state>qi&&e.name===n)return new po([[t]],Zo,n,+r);return null},t.arc=function(){var t=Cm,n=Pm,e=ym(0),r=null,i=zm,o=$m,a=Dm,u=null,c=km(f);function f(){var f,s,l=+t.apply(this,arguments),h=+n.apply(this,arguments),d=i.apply(this,arguments)-Sm,p=o.apply(this,arguments)-Sm,g=vm(p-d),y=p>d;if(u||(u=f=c()),hTm)if(g>Em-Tm)u.moveTo(h*bm(d),h*wm(d)),u.arc(0,0,h,d,p,!y),l>Tm&&(u.moveTo(l*bm(p),l*wm(p)),u.arc(0,0,l,p,d,y));else{var v,_,b=d,m=p,x=d,w=p,M=g,T=g,A=a.apply(this,arguments)/2,S=A>Tm&&(r?+r.apply(this,arguments):Mm(l*l+h*h)),E=xm(vm(h-l)/2,+e.apply(this,arguments)),N=E,k=E;if(S>Tm){var C=Nm(S/l*wm(A)),P=Nm(S/h*wm(A));(M-=2*C)>Tm?(x+=C*=y?1:-1,w-=C):(M=0,x=w=(d+p)/2),(T-=2*P)>Tm?(b+=P*=y?1:-1,m-=P):(T=0,b=m=(d+p)/2)}var z=h*bm(b),$=h*wm(b),D=l*bm(w),R=l*wm(w);if(E>Tm){var F,q=h*bm(m),U=h*wm(m),I=l*bm(x),O=l*wm(x);if(g1?0:t<-1?Am:Math.acos(t)}((B*L+Y*j)/(Mm(B*B+Y*Y)*Mm(L*L+j*j)))/2),X=Mm(F[0]*F[0]+F[1]*F[1]);N=xm(E,(l-X)/(H-1)),k=xm(E,(h-X)/(H+1))}else N=k=0}T>Tm?k>Tm?(v=Rm(I,O,z,$,h,k,y),_=Rm(q,U,D,R,h,k,y),u.moveTo(v.cx+v.x01,v.cy+v.y01),kTm&&M>Tm?N>Tm?(v=Rm(D,R,q,U,l,-N,y),_=Rm(z,$,I,O,l,-N,y),u.lineTo(v.cx+v.x01,v.cy+v.y01),N=0))throw new RangeError("invalid r");let e=t.length;if(!((e=Math.floor(e))>=0))throw new RangeError("invalid length");if(!e||!n)return t;const r=y(n),i=t.slice();return r(t,i,0,e,1),r(i,t,0,e,1),r(t,i,0,e,1),t},t.blur2=l,t.blurImage=h,t.brush=function(){return wa(la)},t.brushSelection=function(t){var n=t.__brush;return n?n.dim.output(n.selection):null},t.brushX=function(){return wa(fa)},t.brushY=function(){return wa(sa)},t.buffer=function(t,n){return fetch(t,n).then(_c)},t.chord=function(){return za(!1,!1)},t.chordDirected=function(){return za(!0,!1)},t.chordTranspose=function(){return za(!1,!0)},t.cluster=function(){var t=Ld,n=1,e=1,r=!1;function i(i){var o,a=0;i.eachAfter((function(n){var e=n.children;e?(n.x=function(t){return t.reduce(jd,0)/t.length}(e),n.y=function(t){return 1+t.reduce(Hd,0)}(e)):(n.x=o?a+=t(n,o):0,n.y=0,o=n)}));var u=function(t){for(var n;n=t.children;)t=n[0];return t}(i),c=function(t){for(var n;n=t.children;)t=n[n.length-1];return t}(i),f=u.x-t(u,c)/2,s=c.x+t(c,u)/2;return i.eachAfter(r?function(t){t.x=(t.x-i.x)*n,t.y=(i.y-t.y)*e}:function(t){t.x=(t.x-f)/(s-f)*n,t.y=(1-(i.y?t.y/i.y:1))*e})}return i.separation=function(n){return arguments.length?(t=n,i):t},i.size=function(t){return arguments.length?(r=!1,n=+t[0],e=+t[1],i):r?null:[n,e]},i.nodeSize=function(t){return arguments.length?(r=!0,n=+t[0],e=+t[1],i):r?[n,e]:null},i},t.color=ze,t.contourDensity=function(){var t=fu,n=su,e=lu,r=960,i=500,o=20,a=2,u=3*o,c=r+2*u>>a,f=i+2*u>>a,s=Qa(20);function h(r){var i=new Float32Array(c*f),s=Math.pow(2,-a),h=-1;for(const o of r){var d=(t(o,++h,r)+u)*s,p=(n(o,h,r)+u)*s,g=+e(o,h,r);if(g&&d>=0&&d=0&&pt*r)))(n).map(((t,n)=>(t.value=+e[n],p(t))))}function p(t){return t.coordinates.forEach(g),t}function g(t){t.forEach(y)}function y(t){t.forEach(v)}function v(t){t[0]=t[0]*Math.pow(2,a)-u,t[1]=t[1]*Math.pow(2,a)-u}function _(){return c=r+2*(u=3*o)>>a,f=i+2*u>>a,d}return d.contours=function(t){var n=h(t),e=iu().size([c,f]),r=Math.pow(2,2*a),i=t=>{t=+t;var i=p(e.contour(n,t*r));return i.value=t,i};return Object.defineProperty(i,"max",{get:()=>J(n)/r}),i},d.x=function(n){return arguments.length?(t="function"==typeof n?n:Qa(+n),d):t},d.y=function(t){return arguments.length?(n="function"==typeof t?t:Qa(+t),d):n},d.weight=function(t){return arguments.length?(e="function"==typeof t?t:Qa(+t),d):e},d.size=function(t){if(!arguments.length)return[r,i];var n=+t[0],e=+t[1];if(!(n>=0&&e>=0))throw new Error("invalid size");return r=n,i=e,_()},d.cellSize=function(t){if(!arguments.length)return 1<=1))throw new Error("invalid cell size");return a=Math.floor(Math.log(t)/Math.LN2),_()},d.thresholds=function(t){return arguments.length?(s="function"==typeof t?t:Array.isArray(t)?Qa(Za.call(t)):Qa(t),d):s},d.bandwidth=function(t){if(!arguments.length)return Math.sqrt(o*(o+1));if(!((t=+t)>=0))throw new Error("invalid bandwidth");return o=(Math.sqrt(4*t*t+1)-1)/2,_()},d},t.contours=iu,t.count=v,t.create=function(t){return Zn(Yt(t).call(document.documentElement))},t.creator=Yt,t.cross=function(...t){const n="function"==typeof t[t.length-1]&&function(t){return n=>t(...n)}(t.pop()),e=(t=t.map(m)).map(_),r=t.length-1,i=new Array(r+1).fill(0),o=[];if(r<0||e.some(b))return o;for(;;){o.push(i.map(((n,e)=>t[e][n])));let a=r;for(;++i[a]===e[a];){if(0===a)return n?o.map(n):o;i[a--]=0}}},t.csv=wc,t.csvFormat=rc,t.csvFormatBody=ic,t.csvFormatRow=ac,t.csvFormatRows=oc,t.csvFormatValue=uc,t.csvParse=nc,t.csvParseRows=ec,t.cubehelix=Tr,t.cumsum=function(t,n){var e=0,r=0;return Float64Array.from(t,void 0===n?t=>e+=+t||0:i=>e+=+n(i,r++,t)||0)},t.curveBasis=function(t){return new Fx(t)},t.curveBasisClosed=function(t){return new qx(t)},t.curveBasisOpen=function(t){return new Ux(t)},t.curveBumpX=nx,t.curveBumpY=ex,t.curveBundle=Ox,t.curveCardinal=Lx,t.curveCardinalClosed=Hx,t.curveCardinalOpen=Gx,t.curveCatmullRom=Zx,t.curveCatmullRomClosed=Qx,t.curveCatmullRomOpen=tw,t.curveLinear=Im,t.curveLinearClosed=function(t){return new nw(t)},t.curveMonotoneX=function(t){return new aw(t)},t.curveMonotoneY=function(t){return new uw(t)},t.curveNatural=function(t){return new fw(t)},t.curveStep=function(t){return new lw(t,.5)},t.curveStepAfter=function(t){return new lw(t,1)},t.curveStepBefore=function(t){return new lw(t,0)},t.descending=e,t.deviation=w,t.difference=function(t,...n){t=new InternSet(t);for(const e of n)for(const n of e)t.delete(n);return t},t.disjoint=function(t,n){const e=n[Symbol.iterator](),r=new InternSet;for(const n of t){if(r.has(n))return!1;let t,i;for(;({value:t,done:i}=e.next())&&!i;){if(Object.is(n,t))return!1;r.add(t)}}return!0},t.dispatch=$t,t.drag=function(){var t,n,e,r,i=se,o=le,a=he,u=de,c={},f=$t("start","drag","end"),s=0,l=0;function h(t){t.on("mousedown.drag",d).filter(u).on("touchstart.drag",y).on("touchmove.drag",v,ee).on("touchend.drag touchcancel.drag",_).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function d(a,u){if(!r&&i.call(this,a,u)){var c=b(this,o.call(this,a,u),a,u,"mouse");c&&(Zn(a.view).on("mousemove.drag",p,re).on("mouseup.drag",g,re),ae(a.view),ie(a),e=!1,t=a.clientX,n=a.clientY,c("start",a))}}function p(r){if(oe(r),!e){var i=r.clientX-t,o=r.clientY-n;e=i*i+o*o>l}c.mouse("drag",r)}function g(t){Zn(t.view).on("mousemove.drag mouseup.drag",null),ue(t.view,e),oe(t),c.mouse("end",t)}function y(t,n){if(i.call(this,t,n)){var e,r,a=t.changedTouches,u=o.call(this,t,n),c=a.length;for(e=0;e+t,t.easePoly=wo,t.easePolyIn=mo,t.easePolyInOut=wo,t.easePolyOut=xo,t.easeQuad=_o,t.easeQuadIn=function(t){return t*t},t.easeQuadInOut=_o,t.easeQuadOut=function(t){return t*(2-t)},t.easeSin=Ao,t.easeSinIn=function(t){return 1==+t?1:1-Math.cos(t*To)},t.easeSinInOut=Ao,t.easeSinOut=function(t){return Math.sin(t*To)},t.every=function(t,n){if("function"!=typeof n)throw new TypeError("test is not a function");let e=-1;for(const r of t)if(!n(r,++e,t))return!1;return!0},t.extent=M,t.fcumsum=function(t,n){const e=new T;let r=-1;return Float64Array.from(t,void 0===n?t=>e.add(+t||0):i=>e.add(+n(i,++r,t)||0))},t.filter=function(t,n){if("function"!=typeof n)throw new TypeError("test is not a function");const e=[];let r=-1;for(const i of t)n(i,++r,t)&&e.push(i);return e},t.flatGroup=function(t,...n){return z(P(t,...n),n)},t.flatRollup=function(t,n,...e){return z(D(t,n,...e),e)},t.forceCenter=function(t,n){var e,r=1;function i(){var i,o,a=e.length,u=0,c=0;for(i=0;if+p||os+p||ac.index){var g=f-u.x-u.vx,y=s-u.y-u.vy,v=g*g+y*y;vt.r&&(t.r=t[n].r)}function c(){if(n){var r,i,o=n.length;for(e=new Array(o),r=0;r[u(t,n,r),t])));for(a=0,i=new Array(f);a=u)){(t.data!==n||t.next)&&(0===l&&(p+=(l=Uc(e))*l),0===h&&(p+=(h=Uc(e))*h),p(t=(Lc*t+jc)%Hc)/Hc}();function l(){h(),f.call("tick",n),e1?(null==e?u.delete(t):u.set(t,p(e)),n):u.get(t)},find:function(n,e,r){var i,o,a,u,c,f=0,s=t.length;for(null==r?r=1/0:r*=r,f=0;f1?(f.on(t,e),n):f.on(t)}}},t.forceX=function(t){var n,e,r,i=qc(.1);function o(t){for(var i,o=0,a=n.length;o=.12&&i<.234&&r>=-.425&&r<-.214?u:i>=.166&&i<.234&&r>=-.214&&r<-.115?c:a).invert(t)},s.stream=function(e){return t&&n===e?t:(r=[a.stream(n=e),u.stream(e),c.stream(e)],i=r.length,t={point:function(t,n){for(var e=-1;++ejs(r[0],r[1])&&(r[1]=i[1]),js(i[0],r[1])>js(r[0],r[1])&&(r[0]=i[0])):o.push(r=i);for(a=-1/0,n=0,r=o[e=o.length-1];n<=e;r=i,++n)i=o[n],(u=js(r[1],i[0]))>a&&(a=u,Wf=i[0],Kf=r[1])}return is=os=null,Wf===1/0||Zf===1/0?[[NaN,NaN],[NaN,NaN]]:[[Wf,Zf],[Kf,Qf]]},t.geoCentroid=function(t){ms=xs=ws=Ms=Ts=As=Ss=Es=0,Ns=new T,ks=new T,Cs=new T,Lf(t,Gs);var n=+Ns,e=+ks,r=+Cs,i=Ef(n,e,r);return i=0))throw new RangeError(`invalid digits: ${t}`);i=n}return null===n&&(r=new ed(i)),a},a.projection(t).digits(i).context(n)},t.geoProjection=yd,t.geoProjectionMutator=vd,t.geoRotation=ll,t.geoStereographic=function(){return yd(Bd).scale(250).clipAngle(142)},t.geoStereographicRaw=Bd,t.geoStream=Lf,t.geoTransform=function(t){return{stream:id(t)}},t.geoTransverseMercator=function(){var t=Ed(Yd),n=t.center,e=t.rotate;return t.center=function(t){return arguments.length?n([-t[1],t[0]]):[(t=n())[1],-t[0]]},t.rotate=function(t){return arguments.length?e([t[0],t[1],t.length>2?t[2]+90:90]):[(t=e())[0],t[1],t[2]-90]},e([0,0,90]).scale(159.155)},t.geoTransverseMercatorRaw=Yd,t.gray=function(t,n){return new ur(t,0,0,null==n?1:n)},t.greatest=ot,t.greatestIndex=function(t,e=n){if(1===e.length)return tt(t,e);let r,i=-1,o=-1;for(const n of t)++o,(i<0?0===e(n,n):e(n,r)>0)&&(r=n,i=o);return i},t.group=C,t.groupSort=function(t,e,r){return(2!==e.length?U($(t,e,r),(([t,e],[r,i])=>n(e,i)||n(t,r))):U(C(t,r),(([t,r],[i,o])=>e(r,o)||n(t,i)))).map((([t])=>t))},t.groups=P,t.hcl=dr,t.hierarchy=Gd,t.histogram=Q,t.hsl=He,t.html=Ec,t.image=function(t,n){return new Promise((function(e,r){var i=new Image;for(var o in n)i[o]=n[o];i.onerror=r,i.onload=function(){e(i)},i.src=t}))},t.index=function(t,...n){return F(t,k,R,n)},t.indexes=function(t,...n){return F(t,Array.from,R,n)},t.interpolate=Gr,t.interpolateArray=function(t,n){return(Ir(n)?Ur:Or)(t,n)},t.interpolateBasis=Er,t.interpolateBasisClosed=Nr,t.interpolateBlues=Gb,t.interpolateBrBG=ob,t.interpolateBuGn=Mb,t.interpolateBuPu=Ab,t.interpolateCividis=function(t){return t=Math.max(0,Math.min(1,t)),"rgb("+Math.max(0,Math.min(255,Math.round(-4.54-t*(35.34-t*(2381.73-t*(6402.7-t*(7024.72-2710.57*t)))))))+", "+Math.max(0,Math.min(255,Math.round(32.49+t*(170.73+t*(52.82-t*(131.46-t*(176.58-67.37*t)))))))+", "+Math.max(0,Math.min(255,Math.round(81.24+t*(442.36-t*(2482.43-t*(6167.24-t*(6614.94-2475.67*t)))))))+")"},t.interpolateCool=am,t.interpolateCubehelix=li,t.interpolateCubehelixDefault=im,t.interpolateCubehelixLong=hi,t.interpolateDate=Br,t.interpolateDiscrete=function(t){var n=t.length;return function(e){return t[Math.max(0,Math.min(n-1,Math.floor(e*n)))]}},t.interpolateGnBu=Eb,t.interpolateGreens=Wb,t.interpolateGreys=Kb,t.interpolateHcl=ci,t.interpolateHclLong=fi,t.interpolateHsl=oi,t.interpolateHslLong=ai,t.interpolateHue=function(t,n){var e=Pr(+t,+n);return function(t){var n=e(t);return n-360*Math.floor(n/360)}},t.interpolateInferno=pm,t.interpolateLab=function(t,n){var e=$r((t=ar(t)).l,(n=ar(n)).l),r=$r(t.a,n.a),i=$r(t.b,n.b),o=$r(t.opacity,n.opacity);return function(n){return t.l=e(n),t.a=r(n),t.b=i(n),t.opacity=o(n),t+""}},t.interpolateMagma=dm,t.interpolateNumber=Yr,t.interpolateNumberArray=Ur,t.interpolateObject=Lr,t.interpolateOrRd=kb,t.interpolateOranges=rm,t.interpolatePRGn=ub,t.interpolatePiYG=fb,t.interpolatePlasma=gm,t.interpolatePuBu=$b,t.interpolatePuBuGn=Pb,t.interpolatePuOr=lb,t.interpolatePuRd=Rb,t.interpolatePurples=Jb,t.interpolateRainbow=function(t){(t<0||t>1)&&(t-=Math.floor(t));var n=Math.abs(t-.5);return um.h=360*t-100,um.s=1.5-1.5*n,um.l=.8-.9*n,um+""},t.interpolateRdBu=db,t.interpolateRdGy=gb,t.interpolateRdPu=qb,t.interpolateRdYlBu=vb,t.interpolateRdYlGn=bb,t.interpolateReds=nm,t.interpolateRgb=Dr,t.interpolateRgbBasis=Fr,t.interpolateRgbBasisClosed=qr,t.interpolateRound=Vr,t.interpolateSinebow=function(t){var n;return t=(.5-t)*Math.PI,cm.r=255*(n=Math.sin(t))*n,cm.g=255*(n=Math.sin(t+fm))*n,cm.b=255*(n=Math.sin(t+sm))*n,cm+""},t.interpolateSpectral=xb,t.interpolateString=Xr,t.interpolateTransformCss=ti,t.interpolateTransformSvg=ni,t.interpolateTurbo=function(t){return t=Math.max(0,Math.min(1,t)),"rgb("+Math.max(0,Math.min(255,Math.round(34.61+t*(1172.33-t*(10793.56-t*(33300.12-t*(38394.49-14825.05*t)))))))+", "+Math.max(0,Math.min(255,Math.round(23.31+t*(557.33+t*(1225.33-t*(3574.96-t*(1073.77+707.56*t)))))))+", "+Math.max(0,Math.min(255,Math.round(27.2+t*(3211.1-t*(15327.97-t*(27814-t*(22569.18-6838.66*t)))))))+")"},t.interpolateViridis=hm,t.interpolateWarm=om,t.interpolateYlGn=Bb,t.interpolateYlGnBu=Ib,t.interpolateYlOrBr=Lb,t.interpolateYlOrRd=Hb,t.interpolateZoom=ri,t.interrupt=Gi,t.intersection=function(t,...n){t=new InternSet(t),n=n.map(vt);t:for(const e of t)for(const r of n)if(!r.has(e)){t.delete(e);continue t}return t},t.interval=function(t,n,e){var r=new Ei,i=n;return null==n?(r.restart(t,n,e),r):(r._restart=r.restart,r.restart=function(t,n,e){n=+n,e=null==e?Ai():+e,r._restart((function o(a){a+=i,r._restart(o,i+=n,e),t(a)}),n,e)},r.restart(t,n,e),r)},t.isoFormat=D_,t.isoParse=F_,t.json=function(t,n){return fetch(t,n).then(Tc)},t.lab=ar,t.lch=function(t,n,e,r){return 1===arguments.length?hr(t):new pr(e,n,t,null==r?1:r)},t.least=function(t,e=n){let r,i=!1;if(1===e.length){let o;for(const a of t){const t=e(a);(i?n(t,o)<0:0===n(t,t))&&(r=a,o=t,i=!0)}}else for(const n of t)(i?e(n,r)<0:0===e(n,n))&&(r=n,i=!0);return r},t.leastIndex=ht,t.line=Ym,t.lineRadial=Zm,t.link=ax,t.linkHorizontal=function(){return ax(nx)},t.linkRadial=function(){const t=ax(rx);return t.angle=t.x,delete t.x,t.radius=t.y,delete t.y,t},t.linkVertical=function(){return ax(ex)},t.local=Qn,t.map=function(t,n){if("function"!=typeof t[Symbol.iterator])throw new TypeError("values is not iterable");if("function"!=typeof n)throw new TypeError("mapper is not a function");return Array.from(t,((e,r)=>n(e,r,t)))},t.matcher=Vt,t.max=J,t.maxIndex=tt,t.mean=function(t,n){let e=0,r=0;if(void 0===n)for(let n of t)null!=n&&(n=+n)>=n&&(++e,r+=n);else{let i=-1;for(let o of t)null!=(o=n(o,++i,t))&&(o=+o)>=o&&(++e,r+=o)}if(e)return r/e},t.median=function(t,n){return at(t,.5,n)},t.medianIndex=function(t,n){return ct(t,.5,n)},t.merge=ft,t.min=nt,t.minIndex=et,t.mode=function(t,n){const e=new InternMap;if(void 0===n)for(let n of t)null!=n&&n>=n&&e.set(n,(e.get(n)||0)+1);else{let r=-1;for(let i of t)null!=(i=n(i,++r,t))&&i>=i&&e.set(i,(e.get(i)||0)+1)}let r,i=0;for(const[t,n]of e)n>i&&(i=n,r=t);return r},t.namespace=It,t.namespaces=Ut,t.nice=Z,t.now=Ai,t.pack=function(){var t=null,n=1,e=1,r=np;function i(i){const o=ap();return i.x=n/2,i.y=e/2,t?i.eachBefore(xp(t)).eachAfter(wp(r,.5,o)).eachBefore(Mp(1)):i.eachBefore(xp(mp)).eachAfter(wp(np,1,o)).eachAfter(wp(r,i.r/Math.min(n,e),o)).eachBefore(Mp(Math.min(n,e)/(2*i.r))),i}return i.radius=function(n){return arguments.length?(t=Jd(n),i):t},i.size=function(t){return arguments.length?(n=+t[0],e=+t[1],i):[n,e]},i.padding=function(t){return arguments.length?(r="function"==typeof t?t:ep(+t),i):r},i},t.packEnclose=function(t){return up(t,ap())},t.packSiblings=function(t){return bp(t,ap()),t},t.pairs=function(t,n=st){const e=[];let r,i=!1;for(const o of t)i&&e.push(n(r,o)),r=o,i=!0;return e},t.partition=function(){var t=1,n=1,e=0,r=!1;function i(i){var o=i.height+1;return i.x0=i.y0=e,i.x1=t,i.y1=n/o,i.eachBefore(function(t,n){return function(r){r.children&&Ap(r,r.x0,t*(r.depth+1)/n,r.x1,t*(r.depth+2)/n);var i=r.x0,o=r.y0,a=r.x1-e,u=r.y1-e;a0&&(d+=l);for(null!=n?p.sort((function(t,e){return n(g[t],g[e])})):null!=e&&p.sort((function(t,n){return e(a[t],a[n])})),u=0,f=d?(v-h*b)/d:0;u0?l*f:0)+b,g[c]={data:a[c],index:u,value:l,startAngle:y,endAngle:s,padAngle:_};return g}return a.value=function(n){return arguments.length?(t="function"==typeof n?n:ym(+n),a):t},a.sortValues=function(t){return arguments.length?(n=t,e=null,a):n},a.sort=function(t){return arguments.length?(e=t,n=null,a):e},a.startAngle=function(t){return arguments.length?(r="function"==typeof t?t:ym(+t),a):r},a.endAngle=function(t){return arguments.length?(i="function"==typeof t?t:ym(+t),a):i},a.padAngle=function(t){return arguments.length?(o="function"==typeof t?t:ym(+t),a):o},a},t.piecewise=di,t.pointRadial=Qm,t.pointer=ne,t.pointers=function(t,n){return t.target&&(t=te(t),void 0===n&&(n=t.currentTarget),t=t.touches||[t]),Array.from(t,(t=>ne(t,n)))},t.polygonArea=function(t){for(var n,e=-1,r=t.length,i=t[r-1],o=0;++eu!=f>u&&a<(c-e)*(u-r)/(f-r)+e&&(s=!s),c=e,f=r;return s},t.polygonHull=function(t){if((e=t.length)<3)return null;var n,e,r=new Array(e),i=new Array(e);for(n=0;n=0;--n)f.push(t[r[o[n]][2]]);for(n=+u;n(n=1664525*n+1013904223|0,lg*(n>>>0))},t.randomLogNormal=Kp,t.randomLogistic=fg,t.randomNormal=Zp,t.randomPareto=ng,t.randomPoisson=sg,t.randomUniform=Vp,t.randomWeibull=ug,t.range=lt,t.rank=function(t,e=n){if("function"!=typeof t[Symbol.iterator])throw new TypeError("values is not iterable");let r=Array.from(t);const i=new Float64Array(r.length);2!==e.length&&(r=r.map(e),e=n);const o=(t,n)=>e(r[t],r[n]);let a,u;return(t=Uint32Array.from(r,((t,n)=>n))).sort(e===n?(t,n)=>O(r[t],r[n]):I(o)),t.forEach(((t,n)=>{const e=o(t,void 0===a?t:a);e>=0?((void 0===a||e>0)&&(a=t,u=n),i[t]=u):i[t]=NaN})),i},t.reduce=function(t,n,e){if("function"!=typeof n)throw new TypeError("reducer is not a function");const r=t[Symbol.iterator]();let i,o,a=-1;if(arguments.length<3){if(({done:i,value:e}=r.next()),i)return;++a}for(;({done:i,value:o}=r.next()),!i;)e=n(e,o,++a,t);return e},t.reverse=function(t){if("function"!=typeof t[Symbol.iterator])throw new TypeError("values is not iterable");return Array.from(t).reverse()},t.rgb=Fe,t.ribbon=function(){return Wa()},t.ribbonArrow=function(){return Wa(Va)},t.rollup=$,t.rollups=D,t.scaleBand=yg,t.scaleDiverging=function t(){var n=Ng(L_()(mg));return n.copy=function(){return B_(n,t())},dg.apply(n,arguments)},t.scaleDivergingLog=function t(){var n=Fg(L_()).domain([.1,1,10]);return n.copy=function(){return B_(n,t()).base(n.base())},dg.apply(n,arguments)},t.scaleDivergingPow=j_,t.scaleDivergingSqrt=function(){return j_.apply(null,arguments).exponent(.5)},t.scaleDivergingSymlog=function t(){var n=Ig(L_());return n.copy=function(){return B_(n,t()).constant(n.constant())},dg.apply(n,arguments)},t.scaleIdentity=function t(n){var e;function r(t){return null==t||isNaN(t=+t)?e:t}return r.invert=r,r.domain=r.range=function(t){return arguments.length?(n=Array.from(t,_g),r):n.slice()},r.unknown=function(t){return arguments.length?(e=t,r):e},r.copy=function(){return t(n).unknown(e)},n=arguments.length?Array.from(n,_g):[0,1],Ng(r)},t.scaleImplicit=pg,t.scaleLinear=function t(){var n=Sg();return n.copy=function(){return Tg(n,t())},hg.apply(n,arguments),Ng(n)},t.scaleLog=function t(){const n=Fg(Ag()).domain([1,10]);return n.copy=()=>Tg(n,t()).base(n.base()),hg.apply(n,arguments),n},t.scaleOrdinal=gg,t.scalePoint=function(){return vg(yg.apply(null,arguments).paddingInner(1))},t.scalePow=jg,t.scaleQuantile=function t(){var e,r=[],i=[],o=[];function a(){var t=0,n=Math.max(1,i.length);for(o=new Array(n-1);++t0?o[n-1]:r[0],n=i?[o[i-1],r]:[o[n-1],o[n]]},u.unknown=function(t){return arguments.length?(n=t,u):u},u.thresholds=function(){return o.slice()},u.copy=function(){return t().domain([e,r]).range(a).unknown(n)},hg.apply(Ng(u),arguments)},t.scaleRadial=function t(){var n,e=Sg(),r=[0,1],i=!1;function o(t){var r=function(t){return Math.sign(t)*Math.sqrt(Math.abs(t))}(e(t));return isNaN(r)?n:i?Math.round(r):r}return o.invert=function(t){return e.invert(Hg(t))},o.domain=function(t){return arguments.length?(e.domain(t),o):e.domain()},o.range=function(t){return arguments.length?(e.range((r=Array.from(t,_g)).map(Hg)),o):r.slice()},o.rangeRound=function(t){return o.range(t).round(!0)},o.round=function(t){return arguments.length?(i=!!t,o):i},o.clamp=function(t){return arguments.length?(e.clamp(t),o):e.clamp()},o.unknown=function(t){return arguments.length?(n=t,o):n},o.copy=function(){return t(e.domain(),r).round(i).clamp(e.clamp()).unknown(n)},hg.apply(o,arguments),Ng(o)},t.scaleSequential=function t(){var n=Ng(O_()(mg));return n.copy=function(){return B_(n,t())},dg.apply(n,arguments)},t.scaleSequentialLog=function t(){var n=Fg(O_()).domain([1,10]);return n.copy=function(){return B_(n,t()).base(n.base())},dg.apply(n,arguments)},t.scaleSequentialPow=Y_,t.scaleSequentialQuantile=function t(){var e=[],r=mg;function i(t){if(null!=t&&!isNaN(t=+t))return r((s(e,t,1)-1)/(e.length-1))}return i.domain=function(t){if(!arguments.length)return e.slice();e=[];for(let n of t)null==n||isNaN(n=+n)||e.push(n);return e.sort(n),i},i.interpolator=function(t){return arguments.length?(r=t,i):r},i.range=function(){return e.map(((t,n)=>r(n/(e.length-1))))},i.quantiles=function(t){return Array.from({length:t+1},((n,r)=>at(e,r/t)))},i.copy=function(){return t(r).domain(e)},dg.apply(i,arguments)},t.scaleSequentialSqrt=function(){return Y_.apply(null,arguments).exponent(.5)},t.scaleSequentialSymlog=function t(){var n=Ig(O_());return n.copy=function(){return B_(n,t()).constant(n.constant())},dg.apply(n,arguments)},t.scaleSqrt=function(){return jg.apply(null,arguments).exponent(.5)},t.scaleSymlog=function t(){var n=Ig(Ag());return n.copy=function(){return Tg(n,t()).constant(n.constant())},hg.apply(n,arguments)},t.scaleThreshold=function t(){var n,e=[.5],r=[0,1],i=1;function o(t){return null!=t&&t<=t?r[s(e,t,0,i)]:n}return o.domain=function(t){return arguments.length?(e=Array.from(t),i=Math.min(e.length,r.length-1),o):e.slice()},o.range=function(t){return arguments.length?(r=Array.from(t),i=Math.min(e.length,r.length-1),o):r.slice()},o.invertExtent=function(t){var n=r.indexOf(t);return[e[n-1],e[n]]},o.unknown=function(t){return arguments.length?(n=t,o):n},o.copy=function(){return t().domain(e).range(r).unknown(n)},hg.apply(o,arguments)},t.scaleTime=function(){return hg.apply(I_(uv,cv,tv,Zy,xy,py,sy,ay,iy,t.timeFormat).domain([new Date(2e3,0,1),new Date(2e3,0,2)]),arguments)},t.scaleUtc=function(){return hg.apply(I_(ov,av,ev,Qy,Fy,yy,hy,cy,iy,t.utcFormat).domain([Date.UTC(2e3,0,1),Date.UTC(2e3,0,2)]),arguments)},t.scan=function(t,n){const e=ht(t,n);return e<0?void 0:e},t.schemeAccent=G_,t.schemeBlues=Xb,t.schemeBrBG=ib,t.schemeBuGn=wb,t.schemeBuPu=Tb,t.schemeCategory10=X_,t.schemeDark2=V_,t.schemeGnBu=Sb,t.schemeGreens=Vb,t.schemeGreys=Zb,t.schemeObservable10=W_,t.schemeOrRd=Nb,t.schemeOranges=em,t.schemePRGn=ab,t.schemePaired=Z_,t.schemePastel1=K_,t.schemePastel2=Q_,t.schemePiYG=cb,t.schemePuBu=zb,t.schemePuBuGn=Cb,t.schemePuOr=sb,t.schemePuRd=Db,t.schemePurples=Qb,t.schemeRdBu=hb,t.schemeRdGy=pb,t.schemeRdPu=Fb,t.schemeRdYlBu=yb,t.schemeRdYlGn=_b,t.schemeReds=tm,t.schemeSet1=J_,t.schemeSet2=tb,t.schemeSet3=nb,t.schemeSpectral=mb,t.schemeTableau10=eb,t.schemeYlGn=Ob,t.schemeYlGnBu=Ub,t.schemeYlOrBr=Yb,t.schemeYlOrRd=jb,t.select=Zn,t.selectAll=function(t){return"string"==typeof t?new Vn([document.querySelectorAll(t)],[document.documentElement]):new Vn([Ht(t)],Gn)},t.selection=Wn,t.selector=jt,t.selectorAll=Gt,t.shuffle=dt,t.shuffler=pt,t.some=function(t,n){if("function"!=typeof n)throw new TypeError("test is not a function");let e=-1;for(const r of t)if(n(r,++e,t))return!0;return!1},t.sort=U,t.stack=function(){var t=ym([]),n=dw,e=hw,r=pw;function i(i){var o,a,u=Array.from(t.apply(this,arguments),gw),c=u.length,f=-1;for(const t of i)for(o=0,++f;o0)for(var e,r,i,o,a,u,c=0,f=t[n[0]].length;c0?(r[0]=o,r[1]=o+=i):i<0?(r[1]=a,r[0]=a+=i):(r[0]=0,r[1]=i)},t.stackOffsetExpand=function(t,n){if((r=t.length)>0){for(var e,r,i,o=0,a=t[0].length;o0){for(var e,r=0,i=t[n[0]],o=i.length;r0&&(r=(e=t[n[0]]).length)>0){for(var e,r,i,o=0,a=1;afunction(t){t=`${t}`;let n=t.length;zp(t,n-1)&&!zp(t,n-2)&&(t=t.slice(0,-1));return"/"===t[0]?t:`/${t}`}(t(n,e,r)))),e=n.map(Pp),i=new Set(n).add("");for(const t of e)i.has(t)||(i.add(t),n.push(t),e.push(Pp(t)),h.push(Np));d=(t,e)=>n[e],p=(t,n)=>e[n]}for(a=0,i=h.length;a=0&&(f=h[t]).data===Np;--t)f.data=null}if(u.parent=Sp,u.eachBefore((function(t){t.depth=t.parent.depth+1,--i})).eachBefore(Kd),u.parent=null,i>0)throw new Error("cycle");return u}return r.id=function(t){return arguments.length?(n=Jd(t),r):n},r.parentId=function(t){return arguments.length?(e=Jd(t),r):e},r.path=function(n){return arguments.length?(t=Jd(n),r):t},r},t.style=_n,t.subset=function(t,n){return _t(n,t)},t.sum=function(t,n){let e=0;if(void 0===n)for(let n of t)(n=+n)&&(e+=n);else{let r=-1;for(let i of t)(i=+n(i,++r,t))&&(e+=i)}return e},t.superset=_t,t.svg=Nc,t.symbol=function(t,n){let e=null,r=km(i);function i(){let i;if(e||(e=i=r()),t.apply(this,arguments).draw(e,+n.apply(this,arguments)),i)return e=null,i+""||null}return t="function"==typeof t?t:ym(t||fx),n="function"==typeof n?n:ym(void 0===n?64:+n),i.type=function(n){return arguments.length?(t="function"==typeof n?n:ym(n),i):t},i.size=function(t){return arguments.length?(n="function"==typeof t?t:ym(+t),i):n},i.context=function(t){return arguments.length?(e=null==t?null:t,i):e},i},t.symbolAsterisk=cx,t.symbolCircle=fx,t.symbolCross=sx,t.symbolDiamond=dx,t.symbolDiamond2=px,t.symbolPlus=gx,t.symbolSquare=yx,t.symbolSquare2=vx,t.symbolStar=xx,t.symbolTimes=Px,t.symbolTriangle=Mx,t.symbolTriangle2=Ax,t.symbolWye=Cx,t.symbolX=Px,t.symbols=zx,t.symbolsFill=zx,t.symbolsStroke=$x,t.text=mc,t.thresholdFreedmanDiaconis=function(t,n,e){const r=v(t),i=at(t,.75)-at(t,.25);return r&&i?Math.ceil((e-n)/(2*i*Math.pow(r,-1/3))):1},t.thresholdScott=function(t,n,e){const r=v(t),i=w(t);return r&&i?Math.ceil((e-n)*Math.cbrt(r)/(3.49*i)):1},t.thresholdSturges=K,t.tickFormat=Eg,t.tickIncrement=V,t.tickStep=W,t.ticks=G,t.timeDay=py,t.timeDays=gy,t.timeFormatDefaultLocale=P_,t.timeFormatLocale=hv,t.timeFriday=Sy,t.timeFridays=$y,t.timeHour=sy,t.timeHours=ly,t.timeInterval=Vg,t.timeMillisecond=Wg,t.timeMilliseconds=Zg,t.timeMinute=ay,t.timeMinutes=uy,t.timeMonday=wy,t.timeMondays=ky,t.timeMonth=Zy,t.timeMonths=Ky,t.timeSaturday=Ey,t.timeSaturdays=Dy,t.timeSecond=iy,t.timeSeconds=oy,t.timeSunday=xy,t.timeSundays=Ny,t.timeThursday=Ay,t.timeThursdays=zy,t.timeTickInterval=cv,t.timeTicks=uv,t.timeTuesday=My,t.timeTuesdays=Cy,t.timeWednesday=Ty,t.timeWednesdays=Py,t.timeWeek=xy,t.timeWeeks=Ny,t.timeYear=tv,t.timeYears=nv,t.timeout=$i,t.timer=Ni,t.timerFlush=ki,t.transition=go,t.transpose=gt,t.tree=function(){var t=$p,n=1,e=1,r=null;function i(i){var c=function(t){for(var n,e,r,i,o,a=new Up(t,0),u=[a];n=u.pop();)if(r=n._.children)for(n.children=new Array(o=r.length),i=o-1;i>=0;--i)u.push(e=n.children[i]=new Up(r[i],i)),e.parent=n;return(a.parent=new Up(null,0)).children=[a],a}(i);if(c.eachAfter(o),c.parent.m=-c.z,c.eachBefore(a),r)i.eachBefore(u);else{var f=i,s=i,l=i;i.eachBefore((function(t){t.xs.x&&(s=t),t.depth>l.depth&&(l=t)}));var h=f===s?1:t(f,s)/2,d=h-f.x,p=n/(s.x+h+d),g=e/(l.depth||1);i.eachBefore((function(t){t.x=(t.x+d)*p,t.y=t.depth*g}))}return i}function o(n){var e=n.children,r=n.parent.children,i=n.i?r[n.i-1]:null;if(e){!function(t){for(var n,e=0,r=0,i=t.children,o=i.length;--o>=0;)(n=i[o]).z+=e,n.m+=e,e+=n.s+(r+=n.c)}(n);var o=(e[0].z+e[e.length-1].z)/2;i?(n.z=i.z+t(n._,i._),n.m=n.z-o):n.z=o}else i&&(n.z=i.z+t(n._,i._));n.parent.A=function(n,e,r){if(e){for(var i,o=n,a=n,u=e,c=o.parent.children[0],f=o.m,s=a.m,l=u.m,h=c.m;u=Rp(u),o=Dp(o),u&&o;)c=Dp(c),(a=Rp(a)).a=n,(i=u.z+l-o.z-f+t(u._,o._))>0&&(Fp(qp(u,n,r),n,i),f+=i,s+=i),l+=u.m,f+=o.m,h+=c.m,s+=a.m;u&&!Rp(a)&&(a.t=u,a.m+=l-s),o&&!Dp(c)&&(c.t=o,c.m+=f-h,r=n)}return r}(n,i,n.parent.A||r[0])}function a(t){t._.x=t.z+t.parent.m,t.m+=t.parent.m}function u(t){t.x*=n,t.y=t.depth*e}return i.separation=function(n){return arguments.length?(t=n,i):t},i.size=function(t){return arguments.length?(r=!1,n=+t[0],e=+t[1],i):r?null:[n,e]},i.nodeSize=function(t){return arguments.length?(r=!0,n=+t[0],e=+t[1],i):r?[n,e]:null},i},t.treemap=function(){var t=Yp,n=!1,e=1,r=1,i=[0],o=np,a=np,u=np,c=np,f=np;function s(t){return t.x0=t.y0=0,t.x1=e,t.y1=r,t.eachBefore(l),i=[0],n&&t.eachBefore(Tp),t}function l(n){var e=i[n.depth],r=n.x0+e,s=n.y0+e,l=n.x1-e,h=n.y1-e;l=e-1){var s=u[n];return s.x0=i,s.y0=o,s.x1=a,void(s.y1=c)}var l=f[n],h=r/2+l,d=n+1,p=e-1;for(;d>>1;f[g]c-o){var _=r?(i*v+a*y)/r:a;t(n,d,y,i,o,_,c),t(d,e,v,_,o,a,c)}else{var b=r?(o*v+c*y)/r:c;t(n,d,y,i,o,a,b),t(d,e,v,i,b,a,c)}}(0,c,t.value,n,e,r,i)},t.treemapDice=Ap,t.treemapResquarify=Lp,t.treemapSlice=Ip,t.treemapSliceDice=function(t,n,e,r,i){(1&t.depth?Ip:Ap)(t,n,e,r,i)},t.treemapSquarify=Yp,t.tsv=Mc,t.tsvFormat=lc,t.tsvFormatBody=hc,t.tsvFormatRow=pc,t.tsvFormatRows=dc,t.tsvFormatValue=gc,t.tsvParse=fc,t.tsvParseRows=sc,t.union=function(...t){const n=new InternSet;for(const e of t)for(const t of e)n.add(t);return n},t.unixDay=_y,t.unixDays=by,t.utcDay=yy,t.utcDays=vy,t.utcFriday=By,t.utcFridays=Vy,t.utcHour=hy,t.utcHours=dy,t.utcMillisecond=Wg,t.utcMilliseconds=Zg,t.utcMinute=cy,t.utcMinutes=fy,t.utcMonday=qy,t.utcMondays=jy,t.utcMonth=Qy,t.utcMonths=Jy,t.utcSaturday=Yy,t.utcSaturdays=Wy,t.utcSecond=iy,t.utcSeconds=oy,t.utcSunday=Fy,t.utcSundays=Ly,t.utcThursday=Oy,t.utcThursdays=Gy,t.utcTickInterval=av,t.utcTicks=ov,t.utcTuesday=Uy,t.utcTuesdays=Hy,t.utcWednesday=Iy,t.utcWednesdays=Xy,t.utcWeek=Fy,t.utcWeeks=Ly,t.utcYear=ev,t.utcYears=rv,t.variance=x,t.version="7.9.0",t.window=pn,t.xml=Sc,t.zip=function(){return gt(arguments)},t.zoom=function(){var t,n,e,r=Ew,i=Nw,o=zw,a=Cw,u=Pw,c=[0,1/0],f=[[-1/0,-1/0],[1/0,1/0]],s=250,l=ri,h=$t("start","zoom","end"),d=500,p=150,g=0,y=10;function v(t){t.property("__zoom",kw).on("wheel.zoom",T,{passive:!1}).on("mousedown.zoom",A).on("dblclick.zoom",S).filter(u).on("touchstart.zoom",E).on("touchmove.zoom",N).on("touchend.zoom touchcancel.zoom",k).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function _(t,n){return(n=Math.max(c[0],Math.min(c[1],n)))===t.k?t:new ww(n,t.x,t.y)}function b(t,n,e){var r=n[0]-e[0]*t.k,i=n[1]-e[1]*t.k;return r===t.x&&i===t.y?t:new ww(t.k,r,i)}function m(t){return[(+t[0][0]+ +t[1][0])/2,(+t[0][1]+ +t[1][1])/2]}function x(t,n,e,r){t.on("start.zoom",(function(){w(this,arguments).event(r).start()})).on("interrupt.zoom end.zoom",(function(){w(this,arguments).event(r).end()})).tween("zoom",(function(){var t=this,o=arguments,a=w(t,o).event(r),u=i.apply(t,o),c=null==e?m(u):"function"==typeof e?e.apply(t,o):e,f=Math.max(u[1][0]-u[0][0],u[1][1]-u[0][1]),s=t.__zoom,h="function"==typeof n?n.apply(t,o):n,d=l(s.invert(c).concat(f/s.k),h.invert(c).concat(f/h.k));return function(t){if(1===t)t=h;else{var n=d(t),e=f/n[2];t=new ww(e,c[0]-n[0]*e,c[1]-n[1]*e)}a.zoom(null,t)}}))}function w(t,n,e){return!e&&t.__zooming||new M(t,n)}function M(t,n){this.that=t,this.args=n,this.active=0,this.sourceEvent=null,this.extent=i.apply(t,n),this.taps=0}function T(t,...n){if(r.apply(this,arguments)){var e=w(this,n).event(t),i=this.__zoom,u=Math.max(c[0],Math.min(c[1],i.k*Math.pow(2,a.apply(this,arguments)))),s=ne(t);if(e.wheel)e.mouse[0][0]===s[0]&&e.mouse[0][1]===s[1]||(e.mouse[1]=i.invert(e.mouse[0]=s)),clearTimeout(e.wheel);else{if(i.k===u)return;e.mouse=[s,i.invert(s)],Gi(this),e.start()}Sw(t),e.wheel=setTimeout((function(){e.wheel=null,e.end()}),p),e.zoom("mouse",o(b(_(i,u),e.mouse[0],e.mouse[1]),e.extent,f))}}function A(t,...n){if(!e&&r.apply(this,arguments)){var i=t.currentTarget,a=w(this,n,!0).event(t),u=Zn(t.view).on("mousemove.zoom",(function(t){if(Sw(t),!a.moved){var n=t.clientX-s,e=t.clientY-l;a.moved=n*n+e*e>g}a.event(t).zoom("mouse",o(b(a.that.__zoom,a.mouse[0]=ne(t,i),a.mouse[1]),a.extent,f))}),!0).on("mouseup.zoom",(function(t){u.on("mousemove.zoom mouseup.zoom",null),ue(t.view,a.moved),Sw(t),a.event(t).end()}),!0),c=ne(t,i),s=t.clientX,l=t.clientY;ae(t.view),Aw(t),a.mouse=[c,this.__zoom.invert(c)],Gi(this),a.start()}}function S(t,...n){if(r.apply(this,arguments)){var e=this.__zoom,a=ne(t.changedTouches?t.changedTouches[0]:t,this),u=e.invert(a),c=e.k*(t.shiftKey?.5:2),l=o(b(_(e,c),a,u),i.apply(this,n),f);Sw(t),s>0?Zn(this).transition().duration(s).call(x,l,a,t):Zn(this).call(v.transform,l,a,t)}}function E(e,...i){if(r.apply(this,arguments)){var o,a,u,c,f=e.touches,s=f.length,l=w(this,i,e.changedTouches.length===s).event(e);for(Aw(e),a=0;a { + var __create = Object.create; + var __defProp = Object.defineProperty; + var __getOwnPropDesc = Object.getOwnPropertyDescriptor; + var __getOwnPropNames = Object.getOwnPropertyNames; + var __getProtoOf = Object.getPrototypeOf; + var __hasOwnProp = Object.prototype.hasOwnProperty; + var __esm = (fn, res) => function __init() { + return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; + }; + var __commonJS = (cb, mod3) => function __require() { + return mod3 || (0, cb[__getOwnPropNames(cb)[0]])((mod3 = { exports: {} }).exports, mod3), mod3.exports; + }; + var __export = (target2, all) => { + for (var name2 in all) + __defProp(target2, name2, { get: all[name2], enumerable: true }); + }; + var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; + }; + var __toESM = (mod3, isNodeMode, target2) => (target2 = mod3 != null ? __create(__getProtoOf(mod3)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod3 || !mod3.__esModule ? __defProp(target2, "default", { value: mod3, enumerable: true }) : target2, + mod3 + )); + + // node_modules/@probe.gl/env/dist/lib/globals.js + var window_2, document_2, process_, console_, navigator_; + var init_globals = __esm({ + "node_modules/@probe.gl/env/dist/lib/globals.js"() { + window_2 = globalThis; + document_2 = globalThis.document || {}; + process_ = globalThis.process || {}; + console_ = globalThis.console; + navigator_ = globalThis.navigator || {}; + } + }); + + // node_modules/@probe.gl/env/dist/lib/is-electron.js + function isElectron(mockUserAgent) { + if (typeof window !== "undefined" && window.process?.type === "renderer") { + return true; + } + if (typeof process !== "undefined" && Boolean(process.versions?.["electron"])) { + return true; + } + const realUserAgent = typeof navigator !== "undefined" && navigator.userAgent; + const userAgent2 = mockUserAgent || realUserAgent; + return Boolean(userAgent2 && userAgent2.indexOf("Electron") >= 0); + } + var init_is_electron = __esm({ + "node_modules/@probe.gl/env/dist/lib/is-electron.js"() { + } + }); + + // node_modules/@probe.gl/env/dist/lib/is-browser.js + function isBrowser2() { + const isNode = ( + // @ts-expect-error + typeof process === "object" && String(process) === "[object process]" && !process?.browser + ); + return !isNode || isElectron(); + } + var init_is_browser = __esm({ + "node_modules/@probe.gl/env/dist/lib/is-browser.js"() { + init_is_electron(); + } + }); + + // node_modules/@probe.gl/env/dist/lib/get-browser.js + function getBrowser(mockUserAgent) { + if (!mockUserAgent && !isBrowser2()) { + return "Node"; + } + if (isElectron(mockUserAgent)) { + return "Electron"; + } + const userAgent2 = mockUserAgent || navigator_.userAgent || ""; + if (userAgent2.indexOf("Edge") > -1) { + return "Edge"; + } + if (globalThis.chrome) { + return "Chrome"; + } + if (globalThis.safari) { + return "Safari"; + } + if (globalThis.mozInnerScreenX) { + return "Firefox"; + } + return "Unknown"; + } + var init_get_browser = __esm({ + "node_modules/@probe.gl/env/dist/lib/get-browser.js"() { + init_is_browser(); + init_is_electron(); + init_globals(); + } + }); + + // node_modules/@probe.gl/env/dist/index.js + var VERSION; + var init_dist = __esm({ + "node_modules/@probe.gl/env/dist/index.js"() { + init_globals(); + init_is_browser(); + init_get_browser(); + VERSION = true ? "4.1.1" : "untranspiled source"; + } + }); + + // node_modules/@probe.gl/log/dist/utils/assert.js + function assert2(condition, message2) { + if (!condition) { + throw new Error(message2 || "Assertion failed"); + } + } + var init_assert = __esm({ + "node_modules/@probe.gl/log/dist/utils/assert.js"() { + } + }); + + // node_modules/@probe.gl/log/dist/loggers/log-utils.js + function normalizeLogLevel(logLevel) { + if (!logLevel) { + return 0; + } + let resolvedLevel; + switch (typeof logLevel) { + case "number": + resolvedLevel = logLevel; + break; + case "object": + resolvedLevel = logLevel.logLevel || logLevel.priority || 0; + break; + default: + return 0; + } + assert2(Number.isFinite(resolvedLevel) && resolvedLevel >= 0); + return resolvedLevel; + } + function normalizeArguments(opts) { + const { logLevel, message: message2 } = opts; + opts.logLevel = normalizeLogLevel(logLevel); + const args = opts.args ? Array.from(opts.args) : []; + while (args.length && args.shift() !== message2) { + } + switch (typeof logLevel) { + case "string": + case "function": + if (message2 !== void 0) { + args.unshift(message2); + } + opts.message = logLevel; + break; + case "object": + Object.assign(opts, logLevel); + break; + default: + } + if (typeof opts.message === "function") { + opts.message = opts.message(); + } + const messageType = typeof opts.message; + assert2(messageType === "string" || messageType === "object"); + return Object.assign(opts, { args }, opts.opts); + } + var init_log_utils = __esm({ + "node_modules/@probe.gl/log/dist/loggers/log-utils.js"() { + init_assert(); + } + }); + + // node_modules/@probe.gl/log/dist/loggers/base-log.js + var noop, BaseLog; + var init_base_log = __esm({ + "node_modules/@probe.gl/log/dist/loggers/base-log.js"() { + init_log_utils(); + noop = () => { + }; + BaseLog = class { + constructor({ level = 0 } = {}) { + this.userData = {}; + this._onceCache = /* @__PURE__ */ new Set(); + this._level = level; + } + set level(newLevel) { + this.setLevel(newLevel); + } + get level() { + return this.getLevel(); + } + setLevel(level) { + this._level = level; + return this; + } + getLevel() { + return this._level; + } + // Unconditional logging + warn(message2, ...args) { + return this._log("warn", 0, message2, args, { once: true }); + } + error(message2, ...args) { + return this._log("error", 0, message2, args); + } + // Conditional logging + log(logLevel, message2, ...args) { + return this._log("log", logLevel, message2, args); + } + info(logLevel, message2, ...args) { + return this._log("info", logLevel, message2, args); + } + once(logLevel, message2, ...args) { + return this._log("once", logLevel, message2, args, { once: true }); + } + _log(type, logLevel, message2, args, options = {}) { + const normalized = normalizeArguments({ + logLevel, + message: message2, + args: this._buildArgs(logLevel, message2, args), + opts: options + }); + return this._createLogFunction(type, normalized, options); + } + _buildArgs(logLevel, message2, args) { + return [logLevel, message2, ...args]; + } + _createLogFunction(type, normalized, options) { + if (!this._shouldLog(normalized.logLevel)) { + return noop; + } + const tag = this._getOnceTag(options.tag ?? normalized.tag ?? normalized.message); + if ((options.once || normalized.once) && tag !== void 0) { + if (this._onceCache.has(tag)) { + return noop; + } + this._onceCache.add(tag); + } + return this._emit(type, normalized); + } + _shouldLog(logLevel) { + return this.getLevel() >= normalizeLogLevel(logLevel); + } + _getOnceTag(tag) { + if (tag === void 0) { + return void 0; + } + try { + return typeof tag === "string" ? tag : String(tag); + } catch { + return void 0; + } + } + }; + } + }); + + // node_modules/@probe.gl/log/dist/utils/local-storage.js + function getStorage(type) { + try { + const storage = window[type]; + const x = "__storage_test__"; + storage.setItem(x, x); + storage.removeItem(x); + return storage; + } catch (e) { + return null; + } + } + var LocalStorage; + var init_local_storage = __esm({ + "node_modules/@probe.gl/log/dist/utils/local-storage.js"() { + LocalStorage = class { + constructor(id, defaultConfig, type = "sessionStorage") { + this.storage = getStorage(type); + this.id = id; + this.config = defaultConfig; + this._loadConfiguration(); + } + getConfiguration() { + return this.config; + } + setConfiguration(configuration) { + Object.assign(this.config, configuration); + if (this.storage) { + const serialized = JSON.stringify(this.config); + this.storage.setItem(this.id, serialized); + } + } + // Get config from persistent store, if available + _loadConfiguration() { + let configuration = {}; + if (this.storage) { + const serializedConfiguration = this.storage.getItem(this.id); + configuration = serializedConfiguration ? JSON.parse(serializedConfiguration) : {}; + } + Object.assign(this.config, configuration); + return this; + } + }; + } + }); + + // node_modules/@probe.gl/log/dist/utils/formatters.js + function formatTime(ms) { + let formatted; + if (ms < 10) { + formatted = `${ms.toFixed(2)}ms`; + } else if (ms < 100) { + formatted = `${ms.toFixed(1)}ms`; + } else if (ms < 1e3) { + formatted = `${ms.toFixed(0)}ms`; + } else { + formatted = `${(ms / 1e3).toFixed(2)}s`; + } + return formatted; + } + function leftPad(string, length4 = 8) { + const padLength = Math.max(length4 - string.length, 0); + return `${" ".repeat(padLength)}${string}`; + } + var init_formatters = __esm({ + "node_modules/@probe.gl/log/dist/utils/formatters.js"() { + } + }); + + // node_modules/@probe.gl/log/dist/utils/color.js + function getColor(color2) { + if (typeof color2 !== "string") { + return color2; + } + color2 = color2.toUpperCase(); + return COLOR[color2] || COLOR.WHITE; + } + function addColor(string, color2, background) { + if (!isBrowser2 && typeof string === "string") { + if (color2) { + const colorCode = getColor(color2); + string = `\x1B[${colorCode}m${string}\x1B[39m`; + } + if (background) { + const colorCode = getColor(background); + string = `\x1B[${colorCode + BACKGROUND_INCREMENT}m${string}\x1B[49m`; + } + } + return string; + } + var COLOR, BACKGROUND_INCREMENT; + var init_color = __esm({ + "node_modules/@probe.gl/log/dist/utils/color.js"() { + init_dist(); + (function(COLOR2) { + COLOR2[COLOR2["BLACK"] = 30] = "BLACK"; + COLOR2[COLOR2["RED"] = 31] = "RED"; + COLOR2[COLOR2["GREEN"] = 32] = "GREEN"; + COLOR2[COLOR2["YELLOW"] = 33] = "YELLOW"; + COLOR2[COLOR2["BLUE"] = 34] = "BLUE"; + COLOR2[COLOR2["MAGENTA"] = 35] = "MAGENTA"; + COLOR2[COLOR2["CYAN"] = 36] = "CYAN"; + COLOR2[COLOR2["WHITE"] = 37] = "WHITE"; + COLOR2[COLOR2["BRIGHT_BLACK"] = 90] = "BRIGHT_BLACK"; + COLOR2[COLOR2["BRIGHT_RED"] = 91] = "BRIGHT_RED"; + COLOR2[COLOR2["BRIGHT_GREEN"] = 92] = "BRIGHT_GREEN"; + COLOR2[COLOR2["BRIGHT_YELLOW"] = 93] = "BRIGHT_YELLOW"; + COLOR2[COLOR2["BRIGHT_BLUE"] = 94] = "BRIGHT_BLUE"; + COLOR2[COLOR2["BRIGHT_MAGENTA"] = 95] = "BRIGHT_MAGENTA"; + COLOR2[COLOR2["BRIGHT_CYAN"] = 96] = "BRIGHT_CYAN"; + COLOR2[COLOR2["BRIGHT_WHITE"] = 97] = "BRIGHT_WHITE"; + })(COLOR || (COLOR = {})); + BACKGROUND_INCREMENT = 10; + } + }); + + // node_modules/@probe.gl/log/dist/utils/autobind.js + function autobind(obj, predefined = ["constructor"]) { + const proto = Object.getPrototypeOf(obj); + const propNames = Object.getOwnPropertyNames(proto); + const object = obj; + for (const key of propNames) { + const value = object[key]; + if (typeof value === "function") { + if (!predefined.find((name2) => key === name2)) { + object[key] = value.bind(obj); + } + } + } + } + var init_autobind = __esm({ + "node_modules/@probe.gl/log/dist/utils/autobind.js"() { + } + }); + + // node_modules/@probe.gl/log/dist/utils/hi-res-timestamp.js + function getHiResTimestamp() { + let timestamp; + if (isBrowser2() && window_2.performance) { + timestamp = window_2?.performance?.now?.(); + } else if ("hrtime" in process_) { + const timeParts = process_?.hrtime?.(); + timestamp = timeParts[0] * 1e3 + timeParts[1] / 1e6; + } else { + timestamp = Date.now(); + } + return timestamp; + } + var init_hi_res_timestamp = __esm({ + "node_modules/@probe.gl/log/dist/utils/hi-res-timestamp.js"() { + init_dist(); + } + }); + + // node_modules/@probe.gl/log/dist/loggers/probe-log.js + function decorateMessage(id, message2, opts) { + if (typeof message2 === "string") { + const time = opts.time ? leftPad(formatTime(opts.total)) : ""; + message2 = opts.time ? `${id}: ${time} ${message2}` : `${id}: ${message2}`; + message2 = addColor(message2, opts.color, opts.background); + } + return message2; + } + function getTableHeader(table) { + for (const key in table) { + for (const title in table[key]) { + return title || "untitled"; + } + } + return "empty"; + } + var originalConsole, DEFAULT_LOG_CONFIGURATION, ProbeLog; + var init_probe_log = __esm({ + "node_modules/@probe.gl/log/dist/loggers/probe-log.js"() { + init_dist(); + init_base_log(); + init_local_storage(); + init_formatters(); + init_color(); + init_autobind(); + init_assert(); + init_hi_res_timestamp(); + originalConsole = { + debug: isBrowser2() ? console.debug || console.log : console.log, + log: console.log, + info: console.info, + warn: console.warn, + error: console.error + }; + DEFAULT_LOG_CONFIGURATION = { + enabled: true, + level: 0 + }; + ProbeLog = class extends BaseLog { + constructor({ id } = { id: "" }) { + super({ level: 0 }); + this.VERSION = VERSION; + this._startTs = getHiResTimestamp(); + this._deltaTs = getHiResTimestamp(); + this.userData = {}; + this.LOG_THROTTLE_TIMEOUT = 0; + this.id = id; + this.userData = {}; + this._storage = new LocalStorage(`__probe-${this.id}__`, { [this.id]: DEFAULT_LOG_CONFIGURATION }); + this.timeStamp(`${this.id} started`); + autobind(this); + Object.seal(this); + } + isEnabled() { + return this._getConfiguration().enabled; + } + getLevel() { + return this._getConfiguration().level; + } + /** @return milliseconds, with fractions */ + getTotal() { + return Number((getHiResTimestamp() - this._startTs).toPrecision(10)); + } + /** @return milliseconds, with fractions */ + getDelta() { + return Number((getHiResTimestamp() - this._deltaTs).toPrecision(10)); + } + /** @deprecated use logLevel */ + set priority(newPriority) { + this.level = newPriority; + } + /** @deprecated use logLevel */ + get priority() { + return this.level; + } + /** @deprecated use logLevel */ + getPriority() { + return this.level; + } + // Configure + enable(enabled = true) { + this._updateConfiguration({ enabled }); + return this; + } + setLevel(level) { + this._updateConfiguration({ level }); + return this; + } + /** return the current status of the setting */ + get(setting) { + return this._getConfiguration()[setting]; + } + // update the status of the setting + set(setting, value) { + this._updateConfiguration({ [setting]: value }); + } + /** Logs the current settings as a table */ + settings() { + if (console.table) { + console.table(this._storage.config); + } else { + console.log(this._storage.config); + } + } + // Unconditional logging + assert(condition, message2) { + if (!condition) { + throw new Error(message2 || "Assertion failed"); + } + } + warn(message2, ...args) { + return this._log("warn", 0, message2, args, { + method: originalConsole.warn, + once: true + }); + } + error(message2, ...args) { + return this._log("error", 0, message2, args, { + method: originalConsole.error + }); + } + /** Print a deprecation warning */ + deprecated(oldUsage, newUsage) { + return this.warn(`\`${oldUsage}\` is deprecated and will be removed in a later version. Use \`${newUsage}\` instead`); + } + /** Print a removal warning */ + removed(oldUsage, newUsage) { + return this.error(`\`${oldUsage}\` has been removed. Use \`${newUsage}\` instead`); + } + probe(logLevel, message2, ...args) { + return this._log("log", logLevel, message2, args, { + method: originalConsole.log, + time: true, + once: true + }); + } + log(logLevel, message2, ...args) { + return this._log("log", logLevel, message2, args, { + method: originalConsole.debug + }); + } + info(logLevel, message2, ...args) { + return this._log("info", logLevel, message2, args, { method: console.info }); + } + once(logLevel, message2, ...args) { + return this._log("once", logLevel, message2, args, { + method: originalConsole.debug || originalConsole.info, + once: true + }); + } + /** Logs an object as a table */ + table(logLevel, table, columns) { + if (table) { + return this._log("table", logLevel, table, columns && [columns] || [], { + method: console.table || noop, + tag: getTableHeader(table) + }); + } + return noop; + } + time(logLevel, message2) { + return this._log("time", logLevel, message2, [], { + method: console.time ? console.time : console.info + }); + } + timeEnd(logLevel, message2) { + return this._log("time", logLevel, message2, [], { + method: console.timeEnd ? console.timeEnd : console.info + }); + } + timeStamp(logLevel, message2) { + return this._log("time", logLevel, message2, [], { + method: console.timeStamp || noop + }); + } + group(logLevel, message2, opts = { collapsed: false }) { + const method = (opts.collapsed ? console.groupCollapsed : console.group) || console.info; + return this._log("group", logLevel, message2, [], { method }); + } + groupCollapsed(logLevel, message2, opts = {}) { + return this.group(logLevel, message2, Object.assign({}, opts, { collapsed: true })); + } + groupEnd(logLevel) { + return this._log("groupEnd", logLevel, "", [], { + method: console.groupEnd || noop + }); + } + // EXPERIMENTAL + withGroup(logLevel, message2, func) { + this.group(logLevel, message2)(); + try { + func(); + } finally { + this.groupEnd(logLevel)(); + } + } + trace() { + if (console.trace) { + console.trace(); + } + } + _shouldLog(logLevel) { + return this.isEnabled() && super._shouldLog(logLevel); + } + _emit(_type, normalized) { + const method = normalized.method; + assert2(method); + normalized.total = this.getTotal(); + normalized.delta = this.getDelta(); + this._deltaTs = getHiResTimestamp(); + const message2 = decorateMessage(this.id, normalized.message, normalized); + return method.bind(console, message2, ...normalized.args); + } + _getConfiguration() { + if (!this._storage.config[this.id]) { + this._updateConfiguration(DEFAULT_LOG_CONFIGURATION); + } + return this._storage.config[this.id]; + } + _updateConfiguration(configuration) { + const currentConfiguration = this._storage.config[this.id] || { + ...DEFAULT_LOG_CONFIGURATION + }; + this._storage.setConfiguration({ + [this.id]: { ...currentConfiguration, ...configuration } + }); + } + }; + ProbeLog.VERSION = VERSION; + } + }); + + // node_modules/@probe.gl/log/dist/init.js + var init_init = __esm({ + "node_modules/@probe.gl/log/dist/init.js"() { + globalThis.probe = {}; + } + }); + + // node_modules/@probe.gl/log/dist/index.js + var dist_default; + var init_dist2 = __esm({ + "node_modules/@probe.gl/log/dist/index.js"() { + init_probe_log(); + init_probe_log(); + init_init(); + dist_default = new ProbeLog({ id: "@probe.gl/log" }); + } + }); + + // node_modules/@probe.gl/stats/dist/utils/hi-res-timestamp.js + function getHiResTimestamp2() { + let timestamp; + if (typeof window !== "undefined" && window.performance) { + timestamp = window.performance.now(); + } else if (typeof process !== "undefined" && process.hrtime) { + const timeParts = process.hrtime(); + timestamp = timeParts[0] * 1e3 + timeParts[1] / 1e6; + } else { + timestamp = Date.now(); + } + return timestamp; + } + var init_hi_res_timestamp2 = __esm({ + "node_modules/@probe.gl/stats/dist/utils/hi-res-timestamp.js"() { + } + }); + + // node_modules/@probe.gl/stats/dist/lib/stat.js + var Stat; + var init_stat = __esm({ + "node_modules/@probe.gl/stats/dist/lib/stat.js"() { + init_hi_res_timestamp2(); + Stat = class { + constructor(name2, type) { + this.sampleSize = 1; + this.time = 0; + this.count = 0; + this.samples = 0; + this.lastTiming = 0; + this.lastSampleTime = 0; + this.lastSampleCount = 0; + this._count = 0; + this._time = 0; + this._samples = 0; + this._startTime = 0; + this._timerPending = false; + this.name = name2; + this.type = type; + this.reset(); + } + reset() { + this.time = 0; + this.count = 0; + this.samples = 0; + this.lastTiming = 0; + this.lastSampleTime = 0; + this.lastSampleCount = 0; + this._count = 0; + this._time = 0; + this._samples = 0; + this._startTime = 0; + this._timerPending = false; + return this; + } + setSampleSize(samples) { + this.sampleSize = samples; + return this; + } + /** Call to increment count (+1) */ + incrementCount() { + this.addCount(1); + return this; + } + /** Call to decrement count (-1) */ + decrementCount() { + this.subtractCount(1); + return this; + } + /** Increase count */ + addCount(value) { + this._count += value; + this._samples++; + this._checkSampling(); + return this; + } + /** Decrease count */ + subtractCount(value) { + this._count -= value; + this._samples++; + this._checkSampling(); + return this; + } + /** Add an arbitrary timing and bump the count */ + addTime(time) { + this._time += time; + this.lastTiming = time; + this._samples++; + this._checkSampling(); + return this; + } + /** Start a timer */ + timeStart() { + this._startTime = getHiResTimestamp2(); + this._timerPending = true; + return this; + } + /** End a timer. Adds to time and bumps the timing count. */ + timeEnd() { + if (!this._timerPending) { + return this; + } + this.addTime(getHiResTimestamp2() - this._startTime); + this._timerPending = false; + this._checkSampling(); + return this; + } + getSampleAverageCount() { + return this.sampleSize > 0 ? this.lastSampleCount / this.sampleSize : 0; + } + /** Calculate average time / count for the previous window */ + getSampleAverageTime() { + return this.sampleSize > 0 ? this.lastSampleTime / this.sampleSize : 0; + } + /** Calculate counts per second for the previous window */ + getSampleHz() { + return this.lastSampleTime > 0 ? this.sampleSize / (this.lastSampleTime / 1e3) : 0; + } + getAverageCount() { + return this.samples > 0 ? this.count / this.samples : 0; + } + /** Calculate average time / count */ + getAverageTime() { + return this.samples > 0 ? this.time / this.samples : 0; + } + /** Calculate counts per second */ + getHz() { + return this.time > 0 ? this.samples / (this.time / 1e3) : 0; + } + _checkSampling() { + if (this._samples === this.sampleSize) { + this.lastSampleTime = this._time; + this.lastSampleCount = this._count; + this.count += this._count; + this.time += this._time; + this.samples += this._samples; + this._time = 0; + this._count = 0; + this._samples = 0; + } + } + }; + } + }); + + // node_modules/@probe.gl/stats/dist/lib/stats.js + var Stats; + var init_stats = __esm({ + "node_modules/@probe.gl/stats/dist/lib/stats.js"() { + init_stat(); + Stats = class { + constructor(options) { + this.stats = {}; + this.id = options.id; + this.stats = {}; + this._initializeStats(options.stats); + Object.seal(this); + } + /** Acquire a stat. Create if it doesn't exist. */ + get(name2, type = "count") { + return this._getOrCreate({ name: name2, type }); + } + get size() { + return Object.keys(this.stats).length; + } + /** Reset all stats */ + reset() { + for (const stat of Object.values(this.stats)) { + stat.reset(); + } + return this; + } + forEach(fn) { + for (const stat of Object.values(this.stats)) { + fn(stat); + } + } + getTable() { + const table = {}; + this.forEach((stat) => { + table[stat.name] = { + time: stat.time || 0, + count: stat.count || 0, + average: stat.getAverageTime() || 0, + hz: stat.getHz() || 0 + }; + }); + return table; + } + _initializeStats(stats = []) { + stats.forEach((stat) => this._getOrCreate(stat)); + } + _getOrCreate(stat) { + const { name: name2, type } = stat; + let result = this.stats[name2]; + if (!result) { + if (stat instanceof Stat) { + result = stat; + } else { + result = new Stat(name2, type); + } + this.stats[name2] = result; + } + return result; + } + }; + } + }); + + // node_modules/@probe.gl/stats/dist/index.js + var init_dist3 = __esm({ + "node_modules/@probe.gl/stats/dist/index.js"() { + init_stats(); + init_stat(); + init_hi_res_timestamp2(); + } + }); + + // node_modules/@luma.gl/core/dist/utils/stats-manager.js + function initializeStats(stats, orderedStatNames) { + const statsMap = stats.stats; + let addedOrderedStat = false; + for (const statName of orderedStatNames) { + if (!statsMap[statName]) { + stats.get(statName); + addedOrderedStat = true; + } + } + const statCount = Object.keys(statsMap).length; + const cachedStats = ORDERED_STATS_CACHE.get(stats); + if (!addedOrderedStat && cachedStats?.orderedStatNames === orderedStatNames && cachedStats.statCount === statCount) { + return; + } + const reorderedStats = {}; + let orderedStatNamesSet = ORDERED_STAT_NAME_SET_CACHE.get(orderedStatNames); + if (!orderedStatNamesSet) { + orderedStatNamesSet = new Set(orderedStatNames); + ORDERED_STAT_NAME_SET_CACHE.set(orderedStatNames, orderedStatNamesSet); + } + for (const statName of orderedStatNames) { + if (statsMap[statName]) { + reorderedStats[statName] = statsMap[statName]; + } + } + for (const [statName, stat] of Object.entries(statsMap)) { + if (!orderedStatNamesSet.has(statName)) { + reorderedStats[statName] = stat; + } + } + for (const statName of Object.keys(statsMap)) { + delete statsMap[statName]; + } + Object.assign(statsMap, reorderedStats); + ORDERED_STATS_CACHE.set(stats, { orderedStatNames, statCount }); + } + var GPU_TIME_AND_MEMORY_STATS, GPU_TIME_AND_MEMORY_STAT_ORDER, ORDERED_STATS_CACHE, ORDERED_STAT_NAME_SET_CACHE, StatsManager, lumaStats; + var init_stats_manager = __esm({ + "node_modules/@luma.gl/core/dist/utils/stats-manager.js"() { + init_dist3(); + GPU_TIME_AND_MEMORY_STATS = "GPU Time and Memory"; + GPU_TIME_AND_MEMORY_STAT_ORDER = [ + "Adapter", + "GPU", + "GPU Type", + "GPU Backend", + "Frame Rate", + "CPU Time", + "GPU Time", + "GPU Memory", + "Buffer Memory", + "Texture Memory", + "Referenced Buffer Memory", + "Referenced Texture Memory", + "Swap Chain Texture" + ]; + ORDERED_STATS_CACHE = /* @__PURE__ */ new WeakMap(); + ORDERED_STAT_NAME_SET_CACHE = /* @__PURE__ */ new WeakMap(); + StatsManager = class { + stats = /* @__PURE__ */ new Map(); + getStats(name2) { + return this.get(name2); + } + get(name2) { + if (!this.stats.has(name2)) { + this.stats.set(name2, new Stats({ id: name2 })); + } + const stats = this.stats.get(name2); + if (name2 === GPU_TIME_AND_MEMORY_STATS) { + initializeStats(stats, GPU_TIME_AND_MEMORY_STAT_ORDER); + } + return stats; + } + }; + lumaStats = new StatsManager(); + } + }); + + // node_modules/@luma.gl/core/dist/utils/log.js + var log2; + var init_log = __esm({ + "node_modules/@luma.gl/core/dist/utils/log.js"() { + init_dist2(); + log2 = new ProbeLog({ id: "luma.gl" }); + } + }); + + // node_modules/@luma.gl/core/dist/utils/uid.js + function uid(id = "id") { + uidCounters[id] = uidCounters[id] || 1; + const count2 = uidCounters[id]++; + return `${id}-${count2}`; + } + var uidCounters; + var init_uid = __esm({ + "node_modules/@luma.gl/core/dist/utils/uid.js"() { + uidCounters = {}; + } + }); + + // node_modules/@luma.gl/core/dist/adapter/resources/resource.js + function selectivelyMerge(props, defaultProps8) { + const mergedProps = { ...defaultProps8 }; + for (const key in props) { + if (props[key] !== void 0) { + mergedProps[key] = props[key]; + } + } + return mergedProps; + } + function initializeStats2(stats, orderedStatNames) { + const statsMap = stats.stats; + let addedOrderedStat = false; + for (const statName of orderedStatNames) { + if (!statsMap[statName]) { + stats.get(statName); + addedOrderedStat = true; + } + } + const statCount = Object.keys(statsMap).length; + const cachedStats = ORDERED_STATS_CACHE2.get(stats); + if (!addedOrderedStat && cachedStats?.orderedStatNames === orderedStatNames && cachedStats.statCount === statCount) { + return; + } + const reorderedStats = {}; + let orderedStatNamesSet = ORDERED_STAT_NAME_SET_CACHE2.get(orderedStatNames); + if (!orderedStatNamesSet) { + orderedStatNamesSet = new Set(orderedStatNames); + ORDERED_STAT_NAME_SET_CACHE2.set(orderedStatNames, orderedStatNamesSet); + } + for (const statName of orderedStatNames) { + if (statsMap[statName]) { + reorderedStats[statName] = statsMap[statName]; + } + } + for (const [statName, stat] of Object.entries(statsMap)) { + if (!orderedStatNamesSet.has(statName)) { + reorderedStats[statName] = stat; + } + } + for (const statName of Object.keys(statsMap)) { + delete statsMap[statName]; + } + Object.assign(statsMap, reorderedStats); + ORDERED_STATS_CACHE2.set(stats, { orderedStatNames, statCount }); + } + function getResourceCountStatOrder(device) { + return device.type === "webgl" ? WEBGL_RESOURCE_COUNT_STAT_ORDER : BASE_RESOURCE_COUNT_STAT_ORDER; + } + function getCpuHotspotProfiler(device) { + const profiler = device.userData[CPU_HOTSPOT_PROFILER_MODULE]; + return profiler?.enabled ? profiler : null; + } + function getTimestamp() { + return globalThis.performance?.now?.() ?? Date.now(); + } + function recordTransientCanvasResourceCreate(device, name2) { + const profiler = getCpuHotspotProfiler(device); + if (!profiler || !profiler.activeDefaultFramebufferAcquireDepth) { + return; + } + profiler.transientCanvasResourceCreates = (profiler.transientCanvasResourceCreates || 0) + 1; + switch (name2) { + case "Texture": + profiler.transientCanvasTextureCreates = (profiler.transientCanvasTextureCreates || 0) + 1; + break; + case "TextureView": + profiler.transientCanvasTextureViewCreates = (profiler.transientCanvasTextureViewCreates || 0) + 1; + break; + case "Sampler": + profiler.transientCanvasSamplerCreates = (profiler.transientCanvasSamplerCreates || 0) + 1; + break; + case "Framebuffer": + profiler.transientCanvasFramebufferCreates = (profiler.transientCanvasFramebufferCreates || 0) + 1; + break; + default: + break; + } + } + function getCanonicalResourceName(resource) { + let prototype = Object.getPrototypeOf(resource); + while (prototype) { + const parentPrototype = Object.getPrototypeOf(prototype); + if (!parentPrototype || parentPrototype === Resource.prototype) { + return getPrototypeToStringTag(prototype) || resource[Symbol.toStringTag] || resource.constructor.name; + } + prototype = parentPrototype; + } + return resource[Symbol.toStringTag] || resource.constructor.name; + } + function getPrototypeToStringTag(prototype) { + const descriptor = Object.getOwnPropertyDescriptor(prototype, Symbol.toStringTag); + if (typeof descriptor?.get === "function") { + return descriptor.get.call(prototype); + } + if (typeof descriptor?.value === "string") { + return descriptor.value; + } + return null; + } + var CPU_HOTSPOT_PROFILER_MODULE, RESOURCE_COUNTS_STATS, LEGACY_RESOURCE_COUNTS_STATS, GPU_TIME_AND_MEMORY_STATS2, BASE_RESOURCE_COUNT_ORDER, WEBGL_RESOURCE_COUNT_ORDER, BASE_RESOURCE_COUNT_STAT_ORDER, WEBGL_RESOURCE_COUNT_STAT_ORDER, ORDERED_STATS_CACHE2, ORDERED_STAT_NAME_SET_CACHE2, Resource; + var init_resource = __esm({ + "node_modules/@luma.gl/core/dist/adapter/resources/resource.js"() { + init_uid(); + CPU_HOTSPOT_PROFILER_MODULE = "cpu-hotspot-profiler"; + RESOURCE_COUNTS_STATS = "GPU Resource Counts"; + LEGACY_RESOURCE_COUNTS_STATS = "Resource Counts"; + GPU_TIME_AND_MEMORY_STATS2 = "GPU Time and Memory"; + BASE_RESOURCE_COUNT_ORDER = [ + "Resources", + "Buffers", + "Textures", + "Samplers", + "TextureViews", + "Framebuffers", + "QuerySets", + "Shaders", + "RenderPipelines", + "ComputePipelines", + "PipelineLayouts", + "VertexArrays", + "RenderPasss", + "ComputePasss", + "CommandEncoders", + "CommandBuffers" + ]; + WEBGL_RESOURCE_COUNT_ORDER = [ + "Resources", + "Buffers", + "Textures", + "Samplers", + "TextureViews", + "Framebuffers", + "QuerySets", + "Shaders", + "RenderPipelines", + "SharedRenderPipelines", + "ComputePipelines", + "PipelineLayouts", + "VertexArrays", + "RenderPasss", + "ComputePasss", + "CommandEncoders", + "CommandBuffers" + ]; + BASE_RESOURCE_COUNT_STAT_ORDER = BASE_RESOURCE_COUNT_ORDER.flatMap((resourceType) => [ + `${resourceType} Created`, + `${resourceType} Active` + ]); + WEBGL_RESOURCE_COUNT_STAT_ORDER = WEBGL_RESOURCE_COUNT_ORDER.flatMap((resourceType) => [ + `${resourceType} Created`, + `${resourceType} Active` + ]); + ORDERED_STATS_CACHE2 = /* @__PURE__ */ new WeakMap(); + ORDERED_STAT_NAME_SET_CACHE2 = /* @__PURE__ */ new WeakMap(); + Resource = class { + /** Default properties for resource */ + static defaultProps = { + id: "undefined", + handle: void 0, + userData: void 0 + }; + toString() { + return `${this[Symbol.toStringTag] || this.constructor.name}:"${this.id}"`; + } + /** props.id, for debugging. */ + id; + /** The props that this resource was created with */ + props; + /** User data object, reserved for the application */ + userData = {}; + /** The device that this resource is associated with - TODO can we remove this dup? */ + _device; + /** Whether this resource has been destroyed */ + destroyed = false; + /** For resources that allocate GPU memory */ + allocatedBytes = 0; + /** Stats bucket currently holding the tracked allocation */ + allocatedBytesName = null; + /** Attached resources will be destroyed when this resource is destroyed. Tracks auto-created "sub" resources. */ + _attachedResources = /* @__PURE__ */ new Set(); + /** + * Create a new Resource. Called from Subclass + */ + constructor(device, props, defaultProps8) { + if (!device) { + throw new Error("no device"); + } + this._device = device; + this.props = selectivelyMerge(props, defaultProps8); + const id = this.props.id !== "undefined" ? this.props.id : uid(this[Symbol.toStringTag]); + this.props.id = id; + this.id = id; + this.userData = this.props.userData || {}; + this.addStats(); + } + /** + * destroy can be called on any resource to release it before it is garbage collected. + */ + destroy() { + if (this.destroyed) { + return; + } + this.destroyResource(); + } + /** @deprecated Use destroy() */ + delete() { + this.destroy(); + return this; + } + /** + * Combines a map of user props and default props, only including props from defaultProps + * @returns returns a map of overridden default props + */ + getProps() { + return this.props; + } + // ATTACHED RESOURCES + /** + * Attaches a resource. Attached resources are auto destroyed when this resource is destroyed + * Called automatically when sub resources are auto created but can be called by application + */ + attachResource(resource) { + this._attachedResources.add(resource); + } + /** + * Detach an attached resource. The resource will no longer be auto-destroyed when this resource is destroyed. + */ + detachResource(resource) { + this._attachedResources.delete(resource); + } + /** + * Destroys a resource (only if owned), and removes from the owned (auto-destroy) list for this resource. + */ + destroyAttachedResource(resource) { + if (this._attachedResources.delete(resource)) { + resource.destroy(); + } + } + /** Destroy all owned resources. Make sure the resources are no longer needed before calling. */ + destroyAttachedResources() { + for (const resource of this._attachedResources) { + resource.destroy(); + } + this._attachedResources = /* @__PURE__ */ new Set(); + } + // PROTECTED METHODS + /** Perform all destroy steps. Can be called by derived resources when overriding destroy() */ + destroyResource() { + if (this.destroyed) { + return; + } + this.destroyAttachedResources(); + this.removeStats(); + this.destroyed = true; + } + /** Called by .destroy() to track object destruction. Subclass must call if overriding destroy() */ + removeStats() { + const profiler = getCpuHotspotProfiler(this._device); + const startTime = profiler ? getTimestamp() : 0; + const statsObjects = [ + this._device.statsManager.getStats(RESOURCE_COUNTS_STATS), + this._device.statsManager.getStats(LEGACY_RESOURCE_COUNTS_STATS) + ]; + const orderedStatNames = getResourceCountStatOrder(this._device); + for (const stats of statsObjects) { + initializeStats2(stats, orderedStatNames); + } + const name2 = this.getStatsName(); + for (const stats of statsObjects) { + stats.get("Resources Active").decrementCount(); + stats.get(`${name2}s Active`).decrementCount(); + } + if (profiler) { + profiler.statsBookkeepingCalls = (profiler.statsBookkeepingCalls || 0) + 1; + profiler.statsBookkeepingTimeMs = (profiler.statsBookkeepingTimeMs || 0) + (getTimestamp() - startTime); + } + } + /** Called by subclass to track memory allocations */ + trackAllocatedMemory(bytes, name2 = this.getStatsName()) { + const profiler = getCpuHotspotProfiler(this._device); + const startTime = profiler ? getTimestamp() : 0; + const stats = this._device.statsManager.getStats(GPU_TIME_AND_MEMORY_STATS2); + if (this.allocatedBytes > 0 && this.allocatedBytesName) { + stats.get("GPU Memory").subtractCount(this.allocatedBytes); + stats.get(`${this.allocatedBytesName} Memory`).subtractCount(this.allocatedBytes); + } + stats.get("GPU Memory").addCount(bytes); + stats.get(`${name2} Memory`).addCount(bytes); + if (profiler) { + profiler.statsBookkeepingCalls = (profiler.statsBookkeepingCalls || 0) + 1; + profiler.statsBookkeepingTimeMs = (profiler.statsBookkeepingTimeMs || 0) + (getTimestamp() - startTime); + } + this.allocatedBytes = bytes; + this.allocatedBytesName = name2; + } + /** Called by subclass to track handle-backed memory allocations separately from owned allocations */ + trackReferencedMemory(bytes, name2 = this.getStatsName()) { + this.trackAllocatedMemory(bytes, `Referenced ${name2}`); + } + /** Called by subclass to track memory deallocations */ + trackDeallocatedMemory(name2 = this.getStatsName()) { + if (this.allocatedBytes === 0) { + this.allocatedBytesName = null; + return; + } + const profiler = getCpuHotspotProfiler(this._device); + const startTime = profiler ? getTimestamp() : 0; + const stats = this._device.statsManager.getStats(GPU_TIME_AND_MEMORY_STATS2); + stats.get("GPU Memory").subtractCount(this.allocatedBytes); + stats.get(`${this.allocatedBytesName || name2} Memory`).subtractCount(this.allocatedBytes); + if (profiler) { + profiler.statsBookkeepingCalls = (profiler.statsBookkeepingCalls || 0) + 1; + profiler.statsBookkeepingTimeMs = (profiler.statsBookkeepingTimeMs || 0) + (getTimestamp() - startTime); + } + this.allocatedBytes = 0; + this.allocatedBytesName = null; + } + /** Called by subclass to deallocate handle-backed memory tracked via trackReferencedMemory() */ + trackDeallocatedReferencedMemory(name2 = this.getStatsName()) { + this.trackDeallocatedMemory(`Referenced ${name2}`); + } + /** Called by resource constructor to track object creation */ + addStats() { + const name2 = this.getStatsName(); + const profiler = getCpuHotspotProfiler(this._device); + const startTime = profiler ? getTimestamp() : 0; + const statsObjects = [ + this._device.statsManager.getStats(RESOURCE_COUNTS_STATS), + this._device.statsManager.getStats(LEGACY_RESOURCE_COUNTS_STATS) + ]; + const orderedStatNames = getResourceCountStatOrder(this._device); + for (const stats of statsObjects) { + initializeStats2(stats, orderedStatNames); + } + for (const stats of statsObjects) { + stats.get("Resources Created").incrementCount(); + stats.get("Resources Active").incrementCount(); + stats.get(`${name2}s Created`).incrementCount(); + stats.get(`${name2}s Active`).incrementCount(); + } + if (profiler) { + profiler.statsBookkeepingCalls = (profiler.statsBookkeepingCalls || 0) + 1; + profiler.statsBookkeepingTimeMs = (profiler.statsBookkeepingTimeMs || 0) + (getTimestamp() - startTime); + } + recordTransientCanvasResourceCreate(this._device, name2); + } + /** Canonical resource name used for stats buckets. */ + getStatsName() { + return getCanonicalResourceName(this); + } + }; + } + }); + + // node_modules/@luma.gl/core/dist/adapter/resources/buffer.js + var Buffer2; + var init_buffer = __esm({ + "node_modules/@luma.gl/core/dist/adapter/resources/buffer.js"() { + init_resource(); + Buffer2 = class _Buffer extends Resource { + /** Index buffer */ + static INDEX = 16; + /** Vertex buffer */ + static VERTEX = 32; + /** Uniform buffer */ + static UNIFORM = 64; + /** Storage buffer */ + static STORAGE = 128; + static INDIRECT = 256; + static QUERY_RESOLVE = 512; + // Usage Flags + static MAP_READ = 1; + static MAP_WRITE = 2; + static COPY_SRC = 4; + static COPY_DST = 8; + get [Symbol.toStringTag]() { + return "Buffer"; + } + /** The usage with which this buffer was created */ + usage; + /** For index buffers, whether indices are 8, 16 or 32 bit. Note: uint8 indices are automatically converted to uint16 for WebGPU compatibility */ + indexType; + /** "Time" of last update, can be used to check if redraw is needed */ + updateTimestamp; + constructor(device, props) { + const deducedProps = { ...props }; + if ((props.usage || 0) & _Buffer.INDEX && !props.indexType) { + if (props.data instanceof Uint32Array) { + deducedProps.indexType = "uint32"; + } else if (props.data instanceof Uint16Array) { + deducedProps.indexType = "uint16"; + } else if (props.data instanceof Uint8Array) { + deducedProps.indexType = "uint8"; + } + } + delete deducedProps.data; + super(device, deducedProps, _Buffer.defaultProps); + this.usage = deducedProps.usage || 0; + this.indexType = deducedProps.indexType; + this.updateTimestamp = device.incrementTimestamp(); + } + /** + * Create a copy of this Buffer with new byteLength, with same props but of the specified size. + * @note Does not copy contents of the cloned Buffer. + */ + clone(props) { + return this.device.createBuffer({ ...this.props, ...props }); + } + // PROTECTED METHODS (INTENDED FOR USE BY OTHER FRAMEWORK CODE ONLY) + /** Max amount of debug data saved. Two vec4's */ + static DEBUG_DATA_MAX_LENGTH = 32; + /** A partial CPU-side copy of the data in this buffer, for debugging purposes */ + debugData = new ArrayBuffer(0); + /** This doesn't handle partial non-zero offset updates correctly */ + _setDebugData(data, _byteOffset, byteLength) { + let arrayBufferView = null; + let arrayBuffer2; + if (ArrayBuffer.isView(data)) { + arrayBufferView = data; + arrayBuffer2 = data.buffer; + } else { + arrayBuffer2 = data; + } + const debugDataLength = Math.min(data ? data.byteLength : byteLength, _Buffer.DEBUG_DATA_MAX_LENGTH); + if (arrayBuffer2 === null) { + this.debugData = new ArrayBuffer(debugDataLength); + } else { + const sourceByteOffset = Math.min(arrayBufferView?.byteOffset || 0, arrayBuffer2.byteLength); + const availableByteLength = Math.max(0, arrayBuffer2.byteLength - sourceByteOffset); + const copyByteLength = Math.min(debugDataLength, availableByteLength); + this.debugData = new Uint8Array(arrayBuffer2, sourceByteOffset, copyByteLength).slice().buffer; + } + } + static defaultProps = { + ...Resource.defaultProps, + usage: 0, + // Buffer.COPY_DST | Buffer.COPY_SRC + byteLength: 0, + byteOffset: 0, + data: null, + indexType: "uint16", + onMapped: void 0 + }; + }; + } + }); + + // node_modules/@luma.gl/core/dist/shadertypes/data-types/data-type-decoder.js + var DataTypeDecoder, dataTypeDecoder, NORMALIZED_TYPE_MAP; + var init_data_type_decoder = __esm({ + "node_modules/@luma.gl/core/dist/shadertypes/data-types/data-type-decoder.js"() { + DataTypeDecoder = class { + /** + * Gets info about a data type constant (signed or normalized) + * @returns underlying primitive / signed types, byte length, normalization, integer, signed flags + */ + getDataTypeInfo(type) { + const [signedType, primitiveType, byteLength] = NORMALIZED_TYPE_MAP[type]; + const normalized = type.includes("norm"); + const integer = !normalized && !type.startsWith("float"); + const signed = type.startsWith("s"); + return { + signedType, + primitiveType, + byteLength, + normalized, + integer, + signed + // TODO - add webglOnly flag + }; + } + /** Build a vertex format from a signed data type and a component */ + getNormalizedDataType(signedDataType) { + const dataType = signedDataType; + switch (dataType) { + case "uint8": + return "unorm8"; + case "sint8": + return "snorm8"; + case "uint16": + return "unorm16"; + case "sint16": + return "snorm16"; + default: + return dataType; + } + } + /** Align offset to 1, 2 or 4 elements (4, 8 or 16 bytes) */ + alignTo(size, count2) { + switch (count2) { + case 1: + return size; + // Pad upwards to even multiple of 2 + case 2: + return size + size % 2; + // Pad upwards to even multiple of 2 + default: + return size + (4 - size % 4) % 4; + } + } + /** Returns the VariableShaderType that corresponds to a typed array */ + getDataType(arrayOrType) { + const Constructor = ArrayBuffer.isView(arrayOrType) ? arrayOrType.constructor : arrayOrType; + if (Constructor === Uint8ClampedArray) { + return "uint8"; + } + const info = Object.values(NORMALIZED_TYPE_MAP).find((entry) => Constructor === entry[4]); + if (!info) { + throw new Error(Constructor.name); + } + return info[0]; + } + /** Returns the TypedArray that corresponds to a shader data type */ + getTypedArrayConstructor(type) { + const [, , , , Constructor] = NORMALIZED_TYPE_MAP[type]; + return Constructor; + } + }; + dataTypeDecoder = new DataTypeDecoder(); + NORMALIZED_TYPE_MAP = { + uint8: ["uint8", "u32", 1, false, Uint8Array], + sint8: ["sint8", "i32", 1, false, Int8Array], + unorm8: ["uint8", "f32", 1, true, Uint8Array], + snorm8: ["sint8", "f32", 1, true, Int8Array], + uint16: ["uint16", "u32", 2, false, Uint16Array], + sint16: ["sint16", "i32", 2, false, Int16Array], + unorm16: ["uint16", "u32", 2, true, Uint16Array], + snorm16: ["sint16", "i32", 2, true, Int16Array], + float16: ["float16", "f16", 2, false, Uint16Array], + float32: ["float32", "f32", 4, false, Float32Array], + uint32: ["uint32", "u32", 4, false, Uint32Array], + sint32: ["sint32", "i32", 4, false, Int32Array] + }; + } + }); + + // node_modules/@luma.gl/core/dist/shadertypes/vertex-types/vertex-format-decoder.js + var VertexFormatDecoder, vertexFormatDecoder; + var init_vertex_format_decoder = __esm({ + "node_modules/@luma.gl/core/dist/shadertypes/vertex-types/vertex-format-decoder.js"() { + init_data_type_decoder(); + VertexFormatDecoder = class { + /** + * Decodes a vertex format, returning type, components, byte length and flags (integer, signed, normalized) + */ + getVertexFormatInfo(format2) { + let webglOnly; + if (format2.endsWith("-webgl")) { + format2.replace("-webgl", ""); + webglOnly = true; + } + const [type_, count2] = format2.split("x"); + const type = type_; + const components = count2 ? parseInt(count2) : 1; + const decodedType = dataTypeDecoder.getDataTypeInfo(type); + const result = { + type, + components, + byteLength: decodedType.byteLength * components, + integer: decodedType.integer, + signed: decodedType.signed, + normalized: decodedType.normalized + }; + if (webglOnly) { + result.webglOnly = true; + } + return result; + } + /** Build a vertex format from a signed data type and a component */ + makeVertexFormat(signedDataType, components, normalized) { + const dataType = normalized ? dataTypeDecoder.getNormalizedDataType(signedDataType) : signedDataType; + switch (dataType) { + // Special cases for WebGL-only x3 formats that WebGPU does not support. + case "unorm8": + if (components === 1) { + return "unorm8"; + } + if (components === 3) { + return "unorm8x3-webgl"; + } + return `${dataType}x${components}`; + case "snorm8": + if (components === 1) { + return "snorm8"; + } + if (components === 3) { + return "snorm8x3-webgl"; + } + return `${dataType}x${components}`; + case "uint8": + case "sint8": + if (components === 1 || components === 3) { + throw new Error(`size: ${components}`); + } + return `${dataType}x${components}`; + case "uint16": + if (components === 1) { + return "uint16"; + } + if (components === 3) { + return "uint16x3-webgl"; + } + return `${dataType}x${components}`; + case "sint16": + if (components === 1) { + return "sint16"; + } + if (components === 3) { + return "sint16x3-webgl"; + } + return `${dataType}x${components}`; + case "unorm16": + if (components === 1) { + return "unorm16"; + } + if (components === 3) { + return "unorm16x3-webgl"; + } + return `${dataType}x${components}`; + case "snorm16": + if (components === 1) { + return "snorm16"; + } + if (components === 3) { + return "snorm16x3-webgl"; + } + return `${dataType}x${components}`; + case "float16": + if (components === 1 || components === 3) { + throw new Error(`size: ${components}`); + } + return `${dataType}x${components}`; + default: + return components === 1 ? dataType : `${dataType}x${components}`; + } + } + /** Get the vertex format for an attribute with TypedArray and size */ + getVertexFormatFromAttribute(typedArray, size, normalized) { + if (!size || size > 4) { + throw new Error(`size ${size}`); + } + const components = size; + const signedDataType = dataTypeDecoder.getDataType(typedArray); + return this.makeVertexFormat(signedDataType, components, normalized); + } + /** + * Return a "default" vertex format for a certain shader data type + * The simplest vertex format that matches the shader attribute's data type + */ + getCompatibleVertexFormat(opts) { + let vertexType; + switch (opts.primitiveType) { + case "f32": + vertexType = "float32"; + break; + case "i32": + vertexType = "sint32"; + break; + case "u32": + vertexType = "uint32"; + break; + case "f16": + return opts.components <= 2 ? "float16x2" : "float16x4"; + } + if (opts.components === 1) { + return vertexType; + } + return `${vertexType}x${opts.components}`; + } + }; + vertexFormatDecoder = new VertexFormatDecoder(); + } + }); + + // node_modules/@luma.gl/core/dist/shadertypes/texture-types/texture-format-table.js + function getTextureFormatDefinition(format2) { + const info = TEXTURE_FORMAT_TABLE[format2]; + if (!info) { + throw new Error(`Unsupported texture format ${format2}`); + } + return info; + } + function getTextureFormatTable() { + return TEXTURE_FORMAT_TABLE; + } + var texture_compression_bc, texture_compression_astc, texture_compression_etc2, texture_compression_etc1_webgl, texture_compression_pvrtc_webgl, texture_compression_atc_webgl, float32_renderable, float16_renderable, rgb9e5ufloat_renderable, snorm8_renderable, norm16_webgl, norm16_renderable, snorm16_renderable, float32_filterable, float16_filterable, TEXTURE_FORMAT_COLOR_DEPTH_TABLE, TEXTURE_FORMAT_COMPRESSED_TABLE, TEXTURE_FORMAT_TABLE; + var init_texture_format_table = __esm({ + "node_modules/@luma.gl/core/dist/shadertypes/texture-types/texture-format-table.js"() { + texture_compression_bc = "texture-compression-bc"; + texture_compression_astc = "texture-compression-astc"; + texture_compression_etc2 = "texture-compression-etc2"; + texture_compression_etc1_webgl = "texture-compression-etc1-webgl"; + texture_compression_pvrtc_webgl = "texture-compression-pvrtc-webgl"; + texture_compression_atc_webgl = "texture-compression-atc-webgl"; + float32_renderable = "float32-renderable-webgl"; + float16_renderable = "float16-renderable-webgl"; + rgb9e5ufloat_renderable = "rgb9e5ufloat-renderable-webgl"; + snorm8_renderable = "snorm8-renderable-webgl"; + norm16_webgl = "norm16-webgl"; + norm16_renderable = "norm16-renderable-webgl"; + snorm16_renderable = "snorm16-renderable-webgl"; + float32_filterable = "float32-filterable"; + float16_filterable = "float16-filterable-webgl"; + TEXTURE_FORMAT_COLOR_DEPTH_TABLE = { + // 8-bit formats + "r8unorm": {}, + "rg8unorm": {}, + "rgb8unorm-webgl": {}, + "rgba8unorm": {}, + "rgba8unorm-srgb": {}, + "r8snorm": { render: snorm8_renderable }, + "rg8snorm": { render: snorm8_renderable }, + "rgb8snorm-webgl": {}, + "rgba8snorm": { render: snorm8_renderable }, + "r8uint": {}, + "rg8uint": {}, + "rgba8uint": {}, + "r8sint": {}, + "rg8sint": {}, + "rgba8sint": {}, + "bgra8unorm": {}, + "bgra8unorm-srgb": {}, + "r16unorm": { f: norm16_webgl, render: norm16_renderable }, + "rg16unorm": { f: norm16_webgl, render: norm16_renderable }, + "rgb16unorm-webgl": { f: norm16_webgl, render: false }, + // rgb not renderable + "rgba16unorm": { f: norm16_webgl, render: norm16_renderable }, + "r16snorm": { f: norm16_webgl, render: snorm16_renderable }, + "rg16snorm": { f: norm16_webgl, render: snorm16_renderable }, + "rgb16snorm-webgl": { f: norm16_webgl, render: false }, + // rgb not renderable + "rgba16snorm": { f: norm16_webgl, render: snorm16_renderable }, + "r16uint": {}, + "rg16uint": {}, + "rgba16uint": {}, + "r16sint": {}, + "rg16sint": {}, + "rgba16sint": {}, + "r16float": { render: float16_renderable, filter: "float16-filterable-webgl" }, + "rg16float": { render: float16_renderable, filter: float16_filterable }, + "rgba16float": { render: float16_renderable, filter: float16_filterable }, + "r32uint": {}, + "rg32uint": {}, + "rgba32uint": {}, + "r32sint": {}, + "rg32sint": {}, + "rgba32sint": {}, + "r32float": { render: float32_renderable, filter: float32_filterable }, + "rg32float": { render: false, filter: float32_filterable }, + "rgb32float-webgl": { render: float32_renderable, filter: float32_filterable }, + "rgba32float": { render: float32_renderable, filter: float32_filterable }, + // Packed 16-bit formats + "rgba4unorm-webgl": { channels: "rgba", bitsPerChannel: [4, 4, 4, 4], packed: true }, + "rgb565unorm-webgl": { channels: "rgb", bitsPerChannel: [5, 6, 5, 0], packed: true }, + "rgb5a1unorm-webgl": { channels: "rgba", bitsPerChannel: [5, 5, 5, 1], packed: true }, + // Packed 32 bit formats + "rgb9e5ufloat": { channels: "rgb", packed: true, render: rgb9e5ufloat_renderable }, + // , filter: true}, + "rg11b10ufloat": { channels: "rgb", bitsPerChannel: [11, 11, 10, 0], packed: true, p: 1, render: float32_renderable }, + "rgb10a2unorm": { channels: "rgba", bitsPerChannel: [10, 10, 10, 2], packed: true, p: 1 }, + "rgb10a2uint": { channels: "rgba", bitsPerChannel: [10, 10, 10, 2], packed: true, p: 1 }, + // Depth/stencil Formats + // Depth and stencil formats + stencil8: { attachment: "stencil", bitsPerChannel: [8, 0, 0, 0], dataType: "uint8" }, + "depth16unorm": { attachment: "depth", bitsPerChannel: [16, 0, 0, 0], dataType: "uint16" }, + "depth24plus": { attachment: "depth", bitsPerChannel: [24, 0, 0, 0], dataType: "uint32" }, + "depth32float": { attachment: "depth", bitsPerChannel: [32, 0, 0, 0], dataType: "float32" }, + // The depth component of the "depth24plus" and "depth24plus-stencil8" formats may be implemented as either a 24-bit depth value or a "depth32float" value. + "depth24plus-stencil8": { attachment: "depth-stencil", bitsPerChannel: [24, 8, 0, 0], packed: true }, + // "depth32float-stencil8" feature + "depth32float-stencil8": { attachment: "depth-stencil", bitsPerChannel: [32, 8, 0, 0], packed: true } + }; + TEXTURE_FORMAT_COMPRESSED_TABLE = { + // BC compressed formats: check device.features.has("texture-compression-bc"); + "bc1-rgb-unorm-webgl": { f: texture_compression_bc }, + "bc1-rgb-unorm-srgb-webgl": { f: texture_compression_bc }, + "bc1-rgba-unorm": { f: texture_compression_bc }, + "bc1-rgba-unorm-srgb": { f: texture_compression_bc }, + "bc2-rgba-unorm": { f: texture_compression_bc }, + "bc2-rgba-unorm-srgb": { f: texture_compression_bc }, + "bc3-rgba-unorm": { f: texture_compression_bc }, + "bc3-rgba-unorm-srgb": { f: texture_compression_bc }, + "bc4-r-unorm": { f: texture_compression_bc }, + "bc4-r-snorm": { f: texture_compression_bc }, + "bc5-rg-unorm": { f: texture_compression_bc }, + "bc5-rg-snorm": { f: texture_compression_bc }, + "bc6h-rgb-ufloat": { f: texture_compression_bc }, + "bc6h-rgb-float": { f: texture_compression_bc }, + "bc7-rgba-unorm": { f: texture_compression_bc }, + "bc7-rgba-unorm-srgb": { f: texture_compression_bc }, + // WEBGL_compressed_texture_etc: device.features.has("texture-compression-etc2") + // Note: Supposedly guaranteed availability compressed formats in WebGL2, but through CPU decompression + "etc2-rgb8unorm": { f: texture_compression_etc2 }, + "etc2-rgb8unorm-srgb": { f: texture_compression_etc2 }, + "etc2-rgb8a1unorm": { f: texture_compression_etc2 }, + "etc2-rgb8a1unorm-srgb": { f: texture_compression_etc2 }, + "etc2-rgba8unorm": { f: texture_compression_etc2 }, + "etc2-rgba8unorm-srgb": { f: texture_compression_etc2 }, + "eac-r11unorm": { f: texture_compression_etc2 }, + "eac-r11snorm": { f: texture_compression_etc2 }, + "eac-rg11unorm": { f: texture_compression_etc2 }, + "eac-rg11snorm": { f: texture_compression_etc2 }, + // X_ASTC compressed formats: device.features.has("texture-compression-astc") + "astc-4x4-unorm": { f: texture_compression_astc }, + "astc-4x4-unorm-srgb": { f: texture_compression_astc }, + "astc-5x4-unorm": { f: texture_compression_astc }, + "astc-5x4-unorm-srgb": { f: texture_compression_astc }, + "astc-5x5-unorm": { f: texture_compression_astc }, + "astc-5x5-unorm-srgb": { f: texture_compression_astc }, + "astc-6x5-unorm": { f: texture_compression_astc }, + "astc-6x5-unorm-srgb": { f: texture_compression_astc }, + "astc-6x6-unorm": { f: texture_compression_astc }, + "astc-6x6-unorm-srgb": { f: texture_compression_astc }, + "astc-8x5-unorm": { f: texture_compression_astc }, + "astc-8x5-unorm-srgb": { f: texture_compression_astc }, + "astc-8x6-unorm": { f: texture_compression_astc }, + "astc-8x6-unorm-srgb": { f: texture_compression_astc }, + "astc-8x8-unorm": { f: texture_compression_astc }, + "astc-8x8-unorm-srgb": { f: texture_compression_astc }, + "astc-10x5-unorm": { f: texture_compression_astc }, + "astc-10x5-unorm-srgb": { f: texture_compression_astc }, + "astc-10x6-unorm": { f: texture_compression_astc }, + "astc-10x6-unorm-srgb": { f: texture_compression_astc }, + "astc-10x8-unorm": { f: texture_compression_astc }, + "astc-10x8-unorm-srgb": { f: texture_compression_astc }, + "astc-10x10-unorm": { f: texture_compression_astc }, + "astc-10x10-unorm-srgb": { f: texture_compression_astc }, + "astc-12x10-unorm": { f: texture_compression_astc }, + "astc-12x10-unorm-srgb": { f: texture_compression_astc }, + "astc-12x12-unorm": { f: texture_compression_astc }, + "astc-12x12-unorm-srgb": { f: texture_compression_astc }, + // WEBGL_compressed_texture_pvrtc + "pvrtc-rgb4unorm-webgl": { f: texture_compression_pvrtc_webgl }, + "pvrtc-rgba4unorm-webgl": { f: texture_compression_pvrtc_webgl }, + "pvrtc-rgb2unorm-webgl": { f: texture_compression_pvrtc_webgl }, + "pvrtc-rgba2unorm-webgl": { f: texture_compression_pvrtc_webgl }, + // WEBGL_compressed_texture_etc1 + "etc1-rbg-unorm-webgl": { f: texture_compression_etc1_webgl }, + // WEBGL_compressed_texture_atc + "atc-rgb-unorm-webgl": { f: texture_compression_atc_webgl }, + "atc-rgba-unorm-webgl": { f: texture_compression_atc_webgl }, + "atc-rgbai-unorm-webgl": { f: texture_compression_atc_webgl } + }; + TEXTURE_FORMAT_TABLE = { + ...TEXTURE_FORMAT_COLOR_DEPTH_TABLE, + ...TEXTURE_FORMAT_COMPRESSED_TABLE + }; + } + }); + + // node_modules/@luma.gl/core/dist/shadertypes/texture-types/texture-format-decoder.js + function computeTextureMemoryLayout({ format: format2, width, height, depth, byteAlignment }) { + const formatInfo = textureFormatDecoder.getInfo(format2); + const { bytesPerPixel, bytesPerBlock = bytesPerPixel, blockWidth = 1, blockHeight = 1, compressed = false } = formatInfo; + const blockColumns = compressed ? Math.ceil(width / blockWidth) : width; + const blockRows = compressed ? Math.ceil(height / blockHeight) : height; + const unpaddedBytesPerRow = blockColumns * bytesPerBlock; + const bytesPerRow = Math.ceil(unpaddedBytesPerRow / byteAlignment) * byteAlignment; + const rowsPerImage = blockRows; + const byteLength = bytesPerRow * rowsPerImage * depth; + return { + bytesPerPixel, + bytesPerRow, + rowsPerImage, + depthOrArrayLayers: depth, + bytesPerImage: bytesPerRow * rowsPerImage, + byteLength + }; + } + function getTextureFormatCapabilities(format2) { + const info = getTextureFormatDefinition(format2); + const formatCapabilities = { + format: format2, + create: info.f ?? true, + render: info.render ?? true, + filter: info.filter ?? true, + blend: info.blend ?? true, + store: info.store ?? true + }; + const formatInfo = getTextureFormatInfo(format2); + const isDepthStencil = format2.startsWith("depth") || format2.startsWith("stencil"); + const isSigned = formatInfo?.signed; + const isInteger = formatInfo?.integer; + const isWebGLSpecific = formatInfo?.webgl; + const isCompressed = Boolean(formatInfo?.compressed); + formatCapabilities.render &&= !isDepthStencil && !isCompressed; + formatCapabilities.filter &&= !isDepthStencil && !isSigned && !isInteger && !isWebGLSpecific; + return formatCapabilities; + } + function getTextureFormatInfo(format2) { + let formatInfo = getTextureFormatInfoUsingTable(format2); + if (textureFormatDecoder.isCompressed(format2)) { + formatInfo.channels = "rgb"; + formatInfo.components = 3; + formatInfo.bytesPerPixel = 1; + formatInfo.srgb = false; + formatInfo.compressed = true; + formatInfo.bytesPerBlock = getCompressedTextureBlockByteLength(format2); + const blockSize = getCompressedTextureBlockSize(format2); + if (blockSize) { + formatInfo.blockWidth = blockSize.blockWidth; + formatInfo.blockHeight = blockSize.blockHeight; + } + } + const matches3 = !formatInfo.packed ? RGB_FORMAT_REGEX.exec(format2) : null; + if (matches3) { + const [, channels, length4, type, srgb, suffix] = matches3; + const dataType = `${type}${length4}`; + const decodedType = dataTypeDecoder.getDataTypeInfo(dataType); + const bits = decodedType.byteLength * 8; + const components = channels?.length ?? 1; + const bitsPerChannel = [ + bits, + components >= 2 ? bits : 0, + components >= 3 ? bits : 0, + components >= 4 ? bits : 0 + ]; + formatInfo = { + format: format2, + attachment: formatInfo.attachment, + dataType: decodedType.signedType, + components, + channels, + integer: decodedType.integer, + signed: decodedType.signed, + normalized: decodedType.normalized, + bitsPerChannel, + bytesPerPixel: decodedType.byteLength * components, + packed: formatInfo.packed, + srgb: formatInfo.srgb + }; + if (suffix === "-webgl") { + formatInfo.webgl = true; + } + if (srgb === "-srgb") { + formatInfo.srgb = true; + } + } + if (format2.endsWith("-webgl")) { + formatInfo.webgl = true; + } + if (format2.endsWith("-srgb")) { + formatInfo.srgb = true; + } + return formatInfo; + } + function getTextureFormatInfoUsingTable(format2) { + const info = getTextureFormatDefinition(format2); + const bytesPerPixel = info.bytesPerPixel || 1; + const bitsPerChannel = info.bitsPerChannel || [8, 8, 8, 8]; + delete info.bitsPerChannel; + delete info.bytesPerPixel; + delete info.f; + delete info.render; + delete info.filter; + delete info.blend; + delete info.store; + const formatInfo = { + ...info, + format: format2, + attachment: info.attachment || "color", + channels: info.channels || "r", + components: info.components || info.channels?.length || 1, + bytesPerPixel, + bitsPerChannel, + dataType: info.dataType || "uint8", + srgb: info.srgb ?? false, + packed: info.packed ?? false, + webgl: info.webgl ?? false, + integer: info.integer ?? false, + signed: info.signed ?? false, + normalized: info.normalized ?? false, + compressed: info.compressed ?? false + }; + return formatInfo; + } + function getCompressedTextureBlockSize(format2) { + const REGEX = /.*-(\d+)x(\d+)-.*/; + const matches3 = REGEX.exec(format2); + if (matches3) { + const [, blockWidth, blockHeight] = matches3; + return { blockWidth: Number(blockWidth), blockHeight: Number(blockHeight) }; + } + if (format2.startsWith("bc") || format2.startsWith("etc1") || format2.startsWith("etc2") || format2.startsWith("eac") || format2.startsWith("atc")) { + return { blockWidth: 4, blockHeight: 4 }; + } + if (format2.startsWith("pvrtc-rgb4") || format2.startsWith("pvrtc-rgba4")) { + return { blockWidth: 4, blockHeight: 4 }; + } + if (format2.startsWith("pvrtc-rgb2") || format2.startsWith("pvrtc-rgba2")) { + return { blockWidth: 8, blockHeight: 4 }; + } + return null; + } + function getCompressedTextureBlockByteLength(format2) { + if (format2.startsWith("bc1") || format2.startsWith("bc4") || format2.startsWith("etc1") || format2.startsWith("etc2-rgb8") || format2.startsWith("etc2-rgb8a1") || format2.startsWith("eac-r11") || format2 === "atc-rgb-unorm-webgl") { + return 8; + } + if (format2.startsWith("bc2") || format2.startsWith("bc3") || format2.startsWith("bc5") || format2.startsWith("bc6h") || format2.startsWith("bc7") || format2.startsWith("etc2-rgba8") || format2.startsWith("eac-rg11") || format2.startsWith("astc") || format2 === "atc-rgba-unorm-webgl" || format2 === "atc-rgbai-unorm-webgl") { + return 16; + } + if (format2.startsWith("pvrtc")) { + return 8; + } + return 16; + } + var RGB_FORMAT_REGEX, COLOR_FORMAT_PREFIXES, DEPTH_FORMAT_PREFIXES, COMPRESSED_TEXTURE_FORMAT_PREFIXES, TextureFormatDecoder, textureFormatDecoder; + var init_texture_format_decoder = __esm({ + "node_modules/@luma.gl/core/dist/shadertypes/texture-types/texture-format-decoder.js"() { + init_data_type_decoder(); + init_texture_format_table(); + RGB_FORMAT_REGEX = /^(r|rg|rgb|rgba|bgra)([0-9]*)([a-z]*)(-srgb)?(-webgl)?$/; + COLOR_FORMAT_PREFIXES = ["rgb", "rgba", "bgra"]; + DEPTH_FORMAT_PREFIXES = ["depth", "stencil"]; + COMPRESSED_TEXTURE_FORMAT_PREFIXES = [ + "bc1", + "bc2", + "bc3", + "bc4", + "bc5", + "bc6", + "bc7", + "etc1", + "etc2", + "eac", + "atc", + "astc", + "pvrtc" + ]; + TextureFormatDecoder = class { + /** Checks if a texture format is color */ + isColor(format2) { + return COLOR_FORMAT_PREFIXES.some((prefix) => format2.startsWith(prefix)); + } + /** Checks if a texture format is depth or stencil */ + isDepthStencil(format2) { + return DEPTH_FORMAT_PREFIXES.some((prefix) => format2.startsWith(prefix)); + } + /** Checks if a texture format is compressed */ + isCompressed(format2) { + return COMPRESSED_TEXTURE_FORMAT_PREFIXES.some((prefix) => format2.startsWith(prefix)); + } + /** Returns information about a texture format, e.g. attachment type, components, byte length and flags (integer, signed, normalized) */ + getInfo(format2) { + return getTextureFormatInfo(format2); + } + /** "static" capabilities of a texture format. @note Needs to be adjusted against current device */ + getCapabilities(format2) { + return getTextureFormatCapabilities(format2); + } + /** Computes the memory layout for a texture, in particular including row byte alignment */ + computeMemoryLayout(opts) { + return computeTextureMemoryLayout(opts); + } + }; + textureFormatDecoder = new TextureFormatDecoder(); + } + }); + + // node_modules/@luma.gl/core/dist/shadertypes/image-types/image-types.js + function isExternalImage(data) { + return typeof ImageData !== "undefined" && data instanceof ImageData || typeof ImageBitmap !== "undefined" && data instanceof ImageBitmap || typeof HTMLImageElement !== "undefined" && data instanceof HTMLImageElement || typeof HTMLVideoElement !== "undefined" && data instanceof HTMLVideoElement || typeof VideoFrame !== "undefined" && data instanceof VideoFrame || typeof HTMLCanvasElement !== "undefined" && data instanceof HTMLCanvasElement || typeof OffscreenCanvas !== "undefined" && data instanceof OffscreenCanvas; + } + function getExternalImageSize(data) { + if (typeof ImageData !== "undefined" && data instanceof ImageData || typeof ImageBitmap !== "undefined" && data instanceof ImageBitmap || typeof HTMLCanvasElement !== "undefined" && data instanceof HTMLCanvasElement || typeof OffscreenCanvas !== "undefined" && data instanceof OffscreenCanvas) { + return { width: data.width, height: data.height }; + } + if (typeof HTMLImageElement !== "undefined" && data instanceof HTMLImageElement) { + return { width: data.naturalWidth, height: data.naturalHeight }; + } + if (typeof HTMLVideoElement !== "undefined" && data instanceof HTMLVideoElement) { + return { width: data.videoWidth, height: data.videoHeight }; + } + if (typeof VideoFrame !== "undefined" && data instanceof VideoFrame) { + return { width: data.displayWidth, height: data.displayHeight }; + } + throw new Error("Unknown image type"); + } + var init_image_types = __esm({ + "node_modules/@luma.gl/core/dist/shadertypes/image-types/image-types.js"() { + } + }); + + // node_modules/@luma.gl/core/dist/adapter/device.js + function formatErrorLogArguments(context, args) { + const formattedContext = formatErrorLogValue(context); + const formattedArgs = args.map(formatErrorLogValue).filter((arg) => arg !== void 0); + return [formattedContext, ...formattedArgs].filter((arg) => arg !== void 0); + } + function formatErrorLogValue(value) { + if (value === void 0) { + return void 0; + } + if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") { + return value; + } + if (value instanceof Error) { + return value.message; + } + if (Array.isArray(value)) { + return value.map(formatErrorLogValue); + } + if (typeof value === "object") { + if (hasCustomToString(value)) { + const stringValue = String(value); + if (stringValue !== "[object Object]") { + return stringValue; + } + } + if (looksLikeGPUCompilationMessage(value)) { + return formatGPUCompilationMessage(value); + } + return value.constructor?.name || "Object"; + } + return String(value); + } + function hasCustomToString(value) { + return "toString" in value && typeof value.toString === "function" && value.toString !== Object.prototype.toString; + } + function looksLikeGPUCompilationMessage(value) { + return "message" in value && "type" in value; + } + function formatGPUCompilationMessage(value) { + const type = typeof value.type === "string" ? value.type : "message"; + const message2 = typeof value.message === "string" ? value.message : ""; + const lineNum = typeof value.lineNum === "number" ? value.lineNum : null; + const linePos = typeof value.linePos === "number" ? value.linePos : null; + const location = lineNum !== null && linePos !== null ? ` @ ${lineNum}:${linePos}` : lineNum !== null ? ` @ ${lineNum}` : ""; + return `${type}${location}: ${message2}`.trim(); + } + function _getDefaultDebugValue(logDebugValue, nodeEnv) { + if (logDebugValue !== void 0 && logDebugValue !== null) { + return Boolean(logDebugValue); + } + if (nodeEnv !== void 0) { + return nodeEnv !== "production"; + } + return false; + } + function getDefaultDebugValue() { + return _getDefaultDebugValue(log2.get("debug"), getNodeEnv()); + } + function getNodeEnv() { + const processObject = globalThis.process; + if (!processObject?.env) { + return void 0; + } + return processObject.env["NODE_ENV"]; + } + var DeviceLimits, DeviceFeatures, Device; + var init_device = __esm({ + "node_modules/@luma.gl/core/dist/adapter/device.js"() { + init_stats_manager(); + init_log(); + init_uid(); + init_buffer(); + init_vertex_format_decoder(); + init_texture_format_decoder(); + init_image_types(); + init_texture_format_table(); + DeviceLimits = class { + }; + DeviceFeatures = class { + features; + disabledFeatures; + constructor(features = [], disabledFeatures) { + this.features = new Set(features); + this.disabledFeatures = disabledFeatures || {}; + } + *[Symbol.iterator]() { + yield* this.features; + } + has(feature) { + return !this.disabledFeatures?.[feature] && this.features.has(feature); + } + }; + Device = class _Device { + static defaultProps = { + id: null, + powerPreference: "high-performance", + failIfMajorPerformanceCaveat: false, + createCanvasContext: void 0, + // WebGL specific + webgl: {}, + // Callbacks + // eslint-disable-next-line handle-callback-err + onError: (error, context) => { + }, + onResize: (context, info) => { + const [width, height] = context.getDevicePixelSize(); + log2.log(1, `${context} resized => ${width}x${height}px`)(); + }, + onPositionChange: (context, info) => { + const [left, top] = context.getPosition(); + log2.log(1, `${context} repositioned => ${left},${top}`)(); + }, + onVisibilityChange: (context) => log2.log(1, `${context} Visibility changed ${context.isVisible}`)(), + onDevicePixelRatioChange: (context, info) => log2.log(1, `${context} DPR changed ${info.oldRatio} => ${context.devicePixelRatio}`)(), + // Debug flags + debug: getDefaultDebugValue(), + debugGPUTime: false, + debugShaders: log2.get("debug-shaders") || void 0, + debugFramebuffers: Boolean(log2.get("debug-framebuffers")), + debugFactories: Boolean(log2.get("debug-factories")), + debugWebGL: Boolean(log2.get("debug-webgl")), + debugSpectorJS: void 0, + // Note: log setting is queried by the spector.js code + debugSpectorJSUrl: void 0, + // Experimental + _reuseDevices: false, + _requestMaxLimits: true, + _cacheShaders: true, + _destroyShaders: false, + _cachePipelines: true, + _sharePipelines: true, + _destroyPipelines: false, + // TODO - Change these after confirming things work as expected + _initializeFeatures: true, + _disabledFeatures: { + "compilation-status-async-webgl": true + }, + // INTERNAL + _handle: void 0 + }; + get [Symbol.toStringTag]() { + return "Device"; + } + toString() { + return `Device(${this.id})`; + } + /** id of this device, primarily for debugging */ + id; + /** A copy of the device props */ + props; + /** Available for the application to store data on the device */ + userData = {}; + /** stats */ + statsManager = lumaStats; + /** Internal per-device factory storage */ + _factories = {}; + /** An abstract timestamp used for change tracking */ + timestamp = 0; + /** True if this device has been reused during device creation (app has multiple references) */ + _reused = false; + /** Used by other luma.gl modules to store data on the device */ + _moduleData = {}; + _textureCaps = {}; + /** Internal timestamp query set used when GPU timing collection is enabled for this device. */ + _debugGPUTimeQuery = null; + constructor(props) { + this.props = { ..._Device.defaultProps, ...props }; + this.id = this.props.id || uid(this[Symbol.toStringTag].toLowerCase()); + } + // TODO - just expose the shadertypes decoders? + getVertexFormatInfo(format2) { + return vertexFormatDecoder.getVertexFormatInfo(format2); + } + isVertexFormatSupported(format2) { + return true; + } + /** Returns information about a texture format, such as data type, channels, bits per channel, compression etc */ + getTextureFormatInfo(format2) { + return textureFormatDecoder.getInfo(format2); + } + /** Determines what operations are supported on a texture format on this particular device (checks against supported device features) */ + getTextureFormatCapabilities(format2) { + let textureCaps = this._textureCaps[format2]; + if (!textureCaps) { + const capabilities = this._getDeviceTextureFormatCapabilities(format2); + textureCaps = this._getDeviceSpecificTextureFormatCapabilities(capabilities); + this._textureCaps[format2] = textureCaps; + } + return textureCaps; + } + /** Calculates the number of mip levels for a texture of width, height and in case of 3d textures only, depth */ + getMipLevelCount(width, height, depth3d = 1) { + const maxSize = Math.max(width, height, depth3d); + return 1 + Math.floor(Math.log2(maxSize)); + } + /** Check if data is an external image */ + isExternalImage(data) { + return isExternalImage(data); + } + /** Get the size of an external image */ + getExternalImageSize(data) { + return getExternalImageSize(data); + } + /** Check if device supports a specific texture format (creation and `nearest` sampling) */ + isTextureFormatSupported(format2) { + return this.getTextureFormatCapabilities(format2).create; + } + /** Check if linear filtering (sampler interpolation) is supported for a specific texture format */ + isTextureFormatFilterable(format2) { + return this.getTextureFormatCapabilities(format2).filter; + } + /** Check if device supports rendering to a framebuffer color attachment of a specific texture format */ + isTextureFormatRenderable(format2) { + return this.getTextureFormatCapabilities(format2).render; + } + /** Check if a specific texture format is GPU compressed */ + isTextureFormatCompressed(format2) { + return textureFormatDecoder.isCompressed(format2); + } + /** Returns the compressed texture formats that can be created and sampled on this device */ + getSupportedCompressedTextureFormats() { + const supportedFormats = []; + for (const format2 of Object.keys(getTextureFormatTable())) { + if (this.isTextureFormatCompressed(format2) && this.isTextureFormatSupported(format2)) { + supportedFormats.push(format2); + } + } + return supportedFormats; + } + // DEBUG METHODS + pushDebugGroup(groupLabel) { + this.commandEncoder.pushDebugGroup(groupLabel); + } + popDebugGroup() { + this.commandEncoder?.popDebugGroup(); + } + insertDebugMarker(markerLabel) { + this.commandEncoder?.insertDebugMarker(markerLabel); + } + /** + * Trigger device loss. + * @returns `true` if context loss could actually be triggered. + * @note primarily intended for testing how application reacts to device loss + */ + loseDevice() { + return false; + } + /** A monotonic counter for tracking buffer and texture updates */ + incrementTimestamp() { + return this.timestamp++; + } + /** + * Reports Device errors in a way that optimizes for developer experience / debugging. + * - Logs so that the console error links directly to the source code that generated the error. + * - Includes the object that reported the error in the log message, even if the error is asynchronous. + * + * Conventions when calling reportError(): + * - Always call the returned function - to ensure error is logged, at the error site + * - Follow with a call to device.debug() - to ensure that the debugger breaks at the error site + * + * @param error - the error to report. If needed, just create a new Error object with the appropriate message. + * @param context - pass `this` as context, otherwise it may not be available in the debugger for async errors. + * @returns the logger function returned by device.props.onError() so that it can be called from the error site. + * + * @example + * device.reportError(new Error(...), this)(); + * device.debug(); + */ + reportError(error, context, ...args) { + const isHandled = this.props.onError(error, context); + if (!isHandled) { + const logArguments = formatErrorLogArguments(context, args); + return log2.error(this.type === "webgl" ? "%cWebGL" : "%cWebGPU", "color: white; background: red; padding: 2px 6px; border-radius: 3px;", error.message, ...logArguments); + } + return () => { + }; + } + /** Break in the debugger - if device.props.debug is true */ + debug() { + if (this.props.debug) { + debugger; + } else { + const message2 = `'Type luma.log.set({debug: true}) in console to enable debug breakpoints', +or create a device with the 'debug: true' prop.`; + log2.once(0, message2)(); + } + } + /** Returns the default / primary canvas context. Throws an error if no canvas context is available (a WebGPU compute device) */ + getDefaultCanvasContext() { + if (!this.canvasContext) { + throw new Error("Device has no default CanvasContext. See props.createCanvasContext"); + } + return this.canvasContext; + } + /** Create a fence sync object */ + createFence() { + throw new Error("createFence() not implemented"); + } + /** Create a RenderPass using the default CommandEncoder */ + beginRenderPass(props) { + return this.commandEncoder.beginRenderPass(props); + } + /** Create a ComputePass using the default CommandEncoder*/ + beginComputePass(props) { + return this.commandEncoder.beginComputePass(props); + } + /** + * Generate mipmaps for a WebGPU texture. + * WebGPU textures must be created up front with the required mip count, usage flags, and a format that supports the chosen generation path. + * WebGL uses `Texture.generateMipmapsWebGL()` directly because the backend manages mip generation on the texture object itself. + */ + generateMipmapsWebGPU(_texture) { + throw new Error("not implemented"); + } + /** Internal helper for creating a shareable WebGL render-pipeline implementation. */ + _createSharedRenderPipelineWebGL(_props) { + throw new Error("_createSharedRenderPipelineWebGL() not implemented"); + } + /** Internal WebGPU-only helper for retrieving the native bind-group layout for a pipeline group. */ + _createBindGroupLayoutWebGPU(_pipeline, _group) { + throw new Error("_createBindGroupLayoutWebGPU() not implemented"); + } + /** Internal WebGPU-only helper for creating a native bind group. */ + _createBindGroupWebGPU(_bindGroupLayout, _shaderLayout, _bindings, _group, _label) { + throw new Error("_createBindGroupWebGPU() not implemented"); + } + /** + * Internal helper that returns `true` when timestamp-query GPU timing should be + * collected for this device. + */ + _supportsDebugGPUTime() { + return this.features.has("timestamp-query") && Boolean(this.props.debug || this.props.debugGPUTime); + } + /** + * Internal helper that enables device-managed GPU timing collection on the + * default command encoder. Reuses the existing query set if timing is already enabled. + * + * @param queryCount - Number of timestamp slots reserved for profiled passes. + * @returns The device-managed timestamp QuerySet, or `null` when timing is not supported or could not be enabled. + */ + _enableDebugGPUTime(queryCount = 256) { + if (!this._supportsDebugGPUTime()) { + return null; + } + if (this._debugGPUTimeQuery) { + return this._debugGPUTimeQuery; + } + try { + this._debugGPUTimeQuery = this.createQuerySet({ type: "timestamp", count: queryCount }); + this.commandEncoder = this.createCommandEncoder({ + id: this.commandEncoder.props.id, + timeProfilingQuerySet: this._debugGPUTimeQuery + }); + } catch { + this._debugGPUTimeQuery = null; + } + return this._debugGPUTimeQuery; + } + /** + * Internal helper that disables device-managed GPU timing collection and restores + * the default command encoder to an unprofiled state. + */ + _disableDebugGPUTime() { + if (!this._debugGPUTimeQuery) { + return; + } + if (this.commandEncoder.getTimeProfilingQuerySet() === this._debugGPUTimeQuery) { + this.commandEncoder = this.createCommandEncoder({ + id: this.commandEncoder.props.id + }); + } + this._debugGPUTimeQuery.destroy(); + this._debugGPUTimeQuery = null; + } + /** Internal helper that returns `true` when device-managed GPU timing is currently active. */ + _isDebugGPUTimeEnabled() { + return this._debugGPUTimeQuery !== null; + } + // DEPRECATED METHODS + /** @deprecated Use getDefaultCanvasContext() */ + getCanvasContext() { + return this.getDefaultCanvasContext(); + } + // WebGL specific HACKS - enables app to remove webgl import + // Use until we have a better way to handle these + /** @deprecated - will be removed - should use command encoder */ + readPixelsToArrayWebGL(source3, options) { + throw new Error("not implemented"); + } + /** @deprecated - will be removed - should use command encoder */ + readPixelsToBufferWebGL(source3, options) { + throw new Error("not implemented"); + } + /** @deprecated - will be removed - should use WebGPU parameters (pipeline) */ + setParametersWebGL(parameters) { + throw new Error("not implemented"); + } + /** @deprecated - will be removed - should use WebGPU parameters (pipeline) */ + getParametersWebGL(parameters) { + throw new Error("not implemented"); + } + /** @deprecated - will be removed - should use WebGPU parameters (pipeline) */ + withParametersWebGL(parameters, func) { + throw new Error("not implemented"); + } + /** @deprecated - will be removed - should use clear arguments in RenderPass */ + clearWebGL(options) { + throw new Error("not implemented"); + } + /** @deprecated - will be removed - should use for debugging only */ + resetWebGL() { + throw new Error("not implemented"); + } + // INTERNAL LUMA.GL METHODS + getModuleData(moduleName) { + this._moduleData[moduleName] ||= {}; + return this._moduleData[moduleName]; + } + // INTERNAL HELPERS + // IMPLEMENTATION + /** Helper to get the canvas context props */ + static _getCanvasContextProps(props) { + return props.createCanvasContext === true ? {} : props.createCanvasContext; + } + _getDeviceTextureFormatCapabilities(format2) { + const genericCapabilities = textureFormatDecoder.getCapabilities(format2); + const checkFeature = (feature) => (typeof feature === "string" ? this.features.has(feature) : feature) ?? true; + const supported = checkFeature(genericCapabilities.create); + return { + format: format2, + create: supported, + render: supported && checkFeature(genericCapabilities.render), + filter: supported && checkFeature(genericCapabilities.filter), + blend: supported && checkFeature(genericCapabilities.blend), + store: supported && checkFeature(genericCapabilities.store) + }; + } + /** Subclasses use this to support .createBuffer() overloads */ + _normalizeBufferProps(props) { + if (props instanceof ArrayBuffer || ArrayBuffer.isView(props)) { + props = { data: props }; + } + const newProps = { ...props }; + const usage = props.usage || 0; + if (usage & Buffer2.INDEX) { + if (!props.indexType) { + if (props.data instanceof Uint32Array) { + newProps.indexType = "uint32"; + } else if (props.data instanceof Uint16Array) { + newProps.indexType = "uint16"; + } else if (props.data instanceof Uint8Array) { + newProps.data = new Uint16Array(props.data); + newProps.indexType = "uint16"; + } + } + if (!newProps.indexType) { + throw new Error("indices buffer content must be of type uint16 or uint32"); + } + } + return newProps; + } + }; + } + }); + + // node_modules/@luma.gl/core/dist/adapter/luma.js + var STARTUP_MESSAGE, ERROR_MESSAGE, Luma, luma; + var init_luma = __esm({ + "node_modules/@luma.gl/core/dist/adapter/luma.js"() { + init_device(); + init_stats_manager(); + init_log(); + STARTUP_MESSAGE = "set luma.log.level=1 (or higher) to trace rendering"; + ERROR_MESSAGE = "No matching device found. Ensure `@luma.gl/webgl` and/or `@luma.gl/webgpu` modules are imported."; + Luma = class _Luma { + static defaultProps = { + ...Device.defaultProps, + type: "best-available", + adapters: void 0, + waitForPageLoad: true + }; + /** Global stats for all devices */ + stats = lumaStats; + /** + * Global log + * + * Assign luma.log.level in console to control logging: \ + * 0: none, 1: minimal, 2: verbose, 3: attribute/uniforms, 4: gl logs + * luma.log.break[], set to gl funcs, luma.log.profile[] set to model names`; + */ + log = log2; + /** Version of luma.gl */ + VERSION = ( + // Version detection using build plugin + // @ts-expect-error no-undef + true ? "9.3.3" : "running from source" + ); + spector; + preregisteredAdapters = /* @__PURE__ */ new Map(); + constructor() { + if (globalThis.luma) { + if (globalThis.luma.VERSION !== this.VERSION) { + log2.error(`Found luma.gl ${globalThis.luma.VERSION} while initialzing ${this.VERSION}`)(); + log2.error(`'yarn why @luma.gl/core' can help identify the source of the conflict`)(); + throw new Error(`luma.gl - multiple versions detected: see console log`); + } + log2.error("This version of luma.gl has already been initialized")(); + } + log2.log(1, `${this.VERSION} - ${STARTUP_MESSAGE}`)(); + globalThis.luma = this; + } + /** Creates a device. Asynchronously. */ + async createDevice(props_ = {}) { + const props = { ..._Luma.defaultProps, ...props_ }; + const adapter = this.selectAdapter(props.type, props.adapters); + if (!adapter) { + throw new Error(ERROR_MESSAGE); + } + if (props.waitForPageLoad) { + await adapter.pageLoaded; + } + return await adapter.create(props); + } + /** + * Attach to an existing GPU API handle (WebGL2RenderingContext or GPUDevice). + * @param handle Externally created WebGL context or WebGPU device + */ + async attachDevice(handle, props) { + const type = this._getTypeFromHandle(handle, props.adapters); + const adapter = type && this.selectAdapter(type, props.adapters); + if (!adapter) { + throw new Error(ERROR_MESSAGE); + } + return await adapter?.attach?.(handle, props); + } + /** + * Global adapter registration. + * @deprecated Use props.adapters instead + */ + registerAdapters(adapters) { + for (const deviceClass of adapters) { + this.preregisteredAdapters.set(deviceClass.type, deviceClass); + } + } + /** Get type strings for supported Devices */ + getSupportedAdapters(adapters = []) { + const adapterMap = this._getAdapterMap(adapters); + return Array.from(adapterMap).map(([, adapter]) => adapter).filter((adapter) => adapter.isSupported?.()).map((adapter) => adapter.type); + } + /** Get type strings for best available Device */ + getBestAvailableAdapterType(adapters = []) { + const KNOWN_ADAPTERS = ["webgpu", "webgl", "null"]; + const adapterMap = this._getAdapterMap(adapters); + for (const type of KNOWN_ADAPTERS) { + if (adapterMap.get(type)?.isSupported?.()) { + return type; + } + } + return null; + } + /** Select adapter of type from registered adapters */ + selectAdapter(type, adapters = []) { + let selectedType = type; + if (type === "best-available") { + selectedType = this.getBestAvailableAdapterType(adapters); + } + const adapterMap = this._getAdapterMap(adapters); + return selectedType && adapterMap.get(selectedType) || null; + } + /** + * Override `HTMLCanvasContext.getCanvas()` to always create WebGL2 contexts with additional WebGL1 compatibility. + * Useful when attaching luma to a context from an external library does not support creating WebGL2 contexts. + */ + enforceWebGL2(enforce = true, adapters = []) { + const adapterMap = this._getAdapterMap(adapters); + const webgl2Adapter2 = adapterMap.get("webgl"); + if (!webgl2Adapter2) { + log2.warn("enforceWebGL2: webgl adapter not found")(); + } + webgl2Adapter2?.enforceWebGL2?.(enforce); + } + // DEPRECATED + /** @deprecated */ + setDefaultDeviceProps(props) { + Object.assign(_Luma.defaultProps, props); + } + // HELPERS + /** Convert a list of adapters to a map */ + _getAdapterMap(adapters = []) { + const map4 = new Map(this.preregisteredAdapters); + for (const adapter of adapters) { + map4.set(adapter.type, adapter); + } + return map4; + } + /** Get type of a handle (for attachDevice) */ + _getTypeFromHandle(handle, adapters = []) { + if (handle instanceof WebGL2RenderingContext) { + return "webgl"; + } + if (typeof GPUDevice !== "undefined" && handle instanceof GPUDevice) { + return "webgpu"; + } + if (handle?.queue) { + return "webgpu"; + } + if (handle === null) { + return "null"; + } + if (handle instanceof WebGLRenderingContext) { + log2.warn("WebGL1 is not supported", handle)(); + } else { + log2.warn("Unknown handle type", handle)(); + } + return null; + } + }; + luma = new Luma(); + } + }); + + // node_modules/@luma.gl/core/dist/adapter/adapter.js + function getPageLoadPromise() { + if (!pageLoadPromise) { + if (isPageLoaded() || typeof window === "undefined") { + pageLoadPromise = Promise.resolve(); + } else { + pageLoadPromise = new Promise((resolve2) => window.addEventListener("load", () => resolve2())); + } + } + return pageLoadPromise; + } + var Adapter, isPage, isPageLoaded, pageLoadPromise; + var init_adapter = __esm({ + "node_modules/@luma.gl/core/dist/adapter/adapter.js"() { + init_dist(); + Adapter = class { + /** + * Page load promise + * Resolves when the DOM is loaded. + * @note Since are be limitations on number of `load` event listeners, + * it is recommended avoid calling this accessor until actually needed. + * I.e. we don't call it unless you know that you will be looking up a string in the DOM. + */ + get pageLoaded() { + return getPageLoadPromise(); + } + }; + isPage = isBrowser2() && typeof document !== "undefined"; + isPageLoaded = () => isPage && document.readyState === "complete"; + pageLoadPromise = null; + } + }); + + // node_modules/@luma.gl/core/dist/adapter/canvas-observer.js + var CanvasObserver; + var init_canvas_observer = __esm({ + "node_modules/@luma.gl/core/dist/adapter/canvas-observer.js"() { + CanvasObserver = class { + props; + _resizeObserver; + _intersectionObserver; + _observeDevicePixelRatioTimeout = null; + _observeDevicePixelRatioMediaQuery = null; + _handleDevicePixelRatioChange = () => this._refreshDevicePixelRatio(); + _trackPositionInterval = null; + _started = false; + get started() { + return this._started; + } + constructor(props) { + this.props = props; + } + start() { + if (this._started || !this.props.canvas) { + return; + } + this._started = true; + this._intersectionObserver ||= new IntersectionObserver((entries) => this.props.onIntersection(entries)); + this._resizeObserver ||= new ResizeObserver((entries) => this.props.onResize(entries)); + this._intersectionObserver.observe(this.props.canvas); + try { + this._resizeObserver.observe(this.props.canvas, { box: "device-pixel-content-box" }); + } catch { + this._resizeObserver.observe(this.props.canvas, { box: "content-box" }); + } + this._observeDevicePixelRatioTimeout = setTimeout(() => this._refreshDevicePixelRatio(), 0); + if (this.props.trackPosition) { + this._trackPosition(); + } + } + stop() { + if (!this._started) { + return; + } + this._started = false; + if (this._observeDevicePixelRatioTimeout) { + clearTimeout(this._observeDevicePixelRatioTimeout); + this._observeDevicePixelRatioTimeout = null; + } + if (this._observeDevicePixelRatioMediaQuery) { + this._observeDevicePixelRatioMediaQuery.removeEventListener("change", this._handleDevicePixelRatioChange); + this._observeDevicePixelRatioMediaQuery = null; + } + if (this._trackPositionInterval) { + clearInterval(this._trackPositionInterval); + this._trackPositionInterval = null; + } + this._resizeObserver?.disconnect(); + this._intersectionObserver?.disconnect(); + } + _refreshDevicePixelRatio() { + if (!this._started) { + return; + } + this.props.onDevicePixelRatioChange(); + this._observeDevicePixelRatioMediaQuery?.removeEventListener("change", this._handleDevicePixelRatioChange); + this._observeDevicePixelRatioMediaQuery = matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`); + this._observeDevicePixelRatioMediaQuery.addEventListener("change", this._handleDevicePixelRatioChange, { once: true }); + } + _trackPosition(intervalMs = 100) { + if (this._trackPositionInterval) { + return; + } + this._trackPositionInterval = setInterval(() => { + if (!this._started) { + if (this._trackPositionInterval) { + clearInterval(this._trackPositionInterval); + this._trackPositionInterval = null; + } + } else { + this.props.onPositionChange(); + } + }, intervalMs); + } + }; + } + }); + + // node_modules/@luma.gl/core/dist/utils/promise-utils.js + function withResolvers() { + let resolve2; + let reject; + const promise = new Promise((_resolve, _reject) => { + resolve2 = _resolve; + reject = _reject; + }); + return { promise, resolve: resolve2, reject }; + } + var init_promise_utils = __esm({ + "node_modules/@luma.gl/core/dist/utils/promise-utils.js"() { + } + }); + + // node_modules/@luma.gl/core/dist/utils/assert.js + function assert6(condition, message2) { + if (!condition) { + const error = new Error(message2 ?? "luma.gl assertion failed."); + Error.captureStackTrace?.(error, assert6); + throw error; + } + } + function assertDefined(value, message2) { + assert6(value, message2); + return value; + } + var init_assert2 = __esm({ + "node_modules/@luma.gl/core/dist/utils/assert.js"() { + } + }); + + // node_modules/@luma.gl/core/dist/adapter/canvas-surface.js + function getContainer(container) { + if (typeof container === "string") { + const element = document.getElementById(container); + if (!element) { + throw new Error(`${container} is not an HTML element`); + } + return element; + } + if (container) { + return container; + } + return document.body; + } + function getCanvasFromDOM(canvasId) { + const canvas = document.getElementById(canvasId); + if (!CanvasSurface.isHTMLCanvas(canvas)) { + throw new Error("Object is not a canvas element"); + } + return canvas; + } + function createCanvasElement(props) { + const { width, height } = props; + const newCanvas = document.createElement("canvas"); + newCanvas.id = uid("lumagl-auto-created-canvas"); + newCanvas.width = width || 1; + newCanvas.height = height || 1; + newCanvas.style.width = Number.isFinite(width) ? `${width}px` : "100%"; + newCanvas.style.height = Number.isFinite(height) ? `${height}px` : "100%"; + if (!props?.visible) { + newCanvas.style.visibility = "hidden"; + } + const container = getContainer(props?.container || null); + container.insertBefore(newCanvas, container.firstChild); + return newCanvas; + } + function scalePixels(pixel, ratio, width, height, yInvert) { + const point = pixel; + const x = scaleX(point[0], ratio, width); + let y = scaleY(point[1], ratio, height, yInvert); + let temporary = scaleX(point[0] + 1, ratio, width); + const xHigh = temporary === width - 1 ? temporary : temporary - 1; + temporary = scaleY(point[1] + 1, ratio, height, yInvert); + let yHigh; + if (yInvert) { + temporary = temporary === 0 ? temporary : temporary + 1; + yHigh = y; + y = temporary; + } else { + yHigh = temporary === height - 1 ? temporary : temporary - 1; + } + return { + x, + y, + width: Math.max(xHigh - x + 1, 1), + height: Math.max(yHigh - y + 1, 1) + }; + } + function scaleX(x, ratio, width) { + return Math.min(Math.round(x * ratio), width - 1); + } + function scaleY(y, ratio, height, yInvert) { + return yInvert ? Math.max(0, height - 1 - Math.round(y * ratio)) : Math.min(Math.round(y * ratio), height - 1); + } + var CanvasSurface; + var init_canvas_surface = __esm({ + "node_modules/@luma.gl/core/dist/adapter/canvas-surface.js"() { + init_dist(); + init_canvas_observer(); + init_uid(); + init_promise_utils(); + init_assert2(); + CanvasSurface = class _CanvasSurface { + static isHTMLCanvas(canvas) { + return typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement; + } + static isOffscreenCanvas(canvas) { + return typeof OffscreenCanvas !== "undefined" && canvas instanceof OffscreenCanvas; + } + static defaultProps = { + id: void 0, + canvas: null, + width: 800, + height: 600, + useDevicePixels: true, + autoResize: true, + container: null, + visible: true, + alphaMode: "opaque", + colorSpace: "srgb", + trackPosition: false + }; + id; + props; + canvas; + /** Handle to HTML canvas */ + htmlCanvas; + /** Handle to wrapped OffScreenCanvas */ + offscreenCanvas; + type; + /** Promise that resolved once the resize observer has updated the pixel size */ + initialized; + isInitialized = false; + /** Visibility is automatically updated (via an IntersectionObserver) */ + isVisible = true; + /** Width of canvas in CSS units (tracked by a ResizeObserver) */ + cssWidth; + /** Height of canvas in CSS units (tracked by a ResizeObserver) */ + cssHeight; + /** Device pixel ratio. Automatically updated via media queries */ + devicePixelRatio; + /** Exact width of canvas in physical pixels (tracked by a ResizeObserver) */ + devicePixelWidth; + /** Exact height of canvas in physical pixels (tracked by a ResizeObserver) */ + devicePixelHeight; + /** Width of drawing buffer: automatically tracks this.pixelWidth if props.autoResize is true */ + drawingBufferWidth; + /** Height of drawing buffer: automatically tracks this.pixelHeight if props.autoResize is true */ + drawingBufferHeight; + /** Resolves when the canvas is initialized, i.e. when the ResizeObserver has updated the pixel size */ + _initializedResolvers = withResolvers(); + _canvasObserver; + /** Position of the canvas in the document, updated by a timer */ + _position = [0, 0]; + /** Whether this canvas context has been destroyed */ + destroyed = false; + /** Whether the drawing buffer size needs to be resized (deferred resizing to avoid flicker) */ + _needsDrawingBufferResize = true; + toString() { + return `${this[Symbol.toStringTag]}(${this.id})`; + } + constructor(props) { + this.props = { ..._CanvasSurface.defaultProps, ...props }; + props = this.props; + this.initialized = this._initializedResolvers.promise; + if (!isBrowser2()) { + this.canvas = { width: props.width || 1, height: props.height || 1 }; + } else if (!props.canvas) { + this.canvas = createCanvasElement(props); + } else if (typeof props.canvas === "string") { + this.canvas = getCanvasFromDOM(props.canvas); + } else { + this.canvas = props.canvas; + } + if (_CanvasSurface.isHTMLCanvas(this.canvas)) { + this.id = props.id || this.canvas.id; + this.type = "html-canvas"; + this.htmlCanvas = this.canvas; + } else if (_CanvasSurface.isOffscreenCanvas(this.canvas)) { + this.id = props.id || "offscreen-canvas"; + this.type = "offscreen-canvas"; + this.offscreenCanvas = this.canvas; + } else { + this.id = props.id || "node-canvas-context"; + this.type = "node"; + } + this.cssWidth = this.htmlCanvas?.clientWidth || this.canvas.width; + this.cssHeight = this.htmlCanvas?.clientHeight || this.canvas.height; + this.devicePixelWidth = this.canvas.width; + this.devicePixelHeight = this.canvas.height; + this.drawingBufferWidth = this.canvas.width; + this.drawingBufferHeight = this.canvas.height; + this.devicePixelRatio = globalThis.devicePixelRatio || 1; + this._position = [0, 0]; + this._canvasObserver = new CanvasObserver({ + canvas: this.htmlCanvas, + trackPosition: this.props.trackPosition, + onResize: (entries) => this._handleResize(entries), + onIntersection: (entries) => this._handleIntersection(entries), + onDevicePixelRatioChange: () => this._observeDevicePixelRatio(), + onPositionChange: () => this.updatePosition() + }); + } + destroy() { + if (!this.destroyed) { + this.destroyed = true; + this._stopObservers(); + this.device = null; + } + } + setProps(props) { + if ("useDevicePixels" in props) { + this.props.useDevicePixels = props.useDevicePixels || false; + this._updateDrawingBufferSize(); + } + return this; + } + /** Returns a framebuffer with properly resized current 'swap chain' textures */ + getCurrentFramebuffer(options) { + this._resizeDrawingBufferIfNeeded(); + return this._getCurrentFramebuffer(options); + } + getCSSSize() { + return [this.cssWidth, this.cssHeight]; + } + getPosition() { + return this._position; + } + getDevicePixelSize() { + return [this.devicePixelWidth, this.devicePixelHeight]; + } + getDrawingBufferSize() { + return [this.drawingBufferWidth, this.drawingBufferHeight]; + } + getMaxDrawingBufferSize() { + const maxTextureDimension = this.device.limits.maxTextureDimension2D; + return [maxTextureDimension, maxTextureDimension]; + } + setDrawingBufferSize(width, height) { + width = Math.floor(width); + height = Math.floor(height); + if (this.drawingBufferWidth === width && this.drawingBufferHeight === height) { + return; + } + this.drawingBufferWidth = width; + this.drawingBufferHeight = height; + this._needsDrawingBufferResize = true; + } + getDevicePixelRatio() { + const devicePixelRatio2 = typeof window !== "undefined" && window.devicePixelRatio; + return devicePixelRatio2 || 1; + } + cssToDevicePixels(cssPixel, yInvert = true) { + const ratio = this.cssToDeviceRatio(); + const [width, height] = this.getDrawingBufferSize(); + return scalePixels(cssPixel, ratio, width, height, yInvert); + } + /** @deprecated - use .getDevicePixelSize() */ + getPixelSize() { + return this.getDevicePixelSize(); + } + /** @deprecated Use the current drawing buffer size for projection setup. */ + getAspect() { + const [width, height] = this.getDrawingBufferSize(); + return width > 0 && height > 0 ? width / height : 1; + } + /** @deprecated Returns multiplier need to convert CSS size to Device size */ + cssToDeviceRatio() { + try { + const [drawingBufferWidth] = this.getDrawingBufferSize(); + const [cssWidth] = this.getCSSSize(); + return cssWidth ? drawingBufferWidth / cssWidth : 1; + } catch { + return 1; + } + } + /** @deprecated Use canvasContext.setDrawingBufferSize() */ + resize(size) { + this.setDrawingBufferSize(size.width, size.height); + } + _setAutoCreatedCanvasId(id) { + if (this.htmlCanvas?.id === "lumagl-auto-created-canvas") { + this.htmlCanvas.id = id; + } + } + /** + * Starts DOM observation after the derived context and its device are fully initialized. + * + * `CanvasSurface` construction runs before subclasses can assign `this.device`, and the + * default WebGL canvas context is created before `WebGLDevice` has initialized `limits`, + * `features`, and the rest of its runtime state. Deferring observer startup avoids early + * `ResizeObserver` and DPR callbacks running against a partially initialized device. + */ + _startObservers() { + if (this.destroyed) { + return; + } + this._canvasObserver.start(); + } + /** + * Stops all DOM observation and timers associated with a canvas surface. + * + * This pairs with `_startObservers()` so teardown uses the same lifecycle whether a context is + * explicitly destroyed, abandoned during device reuse, or temporarily has not started observing + * yet. Centralizing shutdown here keeps resize/DPR/position watchers from surviving past the + * lifetime of the owning device. + */ + _stopObservers() { + this._canvasObserver.stop(); + } + _handleIntersection(entries) { + if (this.destroyed) { + return; + } + const entry = entries.find((entry_) => entry_.target === this.canvas); + if (!entry) { + return; + } + const isVisible = entry.isIntersecting; + if (this.isVisible !== isVisible) { + this.isVisible = isVisible; + this.device.props.onVisibilityChange(this); + } + } + _handleResize(entries) { + if (this.destroyed) { + return; + } + const entry = entries.find((entry_) => entry_.target === this.canvas); + if (!entry) { + return; + } + const contentBoxSize = assertDefined(entry.contentBoxSize?.[0]); + this.cssWidth = contentBoxSize.inlineSize; + this.cssHeight = contentBoxSize.blockSize; + const oldPixelSize = this.getDevicePixelSize(); + const devicePixelWidth = entry.devicePixelContentBoxSize?.[0]?.inlineSize || contentBoxSize.inlineSize * devicePixelRatio; + const devicePixelHeight = entry.devicePixelContentBoxSize?.[0]?.blockSize || contentBoxSize.blockSize * devicePixelRatio; + const [maxDevicePixelWidth, maxDevicePixelHeight] = this.getMaxDrawingBufferSize(); + this.devicePixelWidth = Math.max(1, Math.min(devicePixelWidth, maxDevicePixelWidth)); + this.devicePixelHeight = Math.max(1, Math.min(devicePixelHeight, maxDevicePixelHeight)); + this._updateDrawingBufferSize(); + this.device.props.onResize(this, { oldPixelSize }); + } + _updateDrawingBufferSize() { + if (this.props.autoResize) { + if (typeof this.props.useDevicePixels === "number") { + const devicePixelRatio2 = this.props.useDevicePixels; + this.setDrawingBufferSize(this.cssWidth * devicePixelRatio2, this.cssHeight * devicePixelRatio2); + } else if (this.props.useDevicePixels) { + this.setDrawingBufferSize(this.devicePixelWidth, this.devicePixelHeight); + } else { + this.setDrawingBufferSize(this.cssWidth, this.cssHeight); + } + } + this._initializedResolvers.resolve(); + this.isInitialized = true; + this.updatePosition(); + } + _resizeDrawingBufferIfNeeded() { + if (this._needsDrawingBufferResize) { + this._needsDrawingBufferResize = false; + const sizeChanged = this.drawingBufferWidth !== this.canvas.width || this.drawingBufferHeight !== this.canvas.height; + if (sizeChanged) { + this.canvas.width = this.drawingBufferWidth; + this.canvas.height = this.drawingBufferHeight; + this._configureDevice(); + } + } + } + _observeDevicePixelRatio() { + if (this.destroyed || !this._canvasObserver.started) { + return; + } + const oldRatio = this.devicePixelRatio; + this.devicePixelRatio = window.devicePixelRatio; + this.updatePosition(); + this.device.props.onDevicePixelRatioChange?.(this, { + oldRatio + }); + } + updatePosition() { + if (this.destroyed) { + return; + } + const newRect = this.htmlCanvas?.getBoundingClientRect(); + if (newRect) { + const position = [newRect.left, newRect.top]; + this._position ??= position; + const positionChanged = position[0] !== this._position[0] || position[1] !== this._position[1]; + if (positionChanged) { + const oldPosition = this._position; + this._position = position; + this.device.props.onPositionChange?.(this, { + oldPosition + }); + } + } + } + }; + } + }); + + // node_modules/@luma.gl/core/dist/adapter/canvas-context.js + var CanvasContext; + var init_canvas_context = __esm({ + "node_modules/@luma.gl/core/dist/adapter/canvas-context.js"() { + init_canvas_surface(); + CanvasContext = class extends CanvasSurface { + static defaultProps = CanvasSurface.defaultProps; + }; + } + }); + + // node_modules/@luma.gl/core/dist/adapter/presentation-context.js + var PresentationContext; + var init_presentation_context = __esm({ + "node_modules/@luma.gl/core/dist/adapter/presentation-context.js"() { + init_canvas_surface(); + PresentationContext = class extends CanvasSurface { + }; + } + }); + + // node_modules/@luma.gl/core/dist/adapter/resources/sampler.js + var Sampler; + var init_sampler = __esm({ + "node_modules/@luma.gl/core/dist/adapter/resources/sampler.js"() { + init_resource(); + Sampler = class _Sampler extends Resource { + static defaultProps = { + ...Resource.defaultProps, + type: "color-sampler", + addressModeU: "clamp-to-edge", + addressModeV: "clamp-to-edge", + addressModeW: "clamp-to-edge", + magFilter: "nearest", + minFilter: "nearest", + mipmapFilter: "none", + lodMinClamp: 0, + lodMaxClamp: 32, + // Per WebGPU spec + compare: "less-equal", + maxAnisotropy: 1 + }; + get [Symbol.toStringTag]() { + return "Sampler"; + } + constructor(device, props) { + props = _Sampler.normalizeProps(device, props); + super(device, props, _Sampler.defaultProps); + } + static normalizeProps(device, props) { + return props; + } + }; + } + }); + + // node_modules/@luma.gl/core/dist/adapter/resources/texture.js + var BASE_DIMENSIONS, Texture; + var init_texture = __esm({ + "node_modules/@luma.gl/core/dist/adapter/resources/texture.js"() { + init_resource(); + init_sampler(); + init_log(); + init_texture_format_decoder(); + BASE_DIMENSIONS = { + "1d": "1d", + "2d": "2d", + "2d-array": "2d", + cube: "2d", + "cube-array": "2d", + "3d": "3d" + }; + Texture = class _Texture extends Resource { + /** The texture can be bound for use as a sampled texture in a shader */ + static SAMPLE = 4; + /** The texture can be bound for use as a storage texture in a shader */ + static STORAGE = 8; + /** The texture can be used as a color or depth/stencil attachment in a render pass */ + static RENDER = 16; + /** The texture can be used as the source of a copy operation */ + static COPY_SRC = 1; + /** he texture can be used as the destination of a copy or write operation */ + static COPY_DST = 2; + /** @deprecated Use Texture.SAMPLE */ + static TEXTURE = 4; + /** @deprecated Use Texture.RENDER */ + static RENDER_ATTACHMENT = 16; + /** dimension of this texture */ + dimension; + /** base dimension of this texture */ + baseDimension; + /** format of this texture */ + format; + /** width in pixels of this texture */ + width; + /** height in pixels of this texture */ + height; + /** depth of this texture */ + depth; + /** mip levels in this texture */ + mipLevels; + /** sample count */ + samples; + /** Rows are multiples of this length, padded with extra bytes if needed */ + byteAlignment; + /** The ready promise is always resolved. It is provided for type compatibility with DynamicTexture. */ + ready = Promise.resolve(this); + /** isReady is always true. It is provided for type compatibility with DynamicTexture. */ + isReady = true; + /** "Time" of last update. Monotonically increasing timestamp. TODO move to DynamicTexture? */ + updateTimestamp; + get [Symbol.toStringTag]() { + return "Texture"; + } + toString() { + return `Texture(${this.id},${this.format},${this.width}x${this.height})`; + } + /** Do not use directly. Create with device.createTexture() */ + constructor(device, props, backendProps) { + props = _Texture.normalizeProps(device, props); + super(device, props, _Texture.defaultProps); + this.dimension = this.props.dimension; + this.baseDimension = BASE_DIMENSIONS[this.dimension]; + this.format = this.props.format; + this.width = this.props.width; + this.height = this.props.height; + this.depth = this.props.depth; + this.mipLevels = this.props.mipLevels; + this.samples = this.props.samples || 1; + if (this.dimension === "cube") { + this.depth = 6; + } + if (this.props.width === void 0 || this.props.height === void 0) { + if (device.isExternalImage(props.data)) { + const size = device.getExternalImageSize(props.data); + this.width = size?.width || 1; + this.height = size?.height || 1; + } else { + this.width = 1; + this.height = 1; + if (this.props.width === void 0 || this.props.height === void 0) { + log2.warn(`${this} created with undefined width or height. This is deprecated. Use DynamicTexture instead.`)(); + } + } + } + this.byteAlignment = backendProps?.byteAlignment || 1; + this.updateTimestamp = device.incrementTimestamp(); + } + /** + * Create a new texture with the same parameters and optionally a different size + * @note Textures are immutable and cannot be resized after creation, but we can create a similar texture with the same parameters but a new size. + * @note Does not copy contents of the texture + */ + clone(size) { + return this.device.createTexture({ ...this.props, ...size }); + } + /** Set sampler props associated with this texture */ + setSampler(sampler) { + this.sampler = sampler instanceof Sampler ? sampler : this.device.createSampler(sampler); + } + /** + * Copy raw image data (bytes) into the texture. + * + * @note Deprecated compatibility wrapper over {@link writeData}. + * @note Uses the same layout defaults and alignment rules as {@link writeData}. + * @note Tightly packed CPU uploads can omit `bytesPerRow` and `rowsPerImage`. + * @note If the CPU source rows are padded, pass explicit `bytesPerRow` and `rowsPerImage`. + * @deprecated Use writeData() + */ + copyImageData(options) { + const { data, depth, ...writeOptions } = options; + this.writeData(data, { + ...writeOptions, + depthOrArrayLayers: writeOptions.depthOrArrayLayers ?? depth + }); + } + /** + * Calculates the memory layout of the texture, required when reading and writing data. + * @return the backend-aligned linear layout, in particular bytesPerRow which includes any required padding for buffer copy/read paths + */ + computeMemoryLayout(options_ = {}) { + const options = this._normalizeTextureReadOptions(options_); + const { width = this.width, height = this.height, depthOrArrayLayers = this.depth } = options; + const { format: format2, byteAlignment } = this; + return textureFormatDecoder.computeMemoryLayout({ + format: format2, + width, + height, + depth: depthOrArrayLayers, + byteAlignment + }); + } + /** + * Read the contents of a texture into a GPU Buffer. + * @returns A Buffer containing the texture data. + * + * @note The memory layout of the texture data is determined by the texture format and dimensions. + * @note The application can call Texture.computeMemoryLayout() to compute the backend-aligned layout. + * @note The application can call Buffer.readAsync() to read the returned buffer on the CPU. + * @note The destination buffer must be supplied by the caller and must be large enough for the requested region. + * @note On WebGPU this corresponds to a texture-to-buffer copy and uses buffer-copy alignment rules. + * @note On WebGL, luma.gl emulates the same logical readback behavior. + */ + readBuffer(options, buffer) { + throw new Error("readBuffer not implemented"); + } + /** + * Reads data from a texture into an ArrayBuffer. + * @returns An ArrayBuffer containing the texture data. + * + * @note The memory layout of the texture data is determined by the texture format and dimensions. + * @note The application can call Texture.computeMemoryLayout() to compute the layout. + * @deprecated Use Texture.readBuffer() with an explicit destination buffer, or DynamicTexture.readAsync() for convenience readback. + */ + readDataAsync(options) { + throw new Error("readBuffer not implemented"); + } + /** + * Writes a GPU Buffer into a texture. + * + * @param buffer - Source GPU buffer. + * @param options - Destination subresource, extent, and source layout options. + * @note The memory layout of the texture data is determined by the texture format and dimensions. + * @note The application can call Texture.computeMemoryLayout() to compute the backend-aligned layout. + * @note On WebGPU this corresponds to a buffer-to-texture copy and uses buffer-copy alignment rules. + * @note On WebGL, luma.gl emulates the same destination and layout semantics. + */ + writeBuffer(buffer, options) { + throw new Error("readBuffer not implemented"); + } + /** + * Writes an array buffer into a texture. + * + * @param data - Source texel data. + * @param options - Destination subresource, extent, and source layout options. + * @note If `bytesPerRow` and `rowsPerImage` are omitted, luma.gl computes a tightly packed CPU-memory layout for the requested region. + * @note On WebGPU this corresponds to `GPUQueue.writeTexture()` and does not implicitly pad rows to 256 bytes. + * @note On WebGL, padded CPU data is supported via the same `bytesPerRow` and `rowsPerImage` options. + */ + writeData(data, options) { + throw new Error("readBuffer not implemented"); + } + // IMPLEMENTATION SPECIFIC + /** + * WebGL can read data synchronously. + * @note While it is convenient, the performance penalty is very significant + */ + readDataSyncWebGL(options) { + throw new Error("readDataSyncWebGL not available"); + } + /** Generate mipmaps (WebGL only) */ + generateMipmapsWebGL() { + throw new Error("generateMipmapsWebGL not available"); + } + // HELPERS + /** Ensure we have integer coordinates */ + static normalizeProps(device, props) { + const newProps = { ...props }; + const { width, height } = newProps; + if (typeof width === "number") { + newProps.width = Math.max(1, Math.ceil(width)); + } + if (typeof height === "number") { + newProps.height = Math.max(1, Math.ceil(height)); + } + return newProps; + } + /** Initialize texture with supplied props */ + // eslint-disable-next-line max-statements + _initializeData(data) { + if (this.device.isExternalImage(data)) { + this.copyExternalImage({ + image: data, + width: this.width, + height: this.height, + depth: this.depth, + mipLevel: 0, + x: 0, + y: 0, + z: 0, + aspect: "all", + colorSpace: "srgb", + premultipliedAlpha: false, + flipY: false + }); + } else if (data) { + this.copyImageData({ + data, + // width: this.width, + // height: this.height, + // depth: this.depth, + mipLevel: 0, + x: 0, + y: 0, + z: 0, + aspect: "all" + }); + } + } + _normalizeCopyImageDataOptions(options_) { + const { data, depth, ...writeOptions } = options_; + const options = this._normalizeTextureWriteOptions({ + ...writeOptions, + depthOrArrayLayers: writeOptions.depthOrArrayLayers ?? depth + }); + return { data, depth: options.depthOrArrayLayers, ...options }; + } + _normalizeCopyExternalImageOptions(options_) { + const optionsWithoutUndefined = _Texture._omitUndefined(options_); + const mipLevel = optionsWithoutUndefined.mipLevel ?? 0; + const mipLevelSize = this._getMipLevelSize(mipLevel); + const size = this.device.getExternalImageSize(options_.image); + const options = { + ..._Texture.defaultCopyExternalImageOptions, + ...mipLevelSize, + ...size, + ...optionsWithoutUndefined + }; + options.width = Math.min(options.width, mipLevelSize.width - options.x); + options.height = Math.min(options.height, mipLevelSize.height - options.y); + options.depth = Math.min(options.depth, mipLevelSize.depthOrArrayLayers - options.z); + return options; + } + _normalizeTextureReadOptions(options_) { + const optionsWithoutUndefined = _Texture._omitUndefined(options_); + const mipLevel = optionsWithoutUndefined.mipLevel ?? 0; + const mipLevelSize = this._getMipLevelSize(mipLevel); + const options = { + ..._Texture.defaultTextureReadOptions, + ...mipLevelSize, + ...optionsWithoutUndefined + }; + options.width = Math.min(options.width, mipLevelSize.width - options.x); + options.height = Math.min(options.height, mipLevelSize.height - options.y); + options.depthOrArrayLayers = Math.min(options.depthOrArrayLayers, mipLevelSize.depthOrArrayLayers - options.z); + return options; + } + /** + * Normalizes a texture read request and validates the color-only readback contract used by the + * current texture read APIs. Supported dimensions are `2d`, `cube`, `cube-array`, + * `2d-array`, and `3d`. + * + * @throws if the texture format, aspect, or dimension is not supported by the first-pass + * color-read implementation. + */ + _getSupportedColorReadOptions(options_) { + const options = this._normalizeTextureReadOptions(options_); + const formatInfo = textureFormatDecoder.getInfo(this.format); + this._validateColorReadAspect(options); + this._validateColorReadFormat(formatInfo); + switch (this.dimension) { + case "2d": + case "cube": + case "cube-array": + case "2d-array": + case "3d": + return options; + default: + throw new Error(`${this} color readback does not support ${this.dimension} textures`); + } + } + /** Validates that a read request targets the full color aspect of the texture. */ + _validateColorReadAspect(options) { + if (options.aspect !== "all") { + throw new Error(`${this} color readback only supports aspect 'all'`); + } + } + /** Validates that a read request targets an uncompressed color-renderable texture format. */ + _validateColorReadFormat(formatInfo) { + if (formatInfo.compressed) { + throw new Error(`${this} color readback does not support compressed formats (${this.format})`); + } + switch (formatInfo.attachment) { + case "color": + return; + case "depth": + throw new Error(`${this} color readback does not support depth formats (${this.format})`); + case "stencil": + throw new Error(`${this} color readback does not support stencil formats (${this.format})`); + case "depth-stencil": + throw new Error(`${this} color readback does not support depth-stencil formats (${this.format})`); + default: + throw new Error(`${this} color readback does not support format ${this.format}`); + } + } + _normalizeTextureWriteOptions(options_) { + const optionsWithoutUndefined = _Texture._omitUndefined(options_); + const mipLevel = optionsWithoutUndefined.mipLevel ?? 0; + const mipLevelSize = this._getMipLevelSize(mipLevel); + const options = { + ..._Texture.defaultTextureWriteOptions, + ...mipLevelSize, + ...optionsWithoutUndefined + }; + options.width = Math.min(options.width, mipLevelSize.width - options.x); + options.height = Math.min(options.height, mipLevelSize.height - options.y); + options.depthOrArrayLayers = Math.min(options.depthOrArrayLayers, mipLevelSize.depthOrArrayLayers - options.z); + const layout = textureFormatDecoder.computeMemoryLayout({ + format: this.format, + width: options.width, + height: options.height, + depth: options.depthOrArrayLayers, + byteAlignment: this.byteAlignment + }); + const minimumBytesPerRow = layout.bytesPerPixel * options.width; + options.bytesPerRow = optionsWithoutUndefined.bytesPerRow ?? layout.bytesPerRow; + options.rowsPerImage = optionsWithoutUndefined.rowsPerImage ?? options.height; + if (options.bytesPerRow < minimumBytesPerRow) { + throw new Error(`bytesPerRow (${options.bytesPerRow}) must be at least ${minimumBytesPerRow} for ${this.format}`); + } + if (options.rowsPerImage < options.height) { + throw new Error(`rowsPerImage (${options.rowsPerImage}) must be at least ${options.height} for ${this.format}`); + } + const bytesPerPixel = this.device.getTextureFormatInfo(this.format).bytesPerPixel; + if (bytesPerPixel && options.bytesPerRow % bytesPerPixel !== 0) { + throw new Error(`bytesPerRow (${options.bytesPerRow}) must be a multiple of bytesPerPixel (${bytesPerPixel}) for ${this.format}`); + } + return options; + } + _getMipLevelSize(mipLevel) { + const width = Math.max(1, this.width >> mipLevel); + const height = this.baseDimension === "1d" ? 1 : Math.max(1, this.height >> mipLevel); + const depthOrArrayLayers = this.dimension === "3d" ? Math.max(1, this.depth >> mipLevel) : this.depth; + return { width, height, depthOrArrayLayers }; + } + getAllocatedByteLength() { + let allocatedByteLength = 0; + for (let mipLevel = 0; mipLevel < this.mipLevels; mipLevel++) { + const { width, height, depthOrArrayLayers } = this._getMipLevelSize(mipLevel); + allocatedByteLength += textureFormatDecoder.computeMemoryLayout({ + format: this.format, + width, + height, + depth: depthOrArrayLayers, + byteAlignment: 1 + }).byteLength; + } + return allocatedByteLength * this.samples; + } + static _omitUndefined(options) { + return Object.fromEntries(Object.entries(options).filter(([, value]) => value !== void 0)); + } + static defaultProps = { + ...Resource.defaultProps, + data: null, + dimension: "2d", + format: "rgba8unorm", + usage: _Texture.SAMPLE | _Texture.RENDER | _Texture.COPY_DST, + width: void 0, + height: void 0, + depth: 1, + mipLevels: 1, + samples: void 0, + sampler: {}, + view: void 0 + }; + static defaultCopyDataOptions = { + data: void 0, + byteOffset: 0, + bytesPerRow: void 0, + rowsPerImage: void 0, + width: void 0, + height: void 0, + depthOrArrayLayers: void 0, + depth: 1, + mipLevel: 0, + x: 0, + y: 0, + z: 0, + aspect: "all" + }; + /** Default options */ + static defaultCopyExternalImageOptions = { + image: void 0, + sourceX: 0, + sourceY: 0, + width: void 0, + height: void 0, + depth: 1, + mipLevel: 0, + x: 0, + y: 0, + z: 0, + aspect: "all", + colorSpace: "srgb", + premultipliedAlpha: false, + flipY: false + }; + static defaultTextureReadOptions = { + x: 0, + y: 0, + z: 0, + width: void 0, + height: void 0, + depthOrArrayLayers: 1, + mipLevel: 0, + aspect: "all" + }; + static defaultTextureWriteOptions = { + byteOffset: 0, + bytesPerRow: void 0, + rowsPerImage: void 0, + x: 0, + y: 0, + z: 0, + width: void 0, + height: void 0, + depthOrArrayLayers: 1, + mipLevel: 0, + aspect: "all" + }; + }; + } + }); + + // node_modules/@luma.gl/core/dist/adapter/resources/texture-view.js + var TextureView; + var init_texture_view = __esm({ + "node_modules/@luma.gl/core/dist/adapter/resources/texture-view.js"() { + init_resource(); + TextureView = class _TextureView extends Resource { + get [Symbol.toStringTag]() { + return "TextureView"; + } + /** Should not be constructed directly. Use `texture.createView(props)` */ + constructor(device, props) { + super(device, props, _TextureView.defaultProps); + } + static defaultProps = { + ...Resource.defaultProps, + format: void 0, + dimension: void 0, + aspect: "all", + baseMipLevel: 0, + mipLevelCount: void 0, + baseArrayLayer: 0, + arrayLayerCount: void 0 + }; + }; + } + }); + + // node_modules/@luma.gl/core/dist/adapter-utils/format-compiler-log.js + function formatCompilerLog(shaderLog, source3, options) { + let formattedLog = ""; + const lines = source3.split(/\r?\n/); + const log3 = shaderLog.slice().sort((a, b) => a.lineNum - b.lineNum); + switch (options?.showSourceCode || "no") { + case "all": + let currentMessageIndex = 0; + for (let lineNum = 1; lineNum <= lines.length; lineNum++) { + const line = lines[lineNum - 1]; + const currentMessage = log3[currentMessageIndex]; + if (line && currentMessage) { + formattedLog += getNumberedLine(line, lineNum, options); + } + while (log3.length > currentMessageIndex && currentMessage.lineNum === lineNum) { + const message2 = log3[currentMessageIndex++]; + if (message2) { + formattedLog += formatCompilerMessage(message2, lines, message2.lineNum, { + ...options, + inlineSource: false + }); + } + } + } + while (log3.length > currentMessageIndex) { + const message2 = log3[currentMessageIndex++]; + if (message2) { + formattedLog += formatCompilerMessage(message2, [], 0, { + ...options, + inlineSource: false + }); + } + } + return formattedLog; + case "issues": + case "no": + for (const message2 of shaderLog) { + formattedLog += formatCompilerMessage(message2, lines, message2.lineNum, { + inlineSource: options?.showSourceCode !== "no" + }); + } + return formattedLog; + } + } + function formatCompilerMessage(message2, lines, lineNum, options) { + if (options?.inlineSource) { + const numberedLines = getNumberedLines(lines, lineNum); + const positionIndicator = message2.linePos > 0 ? `${" ".repeat(message2.linePos + 5)}^^^ +` : ""; + return ` +${numberedLines}${positionIndicator}${message2.type.toUpperCase()}: ${message2.message} + +`; + } + const color2 = message2.type === "error" ? "red" : "orange"; + return options?.html ? `
${message2.type.toUpperCase()}: ${message2.message}
` : `${message2.type.toUpperCase()}: ${message2.message}`; + } + function getNumberedLines(lines, lineNum, options) { + let numberedLines = ""; + for (let lineIndex = lineNum - 2; lineIndex <= lineNum; lineIndex++) { + const sourceLine = lines[lineIndex - 1]; + if (sourceLine !== void 0) { + numberedLines += getNumberedLine(sourceLine, lineNum, options); + } + } + return numberedLines; + } + function getNumberedLine(line, lineNum, options) { + const escapedLine = options?.html ? escapeHTML(line) : line; + return `${padLeft(String(lineNum), 4)}: ${escapedLine}${options?.html ? "
" : "\n"}`; + } + function padLeft(string, paddedLength) { + let result = ""; + for (let i = string.length; i < paddedLength; ++i) { + result += " "; + } + return result + string; + } + function escapeHTML(unsafe) { + return unsafe.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """).replaceAll("'", "'"); + } + var init_format_compiler_log = __esm({ + "node_modules/@luma.gl/core/dist/adapter-utils/format-compiler-log.js"() { + } + }); + + // node_modules/@luma.gl/core/dist/adapter/resources/shader.js + function getShaderIdFromProps(props) { + return getShaderName2(props.source) || props.id || uid(`unnamed ${props.stage}-shader`); + } + function getShaderName2(shader, defaultName = "unnamed") { + const SHADER_NAME_REGEXP = /#define[\s*]SHADER_NAME[\s*]([A-Za-z0-9_-]+)[\s*]/; + const match = SHADER_NAME_REGEXP.exec(shader); + return match?.[1] ?? defaultName; + } + var Shader; + var init_shader = __esm({ + "node_modules/@luma.gl/core/dist/adapter/resources/shader.js"() { + init_resource(); + init_uid(); + init_format_compiler_log(); + Shader = class _Shader extends Resource { + get [Symbol.toStringTag]() { + return "Shader"; + } + /** The stage of this shader */ + stage; + /** The source code of this shader */ + source; + /** The compilation status of the shader. 'pending' if compilation is asynchronous, and on production */ + compilationStatus = "pending"; + /** Create a new Shader instance */ + constructor(device, props) { + props = { ...props, debugShaders: props.debugShaders || device.props.debugShaders || "errors" }; + super(device, { id: getShaderIdFromProps(props), ...props }, _Shader.defaultProps); + this.stage = this.props.stage; + this.source = this.props.source; + } + /** Get compiler log synchronously (WebGL only) */ + getCompilationInfoSync() { + return null; + } + /** Get translated shader source in host platform's native language (HLSL, GLSL, and even GLSL ES), if available */ + getTranslatedSource() { + return null; + } + // PORTABLE HELPERS + /** In browser logging of errors */ + async debugShader() { + const trigger = this.props.debugShaders; + switch (trigger) { + case "never": + return; + case "errors": + if (this.compilationStatus === "success") { + return; + } + break; + case "warnings": + case "always": + break; + } + const messages = await this.getCompilationInfo(); + if (trigger === "warnings" && messages?.length === 0) { + return; + } + this._displayShaderLog(messages, this.id); + } + // PRIVATE + /** + * In-browser UI logging of errors + * TODO - this HTML formatting code should not be in Device, should be pluggable + */ + _displayShaderLog(messages, shaderId) { + if (typeof document === "undefined" || !document?.createElement) { + return; + } + const shaderName = shaderId; + const shaderTitle = `${this.stage} shader "${shaderName}"`; + const htmlLog = formatCompilerLog(messages, this.source, { showSourceCode: "all", html: true }); + const translatedSource = this.getTranslatedSource(); + const container = document.createElement("div"); + container.innerHTML = `

Compilation error in ${shaderTitle}

+
+
+ +
+
${htmlLog}
`; + if (translatedSource) { + container.innerHTML += `

Translated Source



${translatedSource}
`; + } + container.style.top = "0"; + container.style.left = "0"; + container.style.background = "white"; + container.style.position = "fixed"; + container.style.zIndex = "9999"; + container.style.maxWidth = "100vw"; + container.style.maxHeight = "100vh"; + container.style.overflowY = "auto"; + document.body.appendChild(container); + const error = container.querySelector(".luma-compiler-log-error"); + error?.scrollIntoView(); + container.querySelector("button#close").onclick = () => { + container.remove(); + }; + container.querySelector("button#copy").onclick = () => { + navigator.clipboard.writeText(this.source); + }; + } + static defaultProps = { + ...Resource.defaultProps, + language: "auto", + stage: void 0, + source: "", + sourceMap: null, + entryPoint: "main", + debugShaders: void 0 + }; + }; + } + }); + + // node_modules/@luma.gl/core/dist/adapter/resources/framebuffer.js + var Framebuffer; + var init_framebuffer = __esm({ + "node_modules/@luma.gl/core/dist/adapter/resources/framebuffer.js"() { + init_resource(); + init_texture(); + init_log(); + Framebuffer = class _Framebuffer extends Resource { + get [Symbol.toStringTag]() { + return "Framebuffer"; + } + /** Width of all attachments in this framebuffer */ + width; + /** Height of all attachments in this framebuffer */ + height; + constructor(device, props = {}) { + super(device, props, _Framebuffer.defaultProps); + this.width = this.props.width; + this.height = this.props.height; + } + /** + * Create a copy of this framebuffer with new attached textures, with same props but of the specified size. + * @note Does not copy contents of the attached textures. + */ + clone(size) { + const colorAttachments = this.colorAttachments.map((colorAttachment) => colorAttachment.texture.clone(size)); + const depthStencilAttachment = this.depthStencilAttachment && this.depthStencilAttachment.texture.clone(size); + return this.device.createFramebuffer({ + ...this.props, + ...size, + colorAttachments, + depthStencilAttachment + }); + } + resize(size) { + let updateSize = !size; + if (size) { + const [width, height] = Array.isArray(size) ? size : [size.width, size.height]; + updateSize = updateSize || height !== this.height || width !== this.width; + this.width = width; + this.height = height; + } + if (updateSize) { + log2.log(2, `Resizing framebuffer ${this.id} to ${this.width}x${this.height}`)(); + this.resizeAttachments(this.width, this.height); + } + } + /** Auto creates any textures */ + autoCreateAttachmentTextures() { + if (this.props.colorAttachments.length === 0 && !this.props.depthStencilAttachment) { + throw new Error("Framebuffer has noattachments"); + } + this.colorAttachments = this.props.colorAttachments.map((attachment2, index2) => { + if (typeof attachment2 === "string") { + const texture = this.createColorTexture(attachment2, index2); + this.attachResource(texture); + return texture.view; + } + if (attachment2 instanceof Texture) { + return attachment2.view; + } + return attachment2; + }); + const attachment = this.props.depthStencilAttachment; + if (attachment) { + if (typeof attachment === "string") { + const texture = this.createDepthStencilTexture(attachment); + this.attachResource(texture); + this.depthStencilAttachment = texture.view; + } else if (attachment instanceof Texture) { + this.depthStencilAttachment = attachment.view; + } else { + this.depthStencilAttachment = attachment; + } + } + } + /** Create a color texture */ + createColorTexture(format2, index2) { + return this.device.createTexture({ + id: `${this.id}-color-attachment-${index2}`, + usage: Texture.RENDER_ATTACHMENT, + format: format2, + width: this.width, + height: this.height, + // TODO deprecated? - luma.gl v8 compatibility + sampler: { + magFilter: "linear", + minFilter: "linear" + } + }); + } + /** Create depth stencil texture */ + createDepthStencilTexture(format2) { + return this.device.createTexture({ + id: `${this.id}-depth-stencil-attachment`, + usage: Texture.RENDER_ATTACHMENT, + format: format2, + width: this.width, + height: this.height + }); + } + /** + * Default implementation of resize + * Creates new textures with correct size for all attachments. + * and destroys existing textures if owned + */ + resizeAttachments(width, height) { + this.colorAttachments.forEach((colorAttachment, i) => { + const resizedTexture = colorAttachment.texture.clone({ + width, + height + }); + this.destroyAttachedResource(colorAttachment); + this.colorAttachments[i] = resizedTexture.view; + this.attachResource(resizedTexture.view); + }); + if (this.depthStencilAttachment) { + const resizedTexture = this.depthStencilAttachment.texture.clone({ + width, + height + }); + this.destroyAttachedResource(this.depthStencilAttachment); + this.depthStencilAttachment = resizedTexture.view; + this.attachResource(resizedTexture); + } + this.updateAttachments(); + } + static defaultProps = { + ...Resource.defaultProps, + width: 1, + height: 1, + colorAttachments: [], + // ['rgba8unorm'], + depthStencilAttachment: null + // 'depth24plus-stencil8' + }; + }; + } + }); + + // node_modules/@luma.gl/core/dist/adapter/resources/render-pipeline.js + var RenderPipeline; + var init_render_pipeline = __esm({ + "node_modules/@luma.gl/core/dist/adapter/resources/render-pipeline.js"() { + init_resource(); + RenderPipeline = class _RenderPipeline extends Resource { + get [Symbol.toStringTag]() { + return "RenderPipeline"; + } + /** The merged layout */ + shaderLayout; + /** Buffer map describing buffer interleaving etc */ + bufferLayout; + /** The linking status of the pipeline. 'pending' if linking is asynchronous, and on production */ + linkStatus = "pending"; + /** The hash of the pipeline */ + hash = ""; + /** Optional shared backend implementation */ + sharedRenderPipeline = null; + /** Whether shader or pipeline compilation/linking is still in progress */ + get isPending() { + return this.linkStatus === "pending" || this.vs.compilationStatus === "pending" || this.fs?.compilationStatus === "pending"; + } + /** Whether shader or pipeline compilation/linking has failed */ + get isErrored() { + return this.linkStatus === "error" || this.vs.compilationStatus === "error" || this.fs?.compilationStatus === "error"; + } + constructor(device, props) { + super(device, props, _RenderPipeline.defaultProps); + this.shaderLayout = this.props.shaderLayout; + this.bufferLayout = this.props.bufferLayout || []; + this.sharedRenderPipeline = this.props._sharedRenderPipeline || null; + } + static defaultProps = { + ...Resource.defaultProps, + vs: null, + vertexEntryPoint: "vertexMain", + vsConstants: {}, + fs: null, + fragmentEntryPoint: "fragmentMain", + fsConstants: {}, + shaderLayout: null, + bufferLayout: [], + topology: "triangle-list", + colorAttachmentFormats: void 0, + depthStencilAttachmentFormat: void 0, + parameters: {}, + varyings: void 0, + bufferMode: void 0, + disableWarnings: false, + _sharedRenderPipeline: void 0, + bindings: void 0, + bindGroups: void 0 + }; + }; + } + }); + + // node_modules/@luma.gl/core/dist/adapter/resources/shared-render-pipeline.js + var SharedRenderPipeline; + var init_shared_render_pipeline = __esm({ + "node_modules/@luma.gl/core/dist/adapter/resources/shared-render-pipeline.js"() { + init_resource(); + SharedRenderPipeline = class extends Resource { + get [Symbol.toStringTag]() { + return "SharedRenderPipeline"; + } + constructor(device, props) { + super(device, props, { + ...Resource.defaultProps, + handle: void 0, + vs: void 0, + fs: void 0, + varyings: void 0, + bufferMode: void 0 + }); + } + }; + } + }); + + // node_modules/@luma.gl/core/dist/adapter/resources/compute-pipeline.js + var ComputePipeline; + var init_compute_pipeline = __esm({ + "node_modules/@luma.gl/core/dist/adapter/resources/compute-pipeline.js"() { + init_resource(); + ComputePipeline = class _ComputePipeline extends Resource { + get [Symbol.toStringTag]() { + return "ComputePipeline"; + } + hash = ""; + /** The merged shader layout */ + shaderLayout; + constructor(device, props) { + super(device, props, _ComputePipeline.defaultProps); + this.shaderLayout = props.shaderLayout; + } + static defaultProps = { + ...Resource.defaultProps, + shader: void 0, + entryPoint: void 0, + constants: {}, + shaderLayout: void 0 + }; + }; + } + }); + + // node_modules/@luma.gl/core/dist/factories/pipeline-factory.js + var PipelineFactory; + var init_pipeline_factory = __esm({ + "node_modules/@luma.gl/core/dist/factories/pipeline-factory.js"() { + init_compute_pipeline(); + init_render_pipeline(); + init_log(); + init_uid(); + PipelineFactory = class _PipelineFactory { + static defaultProps = { ...RenderPipeline.defaultProps }; + /** Get the singleton default pipeline factory for the specified device */ + static getDefaultPipelineFactory(device) { + const moduleData = device.getModuleData("@luma.gl/core"); + moduleData.defaultPipelineFactory ||= new _PipelineFactory(device); + return moduleData.defaultPipelineFactory; + } + device; + _hashCounter = 0; + _hashes = {}; + _renderPipelineCache = {}; + _computePipelineCache = {}; + _sharedRenderPipelineCache = {}; + get [Symbol.toStringTag]() { + return "PipelineFactory"; + } + toString() { + return `PipelineFactory(${this.device.id})`; + } + constructor(device) { + this.device = device; + } + /** + * WebGL has two cache layers with different priorities: + * - `_sharedRenderPipelineCache` owns `WEBGLSharedRenderPipeline` / `WebGLProgram` reuse. + * - `_renderPipelineCache` owns `RenderPipeline` wrapper reuse. + * + * Shared WebGL program reuse is the hard requirement. Wrapper reuse is beneficial, + * but wrapper cache misses are acceptable if that keeps the cache logic simple and + * prevents incorrect cache hits. + * + * In particular, wrapper hash logic must never force program creation or linked-program + * introspection just to decide whether a shared WebGL program can be reused. + */ + /** Return a RenderPipeline matching supplied props. Reuses an equivalent pipeline if already created. */ + createRenderPipeline(props) { + if (!this.device.props._cachePipelines) { + return this.device.createRenderPipeline(props); + } + const allProps = { ...RenderPipeline.defaultProps, ...props }; + const cache2 = this._renderPipelineCache; + const hash = this._hashRenderPipeline(allProps); + let pipeline = cache2[hash]?.resource; + if (!pipeline) { + const sharedRenderPipeline = this.device.type === "webgl" && this.device.props._sharePipelines ? this.createSharedRenderPipeline(allProps) : void 0; + pipeline = this.device.createRenderPipeline({ + ...allProps, + id: allProps.id ? `${allProps.id}-cached` : uid("unnamed-cached"), + _sharedRenderPipeline: sharedRenderPipeline + }); + pipeline.hash = hash; + cache2[hash] = { resource: pipeline, useCount: 1 }; + if (this.device.props.debugFactories) { + log2.log(3, `${this}: ${pipeline} created, count=${cache2[hash].useCount}`)(); + } + } else { + cache2[hash].useCount++; + if (this.device.props.debugFactories) { + log2.log(3, `${this}: ${cache2[hash].resource} reused, count=${cache2[hash].useCount}, (id=${props.id})`)(); + } + } + return pipeline; + } + /** Return a ComputePipeline matching supplied props. Reuses an equivalent pipeline if already created. */ + createComputePipeline(props) { + if (!this.device.props._cachePipelines) { + return this.device.createComputePipeline(props); + } + const allProps = { ...ComputePipeline.defaultProps, ...props }; + const cache2 = this._computePipelineCache; + const hash = this._hashComputePipeline(allProps); + let pipeline = cache2[hash]?.resource; + if (!pipeline) { + pipeline = this.device.createComputePipeline({ + ...allProps, + id: allProps.id ? `${allProps.id}-cached` : void 0 + }); + pipeline.hash = hash; + cache2[hash] = { resource: pipeline, useCount: 1 }; + if (this.device.props.debugFactories) { + log2.log(3, `${this}: ${pipeline} created, count=${cache2[hash].useCount}`)(); + } + } else { + cache2[hash].useCount++; + if (this.device.props.debugFactories) { + log2.log(3, `${this}: ${cache2[hash].resource} reused, count=${cache2[hash].useCount}, (id=${props.id})`)(); + } + } + return pipeline; + } + release(pipeline) { + if (!this.device.props._cachePipelines) { + pipeline.destroy(); + return; + } + const cache2 = this._getCache(pipeline); + const hash = pipeline.hash; + cache2[hash].useCount--; + if (cache2[hash].useCount === 0) { + this._destroyPipeline(pipeline); + if (this.device.props.debugFactories) { + log2.log(3, `${this}: ${pipeline} released and destroyed`)(); + } + } else if (cache2[hash].useCount < 0) { + log2.error(`${this}: ${pipeline} released, useCount < 0, resetting`)(); + cache2[hash].useCount = 0; + } else if (this.device.props.debugFactories) { + log2.log(3, `${this}: ${pipeline} released, count=${cache2[hash].useCount}`)(); + } + } + createSharedRenderPipeline(props) { + const sharedPipelineHash = this._hashSharedRenderPipeline(props); + let sharedCacheItem = this._sharedRenderPipelineCache[sharedPipelineHash]; + if (!sharedCacheItem) { + const sharedRenderPipeline = this.device._createSharedRenderPipelineWebGL(props); + sharedCacheItem = { resource: sharedRenderPipeline, useCount: 0 }; + this._sharedRenderPipelineCache[sharedPipelineHash] = sharedCacheItem; + } + sharedCacheItem.useCount++; + return sharedCacheItem.resource; + } + releaseSharedRenderPipeline(pipeline) { + if (!pipeline.sharedRenderPipeline) { + return; + } + const sharedPipelineHash = this._hashSharedRenderPipeline(pipeline.sharedRenderPipeline.props); + const sharedCacheItem = this._sharedRenderPipelineCache[sharedPipelineHash]; + if (!sharedCacheItem) { + return; + } + sharedCacheItem.useCount--; + if (sharedCacheItem.useCount === 0) { + sharedCacheItem.resource.destroy(); + delete this._sharedRenderPipelineCache[sharedPipelineHash]; + } + } + // PRIVATE + /** Destroy a cached pipeline, removing it from the cache if configured to do so. */ + _destroyPipeline(pipeline) { + const cache2 = this._getCache(pipeline); + if (!this.device.props._destroyPipelines) { + return false; + } + delete cache2[pipeline.hash]; + pipeline.destroy(); + if (pipeline instanceof RenderPipeline) { + this.releaseSharedRenderPipeline(pipeline); + } + return true; + } + /** Get the appropriate cache for the type of pipeline */ + _getCache(pipeline) { + let cache2; + if (pipeline instanceof ComputePipeline) { + cache2 = this._computePipelineCache; + } + if (pipeline instanceof RenderPipeline) { + cache2 = this._renderPipelineCache; + } + if (!cache2) { + throw new Error(`${this}`); + } + if (!cache2[pipeline.hash]) { + throw new Error(`${this}: ${pipeline} matched incorrect entry`); + } + return cache2; + } + /** Calculate a hash based on all the inputs for a compute pipeline */ + _hashComputePipeline(props) { + const { type } = this.device; + const shaderHash = this._getHash(props.shader.source); + const shaderLayoutHash = this._getHash(JSON.stringify(props.shaderLayout)); + return `${type}/C/${shaderHash}SL${shaderLayoutHash}`; + } + /** Calculate a hash based on all the inputs for a render pipeline */ + _hashRenderPipeline(props) { + const vsHash = props.vs ? this._getHash(props.vs.source) : 0; + const fsHash = props.fs ? this._getHash(props.fs.source) : 0; + const varyingHash = this._getWebGLVaryingHash(props); + const shaderLayoutHash = this._getHash(JSON.stringify(props.shaderLayout)); + const bufferLayoutHash = this._getHash(JSON.stringify(props.bufferLayout)); + const { type } = this.device; + switch (type) { + case "webgl": + const webglParameterHash = this._getHash(JSON.stringify(props.parameters)); + return `${type}/R/${vsHash}/${fsHash}V${varyingHash}T${props.topology}P${webglParameterHash}SL${shaderLayoutHash}BL${bufferLayoutHash}`; + case "webgpu": + default: + const entryPointHash = this._getHash(JSON.stringify({ + vertexEntryPoint: props.vertexEntryPoint, + fragmentEntryPoint: props.fragmentEntryPoint + })); + const parameterHash = this._getHash(JSON.stringify(props.parameters)); + const attachmentHash = this._getWebGPUAttachmentHash(props); + return `${type}/R/${vsHash}/${fsHash}V${varyingHash}T${props.topology}EP${entryPointHash}P${parameterHash}SL${shaderLayoutHash}BL${bufferLayoutHash}A${attachmentHash}`; + } + } + // This is the only gate for shared `WebGLProgram` reuse. + // Only include inputs that affect program linking or transform-feedback linkage. + // Wrapper-only concerns such as topology, parameters, attachment formats and layout + // overrides must not be added here. + _hashSharedRenderPipeline(props) { + const vsHash = props.vs ? this._getHash(props.vs.source) : 0; + const fsHash = props.fs ? this._getHash(props.fs.source) : 0; + const varyingHash = this._getWebGLVaryingHash(props); + return `webgl/S/${vsHash}/${fsHash}V${varyingHash}`; + } + _getHash(key) { + if (this._hashes[key] === void 0) { + this._hashes[key] = this._hashCounter++; + } + return this._hashes[key]; + } + _getWebGLVaryingHash(props) { + const { varyings = [], bufferMode = null } = props; + return this._getHash(JSON.stringify({ varyings, bufferMode })); + } + _getWebGPUAttachmentHash(props) { + const colorAttachmentFormats = props.colorAttachmentFormats ?? [ + this.device.preferredColorFormat + ]; + const depthStencilAttachmentFormat = props.parameters?.depthWriteEnabled ? props.depthStencilAttachmentFormat || this.device.preferredDepthFormat : null; + return this._getHash(JSON.stringify({ + colorAttachmentFormats, + depthStencilAttachmentFormat + })); + } + }; + } + }); + + // node_modules/@luma.gl/core/dist/factories/shader-factory.js + var ShaderFactory; + var init_shader_factory = __esm({ + "node_modules/@luma.gl/core/dist/factories/shader-factory.js"() { + init_shader(); + init_log(); + ShaderFactory = class _ShaderFactory { + static defaultProps = { ...Shader.defaultProps }; + /** Returns the default ShaderFactory for the given {@link Device}, creating one if necessary. */ + static getDefaultShaderFactory(device) { + const moduleData = device.getModuleData("@luma.gl/core"); + moduleData.defaultShaderFactory ||= new _ShaderFactory(device); + return moduleData.defaultShaderFactory; + } + device; + _cache = {}; + get [Symbol.toStringTag]() { + return "ShaderFactory"; + } + toString() { + return `${this[Symbol.toStringTag]}(${this.device.id})`; + } + /** @internal */ + constructor(device) { + this.device = device; + } + /** Requests a {@link Shader} from the cache, creating a new Shader only if necessary. */ + createShader(props) { + if (!this.device.props._cacheShaders) { + return this.device.createShader(props); + } + const key = this._hashShader(props); + let cacheEntry = this._cache[key]; + if (!cacheEntry) { + const resource = this.device.createShader({ + ...props, + id: props.id ? `${props.id}-cached` : void 0 + }); + this._cache[key] = cacheEntry = { resource, useCount: 1 }; + if (this.device.props.debugFactories) { + log2.log(3, `${this}: Created new shader ${resource.id}`)(); + } + } else { + cacheEntry.useCount++; + if (this.device.props.debugFactories) { + log2.log(3, `${this}: Reusing shader ${cacheEntry.resource.id} count=${cacheEntry.useCount}`)(); + } + } + return cacheEntry.resource; + } + /** Releases a previously-requested {@link Shader}, destroying it if no users remain. */ + release(shader) { + if (!this.device.props._cacheShaders) { + shader.destroy(); + return; + } + const key = this._hashShader(shader); + const cacheEntry = this._cache[key]; + if (cacheEntry) { + cacheEntry.useCount--; + if (cacheEntry.useCount === 0) { + if (this.device.props._destroyShaders) { + delete this._cache[key]; + cacheEntry.resource.destroy(); + if (this.device.props.debugFactories) { + log2.log(3, `${this}: Releasing shader ${shader.id}, destroyed`)(); + } + } + } else if (cacheEntry.useCount < 0) { + throw new Error(`ShaderFactory: Shader ${shader.id} released too many times`); + } else if (this.device.props.debugFactories) { + log2.log(3, `${this}: Releasing shader ${shader.id} count=${cacheEntry.useCount}`)(); + } + } + } + // PRIVATE + _hashShader(value) { + return `${value.stage}:${value.source}`; + } + }; + } + }); + + // node_modules/@luma.gl/core/dist/adapter-utils/bind-groups.js + function getShaderLayoutBinding(shaderLayout, bindingName, options) { + const bindingLayout = shaderLayout.bindings.find((binding) => binding.name === bindingName || `${binding.name.toLocaleLowerCase()}uniforms` === bindingName.toLocaleLowerCase()); + if (!bindingLayout && !options?.ignoreWarnings) { + log2.warn(`Binding ${bindingName} not set: Not found in shader layout.`)(); + } + return bindingLayout || null; + } + function normalizeBindingsByGroup(shaderLayout, bindingsOrBindGroups) { + if (!bindingsOrBindGroups) { + return {}; + } + if (areBindingsGrouped(bindingsOrBindGroups)) { + const bindGroups2 = bindingsOrBindGroups; + return Object.fromEntries(Object.entries(bindGroups2).map(([group2, bindings]) => [Number(group2), { ...bindings }])); + } + const bindGroups = {}; + for (const [bindingName, binding] of Object.entries(bindingsOrBindGroups)) { + const bindingLayout = getShaderLayoutBinding(shaderLayout, bindingName); + const group2 = bindingLayout?.group ?? 0; + bindGroups[group2] ||= {}; + bindGroups[group2][bindingName] = binding; + } + return bindGroups; + } + function flattenBindingsByGroup(bindGroups) { + const bindings = {}; + for (const groupBindings of Object.values(bindGroups)) { + Object.assign(bindings, groupBindings); + } + return bindings; + } + function areBindingsGrouped(bindingsOrBindGroups) { + const keys = Object.keys(bindingsOrBindGroups); + return keys.length > 0 && keys.every((key) => /^\d+$/.test(key)); + } + var init_bind_groups = __esm({ + "node_modules/@luma.gl/core/dist/adapter-utils/bind-groups.js"() { + init_log(); + } + }); + + // node_modules/@luma.gl/core/dist/adapter/resources/render-pass.js + var RenderPass; + var init_render_pass = __esm({ + "node_modules/@luma.gl/core/dist/adapter/resources/render-pass.js"() { + init_resource(); + RenderPass = class _RenderPass extends Resource { + /** TODO - should be [0, 0, 0, 0], update once deck.gl tests run clean */ + static defaultClearColor = [0, 0, 0, 1]; + /** Depth 1.0 represents the far plance */ + static defaultClearDepth = 1; + /** Clears all stencil bits */ + static defaultClearStencil = 0; + get [Symbol.toStringTag]() { + return "RenderPass"; + } + constructor(device, props) { + props = _RenderPass.normalizeProps(device, props); + super(device, props, _RenderPass.defaultProps); + } + static normalizeProps(device, props) { + return props; + } + /** Default properties for RenderPass */ + static defaultProps = { + ...Resource.defaultProps, + framebuffer: null, + parameters: void 0, + clearColor: _RenderPass.defaultClearColor, + clearColors: void 0, + clearDepth: _RenderPass.defaultClearDepth, + clearStencil: _RenderPass.defaultClearStencil, + depthReadOnly: false, + stencilReadOnly: false, + discard: false, + occlusionQuerySet: void 0, + timestampQuerySet: void 0, + beginTimestampIndex: void 0, + endTimestampIndex: void 0 + }; + }; + } + }); + + // node_modules/@luma.gl/core/dist/adapter/resources/command-encoder.js + var CommandEncoder; + var init_command_encoder = __esm({ + "node_modules/@luma.gl/core/dist/adapter/resources/command-encoder.js"() { + init_resource(); + CommandEncoder = class _CommandEncoder extends Resource { + get [Symbol.toStringTag]() { + return "CommandEncoder"; + } + _timeProfilingQuerySet = null; + _timeProfilingSlotCount = 0; + _gpuTimeMs; + constructor(device, props) { + super(device, props, _CommandEncoder.defaultProps); + this._timeProfilingQuerySet = props.timeProfilingQuerySet ?? null; + this._timeProfilingSlotCount = 0; + this._gpuTimeMs = void 0; + } + /** + * Reads all resolved timestamp pairs on the current profiler query set and caches the sum + * as milliseconds on this encoder. + */ + async resolveTimeProfilingQuerySet() { + this._gpuTimeMs = void 0; + if (!this._timeProfilingQuerySet) { + return; + } + const pairCount = Math.floor(this._timeProfilingSlotCount / 2); + if (pairCount <= 0) { + return; + } + const queryCount = pairCount * 2; + const results = await this._timeProfilingQuerySet.readResults({ + firstQuery: 0, + queryCount + }); + let totalDurationNanoseconds = 0n; + for (let queryIndex = 0; queryIndex < queryCount; queryIndex += 2) { + totalDurationNanoseconds += results[queryIndex + 1] - results[queryIndex]; + } + this._gpuTimeMs = Number(totalDurationNanoseconds) / 1e6; + } + /** Returns the number of query slots consumed by automatic pass profiling on this encoder. */ + getTimeProfilingSlotCount() { + return this._timeProfilingSlotCount; + } + getTimeProfilingQuerySet() { + return this._timeProfilingQuerySet; + } + /** Internal helper for auto-assigning timestamp slots to render/compute passes on this encoder. */ + _applyTimeProfilingToPassProps(props) { + const passProps = props || {}; + if (!this._supportsTimestampQueries() || !this._timeProfilingQuerySet) { + return passProps; + } + if (passProps.timestampQuerySet !== void 0 || passProps.beginTimestampIndex !== void 0 || passProps.endTimestampIndex !== void 0) { + return passProps; + } + const beginTimestampIndex = this._timeProfilingSlotCount; + if (beginTimestampIndex + 1 >= this._timeProfilingQuerySet.props.count) { + return passProps; + } + this._timeProfilingSlotCount += 2; + return { + ...passProps, + timestampQuerySet: this._timeProfilingQuerySet, + beginTimestampIndex, + endTimestampIndex: beginTimestampIndex + 1 + }; + } + _supportsTimestampQueries() { + return this.device.features.has("timestamp-query"); + } + // TODO - luma.gl has these on the device, should we align with WebGPU API? + // beginRenderPass(GPURenderPassDescriptor descriptor): GPURenderPassEncoder; + // beginComputePass(optional GPUComputePassDescriptor descriptor = {}): GPUComputePassEncoder; + static defaultProps = { + ...Resource.defaultProps, + measureExecutionTime: void 0, + timeProfilingQuerySet: void 0 + }; + }; + } + }); + + // node_modules/@luma.gl/core/dist/adapter/resources/command-buffer.js + var CommandBuffer; + var init_command_buffer = __esm({ + "node_modules/@luma.gl/core/dist/adapter/resources/command-buffer.js"() { + init_resource(); + CommandBuffer = class _CommandBuffer extends Resource { + get [Symbol.toStringTag]() { + return "CommandBuffer"; + } + constructor(device, props) { + super(device, props, _CommandBuffer.defaultProps); + } + static defaultProps = { + ...Resource.defaultProps + }; + }; + } + }); + + // node_modules/@luma.gl/core/dist/shadertypes/shader-types/shader-type-decoder.js + function getVariableShaderTypeInfo(format2) { + const resolvedFormat = resolveVariableShaderTypeAlias(format2); + const decoded = UNIFORM_FORMATS[resolvedFormat]; + if (!decoded) { + throw new Error(`Unsupported variable shader type: ${format2}`); + } + return decoded; + } + function getAttributeShaderTypeInfo(attributeType) { + const resolvedAttributeType = resolveAttributeShaderTypeAlias(attributeType); + const decoded = TYPE_INFO[resolvedAttributeType]; + if (!decoded) { + throw new Error(`Unsupported attribute shader type: ${attributeType}`); + } + const [primitiveType, components] = decoded; + const integer = primitiveType === "i32" || primitiveType === "u32"; + const signed = primitiveType !== "u32"; + const byteLength = PRIMITIVE_TYPE_SIZES[primitiveType] * components; + return { + primitiveType, + components, + byteLength, + integer, + signed + }; + } + function makeShaderAttributeType(primitiveType, components) { + return components === 1 ? primitiveType : `vec${components}<${primitiveType}>`; + } + function resolveAttributeShaderTypeAlias(alias) { + return WGSL_ATTRIBUTE_TYPE_ALIAS_MAP[alias] || alias; + } + function resolveVariableShaderTypeAlias(alias) { + return WGSL_VARIABLE_TYPE_ALIAS_MAP[alias] || alias; + } + var ShaderTypeDecoder, shaderTypeDecoder, PRIMITIVE_TYPE_SIZES, TYPE_INFO, UNIFORM_FORMATS, WGSL_ATTRIBUTE_TYPE_ALIAS_MAP, WGSL_VARIABLE_TYPE_ALIAS_MAP; + var init_shader_type_decoder = __esm({ + "node_modules/@luma.gl/core/dist/shadertypes/shader-types/shader-type-decoder.js"() { + ShaderTypeDecoder = class { + getVariableShaderTypeInfo(format2) { + return getVariableShaderTypeInfo(format2); + } + getAttributeShaderTypeInfo(attributeType) { + return getAttributeShaderTypeInfo(attributeType); + } + makeShaderAttributeType(primitiveType, components) { + return makeShaderAttributeType(primitiveType, components); + } + resolveAttributeShaderTypeAlias(alias) { + return resolveAttributeShaderTypeAlias(alias); + } + resolveVariableShaderTypeAlias(alias) { + return resolveVariableShaderTypeAlias(alias); + } + }; + shaderTypeDecoder = new ShaderTypeDecoder(); + PRIMITIVE_TYPE_SIZES = { + f32: 4, + f16: 2, + i32: 4, + u32: 4 + // 'bool-webgl': 4, + }; + TYPE_INFO = { + f32: ["f32", 1], + "vec2": ["f32", 2], + "vec3": ["f32", 3], + "vec4": ["f32", 4], + f16: ["f16", 1], + "vec2": ["f16", 2], + "vec3": ["f16", 3], + "vec4": ["f16", 4], + i32: ["i32", 1], + "vec2": ["i32", 2], + "vec3": ["i32", 3], + "vec4": ["i32", 4], + u32: ["u32", 1], + "vec2": ["u32", 2], + "vec3": ["u32", 3], + "vec4": ["u32", 4] + }; + UNIFORM_FORMATS = { + f32: { type: "f32", components: 1 }, + f16: { type: "f16", components: 1 }, + i32: { type: "i32", components: 1 }, + u32: { type: "u32", components: 1 }, + // 'bool-webgl': {type: 'bool-webgl', components: 1}, + "vec2": { type: "f32", components: 2 }, + "vec3": { type: "f32", components: 3 }, + "vec4": { type: "f32", components: 4 }, + "vec2": { type: "f16", components: 2 }, + "vec3": { type: "f16", components: 3 }, + "vec4": { type: "f16", components: 4 }, + "vec2": { type: "i32", components: 2 }, + "vec3": { type: "i32", components: 3 }, + "vec4": { type: "i32", components: 4 }, + "vec2": { type: "u32", components: 2 }, + "vec3": { type: "u32", components: 3 }, + "vec4": { type: "u32", components: 4 }, + "mat2x2": { type: "f32", components: 4 }, + "mat2x3": { type: "f32", components: 6 }, + "mat2x4": { type: "f32", components: 8 }, + "mat3x2": { type: "f32", components: 6 }, + "mat3x3": { type: "f32", components: 9 }, + "mat3x4": { type: "f32", components: 12 }, + "mat4x2": { type: "f32", components: 8 }, + "mat4x3": { type: "f32", components: 12 }, + "mat4x4": { type: "f32", components: 16 }, + "mat2x2": { type: "f16", components: 4 }, + "mat2x3": { type: "f16", components: 6 }, + "mat2x4": { type: "f16", components: 8 }, + "mat3x2": { type: "f16", components: 6 }, + "mat3x3": { type: "f16", components: 9 }, + "mat3x4": { type: "f16", components: 12 }, + "mat4x2": { type: "f16", components: 8 }, + "mat4x3": { type: "f16", components: 12 }, + "mat4x4": { type: "f16", components: 16 }, + "mat2x2": { type: "i32", components: 4 }, + "mat2x3": { type: "i32", components: 6 }, + "mat2x4": { type: "i32", components: 8 }, + "mat3x2": { type: "i32", components: 6 }, + "mat3x3": { type: "i32", components: 9 }, + "mat3x4": { type: "i32", components: 12 }, + "mat4x2": { type: "i32", components: 8 }, + "mat4x3": { type: "i32", components: 12 }, + "mat4x4": { type: "i32", components: 16 }, + "mat2x2": { type: "u32", components: 4 }, + "mat2x3": { type: "u32", components: 6 }, + "mat2x4": { type: "u32", components: 8 }, + "mat3x2": { type: "u32", components: 6 }, + "mat3x3": { type: "u32", components: 9 }, + "mat3x4": { type: "u32", components: 12 }, + "mat4x2": { type: "u32", components: 8 }, + "mat4x3": { type: "u32", components: 12 }, + "mat4x4": { type: "u32", components: 16 } + }; + WGSL_ATTRIBUTE_TYPE_ALIAS_MAP = { + vec2i: "vec2", + vec3i: "vec3", + vec4i: "vec4", + vec2u: "vec2", + vec3u: "vec3", + vec4u: "vec4", + vec2f: "vec2", + vec3f: "vec3", + vec4f: "vec4", + // Requires the f16 extension. + vec2h: "vec2", + vec3h: "vec3", + vec4h: "vec4" + }; + WGSL_VARIABLE_TYPE_ALIAS_MAP = { + vec2i: "vec2", + vec3i: "vec3", + vec4i: "vec4", + vec2u: "vec2", + vec3u: "vec3", + vec4u: "vec4", + vec2f: "vec2", + vec3f: "vec3", + vec4f: "vec4", + vec2h: "vec2", + vec3h: "vec3", + vec4h: "vec4", + mat2x2f: "mat2x2", + mat2x3f: "mat2x3", + mat2x4f: "mat2x4", + mat3x2f: "mat3x2", + mat3x3f: "mat3x3", + mat3x4f: "mat3x4", + mat4x2f: "mat4x2", + mat4x3f: "mat4x3", + mat4x4f: "mat4x4", + mat2x2i: "mat2x2", + mat2x3i: "mat2x3", + mat2x4i: "mat2x4", + mat3x2i: "mat3x2", + mat3x3i: "mat3x3", + mat3x4i: "mat3x4", + mat4x2i: "mat4x2", + mat4x3i: "mat4x3", + mat4x4i: "mat4x4", + mat2x2u: "mat2x2", + mat2x3u: "mat2x3", + mat2x4u: "mat2x4", + mat3x2u: "mat3x2", + mat3x3u: "mat3x3", + mat3x4u: "mat3x4", + mat4x2u: "mat4x2", + mat4x3u: "mat4x3", + mat4x4u: "mat4x4", + mat2x2h: "mat2x2", + mat2x3h: "mat2x3", + mat2x4h: "mat2x4", + mat3x2h: "mat3x2", + mat3x3h: "mat3x3", + mat3x4h: "mat3x4", + mat4x2h: "mat4x2", + mat4x3h: "mat4x3", + mat4x4h: "mat4x4" + }; + } + }); + + // node_modules/@luma.gl/core/dist/adapter-utils/get-attribute-from-layouts.js + function getAttributeInfosFromLayouts(shaderLayout, bufferLayout) { + const attributeInfos = {}; + for (const attribute of shaderLayout.attributes) { + const attributeInfo = getAttributeInfoFromLayouts(shaderLayout, bufferLayout, attribute.name); + if (attributeInfo) { + attributeInfos[attribute.name] = attributeInfo; + } + } + return attributeInfos; + } + function getAttributeInfosByLocation(shaderLayout, bufferLayout, maxVertexAttributes = 16) { + const attributeInfos = getAttributeInfosFromLayouts(shaderLayout, bufferLayout); + const locationInfos = new Array(maxVertexAttributes).fill(null); + for (const attributeInfo of Object.values(attributeInfos)) { + locationInfos[attributeInfo.location] = attributeInfo; + } + return locationInfos; + } + function getAttributeInfoFromLayouts(shaderLayout, bufferLayout, name2) { + const shaderDeclaration = getAttributeFromShaderLayout(shaderLayout, name2); + const bufferMapping = getAttributeFromBufferLayout(bufferLayout, name2); + if (!shaderDeclaration) { + return null; + } + const attributeTypeInfo = shaderTypeDecoder.getAttributeShaderTypeInfo(shaderDeclaration.type); + const defaultVertexFormat = vertexFormatDecoder.getCompatibleVertexFormat(attributeTypeInfo); + const vertexFormat = bufferMapping?.vertexFormat || defaultVertexFormat; + const vertexFormatInfo = vertexFormatDecoder.getVertexFormatInfo(vertexFormat); + return { + attributeName: bufferMapping?.attributeName || shaderDeclaration.name, + bufferName: bufferMapping?.bufferName || shaderDeclaration.name, + location: shaderDeclaration.location, + shaderType: shaderDeclaration.type, + primitiveType: attributeTypeInfo.primitiveType, + shaderComponents: attributeTypeInfo.components, + vertexFormat, + bufferDataType: vertexFormatInfo.type, + bufferComponents: vertexFormatInfo.components, + // normalized is a property of the buffer's vertex format + normalized: vertexFormatInfo.normalized, + // integer is a property of the shader declaration + integer: attributeTypeInfo.integer, + stepMode: bufferMapping?.stepMode || shaderDeclaration.stepMode || "vertex", + byteOffset: bufferMapping?.byteOffset || 0, + byteStride: bufferMapping?.byteStride || 0 + }; + } + function getAttributeFromShaderLayout(shaderLayout, name2) { + const attribute = shaderLayout.attributes.find((attr) => attr.name === name2); + if (!attribute) { + log2.warn(`shader layout attribute "${name2}" not present in shader`); + } + return attribute || null; + } + function getAttributeFromBufferLayout(bufferLayouts, name2) { + checkBufferLayouts(bufferLayouts); + let bufferLayoutInfo = getAttributeFromShortHand(bufferLayouts, name2); + if (bufferLayoutInfo) { + return bufferLayoutInfo; + } + bufferLayoutInfo = getAttributeFromAttributesList(bufferLayouts, name2); + if (bufferLayoutInfo) { + return bufferLayoutInfo; + } + log2.warn(`layout for attribute "${name2}" not present in buffer layout`); + return null; + } + function checkBufferLayouts(bufferLayouts) { + for (const bufferLayout of bufferLayouts) { + if (bufferLayout.attributes && bufferLayout.format || !bufferLayout.attributes && !bufferLayout.format) { + log2.warn(`BufferLayout ${name} must have either 'attributes' or 'format' field`); + } + } + } + function getAttributeFromShortHand(bufferLayouts, name2) { + for (const bufferLayout of bufferLayouts) { + if (bufferLayout.format && bufferLayout.name === name2) { + return { + attributeName: bufferLayout.name, + bufferName: name2, + stepMode: bufferLayout.stepMode, + vertexFormat: bufferLayout.format, + // If offset is needed, use `attributes` field. + byteOffset: 0, + byteStride: bufferLayout.byteStride || 0 + }; + } + } + return null; + } + function getAttributeFromAttributesList(bufferLayouts, name2) { + for (const bufferLayout of bufferLayouts) { + let byteStride = bufferLayout.byteStride; + if (typeof bufferLayout.byteStride !== "number") { + for (const attributeMapping2 of bufferLayout.attributes || []) { + const info = vertexFormatDecoder.getVertexFormatInfo(attributeMapping2.format); + byteStride += info.byteLength; + } + } + const attributeMapping = bufferLayout.attributes?.find((mapping) => mapping.attribute === name2); + if (attributeMapping) { + return { + attributeName: attributeMapping.attribute, + bufferName: bufferLayout.name, + stepMode: bufferLayout.stepMode, + vertexFormat: attributeMapping.format, + byteOffset: attributeMapping.byteOffset, + // @ts-ignore + byteStride + }; + } + } + return null; + } + var init_get_attribute_from_layouts = __esm({ + "node_modules/@luma.gl/core/dist/adapter-utils/get-attribute-from-layouts.js"() { + init_log(); + init_shader_type_decoder(); + init_vertex_format_decoder(); + } + }); + + // node_modules/@luma.gl/core/dist/adapter/resources/vertex-array.js + var VertexArray; + var init_vertex_array = __esm({ + "node_modules/@luma.gl/core/dist/adapter/resources/vertex-array.js"() { + init_get_attribute_from_layouts(); + init_resource(); + VertexArray = class _VertexArray extends Resource { + static defaultProps = { + ...Resource.defaultProps, + shaderLayout: void 0, + bufferLayout: [] + }; + get [Symbol.toStringTag]() { + return "VertexArray"; + } + /** Max number of vertex attributes */ + maxVertexAttributes; + /** Attribute infos indexed by location - TODO only needed by webgl module? */ + attributeInfos; + /** Index buffer */ + indexBuffer = null; + /** Attributes indexed by buffer slot */ + attributes; + constructor(device, props) { + super(device, props, _VertexArray.defaultProps); + this.maxVertexAttributes = device.limits.maxVertexAttributes; + this.attributes = new Array(this.maxVertexAttributes).fill(null); + this.attributeInfos = getAttributeInfosByLocation(props.shaderLayout, props.bufferLayout, this.maxVertexAttributes); + } + // DEPRECATED METHODS + /** @deprecated Set constant attributes (WebGL only) */ + setConstantWebGL(location, value) { + this.device.reportError(new Error("constant attributes not supported"), this)(); + } + }; + } + }); + + // node_modules/@luma.gl/core/dist/adapter/resources/transform-feedback.js + var TransformFeedback; + var init_transform_feedback = __esm({ + "node_modules/@luma.gl/core/dist/adapter/resources/transform-feedback.js"() { + init_resource(); + TransformFeedback = class _TransformFeedback extends Resource { + static defaultProps = { + ...Resource.defaultProps, + layout: void 0, + buffers: {} + }; + get [Symbol.toStringTag]() { + return "TransformFeedback"; + } + constructor(device, props) { + super(device, props, _TransformFeedback.defaultProps); + } + }; + } + }); + + // node_modules/@luma.gl/core/dist/adapter/resources/query-set.js + var QuerySet; + var init_query_set = __esm({ + "node_modules/@luma.gl/core/dist/adapter/resources/query-set.js"() { + init_resource(); + QuerySet = class _QuerySet extends Resource { + get [Symbol.toStringTag]() { + return "QuerySet"; + } + constructor(device, props) { + super(device, props, _QuerySet.defaultProps); + } + static defaultProps = { + ...Resource.defaultProps, + type: void 0, + count: void 0 + }; + }; + } + }); + + // node_modules/@luma.gl/core/dist/adapter/resources/fence.js + var Fence; + var init_fence = __esm({ + "node_modules/@luma.gl/core/dist/adapter/resources/fence.js"() { + init_resource(); + Fence = class _Fence extends Resource { + static defaultProps = { + ...Resource.defaultProps + }; + get [Symbol.toStringTag]() { + return "Fence"; + } + constructor(device, props = {}) { + super(device, props, _Fence.defaultProps); + } + }; + } + }); + + // node_modules/@luma.gl/core/dist/shadertypes/data-types/decode-data-types.js + function alignTo(size, count2) { + switch (count2) { + case 1: + return size; + // Pad upwards to even multiple of 2 + case 2: + return size + size % 2; + // Pad upwards to even multiple of 2 + default: + return size + (4 - size % 4) % 4; + } + } + function getTypedArrayConstructor(type) { + const [, , , , Constructor] = NORMALIZED_TYPE_MAP2[type]; + return Constructor; + } + var NORMALIZED_TYPE_MAP2; + var init_decode_data_types = __esm({ + "node_modules/@luma.gl/core/dist/shadertypes/data-types/decode-data-types.js"() { + NORMALIZED_TYPE_MAP2 = { + uint8: ["uint8", "u32", 1, false, Uint8Array], + sint8: ["sint8", "i32", 1, false, Int8Array], + unorm8: ["uint8", "f32", 1, true, Uint8Array], + snorm8: ["sint8", "f32", 1, true, Int8Array], + uint16: ["uint16", "u32", 2, false, Uint16Array], + sint16: ["sint16", "i32", 2, false, Int16Array], + unorm16: ["uint16", "u32", 2, true, Uint16Array], + snorm16: ["sint16", "i32", 2, true, Int16Array], + float16: ["float16", "f16", 2, false, Uint16Array], + float32: ["float32", "f32", 4, false, Float32Array], + uint32: ["uint32", "u32", 4, false, Uint32Array], + sint32: ["sint32", "i32", 4, false, Int32Array] + }; + } + }); + + // node_modules/@luma.gl/core/dist/shadertypes/shader-types/shader-block-layout.js + function makeShaderBlockLayout(uniformTypes, options = {}) { + const copiedUniformTypes = { ...uniformTypes }; + const layout = options.layout ?? "std140"; + const fields = {}; + let size = 0; + for (const [key, uniformType] of Object.entries(copiedUniformTypes)) { + size = addToLayout(fields, key, uniformType, size, layout); + } + size = alignTo(size, getTypeAlignment(copiedUniformTypes, layout)); + return { + layout, + byteLength: size * 4, + uniformTypes: copiedUniformTypes, + fields + }; + } + function getLeafLayoutInfo(type, layout) { + const resolvedType = resolveVariableShaderTypeAlias(type); + const decodedType = getVariableShaderTypeInfo(resolvedType); + const matrixMatch = /^mat(\d)x(\d)<.+>$/.exec(resolvedType); + if (matrixMatch) { + const columns = Number(matrixMatch[1]); + const rows = Number(matrixMatch[2]); + const columnInfo = getVectorLayoutInfo(rows, resolvedType, decodedType.type, layout); + const columnStride = getMatrixColumnStride(columnInfo.size, columnInfo.alignment, layout); + return { + alignment: columnInfo.alignment, + size: columns * columnStride, + components: columns * rows, + columns, + rows, + columnStride, + shaderType: resolvedType, + type: decodedType.type + }; + } + const vectorMatch = /^vec(\d)<.+>$/.exec(resolvedType); + if (vectorMatch) { + return getVectorLayoutInfo(Number(vectorMatch[1]), resolvedType, decodedType.type, layout); + } + return { + alignment: 1, + size: 1, + components: 1, + columns: 1, + rows: 1, + columnStride: 1, + shaderType: resolvedType, + type: decodedType.type + }; + } + function isCompositeShaderTypeStruct(value) { + return Boolean(value) && typeof value === "object" && !Array.isArray(value); + } + function addToLayout(fields, name2, type, offset, layout) { + if (typeof type === "string") { + const info = getLeafLayoutInfo(type, layout); + const alignedOffset = alignTo(offset, info.alignment); + fields[name2] = { + offset: alignedOffset, + ...info + }; + return alignedOffset + info.size; + } + if (Array.isArray(type)) { + if (Array.isArray(type[0])) { + throw new Error(`Nested arrays are not supported for ${name2}`); + } + const elementType = type[0]; + const length4 = type[1]; + const stride = getArrayStride(elementType, layout); + const arrayOffset = alignTo(offset, getTypeAlignment(type, layout)); + for (let i = 0; i < length4; i++) { + addToLayout(fields, `${name2}[${i}]`, elementType, arrayOffset + i * stride, layout); + } + return arrayOffset + stride * length4; + } + if (isCompositeShaderTypeStruct(type)) { + const structAlignment = getTypeAlignment(type, layout); + let structOffset = alignTo(offset, structAlignment); + for (const [memberName, memberType] of Object.entries(type)) { + structOffset = addToLayout(fields, `${name2}.${memberName}`, memberType, structOffset, layout); + } + return alignTo(structOffset, structAlignment); + } + throw new Error(`Unsupported CompositeShaderType for ${name2}`); + } + function getTypeSize(type, layout) { + if (typeof type === "string") { + return getLeafLayoutInfo(type, layout).size; + } + if (Array.isArray(type)) { + const elementType = type[0]; + const length4 = type[1]; + if (Array.isArray(elementType)) { + throw new Error("Nested arrays are not supported"); + } + return getArrayStride(elementType, layout) * length4; + } + let size = 0; + for (const memberType of Object.values(type)) { + const compositeMemberType = memberType; + size = alignTo(size, getTypeAlignment(compositeMemberType, layout)); + size += getTypeSize(compositeMemberType, layout); + } + return alignTo(size, getTypeAlignment(type, layout)); + } + function getTypeAlignment(type, layout) { + if (typeof type === "string") { + return getLeafLayoutInfo(type, layout).alignment; + } + if (Array.isArray(type)) { + const elementType = type[0]; + const elementAlignment = getTypeAlignment(elementType, layout); + return uses16ByteArrayAlignment(layout) ? Math.max(elementAlignment, 4) : elementAlignment; + } + let maxAlignment = 1; + for (const memberType of Object.values(type)) { + const memberAlignment = getTypeAlignment(memberType, layout); + maxAlignment = Math.max(maxAlignment, memberAlignment); + } + return uses16ByteStructAlignment(layout) ? Math.max(maxAlignment, 4) : maxAlignment; + } + function getVectorLayoutInfo(components, shaderType, type, layout) { + return { + alignment: components === 2 ? 2 : 4, + size: components === 3 ? 3 : components, + components, + columns: 1, + rows: components, + columnStride: components === 3 ? 3 : components, + shaderType, + type + }; + } + function getArrayStride(elementType, layout) { + const elementSize = getTypeSize(elementType, layout); + const elementAlignment = getTypeAlignment(elementType, layout); + return getArrayLikeStride(elementSize, elementAlignment, layout); + } + function getArrayLikeStride(size, alignment, layout) { + return alignTo(size, uses16ByteArrayAlignment(layout) ? 4 : alignment); + } + function getMatrixColumnStride(size, alignment, layout) { + return layout === "std140" ? 4 : alignTo(size, alignment); + } + function uses16ByteArrayAlignment(layout) { + return layout === "std140" || layout === "wgsl-uniform"; + } + function uses16ByteStructAlignment(layout) { + return layout === "std140" || layout === "wgsl-uniform"; + } + var init_shader_block_layout = __esm({ + "node_modules/@luma.gl/core/dist/shadertypes/shader-types/shader-block-layout.js"() { + init_decode_data_types(); + init_shader_type_decoder(); + } + }); + + // node_modules/@luma.gl/core/dist/utils/array-utils-flat.js + function getScratchArrayBuffer(byteLength) { + if (!arrayBuffer || arrayBuffer.byteLength < byteLength) { + arrayBuffer = new ArrayBuffer(byteLength); + } + return arrayBuffer; + } + function getScratchArray(Type, length4) { + const scratchArrayBuffer = getScratchArrayBuffer(Type.BYTES_PER_ELEMENT * length4); + return new Type(scratchArrayBuffer, 0, length4); + } + var arrayBuffer; + var init_array_utils_flat = __esm({ + "node_modules/@luma.gl/core/dist/utils/array-utils-flat.js"() { + } + }); + + // node_modules/@luma.gl/core/dist/utils/is-array.js + function isTypedArray2(value) { + return ArrayBuffer.isView(value) && !(value instanceof DataView); + } + function isNumberArray2(value) { + if (Array.isArray(value)) { + return value.length === 0 || typeof value[0] === "number"; + } + return isTypedArray2(value); + } + var init_is_array = __esm({ + "node_modules/@luma.gl/core/dist/utils/is-array.js"() { + } + }); + + // node_modules/@luma.gl/core/dist/portable/shader-block-writer.js + function isCompositeUniformObject(value) { + return Boolean(value) && typeof value === "object" && !Array.isArray(value) && !ArrayBuffer.isView(value); + } + function sliceNumericArray(value, start, end) { + return Array.prototype.slice.call(value, start, end); + } + var ShaderBlockWriter; + var init_shader_block_writer = __esm({ + "node_modules/@luma.gl/core/dist/portable/shader-block-writer.js"() { + init_array_utils_flat(); + init_is_array(); + init_log(); + init_shader_block_layout(); + ShaderBlockWriter = class { + /** Layout metadata used to flatten and serialize values. */ + layout; + /** + * Creates a writer for a precomputed shader-block layout. + */ + constructor(layout) { + this.layout = layout; + } + /** + * Returns `true` if the flattened layout contains the given field. + */ + has(name2) { + return Boolean(this.layout.fields[name2]); + } + /** + * Returns offset and size metadata for a flattened field. + */ + get(name2) { + const entry = this.layout.fields[name2]; + return entry ? { offset: entry.offset, size: entry.size } : void 0; + } + /** + * Flattens nested composite values into leaf-path values understood by {@link UniformBlock}. + * + * Top-level values may be supplied either in nested object form matching the + * declared composite shader types or as already-flattened leaf-path values. + */ + getFlatUniformValues(uniformValues) { + const flattenedUniformValues = {}; + for (const [name2, value] of Object.entries(uniformValues)) { + const uniformType = this.layout.uniformTypes[name2]; + if (uniformType) { + this._flattenCompositeValue(flattenedUniformValues, name2, uniformType, value); + } else if (this.layout.fields[name2]) { + flattenedUniformValues[name2] = value; + } + } + return flattenedUniformValues; + } + /** + * Serializes the supplied values into buffer-backed binary data. + * + * The returned view length matches {@link ShaderBlockLayout.byteLength}, which + * is the exact packed size of the block. + */ + getData(uniformValues) { + const buffer = getScratchArrayBuffer(this.layout.byteLength); + new Uint8Array(buffer, 0, this.layout.byteLength).fill(0); + const typedArrays = { + i32: new Int32Array(buffer), + u32: new Uint32Array(buffer), + f32: new Float32Array(buffer), + f16: new Uint16Array(buffer) + }; + const flattenedUniformValues = this.getFlatUniformValues(uniformValues); + for (const [name2, value] of Object.entries(flattenedUniformValues)) { + this._writeLeafValue(typedArrays, name2, value); + } + return new Uint8Array(buffer, 0, this.layout.byteLength); + } + /** + * Recursively flattens nested values using the declared composite shader type. + */ + _flattenCompositeValue(flattenedUniformValues, baseName, uniformType, value) { + if (value === void 0) { + return; + } + if (typeof uniformType === "string" || this.layout.fields[baseName]) { + flattenedUniformValues[baseName] = value; + return; + } + if (Array.isArray(uniformType)) { + const elementType = uniformType[0]; + const length4 = uniformType[1]; + if (Array.isArray(elementType)) { + throw new Error(`Nested arrays are not supported for ${baseName}`); + } + if (typeof elementType === "string" && isNumberArray2(value)) { + this._flattenPackedArray(flattenedUniformValues, baseName, elementType, length4, value); + return; + } + if (!Array.isArray(value)) { + log2.warn(`Unsupported uniform array value for ${baseName}:`, value)(); + return; + } + for (let index2 = 0; index2 < Math.min(value.length, length4); index2++) { + const elementValue = value[index2]; + if (elementValue === void 0) { + continue; + } + this._flattenCompositeValue(flattenedUniformValues, `${baseName}[${index2}]`, elementType, elementValue); + } + return; + } + if (isCompositeShaderTypeStruct(uniformType) && isCompositeUniformObject(value)) { + for (const [key, subValue] of Object.entries(value)) { + if (subValue === void 0) { + continue; + } + const nestedName = `${baseName}.${key}`; + this._flattenCompositeValue(flattenedUniformValues, nestedName, uniformType[key], subValue); + } + return; + } + log2.warn(`Unsupported uniform value for ${baseName}:`, value)(); + } + /** + * Expands tightly packed numeric arrays into per-element leaf fields. + */ + _flattenPackedArray(flattenedUniformValues, baseName, elementType, length4, value) { + const numericValue = value; + const elementLayout = getLeafLayoutInfo(elementType, this.layout.layout); + const packedElementLength = elementLayout.components; + for (let index2 = 0; index2 < length4; index2++) { + const start = index2 * packedElementLength; + if (start >= numericValue.length) { + break; + } + if (packedElementLength === 1) { + flattenedUniformValues[`${baseName}[${index2}]`] = Number(numericValue[start]); + } else { + flattenedUniformValues[`${baseName}[${index2}]`] = sliceNumericArray(value, start, start + packedElementLength); + } + } + } + /** + * Writes one flattened leaf value into its typed-array view. + */ + _writeLeafValue(typedArrays, name2, value) { + const entry = this.layout.fields[name2]; + if (!entry) { + log2.warn(`Uniform ${name2} not found in layout`)(); + return; + } + const { type, components, columns, rows, offset, columnStride } = entry; + const array = typedArrays[type]; + if (components === 1) { + array[offset] = Number(value); + return; + } + const sourceValue = value; + if (columns === 1) { + for (let componentIndex = 0; componentIndex < components; componentIndex++) { + array[offset + componentIndex] = Number(sourceValue[componentIndex] ?? 0); + } + return; + } + let sourceIndex = 0; + for (let columnIndex = 0; columnIndex < columns; columnIndex++) { + const columnOffset = offset + columnIndex * columnStride; + for (let rowIndex = 0; rowIndex < rows; rowIndex++) { + array[columnOffset + rowIndex] = Number(sourceValue[sourceIndex++] ?? 0); + } + } + } + }; + } + }); + + // node_modules/@luma.gl/core/dist/utils/array-equal.js + function arrayEqual(a, b, limit = 16) { + if (a === b) { + return true; + } + const arrayA = a; + const arrayB = b; + if (!isNumberArray2(arrayA) || !isNumberArray2(arrayB)) { + return false; + } + if (arrayA.length !== arrayB.length) { + return false; + } + const maxCompareLength = Math.min(limit, MAX_ELEMENTWISE_ARRAY_COMPARE_LENGTH); + if (arrayA.length > maxCompareLength) { + return false; + } + for (let i = 0; i < arrayA.length; ++i) { + if (arrayB[i] !== arrayA[i]) { + return false; + } + } + return true; + } + function arrayCopy(a) { + if (isNumberArray2(a)) { + return a.slice(); + } + return a; + } + var MAX_ELEMENTWISE_ARRAY_COMPARE_LENGTH; + var init_array_equal = __esm({ + "node_modules/@luma.gl/core/dist/utils/array-equal.js"() { + init_is_array(); + MAX_ELEMENTWISE_ARRAY_COMPARE_LENGTH = 128; + } + }); + + // node_modules/@luma.gl/core/dist/portable/uniform-block.js + var UniformBlock; + var init_uniform_block = __esm({ + "node_modules/@luma.gl/core/dist/portable/uniform-block.js"() { + init_array_equal(); + UniformBlock = class { + name; + uniforms = {}; + modifiedUniforms = {}; + modified = true; + bindingLayout = {}; + needsRedraw = "initialized"; + constructor(props) { + this.name = props?.name || "unnamed"; + if (props?.name && props?.shaderLayout) { + const binding = props?.shaderLayout.bindings?.find((binding_) => binding_.type === "uniform" && binding_.name === props?.name); + if (!binding) { + throw new Error(props?.name); + } + const uniformBlock11 = binding; + for (const uniform of uniformBlock11.uniforms || []) { + this.bindingLayout[uniform.name] = uniform; + } + } + } + /** Set a map of uniforms */ + setUniforms(uniforms) { + for (const [key, value] of Object.entries(uniforms)) { + this._setUniform(key, value); + if (!this.needsRedraw) { + this.setNeedsRedraw(`${this.name}.${key}=${value}`); + } + } + } + setNeedsRedraw(reason) { + this.needsRedraw = this.needsRedraw || reason; + } + /** Returns all uniforms */ + getAllUniforms() { + this.modifiedUniforms = {}; + this.needsRedraw = false; + return this.uniforms || {}; + } + /** Set a single uniform */ + _setUniform(key, value) { + if (arrayEqual(this.uniforms[key], value)) { + return; + } + this.uniforms[key] = arrayCopy(value); + this.modifiedUniforms[key] = true; + this.modified = true; + } + }; + } + }); + + // node_modules/@luma.gl/core/dist/portable/uniform-store.js + function getDefaultUniformBufferLayout(device) { + return device.type === "webgpu" ? "wgsl-uniform" : "std140"; + } + var minUniformBufferSize, UniformStore; + var init_uniform_store = __esm({ + "node_modules/@luma.gl/core/dist/portable/uniform-store.js"() { + init_buffer(); + init_log(); + init_shader_block_layout(); + init_uniform_block(); + init_shader_block_writer(); + minUniformBufferSize = 1024; + UniformStore = class { + /** Device used to infer layout and allocate buffers. */ + device; + /** Stores the uniform values for each uniform block */ + uniformBlocks = /* @__PURE__ */ new Map(); + /** Flattened layout metadata for each block. */ + shaderBlockLayouts = /* @__PURE__ */ new Map(); + /** Serializers for block-backed uniform data. */ + shaderBlockWriters = /* @__PURE__ */ new Map(); + /** Actual buffer for the blocks */ + uniformBuffers = /* @__PURE__ */ new Map(); + /** + * Creates a new {@link UniformStore} for the supplied device and block definitions. + */ + constructor(device, blocks) { + this.device = device; + for (const [bufferName, block] of Object.entries(blocks)) { + const uniformBufferName = bufferName; + const shaderBlockLayout = makeShaderBlockLayout(block.uniformTypes ?? {}, { + layout: block.layout ?? getDefaultUniformBufferLayout(device) + }); + const shaderBlockWriter = new ShaderBlockWriter(shaderBlockLayout); + this.shaderBlockLayouts.set(uniformBufferName, shaderBlockLayout); + this.shaderBlockWriters.set(uniformBufferName, shaderBlockWriter); + const uniformBlock11 = new UniformBlock({ name: bufferName }); + uniformBlock11.setUniforms(shaderBlockWriter.getFlatUniformValues(block.defaultUniforms || {})); + this.uniformBlocks.set(uniformBufferName, uniformBlock11); + } + } + /** Destroy any managed uniform buffers */ + destroy() { + for (const uniformBuffer of this.uniformBuffers.values()) { + uniformBuffer.destroy(); + } + } + /** + * Set uniforms + * + * Makes all group properties partial and eagerly propagates changes to any + * managed GPU buffers. + */ + setUniforms(uniforms) { + for (const [blockName, uniformValues] of Object.entries(uniforms)) { + const uniformBufferName = blockName; + const shaderBlockWriter = this.shaderBlockWriters.get(uniformBufferName); + const flattenedUniforms = shaderBlockWriter?.getFlatUniformValues(uniformValues || {}); + this.uniformBlocks.get(uniformBufferName)?.setUniforms(flattenedUniforms || {}); + } + this.updateUniformBuffers(); + } + /** + * Returns the allocation size for the named uniform buffer. + * + * This may exceed the packed layout size because minimum buffer-size policy is + * applied at the store layer. + */ + getUniformBufferByteLength(uniformBufferName) { + const packedByteLength = this.shaderBlockLayouts.get(uniformBufferName)?.byteLength || 0; + return Math.max(packedByteLength, minUniformBufferSize); + } + /** + * Returns packed binary data that can be uploaded to the named uniform buffer. + * + * The returned view length matches the packed block size and is not padded to + * the store's minimum allocation size. + */ + getUniformBufferData(uniformBufferName) { + const uniformValues = this.uniformBlocks.get(uniformBufferName)?.getAllUniforms() || {}; + const shaderBlockWriter = this.shaderBlockWriters.get(uniformBufferName); + return shaderBlockWriter?.getData(uniformValues) || new Uint8Array(0); + } + /** + * Creates an unmanaged uniform buffer initialized with the current or supplied values. + */ + createUniformBuffer(uniformBufferName, uniforms) { + if (uniforms) { + this.setUniforms(uniforms); + } + const byteLength = this.getUniformBufferByteLength(uniformBufferName); + const uniformBuffer = this.device.createBuffer({ + usage: Buffer2.UNIFORM | Buffer2.COPY_DST, + byteLength + }); + const uniformBufferData = this.getUniformBufferData(uniformBufferName); + uniformBuffer.write(uniformBufferData); + return uniformBuffer; + } + /** Returns the managed uniform buffer for the named block. */ + getManagedUniformBuffer(uniformBufferName) { + if (!this.uniformBuffers.get(uniformBufferName)) { + const byteLength = this.getUniformBufferByteLength(uniformBufferName); + const uniformBuffer = this.device.createBuffer({ + usage: Buffer2.UNIFORM | Buffer2.COPY_DST, + byteLength + }); + this.uniformBuffers.set(uniformBufferName, uniformBuffer); + } + return this.uniformBuffers.get(uniformBufferName); + } + /** + * Updates every managed uniform buffer whose source uniforms have changed. + * + * @returns The first redraw reason encountered, or `false` if nothing changed. + */ + updateUniformBuffers() { + let reason = false; + for (const uniformBufferName of this.uniformBlocks.keys()) { + const bufferReason = this.updateUniformBuffer(uniformBufferName); + reason ||= bufferReason; + } + if (reason) { + log2.log(3, `UniformStore.updateUniformBuffers(): ${reason}`)(); + } + return reason; + } + /** + * Updates one managed uniform buffer if its corresponding block is dirty. + * + * @returns The redraw reason for the update, or `false` if no write occurred. + */ + updateUniformBuffer(uniformBufferName) { + const uniformBlock11 = this.uniformBlocks.get(uniformBufferName); + let uniformBuffer = this.uniformBuffers.get(uniformBufferName); + let reason = false; + if (uniformBuffer && uniformBlock11?.needsRedraw) { + reason ||= uniformBlock11.needsRedraw; + const uniformBufferData = this.getUniformBufferData(uniformBufferName); + uniformBuffer = this.uniformBuffers.get(uniformBufferName); + uniformBuffer?.write(uniformBufferData); + const uniformValues = this.uniformBlocks.get(uniformBufferName)?.getAllUniforms(); + log2.log(4, `Writing to uniform buffer ${String(uniformBufferName)}`, uniformBufferData, uniformValues)(); + } + return reason; + } + }; + } + }); + + // node_modules/@luma.gl/core/dist/index.js + var init_dist4 = __esm({ + "node_modules/@luma.gl/core/dist/index.js"() { + init_luma(); + init_adapter(); + init_device(); + init_canvas_context(); + init_presentation_context(); + init_buffer(); + init_texture(); + init_texture_view(); + init_shader(); + init_sampler(); + init_framebuffer(); + init_render_pipeline(); + init_shared_render_pipeline(); + init_pipeline_factory(); + init_shader_factory(); + init_render_pass(); + init_command_encoder(); + init_command_buffer(); + init_vertex_array(); + init_transform_feedback(); + init_query_set(); + init_fence(); + init_uniform_store(); + init_data_type_decoder(); + init_decode_data_types(); + init_shader_type_decoder(); + init_vertex_format_decoder(); + init_texture_format_decoder(); + init_image_types(); + init_log(); + init_bind_groups(); + init_assert2(); + init_array_utils_flat(); + init_get_attribute_from_layouts(); + } + }); + + // node_modules/@luma.gl/webgl/dist/constants/webgl-constants.js + var GLEnum; + var init_webgl_constants = __esm({ + "node_modules/@luma.gl/webgl/dist/constants/webgl-constants.js"() { + (function(GLEnum2) { + GLEnum2[GLEnum2["DEPTH_BUFFER_BIT"] = 256] = "DEPTH_BUFFER_BIT"; + GLEnum2[GLEnum2["STENCIL_BUFFER_BIT"] = 1024] = "STENCIL_BUFFER_BIT"; + GLEnum2[GLEnum2["COLOR_BUFFER_BIT"] = 16384] = "COLOR_BUFFER_BIT"; + GLEnum2[GLEnum2["POINTS"] = 0] = "POINTS"; + GLEnum2[GLEnum2["LINES"] = 1] = "LINES"; + GLEnum2[GLEnum2["LINE_LOOP"] = 2] = "LINE_LOOP"; + GLEnum2[GLEnum2["LINE_STRIP"] = 3] = "LINE_STRIP"; + GLEnum2[GLEnum2["TRIANGLES"] = 4] = "TRIANGLES"; + GLEnum2[GLEnum2["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP"; + GLEnum2[GLEnum2["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN"; + GLEnum2[GLEnum2["ZERO"] = 0] = "ZERO"; + GLEnum2[GLEnum2["ONE"] = 1] = "ONE"; + GLEnum2[GLEnum2["SRC_COLOR"] = 768] = "SRC_COLOR"; + GLEnum2[GLEnum2["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR"; + GLEnum2[GLEnum2["SRC_ALPHA"] = 770] = "SRC_ALPHA"; + GLEnum2[GLEnum2["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA"; + GLEnum2[GLEnum2["DST_ALPHA"] = 772] = "DST_ALPHA"; + GLEnum2[GLEnum2["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA"; + GLEnum2[GLEnum2["DST_COLOR"] = 774] = "DST_COLOR"; + GLEnum2[GLEnum2["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR"; + GLEnum2[GLEnum2["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE"; + GLEnum2[GLEnum2["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR"; + GLEnum2[GLEnum2["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR"; + GLEnum2[GLEnum2["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA"; + GLEnum2[GLEnum2["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA"; + GLEnum2[GLEnum2["FUNC_ADD"] = 32774] = "FUNC_ADD"; + GLEnum2[GLEnum2["FUNC_SUBTRACT"] = 32778] = "FUNC_SUBTRACT"; + GLEnum2[GLEnum2["FUNC_REVERSE_SUBTRACT"] = 32779] = "FUNC_REVERSE_SUBTRACT"; + GLEnum2[GLEnum2["BLEND_EQUATION"] = 32777] = "BLEND_EQUATION"; + GLEnum2[GLEnum2["BLEND_EQUATION_RGB"] = 32777] = "BLEND_EQUATION_RGB"; + GLEnum2[GLEnum2["BLEND_EQUATION_ALPHA"] = 34877] = "BLEND_EQUATION_ALPHA"; + GLEnum2[GLEnum2["BLEND_DST_RGB"] = 32968] = "BLEND_DST_RGB"; + GLEnum2[GLEnum2["BLEND_SRC_RGB"] = 32969] = "BLEND_SRC_RGB"; + GLEnum2[GLEnum2["BLEND_DST_ALPHA"] = 32970] = "BLEND_DST_ALPHA"; + GLEnum2[GLEnum2["BLEND_SRC_ALPHA"] = 32971] = "BLEND_SRC_ALPHA"; + GLEnum2[GLEnum2["BLEND_COLOR"] = 32773] = "BLEND_COLOR"; + GLEnum2[GLEnum2["ARRAY_BUFFER_BINDING"] = 34964] = "ARRAY_BUFFER_BINDING"; + GLEnum2[GLEnum2["ELEMENT_ARRAY_BUFFER_BINDING"] = 34965] = "ELEMENT_ARRAY_BUFFER_BINDING"; + GLEnum2[GLEnum2["LINE_WIDTH"] = 2849] = "LINE_WIDTH"; + GLEnum2[GLEnum2["ALIASED_POINT_SIZE_RANGE"] = 33901] = "ALIASED_POINT_SIZE_RANGE"; + GLEnum2[GLEnum2["ALIASED_LINE_WIDTH_RANGE"] = 33902] = "ALIASED_LINE_WIDTH_RANGE"; + GLEnum2[GLEnum2["CULL_FACE_MODE"] = 2885] = "CULL_FACE_MODE"; + GLEnum2[GLEnum2["FRONT_FACE"] = 2886] = "FRONT_FACE"; + GLEnum2[GLEnum2["DEPTH_RANGE"] = 2928] = "DEPTH_RANGE"; + GLEnum2[GLEnum2["DEPTH_WRITEMASK"] = 2930] = "DEPTH_WRITEMASK"; + GLEnum2[GLEnum2["DEPTH_CLEAR_VALUE"] = 2931] = "DEPTH_CLEAR_VALUE"; + GLEnum2[GLEnum2["DEPTH_FUNC"] = 2932] = "DEPTH_FUNC"; + GLEnum2[GLEnum2["STENCIL_CLEAR_VALUE"] = 2961] = "STENCIL_CLEAR_VALUE"; + GLEnum2[GLEnum2["STENCIL_FUNC"] = 2962] = "STENCIL_FUNC"; + GLEnum2[GLEnum2["STENCIL_FAIL"] = 2964] = "STENCIL_FAIL"; + GLEnum2[GLEnum2["STENCIL_PASS_DEPTH_FAIL"] = 2965] = "STENCIL_PASS_DEPTH_FAIL"; + GLEnum2[GLEnum2["STENCIL_PASS_DEPTH_PASS"] = 2966] = "STENCIL_PASS_DEPTH_PASS"; + GLEnum2[GLEnum2["STENCIL_REF"] = 2967] = "STENCIL_REF"; + GLEnum2[GLEnum2["STENCIL_VALUE_MASK"] = 2963] = "STENCIL_VALUE_MASK"; + GLEnum2[GLEnum2["STENCIL_WRITEMASK"] = 2968] = "STENCIL_WRITEMASK"; + GLEnum2[GLEnum2["STENCIL_BACK_FUNC"] = 34816] = "STENCIL_BACK_FUNC"; + GLEnum2[GLEnum2["STENCIL_BACK_FAIL"] = 34817] = "STENCIL_BACK_FAIL"; + GLEnum2[GLEnum2["STENCIL_BACK_PASS_DEPTH_FAIL"] = 34818] = "STENCIL_BACK_PASS_DEPTH_FAIL"; + GLEnum2[GLEnum2["STENCIL_BACK_PASS_DEPTH_PASS"] = 34819] = "STENCIL_BACK_PASS_DEPTH_PASS"; + GLEnum2[GLEnum2["STENCIL_BACK_REF"] = 36003] = "STENCIL_BACK_REF"; + GLEnum2[GLEnum2["STENCIL_BACK_VALUE_MASK"] = 36004] = "STENCIL_BACK_VALUE_MASK"; + GLEnum2[GLEnum2["STENCIL_BACK_WRITEMASK"] = 36005] = "STENCIL_BACK_WRITEMASK"; + GLEnum2[GLEnum2["VIEWPORT"] = 2978] = "VIEWPORT"; + GLEnum2[GLEnum2["SCISSOR_BOX"] = 3088] = "SCISSOR_BOX"; + GLEnum2[GLEnum2["COLOR_CLEAR_VALUE"] = 3106] = "COLOR_CLEAR_VALUE"; + GLEnum2[GLEnum2["COLOR_WRITEMASK"] = 3107] = "COLOR_WRITEMASK"; + GLEnum2[GLEnum2["UNPACK_ALIGNMENT"] = 3317] = "UNPACK_ALIGNMENT"; + GLEnum2[GLEnum2["PACK_ALIGNMENT"] = 3333] = "PACK_ALIGNMENT"; + GLEnum2[GLEnum2["MAX_TEXTURE_SIZE"] = 3379] = "MAX_TEXTURE_SIZE"; + GLEnum2[GLEnum2["MAX_VIEWPORT_DIMS"] = 3386] = "MAX_VIEWPORT_DIMS"; + GLEnum2[GLEnum2["SUBPIXEL_BITS"] = 3408] = "SUBPIXEL_BITS"; + GLEnum2[GLEnum2["RED_BITS"] = 3410] = "RED_BITS"; + GLEnum2[GLEnum2["GREEN_BITS"] = 3411] = "GREEN_BITS"; + GLEnum2[GLEnum2["BLUE_BITS"] = 3412] = "BLUE_BITS"; + GLEnum2[GLEnum2["ALPHA_BITS"] = 3413] = "ALPHA_BITS"; + GLEnum2[GLEnum2["DEPTH_BITS"] = 3414] = "DEPTH_BITS"; + GLEnum2[GLEnum2["STENCIL_BITS"] = 3415] = "STENCIL_BITS"; + GLEnum2[GLEnum2["POLYGON_OFFSET_UNITS"] = 10752] = "POLYGON_OFFSET_UNITS"; + GLEnum2[GLEnum2["POLYGON_OFFSET_FACTOR"] = 32824] = "POLYGON_OFFSET_FACTOR"; + GLEnum2[GLEnum2["TEXTURE_BINDING_2D"] = 32873] = "TEXTURE_BINDING_2D"; + GLEnum2[GLEnum2["SAMPLE_BUFFERS"] = 32936] = "SAMPLE_BUFFERS"; + GLEnum2[GLEnum2["SAMPLES"] = 32937] = "SAMPLES"; + GLEnum2[GLEnum2["SAMPLE_COVERAGE_VALUE"] = 32938] = "SAMPLE_COVERAGE_VALUE"; + GLEnum2[GLEnum2["SAMPLE_COVERAGE_INVERT"] = 32939] = "SAMPLE_COVERAGE_INVERT"; + GLEnum2[GLEnum2["COMPRESSED_TEXTURE_FORMATS"] = 34467] = "COMPRESSED_TEXTURE_FORMATS"; + GLEnum2[GLEnum2["VENDOR"] = 7936] = "VENDOR"; + GLEnum2[GLEnum2["RENDERER"] = 7937] = "RENDERER"; + GLEnum2[GLEnum2["VERSION"] = 7938] = "VERSION"; + GLEnum2[GLEnum2["IMPLEMENTATION_COLOR_READ_TYPE"] = 35738] = "IMPLEMENTATION_COLOR_READ_TYPE"; + GLEnum2[GLEnum2["IMPLEMENTATION_COLOR_READ_FORMAT"] = 35739] = "IMPLEMENTATION_COLOR_READ_FORMAT"; + GLEnum2[GLEnum2["BROWSER_DEFAULT_WEBGL"] = 37444] = "BROWSER_DEFAULT_WEBGL"; + GLEnum2[GLEnum2["STATIC_DRAW"] = 35044] = "STATIC_DRAW"; + GLEnum2[GLEnum2["STREAM_DRAW"] = 35040] = "STREAM_DRAW"; + GLEnum2[GLEnum2["DYNAMIC_DRAW"] = 35048] = "DYNAMIC_DRAW"; + GLEnum2[GLEnum2["ARRAY_BUFFER"] = 34962] = "ARRAY_BUFFER"; + GLEnum2[GLEnum2["ELEMENT_ARRAY_BUFFER"] = 34963] = "ELEMENT_ARRAY_BUFFER"; + GLEnum2[GLEnum2["BUFFER_SIZE"] = 34660] = "BUFFER_SIZE"; + GLEnum2[GLEnum2["BUFFER_USAGE"] = 34661] = "BUFFER_USAGE"; + GLEnum2[GLEnum2["CURRENT_VERTEX_ATTRIB"] = 34342] = "CURRENT_VERTEX_ATTRIB"; + GLEnum2[GLEnum2["VERTEX_ATTRIB_ARRAY_ENABLED"] = 34338] = "VERTEX_ATTRIB_ARRAY_ENABLED"; + GLEnum2[GLEnum2["VERTEX_ATTRIB_ARRAY_SIZE"] = 34339] = "VERTEX_ATTRIB_ARRAY_SIZE"; + GLEnum2[GLEnum2["VERTEX_ATTRIB_ARRAY_STRIDE"] = 34340] = "VERTEX_ATTRIB_ARRAY_STRIDE"; + GLEnum2[GLEnum2["VERTEX_ATTRIB_ARRAY_TYPE"] = 34341] = "VERTEX_ATTRIB_ARRAY_TYPE"; + GLEnum2[GLEnum2["VERTEX_ATTRIB_ARRAY_NORMALIZED"] = 34922] = "VERTEX_ATTRIB_ARRAY_NORMALIZED"; + GLEnum2[GLEnum2["VERTEX_ATTRIB_ARRAY_POINTER"] = 34373] = "VERTEX_ATTRIB_ARRAY_POINTER"; + GLEnum2[GLEnum2["VERTEX_ATTRIB_ARRAY_BUFFER_BINDING"] = 34975] = "VERTEX_ATTRIB_ARRAY_BUFFER_BINDING"; + GLEnum2[GLEnum2["CULL_FACE"] = 2884] = "CULL_FACE"; + GLEnum2[GLEnum2["FRONT"] = 1028] = "FRONT"; + GLEnum2[GLEnum2["BACK"] = 1029] = "BACK"; + GLEnum2[GLEnum2["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK"; + GLEnum2[GLEnum2["BLEND"] = 3042] = "BLEND"; + GLEnum2[GLEnum2["DEPTH_TEST"] = 2929] = "DEPTH_TEST"; + GLEnum2[GLEnum2["DITHER"] = 3024] = "DITHER"; + GLEnum2[GLEnum2["POLYGON_OFFSET_FILL"] = 32823] = "POLYGON_OFFSET_FILL"; + GLEnum2[GLEnum2["SAMPLE_ALPHA_TO_COVERAGE"] = 32926] = "SAMPLE_ALPHA_TO_COVERAGE"; + GLEnum2[GLEnum2["SAMPLE_COVERAGE"] = 32928] = "SAMPLE_COVERAGE"; + GLEnum2[GLEnum2["SCISSOR_TEST"] = 3089] = "SCISSOR_TEST"; + GLEnum2[GLEnum2["STENCIL_TEST"] = 2960] = "STENCIL_TEST"; + GLEnum2[GLEnum2["NO_ERROR"] = 0] = "NO_ERROR"; + GLEnum2[GLEnum2["INVALID_ENUM"] = 1280] = "INVALID_ENUM"; + GLEnum2[GLEnum2["INVALID_VALUE"] = 1281] = "INVALID_VALUE"; + GLEnum2[GLEnum2["INVALID_OPERATION"] = 1282] = "INVALID_OPERATION"; + GLEnum2[GLEnum2["OUT_OF_MEMORY"] = 1285] = "OUT_OF_MEMORY"; + GLEnum2[GLEnum2["CONTEXT_LOST_WEBGL"] = 37442] = "CONTEXT_LOST_WEBGL"; + GLEnum2[GLEnum2["CW"] = 2304] = "CW"; + GLEnum2[GLEnum2["CCW"] = 2305] = "CCW"; + GLEnum2[GLEnum2["DONT_CARE"] = 4352] = "DONT_CARE"; + GLEnum2[GLEnum2["FASTEST"] = 4353] = "FASTEST"; + GLEnum2[GLEnum2["NICEST"] = 4354] = "NICEST"; + GLEnum2[GLEnum2["GENERATE_MIPMAP_HINT"] = 33170] = "GENERATE_MIPMAP_HINT"; + GLEnum2[GLEnum2["BYTE"] = 5120] = "BYTE"; + GLEnum2[GLEnum2["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE"; + GLEnum2[GLEnum2["SHORT"] = 5122] = "SHORT"; + GLEnum2[GLEnum2["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT"; + GLEnum2[GLEnum2["INT"] = 5124] = "INT"; + GLEnum2[GLEnum2["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT"; + GLEnum2[GLEnum2["FLOAT"] = 5126] = "FLOAT"; + GLEnum2[GLEnum2["DOUBLE"] = 5130] = "DOUBLE"; + GLEnum2[GLEnum2["DEPTH_COMPONENT"] = 6402] = "DEPTH_COMPONENT"; + GLEnum2[GLEnum2["ALPHA"] = 6406] = "ALPHA"; + GLEnum2[GLEnum2["RGB"] = 6407] = "RGB"; + GLEnum2[GLEnum2["RGBA"] = 6408] = "RGBA"; + GLEnum2[GLEnum2["LUMINANCE"] = 6409] = "LUMINANCE"; + GLEnum2[GLEnum2["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA"; + GLEnum2[GLEnum2["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4"; + GLEnum2[GLEnum2["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1"; + GLEnum2[GLEnum2["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5"; + GLEnum2[GLEnum2["FRAGMENT_SHADER"] = 35632] = "FRAGMENT_SHADER"; + GLEnum2[GLEnum2["VERTEX_SHADER"] = 35633] = "VERTEX_SHADER"; + GLEnum2[GLEnum2["COMPILE_STATUS"] = 35713] = "COMPILE_STATUS"; + GLEnum2[GLEnum2["DELETE_STATUS"] = 35712] = "DELETE_STATUS"; + GLEnum2[GLEnum2["LINK_STATUS"] = 35714] = "LINK_STATUS"; + GLEnum2[GLEnum2["VALIDATE_STATUS"] = 35715] = "VALIDATE_STATUS"; + GLEnum2[GLEnum2["ATTACHED_SHADERS"] = 35717] = "ATTACHED_SHADERS"; + GLEnum2[GLEnum2["ACTIVE_ATTRIBUTES"] = 35721] = "ACTIVE_ATTRIBUTES"; + GLEnum2[GLEnum2["ACTIVE_UNIFORMS"] = 35718] = "ACTIVE_UNIFORMS"; + GLEnum2[GLEnum2["MAX_VERTEX_ATTRIBS"] = 34921] = "MAX_VERTEX_ATTRIBS"; + GLEnum2[GLEnum2["MAX_VERTEX_UNIFORM_VECTORS"] = 36347] = "MAX_VERTEX_UNIFORM_VECTORS"; + GLEnum2[GLEnum2["MAX_VARYING_VECTORS"] = 36348] = "MAX_VARYING_VECTORS"; + GLEnum2[GLEnum2["MAX_COMBINED_TEXTURE_IMAGE_UNITS"] = 35661] = "MAX_COMBINED_TEXTURE_IMAGE_UNITS"; + GLEnum2[GLEnum2["MAX_VERTEX_TEXTURE_IMAGE_UNITS"] = 35660] = "MAX_VERTEX_TEXTURE_IMAGE_UNITS"; + GLEnum2[GLEnum2["MAX_TEXTURE_IMAGE_UNITS"] = 34930] = "MAX_TEXTURE_IMAGE_UNITS"; + GLEnum2[GLEnum2["MAX_FRAGMENT_UNIFORM_VECTORS"] = 36349] = "MAX_FRAGMENT_UNIFORM_VECTORS"; + GLEnum2[GLEnum2["SHADER_TYPE"] = 35663] = "SHADER_TYPE"; + GLEnum2[GLEnum2["SHADING_LANGUAGE_VERSION"] = 35724] = "SHADING_LANGUAGE_VERSION"; + GLEnum2[GLEnum2["CURRENT_PROGRAM"] = 35725] = "CURRENT_PROGRAM"; + GLEnum2[GLEnum2["NEVER"] = 512] = "NEVER"; + GLEnum2[GLEnum2["LESS"] = 513] = "LESS"; + GLEnum2[GLEnum2["EQUAL"] = 514] = "EQUAL"; + GLEnum2[GLEnum2["LEQUAL"] = 515] = "LEQUAL"; + GLEnum2[GLEnum2["GREATER"] = 516] = "GREATER"; + GLEnum2[GLEnum2["NOTEQUAL"] = 517] = "NOTEQUAL"; + GLEnum2[GLEnum2["GEQUAL"] = 518] = "GEQUAL"; + GLEnum2[GLEnum2["ALWAYS"] = 519] = "ALWAYS"; + GLEnum2[GLEnum2["KEEP"] = 7680] = "KEEP"; + GLEnum2[GLEnum2["REPLACE"] = 7681] = "REPLACE"; + GLEnum2[GLEnum2["INCR"] = 7682] = "INCR"; + GLEnum2[GLEnum2["DECR"] = 7683] = "DECR"; + GLEnum2[GLEnum2["INVERT"] = 5386] = "INVERT"; + GLEnum2[GLEnum2["INCR_WRAP"] = 34055] = "INCR_WRAP"; + GLEnum2[GLEnum2["DECR_WRAP"] = 34056] = "DECR_WRAP"; + GLEnum2[GLEnum2["NEAREST"] = 9728] = "NEAREST"; + GLEnum2[GLEnum2["LINEAR"] = 9729] = "LINEAR"; + GLEnum2[GLEnum2["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST"; + GLEnum2[GLEnum2["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST"; + GLEnum2[GLEnum2["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR"; + GLEnum2[GLEnum2["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR"; + GLEnum2[GLEnum2["TEXTURE_MAG_FILTER"] = 10240] = "TEXTURE_MAG_FILTER"; + GLEnum2[GLEnum2["TEXTURE_MIN_FILTER"] = 10241] = "TEXTURE_MIN_FILTER"; + GLEnum2[GLEnum2["TEXTURE_WRAP_S"] = 10242] = "TEXTURE_WRAP_S"; + GLEnum2[GLEnum2["TEXTURE_WRAP_T"] = 10243] = "TEXTURE_WRAP_T"; + GLEnum2[GLEnum2["TEXTURE_2D"] = 3553] = "TEXTURE_2D"; + GLEnum2[GLEnum2["TEXTURE"] = 5890] = "TEXTURE"; + GLEnum2[GLEnum2["TEXTURE_CUBE_MAP"] = 34067] = "TEXTURE_CUBE_MAP"; + GLEnum2[GLEnum2["TEXTURE_BINDING_CUBE_MAP"] = 34068] = "TEXTURE_BINDING_CUBE_MAP"; + GLEnum2[GLEnum2["TEXTURE_CUBE_MAP_POSITIVE_X"] = 34069] = "TEXTURE_CUBE_MAP_POSITIVE_X"; + GLEnum2[GLEnum2["TEXTURE_CUBE_MAP_NEGATIVE_X"] = 34070] = "TEXTURE_CUBE_MAP_NEGATIVE_X"; + GLEnum2[GLEnum2["TEXTURE_CUBE_MAP_POSITIVE_Y"] = 34071] = "TEXTURE_CUBE_MAP_POSITIVE_Y"; + GLEnum2[GLEnum2["TEXTURE_CUBE_MAP_NEGATIVE_Y"] = 34072] = "TEXTURE_CUBE_MAP_NEGATIVE_Y"; + GLEnum2[GLEnum2["TEXTURE_CUBE_MAP_POSITIVE_Z"] = 34073] = "TEXTURE_CUBE_MAP_POSITIVE_Z"; + GLEnum2[GLEnum2["TEXTURE_CUBE_MAP_NEGATIVE_Z"] = 34074] = "TEXTURE_CUBE_MAP_NEGATIVE_Z"; + GLEnum2[GLEnum2["MAX_CUBE_MAP_TEXTURE_SIZE"] = 34076] = "MAX_CUBE_MAP_TEXTURE_SIZE"; + GLEnum2[GLEnum2["TEXTURE0"] = 33984] = "TEXTURE0"; + GLEnum2[GLEnum2["ACTIVE_TEXTURE"] = 34016] = "ACTIVE_TEXTURE"; + GLEnum2[GLEnum2["REPEAT"] = 10497] = "REPEAT"; + GLEnum2[GLEnum2["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE"; + GLEnum2[GLEnum2["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT"; + GLEnum2[GLEnum2["TEXTURE_WIDTH"] = 4096] = "TEXTURE_WIDTH"; + GLEnum2[GLEnum2["TEXTURE_HEIGHT"] = 4097] = "TEXTURE_HEIGHT"; + GLEnum2[GLEnum2["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2"; + GLEnum2[GLEnum2["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3"; + GLEnum2[GLEnum2["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4"; + GLEnum2[GLEnum2["INT_VEC2"] = 35667] = "INT_VEC2"; + GLEnum2[GLEnum2["INT_VEC3"] = 35668] = "INT_VEC3"; + GLEnum2[GLEnum2["INT_VEC4"] = 35669] = "INT_VEC4"; + GLEnum2[GLEnum2["BOOL"] = 35670] = "BOOL"; + GLEnum2[GLEnum2["BOOL_VEC2"] = 35671] = "BOOL_VEC2"; + GLEnum2[GLEnum2["BOOL_VEC3"] = 35672] = "BOOL_VEC3"; + GLEnum2[GLEnum2["BOOL_VEC4"] = 35673] = "BOOL_VEC4"; + GLEnum2[GLEnum2["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2"; + GLEnum2[GLEnum2["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3"; + GLEnum2[GLEnum2["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4"; + GLEnum2[GLEnum2["SAMPLER_2D"] = 35678] = "SAMPLER_2D"; + GLEnum2[GLEnum2["SAMPLER_CUBE"] = 35680] = "SAMPLER_CUBE"; + GLEnum2[GLEnum2["LOW_FLOAT"] = 36336] = "LOW_FLOAT"; + GLEnum2[GLEnum2["MEDIUM_FLOAT"] = 36337] = "MEDIUM_FLOAT"; + GLEnum2[GLEnum2["HIGH_FLOAT"] = 36338] = "HIGH_FLOAT"; + GLEnum2[GLEnum2["LOW_INT"] = 36339] = "LOW_INT"; + GLEnum2[GLEnum2["MEDIUM_INT"] = 36340] = "MEDIUM_INT"; + GLEnum2[GLEnum2["HIGH_INT"] = 36341] = "HIGH_INT"; + GLEnum2[GLEnum2["FRAMEBUFFER"] = 36160] = "FRAMEBUFFER"; + GLEnum2[GLEnum2["RENDERBUFFER"] = 36161] = "RENDERBUFFER"; + GLEnum2[GLEnum2["RGBA4"] = 32854] = "RGBA4"; + GLEnum2[GLEnum2["RGB5_A1"] = 32855] = "RGB5_A1"; + GLEnum2[GLEnum2["RGB565"] = 36194] = "RGB565"; + GLEnum2[GLEnum2["DEPTH_COMPONENT16"] = 33189] = "DEPTH_COMPONENT16"; + GLEnum2[GLEnum2["STENCIL_INDEX"] = 6401] = "STENCIL_INDEX"; + GLEnum2[GLEnum2["STENCIL_INDEX8"] = 36168] = "STENCIL_INDEX8"; + GLEnum2[GLEnum2["DEPTH_STENCIL"] = 34041] = "DEPTH_STENCIL"; + GLEnum2[GLEnum2["RENDERBUFFER_WIDTH"] = 36162] = "RENDERBUFFER_WIDTH"; + GLEnum2[GLEnum2["RENDERBUFFER_HEIGHT"] = 36163] = "RENDERBUFFER_HEIGHT"; + GLEnum2[GLEnum2["RENDERBUFFER_INTERNAL_FORMAT"] = 36164] = "RENDERBUFFER_INTERNAL_FORMAT"; + GLEnum2[GLEnum2["RENDERBUFFER_RED_SIZE"] = 36176] = "RENDERBUFFER_RED_SIZE"; + GLEnum2[GLEnum2["RENDERBUFFER_GREEN_SIZE"] = 36177] = "RENDERBUFFER_GREEN_SIZE"; + GLEnum2[GLEnum2["RENDERBUFFER_BLUE_SIZE"] = 36178] = "RENDERBUFFER_BLUE_SIZE"; + GLEnum2[GLEnum2["RENDERBUFFER_ALPHA_SIZE"] = 36179] = "RENDERBUFFER_ALPHA_SIZE"; + GLEnum2[GLEnum2["RENDERBUFFER_DEPTH_SIZE"] = 36180] = "RENDERBUFFER_DEPTH_SIZE"; + GLEnum2[GLEnum2["RENDERBUFFER_STENCIL_SIZE"] = 36181] = "RENDERBUFFER_STENCIL_SIZE"; + GLEnum2[GLEnum2["FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE"] = 36048] = "FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE"; + GLEnum2[GLEnum2["FRAMEBUFFER_ATTACHMENT_OBJECT_NAME"] = 36049] = "FRAMEBUFFER_ATTACHMENT_OBJECT_NAME"; + GLEnum2[GLEnum2["FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL"] = 36050] = "FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL"; + GLEnum2[GLEnum2["FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE"] = 36051] = "FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE"; + GLEnum2[GLEnum2["COLOR_ATTACHMENT0"] = 36064] = "COLOR_ATTACHMENT0"; + GLEnum2[GLEnum2["DEPTH_ATTACHMENT"] = 36096] = "DEPTH_ATTACHMENT"; + GLEnum2[GLEnum2["STENCIL_ATTACHMENT"] = 36128] = "STENCIL_ATTACHMENT"; + GLEnum2[GLEnum2["DEPTH_STENCIL_ATTACHMENT"] = 33306] = "DEPTH_STENCIL_ATTACHMENT"; + GLEnum2[GLEnum2["NONE"] = 0] = "NONE"; + GLEnum2[GLEnum2["FRAMEBUFFER_COMPLETE"] = 36053] = "FRAMEBUFFER_COMPLETE"; + GLEnum2[GLEnum2["FRAMEBUFFER_INCOMPLETE_ATTACHMENT"] = 36054] = "FRAMEBUFFER_INCOMPLETE_ATTACHMENT"; + GLEnum2[GLEnum2["FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"] = 36055] = "FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"; + GLEnum2[GLEnum2["FRAMEBUFFER_INCOMPLETE_DIMENSIONS"] = 36057] = "FRAMEBUFFER_INCOMPLETE_DIMENSIONS"; + GLEnum2[GLEnum2["FRAMEBUFFER_UNSUPPORTED"] = 36061] = "FRAMEBUFFER_UNSUPPORTED"; + GLEnum2[GLEnum2["FRAMEBUFFER_BINDING"] = 36006] = "FRAMEBUFFER_BINDING"; + GLEnum2[GLEnum2["RENDERBUFFER_BINDING"] = 36007] = "RENDERBUFFER_BINDING"; + GLEnum2[GLEnum2["READ_FRAMEBUFFER"] = 36008] = "READ_FRAMEBUFFER"; + GLEnum2[GLEnum2["DRAW_FRAMEBUFFER"] = 36009] = "DRAW_FRAMEBUFFER"; + GLEnum2[GLEnum2["MAX_RENDERBUFFER_SIZE"] = 34024] = "MAX_RENDERBUFFER_SIZE"; + GLEnum2[GLEnum2["INVALID_FRAMEBUFFER_OPERATION"] = 1286] = "INVALID_FRAMEBUFFER_OPERATION"; + GLEnum2[GLEnum2["UNPACK_FLIP_Y_WEBGL"] = 37440] = "UNPACK_FLIP_Y_WEBGL"; + GLEnum2[GLEnum2["UNPACK_PREMULTIPLY_ALPHA_WEBGL"] = 37441] = "UNPACK_PREMULTIPLY_ALPHA_WEBGL"; + GLEnum2[GLEnum2["UNPACK_COLORSPACE_CONVERSION_WEBGL"] = 37443] = "UNPACK_COLORSPACE_CONVERSION_WEBGL"; + GLEnum2[GLEnum2["READ_BUFFER"] = 3074] = "READ_BUFFER"; + GLEnum2[GLEnum2["UNPACK_ROW_LENGTH"] = 3314] = "UNPACK_ROW_LENGTH"; + GLEnum2[GLEnum2["UNPACK_SKIP_ROWS"] = 3315] = "UNPACK_SKIP_ROWS"; + GLEnum2[GLEnum2["UNPACK_SKIP_PIXELS"] = 3316] = "UNPACK_SKIP_PIXELS"; + GLEnum2[GLEnum2["PACK_ROW_LENGTH"] = 3330] = "PACK_ROW_LENGTH"; + GLEnum2[GLEnum2["PACK_SKIP_ROWS"] = 3331] = "PACK_SKIP_ROWS"; + GLEnum2[GLEnum2["PACK_SKIP_PIXELS"] = 3332] = "PACK_SKIP_PIXELS"; + GLEnum2[GLEnum2["TEXTURE_BINDING_3D"] = 32874] = "TEXTURE_BINDING_3D"; + GLEnum2[GLEnum2["UNPACK_SKIP_IMAGES"] = 32877] = "UNPACK_SKIP_IMAGES"; + GLEnum2[GLEnum2["UNPACK_IMAGE_HEIGHT"] = 32878] = "UNPACK_IMAGE_HEIGHT"; + GLEnum2[GLEnum2["MAX_3D_TEXTURE_SIZE"] = 32883] = "MAX_3D_TEXTURE_SIZE"; + GLEnum2[GLEnum2["MAX_ELEMENTS_VERTICES"] = 33e3] = "MAX_ELEMENTS_VERTICES"; + GLEnum2[GLEnum2["MAX_ELEMENTS_INDICES"] = 33001] = "MAX_ELEMENTS_INDICES"; + GLEnum2[GLEnum2["MAX_TEXTURE_LOD_BIAS"] = 34045] = "MAX_TEXTURE_LOD_BIAS"; + GLEnum2[GLEnum2["MAX_FRAGMENT_UNIFORM_COMPONENTS"] = 35657] = "MAX_FRAGMENT_UNIFORM_COMPONENTS"; + GLEnum2[GLEnum2["MAX_VERTEX_UNIFORM_COMPONENTS"] = 35658] = "MAX_VERTEX_UNIFORM_COMPONENTS"; + GLEnum2[GLEnum2["MAX_ARRAY_TEXTURE_LAYERS"] = 35071] = "MAX_ARRAY_TEXTURE_LAYERS"; + GLEnum2[GLEnum2["MIN_PROGRAM_TEXEL_OFFSET"] = 35076] = "MIN_PROGRAM_TEXEL_OFFSET"; + GLEnum2[GLEnum2["MAX_PROGRAM_TEXEL_OFFSET"] = 35077] = "MAX_PROGRAM_TEXEL_OFFSET"; + GLEnum2[GLEnum2["MAX_VARYING_COMPONENTS"] = 35659] = "MAX_VARYING_COMPONENTS"; + GLEnum2[GLEnum2["FRAGMENT_SHADER_DERIVATIVE_HINT"] = 35723] = "FRAGMENT_SHADER_DERIVATIVE_HINT"; + GLEnum2[GLEnum2["RASTERIZER_DISCARD"] = 35977] = "RASTERIZER_DISCARD"; + GLEnum2[GLEnum2["VERTEX_ARRAY_BINDING"] = 34229] = "VERTEX_ARRAY_BINDING"; + GLEnum2[GLEnum2["MAX_VERTEX_OUTPUT_COMPONENTS"] = 37154] = "MAX_VERTEX_OUTPUT_COMPONENTS"; + GLEnum2[GLEnum2["MAX_FRAGMENT_INPUT_COMPONENTS"] = 37157] = "MAX_FRAGMENT_INPUT_COMPONENTS"; + GLEnum2[GLEnum2["MAX_SERVER_WAIT_TIMEOUT"] = 37137] = "MAX_SERVER_WAIT_TIMEOUT"; + GLEnum2[GLEnum2["MAX_ELEMENT_INDEX"] = 36203] = "MAX_ELEMENT_INDEX"; + GLEnum2[GLEnum2["RED"] = 6403] = "RED"; + GLEnum2[GLEnum2["RGB8"] = 32849] = "RGB8"; + GLEnum2[GLEnum2["RGBA8"] = 32856] = "RGBA8"; + GLEnum2[GLEnum2["RGB10_A2"] = 32857] = "RGB10_A2"; + GLEnum2[GLEnum2["TEXTURE_3D"] = 32879] = "TEXTURE_3D"; + GLEnum2[GLEnum2["TEXTURE_WRAP_R"] = 32882] = "TEXTURE_WRAP_R"; + GLEnum2[GLEnum2["TEXTURE_MIN_LOD"] = 33082] = "TEXTURE_MIN_LOD"; + GLEnum2[GLEnum2["TEXTURE_MAX_LOD"] = 33083] = "TEXTURE_MAX_LOD"; + GLEnum2[GLEnum2["TEXTURE_BASE_LEVEL"] = 33084] = "TEXTURE_BASE_LEVEL"; + GLEnum2[GLEnum2["TEXTURE_MAX_LEVEL"] = 33085] = "TEXTURE_MAX_LEVEL"; + GLEnum2[GLEnum2["TEXTURE_COMPARE_MODE"] = 34892] = "TEXTURE_COMPARE_MODE"; + GLEnum2[GLEnum2["TEXTURE_COMPARE_FUNC"] = 34893] = "TEXTURE_COMPARE_FUNC"; + GLEnum2[GLEnum2["SRGB"] = 35904] = "SRGB"; + GLEnum2[GLEnum2["SRGB8"] = 35905] = "SRGB8"; + GLEnum2[GLEnum2["SRGB8_ALPHA8"] = 35907] = "SRGB8_ALPHA8"; + GLEnum2[GLEnum2["COMPARE_REF_TO_TEXTURE"] = 34894] = "COMPARE_REF_TO_TEXTURE"; + GLEnum2[GLEnum2["RGBA32F"] = 34836] = "RGBA32F"; + GLEnum2[GLEnum2["RGB32F"] = 34837] = "RGB32F"; + GLEnum2[GLEnum2["RGBA16F"] = 34842] = "RGBA16F"; + GLEnum2[GLEnum2["RGB16F"] = 34843] = "RGB16F"; + GLEnum2[GLEnum2["TEXTURE_2D_ARRAY"] = 35866] = "TEXTURE_2D_ARRAY"; + GLEnum2[GLEnum2["TEXTURE_BINDING_2D_ARRAY"] = 35869] = "TEXTURE_BINDING_2D_ARRAY"; + GLEnum2[GLEnum2["R11F_G11F_B10F"] = 35898] = "R11F_G11F_B10F"; + GLEnum2[GLEnum2["RGB9_E5"] = 35901] = "RGB9_E5"; + GLEnum2[GLEnum2["RGBA32UI"] = 36208] = "RGBA32UI"; + GLEnum2[GLEnum2["RGB32UI"] = 36209] = "RGB32UI"; + GLEnum2[GLEnum2["RGBA16UI"] = 36214] = "RGBA16UI"; + GLEnum2[GLEnum2["RGB16UI"] = 36215] = "RGB16UI"; + GLEnum2[GLEnum2["RGBA8UI"] = 36220] = "RGBA8UI"; + GLEnum2[GLEnum2["RGB8UI"] = 36221] = "RGB8UI"; + GLEnum2[GLEnum2["RGBA32I"] = 36226] = "RGBA32I"; + GLEnum2[GLEnum2["RGB32I"] = 36227] = "RGB32I"; + GLEnum2[GLEnum2["RGBA16I"] = 36232] = "RGBA16I"; + GLEnum2[GLEnum2["RGB16I"] = 36233] = "RGB16I"; + GLEnum2[GLEnum2["RGBA8I"] = 36238] = "RGBA8I"; + GLEnum2[GLEnum2["RGB8I"] = 36239] = "RGB8I"; + GLEnum2[GLEnum2["RED_INTEGER"] = 36244] = "RED_INTEGER"; + GLEnum2[GLEnum2["RGB_INTEGER"] = 36248] = "RGB_INTEGER"; + GLEnum2[GLEnum2["RGBA_INTEGER"] = 36249] = "RGBA_INTEGER"; + GLEnum2[GLEnum2["R8"] = 33321] = "R8"; + GLEnum2[GLEnum2["RG8"] = 33323] = "RG8"; + GLEnum2[GLEnum2["R16F"] = 33325] = "R16F"; + GLEnum2[GLEnum2["R32F"] = 33326] = "R32F"; + GLEnum2[GLEnum2["RG16F"] = 33327] = "RG16F"; + GLEnum2[GLEnum2["RG32F"] = 33328] = "RG32F"; + GLEnum2[GLEnum2["R8I"] = 33329] = "R8I"; + GLEnum2[GLEnum2["R8UI"] = 33330] = "R8UI"; + GLEnum2[GLEnum2["R16I"] = 33331] = "R16I"; + GLEnum2[GLEnum2["R16UI"] = 33332] = "R16UI"; + GLEnum2[GLEnum2["R32I"] = 33333] = "R32I"; + GLEnum2[GLEnum2["R32UI"] = 33334] = "R32UI"; + GLEnum2[GLEnum2["RG8I"] = 33335] = "RG8I"; + GLEnum2[GLEnum2["RG8UI"] = 33336] = "RG8UI"; + GLEnum2[GLEnum2["RG16I"] = 33337] = "RG16I"; + GLEnum2[GLEnum2["RG16UI"] = 33338] = "RG16UI"; + GLEnum2[GLEnum2["RG32I"] = 33339] = "RG32I"; + GLEnum2[GLEnum2["RG32UI"] = 33340] = "RG32UI"; + GLEnum2[GLEnum2["R8_SNORM"] = 36756] = "R8_SNORM"; + GLEnum2[GLEnum2["RG8_SNORM"] = 36757] = "RG8_SNORM"; + GLEnum2[GLEnum2["RGB8_SNORM"] = 36758] = "RGB8_SNORM"; + GLEnum2[GLEnum2["RGBA8_SNORM"] = 36759] = "RGBA8_SNORM"; + GLEnum2[GLEnum2["RGB10_A2UI"] = 36975] = "RGB10_A2UI"; + GLEnum2[GLEnum2["TEXTURE_IMMUTABLE_FORMAT"] = 37167] = "TEXTURE_IMMUTABLE_FORMAT"; + GLEnum2[GLEnum2["TEXTURE_IMMUTABLE_LEVELS"] = 33503] = "TEXTURE_IMMUTABLE_LEVELS"; + GLEnum2[GLEnum2["UNSIGNED_INT_2_10_10_10_REV"] = 33640] = "UNSIGNED_INT_2_10_10_10_REV"; + GLEnum2[GLEnum2["UNSIGNED_INT_10F_11F_11F_REV"] = 35899] = "UNSIGNED_INT_10F_11F_11F_REV"; + GLEnum2[GLEnum2["UNSIGNED_INT_5_9_9_9_REV"] = 35902] = "UNSIGNED_INT_5_9_9_9_REV"; + GLEnum2[GLEnum2["FLOAT_32_UNSIGNED_INT_24_8_REV"] = 36269] = "FLOAT_32_UNSIGNED_INT_24_8_REV"; + GLEnum2[GLEnum2["UNSIGNED_INT_24_8"] = 34042] = "UNSIGNED_INT_24_8"; + GLEnum2[GLEnum2["HALF_FLOAT"] = 5131] = "HALF_FLOAT"; + GLEnum2[GLEnum2["RG"] = 33319] = "RG"; + GLEnum2[GLEnum2["RG_INTEGER"] = 33320] = "RG_INTEGER"; + GLEnum2[GLEnum2["INT_2_10_10_10_REV"] = 36255] = "INT_2_10_10_10_REV"; + GLEnum2[GLEnum2["CURRENT_QUERY"] = 34917] = "CURRENT_QUERY"; + GLEnum2[GLEnum2["QUERY_RESULT"] = 34918] = "QUERY_RESULT"; + GLEnum2[GLEnum2["QUERY_RESULT_AVAILABLE"] = 34919] = "QUERY_RESULT_AVAILABLE"; + GLEnum2[GLEnum2["ANY_SAMPLES_PASSED"] = 35887] = "ANY_SAMPLES_PASSED"; + GLEnum2[GLEnum2["ANY_SAMPLES_PASSED_CONSERVATIVE"] = 36202] = "ANY_SAMPLES_PASSED_CONSERVATIVE"; + GLEnum2[GLEnum2["MAX_DRAW_BUFFERS"] = 34852] = "MAX_DRAW_BUFFERS"; + GLEnum2[GLEnum2["DRAW_BUFFER0"] = 34853] = "DRAW_BUFFER0"; + GLEnum2[GLEnum2["DRAW_BUFFER1"] = 34854] = "DRAW_BUFFER1"; + GLEnum2[GLEnum2["DRAW_BUFFER2"] = 34855] = "DRAW_BUFFER2"; + GLEnum2[GLEnum2["DRAW_BUFFER3"] = 34856] = "DRAW_BUFFER3"; + GLEnum2[GLEnum2["DRAW_BUFFER4"] = 34857] = "DRAW_BUFFER4"; + GLEnum2[GLEnum2["DRAW_BUFFER5"] = 34858] = "DRAW_BUFFER5"; + GLEnum2[GLEnum2["DRAW_BUFFER6"] = 34859] = "DRAW_BUFFER6"; + GLEnum2[GLEnum2["DRAW_BUFFER7"] = 34860] = "DRAW_BUFFER7"; + GLEnum2[GLEnum2["DRAW_BUFFER8"] = 34861] = "DRAW_BUFFER8"; + GLEnum2[GLEnum2["DRAW_BUFFER9"] = 34862] = "DRAW_BUFFER9"; + GLEnum2[GLEnum2["DRAW_BUFFER10"] = 34863] = "DRAW_BUFFER10"; + GLEnum2[GLEnum2["DRAW_BUFFER11"] = 34864] = "DRAW_BUFFER11"; + GLEnum2[GLEnum2["DRAW_BUFFER12"] = 34865] = "DRAW_BUFFER12"; + GLEnum2[GLEnum2["DRAW_BUFFER13"] = 34866] = "DRAW_BUFFER13"; + GLEnum2[GLEnum2["DRAW_BUFFER14"] = 34867] = "DRAW_BUFFER14"; + GLEnum2[GLEnum2["DRAW_BUFFER15"] = 34868] = "DRAW_BUFFER15"; + GLEnum2[GLEnum2["MAX_COLOR_ATTACHMENTS"] = 36063] = "MAX_COLOR_ATTACHMENTS"; + GLEnum2[GLEnum2["COLOR_ATTACHMENT1"] = 36065] = "COLOR_ATTACHMENT1"; + GLEnum2[GLEnum2["COLOR_ATTACHMENT2"] = 36066] = "COLOR_ATTACHMENT2"; + GLEnum2[GLEnum2["COLOR_ATTACHMENT3"] = 36067] = "COLOR_ATTACHMENT3"; + GLEnum2[GLEnum2["COLOR_ATTACHMENT4"] = 36068] = "COLOR_ATTACHMENT4"; + GLEnum2[GLEnum2["COLOR_ATTACHMENT5"] = 36069] = "COLOR_ATTACHMENT5"; + GLEnum2[GLEnum2["COLOR_ATTACHMENT6"] = 36070] = "COLOR_ATTACHMENT6"; + GLEnum2[GLEnum2["COLOR_ATTACHMENT7"] = 36071] = "COLOR_ATTACHMENT7"; + GLEnum2[GLEnum2["COLOR_ATTACHMENT8"] = 36072] = "COLOR_ATTACHMENT8"; + GLEnum2[GLEnum2["COLOR_ATTACHMENT9"] = 36073] = "COLOR_ATTACHMENT9"; + GLEnum2[GLEnum2["COLOR_ATTACHMENT10"] = 36074] = "COLOR_ATTACHMENT10"; + GLEnum2[GLEnum2["COLOR_ATTACHMENT11"] = 36075] = "COLOR_ATTACHMENT11"; + GLEnum2[GLEnum2["COLOR_ATTACHMENT12"] = 36076] = "COLOR_ATTACHMENT12"; + GLEnum2[GLEnum2["COLOR_ATTACHMENT13"] = 36077] = "COLOR_ATTACHMENT13"; + GLEnum2[GLEnum2["COLOR_ATTACHMENT14"] = 36078] = "COLOR_ATTACHMENT14"; + GLEnum2[GLEnum2["COLOR_ATTACHMENT15"] = 36079] = "COLOR_ATTACHMENT15"; + GLEnum2[GLEnum2["SAMPLER_3D"] = 35679] = "SAMPLER_3D"; + GLEnum2[GLEnum2["SAMPLER_2D_SHADOW"] = 35682] = "SAMPLER_2D_SHADOW"; + GLEnum2[GLEnum2["SAMPLER_2D_ARRAY"] = 36289] = "SAMPLER_2D_ARRAY"; + GLEnum2[GLEnum2["SAMPLER_2D_ARRAY_SHADOW"] = 36292] = "SAMPLER_2D_ARRAY_SHADOW"; + GLEnum2[GLEnum2["SAMPLER_CUBE_SHADOW"] = 36293] = "SAMPLER_CUBE_SHADOW"; + GLEnum2[GLEnum2["INT_SAMPLER_2D"] = 36298] = "INT_SAMPLER_2D"; + GLEnum2[GLEnum2["INT_SAMPLER_3D"] = 36299] = "INT_SAMPLER_3D"; + GLEnum2[GLEnum2["INT_SAMPLER_CUBE"] = 36300] = "INT_SAMPLER_CUBE"; + GLEnum2[GLEnum2["INT_SAMPLER_2D_ARRAY"] = 36303] = "INT_SAMPLER_2D_ARRAY"; + GLEnum2[GLEnum2["UNSIGNED_INT_SAMPLER_2D"] = 36306] = "UNSIGNED_INT_SAMPLER_2D"; + GLEnum2[GLEnum2["UNSIGNED_INT_SAMPLER_3D"] = 36307] = "UNSIGNED_INT_SAMPLER_3D"; + GLEnum2[GLEnum2["UNSIGNED_INT_SAMPLER_CUBE"] = 36308] = "UNSIGNED_INT_SAMPLER_CUBE"; + GLEnum2[GLEnum2["UNSIGNED_INT_SAMPLER_2D_ARRAY"] = 36311] = "UNSIGNED_INT_SAMPLER_2D_ARRAY"; + GLEnum2[GLEnum2["MAX_SAMPLES"] = 36183] = "MAX_SAMPLES"; + GLEnum2[GLEnum2["SAMPLER_BINDING"] = 35097] = "SAMPLER_BINDING"; + GLEnum2[GLEnum2["PIXEL_PACK_BUFFER"] = 35051] = "PIXEL_PACK_BUFFER"; + GLEnum2[GLEnum2["PIXEL_UNPACK_BUFFER"] = 35052] = "PIXEL_UNPACK_BUFFER"; + GLEnum2[GLEnum2["PIXEL_PACK_BUFFER_BINDING"] = 35053] = "PIXEL_PACK_BUFFER_BINDING"; + GLEnum2[GLEnum2["PIXEL_UNPACK_BUFFER_BINDING"] = 35055] = "PIXEL_UNPACK_BUFFER_BINDING"; + GLEnum2[GLEnum2["COPY_READ_BUFFER"] = 36662] = "COPY_READ_BUFFER"; + GLEnum2[GLEnum2["COPY_WRITE_BUFFER"] = 36663] = "COPY_WRITE_BUFFER"; + GLEnum2[GLEnum2["COPY_READ_BUFFER_BINDING"] = 36662] = "COPY_READ_BUFFER_BINDING"; + GLEnum2[GLEnum2["COPY_WRITE_BUFFER_BINDING"] = 36663] = "COPY_WRITE_BUFFER_BINDING"; + GLEnum2[GLEnum2["FLOAT_MAT2x3"] = 35685] = "FLOAT_MAT2x3"; + GLEnum2[GLEnum2["FLOAT_MAT2x4"] = 35686] = "FLOAT_MAT2x4"; + GLEnum2[GLEnum2["FLOAT_MAT3x2"] = 35687] = "FLOAT_MAT3x2"; + GLEnum2[GLEnum2["FLOAT_MAT3x4"] = 35688] = "FLOAT_MAT3x4"; + GLEnum2[GLEnum2["FLOAT_MAT4x2"] = 35689] = "FLOAT_MAT4x2"; + GLEnum2[GLEnum2["FLOAT_MAT4x3"] = 35690] = "FLOAT_MAT4x3"; + GLEnum2[GLEnum2["UNSIGNED_INT_VEC2"] = 36294] = "UNSIGNED_INT_VEC2"; + GLEnum2[GLEnum2["UNSIGNED_INT_VEC3"] = 36295] = "UNSIGNED_INT_VEC3"; + GLEnum2[GLEnum2["UNSIGNED_INT_VEC4"] = 36296] = "UNSIGNED_INT_VEC4"; + GLEnum2[GLEnum2["UNSIGNED_NORMALIZED"] = 35863] = "UNSIGNED_NORMALIZED"; + GLEnum2[GLEnum2["SIGNED_NORMALIZED"] = 36764] = "SIGNED_NORMALIZED"; + GLEnum2[GLEnum2["VERTEX_ATTRIB_ARRAY_INTEGER"] = 35069] = "VERTEX_ATTRIB_ARRAY_INTEGER"; + GLEnum2[GLEnum2["VERTEX_ATTRIB_ARRAY_DIVISOR"] = 35070] = "VERTEX_ATTRIB_ARRAY_DIVISOR"; + GLEnum2[GLEnum2["TRANSFORM_FEEDBACK_BUFFER_MODE"] = 35967] = "TRANSFORM_FEEDBACK_BUFFER_MODE"; + GLEnum2[GLEnum2["MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS"] = 35968] = "MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS"; + GLEnum2[GLEnum2["TRANSFORM_FEEDBACK_VARYINGS"] = 35971] = "TRANSFORM_FEEDBACK_VARYINGS"; + GLEnum2[GLEnum2["TRANSFORM_FEEDBACK_BUFFER_START"] = 35972] = "TRANSFORM_FEEDBACK_BUFFER_START"; + GLEnum2[GLEnum2["TRANSFORM_FEEDBACK_BUFFER_SIZE"] = 35973] = "TRANSFORM_FEEDBACK_BUFFER_SIZE"; + GLEnum2[GLEnum2["TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN"] = 35976] = "TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN"; + GLEnum2[GLEnum2["MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS"] = 35978] = "MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS"; + GLEnum2[GLEnum2["MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS"] = 35979] = "MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS"; + GLEnum2[GLEnum2["INTERLEAVED_ATTRIBS"] = 35980] = "INTERLEAVED_ATTRIBS"; + GLEnum2[GLEnum2["SEPARATE_ATTRIBS"] = 35981] = "SEPARATE_ATTRIBS"; + GLEnum2[GLEnum2["TRANSFORM_FEEDBACK_BUFFER"] = 35982] = "TRANSFORM_FEEDBACK_BUFFER"; + GLEnum2[GLEnum2["TRANSFORM_FEEDBACK_BUFFER_BINDING"] = 35983] = "TRANSFORM_FEEDBACK_BUFFER_BINDING"; + GLEnum2[GLEnum2["TRANSFORM_FEEDBACK"] = 36386] = "TRANSFORM_FEEDBACK"; + GLEnum2[GLEnum2["TRANSFORM_FEEDBACK_PAUSED"] = 36387] = "TRANSFORM_FEEDBACK_PAUSED"; + GLEnum2[GLEnum2["TRANSFORM_FEEDBACK_ACTIVE"] = 36388] = "TRANSFORM_FEEDBACK_ACTIVE"; + GLEnum2[GLEnum2["TRANSFORM_FEEDBACK_BINDING"] = 36389] = "TRANSFORM_FEEDBACK_BINDING"; + GLEnum2[GLEnum2["FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING"] = 33296] = "FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING"; + GLEnum2[GLEnum2["FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE"] = 33297] = "FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE"; + GLEnum2[GLEnum2["FRAMEBUFFER_ATTACHMENT_RED_SIZE"] = 33298] = "FRAMEBUFFER_ATTACHMENT_RED_SIZE"; + GLEnum2[GLEnum2["FRAMEBUFFER_ATTACHMENT_GREEN_SIZE"] = 33299] = "FRAMEBUFFER_ATTACHMENT_GREEN_SIZE"; + GLEnum2[GLEnum2["FRAMEBUFFER_ATTACHMENT_BLUE_SIZE"] = 33300] = "FRAMEBUFFER_ATTACHMENT_BLUE_SIZE"; + GLEnum2[GLEnum2["FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE"] = 33301] = "FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE"; + GLEnum2[GLEnum2["FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE"] = 33302] = "FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE"; + GLEnum2[GLEnum2["FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE"] = 33303] = "FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE"; + GLEnum2[GLEnum2["FRAMEBUFFER_DEFAULT"] = 33304] = "FRAMEBUFFER_DEFAULT"; + GLEnum2[GLEnum2["DEPTH24_STENCIL8"] = 35056] = "DEPTH24_STENCIL8"; + GLEnum2[GLEnum2["DRAW_FRAMEBUFFER_BINDING"] = 36006] = "DRAW_FRAMEBUFFER_BINDING"; + GLEnum2[GLEnum2["READ_FRAMEBUFFER_BINDING"] = 36010] = "READ_FRAMEBUFFER_BINDING"; + GLEnum2[GLEnum2["RENDERBUFFER_SAMPLES"] = 36011] = "RENDERBUFFER_SAMPLES"; + GLEnum2[GLEnum2["FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER"] = 36052] = "FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER"; + GLEnum2[GLEnum2["FRAMEBUFFER_INCOMPLETE_MULTISAMPLE"] = 36182] = "FRAMEBUFFER_INCOMPLETE_MULTISAMPLE"; + GLEnum2[GLEnum2["UNIFORM_BUFFER"] = 35345] = "UNIFORM_BUFFER"; + GLEnum2[GLEnum2["UNIFORM_BUFFER_BINDING"] = 35368] = "UNIFORM_BUFFER_BINDING"; + GLEnum2[GLEnum2["UNIFORM_BUFFER_START"] = 35369] = "UNIFORM_BUFFER_START"; + GLEnum2[GLEnum2["UNIFORM_BUFFER_SIZE"] = 35370] = "UNIFORM_BUFFER_SIZE"; + GLEnum2[GLEnum2["MAX_VERTEX_UNIFORM_BLOCKS"] = 35371] = "MAX_VERTEX_UNIFORM_BLOCKS"; + GLEnum2[GLEnum2["MAX_FRAGMENT_UNIFORM_BLOCKS"] = 35373] = "MAX_FRAGMENT_UNIFORM_BLOCKS"; + GLEnum2[GLEnum2["MAX_COMBINED_UNIFORM_BLOCKS"] = 35374] = "MAX_COMBINED_UNIFORM_BLOCKS"; + GLEnum2[GLEnum2["MAX_UNIFORM_BUFFER_BINDINGS"] = 35375] = "MAX_UNIFORM_BUFFER_BINDINGS"; + GLEnum2[GLEnum2["MAX_UNIFORM_BLOCK_SIZE"] = 35376] = "MAX_UNIFORM_BLOCK_SIZE"; + GLEnum2[GLEnum2["MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS"] = 35377] = "MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS"; + GLEnum2[GLEnum2["MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS"] = 35379] = "MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS"; + GLEnum2[GLEnum2["UNIFORM_BUFFER_OFFSET_ALIGNMENT"] = 35380] = "UNIFORM_BUFFER_OFFSET_ALIGNMENT"; + GLEnum2[GLEnum2["ACTIVE_UNIFORM_BLOCKS"] = 35382] = "ACTIVE_UNIFORM_BLOCKS"; + GLEnum2[GLEnum2["UNIFORM_TYPE"] = 35383] = "UNIFORM_TYPE"; + GLEnum2[GLEnum2["UNIFORM_SIZE"] = 35384] = "UNIFORM_SIZE"; + GLEnum2[GLEnum2["UNIFORM_BLOCK_INDEX"] = 35386] = "UNIFORM_BLOCK_INDEX"; + GLEnum2[GLEnum2["UNIFORM_OFFSET"] = 35387] = "UNIFORM_OFFSET"; + GLEnum2[GLEnum2["UNIFORM_ARRAY_STRIDE"] = 35388] = "UNIFORM_ARRAY_STRIDE"; + GLEnum2[GLEnum2["UNIFORM_MATRIX_STRIDE"] = 35389] = "UNIFORM_MATRIX_STRIDE"; + GLEnum2[GLEnum2["UNIFORM_IS_ROW_MAJOR"] = 35390] = "UNIFORM_IS_ROW_MAJOR"; + GLEnum2[GLEnum2["UNIFORM_BLOCK_BINDING"] = 35391] = "UNIFORM_BLOCK_BINDING"; + GLEnum2[GLEnum2["UNIFORM_BLOCK_DATA_SIZE"] = 35392] = "UNIFORM_BLOCK_DATA_SIZE"; + GLEnum2[GLEnum2["UNIFORM_BLOCK_ACTIVE_UNIFORMS"] = 35394] = "UNIFORM_BLOCK_ACTIVE_UNIFORMS"; + GLEnum2[GLEnum2["UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES"] = 35395] = "UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES"; + GLEnum2[GLEnum2["UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER"] = 35396] = "UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER"; + GLEnum2[GLEnum2["UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER"] = 35398] = "UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER"; + GLEnum2[GLEnum2["OBJECT_TYPE"] = 37138] = "OBJECT_TYPE"; + GLEnum2[GLEnum2["SYNC_CONDITION"] = 37139] = "SYNC_CONDITION"; + GLEnum2[GLEnum2["SYNC_STATUS"] = 37140] = "SYNC_STATUS"; + GLEnum2[GLEnum2["SYNC_FLAGS"] = 37141] = "SYNC_FLAGS"; + GLEnum2[GLEnum2["SYNC_FENCE"] = 37142] = "SYNC_FENCE"; + GLEnum2[GLEnum2["SYNC_GPU_COMMANDS_COMPLETE"] = 37143] = "SYNC_GPU_COMMANDS_COMPLETE"; + GLEnum2[GLEnum2["UNSIGNALED"] = 37144] = "UNSIGNALED"; + GLEnum2[GLEnum2["SIGNALED"] = 37145] = "SIGNALED"; + GLEnum2[GLEnum2["ALREADY_SIGNALED"] = 37146] = "ALREADY_SIGNALED"; + GLEnum2[GLEnum2["TIMEOUT_EXPIRED"] = 37147] = "TIMEOUT_EXPIRED"; + GLEnum2[GLEnum2["CONDITION_SATISFIED"] = 37148] = "CONDITION_SATISFIED"; + GLEnum2[GLEnum2["WAIT_FAILED"] = 37149] = "WAIT_FAILED"; + GLEnum2[GLEnum2["SYNC_FLUSH_COMMANDS_BIT"] = 1] = "SYNC_FLUSH_COMMANDS_BIT"; + GLEnum2[GLEnum2["COLOR"] = 6144] = "COLOR"; + GLEnum2[GLEnum2["DEPTH"] = 6145] = "DEPTH"; + GLEnum2[GLEnum2["STENCIL"] = 6146] = "STENCIL"; + GLEnum2[GLEnum2["MIN"] = 32775] = "MIN"; + GLEnum2[GLEnum2["MAX"] = 32776] = "MAX"; + GLEnum2[GLEnum2["DEPTH_COMPONENT24"] = 33190] = "DEPTH_COMPONENT24"; + GLEnum2[GLEnum2["STREAM_READ"] = 35041] = "STREAM_READ"; + GLEnum2[GLEnum2["STREAM_COPY"] = 35042] = "STREAM_COPY"; + GLEnum2[GLEnum2["STATIC_READ"] = 35045] = "STATIC_READ"; + GLEnum2[GLEnum2["STATIC_COPY"] = 35046] = "STATIC_COPY"; + GLEnum2[GLEnum2["DYNAMIC_READ"] = 35049] = "DYNAMIC_READ"; + GLEnum2[GLEnum2["DYNAMIC_COPY"] = 35050] = "DYNAMIC_COPY"; + GLEnum2[GLEnum2["DEPTH_COMPONENT32F"] = 36012] = "DEPTH_COMPONENT32F"; + GLEnum2[GLEnum2["DEPTH32F_STENCIL8"] = 36013] = "DEPTH32F_STENCIL8"; + GLEnum2[GLEnum2["INVALID_INDEX"] = 4294967295] = "INVALID_INDEX"; + GLEnum2[GLEnum2["TIMEOUT_IGNORED"] = -1] = "TIMEOUT_IGNORED"; + GLEnum2[GLEnum2["MAX_CLIENT_WAIT_TIMEOUT_WEBGL"] = 37447] = "MAX_CLIENT_WAIT_TIMEOUT_WEBGL"; + GLEnum2[GLEnum2["UNMASKED_VENDOR_WEBGL"] = 37445] = "UNMASKED_VENDOR_WEBGL"; + GLEnum2[GLEnum2["UNMASKED_RENDERER_WEBGL"] = 37446] = "UNMASKED_RENDERER_WEBGL"; + GLEnum2[GLEnum2["MAX_TEXTURE_MAX_ANISOTROPY_EXT"] = 34047] = "MAX_TEXTURE_MAX_ANISOTROPY_EXT"; + GLEnum2[GLEnum2["TEXTURE_MAX_ANISOTROPY_EXT"] = 34046] = "TEXTURE_MAX_ANISOTROPY_EXT"; + GLEnum2[GLEnum2["R16_EXT"] = 33322] = "R16_EXT"; + GLEnum2[GLEnum2["RG16_EXT"] = 33324] = "RG16_EXT"; + GLEnum2[GLEnum2["RGB16_EXT"] = 32852] = "RGB16_EXT"; + GLEnum2[GLEnum2["RGBA16_EXT"] = 32859] = "RGBA16_EXT"; + GLEnum2[GLEnum2["R16_SNORM_EXT"] = 36760] = "R16_SNORM_EXT"; + GLEnum2[GLEnum2["RG16_SNORM_EXT"] = 36761] = "RG16_SNORM_EXT"; + GLEnum2[GLEnum2["RGB16_SNORM_EXT"] = 36762] = "RGB16_SNORM_EXT"; + GLEnum2[GLEnum2["RGBA16_SNORM_EXT"] = 36763] = "RGBA16_SNORM_EXT"; + GLEnum2[GLEnum2["COMPRESSED_RGB_S3TC_DXT1_EXT"] = 33776] = "COMPRESSED_RGB_S3TC_DXT1_EXT"; + GLEnum2[GLEnum2["COMPRESSED_RGBA_S3TC_DXT1_EXT"] = 33777] = "COMPRESSED_RGBA_S3TC_DXT1_EXT"; + GLEnum2[GLEnum2["COMPRESSED_RGBA_S3TC_DXT3_EXT"] = 33778] = "COMPRESSED_RGBA_S3TC_DXT3_EXT"; + GLEnum2[GLEnum2["COMPRESSED_RGBA_S3TC_DXT5_EXT"] = 33779] = "COMPRESSED_RGBA_S3TC_DXT5_EXT"; + GLEnum2[GLEnum2["COMPRESSED_SRGB_S3TC_DXT1_EXT"] = 35916] = "COMPRESSED_SRGB_S3TC_DXT1_EXT"; + GLEnum2[GLEnum2["COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT"] = 35917] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT"; + GLEnum2[GLEnum2["COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT"] = 35918] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT"; + GLEnum2[GLEnum2["COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT"] = 35919] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT"; + GLEnum2[GLEnum2["COMPRESSED_RED_RGTC1_EXT"] = 36283] = "COMPRESSED_RED_RGTC1_EXT"; + GLEnum2[GLEnum2["COMPRESSED_SIGNED_RED_RGTC1_EXT"] = 36284] = "COMPRESSED_SIGNED_RED_RGTC1_EXT"; + GLEnum2[GLEnum2["COMPRESSED_RED_GREEN_RGTC2_EXT"] = 36285] = "COMPRESSED_RED_GREEN_RGTC2_EXT"; + GLEnum2[GLEnum2["COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT"] = 36286] = "COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT"; + GLEnum2[GLEnum2["COMPRESSED_RGBA_BPTC_UNORM_EXT"] = 36492] = "COMPRESSED_RGBA_BPTC_UNORM_EXT"; + GLEnum2[GLEnum2["COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT"] = 36493] = "COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT"; + GLEnum2[GLEnum2["COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT"] = 36494] = "COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT"; + GLEnum2[GLEnum2["COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT"] = 36495] = "COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT"; + GLEnum2[GLEnum2["COMPRESSED_R11_EAC"] = 37488] = "COMPRESSED_R11_EAC"; + GLEnum2[GLEnum2["COMPRESSED_SIGNED_R11_EAC"] = 37489] = "COMPRESSED_SIGNED_R11_EAC"; + GLEnum2[GLEnum2["COMPRESSED_RG11_EAC"] = 37490] = "COMPRESSED_RG11_EAC"; + GLEnum2[GLEnum2["COMPRESSED_SIGNED_RG11_EAC"] = 37491] = "COMPRESSED_SIGNED_RG11_EAC"; + GLEnum2[GLEnum2["COMPRESSED_RGB8_ETC2"] = 37492] = "COMPRESSED_RGB8_ETC2"; + GLEnum2[GLEnum2["COMPRESSED_RGBA8_ETC2_EAC"] = 37493] = "COMPRESSED_RGBA8_ETC2_EAC"; + GLEnum2[GLEnum2["COMPRESSED_SRGB8_ETC2"] = 37494] = "COMPRESSED_SRGB8_ETC2"; + GLEnum2[GLEnum2["COMPRESSED_SRGB8_ALPHA8_ETC2_EAC"] = 37495] = "COMPRESSED_SRGB8_ALPHA8_ETC2_EAC"; + GLEnum2[GLEnum2["COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2"] = 37496] = "COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2"; + GLEnum2[GLEnum2["COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2"] = 37497] = "COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2"; + GLEnum2[GLEnum2["COMPRESSED_RGB_PVRTC_4BPPV1_IMG"] = 35840] = "COMPRESSED_RGB_PVRTC_4BPPV1_IMG"; + GLEnum2[GLEnum2["COMPRESSED_RGBA_PVRTC_4BPPV1_IMG"] = 35842] = "COMPRESSED_RGBA_PVRTC_4BPPV1_IMG"; + GLEnum2[GLEnum2["COMPRESSED_RGB_PVRTC_2BPPV1_IMG"] = 35841] = "COMPRESSED_RGB_PVRTC_2BPPV1_IMG"; + GLEnum2[GLEnum2["COMPRESSED_RGBA_PVRTC_2BPPV1_IMG"] = 35843] = "COMPRESSED_RGBA_PVRTC_2BPPV1_IMG"; + GLEnum2[GLEnum2["COMPRESSED_RGB_ETC1_WEBGL"] = 36196] = "COMPRESSED_RGB_ETC1_WEBGL"; + GLEnum2[GLEnum2["COMPRESSED_RGB_ATC_WEBGL"] = 35986] = "COMPRESSED_RGB_ATC_WEBGL"; + GLEnum2[GLEnum2["COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL"] = 35986] = "COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL"; + GLEnum2[GLEnum2["COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL"] = 34798] = "COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL"; + GLEnum2[GLEnum2["COMPRESSED_RGBA_ASTC_4x4_KHR"] = 37808] = "COMPRESSED_RGBA_ASTC_4x4_KHR"; + GLEnum2[GLEnum2["COMPRESSED_RGBA_ASTC_5x4_KHR"] = 37809] = "COMPRESSED_RGBA_ASTC_5x4_KHR"; + GLEnum2[GLEnum2["COMPRESSED_RGBA_ASTC_5x5_KHR"] = 37810] = "COMPRESSED_RGBA_ASTC_5x5_KHR"; + GLEnum2[GLEnum2["COMPRESSED_RGBA_ASTC_6x5_KHR"] = 37811] = "COMPRESSED_RGBA_ASTC_6x5_KHR"; + GLEnum2[GLEnum2["COMPRESSED_RGBA_ASTC_6x6_KHR"] = 37812] = "COMPRESSED_RGBA_ASTC_6x6_KHR"; + GLEnum2[GLEnum2["COMPRESSED_RGBA_ASTC_8x5_KHR"] = 37813] = "COMPRESSED_RGBA_ASTC_8x5_KHR"; + GLEnum2[GLEnum2["COMPRESSED_RGBA_ASTC_8x6_KHR"] = 37814] = "COMPRESSED_RGBA_ASTC_8x6_KHR"; + GLEnum2[GLEnum2["COMPRESSED_RGBA_ASTC_8x8_KHR"] = 37815] = "COMPRESSED_RGBA_ASTC_8x8_KHR"; + GLEnum2[GLEnum2["COMPRESSED_RGBA_ASTC_10x5_KHR"] = 37816] = "COMPRESSED_RGBA_ASTC_10x5_KHR"; + GLEnum2[GLEnum2["COMPRESSED_RGBA_ASTC_10x6_KHR"] = 37817] = "COMPRESSED_RGBA_ASTC_10x6_KHR"; + GLEnum2[GLEnum2["COMPRESSED_RGBA_ASTC_10x8_KHR"] = 37818] = "COMPRESSED_RGBA_ASTC_10x8_KHR"; + GLEnum2[GLEnum2["COMPRESSED_RGBA_ASTC_10x10_KHR"] = 37819] = "COMPRESSED_RGBA_ASTC_10x10_KHR"; + GLEnum2[GLEnum2["COMPRESSED_RGBA_ASTC_12x10_KHR"] = 37820] = "COMPRESSED_RGBA_ASTC_12x10_KHR"; + GLEnum2[GLEnum2["COMPRESSED_RGBA_ASTC_12x12_KHR"] = 37821] = "COMPRESSED_RGBA_ASTC_12x12_KHR"; + GLEnum2[GLEnum2["COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR"] = 37840] = "COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR"; + GLEnum2[GLEnum2["COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR"] = 37841] = "COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR"; + GLEnum2[GLEnum2["COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR"] = 37842] = "COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR"; + GLEnum2[GLEnum2["COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR"] = 37843] = "COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR"; + GLEnum2[GLEnum2["COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR"] = 37844] = "COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR"; + GLEnum2[GLEnum2["COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR"] = 37845] = "COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR"; + GLEnum2[GLEnum2["COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR"] = 37846] = "COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR"; + GLEnum2[GLEnum2["COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR"] = 37847] = "COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR"; + GLEnum2[GLEnum2["COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR"] = 37848] = "COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR"; + GLEnum2[GLEnum2["COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR"] = 37849] = "COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR"; + GLEnum2[GLEnum2["COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR"] = 37850] = "COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR"; + GLEnum2[GLEnum2["COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR"] = 37851] = "COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR"; + GLEnum2[GLEnum2["COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR"] = 37852] = "COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR"; + GLEnum2[GLEnum2["COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR"] = 37853] = "COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR"; + GLEnum2[GLEnum2["QUERY_COUNTER_BITS_EXT"] = 34916] = "QUERY_COUNTER_BITS_EXT"; + GLEnum2[GLEnum2["CURRENT_QUERY_EXT"] = 34917] = "CURRENT_QUERY_EXT"; + GLEnum2[GLEnum2["QUERY_RESULT_EXT"] = 34918] = "QUERY_RESULT_EXT"; + GLEnum2[GLEnum2["QUERY_RESULT_AVAILABLE_EXT"] = 34919] = "QUERY_RESULT_AVAILABLE_EXT"; + GLEnum2[GLEnum2["TIME_ELAPSED_EXT"] = 35007] = "TIME_ELAPSED_EXT"; + GLEnum2[GLEnum2["TIMESTAMP_EXT"] = 36392] = "TIMESTAMP_EXT"; + GLEnum2[GLEnum2["GPU_DISJOINT_EXT"] = 36795] = "GPU_DISJOINT_EXT"; + GLEnum2[GLEnum2["COMPLETION_STATUS_KHR"] = 37297] = "COMPLETION_STATUS_KHR"; + GLEnum2[GLEnum2["DEPTH_CLAMP_EXT"] = 34383] = "DEPTH_CLAMP_EXT"; + GLEnum2[GLEnum2["FIRST_VERTEX_CONVENTION_WEBGL"] = 36429] = "FIRST_VERTEX_CONVENTION_WEBGL"; + GLEnum2[GLEnum2["LAST_VERTEX_CONVENTION_WEBGL"] = 36430] = "LAST_VERTEX_CONVENTION_WEBGL"; + GLEnum2[GLEnum2["PROVOKING_VERTEX_WEBL"] = 36431] = "PROVOKING_VERTEX_WEBL"; + GLEnum2[GLEnum2["POLYGON_MODE_WEBGL"] = 2880] = "POLYGON_MODE_WEBGL"; + GLEnum2[GLEnum2["POLYGON_OFFSET_LINE_WEBGL"] = 10754] = "POLYGON_OFFSET_LINE_WEBGL"; + GLEnum2[GLEnum2["LINE_WEBGL"] = 6913] = "LINE_WEBGL"; + GLEnum2[GLEnum2["FILL_WEBGL"] = 6914] = "FILL_WEBGL"; + GLEnum2[GLEnum2["MAX_CLIP_DISTANCES_WEBGL"] = 3378] = "MAX_CLIP_DISTANCES_WEBGL"; + GLEnum2[GLEnum2["MAX_CULL_DISTANCES_WEBGL"] = 33529] = "MAX_CULL_DISTANCES_WEBGL"; + GLEnum2[GLEnum2["MAX_COMBINED_CLIP_AND_CULL_DISTANCES_WEBGL"] = 33530] = "MAX_COMBINED_CLIP_AND_CULL_DISTANCES_WEBGL"; + GLEnum2[GLEnum2["CLIP_DISTANCE0_WEBGL"] = 12288] = "CLIP_DISTANCE0_WEBGL"; + GLEnum2[GLEnum2["CLIP_DISTANCE1_WEBGL"] = 12289] = "CLIP_DISTANCE1_WEBGL"; + GLEnum2[GLEnum2["CLIP_DISTANCE2_WEBGL"] = 12290] = "CLIP_DISTANCE2_WEBGL"; + GLEnum2[GLEnum2["CLIP_DISTANCE3_WEBGL"] = 12291] = "CLIP_DISTANCE3_WEBGL"; + GLEnum2[GLEnum2["CLIP_DISTANCE4_WEBGL"] = 12292] = "CLIP_DISTANCE4_WEBGL"; + GLEnum2[GLEnum2["CLIP_DISTANCE5_WEBGL"] = 12293] = "CLIP_DISTANCE5_WEBGL"; + GLEnum2[GLEnum2["CLIP_DISTANCE6_WEBGL"] = 12294] = "CLIP_DISTANCE6_WEBGL"; + GLEnum2[GLEnum2["CLIP_DISTANCE7_WEBGL"] = 12295] = "CLIP_DISTANCE7_WEBGL"; + GLEnum2[GLEnum2["POLYGON_OFFSET_CLAMP_EXT"] = 36379] = "POLYGON_OFFSET_CLAMP_EXT"; + GLEnum2[GLEnum2["LOWER_LEFT_EXT"] = 36001] = "LOWER_LEFT_EXT"; + GLEnum2[GLEnum2["UPPER_LEFT_EXT"] = 36002] = "UPPER_LEFT_EXT"; + GLEnum2[GLEnum2["NEGATIVE_ONE_TO_ONE_EXT"] = 37726] = "NEGATIVE_ONE_TO_ONE_EXT"; + GLEnum2[GLEnum2["ZERO_TO_ONE_EXT"] = 37727] = "ZERO_TO_ONE_EXT"; + GLEnum2[GLEnum2["CLIP_ORIGIN_EXT"] = 37724] = "CLIP_ORIGIN_EXT"; + GLEnum2[GLEnum2["CLIP_DEPTH_MODE_EXT"] = 37725] = "CLIP_DEPTH_MODE_EXT"; + GLEnum2[GLEnum2["SRC1_COLOR_WEBGL"] = 35065] = "SRC1_COLOR_WEBGL"; + GLEnum2[GLEnum2["SRC1_ALPHA_WEBGL"] = 34185] = "SRC1_ALPHA_WEBGL"; + GLEnum2[GLEnum2["ONE_MINUS_SRC1_COLOR_WEBGL"] = 35066] = "ONE_MINUS_SRC1_COLOR_WEBGL"; + GLEnum2[GLEnum2["ONE_MINUS_SRC1_ALPHA_WEBGL"] = 35067] = "ONE_MINUS_SRC1_ALPHA_WEBGL"; + GLEnum2[GLEnum2["MAX_DUAL_SOURCE_DRAW_BUFFERS_WEBGL"] = 35068] = "MAX_DUAL_SOURCE_DRAW_BUFFERS_WEBGL"; + GLEnum2[GLEnum2["MIRROR_CLAMP_TO_EDGE_EXT"] = 34627] = "MIRROR_CLAMP_TO_EDGE_EXT"; + })(GLEnum || (GLEnum = {})); + } + }); + + // node_modules/@luma.gl/webgl/dist/constants/index.js + var init_constants = __esm({ + "node_modules/@luma.gl/webgl/dist/constants/index.js"() { + init_webgl_constants(); + } + }); + + // node_modules/@luma.gl/webgl/dist/context/polyfills/polyfill-webgl1-extensions.js + function enforceWebGL2(enforce = true) { + const prototype = HTMLCanvasElement.prototype; + if (!enforce && prototype.originalGetContext) { + prototype.getContext = prototype.originalGetContext; + prototype.originalGetContext = void 0; + return; + } + prototype.originalGetContext = prototype.getContext; + prototype.getContext = function(contextId, options) { + if (contextId === "webgl" || contextId === "experimental-webgl") { + const context = this.originalGetContext("webgl2", options); + if (context instanceof HTMLElement) { + polyfillWebGL1Extensions(context); + } + return context; + } + return this.originalGetContext(contextId, options); + }; + } + function polyfillWebGL1Extensions(gl) { + gl.getExtension("EXT_color_buffer_float"); + const boundExtensions = { + ...WEBGL1_STATIC_EXTENSIONS, + WEBGL_disjoint_timer_query: gl.getExtension("EXT_disjoint_timer_query_webgl2"), + WEBGL_draw_buffers: getWEBGL_draw_buffers(gl), + OES_vertex_array_object: getOES_vertex_array_object(gl), + ANGLE_instanced_arrays: getANGLE_instanced_arrays(gl) + }; + const originalGetExtension = gl.getExtension; + gl.getExtension = function(extensionName) { + const ext = originalGetExtension.call(gl, extensionName); + if (ext) { + return ext; + } + if (extensionName in boundExtensions) { + return boundExtensions[extensionName]; + } + return null; + }; + const originalGetSupportedExtensions = gl.getSupportedExtensions; + gl.getSupportedExtensions = function() { + const extensions = originalGetSupportedExtensions.apply(gl) || []; + return extensions?.concat(Object.keys(boundExtensions)); + }; + } + var WEBGL1_STATIC_EXTENSIONS, getWEBGL_draw_buffers, getOES_vertex_array_object, getANGLE_instanced_arrays; + var init_polyfill_webgl1_extensions = __esm({ + "node_modules/@luma.gl/webgl/dist/context/polyfills/polyfill-webgl1-extensions.js"() { + WEBGL1_STATIC_EXTENSIONS = { + WEBGL_depth_texture: { + UNSIGNED_INT_24_8_WEBGL: 34042 + }, + OES_element_index_uint: {}, + OES_texture_float: {}, + OES_texture_half_float: { + // @ts-expect-error different numbers? + HALF_FLOAT_OES: 5131 + }, + EXT_color_buffer_float: {}, + OES_standard_derivatives: { + FRAGMENT_SHADER_DERIVATIVE_HINT_OES: 35723 + }, + EXT_frag_depth: {}, + EXT_blend_minmax: { + MIN_EXT: 32775, + MAX_EXT: 32776 + }, + EXT_shader_texture_lod: {} + }; + getWEBGL_draw_buffers = (gl) => ({ + drawBuffersWEBGL(buffers) { + return gl.drawBuffers(buffers); + }, + COLOR_ATTACHMENT0_WEBGL: 36064, + COLOR_ATTACHMENT1_WEBGL: 36065, + COLOR_ATTACHMENT2_WEBGL: 36066, + COLOR_ATTACHMENT3_WEBGL: 36067 + }); + getOES_vertex_array_object = (gl) => ({ + VERTEX_ARRAY_BINDING_OES: 34229, + createVertexArrayOES() { + return gl.createVertexArray(); + }, + deleteVertexArrayOES(vertexArray) { + return gl.deleteVertexArray(vertexArray); + }, + isVertexArrayOES(vertexArray) { + return gl.isVertexArray(vertexArray); + }, + bindVertexArrayOES(vertexArray) { + return gl.bindVertexArray(vertexArray); + } + }); + getANGLE_instanced_arrays = (gl) => ({ + VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: 35070, + drawArraysInstancedANGLE(...args) { + return gl.drawArraysInstanced(...args); + }, + drawElementsInstancedANGLE(...args) { + return gl.drawElementsInstanced(...args); + }, + vertexAttribDivisorANGLE(...args) { + return gl.vertexAttribDivisor(...args); + } + }); + } + }); + + // node_modules/@luma.gl/webgl/dist/utils/load-script.js + async function loadScript(scriptUrl, scriptId) { + const head = document.getElementsByTagName("head")[0]; + if (!head) { + throw new Error("loadScript"); + } + const script = document.createElement("script"); + script.setAttribute("type", "text/javascript"); + script.setAttribute("src", scriptUrl); + if (scriptId) { + script.id = scriptId; + } + return new Promise((resolve2, reject) => { + script.onload = resolve2; + script.onerror = (error) => reject(new Error(`Unable to load script '${scriptUrl}': ${error}`)); + head.appendChild(script); + }); + } + var init_load_script = __esm({ + "node_modules/@luma.gl/webgl/dist/utils/load-script.js"() { + } + }); + + // node_modules/@luma.gl/webgl/dist/context/helpers/webgl-context-data.js + function getWebGLContextData(gl) { + const contextData = gl.luma || { + _polyfilled: false, + extensions: {}, + softwareRenderer: false + }; + contextData._polyfilled ??= false; + contextData.extensions ||= {}; + gl.luma = contextData; + return contextData; + } + var init_webgl_context_data = __esm({ + "node_modules/@luma.gl/webgl/dist/context/helpers/webgl-context-data.js"() { + } + }); + + // node_modules/@luma.gl/webgl/dist/context/debug/spector.js + async function loadSpectorJS(props) { + if (!globalThis.SPECTOR) { + try { + await loadScript(props.debugSpectorJSUrl || DEFAULT_SPECTOR_PROPS.debugSpectorJSUrl); + } catch (error) { + log2.warn(String(error)); + } + } + } + function initializeSpectorJS(props) { + props = { ...DEFAULT_SPECTOR_PROPS, ...props }; + if (!props.debugSpectorJS) { + return null; + } + if (!spector && globalThis.SPECTOR && !globalThis.luma?.spector) { + log2.probe(LOG_LEVEL, "SPECTOR found and initialized. Start with `luma.spector.displayUI()`")(); + const { Spector: SpectorJS } = globalThis.SPECTOR; + spector = new SpectorJS(); + if (globalThis.luma) { + globalThis.luma.spector = spector; + } + } + if (!spector) { + return null; + } + if (!initialized) { + initialized = true; + spector.spyCanvases(); + spector?.onCaptureStarted.add((capture) => log2.info("Spector capture started:", capture)()); + spector?.onCapture.add((capture) => { + log2.info("Spector capture complete:", capture)(); + spector?.getResultUI(); + spector?.resultView.display(); + spector?.resultView.addCapture(capture); + }); + } + if (props.gl) { + const gl = props.gl; + const contextData = getWebGLContextData(gl); + const device = contextData.device; + spector?.startCapture(props.gl, 500); + contextData.device = device; + new Promise((resolve2) => setTimeout(resolve2, 2e3)).then((_) => { + log2.info("Spector capture stopped after 2 seconds")(); + spector?.stopCapture(); + }); + } + return spector; + } + var LOG_LEVEL, spector, initialized, DEFAULT_SPECTOR_PROPS; + var init_spector = __esm({ + "node_modules/@luma.gl/webgl/dist/context/debug/spector.js"() { + init_dist4(); + init_load_script(); + init_webgl_context_data(); + LOG_LEVEL = 1; + spector = null; + initialized = false; + DEFAULT_SPECTOR_PROPS = { + debugSpectorJS: log2.get("debug-spectorjs"), + // https://github.com/BabylonJS/Spector.js#basic-usage + // https://forum.babylonjs.com/t/spectorcdn-is-temporarily-off/48241 + // spectorUrl: 'https://spectorcdn.babylonjs.com/spector.bundle.js'; + debugSpectorJSUrl: "https://cdn.jsdelivr.net/npm/spectorjs@0.9.30/dist/spector.bundle.js", + gl: void 0 + }; + } + }); + + // node_modules/@luma.gl/webgl/dist/context/debug/webgl-developer-tools.js + function getWebGLContextData2(gl) { + gl.luma = gl.luma || {}; + return gl.luma; + } + async function loadWebGLDeveloperTools() { + if (isBrowser2() && !globalThis.WebGLDebugUtils) { + globalThis.global = globalThis.global || globalThis; + globalThis.global.module = {}; + await loadScript(WEBGL_DEBUG_CDN_URL); + } + } + function makeDebugContext(gl, props = {}) { + return props.debugWebGL || props.traceWebGL ? getDebugContext(gl, props) : getRealContext(gl); + } + function getRealContext(gl) { + const data = getWebGLContextData2(gl); + return data.realContext ? data.realContext : gl; + } + function getDebugContext(gl, props) { + if (!globalThis.WebGLDebugUtils) { + log2.warn("webgl-debug not loaded")(); + return gl; + } + const data = getWebGLContextData2(gl); + if (data.debugContext) { + return data.debugContext; + } + globalThis.WebGLDebugUtils.init({ ...GLEnum, ...gl }); + const glDebug = globalThis.WebGLDebugUtils.makeDebugContext(gl, onGLError.bind(null, props), onValidateGLFunc.bind(null, props)); + for (const key in GLEnum) { + if (!(key in glDebug) && typeof GLEnum[key] === "number") { + glDebug[key] = GLEnum[key]; + } + } + class WebGLDebugContext { + } + Object.setPrototypeOf(glDebug, Object.getPrototypeOf(gl)); + Object.setPrototypeOf(WebGLDebugContext, glDebug); + const debugContext = Object.create(WebGLDebugContext); + data.realContext = gl; + data.debugContext = debugContext; + debugContext.luma = data; + debugContext.debug = true; + return debugContext; + } + function getFunctionString(functionName, functionArgs) { + functionArgs = Array.from(functionArgs).map((arg) => arg === void 0 ? "undefined" : arg); + let args = globalThis.WebGLDebugUtils.glFunctionArgsToString(functionName, functionArgs); + args = `${args.slice(0, 100)}${args.length > 100 ? "..." : ""}`; + return `gl.${functionName}(${args})`; + } + function onGLError(props, err, functionName, args) { + args = Array.from(args).map((arg) => arg === void 0 ? "undefined" : arg); + const errorMessage = globalThis.WebGLDebugUtils.glEnumToString(err); + const functionArgs = globalThis.WebGLDebugUtils.glFunctionArgsToString(functionName, args); + const message2 = `${errorMessage} in gl.${functionName}(${functionArgs})`; + log2.error("%cWebGL", "color: white; background: red; padding: 2px 6px; border-radius: 3px;", message2)(); + debugger; + throw new Error(message2); + } + function onValidateGLFunc(props, functionName, functionArgs) { + let functionString = ""; + if (props.traceWebGL && log2.level >= 1) { + functionString = getFunctionString(functionName, functionArgs); + log2.info(1, "%cWebGL", "color: white; background: blue; padding: 2px 6px; border-radius: 3px;", functionString)(); + } + for (const arg of functionArgs) { + if (arg === void 0) { + functionString = functionString || getFunctionString(functionName, functionArgs); + debugger; + } + } + } + var WEBGL_DEBUG_CDN_URL; + var init_webgl_developer_tools = __esm({ + "node_modules/@luma.gl/webgl/dist/context/debug/webgl-developer-tools.js"() { + init_dist4(); + init_constants(); + init_dist(); + init_load_script(); + WEBGL_DEBUG_CDN_URL = "https://unpkg.com/webgl-debug@2.0.1/index.js"; + } + }); + + // node_modules/@luma.gl/webgl/dist/context/parameters/webgl-parameter-tables.js + function isArray2(array) { + return Array.isArray(array) || ArrayBuffer.isView(array) && !(array instanceof DataView); + } + function getValue(glEnum, values, cache2) { + return values[glEnum] !== void 0 ? values[glEnum] : cache2[glEnum]; + } + var GL_PARAMETER_DEFAULTS, enable, hint, pixelStorei, bindFramebuffer, bindBuffer, GL_PARAMETER_SETTERS, GL_COMPOSITE_PARAMETER_SETTERS, GL_HOOKED_SETTERS, isEnabled, GL_PARAMETER_GETTERS, NON_CACHE_PARAMETERS; + var init_webgl_parameter_tables = __esm({ + "node_modules/@luma.gl/webgl/dist/context/parameters/webgl-parameter-tables.js"() { + GL_PARAMETER_DEFAULTS = { + [3042]: false, + [32773]: new Float32Array([0, 0, 0, 0]), + [32777]: 32774, + [34877]: 32774, + [32969]: 1, + [32968]: 0, + [32971]: 1, + [32970]: 0, + [3106]: new Float32Array([0, 0, 0, 0]), + // TBD + [3107]: [true, true, true, true], + [2884]: false, + [2885]: 1029, + [2929]: false, + [2931]: 1, + [2932]: 513, + [2928]: new Float32Array([0, 1]), + // TBD + [2930]: true, + [3024]: true, + [35725]: null, + // FRAMEBUFFER_BINDING and DRAW_FRAMEBUFFER_BINDING(WebGL2) refer same state. + [36006]: null, + [36007]: null, + [34229]: null, + [34964]: null, + [2886]: 2305, + [33170]: 4352, + [2849]: 1, + [32823]: false, + [32824]: 0, + [10752]: 0, + [32926]: false, + [32928]: false, + [32938]: 1, + [32939]: false, + [3089]: false, + // Note: Dynamic value. If scissor test enabled we expect users to set correct scissor box + [3088]: new Int32Array([0, 0, 1024, 1024]), + [2960]: false, + [2961]: 0, + [2968]: 4294967295, + [36005]: 4294967295, + [2962]: 519, + [2967]: 0, + [2963]: 4294967295, + [34816]: 519, + [36003]: 0, + [36004]: 4294967295, + [2964]: 7680, + [2965]: 7680, + [2966]: 7680, + [34817]: 7680, + [34818]: 7680, + [34819]: 7680, + // Dynamic value: We use [0, 0, 1024, 1024] as default, but usually this is updated in each frame. + [2978]: [0, 0, 1024, 1024], + [36389]: null, + [36662]: null, + [36663]: null, + [35053]: null, + [35055]: null, + [35723]: 4352, + [36010]: null, + [35977]: false, + [3333]: 4, + [3317]: 4, + [37440]: false, + [37441]: false, + [37443]: 37444, + [3330]: 0, + [3332]: 0, + [3331]: 0, + [3314]: 0, + [32878]: 0, + [3316]: 0, + [3315]: 0, + [32877]: 0 + }; + enable = (gl, value, key) => value ? gl.enable(key) : gl.disable(key); + hint = (gl, value, key) => gl.hint(key, value); + pixelStorei = (gl, value, key) => gl.pixelStorei(key, value); + bindFramebuffer = (gl, value, key) => { + const target2 = key === 36006 ? 36009 : 36008; + return gl.bindFramebuffer(target2, value); + }; + bindBuffer = (gl, value, key) => { + const bindingMap = { + [34964]: 34962, + [36662]: 36662, + [36663]: 36663, + [35053]: 35051, + [35055]: 35052 + }; + const glTarget = bindingMap[key]; + gl.bindBuffer(glTarget, value); + }; + GL_PARAMETER_SETTERS = { + [3042]: enable, + [32773]: (gl, value) => gl.blendColor(...value), + [32777]: "blendEquation", + [34877]: "blendEquation", + [32969]: "blendFunc", + [32968]: "blendFunc", + [32971]: "blendFunc", + [32970]: "blendFunc", + [3106]: (gl, value) => gl.clearColor(...value), + [3107]: (gl, value) => gl.colorMask(...value), + [2884]: enable, + [2885]: (gl, value) => gl.cullFace(value), + [2929]: enable, + [2931]: (gl, value) => gl.clearDepth(value), + [2932]: (gl, value) => gl.depthFunc(value), + [2928]: (gl, value) => gl.depthRange(...value), + [2930]: (gl, value) => gl.depthMask(value), + [3024]: enable, + [35723]: hint, + [35725]: (gl, value) => gl.useProgram(value), + [36007]: (gl, value) => gl.bindRenderbuffer(36161, value), + [36389]: (gl, value) => gl.bindTransformFeedback?.(36386, value), + [34229]: (gl, value) => gl.bindVertexArray(value), + // NOTE: FRAMEBUFFER_BINDING and DRAW_FRAMEBUFFER_BINDING(WebGL2) refer same state. + [36006]: bindFramebuffer, + [36010]: bindFramebuffer, + // Buffers + [34964]: bindBuffer, + [36662]: bindBuffer, + [36663]: bindBuffer, + [35053]: bindBuffer, + [35055]: bindBuffer, + [2886]: (gl, value) => gl.frontFace(value), + [33170]: hint, + [2849]: (gl, value) => gl.lineWidth(value), + [32823]: enable, + [32824]: "polygonOffset", + [10752]: "polygonOffset", + [35977]: enable, + [32926]: enable, + [32928]: enable, + [32938]: "sampleCoverage", + [32939]: "sampleCoverage", + [3089]: enable, + [3088]: (gl, value) => gl.scissor(...value), + [2960]: enable, + [2961]: (gl, value) => gl.clearStencil(value), + [2968]: (gl, value) => gl.stencilMaskSeparate(1028, value), + [36005]: (gl, value) => gl.stencilMaskSeparate(1029, value), + [2962]: "stencilFuncFront", + [2967]: "stencilFuncFront", + [2963]: "stencilFuncFront", + [34816]: "stencilFuncBack", + [36003]: "stencilFuncBack", + [36004]: "stencilFuncBack", + [2964]: "stencilOpFront", + [2965]: "stencilOpFront", + [2966]: "stencilOpFront", + [34817]: "stencilOpBack", + [34818]: "stencilOpBack", + [34819]: "stencilOpBack", + [2978]: (gl, value) => gl.viewport(...value), + // WEBGL2 EXTENSIONS + // EXT_depth_clamp https://registry.khronos.org/webgl/extensions/EXT_depth_clamp/ + [34383]: enable, + // WEBGL_provoking_vertex https://registry.khronos.org/webgl/extensions/WEBGL_provoking_vertex/ + // [GL.PROVOKING_VERTEX_WEBL]: TODO - extension function needed + // WEBGL_polygon_mode https://registry.khronos.org/webgl/extensions/WEBGL_polygon_mode/ + // POLYGON_MODE_WEBGL TODO - extension function needed + [10754]: enable, + // WEBGL_clip_cull_distance https://registry.khronos.org/webgl/extensions/WEBGL_clip_cull_distance/ + [12288]: enable, + [12289]: enable, + [12290]: enable, + [12291]: enable, + [12292]: enable, + [12293]: enable, + [12294]: enable, + [12295]: enable, + // PIXEL PACK/UNPACK MODES + [3333]: pixelStorei, + [3317]: pixelStorei, + [37440]: pixelStorei, + [37441]: pixelStorei, + [37443]: pixelStorei, + [3330]: pixelStorei, + [3332]: pixelStorei, + [3331]: pixelStorei, + [3314]: pixelStorei, + [32878]: pixelStorei, + [3316]: pixelStorei, + [3315]: pixelStorei, + [32877]: pixelStorei, + // Function-style setters + framebuffer: (gl, framebuffer) => { + const handle = framebuffer && "handle" in framebuffer ? framebuffer.handle : framebuffer; + return gl.bindFramebuffer(36160, handle); + }, + blend: (gl, value) => value ? gl.enable(3042) : gl.disable(3042), + blendColor: (gl, value) => gl.blendColor(...value), + blendEquation: (gl, args) => { + const separateModes = typeof args === "number" ? [args, args] : args; + gl.blendEquationSeparate(...separateModes); + }, + blendFunc: (gl, args) => { + const separateFuncs = args?.length === 2 ? [...args, ...args] : args; + gl.blendFuncSeparate(...separateFuncs); + }, + clearColor: (gl, value) => gl.clearColor(...value), + clearDepth: (gl, value) => gl.clearDepth(value), + clearStencil: (gl, value) => gl.clearStencil(value), + colorMask: (gl, value) => gl.colorMask(...value), + cull: (gl, value) => value ? gl.enable(2884) : gl.disable(2884), + cullFace: (gl, value) => gl.cullFace(value), + depthTest: (gl, value) => value ? gl.enable(2929) : gl.disable(2929), + depthFunc: (gl, value) => gl.depthFunc(value), + depthMask: (gl, value) => gl.depthMask(value), + depthRange: (gl, value) => gl.depthRange(...value), + dither: (gl, value) => value ? gl.enable(3024) : gl.disable(3024), + derivativeHint: (gl, value) => { + gl.hint(35723, value); + }, + frontFace: (gl, value) => gl.frontFace(value), + mipmapHint: (gl, value) => gl.hint(33170, value), + lineWidth: (gl, value) => gl.lineWidth(value), + polygonOffsetFill: (gl, value) => value ? gl.enable(32823) : gl.disable(32823), + polygonOffset: (gl, value) => gl.polygonOffset(...value), + sampleCoverage: (gl, value) => gl.sampleCoverage(value[0], value[1] || false), + scissorTest: (gl, value) => value ? gl.enable(3089) : gl.disable(3089), + scissor: (gl, value) => gl.scissor(...value), + stencilTest: (gl, value) => value ? gl.enable(2960) : gl.disable(2960), + stencilMask: (gl, value) => { + value = isArray2(value) ? value : [value, value]; + const [mask, backMask] = value; + gl.stencilMaskSeparate(1028, mask); + gl.stencilMaskSeparate(1029, backMask); + }, + stencilFunc: (gl, args) => { + args = isArray2(args) && args.length === 3 ? [...args, ...args] : args; + const [func, ref, mask, backFunc, backRef, backMask] = args; + gl.stencilFuncSeparate(1028, func, ref, mask); + gl.stencilFuncSeparate(1029, backFunc, backRef, backMask); + }, + stencilOp: (gl, args) => { + args = isArray2(args) && args.length === 3 ? [...args, ...args] : args; + const [sfail, dpfail, dppass, backSfail, backDpfail, backDppass] = args; + gl.stencilOpSeparate(1028, sfail, dpfail, dppass); + gl.stencilOpSeparate(1029, backSfail, backDpfail, backDppass); + }, + viewport: (gl, value) => gl.viewport(...value) + }; + GL_COMPOSITE_PARAMETER_SETTERS = { + blendEquation: (gl, values, cache2) => gl.blendEquationSeparate(getValue(32777, values, cache2), getValue(34877, values, cache2)), + blendFunc: (gl, values, cache2) => gl.blendFuncSeparate(getValue(32969, values, cache2), getValue(32968, values, cache2), getValue(32971, values, cache2), getValue(32970, values, cache2)), + polygonOffset: (gl, values, cache2) => gl.polygonOffset(getValue(32824, values, cache2), getValue(10752, values, cache2)), + sampleCoverage: (gl, values, cache2) => gl.sampleCoverage(getValue(32938, values, cache2), getValue(32939, values, cache2)), + stencilFuncFront: (gl, values, cache2) => gl.stencilFuncSeparate(1028, getValue(2962, values, cache2), getValue(2967, values, cache2), getValue(2963, values, cache2)), + stencilFuncBack: (gl, values, cache2) => gl.stencilFuncSeparate(1029, getValue(34816, values, cache2), getValue(36003, values, cache2), getValue(36004, values, cache2)), + stencilOpFront: (gl, values, cache2) => gl.stencilOpSeparate(1028, getValue(2964, values, cache2), getValue(2965, values, cache2), getValue(2966, values, cache2)), + stencilOpBack: (gl, values, cache2) => gl.stencilOpSeparate(1029, getValue(34817, values, cache2), getValue(34818, values, cache2), getValue(34819, values, cache2)) + }; + GL_HOOKED_SETTERS = { + // GENERIC SETTERS + enable: (update, capability) => update({ + [capability]: true + }), + disable: (update, capability) => update({ + [capability]: false + }), + pixelStorei: (update, pname, value) => update({ + [pname]: value + }), + hint: (update, pname, value) => update({ + [pname]: value + }), + // SPECIFIC SETTERS + useProgram: (update, value) => update({ + [35725]: value + }), + bindRenderbuffer: (update, target2, value) => update({ + [36007]: value + }), + bindTransformFeedback: (update, target2, value) => update({ + [36389]: value + }), + bindVertexArray: (update, value) => update({ + [34229]: value + }), + bindFramebuffer: (update, target2, framebuffer) => { + switch (target2) { + case 36160: + return update({ + [36006]: framebuffer, + [36010]: framebuffer + }); + case 36009: + return update({ [36006]: framebuffer }); + case 36008: + return update({ [36010]: framebuffer }); + default: + return null; + } + }, + bindBuffer: (update, target2, buffer) => { + const pname = { + [34962]: [34964], + [36662]: [36662], + [36663]: [36663], + [35051]: [35053], + [35052]: [35055] + }[target2]; + if (pname) { + return update({ [pname]: buffer }); + } + return { valueChanged: true }; + }, + blendColor: (update, r, g, b, a) => update({ + [32773]: new Float32Array([r, g, b, a]) + }), + blendEquation: (update, mode) => update({ + [32777]: mode, + [34877]: mode + }), + blendEquationSeparate: (update, modeRGB, modeAlpha) => update({ + [32777]: modeRGB, + [34877]: modeAlpha + }), + blendFunc: (update, src, dst) => update({ + [32969]: src, + [32968]: dst, + [32971]: src, + [32970]: dst + }), + blendFuncSeparate: (update, srcRGB, dstRGB, srcAlpha, dstAlpha) => update({ + [32969]: srcRGB, + [32968]: dstRGB, + [32971]: srcAlpha, + [32970]: dstAlpha + }), + clearColor: (update, r, g, b, a) => update({ + [3106]: new Float32Array([r, g, b, a]) + }), + clearDepth: (update, depth) => update({ + [2931]: depth + }), + clearStencil: (update, s) => update({ + [2961]: s + }), + colorMask: (update, r, g, b, a) => update({ + [3107]: [r, g, b, a] + }), + cullFace: (update, mode) => update({ + [2885]: mode + }), + depthFunc: (update, func) => update({ + [2932]: func + }), + depthRange: (update, zNear, zFar) => update({ + [2928]: new Float32Array([zNear, zFar]) + }), + depthMask: (update, mask) => update({ + [2930]: mask + }), + frontFace: (update, face) => update({ + [2886]: face + }), + lineWidth: (update, width) => update({ + [2849]: width + }), + polygonOffset: (update, factor, units) => update({ + [32824]: factor, + [10752]: units + }), + sampleCoverage: (update, value, invert2) => update({ + [32938]: value, + [32939]: invert2 + }), + scissor: (update, x, y, width, height) => update({ + [3088]: new Int32Array([x, y, width, height]) + }), + stencilMask: (update, mask) => update({ + [2968]: mask, + [36005]: mask + }), + stencilMaskSeparate: (update, face, mask) => update({ + [face === 1028 ? 2968 : 36005]: mask + }), + stencilFunc: (update, func, ref, mask) => update({ + [2962]: func, + [2967]: ref, + [2963]: mask, + [34816]: func, + [36003]: ref, + [36004]: mask + }), + stencilFuncSeparate: (update, face, func, ref, mask) => update({ + [face === 1028 ? 2962 : 34816]: func, + [face === 1028 ? 2967 : 36003]: ref, + [face === 1028 ? 2963 : 36004]: mask + }), + stencilOp: (update, fail, zfail, zpass) => update({ + [2964]: fail, + [2965]: zfail, + [2966]: zpass, + [34817]: fail, + [34818]: zfail, + [34819]: zpass + }), + stencilOpSeparate: (update, face, fail, zfail, zpass) => update({ + [face === 1028 ? 2964 : 34817]: fail, + [face === 1028 ? 2965 : 34818]: zfail, + [face === 1028 ? 2966 : 34819]: zpass + }), + viewport: (update, x, y, width, height) => update({ + [2978]: [x, y, width, height] + }) + }; + isEnabled = (gl, key) => gl.isEnabled(key); + GL_PARAMETER_GETTERS = { + [3042]: isEnabled, + [2884]: isEnabled, + [2929]: isEnabled, + [3024]: isEnabled, + [32823]: isEnabled, + [32926]: isEnabled, + [32928]: isEnabled, + [3089]: isEnabled, + [2960]: isEnabled, + [35977]: isEnabled + }; + NON_CACHE_PARAMETERS = /* @__PURE__ */ new Set([ + 34016, + 36388, + 36387, + 35983, + 35368, + 34965, + 35739, + 35738, + 3074, + 34853, + 34854, + 34855, + 34856, + 34857, + 34858, + 34859, + 34860, + 34861, + 34862, + 34863, + 34864, + 34865, + 34866, + 34867, + 34868, + 35097, + 32873, + 35869, + 32874, + 34068 + ]); + } + }); + + // node_modules/@luma.gl/webgl/dist/context/parameters/unified-parameter-api.js + function setGLParameters(gl, parameters) { + if (isObjectEmpty2(parameters)) { + return; + } + const compositeSetters = {}; + for (const key in parameters) { + const glConstant = Number(key); + const setter = GL_PARAMETER_SETTERS[key]; + if (setter) { + if (typeof setter === "string") { + compositeSetters[setter] = true; + } else { + setter(gl, parameters[key], glConstant); + } + } + } + const cache2 = gl.lumaState?.cache; + if (cache2) { + for (const key in compositeSetters) { + const compositeSetter = GL_COMPOSITE_PARAMETER_SETTERS[key]; + compositeSetter(gl, parameters, cache2); + } + } + } + function getGLParameters(gl, parameters = GL_PARAMETER_DEFAULTS) { + if (typeof parameters === "number") { + const key = parameters; + const getter = GL_PARAMETER_GETTERS[key]; + return getter ? getter(gl, key) : gl.getParameter(key); + } + const parameterKeys = Array.isArray(parameters) ? parameters : Object.keys(parameters); + const state = {}; + for (const key of parameterKeys) { + const getter = GL_PARAMETER_GETTERS[key]; + state[key] = getter ? getter(gl, Number(key)) : gl.getParameter(Number(key)); + } + return state; + } + function resetGLParameters(gl) { + setGLParameters(gl, GL_PARAMETER_DEFAULTS); + } + function isObjectEmpty2(object) { + for (const key in object) { + return false; + } + return true; + } + var init_unified_parameter_api = __esm({ + "node_modules/@luma.gl/webgl/dist/context/parameters/unified-parameter-api.js"() { + init_webgl_parameter_tables(); + } + }); + + // node_modules/@luma.gl/webgl/dist/context/state-tracker/deep-array-equal.js + function deepArrayEqual(x, y) { + if (x === y) { + return true; + } + if (isArray3(x) && isArray3(y) && x.length === y.length) { + for (let i = 0; i < x.length; ++i) { + if (x[i] !== y[i]) { + return false; + } + } + return true; + } + return false; + } + function isArray3(x) { + return Array.isArray(x) || ArrayBuffer.isView(x); + } + var init_deep_array_equal = __esm({ + "node_modules/@luma.gl/webgl/dist/context/state-tracker/deep-array-equal.js"() { + } + }); + + // node_modules/@luma.gl/webgl/dist/context/state-tracker/webgl-state-tracker.js + function installGetterOverride(gl, functionName) { + const originalGetterFunc = gl[functionName].bind(gl); + gl[functionName] = function get(pname) { + if (pname === void 0 || NON_CACHE_PARAMETERS.has(pname)) { + return originalGetterFunc(pname); + } + const glState = WebGLStateTracker.get(gl); + if (!(pname in glState.cache)) { + glState.cache[pname] = originalGetterFunc(pname); + } + return glState.enable ? ( + // Call the getter the params so that it can e.g. serve from a cache + glState.cache[pname] + ) : ( + // Optionally call the original function to do a "hard" query from the WebGL2RenderingContext + originalGetterFunc(pname) + ); + }; + Object.defineProperty(gl[functionName], "name", { + value: `${functionName}-from-cache`, + configurable: false + }); + } + function installSetterSpy(gl, functionName, setter) { + if (!gl[functionName]) { + return; + } + const originalSetterFunc = gl[functionName].bind(gl); + gl[functionName] = function set5(...params) { + const glState = WebGLStateTracker.get(gl); + const { valueChanged, oldValue } = setter(glState._updateCache, ...params); + if (valueChanged) { + originalSetterFunc(...params); + } + return oldValue; + }; + Object.defineProperty(gl[functionName], "name", { + value: `${functionName}-to-cache`, + configurable: false + }); + } + function installProgramSpy(gl) { + const originalUseProgram = gl.useProgram.bind(gl); + gl.useProgram = function useProgramLuma(handle) { + const glState = WebGLStateTracker.get(gl); + if (glState.program !== handle) { + originalUseProgram(handle); + glState.program = handle; + } + }; + } + var WebGLStateTracker; + var init_webgl_state_tracker = __esm({ + "node_modules/@luma.gl/webgl/dist/context/state-tracker/webgl-state-tracker.js"() { + init_unified_parameter_api(); + init_deep_array_equal(); + init_webgl_parameter_tables(); + WebGLStateTracker = class { + static get(gl) { + return gl.lumaState; + } + gl; + program = null; + stateStack = []; + enable = true; + cache = null; + log; + initialized = false; + constructor(gl, props) { + this.gl = gl; + this.log = props?.log || (() => { + }); + this._updateCache = this._updateCache.bind(this); + Object.seal(this); + } + push(values = {}) { + this.stateStack.push({}); + } + pop() { + const oldValues = this.stateStack[this.stateStack.length - 1]; + setGLParameters(this.gl, oldValues); + this.stateStack.pop(); + } + /** + * Initialize WebGL state caching on a context + * can be called multiple times to enable/disable + * + * @note After calling this function, context state will be cached + * .push() and .pop() will be available for saving, + * temporarily modifying, and then restoring state. + */ + trackState(gl, options) { + this.cache = options?.copyState ? getGLParameters(gl) : Object.assign({}, GL_PARAMETER_DEFAULTS); + if (this.initialized) { + throw new Error("WebGLStateTracker"); + } + this.initialized = true; + this.gl.lumaState = this; + installProgramSpy(gl); + for (const key in GL_HOOKED_SETTERS) { + const setter = GL_HOOKED_SETTERS[key]; + installSetterSpy(gl, key, setter); + } + installGetterOverride(gl, "getParameter"); + installGetterOverride(gl, "isEnabled"); + } + /** + // interceptor for context set functions - update our cache and our stack + // values (Object) - the key values for this setter + * @param values + * @returns + */ + _updateCache(values) { + let valueChanged = false; + let oldValue; + const oldValues = this.stateStack.length > 0 ? this.stateStack[this.stateStack.length - 1] : null; + for (const key in values) { + const value = values[key]; + const cached = this.cache[key]; + if (!deepArrayEqual(value, cached)) { + valueChanged = true; + oldValue = cached; + if (oldValues && !(key in oldValues)) { + oldValues[key] = cached; + } + this.cache[key] = value; + } + } + return { valueChanged, oldValue }; + } + }; + } + }); + + // node_modules/@luma.gl/webgl/dist/context/helpers/create-browser-context.js + function createBrowserContext(canvas, props, webglContextAttributes) { + let errorMessage = ""; + const onCreateError = (event) => { + const statusMessage = event.statusMessage; + if (statusMessage) { + errorMessage ||= statusMessage; + } + }; + canvas.addEventListener("webglcontextcreationerror", onCreateError, false); + const allowSoftwareRenderer = webglContextAttributes.failIfMajorPerformanceCaveat !== true; + const webglProps = { + preserveDrawingBuffer: true, + ...webglContextAttributes, + // Always start by requesting a high-performance context. + failIfMajorPerformanceCaveat: true + }; + let gl = null; + try { + gl ||= canvas.getContext("webgl2", webglProps); + if (!gl && webglProps.failIfMajorPerformanceCaveat) { + errorMessage ||= "Only software GPU is available. Set `failIfMajorPerformanceCaveat: false` to allow."; + } + let softwareRenderer = false; + if (!gl && allowSoftwareRenderer) { + webglProps.failIfMajorPerformanceCaveat = false; + gl = canvas.getContext("webgl2", webglProps); + softwareRenderer = true; + } + if (!gl) { + gl = canvas.getContext("webgl", {}); + if (gl) { + gl = null; + errorMessage ||= "Your browser only supports WebGL1"; + } + } + if (!gl) { + errorMessage ||= "Your browser does not support WebGL"; + throw new Error(`Failed to create WebGL context: ${errorMessage}`); + } + const luma2 = getWebGLContextData(gl); + luma2.softwareRenderer = softwareRenderer; + const { onContextLost, onContextRestored } = props; + canvas.addEventListener("webglcontextlost", (event) => onContextLost(event), false); + canvas.addEventListener("webglcontextrestored", (event) => onContextRestored(event), false); + return gl; + } finally { + canvas.removeEventListener("webglcontextcreationerror", onCreateError, false); + } + } + var init_create_browser_context = __esm({ + "node_modules/@luma.gl/webgl/dist/context/helpers/create-browser-context.js"() { + init_webgl_context_data(); + } + }); + + // node_modules/@luma.gl/webgl/dist/context/helpers/webgl-extensions.js + function getWebGLExtension(gl, name2, extensions) { + if (extensions[name2] === void 0) { + extensions[name2] = gl.getExtension(name2) || null; + } + return extensions[name2]; + } + var init_webgl_extensions = __esm({ + "node_modules/@luma.gl/webgl/dist/context/helpers/webgl-extensions.js"() { + } + }); + + // node_modules/@luma.gl/webgl/dist/adapter/device-helpers/webgl-device-info.js + function getDeviceInfo(gl, extensions) { + const vendorMasked = gl.getParameter(7936); + const rendererMasked = gl.getParameter(7937); + getWebGLExtension(gl, "WEBGL_debug_renderer_info", extensions); + const ext = extensions.WEBGL_debug_renderer_info; + const vendorUnmasked = gl.getParameter(ext ? ext.UNMASKED_VENDOR_WEBGL : 7936); + const rendererUnmasked = gl.getParameter(ext ? ext.UNMASKED_RENDERER_WEBGL : 7937); + const vendor = vendorUnmasked || vendorMasked; + const renderer = rendererUnmasked || rendererMasked; + const version2 = gl.getParameter(7938); + const gpu = identifyGPUVendor(vendor, renderer); + const gpuBackend = identifyGPUBackend(vendor, renderer); + const gpuType = identifyGPUType(vendor, renderer); + const shadingLanguage = "glsl"; + const shadingLanguageVersion = 300; + return { + type: "webgl", + gpu, + gpuType, + gpuBackend, + vendor, + renderer, + version: version2, + shadingLanguage, + shadingLanguageVersion + }; + } + function identifyGPUVendor(vendor, renderer) { + if (/NVIDIA/i.exec(vendor) || /NVIDIA/i.exec(renderer)) { + return "nvidia"; + } + if (/INTEL/i.exec(vendor) || /INTEL/i.exec(renderer)) { + return "intel"; + } + if (/Apple/i.exec(vendor) || /Apple/i.exec(renderer)) { + return "apple"; + } + if (/AMD/i.exec(vendor) || /AMD/i.exec(renderer) || /ATI/i.exec(vendor) || /ATI/i.exec(renderer)) { + return "amd"; + } + if (/SwiftShader/i.exec(vendor) || /SwiftShader/i.exec(renderer)) { + return "software"; + } + return "unknown"; + } + function identifyGPUBackend(vendor, renderer) { + if (/Metal/i.exec(vendor) || /Metal/i.exec(renderer)) { + return "metal"; + } + if (/ANGLE/i.exec(vendor) || /ANGLE/i.exec(renderer)) { + return "opengl"; + } + return "unknown"; + } + function identifyGPUType(vendor, renderer) { + if (/SwiftShader/i.exec(vendor) || /SwiftShader/i.exec(renderer)) { + return "cpu"; + } + const gpuVendor = identifyGPUVendor(vendor, renderer); + switch (gpuVendor) { + case "apple": + return isAppleSiliconGPU(vendor, renderer) ? "integrated" : "unknown"; + case "intel": + return "integrated"; + case "software": + return "cpu"; + case "unknown": + return "unknown"; + default: + return "discrete"; + } + } + function isAppleSiliconGPU(vendor, renderer) { + return /Apple (M\d|A\d|GPU)/i.test(`${vendor} ${renderer}`); + } + var init_webgl_device_info = __esm({ + "node_modules/@luma.gl/webgl/dist/adapter/device-helpers/webgl-device-info.js"() { + init_webgl_extensions(); + } + }); + + // node_modules/@luma.gl/webgl/dist/adapter/converters/webgl-vertex-formats.js + function getGLFromVertexType(dataType) { + switch (dataType) { + case "uint8": + return 5121; + case "sint8": + return 5120; + case "unorm8": + return 5121; + case "snorm8": + return 5120; + case "uint16": + return 5123; + case "sint16": + return 5122; + case "unorm16": + return 5123; + case "snorm16": + return 5122; + case "uint32": + return 5125; + case "sint32": + return 5124; + // WebGPU does not support normalized 32 bit integer attributes + // case 'unorm32': return GL.UNSIGNED_INT; + // case 'snorm32': return GL.INT; + case "float16": + return 5131; + case "float32": + return 5126; + } + throw new Error(String(dataType)); + } + var init_webgl_vertex_formats = __esm({ + "node_modules/@luma.gl/webgl/dist/adapter/converters/webgl-vertex-formats.js"() { + } + }); + + // node_modules/@luma.gl/webgl/dist/adapter/converters/webgl-texture-table.js + function isTextureFeature(feature) { + return feature in TEXTURE_FEATURES; + } + function checkTextureFeature(gl, feature, extensions) { + return hasTextureFeature(gl, feature, extensions, /* @__PURE__ */ new Set()); + } + function hasTextureFeature(gl, feature, extensions, seenFeatures) { + const definition = TEXTURE_FEATURES[feature]; + if (!definition) { + return false; + } + if (seenFeatures.has(feature)) { + return false; + } + seenFeatures.add(feature); + const hasDependentFeatures = (definition.features || []).every((dependentFeature) => hasTextureFeature(gl, dependentFeature, extensions, seenFeatures)); + seenFeatures.delete(feature); + if (!hasDependentFeatures) { + return false; + } + return (definition.extensions || []).every((extension) => Boolean(getWebGLExtension(gl, extension, extensions))); + } + function getTextureFormatCapabilitiesWebGL(gl, formatSupport, extensions) { + let supported = formatSupport.create; + const webglFormatInfo = WEBGL_TEXTURE_FORMATS[formatSupport.format]; + if (webglFormatInfo?.gl === void 0) { + supported = false; + } + if (webglFormatInfo?.x) { + supported = supported && Boolean(getWebGLExtension(gl, webglFormatInfo.x, extensions)); + } + if (formatSupport.format === "stencil8") { + supported = false; + } + const renderFeatureSupported = webglFormatInfo?.r === false ? false : webglFormatInfo?.r === void 0 || checkTextureFeature(gl, webglFormatInfo.r, extensions); + const renderable = supported && formatSupport.render && renderFeatureSupported && isColorRenderableTextureFormat(gl, formatSupport.format, extensions); + return { + format: formatSupport.format, + // @ts-ignore + create: supported && formatSupport.create, + // @ts-ignore + render: renderable, + // @ts-ignore + filter: supported && formatSupport.filter, + // @ts-ignore + blend: supported && formatSupport.blend, + // @ts-ignore + store: supported && formatSupport.store + }; + } + function isColorRenderableTextureFormat(gl, format2, extensions) { + const webglFormatInfo = WEBGL_TEXTURE_FORMATS[format2]; + const internalFormat = webglFormatInfo?.gl; + if (internalFormat === void 0) { + return false; + } + if (webglFormatInfo?.x && !getWebGLExtension(gl, webglFormatInfo.x, extensions)) { + return false; + } + const previousTexture = gl.getParameter(32873); + const previousFramebuffer = gl.getParameter(36006); + const texture = gl.createTexture(); + const framebuffer = gl.createFramebuffer(); + if (!texture || !framebuffer) { + return false; + } + const noError = Number(0); + let error = Number(gl.getError()); + while (error !== noError) { + error = gl.getError(); + } + let renderable = false; + try { + gl.bindTexture(3553, texture); + gl.texStorage2D(3553, 1, internalFormat, 1, 1); + if (Number(gl.getError()) !== noError) { + return false; + } + gl.bindFramebuffer(36160, framebuffer); + gl.framebufferTexture2D(36160, 36064, 3553, texture, 0); + renderable = Number(gl.checkFramebufferStatus(36160)) === Number(36053) && Number(gl.getError()) === noError; + } finally { + gl.bindFramebuffer(36160, previousFramebuffer); + gl.deleteFramebuffer(framebuffer); + gl.bindTexture(3553, previousTexture); + gl.deleteTexture(texture); + } + return renderable; + } + function getTextureFormatWebGL(format2) { + const formatData = WEBGL_TEXTURE_FORMATS[format2]; + const webglFormat = convertTextureFormatToGL(format2); + const decoded = textureFormatDecoder.getInfo(format2); + if (decoded.compressed) { + formatData.dataFormat = webglFormat; + } + return { + internalFormat: webglFormat, + format: formatData?.dataFormat || getWebGLPixelDataFormat(decoded.channels, decoded.integer, decoded.normalized, webglFormat), + // depth formats don't have a type + type: decoded.dataType ? getGLFromVertexType(decoded.dataType) : formatData?.types?.[0] || 5121, + compressed: decoded.compressed || false + }; + } + function getDepthStencilAttachmentWebGL(format2) { + const formatInfo = textureFormatDecoder.getInfo(format2); + switch (formatInfo.attachment) { + case "depth": + return 36096; + case "stencil": + return 36128; + case "depth-stencil": + return 33306; + default: + throw new Error(`Not a depth stencil format: ${format2}`); + } + } + function getWebGLPixelDataFormat(channels, integer, normalized, format2) { + if (format2 === 6408 || format2 === 6407) { + return format2; + } + switch (channels) { + case "r": + return integer && !normalized ? 36244 : 6403; + case "rg": + return integer && !normalized ? 33320 : 33319; + case "rgb": + return integer && !normalized ? 36248 : 6407; + case "rgba": + return integer && !normalized ? 36249 : 6408; + case "bgra": + throw new Error("bgra pixels not supported by WebGL"); + default: + return 6408; + } + } + function convertTextureFormatToGL(format2) { + const formatInfo = WEBGL_TEXTURE_FORMATS[format2]; + const webglFormat = formatInfo?.gl; + if (webglFormat === void 0) { + throw new Error(`Unsupported texture format ${format2}`); + } + return webglFormat; + } + var X_S3TC, X_S3TC_SRGB, X_RGTC, X_BPTC, X_ETC2, X_ASTC, X_ETC1, X_PVRTC, X_ATC, EXT_texture_norm16, EXT_render_snorm, EXT_color_buffer_float, SNORM8_COLOR_RENDERABLE, NORM16_COLOR_RENDERABLE, SNORM16_COLOR_RENDERABLE, FLOAT16_COLOR_RENDERABLE, FLOAT32_COLOR_RENDERABLE, RGB9E5UFLOAT_COLOR_RENDERABLE, TEXTURE_FEATURES, WEBGL_TEXTURE_FORMATS; + var init_webgl_texture_table = __esm({ + "node_modules/@luma.gl/webgl/dist/adapter/converters/webgl-texture-table.js"() { + init_dist4(); + init_webgl_extensions(); + init_webgl_vertex_formats(); + X_S3TC = "WEBGL_compressed_texture_s3tc"; + X_S3TC_SRGB = "WEBGL_compressed_texture_s3tc_srgb"; + X_RGTC = "EXT_texture_compression_rgtc"; + X_BPTC = "EXT_texture_compression_bptc"; + X_ETC2 = "WEBGL_compressed_texture_etc"; + X_ASTC = "WEBGL_compressed_texture_astc"; + X_ETC1 = "WEBGL_compressed_texture_etc1"; + X_PVRTC = "WEBGL_compressed_texture_pvrtc"; + X_ATC = "WEBGL_compressed_texture_atc"; + EXT_texture_norm16 = "EXT_texture_norm16"; + EXT_render_snorm = "EXT_render_snorm"; + EXT_color_buffer_float = "EXT_color_buffer_float"; + SNORM8_COLOR_RENDERABLE = "snorm8-renderable-webgl"; + NORM16_COLOR_RENDERABLE = "norm16-renderable-webgl"; + SNORM16_COLOR_RENDERABLE = "snorm16-renderable-webgl"; + FLOAT16_COLOR_RENDERABLE = "float16-renderable-webgl"; + FLOAT32_COLOR_RENDERABLE = "float32-renderable-webgl"; + RGB9E5UFLOAT_COLOR_RENDERABLE = "rgb9e5ufloat-renderable-webgl"; + TEXTURE_FEATURES = { + "float32-renderable-webgl": { extensions: [EXT_color_buffer_float] }, + "float16-renderable-webgl": { extensions: ["EXT_color_buffer_half_float"] }, + "rgb9e5ufloat-renderable-webgl": { extensions: ["WEBGL_render_shared_exponent"] }, + "snorm8-renderable-webgl": { extensions: [EXT_render_snorm] }, + "norm16-webgl": { extensions: [EXT_texture_norm16] }, + "norm16-renderable-webgl": { features: ["norm16-webgl"] }, + "snorm16-renderable-webgl": { features: ["norm16-webgl"], extensions: [EXT_render_snorm] }, + "float32-filterable": { extensions: ["OES_texture_float_linear"] }, + "float16-filterable-webgl": { extensions: ["OES_texture_half_float_linear"] }, + "texture-filterable-anisotropic-webgl": { extensions: ["EXT_texture_filter_anisotropic"] }, + "texture-blend-float-webgl": { extensions: ["EXT_float_blend"] }, + "texture-compression-bc": { extensions: [X_S3TC, X_S3TC_SRGB, X_RGTC, X_BPTC] }, + // 'texture-compression-bc3-srgb-webgl': [X_S3TC_SRGB], + // 'texture-compression-bc3-webgl': [X_S3TC], + "texture-compression-bc5-webgl": { extensions: [X_RGTC] }, + "texture-compression-bc7-webgl": { extensions: [X_BPTC] }, + "texture-compression-etc2": { extensions: [X_ETC2] }, + "texture-compression-astc": { extensions: [X_ASTC] }, + "texture-compression-etc1-webgl": { extensions: [X_ETC1] }, + "texture-compression-pvrtc-webgl": { extensions: [X_PVRTC] }, + "texture-compression-atc-webgl": { extensions: [X_ATC] } + }; + WEBGL_TEXTURE_FORMATS = { + // 8-bit formats + "r8unorm": { gl: 33321, rb: true }, + "r8snorm": { gl: 36756, r: SNORM8_COLOR_RENDERABLE }, + "r8uint": { gl: 33330, rb: true }, + "r8sint": { gl: 33329, rb: true }, + // 16-bit formats + "rg8unorm": { gl: 33323, rb: true }, + "rg8snorm": { gl: 36757, r: SNORM8_COLOR_RENDERABLE }, + "rg8uint": { gl: 33336, rb: true }, + "rg8sint": { gl: 33335, rb: true }, + "r16uint": { gl: 33332, rb: true }, + "r16sint": { gl: 33331, rb: true }, + "r16float": { gl: 33325, rb: true, r: FLOAT16_COLOR_RENDERABLE }, + "r16unorm": { gl: 33322, rb: true, r: NORM16_COLOR_RENDERABLE }, + "r16snorm": { gl: 36760, r: SNORM16_COLOR_RENDERABLE }, + // Packed 16-bit formats + "rgba4unorm-webgl": { gl: 32854, rb: true }, + "rgb565unorm-webgl": { gl: 36194, rb: true }, + "rgb5a1unorm-webgl": { gl: 32855, rb: true }, + // 24-bit formats + "rgb8unorm-webgl": { gl: 32849 }, + "rgb8snorm-webgl": { gl: 36758 }, + // 32-bit formats + "rgba8unorm": { gl: 32856 }, + "rgba8unorm-srgb": { gl: 35907 }, + "rgba8snorm": { gl: 36759, r: SNORM8_COLOR_RENDERABLE }, + "rgba8uint": { gl: 36220 }, + "rgba8sint": { gl: 36238 }, + // reverse colors, webgpu only + "bgra8unorm": {}, + "bgra8unorm-srgb": {}, + "rg16uint": { gl: 33338 }, + "rg16sint": { gl: 33337 }, + "rg16float": { gl: 33327, rb: true, r: FLOAT16_COLOR_RENDERABLE }, + "rg16unorm": { gl: 33324, r: NORM16_COLOR_RENDERABLE }, + "rg16snorm": { gl: 36761, r: SNORM16_COLOR_RENDERABLE }, + "r32uint": { gl: 33334, rb: true }, + "r32sint": { gl: 33333, rb: true }, + "r32float": { gl: 33326, r: FLOAT32_COLOR_RENDERABLE }, + // Packed 32-bit formats + "rgb9e5ufloat": { gl: 35901, r: RGB9E5UFLOAT_COLOR_RENDERABLE }, + // , filter: true}, + "rg11b10ufloat": { gl: 35898, rb: true }, + "rgb10a2unorm": { gl: 32857, rb: true }, + "rgb10a2uint": { gl: 36975, rb: true }, + // 48-bit formats + "rgb16unorm-webgl": { gl: 32852, r: false }, + // rgb not renderable + "rgb16snorm-webgl": { gl: 36762, r: false }, + // rgb not renderable + // 64-bit formats + "rg32uint": { gl: 33340, rb: true }, + "rg32sint": { gl: 33339, rb: true }, + "rg32float": { gl: 33328, rb: true, r: FLOAT32_COLOR_RENDERABLE }, + "rgba16uint": { gl: 36214, rb: true }, + "rgba16sint": { gl: 36232, rb: true }, + "rgba16float": { gl: 34842, r: FLOAT16_COLOR_RENDERABLE }, + "rgba16unorm": { gl: 32859, rb: true, r: NORM16_COLOR_RENDERABLE }, + "rgba16snorm": { gl: 36763, r: SNORM16_COLOR_RENDERABLE }, + // 96-bit formats (deprecated!) + "rgb32float-webgl": { gl: 34837, x: EXT_color_buffer_float, r: FLOAT32_COLOR_RENDERABLE, dataFormat: 6407, types: [5126] }, + // 128-bit formats + "rgba32uint": { gl: 36208, rb: true }, + "rgba32sint": { gl: 36226, rb: true }, + "rgba32float": { gl: 34836, rb: true, r: FLOAT32_COLOR_RENDERABLE }, + // Depth and stencil formats + "stencil8": { gl: 36168, rb: true }, + // 8 stencil bits + "depth16unorm": { gl: 33189, dataFormat: 6402, types: [5123], rb: true }, + // 16 depth bits + "depth24plus": { gl: 33190, dataFormat: 6402, types: [5125] }, + "depth32float": { gl: 36012, dataFormat: 6402, types: [5126], rb: true }, + // The depth component of the "depth24plus" and "depth24plus-stencil8" formats may be implemented as either a 24-bit depth value or a "depth32float" value. + "depth24plus-stencil8": { gl: 35056, rb: true, depthTexture: true, dataFormat: 34041, types: [34042] }, + // "depth32float-stencil8" feature - TODO below is render buffer only? + "depth32float-stencil8": { gl: 36013, dataFormat: 34041, types: [36269], rb: true }, + // BC compressed formats: check device.features.has("texture-compression-bc"); + "bc1-rgb-unorm-webgl": { gl: 33776, x: X_S3TC }, + "bc1-rgb-unorm-srgb-webgl": { gl: 35916, x: X_S3TC_SRGB }, + "bc1-rgba-unorm": { gl: 33777, x: X_S3TC }, + "bc1-rgba-unorm-srgb": { gl: 35916, x: X_S3TC_SRGB }, + "bc2-rgba-unorm": { gl: 33778, x: X_S3TC }, + "bc2-rgba-unorm-srgb": { gl: 35918, x: X_S3TC_SRGB }, + "bc3-rgba-unorm": { gl: 33779, x: X_S3TC }, + "bc3-rgba-unorm-srgb": { gl: 35919, x: X_S3TC_SRGB }, + "bc4-r-unorm": { gl: 36283, x: X_RGTC }, + "bc4-r-snorm": { gl: 36284, x: X_RGTC }, + "bc5-rg-unorm": { gl: 36285, x: X_RGTC }, + "bc5-rg-snorm": { gl: 36286, x: X_RGTC }, + "bc6h-rgb-ufloat": { gl: 36495, x: X_BPTC }, + "bc6h-rgb-float": { gl: 36494, x: X_BPTC }, + "bc7-rgba-unorm": { gl: 36492, x: X_BPTC }, + "bc7-rgba-unorm-srgb": { gl: 36493, x: X_BPTC }, + // WEBGL_compressed_texture_etc: device.features.has("texture-compression-etc2") + // Note: Supposedly guaranteed availability compressed formats in WebGL2, but through CPU decompression + "etc2-rgb8unorm": { gl: 37492 }, + "etc2-rgb8unorm-srgb": { gl: 37494 }, + "etc2-rgb8a1unorm": { gl: 37496 }, + "etc2-rgb8a1unorm-srgb": { gl: 37497 }, + "etc2-rgba8unorm": { gl: 37493 }, + "etc2-rgba8unorm-srgb": { gl: 37495 }, + "eac-r11unorm": { gl: 37488 }, + "eac-r11snorm": { gl: 37489 }, + "eac-rg11unorm": { gl: 37490 }, + "eac-rg11snorm": { gl: 37491 }, + // X_ASTC compressed formats: device.features.has("texture-compression-astc") + "astc-4x4-unorm": { gl: 37808 }, + "astc-4x4-unorm-srgb": { gl: 37840 }, + "astc-5x4-unorm": { gl: 37809 }, + "astc-5x4-unorm-srgb": { gl: 37841 }, + "astc-5x5-unorm": { gl: 37810 }, + "astc-5x5-unorm-srgb": { gl: 37842 }, + "astc-6x5-unorm": { gl: 37811 }, + "astc-6x5-unorm-srgb": { gl: 37843 }, + "astc-6x6-unorm": { gl: 37812 }, + "astc-6x6-unorm-srgb": { gl: 37844 }, + "astc-8x5-unorm": { gl: 37813 }, + "astc-8x5-unorm-srgb": { gl: 37845 }, + "astc-8x6-unorm": { gl: 37814 }, + "astc-8x6-unorm-srgb": { gl: 37846 }, + "astc-8x8-unorm": { gl: 37815 }, + "astc-8x8-unorm-srgb": { gl: 37847 }, + "astc-10x5-unorm": { gl: 37816 }, + "astc-10x5-unorm-srgb": { gl: 37848 }, + "astc-10x6-unorm": { gl: 37817 }, + "astc-10x6-unorm-srgb": { gl: 37849 }, + "astc-10x8-unorm": { gl: 37818 }, + "astc-10x8-unorm-srgb": { gl: 37850 }, + "astc-10x10-unorm": { gl: 37819 }, + "astc-10x10-unorm-srgb": { gl: 37851 }, + "astc-12x10-unorm": { gl: 37820 }, + "astc-12x10-unorm-srgb": { gl: 37852 }, + "astc-12x12-unorm": { gl: 37821 }, + "astc-12x12-unorm-srgb": { gl: 37853 }, + // WEBGL_compressed_texture_pvrtc + "pvrtc-rgb4unorm-webgl": { gl: 35840 }, + "pvrtc-rgba4unorm-webgl": { gl: 35842 }, + "pvrtc-rgb2unorm-webgl": { gl: 35841 }, + "pvrtc-rgba2unorm-webgl": { gl: 35843 }, + // WEBGL_compressed_texture_etc1 + "etc1-rbg-unorm-webgl": { gl: 36196 }, + // WEBGL_compressed_texture_atc + "atc-rgb-unorm-webgl": { gl: 35986 }, + "atc-rgba-unorm-webgl": { gl: 35986 }, + "atc-rgbai-unorm-webgl": { gl: 34798 } + }; + } + }); + + // node_modules/@luma.gl/webgl/dist/adapter/device-helpers/webgl-device-features.js + var WEBGL_FEATURES, WebGLDeviceFeatures; + var init_webgl_device_features = __esm({ + "node_modules/@luma.gl/webgl/dist/adapter/device-helpers/webgl-device-features.js"() { + init_dist4(); + init_webgl_extensions(); + init_webgl_texture_table(); + WEBGL_FEATURES = { + // optional WebGPU features + "depth-clip-control": "EXT_depth_clamp", + // TODO these seem subtly different + "timestamp-query": "EXT_disjoint_timer_query_webgl2", + // "indirect-first-instance" + // Textures are handled by getTextureFeatures() + // 'depth32float-stencil8' // GPUTextureFormat 'depth32float-stencil8' + // optional WebGL features + "compilation-status-async-webgl": "KHR_parallel_shader_compile", + "polygon-mode-webgl": "WEBGL_polygon_mode", + "provoking-vertex-webgl": "WEBGL_provoking_vertex", + "shader-clip-cull-distance-webgl": "WEBGL_clip_cull_distance", + "shader-noperspective-interpolation-webgl": "NV_shader_noperspective_interpolation", + "shader-conservative-depth-webgl": "EXT_conservative_depth" + // Textures are handled by getTextureFeatures() + }; + WebGLDeviceFeatures = class extends DeviceFeatures { + gl; + extensions; + testedFeatures = /* @__PURE__ */ new Set(); + constructor(gl, extensions, disabledFeatures) { + super([], disabledFeatures); + this.gl = gl; + this.extensions = extensions; + getWebGLExtension(gl, "EXT_color_buffer_float", extensions); + } + *[Symbol.iterator]() { + const features = this.getFeatures(); + for (const feature of features) { + if (this.has(feature)) { + yield feature; + } + } + return []; + } + has(feature) { + if (this.disabledFeatures?.[feature]) { + return false; + } + if (!this.testedFeatures.has(feature)) { + this.testedFeatures.add(feature); + if (isTextureFeature(feature) && checkTextureFeature(this.gl, feature, this.extensions)) { + this.features.add(feature); + } + if (this.getWebGLFeature(feature)) { + this.features.add(feature); + } + } + return this.features.has(feature); + } + // FOR DEVICE + initializeFeatures() { + const features = this.getFeatures().filter((feature) => feature !== "polygon-mode-webgl"); + for (const feature of features) { + this.has(feature); + } + } + // IMPLEMENTATION + getFeatures() { + return [...Object.keys(WEBGL_FEATURES), ...Object.keys(TEXTURE_FEATURES)]; + } + /** Extract all WebGL features */ + getWebGLFeature(feature) { + const featureInfo = WEBGL_FEATURES[feature]; + const isSupported = typeof featureInfo === "string" ? Boolean(getWebGLExtension(this.gl, featureInfo, this.extensions)) : Boolean(featureInfo); + return isSupported; + } + }; + } + }); + + // node_modules/@luma.gl/webgl/dist/adapter/device-helpers/webgl-device-limits.js + var WebGLDeviceLimits; + var init_webgl_device_limits = __esm({ + "node_modules/@luma.gl/webgl/dist/adapter/device-helpers/webgl-device-limits.js"() { + init_dist4(); + WebGLDeviceLimits = class extends DeviceLimits { + get maxTextureDimension1D() { + return 0; + } + // WebGL does not support 1D textures + get maxTextureDimension2D() { + return this.getParameter(3379); + } + get maxTextureDimension3D() { + return this.getParameter(32883); + } + get maxTextureArrayLayers() { + return this.getParameter(35071); + } + get maxBindGroups() { + return 0; + } + get maxDynamicUniformBuffersPerPipelineLayout() { + return 0; + } + // TBD + get maxDynamicStorageBuffersPerPipelineLayout() { + return 0; + } + // TBD + get maxSampledTexturesPerShaderStage() { + return this.getParameter(35660); + } + // ) TBD + get maxSamplersPerShaderStage() { + return this.getParameter(35661); + } + get maxStorageBuffersPerShaderStage() { + return 0; + } + // TBD + get maxStorageTexturesPerShaderStage() { + return 0; + } + // TBD + get maxUniformBuffersPerShaderStage() { + return this.getParameter(35375); + } + get maxUniformBufferBindingSize() { + return this.getParameter(35376); + } + get maxStorageBufferBindingSize() { + return 0; + } + get minUniformBufferOffsetAlignment() { + return this.getParameter(35380); + } + get minStorageBufferOffsetAlignment() { + return 0; + } + get maxVertexBuffers() { + return 16; + } + // WebGL 2 supports 16 buffers, see https://github.com/gpuweb/gpuweb/issues/4284 + get maxVertexAttributes() { + return this.getParameter(34921); + } + get maxVertexBufferArrayStride() { + return 2048; + } + // TBD, this is just the default value from WebGPU + get maxInterStageShaderVariables() { + return this.getParameter(35659); + } + get maxComputeWorkgroupStorageSize() { + return 0; + } + // WebGL does not support compute shaders + get maxComputeInvocationsPerWorkgroup() { + return 0; + } + // WebGL does not support compute shaders + get maxComputeWorkgroupSizeX() { + return 0; + } + // WebGL does not support compute shaders + get maxComputeWorkgroupSizeY() { + return 0; + } + // WebGL does not support compute shaders + get maxComputeWorkgroupSizeZ() { + return 0; + } + // WebGL does not support compute shaders + get maxComputeWorkgroupsPerDimension() { + return 0; + } + // WebGL does not support compute shaders + // PRIVATE + gl; + limits = {}; + constructor(gl) { + super(); + this.gl = gl; + } + getParameter(parameter) { + if (this.limits[parameter] === void 0) { + this.limits[parameter] = this.gl.getParameter(parameter); + } + return this.limits[parameter] || 0; + } + }; + } + }); + + // node_modules/@luma.gl/webgl/dist/adapter/resources/webgl-framebuffer.js + function mapIndexToCubeMapFace(layer) { + return layer < 34069 ? layer + 34069 : layer; + } + function _getFrameBufferStatus(status) { + switch (status) { + case 36053: + return "success"; + case 36054: + return "Mismatched attachments"; + case 36055: + return "No attachments"; + case 36057: + return "Height/width mismatch"; + case 36061: + return "Unsupported or split attachments"; + // WebGL2 + case 36182: + return "Samples mismatch"; + // OVR_multiview2 extension + // case GL.FRAMEBUFFER_INCOMPLETE_VIEW_TARGETS_OVR: return 'baseViewIndex mismatch'; + default: + return `${status}`; + } + } + var WEBGLFramebuffer; + var init_webgl_framebuffer = __esm({ + "node_modules/@luma.gl/webgl/dist/adapter/resources/webgl-framebuffer.js"() { + init_dist4(); + init_webgl_texture_table(); + WEBGLFramebuffer = class extends Framebuffer { + device; + gl; + handle; + colorAttachments = []; + depthStencilAttachment = null; + constructor(device, props) { + super(device, props); + const isDefaultFramebuffer = props.handle === null; + this.device = device; + this.gl = device.gl; + this.handle = this.props.handle || isDefaultFramebuffer ? this.props.handle : this.gl.createFramebuffer(); + if (!isDefaultFramebuffer) { + device._setWebGLDebugMetadata(this.handle, this, { spector: this.props }); + if (!props.handle) { + this.autoCreateAttachmentTextures(); + this.updateAttachments(); + } + } + } + /** destroys any auto created resources etc. */ + destroy() { + super.destroy(); + if (!this.destroyed && this.handle !== null && !this.props.handle) { + this.gl.deleteFramebuffer(this.handle); + } + } + updateAttachments() { + const prevHandle = this.gl.bindFramebuffer(36160, this.handle); + for (let i = 0; i < this.colorAttachments.length; ++i) { + const attachment = this.colorAttachments[i]; + if (attachment) { + const attachmentPoint = 36064 + i; + this._attachTextureView(attachmentPoint, attachment); + } + } + if (this.depthStencilAttachment) { + const attachmentPoint = getDepthStencilAttachmentWebGL(this.depthStencilAttachment.props.format); + this._attachTextureView(attachmentPoint, this.depthStencilAttachment); + } + if (this.device.props.debug) { + const status = this.gl.checkFramebufferStatus(36160); + if (status !== 36053) { + throw new Error(`Framebuffer ${_getFrameBufferStatus(status)}`); + } + } + this.gl.bindFramebuffer(36160, prevHandle); + } + // PRIVATE + /** In WebGL we must use renderbuffers for depth/stencil attachments (unless we have extensions) */ + // protected override createDepthStencilTexture(format: TextureFormat): Texture { + // // return new WEBGLRenderbuffer(this.device, { + // return new WEBGLTexture(this.device, { + // id: `${this.id}-depth-stencil`, + // format, + // width: this.width, + // height: this.height, + // mipmaps: false + // }); + // } + /** + * @param attachment + * @param texture + * @param layer = 0 - index into WEBGLTextureArray and Texture3D or face for `TextureCubeMap` + * @param level = 0 - mipmapLevel + */ + _attachTextureView(attachment, textureView) { + const { gl } = this.device; + const { texture } = textureView; + const level = textureView.props.baseMipLevel; + const layer = textureView.props.baseArrayLayer; + gl.bindTexture(texture.glTarget, texture.handle); + switch (texture.glTarget) { + case 35866: + case 32879: + gl.framebufferTextureLayer(36160, attachment, texture.handle, level, layer); + break; + case 34067: + const face = mapIndexToCubeMapFace(layer); + gl.framebufferTexture2D(36160, attachment, face, texture.handle, level); + break; + case 3553: + gl.framebufferTexture2D(36160, attachment, 3553, texture.handle, level); + break; + default: + throw new Error("Illegal texture type"); + } + gl.bindTexture(texture.glTarget, null); + } + /** Default framebuffer resize is managed by canvas size and should be a no-op. */ + resizeAttachments(width, height) { + if (this.handle === null) { + this.width = width; + this.height = height; + return; + } + super.resizeAttachments(width, height); + } + }; + } + }); + + // node_modules/@luma.gl/webgl/dist/adapter/webgl-canvas-context.js + var WebGLCanvasContext; + var init_webgl_canvas_context = __esm({ + "node_modules/@luma.gl/webgl/dist/adapter/webgl-canvas-context.js"() { + init_dist4(); + init_webgl_framebuffer(); + WebGLCanvasContext = class extends CanvasContext { + device; + handle = null; + _framebuffer = null; + get [Symbol.toStringTag]() { + return "WebGLCanvasContext"; + } + constructor(device, props) { + super(props); + this.device = device; + this._setAutoCreatedCanvasId(`${this.device.id}-canvas`); + this._configureDevice(); + } + // IMPLEMENTATION OF ABSTRACT METHODS + _configureDevice() { + const shouldResize = this.drawingBufferWidth !== this._framebuffer?.width || this.drawingBufferHeight !== this._framebuffer?.height; + if (shouldResize) { + this._framebuffer?.resize([this.drawingBufferWidth, this.drawingBufferHeight]); + } + } + _getCurrentFramebuffer() { + this._framebuffer ||= new WEBGLFramebuffer(this.device, { + id: "canvas-context-framebuffer", + handle: null, + // Setting handle to null returns a reference to the default WebGL framebuffer + width: this.drawingBufferWidth, + height: this.drawingBufferHeight + }); + return this._framebuffer; + } + }; + } + }); + + // node_modules/@luma.gl/webgl/dist/adapter/webgl-presentation-context.js + var WebGLPresentationContext; + var init_webgl_presentation_context = __esm({ + "node_modules/@luma.gl/webgl/dist/adapter/webgl-presentation-context.js"() { + init_dist4(); + WebGLPresentationContext = class extends PresentationContext { + device; + handle = null; + context2d; + get [Symbol.toStringTag]() { + return "WebGLPresentationContext"; + } + constructor(device, props = {}) { + super(props); + this.device = device; + const contextLabel = `${this[Symbol.toStringTag]}(${this.id})`; + const defaultCanvasContext = this.device.getDefaultCanvasContext(); + if (!defaultCanvasContext.offscreenCanvas) { + throw new Error(`${contextLabel}: WebGL PresentationContext requires the default CanvasContext canvas to be an OffscreenCanvas`); + } + const context2d = this.canvas.getContext("2d"); + if (!context2d) { + throw new Error(`${contextLabel}: Failed to create 2d presentation context`); + } + this.context2d = context2d; + this._setAutoCreatedCanvasId(`${this.device.id}-presentation-canvas`); + this._configureDevice(); + this._startObservers(); + } + present() { + this._resizeDrawingBufferIfNeeded(); + this.device.submit(); + const defaultCanvasContext = this.device.getDefaultCanvasContext(); + const [sourceWidth, sourceHeight] = defaultCanvasContext.getDrawingBufferSize(); + if (this.drawingBufferWidth === 0 || this.drawingBufferHeight === 0 || sourceWidth === 0 || sourceHeight === 0 || defaultCanvasContext.canvas.width === 0 || defaultCanvasContext.canvas.height === 0) { + return; + } + if (sourceWidth !== this.drawingBufferWidth || sourceHeight !== this.drawingBufferHeight || defaultCanvasContext.canvas.width !== this.drawingBufferWidth || defaultCanvasContext.canvas.height !== this.drawingBufferHeight) { + throw new Error(`${this[Symbol.toStringTag]}(${this.id}): Default canvas context size ${sourceWidth}x${sourceHeight} does not match presentation size ${this.drawingBufferWidth}x${this.drawingBufferHeight}`); + } + this.context2d.clearRect(0, 0, this.drawingBufferWidth, this.drawingBufferHeight); + this.context2d.drawImage(defaultCanvasContext.canvas, 0, 0); + } + _configureDevice() { + } + _getCurrentFramebuffer(options) { + const defaultCanvasContext = this.device.getDefaultCanvasContext(); + defaultCanvasContext.setDrawingBufferSize(this.drawingBufferWidth, this.drawingBufferHeight); + return defaultCanvasContext.getCurrentFramebuffer(options); + } + }; + } + }); + + // node_modules/@luma.gl/webgl/dist/utils/uid.js + function uid3(id = "id") { + uidCounters3[id] = uidCounters3[id] || 1; + const count2 = uidCounters3[id]++; + return `${id}-${count2}`; + } + var uidCounters3; + var init_uid2 = __esm({ + "node_modules/@luma.gl/webgl/dist/utils/uid.js"() { + uidCounters3 = {}; + } + }); + + // node_modules/@luma.gl/webgl/dist/adapter/resources/webgl-buffer.js + function getWebGLTarget(usage) { + if (usage & Buffer2.INDEX) { + return 34963; + } + if (usage & Buffer2.VERTEX) { + return 34962; + } + if (usage & Buffer2.UNIFORM) { + return 35345; + } + return 34962; + } + function getWebGLUsage(usage) { + if (usage & Buffer2.INDEX) { + return 35044; + } + if (usage & Buffer2.VERTEX) { + return 35044; + } + if (usage & Buffer2.UNIFORM) { + return 35048; + } + return 35044; + } + var WEBGLBuffer; + var init_webgl_buffer = __esm({ + "node_modules/@luma.gl/webgl/dist/adapter/resources/webgl-buffer.js"() { + init_dist4(); + WEBGLBuffer = class extends Buffer2 { + device; + gl; + handle; + /** Target in OpenGL defines the type of buffer */ + glTarget; + /** Usage is a hint on how frequently the buffer will be updates */ + glUsage; + /** Index type is needed when issuing draw calls, so we pre-compute it */ + glIndexType = 5123; + /** Number of bytes allocated on the GPU for this buffer */ + byteLength = 0; + /** Number of bytes used */ + bytesUsed = 0; + constructor(device, props = {}) { + super(device, props); + this.device = device; + this.gl = this.device.gl; + const handle = typeof props === "object" ? props.handle : void 0; + this.handle = handle || this.gl.createBuffer(); + device._setWebGLDebugMetadata(this.handle, this, { + spector: { ...this.props, data: typeof this.props.data } + }); + this.glTarget = getWebGLTarget(this.props.usage); + this.glUsage = getWebGLUsage(this.props.usage); + this.glIndexType = this.props.indexType === "uint32" ? 5125 : 5123; + if (props.data) { + this._initWithData(props.data, props.byteOffset, props.byteLength); + } else { + this._initWithByteLength(props.byteLength || 0); + } + } + destroy() { + if (!this.destroyed && this.handle) { + this.removeStats(); + if (!this.props.handle) { + this.trackDeallocatedMemory(); + this.gl.deleteBuffer(this.handle); + } else { + this.trackDeallocatedReferencedMemory("Buffer"); + } + this.destroyed = true; + this.handle = null; + } + } + /** Allocate a new buffer and initialize to contents of typed array */ + _initWithData(data, byteOffset = 0, byteLength = data.byteLength + byteOffset) { + const glTarget = this.glTarget; + this.gl.bindBuffer(glTarget, this.handle); + this.gl.bufferData(glTarget, byteLength, this.glUsage); + this.gl.bufferSubData(glTarget, byteOffset, data); + this.gl.bindBuffer(glTarget, null); + this.bytesUsed = byteLength; + this.byteLength = byteLength; + this._setDebugData(data, byteOffset, byteLength); + if (!this.props.handle) { + this.trackAllocatedMemory(byteLength); + } else { + this.trackReferencedMemory(byteLength, "Buffer"); + } + } + // Allocate a GPU buffer of specified size. + _initWithByteLength(byteLength) { + let data = byteLength; + if (byteLength === 0) { + data = new Float32Array(0); + } + const glTarget = this.glTarget; + this.gl.bindBuffer(glTarget, this.handle); + this.gl.bufferData(glTarget, data, this.glUsage); + this.gl.bindBuffer(glTarget, null); + this.bytesUsed = byteLength; + this.byteLength = byteLength; + this._setDebugData(null, 0, byteLength); + if (!this.props.handle) { + this.trackAllocatedMemory(byteLength); + } else { + this.trackReferencedMemory(byteLength, "Buffer"); + } + return this; + } + write(data, byteOffset = 0) { + const dataView = ArrayBuffer.isView(data) ? data : new Uint8Array(data); + const srcOffset = 0; + const byteLength = void 0; + const glTarget = 36663; + this.gl.bindBuffer(glTarget, this.handle); + if (srcOffset !== 0 || byteLength !== void 0) { + this.gl.bufferSubData(glTarget, byteOffset, dataView, srcOffset, byteLength); + } else { + this.gl.bufferSubData(glTarget, byteOffset, dataView); + } + this.gl.bindBuffer(glTarget, null); + this._setDebugData(data, byteOffset, data.byteLength); + } + async mapAndWriteAsync(callback, byteOffset = 0, byteLength = this.byteLength - byteOffset) { + const arrayBuffer2 = new ArrayBuffer(byteLength); + await callback(arrayBuffer2, "copied"); + this.write(arrayBuffer2, byteOffset); + } + async readAsync(byteOffset = 0, byteLength) { + return this.readSyncWebGL(byteOffset, byteLength); + } + async mapAndReadAsync(callback, byteOffset = 0, byteLength) { + const data = await this.readAsync(byteOffset, byteLength); + return await callback(data.buffer, "copied"); + } + readSyncWebGL(byteOffset = 0, byteLength) { + byteLength = byteLength ?? this.byteLength - byteOffset; + const data = new Uint8Array(byteLength); + const dstOffset = 0; + this.gl.bindBuffer(36662, this.handle); + this.gl.getBufferSubData(36662, byteOffset, data, dstOffset, byteLength); + this.gl.bindBuffer(36662, null); + this._setDebugData(data, byteOffset, byteLength); + return data; + } + }; + } + }); + + // node_modules/@luma.gl/webgl/dist/adapter/helpers/parse-shader-compiler-log.js + function parseShaderCompilerLog(errLog) { + const lines = errLog.split(/\r?\n/); + const messages = []; + for (const line of lines) { + if (line.length <= 1) { + continue; + } + const lineWithTrimmedWhitespace = line.trim(); + const segments = line.split(":"); + const trimmedMessageType = segments[0]?.trim(); + if (segments.length === 2) { + const [messageType2, message2] = segments; + if (!messageType2 || !message2) { + messages.push({ + message: lineWithTrimmedWhitespace, + type: getMessageType(trimmedMessageType || "info"), + lineNum: 0, + linePos: 0 + }); + continue; + } + messages.push({ + message: message2.trim(), + type: getMessageType(messageType2), + lineNum: 0, + linePos: 0 + }); + continue; + } + const [messageType, linePosition, lineNumber, ...rest] = segments; + if (!messageType || !linePosition || !lineNumber) { + messages.push({ + message: segments.slice(1).join(":").trim() || lineWithTrimmedWhitespace, + type: getMessageType(trimmedMessageType || "info"), + lineNum: 0, + linePos: 0 + }); + continue; + } + let lineNum = parseInt(lineNumber, 10); + if (Number.isNaN(lineNum)) { + lineNum = 0; + } + let linePos = parseInt(linePosition, 10); + if (Number.isNaN(linePos)) { + linePos = 0; + } + messages.push({ + message: rest.join(":").trim(), + type: getMessageType(messageType), + lineNum, + linePos + // TODO + }); + } + return messages; + } + function getMessageType(messageType) { + const MESSAGE_TYPES = ["warning", "error", "info"]; + const lowerCaseType = messageType.toLowerCase(); + return MESSAGE_TYPES.includes(lowerCaseType) ? lowerCaseType : "info"; + } + var init_parse_shader_compiler_log = __esm({ + "node_modules/@luma.gl/webgl/dist/adapter/helpers/parse-shader-compiler-log.js"() { + } + }); + + // node_modules/@luma.gl/webgl/dist/adapter/resources/webgl-shader.js + var WEBGLShader; + var init_webgl_shader = __esm({ + "node_modules/@luma.gl/webgl/dist/adapter/resources/webgl-shader.js"() { + init_dist4(); + init_parse_shader_compiler_log(); + WEBGLShader = class extends Shader { + device; + handle; + constructor(device, props) { + super(device, props); + this.device = device; + switch (this.props.stage) { + case "vertex": + this.handle = this.props.handle || this.device.gl.createShader(35633); + break; + case "fragment": + this.handle = this.props.handle || this.device.gl.createShader(35632); + break; + default: + throw new Error(this.props.stage); + } + device._setWebGLDebugMetadata(this.handle, this, { spector: this.props }); + const compilationStatus = this._compile(this.source); + if (compilationStatus && typeof compilationStatus.catch === "function") { + compilationStatus.catch(() => { + this.compilationStatus = "error"; + }); + } + } + destroy() { + if (this.handle) { + this.removeStats(); + this.device.gl.deleteShader(this.handle); + this.destroyed = true; + this.handle.destroyed = true; + } + } + get asyncCompilationStatus() { + return this._waitForCompilationComplete().then(() => { + this._getCompilationStatus(); + return this.compilationStatus; + }); + } + async getCompilationInfo() { + await this._waitForCompilationComplete(); + return this.getCompilationInfoSync(); + } + getCompilationInfoSync() { + const shaderLog = this.device.gl.getShaderInfoLog(this.handle); + return shaderLog ? parseShaderCompilerLog(shaderLog) : []; + } + getTranslatedSource() { + const extensions = this.device.getExtension("WEBGL_debug_shaders"); + const ext = extensions.WEBGL_debug_shaders; + return ext?.getTranslatedShaderSource(this.handle) || null; + } + // PRIVATE METHODS + /** Compile a shader and get compilation status */ + _compile(source3) { + source3 = source3.startsWith("#version ") ? source3 : `#version 300 es +${source3}`; + const { gl } = this.device; + gl.shaderSource(this.handle, source3); + gl.compileShader(this.handle); + if (!this.device.props.debug) { + this.compilationStatus = "pending"; + return; + } + if (!this.device.features.has("compilation-status-async-webgl")) { + this._getCompilationStatus(); + this.debugShader(); + if (this.compilationStatus === "error") { + throw new Error(`GLSL compilation errors in ${this.props.stage} shader ${this.props.id}`); + } + return; + } + log2.once(1, "Shader compilation is asynchronous")(); + return this._waitForCompilationComplete().then(() => { + log2.info(2, `Shader ${this.id} - async compilation complete: ${this.compilationStatus}`)(); + this._getCompilationStatus(); + this.debugShader(); + }); + } + /** Use KHR_parallel_shader_compile extension if available */ + async _waitForCompilationComplete() { + const waitMs = async (ms) => await new Promise((resolve2) => setTimeout(resolve2, ms)); + const DELAY_MS = 10; + if (!this.device.features.has("compilation-status-async-webgl")) { + await waitMs(DELAY_MS); + return; + } + const { gl } = this.device; + for (; ; ) { + const complete = gl.getShaderParameter(this.handle, 37297); + if (complete) { + return; + } + await waitMs(DELAY_MS); + } + } + /** + * Get the shader compilation status + * TODO - Load log even when no error reported, to catch warnings? + * https://gamedev.stackexchange.com/questions/30429/how-to-detect-glsl-warnings + */ + _getCompilationStatus() { + this.compilationStatus = this.device.gl.getShaderParameter(this.handle, 35713) ? "success" : "error"; + } + }; + } + }); + + // node_modules/@luma.gl/webgl/dist/adapter/converters/device-parameters.js + function withDeviceAndGLParameters(device, parameters, glParameters, func) { + if (isObjectEmpty3(parameters)) { + return func(device); + } + const webglDevice = device; + webglDevice.pushState(); + try { + setDeviceParameters(device, parameters); + setGLParameters(webglDevice.gl, glParameters); + return func(device); + } finally { + webglDevice.popState(); + } + } + function setDeviceParameters(device, parameters) { + const webglDevice = device; + const { gl } = webglDevice; + if (parameters.cullMode) { + switch (parameters.cullMode) { + case "none": + gl.disable(2884); + break; + case "front": + gl.enable(2884); + gl.cullFace(1028); + break; + case "back": + gl.enable(2884); + gl.cullFace(1029); + break; + } + } + if (parameters.frontFace) { + gl.frontFace(map2("frontFace", parameters.frontFace, { + ccw: 2305, + cw: 2304 + })); + } + if (parameters.unclippedDepth) { + if (device.features.has("depth-clip-control")) { + gl.enable(34383); + } + } + if (parameters.depthBias !== void 0) { + gl.enable(32823); + gl.polygonOffset(parameters.depthBias, parameters.depthBiasSlopeScale || 0); + } + if (parameters.provokingVertex) { + if (device.features.has("provoking-vertex-webgl")) { + const extensions = webglDevice.getExtension("WEBGL_provoking_vertex"); + const ext = extensions.WEBGL_provoking_vertex; + const vertex2 = map2("provokingVertex", parameters.provokingVertex, { + first: 36429, + last: 36430 + }); + ext?.provokingVertexWEBGL(vertex2); + } + } + if (parameters.polygonMode || parameters.polygonOffsetLine) { + if (device.features.has("polygon-mode-webgl")) { + if (parameters.polygonMode) { + const extensions = webglDevice.getExtension("WEBGL_polygon_mode"); + const ext = extensions.WEBGL_polygon_mode; + const mode = map2("polygonMode", parameters.polygonMode, { + fill: 6914, + line: 6913 + }); + ext?.polygonModeWEBGL(1028, mode); + ext?.polygonModeWEBGL(1029, mode); + } + if (parameters.polygonOffsetLine) { + gl.enable(10754); + } + } + } + if (device.features.has("shader-clip-cull-distance-webgl")) { + if (parameters.clipDistance0) { + gl.enable(12288); + } + if (parameters.clipDistance1) { + gl.enable(12289); + } + if (parameters.clipDistance2) { + gl.enable(12290); + } + if (parameters.clipDistance3) { + gl.enable(12291); + } + if (parameters.clipDistance4) { + gl.enable(12292); + } + if (parameters.clipDistance5) { + gl.enable(12293); + } + if (parameters.clipDistance6) { + gl.enable(12294); + } + if (parameters.clipDistance7) { + gl.enable(12295); + } + } + if (parameters.depthWriteEnabled !== void 0) { + gl.depthMask(mapBoolean("depthWriteEnabled", parameters.depthWriteEnabled)); + } + if (parameters.depthCompare) { + parameters.depthCompare !== "always" ? gl.enable(2929) : gl.disable(2929); + gl.depthFunc(convertCompareFunction("depthCompare", parameters.depthCompare)); + } + if (parameters.clearDepth !== void 0) { + gl.clearDepth(parameters.clearDepth); + } + if (parameters.stencilWriteMask) { + const mask = parameters.stencilWriteMask; + gl.stencilMaskSeparate(1028, mask); + gl.stencilMaskSeparate(1029, mask); + } + if (parameters.stencilReadMask) { + log2.warn("stencilReadMask not supported under WebGL"); + } + if (parameters.stencilCompare) { + const mask = parameters.stencilReadMask || 4294967295; + const glValue = convertCompareFunction("depthCompare", parameters.stencilCompare); + parameters.stencilCompare !== "always" ? gl.enable(2960) : gl.disable(2960); + gl.stencilFuncSeparate(1028, glValue, 0, mask); + gl.stencilFuncSeparate(1029, glValue, 0, mask); + } + if (parameters.stencilPassOperation && parameters.stencilFailOperation && parameters.stencilDepthFailOperation) { + const dppass = convertStencilOperation("stencilPassOperation", parameters.stencilPassOperation); + const sfail = convertStencilOperation("stencilFailOperation", parameters.stencilFailOperation); + const dpfail = convertStencilOperation("stencilDepthFailOperation", parameters.stencilDepthFailOperation); + gl.stencilOpSeparate(1028, sfail, dpfail, dppass); + gl.stencilOpSeparate(1029, sfail, dpfail, dppass); + } + switch (parameters.blend) { + case true: + gl.enable(3042); + break; + case false: + gl.disable(3042); + break; + default: + } + if (parameters.blendColorOperation || parameters.blendAlphaOperation) { + const colorEquation = convertBlendOperationToEquation("blendColorOperation", parameters.blendColorOperation || "add"); + const alphaEquation = convertBlendOperationToEquation("blendAlphaOperation", parameters.blendAlphaOperation || "add"); + gl.blendEquationSeparate(colorEquation, alphaEquation); + const colorSrcFactor = convertBlendFactorToFunction("blendColorSrcFactor", parameters.blendColorSrcFactor || "one"); + const colorDstFactor = convertBlendFactorToFunction("blendColorDstFactor", parameters.blendColorDstFactor || "zero"); + const alphaSrcFactor = convertBlendFactorToFunction("blendAlphaSrcFactor", parameters.blendAlphaSrcFactor || "one"); + const alphaDstFactor = convertBlendFactorToFunction("blendAlphaDstFactor", parameters.blendAlphaDstFactor || "zero"); + gl.blendFuncSeparate(colorSrcFactor, colorDstFactor, alphaSrcFactor, alphaDstFactor); + } + } + function convertCompareFunction(parameter, value) { + return map2(parameter, value, { + never: 512, + less: 513, + equal: 514, + "less-equal": 515, + greater: 516, + "not-equal": 517, + "greater-equal": 518, + always: 519 + }); + } + function convertStencilOperation(parameter, value) { + return map2(parameter, value, { + keep: 7680, + zero: 0, + replace: 7681, + invert: 5386, + "increment-clamp": 7682, + "decrement-clamp": 7683, + "increment-wrap": 34055, + "decrement-wrap": 34056 + }); + } + function convertBlendOperationToEquation(parameter, value) { + return map2(parameter, value, { + add: 32774, + subtract: 32778, + "reverse-subtract": 32779, + min: 32775, + max: 32776 + }); + } + function convertBlendFactorToFunction(parameter, value, type = "color") { + return map2(parameter, value, { + one: 1, + zero: 0, + src: 768, + "one-minus-src": 769, + dst: 774, + "one-minus-dst": 775, + "src-alpha": 770, + "one-minus-src-alpha": 771, + "dst-alpha": 772, + "one-minus-dst-alpha": 773, + "src-alpha-saturated": 776, + constant: type === "color" ? 32769 : 32771, + "one-minus-constant": type === "color" ? 32770 : 32772, + // 'constant-alpha': GL.CONSTANT_ALPHA, + // 'one-minus-constant-alpha': GL.ONE_MINUS_CONSTANT_ALPHA, + // TODO not supported in WebGL2 + src1: 768, + "one-minus-src1": 769, + "src1-alpha": 770, + "one-minus-src1-alpha": 771 + }); + } + function message(parameter, value) { + return `Illegal parameter ${value} for ${parameter}`; + } + function map2(parameter, value, valueMap) { + if (!(value in valueMap)) { + throw new Error(message(parameter, value)); + } + return valueMap[value]; + } + function mapBoolean(parameter, value) { + return value; + } + function isObjectEmpty3(obj) { + let isEmpty = true; + for (const key in obj) { + isEmpty = false; + break; + } + return isEmpty; + } + var init_device_parameters = __esm({ + "node_modules/@luma.gl/webgl/dist/adapter/converters/device-parameters.js"() { + init_dist4(); + init_unified_parameter_api(); + } + }); + + // node_modules/@luma.gl/webgl/dist/adapter/converters/sampler-parameters.js + function convertSamplerParametersToWebGL(props) { + const params = {}; + if (props.addressModeU) { + params[10242] = convertAddressMode(props.addressModeU); + } + if (props.addressModeV) { + params[10243] = convertAddressMode(props.addressModeV); + } + if (props.addressModeW) { + params[32882] = convertAddressMode(props.addressModeW); + } + if (props.magFilter) { + params[10240] = convertMaxFilterMode(props.magFilter); + } + if (props.minFilter || props.mipmapFilter) { + params[10241] = convertMinFilterMode(props.minFilter || "linear", props.mipmapFilter); + } + if (props.lodMinClamp !== void 0) { + params[33082] = props.lodMinClamp; + } + if (props.lodMaxClamp !== void 0) { + params[33083] = props.lodMaxClamp; + } + if (props.type === "comparison-sampler") { + params[34892] = 34894; + } + if (props.compare) { + params[34893] = convertCompareFunction("compare", props.compare); + } + if (props.maxAnisotropy) { + params[34046] = props.maxAnisotropy; + } + return params; + } + function convertAddressMode(addressMode) { + switch (addressMode) { + case "clamp-to-edge": + return 33071; + case "repeat": + return 10497; + case "mirror-repeat": + return 33648; + } + } + function convertMaxFilterMode(maxFilter) { + switch (maxFilter) { + case "nearest": + return 9728; + case "linear": + return 9729; + } + } + function convertMinFilterMode(minFilter, mipmapFilter = "none") { + if (!mipmapFilter) { + return convertMaxFilterMode(minFilter); + } + switch (mipmapFilter) { + case "none": + return convertMaxFilterMode(minFilter); + case "nearest": + switch (minFilter) { + case "nearest": + return 9984; + case "linear": + return 9985; + } + break; + case "linear": + switch (minFilter) { + case "nearest": + return 9986; + case "linear": + return 9987; + } + } + } + var init_sampler_parameters = __esm({ + "node_modules/@luma.gl/webgl/dist/adapter/converters/sampler-parameters.js"() { + init_device_parameters(); + } + }); + + // node_modules/@luma.gl/webgl/dist/adapter/resources/webgl-sampler.js + var WEBGLSampler; + var init_webgl_sampler = __esm({ + "node_modules/@luma.gl/webgl/dist/adapter/resources/webgl-sampler.js"() { + init_dist4(); + init_sampler_parameters(); + WEBGLSampler = class extends Sampler { + device; + handle; + parameters; + constructor(device, props) { + super(device, props); + this.device = device; + this.parameters = convertSamplerParametersToWebGL(props); + this.handle = props.handle || this.device.gl.createSampler(); + this._setSamplerParameters(this.parameters); + } + destroy() { + if (this.handle) { + this.device.gl.deleteSampler(this.handle); + this.handle = void 0; + } + } + toString() { + return `Sampler(${this.id},${JSON.stringify(this.props)})`; + } + /** Set sampler parameters on the sampler */ + _setSamplerParameters(parameters) { + for (const [pname, value] of Object.entries(parameters)) { + const param = Number(pname); + switch (param) { + case 33082: + case 33083: + this.device.gl.samplerParameterf(this.handle, param, value); + break; + default: + this.device.gl.samplerParameteri(this.handle, param, value); + break; + } + } + } + }; + } + }); + + // node_modules/@luma.gl/webgl/dist/context/state-tracker/with-parameters.js + function withGLParameters(gl, parameters, func) { + if (isObjectEmpty4(parameters)) { + return func(gl); + } + const { nocatch = true } = parameters; + const webglState = WebGLStateTracker.get(gl); + webglState.push(); + setGLParameters(gl, parameters); + let value; + if (nocatch) { + value = func(gl); + webglState.pop(); + } else { + try { + value = func(gl); + } finally { + webglState.pop(); + } + } + return value; + } + function isObjectEmpty4(object) { + for (const key in object) { + return false; + } + return true; + } + var init_with_parameters = __esm({ + "node_modules/@luma.gl/webgl/dist/context/state-tracker/with-parameters.js"() { + init_unified_parameter_api(); + init_webgl_state_tracker(); + } + }); + + // node_modules/@luma.gl/webgl/dist/adapter/resources/webgl-texture-view.js + var WEBGLTextureView; + var init_webgl_texture_view = __esm({ + "node_modules/@luma.gl/webgl/dist/adapter/resources/webgl-texture-view.js"() { + init_dist4(); + WEBGLTextureView = class extends TextureView { + device; + gl; + handle; + // Does not have a WebGL representation + texture; + constructor(device, props) { + super(device, { ...Texture.defaultProps, ...props }); + this.device = device; + this.gl = this.device.gl; + this.handle = null; + this.texture = props.texture; + } + }; + } + }); + + // node_modules/@luma.gl/webgl/dist/adapter/converters/shader-formats.js + function convertGLDataTypeToDataType(type) { + return GL_DATA_TYPE_MAP[type]; + } + var GL_DATA_TYPE_MAP; + var init_shader_formats = __esm({ + "node_modules/@luma.gl/webgl/dist/adapter/converters/shader-formats.js"() { + GL_DATA_TYPE_MAP = { + [5124]: "sint32", + [5125]: "uint32", + [5122]: "sint16", + [5123]: "uint16", + [5120]: "sint8", + [5121]: "uint8", + [5126]: "float32", + [5131]: "float16", + [33635]: "uint16", + [32819]: "uint16", + [32820]: "uint16", + [33640]: "uint32", + [35899]: "uint32", + [35902]: "uint32", + [34042]: "uint32", + [36269]: "uint32" + }; + } + }); + + // node_modules/@luma.gl/webgl/dist/adapter/resources/webgl-texture.js + function getArrayBufferView(typedArray, byteOffset = 0) { + if (!byteOffset) { + return typedArray; + } + return new typedArray.constructor(typedArray.buffer, typedArray.byteOffset + byteOffset, (typedArray.byteLength - byteOffset) / typedArray.BYTES_PER_ELEMENT); + } + function getWebGLTextureSourceElementOffset(typedArray, byteOffset) { + if (byteOffset % typedArray.BYTES_PER_ELEMENT !== 0) { + throw new Error(`Texture byteOffset ${byteOffset} must align to typed array element size ${typedArray.BYTES_PER_ELEMENT}`); + } + return byteOffset / typedArray.BYTES_PER_ELEMENT; + } + function getWebGLTextureTarget(dimension) { + switch (dimension) { + case "1d": + break; + // not supported in any WebGL version + case "2d": + return 3553; + // supported in WebGL1 + case "3d": + return 32879; + // supported in WebGL2 + case "cube": + return 34067; + // supported in WebGL1 + case "2d-array": + return 35866; + // supported in WebGL2 + case "cube-array": + break; + } + throw new Error(dimension); + } + function getWebGLCubeFaceTarget(glTarget, dimension, level) { + return dimension === "cube" ? 34069 + level : glTarget; + } + var WEBGLTexture; + var init_webgl_texture = __esm({ + "node_modules/@luma.gl/webgl/dist/adapter/resources/webgl-texture.js"() { + init_dist4(); + init_webgl_texture_table(); + init_sampler_parameters(); + init_with_parameters(); + init_webgl_texture_view(); + init_shader_formats(); + WEBGLTexture = class extends Texture { + // readonly MAX_ATTRIBUTES: number; + device; + gl; + handle; + // @ts-ignore TODO - currently unused in WebGL. Create dummy sampler? + sampler = void 0; + view; + /** + * The WebGL target corresponding to the texture type + * @note `target` cannot be modified by bind: + * textures are special because when you first bind them to a target, + * When you first bind a texture as a GL_TEXTURE_2D, you are saying that this texture is a 2D texture. + * And it will always be a 2D texture; this state cannot be changed ever. + * A texture that was first bound as a GL_TEXTURE_2D, must always be bound as a GL_TEXTURE_2D; + * attempting to bind it as GL_TEXTURE_3D will give rise to a run-time error + */ + glTarget; + /** The WebGL format - essentially channel structure */ + glFormat; + /** The WebGL data format - the type of each channel */ + glType; + /** The WebGL constant corresponding to the WebGPU style constant in format */ + glInternalFormat; + /** Whether the internal format is compressed */ + compressed; + // state + /** Texture binding slot - TODO - move to texture view? */ + _textureUnit = 0; + /** Cached framebuffer reused for color texture readback. */ + _framebuffer = null; + /** Cache key for the currently attached readback subresource `${mipLevel}:${layer}`. */ + _framebufferAttachmentKey = null; + constructor(device, props) { + super(device, props, { byteAlignment: 1 }); + this.device = device; + this.gl = this.device.gl; + const formatInfo = getTextureFormatWebGL(this.props.format); + this.glTarget = getWebGLTextureTarget(this.props.dimension); + this.glInternalFormat = formatInfo.internalFormat; + this.glFormat = formatInfo.format; + this.glType = formatInfo.type; + this.compressed = formatInfo.compressed; + this.handle = this.props.handle || this.gl.createTexture(); + this.device._setWebGLDebugMetadata(this.handle, this, { spector: this.props }); + this.gl.bindTexture(this.glTarget, this.handle); + const { dimension, width, height, depth, mipLevels, glTarget, glInternalFormat } = this; + if (!this.compressed) { + switch (dimension) { + case "2d": + case "cube": + this.gl.texStorage2D(glTarget, mipLevels, glInternalFormat, width, height); + break; + case "2d-array": + case "3d": + this.gl.texStorage3D(glTarget, mipLevels, glInternalFormat, width, height, depth); + break; + default: + throw new Error(dimension); + } + } + this.gl.bindTexture(this.glTarget, null); + this._initializeData(props.data); + if (!this.props.handle) { + this.trackAllocatedMemory(this.getAllocatedByteLength(), "Texture"); + } else { + this.trackReferencedMemory(this.getAllocatedByteLength(), "Texture"); + } + this.setSampler(this.props.sampler); + this.view = new WEBGLTextureView(this.device, { ...this.props, texture: this }); + Object.seal(this); + } + destroy() { + if (this.handle) { + this._framebuffer?.destroy(); + this._framebuffer = null; + this._framebufferAttachmentKey = null; + this.removeStats(); + if (!this.props.handle) { + this.gl.deleteTexture(this.handle); + this.trackDeallocatedMemory("Texture"); + } else { + this.trackDeallocatedReferencedMemory("Texture"); + } + this.destroyed = true; + } + } + createView(props) { + return new WEBGLTextureView(this.device, { ...props, texture: this }); + } + setSampler(sampler = {}) { + super.setSampler(sampler); + const parameters = convertSamplerParametersToWebGL(this.sampler.props); + this._setSamplerParameters(parameters); + } + copyExternalImage(options_) { + const options = this._normalizeCopyExternalImageOptions(options_); + if (options.sourceX || options.sourceY) { + throw new Error("WebGL does not support sourceX/sourceY)"); + } + const { glFormat, glType } = this; + const { image, depth, mipLevel, x, y, z, width, height } = options; + const glTarget = getWebGLCubeFaceTarget(this.glTarget, this.dimension, z); + const glParameters = options.flipY ? { [37440]: true } : {}; + this.gl.bindTexture(this.glTarget, this.handle); + withGLParameters(this.gl, glParameters, () => { + switch (this.dimension) { + case "2d": + case "cube": + this.gl.texSubImage2D(glTarget, mipLevel, x, y, width, height, glFormat, glType, image); + break; + case "2d-array": + case "3d": + this.gl.texSubImage3D(glTarget, mipLevel, x, y, z, width, height, depth, glFormat, glType, image); + break; + default: + } + }); + this.gl.bindTexture(this.glTarget, null); + return { width: options.width, height: options.height }; + } + copyImageData(options_) { + super.copyImageData(options_); + } + /** + * Reads a color texture subresource into a GPU buffer using `PIXEL_PACK_BUFFER`. + * + * @note Only first-pass color readback is supported. Unsupported formats and aspects throw + * before any WebGL calls are issued. + */ + readBuffer(options = {}, buffer) { + if (!buffer) { + throw new Error(`${this} readBuffer requires a destination buffer`); + } + const normalizedOptions = this._getSupportedColorReadOptions(options); + const byteOffset = options.byteOffset ?? 0; + const memoryLayout = this.computeMemoryLayout(normalizedOptions); + if (buffer.byteLength < byteOffset + memoryLayout.byteLength) { + throw new Error(`${this} readBuffer target is too small (${buffer.byteLength} < ${byteOffset + memoryLayout.byteLength})`); + } + const webglBuffer = buffer; + this.gl.bindBuffer(35051, webglBuffer.handle); + try { + this._readColorTextureLayers(normalizedOptions, memoryLayout, (destinationByteOffset) => { + this.gl.readPixels(normalizedOptions.x, normalizedOptions.y, normalizedOptions.width, normalizedOptions.height, this.glFormat, this.glType, byteOffset + destinationByteOffset); + }); + } finally { + this.gl.bindBuffer(35051, null); + } + return buffer; + } + async readDataAsync(options = {}) { + throw new Error(`${this} readDataAsync is deprecated; use readBuffer() with an explicit destination buffer or DynamicTexture.readAsync()`); + } + writeBuffer(buffer, options_ = {}) { + const options = this._normalizeTextureWriteOptions(options_); + const { width, height, depthOrArrayLayers, mipLevel, byteOffset, x, y, z } = options; + const { glFormat, glType, compressed } = this; + const glTarget = getWebGLCubeFaceTarget(this.glTarget, this.dimension, z); + if (compressed) { + throw new Error("writeBuffer for compressed textures is not implemented in WebGL"); + } + const { bytesPerPixel } = this.device.getTextureFormatInfo(this.format); + const unpackRowLength = bytesPerPixel ? options.bytesPerRow / bytesPerPixel : void 0; + const glParameters = { + [3317]: this.byteAlignment, + ...unpackRowLength !== void 0 ? { [3314]: unpackRowLength } : {}, + [32878]: options.rowsPerImage + }; + this.gl.bindTexture(this.glTarget, this.handle); + this.gl.bindBuffer(35052, buffer.handle); + withGLParameters(this.gl, glParameters, () => { + switch (this.dimension) { + case "2d": + case "cube": + this.gl.texSubImage2D(glTarget, mipLevel, x, y, width, height, glFormat, glType, byteOffset); + break; + case "2d-array": + case "3d": + this.gl.texSubImage3D(glTarget, mipLevel, x, y, z, width, height, depthOrArrayLayers, glFormat, glType, byteOffset); + break; + default: + } + }); + this.gl.bindBuffer(35052, null); + this.gl.bindTexture(this.glTarget, null); + } + writeData(data, options_ = {}) { + const options = this._normalizeTextureWriteOptions(options_); + const typedArray = ArrayBuffer.isView(data) ? data : new Uint8Array(data); + const { width, height, depthOrArrayLayers, mipLevel, x, y, z, byteOffset } = options; + const { glFormat, glType, compressed } = this; + const glTarget = getWebGLCubeFaceTarget(this.glTarget, this.dimension, z); + let unpackRowLength; + if (!compressed) { + const { bytesPerPixel } = this.device.getTextureFormatInfo(this.format); + if (bytesPerPixel) { + unpackRowLength = options.bytesPerRow / bytesPerPixel; + } + } + const glParameters = !this.compressed ? { + [3317]: this.byteAlignment, + ...unpackRowLength !== void 0 ? { [3314]: unpackRowLength } : {}, + [32878]: options.rowsPerImage + } : {}; + const sourceElementOffset = getWebGLTextureSourceElementOffset(typedArray, byteOffset); + const compressedData = compressed ? getArrayBufferView(typedArray, byteOffset) : typedArray; + const mipLevelSize = this._getMipLevelSize(mipLevel); + const isFullMipUpload = x === 0 && y === 0 && z === 0 && width === mipLevelSize.width && height === mipLevelSize.height && depthOrArrayLayers === mipLevelSize.depthOrArrayLayers; + this.gl.bindTexture(this.glTarget, this.handle); + this.gl.bindBuffer(35052, null); + withGLParameters(this.gl, glParameters, () => { + switch (this.dimension) { + case "2d": + case "cube": + if (compressed) { + if (isFullMipUpload) { + this.gl.compressedTexImage2D(glTarget, mipLevel, glFormat, width, height, 0, compressedData); + } else { + this.gl.compressedTexSubImage2D(glTarget, mipLevel, x, y, width, height, glFormat, compressedData); + } + } else { + this.gl.texSubImage2D(glTarget, mipLevel, x, y, width, height, glFormat, glType, typedArray, sourceElementOffset); + } + break; + case "2d-array": + case "3d": + if (compressed) { + if (isFullMipUpload) { + this.gl.compressedTexImage3D(glTarget, mipLevel, glFormat, width, height, depthOrArrayLayers, 0, compressedData); + } else { + this.gl.compressedTexSubImage3D(glTarget, mipLevel, x, y, z, width, height, depthOrArrayLayers, glFormat, compressedData); + } + } else { + this.gl.texSubImage3D(glTarget, mipLevel, x, y, z, width, height, depthOrArrayLayers, glFormat, glType, typedArray, sourceElementOffset); + } + break; + default: + } + }); + this.gl.bindTexture(this.glTarget, null); + } + // IMPLEMENTATION SPECIFIC + /** @todo - for now we always use 1 for maximum compatibility, we can fine tune later */ + _getRowByteAlignment(format2, width) { + return 1; + } + /** + * Wraps a given texture into a framebuffer object, that can be further used + * to read data from the texture object. + */ + _getFramebuffer() { + this._framebuffer ||= this.device.createFramebuffer({ + id: `framebuffer-for-${this.id}`, + width: this.width, + height: this.height, + colorAttachments: [this] + }); + return this._framebuffer; + } + // WEBGL SPECIFIC + readDataSyncWebGL(options_ = {}) { + const options = this._getSupportedColorReadOptions(options_); + const memoryLayout = this.computeMemoryLayout(options); + const shaderType = convertGLDataTypeToDataType(this.glType); + const ArrayType = getTypedArrayConstructor(shaderType); + const targetArray = new ArrayType(memoryLayout.byteLength / ArrayType.BYTES_PER_ELEMENT); + this._readColorTextureLayers(options, memoryLayout, (destinationByteOffset) => { + const layerView = new ArrayType(targetArray.buffer, targetArray.byteOffset + destinationByteOffset, memoryLayout.bytesPerImage / ArrayType.BYTES_PER_ELEMENT); + this.gl.readPixels(options.x, options.y, options.width, options.height, this.glFormat, this.glType, layerView); + }); + return targetArray.buffer; + } + /** + * Iterates the requested mip/layer/slice range, reattaching the cached read framebuffer as + * needed before delegating the actual `readPixels()` call to the supplied callback. + */ + _readColorTextureLayers(options, memoryLayout, readLayer) { + const framebuffer = this._getFramebuffer(); + const packRowLength = memoryLayout.bytesPerRow / memoryLayout.bytesPerPixel; + const glParameters = { + [3333]: this.byteAlignment, + ...packRowLength !== options.width ? { [3330]: packRowLength } : {} + }; + const prevReadBuffer = this.gl.getParameter(3074); + const prevHandle = this.gl.bindFramebuffer(36160, framebuffer.handle); + try { + this.gl.readBuffer(36064); + withGLParameters(this.gl, glParameters, () => { + for (let layerIndex = 0; layerIndex < options.depthOrArrayLayers; layerIndex++) { + this._attachReadSubresource(framebuffer, options.mipLevel, options.z + layerIndex); + readLayer(layerIndex * memoryLayout.bytesPerImage); + } + }); + } finally { + this.gl.bindFramebuffer(36160, prevHandle || null); + this.gl.readBuffer(prevReadBuffer); + } + } + /** + * Attaches a single color subresource to the cached read framebuffer. + * + * @note Repeated attachments of the same `(mipLevel, layer)` tuple are skipped. + */ + _attachReadSubresource(framebuffer, mipLevel, layer) { + const attachmentKey = `${mipLevel}:${layer}`; + if (this._framebufferAttachmentKey === attachmentKey) { + return; + } + switch (this.dimension) { + case "2d": + this.gl.framebufferTexture2D(36160, 36064, 3553, this.handle, mipLevel); + break; + case "cube": + this.gl.framebufferTexture2D(36160, 36064, getWebGLCubeFaceTarget(this.glTarget, this.dimension, layer), this.handle, mipLevel); + break; + case "2d-array": + case "3d": + this.gl.framebufferTextureLayer(36160, 36064, this.handle, mipLevel, layer); + break; + default: + throw new Error(`${this} color readback does not support ${this.dimension} textures`); + } + if (this.device.props.debug) { + const status = Number(this.gl.checkFramebufferStatus(36160)); + if (status !== Number(36053)) { + throw new Error(`${framebuffer} incomplete for ${this} readback (${status})`); + } + } + this._framebufferAttachmentKey = attachmentKey; + } + /** + * @note - this is used by the DynamicTexture class to generate mipmaps on WebGL + */ + generateMipmapsWebGL(options) { + const isFilterableAndRenderable = this.device.isTextureFormatRenderable(this.props.format) && this.device.isTextureFormatFilterable(this.props.format); + if (!isFilterableAndRenderable) { + log2.warn(`${this} is not renderable or filterable, may not be able to generate mipmaps`)(); + if (!options?.force) { + return; + } + } + try { + this.gl.bindTexture(this.glTarget, this.handle); + this.gl.generateMipmap(this.glTarget); + } catch (error) { + log2.warn(`Error generating mipmap for ${this}: ${error.message}`)(); + } finally { + this.gl.bindTexture(this.glTarget, null); + } + } + // INTERNAL + /** + * Sets sampler parameters on texture + */ + _setSamplerParameters(parameters) { + log2.log(2, `${this.id} sampler parameters`, this.device.getGLKeys(parameters))(); + this.gl.bindTexture(this.glTarget, this.handle); + for (const [pname, pvalue] of Object.entries(parameters)) { + const param = Number(pname); + const value = pvalue; + switch (param) { + case 33082: + case 33083: + this.gl.texParameterf(this.glTarget, param, value); + break; + case 10240: + case 10241: + this.gl.texParameteri(this.glTarget, param, value); + break; + case 10242: + case 10243: + case 32882: + this.gl.texParameteri(this.glTarget, param, value); + break; + case 34046: + if (this.device.features.has("texture-filterable-anisotropic-webgl")) { + this.gl.texParameteri(this.glTarget, param, value); + } + break; + case 34892: + case 34893: + this.gl.texParameteri(this.glTarget, param, value); + break; + } + } + this.gl.bindTexture(this.glTarget, null); + } + _getActiveUnit() { + return this.gl.getParameter(34016) - 33984; + } + _bind(_textureUnit) { + const { gl } = this; + if (_textureUnit !== void 0) { + this._textureUnit = _textureUnit; + gl.activeTexture(33984 + _textureUnit); + } + gl.bindTexture(this.glTarget, this.handle); + return _textureUnit; + } + _unbind(_textureUnit) { + const { gl } = this; + if (_textureUnit !== void 0) { + this._textureUnit = _textureUnit; + gl.activeTexture(33984 + _textureUnit); + } + gl.bindTexture(this.glTarget, null); + return _textureUnit; + } + }; + } + }); + + // node_modules/@luma.gl/webgl/dist/adapter/helpers/set-uniform.js + function setUniform(gl, location, type, value) { + const gl2 = gl; + let uniformValue = value; + if (uniformValue === true) { + uniformValue = 1; + } + if (uniformValue === false) { + uniformValue = 0; + } + const arrayValue = typeof uniformValue === "number" ? [uniformValue] : uniformValue; + switch (type) { + case 35678: + case 35680: + case 35679: + case 35682: + case 36289: + case 36292: + case 36293: + case 36298: + case 36299: + case 36300: + case 36303: + case 36306: + case 36307: + case 36308: + case 36311: + if (typeof value !== "number") { + throw new Error("samplers must be set to integers"); + } + return gl.uniform1i(location, value); + case 5126: + return gl.uniform1fv(location, arrayValue); + case 35664: + return gl.uniform2fv(location, arrayValue); + case 35665: + return gl.uniform3fv(location, arrayValue); + case 35666: + return gl.uniform4fv(location, arrayValue); + case 5124: + return gl.uniform1iv(location, arrayValue); + case 35667: + return gl.uniform2iv(location, arrayValue); + case 35668: + return gl.uniform3iv(location, arrayValue); + case 35669: + return gl.uniform4iv(location, arrayValue); + case 35670: + return gl.uniform1iv(location, arrayValue); + case 35671: + return gl.uniform2iv(location, arrayValue); + case 35672: + return gl.uniform3iv(location, arrayValue); + case 35673: + return gl.uniform4iv(location, arrayValue); + // WEBGL2 - unsigned integers + case 5125: + return gl2.uniform1uiv(location, arrayValue, 1); + case 36294: + return gl2.uniform2uiv(location, arrayValue, 2); + case 36295: + return gl2.uniform3uiv(location, arrayValue, 3); + case 36296: + return gl2.uniform4uiv(location, arrayValue, 4); + // WebGL2 - quadratic matrices + // false: don't transpose the matrix + case 35674: + return gl.uniformMatrix2fv(location, false, arrayValue); + case 35675: + return gl.uniformMatrix3fv(location, false, arrayValue); + case 35676: + return gl.uniformMatrix4fv(location, false, arrayValue); + // WebGL2 - rectangular matrices + case 35685: + return gl2.uniformMatrix2x3fv(location, false, arrayValue); + case 35686: + return gl2.uniformMatrix2x4fv(location, false, arrayValue); + case 35687: + return gl2.uniformMatrix3x2fv(location, false, arrayValue); + case 35688: + return gl2.uniformMatrix3x4fv(location, false, arrayValue); + case 35689: + return gl2.uniformMatrix4x2fv(location, false, arrayValue); + case 35690: + return gl2.uniformMatrix4x3fv(location, false, arrayValue); + } + throw new Error("Illegal uniform"); + } + var init_set_uniform = __esm({ + "node_modules/@luma.gl/webgl/dist/adapter/helpers/set-uniform.js"() { + } + }); + + // node_modules/@luma.gl/webgl/dist/adapter/helpers/webgl-topology-utils.js + function getGLDrawMode(topology) { + switch (topology) { + case "point-list": + return 0; + case "line-list": + return 1; + case "line-strip": + return 3; + case "triangle-list": + return 4; + case "triangle-strip": + return 5; + default: + throw new Error(topology); + } + } + function getGLPrimitive(topology) { + switch (topology) { + case "point-list": + return 0; + case "line-list": + return 1; + case "line-strip": + return 1; + case "triangle-list": + return 4; + case "triangle-strip": + return 4; + default: + throw new Error(topology); + } + } + var init_webgl_topology_utils = __esm({ + "node_modules/@luma.gl/webgl/dist/adapter/helpers/webgl-topology-utils.js"() { + } + }); + + // node_modules/@luma.gl/webgl/dist/adapter/resources/webgl-render-pipeline.js + function mergeShaderLayout(baseLayout, overrideLayout) { + const mergedLayout = { + ...baseLayout, + attributes: baseLayout.attributes.map((attribute) => ({ ...attribute })), + bindings: baseLayout.bindings.map((binding) => ({ ...binding })) + }; + for (const attribute of overrideLayout?.attributes || []) { + const baseAttribute = mergedLayout.attributes.find((attr) => attr.name === attribute.name); + if (!baseAttribute) { + log2.warn(`shader layout attribute ${attribute.name} not present in shader`); + } else { + baseAttribute.type = attribute.type || baseAttribute.type; + baseAttribute.stepMode = attribute.stepMode || baseAttribute.stepMode; + } + } + for (const binding of overrideLayout?.bindings || []) { + const baseBinding = getShaderLayoutBindingByName(mergedLayout, binding.name); + if (!baseBinding) { + log2.warn(`shader layout binding ${binding.name} not present in shader`); + continue; + } + Object.assign(baseBinding, binding); + } + return mergedLayout; + } + function getShaderLayoutBindingByName(shaderLayout, bindingName) { + return shaderLayout.bindings.find((binding) => binding.name === bindingName || binding.name === `${bindingName}Uniforms` || `${binding.name}Uniforms` === bindingName); + } + function getBindingValueForLayoutBinding(bindings, bindingName) { + return bindings[bindingName] || bindings[`${bindingName}Uniforms`] || bindings[bindingName.replace(/Uniforms$/, "")]; + } + var WEBGLRenderPipeline; + var init_webgl_render_pipeline = __esm({ + "node_modules/@luma.gl/webgl/dist/adapter/resources/webgl-render-pipeline.js"() { + init_dist4(); + init_device_parameters(); + init_set_uniform(); + init_webgl_buffer(); + init_webgl_framebuffer(); + init_webgl_texture(); + init_webgl_texture_view(); + init_webgl_topology_utils(); + WEBGLRenderPipeline = class extends RenderPipeline { + /** The WebGL device that created this render pipeline */ + device; + /** Handle to underlying WebGL program */ + handle; + /** vertex shader */ + vs; + /** fragment shader */ + fs; + /** The layout extracted from shader by WebGL introspection APIs */ + introspectedLayout; + /** Compatibility path for direct pipeline.setBindings() usage */ + bindings = {}; + /** Compatibility path for direct pipeline.uniforms usage */ + uniforms = {}; + /** WebGL varyings */ + varyings = null; + _uniformCount = 0; + _uniformSetters = {}; + // TODO are these used? + get [Symbol.toStringTag]() { + return "WEBGLRenderPipeline"; + } + constructor(device, props) { + super(device, props); + this.device = device; + const webglSharedRenderPipeline = this.sharedRenderPipeline || this.device._createSharedRenderPipelineWebGL(props); + this.sharedRenderPipeline = webglSharedRenderPipeline; + this.handle = webglSharedRenderPipeline.handle; + this.vs = webglSharedRenderPipeline.vs; + this.fs = webglSharedRenderPipeline.fs; + this.linkStatus = webglSharedRenderPipeline.linkStatus; + this.introspectedLayout = webglSharedRenderPipeline.introspectedLayout; + this.device._setWebGLDebugMetadata(this.handle, this, { spector: { id: this.props.id } }); + this.shaderLayout = props.shaderLayout ? mergeShaderLayout(this.introspectedLayout, props.shaderLayout) : this.introspectedLayout; + } + destroy() { + if (this.destroyed) { + return; + } + if (this.sharedRenderPipeline && !this.props._sharedRenderPipeline) { + this.sharedRenderPipeline.destroy(); + } + this.destroyResource(); + } + /** + * Compatibility shim for code paths that still set bindings on the pipeline. + * Shared-model draws pass bindings per draw and do not rely on this state. + */ + setBindings(bindings, options) { + const flatBindings = flattenBindingsByGroup(normalizeBindingsByGroup(this.shaderLayout, bindings)); + for (const [name2, value] of Object.entries(flatBindings)) { + const binding = getShaderLayoutBindingByName(this.shaderLayout, name2); + if (!binding) { + const validBindings = this.shaderLayout.bindings.map((binding_) => `"${binding_.name}"`).join(", "); + if (!options?.disableWarnings) { + log2.warn(`No binding "${name2}" in render pipeline "${this.id}", expected one of ${validBindings}`, value)(); + } + } else { + if (!value) { + log2.warn(`Unsetting binding "${name2}" in render pipeline "${this.id}"`)(); + } + switch (binding.type) { + case "uniform": + if (!(value instanceof WEBGLBuffer) && !(value.buffer instanceof WEBGLBuffer)) { + throw new Error("buffer value"); + } + break; + case "texture": + if (!(value instanceof WEBGLTextureView || value instanceof WEBGLTexture || value instanceof WEBGLFramebuffer)) { + throw new Error(`${this} Bad texture binding for ${name2}`); + } + break; + case "sampler": + log2.warn(`Ignoring sampler ${name2}`)(); + break; + default: + throw new Error(binding.type); + } + this.bindings[name2] = value; + } + } + } + /** @todo needed for portable model + * @note The WebGL API is offers many ways to draw things + * This function unifies those ways into a single call using common parameters with sane defaults + */ + draw(options) { + this._syncLinkStatus(); + const drawBindings = options.bindGroups ? flattenBindingsByGroup(options.bindGroups) : options.bindings || this.bindings; + const { + renderPass, + parameters = this.props.parameters, + topology = this.props.topology, + vertexArray, + vertexCount, + // indexCount, + instanceCount, + isInstanced = false, + firstVertex = 0, + // firstIndex, + // firstInstance, + // baseVertex, + transformFeedback, + uniforms = this.uniforms + } = options; + const glDrawMode = getGLDrawMode(topology); + const isIndexed = Boolean(vertexArray.indexBuffer); + const glIndexType = vertexArray.indexBuffer?.glIndexType; + if (this.linkStatus !== "success") { + log2.info(2, `RenderPipeline:${this.id}.draw() aborted - waiting for shader linking`)(); + return false; + } + if (!this._areTexturesRenderable(drawBindings)) { + log2.info(2, `RenderPipeline:${this.id}.draw() aborted - textures not yet loaded`)(); + return false; + } + this.device.gl.useProgram(this.handle); + vertexArray.bindBeforeRender(renderPass); + if (transformFeedback) { + transformFeedback.begin(this.props.topology); + } + this._applyBindings(drawBindings, { disableWarnings: this.props.disableWarnings }); + this._applyUniforms(uniforms); + const webglRenderPass = renderPass; + withDeviceAndGLParameters(this.device, parameters, webglRenderPass.glParameters, () => { + if (isIndexed && isInstanced) { + this.device.gl.drawElementsInstanced( + glDrawMode, + vertexCount || 0, + // indexCount? + glIndexType, + firstVertex, + instanceCount || 0 + ); + } else if (isIndexed) { + this.device.gl.drawElements(glDrawMode, vertexCount || 0, glIndexType, firstVertex); + } else if (isInstanced) { + this.device.gl.drawArraysInstanced(glDrawMode, firstVertex, vertexCount || 0, instanceCount || 0); + } else { + this.device.gl.drawArrays(glDrawMode, firstVertex, vertexCount || 0); + } + if (transformFeedback) { + transformFeedback.end(); + } + }); + vertexArray.unbindAfterRender(renderPass); + return true; + } + /** + * Checks if all texture-values uniforms are renderable (i.e. loaded) + * Update a texture if needed (e.g. from video) + * Note: This is currently done before every draw call + */ + _areTexturesRenderable(bindings) { + let texturesRenderable = true; + for (const bindingInfo of this.shaderLayout.bindings) { + if (!getBindingValueForLayoutBinding(bindings, bindingInfo.name)) { + log2.warn(`Binding ${bindingInfo.name} not found in ${this.id}`)(); + texturesRenderable = false; + } + } + return texturesRenderable; + } + /** Apply any bindings (before each draw call) */ + _applyBindings(bindings, _options) { + this._syncLinkStatus(); + if (this.linkStatus !== "success") { + return; + } + const { gl } = this.device; + gl.useProgram(this.handle); + let textureUnit = 0; + let uniformBufferIndex = 0; + for (const binding of this.shaderLayout.bindings) { + const value = getBindingValueForLayoutBinding(bindings, binding.name); + if (!value) { + throw new Error(`No value for binding ${binding.name} in ${this.id}`); + } + switch (binding.type) { + case "uniform": + const { name: name2 } = binding; + const location = gl.getUniformBlockIndex(this.handle, name2); + if (location === 4294967295) { + throw new Error(`Invalid uniform block name ${name2}`); + } + gl.uniformBlockBinding(this.handle, location, uniformBufferIndex); + if (value instanceof WEBGLBuffer) { + gl.bindBufferBase(35345, uniformBufferIndex, value.handle); + } else { + const bufferBinding = value; + gl.bindBufferRange(35345, uniformBufferIndex, bufferBinding.buffer.handle, bufferBinding.offset || 0, bufferBinding.size || bufferBinding.buffer.byteLength - (bufferBinding.offset || 0)); + } + uniformBufferIndex += 1; + break; + case "texture": + if (!(value instanceof WEBGLTextureView || value instanceof WEBGLTexture || value instanceof WEBGLFramebuffer)) { + throw new Error("texture"); + } + let texture; + if (value instanceof WEBGLTextureView) { + texture = value.texture; + } else if (value instanceof WEBGLTexture) { + texture = value; + } else if (value instanceof WEBGLFramebuffer && value.colorAttachments[0] instanceof WEBGLTextureView) { + log2.warn("Passing framebuffer in texture binding may be deprecated. Use fbo.colorAttachments[0] instead")(); + texture = value.colorAttachments[0].texture; + } else { + throw new Error("No texture"); + } + gl.activeTexture(33984 + textureUnit); + gl.bindTexture(texture.glTarget, texture.handle); + textureUnit += 1; + break; + case "sampler": + break; + case "storage": + case "read-only-storage": + throw new Error(`binding type '${binding.type}' not supported in WebGL`); + } + } + } + /** + * Due to program sharing, uniforms need to be reset before every draw call + * (though caching will avoid redundant WebGL calls) + */ + _applyUniforms(uniforms) { + for (const uniformLayout of this.shaderLayout.uniforms || []) { + const { name: name2, location, type, textureUnit } = uniformLayout; + const value = uniforms[name2] ?? textureUnit; + if (value !== void 0) { + setUniform(this.device.gl, location, type, value); + } + } + } + _syncLinkStatus() { + this.linkStatus = this.sharedRenderPipeline.linkStatus; + } + }; + } + }); + + // node_modules/@luma.gl/webgl/dist/adapter/converters/webgl-shadertypes.js + function convertDataTypeToGLDataType(normalizedType) { + return NORMALIZED_SHADER_TYPE_TO_WEBGL[normalizedType]; + } + function convertGLUniformTypeToShaderVariableType(glUniformType) { + return WEBGL_SHADER_TYPES[glUniformType]; + } + function isGLSamplerType(type) { + return Boolean(WEBGL_SAMPLER_TO_TEXTURE_BINDINGS[type]); + } + function getTextureBindingFromGLSamplerType(glSamplerType) { + return WEBGL_SAMPLER_TO_TEXTURE_BINDINGS[glSamplerType]; + } + var WEBGL_SHADER_TYPES, WEBGL_SAMPLER_TO_TEXTURE_BINDINGS, NORMALIZED_SHADER_TYPE_TO_WEBGL; + var init_webgl_shadertypes = __esm({ + "node_modules/@luma.gl/webgl/dist/adapter/converters/webgl-shadertypes.js"() { + WEBGL_SHADER_TYPES = { + [5126]: "f32", + [35664]: "vec2", + [35665]: "vec3", + [35666]: "vec4", + [5124]: "i32", + [35667]: "vec2", + [35668]: "vec3", + [35669]: "vec4", + [5125]: "u32", + [36294]: "vec2", + [36295]: "vec3", + [36296]: "vec4", + [35670]: "f32", + [35671]: "vec2", + [35672]: "vec3", + [35673]: "vec4", + // TODO - are sizes/components below correct? + [35674]: "mat2x2", + [35685]: "mat2x3", + [35686]: "mat2x4", + [35687]: "mat3x2", + [35675]: "mat3x3", + [35688]: "mat3x4", + [35689]: "mat4x2", + [35690]: "mat4x3", + [35676]: "mat4x4" + }; + WEBGL_SAMPLER_TO_TEXTURE_BINDINGS = { + [35678]: { viewDimension: "2d", sampleType: "float" }, + [35680]: { viewDimension: "cube", sampleType: "float" }, + [35679]: { viewDimension: "3d", sampleType: "float" }, + [35682]: { viewDimension: "3d", sampleType: "depth" }, + [36289]: { viewDimension: "2d-array", sampleType: "float" }, + [36292]: { viewDimension: "2d-array", sampleType: "depth" }, + [36293]: { viewDimension: "cube", sampleType: "float" }, + [36298]: { viewDimension: "2d", sampleType: "sint" }, + [36299]: { viewDimension: "3d", sampleType: "sint" }, + [36300]: { viewDimension: "cube", sampleType: "sint" }, + [36303]: { viewDimension: "2d-array", sampleType: "uint" }, + [36306]: { viewDimension: "2d", sampleType: "uint" }, + [36307]: { viewDimension: "3d", sampleType: "uint" }, + [36308]: { viewDimension: "cube", sampleType: "uint" }, + [36311]: { viewDimension: "2d-array", sampleType: "uint" } + }; + NORMALIZED_SHADER_TYPE_TO_WEBGL = { + uint8: 5121, + sint8: 5120, + unorm8: 5121, + snorm8: 5120, + uint16: 5123, + sint16: 5122, + unorm16: 5123, + snorm16: 5122, + uint32: 5125, + sint32: 5124, + // WebGPU does not support normalized 32 bit integer attributes + // 'unorm32': GL.UNSIGNED_INT, + // 'snorm32': GL.INT, + float16: 5131, + float32: 5126 + }; + } + }); + + // node_modules/@luma.gl/webgl/dist/adapter/helpers/get-shader-layout-from-glsl.js + function getShaderLayoutFromGLSL(gl, program) { + const shaderLayout = { + attributes: [], + bindings: [] + }; + shaderLayout.attributes = readAttributeDeclarations(gl, program); + const uniformBlocks = readUniformBlocks(gl, program); + for (const uniformBlock11 of uniformBlocks) { + const uniforms2 = uniformBlock11.uniforms.map((uniform) => ({ + name: uniform.name, + format: uniform.format, + byteOffset: uniform.byteOffset, + byteStride: uniform.byteStride, + arrayLength: uniform.arrayLength + })); + shaderLayout.bindings.push({ + type: "uniform", + name: uniformBlock11.name, + group: 0, + location: uniformBlock11.location, + visibility: (uniformBlock11.vertex ? 1 : 0) & (uniformBlock11.fragment ? 2 : 0), + minBindingSize: uniformBlock11.byteLength, + uniforms: uniforms2 + }); + } + const uniforms = readUniformBindings(gl, program); + let textureUnit = 0; + for (const uniform of uniforms) { + if (isGLSamplerType(uniform.type)) { + const { viewDimension, sampleType } = getTextureBindingFromGLSamplerType(uniform.type); + shaderLayout.bindings.push({ + type: "texture", + name: uniform.name, + group: 0, + location: textureUnit, + viewDimension, + sampleType + }); + uniform.textureUnit = textureUnit; + textureUnit += 1; + } + } + if (uniforms.length) { + shaderLayout.uniforms = uniforms; + } + const varyings = readVaryings(gl, program); + if (varyings?.length) { + shaderLayout.varyings = varyings; + } + return shaderLayout; + } + function readAttributeDeclarations(gl, program) { + const attributes = []; + const count2 = gl.getProgramParameter(program, 35721); + for (let index2 = 0; index2 < count2; index2++) { + const activeInfo = gl.getActiveAttrib(program, index2); + if (!activeInfo) { + throw new Error("activeInfo"); + } + const { + name: name2, + type: compositeType + /* , size*/ + } = activeInfo; + const location = gl.getAttribLocation(program, name2); + if (location >= 0) { + const attributeType = convertGLUniformTypeToShaderVariableType(compositeType); + const stepMode = /instance/i.test(name2) ? "instance" : "vertex"; + attributes.push({ + name: name2, + location, + stepMode, + type: attributeType + // size - for arrays, size is the number of elements in the array + }); + } + } + attributes.sort((a, b) => a.location - b.location); + return attributes; + } + function readVaryings(gl, program) { + const varyings = []; + const count2 = gl.getProgramParameter(program, 35971); + for (let location = 0; location < count2; location++) { + const activeInfo = gl.getTransformFeedbackVarying(program, location); + if (!activeInfo) { + throw new Error("activeInfo"); + } + const { name: name2, type: glUniformType, size } = activeInfo; + const uniformType = convertGLUniformTypeToShaderVariableType(glUniformType); + const { type, components } = getVariableShaderTypeInfo(uniformType); + varyings.push({ location, name: name2, type, size: size * components }); + } + varyings.sort((a, b) => a.location - b.location); + return varyings; + } + function readUniformBindings(gl, program) { + const uniforms = []; + const uniformCount = gl.getProgramParameter(program, 35718); + for (let i = 0; i < uniformCount; i++) { + const activeInfo = gl.getActiveUniform(program, i); + if (!activeInfo) { + throw new Error("activeInfo"); + } + const { name: rawName, size, type } = activeInfo; + const { name: name2, isArray: isArray5 } = parseUniformName(rawName); + let webglLocation = gl.getUniformLocation(program, name2); + const uniformInfo = { + // WebGL locations are uniquely typed but just numbers + location: webglLocation, + name: name2, + size, + type, + isArray: isArray5 + }; + uniforms.push(uniformInfo); + if (uniformInfo.size > 1) { + for (let j = 0; j < uniformInfo.size; j++) { + const elementName = `${name2}[${j}]`; + webglLocation = gl.getUniformLocation(program, elementName); + const arrayElementUniformInfo = { + ...uniformInfo, + name: elementName, + location: webglLocation + }; + uniforms.push(arrayElementUniformInfo); + } + } + } + return uniforms; + } + function readUniformBlocks(gl, program) { + const getBlockParameter = (blockIndex, pname) => gl.getActiveUniformBlockParameter(program, blockIndex, pname); + const uniformBlocks = []; + const blockCount = gl.getProgramParameter(program, 35382); + for (let blockIndex = 0; blockIndex < blockCount; blockIndex++) { + const blockInfo = { + name: gl.getActiveUniformBlockName(program, blockIndex) || "", + location: getBlockParameter(blockIndex, 35391), + byteLength: getBlockParameter(blockIndex, 35392), + vertex: getBlockParameter(blockIndex, 35396), + fragment: getBlockParameter(blockIndex, 35398), + uniformCount: getBlockParameter(blockIndex, 35394), + uniforms: [] + }; + const uniformIndices = getBlockParameter(blockIndex, 35395) || []; + const uniformType = gl.getActiveUniforms(program, uniformIndices, 35383); + const uniformArrayLength = gl.getActiveUniforms(program, uniformIndices, 35384); + const uniformOffset = gl.getActiveUniforms(program, uniformIndices, 35387); + const uniformStride = gl.getActiveUniforms(program, uniformIndices, 35388); + for (let i = 0; i < blockInfo.uniformCount; ++i) { + const uniformIndex = uniformIndices[i]; + if (uniformIndex !== void 0) { + const activeInfo = gl.getActiveUniform(program, uniformIndex); + if (!activeInfo) { + throw new Error("activeInfo"); + } + const format2 = convertGLUniformTypeToShaderVariableType(uniformType[i]); + blockInfo.uniforms.push({ + name: activeInfo.name, + format: format2, + type: uniformType[i], + arrayLength: uniformArrayLength[i], + byteOffset: uniformOffset[i], + byteStride: uniformStride[i] + // matrixStride: uniformStride[i], + // rowMajor: uniformRowMajor[i] + }); + } + } + const uniformInstancePrefixes = new Set(blockInfo.uniforms.map((uniform) => uniform.name.split(".")[0]).filter((instanceName) => Boolean(instanceName))); + const blockAlias = blockInfo.name.replace(/Uniforms$/, ""); + if (uniformInstancePrefixes.size === 1 && !uniformInstancePrefixes.has(blockInfo.name) && !uniformInstancePrefixes.has(blockAlias)) { + const [instanceName] = uniformInstancePrefixes; + log2.warn(`Uniform block "${blockInfo.name}" uses GLSL instance "${instanceName}". luma.gl binds uniform buffers by block name ("${blockInfo.name}") and alias ("${blockAlias}"). Prefer matching the instance name to one of those to avoid confusing silent mismatches.`)(); + } + uniformBlocks.push(blockInfo); + } + uniformBlocks.sort((a, b) => a.location - b.location); + return uniformBlocks; + } + function parseUniformName(name2) { + if (name2[name2.length - 1] !== "]") { + return { + name: name2, + length: 1, + isArray: false + }; + } + const UNIFORM_NAME_REGEXP = /([^[]*)(\[[0-9]+\])?/; + const matches3 = UNIFORM_NAME_REGEXP.exec(name2); + const uniformName = assertDefined(matches3?.[1], `Failed to parse GLSL uniform name ${name2}`); + return { + name: uniformName, + // TODO - is this a bug, shouldn't we return the value? + length: matches3?.[2] ? 1 : 0, + isArray: Boolean(matches3?.[2]) + }; + } + var init_get_shader_layout_from_glsl = __esm({ + "node_modules/@luma.gl/webgl/dist/adapter/helpers/get-shader-layout-from-glsl.js"() { + init_dist4(); + init_webgl_shadertypes(); + } + }); + + // node_modules/@luma.gl/webgl/dist/adapter/resources/webgl-shared-render-pipeline.js + var LOG_PROGRAM_PERF_PRIORITY, WEBGLSharedRenderPipeline; + var init_webgl_shared_render_pipeline = __esm({ + "node_modules/@luma.gl/webgl/dist/adapter/resources/webgl-shared-render-pipeline.js"() { + init_dist4(); + init_get_shader_layout_from_glsl(); + init_webgl_shadertypes(); + LOG_PROGRAM_PERF_PRIORITY = 4; + WEBGLSharedRenderPipeline = class extends SharedRenderPipeline { + device; + handle; + vs; + fs; + introspectedLayout = { attributes: [], bindings: [], uniforms: [] }; + linkStatus = "pending"; + constructor(device, props) { + super(device, props); + this.device = device; + this.handle = props.handle || this.device.gl.createProgram(); + this.vs = props.vs; + this.fs = props.fs; + if (props.varyings && props.varyings.length > 0) { + this.device.gl.transformFeedbackVaryings(this.handle, props.varyings, props.bufferMode || 35981); + } + this._linkShaders(); + log2.time(3, `RenderPipeline ${this.id} - shaderLayout introspection`)(); + this.introspectedLayout = getShaderLayoutFromGLSL(this.device.gl, this.handle); + log2.timeEnd(3, `RenderPipeline ${this.id} - shaderLayout introspection`)(); + } + destroy() { + if (this.destroyed) { + return; + } + this.device.gl.useProgram(null); + this.device.gl.deleteProgram(this.handle); + this.handle.destroyed = true; + this.destroyResource(); + } + async _linkShaders() { + const { gl } = this.device; + gl.attachShader(this.handle, this.vs.handle); + gl.attachShader(this.handle, this.fs.handle); + log2.time(LOG_PROGRAM_PERF_PRIORITY, `linkProgram for ${this.id}`)(); + gl.linkProgram(this.handle); + log2.timeEnd(LOG_PROGRAM_PERF_PRIORITY, `linkProgram for ${this.id}`)(); + if (!this.device.features.has("compilation-status-async-webgl")) { + const status2 = this._getLinkStatus(); + this._reportLinkStatus(status2); + return; + } + log2.once(1, "RenderPipeline linking is asynchronous")(); + await this._waitForLinkComplete(); + log2.info(2, `RenderPipeline ${this.id} - async linking complete: ${this.linkStatus}`)(); + const status = this._getLinkStatus(); + this._reportLinkStatus(status); + } + async _reportLinkStatus(status) { + switch (status) { + case "success": + return; + default: + const errorType = status === "link-error" ? "Link error" : "Validation error"; + switch (this.vs.compilationStatus) { + case "error": + this.vs.debugShader(); + throw new Error(`${this} ${errorType} during compilation of ${this.vs}`); + case "pending": + await this.vs.asyncCompilationStatus; + this.vs.debugShader(); + break; + case "success": + break; + } + switch (this.fs?.compilationStatus) { + case "error": + this.fs.debugShader(); + throw new Error(`${this} ${errorType} during compilation of ${this.fs}`); + case "pending": + await this.fs.asyncCompilationStatus; + this.fs.debugShader(); + break; + case "success": + break; + } + const linkErrorLog = this.device.gl.getProgramInfoLog(this.handle); + this.device.reportError(new Error(`${errorType} during ${status}: ${linkErrorLog}`), this)(); + this.device.debug(); + } + } + _getLinkStatus() { + const { gl } = this.device; + const linked = gl.getProgramParameter(this.handle, 35714); + if (!linked) { + this.linkStatus = "error"; + return "link-error"; + } + this._initializeSamplerUniforms(); + gl.validateProgram(this.handle); + const validated = gl.getProgramParameter(this.handle, 35715); + if (!validated) { + this.linkStatus = "error"; + return "validation-error"; + } + this.linkStatus = "success"; + return "success"; + } + _initializeSamplerUniforms() { + const { gl } = this.device; + gl.useProgram(this.handle); + let textureUnit = 0; + const uniformCount = gl.getProgramParameter(this.handle, 35718); + for (let uniformIndex = 0; uniformIndex < uniformCount; uniformIndex++) { + const activeInfo = gl.getActiveUniform(this.handle, uniformIndex); + if (activeInfo && isGLSamplerType(activeInfo.type)) { + const isArray5 = activeInfo.name.endsWith("[0]"); + const uniformName = isArray5 ? activeInfo.name.slice(0, -3) : activeInfo.name; + const location = gl.getUniformLocation(this.handle, uniformName); + if (location !== null) { + textureUnit = this._assignSamplerUniform(location, activeInfo, isArray5, textureUnit); + } + } + } + } + _assignSamplerUniform(location, activeInfo, isArray5, textureUnit) { + const { gl } = this.device; + if (isArray5 && activeInfo.size > 1) { + const textureUnits = Int32Array.from({ length: activeInfo.size }, (_, arrayIndex) => textureUnit + arrayIndex); + gl.uniform1iv(location, textureUnits); + return textureUnit + activeInfo.size; + } + gl.uniform1i(location, textureUnit); + return textureUnit + 1; + } + async _waitForLinkComplete() { + const waitMs = async (ms) => await new Promise((resolve2) => setTimeout(resolve2, ms)); + const DELAY_MS = 10; + if (!this.device.features.has("compilation-status-async-webgl")) { + await waitMs(DELAY_MS); + return; + } + const { gl } = this.device; + for (; ; ) { + const complete = gl.getProgramParameter(this.handle, 37297); + if (complete) { + return; + } + await waitMs(DELAY_MS); + } + } + }; + } + }); + + // node_modules/@luma.gl/webgl/dist/adapter/resources/webgl-command-buffer.js + function _copyBufferToBuffer(device, options) { + const source3 = options.sourceBuffer; + const destination = options.destinationBuffer; + device.gl.bindBuffer(36662, source3.handle); + device.gl.bindBuffer(36663, destination.handle); + device.gl.copyBufferSubData(36662, 36663, options.sourceOffset ?? 0, options.destinationOffset ?? 0, options.size); + device.gl.bindBuffer(36662, null); + device.gl.bindBuffer(36663, null); + } + function _copyBufferToTexture(_device, _options) { + throw new Error("copyBufferToTexture is not supported in WebGL"); + } + function _copyTextureToBuffer(device, options) { + const { sourceTexture, mipLevel = 0, aspect = "all", width = options.sourceTexture.width, height = options.sourceTexture.height, depthOrArrayLayers, origin = [0, 0, 0], destinationBuffer, byteOffset = 0, bytesPerRow, rowsPerImage } = options; + if (sourceTexture instanceof Texture) { + sourceTexture.readBuffer({ + x: origin[0] ?? 0, + y: origin[1] ?? 0, + z: origin[2] ?? 0, + width, + height, + depthOrArrayLayers, + mipLevel, + aspect, + byteOffset + }, destinationBuffer); + return; + } + if (aspect !== "all") { + throw new Error("aspect not supported in WebGL"); + } + if (mipLevel !== 0 || depthOrArrayLayers !== void 0 || bytesPerRow || rowsPerImage) { + throw new Error("not implemented"); + } + const { framebuffer, destroyFramebuffer } = getFramebuffer(sourceTexture); + let prevHandle; + try { + const webglBuffer = destinationBuffer; + const sourceWidth = width || framebuffer.width; + const sourceHeight = height || framebuffer.height; + const colorAttachment0 = assertDefined(framebuffer.colorAttachments[0]); + const sourceParams = getTextureFormatWebGL(colorAttachment0.texture.props.format); + const sourceFormat = sourceParams.format; + const sourceType = sourceParams.type; + device.gl.bindBuffer(35051, webglBuffer.handle); + prevHandle = device.gl.bindFramebuffer(36160, framebuffer.handle); + device.gl.readPixels(origin[0], origin[1], sourceWidth, sourceHeight, sourceFormat, sourceType, byteOffset); + } finally { + device.gl.bindBuffer(35051, null); + if (prevHandle !== void 0) { + device.gl.bindFramebuffer(36160, prevHandle); + } + if (destroyFramebuffer) { + framebuffer.destroy(); + } + } + } + function _copyTextureToTexture(device, options) { + const { + /** Texture to copy to/from. */ + sourceTexture, + /** Mip-map level of the texture to copy to (Default 0) */ + destinationMipLevel = 0, + /** Defines which aspects of the texture to copy to/from. */ + // aspect = 'all', + /** Defines the origin of the copy - the minimum corner of the texture sub-region to copy from. */ + origin = [0, 0], + /** Defines the origin of the copy - the minimum corner of the texture sub-region to copy to. */ + destinationOrigin = [0, 0, 0], + /** Texture to copy to/from. */ + destinationTexture + /** Mip-map level of the texture to copy to/from. (Default 0) */ + // destinationMipLevel = options.mipLevel, + /** Defines the origin of the copy - the minimum corner of the texture sub-region to copy to/from. */ + // destinationOrigin = [0, 0], + /** Defines which aspects of the texture to copy to/from. */ + // destinationAspect = options.aspect, + } = options; + let { + width = options.destinationTexture.width, + height = options.destinationTexture.height + // depthOrArrayLayers = 0 + } = options; + const { framebuffer, destroyFramebuffer } = getFramebuffer(sourceTexture); + const [sourceX = 0, sourceY = 0] = origin; + const [destinationX, destinationY, destinationZ] = destinationOrigin; + const prevHandle = device.gl.bindFramebuffer(36160, framebuffer.handle); + let texture; + let textureTarget; + if (destinationTexture instanceof WEBGLTexture) { + texture = destinationTexture; + width = Number.isFinite(width) ? width : texture.width; + height = Number.isFinite(height) ? height : texture.height; + texture._bind(0); + textureTarget = texture.glTarget; + } else { + throw new Error("invalid destination"); + } + switch (textureTarget) { + case 3553: + case 34067: + device.gl.copyTexSubImage2D(textureTarget, destinationMipLevel, destinationX, destinationY, sourceX, sourceY, width, height); + break; + case 35866: + case 32879: + device.gl.copyTexSubImage3D(textureTarget, destinationMipLevel, destinationX, destinationY, destinationZ, sourceX, sourceY, width, height); + break; + default: + } + if (texture) { + texture._unbind(); + } + device.gl.bindFramebuffer(36160, prevHandle); + if (destroyFramebuffer) { + framebuffer.destroy(); + } + } + function getFramebuffer(source3) { + if (source3 instanceof Texture) { + const { width, height, id } = source3; + const framebuffer = source3.device.createFramebuffer({ + id: `framebuffer-for-${id}`, + width, + height, + colorAttachments: [source3] + }); + return { framebuffer, destroyFramebuffer: true }; + } + return { framebuffer: source3, destroyFramebuffer: false }; + } + var WEBGLCommandBuffer; + var init_webgl_command_buffer = __esm({ + "node_modules/@luma.gl/webgl/dist/adapter/resources/webgl-command-buffer.js"() { + init_dist4(); + init_webgl_texture_table(); + init_webgl_texture(); + WEBGLCommandBuffer = class extends CommandBuffer { + device; + handle = null; + commands = []; + constructor(device, props = {}) { + super(device, props); + this.device = device; + } + _executeCommands(commands = this.commands) { + for (const command of commands) { + switch (command.name) { + case "copy-buffer-to-buffer": + _copyBufferToBuffer(this.device, command.options); + break; + case "copy-buffer-to-texture": + _copyBufferToTexture(this.device, command.options); + break; + case "copy-texture-to-buffer": + _copyTextureToBuffer(this.device, command.options); + break; + case "copy-texture-to-texture": + _copyTextureToTexture(this.device, command.options); + break; + // case 'clear-texture': + // _clearTexture(this.device, command.options); + // break; + default: + throw new Error(command.name); + } + } + } + }; + } + }); + + // node_modules/@luma.gl/webgl/dist/adapter/resources/webgl-render-pass.js + var COLOR_CHANNELS, WEBGLRenderPass; + var init_webgl_render_pass = __esm({ + "node_modules/@luma.gl/webgl/dist/adapter/resources/webgl-render-pass.js"() { + init_dist4(); + init_with_parameters(); + init_unified_parameter_api(); + COLOR_CHANNELS = [1, 2, 4, 8]; + WEBGLRenderPass = class extends RenderPass { + device; + handle = null; + /** Parameters that should be applied before each draw call */ + glParameters = {}; + constructor(device, props) { + super(device, props); + this.device = device; + const webglFramebuffer = this.props.framebuffer; + const isDefaultFramebuffer = !webglFramebuffer || webglFramebuffer.handle === null; + if (isDefaultFramebuffer) { + device.getDefaultCanvasContext()._resizeDrawingBufferIfNeeded(); + } + let viewport; + if (!props?.parameters?.viewport) { + if (!isDefaultFramebuffer && webglFramebuffer) { + const { width, height } = webglFramebuffer; + viewport = [0, 0, width, height]; + } else { + const [width, height] = device.getDefaultCanvasContext().getDrawingBufferSize(); + viewport = [0, 0, width, height]; + } + } + this.device.pushState(); + this.setParameters({ viewport, ...this.props.parameters }); + if (!isDefaultFramebuffer && webglFramebuffer?.colorAttachments.length) { + const drawBuffers = webglFramebuffer.colorAttachments.map((_, i) => 36064 + i); + this.device.gl.drawBuffers(drawBuffers); + } else if (isDefaultFramebuffer) { + this.device.gl.drawBuffers([1029]); + } + this.clear(); + if (this.props.timestampQuerySet && this.props.beginTimestampIndex !== void 0) { + const webglQuerySet = this.props.timestampQuerySet; + webglQuerySet.writeTimestamp(this.props.beginTimestampIndex); + } + } + end() { + if (this.destroyed) { + return; + } + if (this.props.timestampQuerySet && this.props.endTimestampIndex !== void 0) { + const webglQuerySet = this.props.timestampQuerySet; + webglQuerySet.writeTimestamp(this.props.endTimestampIndex); + } + this.device.popState(); + this.destroy(); + } + pushDebugGroup(groupLabel) { + } + popDebugGroup() { + } + insertDebugMarker(markerLabel) { + } + // beginOcclusionQuery(queryIndex: number): void; + // endOcclusionQuery(): void; + // executeBundles(bundles: Iterable): void; + /** + * Maps RenderPass parameters to GL parameters + */ + setParameters(parameters = {}) { + const glParameters = { ...this.glParameters }; + glParameters.framebuffer = this.props.framebuffer || null; + if (this.props.depthReadOnly) { + glParameters.depthMask = !this.props.depthReadOnly; + } + glParameters.stencilMask = this.props.stencilReadOnly ? 0 : 1; + glParameters[35977] = this.props.discard; + if (parameters.viewport) { + if (parameters.viewport.length >= 6) { + glParameters.viewport = parameters.viewport.slice(0, 4); + glParameters.depthRange = [ + parameters.viewport[4], + parameters.viewport[5] + ]; + } else { + glParameters.viewport = parameters.viewport; + } + } + if (parameters.scissorRect) { + glParameters.scissorTest = true; + glParameters.scissor = parameters.scissorRect; + } + if (parameters.blendConstant) { + glParameters.blendColor = parameters.blendConstant; + } + if (parameters.stencilReference !== void 0) { + glParameters[2967] = parameters.stencilReference; + glParameters[36003] = parameters.stencilReference; + } + if ("colorMask" in parameters) { + glParameters.colorMask = COLOR_CHANNELS.map((channel) => Boolean(channel & parameters.colorMask)); + } + this.glParameters = glParameters; + setGLParameters(this.device.gl, glParameters); + } + beginOcclusionQuery(queryIndex) { + const webglQuerySet = this.props.occlusionQuerySet; + webglQuerySet?.beginOcclusionQuery(); + } + endOcclusionQuery() { + const webglQuerySet = this.props.occlusionQuerySet; + webglQuerySet?.endOcclusionQuery(); + } + // PRIVATE + /** + * Optionally clears depth, color and stencil buffers based on parameters + */ + clear() { + const glParameters = { ...this.glParameters }; + let clearMask = 0; + if (this.props.clearColors) { + this.props.clearColors.forEach((color2, drawBufferIndex) => { + if (color2) { + this.clearColorBuffer(drawBufferIndex, color2); + } + }); + } + if (this.props.clearColor !== false && this.props.clearColors === void 0) { + clearMask |= 16384; + glParameters.clearColor = this.props.clearColor; + } + if (this.props.clearDepth !== false) { + clearMask |= 256; + glParameters.clearDepth = this.props.clearDepth; + } + if (this.props.clearStencil !== false) { + clearMask |= 1024; + glParameters.clearStencil = this.props.clearStencil; + } + if (clearMask !== 0) { + withGLParameters(this.device.gl, glParameters, () => { + this.device.gl.clear(clearMask); + }); + } + } + /** + * WebGL2 - clear a specific color buffer + */ + clearColorBuffer(drawBuffer = 0, value = [0, 0, 0, 0]) { + withGLParameters(this.device.gl, { framebuffer: this.props.framebuffer }, () => { + switch (value.constructor) { + case Int8Array: + case Int16Array: + case Int32Array: + this.device.gl.clearBufferiv(6144, drawBuffer, value); + break; + case Uint8Array: + case Uint8ClampedArray: + case Uint16Array: + case Uint32Array: + this.device.gl.clearBufferuiv(6144, drawBuffer, value); + break; + case Float32Array: + this.device.gl.clearBufferfv(6144, drawBuffer, value); + break; + default: + throw new Error("clearColorBuffer: color must be typed array"); + } + }); + } + }; + } + }); + + // node_modules/@luma.gl/webgl/dist/adapter/resources/webgl-command-encoder.js + var WEBGLCommandEncoder; + var init_webgl_command_encoder = __esm({ + "node_modules/@luma.gl/webgl/dist/adapter/resources/webgl-command-encoder.js"() { + init_dist4(); + init_webgl_command_buffer(); + init_webgl_render_pass(); + WEBGLCommandEncoder = class extends CommandEncoder { + device; + handle = null; + commandBuffer; + constructor(device, props) { + super(device, props); + this.device = device; + this.commandBuffer = new WEBGLCommandBuffer(device, { + id: `${this.props.id}-command-buffer` + }); + } + destroy() { + this.destroyResource(); + } + finish(props) { + if (props?.id && this.commandBuffer.id !== props.id) { + this.commandBuffer.id = props.id; + this.commandBuffer.props.id = props.id; + } + this.destroy(); + return this.commandBuffer; + } + beginRenderPass(props = {}) { + return new WEBGLRenderPass(this.device, this._applyTimeProfilingToPassProps(props)); + } + beginComputePass(props = {}) { + throw new Error("ComputePass not supported in WebGL"); + } + copyBufferToBuffer(options) { + this.commandBuffer.commands.push({ name: "copy-buffer-to-buffer", options }); + } + copyBufferToTexture(options) { + this.commandBuffer.commands.push({ name: "copy-buffer-to-texture", options }); + } + copyTextureToBuffer(options) { + this.commandBuffer.commands.push({ name: "copy-texture-to-buffer", options }); + } + copyTextureToTexture(options) { + this.commandBuffer.commands.push({ name: "copy-texture-to-texture", options }); + } + // clearTexture(options: ClearTextureOptions): void { + // this.commandBuffer.commands.push({name: 'copy-texture-to-texture', options}); + // } + pushDebugGroup(groupLabel) { + } + popDebugGroup() { + } + insertDebugMarker(markerLabel) { + } + resolveQuerySet(_querySet, _destination, _options) { + throw new Error("resolveQuerySet is not supported in WebGL"); + } + writeTimestamp(querySet, queryIndex) { + const webglQuerySet = querySet; + webglQuerySet.writeTimestamp(queryIndex); + } + }; + } + }); + + // node_modules/@luma.gl/webgl/dist/utils/fill-array.js + function fillArray2(options) { + const { target: target2, source: source3, start = 0, count: count2 = 1 } = options; + const length4 = source3.length; + const total = count2 * length4; + let copied = 0; + for (let i = start; copied < length4; copied++) { + target2[i++] = source3[copied] ?? 0; + } + while (copied < total) { + if (copied < total - copied) { + target2.copyWithin(start + copied, start, start + copied); + copied *= 2; + } else { + target2.copyWithin(start + copied, start, start + total - copied); + copied = total; + } + } + return options.target; + } + var init_fill_array = __esm({ + "node_modules/@luma.gl/webgl/dist/utils/fill-array.js"() { + } + }); + + // node_modules/@luma.gl/webgl/dist/adapter/resources/webgl-vertex-array.js + function normalizeConstantArrayValue(arrayValue) { + if (Array.isArray(arrayValue)) { + return new Float32Array(arrayValue); + } + return arrayValue; + } + function compareConstantArrayValues(v1, v2) { + if (!v1 || !v2 || v1.length !== v2.length || v1.constructor !== v2.constructor) { + return false; + } + for (let i = 0; i < v1.length; ++i) { + if (v1[i] !== v2[i]) { + return false; + } + } + return true; + } + var WEBGLVertexArray; + var init_webgl_vertex_array = __esm({ + "node_modules/@luma.gl/webgl/dist/adapter/resources/webgl-vertex-array.js"() { + init_dist4(); + init_dist(); + init_webgl_vertex_formats(); + init_fill_array(); + WEBGLVertexArray = class _WEBGLVertexArray extends VertexArray { + get [Symbol.toStringTag]() { + return "VertexArray"; + } + device; + handle; + /** Attribute 0 buffer constant */ + buffer = null; + bufferValue = null; + /** * Attribute 0 can not be disable on most desktop OpenGL based browsers */ + static isConstantAttributeZeroSupported(device) { + return getBrowser() === "Chrome"; + } + // Create a VertexArray + constructor(device, props) { + super(device, props); + this.device = device; + this.handle = this.device.gl.createVertexArray(); + } + destroy() { + super.destroy(); + if (this.buffer) { + this.buffer?.destroy(); + } + if (this.handle) { + this.device.gl.deleteVertexArray(this.handle); + this.handle = void 0; + } + } + /** + // Set (bind/unbind) an elements buffer, for indexed rendering. + // Must be a Buffer bound to GL.ELEMENT_ARRAY_BUFFER or null. Constants not supported + * + * @param elementBuffer + */ + setIndexBuffer(indexBuffer) { + const buffer = indexBuffer; + if (buffer && buffer.glTarget !== 34963) { + throw new Error("Use .setBuffer()"); + } + this.device.gl.bindVertexArray(this.handle); + this.device.gl.bindBuffer(34963, buffer ? buffer.handle : null); + this.indexBuffer = buffer; + this.device.gl.bindVertexArray(null); + } + /** Set a location in vertex attributes array to a buffer, enables the location, sets divisor */ + setBuffer(location, attributeBuffer) { + const buffer = attributeBuffer; + if (buffer.glTarget === 34963) { + throw new Error("Use .setIndexBuffer()"); + } + const { size, type, stride, offset, normalized, integer, divisor } = this._getAccessor(location); + this.device.gl.bindVertexArray(this.handle); + this.device.gl.bindBuffer(34962, buffer.handle); + if (integer) { + this.device.gl.vertexAttribIPointer(location, size, type, stride, offset); + } else { + this.device.gl.vertexAttribPointer(location, size, type, normalized, stride, offset); + } + this.device.gl.bindBuffer(34962, null); + this.device.gl.enableVertexAttribArray(location); + this.device.gl.vertexAttribDivisor(location, divisor || 0); + this.attributes[location] = buffer; + this.device.gl.bindVertexArray(null); + } + /** Set a location in vertex attributes array to a constant value, disables the location */ + setConstantWebGL(location, value) { + this._enable(location, false); + this.attributes[location] = value; + } + bindBeforeRender() { + this.device.gl.bindVertexArray(this.handle); + this._applyConstantAttributes(); + } + unbindAfterRender() { + this.device.gl.bindVertexArray(null); + } + // Internal methods + /** + * Constant attributes need to be reset before every draw call + * Any attribute that is disabled in the current vertex array object + * is read from the context's global constant value for that attribute location. + * @note Constant attributes are only supported in WebGL, not in WebGPU + */ + _applyConstantAttributes() { + for (let location = 0; location < this.maxVertexAttributes; ++location) { + const constant = this.attributes[location]; + if (ArrayBuffer.isView(constant)) { + this.device.setConstantAttributeWebGL(location, constant); + } + } + } + /** + * Set a location in vertex attributes array to a buffer, enables the location, sets divisor + * @note requires vertex array to be bound + */ + // protected _setAttributeLayout(location: number): void { + // const {size, type, stride, offset, normalized, integer, divisor} = this._getAccessor(location); + // // WebGL2 supports *integer* data formats, i.e. GPU will see integer values + // if (integer) { + // this.device.gl.vertexAttribIPointer(location, size, type, stride, offset); + // } else { + // // Attaches ARRAY_BUFFER with specified buffer format to location + // this.device.gl.vertexAttribPointer(location, size, type, normalized, stride, offset); + // } + // this.device.gl.vertexAttribDivisor(location, divisor || 0); + // } + /** Get an accessor from the */ + _getAccessor(location) { + const attributeInfo = this.attributeInfos[location]; + if (!attributeInfo) { + throw new Error(`Unknown attribute location ${location}`); + } + const glType = getGLFromVertexType(attributeInfo.bufferDataType); + return { + size: attributeInfo.bufferComponents, + type: glType, + stride: attributeInfo.byteStride, + offset: attributeInfo.byteOffset, + normalized: attributeInfo.normalized, + // it is the shader attribute declaration, not the vertex memory format, + // that determines if the data in the buffer will be treated as integers. + // + // Also note that WebGL supports assigning non-normalized integer data to floating point attributes, + // but as far as we can tell, WebGPU does not. + integer: attributeInfo.integer, + divisor: attributeInfo.stepMode === "instance" ? 1 : 0 + }; + } + /** + * Enabling an attribute location makes it reference the currently bound buffer + * Disabling an attribute location makes it reference the global constant value + * TODO - handle single values for size 1 attributes? + * TODO - convert classic arrays based on known type? + */ + _enable(location, enable2 = true) { + const canDisableAttributeZero = _WEBGLVertexArray.isConstantAttributeZeroSupported(this.device); + const canDisableAttribute = canDisableAttributeZero || location !== 0; + if (enable2 || canDisableAttribute) { + location = Number(location); + this.device.gl.bindVertexArray(this.handle); + if (enable2) { + this.device.gl.enableVertexAttribArray(location); + } else { + this.device.gl.disableVertexAttribArray(location); + } + this.device.gl.bindVertexArray(null); + } + } + /** + * Provide a means to create a buffer that is equivalent to a constant. + * NOTE: Desktop OpenGL cannot disable attribute 0. + * https://stackoverflow.com/questions/20305231/webgl-warning-attribute-0-is-disabled- + * this-has-significant-performance-penalty + */ + getConstantBuffer(elementCount, value) { + const constantValue = normalizeConstantArrayValue(value); + const byteLength = constantValue.byteLength * elementCount; + const length4 = constantValue.length * elementCount; + if (this.buffer && byteLength !== this.buffer.byteLength) { + throw new Error(`Buffer size is immutable, byte length ${byteLength} !== ${this.buffer.byteLength}.`); + } + let updateNeeded = !this.buffer; + this.buffer = this.buffer || this.device.createBuffer({ byteLength }); + updateNeeded ||= !compareConstantArrayValues(constantValue, this.bufferValue); + if (updateNeeded) { + const typedArray = getScratchArray(value.constructor, length4); + fillArray2({ target: typedArray, source: constantValue, start: 0, count: length4 }); + this.buffer.write(typedArray); + this.bufferValue = value; + } + return this.buffer; + } + }; + } + }); + + // node_modules/@luma.gl/webgl/dist/adapter/resources/webgl-transform-feedback.js + function isIndex(value) { + if (typeof value === "number") { + return Number.isInteger(value); + } + return /^\d+$/.test(value); + } + var WEBGLTransformFeedback; + var init_webgl_transform_feedback = __esm({ + "node_modules/@luma.gl/webgl/dist/adapter/resources/webgl-transform-feedback.js"() { + init_dist4(); + init_dist5(); + init_webgl_topology_utils(); + WEBGLTransformFeedback = class extends TransformFeedback { + device; + gl; + handle; + /** + * NOTE: The Model already has this information while drawing, but + * TransformFeedback currently needs it internally, to look up + * varying information outside of a draw() call. + */ + layout; + buffers = {}; + unusedBuffers = {}; + /** + * Allows us to avoid a Chrome bug where a buffer that is already bound to a + * different target cannot be bound to 'TRANSFORM_FEEDBACK_BUFFER' target. + * This a major workaround, see: https://github.com/KhronosGroup/WebGL/issues/2346 + */ + bindOnUse = true; + _bound = false; + constructor(device, props) { + super(device, props); + this.device = device; + this.gl = device.gl; + this.handle = this.props.handle || this.gl.createTransformFeedback(); + this.layout = this.props.layout; + if (props.buffers) { + this.setBuffers(props.buffers); + } + Object.seal(this); + } + destroy() { + this.gl.deleteTransformFeedback(this.handle); + super.destroy(); + } + begin(topology = "point-list") { + this.gl.bindTransformFeedback(36386, this.handle); + if (this.bindOnUse) { + this._bindBuffers(); + } + this.gl.beginTransformFeedback(getGLPrimitive(topology)); + } + end() { + this.gl.endTransformFeedback(); + if (this.bindOnUse) { + this._unbindBuffers(); + } + this.gl.bindTransformFeedback(36386, null); + } + // SUBCLASS + setBuffers(buffers) { + this.buffers = {}; + this.unusedBuffers = {}; + this.bind(() => { + for (const [bufferName, buffer] of Object.entries(buffers)) { + this.setBuffer(bufferName, buffer); + } + }); + } + setBuffer(locationOrName, bufferOrRange) { + const location = this._getVaryingIndex(locationOrName); + const { buffer, byteLength, byteOffset } = this._getBufferRange(bufferOrRange); + if (location < 0) { + this.unusedBuffers[locationOrName] = buffer; + log2.warn(`${this.id} unusedBuffers varying buffer ${locationOrName}`)(); + return; + } + this.buffers[location] = { buffer, byteLength, byteOffset }; + if (!this.bindOnUse) { + this._bindBuffer(location, buffer, byteOffset, byteLength); + } + } + getBuffer(locationOrName) { + if (isIndex(locationOrName)) { + return this.buffers[locationOrName] || null; + } + const location = this._getVaryingIndex(locationOrName); + return this.buffers[location] ?? null; + } + bind(funcOrHandle = this.handle) { + if (typeof funcOrHandle !== "function") { + this.gl.bindTransformFeedback(36386, funcOrHandle); + return this; + } + let value; + if (!this._bound) { + this.gl.bindTransformFeedback(36386, this.handle); + this._bound = true; + value = funcOrHandle(); + this._bound = false; + this.gl.bindTransformFeedback(36386, null); + } else { + value = funcOrHandle(); + } + return value; + } + unbind() { + this.bind(null); + } + // PRIVATE METHODS + /** Extract offsets for bindBufferRange */ + _getBufferRange(bufferOrRange) { + if (bufferOrRange instanceof WEBGLBuffer) { + return { buffer: bufferOrRange, byteOffset: 0, byteLength: bufferOrRange.byteLength }; + } + const { buffer, byteOffset = 0, byteLength = bufferOrRange.buffer.byteLength } = bufferOrRange; + return { buffer, byteOffset, byteLength }; + } + _getVaryingIndex(locationOrName) { + if (isIndex(locationOrName)) { + return Number(locationOrName); + } + for (const varying of this.layout.varyings || []) { + if (locationOrName === varying.name) { + return varying.location; + } + } + return -1; + } + /** + * Need to avoid chrome bug where buffer that is already bound to a different target + * cannot be bound to 'TRANSFORM_FEEDBACK_BUFFER' target. + */ + _bindBuffers() { + for (const [bufferIndex, bufferEntry] of Object.entries(this.buffers)) { + const { buffer, byteLength, byteOffset } = this._getBufferRange(bufferEntry); + this._bindBuffer(Number(bufferIndex), buffer, byteOffset, byteLength); + } + } + _unbindBuffers() { + for (const bufferIndex in this.buffers) { + this.gl.bindBufferBase(35982, Number(bufferIndex), null); + } + } + _bindBuffer(index2, buffer, byteOffset = 0, byteLength) { + const handle = buffer && buffer.handle; + if (!handle || byteLength === void 0) { + this.gl.bindBufferBase(35982, index2, handle); + } else { + this.gl.bindBufferRange(35982, index2, handle, byteOffset, byteLength); + } + } + }; + } + }); + + // node_modules/@luma.gl/webgl/dist/adapter/resources/webgl-query-set.js + var WEBGLQuerySet; + var init_webgl_query_set = __esm({ + "node_modules/@luma.gl/webgl/dist/adapter/resources/webgl-query-set.js"() { + init_dist4(); + WEBGLQuerySet = class extends QuerySet { + device; + handle; + _timestampPairs = []; + _pendingReads = /* @__PURE__ */ new Set(); + _occlusionQuery = null; + _occlusionActive = false; + get [Symbol.toStringTag]() { + return "QuerySet"; + } + constructor(device, props) { + super(device, props); + this.device = device; + if (props.type === "timestamp") { + if (props.count < 2) { + throw new Error("Timestamp QuerySet requires at least two query slots"); + } + this._timestampPairs = new Array(Math.ceil(props.count / 2)).fill(null).map(() => ({ activeQuery: null, completedQueries: [] })); + this.handle = null; + } else { + if (props.count > 1) { + throw new Error("WebGL occlusion QuerySet can only have one value"); + } + const handle = this.device.gl.createQuery(); + if (!handle) { + throw new Error("WebGL query not supported"); + } + this.handle = handle; + } + Object.seal(this); + } + destroy() { + if (this.destroyed) { + return; + } + if (this.handle) { + this.device.gl.deleteQuery(this.handle); + } + for (const pair of this._timestampPairs) { + if (pair.activeQuery) { + this._cancelPendingQuery(pair.activeQuery); + this.device.gl.deleteQuery(pair.activeQuery.handle); + } + for (const query of pair.completedQueries) { + this._cancelPendingQuery(query); + this.device.gl.deleteQuery(query.handle); + } + } + if (this._occlusionQuery) { + this._cancelPendingQuery(this._occlusionQuery); + this.device.gl.deleteQuery(this._occlusionQuery.handle); + } + for (const query of Array.from(this._pendingReads)) { + this._cancelPendingQuery(query); + } + this.destroyResource(); + } + isResultAvailable(queryIndex) { + if (this.props.type === "timestamp") { + if (queryIndex === void 0) { + return this._timestampPairs.some((_, pairIndex) => this._isTimestampPairAvailable(pairIndex)); + } + return this._isTimestampPairAvailable(this._getTimestampPairIndex(queryIndex)); + } + if (!this._occlusionQuery) { + return false; + } + return this._pollQueryAvailability(this._occlusionQuery); + } + async readResults(options) { + const firstQuery = options?.firstQuery || 0; + const queryCount = options?.queryCount || this.props.count - firstQuery; + this._validateRange(firstQuery, queryCount); + if (this.props.type === "timestamp") { + const results = new Array(queryCount).fill(0n); + const startPairIndex = Math.floor(firstQuery / 2); + const endPairIndex = Math.floor((firstQuery + queryCount - 1) / 2); + for (let pairIndex = startPairIndex; pairIndex <= endPairIndex; pairIndex++) { + const duration = await this._consumeTimestampPairResult(pairIndex); + const beginSlot = pairIndex * 2; + const endSlot = beginSlot + 1; + if (beginSlot >= firstQuery && beginSlot < firstQuery + queryCount) { + results[beginSlot - firstQuery] = 0n; + } + if (endSlot >= firstQuery && endSlot < firstQuery + queryCount) { + results[endSlot - firstQuery] = duration; + } + } + return results; + } + if (!this._occlusionQuery) { + throw new Error("Occlusion query has not been started"); + } + return [await this._consumeQueryResult(this._occlusionQuery)]; + } + async readTimestampDuration(beginIndex, endIndex) { + if (this.props.type !== "timestamp") { + throw new Error("Timestamp durations require a timestamp QuerySet"); + } + if (beginIndex < 0 || endIndex >= this.props.count || endIndex <= beginIndex) { + throw new Error("Timestamp duration range is out of bounds"); + } + if (beginIndex % 2 !== 0 || endIndex !== beginIndex + 1) { + throw new Error("WebGL timestamp durations require adjacent even/odd query indices"); + } + const result = await this._consumeTimestampPairResult(this._getTimestampPairIndex(beginIndex)); + return Number(result) / 1e6; + } + beginOcclusionQuery() { + if (this.props.type !== "occlusion") { + throw new Error("Occlusion queries require an occlusion QuerySet"); + } + if (!this.handle) { + throw new Error("WebGL occlusion query is not available"); + } + if (this._occlusionActive) { + throw new Error("Occlusion query is already active"); + } + this.device.gl.beginQuery(35887, this.handle); + this._occlusionQuery = { + handle: this.handle, + promise: null, + result: null, + disjoint: false, + cancelled: false, + pollRequestId: null, + resolve: null, + reject: null + }; + this._occlusionActive = true; + } + endOcclusionQuery() { + if (!this._occlusionActive) { + throw new Error("Occlusion query is not active"); + } + this.device.gl.endQuery(35887); + this._occlusionActive = false; + } + writeTimestamp(queryIndex) { + if (this.props.type !== "timestamp") { + throw new Error("Timestamp writes require a timestamp QuerySet"); + } + const pairIndex = this._getTimestampPairIndex(queryIndex); + const pair = this._timestampPairs[pairIndex]; + if (queryIndex % 2 === 0) { + if (pair.activeQuery) { + throw new Error("Timestamp query pair is already active"); + } + const handle = this.device.gl.createQuery(); + if (!handle) { + throw new Error("WebGL query not supported"); + } + const query = { + handle, + promise: null, + result: null, + disjoint: false, + cancelled: false, + pollRequestId: null, + resolve: null, + reject: null + }; + this.device.gl.beginQuery(35007, handle); + pair.activeQuery = query; + return; + } + if (!pair.activeQuery) { + throw new Error("Timestamp query pair was ended before it was started"); + } + this.device.gl.endQuery(35007); + pair.completedQueries.push(pair.activeQuery); + pair.activeQuery = null; + } + _validateRange(firstQuery, queryCount) { + if (firstQuery < 0 || queryCount < 0 || firstQuery + queryCount > this.props.count) { + throw new Error("Query read range is out of bounds"); + } + } + _getTimestampPairIndex(queryIndex) { + if (queryIndex < 0 || queryIndex >= this.props.count) { + throw new Error("Query index is out of bounds"); + } + return Math.floor(queryIndex / 2); + } + _isTimestampPairAvailable(pairIndex) { + const pair = this._timestampPairs[pairIndex]; + if (!pair || pair.completedQueries.length === 0) { + return false; + } + return this._pollQueryAvailability(pair.completedQueries[0]); + } + _pollQueryAvailability(query) { + if (query.cancelled || this.destroyed) { + query.result = 0n; + return true; + } + if (query.result !== null || query.disjoint) { + return true; + } + const resultAvailable = this.device.gl.getQueryParameter(query.handle, 34919); + if (!resultAvailable) { + return false; + } + const isDisjoint = Boolean(this.device.gl.getParameter(36795)); + query.disjoint = isDisjoint; + query.result = isDisjoint ? 0n : BigInt(this.device.gl.getQueryParameter(query.handle, 34918)); + return true; + } + async _consumeTimestampPairResult(pairIndex) { + const pair = this._timestampPairs[pairIndex]; + if (!pair || pair.completedQueries.length === 0) { + throw new Error("Timestamp query pair has no completed result"); + } + const query = pair.completedQueries.shift(); + try { + return await this._consumeQueryResult(query); + } finally { + this.device.gl.deleteQuery(query.handle); + } + } + _consumeQueryResult(query) { + if (query.promise) { + return query.promise; + } + this._pendingReads.add(query); + query.promise = new Promise((resolve2, reject) => { + query.resolve = resolve2; + query.reject = reject; + const poll = () => { + query.pollRequestId = null; + if (query.cancelled || this.destroyed) { + this._pendingReads.delete(query); + query.promise = null; + query.resolve = null; + query.reject = null; + resolve2(0n); + return; + } + if (!this._pollQueryAvailability(query)) { + query.pollRequestId = this._requestAnimationFrame(poll); + return; + } + this._pendingReads.delete(query); + query.promise = null; + query.resolve = null; + query.reject = null; + if (query.disjoint) { + reject(new Error("GPU timestamp query was invalidated by a disjoint event")); + } else { + resolve2(query.result || 0n); + } + }; + poll(); + }); + return query.promise; + } + _cancelPendingQuery(query) { + this._pendingReads.delete(query); + query.cancelled = true; + if (query.pollRequestId !== null) { + this._cancelAnimationFrame(query.pollRequestId); + query.pollRequestId = null; + } + if (query.resolve) { + const resolve2 = query.resolve; + query.promise = null; + query.resolve = null; + query.reject = null; + resolve2(0n); + } + } + _requestAnimationFrame(callback) { + return requestAnimationFrame(callback); + } + _cancelAnimationFrame(requestId) { + cancelAnimationFrame(requestId); + } + }; + } + }); + + // node_modules/@luma.gl/webgl/dist/adapter/resources/webgl-fence.js + var WEBGLFence; + var init_webgl_fence = __esm({ + "node_modules/@luma.gl/webgl/dist/adapter/resources/webgl-fence.js"() { + init_dist4(); + WEBGLFence = class extends Fence { + device; + gl; + handle; + signaled; + _signaled = false; + constructor(device, props = {}) { + super(device, {}); + this.device = device; + this.gl = device.gl; + const sync = this.props.handle || this.gl.fenceSync(this.gl.SYNC_GPU_COMMANDS_COMPLETE, 0); + if (!sync) { + throw new Error("Failed to create WebGL fence"); + } + this.handle = sync; + this.signaled = new Promise((resolve2) => { + const poll = () => { + const status = this.gl.clientWaitSync(this.handle, 0, 0); + if (status === this.gl.ALREADY_SIGNALED || status === this.gl.CONDITION_SATISFIED) { + this._signaled = true; + resolve2(); + } else { + setTimeout(poll, 1); + } + }; + poll(); + }); + } + isSignaled() { + if (this._signaled) { + return true; + } + const status = this.gl.getSyncParameter(this.handle, this.gl.SYNC_STATUS); + this._signaled = status === this.gl.SIGNALED; + return this._signaled; + } + destroy() { + if (!this.destroyed) { + this.gl.deleteSync(this.handle); + } + } + }; + } + }); + + // node_modules/@luma.gl/webgl/dist/adapter/helpers/format-utils.js + function glFormatToComponents(format2) { + switch (format2) { + case 6406: + case 33326: + case 6403: + case 36244: + return 1; + case 33339: + case 33340: + case 33328: + case 33320: + case 33319: + return 2; + case 6407: + case 36248: + case 34837: + return 3; + case 6408: + case 36249: + case 34836: + return 4; + // TODO: Add support for additional WebGL2 formats + default: + return 0; + } + } + function glTypeToBytes(type) { + switch (type) { + case 5121: + return 1; + case 33635: + case 32819: + case 32820: + return 2; + case 5126: + return 4; + // TODO: Add support for additional WebGL2 types + default: + return 0; + } + } + var init_format_utils = __esm({ + "node_modules/@luma.gl/webgl/dist/adapter/helpers/format-utils.js"() { + } + }); + + // node_modules/@luma.gl/webgl/dist/adapter/helpers/webgl-texture-utils.js + function readPixelsToArray(source3, options) { + const { + sourceX = 0, + sourceY = 0, + sourceAttachment = 0 + // TODO - support gl.readBuffer + } = options || {}; + let { + target: target2 = null, + // following parameters are auto deduced if not provided + sourceWidth, + sourceHeight, + sourceDepth, + sourceFormat, + sourceType + } = options || {}; + const { framebuffer, deleteFramebuffer } = getFramebuffer2(source3); + const { gl, handle } = framebuffer; + sourceWidth ||= framebuffer.width; + sourceHeight ||= framebuffer.height; + const texture = framebuffer.colorAttachments[sourceAttachment]?.texture; + if (!texture) { + throw new Error(`Invalid framebuffer attachment ${sourceAttachment}`); + } + sourceDepth = texture?.depth || 1; + sourceFormat ||= texture?.glFormat || 6408; + sourceType ||= texture?.glType || 5121; + target2 = getPixelArray(target2, sourceType, sourceFormat, sourceWidth, sourceHeight, sourceDepth); + const signedType = dataTypeDecoder.getDataType(target2); + sourceType = sourceType || convertDataTypeToGLDataType(signedType); + const prevHandle = gl.bindFramebuffer(36160, handle); + gl.readBuffer(36064 + sourceAttachment); + gl.readPixels(sourceX, sourceY, sourceWidth, sourceHeight, sourceFormat, sourceType, target2); + gl.readBuffer(36064); + gl.bindFramebuffer(36160, prevHandle || null); + if (deleteFramebuffer) { + framebuffer.destroy(); + } + return target2; + } + function readPixelsToBuffer(source3, options) { + const { target: target2, sourceX = 0, sourceY = 0, sourceFormat = 6408, targetByteOffset = 0 } = options || {}; + let { sourceWidth, sourceHeight, sourceType } = options || {}; + const { framebuffer, deleteFramebuffer } = getFramebuffer2(source3); + sourceWidth = sourceWidth || framebuffer.width; + sourceHeight = sourceHeight || framebuffer.height; + const webglFramebuffer = framebuffer; + sourceType = sourceType || 5121; + let webglBufferTarget = target2; + if (!webglBufferTarget) { + const components = glFormatToComponents(sourceFormat); + const byteCount = glTypeToBytes(sourceType); + const byteLength = targetByteOffset + sourceWidth * sourceHeight * components * byteCount; + webglBufferTarget = webglFramebuffer.device.createBuffer({ byteLength }); + } + const commandEncoder = source3.device.createCommandEncoder(); + commandEncoder.copyTextureToBuffer({ + sourceTexture: source3, + width: sourceWidth, + height: sourceHeight, + origin: [sourceX, sourceY], + destinationBuffer: webglBufferTarget, + byteOffset: targetByteOffset + }); + commandEncoder.destroy(); + if (deleteFramebuffer) { + framebuffer.destroy(); + } + return webglBufferTarget; + } + function getFramebuffer2(source3) { + if (!(source3 instanceof Framebuffer)) { + return { framebuffer: toFramebuffer(source3), deleteFramebuffer: true }; + } + return { framebuffer: source3, deleteFramebuffer: false }; + } + function toFramebuffer(texture, props) { + const { device, width, height, id } = texture; + const framebuffer = device.createFramebuffer({ + ...props, + id: `framebuffer-for-${id}`, + width, + height, + colorAttachments: [texture] + }); + return framebuffer; + } + function getPixelArray(pixelArray, glType, glFormat, width, height, depth) { + if (pixelArray) { + return pixelArray; + } + glType ||= 5121; + const shaderType = convertGLDataTypeToDataType(glType); + const ArrayType = dataTypeDecoder.getTypedArrayConstructor(shaderType); + const components = glFormatToComponents(glFormat); + return new ArrayType(width * height * components); + } + var init_webgl_texture_utils = __esm({ + "node_modules/@luma.gl/webgl/dist/adapter/helpers/webgl-texture-utils.js"() { + init_dist4(); + init_webgl_shadertypes(); + init_format_utils(); + init_shader_formats(); + } + }); + + // node_modules/@luma.gl/webgl/dist/adapter/webgl-device.js + var webgl_device_exports = {}; + __export(webgl_device_exports, { + WebGLDevice: () => WebGLDevice + }); + function setConstantFloatArray(device, location, array) { + switch (array.length) { + case 1: + device.gl.vertexAttrib1fv(location, array); + break; + case 2: + device.gl.vertexAttrib2fv(location, array); + break; + case 3: + device.gl.vertexAttrib3fv(location, array); + break; + case 4: + device.gl.vertexAttrib4fv(location, array); + break; + default: + } + } + function setConstantIntArray(device, location, array) { + device.gl.vertexAttribI4iv(location, array); + } + function setConstantUintArray(device, location, array) { + device.gl.vertexAttribI4uiv(location, array); + } + function compareConstantArrayValues2(v1, v2) { + if (!v1 || !v2 || v1.length !== v2.length || v1.constructor !== v2.constructor) { + return false; + } + for (let i = 0; i < v1.length; ++i) { + if (v1[i] !== v2[i]) { + return false; + } + } + return true; + } + var WebGLDevice; + var init_webgl_device = __esm({ + "node_modules/@luma.gl/webgl/dist/adapter/webgl-device.js"() { + init_dist4(); + init_webgl_state_tracker(); + init_create_browser_context(); + init_webgl_context_data(); + init_webgl_device_info(); + init_webgl_device_features(); + init_webgl_device_limits(); + init_webgl_canvas_context(); + init_webgl_presentation_context(); + init_spector(); + init_webgl_developer_tools(); + init_webgl_texture_table(); + init_uid2(); + init_webgl_buffer(); + init_webgl_shader(); + init_webgl_sampler(); + init_webgl_texture(); + init_webgl_framebuffer(); + init_webgl_render_pipeline(); + init_webgl_shared_render_pipeline(); + init_webgl_command_encoder(); + init_webgl_vertex_array(); + init_webgl_transform_feedback(); + init_webgl_query_set(); + init_webgl_fence(); + init_webgl_texture_utils(); + init_unified_parameter_api(); + init_with_parameters(); + init_webgl_extensions(); + WebGLDevice = class _WebGLDevice extends Device { + static getDeviceFromContext(gl) { + if (!gl) { + return null; + } + return gl.luma?.device ?? null; + } + // Public `Device` API + /** type of this device */ + type = "webgl"; + // Use the ! assertion to handle the case where _reuseDevices causes the constructor to return early + /** The underlying WebGL context */ + handle; + features; + limits; + info; + canvasContext; + preferredColorFormat = "rgba8unorm"; + preferredDepthFormat = "depth24plus"; + commandEncoder; + lost; + _resolveContextLost; + /** WebGL2 context. */ + gl; + /** Store constants */ + // @ts-ignore TODO fix + _constants; + /** State used by luma.gl classes - TODO - not used? */ + extensions; + _polyfilled = false; + /** Instance of Spector.js (if initialized) */ + spectorJS; + // + // Public API + // + get [Symbol.toStringTag]() { + return "WebGLDevice"; + } + toString() { + return `${this[Symbol.toStringTag]}(${this.id})`; + } + isVertexFormatSupported(format2) { + switch (format2) { + case "unorm8x4-bgra": + return false; + default: + return true; + } + } + constructor(props) { + super({ ...props, id: props.id || uid3("webgl-device") }); + const canvasContextProps = Device._getCanvasContextProps(props); + if (!canvasContextProps) { + throw new Error("WebGLDevice requires props.createCanvasContext to be set"); + } + const existingContext = canvasContextProps.canvas?.gl ?? null; + let device = _WebGLDevice.getDeviceFromContext(existingContext); + if (device) { + throw new Error(`WebGL context already attached to device ${device.id}`); + } + this.canvasContext = new WebGLCanvasContext(this, canvasContextProps); + this.lost = new Promise((resolve2) => { + this._resolveContextLost = resolve2; + }); + const webglContextAttributes = { ...props.webgl }; + if (canvasContextProps.alphaMode === "premultiplied") { + webglContextAttributes.premultipliedAlpha = true; + } + if (props.powerPreference !== void 0) { + webglContextAttributes.powerPreference = props.powerPreference; + } + if (props.failIfMajorPerformanceCaveat !== void 0) { + webglContextAttributes.failIfMajorPerformanceCaveat = props.failIfMajorPerformanceCaveat; + } + const externalGLContext = this.props._handle; + const gl = externalGLContext || createBrowserContext(this.canvasContext.canvas, { + onContextLost: (event) => this._resolveContextLost?.({ + reason: "destroyed", + message: "Entered sleep mode, or too many apps or browser tabs are using the GPU." + }), + // eslint-disable-next-line no-console + onContextRestored: (event) => console.log("WebGL context restored") + }, webglContextAttributes); + if (!gl) { + throw new Error("WebGL context creation failed"); + } + device = _WebGLDevice.getDeviceFromContext(gl); + if (device) { + if (props._reuseDevices) { + log2.log(1, `Not creating a new Device, instead returning a reference to Device ${device.id} already attached to WebGL context`, device)(); + this.canvasContext.destroy(); + device._reused = true; + return device; + } + throw new Error(`WebGL context already attached to device ${device.id}`); + } + this.handle = gl; + this.gl = gl; + this.spectorJS = initializeSpectorJS({ ...this.props, gl: this.handle }); + const contextData = getWebGLContextData(this.handle); + contextData.device = this; + if (!contextData.extensions) { + contextData.extensions = {}; + } + this.extensions = contextData.extensions; + this.info = getDeviceInfo(this.gl, this.extensions); + this.limits = new WebGLDeviceLimits(this.gl); + this.features = new WebGLDeviceFeatures(this.gl, this.extensions, this.props._disabledFeatures); + if (this.props._initializeFeatures) { + this.features.initializeFeatures(); + } + const glState = new WebGLStateTracker(this.gl, { + log: (...args) => log2.log(1, ...args)() + }); + glState.trackState(this.gl, { copyState: false }); + if (props.debug || props.debugWebGL) { + this.gl = makeDebugContext(this.gl, { debugWebGL: true, traceWebGL: props.debugWebGL }); + log2.warn("WebGL debug mode activated. Performance reduced.")(); + } + if (props.debugWebGL) { + log2.level = Math.max(log2.level, 1); + } + this.commandEncoder = new WEBGLCommandEncoder(this, { id: `${this}-command-encoder` }); + this.canvasContext._startObservers(); + } + /** + * Destroys the device + * + * @note "Detaches" from the WebGL context unless _reuseDevices is true. + * + * @note The underlying WebGL context is not immediately destroyed, + * but may be destroyed later through normal JavaScript garbage collection. + * This is a fundamental limitation since WebGL does not offer any + * browser API for destroying WebGL contexts. + */ + destroy() { + this.commandEncoder?.destroy(); + if (!this.props._reuseDevices && !this._reused) { + const contextData = getWebGLContextData(this.handle); + contextData.device = null; + } + } + get isLost() { + return this.gl.isContextLost(); + } + // IMPLEMENTATION OF ABSTRACT DEVICE + createCanvasContext(props) { + throw new Error("WebGL only supports a single canvas"); + } + createPresentationContext(props) { + return new WebGLPresentationContext(this, props || {}); + } + createBuffer(props) { + const newProps = this._normalizeBufferProps(props); + return new WEBGLBuffer(this, newProps); + } + createTexture(props) { + return new WEBGLTexture(this, props); + } + createExternalTexture(props) { + throw new Error("createExternalTexture() not implemented"); + } + createSampler(props) { + return new WEBGLSampler(this, props); + } + createShader(props) { + return new WEBGLShader(this, props); + } + createFramebuffer(props) { + return new WEBGLFramebuffer(this, props); + } + createVertexArray(props) { + return new WEBGLVertexArray(this, props); + } + createTransformFeedback(props) { + return new WEBGLTransformFeedback(this, props); + } + createQuerySet(props) { + return new WEBGLQuerySet(this, props); + } + createFence() { + return new WEBGLFence(this); + } + createRenderPipeline(props) { + return new WEBGLRenderPipeline(this, props); + } + _createSharedRenderPipelineWebGL(props) { + return new WEBGLSharedRenderPipeline(this, props); + } + createComputePipeline(props) { + throw new Error("ComputePipeline not supported in WebGL"); + } + createCommandEncoder(props = {}) { + return new WEBGLCommandEncoder(this, props); + } + /** + * Offscreen Canvas Support: Commit the frame + * https://developer.mozilla.org/en-US/docs/Web/API/WebGL2RenderingContext/commit + * Chrome's offscreen canvas does not require gl.commit + */ + submit(commandBuffer) { + let submittedCommandEncoder = null; + if (!commandBuffer) { + ({ submittedCommandEncoder, commandBuffer } = this._finalizeDefaultCommandEncoderForSubmit()); + } + try { + commandBuffer._executeCommands(); + if (submittedCommandEncoder) { + submittedCommandEncoder.resolveTimeProfilingQuerySet().then(() => { + this.commandEncoder._gpuTimeMs = submittedCommandEncoder._gpuTimeMs; + }).catch(() => { + }); + } + } finally { + commandBuffer.destroy(); + } + } + _finalizeDefaultCommandEncoderForSubmit() { + const submittedCommandEncoder = this.commandEncoder; + const commandBuffer = submittedCommandEncoder.finish(); + this.commandEncoder.destroy(); + this.commandEncoder = this.createCommandEncoder({ + id: submittedCommandEncoder.props.id, + timeProfilingQuerySet: submittedCommandEncoder.getTimeProfilingQuerySet() + }); + return { submittedCommandEncoder, commandBuffer }; + } + // + // TEMPORARY HACKS - will be removed in v9.1 + // + /** @deprecated - should use command encoder */ + readPixelsToArrayWebGL(source3, options) { + return readPixelsToArray(source3, options); + } + /** @deprecated - should use command encoder */ + readPixelsToBufferWebGL(source3, options) { + return readPixelsToBuffer(source3, options); + } + setParametersWebGL(parameters) { + setGLParameters(this.gl, parameters); + } + getParametersWebGL(parameters) { + return getGLParameters(this.gl, parameters); + } + withParametersWebGL(parameters, func) { + return withGLParameters(this.gl, parameters, func); + } + resetWebGL() { + log2.warn("WebGLDevice.resetWebGL is deprecated, use only for debugging")(); + resetGLParameters(this.gl); + } + _getDeviceSpecificTextureFormatCapabilities(capabilities) { + return getTextureFormatCapabilitiesWebGL(this.gl, capabilities, this.extensions); + } + // + // WebGL-only API (not part of `Device` API) + // + /** + * Triggers device (or WebGL context) loss. + * @note primarily intended for testing how application reacts to device loss + */ + loseDevice() { + let deviceLossTriggered = false; + const extensions = this.getExtension("WEBGL_lose_context"); + const ext = extensions.WEBGL_lose_context; + if (ext) { + deviceLossTriggered = true; + ext.loseContext(); + } + this._resolveContextLost?.({ + reason: "destroyed", + message: "Application triggered context loss" + }); + return deviceLossTriggered; + } + /** Save current WebGL context state onto an internal stack */ + pushState() { + const webglState = WebGLStateTracker.get(this.gl); + webglState.push(); + } + /** Restores previously saved context state */ + popState() { + const webglState = WebGLStateTracker.get(this.gl); + webglState.pop(); + } + /** + * Returns the GL. constant that corresponds to a numeric value of a GL constant + * Be aware that there are some duplicates especially for constants that are 0, + * so this isn't guaranteed to return the right key in all cases. + */ + getGLKey(value, options) { + const number3 = Number(value); + for (const key in this.gl) { + if (this.gl[key] === number3) { + return `GL.${key}`; + } + } + return options?.emptyIfUnknown ? "" : String(value); + } + /** + * Returns a map with any GL. constants mapped to strings, both for keys and values + */ + getGLKeys(glParameters) { + const opts = { emptyIfUnknown: true }; + return Object.entries(glParameters).reduce((keys, [key, value]) => { + keys[`${key}:${this.getGLKey(key, opts)}`] = `${value}:${this.getGLKey(value, opts)}`; + return keys; + }, {}); + } + /** + * Set a constant value for a location. Disabled attributes at that location will read from this value + * @note WebGL constants are stored globally on the WebGL context, not the VertexArray + * so they need to be updated before every render + * @todo - remember/cache values to avoid setting them unnecessarily? + */ + setConstantAttributeWebGL(location, constant) { + const maxVertexAttributes = this.limits.maxVertexAttributes; + this._constants = this._constants || new Array(maxVertexAttributes).fill(null); + const currentConstant = this._constants[location]; + if (currentConstant && compareConstantArrayValues2(currentConstant, constant)) { + log2.info(1, `setConstantAttributeWebGL(${location}) could have been skipped, value unchanged`)(); + } + this._constants[location] = constant; + switch (constant.constructor) { + case Float32Array: + setConstantFloatArray(this, location, constant); + break; + case Int32Array: + setConstantIntArray(this, location, constant); + break; + case Uint32Array: + setConstantUintArray(this, location, constant); + break; + default: + throw new Error("constant"); + } + } + /** Ensure extensions are only requested once */ + getExtension(name2) { + getWebGLExtension(this.gl, name2, this.extensions); + return this.extensions; + } + // INTERNAL SUPPORT METHODS FOR WEBGL RESOURCES + /** + * Storing data on a special field on WebGLObjects makes that data visible in SPECTOR chrome debug extension + * luma.gl ids and props can be inspected + */ + _setWebGLDebugMetadata(handle, resource, options) { + handle.luma = resource; + const spectorMetadata = { props: options.spector, id: options.spector["id"] }; + handle.__SPECTOR_Metadata = spectorMetadata; + } + }; + } + }); + + // node_modules/@luma.gl/webgl/dist/adapter/webgl-adapter.js + function isWebGL(gl) { + if (typeof WebGL2RenderingContext !== "undefined" && gl instanceof WebGL2RenderingContext) { + return true; + } + return Boolean(gl && typeof gl.createVertexArray === "function"); + } + var LOG_LEVEL2, WebGLAdapter, webgl2Adapter; + var init_webgl_adapter = __esm({ + "node_modules/@luma.gl/webgl/dist/adapter/webgl-adapter.js"() { + init_dist4(); + init_polyfill_webgl1_extensions(); + init_spector(); + init_webgl_developer_tools(); + LOG_LEVEL2 = 1; + WebGLAdapter = class extends Adapter { + /** type of device's created by this adapter */ + type = "webgl"; + constructor() { + super(); + Device.defaultProps = { ...Device.defaultProps, ...DEFAULT_SPECTOR_PROPS }; + } + /** Force any created WebGL contexts to be WebGL2 contexts, polyfilled with WebGL1 extensions */ + enforceWebGL2(enable2) { + enforceWebGL2(enable2); + } + /** Check if WebGL 2 is available */ + isSupported() { + return typeof WebGL2RenderingContext !== "undefined"; + } + isDeviceHandle(handle) { + if (typeof WebGL2RenderingContext !== "undefined" && handle instanceof WebGL2RenderingContext) { + return true; + } + if (typeof WebGLRenderingContext !== "undefined" && handle instanceof WebGLRenderingContext) { + log2.warn("WebGL1 is not supported", handle)(); + } + return false; + } + /** + * Get a device instance from a GL context + * Creates a WebGLCanvasContext against the contexts canvas + * @note autoResize will be disabled, assuming that whoever created the external context will be handling resizes. + * @param gl + * @returns + */ + async attach(gl, props = {}) { + const { WebGLDevice: WebGLDevice2 } = await Promise.resolve().then(() => (init_webgl_device(), webgl_device_exports)); + if (gl instanceof WebGLDevice2) { + return gl; + } + const existingDevice = WebGLDevice2.getDeviceFromContext(gl); + if (existingDevice) { + return existingDevice; + } + if (!isWebGL(gl)) { + throw new Error("Invalid WebGL2RenderingContext"); + } + const createCanvasContext = props.createCanvasContext === true ? {} : props.createCanvasContext; + return new WebGLDevice2({ + ...props, + _handle: gl, + createCanvasContext: { canvas: gl.canvas, autoResize: false, ...createCanvasContext } + }); + } + async create(props = {}) { + const { WebGLDevice: WebGLDevice2 } = await Promise.resolve().then(() => (init_webgl_device(), webgl_device_exports)); + const promises = []; + if (props.debugWebGL || props.debug) { + promises.push(loadWebGLDeveloperTools()); + } + if (props.debugSpectorJS) { + promises.push(loadSpectorJS(props)); + } + const results = await Promise.allSettled(promises); + for (const result of results) { + if (result.status === "rejected") { + log2.error(`Failed to initialize debug libraries ${result.reason}`)(); + } + } + try { + const device = new WebGLDevice2(props); + log2.groupCollapsed(LOG_LEVEL2, `WebGLDevice ${device.id} created`)(); + const message2 = `${device._reused ? "Reusing" : "Created"} device with WebGL2 ${device.props.debug ? "debug " : ""}context: ${device.info.vendor}, ${device.info.renderer} for canvas: ${device.canvasContext.id}`; + log2.probe(LOG_LEVEL2, message2)(); + log2.table(LOG_LEVEL2, device.info)(); + return device; + } finally { + log2.groupEnd(LOG_LEVEL2)(); + log2.info(LOG_LEVEL2, `%cWebGL call tracing: luma.log.set('debug-webgl') `, "color: white; background: blue; padding: 2px 6px; border-radius: 3px;")(); + } + } + }; + webgl2Adapter = new WebGLAdapter(); + } + }); + + // node_modules/@luma.gl/webgl/dist/index.js + var init_dist5 = __esm({ + "node_modules/@luma.gl/webgl/dist/index.js"() { + init_webgl_adapter(); + init_webgl_device(); + init_webgl_buffer(); + } + }); + + // node_modules/seedrandom/lib/alea.js + var require_alea = __commonJS({ + "node_modules/seedrandom/lib/alea.js"(exports, module) { + (function(global2, module2, define2) { + function Alea(seed) { + var me = this, mash = Mash(); + me.next = function() { + var t = 2091639 * me.s0 + me.c * 23283064365386963e-26; + me.s0 = me.s1; + me.s1 = me.s2; + return me.s2 = t - (me.c = t | 0); + }; + me.c = 1; + me.s0 = mash(" "); + me.s1 = mash(" "); + me.s2 = mash(" "); + me.s0 -= mash(seed); + if (me.s0 < 0) { + me.s0 += 1; + } + me.s1 -= mash(seed); + if (me.s1 < 0) { + me.s1 += 1; + } + me.s2 -= mash(seed); + if (me.s2 < 0) { + me.s2 += 1; + } + mash = null; + } + function copy7(f, t) { + t.c = f.c; + t.s0 = f.s0; + t.s1 = f.s1; + t.s2 = f.s2; + return t; + } + function impl(seed, opts) { + var xg = new Alea(seed), state = opts && opts.state, prng = xg.next; + prng.int32 = function() { + return xg.next() * 4294967296 | 0; + }; + prng.double = function() { + return prng() + (prng() * 2097152 | 0) * 11102230246251565e-32; + }; + prng.quick = prng; + if (state) { + if (typeof state == "object") copy7(state, xg); + prng.state = function() { + return copy7(xg, {}); + }; + } + return prng; + } + function Mash() { + var n = 4022871197; + var mash = function(data) { + data = String(data); + for (var i = 0; i < data.length; i++) { + n += data.charCodeAt(i); + var h = 0.02519603282416938 * n; + n = h >>> 0; + h -= n; + h *= n; + n = h >>> 0; + h -= n; + n += h * 4294967296; + } + return (n >>> 0) * 23283064365386963e-26; + }; + return mash; + } + if (module2 && module2.exports) { + module2.exports = impl; + } else if (define2 && define2.amd) { + define2(function() { + return impl; + }); + } else { + this.alea = impl; + } + })( + exports, + typeof module == "object" && module, + // present in node.js + typeof define == "function" && define + // present with an AMD loader + ); + } + }); + + // node_modules/seedrandom/lib/xor128.js + var require_xor128 = __commonJS({ + "node_modules/seedrandom/lib/xor128.js"(exports, module) { + (function(global2, module2, define2) { + function XorGen(seed) { + var me = this, strseed = ""; + me.x = 0; + me.y = 0; + me.z = 0; + me.w = 0; + me.next = function() { + var t = me.x ^ me.x << 11; + me.x = me.y; + me.y = me.z; + me.z = me.w; + return me.w ^= me.w >>> 19 ^ t ^ t >>> 8; + }; + if (seed === (seed | 0)) { + me.x = seed; + } else { + strseed += seed; + } + for (var k = 0; k < strseed.length + 64; k++) { + me.x ^= strseed.charCodeAt(k) | 0; + me.next(); + } + } + function copy7(f, t) { + t.x = f.x; + t.y = f.y; + t.z = f.z; + t.w = f.w; + return t; + } + function impl(seed, opts) { + var xg = new XorGen(seed), state = opts && opts.state, prng = function() { + return (xg.next() >>> 0) / 4294967296; + }; + prng.double = function() { + do { + var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21); + } while (result === 0); + return result; + }; + prng.int32 = xg.next; + prng.quick = prng; + if (state) { + if (typeof state == "object") copy7(state, xg); + prng.state = function() { + return copy7(xg, {}); + }; + } + return prng; + } + if (module2 && module2.exports) { + module2.exports = impl; + } else if (define2 && define2.amd) { + define2(function() { + return impl; + }); + } else { + this.xor128 = impl; + } + })( + exports, + typeof module == "object" && module, + // present in node.js + typeof define == "function" && define + // present with an AMD loader + ); + } + }); + + // node_modules/seedrandom/lib/xorwow.js + var require_xorwow = __commonJS({ + "node_modules/seedrandom/lib/xorwow.js"(exports, module) { + (function(global2, module2, define2) { + function XorGen(seed) { + var me = this, strseed = ""; + me.next = function() { + var t = me.x ^ me.x >>> 2; + me.x = me.y; + me.y = me.z; + me.z = me.w; + me.w = me.v; + return (me.d = me.d + 362437 | 0) + (me.v = me.v ^ me.v << 4 ^ (t ^ t << 1)) | 0; + }; + me.x = 0; + me.y = 0; + me.z = 0; + me.w = 0; + me.v = 0; + if (seed === (seed | 0)) { + me.x = seed; + } else { + strseed += seed; + } + for (var k = 0; k < strseed.length + 64; k++) { + me.x ^= strseed.charCodeAt(k) | 0; + if (k == strseed.length) { + me.d = me.x << 10 ^ me.x >>> 4; + } + me.next(); + } + } + function copy7(f, t) { + t.x = f.x; + t.y = f.y; + t.z = f.z; + t.w = f.w; + t.v = f.v; + t.d = f.d; + return t; + } + function impl(seed, opts) { + var xg = new XorGen(seed), state = opts && opts.state, prng = function() { + return (xg.next() >>> 0) / 4294967296; + }; + prng.double = function() { + do { + var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21); + } while (result === 0); + return result; + }; + prng.int32 = xg.next; + prng.quick = prng; + if (state) { + if (typeof state == "object") copy7(state, xg); + prng.state = function() { + return copy7(xg, {}); + }; + } + return prng; + } + if (module2 && module2.exports) { + module2.exports = impl; + } else if (define2 && define2.amd) { + define2(function() { + return impl; + }); + } else { + this.xorwow = impl; + } + })( + exports, + typeof module == "object" && module, + // present in node.js + typeof define == "function" && define + // present with an AMD loader + ); + } + }); + + // node_modules/seedrandom/lib/xorshift7.js + var require_xorshift7 = __commonJS({ + "node_modules/seedrandom/lib/xorshift7.js"(exports, module) { + (function(global2, module2, define2) { + function XorGen(seed) { + var me = this; + me.next = function() { + var X = me.x, i = me.i, t, v, w; + t = X[i]; + t ^= t >>> 7; + v = t ^ t << 24; + t = X[i + 1 & 7]; + v ^= t ^ t >>> 10; + t = X[i + 3 & 7]; + v ^= t ^ t >>> 3; + t = X[i + 4 & 7]; + v ^= t ^ t << 7; + t = X[i + 7 & 7]; + t = t ^ t << 13; + v ^= t ^ t << 9; + X[i] = v; + me.i = i + 1 & 7; + return v; + }; + function init(me2, seed2) { + var j, w, X = []; + if (seed2 === (seed2 | 0)) { + w = X[0] = seed2; + } else { + seed2 = "" + seed2; + for (j = 0; j < seed2.length; ++j) { + X[j & 7] = X[j & 7] << 15 ^ seed2.charCodeAt(j) + X[j + 1 & 7] << 13; + } + } + while (X.length < 8) X.push(0); + for (j = 0; j < 8 && X[j] === 0; ++j) ; + if (j == 8) w = X[7] = -1; + else w = X[j]; + me2.x = X; + me2.i = 0; + for (j = 256; j > 0; --j) { + me2.next(); + } + } + init(me, seed); + } + function copy7(f, t) { + t.x = f.x.slice(); + t.i = f.i; + return t; + } + function impl(seed, opts) { + if (seed == null) seed = +/* @__PURE__ */ new Date(); + var xg = new XorGen(seed), state = opts && opts.state, prng = function() { + return (xg.next() >>> 0) / 4294967296; + }; + prng.double = function() { + do { + var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21); + } while (result === 0); + return result; + }; + prng.int32 = xg.next; + prng.quick = prng; + if (state) { + if (state.x) copy7(state, xg); + prng.state = function() { + return copy7(xg, {}); + }; + } + return prng; + } + if (module2 && module2.exports) { + module2.exports = impl; + } else if (define2 && define2.amd) { + define2(function() { + return impl; + }); + } else { + this.xorshift7 = impl; + } + })( + exports, + typeof module == "object" && module, + // present in node.js + typeof define == "function" && define + // present with an AMD loader + ); + } + }); + + // node_modules/seedrandom/lib/xor4096.js + var require_xor4096 = __commonJS({ + "node_modules/seedrandom/lib/xor4096.js"(exports, module) { + (function(global2, module2, define2) { + function XorGen(seed) { + var me = this; + me.next = function() { + var w = me.w, X = me.X, i = me.i, t, v; + me.w = w = w + 1640531527 | 0; + v = X[i + 34 & 127]; + t = X[i = i + 1 & 127]; + v ^= v << 13; + t ^= t << 17; + v ^= v >>> 15; + t ^= t >>> 12; + v = X[i] = v ^ t; + me.i = i; + return v + (w ^ w >>> 16) | 0; + }; + function init(me2, seed2) { + var t, v, i, j, w, X = [], limit = 128; + if (seed2 === (seed2 | 0)) { + v = seed2; + seed2 = null; + } else { + seed2 = seed2 + "\0"; + v = 0; + limit = Math.max(limit, seed2.length); + } + for (i = 0, j = -32; j < limit; ++j) { + if (seed2) v ^= seed2.charCodeAt((j + 32) % seed2.length); + if (j === 0) w = v; + v ^= v << 10; + v ^= v >>> 15; + v ^= v << 4; + v ^= v >>> 13; + if (j >= 0) { + w = w + 1640531527 | 0; + t = X[j & 127] ^= v + w; + i = 0 == t ? i + 1 : 0; + } + } + if (i >= 128) { + X[(seed2 && seed2.length || 0) & 127] = -1; + } + i = 127; + for (j = 4 * 128; j > 0; --j) { + v = X[i + 34 & 127]; + t = X[i = i + 1 & 127]; + v ^= v << 13; + t ^= t << 17; + v ^= v >>> 15; + t ^= t >>> 12; + X[i] = v ^ t; + } + me2.w = w; + me2.X = X; + me2.i = i; + } + init(me, seed); + } + function copy7(f, t) { + t.i = f.i; + t.w = f.w; + t.X = f.X.slice(); + return t; + } + ; + function impl(seed, opts) { + if (seed == null) seed = +/* @__PURE__ */ new Date(); + var xg = new XorGen(seed), state = opts && opts.state, prng = function() { + return (xg.next() >>> 0) / 4294967296; + }; + prng.double = function() { + do { + var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21); + } while (result === 0); + return result; + }; + prng.int32 = xg.next; + prng.quick = prng; + if (state) { + if (state.X) copy7(state, xg); + prng.state = function() { + return copy7(xg, {}); + }; + } + return prng; + } + if (module2 && module2.exports) { + module2.exports = impl; + } else if (define2 && define2.amd) { + define2(function() { + return impl; + }); + } else { + this.xor4096 = impl; + } + })( + exports, + // window object or global + typeof module == "object" && module, + // present in node.js + typeof define == "function" && define + // present with an AMD loader + ); + } + }); + + // node_modules/seedrandom/lib/tychei.js + var require_tychei = __commonJS({ + "node_modules/seedrandom/lib/tychei.js"(exports, module) { + (function(global2, module2, define2) { + function XorGen(seed) { + var me = this, strseed = ""; + me.next = function() { + var b = me.b, c2 = me.c, d = me.d, a = me.a; + b = b << 25 ^ b >>> 7 ^ c2; + c2 = c2 - d | 0; + d = d << 24 ^ d >>> 8 ^ a; + a = a - b | 0; + me.b = b = b << 20 ^ b >>> 12 ^ c2; + me.c = c2 = c2 - d | 0; + me.d = d << 16 ^ c2 >>> 16 ^ a; + return me.a = a - b | 0; + }; + me.a = 0; + me.b = 0; + me.c = 2654435769 | 0; + me.d = 1367130551; + if (seed === Math.floor(seed)) { + me.a = seed / 4294967296 | 0; + me.b = seed | 0; + } else { + strseed += seed; + } + for (var k = 0; k < strseed.length + 20; k++) { + me.b ^= strseed.charCodeAt(k) | 0; + me.next(); + } + } + function copy7(f, t) { + t.a = f.a; + t.b = f.b; + t.c = f.c; + t.d = f.d; + return t; + } + ; + function impl(seed, opts) { + var xg = new XorGen(seed), state = opts && opts.state, prng = function() { + return (xg.next() >>> 0) / 4294967296; + }; + prng.double = function() { + do { + var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21); + } while (result === 0); + return result; + }; + prng.int32 = xg.next; + prng.quick = prng; + if (state) { + if (typeof state == "object") copy7(state, xg); + prng.state = function() { + return copy7(xg, {}); + }; + } + return prng; + } + if (module2 && module2.exports) { + module2.exports = impl; + } else if (define2 && define2.amd) { + define2(function() { + return impl; + }); + } else { + this.tychei = impl; + } + })( + exports, + typeof module == "object" && module, + // present in node.js + typeof define == "function" && define + // present with an AMD loader + ); + } + }); + + // (disabled):crypto + var require_crypto = __commonJS({ + "(disabled):crypto"() { + } + }); + + // node_modules/seedrandom/seedrandom.js + var require_seedrandom = __commonJS({ + "node_modules/seedrandom/seedrandom.js"(exports, module) { + (function(global2, pool, math) { + var width = 256, chunks = 6, digits = 52, rngname = "random", startdenom = math.pow(width, chunks), significance = math.pow(2, digits), overflow = significance * 2, mask = width - 1, nodecrypto; + function seedrandom(seed, options, callback) { + var key = []; + options = options == true ? { entropy: true } : options || {}; + var shortseed = mixkey(flatten2( + options.entropy ? [seed, tostring(pool)] : seed == null ? autoseed() : seed, + 3 + ), key); + var arc4 = new ARC4(key); + var prng = function() { + var n = arc4.g(chunks), d = startdenom, x = 0; + while (n < significance) { + n = (n + x) * width; + d *= width; + x = arc4.g(1); + } + while (n >= overflow) { + n /= 2; + d /= 2; + x >>>= 1; + } + return (n + x) / d; + }; + prng.int32 = function() { + return arc4.g(4) | 0; + }; + prng.quick = function() { + return arc4.g(4) / 4294967296; + }; + prng.double = prng; + mixkey(tostring(arc4.S), pool); + return (options.pass || callback || function(prng2, seed2, is_math_call, state) { + if (state) { + if (state.S) { + copy7(state, arc4); + } + prng2.state = function() { + return copy7(arc4, {}); + }; + } + if (is_math_call) { + math[rngname] = prng2; + return seed2; + } else return prng2; + })( + prng, + shortseed, + "global" in options ? options.global : this == math, + options.state + ); + } + function ARC4(key) { + var t, keylen = key.length, me = this, i = 0, j = me.i = me.j = 0, s = me.S = []; + if (!keylen) { + key = [keylen++]; + } + while (i < width) { + s[i] = i++; + } + for (i = 0; i < width; i++) { + s[i] = s[j = mask & j + key[i % keylen] + (t = s[i])]; + s[j] = t; + } + (me.g = function(count2) { + var t4, r = 0, i2 = me.i, j2 = me.j, s2 = me.S; + while (count2--) { + t4 = s2[i2 = mask & i2 + 1]; + r = r * width + s2[mask & (s2[i2] = s2[j2 = mask & j2 + t4]) + (s2[j2] = t4)]; + } + me.i = i2; + me.j = j2; + return r; + })(width); + } + function copy7(f, t) { + t.i = f.i; + t.j = f.j; + t.S = f.S.slice(); + return t; + } + ; + function flatten2(obj, depth) { + var result = [], typ = typeof obj, prop; + if (depth && typ == "object") { + for (prop in obj) { + try { + result.push(flatten2(obj[prop], depth - 1)); + } catch (e) { + } + } + } + return result.length ? result : typ == "string" ? obj : obj + "\0"; + } + function mixkey(seed, key) { + var stringseed = seed + "", smear, j = 0; + while (j < stringseed.length) { + key[mask & j] = mask & (smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++); + } + return tostring(key); + } + function autoseed() { + try { + var out; + if (nodecrypto && (out = nodecrypto.randomBytes)) { + out = out(width); + } else { + out = new Uint8Array(width); + (global2.crypto || global2.msCrypto).getRandomValues(out); + } + return tostring(out); + } catch (e) { + var browser = global2.navigator, plugins = browser && browser.plugins; + return [+/* @__PURE__ */ new Date(), global2, plugins, global2.screen, tostring(pool)]; + } + } + function tostring(a) { + return String.fromCharCode.apply(0, a); + } + mixkey(math.random(), pool); + if (typeof module == "object" && module.exports) { + module.exports = seedrandom; + try { + nodecrypto = require_crypto(); + } catch (ex) { + } + } else if (typeof define == "function" && define.amd) { + define(function() { + return seedrandom; + }); + } else { + math["seed" + rngname] = seedrandom; + } + })( + // global: `self` in browsers (including strict mode and web workers), + // otherwise `this` in Node and other environments + typeof self !== "undefined" ? self : exports, + [], + // pool: entropy pool starts empty + Math + // math: package containing random, pow, and seedrandom + ); + } + }); + + // node_modules/seedrandom/index.js + var require_seedrandom2 = __commonJS({ + "node_modules/seedrandom/index.js"(exports, module) { + var alea2 = require_alea(); + var xor128 = require_xor128(); + var xorwow = require_xorwow(); + var xorshift7 = require_xorshift7(); + var xor4096 = require_xor4096(); + var tychei = require_tychei(); + var sr = require_seedrandom(); + sr.alea = alea2; + sr.xor128 = xor128; + sr.xorwow = xorwow; + sr.xorshift7 = xorshift7; + sr.xor4096 = xor4096; + sr.tychei = tychei; + module.exports = sr; + } + }); + + // node_modules/@loaders.gl/loader-utils/dist/lib/env-utils/assert.js + function assert(condition, message2) { + if (!condition) { + throw new Error(message2 || "loader assertion failed."); + } + } + + // node_modules/@loaders.gl/loader-utils/dist/lib/env-utils/globals.js + var globals = { + self: typeof self !== "undefined" && self, + window: typeof window !== "undefined" && window, + global: typeof global !== "undefined" && global, + document: typeof document !== "undefined" && document + }; + var self_ = globals.self || globals.window || globals.global || {}; + var window_ = globals.window || globals.self || globals.global || {}; + var global_ = globals.global || globals.self || globals.window || {}; + var document_ = globals.document || {}; + var isBrowser = ( + // @ts-ignore process does not exist on browser + Boolean(typeof process !== "object" || String(process) !== "[object process]" || process.browser) + ); + var matches = typeof process !== "undefined" && process.version && /v([0-9]*)/.exec(process.version); + var nodeVersion = matches && parseFloat(matches[1]) || 0; + + // node_modules/@loaders.gl/loader-utils/dist/lib/log-utils/log.js + init_dist2(); + var VERSION2 = true ? "4.4.2" : "latest"; + var version = VERSION2[0] >= "0" && VERSION2[0] <= "9" ? `v${VERSION2}` : ""; + function createLog() { + const log3 = new ProbeLog({ id: "loaders.gl" }); + globalThis.loaders ||= {}; + globalThis.loaders.log = log3; + globalThis.loaders.version = version; + globalThis.probe ||= {}; + globalThis.probe.loaders = log3; + return log3; + } + var log = createLog(); + + // node_modules/@loaders.gl/loader-utils/dist/lib/javascript-utils/is-type.js + var isBoolean = (value) => typeof value === "boolean"; + var isFunction = (value) => typeof value === "function"; + var isObject = (value) => value !== null && typeof value === "object"; + var isPureObject = (value) => isObject(value) && value.constructor === {}.constructor; + var isSharedArrayBuffer = (value) => typeof SharedArrayBuffer !== "undefined" && value instanceof SharedArrayBuffer; + var isArrayBufferLike = (value) => isObject(value) && typeof value.byteLength === "number" && typeof value.slice === "function"; + var isIterable = (value) => Boolean(value) && isFunction(value[Symbol.iterator]); + var isAsyncIterable = (value) => Boolean(value) && isFunction(value[Symbol.asyncIterator]); + var isResponse = (value) => typeof Response !== "undefined" && value instanceof Response || isObject(value) && isFunction(value.arrayBuffer) && isFunction(value.text) && isFunction(value.json); + var isBlob = (value) => typeof Blob !== "undefined" && value instanceof Blob; + var isReadableDOMStream = (value) => typeof ReadableStream !== "undefined" && value instanceof ReadableStream || isObject(value) && isFunction(value.tee) && isFunction(value.cancel) && isFunction(value.getReader); + var isReadableNodeStream = (value) => isObject(value) && isFunction(value.read) && isFunction(value.pipe) && isBoolean(value.readable); + var isReadableStream = (value) => isReadableDOMStream(value) || isReadableNodeStream(value); + + // node_modules/@loaders.gl/loader-utils/dist/lib/option-utils/merge-options.js + function mergeOptions(baseOptions, newOptions) { + return mergeOptionsRecursively(baseOptions || {}, newOptions); + } + function mergeOptionsRecursively(baseOptions, newOptions, level = 0) { + if (level > 3) { + return newOptions; + } + const options = { ...baseOptions }; + for (const [key, newValue] of Object.entries(newOptions)) { + if (newValue && typeof newValue === "object" && !Array.isArray(newValue)) { + options[key] = mergeOptionsRecursively(options[key] || {}, newOptions[key], level + 1); + } else { + options[key] = newOptions[key]; + } + } + return options; + } + + // node_modules/@loaders.gl/worker-utils/dist/lib/npm-tag.js + var NPM_TAG = "latest"; + + // node_modules/@loaders.gl/worker-utils/dist/lib/env-utils/version.js + function getVersion() { + if (!globalThis._loadersgl_?.version) { + globalThis._loadersgl_ = globalThis._loadersgl_ || {}; + if (false) { + console.warn("loaders.gl: The __VERSION__ variable is not injected using babel plugin. Latest unstable workers would be fetched from the CDN."); + globalThis._loadersgl_.version = NPM_TAG; + warningIssued = true; + } else { + globalThis._loadersgl_.version = "4.4.2"; + } + } + return globalThis._loadersgl_.version; + } + var VERSION3 = getVersion(); + + // node_modules/@loaders.gl/worker-utils/dist/lib/env-utils/assert.js + function assert3(condition, message2) { + if (!condition) { + throw new Error(message2 || "loaders.gl assertion failed."); + } + } + + // node_modules/@loaders.gl/worker-utils/dist/lib/env-utils/globals.js + var globals2 = { + self: typeof self !== "undefined" && self, + window: typeof window !== "undefined" && window, + global: typeof global !== "undefined" && global, + document: typeof document !== "undefined" && document + }; + var self_2 = globals2.self || globals2.window || globals2.global || {}; + var window_3 = globals2.window || globals2.self || globals2.global || {}; + var global_3 = globals2.global || globals2.self || globals2.window || {}; + var document_3 = globals2.document || {}; + var isBrowser3 = ( + // @ts-ignore process.browser + typeof process !== "object" || String(process) !== "[object process]" || process.browser + ); + var isMobile2 = typeof window !== "undefined" && typeof window.orientation !== "undefined"; + var matches2 = typeof process !== "undefined" && process.version && /v([0-9]*)/.exec(process.version); + var nodeVersion2 = matches2 && parseFloat(matches2[1]) || 0; + + // node_modules/@loaders.gl/worker-utils/dist/lib/worker-farm/worker-job.js + var WorkerJob = class { + name; + workerThread; + isRunning = true; + /** Promise that resolves when Job is done */ + result; + _resolve = () => { + }; + _reject = () => { + }; + constructor(jobName, workerThread) { + this.name = jobName; + this.workerThread = workerThread; + this.result = new Promise((resolve2, reject) => { + this._resolve = resolve2; + this._reject = reject; + }); + } + /** + * Send a message to the job's worker thread + * @param data any data structure, ideally consisting mostly of transferrable objects + */ + postMessage(type, payload) { + this.workerThread.postMessage({ + source: "loaders.gl", + // Lets worker ignore unrelated messages + type, + payload + }); + } + /** + * Call to resolve the `result` Promise with the supplied value + */ + done(value) { + assert3(this.isRunning); + this.isRunning = false; + this._resolve(value); + } + /** + * Call to reject the `result` Promise with the supplied error + */ + error(error) { + assert3(this.isRunning); + this.isRunning = false; + this._reject(error); + } + }; + + // node_modules/@loaders.gl/worker-utils/dist/lib/node/worker_threads-browser.js + var NodeWorker = class { + terminate() { + } + }; + + // node_modules/@loaders.gl/worker-utils/dist/lib/worker-utils/get-loadable-worker-url.js + var workerURLCache = /* @__PURE__ */ new Map(); + function getLoadableWorkerURL(props) { + assert3(props.source && !props.url || !props.source && props.url); + let workerURL = workerURLCache.get(props.source || props.url); + if (!workerURL) { + if (props.url) { + workerURL = getLoadableWorkerURLFromURL(props.url); + workerURLCache.set(props.url, workerURL); + } + if (props.source) { + workerURL = getLoadableWorkerURLFromSource(props.source); + workerURLCache.set(props.source, workerURL); + } + } + assert3(workerURL); + return workerURL; + } + function getLoadableWorkerURLFromURL(url) { + if (!url.startsWith("http")) { + return url; + } + const workerSource = buildScriptSource(url); + return getLoadableWorkerURLFromSource(workerSource); + } + function getLoadableWorkerURLFromSource(workerSource) { + const blob = new Blob([workerSource], { type: "application/javascript" }); + return URL.createObjectURL(blob); + } + function buildScriptSource(workerUrl) { + return `try { + importScripts('${workerUrl}'); +} catch (error) { + console.error(error); + throw error; +}`; + } + + // node_modules/@loaders.gl/worker-utils/dist/lib/worker-utils/get-transfer-list.js + function getTransferList(object, recursive = true, transfers) { + const transfersSet = transfers || /* @__PURE__ */ new Set(); + if (!object) { + } else if (isTransferable(object)) { + transfersSet.add(object); + } else if (isTransferable(object.buffer)) { + transfersSet.add(object.buffer); + } else if (ArrayBuffer.isView(object)) { + } else if (recursive && typeof object === "object") { + for (const key in object) { + getTransferList(object[key], recursive, transfersSet); + } + } + return transfers === void 0 ? Array.from(transfersSet) : []; + } + function isTransferable(object) { + if (!object) { + return false; + } + if (object instanceof ArrayBuffer) { + return true; + } + if (typeof MessagePort !== "undefined" && object instanceof MessagePort) { + return true; + } + if (typeof ImageBitmap !== "undefined" && object instanceof ImageBitmap) { + return true; + } + if (typeof OffscreenCanvas !== "undefined" && object instanceof OffscreenCanvas) { + return true; + } + return false; + } + + // node_modules/@loaders.gl/worker-utils/dist/lib/worker-farm/worker-thread.js + var NOOP = () => { + }; + var WorkerThread = class { + name; + source; + url; + terminated = false; + worker; + onMessage; + onError; + _loadableURL = ""; + /** Checks if workers are supported on this platform */ + static isSupported() { + return typeof Worker !== "undefined" && isBrowser3 || typeof NodeWorker !== "undefined" && !isBrowser3; + } + constructor(props) { + const { name: name2, source: source3, url } = props; + assert3(source3 || url); + this.name = name2; + this.source = source3; + this.url = url; + this.onMessage = NOOP; + this.onError = (error) => console.log(error); + this.worker = isBrowser3 ? this._createBrowserWorker() : this._createNodeWorker(); + } + /** + * Terminate this worker thread + * @note Can free up significant memory + */ + destroy() { + this.onMessage = NOOP; + this.onError = NOOP; + this.worker.terminate(); + this.terminated = true; + } + get isRunning() { + return Boolean(this.onMessage); + } + /** + * Send a message to this worker thread + * @param data any data structure, ideally consisting mostly of transferrable objects + * @param transferList If not supplied, calculated automatically by traversing data + */ + postMessage(data, transferList) { + transferList = transferList || getTransferList(data); + this.worker.postMessage(data, transferList); + } + // PRIVATE + /** + * Generate a standard Error from an ErrorEvent + * @param event + */ + _getErrorFromErrorEvent(event) { + let message2 = "Failed to load "; + message2 += `worker ${this.name} from ${this.url}. `; + if (event.message) { + message2 += `${event.message} in `; + } + if (event.lineno) { + message2 += `:${event.lineno}:${event.colno}`; + } + return new Error(message2); + } + /** + * Creates a worker thread on the browser + */ + _createBrowserWorker() { + this._loadableURL = getLoadableWorkerURL({ source: this.source, url: this.url }); + const worker = new Worker(this._loadableURL, { name: this.name }); + worker.onmessage = (event) => { + if (!event.data) { + this.onError(new Error("No data received")); + } else { + this.onMessage(event.data); + } + }; + worker.onerror = (error) => { + this.onError(this._getErrorFromErrorEvent(error)); + this.terminated = true; + }; + worker.onmessageerror = (event) => console.error(event); + return worker; + } + /** + * Creates a worker thread in node.js + * @todo https://nodejs.org/api/async_hooks.html#async-resource-worker-pool + */ + _createNodeWorker() { + let worker; + if (this.url) { + const absolute = this.url.includes(":/") || this.url.startsWith("/"); + const url = absolute ? this.url : `./${this.url}`; + const type = this.url.endsWith(".ts") || this.url.endsWith(".mjs") ? "module" : "commonjs"; + worker = new NodeWorker(url, { eval: false, type }); + } else if (this.source) { + worker = new NodeWorker(this.source, { eval: true }); + } else { + throw new Error("no worker"); + } + worker.on("message", (data) => { + this.onMessage(data); + }); + worker.on("error", (error) => { + this.onError(error); + }); + worker.on("exit", (code) => { + }); + return worker; + } + }; + + // node_modules/@loaders.gl/worker-utils/dist/lib/worker-farm/worker-pool.js + var WorkerPool = class { + name = "unnamed"; + source; + // | Function; + url; + maxConcurrency = 1; + maxMobileConcurrency = 1; + onDebug = () => { + }; + reuseWorkers = true; + props = {}; + jobQueue = []; + idleQueue = []; + count = 0; + isDestroyed = false; + /** Checks if workers are supported on this platform */ + static isSupported() { + return WorkerThread.isSupported(); + } + /** + * @param processor - worker function + * @param maxConcurrency - max count of workers + */ + constructor(props) { + this.source = props.source; + this.url = props.url; + this.setProps(props); + } + /** + * Terminates all workers in the pool + * @note Can free up significant memory + */ + destroy() { + this.idleQueue.forEach((worker) => worker.destroy()); + this.isDestroyed = true; + } + setProps(props) { + this.props = { ...this.props, ...props }; + if (props.name !== void 0) { + this.name = props.name; + } + if (props.maxConcurrency !== void 0) { + this.maxConcurrency = props.maxConcurrency; + } + if (props.maxMobileConcurrency !== void 0) { + this.maxMobileConcurrency = props.maxMobileConcurrency; + } + if (props.reuseWorkers !== void 0) { + this.reuseWorkers = props.reuseWorkers; + } + if (props.onDebug !== void 0) { + this.onDebug = props.onDebug; + } + } + async startJob(name2, onMessage2 = (job, type, data) => job.done(data), onError = (job, error) => job.error(error)) { + const startPromise = new Promise((onStart) => { + this.jobQueue.push({ name: name2, onMessage: onMessage2, onError, onStart }); + return this; + }); + this._startQueuedJob(); + return await startPromise; + } + // PRIVATE + /** + * Starts first queued job if worker is available or can be created + * Called when job is started and whenever a worker returns to the idleQueue + */ + async _startQueuedJob() { + if (!this.jobQueue.length) { + return; + } + const workerThread = this._getAvailableWorker(); + if (!workerThread) { + return; + } + const queuedJob = this.jobQueue.shift(); + if (queuedJob) { + this.onDebug({ + message: "Starting job", + name: queuedJob.name, + workerThread, + backlog: this.jobQueue.length + }); + const job = new WorkerJob(queuedJob.name, workerThread); + workerThread.onMessage = (data) => queuedJob.onMessage(job, data.type, data.payload); + workerThread.onError = (error) => queuedJob.onError(job, error); + queuedJob.onStart(job); + try { + await job.result; + } catch (error) { + console.error(`Worker exception: ${error}`); + } finally { + this.returnWorkerToQueue(workerThread); + } + } + } + /** + * Returns a worker to the idle queue + * Destroys the worker if + * - pool is destroyed + * - if this pool doesn't reuse workers + * - if maxConcurrency has been lowered + * @param worker + */ + returnWorkerToQueue(worker) { + const shouldDestroyWorker = ( + // Workers on Node.js prevent the process from exiting. + // Until we figure out how to close them before exit, we always destroy them + !isBrowser3 || // If the pool is destroyed, there is no reason to keep the worker around + this.isDestroyed || // If the app has disabled worker reuse, any completed workers should be destroyed + !this.reuseWorkers || // If concurrency has been lowered, this worker might be surplus to requirements + this.count > this._getMaxConcurrency() + ); + if (shouldDestroyWorker) { + worker.destroy(); + this.count--; + } else { + this.idleQueue.push(worker); + } + if (!this.isDestroyed) { + this._startQueuedJob(); + } + } + /** + * Returns idle worker or creates new worker if maxConcurrency has not been reached + */ + _getAvailableWorker() { + if (this.idleQueue.length > 0) { + return this.idleQueue.shift() || null; + } + if (this.count < this._getMaxConcurrency()) { + this.count++; + const name2 = `${this.name.toLowerCase()} (#${this.count} of ${this.maxConcurrency})`; + return new WorkerThread({ name: name2, source: this.source, url: this.url }); + } + return null; + } + _getMaxConcurrency() { + return isMobile2 ? this.maxMobileConcurrency : this.maxConcurrency; + } + }; + + // node_modules/@loaders.gl/worker-utils/dist/lib/worker-farm/worker-farm.js + var DEFAULT_PROPS = { + maxConcurrency: 3, + maxMobileConcurrency: 1, + reuseWorkers: true, + onDebug: () => { + } + }; + var WorkerFarm = class _WorkerFarm { + props; + workerPools = /* @__PURE__ */ new Map(); + // singleton + static _workerFarm; + /** Checks if workers are supported on this platform */ + static isSupported() { + return WorkerThread.isSupported(); + } + /** Get the singleton instance of the global worker farm */ + static getWorkerFarm(props = {}) { + _WorkerFarm._workerFarm = _WorkerFarm._workerFarm || new _WorkerFarm({}); + _WorkerFarm._workerFarm.setProps(props); + return _WorkerFarm._workerFarm; + } + /** get global instance with WorkerFarm.getWorkerFarm() */ + constructor(props) { + this.props = { ...DEFAULT_PROPS }; + this.setProps(props); + this.workerPools = /* @__PURE__ */ new Map(); + } + /** + * Terminate all workers in the farm + * @note Can free up significant memory + */ + destroy() { + for (const workerPool of this.workerPools.values()) { + workerPool.destroy(); + } + this.workerPools = /* @__PURE__ */ new Map(); + } + /** + * Set props used when initializing worker pools + * @param props + */ + setProps(props) { + this.props = { ...this.props, ...props }; + for (const workerPool of this.workerPools.values()) { + workerPool.setProps(this._getWorkerPoolProps()); + } + } + /** + * Returns a worker pool for the specified worker + * @param options - only used first time for a specific worker name + * @param options.name - the name of the worker - used to identify worker pool + * @param options.url - + * @param options.source - + * @example + * const job = WorkerFarm.getWorkerFarm().getWorkerPool({name, url}).startJob(...); + */ + getWorkerPool(options) { + const { name: name2, source: source3, url } = options; + let workerPool = this.workerPools.get(name2); + if (!workerPool) { + workerPool = new WorkerPool({ + name: name2, + source: source3, + url + }); + workerPool.setProps(this._getWorkerPoolProps()); + this.workerPools.set(name2, workerPool); + } + return workerPool; + } + _getWorkerPoolProps() { + return { + maxConcurrency: this.props.maxConcurrency, + maxMobileConcurrency: this.props.maxMobileConcurrency, + reuseWorkers: this.props.reuseWorkers, + onDebug: this.props.onDebug + }; + } + }; + + // node_modules/@loaders.gl/worker-utils/dist/lib/worker-api/get-worker-url.js + function getWorkerURL(worker, options = {}) { + const workerOptions = options[worker.id] || {}; + const workerFile = isBrowser3 ? `${worker.id}-worker.js` : `${worker.id}-worker-node.js`; + let url = workerOptions.workerUrl; + if (!url && worker.id === "compression") { + url = options.workerUrl; + } + const workerType = options._workerType || options?.core?._workerType; + if (workerType === "test") { + if (isBrowser3) { + url = `modules/${worker.module}/dist/${workerFile}`; + } else { + url = `modules/${worker.module}/src/workers/${worker.id}-worker-node.ts`; + } + } + if (!url) { + let version2 = worker.version; + if (version2 === "latest") { + version2 = NPM_TAG; + } + const versionTag = version2 ? `@${version2}` : ""; + url = `https://unpkg.com/@loaders.gl/${worker.module}${versionTag}/dist/${workerFile}`; + } + assert3(url); + return url; + } + + // node_modules/@loaders.gl/worker-utils/dist/lib/worker-api/validate-worker-version.js + function validateWorkerVersion(worker, coreVersion = VERSION3) { + assert3(worker, "no worker provided"); + const workerVersion = worker.version; + if (!coreVersion || !workerVersion) { + return false; + } + return true; + } + + // node_modules/@loaders.gl/loader-utils/dist/lib/worker-loader-utils/parse-with-worker.js + function canParseWithWorker(loader, options) { + if (!WorkerFarm.isSupported()) { + return false; + } + const nodeWorkers = options?._nodeWorkers ?? options?.core?._nodeWorkers; + if (!isBrowser3 && !nodeWorkers) { + return false; + } + const useWorkers = options?.worker ?? options?.core?.worker; + return Boolean(loader.worker && useWorkers); + } + async function parseWithWorker(loader, data, options, context, parseOnMainThread) { + const name2 = loader.id; + const url = getWorkerURL(loader, options); + const workerFarm = WorkerFarm.getWorkerFarm(options?.core); + const workerPool = workerFarm.getWorkerPool({ name: name2, url }); + options = JSON.parse(JSON.stringify(options)); + context = JSON.parse(JSON.stringify(context || {})); + const job = await workerPool.startJob( + "process-on-worker", + // @ts-expect-error + onMessage.bind(null, parseOnMainThread) + // eslint-disable-line @typescript-eslint/no-misused-promises + ); + job.postMessage("process", { + // @ts-ignore + input: data, + options, + context + }); + const result = await job.result; + return await result.result; + } + async function onMessage(parseOnMainThread, job, type, payload) { + switch (type) { + case "done": + job.done(payload); + break; + case "error": + job.error(new Error(payload.error)); + break; + case "process": + const { id, input, options } = payload; + try { + const result = await parseOnMainThread(input, options); + job.postMessage("done", { id, result }); + } catch (error) { + const message2 = error instanceof Error ? error.message : "unknown error"; + job.postMessage("error", { id, error: message2 }); + } + break; + default: + console.warn(`parse-with-worker unknown message ${type}`); + } + } + + // node_modules/@loaders.gl/loader-utils/dist/lib/binary-utils/array-buffer-utils.js + function compareArrayBuffers(arrayBuffer1, arrayBuffer2, byteLength) { + byteLength = byteLength || arrayBuffer1.byteLength; + if (arrayBuffer1.byteLength < byteLength || arrayBuffer2.byteLength < byteLength) { + return false; + } + const array1 = new Uint8Array(arrayBuffer1); + const array2 = new Uint8Array(arrayBuffer2); + for (let i = 0; i < array1.length; ++i) { + if (array1[i] !== array2[i]) { + return false; + } + } + return true; + } + function concatenateArrayBuffers(...sources) { + return concatenateArrayBuffersFromArray(sources); + } + function concatenateArrayBuffersFromArray(sources) { + const sourceArrays = sources.map((source22) => source22 instanceof ArrayBuffer ? new Uint8Array(source22) : source22); + const byteLength = sourceArrays.reduce((length4, typedArray) => length4 + typedArray.byteLength, 0); + const result = new Uint8Array(byteLength); + let offset = 0; + for (const sourceArray of sourceArrays) { + result.set(sourceArray, offset); + offset += sourceArray.byteLength; + } + return result.buffer; + } + + // node_modules/@loaders.gl/loader-utils/dist/lib/iterators/async-iteration.js + async function concatenateArrayBuffersAsync(asyncIterator) { + const arrayBuffers = []; + for await (const chunk of asyncIterator) { + arrayBuffers.push(copyToArrayBuffer(chunk)); + } + return concatenateArrayBuffers(...arrayBuffers); + } + function copyToArrayBuffer(chunk) { + if (chunk instanceof ArrayBuffer) { + return chunk; + } + if (ArrayBuffer.isView(chunk)) { + const { buffer, byteOffset, byteLength } = chunk; + return copyFromBuffer(buffer, byteOffset, byteLength); + } + return copyFromBuffer(chunk); + } + function copyFromBuffer(buffer, byteOffset = 0, byteLength = buffer.byteLength - byteOffset) { + const view = new Uint8Array(buffer, byteOffset, byteLength); + const copy7 = new Uint8Array(view.length); + copy7.set(view); + return copy7.buffer; + } + + // node_modules/@loaders.gl/loader-utils/dist/lib/path-utils/file-aliases.js + var pathPrefix = ""; + var fileAliases = {}; + function resolvePath(filename2) { + for (const alias in fileAliases) { + if (filename2.startsWith(alias)) { + const replacement = fileAliases[alias]; + filename2 = filename2.replace(alias, replacement); + } + } + if (!filename2.startsWith("http://") && !filename2.startsWith("https://")) { + filename2 = `${pathPrefix}${filename2}`; + } + return filename2; + } + + // node_modules/@loaders.gl/loader-utils/dist/lib/node/buffer.browser.js + function toArrayBuffer(buffer) { + return buffer; + } + + // node_modules/@loaders.gl/loader-utils/dist/lib/binary-utils/memory-conversion-utils.js + function isBuffer(value) { + return value && typeof value === "object" && value.isBuffer; + } + function toArrayBuffer2(data) { + if (isBuffer(data)) { + return toArrayBuffer(data); + } + if (data instanceof ArrayBuffer) { + return data; + } + if (isSharedArrayBuffer(data)) { + return copyToArrayBuffer2(data); + } + if (ArrayBuffer.isView(data)) { + const buffer = data.buffer; + if (data.byteOffset === 0 && data.byteLength === data.buffer.byteLength) { + return buffer; + } + return buffer.slice(data.byteOffset, data.byteOffset + data.byteLength); + } + if (typeof data === "string") { + const text = data; + const uint8Array = new TextEncoder().encode(text); + return uint8Array.buffer; + } + if (data && typeof data === "object" && data._toArrayBuffer) { + return data._toArrayBuffer(); + } + throw new Error("toArrayBuffer"); + } + function ensureArrayBuffer(bufferSource) { + if (bufferSource instanceof ArrayBuffer) { + return bufferSource; + } + if (isSharedArrayBuffer(bufferSource)) { + return copyToArrayBuffer2(bufferSource); + } + const { buffer, byteOffset, byteLength } = bufferSource; + if (buffer instanceof ArrayBuffer && byteOffset === 0 && byteLength === buffer.byteLength) { + return buffer; + } + return copyToArrayBuffer2(buffer, byteOffset, byteLength); + } + function copyToArrayBuffer2(buffer, byteOffset = 0, byteLength = buffer.byteLength - byteOffset) { + const view = new Uint8Array(buffer, byteOffset, byteLength); + const copy7 = new Uint8Array(view.length); + copy7.set(view); + return copy7.buffer; + } + function toArrayBufferView(data) { + if (ArrayBuffer.isView(data)) { + return data; + } + return new Uint8Array(data); + } + + // node_modules/@loaders.gl/loader-utils/dist/lib/path-utils/path.js + var path_exports = {}; + __export(path_exports, { + dirname: () => dirname, + filename: () => filename, + join: () => join, + resolve: () => resolve + }); + + // node_modules/@loaders.gl/loader-utils/dist/lib/path-utils/get-cwd.js + function getCWD() { + if (typeof process !== "undefined" && typeof process.cwd !== "undefined") { + return process.cwd(); + } + const pathname = window.location?.pathname; + return pathname?.slice(0, pathname.lastIndexOf("/") + 1) || ""; + } + + // node_modules/@loaders.gl/loader-utils/dist/lib/path-utils/path.js + function filename(url) { + const slashIndex = url ? url.lastIndexOf("/") : -1; + return slashIndex >= 0 ? url.substr(slashIndex + 1) : url; + } + function dirname(url) { + const slashIndex = url ? url.lastIndexOf("/") : -1; + return slashIndex >= 0 ? url.substr(0, slashIndex) : ""; + } + function join(...parts) { + const separator = "/"; + parts = parts.map((part, index2) => { + if (index2) { + part = part.replace(new RegExp(`^${separator}`), ""); + } + if (index2 !== parts.length - 1) { + part = part.replace(new RegExp(`${separator}$`), ""); + } + return part; + }); + return parts.join(separator); + } + function resolve(...components) { + const paths = []; + for (let _i = 0; _i < components.length; _i++) { + paths[_i] = components[_i]; + } + let resolvedPath = ""; + let resolvedAbsolute = false; + let cwd; + for (let i = paths.length - 1; i >= -1 && !resolvedAbsolute; i--) { + let path; + if (i >= 0) { + path = paths[i]; + } else { + if (cwd === void 0) { + cwd = getCWD(); + } + path = cwd; + } + if (path.length === 0) { + continue; + } + resolvedPath = `${path}/${resolvedPath}`; + resolvedAbsolute = path.charCodeAt(0) === SLASH; + } + resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute); + if (resolvedAbsolute) { + return `/${resolvedPath}`; + } else if (resolvedPath.length > 0) { + return resolvedPath; + } + return "."; + } + var SLASH = 47; + var DOT = 46; + function normalizeStringPosix(path, allowAboveRoot) { + let res = ""; + let lastSlash = -1; + let dots = 0; + let code; + let isAboveRoot = false; + for (let i = 0; i <= path.length; ++i) { + if (i < path.length) { + code = path.charCodeAt(i); + } else if (code === SLASH) { + break; + } else { + code = SLASH; + } + if (code === SLASH) { + if (lastSlash === i - 1 || dots === 1) { + } else if (lastSlash !== i - 1 && dots === 2) { + if (res.length < 2 || !isAboveRoot || res.charCodeAt(res.length - 1) !== DOT || res.charCodeAt(res.length - 2) !== DOT) { + if (res.length > 2) { + const start = res.length - 1; + let j = start; + for (; j >= 0; --j) { + if (res.charCodeAt(j) === SLASH) { + break; + } + } + if (j !== start) { + res = j === -1 ? "" : res.slice(0, j); + lastSlash = i; + dots = 0; + isAboveRoot = false; + continue; + } + } else if (res.length === 2 || res.length === 1) { + res = ""; + lastSlash = i; + dots = 0; + isAboveRoot = false; + continue; + } + } + if (allowAboveRoot) { + if (res.length > 0) { + res += "/.."; + } else { + res = ".."; + } + isAboveRoot = true; + } + } else { + const slice = path.slice(lastSlash + 1, i); + if (res.length > 0) { + res += `/${slice}`; + } else { + res = slice; + } + isAboveRoot = false; + } + lastSlash = i; + dots = 0; + } else if (code === DOT && dots !== -1) { + ++dots; + } else { + dots = -1; + } + } + return res; + } + + // node_modules/@loaders.gl/core/dist/lib/fetch/fetch-error.js + var FetchError = class extends Error { + constructor(message2, info) { + super(message2); + this.reason = info.reason; + this.url = info.url; + this.response = info.response; + } + /** A best effort reason for why the fetch failed */ + reason; + /** The URL that failed to load. Empty string if not available. */ + url; + /** The Response object, if any. */ + response; + }; + + // node_modules/@loaders.gl/core/dist/lib/utils/mime-type-utils.js + var DATA_URL_PATTERN = /^data:([-\w.]+\/[-\w.+]+)(;|,)/; + var MIME_TYPE_PATTERN = /^([-\w.]+\/[-\w.+]+)/; + function compareMIMETypes(mimeType1, mimeType2) { + if (mimeType1.toLowerCase() === mimeType2.toLowerCase()) { + return true; + } + return false; + } + function parseMIMEType(mimeString) { + const matches3 = MIME_TYPE_PATTERN.exec(mimeString); + if (matches3) { + return matches3[1]; + } + return mimeString; + } + function parseMIMETypeFromURL(url) { + const matches3 = DATA_URL_PATTERN.exec(url); + if (matches3) { + return matches3[1]; + } + return ""; + } + + // node_modules/@loaders.gl/core/dist/lib/utils/url-utils.js + var QUERY_STRING_PATTERN = /\?.*/; + function extractQueryString(url) { + const matches3 = url.match(QUERY_STRING_PATTERN); + return matches3 && matches3[0]; + } + function stripQueryString(url) { + return url.replace(QUERY_STRING_PATTERN, ""); + } + function shortenUrlForDisplay(url) { + if (url.length < 50) { + return url; + } + const urlEnd = url.slice(url.length - 15); + const urlStart = url.substr(0, 32); + return `${urlStart}...${urlEnd}`; + } + + // node_modules/@loaders.gl/core/dist/lib/utils/resource-utils.js + function getResourceUrl(resource) { + if (isResponse(resource)) { + return resource.url; + } + if (isBlob(resource)) { + const fileName = "name" in resource ? resource.name : ""; + return fileName || ""; + } + if (typeof resource === "string") { + return resource; + } + return ""; + } + function getResourceMIMEType(resource) { + if (isResponse(resource)) { + const contentTypeHeader = resource.headers.get("content-type") || ""; + const noQueryUrl = stripQueryString(resource.url); + return parseMIMEType(contentTypeHeader) || parseMIMETypeFromURL(noQueryUrl); + } + if (isBlob(resource)) { + return resource.type || ""; + } + if (typeof resource === "string") { + return parseMIMETypeFromURL(resource); + } + return ""; + } + function getResourceContentLength(resource) { + if (isResponse(resource)) { + const response = resource; + return response.headers["content-length"] || -1; + } + if (isBlob(resource)) { + const blob = resource; + return blob.size; + } + if (typeof resource === "string") { + return resource.length; + } + if (resource instanceof ArrayBuffer) { + return resource.byteLength; + } + if (ArrayBuffer.isView(resource)) { + return resource.byteLength; + } + return -1; + } + + // node_modules/@loaders.gl/core/dist/lib/utils/response-utils.js + async function makeResponse(resource) { + if (isResponse(resource)) { + return resource; + } + const headers = {}; + const contentLength = getResourceContentLength(resource); + if (contentLength >= 0) { + headers["content-length"] = String(contentLength); + } + const url = getResourceUrl(resource); + const type = getResourceMIMEType(resource); + if (type) { + headers["content-type"] = type; + } + const initialDataUrl = await getInitialDataUrl(resource); + if (initialDataUrl) { + headers["x-first-bytes"] = initialDataUrl; + } + if (typeof resource === "string") { + resource = new TextEncoder().encode(resource); + } + const response = new Response(resource, { headers }); + Object.defineProperty(response, "url", { value: url }); + return response; + } + async function checkResponse(response) { + if (!response.ok) { + const error = await getResponseError(response); + throw error; + } + } + async function getResponseError(response) { + const shortUrl = shortenUrlForDisplay(response.url); + let message2 = `Failed to fetch resource (${response.status}) ${response.statusText}: ${shortUrl}`; + message2 = message2.length > 100 ? `${message2.slice(0, 100)}...` : message2; + const info = { + reason: response.statusText, + url: response.url, + response + }; + try { + const contentType = response.headers.get("Content-Type"); + info.reason = !response.bodyUsed && contentType?.includes("application/json") ? await response.json() : await response.text(); + } catch (error) { + } + return new FetchError(message2, info); + } + async function getInitialDataUrl(resource) { + const INITIAL_DATA_LENGTH = 5; + if (typeof resource === "string") { + return `data:,${resource.slice(0, INITIAL_DATA_LENGTH)}`; + } + if (resource instanceof Blob) { + const blobSlice = resource.slice(0, 5); + return await new Promise((resolve2) => { + const reader = new FileReader(); + reader.onload = (event) => resolve2(event?.target?.result); + reader.readAsDataURL(blobSlice); + }); + } + if (resource instanceof ArrayBuffer) { + const slice = resource.slice(0, INITIAL_DATA_LENGTH); + const base64 = arrayBufferToBase64(slice); + return `data:base64,${base64}`; + } + return null; + } + function arrayBufferToBase64(buffer) { + let binary = ""; + const bytes = new Uint8Array(buffer); + for (let i = 0; i < bytes.byteLength; i++) { + binary += String.fromCharCode(bytes[i]); + } + return btoa(binary); + } + + // node_modules/@loaders.gl/core/dist/lib/fetch/fetch-file.js + function isNodePath(url) { + return !isRequestURL(url) && !isDataURL(url); + } + function isRequestURL(url) { + return url.startsWith("http:") || url.startsWith("https:"); + } + function isDataURL(url) { + return url.startsWith("data:"); + } + async function fetchFile(urlOrData, fetchOptions) { + if (typeof urlOrData === "string") { + const url = resolvePath(urlOrData); + if (isNodePath(url)) { + if (globalThis.loaders?.fetchNode) { + return globalThis.loaders?.fetchNode(url, fetchOptions); + } + } + return await fetch(url, fetchOptions); + } + return await makeResponse(urlOrData); + } + + // node_modules/@loaders.gl/core/dist/lib/loader-utils/loggers.js + init_dist2(); + var probeLog = new ProbeLog({ id: "loaders.gl" }); + var NullLog = class { + log() { + return () => { + }; + } + info() { + return () => { + }; + } + warn() { + return () => { + }; + } + error() { + return () => { + }; + } + }; + var ConsoleLog = class { + console; + constructor() { + this.console = console; + } + log(...args) { + return this.console.log.bind(this.console, ...args); + } + info(...args) { + return this.console.info.bind(this.console, ...args); + } + warn(...args) { + return this.console.warn.bind(this.console, ...args); + } + error(...args) { + return this.console.error.bind(this.console, ...args); + } + }; + + // node_modules/@loaders.gl/core/dist/lib/loader-utils/option-defaults.js + var DEFAULT_LOADER_OPTIONS = { + core: { + baseUrl: void 0, + // baseUrl + fetch: null, + mimeType: void 0, + fallbackMimeType: void 0, + ignoreRegisteredLoaders: void 0, + nothrow: false, + log: new ConsoleLog(), + // A probe.gl compatible (`log.log()()` syntax) that just logs to console + useLocalLibraries: false, + CDN: "https://unpkg.com/@loaders.gl", + worker: true, + // By default, use worker if provided by loader. + maxConcurrency: 3, + // How many worker instances should be created for each loader. + maxMobileConcurrency: 1, + // How many worker instances should be created for each loader on mobile devices. + reuseWorkers: isBrowser, + // By default reuse workers in browser (Node.js refuses to terminate if browsers are running) + _nodeWorkers: false, + // By default do not support node workers + _workerType: "", + // 'test' to use locally generated workers + limit: 0, + _limitMB: 0, + batchSize: "auto", + batchDebounceMs: 0, + metadata: false, + // TODO - currently only implemented for parseInBatches, adds initial metadata batch, + transforms: [] + } + }; + var REMOVED_LOADER_OPTIONS = { + // deprecated top-level alias + baseUri: "core.baseUrl", + fetch: "core.fetch", + mimeType: "core.mimeType", + fallbackMimeType: "core.fallbackMimeType", + ignoreRegisteredLoaders: "core.ignoreRegisteredLoaders", + nothrow: "core.nothrow", + log: "core.log", + useLocalLibraries: "core.useLocalLibraries", + CDN: "core.CDN", + worker: "core.worker", + maxConcurrency: "core.maxConcurrency", + maxMobileConcurrency: "core.maxMobileConcurrency", + reuseWorkers: "core.reuseWorkers", + _nodeWorkers: "core.nodeWorkers", + _workerType: "core._workerType", + _worker: "core._workerType", + limit: "core.limit", + _limitMB: "core._limitMB", + batchSize: "core.batchSize", + batchDebounceMs: "core.batchDebounceMs", + metadata: "core.metadata", + transforms: "core.transforms", + // Older deprecations + throws: "nothrow", + dataType: "(no longer used)", + uri: "core.baseUrl", + // Warn if fetch options are used on toplevel + method: "core.fetch.method", + headers: "core.fetch.headers", + body: "core.fetch.body", + mode: "core.fetch.mode", + credentials: "core.fetch.credentials", + cache: "core.fetch.cache", + redirect: "core.fetch.redirect", + referrer: "core.fetch.referrer", + referrerPolicy: "core.fetch.referrerPolicy", + integrity: "core.fetch.integrity", + keepalive: "core.fetch.keepalive", + signal: "core.fetch.signal" + }; + + // node_modules/@loaders.gl/core/dist/lib/loader-utils/option-utils.js + var CORE_LOADER_OPTION_KEYS = [ + "baseUrl", + "fetch", + "mimeType", + "fallbackMimeType", + "ignoreRegisteredLoaders", + "nothrow", + "log", + "useLocalLibraries", + "CDN", + "worker", + "maxConcurrency", + "maxMobileConcurrency", + "reuseWorkers", + "_nodeWorkers", + "_workerType", + "limit", + "_limitMB", + "batchSize", + "batchDebounceMs", + "metadata", + "transforms" + ]; + function getGlobalLoaderState() { + globalThis.loaders = globalThis.loaders || {}; + const { loaders } = globalThis; + if (!loaders._state) { + loaders._state = {}; + } + return loaders._state; + } + function getGlobalLoaderOptions() { + const state = getGlobalLoaderState(); + state.globalOptions = state.globalOptions || { + ...DEFAULT_LOADER_OPTIONS, + core: { ...DEFAULT_LOADER_OPTIONS.core } + }; + return normalizeLoaderOptions(state.globalOptions); + } + function normalizeOptions(options, loader, loaders, url) { + loaders = loaders || []; + loaders = Array.isArray(loaders) ? loaders : [loaders]; + validateOptions(options, loaders); + return normalizeLoaderOptions(normalizeOptionsInternal(loader, options, url)); + } + function normalizeLoaderOptions(options) { + const normalized = cloneLoaderOptions(options); + moveDeprecatedTopLevelOptionsToCore(normalized); + for (const key of CORE_LOADER_OPTION_KEYS) { + if (normalized.core && normalized.core[key] !== void 0) { + delete normalized[key]; + } + } + if (normalized.core && normalized.core._workerType !== void 0) { + delete normalized._worker; + } + return normalized; + } + function validateOptions(options, loaders) { + validateOptionsObject(options, null, DEFAULT_LOADER_OPTIONS, REMOVED_LOADER_OPTIONS, loaders); + for (const loader of loaders) { + const idOptions = options && options[loader.id] || {}; + const loaderOptions = loader.options && loader.options[loader.id] || {}; + const deprecatedOptions = loader.deprecatedOptions && loader.deprecatedOptions[loader.id] || {}; + validateOptionsObject(idOptions, loader.id, loaderOptions, deprecatedOptions, loaders); + } + } + function validateOptionsObject(options, id, defaultOptions3, deprecatedOptions, loaders) { + const loaderName = id || "Top level"; + const prefix = id ? `${id}.` : ""; + for (const key in options) { + const isSubOptions = !id && isObject(options[key]); + const isBaseUriOption = key === "baseUri" && !id; + const isWorkerUrlOption = key === "workerUrl" && id; + if (!(key in defaultOptions3) && !isBaseUriOption && !isWorkerUrlOption) { + if (key in deprecatedOptions) { + if (probeLog.level > 0) { + probeLog.warn(`${loaderName} loader option '${prefix}${key}' no longer supported, use '${deprecatedOptions[key]}'`)(); + } + } else if (!isSubOptions) { + if (probeLog.level > 0) { + const suggestion = findSimilarOption(key, loaders); + probeLog.warn(`${loaderName} loader option '${prefix}${key}' not recognized. ${suggestion}`)(); + } + } + } + } + } + function findSimilarOption(optionKey, loaders) { + const lowerCaseOptionKey = optionKey.toLowerCase(); + let bestSuggestion = ""; + for (const loader of loaders) { + for (const key in loader.options) { + if (optionKey === key) { + return `Did you mean '${loader.id}.${key}'?`; + } + const lowerCaseKey = key.toLowerCase(); + const isPartialMatch = lowerCaseOptionKey.startsWith(lowerCaseKey) || lowerCaseKey.startsWith(lowerCaseOptionKey); + if (isPartialMatch) { + bestSuggestion = bestSuggestion || `Did you mean '${loader.id}.${key}'?`; + } + } + } + return bestSuggestion; + } + function normalizeOptionsInternal(loader, options, url) { + const loaderDefaultOptions = loader.options || {}; + const mergedOptions = { ...loaderDefaultOptions }; + if (loaderDefaultOptions.core) { + mergedOptions.core = { ...loaderDefaultOptions.core }; + } + moveDeprecatedTopLevelOptionsToCore(mergedOptions); + if (mergedOptions.core?.log === null) { + mergedOptions.core = { ...mergedOptions.core, log: new NullLog() }; + } + mergeNestedFields(mergedOptions, normalizeLoaderOptions(getGlobalLoaderOptions())); + const userOptions = normalizeLoaderOptions(options); + mergeNestedFields(mergedOptions, userOptions); + addUrlOptions(mergedOptions, url); + addDeprecatedTopLevelOptions(mergedOptions); + return mergedOptions; + } + function mergeNestedFields(mergedOptions, options) { + for (const key in options) { + if (key in options) { + const value = options[key]; + if (isPureObject(value) && isPureObject(mergedOptions[key])) { + mergedOptions[key] = { + ...mergedOptions[key], + ...options[key] + }; + } else { + mergedOptions[key] = options[key]; + } + } + } + } + function addUrlOptions(options, url) { + if (!url) { + return; + } + const hasCoreBaseUrl = options.core?.baseUrl !== void 0; + if (!hasCoreBaseUrl) { + options.core ||= {}; + options.core.baseUrl = path_exports.dirname(stripQueryString(url)); + } + } + function cloneLoaderOptions(options) { + const clonedOptions = { ...options }; + if (options.core) { + clonedOptions.core = { ...options.core }; + } + return clonedOptions; + } + function moveDeprecatedTopLevelOptionsToCore(options) { + if (options.baseUri !== void 0) { + options.core ||= {}; + if (options.core.baseUrl === void 0) { + options.core.baseUrl = options.baseUri; + } + } + for (const key of CORE_LOADER_OPTION_KEYS) { + if (options[key] !== void 0) { + const coreOptions = options.core = options.core || {}; + const coreRecord = coreOptions; + if (coreRecord[key] === void 0) { + coreRecord[key] = options[key]; + } + } + } + const workerTypeAlias = options._worker; + if (workerTypeAlias !== void 0) { + options.core ||= {}; + if (options.core._workerType === void 0) { + options.core._workerType = workerTypeAlias; + } + } + } + function addDeprecatedTopLevelOptions(options) { + const coreOptions = options.core; + if (!coreOptions) { + return; + } + for (const key of CORE_LOADER_OPTION_KEYS) { + if (coreOptions[key] !== void 0) { + options[key] = coreOptions[key]; + } + } + } + + // node_modules/@loaders.gl/core/dist/lib/loader-utils/normalize-loader.js + function isLoaderObject(loader) { + if (!loader) { + return false; + } + if (Array.isArray(loader)) { + loader = loader[0]; + } + const hasExtensions = Array.isArray(loader?.extensions); + return hasExtensions; + } + function normalizeLoader(loader) { + assert(loader, "null loader"); + assert(isLoaderObject(loader), "invalid loader"); + let options; + if (Array.isArray(loader)) { + options = loader[1]; + loader = loader[0]; + loader = { + ...loader, + options: { ...loader.options, ...options } + }; + } + if (loader?.parseTextSync || loader?.parseText) { + loader.text = true; + } + if (!loader.text) { + loader.binary = true; + } + return loader; + } + + // node_modules/@loaders.gl/core/dist/lib/api/register-loaders.js + var getGlobalLoaderRegistry = () => { + const state = getGlobalLoaderState(); + state.loaderRegistry = state.loaderRegistry || []; + return state.loaderRegistry; + }; + function registerLoaders(loaders) { + const loaderRegistry = getGlobalLoaderRegistry(); + loaders = Array.isArray(loaders) ? loaders : [loaders]; + for (const loader of loaders) { + const normalizedLoader = normalizeLoader(loader); + if (!loaderRegistry.find((registeredLoader) => normalizedLoader === registeredLoader)) { + loaderRegistry.unshift(normalizedLoader); + } + } + } + function getRegisteredLoaders() { + return getGlobalLoaderRegistry(); + } + + // node_modules/@loaders.gl/core/dist/lib/api/select-loader.js + var EXT_PATTERN = /\.([^.]+)$/; + async function selectLoader(data, loaders = [], options, context) { + if (!validHTTPResponse(data)) { + return null; + } + const normalizedOptions = normalizeLoaderOptions(options || {}); + normalizedOptions.core ||= {}; + if (data instanceof Response && mayContainText(data)) { + const text = await data.clone().text(); + const textLoader = selectLoaderSync(text, loaders, { ...normalizedOptions, core: { ...normalizedOptions.core, nothrow: true } }, context); + if (textLoader) { + return textLoader; + } + } + let loader = selectLoaderSync(data, loaders, { ...normalizedOptions, core: { ...normalizedOptions.core, nothrow: true } }, context); + if (loader) { + return loader; + } + if (isBlob(data)) { + data = await data.slice(0, 10).arrayBuffer(); + loader = selectLoaderSync(data, loaders, normalizedOptions, context); + } + if (!loader && data instanceof Response && mayContainText(data)) { + const text = await data.clone().text(); + loader = selectLoaderSync(text, loaders, normalizedOptions, context); + } + if (!loader && !normalizedOptions.core.nothrow) { + throw new Error(getNoValidLoaderMessage(data)); + } + return loader; + } + function mayContainText(response) { + const mimeType = getResourceMIMEType(response); + return Boolean(mimeType && (mimeType.startsWith("text/") || mimeType === "application/json" || mimeType.endsWith("+json"))); + } + function selectLoaderSync(data, loaders = [], options, context) { + if (!validHTTPResponse(data)) { + return null; + } + const normalizedOptions = normalizeLoaderOptions(options || {}); + normalizedOptions.core ||= {}; + if (loaders && !Array.isArray(loaders)) { + return normalizeLoader(loaders); + } + let candidateLoaders = []; + if (loaders) { + candidateLoaders = candidateLoaders.concat(loaders); + } + if (!normalizedOptions.core.ignoreRegisteredLoaders) { + candidateLoaders.push(...getRegisteredLoaders()); + } + normalizeLoaders(candidateLoaders); + const loader = selectLoaderInternal(data, candidateLoaders, normalizedOptions, context); + if (!loader && !normalizedOptions.core.nothrow) { + throw new Error(getNoValidLoaderMessage(data)); + } + return loader; + } + function selectLoaderInternal(data, loaders, options, context) { + const url = getResourceUrl(data); + const type = getResourceMIMEType(data); + const testUrl = stripQueryString(url) || context?.url; + let loader = null; + let reason = ""; + if (options?.core?.mimeType) { + loader = findLoaderByMIMEType(loaders, options?.core?.mimeType); + reason = `match forced by supplied MIME type ${options?.core?.mimeType}`; + } + loader = loader || findLoaderByUrl(loaders, testUrl); + reason = reason || (loader ? `matched url ${testUrl}` : ""); + loader = loader || findLoaderByMIMEType(loaders, type); + reason = reason || (loader ? `matched MIME type ${type}` : ""); + loader = loader || findLoaderByInitialBytes(loaders, data); + reason = reason || (loader ? `matched initial data ${getFirstCharacters(data)}` : ""); + if (options?.core?.fallbackMimeType) { + loader = loader || findLoaderByMIMEType(loaders, options?.core?.fallbackMimeType); + reason = reason || (loader ? `matched fallback MIME type ${type}` : ""); + } + if (reason) { + log.log(1, `selectLoader selected ${loader?.name}: ${reason}.`); + } + return loader; + } + function validHTTPResponse(data) { + if (data instanceof Response) { + if (data.status === 204) { + return false; + } + } + return true; + } + function getNoValidLoaderMessage(data) { + const url = getResourceUrl(data); + const type = getResourceMIMEType(data); + let message2 = "No valid loader found ("; + message2 += url ? `${path_exports.filename(url)}, ` : "no url provided, "; + message2 += `MIME type: ${type ? `"${type}"` : "not provided"}, `; + const firstCharacters = data ? getFirstCharacters(data) : ""; + message2 += firstCharacters ? ` first bytes: "${firstCharacters}"` : "first bytes: not available"; + message2 += ")"; + return message2; + } + function normalizeLoaders(loaders) { + for (const loader of loaders) { + normalizeLoader(loader); + } + } + function findLoaderByUrl(loaders, url) { + const match = url && EXT_PATTERN.exec(url); + const extension = match && match[1]; + return extension ? findLoaderByExtension(loaders, extension) : null; + } + function findLoaderByExtension(loaders, extension) { + extension = extension.toLowerCase(); + for (const loader of loaders) { + for (const loaderExtension of loader.extensions) { + if (loaderExtension.toLowerCase() === extension) { + return loader; + } + } + } + return null; + } + function findLoaderByMIMEType(loaders, mimeType) { + for (const loader of loaders) { + if (loader.mimeTypes?.some((mimeType1) => compareMIMETypes(mimeType, mimeType1))) { + return loader; + } + if (compareMIMETypes(mimeType, `application/x.${loader.id}`)) { + return loader; + } + } + return null; + } + function findLoaderByInitialBytes(loaders, data) { + if (!data) { + return null; + } + for (const loader of loaders) { + if (typeof data === "string") { + if (testDataAgainstText(data, loader)) { + return loader; + } + } else if (ArrayBuffer.isView(data)) { + if (testDataAgainstBinary(data.buffer, data.byteOffset, loader)) { + return loader; + } + } else if (data instanceof ArrayBuffer) { + const byteOffset = 0; + if (testDataAgainstBinary(data, byteOffset, loader)) { + return loader; + } + } + } + return null; + } + function testDataAgainstText(data, loader) { + if (loader.testText) { + return loader.testText(data); + } + const tests = Array.isArray(loader.tests) ? loader.tests : [loader.tests]; + return tests.some((test) => data.startsWith(test)); + } + function testDataAgainstBinary(data, byteOffset, loader) { + const tests = Array.isArray(loader.tests) ? loader.tests : [loader.tests]; + return tests.some((test) => testBinary(data, byteOffset, loader, test)); + } + function testBinary(data, byteOffset, loader, test) { + if (isArrayBufferLike(test)) { + return compareArrayBuffers(test, data, test.byteLength); + } + switch (typeof test) { + case "function": + return test(ensureArrayBuffer(data)); + case "string": + const magic = getMagicString(data, byteOffset, test.length); + return test === magic; + default: + return false; + } + } + function getFirstCharacters(data, length4 = 5) { + if (typeof data === "string") { + return data.slice(0, length4); + } else if (ArrayBuffer.isView(data)) { + return getMagicString(data.buffer, data.byteOffset, length4); + } else if (data instanceof ArrayBuffer) { + const byteOffset = 0; + return getMagicString(data, byteOffset, length4); + } + return ""; + } + function getMagicString(arrayBuffer2, byteOffset, length4) { + if (arrayBuffer2.byteLength < byteOffset + length4) { + return ""; + } + const dataView = new DataView(arrayBuffer2); + let magic = ""; + for (let i = 0; i < length4; i++) { + magic += String.fromCharCode(dataView.getUint8(byteOffset + i)); + } + return magic; + } + + // node_modules/@loaders.gl/core/dist/iterators/make-iterator/make-string-iterator.js + var DEFAULT_CHUNK_SIZE = 256 * 1024; + function* makeStringIterator(string, options) { + const chunkSize = options?.chunkSize || DEFAULT_CHUNK_SIZE; + let offset = 0; + const textEncoder = new TextEncoder(); + while (offset < string.length) { + const chunkLength = Math.min(string.length - offset, chunkSize); + const chunk = string.slice(offset, offset + chunkLength); + offset += chunkLength; + yield ensureArrayBuffer(textEncoder.encode(chunk)); + } + } + + // node_modules/@loaders.gl/core/dist/iterators/make-iterator/make-array-buffer-iterator.js + var DEFAULT_CHUNK_SIZE2 = 256 * 1024; + function* makeArrayBufferIterator(arrayBuffer2, options = {}) { + const { chunkSize = DEFAULT_CHUNK_SIZE2 } = options; + let byteOffset = 0; + while (byteOffset < arrayBuffer2.byteLength) { + const chunkByteLength = Math.min(arrayBuffer2.byteLength - byteOffset, chunkSize); + const chunk = new ArrayBuffer(chunkByteLength); + const sourceArray = new Uint8Array(arrayBuffer2, byteOffset, chunkByteLength); + const chunkArray = new Uint8Array(chunk); + chunkArray.set(sourceArray); + byteOffset += chunkByteLength; + yield chunk; + } + } + + // node_modules/@loaders.gl/core/dist/iterators/make-iterator/make-blob-iterator.js + var DEFAULT_CHUNK_SIZE3 = 1024 * 1024; + async function* makeBlobIterator(blob, options) { + const chunkSize = options?.chunkSize || DEFAULT_CHUNK_SIZE3; + let offset = 0; + while (offset < blob.size) { + const end = offset + chunkSize; + const chunk = await blob.slice(offset, end).arrayBuffer(); + offset = end; + yield chunk; + } + } + + // node_modules/@loaders.gl/core/dist/iterators/make-iterator/make-stream-iterator.js + function makeStreamIterator(stream, options) { + return isBrowser ? makeBrowserStreamIterator(stream, options) : makeNodeStreamIterator(stream, options); + } + async function* makeBrowserStreamIterator(stream, options) { + const reader = stream.getReader(); + let nextBatchPromise; + try { + while (true) { + const currentBatchPromise = nextBatchPromise || reader.read(); + if (options?._streamReadAhead) { + nextBatchPromise = reader.read(); + } + const { done, value } = await currentBatchPromise; + if (done) { + return; + } + yield toArrayBuffer2(value); + } + } catch (error) { + reader.releaseLock(); + } + } + async function* makeNodeStreamIterator(stream, options) { + for await (const chunk of stream) { + yield toArrayBuffer2(chunk); + } + } + + // node_modules/@loaders.gl/core/dist/iterators/make-iterator/make-iterator.js + function makeIterator(data, options) { + if (typeof data === "string") { + return makeStringIterator(data, options); + } + if (data instanceof ArrayBuffer) { + return makeArrayBufferIterator(data, options); + } + if (isBlob(data)) { + return makeBlobIterator(data, options); + } + if (isReadableStream(data)) { + return makeStreamIterator(data, options); + } + if (isResponse(data)) { + const responseBody = data.body; + if (!responseBody) { + throw new Error("Readable stream not available on Response"); + } + return makeStreamIterator(responseBody, options); + } + throw new Error("makeIterator"); + } + + // node_modules/@loaders.gl/core/dist/lib/loader-utils/get-data.js + var ERR_DATA = "Cannot convert supplied data type"; + function getArrayBufferOrStringFromDataSync(data, loader, options) { + if (loader.text && typeof data === "string") { + return data; + } + if (isBuffer(data)) { + data = data.buffer; + } + if (isArrayBufferLike(data)) { + const bufferSource = toArrayBufferView(data); + if (loader.text && !loader.binary) { + const textDecoder = new TextDecoder("utf8"); + return textDecoder.decode(bufferSource); + } + return toArrayBuffer2(bufferSource); + } + throw new Error(ERR_DATA); + } + async function getArrayBufferOrStringFromData(data, loader, options) { + if (typeof data === "string" || isArrayBufferLike(data)) { + return getArrayBufferOrStringFromDataSync(data, loader, options); + } + if (isBlob(data)) { + data = await makeResponse(data); + } + if (isResponse(data)) { + await checkResponse(data); + return loader.binary ? await data.arrayBuffer() : await data.text(); + } + if (isReadableStream(data)) { + data = makeIterator(data, options); + } + if (isIterable(data) || isAsyncIterable(data)) { + return concatenateArrayBuffersAsync(data); + } + throw new Error(ERR_DATA); + } + + // node_modules/@loaders.gl/core/dist/lib/loader-utils/get-fetch-function.js + function getFetchFunction(options, context) { + const globalOptions = getGlobalLoaderOptions(); + const loaderOptions = options || globalOptions; + const fetchOption = loaderOptions.fetch ?? loaderOptions.core?.fetch; + if (typeof fetchOption === "function") { + return fetchOption; + } + if (isObject(fetchOption)) { + return (url) => fetchFile(url, fetchOption); + } + if (context?.fetch) { + return context?.fetch; + } + return fetchFile; + } + + // node_modules/@loaders.gl/core/dist/lib/loader-utils/loader-context.js + function getLoaderContext(context, options, parentContext) { + if (parentContext) { + return parentContext; + } + const newContext = { + fetch: getFetchFunction(options, context), + ...context + }; + if (newContext.url) { + const baseUrl = stripQueryString(newContext.url); + newContext.baseUrl = baseUrl; + newContext.queryString = extractQueryString(newContext.url); + newContext.filename = path_exports.filename(baseUrl); + newContext.baseUrl = path_exports.dirname(baseUrl); + } + if (!Array.isArray(newContext.loaders)) { + newContext.loaders = null; + } + return newContext; + } + function getLoadersFromContext(loaders, context) { + if (loaders && !Array.isArray(loaders)) { + return loaders; + } + let candidateLoaders; + if (loaders) { + candidateLoaders = Array.isArray(loaders) ? loaders : [loaders]; + } + if (context && context.loaders) { + const contextLoaders = Array.isArray(context.loaders) ? context.loaders : [context.loaders]; + candidateLoaders = candidateLoaders ? [...candidateLoaders, ...contextLoaders] : contextLoaders; + } + return candidateLoaders && candidateLoaders.length ? candidateLoaders : void 0; + } + + // node_modules/@loaders.gl/core/dist/lib/api/parse.js + async function parse(data, loaders, options, context) { + if (loaders && !Array.isArray(loaders) && !isLoaderObject(loaders)) { + context = void 0; + options = loaders; + loaders = void 0; + } + data = await data; + options = options || {}; + const url = getResourceUrl(data); + const typedLoaders = loaders; + const candidateLoaders = getLoadersFromContext(typedLoaders, context); + const loader = await selectLoader(data, candidateLoaders, options); + if (!loader) { + return null; + } + const strictOptions = normalizeOptions(options, loader, candidateLoaders, url); + context = getLoaderContext( + // @ts-expect-error + { url, _parse: parse, loaders: candidateLoaders }, + strictOptions, + context || null + ); + return await parseWithLoader(loader, data, strictOptions, context); + } + async function parseWithLoader(loader, data, options, context) { + validateWorkerVersion(loader); + options = mergeOptions(loader.options, options); + if (isResponse(data)) { + const { ok, redirected, status, statusText, type, url } = data; + const headers = Object.fromEntries(data.headers.entries()); + context.response = { headers, ok, redirected, status, statusText, type, url }; + } + data = await getArrayBufferOrStringFromData(data, loader, options); + const loaderWithParser = loader; + if (loaderWithParser.parseTextSync && typeof data === "string") { + return loaderWithParser.parseTextSync(data, options, context); + } + if (canParseWithWorker(loader, options)) { + return await parseWithWorker(loader, data, options, context, parse); + } + if (loaderWithParser.parseText && typeof data === "string") { + return await loaderWithParser.parseText(data, options, context); + } + if (loaderWithParser.parse) { + return await loaderWithParser.parse(data, options, context); + } + assert3(!loaderWithParser.parseSync); + throw new Error(`${loader.id} loader - no parser found and worker is disabled`); + } + + // node_modules/@math.gl/types/dist/is-array.js + function isTypedArray(value) { + return ArrayBuffer.isView(value) && !(value instanceof DataView); + } + function isNumberArray(value) { + if (Array.isArray(value)) { + return value.length === 0 || typeof value[0] === "number"; + } + return false; + } + function isNumericArray(value) { + return isTypedArray(value) || isNumberArray(value); + } + + // node_modules/@loaders.gl/core/dist/lib/api/load.js + async function load(url, loaders, options, context) { + let resolvedLoaders; + let resolvedOptions; + if (!Array.isArray(loaders) && !isLoaderObject(loaders)) { + resolvedLoaders = []; + resolvedOptions = loaders; + context = void 0; + } else { + resolvedLoaders = loaders; + resolvedOptions = options; + } + const fetch2 = getFetchFunction(resolvedOptions); + let data = url; + if (typeof url === "string") { + data = await fetch2(url); + } + if (isBlob(url)) { + data = await fetch2(url); + } + if (typeof url === "string") { + const normalizedOptions = normalizeLoaderOptions(resolvedOptions || {}); + if (!normalizedOptions.core?.baseUrl) { + resolvedOptions = { + ...resolvedOptions, + core: { + ...resolvedOptions?.core, + baseUrl: url + } + }; + } + } + return Array.isArray(resolvedLoaders) ? await parse(data, resolvedLoaders, resolvedOptions) : await parse(data, resolvedLoaders, resolvedOptions); + } + + // node_modules/@loaders.gl/images/dist/lib/utils/version.js + var VERSION4 = true ? "4.4.2" : "latest"; + + // node_modules/@loaders.gl/images/dist/lib/category-api/image-type.js + var parseImageNode = globalThis.loaders?.parseImageNode; + var IMAGE_SUPPORTED = typeof Image !== "undefined"; + var IMAGE_BITMAP_SUPPORTED = typeof ImageBitmap !== "undefined"; + var NODE_IMAGE_SUPPORTED = Boolean(parseImageNode); + var DATA_SUPPORTED = isBrowser ? true : NODE_IMAGE_SUPPORTED; + function isImageTypeSupported(type) { + switch (type) { + case "auto": + return IMAGE_BITMAP_SUPPORTED || IMAGE_SUPPORTED || DATA_SUPPORTED; + case "imagebitmap": + return IMAGE_BITMAP_SUPPORTED; + case "image": + return IMAGE_SUPPORTED; + case "data": + return DATA_SUPPORTED; + default: + throw new Error(`@loaders.gl/images: image ${type} not supported in this environment`); + } + } + function getDefaultImageType() { + if (IMAGE_BITMAP_SUPPORTED) { + return "imagebitmap"; + } + if (IMAGE_SUPPORTED) { + return "image"; + } + if (DATA_SUPPORTED) { + return "data"; + } + throw new Error("Install '@loaders.gl/polyfills' to parse images under Node.js"); + } + + // node_modules/@loaders.gl/images/dist/lib/category-api/parsed-image-api.js + function getImageType(image) { + const format2 = getImageTypeOrNull(image); + if (!format2) { + throw new Error("Not an image"); + } + return format2; + } + function getImageData(image) { + switch (getImageType(image)) { + case "data": + return image; + case "image": + case "imagebitmap": + const canvas = document.createElement("canvas"); + const context = canvas.getContext("2d"); + if (!context) { + throw new Error("getImageData"); + } + canvas.width = image.width; + canvas.height = image.height; + context.drawImage(image, 0, 0); + return context.getImageData(0, 0, image.width, image.height); + default: + throw new Error("getImageData"); + } + } + function getImageTypeOrNull(image) { + if (typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap) { + return "imagebitmap"; + } + if (typeof Image !== "undefined" && image instanceof Image) { + return "image"; + } + if (image && typeof image === "object" && image.data && image.width && image.height) { + return "data"; + } + return null; + } + + // node_modules/@loaders.gl/images/dist/lib/parsers/svg-utils.js + var SVG_DATA_URL_PATTERN = /^data:image\/svg\+xml/; + var SVG_URL_PATTERN = /\.svg((\?|#).*)?$/; + function isSVG(url) { + return url && (SVG_DATA_URL_PATTERN.test(url) || SVG_URL_PATTERN.test(url)); + } + function getBlobOrSVGDataUrl(arrayBuffer2, url) { + if (isSVG(url)) { + const textDecoder = new TextDecoder(); + let xmlText = textDecoder.decode(arrayBuffer2); + try { + if (typeof unescape === "function" && typeof encodeURIComponent === "function") { + xmlText = unescape(encodeURIComponent(xmlText)); + } + } catch (error) { + throw new Error(error.message); + } + const src = `data:image/svg+xml;base64,${btoa(xmlText)}`; + return src; + } + return getBlob(arrayBuffer2, url); + } + function getBlob(arrayBuffer2, url) { + if (isSVG(url)) { + throw new Error("SVG cannot be parsed directly to imagebitmap"); + } + return new Blob([new Uint8Array(arrayBuffer2)]); + } + + // node_modules/@loaders.gl/images/dist/lib/parsers/parse-to-image.js + async function parseToImage(arrayBuffer2, options, url) { + const blobOrDataUrl = getBlobOrSVGDataUrl(arrayBuffer2, url); + const URL2 = self.URL || self.webkitURL; + const objectUrl = typeof blobOrDataUrl !== "string" && URL2.createObjectURL(blobOrDataUrl); + try { + return await loadToImage(objectUrl || blobOrDataUrl, options); + } finally { + if (objectUrl) { + URL2.revokeObjectURL(objectUrl); + } + } + } + async function loadToImage(url, options) { + const image = new Image(); + image.src = url; + if (options.image && options.image.decode && image.decode) { + await image.decode(); + return image; + } + return await new Promise((resolve2, reject) => { + try { + image.onload = () => resolve2(image); + image.onerror = (error) => { + const message2 = error instanceof Error ? error.message : "error"; + reject(new Error(message2)); + }; + } catch (error) { + reject(error); + } + }); + } + + // node_modules/@loaders.gl/images/dist/lib/parsers/parse-to-image-bitmap.js + var imagebitmapOptionsSupported = true; + async function parseToImageBitmap(arrayBuffer2, options, url) { + let blob; + if (isSVG(url)) { + const image = await parseToImage(arrayBuffer2, options, url); + blob = image; + } else { + blob = getBlob(arrayBuffer2, url); + } + const imagebitmapOptions = options && options.imagebitmap; + return await safeCreateImageBitmap(blob, imagebitmapOptions); + } + async function safeCreateImageBitmap(blob, imagebitmapOptions = null) { + if (isEmptyObject(imagebitmapOptions) || !imagebitmapOptionsSupported) { + imagebitmapOptions = null; + } + if (imagebitmapOptions) { + try { + return await createImageBitmap(blob, imagebitmapOptions); + } catch (error) { + console.warn(error); + imagebitmapOptionsSupported = false; + } + } + return await createImageBitmap(blob); + } + function isEmptyObject(object) { + if (!object) { + return true; + } + for (const key in object) { + if (Object.prototype.hasOwnProperty.call(object, key)) { + return false; + } + } + return true; + } + + // node_modules/@loaders.gl/images/dist/lib/category-api/parse-isobmff-binary.js + function getISOBMFFMediaType(buffer) { + if (!checkString(buffer, "ftyp", 4)) { + return null; + } + if ((buffer[8] & 96) === 0) { + return null; + } + return decodeMajorBrand(buffer); + } + function decodeMajorBrand(buffer) { + const brandMajor = getUTF8String(buffer, 8, 12).replace("\0", " ").trim(); + switch (brandMajor) { + case "avif": + case "avis": + return { extension: "avif", mimeType: "image/avif" }; + default: + return null; + } + } + function getUTF8String(array, start, end) { + return String.fromCharCode(...array.slice(start, end)); + } + function stringToBytes(string) { + return [...string].map((character) => character.charCodeAt(0)); + } + function checkString(buffer, header, offset = 0) { + const headerBytes = stringToBytes(header); + for (let i = 0; i < headerBytes.length; ++i) { + if (headerBytes[i] !== buffer[i + offset]) { + return false; + } + } + return true; + } + + // node_modules/@loaders.gl/images/dist/lib/category-api/binary-image-api.js + var BIG_ENDIAN = false; + var LITTLE_ENDIAN = true; + function getBinaryImageMetadata(binaryData) { + const dataView = toDataView(binaryData); + return getPngMetadata(dataView) || getJpegMetadata(dataView) || getGifMetadata(dataView) || getBmpMetadata(dataView) || getISOBMFFMetadata(dataView); + } + function getISOBMFFMetadata(binaryData) { + const buffer = new Uint8Array(binaryData instanceof DataView ? binaryData.buffer : binaryData); + const mediaType = getISOBMFFMediaType(buffer); + if (!mediaType) { + return null; + } + return { + mimeType: mediaType.mimeType, + // TODO - decode width and height + width: 0, + height: 0 + }; + } + function getPngMetadata(binaryData) { + const dataView = toDataView(binaryData); + const isPng = dataView.byteLength >= 24 && dataView.getUint32(0, BIG_ENDIAN) === 2303741511; + if (!isPng) { + return null; + } + return { + mimeType: "image/png", + width: dataView.getUint32(16, BIG_ENDIAN), + height: dataView.getUint32(20, BIG_ENDIAN) + }; + } + function getGifMetadata(binaryData) { + const dataView = toDataView(binaryData); + const isGif = dataView.byteLength >= 10 && dataView.getUint32(0, BIG_ENDIAN) === 1195984440; + if (!isGif) { + return null; + } + return { + mimeType: "image/gif", + width: dataView.getUint16(6, LITTLE_ENDIAN), + height: dataView.getUint16(8, LITTLE_ENDIAN) + }; + } + function getBmpMetadata(binaryData) { + const dataView = toDataView(binaryData); + const isBmp = dataView.byteLength >= 14 && dataView.getUint16(0, BIG_ENDIAN) === 16973 && dataView.getUint32(2, LITTLE_ENDIAN) === dataView.byteLength; + if (!isBmp) { + return null; + } + return { + mimeType: "image/bmp", + width: dataView.getUint32(18, LITTLE_ENDIAN), + height: dataView.getUint32(22, LITTLE_ENDIAN) + }; + } + function getJpegMetadata(binaryData) { + const dataView = toDataView(binaryData); + const isJpeg = dataView.byteLength >= 3 && dataView.getUint16(0, BIG_ENDIAN) === 65496 && dataView.getUint8(2) === 255; + if (!isJpeg) { + return null; + } + const { tableMarkers, sofMarkers } = getJpegMarkers(); + let i = 2; + while (i + 9 < dataView.byteLength) { + const marker = dataView.getUint16(i, BIG_ENDIAN); + if (sofMarkers.has(marker)) { + return { + mimeType: "image/jpeg", + height: dataView.getUint16(i + 5, BIG_ENDIAN), + // Number of lines + width: dataView.getUint16(i + 7, BIG_ENDIAN) + // Number of pixels per line + }; + } + if (!tableMarkers.has(marker)) { + return null; + } + i += 2; + i += dataView.getUint16(i, BIG_ENDIAN); + } + return null; + } + function getJpegMarkers() { + const tableMarkers = /* @__PURE__ */ new Set([65499, 65476, 65484, 65501, 65534]); + for (let i = 65504; i < 65520; ++i) { + tableMarkers.add(i); + } + const sofMarkers = /* @__PURE__ */ new Set([ + 65472, + 65473, + 65474, + 65475, + 65477, + 65478, + 65479, + 65481, + 65482, + 65483, + 65485, + 65486, + 65487, + 65502 + ]); + return { tableMarkers, sofMarkers }; + } + function toDataView(data) { + if (data instanceof DataView) { + return data; + } + if (ArrayBuffer.isView(data)) { + return new DataView(data.buffer); + } + if (data instanceof ArrayBuffer) { + return new DataView(data); + } + throw new Error("toDataView"); + } + + // node_modules/@loaders.gl/images/dist/lib/parsers/parse-to-node-image.js + async function parseToNodeImage(arrayBuffer2, options) { + const { mimeType } = getBinaryImageMetadata(arrayBuffer2) || {}; + const parseImageNode2 = globalThis.loaders?.parseImageNode; + assert(parseImageNode2); + return await parseImageNode2(arrayBuffer2, mimeType); + } + + // node_modules/@loaders.gl/images/dist/lib/parsers/parse-image.js + async function parseImage(arrayBuffer2, options, context) { + options = options || {}; + const imageOptions = options.image || {}; + const imageType = imageOptions.type || "auto"; + const { url } = context || {}; + const loadType = getLoadableImageType(imageType); + let image; + switch (loadType) { + case "imagebitmap": + image = await parseToImageBitmap(arrayBuffer2, options, url); + break; + case "image": + image = await parseToImage(arrayBuffer2, options, url); + break; + case "data": + image = await parseToNodeImage(arrayBuffer2, options); + break; + default: + assert(false); + } + if (imageType === "data") { + image = getImageData(image); + } + return image; + } + function getLoadableImageType(type) { + switch (type) { + case "auto": + case "data": + return getDefaultImageType(); + default: + isImageTypeSupported(type); + return type; + } + } + + // node_modules/@loaders.gl/images/dist/image-loader.js + var EXTENSIONS = ["png", "jpg", "jpeg", "gif", "webp", "bmp", "ico", "svg", "avif"]; + var MIME_TYPES = [ + "image/png", + "image/jpeg", + "image/gif", + "image/webp", + "image/avif", + "image/bmp", + "image/vnd.microsoft.icon", + "image/svg+xml" + ]; + var DEFAULT_IMAGE_LOADER_OPTIONS = { + image: { + type: "auto", + decode: true + // if format is HTML + } + // imagebitmap: {} - passes (platform dependent) parameters to ImageBitmap constructor + }; + var ImageLoader = { + dataType: null, + batchType: null, + id: "image", + module: "images", + name: "Images", + version: VERSION4, + mimeTypes: MIME_TYPES, + extensions: EXTENSIONS, + parse: parseImage, + // TODO: byteOffset, byteLength; + tests: [(arrayBuffer2) => Boolean(getBinaryImageMetadata(new DataView(arrayBuffer2)))], + options: DEFAULT_IMAGE_LOADER_OPTIONS + }; + + // node_modules/@deck.gl/core/dist/utils/log.js + init_dist2(); + var defaultLogger = new ProbeLog({ id: "deck" }); + var log_default = defaultLogger; + + // node_modules/@deck.gl/core/dist/debug/loggers.js + var logState = { + attributeUpdateStart: -1, + attributeManagerUpdateStart: -1, + attributeUpdateMessages: [] + }; + var LOG_LEVEL_MAJOR_UPDATE = 1; + var LOG_LEVEL_MINOR_UPDATE = 2; + var LOG_LEVEL_UPDATE_DETAIL = 3; + var LOG_LEVEL_INFO = 4; + var LOG_LEVEL_DRAW = 2; + var getLoggers = (log3) => ({ + /* Layer events */ + "layer.changeFlag": (layer, key, flags) => { + log3.log(LOG_LEVEL_UPDATE_DETAIL, `${layer.id} ${key}: `, flags[key])(); + }, + "layer.initialize": (layer) => { + log3.log(LOG_LEVEL_MAJOR_UPDATE, `Initializing ${layer}`)(); + }, + "layer.update": (layer, needsUpdate) => { + if (needsUpdate) { + const flags = layer.getChangeFlags(); + log3.log(LOG_LEVEL_MINOR_UPDATE, `Updating ${layer} because: ${Object.keys(flags).filter((key) => flags[key]).join(", ")}`)(); + } else { + log3.log(LOG_LEVEL_INFO, `${layer} does not need update`)(); + } + }, + "layer.matched": (layer, changed) => { + if (changed) { + log3.log(LOG_LEVEL_INFO, `Matched ${layer}, state transfered`)(); + } + }, + "layer.finalize": (layer) => { + log3.log(LOG_LEVEL_MAJOR_UPDATE, `Finalizing ${layer}`)(); + }, + /* CompositeLayer events */ + "compositeLayer.renderLayers": (layer, updated, subLayers) => { + if (updated) { + log3.log(LOG_LEVEL_MINOR_UPDATE, `Composite layer rendered new subLayers ${layer}`, subLayers)(); + } else { + log3.log(LOG_LEVEL_INFO, `Composite layer reused subLayers ${layer}`, subLayers)(); + } + }, + /* LayerManager events */ + "layerManager.setLayers": (layerManager, updated, layers) => { + if (updated) { + log3.log(LOG_LEVEL_MINOR_UPDATE, `Updating ${layers.length} deck layers`)(); + } + }, + "layerManager.activateViewport": (layerManager, viewport) => { + log3.log(LOG_LEVEL_UPDATE_DETAIL, "Viewport changed", viewport)(); + }, + /* AttributeManager events */ + "attributeManager.invalidate": (attributeManager, trigger, attributeNames) => { + log3.log(LOG_LEVEL_MAJOR_UPDATE, attributeNames ? `invalidated attributes ${attributeNames} (${trigger}) for ${attributeManager.id}` : `invalidated all attributes for ${attributeManager.id}`)(); + }, + "attributeManager.updateStart": (attributeManager) => { + logState.attributeUpdateMessages.length = 0; + logState.attributeManagerUpdateStart = Date.now(); + }, + "attributeManager.updateEnd": (attributeManager, numInstances) => { + const timeMs = Math.round(Date.now() - logState.attributeManagerUpdateStart); + log3.groupCollapsed(LOG_LEVEL_MINOR_UPDATE, `Updated attributes for ${numInstances} instances in ${attributeManager.id} in ${timeMs}ms`)(); + for (const updateMessage of logState.attributeUpdateMessages) { + log3.log(LOG_LEVEL_UPDATE_DETAIL, updateMessage)(); + } + log3.groupEnd(LOG_LEVEL_MINOR_UPDATE)(); + }, + /* Attribute events */ + "attribute.updateStart": (attribute) => { + logState.attributeUpdateStart = Date.now(); + }, + "attribute.allocate": (attribute, numInstances) => { + const message2 = `${attribute.id} allocated ${numInstances}`; + logState.attributeUpdateMessages.push(message2); + }, + "attribute.updateEnd": (attribute, numInstances) => { + const timeMs = Math.round(Date.now() - logState.attributeUpdateStart); + const message2 = `${attribute.id} updated ${numInstances} in ${timeMs}ms`; + logState.attributeUpdateMessages.push(message2); + }, + /* Render events */ + "deckRenderer.renderLayers": (deckRenderer, renderStats, opts) => { + const { pass, redrawReason } = opts; + for (const status of renderStats) { + const { totalCount, visibleCount, compositeCount, pickableCount } = status; + const primitiveCount = totalCount - compositeCount; + const hiddenCount = primitiveCount - visibleCount; + log3.log(LOG_LEVEL_DRAW, `RENDER #${deckRenderer.renderCount} ${visibleCount} (of ${totalCount} layers) to ${pass} because ${redrawReason} (${hiddenCount} hidden, ${compositeCount} composite ${pickableCount} pickable)`)(); + } + } + }); + + // node_modules/@deck.gl/core/dist/debug/index.js + var loggers = {}; + if (true) { + loggers = getLoggers(log_default); + } + function register(handlers) { + loggers = handlers; + } + function debug(eventType, arg1, arg2, arg3) { + if (log_default.level > 0 && loggers[eventType]) { + loggers[eventType].call(null, arg1, arg2, arg3); + } + } + + // node_modules/@deck.gl/core/dist/utils/json-loader.js + function isJSON(text) { + const firstChar = text[0]; + const lastChar = text[text.length - 1]; + return firstChar === "{" && lastChar === "}" || firstChar === "[" && lastChar === "]"; + } + var json_loader_default = { + dataType: null, + batchType: null, + id: "JSON", + name: "JSON", + module: "", + version: "", + options: {}, + extensions: ["json", "geojson"], + mimeTypes: ["application/json", "application/geo+json"], + testText: isJSON, + parseTextSync: JSON.parse + }; + + // node_modules/@deck.gl/core/dist/lib/init.js + function checkVersion() { + const version2 = true ? "9.3.2" : globalThis.DECK_VERSION || "untranspiled source"; + const existingVersion = globalThis.deck && globalThis.deck.VERSION; + if (existingVersion && existingVersion !== version2) { + throw new Error(`deck.gl - multiple versions detected: ${existingVersion} vs ${version2}`); + } + if (!existingVersion) { + log_default.log(1, `deck.gl ${version2}`)(); + globalThis.deck = { + ...globalThis.deck, + VERSION: version2, + version: version2, + log: log_default, + // experimental + _registerLoggers: register + }; + registerLoaders([ + json_loader_default, + // @ts-expect-error non-standard Loader format + [ImageLoader, { imagebitmap: { premultiplyAlpha: "none" } }] + ]); + } + return version2; + } + var VERSION5 = checkVersion(); + + // node_modules/@luma.gl/shadertools/dist/lib/utils/assert.js + function assert4(condition, message2) { + if (!condition) { + const error = new Error(message2 || "shadertools: assertion failed."); + Error.captureStackTrace?.(error, assert4); + throw error; + } + } + + // node_modules/@luma.gl/shadertools/dist/lib/filters/prop-types.js + var DEFAULT_PROP_VALIDATORS = { + number: { + type: "number", + validate(value, propType) { + return Number.isFinite(value) && typeof propType === "object" && (propType.max === void 0 || value <= propType.max) && (propType.min === void 0 || value >= propType.min); + } + }, + array: { + type: "array", + validate(value, propType) { + return Array.isArray(value) || ArrayBuffer.isView(value); + } + } + }; + function makePropValidators(propTypes) { + const propValidators = {}; + for (const [name2, propType] of Object.entries(propTypes)) { + propValidators[name2] = makePropValidator(propType); + } + return propValidators; + } + function makePropValidator(propType) { + let type = getTypeOf(propType); + if (type !== "object") { + return { value: propType, ...DEFAULT_PROP_VALIDATORS[type], type }; + } + if (typeof propType === "object") { + if (!propType) { + return { type: "object", value: null }; + } + if (propType.type !== void 0) { + return { ...propType, ...DEFAULT_PROP_VALIDATORS[propType.type], type: propType.type }; + } + if (propType.value === void 0) { + return { type: "object", value: propType }; + } + type = getTypeOf(propType.value); + return { ...propType, ...DEFAULT_PROP_VALIDATORS[type], type }; + } + throw new Error("props"); + } + function getTypeOf(value) { + if (Array.isArray(value) || ArrayBuffer.isView(value)) { + return "array"; + } + return typeof value; + } + + // node_modules/@luma.gl/shadertools/dist/module-injectors.js + var MODULE_INJECTORS_VS = ( + /* glsl */ + `#ifdef MODULE_LOGDEPTH + logdepth_adjustPosition(gl_Position); +#endif +` + ); + var MODULE_INJECTORS_FS = ( + /* glsl */ + `#ifdef MODULE_MATERIAL + fragColor = material_filterColor(fragColor); +#endif + +#ifdef MODULE_LIGHTING + fragColor = lighting_filterColor(fragColor); +#endif + +#ifdef MODULE_FOG + fragColor = fog_filterColor(fragColor); +#endif + +#ifdef MODULE_PICKING + fragColor = picking_filterHighlightColor(fragColor); + fragColor = picking_filterPickingColor(fragColor); +#endif + +#ifdef MODULE_LOGDEPTH + logdepth_setFragDepth(); +#endif +` + ); + + // node_modules/@luma.gl/shadertools/dist/lib/shader-assembly/shader-injections.js + var MODULE_INJECTORS = { + vertex: MODULE_INJECTORS_VS, + fragment: MODULE_INJECTORS_FS + }; + var REGEX_START_OF_MAIN = /void\s+main\s*\([^)]*\)\s*\{\n?/; + var REGEX_END_OF_MAIN = /}\n?[^{}]*$/; + var fragments = []; + var DECLARATION_INJECT_MARKER = "__LUMA_INJECT_DECLARATIONS__"; + function normalizeInjections(injections) { + const result = { vertex: {}, fragment: {} }; + for (const hook in injections) { + let injection = injections[hook]; + const stage = getHookStage(hook); + if (typeof injection === "string") { + injection = { + order: 0, + injection + }; + } + result[stage][hook] = injection; + } + return result; + } + function getHookStage(hook) { + const type = hook.slice(0, 2); + switch (type) { + case "vs": + return "vertex"; + case "fs": + return "fragment"; + default: + throw new Error(type); + } + } + function injectShader(source3, stage, inject, injectStandardStubs = false) { + const isVertex = stage === "vertex"; + for (const key in inject) { + const fragmentData = inject[key]; + fragmentData.sort((a, b) => a.order - b.order); + fragments.length = fragmentData.length; + for (let i = 0, len4 = fragmentData.length; i < len4; ++i) { + fragments[i] = fragmentData[i].injection; + } + const fragmentString = `${fragments.join("\n")} +`; + switch (key) { + // declarations are injected before the main function + case "vs:#decl": + if (isVertex) { + source3 = source3.replace(DECLARATION_INJECT_MARKER, fragmentString); + } + break; + // inject code at the beginning of the main function + case "vs:#main-start": + if (isVertex) { + source3 = source3.replace(REGEX_START_OF_MAIN, (match) => match + fragmentString); + } + break; + // inject code at the end of main function + case "vs:#main-end": + if (isVertex) { + source3 = source3.replace(REGEX_END_OF_MAIN, (match) => fragmentString + match); + } + break; + // declarations are injected before the main function + case "fs:#decl": + if (!isVertex) { + source3 = source3.replace(DECLARATION_INJECT_MARKER, fragmentString); + } + break; + // inject code at the beginning of the main function + case "fs:#main-start": + if (!isVertex) { + source3 = source3.replace(REGEX_START_OF_MAIN, (match) => match + fragmentString); + } + break; + // inject code at the end of main function + case "fs:#main-end": + if (!isVertex) { + source3 = source3.replace(REGEX_END_OF_MAIN, (match) => fragmentString + match); + } + break; + default: + source3 = source3.replace(key, (match) => match + fragmentString); + } + } + source3 = source3.replace(DECLARATION_INJECT_MARKER, ""); + if (injectStandardStubs) { + source3 = source3.replace(/\}\s*$/, (match) => match + MODULE_INJECTORS[stage]); + } + return source3; + } + + // node_modules/@luma.gl/shadertools/dist/lib/shader-module/shader-module.js + function initializeShaderModules(modules) { + modules.map((module) => initializeShaderModule(module)); + } + function initializeShaderModule(module) { + if (module.instance) { + return; + } + initializeShaderModules(module.dependencies || []); + const { + propTypes = {}, + deprecations = [], + // defines = {}, + inject = {} + } = module; + const instance = { + normalizedInjections: normalizeInjections(inject), + parsedDeprecations: parseDeprecationDefinitions(deprecations) + }; + if (propTypes) { + instance.propValidators = makePropValidators(propTypes); + } + module.instance = instance; + let defaultProps8 = {}; + if (propTypes) { + defaultProps8 = Object.entries(propTypes).reduce((obj, [key, propType]) => { + const value = propType?.value; + if (value) { + obj[key] = value; + } + return obj; + }, {}); + } + module.defaultUniforms = { ...module.defaultUniforms, ...defaultProps8 }; + } + function checkShaderModuleDeprecations(shaderModule, shaderSource, log3) { + shaderModule.deprecations?.forEach((def) => { + if (def.regex?.test(shaderSource)) { + if (def.deprecated) { + log3.deprecated(def.old, def.new)(); + } else { + log3.removed(def.old, def.new)(); + } + } + }); + } + function parseDeprecationDefinitions(deprecations) { + deprecations.forEach((def) => { + switch (def.type) { + case "function": + def.regex = new RegExp(`\\b${def.old}\\(`); + break; + default: + def.regex = new RegExp(`${def.type} ${def.old};`); + } + }); + return deprecations; + } + + // node_modules/@luma.gl/shadertools/dist/lib/shader-module/shader-module-dependencies.js + function getShaderModuleDependencies(modules) { + initializeShaderModules(modules); + const moduleMap = {}; + const moduleDepth = {}; + getDependencyGraph({ modules, level: 0, moduleMap, moduleDepth }); + const dependencies = Object.keys(moduleDepth).sort((a, b) => moduleDepth[b] - moduleDepth[a]).map((name2) => moduleMap[name2]); + initializeShaderModules(dependencies); + return dependencies; + } + function getDependencyGraph(options) { + const { modules, level, moduleMap, moduleDepth } = options; + if (level >= 5) { + throw new Error("Possible loop in shader dependency graph"); + } + for (const module of modules) { + moduleMap[module.name] = module; + if (moduleDepth[module.name] === void 0 || moduleDepth[module.name] < level) { + moduleDepth[module.name] = level; + } + } + for (const module of modules) { + if (module.dependencies) { + getDependencyGraph({ modules: module.dependencies, level: level + 1, moduleMap, moduleDepth }); + } + } + } + + // node_modules/@luma.gl/shadertools/dist/lib/shader-module/shader-module-uniform-layout.js + var GLSL_UNIFORM_BLOCK_FIELD_REGEXP = /^(?:uniform\s+)?(?:(?:lowp|mediump|highp)\s+)?[A-Za-z0-9_]+(?:<[^>]+>)?\s+([A-Za-z0-9_]+)(?:\s*\[[^\]]+\])?\s*;/; + var GLSL_UNIFORM_BLOCK_REGEXP = /((?:layout\s*\([^)]*\)\s*)*)uniform\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{([\s\S]*?)\}\s*([A-Za-z_][A-Za-z0-9_]*)?\s*;/g; + function getShaderModuleUniformBlockName(module) { + return `${module.name}Uniforms`; + } + function getShaderModuleUniformBlockFields(module, stage) { + const shaderSource = stage === "wgsl" ? module.source : stage === "vertex" ? module.vs : module.fs; + if (!shaderSource) { + return null; + } + const uniformBlockName = getShaderModuleUniformBlockName(module); + return extractShaderUniformBlockFieldNames(shaderSource, stage === "wgsl" ? "wgsl" : "glsl", uniformBlockName); + } + function getShaderModuleUniformLayoutValidationResult(module, stage) { + const expectedUniformNames = Object.keys(module.uniformTypes || {}); + if (!expectedUniformNames.length) { + return null; + } + const actualUniformNames = getShaderModuleUniformBlockFields(module, stage); + if (!actualUniformNames) { + return null; + } + return { + moduleName: module.name, + uniformBlockName: getShaderModuleUniformBlockName(module), + stage, + expectedUniformNames, + actualUniformNames, + matches: areStringArraysEqual(expectedUniformNames, actualUniformNames) + }; + } + function validateShaderModuleUniformLayout(module, stage, options = {}) { + const validationResult = getShaderModuleUniformLayoutValidationResult(module, stage); + if (!validationResult || validationResult.matches) { + return validationResult; + } + const message2 = formatShaderModuleUniformLayoutError(validationResult); + options.log?.error?.(message2, validationResult)(); + if (options.throwOnError !== false) { + assert4(false, message2); + } + return validationResult; + } + function getGLSLUniformBlocks(shaderSource) { + const blocks = []; + const uncommentedSource = stripShaderComments(shaderSource); + for (const sourceMatch of uncommentedSource.matchAll(GLSL_UNIFORM_BLOCK_REGEXP)) { + const layoutQualifier = sourceMatch[1]?.trim() || null; + blocks.push({ + blockName: sourceMatch[2], + body: sourceMatch[3], + instanceName: sourceMatch[4] || null, + layoutQualifier, + hasLayoutQualifier: Boolean(layoutQualifier), + isStd140: Boolean(layoutQualifier && /\blayout\s*\([^)]*\bstd140\b[^)]*\)/.exec(layoutQualifier)) + }); + } + return blocks; + } + function warnIfGLSLUniformBlocksAreNotStd140(shaderSource, stage, log3, context) { + const nonStd140Blocks = getGLSLUniformBlocks(shaderSource).filter((block) => !block.isStd140); + const seenBlockNames = /* @__PURE__ */ new Set(); + for (const block of nonStd140Blocks) { + if (seenBlockNames.has(block.blockName)) { + continue; + } + seenBlockNames.add(block.blockName); + const shaderLabel = context?.label ? `${context.label} ` : ""; + const actualLayout = block.hasLayoutQualifier ? `declares ${normalizeWhitespace(block.layoutQualifier)} instead of layout(std140)` : "does not declare layout(std140)"; + const message2 = `${shaderLabel}${stage} shader uniform block ${block.blockName} ${actualLayout}. luma.gl host-side shader block packing assumes explicit layout(std140) for GLSL uniform blocks. Add \`layout(std140)\` to the block declaration.`; + log3?.warn?.(message2, block)(); + } + return nonStd140Blocks; + } + function extractShaderUniformBlockFieldNames(shaderSource, language, uniformBlockName) { + const sourceBody = language === "wgsl" ? extractWGSLStructBody(shaderSource, uniformBlockName) : extractGLSLUniformBlockBody(shaderSource, uniformBlockName); + if (!sourceBody) { + return null; + } + const fieldNames = []; + for (const sourceLine of sourceBody.split("\n")) { + const line = sourceLine.replace(/\/\/.*$/, "").trim(); + if (!line || line.startsWith("#")) { + continue; + } + const fieldMatch = language === "wgsl" ? line.match(/^([A-Za-z0-9_]+)\s*:/) : line.match(GLSL_UNIFORM_BLOCK_FIELD_REGEXP); + if (fieldMatch) { + fieldNames.push(fieldMatch[1]); + } + } + return fieldNames; + } + function extractWGSLStructBody(shaderSource, uniformBlockName) { + const structMatch = new RegExp(`\\bstruct\\s+${uniformBlockName}\\b`, "m").exec(shaderSource); + if (!structMatch) { + return null; + } + const openBraceIndex = shaderSource.indexOf("{", structMatch.index); + if (openBraceIndex < 0) { + return null; + } + let braceDepth = 0; + for (let index2 = openBraceIndex; index2 < shaderSource.length; index2++) { + const character = shaderSource[index2]; + if (character === "{") { + braceDepth++; + continue; + } + if (character !== "}") { + continue; + } + braceDepth--; + if (braceDepth === 0) { + return shaderSource.slice(openBraceIndex + 1, index2); + } + } + return null; + } + function extractGLSLUniformBlockBody(shaderSource, uniformBlockName) { + const block = getGLSLUniformBlocks(shaderSource).find((candidate) => candidate.blockName === uniformBlockName); + return block?.body || null; + } + function areStringArraysEqual(leftValues, rightValues) { + if (leftValues.length !== rightValues.length) { + return false; + } + for (let valueIndex = 0; valueIndex < leftValues.length; valueIndex++) { + if (leftValues[valueIndex] !== rightValues[valueIndex]) { + return false; + } + } + return true; + } + function formatShaderModuleUniformLayoutError(validationResult) { + const { expectedUniformNames, actualUniformNames } = validationResult; + const missingUniformNames = expectedUniformNames.filter((uniformName) => !actualUniformNames.includes(uniformName)); + const unexpectedUniformNames = actualUniformNames.filter((uniformName) => !expectedUniformNames.includes(uniformName)); + const mismatchDetails = [ + `Expected ${expectedUniformNames.length} fields, found ${actualUniformNames.length}.` + ]; + const firstMismatchDescription = getFirstUniformMismatchDescription(expectedUniformNames, actualUniformNames); + if (firstMismatchDescription) { + mismatchDetails.push(firstMismatchDescription); + } + if (missingUniformNames.length) { + mismatchDetails.push(`Missing from shader block (${missingUniformNames.length}): ${formatUniformNameList(missingUniformNames)}.`); + } + if (unexpectedUniformNames.length) { + mismatchDetails.push(`Unexpected in shader block (${unexpectedUniformNames.length}): ${formatUniformNameList(unexpectedUniformNames)}.`); + } + if (expectedUniformNames.length <= 12 && actualUniformNames.length <= 12 && (missingUniformNames.length || unexpectedUniformNames.length)) { + mismatchDetails.push(`Expected: ${expectedUniformNames.join(", ")}.`); + mismatchDetails.push(`Actual: ${actualUniformNames.join(", ")}.`); + } + return `${validationResult.moduleName}: ${validationResult.stage} shader uniform block ${validationResult.uniformBlockName} does not match module.uniformTypes. ${mismatchDetails.join(" ")}`; + } + function stripShaderComments(shaderSource) { + return shaderSource.replace(/\/\*[\s\S]*?\*\//g, "").replace(/\/\/.*$/gm, ""); + } + function normalizeWhitespace(value) { + return value.replace(/\s+/g, " ").trim(); + } + function getFirstUniformMismatchDescription(expectedUniformNames, actualUniformNames) { + const minimumLength = Math.min(expectedUniformNames.length, actualUniformNames.length); + for (let index2 = 0; index2 < minimumLength; index2++) { + if (expectedUniformNames[index2] !== actualUniformNames[index2]) { + return `First mismatch at field ${index2 + 1}: expected ${expectedUniformNames[index2]}, found ${actualUniformNames[index2]}.`; + } + } + if (expectedUniformNames.length > actualUniformNames.length) { + return `Shader block ends after field ${actualUniformNames.length}; expected next field ${expectedUniformNames[actualUniformNames.length]}.`; + } + if (actualUniformNames.length > expectedUniformNames.length) { + return `Shader block has extra field ${actualUniformNames.length}: ${actualUniformNames[expectedUniformNames.length]}.`; + } + return null; + } + function formatUniformNameList(uniformNames, maxNames = 8) { + if (uniformNames.length <= maxNames) { + return uniformNames.join(", "); + } + const remainingCount = uniformNames.length - maxNames; + return `${uniformNames.slice(0, maxNames).join(", ")}, ... (${remainingCount} more)`; + } + + // node_modules/@luma.gl/shadertools/dist/lib/shader-assembly/platform-defines.js + function getPlatformShaderDefines(platformInfo) { + switch (platformInfo?.gpu.toLowerCase()) { + case "apple": + return ( + /* glsl */ + `#define APPLE_GPU +// Apple optimizes away the calculation necessary for emulated fp64 +#define LUMA_FP64_CODE_ELIMINATION_WORKAROUND 1 +#define LUMA_FP32_TAN_PRECISION_WORKAROUND 1 +// Intel GPU doesn't have full 32 bits precision in same cases, causes overflow +#define LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND 1 +` + ); + case "nvidia": + return ( + /* glsl */ + `#define NVIDIA_GPU +// Nvidia optimizes away the calculation necessary for emulated fp64 +#define LUMA_FP64_CODE_ELIMINATION_WORKAROUND 1 +` + ); + case "intel": + return ( + /* glsl */ + `#define INTEL_GPU +// Intel optimizes away the calculation necessary for emulated fp64 +#define LUMA_FP64_CODE_ELIMINATION_WORKAROUND 1 +// Intel's built-in 'tan' function doesn't have acceptable precision +#define LUMA_FP32_TAN_PRECISION_WORKAROUND 1 +// Intel GPU doesn't have full 32 bits precision in same cases, causes overflow +#define LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND 1 +` + ); + case "amd": + return ( + /* glsl */ + `#define AMD_GPU +` + ); + default: + return ( + /* glsl */ + `#define DEFAULT_GPU +// Prevent driver from optimizing away the calculation necessary for emulated fp64 +#define LUMA_FP64_CODE_ELIMINATION_WORKAROUND 1 +// Headless Chrome's software shader 'tan' function doesn't have acceptable precision +#define LUMA_FP32_TAN_PRECISION_WORKAROUND 1 +// If the GPU doesn't have full 32 bits precision, will causes overflow +#define LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND 1 +` + ); + } + } + + // node_modules/@luma.gl/shadertools/dist/lib/shader-transpiler/transpile-glsl-shader.js + function transpileGLSLShader(source3, stage) { + const sourceGLSLVersion = Number(source3.match(/^#version[ \t]+(\d+)/m)?.[1] || 100); + if (sourceGLSLVersion !== 300) { + throw new Error("luma.gl v9 only supports GLSL 3.00 shader sources"); + } + switch (stage) { + case "vertex": + source3 = convertShader(source3, ES300_VERTEX_REPLACEMENTS); + return source3; + case "fragment": + source3 = convertShader(source3, ES300_FRAGMENT_REPLACEMENTS); + return source3; + default: + throw new Error(stage); + } + } + var ES300_REPLACEMENTS = [ + // Fix poorly formatted version directive + [/^(#version[ \t]+(100|300[ \t]+es))?[ \t]*\n/, "#version 300 es\n"], + // The individual `texture...()` functions were replaced with `texture()` overloads + [/\btexture(2D|2DProj|Cube)Lod(EXT)?\(/g, "textureLod("], + [/\btexture(2D|2DProj|Cube)(EXT)?\(/g, "texture("] + ]; + var ES300_VERTEX_REPLACEMENTS = [ + ...ES300_REPLACEMENTS, + // `attribute` keyword replaced with `in` + [makeVariableTextRegExp("attribute"), "in $1"], + // `varying` keyword replaced with `out` + [makeVariableTextRegExp("varying"), "out $1"] + ]; + var ES300_FRAGMENT_REPLACEMENTS = [ + ...ES300_REPLACEMENTS, + // `varying` keyword replaced with `in` + [makeVariableTextRegExp("varying"), "in $1"] + ]; + function convertShader(source3, replacements) { + for (const [pattern, replacement] of replacements) { + source3 = source3.replace(pattern, replacement); + } + return source3; + } + function makeVariableTextRegExp(qualifier) { + return new RegExp(`\\b${qualifier}[ \\t]+(\\w+[ \\t]+\\w+(\\[\\w+\\])?;)`, "g"); + } + + // node_modules/@luma.gl/shadertools/dist/lib/shader-assembly/shader-hooks.js + function getShaderHooks(hookFunctions, hookInjections) { + let result = ""; + for (const hookName in hookFunctions) { + const hookFunction = hookFunctions[hookName]; + result += `void ${hookFunction.signature} { +`; + if (hookFunction.header) { + result += ` ${hookFunction.header}`; + } + if (hookInjections[hookName]) { + const injections = hookInjections[hookName]; + injections.sort((a, b) => a.order - b.order); + for (const injection of injections) { + result += ` ${injection.injection} +`; + } + } + if (hookFunction.footer) { + result += ` ${hookFunction.footer}`; + } + result += "}\n"; + } + return result; + } + function normalizeShaderHooks(hookFunctions) { + const result = { vertex: {}, fragment: {} }; + for (const hookFunction of hookFunctions) { + let opts; + let hook; + if (typeof hookFunction !== "string") { + opts = hookFunction; + hook = opts.hook; + } else { + opts = {}; + hook = hookFunction; + } + hook = hook.trim(); + const [shaderStage, signature] = hook.split(":"); + const name2 = hook.replace(/\(.+/, ""); + const normalizedHook = Object.assign(opts, { signature }); + switch (shaderStage) { + case "vs": + result.vertex[name2] = normalizedHook; + break; + case "fs": + result.fragment[name2] = normalizedHook; + break; + default: + throw new Error(shaderStage); + } + } + return result; + } + + // node_modules/@luma.gl/shadertools/dist/lib/glsl-utils/get-shader-info.js + function getShaderInfo(source3, defaultName) { + return { + name: getShaderName(source3, defaultName), + language: "glsl", + version: getShaderVersion(source3) + }; + } + function getShaderName(shader, defaultName = "unnamed") { + const SHADER_NAME_REGEXP = /#define[^\S\r\n]*SHADER_NAME[^\S\r\n]*([A-Za-z0-9_-]+)\s*/; + const match = SHADER_NAME_REGEXP.exec(shader); + return match ? match[1] : defaultName; + } + function getShaderVersion(source3) { + let version2 = 100; + const words = source3.match(/[^\s]+/g); + if (words && words.length >= 2 && words[0] === "#version") { + const parsedVersion = parseInt(words[1], 10); + if (Number.isFinite(parsedVersion)) { + version2 = parsedVersion; + } + } + if (version2 !== 100 && version2 !== 300) { + throw new Error(`Invalid GLSL version ${version2}`); + } + return version2; + } + + // node_modules/@luma.gl/shadertools/dist/lib/shader-assembly/wgsl-binding-scan.js + var WGSL_BINDABLE_VARIABLE_PATTERN = "(?:var<\\s*(uniform|storage(?:\\s*,\\s*[A-Za-z_][A-Za-z0-9_]*)?)\\s*>|var)\\s+([A-Za-z_][A-Za-z0-9_]*)"; + var WGSL_BINDING_DECLARATION_SEPARATOR_PATTERN = "\\s*"; + var MODULE_WGSL_BINDING_DECLARATION_REGEXES = [ + new RegExp(`@binding\\(\\s*(auto|\\d+)\\s*\\)${WGSL_BINDING_DECLARATION_SEPARATOR_PATTERN}@group\\(\\s*(\\d+)\\s*\\)${WGSL_BINDING_DECLARATION_SEPARATOR_PATTERN}${WGSL_BINDABLE_VARIABLE_PATTERN}`, "g"), + new RegExp(`@group\\(\\s*(\\d+)\\s*\\)${WGSL_BINDING_DECLARATION_SEPARATOR_PATTERN}@binding\\(\\s*(auto|\\d+)\\s*\\)${WGSL_BINDING_DECLARATION_SEPARATOR_PATTERN}${WGSL_BINDABLE_VARIABLE_PATTERN}`, "g") + ]; + var WGSL_BINDING_DECLARATION_REGEXES = [ + new RegExp(`@binding\\(\\s*(auto|\\d+)\\s*\\)${WGSL_BINDING_DECLARATION_SEPARATOR_PATTERN}@group\\(\\s*(\\d+)\\s*\\)${WGSL_BINDING_DECLARATION_SEPARATOR_PATTERN}${WGSL_BINDABLE_VARIABLE_PATTERN}`, "g"), + new RegExp(`@group\\(\\s*(\\d+)\\s*\\)${WGSL_BINDING_DECLARATION_SEPARATOR_PATTERN}@binding\\(\\s*(auto|\\d+)\\s*\\)${WGSL_BINDING_DECLARATION_SEPARATOR_PATTERN}${WGSL_BINDABLE_VARIABLE_PATTERN}`, "g") + ]; + var WGSL_EXPLICIT_BINDING_DECLARATION_REGEXES = [ + new RegExp(`@binding\\(\\s*(\\d+)\\s*\\)${WGSL_BINDING_DECLARATION_SEPARATOR_PATTERN}@group\\(\\s*(\\d+)\\s*\\)${WGSL_BINDING_DECLARATION_SEPARATOR_PATTERN}${WGSL_BINDABLE_VARIABLE_PATTERN}`, "g"), + new RegExp(`@group\\(\\s*(\\d+)\\s*\\)${WGSL_BINDING_DECLARATION_SEPARATOR_PATTERN}@binding\\(\\s*(\\d+)\\s*\\)${WGSL_BINDING_DECLARATION_SEPARATOR_PATTERN}${WGSL_BINDABLE_VARIABLE_PATTERN}`, "g") + ]; + var WGSL_AUTO_BINDING_DECLARATION_REGEXES = [ + new RegExp(`@binding\\(\\s*(auto)\\s*\\)\\s*@group\\(\\s*(\\d+)\\s*\\)\\s*${WGSL_BINDABLE_VARIABLE_PATTERN}`, "g"), + new RegExp(`@group\\(\\s*(\\d+)\\s*\\)\\s*@binding\\(\\s*(auto)\\s*\\)\\s*${WGSL_BINDABLE_VARIABLE_PATTERN}`, "g"), + new RegExp(`@binding\\(\\s*(auto)\\s*\\)\\s*@group\\(\\s*(\\d+)\\s*\\)(?:[\\s\\n\\r]*@[A-Za-z_][^\\n\\r]*)*[\\s\\n\\r]*${WGSL_BINDABLE_VARIABLE_PATTERN}`, "g"), + new RegExp(`@group\\(\\s*(\\d+)\\s*\\)\\s*@binding\\(\\s*(auto)\\s*\\)(?:[\\s\\n\\r]*@[A-Za-z_][^\\n\\r]*)*[\\s\\n\\r]*${WGSL_BINDABLE_VARIABLE_PATTERN}`, "g") + ]; + function maskWGSLComments(source3) { + const maskedCharacters = source3.split(""); + let index2 = 0; + let blockCommentDepth = 0; + let inLineComment = false; + let inString = false; + let isEscaped = false; + while (index2 < source3.length) { + const character = source3[index2]; + const nextCharacter = source3[index2 + 1]; + if (inString) { + if (isEscaped) { + isEscaped = false; + } else if (character === "\\") { + isEscaped = true; + } else if (character === '"') { + inString = false; + } + index2++; + continue; + } + if (inLineComment) { + if (character === "\n" || character === "\r") { + inLineComment = false; + } else { + maskedCharacters[index2] = " "; + } + index2++; + continue; + } + if (blockCommentDepth > 0) { + if (character === "/" && nextCharacter === "*") { + maskedCharacters[index2] = " "; + maskedCharacters[index2 + 1] = " "; + blockCommentDepth++; + index2 += 2; + continue; + } + if (character === "*" && nextCharacter === "/") { + maskedCharacters[index2] = " "; + maskedCharacters[index2 + 1] = " "; + blockCommentDepth--; + index2 += 2; + continue; + } + if (character !== "\n" && character !== "\r") { + maskedCharacters[index2] = " "; + } + index2++; + continue; + } + if (character === '"') { + inString = true; + index2++; + continue; + } + if (character === "/" && nextCharacter === "/") { + maskedCharacters[index2] = " "; + maskedCharacters[index2 + 1] = " "; + inLineComment = true; + index2 += 2; + continue; + } + if (character === "/" && nextCharacter === "*") { + maskedCharacters[index2] = " "; + maskedCharacters[index2 + 1] = " "; + blockCommentDepth = 1; + index2 += 2; + continue; + } + index2++; + } + return maskedCharacters.join(""); + } + function getWGSLBindingDeclarationMatches(source3, regexes) { + const maskedSource = maskWGSLComments(source3); + const matches3 = []; + for (const regex of regexes) { + regex.lastIndex = 0; + let match; + match = regex.exec(maskedSource); + while (match) { + const isBindingFirst = regex === regexes[0]; + const index2 = match.index; + const length4 = match[0].length; + matches3.push({ + match: source3.slice(index2, index2 + length4), + index: index2, + length: length4, + bindingToken: match[isBindingFirst ? 1 : 2], + groupToken: match[isBindingFirst ? 2 : 1], + accessDeclaration: match[3]?.trim(), + name: match[4] + }); + match = regex.exec(maskedSource); + } + } + return matches3.sort((left, right) => left.index - right.index); + } + function replaceWGSLBindingDeclarationMatches(source3, regexes, replacer) { + const matches3 = getWGSLBindingDeclarationMatches(source3, regexes); + if (!matches3.length) { + return source3; + } + let relocatedSource = ""; + let lastIndex = 0; + for (const match of matches3) { + relocatedSource += source3.slice(lastIndex, match.index); + relocatedSource += replacer(match); + lastIndex = match.index + match.length; + } + relocatedSource += source3.slice(lastIndex); + return relocatedSource; + } + function hasWGSLAutoBinding(source3) { + return /@binding\(\s*auto\s*\)/.test(maskWGSLComments(source3)); + } + function getFirstWGSLAutoBindingDeclarationMatch(source3, regexes) { + const autoBindingRegexes = regexes === MODULE_WGSL_BINDING_DECLARATION_REGEXES || regexes === WGSL_BINDING_DECLARATION_REGEXES ? WGSL_AUTO_BINDING_DECLARATION_REGEXES : regexes; + return getWGSLBindingDeclarationMatches(source3, autoBindingRegexes).find((declarationMatch) => declarationMatch.bindingToken === "auto"); + } + + // node_modules/@luma.gl/shadertools/dist/lib/shader-assembly/wgsl-binding-debug.js + var WGSL_BINDING_DEBUG_REGEXES = [ + new RegExp(`@binding\\(\\s*(\\d+)\\s*\\)\\s*@group\\(\\s*(\\d+)\\s*\\)\\s*${WGSL_BINDABLE_VARIABLE_PATTERN}\\s*:\\s*([^;]+);`, "g"), + new RegExp(`@group\\(\\s*(\\d+)\\s*\\)\\s*@binding\\(\\s*(\\d+)\\s*\\)\\s*${WGSL_BINDABLE_VARIABLE_PATTERN}\\s*:\\s*([^;]+);`, "g") + ]; + function getShaderBindingDebugRowsFromWGSL(source3, bindingAssignments = []) { + const maskedSource = maskWGSLComments(source3); + const assignmentMap = /* @__PURE__ */ new Map(); + for (const bindingAssignment of bindingAssignments) { + assignmentMap.set(getBindingAssignmentKey(bindingAssignment.name, bindingAssignment.group, bindingAssignment.location), bindingAssignment.moduleName); + } + const rows = []; + for (const regex of WGSL_BINDING_DEBUG_REGEXES) { + regex.lastIndex = 0; + let match; + match = regex.exec(maskedSource); + while (match) { + const isBindingFirst = regex === WGSL_BINDING_DEBUG_REGEXES[0]; + const binding = Number(match[isBindingFirst ? 1 : 2]); + const group2 = Number(match[isBindingFirst ? 2 : 1]); + const accessDeclaration = match[3]?.trim(); + const name2 = match[4]; + const resourceType = match[5].trim(); + const moduleName = assignmentMap.get(getBindingAssignmentKey(name2, group2, binding)); + rows.push(normalizeShaderBindingDebugRow({ + name: name2, + group: group2, + binding, + owner: moduleName ? "module" : "application", + moduleName, + accessDeclaration, + resourceType + })); + match = regex.exec(maskedSource); + } + } + return rows.sort((left, right) => { + if (left.group !== right.group) { + return left.group - right.group; + } + if (left.binding !== right.binding) { + return left.binding - right.binding; + } + return left.name.localeCompare(right.name); + }); + } + function normalizeShaderBindingDebugRow(row) { + const baseRow = { + name: row.name, + group: row.group, + binding: row.binding, + owner: row.owner, + kind: "unknown", + moduleName: row.moduleName, + resourceType: row.resourceType + }; + if (row.accessDeclaration) { + const access = row.accessDeclaration.split(",").map((value) => value.trim()); + if (access[0] === "uniform") { + return { ...baseRow, kind: "uniform", access: "uniform" }; + } + if (access[0] === "storage") { + const storageAccess = access[1] || "read_write"; + return { + ...baseRow, + kind: storageAccess === "read" ? "read-only-storage" : "storage", + access: storageAccess + }; + } + } + if (row.resourceType === "sampler" || row.resourceType === "sampler_comparison") { + return { + ...baseRow, + kind: "sampler", + samplerKind: row.resourceType === "sampler_comparison" ? "comparison" : "filtering" + }; + } + if (row.resourceType.startsWith("texture_storage_")) { + return { + ...baseRow, + kind: "storage-texture", + access: getStorageTextureAccess(row.resourceType), + viewDimension: getTextureViewDimension(row.resourceType) + }; + } + if (row.resourceType.startsWith("texture_")) { + return { + ...baseRow, + kind: "texture", + viewDimension: getTextureViewDimension(row.resourceType), + sampleType: getTextureSampleType(row.resourceType), + multisampled: row.resourceType.startsWith("texture_multisampled_") + }; + } + return baseRow; + } + function getBindingAssignmentKey(name2, group2, binding) { + return `${group2}:${binding}:${name2}`; + } + function getTextureViewDimension(resourceType) { + if (resourceType.includes("cube_array")) { + return "cube-array"; + } + if (resourceType.includes("2d_array")) { + return "2d-array"; + } + if (resourceType.includes("cube")) { + return "cube"; + } + if (resourceType.includes("3d")) { + return "3d"; + } + if (resourceType.includes("2d")) { + return "2d"; + } + if (resourceType.includes("1d")) { + return "1d"; + } + return void 0; + } + function getTextureSampleType(resourceType) { + if (resourceType.startsWith("texture_depth_")) { + return "depth"; + } + if (resourceType.includes("")) { + return "sint"; + } + if (resourceType.includes("")) { + return "uint"; + } + if (resourceType.includes("")) { + return "float"; + } + return void 0; + } + function getStorageTextureAccess(resourceType) { + const match = /,\s*([A-Za-z_][A-Za-z0-9_]*)\s*>$/.exec(resourceType); + return match?.[1]; + } + + // node_modules/@luma.gl/shadertools/dist/lib/shader-assembly/assemble-shaders.js + var INJECT_SHADER_DECLARATIONS = ` + +${DECLARATION_INJECT_MARKER} +`; + var RESERVED_APPLICATION_GROUP_0_BINDING_LIMIT = 100; + var FRAGMENT_SHADER_PROLOGUE = ( + /* glsl */ + `precision highp float; +` + ); + function assembleWGSLShader(options) { + const modules = getShaderModuleDependencies(options.modules || []); + const { source: source3, bindingAssignments } = assembleShaderWGSL(options.platformInfo, { + ...options, + source: options.source, + stage: "vertex", + modules + }); + return { + source: source3, + getUniforms: assembleGetUniforms(modules), + bindingAssignments, + bindingTable: getShaderBindingDebugRowsFromWGSL(source3, bindingAssignments) + }; + } + function assembleGLSLShaderPair(options) { + const { vs: vs7, fs: fs5 } = options; + const modules = getShaderModuleDependencies(options.modules || []); + return { + vs: assembleShaderGLSL(options.platformInfo, { + ...options, + source: vs7, + stage: "vertex", + modules + }), + fs: assembleShaderGLSL(options.platformInfo, { + ...options, + // @ts-expect-error + source: fs5, + stage: "fragment", + modules + }), + getUniforms: assembleGetUniforms(modules) + }; + } + function assembleShaderWGSL(platformInfo, options) { + const { + // id, + source: source3, + stage, + modules, + // defines = {}, + hookFunctions = [], + inject = {}, + log: log3 + } = options; + assert4(typeof source3 === "string", "shader source must be a string"); + const coreSource = source3; + let assembledSource = ""; + const hookFunctionMap = normalizeShaderHooks(hookFunctions); + const hookInjections = {}; + const declInjections = {}; + const mainInjections = {}; + for (const key in inject) { + const injection = typeof inject[key] === "string" ? { injection: inject[key], order: 0 } : inject[key]; + const match = /^(v|f)s:(#)?([\w-]+)$/.exec(key); + if (match) { + const hash = match[2]; + const name2 = match[3]; + if (hash) { + if (name2 === "decl") { + declInjections[key] = [injection]; + } else { + mainInjections[key] = [injection]; + } + } else { + hookInjections[key] = [injection]; + } + } else { + mainInjections[key] = [injection]; + } + } + const modulesToInject = modules; + const applicationRelocation = relocateWGSLApplicationBindings(coreSource); + const usedBindingsByGroup = getUsedBindingsByGroupFromApplicationWGSL(applicationRelocation.source); + const reservedBindingKeysByGroup = reserveRegisteredModuleBindings(modulesToInject, options._bindingRegistry, usedBindingsByGroup); + const bindingAssignments = []; + for (const module of modulesToInject) { + if (log3) { + checkShaderModuleDeprecations(module, coreSource, log3); + } + const relocation = relocateWGSLModuleBindings(getShaderModuleSource(module, "wgsl", log3), module, { + usedBindingsByGroup, + bindingRegistry: options._bindingRegistry, + reservedBindingKeysByGroup + }); + bindingAssignments.push(...relocation.bindingAssignments); + const moduleSource = relocation.source; + assembledSource += moduleSource; + const injections = module.injections?.[stage] || {}; + for (const key in injections) { + const match = /^(v|f)s:#([\w-]+)$/.exec(key); + if (match) { + const name2 = match[2]; + const injectionType = name2 === "decl" ? declInjections : mainInjections; + injectionType[key] = injectionType[key] || []; + injectionType[key].push(injections[key]); + } else { + hookInjections[key] = hookInjections[key] || []; + hookInjections[key].push(injections[key]); + } + } + } + assembledSource += INJECT_SHADER_DECLARATIONS; + assembledSource = injectShader(assembledSource, stage, declInjections); + assembledSource += getShaderHooks(hookFunctionMap[stage], hookInjections); + assembledSource += formatWGSLBindingAssignmentComments(bindingAssignments); + assembledSource += applicationRelocation.source; + assembledSource = injectShader(assembledSource, stage, mainInjections); + assertNoUnresolvedAutoBindings(assembledSource); + return { source: assembledSource, bindingAssignments }; + } + function assembleShaderGLSL(platformInfo, options) { + const { source: source3, stage, language = "glsl", modules, defines: defines2 = {}, hookFunctions = [], inject = {}, prologue = true, log: log3 } = options; + assert4(typeof source3 === "string", "shader source must be a string"); + const sourceVersion = language === "glsl" ? getShaderInfo(source3).version : -1; + const targetVersion = platformInfo.shaderLanguageVersion; + const sourceVersionDirective = sourceVersion === 100 ? "#version 100" : "#version 300 es"; + const sourceLines = source3.split("\n"); + const coreSource = sourceLines.slice(1).join("\n"); + const allDefines = {}; + modules.forEach((module) => { + Object.assign(allDefines, module.defines); + }); + Object.assign(allDefines, defines2); + let assembledSource = ""; + switch (language) { + case "wgsl": + break; + case "glsl": + assembledSource = prologue ? `${sourceVersionDirective} + +// ----- PROLOGUE ------------------------- +${`#define SHADER_TYPE_${stage.toUpperCase()}`} + +${getPlatformShaderDefines(platformInfo)} +${stage === "fragment" ? FRAGMENT_SHADER_PROLOGUE : ""} + +// ----- APPLICATION DEFINES ------------------------- + +${getApplicationDefines(allDefines)} + +` : `${sourceVersionDirective} +`; + break; + } + const hookFunctionMap = normalizeShaderHooks(hookFunctions); + const hookInjections = {}; + const declInjections = {}; + const mainInjections = {}; + for (const key in inject) { + const injection = typeof inject[key] === "string" ? { injection: inject[key], order: 0 } : inject[key]; + const match = /^(v|f)s:(#)?([\w-]+)$/.exec(key); + if (match) { + const hash = match[2]; + const name2 = match[3]; + if (hash) { + if (name2 === "decl") { + declInjections[key] = [injection]; + } else { + mainInjections[key] = [injection]; + } + } else { + hookInjections[key] = [injection]; + } + } else { + mainInjections[key] = [injection]; + } + } + for (const module of modules) { + if (log3) { + checkShaderModuleDeprecations(module, coreSource, log3); + } + const moduleSource = getShaderModuleSource(module, stage, log3); + assembledSource += moduleSource; + const injections = module.instance?.normalizedInjections[stage] || {}; + for (const key in injections) { + const match = /^(v|f)s:#([\w-]+)$/.exec(key); + if (match) { + const name2 = match[2]; + const injectionType = name2 === "decl" ? declInjections : mainInjections; + injectionType[key] = injectionType[key] || []; + injectionType[key].push(injections[key]); + } else { + hookInjections[key] = hookInjections[key] || []; + hookInjections[key].push(injections[key]); + } + } + } + assembledSource += "// ----- MAIN SHADER SOURCE -------------------------"; + assembledSource += INJECT_SHADER_DECLARATIONS; + assembledSource = injectShader(assembledSource, stage, declInjections); + assembledSource += getShaderHooks(hookFunctionMap[stage], hookInjections); + assembledSource += coreSource; + assembledSource = injectShader(assembledSource, stage, mainInjections); + if (language === "glsl" && sourceVersion !== targetVersion) { + assembledSource = transpileGLSLShader(assembledSource, stage); + } + if (language === "glsl") { + warnIfGLSLUniformBlocksAreNotStd140(assembledSource, stage, log3); + } + return assembledSource.trim(); + } + function assembleGetUniforms(modules) { + return function getUniforms3(opts) { + const uniforms = {}; + for (const module of modules) { + const moduleUniforms = module.getUniforms?.(opts, uniforms); + Object.assign(uniforms, moduleUniforms); + } + return uniforms; + }; + } + function getApplicationDefines(defines2 = {}) { + let sourceText = ""; + for (const define2 in defines2) { + const value = defines2[define2]; + if (value || Number.isFinite(value)) { + sourceText += `#define ${define2.toUpperCase()} ${defines2[define2]} +`; + } + } + return sourceText; + } + function getShaderModuleSource(module, stage, log3) { + let moduleSource; + switch (stage) { + case "vertex": + moduleSource = module.vs || ""; + break; + case "fragment": + moduleSource = module.fs || ""; + break; + case "wgsl": + moduleSource = module.source || ""; + break; + default: + assert4(false); + } + if (!module.name) { + throw new Error("Shader module must have a name"); + } + validateShaderModuleUniformLayout(module, stage, { log: log3 }); + const moduleName = module.name.toUpperCase().replace(/[^0-9a-z]/gi, "_"); + let source3 = `// ----- MODULE ${module.name} --------------- + +`; + if (stage !== "wgsl") { + source3 += `#define MODULE_${moduleName} +`; + } + source3 += `${moduleSource} +`; + return source3; + } + function getUsedBindingsByGroupFromApplicationWGSL(source3) { + const usedBindingsByGroup = /* @__PURE__ */ new Map(); + for (const match of getWGSLBindingDeclarationMatches(source3, WGSL_EXPLICIT_BINDING_DECLARATION_REGEXES)) { + const location = Number(match.bindingToken); + const group2 = Number(match.groupToken); + validateApplicationWGSLBinding(group2, location, match.name); + registerUsedBindingLocation(usedBindingsByGroup, group2, location, `application binding "${match.name}"`); + } + return usedBindingsByGroup; + } + function relocateWGSLApplicationBindings(source3) { + const declarationMatches = getWGSLBindingDeclarationMatches(source3, WGSL_BINDING_DECLARATION_REGEXES); + const usedBindingsByGroup = /* @__PURE__ */ new Map(); + for (const declarationMatch of declarationMatches) { + if (declarationMatch.bindingToken === "auto") { + continue; + } + const location = Number(declarationMatch.bindingToken); + const group2 = Number(declarationMatch.groupToken); + validateApplicationWGSLBinding(group2, location, declarationMatch.name); + registerUsedBindingLocation(usedBindingsByGroup, group2, location, `application binding "${declarationMatch.name}"`); + } + const relocationState = { + sawSupportedBindingDeclaration: declarationMatches.length > 0 + }; + const relocatedSource = replaceWGSLBindingDeclarationMatches(source3, WGSL_BINDING_DECLARATION_REGEXES, (declarationMatch) => relocateWGSLApplicationBindingMatch(declarationMatch, usedBindingsByGroup, relocationState)); + if (hasWGSLAutoBinding(source3) && !relocationState.sawSupportedBindingDeclaration) { + throw new Error('Unsupported @binding(auto) declaration form in application WGSL. Use adjacent "@group(N)" and "@binding(auto)" decorators followed by a bindable "var" declaration.'); + } + return { source: relocatedSource }; + } + function relocateWGSLModuleBindings(moduleSource, module, context) { + const bindingAssignments = []; + const declarationMatches = getWGSLBindingDeclarationMatches(moduleSource, MODULE_WGSL_BINDING_DECLARATION_REGEXES); + const relocationState = { + sawSupportedBindingDeclaration: declarationMatches.length > 0, + nextHintedBindingLocation: typeof module.firstBindingSlot === "number" ? module.firstBindingSlot : null + }; + const relocatedSource = replaceWGSLBindingDeclarationMatches(moduleSource, MODULE_WGSL_BINDING_DECLARATION_REGEXES, (declarationMatch) => relocateWGSLModuleBindingMatch(declarationMatch, { + module, + context, + bindingAssignments, + relocationState + })); + if (hasWGSLAutoBinding(moduleSource) && !relocationState.sawSupportedBindingDeclaration) { + throw new Error(`Unsupported @binding(auto) declaration form in module "${module.name}". Use adjacent "@group(N)" and "@binding(auto)" decorators followed by a bindable "var" declaration.`); + } + return { source: relocatedSource, bindingAssignments }; + } + function relocateWGSLModuleBindingMatch(declarationMatch, params) { + const { module, context, bindingAssignments, relocationState } = params; + const { match, bindingToken, groupToken, name: name2 } = declarationMatch; + const group2 = Number(groupToken); + if (bindingToken === "auto") { + const registryKey = getBindingRegistryKey(group2, module.name, name2); + const registryLocation = context.bindingRegistry?.get(registryKey); + const location2 = registryLocation !== void 0 ? registryLocation : relocationState.nextHintedBindingLocation === null ? allocateAutoBindingLocation(group2, context.usedBindingsByGroup) : allocateAutoBindingLocation(group2, context.usedBindingsByGroup, relocationState.nextHintedBindingLocation); + validateModuleWGSLBinding(module.name, group2, location2, name2); + if (registryLocation !== void 0 && claimReservedBindingLocation(context.reservedBindingKeysByGroup, group2, location2, registryKey)) { + bindingAssignments.push({ moduleName: module.name, name: name2, group: group2, location: location2 }); + return match.replace(/@binding\(\s*auto\s*\)/, `@binding(${location2})`); + } + registerUsedBindingLocation(context.usedBindingsByGroup, group2, location2, `module "${module.name}" binding "${name2}"`); + context.bindingRegistry?.set(registryKey, location2); + bindingAssignments.push({ moduleName: module.name, name: name2, group: group2, location: location2 }); + if (relocationState.nextHintedBindingLocation !== null && registryLocation === void 0) { + relocationState.nextHintedBindingLocation = location2 + 1; + } + return match.replace(/@binding\(\s*auto\s*\)/, `@binding(${location2})`); + } + const location = Number(bindingToken); + validateModuleWGSLBinding(module.name, group2, location, name2); + registerUsedBindingLocation(context.usedBindingsByGroup, group2, location, `module "${module.name}" binding "${name2}"`); + bindingAssignments.push({ moduleName: module.name, name: name2, group: group2, location }); + return match; + } + function relocateWGSLApplicationBindingMatch(declarationMatch, usedBindingsByGroup, relocationState) { + const { match, bindingToken, groupToken, name: name2 } = declarationMatch; + const group2 = Number(groupToken); + if (bindingToken === "auto") { + const location = allocateApplicationAutoBindingLocation(group2, usedBindingsByGroup); + validateApplicationWGSLBinding(group2, location, name2); + registerUsedBindingLocation(usedBindingsByGroup, group2, location, `application binding "${name2}"`); + return match.replace(/@binding\(\s*auto\s*\)/, `@binding(${location})`); + } + relocationState.sawSupportedBindingDeclaration = true; + return match; + } + function reserveRegisteredModuleBindings(modules, bindingRegistry, usedBindingsByGroup) { + const reservedBindingKeysByGroup = /* @__PURE__ */ new Map(); + if (!bindingRegistry) { + return reservedBindingKeysByGroup; + } + for (const module of modules) { + for (const binding of getModuleWGSLBindingDeclarations(module)) { + const registryKey = getBindingRegistryKey(binding.group, module.name, binding.name); + const location = bindingRegistry.get(registryKey); + if (location !== void 0) { + const reservedBindingKeys = reservedBindingKeysByGroup.get(binding.group) || /* @__PURE__ */ new Map(); + const existingReservation = reservedBindingKeys.get(location); + if (existingReservation && existingReservation !== registryKey) { + throw new Error(`Duplicate WGSL binding reservation for modules "${existingReservation}" and "${registryKey}": group ${binding.group}, binding ${location}.`); + } + registerUsedBindingLocation(usedBindingsByGroup, binding.group, location, `registered module binding "${registryKey}"`); + reservedBindingKeys.set(location, registryKey); + reservedBindingKeysByGroup.set(binding.group, reservedBindingKeys); + } + } + } + return reservedBindingKeysByGroup; + } + function claimReservedBindingLocation(reservedBindingKeysByGroup, group2, location, registryKey) { + const reservedBindingKeys = reservedBindingKeysByGroup.get(group2); + if (!reservedBindingKeys) { + return false; + } + const reservedKey = reservedBindingKeys.get(location); + if (!reservedKey) { + return false; + } + if (reservedKey !== registryKey) { + throw new Error(`Registered module binding "${registryKey}" collided with "${reservedKey}": group ${group2}, binding ${location}.`); + } + return true; + } + function getModuleWGSLBindingDeclarations(module) { + const declarations = []; + const moduleSource = module.source || ""; + for (const match of getWGSLBindingDeclarationMatches(moduleSource, MODULE_WGSL_BINDING_DECLARATION_REGEXES)) { + declarations.push({ + name: match.name, + group: Number(match.groupToken) + }); + } + return declarations; + } + function validateApplicationWGSLBinding(group2, location, name2) { + if (group2 === 0 && location >= RESERVED_APPLICATION_GROUP_0_BINDING_LIMIT) { + throw new Error(`Application binding "${name2}" in group 0 uses reserved binding ${location}. Application-owned explicit group-0 bindings must stay below ${RESERVED_APPLICATION_GROUP_0_BINDING_LIMIT}.`); + } + } + function validateModuleWGSLBinding(moduleName, group2, location, name2) { + if (group2 === 0 && location < RESERVED_APPLICATION_GROUP_0_BINDING_LIMIT) { + throw new Error(`Module "${moduleName}" binding "${name2}" in group 0 uses reserved application binding ${location}. Module-owned explicit group-0 bindings must be ${RESERVED_APPLICATION_GROUP_0_BINDING_LIMIT} or higher.`); + } + } + function registerUsedBindingLocation(usedBindingsByGroup, group2, location, label) { + const usedBindings = usedBindingsByGroup.get(group2) || /* @__PURE__ */ new Set(); + if (usedBindings.has(location)) { + throw new Error(`Duplicate WGSL binding assignment for ${label}: group ${group2}, binding ${location}.`); + } + usedBindings.add(location); + usedBindingsByGroup.set(group2, usedBindings); + } + function allocateAutoBindingLocation(group2, usedBindingsByGroup, preferredBindingLocation) { + const usedBindings = usedBindingsByGroup.get(group2) || /* @__PURE__ */ new Set(); + let nextBinding = preferredBindingLocation ?? (group2 === 0 ? RESERVED_APPLICATION_GROUP_0_BINDING_LIMIT : usedBindings.size > 0 ? Math.max(...usedBindings) + 1 : 0); + while (usedBindings.has(nextBinding)) { + nextBinding++; + } + return nextBinding; + } + function allocateApplicationAutoBindingLocation(group2, usedBindingsByGroup) { + const usedBindings = usedBindingsByGroup.get(group2) || /* @__PURE__ */ new Set(); + let nextBinding = 0; + while (usedBindings.has(nextBinding)) { + nextBinding++; + } + return nextBinding; + } + function assertNoUnresolvedAutoBindings(source3) { + const unresolvedBinding = getFirstWGSLAutoBindingDeclarationMatch(source3, MODULE_WGSL_BINDING_DECLARATION_REGEXES); + if (!unresolvedBinding) { + return; + } + const moduleName = getWGSLModuleNameAtIndex(source3, unresolvedBinding.index); + if (moduleName) { + throw new Error(`Unresolved @binding(auto) for module "${moduleName}" binding "${unresolvedBinding.name}" remained in assembled WGSL source.`); + } + if (isInApplicationWGSLSection(source3, unresolvedBinding.index)) { + throw new Error(`Unresolved @binding(auto) for application binding "${unresolvedBinding.name}" remained in assembled WGSL source.`); + } + throw new Error(`Unresolved @binding(auto) remained in assembled WGSL source near "${formatWGSLSourceSnippet(unresolvedBinding.match)}".`); + } + function formatWGSLBindingAssignmentComments(bindingAssignments) { + if (bindingAssignments.length === 0) { + return ""; + } + let source3 = "// ----- MODULE WGSL BINDING ASSIGNMENTS ---------------\n"; + for (const bindingAssignment of bindingAssignments) { + source3 += `// ${bindingAssignment.moduleName}.${bindingAssignment.name} -> @group(${bindingAssignment.group}) @binding(${bindingAssignment.location}) +`; + } + source3 += "\n"; + return source3; + } + function getBindingRegistryKey(group2, moduleName, bindingName) { + return `${group2}:${moduleName}:${bindingName}`; + } + function getWGSLModuleNameAtIndex(source3, index2) { + const moduleHeaderRegex = /^\/\/ ----- MODULE ([^\n]+) ---------------$/gm; + let moduleName; + let match; + match = moduleHeaderRegex.exec(source3); + while (match && match.index <= index2) { + moduleName = match[1]; + match = moduleHeaderRegex.exec(source3); + } + return moduleName; + } + function isInApplicationWGSLSection(source3, index2) { + const injectionMarkerIndex = source3.indexOf(INJECT_SHADER_DECLARATIONS); + return injectionMarkerIndex >= 0 ? index2 > injectionMarkerIndex : true; + } + function formatWGSLSourceSnippet(source3) { + return source3.replace(/\s+/g, " ").trim(); + } + + // node_modules/@luma.gl/shadertools/dist/lib/preprocessor/preprocessor.js + var DEFINE_NAME_PATTERN = "([a-zA-Z_][a-zA-Z0-9_]*)"; + var IFDEF_REGEXP = new RegExp(`^\\s*\\#\\s*ifdef\\s*${DEFINE_NAME_PATTERN}\\s*$`); + var IFNDEF_REGEXP = new RegExp(`^\\s*\\#\\s*ifndef\\s*${DEFINE_NAME_PATTERN}\\s*(?:\\/\\/.*)?$`); + var ELSE_REGEXP = /^\s*\#\s*else\s*(?:\/\/.*)?$/; + var ENDIF_REGEXP = /^\s*\#\s*endif\s*$/; + var IFDEF_WITH_COMMENT_REGEXP = new RegExp(`^\\s*\\#\\s*ifdef\\s*${DEFINE_NAME_PATTERN}\\s*(?:\\/\\/.*)?$`); + var ENDIF_WITH_COMMENT_REGEXP = /^\s*\#\s*endif\s*(?:\/\/.*)?$/; + function preprocess(source3, options) { + const lines = source3.split("\n"); + const output = []; + const conditionalStack = []; + let conditional = true; + for (const line of lines) { + const matchIf = line.match(IFDEF_WITH_COMMENT_REGEXP) || line.match(IFDEF_REGEXP); + const matchIfNot = line.match(IFNDEF_REGEXP); + const matchElse = line.match(ELSE_REGEXP); + const matchEnd = line.match(ENDIF_WITH_COMMENT_REGEXP) || line.match(ENDIF_REGEXP); + if (matchIf || matchIfNot) { + const defineName = (matchIf || matchIfNot)?.[1]; + const defineValue = Boolean(options?.defines?.[defineName]); + const branchTaken = matchIf ? defineValue : !defineValue; + const active = conditional && branchTaken; + conditionalStack.push({ parentActive: conditional, branchTaken, active }); + conditional = active; + } else if (matchElse) { + const currentConditional = conditionalStack[conditionalStack.length - 1]; + if (!currentConditional) { + throw new Error("Encountered #else without matching #ifdef or #ifndef"); + } + currentConditional.active = currentConditional.parentActive && !currentConditional.branchTaken; + currentConditional.branchTaken = true; + conditional = currentConditional.active; + } else if (matchEnd) { + conditionalStack.pop(); + conditional = conditionalStack.length ? conditionalStack[conditionalStack.length - 1].active : true; + } else if (conditional) { + output.push(line); + } + } + if (conditionalStack.length > 0) { + throw new Error("Unterminated conditional block in shader source"); + } + return output.join("\n"); + } + + // node_modules/@luma.gl/shadertools/dist/lib/shader-assembler.js + var ShaderAssembler = class _ShaderAssembler { + /** Default ShaderAssembler instance */ + static defaultShaderAssembler; + /** Hook functions */ + _hookFunctions = []; + /** Shader modules */ + _defaultModules = []; + /** Stable per-run WGSL auto-binding assignments keyed by group/module/binding. */ + _wgslBindingRegistry = /* @__PURE__ */ new Map(); + /** + * A default shader assembler instance - the natural place to register default modules and hooks + * @returns + */ + static getDefaultShaderAssembler() { + _ShaderAssembler.defaultShaderAssembler = _ShaderAssembler.defaultShaderAssembler || new _ShaderAssembler(); + return _ShaderAssembler.defaultShaderAssembler; + } + /** + * Add a default module that does not have to be provided with every call to assembleShaders() + */ + addDefaultModule(module) { + if (!this._defaultModules.find((m) => m.name === (typeof module === "string" ? module : module.name))) { + this._defaultModules.push(module); + } + } + /** + * Remove a default module + */ + removeDefaultModule(module) { + const moduleName = typeof module === "string" ? module : module.name; + this._defaultModules = this._defaultModules.filter((m) => m.name !== moduleName); + } + /** + * Register a shader hook + * @param hook + * @param opts + */ + addShaderHook(hook, opts) { + if (opts) { + hook = Object.assign(opts, { hook }); + } + this._hookFunctions.push(hook); + } + /** + * Assemble a WGSL unified shader + * @param platformInfo + * @param props + * @returns + */ + assembleWGSLShader(props) { + const modules = this._getModuleList(props.modules); + const hookFunctions = this._hookFunctions; + const { source: source3, getUniforms: getUniforms3, bindingAssignments } = assembleWGSLShader({ + ...props, + // @ts-expect-error + source: props.source, + _bindingRegistry: this._wgslBindingRegistry, + modules, + hookFunctions + }); + const defines2 = { + ...modules.reduce((accumulator, module) => { + Object.assign(accumulator, module.defines); + return accumulator; + }, {}), + ...props.defines + }; + const preprocessedSource = props.platformInfo.shaderLanguage === "wgsl" ? preprocess(source3, { defines: defines2 }) : source3; + return { + source: preprocessedSource, + getUniforms: getUniforms3, + modules, + bindingAssignments, + bindingTable: getShaderBindingDebugRowsFromWGSL(preprocessedSource, bindingAssignments) + }; + } + /** + * Assemble a pair of shaders into a single shader program + * @param platformInfo + * @param props + * @returns + */ + assembleGLSLShaderPair(props) { + const modules = this._getModuleList(props.modules); + const hookFunctions = this._hookFunctions; + const assembled = assembleGLSLShaderPair({ + ...props, + // @ts-expect-error + vs: props.vs, + // @ts-expect-error + fs: props.fs, + modules, + hookFunctions + }); + return { ...assembled, modules }; + } + /** + * Dedupe and combine with default modules + */ + _getModuleList(appModules = []) { + const modules = new Array(this._defaultModules.length + appModules.length); + const seen = {}; + let count2 = 0; + for (let i = 0, len4 = this._defaultModules.length; i < len4; ++i) { + const module = this._defaultModules[i]; + const name2 = module.name; + modules[count2++] = module; + seen[name2] = true; + } + for (let i = 0, len4 = appModules.length; i < len4; ++i) { + const module = appModules[i]; + const name2 = module.name; + if (!seen[name2]) { + modules[count2++] = module; + seen[name2] = true; + } + } + modules.length = count2; + initializeShaderModules(modules); + return modules; + } + }; + + // node_modules/@luma.gl/shadertools/dist/lib/glsl-utils/shader-utils.js + var FS_GLES = ( + /* glsl */ + `out vec4 transform_output; +void main() { + transform_output = vec4(0); +}` + ); + var FS300 = `#version 300 es +${FS_GLES}`; + function getPassthroughFS(options) { + const { input, inputChannels, output } = options || {}; + if (!input) { + return FS300; + } + if (!inputChannels) { + throw new Error("inputChannels"); + } + const inputType = channelCountToType(inputChannels); + const outputValue = convertToVec4(input, inputChannels); + return `#version 300 es +in ${inputType} ${input}; +out vec4 ${output}; +void main() { + ${output} = ${outputValue}; +}`; + } + function channelCountToType(channels) { + switch (channels) { + case 1: + return "float"; + case 2: + return "vec2"; + case 3: + return "vec3"; + case 4: + return "vec4"; + default: + throw new Error(`invalid channels: ${channels}`); + } + } + function convertToVec4(variable, channels) { + switch (channels) { + case 1: + return `vec4(${variable}, 0.0, 0.0, 1.0)`; + case 2: + return `vec4(${variable}, 0.0, 1.0)`; + case 3: + return `vec4(${variable}, 1.0)`; + case 4: + return variable; + default: + throw new Error(`invalid channels: ${channels}`); + } + } + + // node_modules/@math.gl/core/dist/lib/common.js + var RADIANS_TO_DEGREES = 1 / Math.PI * 180; + var DEGREES_TO_RADIANS = 1 / 180 * Math.PI; + var DEFAULT_CONFIG = { + EPSILON: 1e-12, + debug: false, + precision: 4, + printTypes: false, + printDegrees: false, + printRowMajor: true, + _cartographicRadians: false + }; + globalThis.mathgl = globalThis.mathgl || { config: { ...DEFAULT_CONFIG } }; + var config = globalThis.mathgl.config; + function formatValue(value, { precision = config.precision } = {}) { + value = round(value); + return `${parseFloat(value.toPrecision(precision))}`; + } + function isArray(value) { + return Array.isArray(value) || ArrayBuffer.isView(value) && !(value instanceof DataView); + } + function clamp(value, min5, max4) { + return map(value, (value2) => Math.max(min5, Math.min(max4, value2))); + } + function lerp(a, b, t) { + if (isArray(a)) { + return a.map((ai, i) => lerp(ai, b[i], t)); + } + return t * b + (1 - t) * a; + } + function equals(a, b, epsilon2) { + const oldEpsilon = config.EPSILON; + if (epsilon2) { + config.EPSILON = epsilon2; + } + try { + if (a === b) { + return true; + } + if (isArray(a) && isArray(b)) { + if (a.length !== b.length) { + return false; + } + for (let i = 0; i < a.length; ++i) { + if (!equals(a[i], b[i])) { + return false; + } + } + return true; + } + if (a && a.equals) { + return a.equals(b); + } + if (b && b.equals) { + return b.equals(a); + } + if (typeof a === "number" && typeof b === "number") { + return Math.abs(a - b) <= config.EPSILON * Math.max(1, Math.abs(a), Math.abs(b)); + } + return false; + } finally { + config.EPSILON = oldEpsilon; + } + } + function round(value) { + return Math.round(value / config.EPSILON) * config.EPSILON; + } + function duplicateArray(array) { + return array.clone ? array.clone() : new Array(array.length); + } + function map(value, func, result) { + if (isArray(value)) { + const array = value; + result = result || duplicateArray(array); + for (let i = 0; i < result.length && i < array.length; ++i) { + const val = typeof value === "number" ? value : value[i]; + result[i] = func(val, i, result); + } + return result; + } + return func(value); + } + + // node_modules/@math.gl/core/dist/classes/base/math-array.js + var MathArray = class extends Array { + // Common methods + /** + * Clone the current object + * @returns a new copy of this object + */ + clone() { + return new this.constructor().copy(this); + } + fromArray(array, offset = 0) { + for (let i = 0; i < this.ELEMENTS; ++i) { + this[i] = array[i + offset]; + } + return this.check(); + } + toArray(targetArray = [], offset = 0) { + for (let i = 0; i < this.ELEMENTS; ++i) { + targetArray[offset + i] = this[i]; + } + return targetArray; + } + toObject(targetObject) { + return targetObject; + } + from(arrayOrObject) { + return Array.isArray(arrayOrObject) ? this.copy(arrayOrObject) : ( + // @ts-ignore + this.fromObject(arrayOrObject) + ); + } + to(arrayOrObject) { + if (arrayOrObject === this) { + return this; + } + return isArray(arrayOrObject) ? this.toArray(arrayOrObject) : this.toObject(arrayOrObject); + } + toTarget(target2) { + return target2 ? this.to(target2) : this; + } + /** @deprecated */ + toFloat32Array() { + return new Float32Array(this); + } + toString() { + return this.formatString(config); + } + /** Formats string according to options */ + formatString(opts) { + let string = ""; + for (let i = 0; i < this.ELEMENTS; ++i) { + string += (i > 0 ? ", " : "") + formatValue(this[i], opts); + } + return `${opts.printTypes ? this.constructor.name : ""}[${string}]`; + } + equals(array) { + if (!array || this.length !== array.length) { + return false; + } + for (let i = 0; i < this.ELEMENTS; ++i) { + if (!equals(this[i], array[i])) { + return false; + } + } + return true; + } + exactEquals(array) { + if (!array || this.length !== array.length) { + return false; + } + for (let i = 0; i < this.ELEMENTS; ++i) { + if (this[i] !== array[i]) { + return false; + } + } + return true; + } + // Modifiers + /** Negates all values in this object */ + negate() { + for (let i = 0; i < this.ELEMENTS; ++i) { + this[i] = -this[i]; + } + return this.check(); + } + lerp(a, b, t) { + if (t === void 0) { + return this.lerp(this, a, b); + } + for (let i = 0; i < this.ELEMENTS; ++i) { + const ai = a[i]; + const endValue = typeof b === "number" ? b : b[i]; + this[i] = ai + t * (endValue - ai); + } + return this.check(); + } + /** Minimal */ + min(vector) { + for (let i = 0; i < this.ELEMENTS; ++i) { + this[i] = Math.min(vector[i], this[i]); + } + return this.check(); + } + /** Maximal */ + max(vector) { + for (let i = 0; i < this.ELEMENTS; ++i) { + this[i] = Math.max(vector[i], this[i]); + } + return this.check(); + } + clamp(minVector, maxVector) { + for (let i = 0; i < this.ELEMENTS; ++i) { + this[i] = Math.min(Math.max(this[i], minVector[i]), maxVector[i]); + } + return this.check(); + } + add(...vectors) { + for (const vector of vectors) { + for (let i = 0; i < this.ELEMENTS; ++i) { + this[i] += vector[i]; + } + } + return this.check(); + } + subtract(...vectors) { + for (const vector of vectors) { + for (let i = 0; i < this.ELEMENTS; ++i) { + this[i] -= vector[i]; + } + } + return this.check(); + } + scale(scale5) { + if (typeof scale5 === "number") { + for (let i = 0; i < this.ELEMENTS; ++i) { + this[i] *= scale5; + } + } else { + for (let i = 0; i < this.ELEMENTS && i < scale5.length; ++i) { + this[i] *= scale5[i]; + } + } + return this.check(); + } + /** + * Multiplies all elements by `scale` + * Note: `Matrix4.multiplyByScalar` only scales its 3x3 "minor" + */ + multiplyByScalar(scalar) { + for (let i = 0; i < this.ELEMENTS; ++i) { + this[i] *= scalar; + } + return this.check(); + } + // Debug checks + /** Throws an error if array length is incorrect or contains illegal values */ + check() { + if (config.debug && !this.validate()) { + throw new Error(`math.gl: ${this.constructor.name} some fields set to invalid numbers'`); + } + return this; + } + /** Returns false if the array length is incorrect or contains illegal values */ + validate() { + let valid = this.length === this.ELEMENTS; + for (let i = 0; i < this.ELEMENTS; ++i) { + valid = valid && Number.isFinite(this[i]); + } + return valid; + } + // three.js compatibility + /** @deprecated */ + sub(a) { + return this.subtract(a); + } + /** @deprecated */ + setScalar(a) { + for (let i = 0; i < this.ELEMENTS; ++i) { + this[i] = a; + } + return this.check(); + } + /** @deprecated */ + addScalar(a) { + for (let i = 0; i < this.ELEMENTS; ++i) { + this[i] += a; + } + return this.check(); + } + /** @deprecated */ + subScalar(a) { + return this.addScalar(-a); + } + /** @deprecated */ + multiplyScalar(scalar) { + for (let i = 0; i < this.ELEMENTS; ++i) { + this[i] *= scalar; + } + return this.check(); + } + /** @deprecated */ + divideScalar(a) { + return this.multiplyByScalar(1 / a); + } + /** @deprecated */ + clampScalar(min5, max4) { + for (let i = 0; i < this.ELEMENTS; ++i) { + this[i] = Math.min(Math.max(this[i], min5), max4); + } + return this.check(); + } + /** @deprecated */ + get elements() { + return this; + } + }; + + // node_modules/@math.gl/core/dist/lib/validators.js + function validateVector(v, length4) { + if (v.length !== length4) { + return false; + } + for (let i = 0; i < v.length; ++i) { + if (!Number.isFinite(v[i])) { + return false; + } + } + return true; + } + function checkNumber(value) { + if (!Number.isFinite(value)) { + throw new Error(`Invalid number ${JSON.stringify(value)}`); + } + return value; + } + function checkVector(v, length4, callerName = "") { + if (config.debug && !validateVector(v, length4)) { + throw new Error(`math.gl: ${callerName} some fields set to invalid numbers'`); + } + return v; + } + + // node_modules/@math.gl/core/dist/lib/assert.js + function assert5(condition, message2) { + if (!condition) { + throw new Error(`math.gl assertion ${message2}`); + } + } + + // node_modules/@math.gl/core/dist/classes/base/vector.js + var Vector = class extends MathArray { + // ACCESSORS + get x() { + return this[0]; + } + set x(value) { + this[0] = checkNumber(value); + } + get y() { + return this[1]; + } + set y(value) { + this[1] = checkNumber(value); + } + /** + * Returns the length of the vector from the origin to the point described by this vector + * + * @note `length` is a reserved word for Arrays, so `v.length()` will return number of elements + * Instead we provide `len` and `magnitude` + */ + len() { + return Math.sqrt(this.lengthSquared()); + } + /** + * Returns the length of the vector from the origin to the point described by this vector + */ + magnitude() { + return this.len(); + } + /** + * Returns the squared length of the vector from the origin to the point described by this vector + */ + lengthSquared() { + let length4 = 0; + for (let i = 0; i < this.ELEMENTS; ++i) { + length4 += this[i] * this[i]; + } + return length4; + } + /** + * Returns the squared length of the vector from the origin to the point described by this vector + */ + magnitudeSquared() { + return this.lengthSquared(); + } + distance(mathArray) { + return Math.sqrt(this.distanceSquared(mathArray)); + } + distanceSquared(mathArray) { + let length4 = 0; + for (let i = 0; i < this.ELEMENTS; ++i) { + const dist4 = this[i] - mathArray[i]; + length4 += dist4 * dist4; + } + return checkNumber(length4); + } + dot(mathArray) { + let product = 0; + for (let i = 0; i < this.ELEMENTS; ++i) { + product += this[i] * mathArray[i]; + } + return checkNumber(product); + } + // MODIFIERS + normalize() { + const length4 = this.magnitude(); + if (length4 !== 0) { + for (let i = 0; i < this.ELEMENTS; ++i) { + this[i] /= length4; + } + } + return this.check(); + } + multiply(...vectors) { + for (const vector of vectors) { + for (let i = 0; i < this.ELEMENTS; ++i) { + this[i] *= vector[i]; + } + } + return this.check(); + } + divide(...vectors) { + for (const vector of vectors) { + for (let i = 0; i < this.ELEMENTS; ++i) { + this[i] /= vector[i]; + } + } + return this.check(); + } + // THREE.js compatibility + lengthSq() { + return this.lengthSquared(); + } + distanceTo(vector) { + return this.distance(vector); + } + distanceToSquared(vector) { + return this.distanceSquared(vector); + } + getComponent(i) { + assert5(i >= 0 && i < this.ELEMENTS, "index is out of range"); + return checkNumber(this[i]); + } + setComponent(i, value) { + assert5(i >= 0 && i < this.ELEMENTS, "index is out of range"); + this[i] = value; + return this.check(); + } + addVectors(a, b) { + return this.copy(a).add(b); + } + subVectors(a, b) { + return this.copy(a).subtract(b); + } + multiplyVectors(a, b) { + return this.copy(a).multiply(b); + } + addScaledVector(a, b) { + return this.add(new this.constructor(a).multiplyScalar(b)); + } + }; + + // node_modules/@math.gl/core/dist/gl-matrix/vec2.js + var vec2_exports = {}; + __export(vec2_exports, { + add: () => add, + angle: () => angle, + ceil: () => ceil, + clone: () => clone, + copy: () => copy, + create: () => create, + cross: () => cross, + dist: () => dist, + distance: () => distance, + div: () => div, + divide: () => divide, + dot: () => dot, + equals: () => equals2, + exactEquals: () => exactEquals, + floor: () => floor, + forEach: () => forEach2, + fromValues: () => fromValues, + inverse: () => inverse, + len: () => len, + length: () => length, + lerp: () => lerp2, + max: () => max, + min: () => min, + mul: () => mul, + multiply: () => multiply, + negate: () => negate, + normalize: () => normalize, + random: () => random, + rotate: () => rotate, + round: () => round3, + scale: () => scale, + scaleAndAdd: () => scaleAndAdd, + set: () => set, + sqrDist: () => sqrDist, + sqrLen: () => sqrLen, + squaredDistance: () => squaredDistance, + squaredLength: () => squaredLength, + str: () => str, + sub: () => sub, + subtract: () => subtract, + transformMat2: () => transformMat2, + transformMat2d: () => transformMat2d, + transformMat3: () => transformMat3, + transformMat4: () => transformMat4, + zero: () => zero + }); + + // node_modules/@math.gl/core/dist/gl-matrix/common.js + var EPSILON = 1e-6; + var ARRAY_TYPE = typeof Float32Array !== "undefined" ? Float32Array : Array; + var RANDOM = Math.random; + function round2(a) { + if (a >= 0) + return Math.round(a); + return a % 0.5 === 0 ? Math.floor(a) : Math.round(a); + } + var degree = Math.PI / 180; + + // node_modules/@math.gl/core/dist/gl-matrix/vec2.js + function create() { + const out = new ARRAY_TYPE(2); + if (ARRAY_TYPE != Float32Array) { + out[0] = 0; + out[1] = 0; + } + return out; + } + function clone(a) { + const out = new ARRAY_TYPE(2); + out[0] = a[0]; + out[1] = a[1]; + return out; + } + function fromValues(x, y) { + const out = new ARRAY_TYPE(2); + out[0] = x; + out[1] = y; + return out; + } + function copy(out, a) { + out[0] = a[0]; + out[1] = a[1]; + return out; + } + function set(out, x, y) { + out[0] = x; + out[1] = y; + return out; + } + function add(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + return out; + } + function subtract(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + return out; + } + function multiply(out, a, b) { + out[0] = a[0] * b[0]; + out[1] = a[1] * b[1]; + return out; + } + function divide(out, a, b) { + out[0] = a[0] / b[0]; + out[1] = a[1] / b[1]; + return out; + } + function ceil(out, a) { + out[0] = Math.ceil(a[0]); + out[1] = Math.ceil(a[1]); + return out; + } + function floor(out, a) { + out[0] = Math.floor(a[0]); + out[1] = Math.floor(a[1]); + return out; + } + function min(out, a, b) { + out[0] = Math.min(a[0], b[0]); + out[1] = Math.min(a[1], b[1]); + return out; + } + function max(out, a, b) { + out[0] = Math.max(a[0], b[0]); + out[1] = Math.max(a[1], b[1]); + return out; + } + function round3(out, a) { + out[0] = round2(a[0]); + out[1] = round2(a[1]); + return out; + } + function scale(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + return out; + } + function scaleAndAdd(out, a, b, scale5) { + out[0] = a[0] + b[0] * scale5; + out[1] = a[1] + b[1] * scale5; + return out; + } + function distance(a, b) { + const x = b[0] - a[0]; + const y = b[1] - a[1]; + return Math.sqrt(x * x + y * y); + } + function squaredDistance(a, b) { + const x = b[0] - a[0]; + const y = b[1] - a[1]; + return x * x + y * y; + } + function length(a) { + const x = a[0]; + const y = a[1]; + return Math.sqrt(x * x + y * y); + } + function squaredLength(a) { + const x = a[0]; + const y = a[1]; + return x * x + y * y; + } + function negate(out, a) { + out[0] = -a[0]; + out[1] = -a[1]; + return out; + } + function inverse(out, a) { + out[0] = 1 / a[0]; + out[1] = 1 / a[1]; + return out; + } + function normalize(out, a) { + const x = a[0]; + const y = a[1]; + let len4 = x * x + y * y; + if (len4 > 0) { + len4 = 1 / Math.sqrt(len4); + } + out[0] = a[0] * len4; + out[1] = a[1] * len4; + return out; + } + function dot(a, b) { + return a[0] * b[0] + a[1] * b[1]; + } + function cross(out, a, b) { + const z = a[0] * b[1] - a[1] * b[0]; + out[0] = out[1] = 0; + out[2] = z; + return out; + } + function lerp2(out, a, b, t) { + const ax = a[0]; + const ay = a[1]; + out[0] = ax + t * (b[0] - ax); + out[1] = ay + t * (b[1] - ay); + return out; + } + function random(out, scale5) { + scale5 = scale5 === void 0 ? 1 : scale5; + const r = RANDOM() * 2 * Math.PI; + out[0] = Math.cos(r) * scale5; + out[1] = Math.sin(r) * scale5; + return out; + } + function transformMat2(out, a, m) { + const x = a[0]; + const y = a[1]; + out[0] = m[0] * x + m[2] * y; + out[1] = m[1] * x + m[3] * y; + return out; + } + function transformMat2d(out, a, m) { + const x = a[0]; + const y = a[1]; + out[0] = m[0] * x + m[2] * y + m[4]; + out[1] = m[1] * x + m[3] * y + m[5]; + return out; + } + function transformMat3(out, a, m) { + const x = a[0]; + const y = a[1]; + out[0] = m[0] * x + m[3] * y + m[6]; + out[1] = m[1] * x + m[4] * y + m[7]; + return out; + } + function transformMat4(out, a, m) { + const x = a[0]; + const y = a[1]; + out[0] = m[0] * x + m[4] * y + m[12]; + out[1] = m[1] * x + m[5] * y + m[13]; + return out; + } + function rotate(out, a, b, rad) { + const p02 = a[0] - b[0]; + const p1 = a[1] - b[1]; + const sinC = Math.sin(rad); + const cosC = Math.cos(rad); + out[0] = p02 * cosC - p1 * sinC + b[0]; + out[1] = p02 * sinC + p1 * cosC + b[1]; + return out; + } + function angle(a, b) { + const x1 = a[0]; + const y1 = a[1]; + const x2 = b[0]; + const y2 = b[1]; + const mag = Math.sqrt((x1 * x1 + y1 * y1) * (x2 * x2 + y2 * y2)); + const cosine = mag && (x1 * x2 + y1 * y2) / mag; + return Math.acos(Math.min(Math.max(cosine, -1), 1)); + } + function zero(out) { + out[0] = 0; + out[1] = 0; + return out; + } + function str(a) { + return `vec2(${a[0]}, ${a[1]})`; + } + function exactEquals(a, b) { + return a[0] === b[0] && a[1] === b[1]; + } + function equals2(a, b) { + const a0 = a[0]; + const a1 = a[1]; + const b0 = b[0]; + const b1 = b[1]; + return Math.abs(a0 - b0) <= EPSILON * Math.max(1, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1, Math.abs(a1), Math.abs(b1)); + } + var len = length; + var sub = subtract; + var mul = multiply; + var div = divide; + var dist = distance; + var sqrDist = squaredDistance; + var sqrLen = squaredLength; + var forEach2 = (function() { + const vec = create(); + return function(a, stride, offset, count2, fn, arg) { + let i; + let l; + if (!stride) { + stride = 2; + } + if (!offset) { + offset = 0; + } + if (count2) { + l = Math.min(count2 * stride + offset, a.length); + } else { + l = a.length; + } + for (i = offset; i < l; i += stride) { + vec[0] = a[i]; + vec[1] = a[i + 1]; + fn(vec, vec, arg); + a[i] = vec[0]; + a[i + 1] = vec[1]; + } + return a; + }; + })(); + + // node_modules/@math.gl/core/dist/lib/gl-matrix-extras.js + function vec2_transformMat4AsVector(out, a, m) { + const x = a[0]; + const y = a[1]; + const w = m[3] * x + m[7] * y || 1; + out[0] = (m[0] * x + m[4] * y) / w; + out[1] = (m[1] * x + m[5] * y) / w; + return out; + } + function vec3_transformMat4AsVector(out, a, m) { + const x = a[0]; + const y = a[1]; + const z = a[2]; + const w = m[3] * x + m[7] * y + m[11] * z || 1; + out[0] = (m[0] * x + m[4] * y + m[8] * z) / w; + out[1] = (m[1] * x + m[5] * y + m[9] * z) / w; + out[2] = (m[2] * x + m[6] * y + m[10] * z) / w; + return out; + } + function vec3_transformMat2(out, a, m) { + const x = a[0]; + const y = a[1]; + out[0] = m[0] * x + m[2] * y; + out[1] = m[1] * x + m[3] * y; + out[2] = a[2]; + return out; + } + + // node_modules/@math.gl/core/dist/gl-matrix/vec3.js + var vec3_exports = {}; + __export(vec3_exports, { + add: () => add2, + angle: () => angle2, + bezier: () => bezier, + ceil: () => ceil2, + clone: () => clone2, + copy: () => copy2, + create: () => create2, + cross: () => cross2, + dist: () => dist2, + distance: () => distance2, + div: () => div2, + divide: () => divide2, + dot: () => dot2, + equals: () => equals3, + exactEquals: () => exactEquals2, + floor: () => floor2, + forEach: () => forEach3, + fromValues: () => fromValues2, + hermite: () => hermite, + inverse: () => inverse2, + len: () => len2, + length: () => length2, + lerp: () => lerp3, + max: () => max2, + min: () => min2, + mul: () => mul2, + multiply: () => multiply2, + negate: () => negate2, + normalize: () => normalize2, + random: () => random2, + rotateX: () => rotateX, + rotateY: () => rotateY, + rotateZ: () => rotateZ, + round: () => round4, + scale: () => scale2, + scaleAndAdd: () => scaleAndAdd2, + set: () => set2, + slerp: () => slerp, + sqrDist: () => sqrDist2, + sqrLen: () => sqrLen2, + squaredDistance: () => squaredDistance2, + squaredLength: () => squaredLength2, + str: () => str2, + sub: () => sub2, + subtract: () => subtract2, + transformMat3: () => transformMat32, + transformMat4: () => transformMat42, + transformQuat: () => transformQuat, + zero: () => zero2 + }); + function create2() { + const out = new ARRAY_TYPE(3); + if (ARRAY_TYPE != Float32Array) { + out[0] = 0; + out[1] = 0; + out[2] = 0; + } + return out; + } + function clone2(a) { + const out = new ARRAY_TYPE(3); + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + return out; + } + function length2(a) { + const x = a[0]; + const y = a[1]; + const z = a[2]; + return Math.sqrt(x * x + y * y + z * z); + } + function fromValues2(x, y, z) { + const out = new ARRAY_TYPE(3); + out[0] = x; + out[1] = y; + out[2] = z; + return out; + } + function copy2(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + return out; + } + function set2(out, x, y, z) { + out[0] = x; + out[1] = y; + out[2] = z; + return out; + } + function add2(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + out[2] = a[2] + b[2]; + return out; + } + function subtract2(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + out[2] = a[2] - b[2]; + return out; + } + function multiply2(out, a, b) { + out[0] = a[0] * b[0]; + out[1] = a[1] * b[1]; + out[2] = a[2] * b[2]; + return out; + } + function divide2(out, a, b) { + out[0] = a[0] / b[0]; + out[1] = a[1] / b[1]; + out[2] = a[2] / b[2]; + return out; + } + function ceil2(out, a) { + out[0] = Math.ceil(a[0]); + out[1] = Math.ceil(a[1]); + out[2] = Math.ceil(a[2]); + return out; + } + function floor2(out, a) { + out[0] = Math.floor(a[0]); + out[1] = Math.floor(a[1]); + out[2] = Math.floor(a[2]); + return out; + } + function min2(out, a, b) { + out[0] = Math.min(a[0], b[0]); + out[1] = Math.min(a[1], b[1]); + out[2] = Math.min(a[2], b[2]); + return out; + } + function max2(out, a, b) { + out[0] = Math.max(a[0], b[0]); + out[1] = Math.max(a[1], b[1]); + out[2] = Math.max(a[2], b[2]); + return out; + } + function round4(out, a) { + out[0] = round2(a[0]); + out[1] = round2(a[1]); + out[2] = round2(a[2]); + return out; + } + function scale2(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + out[2] = a[2] * b; + return out; + } + function scaleAndAdd2(out, a, b, scale5) { + out[0] = a[0] + b[0] * scale5; + out[1] = a[1] + b[1] * scale5; + out[2] = a[2] + b[2] * scale5; + return out; + } + function distance2(a, b) { + const x = b[0] - a[0]; + const y = b[1] - a[1]; + const z = b[2] - a[2]; + return Math.sqrt(x * x + y * y + z * z); + } + function squaredDistance2(a, b) { + const x = b[0] - a[0]; + const y = b[1] - a[1]; + const z = b[2] - a[2]; + return x * x + y * y + z * z; + } + function squaredLength2(a) { + const x = a[0]; + const y = a[1]; + const z = a[2]; + return x * x + y * y + z * z; + } + function negate2(out, a) { + out[0] = -a[0]; + out[1] = -a[1]; + out[2] = -a[2]; + return out; + } + function inverse2(out, a) { + out[0] = 1 / a[0]; + out[1] = 1 / a[1]; + out[2] = 1 / a[2]; + return out; + } + function normalize2(out, a) { + const x = a[0]; + const y = a[1]; + const z = a[2]; + let len4 = x * x + y * y + z * z; + if (len4 > 0) { + len4 = 1 / Math.sqrt(len4); + } + out[0] = a[0] * len4; + out[1] = a[1] * len4; + out[2] = a[2] * len4; + return out; + } + function dot2(a, b) { + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; + } + function cross2(out, a, b) { + const ax = a[0]; + const ay = a[1]; + const az = a[2]; + const bx = b[0]; + const by = b[1]; + const bz = b[2]; + out[0] = ay * bz - az * by; + out[1] = az * bx - ax * bz; + out[2] = ax * by - ay * bx; + return out; + } + function lerp3(out, a, b, t) { + const ax = a[0]; + const ay = a[1]; + const az = a[2]; + out[0] = ax + t * (b[0] - ax); + out[1] = ay + t * (b[1] - ay); + out[2] = az + t * (b[2] - az); + return out; + } + function slerp(out, a, b, t) { + const angle4 = Math.acos(Math.min(Math.max(dot2(a, b), -1), 1)); + const sinTotal = Math.sin(angle4); + const ratioA = Math.sin((1 - t) * angle4) / sinTotal; + const ratioB = Math.sin(t * angle4) / sinTotal; + out[0] = ratioA * a[0] + ratioB * b[0]; + out[1] = ratioA * a[1] + ratioB * b[1]; + out[2] = ratioA * a[2] + ratioB * b[2]; + return out; + } + function hermite(out, a, b, c2, d, t) { + const factorTimes2 = t * t; + const factor1 = factorTimes2 * (2 * t - 3) + 1; + const factor2 = factorTimes2 * (t - 2) + t; + const factor3 = factorTimes2 * (t - 1); + const factor4 = factorTimes2 * (3 - 2 * t); + out[0] = a[0] * factor1 + b[0] * factor2 + c2[0] * factor3 + d[0] * factor4; + out[1] = a[1] * factor1 + b[1] * factor2 + c2[1] * factor3 + d[1] * factor4; + out[2] = a[2] * factor1 + b[2] * factor2 + c2[2] * factor3 + d[2] * factor4; + return out; + } + function bezier(out, a, b, c2, d, t) { + const inverseFactor = 1 - t; + const inverseFactorTimesTwo = inverseFactor * inverseFactor; + const factorTimes2 = t * t; + const factor1 = inverseFactorTimesTwo * inverseFactor; + const factor2 = 3 * t * inverseFactorTimesTwo; + const factor3 = 3 * factorTimes2 * inverseFactor; + const factor4 = factorTimes2 * t; + out[0] = a[0] * factor1 + b[0] * factor2 + c2[0] * factor3 + d[0] * factor4; + out[1] = a[1] * factor1 + b[1] * factor2 + c2[1] * factor3 + d[1] * factor4; + out[2] = a[2] * factor1 + b[2] * factor2 + c2[2] * factor3 + d[2] * factor4; + return out; + } + function random2(out, scale5) { + scale5 = scale5 === void 0 ? 1 : scale5; + const r = RANDOM() * 2 * Math.PI; + const z = RANDOM() * 2 - 1; + const zScale = Math.sqrt(1 - z * z) * scale5; + out[0] = Math.cos(r) * zScale; + out[1] = Math.sin(r) * zScale; + out[2] = z * scale5; + return out; + } + function transformMat42(out, a, m) { + const x = a[0]; + const y = a[1]; + const z = a[2]; + let w = m[3] * x + m[7] * y + m[11] * z + m[15]; + w = w || 1; + out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w; + out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w; + out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w; + return out; + } + function transformMat32(out, a, m) { + const x = a[0]; + const y = a[1]; + const z = a[2]; + out[0] = x * m[0] + y * m[3] + z * m[6]; + out[1] = x * m[1] + y * m[4] + z * m[7]; + out[2] = x * m[2] + y * m[5] + z * m[8]; + return out; + } + function transformQuat(out, a, q) { + const qx = q[0]; + const qy = q[1]; + const qz = q[2]; + const qw = q[3]; + const x = a[0]; + const y = a[1]; + const z = a[2]; + let uvx = qy * z - qz * y; + let uvy = qz * x - qx * z; + let uvz = qx * y - qy * x; + let uuvx = qy * uvz - qz * uvy; + let uuvy = qz * uvx - qx * uvz; + let uuvz = qx * uvy - qy * uvx; + const w2 = qw * 2; + uvx *= w2; + uvy *= w2; + uvz *= w2; + uuvx *= 2; + uuvy *= 2; + uuvz *= 2; + out[0] = x + uvx + uuvx; + out[1] = y + uvy + uuvy; + out[2] = z + uvz + uuvz; + return out; + } + function rotateX(out, a, b, rad) { + const p = []; + const r = []; + p[0] = a[0] - b[0]; + p[1] = a[1] - b[1]; + p[2] = a[2] - b[2]; + r[0] = p[0]; + r[1] = p[1] * Math.cos(rad) - p[2] * Math.sin(rad); + r[2] = p[1] * Math.sin(rad) + p[2] * Math.cos(rad); + out[0] = r[0] + b[0]; + out[1] = r[1] + b[1]; + out[2] = r[2] + b[2]; + return out; + } + function rotateY(out, a, b, rad) { + const p = []; + const r = []; + p[0] = a[0] - b[0]; + p[1] = a[1] - b[1]; + p[2] = a[2] - b[2]; + r[0] = p[2] * Math.sin(rad) + p[0] * Math.cos(rad); + r[1] = p[1]; + r[2] = p[2] * Math.cos(rad) - p[0] * Math.sin(rad); + out[0] = r[0] + b[0]; + out[1] = r[1] + b[1]; + out[2] = r[2] + b[2]; + return out; + } + function rotateZ(out, a, b, rad) { + const p = []; + const r = []; + p[0] = a[0] - b[0]; + p[1] = a[1] - b[1]; + p[2] = a[2] - b[2]; + r[0] = p[0] * Math.cos(rad) - p[1] * Math.sin(rad); + r[1] = p[0] * Math.sin(rad) + p[1] * Math.cos(rad); + r[2] = p[2]; + out[0] = r[0] + b[0]; + out[1] = r[1] + b[1]; + out[2] = r[2] + b[2]; + return out; + } + function angle2(a, b) { + const ax = a[0]; + const ay = a[1]; + const az = a[2]; + const bx = b[0]; + const by = b[1]; + const bz = b[2]; + const mag = Math.sqrt((ax * ax + ay * ay + az * az) * (bx * bx + by * by + bz * bz)); + const cosine = mag && dot2(a, b) / mag; + return Math.acos(Math.min(Math.max(cosine, -1), 1)); + } + function zero2(out) { + out[0] = 0; + out[1] = 0; + out[2] = 0; + return out; + } + function str2(a) { + return `vec3(${a[0]}, ${a[1]}, ${a[2]})`; + } + function exactEquals2(a, b) { + return a[0] === b[0] && a[1] === b[1] && a[2] === b[2]; + } + function equals3(a, b) { + const a0 = a[0]; + const a1 = a[1]; + const a2 = a[2]; + const b0 = b[0]; + const b1 = b[1]; + const b2 = b[2]; + return Math.abs(a0 - b0) <= EPSILON * Math.max(1, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= EPSILON * Math.max(1, Math.abs(a2), Math.abs(b2)); + } + var sub2 = subtract2; + var mul2 = multiply2; + var div2 = divide2; + var dist2 = distance2; + var sqrDist2 = squaredDistance2; + var len2 = length2; + var sqrLen2 = squaredLength2; + var forEach3 = (function() { + const vec = create2(); + return function(a, stride, offset, count2, fn, arg) { + let i; + let l; + if (!stride) { + stride = 3; + } + if (!offset) { + offset = 0; + } + if (count2) { + l = Math.min(count2 * stride + offset, a.length); + } else { + l = a.length; + } + for (i = offset; i < l; i += stride) { + vec[0] = a[i]; + vec[1] = a[i + 1]; + vec[2] = a[i + 2]; + fn(vec, vec, arg); + a[i] = vec[0]; + a[i + 1] = vec[1]; + a[i + 2] = vec[2]; + } + return a; + }; + })(); + + // node_modules/@math.gl/core/dist/classes/vector3.js + var ORIGIN = [0, 0, 0]; + var ZERO; + var Vector3 = class _Vector3 extends Vector { + static get ZERO() { + if (!ZERO) { + ZERO = new _Vector3(0, 0, 0); + Object.freeze(ZERO); + } + return ZERO; + } + /** + * @class + * @param x + * @param y + * @param z + */ + constructor(x = 0, y = 0, z = 0) { + super(-0, -0, -0); + if (arguments.length === 1 && isArray(x)) { + this.copy(x); + } else { + if (config.debug) { + checkNumber(x); + checkNumber(y); + checkNumber(z); + } + this[0] = x; + this[1] = y; + this[2] = z; + } + } + set(x, y, z) { + this[0] = x; + this[1] = y; + this[2] = z; + return this.check(); + } + copy(array) { + this[0] = array[0]; + this[1] = array[1]; + this[2] = array[2]; + return this.check(); + } + fromObject(object) { + if (config.debug) { + checkNumber(object.x); + checkNumber(object.y); + checkNumber(object.z); + } + this[0] = object.x; + this[1] = object.y; + this[2] = object.z; + return this.check(); + } + toObject(object) { + object.x = this[0]; + object.y = this[1]; + object.z = this[2]; + return object; + } + // Getters/setters + get ELEMENTS() { + return 3; + } + get z() { + return this[2]; + } + set z(value) { + this[2] = checkNumber(value); + } + // ACCESSORS + angle(vector) { + return angle2(this, vector); + } + // MODIFIERS + cross(vector) { + cross2(this, this, vector); + return this.check(); + } + rotateX({ radians: radians4, origin = ORIGIN }) { + rotateX(this, this, origin, radians4); + return this.check(); + } + rotateY({ radians: radians4, origin = ORIGIN }) { + rotateY(this, this, origin, radians4); + return this.check(); + } + rotateZ({ radians: radians4, origin = ORIGIN }) { + rotateZ(this, this, origin, radians4); + return this.check(); + } + // Transforms + // transforms as point (4th component is implicitly 1) + transform(matrix4) { + return this.transformAsPoint(matrix4); + } + // transforms as point (4th component is implicitly 1) + transformAsPoint(matrix4) { + transformMat42(this, this, matrix4); + return this.check(); + } + // transforms as vector (4th component is implicitly 0, ignores translation. slightly faster) + transformAsVector(matrix4) { + vec3_transformMat4AsVector(this, this, matrix4); + return this.check(); + } + transformByMatrix3(matrix3) { + transformMat32(this, this, matrix3); + return this.check(); + } + transformByMatrix2(matrix2) { + vec3_transformMat2(this, this, matrix2); + return this.check(); + } + transformByQuaternion(quaternion) { + transformQuat(this, this, quaternion); + return this.check(); + } + }; + + // node_modules/@math.gl/core/dist/classes/base/matrix.js + var Matrix = class extends MathArray { + // fromObject(object) { + // const array = object.elements; + // return this.fromRowMajor(array); + // } + // toObject(object) { + // const array = object.elements; + // this.toRowMajor(array); + // return object; + // } + // TODO better override formatString? + toString() { + let string = "["; + if (config.printRowMajor) { + string += "row-major:"; + for (let row = 0; row < this.RANK; ++row) { + for (let col = 0; col < this.RANK; ++col) { + string += ` ${this[col * this.RANK + row]}`; + } + } + } else { + string += "column-major:"; + for (let i = 0; i < this.ELEMENTS; ++i) { + string += ` ${this[i]}`; + } + } + string += "]"; + return string; + } + getElementIndex(row, col) { + return col * this.RANK + row; + } + // By default assumes row major indices + getElement(row, col) { + return this[col * this.RANK + row]; + } + // By default assumes row major indices + setElement(row, col, value) { + this[col * this.RANK + row] = checkNumber(value); + return this; + } + getColumn(columnIndex, result = new Array(this.RANK).fill(-0)) { + const firstIndex = columnIndex * this.RANK; + for (let i = 0; i < this.RANK; ++i) { + result[i] = this[firstIndex + i]; + } + return result; + } + setColumn(columnIndex, columnVector) { + const firstIndex = columnIndex * this.RANK; + for (let i = 0; i < this.RANK; ++i) { + this[firstIndex + i] = columnVector[i]; + } + return this; + } + }; + + // node_modules/@math.gl/core/dist/gl-matrix/mat4.js + var mat4_exports = {}; + __export(mat4_exports, { + add: () => add3, + adjoint: () => adjoint, + clone: () => clone3, + copy: () => copy3, + create: () => create3, + decompose: () => decompose, + determinant: () => determinant, + equals: () => equals4, + exactEquals: () => exactEquals3, + frob: () => frob, + fromQuat: () => fromQuat, + fromQuat2: () => fromQuat2, + fromRotation: () => fromRotation, + fromRotationTranslation: () => fromRotationTranslation, + fromRotationTranslationScale: () => fromRotationTranslationScale, + fromRotationTranslationScaleOrigin: () => fromRotationTranslationScaleOrigin, + fromScaling: () => fromScaling, + fromTranslation: () => fromTranslation, + fromValues: () => fromValues3, + fromXRotation: () => fromXRotation, + fromYRotation: () => fromYRotation, + fromZRotation: () => fromZRotation, + frustum: () => frustum, + getRotation: () => getRotation, + getScaling: () => getScaling, + getTranslation: () => getTranslation, + identity: () => identity, + invert: () => invert, + lookAt: () => lookAt, + mul: () => mul3, + multiply: () => multiply3, + multiplyScalar: () => multiplyScalar, + multiplyScalarAndAdd: () => multiplyScalarAndAdd, + ortho: () => ortho, + orthoNO: () => orthoNO, + orthoZO: () => orthoZO, + perspective: () => perspective, + perspectiveFromFieldOfView: () => perspectiveFromFieldOfView, + perspectiveNO: () => perspectiveNO, + perspectiveZO: () => perspectiveZO, + rotate: () => rotate2, + rotateX: () => rotateX2, + rotateY: () => rotateY2, + rotateZ: () => rotateZ2, + scale: () => scale3, + set: () => set3, + str: () => str3, + sub: () => sub3, + subtract: () => subtract3, + targetTo: () => targetTo, + translate: () => translate, + transpose: () => transpose + }); + function create3() { + const out = new ARRAY_TYPE(16); + if (ARRAY_TYPE != Float32Array) { + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + } + out[0] = 1; + out[5] = 1; + out[10] = 1; + out[15] = 1; + return out; + } + function clone3(a) { + const out = new ARRAY_TYPE(16); + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + out[9] = a[9]; + out[10] = a[10]; + out[11] = a[11]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + return out; + } + function copy3(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + out[9] = a[9]; + out[10] = a[10]; + out[11] = a[11]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + return out; + } + function fromValues3(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) { + const out = new ARRAY_TYPE(16); + out[0] = m00; + out[1] = m01; + out[2] = m02; + out[3] = m03; + out[4] = m10; + out[5] = m11; + out[6] = m12; + out[7] = m13; + out[8] = m20; + out[9] = m21; + out[10] = m22; + out[11] = m23; + out[12] = m30; + out[13] = m31; + out[14] = m32; + out[15] = m33; + return out; + } + function set3(out, m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) { + out[0] = m00; + out[1] = m01; + out[2] = m02; + out[3] = m03; + out[4] = m10; + out[5] = m11; + out[6] = m12; + out[7] = m13; + out[8] = m20; + out[9] = m21; + out[10] = m22; + out[11] = m23; + out[12] = m30; + out[13] = m31; + out[14] = m32; + out[15] = m33; + return out; + } + function identity(out) { + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = 1; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = 1; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; + } + function transpose(out, a) { + if (out === a) { + const a01 = a[1]; + const a02 = a[2]; + const a03 = a[3]; + const a12 = a[6]; + const a13 = a[7]; + const a23 = a[11]; + out[1] = a[4]; + out[2] = a[8]; + out[3] = a[12]; + out[4] = a01; + out[6] = a[9]; + out[7] = a[13]; + out[8] = a02; + out[9] = a12; + out[11] = a[14]; + out[12] = a03; + out[13] = a13; + out[14] = a23; + } else { + out[0] = a[0]; + out[1] = a[4]; + out[2] = a[8]; + out[3] = a[12]; + out[4] = a[1]; + out[5] = a[5]; + out[6] = a[9]; + out[7] = a[13]; + out[8] = a[2]; + out[9] = a[6]; + out[10] = a[10]; + out[11] = a[14]; + out[12] = a[3]; + out[13] = a[7]; + out[14] = a[11]; + out[15] = a[15]; + } + return out; + } + function invert(out, a) { + const a00 = a[0]; + const a01 = a[1]; + const a02 = a[2]; + const a03 = a[3]; + const a10 = a[4]; + const a11 = a[5]; + const a12 = a[6]; + const a13 = a[7]; + const a20 = a[8]; + const a21 = a[9]; + const a22 = a[10]; + const a23 = a[11]; + const a30 = a[12]; + const a31 = a[13]; + const a32 = a[14]; + const a33 = a[15]; + const b00 = a00 * a11 - a01 * a10; + const b01 = a00 * a12 - a02 * a10; + const b02 = a00 * a13 - a03 * a10; + const b03 = a01 * a12 - a02 * a11; + const b04 = a01 * a13 - a03 * a11; + const b05 = a02 * a13 - a03 * a12; + const b06 = a20 * a31 - a21 * a30; + const b07 = a20 * a32 - a22 * a30; + const b08 = a20 * a33 - a23 * a30; + const b09 = a21 * a32 - a22 * a31; + const b10 = a21 * a33 - a23 * a31; + const b11 = a22 * a33 - a23 * a32; + let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; + if (!det) { + return null; + } + det = 1 / det; + out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; + out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det; + out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det; + out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det; + out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det; + out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det; + out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det; + out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det; + out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det; + out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det; + out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det; + out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det; + out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det; + out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det; + out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det; + out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det; + return out; + } + function adjoint(out, a) { + const a00 = a[0]; + const a01 = a[1]; + const a02 = a[2]; + const a03 = a[3]; + const a10 = a[4]; + const a11 = a[5]; + const a12 = a[6]; + const a13 = a[7]; + const a20 = a[8]; + const a21 = a[9]; + const a22 = a[10]; + const a23 = a[11]; + const a30 = a[12]; + const a31 = a[13]; + const a32 = a[14]; + const a33 = a[15]; + const b00 = a00 * a11 - a01 * a10; + const b01 = a00 * a12 - a02 * a10; + const b02 = a00 * a13 - a03 * a10; + const b03 = a01 * a12 - a02 * a11; + const b04 = a01 * a13 - a03 * a11; + const b05 = a02 * a13 - a03 * a12; + const b06 = a20 * a31 - a21 * a30; + const b07 = a20 * a32 - a22 * a30; + const b08 = a20 * a33 - a23 * a30; + const b09 = a21 * a32 - a22 * a31; + const b10 = a21 * a33 - a23 * a31; + const b11 = a22 * a33 - a23 * a32; + out[0] = a11 * b11 - a12 * b10 + a13 * b09; + out[1] = a02 * b10 - a01 * b11 - a03 * b09; + out[2] = a31 * b05 - a32 * b04 + a33 * b03; + out[3] = a22 * b04 - a21 * b05 - a23 * b03; + out[4] = a12 * b08 - a10 * b11 - a13 * b07; + out[5] = a00 * b11 - a02 * b08 + a03 * b07; + out[6] = a32 * b02 - a30 * b05 - a33 * b01; + out[7] = a20 * b05 - a22 * b02 + a23 * b01; + out[8] = a10 * b10 - a11 * b08 + a13 * b06; + out[9] = a01 * b08 - a00 * b10 - a03 * b06; + out[10] = a30 * b04 - a31 * b02 + a33 * b00; + out[11] = a21 * b02 - a20 * b04 - a23 * b00; + out[12] = a11 * b07 - a10 * b09 - a12 * b06; + out[13] = a00 * b09 - a01 * b07 + a02 * b06; + out[14] = a31 * b01 - a30 * b03 - a32 * b00; + out[15] = a20 * b03 - a21 * b01 + a22 * b00; + return out; + } + function determinant(a) { + const a00 = a[0]; + const a01 = a[1]; + const a02 = a[2]; + const a03 = a[3]; + const a10 = a[4]; + const a11 = a[5]; + const a12 = a[6]; + const a13 = a[7]; + const a20 = a[8]; + const a21 = a[9]; + const a22 = a[10]; + const a23 = a[11]; + const a30 = a[12]; + const a31 = a[13]; + const a32 = a[14]; + const a33 = a[15]; + const b0 = a00 * a11 - a01 * a10; + const b1 = a00 * a12 - a02 * a10; + const b2 = a01 * a12 - a02 * a11; + const b3 = a20 * a31 - a21 * a30; + const b4 = a20 * a32 - a22 * a30; + const b5 = a21 * a32 - a22 * a31; + const b6 = a00 * b5 - a01 * b4 + a02 * b3; + const b7 = a10 * b5 - a11 * b4 + a12 * b3; + const b8 = a20 * b2 - a21 * b1 + a22 * b0; + const b9 = a30 * b2 - a31 * b1 + a32 * b0; + return a13 * b6 - a03 * b7 + a33 * b8 - a23 * b9; + } + function multiply3(out, a, b) { + const a00 = a[0]; + const a01 = a[1]; + const a02 = a[2]; + const a03 = a[3]; + const a10 = a[4]; + const a11 = a[5]; + const a12 = a[6]; + const a13 = a[7]; + const a20 = a[8]; + const a21 = a[9]; + const a22 = a[10]; + const a23 = a[11]; + const a30 = a[12]; + const a31 = a[13]; + const a32 = a[14]; + const a33 = a[15]; + let b0 = b[0]; + let b1 = b[1]; + let b2 = b[2]; + let b3 = b[3]; + out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + b0 = b[4]; + b1 = b[5]; + b2 = b[6]; + b3 = b[7]; + out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + b0 = b[8]; + b1 = b[9]; + b2 = b[10]; + b3 = b[11]; + out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + b0 = b[12]; + b1 = b[13]; + b2 = b[14]; + b3 = b[15]; + out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + return out; + } + function translate(out, a, v) { + const x = v[0]; + const y = v[1]; + const z = v[2]; + let a00; + let a01; + let a02; + let a03; + let a10; + let a11; + let a12; + let a13; + let a20; + let a21; + let a22; + let a23; + if (a === out) { + out[12] = a[0] * x + a[4] * y + a[8] * z + a[12]; + out[13] = a[1] * x + a[5] * y + a[9] * z + a[13]; + out[14] = a[2] * x + a[6] * y + a[10] * z + a[14]; + out[15] = a[3] * x + a[7] * y + a[11] * z + a[15]; + } else { + a00 = a[0]; + a01 = a[1]; + a02 = a[2]; + a03 = a[3]; + a10 = a[4]; + a11 = a[5]; + a12 = a[6]; + a13 = a[7]; + a20 = a[8]; + a21 = a[9]; + a22 = a[10]; + a23 = a[11]; + out[0] = a00; + out[1] = a01; + out[2] = a02; + out[3] = a03; + out[4] = a10; + out[5] = a11; + out[6] = a12; + out[7] = a13; + out[8] = a20; + out[9] = a21; + out[10] = a22; + out[11] = a23; + out[12] = a00 * x + a10 * y + a20 * z + a[12]; + out[13] = a01 * x + a11 * y + a21 * z + a[13]; + out[14] = a02 * x + a12 * y + a22 * z + a[14]; + out[15] = a03 * x + a13 * y + a23 * z + a[15]; + } + return out; + } + function scale3(out, a, v) { + const x = v[0]; + const y = v[1]; + const z = v[2]; + out[0] = a[0] * x; + out[1] = a[1] * x; + out[2] = a[2] * x; + out[3] = a[3] * x; + out[4] = a[4] * y; + out[5] = a[5] * y; + out[6] = a[6] * y; + out[7] = a[7] * y; + out[8] = a[8] * z; + out[9] = a[9] * z; + out[10] = a[10] * z; + out[11] = a[11] * z; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + return out; + } + function rotate2(out, a, rad, axis) { + let x = axis[0]; + let y = axis[1]; + let z = axis[2]; + let len4 = Math.sqrt(x * x + y * y + z * z); + let c2; + let s; + let t; + let a00; + let a01; + let a02; + let a03; + let a10; + let a11; + let a12; + let a13; + let a20; + let a21; + let a22; + let a23; + let b00; + let b01; + let b02; + let b10; + let b11; + let b12; + let b20; + let b21; + let b22; + if (len4 < EPSILON) { + return null; + } + len4 = 1 / len4; + x *= len4; + y *= len4; + z *= len4; + s = Math.sin(rad); + c2 = Math.cos(rad); + t = 1 - c2; + a00 = a[0]; + a01 = a[1]; + a02 = a[2]; + a03 = a[3]; + a10 = a[4]; + a11 = a[5]; + a12 = a[6]; + a13 = a[7]; + a20 = a[8]; + a21 = a[9]; + a22 = a[10]; + a23 = a[11]; + b00 = x * x * t + c2; + b01 = y * x * t + z * s; + b02 = z * x * t - y * s; + b10 = x * y * t - z * s; + b11 = y * y * t + c2; + b12 = z * y * t + x * s; + b20 = x * z * t + y * s; + b21 = y * z * t - x * s; + b22 = z * z * t + c2; + out[0] = a00 * b00 + a10 * b01 + a20 * b02; + out[1] = a01 * b00 + a11 * b01 + a21 * b02; + out[2] = a02 * b00 + a12 * b01 + a22 * b02; + out[3] = a03 * b00 + a13 * b01 + a23 * b02; + out[4] = a00 * b10 + a10 * b11 + a20 * b12; + out[5] = a01 * b10 + a11 * b11 + a21 * b12; + out[6] = a02 * b10 + a12 * b11 + a22 * b12; + out[7] = a03 * b10 + a13 * b11 + a23 * b12; + out[8] = a00 * b20 + a10 * b21 + a20 * b22; + out[9] = a01 * b20 + a11 * b21 + a21 * b22; + out[10] = a02 * b20 + a12 * b21 + a22 * b22; + out[11] = a03 * b20 + a13 * b21 + a23 * b22; + if (a !== out) { + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + } + return out; + } + function rotateX2(out, a, rad) { + const s = Math.sin(rad); + const c2 = Math.cos(rad); + const a10 = a[4]; + const a11 = a[5]; + const a12 = a[6]; + const a13 = a[7]; + const a20 = a[8]; + const a21 = a[9]; + const a22 = a[10]; + const a23 = a[11]; + if (a !== out) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + } + out[4] = a10 * c2 + a20 * s; + out[5] = a11 * c2 + a21 * s; + out[6] = a12 * c2 + a22 * s; + out[7] = a13 * c2 + a23 * s; + out[8] = a20 * c2 - a10 * s; + out[9] = a21 * c2 - a11 * s; + out[10] = a22 * c2 - a12 * s; + out[11] = a23 * c2 - a13 * s; + return out; + } + function rotateY2(out, a, rad) { + const s = Math.sin(rad); + const c2 = Math.cos(rad); + const a00 = a[0]; + const a01 = a[1]; + const a02 = a[2]; + const a03 = a[3]; + const a20 = a[8]; + const a21 = a[9]; + const a22 = a[10]; + const a23 = a[11]; + if (a !== out) { + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + } + out[0] = a00 * c2 - a20 * s; + out[1] = a01 * c2 - a21 * s; + out[2] = a02 * c2 - a22 * s; + out[3] = a03 * c2 - a23 * s; + out[8] = a00 * s + a20 * c2; + out[9] = a01 * s + a21 * c2; + out[10] = a02 * s + a22 * c2; + out[11] = a03 * s + a23 * c2; + return out; + } + function rotateZ2(out, a, rad) { + const s = Math.sin(rad); + const c2 = Math.cos(rad); + const a00 = a[0]; + const a01 = a[1]; + const a02 = a[2]; + const a03 = a[3]; + const a10 = a[4]; + const a11 = a[5]; + const a12 = a[6]; + const a13 = a[7]; + if (a !== out) { + out[8] = a[8]; + out[9] = a[9]; + out[10] = a[10]; + out[11] = a[11]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + } + out[0] = a00 * c2 + a10 * s; + out[1] = a01 * c2 + a11 * s; + out[2] = a02 * c2 + a12 * s; + out[3] = a03 * c2 + a13 * s; + out[4] = a10 * c2 - a00 * s; + out[5] = a11 * c2 - a01 * s; + out[6] = a12 * c2 - a02 * s; + out[7] = a13 * c2 - a03 * s; + return out; + } + function fromTranslation(out, v) { + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = 1; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = 1; + out[11] = 0; + out[12] = v[0]; + out[13] = v[1]; + out[14] = v[2]; + out[15] = 1; + return out; + } + function fromScaling(out, v) { + out[0] = v[0]; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = v[1]; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = v[2]; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; + } + function fromRotation(out, rad, axis) { + let x = axis[0]; + let y = axis[1]; + let z = axis[2]; + let len4 = Math.sqrt(x * x + y * y + z * z); + let c2; + let s; + let t; + if (len4 < EPSILON) { + return null; + } + len4 = 1 / len4; + x *= len4; + y *= len4; + z *= len4; + s = Math.sin(rad); + c2 = Math.cos(rad); + t = 1 - c2; + out[0] = x * x * t + c2; + out[1] = y * x * t + z * s; + out[2] = z * x * t - y * s; + out[3] = 0; + out[4] = x * y * t - z * s; + out[5] = y * y * t + c2; + out[6] = z * y * t + x * s; + out[7] = 0; + out[8] = x * z * t + y * s; + out[9] = y * z * t - x * s; + out[10] = z * z * t + c2; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; + } + function fromXRotation(out, rad) { + const s = Math.sin(rad); + const c2 = Math.cos(rad); + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = c2; + out[6] = s; + out[7] = 0; + out[8] = 0; + out[9] = -s; + out[10] = c2; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; + } + function fromYRotation(out, rad) { + const s = Math.sin(rad); + const c2 = Math.cos(rad); + out[0] = c2; + out[1] = 0; + out[2] = -s; + out[3] = 0; + out[4] = 0; + out[5] = 1; + out[6] = 0; + out[7] = 0; + out[8] = s; + out[9] = 0; + out[10] = c2; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; + } + function fromZRotation(out, rad) { + const s = Math.sin(rad); + const c2 = Math.cos(rad); + out[0] = c2; + out[1] = s; + out[2] = 0; + out[3] = 0; + out[4] = -s; + out[5] = c2; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = 1; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; + } + function fromRotationTranslation(out, q, v) { + const x = q[0]; + const y = q[1]; + const z = q[2]; + const w = q[3]; + const x2 = x + x; + const y2 = y + y; + const z2 = z + z; + const xx = x * x2; + const xy = x * y2; + const xz = x * z2; + const yy = y * y2; + const yz = y * z2; + const zz = z * z2; + const wx = w * x2; + const wy = w * y2; + const wz = w * z2; + out[0] = 1 - (yy + zz); + out[1] = xy + wz; + out[2] = xz - wy; + out[3] = 0; + out[4] = xy - wz; + out[5] = 1 - (xx + zz); + out[6] = yz + wx; + out[7] = 0; + out[8] = xz + wy; + out[9] = yz - wx; + out[10] = 1 - (xx + yy); + out[11] = 0; + out[12] = v[0]; + out[13] = v[1]; + out[14] = v[2]; + out[15] = 1; + return out; + } + function fromQuat2(out, a) { + const translation = new ARRAY_TYPE(3); + const bx = -a[0]; + const by = -a[1]; + const bz = -a[2]; + const bw = a[3]; + const ax = a[4]; + const ay = a[5]; + const az = a[6]; + const aw = a[7]; + const magnitude = bx * bx + by * by + bz * bz + bw * bw; + if (magnitude > 0) { + translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2 / magnitude; + translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2 / magnitude; + translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2 / magnitude; + } else { + translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2; + translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2; + translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2; + } + fromRotationTranslation(out, a, translation); + return out; + } + function getTranslation(out, mat) { + out[0] = mat[12]; + out[1] = mat[13]; + out[2] = mat[14]; + return out; + } + function getScaling(out, mat) { + const m11 = mat[0]; + const m12 = mat[1]; + const m13 = mat[2]; + const m21 = mat[4]; + const m22 = mat[5]; + const m23 = mat[6]; + const m31 = mat[8]; + const m32 = mat[9]; + const m33 = mat[10]; + out[0] = Math.sqrt(m11 * m11 + m12 * m12 + m13 * m13); + out[1] = Math.sqrt(m21 * m21 + m22 * m22 + m23 * m23); + out[2] = Math.sqrt(m31 * m31 + m32 * m32 + m33 * m33); + return out; + } + function getRotation(out, mat) { + const scaling = new ARRAY_TYPE(3); + getScaling(scaling, mat); + const is1 = 1 / scaling[0]; + const is2 = 1 / scaling[1]; + const is3 = 1 / scaling[2]; + const sm11 = mat[0] * is1; + const sm12 = mat[1] * is2; + const sm13 = mat[2] * is3; + const sm21 = mat[4] * is1; + const sm22 = mat[5] * is2; + const sm23 = mat[6] * is3; + const sm31 = mat[8] * is1; + const sm32 = mat[9] * is2; + const sm33 = mat[10] * is3; + const trace = sm11 + sm22 + sm33; + let S = 0; + if (trace > 0) { + S = Math.sqrt(trace + 1) * 2; + out[3] = 0.25 * S; + out[0] = (sm23 - sm32) / S; + out[1] = (sm31 - sm13) / S; + out[2] = (sm12 - sm21) / S; + } else if (sm11 > sm22 && sm11 > sm33) { + S = Math.sqrt(1 + sm11 - sm22 - sm33) * 2; + out[3] = (sm23 - sm32) / S; + out[0] = 0.25 * S; + out[1] = (sm12 + sm21) / S; + out[2] = (sm31 + sm13) / S; + } else if (sm22 > sm33) { + S = Math.sqrt(1 + sm22 - sm11 - sm33) * 2; + out[3] = (sm31 - sm13) / S; + out[0] = (sm12 + sm21) / S; + out[1] = 0.25 * S; + out[2] = (sm23 + sm32) / S; + } else { + S = Math.sqrt(1 + sm33 - sm11 - sm22) * 2; + out[3] = (sm12 - sm21) / S; + out[0] = (sm31 + sm13) / S; + out[1] = (sm23 + sm32) / S; + out[2] = 0.25 * S; + } + return out; + } + function decompose(out_r, out_t, out_s, mat) { + out_t[0] = mat[12]; + out_t[1] = mat[13]; + out_t[2] = mat[14]; + const m11 = mat[0]; + const m12 = mat[1]; + const m13 = mat[2]; + const m21 = mat[4]; + const m22 = mat[5]; + const m23 = mat[6]; + const m31 = mat[8]; + const m32 = mat[9]; + const m33 = mat[10]; + out_s[0] = Math.sqrt(m11 * m11 + m12 * m12 + m13 * m13); + out_s[1] = Math.sqrt(m21 * m21 + m22 * m22 + m23 * m23); + out_s[2] = Math.sqrt(m31 * m31 + m32 * m32 + m33 * m33); + const is1 = 1 / out_s[0]; + const is2 = 1 / out_s[1]; + const is3 = 1 / out_s[2]; + const sm11 = m11 * is1; + const sm12 = m12 * is2; + const sm13 = m13 * is3; + const sm21 = m21 * is1; + const sm22 = m22 * is2; + const sm23 = m23 * is3; + const sm31 = m31 * is1; + const sm32 = m32 * is2; + const sm33 = m33 * is3; + const trace = sm11 + sm22 + sm33; + let S = 0; + if (trace > 0) { + S = Math.sqrt(trace + 1) * 2; + out_r[3] = 0.25 * S; + out_r[0] = (sm23 - sm32) / S; + out_r[1] = (sm31 - sm13) / S; + out_r[2] = (sm12 - sm21) / S; + } else if (sm11 > sm22 && sm11 > sm33) { + S = Math.sqrt(1 + sm11 - sm22 - sm33) * 2; + out_r[3] = (sm23 - sm32) / S; + out_r[0] = 0.25 * S; + out_r[1] = (sm12 + sm21) / S; + out_r[2] = (sm31 + sm13) / S; + } else if (sm22 > sm33) { + S = Math.sqrt(1 + sm22 - sm11 - sm33) * 2; + out_r[3] = (sm31 - sm13) / S; + out_r[0] = (sm12 + sm21) / S; + out_r[1] = 0.25 * S; + out_r[2] = (sm23 + sm32) / S; + } else { + S = Math.sqrt(1 + sm33 - sm11 - sm22) * 2; + out_r[3] = (sm12 - sm21) / S; + out_r[0] = (sm31 + sm13) / S; + out_r[1] = (sm23 + sm32) / S; + out_r[2] = 0.25 * S; + } + return out_r; + } + function fromRotationTranslationScale(out, q, v, s) { + const x = q[0]; + const y = q[1]; + const z = q[2]; + const w = q[3]; + const x2 = x + x; + const y2 = y + y; + const z2 = z + z; + const xx = x * x2; + const xy = x * y2; + const xz = x * z2; + const yy = y * y2; + const yz = y * z2; + const zz = z * z2; + const wx = w * x2; + const wy = w * y2; + const wz = w * z2; + const sx = s[0]; + const sy = s[1]; + const sz = s[2]; + out[0] = (1 - (yy + zz)) * sx; + out[1] = (xy + wz) * sx; + out[2] = (xz - wy) * sx; + out[3] = 0; + out[4] = (xy - wz) * sy; + out[5] = (1 - (xx + zz)) * sy; + out[6] = (yz + wx) * sy; + out[7] = 0; + out[8] = (xz + wy) * sz; + out[9] = (yz - wx) * sz; + out[10] = (1 - (xx + yy)) * sz; + out[11] = 0; + out[12] = v[0]; + out[13] = v[1]; + out[14] = v[2]; + out[15] = 1; + return out; + } + function fromRotationTranslationScaleOrigin(out, q, v, s, o) { + const x = q[0]; + const y = q[1]; + const z = q[2]; + const w = q[3]; + const x2 = x + x; + const y2 = y + y; + const z2 = z + z; + const xx = x * x2; + const xy = x * y2; + const xz = x * z2; + const yy = y * y2; + const yz = y * z2; + const zz = z * z2; + const wx = w * x2; + const wy = w * y2; + const wz = w * z2; + const sx = s[0]; + const sy = s[1]; + const sz = s[2]; + const ox = o[0]; + const oy = o[1]; + const oz = o[2]; + const out0 = (1 - (yy + zz)) * sx; + const out1 = (xy + wz) * sx; + const out2 = (xz - wy) * sx; + const out4 = (xy - wz) * sy; + const out5 = (1 - (xx + zz)) * sy; + const out6 = (yz + wx) * sy; + const out8 = (xz + wy) * sz; + const out9 = (yz - wx) * sz; + const out10 = (1 - (xx + yy)) * sz; + out[0] = out0; + out[1] = out1; + out[2] = out2; + out[3] = 0; + out[4] = out4; + out[5] = out5; + out[6] = out6; + out[7] = 0; + out[8] = out8; + out[9] = out9; + out[10] = out10; + out[11] = 0; + out[12] = v[0] + ox - (out0 * ox + out4 * oy + out8 * oz); + out[13] = v[1] + oy - (out1 * ox + out5 * oy + out9 * oz); + out[14] = v[2] + oz - (out2 * ox + out6 * oy + out10 * oz); + out[15] = 1; + return out; + } + function fromQuat(out, q) { + const x = q[0]; + const y = q[1]; + const z = q[2]; + const w = q[3]; + const x2 = x + x; + const y2 = y + y; + const z2 = z + z; + const xx = x * x2; + const yx = y * x2; + const yy = y * y2; + const zx = z * x2; + const zy = z * y2; + const zz = z * z2; + const wx = w * x2; + const wy = w * y2; + const wz = w * z2; + out[0] = 1 - yy - zz; + out[1] = yx + wz; + out[2] = zx - wy; + out[3] = 0; + out[4] = yx - wz; + out[5] = 1 - xx - zz; + out[6] = zy + wx; + out[7] = 0; + out[8] = zx + wy; + out[9] = zy - wx; + out[10] = 1 - xx - yy; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; + } + function frustum(out, left, right, bottom, top, near, far) { + const rl = 1 / (right - left); + const tb = 1 / (top - bottom); + const nf = 1 / (near - far); + out[0] = near * 2 * rl; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = near * 2 * tb; + out[6] = 0; + out[7] = 0; + out[8] = (right + left) * rl; + out[9] = (top + bottom) * tb; + out[10] = (far + near) * nf; + out[11] = -1; + out[12] = 0; + out[13] = 0; + out[14] = far * near * 2 * nf; + out[15] = 0; + return out; + } + function perspectiveNO(out, fovy, aspect, near, far) { + const f = 1 / Math.tan(fovy / 2); + out[0] = f / aspect; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = f; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[11] = -1; + out[12] = 0; + out[13] = 0; + out[15] = 0; + if (far != null && far !== Infinity) { + const nf = 1 / (near - far); + out[10] = (far + near) * nf; + out[14] = 2 * far * near * nf; + } else { + out[10] = -1; + out[14] = -2 * near; + } + return out; + } + var perspective = perspectiveNO; + function perspectiveZO(out, fovy, aspect, near, far) { + const f = 1 / Math.tan(fovy / 2); + out[0] = f / aspect; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = f; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[11] = -1; + out[12] = 0; + out[13] = 0; + out[15] = 0; + if (far != null && far !== Infinity) { + const nf = 1 / (near - far); + out[10] = far * nf; + out[14] = far * near * nf; + } else { + out[10] = -1; + out[14] = -near; + } + return out; + } + function perspectiveFromFieldOfView(out, fov, near, far) { + const upTan = Math.tan(fov.upDegrees * Math.PI / 180); + const downTan = Math.tan(fov.downDegrees * Math.PI / 180); + const leftTan = Math.tan(fov.leftDegrees * Math.PI / 180); + const rightTan = Math.tan(fov.rightDegrees * Math.PI / 180); + const xScale = 2 / (leftTan + rightTan); + const yScale = 2 / (upTan + downTan); + out[0] = xScale; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = yScale; + out[6] = 0; + out[7] = 0; + out[8] = -((leftTan - rightTan) * xScale * 0.5); + out[9] = (upTan - downTan) * yScale * 0.5; + out[10] = far / (near - far); + out[11] = -1; + out[12] = 0; + out[13] = 0; + out[14] = far * near / (near - far); + out[15] = 0; + return out; + } + function orthoNO(out, left, right, bottom, top, near, far) { + const lr = 1 / (left - right); + const bt = 1 / (bottom - top); + const nf = 1 / (near - far); + out[0] = -2 * lr; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = -2 * bt; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = 2 * nf; + out[11] = 0; + out[12] = (left + right) * lr; + out[13] = (top + bottom) * bt; + out[14] = (far + near) * nf; + out[15] = 1; + return out; + } + var ortho = orthoNO; + function orthoZO(out, left, right, bottom, top, near, far) { + const lr = 1 / (left - right); + const bt = 1 / (bottom - top); + const nf = 1 / (near - far); + out[0] = -2 * lr; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = -2 * bt; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = nf; + out[11] = 0; + out[12] = (left + right) * lr; + out[13] = (top + bottom) * bt; + out[14] = near * nf; + out[15] = 1; + return out; + } + function lookAt(out, eye, center, up) { + let len4; + let x0; + let x1; + let x2; + let y0; + let y1; + let y2; + let z0; + let z1; + let z2; + const eyex = eye[0]; + const eyey = eye[1]; + const eyez = eye[2]; + const upx = up[0]; + const upy = up[1]; + const upz = up[2]; + const centerx = center[0]; + const centery = center[1]; + const centerz = center[2]; + if (Math.abs(eyex - centerx) < EPSILON && Math.abs(eyey - centery) < EPSILON && Math.abs(eyez - centerz) < EPSILON) { + return identity(out); + } + z0 = eyex - centerx; + z1 = eyey - centery; + z2 = eyez - centerz; + len4 = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2); + z0 *= len4; + z1 *= len4; + z2 *= len4; + x0 = upy * z2 - upz * z1; + x1 = upz * z0 - upx * z2; + x2 = upx * z1 - upy * z0; + len4 = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2); + if (!len4) { + x0 = 0; + x1 = 0; + x2 = 0; + } else { + len4 = 1 / len4; + x0 *= len4; + x1 *= len4; + x2 *= len4; + } + y0 = z1 * x2 - z2 * x1; + y1 = z2 * x0 - z0 * x2; + y2 = z0 * x1 - z1 * x0; + len4 = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2); + if (!len4) { + y0 = 0; + y1 = 0; + y2 = 0; + } else { + len4 = 1 / len4; + y0 *= len4; + y1 *= len4; + y2 *= len4; + } + out[0] = x0; + out[1] = y0; + out[2] = z0; + out[3] = 0; + out[4] = x1; + out[5] = y1; + out[6] = z1; + out[7] = 0; + out[8] = x2; + out[9] = y2; + out[10] = z2; + out[11] = 0; + out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez); + out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez); + out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez); + out[15] = 1; + return out; + } + function targetTo(out, eye, target2, up) { + const eyex = eye[0]; + const eyey = eye[1]; + const eyez = eye[2]; + const upx = up[0]; + const upy = up[1]; + const upz = up[2]; + let z0 = eyex - target2[0]; + let z1 = eyey - target2[1]; + let z2 = eyez - target2[2]; + let len4 = z0 * z0 + z1 * z1 + z2 * z2; + if (len4 > 0) { + len4 = 1 / Math.sqrt(len4); + z0 *= len4; + z1 *= len4; + z2 *= len4; + } + let x0 = upy * z2 - upz * z1; + let x1 = upz * z0 - upx * z2; + let x2 = upx * z1 - upy * z0; + len4 = x0 * x0 + x1 * x1 + x2 * x2; + if (len4 > 0) { + len4 = 1 / Math.sqrt(len4); + x0 *= len4; + x1 *= len4; + x2 *= len4; + } + out[0] = x0; + out[1] = x1; + out[2] = x2; + out[3] = 0; + out[4] = z1 * x2 - z2 * x1; + out[5] = z2 * x0 - z0 * x2; + out[6] = z0 * x1 - z1 * x0; + out[7] = 0; + out[8] = z0; + out[9] = z1; + out[10] = z2; + out[11] = 0; + out[12] = eyex; + out[13] = eyey; + out[14] = eyez; + out[15] = 1; + return out; + } + function str3(a) { + return `mat4(${a[0]}, ${a[1]}, ${a[2]}, ${a[3]}, ${a[4]}, ${a[5]}, ${a[6]}, ${a[7]}, ${a[8]}, ${a[9]}, ${a[10]}, ${a[11]}, ${a[12]}, ${a[13]}, ${a[14]}, ${a[15]})`; + } + function frob(a) { + return Math.sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2] + a[3] * a[3] + a[4] * a[4] + a[5] * a[5] + a[6] * a[6] + a[7] * a[7] + a[8] * a[8] + a[9] * a[9] + a[10] * a[10] + a[11] * a[11] + a[12] * a[12] + a[13] * a[13] + a[14] * a[14] + a[15] * a[15]); + } + function add3(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + out[2] = a[2] + b[2]; + out[3] = a[3] + b[3]; + out[4] = a[4] + b[4]; + out[5] = a[5] + b[5]; + out[6] = a[6] + b[6]; + out[7] = a[7] + b[7]; + out[8] = a[8] + b[8]; + out[9] = a[9] + b[9]; + out[10] = a[10] + b[10]; + out[11] = a[11] + b[11]; + out[12] = a[12] + b[12]; + out[13] = a[13] + b[13]; + out[14] = a[14] + b[14]; + out[15] = a[15] + b[15]; + return out; + } + function subtract3(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + out[2] = a[2] - b[2]; + out[3] = a[3] - b[3]; + out[4] = a[4] - b[4]; + out[5] = a[5] - b[5]; + out[6] = a[6] - b[6]; + out[7] = a[7] - b[7]; + out[8] = a[8] - b[8]; + out[9] = a[9] - b[9]; + out[10] = a[10] - b[10]; + out[11] = a[11] - b[11]; + out[12] = a[12] - b[12]; + out[13] = a[13] - b[13]; + out[14] = a[14] - b[14]; + out[15] = a[15] - b[15]; + return out; + } + function multiplyScalar(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + out[2] = a[2] * b; + out[3] = a[3] * b; + out[4] = a[4] * b; + out[5] = a[5] * b; + out[6] = a[6] * b; + out[7] = a[7] * b; + out[8] = a[8] * b; + out[9] = a[9] * b; + out[10] = a[10] * b; + out[11] = a[11] * b; + out[12] = a[12] * b; + out[13] = a[13] * b; + out[14] = a[14] * b; + out[15] = a[15] * b; + return out; + } + function multiplyScalarAndAdd(out, a, b, scale5) { + out[0] = a[0] + b[0] * scale5; + out[1] = a[1] + b[1] * scale5; + out[2] = a[2] + b[2] * scale5; + out[3] = a[3] + b[3] * scale5; + out[4] = a[4] + b[4] * scale5; + out[5] = a[5] + b[5] * scale5; + out[6] = a[6] + b[6] * scale5; + out[7] = a[7] + b[7] * scale5; + out[8] = a[8] + b[8] * scale5; + out[9] = a[9] + b[9] * scale5; + out[10] = a[10] + b[10] * scale5; + out[11] = a[11] + b[11] * scale5; + out[12] = a[12] + b[12] * scale5; + out[13] = a[13] + b[13] * scale5; + out[14] = a[14] + b[14] * scale5; + out[15] = a[15] + b[15] * scale5; + return out; + } + function exactEquals3(a, b) { + return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3] && a[4] === b[4] && a[5] === b[5] && a[6] === b[6] && a[7] === b[7] && a[8] === b[8] && a[9] === b[9] && a[10] === b[10] && a[11] === b[11] && a[12] === b[12] && a[13] === b[13] && a[14] === b[14] && a[15] === b[15]; + } + function equals4(a, b) { + const a0 = a[0]; + const a1 = a[1]; + const a2 = a[2]; + const a3 = a[3]; + const a4 = a[4]; + const a5 = a[5]; + const a6 = a[6]; + const a7 = a[7]; + const a8 = a[8]; + const a9 = a[9]; + const a10 = a[10]; + const a11 = a[11]; + const a12 = a[12]; + const a13 = a[13]; + const a14 = a[14]; + const a15 = a[15]; + const b0 = b[0]; + const b1 = b[1]; + const b2 = b[2]; + const b3 = b[3]; + const b4 = b[4]; + const b5 = b[5]; + const b6 = b[6]; + const b7 = b[7]; + const b8 = b[8]; + const b9 = b[9]; + const b10 = b[10]; + const b11 = b[11]; + const b12 = b[12]; + const b13 = b[13]; + const b14 = b[14]; + const b15 = b[15]; + return Math.abs(a0 - b0) <= EPSILON * Math.max(1, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= EPSILON * Math.max(1, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= EPSILON * Math.max(1, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= EPSILON * Math.max(1, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= EPSILON * Math.max(1, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= EPSILON * Math.max(1, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= EPSILON * Math.max(1, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= EPSILON * Math.max(1, Math.abs(a8), Math.abs(b8)) && Math.abs(a9 - b9) <= EPSILON * Math.max(1, Math.abs(a9), Math.abs(b9)) && Math.abs(a10 - b10) <= EPSILON * Math.max(1, Math.abs(a10), Math.abs(b10)) && Math.abs(a11 - b11) <= EPSILON * Math.max(1, Math.abs(a11), Math.abs(b11)) && Math.abs(a12 - b12) <= EPSILON * Math.max(1, Math.abs(a12), Math.abs(b12)) && Math.abs(a13 - b13) <= EPSILON * Math.max(1, Math.abs(a13), Math.abs(b13)) && Math.abs(a14 - b14) <= EPSILON * Math.max(1, Math.abs(a14), Math.abs(b14)) && Math.abs(a15 - b15) <= EPSILON * Math.max(1, Math.abs(a15), Math.abs(b15)); + } + var mul3 = multiply3; + var sub3 = subtract3; + + // node_modules/@math.gl/core/dist/gl-matrix/vec4.js + var vec4_exports = {}; + __export(vec4_exports, { + add: () => add4, + ceil: () => ceil3, + clone: () => clone4, + copy: () => copy4, + create: () => create4, + cross: () => cross3, + dist: () => dist3, + distance: () => distance3, + div: () => div3, + divide: () => divide3, + dot: () => dot3, + equals: () => equals5, + exactEquals: () => exactEquals4, + floor: () => floor3, + forEach: () => forEach4, + fromValues: () => fromValues4, + inverse: () => inverse3, + len: () => len3, + length: () => length3, + lerp: () => lerp4, + max: () => max3, + min: () => min3, + mul: () => mul4, + multiply: () => multiply4, + negate: () => negate3, + normalize: () => normalize3, + random: () => random3, + round: () => round5, + scale: () => scale4, + scaleAndAdd: () => scaleAndAdd3, + set: () => set4, + sqrDist: () => sqrDist3, + sqrLen: () => sqrLen3, + squaredDistance: () => squaredDistance3, + squaredLength: () => squaredLength3, + str: () => str4, + sub: () => sub4, + subtract: () => subtract4, + transformMat4: () => transformMat43, + transformQuat: () => transformQuat2, + zero: () => zero3 + }); + function create4() { + const out = new ARRAY_TYPE(4); + if (ARRAY_TYPE != Float32Array) { + out[0] = 0; + out[1] = 0; + out[2] = 0; + out[3] = 0; + } + return out; + } + function clone4(a) { + const out = new ARRAY_TYPE(4); + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + return out; + } + function fromValues4(x, y, z, w) { + const out = new ARRAY_TYPE(4); + out[0] = x; + out[1] = y; + out[2] = z; + out[3] = w; + return out; + } + function copy4(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + return out; + } + function set4(out, x, y, z, w) { + out[0] = x; + out[1] = y; + out[2] = z; + out[3] = w; + return out; + } + function add4(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + out[2] = a[2] + b[2]; + out[3] = a[3] + b[3]; + return out; + } + function subtract4(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + out[2] = a[2] - b[2]; + out[3] = a[3] - b[3]; + return out; + } + function multiply4(out, a, b) { + out[0] = a[0] * b[0]; + out[1] = a[1] * b[1]; + out[2] = a[2] * b[2]; + out[3] = a[3] * b[3]; + return out; + } + function divide3(out, a, b) { + out[0] = a[0] / b[0]; + out[1] = a[1] / b[1]; + out[2] = a[2] / b[2]; + out[3] = a[3] / b[3]; + return out; + } + function ceil3(out, a) { + out[0] = Math.ceil(a[0]); + out[1] = Math.ceil(a[1]); + out[2] = Math.ceil(a[2]); + out[3] = Math.ceil(a[3]); + return out; + } + function floor3(out, a) { + out[0] = Math.floor(a[0]); + out[1] = Math.floor(a[1]); + out[2] = Math.floor(a[2]); + out[3] = Math.floor(a[3]); + return out; + } + function min3(out, a, b) { + out[0] = Math.min(a[0], b[0]); + out[1] = Math.min(a[1], b[1]); + out[2] = Math.min(a[2], b[2]); + out[3] = Math.min(a[3], b[3]); + return out; + } + function max3(out, a, b) { + out[0] = Math.max(a[0], b[0]); + out[1] = Math.max(a[1], b[1]); + out[2] = Math.max(a[2], b[2]); + out[3] = Math.max(a[3], b[3]); + return out; + } + function round5(out, a) { + out[0] = round2(a[0]); + out[1] = round2(a[1]); + out[2] = round2(a[2]); + out[3] = round2(a[3]); + return out; + } + function scale4(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + out[2] = a[2] * b; + out[3] = a[3] * b; + return out; + } + function scaleAndAdd3(out, a, b, scale5) { + out[0] = a[0] + b[0] * scale5; + out[1] = a[1] + b[1] * scale5; + out[2] = a[2] + b[2] * scale5; + out[3] = a[3] + b[3] * scale5; + return out; + } + function distance3(a, b) { + const x = b[0] - a[0]; + const y = b[1] - a[1]; + const z = b[2] - a[2]; + const w = b[3] - a[3]; + return Math.sqrt(x * x + y * y + z * z + w * w); + } + function squaredDistance3(a, b) { + const x = b[0] - a[0]; + const y = b[1] - a[1]; + const z = b[2] - a[2]; + const w = b[3] - a[3]; + return x * x + y * y + z * z + w * w; + } + function length3(a) { + const x = a[0]; + const y = a[1]; + const z = a[2]; + const w = a[3]; + return Math.sqrt(x * x + y * y + z * z + w * w); + } + function squaredLength3(a) { + const x = a[0]; + const y = a[1]; + const z = a[2]; + const w = a[3]; + return x * x + y * y + z * z + w * w; + } + function negate3(out, a) { + out[0] = -a[0]; + out[1] = -a[1]; + out[2] = -a[2]; + out[3] = -a[3]; + return out; + } + function inverse3(out, a) { + out[0] = 1 / a[0]; + out[1] = 1 / a[1]; + out[2] = 1 / a[2]; + out[3] = 1 / a[3]; + return out; + } + function normalize3(out, a) { + const x = a[0]; + const y = a[1]; + const z = a[2]; + const w = a[3]; + let len4 = x * x + y * y + z * z + w * w; + if (len4 > 0) { + len4 = 1 / Math.sqrt(len4); + } + out[0] = x * len4; + out[1] = y * len4; + out[2] = z * len4; + out[3] = w * len4; + return out; + } + function dot3(a, b) { + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]; + } + function cross3(out, u, v, w) { + const A2 = v[0] * w[1] - v[1] * w[0]; + const B2 = v[0] * w[2] - v[2] * w[0]; + const C2 = v[0] * w[3] - v[3] * w[0]; + const D2 = v[1] * w[2] - v[2] * w[1]; + const E2 = v[1] * w[3] - v[3] * w[1]; + const F = v[2] * w[3] - v[3] * w[2]; + const G = u[0]; + const H = u[1]; + const I = u[2]; + const J = u[3]; + out[0] = H * F - I * E2 + J * D2; + out[1] = -(G * F) + I * C2 - J * B2; + out[2] = G * E2 - H * C2 + J * A2; + out[3] = -(G * D2) + H * B2 - I * A2; + return out; + } + function lerp4(out, a, b, t) { + const ax = a[0]; + const ay = a[1]; + const az = a[2]; + const aw = a[3]; + out[0] = ax + t * (b[0] - ax); + out[1] = ay + t * (b[1] - ay); + out[2] = az + t * (b[2] - az); + out[3] = aw + t * (b[3] - aw); + return out; + } + function random3(out, scale5) { + scale5 = scale5 === void 0 ? 1 : scale5; + let v1; + let v2; + let v3; + let v4; + let s1; + let s2; + do { + v1 = RANDOM() * 2 - 1; + v2 = RANDOM() * 2 - 1; + s1 = v1 * v1 + v2 * v2; + } while (s1 >= 1); + do { + v3 = RANDOM() * 2 - 1; + v4 = RANDOM() * 2 - 1; + s2 = v3 * v3 + v4 * v4; + } while (s2 >= 1); + const d = Math.sqrt((1 - s1) / s2); + out[0] = scale5 * v1; + out[1] = scale5 * v2; + out[2] = scale5 * v3 * d; + out[3] = scale5 * v4 * d; + return out; + } + function transformMat43(out, a, m) { + const x = a[0]; + const y = a[1]; + const z = a[2]; + const w = a[3]; + out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w; + out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w; + out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w; + out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w; + return out; + } + function transformQuat2(out, a, q) { + const x = a[0]; + const y = a[1]; + const z = a[2]; + const qx = q[0]; + const qy = q[1]; + const qz = q[2]; + const qw = q[3]; + const ix = qw * x + qy * z - qz * y; + const iy = qw * y + qz * x - qx * z; + const iz = qw * z + qx * y - qy * x; + const iw = -qx * x - qy * y - qz * z; + out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy; + out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz; + out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx; + out[3] = a[3]; + return out; + } + function zero3(out) { + out[0] = 0; + out[1] = 0; + out[2] = 0; + out[3] = 0; + return out; + } + function str4(a) { + return `vec4(${a[0]}, ${a[1]}, ${a[2]}, ${a[3]})`; + } + function exactEquals4(a, b) { + return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3]; + } + function equals5(a, b) { + const a0 = a[0]; + const a1 = a[1]; + const a2 = a[2]; + const a3 = a[3]; + const b0 = b[0]; + const b1 = b[1]; + const b2 = b[2]; + const b3 = b[3]; + return Math.abs(a0 - b0) <= EPSILON * Math.max(1, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= EPSILON * Math.max(1, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= EPSILON * Math.max(1, Math.abs(a3), Math.abs(b3)); + } + var sub4 = subtract4; + var mul4 = multiply4; + var div3 = divide3; + var dist3 = distance3; + var sqrDist3 = squaredDistance3; + var len3 = length3; + var sqrLen3 = squaredLength3; + var forEach4 = (function() { + const vec = create4(); + return function(a, stride, offset, count2, fn, arg) { + let i; + let l; + if (!stride) { + stride = 4; + } + if (!offset) { + offset = 0; + } + if (count2) { + l = Math.min(count2 * stride + offset, a.length); + } else { + l = a.length; + } + for (i = offset; i < l; i += stride) { + vec[0] = a[i]; + vec[1] = a[i + 1]; + vec[2] = a[i + 2]; + vec[3] = a[i + 3]; + fn(vec, vec, arg); + a[i] = vec[0]; + a[i + 1] = vec[1]; + a[i + 2] = vec[2]; + a[i + 3] = vec[3]; + } + return a; + }; + })(); + + // node_modules/@math.gl/core/dist/classes/matrix4.js + var INDICES; + (function(INDICES2) { + INDICES2[INDICES2["COL0ROW0"] = 0] = "COL0ROW0"; + INDICES2[INDICES2["COL0ROW1"] = 1] = "COL0ROW1"; + INDICES2[INDICES2["COL0ROW2"] = 2] = "COL0ROW2"; + INDICES2[INDICES2["COL0ROW3"] = 3] = "COL0ROW3"; + INDICES2[INDICES2["COL1ROW0"] = 4] = "COL1ROW0"; + INDICES2[INDICES2["COL1ROW1"] = 5] = "COL1ROW1"; + INDICES2[INDICES2["COL1ROW2"] = 6] = "COL1ROW2"; + INDICES2[INDICES2["COL1ROW3"] = 7] = "COL1ROW3"; + INDICES2[INDICES2["COL2ROW0"] = 8] = "COL2ROW0"; + INDICES2[INDICES2["COL2ROW1"] = 9] = "COL2ROW1"; + INDICES2[INDICES2["COL2ROW2"] = 10] = "COL2ROW2"; + INDICES2[INDICES2["COL2ROW3"] = 11] = "COL2ROW3"; + INDICES2[INDICES2["COL3ROW0"] = 12] = "COL3ROW0"; + INDICES2[INDICES2["COL3ROW1"] = 13] = "COL3ROW1"; + INDICES2[INDICES2["COL3ROW2"] = 14] = "COL3ROW2"; + INDICES2[INDICES2["COL3ROW3"] = 15] = "COL3ROW3"; + })(INDICES || (INDICES = {})); + var DEFAULT_FOVY = 45 * Math.PI / 180; + var DEFAULT_ASPECT = 1; + var DEFAULT_NEAR = 0.1; + var DEFAULT_FAR = 500; + var IDENTITY_MATRIX = Object.freeze([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); + var Matrix4 = class extends Matrix { + static get IDENTITY() { + return getIdentityMatrix(); + } + static get ZERO() { + return getZeroMatrix(); + } + get ELEMENTS() { + return 16; + } + get RANK() { + return 4; + } + get INDICES() { + return INDICES; + } + constructor(array) { + super(-0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0); + if (arguments.length === 1 && Array.isArray(array)) { + this.copy(array); + } else { + this.identity(); + } + } + copy(array) { + this[0] = array[0]; + this[1] = array[1]; + this[2] = array[2]; + this[3] = array[3]; + this[4] = array[4]; + this[5] = array[5]; + this[6] = array[6]; + this[7] = array[7]; + this[8] = array[8]; + this[9] = array[9]; + this[10] = array[10]; + this[11] = array[11]; + this[12] = array[12]; + this[13] = array[13]; + this[14] = array[14]; + this[15] = array[15]; + return this.check(); + } + // eslint-disable-next-line max-params + set(m00, m10, m20, m30, m01, m11, m21, m31, m02, m12, m22, m32, m03, m13, m23, m33) { + this[0] = m00; + this[1] = m10; + this[2] = m20; + this[3] = m30; + this[4] = m01; + this[5] = m11; + this[6] = m21; + this[7] = m31; + this[8] = m02; + this[9] = m12; + this[10] = m22; + this[11] = m32; + this[12] = m03; + this[13] = m13; + this[14] = m23; + this[15] = m33; + return this.check(); + } + // accepts row major order, stores as column major + // eslint-disable-next-line max-params + setRowMajor(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) { + this[0] = m00; + this[1] = m10; + this[2] = m20; + this[3] = m30; + this[4] = m01; + this[5] = m11; + this[6] = m21; + this[7] = m31; + this[8] = m02; + this[9] = m12; + this[10] = m22; + this[11] = m32; + this[12] = m03; + this[13] = m13; + this[14] = m23; + this[15] = m33; + return this.check(); + } + toRowMajor(result) { + result[0] = this[0]; + result[1] = this[4]; + result[2] = this[8]; + result[3] = this[12]; + result[4] = this[1]; + result[5] = this[5]; + result[6] = this[9]; + result[7] = this[13]; + result[8] = this[2]; + result[9] = this[6]; + result[10] = this[10]; + result[11] = this[14]; + result[12] = this[3]; + result[13] = this[7]; + result[14] = this[11]; + result[15] = this[15]; + return result; + } + // Constructors + /** Set to identity matrix */ + identity() { + return this.copy(IDENTITY_MATRIX); + } + /** + * + * @param object + * @returns self + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + fromObject(object) { + return this.check(); + } + /** + * Calculates a 4x4 matrix from the given quaternion + * @param quaternion Quaternion to create matrix from + * @returns self + */ + fromQuaternion(quaternion) { + fromQuat(this, quaternion); + return this.check(); + } + /** + * Generates a frustum matrix with the given bounds + * @param view.left - Left bound of the frustum + * @param view.right - Right bound of the frustum + * @param view.bottom - Bottom bound of the frustum + * @param view.top - Top bound of the frustum + * @param view.near - Near bound of the frustum + * @param view.far - Far bound of the frustum. Can be set to Infinity. + * @returns self + */ + frustum(view) { + const { left, right, bottom, top, near = DEFAULT_NEAR, far = DEFAULT_FAR } = view; + if (far === Infinity) { + computeInfinitePerspectiveOffCenter(this, left, right, bottom, top, near); + } else { + frustum(this, left, right, bottom, top, near, far); + } + return this.check(); + } + /** + * Generates a look-at matrix with the given eye position, focal point, + * and up axis + * @param view.eye - (vector) Position of the viewer + * @param view.center - (vector) Point the viewer is looking at + * @param view.up - (vector) Up axis + * @returns self + */ + lookAt(view) { + const { eye, center = [0, 0, 0], up = [0, 1, 0] } = view; + lookAt(this, eye, center, up); + return this.check(); + } + /** + * Generates a orthogonal projection matrix with the given bounds + * from "traditional" view space parameters + * @param view.left - Left bound of the frustum + * @param view.right number Right bound of the frustum + * @param view.bottom - Bottom bound of the frustum + * @param view.top number Top bound of the frustum + * @param view.near - Near bound of the frustum + * @param view.far number Far bound of the frustum + * @returns self + */ + ortho(view) { + const { left, right, bottom, top, near = DEFAULT_NEAR, far = DEFAULT_FAR } = view; + ortho(this, left, right, bottom, top, near, far); + return this.check(); + } + /** + * Generates an orthogonal projection matrix with the same parameters + * as a perspective matrix (plus focalDistance) + * @param view.fovy Vertical field of view in radians + * @param view.aspect Aspect ratio. Typically viewport width / viewport height + * @param view.focalDistance Distance in the view frustum used for extent calculations + * @param view.near Near bound of the frustum + * @param view.far Far bound of the frustum + * @returns self + */ + orthographic(view) { + const { fovy = DEFAULT_FOVY, aspect = DEFAULT_ASPECT, focalDistance = 1, near = DEFAULT_NEAR, far = DEFAULT_FAR } = view; + checkRadians(fovy); + const halfY = fovy / 2; + const top = focalDistance * Math.tan(halfY); + const right = top * aspect; + return this.ortho({ + left: -right, + right, + bottom: -top, + top, + near, + far + }); + } + /** + * Generates a perspective projection matrix with the given bounds + * @param view.fovy Vertical field of view in radians + * @param view.aspect Aspect ratio. typically viewport width/height + * @param view.near Near bound of the frustum + * @param view.far Far bound of the frustum + * @returns self + */ + perspective(view) { + const { fovy = 45 * Math.PI / 180, aspect = 1, near = 0.1, far = 500 } = view; + checkRadians(fovy); + perspective(this, fovy, aspect, near, far); + return this.check(); + } + // Accessors + determinant() { + return determinant(this); + } + /** + * Extracts the non-uniform scale assuming the matrix is an affine transformation. + * The scales are the "lengths" of the column vectors in the upper-left 3x3 matrix. + * @param result + * @returns self + */ + getScale(result = [-0, -0, -0]) { + result[0] = Math.sqrt(this[0] * this[0] + this[1] * this[1] + this[2] * this[2]); + result[1] = Math.sqrt(this[4] * this[4] + this[5] * this[5] + this[6] * this[6]); + result[2] = Math.sqrt(this[8] * this[8] + this[9] * this[9] + this[10] * this[10]); + return result; + } + /** + * Gets the translation portion, assuming the matrix is a affine transformation matrix. + * @param result + * @returns self + */ + getTranslation(result = [-0, -0, -0]) { + result[0] = this[12]; + result[1] = this[13]; + result[2] = this[14]; + return result; + } + /** + * Gets upper left 3x3 pure rotation matrix (non-scaling), assume affine transformation matrix + * @param result + * @param scaleResult + * @returns self + */ + getRotation(result, scaleResult) { + result = result || [-0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0]; + scaleResult = scaleResult || [-0, -0, -0]; + const scale5 = this.getScale(scaleResult); + const inverseScale0 = 1 / scale5[0]; + const inverseScale1 = 1 / scale5[1]; + const inverseScale2 = 1 / scale5[2]; + result[0] = this[0] * inverseScale0; + result[1] = this[1] * inverseScale1; + result[2] = this[2] * inverseScale2; + result[3] = 0; + result[4] = this[4] * inverseScale0; + result[5] = this[5] * inverseScale1; + result[6] = this[6] * inverseScale2; + result[7] = 0; + result[8] = this[8] * inverseScale0; + result[9] = this[9] * inverseScale1; + result[10] = this[10] * inverseScale2; + result[11] = 0; + result[12] = 0; + result[13] = 0; + result[14] = 0; + result[15] = 1; + return result; + } + /** + * + * @param result + * @param scaleResult + * @returns self + */ + getRotationMatrix3(result, scaleResult) { + result = result || [-0, -0, -0, -0, -0, -0, -0, -0, -0]; + scaleResult = scaleResult || [-0, -0, -0]; + const scale5 = this.getScale(scaleResult); + const inverseScale0 = 1 / scale5[0]; + const inverseScale1 = 1 / scale5[1]; + const inverseScale2 = 1 / scale5[2]; + result[0] = this[0] * inverseScale0; + result[1] = this[1] * inverseScale1; + result[2] = this[2] * inverseScale2; + result[3] = this[4] * inverseScale0; + result[4] = this[5] * inverseScale1; + result[5] = this[6] * inverseScale2; + result[6] = this[8] * inverseScale0; + result[7] = this[9] * inverseScale1; + result[8] = this[10] * inverseScale2; + return result; + } + // Modifiers + transpose() { + transpose(this, this); + return this.check(); + } + invert() { + invert(this, this); + return this.check(); + } + // Operations + multiplyLeft(a) { + multiply3(this, a, this); + return this.check(); + } + multiplyRight(a) { + multiply3(this, this, a); + return this.check(); + } + // Rotates a matrix by the given angle around the X axis + rotateX(radians4) { + rotateX2(this, this, radians4); + return this.check(); + } + // Rotates a matrix by the given angle around the Y axis. + rotateY(radians4) { + rotateY2(this, this, radians4); + return this.check(); + } + /** + * Rotates a matrix by the given angle around the Z axis. + * @param radians + * @returns self + */ + rotateZ(radians4) { + rotateZ2(this, this, radians4); + return this.check(); + } + /** + * + * @param param0 + * @returns self + */ + rotateXYZ(angleXYZ) { + return this.rotateX(angleXYZ[0]).rotateY(angleXYZ[1]).rotateZ(angleXYZ[2]); + } + /** + * + * @param radians + * @param axis + * @returns self + */ + rotateAxis(radians4, axis) { + rotate2(this, this, radians4, axis); + return this.check(); + } + /** + * + * @param factor + * @returns self + */ + scale(factor) { + scale3(this, this, Array.isArray(factor) ? factor : [factor, factor, factor]); + return this.check(); + } + /** + * + * @param vec + * @returns self + */ + translate(vector) { + translate(this, this, vector); + return this.check(); + } + // Transforms + /** + * Transforms any 2, 3 or 4 element vector. 2 and 3 elements are treated as points + * @param vector + * @param result + * @returns self + */ + transform(vector, result) { + if (vector.length === 4) { + result = transformMat43(result || [-0, -0, -0, -0], vector, this); + checkVector(result, 4); + return result; + } + return this.transformAsPoint(vector, result); + } + /** + * Transforms any 2 or 3 element array as point (w implicitly 1) + * @param vector + * @param result + * @returns self + */ + transformAsPoint(vector, result) { + const { length: length4 } = vector; + let out; + switch (length4) { + case 2: + out = transformMat4(result || [-0, -0], vector, this); + break; + case 3: + out = transformMat42(result || [-0, -0, -0], vector, this); + break; + default: + throw new Error("Illegal vector"); + } + checkVector(out, vector.length); + return out; + } + /** + * Transforms any 2 or 3 element array as vector (w implicitly 0) + * @param vector + * @param result + * @returns self + */ + transformAsVector(vector, result) { + let out; + switch (vector.length) { + case 2: + out = vec2_transformMat4AsVector(result || [-0, -0], vector, this); + break; + case 3: + out = vec3_transformMat4AsVector(result || [-0, -0, -0], vector, this); + break; + default: + throw new Error("Illegal vector"); + } + checkVector(out, vector.length); + return out; + } + /** @deprecated */ + transformPoint(vector, result) { + return this.transformAsPoint(vector, result); + } + /** @deprecated */ + transformVector(vector, result) { + return this.transformAsPoint(vector, result); + } + /** @deprecated */ + transformDirection(vector, result) { + return this.transformAsVector(vector, result); + } + // three.js math API compatibility + makeRotationX(radians4) { + return this.identity().rotateX(radians4); + } + makeTranslation(x, y, z) { + return this.identity().translate([x, y, z]); + } + }; + var ZERO2; + var IDENTITY; + function getZeroMatrix() { + if (!ZERO2) { + ZERO2 = new Matrix4([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + Object.freeze(ZERO2); + } + return ZERO2; + } + function getIdentityMatrix() { + if (!IDENTITY) { + IDENTITY = new Matrix4(); + Object.freeze(IDENTITY); + } + return IDENTITY; + } + function checkRadians(possiblyDegrees) { + if (possiblyDegrees > Math.PI * 2) { + throw Error("expected radians"); + } + } + function computeInfinitePerspectiveOffCenter(result, left, right, bottom, top, near) { + const column0Row0 = 2 * near / (right - left); + const column1Row1 = 2 * near / (top - bottom); + const column2Row0 = (right + left) / (right - left); + const column2Row1 = (top + bottom) / (top - bottom); + const column2Row2 = -1; + const column2Row3 = -1; + const column3Row2 = -2 * near; + result[0] = column0Row0; + result[1] = 0; + result[2] = 0; + result[3] = 0; + result[4] = 0; + result[5] = column1Row1; + result[6] = 0; + result[7] = 0; + result[8] = column2Row0; + result[9] = column2Row1; + result[10] = column2Row2; + result[11] = column2Row3; + result[12] = 0; + result[13] = 0; + result[14] = column3Row2; + result[15] = 0; + return result; + } + + // node_modules/@luma.gl/shadertools/dist/modules/math/fp64/fp64-utils.js + function fp64ify(a, out = [], startIndex = 0) { + const hiPart = Math.fround(a); + const loPart = a - hiPart; + out[startIndex] = hiPart; + out[startIndex + 1] = loPart; + return out; + } + function fp64LowPart(a) { + return a - Math.fround(a); + } + function fp64ifyMatrix4(matrix) { + const matrixFP64 = new Float32Array(32); + for (let i = 0; i < 4; ++i) { + for (let j = 0; j < 4; ++j) { + const index2 = i * 4 + j; + fp64ify(matrix[j * 4 + i], matrixFP64, index2 * 2); + } + } + return matrixFP64; + } + + // node_modules/@luma.gl/shadertools/dist/lib/color/normalize-byte-colors.js + function resolveUseByteColors(useByteColors, defaultUseByteColors = true) { + return useByteColors ?? defaultUseByteColors; + } + function normalizeByteColor3(color2 = [0, 0, 0], useByteColors = true) { + if (!useByteColors) { + return [...color2]; + } + return color2.map((component) => component / 255); + } + function normalizeByteColor4(color2, useByteColors = true) { + const normalizedColor = normalizeByteColor3(color2.slice(0, 3), useByteColors); + const hasAlpha = Number.isFinite(color2[3]); + const alpha = hasAlpha ? color2[3] : 1; + return [ + normalizedColor[0], + normalizedColor[1], + normalizedColor[2], + useByteColors && hasAlpha ? alpha / 255 : alpha + ]; + } + + // node_modules/@luma.gl/shadertools/dist/modules/math/fp32/fp32.js + var fp32shader = ( + /* glsl */ + `#ifdef LUMA_FP32_TAN_PRECISION_WORKAROUND + +// All these functions are for substituting tan() function from Intel GPU only +const float TWO_PI = 6.2831854820251465; +const float PI_2 = 1.5707963705062866; +const float PI_16 = 0.1963495463132858; + +const float SIN_TABLE_0 = 0.19509032368659973; +const float SIN_TABLE_1 = 0.3826834261417389; +const float SIN_TABLE_2 = 0.5555702447891235; +const float SIN_TABLE_3 = 0.7071067690849304; + +const float COS_TABLE_0 = 0.9807852506637573; +const float COS_TABLE_1 = 0.9238795042037964; +const float COS_TABLE_2 = 0.8314695954322815; +const float COS_TABLE_3 = 0.7071067690849304; + +const float INVERSE_FACTORIAL_3 = 1.666666716337204e-01; // 1/3! +const float INVERSE_FACTORIAL_5 = 8.333333767950535e-03; // 1/5! +const float INVERSE_FACTORIAL_7 = 1.9841270113829523e-04; // 1/7! +const float INVERSE_FACTORIAL_9 = 2.75573188446287533e-06; // 1/9! + +float sin_taylor_fp32(float a) { + float r, s, t, x; + + if (a == 0.0) { + return 0.0; + } + + x = -a * a; + s = a; + r = a; + + r = r * x; + t = r * INVERSE_FACTORIAL_3; + s = s + t; + + r = r * x; + t = r * INVERSE_FACTORIAL_5; + s = s + t; + + r = r * x; + t = r * INVERSE_FACTORIAL_7; + s = s + t; + + r = r * x; + t = r * INVERSE_FACTORIAL_9; + s = s + t; + + return s; +} + +void sincos_taylor_fp32(float a, out float sin_t, out float cos_t) { + if (a == 0.0) { + sin_t = 0.0; + cos_t = 1.0; + } + sin_t = sin_taylor_fp32(a); + cos_t = sqrt(1.0 - sin_t * sin_t); +} + +float tan_taylor_fp32(float a) { + float sin_a; + float cos_a; + + if (a == 0.0) { + return 0.0; + } + + // 2pi range reduction + float z = floor(a / TWO_PI); + float r = a - TWO_PI * z; + + float t; + float q = floor(r / PI_2 + 0.5); + int j = int(q); + + if (j < -2 || j > 2) { + return 1.0 / 0.0; + } + + t = r - PI_2 * q; + + q = floor(t / PI_16 + 0.5); + int k = int(q); + int abs_k = int(abs(float(k))); + + if (abs_k > 4) { + return 1.0 / 0.0; + } else { + t = t - PI_16 * q; + } + + float u = 0.0; + float v = 0.0; + + float sin_t, cos_t; + float s, c; + sincos_taylor_fp32(t, sin_t, cos_t); + + if (k == 0) { + s = sin_t; + c = cos_t; + } else { + if (abs(float(abs_k) - 1.0) < 0.5) { + u = COS_TABLE_0; + v = SIN_TABLE_0; + } else if (abs(float(abs_k) - 2.0) < 0.5) { + u = COS_TABLE_1; + v = SIN_TABLE_1; + } else if (abs(float(abs_k) - 3.0) < 0.5) { + u = COS_TABLE_2; + v = SIN_TABLE_2; + } else if (abs(float(abs_k) - 4.0) < 0.5) { + u = COS_TABLE_3; + v = SIN_TABLE_3; + } + if (k > 0) { + s = u * sin_t + v * cos_t; + c = u * cos_t - v * sin_t; + } else { + s = u * sin_t - v * cos_t; + c = u * cos_t + v * sin_t; + } + } + + if (j == 0) { + sin_a = s; + cos_a = c; + } else if (j == 1) { + sin_a = c; + cos_a = -s; + } else if (j == -1) { + sin_a = -c; + cos_a = s; + } else { + sin_a = -s; + cos_a = -c; + } + return sin_a / cos_a; +} +#endif + +float tan_fp32(float a) { +#ifdef LUMA_FP32_TAN_PRECISION_WORKAROUND + return tan_taylor_fp32(a); +#else + return tan(a); +#endif +} +` + ); + var fp32 = { + name: "fp32", + vs: fp32shader + }; + + // node_modules/@luma.gl/shadertools/dist/modules/math/fp64/fp64-arithmetic-glsl.js + var fp64arithmeticShader = ( + /* glsl */ + ` +layout(std140) uniform fp64arithmeticUniforms { + uniform float ONE; + uniform float SPLIT; +} fp64; + +/* +About LUMA_FP64_CODE_ELIMINATION_WORKAROUND + +The purpose of this workaround is to prevent shader compilers from +optimizing away necessary arithmetic operations by swapping their sequences +or transform the equation to some 'equivalent' form. + +These helpers implement Dekker/Veltkamp-style error tracking. If the compiler +folds constants or reassociates the arithmetic, the high/low split can stop +tracking the rounding error correctly. That failure mode tends to look fine in +simple coordinate setup, but then breaks down inside iterative arithmetic such +as fp64 Mandelbrot loops. + +The method is to multiply an artifical variable, ONE, which will be known to +the compiler to be 1 only at runtime. The whole expression is then represented +as a polynomial with respective to ONE. In the coefficients of all terms, only one a +and one b should appear + +err = (a + b) * ONE^6 - a * ONE^5 - (a + b) * ONE^4 + a * ONE^3 - b - (a + b) * ONE^2 + a * ONE +*/ + +float prevent_fp64_optimization(float value) { +#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND) + return value + fp64.ONE * 0.0; +#else + return value; +#endif +} + +// Divide float number to high and low floats to extend fraction bits +vec2 split(float a) { + // Keep SPLIT as a runtime uniform so the compiler cannot fold the Dekker + // split into a constant expression and reassociate the recovery steps. + float split = prevent_fp64_optimization(fp64.SPLIT); + float t = prevent_fp64_optimization(a * split); + float temp = t - a; + float a_hi = t - temp; + float a_lo = a - a_hi; + return vec2(a_hi, a_lo); +} + +// Divide float number again when high float uses too many fraction bits +vec2 split2(vec2 a) { + vec2 b = split(a.x); + b.y += a.y; + return b; +} + +// Special sum operation when a > b +vec2 quickTwoSum(float a, float b) { +#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND) + float sum = (a + b) * fp64.ONE; + float err = b - (sum - a) * fp64.ONE; +#else + float sum = a + b; + float err = b - (sum - a); +#endif + return vec2(sum, err); +} + +// General sum operation +vec2 twoSum(float a, float b) { + float s = (a + b); +#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND) + float v = (s * fp64.ONE - a) * fp64.ONE; + float err = (a - (s - v) * fp64.ONE) * fp64.ONE * fp64.ONE * fp64.ONE + (b - v); +#else + float v = s - a; + float err = (a - (s - v)) + (b - v); +#endif + return vec2(s, err); +} + +vec2 twoSub(float a, float b) { + float s = (a - b); +#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND) + float v = (s * fp64.ONE - a) * fp64.ONE; + float err = (a - (s - v) * fp64.ONE) * fp64.ONE * fp64.ONE * fp64.ONE - (b + v); +#else + float v = s - a; + float err = (a - (s - v)) - (b + v); +#endif + return vec2(s, err); +} + +vec2 twoSqr(float a) { + float prod = a * a; + vec2 a_fp64 = split(a); +#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND) + float err = ((a_fp64.x * a_fp64.x - prod) * fp64.ONE + 2.0 * a_fp64.x * + a_fp64.y * fp64.ONE * fp64.ONE) + a_fp64.y * a_fp64.y * fp64.ONE * fp64.ONE * fp64.ONE; +#else + float err = ((a_fp64.x * a_fp64.x - prod) + 2.0 * a_fp64.x * a_fp64.y) + a_fp64.y * a_fp64.y; +#endif + return vec2(prod, err); +} + +vec2 twoProd(float a, float b) { + float prod = a * b; + vec2 a_fp64 = split(a); + vec2 b_fp64 = split(b); + // twoProd is especially sensitive because mul_fp64 and div_fp64 both depend + // on the split terms and cross terms staying in the original evaluation + // order. If the compiler folds or reassociates them, the low part tends to + // collapse to zero or NaN on some drivers. + float highProduct = prevent_fp64_optimization(a_fp64.x * b_fp64.x); + float crossProduct1 = prevent_fp64_optimization(a_fp64.x * b_fp64.y); + float crossProduct2 = prevent_fp64_optimization(a_fp64.y * b_fp64.x); + float lowProduct = prevent_fp64_optimization(a_fp64.y * b_fp64.y); +#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND) + float err1 = (highProduct - prod) * fp64.ONE; + float err2 = crossProduct1 * fp64.ONE * fp64.ONE; + float err3 = crossProduct2 * fp64.ONE * fp64.ONE * fp64.ONE; + float err4 = lowProduct * fp64.ONE * fp64.ONE * fp64.ONE * fp64.ONE; +#else + float err1 = highProduct - prod; + float err2 = crossProduct1; + float err3 = crossProduct2; + float err4 = lowProduct; +#endif + float err = ((err1 + err2) + err3) + err4; + return vec2(prod, err); +} + +vec2 sum_fp64(vec2 a, vec2 b) { + vec2 s, t; + s = twoSum(a.x, b.x); + t = twoSum(a.y, b.y); + s.y += t.x; + s = quickTwoSum(s.x, s.y); + s.y += t.y; + s = quickTwoSum(s.x, s.y); + return s; +} + +vec2 sub_fp64(vec2 a, vec2 b) { + vec2 s, t; + s = twoSub(a.x, b.x); + t = twoSub(a.y, b.y); + s.y += t.x; + s = quickTwoSum(s.x, s.y); + s.y += t.y; + s = quickTwoSum(s.x, s.y); + return s; +} + +vec2 mul_fp64(vec2 a, vec2 b) { + vec2 prod = twoProd(a.x, b.x); + // y component is for the error + prod.y += a.x * b.y; +#if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND) + prod = split2(prod); +#endif + prod = quickTwoSum(prod.x, prod.y); + prod.y += a.y * b.x; +#if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND) + prod = split2(prod); +#endif + prod = quickTwoSum(prod.x, prod.y); + return prod; +} + +vec2 div_fp64(vec2 a, vec2 b) { + float xn = 1.0 / b.x; +#if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND) + vec2 yn = mul_fp64(a, vec2(xn, 0)); +#else + vec2 yn = a * xn; +#endif + float diff = (sub_fp64(a, mul_fp64(b, yn))).x; + vec2 prod = twoProd(xn, diff); + return sum_fp64(yn, prod); +} + +vec2 sqrt_fp64(vec2 a) { + if (a.x == 0.0 && a.y == 0.0) return vec2(0.0, 0.0); + if (a.x < 0.0) return vec2(0.0 / 0.0, 0.0 / 0.0); + + float x = 1.0 / sqrt(a.x); + float yn = a.x * x; +#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND) + vec2 yn_sqr = twoSqr(yn) * fp64.ONE; +#else + vec2 yn_sqr = twoSqr(yn); +#endif + float diff = sub_fp64(a, yn_sqr).x; + vec2 prod = twoProd(x * 0.5, diff); +#if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND) + return sum_fp64(split(yn), prod); +#else + return sum_fp64(vec2(yn, 0.0), prod); +#endif +} +` + ); + + // node_modules/@luma.gl/shadertools/dist/modules/math/fp64/fp64-arithmetic-wgsl.js + var fp64arithmeticWGSL = ( + /* wgsl */ + `struct Fp64ArithmeticUniforms { + ONE: f32, + SPLIT: f32, +}; + +@group(0) @binding(auto) var fp64arithmetic : Fp64ArithmeticUniforms; + +fn fp64_nan(seed: f32) -> f32 { + let nanBits = 0x7fc00000u | select(0u, 1u, seed < 0.0); + return bitcast(nanBits); +} + +fn fp64_runtime_zero() -> f32 { + return fp64arithmetic.ONE * 0.0; +} + +fn prevent_fp64_optimization(value: f32) -> f32 { +#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND + return value + fp64_runtime_zero(); +#else + return value; +#endif +} + +fn split(a: f32) -> vec2f { + let splitValue = prevent_fp64_optimization(fp64arithmetic.SPLIT + fp64_runtime_zero()); + let t = prevent_fp64_optimization(a * splitValue); + let temp = prevent_fp64_optimization(t - a); + let aHi = prevent_fp64_optimization(t - temp); + let aLo = prevent_fp64_optimization(a - aHi); + return vec2f(aHi, aLo); +} + +fn split2(a: vec2f) -> vec2f { + var b = split(a.x); + b.y = b.y + a.y; + return b; +} + +fn quickTwoSum(a: f32, b: f32) -> vec2f { +#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND + let sum = prevent_fp64_optimization((a + b) * fp64arithmetic.ONE); + let err = prevent_fp64_optimization(b - (sum - a) * fp64arithmetic.ONE); +#else + let sum = prevent_fp64_optimization(a + b); + let err = prevent_fp64_optimization(b - (sum - a)); +#endif + return vec2f(sum, err); +} + +fn twoSum(a: f32, b: f32) -> vec2f { + let s = prevent_fp64_optimization(a + b); +#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND + let v = prevent_fp64_optimization((s * fp64arithmetic.ONE - a) * fp64arithmetic.ONE); + let err = + prevent_fp64_optimization((a - (s - v) * fp64arithmetic.ONE) * + fp64arithmetic.ONE * + fp64arithmetic.ONE * + fp64arithmetic.ONE) + + prevent_fp64_optimization(b - v); +#else + let v = prevent_fp64_optimization(s - a); + let err = prevent_fp64_optimization(a - (s - v)) + prevent_fp64_optimization(b - v); +#endif + return vec2f(s, err); +} + +fn twoSub(a: f32, b: f32) -> vec2f { + let s = prevent_fp64_optimization(a - b); +#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND + let v = prevent_fp64_optimization((s * fp64arithmetic.ONE - a) * fp64arithmetic.ONE); + let err = + prevent_fp64_optimization((a - (s - v) * fp64arithmetic.ONE) * + fp64arithmetic.ONE * + fp64arithmetic.ONE * + fp64arithmetic.ONE) - + prevent_fp64_optimization(b + v); +#else + let v = prevent_fp64_optimization(s - a); + let err = prevent_fp64_optimization(a - (s - v)) - prevent_fp64_optimization(b + v); +#endif + return vec2f(s, err); +} + +fn twoSqr(a: f32) -> vec2f { + let prod = prevent_fp64_optimization(a * a); + let aFp64 = split(a); + let highProduct = prevent_fp64_optimization(aFp64.x * aFp64.x); + let crossProduct = prevent_fp64_optimization(2.0 * aFp64.x * aFp64.y); + let lowProduct = prevent_fp64_optimization(aFp64.y * aFp64.y); +#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND + let err = + (prevent_fp64_optimization(highProduct - prod) * fp64arithmetic.ONE + + crossProduct * fp64arithmetic.ONE * fp64arithmetic.ONE) + + lowProduct * fp64arithmetic.ONE * fp64arithmetic.ONE * fp64arithmetic.ONE; +#else + let err = ((prevent_fp64_optimization(highProduct - prod) + crossProduct) + lowProduct); +#endif + return vec2f(prod, err); +} + +fn twoProd(a: f32, b: f32) -> vec2f { + let prod = prevent_fp64_optimization(a * b); + let aFp64 = split(a); + let bFp64 = split(b); + let highProduct = prevent_fp64_optimization(aFp64.x * bFp64.x); + let crossProduct1 = prevent_fp64_optimization(aFp64.x * bFp64.y); + let crossProduct2 = prevent_fp64_optimization(aFp64.y * bFp64.x); + let lowProduct = prevent_fp64_optimization(aFp64.y * bFp64.y); +#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND + let err1 = (highProduct - prod) * fp64arithmetic.ONE; + let err2 = crossProduct1 * fp64arithmetic.ONE * fp64arithmetic.ONE; + let err3 = crossProduct2 * fp64arithmetic.ONE * fp64arithmetic.ONE * fp64arithmetic.ONE; + let err4 = + lowProduct * + fp64arithmetic.ONE * + fp64arithmetic.ONE * + fp64arithmetic.ONE * + fp64arithmetic.ONE; +#else + let err1 = highProduct - prod; + let err2 = crossProduct1; + let err3 = crossProduct2; + let err4 = lowProduct; +#endif + let err12InputA = prevent_fp64_optimization(err1); + let err12InputB = prevent_fp64_optimization(err2); + let err12 = prevent_fp64_optimization(err12InputA + err12InputB); + let err123InputA = prevent_fp64_optimization(err12); + let err123InputB = prevent_fp64_optimization(err3); + let err123 = prevent_fp64_optimization(err123InputA + err123InputB); + let err1234InputA = prevent_fp64_optimization(err123); + let err1234InputB = prevent_fp64_optimization(err4); + let err = prevent_fp64_optimization(err1234InputA + err1234InputB); + return vec2f(prod, err); +} + +fn sum_fp64(a: vec2f, b: vec2f) -> vec2f { + var s = twoSum(a.x, b.x); + let t = twoSum(a.y, b.y); + s.y = prevent_fp64_optimization(s.y + t.x); + s = quickTwoSum(s.x, s.y); + s.y = prevent_fp64_optimization(s.y + t.y); + s = quickTwoSum(s.x, s.y); + return s; +} + +fn sub_fp64(a: vec2f, b: vec2f) -> vec2f { + var s = twoSub(a.x, b.x); + let t = twoSub(a.y, b.y); + s.y = prevent_fp64_optimization(s.y + t.x); + s = quickTwoSum(s.x, s.y); + s.y = prevent_fp64_optimization(s.y + t.y); + s = quickTwoSum(s.x, s.y); + return s; +} + +fn mul_fp64(a: vec2f, b: vec2f) -> vec2f { + var prod = twoProd(a.x, b.x); + let crossProduct1 = prevent_fp64_optimization(a.x * b.y); + prod.y = prevent_fp64_optimization(prod.y + crossProduct1); +#ifdef LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND + prod = split2(prod); +#endif + prod = quickTwoSum(prod.x, prod.y); + let crossProduct2 = prevent_fp64_optimization(a.y * b.x); + prod.y = prevent_fp64_optimization(prod.y + crossProduct2); +#ifdef LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND + prod = split2(prod); +#endif + prod = quickTwoSum(prod.x, prod.y); + return prod; +} + +fn div_fp64(a: vec2f, b: vec2f) -> vec2f { + let xn = prevent_fp64_optimization(1.0 / b.x); + let yn = mul_fp64(a, vec2f(xn, fp64_runtime_zero())); + let diff = prevent_fp64_optimization(sub_fp64(a, mul_fp64(b, yn)).x); + let prod = twoProd(xn, diff); + return sum_fp64(yn, prod); +} + +fn sqrt_fp64(a: vec2f) -> vec2f { + if (a.x == 0.0 && a.y == 0.0) { + return vec2f(0.0, 0.0); + } + if (a.x < 0.0) { + let nanValue = fp64_nan(a.x); + return vec2f(nanValue, nanValue); + } + + let x = prevent_fp64_optimization(1.0 / sqrt(a.x)); + let yn = prevent_fp64_optimization(a.x * x); +#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND + let ynSqr = twoSqr(yn) * fp64arithmetic.ONE; +#else + let ynSqr = twoSqr(yn); +#endif + let diff = prevent_fp64_optimization(sub_fp64(a, ynSqr).x); + let prod = twoProd(prevent_fp64_optimization(x * 0.5), diff); +#ifdef LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND + return sum_fp64(split(yn), prod); +#else + return sum_fp64(vec2f(yn, 0.0), prod); +#endif +} +` + ); + + // node_modules/@luma.gl/shadertools/dist/modules/math/fp64/fp64.js + var defaultUniforms = { + // Used in LUMA_FP64_CODE_ELIMINATION_WORKAROUND + ONE: 1, + // Runtime split factor for Dekker splitting. Keeping this as a uniform helps + // prevent aggressive constant folding in shader compilers. + SPLIT: 4097 + }; + var fp64arithmetic = { + name: "fp64arithmetic", + source: fp64arithmeticWGSL, + fs: fp64arithmeticShader, + vs: fp64arithmeticShader, + defaultUniforms, + uniformTypes: { ONE: "f32", SPLIT: "f32" }, + // Additional Functions + fp64ify, + fp64LowPart, + fp64ifyMatrix4 + }; + + // node_modules/@luma.gl/shadertools/dist/modules/engine/picking/picking.js + var DEFAULT_HIGHLIGHT_COLOR = [0, 1, 1, 1]; + var vs = ( + /* glsl */ + `layout(std140) uniform pickingUniforms { + float isActive; + float isAttribute; + float isHighlightActive; + float useByteColors; + vec3 highlightedObjectColor; + vec4 highlightColor; +} picking; + +out vec4 picking_vRGBcolor_Avalid; + +// Normalize unsigned byte color to 0-1 range +vec3 picking_normalizeColor(vec3 color) { + return picking.useByteColors > 0.5 ? color / 255.0 : color; +} + +// Normalize unsigned byte color to 0-1 range +vec4 picking_normalizeColor(vec4 color) { + return picking.useByteColors > 0.5 ? color / 255.0 : color; +} + +bool picking_isColorZero(vec3 color) { + return dot(color, vec3(1.0)) < 0.00001; +} + +bool picking_isColorValid(vec3 color) { + return dot(color, vec3(1.0)) > 0.00001; +} + +// Check if this vertex is highlighted +bool isVertexHighlighted(vec3 vertexColor) { + vec3 highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor); + return + bool(picking.isHighlightActive) && picking_isColorZero(abs(vertexColor - highlightedObjectColor)); +} + +// Set the current picking color +void picking_setPickingColor(vec3 pickingColor) { + pickingColor = picking_normalizeColor(pickingColor); + + if (bool(picking.isActive)) { + // Use alpha as the validity flag. If pickingColor is [0, 0, 0] fragment is non-pickable + picking_vRGBcolor_Avalid.a = float(picking_isColorValid(pickingColor)); + + if (!bool(picking.isAttribute)) { + // Stores the picking color so that the fragment shader can render it during picking + picking_vRGBcolor_Avalid.rgb = pickingColor; + } + } else { + // Do the comparison with selected item color in vertex shader as it should mean fewer compares + picking_vRGBcolor_Avalid.a = float(isVertexHighlighted(pickingColor)); + } +} + +void picking_setPickingAttribute(float value) { + if (bool(picking.isAttribute)) { + picking_vRGBcolor_Avalid.r = value; + } +} + +void picking_setPickingAttribute(vec2 value) { + if (bool(picking.isAttribute)) { + picking_vRGBcolor_Avalid.rg = value; + } +} + +void picking_setPickingAttribute(vec3 value) { + if (bool(picking.isAttribute)) { + picking_vRGBcolor_Avalid.rgb = value; + } +} +` + ); + var fs = ( + /* glsl */ + `layout(std140) uniform pickingUniforms { + float isActive; + float isAttribute; + float isHighlightActive; + float useByteColors; + vec3 highlightedObjectColor; + vec4 highlightColor; +} picking; + +in vec4 picking_vRGBcolor_Avalid; + +/* + * Returns highlight color if this item is selected. + */ +vec4 picking_filterHighlightColor(vec4 color) { + // If we are still picking, we don't highlight + if (picking.isActive > 0.5) { + return color; + } + + bool selected = bool(picking_vRGBcolor_Avalid.a); + + if (selected) { + // Blend in highlight color based on its alpha value + float highLightAlpha = picking.highlightColor.a; + float blendedAlpha = highLightAlpha + color.a * (1.0 - highLightAlpha); + float highLightRatio = highLightAlpha / blendedAlpha; + + vec3 blendedRGB = mix(color.rgb, picking.highlightColor.rgb, highLightRatio); + return vec4(blendedRGB, blendedAlpha); + } else { + return color; + } +} + +/* + * Returns picking color if picking enabled else unmodified argument. + */ +vec4 picking_filterPickingColor(vec4 color) { + if (bool(picking.isActive)) { + if (picking_vRGBcolor_Avalid.a == 0.0) { + discard; + } + return picking_vRGBcolor_Avalid; + } + return color; +} + +/* + * Returns picking color if picking is enabled if not + * highlight color if this item is selected, otherwise unmodified argument. + */ +vec4 picking_filterColor(vec4 color) { + vec4 highlightColor = picking_filterHighlightColor(color); + return picking_filterPickingColor(highlightColor); +} +` + ); + var picking = { + props: {}, + uniforms: {}, + name: "picking", + uniformTypes: { + isActive: "f32", + isAttribute: "f32", + isHighlightActive: "f32", + useByteColors: "f32", + highlightedObjectColor: "vec3", + highlightColor: "vec4" + }, + defaultUniforms: { + isActive: false, + isAttribute: false, + isHighlightActive: false, + useByteColors: true, + highlightedObjectColor: [0, 0, 0], + highlightColor: DEFAULT_HIGHLIGHT_COLOR + }, + vs, + fs, + getUniforms + }; + function getUniforms(opts = {}, prevUniforms) { + const uniforms = {}; + const useByteColors = resolveUseByteColors(opts.useByteColors, true); + if (opts.highlightedObjectColor === void 0) { + } else if (opts.highlightedObjectColor === null) { + uniforms.isHighlightActive = false; + } else { + uniforms.isHighlightActive = true; + const highlightedObjectColor = opts.highlightedObjectColor.slice(0, 3); + uniforms.highlightedObjectColor = highlightedObjectColor; + } + if (opts.highlightColor) { + uniforms.highlightColor = normalizeByteColor4(opts.highlightColor, useByteColors); + } + if (opts.isActive !== void 0) { + uniforms.isActive = Boolean(opts.isActive); + uniforms.isAttribute = Boolean(opts.isAttribute); + } + if (opts.useByteColors !== void 0) { + uniforms.useByteColors = Boolean(opts.useByteColors); + } + return uniforms; + } + + // node_modules/@deck.gl/core/dist/shaderlib/misc/layer-uniforms.js + var uniformBlockWGSL = ( + /* wgsl */ + `struct LayerUniforms { + opacity: f32, +}; + +@group(0) @binding(auto) +var layer: LayerUniforms; +` + ); + var uniformBlock = `layout(std140) uniform layerUniforms { + uniform float opacity; +} layer; +`; + var layerUniforms = { + name: "layer", + source: uniformBlockWGSL, + vs: uniformBlock, + fs: uniformBlock, + getUniforms: (props) => { + return { + // apply gamma to opacity to make it visually "linear" + // TODO - v10: use raw opacity? + opacity: Math.pow(props.opacity, 1 / 2.2) + }; + }, + uniformTypes: { + opacity: "f32" + } + }; + + // node_modules/@deck.gl/core/dist/shaderlib/color/color.js + var colorWGSL = ( + /* WGSL */ + ` + +@must_use +fn deckgl_premultiplied_alpha(fragColor: vec4) -> vec4 { + return vec4(fragColor.rgb * fragColor.a, fragColor.a); +}; +` + ); + var color_default = { + name: "color", + dependencies: [], + source: colorWGSL, + getUniforms: (_props) => { + return {}; + } + // @ts-ignore TODO v9.1 + }; + + // node_modules/@deck.gl/core/dist/shaderlib/misc/geometry.js + var source = ( + /* wgsl */ + `const SMOOTH_EDGE_RADIUS: f32 = 0.5; + +struct VertexGeometry { + position: vec4, + worldPosition: vec3, + worldPositionAlt: vec3, + normal: vec3, + uv: vec2, + pickingColor: vec3, +}; + +var geometry_: VertexGeometry = VertexGeometry( + vec4(0.0, 0.0, 1.0, 0.0), + vec3(0.0, 0.0, 0.0), + vec3(0.0, 0.0, 0.0), + vec3(0.0, 0.0, 0.0), + vec2(0.0, 0.0), + vec3(0.0, 0.0, 0.0) +); + +struct FragmentGeometry { + uv: vec2, +}; + +var fragmentGeometry: FragmentGeometry; + +fn smoothedge(edge: f32, x: f32) -> f32 { + return smoothstep(edge - SMOOTH_EDGE_RADIUS, edge + SMOOTH_EDGE_RADIUS, x); +} +` + ); + var defines = "#define SMOOTH_EDGE_RADIUS 0.5"; + var vs2 = ( + /* glsl */ + `${defines} + +struct VertexGeometry { + vec4 position; + vec3 worldPosition; + vec3 worldPositionAlt; + vec3 normal; + vec2 uv; + vec3 pickingColor; +} geometry = VertexGeometry( + vec4(0.0, 0.0, 1.0, 0.0), + vec3(0.0), + vec3(0.0), + vec3(0.0), + vec2(0.0), + vec3(0.0) +); +` + ); + var fs2 = ( + /* glsl */ + `${defines} + +struct FragmentGeometry { + vec2 uv; +} geometry; + +float smoothedge(float edge, float x) { + return smoothstep(edge - SMOOTH_EDGE_RADIUS, edge + SMOOTH_EDGE_RADIUS, x); +} +` + ); + var geometry_default = { + name: "geometry", + source, + vs: vs2, + fs: fs2 + }; + + // node_modules/mjolnir.js/dist/hammerjs/input/input-consts.js + var COMPUTE_INTERVAL = 25; + var InputEvent; + (function(InputEvent2) { + InputEvent2[InputEvent2["Start"] = 1] = "Start"; + InputEvent2[InputEvent2["Move"] = 2] = "Move"; + InputEvent2[InputEvent2["End"] = 4] = "End"; + InputEvent2[InputEvent2["Cancel"] = 8] = "Cancel"; + })(InputEvent || (InputEvent = {})); + var InputDirection; + (function(InputDirection2) { + InputDirection2[InputDirection2["None"] = 0] = "None"; + InputDirection2[InputDirection2["Left"] = 1] = "Left"; + InputDirection2[InputDirection2["Right"] = 2] = "Right"; + InputDirection2[InputDirection2["Up"] = 4] = "Up"; + InputDirection2[InputDirection2["Down"] = 8] = "Down"; + InputDirection2[InputDirection2["Horizontal"] = 3] = "Horizontal"; + InputDirection2[InputDirection2["Vertical"] = 12] = "Vertical"; + InputDirection2[InputDirection2["All"] = 15] = "All"; + })(InputDirection || (InputDirection = {})); + + // node_modules/mjolnir.js/dist/hammerjs/recognizer/recognizer-state.js + var RecognizerState; + (function(RecognizerState2) { + RecognizerState2[RecognizerState2["Possible"] = 1] = "Possible"; + RecognizerState2[RecognizerState2["Began"] = 2] = "Began"; + RecognizerState2[RecognizerState2["Changed"] = 4] = "Changed"; + RecognizerState2[RecognizerState2["Ended"] = 8] = "Ended"; + RecognizerState2[RecognizerState2["Recognized"] = 8] = "Recognized"; + RecognizerState2[RecognizerState2["Cancelled"] = 16] = "Cancelled"; + RecognizerState2[RecognizerState2["Failed"] = 32] = "Failed"; + })(RecognizerState || (RecognizerState = {})); + + // node_modules/mjolnir.js/dist/hammerjs/touchaction/touchaction-Consts.js + var TOUCH_ACTION_COMPUTE = "compute"; + var TOUCH_ACTION_AUTO = "auto"; + var TOUCH_ACTION_MANIPULATION = "manipulation"; + var TOUCH_ACTION_NONE = "none"; + var TOUCH_ACTION_PAN_X = "pan-x"; + var TOUCH_ACTION_PAN_Y = "pan-y"; + + // node_modules/mjolnir.js/dist/hammerjs/touchaction/clean-touch-actions.js + function cleanTouchActions(actions) { + if (actions.includes(TOUCH_ACTION_NONE)) { + return TOUCH_ACTION_NONE; + } + const hasPanX = actions.includes(TOUCH_ACTION_PAN_X); + const hasPanY = actions.includes(TOUCH_ACTION_PAN_Y); + if (hasPanX && hasPanY) { + return TOUCH_ACTION_NONE; + } + if (hasPanX || hasPanY) { + return hasPanX ? TOUCH_ACTION_PAN_X : TOUCH_ACTION_PAN_Y; + } + if (actions.includes(TOUCH_ACTION_MANIPULATION)) { + return TOUCH_ACTION_MANIPULATION; + } + return TOUCH_ACTION_AUTO; + } + + // node_modules/mjolnir.js/dist/hammerjs/touchaction/touchaction.js + var TouchAction = class { + constructor(manager, value) { + this.actions = ""; + this.manager = manager; + this.set(value); + } + /** + * set the touchAction value on the element or enable the polyfill + */ + set(value) { + if (value === TOUCH_ACTION_COMPUTE) { + value = this.compute(); + } + if (this.manager.element) { + this.manager.element.style.touchAction = value; + this.actions = value; + } + } + /** + * just re-set the touchAction value + */ + update() { + this.set(this.manager.options.touchAction); + } + /** + * compute the value for the touchAction property based on the recognizer's settings + */ + compute() { + let actions = []; + for (const recognizer of this.manager.recognizers) { + if (recognizer.options.enable) { + actions = actions.concat(recognizer.getTouchAction()); + } + } + return cleanTouchActions(actions.join(" ")); + } + }; + + // node_modules/mjolnir.js/dist/hammerjs/utils/split-str.js + function splitStr(str5) { + return str5.trim().split(/\s+/g); + } + + // node_modules/mjolnir.js/dist/hammerjs/utils/event-listeners.js + function addEventListeners(target2, types, handler) { + if (!target2) { + return; + } + for (const type of splitStr(types)) { + target2.addEventListener(type, handler, false); + } + } + function removeEventListeners(target2, types, handler) { + if (!target2) { + return; + } + for (const type of splitStr(types)) { + target2.removeEventListener(type, handler, false); + } + } + + // node_modules/mjolnir.js/dist/hammerjs/utils/get-window-for-element.js + function getWindowForElement(element) { + const doc = element.ownerDocument || element; + return doc.defaultView; + } + + // node_modules/mjolnir.js/dist/hammerjs/utils/has-parent.js + function hasParent(node, parent) { + let ancestor = node; + while (ancestor) { + if (ancestor === parent) { + return true; + } + ancestor = ancestor.parentNode; + } + return false; + } + + // node_modules/mjolnir.js/dist/hammerjs/input/get-center.js + function getCenter(pointers) { + const pointersLength = pointers.length; + if (pointersLength === 1) { + return { + x: Math.round(pointers[0].clientX), + y: Math.round(pointers[0].clientY) + }; + } + let x = 0; + let y = 0; + let i = 0; + while (i < pointersLength) { + x += pointers[i].clientX; + y += pointers[i].clientY; + i++; + } + return { + x: Math.round(x / pointersLength), + y: Math.round(y / pointersLength) + }; + } + + // node_modules/mjolnir.js/dist/hammerjs/input/simple-clone-input-data.js + function simpleCloneInputData(input) { + const pointers = []; + let i = 0; + while (i < input.pointers.length) { + pointers[i] = { + clientX: Math.round(input.pointers[i].clientX), + clientY: Math.round(input.pointers[i].clientY) + }; + i++; + } + return { + timeStamp: Date.now(), + pointers, + center: getCenter(pointers), + deltaX: input.deltaX, + deltaY: input.deltaY + }; + } + + // node_modules/mjolnir.js/dist/hammerjs/input/get-distance.js + function getPointDistance(p1, p2) { + const x = p2.x - p1.x; + const y = p2.y - p1.y; + return Math.sqrt(x * x + y * y); + } + function getEventDistance(p1, p2) { + const x = p2.clientX - p1.clientX; + const y = p2.clientY - p1.clientY; + return Math.sqrt(x * x + y * y); + } + + // node_modules/mjolnir.js/dist/hammerjs/input/get-angle.js + function getPointAngle(p1, p2) { + const x = p2.x - p1.x; + const y = p2.y - p1.y; + return Math.atan2(y, x) * 180 / Math.PI; + } + function getEventAngle(p1, p2) { + const x = p2.clientX - p1.clientX; + const y = p2.clientY - p1.clientY; + return Math.atan2(y, x) * 180 / Math.PI; + } + + // node_modules/mjolnir.js/dist/hammerjs/input/get-direction.js + function getDirection(dx, dy) { + if (dx === dy) { + return InputDirection.None; + } + if (Math.abs(dx) >= Math.abs(dy)) { + return dx < 0 ? InputDirection.Left : InputDirection.Right; + } + return dy < 0 ? InputDirection.Up : InputDirection.Down; + } + + // node_modules/mjolnir.js/dist/hammerjs/input/get-delta-xy.js + function computeDeltaXY(session, input) { + const center = input.center; + let offset = session.offsetDelta; + let prevDelta = session.prevDelta; + const prevInput = session.prevInput; + if (input.eventType === InputEvent.Start || prevInput?.eventType === InputEvent.End) { + prevDelta = session.prevDelta = { + x: prevInput?.deltaX || 0, + y: prevInput?.deltaY || 0 + }; + offset = session.offsetDelta = { + x: center.x, + y: center.y + }; + } + return { + deltaX: prevDelta.x + (center.x - offset.x), + deltaY: prevDelta.y + (center.y - offset.y) + }; + } + + // node_modules/mjolnir.js/dist/hammerjs/input/get-velocity.js + function getVelocity(deltaTime, x, y) { + return { + x: x / deltaTime || 0, + y: y / deltaTime || 0 + }; + } + + // node_modules/mjolnir.js/dist/hammerjs/input/get-scale.js + function getScale(start, end) { + return getEventDistance(end[0], end[1]) / getEventDistance(start[0], start[1]); + } + + // node_modules/mjolnir.js/dist/hammerjs/input/get-rotation.js + function getRotation2(start, end) { + return getEventAngle(end[1], end[0]) - getEventAngle(start[1], start[0]); + } + + // node_modules/mjolnir.js/dist/hammerjs/input/compute-interval-input-data.js + function computeIntervalInputData(session, input) { + const last = session.lastInterval || input; + const deltaTime = input.timeStamp - last.timeStamp; + let velocity; + let velocityX; + let velocityY; + let direction; + if (input.eventType !== InputEvent.Cancel && (deltaTime > COMPUTE_INTERVAL || last.velocity === void 0)) { + const deltaX = input.deltaX - last.deltaX; + const deltaY = input.deltaY - last.deltaY; + const v = getVelocity(deltaTime, deltaX, deltaY); + velocityX = v.x; + velocityY = v.y; + velocity = Math.abs(v.x) > Math.abs(v.y) ? v.x : v.y; + direction = getDirection(deltaX, deltaY); + session.lastInterval = input; + } else { + velocity = last.velocity; + velocityX = last.velocityX; + velocityY = last.velocityY; + direction = last.direction; + } + input.velocity = velocity; + input.velocityX = velocityX; + input.velocityY = velocityY; + input.direction = direction; + } + + // node_modules/mjolnir.js/dist/hammerjs/input/compute-input-data.js + function computeInputData(manager, input) { + const { session } = manager; + const { pointers } = input; + const { length: pointersLength } = pointers; + if (!session.firstInput) { + session.firstInput = simpleCloneInputData(input); + } + if (pointersLength > 1 && !session.firstMultiple) { + session.firstMultiple = simpleCloneInputData(input); + } else if (pointersLength === 1) { + session.firstMultiple = false; + } + const { firstInput, firstMultiple } = session; + const offsetCenter = firstMultiple ? firstMultiple.center : firstInput.center; + const center = input.center = getCenter(pointers); + input.timeStamp = Date.now(); + input.deltaTime = input.timeStamp - firstInput.timeStamp; + input.angle = getPointAngle(offsetCenter, center); + input.distance = getPointDistance(offsetCenter, center); + const { deltaX, deltaY } = computeDeltaXY(session, input); + input.deltaX = deltaX; + input.deltaY = deltaY; + input.offsetDirection = getDirection(input.deltaX, input.deltaY); + const overallVelocity = getVelocity(input.deltaTime, input.deltaX, input.deltaY); + input.overallVelocityX = overallVelocity.x; + input.overallVelocityY = overallVelocity.y; + input.overallVelocity = Math.abs(overallVelocity.x) > Math.abs(overallVelocity.y) ? overallVelocity.x : overallVelocity.y; + input.scale = firstMultiple ? getScale(firstMultiple.pointers, pointers) : 1; + input.rotation = firstMultiple ? getRotation2(firstMultiple.pointers, pointers) : 0; + input.maxPointers = !session.prevInput ? input.pointers.length : input.pointers.length > session.prevInput.maxPointers ? input.pointers.length : session.prevInput.maxPointers; + let target2 = manager.element; + if (hasParent(input.srcEvent.target, target2)) { + target2 = input.srcEvent.target; + } + input.target = target2; + computeIntervalInputData(session, input); + return input; + } + + // node_modules/mjolnir.js/dist/hammerjs/input/input-handler.js + function inputHandler(manager, eventType, input) { + const pointersLen = input.pointers.length; + const changedPointersLen = input.changedPointers.length; + const isFirst = eventType & InputEvent.Start && pointersLen - changedPointersLen === 0; + const isFinal = eventType & (InputEvent.End | InputEvent.Cancel) && pointersLen - changedPointersLen === 0; + input.isFirst = Boolean(isFirst); + input.isFinal = Boolean(isFinal); + if (isFirst) { + manager.session = {}; + } + input.eventType = eventType; + const processedInput = computeInputData(manager, input); + manager.emit("hammer.input", processedInput); + manager.recognize(processedInput); + manager.session.prevInput = processedInput; + } + + // node_modules/mjolnir.js/dist/hammerjs/input/input.js + var Input = class { + constructor(manager) { + this.evEl = ""; + this.evWin = ""; + this.evTarget = ""; + this.domHandler = (ev) => { + if (this.manager.options.enable) { + this.handler(ev); + } + }; + this.manager = manager; + this.element = manager.element; + this.target = manager.options.inputTarget || manager.element; + } + callback(eventType, input) { + inputHandler(this.manager, eventType, input); + } + // eslint-disable @typescript-eslint/unbound-method + /** + * bind the events + */ + init() { + addEventListeners(this.element, this.evEl, this.domHandler); + addEventListeners(this.target, this.evTarget, this.domHandler); + addEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler); + } + /** + * unbind the events + */ + destroy() { + removeEventListeners(this.element, this.evEl, this.domHandler); + removeEventListeners(this.target, this.evTarget, this.domHandler); + removeEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler); + } + }; + + // node_modules/mjolnir.js/dist/hammerjs/inputs/pointerevent.js + var POINTER_INPUT_MAP = { + pointerdown: InputEvent.Start, + pointermove: InputEvent.Move, + pointerup: InputEvent.End, + pointercancel: InputEvent.Cancel, + pointerout: InputEvent.Cancel + }; + var POINTER_ELEMENT_EVENTS = "pointerdown"; + var POINTER_WINDOW_EVENTS = "pointermove pointerup pointercancel"; + var PointerEventInput = class extends Input { + constructor(manager) { + super(manager); + this.evEl = POINTER_ELEMENT_EVENTS; + this.evWin = POINTER_WINDOW_EVENTS; + this.store = this.manager.session.pointerEvents = []; + this.init(); + } + /** + * handle mouse events + */ + handler(ev) { + const { store } = this; + let removePointer = false; + const eventType = POINTER_INPUT_MAP[ev.type]; + const pointerType = ev.pointerType; + const isTouch = pointerType === "touch"; + let storeIndex = store.findIndex((e) => e.pointerId === ev.pointerId); + if (eventType & InputEvent.Start && (ev.buttons || isTouch)) { + if (storeIndex < 0) { + store.push(ev); + storeIndex = store.length - 1; + } + } else if (eventType & (InputEvent.End | InputEvent.Cancel)) { + removePointer = true; + } + if (storeIndex < 0) { + return; + } + store[storeIndex] = ev; + this.callback(eventType, { + pointers: store, + changedPointers: [ev], + eventType, + pointerType, + srcEvent: ev + }); + if (removePointer) { + store.splice(storeIndex, 1); + } + } + }; + + // node_modules/mjolnir.js/dist/hammerjs/utils/prefixed.js + var VENDOR_PREFIXES = ["", "webkit", "Moz", "MS", "ms", "o"]; + function prefixed(obj, property) { + const camelProp = property[0].toUpperCase() + property.slice(1); + for (const prefix of VENDOR_PREFIXES) { + const prop = prefix ? prefix + camelProp : property; + if (prop in obj) { + return prop; + } + } + return void 0; + } + + // node_modules/mjolnir.js/dist/hammerjs/manager.js + var STOP = 1; + var FORCED_STOP = 2; + var defaultOptions = { + touchAction: "compute", + enable: true, + inputTarget: null, + cssProps: { + /** + * Disables text selection to improve the dragging gesture. Mainly for desktop browsers. + */ + userSelect: "none", + /** + * (Webkit) Disable default dragging behavior + */ + // @ts-ignore + userDrag: "none", + /** + * (iOS only) Disables the default callout shown when you touch and hold a touch target. + * When you touch and hold a touch target such as a link, Safari displays + * a callout containing information about the link. This property allows you to disable that callout. + */ + // @ts-ignore + touchCallout: "none", + /** + * (iOS only) Sets the color of the highlight that appears over a link while it's being tapped. + */ + // @ts-ignore + tapHighlightColor: "rgba(0,0,0,0)" + } + }; + var Manager = class { + constructor(element, options) { + this.options = { + ...defaultOptions, + ...options, + cssProps: { ...defaultOptions.cssProps, ...options.cssProps }, + inputTarget: options.inputTarget || element + }; + this.handlers = {}; + this.session = {}; + this.recognizers = []; + this.oldCssProps = {}; + this.element = element; + this.input = new PointerEventInput(this); + this.touchAction = new TouchAction(this, this.options.touchAction); + this.toggleCssProps(true); + } + /** + * set options + */ + set(options) { + Object.assign(this.options, options); + if (options.touchAction) { + this.touchAction.update(); + } + if (options.inputTarget) { + this.input.destroy(); + this.input.target = options.inputTarget; + this.input.init(); + } + return this; + } + /** + * stop recognizing for this session. + * This session will be discarded, when a new [input]start event is fired. + * When forced, the recognizer cycle is stopped immediately. + */ + stop(force) { + this.session.stopped = force ? FORCED_STOP : STOP; + } + /** + * run the recognizers! + * called by the inputHandler function on every movement of the pointers (touches) + * it walks through all the recognizers and tries to detect the gesture that is being made + */ + recognize(inputData) { + const { session } = this; + if (session.stopped) { + return; + } + if (this.session.prevented) { + inputData.srcEvent.preventDefault(); + } + let recognizer; + const { recognizers } = this; + let { curRecognizer } = session; + if (!curRecognizer || curRecognizer && curRecognizer.state & RecognizerState.Recognized) { + curRecognizer = session.curRecognizer = null; + } + let i = 0; + while (i < recognizers.length) { + recognizer = recognizers[i]; + if (session.stopped !== FORCED_STOP && // 1 + (!curRecognizer || recognizer === curRecognizer || // 2 + recognizer.canRecognizeWith(curRecognizer))) { + recognizer.recognize(inputData); + } else { + recognizer.reset(); + } + if (!curRecognizer && recognizer.state & (RecognizerState.Began | RecognizerState.Changed | RecognizerState.Ended)) { + curRecognizer = session.curRecognizer = recognizer; + } + i++; + } + } + /** + * get a recognizer by its event name. + */ + get(recognizerName) { + const { recognizers } = this; + for (let i = 0; i < recognizers.length; i++) { + if (recognizers[i].options.event === recognizerName) { + return recognizers[i]; + } + } + return null; + } + /** + * add a recognizer to the manager + * existing recognizers with the same event name will be removed + */ + add(recognizer) { + if (Array.isArray(recognizer)) { + for (const item of recognizer) { + this.add(item); + } + return this; + } + const existing = this.get(recognizer.options.event); + if (existing) { + this.remove(existing); + } + this.recognizers.push(recognizer); + recognizer.manager = this; + this.touchAction.update(); + return recognizer; + } + /** + * remove a recognizer by name or instance + */ + remove(recognizerOrName) { + if (Array.isArray(recognizerOrName)) { + for (const item of recognizerOrName) { + this.remove(item); + } + return this; + } + const recognizer = typeof recognizerOrName === "string" ? this.get(recognizerOrName) : recognizerOrName; + if (recognizer) { + const { recognizers } = this; + const index2 = recognizers.indexOf(recognizer); + if (index2 !== -1) { + recognizers.splice(index2, 1); + this.touchAction.update(); + } + } + return this; + } + /** + * bind event + */ + on(events, handler) { + if (!events || !handler) { + return; + } + const { handlers } = this; + for (const event of splitStr(events)) { + handlers[event] = handlers[event] || []; + handlers[event].push(handler); + } + } + /** + * unbind event, leave hander blank to remove all handlers + */ + off(events, handler) { + if (!events) { + return; + } + const { handlers } = this; + for (const event of splitStr(events)) { + if (!handler) { + delete handlers[event]; + } else if (handlers[event]) { + handlers[event].splice(handlers[event].indexOf(handler), 1); + } + } + } + /** + * emit event to the listeners + */ + emit(event, data) { + const handlers = this.handlers[event] && this.handlers[event].slice(); + if (!handlers || !handlers.length) { + return; + } + const evt = data; + evt.type = event; + evt.preventDefault = function() { + data.srcEvent.preventDefault(); + }; + let i = 0; + while (i < handlers.length) { + handlers[i](evt); + i++; + } + } + /** + * destroy the manager and unbinds all events + * it doesn't unbind dom events, that is the user own responsibility + */ + destroy() { + this.toggleCssProps(false); + this.handlers = {}; + this.session = {}; + this.input.destroy(); + this.element = null; + } + /** + * add/remove the css properties as defined in manager.options.cssProps + */ + toggleCssProps(add6) { + const { element } = this; + if (!element) { + return; + } + for (const [name2, value] of Object.entries(this.options.cssProps)) { + const prop = prefixed(element.style, name2); + if (add6) { + this.oldCssProps[prop] = element.style[prop]; + element.style[prop] = value; + } else { + element.style[prop] = this.oldCssProps[prop] || ""; + } + } + if (!add6) { + this.oldCssProps = {}; + } + } + }; + + // node_modules/mjolnir.js/dist/hammerjs/utils/unique-id.js + var _uniqueId = 1; + function uniqueId() { + return _uniqueId++; + } + + // node_modules/mjolnir.js/dist/hammerjs/recognizer/state-str.js + function stateStr(state) { + if (state & RecognizerState.Cancelled) { + return "cancel"; + } else if (state & RecognizerState.Ended) { + return "end"; + } else if (state & RecognizerState.Changed) { + return "move"; + } else if (state & RecognizerState.Began) { + return "start"; + } + return ""; + } + + // node_modules/mjolnir.js/dist/hammerjs/recognizer/recognizer.js + var Recognizer = class { + constructor(options) { + this.options = options; + this.id = uniqueId(); + this.state = RecognizerState.Possible; + this.simultaneous = {}; + this.requireFail = []; + } + /** + * set options + */ + set(options) { + Object.assign(this.options, options); + this.manager.touchAction.update(); + return this; + } + /** + * recognize simultaneous with an other recognizer. + */ + recognizeWith(recognizerOrName) { + if (Array.isArray(recognizerOrName)) { + for (const item of recognizerOrName) { + this.recognizeWith(item); + } + return this; + } + let otherRecognizer; + if (typeof recognizerOrName === "string") { + otherRecognizer = this.manager.get(recognizerOrName); + if (!otherRecognizer) { + throw new Error(`Cannot find recognizer ${recognizerOrName}`); + } + } else { + otherRecognizer = recognizerOrName; + } + const { simultaneous } = this; + if (!simultaneous[otherRecognizer.id]) { + simultaneous[otherRecognizer.id] = otherRecognizer; + otherRecognizer.recognizeWith(this); + } + return this; + } + /** + * drop the simultaneous link. it doesnt remove the link on the other recognizer. + */ + dropRecognizeWith(recognizerOrName) { + if (Array.isArray(recognizerOrName)) { + for (const item of recognizerOrName) { + this.dropRecognizeWith(item); + } + return this; + } + let otherRecognizer; + if (typeof recognizerOrName === "string") { + otherRecognizer = this.manager.get(recognizerOrName); + } else { + otherRecognizer = recognizerOrName; + } + if (otherRecognizer) { + delete this.simultaneous[otherRecognizer.id]; + } + return this; + } + /** + * recognizer can only run when an other is failing + */ + requireFailure(recognizerOrName) { + if (Array.isArray(recognizerOrName)) { + for (const item of recognizerOrName) { + this.requireFailure(item); + } + return this; + } + let otherRecognizer; + if (typeof recognizerOrName === "string") { + otherRecognizer = this.manager.get(recognizerOrName); + if (!otherRecognizer) { + throw new Error(`Cannot find recognizer ${recognizerOrName}`); + } + } else { + otherRecognizer = recognizerOrName; + } + const { requireFail } = this; + if (requireFail.indexOf(otherRecognizer) === -1) { + requireFail.push(otherRecognizer); + otherRecognizer.requireFailure(this); + } + return this; + } + /** + * drop the requireFailure link. it does not remove the link on the other recognizer. + */ + dropRequireFailure(recognizerOrName) { + if (Array.isArray(recognizerOrName)) { + for (const item of recognizerOrName) { + this.dropRequireFailure(item); + } + return this; + } + let otherRecognizer; + if (typeof recognizerOrName === "string") { + otherRecognizer = this.manager.get(recognizerOrName); + } else { + otherRecognizer = recognizerOrName; + } + if (otherRecognizer) { + const index2 = this.requireFail.indexOf(otherRecognizer); + if (index2 > -1) { + this.requireFail.splice(index2, 1); + } + } + return this; + } + /** + * has require failures boolean + */ + hasRequireFailures() { + return Boolean(this.requireFail.find((recognier) => recognier.options.enable)); + } + /** + * if the recognizer can recognize simultaneous with an other recognizer + */ + canRecognizeWith(otherRecognizer) { + return Boolean(this.simultaneous[otherRecognizer.id]); + } + /** + * You should use `tryEmit` instead of `emit` directly to check + * that all the needed recognizers has failed before emitting. + */ + emit(input) { + if (!input) + return; + const { state } = this; + if (state < RecognizerState.Ended) { + this.manager.emit(this.options.event + stateStr(state), input); + } + this.manager.emit(this.options.event, input); + if (input.additionalEvent) { + this.manager.emit(input.additionalEvent, input); + } + if (state >= RecognizerState.Ended) { + this.manager.emit(this.options.event + stateStr(state), input); + } + } + /** + * Check that all the require failure recognizers has failed, + * if true, it emits a gesture event, + * otherwise, setup the state to FAILED. + */ + tryEmit(input) { + if (this.canEmit()) { + this.emit(input); + } else { + this.state = RecognizerState.Failed; + } + } + /** + * can we emit? + */ + canEmit() { + let i = 0; + while (i < this.requireFail.length) { + if (!(this.requireFail[i].state & (RecognizerState.Failed | RecognizerState.Possible))) { + return false; + } + i++; + } + return true; + } + /** + * update the recognizer + */ + recognize(inputData) { + const inputDataClone = { ...inputData }; + if (!this.options.enable) { + this.reset(); + this.state = RecognizerState.Failed; + return; + } + if (this.state & (RecognizerState.Recognized | RecognizerState.Cancelled | RecognizerState.Failed)) { + this.state = RecognizerState.Possible; + } + this.state = this.process(inputDataClone); + if (this.state & (RecognizerState.Began | RecognizerState.Changed | RecognizerState.Ended | RecognizerState.Cancelled)) { + this.tryEmit(inputDataClone); + } + } + /** + * return the event names that are emitted by this recognizer + */ + getEventNames() { + return [this.options.event]; + } + /** + * called when the gesture isn't allowed to recognize + * like when another is being recognized or it is disabled + */ + reset() { + } + }; + + // node_modules/mjolnir.js/dist/hammerjs/recognizers/attribute.js + var AttrRecognizer = class extends Recognizer { + /** + * Used to check if it the recognizer receives valid input, like input.distance > 10. + */ + attrTest(input) { + const optionPointers = this.options.pointers; + return optionPointers === 0 || input.pointers.length === optionPointers; + } + /** + * Process the input and return the state for the recognizer + */ + process(input) { + const { state } = this; + const { eventType } = input; + const isRecognized = state & (RecognizerState.Began | RecognizerState.Changed); + const isValid = this.attrTest(input); + if (isRecognized && (eventType & InputEvent.Cancel || !isValid)) { + return state | RecognizerState.Cancelled; + } else if (isRecognized || isValid) { + if (eventType & InputEvent.End) { + return state | RecognizerState.Ended; + } else if (!(state & RecognizerState.Began)) { + return RecognizerState.Began; + } + return state | RecognizerState.Changed; + } + return RecognizerState.Failed; + } + }; + + // node_modules/mjolnir.js/dist/hammerjs/recognizers/tap.js + var TapRecognizer = class extends Recognizer { + constructor(options = {}) { + super({ + enable: true, + event: "tap", + pointers: 1, + taps: 1, + interval: 300, + time: 250, + threshold: 9, + posThreshold: 10, + ...options + }); + this.pTime = null; + this.pCenter = null; + this._timer = null; + this._input = null; + this.count = 0; + } + getTouchAction() { + return [TOUCH_ACTION_MANIPULATION]; + } + process(input) { + const { options } = this; + const validPointers = input.pointers.length === options.pointers; + const validMovement = input.distance < options.threshold; + const validTouchTime = input.deltaTime < options.time; + this.reset(); + if (input.eventType & InputEvent.Start && this.count === 0) { + return this.failTimeout(); + } + if (validMovement && validTouchTime && validPointers) { + if (input.eventType !== InputEvent.End) { + return this.failTimeout(); + } + const validInterval = this.pTime ? input.timeStamp - this.pTime < options.interval : true; + const validMultiTap = !this.pCenter || getPointDistance(this.pCenter, input.center) < options.posThreshold; + this.pTime = input.timeStamp; + this.pCenter = input.center; + if (!validMultiTap || !validInterval) { + this.count = 1; + } else { + this.count += 1; + } + this._input = input; + const tapCount = this.count % options.taps; + if (tapCount === 0) { + if (!this.hasRequireFailures()) { + return RecognizerState.Recognized; + } + this._timer = setTimeout(() => { + this.state = RecognizerState.Recognized; + this.tryEmit(this._input); + }, options.interval); + return RecognizerState.Began; + } + } + return RecognizerState.Failed; + } + failTimeout() { + this._timer = setTimeout(() => { + this.state = RecognizerState.Failed; + }, this.options.interval); + return RecognizerState.Failed; + } + reset() { + clearTimeout(this._timer); + } + emit(input) { + if (this.state === RecognizerState.Recognized) { + input.tapCount = this.count; + this.manager.emit(this.options.event, input); + } + } + }; + + // node_modules/mjolnir.js/dist/hammerjs/recognizers/pan.js + var EVENT_NAMES = ["", "start", "move", "end", "cancel", "up", "down", "left", "right"]; + var PanRecognizer = class extends AttrRecognizer { + constructor(options = {}) { + super({ + enable: true, + pointers: 1, + event: "pan", + threshold: 10, + direction: InputDirection.All, + ...options + }); + this.pX = null; + this.pY = null; + } + getTouchAction() { + const { options: { direction } } = this; + const actions = []; + if (direction & InputDirection.Horizontal) { + actions.push(TOUCH_ACTION_PAN_Y); + } + if (direction & InputDirection.Vertical) { + actions.push(TOUCH_ACTION_PAN_X); + } + return actions; + } + getEventNames() { + return EVENT_NAMES.map((suffix) => this.options.event + suffix); + } + directionTest(input) { + const { options } = this; + let hasMoved = true; + let { distance: distance5 } = input; + let { direction } = input; + const x = input.deltaX; + const y = input.deltaY; + if (!(direction & options.direction)) { + if (options.direction & InputDirection.Horizontal) { + direction = x === 0 ? InputDirection.None : x < 0 ? InputDirection.Left : InputDirection.Right; + hasMoved = x !== this.pX; + distance5 = Math.abs(input.deltaX); + } else { + direction = y === 0 ? InputDirection.None : y < 0 ? InputDirection.Up : InputDirection.Down; + hasMoved = y !== this.pY; + distance5 = Math.abs(input.deltaY); + } + } + input.direction = direction; + return hasMoved && distance5 > options.threshold && Boolean(direction & options.direction); + } + attrTest(input) { + return super.attrTest(input) && (Boolean(this.state & RecognizerState.Began) || !(this.state & RecognizerState.Began) && this.directionTest(input)); + } + emit(input) { + this.pX = input.deltaX; + this.pY = input.deltaY; + const direction = InputDirection[input.direction].toLowerCase(); + if (direction) { + input.additionalEvent = this.options.event + direction; + } + super.emit(input); + } + }; + + // node_modules/mjolnir.js/dist/hammerjs/recognizers/pinch.js + var EVENT_NAMES2 = ["", "start", "move", "end", "cancel", "in", "out"]; + var PinchRecognizer = class extends AttrRecognizer { + constructor(options = {}) { + super({ + enable: true, + event: "pinch", + threshold: 0, + pointers: 2, + ...options + }); + } + getTouchAction() { + return [TOUCH_ACTION_NONE]; + } + getEventNames() { + return EVENT_NAMES2.map((suffix) => this.options.event + suffix); + } + attrTest(input) { + return super.attrTest(input) && (Math.abs(input.scale - 1) > this.options.threshold || Boolean(this.state & RecognizerState.Began)); + } + emit(input) { + if (input.scale !== 1) { + const inOut = input.scale < 1 ? "in" : "out"; + input.additionalEvent = this.options.event + inOut; + } + super.emit(input); + } + }; + + // node_modules/mjolnir.js/dist/inputs/input.js + var Input2 = class { + constructor(element, callback, options) { + this.element = element; + this.callback = callback; + this.options = options; + } + }; + + // node_modules/mjolnir.js/dist/utils/globals.js + var userAgent = typeof navigator !== "undefined" && navigator.userAgent ? navigator.userAgent.toLowerCase() : ""; + var window_4 = typeof window !== "undefined" ? window : global; + + // node_modules/mjolnir.js/dist/inputs/wheel-input.js + var firefox = userAgent.indexOf("firefox") !== -1; + var WHEEL_DELTA_MAGIC_SCALER = 4.000244140625; + var WHEEL_DELTA_PER_LINE = 40; + var SHIFT_MULTIPLIER = 0.25; + var WheelInput = class extends Input2 { + constructor(element, callback, options) { + super(element, callback, { enable: true, ...options }); + this.handleEvent = (event) => { + if (!this.options.enable) { + return; + } + let value = event.deltaY; + if (globalThis.WheelEvent) { + if (firefox && event.deltaMode === globalThis.WheelEvent.DOM_DELTA_PIXEL) { + value /= globalThis.devicePixelRatio; + } + if (event.deltaMode === globalThis.WheelEvent.DOM_DELTA_LINE) { + value *= WHEEL_DELTA_PER_LINE; + } + } + if (value !== 0 && value % WHEEL_DELTA_MAGIC_SCALER === 0) { + value = Math.floor(value / WHEEL_DELTA_MAGIC_SCALER); + } + if (event.shiftKey && value) { + value = value * SHIFT_MULTIPLIER; + } + this.callback({ + type: "wheel", + center: { + x: event.clientX, + y: event.clientY + }, + delta: -value, + srcEvent: event, + pointerType: "mouse", + target: event.target + }); + }; + element.addEventListener("wheel", this.handleEvent, { passive: false }); + } + destroy() { + this.element.removeEventListener("wheel", this.handleEvent); + } + /** + * Enable this input (begin processing events) + * if the specified event type is among those handled by this input. + */ + enableEventType(eventType, enabled) { + if (eventType === "wheel") { + this.options.enable = enabled; + } + } + }; + + // node_modules/mjolnir.js/dist/inputs/move-input.js + var MOUSE_EVENTS = [ + "mousedown", + "mousemove", + "mouseup", + "mouseover", + "mouseout", + "mouseleave" + ]; + var MoveInput = class extends Input2 { + constructor(element, callback, options) { + super(element, callback, { enable: true, ...options }); + this.handleEvent = (event) => { + this.handleOverEvent(event); + this.handleOutEvent(event); + this.handleEnterEvent(event); + this.handleLeaveEvent(event); + this.handleMoveEvent(event); + }; + this.pressed = false; + const { enable: enable2 } = this.options; + this.enableMoveEvent = enable2; + this.enableLeaveEvent = enable2; + this.enableEnterEvent = enable2; + this.enableOutEvent = enable2; + this.enableOverEvent = enable2; + MOUSE_EVENTS.forEach((event) => element.addEventListener(event, this.handleEvent)); + } + destroy() { + MOUSE_EVENTS.forEach((event) => this.element.removeEventListener(event, this.handleEvent)); + } + /** + * Enable this input (begin processing events) + * if the specified event type is among those handled by this input. + */ + enableEventType(eventType, enabled) { + switch (eventType) { + case "pointermove": + this.enableMoveEvent = enabled; + break; + case "pointerover": + this.enableOverEvent = enabled; + break; + case "pointerout": + this.enableOutEvent = enabled; + break; + case "pointerenter": + this.enableEnterEvent = enabled; + break; + case "pointerleave": + this.enableLeaveEvent = enabled; + break; + default: + } + } + handleOverEvent(event) { + if (this.enableOverEvent && event.type === "mouseover") { + this._emit("pointerover", event); + } + } + handleOutEvent(event) { + if (this.enableOutEvent && event.type === "mouseout") { + this._emit("pointerout", event); + } + } + handleEnterEvent(event) { + if (this.enableEnterEvent && event.type === "mouseenter") { + this._emit("pointerenter", event); + } + } + handleLeaveEvent(event) { + if (this.enableLeaveEvent && event.type === "mouseleave") { + this._emit("pointerleave", event); + } + } + handleMoveEvent(event) { + if (this.enableMoveEvent) { + switch (event.type) { + case "mousedown": + if (event.button >= 0) { + this.pressed = true; + } + break; + case "mousemove": + if (event.buttons === 0) { + this.pressed = false; + } + if (!this.pressed) { + this._emit("pointermove", event); + } + break; + case "mouseup": + this.pressed = false; + break; + default: + } + } + } + _emit(type, event) { + this.callback({ + type, + center: { + x: event.clientX, + y: event.clientY + }, + srcEvent: event, + pointerType: "mouse", + target: event.target + }); + } + }; + + // node_modules/mjolnir.js/dist/inputs/key-input.js + var KEY_EVENTS = ["keydown", "keyup"]; + var KeyInput = class extends Input2 { + constructor(element, callback, options) { + super(element, callback, { enable: true, tabIndex: 0, ...options }); + this.handleEvent = (event) => { + const targetElement = event.target || event.srcElement; + if (targetElement.tagName === "INPUT" && targetElement.type === "text" || targetElement.tagName === "TEXTAREA") { + return; + } + if (this.enableDownEvent && event.type === "keydown") { + this.callback({ + type: "keydown", + srcEvent: event, + key: event.key, + target: event.target + }); + } + if (this.enableUpEvent && event.type === "keyup") { + this.callback({ + type: "keyup", + srcEvent: event, + key: event.key, + target: event.target + }); + } + }; + this.enableDownEvent = this.options.enable; + this.enableUpEvent = this.options.enable; + element.tabIndex = this.options.tabIndex; + element.style.outline = "none"; + KEY_EVENTS.forEach((event) => element.addEventListener(event, this.handleEvent)); + } + destroy() { + KEY_EVENTS.forEach((event) => this.element.removeEventListener(event, this.handleEvent)); + } + /** + * Enable this input (begin processing events) + * if the specified event type is among those handled by this input. + */ + enableEventType(eventType, enabled) { + if (eventType === "keydown") { + this.enableDownEvent = enabled; + } + if (eventType === "keyup") { + this.enableUpEvent = enabled; + } + } + }; + + // node_modules/mjolnir.js/dist/inputs/contextmenu-input.js + var ContextmenuInput = class extends Input2 { + constructor(element, callback, options) { + super(element, callback, options); + this.handleEvent = (event) => { + if (!this.options.enable) { + return; + } + this.callback({ + type: "contextmenu", + center: { + x: event.clientX, + y: event.clientY + }, + srcEvent: event, + pointerType: "mouse", + target: event.target + }); + }; + element.addEventListener("contextmenu", this.handleEvent); + } + destroy() { + this.element.removeEventListener("contextmenu", this.handleEvent); + } + /** + * Enable this input (begin processing events) + * if the specified event type is among those handled by this input. + */ + enableEventType(eventType, enabled) { + if (eventType === "contextmenu") { + this.options.enable = enabled; + } + } + }; + + // node_modules/mjolnir.js/dist/utils/event-utils.js + var DOWN_EVENT = 1; + var MOVE_EVENT = 2; + var UP_EVENT = 4; + var MOUSE_EVENTS2 = { + pointerdown: DOWN_EVENT, + pointermove: MOVE_EVENT, + pointerup: UP_EVENT, + mousedown: DOWN_EVENT, + mousemove: MOVE_EVENT, + mouseup: UP_EVENT + }; + var MOUSE_EVENT_BUTTON_LEFT = 0; + var MOUSE_EVENT_BUTTON_MIDDLE = 1; + var MOUSE_EVENT_BUTTON_RIGHT = 2; + var MOUSE_EVENT_BUTTONS_LEFT_MASK = 1; + var MOUSE_EVENT_BUTTONS_RIGHT_MASK = 2; + var MOUSE_EVENT_BUTTONS_MIDDLE_MASK = 4; + function whichButtons(event) { + const eventType = MOUSE_EVENTS2[event.srcEvent.type]; + if (!eventType) { + return null; + } + const { buttons, button } = event.srcEvent; + let leftButton = false; + let middleButton = false; + let rightButton = false; + if (eventType === MOVE_EVENT) { + leftButton = Boolean(buttons & MOUSE_EVENT_BUTTONS_LEFT_MASK); + middleButton = Boolean(buttons & MOUSE_EVENT_BUTTONS_MIDDLE_MASK); + rightButton = Boolean(buttons & MOUSE_EVENT_BUTTONS_RIGHT_MASK); + } else { + leftButton = button === MOUSE_EVENT_BUTTON_LEFT; + middleButton = button === MOUSE_EVENT_BUTTON_MIDDLE; + rightButton = button === MOUSE_EVENT_BUTTON_RIGHT; + } + return { leftButton, middleButton, rightButton }; + } + function getOffsetPosition(event, rootElement) { + const center = event.center; + if (!center) { + return null; + } + const rect = rootElement.getBoundingClientRect(); + const scaleX2 = rect.width / rootElement.offsetWidth || 1; + const scaleY2 = rect.height / rootElement.offsetHeight || 1; + const offsetCenter = { + x: (center.x - rect.left - rootElement.clientLeft) / scaleX2, + y: (center.y - rect.top - rootElement.clientTop) / scaleY2 + }; + return { center, offsetCenter }; + } + + // node_modules/mjolnir.js/dist/utils/event-registrar.js + var DEFAULT_OPTIONS = { + srcElement: "root", + priority: 0 + }; + var EventRegistrar = class { + constructor(eventManager, recognizerName) { + this.handleEvent = (event) => { + if (this.isEmpty()) { + return; + } + const mjolnirEvent = this._normalizeEvent(event); + let target2 = event.srcEvent.target; + while (target2 && target2 !== mjolnirEvent.rootElement) { + this._emit(mjolnirEvent, target2); + if (mjolnirEvent.handled) { + return; + } + target2 = target2.parentNode; + } + this._emit(mjolnirEvent, "root"); + }; + this.eventManager = eventManager; + this.recognizerName = recognizerName; + this.handlers = []; + this.handlersByElement = /* @__PURE__ */ new Map(); + this._active = false; + } + // Returns true if there are no non-passive handlers + isEmpty() { + return !this._active; + } + add(type, handler, options, once = false, passive = false) { + const { handlers, handlersByElement } = this; + const opts = { ...DEFAULT_OPTIONS, ...options }; + let entries = handlersByElement.get(opts.srcElement); + if (!entries) { + entries = []; + handlersByElement.set(opts.srcElement, entries); + } + const entry = { + type, + handler, + srcElement: opts.srcElement, + priority: opts.priority + }; + if (once) { + entry.once = true; + } + if (passive) { + entry.passive = true; + } + handlers.push(entry); + this._active = this._active || !entry.passive; + let insertPosition = entries.length - 1; + while (insertPosition >= 0) { + if (entries[insertPosition].priority >= entry.priority) { + break; + } + insertPosition--; + } + entries.splice(insertPosition + 1, 0, entry); + } + remove(type, handler) { + const { handlers, handlersByElement } = this; + for (let i = handlers.length - 1; i >= 0; i--) { + const entry = handlers[i]; + if (entry.type === type && entry.handler === handler) { + handlers.splice(i, 1); + const entries = handlersByElement.get(entry.srcElement); + entries.splice(entries.indexOf(entry), 1); + if (entries.length === 0) { + handlersByElement.delete(entry.srcElement); + } + } + } + this._active = handlers.some((entry) => !entry.passive); + } + /** + * Invoke handlers on a particular element + */ + _emit(event, srcElement) { + const entries = this.handlersByElement.get(srcElement); + if (entries) { + let immediatePropagationStopped = false; + const stopPropagation = () => { + event.handled = true; + }; + const stopImmediatePropagation = () => { + event.handled = true; + immediatePropagationStopped = true; + }; + const entriesToRemove = []; + for (let i = 0; i < entries.length; i++) { + const { type, handler, once } = entries[i]; + handler({ + ...event, + type, + stopPropagation, + stopImmediatePropagation + }); + if (once) { + entriesToRemove.push(entries[i]); + } + if (immediatePropagationStopped) { + break; + } + } + for (let i = 0; i < entriesToRemove.length; i++) { + const { type, handler } = entriesToRemove[i]; + this.remove(type, handler); + } + } + } + /** + * Normalizes hammerjs and custom events to have predictable fields. + */ + _normalizeEvent(event) { + const rootElement = this.eventManager.getElement(); + return { + ...event, + ...whichButtons(event), + ...getOffsetPosition(event, rootElement), + preventDefault: () => { + event.srcEvent.preventDefault(); + }, + stopImmediatePropagation: null, + stopPropagation: null, + handled: false, + rootElement + }; + } + }; + + // node_modules/mjolnir.js/dist/event-manager.js + function normalizeRecognizer(item) { + if ("recognizer" in item) { + return item; + } + let recognizer; + const itemArray = Array.isArray(item) ? [...item] : [item]; + if (typeof itemArray[0] === "function") { + const RecognizerType = itemArray.shift(); + const options = itemArray.shift() || {}; + recognizer = new RecognizerType(options); + } else { + recognizer = itemArray.shift(); + } + return { + recognizer, + recognizeWith: typeof itemArray[0] === "string" ? [itemArray[0]] : itemArray[0], + requireFailure: typeof itemArray[1] === "string" ? [itemArray[1]] : itemArray[1] + }; + } + var EventManager = class { + constructor(element = null, options = {}) { + this._onBasicInput = (event) => { + this.manager.emit(event.srcEvent.type, event); + }; + this._onOtherEvent = (event) => { + this.manager.emit(event.type, event); + }; + this.options = { + recognizers: [], + events: {}, + touchAction: "compute", + tabIndex: 0, + cssProps: {}, + ...options + }; + this.events = /* @__PURE__ */ new Map(); + this.element = element; + if (!element) + return; + this.manager = new Manager(element, this.options); + for (const item of this.options.recognizers) { + const { recognizer, recognizeWith, requireFailure } = normalizeRecognizer(item); + this.manager.add(recognizer); + if (recognizeWith) { + recognizer.recognizeWith(recognizeWith); + } + if (requireFailure) { + recognizer.requireFailure(requireFailure); + } + } + this.manager.on("hammer.input", this._onBasicInput); + this.wheelInput = new WheelInput(element, this._onOtherEvent, { + enable: false + }); + this.moveInput = new MoveInput(element, this._onOtherEvent, { + enable: false + }); + this.keyInput = new KeyInput(element, this._onOtherEvent, { + enable: false, + tabIndex: options.tabIndex + }); + this.contextmenuInput = new ContextmenuInput(element, this._onOtherEvent, { + enable: false + }); + this.on(this.options.events); + } + getElement() { + return this.element; + } + // Tear down internal event management implementations. + destroy() { + if (!this.element) + return; + this.wheelInput.destroy(); + this.moveInput.destroy(); + this.keyInput.destroy(); + this.contextmenuInput.destroy(); + this.manager.destroy(); + } + /** Register an event handler function to be called on `event` */ + on(event, handler, opts) { + this._addEventHandler(event, handler, opts, false); + } + once(event, handler, opts) { + this._addEventHandler(event, handler, opts, true); + } + watch(event, handler, opts) { + this._addEventHandler(event, handler, opts, false, true); + } + off(event, handler) { + this._removeEventHandler(event, handler); + } + /* + * Enable/disable recognizer for the given event + */ + _toggleRecognizer(name2, enabled) { + const { manager } = this; + if (!manager) { + return; + } + const recognizer = manager.get(name2); + if (recognizer) { + recognizer.set({ enable: enabled }); + manager.touchAction.update(); + } + this.wheelInput?.enableEventType(name2, enabled); + this.moveInput?.enableEventType(name2, enabled); + this.keyInput?.enableEventType(name2, enabled); + this.contextmenuInput?.enableEventType(name2, enabled); + } + /** + * Process the event registration for a single event + handler. + */ + _addEventHandler(event, handler, opts, once, passive) { + if (typeof event !== "string") { + opts = handler; + for (const [eventName, eventHandler] of Object.entries(event)) { + this._addEventHandler(eventName, eventHandler, opts, once, passive); + } + return; + } + const { manager, events } = this; + if (!manager) + return; + let eventRegistrar = events.get(event); + if (!eventRegistrar) { + const recognizerName = this._getRecognizerName(event) || event; + eventRegistrar = new EventRegistrar(this, recognizerName); + events.set(event, eventRegistrar); + if (manager) { + manager.on(event, eventRegistrar.handleEvent); + } + } + eventRegistrar.add(event, handler, opts, once, passive); + if (!eventRegistrar.isEmpty()) { + this._toggleRecognizer(eventRegistrar.recognizerName, true); + } + } + /** + * Process the event deregistration for a single event + handler. + */ + _removeEventHandler(event, handler) { + if (typeof event !== "string") { + for (const [eventName, eventHandler] of Object.entries(event)) { + this._removeEventHandler(eventName, eventHandler); + } + return; + } + const { events } = this; + const eventRegistrar = events.get(event); + if (!eventRegistrar) { + return; + } + eventRegistrar.remove(event, handler); + if (eventRegistrar.isEmpty()) { + const { recognizerName } = eventRegistrar; + let isRecognizerUsed = false; + for (const eh of events.values()) { + if (eh.recognizerName === recognizerName && !eh.isEmpty()) { + isRecognizerUsed = true; + break; + } + } + if (!isRecognizerUsed) { + this._toggleRecognizer(recognizerName, false); + } + } + } + _getRecognizerName(event) { + return this.manager.recognizers.find((recognizer) => { + return recognizer.getEventNames().includes(event); + })?.options.event; + } + }; + + // node_modules/@deck.gl/core/dist/lib/constants.js + var COORDINATE_SYSTEM = { + /** + * `LNGLAT` if rendering into a geospatial viewport, `CARTESIAN` otherwise + */ + DEFAULT: "default", + /** + * Positions are interpreted as [longitude, latitude, elevation] + * longitude/latitude are in degrees, elevation is in meters. + * Dimensions are in meters. + */ + LNGLAT: "lnglat", + /** + * Positions are interpreted as [x, y, z] in meter offsets from the coordinate origin. + * Dimensions are in meters. + */ + METER_OFFSETS: "meter-offsets", + /** + * Positions are interpreted as [deltaLng, deltaLat, elevation] from the coordinate origin. + * deltaLng/deltaLat are in degrees, elevation is in meters. + * Dimensions are in meters. + */ + LNGLAT_OFFSETS: "lnglat-offsets", + /** + * Positions and dimensions are in the common units of the viewport. + */ + CARTESIAN: "cartesian" + }; + Object.defineProperty(COORDINATE_SYSTEM, "IDENTITY", { + get: () => { + log_default.deprecated("COORDINATE_SYSTEM.IDENTITY", "COORDINATE_SYSTEM.CARTESIAN")(); + return COORDINATE_SYSTEM.CARTESIAN; + } + }); + var PROJECTION_MODE = { + /** + * Render geospatial data in Web Mercator projection + */ + WEB_MERCATOR: 1, + /** + * Render geospatial data as a 3D globe + */ + GLOBE: 2, + /** + * (Internal use only) Web Mercator projection at high zoom + */ + WEB_MERCATOR_AUTO_OFFSET: 4, + /** + * No transformation + */ + IDENTITY: 0 + }; + var UNIT = { + common: 0, + meters: 1, + pixels: 2 + }; + var EVENT_HANDLERS = { + click: "onClick", + dblclick: "onClick", + panstart: "onDragStart", + panmove: "onDrag", + panend: "onDragEnd" + }; + var RECOGNIZERS = { + multipan: [PanRecognizer, { threshold: 10, direction: InputDirection.Vertical, pointers: 2 }], + pinch: [PinchRecognizer, {}, null, ["multipan"]], + pan: [PanRecognizer, { threshold: 1 }, ["pinch"], ["multipan"]], + dblclick: [TapRecognizer, { event: "dblclick", taps: 2 }], + click: [TapRecognizer, { event: "click" }, null, ["dblclick"]] + }; + + // node_modules/@deck.gl/core/dist/utils/memoize.js + function isEqual(a, b) { + if (a === b) { + return true; + } + if (Array.isArray(a)) { + const len4 = a.length; + if (!b || b.length !== len4) { + return false; + } + for (let i = 0; i < len4; i++) { + if (a[i] !== b[i]) { + return false; + } + } + return true; + } + return false; + } + function memoize(compute) { + let cachedArgs = {}; + let cachedResult; + return (args) => { + for (const key in args) { + if (!isEqual(args[key], cachedArgs[key])) { + cachedResult = compute(args); + cachedArgs = args; + break; + } + } + return cachedResult; + }; + } + + // node_modules/@deck.gl/core/dist/shaderlib/project/viewport-uniforms.js + var ZERO_VECTOR = [0, 0, 0, 0]; + var VECTOR_TO_POINT_MATRIX = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]; + var IDENTITY_MATRIX2 = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]; + var DEFAULT_PIXELS_PER_UNIT2 = [0, 0, 0]; + var DEFAULT_COORDINATE_ORIGIN = [0, 0, 0]; + var COORDINATE_SYSTEM_NUMBERS = { + default: -1, + cartesian: 0, + lnglat: 1, + "meter-offsets": 2, + "lnglat-offsets": 3 + }; + function getShaderCoordinateSystem(coordinateSystem) { + const shaderCoordinateSystem = COORDINATE_SYSTEM_NUMBERS[coordinateSystem]; + if (shaderCoordinateSystem === void 0) { + throw new Error(`Invalid coordinateSystem: ${coordinateSystem}`); + } + return shaderCoordinateSystem; + } + var getMemoizedViewportUniforms = memoize(calculateViewportUniforms); + function getOffsetOrigin(viewport, coordinateSystem, coordinateOrigin = DEFAULT_COORDINATE_ORIGIN) { + if (coordinateOrigin.length < 3) { + coordinateOrigin = [coordinateOrigin[0], coordinateOrigin[1], 0]; + } + let shaderCoordinateOrigin = coordinateOrigin; + let geospatialOrigin; + let offsetMode = true; + if (coordinateSystem === "lnglat-offsets" || coordinateSystem === "meter-offsets") { + geospatialOrigin = coordinateOrigin; + } else { + geospatialOrigin = viewport.isGeospatial ? ( + // @ts-expect-error longitude and latitude are not defined on the base Viewport, but is expected on geospatial viewports + [Math.fround(viewport.longitude), Math.fround(viewport.latitude), 0] + ) : null; + } + switch (viewport.projectionMode) { + case PROJECTION_MODE.WEB_MERCATOR: + if (coordinateSystem === "lnglat" || coordinateSystem === "cartesian") { + geospatialOrigin = [0, 0, 0]; + offsetMode = false; + } + break; + case PROJECTION_MODE.WEB_MERCATOR_AUTO_OFFSET: + if (coordinateSystem === "lnglat") { + shaderCoordinateOrigin = geospatialOrigin; + } else if (coordinateSystem === "cartesian") { + shaderCoordinateOrigin = [ + Math.fround(viewport.center[0]), + Math.fround(viewport.center[1]), + 0 + ]; + geospatialOrigin = viewport.unprojectPosition(shaderCoordinateOrigin); + shaderCoordinateOrigin[0] -= coordinateOrigin[0]; + shaderCoordinateOrigin[1] -= coordinateOrigin[1]; + shaderCoordinateOrigin[2] -= coordinateOrigin[2]; + } + break; + case PROJECTION_MODE.IDENTITY: + shaderCoordinateOrigin = viewport.position.map(Math.fround); + shaderCoordinateOrigin[2] = shaderCoordinateOrigin[2] || 0; + break; + case PROJECTION_MODE.GLOBE: + offsetMode = false; + geospatialOrigin = null; + break; + default: + offsetMode = false; + } + return { geospatialOrigin, shaderCoordinateOrigin, offsetMode }; + } + function calculateMatrixAndOffset(viewport, coordinateSystem, coordinateOrigin) { + const { viewMatrixUncentered, projectionMatrix } = viewport; + let { viewMatrix, viewProjectionMatrix } = viewport; + let projectionCenter = ZERO_VECTOR; + let originCommon = ZERO_VECTOR; + let cameraPosCommon = viewport.cameraPosition; + const { geospatialOrigin, shaderCoordinateOrigin, offsetMode } = getOffsetOrigin(viewport, coordinateSystem, coordinateOrigin); + if (offsetMode) { + originCommon = viewport.projectPosition(geospatialOrigin || shaderCoordinateOrigin); + cameraPosCommon = [ + cameraPosCommon[0] - originCommon[0], + cameraPosCommon[1] - originCommon[1], + cameraPosCommon[2] - originCommon[2] + ]; + originCommon[3] = 1; + projectionCenter = vec4_exports.transformMat4([], originCommon, viewProjectionMatrix); + viewMatrix = viewMatrixUncentered || viewMatrix; + viewProjectionMatrix = mat4_exports.multiply([], projectionMatrix, viewMatrix); + viewProjectionMatrix = mat4_exports.multiply([], viewProjectionMatrix, VECTOR_TO_POINT_MATRIX); + } + return { + viewMatrix, + viewProjectionMatrix, + projectionCenter, + originCommon, + cameraPosCommon, + shaderCoordinateOrigin, + geospatialOrigin + }; + } + function getUniformsFromViewport({ + viewport, + devicePixelRatio: devicePixelRatio2 = 1, + modelMatrix = null, + // Match Layer.defaultProps + coordinateSystem = "default", + coordinateOrigin = DEFAULT_COORDINATE_ORIGIN, + autoWrapLongitude = false + }) { + if (coordinateSystem === "default") { + coordinateSystem = viewport.isGeospatial ? "lnglat" : "cartesian"; + } + const uniforms = getMemoizedViewportUniforms({ + viewport, + devicePixelRatio: devicePixelRatio2, + coordinateSystem, + coordinateOrigin + }); + uniforms.wrapLongitude = autoWrapLongitude; + uniforms.modelMatrix = modelMatrix || IDENTITY_MATRIX2; + return uniforms; + } + function calculateViewportUniforms({ viewport, devicePixelRatio: devicePixelRatio2, coordinateSystem, coordinateOrigin }) { + const { projectionCenter, viewProjectionMatrix, originCommon, cameraPosCommon, shaderCoordinateOrigin, geospatialOrigin } = calculateMatrixAndOffset(viewport, coordinateSystem, coordinateOrigin); + const distanceScales = viewport.getDistanceScales(); + const viewportSize = [ + viewport.width * devicePixelRatio2, + viewport.height * devicePixelRatio2 + ]; + const focalDistance = vec4_exports.transformMat4([], [0, 0, -viewport.focalDistance, 1], viewport.projectionMatrix)[3] || 1; + const uniforms = { + // Projection mode values + coordinateSystem: getShaderCoordinateSystem(coordinateSystem), + projectionMode: viewport.projectionMode, + coordinateOrigin: shaderCoordinateOrigin, + commonOrigin: originCommon.slice(0, 3), + center: projectionCenter, + // Backward compatibility + // TODO: remove in v9 + // @ts-expect-error _pseudoMeters is only defined on WebMercator viewport + pseudoMeters: Boolean(viewport._pseudoMeters), + // Screen size + viewportSize, + devicePixelRatio: devicePixelRatio2, + focalDistance, + commonUnitsPerMeter: distanceScales.unitsPerMeter, + commonUnitsPerWorldUnit: distanceScales.unitsPerMeter, + commonUnitsPerWorldUnit2: DEFAULT_PIXELS_PER_UNIT2, + scale: viewport.scale, + // This is the mercator scale (2 ** zoom) + wrapLongitude: false, + viewProjectionMatrix, + modelMatrix: IDENTITY_MATRIX2, + // This is for lighting calculations + cameraPosition: cameraPosCommon + }; + if (geospatialOrigin) { + const distanceScalesAtOrigin = viewport.getDistanceScales(geospatialOrigin); + switch (coordinateSystem) { + case "meter-offsets": + uniforms.commonUnitsPerWorldUnit = distanceScalesAtOrigin.unitsPerMeter; + uniforms.commonUnitsPerWorldUnit2 = distanceScalesAtOrigin.unitsPerMeter2; + break; + case "lnglat": + case "lnglat-offsets": + if (!viewport._pseudoMeters) { + uniforms.commonUnitsPerMeter = distanceScalesAtOrigin.unitsPerMeter; + } + uniforms.commonUnitsPerWorldUnit = distanceScalesAtOrigin.unitsPerDegree; + uniforms.commonUnitsPerWorldUnit2 = distanceScalesAtOrigin.unitsPerDegree2; + break; + // a.k.a "preprojected" positions + case "cartesian": + uniforms.commonUnitsPerWorldUnit = [1, 1, distanceScalesAtOrigin.unitsPerMeter[2]]; + uniforms.commonUnitsPerWorldUnit2 = [0, 0, distanceScalesAtOrigin.unitsPerMeter2[2]]; + break; + default: + break; + } + } + return uniforms; + } + + // node_modules/@deck.gl/core/dist/shaderlib/project/project.wgsl.js + var SHADER_COORDINATE_SYSTEMS = [ + "default", + "lnglat", + "meter-offsets", + "lnglat-offsets", + "cartesian" + ]; + var COORDINATE_SYSTEM_WGSL_CONSTANTS = SHADER_COORDINATE_SYSTEMS.map((coordinateSystem) => `const COORDINATE_SYSTEM_${coordinateSystem.toUpperCase().replaceAll("-", "_")}: i32 = ${getShaderCoordinateSystem(coordinateSystem)};`).join(""); + var PROJECTION_MODE_WGSL_CONSTANTS = Object.keys(PROJECTION_MODE).map((key) => `const PROJECTION_MODE_${key}: i32 = ${PROJECTION_MODE[key]};`).join(""); + var UNIT_WGSL_CONSTANTS = Object.keys(UNIT).map((key) => `const UNIT_${key.toUpperCase()}: i32 = ${UNIT[key]};`).join(""); + var projectWGSLHeader = ( + /* wgsl */ + `${COORDINATE_SYSTEM_WGSL_CONSTANTS} +${PROJECTION_MODE_WGSL_CONSTANTS} +${UNIT_WGSL_CONSTANTS} + +const TILE_SIZE: f32 = 512.0; +const PI: f32 = 3.1415926536; +const WORLD_SCALE: f32 = TILE_SIZE / (PI * 2.0); +const ZERO_64_LOW: vec3 = vec3(0.0, 0.0, 0.0); +const EARTH_RADIUS: f32 = 6370972.0; // meters +const GLOBE_RADIUS: f32 = 256.0; + +// ----------------------------------------------------------------------------- +// Uniform block (converted from GLSL uniform block) +// ----------------------------------------------------------------------------- +struct ProjectUniforms { + wrapLongitude: i32, + coordinateSystem: i32, + commonUnitsPerMeter: vec3, + projectionMode: i32, + scale: f32, + commonUnitsPerWorldUnit: vec3, + commonUnitsPerWorldUnit2: vec3, + center: vec4, + modelMatrix: mat4x4, + viewProjectionMatrix: mat4x4, + viewportSize: vec2, + devicePixelRatio: f32, + focalDistance: f32, + cameraPosition: vec3, + coordinateOrigin: vec3, + commonOrigin: vec3, + pseudoMeters: i32, +}; + +@group(0) @binding(auto) +var project: ProjectUniforms; + +// ----------------------------------------------------------------------------- +// Geometry data shared across the project helpers. +// The active layer shader is responsible for populating this private module +// state before calling the project functions below. +// ----------------------------------------------------------------------------- + +// Structure to carry additional geometry data used by deck.gl filters. +struct Geometry { + worldPosition: vec3, + worldPositionAlt: vec3, + position: vec4, + normal: vec3, + uv: vec2, + pickingColor: vec3, +}; + +var geometry: Geometry; +` + ); + var projectWGSL = ( + /* wgsl */ + `${projectWGSLHeader} + +// ----------------------------------------------------------------------------- +// Functions +// ----------------------------------------------------------------------------- + +// Returns an adjustment factor for commonUnitsPerMeter +fn _project_size_at_latitude(lat: f32) -> f32 { + let y = clamp(lat, -89.9, 89.9); + return 1.0 / cos(radians(y)); +} + +// Overloaded version: scales a value in meters at a given latitude. +fn _project_size_at_latitude_m(meters: f32, lat: f32) -> f32 { + return meters * project.commonUnitsPerMeter.z * _project_size_at_latitude(lat); +} + +// Computes a non-linear scale factor based on geometry. +// (Note: This function relies on "geometry" being provided.) +fn project_size() -> f32 { + if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR && + project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT && + project.pseudoMeters == 0) { + if (geometry.position.w == 0.0) { + return _project_size_at_latitude(geometry.worldPosition.y); + } + let y: f32 = geometry.position.y / TILE_SIZE * 2.0 - 1.0; + let y2 = y * y; + let y4 = y2 * y2; + let y6 = y4 * y2; + return 1.0 + 4.9348 * y2 + 4.0587 * y4 + 1.5642 * y6; + } + return 1.0; +} + +// Overloads to scale offsets (meters to world units) +fn project_size_float(meters: f32) -> f32 { + return meters * project.commonUnitsPerMeter.z * project_size(); +} + +fn project_size_vec2(meters: vec2) -> vec2 { + return meters * project.commonUnitsPerMeter.xy * project_size(); +} + +fn project_size_vec3(meters: vec3) -> vec3 { + return meters * project.commonUnitsPerMeter * project_size(); +} + +fn project_size_vec4(meters: vec4) -> vec4 { + return vec4(meters.xyz * project.commonUnitsPerMeter, meters.w); +} + +// Returns a rotation matrix aligning the z\u2011axis with the given up vector. +fn project_get_orientation_matrix(up: vec3) -> mat3x3 { + let uz = normalize(up); + let ux = select( + vec3(1.0, 0.0, 0.0), + normalize(vec3(uz.y, -uz.x, 0.0)), + abs(uz.z) == 1.0 + ); + let uy = cross(uz, ux); + return mat3x3(ux, uy, uz); +} + +// Since WGSL does not support "out" parameters, we return a struct. +struct RotationResult { + needsRotation: bool, + transform: mat3x3, +}; + +fn project_needs_rotation(commonPosition: vec3) -> RotationResult { + if (project.projectionMode == PROJECTION_MODE_GLOBE) { + return RotationResult(true, project_get_orientation_matrix(commonPosition)); + } else { + return RotationResult(false, mat3x3()); // identity alternative if needed + }; +} + +// Projects a normal vector from the current coordinate system to world space. +fn project_normal(vector: vec3) -> vec3 { + let normal_modelspace = project.modelMatrix * vec4(vector, 0.0); + var n = normalize(normal_modelspace.xyz * project.commonUnitsPerMeter); + let rotResult = project_needs_rotation(geometry.position.xyz); + if (rotResult.needsRotation) { + n = rotResult.transform * n; + } + return n; +} + +// Applies a scale offset based on y-offset (dy) +fn project_offset_(offset: vec4) -> vec4 { + let dy: f32 = offset.y; + let commonUnitsPerWorldUnit = project.commonUnitsPerWorldUnit + project.commonUnitsPerWorldUnit2 * dy; + return vec4(offset.xyz * commonUnitsPerWorldUnit, offset.w); +} + +// Projects lng/lat coordinates to a unit tile [0,1] +fn project_mercator_(lnglat: vec2) -> vec2 { + var x = lnglat.x; + if (project.wrapLongitude != 0) { + x = ((x + 180.0) % 360.0) - 180.0; + } + let y = clamp(lnglat.y, -89.9, 89.9); + return vec2( + radians(x) + PI, + PI + log(tan(PI * 0.25 + radians(y) * 0.5)) + ) * WORLD_SCALE; +} + +// Projects lng/lat/z coordinates for a globe projection. +fn project_globe_(lnglatz: vec3) -> vec3 { + let lambda = radians(lnglatz.x); + let phi = radians(lnglatz.y); + let cosPhi = cos(phi); + let D = (lnglatz.z / EARTH_RADIUS + 1.0) * GLOBE_RADIUS; + return vec3( + sin(lambda) * cosPhi, + -cos(lambda) * cosPhi, + sin(phi) + ) * D; +} + +// Projects positions (with an optional 64-bit low part) from the input +// coordinate system to the common space. +fn project_position_vec4_f64(position: vec4, position64Low: vec3) -> vec4 { + var position_world = project.modelMatrix * position; + + // Work around for a Mac+NVIDIA bug: + if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR) { + if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) { + return vec4( + project_mercator_(position_world.xy), + _project_size_at_latitude_m(position_world.z, position_world.y), + position_world.w + ); + } + if (project.coordinateSystem == COORDINATE_SYSTEM_CARTESIAN) { + position_world = vec4f(position_world.xyz + project.coordinateOrigin, position_world.w); + } + } + if (project.projectionMode == PROJECTION_MODE_GLOBE) { + if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) { + return vec4( + project_globe_(position_world.xyz), + position_world.w + ); + } + } + if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR_AUTO_OFFSET) { + if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) { + if (abs(position_world.y - project.coordinateOrigin.y) > 0.25) { + return vec4( + project_mercator_(position_world.xy) - project.commonOrigin.xy, + project_size_float(position_world.z), + position_world.w + ); + } + } + } + if (project.projectionMode == PROJECTION_MODE_IDENTITY || + (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR_AUTO_OFFSET && + (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT || + project.coordinateSystem == COORDINATE_SYSTEM_CARTESIAN))) { + position_world = vec4f(position_world.xyz - project.coordinateOrigin, position_world.w); + } + + return project_offset_(position_world) + + project_offset_(project.modelMatrix * vec4(position64Low, 0.0)); +} + +// Overloaded versions for different input types. +fn project_position_vec4_f32(position: vec4) -> vec4 { + return project_position_vec4_f64(position, ZERO_64_LOW); +} + +fn project_position_vec3_f64(position: vec3, position64Low: vec3) -> vec3 { + let projected_position = project_position_vec4_f64(vec4(position, 1.0), position64Low); + return projected_position.xyz; +} + +fn project_position_vec3_f32(position: vec3) -> vec3 { + let projected_position = project_position_vec4_f64(vec4(position, 1.0), ZERO_64_LOW); + return projected_position.xyz; +} + +fn project_position_vec2_f32(position: vec2) -> vec2 { + let projected_position = project_position_vec4_f64(vec4(position, 0.0, 1.0), ZERO_64_LOW); + return projected_position.xy; +} + +// Transforms a common space position to clip space. +fn project_common_position_to_clipspace_with_projection(position: vec4, viewProjectionMatrix: mat4x4, center: vec4) -> vec4 { + return viewProjectionMatrix * position + center; +} + +// Uses the project viewProjectionMatrix and center. +fn project_common_position_to_clipspace(position: vec4) -> vec4 { + return project_common_position_to_clipspace_with_projection(position, project.viewProjectionMatrix, project.center); +} + +// Returns a clip space offset corresponding to a given number of screen pixels. +fn project_pixel_size_to_clipspace(pixels: vec2) -> vec2 { + let offset = pixels / project.viewportSize * project.devicePixelRatio * 2.0; + return offset * project.focalDistance; +} + +fn project_meter_size_to_pixel(meters: f32) -> f32 { + return project_size_float(meters) * project.scale; +} + +fn project_unit_size_to_pixel(size: f32, unit: i32) -> f32 { + if (unit == UNIT_METERS) { + return project_meter_size_to_pixel(size); + } else if (unit == UNIT_COMMON) { + return size * project.scale; + } + // UNIT_PIXELS: no scaling applied. + return size; +} + +fn project_pixel_size_float(pixels: f32) -> f32 { + return pixels / project.scale; +} + +fn project_pixel_size_vec2(pixels: vec2) -> vec2 { + return pixels / project.scale; +} +` + ); + + // node_modules/@deck.gl/core/dist/shaderlib/project/project.glsl.js + var SHADER_COORDINATE_SYSTEMS2 = [ + "default", + "lnglat", + "meter-offsets", + "lnglat-offsets", + "cartesian" + ]; + var COORDINATE_SYSTEM_GLSL_CONSTANTS = SHADER_COORDINATE_SYSTEMS2.map((coordinateSystem) => `const int COORDINATE_SYSTEM_${coordinateSystem.toUpperCase().replaceAll("-", "_")} = ${getShaderCoordinateSystem(coordinateSystem)};`).join(""); + var PROJECTION_MODE_GLSL_CONSTANTS = Object.keys(PROJECTION_MODE).map((key) => `const int PROJECTION_MODE_${key} = ${PROJECTION_MODE[key]};`).join(""); + var UNIT_GLSL_CONSTANTS = Object.keys(UNIT).map((key) => `const int UNIT_${key.toUpperCase()} = ${UNIT[key]};`).join(""); + var projectGLSL = ( + /* glsl */ + `${COORDINATE_SYSTEM_GLSL_CONSTANTS} +${PROJECTION_MODE_GLSL_CONSTANTS} +${UNIT_GLSL_CONSTANTS} +layout(std140) uniform projectUniforms { +bool wrapLongitude; +int coordinateSystem; +vec3 commonUnitsPerMeter; +int projectionMode; +float scale; +vec3 commonUnitsPerWorldUnit; +vec3 commonUnitsPerWorldUnit2; +vec4 center; +mat4 modelMatrix; +mat4 viewProjectionMatrix; +vec2 viewportSize; +float devicePixelRatio; +float focalDistance; +vec3 cameraPosition; +vec3 coordinateOrigin; +vec3 commonOrigin; +bool pseudoMeters; +} project; +const float TILE_SIZE = 512.0; +const float PI = 3.1415926536; +const float WORLD_SCALE = TILE_SIZE / (PI * 2.0); +const vec3 ZERO_64_LOW = vec3(0.0); +const float EARTH_RADIUS = 6370972.0; +const float GLOBE_RADIUS = 256.0; +float project_size_at_latitude(float lat) { +float y = clamp(lat, -89.9, 89.9); +return 1.0 / cos(radians(y)); +} +float project_size() { +if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR && +project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT && +project.pseudoMeters == false) { +if (geometry.position.w == 0.0) { +return project_size_at_latitude(geometry.worldPosition.y); +} +float y = geometry.position.y / TILE_SIZE * 2.0 - 1.0; +float y2 = y * y; +float y4 = y2 * y2; +float y6 = y4 * y2; +return 1.0 + 4.9348 * y2 + 4.0587 * y4 + 1.5642 * y6; +} +return 1.0; +} +float project_size_at_latitude(float meters, float lat) { +return meters * project.commonUnitsPerMeter.z * project_size_at_latitude(lat); +} +float project_size(float meters) { +return meters * project.commonUnitsPerMeter.z * project_size(); +} +vec2 project_size(vec2 meters) { +return meters * project.commonUnitsPerMeter.xy * project_size(); +} +vec3 project_size(vec3 meters) { +return meters * project.commonUnitsPerMeter * project_size(); +} +vec4 project_size(vec4 meters) { +return vec4(meters.xyz * project.commonUnitsPerMeter, meters.w); +} +mat3 project_get_orientation_matrix(vec3 up) { +vec3 uz = normalize(up); +vec3 ux = abs(uz.z) == 1.0 ? vec3(1.0, 0.0, 0.0) : normalize(vec3(uz.y, -uz.x, 0)); +vec3 uy = cross(uz, ux); +return mat3(ux, uy, uz); +} +bool project_needs_rotation(vec3 commonPosition, out mat3 transform) { +if (project.projectionMode == PROJECTION_MODE_GLOBE) { +transform = project_get_orientation_matrix(commonPosition); +return true; +} +return false; +} +vec3 project_normal(vec3 vector) { +vec4 normal_modelspace = project.modelMatrix * vec4(vector, 0.0); +vec3 n = normalize(normal_modelspace.xyz * project.commonUnitsPerMeter); +mat3 rotation; +if (project_needs_rotation(geometry.position.xyz, rotation)) { +n = rotation * n; +} +return n; +} +vec4 project_offset_(vec4 offset) { +float dy = offset.y; +vec3 commonUnitsPerWorldUnit = project.commonUnitsPerWorldUnit + project.commonUnitsPerWorldUnit2 * dy; +return vec4(offset.xyz * commonUnitsPerWorldUnit, offset.w); +} +vec2 project_mercator_(vec2 lnglat) { +float x = lnglat.x; +if (project.wrapLongitude) { +x = mod(x + 180., 360.0) - 180.; +} +float y = clamp(lnglat.y, -89.9, 89.9); +return vec2( +radians(x) + PI, +PI + log(tan_fp32(PI * 0.25 + radians(y) * 0.5)) +) * WORLD_SCALE; +} +vec3 project_globe_(vec3 lnglatz) { +float lambda = radians(lnglatz.x); +float phi = radians(lnglatz.y); +float cosPhi = cos(phi); +float D = (lnglatz.z / EARTH_RADIUS + 1.0) * GLOBE_RADIUS; +return vec3( +sin(lambda) * cosPhi, +-cos(lambda) * cosPhi, +sin(phi) +) * D; +} +vec4 project_position(vec4 position, vec3 position64Low) { +vec4 position_world = project.modelMatrix * position; +if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR) { +if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) { +return vec4( +project_mercator_(position_world.xy), +project_size_at_latitude(position_world.z, position_world.y), +position_world.w +); +} +if (project.coordinateSystem == COORDINATE_SYSTEM_CARTESIAN) { +position_world.xyz += project.coordinateOrigin; +} +} +if (project.projectionMode == PROJECTION_MODE_GLOBE) { +if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) { +return vec4( +project_globe_(position_world.xyz), +position_world.w +); +} +} +if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR_AUTO_OFFSET) { +if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) { +if (abs(position_world.y - project.coordinateOrigin.y) > 0.25) { +return vec4( +project_mercator_(position_world.xy) - project.commonOrigin.xy, +project_size(position_world.z), +position_world.w +); +} +} +} +if (project.projectionMode == PROJECTION_MODE_IDENTITY || +(project.projectionMode == PROJECTION_MODE_WEB_MERCATOR_AUTO_OFFSET && +(project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT || +project.coordinateSystem == COORDINATE_SYSTEM_CARTESIAN))) { +position_world.xyz -= project.coordinateOrigin; +} +return project_offset_(position_world) + project_offset_(project.modelMatrix * vec4(position64Low, 0.0)); +} +vec4 project_position(vec4 position) { +return project_position(position, ZERO_64_LOW); +} +vec3 project_position(vec3 position, vec3 position64Low) { +vec4 projected_position = project_position(vec4(position, 1.0), position64Low); +return projected_position.xyz; +} +vec3 project_position(vec3 position) { +vec4 projected_position = project_position(vec4(position, 1.0), ZERO_64_LOW); +return projected_position.xyz; +} +vec2 project_position(vec2 position) { +vec4 projected_position = project_position(vec4(position, 0.0, 1.0), ZERO_64_LOW); +return projected_position.xy; +} +vec4 project_common_position_to_clipspace(vec4 position, mat4 viewProjectionMatrix, vec4 center) { +return viewProjectionMatrix * position + center; +} +vec4 project_common_position_to_clipspace(vec4 position) { +return project_common_position_to_clipspace(position, project.viewProjectionMatrix, project.center); +} +vec2 project_pixel_size_to_clipspace(vec2 pixels) { +vec2 offset = pixels / project.viewportSize * project.devicePixelRatio * 2.0; +return offset * project.focalDistance; +} +float project_size_to_pixel(float meters) { +return project_size(meters) * project.scale; +} +vec2 project_size_to_pixel(vec2 meters) { +return project_size(meters) * project.scale; +} +float project_size_to_pixel(float size, int unit) { +if (unit == UNIT_METERS) return project_size_to_pixel(size); +if (unit == UNIT_COMMON) return size * project.scale; +return size; +} +float project_pixel_size(float pixels) { +return pixels / project.scale; +} +vec2 project_pixel_size(vec2 pixels) { +return pixels / project.scale; +} +` + ); + + // node_modules/@deck.gl/core/dist/shaderlib/project/project.js + var INITIAL_MODULE_OPTIONS = {}; + function getUniforms2(opts = INITIAL_MODULE_OPTIONS) { + if ("viewport" in opts) { + return getUniformsFromViewport(opts); + } + return {}; + } + var project_default = { + name: "project", + dependencies: [fp32, geometry_default], + source: projectWGSL, + vs: projectGLSL, + getUniforms: getUniforms2, + uniformTypes: { + wrapLongitude: "f32", + coordinateSystem: "i32", + commonUnitsPerMeter: "vec3", + projectionMode: "i32", + scale: "f32", + commonUnitsPerWorldUnit: "vec3", + commonUnitsPerWorldUnit2: "vec3", + center: "vec4", + modelMatrix: "mat4x4", + viewProjectionMatrix: "mat4x4", + viewportSize: "vec2", + devicePixelRatio: "f32", + focalDistance: "f32", + cameraPosition: "vec3", + coordinateOrigin: "vec3", + commonOrigin: "vec3", + pseudoMeters: "f32" + } + // @ts-ignore TODO v9.1 + }; + + // node_modules/@deck.gl/core/dist/shaderlib/project32/project32.js + var source2 = ( + /* wgsl */ + `// Define a structure to hold both the clip-space position and the common position. +struct ProjectResult { + clipPosition: vec4, + commonPosition: vec4, +}; + +// This function mimics the GLSL version with the 'out' parameter by returning both values. +fn project_position_to_clipspace_and_commonspace( + position: vec3, + position64Low: vec3, + offset: vec3 +) -> ProjectResult { + // Compute the projected position. + let projectedPosition: vec3 = project_position_vec3_f64(position, position64Low); + + // Start with the provided offset. + var finalOffset: vec3 = offset; + + // Get whether a rotation is needed and the rotation matrix. + let rotationResult = project_needs_rotation(projectedPosition); + + // If rotation is needed, update the offset. + if (rotationResult.needsRotation) { + finalOffset = rotationResult.transform * offset; + } + + // Compute the common position. + let commonPosition: vec4 = vec4(projectedPosition + finalOffset, 1.0); + + // Convert to clip-space. + let clipPosition: vec4 = project_common_position_to_clipspace(commonPosition); + + return ProjectResult(clipPosition, commonPosition); +} + +// A convenience overload that returns only the clip-space position. +fn project_position_to_clipspace( + position: vec3, + position64Low: vec3, + offset: vec3 +) -> vec4 { + return project_position_to_clipspace_and_commonspace(position, position64Low, offset).clipPosition; +} +` + ); + var vs3 = ( + /* glsl */ + `vec4 project_position_to_clipspace( + vec3 position, vec3 position64Low, vec3 offset, out vec4 commonPosition +) { + vec3 projectedPosition = project_position(position, position64Low); + mat3 rotation; + if (project_needs_rotation(projectedPosition, rotation)) { + // offset is specified as ENU + // when in globe projection, rotate offset so that the ground alighs with the surface of the globe + offset = rotation * offset; + } + commonPosition = vec4(projectedPosition + offset, 1.0); + return project_common_position_to_clipspace(commonPosition); +} + +vec4 project_position_to_clipspace( + vec3 position, vec3 position64Low, vec3 offset +) { + vec4 commonPosition; + return project_position_to_clipspace(position, position64Low, offset, commonPosition); +} +` + ); + var project32_default = { + name: "project32", + dependencies: [project_default], + source: source2, + vs: vs3 + }; + + // node_modules/@math.gl/web-mercator/dist/math-utils.js + function createMat4() { + return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]; + } + function transformVector(matrix, vector) { + const result = vec4_exports.transformMat4([], vector, matrix); + vec4_exports.scale(result, result, 1 / result[3]); + return result; + } + function clamp2(x, min5, max4) { + return x < min5 ? min5 : x > max4 ? max4 : x; + } + function ieLog2(x) { + return Math.log(x) * Math.LOG2E; + } + var log22 = Math.log2 || ieLog2; + + // node_modules/@math.gl/web-mercator/dist/assert.js + function assert7(condition, message2) { + if (!condition) { + throw new Error(message2 || "@math.gl/web-mercator: assertion failed."); + } + } + + // node_modules/@math.gl/web-mercator/dist/web-mercator-utils.js + var PI = Math.PI; + var PI_4 = PI / 4; + var DEGREES_TO_RADIANS2 = PI / 180; + var RADIANS_TO_DEGREES2 = 180 / PI; + var TILE_SIZE = 512; + var EARTH_CIRCUMFERENCE = 4003e4; + var MAX_LATITUDE = 85.051129; + var DEFAULT_ALTITUDE = 1.5; + function zoomToScale(zoom) { + return Math.pow(2, zoom); + } + function scaleToZoom(scale5) { + return log22(scale5); + } + function lngLatToWorld(lngLat) { + const [lng, lat] = lngLat; + assert7(Number.isFinite(lng)); + assert7(Number.isFinite(lat) && lat >= -90 && lat <= 90, "invalid latitude"); + const lambda22 = lng * DEGREES_TO_RADIANS2; + const phi2 = lat * DEGREES_TO_RADIANS2; + const x = TILE_SIZE * (lambda22 + PI) / (2 * PI); + const y = TILE_SIZE * (PI + Math.log(Math.tan(PI_4 + phi2 * 0.5))) / (2 * PI); + return [x, y]; + } + function worldToLngLat(xy) { + const [x, y] = xy; + const lambda22 = x / TILE_SIZE * (2 * PI) - PI; + const phi2 = 2 * (Math.atan(Math.exp(y / TILE_SIZE * (2 * PI) - PI)) - PI_4); + return [lambda22 * RADIANS_TO_DEGREES2, phi2 * RADIANS_TO_DEGREES2]; + } + function getMeterZoom(options) { + const { latitude } = options; + assert7(Number.isFinite(latitude)); + const latCosine = Math.cos(latitude * DEGREES_TO_RADIANS2); + return scaleToZoom(EARTH_CIRCUMFERENCE * latCosine) - 9; + } + function unitsPerMeter(latitude) { + const latCosine = Math.cos(latitude * DEGREES_TO_RADIANS2); + return TILE_SIZE / EARTH_CIRCUMFERENCE / latCosine; + } + function getDistanceScales(options) { + const { latitude, longitude, highPrecision = false } = options; + assert7(Number.isFinite(latitude) && Number.isFinite(longitude)); + const worldSize = TILE_SIZE; + const latCosine = Math.cos(latitude * DEGREES_TO_RADIANS2); + const unitsPerDegreeX = worldSize / 360; + const unitsPerDegreeY = unitsPerDegreeX / latCosine; + const altUnitsPerMeter = worldSize / EARTH_CIRCUMFERENCE / latCosine; + const result = { + unitsPerMeter: [altUnitsPerMeter, altUnitsPerMeter, altUnitsPerMeter], + metersPerUnit: [1 / altUnitsPerMeter, 1 / altUnitsPerMeter, 1 / altUnitsPerMeter], + unitsPerDegree: [unitsPerDegreeX, unitsPerDegreeY, altUnitsPerMeter], + degreesPerUnit: [1 / unitsPerDegreeX, 1 / unitsPerDegreeY, 1 / altUnitsPerMeter] + }; + if (highPrecision) { + const latCosine2 = DEGREES_TO_RADIANS2 * Math.tan(latitude * DEGREES_TO_RADIANS2) / latCosine; + const unitsPerDegreeY2 = unitsPerDegreeX * latCosine2 / 2; + const altUnitsPerDegree2 = worldSize / EARTH_CIRCUMFERENCE * latCosine2; + const altUnitsPerMeter2 = altUnitsPerDegree2 / unitsPerDegreeY * altUnitsPerMeter; + result.unitsPerDegree2 = [0, unitsPerDegreeY2, altUnitsPerDegree2]; + result.unitsPerMeter2 = [altUnitsPerMeter2, 0, altUnitsPerMeter2]; + } + return result; + } + function addMetersToLngLat(lngLatZ, xyz) { + const [longitude, latitude, z0] = lngLatZ; + const [x, y, z] = xyz; + const { unitsPerMeter: unitsPerMeter2, unitsPerMeter2: unitsPerMeter22 } = getDistanceScales({ + longitude, + latitude, + highPrecision: true + }); + const worldspace = lngLatToWorld(lngLatZ); + worldspace[0] += x * (unitsPerMeter2[0] + unitsPerMeter22[0] * y); + worldspace[1] += y * (unitsPerMeter2[1] + unitsPerMeter22[1] * y); + const newLngLat = worldToLngLat(worldspace); + const newZ = (z0 || 0) + (z || 0); + return Number.isFinite(z0) || Number.isFinite(z) ? [newLngLat[0], newLngLat[1], newZ] : newLngLat; + } + function getViewMatrix(options) { + const { + // Viewport props + height, + pitch, + bearing, + altitude, + // Pre-calculated parameters + scale: scale5, + center + } = options; + const vm = createMat4(); + mat4_exports.translate(vm, vm, [0, 0, -altitude]); + mat4_exports.rotateX(vm, vm, -pitch * DEGREES_TO_RADIANS2); + mat4_exports.rotateZ(vm, vm, bearing * DEGREES_TO_RADIANS2); + const relativeScale = scale5 / height; + mat4_exports.scale(vm, vm, [relativeScale, relativeScale, relativeScale]); + if (center) { + mat4_exports.translate(vm, vm, vec3_exports.negate([], center)); + } + return vm; + } + function getProjectionParameters(options) { + const { width, height, altitude, pitch = 0, offset, center, scale: scale5, nearZMultiplier = 1, farZMultiplier = 1 } = options; + let { fovy = altitudeToFovy(DEFAULT_ALTITUDE) } = options; + if (altitude !== void 0) { + fovy = altitudeToFovy(altitude); + } + const fovRadians = fovy * DEGREES_TO_RADIANS2; + const pitchRadians = pitch * DEGREES_TO_RADIANS2; + const focalDistance = fovyToAltitude(fovy); + let cameraToSeaLevelDistance = focalDistance; + if (center) { + cameraToSeaLevelDistance += center[2] * scale5 / Math.cos(pitchRadians) / height; + } + const fovAboveCenter = fovRadians * (0.5 + (offset ? offset[1] : 0) / height); + const topHalfSurfaceDistance = Math.sin(fovAboveCenter) * cameraToSeaLevelDistance / Math.sin(clamp2(Math.PI / 2 - pitchRadians - fovAboveCenter, 0.01, Math.PI - 0.01)); + const furthestDistance = Math.sin(pitchRadians) * topHalfSurfaceDistance + cameraToSeaLevelDistance; + const horizonDistance = cameraToSeaLevelDistance * 10; + const farZ = Math.min(furthestDistance * farZMultiplier, horizonDistance); + return { + fov: fovRadians, + aspect: width / height, + focalDistance, + near: nearZMultiplier, + far: farZ + }; + } + function getProjectionMatrix(options) { + const { fov, aspect, near, far } = getProjectionParameters(options); + const projectionMatrix = mat4_exports.perspective( + [], + fov, + // fov in radians + aspect, + // aspect ratio + near, + // near plane + far + // far plane + ); + return projectionMatrix; + } + function altitudeToFovy(altitude) { + return 2 * Math.atan(0.5 / altitude) * RADIANS_TO_DEGREES2; + } + function fovyToAltitude(fovy) { + return 0.5 / Math.tan(0.5 * fovy * DEGREES_TO_RADIANS2); + } + function worldToPixels(xyz, pixelProjectionMatrix) { + const [x, y, z = 0] = xyz; + assert7(Number.isFinite(x) && Number.isFinite(y) && Number.isFinite(z)); + return transformVector(pixelProjectionMatrix, [x, y, z, 1]); + } + function pixelsToWorld(xyz, pixelUnprojectionMatrix, targetZ = 0) { + const [x, y, z] = xyz; + assert7(Number.isFinite(x) && Number.isFinite(y), "invalid pixel coordinate"); + if (Number.isFinite(z)) { + const coord = transformVector(pixelUnprojectionMatrix, [x, y, z, 1]); + return coord; + } + const coord0 = transformVector(pixelUnprojectionMatrix, [x, y, 0, 1]); + const coord1 = transformVector(pixelUnprojectionMatrix, [x, y, 1, 1]); + const z0 = coord0[2]; + const z1 = coord1[2]; + const t = z0 === z1 ? 0 : ((targetZ || 0) - z0) / (z1 - z0); + return vec2_exports.lerp([], coord0, coord1, t); + } + + // node_modules/@math.gl/web-mercator/dist/fit-bounds.js + function fitBounds(options) { + const { + width, + height, + bounds, + minExtent = 0, + // 0.01 would be about 1000 meters (degree is ~110KM) + maxZoom = 24, + // ~x4,000,000 => About 10 meter extents + offset = [0, 0] + } = options; + const [[west, south], [east, north]] = bounds; + const padding = getPaddingObject(options.padding); + const nw = lngLatToWorld([west, clamp2(north, -MAX_LATITUDE, MAX_LATITUDE)]); + const se = lngLatToWorld([east, clamp2(south, -MAX_LATITUDE, MAX_LATITUDE)]); + const size = [ + Math.max(Math.abs(se[0] - nw[0]), minExtent), + Math.max(Math.abs(se[1] - nw[1]), minExtent) + ]; + const targetSize = [ + width - padding.left - padding.right - Math.abs(offset[0]) * 2, + height - padding.top - padding.bottom - Math.abs(offset[1]) * 2 + ]; + assert7(targetSize[0] > 0 && targetSize[1] > 0); + const scaleX2 = targetSize[0] / size[0]; + const scaleY2 = targetSize[1] / size[1]; + const offsetX = (padding.right - padding.left) / 2 / scaleX2; + const offsetY = (padding.top - padding.bottom) / 2 / scaleY2; + const center = [(se[0] + nw[0]) / 2 + offsetX, (se[1] + nw[1]) / 2 + offsetY]; + const centerLngLat = worldToLngLat(center); + const zoom = Math.min(maxZoom, log22(Math.abs(Math.min(scaleX2, scaleY2)))); + assert7(Number.isFinite(zoom)); + return { + longitude: centerLngLat[0], + latitude: centerLngLat[1], + zoom + }; + } + function getPaddingObject(padding = 0) { + if (typeof padding === "number") { + return { + top: padding, + bottom: padding, + left: padding, + right: padding + }; + } + assert7(Number.isFinite(padding.top) && Number.isFinite(padding.bottom) && Number.isFinite(padding.left) && Number.isFinite(padding.right)); + return padding; + } + + // node_modules/@math.gl/web-mercator/dist/get-bounds.js + var DEGREES_TO_RADIANS3 = Math.PI / 180; + function getBounds(viewport, z = 0) { + const { width, height, unproject } = viewport; + const unprojectOps = { targetZ: z }; + const bottomLeft = unproject([0, height], unprojectOps); + const bottomRight = unproject([width, height], unprojectOps); + let topLeft; + let topRight; + const halfFov = viewport.fovy ? 0.5 * viewport.fovy * DEGREES_TO_RADIANS3 : Math.atan(0.5 / viewport.altitude); + const angleToGround = (90 - viewport.pitch) * DEGREES_TO_RADIANS3; + if (halfFov > angleToGround - 0.01) { + topLeft = unprojectOnFarPlane(viewport, 0, z); + topRight = unprojectOnFarPlane(viewport, width, z); + } else { + topLeft = unproject([0, 0], unprojectOps); + topRight = unproject([width, 0], unprojectOps); + } + return [bottomLeft, bottomRight, topRight, topLeft]; + } + function unprojectOnFarPlane(viewport, x, targetZ) { + const { pixelUnprojectionMatrix } = viewport; + const coord0 = transformVector(pixelUnprojectionMatrix, [x, 0, 1, 1]); + const coord1 = transformVector(pixelUnprojectionMatrix, [x, viewport.height, 1, 1]); + const z = targetZ * viewport.distanceScales.unitsPerMeter[2]; + const t = (z - coord0[2]) / (coord1[2] - coord0[2]); + const coord = vec2_exports.lerp([], coord0, coord1, t); + const result = worldToLngLat(coord); + result.push(targetZ); + return result; + } + + // node_modules/@math.gl/web-mercator/dist/web-mercator-viewport.js + var WebMercatorViewport = class _WebMercatorViewport { + /** + * @classdesc + * Creates view/projection matrices from mercator params + * Note: The Viewport is immutable in the sense that it only has accessors. + * A new viewport instance should be created if any parameters have changed. + */ + // eslint-disable-next-line max-statements + constructor(props = { width: 1, height: 1 }) { + this.equals = (viewport) => { + if (!(viewport instanceof _WebMercatorViewport)) { + return false; + } + return viewport.width === this.width && viewport.height === this.height && mat4_exports.equals(viewport.projectionMatrix, this.projectionMatrix) && mat4_exports.equals(viewport.viewMatrix, this.viewMatrix); + }; + this.project = (lngLatZ, options = {}) => { + const { topLeft = true } = options; + const worldPosition = this.projectPosition(lngLatZ); + const coord = worldToPixels(worldPosition, this.pixelProjectionMatrix); + const [x, y] = coord; + const y2 = topLeft ? y : this.height - y; + return lngLatZ.length === 2 ? [x, y2] : [x, y2, coord[2]]; + }; + this.unproject = (xyz, options = {}) => { + const { topLeft = true, targetZ = void 0 } = options; + const [x, y, z] = xyz; + const y2 = topLeft ? y : this.height - y; + const targetZWorld = targetZ && targetZ * this.distanceScales.unitsPerMeter[2]; + const coord = pixelsToWorld([x, y2, z], this.pixelUnprojectionMatrix, targetZWorld); + const [X, Y, Z] = this.unprojectPosition(coord); + if (Number.isFinite(z)) { + return [X, Y, Z]; + } + return Number.isFinite(targetZ) ? [X, Y, targetZ] : [X, Y]; + }; + this.projectPosition = (xyz) => { + const [X, Y] = lngLatToWorld(xyz); + const Z = (xyz[2] || 0) * this.distanceScales.unitsPerMeter[2]; + return [X, Y, Z]; + }; + this.unprojectPosition = (xyz) => { + const [X, Y] = worldToLngLat(xyz); + const Z = (xyz[2] || 0) * this.distanceScales.metersPerUnit[2]; + return [X, Y, Z]; + }; + let { + // Map state + width, + height, + altitude = null, + fovy = null + } = props; + const { latitude = 0, longitude = 0, zoom = 0, pitch = 0, bearing = 0, position = null, nearZMultiplier = 0.02, farZMultiplier = 1.01 } = props; + width = width || 1; + height = height || 1; + if (fovy === null && altitude === null) { + altitude = DEFAULT_ALTITUDE; + fovy = altitudeToFovy(altitude); + } else if (fovy === null) { + fovy = altitudeToFovy(altitude); + } else if (altitude === null) { + altitude = fovyToAltitude(fovy); + } + const scale5 = zoomToScale(zoom); + altitude = Math.max(0.75, altitude); + const distanceScales = getDistanceScales({ longitude, latitude }); + const center = lngLatToWorld([longitude, latitude]); + center.push(0); + if (position) { + vec3_exports.add(center, center, vec3_exports.mul([], position, distanceScales.unitsPerMeter)); + } + this.projectionMatrix = getProjectionMatrix({ + width, + height, + scale: scale5, + center, + pitch, + fovy, + nearZMultiplier, + farZMultiplier + }); + this.viewMatrix = getViewMatrix({ + height, + scale: scale5, + center, + pitch, + bearing, + altitude + }); + this.width = width; + this.height = height; + this.scale = scale5; + this.latitude = latitude; + this.longitude = longitude; + this.zoom = zoom; + this.pitch = pitch; + this.bearing = bearing; + this.altitude = altitude; + this.fovy = fovy; + this.center = center; + this.meterOffset = position || [0, 0, 0]; + this.distanceScales = distanceScales; + this._initMatrices(); + Object.freeze(this); + } + _initMatrices() { + const { width, height, projectionMatrix, viewMatrix } = this; + const vpm = createMat4(); + mat4_exports.multiply(vpm, vpm, projectionMatrix); + mat4_exports.multiply(vpm, vpm, viewMatrix); + this.viewProjectionMatrix = vpm; + const m = createMat4(); + mat4_exports.scale(m, m, [width / 2, -height / 2, 1]); + mat4_exports.translate(m, m, [1, -1, 0]); + mat4_exports.multiply(m, m, vpm); + const mInverse = mat4_exports.invert(createMat4(), m); + if (!mInverse) { + throw new Error("Pixel project matrix not invertible"); + } + this.pixelProjectionMatrix = m; + this.pixelUnprojectionMatrix = mInverse; + } + /** + * Project [lng,lat] on sphere onto [x,y] on 512*512 Mercator Zoom 0 tile. + * Performs the nonlinear part of the web mercator projection. + * Remaining projection is done with 4x4 matrices which also handles + * perspective. + * + * @param lngLat - [lng, lat] coordinates + * Specifies a point on the sphere to project onto the map. + * @return [x,y] coordinates. + */ + projectFlat(lngLat) { + return lngLatToWorld(lngLat); + } + /** + * Unproject world point [x,y] on map onto {lat, lon} on sphere + * + * @param xy - array with [x,y] members + * representing point on projected map plane + * @return - array with [lat,lon] of point on sphere. + * Has toArray method if you need a GeoJSON Array. + * Per cartographic tradition, lat and lon are specified as degrees. + */ + unprojectFlat(xy) { + return worldToLngLat(xy); + } + /** + * Get the map center that place a given [lng, lat] coordinate at screen point [x, y] + * @param opt + * @param opt.lngLat - [lng,lat] coordinates + * Specifies a point on the sphere. + * @param opt.pos - [x,y] coordinates + * Specifies a point on the screen. + * @return [lng,lat] new map center. + */ + getMapCenterByLngLatPosition({ lngLat, pos }) { + const fromLocation = pixelsToWorld(pos, this.pixelUnprojectionMatrix); + const toLocation = lngLatToWorld(lngLat); + const translate2 = vec2_exports.add([], toLocation, vec2_exports.negate([], fromLocation)); + const newCenter = vec2_exports.add([], this.center, translate2); + return worldToLngLat(newCenter); + } + /** + * Returns a new viewport that fit around the given rectangle. + * Only supports non-perspective mode. + * @param bounds - [[lon, lat], [lon, lat]] + * @param [options] + * @param [options.padding] - The amount of padding in pixels to add to the given bounds. + * @param [options.offset] - The center of the given bounds relative to the map's center, + * [x, y] measured in pixels. + * @returns {WebMercatorViewport} + */ + fitBounds(bounds, options = {}) { + const { width, height } = this; + const { longitude, latitude, zoom } = fitBounds(Object.assign({ width, height, bounds }, options)); + return new _WebMercatorViewport({ width, height, longitude, latitude, zoom }); + } + /** + * Returns the bounding box of the viewport. + * @param [options] + * @param [options.z] - The altitude at which the bounds should be calculated. + * @returns {Array} bounds - [[lon, lat], [lon, lat]] + */ + getBounds(options) { + const corners = this.getBoundingRegion(options); + const west = Math.min(...corners.map((p) => p[0])); + const east = Math.max(...corners.map((p) => p[0])); + const south = Math.min(...corners.map((p) => p[1])); + const north = Math.max(...corners.map((p) => p[1])); + return [ + [west, south], + [east, north] + ]; + } + /** + * Returns the bounding box of the viewport. + * @param [options] + * @param [options.z] - The altitude at which the bounds should be calculated. + * @returns {Array} an array of 4 points that define the visible region + */ + getBoundingRegion(options = {}) { + return getBounds(this, options.z || 0); + } + // DEPRECATED + /** @deprecated Legacy method name */ + getLocationAtPoint({ lngLat, pos }) { + return this.getMapCenterByLngLatPosition({ lngLat, pos }); + } + }; + + // node_modules/@deck.gl/core/dist/shaderlib/shadow/shadow.js + var uniformBlock2 = ( + /* glsl */ + ` +layout(std140) uniform shadowUniforms { + bool drawShadowMap; + bool useShadowMap; + vec4 color; + highp int lightId; + float lightCount; + mat4 viewProjectionMatrix0; + mat4 viewProjectionMatrix1; + vec4 projectCenter0; + vec4 projectCenter1; +} shadow; +` + ); + var vertex = ( + /* glsl */ + ` +const int max_lights = 2; + +out vec3 shadow_vPosition[max_lights]; + +vec4 shadow_setVertexPosition(vec4 position_commonspace) { + mat4 viewProjectionMatrices[max_lights]; + viewProjectionMatrices[0] = shadow.viewProjectionMatrix0; + viewProjectionMatrices[1] = shadow.viewProjectionMatrix1; + vec4 projectCenters[max_lights]; + projectCenters[0] = shadow.projectCenter0; + projectCenters[1] = shadow.projectCenter1; + + if (shadow.drawShadowMap) { + return project_common_position_to_clipspace(position_commonspace, viewProjectionMatrices[shadow.lightId], projectCenters[shadow.lightId]); + } + if (shadow.useShadowMap) { + for (int i = 0; i < max_lights; i++) { + if(i < int(shadow.lightCount)) { + vec4 shadowMap_position = project_common_position_to_clipspace(position_commonspace, viewProjectionMatrices[i], projectCenters[i]); + shadow_vPosition[i] = (shadowMap_position.xyz / shadowMap_position.w + 1.0) / 2.0; + } + } + } + return gl_Position; +} +` + ); + var vs4 = ` +${uniformBlock2} +${vertex} +`; + var fragment = ( + /* glsl */ + ` +const int max_lights = 2; +uniform sampler2D shadow_uShadowMap0; +uniform sampler2D shadow_uShadowMap1; + +in vec3 shadow_vPosition[max_lights]; + +const vec4 bitPackShift = vec4(1.0, 255.0, 65025.0, 16581375.0); +const vec4 bitUnpackShift = 1.0 / bitPackShift; +const vec4 bitMask = vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0); + +float shadow_getShadowWeight(vec3 position, sampler2D shadowMap) { + vec4 rgbaDepth = texture(shadowMap, position.xy); + + float z = dot(rgbaDepth, bitUnpackShift); + return smoothstep(0.001, 0.01, position.z - z); +} + +vec4 shadow_filterShadowColor(vec4 color) { + if (shadow.drawShadowMap) { + vec4 rgbaDepth = fract(gl_FragCoord.z * bitPackShift); + rgbaDepth -= rgbaDepth.gbaa * bitMask; + return rgbaDepth; + } + if (shadow.useShadowMap) { + float shadowAlpha = 0.0; + shadowAlpha += shadow_getShadowWeight(shadow_vPosition[0], shadow_uShadowMap0); + if(shadow.lightCount > 1.0) { + shadowAlpha += shadow_getShadowWeight(shadow_vPosition[1], shadow_uShadowMap1); + } + shadowAlpha *= shadow.color.a / shadow.lightCount; + float blendedAlpha = shadowAlpha + color.a * (1.0 - shadowAlpha); + + return vec4( + mix(color.rgb, shadow.color.rgb, shadowAlpha / blendedAlpha), + blendedAlpha + ); + } + return color; +} +` + ); + var fs3 = ` +${uniformBlock2} +${fragment} +`; + var getMemoizedViewportCenterPosition = memoize(getViewportCenterPosition); + var getMemoizedViewProjectionMatrices = memoize(getViewProjectionMatrices); + var DEFAULT_SHADOW_COLOR = [0, 0, 0, 1]; + var VECTOR_TO_POINT_MATRIX2 = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]; + function screenToCommonSpace(xyz, pixelUnprojectionMatrix) { + const [x, y, z] = xyz; + const coord = pixelsToWorld([x, y, z], pixelUnprojectionMatrix); + if (Number.isFinite(z)) { + return coord; + } + return [coord[0], coord[1], 0]; + } + function getViewportCenterPosition({ viewport, center }) { + return new Matrix4(viewport.viewProjectionMatrix).invert().transform(center); + } + function getViewProjectionMatrices({ viewport, shadowMatrices }) { + const projectionMatrices = []; + const pixelUnprojectionMatrix = viewport.pixelUnprojectionMatrix; + const farZ = viewport.isGeospatial ? void 0 : 1; + const corners = [ + [0, 0, farZ], + // top left ground + [viewport.width, 0, farZ], + // top right ground + [0, viewport.height, farZ], + // bottom left ground + [viewport.width, viewport.height, farZ], + // bottom right ground + [0, 0, -1], + // top left near + [viewport.width, 0, -1], + // top right near + [0, viewport.height, -1], + // bottom left near + [viewport.width, viewport.height, -1] + // bottom right near + ].map((pixel) => ( + // @ts-expect-error z may be undefined + screenToCommonSpace(pixel, pixelUnprojectionMatrix) + )); + for (const shadowMatrix of shadowMatrices) { + const viewMatrix = shadowMatrix.clone().translate(new Vector3(viewport.center).negate()); + const positions = corners.map((corner) => viewMatrix.transform(corner)); + const projectionMatrix = new Matrix4().ortho({ + left: Math.min(...positions.map((position) => position[0])), + right: Math.max(...positions.map((position) => position[0])), + bottom: Math.min(...positions.map((position) => position[1])), + top: Math.max(...positions.map((position) => position[1])), + near: Math.min(...positions.map((position) => -position[2])), + far: Math.max(...positions.map((position) => -position[2])) + }); + projectionMatrices.push(projectionMatrix.multiplyRight(shadowMatrix)); + } + return projectionMatrices; + } + function createShadowUniforms(opts) { + const { shadowEnabled = true, project: projectProps } = opts; + if (!shadowEnabled || !projectProps || !opts.shadowMatrices || !opts.shadowMatrices.length) { + return { + drawShadowMap: false, + useShadowMap: false, + shadow_uShadowMap0: opts.dummyShadowMap, + shadow_uShadowMap1: opts.dummyShadowMap + }; + } + const projectUniforms = project_default.getUniforms(projectProps); + const center = getMemoizedViewportCenterPosition({ + viewport: projectProps.viewport, + center: projectUniforms.center + }); + const projectCenters = []; + const viewProjectionMatrices = getMemoizedViewProjectionMatrices({ + shadowMatrices: opts.shadowMatrices, + viewport: projectProps.viewport + }).slice(); + for (let i = 0; i < opts.shadowMatrices.length; i++) { + const viewProjectionMatrix = viewProjectionMatrices[i]; + const viewProjectionMatrixCentered = viewProjectionMatrix.clone().translate(new Vector3(projectProps.viewport.center).negate()); + if (projectUniforms.coordinateSystem === getShaderCoordinateSystem("lnglat") && projectUniforms.projectionMode === PROJECTION_MODE.WEB_MERCATOR) { + viewProjectionMatrices[i] = viewProjectionMatrixCentered; + projectCenters[i] = center; + } else { + viewProjectionMatrices[i] = viewProjectionMatrix.clone().multiplyRight(VECTOR_TO_POINT_MATRIX2); + projectCenters[i] = viewProjectionMatrixCentered.transform(center); + } + } + const uniforms = { + drawShadowMap: Boolean(opts.drawToShadowMap), + useShadowMap: opts.shadowMaps ? opts.shadowMaps.length > 0 : false, + color: opts.shadowColor || DEFAULT_SHADOW_COLOR, + lightId: opts.shadowLightId || 0, + lightCount: opts.shadowMatrices.length, + shadow_uShadowMap0: opts.dummyShadowMap, + shadow_uShadowMap1: opts.dummyShadowMap + }; + for (let i = 0; i < viewProjectionMatrices.length; i++) { + uniforms[`viewProjectionMatrix${i}`] = viewProjectionMatrices[i]; + uniforms[`projectCenter${i}`] = projectCenters[i]; + } + for (let i = 0; i < 2; i++) { + uniforms[`shadow_uShadowMap${i}`] = opts.shadowMaps && opts.shadowMaps[i] || opts.dummyShadowMap; + } + return uniforms; + } + var shadow_default = { + name: "shadow", + dependencies: [project_default], + vs: vs4, + fs: fs3, + inject: { + "vs:DECKGL_FILTER_GL_POSITION": ` + position = shadow_setVertexPosition(geometry.position); + `, + "fs:DECKGL_FILTER_COLOR": ` + color = shadow_filterShadowColor(color); + ` + }, + getUniforms: createShadowUniforms, + uniformTypes: { + drawShadowMap: "f32", + useShadowMap: "f32", + color: "vec4", + lightId: "i32", + lightCount: "f32", + viewProjectionMatrix0: "mat4x4", + viewProjectionMatrix1: "mat4x4", + projectCenter0: "vec4", + projectCenter1: "vec4" + } + }; + + // node_modules/@deck.gl/core/dist/shaderlib/picking/picking.js + var sourceWGSL = ( + /* wgsl */ + `struct pickingUniforms { + isActive: f32, + isAttribute: f32, + isHighlightActive: f32, + useByteColors: f32, + highlightedObjectColor: vec3, + highlightColor: vec4, +}; + +@group(0) @binding(auto) var picking: pickingUniforms; + +fn picking_normalizeColor(color: vec3) -> vec3 { + return select(color, color / 255.0, picking.useByteColors > 0.5); +} + +fn picking_normalizeColor4(color: vec4) -> vec4 { + return select(color, color / 255.0, picking.useByteColors > 0.5); +} + +fn picking_isColorZero(color: vec3) -> bool { + return dot(color, vec3(1.0)) < 0.00001; +} + +fn picking_isColorValid(color: vec3) -> bool { + return dot(color, vec3(1.0)) > 0.00001; +} +` + ); + var picking_default = { + ...picking, + source: sourceWGSL, + defaultUniforms: { ...picking.defaultUniforms, useByteColors: true }, + inject: { + "vs:DECKGL_FILTER_GL_POSITION": ` + // for picking depth values + picking_setPickingAttribute(position.z / position.w); + `, + "vs:DECKGL_FILTER_COLOR": ` + picking_setPickingColor(geometry.pickingColor); + `, + "fs:DECKGL_FILTER_COLOR": { + order: 99, + injection: ` + // use highlight color if this fragment belongs to the selected object. + color = picking_filterHighlightColor(color); + + // use picking color if rendering to picking FBO. + color = picking_filterPickingColor(color); + ` + } + } + }; + + // node_modules/@deck.gl/core/dist/shaderlib/index.js + var DEFAULT_MODULES = [geometry_default]; + var SHADER_HOOKS_GLSL = [ + "vs:DECKGL_FILTER_SIZE(inout vec3 size, VertexGeometry geometry)", + "vs:DECKGL_FILTER_GL_POSITION(inout vec4 position, VertexGeometry geometry)", + "vs:DECKGL_FILTER_COLOR(inout vec4 color, VertexGeometry geometry)", + "fs:DECKGL_FILTER_COLOR(inout vec4 color, FragmentGeometry geometry)" + ]; + var SHADER_HOOKS_WGSL = [ + // Not yet supported + ]; + function getShaderAssembler(language) { + const shaderAssembler = ShaderAssembler.getDefaultShaderAssembler(); + for (const shaderModule of DEFAULT_MODULES) { + shaderAssembler.addDefaultModule(shaderModule); + } + shaderAssembler._hookFunctions.length = 0; + const shaderHooks = language === "glsl" ? SHADER_HOOKS_GLSL : SHADER_HOOKS_WGSL; + for (const shaderHook of shaderHooks) { + shaderAssembler.addShaderHook(shaderHook); + } + return shaderAssembler; + } + + // node_modules/@deck.gl/core/dist/effects/lighting/ambient-light.js + var DEFAULT_LIGHT_COLOR = [255, 255, 255]; + var DEFAULT_LIGHT_INTENSITY = 1; + var idCount = 0; + var AmbientLight = class { + constructor(props = {}) { + this.type = "ambient"; + const { color: color2 = DEFAULT_LIGHT_COLOR } = props; + const { intensity = DEFAULT_LIGHT_INTENSITY } = props; + this.id = props.id || `ambient-${idCount++}`; + this.color = color2; + this.intensity = intensity; + } + }; + + // node_modules/@deck.gl/core/dist/effects/lighting/directional-light.js + var DEFAULT_LIGHT_COLOR2 = [255, 255, 255]; + var DEFAULT_LIGHT_INTENSITY2 = 1; + var DEFAULT_LIGHT_DIRECTION = [0, 0, -1]; + var idCount2 = 0; + var DirectionalLight = class { + constructor(props = {}) { + this.type = "directional"; + const { color: color2 = DEFAULT_LIGHT_COLOR2 } = props; + const { intensity = DEFAULT_LIGHT_INTENSITY2 } = props; + const { direction = DEFAULT_LIGHT_DIRECTION } = props; + const { _shadow = false } = props; + this.id = props.id || `directional-${idCount2++}`; + this.color = color2; + this.intensity = intensity; + this.type = "directional"; + this.direction = new Vector3(direction).normalize().toArray(); + this.shadow = _shadow; + } + getProjectedLight(opts) { + return this; + } + }; + + // node_modules/@deck.gl/core/dist/passes/pass.js + var Pass = class { + /** Create a new Pass instance */ + constructor(device, props = { id: "pass" }) { + const { id } = props; + this.id = id; + this.device = device; + this.props = { ...props }; + } + setProps(props) { + Object.assign(this.props, props); + } + render(params) { + } + // eslint-disable-line @typescript-eslint/no-empty-function + cleanup() { + } + // eslint-disable-line @typescript-eslint/no-empty-function + }; + + // node_modules/@deck.gl/core/dist/passes/layers-pass.js + var WEBGPU_DEFAULT_DRAW_PARAMETERS = { + depthWriteEnabled: true, + depthCompare: "less-equal", + blendColorOperation: "add", + blendColorSrcFactor: "src-alpha", + blendColorDstFactor: "one", + blendAlphaOperation: "add", + blendAlphaSrcFactor: "one-minus-dst-alpha", + blendAlphaDstFactor: "one" + }; + var LayersPass = class extends Pass { + constructor() { + super(...arguments); + this._lastRenderIndex = -1; + } + render(options) { + this._render(options); + } + _render(options) { + const canvasContext = this.device.canvasContext; + const framebuffer = options.target ?? canvasContext.getCurrentFramebuffer(); + const [width, height] = canvasContext.getDrawingBufferSize(); + const clearCanvas = options.clearCanvas ?? true; + const clearColor = options.clearColor ?? (clearCanvas ? [0, 0, 0, 0] : false); + const clearDepth = clearCanvas ? 1 : false; + const clearStencil = clearCanvas ? 0 : false; + const colorMask = options.colorMask ?? 15; + const parameters = { viewport: [0, 0, width, height] }; + if (options.colorMask) { + parameters.colorMask = colorMask; + } + if (options.scissorRect) { + parameters.scissorRect = options.scissorRect; + } + const renderPass = this.device.beginRenderPass({ + framebuffer, + parameters, + clearColor, + clearDepth, + clearStencil + }); + try { + return this._drawLayers(renderPass, options); + } finally { + renderPass.end(); + this.device.submit(); + } + } + /** Draw a list of layers in a list of viewports */ + _drawLayers(renderPass, options) { + const { target: target2, shaderModuleProps, viewports, views, onViewportActive, clearStack = true } = options; + options.pass = options.pass || "unknown"; + if (clearStack) { + this._lastRenderIndex = -1; + } + const renderStats = []; + for (const viewport of viewports) { + const view = views && views[viewport.id]; + onViewportActive?.(viewport); + const drawLayerParams = this._getDrawLayerParams(viewport, options); + const subViewports = viewport.subViewports || [viewport]; + for (const subViewport of subViewports) { + const stats = this._drawLayersInViewport(renderPass, { + target: target2, + shaderModuleProps, + viewport: subViewport, + view, + pass: options.pass, + layers: options.layers + }, drawLayerParams); + renderStats.push(stats); + } + } + return renderStats; + } + // When a viewport contains multiple subviewports (e.g. repeated web mercator map), + // this is only done once for the parent viewport + /* Resolve the parameters needed to draw each layer */ + _getDrawLayerParams(viewport, { layers, pass, isPicking = false, layerFilter, cullRect, effects, shaderModuleProps }, evaluateShouldDrawOnly = false) { + const drawLayerParams = []; + const indexResolver = layerIndexResolver(this._lastRenderIndex + 1); + const drawContext = { + layer: layers[0], + viewport, + isPicking, + renderPass: pass, + cullRect + }; + const layerFilterCache = {}; + for (let layerIndex = 0; layerIndex < layers.length; layerIndex++) { + const layer = layers[layerIndex]; + const shouldDrawLayer = this._shouldDrawLayer(layer, drawContext, layerFilter, layerFilterCache); + const layerParam = { shouldDrawLayer }; + if (shouldDrawLayer && !evaluateShouldDrawOnly) { + layerParam.shouldDrawLayer = true; + layerParam.layerRenderIndex = indexResolver(layer, shouldDrawLayer); + layerParam.shaderModuleProps = this._getShaderModuleProps(layer, effects, pass, shaderModuleProps); + const defaultParams = layer.context.device.type === "webgpu" ? WEBGPU_DEFAULT_DRAW_PARAMETERS : null; + layerParam.layerParameters = { + ...defaultParams, + ...layer.context.deck?.props.parameters, + ...this.getLayerParameters(layer, layerIndex, viewport) + }; + } + drawLayerParams[layerIndex] = layerParam; + } + return drawLayerParams; + } + // Draws a list of layers in one viewport + // TODO - when picking we could completely skip rendering viewports that dont + // intersect with the picking rect + /* eslint-disable max-depth, max-statements, complexity */ + _drawLayersInViewport(renderPass, { layers, shaderModuleProps: globalModuleParameters, pass, target: target2, viewport, view }, drawLayerParams) { + const glViewport = getGLViewport(this.device, { + shaderModuleProps: globalModuleParameters, + target: target2, + viewport + }); + if (view) { + const { clear, clearColor, clearDepth, clearStencil } = view.props; + if (clear) { + let colorToUse = [0, 0, 0, 0]; + let depthToUse = 1; + let stencilToUse = 0; + if (Array.isArray(clearColor)) { + colorToUse = [...clearColor.slice(0, 3), clearColor[3] || 255].map((c2) => c2 / 255); + } else if (clearColor === false) { + colorToUse = false; + } + if (clearDepth !== void 0) { + depthToUse = clearDepth; + } + if (clearStencil !== void 0) { + stencilToUse = clearStencil; + } + const clearRenderPass = this.device.beginRenderPass({ + framebuffer: target2, + parameters: { + viewport: glViewport, + scissorRect: glViewport + }, + clearColor: colorToUse, + clearDepth: depthToUse, + clearStencil: stencilToUse + }); + clearRenderPass.end(); + } + } + const renderStatus = { + totalCount: layers.length, + visibleCount: 0, + compositeCount: 0, + pickableCount: 0 + }; + renderPass.setParameters({ viewport: glViewport }); + for (let layerIndex = 0; layerIndex < layers.length; layerIndex++) { + const layer = layers[layerIndex]; + const drawLayerParameters = drawLayerParams[layerIndex]; + const { shouldDrawLayer } = drawLayerParameters; + if (shouldDrawLayer && layer.props.pickable) { + renderStatus.pickableCount++; + } + if (layer.isComposite) { + renderStatus.compositeCount++; + } + if (layer.isDrawable && drawLayerParameters.shouldDrawLayer) { + const { layerRenderIndex, shaderModuleProps, layerParameters } = drawLayerParameters; + renderStatus.visibleCount++; + this._lastRenderIndex = Math.max(this._lastRenderIndex, layerRenderIndex); + if (shaderModuleProps.project) { + shaderModuleProps.project.viewport = viewport; + } + layer.context.renderPass = renderPass; + try { + layer._drawLayer({ + renderPass, + shaderModuleProps, + uniforms: { layerIndex: layerRenderIndex }, + parameters: layerParameters + }); + } catch (err) { + layer.raiseError(err, `drawing ${layer} to ${pass}`); + } + } + } + return renderStatus; + } + /* eslint-enable max-depth, max-statements */ + /* Methods for subclass overrides */ + shouldDrawLayer(layer) { + return true; + } + getShaderModuleProps(layer, effects, otherShaderModuleProps) { + return null; + } + getLayerParameters(layer, layerIndex, viewport) { + return layer.props.parameters; + } + /* Private */ + _shouldDrawLayer(layer, drawContext, layerFilter, layerFilterCache) { + const shouldDrawLayer = layer.props.visible && this.shouldDrawLayer(layer); + if (!shouldDrawLayer) { + return false; + } + drawContext.layer = layer; + let parent = layer.parent; + while (parent) { + if (!parent.props.visible || !parent.filterSubLayer(drawContext)) { + return false; + } + drawContext.layer = parent; + parent = parent.parent; + } + if (layerFilter) { + const rootLayerId = drawContext.layer.id; + if (!(rootLayerId in layerFilterCache)) { + layerFilterCache[rootLayerId] = layerFilter(drawContext); + } + if (!layerFilterCache[rootLayerId]) { + return false; + } + } + layer.activateViewport(drawContext.viewport); + return true; + } + _getShaderModuleProps(layer, effects, pass, overrides) { + const devicePixelRatio2 = this.device.canvasContext.cssToDeviceRatio(); + const layerProps = layer.internalState?.propsInTransition || layer.props; + const shaderModuleProps = { + layer: layerProps, + picking: { + isActive: false + }, + project: { + viewport: layer.context.viewport, + devicePixelRatio: devicePixelRatio2, + modelMatrix: layerProps.modelMatrix, + coordinateSystem: layerProps.coordinateSystem, + coordinateOrigin: layerProps.coordinateOrigin, + autoWrapLongitude: layer.wrapLongitude + } + }; + if (effects) { + for (const effect of effects) { + mergeModuleParameters(shaderModuleProps, effect.getShaderModuleProps?.(layer, shaderModuleProps)); + } + } + return mergeModuleParameters(shaderModuleProps, this.getShaderModuleProps(layer, effects, shaderModuleProps), overrides); + } + }; + function layerIndexResolver(startIndex = 0, layerIndices = {}) { + const resolvers = {}; + const resolveLayerIndex = (layer, isDrawn) => { + const indexOverride = layer.props._offset; + const layerId = layer.id; + const parentId = layer.parent && layer.parent.id; + let index2; + if (parentId && !(parentId in layerIndices)) { + resolveLayerIndex(layer.parent, false); + } + if (parentId in resolvers) { + const resolver = resolvers[parentId] = resolvers[parentId] || layerIndexResolver(layerIndices[parentId], layerIndices); + index2 = resolver(layer, isDrawn); + resolvers[layerId] = resolver; + } else if (Number.isFinite(indexOverride)) { + index2 = indexOverride + (layerIndices[parentId] || 0); + resolvers[layerId] = null; + } else { + index2 = startIndex; + } + if (isDrawn && index2 >= startIndex) { + startIndex = index2 + 1; + } + layerIndices[layerId] = index2; + return index2; + }; + return resolveLayerIndex; + } + function getGLViewport(device, { shaderModuleProps, target: target2, viewport }) { + const pixelRatio = shaderModuleProps?.project?.devicePixelRatio ?? // @ts-expect-error TODO - assuming WebGL context + device.canvasContext.cssToDeviceRatio(); + const [, drawingBufferHeight] = device.canvasContext.getDrawingBufferSize(); + const height = target2 ? target2.height : drawingBufferHeight; + const dimensions = viewport; + return [ + dimensions.x * pixelRatio, + height - (dimensions.y + dimensions.height) * pixelRatio, + dimensions.width * pixelRatio, + dimensions.height * pixelRatio + ]; + } + function mergeModuleParameters(target2, ...sources) { + for (const source3 of sources) { + if (source3) { + for (const key in source3) { + if (target2[key]) { + Object.assign(target2[key], source3[key]); + } else { + target2[key] = source3[key]; + } + } + } + } + return target2; + } + + // node_modules/@deck.gl/core/dist/passes/shadow-pass.js + var ShadowPass = class extends LayersPass { + constructor(device, props) { + super(device, props); + const shadowMap = device.createTexture({ + format: "rgba8unorm", + width: 1, + height: 1, + sampler: { + minFilter: "linear", + magFilter: "linear", + addressModeU: "clamp-to-edge", + addressModeV: "clamp-to-edge" + } + // TODO - texture API change in luma.gl v9.2 + // mipmaps: true + }); + const depthBuffer = device.createTexture({ format: "depth16unorm", width: 1, height: 1 }); + this.fbo = device.createFramebuffer({ + id: "shadowmap", + width: 1, + height: 1, + colorAttachments: [shadowMap], + // Depth attachment has to be specified for depth test to work + depthStencilAttachment: depthBuffer + }); + } + delete() { + if (this.fbo) { + this.fbo.destroy(); + this.fbo = null; + } + } + getShadowMap() { + return this.fbo.colorAttachments[0].texture; + } + render(params) { + const target2 = this.fbo; + const pixelRatio = this.device.canvasContext.cssToDeviceRatio(); + const viewport = params.viewports[0]; + const width = viewport.width * pixelRatio; + const height = viewport.height * pixelRatio; + const clearColor = [1, 1, 1, 1]; + if (width !== target2.width || height !== target2.height) { + target2.resize({ width, height }); + } + super.render({ ...params, clearColor, target: target2, pass: "shadow" }); + } + getLayerParameters(layer, layerIndex, viewport) { + return { + ...layer.props.parameters, + blend: false, + depthWriteEnabled: true, + depthCompare: "less-equal" + }; + } + shouldDrawLayer(layer) { + return layer.props.shadowEnabled !== false; + } + getShaderModuleProps(layer, effects, otherShaderModuleProps) { + return { + shadow: { + project: otherShaderModuleProps.project, + drawToShadowMap: true + } + }; + } + }; + + // node_modules/@deck.gl/core/dist/effects/lighting/lighting-effect.js + var DEFAULT_AMBIENT_LIGHT_PROPS = { + color: [255, 255, 255], + intensity: 1 + }; + var DEFAULT_DIRECTIONAL_LIGHT_PROPS = [ + { + color: [255, 255, 255], + intensity: 1, + direction: [-1, 3, -1] + }, + { + color: [255, 255, 255], + intensity: 0.9, + direction: [1, -8, -2.5] + } + ]; + var DEFAULT_SHADOW_COLOR2 = [0, 0, 0, 200 / 255]; + var LightingEffect = class { + constructor(props = {}) { + this.id = "lighting-effect"; + this.shadowColor = DEFAULT_SHADOW_COLOR2; + this.shadow = false; + this.directionalLights = []; + this.pointLights = []; + this.shadowPasses = []; + this.dummyShadowMap = null; + this.setProps(props); + } + setup(context) { + this.context = context; + const { device, deck } = context; + if (this.shadow && !this.dummyShadowMap) { + this._createShadowPasses(device); + deck._addDefaultShaderModule(shadow_default); + this.dummyShadowMap = device.createTexture({ + width: 1, + height: 1 + }); + } + } + setProps(props) { + this.ambientLight = void 0; + this.directionalLights = []; + this.pointLights = []; + for (const key in props) { + const lightSource = props[key]; + switch (lightSource.type) { + case "ambient": + this.ambientLight = lightSource; + break; + case "directional": + this.directionalLights.push(lightSource); + break; + case "point": + this.pointLights.push(lightSource); + break; + default: + } + } + this._applyDefaultLights(); + this.shadow = this.directionalLights.some((light) => light.shadow); + if (this.context) { + this.setup(this.context); + } + this.props = props; + } + preRender({ layers, layerFilter, viewports, onViewportActive, views }) { + if (!this.shadow) + return; + this.shadowMatrices = this._calculateMatrices(); + for (let i = 0; i < this.shadowPasses.length; i++) { + const shadowPass = this.shadowPasses[i]; + shadowPass.render({ + layers, + layerFilter, + viewports, + onViewportActive, + views, + shaderModuleProps: { + shadow: { + shadowLightId: i, + dummyShadowMap: this.dummyShadowMap, + shadowMatrices: this.shadowMatrices + } + } + }); + } + } + getShaderModuleProps(layer, otherShaderModuleProps) { + const shadowProps = this.shadow ? { + project: otherShaderModuleProps.project, + shadowMaps: this.shadowPasses.map((shadowPass) => shadowPass.getShadowMap()), + dummyShadowMap: this.dummyShadowMap, + shadowColor: this.shadowColor, + shadowMatrices: this.shadowMatrices + } : {}; + const lightingProps = { + enabled: true, + lights: this._getLights(layer) + }; + const materialProps = layer.props.material; + return { + shadow: shadowProps, + lighting: lightingProps, + phongMaterial: materialProps, + gouraudMaterial: materialProps + }; + } + cleanup(context) { + for (const shadowPass of this.shadowPasses) { + shadowPass.delete(); + } + this.shadowPasses.length = 0; + if (this.dummyShadowMap) { + this.dummyShadowMap.destroy(); + this.dummyShadowMap = null; + context.deck._removeDefaultShaderModule(shadow_default); + } + } + _calculateMatrices() { + const lightMatrices = []; + for (const light of this.directionalLights) { + const viewMatrix = new Matrix4().lookAt({ + eye: new Vector3(light.direction).negate() + }); + lightMatrices.push(viewMatrix); + } + return lightMatrices; + } + _createShadowPasses(device) { + for (let i = 0; i < this.directionalLights.length; i++) { + const shadowPass = new ShadowPass(device); + this.shadowPasses[i] = shadowPass; + } + } + _applyDefaultLights() { + const { ambientLight, pointLights, directionalLights } = this; + if (!ambientLight && pointLights.length === 0 && directionalLights.length === 0) { + this.ambientLight = new AmbientLight(DEFAULT_AMBIENT_LIGHT_PROPS); + this.directionalLights.push(new DirectionalLight(DEFAULT_DIRECTIONAL_LIGHT_PROPS[0]), new DirectionalLight(DEFAULT_DIRECTIONAL_LIGHT_PROPS[1])); + } + } + _getLights(layer) { + const lights = []; + if (this.ambientLight) { + lights.push(this.ambientLight); + } + for (const pointLight of this.pointLights) { + lights.push(pointLight.getProjectedLight({ layer })); + } + for (const directionalLight of this.directionalLights) { + lights.push(directionalLight.getProjectedLight({ layer })); + } + return lights; + } + }; + + // node_modules/@deck.gl/core/dist/utils/typed-array-manager.js + var TypedArrayManager = class { + constructor(options = {}) { + this._pool = []; + this.opts = { overAlloc: 2, poolSize: 100 }; + this.setOptions(options); + } + setOptions(options) { + Object.assign(this.opts, options); + } + allocate(typedArray, count2, { size = 1, type, padding = 0, copy: copy7 = false, initialize = false, maxCount }) { + const Type = type || typedArray && typedArray.constructor || Float32Array; + const newSize = count2 * size + padding; + if (ArrayBuffer.isView(typedArray)) { + if (newSize <= typedArray.length) { + return typedArray; + } + if (newSize * typedArray.BYTES_PER_ELEMENT <= typedArray.buffer.byteLength) { + return new Type(typedArray.buffer, 0, newSize); + } + } + let maxSize = Infinity; + if (maxCount) { + maxSize = maxCount * size + padding; + } + const newArray = this._allocate(Type, newSize, initialize, maxSize); + if (typedArray && copy7) { + newArray.set(typedArray); + } else if (!initialize) { + newArray.fill(0, 0, 4); + } + this._release(typedArray); + return newArray; + } + release(typedArray) { + this._release(typedArray); + } + _allocate(Type, size, initialize, maxSize) { + let sizeToAllocate = Math.max(Math.ceil(size * this.opts.overAlloc), 1); + if (sizeToAllocate > maxSize) { + sizeToAllocate = maxSize; + } + const pool = this._pool; + const byteLength = Type.BYTES_PER_ELEMENT * sizeToAllocate; + const i = pool.findIndex((b) => b.byteLength >= byteLength); + if (i >= 0) { + const array = new Type(pool.splice(i, 1)[0], 0, sizeToAllocate); + if (initialize) { + array.fill(0); + } + return array; + } + return new Type(sizeToAllocate); + } + _release(typedArray) { + if (!ArrayBuffer.isView(typedArray)) { + return; + } + const pool = this._pool; + const { buffer } = typedArray; + const { byteLength } = buffer; + const i = pool.findIndex((b) => b.byteLength >= byteLength); + if (i < 0) { + pool.push(buffer); + } else if (i > 0 || pool.length < this.opts.poolSize) { + pool.splice(i, 0, buffer); + } + if (pool.length > this.opts.poolSize) { + pool.shift(); + } + } + }; + var typed_array_manager_default = new TypedArrayManager(); + + // node_modules/@deck.gl/core/dist/utils/math-utils.js + function createMat42() { + return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]; + } + function mod2(value, divisor) { + const modulus = value % divisor; + return modulus < 0 ? divisor + modulus : modulus; + } + function getCameraPosition(viewMatrixInverse) { + return [viewMatrixInverse[12], viewMatrixInverse[13], viewMatrixInverse[14]]; + } + function getFrustumPlanes(viewProjectionMatrix) { + return { + left: getFrustumPlane(viewProjectionMatrix[3] + viewProjectionMatrix[0], viewProjectionMatrix[7] + viewProjectionMatrix[4], viewProjectionMatrix[11] + viewProjectionMatrix[8], viewProjectionMatrix[15] + viewProjectionMatrix[12]), + right: getFrustumPlane(viewProjectionMatrix[3] - viewProjectionMatrix[0], viewProjectionMatrix[7] - viewProjectionMatrix[4], viewProjectionMatrix[11] - viewProjectionMatrix[8], viewProjectionMatrix[15] - viewProjectionMatrix[12]), + bottom: getFrustumPlane(viewProjectionMatrix[3] + viewProjectionMatrix[1], viewProjectionMatrix[7] + viewProjectionMatrix[5], viewProjectionMatrix[11] + viewProjectionMatrix[9], viewProjectionMatrix[15] + viewProjectionMatrix[13]), + top: getFrustumPlane(viewProjectionMatrix[3] - viewProjectionMatrix[1], viewProjectionMatrix[7] - viewProjectionMatrix[5], viewProjectionMatrix[11] - viewProjectionMatrix[9], viewProjectionMatrix[15] - viewProjectionMatrix[13]), + near: getFrustumPlane(viewProjectionMatrix[3] + viewProjectionMatrix[2], viewProjectionMatrix[7] + viewProjectionMatrix[6], viewProjectionMatrix[11] + viewProjectionMatrix[10], viewProjectionMatrix[15] + viewProjectionMatrix[14]), + far: getFrustumPlane(viewProjectionMatrix[3] - viewProjectionMatrix[2], viewProjectionMatrix[7] - viewProjectionMatrix[6], viewProjectionMatrix[11] - viewProjectionMatrix[10], viewProjectionMatrix[15] - viewProjectionMatrix[14]) + }; + } + var scratchVector = new Vector3(); + function getFrustumPlane(a, b, c2, d) { + scratchVector.set(a, b, c2); + const L = scratchVector.len(); + return { distance: d / L, normal: new Vector3(-a / L, -b / L, -c2 / L) }; + } + function fp64LowPart2(x) { + return x - Math.fround(x); + } + var scratchArray; + function toDoublePrecisionArray(typedArray, options) { + const { size = 1, startIndex = 0 } = options; + const endIndex = options.endIndex !== void 0 ? options.endIndex : typedArray.length; + const count2 = (endIndex - startIndex) / size; + scratchArray = typed_array_manager_default.allocate(scratchArray, count2, { + type: Float32Array, + size: size * 2 + }); + let sourceIndex = startIndex; + let targetIndex = 0; + while (sourceIndex < endIndex) { + for (let j = 0; j < size; j++) { + const value = typedArray[sourceIndex++]; + scratchArray[targetIndex + j] = value; + scratchArray[targetIndex + j + size] = fp64LowPart2(value); + } + targetIndex += size * 2; + } + return scratchArray.subarray(0, count2 * size * 2); + } + function mergeBounds(boundsList) { + let mergedBounds = null; + let isMerged = false; + for (const bounds of boundsList) { + if (!bounds) + continue; + if (!mergedBounds) { + mergedBounds = bounds; + } else { + if (!isMerged) { + mergedBounds = [ + [mergedBounds[0][0], mergedBounds[0][1]], + [mergedBounds[1][0], mergedBounds[1][1]] + ]; + isMerged = true; + } + mergedBounds[0][0] = Math.min(mergedBounds[0][0], bounds[0][0]); + mergedBounds[0][1] = Math.min(mergedBounds[0][1], bounds[0][1]); + mergedBounds[1][0] = Math.max(mergedBounds[1][0], bounds[1][0]); + mergedBounds[1][1] = Math.max(mergedBounds[1][1], bounds[1][1]); + } + } + return mergedBounds; + } + + // node_modules/@deck.gl/core/dist/viewports/viewport.js + var DEGREES_TO_RADIANS4 = Math.PI / 180; + var IDENTITY2 = createMat42(); + var ZERO_VECTOR2 = [0, 0, 0]; + var DEFAULT_DISTANCE_SCALES = { + unitsPerMeter: [1, 1, 1], + metersPerUnit: [1, 1, 1] + }; + function createProjectionMatrix({ width, height, orthographic, fovyRadians, focalDistance, padding, near, far }) { + const aspect = width / height; + const matrix = orthographic ? new Matrix4().orthographic({ fovy: fovyRadians, aspect, focalDistance, near, far }) : new Matrix4().perspective({ fovy: fovyRadians, aspect, near, far }); + if (padding) { + const { left = 0, right = 0, top = 0, bottom = 0 } = padding; + const offsetX = clamp((left + width - right) / 2, 0, width) - width / 2; + const offsetY = clamp((top + height - bottom) / 2, 0, height) - height / 2; + matrix[8] -= offsetX * 2 / width; + matrix[9] += offsetY * 2 / height; + } + return matrix; + } + var Viewport = class _Viewport { + // eslint-disable-next-line complexity + constructor(opts = {}) { + this._frustumPlanes = {}; + this.id = opts.id || this.constructor.displayName || "viewport"; + this.x = opts.x || 0; + this.y = opts.y || 0; + this.width = opts.width || 1; + this.height = opts.height || 1; + this.zoom = opts.zoom || 0; + this.padding = opts.padding; + this.distanceScales = opts.distanceScales || DEFAULT_DISTANCE_SCALES; + this.focalDistance = opts.focalDistance || 1; + this.position = opts.position || ZERO_VECTOR2; + this.modelMatrix = opts.modelMatrix || null; + const { longitude, latitude } = opts; + this.isGeospatial = Number.isFinite(latitude) && Number.isFinite(longitude); + this._initProps(opts); + this._initMatrices(opts); + this.equals = this.equals.bind(this); + this.project = this.project.bind(this); + this.unproject = this.unproject.bind(this); + this.projectPosition = this.projectPosition.bind(this); + this.unprojectPosition = this.unprojectPosition.bind(this); + this.projectFlat = this.projectFlat.bind(this); + this.unprojectFlat = this.unprojectFlat.bind(this); + } + get subViewports() { + return null; + } + get metersPerPixel() { + return this.distanceScales.metersPerUnit[2] / this.scale; + } + get projectionMode() { + if (this.isGeospatial) { + return this.zoom < 12 ? PROJECTION_MODE.WEB_MERCATOR : PROJECTION_MODE.WEB_MERCATOR_AUTO_OFFSET; + } + return PROJECTION_MODE.IDENTITY; + } + // Two viewports are equal if width and height are identical, and if + // their view and projection matrices are (approximately) equal. + equals(viewport) { + if (!(viewport instanceof _Viewport)) { + return false; + } + if (this === viewport) { + return true; + } + return viewport.width === this.width && viewport.height === this.height && viewport.scale === this.scale && equals(viewport.projectionMatrix, this.projectionMatrix) && equals(viewport.viewMatrix, this.viewMatrix); + } + /** + * Projects xyz (possibly latitude and longitude) to pixel coordinates in window + * using viewport projection parameters + * - [longitude, latitude] to [x, y] + * - [longitude, latitude, Z] => [x, y, z] + * Note: By default, returns top-left coordinates for canvas/SVG type render + * + * @param {Array} lngLatZ - [lng, lat] or [lng, lat, Z] + * @param {Object} opts - options + * @param {Object} opts.topLeft=true - Whether projected coords are top left + * @return {Array} - [x, y] or [x, y, z] in top left coords + */ + project(xyz, { topLeft = true } = {}) { + const worldPosition = this.projectPosition(xyz); + const coord = worldToPixels(worldPosition, this.pixelProjectionMatrix); + const [x, y] = coord; + const y2 = topLeft ? y : this.height - y; + return xyz.length === 2 ? [x, y2] : [x, y2, coord[2]]; + } + /** + * Unproject pixel coordinates on screen onto world coordinates, + * (possibly [lon, lat]) on map. + * - [x, y] => [lng, lat] + * - [x, y, z] => [lng, lat, Z] + * @param {Array} xyz - + * @param {Object} opts - options + * @param {Object} opts.topLeft=true - Whether origin is top left + * @return {Array|null} - [lng, lat, Z] or [X, Y, Z] + */ + unproject(xyz, { topLeft = true, targetZ } = {}) { + const [x, y, z] = xyz; + const y2 = topLeft ? y : this.height - y; + const targetZWorld = targetZ && targetZ * this.distanceScales.unitsPerMeter[2]; + const coord = pixelsToWorld([x, y2, z], this.pixelUnprojectionMatrix, targetZWorld); + const [X, Y, Z] = this.unprojectPosition(coord); + if (Number.isFinite(z)) { + return [X, Y, Z]; + } + return Number.isFinite(targetZ) ? [X, Y, targetZ] : [X, Y]; + } + // NON_LINEAR PROJECTION HOOKS + // Used for web meractor projection + projectPosition(xyz) { + const [X, Y] = this.projectFlat(xyz); + const Z = (xyz[2] || 0) * this.distanceScales.unitsPerMeter[2]; + return [X, Y, Z]; + } + unprojectPosition(xyz) { + const [X, Y] = this.unprojectFlat(xyz); + const Z = (xyz[2] || 0) * this.distanceScales.metersPerUnit[2]; + return [X, Y, Z]; + } + /** + * Project [lng,lat] on sphere onto [x,y] on 512*512 Mercator Zoom 0 tile. + * Performs the nonlinear part of the web mercator projection. + * Remaining projection is done with 4x4 matrices which also handles + * perspective. + * @param {Array} lngLat - [lng, lat] coordinates + * Specifies a point on the sphere to project onto the map. + * @return {Array} [x,y] coordinates. + */ + projectFlat(xyz) { + if (this.isGeospatial) { + const result = lngLatToWorld(xyz); + result[1] = clamp(result[1], -318, 830); + return result; + } + return xyz; + } + /** + * Unproject world point [x,y] on map onto {lat, lon} on sphere + * @param {object|Vector} xy - object with {x,y} members + * representing point on projected map plane + * @return {GeoCoordinates} - object with {lat,lon} of point on sphere. + * Has toArray method if you need a GeoJSON Array. + * Per cartographic tradition, lat and lon are specified as degrees. + */ + unprojectFlat(xyz) { + if (this.isGeospatial) { + return worldToLngLat(xyz); + } + return xyz; + } + /** + * Get bounds of the current viewport + * @return {Array} - [minX, minY, maxX, maxY] + */ + getBounds(options = {}) { + const unprojectOption = { targetZ: options.z || 0 }; + const topLeft = this.unproject([0, 0], unprojectOption); + const topRight = this.unproject([this.width, 0], unprojectOption); + const bottomLeft = this.unproject([0, this.height], unprojectOption); + const bottomRight = this.unproject([this.width, this.height], unprojectOption); + return [ + Math.min(topLeft[0], topRight[0], bottomLeft[0], bottomRight[0]), + Math.min(topLeft[1], topRight[1], bottomLeft[1], bottomRight[1]), + Math.max(topLeft[0], topRight[0], bottomLeft[0], bottomRight[0]), + Math.max(topLeft[1], topRight[1], bottomLeft[1], bottomRight[1]) + ]; + } + getDistanceScales(coordinateOrigin) { + if (coordinateOrigin && this.isGeospatial) { + return getDistanceScales({ + longitude: coordinateOrigin[0], + latitude: coordinateOrigin[1], + highPrecision: true + }); + } + return this.distanceScales; + } + containsPixel({ x, y, width = 1, height = 1 }) { + return x < this.x + this.width && this.x < x + width && y < this.y + this.height && this.y < y + height; + } + // Extract frustum planes in common space + getFrustumPlanes() { + if (this._frustumPlanes.near) { + return this._frustumPlanes; + } + Object.assign(this._frustumPlanes, getFrustumPlanes(this.viewProjectionMatrix)); + return this._frustumPlanes; + } + // EXPERIMENTAL METHODS + /** + * Needed by panning and linear transition + * Pan the viewport to place a given world coordinate at screen point [x, y] + * + * @param {Array} coords - world coordinates + * @param {Array} pixel - [x,y] coordinates on screen + * @param {Array} startPixel - [x,y] screen position where pan started (optional, for delta-based panning) + * @return {Object} props of the new viewport + */ + panByPosition(coords, pixel, startPixel) { + return null; + } + // INTERNAL METHODS + /* eslint-disable complexity, max-statements */ + _initProps(opts) { + const longitude = opts.longitude; + const latitude = opts.latitude; + if (this.isGeospatial) { + if (!Number.isFinite(opts.zoom)) { + this.zoom = getMeterZoom({ latitude }) + Math.log2(this.focalDistance); + } + this.distanceScales = opts.distanceScales || getDistanceScales({ latitude, longitude }); + } + const scale5 = Math.pow(2, this.zoom); + this.scale = scale5; + const { position, modelMatrix } = opts; + let meterOffset = ZERO_VECTOR2; + if (position) { + meterOffset = modelMatrix ? new Matrix4(modelMatrix).transformAsVector(position, []) : position; + } + if (this.isGeospatial) { + const center = this.projectPosition([longitude, latitude, 0]); + this.center = new Vector3(meterOffset).scale(this.distanceScales.unitsPerMeter).add(center); + } else { + this.center = this.projectPosition(meterOffset); + } + } + /* eslint-enable complexity, max-statements */ + _initMatrices(opts) { + const { + // View matrix + viewMatrix = IDENTITY2, + // Projection matrix + projectionMatrix = null, + // Projection matrix parameters, used if projectionMatrix not supplied + orthographic = false, + fovyRadians, + fovy = 75, + near = 0.1, + // Distance of near clipping plane + far = 1e3, + // Distance of far clipping plane + padding = null, + // Center offset in pixels + focalDistance = 1 + } = opts; + this.viewMatrixUncentered = viewMatrix; + this.viewMatrix = new Matrix4().multiplyRight(viewMatrix).translate(new Vector3(this.center).negate()); + this.projectionMatrix = projectionMatrix || createProjectionMatrix({ + width: this.width, + height: this.height, + orthographic, + fovyRadians: fovyRadians || fovy * DEGREES_TO_RADIANS4, + focalDistance, + padding, + near, + far + }); + const vpm = createMat42(); + mat4_exports.multiply(vpm, vpm, this.projectionMatrix); + mat4_exports.multiply(vpm, vpm, this.viewMatrix); + this.viewProjectionMatrix = vpm; + this.viewMatrixInverse = mat4_exports.invert([], this.viewMatrix) || this.viewMatrix; + this.cameraPosition = getCameraPosition(this.viewMatrixInverse); + const viewportMatrix = createMat42(); + const pixelProjectionMatrix = createMat42(); + mat4_exports.scale(viewportMatrix, viewportMatrix, [this.width / 2, -this.height / 2, 1]); + mat4_exports.translate(viewportMatrix, viewportMatrix, [1, -1, 0]); + mat4_exports.multiply(pixelProjectionMatrix, viewportMatrix, this.viewProjectionMatrix); + this.pixelProjectionMatrix = pixelProjectionMatrix; + this.pixelUnprojectionMatrix = mat4_exports.invert(createMat42(), this.pixelProjectionMatrix); + if (!this.pixelUnprojectionMatrix) { + log_default.warn("Pixel project matrix not invertible")(); + } + } + }; + Viewport.displayName = "Viewport"; + var viewport_default = Viewport; + + // node_modules/@deck.gl/core/dist/viewports/web-mercator-viewport.js + var WebMercatorViewport2 = class _WebMercatorViewport extends viewport_default { + /* eslint-disable complexity, max-statements */ + constructor(opts = {}) { + const { + latitude = 0, + longitude = 0, + zoom = 0, + pitch = 0, + bearing = 0, + nearZMultiplier = 0.1, + farZMultiplier = 1.01, + nearZ, + farZ, + orthographic = false, + projectionMatrix, + repeat = false, + worldOffset = 0, + position, + padding, + // backward compatibility + // TODO: remove in v9 + legacyMeterSizes = false + } = opts; + let { width, height, altitude = 1.5 } = opts; + const scale5 = Math.pow(2, zoom); + width = width || 1; + height = height || 1; + let fovy; + let projectionParameters = null; + if (projectionMatrix) { + altitude = projectionMatrix[5] / 2; + fovy = altitudeToFovy(altitude); + } else { + if (opts.fovy) { + fovy = opts.fovy; + altitude = fovyToAltitude(fovy); + } else { + fovy = altitudeToFovy(altitude); + } + let offset; + if (padding) { + const { top = 0, bottom = 0 } = padding; + offset = [0, clamp((top + height - bottom) / 2, 0, height) - height / 2]; + } + projectionParameters = getProjectionParameters({ + width, + height, + scale: scale5, + center: position && [0, 0, position[2] * unitsPerMeter(latitude)], + offset, + pitch, + fovy, + nearZMultiplier, + farZMultiplier + }); + if (Number.isFinite(nearZ)) { + projectionParameters.near = nearZ; + } + if (Number.isFinite(farZ)) { + projectionParameters.far = farZ; + } + } + let viewMatrixUncentered = getViewMatrix({ + height, + pitch, + bearing, + scale: scale5, + altitude + }); + if (worldOffset) { + const viewOffset = new Matrix4().translate([512 * worldOffset, 0, 0]); + viewMatrixUncentered = viewOffset.multiplyLeft(viewMatrixUncentered); + } + super({ + ...opts, + // x, y, + width, + height, + // view matrix + viewMatrix: viewMatrixUncentered, + longitude, + latitude, + zoom, + // projection matrix parameters + ...projectionParameters, + fovy, + focalDistance: altitude + }); + this.latitude = latitude; + this.longitude = longitude; + this.zoom = zoom; + this.pitch = pitch; + this.bearing = bearing; + this.altitude = altitude; + this.fovy = fovy; + this.orthographic = orthographic; + this._subViewports = repeat ? [] : null; + this._pseudoMeters = legacyMeterSizes; + Object.freeze(this); + } + /* eslint-enable complexity, max-statements */ + get subViewports() { + if (this._subViewports && !this._subViewports.length) { + const bounds = this.getBounds(); + const minOffset = Math.floor((bounds[0] + 180) / 360); + const maxOffset = Math.ceil((bounds[2] - 180) / 360); + for (let x = minOffset; x <= maxOffset; x++) { + const offsetViewport = x ? new _WebMercatorViewport({ + ...this, + worldOffset: x + }) : this; + this._subViewports.push(offsetViewport); + } + } + return this._subViewports; + } + projectPosition(xyz) { + if (this._pseudoMeters) { + return super.projectPosition(xyz); + } + const [X, Y] = this.projectFlat(xyz); + const Z = (xyz[2] || 0) * unitsPerMeter(xyz[1]); + return [X, Y, Z]; + } + unprojectPosition(xyz) { + if (this._pseudoMeters) { + return super.unprojectPosition(xyz); + } + const [X, Y] = this.unprojectFlat(xyz); + const Z = (xyz[2] || 0) / unitsPerMeter(Y); + return [X, Y, Z]; + } + /** + * Add a meter delta to a base lnglat coordinate, returning a new lnglat array + * + * Note: Uses simple linear approximation around the viewport center + * Error increases with size of offset (roughly 1% per 100km) + * + * @param {[Number,Number]|[Number,Number,Number]) lngLatZ - base coordinate + * @param {[Number,Number]|[Number,Number,Number]) xyz - array of meter deltas + * @return {[Number,Number]|[Number,Number,Number]) array of [lng,lat,z] deltas + */ + addMetersToLngLat(lngLatZ, xyz) { + return addMetersToLngLat(lngLatZ, xyz); + } + panByPosition(coords, pixel, startPixel) { + const fromLocation = pixelsToWorld(pixel, this.pixelUnprojectionMatrix); + const toLocation = this.projectFlat(coords); + const translate2 = vec2_exports.add([], toLocation, vec2_exports.negate([], fromLocation)); + const newCenter = vec2_exports.add([], this.center, translate2); + const [longitude, latitude] = this.unprojectFlat(newCenter); + return { longitude, latitude }; + } + /** + * Returns a new longitude and latitude that keeps a 3D world coordinate at a given screen pixel + * This version handles the z-component (altitude) properly for cameras positioned above ground + */ + panByPosition3D(coords, pixel) { + const targetZ = coords[2] || 0; + const deltaLngLat = vec2_exports.sub([], coords, this.unproject(pixel, { targetZ })); + return { longitude: this.longitude + deltaLngLat[0], latitude: this.latitude + deltaLngLat[1] }; + } + getBounds(options = {}) { + const corners = getBounds(this, options.z || 0); + return [ + Math.min(corners[0][0], corners[1][0], corners[2][0], corners[3][0]), + Math.min(corners[0][1], corners[1][1], corners[2][1], corners[3][1]), + Math.max(corners[0][0], corners[1][0], corners[2][0], corners[3][0]), + Math.max(corners[0][1], corners[1][1], corners[2][1], corners[3][1]) + ]; + } + /** + * Returns a new viewport that fit around the given rectangle. + * Only supports non-perspective mode. + */ + fitBounds(bounds, options = {}) { + const { width, height } = this; + const { longitude, latitude, zoom } = fitBounds({ width, height, bounds, ...options }); + return new _WebMercatorViewport({ width, height, longitude, latitude, zoom }); + } + }; + WebMercatorViewport2.displayName = "WebMercatorViewport"; + var web_mercator_viewport_default = WebMercatorViewport2; + + // node_modules/@deck.gl/core/dist/shaderlib/project/project-functions.js + var DEFAULT_COORDINATE_ORIGIN2 = [0, 0, 0]; + function lngLatZToWorldPosition(lngLatZ, viewport, offsetMode = false) { + const p = viewport.projectPosition(lngLatZ); + if (offsetMode && viewport instanceof web_mercator_viewport_default) { + const [longitude, latitude, z = 0] = lngLatZ; + const distanceScales = viewport.getDistanceScales([longitude, latitude]); + p[2] = z * distanceScales.unitsPerMeter[2]; + } + return p; + } + function normalizeParameters(opts) { + const { viewport, modelMatrix, coordinateOrigin } = opts; + let { coordinateSystem, fromCoordinateSystem, fromCoordinateOrigin } = opts; + if (coordinateSystem === "default") { + coordinateSystem = viewport.isGeospatial ? "lnglat" : "cartesian"; + } + if (fromCoordinateSystem === void 0) { + fromCoordinateSystem = coordinateSystem; + } else if (fromCoordinateSystem === "default") { + fromCoordinateSystem = viewport.isGeospatial ? "lnglat" : "cartesian"; + } + if (fromCoordinateOrigin === void 0) { + fromCoordinateOrigin = coordinateOrigin; + } + return { + viewport, + coordinateSystem, + coordinateOrigin, + modelMatrix, + fromCoordinateSystem, + fromCoordinateOrigin + }; + } + function getWorldPosition(position, { viewport, modelMatrix, coordinateSystem, coordinateOrigin, offsetMode }) { + let [x, y, z = 0] = position; + if (modelMatrix) { + [x, y, z] = vec4_exports.transformMat4([], [x, y, z, 1], modelMatrix); + } + switch (coordinateSystem) { + case "default": + return getWorldPosition(position, { + viewport, + modelMatrix, + coordinateSystem: viewport.isGeospatial ? "lnglat" : "cartesian", + coordinateOrigin, + offsetMode + }); + case "lnglat": + return lngLatZToWorldPosition([x, y, z], viewport, offsetMode); + case "lnglat-offsets": + return lngLatZToWorldPosition([x + coordinateOrigin[0], y + coordinateOrigin[1], z + (coordinateOrigin[2] || 0)], viewport, offsetMode); + case "meter-offsets": + return lngLatZToWorldPosition(addMetersToLngLat(coordinateOrigin, [x, y, z]), viewport, offsetMode); + case "cartesian": + return viewport.isGeospatial ? [x + coordinateOrigin[0], y + coordinateOrigin[1], z + coordinateOrigin[2]] : viewport.projectPosition([x, y, z]); + default: + throw new Error(`Invalid coordinateSystem: ${coordinateSystem}`); + } + } + function projectPosition(position, params) { + const { viewport, coordinateSystem, coordinateOrigin, modelMatrix, fromCoordinateSystem, fromCoordinateOrigin } = normalizeParameters(params); + const { autoOffset = true } = params; + const { geospatialOrigin = DEFAULT_COORDINATE_ORIGIN2, shaderCoordinateOrigin = DEFAULT_COORDINATE_ORIGIN2, offsetMode = false } = autoOffset ? getOffsetOrigin(viewport, coordinateSystem, coordinateOrigin) : {}; + const worldPosition = getWorldPosition(position, { + viewport, + modelMatrix, + coordinateSystem: fromCoordinateSystem, + coordinateOrigin: fromCoordinateOrigin, + offsetMode + }); + if (offsetMode) { + const positionCommonSpace = viewport.projectPosition(geospatialOrigin || shaderCoordinateOrigin); + vec3_exports.sub(worldPosition, worldPosition, positionCommonSpace); + } + return worldPosition; + } + + // node_modules/@luma.gl/engine/dist/animation/timeline.js + var channelHandles = 1; + var animationHandles = 1; + var Timeline = class { + time = 0; + channels = /* @__PURE__ */ new Map(); + animations = /* @__PURE__ */ new Map(); + playing = false; + lastEngineTime = -1; + constructor() { + } + addChannel(props) { + const { delay = 0, duration = Number.POSITIVE_INFINITY, rate = 1, repeat = 1 } = props; + const channelId = channelHandles++; + const channel = { + time: 0, + delay, + duration, + rate, + repeat + }; + this._setChannelTime(channel, this.time); + this.channels.set(channelId, channel); + return channelId; + } + removeChannel(channelId) { + this.channels.delete(channelId); + for (const [animationHandle, animation] of this.animations) { + if (animation.channel === channelId) { + this.detachAnimation(animationHandle); + } + } + } + isFinished(channelId) { + const channel = this.channels.get(channelId); + if (channel === void 0) { + return false; + } + return this.time >= channel.delay + channel.duration * channel.repeat; + } + getTime(channelId) { + if (channelId === void 0) { + return this.time; + } + const channel = this.channels.get(channelId); + if (channel === void 0) { + return -1; + } + return channel.time; + } + setTime(time) { + this.time = Math.max(0, time); + const channels = this.channels.values(); + for (const channel of channels) { + this._setChannelTime(channel, this.time); + } + const animations = this.animations.values(); + for (const animationData of animations) { + const { animation, channel } = animationData; + animation.setTime(this.getTime(channel)); + } + } + play() { + this.playing = true; + } + pause() { + this.playing = false; + this.lastEngineTime = -1; + } + reset() { + this.setTime(0); + } + attachAnimation(animation, channelHandle) { + const animationHandle = animationHandles++; + this.animations.set(animationHandle, { + animation, + channel: channelHandle + }); + animation.setTime(this.getTime(channelHandle)); + return animationHandle; + } + detachAnimation(channelId) { + this.animations.delete(channelId); + } + update(engineTime) { + if (this.playing) { + if (this.lastEngineTime === -1) { + this.lastEngineTime = engineTime; + } + this.setTime(this.time + (engineTime - this.lastEngineTime)); + this.lastEngineTime = engineTime; + } + } + _setChannelTime(channel, time) { + const offsetTime = time - channel.delay; + const totalDuration = channel.duration * channel.repeat; + if (offsetTime >= totalDuration) { + channel.time = channel.duration * channel.rate; + } else { + channel.time = Math.max(0, offsetTime) % channel.duration; + channel.time *= channel.rate; + } + } + }; + + // node_modules/@luma.gl/engine/dist/animation-loop/animation-loop.js + init_dist4(); + + // node_modules/@luma.gl/engine/dist/animation-loop/request-animation-frame.js + function requestAnimationFramePolyfill(callback) { + const browserRequestAnimationFrame = typeof window !== "undefined" ? window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame : null; + if (browserRequestAnimationFrame) { + return browserRequestAnimationFrame.call(window, callback); + } + return setTimeout(() => callback(typeof performance !== "undefined" ? performance.now() : Date.now()), 1e3 / 60); + } + function cancelAnimationFramePolyfill(timerId) { + const browserCancelAnimationFrame = typeof window !== "undefined" ? window.cancelAnimationFrame || window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame : null; + if (browserCancelAnimationFrame) { + browserCancelAnimationFrame.call(window, timerId); + return; + } + clearTimeout(timerId); + } + + // node_modules/@luma.gl/engine/dist/animation-loop/animation-loop.js + init_dist3(); + var statIdCounter = 0; + var ANIMATION_LOOP_STATS = "Animation Loop"; + var AnimationLoop = class _AnimationLoop { + static defaultAnimationLoopProps = { + device: null, + onAddHTML: () => "", + onInitialize: async () => null, + onRender: () => { + }, + onFinalize: () => { + }, + onError: (error) => console.error(error), + // eslint-disable-line no-console + stats: void 0, + // view parameters + autoResizeViewport: false + }; + device = null; + canvas = null; + props; + animationProps = null; + timeline = null; + stats; + sharedStats; + cpuTime; + gpuTime; + frameRate; + display; + _needsRedraw = "initialized"; + _initialized = false; + _running = false; + _animationFrameId = null; + _nextFramePromise = null; + _resolveNextFrame = null; + _cpuStartTime = 0; + _error = null; + _lastFrameTime = 0; + /* + * @param {HTMLCanvasElement} canvas - if provided, width and height will be passed to context + */ + constructor(props) { + this.props = { ..._AnimationLoop.defaultAnimationLoopProps, ...props }; + props = this.props; + if (!props.device) { + throw new Error("No device provided"); + } + this.stats = props.stats || new Stats({ id: `animation-loop-${statIdCounter++}` }); + this.sharedStats = luma.stats.get(ANIMATION_LOOP_STATS); + this.frameRate = this.stats.get("Frame Rate"); + this.frameRate.setSampleSize(1); + this.cpuTime = this.stats.get("CPU Time"); + this.gpuTime = this.stats.get("GPU Time"); + this.setProps({ autoResizeViewport: props.autoResizeViewport }); + this.start = this.start.bind(this); + this.stop = this.stop.bind(this); + this._onMousemove = this._onMousemove.bind(this); + this._onMouseleave = this._onMouseleave.bind(this); + } + destroy() { + this.stop(); + this._setDisplay(null); + this.device?._disableDebugGPUTime(); + } + /** @deprecated Use .destroy() */ + delete() { + this.destroy(); + } + reportError(error) { + this.props.onError(error); + this._error = error; + } + /** Flags this animation loop as needing redraw */ + setNeedsRedraw(reason) { + this._needsRedraw = this._needsRedraw || reason; + return this; + } + /** Query redraw status. Clears the flag. */ + needsRedraw() { + const reason = this._needsRedraw; + this._needsRedraw = false; + return reason; + } + setProps(props) { + if ("autoResizeViewport" in props) { + this.props.autoResizeViewport = props.autoResizeViewport || false; + } + return this; + } + /** Starts a render loop if not already running */ + async start() { + if (this._running) { + return this; + } + this._running = true; + try { + let appContext; + if (!this._initialized) { + this._initialized = true; + await this._initDevice(); + this._initialize(); + if (!this._running) { + return null; + } + await this.props.onInitialize(this._getAnimationProps()); + } + if (!this._running) { + return null; + } + if (appContext !== false) { + this._cancelAnimationFrame(); + this._requestAnimationFrame(); + } + return this; + } catch (err) { + const error = err instanceof Error ? err : new Error("Unknown error"); + this.props.onError(error); + throw error; + } + } + /** Stops a render loop if already running, finalizing */ + stop() { + if (this._running) { + if (this.animationProps && !this._error) { + this.props.onFinalize(this.animationProps); + } + this._cancelAnimationFrame(); + this._nextFramePromise = null; + this._resolveNextFrame = null; + this._running = false; + this._lastFrameTime = 0; + } + return this; + } + /** Explicitly draw a frame */ + redraw(time) { + if (this.device?.isLost || this._error) { + return this; + } + this._beginFrameTimers(time); + this._setupFrame(); + this._updateAnimationProps(); + this._renderFrame(this._getAnimationProps()); + this._clearNeedsRedraw(); + if (this._resolveNextFrame) { + this._resolveNextFrame(this); + this._nextFramePromise = null; + this._resolveNextFrame = null; + } + this._endFrameTimers(); + return this; + } + /** Add a timeline, it will be automatically updated by the animation loop. */ + attachTimeline(timeline) { + this.timeline = timeline; + return this.timeline; + } + /** Remove a timeline */ + detachTimeline() { + this.timeline = null; + } + /** Wait until a render completes */ + waitForRender() { + this.setNeedsRedraw("waitForRender"); + if (!this._nextFramePromise) { + this._nextFramePromise = new Promise((resolve2) => { + this._resolveNextFrame = resolve2; + }); + } + return this._nextFramePromise; + } + /** TODO - should use device.deviceContext */ + async toDataURL() { + this.setNeedsRedraw("toDataURL"); + await this.waitForRender(); + if (this.canvas instanceof HTMLCanvasElement) { + return this.canvas.toDataURL(); + } + throw new Error("OffscreenCanvas"); + } + // PRIVATE METHODS + _initialize() { + this._startEventHandling(); + this._initializeAnimationProps(); + this._updateAnimationProps(); + this._resizeViewport(); + this.device?._enableDebugGPUTime(); + } + _setDisplay(display) { + if (this.display) { + this.display.destroy(); + this.display.animationLoop = null; + } + if (display) { + display.animationLoop = this; + } + this.display = display; + } + _requestAnimationFrame() { + if (!this._running) { + return; + } + this._animationFrameId = requestAnimationFramePolyfill(this._animationFrame.bind(this)); + } + _cancelAnimationFrame() { + if (this._animationFrameId === null) { + return; + } + cancelAnimationFramePolyfill(this._animationFrameId); + this._animationFrameId = null; + } + _animationFrame(time) { + if (!this._running) { + return; + } + this.redraw(time); + this._requestAnimationFrame(); + } + // Called on each frame, can be overridden to call onRender multiple times + // to support e.g. stereoscopic rendering + _renderFrame(animationProps) { + if (this.display) { + this.display._renderFrame(animationProps); + return; + } + this.props.onRender(this._getAnimationProps()); + this.device?.submit(); + } + _clearNeedsRedraw() { + this._needsRedraw = false; + } + _setupFrame() { + this._resizeViewport(); + } + // Initialize the object that will be passed to app callbacks + _initializeAnimationProps() { + const canvasContext = this.device?.getDefaultCanvasContext(); + if (!this.device || !canvasContext) { + throw new Error("loop"); + } + const canvas = canvasContext?.canvas; + const useDevicePixels = canvasContext.props.useDevicePixels; + this.animationProps = { + animationLoop: this, + device: this.device, + canvasContext, + canvas, + // @ts-expect-error Deprecated + useDevicePixels, + timeline: this.timeline, + needsRedraw: false, + // Placeholders + width: 1, + height: 1, + aspect: 1, + // Animation props + time: 0, + startTime: Date.now(), + engineTime: 0, + tick: 0, + tock: 0, + // Experimental + _mousePosition: null + // Event props + }; + } + _getAnimationProps() { + if (!this.animationProps) { + throw new Error("animationProps"); + } + return this.animationProps; + } + // Update the context object that will be passed to app callbacks + _updateAnimationProps() { + if (!this.animationProps) { + return; + } + const { width, height, aspect } = this._getSizeAndAspect(); + if (width !== this.animationProps.width || height !== this.animationProps.height) { + this.setNeedsRedraw("drawing buffer resized"); + } + if (aspect !== this.animationProps.aspect) { + this.setNeedsRedraw("drawing buffer aspect changed"); + } + this.animationProps.width = width; + this.animationProps.height = height; + this.animationProps.aspect = aspect; + this.animationProps.needsRedraw = this._needsRedraw; + this.animationProps.engineTime = Date.now() - this.animationProps.startTime; + if (this.timeline) { + this.timeline.update(this.animationProps.engineTime); + } + this.animationProps.tick = Math.floor(this.animationProps.time / 1e3 * 60); + this.animationProps.tock++; + this.animationProps.time = this.timeline ? this.timeline.getTime() : this.animationProps.engineTime; + } + /** Wait for supplied device */ + async _initDevice() { + this.device = await this.props.device; + if (!this.device) { + throw new Error("No device provided"); + } + this.canvas = this.device.getDefaultCanvasContext().canvas || null; + } + _createInfoDiv() { + if (this.canvas && this.props.onAddHTML) { + const wrapperDiv = document.createElement("div"); + document.body.appendChild(wrapperDiv); + wrapperDiv.style.position = "relative"; + const div4 = document.createElement("div"); + div4.style.position = "absolute"; + div4.style.left = "10px"; + div4.style.bottom = "10px"; + div4.style.width = "300px"; + div4.style.background = "white"; + if (this.canvas instanceof HTMLCanvasElement) { + wrapperDiv.appendChild(this.canvas); + } + wrapperDiv.appendChild(div4); + const html = this.props.onAddHTML(div4); + if (html) { + div4.innerHTML = html; + } + } + } + _getSizeAndAspect() { + if (!this.device) { + return { width: 1, height: 1, aspect: 1 }; + } + const [width, height] = this.device.getDefaultCanvasContext().getDrawingBufferSize(); + const aspect = width > 0 && height > 0 ? width / height : 1; + return { width, height, aspect }; + } + /** @deprecated Default viewport setup */ + _resizeViewport() { + if (this.props.autoResizeViewport && this.device.gl) { + this.device.gl.viewport( + 0, + 0, + // @ts-expect-error Expose canvasContext + this.device.gl.drawingBufferWidth, + // @ts-expect-error Expose canvasContext + this.device.gl.drawingBufferHeight + ); + } + } + _beginFrameTimers(time) { + const now = time ?? (typeof performance !== "undefined" ? performance.now() : Date.now()); + if (this._lastFrameTime) { + const frameTime = now - this._lastFrameTime; + if (frameTime > 0) { + this.frameRate.addTime(frameTime); + } + } + this._lastFrameTime = now; + if (this.device?._isDebugGPUTimeEnabled()) { + this._consumeEncodedGpuTime(); + } + this.cpuTime.timeStart(); + } + _endFrameTimers() { + if (this.device?._isDebugGPUTimeEnabled()) { + this._consumeEncodedGpuTime(); + } + this.cpuTime.timeEnd(); + this._updateSharedStats(); + } + _consumeEncodedGpuTime() { + if (!this.device) { + return; + } + const gpuTimeMs = this.device.commandEncoder._gpuTimeMs; + if (gpuTimeMs !== void 0) { + this.gpuTime.addTime(gpuTimeMs); + this.device.commandEncoder._gpuTimeMs = void 0; + } + } + _updateSharedStats() { + if (this.stats === this.sharedStats) { + return; + } + for (const name2 of Object.keys(this.sharedStats.stats)) { + if (!this.stats.stats[name2]) { + delete this.sharedStats.stats[name2]; + } + } + this.stats.forEach((sourceStat) => { + const targetStat = this.sharedStats.get(sourceStat.name, sourceStat.type); + targetStat.sampleSize = sourceStat.sampleSize; + targetStat.time = sourceStat.time; + targetStat.count = sourceStat.count; + targetStat.samples = sourceStat.samples; + targetStat.lastTiming = sourceStat.lastTiming; + targetStat.lastSampleTime = sourceStat.lastSampleTime; + targetStat.lastSampleCount = sourceStat.lastSampleCount; + targetStat._count = sourceStat._count; + targetStat._time = sourceStat._time; + targetStat._samples = sourceStat._samples; + targetStat._startTime = sourceStat._startTime; + targetStat._timerPending = sourceStat._timerPending; + }); + } + // Event handling + _startEventHandling() { + if (this.canvas) { + this.canvas.addEventListener("mousemove", this._onMousemove.bind(this)); + this.canvas.addEventListener("mouseleave", this._onMouseleave.bind(this)); + } + } + _onMousemove(event) { + if (event instanceof MouseEvent) { + this._getAnimationProps()._mousePosition = [event.offsetX, event.offsetY]; + } + } + _onMouseleave(event) { + this._getAnimationProps()._mousePosition = null; + } + }; + + // node_modules/@luma.gl/engine/dist/model/model.js + init_dist4(); + + // node_modules/@luma.gl/engine/dist/geometry/gpu-geometry.js + init_dist4(); + + // node_modules/@luma.gl/engine/dist/utils/uid.js + var uidCounters2 = {}; + function uid2(id = "id") { + uidCounters2[id] = uidCounters2[id] || 1; + const count2 = uidCounters2[id]++; + return `${id}-${count2}`; + } + + // node_modules/@luma.gl/engine/dist/geometry/gpu-geometry.js + var GPUGeometry = class { + id; + userData = {}; + /** Determines how vertices are read from the 'vertex' attributes */ + topology; + bufferLayout = []; + vertexCount; + indices; + attributes; + constructor(props) { + this.id = props.id || uid2("geometry"); + this.topology = props.topology; + this.indices = props.indices || null; + this.attributes = props.attributes; + this.vertexCount = props.vertexCount; + this.bufferLayout = props.bufferLayout || []; + if (this.indices) { + if (!(this.indices.usage & Buffer2.INDEX)) { + throw new Error("Index buffer must have INDEX usage"); + } + } + } + destroy() { + this.indices?.destroy(); + for (const attribute of Object.values(this.attributes)) { + attribute.destroy(); + } + } + getVertexCount() { + return this.vertexCount; + } + getAttributes() { + return this.attributes; + } + getIndexes() { + return this.indices || null; + } + _calculateVertexCount(positions) { + const vertexCount = positions.byteLength / 12; + return vertexCount; + } + }; + function makeGPUGeometry(device, geometry) { + if (geometry instanceof GPUGeometry) { + return geometry; + } + const indices = getIndexBufferFromGeometry(device, geometry); + const { attributes, bufferLayout } = getAttributeBuffersFromGeometry(device, geometry); + return new GPUGeometry({ + topology: geometry.topology || "triangle-list", + bufferLayout, + vertexCount: geometry.vertexCount, + indices, + attributes + }); + } + function getIndexBufferFromGeometry(device, geometry) { + if (!geometry.indices) { + return void 0; + } + const data = geometry.indices.value; + return device.createBuffer({ usage: Buffer2.INDEX, data }); + } + function getAttributeBuffersFromGeometry(device, geometry) { + const bufferLayout = []; + const attributes = {}; + for (const [attributeName, attribute] of Object.entries(geometry.attributes)) { + let name2 = attributeName; + switch (attributeName) { + case "POSITION": + name2 = "positions"; + break; + case "NORMAL": + name2 = "normals"; + break; + case "TEXCOORD_0": + name2 = "texCoords"; + break; + case "TEXCOORD_1": + name2 = "texCoords1"; + break; + case "COLOR_0": + name2 = "colors"; + break; + } + if (attribute) { + attributes[name2] = device.createBuffer({ + data: attribute.value, + id: `${attributeName}-buffer` + }); + const { value, size, normalized } = attribute; + if (size === void 0) { + throw new Error(`Attribute ${attributeName} is missing a size`); + } + bufferLayout.push({ + name: name2, + format: vertexFormatDecoder.getVertexFormatFromAttribute(value, size, normalized) + }); + } + } + const vertexCount = geometry._calculateVertexCount(geometry.attributes, geometry.indices); + return { attributes, bufferLayout, vertexCount }; + } + + // node_modules/@luma.gl/engine/dist/debug/debug-shader-layout.js + function getDebugTableForShaderLayout(layout, name2) { + const table = {}; + const header = "Values"; + if (layout.attributes.length === 0 && !layout.varyings?.length) { + return { "No attributes or varyings": { [header]: "N/A" } }; + } + for (const attributeDeclaration of layout.attributes) { + if (attributeDeclaration) { + const glslDeclaration = `${attributeDeclaration.location} ${attributeDeclaration.name}: ${attributeDeclaration.type}`; + table[`in ${glslDeclaration}`] = { [header]: attributeDeclaration.stepMode || "vertex" }; + } + } + for (const varyingDeclaration of layout.varyings || []) { + const glslDeclaration = `${varyingDeclaration.location} ${varyingDeclaration.name}`; + table[`out ${glslDeclaration}`] = { [header]: JSON.stringify(varyingDeclaration) }; + } + return table; + } + + // node_modules/@luma.gl/engine/dist/debug/debug-framebuffer.js + var DEBUG_FRAMEBUFFER_STATE_KEY = "__debugFramebufferState"; + var DEFAULT_MARGIN_PX = 8; + function debugFramebuffer(renderPass, source3, options) { + if (renderPass.device.type !== "webgl") { + return; + } + const state = getDebugFramebufferState(renderPass.device); + if (state.flushing) { + return; + } + if (isDefaultRenderPass(renderPass)) { + flushDebugFramebuffers(renderPass, options, state); + return; + } + if (source3 && isFramebuffer(source3) && source3.handle !== null) { + if (!state.queuedFramebuffers.includes(source3)) { + state.queuedFramebuffers.push(source3); + } + } + } + function flushDebugFramebuffers(renderPass, options, state) { + if (state.queuedFramebuffers.length === 0) { + return; + } + const webglDevice = renderPass.device; + const { gl } = webglDevice; + const previousReadFramebuffer = gl.getParameter(36010); + const previousDrawFramebuffer = gl.getParameter(36006); + const [targetWidth, targetHeight] = renderPass.device.getDefaultCanvasContext().getDrawingBufferSize(); + let topPx = parseCssPixel(options.top, DEFAULT_MARGIN_PX); + const leftPx = parseCssPixel(options.left, DEFAULT_MARGIN_PX); + state.flushing = true; + try { + for (const framebuffer of state.queuedFramebuffers) { + const [targetX0, targetY0, targetX1, targetY1, previewHeight] = getOverlayRect({ + framebuffer, + targetWidth, + targetHeight, + topPx, + leftPx, + minimap: options.minimap + }); + gl.bindFramebuffer(36008, framebuffer.handle); + gl.bindFramebuffer(36009, null); + gl.blitFramebuffer(0, 0, framebuffer.width, framebuffer.height, targetX0, targetY0, targetX1, targetY1, 16384, 9728); + topPx += previewHeight + DEFAULT_MARGIN_PX; + } + } finally { + gl.bindFramebuffer(36008, previousReadFramebuffer); + gl.bindFramebuffer(36009, previousDrawFramebuffer); + state.flushing = false; + } + } + function getOverlayRect(options) { + const { framebuffer, targetWidth, targetHeight, topPx, leftPx, minimap } = options; + const maxWidth = minimap ? Math.max(Math.floor(targetWidth / 4), 1) : targetWidth; + const maxHeight = minimap ? Math.max(Math.floor(targetHeight / 4), 1) : targetHeight; + const scale5 = Math.min(maxWidth / framebuffer.width, maxHeight / framebuffer.height); + const previewWidth = Math.max(Math.floor(framebuffer.width * scale5), 1); + const previewHeight = Math.max(Math.floor(framebuffer.height * scale5), 1); + const targetX0 = leftPx; + const targetY0 = Math.max(targetHeight - topPx - previewHeight, 0); + const targetX1 = targetX0 + previewWidth; + const targetY1 = targetY0 + previewHeight; + return [targetX0, targetY0, targetX1, targetY1, previewHeight]; + } + function getDebugFramebufferState(device) { + device.userData[DEBUG_FRAMEBUFFER_STATE_KEY] ||= { + flushing: false, + queuedFramebuffers: [] + }; + return device.userData[DEBUG_FRAMEBUFFER_STATE_KEY]; + } + function isFramebuffer(value) { + return "colorAttachments" in value; + } + function isDefaultRenderPass(renderPass) { + const framebuffer = renderPass.props.framebuffer; + return !framebuffer || framebuffer.handle === null; + } + function parseCssPixel(value, defaultValue) { + if (!value) { + return defaultValue; + } + const parsedValue = Number.parseInt(value, 10); + return Number.isFinite(parsedValue) ? parsedValue : defaultValue; + } + + // node_modules/@luma.gl/engine/dist/utils/deep-equal.js + function deepEqual(a, b, depth) { + if (a === b) { + return true; + } + if (!depth || !a || !b) { + return false; + } + if (Array.isArray(a)) { + if (!Array.isArray(b) || a.length !== b.length) { + return false; + } + for (let i = 0; i < a.length; i++) { + if (!deepEqual(a[i], b[i], depth - 1)) { + return false; + } + } + return true; + } + if (Array.isArray(b)) { + return false; + } + if (typeof a === "object" && typeof b === "object") { + const aKeys = Object.keys(a); + const bKeys = Object.keys(b); + if (aKeys.length !== bKeys.length) { + return false; + } + for (const key of aKeys) { + if (!b.hasOwnProperty(key)) { + return false; + } + if (!deepEqual(a[key], b[key], depth - 1)) { + return false; + } + } + return true; + } + return false; + } + + // node_modules/@luma.gl/engine/dist/utils/buffer-layout-helper.js + init_dist4(); + var BufferLayoutHelper = class { + bufferLayouts; + constructor(bufferLayouts) { + this.bufferLayouts = bufferLayouts; + } + getBufferLayout(name2) { + return this.bufferLayouts.find((layout) => layout.name === name2) || null; + } + /** Get attribute names from a BufferLayout */ + getAttributeNamesForBuffer(bufferLayout) { + return bufferLayout.attributes ? bufferLayout.attributes?.map((layout) => layout.attribute) : [bufferLayout.name]; + } + mergeBufferLayouts(bufferLayouts1, bufferLayouts2) { + const mergedLayouts = [...bufferLayouts1]; + for (const attribute of bufferLayouts2) { + const index2 = mergedLayouts.findIndex((attribute2) => attribute2.name === attribute.name); + if (index2 < 0) { + mergedLayouts.push(attribute); + } else { + mergedLayouts[index2] = attribute; + } + } + return mergedLayouts; + } + getBufferIndex(bufferName) { + const bufferIndex = this.bufferLayouts.findIndex((layout) => layout.name === bufferName); + if (bufferIndex === -1) { + log2.warn(`BufferLayout: Missing buffer for "${bufferName}".`)(); + } + return bufferIndex; + } + }; + + // node_modules/@luma.gl/engine/dist/utils/buffer-layout-order.js + function getMinLocation(attributeNames, shaderLayoutMap) { + let minLocation = Infinity; + for (const name2 of attributeNames) { + const location = shaderLayoutMap[name2]; + if (location !== void 0) { + minLocation = Math.min(minLocation, location); + } + } + return minLocation; + } + function sortedBufferLayoutByShaderSourceLocations(shaderLayout, bufferLayout) { + const shaderLayoutMap = Object.fromEntries(shaderLayout.attributes.map((attr) => [attr.name, attr.location])); + const sortedLayout = bufferLayout.slice(); + sortedLayout.sort((a, b) => { + const attributeNamesA = a.attributes ? a.attributes.map((attr) => attr.attribute) : [a.name]; + const attributeNamesB = b.attributes ? b.attributes.map((attr) => attr.attribute) : [b.name]; + const minLocationA = getMinLocation(attributeNamesA, shaderLayoutMap); + const minLocationB = getMinLocation(attributeNamesB, shaderLayoutMap); + return minLocationA - minLocationB; + }); + return sortedLayout; + } + + // node_modules/@luma.gl/engine/dist/utils/shader-module-utils.js + function mergeShaderModuleBindingsIntoLayout(shaderLayout, modules) { + if (!shaderLayout || !modules.some((module) => module.bindingLayout?.length)) { + return shaderLayout; + } + const mergedLayout = { + ...shaderLayout, + bindings: shaderLayout.bindings.map((binding) => ({ ...binding })) + }; + if ("attributes" in (shaderLayout || {})) { + mergedLayout.attributes = shaderLayout?.attributes || []; + } + for (const module of modules) { + for (const bindingLayout of module.bindingLayout || []) { + for (const relatedBindingName of getRelatedBindingNames(bindingLayout.name)) { + const binding = mergedLayout.bindings.find((candidate) => candidate.name === relatedBindingName); + if (binding?.group === 0) { + binding.group = bindingLayout.group; + } + } + } + } + return mergedLayout; + } + function shaderModuleHasUniforms(module) { + return Boolean(module.uniformTypes && !isObjectEmpty(module.uniformTypes)); + } + function getRelatedBindingNames(bindingName) { + const bindingNames = /* @__PURE__ */ new Set([bindingName, `${bindingName}Uniforms`]); + if (!bindingName.endsWith("Uniforms")) { + bindingNames.add(`${bindingName}Sampler`); + } + return [...bindingNames]; + } + function isObjectEmpty(obj) { + for (const key in obj) { + return false; + } + return true; + } + + // node_modules/@luma.gl/engine/dist/shader-inputs.js + init_dist4(); + + // node_modules/@luma.gl/engine/dist/model/split-uniforms-and-bindings.js + function isUniformValue(value) { + return isNumericArray(value) || typeof value === "number" || typeof value === "boolean"; + } + function splitUniformsAndBindings(uniforms, uniformTypes = {}) { + const result = { bindings: {}, uniforms: {} }; + Object.keys(uniforms).forEach((name2) => { + const uniform = uniforms[name2]; + if (Object.prototype.hasOwnProperty.call(uniformTypes, name2) || isUniformValue(uniform)) { + result.uniforms[name2] = uniform; + } else { + result.bindings[name2] = uniform; + } + }); + return result; + } + + // node_modules/@luma.gl/engine/dist/shader-inputs.js + var ShaderInputs = class { + options = { + disableWarnings: false + }; + /** + * The map of modules + * @todo should should this include the resolved dependencies? + */ + // @ts-ignore Fix typings + modules; + /** Stores the uniform values for each module */ + moduleUniforms; + /** Stores the uniform bindings for each module */ + moduleBindings; + /** Tracks if uniforms have changed */ + // moduleUniformsChanged: Record; + /** + * Create a new UniformStore instance + * @param modules + */ + constructor(modules, options) { + Object.assign(this.options, options); + const resolvedModules = getShaderModuleDependencies(Object.values(modules).filter(isShaderInputsModuleWithDependencies)); + for (const resolvedModule of resolvedModules) { + modules[resolvedModule.name] = resolvedModule; + } + log2.log(1, "Creating ShaderInputs with modules", Object.keys(modules))(); + this.modules = modules; + this.moduleUniforms = {}; + this.moduleBindings = {}; + for (const [name2, module] of Object.entries(modules)) { + if (module) { + this._addModule(module); + if (module.name && name2 !== module.name && !this.options.disableWarnings) { + log2.warn(`Module name: ${name2} vs ${module.name}`)(); + } + } + } + } + /** Destroy */ + destroy() { + } + /** + * Set module props + */ + setProps(props) { + for (const name2 of Object.keys(props)) { + const moduleName = name2; + const moduleProps = props[moduleName] || {}; + const module = this.modules[moduleName]; + if (!module) { + if (!this.options.disableWarnings) { + log2.warn(`Module ${name2} not found`)(); + } + } else { + const oldUniforms = this.moduleUniforms[moduleName]; + const oldBindings = this.moduleBindings[moduleName]; + const uniformsAndBindings = module.getUniforms?.(moduleProps, oldUniforms) || moduleProps; + const { uniforms, bindings } = splitUniformsAndBindings(uniformsAndBindings, module.uniformTypes); + this.moduleUniforms[moduleName] = mergeModuleUniforms(oldUniforms, uniforms, module.uniformTypes); + this.moduleBindings[moduleName] = { ...oldBindings, ...bindings }; + } + } + } + /** + * Return the map of modules + * @todo should should this include the resolved dependencies? + */ + getModules() { + return Object.values(this.modules); + } + /** Get all uniform values for all modules */ + getUniformValues() { + return this.moduleUniforms; + } + /** Merges all bindings for the shader (from the various modules) */ + getBindingValues() { + const bindings = {}; + for (const moduleBindings of Object.values(this.moduleBindings)) { + Object.assign(bindings, moduleBindings); + } + return bindings; + } + // INTERNAL + /** Return a debug table that can be used for console.table() or log.table() */ + getDebugTable() { + const table = {}; + for (const [moduleName, module] of Object.entries(this.moduleUniforms)) { + for (const [key, value] of Object.entries(module)) { + table[`${moduleName}.${key}`] = { + type: this.modules[moduleName].uniformTypes?.[key], + value: String(value) + }; + } + } + return table; + } + _addModule(module) { + const moduleName = module.name; + this.moduleUniforms[moduleName] = mergeModuleUniforms({}, module.defaultUniforms || {}, module.uniformTypes); + this.moduleBindings[moduleName] = {}; + } + }; + function mergeModuleUniforms(currentUniforms = {}, nextUniforms = {}, uniformTypes = {}) { + const mergedUniforms = { ...currentUniforms }; + for (const [key, value] of Object.entries(nextUniforms)) { + if (value !== void 0) { + mergedUniforms[key] = mergeModuleUniformValue(currentUniforms[key], value, uniformTypes[key]); + } + } + return mergedUniforms; + } + function mergeModuleUniformValue(currentValue, nextValue, uniformType) { + if (!uniformType || typeof uniformType === "string") { + return cloneModuleUniformValue(nextValue); + } + if (Array.isArray(uniformType)) { + if (isPackedUniformArrayValue(nextValue) || !Array.isArray(nextValue)) { + return cloneModuleUniformValue(nextValue); + } + const currentArray = Array.isArray(currentValue) && !isPackedUniformArrayValue(currentValue) ? [...currentValue] : []; + const mergedArray = currentArray.slice(); + for (let index2 = 0; index2 < nextValue.length; index2++) { + const elementValue = nextValue[index2]; + if (elementValue !== void 0) { + mergedArray[index2] = mergeModuleUniformValue(currentArray[index2], elementValue, uniformType[0]); + } + } + return mergedArray; + } + if (!isPlainUniformObject(nextValue)) { + return cloneModuleUniformValue(nextValue); + } + const uniformStruct = uniformType; + const currentObject = isPlainUniformObject(currentValue) ? currentValue : {}; + const mergedObject = { ...currentObject }; + for (const [key, value] of Object.entries(nextValue)) { + if (value !== void 0) { + mergedObject[key] = mergeModuleUniformValue(currentObject[key], value, uniformStruct[key]); + } + } + return mergedObject; + } + function cloneModuleUniformValue(value) { + if (ArrayBuffer.isView(value)) { + return Array.prototype.slice.call(value); + } + if (Array.isArray(value)) { + if (isPackedUniformArrayValue(value)) { + return value.slice(); + } + const compositeArray = value; + return compositeArray.map((element) => element === void 0 ? void 0 : cloneModuleUniformValue(element)); + } + if (isPlainUniformObject(value)) { + return Object.fromEntries(Object.entries(value).map(([key, nestedValue]) => [ + key, + nestedValue === void 0 ? void 0 : cloneModuleUniformValue(nestedValue) + ])); + } + return value; + } + function isPackedUniformArrayValue(value) { + return ArrayBuffer.isView(value) || Array.isArray(value) && (value.length === 0 || typeof value[0] === "number"); + } + function isPlainUniformObject(value) { + return Boolean(value) && typeof value === "object" && !Array.isArray(value) && !ArrayBuffer.isView(value); + } + function isShaderInputsModuleWithDependencies(module) { + return Boolean(module?.dependencies); + } + + // node_modules/@luma.gl/engine/dist/dynamic-texture/dynamic-texture.js + init_dist4(); + + // node_modules/@luma.gl/engine/dist/dynamic-texture/texture-data.js + init_dist4(); + var TEXTURE_CUBE_FACE_MAP = { "+X": 0, "-X": 1, "+Y": 2, "-Y": 3, "+Z": 4, "-Z": 5 }; + function getFirstMipLevel(layer) { + if (!layer) + return null; + return Array.isArray(layer) ? layer[0] ?? null : layer; + } + function getTextureSizeFromData(props) { + const { dimension, data } = props; + if (!data) { + return null; + } + switch (dimension) { + case "1d": { + const mipLevel = getFirstMipLevel(data); + if (!mipLevel) + return null; + const { width } = getTextureMipLevelSize(mipLevel); + return { width, height: 1 }; + } + case "2d": { + const mipLevel = getFirstMipLevel(data); + return mipLevel ? getTextureMipLevelSize(mipLevel) : null; + } + case "3d": + case "2d-array": { + if (!Array.isArray(data) || data.length === 0) + return null; + const mipLevel = getFirstMipLevel(data[0]); + return mipLevel ? getTextureMipLevelSize(mipLevel) : null; + } + case "cube": { + const face = Object.keys(data)[0] ?? null; + if (!face) + return null; + const faceData = data[face]; + const mipLevel = getFirstMipLevel(faceData); + return mipLevel ? getTextureMipLevelSize(mipLevel) : null; + } + case "cube-array": { + if (!Array.isArray(data) || data.length === 0) + return null; + const firstCube = data[0]; + const face = Object.keys(firstCube)[0] ?? null; + if (!face) + return null; + const mipLevel = getFirstMipLevel(firstCube[face]); + return mipLevel ? getTextureMipLevelSize(mipLevel) : null; + } + default: + return null; + } + } + function getTextureMipLevelSize(data) { + if (isExternalImage(data)) { + return getExternalImageSize(data); + } + if (typeof data === "object" && "width" in data && "height" in data) { + return { width: data.width, height: data.height }; + } + throw new Error("Unsupported mip-level data"); + } + function isTextureImageData(data) { + return typeof data === "object" && data !== null && "data" in data && "width" in data && "height" in data; + } + function isTypedArrayMipLevelData(data) { + return ArrayBuffer.isView(data); + } + function resolveTextureImageFormat(data) { + const { textureFormat, format: format2 } = data; + if (textureFormat && format2 && textureFormat !== format2) { + throw new Error(`Conflicting texture formats "${textureFormat}" and "${format2}" provided for the same mip level`); + } + return textureFormat ?? format2; + } + function getCubeFaceIndex(face) { + const idx = TEXTURE_CUBE_FACE_MAP[face]; + if (idx === void 0) + throw new Error(`Invalid cube face: ${face}`); + return idx; + } + function getCubeArrayFaceIndex(cubeIndex, face) { + return 6 * cubeIndex + getCubeFaceIndex(face); + } + function getTexture1DSubresources(data) { + throw new Error("setTexture1DData not supported in WebGL."); + } + function _normalizeTexture2DData(data) { + return Array.isArray(data) ? data : [data]; + } + function getTexture2DSubresources(slice, lodData, baseLevelSize, textureFormat) { + const lodArray = _normalizeTexture2DData(lodData); + const z = slice; + const subresources = []; + for (let mipLevel = 0; mipLevel < lodArray.length; mipLevel++) { + const imageData = lodArray[mipLevel]; + if (isExternalImage(imageData)) { + subresources.push({ + type: "external-image", + image: imageData, + z, + mipLevel + }); + } else if (isTextureImageData(imageData)) { + subresources.push({ + type: "texture-data", + data: imageData, + textureFormat: resolveTextureImageFormat(imageData), + z, + mipLevel + }); + } else if (isTypedArrayMipLevelData(imageData) && baseLevelSize) { + subresources.push({ + type: "texture-data", + data: { + data: imageData, + width: Math.max(1, baseLevelSize.width >> mipLevel), + height: Math.max(1, baseLevelSize.height >> mipLevel), + ...textureFormat ? { format: textureFormat } : {} + }, + textureFormat, + z, + mipLevel + }); + } else { + throw new Error("Unsupported 2D mip-level payload"); + } + } + return subresources; + } + function getTexture3DSubresources(data) { + const subresources = []; + for (let depth = 0; depth < data.length; depth++) { + subresources.push(...getTexture2DSubresources(depth, data[depth])); + } + return subresources; + } + function getTextureArraySubresources(data) { + const subresources = []; + for (let layer = 0; layer < data.length; layer++) { + subresources.push(...getTexture2DSubresources(layer, data[layer])); + } + return subresources; + } + function getTextureCubeSubresources(data) { + const subresources = []; + for (const [face, faceData] of Object.entries(data)) { + const faceDepth = getCubeFaceIndex(face); + subresources.push(...getTexture2DSubresources(faceDepth, faceData)); + } + return subresources; + } + function getTextureCubeArraySubresources(data) { + const subresources = []; + data.forEach((cubeData, cubeIndex) => { + for (const [face, faceData] of Object.entries(cubeData)) { + const faceDepth = getCubeArrayFaceIndex(cubeIndex, face); + subresources.push(...getTexture2DSubresources(faceDepth, faceData)); + } + }); + return subresources; + } + + // node_modules/@luma.gl/engine/dist/dynamic-texture/dynamic-texture.js + var DynamicTexture = class _DynamicTexture { + device; + id; + /** Props with defaults resolved (except `data` which is processed separately) */ + props; + /** Created resources */ + _texture = null; + _sampler = null; + _view = null; + /** Ready when GPU texture has been created and data (if any) uploaded */ + ready; + isReady = false; + destroyed = false; + resolveReady = () => { + }; + rejectReady = () => { + }; + get texture() { + if (!this._texture) + throw new Error("Texture not initialized yet"); + return this._texture; + } + get sampler() { + if (!this._sampler) + throw new Error("Sampler not initialized yet"); + return this._sampler; + } + get view() { + if (!this._view) + throw new Error("View not initialized yet"); + return this._view; + } + get [Symbol.toStringTag]() { + return "DynamicTexture"; + } + toString() { + const width = this._texture?.width ?? this.props.width ?? "?"; + const height = this._texture?.height ?? this.props.height ?? "?"; + return `DynamicTexture:"${this.id}":${width}x${height}px:(${this.isReady ? "ready" : "loading..."})`; + } + constructor(device, props) { + this.device = device; + const id = uid2("dynamic-texture"); + const originalPropsWithAsyncData = props; + this.props = { ..._DynamicTexture.defaultProps, id, ...props, data: null }; + this.id = this.props.id; + this.ready = new Promise((resolve2, reject) => { + this.resolveReady = resolve2; + this.rejectReady = reject; + }); + this.initAsync(originalPropsWithAsyncData); + } + /** @note Fire and forget; caller can await `ready` */ + async initAsync(originalPropsWithAsyncData) { + try { + const propsWithSyncData = await this._loadAllData(originalPropsWithAsyncData); + this._checkNotDestroyed(); + const subresources = propsWithSyncData.data ? getTextureSubresources({ + ...propsWithSyncData, + width: originalPropsWithAsyncData.width, + height: originalPropsWithAsyncData.height, + format: originalPropsWithAsyncData.format + }) : []; + const userProvidedFormat = "format" in originalPropsWithAsyncData && originalPropsWithAsyncData.format !== void 0; + const userProvidedUsage = "usage" in originalPropsWithAsyncData && originalPropsWithAsyncData.usage !== void 0; + const deduceSize = () => { + if (this.props.width && this.props.height) { + return { width: this.props.width, height: this.props.height }; + } + const size2 = getTextureSizeFromData(propsWithSyncData); + if (size2) { + return size2; + } + return { width: this.props.width || 1, height: this.props.height || 1 }; + }; + const size = deduceSize(); + if (!size || size.width <= 0 || size.height <= 0) { + throw new Error(`${this} size could not be determined or was zero`); + } + const textureData = analyzeTextureSubresources(this.device, subresources, size, { + format: userProvidedFormat ? originalPropsWithAsyncData.format : void 0 + }); + const resolvedFormat = textureData.format ?? this.props.format; + const baseTextureProps = { + ...this.props, + ...size, + format: resolvedFormat, + mipLevels: 1, + // temporary; updated below + data: void 0 + }; + if (this.device.isTextureFormatCompressed(resolvedFormat) && !userProvidedUsage) { + baseTextureProps.usage = Texture.SAMPLE | Texture.COPY_DST; + } + const shouldGenerateMipmaps = this.props.mipmaps && !textureData.hasExplicitMipChain && !this.device.isTextureFormatCompressed(resolvedFormat); + if (this.device.type === "webgpu" && shouldGenerateMipmaps) { + const requiredUsage = this.props.dimension === "3d" ? Texture.SAMPLE | Texture.STORAGE | Texture.COPY_DST | Texture.COPY_SRC : Texture.SAMPLE | Texture.RENDER | Texture.COPY_DST | Texture.COPY_SRC; + baseTextureProps.usage |= requiredUsage; + } + const maxMips = this.device.getMipLevelCount(baseTextureProps.width, baseTextureProps.height); + const desired = textureData.hasExplicitMipChain ? textureData.mipLevels : this.props.mipLevels === "auto" ? maxMips : Math.max(1, Math.min(maxMips, this.props.mipLevels ?? 1)); + const finalTextureProps = { ...baseTextureProps, mipLevels: desired }; + this._texture = this.device.createTexture(finalTextureProps); + this._sampler = this.texture.sampler; + this._view = this.texture.view; + if (textureData.subresources.length) { + this._setTextureSubresources(textureData.subresources); + } + if (this.props.mipmaps && !textureData.hasExplicitMipChain && !shouldGenerateMipmaps) { + log2.warn(`${this} skipping auto-generated mipmaps for compressed texture format`)(); + } + if (shouldGenerateMipmaps) { + this.generateMipmaps(); + } + this.isReady = true; + this.resolveReady(this.texture); + log2.info(0, `${this} created`)(); + } catch (e) { + const err = e instanceof Error ? e : new Error(String(e)); + this.rejectReady(err); + } + } + destroy() { + if (this._texture) { + this._texture.destroy(); + this._texture = null; + this._sampler = null; + this._view = null; + } + this.destroyed = true; + } + generateMipmaps() { + if (this.device.type === "webgl") { + this.texture.generateMipmapsWebGL(); + } else if (this.device.type === "webgpu") { + this.device.generateMipmapsWebGPU(this.texture); + } else { + log2.warn(`${this} mipmaps not supported on ${this.device.type}`); + } + } + /** Set sampler or create one from props */ + setSampler(sampler = {}) { + this._checkReady(); + const s = sampler instanceof Sampler ? sampler : this.device.createSampler(sampler); + this.texture.setSampler(s); + this._sampler = s; + } + /** + * Copies texture contents into a GPU buffer and waits until the copy is complete. + * The caller owns the returned buffer and must destroy it when finished. + */ + async readBuffer(options = {}) { + if (!this.isReady) { + await this.ready; + } + const width = options.width ?? this.texture.width; + const height = options.height ?? this.texture.height; + const depthOrArrayLayers = options.depthOrArrayLayers ?? this.texture.depth; + const layout = this.texture.computeMemoryLayout({ width, height, depthOrArrayLayers }); + const buffer = this.device.createBuffer({ + byteLength: layout.byteLength, + usage: Buffer2.COPY_DST | Buffer2.MAP_READ + }); + this.texture.readBuffer({ + ...options, + width, + height, + depthOrArrayLayers + }, buffer); + const fence = this.device.createFence(); + await fence.signaled; + fence.destroy(); + return buffer; + } + /** Reads texture contents back to CPU memory. */ + async readAsync(options = {}) { + if (!this.isReady) { + await this.ready; + } + const width = options.width ?? this.texture.width; + const height = options.height ?? this.texture.height; + const depthOrArrayLayers = options.depthOrArrayLayers ?? this.texture.depth; + const layout = this.texture.computeMemoryLayout({ width, height, depthOrArrayLayers }); + const buffer = await this.readBuffer(options); + const data = await buffer.readAsync(0, layout.byteLength); + buffer.destroy(); + return data.buffer; + } + /** + * Resize by cloning the underlying immutable texture. + * Does not copy contents; caller may need to re-upload and/or regenerate mips. + */ + resize(size) { + this._checkReady(); + if (size.width === this.texture.width && size.height === this.texture.height) { + return false; + } + const prev = this.texture; + this._texture = prev.clone(size); + this._sampler = this.texture.sampler; + this._view = this.texture.view; + prev.destroy(); + log2.info(`${this} resized`); + return true; + } + /** Convert cube face label to texture slice index. Index can be used with `setTexture2DData()`. */ + getCubeFaceIndex(face) { + const index2 = TEXTURE_CUBE_FACE_MAP[face]; + if (index2 === void 0) + throw new Error(`Invalid cube face: ${face}`); + return index2; + } + /** Convert cube face label to texture slice index. Index can be used with `setTexture2DData()`. */ + getCubeArrayFaceIndex(cubeIndex, face) { + return 6 * cubeIndex + this.getCubeFaceIndex(face); + } + /** @note experimental: Set multiple mip levels (1D) */ + setTexture1DData(data) { + this._checkReady(); + if (this.texture.props.dimension !== "1d") { + throw new Error(`${this} is not 1d`); + } + const subresources = getTexture1DSubresources(data); + this._setTextureSubresources(subresources); + } + /** @note experimental: Set multiple mip levels (2D), optionally at `z`, slice (depth/array level) index */ + setTexture2DData(lodData, z = 0) { + this._checkReady(); + if (this.texture.props.dimension !== "2d") { + throw new Error(`${this} is not 2d`); + } + const subresources = getTexture2DSubresources(z, lodData); + this._setTextureSubresources(subresources); + } + /** 3D: multiple depth slices, each may carry multiple mip levels */ + setTexture3DData(data) { + if (this.texture.props.dimension !== "3d") { + throw new Error(`${this} is not 3d`); + } + const subresources = getTexture3DSubresources(data); + this._setTextureSubresources(subresources); + } + /** 2D array: multiple layers, each may carry multiple mip levels */ + setTextureArrayData(data) { + if (this.texture.props.dimension !== "2d-array") { + throw new Error(`${this} is not 2d-array`); + } + const subresources = getTextureArraySubresources(data); + this._setTextureSubresources(subresources); + } + /** Cube: 6 faces, each may carry multiple mip levels */ + setTextureCubeData(data) { + if (this.texture.props.dimension !== "cube") { + throw new Error(`${this} is not cube`); + } + const subresources = getTextureCubeSubresources(data); + this._setTextureSubresources(subresources); + } + /** Cube array: multiple cubes (faces×layers), each face may carry multiple mips */ + setTextureCubeArrayData(data) { + if (this.texture.props.dimension !== "cube-array") { + throw new Error(`${this} is not cube-array`); + } + const subresources = getTextureCubeArraySubresources(data); + this._setTextureSubresources(subresources); + } + /** Sets multiple mip levels on different `z` slices (depth/array index) */ + _setTextureSubresources(subresources) { + for (const subresource of subresources) { + const { z, mipLevel } = subresource; + switch (subresource.type) { + case "external-image": + const { image, flipY } = subresource; + this.texture.copyExternalImage({ image, z, mipLevel, flipY }); + break; + case "texture-data": + const { data, textureFormat } = subresource; + if (textureFormat && textureFormat !== this.texture.format) { + throw new Error(`${this} mip level ${mipLevel} uses format "${textureFormat}" but texture format is "${this.texture.format}"`); + } + this.texture.writeData(data.data, { + x: 0, + y: 0, + z, + width: data.width, + height: data.height, + depthOrArrayLayers: 1, + mipLevel + }); + break; + default: + throw new Error("Unsupported 2D mip-level payload"); + } + } + } + // ------------------ helpers ------------------ + /** Recursively resolve all promises in data structures */ + async _loadAllData(props) { + const syncData = await awaitAllPromises(props.data); + const dimension = props.dimension ?? "2d"; + return { dimension, data: syncData ?? null }; + } + _checkNotDestroyed() { + if (this.destroyed) { + log2.warn(`${this} already destroyed`); + } + } + _checkReady() { + if (!this.isReady) { + log2.warn(`${this} Cannot perform this operation before ready`); + } + } + static defaultProps = { + ...Texture.defaultProps, + dimension: "2d", + data: null, + mipmaps: false + }; + }; + function getTextureSubresources(props) { + if (!props.data) { + return []; + } + const baseLevelSize = props.width && props.height ? { width: props.width, height: props.height } : void 0; + const textureFormat = "format" in props ? props.format : void 0; + switch (props.dimension) { + case "1d": + return getTexture1DSubresources(props.data); + case "2d": + return getTexture2DSubresources(0, props.data, baseLevelSize, textureFormat); + case "3d": + return getTexture3DSubresources(props.data); + case "2d-array": + return getTextureArraySubresources(props.data); + case "cube": + return getTextureCubeSubresources(props.data); + case "cube-array": + return getTextureCubeArraySubresources(props.data); + default: + throw new Error(`Unhandled dimension ${props.dimension}`); + } + } + function analyzeTextureSubresources(device, subresources, size, options) { + if (subresources.length === 0) { + return { + subresources, + mipLevels: 1, + format: options.format, + hasExplicitMipChain: false + }; + } + const groupedSubresources = /* @__PURE__ */ new Map(); + for (const subresource of subresources) { + const group2 = groupedSubresources.get(subresource.z) ?? []; + group2.push(subresource); + groupedSubresources.set(subresource.z, group2); + } + const hasExplicitMipChain = subresources.some((subresource) => subresource.mipLevel > 0); + let resolvedFormat = options.format; + let resolvedMipLevels = Number.POSITIVE_INFINITY; + const validSubresources = []; + for (const [z, sliceSubresources] of groupedSubresources) { + const sortedSubresources = [...sliceSubresources].sort((left, right) => left.mipLevel - right.mipLevel); + const baseLevel = sortedSubresources[0]; + if (!baseLevel || baseLevel.mipLevel !== 0) { + throw new Error(`DynamicTexture: slice ${z} is missing mip level 0`); + } + const baseSize = getTextureSubresourceSize(device, baseLevel); + if (baseSize.width !== size.width || baseSize.height !== size.height) { + throw new Error(`DynamicTexture: slice ${z} base level dimensions ${baseSize.width}x${baseSize.height} do not match expected ${size.width}x${size.height}`); + } + const baseFormat = getTextureSubresourceFormat(baseLevel); + if (baseFormat) { + if (resolvedFormat && resolvedFormat !== baseFormat) { + throw new Error(`DynamicTexture: slice ${z} base level format "${baseFormat}" does not match texture format "${resolvedFormat}"`); + } + resolvedFormat = baseFormat; + } + const mipLevelLimit = resolvedFormat && device.isTextureFormatCompressed(resolvedFormat) ? ( + // Block-compressed formats cannot have mips smaller than a single compression block. + getMaxCompressedMipLevels(device, baseSize.width, baseSize.height, resolvedFormat) + ) : device.getMipLevelCount(baseSize.width, baseSize.height); + let validMipLevelsForSlice = 0; + for (let expectedMipLevel = 0; expectedMipLevel < sortedSubresources.length; expectedMipLevel++) { + const subresource = sortedSubresources[expectedMipLevel]; + if (!subresource || subresource.mipLevel !== expectedMipLevel) { + break; + } + if (expectedMipLevel >= mipLevelLimit) { + break; + } + const subresourceSize = getTextureSubresourceSize(device, subresource); + const expectedWidth = Math.max(1, baseSize.width >> expectedMipLevel); + const expectedHeight = Math.max(1, baseSize.height >> expectedMipLevel); + if (subresourceSize.width !== expectedWidth || subresourceSize.height !== expectedHeight) { + break; + } + const subresourceFormat = getTextureSubresourceFormat(subresource); + if (subresourceFormat) { + if (!resolvedFormat) { + resolvedFormat = subresourceFormat; + } + if (subresourceFormat !== resolvedFormat) { + break; + } + } + validMipLevelsForSlice++; + validSubresources.push(subresource); + } + resolvedMipLevels = Math.min(resolvedMipLevels, validMipLevelsForSlice); + } + const mipLevels = Number.isFinite(resolvedMipLevels) ? Math.max(1, resolvedMipLevels) : 1; + return { + // Keep every slice trimmed to the same mip count so the texture shape stays internally consistent. + subresources: validSubresources.filter((subresource) => subresource.mipLevel < mipLevels), + mipLevels, + format: resolvedFormat, + hasExplicitMipChain + }; + } + function getTextureSubresourceFormat(subresource) { + if (subresource.type !== "texture-data") { + return void 0; + } + return subresource.textureFormat ?? resolveTextureImageFormat(subresource.data); + } + function getTextureSubresourceSize(device, subresource) { + switch (subresource.type) { + case "external-image": + return device.getExternalImageSize(subresource.image); + case "texture-data": + return { width: subresource.data.width, height: subresource.data.height }; + default: + throw new Error("Unsupported texture subresource"); + } + } + function getMaxCompressedMipLevels(device, baseWidth, baseHeight, format2) { + const { blockWidth = 1, blockHeight = 1 } = device.getTextureFormatInfo(format2); + let mipLevels = 1; + for (let mipLevel = 1; ; mipLevel++) { + const width = Math.max(1, baseWidth >> mipLevel); + const height = Math.max(1, baseHeight >> mipLevel); + if (width < blockWidth || height < blockHeight) { + break; + } + mipLevels++; + } + return mipLevels; + } + async function awaitAllPromises(x) { + x = await x; + if (Array.isArray(x)) { + return await Promise.all(x.map(awaitAllPromises)); + } + if (x && typeof x === "object" && x.constructor === Object) { + const object = x; + const values = await Promise.all(Object.values(object).map(awaitAllPromises)); + const keys = Object.keys(object); + const resolvedObject = {}; + for (let i = 0; i < keys.length; i++) { + resolvedObject[keys[i]] = values[i]; + } + return resolvedObject; + } + return x; + } + + // node_modules/@luma.gl/engine/dist/model/model.js + var LOG_DRAW_PRIORITY = 2; + var LOG_DRAW_TIMEOUT = 1e4; + var PIPELINE_INITIALIZATION_FAILED = "render pipeline initialization failed"; + var Model = class _Model { + static defaultProps = { + ...RenderPipeline.defaultProps, + source: void 0, + vs: null, + fs: null, + id: "unnamed", + handle: void 0, + userData: {}, + defines: {}, + modules: [], + geometry: null, + indexBuffer: null, + attributes: {}, + constantAttributes: {}, + bindings: {}, + uniforms: {}, + varyings: [], + isInstanced: void 0, + instanceCount: 0, + vertexCount: 0, + shaderInputs: void 0, + material: void 0, + pipelineFactory: void 0, + shaderFactory: void 0, + transformFeedback: void 0, + shaderAssembler: ShaderAssembler.getDefaultShaderAssembler(), + debugShaders: void 0, + disableWarnings: void 0 + }; + /** Device that created this model */ + device; + /** Application provided identifier */ + id; + /** WGSL shader source when using unified shader */ + // @ts-expect-error assigned in function called from constructor + source; + /** GLSL vertex shader source */ + // @ts-expect-error assigned in function called from constructor + vs; + /** GLSL fragment shader source */ + // @ts-expect-error assigned in function called from constructor + fs; + /** Factory used to create render pipelines */ + pipelineFactory; + /** Factory used to create shaders */ + shaderFactory; + /** User-supplied per-model data */ + userData = {}; + // Fixed properties (change can trigger pipeline rebuild) + /** The render pipeline GPU parameters, depth testing etc */ + parameters; + /** The primitive topology */ + topology; + /** Buffer layout */ + bufferLayout; + // Dynamic properties + /** Use instanced rendering */ + isInstanced = void 0; + /** instance count. `undefined` means not instanced */ + instanceCount = 0; + /** Vertex count */ + vertexCount; + /** Index buffer */ + indexBuffer = null; + /** Buffer-valued attributes */ + bufferAttributes = {}; + /** Constant-valued attributes */ + constantAttributes = {}; + /** Bindings (textures, samplers, uniform buffers) */ + bindings = {}; + /** + * VertexArray + * @note not implemented: if bufferLayout is updated, vertex array has to be rebuilt! + * @todo - allow application to define multiple vertex arrays? + * */ + vertexArray; + /** TransformFeedback, WebGL 2 only. */ + transformFeedback = null; + /** The underlying GPU "program". @note May be recreated if parameters change */ + pipeline; + /** ShaderInputs instance */ + // @ts-expect-error Assigned in function called by constructor + shaderInputs; + material = null; + // @ts-expect-error Assigned in function called by constructor + _uniformStore; + _attributeInfos = {}; + _gpuGeometry = null; + props; + _pipelineNeedsUpdate = "newly created"; + _needsRedraw = "initializing"; + _destroyed = false; + /** "Time" of last draw. Monotonically increasing timestamp */ + _lastDrawTimestamp = -1; + _bindingTable = []; + get [Symbol.toStringTag]() { + return "Model"; + } + toString() { + return `Model(${this.id})`; + } + constructor(device, props) { + this.props = { ..._Model.defaultProps, ...props }; + props = this.props; + this.id = props.id || uid2("model"); + this.device = device; + Object.assign(this.userData, props.userData); + this.material = props.material || null; + const moduleMap = Object.fromEntries(this.props.modules?.map((module) => [module.name, module]) || []); + const shaderInputs = props.shaderInputs || new ShaderInputs(moduleMap, { disableWarnings: this.props.disableWarnings }); + this.setShaderInputs(shaderInputs); + const platformInfo = getPlatformInfo(device); + const modules = ( + // @ts-ignore shaderInputs is assigned in setShaderInputs above. + (this.props.modules?.length > 0 ? this.props.modules : this.shaderInputs?.getModules()) || [] + ); + this.props.shaderLayout = mergeShaderModuleBindingsIntoLayout(this.props.shaderLayout, modules) || null; + const isWebGPU = this.device.type === "webgpu"; + if (isWebGPU && this.props.source) { + const { source: source3, getUniforms: getUniforms3, bindingTable } = this.props.shaderAssembler.assembleWGSLShader({ + platformInfo, + ...this.props, + modules + }); + this.source = source3; + this._getModuleUniforms = getUniforms3; + this._bindingTable = bindingTable; + const inferredShaderLayout = device.getShaderLayout?.(this.source); + this.props.shaderLayout = mergeShaderModuleBindingsIntoLayout(this.props.shaderLayout || inferredShaderLayout || null, modules) || null; + } else { + const { vs: vs7, fs: fs5, getUniforms: getUniforms3 } = this.props.shaderAssembler.assembleGLSLShaderPair({ + platformInfo, + ...this.props, + modules + }); + this.vs = vs7; + this.fs = fs5; + this._getModuleUniforms = getUniforms3; + this._bindingTable = []; + } + this.vertexCount = this.props.vertexCount; + this.instanceCount = this.props.instanceCount; + this.topology = this.props.topology; + this.bufferLayout = this.props.bufferLayout; + this.parameters = this.props.parameters; + if (props.geometry) { + this.setGeometry(props.geometry); + } + this.pipelineFactory = props.pipelineFactory || PipelineFactory.getDefaultPipelineFactory(this.device); + this.shaderFactory = props.shaderFactory || ShaderFactory.getDefaultShaderFactory(this.device); + this.pipeline = this._updatePipeline(); + this.vertexArray = device.createVertexArray({ + shaderLayout: this.pipeline.shaderLayout, + bufferLayout: this.pipeline.bufferLayout + }); + if (this._gpuGeometry) { + this._setGeometryAttributes(this._gpuGeometry); + } + if ("isInstanced" in props) { + this.isInstanced = props.isInstanced; + } + if (props.instanceCount) { + this.setInstanceCount(props.instanceCount); + } + if (props.vertexCount) { + this.setVertexCount(props.vertexCount); + } + if (props.indexBuffer) { + this.setIndexBuffer(props.indexBuffer); + } + if (props.attributes) { + this.setAttributes(props.attributes); + } + if (props.constantAttributes) { + this.setConstantAttributes(props.constantAttributes); + } + if (props.bindings) { + this.setBindings(props.bindings); + } + if (props.transformFeedback) { + this.transformFeedback = props.transformFeedback; + } + } + destroy() { + if (!this._destroyed) { + this.pipelineFactory.release(this.pipeline); + this.shaderFactory.release(this.pipeline.vs); + if (this.pipeline.fs && this.pipeline.fs !== this.pipeline.vs) { + this.shaderFactory.release(this.pipeline.fs); + } + this._uniformStore.destroy(); + this._gpuGeometry?.destroy(); + this._destroyed = true; + } + } + // Draw call + /** Query redraw status. Clears the status. */ + needsRedraw() { + if (this._getBindingsUpdateTimestamp() > this._lastDrawTimestamp) { + this.setNeedsRedraw("contents of bound textures or buffers updated"); + } + const needsRedraw = this._needsRedraw; + this._needsRedraw = false; + return needsRedraw; + } + /** Mark the model as needing a redraw */ + setNeedsRedraw(reason) { + this._needsRedraw ||= reason; + } + /** Returns WGSL binding debug rows for the assembled shader. Returns an empty array for GLSL models. */ + getBindingDebugTable() { + return this._bindingTable; + } + /** Update uniforms and pipeline state prior to drawing. */ + predraw() { + this.updateShaderInputs(); + this.pipeline = this._updatePipeline(); + } + /** + * Issue one draw call. + * @param renderPass - render pass to draw into + * @returns `true` if the draw call was executed, `false` if resources were not ready. + */ + draw(renderPass) { + const loadingBinding = this._areBindingsLoading(); + if (loadingBinding) { + log2.info(LOG_DRAW_PRIORITY, `>>> DRAWING ABORTED ${this.id}: ${loadingBinding} not loaded`)(); + return false; + } + try { + renderPass.pushDebugGroup(`${this}.predraw(${renderPass})`); + this.predraw(); + } finally { + renderPass.popDebugGroup(); + } + let drawSuccess; + let pipelineErrored = this.pipeline.isErrored; + try { + renderPass.pushDebugGroup(`${this}.draw(${renderPass})`); + this._logDrawCallStart(); + this.pipeline = this._updatePipeline(); + pipelineErrored = this.pipeline.isErrored; + if (pipelineErrored) { + log2.info(LOG_DRAW_PRIORITY, `>>> DRAWING ABORTED ${this.id}: ${PIPELINE_INITIALIZATION_FAILED}`)(); + drawSuccess = false; + } else { + const syncBindings = this._getBindings(); + const syncBindGroups = this._getBindGroups(); + const { indexBuffer } = this.vertexArray; + const indexCount = indexBuffer ? indexBuffer.byteLength / (indexBuffer.indexType === "uint32" ? 4 : 2) : void 0; + drawSuccess = this.pipeline.draw({ + renderPass, + vertexArray: this.vertexArray, + isInstanced: this.isInstanced, + vertexCount: this.vertexCount, + instanceCount: this.instanceCount, + indexCount, + transformFeedback: this.transformFeedback || void 0, + // Pipelines may be shared across models when caching is enabled, so bindings + // and WebGL uniforms must be supplied on every draw instead of being stored + // on the pipeline instance. + bindings: syncBindings, + bindGroups: syncBindGroups, + _bindGroupCacheKeys: this._getBindGroupCacheKeys(), + uniforms: this.props.uniforms, + // WebGL shares underlying cached pipelines even for models that have different parameters and topology, + // so we must provide our unique parameters to each draw + // (In WebGPU most parameters are encoded in the pipeline and cannot be changed per draw call) + parameters: this.parameters, + topology: this.topology + }); + } + } finally { + renderPass.popDebugGroup(); + this._logDrawCallEnd(); + } + this._logFramebuffer(renderPass); + if (drawSuccess) { + this._lastDrawTimestamp = this.device.timestamp; + this._needsRedraw = false; + } else if (pipelineErrored) { + this._needsRedraw = PIPELINE_INITIALIZATION_FAILED; + } else { + this._needsRedraw = "waiting for resource initialization"; + } + return drawSuccess; + } + // Update fixed fields (can trigger pipeline rebuild) + /** + * Updates the optional geometry + * Geometry, set topology and bufferLayout + * @note Can trigger a pipeline rebuild / pipeline cache fetch on WebGPU + */ + setGeometry(geometry) { + this._gpuGeometry?.destroy(); + const gpuGeometry = geometry && makeGPUGeometry(this.device, geometry); + if (gpuGeometry) { + this.setTopology(gpuGeometry.topology || "triangle-list"); + const bufferLayoutHelper = new BufferLayoutHelper(this.bufferLayout); + this.bufferLayout = bufferLayoutHelper.mergeBufferLayouts(gpuGeometry.bufferLayout, this.bufferLayout); + if (this.vertexArray) { + this._setGeometryAttributes(gpuGeometry); + } + } + this._gpuGeometry = gpuGeometry; + } + /** + * Updates the primitive topology ('triangle-list', 'triangle-strip' etc). + * @note Triggers a pipeline rebuild / pipeline cache fetch on WebGPU + */ + setTopology(topology) { + if (topology !== this.topology) { + this.topology = topology; + this._setPipelineNeedsUpdate("topology"); + } + } + /** + * Updates the buffer layout. + * @note Triggers a pipeline rebuild / pipeline cache fetch + */ + setBufferLayout(bufferLayout) { + const bufferLayoutHelper = new BufferLayoutHelper(this.bufferLayout); + this.bufferLayout = this._gpuGeometry ? bufferLayoutHelper.mergeBufferLayouts(bufferLayout, this._gpuGeometry.bufferLayout) : bufferLayout; + this._setPipelineNeedsUpdate("bufferLayout"); + this.pipeline = this._updatePipeline(); + this.vertexArray = this.device.createVertexArray({ + shaderLayout: this.pipeline.shaderLayout, + bufferLayout: this.pipeline.bufferLayout + }); + if (this._gpuGeometry) { + this._setGeometryAttributes(this._gpuGeometry); + } + } + /** + * Set GPU parameters. + * @note Can trigger a pipeline rebuild / pipeline cache fetch. + * @param parameters + */ + setParameters(parameters) { + if (!deepEqual(parameters, this.parameters, 2)) { + this.parameters = parameters; + this._setPipelineNeedsUpdate("parameters"); + } + } + // Update dynamic fields + /** + * Updates the instance count (used in draw calls) + * @note Any attributes with stepMode=instance need to be at least this big + */ + setInstanceCount(instanceCount) { + this.instanceCount = instanceCount; + if (this.isInstanced === void 0 && instanceCount > 0) { + this.isInstanced = true; + } + this.setNeedsRedraw("instanceCount"); + } + /** + * Updates the vertex count (used in draw calls) + * @note Any attributes with stepMode=vertex need to be at least this big + */ + setVertexCount(vertexCount) { + this.vertexCount = vertexCount; + this.setNeedsRedraw("vertexCount"); + } + /** Set the shader inputs */ + setShaderInputs(shaderInputs) { + this.shaderInputs = shaderInputs; + this._uniformStore = new UniformStore(this.device, this.shaderInputs.modules); + for (const [moduleName, module] of Object.entries(this.shaderInputs.modules)) { + if (shaderModuleHasUniforms(module) && !this.material?.ownsModule(moduleName)) { + const uniformBuffer = this._uniformStore.getManagedUniformBuffer(moduleName); + this.bindings[`${moduleName}Uniforms`] = uniformBuffer; + } + } + this.setNeedsRedraw("shaderInputs"); + } + setMaterial(material) { + this.material = material; + this.setNeedsRedraw("material"); + } + /** Update uniform buffers from the model's shader inputs */ + updateShaderInputs() { + this._uniformStore.setUniforms(this.shaderInputs.getUniformValues()); + this.setBindings(this._getNonMaterialBindings(this.shaderInputs.getBindingValues())); + this.setNeedsRedraw("shaderInputs"); + } + /** + * Sets bindings (textures, samplers, uniform buffers) + */ + setBindings(bindings) { + Object.assign(this.bindings, bindings); + this.setNeedsRedraw("bindings"); + } + /** + * Updates optional transform feedback. WebGL only. + */ + setTransformFeedback(transformFeedback) { + this.transformFeedback = transformFeedback; + this.setNeedsRedraw("transformFeedback"); + } + /** + * Sets the index buffer + * @todo - how to unset it if we change geometry? + */ + setIndexBuffer(indexBuffer) { + this.vertexArray.setIndexBuffer(indexBuffer); + this.setNeedsRedraw("indexBuffer"); + } + /** + * Sets attributes (buffers) + * @note Overrides any attributes previously set with the same name + */ + setAttributes(buffers, options) { + const disableWarnings = options?.disableWarnings ?? this.props.disableWarnings; + if (buffers["indices"]) { + log2.warn(`Model:${this.id} setAttributes() - indexBuffer should be set using setIndexBuffer()`)(); + } + this.bufferLayout = sortedBufferLayoutByShaderSourceLocations(this.pipeline.shaderLayout, this.bufferLayout); + const bufferLayoutHelper = new BufferLayoutHelper(this.bufferLayout); + for (const [bufferName, buffer] of Object.entries(buffers)) { + const bufferLayout = bufferLayoutHelper.getBufferLayout(bufferName); + if (!bufferLayout) { + if (!disableWarnings) { + log2.warn(`Model(${this.id}): Missing layout for buffer "${bufferName}".`)(); + } + continue; + } + const attributeNames = bufferLayoutHelper.getAttributeNamesForBuffer(bufferLayout); + let set5 = false; + for (const attributeName of attributeNames) { + const attributeInfo = this._attributeInfos[attributeName]; + if (attributeInfo) { + const location = this.device.type === "webgpu" ? bufferLayoutHelper.getBufferIndex(attributeInfo.bufferName) : attributeInfo.location; + this.vertexArray.setBuffer(location, buffer); + set5 = true; + } + } + if (!set5 && !disableWarnings) { + log2.warn(`Model(${this.id}): Ignoring buffer "${buffer.id}" for unknown attribute "${bufferName}"`)(); + } + } + this.setNeedsRedraw("attributes"); + } + /** + * Sets constant attributes + * @note Overrides any attributes previously set with the same name + * Constant attributes are only supported in WebGL, not in WebGPU + * Any attribute that is disabled in the current vertex array object + * is read from the context's global constant value for that attribute location. + * @param constantAttributes + */ + setConstantAttributes(attributes, options) { + for (const [attributeName, value] of Object.entries(attributes)) { + const attributeInfo = this._attributeInfos[attributeName]; + if (attributeInfo) { + this.vertexArray.setConstantWebGL(attributeInfo.location, value); + } else if (!(options?.disableWarnings ?? this.props.disableWarnings)) { + log2.warn(`Model "${this.id}: Ignoring constant supplied for unknown attribute "${attributeName}"`)(); + } + } + this.setNeedsRedraw("constants"); + } + // INTERNAL METHODS + /** Check that bindings are loaded. Returns id of first binding that is still loading. */ + _areBindingsLoading() { + for (const binding of Object.values(this.bindings)) { + if (binding instanceof DynamicTexture && !binding.isReady) { + return binding.id; + } + } + for (const binding of Object.values(this.material?.bindings || {})) { + if (binding instanceof DynamicTexture && !binding.isReady) { + return binding.id; + } + } + return false; + } + /** Extracts texture view from loaded async textures. Returns null if any textures have not yet been loaded. */ + _getBindings() { + const validBindings = {}; + for (const [name2, binding] of Object.entries(this.bindings)) { + if (binding instanceof DynamicTexture) { + if (binding.isReady) { + validBindings[name2] = binding.texture; + } + } else { + validBindings[name2] = binding; + } + } + return validBindings; + } + _getBindGroups() { + const shaderLayout = this.pipeline?.shaderLayout || this.props.shaderLayout || { bindings: [] }; + const bindGroups = shaderLayout.bindings.length ? normalizeBindingsByGroup(shaderLayout, this._getBindings()) : { 0: this._getBindings() }; + if (!this.material) { + return bindGroups; + } + for (const [groupKey, groupBindings] of Object.entries(this.material.getBindingsByGroup())) { + const group2 = Number(groupKey); + bindGroups[group2] = { + ...bindGroups[group2] || {}, + ...groupBindings + }; + } + return bindGroups; + } + _getBindGroupCacheKeys() { + const bindGroupCacheKey = this.material?.getBindGroupCacheKey(3); + return bindGroupCacheKey ? { 3: bindGroupCacheKey } : {}; + } + /** Get the timestamp of the latest updated bound GPU memory resource (buffer/texture). */ + _getBindingsUpdateTimestamp() { + let timestamp = 0; + for (const binding of Object.values(this.bindings)) { + if (binding instanceof TextureView) { + timestamp = Math.max(timestamp, binding.texture.updateTimestamp); + } else if (binding instanceof Buffer2 || binding instanceof Texture) { + timestamp = Math.max(timestamp, binding.updateTimestamp); + } else if (binding instanceof DynamicTexture) { + timestamp = binding.texture ? Math.max(timestamp, binding.texture.updateTimestamp) : ( + // The texture will become available in the future + Infinity + ); + } else if (!(binding instanceof Sampler)) { + timestamp = Math.max(timestamp, binding.buffer.updateTimestamp); + } + } + return Math.max(timestamp, this.material?.getBindingsUpdateTimestamp() || 0); + } + /** + * Updates the optional geometry attributes + * Geometry, sets several attributes, indexBuffer, and also vertex count + * @note Can trigger a pipeline rebuild / pipeline cache fetch on WebGPU + */ + _setGeometryAttributes(gpuGeometry) { + const attributes = { ...gpuGeometry.attributes }; + for (const [attributeName] of Object.entries(attributes)) { + if (!this.pipeline.shaderLayout.attributes.find((layout) => layout.name === attributeName) && attributeName !== "positions") { + delete attributes[attributeName]; + } + } + this.vertexCount = gpuGeometry.vertexCount; + this.setIndexBuffer(gpuGeometry.indices || null); + this.setAttributes(gpuGeometry.attributes, { disableWarnings: true }); + this.setAttributes(attributes, { disableWarnings: this.props.disableWarnings }); + this.setNeedsRedraw("geometry attributes"); + } + /** Mark pipeline as needing update */ + _setPipelineNeedsUpdate(reason) { + this._pipelineNeedsUpdate ||= reason; + this.setNeedsRedraw(reason); + } + /** Update pipeline if needed */ + _updatePipeline() { + if (this._pipelineNeedsUpdate) { + let prevShaderVs = null; + let prevShaderFs = null; + if (this.pipeline) { + log2.log(1, `Model ${this.id}: Recreating pipeline because "${this._pipelineNeedsUpdate}".`)(); + prevShaderVs = this.pipeline.vs; + prevShaderFs = this.pipeline.fs; + } + this._pipelineNeedsUpdate = false; + const vs7 = this.shaderFactory.createShader({ + id: `${this.id}-vertex`, + stage: "vertex", + source: this.source || this.vs, + debugShaders: this.props.debugShaders + }); + let fs5 = null; + if (this.source) { + fs5 = vs7; + } else if (this.fs) { + fs5 = this.shaderFactory.createShader({ + id: `${this.id}-fragment`, + stage: "fragment", + source: this.source || this.fs, + debugShaders: this.props.debugShaders + }); + } + this.pipeline = this.pipelineFactory.createRenderPipeline({ + ...this.props, + bindings: void 0, + bufferLayout: this.bufferLayout, + topology: this.topology, + parameters: this.parameters, + bindGroups: this._getBindGroups(), + vs: vs7, + fs: fs5 + }); + this._attributeInfos = getAttributeInfosFromLayouts(this.pipeline.shaderLayout, this.bufferLayout); + if (prevShaderVs) + this.shaderFactory.release(prevShaderVs); + if (prevShaderFs && prevShaderFs !== prevShaderVs) { + this.shaderFactory.release(prevShaderFs); + } + } + return this.pipeline; + } + /** Throttle draw call logging */ + _lastLogTime = 0; + _logOpen = false; + _logDrawCallStart() { + const logDrawTimeout = log2.level > 3 ? 0 : LOG_DRAW_TIMEOUT; + if (log2.level < 2 || Date.now() - this._lastLogTime < logDrawTimeout) { + return; + } + this._lastLogTime = Date.now(); + this._logOpen = true; + log2.group(LOG_DRAW_PRIORITY, `>>> DRAWING MODEL ${this.id}`, { collapsed: log2.level <= 2 })(); + } + _logDrawCallEnd() { + if (this._logOpen) { + const shaderLayoutTable = getDebugTableForShaderLayout(this.pipeline.shaderLayout, this.id); + log2.table(LOG_DRAW_PRIORITY, shaderLayoutTable)(); + const uniformTable = this.shaderInputs.getDebugTable(); + log2.table(LOG_DRAW_PRIORITY, uniformTable)(); + const attributeTable = this._getAttributeDebugTable(); + log2.table(LOG_DRAW_PRIORITY, this._attributeInfos)(); + log2.table(LOG_DRAW_PRIORITY, attributeTable)(); + log2.groupEnd(LOG_DRAW_PRIORITY)(); + this._logOpen = false; + } + } + _drawCount = 0; + _logFramebuffer(renderPass) { + const debugFramebuffers = this.device.props.debugFramebuffers; + this._drawCount++; + if (!debugFramebuffers) { + return; + } + const framebuffer = renderPass.props.framebuffer; + debugFramebuffer(renderPass, framebuffer, { + id: framebuffer?.id || `${this.id}-framebuffer`, + minimap: true + }); + } + _getAttributeDebugTable() { + const table = {}; + for (const [name2, attributeInfo] of Object.entries(this._attributeInfos)) { + const values = this.vertexArray.attributes[attributeInfo.location]; + table[attributeInfo.location] = { + name: name2, + type: attributeInfo.shaderType, + values: values ? this._getBufferOrConstantValues(values, attributeInfo.bufferDataType) : "null" + }; + } + if (this.vertexArray.indexBuffer) { + const { indexBuffer } = this.vertexArray; + const values = indexBuffer.indexType === "uint32" ? new Uint32Array(indexBuffer.debugData) : new Uint16Array(indexBuffer.debugData); + table["indices"] = { + name: "indices", + type: indexBuffer.indexType, + values: values.toString() + }; + } + return table; + } + // TODO - fix typing of luma data types + _getBufferOrConstantValues(attribute, dataType) { + const TypedArrayConstructor = dataTypeDecoder.getTypedArrayConstructor(dataType); + const typedArray = attribute instanceof Buffer2 ? new TypedArrayConstructor(attribute.debugData) : attribute; + return typedArray.toString(); + } + _getNonMaterialBindings(bindings) { + if (!this.material) { + return bindings; + } + const filteredBindings = {}; + for (const [name2, binding] of Object.entries(bindings)) { + if (!this.material.ownsBinding(name2)) { + filteredBindings[name2] = binding; + } + } + return filteredBindings; + } + }; + function getPlatformInfo(device) { + return { + type: device.type, + shaderLanguage: device.info.shadingLanguage, + shaderLanguageVersion: device.info.shadingLanguageVersion, + gpu: device.info.gpu, + // HACK - we pretend that the DeviceFeatures is a Set, it has a similar API + features: device.features + }; + } + + // node_modules/@luma.gl/engine/dist/compute/buffer-transform.js + init_dist4(); + var BufferTransform = class _BufferTransform { + device; + model; + transformFeedback; + static defaultProps = { + ...Model.defaultProps, + outputs: void 0, + feedbackBuffers: void 0 + }; + static isSupported(device) { + return device?.info?.type === "webgl"; + } + constructor(device, props = _BufferTransform.defaultProps) { + if (!_BufferTransform.isSupported(device)) { + throw new Error("BufferTransform not yet implemented on WebGPU"); + } + this.device = device; + this.model = new Model(this.device, { + id: props.id || "buffer-transform-model", + fs: props.fs || getPassthroughFS(), + topology: props.topology || "point-list", + varyings: props.outputs || props.varyings, + ...props + }); + this.transformFeedback = this.device.createTransformFeedback({ + layout: this.model.pipeline.shaderLayout, + // @ts-expect-error TODO + buffers: props.feedbackBuffers + }); + this.model.setTransformFeedback(this.transformFeedback); + Object.seal(this); + } + /** Destroy owned resources. */ + destroy() { + if (this.model) { + this.model.destroy(); + } + } + /** @deprecated Use {@link destroy}. */ + delete() { + this.destroy(); + } + /** Run one transform loop. */ + run(options) { + if (options?.inputBuffers) { + this.model.setAttributes(options.inputBuffers); + } + if (options?.outputBuffers) { + this.transformFeedback.setBuffers(options.outputBuffers); + } + const renderPass = this.device.beginRenderPass(options); + this.model.draw(renderPass); + renderPass.end(); + } + // DEPRECATED METHODS + /** @deprecated App knows what buffers it is passing in - Returns the {@link Buffer} or {@link BufferRange} for given varying name. */ + getBuffer(varyingName) { + return this.transformFeedback.getBuffer(varyingName); + } + /** @deprecated App knows what buffers it is passing in - Reads the {@link Buffer} or {@link BufferRange} for given varying name. */ + readAsync(varyingName) { + const result = this.getBuffer(varyingName); + if (!result) { + throw new Error("BufferTransform#getBuffer"); + } + if (result instanceof Buffer2) { + return result.readAsync(); + } + const { buffer, byteOffset = 0, byteLength = buffer.byteLength } = result; + return buffer.readAsync(byteOffset, byteLength); + } + }; + + // node_modules/@luma.gl/engine/dist/geometry/geometry.js + var Geometry = class { + id; + /** Determines how vertices are read from the 'vertex' attributes */ + topology; + vertexCount; + indices; + attributes; + userData = {}; + constructor(props) { + const { attributes = {}, indices = null, vertexCount = null } = props; + this.id = props.id || uid2("geometry"); + this.topology = props.topology; + if (indices) { + this.indices = ArrayBuffer.isView(indices) ? { value: indices, size: 1 } : indices; + } + this.attributes = {}; + for (const [attributeName, attributeValue] of Object.entries(attributes)) { + const attribute = ArrayBuffer.isView(attributeValue) ? { value: attributeValue } : attributeValue; + if (!ArrayBuffer.isView(attribute.value)) { + throw new Error(`${this._print(attributeName)}: must be typed array or object with value as typed array`); + } + if ((attributeName === "POSITION" || attributeName === "positions") && !attribute.size) { + attribute.size = 3; + } + if (attributeName === "indices") { + if (this.indices) { + throw new Error("Multiple indices detected"); + } + this.indices = attribute; + } else { + this.attributes[attributeName] = attribute; + } + } + if (this.indices && this.indices["isIndexed"] !== void 0) { + this.indices = Object.assign({}, this.indices); + delete this.indices["isIndexed"]; + } + this.vertexCount = vertexCount || this._calculateVertexCount(this.attributes, this.indices); + } + getVertexCount() { + return this.vertexCount; + } + /** + * Return an object with all attributes plus indices added as a field. + * TODO Geometry types are a mess + */ + getAttributes() { + return this.indices ? { indices: this.indices, ...this.attributes } : this.attributes; + } + // PRIVATE + _print(attributeName) { + return `Geometry ${this.id} attribute ${attributeName}`; + } + /** + * GeometryAttribute + * value: typed array + * type: indices, vertices, uvs + * size: elements per vertex + * target: WebGL buffer type (string or constant) + * + * @param attributes + * @param indices + * @returns + */ + _setAttributes(attributes, indices) { + return this; + } + _calculateVertexCount(attributes, indices) { + if (indices) { + return indices.value.length; + } + let vertexCount = Infinity; + for (const attribute of Object.values(attributes)) { + const { value, size, constant } = attribute; + if (!constant && value && size !== void 0 && size >= 1) { + vertexCount = Math.min(vertexCount, value.length / size); + } + } + return vertexCount; + } + }; + + // node_modules/@deck.gl/core/dist/passes/pick-layers-pass.js + var PICKING_BLENDING = { + blendColorOperation: "add", + blendColorSrcFactor: "one", + blendColorDstFactor: "zero", + blendAlphaOperation: "add", + blendAlphaSrcFactor: "constant", + blendAlphaDstFactor: "zero" + }; + var PickLayersPass = class extends LayersPass { + constructor() { + super(...arguments); + this._colorEncoderState = null; + } + render(props) { + if ("pickingFBO" in props) { + return this._drawPickingBuffer(props); + } + const stats = super._render(props); + return { decodePickingColor: null, stats }; + } + // Private + // Draws list of layers and viewports into the picking buffer + // Note: does not sample the buffer, that has to be done by the caller + _drawPickingBuffer({ layers, layerFilter, views, viewports, onViewportActive, pickingFBO, deviceRect: { x, y, width, height }, cullRect, effects, pass = "picking", pickZ, shaderModuleProps, clearColor }) { + this.pickZ = pickZ; + const colorEncoderState = this._resetColorEncoder(pickZ); + const scissorRect = [x, y, width, height]; + const renderStatus = super._render({ + target: pickingFBO, + layers, + layerFilter, + views, + viewports, + onViewportActive, + cullRect, + effects: effects?.filter((e) => e.useInPicking), + pass, + isPicking: true, + shaderModuleProps, + clearColor: clearColor ?? [0, 0, 0, 0], + colorMask: 15, + scissorRect + }); + this._colorEncoderState = null; + const decodePickingColor = colorEncoderState && decodeColor.bind(null, colorEncoderState); + return { decodePickingColor, stats: renderStatus }; + } + shouldDrawLayer(layer) { + const { pickable, operation } = layer.props; + return pickable && operation.includes("draw") || operation.includes("terrain") || operation.includes("mask"); + } + getShaderModuleProps(layer, effects, otherShaderModuleProps) { + return { + picking: { + isActive: 1, + isAttribute: this.pickZ + }, + lighting: { enabled: false } + }; + } + getLayerParameters(layer, layerIndex, viewport) { + const pickParameters = { + ...layer.props.parameters + }; + const { pickable, operation } = layer.props; + if (!this._colorEncoderState) { + pickParameters.blend = false; + } else if (pickable && operation.includes("draw")) { + Object.assign(pickParameters, PICKING_BLENDING); + pickParameters.blend = true; + if (this.device.type === "webgpu") { + pickParameters.blendConstant = encodeColor(this._colorEncoderState, layer, viewport); + } else { + pickParameters.blendColor = encodeColor(this._colorEncoderState, layer, viewport); + } + if (operation.includes("terrain") && layer.state?._hasPickingCover) { + pickParameters.blendAlphaSrcFactor = "one"; + } + } else if (operation.includes("terrain")) { + pickParameters.blend = false; + } + return pickParameters; + } + _resetColorEncoder(pickZ) { + this._colorEncoderState = pickZ ? null : { + byLayer: /* @__PURE__ */ new Map(), + byAlpha: [] + }; + return this._colorEncoderState; + } + }; + function encodeColor(encoded, layer, viewport) { + const { byLayer, byAlpha } = encoded; + let a; + let entry = byLayer.get(layer); + if (entry) { + entry.viewports.push(viewport); + a = entry.a; + } else { + a = byLayer.size + 1; + if (a <= 255) { + entry = { a, layer, viewports: [viewport] }; + byLayer.set(layer, entry); + byAlpha[a] = entry; + } else { + log_default.warn("Too many pickable layers, only picking the first 255")(); + a = 0; + } + } + return [0, 0, 0, a / 255]; + } + function decodeColor(encoded, pickedColor) { + const entry = encoded.byAlpha[pickedColor[3]]; + return entry && { + pickedLayer: entry.layer, + pickedViewports: entry.viewports, + pickedObjectIndex: entry.layer.decodePickingColor(pickedColor) + }; + } + + // node_modules/@deck.gl/core/dist/lifecycle/constants.js + var LIFECYCLE = { + NO_STATE: "Awaiting state", + MATCHED: "Matched. State transferred from previous layer", + INITIALIZED: "Initialized", + AWAITING_GC: "Discarded. Awaiting garbage collection", + AWAITING_FINALIZATION: "No longer matched. Awaiting garbage collection", + FINALIZED: "Finalized! Awaiting garbage collection" + }; + var COMPONENT_SYMBOL = /* @__PURE__ */ Symbol.for("component"); + var PROP_TYPES_SYMBOL = /* @__PURE__ */ Symbol.for("propTypes"); + var DEPRECATED_PROPS_SYMBOL = /* @__PURE__ */ Symbol.for("deprecatedProps"); + var ASYNC_DEFAULTS_SYMBOL = /* @__PURE__ */ Symbol.for("asyncPropDefaults"); + var ASYNC_ORIGINAL_SYMBOL = /* @__PURE__ */ Symbol.for("asyncPropOriginal"); + var ASYNC_RESOLVED_SYMBOL = /* @__PURE__ */ Symbol.for("asyncPropResolved"); + + // node_modules/@deck.gl/core/dist/utils/flatten.js + function flatten(array, filter = () => true) { + if (!Array.isArray(array)) { + return filter(array) ? [array] : []; + } + return flattenArray(array, filter, []); + } + function flattenArray(array, filter, result) { + let index2 = -1; + while (++index2 < array.length) { + const value = array[index2]; + if (Array.isArray(value)) { + flattenArray(value, filter, result); + } else if (filter(value)) { + result.push(value); + } + } + return result; + } + function fillArray({ target: target2, source: source3, start = 0, count: count2 = 1 }) { + const length4 = source3.length; + const total = count2 * length4; + let copied = 0; + for (let i = start; copied < length4; copied++) { + target2[i++] = source3[copied]; + } + while (copied < total) { + if (copied < total - copied) { + target2.copyWithin(start + copied, start, start + copied); + copied *= 2; + } else { + target2.copyWithin(start + copied, start, start + total - copied); + copied = total; + } + } + return target2; + } + + // node_modules/@deck.gl/core/dist/lib/layer-manager.js + init_dist3(); + + // node_modules/@deck.gl/core/dist/lib/resource/resource.js + var Resource2 = class { + constructor(id, data, context) { + this._loadCount = 0; + this._subscribers = /* @__PURE__ */ new Set(); + this.id = id; + this.context = context; + this.setData(data); + } + // consumer: {onChange: Function} + subscribe(consumer) { + this._subscribers.add(consumer); + } + unsubscribe(consumer) { + this._subscribers.delete(consumer); + } + inUse() { + return this._subscribers.size > 0; + } + delete() { + } + getData() { + return this.isLoaded ? this._error ? Promise.reject(this._error) : this._content : this._loader.then(() => this.getData()); + } + setData(data, forceUpdate) { + if (data === this._data && !forceUpdate) { + return; + } + this._data = data; + const loadCount = ++this._loadCount; + let loader = data; + if (typeof data === "string") { + loader = load(data); + } + if (loader instanceof Promise) { + this.isLoaded = false; + this._loader = loader.then((result) => { + if (this._loadCount === loadCount) { + this.isLoaded = true; + this._error = void 0; + this._content = result; + } + }).catch((error) => { + if (this._loadCount === loadCount) { + this.isLoaded = true; + this._error = error || true; + } + }); + } else { + this.isLoaded = true; + this._error = void 0; + this._content = data; + } + for (const subscriber of this._subscribers) { + subscriber.onChange(this.getData()); + } + } + }; + + // node_modules/@deck.gl/core/dist/lib/resource/resource-manager.js + var ResourceManager = class { + constructor(props) { + this.protocol = props.protocol || "resource://"; + this._context = { + device: props.device, + // @ts-expect-error + gl: props.device?.gl, + resourceManager: this + }; + this._resources = {}; + this._consumers = {}; + this._pruneRequest = null; + } + contains(resourceId) { + if (resourceId.startsWith(this.protocol)) { + return true; + } + return resourceId in this._resources; + } + add({ resourceId, data, forceUpdate = false, persistent = true }) { + let res = this._resources[resourceId]; + if (res) { + res.setData(data, forceUpdate); + } else { + res = new Resource2(resourceId, data, this._context); + this._resources[resourceId] = res; + } + res.persistent = persistent; + } + remove(resourceId) { + const res = this._resources[resourceId]; + if (res) { + res.delete(); + delete this._resources[resourceId]; + } + } + unsubscribe({ consumerId }) { + const consumer = this._consumers[consumerId]; + if (consumer) { + for (const requestId in consumer) { + const request = consumer[requestId]; + const resource = this._resources[request.resourceId]; + if (resource) { + resource.unsubscribe(request); + } + } + delete this._consumers[consumerId]; + this.prune(); + } + } + subscribe({ resourceId, onChange, consumerId, requestId = "default" }) { + const { _resources: resources, protocol } = this; + if (resourceId.startsWith(protocol)) { + resourceId = resourceId.replace(protocol, ""); + if (!resources[resourceId]) { + this.add({ resourceId, data: null, persistent: false }); + } + } + const res = resources[resourceId]; + this._track(consumerId, requestId, res, onChange); + if (res) { + return res.getData(); + } + return void 0; + } + prune() { + if (!this._pruneRequest) { + this._pruneRequest = setTimeout(() => this._prune(), 0); + } + } + finalize() { + for (const key in this._resources) { + this._resources[key].delete(); + } + } + _track(consumerId, requestId, resource, onChange) { + const consumers = this._consumers; + const consumer = consumers[consumerId] = consumers[consumerId] || {}; + let request = consumer[requestId]; + const oldResource = request && request.resourceId && this._resources[request.resourceId]; + if (oldResource) { + oldResource.unsubscribe(request); + this.prune(); + } + if (resource) { + if (request) { + request.onChange = onChange; + request.resourceId = resource.id; + } else { + request = { + onChange, + resourceId: resource.id + }; + } + consumer[requestId] = request; + resource.subscribe(request); + } + } + _prune() { + this._pruneRequest = null; + for (const key of Object.keys(this._resources)) { + const res = this._resources[key]; + if (!res.persistent && !res.inUse()) { + res.delete(); + delete this._resources[key]; + } + } + } + }; + + // node_modules/@deck.gl/core/dist/lib/layer-manager.js + var TRACE_SET_LAYERS = "layerManager.setLayers"; + var TRACE_ACTIVATE_VIEWPORT = "layerManager.activateViewport"; + var LayerManager = class { + /** + * @param device + * @param param1 + */ + // eslint-disable-next-line + constructor(device, props) { + this._lastRenderedLayers = []; + this._needsRedraw = false; + this._needsUpdate = false; + this._nextLayers = null; + this._debug = false; + this._defaultShaderModulesChanged = false; + this.activateViewport = (viewport2) => { + debug(TRACE_ACTIVATE_VIEWPORT, this, viewport2); + if (viewport2) { + this.context.viewport = viewport2; + } + }; + const { deck, stats, viewport, timeline } = props || {}; + this.layers = []; + this.resourceManager = new ResourceManager({ device, protocol: "deck://" }); + this.context = { + mousePosition: null, + userData: {}, + layerManager: this, + device, + // @ts-expect-error + gl: device?.gl, + deck, + shaderAssembler: getShaderAssembler(device?.info?.shadingLanguage || "glsl"), + defaultShaderModules: [layerUniforms], + renderPass: void 0, + stats: stats || new Stats({ id: "deck.gl" }), + // Make sure context.viewport is not empty on the first layer initialization + viewport: viewport || new viewport_default({ id: "DEFAULT-INITIAL-VIEWPORT" }), + // Current viewport, exposed to layers for project* function + timeline: timeline || new Timeline(), + resourceManager: this.resourceManager, + onError: void 0 + }; + Object.seal(this); + } + /** Method to call when the layer manager is not needed anymore. */ + finalize() { + this.resourceManager.finalize(); + for (const layer of this.layers) { + this._finalizeLayer(layer); + } + } + /** Check if a redraw is needed */ + needsRedraw(opts = { clearRedrawFlags: false }) { + let redraw = this._needsRedraw; + if (opts.clearRedrawFlags) { + this._needsRedraw = false; + } + for (const layer of this.layers) { + const layerNeedsRedraw = layer.getNeedsRedraw(opts); + redraw = redraw || layerNeedsRedraw; + } + return redraw; + } + /** Check if a deep update of all layers is needed */ + needsUpdate() { + if (this._nextLayers && this._nextLayers !== this._lastRenderedLayers) { + return "layers changed"; + } + if (this._defaultShaderModulesChanged) { + return "shader modules changed"; + } + return this._needsUpdate; + } + /** Layers will be redrawn (in next animation frame) */ + setNeedsRedraw(reason) { + this._needsRedraw = this._needsRedraw || reason; + } + /** Layers will be updated deeply (in next animation frame) + Potentially regenerating attributes and sub layers */ + setNeedsUpdate(reason) { + this._needsUpdate = this._needsUpdate || reason; + } + /** Gets a list of currently rendered layers. Optionally filter by id. */ + getLayers({ layerIds } = {}) { + return layerIds ? this.layers.filter((layer) => layerIds.find((layerId) => layer.id.indexOf(layerId) === 0)) : this.layers; + } + /** Set props needed for layer rendering and picking. */ + setProps(props) { + if ("debug" in props) { + this._debug = props.debug; + } + if ("userData" in props) { + this.context.userData = props.userData; + } + if ("layers" in props) { + this._nextLayers = props.layers; + } + if ("onError" in props) { + this.context.onError = props.onError; + } + } + /** Supply a new layer list, initiating sublayer generation and layer matching */ + setLayers(newLayers, reason) { + debug(TRACE_SET_LAYERS, this, reason, newLayers); + this._lastRenderedLayers = newLayers; + const flatLayers = flatten(newLayers, Boolean); + for (const layer of flatLayers) { + layer.context = this.context; + } + this._updateLayers(this.layers, flatLayers); + } + /** Update layers from last cycle if `setNeedsUpdate()` has been called */ + updateLayers() { + const reason = this.needsUpdate(); + if (reason) { + this.setNeedsRedraw(`updating layers: ${reason}`); + this.setLayers(this._nextLayers || this._lastRenderedLayers, reason); + } + this._nextLayers = null; + } + /** Register a default shader module */ + addDefaultShaderModule(module) { + const { defaultShaderModules } = this.context; + if (!defaultShaderModules.find((m) => m.name === module.name)) { + defaultShaderModules.push(module); + this._defaultShaderModulesChanged = true; + } + } + /** Deregister a default shader module */ + removeDefaultShaderModule(module) { + const { defaultShaderModules } = this.context; + const i = defaultShaderModules.findIndex((m) => m.name === module.name); + if (i >= 0) { + defaultShaderModules.splice(i, 1); + this._defaultShaderModulesChanged = true; + } + } + _handleError(stage, error, layer) { + layer.raiseError(error, `${stage} of ${layer}`); + } + // TODO - mark layers with exceptions as bad and remove from rendering cycle? + /** Match all layers, checking for caught errors + to avoid having an exception in one layer disrupt other layers */ + _updateLayers(oldLayers, newLayers) { + const oldLayerMap = {}; + for (const oldLayer of oldLayers) { + if (oldLayerMap[oldLayer.id]) { + log_default.warn(`Multiple old layers with same id ${oldLayer.id}`)(); + } else { + oldLayerMap[oldLayer.id] = oldLayer; + } + } + if (this._defaultShaderModulesChanged) { + for (const layer of oldLayers) { + layer.setNeedsUpdate(); + layer.setChangeFlags({ extensionsChanged: true }); + } + this._defaultShaderModulesChanged = false; + } + const generatedLayers = []; + this._updateSublayersRecursively(newLayers, oldLayerMap, generatedLayers); + this._finalizeOldLayers(oldLayerMap); + let needsUpdate = false; + for (const layer of generatedLayers) { + if (layer.hasUniformTransition()) { + needsUpdate = `Uniform transition in ${layer}`; + break; + } + } + this._needsUpdate = needsUpdate; + this.layers = generatedLayers; + } + /* eslint-disable complexity,max-statements */ + // Note: adds generated layers to `generatedLayers` array parameter + _updateSublayersRecursively(newLayers, oldLayerMap, generatedLayers) { + for (const newLayer of newLayers) { + newLayer.context = this.context; + const oldLayer = oldLayerMap[newLayer.id]; + if (oldLayer === null) { + log_default.warn(`Multiple new layers with same id ${newLayer.id}`)(); + } + oldLayerMap[newLayer.id] = null; + let sublayers = null; + try { + if (this._debug && oldLayer !== newLayer) { + newLayer.validateProps(); + } + if (!oldLayer) { + this._initializeLayer(newLayer); + } else { + this._transferLayerState(oldLayer, newLayer); + this._updateLayer(newLayer); + } + generatedLayers.push(newLayer); + sublayers = newLayer.isComposite ? newLayer.getSubLayers() : null; + } catch (err) { + this._handleError("matching", err, newLayer); + } + if (sublayers) { + this._updateSublayersRecursively(sublayers, oldLayerMap, generatedLayers); + } + } + } + /* eslint-enable complexity,max-statements */ + // Finalize any old layers that were not matched + _finalizeOldLayers(oldLayerMap) { + for (const layerId in oldLayerMap) { + const layer = oldLayerMap[layerId]; + if (layer) { + this._finalizeLayer(layer); + } + } + } + // / EXCEPTION SAFE LAYER ACCESS + /** Safely initializes a single layer, calling layer methods */ + _initializeLayer(layer) { + try { + layer._initialize(); + layer.lifecycle = LIFECYCLE.INITIALIZED; + } catch (err) { + this._handleError("initialization", err, layer); + } + } + /** Transfer state from one layer to a newer version */ + _transferLayerState(oldLayer, newLayer) { + newLayer._transferState(oldLayer); + newLayer.lifecycle = LIFECYCLE.MATCHED; + if (newLayer !== oldLayer) { + oldLayer.lifecycle = LIFECYCLE.AWAITING_GC; + } + } + /** Safely updates a single layer, cleaning all flags */ + _updateLayer(layer) { + try { + layer._update(); + } catch (err) { + this._handleError("update", err, layer); + } + } + /** Safely finalizes a single layer, removing all resources */ + _finalizeLayer(layer) { + this._needsRedraw = this._needsRedraw || `finalized ${layer}`; + layer.lifecycle = LIFECYCLE.AWAITING_FINALIZATION; + try { + layer._finalize(); + layer.lifecycle = LIFECYCLE.FINALIZED; + } catch (err) { + this._handleError("finalization", err, layer); + } + } + }; + + // node_modules/@deck.gl/core/dist/utils/deep-equal.js + function deepEqual2(a, b, depth) { + if (a === b) { + return true; + } + if (!depth || !a || !b) { + return false; + } + if (Array.isArray(a)) { + if (!Array.isArray(b) || a.length !== b.length) { + return false; + } + for (let i = 0; i < a.length; i++) { + if (!deepEqual2(a[i], b[i], depth - 1)) { + return false; + } + } + return true; + } + if (Array.isArray(b)) { + return false; + } + if (typeof a === "object" && typeof b === "object") { + const aKeys = Object.keys(a); + const bKeys = Object.keys(b); + if (aKeys.length !== bKeys.length) { + return false; + } + for (const key of aKeys) { + if (!b.hasOwnProperty(key)) { + return false; + } + if (!deepEqual2(a[key], b[key], depth - 1)) { + return false; + } + } + return true; + } + return false; + } + + // node_modules/@deck.gl/core/dist/lib/view-manager.js + var ViewManager = class { + constructor(props) { + this.views = []; + this.width = 100; + this.height = 100; + this.viewState = {}; + this.controllers = {}; + this.timeline = props.timeline; + this._viewports = []; + this._viewportMap = {}; + this._isUpdating = false; + this._needsRedraw = "First render"; + this._needsUpdate = "Initialize"; + this._eventManager = props.eventManager; + this._eventCallbacks = { + onViewStateChange: props.onViewStateChange, + onInteractionStateChange: props.onInteractionStateChange + }; + this._pickPosition = props.pickPosition; + Object.seal(this); + this.setProps(props); + } + /** Remove all resources and event listeners */ + finalize() { + for (const key in this.controllers) { + const controller = this.controllers[key]; + if (controller) { + controller.finalize(); + } + } + this.controllers = {}; + } + /** Check if a redraw is needed */ + needsRedraw(opts = { clearRedrawFlags: false }) { + const redraw = this._needsRedraw; + if (opts.clearRedrawFlags) { + this._needsRedraw = false; + } + return redraw; + } + /** Mark the manager as dirty. Will rebuild all viewports and update controllers. */ + setNeedsUpdate(reason) { + this._needsUpdate = this._needsUpdate || reason; + this._needsRedraw = this._needsRedraw || reason; + } + /** Checks each viewport for transition updates */ + updateViewStates() { + for (const viewId in this.controllers) { + const controller = this.controllers[viewId]; + if (controller) { + controller.updateTransition(); + } + } + } + /** Get a set of viewports for a given width and height + * TODO - Intention is for deck.gl to autodeduce width and height and drop the need for props + * @param rect (object, optional) - filter the viewports + * + not provided - return all viewports + * + {x, y} - only return viewports that contain this pixel + * + {x, y, width, height} - only return viewports that overlap with this rectangle + */ + getViewports(rect) { + if (rect) { + return this._viewports.filter((viewport) => viewport.containsPixel(rect)); + } + return this._viewports; + } + /** Get a map of all views */ + getViews() { + const viewMap = {}; + this.views.forEach((view) => { + viewMap[view.id] = view; + }); + return viewMap; + } + /** Resolves a viewId string to a View */ + getView(viewId) { + return this.views.find((view) => view.id === viewId); + } + /** Returns the viewState for a specific viewId. Matches the viewState by + 1. view.viewStateId + 2. view.id + 3. root viewState + then applies the view's filter if any */ + getViewState(viewOrViewId) { + const view = typeof viewOrViewId === "string" ? this.getView(viewOrViewId) : viewOrViewId; + const viewState = view && this.viewState[view.getViewStateId()] || this.viewState; + return view ? view.filterViewState(viewState) : viewState; + } + getViewport(viewId) { + return this._viewportMap[viewId]; + } + /** + * Unproject pixel coordinates on screen onto world coordinates, + * (possibly [lon, lat]) on map. + * - [x, y] => [lng, lat] + * - [x, y, z] => [lng, lat, Z] + * @param {Array} xyz - + * @param {Object} opts - options + * @param {Object} opts.topLeft=true - Whether origin is top left + * @return {Array|null} - [lng, lat, Z] or [X, Y, Z] + */ + unproject(xyz, opts) { + const viewports = this.getViewports(); + const pixel = { x: xyz[0], y: xyz[1] }; + for (let i = viewports.length - 1; i >= 0; --i) { + const viewport = viewports[i]; + if (viewport.containsPixel(pixel)) { + const p = xyz.slice(); + p[0] -= viewport.x; + p[1] -= viewport.y; + return viewport.unproject(p, opts); + } + } + return null; + } + /** Update the manager with new Deck props */ + setProps(props) { + if (props.views) { + this._setViews(props.views); + } + if (props.viewState) { + this._setViewState(props.viewState); + } + if ("width" in props || "height" in props) { + this._setSize(props.width, props.height); + } + if ("pickPosition" in props) { + this._pickPosition = props.pickPosition; + } + if (!this._isUpdating) { + this._update(); + } + } + // + // PRIVATE METHODS + // + _update() { + this._isUpdating = true; + if (this._needsUpdate) { + this._needsUpdate = false; + this._rebuildViewports(); + } + if (this._needsUpdate) { + this._needsUpdate = false; + this._rebuildViewports(); + } + this._isUpdating = false; + } + _setSize(width, height) { + if (width !== this.width || height !== this.height) { + this.width = width; + this.height = height; + this.setNeedsUpdate("Size changed"); + } + } + // Update the view descriptor list and set change flag if needed + // Does not actually rebuild the `Viewport`s until `getViewports` is called + _setViews(views) { + views = flatten(views, Boolean); + const viewsChanged = this._diffViews(views, this.views); + if (viewsChanged) { + this.setNeedsUpdate("views changed"); + } + this.views = views; + } + _setViewState(viewState) { + if (viewState) { + const viewStateChanged = !deepEqual2(viewState, this.viewState, 3); + if (viewStateChanged) { + this.setNeedsUpdate("viewState changed"); + } + this.viewState = viewState; + } else { + log_default.warn("missing `viewState` or `initialViewState`")(); + } + } + _createController(view, props) { + const Controller2 = props.type; + const controller = new Controller2({ + timeline: this.timeline, + eventManager: this._eventManager, + // Set an internal callback that calls the prop callback if provided + onViewStateChange: this._eventCallbacks.onViewStateChange, + onStateChange: this._eventCallbacks.onInteractionStateChange, + makeViewport: (viewState) => this.getView(view.id)?.makeViewport({ + viewState, + width: this.width, + height: this.height + }), + pickPosition: this._pickPosition + }); + return controller; + } + _updateController(view, viewState, viewport, controller) { + const controllerProps = view.controller; + if (controllerProps && viewport) { + const resolvedProps = { + ...viewState, + ...controllerProps, + id: view.id, + x: viewport.x, + y: viewport.y, + width: viewport.width, + height: viewport.height + }; + if (!controller || controller.constructor !== controllerProps.type) { + controller = this._createController(view, resolvedProps); + } + if (controller) { + controller.setProps(resolvedProps); + } + return controller; + } + return null; + } + // Rebuilds viewports from descriptors towards a certain window size + _rebuildViewports() { + const { views } = this; + const oldControllers = this.controllers; + this._viewports = []; + this.controllers = {}; + let invalidateControllers = false; + for (let i = views.length; i--; ) { + const view = views[i]; + const viewState = this.getViewState(view); + const viewport = view.makeViewport({ viewState, width: this.width, height: this.height }); + let oldController = oldControllers[view.id]; + const hasController = Boolean(view.controller); + if (hasController && !oldController) { + invalidateControllers = true; + } + if ((invalidateControllers || !hasController) && oldController) { + oldController.finalize(); + oldController = null; + } + this.controllers[view.id] = this._updateController(view, viewState, viewport, oldController); + if (viewport) { + this._viewports.unshift(viewport); + } + } + for (const id in oldControllers) { + const oldController = oldControllers[id]; + if (oldController && !this.controllers[id]) { + oldController.finalize(); + } + } + this._buildViewportMap(); + } + _buildViewportMap() { + this._viewportMap = {}; + this._viewports.forEach((viewport) => { + if (viewport.id) { + this._viewportMap[viewport.id] = this._viewportMap[viewport.id] || viewport; + } + }); + } + // Check if viewport array has changed, returns true if any change + // Note that descriptors can be the same + _diffViews(newViews, oldViews) { + if (newViews.length !== oldViews.length) { + return true; + } + return newViews.some((_, i) => !newViews[i].equals(oldViews[i])); + } + }; + + // node_modules/@deck.gl/core/dist/utils/positions.js + var NUMBER_REGEX = /^(?:\d+\.?\d*|\.\d+)$/; + function parsePosition(value) { + switch (typeof value) { + case "number": + if (!Number.isFinite(value)) { + throw new Error(`Could not parse position string ${value}`); + } + return { type: "literal", value }; + case "string": + try { + const tokens = tokenize(value); + const parser = new LayoutExpressionParser(tokens); + return parser.parseExpression(); + } catch (error) { + const reason = error instanceof Error ? error.message : String(error); + throw new Error(`Could not parse position string ${value}: ${reason}`); + } + default: + throw new Error(`Could not parse position string ${value}`); + } + } + function evaluateLayoutExpression(expression, extent2) { + switch (expression.type) { + case "literal": + return expression.value; + case "percentage": + return Math.round(expression.value * extent2); + case "binary": + const left = evaluateLayoutExpression(expression.left, extent2); + const right = evaluateLayoutExpression(expression.right, extent2); + return expression.operator === "+" ? left + right : left - right; + default: + throw new Error("Unknown layout expression type"); + } + } + function getPosition(expression, extent2) { + return evaluateLayoutExpression(expression, extent2); + } + function tokenize(input) { + const tokens = []; + let index2 = 0; + while (index2 < input.length) { + const char = input[index2]; + if (/\s/.test(char)) { + index2++; + continue; + } + if (char === "+" || char === "-" || char === "(" || char === ")" || char === "%") { + tokens.push({ type: "symbol", value: char }); + index2++; + continue; + } + if (isDigit(char) || char === ".") { + const start = index2; + let hasDecimal = char === "."; + index2++; + while (index2 < input.length) { + const next = input[index2]; + if (isDigit(next)) { + index2++; + continue; + } + if (next === "." && !hasDecimal) { + hasDecimal = true; + index2++; + continue; + } + break; + } + const numberString = input.slice(start, index2); + if (!NUMBER_REGEX.test(numberString)) { + throw new Error("Invalid number token"); + } + tokens.push({ type: "number", value: parseFloat(numberString) }); + continue; + } + if (isAlpha(char)) { + const start = index2; + while (index2 < input.length && isAlpha(input[index2])) { + index2++; + } + const word = input.slice(start, index2).toLowerCase(); + tokens.push({ type: "word", value: word }); + continue; + } + throw new Error("Invalid token in position string"); + } + return tokens; + } + var LayoutExpressionParser = class { + constructor(tokens) { + this.index = 0; + this.tokens = tokens; + } + parseExpression() { + const expression = this.parseBinaryExpression(); + if (this.index < this.tokens.length) { + throw new Error("Unexpected token at end of expression"); + } + return expression; + } + parseBinaryExpression() { + let expression = this.parseFactor(); + let token = this.peek(); + while (isAddSubSymbol(token)) { + this.index++; + const right = this.parseFactor(); + expression = { type: "binary", operator: token.value, left: expression, right }; + token = this.peek(); + } + return expression; + } + parseFactor() { + const token = this.peek(); + if (!token) { + throw new Error("Unexpected end of expression"); + } + if (token.type === "symbol" && token.value === "+") { + this.index++; + return this.parseFactor(); + } + if (token.type === "symbol" && token.value === "-") { + this.index++; + const factor = this.parseFactor(); + return { type: "binary", operator: "-", left: { type: "literal", value: 0 }, right: factor }; + } + if (token.type === "symbol" && token.value === "(") { + this.index++; + const expression = this.parseBinaryExpression(); + if (!this.consumeSymbol(")")) { + throw new Error("Missing closing parenthesis"); + } + return expression; + } + if (token.type === "word" && token.value === "calc") { + this.index++; + if (!this.consumeSymbol("(")) { + throw new Error("Missing opening parenthesis after calc"); + } + const expression = this.parseBinaryExpression(); + if (!this.consumeSymbol(")")) { + throw new Error("Missing closing parenthesis"); + } + return expression; + } + if (token.type === "number") { + this.index++; + const numberValue = token.value; + const nextToken = this.peek(); + if (nextToken && nextToken.type === "symbol" && nextToken.value === "%") { + this.index++; + return { type: "percentage", value: numberValue / 100 }; + } + if (nextToken && nextToken.type === "word" && nextToken.value === "px") { + this.index++; + return { type: "literal", value: numberValue }; + } + return { type: "literal", value: numberValue }; + } + throw new Error("Unexpected token in expression"); + } + consumeSymbol(value) { + const token = this.peek(); + if (token && token.type === "symbol" && token.value === value) { + this.index++; + return true; + } + return false; + } + peek() { + return this.tokens[this.index] || null; + } + }; + function isDigit(char) { + return char >= "0" && char <= "9"; + } + function isAlpha(char) { + return char >= "a" && char <= "z" || char >= "A" && char <= "Z"; + } + function isAddSubSymbol(token) { + return Boolean(token && token.type === "symbol" && (token.value === "+" || token.value === "-")); + } + + // node_modules/@deck.gl/core/dist/utils/deep-merge.js + function deepMergeViewState(a, b) { + const result = { ...a }; + for (const key in b) { + if (key === "id") + continue; + if (Array.isArray(result[key]) && Array.isArray(b[key])) { + result[key] = mergeNumericArray(result[key], b[key]); + } else { + result[key] = b[key]; + } + } + return result; + } + function mergeNumericArray(target2, source3) { + target2 = target2.slice(); + for (let i = 0; i < source3.length; i++) { + const v = source3[i]; + if (Number.isFinite(v)) { + target2[i] = v; + } + } + return target2; + } + + // node_modules/@deck.gl/core/dist/views/view.js + var View = class { + constructor(props) { + const { id, x = 0, y = 0, width = "100%", height = "100%", padding = null } = props; + this.id = id || this.constructor.displayName || "view"; + this.props = { ...props, id: this.id }; + this._x = parsePosition(x); + this._y = parsePosition(y); + this._width = parsePosition(width); + this._height = parsePosition(height); + this._padding = padding && { + left: parsePosition(padding.left || 0), + right: parsePosition(padding.right || 0), + top: parsePosition(padding.top || 0), + bottom: parsePosition(padding.bottom || 0) + }; + this.equals = this.equals.bind(this); + Object.seal(this); + } + equals(view) { + if (this === view) { + return true; + } + return this.constructor === view.constructor && deepEqual2(this.props, view.props, 2); + } + /** Clone this view with modified props */ + clone(newProps) { + const ViewConstructor = this.constructor; + return new ViewConstructor({ ...this.props, ...newProps }); + } + /** Make viewport from canvas dimensions and view state */ + makeViewport({ width, height, viewState }) { + viewState = this.filterViewState(viewState); + const viewportDimensions = this.getDimensions({ width, height }); + if (!viewportDimensions.height || !viewportDimensions.width) { + return null; + } + const ViewportType = this.getViewportType(viewState); + return new ViewportType({ ...viewState, ...this.props, ...viewportDimensions }); + } + getViewStateId() { + const { viewState } = this.props; + if (typeof viewState === "string") { + return viewState; + } + return viewState?.id || this.id; + } + // Allows view to override (or completely define) viewState + filterViewState(viewState) { + if (this.props.viewState && typeof this.props.viewState === "object") { + if (!this.props.viewState.id) { + return this.props.viewState; + } + return deepMergeViewState(viewState, this.props.viewState); + } + return viewState; + } + /** Resolve the dimensions of the view from overall canvas dimensions */ + getDimensions({ width, height }) { + const dimensions = { + x: getPosition(this._x, width), + y: getPosition(this._y, height), + width: getPosition(this._width, width), + height: getPosition(this._height, height) + }; + if (this._padding) { + dimensions.padding = { + left: getPosition(this._padding.left, width), + top: getPosition(this._padding.top, height), + right: getPosition(this._padding.right, width), + bottom: getPosition(this._padding.bottom, height) + }; + } + return dimensions; + } + // Used by sub classes to resolve controller props + get controller() { + const opts = this.props.controller; + if (!opts) { + return null; + } + if (opts === true) { + return { type: this.ControllerType }; + } + if (typeof opts === "function") { + return { type: opts }; + } + return { type: this.ControllerType, ...opts }; + } + }; + + // node_modules/@deck.gl/core/dist/transitions/transition.js + var Transition = class { + /** + * @params timeline {Timeline} + */ + constructor(timeline) { + this._inProgress = false; + this._handle = null; + this.time = 0; + this.settings = { + duration: 0 + }; + this._timeline = timeline; + } + /* Public API */ + get inProgress() { + return this._inProgress; + } + /** + * (re)start this transition. + * @params props {object} - optional overriding props. see constructor + */ + start(settings) { + this.cancel(); + this.settings = settings; + this._inProgress = true; + this.settings.onStart?.(this); + } + /** + * end this transition if it is in progress. + */ + end() { + if (this._inProgress) { + this._timeline.removeChannel(this._handle); + this._handle = null; + this._inProgress = false; + this.settings.onEnd?.(this); + } + } + /** + * cancel this transition if it is in progress. + */ + cancel() { + if (this._inProgress) { + this.settings.onInterrupt?.(this); + this._timeline.removeChannel(this._handle); + this._handle = null; + this._inProgress = false; + } + } + /** + * update this transition. Returns `true` if updated. + */ + update() { + if (!this._inProgress) { + return false; + } + if (this._handle === null) { + const { _timeline: timeline, settings } = this; + this._handle = timeline.addChannel({ + delay: timeline.getTime(), + duration: settings.duration + }); + } + this.time = this._timeline.getTime(this._handle); + this._onUpdate(); + this.settings.onUpdate?.(this); + if (this._timeline.isFinished(this._handle)) { + this.end(); + } + return true; + } + /* Private API */ + _onUpdate() { + } + }; + + // node_modules/@deck.gl/core/dist/controllers/transition-manager.js + var noop2 = () => { + }; + var TRANSITION_EVENTS = { + BREAK: 1, + SNAP_TO_END: 2, + IGNORE: 3 + }; + var DEFAULT_EASING = (t) => t; + var DEFAULT_INTERRUPTION = TRANSITION_EVENTS.BREAK; + var TransitionManager = class { + constructor(opts) { + this._onTransitionUpdate = (transition) => { + const { time, settings: { interpolator, startProps, endProps, duration, easing } } = transition; + const t = easing(time / duration); + const viewport = interpolator.interpolateProps(startProps, endProps, t); + this.propsInTransition = this.getControllerState({ + ...this.props, + ...viewport + }).getViewportProps(); + this.onViewStateChange({ + viewState: this.propsInTransition, + oldViewState: this.props + }); + }; + this.getControllerState = opts.getControllerState; + this.propsInTransition = null; + this.transition = new Transition(opts.timeline); + this.onViewStateChange = opts.onViewStateChange || noop2; + this.onStateChange = opts.onStateChange || noop2; + } + finalize() { + this.transition.cancel(); + } + // Returns current transitioned viewport. + getViewportInTransition() { + return this.propsInTransition; + } + // Process the vewiport change, either ignore or trigger a new transition. + // Return true if a new transition is triggered, false otherwise. + processViewStateChange(nextProps) { + let transitionTriggered = false; + const currentProps = this.props; + this.props = nextProps; + if (!currentProps || this._shouldIgnoreViewportChange(currentProps, nextProps)) { + return false; + } + if (this._isTransitionEnabled(nextProps)) { + let startProps = currentProps; + if (this.transition.inProgress) { + const { interruption, endProps } = this.transition.settings; + startProps = { + ...currentProps, + ...interruption === TRANSITION_EVENTS.SNAP_TO_END ? endProps : this.propsInTransition || currentProps + }; + } + this._triggerTransition(startProps, nextProps); + transitionTriggered = true; + } else { + this.transition.cancel(); + } + return transitionTriggered; + } + updateTransition() { + this.transition.update(); + } + // Helper methods + _isTransitionEnabled(props) { + const { transitionDuration, transitionInterpolator } = props; + return (transitionDuration > 0 || transitionDuration === "auto") && Boolean(transitionInterpolator); + } + _isUpdateDueToCurrentTransition(props) { + if (this.transition.inProgress && this.propsInTransition) { + return this.transition.settings.interpolator.arePropsEqual(props, this.propsInTransition); + } + return false; + } + _shouldIgnoreViewportChange(currentProps, nextProps) { + if (this.transition.inProgress) { + const transitionSettings = this.transition.settings; + return transitionSettings.interruption === TRANSITION_EVENTS.IGNORE || // Ignore update if it is due to current active transition. + this._isUpdateDueToCurrentTransition(nextProps); + } + if (this._isTransitionEnabled(nextProps)) { + return nextProps.transitionInterpolator.arePropsEqual(currentProps, nextProps); + } + return true; + } + _triggerTransition(startProps, endProps) { + const startViewstate = this.getControllerState(startProps); + const endViewStateProps = this.getControllerState(endProps).shortestPathFrom(startViewstate); + const transitionInterpolator = endProps.transitionInterpolator; + const duration = transitionInterpolator.getDuration ? transitionInterpolator.getDuration(startProps, endProps) : endProps.transitionDuration; + if (duration === 0) { + return; + } + const initialProps = transitionInterpolator.initializeProps(startProps, endViewStateProps); + this.propsInTransition = {}; + const transitionSettings = { + duration, + easing: endProps.transitionEasing || DEFAULT_EASING, + interpolator: transitionInterpolator, + interruption: endProps.transitionInterruption || DEFAULT_INTERRUPTION, + startProps: initialProps.start, + endProps: initialProps.end, + onStart: endProps.onTransitionStart, + onUpdate: this._onTransitionUpdate, + onInterrupt: this._onTransitionEnd(endProps.onTransitionInterrupt), + onEnd: this._onTransitionEnd(endProps.onTransitionEnd) + }; + this.transition.start(transitionSettings); + this.onStateChange({ inTransition: true }); + this.updateTransition(); + } + _onTransitionEnd(callback) { + return (transition) => { + this.propsInTransition = null; + this.onStateChange({ + inTransition: false, + isZooming: false, + isPanning: false, + isRotating: false + }); + callback?.(transition); + }; + } + }; + + // node_modules/@deck.gl/core/dist/utils/assert.js + function assert8(condition, message2) { + if (!condition) { + throw new Error(message2 || "deck.gl: assertion failed."); + } + } + + // node_modules/@deck.gl/core/dist/transitions/transition-interpolator.js + var TransitionInterpolator = class { + /** + * @param opts {array|object} + * @param opts.compare {array} - prop names used in equality check + * @param opts.extract {array} - prop names needed for interpolation + * @param opts.required {array} - prop names that must be supplied + * alternatively, supply one list of prop names as `opts` if all of the above are the same. + */ + constructor(opts) { + const { compare, extract, required } = opts; + this._propsToCompare = compare; + this._propsToExtract = extract || compare; + this._requiredProps = required; + } + /** + * Checks if two sets of props need transition in between + * @param currentProps {object} - a list of viewport props + * @param nextProps {object} - a list of viewport props + * @returns {bool} - true if two props are equivalent + */ + arePropsEqual(currentProps, nextProps) { + for (const key of this._propsToCompare) { + if (!(key in currentProps) || !(key in nextProps) || !equals(currentProps[key], nextProps[key])) { + return false; + } + } + return true; + } + /** + * Called before transition starts to validate/pre-process start and end props + * @param startProps {object} - a list of starting viewport props + * @param endProps {object} - a list of target viewport props + * @returns {Object} {start, end} - start and end props to be passed + * to `interpolateProps` + */ + initializeProps(startProps, endProps) { + const startViewStateProps = {}; + const endViewStateProps = {}; + for (const key of this._propsToExtract) { + if (key in startProps || key in endProps) { + startViewStateProps[key] = startProps[key]; + endViewStateProps[key] = endProps[key]; + } + } + this._checkRequiredProps(startViewStateProps); + this._checkRequiredProps(endViewStateProps); + return { start: startViewStateProps, end: endViewStateProps }; + } + /** + * Returns transition duration + * @param startProps {object} - a list of starting viewport props + * @param endProps {object} - a list of target viewport props + * @returns {Number} - transition duration in milliseconds + */ + getDuration(startProps, endProps) { + return endProps.transitionDuration; + } + _checkRequiredProps(props) { + if (!this._requiredProps) { + return; + } + this._requiredProps.forEach((propName) => { + const value = props[propName]; + assert8(Number.isFinite(value) || Array.isArray(value), `${propName} is required for transition`); + }); + } + }; + + // node_modules/@deck.gl/core/dist/viewports/globe-viewport.js + var DEGREES_TO_RADIANS5 = Math.PI / 180; + var RADIANS_TO_DEGREES3 = 180 / Math.PI; + var EARTH_RADIUS = 6370972; + var GLOBE_RADIUS = 256; + function getDistanceScales2() { + const unitsPerMeter2 = GLOBE_RADIUS / EARTH_RADIUS; + const unitsPerDegree = Math.PI / 180 * GLOBE_RADIUS; + return { + unitsPerMeter: [unitsPerMeter2, unitsPerMeter2, unitsPerMeter2], + unitsPerMeter2: [0, 0, 0], + metersPerUnit: [1 / unitsPerMeter2, 1 / unitsPerMeter2, 1 / unitsPerMeter2], + unitsPerDegree: [unitsPerDegree, unitsPerDegree, unitsPerMeter2], + unitsPerDegree2: [0, 0, 0], + degreesPerUnit: [1 / unitsPerDegree, 1 / unitsPerDegree, 1 / unitsPerMeter2] + }; + } + var GlobeViewport = class extends viewport_default { + constructor(opts = {}) { + const { + longitude = 0, + zoom = 0, + // Matches Maplibre defaults + // https://github.com/maplibre/maplibre-gl-js/blob/f8ab4b48d59ab8fe7b068b102538793bbdd4c848/src/geo/projection/globe_transform.ts#L632-L633 + nearZMultiplier = 0.5, + farZMultiplier = 1, + resolution = 10 + } = opts; + let { latitude = 0, height, altitude = 1.5, fovy } = opts; + latitude = Math.max(Math.min(latitude, MAX_LATITUDE), -MAX_LATITUDE); + height = height || 1; + if (fovy) { + altitude = fovyToAltitude(fovy); + } else { + fovy = altitudeToFovy(altitude); + } + const scale5 = Math.pow(2, zoom - zoomAdjust(latitude)); + const nearZ = opts.nearZ ?? nearZMultiplier; + const farZ = opts.farZ ?? (altitude + GLOBE_RADIUS * 2 * scale5 / height) * farZMultiplier; + const viewMatrix = new Matrix4().lookAt({ eye: [0, -altitude, 0], up: [0, 0, 1] }); + viewMatrix.rotateX(latitude * DEGREES_TO_RADIANS5); + viewMatrix.rotateZ(-longitude * DEGREES_TO_RADIANS5); + viewMatrix.scale(scale5 / height); + super({ + ...opts, + // x, y, width, + height, + // view matrix + viewMatrix, + longitude, + latitude, + zoom, + // projection matrix parameters + distanceScales: getDistanceScales2(), + fovy, + focalDistance: altitude, + near: nearZ, + far: farZ + }); + this.scale = scale5; + this.latitude = latitude; + this.longitude = longitude; + this.fovy = fovy; + this.resolution = resolution; + } + get projectionMode() { + return PROJECTION_MODE.GLOBE; + } + getDistanceScales() { + return this.distanceScales; + } + getBounds(options = {}) { + const unprojectOption = { targetZ: options.z || 0 }; + const left = this.unproject([0, this.height / 2], unprojectOption); + const top = this.unproject([this.width / 2, 0], unprojectOption); + const right = this.unproject([this.width, this.height / 2], unprojectOption); + const bottom = this.unproject([this.width / 2, this.height], unprojectOption); + if (right[0] < this.longitude) + right[0] += 360; + if (left[0] > this.longitude) + left[0] -= 360; + return [ + Math.min(left[0], right[0], top[0], bottom[0]), + Math.min(left[1], right[1], top[1], bottom[1]), + Math.max(left[0], right[0], top[0], bottom[0]), + Math.max(left[1], right[1], top[1], bottom[1]) + ]; + } + unproject(xyz, { topLeft = true, targetZ } = {}) { + const [x, y, z] = xyz; + const y2 = topLeft ? y : this.height - y; + const { pixelUnprojectionMatrix } = this; + let coord; + if (Number.isFinite(z)) { + coord = transformVector2(pixelUnprojectionMatrix, [x, y2, z, 1]); + } else { + const coord0 = transformVector2(pixelUnprojectionMatrix, [x, y2, -1, 1]); + const coord1 = transformVector2(pixelUnprojectionMatrix, [x, y2, 1, 1]); + const lt = ((targetZ || 0) / EARTH_RADIUS + 1) * GLOBE_RADIUS; + const lSqr = vec3_exports.sqrLen(vec3_exports.sub([], coord0, coord1)); + const l0Sqr = vec3_exports.sqrLen(coord0); + const l1Sqr = vec3_exports.sqrLen(coord1); + const sSqr = (4 * l0Sqr * l1Sqr - (lSqr - l0Sqr - l1Sqr) ** 2) / 16; + const dSqr = 4 * sSqr / lSqr; + const r0 = Math.sqrt(l0Sqr - dSqr); + const dr = Math.sqrt(Math.max(0, lt * lt - dSqr)); + const t = (r0 - dr) / Math.sqrt(lSqr); + coord = vec3_exports.lerp([], coord0, coord1, t); + } + const [X, Y, Z] = this.unprojectPosition(coord); + if (Number.isFinite(z)) { + return [X, Y, Z]; + } + return Number.isFinite(targetZ) ? [X, Y, targetZ] : [X, Y]; + } + projectPosition(xyz) { + const [lng, lat, Z = 0] = xyz; + const lambda = lng * DEGREES_TO_RADIANS5; + const phi = lat * DEGREES_TO_RADIANS5; + const cosPhi = Math.cos(phi); + const D2 = (Z / EARTH_RADIUS + 1) * GLOBE_RADIUS; + return [Math.sin(lambda) * cosPhi * D2, -Math.cos(lambda) * cosPhi * D2, Math.sin(phi) * D2]; + } + unprojectPosition(xyz) { + const [x, y, z] = xyz; + const D2 = vec3_exports.len(xyz); + const phi = Math.asin(z / D2); + const lambda = Math.atan2(x, -y); + const lng = lambda * RADIANS_TO_DEGREES3; + const lat = phi * RADIANS_TO_DEGREES3; + const Z = (D2 / GLOBE_RADIUS - 1) * EARTH_RADIUS; + return [lng, lat, Z]; + } + projectFlat(xyz) { + return xyz; + } + unprojectFlat(xyz) { + return xyz; + } + /** + * Pan the globe using delta-based movement + * @param coords - the geographic coordinates where the pan started + * @param pixel - the current screen position + * @param startPixel - the screen position where the pan started + * @returns updated viewport options with new longitude/latitude + */ + panByPosition([startLng, startLat, startZoom], pixel, startPixel) { + const scale5 = Math.pow(2, this.zoom - zoomAdjust(this.latitude)); + const rotationSpeed = 0.25 / scale5; + const longitude = startLng + rotationSpeed * (startPixel[0] - pixel[0]); + let latitude = startLat - rotationSpeed * (startPixel[1] - pixel[1]); + latitude = Math.max(Math.min(latitude, MAX_LATITUDE), -MAX_LATITUDE); + const out = { longitude, latitude, zoom: startZoom - zoomAdjust(startLat) }; + out.zoom += zoomAdjust(out.latitude); + return out; + } + }; + GlobeViewport.displayName = "GlobeViewport"; + var globe_viewport_default = GlobeViewport; + function zoomAdjust(latitude) { + const scaleAdjust = Math.PI * Math.cos(latitude * Math.PI / 180); + return Math.log2(scaleAdjust); + } + function transformVector2(matrix, vector) { + const result = vec4_exports.transformMat4([], vector, matrix); + vec4_exports.scale(result, result, 1 / result[3]); + return result; + } + + // node_modules/@deck.gl/core/dist/transitions/linear-interpolator.js + var DEFAULT_PROPS2 = ["longitude", "latitude", "zoom", "bearing", "pitch"]; + var DEFAULT_REQUIRED_PROPS = ["longitude", "latitude", "zoom"]; + var LinearInterpolator = class extends TransitionInterpolator { + /** + * @param {Object} opts + * @param {Array} opts.transitionProps - list of props to apply linear transition to. + * @param {Array} opts.around - a screen point to zoom/rotate around. + * @param {Function} opts.makeViewport - construct a viewport instance with given props. + */ + constructor(opts = {}) { + const transitionProps = Array.isArray(opts) ? opts : opts.transitionProps; + const normalizedOpts = Array.isArray(opts) ? {} : opts; + normalizedOpts.transitionProps = Array.isArray(transitionProps) ? { + compare: transitionProps, + required: transitionProps + } : transitionProps || { + compare: DEFAULT_PROPS2, + required: DEFAULT_REQUIRED_PROPS + }; + super(normalizedOpts.transitionProps); + this.opts = normalizedOpts; + } + initializeProps(startProps, endProps) { + const result = super.initializeProps(startProps, endProps); + const { makeViewport, around } = this.opts; + if (makeViewport && around) { + const TestViewport = makeViewport(startProps); + if (TestViewport instanceof globe_viewport_default) { + log_default.warn("around not supported in GlobeView")(); + } else { + const startViewport = makeViewport(startProps); + const endViewport = makeViewport(endProps); + const aroundPosition = startViewport.unproject(around); + result.start.around = around; + Object.assign(result.end, { + around: endViewport.project(aroundPosition), + aroundPosition, + width: endProps.width, + height: endProps.height + }); + } + } + return result; + } + interpolateProps(startProps, endProps, t) { + const propsInTransition = {}; + for (const key of this._propsToExtract) { + propsInTransition[key] = lerp(startProps[key] || 0, endProps[key] || 0, t); + } + if (endProps.aroundPosition && this.opts.makeViewport) { + const viewport = this.opts.makeViewport({ ...endProps, ...propsInTransition }); + Object.assign(propsInTransition, viewport.panByPosition( + endProps.aroundPosition, + // anchor point in current screen coordinates + lerp(startProps.around, endProps.around, t) + )); + } + return propsInTransition; + } + }; + + // node_modules/@deck.gl/core/dist/controllers/controller.js + var NO_TRANSITION_PROPS = { + transitionDuration: 0 + }; + var DEFAULT_INERTIA = 300; + var INERTIA_EASING = (t) => 1 - (1 - t) * (1 - t); + var EVENT_TYPES = { + WHEEL: ["wheel"], + PAN: ["panstart", "panmove", "panend"], + PINCH: ["pinchstart", "pinchmove", "pinchend"], + MULTI_PAN: ["multipanstart", "multipanmove", "multipanend"], + DOUBLE_CLICK: ["dblclick"], + KEYBOARD: ["keydown"] + }; + var pinchEventWorkaround = {}; + var Controller = class { + constructor(opts) { + this.state = {}; + this._events = {}; + this._interactionState = { + isDragging: false + }; + this._customEvents = []; + this._eventStartBlocked = null; + this._panMove = false; + this.invertPan = false; + this.dragMode = "rotate"; + this.inertia = 0; + this.scrollZoom = true; + this.dragPan = true; + this.dragRotate = true; + this.doubleClickZoom = true; + this.touchZoom = true; + this.touchRotate = false; + this.keyboard = true; + this.transitionManager = new TransitionManager({ + ...opts, + getControllerState: (props) => new this.ControllerState(props), + onViewStateChange: this._onTransition.bind(this), + onStateChange: this._setInteractionState.bind(this) + }); + this.handleEvent = this.handleEvent.bind(this); + this.eventManager = opts.eventManager; + this.onViewStateChange = opts.onViewStateChange || (() => { + }); + this.onStateChange = opts.onStateChange || (() => { + }); + this.makeViewport = opts.makeViewport; + this.pickPosition = opts.pickPosition; + } + set events(customEvents) { + this.toggleEvents(this._customEvents, false); + this.toggleEvents(customEvents, true); + this._customEvents = customEvents; + if (this.props) { + this.setProps(this.props); + } + } + finalize() { + for (const eventName in this._events) { + if (this._events[eventName]) { + this.eventManager?.off(eventName, this.handleEvent); + } + } + this.transitionManager.finalize(); + } + /** + * Callback for events + */ + handleEvent(event) { + this._controllerState = void 0; + const eventStartBlocked = this._eventStartBlocked; + switch (event.type) { + case "panstart": + return eventStartBlocked ? false : this._onPanStart(event); + case "panmove": + return this._onPan(event); + case "panend": + return this._onPanEnd(event); + case "pinchstart": + return eventStartBlocked ? false : this._onPinchStart(event); + case "pinchmove": + return this._onPinch(event); + case "pinchend": + return this._onPinchEnd(event); + case "multipanstart": + return eventStartBlocked ? false : this._onMultiPanStart(event); + case "multipanmove": + return this._onMultiPan(event); + case "multipanend": + return this._onMultiPanEnd(event); + case "dblclick": + return this._onDoubleClick(event); + case "wheel": + return this._onWheel(event); + case "keydown": + return this._onKeyDown(event); + default: + return false; + } + } + /* Event utils */ + // Event object: http://hammerjs.github.io/api/#event-object + get controllerState() { + this._controllerState = this._controllerState || new this.ControllerState({ + makeViewport: this.makeViewport, + ...this.props, + ...this.state + }); + return this._controllerState; + } + getCenter(event) { + const { x, y } = this.props; + const { offsetCenter } = event; + return [offsetCenter.x - x, offsetCenter.y - y]; + } + isPointInBounds(pos, event) { + const { width, height } = this.props; + if (event && event.handled) { + return false; + } + const inside = pos[0] >= 0 && pos[0] <= width && pos[1] >= 0 && pos[1] <= height; + if (inside && event) { + event.stopPropagation(); + } + return inside; + } + isFunctionKeyPressed(event) { + const { srcEvent } = event; + return Boolean(srcEvent.metaKey || srcEvent.altKey || srcEvent.ctrlKey || srcEvent.shiftKey); + } + isDragging() { + return this._interactionState.isDragging || false; + } + // When a multi-touch event ends, e.g. pinch, not all pointers are lifted at the same time. + // This triggers a brief `pan` event. + // Calling this method will temporarily disable *start events to avoid conflicting transitions. + blockEvents(timeout) { + const timer = setTimeout(() => { + if (this._eventStartBlocked === timer) { + this._eventStartBlocked = null; + } + }, timeout); + this._eventStartBlocked = timer; + } + /** + * Extract interactivity options + */ + setProps(props) { + if (props.dragMode) { + this.dragMode = props.dragMode; + } + const oldProps = this.props; + this.props = props; + if (!("transitionInterpolator" in props)) { + props.transitionInterpolator = this._getTransitionProps().transitionInterpolator; + } + this.transitionManager.processViewStateChange(props); + const { inertia } = props; + this.inertia = Number.isFinite(inertia) ? inertia : inertia === true ? DEFAULT_INERTIA : 0; + const { scrollZoom = true, dragPan = true, dragRotate = true, doubleClickZoom = true, touchZoom = true, touchRotate = false, keyboard = true } = props; + const isInteractive = Boolean(this.onViewStateChange); + this.toggleEvents(EVENT_TYPES.WHEEL, isInteractive && scrollZoom); + this.toggleEvents(EVENT_TYPES.PAN, isInteractive); + this.toggleEvents(EVENT_TYPES.PINCH, isInteractive && (touchZoom || touchRotate)); + this.toggleEvents(EVENT_TYPES.MULTI_PAN, isInteractive && touchRotate); + this.toggleEvents(EVENT_TYPES.DOUBLE_CLICK, isInteractive && doubleClickZoom); + this.toggleEvents(EVENT_TYPES.KEYBOARD, isInteractive && keyboard); + this.scrollZoom = scrollZoom; + this.dragPan = dragPan; + this.dragRotate = dragRotate; + this.doubleClickZoom = doubleClickZoom; + this.touchZoom = touchZoom; + this.touchRotate = touchRotate; + this.keyboard = keyboard; + const dimensionChanged = !oldProps || oldProps.height !== props.height || oldProps.width !== props.width || oldProps.maxBounds !== props.maxBounds; + if (dimensionChanged && props.maxBounds) { + const controllerState = new this.ControllerState({ ...props, makeViewport: this.makeViewport }); + const normalizedProps = controllerState.getViewportProps(); + const changed = Object.keys(normalizedProps).some((key) => !deepEqual2(normalizedProps[key], props[key], 1)); + if (changed) { + this.updateViewport(controllerState); + } + } + } + updateTransition() { + this.transitionManager.updateTransition(); + } + toggleEvents(eventNames, enabled) { + if (this.eventManager) { + eventNames.forEach((eventName) => { + if (this._events[eventName] !== enabled) { + this._events[eventName] = enabled; + if (enabled) { + this.eventManager.on(eventName, this.handleEvent); + } else { + this.eventManager.off(eventName, this.handleEvent); + } + } + }); + } + } + // Private Methods + /* Callback util */ + // formats map state and invokes callback function + updateViewport(newControllerState, extraProps = null, interactionState = {}) { + const viewState = { ...newControllerState.getViewportProps(), ...extraProps }; + const changed = this.controllerState !== newControllerState; + this.state = newControllerState.getState(); + this._setInteractionState(interactionState); + if (changed) { + const oldViewState = this.controllerState && this.controllerState.getViewportProps(); + if (this.onViewStateChange) { + this.onViewStateChange({ viewState, interactionState: this._interactionState, oldViewState, viewId: this.props.id }); + } + } + } + _onTransition(params) { + this.onViewStateChange({ ...params, interactionState: this._interactionState, viewId: this.props.id }); + } + _setInteractionState(newStates) { + Object.assign(this._interactionState, newStates); + this.onStateChange(this._interactionState); + } + /* Event handlers */ + // Default handler for the `panstart` event. + _onPanStart(event) { + const pos = this.getCenter(event); + if (!this.isPointInBounds(pos, event)) { + return false; + } + let alternateMode = this.isFunctionKeyPressed(event) || event.rightButton || false; + if (this.invertPan || this.dragMode === "pan") { + alternateMode = !alternateMode; + } + const newControllerState = this.controllerState[alternateMode ? "panStart" : "rotateStart"]({ + pos + }); + this._panMove = alternateMode; + this.updateViewport(newControllerState, NO_TRANSITION_PROPS, { isDragging: true }); + return true; + } + // Default handler for the `panmove` and `panend` event. + _onPan(event) { + if (!this.isDragging()) { + return false; + } + return this._panMove ? this._onPanMove(event) : this._onPanRotate(event); + } + _onPanEnd(event) { + if (!this.isDragging()) { + return false; + } + return this._panMove ? this._onPanMoveEnd(event) : this._onPanRotateEnd(event); + } + // Default handler for panning to move. + // Called by `_onPan` when panning without function key pressed. + _onPanMove(event) { + if (!this.dragPan) { + return false; + } + const pos = this.getCenter(event); + const newControllerState = this.controllerState.pan({ pos }); + this.updateViewport(newControllerState, NO_TRANSITION_PROPS, { + isDragging: true, + isPanning: true + }); + return true; + } + _onPanMoveEnd(event) { + const { inertia } = this; + if (this.dragPan && inertia && event.velocity) { + const pos = this.getCenter(event); + const endPos = [ + pos[0] + event.velocityX * inertia / 2, + pos[1] + event.velocityY * inertia / 2 + ]; + const newControllerState = this.controllerState.pan({ pos: endPos }).panEnd(); + this.updateViewport(newControllerState, { + ...this._getTransitionProps(), + transitionDuration: inertia, + transitionEasing: INERTIA_EASING + }, { + isDragging: false, + isPanning: true + }); + } else { + const newControllerState = this.controllerState.panEnd(); + this.updateViewport(newControllerState, null, { + isDragging: false, + isPanning: false + }); + } + return true; + } + // Default handler for panning to rotate. + // Called by `_onPan` when panning with function key pressed. + _onPanRotate(event) { + if (!this.dragRotate) { + return false; + } + const pos = this.getCenter(event); + const newControllerState = this.controllerState.rotate({ pos }); + this.updateViewport(newControllerState, NO_TRANSITION_PROPS, { + isDragging: true, + isRotating: true + }); + return true; + } + _onPanRotateEnd(event) { + const { inertia } = this; + if (this.dragRotate && inertia && event.velocity) { + const pos = this.getCenter(event); + const endPos = [ + pos[0] + event.velocityX * inertia / 2, + pos[1] + event.velocityY * inertia / 2 + ]; + const newControllerState = this.controllerState.rotate({ pos: endPos }).rotateEnd(); + this.updateViewport(newControllerState, { + ...this._getTransitionProps(), + transitionDuration: inertia, + transitionEasing: INERTIA_EASING + }, { + isDragging: false, + isRotating: true + }); + } else { + const newControllerState = this.controllerState.rotateEnd(); + this.updateViewport(newControllerState, null, { + isDragging: false, + isRotating: false + }); + } + return true; + } + // Default handler for the `wheel` event. + _onWheel(event) { + if (!this.scrollZoom) { + return false; + } + const pos = this.getCenter(event); + if (!this.isPointInBounds(pos, event)) { + return false; + } + event.srcEvent.preventDefault(); + const { speed = 0.01, smooth = false } = this.scrollZoom === true ? {} : this.scrollZoom; + const { delta } = event; + let scale5 = 2 / (1 + Math.exp(-Math.abs(delta * speed))); + if (delta < 0 && scale5 !== 0) { + scale5 = 1 / scale5; + } + const transitionProps = smooth ? { ...this._getTransitionProps({ around: pos }), transitionDuration: 250 } : NO_TRANSITION_PROPS; + const newControllerState = this.controllerState.zoom({ pos, scale: scale5 }); + this.updateViewport(newControllerState, transitionProps, { + isZooming: true, + isPanning: true + }); + if (!smooth) { + this._setInteractionState({ isZooming: false, isPanning: false }); + } + return true; + } + _onMultiPanStart(event) { + const pos = this.getCenter(event); + if (!this.isPointInBounds(pos, event)) { + return false; + } + const newControllerState = this.controllerState.rotateStart({ pos }); + this.updateViewport(newControllerState, NO_TRANSITION_PROPS, { isDragging: true }); + return true; + } + _onMultiPan(event) { + if (!this.touchRotate) { + return false; + } + if (!this.isDragging()) { + return false; + } + const pos = this.getCenter(event); + pos[0] -= event.deltaX; + const newControllerState = this.controllerState.rotate({ pos }); + this.updateViewport(newControllerState, NO_TRANSITION_PROPS, { + isDragging: true, + isRotating: true + }); + return true; + } + _onMultiPanEnd(event) { + if (!this.isDragging()) { + return false; + } + const { inertia } = this; + if (this.touchRotate && inertia && event.velocityY) { + const pos = this.getCenter(event); + const endPos = [pos[0], pos[1] += event.velocityY * inertia / 2]; + const newControllerState = this.controllerState.rotate({ pos: endPos }); + this.updateViewport(newControllerState, { + ...this._getTransitionProps(), + transitionDuration: inertia, + transitionEasing: INERTIA_EASING + }, { + isDragging: false, + isRotating: true + }); + this.blockEvents(inertia); + } else { + const newControllerState = this.controllerState.rotateEnd(); + this.updateViewport(newControllerState, null, { + isDragging: false, + isRotating: false + }); + } + return true; + } + // Default handler for the `pinchstart` event. + _onPinchStart(event) { + const pos = this.getCenter(event); + if (!this.isPointInBounds(pos, event)) { + return false; + } + const newControllerState = this.controllerState.zoomStart({ pos }).rotateStart({ pos }); + pinchEventWorkaround._startPinchRotation = event.rotation; + pinchEventWorkaround._lastPinchEvent = event; + this.updateViewport(newControllerState, NO_TRANSITION_PROPS, { isDragging: true }); + return true; + } + // Default handler for the `pinchmove` and `pinchend` events. + _onPinch(event) { + if (!this.touchZoom && !this.touchRotate) { + return false; + } + if (!this.isDragging()) { + return false; + } + let newControllerState = this.controllerState; + if (this.touchZoom) { + const { scale: scale5 } = event; + const pos = this.getCenter(event); + newControllerState = newControllerState.zoom({ pos, scale: scale5 }); + } + if (this.touchRotate) { + const { rotation } = event; + newControllerState = newControllerState.rotate({ + deltaAngleX: pinchEventWorkaround._startPinchRotation - rotation + }); + } + this.updateViewport(newControllerState, NO_TRANSITION_PROPS, { + isDragging: true, + isPanning: this.touchZoom, + isZooming: this.touchZoom, + isRotating: this.touchRotate + }); + pinchEventWorkaround._lastPinchEvent = event; + return true; + } + _onPinchEnd(event) { + if (!this.isDragging()) { + return false; + } + const { inertia } = this; + const { _lastPinchEvent } = pinchEventWorkaround; + if (this.touchZoom && inertia && _lastPinchEvent && event.scale !== _lastPinchEvent.scale) { + const pos = this.getCenter(event); + let newControllerState = this.controllerState.rotateEnd(); + const z = Math.log2(event.scale); + const velocityZ = (z - Math.log2(_lastPinchEvent.scale)) / (event.deltaTime - _lastPinchEvent.deltaTime); + const endScale = Math.pow(2, z + velocityZ * inertia / 2); + newControllerState = newControllerState.zoom({ pos, scale: endScale }).zoomEnd(); + this.updateViewport(newControllerState, { + ...this._getTransitionProps({ around: pos }), + transitionDuration: inertia, + transitionEasing: INERTIA_EASING + }, { + isDragging: false, + isPanning: this.touchZoom, + isZooming: this.touchZoom, + isRotating: false + }); + this.blockEvents(inertia); + } else { + const newControllerState = this.controllerState.zoomEnd().rotateEnd(); + this.updateViewport(newControllerState, null, { + isDragging: false, + isPanning: false, + isZooming: false, + isRotating: false + }); + } + pinchEventWorkaround._startPinchRotation = null; + pinchEventWorkaround._lastPinchEvent = null; + return true; + } + // Default handler for the `dblclick` event. + _onDoubleClick(event) { + if (!this.doubleClickZoom) { + return false; + } + const pos = this.getCenter(event); + if (!this.isPointInBounds(pos, event)) { + return false; + } + const isZoomOut = this.isFunctionKeyPressed(event); + const newControllerState = this.controllerState.zoom({ pos, scale: isZoomOut ? 0.5 : 2 }); + this.updateViewport(newControllerState, this._getTransitionProps({ around: pos }), { + isZooming: true, + isPanning: true + }); + this.blockEvents(100); + return true; + } + // Default handler for the `keydown` event + _onKeyDown(event) { + if (!this.keyboard) { + return false; + } + const funcKey = this.isFunctionKeyPressed(event); + const { zoomSpeed, moveSpeed, rotateSpeedX, rotateSpeedY } = this.keyboard === true ? {} : this.keyboard; + const { controllerState } = this; + let newControllerState; + const interactionState = {}; + switch (event.srcEvent.code) { + case "Minus": + newControllerState = funcKey ? controllerState.zoomOut(zoomSpeed).zoomOut(zoomSpeed) : controllerState.zoomOut(zoomSpeed); + interactionState.isZooming = true; + break; + case "Equal": + newControllerState = funcKey ? controllerState.zoomIn(zoomSpeed).zoomIn(zoomSpeed) : controllerState.zoomIn(zoomSpeed); + interactionState.isZooming = true; + break; + case "ArrowLeft": + if (funcKey) { + newControllerState = controllerState.rotateLeft(rotateSpeedX); + interactionState.isRotating = true; + } else { + newControllerState = controllerState.moveLeft(moveSpeed); + interactionState.isPanning = true; + } + break; + case "ArrowRight": + if (funcKey) { + newControllerState = controllerState.rotateRight(rotateSpeedX); + interactionState.isRotating = true; + } else { + newControllerState = controllerState.moveRight(moveSpeed); + interactionState.isPanning = true; + } + break; + case "ArrowUp": + if (funcKey) { + newControllerState = controllerState.rotateUp(rotateSpeedY); + interactionState.isRotating = true; + } else { + newControllerState = controllerState.moveUp(moveSpeed); + interactionState.isPanning = true; + } + break; + case "ArrowDown": + if (funcKey) { + newControllerState = controllerState.rotateDown(rotateSpeedY); + interactionState.isRotating = true; + } else { + newControllerState = controllerState.moveDown(moveSpeed); + interactionState.isPanning = true; + } + break; + default: + return false; + } + this.updateViewport(newControllerState, this._getTransitionProps(), interactionState); + return true; + } + _getTransitionProps(opts) { + const { transition } = this; + if (!transition || !transition.transitionInterpolator) { + return NO_TRANSITION_PROPS; + } + return opts ? { + ...transition, + transitionInterpolator: new LinearInterpolator({ + ...opts, + ...transition.transitionInterpolator.opts, + makeViewport: this.controllerState.makeViewport + }) + } : transition; + } + }; + + // node_modules/@deck.gl/core/dist/controllers/view-state.js + var ViewState = class { + constructor(props, state, makeViewport) { + this.makeViewport = makeViewport; + this._viewportProps = this.applyConstraints(props); + this._state = state; + } + getViewportProps() { + return this._viewportProps; + } + getState() { + return this._state; + } + }; + + // node_modules/@deck.gl/core/dist/controllers/map-controller.js + var PITCH_MOUSE_THRESHOLD = 5; + var PITCH_ACCEL = 1.2; + var WEB_MERCATOR_TILE_SIZE = 512; + var WEB_MERCATOR_MAX_BOUNDS = [ + [-Infinity, -90], + [Infinity, 90] + ]; + function lngLatToWorld2([lng, lat]) { + if (Math.abs(lat) > 90) { + lat = Math.sign(lat) * 90; + } + if (Number.isFinite(lng)) { + const [x, y2] = lngLatToWorld([lng, lat]); + return [x, clamp(y2, 0, WEB_MERCATOR_TILE_SIZE)]; + } + const [, y] = lngLatToWorld([0, lat]); + return [lng, clamp(y, 0, WEB_MERCATOR_TILE_SIZE)]; + } + var MapState = class extends ViewState { + constructor(options) { + const { + /** Mapbox viewport properties */ + /** The width of the viewport */ + width, + /** The height of the viewport */ + height, + /** The latitude at the center of the viewport */ + latitude, + /** The longitude at the center of the viewport */ + longitude, + /** The tile zoom level of the map. */ + zoom, + /** The bearing of the viewport in degrees */ + bearing = 0, + /** The pitch of the viewport in degrees */ + pitch = 0, + /** + * Specify the altitude of the viewport camera + * Unit: map heights, default 1.5 + * Non-public API, see https://github.com/mapbox/mapbox-gl-js/issues/1137 + */ + altitude = 1.5, + /** Viewport position */ + position = [0, 0, 0], + /** Viewport constraints */ + maxZoom = 20, + minZoom = 0, + maxPitch = 60, + minPitch = 0, + /** Interaction states, required to calculate change during transform */ + /* The point on map being grabbed when the operation first started */ + startPanLngLat, + /* Center of the zoom when the operation first started */ + startZoomLngLat, + /* Pointer position when rotation started */ + startRotatePos, + /* The lng/lat point at the rotation pivot (where rotation started) */ + startRotateLngLat, + /** Bearing when current perspective rotate operation started */ + startBearing, + /** Pitch when current perspective rotate operation started */ + startPitch, + /** Zoom when current zoom operation started */ + startZoom, + /** Normalize viewport props to fit map height into viewport */ + normalize: normalize5 = true + } = options; + assert8(Number.isFinite(longitude)); + assert8(Number.isFinite(latitude)); + assert8(Number.isFinite(zoom)); + const maxBounds = options.maxBounds || (normalize5 ? WEB_MERCATOR_MAX_BOUNDS : null); + super({ + width, + height, + latitude, + longitude, + zoom, + bearing, + pitch, + altitude, + maxZoom, + minZoom, + maxPitch, + minPitch, + normalize: normalize5, + position, + maxBounds + }, { + startPanLngLat, + startZoomLngLat, + startRotatePos, + startRotateLngLat, + startBearing, + startPitch, + startZoom + }, options.makeViewport); + this.getAltitude = options.getAltitude; + } + /** + * Start panning + * @param {[Number, Number]} pos - position on screen where the pointer grabs + */ + panStart({ pos }) { + return this._getUpdatedState({ + startPanLngLat: this._unproject(pos) + }); + } + /** + * Pan + * @param {[Number, Number]} pos - position on screen where the pointer is + * @param {[Number, Number], optional} startPos - where the pointer grabbed at + * the start of the operation. Must be supplied of `panStart()` was not called + */ + pan({ pos, startPos }) { + const startPanLngLat = this.getState().startPanLngLat || this._unproject(startPos); + if (!startPanLngLat) { + return this; + } + const viewport = this.makeViewport(this.getViewportProps()); + const newProps = viewport.panByPosition(startPanLngLat, pos); + return this._getUpdatedState(newProps); + } + /** + * End panning + * Must call if `panStart()` was called + */ + panEnd() { + return this._getUpdatedState({ + startPanLngLat: null + }); + } + /** + * Start rotating + * @param {[Number, Number]} pos - position on screen where the center is + */ + rotateStart({ pos }) { + const altitude = this.getAltitude?.(pos); + return this._getUpdatedState({ + startRotatePos: pos, + startRotateLngLat: altitude !== void 0 ? this._unproject3D(pos, altitude) : void 0, + startBearing: this.getViewportProps().bearing, + startPitch: this.getViewportProps().pitch + }); + } + /** + * Rotate + * @param {[Number, Number]} pos - position on screen where the center is + */ + rotate({ pos, deltaAngleX = 0, deltaAngleY = 0 }) { + const { startRotatePos, startRotateLngLat, startBearing, startPitch } = this.getState(); + if (!startRotatePos || startBearing === void 0 || startPitch === void 0) { + return this; + } + let newRotation; + if (pos) { + newRotation = this._getNewRotation(pos, startRotatePos, startPitch, startBearing); + } else { + newRotation = { + bearing: startBearing + deltaAngleX, + pitch: startPitch + deltaAngleY + }; + } + if (startRotateLngLat) { + const rotatedViewport = this.makeViewport({ + ...this.getViewportProps(), + ...newRotation + }); + const panMethod = "panByPosition3D" in rotatedViewport ? "panByPosition3D" : "panByPosition"; + return this._getUpdatedState({ + ...newRotation, + ...rotatedViewport[panMethod](startRotateLngLat, startRotatePos) + }); + } + return this._getUpdatedState(newRotation); + } + /** + * End rotating + * Must call if `rotateStart()` was called + */ + rotateEnd() { + return this._getUpdatedState({ + startRotatePos: null, + startRotateLngLat: null, + startBearing: null, + startPitch: null + }); + } + /** + * Start zooming + * @param {[Number, Number]} pos - position on screen where the center is + */ + zoomStart({ pos }) { + return this._getUpdatedState({ + startZoomLngLat: this._unproject(pos), + startZoom: this.getViewportProps().zoom + }); + } + /** + * Zoom + * @param {[Number, Number]} pos - position on screen where the current center is + * @param {[Number, Number]} startPos - the center position at + * the start of the operation. Must be supplied of `zoomStart()` was not called + * @param {Number} scale - a number between [0, 1] specifying the accumulated + * relative scale. + */ + zoom({ pos, startPos, scale: scale5 }) { + let { startZoom, startZoomLngLat } = this.getState(); + if (!startZoomLngLat) { + startZoom = this.getViewportProps().zoom; + startZoomLngLat = this._unproject(startPos) || this._unproject(pos); + } + if (!startZoomLngLat) { + return this; + } + const zoom = this._constrainZoom(startZoom + Math.log2(scale5)); + const zoomedViewport = this.makeViewport({ ...this.getViewportProps(), zoom }); + return this._getUpdatedState({ + zoom, + ...zoomedViewport.panByPosition(startZoomLngLat, pos) + }); + } + /** + * End zooming + * Must call if `zoomStart()` was called + */ + zoomEnd() { + return this._getUpdatedState({ + startZoomLngLat: null, + startZoom: null + }); + } + zoomIn(speed = 2) { + return this._zoomFromCenter(speed); + } + zoomOut(speed = 2) { + return this._zoomFromCenter(1 / speed); + } + moveLeft(speed = 100) { + return this._panFromCenter([speed, 0]); + } + moveRight(speed = 100) { + return this._panFromCenter([-speed, 0]); + } + moveUp(speed = 100) { + return this._panFromCenter([0, speed]); + } + moveDown(speed = 100) { + return this._panFromCenter([0, -speed]); + } + rotateLeft(speed = 15) { + return this._getUpdatedState({ + bearing: this.getViewportProps().bearing - speed + }); + } + rotateRight(speed = 15) { + return this._getUpdatedState({ + bearing: this.getViewportProps().bearing + speed + }); + } + rotateUp(speed = 10) { + return this._getUpdatedState({ + pitch: this.getViewportProps().pitch + speed + }); + } + rotateDown(speed = 10) { + return this._getUpdatedState({ + pitch: this.getViewportProps().pitch - speed + }); + } + shortestPathFrom(viewState) { + const fromProps = viewState.getViewportProps(); + const props = { ...this.getViewportProps() }; + const { bearing, longitude } = props; + if (Math.abs(bearing - fromProps.bearing) > 180) { + props.bearing = bearing < 0 ? bearing + 360 : bearing - 360; + } + if (Math.abs(longitude - fromProps.longitude) > 180) { + props.longitude = longitude < 0 ? longitude + 360 : longitude - 360; + } + return props; + } + // Apply any constraints (mathematical or defined by _viewportProps) to map state + applyConstraints(props) { + const { maxPitch, minPitch, pitch, longitude, bearing, normalize: normalize5, maxBounds } = props; + if (normalize5) { + if (longitude < -180 || longitude > 180) { + props.longitude = mod2(longitude + 180, 360) - 180; + } + if (bearing < -180 || bearing > 180) { + props.bearing = mod2(bearing + 180, 360) - 180; + } + } + props.pitch = clamp(pitch, minPitch, maxPitch); + props.zoom = this._constrainZoom(props.zoom, props); + if (maxBounds) { + const bl = lngLatToWorld2(maxBounds[0]); + const tr = lngLatToWorld2(maxBounds[1]); + const scale5 = 2 ** props.zoom; + const halfWidth = props.width / 2 / scale5; + const halfHeight = props.height / 2 / scale5; + const [minLng, minLat] = worldToLngLat([bl[0] + halfWidth, bl[1] + halfHeight]); + const [maxLng, maxLat] = worldToLngLat([tr[0] - halfWidth, tr[1] - halfHeight]); + props.longitude = clamp(props.longitude, minLng, maxLng); + props.latitude = clamp(props.latitude, minLat, maxLat); + } + return props; + } + /* Private methods */ + _constrainZoom(zoom, props) { + props || (props = this.getViewportProps()); + const { maxZoom, maxBounds } = props; + const shouldApplyMaxBounds = maxBounds !== null && props.width > 0 && props.height > 0; + let { minZoom } = props; + if (shouldApplyMaxBounds) { + const bl = lngLatToWorld2(maxBounds[0]); + const tr = lngLatToWorld2(maxBounds[1]); + const w = tr[0] - bl[0]; + const h = tr[1] - bl[1]; + if (Number.isFinite(w) && w > 0) { + minZoom = Math.max(minZoom, Math.log2(props.width / w)); + } + if (Number.isFinite(h) && h > 0) { + minZoom = Math.max(minZoom, Math.log2(props.height / h)); + } + if (minZoom > maxZoom) + minZoom = maxZoom; + } + return clamp(zoom, minZoom, maxZoom); + } + _zoomFromCenter(scale5) { + const { width, height } = this.getViewportProps(); + return this.zoom({ + pos: [width / 2, height / 2], + scale: scale5 + }); + } + _panFromCenter(offset) { + const { width, height } = this.getViewportProps(); + return this.pan({ + startPos: [width / 2, height / 2], + pos: [width / 2 + offset[0], height / 2 + offset[1]] + }); + } + _getUpdatedState(newProps) { + return new this.constructor({ + makeViewport: this.makeViewport, + ...this.getViewportProps(), + ...this.getState(), + ...newProps + }); + } + _unproject(pos) { + const viewport = this.makeViewport(this.getViewportProps()); + return pos && viewport.unproject(pos); + } + _unproject3D(pos, altitude) { + const viewport = this.makeViewport(this.getViewportProps()); + return viewport.unproject(pos, { targetZ: altitude }); + } + _getNewRotation(pos, startPos, startPitch, startBearing) { + const deltaX = pos[0] - startPos[0]; + const deltaY = pos[1] - startPos[1]; + const centerY = pos[1]; + const startY = startPos[1]; + const { width, height } = this.getViewportProps(); + const deltaScaleX = deltaX / width; + let deltaScaleY = 0; + if (deltaY > 0) { + if (Math.abs(height - startY) > PITCH_MOUSE_THRESHOLD) { + deltaScaleY = deltaY / (startY - height) * PITCH_ACCEL; + } + } else if (deltaY < 0) { + if (startY > PITCH_MOUSE_THRESHOLD) { + deltaScaleY = 1 - centerY / startY; + } + } + deltaScaleY = clamp(deltaScaleY, -1, 1); + const { minPitch, maxPitch } = this.getViewportProps(); + const bearing = startBearing + 180 * deltaScaleX; + let pitch = startPitch; + if (deltaScaleY > 0) { + pitch = startPitch + deltaScaleY * (maxPitch - startPitch); + } else if (deltaScaleY < 0) { + pitch = startPitch - deltaScaleY * (minPitch - startPitch); + } + return { + pitch, + bearing + }; + } + }; + var MapController = class extends Controller { + constructor() { + super(...arguments); + this.ControllerState = MapState; + this.transition = { + transitionDuration: 300, + transitionInterpolator: new LinearInterpolator({ + transitionProps: { + compare: ["longitude", "latitude", "zoom", "bearing", "pitch", "position"], + required: ["longitude", "latitude", "zoom"] + } + }) + }; + this.dragMode = "pan"; + this.rotationPivot = "center"; + this._getAltitude = (pos) => { + if (this.rotationPivot === "2d") { + return 0; + } else if (this.rotationPivot === "3d") { + if (this.pickPosition) { + const { x, y } = this.props; + const pickResult = this.pickPosition(x + pos[0], y + pos[1]); + if (pickResult && pickResult.coordinate && pickResult.coordinate.length >= 3) { + return pickResult.coordinate[2]; + } + } + } + return void 0; + }; + } + setProps(props) { + if ("rotationPivot" in props) { + this.rotationPivot = props.rotationPivot || "center"; + } + props.getAltitude = this._getAltitude; + props.position = props.position || [0, 0, 0]; + props.maxBounds = props.maxBounds || (props.normalize === false ? null : WEB_MERCATOR_MAX_BOUNDS); + super.setProps(props); + } + updateViewport(newControllerState, extraProps = null, interactionState = {}) { + const state = newControllerState.getState(); + if (interactionState.isDragging && state.startRotateLngLat) { + interactionState = { + ...interactionState, + rotationPivotPosition: state.startRotateLngLat + }; + } else if (interactionState.isDragging === false) { + interactionState = { ...interactionState, rotationPivotPosition: void 0 }; + } + super.updateViewport(newControllerState, extraProps, interactionState); + } + }; + + // node_modules/@deck.gl/core/dist/views/map-view.js + var MapView = class extends View { + constructor(props = {}) { + super(props); + } + getViewportType() { + return web_mercator_viewport_default; + } + get ControllerType() { + return MapController; + } + }; + MapView.displayName = "MapView"; + var map_view_default = MapView; + + // node_modules/@deck.gl/core/dist/lib/effect-manager.js + var DEFAULT_LIGHTING_EFFECT = new LightingEffect(); + function compareEffects(e1, e22) { + const o1 = e1.order ?? Infinity; + const o2 = e22.order ?? Infinity; + return o1 - o2; + } + var EffectManager = class { + constructor(context) { + this._resolvedEffects = []; + this._defaultEffects = []; + this.effects = []; + this._context = context; + this._needsRedraw = "Initial render"; + this._setEffects([]); + } + /** + * Register a new default effect, i.e. an effect presents regardless of user supplied props.effects + */ + addDefaultEffect(effect) { + const defaultEffects = this._defaultEffects; + if (!defaultEffects.find((e) => e.id === effect.id)) { + const index2 = defaultEffects.findIndex((e) => compareEffects(e, effect) > 0); + if (index2 < 0) { + defaultEffects.push(effect); + } else { + defaultEffects.splice(index2, 0, effect); + } + effect.setup(this._context); + this._setEffects(this.effects); + } + } + setProps(props) { + if ("effects" in props) { + if (!deepEqual2(props.effects, this.effects, 1)) { + this._setEffects(props.effects); + } + } + } + needsRedraw(opts = { clearRedrawFlags: false }) { + const redraw = this._needsRedraw; + if (opts.clearRedrawFlags) { + this._needsRedraw = false; + } + return redraw; + } + getEffects() { + return this._resolvedEffects; + } + _setEffects(effects) { + const oldEffectsMap = {}; + for (const effect of this.effects) { + oldEffectsMap[effect.id] = effect; + } + const nextEffects = []; + for (const effect of effects) { + const oldEffect = oldEffectsMap[effect.id]; + let effectToAdd = effect; + if (oldEffect && oldEffect !== effect) { + if (oldEffect.setProps) { + oldEffect.setProps(effect.props); + effectToAdd = oldEffect; + } else { + oldEffect.cleanup(this._context); + } + } else if (!oldEffect) { + effect.setup(this._context); + } + nextEffects.push(effectToAdd); + delete oldEffectsMap[effect.id]; + } + for (const removedEffectId in oldEffectsMap) { + oldEffectsMap[removedEffectId].cleanup(this._context); + } + this.effects = nextEffects; + this._resolvedEffects = nextEffects.concat(this._defaultEffects); + if (!effects.some((effect) => effect instanceof LightingEffect)) { + this._resolvedEffects.push(DEFAULT_LIGHTING_EFFECT); + } + this._needsRedraw = "effects changed"; + } + finalize() { + for (const effect of this._resolvedEffects) { + effect.cleanup(this._context); + } + this.effects.length = 0; + this._resolvedEffects.length = 0; + this._defaultEffects.length = 0; + } + }; + + // node_modules/@deck.gl/core/dist/passes/draw-layers-pass.js + var DrawLayersPass = class extends LayersPass { + shouldDrawLayer(layer) { + const { operation } = layer.props; + return operation.includes("draw") || operation.includes("terrain"); + } + render(options) { + return this._render(options); + } + }; + + // node_modules/@deck.gl/core/dist/lib/deck-renderer.js + var TRACE_RENDER_LAYERS = "deckRenderer.renderLayers"; + var DeckRenderer = class { + constructor(device, opts = {}) { + this.device = device; + this.stats = opts.stats; + this.layerFilter = null; + this.drawPickingColors = false; + this.drawLayersPass = new DrawLayersPass(device); + this.pickLayersPass = new PickLayersPass(device); + this.renderCount = 0; + this._needsRedraw = "Initial render"; + this.renderBuffers = []; + this.lastPostProcessEffect = null; + } + setProps(props) { + if (this.layerFilter !== props.layerFilter) { + this.layerFilter = props.layerFilter; + this._needsRedraw = "layerFilter changed"; + } + if (this.drawPickingColors !== props.drawPickingColors) { + this.drawPickingColors = props.drawPickingColors; + this._needsRedraw = "drawPickingColors changed"; + } + } + renderLayers(opts) { + if (!opts.viewports.length) { + return; + } + const layerPass = this.drawPickingColors ? this.pickLayersPass : this.drawLayersPass; + const renderOpts = { + layerFilter: this.layerFilter, + isPicking: this.drawPickingColors, + ...opts + }; + if (renderOpts.effects) { + this._preRender(renderOpts.effects, renderOpts); + } + const outputBuffer = this.lastPostProcessEffect ? this.renderBuffers[0] : renderOpts.target; + if (this.lastPostProcessEffect) { + renderOpts.clearColor = [0, 0, 0, 0]; + renderOpts.clearCanvas = true; + } + const renderResult = layerPass.render({ ...renderOpts, target: outputBuffer }); + const renderStats = "stats" in renderResult ? renderResult.stats : renderResult; + if (renderOpts.effects) { + if (this.lastPostProcessEffect) { + renderOpts.clearCanvas = opts.clearCanvas === void 0 ? true : opts.clearCanvas; + } + this._postRender(renderOpts.effects, renderOpts); + } + this.renderCount++; + debug(TRACE_RENDER_LAYERS, this, renderStats, opts); + this._updateStats(renderStats); + } + needsRedraw(opts = { clearRedrawFlags: false }) { + const redraw = this._needsRedraw; + if (opts.clearRedrawFlags) { + this._needsRedraw = false; + } + return redraw; + } + finalize() { + const { renderBuffers } = this; + for (const buffer of renderBuffers) { + buffer.delete(); + } + renderBuffers.length = 0; + } + _updateStats(source3) { + if (!this.stats) + return; + let layersCount = 0; + for (const { visibleCount } of source3) { + layersCount += visibleCount; + } + this.stats.get("Layers rendered").addCount(layersCount); + } + _preRender(effects, opts) { + this.lastPostProcessEffect = null; + opts.preRenderStats = opts.preRenderStats || {}; + for (const effect of effects) { + opts.preRenderStats[effect.id] = effect.preRender(opts); + if (effect.postRender) { + this.lastPostProcessEffect = effect.id; + } + } + if (this.lastPostProcessEffect) { + this._resizeRenderBuffers(); + } + } + _resizeRenderBuffers() { + const { renderBuffers } = this; + const size = this.device.canvasContext.getDrawingBufferSize(); + const [width, height] = size; + if (renderBuffers.length === 0) { + [0, 1].map((i) => { + const texture = this.device.createTexture({ + sampler: { minFilter: "linear", magFilter: "linear" }, + width, + height + }); + renderBuffers.push(this.device.createFramebuffer({ + id: `deck-renderbuffer-${i}`, + colorAttachments: [texture] + })); + }); + } + for (const buffer of renderBuffers) { + buffer.resize(size); + } + } + _postRender(effects, opts) { + const { renderBuffers } = this; + const params = { + ...opts, + inputBuffer: renderBuffers[0], + swapBuffer: renderBuffers[1] + }; + for (const effect of effects) { + if (effect.postRender) { + params.target = effect.id === this.lastPostProcessEffect ? opts.target : void 0; + const buffer = effect.postRender(params); + params.inputBuffer = buffer; + params.swapBuffer = buffer === renderBuffers[0] ? renderBuffers[1] : renderBuffers[0]; + } + } + } + }; + + // node_modules/@deck.gl/core/dist/lib/deck-picker.js + init_dist4(); + + // node_modules/@deck.gl/core/dist/lib/picking/query-object.js + var NO_PICKED_OBJECT = { + pickedColor: null, + pickedObjectIndex: -1 + }; + function getClosestObject({ pickedColors, decodePickingColor, deviceX, deviceY, deviceRadius, deviceRect }) { + const { x, y, width, height } = deviceRect; + let minSquareDistanceToCenter = deviceRadius * deviceRadius; + let closestPixelIndex = -1; + let i = 0; + for (let row = 0; row < height; row++) { + const dy = row + y - deviceY; + const dy2 = dy * dy; + if (dy2 > minSquareDistanceToCenter) { + i += 4 * width; + } else { + for (let col = 0; col < width; col++) { + const pickedLayerIndex = pickedColors[i + 3] - 1; + if (pickedLayerIndex >= 0) { + const dx = col + x - deviceX; + const d2 = dx * dx + dy2; + if (d2 <= minSquareDistanceToCenter) { + minSquareDistanceToCenter = d2; + closestPixelIndex = i; + } + } + i += 4; + } + } + } + if (closestPixelIndex >= 0) { + const pickedColor = pickedColors.slice(closestPixelIndex, closestPixelIndex + 4); + const pickedObject = decodePickingColor(pickedColor); + if (pickedObject) { + const dy = Math.floor(closestPixelIndex / 4 / width); + const dx = closestPixelIndex / 4 - dy * width; + return { + ...pickedObject, + pickedColor, + pickedX: x + dx, + pickedY: y + dy + }; + } + log_default.error("Picked non-existent layer. Is picking buffer corrupt?")(); + } + return NO_PICKED_OBJECT; + } + function getUniqueObjects({ pickedColors, decodePickingColor }) { + const uniqueColors = /* @__PURE__ */ new Map(); + if (pickedColors) { + for (let i = 0; i < pickedColors.length; i += 4) { + const pickedLayerIndex = pickedColors[i + 3] - 1; + if (pickedLayerIndex >= 0) { + const pickedColor = pickedColors.slice(i, i + 4); + const colorKey = pickedColor.join(","); + if (!uniqueColors.has(colorKey)) { + const pickedObject = decodePickingColor(pickedColor); + if (pickedObject) { + uniqueColors.set(colorKey, { + ...pickedObject, + color: pickedColor + }); + } else { + log_default.error("Picked non-existent layer. Is picking buffer corrupt?")(); + } + } + } + } + } + return Array.from(uniqueColors.values()); + } + + // node_modules/@deck.gl/core/dist/lib/picking/pick-info.js + function getEmptyPickingInfo({ pickInfo, viewports, pixelRatio, x, y, z }) { + let pickedViewport = viewports[0]; + if (viewports.length > 1) { + pickedViewport = getViewportFromCoordinates(pickInfo?.pickedViewports || viewports, { x, y }); + } + let coordinate; + if (pickedViewport) { + const point = [x - pickedViewport.x, y - pickedViewport.y]; + if (z !== void 0) { + point[2] = z; + } + coordinate = pickedViewport.unproject(point); + } + return { + color: null, + layer: null, + viewport: pickedViewport, + index: -1, + picked: false, + x, + y, + pixel: [x, y], + coordinate, + devicePixel: pickInfo && "pickedX" in pickInfo ? [pickInfo.pickedX, pickInfo.pickedY] : void 0, + pixelRatio + }; + } + function processPickInfo(opts) { + const { pickInfo, lastPickedInfo, mode, layers } = opts; + const { pickedColor, pickedLayer, pickedObjectIndex } = pickInfo; + const affectedLayers = pickedLayer ? [pickedLayer] : []; + if (mode === "hover") { + const lastPickedPixelIndex = lastPickedInfo.index; + const lastPickedLayerId = lastPickedInfo.layerId; + const pickedLayerId = pickedLayer ? pickedLayer.props.id : null; + if (pickedLayerId !== lastPickedLayerId || pickedObjectIndex !== lastPickedPixelIndex) { + if (pickedLayerId !== lastPickedLayerId) { + const lastPickedLayer = layers.find((layer) => layer.props.id === lastPickedLayerId); + if (lastPickedLayer) { + affectedLayers.unshift(lastPickedLayer); + } + } + lastPickedInfo.layerId = pickedLayerId; + lastPickedInfo.index = pickedObjectIndex; + lastPickedInfo.info = null; + } + } + const baseInfo = getEmptyPickingInfo(opts); + const infos = /* @__PURE__ */ new Map(); + infos.set(null, baseInfo); + affectedLayers.forEach((layer) => { + let info = { ...baseInfo }; + if (layer === pickedLayer) { + info.color = pickedColor; + info.index = pickedObjectIndex; + info.picked = true; + } + info = getLayerPickingInfo({ layer, info, mode }); + const rootLayer = info.layer; + if (layer === pickedLayer && mode === "hover") { + lastPickedInfo.info = info; + } + infos.set(rootLayer.id, info); + if (mode === "hover") { + rootLayer.updateAutoHighlight(info); + } + }); + return infos; + } + function getLayerPickingInfo({ layer, info, mode }) { + while (layer && info) { + const sourceLayer = info.layer || null; + info.sourceLayer = sourceLayer; + info.layer = layer; + info = layer.getPickingInfo({ info, mode, sourceLayer }); + layer = layer.parent; + } + return info; + } + function getViewportFromCoordinates(viewports, pixel) { + for (let i = viewports.length - 1; i >= 0; i--) { + const viewport = viewports[i]; + if (viewport.containsPixel(pixel)) { + return viewport; + } + } + return viewports[0]; + } + + // node_modules/@deck.gl/core/dist/lib/deck-picker.js + var DeckPicker = class { + constructor(device, opts = {}) { + this._pickable = true; + this.device = device; + this.stats = opts.stats; + this.pickLayersPass = new PickLayersPass(device); + this.lastPickedInfo = { + index: -1, + layerId: null, + info: null + }; + } + setProps(props) { + if ("layerFilter" in props) { + this.layerFilter = props.layerFilter; + } + if ("_pickable" in props) { + this._pickable = props._pickable; + } + } + finalize() { + if (this.pickingFBO) { + this.pickingFBO.destroy(); + } + if (this.depthFBO) { + this.depthFBO.destroy(); + } + } + /** + * Pick the closest info at given coordinate + * @returns Promise that resolves with picking info + */ + pickObjectAsync(opts) { + return this._pickClosestObjectAsync(opts); + } + /** + * Picks a list of unique infos within a bounding box + * @returns Promise that resolves to all unique infos within a bounding box + */ + pickObjectsAsync(opts) { + return this._pickVisibleObjectsAsync(opts); + } + /** + * Pick the closest info at given coordinate + * @returns picking info + * @note WebGL only - use pickObjectAsync instead + */ + pickObject(opts) { + return this._pickClosestObject(opts); + } + /** + * Get all unique infos within a bounding box + * @returns all unique infos within a bounding box + * @note WebGL only - use pickObjectAsync instead + */ + pickObjects(opts) { + return this._pickVisibleObjects(opts); + } + // Returns a new picking info object by assuming the last picked object is still picked + getLastPickedObject({ x, y, layers, viewports }, lastPickedInfo = this.lastPickedInfo.info) { + const lastPickedLayerId = lastPickedInfo && lastPickedInfo.layer && lastPickedInfo.layer.id; + const lastPickedViewportId = lastPickedInfo && lastPickedInfo.viewport && lastPickedInfo.viewport.id; + const layer = lastPickedLayerId ? layers.find((l) => l.id === lastPickedLayerId) : null; + const viewport = lastPickedViewportId && viewports.find((v) => v.id === lastPickedViewportId) || viewports[0]; + const coordinate = viewport && viewport.unproject([x - viewport.x, y - viewport.y]); + const info = { + x, + y, + viewport, + coordinate, + layer + }; + return { ...lastPickedInfo, ...info }; + } + // Private + /** Ensures that picking framebuffer exists and matches the canvas size */ + _resizeBuffer() { + if (!this.pickingFBO) { + const pickingColorTexture = this.device.createTexture({ + format: "rgba8unorm", + width: 1, + height: 1, + usage: Texture.RENDER_ATTACHMENT | Texture.COPY_SRC + }); + this.pickingFBO = this.device.createFramebuffer({ + colorAttachments: [pickingColorTexture], + depthStencilAttachment: "depth16unorm" + }); + if (this.device.isTextureFormatRenderable("rgba32float")) { + const depthColorTexture = this.device.createTexture({ + format: "rgba32float", + width: 1, + height: 1, + usage: Texture.RENDER_ATTACHMENT | Texture.COPY_SRC + }); + const depthFBO = this.device.createFramebuffer({ + colorAttachments: [depthColorTexture], + depthStencilAttachment: "depth16unorm" + }); + this.depthFBO = depthFBO; + } + } + const { canvas } = this.device.getDefaultCanvasContext(); + this.pickingFBO?.resize({ width: canvas.width, height: canvas.height }); + this.depthFBO?.resize({ width: canvas.width, height: canvas.height }); + } + /** Preliminary filtering of the layers list. Skid picking pass if no layer is pickable. */ + _getPickable(layers) { + if (this._pickable === false) { + return null; + } + const pickableLayers = layers.filter((layer) => this.pickLayersPass.shouldDrawLayer(layer) && !layer.isComposite); + return pickableLayers.length ? pickableLayers : null; + } + /** + * Pick the closest object at the given coordinate + */ + // eslint-disable-next-line max-statements,complexity + async _pickClosestObjectAsync({ layers, views, viewports, x, y, radius = 0, depth = 1, mode = "query", unproject3D, onViewportActive, effects }) { + const pixelRatio = this.device.canvasContext.cssToDeviceRatio(); + const pickableLayers = this._getPickable(layers); + if (!pickableLayers || viewports.length === 0) { + return { + result: [], + emptyInfo: getEmptyPickingInfo({ viewports, x, y, pixelRatio }) + }; + } + this._resizeBuffer(); + const devicePixelRange = this.device.canvasContext.cssToDevicePixels([x, y], true); + const devicePixel = [ + devicePixelRange.x + Math.floor(devicePixelRange.width / 2), + devicePixelRange.y + Math.floor(devicePixelRange.height / 2) + ]; + const deviceRadius = Math.round(radius * pixelRatio); + const { width, height } = this.pickingFBO; + const deviceRect = this._getPickingRect({ + deviceX: devicePixel[0], + deviceY: devicePixel[1], + deviceRadius, + deviceWidth: width, + deviceHeight: height + }); + const cullRect = { + x: x - radius, + y: y - radius, + width: radius * 2 + 1, + height: radius * 2 + 1 + }; + let infos; + const result = []; + const affectedLayers = /* @__PURE__ */ new Set(); + for (let i = 0; i < depth; i++) { + let pickInfo; + if (deviceRect) { + const pickedResult = await this._drawAndSampleAsync({ + layers: pickableLayers, + views, + viewports, + onViewportActive, + deviceRect, + cullRect, + effects, + pass: `picking:${mode}` + }); + pickInfo = getClosestObject({ + ...pickedResult, + deviceX: devicePixel[0], + deviceY: devicePixel[1], + deviceRadius, + deviceRect + }); + } else { + pickInfo = { + pickedColor: null, + pickedObjectIndex: -1 + }; + } + let z; + const depthLayers = this._getDepthLayers(pickInfo, pickableLayers, unproject3D); + if (depthLayers.length > 0) { + const { pickedColors: pickedColors2 } = await this._drawAndSampleAsync({ + layers: depthLayers, + views, + viewports, + onViewportActive, + deviceRect: { + x: pickInfo.pickedX ?? devicePixel[0], + y: pickInfo.pickedY ?? devicePixel[1], + width: 1, + height: 1 + }, + cullRect, + effects, + pass: `picking:${mode}:z` + }, true); + if (pickedColors2[3]) { + z = pickedColors2[0]; + } + } + if (pickInfo.pickedLayer && i + 1 < depth) { + affectedLayers.add(pickInfo.pickedLayer); + pickInfo.pickedLayer.disablePickingIndex(pickInfo.pickedObjectIndex); + } + infos = processPickInfo({ + pickInfo, + lastPickedInfo: this.lastPickedInfo, + mode, + layers: pickableLayers, + viewports, + x, + y, + z, + pixelRatio + }); + for (const info of infos.values()) { + if (info.layer) { + result.push(info); + } + } + if (!pickInfo.pickedColor) { + break; + } + } + for (const layer of affectedLayers) { + layer.restorePickingColors(); + } + return { result, emptyInfo: infos.get(null) }; + } + /** + * Pick the closest object at the given coordinate + * @deprecated WebGL only + */ + // eslint-disable-next-line max-statements,complexity + _pickClosestObject({ layers, views, viewports, x, y, radius = 0, depth = 1, mode = "query", unproject3D, onViewportActive, effects }) { + const pixelRatio = this.device.canvasContext.cssToDeviceRatio(); + const pickableLayers = this._getPickable(layers); + if (!pickableLayers || viewports.length === 0) { + return { + result: [], + emptyInfo: getEmptyPickingInfo({ viewports, x, y, pixelRatio }) + }; + } + this._resizeBuffer(); + const devicePixelRange = this.device.canvasContext.cssToDevicePixels([x, y], true); + const devicePixel = [ + devicePixelRange.x + Math.floor(devicePixelRange.width / 2), + devicePixelRange.y + Math.floor(devicePixelRange.height / 2) + ]; + const deviceRadius = Math.round(radius * pixelRatio); + const { width, height } = this.pickingFBO; + const deviceRect = this._getPickingRect({ + deviceX: devicePixel[0], + deviceY: devicePixel[1], + deviceRadius, + deviceWidth: width, + deviceHeight: height + }); + const cullRect = { + x: x - radius, + y: y - radius, + width: radius * 2 + 1, + height: radius * 2 + 1 + }; + let infos; + const result = []; + const affectedLayers = /* @__PURE__ */ new Set(); + for (let i = 0; i < depth; i++) { + let pickInfo; + if (deviceRect) { + const pickedResult = this._drawAndSample({ + layers: pickableLayers, + views, + viewports, + onViewportActive, + deviceRect, + cullRect, + effects, + pass: `picking:${mode}` + }); + pickInfo = getClosestObject({ + ...pickedResult, + deviceX: devicePixel[0], + deviceY: devicePixel[1], + deviceRadius, + deviceRect + }); + } else { + pickInfo = { + pickedColor: null, + pickedObjectIndex: -1 + }; + } + let z; + const depthLayers = this._getDepthLayers(pickInfo, pickableLayers, unproject3D); + if (depthLayers.length > 0) { + const { pickedColors: pickedColors2 } = this._drawAndSample({ + layers: depthLayers, + views, + viewports, + onViewportActive, + deviceRect: { + x: pickInfo.pickedX ?? devicePixel[0], + y: pickInfo.pickedY ?? devicePixel[1], + width: 1, + height: 1 + }, + cullRect, + effects, + pass: `picking:${mode}:z` + }, true); + if (pickedColors2[3]) { + z = pickedColors2[0]; + } + } + if (pickInfo.pickedLayer && i + 1 < depth) { + affectedLayers.add(pickInfo.pickedLayer); + pickInfo.pickedLayer.disablePickingIndex(pickInfo.pickedObjectIndex); + } + infos = processPickInfo({ + pickInfo, + lastPickedInfo: this.lastPickedInfo, + mode, + layers: pickableLayers, + viewports, + x, + y, + z, + pixelRatio + }); + for (const info of infos.values()) { + if (info.layer) { + result.push(info); + } + } + if (!pickInfo.pickedColor) { + break; + } + } + for (const layer of affectedLayers) { + layer.restorePickingColors(); + } + return { result, emptyInfo: infos.get(null) }; + } + /** + * Pick all objects within the given bounding box + */ + // eslint-disable-next-line max-statements + async _pickVisibleObjectsAsync({ layers, views, viewports, x, y, width = 1, height = 1, mode = "query", maxObjects = null, onViewportActive, effects }) { + const pickableLayers = this._getPickable(layers); + if (!pickableLayers || viewports.length === 0) { + return []; + } + this._resizeBuffer(); + const pixelRatio = this.device.canvasContext.cssToDeviceRatio(); + const leftTop = this.device.canvasContext.cssToDevicePixels([x, y], true); + const deviceLeft = leftTop.x; + const deviceTop = leftTop.y + leftTop.height; + const rightBottom = this.device.canvasContext.cssToDevicePixels([x + width, y + height], true); + const deviceRight = rightBottom.x + rightBottom.width; + const deviceBottom = rightBottom.y; + const deviceRect = { + x: deviceLeft, + y: deviceBottom, + // deviceTop and deviceRight represent the first pixel outside the desired rect + width: deviceRight - deviceLeft, + height: deviceTop - deviceBottom + }; + const pickedResult = await this._drawAndSampleAsync({ + layers: pickableLayers, + views, + viewports, + onViewportActive, + deviceRect, + cullRect: { x, y, width, height }, + effects, + pass: `picking:${mode}` + }); + const pickInfos = getUniqueObjects(pickedResult); + const uniquePickedObjects = /* @__PURE__ */ new Map(); + const uniqueInfos = []; + const limitMaxObjects = Number.isFinite(maxObjects); + for (let i = 0; i < pickInfos.length; i++) { + if (limitMaxObjects && uniqueInfos.length >= maxObjects) { + break; + } + const pickInfo = pickInfos[i]; + let info = { + color: pickInfo.pickedColor, + layer: null, + index: pickInfo.pickedObjectIndex, + picked: true, + x, + y, + pixelRatio + }; + info = getLayerPickingInfo({ layer: pickInfo.pickedLayer, info, mode }); + const pickedLayerId = info.layer.id; + if (!uniquePickedObjects.has(pickedLayerId)) { + uniquePickedObjects.set(pickedLayerId, /* @__PURE__ */ new Set()); + } + const uniqueObjectsInLayer = uniquePickedObjects.get(pickedLayerId); + const pickedObjectKey = info.object ?? info.index; + if (!uniqueObjectsInLayer.has(pickedObjectKey)) { + uniqueObjectsInLayer.add(pickedObjectKey); + uniqueInfos.push(info); + } + } + return uniqueInfos; + } + /** + * Pick all objects within the given bounding box + * @deprecated WebGL only + */ + // eslint-disable-next-line max-statements + _pickVisibleObjects({ layers, views, viewports, x, y, width = 1, height = 1, mode = "query", maxObjects = null, onViewportActive, effects }) { + const pickableLayers = this._getPickable(layers); + if (!pickableLayers || viewports.length === 0) { + return []; + } + this._resizeBuffer(); + const pixelRatio = this.device.canvasContext.cssToDeviceRatio(); + const leftTop = this.device.canvasContext.cssToDevicePixels([x, y], true); + const deviceLeft = leftTop.x; + const deviceTop = leftTop.y + leftTop.height; + const rightBottom = this.device.canvasContext.cssToDevicePixels([x + width, y + height], true); + const deviceRight = rightBottom.x + rightBottom.width; + const deviceBottom = rightBottom.y; + const deviceRect = { + x: deviceLeft, + y: deviceBottom, + // deviceTop and deviceRight represent the first pixel outside the desired rect + width: deviceRight - deviceLeft, + height: deviceTop - deviceBottom + }; + const pickedResult = this._drawAndSample({ + layers: pickableLayers, + views, + viewports, + onViewportActive, + deviceRect, + cullRect: { x, y, width, height }, + effects, + pass: `picking:${mode}` + }); + const pickInfos = getUniqueObjects(pickedResult); + const uniquePickedObjects = /* @__PURE__ */ new Map(); + const uniqueInfos = []; + const limitMaxObjects = Number.isFinite(maxObjects); + for (let i = 0; i < pickInfos.length; i++) { + if (limitMaxObjects && uniqueInfos.length >= maxObjects) { + break; + } + const pickInfo = pickInfos[i]; + let info = { + color: pickInfo.pickedColor, + layer: null, + index: pickInfo.pickedObjectIndex, + picked: true, + x, + y, + pixelRatio + }; + info = getLayerPickingInfo({ layer: pickInfo.pickedLayer, info, mode }); + const pickedLayerId = info.layer.id; + if (!uniquePickedObjects.has(pickedLayerId)) { + uniquePickedObjects.set(pickedLayerId, /* @__PURE__ */ new Set()); + } + const uniqueObjectsInLayer = uniquePickedObjects.get(pickedLayerId); + const pickedObjectKey = info.object ?? info.index; + if (!uniqueObjectsInLayer.has(pickedObjectKey)) { + uniqueObjectsInLayer.add(pickedObjectKey); + uniqueInfos.push(info); + } + } + return uniqueInfos; + } + // Note: Implementation of the overloaded signatures above, TSDoc is on the signatures + async _drawAndSampleAsync({ layers, views, viewports, onViewportActive, deviceRect, cullRect, effects, pass }, pickZ = false) { + const pickingFBO = pickZ ? this.depthFBO : this.pickingFBO; + const opts = { + layers, + layerFilter: this.layerFilter, + views, + viewports, + onViewportActive, + pickingFBO, + deviceRect, + cullRect, + effects, + pass, + pickZ, + preRenderStats: {}, + isPicking: true + }; + for (const effect of effects) { + if (effect.useInPicking) { + opts.preRenderStats[effect.id] = effect.preRender(opts); + } + } + const { decodePickingColor, stats } = this.pickLayersPass.render(opts); + this._updateStats(stats); + const { x, y, width, height } = deviceRect; + const texture = pickingFBO.colorAttachments[0]?.texture; + if (!texture) { + throw new Error("Picking framebuffer color attachment is missing"); + } + const pickedColors = await this._readTextureDataAsync(texture, { x, y, width, height }, pickZ ? Float32Array : Uint8Array); + if (!pickZ) { + let hasNonZeroAlpha = false; + for (let i = 3; i < pickedColors.length; i += 4) { + if (pickedColors[i] !== 0) { + hasNonZeroAlpha = true; + break; + } + } + if (!hasNonZeroAlpha && pickedColors.length > 0) { + log_default.warn("Async pick readback returned only zero alpha values", { + deviceRect, + bytes: Array.from(pickedColors.subarray(0, Math.min(pickedColors.length, 16))) + })(); + } + } + return { pickedColors, decodePickingColor }; + } + async _readTextureDataAsync(texture, options, ArrayType) { + const { width, height } = options; + const layout = texture.computeMemoryLayout(options); + const readBuffer = this.device.createBuffer({ + byteLength: layout.byteLength, + usage: Buffer2.COPY_DST | Buffer2.MAP_READ + }); + try { + texture.readBuffer(options, readBuffer); + const readData = await readBuffer.readAsync(0, layout.byteLength); + const bytesPerElement = ArrayType.BYTES_PER_ELEMENT; + if (layout.bytesPerRow % bytesPerElement !== 0) { + throw new Error(`Texture readback row stride ${layout.bytesPerRow} is not aligned to ${bytesPerElement}-byte elements.`); + } + const source3 = new ArrayType(readData.buffer, readData.byteOffset, layout.byteLength / bytesPerElement); + const packedRowLength = width * 4; + const sourceRowLength = layout.bytesPerRow / bytesPerElement; + if (sourceRowLength < packedRowLength) { + throw new Error(`Texture readback row stride ${sourceRowLength} is smaller than packed row length ${packedRowLength}.`); + } + const packed = new ArrayType(width * height * 4); + for (let row = 0; row < height; row++) { + const sourceStart = row * sourceRowLength; + packed.set(source3.subarray(sourceStart, sourceStart + packedRowLength), row * packedRowLength); + } + return packed; + } finally { + readBuffer.destroy(); + } + } + // Note: Implementation of the overloaded signatures above, TSDoc is on the signatures + _drawAndSample({ layers, views, viewports, onViewportActive, deviceRect, cullRect, effects, pass }, pickZ = false) { + const pickingFBO = pickZ ? this.depthFBO : this.pickingFBO; + const opts = { + layers, + layerFilter: this.layerFilter, + views, + viewports, + onViewportActive, + pickingFBO, + deviceRect, + cullRect, + effects, + pass, + pickZ, + preRenderStats: {}, + isPicking: true + }; + for (const effect of effects) { + if (effect.useInPicking) { + opts.preRenderStats[effect.id] = effect.preRender(opts); + } + } + const { decodePickingColor, stats } = this.pickLayersPass.render(opts); + this._updateStats(stats); + const { x, y, width, height } = deviceRect; + const pickedColors = new (pickZ ? Float32Array : Uint8Array)(width * height * 4); + this.device.readPixelsToArrayWebGL(pickingFBO, { + sourceX: x, + sourceY: y, + sourceWidth: width, + sourceHeight: height, + target: pickedColors + }); + return { pickedColors, decodePickingColor }; + } + _updateStats(source3) { + if (!this.stats) + return; + let layersCount = 0; + for (const { visibleCount } of source3) { + layersCount += visibleCount; + } + this.stats.get("Layers picked").addCount(layersCount); + } + /** + * Determine which layers to use for the depth (pickZ) pass. + * - If a non-draped layer was picked, use just that layer. + * - If a draped layer was picked (geometry is at z=0) or no layer was picked + * (e.g. no-FBO tiles at extreme zoom), fall back to terrain layers. + */ + _getDepthLayers(pickInfo, pickableLayers, unproject3D) { + if (!unproject3D || !this.depthFBO) { + return []; + } + const { pickedLayer } = pickInfo; + const isDraped = pickedLayer?.state?.terrainDrawMode === "drape"; + if (pickedLayer && !isDraped) { + return [pickedLayer]; + } + return pickableLayers.filter((l) => l.props.operation.includes("terrain")); + } + /** + * Calculate a picking rect centered on deviceX and deviceY and clipped to device + * @returns null if pixel is outside of device + */ + _getPickingRect({ deviceX, deviceY, deviceRadius, deviceWidth, deviceHeight }) { + const x = Math.max(0, deviceX - deviceRadius); + const y = Math.max(0, deviceY - deviceRadius); + const width = Math.min(deviceWidth, deviceX + deviceRadius + 1) - x; + const height = Math.min(deviceHeight, deviceY + deviceRadius + 1) - y; + if (width <= 0 || height <= 0) { + return null; + } + return { x, y, width, height }; + } + }; + + // node_modules/@deck.gl/core/dist/lib/widget-manager.js + var PLACEMENTS = { + "top-left": { top: 0, left: 0 }, + "top-right": { top: 0, right: 0 }, + "bottom-left": { bottom: 0, left: 0 }, + "bottom-right": { bottom: 0, right: 0 }, + fill: { top: 0, left: 0, bottom: 0, right: 0 } + }; + var DEFAULT_PLACEMENT = "top-left"; + var ROOT_CONTAINER_ID = "root"; + var WidgetManager = class { + constructor({ deck, parentElement }) { + this.defaultWidgets = []; + this.widgets = []; + this.resolvedWidgets = []; + this.containers = {}; + this.lastViewports = {}; + this.deck = deck; + parentElement?.classList.add("deck-widget-container"); + this.parentElement = parentElement; + } + getWidgets() { + return this.resolvedWidgets; + } + /** Declarative API to configure widgets */ + setProps(props) { + if (props.widgets && !deepEqual2(props.widgets, this.widgets, 1)) { + const nextWidgets = props.widgets.filter(Boolean); + this._setWidgets(nextWidgets); + } + } + finalize() { + for (const widget of this.getWidgets()) { + this._removeWidget(widget); + } + this.defaultWidgets.length = 0; + this.resolvedWidgets.length = 0; + for (const id in this.containers) { + this.containers[id].remove(); + } + } + /** Imperative API. Widgets added this way are not affected by the declarative prop. */ + addDefault(widget) { + if (!this.defaultWidgets.find((w) => w.id === widget.id)) { + this._addWidget(widget); + this.defaultWidgets.push(widget); + this._setWidgets(this.widgets); + } + } + onRedraw({ viewports, layers }) { + const viewportsById = viewports.reduce((acc, v) => { + acc[v.id] = v; + return acc; + }, {}); + for (const widget of this.getWidgets()) { + const { viewId } = widget; + if (viewId) { + const viewport = viewportsById[viewId]; + if (viewport) { + if (widget.onViewportChange) { + widget.onViewportChange(viewport); + } + widget.onRedraw?.({ viewports: [viewport], layers }); + } + } else { + if (widget.onViewportChange) { + for (const viewport of viewports) { + widget.onViewportChange(viewport); + } + } + widget.onRedraw?.({ viewports, layers }); + } + } + this.lastViewports = viewportsById; + this._updateContainers(); + } + onHover(info, event) { + for (const widget of this.getWidgets()) { + const { viewId } = widget; + if (!viewId || viewId === info.viewport?.id) { + widget.onHover?.(info, event); + } + } + } + onEvent(info, event) { + const eventHandlerProp = EVENT_HANDLERS[event.type]; + if (!eventHandlerProp) { + return; + } + for (const widget of this.getWidgets()) { + const { viewId } = widget; + if (!viewId || viewId === info.viewport?.id) { + widget[eventHandlerProp]?.(info, event); + } + } + } + // INTERNAL METHODS + /** + * Resolve widgets from the declarative prop + * Initialize new widgets and remove old ones + * Update props of existing widgets + */ + _setWidgets(nextWidgets) { + const oldWidgetMap = {}; + for (const widget of this.resolvedWidgets) { + oldWidgetMap[widget.id] = widget; + } + this.resolvedWidgets.length = 0; + for (const widget of this.defaultWidgets) { + oldWidgetMap[widget.id] = null; + this.resolvedWidgets.push(widget); + } + for (let widget of nextWidgets) { + const oldWidget = oldWidgetMap[widget.id]; + if (!oldWidget) { + this._addWidget(widget); + } else if ( + // Widget placement changed + oldWidget.viewId !== widget.viewId || oldWidget.placement !== widget.placement + ) { + this._removeWidget(oldWidget); + this._addWidget(widget); + } else if (widget !== oldWidget) { + oldWidget.setProps(widget.props); + widget = oldWidget; + } + oldWidgetMap[widget.id] = null; + this.resolvedWidgets.push(widget); + } + for (const id in oldWidgetMap) { + const oldWidget = oldWidgetMap[id]; + if (oldWidget) { + this._removeWidget(oldWidget); + } + } + this.widgets = nextWidgets; + } + /** Initialize new widget */ + _addWidget(widget) { + const { viewId = null, placement = DEFAULT_PLACEMENT } = widget; + const container = widget.props._container ?? viewId; + widget.widgetManager = this; + widget.deck = this.deck; + widget.rootElement = widget._onAdd({ deck: this.deck, viewId }); + if (widget.rootElement) { + this._getContainer(container, placement).append(widget.rootElement); + } + widget.updateHTML(); + } + /** Destroy an old widget */ + _removeWidget(widget) { + widget.onRemove?.(); + if (widget.rootElement) { + widget.rootElement.remove(); + } + widget.rootElement = void 0; + widget.deck = void 0; + widget.widgetManager = void 0; + } + /** Get a container element based on view and placement */ + _getContainer(viewIdOrContainer, placement) { + if (viewIdOrContainer && typeof viewIdOrContainer !== "string") { + return viewIdOrContainer; + } + const containerId = viewIdOrContainer || ROOT_CONTAINER_ID; + let viewContainer = this.containers[containerId]; + if (!viewContainer) { + viewContainer = document.createElement("div"); + viewContainer.style.pointerEvents = "none"; + viewContainer.style.position = "absolute"; + viewContainer.style.overflow = "hidden"; + this.parentElement?.append(viewContainer); + this.containers[containerId] = viewContainer; + } + let container = viewContainer.querySelector(`.${placement}`); + if (!container) { + container = globalThis.document.createElement("div"); + container.className = placement; + container.style.position = "absolute"; + container.style.zIndex = "2"; + Object.assign(container.style, PLACEMENTS[placement]); + viewContainer.append(container); + } + return container; + } + _updateContainers() { + const canvasWidth = this.deck.width; + const canvasHeight = this.deck.height; + for (const id in this.containers) { + const viewport = this.lastViewports[id] || null; + const visible = id === ROOT_CONTAINER_ID || viewport; + const container = this.containers[id]; + if (visible) { + container.style.display = "block"; + container.style.left = `${viewport ? viewport.x : 0}px`; + container.style.top = `${viewport ? viewport.y : 0}px`; + container.style.width = `${viewport ? viewport.width : canvasWidth}px`; + container.style.height = `${viewport ? viewport.height : canvasHeight}px`; + } else { + container.style.display = "none"; + } + } + } + }; + + // node_modules/@deck.gl/core/dist/utils/apply-styles.js + function applyStyles(element, style) { + if (style) { + Object.entries(style).map(([key, value]) => { + if (key.startsWith("--")) { + element.style.setProperty(key, value); + } else { + element.style[key] = value; + } + }); + } + } + function removeStyles(element, style) { + if (style) { + Object.keys(style).map((key) => { + if (key.startsWith("--")) { + element.style.removeProperty(key); + } else { + element.style[key] = ""; + } + }); + } + } + + // node_modules/@deck.gl/core/dist/lib/widget.js + var Widget = class { + constructor(props) { + this.viewId = null; + this.props = { + // @ts-expect-error `defaultProps` may not exist on constructor + ...this.constructor.defaultProps, + ...props + }; + this.id = this.props.id; + } + /** Called to update widget options */ + setProps(props) { + const oldProps = this.props; + const el = this.rootElement; + if (el && oldProps.className !== props.className) { + if (oldProps.className) + el.classList.remove(oldProps.className); + if (props.className) + el.classList.add(props.className); + } + if (el && !deepEqual2(oldProps.style, props.style, 1)) { + removeStyles(el, oldProps.style); + applyStyles(el, props.style); + } + Object.assign(this.props, props); + this.updateHTML(); + } + /** Update the HTML to reflect latest props and state */ + updateHTML() { + if (this.rootElement) { + this.onRenderHTML(this.rootElement); + } + } + // VIEW STATE HELPERS + get viewIds() { + return this.viewId ? [this.viewId] : this.deck?.getViews().map((v) => v.id) ?? []; + } + /** Returns the current view state for the given view */ + getViewState(viewId) { + return this.deck?.viewManager?.getViewState(viewId) || {}; + } + /** Updates the view state for the given view */ + setViewState(viewId, viewState) { + this.deck?._onViewStateChange({ viewId, viewState, interactionState: {} }); + } + // @note empty method calls have an overhead in V8 but it is very low, ~1ns + /** + * Common utility to create the root DOM element for this widget + * Configures the top-level styles and adds basic class names for theming + * @returns an UI element that should be appended to the Deck container + */ + onCreateRootElement() { + const CLASS_NAMES = [ + // Add class names for theming + "deck-widget", + this.className, + // plus any app-supplied class name + this.props.className + ]; + const element = document.createElement("div"); + CLASS_NAMES.filter((cls) => typeof cls === "string" && cls.length > 0).forEach((className) => element.classList.add(className)); + applyStyles(element, this.props.style); + return element; + } + /** Internal API called by Deck when the widget is first added to a Deck instance */ + _onAdd(params) { + return this.onAdd(params) ?? this.onCreateRootElement(); + } + /** Overridable by subclass - called when the widget is first added to a Deck instance + * @returns an optional UI element that should be appended to the Deck container + */ + onAdd(params) { + } + /** Called when the widget is removed */ + onRemove() { + } + // deck integration - Event hooks + /** Called when the containing view is changed */ + onViewportChange(viewport) { + } + /** Called when the containing view is redrawn */ + onRedraw(params) { + } + /** Called when a hover event occurs */ + onHover(info, event) { + } + /** Called when a click event occurs */ + onClick(info, event) { + } + /** Called when a drag event occurs */ + onDrag(info, event) { + } + /** Called when a dragstart event occurs */ + onDragStart(info, event) { + } + /** Called when a dragend event occurs */ + onDragEnd(info, event) { + } + }; + Widget.defaultProps = { + id: "widget", + style: {}, + _container: null, + className: "" + }; + + // node_modules/@deck.gl/core/dist/lib/tooltip-widget.js + var defaultStyle = { + zIndex: "1", + position: "absolute", + pointerEvents: "none", + color: "#a0a7b4", + backgroundColor: "#29323c", + padding: "10px", + top: "0", + left: "0", + display: "none" + }; + var TooltipWidget = class extends Widget { + constructor(props = {}) { + super(props); + this.id = "default-tooltip"; + this.placement = "fill"; + this.className = "deck-tooltip"; + this.isVisible = false; + this.setProps(props); + } + // TODO(ib) - does this really need to be overridden? + onCreateRootElement() { + const el = document.createElement("div"); + el.className = this.className; + Object.assign(el.style, defaultStyle); + return el; + } + onRenderHTML(rootElement) { + } + onViewportChange(viewport) { + if (this.isVisible && viewport.id === this.lastViewport?.id && !viewport.equals(this.lastViewport)) { + this.setTooltip(null); + } + this.lastViewport = viewport; + } + onHover(info) { + const { deck } = this; + const getTooltip = deck && deck.props.getTooltip; + if (!getTooltip) { + return; + } + const displayInfo = getTooltip(info); + this.setTooltip(displayInfo, info.x, info.y); + } + setTooltip(displayInfo, x, y) { + const el = this.rootElement; + if (!el) { + return; + } + if (typeof displayInfo === "string") { + el.innerText = displayInfo; + } else if (!displayInfo) { + this.isVisible = false; + el.style.display = "none"; + return; + } else { + if (displayInfo.text) { + el.innerText = displayInfo.text; + } + if (displayInfo.html) { + el.innerHTML = displayInfo.html; + } + if (displayInfo.className) { + el.className = displayInfo.className; + } + } + this.isVisible = true; + el.style.display = "block"; + el.style.transform = `translate(${x}px, ${y}px)`; + if (displayInfo && typeof displayInfo === "object" && "style" in displayInfo) { + Object.assign(el.style, displayInfo.style); + } + } + }; + TooltipWidget.defaultProps = { + ...Widget.defaultProps + }; + + // node_modules/@deck.gl/core/dist/lib/deck.js + init_dist4(); + init_dist5(); + init_dist3(); + function noop3() { + } + var getCursor = ({ isDragging }) => isDragging ? "grabbing" : "grab"; + var defaultProps = { + id: "", + width: "100%", + height: "100%", + style: null, + viewState: null, + initialViewState: null, + pickingRadius: 0, + pickAsync: "auto", + layerFilter: null, + parameters: {}, + parent: null, + device: null, + deviceProps: {}, + gl: null, + canvas: null, + layers: [], + effects: [], + views: null, + controller: null, + // Rely on external controller, e.g. react-map-gl + useDevicePixels: true, + touchAction: "none", + eventRecognizerOptions: {}, + _framebuffer: null, + _animate: false, + _pickable: true, + _typedArrayManagerProps: {}, + _customRender: null, + widgets: [], + onDeviceInitialized: noop3, + onWebGLInitialized: noop3, + onResize: noop3, + onViewStateChange: noop3, + onInteractionStateChange: noop3, + onBeforeRender: noop3, + onAfterRender: noop3, + onLoad: noop3, + onError: (error) => log_default.error(error.message, error.cause)(), + onHover: null, + onClick: null, + onDragStart: null, + onDrag: null, + onDragEnd: null, + _onMetrics: null, + getCursor, + getTooltip: null, + debug: false, + drawPickingColors: false + }; + var Deck = class { + constructor(props) { + this.width = 0; + this.height = 0; + this.userData = {}; + this.device = null; + this.canvas = null; + this.viewManager = null; + this.layerManager = null; + this.effectManager = null; + this.deckRenderer = null; + this.deckPicker = null; + this.eventManager = null; + this.widgetManager = null; + this.tooltip = null; + this.animationLoop = null; + this.cursorState = { + isHovering: false, + isDragging: false + }; + this.stats = new Stats({ id: "deck.gl" }); + this.metrics = { + fps: 0, + setPropsTime: 0, + layersCount: 0, + drawLayersCount: 0, + updateLayersCount: 0, + updateAttributesCount: 0, + updateAttributesTime: 0, + framesRedrawn: 0, + pickTime: 0, + pickCount: 0, + pickLayersCount: 0, + gpuTime: 0, + gpuTimePerFrame: 0, + cpuTime: 0, + cpuTimePerFrame: 0, + bufferMemory: 0, + textureMemory: 0, + renderbufferMemory: 0, + gpuMemory: 0 + }; + this._metricsCounter = 0; + this._hoverPickSequence = 0; + this._pointerDownPickSequence = 0; + this._needsRedraw = "Initial render"; + this._pickRequest = { + mode: "hover", + x: -1, + y: -1, + radius: 0, + event: null, + unproject3D: false + }; + this._lastPointerDownInfo = null; + this._lastPointerDownInfoPromise = null; + this._onPointerMove = (event) => { + const { _pickRequest } = this; + if (event.type === "pointerleave") { + _pickRequest.x = -1; + _pickRequest.y = -1; + _pickRequest.radius = 0; + } else if (event.leftButton || event.rightButton) { + return; + } else { + const pos = event.offsetCenter; + if (!pos) { + return; + } + _pickRequest.x = pos.x; + _pickRequest.y = pos.y; + _pickRequest.radius = this.props.pickingRadius; + } + if (this.layerManager) { + this.layerManager.context.mousePosition = { x: _pickRequest.x, y: _pickRequest.y }; + } + _pickRequest.event = event; + }; + this._onEvent = (event) => { + const eventHandlerProp = EVENT_HANDLERS[event.type]; + const pos = event.offsetCenter; + if (!eventHandlerProp || !pos || !this.layerManager) { + return; + } + const layers = this.layerManager.getLayers(); + const internalPickingMode = this._getInternalPickingMode(); + if (!internalPickingMode) { + return; + } + if (internalPickingMode === "sync") { + const info = event.type === "click" && this._shouldUnproject3D(layers) ? this._getFirstPickedInfo(this._pickPointSync(this._getPointPickOptions(pos.x, pos.y, { unproject3D: true }, layers))) : this._getLastPointerDownPickingInfo(pos.x, pos.y, layers); + this._dispatchPickingEvent(info, event); + return; + } + const pointerDownInfoPromise = this._lastPointerDownInfoPromise || Promise.resolve(this._getLastPointerDownPickingInfo(pos.x, pos.y, layers)); + pointerDownInfoPromise.then((info) => { + this._dispatchPickingEvent(info, event); + }).catch((error) => this.props.onError?.(error)); + }; + this._onPointerDown = (event) => { + const pos = event.offsetCenter; + if (!pos) { + return; + } + const internalPickingMode = this._getInternalPickingMode(); + if (!internalPickingMode) { + return; + } + const layers = this.layerManager?.getLayers() || []; + const pointerDownPickSequence = ++this._pointerDownPickSequence; + if (internalPickingMode === "sync") { + const pickedInfo = this._pickPointSync({ + x: pos.x, + y: pos.y, + radius: this.props.pickingRadius + }); + const info = this._getFirstPickedInfo(pickedInfo); + this._lastPointerDownInfo = info; + this._lastPointerDownInfoPromise = Promise.resolve(info); + return; + } + const pickPromise = this._pickPointAsync(this._getPointPickOptions(pos.x, pos.y, {}, layers)).then((pickResult) => this._getFirstPickedInfo(pickResult)).then((info) => { + if (pointerDownPickSequence === this._pointerDownPickSequence) { + this._lastPointerDownInfo = info; + } + return info; + }).catch((error) => { + this.props.onError?.(error); + const fallbackInfo = this.deckPicker && this.viewManager ? this._getLastPointerDownPickingInfo(pos.x, pos.y, layers) : {}; + if (pointerDownPickSequence === this._pointerDownPickSequence) { + this._lastPointerDownInfo = fallbackInfo; + } + return fallbackInfo; + }); + this._lastPointerDownInfo = null; + this._lastPointerDownInfoPromise = pickPromise; + }; + this.props = { ...defaultProps, ...props }; + props = this.props; + if (props.viewState && props.initialViewState) { + log_default.warn("View state tracking is disabled. Use either `initialViewState` for auto update or `viewState` for manual update.")(); + } + this.viewState = this.props.initialViewState; + if (props.device) { + this.device = props.device; + } + let deviceOrPromise = this.device; + if (!deviceOrPromise && props.gl) { + if (props.gl instanceof WebGLRenderingContext) { + log_default.error("WebGL1 context not supported.")(); + } + const userOnResize = this.props.deviceProps?.onResize; + deviceOrPromise = webgl2Adapter.attach(props.gl, { + // Enable shader and pipeline caching for attached devices (matches _createDevice defaults) + // Without this, interleaved mode (e.g., MapboxOverlay) creates new pipelines every frame + _cacheShaders: true, + _cachePipelines: true, + ...this.props.deviceProps, + onResize: (canvasContext, info) => { + const { width, height } = canvasContext.canvas; + canvasContext.setDrawingBufferSize(width, height); + this._needsRedraw = "Canvas resized"; + userOnResize?.(canvasContext, info); + } + }); + } + if (!deviceOrPromise) { + deviceOrPromise = this._createDevice(props); + } + this.animationLoop = this._createAnimationLoop(deviceOrPromise, props); + this.setProps(props); + if (props._typedArrayManagerProps) { + typed_array_manager_default.setOptions(props._typedArrayManagerProps); + } + this.animationLoop.start(); + } + /** Stop rendering and dispose all resources */ + finalize() { + this.animationLoop?.stop(); + this.animationLoop?.destroy(); + this.animationLoop = null; + this._hoverPickSequence++; + this._pointerDownPickSequence++; + this._lastPointerDownInfo = null; + this._lastPointerDownInfoPromise = null; + this.layerManager?.finalize(); + this.layerManager = null; + this.viewManager?.finalize(); + this.viewManager = null; + this.effectManager?.finalize(); + this.effectManager = null; + this.deckRenderer?.finalize(); + this.deckRenderer = null; + this.deckPicker?.finalize(); + this.deckPicker = null; + this.eventManager?.destroy(); + this.eventManager = null; + this.widgetManager?.finalize(); + this.widgetManager = null; + if (!this.props.canvas && !this.props.device && !this.props.gl && this.canvas) { + this.canvas.parentElement?.removeChild(this.canvas); + this.canvas = null; + } + } + /** Partially update props */ + setProps(props) { + this.stats.get("setProps Time").timeStart(); + if ("onLayerHover" in props) { + log_default.removed("onLayerHover", "onHover")(); + } + if ("onLayerClick" in props) { + log_default.removed("onLayerClick", "onClick")(); + } + if (props.initialViewState && // depth = 3 when comparing viewStates: viewId.position.0 + !deepEqual2(this.props.initialViewState, props.initialViewState, 3)) { + this.viewState = props.initialViewState; + } + Object.assign(this.props, props); + this._validateInternalPickingMode(); + this._setCanvasSize(this.props); + const resolvedProps = Object.create(this.props); + Object.assign(resolvedProps, { + views: this._getViews(), + width: this.width, + height: this.height, + viewState: this._getViewState() + }); + if (props.device && props.device.id !== this.device?.id) { + this.animationLoop?.stop(); + if (this.canvas !== props.device.canvasContext?.canvas) { + this.canvas?.remove(); + this.eventManager?.destroy(); + this.canvas = null; + } + log_default.log(`recreating animation loop for new device! id=${props.device.id}`)(); + this.animationLoop = this._createAnimationLoop(props.device, props); + this.animationLoop.start(); + } + this.animationLoop?.setProps(resolvedProps); + if (props.useDevicePixels !== void 0 && this.device?.canvasContext?.setProps) { + this.device.canvasContext.setProps({ useDevicePixels: props.useDevicePixels }); + } + if (this.layerManager) { + this.viewManager.setProps(resolvedProps); + this.layerManager.activateViewport(this.getViewports()[0]); + this.layerManager.setProps(resolvedProps); + this.effectManager.setProps(resolvedProps); + this.deckRenderer.setProps(resolvedProps); + this.deckPicker.setProps(resolvedProps); + this.widgetManager.setProps(resolvedProps); + } + this.stats.get("setProps Time").timeEnd(); + } + // Public API + /** + * Check if a redraw is needed + * @returns `false` or a string summarizing the redraw reason + */ + needsRedraw(opts = { clearRedrawFlags: false }) { + if (!this.layerManager) { + return false; + } + if (this.props._animate) { + return "Deck._animate"; + } + let redraw = this._needsRedraw; + if (opts.clearRedrawFlags) { + this._needsRedraw = false; + } + const viewManagerNeedsRedraw = this.viewManager.needsRedraw(opts); + const layerManagerNeedsRedraw = this.layerManager.needsRedraw(opts); + const effectManagerNeedsRedraw = this.effectManager.needsRedraw(opts); + const deckRendererNeedsRedraw = this.deckRenderer.needsRedraw(opts); + redraw = redraw || viewManagerNeedsRedraw || layerManagerNeedsRedraw || effectManagerNeedsRedraw || deckRendererNeedsRedraw; + return redraw; + } + /** + * Redraw the GL context + * @param reason If not provided, only redraw if deemed necessary. Otherwise redraw regardless of internal states. + * @returns + */ + redraw(reason) { + if (!this.layerManager) { + return; + } + let redrawReason = this.needsRedraw({ clearRedrawFlags: true }); + redrawReason = reason || redrawReason; + if (!redrawReason) { + return; + } + this.stats.get("Redraw Count").incrementCount(); + if (this.props._customRender) { + this.props._customRender(redrawReason); + } else { + this._drawLayers(redrawReason); + } + } + /** Flag indicating that the Deck instance has initialized its resources and it's safe to call public methods. */ + get isInitialized() { + return this.viewManager !== null; + } + /** Get a list of views that are currently rendered */ + getViews() { + assert8(this.viewManager); + return this.viewManager.views; + } + /** Get a view by id */ + getView(viewId) { + assert8(this.viewManager); + return this.viewManager.getView(viewId); + } + /** Get a list of viewports that are currently rendered. + * @param rect If provided, only returns viewports within the given bounding box. + */ + getViewports(rect) { + assert8(this.viewManager); + return this.viewManager.getViewports(rect); + } + /** Get the current canvas element. */ + getCanvas() { + return this.canvas; + } + /** Query the object rendered on top at a given point */ + async pickObjectAsync(opts) { + const infos = (await this._pickAsync("pickObjectAsync", "pickObject Time", opts)).result; + return infos.length ? infos[0] : null; + } + /** + * Query all objects rendered on top within a bounding box + * @note Caveat: this method performs multiple async GPU queries, so state could potentially change between calls. + */ + async pickObjectsAsync(opts) { + return await this._pickAsync("pickObjectsAsync", "pickObjects Time", opts); + } + /** + * Query the object rendered on top at a given point + * @deprecated WebGL only. Use `pickObjectsAsync` instead + */ + pickObject(opts) { + const infos = this._pick("pickObject", "pickObject Time", opts).result; + return infos.length ? infos[0] : null; + } + /** + * Query all rendered objects at a given point + * @deprecated WebGL only. Use `pickObjectsAsync` instead + */ + pickMultipleObjects(opts) { + opts.depth = opts.depth || 10; + return this._pick("pickObject", "pickMultipleObjects Time", opts).result; + } + /** + * Query all objects rendered on top within a bounding box + * @deprecated WebGL only. Use `pickObjectsAsync` instead + */ + pickObjects(opts) { + return this._pick("pickObjects", "pickObjects Time", opts); + } + /** + * Internal method used by controllers to pick 3D position at a screen coordinate + * @private + */ + _pickPositionForController(x, y) { + const internalPickingMode = this._getInternalPickingMode(); + if (internalPickingMode !== "sync") { + return null; + } + return this.pickObject({ x, y, radius: 0, unproject3D: true }); + } + /** Experimental + * Add a global resource for sharing among layers + */ + _addResources(resources, forceUpdate = false) { + for (const id in resources) { + this.layerManager.resourceManager.add({ resourceId: id, data: resources[id], forceUpdate }); + } + } + /** Experimental + * Remove a global resource + */ + _removeResources(resourceIds) { + for (const id of resourceIds) { + this.layerManager.resourceManager.remove(id); + } + } + /** Experimental + * Register a default effect. Effects will be sorted by order, those with a low order will be rendered first + */ + _addDefaultEffect(effect) { + this.effectManager.addDefaultEffect(effect); + } + _addDefaultShaderModule(module) { + this.layerManager.addDefaultShaderModule(module); + } + _removeDefaultShaderModule(module) { + this.layerManager?.removeDefaultShaderModule(module); + } + // Private Methods + _resolveInternalPickingMode() { + const { pickAsync } = this.props; + const deviceType = this.device?.type || this.props.deviceProps?.type; + if (pickAsync === "auto") { + return deviceType === "webgpu" ? "async" : "sync"; + } + if (pickAsync === "sync" && deviceType === "webgpu") { + throw new Error('`pickAsync: "sync"` is not supported when Deck is using a WebGPU device.'); + } + return pickAsync; + } + _getInternalPickingMode() { + try { + return this._resolveInternalPickingMode(); + } catch (error) { + this.props.onError?.(error); + return null; + } + } + _validateInternalPickingMode() { + this._getInternalPickingMode(); + } + _getFirstPickedInfo({ result, emptyInfo }) { + return result[0] || emptyInfo; + } + _shouldUnproject3D(layers = this.layerManager?.getLayers() || []) { + return layers.some((layer) => layer.props.pickable === "3d"); + } + _getPointPickOptions(x, y, opts = {}, layers = this.layerManager?.getLayers() || []) { + return { + x, + y, + radius: this.props.pickingRadius, + unproject3D: this._shouldUnproject3D(layers), + ...opts + }; + } + _pickPointSync(opts) { + return this._pick("pickObject", "pickObject Time", opts); + } + _pickPointAsync(opts) { + return this._pickAsync("pickObjectAsync", "pickObject Time", opts); + } + _getLastPointerDownPickingInfo(x, y, layers = this.layerManager?.getLayers() || []) { + return this.deckPicker.getLastPickedObject({ + x, + y, + layers, + viewports: this.getViewports({ x, y }) + }, this._lastPointerDownInfo); + } + _applyHoverCallbacks({ result, emptyInfo }, event) { + if (!this.widgetManager) { + return; + } + this.cursorState.isHovering = result.length > 0; + let pickedInfo = emptyInfo; + let handled = false; + for (const info of result) { + pickedInfo = info; + handled = info.layer?.onHover(info, event) || handled; + } + if (!handled) { + this.props.onHover?.(pickedInfo, event); + this.widgetManager.onHover(pickedInfo, event); + } + } + _dispatchPickingEvent(info, event) { + if (!this.layerManager || !this.widgetManager) { + return; + } + const eventHandlerProp = EVENT_HANDLERS[event.type]; + if (!eventHandlerProp) { + return; + } + const { layer } = info; + const layerHandler = layer && (layer[eventHandlerProp] || layer.props[eventHandlerProp]); + const rootHandler = this.props[eventHandlerProp]; + let handled = false; + if (layerHandler) { + handled = layerHandler.call(layer, info, event); + } + if (!handled) { + rootHandler?.(info, event); + this.widgetManager.onEvent(info, event); + } + } + _pickAsync(method, statKey, opts) { + assert8(this.deckPicker); + const { stats } = this; + stats.get("Pick Count").incrementCount(); + stats.get(statKey).timeStart(); + const infos = this.deckPicker[method]({ + // layerManager, viewManager and effectManager are always defined if deckPicker is + layers: this.layerManager.getLayers(opts), + views: this.viewManager.getViews(), + viewports: this.getViewports(opts), + onViewportActive: this.layerManager.activateViewport, + effects: this.effectManager.getEffects(), + ...opts + }); + stats.get(statKey).timeEnd(); + return infos; + } + _pick(method, statKey, opts) { + assert8(this.deckPicker); + const { stats } = this; + stats.get("Pick Count").incrementCount(); + stats.get(statKey).timeStart(); + const infos = this.deckPicker[method]({ + // layerManager, viewManager and effectManager are always defined if deckPicker is + layers: this.layerManager.getLayers(opts), + views: this.viewManager.getViews(), + viewports: this.getViewports(opts), + onViewportActive: this.layerManager.activateViewport, + effects: this.effectManager.getEffects(), + ...opts + }); + stats.get(statKey).timeEnd(); + return infos; + } + /** Resolve props.canvas to element */ + _createCanvas(props) { + let canvas = props.canvas; + if (typeof canvas === "string") { + canvas = document.getElementById(canvas); + assert8(canvas); + } + if (!canvas) { + canvas = document.createElement("canvas"); + canvas.id = props.id || "deckgl-overlay"; + if (props.width && typeof props.width === "number") { + canvas.width = props.width; + } + if (props.height && typeof props.height === "number") { + canvas.height = props.height; + } + const parent = props.parent || document.body; + parent.appendChild(canvas); + } + Object.assign(canvas.style, props.style); + return canvas; + } + /** Updates canvas width and/or height, if provided as props */ + _setCanvasSize(props) { + if (!this.canvas) { + return; + } + const { width, height } = props; + if (width || width === 0) { + const cssWidth = Number.isFinite(width) ? `${width}px` : width; + this.canvas.style.width = cssWidth; + } + if (height || height === 0) { + const cssHeight = Number.isFinite(height) ? `${height}px` : height; + this.canvas.style.position = props.style?.position || "absolute"; + this.canvas.style.height = cssHeight; + } + } + /** If canvas size has changed, reads out the new size and update */ + _updateCanvasSize() { + const { canvas } = this; + if (!canvas) { + return; + } + const newWidth = canvas.clientWidth ?? canvas.width; + const newHeight = canvas.clientHeight ?? canvas.height; + if (newWidth !== this.width || newHeight !== this.height) { + this.width = newWidth; + this.height = newHeight; + this.viewManager?.setProps({ width: newWidth, height: newHeight }); + this.layerManager?.activateViewport(this.getViewports()[0]); + this.props.onResize({ width: newWidth, height: newHeight }); + } + } + _createAnimationLoop(deviceOrPromise, props) { + const { + // width, + // height, + gl, + // debug, + onError + // onBeforeRender, + // onAfterRender, + } = props; + return new AnimationLoop({ + device: deviceOrPromise, + // TODO v9 + autoResizeDrawingBuffer: !gl, + // do not auto resize external context + autoResizeViewport: false, + // @ts-expect-error luma.gl needs to accept Promise return value + onInitialize: (context) => this._setDevice(context.device), + onRender: this._onRenderFrame.bind(this), + // @ts-expect-error typing mismatch: AnimationLoop does not accept onError:null + onError + // onBeforeRender, + // onAfterRender, + }); + } + // Create a device from the deviceProps, assigning required defaults + _createDevice(props) { + const canvasContextUserProps = this.props.deviceProps?.createCanvasContext; + const canvasContextProps = typeof canvasContextUserProps === "object" ? canvasContextUserProps : void 0; + const deviceProps = { + adapters: [], + _cacheShaders: true, + _cachePipelines: true, + ...props.deviceProps + }; + if (!deviceProps.adapters.includes(webgl2Adapter)) { + deviceProps.adapters.push(webgl2Adapter); + } + const defaultCanvasProps = { + // we must use 'premultiplied' canvas for webgpu to enable transparency and match shaders + alphaMode: this.props.deviceProps?.type === "webgpu" ? "premultiplied" : void 0 + }; + const userOnResize = this.props.deviceProps?.onResize; + return luma.createDevice({ + // luma by default throws if a device is already attached + // asynchronous device creation could happen after finalize() is called + // TODO - createDevice should support AbortController? + _reuseDevices: true, + // tests can't handle WebGPU devices yet so we force WebGL2 unless overridden + type: "webgl", + ...deviceProps, + // In deck.gl v10 we may emphasize multi canvas support and unwind this prop wrapping + createCanvasContext: { + ...defaultCanvasProps, + ...canvasContextProps, + canvas: this._createCanvas(props), + useDevicePixels: this.props.useDevicePixels, + autoResize: true + }, + onResize: (canvasContext, info) => { + this._needsRedraw = "Canvas resized"; + userOnResize?.(canvasContext, info); + } + }); + } + // Get the most relevant view state: props.viewState, if supplied, shadows internal viewState + // TODO: For backwards compatibility ensure numeric width and height is added to the viewState + _getViewState() { + return this.props.viewState || this.viewState; + } + // Get the view descriptor list + _getViews() { + const { views } = this.props; + const normalizedViews = Array.isArray(views) ? views : ( + // If null, default to a full screen map view port + views ? [views] : [new map_view_default({ id: "default-view" })] + ); + if (normalizedViews.length && this.props.controller) { + normalizedViews[0].props.controller = this.props.controller; + } + return normalizedViews; + } + _onContextLost() { + const { onError } = this.props; + if (this.animationLoop && onError) { + onError(new Error("WebGL context is lost")); + } + } + /** Actually run picking */ + _pickAndCallback() { + const { _pickRequest } = this; + if (_pickRequest.event) { + const event = _pickRequest.event; + const layers = this.layerManager?.getLayers() || []; + const pickOptions = this._getPointPickOptions(_pickRequest.x, _pickRequest.y, { + radius: _pickRequest.radius, + mode: _pickRequest.mode + }, layers); + const internalPickingMode = this._getInternalPickingMode(); + const hoverPickSequence = ++this._hoverPickSequence; + _pickRequest.event = null; + if (!internalPickingMode) { + return; + } + if (internalPickingMode === "sync") { + this._applyHoverCallbacks(this._pickPointSync(pickOptions), event); + return; + } + this._pickPointAsync(pickOptions).then(({ result, emptyInfo }) => { + if (hoverPickSequence === this._hoverPickSequence) { + this._applyHoverCallbacks({ result, emptyInfo }, event); + } + }).catch((error) => this.props.onError?.(error)); + } + } + _updateCursor() { + const container = this.props.parent || this.canvas; + if (container) { + container.style.cursor = this.props.getCursor(this.cursorState); + } + } + _setDevice(device) { + this.device = device; + this._validateInternalPickingMode(); + if (!this.animationLoop) { + return; + } + if (!this.canvas) { + this.canvas = this.device.canvasContext?.canvas; + if (!this.canvas.isConnected && this.props.parent) { + this.props.parent.insertBefore(this.canvas, this.props.parent.firstChild); + } + } + if (this.device.type === "webgl") { + this.device.setParametersWebGL({ + blend: true, + blendFunc: [770, 771, 1, 771], + polygonOffsetFill: true, + depthTest: true, + depthFunc: 515 + }); + } + this.props.onDeviceInitialized(this.device); + if (this.device.type === "webgl") { + this.props.onWebGLInitialized(this.device.gl); + } + const timeline = new Timeline(); + timeline.play(); + this.animationLoop.attachTimeline(timeline); + const eventRoot = this.props.parent?.querySelector(".deck-events-root") || this.canvas; + this.eventManager = new EventManager(eventRoot, { + touchAction: this.props.touchAction, + recognizers: Object.keys(RECOGNIZERS).map((eventName) => { + const [RecognizerConstructor, defaultOptions3, recognizeWith, requestFailure] = RECOGNIZERS[eventName]; + const optionsOverride = this.props.eventRecognizerOptions?.[eventName]; + const options = { ...defaultOptions3, ...optionsOverride, event: eventName }; + return { + recognizer: new RecognizerConstructor(options), + recognizeWith, + requestFailure + }; + }), + events: { + pointerdown: this._onPointerDown, + pointermove: this._onPointerMove, + pointerleave: this._onPointerMove + } + }); + for (const eventType in EVENT_HANDLERS) { + this.eventManager.on(eventType, this._onEvent); + } + this.viewManager = new ViewManager({ + timeline, + eventManager: this.eventManager, + onViewStateChange: this._onViewStateChange.bind(this), + onInteractionStateChange: this._onInteractionStateChange.bind(this), + pickPosition: this._pickPositionForController.bind(this), + views: this._getViews(), + viewState: this._getViewState(), + width: this.width, + height: this.height + }); + const viewport = this.viewManager.getViewports()[0]; + this.layerManager = new LayerManager(this.device, { + deck: this, + stats: this.stats, + viewport, + timeline + }); + this.effectManager = new EffectManager({ + deck: this, + device: this.device + }); + this.deckRenderer = new DeckRenderer(this.device, { stats: this.stats }); + this.deckPicker = new DeckPicker(this.device, { stats: this.stats }); + const widgetParent = this.props.parent?.querySelector(".deck-widgets-root") || this.canvas?.parentElement; + this.widgetManager = new WidgetManager({ + deck: this, + parentElement: widgetParent + }); + this.widgetManager.addDefault(new TooltipWidget()); + this.setProps(this.props); + this._updateCanvasSize(); + this.props.onLoad(); + } + /** Internal only: default render function (redraw all layers and views) */ + _drawLayers(redrawReason, renderOptions) { + const { device, gl } = this.layerManager.context; + this.props.onBeforeRender({ device, gl }); + const opts = { + target: this.props._framebuffer, + layers: this.layerManager.getLayers(), + viewports: this.viewManager.getViewports(), + onViewportActive: this.layerManager.activateViewport, + views: this.viewManager.getViews(), + pass: "screen", + effects: this.effectManager.getEffects(), + ...renderOptions + }; + this.deckRenderer?.renderLayers(opts); + if (opts.pass === "screen") { + this.widgetManager.onRedraw({ + viewports: opts.viewports, + layers: opts.layers + }); + } + this.props.onAfterRender({ device, gl }); + } + // Callbacks + _onRenderFrame() { + this._getFrameStats(); + if (this._metricsCounter++ % 60 === 0) { + this._getMetrics(); + this.stats.reset(); + log_default.table(4, this.metrics)(); + if (this.props._onMetrics) { + this.props._onMetrics(this.metrics); + } + } + this._updateCanvasSize(); + this._updateCursor(); + this.layerManager.updateLayers(); + this._pickAndCallback(); + this.redraw(); + if (this.viewManager) { + this.viewManager.updateViewStates(); + } + } + // Callbacks + _onViewStateChange(params) { + const viewState = this.props.onViewStateChange(params) || params.viewState; + if (this.viewState) { + this.viewState = { ...this.viewState, [params.viewId]: viewState }; + if (!this.props.viewState) { + if (this.viewManager) { + this.viewManager.setProps({ viewState: this.viewState }); + } + } + } + } + _onInteractionStateChange(interactionState) { + this.cursorState.isDragging = interactionState.isDragging || false; + this.props.onInteractionStateChange(interactionState); + } + _getFrameStats() { + const { stats } = this; + stats.get("frameRate").timeEnd(); + stats.get("frameRate").timeStart(); + const animationLoopStats = this.animationLoop.stats; + stats.get("GPU Time").addTime(animationLoopStats.get("GPU Time").lastTiming); + stats.get("CPU Time").addTime(animationLoopStats.get("CPU Time").lastTiming); + } + _getMetrics() { + const { metrics, stats } = this; + metrics.fps = stats.get("frameRate").getHz(); + metrics.setPropsTime = stats.get("setProps Time").time; + metrics.updateAttributesTime = stats.get("Update Attributes").time; + metrics.framesRedrawn = stats.get("Redraw Count").count; + metrics.pickTime = stats.get("pickObject Time").time + stats.get("pickMultipleObjects Time").time + stats.get("pickObjects Time").time; + metrics.pickCount = stats.get("Pick Count").count; + metrics.layersCount = this.layerManager?.layers.length ?? 0; + metrics.drawLayersCount = stats.get("Layers rendered").lastSampleCount; + metrics.pickLayersCount = stats.get("Layers picked").lastSampleCount; + metrics.updateAttributesCount = stats.get("Layers updated").count; + metrics.updateAttributesCount = stats.get("Attributes updated").count; + metrics.gpuTime = stats.get("GPU Time").time; + metrics.cpuTime = stats.get("CPU Time").time; + metrics.gpuTimePerFrame = stats.get("GPU Time").getAverageTime(); + metrics.cpuTimePerFrame = stats.get("CPU Time").getAverageTime(); + const memoryStats = luma.stats.get("GPU Time and Memory"); + metrics.bufferMemory = memoryStats.get("Buffer Memory").count; + metrics.textureMemory = memoryStats.get("Texture Memory").count; + metrics.renderbufferMemory = memoryStats.get("Renderbuffer Memory").count; + metrics.gpuMemory = memoryStats.get("GPU Memory").count; + } + }; + Deck.defaultProps = defaultProps; + Deck.VERSION = VERSION5; + var deck_default = Deck; + + // node_modules/@deck.gl/core/dist/lib/attribute/data-column.js + init_dist4(); + + // node_modules/@deck.gl/core/dist/lib/attribute/gl-utils.js + init_dist4(); + function typedArrayFromDataType(type) { + switch (type) { + case "float64": + return Float64Array; + case "uint8": + case "unorm8": + return Uint8ClampedArray; + default: + return getTypedArrayConstructor(type); + } + } + var dataTypeFromTypedArray = dataTypeDecoder.getDataType.bind(dataTypeDecoder); + function getBufferAttributeLayout(name2, accessor, deviceType) { + if (accessor.size > 4) { + return null; + } + const type = deviceType === "webgpu" && accessor.type === "uint8" ? "unorm8" : accessor.type; + return { + attribute: name2, + // @ts-expect-error Not all combinations are valid vertex formats; it's up to DataColumn to ensure + format: accessor.size > 1 ? `${type}x${accessor.size}` : accessor.type, + byteOffset: accessor.offset || 0 + // Note stride is set on the top level + }; + } + function getStride(accessor) { + return accessor.stride || accessor.size * accessor.bytesPerElement; + } + function bufferLayoutEqual(accessor1, accessor2) { + return accessor1.type === accessor2.type && accessor1.size === accessor2.size && getStride(accessor1) === getStride(accessor2) && (accessor1.offset || 0) === (accessor2.offset || 0); + } + + // node_modules/@deck.gl/core/dist/lib/attribute/data-column.js + function resolveShaderAttribute(baseAccessor, shaderAttributeOptions) { + if (shaderAttributeOptions.offset) { + log_default.removed("shaderAttribute.offset", "vertexOffset, elementOffset")(); + } + const stride = getStride(baseAccessor); + const vertexOffset = shaderAttributeOptions.vertexOffset !== void 0 ? shaderAttributeOptions.vertexOffset : baseAccessor.vertexOffset || 0; + const elementOffset = shaderAttributeOptions.elementOffset || 0; + const offset = ( + // offsets defined by the attribute + vertexOffset * stride + elementOffset * baseAccessor.bytesPerElement + // offsets defined by external buffers if any + (baseAccessor.offset || 0) + ); + return { + ...shaderAttributeOptions, + offset, + stride + }; + } + function resolveDoublePrecisionShaderAttributes(baseAccessor, shaderAttributeOptions) { + const resolvedOptions = resolveShaderAttribute(baseAccessor, shaderAttributeOptions); + return { + high: resolvedOptions, + low: { + ...resolvedOptions, + offset: resolvedOptions.offset + baseAccessor.size * 4 + } + }; + } + var DataColumn = class { + /* eslint-disable max-statements */ + constructor(device, opts, state) { + this._buffer = null; + this.device = device; + this.id = opts.id || ""; + this.size = opts.size || 1; + const logicalType = opts.logicalType || opts.type; + const doublePrecision = logicalType === "float64"; + let { defaultValue } = opts; + defaultValue = Number.isFinite(defaultValue) ? [defaultValue] : defaultValue || new Array(this.size).fill(0); + let bufferType; + if (doublePrecision) { + bufferType = "float32"; + } else if (!logicalType && opts.isIndexed) { + bufferType = "uint32"; + } else { + bufferType = logicalType || "float32"; + } + let defaultType = typedArrayFromDataType(logicalType || bufferType); + this.doublePrecision = doublePrecision; + if (doublePrecision && opts.fp64 === false) { + defaultType = Float32Array; + } + this.value = null; + this.settings = { + ...opts, + defaultType, + defaultValue, + logicalType, + type: bufferType, + normalized: bufferType.includes("norm"), + size: this.size, + bytesPerElement: defaultType.BYTES_PER_ELEMENT + }; + this.state = { + ...state, + externalBuffer: null, + bufferAccessor: this.settings, + allocatedValue: null, + numInstances: 0, + bounds: null, + constant: false + }; + } + /* eslint-enable max-statements */ + get isConstant() { + return this.state.constant; + } + get buffer() { + return this._buffer; + } + get byteOffset() { + const accessor = this.getAccessor(); + if (accessor.vertexOffset) { + return accessor.vertexOffset * getStride(accessor); + } + return 0; + } + get numInstances() { + return this.state.numInstances; + } + set numInstances(n) { + this.state.numInstances = n; + } + delete() { + if (this._buffer) { + this._buffer.delete(); + this._buffer = null; + } + typed_array_manager_default.release(this.state.allocatedValue); + } + getBuffer() { + if (this.state.constant) { + return null; + } + return this.state.externalBuffer || this._buffer; + } + getValue(attributeName = this.id, options = null) { + const result = {}; + if (this.state.constant) { + const value = this.value; + if (options) { + const shaderAttributeDef = resolveShaderAttribute(this.getAccessor(), options); + const offset = shaderAttributeDef.offset / value.BYTES_PER_ELEMENT; + const size = shaderAttributeDef.size || this.size; + result[attributeName] = value.subarray(offset, offset + size); + } else { + result[attributeName] = value; + } + } else { + result[attributeName] = this.getBuffer(); + } + if (this.doublePrecision) { + if (this.value instanceof Float64Array) { + result[`${attributeName}64Low`] = result[attributeName]; + } else { + result[`${attributeName}64Low`] = new Float32Array(this.size); + } + } + return result; + } + _getBufferLayout(attributeName = this.id, options = null) { + const accessor = this.getAccessor(); + const attributes = []; + const result = { + name: this.id, + byteStride: getStride(accessor) + }; + if (this.doublePrecision) { + const doubleShaderAttributeDefs = resolveDoublePrecisionShaderAttributes(accessor, options || {}); + attributes.push(getBufferAttributeLayout(attributeName, { ...accessor, ...doubleShaderAttributeDefs.high }, this.device.type), getBufferAttributeLayout(`${attributeName}64Low`, { + ...accessor, + ...doubleShaderAttributeDefs.low + }, this.device.type)); + } else if (options) { + const shaderAttributeDef = resolveShaderAttribute(accessor, options); + attributes.push(getBufferAttributeLayout(attributeName, { ...accessor, ...shaderAttributeDef }, this.device.type)); + } else { + attributes.push(getBufferAttributeLayout(attributeName, accessor, this.device.type)); + } + result.attributes = attributes.filter(Boolean); + return result; + } + setAccessor(accessor) { + this.state.bufferAccessor = accessor; + } + getAccessor() { + return this.state.bufferAccessor; + } + // Returns [min: Array(size), max: Array(size)] + /* eslint-disable max-depth */ + getBounds() { + if (this.state.bounds) { + return this.state.bounds; + } + let result = null; + if (this.state.constant && this.value) { + const min5 = Array.from(this.value); + result = [min5, min5]; + } else { + const { value, numInstances, size } = this; + const len4 = numInstances * size; + if (value && len4 && value.length >= len4) { + const min5 = new Array(size).fill(Infinity); + const max4 = new Array(size).fill(-Infinity); + for (let i = 0; i < len4; ) { + for (let j = 0; j < size; j++) { + const v = value[i++]; + if (v < min5[j]) + min5[j] = v; + if (v > max4[j]) + max4[j] = v; + } + } + result = [min5, max4]; + } + } + this.state.bounds = result; + return result; + } + // returns true if success + // eslint-disable-next-line max-statements + setData(data) { + const { state } = this; + let opts; + if (ArrayBuffer.isView(data)) { + opts = { value: data }; + } else if (data instanceof Buffer2) { + opts = { buffer: data }; + } else { + opts = data; + } + const accessor = { ...this.settings, ...opts }; + if (ArrayBuffer.isView(opts.value)) { + if (!opts.type) { + const is64Bit = this.doublePrecision && opts.value instanceof Float64Array; + if (is64Bit) { + accessor.type = "float32"; + } else { + const type = dataTypeFromTypedArray(opts.value); + accessor.type = accessor.normalized ? type.replace("int", "norm") : type; + } + } + accessor.bytesPerElement = opts.value.BYTES_PER_ELEMENT; + accessor.stride = getStride(accessor); + } + state.bounds = null; + if (opts.constant) { + let value = opts.value; + value = this._normalizeValue(value, [], 0); + if (this.settings.normalized) { + value = this.normalizeConstant(value); + } + const hasChanged = !state.constant || !this._areValuesEqual(value, this.value); + if (!hasChanged) { + return false; + } + state.externalBuffer = null; + state.constant = true; + this.value = ArrayBuffer.isView(value) ? value : new Float32Array(value); + } else if (opts.buffer) { + const buffer = opts.buffer; + state.externalBuffer = buffer; + state.constant = false; + this.value = opts.value || null; + } else if (opts.value) { + this._checkExternalBuffer(opts); + let value = opts.value; + state.externalBuffer = null; + state.constant = false; + this.value = value; + let { buffer } = this; + const stride = getStride(accessor); + const byteOffset = (accessor.vertexOffset || 0) * stride; + if (this.doublePrecision && value instanceof Float64Array) { + value = toDoublePrecisionArray(value, accessor); + } + if (this.settings.isIndexed) { + const ArrayType = this.settings.defaultType; + if (value.constructor !== ArrayType) { + value = new ArrayType(value); + } + } + const requiredBufferSize = value.byteLength + byteOffset + stride * 2; + if (!buffer || buffer.byteLength < requiredBufferSize) { + buffer = this._createBuffer(requiredBufferSize); + } + buffer.write(value, byteOffset); + } + this.setAccessor(accessor); + return true; + } + updateSubBuffer(opts = {}) { + this.state.bounds = null; + const value = this.value; + const { startOffset = 0, endOffset } = opts; + this.buffer.write(this.doublePrecision && value instanceof Float64Array ? toDoublePrecisionArray(value, { + size: this.size, + startIndex: startOffset, + endIndex: endOffset + }) : value.subarray(startOffset, endOffset), startOffset * value.BYTES_PER_ELEMENT + this.byteOffset); + } + allocate(numInstances, copy7 = false) { + const { state } = this; + const oldValue = state.allocatedValue; + const value = typed_array_manager_default.allocate(oldValue, numInstances + 1, { + size: this.size, + type: this.settings.defaultType, + copy: copy7 + }); + this.value = value; + const { byteOffset } = this; + let { buffer } = this; + if (!buffer || buffer.byteLength < value.byteLength + byteOffset) { + buffer = this._createBuffer(value.byteLength + byteOffset); + if (copy7 && oldValue) { + buffer.write(oldValue instanceof Float64Array ? toDoublePrecisionArray(oldValue, this) : oldValue, byteOffset); + } + } + state.allocatedValue = value; + state.constant = false; + state.externalBuffer = null; + this.setAccessor(this.settings); + return true; + } + // PRIVATE HELPER METHODS + _checkExternalBuffer(opts) { + const { value } = opts; + if (!ArrayBuffer.isView(value)) { + throw new Error(`Attribute ${this.id} value is not TypedArray`); + } + const ArrayType = this.settings.defaultType; + let illegalArrayType = false; + if (this.doublePrecision) { + illegalArrayType = value.BYTES_PER_ELEMENT < 4; + } + if (illegalArrayType) { + throw new Error(`Attribute ${this.id} does not support ${value.constructor.name}`); + } + if (!(value instanceof ArrayType) && this.settings.normalized && !("normalized" in opts)) { + log_default.warn(`Attribute ${this.id} is normalized`)(); + } + } + // https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/vertexAttribPointer + normalizeConstant(value) { + switch (this.settings.type) { + case "snorm8": + return new Float32Array(value).map((x) => (x + 128) / 255 * 2 - 1); + case "snorm16": + return new Float32Array(value).map((x) => (x + 32768) / 65535 * 2 - 1); + case "unorm8": + return new Float32Array(value).map((x) => x / 255); + case "unorm16": + return new Float32Array(value).map((x) => x / 65535); + default: + return value; + } + } + /* check user supplied values and apply fallback */ + _normalizeValue(value, out, start) { + const { defaultValue, size } = this.settings; + if (Number.isFinite(value)) { + out[start] = value; + return out; + } + if (!value) { + let i = size; + while (--i >= 0) { + out[start + i] = defaultValue[i]; + } + return out; + } + switch (size) { + case 4: + out[start + 3] = Number.isFinite(value[3]) ? value[3] : defaultValue[3]; + case 3: + out[start + 2] = Number.isFinite(value[2]) ? value[2] : defaultValue[2]; + case 2: + out[start + 1] = Number.isFinite(value[1]) ? value[1] : defaultValue[1]; + case 1: + out[start + 0] = Number.isFinite(value[0]) ? value[0] : defaultValue[0]; + break; + default: + let i = size; + while (--i >= 0) { + out[start + i] = Number.isFinite(value[i]) ? value[i] : defaultValue[i]; + } + } + return out; + } + _areValuesEqual(value1, value2) { + if (!value1 || !value2) { + return false; + } + const { size } = this; + for (let i = 0; i < size; i++) { + if (value1[i] !== value2[i]) { + return false; + } + } + return true; + } + _createBuffer(byteLength) { + if (this._buffer) { + this._buffer.destroy(); + } + const { isIndexed, type } = this.settings; + this._buffer = this.device.createBuffer({ + ...this._buffer?.props, + id: this.id, + // TODO(ibgreen) - WebGPU requires COPY_DST and COPY_SRC to allow write / read + usage: (isIndexed ? Buffer2.INDEX : Buffer2.VERTEX) | Buffer2.COPY_DST, + indexType: isIndexed ? type : void 0, + byteLength + }); + return this._buffer; + } + }; + + // node_modules/@deck.gl/core/dist/utils/iterable-utils.js + var EMPTY_ARRAY = []; + var placeholderArray = []; + function createIterable(data, startRow = 0, endRow = Infinity) { + let iterable = EMPTY_ARRAY; + const objectInfo = { + index: -1, + data, + // visitor can optionally utilize this to avoid constructing a new array for every object + target: [] + }; + if (!data) { + iterable = EMPTY_ARRAY; + } else if (typeof data[Symbol.iterator] === "function") { + iterable = data; + } else if (data.length > 0) { + placeholderArray.length = data.length; + iterable = placeholderArray; + } + if (startRow > 0 || Number.isFinite(endRow)) { + iterable = (Array.isArray(iterable) ? iterable : Array.from(iterable)).slice(startRow, endRow); + objectInfo.index = startRow - 1; + } + return { iterable, objectInfo }; + } + function isAsyncIterable2(data) { + return data && data[Symbol.asyncIterator]; + } + function getAccessorFromBuffer(typedArray, options) { + const { size, stride, offset, startIndices, nested } = options; + const bytesPerElement = typedArray.BYTES_PER_ELEMENT; + const elementStride = stride ? stride / bytesPerElement : size; + const elementOffset = offset ? offset / bytesPerElement : 0; + const vertexCount = Math.floor((typedArray.length - elementOffset) / elementStride); + return (_, { index: index2, target: target2 }) => { + if (!startIndices) { + const sourceIndex = index2 * elementStride + elementOffset; + for (let j = 0; j < size; j++) { + target2[j] = typedArray[sourceIndex + j]; + } + return target2; + } + const startIndex = startIndices[index2]; + const endIndex = startIndices[index2 + 1] || vertexCount; + let result; + if (nested) { + result = new Array(endIndex - startIndex); + for (let i = startIndex; i < endIndex; i++) { + const sourceIndex = i * elementStride + elementOffset; + target2 = new Array(size); + for (let j = 0; j < size; j++) { + target2[j] = typedArray[sourceIndex + j]; + } + result[i - startIndex] = target2; + } + } else if (elementStride === size) { + result = typedArray.subarray(startIndex * size + elementOffset, endIndex * size + elementOffset); + } else { + result = new typedArray.constructor((endIndex - startIndex) * size); + let targetIndex = 0; + for (let i = startIndex; i < endIndex; i++) { + const sourceIndex = i * elementStride + elementOffset; + for (let j = 0; j < size; j++) { + result[targetIndex++] = typedArray[sourceIndex + j]; + } + } + } + return result; + }; + } + + // node_modules/@deck.gl/core/dist/utils/range.js + var EMPTY = []; + var FULL = [[0, Infinity]]; + function add5(rangeList, range3) { + if (rangeList === FULL) { + return rangeList; + } + if (range3[0] < 0) { + range3[0] = 0; + } + if (range3[0] >= range3[1]) { + return rangeList; + } + const newRangeList = []; + const len4 = rangeList.length; + let insertPosition = 0; + for (let i = 0; i < len4; i++) { + const range0 = rangeList[i]; + if (range0[1] < range3[0]) { + newRangeList.push(range0); + insertPosition = i + 1; + } else if (range0[0] > range3[1]) { + newRangeList.push(range0); + } else { + range3 = [Math.min(range0[0], range3[0]), Math.max(range0[1], range3[1])]; + } + } + newRangeList.splice(insertPosition, 0, range3); + return newRangeList; + } + + // node_modules/@deck.gl/core/dist/lib/attribute/transition-settings.js + var DEFAULT_TRANSITION_SETTINGS = { + interpolation: { + duration: 0, + easing: (t) => t + }, + spring: { + stiffness: 0.05, + damping: 0.5 + } + }; + function normalizeTransitionSettings(userSettings, layerSettings) { + if (!userSettings) { + return null; + } + if (Number.isFinite(userSettings)) { + userSettings = { type: "interpolation", duration: userSettings }; + } + const type = userSettings.type || "interpolation"; + return { + ...DEFAULT_TRANSITION_SETTINGS[type], + ...layerSettings, + ...userSettings, + type + }; + } + + // node_modules/@deck.gl/core/dist/lib/attribute/attribute.js + var Attribute = class extends DataColumn { + constructor(device, opts) { + super(device, opts, { + startIndices: null, + lastExternalBuffer: null, + binaryValue: null, + binaryAccessor: null, + needsUpdate: true, + needsRedraw: false, + layoutChanged: false, + updateRanges: FULL + }); + this.constant = false; + this.settings.update = opts.update || (opts.accessor ? this._autoUpdater : void 0); + Object.seal(this.settings); + Object.seal(this.state); + this._validateAttributeUpdaters(); + } + get startIndices() { + return this.state.startIndices; + } + set startIndices(layout) { + this.state.startIndices = layout; + } + needsUpdate() { + return this.state.needsUpdate; + } + needsRedraw({ clearChangedFlags = false } = {}) { + const needsRedraw = this.state.needsRedraw; + this.state.needsRedraw = needsRedraw && !clearChangedFlags; + return needsRedraw; + } + layoutChanged() { + return this.state.layoutChanged; + } + setAccessor(accessor) { + var _a; + (_a = this.state).layoutChanged || (_a.layoutChanged = !bufferLayoutEqual(accessor, this.getAccessor())); + super.setAccessor(accessor); + } + getUpdateTriggers() { + const { accessor } = this.settings; + return [this.id].concat(typeof accessor !== "function" && accessor || []); + } + supportsTransition() { + return Boolean(this.settings.transition); + } + // Resolve transition settings object if transition is enabled, otherwise `null` + getTransitionSetting(opts) { + if (!opts || !this.supportsTransition()) { + return null; + } + const { accessor } = this.settings; + const layerSettings = this.settings.transition; + const userSettings = Array.isArray(accessor) ? ( + // @ts-ignore + opts[accessor.find((a) => opts[a])] + ) : ( + // @ts-ignore + opts[accessor] + ); + return normalizeTransitionSettings(userSettings, layerSettings); + } + setNeedsUpdate(reason = this.id, dataRange) { + this.state.needsUpdate = this.state.needsUpdate || reason; + this.setNeedsRedraw(reason); + if (dataRange) { + const { startRow = 0, endRow = Infinity } = dataRange; + this.state.updateRanges = add5(this.state.updateRanges, [startRow, endRow]); + } else { + this.state.updateRanges = FULL; + } + } + clearNeedsUpdate() { + this.state.needsUpdate = false; + this.state.updateRanges = EMPTY; + } + setNeedsRedraw(reason = this.id) { + this.state.needsRedraw = this.state.needsRedraw || reason; + } + allocate(numInstances) { + const { state, settings } = this; + if (settings.noAlloc) { + return false; + } + if (settings.update) { + super.allocate(numInstances, state.updateRanges !== FULL); + return true; + } + return false; + } + updateBuffer({ numInstances, data, props, context }) { + if (!this.needsUpdate()) { + return false; + } + const { state: { updateRanges }, settings: { update, noAlloc } } = this; + let updated = true; + if (update) { + for (const [startRow, endRow] of updateRanges) { + update.call(context, this, { data, startRow, endRow, props, numInstances }); + } + if (!this.value) { + } else if (this.constant || !this.buffer || this.buffer.byteLength < this.value.byteLength + this.byteOffset) { + if (this.constant) { + this.setConstantValue(context, this.value); + } else { + this.setData({ + value: this.value, + constant: this.constant + }); + } + this.constant = false; + } else { + for (const [startRow, endRow] of updateRanges) { + const startOffset = Number.isFinite(startRow) ? this.getVertexOffset(startRow) : 0; + const endOffset = Number.isFinite(endRow) ? this.getVertexOffset(endRow) : noAlloc || !Number.isFinite(numInstances) ? this.value.length : numInstances * this.size; + super.updateSubBuffer({ startOffset, endOffset }); + } + } + this._checkAttributeArray(); + } else { + updated = false; + } + this.clearNeedsUpdate(); + this.setNeedsRedraw(); + return updated; + } + // Use generic value + // Returns true if successful + setConstantValue(context, value) { + if (value === void 0 || typeof value === "function") { + return false; + } + const transformedValue = this.settings.transform && context ? this.settings.transform.call(context, value) : value; + if (this.device.type === "webgpu") { + return this.setConstantBufferValue(transformedValue, this.numInstances); + } + const hasChanged = this.setData({ constant: true, value: transformedValue }); + if (hasChanged) { + this.setNeedsRedraw(); + } + this.clearNeedsUpdate(); + return true; + } + setConstantBufferValue(value, numInstances) { + const ArrayType = this.settings.defaultType; + const constantValue = this._normalizeValue(value, new ArrayType(this.size), 0); + if (this._hasConstantBufferValue(constantValue, numInstances)) { + this.constant = false; + this.clearNeedsUpdate(); + return false; + } + const repeatedValue = new ArrayType(Math.max(numInstances, 1) * this.size); + for (let i = 0; i < repeatedValue.length; i += this.size) { + repeatedValue.set(constantValue, i); + } + const hasChanged = this.setData({ value: repeatedValue }); + this.constant = false; + this.clearNeedsUpdate(); + if (hasChanged) { + this.setNeedsRedraw(); + } + return hasChanged; + } + _hasConstantBufferValue(value, numInstances) { + const currentValue = this.value; + const expectedLength = Math.max(numInstances, 1) * this.size; + if (!ArrayBuffer.isView(currentValue) || currentValue.length !== expectedLength || currentValue.length % this.size !== 0) { + return false; + } + for (let i = 0; i < currentValue.length; i += this.size) { + for (let j = 0; j < this.size; j++) { + if (currentValue[i + j] !== value[j]) { + return false; + } + } + } + return true; + } + // Use external buffer + // Returns true if successful + // eslint-disable-next-line max-statements + setExternalBuffer(buffer) { + const { state } = this; + if (!buffer) { + state.lastExternalBuffer = null; + return false; + } + this.clearNeedsUpdate(); + if (state.lastExternalBuffer === buffer) { + return true; + } + state.lastExternalBuffer = buffer; + this.setNeedsRedraw(); + this.setData(buffer); + return true; + } + // Binary value is a typed array packed from mapping the source data with the accessor + // If the returned value from the accessor is the same as the attribute value, set it directly + // Otherwise use the auto updater for transform/normalization + setBinaryValue(buffer, startIndices = null) { + const { state, settings } = this; + if (!buffer) { + state.binaryValue = null; + state.binaryAccessor = null; + return false; + } + if (settings.noAlloc) { + return false; + } + if (state.binaryValue === buffer) { + this.clearNeedsUpdate(); + return true; + } + state.binaryValue = buffer; + this.setNeedsRedraw(); + const needsUpdate = settings.transform || startIndices !== this.startIndices; + if (needsUpdate) { + if (ArrayBuffer.isView(buffer)) { + buffer = { value: buffer }; + } + const binaryValue = buffer; + assert8(ArrayBuffer.isView(binaryValue.value), `invalid ${settings.accessor}`); + const needsNormalize = Boolean(binaryValue.size) && binaryValue.size !== this.size; + state.binaryAccessor = getAccessorFromBuffer(binaryValue.value, { + size: binaryValue.size || this.size, + stride: binaryValue.stride, + offset: binaryValue.offset, + startIndices, + nested: needsNormalize + }); + return false; + } + this.clearNeedsUpdate(); + this.setData(buffer); + return true; + } + getVertexOffset(row) { + const { startIndices } = this; + const vertexIndex = startIndices ? row < startIndices.length ? startIndices[row] : this.numInstances : row; + return vertexIndex * this.size; + } + getValue() { + const shaderAttributeDefs = this.settings.shaderAttributes; + const result = super.getValue(); + if (!shaderAttributeDefs) { + return result; + } + for (const shaderAttributeName in shaderAttributeDefs) { + Object.assign(result, super.getValue(shaderAttributeName, shaderAttributeDefs[shaderAttributeName])); + } + return result; + } + /** Generate WebGPU-style buffer layout descriptor from this attribute */ + getBufferLayout(modelInfo) { + this.state.layoutChanged = false; + const shaderAttributeDefs = this.settings.shaderAttributes; + const result = super._getBufferLayout(); + const { stepMode } = this.settings; + if (stepMode === "dynamic") { + result.stepMode = modelInfo ? modelInfo.isInstanced ? "instance" : "vertex" : "instance"; + } else { + result.stepMode = stepMode ?? "vertex"; + } + if (!shaderAttributeDefs) { + return result; + } + for (const shaderAttributeName in shaderAttributeDefs) { + const map4 = super._getBufferLayout(shaderAttributeName, shaderAttributeDefs[shaderAttributeName]); + result.attributes.push(...map4.attributes); + } + return result; + } + /* eslint-disable max-depth, max-statements */ + _autoUpdater(attribute, { data, startRow, endRow, props, numInstances }) { + const { settings, state, value, size, startIndices } = attribute; + const { accessor, transform } = settings; + const accessorFunc = state.binaryAccessor || // @ts-ignore + (typeof accessor === "function" ? accessor : props[accessor]); + assert8(typeof accessorFunc === "function", `accessor "${accessor}" is not a function`); + let i = attribute.getVertexOffset(startRow); + const { iterable, objectInfo } = createIterable(data, startRow, endRow); + for (const object of iterable) { + objectInfo.index++; + let objectValue = accessorFunc(object, objectInfo); + if (transform) { + objectValue = transform.call(this, objectValue); + } + if (startIndices) { + const numVertices = (objectInfo.index < startIndices.length - 1 ? startIndices[objectInfo.index + 1] : numInstances) - startIndices[objectInfo.index]; + if (objectValue && Array.isArray(objectValue[0])) { + let startIndex = i; + for (const item of objectValue) { + attribute._normalizeValue(item, value, startIndex); + startIndex += size; + } + } else if (objectValue && objectValue.length > size) { + value.set(objectValue, i); + } else { + attribute._normalizeValue(objectValue, objectInfo.target, 0); + fillArray({ + target: value, + source: objectInfo.target, + start: i, + count: numVertices + }); + } + i += numVertices * size; + } else { + attribute._normalizeValue(objectValue, value, i); + i += size; + } + } + } + /* eslint-enable max-depth, max-statements */ + // Validate deck.gl level fields + _validateAttributeUpdaters() { + const { settings } = this; + const hasUpdater = settings.noAlloc || typeof settings.update === "function"; + if (!hasUpdater) { + throw new Error(`Attribute ${this.id} missing update or accessor`); + } + } + // check that the first few elements of the attribute are reasonable + /* eslint-disable no-fallthrough */ + _checkAttributeArray() { + const { value } = this; + const limit = Math.min(4, this.size); + if (value && value.length >= limit) { + let valid = true; + switch (limit) { + case 4: + valid = valid && Number.isFinite(value[3]); + case 3: + valid = valid && Number.isFinite(value[2]); + case 2: + valid = valid && Number.isFinite(value[1]); + case 1: + valid = valid && Number.isFinite(value[0]); + break; + default: + valid = false; + } + if (!valid) { + throw new Error(`Illegal attribute generated for ${this.id}`); + } + } + } + }; + + // node_modules/@deck.gl/core/dist/utils/array-utils.js + function padArrayChunk(options) { + const { source: source3, target: target2, start = 0, size, getData } = options; + const end = options.end || target2.length; + const sourceLength = source3.length; + const targetLength = end - start; + if (sourceLength > targetLength) { + target2.set(source3.subarray(0, targetLength), start); + return; + } + target2.set(source3, start); + if (!getData) { + return; + } + let i = sourceLength; + while (i < targetLength) { + const datum = getData(i, source3); + for (let j = 0; j < size; j++) { + target2[start + i] = datum[j] || 0; + i++; + } + } + } + function padArray({ source: source3, target: target2, size, getData, sourceStartIndices, targetStartIndices }) { + if (!sourceStartIndices || !targetStartIndices) { + padArrayChunk({ + source: source3, + target: target2, + size, + getData + }); + return target2; + } + let sourceIndex = 0; + let targetIndex = 0; + const getChunkData = getData && ((i, chunk) => getData(i + targetIndex, chunk)); + const n = Math.min(sourceStartIndices.length, targetStartIndices.length); + for (let i = 1; i < n; i++) { + const nextSourceIndex = sourceStartIndices[i] * size; + const nextTargetIndex = targetStartIndices[i] * size; + padArrayChunk({ + source: source3.subarray(sourceIndex, nextSourceIndex), + target: target2, + start: targetIndex, + end: nextTargetIndex, + size, + getData: getChunkData + }); + sourceIndex = nextSourceIndex; + targetIndex = nextTargetIndex; + } + if (targetIndex < target2.length) { + padArrayChunk({ + // @ts-ignore + source: [], + target: target2, + start: targetIndex, + size, + getData: getChunkData + }); + } + return target2; + } + + // node_modules/@deck.gl/core/dist/transitions/gpu-transition-utils.js + function cloneAttribute(attribute) { + const { device, settings, value } = attribute; + const newAttribute = new Attribute(device, settings); + newAttribute.setData({ + value: value instanceof Float64Array ? new Float64Array(0) : new Float32Array(0), + normalized: settings.normalized + }); + return newAttribute; + } + function getAttributeTypeFromSize(size) { + switch (size) { + case 1: + return "float"; + case 2: + return "vec2"; + case 3: + return "vec3"; + case 4: + return "vec4"; + default: + throw new Error(`No defined attribute type for size "${size}"`); + } + } + function getFloat32VertexFormat(size) { + switch (size) { + case 1: + return "float32"; + case 2: + return "float32x2"; + case 3: + return "float32x3"; + case 4: + return "float32x4"; + default: + throw new Error("invalid type size"); + } + } + function cycleBuffers(buffers) { + buffers.push(buffers.shift()); + } + function getAttributeBufferLength(attribute, numInstances) { + const { doublePrecision, settings, value, size } = attribute; + const multiplier = doublePrecision && value instanceof Float64Array ? 2 : 1; + let maxVertexOffset = 0; + const { shaderAttributes } = attribute.settings; + if (shaderAttributes) { + for (const shaderAttribute of Object.values(shaderAttributes)) { + maxVertexOffset = Math.max(maxVertexOffset, shaderAttribute.vertexOffset ?? 0); + } + } + return (settings.noAlloc ? value.length : (numInstances + maxVertexOffset) * size) * multiplier; + } + function matchBuffer({ device, source: source3, target: target2 }) { + if (!target2 || target2.byteLength < source3.byteLength) { + target2?.destroy(); + target2 = device.createBuffer({ + byteLength: source3.byteLength, + usage: source3.usage + }); + } + return target2; + } + function padBuffer({ device, buffer, attribute, fromLength, toLength, fromStartIndices, getData = (x) => x }) { + const precisionMultiplier = attribute.doublePrecision && attribute.value instanceof Float64Array ? 2 : 1; + const size = attribute.size * precisionMultiplier; + const byteOffset = attribute.byteOffset; + const targetByteOffset = attribute.settings.bytesPerElement < 4 ? byteOffset / attribute.settings.bytesPerElement * 4 : byteOffset; + const toStartIndices = attribute.startIndices; + const hasStartIndices = fromStartIndices && toStartIndices; + const isConstant = attribute.isConstant; + if (!hasStartIndices && buffer && fromLength >= toLength) { + return buffer; + } + const ArrayType = attribute.value instanceof Float64Array ? Float32Array : attribute.value.constructor; + const toData = isConstant ? attribute.value : ( + // TODO(v9.1): Avoid non-portable synchronous reads. + new ArrayType(attribute.getBuffer().readSyncWebGL(byteOffset, toLength * ArrayType.BYTES_PER_ELEMENT).buffer) + ); + if (attribute.settings.normalized && !isConstant) { + const getter = getData; + getData = (value, chunk) => attribute.normalizeConstant(getter(value, chunk)); + } + const getMissingData = isConstant ? (i, chunk) => getData(toData, chunk) : (i, chunk) => getData(toData.subarray(i + byteOffset, i + byteOffset + size), chunk); + const source3 = buffer ? new Float32Array(buffer.readSyncWebGL(targetByteOffset, fromLength * 4).buffer) : new Float32Array(0); + const target2 = new Float32Array(toLength); + padArray({ + source: source3, + target: target2, + sourceStartIndices: fromStartIndices, + targetStartIndices: toStartIndices, + size, + getData: getMissingData + }); + if (!buffer || buffer.byteLength < target2.byteLength + targetByteOffset) { + buffer?.destroy(); + buffer = device.createBuffer({ + byteLength: target2.byteLength + targetByteOffset, + usage: 35050 + }); + } + buffer.write(target2, targetByteOffset); + return buffer; + } + + // node_modules/@deck.gl/core/dist/transitions/gpu-transition.js + var GPUTransitionBase = class { + constructor({ device, attribute, timeline }) { + this.buffers = []; + this.currentLength = 0; + this.device = device; + this.transition = new Transition(timeline); + this.attribute = attribute; + this.attributeInTransition = cloneAttribute(attribute); + this.currentStartIndices = attribute.startIndices; + } + get inProgress() { + return this.transition.inProgress; + } + start(transitionSettings, numInstances, duration = Infinity) { + this.settings = transitionSettings; + this.currentStartIndices = this.attribute.startIndices; + this.currentLength = getAttributeBufferLength(this.attribute, numInstances); + this.transition.start({ ...transitionSettings, duration }); + } + update() { + const updated = this.transition.update(); + if (updated) { + this.onUpdate(); + } + return updated; + } + setBuffer(buffer) { + this.attributeInTransition.setData({ + buffer, + normalized: this.attribute.settings.normalized, + // Retain placeholder value to generate correct shader layout + value: this.attributeInTransition.value + }); + } + cancel() { + this.transition.cancel(); + } + delete() { + this.cancel(); + for (const buffer of this.buffers) { + buffer.destroy(); + } + this.buffers.length = 0; + } + }; + + // node_modules/@deck.gl/core/dist/transitions/gpu-interpolation-transition.js + var GPUInterpolationTransition = class extends GPUTransitionBase { + constructor({ device, attribute, timeline }) { + super({ device, attribute, timeline }); + this.type = "interpolation"; + this.transform = getTransform(device, attribute); + } + start(transitionSettings, numInstances) { + const prevLength = this.currentLength; + const prevStartIndices = this.currentStartIndices; + super.start(transitionSettings, numInstances, transitionSettings.duration); + if (transitionSettings.duration <= 0) { + this.transition.cancel(); + return; + } + const { buffers, attribute } = this; + cycleBuffers(buffers); + buffers[0] = padBuffer({ + device: this.device, + buffer: buffers[0], + attribute, + fromLength: prevLength, + toLength: this.currentLength, + fromStartIndices: prevStartIndices, + getData: transitionSettings.enter + }); + buffers[1] = matchBuffer({ + device: this.device, + source: buffers[0], + target: buffers[1] + }); + this.setBuffer(buffers[1]); + const { transform } = this; + const model = transform.model; + let vertexCount = Math.floor(this.currentLength / attribute.size); + if (useFp64(attribute)) { + vertexCount /= 2; + } + model.setVertexCount(vertexCount); + if (attribute.isConstant) { + model.setAttributes({ aFrom: buffers[0] }); + model.setConstantAttributes({ aTo: attribute.value }); + } else { + model.setAttributes({ + aFrom: buffers[0], + aTo: attribute.getBuffer() + }); + } + transform.transformFeedback.setBuffers({ vCurrent: buffers[1] }); + } + onUpdate() { + const { duration, easing } = this.settings; + const { time } = this.transition; + let t = time / duration; + if (easing) { + t = easing(t); + } + const { model } = this.transform; + const interpolationProps = { time: t }; + model.shaderInputs.setProps({ interpolation: interpolationProps }); + this.transform.run({ discard: true }); + } + delete() { + super.delete(); + this.transform.destroy(); + } + }; + var uniformBlock3 = `layout(std140) uniform interpolationUniforms { + float time; +} interpolation; +`; + var interpolationUniforms = { + name: "interpolation", + vs: uniformBlock3, + uniformTypes: { + time: "f32" + } + }; + var vs5 = `#version 300 es +#define SHADER_NAME interpolation-transition-vertex-shader + +in ATTRIBUTE_TYPE aFrom; +in ATTRIBUTE_TYPE aTo; +out ATTRIBUTE_TYPE vCurrent; + +void main(void) { + vCurrent = mix(aFrom, aTo, interpolation.time); + gl_Position = vec4(0.0); +} +`; + var vs64 = `#version 300 es +#define SHADER_NAME interpolation-transition-vertex-shader + +in ATTRIBUTE_TYPE aFrom; +in ATTRIBUTE_TYPE aFrom64Low; +in ATTRIBUTE_TYPE aTo; +in ATTRIBUTE_TYPE aTo64Low; +out ATTRIBUTE_TYPE vCurrent; +out ATTRIBUTE_TYPE vCurrent64Low; + +vec2 mix_fp64(vec2 a, vec2 b, float x) { + vec2 range = sub_fp64(b, a); + return sum_fp64(a, mul_fp64(range, vec2(x, 0.0))); +} + +void main(void) { + for (int i=0; i 0; + if (!isTransitioning) { + transition.end(); + } + } + delete() { + super.delete(); + this.transform.destroy(); + this.texture.destroy(); + this.framebuffer.destroy(); + } + }; + var uniformBlock4 = `layout(std140) uniform springUniforms { + float damping; + float stiffness; +} spring; +`; + var springUniforms = { + name: "spring", + vs: uniformBlock4, + uniformTypes: { + damping: "f32", + stiffness: "f32" + } + }; + var vs6 = `#version 300 es +#define SHADER_NAME spring-transition-vertex-shader + +#define EPSILON 0.00001 + +in ATTRIBUTE_TYPE aPrev; +in ATTRIBUTE_TYPE aCur; +in ATTRIBUTE_TYPE aTo; +out ATTRIBUTE_TYPE vNext; +out float vIsTransitioningFlag; + +ATTRIBUTE_TYPE getNextValue(ATTRIBUTE_TYPE cur, ATTRIBUTE_TYPE prev, ATTRIBUTE_TYPE dest) { + ATTRIBUTE_TYPE velocity = cur - prev; + ATTRIBUTE_TYPE delta = dest - cur; + ATTRIBUTE_TYPE force = delta * spring.stiffness; + ATTRIBUTE_TYPE resistance = velocity * spring.damping; + return force - resistance + velocity + cur; +} + +void main(void) { + bool isTransitioning = length(aCur - aPrev) > EPSILON || length(aTo - aCur) > EPSILON; + vIsTransitioningFlag = isTransitioning ? 1.0 : 0.0; + + vNext = getNextValue(aCur, aPrev, aTo); + gl_Position = vec4(0, 0, 0, 1); + gl_PointSize = 100.0; +} +`; + var fs4 = `#version 300 es +#define SHADER_NAME spring-transition-is-transitioning-fragment-shader + +in float vIsTransitioningFlag; + +out vec4 fragColor; + +void main(void) { + if (vIsTransitioningFlag == 0.0) { + discard; + } + fragColor = vec4(1.0); +}`; + function getTransform2(device, attribute) { + const attributeType = getAttributeTypeFromSize(attribute.size); + const format2 = getFloat32VertexFormat(attribute.size); + return new BufferTransform(device, { + vs: vs6, + fs: fs4, + bufferLayout: [ + { name: "aPrev", format: format2 }, + { name: "aCur", format: format2 }, + { name: "aTo", format: attribute.getBufferLayout().attributes[0].format } + ], + varyings: ["vNext"], + modules: [springUniforms], + // @ts-expect-error TODO fix luma type + defines: { ATTRIBUTE_TYPE: attributeType }, + parameters: { + depthCompare: "always", + blendColorOperation: "max", + blendColorSrcFactor: "one", + blendColorDstFactor: "one", + blendAlphaOperation: "max", + blendAlphaSrcFactor: "one", + blendAlphaDstFactor: "one" + } + }); + } + function getTexture(device) { + return device.createTexture({ + data: new Uint8Array(4), + format: "rgba8unorm", + width: 1, + height: 1 + }); + } + function getFramebuffer3(device, texture) { + return device.createFramebuffer({ + id: "spring-transition-is-transitioning-framebuffer", + width: 1, + height: 1, + colorAttachments: [texture] + }); + } + + // node_modules/@deck.gl/core/dist/lib/attribute/attribute-transition-manager.js + var TRANSITION_TYPES = { + interpolation: GPUInterpolationTransition, + spring: GPUSpringTransition + }; + var AttributeTransitionManager = class { + constructor(device, { id, timeline }) { + if (!device) + throw new Error("AttributeTransitionManager is constructed without device"); + this.id = id; + this.device = device; + this.timeline = timeline; + this.transitions = {}; + this.needsRedraw = false; + this.numInstances = 1; + } + finalize() { + for (const attributeName in this.transitions) { + this._removeTransition(attributeName); + } + } + /* Public methods */ + // Called when attribute manager updates + // Check the latest attributes for updates. + update({ attributes, transitions, numInstances }) { + this.numInstances = numInstances || 1; + for (const attributeName in attributes) { + const attribute = attributes[attributeName]; + const settings = attribute.getTransitionSetting(transitions); + if (!settings) + continue; + this._updateAttribute(attributeName, attribute, settings); + } + for (const attributeName in this.transitions) { + const attribute = attributes[attributeName]; + if (!attribute || !attribute.getTransitionSetting(transitions)) { + this._removeTransition(attributeName); + } + } + } + // Returns `true` if attribute is transition-enabled + hasAttribute(attributeName) { + const transition = this.transitions[attributeName]; + return transition && transition.inProgress; + } + // Get all the animated attributes + getAttributes() { + const animatedAttributes = {}; + for (const attributeName in this.transitions) { + const transition = this.transitions[attributeName]; + if (transition.inProgress) { + animatedAttributes[attributeName] = transition.attributeInTransition; + } + } + return animatedAttributes; + } + /* eslint-disable max-statements */ + // Called every render cycle, run transform feedback + // Returns `true` if anything changes + run() { + if (this.numInstances === 0) { + return false; + } + for (const attributeName in this.transitions) { + const updated = this.transitions[attributeName].update(); + if (updated) { + this.needsRedraw = true; + } + } + const needsRedraw = this.needsRedraw; + this.needsRedraw = false; + return needsRedraw; + } + /* eslint-enable max-statements */ + /* Private methods */ + _removeTransition(attributeName) { + this.transitions[attributeName].delete(); + delete this.transitions[attributeName]; + } + // Check an attributes for updates + // Returns a transition object if a new transition is triggered. + _updateAttribute(attributeName, attribute, settings) { + const transition = this.transitions[attributeName]; + let isNew = !transition || transition.type !== settings.type; + if (isNew) { + if (transition) { + this._removeTransition(attributeName); + } + const TransitionType = TRANSITION_TYPES[settings.type]; + if (TransitionType) { + this.transitions[attributeName] = new TransitionType({ + attribute, + timeline: this.timeline, + device: this.device + }); + } else { + log_default.error(`unsupported transition type '${settings.type}'`)(); + isNew = false; + } + } + if (isNew || attribute.needsRedraw()) { + this.needsRedraw = true; + this.transitions[attributeName].start(settings, this.numInstances); + } + } + }; + + // node_modules/@deck.gl/core/dist/lib/attribute/attribute-manager.js + var TRACE_INVALIDATE = "attributeManager.invalidate"; + var TRACE_UPDATE_START = "attributeManager.updateStart"; + var TRACE_UPDATE_END = "attributeManager.updateEnd"; + var TRACE_ATTRIBUTE_UPDATE_START = "attribute.updateStart"; + var TRACE_ATTRIBUTE_ALLOCATE = "attribute.allocate"; + var TRACE_ATTRIBUTE_UPDATE_END = "attribute.updateEnd"; + var AttributeManager = class { + constructor(device, { id = "attribute-manager", stats, timeline } = {}) { + this.mergeBoundsMemoized = memoize(mergeBounds); + this.id = id; + this.device = device; + this.attributes = {}; + this.updateTriggers = {}; + this.needsRedraw = true; + this.userData = {}; + this.stats = stats; + this.attributeTransitionManager = new AttributeTransitionManager(device, { + id: `${id}-transitions`, + timeline + }); + Object.seal(this); + } + finalize() { + for (const attributeName in this.attributes) { + this.attributes[attributeName].delete(); + } + this.attributeTransitionManager.finalize(); + } + // Returns the redraw flag, optionally clearing it. + // Redraw flag will be set if any attributes attributes changed since + // flag was last cleared. + // + // @param {String} [clearRedrawFlags=false] - whether to clear the flag + // @return {false|String} - reason a redraw is needed. + getNeedsRedraw(opts = { clearRedrawFlags: false }) { + const redraw = this.needsRedraw; + this.needsRedraw = this.needsRedraw && !opts.clearRedrawFlags; + return redraw && this.id; + } + // Sets the redraw flag. + // @param {Boolean} redraw=true + setNeedsRedraw() { + this.needsRedraw = true; + } + // Adds attributes + add(attributes) { + this._add(attributes); + } + // Adds attributes + addInstanced(attributes) { + this._add(attributes, { stepMode: "instance" }); + } + /** + * Removes attributes + * Takes an array of attribute names and delete them from + * the attribute map if they exists + * + * @example + * attributeManager.remove(['position']); + * + * @param {Object} attributeNameArray - attribute name array (see above) + */ + remove(attributeNameArray) { + for (const name2 of attributeNameArray) { + if (this.attributes[name2] !== void 0) { + this.attributes[name2].delete(); + delete this.attributes[name2]; + } + } + } + // Marks an attribute for update + invalidate(triggerName, dataRange) { + const invalidatedAttributes = this._invalidateTrigger(triggerName, dataRange); + debug(TRACE_INVALIDATE, this, triggerName, invalidatedAttributes); + } + invalidateAll(dataRange) { + for (const attributeName in this.attributes) { + this.attributes[attributeName].setNeedsUpdate(attributeName, dataRange); + } + debug(TRACE_INVALIDATE, this, "all"); + } + // Ensure all attribute buffers are updated from props or data. + // eslint-disable-next-line complexity + update({ data, numInstances, startIndices = null, transitions, props = {}, buffers = {}, context = {} }) { + let updated = false; + debug(TRACE_UPDATE_START, this); + if (this.stats) { + this.stats.get("Update Attributes").timeStart(); + } + for (const attributeName in this.attributes) { + const attribute = this.attributes[attributeName]; + const accessorName = attribute.settings.accessor; + attribute.startIndices = startIndices; + attribute.numInstances = numInstances; + if (props[attributeName]) { + log_default.removed(`props.${attributeName}`, `data.attributes.${attributeName}`)(); + } + if (attribute.setExternalBuffer(buffers[attributeName])) { + } else if (attribute.setBinaryValue(typeof accessorName === "string" ? buffers[accessorName] : void 0, data.startIndices)) { + } else if (typeof accessorName === "string" && !buffers[accessorName] && attribute.setConstantValue(context, props[accessorName])) { + } else if (attribute.needsUpdate()) { + updated = true; + this._updateAttribute({ + attribute, + numInstances, + data, + props, + context + }); + } + this.needsRedraw = this.needsRedraw || attribute.needsRedraw(); + } + if (updated) { + debug(TRACE_UPDATE_END, this, numInstances); + } + if (this.stats) { + this.stats.get("Update Attributes").timeEnd(); + if (updated) + this.stats.get("Attributes updated").incrementCount(); + } + this.attributeTransitionManager.update({ + attributes: this.attributes, + numInstances, + transitions + }); + } + // Update attribute transition to the current timestamp + // Returns `true` if any transition is in progress + updateTransition() { + const { attributeTransitionManager } = this; + const transitionUpdated = attributeTransitionManager.run(); + this.needsRedraw = this.needsRedraw || transitionUpdated; + return transitionUpdated; + } + /** + * Returns all attribute descriptors + * Note: Format matches luma.gl Model/Program.setAttributes() + * @return {Object} attributes - descriptors + */ + getAttributes() { + return { ...this.attributes, ...this.attributeTransitionManager.getAttributes() }; + } + /** + * Computes the spatial bounds of a given set of attributes + */ + getBounds(attributeNames) { + const bounds = attributeNames.map((attributeName) => this.attributes[attributeName]?.getBounds()); + return this.mergeBoundsMemoized(bounds); + } + /** + * Returns changed attribute descriptors + * This indicates which WebGLBuffers need to be updated + * @return {Object} attributes - descriptors + */ + getChangedAttributes(opts = { clearChangedFlags: false }) { + const { attributes, attributeTransitionManager } = this; + const changedAttributes = { ...attributeTransitionManager.getAttributes() }; + for (const attributeName in attributes) { + const attribute = attributes[attributeName]; + if (attribute.needsRedraw(opts) && !attributeTransitionManager.hasAttribute(attributeName)) { + changedAttributes[attributeName] = attribute; + } + } + return changedAttributes; + } + /** Generate WebGPU-style buffer layout descriptors from all attributes */ + getBufferLayouts(modelInfo) { + return Object.values(this.getAttributes()).map((attribute) => attribute.getBufferLayout(modelInfo)); + } + // PRIVATE METHODS + /** Register new attributes */ + _add(attributes, overrideOptions) { + for (const attributeName in attributes) { + const attribute = attributes[attributeName]; + const props = { + ...attribute, + id: attributeName, + size: attribute.isIndexed && 1 || attribute.size || 1, + ...overrideOptions + }; + this.attributes[attributeName] = new Attribute(this.device, props); + } + this._mapUpdateTriggersToAttributes(); + } + // build updateTrigger name to attribute name mapping + _mapUpdateTriggersToAttributes() { + const triggers = {}; + for (const attributeName in this.attributes) { + const attribute = this.attributes[attributeName]; + attribute.getUpdateTriggers().forEach((triggerName) => { + if (!triggers[triggerName]) { + triggers[triggerName] = []; + } + triggers[triggerName].push(attributeName); + }); + } + this.updateTriggers = triggers; + } + _invalidateTrigger(triggerName, dataRange) { + const { attributes, updateTriggers } = this; + const invalidatedAttributes = updateTriggers[triggerName]; + if (invalidatedAttributes) { + invalidatedAttributes.forEach((name2) => { + const attribute = attributes[name2]; + if (attribute) { + attribute.setNeedsUpdate(attribute.id, dataRange); + } + }); + } + return invalidatedAttributes; + } + _updateAttribute(opts) { + const { attribute, numInstances } = opts; + debug(TRACE_ATTRIBUTE_UPDATE_START, attribute); + if (attribute.constant) { + attribute.setConstantValue(opts.context, attribute.value); + return; + } + if (attribute.allocate(numInstances)) { + debug(TRACE_ATTRIBUTE_ALLOCATE, attribute, numInstances); + } + const updated = attribute.updateBuffer(opts); + if (updated) { + this.needsRedraw = true; + debug(TRACE_ATTRIBUTE_UPDATE_END, attribute, numInstances); + } + } + }; + + // node_modules/@deck.gl/core/dist/lib/layer.js + init_dist4(); + init_dist5(); + + // node_modules/@deck.gl/core/dist/transitions/cpu-interpolation-transition.js + var CPUInterpolationTransition = class extends Transition { + get value() { + return this._value; + } + _onUpdate() { + const { time, settings: { fromValue, toValue, duration, easing } } = this; + const t = easing(time / duration); + this._value = lerp(fromValue, toValue, t); + } + }; + + // node_modules/@deck.gl/core/dist/transitions/cpu-spring-transition.js + var EPSILON2 = 1e-5; + function updateSpringElement(prev, cur, dest, damping, stiffness) { + const velocity = cur - prev; + const delta = dest - cur; + const spring = delta * stiffness; + const damper = -velocity * damping; + return spring + damper + velocity + cur; + } + function updateSpring(prev, cur, dest, damping, stiffness) { + if (Array.isArray(dest)) { + const next = []; + for (let i = 0; i < dest.length; i++) { + next[i] = updateSpringElement(prev[i], cur[i], dest[i], damping, stiffness); + } + return next; + } + return updateSpringElement(prev, cur, dest, damping, stiffness); + } + function distance4(value1, value2) { + if (Array.isArray(value1)) { + let distanceSquare = 0; + for (let i = 0; i < value1.length; i++) { + const d = value1[i] - value2[i]; + distanceSquare += d * d; + } + return Math.sqrt(distanceSquare); + } + return Math.abs(value1 - value2); + } + var CPUSpringTransition = class extends Transition { + get value() { + return this._currValue; + } + _onUpdate() { + const { fromValue, toValue, damping, stiffness } = this.settings; + const { _prevValue = fromValue, _currValue = fromValue } = this; + let nextValue = updateSpring(_prevValue, _currValue, toValue, damping, stiffness); + const delta = distance4(nextValue, toValue); + const velocity = distance4(nextValue, _currValue); + if (delta < EPSILON2 && velocity < EPSILON2) { + nextValue = toValue; + this.end(); + } + this._prevValue = _currValue; + this._currValue = nextValue; + } + }; + + // node_modules/@deck.gl/core/dist/lib/uniform-transition-manager.js + var TRANSITION_TYPES2 = { + interpolation: CPUInterpolationTransition, + spring: CPUSpringTransition + }; + var UniformTransitionManager = class { + constructor(timeline) { + this.transitions = /* @__PURE__ */ new Map(); + this.timeline = timeline; + } + get active() { + return this.transitions.size > 0; + } + add(key, fromValue, toValue, settings) { + const { transitions } = this; + if (transitions.has(key)) { + const transition2 = transitions.get(key); + const { value = transition2.settings.fromValue } = transition2; + fromValue = value; + this.remove(key); + } + settings = normalizeTransitionSettings(settings); + if (!settings) { + return; + } + const TransitionType = TRANSITION_TYPES2[settings.type]; + if (!TransitionType) { + log_default.error(`unsupported transition type '${settings.type}'`)(); + return; + } + const transition = new TransitionType(this.timeline); + transition.start({ + ...settings, + fromValue, + toValue + }); + transitions.set(key, transition); + } + remove(key) { + const { transitions } = this; + if (transitions.has(key)) { + transitions.get(key).cancel(); + transitions.delete(key); + } + } + update() { + const propsInTransition = {}; + for (const [key, transition] of this.transitions) { + transition.update(); + propsInTransition[key] = transition.value; + if (!transition.inProgress) { + this.remove(key); + } + } + return propsInTransition; + } + clear() { + for (const key of this.transitions.keys()) { + this.remove(key); + } + } + }; + + // node_modules/@deck.gl/core/dist/lifecycle/props.js + function validateProps(props) { + const propTypes = props[PROP_TYPES_SYMBOL]; + for (const propName in propTypes) { + const propType = propTypes[propName]; + const { validate } = propType; + if (validate && !validate(props[propName], propType)) { + throw new Error(`Invalid prop ${propName}: ${props[propName]}`); + } + } + } + function diffProps(props, oldProps) { + const propsChangedReason = compareProps({ + newProps: props, + oldProps, + propTypes: props[PROP_TYPES_SYMBOL], + ignoreProps: { data: null, updateTriggers: null, extensions: null, transitions: null } + }); + const dataChangedReason = diffDataProps(props, oldProps); + let updateTriggersChangedReason = false; + if (!dataChangedReason) { + updateTriggersChangedReason = diffUpdateTriggers(props, oldProps); + } + return { + dataChanged: dataChangedReason, + propsChanged: propsChangedReason, + updateTriggersChanged: updateTriggersChangedReason, + extensionsChanged: diffExtensions(props, oldProps), + transitionsChanged: diffTransitions(props, oldProps) + }; + } + function diffTransitions(props, oldProps) { + if (!props.transitions) { + return false; + } + const result = {}; + const propTypes = props[PROP_TYPES_SYMBOL]; + let changed = false; + for (const key in props.transitions) { + const propType = propTypes[key]; + const type = propType && propType.type; + const isTransitionable = type === "number" || type === "color" || type === "array"; + if (isTransitionable && comparePropValues(props[key], oldProps[key], propType)) { + result[key] = true; + changed = true; + } + } + return changed ? result : false; + } + function compareProps({ newProps, oldProps, ignoreProps = {}, propTypes = {}, triggerName = "props" }) { + if (oldProps === newProps) { + return false; + } + if (typeof newProps !== "object" || newProps === null) { + return `${triggerName} changed shallowly`; + } + if (typeof oldProps !== "object" || oldProps === null) { + return `${triggerName} changed shallowly`; + } + for (const key of Object.keys(newProps)) { + if (!(key in ignoreProps)) { + if (!(key in oldProps)) { + return `${triggerName}.${key} added`; + } + const changed = comparePropValues(newProps[key], oldProps[key], propTypes[key]); + if (changed) { + return `${triggerName}.${key} ${changed}`; + } + } + } + for (const key of Object.keys(oldProps)) { + if (!(key in ignoreProps)) { + if (!(key in newProps)) { + return `${triggerName}.${key} dropped`; + } + if (!Object.hasOwnProperty.call(newProps, key)) { + const changed = comparePropValues(newProps[key], oldProps[key], propTypes[key]); + if (changed) { + return `${triggerName}.${key} ${changed}`; + } + } + } + } + return false; + } + function comparePropValues(newProp, oldProp, propType) { + let equal = propType && propType.equal; + if (equal && !equal(newProp, oldProp, propType)) { + return "changed deeply"; + } + if (!equal) { + equal = newProp && oldProp && newProp.equals; + if (equal && !equal.call(newProp, oldProp)) { + return "changed deeply"; + } + } + if (!equal && oldProp !== newProp) { + return "changed shallowly"; + } + return null; + } + function diffDataProps(props, oldProps) { + if (oldProps === null) { + return "oldProps is null, initial diff"; + } + let dataChanged = false; + const { dataComparator, _dataDiff } = props; + if (dataComparator) { + if (!dataComparator(props.data, oldProps.data)) { + dataChanged = "Data comparator detected a change"; + } + } else if (props.data !== oldProps.data) { + dataChanged = "A new data container was supplied"; + } + if (dataChanged && _dataDiff) { + dataChanged = _dataDiff(props.data, oldProps.data) || dataChanged; + } + return dataChanged; + } + function diffUpdateTriggers(props, oldProps) { + if (oldProps === null) { + return { all: true }; + } + if ("all" in props.updateTriggers) { + const diffReason = diffUpdateTrigger(props, oldProps, "all"); + if (diffReason) { + return { all: true }; + } + } + const reason = {}; + let changed = false; + for (const triggerName in props.updateTriggers) { + if (triggerName !== "all") { + const diffReason = diffUpdateTrigger(props, oldProps, triggerName); + if (diffReason) { + reason[triggerName] = true; + changed = true; + } + } + } + return changed ? reason : false; + } + function diffExtensions(props, oldProps) { + if (oldProps === null) { + return true; + } + const oldExtensions = oldProps.extensions; + const { extensions } = props; + if (extensions === oldExtensions) { + return false; + } + if (!oldExtensions || !extensions) { + return true; + } + if (extensions.length !== oldExtensions.length) { + return true; + } + for (let i = 0; i < extensions.length; i++) { + if (!extensions[i].equals(oldExtensions[i])) { + return true; + } + } + return false; + } + function diffUpdateTrigger(props, oldProps, triggerName) { + let newTriggers = props.updateTriggers[triggerName]; + newTriggers = newTriggers === void 0 || newTriggers === null ? {} : newTriggers; + let oldTriggers = oldProps.updateTriggers[triggerName]; + oldTriggers = oldTriggers === void 0 || oldTriggers === null ? {} : oldTriggers; + const diffReason = compareProps({ + oldProps: oldTriggers, + newProps: newTriggers, + triggerName + }); + return diffReason; + } + + // node_modules/@deck.gl/core/dist/utils/count.js + var ERR_NOT_OBJECT = "count(): argument not an object"; + var ERR_NOT_CONTAINER = "count(): argument not a container"; + function count(container) { + if (!isObject2(container)) { + throw new Error(ERR_NOT_OBJECT); + } + if (typeof container.count === "function") { + return container.count(); + } + if (Number.isFinite(container.size)) { + return container.size; + } + if (Number.isFinite(container.length)) { + return container.length; + } + if (isPlainObject(container)) { + return Object.keys(container).length; + } + throw new Error(ERR_NOT_CONTAINER); + } + function isPlainObject(value) { + return value !== null && typeof value === "object" && value.constructor === Object; + } + function isObject2(value) { + return value !== null && typeof value === "object"; + } + + // node_modules/@deck.gl/core/dist/utils/shader.js + function mergeShaders(target2, source3) { + if (!source3) { + return target2; + } + const result = { ...target2, ...source3 }; + if ("defines" in source3) { + result.defines = { ...target2.defines, ...source3.defines }; + } + if ("modules" in source3) { + result.modules = (target2.modules || []).concat(source3.modules); + if (source3.modules.some((module) => module.name === "project64")) { + const index2 = result.modules.findIndex((module) => module.name === "project32"); + if (index2 >= 0) { + result.modules.splice(index2, 1); + } + } + } + if ("inject" in source3) { + if (!target2.inject) { + result.inject = source3.inject; + } else { + const mergedInjection = { ...target2.inject }; + for (const key in source3.inject) { + mergedInjection[key] = (mergedInjection[key] || "") + source3.inject[key]; + } + result.inject = mergedInjection; + } + } + return result; + } + + // node_modules/@deck.gl/core/dist/utils/texture.js + init_dist4(); + var DEFAULT_TEXTURE_PARAMETERS = { + minFilter: "linear", + mipmapFilter: "linear", + magFilter: "linear", + addressModeU: "clamp-to-edge", + addressModeV: "clamp-to-edge" + }; + var internalTextures = {}; + function createTexture(owner, device, image, sampler) { + if (image instanceof Texture) { + return image; + } else if (image.constructor && image.constructor.name !== "Object") { + image = { data: image }; + } + let samplerParameters = null; + if (image.compressed) { + samplerParameters = { + minFilter: "linear", + mipmapFilter: image.data.length > 1 ? "nearest" : "linear" + }; + } + const { width, height } = image.data; + const texture = device.createTexture({ + ...image, + sampler: { + ...DEFAULT_TEXTURE_PARAMETERS, + ...samplerParameters, + ...sampler + }, + mipLevels: device.getMipLevelCount(width, height) + }); + if (device.type === "webgl") { + texture.generateMipmapsWebGL(); + } else if (device.type === "webgpu") { + device.generateMipmapsWebGPU(texture); + } + internalTextures[texture.id] = owner; + return texture; + } + function destroyTexture(owner, texture) { + if (!texture || !(texture instanceof Texture)) { + return; + } + if (internalTextures[texture.id] === owner) { + texture.delete(); + delete internalTextures[texture.id]; + } + } + + // node_modules/@deck.gl/core/dist/lifecycle/prop-types.js + var TYPE_DEFINITIONS = { + boolean: { + validate(value, propType) { + return true; + }, + equal(value1, value2, propType) { + return Boolean(value1) === Boolean(value2); + } + }, + number: { + validate(value, propType) { + return Number.isFinite(value) && (!("max" in propType) || value <= propType.max) && (!("min" in propType) || value >= propType.min); + } + }, + color: { + validate(value, propType) { + return propType.optional && !value || isArray4(value) && (value.length === 3 || value.length === 4); + }, + equal(value1, value2, propType) { + return deepEqual2(value1, value2, 1); + } + }, + accessor: { + validate(value, propType) { + const valueType = getTypeOf2(value); + return valueType === "function" || valueType === getTypeOf2(propType.value); + }, + equal(value1, value2, propType) { + if (typeof value2 === "function") { + return true; + } + return deepEqual2(value1, value2, 1); + } + }, + array: { + validate(value, propType) { + return propType.optional && !value || isArray4(value); + }, + equal(value1, value2, propType) { + const { compare } = propType; + const depth = Number.isInteger(compare) ? compare : compare ? 1 : 0; + return compare ? deepEqual2(value1, value2, depth) : value1 === value2; + } + }, + object: { + equal(value1, value2, propType) { + if (propType.ignore) { + return true; + } + const { compare } = propType; + const depth = Number.isInteger(compare) ? compare : compare ? 1 : 0; + return compare ? deepEqual2(value1, value2, depth) : value1 === value2; + } + }, + function: { + validate(value, propType) { + return propType.optional && !value || typeof value === "function"; + }, + equal(value1, value2, propType) { + const shouldIgnore = !propType.compare && propType.ignore !== false; + return shouldIgnore || value1 === value2; + } + }, + data: { + transform: (value, propType, component) => { + if (!value) { + return value; + } + const { dataTransform } = component.props; + if (dataTransform) { + return dataTransform(value); + } + if (typeof value.shape === "string" && value.shape.endsWith("-table") && Array.isArray(value.data)) { + return value.data; + } + return value; + } + }, + image: { + transform: (value, propType, component) => { + const context = component.context; + if (!context || !context.device) { + return null; + } + return createTexture(component.id, context.device, value, { + ...propType.parameters, + ...component.props.textureParameters + }); + }, + release: (value, propType, component) => { + destroyTexture(component.id, value); + } + } + }; + function parsePropTypes(propDefs) { + const propTypes = {}; + const defaultProps8 = {}; + const deprecatedProps = {}; + for (const [propName, propDef] of Object.entries(propDefs)) { + const deprecated = propDef?.deprecatedFor; + if (deprecated) { + deprecatedProps[propName] = Array.isArray(deprecated) ? deprecated : [deprecated]; + } else { + const propType = parsePropType(propName, propDef); + propTypes[propName] = propType; + defaultProps8[propName] = propType.value; + } + } + return { propTypes, defaultProps: defaultProps8, deprecatedProps }; + } + function parsePropType(name2, propDef) { + switch (getTypeOf2(propDef)) { + case "object": + return normalizePropDefinition(name2, propDef); + case "array": + return normalizePropDefinition(name2, { type: "array", value: propDef, compare: false }); + case "boolean": + return normalizePropDefinition(name2, { type: "boolean", value: propDef }); + case "number": + return normalizePropDefinition(name2, { type: "number", value: propDef }); + case "function": + return normalizePropDefinition(name2, { type: "function", value: propDef, compare: true }); + default: + return { name: name2, type: "unknown", value: propDef }; + } + } + function normalizePropDefinition(name2, propDef) { + if (!("type" in propDef)) { + if (!("value" in propDef)) { + return { name: name2, type: "object", value: propDef }; + } + return { name: name2, type: getTypeOf2(propDef.value), ...propDef }; + } + return { name: name2, ...TYPE_DEFINITIONS[propDef.type], ...propDef }; + } + function isArray4(value) { + return Array.isArray(value) || ArrayBuffer.isView(value); + } + function getTypeOf2(value) { + if (isArray4(value)) { + return "array"; + } + if (value === null) { + return "null"; + } + return typeof value; + } + + // node_modules/@deck.gl/core/dist/lifecycle/create-props.js + function createProps(component, propObjects) { + let extensions; + for (let i = propObjects.length - 1; i >= 0; i--) { + const props = propObjects[i]; + if ("extensions" in props) { + extensions = props.extensions; + } + } + const propsPrototype = getPropsPrototype(component.constructor, extensions); + const propsInstance = Object.create(propsPrototype); + propsInstance[COMPONENT_SYMBOL] = component; + propsInstance[ASYNC_ORIGINAL_SYMBOL] = {}; + propsInstance[ASYNC_RESOLVED_SYMBOL] = {}; + for (let i = 0; i < propObjects.length; ++i) { + const props = propObjects[i]; + for (const key in props) { + propsInstance[key] = props[key]; + } + } + Object.freeze(propsInstance); + return propsInstance; + } + var MergedDefaultPropsCacheKey = "_mergedDefaultProps"; + function getPropsPrototype(componentClass, extensions) { + if (!(componentClass instanceof component_default.constructor)) + return {}; + let cacheKey = MergedDefaultPropsCacheKey; + if (extensions) { + for (const extension of extensions) { + const ExtensionClass = extension.constructor; + if (ExtensionClass) { + cacheKey += `:${ExtensionClass.extensionName || ExtensionClass.name}`; + } + } + } + const defaultProps8 = getOwnProperty(componentClass, cacheKey); + if (!defaultProps8) { + return componentClass[cacheKey] = createPropsPrototypeAndTypes(componentClass, extensions || []); + } + return defaultProps8; + } + function createPropsPrototypeAndTypes(componentClass, extensions) { + const parent = componentClass.prototype; + if (!parent) { + return null; + } + const parentClass = Object.getPrototypeOf(componentClass); + const parentDefaultProps = getPropsPrototype(parentClass); + const componentDefaultProps = getOwnProperty(componentClass, "defaultProps") || {}; + const componentPropDefs = parsePropTypes(componentDefaultProps); + const defaultProps8 = Object.assign(/* @__PURE__ */ Object.create(null), parentDefaultProps, componentPropDefs.defaultProps); + const propTypes = Object.assign(/* @__PURE__ */ Object.create(null), parentDefaultProps?.[PROP_TYPES_SYMBOL], componentPropDefs.propTypes); + const deprecatedProps = Object.assign(/* @__PURE__ */ Object.create(null), parentDefaultProps?.[DEPRECATED_PROPS_SYMBOL], componentPropDefs.deprecatedProps); + for (const extension of extensions) { + const extensionDefaultProps = getPropsPrototype(extension.constructor); + if (extensionDefaultProps) { + Object.assign(defaultProps8, extensionDefaultProps); + Object.assign(propTypes, extensionDefaultProps[PROP_TYPES_SYMBOL]); + Object.assign(deprecatedProps, extensionDefaultProps[DEPRECATED_PROPS_SYMBOL]); + } + } + createPropsPrototype(defaultProps8, componentClass); + addAsyncPropsToPropPrototype(defaultProps8, propTypes); + addDeprecatedPropsToPropPrototype(defaultProps8, deprecatedProps); + defaultProps8[PROP_TYPES_SYMBOL] = propTypes; + defaultProps8[DEPRECATED_PROPS_SYMBOL] = deprecatedProps; + if (extensions.length === 0 && !hasOwnProperty(componentClass, "_propTypes")) { + componentClass._propTypes = propTypes; + } + return defaultProps8; + } + function createPropsPrototype(defaultProps8, componentClass) { + const id = getComponentName(componentClass); + Object.defineProperties(defaultProps8, { + // `id` is treated specially because layer might need to override it + id: { + writable: true, + value: id + } + }); + } + function addDeprecatedPropsToPropPrototype(defaultProps8, deprecatedProps) { + for (const propName in deprecatedProps) { + Object.defineProperty(defaultProps8, propName, { + enumerable: false, + set(newValue) { + const nameStr = `${this.id}: ${propName}`; + for (const newPropName of deprecatedProps[propName]) { + if (!hasOwnProperty(this, newPropName)) { + this[newPropName] = newValue; + } + } + log_default.deprecated(nameStr, deprecatedProps[propName].join("/"))(); + } + }); + } + } + function addAsyncPropsToPropPrototype(defaultProps8, propTypes) { + const defaultValues = {}; + const descriptors = {}; + for (const propName in propTypes) { + const propType = propTypes[propName]; + const { name: name2, value } = propType; + if (propType.async) { + defaultValues[name2] = value; + descriptors[name2] = getDescriptorForAsyncProp(name2); + } + } + defaultProps8[ASYNC_DEFAULTS_SYMBOL] = defaultValues; + defaultProps8[ASYNC_ORIGINAL_SYMBOL] = {}; + Object.defineProperties(defaultProps8, descriptors); + } + function getDescriptorForAsyncProp(name2) { + return { + enumerable: true, + // Save the provided value for async props in a special map + set(newValue) { + if (typeof newValue === "string" || newValue instanceof Promise || isAsyncIterable2(newValue)) { + this[ASYNC_ORIGINAL_SYMBOL][name2] = newValue; + } else { + this[ASYNC_RESOLVED_SYMBOL][name2] = newValue; + } + }, + // Only the component's state knows the true value of async prop + get() { + if (this[ASYNC_RESOLVED_SYMBOL]) { + if (name2 in this[ASYNC_RESOLVED_SYMBOL]) { + const value = this[ASYNC_RESOLVED_SYMBOL][name2]; + return value || this[ASYNC_DEFAULTS_SYMBOL][name2]; + } + if (name2 in this[ASYNC_ORIGINAL_SYMBOL]) { + const state = this[COMPONENT_SYMBOL] && this[COMPONENT_SYMBOL].internalState; + if (state && state.hasAsyncProp(name2)) { + return state.getAsyncProp(name2) || this[ASYNC_DEFAULTS_SYMBOL][name2]; + } + } + } + return this[ASYNC_DEFAULTS_SYMBOL][name2]; + } + }; + } + function hasOwnProperty(object, prop) { + return Object.prototype.hasOwnProperty.call(object, prop); + } + function getOwnProperty(object, prop) { + return hasOwnProperty(object, prop) && object[prop]; + } + function getComponentName(componentClass) { + const componentName = componentClass.componentName; + if (!componentName) { + log_default.warn(`${componentClass.name}.componentName not specified`)(); + } + return componentName || componentClass.name; + } + + // node_modules/@deck.gl/core/dist/lifecycle/component.js + var counter = 0; + var Component = class { + constructor(...propObjects) { + this.props = createProps(this, propObjects); + this.id = this.props.id; + this.count = counter++; + } + // clone this layer with modified props + clone(newProps) { + const { props } = this; + const asyncProps = {}; + for (const key in props[ASYNC_DEFAULTS_SYMBOL]) { + if (key in props[ASYNC_RESOLVED_SYMBOL]) { + asyncProps[key] = props[ASYNC_RESOLVED_SYMBOL][key]; + } else if (key in props[ASYNC_ORIGINAL_SYMBOL]) { + asyncProps[key] = props[ASYNC_ORIGINAL_SYMBOL][key]; + } + } + return new this.constructor({ ...props, ...asyncProps, ...newProps }); + } + }; + Component.componentName = "Component"; + Component.defaultProps = {}; + var component_default = Component; + + // node_modules/@deck.gl/core/dist/lifecycle/component-state.js + var EMPTY_PROPS = Object.freeze({}); + var ComponentState = class { + constructor(component) { + this.component = component; + this.asyncProps = {}; + this.onAsyncPropUpdated = () => { + }; + this.oldProps = null; + this.oldAsyncProps = null; + } + finalize() { + for (const propName in this.asyncProps) { + const asyncProp = this.asyncProps[propName]; + if (asyncProp && asyncProp.type && asyncProp.type.release) { + asyncProp.type.release(asyncProp.resolvedValue, asyncProp.type, this.component); + } + } + this.asyncProps = {}; + this.component = null; + this.resetOldProps(); + } + /* Layer-facing props API */ + getOldProps() { + return this.oldAsyncProps || this.oldProps || EMPTY_PROPS; + } + resetOldProps() { + this.oldAsyncProps = null; + this.oldProps = this.component ? this.component.props : null; + } + // Checks if a prop is overridden + hasAsyncProp(propName) { + return propName in this.asyncProps; + } + // Returns value of an overriden prop + getAsyncProp(propName) { + const asyncProp = this.asyncProps[propName]; + return asyncProp && asyncProp.resolvedValue; + } + isAsyncPropLoading(propName) { + if (propName) { + const asyncProp = this.asyncProps[propName]; + return Boolean(asyncProp && asyncProp.pendingLoadCount > 0 && asyncProp.pendingLoadCount !== asyncProp.resolvedLoadCount); + } + for (const key in this.asyncProps) { + if (this.isAsyncPropLoading(key)) { + return true; + } + } + return false; + } + // Without changing the original prop value, swap out the data resolution under the hood + reloadAsyncProp(propName, value) { + this._watchPromise(propName, Promise.resolve(value)); + } + // Updates all async/overridden props (when new props come in) + // Checks if urls have changed, starts loading, or removes override + setAsyncProps(props) { + this.component = props[COMPONENT_SYMBOL] || this.component; + const resolvedValues = props[ASYNC_RESOLVED_SYMBOL] || {}; + const originalValues = props[ASYNC_ORIGINAL_SYMBOL] || props; + const defaultValues = props[ASYNC_DEFAULTS_SYMBOL] || {}; + for (const propName in resolvedValues) { + const value = resolvedValues[propName]; + this._createAsyncPropData(propName, defaultValues[propName]); + this._updateAsyncProp(propName, value); + resolvedValues[propName] = this.getAsyncProp(propName); + } + for (const propName in originalValues) { + const value = originalValues[propName]; + this._createAsyncPropData(propName, defaultValues[propName]); + this._updateAsyncProp(propName, value); + } + } + /* Placeholder methods for subclassing */ + _fetch(propName, url) { + return null; + } + _onResolve(propName, value) { + } + // eslint-disable-line @typescript-eslint/no-empty-function + _onError(propName, error) { + } + // eslint-disable-line @typescript-eslint/no-empty-function + // Intercept strings (URLs) and Promises and activates loading and prop rewriting + _updateAsyncProp(propName, value) { + if (!this._didAsyncInputValueChange(propName, value)) { + return; + } + if (typeof value === "string") { + value = this._fetch(propName, value); + } + if (value instanceof Promise) { + this._watchPromise(propName, value); + return; + } + if (isAsyncIterable2(value)) { + this._resolveAsyncIterable(propName, value); + return; + } + this._setPropValue(propName, value); + } + // Whenever async props are changing, we need to make a copy of oldProps + // otherwise the prop rewriting will affect the value both in props and oldProps. + // While the copy is relatively expensive, this only happens on load completion. + _freezeAsyncOldProps() { + if (!this.oldAsyncProps && this.oldProps) { + this.oldAsyncProps = Object.create(this.oldProps); + for (const propName in this.asyncProps) { + Object.defineProperty(this.oldAsyncProps, propName, { + enumerable: true, + value: this.oldProps[propName] + }); + } + } + } + // Checks if an input value actually changed (to avoid reloading/rewatching promises/urls) + _didAsyncInputValueChange(propName, value) { + const asyncProp = this.asyncProps[propName]; + if (value === asyncProp.resolvedValue || value === asyncProp.lastValue) { + return false; + } + asyncProp.lastValue = value; + return true; + } + // Set normal, non-async value + _setPropValue(propName, value) { + this._freezeAsyncOldProps(); + const asyncProp = this.asyncProps[propName]; + if (asyncProp) { + value = this._postProcessValue(asyncProp, value); + asyncProp.resolvedValue = value; + asyncProp.pendingLoadCount++; + asyncProp.resolvedLoadCount = asyncProp.pendingLoadCount; + } + } + // Set a just resolved async value, calling onAsyncPropUpdates if value changes asynchronously + _setAsyncPropValue(propName, value, loadCount) { + const asyncProp = this.asyncProps[propName]; + if (asyncProp && loadCount >= asyncProp.resolvedLoadCount && value !== void 0) { + this._freezeAsyncOldProps(); + asyncProp.resolvedValue = value; + asyncProp.resolvedLoadCount = loadCount; + this.onAsyncPropUpdated(propName, value); + } + } + // Tracks a promise, sets the prop when loaded, handles load count + _watchPromise(propName, promise) { + const asyncProp = this.asyncProps[propName]; + if (asyncProp) { + asyncProp.pendingLoadCount++; + const loadCount = asyncProp.pendingLoadCount; + promise.then((data) => { + if (!this.component) { + return; + } + data = this._postProcessValue(asyncProp, data); + this._setAsyncPropValue(propName, data, loadCount); + this._onResolve(propName, data); + }).catch((error) => { + this._onError(propName, error); + }); + } + } + async _resolveAsyncIterable(propName, iterable) { + if (propName !== "data") { + this._setPropValue(propName, iterable); + return; + } + const asyncProp = this.asyncProps[propName]; + if (!asyncProp) { + return; + } + asyncProp.pendingLoadCount++; + const loadCount = asyncProp.pendingLoadCount; + let data = []; + let count2 = 0; + for await (const chunk of iterable) { + if (!this.component) { + return; + } + const { dataTransform } = this.component.props; + if (dataTransform) { + data = dataTransform(chunk, data); + } else { + data = data.concat(chunk); + } + Object.defineProperty(data, "__diff", { + enumerable: false, + value: [{ startRow: count2, endRow: data.length }] + }); + count2 = data.length; + this._setAsyncPropValue(propName, data, loadCount); + } + this._onResolve(propName, data); + } + // Give the app a chance to post process the loaded data + _postProcessValue(asyncProp, value) { + const propType = asyncProp.type; + if (propType && this.component) { + if (propType.release) { + propType.release(asyncProp.resolvedValue, propType, this.component); + } + if (propType.transform) { + return propType.transform(value, propType, this.component); + } + } + return value; + } + // Creating an asyncProp record if needed + _createAsyncPropData(propName, defaultValue) { + const asyncProp = this.asyncProps[propName]; + if (!asyncProp) { + const propTypes = this.component && this.component.props[PROP_TYPES_SYMBOL]; + this.asyncProps[propName] = { + type: propTypes && propTypes[propName], + lastValue: null, + resolvedValue: defaultValue, + pendingLoadCount: 0, + resolvedLoadCount: 0 + }; + } + } + }; + + // node_modules/@deck.gl/core/dist/lib/layer-state.js + var LayerState = class extends ComponentState { + constructor({ attributeManager, layer }) { + super(layer); + this.attributeManager = attributeManager; + this.needsRedraw = true; + this.needsUpdate = true; + this.subLayers = null; + this.usesPickingColorCache = false; + } + get layer() { + return this.component; + } + /* Override base Component methods with Layer-specific handling */ + _fetch(propName, url) { + const layer = this.layer; + const fetch2 = layer?.props.fetch; + if (fetch2) { + return fetch2(url, { propName, layer }); + } + return super._fetch(propName, url); + } + _onResolve(propName, value) { + const layer = this.layer; + if (layer) { + const onDataLoad = layer.props.onDataLoad; + if (propName === "data" && onDataLoad) { + onDataLoad(value, { propName, layer }); + } + } + } + _onError(propName, error) { + const layer = this.layer; + if (layer) { + layer.raiseError(error, `loading ${propName} of ${this.layer}`); + } + } + }; + + // node_modules/@deck.gl/core/dist/lib/layer.js + var TRACE_CHANGE_FLAG = "layer.changeFlag"; + var TRACE_INITIALIZE = "layer.initialize"; + var TRACE_UPDATE = "layer.update"; + var TRACE_FINALIZE = "layer.finalize"; + var TRACE_MATCHED = "layer.matched"; + var MAX_PICKING_COLOR_CACHE_SIZE = 2 ** 24 - 1; + var EMPTY_ARRAY2 = Object.freeze([]); + var areViewportsEqual = memoize(({ oldViewport, viewport }) => { + return oldViewport.equals(viewport); + }); + var pickingColorCache = new Uint8ClampedArray(0); + var defaultProps2 = { + // data: Special handling for null, see below + data: { type: "data", value: EMPTY_ARRAY2, async: true }, + dataComparator: { type: "function", value: null, optional: true }, + _dataDiff: { + type: "function", + // @ts-ignore __diff is not defined on data + value: (data) => data && data.__diff, + optional: true + }, + dataTransform: { type: "function", value: null, optional: true }, + onDataLoad: { type: "function", value: null, optional: true }, + onError: { type: "function", value: null, optional: true }, + fetch: { + type: "function", + value: (url, { propName, layer, loaders, loadOptions, signal }) => { + const { resourceManager } = layer.context; + loadOptions = loadOptions || layer.getLoadOptions(); + loaders = loaders || layer.props.loaders; + if (signal) { + loadOptions = { + ...loadOptions, + core: { + ...loadOptions?.core, + fetch: { + ...loadOptions?.core?.fetch, + signal + } + } + }; + } + let inResourceManager = resourceManager.contains(url); + if (!inResourceManager && !loadOptions) { + resourceManager.add({ resourceId: url, data: load(url, loaders), persistent: false }); + inResourceManager = true; + } + if (inResourceManager) { + return resourceManager.subscribe({ + resourceId: url, + onChange: (data) => layer.internalState?.reloadAsyncProp(propName, data), + consumerId: layer.id, + requestId: propName + }); + } + return load(url, loaders, loadOptions); + } + }, + updateTriggers: {}, + // Update triggers: a core change detection mechanism in deck.gl + visible: true, + pickable: false, + opacity: { type: "number", min: 0, max: 1, value: 1 }, + operation: "draw", + onHover: { type: "function", value: null, optional: true }, + onClick: { type: "function", value: null, optional: true }, + onDragStart: { type: "function", value: null, optional: true }, + onDrag: { type: "function", value: null, optional: true }, + onDragEnd: { type: "function", value: null, optional: true }, + coordinateSystem: "default", + coordinateOrigin: { type: "array", value: [0, 0, 0], compare: true }, + modelMatrix: { type: "array", value: null, compare: true, optional: true }, + wrapLongitude: false, + positionFormat: "XYZ", + colorFormat: "RGBA", + parameters: { type: "object", value: {}, optional: true, compare: 2 }, + loadOptions: { type: "object", value: null, optional: true, ignore: true }, + transitions: null, + extensions: [], + loaders: { type: "array", value: [], optional: true, ignore: true }, + // Offset depth based on layer index to avoid z-fighting. + // Negative values pull layer towards the camera + // https://www.opengl.org/archives/resources/faq/technical/polygonoffset.htm + getPolygonOffset: { + type: "function", + value: ({ layerIndex }) => [0, -layerIndex * 100] + }, + // Selection/Highlighting + highlightedObjectIndex: null, + autoHighlight: false, + highlightColor: { type: "accessor", value: [0, 0, 128, 128] } + }; + var Layer = class extends component_default { + constructor() { + super(...arguments); + this.internalState = null; + this.lifecycle = LIFECYCLE.NO_STATE; + this.parent = null; + } + static get componentName() { + return Object.prototype.hasOwnProperty.call(this, "layerName") ? this.layerName : ""; + } + get root() { + let layer = this; + while (layer.parent) { + layer = layer.parent; + } + return layer; + } + toString() { + const className = this.constructor.layerName || this.constructor.name; + return `${className}({id: '${this.props.id}'})`; + } + // Public API for users + /** Projects a point with current view state from the current layer's coordinate system to screen */ + project(xyz) { + assert8(this.internalState); + const viewport = this.internalState.viewport || this.context.viewport; + const worldPosition = getWorldPosition(xyz, { + viewport, + modelMatrix: this.props.modelMatrix, + coordinateOrigin: this.props.coordinateOrigin, + coordinateSystem: this.props.coordinateSystem + }); + const [x, y, z] = worldToPixels(worldPosition, viewport.pixelProjectionMatrix); + return xyz.length === 2 ? [x, y] : [x, y, z]; + } + /** Unprojects a screen pixel to the current view's default coordinate system + Note: this does not reverse `project`. */ + unproject(xy) { + assert8(this.internalState); + const viewport = this.internalState.viewport || this.context.viewport; + return viewport.unproject(xy); + } + /** Projects a point with current view state from the current layer's coordinate system to the world space */ + projectPosition(xyz, params) { + assert8(this.internalState); + const viewport = this.internalState.viewport || this.context.viewport; + return projectPosition(xyz, { + viewport, + modelMatrix: this.props.modelMatrix, + coordinateOrigin: this.props.coordinateOrigin, + coordinateSystem: this.props.coordinateSystem, + ...params + }); + } + // Public API for custom layer implementation + /** `true` if this layer renders other layers */ + get isComposite() { + return false; + } + /** `true` if the layer renders to screen */ + get isDrawable() { + return true; + } + /** Updates selected state members and marks the layer for redraw */ + setState(partialState) { + this.setChangeFlags({ stateChanged: true }); + Object.assign(this.state, partialState); + this.setNeedsRedraw(); + } + /** Sets the redraw flag for this layer, will trigger a redraw next animation frame */ + setNeedsRedraw() { + if (this.internalState) { + this.internalState.needsRedraw = true; + } + } + /** Mark this layer as needs a deep update */ + setNeedsUpdate() { + if (this.internalState) { + this.context.layerManager.setNeedsUpdate(String(this)); + this.internalState.needsUpdate = true; + } + } + /** Returns true if all async resources are loaded */ + get isLoaded() { + return this.internalState ? !this.internalState.isAsyncPropLoading() : false; + } + /** Returns true if using shader-based WGS84 longitude wrapping */ + get wrapLongitude() { + return this.props.wrapLongitude; + } + /** @deprecated Returns true if the layer is visible in the picking pass */ + isPickable() { + return this.props.pickable && this.props.visible; + } + /** Returns an array of models used by this layer, can be overriden by layer subclass */ + getModels() { + const state = this.state; + return state && (state.models || state.model && [state.model]) || []; + } + /** Update shader input parameters */ + setShaderModuleProps(...props) { + for (const model of this.getModels()) { + model.shaderInputs.setProps(...props); + } + } + /** Returns the attribute manager of this layer */ + getAttributeManager() { + return this.internalState && this.internalState.attributeManager; + } + /** Returns the most recent layer that matched to this state + (When reacting to an async event, this layer may no longer be the latest) */ + getCurrentLayer() { + return this.internalState && this.internalState.layer; + } + /** Returns the default parse options for async props */ + getLoadOptions() { + return this.props.loadOptions; + } + use64bitPositions() { + const { coordinateSystem } = this.props; + return coordinateSystem === "default" || coordinateSystem === "lnglat" || coordinateSystem === "cartesian"; + } + // Event handling + onHover(info, pickingEvent) { + if (this.props.onHover) { + return this.props.onHover(info, pickingEvent) || false; + } + return false; + } + onClick(info, pickingEvent) { + if (this.props.onClick) { + return this.props.onClick(info, pickingEvent) || false; + } + return false; + } + // Returns the picking color that doesn't match any subfeature + // Use if some graphics do not belong to any pickable subfeature + // @return {Array} - a black color + nullPickingColor() { + return [0, 0, 0]; + } + // Returns the picking color that doesn't match any subfeature + // Use if some graphics do not belong to any pickable subfeature + encodePickingColor(i, target2 = []) { + target2[0] = i + 1 & 255; + target2[1] = i + 1 >> 8 & 255; + target2[2] = i + 1 >> 8 >> 8 & 255; + return target2; + } + // Returns the index corresponding to a picking color that doesn't match any subfeature + // @param {Uint8Array} color - color array to be decoded + // @return {Array} - the decoded picking color + decodePickingColor(color2) { + assert8(color2 instanceof Uint8Array); + const [i1, i2, i3] = color2; + const index2 = i1 + i2 * 256 + i3 * 65536 - 1; + return index2; + } + /** Deduces number of instances. Intention is to support: + - Explicit setting of numInstances + - Auto-deduction for ES6 containers that define a size member + - Auto-deduction for Classic Arrays via the built-in length attribute + - Auto-deduction via arrays */ + getNumInstances() { + if (Number.isFinite(this.props.numInstances)) { + return this.props.numInstances; + } + if (this.state && this.state.numInstances !== void 0) { + return this.state.numInstances; + } + return count(this.props.data); + } + /** Buffer layout describes how many attribute values are packed for each data object + The default (null) is one value each object. + Some data formats (e.g. paths, polygons) have various length. Their buffer layout + is in the form of [L0, L1, L2, ...] */ + getStartIndices() { + if (this.props.startIndices) { + return this.props.startIndices; + } + if (this.state && this.state.startIndices) { + return this.state.startIndices; + } + return null; + } + // Default implementation + getBounds() { + return this.getAttributeManager()?.getBounds(["positions", "instancePositions"]); + } + getShaders(shaders) { + shaders = mergeShaders(shaders, { + disableWarnings: true, + modules: this.context.defaultShaderModules + }); + for (const extension of this.props.extensions) { + shaders = mergeShaders(shaders, extension.getShaders.call(this, extension)); + } + return shaders; + } + /** Controls if updateState should be called. By default returns true if any prop has changed */ + shouldUpdateState(params) { + return params.changeFlags.propsOrDataChanged; + } + /** Default implementation, all attributes will be invalidated and updated when data changes */ + // eslint-disable-next-line complexity + updateState(params) { + const attributeManager = this.getAttributeManager(); + const { dataChanged } = params.changeFlags; + if (dataChanged && attributeManager) { + if (Array.isArray(dataChanged)) { + for (const dataRange of dataChanged) { + attributeManager.invalidateAll(dataRange); + } + } else { + attributeManager.invalidateAll(); + } + } + if (attributeManager) { + const { props } = params; + const hasPickingBuffer = this.internalState.hasPickingBuffer; + const needsPickingBuffer = Number.isInteger(props.highlightedObjectIndex) || Boolean(props.pickable) || props.extensions.some((extension) => extension.getNeedsPickingBuffer.call(this, extension)); + if (hasPickingBuffer !== needsPickingBuffer) { + this.internalState.hasPickingBuffer = needsPickingBuffer; + const { pickingColors, instancePickingColors } = attributeManager.attributes; + const pickingColorsAttribute = pickingColors || instancePickingColors; + if (pickingColorsAttribute) { + if (needsPickingBuffer && pickingColorsAttribute.constant) { + pickingColorsAttribute.constant = false; + attributeManager.invalidate(pickingColorsAttribute.id); + } + if (!pickingColorsAttribute.value && !needsPickingBuffer) { + pickingColorsAttribute.constant = true; + pickingColorsAttribute.value = [0, 0, 0]; + } + } + } + } + } + /** Called once when layer is no longer matched and state will be discarded. Layers can destroy WebGL resources here. */ + finalizeState(context) { + for (const model of this.getModels()) { + model.destroy(); + } + const attributeManager = this.getAttributeManager(); + if (attributeManager) { + attributeManager.finalize(); + } + if (this.context) { + this.context.resourceManager.unsubscribe({ consumerId: this.id }); + } + if (this.internalState) { + this.internalState.uniformTransitions.clear(); + this.internalState.finalize(); + } + } + // If state has a model, draw it with supplied uniforms + draw(opts) { + for (const model of this.getModels()) { + model.draw(opts.renderPass); + } + } + // called to populate the info object that is passed to the event handler + // @return null to cancel event + getPickingInfo({ info, mode, sourceLayer }) { + const { index: index2 } = info; + if (index2 >= 0) { + if (Array.isArray(this.props.data)) { + info.object = this.props.data[index2]; + } + } + return info; + } + // END LIFECYCLE METHODS + // / INTERNAL METHODS - called by LayerManager, DeckRenderer and DeckPicker + /** (Internal) Propagate an error event through the system */ + raiseError(error, message2) { + if (message2) { + error = new Error(`${message2}: ${error.message}`, { cause: error }); + } + if (!this.props.onError?.(error)) { + this.context?.onError?.(error, this); + } + } + /** (Internal) Checks if this layer needs redraw */ + getNeedsRedraw(opts = { clearRedrawFlags: false }) { + return this._getNeedsRedraw(opts); + } + /** (Internal) Checks if this layer needs a deep update */ + needsUpdate() { + if (!this.internalState) { + return false; + } + return this.internalState.needsUpdate || this.hasUniformTransition() || this.shouldUpdateState(this._getUpdateParams()); + } + /** Checks if this layer has ongoing uniform transition */ + hasUniformTransition() { + return this.internalState?.uniformTransitions.active || false; + } + /** Called when this layer is rendered into the given viewport */ + activateViewport(viewport) { + if (!this.internalState) { + return; + } + const oldViewport = this.internalState.viewport; + this.internalState.viewport = viewport; + if (!oldViewport || !areViewportsEqual({ oldViewport, viewport })) { + this.setChangeFlags({ viewportChanged: true }); + if (this.isComposite) { + if (this.needsUpdate()) { + this.setNeedsUpdate(); + } + } else { + this._update(); + } + } + } + /** Default implementation of attribute invalidation, can be redefined */ + invalidateAttribute(name2 = "all") { + const attributeManager = this.getAttributeManager(); + if (!attributeManager) { + return; + } + if (name2 === "all") { + attributeManager.invalidateAll(); + } else { + attributeManager.invalidate(name2); + } + } + /** Send updated attributes to the WebGL model */ + updateAttributes(changedAttributes) { + let bufferLayoutChanged = false; + for (const id in changedAttributes) { + if (changedAttributes[id].layoutChanged()) { + bufferLayoutChanged = true; + } + } + for (const model of this.getModels()) { + this._setModelAttributes(model, changedAttributes, bufferLayoutChanged); + } + } + /** Recalculate any attributes if needed */ + _updateAttributes() { + const attributeManager = this.getAttributeManager(); + if (!attributeManager) { + return; + } + const props = this.props; + const numInstances = this.getNumInstances(); + const startIndices = this.getStartIndices(); + attributeManager.update({ + data: props.data, + numInstances, + startIndices, + props, + transitions: props.transitions, + // @ts-ignore (TS2339) property attribute is not present on some acceptable data types + buffers: props.data.attributes, + context: this + }); + const changedAttributes = attributeManager.getChangedAttributes({ clearChangedFlags: true }); + this.updateAttributes(changedAttributes); + } + /** Update attribute transitions. This is called in drawLayer, no model updates required. */ + _updateAttributeTransition() { + const attributeManager = this.getAttributeManager(); + if (attributeManager) { + attributeManager.updateTransition(); + } + } + /** Update uniform (prop) transitions. This is called in updateState, may result in model updates. */ + _updateUniformTransition() { + const { uniformTransitions } = this.internalState; + if (uniformTransitions.active) { + const propsInTransition = uniformTransitions.update(); + const props = Object.create(this.props); + for (const key in propsInTransition) { + Object.defineProperty(props, key, { value: propsInTransition[key] }); + } + return props; + } + return this.props; + } + /** Updater for the automatically populated instancePickingColors attribute */ + calculateInstancePickingColors(attribute, { numInstances }) { + if (attribute.constant) { + return; + } + const cacheSize = Math.floor(pickingColorCache.length / 4); + this.internalState.usesPickingColorCache = true; + if (cacheSize < numInstances) { + if (numInstances > MAX_PICKING_COLOR_CACHE_SIZE) { + log_default.warn("Layer has too many data objects. Picking might not be able to distinguish all objects.")(); + } + pickingColorCache = typed_array_manager_default.allocate(pickingColorCache, numInstances, { + size: 4, + copy: true, + maxCount: Math.max(numInstances, MAX_PICKING_COLOR_CACHE_SIZE) + }); + const newCacheSize = Math.floor(pickingColorCache.length / 4); + const pickingColor = [0, 0, 0]; + for (let i = cacheSize; i < newCacheSize; i++) { + this.encodePickingColor(i, pickingColor); + pickingColorCache[i * 4 + 0] = pickingColor[0]; + pickingColorCache[i * 4 + 1] = pickingColor[1]; + pickingColorCache[i * 4 + 2] = pickingColor[2]; + pickingColorCache[i * 4 + 3] = 0; + } + } + attribute.value = pickingColorCache.subarray(0, numInstances * 4); + } + /** Apply changed attributes to model */ + _setModelAttributes(model, changedAttributes, bufferLayoutChanged = false) { + if (!Object.keys(changedAttributes).length) { + return; + } + if (bufferLayoutChanged) { + const attributeManager = this.getAttributeManager(); + model.setBufferLayout(attributeManager.getBufferLayouts(model)); + changedAttributes = attributeManager.getAttributes(); + } + const excludeAttributes = model.userData?.excludeAttributes || {}; + const attributeBuffers = {}; + const constantAttributes = {}; + for (const name2 in changedAttributes) { + if (excludeAttributes[name2]) { + continue; + } + const values = changedAttributes[name2].getValue(); + for (const attributeName in values) { + const value = values[attributeName]; + if (value instanceof Buffer2) { + if (changedAttributes[name2].settings.isIndexed) { + model.setIndexBuffer(value); + } else { + attributeBuffers[attributeName] = value; + } + } else if (value) { + constantAttributes[attributeName] = value; + } + } + } + model.setAttributes(attributeBuffers); + model.setConstantAttributes(constantAttributes); + } + /** (Internal) Sets the picking color at the specified index to null picking color. Used for multi-depth picking. + This method may be overriden by layer implementations */ + disablePickingIndex(objectIndex) { + const data = this.props.data; + if (!("attributes" in data)) { + this._disablePickingIndex(objectIndex); + return; + } + const { pickingColors, instancePickingColors } = this.getAttributeManager().attributes; + const colors = pickingColors || instancePickingColors; + const externalColorAttribute = colors && data.attributes && data.attributes[colors.id]; + if (externalColorAttribute && externalColorAttribute.value) { + const values = externalColorAttribute.value; + const objectColor = this.encodePickingColor(objectIndex); + for (let index2 = 0; index2 < data.length; index2++) { + const i = colors.getVertexOffset(index2); + if (values[i] === objectColor[0] && values[i + 1] === objectColor[1] && values[i + 2] === objectColor[2]) { + this._disablePickingIndex(index2); + } + } + } else { + this._disablePickingIndex(objectIndex); + } + } + // TODO - simplify subclassing interface + _disablePickingIndex(objectIndex) { + const { pickingColors, instancePickingColors } = this.getAttributeManager().attributes; + const colors = pickingColors || instancePickingColors; + if (!colors) { + return; + } + const start = colors.getVertexOffset(objectIndex); + const end = colors.getVertexOffset(objectIndex + 1); + colors.buffer.write(new Uint8Array(end - start), start); + } + /** (Internal) Re-enable all picking indices after multi-depth picking */ + restorePickingColors() { + const { pickingColors, instancePickingColors } = this.getAttributeManager().attributes; + const colors = pickingColors || instancePickingColors; + if (!colors) { + return; + } + if ( + // @ts-ignore (TS2531) this method is only called internally with internalState defined + this.internalState.usesPickingColorCache && colors.value.buffer !== pickingColorCache.buffer + ) { + colors.value = pickingColorCache.subarray(0, colors.value.length); + } + colors.updateSubBuffer({ startOffset: 0 }); + } + /* eslint-disable max-statements */ + /* (Internal) Called by layer manager when a new layer is found */ + _initialize() { + assert8(!this.internalState); + debug(TRACE_INITIALIZE, this); + const attributeManager = this._getAttributeManager(); + if (attributeManager) { + attributeManager.addInstanced({ + instancePickingColors: { + type: "uint8", + size: 4, + noAlloc: true, + // Updaters are always called with `this` pointing to the layer + // eslint-disable-next-line @typescript-eslint/unbound-method + update: this.calculateInstancePickingColors + } + }); + } + this.internalState = new LayerState({ + attributeManager, + layer: this + }); + this._clearChangeFlags(); + this.state = {}; + Object.defineProperty(this.state, "attributeManager", { + get: () => { + log_default.deprecated("layer.state.attributeManager", "layer.getAttributeManager()")(); + return attributeManager; + } + }); + this.internalState.uniformTransitions = new UniformTransitionManager(this.context.timeline); + this.internalState.onAsyncPropUpdated = this._onAsyncPropUpdated.bind(this); + this.internalState.setAsyncProps(this.props); + this.initializeState(this.context); + for (const extension of this.props.extensions) { + extension.initializeState.call(this, this.context, extension); + } + this.setChangeFlags({ + dataChanged: "init", + propsChanged: "init", + viewportChanged: true, + extensionsChanged: true + }); + this._update(); + } + /** (Internal) Called by layer manager to transfer state from an old layer */ + _transferState(oldLayer) { + debug(TRACE_MATCHED, this, this === oldLayer); + const { state, internalState } = oldLayer; + if (this === oldLayer) { + return; + } + this.internalState = internalState; + this.state = state; + this.internalState.setAsyncProps(this.props); + this._diffProps(this.props, this.internalState.getOldProps()); + } + /** (Internal) Called by layer manager when a new layer is added or an existing layer is matched with a new instance */ + _update() { + const stateNeedsUpdate = this.needsUpdate(); + debug(TRACE_UPDATE, this, stateNeedsUpdate); + if (!stateNeedsUpdate) { + return; + } + this.context.stats.get("Layer updates").incrementCount(); + const currentProps = this.props; + const context = this.context; + const internalState = this.internalState; + const currentViewport = context.viewport; + const propsInTransition = this._updateUniformTransition(); + internalState.propsInTransition = propsInTransition; + context.viewport = internalState.viewport || currentViewport; + this.props = propsInTransition; + try { + const updateParams = this._getUpdateParams(); + const oldModels = this.getModels(); + if (context.device) { + this.updateState(updateParams); + } else { + try { + this.updateState(updateParams); + } catch (error) { + } + } + for (const extension of this.props.extensions) { + extension.updateState.call(this, updateParams, extension); + } + this.setNeedsRedraw(); + this._updateAttributes(); + const modelChanged = this.getModels()[0] !== oldModels[0]; + this._postUpdate(updateParams, modelChanged); + } finally { + context.viewport = currentViewport; + this.props = currentProps; + this._clearChangeFlags(); + internalState.needsUpdate = false; + internalState.resetOldProps(); + } + } + /* eslint-enable max-statements */ + /** (Internal) Called by manager when layer is about to be disposed + Note: not guaranteed to be called on application shutdown */ + _finalize() { + debug(TRACE_FINALIZE, this); + this.finalizeState(this.context); + for (const extension of this.props.extensions) { + extension.finalizeState.call(this, this.context, extension); + } + } + // Calculates uniforms + _drawLayer({ renderPass, shaderModuleProps = null, uniforms = {}, parameters = {} }) { + this._updateAttributeTransition(); + const currentProps = this.props; + const context = this.context; + this.props = this.internalState.propsInTransition || currentProps; + try { + if (shaderModuleProps) { + this.setShaderModuleProps(shaderModuleProps); + } + const { getPolygonOffset } = this.props; + const offsets = getPolygonOffset && getPolygonOffset(uniforms) || [0, 0]; + if (context.device instanceof WebGLDevice) { + context.device.setParametersWebGL({ polygonOffset: offsets }); + } + const webGPUDrawParameters = context.device instanceof WebGLDevice ? null : splitWebGPUDrawParameters(parameters); + applyModelParameters(this.getModels(), renderPass, parameters, webGPUDrawParameters); + if (context.device instanceof WebGLDevice) { + context.device.withParametersWebGL(parameters, () => { + const opts = { renderPass, shaderModuleProps, uniforms, parameters, context }; + for (const extension of this.props.extensions) { + extension.draw.call(this, opts, extension); + } + this.draw(opts); + }); + } else { + if (webGPUDrawParameters?.renderPassParameters) { + renderPass.setParameters(webGPUDrawParameters.renderPassParameters); + } + const opts = { renderPass, shaderModuleProps, uniforms, parameters, context }; + for (const extension of this.props.extensions) { + extension.draw.call(this, opts, extension); + } + this.draw(opts); + } + } finally { + this.props = currentProps; + } + } + // Helper methods + /** Returns the current change flags */ + getChangeFlags() { + return this.internalState?.changeFlags; + } + /* eslint-disable complexity */ + /** Dirty some change flags, will be handled by updateLayer */ + setChangeFlags(flags) { + if (!this.internalState) { + return; + } + const { changeFlags } = this.internalState; + for (const key in flags) { + if (flags[key]) { + let flagChanged = false; + switch (key) { + case "dataChanged": + const dataChangedReason = flags[key]; + const prevDataChangedReason = changeFlags[key]; + if (dataChangedReason && Array.isArray(prevDataChangedReason)) { + changeFlags.dataChanged = Array.isArray(dataChangedReason) ? prevDataChangedReason.concat(dataChangedReason) : dataChangedReason; + flagChanged = true; + } + default: + if (!changeFlags[key]) { + changeFlags[key] = flags[key]; + flagChanged = true; + } + } + if (flagChanged) { + debug(TRACE_CHANGE_FLAG, this, key, flags); + } + } + } + const propsOrDataChanged = Boolean(changeFlags.dataChanged || changeFlags.updateTriggersChanged || changeFlags.propsChanged || changeFlags.extensionsChanged); + changeFlags.propsOrDataChanged = propsOrDataChanged; + changeFlags.somethingChanged = propsOrDataChanged || changeFlags.viewportChanged || changeFlags.stateChanged; + } + /* eslint-enable complexity */ + /** Clear all changeFlags, typically after an update */ + _clearChangeFlags() { + this.internalState.changeFlags = { + dataChanged: false, + propsChanged: false, + updateTriggersChanged: false, + viewportChanged: false, + stateChanged: false, + extensionsChanged: false, + propsOrDataChanged: false, + somethingChanged: false + }; + } + /** Compares the layers props with old props from a matched older layer + and extracts change flags that describe what has change so that state + can be update correctly with minimal effort */ + _diffProps(newProps, oldProps) { + const changeFlags = diffProps(newProps, oldProps); + if (changeFlags.updateTriggersChanged) { + for (const key in changeFlags.updateTriggersChanged) { + if (changeFlags.updateTriggersChanged[key]) { + this.invalidateAttribute(key); + } + } + } + if (changeFlags.transitionsChanged) { + for (const key in changeFlags.transitionsChanged) { + this.internalState.uniformTransitions.add(key, oldProps[key], newProps[key], newProps.transitions?.[key]); + } + } + return this.setChangeFlags(changeFlags); + } + /** (Internal) called by layer manager to perform extra props validation (in development only) */ + validateProps() { + validateProps(this.props); + } + /** (Internal) Called by deck picker when the hovered object changes to update the auto highlight */ + updateAutoHighlight(info) { + if (this.props.autoHighlight && !Number.isInteger(this.props.highlightedObjectIndex)) { + this._updateAutoHighlight(info); + } + } + // May be overriden by subclasses + // TODO - simplify subclassing interface + /** Update picking module parameters to highlight the hovered object */ + _updateAutoHighlight(info) { + const picking2 = { + // @ts-ignore + highlightedObjectColor: info.picked ? info.color : null + }; + const { highlightColor } = this.props; + if (info.picked && typeof highlightColor === "function") { + picking2.highlightColor = highlightColor(info); + } + this.setShaderModuleProps({ picking: picking2 }); + this.setNeedsRedraw(); + } + /** Create new attribute manager */ + _getAttributeManager() { + const context = this.context; + return new AttributeManager(context.device, { + id: this.props.id, + stats: context.stats, + timeline: context.timeline + }); + } + // Private methods + /** Called after updateState to perform common tasks */ + // eslint-disable-next-line complexity + _postUpdate(updateParams, forceUpdate) { + const { props, oldProps } = updateParams; + const model = this.state.model; + if (model?.isInstanced) { + model.setInstanceCount(this.getNumInstances()); + } + const { autoHighlight, highlightedObjectIndex, highlightColor } = props; + if (forceUpdate || oldProps.autoHighlight !== autoHighlight || oldProps.highlightedObjectIndex !== highlightedObjectIndex || oldProps.highlightColor !== highlightColor) { + const picking2 = {}; + if (Array.isArray(highlightColor)) { + picking2.highlightColor = highlightColor; + } + if (forceUpdate || oldProps.autoHighlight !== autoHighlight || highlightedObjectIndex !== oldProps.highlightedObjectIndex) { + picking2.highlightedObjectColor = Number.isFinite(highlightedObjectIndex) && highlightedObjectIndex >= 0 ? this.encodePickingColor(highlightedObjectIndex) : null; + } + this.setShaderModuleProps({ picking: picking2 }); + } + } + _getUpdateParams() { + return { + props: this.props, + // @ts-ignore TS2531 this method can only be called internally with internalState assigned + oldProps: this.internalState.getOldProps(), + context: this.context, + // @ts-ignore TS2531 this method can only be called internally with internalState assigned + changeFlags: this.internalState.changeFlags + }; + } + /** Checks state of attributes and model */ + _getNeedsRedraw(opts) { + if (!this.internalState) { + return false; + } + let redraw = false; + redraw = redraw || this.internalState.needsRedraw && this.id; + const attributeManager = this.getAttributeManager(); + const attributeManagerNeedsRedraw = attributeManager ? attributeManager.getNeedsRedraw(opts) : false; + redraw = redraw || attributeManagerNeedsRedraw; + if (redraw) { + for (const extension of this.props.extensions) { + extension.onNeedsRedraw.call(this, extension); + } + } + this.internalState.needsRedraw = this.internalState.needsRedraw && !opts.clearRedrawFlags; + return redraw; + } + /** Callback when asyn prop is loaded */ + _onAsyncPropUpdated() { + this._diffProps(this.props, this.internalState.getOldProps()); + this.setNeedsUpdate(); + } + }; + Layer.defaultProps = defaultProps2; + Layer.layerName = "Layer"; + var layer_default = Layer; + function splitWebGPUDrawParameters(parameters) { + const { blendConstant, ...pipelineParameters } = parameters; + return blendConstant ? { + pipelineParameters, + renderPassParameters: { blendConstant } + } : { pipelineParameters }; + } + function applyModelParameters(models, renderPass, parameters, webGPUDrawParameters) { + for (const model of models) { + if (model.device.type === "webgpu") { + syncModelAttachmentFormats(model, renderPass); + model.setParameters({ + ...model.parameters, + ...webGPUDrawParameters?.pipelineParameters + }); + } else { + model.setParameters(parameters); + } + } + } + function syncModelAttachmentFormats(model, renderPass) { + const framebuffer = renderPass.props.framebuffer || (renderPass.framebuffer ?? null); + if (!framebuffer) { + return; + } + const colorAttachmentFormats = framebuffer.colorAttachments.map((attachment) => attachment?.texture?.format ?? null); + const depthStencilAttachmentFormat = framebuffer.depthStencilAttachment?.texture?.format; + const modelWithProps = model; + if (!equalAttachmentFormats(modelWithProps.props.colorAttachmentFormats, colorAttachmentFormats) || modelWithProps.props.depthStencilAttachmentFormat !== depthStencilAttachmentFormat) { + modelWithProps.props.colorAttachmentFormats = colorAttachmentFormats; + modelWithProps.props.depthStencilAttachmentFormat = depthStencilAttachmentFormat; + modelWithProps._setPipelineNeedsUpdate("attachment formats"); + } + } + function equalAttachmentFormats(left, right) { + if (left === right) { + return true; + } + if (!left || !right || left.length !== right.length) { + return false; + } + for (let i = 0; i < left.length; i++) { + if (left[i] !== right[i]) { + return false; + } + } + return true; + } + + // node_modules/@deck.gl/core/dist/lib/composite-layer.js + var TRACE_RENDER_LAYERS2 = "compositeLayer.renderLayers"; + var CompositeLayer = class extends layer_default { + /** `true` if this layer renders other layers */ + get isComposite() { + return true; + } + /** `true` if the layer renders to screen */ + get isDrawable() { + return false; + } + /** Returns true if all async resources are loaded */ + get isLoaded() { + return super.isLoaded && this.getSubLayers().every((layer) => layer.isLoaded); + } + /** Return last rendered sub layers */ + getSubLayers() { + return this.internalState && this.internalState.subLayers || []; + } + // initializeState is usually not needed for composite layers + // Provide empty definition to disable check for missing definition + // eslint-disable-next-line @typescript-eslint/no-empty-function + initializeState(context) { + } + /** Updates selected state members and marks the composite layer to need rerender */ + setState(updateObject) { + super.setState(updateObject); + this.setNeedsUpdate(); + } + /** called to augment the info object that is bubbled up from a sublayer + override Layer.getPickingInfo() because decoding / setting uniform do + not apply to a composite layer. */ + getPickingInfo({ info }) { + const { object } = info; + const isDataWrapped = object && object.__source && object.__source.parent && object.__source.parent.id === this.id; + if (!isDataWrapped) { + return info; + } + info.object = object.__source.object; + info.index = object.__source.index; + return info; + } + /** + * Filters sub layers at draw time. Return true if the sub layer should be drawn. + */ + filterSubLayer(context) { + return true; + } + /** Returns true if sub layer needs to be rendered */ + shouldRenderSubLayer(subLayerId, data) { + return data && data.length; + } + /** Returns sub layer class for a specific sublayer */ + getSubLayerClass(subLayerId, DefaultLayerClass) { + const { _subLayerProps: overridingProps } = this.props; + return overridingProps && overridingProps[subLayerId] && overridingProps[subLayerId].type || DefaultLayerClass; + } + /** When casting user data into another format to pass to sublayers, + add reference to the original object and object index */ + getSubLayerRow(row, sourceObject, sourceObjectIndex) { + row.__source = { + parent: this, + object: sourceObject, + index: sourceObjectIndex + }; + return row; + } + /** Some composite layers cast user data into another format before passing to sublayers + We need to unwrap them before calling the accessor so that they see the original data + objects */ + getSubLayerAccessor(accessor) { + if (typeof accessor === "function") { + const objectInfo = { + index: -1, + // @ts-ignore accessing resolved data + data: this.props.data, + target: [] + }; + return (x, i) => { + if (x && x.__source) { + objectInfo.index = x.__source.index; + return accessor(x.__source.object, objectInfo); + } + return accessor(x, i); + }; + } + return accessor; + } + /** Returns sub layer props for a specific sublayer */ + // eslint-disable-next-line complexity + getSubLayerProps(sublayerProps = {}) { + const { opacity, pickable, visible, parameters, getPolygonOffset, highlightedObjectIndex, autoHighlight, highlightColor, coordinateSystem, coordinateOrigin, wrapLongitude, positionFormat, modelMatrix, extensions, fetch: fetch2, operation, _subLayerProps: overridingProps } = this.props; + const newProps = { + id: "", + updateTriggers: {}, + opacity, + pickable, + visible, + parameters, + getPolygonOffset, + highlightedObjectIndex, + autoHighlight, + highlightColor, + coordinateSystem, + coordinateOrigin, + wrapLongitude, + positionFormat, + modelMatrix, + extensions, + fetch: fetch2, + operation + }; + const overridingSublayerProps = overridingProps && sublayerProps.id && overridingProps[sublayerProps.id]; + const overridingSublayerTriggers = overridingSublayerProps && overridingSublayerProps.updateTriggers; + const sublayerId = sublayerProps.id || "sublayer"; + if (overridingSublayerProps) { + const propTypes = this.props[PROP_TYPES_SYMBOL]; + const subLayerPropTypes = sublayerProps.type ? sublayerProps.type._propTypes : {}; + for (const key in overridingSublayerProps) { + const propType = subLayerPropTypes[key] || propTypes[key]; + if (propType && propType.type === "accessor") { + overridingSublayerProps[key] = this.getSubLayerAccessor(overridingSublayerProps[key]); + } + } + } + Object.assign( + newProps, + sublayerProps, + // experimental feature that allows users to override sublayer props via parent layer prop + overridingSublayerProps + ); + newProps.id = `${this.props.id}-${sublayerId}`; + newProps.updateTriggers = { + all: this.props.updateTriggers?.all, + ...sublayerProps.updateTriggers, + ...overridingSublayerTriggers + }; + for (const extension of extensions) { + const passThroughProps = extension.getSubLayerProps.call(this, extension); + if (passThroughProps) { + Object.assign(newProps, passThroughProps, { + updateTriggers: Object.assign(newProps.updateTriggers, passThroughProps.updateTriggers) + }); + } + } + return newProps; + } + /** Update sub layers to highlight the hovered object */ + _updateAutoHighlight(info) { + for (const layer of this.getSubLayers()) { + layer.updateAutoHighlight(info); + } + } + /** Override base Layer method */ + _getAttributeManager() { + return null; + } + /** (Internal) Called after an update to rerender sub layers */ + _postUpdate(updateParams, forceUpdate) { + let subLayers = this.internalState.subLayers; + const shouldUpdate = !subLayers || this.needsUpdate(); + if (shouldUpdate) { + const subLayersList = this.renderLayers(); + subLayers = flatten(subLayersList, Boolean); + this.internalState.subLayers = subLayers; + } + debug(TRACE_RENDER_LAYERS2, this, shouldUpdate, subLayers); + for (const layer of subLayers) { + layer.parent = this; + } + } + }; + CompositeLayer.layerName = "CompositeLayer"; + var composite_layer_default = CompositeLayer; + + // node_modules/@deck.gl/core/dist/controllers/globe-controller.js + var DEGREES_TO_RADIANS6 = Math.PI / 180; + var RADIANS_TO_DEGREES4 = 180 / Math.PI; + function degreesToPixels(angle4, zoom = 0) { + const radians4 = Math.min(180, angle4) * DEGREES_TO_RADIANS6; + const size = GLOBE_RADIUS * 2 * Math.sin(radians4 / 2); + return size * Math.pow(2, zoom); + } + function pixelsToDegrees(pixels, zoom = 0) { + const size = pixels / Math.pow(2, zoom); + const radians4 = Math.asin(Math.min(1, size / GLOBE_RADIUS / 2)) * 2; + return radians4 * RADIANS_TO_DEGREES4; + } + var GlobeState = class extends MapState { + constructor(options) { + const { startPanPos, ...mapStateOptions } = options; + mapStateOptions.normalize = false; + super(mapStateOptions); + if (startPanPos !== void 0) { + this._state.startPanPos = startPanPos; + } + } + panStart({ pos }) { + const { latitude, longitude, zoom } = this.getViewportProps(); + return this._getUpdatedState({ + startPanLngLat: [longitude, latitude], + startPanPos: pos, + startZoom: zoom + }); + } + pan({ pos, startPos }) { + const state = this.getState(); + const startPanLngLat = state.startPanLngLat || this._unproject(startPos); + if (!startPanLngLat) + return this; + const startZoom = state.startZoom ?? this.getViewportProps().zoom; + const startPanPos = state.startPanPos || startPos; + const coords = [startPanLngLat[0], startPanLngLat[1], startZoom]; + const viewport = this.makeViewport(this.getViewportProps()); + const newProps = viewport.panByPosition(coords, pos, startPanPos); + return this._getUpdatedState(newProps); + } + panEnd() { + return this._getUpdatedState({ + startPanLngLat: null, + startPanPos: null, + startZoom: null + }); + } + zoom({ scale: scale5 }) { + const startZoom = this.getState().startZoom || this.getViewportProps().zoom; + const zoom = startZoom + Math.log2(scale5); + return this._getUpdatedState({ zoom }); + } + applyConstraints(props) { + const { longitude, latitude, maxBounds } = props; + props.zoom = this._constrainZoom(props.zoom, props); + if (longitude < -180 || longitude > 180) { + props.longitude = mod2(longitude + 180, 360) - 180; + } + props.latitude = clamp(latitude, -MAX_LATITUDE, MAX_LATITUDE); + if (maxBounds) { + props.longitude = clamp(props.longitude, maxBounds[0][0], maxBounds[1][0]); + props.latitude = clamp(props.latitude, maxBounds[0][1], maxBounds[1][1]); + } + if (maxBounds) { + const effectiveZoom = props.zoom - zoomAdjust(latitude); + const lngSpan = maxBounds[1][0] - maxBounds[0][0]; + const latSpan = maxBounds[1][1] - maxBounds[0][1]; + if (latSpan > 0 && latSpan < MAX_LATITUDE * 2) { + const halfHeightDegrees = Math.min(pixelsToDegrees(props.height, effectiveZoom), latSpan) / 2; + props.latitude = clamp(props.latitude, maxBounds[0][1] + halfHeightDegrees, maxBounds[1][1] - halfHeightDegrees); + } + if (lngSpan > 0 && lngSpan < 360) { + const halfWidthDegrees = Math.min(pixelsToDegrees(props.width / Math.cos(props.latitude * DEGREES_TO_RADIANS6), effectiveZoom), lngSpan) / 2; + props.longitude = clamp(props.longitude, maxBounds[0][0] + halfWidthDegrees, maxBounds[1][0] - halfWidthDegrees); + } + } + if (props.latitude !== latitude) { + props.zoom += zoomAdjust(props.latitude) - zoomAdjust(latitude); + } + return props; + } + _constrainZoom(zoom, props) { + props || (props = this.getViewportProps()); + const { latitude, maxZoom, maxBounds } = props; + let { minZoom } = props; + const ZOOM0 = zoomAdjust(0); + const zoomAdjustment = zoomAdjust(latitude) - ZOOM0; + const shouldApplyMaxBounds = maxBounds !== null && props.width > 0 && props.height > 0; + if (shouldApplyMaxBounds) { + const minLatitude = maxBounds[0][1]; + const maxLatitude = maxBounds[1][1]; + const fitLatitude = Math.sign(minLatitude) === Math.sign(maxLatitude) ? Math.min(Math.abs(minLatitude), Math.abs(maxLatitude)) : 0; + const w = degreesToPixels(maxBounds[1][0] - maxBounds[0][0]) * Math.cos(fitLatitude * DEGREES_TO_RADIANS6); + const h = degreesToPixels(maxBounds[1][1] - maxBounds[0][1]); + if (w > 0) { + minZoom = Math.max(minZoom, Math.log2(props.width / w) + ZOOM0); + } + if (h > 0) { + minZoom = Math.max(minZoom, Math.log2(props.height / h) + ZOOM0); + } + if (minZoom > maxZoom) + minZoom = maxZoom; + } + return clamp(zoom, minZoom + zoomAdjustment, maxZoom + zoomAdjustment); + } + }; + var GlobeController = class extends Controller { + constructor() { + super(...arguments); + this.ControllerState = GlobeState; + this.transition = { + transitionDuration: 300, + transitionInterpolator: new LinearInterpolator(["longitude", "latitude", "zoom"]) + }; + this.dragMode = "pan"; + } + setProps(props) { + super.setProps(props); + this.dragRotate = false; + this.touchRotate = false; + } + }; + + // node_modules/@deck.gl/core/dist/views/globe-view.js + var GlobeView = class extends View { + constructor(props = {}) { + super(props); + } + getViewportType(viewState) { + return viewState.zoom > 12 ? web_mercator_viewport_default : globe_viewport_default; + } + get ControllerType() { + return GlobeController; + } + }; + GlobeView.displayName = "GlobeView"; + var globe_view_default = GlobeView; + + // node_modules/@deck.gl/mapbox/dist/mapbox-layer-group.js + var MapboxLayerGroup = class { + /* eslint-disable no-this-before-super */ + constructor(props) { + assert8(props.id, "id is required"); + this.id = props.id; + this.type = "custom"; + this.renderingMode = props.renderingMode || "3d"; + this.slot = props.slot; + this.beforeId = props.beforeId; + this.map = null; + } + /* Mapbox custom layer methods */ + onAdd(map4, gl) { + this.map = map4; + } + render(gl, renderParameters) { + if (!this.map) + return; + drawLayerGroup(this.map.__deck, this.map, this, renderParameters); + } + }; + + // node_modules/@deck.gl/mapbox/dist/resolve-layer-groups.js + var UNDEFINED_BEFORE_ID = "__UNDEFINED__"; + function getLayerGroupId(layer) { + if (layer.props.beforeId) { + return `deck-layer-group-before:${layer.props.beforeId}`; + } else if (layer.props.slot) { + return `deck-layer-group-slot:${layer.props.slot}`; + } + return "deck-layer-group-last"; + } + function resolveLayerGroups(map4, oldLayers, newLayers) { + if (!map4 || !map4.style || !map4.style._loaded) { + return; + } + const layers = flatten(newLayers, Boolean); + if (oldLayers !== newLayers) { + const prevLayers = flatten(oldLayers, Boolean); + const prevLayerGroupIds = new Set(prevLayers.map((l) => getLayerGroupId(l))); + const newLayerGroupIds = new Set(layers.map((l) => getLayerGroupId(l))); + for (const groupId of prevLayerGroupIds) { + if (!newLayerGroupIds.has(groupId)) { + if (map4.getLayer(groupId)) { + map4.removeLayer(groupId); + } + } + } + } + const layerGroups = {}; + for (const layer of layers) { + const groupId = getLayerGroupId(layer); + const mapboxGroup = map4.getLayer(groupId); + if (mapboxGroup) { + const groupInstance = mapboxGroup.implementation || mapboxGroup; + layerGroups[groupId] = groupInstance; + } else { + const newGroup = new MapboxLayerGroup({ + id: groupId, + slot: layer.props.slot, + beforeId: layer.props.beforeId + }); + layerGroups[groupId] = newGroup; + map4.addLayer(newGroup, layer.props.beforeId); + } + } + const mapLayers = map4.style._order; + for (const [groupId, group2] of Object.entries(layerGroups)) { + const beforeId = group2.beforeId || UNDEFINED_BEFORE_ID; + const expectedGroupIndex = beforeId === UNDEFINED_BEFORE_ID ? mapLayers.length : mapLayers.indexOf(beforeId); + const currentGropupIndex = mapLayers.indexOf(groupId); + if (currentGropupIndex !== expectedGroupIndex - 1) { + const moveBeforeId = beforeId === UNDEFINED_BEFORE_ID ? void 0 : beforeId; + map4.moveLayer(groupId, moveBeforeId); + } + } + } + + // node_modules/@deck.gl/mapbox/dist/deck-utils.js + var MAPBOX_VIEW_ID = "mapbox"; + var TILE_SIZE2 = 512; + var DEGREES_TO_RADIANS7 = Math.PI / 180; + function getDeckInstance({ map: map4, deck }) { + if (map4.__deck) { + return map4.__deck; + } + const customRender = deck.props._customRender; + const onLoad = deck.props.onLoad; + const deckProps = { + ...deck.props, + _customRender: () => { + map4.triggerRepaint(); + customRender?.(""); + } + }; + deckProps.views || (deckProps.views = getDefaultView(map4)); + Object.assign(deckProps, { + width: null, + height: null, + touchAction: "unset", + viewState: getViewState(map4) + }); + if (deck.isInitialized) { + watchMapMove(deck, map4); + } else { + deckProps.onLoad = () => { + onLoad?.(); + watchMapMove(deck, map4); + }; + } + deck.setProps(deckProps); + map4.__deck = deck; + map4.on("render", () => { + if (deck.isInitialized) + afterRender(deck, map4); + }); + return deck; + } + function watchMapMove(deck, map4) { + const _handleMapMove = () => { + if (deck.isInitialized) { + onMapMove(deck, map4); + } else { + map4.off("move", _handleMapMove); + } + }; + map4.on("move", _handleMapMove); + } + function removeDeckInstance(map4) { + map4.__deck?.finalize(); + map4.__deck = null; + } + function getDefaultParameters(map4, interleaved) { + const result = interleaved ? { + depthWriteEnabled: true, + depthCompare: "less-equal", + depthBias: 0, + blend: true, + blendColorSrcFactor: "src-alpha", + blendColorDstFactor: "one-minus-src-alpha", + blendAlphaSrcFactor: "one", + blendAlphaDstFactor: "one-minus-src-alpha", + blendColorOperation: "add", + blendAlphaOperation: "add" + } : {}; + if (getProjection(map4) === "globe") { + result.cullMode = "back"; + } + return result; + } + function drawLayerGroup(deck, map4, group2, renderParameters) { + if (!deck.isInitialized) { + return; + } + let { currentViewport } = deck.userData; + let clearStack = false; + if (!currentViewport) { + currentViewport = getViewport(deck, map4, renderParameters); + deck.userData.currentViewport = currentViewport; + clearStack = true; + } + if (!currentViewport) { + return; + } + deck._drawLayers("mapbox-repaint", { + viewports: [currentViewport], + layerFilter: (params) => { + if (deck.props.layerFilter && !deck.props.layerFilter(params)) { + return false; + } + const layer = params.layer; + if (layer.props.beforeId === group2.beforeId && layer.props.slot === group2.slot) { + return true; + } + return false; + }, + clearStack, + clearCanvas: false + }); + } + function getProjection(map4) { + const projection = map4.getProjection?.(); + const type = ( + // maplibre projection spec + projection?.type || // mapbox projection spec + projection?.name + ); + if (type === "globe") { + return "globe"; + } + if (type && type !== "mercator") { + throw new Error("Unsupported projection"); + } + return "mercator"; + } + function getDefaultView(map4) { + if (getProjection(map4) === "globe") { + return new globe_view_default({ id: MAPBOX_VIEW_ID }); + } + return new map_view_default({ id: MAPBOX_VIEW_ID }); + } + function getViewState(map4) { + const { lng, lat } = map4.getCenter(); + const viewState = { + // Longitude returned by getCenter can be outside of [-180, 180] when zooming near the anti meridian + // https://github.com/visgl/deck.gl/issues/6894 + longitude: (lng + 540) % 360 - 180, + latitude: lat, + zoom: map4.getZoom(), + bearing: map4.getBearing(), + pitch: map4.getPitch(), + padding: map4.getPadding(), + repeat: map4.getRenderWorldCopies() + }; + if (map4.getTerrain?.()) { + centerCameraOnTerrain(map4, viewState); + } + return viewState; + } + function centerCameraOnTerrain(map4, viewState) { + if (map4.getFreeCameraOptions) { + const { position } = map4.getFreeCameraOptions(); + if (!position || position.z === void 0) { + return; + } + const height = map4.transform.height; + const { longitude, latitude, pitch } = viewState; + const cameraX = position.x * TILE_SIZE2; + const cameraY = (1 - position.y) * TILE_SIZE2; + const cameraZ = position.z * TILE_SIZE2; + const center = lngLatToWorld([longitude, latitude]); + const dx = cameraX - center[0]; + const dy = cameraY - center[1]; + const cameraToCenterDistanceGround = Math.sqrt(dx * dx + dy * dy); + const pitchRadians = pitch * DEGREES_TO_RADIANS7; + const altitudePixels = 1.5 * height; + const scale5 = pitchRadians < 1e-3 ? ( + // Pitch angle too small to deduce the look at point, assume elevation is 0 + altitudePixels * Math.cos(pitchRadians) / cameraZ + ) : altitudePixels * Math.sin(pitchRadians) / cameraToCenterDistanceGround; + viewState.zoom = Math.log2(scale5); + const cameraZFromSurface = altitudePixels * Math.cos(pitchRadians) / scale5; + const surfaceElevation = cameraZ - cameraZFromSurface; + viewState.position = [0, 0, surfaceElevation / unitsPerMeter(latitude)]; + } else if (typeof map4.transform.elevation === "number") { + viewState.position = [0, 0, map4.transform.elevation]; + } + } + function getViewport(deck, map4, renderParameters) { + const viewState = getViewState(map4); + const view = deck.getView(MAPBOX_VIEW_ID) || getDefaultView(map4); + if (renderParameters) { + view.props.nearZMultiplier = 0.2; + } + const nearZ = renderParameters?.nearZ ?? map4.transform._nearZ; + const farZ = renderParameters?.farZ ?? map4.transform._farZ; + if (Number.isFinite(nearZ)) { + viewState.nearZ = nearZ / map4.transform.height; + viewState.farZ = farZ / map4.transform.height; + } + return view.makeViewport({ + width: deck.width, + height: deck.height, + viewState + }); + } + function afterRender(deck, map4) { + const deckLayers = flatten(deck.props.layers, Boolean); + const hasNonMapboxLayers = deckLayers.some((layer) => layer && !map4.getLayer(getLayerGroupId(layer))); + let viewports = deck.getViewports(); + const mapboxViewportIdx = viewports.findIndex((vp) => vp.id === MAPBOX_VIEW_ID); + const hasNonMapboxViews = viewports.length > 1 || mapboxViewportIdx < 0; + if (hasNonMapboxLayers || hasNonMapboxViews) { + if (mapboxViewportIdx >= 0) { + viewports = viewports.slice(); + const mapboxViewport = getViewport(deck, map4); + if (mapboxViewport) { + viewports[mapboxViewportIdx] = mapboxViewport; + } else { + viewports.splice(mapboxViewportIdx, 1); + } + } + deck._drawLayers("mapbox-repaint", { + viewports, + layerFilter: (params) => (!deck.props.layerFilter || deck.props.layerFilter(params)) && (params.viewport.id !== MAPBOX_VIEW_ID || !map4.getLayer(getLayerGroupId(params.layer))), + clearCanvas: false + }); + } else { + const device = deck.device; + const gl = device?.gl; + deck.props.onBeforeRender?.({ device, gl }); + deck.props.onAfterRender?.({ device, gl }); + } + deck.userData.currentViewport = null; + } + function onMapMove(deck, map4) { + deck.setProps({ + viewState: getViewState(map4) + }); + deck.needsRedraw({ clearRedrawFlags: true }); + } + + // node_modules/@deck.gl/mapbox/dist/mapbox-overlay.js + var MapboxOverlay = class { + constructor(props) { + this._handleStyleChange = () => { + this._resolveLayers(this._map, this._deck, this._props.layers, this._props.layers); + if (!this._map) + return; + const projection = getProjection(this._map); + if (projection) { + this._deck?.setProps({ views: this._getViews(this._map) }); + } + }; + this._updateContainerSize = () => { + if (this._map && this._container) { + const { clientWidth, clientHeight } = this._map.getContainer(); + Object.assign(this._container.style, { + width: `${clientWidth}px`, + height: `${clientHeight}px` + }); + } + }; + this._updateViewState = () => { + const deck = this._deck; + const map4 = this._map; + if (deck && map4) { + deck.setProps({ + views: this._getViews(map4), + viewState: getViewState(map4) + }); + if (deck.isInitialized) { + deck.redraw(); + } + } + }; + this._handleMouseEvent = (event) => { + const deck = this._deck; + if (!deck || !deck.isInitialized) { + return; + } + const mockEvent = { + type: event.type, + offsetCenter: event.point, + srcEvent: event + }; + const lastDown = this._lastMouseDownPoint; + if (!event.point && lastDown) { + mockEvent.deltaX = event.originalEvent.clientX - lastDown.clientX; + mockEvent.deltaY = event.originalEvent.clientY - lastDown.clientY; + mockEvent.offsetCenter = { + x: lastDown.x + mockEvent.deltaX, + y: lastDown.y + mockEvent.deltaY + }; + } + switch (mockEvent.type) { + case "mousedown": + deck._onPointerDown(mockEvent); + this._lastMouseDownPoint = { + ...event.point, + clientX: event.originalEvent.clientX, + clientY: event.originalEvent.clientY + }; + break; + case "dragstart": + mockEvent.type = "panstart"; + deck._onEvent(mockEvent); + break; + case "drag": + mockEvent.type = "panmove"; + deck._onEvent(mockEvent); + break; + case "dragend": + mockEvent.type = "panend"; + deck._onEvent(mockEvent); + break; + case "click": + mockEvent.tapCount = 1; + deck._onEvent(mockEvent); + break; + case "dblclick": + mockEvent.type = "click"; + mockEvent.tapCount = 2; + deck._onEvent(mockEvent); + break; + case "mousemove": + mockEvent.type = "pointermove"; + deck._onPointerMove(mockEvent); + break; + case "mouseout": + mockEvent.type = "pointerleave"; + deck._onPointerMove(mockEvent); + break; + default: + return; + } + }; + const { interleaved = false } = props; + this._interleaved = interleaved; + this._props = this.filterProps(props); + } + /** Filter out props to pass to Deck **/ + filterProps(props) { + const { interleaved = false, useDevicePixels, ...deckProps } = props; + if (!interleaved && useDevicePixels !== void 0) { + deckProps.useDevicePixels = useDevicePixels; + } + return deckProps; + } + /** Update (partial) props of the underlying Deck instance. */ + setProps(props) { + if (this._interleaved && props.layers) { + this._resolveLayers(this._map, this._deck, this._props.layers, props.layers); + } + Object.assign(this._props, this.filterProps(props)); + if (this._deck && this._map) { + this._deck.setProps({ + ...this._props, + views: this._getViews(this._map), + parameters: { + ...getDefaultParameters(this._map, this._interleaved), + ...this._props.parameters + } + }); + } + } + // The local Map type is for internal typecheck only. It does not necesarily satisefy mapbox/maplibre types at runtime. + // Do not restrict the argument type here to avoid type conflict. + /** Called when the control is added to a map */ + onAdd(map4) { + this._map = map4; + return this._interleaved ? this._onAddInterleaved(map4) : this._onAddOverlaid(map4); + } + _onAddOverlaid(map4) { + const container = document.createElement("div"); + Object.assign(container.style, { + position: "absolute", + left: 0, + top: 0, + textAlign: "initial", + pointerEvents: "none" + }); + this._container = container; + this._deck = new deck_default({ + ...this._props, + parent: container, + parameters: { ...getDefaultParameters(map4, false), ...this._props.parameters }, + views: this._getViews(map4), + viewState: getViewState(map4) + }); + map4.on("resize", this._updateContainerSize); + map4.on("render", this._updateViewState); + map4.on("mousedown", this._handleMouseEvent); + map4.on("dragstart", this._handleMouseEvent); + map4.on("drag", this._handleMouseEvent); + map4.on("dragend", this._handleMouseEvent); + map4.on("mousemove", this._handleMouseEvent); + map4.on("mouseout", this._handleMouseEvent); + map4.on("click", this._handleMouseEvent); + map4.on("dblclick", this._handleMouseEvent); + this._updateContainerSize(); + return container; + } + _onAddInterleaved(map4) { + const gl = map4.painter.context.gl; + if (gl instanceof WebGLRenderingContext) { + log_default.warn("Incompatible basemap library. See: https://deck.gl/docs/api-reference/mapbox/overview#compatibility")(); + } + this._deck = getDeckInstance({ + map: map4, + deck: new deck_default({ + ...this._props, + views: this._getViews(map4), + gl, + parameters: { ...getDefaultParameters(map4, true), ...this._props.parameters } + }) + }); + map4.on("styledata", this._handleStyleChange); + this._resolveLayers(map4, this._deck, [], this._props.layers); + return document.createElement("div"); + } + _resolveLayers(map4, _deck, prevLayers, newLayers) { + resolveLayerGroups(map4, prevLayers, newLayers); + } + /** Called when the control is removed from a map */ + onRemove() { + const map4 = this._map; + if (map4) { + if (this._interleaved) { + this._onRemoveInterleaved(map4); + } else { + this._onRemoveOverlaid(map4); + } + } + this._deck = void 0; + this._map = void 0; + this._container = void 0; + } + _onRemoveOverlaid(map4) { + map4.off("resize", this._updateContainerSize); + map4.off("render", this._updateViewState); + map4.off("mousedown", this._handleMouseEvent); + map4.off("dragstart", this._handleMouseEvent); + map4.off("drag", this._handleMouseEvent); + map4.off("dragend", this._handleMouseEvent); + map4.off("mousemove", this._handleMouseEvent); + map4.off("mouseout", this._handleMouseEvent); + map4.off("click", this._handleMouseEvent); + map4.off("dblclick", this._handleMouseEvent); + this._deck?.finalize(); + } + _onRemoveInterleaved(map4) { + map4.off("styledata", this._handleStyleChange); + this._resolveLayers(map4, this._deck, this._props.layers, []); + removeDeckInstance(map4); + } + getDefaultPosition() { + return "top-left"; + } + /** Forwards the Deck.pickObject method */ + pickObject(params) { + assert8(this._deck); + return this._deck.pickObject(params); + } + /** Forwards the Deck.pickMultipleObjects method */ + pickMultipleObjects(params) { + assert8(this._deck); + return this._deck.pickMultipleObjects(params); + } + /** Forwards the Deck.pickObjects method */ + pickObjects(params) { + assert8(this._deck); + return this._deck.pickObjects(params); + } + /** Remove from map and releases all resources */ + finalize() { + if (this._map) { + this._map.removeControl(this); + } + } + /** If interleaved: true, returns base map's canvas, otherwise forwards the Deck.getCanvas method. */ + getCanvas() { + if (!this._map) { + return null; + } + return this._interleaved ? this._map.getCanvas() : this._deck.getCanvas(); + } + _getViews(map4) { + if (!this._props.views) { + return getDefaultView(map4); + } + const views = Array.isArray(this._props.views) ? this._props.views : [this._props.views]; + const hasMapboxView = views.some((v) => v.id === MAPBOX_VIEW_ID); + if (hasMapboxView) { + return this._props.views; + } + return [getDefaultView(map4), ...views]; + } + }; + + // node_modules/@flowmap.gl/layers/dist/AnimatedFlowLinesLayer/AnimatedFlowLinesLayerFragment.glsl.js + var AnimatedFlowLinesLayerFragment_glsl_default = `#version 300 es +#define SHADER_NAME animated-flow-lines-layer-fragment-shader + +precision highp float; + +in vec4 vColor; +in float sourceToTarget; +in vec2 uv; + +out vec4 fragColor; + +void main(void) { + geometry.uv = uv; + + fragColor = vec4(vColor.xyz, vColor.w * smoothstep(1.0 - animatedFlowLines.animationTailLength, 1.0, fract(sourceToTarget))); + + DECKGL_FILTER_COLOR(fragColor, geometry); +} +`; + + // node_modules/@flowmap.gl/layers/dist/AnimatedFlowLinesLayer/AnimatedFlowLinesLayerVertex.glsl.js + var AnimatedFlowLinesLayerVertex_glsl_default = `#version 300 es +#define SHADER_NAME animated-flow-lines-layer-vertex-shader +#define SPEED 0.015 +#define NUM_PARTS 5.0 + +in vec3 positions; +in vec3 instanceSourcePositions; +in vec3 instanceTargetPositions; +in vec3 instanceSourcePositions64Low; +in vec3 instanceTargetPositions64Low; +in vec4 instanceColors; +in vec3 instancePickingColors; +in float instanceWidths; +in float instancePickable; +in float instanceStaggering; + +out vec4 vColor; +out float sourceToTarget; +out vec2 uv; + +// offset vector by strokeWidth pixels +// offset_direction is -1 (left) or 1 (right) +vec2 getExtrusionOffset(vec2 line_clipspace, float offset_direction, float width) { + // normalized direction of the line + vec2 dir_screenspace = normalize(line_clipspace * project.viewportSize); + // rotate by 90 degrees + dir_screenspace = vec2(-dir_screenspace.y, dir_screenspace.x); + + return dir_screenspace * offset_direction * width / 2.0; +} + +void main(void) { + geometry.worldPosition = instanceSourcePositions; + geometry.worldPositionAlt = instanceTargetPositions; + + // Position + vec4 source_commonspace; + vec4 target_commonspace; + vec4 source = project_position_to_clipspace(instanceSourcePositions, instanceSourcePositions64Low, vec3(0.), source_commonspace); + vec4 target = project_position_to_clipspace(instanceTargetPositions, instanceTargetPositions64Low, vec3(0.), target_commonspace); + + float widthPixels = instanceWidths * animatedFlowLines.thicknessUnit; + + + // linear interpolation of source & target to pick right coord + float segmentIndex = positions.x; + vec4 p = mix(source, target, segmentIndex); + geometry.position = mix(source_commonspace, target_commonspace, segmentIndex); + uv = positions.xy; + geometry.uv = uv; + if (instancePickable > 0.5) { + geometry.pickingColor = instancePickingColors; + } + + // extrude + vec3 offset = vec3( + getExtrusionOffset(target.xy - source.xy, positions.y, widthPixels), + 0.0); + DECKGL_FILTER_SIZE(offset, geometry); + gl_Position = p + vec4(project_pixel_size_to_clipspace(offset.xy), 0.0, 0.0); + DECKGL_FILTER_GL_POSITION(gl_Position, geometry); + + // Color + vColor = vec4(instanceColors.rgb, instanceColors.a * layer.opacity); + DECKGL_FILTER_COLOR(vColor, geometry); + + sourceToTarget = positions.x * length(source - target) * NUM_PARTS - animatedFlowLines.currentTime * SPEED + instanceStaggering; +} +`; + + // node_modules/@flowmap.gl/layers/dist/AnimatedFlowLinesLayer/AnimatedFlowLinesLayerUniforms.js + var uniformBlock5 = `layout(std140) uniform animatedFlowLinesUniforms { + float thicknessUnit; + float animationTailLength; + float currentTime; +} animatedFlowLines; +`; + var animatedFlowLinesUniforms = { + name: "animatedFlowLines", + vs: uniformBlock5, + fs: uniformBlock5, + uniformTypes: { + thicknessUnit: "f32", + animationTailLength: "f32", + currentTime: "f32" + } + }; + + // node_modules/@flowmap.gl/layers/dist/AnimatedFlowLinesLayer/AnimatedFlowLinesLayer.js + var DEFAULT_COLOR = [0, 132, 193, 255]; + var loopLength = 1800; + var animationSpeed = 20; + var loopTime = loopLength / animationSpeed; + var AnimatedFlowLinesLayer = class extends layer_default { + constructor(props) { + super(props); + } + getShaders() { + return super.getShaders({ + vs: AnimatedFlowLinesLayerVertex_glsl_default, + fs: AnimatedFlowLinesLayerFragment_glsl_default, + modules: [project32_default, picking_default, animatedFlowLinesUniforms] + }); + } + initializeState() { + this.getAttributeManager().addInstanced({ + instanceSourcePositions: { + size: 3, + type: "float64", + transition: true, + accessor: "getSourcePosition" + }, + instanceTargetPositions: { + size: 3, + type: "float64", + transition: true, + accessor: "getTargetPosition" + }, + instanceColors: { + size: 4, + type: "unorm8", + transition: true, + accessor: "getColor", + defaultValue: [0, 0, 0, 255] + }, + instanceWidths: { + size: 1, + transition: true, + accessor: "getThickness", + defaultValue: 1 + }, + instanceStaggering: { + accessor: "getStaggering", + size: 1, + transition: false + }, + instancePickable: { + accessor: "getPickable", + size: 1, + transition: false + } + }); + this.setState({ model: this._getModel() }); + } + getNeedsRedraw() { + return "animation"; + } + updateState(params) { + super.updateState(params); + const { changeFlags } = params; + if (!this.state.model || changeFlags.extensionsChanged) { + this.state.model?.destroy(); + this.setState({ model: this._getModel() }); + this.getAttributeManager().invalidateAll(); + } + } + draw() { + const { thicknessUnit = 15 * 2, animationTailLength = 0.7 } = this.props; + const timestamp = Date.now() / 1e3; + const animationTime = timestamp % loopTime / loopTime * loopLength; + const model = this.state.model; + if (!model) { + return; + } + model.shaderInputs.setProps({ + animatedFlowLines: { + thicknessUnit: thicknessUnit * 4, + animationTailLength, + currentTime: animationTime + } + }); + model.draw(this.context.renderPass); + } + _getModel() { + const { id } = this.props; + const positions = [0, -1, 0, 0, 1, 0, 1, -1, 0, 1, 1, 0]; + return new Model(this.context.device, { + ...this.getShaders(), + id, + bufferLayout: this.getAttributeManager().getBufferLayouts(), + geometry: new Geometry({ + topology: "triangle-strip", + attributes: { + positions: { size: 3, value: new Float32Array(positions) } + } + }), + isInstanced: true + }); + } + }; + AnimatedFlowLinesLayer.defaultProps = { + currentTime: 0, + animationTailLength: 0.7, + getSourcePosition: { type: "accessor", value: (d) => [0, 0] }, + getTargetPosition: { type: "accessor", value: (d) => [0, 0] }, + getPickable: { type: "accessor", value: (d) => 1 }, + getStaggering: { + type: "accessor", + value: (d, { index: index2 }) => Math.random() + }, + getColor: { type: "accessor", value: DEFAULT_COLOR }, + getThickness: { type: "accessor", value: 1 }, + thicknessUnit: 15 * 2, + parameters: { + depthTest: false + } + }; + var AnimatedFlowLinesLayer_default = AnimatedFlowLinesLayer; + + // node_modules/@flowmap.gl/layers/dist/AnimatedFlowLinesLayer/index.js + var AnimatedFlowLinesLayer_default2 = AnimatedFlowLinesLayer_default; + + // node_modules/@flowmap.gl/layers/dist/FlowLinesLayer/FlowLinesLayerUniforms.js + var uniformBlock6 = `layout(std140) uniform flowLinesUniforms { + vec4 outlineColor; + float thicknessUnit; + float outlineThickness; + float drawOutline; + float gap; + float curviness; +} flowLines; +`; + var flowLinesUniforms = { + name: "flowLines", + vs: uniformBlock6, + fs: uniformBlock6, + uniformTypes: { + outlineColor: "vec4", + thicknessUnit: "f32", + outlineThickness: "f32", + drawOutline: "f32", + gap: "f32", + curviness: "f32" + } + }; + + // node_modules/@flowmap.gl/layers/dist/CurvedFlowLinesLayer/CurvedFlowLinesLayerFragment.glsl.js + var CurvedFlowLinesLayerFragment_glsl_default = `#version 300 es +#define SHADER_NAME curved-flow-line-layer-fragment-shader + +precision highp float; + +in vec4 vColor; +in vec2 uv; +in vec3 vBarycentrics; +flat in vec3 vEdgeMask; + +out vec4 fragColor; + +void main(void) { + if (vColor.a == 0.0) { + discard; + } + + geometry.uv = uv; + fragColor = vColor; + + if (flowLines.drawOutline > 0.5 && !bool(picking.isActive)) { + vec3 edgeDistancePx = vBarycentrics / max(fwidth(vBarycentrics), vec3(1e-4)); + vec3 maskedDistancePx = mix(vec3(1e6), edgeDistancePx, step(vec3(0.5), vEdgeMask)); + float minBoundaryDistancePx = min( + maskedDistancePx.x, + min(maskedDistancePx.y, maskedDistancePx.z) + ); + float outlineMix = 1.0 - smoothstep( + max(flowLines.outlineThickness - 1.0, 0.0), + flowLines.outlineThickness, + minBoundaryDistancePx + ); + fragColor = mix( + fragColor, + vec4(flowLines.outlineColor.rgb, flowLines.outlineColor.a * fragColor.a), + outlineMix + ); + } + + DECKGL_FILTER_COLOR(fragColor, geometry); +} +`; + + // node_modules/@flowmap.gl/layers/dist/CurvedFlowLinesLayer/CurvedFlowLinesLayerVertex.glsl.js + var HEAD_START_T = (1 - 1 / 24).toFixed(8); + var CurvedFlowLinesLayerVertex_glsl_default = `#version 300 es +#define SHADER_NAME curved-flow-line-layer-vertex-shader + +in vec3 positions; +in vec3 barycentrics; +in vec3 edgeMasks; +in vec4 instanceColors; +in float instanceThickness; +in vec3 instanceSourcePositions; +in vec3 instanceTargetPositions; +in vec3 instanceSourcePositions64Low; +in vec3 instanceTargetPositions64Low; +in vec3 instancePickingColors; +in vec2 instanceEndpointOffsets; +in float instancePickable; +in float instanceCurveOffset; + +out vec4 vColor; +out vec2 uv; +out vec3 vBarycentrics; +flat out vec3 vEdgeMask; + +vec3 quadraticBezier(vec3 p0, vec3 p1, vec3 p2, float t) { + float oneMinusT = 1.0 - t; + return + oneMinusT * oneMinusT * p0 + + 2.0 * oneMinusT * t * p1 + + t * t * p2; +} + +vec3 quadraticBezierTangent(vec3 p0, vec3 p1, vec3 p2, float t) { + return 2.0 * (1.0 - t) * (p1 - p0) + 2.0 * t * (p2 - p1); +} + +void main(void) { + geometry.worldPosition = instanceSourcePositions; + geometry.worldPositionAlt = instanceTargetPositions; + + vec4 source_commonspace; + vec4 target_commonspace; + project_position_to_clipspace( + instanceSourcePositions, + instanceSourcePositions64Low, + vec3(0.0), + source_commonspace + ); + project_position_to_clipspace( + instanceTargetPositions, + instanceTargetPositions64Low, + vec3(0.0), + target_commonspace + ); + + vec2 chord = target_commonspace.xy - source_commonspace.xy; + float chordLengthCommon = max(length(chord), 1e-6); + float startTrim = clamp( + project_pixel_size(instanceEndpointOffsets.x) / chordLengthCommon, + 0.0, + 0.35 + ); + float endTrim = 1.0 - clamp( + project_pixel_size(instanceEndpointOffsets.y) / chordLengthCommon, + 0.0, + 0.35 + ); + endTrim = max(startTrim + 0.05, endTrim); + float baseHeadBacktrackT = project_pixel_size( + instanceThickness * 3.0 * flowLines.thicknessUnit + ) / chordLengthCommon; + float availableSpanT = max(endTrim - startTrim, 0.0); + float headBacktrackT = min(baseHeadBacktrackT, availableSpanT * 0.45); + float headScale = baseHeadBacktrackT > 1e-6 + ? clamp(headBacktrackT / baseHeadBacktrackT, 0.0, 1.0) + : 1.0; + // A soft nonlinear fade of the head deformation avoids tiny heads folding + // into themselves while still allowing them to collapse back toward the strip. + float headDeformation = smoothstep(0.0, 1.0, headScale); + float shaftEndTrim = max(startTrim + 0.02, endTrim - headBacktrackT); + + float curveT = positions.x < 1.0 + ? mix(startTrim, shaftEndTrim, positions.x / ${HEAD_START_T}) + : endTrim; + float headWeight = smoothstep(${HEAD_START_T}, 1.0, positions.x); + float tangentT = mix(curveT, endTrim, headWeight); + vec2 curveNormal = normalize(vec2(chord.y, -chord.x)); + if (length(curveNormal) < 1e-6) { + curveNormal = vec2(0.0, 1.0); + } + vec3 control_commonspace = mix( + source_commonspace.xyz, + target_commonspace.xyz, + 0.5 + ); + control_commonspace.xy += curveNormal * project_pixel_size(abs(instanceCurveOffset)) * flowLines.curviness; + + vec3 curvePoint = quadraticBezier( + source_commonspace.xyz, + control_commonspace, + target_commonspace.xyz, + curveT + ); + vec3 tangent = quadraticBezierTangent( + source_commonspace.xyz, + control_commonspace, + target_commonspace.xyz, + tangentT + ); + if (length(tangent.xy) < 1e-6) { + tangent = target_commonspace.xyz - source_commonspace.xyz; + } + + vec2 flowlineDir = normalize(tangent.xy); + vec2 perpendicularDir = vec2(-flowlineDir.y, flowlineDir.x); + float widthScale = mix(1.0, headScale, headWeight); + float lengthScale = mix(1.0, headScale, headWeight); + float shapeY = mix(min(positions.y, 1.0), positions.y, headDeformation); + float shapeZ = positions.z * headDeformation; + float normalDistanceCommon = clamp( + project_pixel_size( + instanceThickness * shapeY * widthScale * flowLines.thicknessUnit + ), + -chordLengthCommon * 0.8, + chordLengthCommon * 0.8 + ); + float tangentDistanceCommon = clamp( + project_pixel_size( + instanceThickness * shapeZ * lengthScale * flowLines.thicknessUnit + ), + -chordLengthCommon * 0.8, + chordLengthCommon * 0.8 + ); + float gapCommon = project_pixel_size(flowLines.gap); + vec3 offsetCommon = vec3( + flowlineDir * tangentDistanceCommon - + perpendicularDir * (normalDistanceCommon + gapCommon), + 0.0 + ); + + geometry.position = vec4(curvePoint, 1.0); + uv = vec2(curveT, positions.y); + geometry.uv = uv; + vBarycentrics = barycentrics; + vEdgeMask = edgeMasks; + if (instancePickable > 0.5) { + geometry.pickingColor = instancePickingColors; + } + + DECKGL_FILTER_SIZE(offsetCommon, geometry); + vec4 position_commonspace = vec4(curvePoint + offsetCommon, 1.0); + gl_Position = project_common_position_to_clipspace(position_commonspace); + DECKGL_FILTER_GL_POSITION(gl_Position, geometry); + + vec4 fillColor = vec4(instanceColors.rgb, instanceColors.a * layer.opacity); + vColor = fillColor; + DECKGL_FILTER_COLOR(vColor, geometry); +} +`; + + // node_modules/@flowmap.gl/layers/dist/CurvedFlowLinesLayer/CurvedFlowLinesLayer.js + var DEFAULT_COLOR2 = [0, 132, 193, 255]; + var SHAFT_SEGMENTS = 24; + var HEAD_START_T2 = 1 - 1 / SHAFT_SEGMENTS; + var CurvedFlowLinesLayer = class extends layer_default { + getShaders() { + return super.getShaders({ + vs: CurvedFlowLinesLayerVertex_glsl_default, + fs: CurvedFlowLinesLayerFragment_glsl_default, + modules: [project32_default, picking_default, flowLinesUniforms] + }); + } + initializeState() { + this.getAttributeManager().addInstanced({ + instanceSourcePositions: { + accessor: "getSourcePosition", + size: 3, + transition: false, + type: "float64" + }, + instanceTargetPositions: { + accessor: "getTargetPosition", + size: 3, + transition: false, + type: "float64" + }, + instanceThickness: { + accessor: "getThickness", + size: 1, + transition: false + }, + instanceEndpointOffsets: { + accessor: "getEndpointOffsets", + size: 2, + transition: false + }, + instanceCurveOffset: { + accessor: "getCurveOffset", + size: 1, + transition: false + }, + instanceColors: { + accessor: "getColor", + size: 4, + type: "unorm8", + transition: false + }, + instancePickable: { + accessor: "getPickable", + size: 1, + transition: false + } + }); + this.setState({ model: this._getModel() }); + } + updateState(params) { + super.updateState(params); + const { changeFlags } = params; + if (!this.state.model || changeFlags.extensionsChanged) { + this.state.model?.destroy(); + this.setState({ model: this._getModel() }); + this.getAttributeManager().invalidateAll(); + } + } + draw() { + const { drawOutline = true, outlineColor = [255, 255, 255, 255], outlineThickness = 1, thicknessUnit = 12, curviness = 1 } = this.props; + const model = this.state.model; + if (!model) { + return; + } + model.shaderInputs.setProps({ + flowLines: { + outlineColor: outlineColor.map((x) => x / 255), + thicknessUnit: thicknessUnit * 2, + outlineThickness, + drawOutline: drawOutline ? 1 : 0, + gap: 0.5, + curviness + } + }); + model.draw(this.context.renderPass); + } + _getModel() { + const { id } = this.props; + const geometry = buildGeometry(); + return new Model(this.context.device, { + id, + ...this.getShaders(), + bufferLayout: this.getAttributeManager().getBufferLayouts(), + geometry: new Geometry({ + topology: "triangle-list", + attributes: { + positions: { size: 3, value: geometry.positions }, + barycentrics: { size: 3, value: geometry.barycentrics }, + edgeMasks: { size: 3, value: geometry.edgeMasks } + } + }), + isInstanced: true + }); + } + }; + CurvedFlowLinesLayer.layerName = "CurvedFlowLinesLayer"; + CurvedFlowLinesLayer.defaultProps = { + getSourcePosition: { type: "accessor", value: (d) => [0, 0] }, + getTargetPosition: { type: "accessor", value: (d) => [0, 0] }, + getColor: { type: "accessor", value: DEFAULT_COLOR2 }, + getThickness: { type: "accessor", value: (d) => d.count }, + getPickable: { type: "accessor", value: () => 1 }, + getCurveOffset: { type: "accessor", value: () => 0 }, + drawOutline: true, + thicknessUnit: 12, + outlineThickness: 1, + outlineColor: [255, 255, 255, 255], + curviness: 1, + parameters: { + depthTest: false + } + }; + var CurvedFlowLinesLayer_default = CurvedFlowLinesLayer; + function buildGeometry() { + const positions = []; + const barycentrics = []; + const edgeMasks = []; + const pushTriangle = (a, b, c2, mask) => { + positions.push(...a, ...b, ...c2); + barycentrics.push(1, 0, 0, 0, 1, 0, 0, 0, 1); + edgeMasks.push(...mask, ...mask, ...mask); + }; + for (let index2 = 0; index2 < SHAFT_SEGMENTS - 1; index2++) { + const t03 = index2 / SHAFT_SEGMENTS; + const t13 = (index2 + 1) / SHAFT_SEGMENTS; + pushTriangle([t03, 1, 0], [t13, 1, 0], [t03, 0, 0], [0, index2 === 0 ? 1 : 0, 1]); + pushTriangle([t03, 0, 0], [t13, 1, 0], [t13, 0, 0], [0, 1, 0]); + } + pushTriangle([HEAD_START_T2, 1, 0], [1, 1.7, -4.4], [HEAD_START_T2, 0, 0], [0, 0, 1]); + pushTriangle([HEAD_START_T2, 0, 0], [1, 1.7, -4.4], [1, 0, 0], [1, 1, 0]); + return { + positions: new Float32Array(positions), + barycentrics: new Float32Array(barycentrics), + edgeMasks: new Float32Array(edgeMasks) + }; + } + + // node_modules/@flowmap.gl/layers/dist/CurvedFlowLinesLayer/index.js + var CurvedFlowLinesLayer_default2 = CurvedFlowLinesLayer_default; + + // node_modules/@flowmap.gl/layers/dist/FlowLinesLayer/FlowLinesLayerFragment.glsl.js + var FlowLinesLayerFragment_glsl_default = `#version 300 es +#define SHADER_NAME flow-line-layer-fragment-shader + +precision highp float; + +in vec4 vColor; +in vec2 uv; +in vec3 vBarycentrics; +flat in vec3 vEdgeMask; + +out vec4 fragColor; + +void main(void) { + if (vColor.a == 0.0) { + discard; + } + + geometry.uv = uv; + fragColor = vColor; + + if (flowLines.drawOutline > 0.5 && !bool(picking.isActive)) { + // For barycentric coordinates, each component trends to 0 on one triangle edge. + // Dividing by fwidth converts that into an approximate edge distance in pixels. + vec3 edgeDistancePx = vBarycentrics / max(fwidth(vBarycentrics), vec3(1e-4)); + // Ignore edges that are only part of the internal triangulation by assigning + // them a large sentinel distance, so only true boundary edges contribute. + vec3 maskedDistancePx = mix(vec3(1e6), edgeDistancePx, step(vec3(0.5), vEdgeMask)); + float minBoundaryDistancePx = min( + maskedDistancePx.x, + min(maskedDistancePx.y, maskedDistancePx.z) + ); + // The outline is inset: fragments within 'outlineThickness' pixels of an + // active boundary edge are mixed toward the outline color. + float outlineMix = 1.0 - smoothstep( + max(flowLines.outlineThickness - 1.0, 0.0), + flowLines.outlineThickness, + minBoundaryDistancePx + ); + fragColor = mix( + fragColor, + vec4(flowLines.outlineColor.rgb, flowLines.outlineColor.a * fragColor.a), + outlineMix + ); + } + + DECKGL_FILTER_COLOR(fragColor, geometry); +} +`; + + // node_modules/@flowmap.gl/layers/dist/FlowLinesLayer/FlowLinesLayerVertex.glsl.js + var FlowLinesLayerVertex_glsl_default = `#version 300 es +#define SHADER_NAME flow-line-layer-vertex-shader + +in vec3 positions; +in vec2 pixelOffsets; +in vec2 outlineOffsetCoefficients; +in vec2 outlineOffsetConstants; +in vec3 barycentrics; +in vec3 edgeMasks; +in vec4 instanceColors; +in float instanceThickness; // 0..0.5 +in vec3 instanceSourcePositions; +in vec3 instanceTargetPositions; +in vec3 instanceSourcePositions64Low; +in vec3 instanceTargetPositions64Low; +in vec3 instancePickingColors; +in vec2 instanceEndpointOffsets; +in float instancePickable; + +out vec4 vColor; +out vec2 uv; +// Interpolated barycentric coordinates let the fragment shader measure distance +// to triangle edges in screen pixels without extra geometry. +out vec3 vBarycentrics; +// The edge mask is constant per triangle and tells the fragment shader which +// barycentric edges are real outline candidates vs internal triangulation seams. +flat out vec3 vEdgeMask; + +void main(void) { + geometry.worldPosition = instanceSourcePositions; + geometry.worldPositionAlt = instanceTargetPositions; + + // Position + vec4 source_commonspace; + vec4 target_commonspace; + project_position_to_clipspace(instanceSourcePositions, instanceSourcePositions64Low, vec3(0.), source_commonspace); + project_position_to_clipspace(instanceTargetPositions, instanceTargetPositions64Low, vec3(0.), target_commonspace); + + // linear interpolation of source & target to pick right coord + float sourceOrTarget = positions.x; + geometry.position = mix(source_commonspace, target_commonspace, sourceOrTarget); + uv = positions.xy; + geometry.uv = uv; + vBarycentrics = barycentrics; + vEdgeMask = edgeMasks; + if (instancePickable > 0.5) { + geometry.pickingColor = instancePickingColors; + } + + // set the clamp limits in pixel size + float lengthCommon = length(target_commonspace - source_commonspace); + vec2 limitedOffsetDistances = clamp( + project_pixel_size(positions.yz) * flowLines.thicknessUnit, + -lengthCommon*.8, lengthCommon*.8 + ); + float startOffsetCommon = project_pixel_size(instanceEndpointOffsets[0]); + float endOffsetCommon = project_pixel_size(instanceEndpointOffsets[1]); + float endpointOffset = mix( + clamp(startOffsetCommon, 0.0, lengthCommon*.2), + -clamp(endOffsetCommon, 0.0, lengthCommon*.2), + positions.x + ); + + vec2 flowlineDir = normalize(target_commonspace.xy - source_commonspace.xy); + vec2 perpendicularDir = vec2(-flowlineDir.y, flowlineDir.x); + vec2 outlinePixelOffset = ( + outlineOffsetCoefficients * flowLines.outlineThickness + + outlineOffsetConstants + ) * flowLines.drawOutline; + vec2 pixelOffsetCommon = project_pixel_size(pixelOffsets + outlinePixelOffset); + float gapCommon = project_pixel_size(flowLines.gap); + vec3 offsetCommon = vec3( + flowlineDir * (instanceThickness * limitedOffsetDistances[1] + pixelOffsetCommon.y + endpointOffset * 1.05) - + perpendicularDir * (instanceThickness * limitedOffsetDistances[0] + gapCommon + pixelOffsetCommon.x), + 0.0 + ); + + DECKGL_FILTER_SIZE(offsetCommon, geometry); + vec4 position_commonspace = mix(source_commonspace, target_commonspace, sourceOrTarget); + vec4 offset_commonspace = vec4(offsetCommon, 0.0); + gl_Position = project_common_position_to_clipspace(position_commonspace + offset_commonspace); + + DECKGL_FILTER_GL_POSITION(gl_Position, geometry); + + vec4 fillColor = vec4(instanceColors.rgb, instanceColors.a * layer.opacity); + vColor = fillColor; + DECKGL_FILTER_COLOR(vColor, geometry); +} +`; + + // node_modules/@flowmap.gl/layers/dist/FlowLinesLayer/FlowLinesLayer.js + var DEFAULT_COLOR3 = [0, 132, 193, 255]; + var POSITIONS = [ + 1, + 0, + 0, + // 0 + 1, + 2, + -3, + // 1 + 1, + 1, + -3, + // 2 + 1, + 0, + 0, + // 0 + 1, + 1, + -3, + // 2 + 0, + 1, + 0, + // 3 + 1, + 0, + 0, + // 0 + 0, + 1, + 0, + // 3 + 0, + 0, + 0 + // 4 + ]; + var INNER_SIDE_OUTLINE_THICKNESS = 0.5; + var PIXEL_OFFSETS = new Float32Array(9 * 2); + var OUTLINE_OFFSET_COEFFICIENTS = new Float32Array([ + 0, + 2, + 2, + -1, + 1, + -1, + 0, + 2, + 1, + -1, + 1, + -1, + 0, + 2, + 1, + -1, + 0, + -1 + ]); + var OUTLINE_OFFSET_CONSTANTS = new Float32Array([ + -INNER_SIDE_OUTLINE_THICKNESS, + 0, + 0, + 0, + 0, + 0, + -INNER_SIDE_OUTLINE_THICKNESS, + 0, + 0, + 0, + 0, + 0, + -INNER_SIDE_OUTLINE_THICKNESS, + 0, + 0, + 0, + -INNER_SIDE_OUTLINE_THICKNESS, + 0 + ]); + var BARYCENTRICS = new Float32Array([ + 1, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 1, + 1, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 1, + 1, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 1 + ]); + var EDGE_MASKS = new Float32Array([ + 1, + 0, + 1, + 1, + 0, + 1, + 1, + 0, + 1, + 1, + 0, + 0, + 1, + 0, + 0, + 1, + 0, + 0, + 1, + 1, + 0, + 1, + 1, + 0, + 1, + 1, + 0 + ]); + var FlowLinesLayer = class extends layer_default { + // props!: Props; + constructor(props) { + super(props); + } + getShaders() { + return super.getShaders({ + vs: FlowLinesLayerVertex_glsl_default, + fs: FlowLinesLayerFragment_glsl_default, + modules: [project32_default, picking_default, flowLinesUniforms] + }); + } + initializeState() { + this.getAttributeManager().addInstanced({ + instanceSourcePositions: { + accessor: "getSourcePosition", + size: 3, + transition: false, + type: "float64" + }, + instanceTargetPositions: { + accessor: "getTargetPosition", + size: 3, + transition: false, + type: "float64" + }, + instanceThickness: { + accessor: "getThickness", + size: 1, + transition: false + }, + instanceEndpointOffsets: { + accessor: "getEndpointOffsets", + size: 2, + transition: false + }, + instanceColors: { + accessor: "getColor", + size: 4, + type: "unorm8", + transition: false + }, + instancePickable: { + accessor: "getPickable", + size: 1, + transition: false + } + }); + this.setState({ model: this._getModel() }); + } + updateState(params) { + super.updateState(params); + const { changeFlags } = params; + if (!this.state.model || changeFlags.extensionsChanged) { + this.state.model?.destroy(); + this.setState({ model: this._getModel() }); + this.getAttributeManager().invalidateAll(); + } + } + draw() { + const { drawOutline = true, outlineColor = [255, 255, 255, 255], outlineThickness = 1, thicknessUnit = 12 } = this.props; + const model = this.state.model; + if (!model) { + return; + } + model.shaderInputs.setProps({ + flowLines: { + outlineColor: outlineColor.map((x) => x / 255), + thicknessUnit: thicknessUnit * 2, + outlineThickness, + drawOutline: drawOutline ? 1 : 0, + gap: 0.5, + curviness: 1 + } + }); + model.draw(this.context.renderPass); + } + _getModel() { + const { id } = this.props; + return new Model(this.context.device, { + id, + ...this.getShaders(), + bufferLayout: this.getAttributeManager().getBufferLayouts(), + geometry: new Geometry({ + topology: "triangle-list", + attributes: { + positions: { size: 3, value: new Float32Array(POSITIONS) }, + pixelOffsets: { size: 2, value: PIXEL_OFFSETS }, + outlineOffsetCoefficients: { + size: 2, + value: OUTLINE_OFFSET_COEFFICIENTS + }, + outlineOffsetConstants: { + size: 2, + value: OUTLINE_OFFSET_CONSTANTS + }, + barycentrics: { size: 3, value: BARYCENTRICS }, + edgeMasks: { size: 3, value: EDGE_MASKS } + } + }), + isInstanced: true + }); + } + }; + FlowLinesLayer.layerName = "FlowLinesLayer"; + FlowLinesLayer.defaultProps = { + getSourcePosition: { type: "accessor", value: (d) => [0, 0] }, + getTargetPosition: { type: "accessor", value: (d) => [0, 0] }, + getColor: { type: "accessor", value: DEFAULT_COLOR3 }, + getThickness: { type: "accessor", value: (d) => d.count }, + // 0..0.5 + getPickable: { type: "accessor", value: (d) => 1 }, + drawOutline: true, + thicknessUnit: 12, + outlineThickness: 1, + outlineColor: [255, 255, 255, 255], + parameters: { + depthTest: false + } + }; + var FlowLinesLayer_default = FlowLinesLayer; + + // node_modules/@flowmap.gl/layers/dist/FlowLinesLayer/index.js + var FlowLinesLayer_default2 = FlowLinesLayer_default; + + // node_modules/@flowmap.gl/layers/dist/FlowCirclesLayer/FlowCirclesLayerFragment.glsl.js + var FlowCirclesLayerFragment_glsl_default = `#version 300 es +#define SHADER_NAME flow-circles-layer-fragment-shader +#define SOFT_OUTLINE 0.05 +#define EPS 0.05 +precision highp float; + +in vec4 vColor; +in vec2 unitPosition; +in float unitInRadius; +in float unitOutRadius; + +out vec4 fragColor; + +float when_gt(float x, float y) { + return max(sign(x - y), 0.0); +} + +void main(void) { + geometry.uv = unitPosition; + float distToCenter = length(unitPosition); + if (distToCenter > 1.0) { + discard; + } + + // See https://stackoverflow.com/questions/47285778 + vec4 ringColor = mix( + flowCircles.emptyColor, vColor, + when_gt(unitInRadius, unitOutRadius) + ); + vec4 outlineColor = mix( + mix(vColor, flowCircles.emptyColor, flowCircles.outlineEmptyMix), + vColor, + when_gt(unitInRadius, unitOutRadius) + ); + + float innerR = min(unitInRadius, unitOutRadius) * (1.0 - SOFT_OUTLINE); + + // Inner circle + float step2 = innerR - 2.0 * EPS; + float step3 = innerR - EPS; + + // Ring + float step4 = innerR; + // float step5 = 1.0 - SOFT_OUTLINE - EPS; + // float step6 = 1.0 - SOFT_OUTLINE; + float step5 = 1.0 - 5.0 * EPS; + float step6 = 1.0; + + fragColor = vColor; + fragColor = mix(fragColor, flowCircles.emptyColor, smoothstep(step2, step3, distToCenter)); + fragColor = mix(fragColor, ringColor, smoothstep(step3, step4, distToCenter)); + fragColor = mix(fragColor, outlineColor, smoothstep(step5, step6, distToCenter)); + fragColor.a = vColor.a; + fragColor.a *= smoothstep(0.0, SOFT_OUTLINE, 1.0 - distToCenter); + DECKGL_FILTER_COLOR(fragColor, geometry); +} +`; + + // node_modules/@flowmap.gl/layers/dist/FlowCirclesLayer/FlowCirclesLayerVertex.glsl.js + var FlowCirclesLayerVertex_glsl_default = `#version 300 es +#define SHADER_NAME flow-circles-layer-vertex-shader +#define radiusScale 100 + +in vec3 positions; + +in vec3 instancePositions; +in vec3 instancePositions64Low; +in float instanceInRadius; +in float instanceOutRadius; +in vec4 instanceColors; +in vec3 instancePickingColors; + +out vec4 vColor; +out vec2 unitPosition; +out float unitInRadius; +out float unitOutRadius; + +void main(void) { + geometry.worldPosition = instancePositions; + + float outerRadiusPixels = max(instanceInRadius, instanceOutRadius); + unitInRadius = instanceInRadius / outerRadiusPixels; + unitOutRadius = instanceOutRadius / outerRadiusPixels; + + // position on the containing square in [-1, 1] space + unitPosition = positions.xy; + geometry.uv = unitPosition; + geometry.pickingColor = instancePickingColors; + + // Find the center of the point and add the current vertex + vec3 offset = positions * project_pixel_size(outerRadiusPixels); + DECKGL_FILTER_SIZE(offset, geometry); + gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset, geometry.position); + DECKGL_FILTER_GL_POSITION(gl_Position, geometry); + + // Apply opacity to instance color, or return instance picking color + vColor = vec4(instanceColors.rgb, instanceColors.a * layer.opacity); + DECKGL_FILTER_COLOR(vColor, geometry); +} +`; + + // node_modules/@flowmap.gl/layers/dist/FlowCirclesLayer/FlowCirclesLayerUniforms.js + var uniformBlock7 = `layout(std140) uniform flowCirclesUniforms { + vec4 emptyColor; + float outlineEmptyMix; +} flowCircles; +`; + var flowCirclesUniforms = { + name: "flowCircles", + vs: uniformBlock7, + fs: uniformBlock7, + uniformTypes: { + emptyColor: "vec4", + outlineEmptyMix: "f32" + } + }; + + // node_modules/@flowmap.gl/layers/dist/FlowCirclesLayer/FlowCirclesLayer.js + var DEFAULT_COLOR4 = [0, 0, 0, 255]; + var DEFAULT_EMPTY_COLOR = [255, 255, 255, 255]; + var DEFAULT_OUTLINE_EMPTY_MIX = 0.4; + var FlowCirclesLayer = class extends layer_default { + // props!: Props; + constructor(props) { + super(props); + } + getShaders() { + return super.getShaders({ + vs: FlowCirclesLayerVertex_glsl_default, + fs: FlowCirclesLayerFragment_glsl_default, + modules: [project32_default, picking_default, flowCirclesUniforms] + }); + } + initializeState() { + this.getAttributeManager().addInstanced({ + instancePositions: { + size: 3, + type: "float64", + fp64: this.use64bitPositions(), + transition: true, + accessor: "getPosition" + }, + instanceInRadius: { + size: 1, + transition: true, + accessor: "getInRadius", + defaultValue: 1 + }, + instanceOutRadius: { + size: 1, + transition: true, + accessor: "getOutRadius", + defaultValue: 1 + }, + instanceColors: { + size: 4, + transition: true, + type: "unorm8", + accessor: "getColor", + defaultValue: DEFAULT_COLOR4 + } + }); + this.setState({ model: this._getModel() }); + } + updateState(params) { + super.updateState(params); + const { changeFlags } = params; + if (!this.state.model || changeFlags.extensionsChanged) { + this.state.model?.destroy(); + this.setState({ model: this._getModel() }); + this.getAttributeManager().invalidateAll(); + } + } + draw() { + const { emptyColor = DEFAULT_EMPTY_COLOR, outlineEmptyMix = DEFAULT_OUTLINE_EMPTY_MIX } = this.props; + const model = this.state.model; + if (!model) { + return; + } + model.shaderInputs.setProps({ + flowCircles: { + emptyColor: emptyColor.map((x) => x / 255), + outlineEmptyMix + } + }); + model.draw(this.context.renderPass); + } + _getModel() { + const { id } = this.props; + const positions = [-1, -1, 0, 1, -1, 0, -1, 1, 0, 1, 1, 0]; + return new Model(this.context.device, { + ...this.getShaders(), + id, + bufferLayout: this.getAttributeManager().getBufferLayouts(), + geometry: new Geometry({ + topology: "triangle-strip", + attributes: { + positions: { size: 3, value: new Float32Array(positions) } + } + }), + isInstanced: true + }); + } + }; + FlowCirclesLayer.layerName = "FlowCirclesLayer"; + FlowCirclesLayer.defaultProps = { + getColor: { type: "accessor", value: DEFAULT_COLOR4 }, + emptyColor: { type: "accessor", value: DEFAULT_EMPTY_COLOR }, + outlineEmptyMix: { type: "accessor", value: DEFAULT_OUTLINE_EMPTY_MIX }, + getPosition: { type: "accessor", value: (d) => d.position }, + getInRadius: { type: "accessor", value: 1 }, + getOutRadius: { type: "accessor", value: 1 }, + parameters: { + depthTest: false + } + }; + var FlowCirclesLayer_default = FlowCirclesLayer; + + // node_modules/@flowmap.gl/layers/dist/FlowCirclesLayer/index.js + var FlowCirclesLayer_default2 = FlowCirclesLayer_default; + + // node_modules/@deck.gl/layers/dist/icon-layer/icon-layer-uniforms.js + var uniformBlock8 = `layout(std140) uniform iconUniforms { + float sizeScale; + vec2 iconsTextureDim; + float sizeBasis; + float sizeMinPixels; + float sizeMaxPixels; + bool billboard; + highp int sizeUnits; + float alphaCutoff; +} icon; +`; + var iconUniforms = { + name: "icon", + vs: uniformBlock8, + fs: uniformBlock8, + uniformTypes: { + sizeScale: "f32", + iconsTextureDim: "vec2", + sizeBasis: "f32", + sizeMinPixels: "f32", + sizeMaxPixels: "f32", + billboard: "f32", + sizeUnits: "i32", + alphaCutoff: "f32" + } + }; + + // node_modules/@deck.gl/layers/dist/icon-layer/icon-layer-vertex.glsl.js + var icon_layer_vertex_glsl_default = `#version 300 es +#define SHADER_NAME icon-layer-vertex-shader +in vec2 positions; +in vec3 instancePositions; +in vec3 instancePositions64Low; +in float instanceSizes; +in float instanceAngles; +in vec4 instanceColors; +in vec3 instancePickingColors; +in vec4 instanceIconFrames; +in float instanceColorModes; +in vec2 instanceOffsets; +in vec2 instancePixelOffset; +out float vColorMode; +out vec4 vColor; +out vec2 vTextureCoords; +out vec2 uv; +vec2 rotate_by_angle(vec2 vertex, float angle) { +float angle_radian = angle * PI / 180.0; +float cos_angle = cos(angle_radian); +float sin_angle = sin(angle_radian); +mat2 rotationMatrix = mat2(cos_angle, -sin_angle, sin_angle, cos_angle); +return rotationMatrix * vertex; +} +void main(void) { +geometry.worldPosition = instancePositions; +geometry.uv = positions; +geometry.pickingColor = instancePickingColors; +uv = positions; +vec2 iconSize = instanceIconFrames.zw; +float sizePixels = clamp( +project_size_to_pixel(instanceSizes * icon.sizeScale, icon.sizeUnits), +icon.sizeMinPixels, icon.sizeMaxPixels +); +float iconConstraint = icon.sizeBasis == 0.0 ? iconSize.x : iconSize.y; +float instanceScale = iconConstraint == 0.0 ? 0.0 : sizePixels / iconConstraint; +vec2 pixelOffset = positions / 2.0 * iconSize + instanceOffsets; +pixelOffset = rotate_by_angle(pixelOffset, instanceAngles) * instanceScale; +pixelOffset += instancePixelOffset; +pixelOffset.y *= -1.0; +if (icon.billboard) { +gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0), geometry.position); +DECKGL_FILTER_GL_POSITION(gl_Position, geometry); +vec3 offset = vec3(pixelOffset, 0.0); +DECKGL_FILTER_SIZE(offset, geometry); +gl_Position.xy += project_pixel_size_to_clipspace(offset.xy); +} else { +vec3 offset_common = vec3(project_pixel_size(pixelOffset), 0.0); +DECKGL_FILTER_SIZE(offset_common, geometry); +gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset_common, geometry.position); +DECKGL_FILTER_GL_POSITION(gl_Position, geometry); +} +vTextureCoords = mix( +instanceIconFrames.xy, +instanceIconFrames.xy + iconSize, +(positions.xy + 1.0) / 2.0 +) / icon.iconsTextureDim; +vColor = instanceColors; +DECKGL_FILTER_COLOR(vColor, geometry); +vColorMode = instanceColorModes; +} +`; + + // node_modules/@deck.gl/layers/dist/icon-layer/icon-layer-fragment.glsl.js + var icon_layer_fragment_glsl_default = `#version 300 es +#define SHADER_NAME icon-layer-fragment-shader +precision highp float; +uniform sampler2D iconsTexture; +in float vColorMode; +in vec4 vColor; +in vec2 vTextureCoords; +in vec2 uv; +out vec4 fragColor; +void main(void) { +geometry.uv = uv; +vec4 texColor = texture(iconsTexture, vTextureCoords); +vec3 color = mix(texColor.rgb, vColor.rgb, vColorMode); +float a = texColor.a * layer.opacity * vColor.a; +if (a < icon.alphaCutoff) { +discard; +} +fragColor = vec4(color, a); +DECKGL_FILTER_COLOR(fragColor, geometry); +} +`; + + // node_modules/@deck.gl/layers/dist/icon-layer/icon-layer.wgsl.js + var shaderWGSL = ( + /* wgsl */ + `struct IconUniforms { + sizeScale: f32, + iconsTextureDim: vec2, + sizeBasis: f32, + sizeMinPixels: f32, + sizeMaxPixels: f32, + billboard: i32, + sizeUnits: i32, + alphaCutoff: f32 +}; + +@group(0) @binding(auto) var icon: IconUniforms; +@group(0) @binding(auto) var iconsTexture : texture_2d; +@group(0) @binding(auto) var iconsTextureSampler : sampler; + +fn rotate_by_angle(vertex: vec2, angle_deg: f32) -> vec2 { + let angle_radian = angle_deg * PI / 180.0; + let c = cos(angle_radian); + let s = sin(angle_radian); + let rotation = mat2x2(vec2(c, s), vec2(-s, c)); + return rotation * vertex; +} + +struct Attributes { + @location(0) positions: vec2, + + @location(1) instancePositions: vec3, + @location(2) instancePositions64Low: vec3, + @location(3) instanceSizes: f32, + @location(4) instanceAngles: f32, + @location(5) instanceColors: vec4, + @location(6) instancePickingColors: vec3, + @location(7) instanceIconFrames: vec4, + @location(8) instanceColorModes: f32, + @location(9) instanceOffsets: vec2, + @location(10) instancePixelOffset: vec2, +}; + +struct Varyings { + @builtin(position) position: vec4, + + @location(0) vColorMode: f32, + @location(1) vColor: vec4, + @location(2) vTextureCoords: vec2, + @location(3) uv: vec2, + @location(4) pickingColor: vec3, +}; + +@vertex +fn vertexMain(inp: Attributes) -> Varyings { + // write geometry fields used by filters + FS + geometry.worldPosition = inp.instancePositions; + geometry.uv = inp.positions; + geometry.pickingColor = inp.instancePickingColors; + + var outp: Varyings; + outp.uv = inp.positions; + + let iconSize = inp.instanceIconFrames.zw; + + // convert size in meters to pixels, then clamp + let sizePixels = clamp( + project_unit_size_to_pixel(inp.instanceSizes * icon.sizeScale, icon.sizeUnits), + icon.sizeMinPixels, icon.sizeMaxPixels + ); + + // scale icon height to match instanceSize + let iconConstraint = select(iconSize.y, iconSize.x, icon.sizeBasis == 0.0); + let instanceScale = select(sizePixels / iconConstraint, 0.0, iconConstraint == 0.0); + + // scale and rotate vertex in "pixel" units; then add per-instance pixel offset + var pixelOffset = inp.positions / 2.0 * iconSize + inp.instanceOffsets; + pixelOffset = rotate_by_angle(pixelOffset, inp.instanceAngles) * instanceScale; + pixelOffset = pixelOffset + inp.instancePixelOffset; + pixelOffset.y = pixelOffset.y * -1.0; + + if (icon.billboard != 0) { + var pos = project_position_to_clipspace(inp.instancePositions, inp.instancePositions64Low, vec3(0.0)); // TODO, &geometry.position); + // DECKGL_FILTER_GL_POSITION(pos, geometry); + + var offset = vec3(pixelOffset, 0.0); + // DECKGL_FILTER_SIZE(offset, geometry); + let clipOffset = project_pixel_size_to_clipspace(offset.xy); + pos = vec4(pos.x + clipOffset.x, pos.y + clipOffset.y, pos.z, pos.w); + outp.position = pos; + } else { + var offset_common = vec3(project_pixel_size_vec2(pixelOffset), 0.0); + // DECKGL_FILTER_SIZE(offset_common, geometry); + var pos = project_position_to_clipspace(inp.instancePositions, inp.instancePositions64Low, offset_common); // TODO, &geometry.position); + // DECKGL_FILTER_GL_POSITION(pos, geometry); + outp.position = pos; + } + + let uvMix = (inp.positions.xy + vec2(1.0, 1.0)) * 0.5; + outp.vTextureCoords = mix(inp.instanceIconFrames.xy, inp.instanceIconFrames.xy + iconSize, uvMix) / icon.iconsTextureDim; + + outp.vColor = inp.instanceColors; + // DECKGL_FILTER_COLOR(outp.vColor, geometry); + + outp.vColorMode = inp.instanceColorModes; + outp.pickingColor = inp.instancePickingColors; + + return outp; +} + +@fragment +fn fragmentMain(inp: Varyings) -> @location(0) vec4 { + // expose to deck.gl filter hooks + geometry.uv = inp.uv; + + let texColor = textureSample(iconsTexture, iconsTextureSampler, inp.vTextureCoords); + + // if colorMode == 0, use pixel color from the texture + // if colorMode == 1 (or picking), use texture as transparency mask + let rgb = mix(texColor.rgb, inp.vColor.rgb, inp.vColorMode); + let a = texColor.a * layer.opacity * inp.vColor.a; + + if (a < icon.alphaCutoff) { + discard; + } + + if (picking.isActive > 0.5) { + if (!picking_isColorValid(inp.pickingColor)) { + discard; + } + return vec4(inp.pickingColor, 1.0); + } + + var fragColor = deckgl_premultiplied_alpha(vec4(rgb, a)); + + if (picking.isHighlightActive > 0.5) { + let highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor); + if (picking_isColorZero(abs(inp.pickingColor - highlightedObjectColor))) { + let highLightAlpha = picking.highlightColor.a; + let blendedAlpha = highLightAlpha + fragColor.a * (1.0 - highLightAlpha); + if (blendedAlpha > 0.0) { + let highLightRatio = highLightAlpha / blendedAlpha; + fragColor = vec4( + mix(fragColor.rgb, picking.highlightColor.rgb, highLightRatio), + blendedAlpha + ); + } else { + fragColor = vec4(fragColor.rgb, 0.0); + } + } + } + + return fragColor; +} +` + ); + + // node_modules/@deck.gl/layers/dist/icon-layer/icon-manager.js + var DEFAULT_CANVAS_WIDTH = 1024; + var DEFAULT_BUFFER = 4; + var noop4 = () => { + }; + var DEFAULT_SAMPLER_PARAMETERS = { + minFilter: "linear", + mipmapFilter: "linear", + // LINEAR is the default value but explicitly set it here + magFilter: "linear", + // minimize texture boundary artifacts + addressModeU: "clamp-to-edge", + addressModeV: "clamp-to-edge" + }; + var MISSING_ICON = { + x: 0, + y: 0, + width: 0, + height: 0 + }; + function nextPowOfTwo(number3) { + return Math.pow(2, Math.ceil(Math.log2(number3))); + } + function resizeImage(ctx, imageData, maxWidth, maxHeight) { + const resizeRatio = Math.min(maxWidth / imageData.width, maxHeight / imageData.height); + const width = Math.floor(imageData.width * resizeRatio); + const height = Math.floor(imageData.height * resizeRatio); + if (resizeRatio === 1) { + return { image: imageData, width, height }; + } + ctx.canvas.height = height; + ctx.canvas.width = width; + ctx.clearRect(0, 0, width, height); + ctx.drawImage(imageData, 0, 0, imageData.width, imageData.height, 0, 0, width, height); + return { image: ctx.canvas, width, height }; + } + function getIconId(icon) { + return icon && (icon.id || icon.url); + } + function regenerateMipmaps(texture) { + const { device } = texture; + if (device.type === "webgl") { + texture.generateMipmapsWebGL(); + } else if (device.type === "webgpu") { + device.generateMipmapsWebGPU(texture); + } + } + function resizeTexture(texture, width, height, sampler) { + const { width: oldWidth, height: oldHeight, device } = texture; + const newTexture = device.createTexture({ + format: "rgba8unorm", + width, + height, + sampler, + mipLevels: device.getMipLevelCount(width, height) + }); + const commandEncoder = device.createCommandEncoder(); + commandEncoder.copyTextureToTexture({ + sourceTexture: texture, + destinationTexture: newTexture, + width: oldWidth, + height: oldHeight + }); + const commandBuffer = commandEncoder.finish(); + device.submit(commandBuffer); + regenerateMipmaps(newTexture); + texture.destroy(); + return newTexture; + } + function buildRowMapping(mapping, columns, yOffset) { + for (let i = 0; i < columns.length; i++) { + const { icon, xOffset } = columns[i]; + const id = getIconId(icon); + mapping[id] = { + ...icon, + x: xOffset, + y: yOffset + }; + } + } + function buildMapping({ icons, buffer, mapping = {}, xOffset = 0, yOffset = 0, rowHeight = 0, canvasWidth }) { + let columns = []; + for (let i = 0; i < icons.length; i++) { + const icon = icons[i]; + const id = getIconId(icon); + if (!mapping[id]) { + const { height, width } = icon; + if (xOffset + width + buffer > canvasWidth) { + buildRowMapping(mapping, columns, yOffset); + xOffset = 0; + yOffset = rowHeight + yOffset + buffer; + rowHeight = 0; + columns = []; + } + columns.push({ + icon, + xOffset + }); + xOffset = xOffset + width + buffer; + rowHeight = Math.max(rowHeight, height); + } + } + if (columns.length > 0) { + buildRowMapping(mapping, columns, yOffset); + } + return { + mapping, + rowHeight, + xOffset, + yOffset, + canvasWidth, + canvasHeight: nextPowOfTwo(rowHeight + yOffset + buffer) + }; + } + function getDiffIcons(data, getIcon, cachedIcons) { + if (!data || !getIcon) { + return null; + } + cachedIcons = cachedIcons || {}; + const icons = {}; + const { iterable, objectInfo } = createIterable(data); + for (const object of iterable) { + objectInfo.index++; + const icon = getIcon(object, objectInfo); + const id = getIconId(icon); + if (!icon) { + throw new Error("Icon is missing."); + } + if (!icon.url) { + throw new Error("Icon url is missing."); + } + if (!icons[id] && (!cachedIcons[id] || icon.url !== cachedIcons[id].url)) { + icons[id] = { ...icon, source: object, sourceIndex: objectInfo.index }; + } + } + return icons; + } + var IconManager = class { + constructor(device, { onUpdate = noop4, onError = noop4 }) { + this._loadOptions = null; + this._texture = null; + this._externalTexture = null; + this._mapping = {}; + this._samplerParameters = null; + this._pendingCount = 0; + this._autoPacking = false; + this._xOffset = 0; + this._yOffset = 0; + this._rowHeight = 0; + this._buffer = DEFAULT_BUFFER; + this._canvasWidth = DEFAULT_CANVAS_WIDTH; + this._canvasHeight = 0; + this._canvas = null; + this.device = device; + this.onUpdate = onUpdate; + this.onError = onError; + } + finalize() { + this._texture?.delete(); + } + getTexture() { + return this._texture || this._externalTexture; + } + getIconMapping(icon) { + const id = this._autoPacking ? getIconId(icon) : icon; + return this._mapping[id] || MISSING_ICON; + } + setProps({ loadOptions, autoPacking, iconAtlas, iconMapping, textureParameters }) { + if (loadOptions) { + this._loadOptions = loadOptions; + } + if (autoPacking !== void 0) { + this._autoPacking = autoPacking; + } + if (iconMapping) { + this._mapping = iconMapping; + } + if (iconAtlas) { + this._texture?.delete(); + this._texture = null; + this._externalTexture = iconAtlas; + } + if (textureParameters) { + this._samplerParameters = textureParameters; + } + } + get isLoaded() { + return this._pendingCount === 0; + } + packIcons(data, getIcon) { + if (!this._autoPacking || typeof document === "undefined") { + return; + } + const icons = Object.values(getDiffIcons(data, getIcon, this._mapping) || {}); + if (icons.length > 0) { + const { mapping, xOffset, yOffset, rowHeight, canvasHeight } = buildMapping({ + icons, + buffer: this._buffer, + canvasWidth: this._canvasWidth, + mapping: this._mapping, + rowHeight: this._rowHeight, + xOffset: this._xOffset, + yOffset: this._yOffset + }); + this._rowHeight = rowHeight; + this._mapping = mapping; + this._xOffset = xOffset; + this._yOffset = yOffset; + this._canvasHeight = canvasHeight; + if (!this._texture) { + this._texture = this.device.createTexture({ + format: "rgba8unorm", + data: null, + width: this._canvasWidth, + height: this._canvasHeight, + sampler: this._samplerParameters || DEFAULT_SAMPLER_PARAMETERS, + mipLevels: this.device.getMipLevelCount(this._canvasWidth, this._canvasHeight) + }); + } + if (this._texture.height !== this._canvasHeight) { + this._texture = resizeTexture(this._texture, this._canvasWidth, this._canvasHeight, this._samplerParameters || DEFAULT_SAMPLER_PARAMETERS); + } + this.onUpdate(true); + this._canvas = this._canvas || document.createElement("canvas"); + this._loadIcons(icons); + } + } + _loadIcons(icons) { + const ctx = this._canvas.getContext("2d", { + willReadFrequently: true + }); + for (const icon of icons) { + this._pendingCount++; + load(icon.url, this._loadOptions).then((imageData) => { + const id = getIconId(icon); + const iconDef = this._mapping[id]; + const { x: initialX, y: initialY, width: maxWidth, height: maxHeight } = iconDef; + const { image, width, height } = resizeImage(ctx, imageData, maxWidth, maxHeight); + const x = initialX + (maxWidth - width) / 2; + const y = initialY + (maxHeight - height) / 2; + this._texture?.copyExternalImage({ + image, + x, + y, + width, + height + }); + iconDef.x = x; + iconDef.y = y; + iconDef.width = width; + iconDef.height = height; + if (this._texture) { + regenerateMipmaps(this._texture); + } + this.onUpdate(width !== maxWidth || height !== maxHeight); + }).catch((error) => { + this.onError({ + url: icon.url, + source: icon.source, + sourceIndex: icon.sourceIndex, + loadOptions: this._loadOptions, + error + }); + }).finally(() => { + this._pendingCount--; + }); + } + } + }; + + // node_modules/@deck.gl/layers/dist/icon-layer/icon-layer.js + var DEFAULT_COLOR5 = [0, 0, 0, 255]; + var defaultProps3 = { + iconAtlas: { type: "image", value: null, async: true }, + iconMapping: { type: "object", value: {}, async: true }, + sizeScale: { type: "number", value: 1, min: 0 }, + billboard: true, + sizeUnits: "pixels", + sizeBasis: "height", + sizeMinPixels: { type: "number", min: 0, value: 0 }, + // min point radius in pixels + sizeMaxPixels: { type: "number", min: 0, value: Number.MAX_SAFE_INTEGER }, + // max point radius in pixels + alphaCutoff: { type: "number", value: 0.05, min: 0, max: 1 }, + getPosition: { type: "accessor", value: (x) => x.position }, + getIcon: { type: "accessor", value: (x) => x.icon }, + getColor: { type: "accessor", value: DEFAULT_COLOR5 }, + getSize: { type: "accessor", value: 1 }, + getAngle: { type: "accessor", value: 0 }, + getPixelOffset: { type: "accessor", value: [0, 0] }, + onIconError: { type: "function", value: null, optional: true }, + textureParameters: { type: "object", ignore: true, value: null } + }; + var IconLayer = class extends layer_default { + getShaders() { + return super.getShaders({ vs: icon_layer_vertex_glsl_default, fs: icon_layer_fragment_glsl_default, source: shaderWGSL, modules: [project32_default, color_default, picking_default, iconUniforms] }); + } + initializeState() { + this.state = { + iconManager: new IconManager(this.context.device, { + onUpdate: this._onUpdate.bind(this), + onError: this._onError.bind(this) + }) + }; + const attributeManager = this.getAttributeManager(); + attributeManager.addInstanced({ + instancePositions: { + size: 3, + type: "float64", + fp64: this.use64bitPositions(), + transition: true, + accessor: "getPosition" + }, + instanceSizes: { + size: 1, + transition: true, + accessor: "getSize", + defaultValue: 1 + }, + instanceIconDefs: { + size: 7, + accessor: "getIcon", + // eslint-disable-next-line @typescript-eslint/unbound-method + transform: this.getInstanceIconDef, + shaderAttributes: { + instanceOffsets: { + size: 2, + elementOffset: 0 + }, + instanceIconFrames: { + size: 4, + elementOffset: 2 + }, + instanceColorModes: { + size: 1, + elementOffset: 6 + } + } + }, + instanceColors: { + size: this.props.colorFormat.length, + type: "unorm8", + transition: true, + accessor: "getColor", + defaultValue: DEFAULT_COLOR5 + }, + instanceAngles: { + size: 1, + transition: true, + accessor: "getAngle" + }, + instancePixelOffset: { + size: 2, + transition: true, + accessor: "getPixelOffset" + } + }); + } + /* eslint-disable max-statements, complexity */ + updateState(params) { + super.updateState(params); + const { props, oldProps, changeFlags } = params; + const attributeManager = this.getAttributeManager(); + const { iconAtlas, iconMapping, data, getIcon, textureParameters } = props; + const { iconManager } = this.state; + if (typeof iconAtlas === "string") { + return; + } + const prePacked = iconAtlas || this.internalState.isAsyncPropLoading("iconAtlas"); + iconManager.setProps({ + loadOptions: props.loadOptions, + autoPacking: !prePacked, + iconAtlas, + iconMapping: prePacked ? iconMapping : null, + textureParameters + }); + if (prePacked) { + if (oldProps.iconMapping !== props.iconMapping) { + attributeManager.invalidate("getIcon"); + } + } else if (changeFlags.dataChanged || changeFlags.updateTriggersChanged && (changeFlags.updateTriggersChanged.all || changeFlags.updateTriggersChanged.getIcon)) { + iconManager.packIcons(data, getIcon); + } + if (changeFlags.extensionsChanged) { + this.state.model?.destroy(); + this.state.model = this._getModel(); + attributeManager.invalidateAll(); + } + } + /* eslint-enable max-statements, complexity */ + get isLoaded() { + return super.isLoaded && this.state.iconManager.isLoaded; + } + finalizeState(context) { + super.finalizeState(context); + this.state.iconManager.finalize(); + } + draw({ uniforms }) { + const { sizeScale, sizeBasis, sizeMinPixels, sizeMaxPixels, sizeUnits, billboard, alphaCutoff } = this.props; + const { iconManager } = this.state; + const iconsTexture = iconManager.getTexture(); + if (iconsTexture) { + const model = this.state.model; + const iconProps = { + iconsTexture, + iconsTextureDim: [iconsTexture.width, iconsTexture.height], + sizeUnits: UNIT[sizeUnits], + sizeScale, + sizeBasis: sizeBasis === "height" ? 1 : 0, + sizeMinPixels, + sizeMaxPixels, + billboard, + alphaCutoff + }; + model.shaderInputs.setProps({ icon: iconProps }); + model.draw(this.context.renderPass); + } + } + _getModel() { + const positions = [-1, -1, 1, -1, -1, 1, 1, 1]; + return new Model(this.context.device, { + ...this.getShaders(), + id: this.props.id, + bufferLayout: this.getAttributeManager().getBufferLayouts(), + geometry: new Geometry({ + topology: "triangle-strip", + attributes: { + // The size must be explicitly passed here otherwise luma.gl + // will default to assuming that positions are 3D (x,y,z) + positions: { + size: 2, + value: new Float32Array(positions) + } + } + }), + isInstanced: true + }); + } + _onUpdate(didFrameChange) { + if (didFrameChange) { + this.getAttributeManager()?.invalidate("getIcon"); + this.setNeedsUpdate(); + } else { + this.setNeedsRedraw(); + } + } + _onError(evt) { + const onIconError = this.getCurrentLayer()?.props.onIconError; + if (onIconError) { + onIconError(evt); + } else { + log_default.error(evt.error.message)(); + } + } + getInstanceIconDef(icon) { + const { x, y, width, height, mask, anchorX = width / 2, anchorY = height / 2 } = this.state.iconManager.getIconMapping(icon); + return [width / 2 - anchorX, height / 2 - anchorY, x, y, width, height, mask ? 1 : 0]; + } + }; + IconLayer.defaultProps = defaultProps3; + IconLayer.layerName = "IconLayer"; + var icon_layer_default = IconLayer; + + // node_modules/@deck.gl/layers/dist/scatterplot-layer/scatterplot-layer-uniforms.js + var glslUniformBlock = `layout(std140) uniform scatterplotUniforms { + float radiusScale; + float radiusMinPixels; + float radiusMaxPixels; + float lineWidthScale; + float lineWidthMinPixels; + float lineWidthMaxPixels; + float stroked; + float filled; + bool antialiasing; + bool billboard; + highp int radiusUnits; + highp int lineWidthUnits; +} scatterplot; +`; + var scatterplotUniforms = { + name: "scatterplot", + vs: glslUniformBlock, + fs: glslUniformBlock, + source: "", + uniformTypes: { + radiusScale: "f32", + radiusMinPixels: "f32", + radiusMaxPixels: "f32", + lineWidthScale: "f32", + lineWidthMinPixels: "f32", + lineWidthMaxPixels: "f32", + stroked: "f32", + filled: "f32", + antialiasing: "f32", + billboard: "f32", + radiusUnits: "i32", + lineWidthUnits: "i32" + } + }; + + // node_modules/@deck.gl/layers/dist/scatterplot-layer/scatterplot-layer-vertex.glsl.js + var scatterplot_layer_vertex_glsl_default = ( + /* glsl */ + `#version 300 es +#define SHADER_NAME scatterplot-layer-vertex-shader +in vec3 positions; +in vec3 instancePositions; +in vec3 instancePositions64Low; +in float instanceRadius; +in float instanceLineWidths; +in vec4 instanceFillColors; +in vec4 instanceLineColors; +in vec3 instancePickingColors; +out vec4 vFillColor; +out vec4 vLineColor; +out vec2 unitPosition; +out float innerUnitRadius; +out float outerRadiusPixels; +void main(void) { +geometry.worldPosition = instancePositions; +outerRadiusPixels = clamp( +project_size_to_pixel(scatterplot.radiusScale * instanceRadius, scatterplot.radiusUnits), +scatterplot.radiusMinPixels, scatterplot.radiusMaxPixels +); +float lineWidthPixels = clamp( +project_size_to_pixel(scatterplot.lineWidthScale * instanceLineWidths, scatterplot.lineWidthUnits), +scatterplot.lineWidthMinPixels, scatterplot.lineWidthMaxPixels +); +outerRadiusPixels += scatterplot.stroked * lineWidthPixels / 2.0; +float edgePadding = scatterplot.antialiasing ? (outerRadiusPixels + SMOOTH_EDGE_RADIUS) / outerRadiusPixels : 1.0; +unitPosition = edgePadding * positions.xy; +geometry.uv = unitPosition; +geometry.pickingColor = instancePickingColors; +innerUnitRadius = 1.0 - scatterplot.stroked * lineWidthPixels / outerRadiusPixels; +if (scatterplot.billboard) { +gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0), geometry.position); +DECKGL_FILTER_GL_POSITION(gl_Position, geometry); +vec3 offset = edgePadding * positions * outerRadiusPixels; +DECKGL_FILTER_SIZE(offset, geometry); +gl_Position.xy += project_pixel_size_to_clipspace(offset.xy); +} else { +vec3 offset = edgePadding * positions * project_pixel_size(outerRadiusPixels); +DECKGL_FILTER_SIZE(offset, geometry); +gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset, geometry.position); +DECKGL_FILTER_GL_POSITION(gl_Position, geometry); +} +vFillColor = vec4(instanceFillColors.rgb, instanceFillColors.a * layer.opacity); +DECKGL_FILTER_COLOR(vFillColor, geometry); +vLineColor = vec4(instanceLineColors.rgb, instanceLineColors.a * layer.opacity); +DECKGL_FILTER_COLOR(vLineColor, geometry); +} +` + ); + + // node_modules/@deck.gl/layers/dist/scatterplot-layer/scatterplot-layer-fragment.glsl.js + var scatterplot_layer_fragment_glsl_default = ( + /* glsl */ + `#version 300 es +#define SHADER_NAME scatterplot-layer-fragment-shader +precision highp float; +in vec4 vFillColor; +in vec4 vLineColor; +in vec2 unitPosition; +in float innerUnitRadius; +in float outerRadiusPixels; +out vec4 fragColor; +void main(void) { +geometry.uv = unitPosition; +float distToCenter = length(unitPosition) * outerRadiusPixels; +float inCircle = scatterplot.antialiasing ? +smoothedge(distToCenter, outerRadiusPixels) : +step(distToCenter, outerRadiusPixels); +if (inCircle == 0.0) { +discard; +} +if (scatterplot.stroked > 0.5) { +float isLine = scatterplot.antialiasing ? +smoothedge(innerUnitRadius * outerRadiusPixels, distToCenter) : +step(innerUnitRadius * outerRadiusPixels, distToCenter); +if (scatterplot.filled > 0.5) { +fragColor = mix(vFillColor, vLineColor, isLine); +} else { +if (isLine == 0.0) { +discard; +} +fragColor = vec4(vLineColor.rgb, vLineColor.a * isLine); +} +} else if (scatterplot.filled < 0.5) { +discard; +} else { +fragColor = vFillColor; +} +fragColor.a *= inCircle; +DECKGL_FILTER_COLOR(fragColor, geometry); +} +` + ); + + // node_modules/@deck.gl/layers/dist/scatterplot-layer/scatterplot-layer.wgsl.js + var scatterplot_layer_wgsl_default = ( + /* wgsl */ + `// Main shaders + +struct ScatterplotUniforms { + radiusScale: f32, + radiusMinPixels: f32, + radiusMaxPixels: f32, + lineWidthScale: f32, + lineWidthMinPixels: f32, + lineWidthMaxPixels: f32, + stroked: f32, + filled: i32, + antialiasing: i32, + billboard: i32, + radiusUnits: i32, + lineWidthUnits: i32, +}; + +struct ConstantAttributeUniforms { + instancePositions: vec3, + instancePositions64Low: vec3, + instanceRadius: f32, + instanceLineWidths: f32, + instanceFillColors: vec4, + instanceLineColors: vec4, + instancePickingColors: vec3, + + instancePositionsConstant: i32, + instancePositions64LowConstant: i32, + instanceRadiusConstant: i32, + instanceLineWidthsConstant: i32, + instanceFillColorsConstant: i32, + instanceLineColorsConstant: i32, + instancePickingColorsConstant: i32 +}; + +@group(0) @binding(0) var scatterplot: ScatterplotUniforms; + +struct ConstantAttributes { + instancePositions: vec3, + instancePositions64Low: vec3, + instanceRadius: f32, + instanceLineWidths: f32, + instanceFillColors: vec4, + instanceLineColors: vec4, + instancePickingColors: vec3 +}; + +const constants = ConstantAttributes( + vec3(0.0), + vec3(0.0), + 0.0, + 0.0, + vec4(0.0, 0.0, 0.0, 1.0), + vec4(0.0, 0.0, 0.0, 1.0), + vec3(0.0) +); + +struct Attributes { + @builtin(instance_index) instanceIndex : u32, + @builtin(vertex_index) vertexIndex : u32, + @location(0) positions: vec3, + @location(1) instancePositions: vec3, + @location(2) instancePositions64Low: vec3, + @location(3) instanceRadius: f32, + @location(4) instanceLineWidths: f32, + @location(5) instanceFillColors: vec4, + @location(6) instanceLineColors: vec4, + @location(7) instancePickingColors: vec3, +}; + +struct Varyings { + @builtin(position) position: vec4, + @location(0) vFillColor: vec4, + @location(1) vLineColor: vec4, + @location(2) unitPosition: vec2, + @location(3) innerUnitRadius: f32, + @location(4) outerRadiusPixels: f32, + @location(5) pickingColor: vec3, +}; + +@vertex +fn vertexMain(attributes: Attributes) -> Varyings { + var varyings: Varyings; + + // Draw an inline geometry constant array clip space triangle to verify that rendering works. + // var positions = array, 3>(vec2(0.0, 0.5), vec2(-0.5, -0.5), vec2(0.5, -0.5)); + // if (attributes.instanceIndex == 0) { + // varyings.position = vec4(positions[attributes.vertexIndex], 0.0, 1.0); + // return varyings; + // } + + geometry.worldPosition = attributes.instancePositions; + + // Multiply out radius and clamp to limits + varyings.outerRadiusPixels = clamp( + project_unit_size_to_pixel(scatterplot.radiusScale * attributes.instanceRadius, scatterplot.radiusUnits), + scatterplot.radiusMinPixels, scatterplot.radiusMaxPixels + ); + + // Multiply out line width and clamp to limits + let lineWidthPixels = clamp( + project_unit_size_to_pixel(scatterplot.lineWidthScale * attributes.instanceLineWidths, scatterplot.lineWidthUnits), + scatterplot.lineWidthMinPixels, scatterplot.lineWidthMaxPixels + ); + + // outer radius needs to offset by half stroke width + varyings.outerRadiusPixels += scatterplot.stroked * lineWidthPixels / 2.0; + // Expand geometry to accommodate edge smoothing + let edgePadding = select( + (varyings.outerRadiusPixels + SMOOTH_EDGE_RADIUS) / varyings.outerRadiusPixels, + 1.0, + scatterplot.antialiasing != 0 + ); + + // position on the containing square in [-1, 1] space + varyings.unitPosition = edgePadding * attributes.positions.xy; + geometry.uv = varyings.unitPosition; + geometry.pickingColor = attributes.instancePickingColors; + + varyings.innerUnitRadius = 1.0 - scatterplot.stroked * lineWidthPixels / varyings.outerRadiusPixels; + + if (scatterplot.billboard != 0) { + varyings.position = project_position_to_clipspace(attributes.instancePositions, attributes.instancePositions64Low, vec3(0.0)); // TODO , geometry.position); + // DECKGL_FILTER_GL_POSITION(varyings.position, geometry); + let offset = attributes.positions; // * edgePadding * varyings.outerRadiusPixels; + // DECKGL_FILTER_SIZE(offset, geometry); + let clipPixels = project_pixel_size_to_clipspace(offset.xy); + varyings.position.x = clipPixels.x; + varyings.position.y = clipPixels.y; + } else { + let offset = edgePadding * attributes.positions * project_pixel_size_float(varyings.outerRadiusPixels); + // DECKGL_FILTER_SIZE(offset, geometry); + varyings.position = project_position_to_clipspace(attributes.instancePositions, attributes.instancePositions64Low, offset); // TODO , geometry.position); + // DECKGL_FILTER_GL_POSITION(varyings.position, geometry); + } + + // Apply opacity to instance color, or return instance picking color + varyings.vFillColor = vec4(attributes.instanceFillColors.rgb, attributes.instanceFillColors.a * layer.opacity); + // DECKGL_FILTER_COLOR(varyings.vFillColor, geometry); + varyings.vLineColor = vec4(attributes.instanceLineColors.rgb, attributes.instanceLineColors.a * layer.opacity); + // DECKGL_FILTER_COLOR(varyings.vLineColor, geometry); + varyings.pickingColor = attributes.instancePickingColors; + + return varyings; +} + +@fragment +fn fragmentMain(varyings: Varyings) -> @location(0) vec4 { + // var geometry: Geometry; + // geometry.uv = unitPosition; + + let distToCenter = length(varyings.unitPosition) * varyings.outerRadiusPixels; + let inCircle = select( + smoothedge(distToCenter, varyings.outerRadiusPixels), + step(distToCenter, varyings.outerRadiusPixels), + scatterplot.antialiasing != 0 + ); + + if (inCircle == 0.0) { + discard; + } + + var fragColor: vec4; + + if (scatterplot.stroked != 0) { + let isLine = select( + smoothedge(varyings.innerUnitRadius * varyings.outerRadiusPixels, distToCenter), + step(varyings.innerUnitRadius * varyings.outerRadiusPixels, distToCenter), + scatterplot.antialiasing != 0 + ); + + if (scatterplot.filled != 0) { + fragColor = mix(varyings.vFillColor, varyings.vLineColor, isLine); + } else { + if (isLine == 0.0) { + discard; + } + fragColor = vec4(varyings.vLineColor.rgb, varyings.vLineColor.a * isLine); + } + } else if (scatterplot.filled == 0) { + discard; + } else { + fragColor = varyings.vFillColor; + } + + fragColor.a *= inCircle; + + if (picking.isActive > 0.5) { + if (!picking_isColorValid(varyings.pickingColor)) { + discard; + } + return vec4(varyings.pickingColor, 1.0); + } + + if (picking.isHighlightActive > 0.5) { + let highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor); + if (picking_isColorZero(abs(varyings.pickingColor - highlightedObjectColor))) { + let highLightAlpha = picking.highlightColor.a; + let blendedAlpha = highLightAlpha + fragColor.a * (1.0 - highLightAlpha); + if (blendedAlpha > 0.0) { + let highLightRatio = highLightAlpha / blendedAlpha; + fragColor = vec4( + mix(fragColor.rgb, picking.highlightColor.rgb, highLightRatio), + blendedAlpha + ); + } else { + fragColor = vec4(fragColor.rgb, 0.0); + } + } + } + + // Apply premultiplied alpha as required by transparent canvas + fragColor = deckgl_premultiplied_alpha(fragColor); + + return fragColor; + // return vec4(0, 0, 1, 1); +} +` + ); + + // node_modules/@deck.gl/layers/dist/scatterplot-layer/scatterplot-layer.js + var DEFAULT_COLOR6 = [0, 0, 0, 255]; + var defaultProps4 = { + radiusUnits: "meters", + radiusScale: { type: "number", min: 0, value: 1 }, + radiusMinPixels: { type: "number", min: 0, value: 0 }, + // min point radius in pixels + radiusMaxPixels: { type: "number", min: 0, value: Number.MAX_SAFE_INTEGER }, + // max point radius in pixels + lineWidthUnits: "meters", + lineWidthScale: { type: "number", min: 0, value: 1 }, + lineWidthMinPixels: { type: "number", min: 0, value: 0 }, + lineWidthMaxPixels: { type: "number", min: 0, value: Number.MAX_SAFE_INTEGER }, + stroked: false, + filled: true, + billboard: false, + antialiasing: true, + getPosition: { type: "accessor", value: (x) => x.position }, + getRadius: { type: "accessor", value: 1 }, + getFillColor: { type: "accessor", value: DEFAULT_COLOR6 }, + getLineColor: { type: "accessor", value: DEFAULT_COLOR6 }, + getLineWidth: { type: "accessor", value: 1 }, + // deprecated + strokeWidth: { deprecatedFor: "getLineWidth" }, + outline: { deprecatedFor: "stroked" }, + getColor: { deprecatedFor: ["getFillColor", "getLineColor"] } + }; + var ScatterplotLayer = class extends layer_default { + getShaders() { + return super.getShaders({ + vs: scatterplot_layer_vertex_glsl_default, + fs: scatterplot_layer_fragment_glsl_default, + source: scatterplot_layer_wgsl_default, + modules: [project32_default, color_default, picking_default, scatterplotUniforms] + }); + } + initializeState() { + this.getAttributeManager().addInstanced({ + instancePositions: { + size: 3, + type: "float64", + fp64: this.use64bitPositions(), + transition: true, + accessor: "getPosition" + }, + instanceRadius: { + size: 1, + transition: true, + accessor: "getRadius", + defaultValue: 1 + }, + instanceFillColors: { + size: this.props.colorFormat.length, + transition: true, + type: "unorm8", + accessor: "getFillColor", + defaultValue: [0, 0, 0, 255] + }, + instanceLineColors: { + size: this.props.colorFormat.length, + transition: true, + type: "unorm8", + accessor: "getLineColor", + defaultValue: [0, 0, 0, 255] + }, + instanceLineWidths: { + size: 1, + transition: true, + accessor: "getLineWidth", + defaultValue: 1 + } + }); + } + updateState(params) { + super.updateState(params); + if (params.changeFlags.extensionsChanged) { + this.state.model?.destroy(); + this.state.model = this._getModel(); + this.getAttributeManager().invalidateAll(); + } + } + draw({ uniforms }) { + const { radiusUnits, radiusScale, radiusMinPixels, radiusMaxPixels, stroked, filled, billboard, antialiasing, lineWidthUnits, lineWidthScale, lineWidthMinPixels, lineWidthMaxPixels } = this.props; + const scatterplotProps = { + stroked, + filled, + billboard, + antialiasing, + radiusUnits: UNIT[radiusUnits], + radiusScale, + radiusMinPixels, + radiusMaxPixels, + lineWidthUnits: UNIT[lineWidthUnits], + lineWidthScale, + lineWidthMinPixels, + lineWidthMaxPixels + }; + const model = this.state.model; + model.shaderInputs.setProps({ scatterplot: scatterplotProps }); + model.draw(this.context.renderPass); + } + _getModel() { + const positions = [-1, -1, 0, 1, -1, 0, -1, 1, 0, 1, 1, 0]; + return new Model(this.context.device, { + ...this.getShaders(), + id: this.props.id, + bufferLayout: this.getAttributeManager().getBufferLayouts(), + geometry: new Geometry({ + topology: "triangle-strip", + attributes: { + positions: { size: 3, value: new Float32Array(positions) } + } + }), + isInstanced: true + }); + } + }; + ScatterplotLayer.defaultProps = defaultProps4; + ScatterplotLayer.layerName = "ScatterplotLayer"; + var scatterplot_layer_default = ScatterplotLayer; + + // node_modules/@deck.gl/layers/dist/text-layer/multi-icon-layer/sdf-uniforms.js + var uniformBlock9 = `layout(std140) uniform sdfUniforms { + float gamma; + bool enabled; + float buffer; + float outlineBuffer; + vec4 outlineColor; +} sdf; +`; + var sdfUniforms = { + name: "sdf", + vs: uniformBlock9, + fs: uniformBlock9, + uniformTypes: { + gamma: "f32", + enabled: "f32", + buffer: "f32", + outlineBuffer: "f32", + outlineColor: "vec4" + } + }; + + // node_modules/@deck.gl/layers/dist/text-layer/text-uniforms.js + var CONTENT_ALIGN = { + none: 0, + start: 1, + center: 2, + end: 3 + }; + var glslUniformBlock2 = `layout(std140) uniform textUniforms { + highp vec2 cutoffPixels; + highp ivec2 align; + highp float fontSize; + bool flipY; +} text; + +#define ALIGN_MODE_START ${CONTENT_ALIGN.start} +#define ALIGN_MODE_CENTER ${CONTENT_ALIGN.center} +#define ALIGN_MODE_END ${CONTENT_ALIGN.end} +`; + var textUniforms = { + name: "text", + vs: glslUniformBlock2, + getUniforms: ({ contentCutoffPixels = [0, 0], contentAlignHorizontal = "none", contentAlignVertical = "none", fontSize, viewport }) => ({ + cutoffPixels: contentCutoffPixels, + align: [CONTENT_ALIGN[contentAlignHorizontal], CONTENT_ALIGN[contentAlignVertical]], + fontSize, + flipY: viewport?.flipY ?? false + }), + uniformTypes: { + cutoffPixels: "vec2", + align: "vec2", + fontSize: "f32", + flipY: "f32" + } + }; + + // node_modules/@deck.gl/layers/dist/text-layer/multi-icon-layer/multi-icon-layer-vertex.glsl.js + var multi_icon_layer_vertex_glsl_default = ( + /* glsl */ + `#version 300 es +#define SHADER_NAME multi-icon-layer-vertex-shader +in vec2 positions; +in vec3 instancePositions; +in vec3 instancePositions64Low; +in float instanceSizes; +in float instanceAngles; +in vec4 instanceColors; +in vec3 instancePickingColors; +in vec4 instanceIconFrames; +in float instanceColorModes; +in vec2 instanceOffsets; +in vec2 instancePixelOffset; +in vec4 instanceClipRect; +out float vColorMode; +out vec4 vColor; +out vec2 vTextureCoords; +out vec2 uv; +vec2 rotate_by_angle(vec2 vertex, float angle) { +float angle_radian = angle * PI / 180.0; +float cos_angle = cos(angle_radian); +float sin_angle = sin(angle_radian); +mat2 rotationMatrix = mat2(cos_angle, -sin_angle, sin_angle, cos_angle); +return rotationMatrix * vertex; +} +float getPixelOffsetFromAlignment(float anchor, float extent, float clipStart, float clipEnd, int mode) { +if (clipEnd < clipStart) return 0.0; +if (mode == ALIGN_MODE_START) { +return max(- (anchor + clipStart), 0.0); +} +if (mode == ALIGN_MODE_CENTER) { +float _min = max(0., anchor + clipStart); +float _max = min(extent, anchor + clipEnd); +return _min < _max ? (_min + _max) / 2.0 - anchor : 0.0; +} +if (mode == ALIGN_MODE_END) { +return min(extent - (anchor + clipEnd), 0.); +} +return 0.0; +} +void main(void) { +geometry.worldPosition = instancePositions; +geometry.uv = positions; +geometry.pickingColor = instancePickingColors; +uv = positions; +vec2 iconSize = instanceIconFrames.zw; +float sizePixels = clamp( +project_size_to_pixel(instanceSizes * icon.sizeScale, icon.sizeUnits), +icon.sizeMinPixels, icon.sizeMaxPixels +); +float instanceScale = sizePixels / text.fontSize; +vec2 pixelOffset = positions / 2.0 * iconSize + instanceOffsets; +pixelOffset = rotate_by_angle(pixelOffset, instanceAngles) * instanceScale; +pixelOffset += instancePixelOffset; +pixelOffset.y *= -1.0; +vec2 anchorPosScreen; +if (icon.billboard) { +gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0), geometry.position); +anchorPosScreen = gl_Position.xy / gl_Position.w; +DECKGL_FILTER_GL_POSITION(gl_Position, geometry); +vec3 offset = vec3(pixelOffset, 0.0); +DECKGL_FILTER_SIZE(offset, geometry); +gl_Position.xy += project_pixel_size_to_clipspace(offset.xy); +} else { +vec3 offset_common = vec3(project_pixel_size(pixelOffset), 0.0); +if (text.flipY) { +offset_common.y *= -1.; +} +DECKGL_FILTER_SIZE(offset_common, geometry); +vec4 anchorPos = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0)); +anchorPosScreen = anchorPos.xy / anchorPos.w; +gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset_common, geometry.position); +DECKGL_FILTER_GL_POSITION(gl_Position, geometry); +} +anchorPosScreen = vec2(anchorPosScreen.x + 1.0, 1.0 - anchorPosScreen.y) / 2.0 * project.viewportSize / project.devicePixelRatio; +vec2 xy = project_size_to_pixel(instanceClipRect.xy); +vec2 wh = project_size_to_pixel(instanceClipRect.zw); +if (text.flipY) { +xy.y = -xy.y - wh.y; +} +if (text.align.x > 0 || text.align.y > 0) { +vec2 viewportPixels = project.viewportSize / project.devicePixelRatio; +vec2 scrollPixels = vec2( +getPixelOffsetFromAlignment(anchorPosScreen.x, viewportPixels.x, xy.x, xy.x + wh.x, text.align.x), +-getPixelOffsetFromAlignment(anchorPosScreen.y, viewportPixels.y, -xy.y - wh.y, -xy.y, text.align.y) +); +pixelOffset += scrollPixels; +gl_Position.xy += project_pixel_size_to_clipspace(scrollPixels); +} +if (instanceClipRect.z >= 0.) { +if (pixelOffset.x < xy.x || pixelOffset.x > xy.x + wh.x) { +gl_Position = vec4(0.0); +} +else if (text.cutoffPixels.x > 0.) { +float vpWidth = project.viewportSize.x / project.devicePixelRatio; +float l = max(anchorPosScreen.x + xy.x, 0.0); +float r = min(anchorPosScreen.x + xy.x + wh.x, vpWidth); +if (r - l < text.cutoffPixels.x) { +gl_Position = vec4(0.0); +} +} +} +if (instanceClipRect.w >= 0.) { +if (pixelOffset.y < xy.y || pixelOffset.y > xy.y + wh.y) { +gl_Position = vec4(0.0); +} +else if (text.cutoffPixels.y > 0.) { +float vpHeight = project.viewportSize.y / project.devicePixelRatio; +float t = max(anchorPosScreen.y - xy.y - wh.y, 0.0); +float b = min(anchorPosScreen.y - xy.y, vpHeight); +if (b - t < text.cutoffPixels.y) { +gl_Position = vec4(0.0); +} +} +} +vTextureCoords = mix( +instanceIconFrames.xy, +instanceIconFrames.xy + iconSize, +(positions.xy + 1.0) / 2.0 +) / icon.iconsTextureDim; +vColor = instanceColors; +DECKGL_FILTER_COLOR(vColor, geometry); +vColorMode = instanceColorModes; +} +` + ); + + // node_modules/@deck.gl/layers/dist/text-layer/multi-icon-layer/multi-icon-layer-fragment.glsl.js + var multi_icon_layer_fragment_glsl_default = `#version 300 es +#define SHADER_NAME multi-icon-layer-fragment-shader +precision highp float; +uniform sampler2D iconsTexture; +in vec4 vColor; +in vec2 vTextureCoords; +in vec2 uv; +out vec4 fragColor; +void main(void) { +geometry.uv = uv; +if (!bool(picking.isActive)) { +float alpha = texture(iconsTexture, vTextureCoords).a; +vec4 color = vColor; +if (sdf.enabled) { +float distance = alpha; +alpha = smoothstep(sdf.buffer - sdf.gamma, sdf.buffer + sdf.gamma, distance); +if (sdf.outlineBuffer > 0.0) { +float inFill = alpha; +float inBorder = smoothstep(sdf.outlineBuffer - sdf.gamma, sdf.outlineBuffer + sdf.gamma, distance); +color = mix(sdf.outlineColor, vColor, inFill); +alpha = inBorder; +} +} +float a = alpha * color.a; +if (a < icon.alphaCutoff) { +discard; +} +fragColor = vec4(color.rgb, a * layer.opacity); +} +DECKGL_FILTER_COLOR(fragColor, geometry); +} +`; + + // node_modules/@deck.gl/layers/dist/text-layer/multi-icon-layer/multi-icon-layer.js + var DEFAULT_BUFFER2 = 192 / 256; + var defaultProps5 = { + getIconOffsets: { type: "accessor", value: (x) => x.offsets }, + getContentBox: { type: "accessor", value: [0, 0, -1, -1] }, + fontSize: 1, + alphaCutoff: 1e-3, + smoothing: 0.1, + outlineWidth: 0, + outlineColor: { type: "color", value: [0, 0, 0, 255] }, + contentCutoffPixels: { type: "array", value: [0, 0] }, + contentAlignHorizontal: "none", + contentAlignVertical: "none" + }; + var MultiIconLayer = class extends icon_layer_default { + getShaders() { + const shaders = super.getShaders(); + return { ...shaders, modules: [...shaders.modules, textUniforms, sdfUniforms], vs: multi_icon_layer_vertex_glsl_default, fs: multi_icon_layer_fragment_glsl_default }; + } + initializeState() { + super.initializeState(); + const attributeManager = this.getAttributeManager(); + const instanceIconDefs = attributeManager.attributes.instanceIconDefs; + instanceIconDefs.settings.update = this.calculateInstanceIconDefs; + attributeManager.addInstanced({ + instancePickingColors: { + type: "uint8", + size: 4, + accessor: (object, { index: index2, target: value }) => this.encodePickingColor(index2, value) + }, + instanceClipRect: { + size: 4, + accessor: "getContentBox", + defaultValue: [0, 0, -1, -1] + } + }); + } + updateState(params) { + super.updateState(params); + const { props, oldProps, changeFlags } = params; + const { outlineColor } = props; + if (changeFlags.updateTriggersChanged && (changeFlags.updateTriggersChanged.getIcon || changeFlags.updateTriggersChanged.getIconOffsets)) { + this.getAttributeManager().invalidate("instanceIconDefs"); + } + if (outlineColor !== oldProps.outlineColor) { + const normalizedOutlineColor = [ + outlineColor[0] / 255, + outlineColor[1] / 255, + outlineColor[2] / 255, + (outlineColor[3] ?? 255) / 255 + ]; + this.setState({ + outlineColor: normalizedOutlineColor + }); + } + if (!props.sdf && props.outlineWidth) { + log_default.warn(`${this.id}: fontSettings.sdf is required to render outline`)(); + } + } + draw(params) { + const { sdf, smoothing, fontSize, outlineWidth, contentCutoffPixels, contentAlignHorizontal, contentAlignVertical } = this.props; + const { outlineColor } = this.state; + const outlineBuffer = outlineWidth ? Math.max(smoothing, DEFAULT_BUFFER2 * (1 - outlineWidth)) : -1; + const model = this.state.model; + const sdfProps = { + buffer: DEFAULT_BUFFER2, + outlineBuffer, + gamma: smoothing, + enabled: Boolean(sdf), + outlineColor + }; + const textProps = { + contentCutoffPixels, + contentAlignHorizontal, + contentAlignVertical, + fontSize, + viewport: this.context.viewport + }; + model.shaderInputs.setProps({ sdf: sdfProps, text: textProps }); + super.draw(params); + if (sdf && outlineWidth) { + const { iconManager } = this.state; + const iconsTexture = iconManager.getTexture(); + if (iconsTexture) { + model.shaderInputs.setProps({ sdf: { ...sdfProps, outlineBuffer: DEFAULT_BUFFER2 } }); + model.draw(this.context.renderPass); + } + } + } + calculateInstanceIconDefs(attribute, { startRow, endRow }) { + const { data, getIcon, getIconOffsets } = this.props; + let i = attribute.getVertexOffset(startRow); + const output = attribute.value; + const { iterable, objectInfo } = createIterable(data, startRow, endRow); + for (const object of iterable) { + objectInfo.index++; + const text = getIcon(object, objectInfo); + const offsets = getIconOffsets(object, objectInfo); + if (text) { + let j = 0; + for (const char of Array.from(text)) { + const def = super.getInstanceIconDef(char); + def[0] = offsets[j * 2]; + def[1] += offsets[j * 2 + 1]; + def[6] = 1; + output.set(def, i); + i += attribute.size; + j++; + } + } + } + } + }; + MultiIconLayer.defaultProps = defaultProps5; + MultiIconLayer.layerName = "MultiIconLayer"; + var multi_icon_layer_default = MultiIconLayer; + + // node_modules/@mapbox/tiny-sdf/index.js + var INF = 1e20; + var alphaTable = new Float64Array(256); + for (let i = 0; i < 256; i++) { + const d = 0.5 - Math.pow(i / 255, 1 / 2.2); + alphaTable[i] = d * Math.abs(d); + } + alphaTable[255] = -INF; + var TinySDF = class { + constructor({ + fontSize = 24, + buffer = 3, + radius = 8, + cutoff = 0.25, + fontFamily = "sans-serif", + fontWeight = "normal", + fontStyle = "normal", + lang = null + } = {}) { + this.buffer = buffer; + this.radius = radius; + this.cutoff = cutoff; + this.lang = lang; + const size = this.size = fontSize + buffer * 4; + const canvas = this._createCanvas(size); + const ctx = this.ctx = canvas.getContext("2d", { willReadFrequently: true }); + ctx.font = `${fontStyle} ${fontWeight} ${fontSize}px ${fontFamily}`; + ctx.textBaseline = "alphabetic"; + ctx.textAlign = "left"; + ctx.fillStyle = "black"; + this.gridOuter = new Float64Array(size * size); + this.gridInner = new Float64Array(size * size); + this.f = new Float64Array(size); + this.z = new Float64Array(size + 1); + this.v = new Uint16Array(size); + } + _createCanvas(size) { + if (typeof OffscreenCanvas !== "undefined") { + return new OffscreenCanvas(size, size); + } + const canvas = document.createElement("canvas"); + canvas.width = canvas.height = size; + return canvas; + } + draw(char) { + const { + width: glyphAdvance, + actualBoundingBoxAscent, + actualBoundingBoxDescent, + actualBoundingBoxLeft, + actualBoundingBoxRight + } = this.ctx.measureText(char); + const glyphTop = Math.ceil(actualBoundingBoxAscent); + const glyphLeft = Math.floor(-actualBoundingBoxLeft); + const glyphWidth = Math.max(0, Math.min(this.size - this.buffer, Math.ceil(actualBoundingBoxRight) - glyphLeft)); + const glyphHeight = Math.max(0, Math.min(this.size - this.buffer, glyphTop + Math.ceil(actualBoundingBoxDescent))); + const width = glyphWidth + 2 * this.buffer; + const height = glyphHeight + 2 * this.buffer; + const len4 = Math.max(width * height, 0); + const data = new Uint8ClampedArray(len4); + const glyph = { data, width, height, glyphWidth, glyphHeight, glyphTop, glyphLeft, glyphAdvance }; + if (glyphWidth === 0 || glyphHeight === 0) return glyph; + const { ctx, buffer, gridInner, gridOuter } = this; + if (this.lang) ctx.lang = this.lang; + ctx.clearRect(buffer, buffer, glyphWidth, glyphHeight); + ctx.fillText(char, buffer - glyphLeft, buffer + glyphTop); + const imgData = ctx.getImageData(buffer, buffer, glyphWidth, glyphHeight); + gridOuter.fill(INF, 0, len4); + gridInner.fill(0, 0, len4); + let imgIdx = 3; + for (let y = 0; y < glyphHeight; y++) { + let j = (y + buffer) * width + buffer; + for (let x = 0; x < glyphWidth; x++, imgIdx += 4, j++) { + const a = imgData.data[imgIdx]; + if (a === 0) continue; + const t = alphaTable[a]; + gridOuter[j] = Math.max(0, t); + gridInner[j] = Math.max(0, -t); + } + } + edt(gridOuter, 0, 0, width, height, width, this.f, this.v, this.z); + const pad2 = Math.min(buffer, 1); + edt(gridInner, buffer - pad2, buffer - pad2, glyphWidth + 2 * pad2, glyphHeight + 2 * pad2, width, this.f, this.v, this.z); + const scale5 = 255 / this.radius; + const base = 255 * (1 - this.cutoff); + for (let i = 0; i < len4; i++) { + const d = Math.sqrt(gridOuter[i]) - Math.sqrt(gridInner[i]); + data[i] = Math.round(base - scale5 * d); + } + return glyph; + } + }; + function edt(data, x0, y0, width, height, gridSize, f, v, z) { + for (let x = x0; x < x0 + width; x++) edt1d(data, y0 * gridSize + x, gridSize, height, f, v, z); + for (let y = y0; y < y0 + height; y++) edt1d(data, y * gridSize + x0, 1, width, f, v, z); + } + function edt1d(grid, offset, stride, length4, f, v, z) { + v[0] = 0; + z[0] = -INF; + z[1] = INF; + f[0] = grid[offset]; + for (let q = 1, k = 0, s = 0; q < length4; q++) { + f[q] = grid[offset + q * stride]; + const q2 = q * q; + do { + const r = v[k]; + s = (f[q] - f[r] + q2 - r * r) / (q - r) / 2; + } while (s <= z[k] && --k > -1); + k++; + v[k] = q; + z[k] = s; + z[k + 1] = INF; + } + for (let q = 0, k = 0; q < length4; q++) { + while (z[k + 1] < q) k++; + const r = v[k]; + const qr = q - r; + grid[offset + q * stride] = f[r] + qr * qr; + } + } + + // node_modules/@deck.gl/layers/dist/text-layer/utils.js + var MISSING_CHAR_WIDTH = 32; + var SINGLE_LINE = []; + function nextPowOfTwo2(number3) { + return Math.pow(2, Math.ceil(Math.log2(number3))); + } + function buildMapping2({ characterSet, measureText: measureText2, buffer, maxCanvasWidth, mapping = {}, xOffset = 0, yOffsetMin = 0, yOffsetMax = 0 }) { + const row = 0; + let x = xOffset; + let yMin = yOffsetMin; + let yMax = yOffsetMax; + for (const char of characterSet) { + if (!mapping[char]) { + const { advance, width, ascent, descent } = measureText2(char); + const height = ascent + descent; + if (x + width + buffer * 2 > maxCanvasWidth) { + x = 0; + yMin = yMax; + } + mapping[char] = { + x: x + buffer, + y: yMin + buffer, + width, + height, + advance, + anchorX: width / 2, + anchorY: ascent + }; + x += width + buffer * 2; + yMax = Math.max(yMax, yMin + height + buffer * 2); + } + } + return { + mapping, + xOffset: x, + yOffsetMin: yMin, + yOffsetMax: yMax, + canvasHeight: nextPowOfTwo2(yMax) + }; + } + function getTextWidth(text, startIndex, endIndex, mapping) { + let width = 0; + for (let i = startIndex; i < endIndex; i++) { + const character = text[i]; + width += mapping[character]?.advance || 0; + } + return width; + } + function breakAll(text, startIndex, endIndex, maxWidth, iconMapping, target2) { + let rowStartCharIndex = startIndex; + let rowOffsetLeft = 0; + for (let i = startIndex; i < endIndex; i++) { + const textWidth = getTextWidth(text, i, i + 1, iconMapping); + if (rowOffsetLeft + textWidth > maxWidth) { + if (rowStartCharIndex < i) { + target2.push(i); + } + rowStartCharIndex = i; + rowOffsetLeft = 0; + } + rowOffsetLeft += textWidth; + } + return rowOffsetLeft; + } + function breakWord(text, startIndex, endIndex, maxWidth, iconMapping, target2) { + let rowStartCharIndex = startIndex; + let groupStartCharIndex = startIndex; + let groupEndCharIndex = startIndex; + let rowOffsetLeft = 0; + for (let i = startIndex; i < endIndex; i++) { + if (text[i] === " ") { + groupEndCharIndex = i + 1; + } else if (text[i + 1] === " " || i + 1 === endIndex) { + groupEndCharIndex = i + 1; + } + if (groupEndCharIndex > groupStartCharIndex) { + let groupWidth = getTextWidth(text, groupStartCharIndex, groupEndCharIndex, iconMapping); + if (rowOffsetLeft + groupWidth > maxWidth) { + if (rowStartCharIndex < groupStartCharIndex) { + target2.push(groupStartCharIndex); + rowStartCharIndex = groupStartCharIndex; + rowOffsetLeft = 0; + } + if (groupWidth > maxWidth) { + groupWidth = breakAll(text, groupStartCharIndex, groupEndCharIndex, maxWidth, iconMapping, target2); + rowStartCharIndex = target2[target2.length - 1]; + } + } + groupStartCharIndex = groupEndCharIndex; + rowOffsetLeft += groupWidth; + } + } + return rowOffsetLeft; + } + function autoWrapping(text, wordBreak, maxWidth, iconMapping, startIndex = 0, endIndex) { + if (endIndex === void 0) { + endIndex = text.length; + } + const result = []; + if (wordBreak === "break-all") { + breakAll(text, startIndex, endIndex, maxWidth, iconMapping, result); + } else { + breakWord(text, startIndex, endIndex, maxWidth, iconMapping, result); + } + return result; + } + function transformRow(line, startIndex, endIndex, iconMapping, leftOffsets, rowSize) { + let x = 0; + let rowHeight = 0; + for (let i = startIndex; i < endIndex; i++) { + const character = line[i]; + const frame = iconMapping[character]; + if (frame) { + rowHeight = Math.max(rowHeight, frame.height); + } + } + for (let i = startIndex; i < endIndex; i++) { + const character = line[i]; + const frame = iconMapping[character]; + if (frame) { + leftOffsets[i] = x + frame.anchorX; + x += frame.advance; + } else { + log_default.warn(`Missing character: ${character} (${character.codePointAt(0)})`)(); + leftOffsets[i] = x; + x += MISSING_CHAR_WIDTH; + } + } + rowSize[0] = x; + rowSize[1] = rowHeight; + } + function transformParagraph(paragraph, baselineOffset, lineHeight, wordBreak, maxWidth, iconMapping) { + const characters = Array.from(paragraph); + const numCharacters = characters.length; + const x = new Array(numCharacters); + const y = new Array(numCharacters); + const rowWidth = new Array(numCharacters); + const autoWrappingEnabled = (wordBreak === "break-word" || wordBreak === "break-all") && isFinite(maxWidth) && maxWidth > 0; + const size = [0, 0]; + const rowSize = [0, 0]; + let rowCount = 0; + let rowOffsetTop = baselineOffset + lineHeight / 2; + let lineStartIndex = 0; + let lineEndIndex = 0; + for (let i = 0; i <= numCharacters; i++) { + const char = characters[i]; + if (char === "\n" || i === numCharacters) { + lineEndIndex = i; + } + if (lineEndIndex > lineStartIndex) { + const rows = autoWrappingEnabled ? autoWrapping(characters, wordBreak, maxWidth, iconMapping, lineStartIndex, lineEndIndex) : SINGLE_LINE; + for (let rowIndex = 0; rowIndex <= rows.length; rowIndex++) { + const rowStart = rowIndex === 0 ? lineStartIndex : rows[rowIndex - 1]; + const rowEnd = rowIndex < rows.length ? rows[rowIndex] : lineEndIndex; + transformRow(characters, rowStart, rowEnd, iconMapping, x, rowSize); + for (let j = rowStart; j < rowEnd; j++) { + y[j] = rowOffsetTop; + rowWidth[j] = rowSize[0]; + } + rowCount++; + rowOffsetTop += lineHeight; + size[0] = Math.max(size[0], rowSize[0]); + } + lineStartIndex = lineEndIndex; + } + if (char === "\n") { + x[lineStartIndex] = 0; + y[lineStartIndex] = 0; + rowWidth[lineStartIndex] = 0; + lineStartIndex++; + } + } + size[1] = rowCount * lineHeight; + return { x, y, rowWidth, size }; + } + function getTextFromBuffer({ value, length: length4, stride, offset, startIndices, characterSet }) { + const bytesPerElement = value.BYTES_PER_ELEMENT; + const elementStride = stride ? stride / bytesPerElement : 1; + const elementOffset = offset ? offset / bytesPerElement : 0; + const characterCount = startIndices[length4] || Math.ceil((value.length - elementOffset) / elementStride); + const autoCharacterSet = characterSet && /* @__PURE__ */ new Set(); + const texts = new Array(length4); + let codes = value; + if (elementStride > 1 || elementOffset > 0) { + const ArrayType = value.constructor; + codes = new ArrayType(characterCount); + for (let i = 0; i < characterCount; i++) { + codes[i] = value[i * elementStride + elementOffset]; + } + } + for (let index2 = 0; index2 < length4; index2++) { + const startIndex = startIndices[index2]; + const endIndex = startIndices[index2 + 1] || characterCount; + const codesAtIndex = codes.subarray(startIndex, endIndex); + texts[index2] = String.fromCodePoint.apply(null, codesAtIndex); + if (autoCharacterSet) { + codesAtIndex.forEach(autoCharacterSet.add, autoCharacterSet); + } + } + if (autoCharacterSet) { + for (const charCode of autoCharacterSet) { + characterSet.add(String.fromCodePoint(charCode)); + } + } + return { texts, characterCount }; + } + + // node_modules/@deck.gl/layers/dist/text-layer/lru-cache.js + var LRUCache = class { + constructor(limit = 5) { + this._cache = {}; + this._order = []; + this.limit = limit; + } + get(key) { + const value = this._cache[key]; + if (value) { + this._deleteOrder(key); + this._appendOrder(key); + } + return value; + } + set(key, value) { + if (!this._cache[key]) { + if (Object.keys(this._cache).length === this.limit) { + this.delete(this._order[0]); + } + this._cache[key] = value; + this._appendOrder(key); + } else { + this.delete(key); + this._cache[key] = value; + this._appendOrder(key); + } + } + delete(key) { + const value = this._cache[key]; + if (value) { + delete this._cache[key]; + this._deleteOrder(key); + } + } + _deleteOrder(key) { + const index2 = this._order.indexOf(key); + if (index2 >= 0) { + this._order.splice(index2, 1); + } + } + _appendOrder(key) { + this._order.push(key); + } + }; + + // node_modules/@deck.gl/layers/dist/text-layer/font-atlas-manager.js + function getDefaultCharacterSet() { + const charSet = []; + for (let i = 32; i < 128; i++) { + charSet.push(String.fromCharCode(i)); + } + return charSet; + } + var DEFAULT_FONT_SETTINGS = { + fontFamily: "Monaco, monospace", + fontWeight: "normal", + characterSet: getDefaultCharacterSet(), + fontSize: 64, + buffer: 4, + sdf: false, + cutoff: 0.25, + radius: 12, + smoothing: 0.1 + }; + var MAX_CANVAS_WIDTH = 1024; + var DEFAULT_ASCENT = 0.9; + var DEFAULT_DESCENT = 0.3; + var CACHE_LIMIT = 3; + var cache = new LRUCache(CACHE_LIMIT); + function getNewChars(cacheKey, characterSet) { + let newCharSet; + if (typeof characterSet === "string") { + newCharSet = new Set(Array.from(characterSet)); + } else { + newCharSet = new Set(characterSet); + } + const cachedFontAtlas = cache.get(cacheKey); + if (!cachedFontAtlas) { + return newCharSet; + } + for (const char in cachedFontAtlas.mapping) { + if (newCharSet.has(char)) { + newCharSet.delete(char); + } + } + return newCharSet; + } + function populateAlphaChannel(alphaChannel, imageData) { + for (let i = 0; i < alphaChannel.length; i++) { + imageData.data[4 * i + 3] = alphaChannel[i]; + } + } + function setTextStyle(ctx, fontFamily, fontSize, fontWeight) { + ctx.font = `${fontWeight} ${fontSize}px ${fontFamily}`; + ctx.fillStyle = "#000"; + ctx.textBaseline = "alphabetic"; + ctx.textAlign = "left"; + } + function measureText(ctx, fontSize, char) { + if (char === void 0) { + const fontMetrics = ctx.measureText("A"); + if (fontMetrics.fontBoundingBoxAscent) { + return { + advance: 0, + width: 0, + ascent: Math.ceil(fontMetrics.fontBoundingBoxAscent), + descent: Math.ceil(fontMetrics.fontBoundingBoxDescent) + }; + } + return { + advance: 0, + width: 0, + ascent: fontSize * DEFAULT_ASCENT, + descent: fontSize * DEFAULT_DESCENT + }; + } + const metrics = ctx.measureText(char); + if (!metrics.actualBoundingBoxAscent) { + return { + advance: metrics.width, + width: metrics.width, + ascent: fontSize * DEFAULT_ASCENT, + descent: fontSize * DEFAULT_DESCENT + }; + } + return { + advance: metrics.width, + width: Math.ceil(metrics.actualBoundingBoxRight - metrics.actualBoundingBoxLeft), + ascent: Math.ceil(metrics.actualBoundingBoxAscent), + descent: Math.ceil(metrics.actualBoundingBoxDescent) + }; + } + function setFontAtlasCacheLimit(limit) { + log_default.assert(Number.isFinite(limit) && limit >= CACHE_LIMIT, "Invalid cache limit"); + cache = new LRUCache(limit); + } + var FontAtlasManager = class { + constructor() { + this.props = { ...DEFAULT_FONT_SETTINGS }; + } + get atlas() { + return this._atlas; + } + // TODO - cut during v9 porting as types reveal this is not correct + // get texture(): Texture | undefined { + // return this._atlas; + // } + get mapping() { + return this._atlas && this._atlas.mapping; + } + setProps(props = {}) { + Object.assign(this.props, props); + if (props._getFontRenderer) { + this._getFontRenderer = props._getFontRenderer; + } + this._key = this._getKey(); + const charSet = getNewChars(this._key, this.props.characterSet); + const cachedFontAtlas = cache.get(this._key); + if (cachedFontAtlas && charSet.size === 0) { + if (this._atlas !== cachedFontAtlas) { + this._atlas = cachedFontAtlas; + } + return; + } + const fontAtlas = this._generateFontAtlas(charSet, cachedFontAtlas); + this._atlas = fontAtlas; + cache.set(this._key, fontAtlas); + } + // eslint-disable-next-line max-statements + _generateFontAtlas(characterSet, cachedFontAtlas) { + const { fontFamily, fontWeight, fontSize, buffer, sdf, radius, cutoff } = this.props; + let canvas = cachedFontAtlas && cachedFontAtlas.data; + if (!canvas) { + canvas = document.createElement("canvas"); + canvas.width = MAX_CANVAS_WIDTH; + } + const ctx = canvas.getContext("2d", { willReadFrequently: true }); + setTextStyle(ctx, fontFamily, fontSize, fontWeight); + const defaultMeasure = (char) => measureText(ctx, fontSize, char); + let renderer; + if (this._getFontRenderer) { + renderer = this._getFontRenderer(this.props); + } else if (sdf) { + renderer = { + measure: defaultMeasure, + draw: getSdfFontRenderer(this.props) + }; + } + const { mapping, canvasHeight, xOffset, yOffsetMin, yOffsetMax } = buildMapping2({ + measureText: (char) => renderer ? renderer.measure(char) : defaultMeasure(char), + buffer, + characterSet, + maxCanvasWidth: MAX_CANVAS_WIDTH, + ...cachedFontAtlas && { + mapping: cachedFontAtlas.mapping, + xOffset: cachedFontAtlas.xOffset, + yOffsetMin: cachedFontAtlas.yOffsetMin, + yOffsetMax: cachedFontAtlas.yOffsetMax + } + }); + if (canvas.height !== canvasHeight) { + const imageData = canvas.height > 0 ? ctx.getImageData(0, 0, canvas.width, canvas.height) : null; + canvas.height = canvasHeight; + if (imageData) { + ctx.putImageData(imageData, 0, 0); + } + } + setTextStyle(ctx, fontFamily, fontSize, fontWeight); + if (renderer) { + for (const char of characterSet) { + const frame = mapping[char]; + const { data, left = 0, top = 0 } = renderer.draw(char); + const x = frame.x - left; + const y = frame.y - top; + const x0 = Math.max(0, Math.round(x)); + const y0 = Math.max(0, Math.round(y)); + const w = Math.min(data.width, canvas.width - x0); + const h = Math.min(data.height, canvas.height - y0); + ctx.putImageData(data, x0, y0, 0, 0, w, h); + frame.x += x0 - x; + frame.y += y0 - y; + } + } else { + for (const char of characterSet) { + const frame = mapping[char]; + ctx.fillText(char, frame.x, frame.y + frame.anchorY); + } + } + const fontMetrics = renderer ? renderer.measure() : defaultMeasure(); + return { + baselineOffset: (fontMetrics.ascent - fontMetrics.descent) / 2, + xOffset, + yOffsetMin, + yOffsetMax, + mapping, + data: canvas, + width: canvas.width, + height: canvas.height + }; + } + _getKey() { + const { fontFamily, fontWeight, fontSize, buffer, sdf, radius, cutoff } = this.props; + if (sdf) { + return `${fontFamily} ${fontWeight} ${fontSize} ${buffer} ${radius} ${cutoff}`; + } + return `${fontFamily} ${fontWeight} ${fontSize} ${buffer}`; + } + }; + function getSdfFontRenderer({ fontSize, buffer, radius, cutoff, fontFamily, fontWeight }) { + const tinySDF = new TinySDF({ + fontSize, + buffer, + radius, + cutoff, + fontFamily, + fontWeight: `${fontWeight}` + }); + return (char) => { + const { data, width, height } = tinySDF.draw(char); + const imageData = new ImageData(width, height); + populateAlphaChannel(data, imageData); + return { data: imageData, left: buffer, top: buffer }; + }; + } + + // node_modules/@deck.gl/layers/dist/text-layer/text-background-layer/text-background-layer-uniforms.js + var uniformBlock10 = `layout(std140) uniform textBackgroundUniforms { + bool billboard; + float sizeScale; + float sizeMinPixels; + float sizeMaxPixels; + vec4 borderRadius; + vec4 padding; + highp int sizeUnits; + bool stroked; +} textBackground; +`; + var textBackgroundUniforms = { + name: "textBackground", + vs: uniformBlock10, + fs: uniformBlock10, + uniformTypes: { + billboard: "f32", + sizeScale: "f32", + sizeMinPixels: "f32", + sizeMaxPixels: "f32", + borderRadius: "vec4", + padding: "vec4", + sizeUnits: "i32", + stroked: "f32" + } + }; + + // node_modules/@deck.gl/layers/dist/text-layer/text-background-layer/text-background-layer-vertex.glsl.js + var text_background_layer_vertex_glsl_default = ( + /* glsl */ + `#version 300 es +#define SHADER_NAME text-background-layer-vertex-shader +in vec2 positions; +in vec3 instancePositions; +in vec3 instancePositions64Low; +in vec4 instanceRects; +in vec4 instanceClipRect; +in float instanceSizes; +in float instanceAngles; +in vec2 instancePixelOffsets; +in float instanceLineWidths; +in vec4 instanceFillColors; +in vec4 instanceLineColors; +in vec3 instancePickingColors; +out vec4 vFillColor; +out vec4 vLineColor; +out float vLineWidth; +out vec2 uv; +out vec2 dimensions; +vec2 rotate_by_angle(vec2 vertex, float angle) { +float angle_radian = radians(angle); +float cos_angle = cos(angle_radian); +float sin_angle = sin(angle_radian); +mat2 rotationMatrix = mat2(cos_angle, -sin_angle, sin_angle, cos_angle); +return rotationMatrix * vertex; +} +void main(void) { +geometry.worldPosition = instancePositions; +geometry.uv = positions; +geometry.pickingColor = instancePickingColors; +uv = positions; +vLineWidth = instanceLineWidths; +float sizePixels = clamp( +project_size_to_pixel(instanceSizes * textBackground.sizeScale, textBackground.sizeUnits), +textBackground.sizeMinPixels, textBackground.sizeMaxPixels +); +float instanceScale = sizePixels / text.fontSize; +dimensions = instanceRects.zw * instanceScale + textBackground.padding.xy + textBackground.padding.zw; +vec2 pixelOffset = (positions * instanceRects.zw + instanceRects.xy) * instanceScale + mix(-textBackground.padding.xy, textBackground.padding.zw, positions); +pixelOffset = rotate_by_angle(pixelOffset, instanceAngles); +pixelOffset += instancePixelOffsets; +pixelOffset.y *= -1.0; +vec2 xy = project_size_to_pixel(instanceClipRect.xy); +vec2 wh = project_size_to_pixel(instanceClipRect.zw); +if (text.flipY) { +xy.y = -xy.y - wh.y; +} +if (instanceClipRect.z >= 0.0) { +dimensions.x = wh.x; +pixelOffset.x = xy.x + uv.x * wh.x + mix(-textBackground.padding.x, textBackground.padding.z, uv.x); +} +if (instanceClipRect.w >= 0.0) { +dimensions.y = wh.y; +pixelOffset.y = xy.y + uv.y * wh.y + mix(-textBackground.padding.y, textBackground.padding.w, uv.y); +} +if (textBackground.billboard) { +gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0), geometry.position); +DECKGL_FILTER_GL_POSITION(gl_Position, geometry); +vec3 offset = vec3(pixelOffset, 0.0); +DECKGL_FILTER_SIZE(offset, geometry); +gl_Position.xy += project_pixel_size_to_clipspace(offset.xy); +} else { +vec3 offset_common = vec3(project_pixel_size(pixelOffset), 0.0); +if (text.flipY) { +offset_common.y *= -1.; +} +DECKGL_FILTER_SIZE(offset_common, geometry); +gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset_common, geometry.position); +DECKGL_FILTER_GL_POSITION(gl_Position, geometry); +} +vFillColor = vec4(instanceFillColors.rgb, instanceFillColors.a * layer.opacity); +DECKGL_FILTER_COLOR(vFillColor, geometry); +vLineColor = vec4(instanceLineColors.rgb, instanceLineColors.a * layer.opacity); +DECKGL_FILTER_COLOR(vLineColor, geometry); +} +` + ); + + // node_modules/@deck.gl/layers/dist/text-layer/text-background-layer/text-background-layer-fragment.glsl.js + var text_background_layer_fragment_glsl_default = `#version 300 es +#define SHADER_NAME text-background-layer-fragment-shader +precision highp float; +in vec4 vFillColor; +in vec4 vLineColor; +in float vLineWidth; +in vec2 uv; +in vec2 dimensions; +out vec4 fragColor; +float round_rect(vec2 p, vec2 size, vec4 radii) { +vec2 pixelPositionCB = (p - 0.5) * size; +vec2 sizeCB = size * 0.5; +float maxBorderRadius = min(size.x, size.y) * 0.5; +vec4 borderRadius = vec4(min(radii, maxBorderRadius)); +borderRadius.xy = +(pixelPositionCB.x > 0.0) ? borderRadius.xy : borderRadius.zw; +borderRadius.x = (pixelPositionCB.y > 0.0) ? borderRadius.x : borderRadius.y; +vec2 q = abs(pixelPositionCB) - sizeCB + borderRadius.x; +return -(min(max(q.x, q.y), 0.0) + length(max(q, 0.0)) - borderRadius.x); +} +float rect(vec2 p, vec2 size) { +vec2 pixelPosition = p * size; +return min(min(pixelPosition.x, size.x - pixelPosition.x), +min(pixelPosition.y, size.y - pixelPosition.y)); +} +vec4 get_stroked_fragColor(float dist) { +float isBorder = smoothedge(dist, vLineWidth); +return mix(vFillColor, vLineColor, isBorder); +} +void main(void) { +geometry.uv = uv; +if (textBackground.borderRadius != vec4(0.0)) { +float distToEdge = round_rect(uv, dimensions, textBackground.borderRadius); +float shapeAlpha = smoothedge(-distToEdge, 0.0); +if (shapeAlpha == 0.0) { +discard; +} +if (textBackground.stroked) { +fragColor = get_stroked_fragColor(distToEdge); +} else { +fragColor = vFillColor; +} +fragColor.a *= shapeAlpha; +} else { +if (textBackground.stroked) { +float distToEdge = rect(uv, dimensions); +fragColor = get_stroked_fragColor(distToEdge); +} else { +fragColor = vFillColor; +} +} +DECKGL_FILTER_COLOR(fragColor, geometry); +} +`; + + // node_modules/@deck.gl/layers/dist/text-layer/text-background-layer/text-background-layer.js + var defaultProps6 = { + billboard: true, + sizeScale: 1, + sizeUnits: "pixels", + sizeMinPixels: 0, + sizeMaxPixels: Number.MAX_SAFE_INTEGER, + fontSize: 1, + borderRadius: { type: "object", value: 0 }, + padding: { type: "array", value: [0, 0, 0, 0] }, + getPosition: { type: "accessor", value: (x) => x.position }, + getSize: { type: "accessor", value: 1 }, + getAngle: { type: "accessor", value: 0 }, + getPixelOffset: { type: "accessor", value: [0, 0] }, + getBoundingRect: { type: "accessor", value: [0, 0, 0, 0] }, + getClipRect: { type: "accessor", value: [0, 0, -1, -1] }, + getFillColor: { type: "accessor", value: [0, 0, 0, 255] }, + getLineColor: { type: "accessor", value: [0, 0, 0, 255] }, + getLineWidth: { type: "accessor", value: 1 } + }; + var TextBackgroundLayer = class extends layer_default { + getShaders() { + return super.getShaders({ + vs: text_background_layer_vertex_glsl_default, + fs: text_background_layer_fragment_glsl_default, + modules: [project32_default, picking_default, textBackgroundUniforms, textUniforms] + }); + } + initializeState() { + this.getAttributeManager().addInstanced({ + instancePositions: { + size: 3, + type: "float64", + fp64: this.use64bitPositions(), + transition: true, + accessor: "getPosition" + }, + instanceSizes: { + size: 1, + transition: true, + accessor: "getSize", + defaultValue: 1 + }, + instanceAngles: { + size: 1, + transition: true, + accessor: "getAngle" + }, + instanceRects: { + size: 4, + accessor: "getBoundingRect" + }, + instanceClipRect: { + size: 4, + accessor: "getClipRect", + defaultValue: [0, 0, -1, -1] + }, + instancePixelOffsets: { + size: 2, + transition: true, + accessor: "getPixelOffset" + }, + instanceFillColors: { + size: 4, + transition: true, + type: "unorm8", + accessor: "getFillColor", + defaultValue: [0, 0, 0, 255] + }, + instanceLineColors: { + size: 4, + transition: true, + type: "unorm8", + accessor: "getLineColor", + defaultValue: [0, 0, 0, 255] + }, + instanceLineWidths: { + size: 1, + transition: true, + accessor: "getLineWidth", + defaultValue: 1 + } + }); + } + updateState(params) { + super.updateState(params); + const { changeFlags } = params; + if (changeFlags.extensionsChanged) { + this.state.model?.destroy(); + this.state.model = this._getModel(); + this.getAttributeManager().invalidateAll(); + } + } + draw({ uniforms }) { + const { billboard, sizeScale, sizeUnits, sizeMinPixels, sizeMaxPixels, getLineWidth, fontSize } = this.props; + let { padding, borderRadius } = this.props; + if (padding.length < 4) { + padding = [padding[0], padding[1], padding[0], padding[1]]; + } + if (!Array.isArray(borderRadius)) { + borderRadius = [ + borderRadius, + borderRadius, + borderRadius, + borderRadius + ]; + } + const model = this.state.model; + const textBackgroundProps = { + billboard, + stroked: Boolean(getLineWidth), + borderRadius, + padding, + sizeUnits: UNIT[sizeUnits], + sizeScale, + sizeMinPixels, + sizeMaxPixels + }; + const textProps = { + fontSize, + viewport: this.context.viewport + }; + model.shaderInputs.setProps({ textBackground: textBackgroundProps, text: textProps }); + model.draw(this.context.renderPass); + } + _getModel() { + const positions = [0, 0, 1, 0, 0, 1, 1, 1]; + return new Model(this.context.device, { + ...this.getShaders(), + id: this.props.id, + bufferLayout: this.getAttributeManager().getBufferLayouts(), + geometry: new Geometry({ + topology: "triangle-strip", + vertexCount: 4, + attributes: { + positions: { size: 2, value: new Float32Array(positions) } + } + }), + isInstanced: true + }); + } + }; + TextBackgroundLayer.defaultProps = defaultProps6; + TextBackgroundLayer.layerName = "TextBackgroundLayer"; + var text_background_layer_default = TextBackgroundLayer; + + // node_modules/@deck.gl/layers/dist/text-layer/text-layer.js + var TEXT_ANCHOR = { + start: 1, + middle: 0, + end: -1 + }; + var ALIGNMENT_BASELINE = { + top: 1, + center: 0, + bottom: -1 + }; + var DEFAULT_COLOR7 = [0, 0, 0, 255]; + var DEFAULT_LINE_HEIGHT = 1; + var defaultProps7 = { + billboard: true, + sizeScale: 1, + sizeUnits: "pixels", + sizeMinPixels: 0, + sizeMaxPixels: Number.MAX_SAFE_INTEGER, + background: false, + getBackgroundColor: { type: "accessor", value: [255, 255, 255, 255] }, + getBorderColor: { type: "accessor", value: DEFAULT_COLOR7 }, + getBorderWidth: { type: "accessor", value: 0 }, + backgroundBorderRadius: { type: "object", value: 0 }, + backgroundPadding: { type: "array", value: [0, 0, 0, 0] }, + characterSet: { type: "object", value: DEFAULT_FONT_SETTINGS.characterSet }, + fontFamily: DEFAULT_FONT_SETTINGS.fontFamily, + fontWeight: DEFAULT_FONT_SETTINGS.fontWeight, + lineHeight: DEFAULT_LINE_HEIGHT, + outlineWidth: { type: "number", value: 0, min: 0 }, + outlineColor: { type: "color", value: DEFAULT_COLOR7 }, + fontSettings: { type: "object", value: {}, compare: 1 }, + // auto wrapping options + wordBreak: "break-word", + maxWidth: { type: "number", value: -1 }, + contentCutoffPixels: { type: "array", value: [0, 0] }, + contentAlignHorizontal: "none", + contentAlignVertical: "none", + getText: { type: "accessor", value: (x) => x.text }, + getPosition: { type: "accessor", value: (x) => x.position }, + getColor: { type: "accessor", value: DEFAULT_COLOR7 }, + getSize: { type: "accessor", value: 32 }, + getAngle: { type: "accessor", value: 0 }, + getTextAnchor: { type: "accessor", value: "middle" }, + getAlignmentBaseline: { type: "accessor", value: "center" }, + getPixelOffset: { type: "accessor", value: [0, 0] }, + getContentBox: { type: "accessor", value: [0, 0, -1, -1] }, + // deprecated + backgroundColor: { deprecatedFor: ["background", "getBackgroundColor"] } + }; + var TextLayer = class extends composite_layer_default { + constructor() { + super(...arguments); + this.getBoundingRect = (object, objectInfo) => { + const { size: [width, height] } = this.transformParagraph(object, objectInfo); + const { getTextAnchor, getAlignmentBaseline } = this.props; + const anchorX = TEXT_ANCHOR[typeof getTextAnchor === "function" ? getTextAnchor(object, objectInfo) : getTextAnchor]; + const anchorY = ALIGNMENT_BASELINE[typeof getAlignmentBaseline === "function" ? getAlignmentBaseline(object, objectInfo) : getAlignmentBaseline]; + return [(anchorX - 1) * width / 2, (anchorY - 1) * height / 2, width, height]; + }; + this.getIconOffsets = (object, objectInfo) => { + const { getTextAnchor, getAlignmentBaseline } = this.props; + const { x, y, rowWidth, size: [, height] } = this.transformParagraph(object, objectInfo); + const anchorX = TEXT_ANCHOR[typeof getTextAnchor === "function" ? getTextAnchor(object, objectInfo) : getTextAnchor]; + const anchorY = ALIGNMENT_BASELINE[typeof getAlignmentBaseline === "function" ? getAlignmentBaseline(object, objectInfo) : getAlignmentBaseline]; + const numCharacters = x.length; + const offsets = new Array(numCharacters * 2); + let index2 = 0; + for (let i = 0; i < numCharacters; i++) { + offsets[index2++] = (anchorX - 1) * rowWidth[i] / 2 + x[i]; + offsets[index2++] = (anchorY - 1) * height / 2 + y[i]; + } + return offsets; + }; + } + initializeState() { + this.state = { + styleVersion: 0, + fontAtlasManager: new FontAtlasManager() + }; + if (this.props.maxWidth > 0) { + log_default.once(1, "v8.9 breaking change: TextLayer maxWidth is now relative to text size")(); + } + } + // eslint-disable-next-line complexity + updateState(params) { + const { props, oldProps, changeFlags } = params; + const textChanged = changeFlags.dataChanged || changeFlags.updateTriggersChanged && (changeFlags.updateTriggersChanged.all || changeFlags.updateTriggersChanged.getText); + if (textChanged) { + this._updateText(); + } + const fontChanged = this._updateFontAtlas(); + const styleChanged = fontChanged || props.lineHeight !== oldProps.lineHeight || props.wordBreak !== oldProps.wordBreak || props.maxWidth !== oldProps.maxWidth; + if (styleChanged) { + this.setState({ + styleVersion: this.state.styleVersion + 1 + }); + } + } + getPickingInfo({ info }) { + info.object = info.index >= 0 ? this.props.data[info.index] : null; + return info; + } + /** Returns true if font has changed */ + _updateFontAtlas() { + const { fontSettings, fontFamily, fontWeight, _getFontRenderer } = this.props; + const { fontAtlasManager, characterSet } = this.state; + const fontProps = { + ...fontSettings, + characterSet, + fontFamily, + fontWeight, + _getFontRenderer + }; + if (!fontAtlasManager.mapping) { + fontAtlasManager.setProps(fontProps); + return true; + } + for (const key in fontProps) { + if (fontProps[key] !== fontAtlasManager.props[key]) { + fontAtlasManager.setProps(fontProps); + return true; + } + } + return false; + } + // Text strings are variable width objects + // Count characters and start offsets + _updateText() { + const { data, characterSet } = this.props; + const textBuffer = data.attributes?.getText; + let { getText } = this.props; + let startIndices = data.startIndices; + let numInstances; + const autoCharacterSet = characterSet === "auto" && /* @__PURE__ */ new Set(); + if (textBuffer && startIndices) { + const { texts, characterCount } = getTextFromBuffer({ + ...ArrayBuffer.isView(textBuffer) ? { value: textBuffer } : textBuffer, + // @ts-ignore if data.attribute is defined then length is expected + length: data.length, + startIndices, + characterSet: autoCharacterSet + }); + numInstances = characterCount; + getText = (_, { index: index2 }) => texts[index2]; + } else { + const { iterable, objectInfo } = createIterable(data); + startIndices = [0]; + numInstances = 0; + for (const object of iterable) { + objectInfo.index++; + const text = Array.from(getText(object, objectInfo) || ""); + if (autoCharacterSet) { + text.forEach(autoCharacterSet.add, autoCharacterSet); + } + numInstances += text.length; + startIndices.push(numInstances); + } + } + this.setState({ + getText, + startIndices, + numInstances, + characterSet: autoCharacterSet || characterSet + }); + } + /** There are two size systems in this layer: + + + Pixel size: user-specified text size, via getSize, sizeScale, sizeUnits etc. + The layer roughly matches the output of the layer to CSS pixels, e.g. getSize: 12, sizeScale: 2 + in layer props is roughly equivalent to font-size: 24px in CSS. + + Texture size: internally, character positions in a text blob are calculated using the sizes of iconMapping, + which depends on how large each character is drawn into the font atlas. This is controlled by + fontSettings.fontSize (default 64) and most users do not set it manually. + These numbers are intended to be used in the vertex shader and never to be exposed to the end user. + + All surfaces exposed to the user should either use the pixel size or a multiplier relative to the pixel size. */ + /** Calculate the size and position of each character in a text string. + * Values are in texture size */ + transformParagraph(object, objectInfo) { + const { fontAtlasManager } = this.state; + const iconMapping = fontAtlasManager.mapping; + const { baselineOffset } = fontAtlasManager.atlas; + const { fontSize } = fontAtlasManager.props; + const getText = this.state.getText; + const { wordBreak, lineHeight, maxWidth } = this.props; + const paragraph = getText(object, objectInfo) || ""; + return transformParagraph(paragraph, baselineOffset, lineHeight * fontSize, wordBreak, maxWidth * fontSize, iconMapping); + } + renderLayers() { + const { startIndices, numInstances, getText, fontAtlasManager: { atlas, mapping }, styleVersion } = this.state; + const { data, _dataDiff, getPosition: getPosition2, getColor: getColor2, getSize, getAngle, getPixelOffset, getBackgroundColor, getBorderColor, getBorderWidth, getContentBox, backgroundBorderRadius, backgroundPadding, background, billboard, fontSettings, outlineWidth, outlineColor, sizeScale, sizeUnits, sizeMinPixels, sizeMaxPixels, contentCutoffPixels, contentAlignHorizontal, contentAlignVertical, transitions, updateTriggers } = this.props; + const CharactersLayerClass = this.getSubLayerClass("characters", multi_icon_layer_default); + const BackgroundLayerClass = this.getSubLayerClass("background", text_background_layer_default); + const { fontSize } = this.state.fontAtlasManager.props; + return [ + background && new BackgroundLayerClass({ + // background props + getFillColor: getBackgroundColor, + getLineColor: getBorderColor, + getLineWidth: getBorderWidth, + borderRadius: backgroundBorderRadius, + padding: backgroundPadding, + // props shared with characters layer + getPosition: getPosition2, + getSize, + getAngle, + getPixelOffset, + getClipRect: getContentBox, + billboard, + sizeScale, + sizeUnits, + sizeMinPixels, + sizeMaxPixels, + fontSize, + transitions: transitions && { + getPosition: transitions.getPosition, + getAngle: transitions.getAngle, + getSize: transitions.getSize, + getFillColor: transitions.getBackgroundColor, + getLineColor: transitions.getBorderColor, + getLineWidth: transitions.getBorderWidth, + getPixelOffset: transitions.getPixelOffset + } + }, this.getSubLayerProps({ + id: "background", + updateTriggers: { + getPosition: updateTriggers.getPosition, + getAngle: updateTriggers.getAngle, + getSize: updateTriggers.getSize, + getFillColor: updateTriggers.getBackgroundColor, + getLineColor: updateTriggers.getBorderColor, + getLineWidth: updateTriggers.getBorderWidth, + getPixelOffset: updateTriggers.getPixelOffset, + getBoundingRect: { + getText: updateTriggers.getText, + getTextAnchor: updateTriggers.getTextAnchor, + getAlignmentBaseline: updateTriggers.getAlignmentBaseline, + styleVersion + } + } + }), { + data: ( + // @ts-ignore (2339) attribute is not defined on all data types + data.attributes && data.attributes.background ? ( + // @ts-ignore (2339) attribute is not defined on all data types + { length: data.length, attributes: data.attributes.background } + ) : data + ), + _dataDiff, + // Maintain the same background behavior as <=8.3. Remove in v9? + autoHighlight: false, + getBoundingRect: this.getBoundingRect + }), + new CharactersLayerClass({ + sdf: fontSettings.sdf, + smoothing: Number.isFinite(fontSettings.smoothing) ? fontSettings.smoothing : DEFAULT_FONT_SETTINGS.smoothing, + outlineWidth: outlineWidth / (fontSettings.radius || DEFAULT_FONT_SETTINGS.radius), + outlineColor, + iconAtlas: atlas, + iconMapping: mapping, + getPosition: getPosition2, + getColor: getColor2, + getSize, + getAngle, + getPixelOffset, + getContentBox, + billboard, + sizeScale, + sizeUnits, + sizeMinPixels, + sizeMaxPixels, + fontSize, + contentCutoffPixels, + contentAlignHorizontal, + contentAlignVertical, + transitions: transitions && { + getPosition: transitions.getPosition, + getAngle: transitions.getAngle, + getColor: transitions.getColor, + getSize: transitions.getSize, + getPixelOffset: transitions.getPixelOffset, + getContentBox: transitions.getContentBox + } + }, this.getSubLayerProps({ + id: "characters", + updateTriggers: { + all: updateTriggers.getText, + getPosition: updateTriggers.getPosition, + getAngle: updateTriggers.getAngle, + getColor: updateTriggers.getColor, + getSize: updateTriggers.getSize, + getPixelOffset: updateTriggers.getPixelOffset, + getContentBox: updateTriggers.getContentBox, + getIconOffsets: { + getTextAnchor: updateTriggers.getTextAnchor, + getAlignmentBaseline: updateTriggers.getAlignmentBaseline, + styleVersion + } + } + }), { + data, + _dataDiff, + startIndices, + numInstances, + getIconOffsets: this.getIconOffsets, + getIcon: getText + }) + ]; + } + static set fontAtlasCacheLimit(limit) { + setFontAtlasCacheLimit(limit); + } + }; + TextLayer.defaultProps = defaultProps7; + TextLayer.layerName = "TextLayer"; + var text_layer_default = TextLayer; + + // node_modules/@flowmap.gl/data/dist/types.js + function isCluster(c2) { + const { children } = c2; + return children && children.length > 0; + } + function isLocationClusterNode(l) { + const { zoom } = l; + return zoom !== void 0; + } + function isAggregateFlow(flow) { + return flow && // flow.origin !== undefined && + // flow.dest !== undefined && + // flow.count !== undefined && + (flow.aggregate ? true : false); + } + var LocationFilterMode; + (function(LocationFilterMode2) { + LocationFilterMode2["ALL"] = "ALL"; + LocationFilterMode2["INCOMING"] = "INCOMING"; + LocationFilterMode2["OUTGOING"] = "OUTGOING"; + LocationFilterMode2["BETWEEN"] = "BETWEEN"; + })(LocationFilterMode || (LocationFilterMode = {})); + + // node_modules/d3-scale-chromatic/src/colors.js + function colors_default(specifier) { + var n = specifier.length / 6 | 0, colors = new Array(n), i = 0; + while (i < n) colors[i] = "#" + specifier.slice(i * 6, ++i * 6); + return colors; + } + + // node_modules/d3-color/src/define.js + function define_default(constructor, factory, prototype) { + constructor.prototype = factory.prototype = prototype; + prototype.constructor = constructor; + } + function extend(parent, definition) { + var prototype = Object.create(parent.prototype); + for (var key in definition) prototype[key] = definition[key]; + return prototype; + } + + // node_modules/d3-color/src/color.js + function Color() { + } + var darker = 0.7; + var brighter = 1 / darker; + var reI = "\\s*([+-]?\\d+)\\s*"; + var reN = "\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*"; + var reP = "\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*"; + var reHex = /^#([0-9a-f]{3,8})$/; + var reRgbInteger = new RegExp(`^rgb\\(${reI},${reI},${reI}\\)$`); + var reRgbPercent = new RegExp(`^rgb\\(${reP},${reP},${reP}\\)$`); + var reRgbaInteger = new RegExp(`^rgba\\(${reI},${reI},${reI},${reN}\\)$`); + var reRgbaPercent = new RegExp(`^rgba\\(${reP},${reP},${reP},${reN}\\)$`); + var reHslPercent = new RegExp(`^hsl\\(${reN},${reP},${reP}\\)$`); + var reHslaPercent = new RegExp(`^hsla\\(${reN},${reP},${reP},${reN}\\)$`); + var named = { + aliceblue: 15792383, + antiquewhite: 16444375, + aqua: 65535, + aquamarine: 8388564, + azure: 15794175, + beige: 16119260, + bisque: 16770244, + black: 0, + blanchedalmond: 16772045, + blue: 255, + blueviolet: 9055202, + brown: 10824234, + burlywood: 14596231, + cadetblue: 6266528, + chartreuse: 8388352, + chocolate: 13789470, + coral: 16744272, + cornflowerblue: 6591981, + cornsilk: 16775388, + crimson: 14423100, + cyan: 65535, + darkblue: 139, + darkcyan: 35723, + darkgoldenrod: 12092939, + darkgray: 11119017, + darkgreen: 25600, + darkgrey: 11119017, + darkkhaki: 12433259, + darkmagenta: 9109643, + darkolivegreen: 5597999, + darkorange: 16747520, + darkorchid: 10040012, + darkred: 9109504, + darksalmon: 15308410, + darkseagreen: 9419919, + darkslateblue: 4734347, + darkslategray: 3100495, + darkslategrey: 3100495, + darkturquoise: 52945, + darkviolet: 9699539, + deeppink: 16716947, + deepskyblue: 49151, + dimgray: 6908265, + dimgrey: 6908265, + dodgerblue: 2003199, + firebrick: 11674146, + floralwhite: 16775920, + forestgreen: 2263842, + fuchsia: 16711935, + gainsboro: 14474460, + ghostwhite: 16316671, + gold: 16766720, + goldenrod: 14329120, + gray: 8421504, + green: 32768, + greenyellow: 11403055, + grey: 8421504, + honeydew: 15794160, + hotpink: 16738740, + indianred: 13458524, + indigo: 4915330, + ivory: 16777200, + khaki: 15787660, + lavender: 15132410, + lavenderblush: 16773365, + lawngreen: 8190976, + lemonchiffon: 16775885, + lightblue: 11393254, + lightcoral: 15761536, + lightcyan: 14745599, + lightgoldenrodyellow: 16448210, + lightgray: 13882323, + lightgreen: 9498256, + lightgrey: 13882323, + lightpink: 16758465, + lightsalmon: 16752762, + lightseagreen: 2142890, + lightskyblue: 8900346, + lightslategray: 7833753, + lightslategrey: 7833753, + lightsteelblue: 11584734, + lightyellow: 16777184, + lime: 65280, + limegreen: 3329330, + linen: 16445670, + magenta: 16711935, + maroon: 8388608, + mediumaquamarine: 6737322, + mediumblue: 205, + mediumorchid: 12211667, + mediumpurple: 9662683, + mediumseagreen: 3978097, + mediumslateblue: 8087790, + mediumspringgreen: 64154, + mediumturquoise: 4772300, + mediumvioletred: 13047173, + midnightblue: 1644912, + mintcream: 16121850, + mistyrose: 16770273, + moccasin: 16770229, + navajowhite: 16768685, + navy: 128, + oldlace: 16643558, + olive: 8421376, + olivedrab: 7048739, + orange: 16753920, + orangered: 16729344, + orchid: 14315734, + palegoldenrod: 15657130, + palegreen: 10025880, + paleturquoise: 11529966, + palevioletred: 14381203, + papayawhip: 16773077, + peachpuff: 16767673, + peru: 13468991, + pink: 16761035, + plum: 14524637, + powderblue: 11591910, + purple: 8388736, + rebeccapurple: 6697881, + red: 16711680, + rosybrown: 12357519, + royalblue: 4286945, + saddlebrown: 9127187, + salmon: 16416882, + sandybrown: 16032864, + seagreen: 3050327, + seashell: 16774638, + sienna: 10506797, + silver: 12632256, + skyblue: 8900331, + slateblue: 6970061, + slategray: 7372944, + slategrey: 7372944, + snow: 16775930, + springgreen: 65407, + steelblue: 4620980, + tan: 13808780, + teal: 32896, + thistle: 14204888, + tomato: 16737095, + turquoise: 4251856, + violet: 15631086, + wheat: 16113331, + white: 16777215, + whitesmoke: 16119285, + yellow: 16776960, + yellowgreen: 10145074 + }; + define_default(Color, color, { + copy(channels) { + return Object.assign(new this.constructor(), this, channels); + }, + displayable() { + return this.rgb().displayable(); + }, + hex: color_formatHex, + // Deprecated! Use color.formatHex. + formatHex: color_formatHex, + formatHex8: color_formatHex8, + formatHsl: color_formatHsl, + formatRgb: color_formatRgb, + toString: color_formatRgb + }); + function color_formatHex() { + return this.rgb().formatHex(); + } + function color_formatHex8() { + return this.rgb().formatHex8(); + } + function color_formatHsl() { + return hslConvert(this).formatHsl(); + } + function color_formatRgb() { + return this.rgb().formatRgb(); + } + function color(format2) { + var m, l; + format2 = (format2 + "").trim().toLowerCase(); + return (m = reHex.exec(format2)) ? (l = m[1].length, m = parseInt(m[1], 16), l === 6 ? rgbn(m) : l === 3 ? new Rgb(m >> 8 & 15 | m >> 4 & 240, m >> 4 & 15 | m & 240, (m & 15) << 4 | m & 15, 1) : l === 8 ? rgba(m >> 24 & 255, m >> 16 & 255, m >> 8 & 255, (m & 255) / 255) : l === 4 ? rgba(m >> 12 & 15 | m >> 8 & 240, m >> 8 & 15 | m >> 4 & 240, m >> 4 & 15 | m & 240, ((m & 15) << 4 | m & 15) / 255) : null) : (m = reRgbInteger.exec(format2)) ? new Rgb(m[1], m[2], m[3], 1) : (m = reRgbPercent.exec(format2)) ? new Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) : (m = reRgbaInteger.exec(format2)) ? rgba(m[1], m[2], m[3], m[4]) : (m = reRgbaPercent.exec(format2)) ? rgba(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) : (m = reHslPercent.exec(format2)) ? hsla(m[1], m[2] / 100, m[3] / 100, 1) : (m = reHslaPercent.exec(format2)) ? hsla(m[1], m[2] / 100, m[3] / 100, m[4]) : named.hasOwnProperty(format2) ? rgbn(named[format2]) : format2 === "transparent" ? new Rgb(NaN, NaN, NaN, 0) : null; + } + function rgbn(n) { + return new Rgb(n >> 16 & 255, n >> 8 & 255, n & 255, 1); + } + function rgba(r, g, b, a) { + if (a <= 0) r = g = b = NaN; + return new Rgb(r, g, b, a); + } + function rgbConvert(o) { + if (!(o instanceof Color)) o = color(o); + if (!o) return new Rgb(); + o = o.rgb(); + return new Rgb(o.r, o.g, o.b, o.opacity); + } + function rgb(r, g, b, opacity) { + return arguments.length === 1 ? rgbConvert(r) : new Rgb(r, g, b, opacity == null ? 1 : opacity); + } + function Rgb(r, g, b, opacity) { + this.r = +r; + this.g = +g; + this.b = +b; + this.opacity = +opacity; + } + define_default(Rgb, rgb, extend(Color, { + brighter(k) { + k = k == null ? brighter : Math.pow(brighter, k); + return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity); + }, + darker(k) { + k = k == null ? darker : Math.pow(darker, k); + return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity); + }, + rgb() { + return this; + }, + clamp() { + return new Rgb(clampi(this.r), clampi(this.g), clampi(this.b), clampa(this.opacity)); + }, + displayable() { + return -0.5 <= this.r && this.r < 255.5 && (-0.5 <= this.g && this.g < 255.5) && (-0.5 <= this.b && this.b < 255.5) && (0 <= this.opacity && this.opacity <= 1); + }, + hex: rgb_formatHex, + // Deprecated! Use color.formatHex. + formatHex: rgb_formatHex, + formatHex8: rgb_formatHex8, + formatRgb: rgb_formatRgb, + toString: rgb_formatRgb + })); + function rgb_formatHex() { + return `#${hex(this.r)}${hex(this.g)}${hex(this.b)}`; + } + function rgb_formatHex8() { + return `#${hex(this.r)}${hex(this.g)}${hex(this.b)}${hex((isNaN(this.opacity) ? 1 : this.opacity) * 255)}`; + } + function rgb_formatRgb() { + const a = clampa(this.opacity); + return `${a === 1 ? "rgb(" : "rgba("}${clampi(this.r)}, ${clampi(this.g)}, ${clampi(this.b)}${a === 1 ? ")" : `, ${a})`}`; + } + function clampa(opacity) { + return isNaN(opacity) ? 1 : Math.max(0, Math.min(1, opacity)); + } + function clampi(value) { + return Math.max(0, Math.min(255, Math.round(value) || 0)); + } + function hex(value) { + value = clampi(value); + return (value < 16 ? "0" : "") + value.toString(16); + } + function hsla(h, s, l, a) { + if (a <= 0) h = s = l = NaN; + else if (l <= 0 || l >= 1) h = s = NaN; + else if (s <= 0) h = NaN; + return new Hsl(h, s, l, a); + } + function hslConvert(o) { + if (o instanceof Hsl) return new Hsl(o.h, o.s, o.l, o.opacity); + if (!(o instanceof Color)) o = color(o); + if (!o) return new Hsl(); + if (o instanceof Hsl) return o; + o = o.rgb(); + var r = o.r / 255, g = o.g / 255, b = o.b / 255, min5 = Math.min(r, g, b), max4 = Math.max(r, g, b), h = NaN, s = max4 - min5, l = (max4 + min5) / 2; + if (s) { + if (r === max4) h = (g - b) / s + (g < b) * 6; + else if (g === max4) h = (b - r) / s + 2; + else h = (r - g) / s + 4; + s /= l < 0.5 ? max4 + min5 : 2 - max4 - min5; + h *= 60; + } else { + s = l > 0 && l < 1 ? 0 : h; + } + return new Hsl(h, s, l, o.opacity); + } + function hsl(h, s, l, opacity) { + return arguments.length === 1 ? hslConvert(h) : new Hsl(h, s, l, opacity == null ? 1 : opacity); + } + function Hsl(h, s, l, opacity) { + this.h = +h; + this.s = +s; + this.l = +l; + this.opacity = +opacity; + } + define_default(Hsl, hsl, extend(Color, { + brighter(k) { + k = k == null ? brighter : Math.pow(brighter, k); + return new Hsl(this.h, this.s, this.l * k, this.opacity); + }, + darker(k) { + k = k == null ? darker : Math.pow(darker, k); + return new Hsl(this.h, this.s, this.l * k, this.opacity); + }, + rgb() { + var h = this.h % 360 + (this.h < 0) * 360, s = isNaN(h) || isNaN(this.s) ? 0 : this.s, l = this.l, m2 = l + (l < 0.5 ? l : 1 - l) * s, m1 = 2 * l - m2; + return new Rgb( + hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2), + hsl2rgb(h, m1, m2), + hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2), + this.opacity + ); + }, + clamp() { + return new Hsl(clamph(this.h), clampt(this.s), clampt(this.l), clampa(this.opacity)); + }, + displayable() { + return (0 <= this.s && this.s <= 1 || isNaN(this.s)) && (0 <= this.l && this.l <= 1) && (0 <= this.opacity && this.opacity <= 1); + }, + formatHsl() { + const a = clampa(this.opacity); + return `${a === 1 ? "hsl(" : "hsla("}${clamph(this.h)}, ${clampt(this.s) * 100}%, ${clampt(this.l) * 100}%${a === 1 ? ")" : `, ${a})`}`; + } + })); + function clamph(value) { + value = (value || 0) % 360; + return value < 0 ? value + 360 : value; + } + function clampt(value) { + return Math.max(0, Math.min(1, value || 0)); + } + function hsl2rgb(h, m1, m2) { + return (h < 60 ? m1 + (m2 - m1) * h / 60 : h < 180 ? m2 : h < 240 ? m1 + (m2 - m1) * (240 - h) / 60 : m1) * 255; + } + + // node_modules/d3-color/src/math.js + var radians2 = Math.PI / 180; + var degrees2 = 180 / Math.PI; + + // node_modules/d3-color/src/lab.js + var K = 18; + var Xn = 0.96422; + var Yn = 1; + var Zn = 0.82521; + var t0 = 4 / 29; + var t1 = 6 / 29; + var t2 = 3 * t1 * t1; + var t3 = t1 * t1 * t1; + function labConvert(o) { + if (o instanceof Lab) return new Lab(o.l, o.a, o.b, o.opacity); + if (o instanceof Hcl) return hcl2lab(o); + if (!(o instanceof Rgb)) o = rgbConvert(o); + var r = rgb2lrgb(o.r), g = rgb2lrgb(o.g), b = rgb2lrgb(o.b), y = xyz2lab((0.2225045 * r + 0.7168786 * g + 0.0606169 * b) / Yn), x, z; + if (r === g && g === b) x = z = y; + else { + x = xyz2lab((0.4360747 * r + 0.3850649 * g + 0.1430804 * b) / Xn); + z = xyz2lab((0.0139322 * r + 0.0971045 * g + 0.7141733 * b) / Zn); + } + return new Lab(116 * y - 16, 500 * (x - y), 200 * (y - z), o.opacity); + } + function lab(l, a, b, opacity) { + return arguments.length === 1 ? labConvert(l) : new Lab(l, a, b, opacity == null ? 1 : opacity); + } + function Lab(l, a, b, opacity) { + this.l = +l; + this.a = +a; + this.b = +b; + this.opacity = +opacity; + } + define_default(Lab, lab, extend(Color, { + brighter(k) { + return new Lab(this.l + K * (k == null ? 1 : k), this.a, this.b, this.opacity); + }, + darker(k) { + return new Lab(this.l - K * (k == null ? 1 : k), this.a, this.b, this.opacity); + }, + rgb() { + var y = (this.l + 16) / 116, x = isNaN(this.a) ? y : y + this.a / 500, z = isNaN(this.b) ? y : y - this.b / 200; + x = Xn * lab2xyz(x); + y = Yn * lab2xyz(y); + z = Zn * lab2xyz(z); + return new Rgb( + lrgb2rgb(3.1338561 * x - 1.6168667 * y - 0.4906146 * z), + lrgb2rgb(-0.9787684 * x + 1.9161415 * y + 0.033454 * z), + lrgb2rgb(0.0719453 * x - 0.2289914 * y + 1.4052427 * z), + this.opacity + ); + } + })); + function xyz2lab(t) { + return t > t3 ? Math.pow(t, 1 / 3) : t / t2 + t0; + } + function lab2xyz(t) { + return t > t1 ? t * t * t : t2 * (t - t0); + } + function lrgb2rgb(x) { + return 255 * (x <= 31308e-7 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055); + } + function rgb2lrgb(x) { + return (x /= 255) <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4); + } + function hclConvert(o) { + if (o instanceof Hcl) return new Hcl(o.h, o.c, o.l, o.opacity); + if (!(o instanceof Lab)) o = labConvert(o); + if (o.a === 0 && o.b === 0) return new Hcl(NaN, 0 < o.l && o.l < 100 ? 0 : NaN, o.l, o.opacity); + var h = Math.atan2(o.b, o.a) * degrees2; + return new Hcl(h < 0 ? h + 360 : h, Math.sqrt(o.a * o.a + o.b * o.b), o.l, o.opacity); + } + function hcl(h, c2, l, opacity) { + return arguments.length === 1 ? hclConvert(h) : new Hcl(h, c2, l, opacity == null ? 1 : opacity); + } + function Hcl(h, c2, l, opacity) { + this.h = +h; + this.c = +c2; + this.l = +l; + this.opacity = +opacity; + } + function hcl2lab(o) { + if (isNaN(o.h)) return new Lab(o.l, 0, 0, o.opacity); + var h = o.h * radians2; + return new Lab(o.l, Math.cos(h) * o.c, Math.sin(h) * o.c, o.opacity); + } + define_default(Hcl, hcl, extend(Color, { + brighter(k) { + return new Hcl(this.h, this.c, this.l + K * (k == null ? 1 : k), this.opacity); + }, + darker(k) { + return new Hcl(this.h, this.c, this.l - K * (k == null ? 1 : k), this.opacity); + }, + rgb() { + return hcl2lab(this).rgb(); + } + })); + + // node_modules/d3-color/src/cubehelix.js + var A = -0.14861; + var B = 1.78277; + var C = -0.29227; + var D = -0.90649; + var E = 1.97294; + var ED = E * D; + var EB = E * B; + var BC_DA = B * C - D * A; + function cubehelixConvert(o) { + if (o instanceof Cubehelix) return new Cubehelix(o.h, o.s, o.l, o.opacity); + if (!(o instanceof Rgb)) o = rgbConvert(o); + var r = o.r / 255, g = o.g / 255, b = o.b / 255, l = (BC_DA * b + ED * r - EB * g) / (BC_DA + ED - EB), bl = b - l, k = (E * (g - l) - C * bl) / D, s = Math.sqrt(k * k + bl * bl) / (E * l * (1 - l)), h = s ? Math.atan2(k, bl) * degrees2 - 120 : NaN; + return new Cubehelix(h < 0 ? h + 360 : h, s, l, o.opacity); + } + function cubehelix(h, s, l, opacity) { + return arguments.length === 1 ? cubehelixConvert(h) : new Cubehelix(h, s, l, opacity == null ? 1 : opacity); + } + function Cubehelix(h, s, l, opacity) { + this.h = +h; + this.s = +s; + this.l = +l; + this.opacity = +opacity; + } + define_default(Cubehelix, cubehelix, extend(Color, { + brighter(k) { + k = k == null ? brighter : Math.pow(brighter, k); + return new Cubehelix(this.h, this.s, this.l * k, this.opacity); + }, + darker(k) { + k = k == null ? darker : Math.pow(darker, k); + return new Cubehelix(this.h, this.s, this.l * k, this.opacity); + }, + rgb() { + var h = isNaN(this.h) ? 0 : (this.h + 120) * radians2, l = +this.l, a = isNaN(this.s) ? 0 : this.s * l * (1 - l), cosh = Math.cos(h), sinh = Math.sin(h); + return new Rgb( + 255 * (l + a * (A * cosh + B * sinh)), + 255 * (l + a * (C * cosh + D * sinh)), + 255 * (l + a * (E * cosh)), + this.opacity + ); + } + })); + + // node_modules/d3-interpolate/src/basis.js + function basis(t13, v0, v1, v2, v3) { + var t22 = t13 * t13, t32 = t22 * t13; + return ((1 - 3 * t13 + 3 * t22 - t32) * v0 + (4 - 6 * t22 + 3 * t32) * v1 + (1 + 3 * t13 + 3 * t22 - 3 * t32) * v2 + t32 * v3) / 6; + } + function basis_default(values) { + var n = values.length - 1; + return function(t) { + var i = t <= 0 ? t = 0 : t >= 1 ? (t = 1, n - 1) : Math.floor(t * n), v1 = values[i], v2 = values[i + 1], v0 = i > 0 ? values[i - 1] : 2 * v1 - v2, v3 = i < n - 1 ? values[i + 2] : 2 * v2 - v1; + return basis((t - i / n) * n, v0, v1, v2, v3); + }; + } + + // node_modules/d3-interpolate/src/basisClosed.js + function basisClosed_default(values) { + var n = values.length; + return function(t) { + var i = Math.floor(((t %= 1) < 0 ? ++t : t) * n), v0 = values[(i + n - 1) % n], v1 = values[i % n], v2 = values[(i + 1) % n], v3 = values[(i + 2) % n]; + return basis((t - i / n) * n, v0, v1, v2, v3); + }; + } + + // node_modules/d3-interpolate/src/constant.js + var constant_default = (x) => () => x; + + // node_modules/d3-interpolate/src/color.js + function linear(a, d) { + return function(t) { + return a + t * d; + }; + } + function exponential(a, b, y) { + return a = Math.pow(a, y), b = Math.pow(b, y) - a, y = 1 / y, function(t) { + return Math.pow(a + t * b, y); + }; + } + function hue(a, b) { + var d = b - a; + return d ? linear(a, d > 180 || d < -180 ? d - 360 * Math.round(d / 360) : d) : constant_default(isNaN(a) ? b : a); + } + function gamma(y) { + return (y = +y) === 1 ? nogamma : function(a, b) { + return b - a ? exponential(a, b, y) : constant_default(isNaN(a) ? b : a); + }; + } + function nogamma(a, b) { + var d = b - a; + return d ? linear(a, d) : constant_default(isNaN(a) ? b : a); + } + + // node_modules/d3-interpolate/src/rgb.js + var rgb_default = (function rgbGamma(y) { + var color2 = gamma(y); + function rgb2(start, end) { + var r = color2((start = rgb(start)).r, (end = rgb(end)).r), g = color2(start.g, end.g), b = color2(start.b, end.b), opacity = nogamma(start.opacity, end.opacity); + return function(t) { + start.r = r(t); + start.g = g(t); + start.b = b(t); + start.opacity = opacity(t); + return start + ""; + }; + } + rgb2.gamma = rgbGamma; + return rgb2; + })(1); + function rgbSpline(spline) { + return function(colors) { + var n = colors.length, r = new Array(n), g = new Array(n), b = new Array(n), i, color2; + for (i = 0; i < n; ++i) { + color2 = rgb(colors[i]); + r[i] = color2.r || 0; + g[i] = color2.g || 0; + b[i] = color2.b || 0; + } + r = spline(r); + g = spline(g); + b = spline(b); + color2.opacity = 1; + return function(t) { + color2.r = r(t); + color2.g = g(t); + color2.b = b(t); + return color2 + ""; + }; + }; + } + var rgbBasis = rgbSpline(basis_default); + var rgbBasisClosed = rgbSpline(basisClosed_default); + + // node_modules/d3-interpolate/src/numberArray.js + function numberArray_default(a, b) { + if (!b) b = []; + var n = a ? Math.min(b.length, a.length) : 0, c2 = b.slice(), i; + return function(t) { + for (i = 0; i < n; ++i) c2[i] = a[i] * (1 - t) + b[i] * t; + return c2; + }; + } + function isNumberArray3(x) { + return ArrayBuffer.isView(x) && !(x instanceof DataView); + } + + // node_modules/d3-interpolate/src/array.js + function genericArray(a, b) { + var nb = b ? b.length : 0, na = a ? Math.min(nb, a.length) : 0, x = new Array(na), c2 = new Array(nb), i; + for (i = 0; i < na; ++i) x[i] = value_default(a[i], b[i]); + for (; i < nb; ++i) c2[i] = b[i]; + return function(t) { + for (i = 0; i < na; ++i) c2[i] = x[i](t); + return c2; + }; + } + + // node_modules/d3-interpolate/src/date.js + function date_default(a, b) { + var d = /* @__PURE__ */ new Date(); + return a = +a, b = +b, function(t) { + return d.setTime(a * (1 - t) + b * t), d; + }; + } + + // node_modules/d3-interpolate/src/number.js + function number_default(a, b) { + return a = +a, b = +b, function(t) { + return a * (1 - t) + b * t; + }; + } + + // node_modules/d3-interpolate/src/object.js + function object_default(a, b) { + var i = {}, c2 = {}, k; + if (a === null || typeof a !== "object") a = {}; + if (b === null || typeof b !== "object") b = {}; + for (k in b) { + if (k in a) { + i[k] = value_default(a[k], b[k]); + } else { + c2[k] = b[k]; + } + } + return function(t) { + for (k in i) c2[k] = i[k](t); + return c2; + }; + } + + // node_modules/d3-interpolate/src/string.js + var reA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g; + var reB = new RegExp(reA.source, "g"); + function zero4(b) { + return function() { + return b; + }; + } + function one(b) { + return function(t) { + return b(t) + ""; + }; + } + function string_default(a, b) { + var bi = reA.lastIndex = reB.lastIndex = 0, am, bm, bs, i = -1, s = [], q = []; + a = a + "", b = b + ""; + while ((am = reA.exec(a)) && (bm = reB.exec(b))) { + if ((bs = bm.index) > bi) { + bs = b.slice(bi, bs); + if (s[i]) s[i] += bs; + else s[++i] = bs; + } + if ((am = am[0]) === (bm = bm[0])) { + if (s[i]) s[i] += bm; + else s[++i] = bm; + } else { + s[++i] = null; + q.push({ i, x: number_default(am, bm) }); + } + bi = reB.lastIndex; + } + if (bi < b.length) { + bs = b.slice(bi); + if (s[i]) s[i] += bs; + else s[++i] = bs; + } + return s.length < 2 ? q[0] ? one(q[0].x) : zero4(b) : (b = q.length, function(t) { + for (var i2 = 0, o; i2 < b; ++i2) s[(o = q[i2]).i] = o.x(t); + return s.join(""); + }); + } + + // node_modules/d3-interpolate/src/value.js + function value_default(a, b) { + var t = typeof b, c2; + return b == null || t === "boolean" ? constant_default(b) : (t === "number" ? number_default : t === "string" ? (c2 = color(b)) ? (b = c2, rgb_default) : string_default : b instanceof color ? rgb_default : b instanceof Date ? date_default : isNumberArray3(b) ? numberArray_default : Array.isArray(b) ? genericArray : typeof b.valueOf !== "function" && typeof b.toString !== "function" || isNaN(b) ? object_default : number_default)(a, b); + } + + // node_modules/d3-interpolate/src/round.js + function round_default(a, b) { + return a = +a, b = +b, function(t) { + return Math.round(a * (1 - t) + b * t); + }; + } + + // node_modules/d3-interpolate/src/cubehelix.js + function cubehelix2(hue2) { + return (function cubehelixGamma(y) { + y = +y; + function cubehelix3(start, end) { + var h = hue2((start = cubehelix(start)).h, (end = cubehelix(end)).h), s = nogamma(start.s, end.s), l = nogamma(start.l, end.l), opacity = nogamma(start.opacity, end.opacity); + return function(t) { + start.h = h(t); + start.s = s(t); + start.l = l(Math.pow(t, y)); + start.opacity = opacity(t); + return start + ""; + }; + } + cubehelix3.gamma = cubehelixGamma; + return cubehelix3; + })(1); + } + var cubehelix_default = cubehelix2(hue); + var cubehelixLong = cubehelix2(nogamma); + + // node_modules/d3-scale-chromatic/src/ramp.js + var ramp_default = (scheme19) => rgbBasis(scheme19[scheme19.length - 1]); + + // node_modules/d3-scale-chromatic/src/sequential-multi/BuGn.js + var scheme = new Array(3).concat( + "e5f5f999d8c92ca25f", + "edf8fbb2e2e266c2a4238b45", + "edf8fbb2e2e266c2a42ca25f006d2c", + "edf8fbccece699d8c966c2a42ca25f006d2c", + "edf8fbccece699d8c966c2a441ae76238b45005824", + "f7fcfde5f5f9ccece699d8c966c2a441ae76238b45005824", + "f7fcfde5f5f9ccece699d8c966c2a441ae76238b45006d2c00441b" + ).map(colors_default); + var BuGn_default = ramp_default(scheme); + + // node_modules/d3-scale-chromatic/src/sequential-multi/BuPu.js + var scheme2 = new Array(3).concat( + "e0ecf49ebcda8856a7", + "edf8fbb3cde38c96c688419d", + "edf8fbb3cde38c96c68856a7810f7c", + "edf8fbbfd3e69ebcda8c96c68856a7810f7c", + "edf8fbbfd3e69ebcda8c96c68c6bb188419d6e016b", + "f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d6e016b", + "f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d810f7c4d004b" + ).map(colors_default); + var BuPu_default = ramp_default(scheme2); + + // node_modules/d3-scale-chromatic/src/sequential-multi/GnBu.js + var scheme3 = new Array(3).concat( + "e0f3dba8ddb543a2ca", + "f0f9e8bae4bc7bccc42b8cbe", + "f0f9e8bae4bc7bccc443a2ca0868ac", + "f0f9e8ccebc5a8ddb57bccc443a2ca0868ac", + "f0f9e8ccebc5a8ddb57bccc44eb3d32b8cbe08589e", + "f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe08589e", + "f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe0868ac084081" + ).map(colors_default); + var GnBu_default = ramp_default(scheme3); + + // node_modules/d3-scale-chromatic/src/sequential-multi/OrRd.js + var scheme4 = new Array(3).concat( + "fee8c8fdbb84e34a33", + "fef0d9fdcc8afc8d59d7301f", + "fef0d9fdcc8afc8d59e34a33b30000", + "fef0d9fdd49efdbb84fc8d59e34a33b30000", + "fef0d9fdd49efdbb84fc8d59ef6548d7301f990000", + "fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301f990000", + "fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301fb300007f0000" + ).map(colors_default); + var OrRd_default = ramp_default(scheme4); + + // node_modules/d3-scale-chromatic/src/sequential-multi/PuBuGn.js + var scheme5 = new Array(3).concat( + "ece2f0a6bddb1c9099", + "f6eff7bdc9e167a9cf02818a", + "f6eff7bdc9e167a9cf1c9099016c59", + "f6eff7d0d1e6a6bddb67a9cf1c9099016c59", + "f6eff7d0d1e6a6bddb67a9cf3690c002818a016450", + "fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016450", + "fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016c59014636" + ).map(colors_default); + var PuBuGn_default = ramp_default(scheme5); + + // node_modules/d3-scale-chromatic/src/sequential-multi/PuBu.js + var scheme6 = new Array(3).concat( + "ece7f2a6bddb2b8cbe", + "f1eef6bdc9e174a9cf0570b0", + "f1eef6bdc9e174a9cf2b8cbe045a8d", + "f1eef6d0d1e6a6bddb74a9cf2b8cbe045a8d", + "f1eef6d0d1e6a6bddb74a9cf3690c00570b0034e7b", + "fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0034e7b", + "fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0045a8d023858" + ).map(colors_default); + var PuBu_default = ramp_default(scheme6); + + // node_modules/d3-scale-chromatic/src/sequential-multi/PuRd.js + var scheme7 = new Array(3).concat( + "e7e1efc994c7dd1c77", + "f1eef6d7b5d8df65b0ce1256", + "f1eef6d7b5d8df65b0dd1c77980043", + "f1eef6d4b9dac994c7df65b0dd1c77980043", + "f1eef6d4b9dac994c7df65b0e7298ace125691003f", + "f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125691003f", + "f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125698004367001f" + ).map(colors_default); + var PuRd_default = ramp_default(scheme7); + + // node_modules/d3-scale-chromatic/src/sequential-multi/RdPu.js + var scheme8 = new Array(3).concat( + "fde0ddfa9fb5c51b8a", + "feebe2fbb4b9f768a1ae017e", + "feebe2fbb4b9f768a1c51b8a7a0177", + "feebe2fcc5c0fa9fb5f768a1c51b8a7a0177", + "feebe2fcc5c0fa9fb5f768a1dd3497ae017e7a0177", + "fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a0177", + "fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a017749006a" + ).map(colors_default); + var RdPu_default = ramp_default(scheme8); + + // node_modules/d3-scale-chromatic/src/sequential-multi/YlGnBu.js + var scheme9 = new Array(3).concat( + "edf8b17fcdbb2c7fb8", + "ffffcca1dab441b6c4225ea8", + "ffffcca1dab441b6c42c7fb8253494", + "ffffccc7e9b47fcdbb41b6c42c7fb8253494", + "ffffccc7e9b47fcdbb41b6c41d91c0225ea80c2c84", + "ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea80c2c84", + "ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea8253494081d58" + ).map(colors_default); + var YlGnBu_default = ramp_default(scheme9); + + // node_modules/d3-scale-chromatic/src/sequential-multi/YlGn.js + var scheme10 = new Array(3).concat( + "f7fcb9addd8e31a354", + "ffffccc2e69978c679238443", + "ffffccc2e69978c67931a354006837", + "ffffccd9f0a3addd8e78c67931a354006837", + "ffffccd9f0a3addd8e78c67941ab5d238443005a32", + "ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443005a32", + "ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443006837004529" + ).map(colors_default); + var YlGn_default = ramp_default(scheme10); + + // node_modules/d3-scale-chromatic/src/sequential-multi/YlOrBr.js + var scheme11 = new Array(3).concat( + "fff7bcfec44fd95f0e", + "ffffd4fed98efe9929cc4c02", + "ffffd4fed98efe9929d95f0e993404", + "ffffd4fee391fec44ffe9929d95f0e993404", + "ffffd4fee391fec44ffe9929ec7014cc4c028c2d04", + "ffffe5fff7bcfee391fec44ffe9929ec7014cc4c028c2d04", + "ffffe5fff7bcfee391fec44ffe9929ec7014cc4c02993404662506" + ).map(colors_default); + var YlOrBr_default = ramp_default(scheme11); + + // node_modules/d3-scale-chromatic/src/sequential-multi/YlOrRd.js + var scheme12 = new Array(3).concat( + "ffeda0feb24cf03b20", + "ffffb2fecc5cfd8d3ce31a1c", + "ffffb2fecc5cfd8d3cf03b20bd0026", + "ffffb2fed976feb24cfd8d3cf03b20bd0026", + "ffffb2fed976feb24cfd8d3cfc4e2ae31a1cb10026", + "ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cb10026", + "ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cbd0026800026" + ).map(colors_default); + var YlOrRd_default = ramp_default(scheme12); + + // node_modules/d3-scale-chromatic/src/sequential-single/Blues.js + var scheme13 = new Array(3).concat( + "deebf79ecae13182bd", + "eff3ffbdd7e76baed62171b5", + "eff3ffbdd7e76baed63182bd08519c", + "eff3ffc6dbef9ecae16baed63182bd08519c", + "eff3ffc6dbef9ecae16baed64292c62171b5084594", + "f7fbffdeebf7c6dbef9ecae16baed64292c62171b5084594", + "f7fbffdeebf7c6dbef9ecae16baed64292c62171b508519c08306b" + ).map(colors_default); + var Blues_default = ramp_default(scheme13); + + // node_modules/d3-scale-chromatic/src/sequential-single/Greens.js + var scheme14 = new Array(3).concat( + "e5f5e0a1d99b31a354", + "edf8e9bae4b374c476238b45", + "edf8e9bae4b374c47631a354006d2c", + "edf8e9c7e9c0a1d99b74c47631a354006d2c", + "edf8e9c7e9c0a1d99b74c47641ab5d238b45005a32", + "f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45005a32", + "f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45006d2c00441b" + ).map(colors_default); + var Greens_default = ramp_default(scheme14); + + // node_modules/d3-scale-chromatic/src/sequential-single/Greys.js + var scheme15 = new Array(3).concat( + "f0f0f0bdbdbd636363", + "f7f7f7cccccc969696525252", + "f7f7f7cccccc969696636363252525", + "f7f7f7d9d9d9bdbdbd969696636363252525", + "f7f7f7d9d9d9bdbdbd969696737373525252252525", + "fffffff0f0f0d9d9d9bdbdbd969696737373525252252525", + "fffffff0f0f0d9d9d9bdbdbd969696737373525252252525000000" + ).map(colors_default); + var Greys_default = ramp_default(scheme15); + + // node_modules/d3-scale-chromatic/src/sequential-single/Purples.js + var scheme16 = new Array(3).concat( + "efedf5bcbddc756bb1", + "f2f0f7cbc9e29e9ac86a51a3", + "f2f0f7cbc9e29e9ac8756bb154278f", + "f2f0f7dadaebbcbddc9e9ac8756bb154278f", + "f2f0f7dadaebbcbddc9e9ac8807dba6a51a34a1486", + "fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a34a1486", + "fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a354278f3f007d" + ).map(colors_default); + var Purples_default = ramp_default(scheme16); + + // node_modules/d3-scale-chromatic/src/sequential-single/Reds.js + var scheme17 = new Array(3).concat( + "fee0d2fc9272de2d26", + "fee5d9fcae91fb6a4acb181d", + "fee5d9fcae91fb6a4ade2d26a50f15", + "fee5d9fcbba1fc9272fb6a4ade2d26a50f15", + "fee5d9fcbba1fc9272fb6a4aef3b2ccb181d99000d", + "fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181d99000d", + "fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181da50f1567000d" + ).map(colors_default); + var Reds_default = ramp_default(scheme17); + + // node_modules/d3-scale-chromatic/src/sequential-single/Oranges.js + var scheme18 = new Array(3).concat( + "fee6cefdae6be6550d", + "feeddefdbe85fd8d3cd94701", + "feeddefdbe85fd8d3ce6550da63603", + "feeddefdd0a2fdae6bfd8d3ce6550da63603", + "feeddefdd0a2fdae6bfd8d3cf16913d948018c2d04", + "fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d948018c2d04", + "fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d94801a636037f2704" + ).map(colors_default); + var Oranges_default = ramp_default(scheme18); + + // node_modules/d3-scale-chromatic/src/sequential-multi/rainbow.js + var warm = cubehelixLong(cubehelix(-100, 0.75, 0.35), cubehelix(80, 1.5, 0.8)); + var cool = cubehelixLong(cubehelix(260, 0.75, 0.35), cubehelix(80, 1.5, 0.8)); + var c = cubehelix(); + + // node_modules/d3-scale-chromatic/src/sequential-multi/viridis.js + function ramp(range3) { + var n = range3.length; + return function(t) { + return range3[Math.max(0, Math.min(n - 1, Math.floor(t * n)))]; + }; + } + var viridis_default = ramp(colors_default("44015444025645045745055946075a46085c460a5d460b5e470d60470e6147106347116447136548146748166848176948186a481a6c481b6d481c6e481d6f481f70482071482173482374482475482576482677482878482979472a7a472c7a472d7b472e7c472f7d46307e46327e46337f463480453581453781453882443983443a83443b84433d84433e85423f854240864241864142874144874045884046883f47883f48893e49893e4a893e4c8a3d4d8a3d4e8a3c4f8a3c508b3b518b3b528b3a538b3a548c39558c39568c38588c38598c375a8c375b8d365c8d365d8d355e8d355f8d34608d34618d33628d33638d32648e32658e31668e31678e31688e30698e306a8e2f6b8e2f6c8e2e6d8e2e6e8e2e6f8e2d708e2d718e2c718e2c728e2c738e2b748e2b758e2a768e2a778e2a788e29798e297a8e297b8e287c8e287d8e277e8e277f8e27808e26818e26828e26828e25838e25848e25858e24868e24878e23888e23898e238a8d228b8d228c8d228d8d218e8d218f8d21908d21918c20928c20928c20938c1f948c1f958b1f968b1f978b1f988b1f998a1f9a8a1e9b8a1e9c891e9d891f9e891f9f881fa0881fa1881fa1871fa28720a38620a48621a58521a68522a78522a88423a98324aa8325ab8225ac8226ad8127ad8128ae8029af7f2ab07f2cb17e2db27d2eb37c2fb47c31b57b32b67a34b67935b77937b87838b9773aba763bbb753dbc743fbc7340bd7242be7144bf7046c06f48c16e4ac16d4cc26c4ec36b50c46a52c56954c56856c66758c7655ac8645cc8635ec96260ca6063cb5f65cb5e67cc5c69cd5b6ccd5a6ece5870cf5773d05675d05477d1537ad1517cd2507fd34e81d34d84d44b86d54989d5488bd6468ed64590d74393d74195d84098d83e9bd93c9dd93ba0da39a2da37a5db36a8db34aadc32addc30b0dd2fb2dd2db5de2bb8de29bade28bddf26c0df25c2df23c5e021c8e020cae11fcde11dd0e11cd2e21bd5e21ad8e219dae319dde318dfe318e2e418e5e419e7e419eae51aece51befe51cf1e51df4e61ef6e620f8e621fbe723fde725")); + var magma = ramp(colors_default("00000401000501010601010802010902020b02020d03030f03031204041405041606051806051a07061c08071e0907200a08220b09240c09260d0a290e0b2b100b2d110c2f120d31130d34140e36150e38160f3b180f3d19103f1a10421c10441d11471e114920114b21114e22115024125325125527125829115a2a115c2c115f2d11612f116331116533106734106936106b38106c390f6e3b0f703d0f713f0f72400f74420f75440f764510774710784910784a10794c117a4e117b4f127b51127c52137c54137d56147d57157e59157e5a167e5c167f5d177f5f187f601880621980641a80651a80671b80681c816a1c816b1d816d1d816e1e81701f81721f817320817521817621817822817922827b23827c23827e24828025828125818326818426818627818827818928818b29818c29818e2a81902a81912b81932b80942c80962c80982d80992d809b2e7f9c2e7f9e2f7fa02f7fa1307ea3307ea5317ea6317da8327daa337dab337cad347cae347bb0357bb2357bb3367ab5367ab73779b83779ba3878bc3978bd3977bf3a77c03a76c23b75c43c75c53c74c73d73c83e73ca3e72cc3f71cd4071cf4070d0416fd2426fd3436ed5446dd6456cd8456cd9466bdb476adc4869de4968df4a68e04c67e24d66e34e65e44f64e55064e75263e85362e95462ea5661eb5760ec5860ed5a5fee5b5eef5d5ef05f5ef1605df2625df2645cf3655cf4675cf4695cf56b5cf66c5cf66e5cf7705cf7725cf8745cf8765cf9785df9795df97b5dfa7d5efa7f5efa815ffb835ffb8560fb8761fc8961fc8a62fc8c63fc8e64fc9065fd9266fd9467fd9668fd9869fd9a6afd9b6bfe9d6cfe9f6dfea16efea36ffea571fea772fea973feaa74feac76feae77feb078feb27afeb47bfeb67cfeb77efeb97ffebb81febd82febf84fec185fec287fec488fec68afec88cfeca8dfecc8ffecd90fecf92fed194fed395fed597fed799fed89afdda9cfddc9efddea0fde0a1fde2a3fde3a5fde5a7fde7a9fde9aafdebacfcecaefceeb0fcf0b2fcf2b4fcf4b6fcf6b8fcf7b9fcf9bbfcfbbdfcfdbf")); + var inferno = ramp(colors_default("00000401000501010601010802010a02020c02020e03021004031204031405041706041907051b08051d09061f0a07220b07240c08260d08290e092b10092d110a30120a32140b34150b37160b39180c3c190c3e1b0c411c0c431e0c451f0c48210c4a230c4c240c4f260c51280b53290b552b0b572d0b592f0a5b310a5c320a5e340a5f3609613809623909633b09643d09653e0966400a67420a68440a68450a69470b6a490b6a4a0c6b4c0c6b4d0d6c4f0d6c510e6c520e6d540f6d550f6d57106e59106e5a116e5c126e5d126e5f136e61136e62146e64156e65156e67166e69166e6a176e6c186e6d186e6f196e71196e721a6e741a6e751b6e771c6d781c6d7a1d6d7c1d6d7d1e6d7f1e6c801f6c82206c84206b85216b87216b88226a8a226a8c23698d23698f24699025689225689326679526679727669827669a28659b29649d29649f2a63a02a63a22b62a32c61a52c60a62d60a82e5fa92e5eab2f5ead305dae305cb0315bb1325ab3325ab43359b63458b73557b93556ba3655bc3754bd3853bf3952c03a51c13a50c33b4fc43c4ec63d4dc73e4cc83f4bca404acb4149cc4248ce4347cf4446d04545d24644d34743d44842d54a41d74b3fd84c3ed94d3dda4e3cdb503bdd513ade5238df5337e05536e15635e25734e35933e45a31e55c30e65d2fe75e2ee8602de9612bea632aeb6429eb6628ec6726ed6925ee6a24ef6c23ef6e21f06f20f1711ff1731df2741cf3761bf37819f47918f57b17f57d15f67e14f68013f78212f78410f8850ff8870ef8890cf98b0bf98c0af98e09fa9008fa9207fa9407fb9606fb9706fb9906fb9b06fb9d07fc9f07fca108fca309fca50afca60cfca80dfcaa0ffcac11fcae12fcb014fcb216fcb418fbb61afbb81dfbba1ffbbc21fbbe23fac026fac228fac42afac62df9c72ff9c932f9cb35f8cd37f8cf3af7d13df7d340f6d543f6d746f5d949f5db4cf4dd4ff4df53f4e156f3e35af3e55df2e661f2e865f2ea69f1ec6df1ed71f1ef75f1f179f2f27df2f482f3f586f3f68af4f88ef5f992f6fa96f8fb9af9fc9dfafda1fcffa4")); + var plasma = ramp(colors_default("0d088710078813078916078a19068c1b068d1d068e20068f2206902406912605912805922a05932c05942e05952f059631059733059735049837049938049a3a049a3c049b3e049c3f049c41049d43039e44039e46039f48039f4903a04b03a14c02a14e02a25002a25102a35302a35502a45601a45801a45901a55b01a55c01a65e01a66001a66100a76300a76400a76600a76700a86900a86a00a86c00a86e00a86f00a87100a87201a87401a87501a87701a87801a87a02a87b02a87d03a87e03a88004a88104a78305a78405a78606a68707a68808a68a09a58b0aa58d0ba58e0ca48f0da4910ea3920fa39410a29511a19613a19814a099159f9a169f9c179e9d189d9e199da01a9ca11b9ba21d9aa31e9aa51f99a62098a72197a82296aa2395ab2494ac2694ad2793ae2892b02991b12a90b22b8fb32c8eb42e8db52f8cb6308bb7318ab83289ba3388bb3488bc3587bd3786be3885bf3984c03a83c13b82c23c81c33d80c43e7fc5407ec6417dc7427cc8437bc9447aca457acb4679cc4778cc4977cd4a76ce4b75cf4c74d04d73d14e72d24f71d35171d45270d5536fd5546ed6556dd7566cd8576bd9586ada5a6ada5b69db5c68dc5d67dd5e66de5f65de6164df6263e06363e16462e26561e26660e3685fe4695ee56a5de56b5de66c5ce76e5be76f5ae87059e97158e97257ea7457eb7556eb7655ec7754ed7953ed7a52ee7b51ef7c51ef7e50f07f4ff0804ef1814df1834cf2844bf3854bf3874af48849f48948f58b47f58c46f68d45f68f44f79044f79143f79342f89441f89540f9973ff9983ef99a3efa9b3dfa9c3cfa9e3bfb9f3afba139fba238fca338fca537fca636fca835fca934fdab33fdac33fdae32fdaf31fdb130fdb22ffdb42ffdb52efeb72dfeb82cfeba2cfebb2bfebd2afebe2afec029fdc229fdc328fdc527fdc627fdc827fdca26fdcb26fccd25fcce25fcd025fcd225fbd324fbd524fbd724fad824fada24f9dc24f9dd25f8df25f8e125f7e225f7e425f6e626f6e826f5e926f5eb27f4ed27f3ee27f3f027f2f227f1f426f1f525f0f724f0f921")); + + // node_modules/d3-array/src/ascending.js + function ascending(a, b) { + return a == null || b == null ? NaN : a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN; + } + + // node_modules/d3-array/src/descending.js + function descending(a, b) { + return a == null || b == null ? NaN : b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN; + } + + // node_modules/d3-array/src/bisector.js + function bisector(f) { + let compare1, compare2, delta; + if (f.length !== 2) { + compare1 = ascending; + compare2 = (d, x) => ascending(f(d), x); + delta = (d, x) => f(d) - x; + } else { + compare1 = f === ascending || f === descending ? f : zero5; + compare2 = f; + delta = f; + } + function left(a, x, lo = 0, hi = a.length) { + if (lo < hi) { + if (compare1(x, x) !== 0) return hi; + do { + const mid = lo + hi >>> 1; + if (compare2(a[mid], x) < 0) lo = mid + 1; + else hi = mid; + } while (lo < hi); + } + return lo; + } + function right(a, x, lo = 0, hi = a.length) { + if (lo < hi) { + if (compare1(x, x) !== 0) return hi; + do { + const mid = lo + hi >>> 1; + if (compare2(a[mid], x) <= 0) lo = mid + 1; + else hi = mid; + } while (lo < hi); + } + return lo; + } + function center(a, x, lo = 0, hi = a.length) { + const i = left(a, x, lo, hi - 1); + return i > lo && delta(a[i - 1], x) > -delta(a[i], x) ? i - 1 : i; + } + return { left, center, right }; + } + function zero5() { + return 0; + } + + // node_modules/d3-array/src/number.js + function number(x) { + return x === null ? NaN : +x; + } + + // node_modules/d3-array/src/bisect.js + var ascendingBisect = bisector(ascending); + var bisectRight = ascendingBisect.right; + var bisectLeft = ascendingBisect.left; + var bisectCenter = bisector(number).center; + var bisect_default = bisectRight; + + // node_modules/d3-array/src/extent.js + function extent(values, valueof) { + let min5; + let max4; + if (valueof === void 0) { + for (const value of values) { + if (value != null) { + if (min5 === void 0) { + if (value >= value) min5 = max4 = value; + } else { + if (min5 > value) min5 = value; + if (max4 < value) max4 = value; + } + } + } + } else { + let index2 = -1; + for (let value of values) { + if ((value = valueof(value, ++index2, values)) != null) { + if (min5 === void 0) { + if (value >= value) min5 = max4 = value; + } else { + if (min5 > value) min5 = value; + if (max4 < value) max4 = value; + } + } + } + } + return [min5, max4]; + } + + // node_modules/d3-array/src/fsum.js + var Adder = class { + constructor() { + this._partials = new Float64Array(32); + this._n = 0; + } + add(x) { + const p = this._partials; + let i = 0; + for (let j = 0; j < this._n && j < 32; j++) { + const y = p[j], hi = x + y, lo = Math.abs(x) < Math.abs(y) ? x - (hi - y) : y - (hi - x); + if (lo) p[i++] = lo; + x = hi; + } + p[i] = x; + this._n = i + 1; + return this; + } + valueOf() { + const p = this._partials; + let n = this._n, x, y, lo, hi = 0; + if (n > 0) { + hi = p[--n]; + while (n > 0) { + x = hi; + y = p[--n]; + hi = x + y; + lo = y - (hi - x); + if (lo) break; + } + if (n > 0 && (lo < 0 && p[n - 1] < 0 || lo > 0 && p[n - 1] > 0)) { + y = lo * 2; + x = hi + y; + if (y == x - hi) hi = x; + } + } + return hi; + } + }; + + // node_modules/internmap/src/index.js + var InternMap = class extends Map { + constructor(entries, key = keyof) { + super(); + Object.defineProperties(this, { _intern: { value: /* @__PURE__ */ new Map() }, _key: { value: key } }); + if (entries != null) for (const [key2, value] of entries) this.set(key2, value); + } + get(key) { + return super.get(intern_get(this, key)); + } + has(key) { + return super.has(intern_get(this, key)); + } + set(key, value) { + return super.set(intern_set(this, key), value); + } + delete(key) { + return super.delete(intern_delete(this, key)); + } + }; + function intern_get({ _intern, _key }, value) { + const key = _key(value); + return _intern.has(key) ? _intern.get(key) : value; + } + function intern_set({ _intern, _key }, value) { + const key = _key(value); + if (_intern.has(key)) return _intern.get(key); + _intern.set(key, value); + return value; + } + function intern_delete({ _intern, _key }, value) { + const key = _key(value); + if (_intern.has(key)) { + value = _intern.get(key); + _intern.delete(key); + } + return value; + } + function keyof(value) { + return value !== null && typeof value === "object" ? value.valueOf() : value; + } + + // node_modules/d3-array/src/identity.js + function identity2(x) { + return x; + } + + // node_modules/d3-array/src/group.js + function rollup(values, reduce, ...keys) { + return nest(values, identity2, reduce, keys); + } + function nest(values, map4, reduce, keys) { + return (function regroup(values2, i) { + if (i >= keys.length) return reduce(values2); + const groups2 = new InternMap(); + const keyof2 = keys[i++]; + let index2 = -1; + for (const value of values2) { + const key = keyof2(value, ++index2, values2); + const group2 = groups2.get(key); + if (group2) group2.push(value); + else groups2.set(key, [value]); + } + for (const [key, values3] of groups2) { + groups2.set(key, regroup(values3, i)); + } + return map4(groups2); + })(values, 0); + } + + // node_modules/d3-array/src/ticks.js + var e10 = Math.sqrt(50); + var e5 = Math.sqrt(10); + var e2 = Math.sqrt(2); + function tickSpec(start, stop, count2) { + const step = (stop - start) / Math.max(0, count2), power = Math.floor(Math.log10(step)), error = step / Math.pow(10, power), factor = error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1; + let i1, i2, inc; + if (power < 0) { + inc = Math.pow(10, -power) / factor; + i1 = Math.round(start * inc); + i2 = Math.round(stop * inc); + if (i1 / inc < start) ++i1; + if (i2 / inc > stop) --i2; + inc = -inc; + } else { + inc = Math.pow(10, power) * factor; + i1 = Math.round(start / inc); + i2 = Math.round(stop / inc); + if (i1 * inc < start) ++i1; + if (i2 * inc > stop) --i2; + } + if (i2 < i1 && 0.5 <= count2 && count2 < 2) return tickSpec(start, stop, count2 * 2); + return [i1, i2, inc]; + } + function ticks(start, stop, count2) { + stop = +stop, start = +start, count2 = +count2; + if (!(count2 > 0)) return []; + if (start === stop) return [start]; + const reverse = stop < start, [i1, i2, inc] = reverse ? tickSpec(stop, start, count2) : tickSpec(start, stop, count2); + if (!(i2 >= i1)) return []; + const n = i2 - i1 + 1, ticks2 = new Array(n); + if (reverse) { + if (inc < 0) for (let i = 0; i < n; ++i) ticks2[i] = (i2 - i) / -inc; + else for (let i = 0; i < n; ++i) ticks2[i] = (i2 - i) * inc; + } else { + if (inc < 0) for (let i = 0; i < n; ++i) ticks2[i] = (i1 + i) / -inc; + else for (let i = 0; i < n; ++i) ticks2[i] = (i1 + i) * inc; + } + return ticks2; + } + function tickIncrement(start, stop, count2) { + stop = +stop, start = +start, count2 = +count2; + return tickSpec(start, stop, count2)[2]; + } + function tickStep(start, stop, count2) { + stop = +stop, start = +start, count2 = +count2; + const reverse = stop < start, inc = reverse ? tickIncrement(stop, start, count2) : tickIncrement(start, stop, count2); + return (reverse ? -1 : 1) * (inc < 0 ? 1 / -inc : inc); + } + + // node_modules/d3-array/src/min.js + function min4(values, valueof) { + let min5; + if (valueof === void 0) { + for (const value of values) { + if (value != null && (min5 > value || min5 === void 0 && value >= value)) { + min5 = value; + } + } + } else { + let index2 = -1; + for (let value of values) { + if ((value = valueof(value, ++index2, values)) != null && (min5 > value || min5 === void 0 && value >= value)) { + min5 = value; + } + } + } + return min5; + } + + // node_modules/d3-array/src/range.js + function range(start, stop, step) { + start = +start, stop = +stop, step = (n = arguments.length) < 2 ? (stop = start, start = 0, 1) : n < 3 ? 1 : +step; + var i = -1, n = Math.max(0, Math.ceil((stop - start) / step)) | 0, range3 = new Array(n); + while (++i < n) { + range3[i] = start + i * step; + } + return range3; + } + + // node_modules/d3-scale/src/init.js + function initRange(domain, range3) { + switch (arguments.length) { + case 0: + break; + case 1: + this.range(domain); + break; + default: + this.range(range3).domain(domain); + break; + } + return this; + } + function initInterpolator(domain, interpolator) { + switch (arguments.length) { + case 0: + break; + case 1: { + if (typeof domain === "function") this.interpolator(domain); + else this.range(domain); + break; + } + default: { + this.domain(domain); + if (typeof interpolator === "function") this.interpolator(interpolator); + else this.range(interpolator); + break; + } + } + return this; + } + + // node_modules/d3-scale/src/constant.js + function constants(x) { + return function() { + return x; + }; + } + + // node_modules/d3-scale/src/number.js + function number2(x) { + return +x; + } + + // node_modules/d3-scale/src/continuous.js + var unit = [0, 1]; + function identity3(x) { + return x; + } + function normalize4(a, b) { + return (b -= a = +a) ? function(x) { + return (x - a) / b; + } : constants(isNaN(b) ? NaN : 0.5); + } + function clamper(a, b) { + var t; + if (a > b) t = a, a = b, b = t; + return function(x) { + return Math.max(a, Math.min(b, x)); + }; + } + function bimap(domain, range3, interpolate) { + var d0 = domain[0], d1 = domain[1], r0 = range3[0], r1 = range3[1]; + if (d1 < d0) d0 = normalize4(d1, d0), r0 = interpolate(r1, r0); + else d0 = normalize4(d0, d1), r0 = interpolate(r0, r1); + return function(x) { + return r0(d0(x)); + }; + } + function polymap(domain, range3, interpolate) { + var j = Math.min(domain.length, range3.length) - 1, d = new Array(j), r = new Array(j), i = -1; + if (domain[j] < domain[0]) { + domain = domain.slice().reverse(); + range3 = range3.slice().reverse(); + } + while (++i < j) { + d[i] = normalize4(domain[i], domain[i + 1]); + r[i] = interpolate(range3[i], range3[i + 1]); + } + return function(x) { + var i2 = bisect_default(domain, x, 1, j) - 1; + return r[i2](d[i2](x)); + }; + } + function copy5(source3, target2) { + return target2.domain(source3.domain()).range(source3.range()).interpolate(source3.interpolate()).clamp(source3.clamp()).unknown(source3.unknown()); + } + function transformer() { + var domain = unit, range3 = unit, interpolate = value_default, transform, untransform, unknown, clamp3 = identity3, piecewise, output, input; + function rescale() { + var n = Math.min(domain.length, range3.length); + if (clamp3 !== identity3) clamp3 = clamper(domain[0], domain[n - 1]); + piecewise = n > 2 ? polymap : bimap; + output = input = null; + return scale5; + } + function scale5(x) { + return x == null || isNaN(x = +x) ? unknown : (output || (output = piecewise(domain.map(transform), range3, interpolate)))(transform(clamp3(x))); + } + scale5.invert = function(y) { + return clamp3(untransform((input || (input = piecewise(range3, domain.map(transform), number_default)))(y))); + }; + scale5.domain = function(_) { + return arguments.length ? (domain = Array.from(_, number2), rescale()) : domain.slice(); + }; + scale5.range = function(_) { + return arguments.length ? (range3 = Array.from(_), rescale()) : range3.slice(); + }; + scale5.rangeRound = function(_) { + return range3 = Array.from(_), interpolate = round_default, rescale(); + }; + scale5.clamp = function(_) { + return arguments.length ? (clamp3 = _ ? true : identity3, rescale()) : clamp3 !== identity3; + }; + scale5.interpolate = function(_) { + return arguments.length ? (interpolate = _, rescale()) : interpolate; + }; + scale5.unknown = function(_) { + return arguments.length ? (unknown = _, scale5) : unknown; + }; + return function(t, u) { + transform = t, untransform = u; + return rescale(); + }; + } + function continuous() { + return transformer()(identity3, identity3); + } + + // node_modules/d3-format/src/formatDecimal.js + function formatDecimal_default(x) { + return Math.abs(x = Math.round(x)) >= 1e21 ? x.toLocaleString("en").replace(/,/g, "") : x.toString(10); + } + function formatDecimalParts(x, p) { + if (!isFinite(x) || x === 0) return null; + var i = (x = p ? x.toExponential(p - 1) : x.toExponential()).indexOf("e"), coefficient = x.slice(0, i); + return [ + coefficient.length > 1 ? coefficient[0] + coefficient.slice(2) : coefficient, + +x.slice(i + 1) + ]; + } + + // node_modules/d3-format/src/exponent.js + function exponent_default(x) { + return x = formatDecimalParts(Math.abs(x)), x ? x[1] : NaN; + } + + // node_modules/d3-format/src/formatGroup.js + function formatGroup_default(grouping, thousands) { + return function(value, width) { + var i = value.length, t = [], j = 0, g = grouping[0], length4 = 0; + while (i > 0 && g > 0) { + if (length4 + g + 1 > width) g = Math.max(1, width - length4); + t.push(value.substring(i -= g, i + g)); + if ((length4 += g + 1) > width) break; + g = grouping[j = (j + 1) % grouping.length]; + } + return t.reverse().join(thousands); + }; + } + + // node_modules/d3-format/src/formatNumerals.js + function formatNumerals_default(numerals) { + return function(value) { + return value.replace(/[0-9]/g, function(i) { + return numerals[+i]; + }); + }; + } + + // node_modules/d3-format/src/formatSpecifier.js + var re = /^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i; + function formatSpecifier(specifier) { + if (!(match = re.exec(specifier))) throw new Error("invalid format: " + specifier); + var match; + return new FormatSpecifier({ + fill: match[1], + align: match[2], + sign: match[3], + symbol: match[4], + zero: match[5], + width: match[6], + comma: match[7], + precision: match[8] && match[8].slice(1), + trim: match[9], + type: match[10] + }); + } + formatSpecifier.prototype = FormatSpecifier.prototype; + function FormatSpecifier(specifier) { + this.fill = specifier.fill === void 0 ? " " : specifier.fill + ""; + this.align = specifier.align === void 0 ? ">" : specifier.align + ""; + this.sign = specifier.sign === void 0 ? "-" : specifier.sign + ""; + this.symbol = specifier.symbol === void 0 ? "" : specifier.symbol + ""; + this.zero = !!specifier.zero; + this.width = specifier.width === void 0 ? void 0 : +specifier.width; + this.comma = !!specifier.comma; + this.precision = specifier.precision === void 0 ? void 0 : +specifier.precision; + this.trim = !!specifier.trim; + this.type = specifier.type === void 0 ? "" : specifier.type + ""; + } + FormatSpecifier.prototype.toString = function() { + return this.fill + this.align + this.sign + this.symbol + (this.zero ? "0" : "") + (this.width === void 0 ? "" : Math.max(1, this.width | 0)) + (this.comma ? "," : "") + (this.precision === void 0 ? "" : "." + Math.max(0, this.precision | 0)) + (this.trim ? "~" : "") + this.type; + }; + + // node_modules/d3-format/src/formatTrim.js + function formatTrim_default(s) { + out: for (var n = s.length, i = 1, i0 = -1, i1; i < n; ++i) { + switch (s[i]) { + case ".": + i0 = i1 = i; + break; + case "0": + if (i0 === 0) i0 = i; + i1 = i; + break; + default: + if (!+s[i]) break out; + if (i0 > 0) i0 = 0; + break; + } + } + return i0 > 0 ? s.slice(0, i0) + s.slice(i1 + 1) : s; + } + + // node_modules/d3-format/src/formatPrefixAuto.js + var prefixExponent; + function formatPrefixAuto_default(x, p) { + var d = formatDecimalParts(x, p); + if (!d) return prefixExponent = void 0, x.toPrecision(p); + var coefficient = d[0], exponent = d[1], i = exponent - (prefixExponent = Math.max(-8, Math.min(8, Math.floor(exponent / 3))) * 3) + 1, n = coefficient.length; + return i === n ? coefficient : i > n ? coefficient + new Array(i - n + 1).join("0") : i > 0 ? coefficient.slice(0, i) + "." + coefficient.slice(i) : "0." + new Array(1 - i).join("0") + formatDecimalParts(x, Math.max(0, p + i - 1))[0]; + } + + // node_modules/d3-format/src/formatRounded.js + function formatRounded_default(x, p) { + var d = formatDecimalParts(x, p); + if (!d) return x + ""; + var coefficient = d[0], exponent = d[1]; + return exponent < 0 ? "0." + new Array(-exponent).join("0") + coefficient : coefficient.length > exponent + 1 ? coefficient.slice(0, exponent + 1) + "." + coefficient.slice(exponent + 1) : coefficient + new Array(exponent - coefficient.length + 2).join("0"); + } + + // node_modules/d3-format/src/formatTypes.js + var formatTypes_default = { + "%": (x, p) => (x * 100).toFixed(p), + "b": (x) => Math.round(x).toString(2), + "c": (x) => x + "", + "d": formatDecimal_default, + "e": (x, p) => x.toExponential(p), + "f": (x, p) => x.toFixed(p), + "g": (x, p) => x.toPrecision(p), + "o": (x) => Math.round(x).toString(8), + "p": (x, p) => formatRounded_default(x * 100, p), + "r": formatRounded_default, + "s": formatPrefixAuto_default, + "X": (x) => Math.round(x).toString(16).toUpperCase(), + "x": (x) => Math.round(x).toString(16) + }; + + // node_modules/d3-format/src/identity.js + function identity_default(x) { + return x; + } + + // node_modules/d3-format/src/locale.js + var map3 = Array.prototype.map; + var prefixes = ["y", "z", "a", "f", "p", "n", "\xB5", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y"]; + function locale_default(locale3) { + var group2 = locale3.grouping === void 0 || locale3.thousands === void 0 ? identity_default : formatGroup_default(map3.call(locale3.grouping, Number), locale3.thousands + ""), currencyPrefix = locale3.currency === void 0 ? "" : locale3.currency[0] + "", currencySuffix = locale3.currency === void 0 ? "" : locale3.currency[1] + "", decimal = locale3.decimal === void 0 ? "." : locale3.decimal + "", numerals = locale3.numerals === void 0 ? identity_default : formatNumerals_default(map3.call(locale3.numerals, String)), percent = locale3.percent === void 0 ? "%" : locale3.percent + "", minus = locale3.minus === void 0 ? "\u2212" : locale3.minus + "", nan = locale3.nan === void 0 ? "NaN" : locale3.nan + ""; + function newFormat(specifier, options) { + specifier = formatSpecifier(specifier); + var fill = specifier.fill, align = specifier.align, sign = specifier.sign, symbol = specifier.symbol, zero6 = specifier.zero, width = specifier.width, comma = specifier.comma, precision = specifier.precision, trim = specifier.trim, type = specifier.type; + if (type === "n") comma = true, type = "g"; + else if (!formatTypes_default[type]) precision === void 0 && (precision = 12), trim = true, type = "g"; + if (zero6 || fill === "0" && align === "=") zero6 = true, fill = "0", align = "="; + var prefix = (options && options.prefix !== void 0 ? options.prefix : "") + (symbol === "$" ? currencyPrefix : symbol === "#" && /[boxX]/.test(type) ? "0" + type.toLowerCase() : ""), suffix = (symbol === "$" ? currencySuffix : /[%p]/.test(type) ? percent : "") + (options && options.suffix !== void 0 ? options.suffix : ""); + var formatType = formatTypes_default[type], maybeSuffix = /[defgprs%]/.test(type); + precision = precision === void 0 ? 6 : /[gprs]/.test(type) ? Math.max(1, Math.min(21, precision)) : Math.max(0, Math.min(20, precision)); + function format2(value) { + var valuePrefix = prefix, valueSuffix = suffix, i, n, c2; + if (type === "c") { + valueSuffix = formatType(value) + valueSuffix; + value = ""; + } else { + value = +value; + var valueNegative = value < 0 || 1 / value < 0; + value = isNaN(value) ? nan : formatType(Math.abs(value), precision); + if (trim) value = formatTrim_default(value); + if (valueNegative && +value === 0 && sign !== "+") valueNegative = false; + valuePrefix = (valueNegative ? sign === "(" ? sign : minus : sign === "-" || sign === "(" ? "" : sign) + valuePrefix; + valueSuffix = (type === "s" && !isNaN(value) && prefixExponent !== void 0 ? prefixes[8 + prefixExponent / 3] : "") + valueSuffix + (valueNegative && sign === "(" ? ")" : ""); + if (maybeSuffix) { + i = -1, n = value.length; + while (++i < n) { + if (c2 = value.charCodeAt(i), 48 > c2 || c2 > 57) { + valueSuffix = (c2 === 46 ? decimal + value.slice(i + 1) : value.slice(i)) + valueSuffix; + value = value.slice(0, i); + break; + } + } + } + } + if (comma && !zero6) value = group2(value, Infinity); + var length4 = valuePrefix.length + value.length + valueSuffix.length, padding = length4 < width ? new Array(width - length4 + 1).join(fill) : ""; + if (comma && zero6) value = group2(padding + value, padding.length ? width - valueSuffix.length : Infinity), padding = ""; + switch (align) { + case "<": + value = valuePrefix + value + valueSuffix + padding; + break; + case "=": + value = valuePrefix + padding + value + valueSuffix; + break; + case "^": + value = padding.slice(0, length4 = padding.length >> 1) + valuePrefix + value + valueSuffix + padding.slice(length4); + break; + default: + value = padding + valuePrefix + value + valueSuffix; + break; + } + return numerals(value); + } + format2.toString = function() { + return specifier + ""; + }; + return format2; + } + function formatPrefix2(specifier, value) { + var e = Math.max(-8, Math.min(8, Math.floor(exponent_default(value) / 3))) * 3, k = Math.pow(10, -e), f = newFormat((specifier = formatSpecifier(specifier), specifier.type = "f", specifier), { suffix: prefixes[8 + e / 3] }); + return function(value2) { + return f(k * value2); + }; + } + return { + format: newFormat, + formatPrefix: formatPrefix2 + }; + } + + // node_modules/d3-format/src/defaultLocale.js + var locale; + var format; + var formatPrefix; + defaultLocale({ + thousands: ",", + grouping: [3], + currency: ["$", ""] + }); + function defaultLocale(definition) { + locale = locale_default(definition); + format = locale.format; + formatPrefix = locale.formatPrefix; + return locale; + } + + // node_modules/d3-format/src/precisionFixed.js + function precisionFixed_default(step) { + return Math.max(0, -exponent_default(Math.abs(step))); + } + + // node_modules/d3-format/src/precisionPrefix.js + function precisionPrefix_default(step, value) { + return Math.max(0, Math.max(-8, Math.min(8, Math.floor(exponent_default(value) / 3))) * 3 - exponent_default(Math.abs(step))); + } + + // node_modules/d3-format/src/precisionRound.js + function precisionRound_default(step, max4) { + step = Math.abs(step), max4 = Math.abs(max4) - step; + return Math.max(0, exponent_default(max4) - exponent_default(step)) + 1; + } + + // node_modules/d3-scale/src/tickFormat.js + function tickFormat(start, stop, count2, specifier) { + var step = tickStep(start, stop, count2), precision; + specifier = formatSpecifier(specifier == null ? ",f" : specifier); + switch (specifier.type) { + case "s": { + var value = Math.max(Math.abs(start), Math.abs(stop)); + if (specifier.precision == null && !isNaN(precision = precisionPrefix_default(step, value))) specifier.precision = precision; + return formatPrefix(specifier, value); + } + case "": + case "e": + case "g": + case "p": + case "r": { + if (specifier.precision == null && !isNaN(precision = precisionRound_default(step, Math.max(Math.abs(start), Math.abs(stop))))) specifier.precision = precision - (specifier.type === "e"); + break; + } + case "f": + case "%": { + if (specifier.precision == null && !isNaN(precision = precisionFixed_default(step))) specifier.precision = precision - (specifier.type === "%") * 2; + break; + } + } + return format(specifier); + } + + // node_modules/d3-scale/src/linear.js + function linearish(scale5) { + var domain = scale5.domain; + scale5.ticks = function(count2) { + var d = domain(); + return ticks(d[0], d[d.length - 1], count2 == null ? 10 : count2); + }; + scale5.tickFormat = function(count2, specifier) { + var d = domain(); + return tickFormat(d[0], d[d.length - 1], count2 == null ? 10 : count2, specifier); + }; + scale5.nice = function(count2) { + if (count2 == null) count2 = 10; + var d = domain(); + var i0 = 0; + var i1 = d.length - 1; + var start = d[i0]; + var stop = d[i1]; + var prestep; + var step; + var maxIter = 10; + if (stop < start) { + step = start, start = stop, stop = step; + step = i0, i0 = i1, i1 = step; + } + while (maxIter-- > 0) { + step = tickIncrement(start, stop, count2); + if (step === prestep) { + d[i0] = start; + d[i1] = stop; + return domain(d); + } else if (step > 0) { + start = Math.floor(start / step) * step; + stop = Math.ceil(stop / step) * step; + } else if (step < 0) { + start = Math.ceil(start * step) / step; + stop = Math.floor(stop * step) / step; + } else { + break; + } + prestep = step; + } + return scale5; + }; + return scale5; + } + function linear2() { + var scale5 = continuous(); + scale5.copy = function() { + return copy5(scale5, linear2()); + }; + initRange.apply(scale5, arguments); + return linearish(scale5); + } + + // node_modules/d3-scale/src/pow.js + function transformPow(exponent) { + return function(x) { + return x < 0 ? -Math.pow(-x, exponent) : Math.pow(x, exponent); + }; + } + function transformSqrt(x) { + return x < 0 ? -Math.sqrt(-x) : Math.sqrt(x); + } + function transformSquare(x) { + return x < 0 ? -x * x : x * x; + } + function powish(transform) { + var scale5 = transform(identity3, identity3), exponent = 1; + function rescale() { + return exponent === 1 ? transform(identity3, identity3) : exponent === 0.5 ? transform(transformSqrt, transformSquare) : transform(transformPow(exponent), transformPow(1 / exponent)); + } + scale5.exponent = function(_) { + return arguments.length ? (exponent = +_, rescale()) : exponent; + }; + return linearish(scale5); + } + function pow() { + var scale5 = powish(transformer()); + scale5.copy = function() { + return copy5(scale5, pow()).exponent(scale5.exponent()); + }; + initRange.apply(scale5, arguments); + return scale5; + } + function sqrt() { + return pow.apply(null, arguments).exponent(0.5); + } + + // node_modules/d3-time/src/interval.js + var t02 = /* @__PURE__ */ new Date(); + var t12 = /* @__PURE__ */ new Date(); + function timeInterval(floori, offseti, count2, field) { + function interval(date) { + return floori(date = arguments.length === 0 ? /* @__PURE__ */ new Date() : /* @__PURE__ */ new Date(+date)), date; + } + interval.floor = (date) => { + return floori(date = /* @__PURE__ */ new Date(+date)), date; + }; + interval.ceil = (date) => { + return floori(date = new Date(date - 1)), offseti(date, 1), floori(date), date; + }; + interval.round = (date) => { + const d0 = interval(date), d1 = interval.ceil(date); + return date - d0 < d1 - date ? d0 : d1; + }; + interval.offset = (date, step) => { + return offseti(date = /* @__PURE__ */ new Date(+date), step == null ? 1 : Math.floor(step)), date; + }; + interval.range = (start, stop, step) => { + const range3 = []; + start = interval.ceil(start); + step = step == null ? 1 : Math.floor(step); + if (!(start < stop) || !(step > 0)) return range3; + let previous; + do + range3.push(previous = /* @__PURE__ */ new Date(+start)), offseti(start, step), floori(start); + while (previous < start && start < stop); + return range3; + }; + interval.filter = (test) => { + return timeInterval((date) => { + if (date >= date) while (floori(date), !test(date)) date.setTime(date - 1); + }, (date, step) => { + if (date >= date) { + if (step < 0) while (++step <= 0) { + while (offseti(date, -1), !test(date)) { + } + } + else while (--step >= 0) { + while (offseti(date, 1), !test(date)) { + } + } + } + }); + }; + if (count2) { + interval.count = (start, end) => { + t02.setTime(+start), t12.setTime(+end); + floori(t02), floori(t12); + return Math.floor(count2(t02, t12)); + }; + interval.every = (step) => { + step = Math.floor(step); + return !isFinite(step) || !(step > 0) ? null : !(step > 1) ? interval : interval.filter(field ? (d) => field(d) % step === 0 : (d) => interval.count(0, d) % step === 0); + }; + } + return interval; + } + + // node_modules/d3-time/src/duration.js + var durationSecond = 1e3; + var durationMinute = durationSecond * 60; + var durationHour = durationMinute * 60; + var durationDay = durationHour * 24; + var durationWeek = durationDay * 7; + var durationMonth = durationDay * 30; + var durationYear = durationDay * 365; + + // node_modules/d3-time/src/second.js + var second = timeInterval((date) => { + date.setTime(date - date.getMilliseconds()); + }, (date, step) => { + date.setTime(+date + step * durationSecond); + }, (start, end) => { + return (end - start) / durationSecond; + }, (date) => { + return date.getUTCSeconds(); + }); + var seconds = second.range; + + // node_modules/d3-time/src/minute.js + var timeMinute = timeInterval((date) => { + date.setTime(date - date.getMilliseconds() - date.getSeconds() * durationSecond); + }, (date, step) => { + date.setTime(+date + step * durationMinute); + }, (start, end) => { + return (end - start) / durationMinute; + }, (date) => { + return date.getMinutes(); + }); + var timeMinutes = timeMinute.range; + var utcMinute = timeInterval((date) => { + date.setUTCSeconds(0, 0); + }, (date, step) => { + date.setTime(+date + step * durationMinute); + }, (start, end) => { + return (end - start) / durationMinute; + }, (date) => { + return date.getUTCMinutes(); + }); + var utcMinutes = utcMinute.range; + + // node_modules/d3-time/src/hour.js + var timeHour = timeInterval((date) => { + date.setTime(date - date.getMilliseconds() - date.getSeconds() * durationSecond - date.getMinutes() * durationMinute); + }, (date, step) => { + date.setTime(+date + step * durationHour); + }, (start, end) => { + return (end - start) / durationHour; + }, (date) => { + return date.getHours(); + }); + var timeHours = timeHour.range; + var utcHour = timeInterval((date) => { + date.setUTCMinutes(0, 0, 0); + }, (date, step) => { + date.setTime(+date + step * durationHour); + }, (start, end) => { + return (end - start) / durationHour; + }, (date) => { + return date.getUTCHours(); + }); + var utcHours = utcHour.range; + + // node_modules/d3-time/src/day.js + var timeDay = timeInterval( + (date) => date.setHours(0, 0, 0, 0), + (date, step) => date.setDate(date.getDate() + step), + (start, end) => (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationDay, + (date) => date.getDate() - 1 + ); + var timeDays = timeDay.range; + var utcDay = timeInterval((date) => { + date.setUTCHours(0, 0, 0, 0); + }, (date, step) => { + date.setUTCDate(date.getUTCDate() + step); + }, (start, end) => { + return (end - start) / durationDay; + }, (date) => { + return date.getUTCDate() - 1; + }); + var utcDays = utcDay.range; + var unixDay = timeInterval((date) => { + date.setUTCHours(0, 0, 0, 0); + }, (date, step) => { + date.setUTCDate(date.getUTCDate() + step); + }, (start, end) => { + return (end - start) / durationDay; + }, (date) => { + return Math.floor(date / durationDay); + }); + var unixDays = unixDay.range; + + // node_modules/d3-time/src/week.js + function timeWeekday(i) { + return timeInterval((date) => { + date.setDate(date.getDate() - (date.getDay() + 7 - i) % 7); + date.setHours(0, 0, 0, 0); + }, (date, step) => { + date.setDate(date.getDate() + step * 7); + }, (start, end) => { + return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationWeek; + }); + } + var timeSunday = timeWeekday(0); + var timeMonday = timeWeekday(1); + var timeTuesday = timeWeekday(2); + var timeWednesday = timeWeekday(3); + var timeThursday = timeWeekday(4); + var timeFriday = timeWeekday(5); + var timeSaturday = timeWeekday(6); + var timeSundays = timeSunday.range; + var timeMondays = timeMonday.range; + var timeTuesdays = timeTuesday.range; + var timeWednesdays = timeWednesday.range; + var timeThursdays = timeThursday.range; + var timeFridays = timeFriday.range; + var timeSaturdays = timeSaturday.range; + function utcWeekday(i) { + return timeInterval((date) => { + date.setUTCDate(date.getUTCDate() - (date.getUTCDay() + 7 - i) % 7); + date.setUTCHours(0, 0, 0, 0); + }, (date, step) => { + date.setUTCDate(date.getUTCDate() + step * 7); + }, (start, end) => { + return (end - start) / durationWeek; + }); + } + var utcSunday = utcWeekday(0); + var utcMonday = utcWeekday(1); + var utcTuesday = utcWeekday(2); + var utcWednesday = utcWeekday(3); + var utcThursday = utcWeekday(4); + var utcFriday = utcWeekday(5); + var utcSaturday = utcWeekday(6); + var utcSundays = utcSunday.range; + var utcMondays = utcMonday.range; + var utcTuesdays = utcTuesday.range; + var utcWednesdays = utcWednesday.range; + var utcThursdays = utcThursday.range; + var utcFridays = utcFriday.range; + var utcSaturdays = utcSaturday.range; + + // node_modules/d3-time/src/month.js + var timeMonth = timeInterval((date) => { + date.setDate(1); + date.setHours(0, 0, 0, 0); + }, (date, step) => { + date.setMonth(date.getMonth() + step); + }, (start, end) => { + return end.getMonth() - start.getMonth() + (end.getFullYear() - start.getFullYear()) * 12; + }, (date) => { + return date.getMonth(); + }); + var timeMonths = timeMonth.range; + var utcMonth = timeInterval((date) => { + date.setUTCDate(1); + date.setUTCHours(0, 0, 0, 0); + }, (date, step) => { + date.setUTCMonth(date.getUTCMonth() + step); + }, (start, end) => { + return end.getUTCMonth() - start.getUTCMonth() + (end.getUTCFullYear() - start.getUTCFullYear()) * 12; + }, (date) => { + return date.getUTCMonth(); + }); + var utcMonths = utcMonth.range; + + // node_modules/d3-time/src/year.js + var timeYear = timeInterval((date) => { + date.setMonth(0, 1); + date.setHours(0, 0, 0, 0); + }, (date, step) => { + date.setFullYear(date.getFullYear() + step); + }, (start, end) => { + return end.getFullYear() - start.getFullYear(); + }, (date) => { + return date.getFullYear(); + }); + timeYear.every = (k) => { + return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : timeInterval((date) => { + date.setFullYear(Math.floor(date.getFullYear() / k) * k); + date.setMonth(0, 1); + date.setHours(0, 0, 0, 0); + }, (date, step) => { + date.setFullYear(date.getFullYear() + step * k); + }); + }; + var timeYears = timeYear.range; + var utcYear = timeInterval((date) => { + date.setUTCMonth(0, 1); + date.setUTCHours(0, 0, 0, 0); + }, (date, step) => { + date.setUTCFullYear(date.getUTCFullYear() + step); + }, (start, end) => { + return end.getUTCFullYear() - start.getUTCFullYear(); + }, (date) => { + return date.getUTCFullYear(); + }); + utcYear.every = (k) => { + return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : timeInterval((date) => { + date.setUTCFullYear(Math.floor(date.getUTCFullYear() / k) * k); + date.setUTCMonth(0, 1); + date.setUTCHours(0, 0, 0, 0); + }, (date, step) => { + date.setUTCFullYear(date.getUTCFullYear() + step * k); + }); + }; + var utcYears = utcYear.range; + + // node_modules/d3-time-format/src/locale.js + function localDate(d) { + if (0 <= d.y && d.y < 100) { + var date = new Date(-1, d.m, d.d, d.H, d.M, d.S, d.L); + date.setFullYear(d.y); + return date; + } + return new Date(d.y, d.m, d.d, d.H, d.M, d.S, d.L); + } + function utcDate(d) { + if (0 <= d.y && d.y < 100) { + var date = new Date(Date.UTC(-1, d.m, d.d, d.H, d.M, d.S, d.L)); + date.setUTCFullYear(d.y); + return date; + } + return new Date(Date.UTC(d.y, d.m, d.d, d.H, d.M, d.S, d.L)); + } + function newDate(y, m, d) { + return { y, m, d, H: 0, M: 0, S: 0, L: 0 }; + } + function formatLocale(locale3) { + var locale_dateTime = locale3.dateTime, locale_date = locale3.date, locale_time = locale3.time, locale_periods = locale3.periods, locale_weekdays = locale3.days, locale_shortWeekdays = locale3.shortDays, locale_months = locale3.months, locale_shortMonths = locale3.shortMonths; + var periodRe = formatRe(locale_periods), periodLookup = formatLookup(locale_periods), weekdayRe = formatRe(locale_weekdays), weekdayLookup = formatLookup(locale_weekdays), shortWeekdayRe = formatRe(locale_shortWeekdays), shortWeekdayLookup = formatLookup(locale_shortWeekdays), monthRe = formatRe(locale_months), monthLookup = formatLookup(locale_months), shortMonthRe = formatRe(locale_shortMonths), shortMonthLookup = formatLookup(locale_shortMonths); + var formats = { + "a": formatShortWeekday, + "A": formatWeekday, + "b": formatShortMonth, + "B": formatMonth2, + "c": null, + "d": formatDayOfMonth, + "e": formatDayOfMonth, + "f": formatMicroseconds, + "g": formatYearISO, + "G": formatFullYearISO, + "H": formatHour24, + "I": formatHour12, + "j": formatDayOfYear, + "L": formatMilliseconds, + "m": formatMonthNumber, + "M": formatMinutes, + "p": formatPeriod, + "q": formatQuarter, + "Q": formatUnixTimestamp, + "s": formatUnixTimestampSeconds, + "S": formatSeconds, + "u": formatWeekdayNumberMonday, + "U": formatWeekNumberSunday, + "V": formatWeekNumberISO, + "w": formatWeekdayNumberSunday, + "W": formatWeekNumberMonday, + "x": null, + "X": null, + "y": formatYear, + "Y": formatFullYear, + "Z": formatZone, + "%": formatLiteralPercent + }; + var utcFormats = { + "a": formatUTCShortWeekday, + "A": formatUTCWeekday, + "b": formatUTCShortMonth, + "B": formatUTCMonth, + "c": null, + "d": formatUTCDayOfMonth, + "e": formatUTCDayOfMonth, + "f": formatUTCMicroseconds, + "g": formatUTCYearISO, + "G": formatUTCFullYearISO, + "H": formatUTCHour24, + "I": formatUTCHour12, + "j": formatUTCDayOfYear, + "L": formatUTCMilliseconds, + "m": formatUTCMonthNumber, + "M": formatUTCMinutes, + "p": formatUTCPeriod, + "q": formatUTCQuarter, + "Q": formatUnixTimestamp, + "s": formatUnixTimestampSeconds, + "S": formatUTCSeconds, + "u": formatUTCWeekdayNumberMonday, + "U": formatUTCWeekNumberSunday, + "V": formatUTCWeekNumberISO, + "w": formatUTCWeekdayNumberSunday, + "W": formatUTCWeekNumberMonday, + "x": null, + "X": null, + "y": formatUTCYear, + "Y": formatUTCFullYear, + "Z": formatUTCZone, + "%": formatLiteralPercent + }; + var parses = { + "a": parseShortWeekday, + "A": parseWeekday, + "b": parseShortMonth, + "B": parseMonth, + "c": parseLocaleDateTime, + "d": parseDayOfMonth, + "e": parseDayOfMonth, + "f": parseMicroseconds, + "g": parseYear, + "G": parseFullYear, + "H": parseHour24, + "I": parseHour24, + "j": parseDayOfYear, + "L": parseMilliseconds, + "m": parseMonthNumber, + "M": parseMinutes, + "p": parsePeriod, + "q": parseQuarter, + "Q": parseUnixTimestamp, + "s": parseUnixTimestampSeconds, + "S": parseSeconds, + "u": parseWeekdayNumberMonday, + "U": parseWeekNumberSunday, + "V": parseWeekNumberISO, + "w": parseWeekdayNumberSunday, + "W": parseWeekNumberMonday, + "x": parseLocaleDate, + "X": parseLocaleTime, + "y": parseYear, + "Y": parseFullYear, + "Z": parseZone, + "%": parseLiteralPercent + }; + formats.x = newFormat(locale_date, formats); + formats.X = newFormat(locale_time, formats); + formats.c = newFormat(locale_dateTime, formats); + utcFormats.x = newFormat(locale_date, utcFormats); + utcFormats.X = newFormat(locale_time, utcFormats); + utcFormats.c = newFormat(locale_dateTime, utcFormats); + function newFormat(specifier, formats2) { + return function(date) { + var string = [], i = -1, j = 0, n = specifier.length, c2, pad2, format2; + if (!(date instanceof Date)) date = /* @__PURE__ */ new Date(+date); + while (++i < n) { + if (specifier.charCodeAt(i) === 37) { + string.push(specifier.slice(j, i)); + if ((pad2 = pads[c2 = specifier.charAt(++i)]) != null) c2 = specifier.charAt(++i); + else pad2 = c2 === "e" ? " " : "0"; + if (format2 = formats2[c2]) c2 = format2(date, pad2); + string.push(c2); + j = i + 1; + } + } + string.push(specifier.slice(j, i)); + return string.join(""); + }; + } + function newParse(specifier, Z) { + return function(string) { + var d = newDate(1900, void 0, 1), i = parseSpecifier(d, specifier, string += "", 0), week, day; + if (i != string.length) return null; + if ("Q" in d) return new Date(d.Q); + if ("s" in d) return new Date(d.s * 1e3 + ("L" in d ? d.L : 0)); + if (Z && !("Z" in d)) d.Z = 0; + if ("p" in d) d.H = d.H % 12 + d.p * 12; + if (d.m === void 0) d.m = "q" in d ? d.q : 0; + if ("V" in d) { + if (d.V < 1 || d.V > 53) return null; + if (!("w" in d)) d.w = 1; + if ("Z" in d) { + week = utcDate(newDate(d.y, 0, 1)), day = week.getUTCDay(); + week = day > 4 || day === 0 ? utcMonday.ceil(week) : utcMonday(week); + week = utcDay.offset(week, (d.V - 1) * 7); + d.y = week.getUTCFullYear(); + d.m = week.getUTCMonth(); + d.d = week.getUTCDate() + (d.w + 6) % 7; + } else { + week = localDate(newDate(d.y, 0, 1)), day = week.getDay(); + week = day > 4 || day === 0 ? timeMonday.ceil(week) : timeMonday(week); + week = timeDay.offset(week, (d.V - 1) * 7); + d.y = week.getFullYear(); + d.m = week.getMonth(); + d.d = week.getDate() + (d.w + 6) % 7; + } + } else if ("W" in d || "U" in d) { + if (!("w" in d)) d.w = "u" in d ? d.u % 7 : "W" in d ? 1 : 0; + day = "Z" in d ? utcDate(newDate(d.y, 0, 1)).getUTCDay() : localDate(newDate(d.y, 0, 1)).getDay(); + d.m = 0; + d.d = "W" in d ? (d.w + 6) % 7 + d.W * 7 - (day + 5) % 7 : d.w + d.U * 7 - (day + 6) % 7; + } + if ("Z" in d) { + d.H += d.Z / 100 | 0; + d.M += d.Z % 100; + return utcDate(d); + } + return localDate(d); + }; + } + function parseSpecifier(d, specifier, string, j) { + var i = 0, n = specifier.length, m = string.length, c2, parse2; + while (i < n) { + if (j >= m) return -1; + c2 = specifier.charCodeAt(i++); + if (c2 === 37) { + c2 = specifier.charAt(i++); + parse2 = parses[c2 in pads ? specifier.charAt(i++) : c2]; + if (!parse2 || (j = parse2(d, string, j)) < 0) return -1; + } else if (c2 != string.charCodeAt(j++)) { + return -1; + } + } + return j; + } + function parsePeriod(d, string, i) { + var n = periodRe.exec(string.slice(i)); + return n ? (d.p = periodLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; + } + function parseShortWeekday(d, string, i) { + var n = shortWeekdayRe.exec(string.slice(i)); + return n ? (d.w = shortWeekdayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; + } + function parseWeekday(d, string, i) { + var n = weekdayRe.exec(string.slice(i)); + return n ? (d.w = weekdayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; + } + function parseShortMonth(d, string, i) { + var n = shortMonthRe.exec(string.slice(i)); + return n ? (d.m = shortMonthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; + } + function parseMonth(d, string, i) { + var n = monthRe.exec(string.slice(i)); + return n ? (d.m = monthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; + } + function parseLocaleDateTime(d, string, i) { + return parseSpecifier(d, locale_dateTime, string, i); + } + function parseLocaleDate(d, string, i) { + return parseSpecifier(d, locale_date, string, i); + } + function parseLocaleTime(d, string, i) { + return parseSpecifier(d, locale_time, string, i); + } + function formatShortWeekday(d) { + return locale_shortWeekdays[d.getDay()]; + } + function formatWeekday(d) { + return locale_weekdays[d.getDay()]; + } + function formatShortMonth(d) { + return locale_shortMonths[d.getMonth()]; + } + function formatMonth2(d) { + return locale_months[d.getMonth()]; + } + function formatPeriod(d) { + return locale_periods[+(d.getHours() >= 12)]; + } + function formatQuarter(d) { + return 1 + ~~(d.getMonth() / 3); + } + function formatUTCShortWeekday(d) { + return locale_shortWeekdays[d.getUTCDay()]; + } + function formatUTCWeekday(d) { + return locale_weekdays[d.getUTCDay()]; + } + function formatUTCShortMonth(d) { + return locale_shortMonths[d.getUTCMonth()]; + } + function formatUTCMonth(d) { + return locale_months[d.getUTCMonth()]; + } + function formatUTCPeriod(d) { + return locale_periods[+(d.getUTCHours() >= 12)]; + } + function formatUTCQuarter(d) { + return 1 + ~~(d.getUTCMonth() / 3); + } + return { + format: function(specifier) { + var f = newFormat(specifier += "", formats); + f.toString = function() { + return specifier; + }; + return f; + }, + parse: function(specifier) { + var p = newParse(specifier += "", false); + p.toString = function() { + return specifier; + }; + return p; + }, + utcFormat: function(specifier) { + var f = newFormat(specifier += "", utcFormats); + f.toString = function() { + return specifier; + }; + return f; + }, + utcParse: function(specifier) { + var p = newParse(specifier += "", true); + p.toString = function() { + return specifier; + }; + return p; + } + }; + } + var pads = { "-": "", "_": " ", "0": "0" }; + var numberRe = /^\s*\d+/; + var percentRe = /^%/; + var requoteRe = /[\\^$*+?|[\]().{}]/g; + function pad(value, fill, width) { + var sign = value < 0 ? "-" : "", string = (sign ? -value : value) + "", length4 = string.length; + return sign + (length4 < width ? new Array(width - length4 + 1).join(fill) + string : string); + } + function requote(s) { + return s.replace(requoteRe, "\\$&"); + } + function formatRe(names) { + return new RegExp("^(?:" + names.map(requote).join("|") + ")", "i"); + } + function formatLookup(names) { + return new Map(names.map((name2, i) => [name2.toLowerCase(), i])); + } + function parseWeekdayNumberSunday(d, string, i) { + var n = numberRe.exec(string.slice(i, i + 1)); + return n ? (d.w = +n[0], i + n[0].length) : -1; + } + function parseWeekdayNumberMonday(d, string, i) { + var n = numberRe.exec(string.slice(i, i + 1)); + return n ? (d.u = +n[0], i + n[0].length) : -1; + } + function parseWeekNumberSunday(d, string, i) { + var n = numberRe.exec(string.slice(i, i + 2)); + return n ? (d.U = +n[0], i + n[0].length) : -1; + } + function parseWeekNumberISO(d, string, i) { + var n = numberRe.exec(string.slice(i, i + 2)); + return n ? (d.V = +n[0], i + n[0].length) : -1; + } + function parseWeekNumberMonday(d, string, i) { + var n = numberRe.exec(string.slice(i, i + 2)); + return n ? (d.W = +n[0], i + n[0].length) : -1; + } + function parseFullYear(d, string, i) { + var n = numberRe.exec(string.slice(i, i + 4)); + return n ? (d.y = +n[0], i + n[0].length) : -1; + } + function parseYear(d, string, i) { + var n = numberRe.exec(string.slice(i, i + 2)); + return n ? (d.y = +n[0] + (+n[0] > 68 ? 1900 : 2e3), i + n[0].length) : -1; + } + function parseZone(d, string, i) { + var n = /^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(string.slice(i, i + 6)); + return n ? (d.Z = n[1] ? 0 : -(n[2] + (n[3] || "00")), i + n[0].length) : -1; + } + function parseQuarter(d, string, i) { + var n = numberRe.exec(string.slice(i, i + 1)); + return n ? (d.q = n[0] * 3 - 3, i + n[0].length) : -1; + } + function parseMonthNumber(d, string, i) { + var n = numberRe.exec(string.slice(i, i + 2)); + return n ? (d.m = n[0] - 1, i + n[0].length) : -1; + } + function parseDayOfMonth(d, string, i) { + var n = numberRe.exec(string.slice(i, i + 2)); + return n ? (d.d = +n[0], i + n[0].length) : -1; + } + function parseDayOfYear(d, string, i) { + var n = numberRe.exec(string.slice(i, i + 3)); + return n ? (d.m = 0, d.d = +n[0], i + n[0].length) : -1; + } + function parseHour24(d, string, i) { + var n = numberRe.exec(string.slice(i, i + 2)); + return n ? (d.H = +n[0], i + n[0].length) : -1; + } + function parseMinutes(d, string, i) { + var n = numberRe.exec(string.slice(i, i + 2)); + return n ? (d.M = +n[0], i + n[0].length) : -1; + } + function parseSeconds(d, string, i) { + var n = numberRe.exec(string.slice(i, i + 2)); + return n ? (d.S = +n[0], i + n[0].length) : -1; + } + function parseMilliseconds(d, string, i) { + var n = numberRe.exec(string.slice(i, i + 3)); + return n ? (d.L = +n[0], i + n[0].length) : -1; + } + function parseMicroseconds(d, string, i) { + var n = numberRe.exec(string.slice(i, i + 6)); + return n ? (d.L = Math.floor(n[0] / 1e3), i + n[0].length) : -1; + } + function parseLiteralPercent(d, string, i) { + var n = percentRe.exec(string.slice(i, i + 1)); + return n ? i + n[0].length : -1; + } + function parseUnixTimestamp(d, string, i) { + var n = numberRe.exec(string.slice(i)); + return n ? (d.Q = +n[0], i + n[0].length) : -1; + } + function parseUnixTimestampSeconds(d, string, i) { + var n = numberRe.exec(string.slice(i)); + return n ? (d.s = +n[0], i + n[0].length) : -1; + } + function formatDayOfMonth(d, p) { + return pad(d.getDate(), p, 2); + } + function formatHour24(d, p) { + return pad(d.getHours(), p, 2); + } + function formatHour12(d, p) { + return pad(d.getHours() % 12 || 12, p, 2); + } + function formatDayOfYear(d, p) { + return pad(1 + timeDay.count(timeYear(d), d), p, 3); + } + function formatMilliseconds(d, p) { + return pad(d.getMilliseconds(), p, 3); + } + function formatMicroseconds(d, p) { + return formatMilliseconds(d, p) + "000"; + } + function formatMonthNumber(d, p) { + return pad(d.getMonth() + 1, p, 2); + } + function formatMinutes(d, p) { + return pad(d.getMinutes(), p, 2); + } + function formatSeconds(d, p) { + return pad(d.getSeconds(), p, 2); + } + function formatWeekdayNumberMonday(d) { + var day = d.getDay(); + return day === 0 ? 7 : day; + } + function formatWeekNumberSunday(d, p) { + return pad(timeSunday.count(timeYear(d) - 1, d), p, 2); + } + function dISO(d) { + var day = d.getDay(); + return day >= 4 || day === 0 ? timeThursday(d) : timeThursday.ceil(d); + } + function formatWeekNumberISO(d, p) { + d = dISO(d); + return pad(timeThursday.count(timeYear(d), d) + (timeYear(d).getDay() === 4), p, 2); + } + function formatWeekdayNumberSunday(d) { + return d.getDay(); + } + function formatWeekNumberMonday(d, p) { + return pad(timeMonday.count(timeYear(d) - 1, d), p, 2); + } + function formatYear(d, p) { + return pad(d.getFullYear() % 100, p, 2); + } + function formatYearISO(d, p) { + d = dISO(d); + return pad(d.getFullYear() % 100, p, 2); + } + function formatFullYear(d, p) { + return pad(d.getFullYear() % 1e4, p, 4); + } + function formatFullYearISO(d, p) { + var day = d.getDay(); + d = day >= 4 || day === 0 ? timeThursday(d) : timeThursday.ceil(d); + return pad(d.getFullYear() % 1e4, p, 4); + } + function formatZone(d) { + var z = d.getTimezoneOffset(); + return (z > 0 ? "-" : (z *= -1, "+")) + pad(z / 60 | 0, "0", 2) + pad(z % 60, "0", 2); + } + function formatUTCDayOfMonth(d, p) { + return pad(d.getUTCDate(), p, 2); + } + function formatUTCHour24(d, p) { + return pad(d.getUTCHours(), p, 2); + } + function formatUTCHour12(d, p) { + return pad(d.getUTCHours() % 12 || 12, p, 2); + } + function formatUTCDayOfYear(d, p) { + return pad(1 + utcDay.count(utcYear(d), d), p, 3); + } + function formatUTCMilliseconds(d, p) { + return pad(d.getUTCMilliseconds(), p, 3); + } + function formatUTCMicroseconds(d, p) { + return formatUTCMilliseconds(d, p) + "000"; + } + function formatUTCMonthNumber(d, p) { + return pad(d.getUTCMonth() + 1, p, 2); + } + function formatUTCMinutes(d, p) { + return pad(d.getUTCMinutes(), p, 2); + } + function formatUTCSeconds(d, p) { + return pad(d.getUTCSeconds(), p, 2); + } + function formatUTCWeekdayNumberMonday(d) { + var dow = d.getUTCDay(); + return dow === 0 ? 7 : dow; + } + function formatUTCWeekNumberSunday(d, p) { + return pad(utcSunday.count(utcYear(d) - 1, d), p, 2); + } + function UTCdISO(d) { + var day = d.getUTCDay(); + return day >= 4 || day === 0 ? utcThursday(d) : utcThursday.ceil(d); + } + function formatUTCWeekNumberISO(d, p) { + d = UTCdISO(d); + return pad(utcThursday.count(utcYear(d), d) + (utcYear(d).getUTCDay() === 4), p, 2); + } + function formatUTCWeekdayNumberSunday(d) { + return d.getUTCDay(); + } + function formatUTCWeekNumberMonday(d, p) { + return pad(utcMonday.count(utcYear(d) - 1, d), p, 2); + } + function formatUTCYear(d, p) { + return pad(d.getUTCFullYear() % 100, p, 2); + } + function formatUTCYearISO(d, p) { + d = UTCdISO(d); + return pad(d.getUTCFullYear() % 100, p, 2); + } + function formatUTCFullYear(d, p) { + return pad(d.getUTCFullYear() % 1e4, p, 4); + } + function formatUTCFullYearISO(d, p) { + var day = d.getUTCDay(); + d = day >= 4 || day === 0 ? utcThursday(d) : utcThursday.ceil(d); + return pad(d.getUTCFullYear() % 1e4, p, 4); + } + function formatUTCZone() { + return "+0000"; + } + function formatLiteralPercent() { + return "%"; + } + function formatUnixTimestamp(d) { + return +d; + } + function formatUnixTimestampSeconds(d) { + return Math.floor(+d / 1e3); + } + + // node_modules/d3-time-format/src/defaultLocale.js + var locale2; + var timeFormat; + var timeParse; + var utcFormat; + var utcParse; + defaultLocale2({ + dateTime: "%x, %X", + date: "%-m/%-d/%Y", + time: "%-I:%M:%S %p", + periods: ["AM", "PM"], + days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], + shortDays: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], + months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], + shortMonths: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] + }); + function defaultLocale2(definition) { + locale2 = formatLocale(definition); + timeFormat = locale2.format; + timeParse = locale2.parse; + utcFormat = locale2.utcFormat; + utcParse = locale2.utcParse; + return locale2; + } + + // node_modules/d3-scale/src/sequential.js + function transformer2() { + var x0 = 0, x1 = 1, t03, t13, k10, transform, interpolator = identity3, clamp3 = false, unknown; + function scale5(x) { + return x == null || isNaN(x = +x) ? unknown : interpolator(k10 === 0 ? 0.5 : (x = (transform(x) - t03) * k10, clamp3 ? Math.max(0, Math.min(1, x)) : x)); + } + scale5.domain = function(_) { + return arguments.length ? ([x0, x1] = _, t03 = transform(x0 = +x0), t13 = transform(x1 = +x1), k10 = t03 === t13 ? 0 : 1 / (t13 - t03), scale5) : [x0, x1]; + }; + scale5.clamp = function(_) { + return arguments.length ? (clamp3 = !!_, scale5) : clamp3; + }; + scale5.interpolator = function(_) { + return arguments.length ? (interpolator = _, scale5) : interpolator; + }; + function range3(interpolate) { + return function(_) { + var r0, r1; + return arguments.length ? ([r0, r1] = _, interpolator = interpolate(r0, r1), scale5) : [interpolator(0), interpolator(1)]; + }; + } + scale5.range = range3(value_default); + scale5.rangeRound = range3(round_default); + scale5.unknown = function(_) { + return arguments.length ? (unknown = _, scale5) : unknown; + }; + return function(t) { + transform = t, t03 = t(x0), t13 = t(x1), k10 = t03 === t13 ? 0 : 1 / (t13 - t03); + return scale5; + }; + } + function copy6(source3, target2) { + return target2.domain(source3.domain()).interpolator(source3.interpolator()).clamp(source3.clamp()).unknown(source3.unknown()); + } + function sequential() { + var scale5 = linearish(transformer2()(identity3)); + scale5.copy = function() { + return copy6(scale5, sequential()); + }; + return initInterpolator.apply(scale5, arguments); + } + function sequentialPow() { + var scale5 = powish(transformer2()); + scale5.copy = function() { + return copy6(scale5, sequentialPow()).exponent(scale5.exponent()); + }; + return initInterpolator.apply(scale5, arguments); + } + + // node_modules/@flowmap.gl/data/dist/colors.js + var DEFAULT_OUTLINE_COLOR = "#fff"; + var DEFAULT_DIMMED_OPACITY = 0.4; + var DEFAULT_FLOW_MIN_COLOR = "rgba(240,240,240,0.5)"; + var DEFAULT_FLOW_COLOR_SCHEME = [DEFAULT_FLOW_MIN_COLOR, "#137CBD"]; + var DEFAULT_LOCATION_AREA_COLOR = "rgba(220,220,220,0.5)"; + var DEFAULT_FLOW_COLOR_SCHEME_POSITIVE = [DEFAULT_FLOW_MIN_COLOR, "#f6654e"]; + var DEFAULT_FLOW_COLOR_SCHEME_NEGATIVE = [DEFAULT_FLOW_MIN_COLOR, "#00a9cc"]; + var FALLBACK_COLOR_RGBA = [255, 255, 255, 255]; + function opacityFloatToInteger(opacity) { + return Math.round(opacity * 255); + } + function opacifyHex(hexCode, opacity) { + const c2 = color(hexCode); + if (!c2) { + console.warn("Invalid color: ", hexCode); + return `rgba(255, 255, 255, ${opacity})`; + } + const col = c2.rgb(); + return `rgba(${col.r}, ${col.g}, ${col.b}, ${opacity})`; + } + function colorAsRgba(color2) { + if (Array.isArray(color2)) { + return color2; + } + const col = color(color2); + if (!col) { + console.warn("Invalid color: ", color2); + return FALLBACK_COLOR_RGBA; + } + const rgbColor = col.rgb(); + return [ + Math.floor(rgbColor.r), + Math.floor(rgbColor.g), + Math.floor(rgbColor.b), + opacityFloatToInteger(col.opacity) + ]; + } + function colorAsRgbaOr(color2, defaultColor) { + if (color2) { + return colorAsRgba(color2); + } + if (typeof defaultColor === "string") { + return colorAsRgba(defaultColor); + } + return defaultColor; + } + var asScheme = (scheme19) => scheme19[scheme19.length - 1]; + var ColorScheme; + (function(ColorScheme2) { + ColorScheme2["primary"] = "#162d3c"; + })(ColorScheme || (ColorScheme = {})); + var SCALE_NUM_STEPS = 20; + var getColorSteps = (interpolate) => range(0, SCALE_NUM_STEPS + 1).map((i) => interpolate(i / SCALE_NUM_STEPS)).reverse(); + var FLOW_MIN_COLOR = "rgba(240,240,240,0.5)"; + var GRAYISH = [FLOW_MIN_COLOR, ColorScheme.primary]; + var schemeBluYl = [ + "#f7feae", + "#b7e6a5", + "#7ccba2", + "#46aea0", + "#089099", + "#00718b", + "#045275" + ]; + var schemeEmrld = [ + "#d3f2a3", + "#97e196", + "#6cc08b", + "#4c9b82", + "#217a79", + "#105965", + "#074050" + ]; + var schemeTeal = [ + "#d1eeea", + "#a8dbd9", + "#85c4c9", + "#68abb8", + "#4f90a6", + "#3b738f", + "#2a5674" + ]; + var DEFAULT_COLOR_SCHEME = schemeTeal; + var COLOR_SCHEMES = { + Blues: asScheme(scheme13), + BluGrn: [ + "#c4e6c3", + "#96d2a4", + "#6dbc90", + "#4da284", + "#36877a", + "#266b6e", + "#1d4f60" + ], + BluYl: schemeBluYl, + BrwnYl: [ + "#ede5cf", + "#e0c2a2", + "#d39c83", + "#c1766f", + "#a65461", + "#813753", + "#541f3f" + ], + BuGn: asScheme(scheme), + BuPu: asScheme(scheme2), + Burg: [ + "#ffc6c4", + "#f4a3a8", + "#e38191", + "#cc607d", + "#ad466c", + "#8b3058", + "#672044" + ], + BurgYl: [ + "#fbe6c5", + "#f5ba98", + "#ee8a82", + "#dc7176", + "#c8586c", + "#9c3f5d", + "#70284a" + ], + Cool: getColorSteps(cool), + DarkMint: [ + "#d2fbd4", + "#a5dbc2", + "#7bbcb0", + "#559c9e", + "#3a7c89", + "#235d72", + "#123f5a" + ], + Emrld: schemeEmrld, + GnBu: asScheme(scheme3), + Grayish: GRAYISH, + Greens: asScheme(scheme14), + Greys: asScheme(scheme15), + Inferno: getColorSteps(inferno), + Magenta: [ + "#f3cbd3", + "#eaa9bd", + "#dd88ac", + "#ca699d", + "#b14d8e", + "#91357d", + "#6c2167" + ], + Magma: getColorSteps(magma), + Mint: [ + "#e4f1e1", + "#b4d9cc", + "#89c0b6", + "#63a6a0", + "#448c8a", + "#287274", + "#0d585f" + ], + Oranges: asScheme(scheme18), + OrRd: asScheme(scheme4), + OrYel: [ + "#ecda9a", + "#efc47e", + "#f3ad6a", + "#f7945d", + "#f97b57", + "#f66356", + "#ee4d5a" + ], + Peach: [ + "#fde0c5", + "#facba6", + "#f8b58b", + "#f59e72", + "#f2855d", + "#ef6a4c", + "#eb4a40" + ], + Plasma: getColorSteps(plasma), + PinkYl: [ + "#fef6b5", + "#ffdd9a", + "#ffc285", + "#ffa679", + "#fa8a76", + "#f16d7a", + "#e15383" + ], + PuBu: asScheme(scheme6), + PuBuGn: asScheme(scheme5), + PuRd: asScheme(scheme7), + Purp: [ + "#f3e0f7", + "#e4c7f1", + "#d1afe8", + "#b998dd", + "#9f82ce", + "#826dba", + "#63589f" + ], + Purples: asScheme(scheme16), + PurpOr: [ + "#f9ddda", + "#f2b9c4", + "#e597b9", + "#ce78b3", + "#ad5fad", + "#834ba0", + "#573b88" + ], + RdPu: asScheme(scheme8), + RedOr: [ + "#f6d2a9", + "#f5b78e", + "#f19c7c", + "#ea8171", + "#dd686c", + "#ca5268", + "#b13f64" + ], + Reds: asScheme(scheme17), + Sunset: [ + "#f3e79b", + "#fac484", + "#f8a07e", + "#eb7f86", + "#ce6693", + "#a059a0", + "#5c53a5" + ], + SunsetDark: [ + "#fcde9c", + "#faa476", + "#f0746e", + "#e34f6f", + "#dc3977", + "#b9257a", + "#7c1d6f" + ], + Teal: schemeTeal, + TealGrn: [ + "#b0f2bc", + "#89e8ac", + "#67dba5", + "#4cc8a3", + "#38b2a3", + "#2c98a0", + "#257d98" + ], + Viridis: getColorSteps(viridis_default), + Warm: getColorSteps(warm), + YlGn: asScheme(scheme10), + YlGnBu: asScheme(scheme9), + YlOrBr: asScheme(scheme11), + YlOrRd: asScheme(scheme12) + }; + var COLOR_SCHEME_KEYS = Object.keys(COLOR_SCHEMES); + var complementary = "#f52020"; + var baseDiffColor = "#17a5be"; + var diffColors = { + negative: { + flows: { + scheme: [FLOW_MIN_COLOR, baseDiffColor] + } + }, + positive: { + flows: { + scheme: [FLOW_MIN_COLOR, complementary] + } + }, + locationAreas: { + outline: "rgba(92,112,128,0.5)", + normal: "rgba(220,220,220,0.5)" + }, + outlineColor: "rgb(230,233,237)" + }; + function getFlowmapColors(settings) { + return getColors( + false, + // TODO: diffMode + settings.colorScheme, + settings.darkMode, + settings.fadeEnabled, + settings.fadeOpacityEnabled, + settings.fadeAmount, + isAnimatedFlowLinesMode(settings.flowLinesRenderingMode) + ); + } + function isAnimatedFlowLinesMode(flowLinesRenderingMode) { + return flowLinesRenderingMode === "animated-straight"; + } + function getColors(diffMode, colorScheme, darkMode, fadeEnabled, fadeOpacityEnabled, fadeAmount, animate) { + if (diffMode) { + return diffColors; + } + let scheme19; + if (Array.isArray(colorScheme)) { + scheme19 = colorScheme; + } else { + scheme19 = colorScheme && COLOR_SCHEMES[colorScheme] || DEFAULT_COLOR_SCHEME; + if (darkMode) { + scheme19 = scheme19.slice().reverse(); + } + } + { + const indices = range(0, Math.max(10, scheme19.length)); + const N = indices.length - 1; + const colorScale = sequential(rgbBasis(scheme19)).domain([ + 0, + N + ]); + if (!fadeEnabled || fadeAmount === 0) { + scheme19 = indices.map((c2, i) => colorScale(i)); + } else { + const amount = pow().exponent(1.5).domain([N, 0]).range([0, 2 * fadeAmount / 100]); + scheme19 = indices.map((c2, i) => { + const color2 = colorScale(i); + const a = amount(i); + if (color2 == null || a == null) + return "#000"; + const col = hcl(color2); + col.l = darkMode ? col.l - col.l * a : col.l + (100 - col.l) * a; + col.c = col.c - col.c * (a / 4); + if (fadeOpacityEnabled) { + col.opacity = col.opacity * (1 - a); + } + return col.toString(); + }); + } + } + return { + darkMode, + flows: { + scheme: scheme19 + }, + locationCircles: { + outgoing: darkMode ? "#000" : "#fff" + }, + outlineColor: darkMode ? "#000" : "rgba(255, 255, 255, 0.5)" + }; + } + function interpolateRgbaBasis(colors) { + const spline = basis_default; + const n = colors.length; + let r = new Array(n), g = new Array(n), b = new Array(n), opacity = new Array(n), i, color2; + for (i = 0; i < n; ++i) { + color2 = rgb(colors[i]); + r[i] = color2.r || 0; + g[i] = color2.g || 0; + b[i] = color2.b || 0; + opacity[i] = color2.opacity || 0; + } + r = spline(r); + g = spline(g); + b = spline(b); + opacity = spline(opacity); + return function(t) { + color2.r = r(t); + color2.g = g(t); + color2.b = b(t); + color2.opacity = opacity(t); + return color2 + ""; + }; + } + function createFlowColorScale(domain, scheme19, animate) { + const scale5 = sequentialPow(interpolateRgbaBasis(scheme19)).exponent(animate ? 1 / 2 : 1 / 3).domain(domain); + return (value) => colorAsRgba(scale5(value)); + } + function getFlowColorScale(colors, magnitudeExtent, animate) { + const minMagnitude = magnitudeExtent ? magnitudeExtent[0] : 0; + const maxMagnitude = magnitudeExtent ? magnitudeExtent[1] : 0; + if (isDiffColorsRGBA(colors)) { + const posScale = createFlowColorScale([0, maxMagnitude], colors.positive.flows.scheme, animate); + const negScale = createFlowColorScale([0, minMagnitude], colors.negative.flows.scheme, animate); + return (magnitude) => magnitude >= 0 ? posScale(magnitude) : negScale(magnitude); + } + const scale5 = createFlowColorScale([0, maxMagnitude || 0], colors.flows.scheme, animate); + return (magnitude) => scale5(magnitude); + } + function isDiffColors(colors) { + return colors.positive !== void 0; + } + function isDiffColorsRGBA(colors) { + return colors.positive !== void 0; + } + function getLocationAreaColorsRGBA(colors, darkMode) { + const normalColor = colors && colors.normal || DEFAULT_LOCATION_AREA_COLOR; + const normalColorHcl = hcl(normalColor); + const locationAreasNormal = colorAsRgba(normalColor); + return { + normal: locationAreasNormal, + connected: colorAsRgbaOr(colors && colors.connected, locationAreasNormal), + highlighted: colorAsRgbaOr(colors && colors.highlighted, opacifyHex(normalColorHcl[darkMode ? "brighter" : "darker"](1).toString(), 0.5)), + selected: colorAsRgbaOr(colors && colors.selected, opacifyHex(normalColorHcl[darkMode ? "brighter" : "darker"](2).toString(), 0.8)), + outline: colorAsRgbaOr(colors && colors.outline, colorAsRgba(normalColorHcl[darkMode ? "brighter" : "darker"](4).toString())) + }; + } + function getFlowAndCircleColors(inputColors, defaultFlowColorScheme, darkMode) { + const flowColorScheme = inputColors && inputColors.flows && inputColors.flows.scheme || defaultFlowColorScheme; + const maxFlowColorHcl = hcl(flowColorScheme[flowColorScheme.length - 1]); + const flowColorHighlighted = colorAsRgbaOr(inputColors && inputColors.flows && inputColors.flows.highlighted, colorAsRgba(maxFlowColorHcl[darkMode ? "brighter" : "darker"](0.7).toString())); + const emptyColor = colorAsRgbaOr(inputColors?.locationCircles?.empty, darkMode ? "#000" : "#fff"); + const innerColor = colorAsRgbaOr(inputColors && inputColors.locationCircles && inputColors.locationCircles.inner, maxFlowColorHcl.toString()); + return { + flows: { + scheme: flowColorScheme, + highlighted: flowColorHighlighted + }, + locationCircles: { + inner: innerColor, + outgoing: colorAsRgbaOr(inputColors && inputColors.locationCircles && inputColors.locationCircles.outgoing, darkMode ? "#000" : "#fff"), + incoming: colorAsRgbaOr(inputColors && inputColors.locationCircles && inputColors.locationCircles.incoming, maxFlowColorHcl[darkMode ? "brighter" : "darker"](1.25).toString()), + highlighted: colorAsRgbaOr(inputColors && inputColors.locationCircles && inputColors.locationCircles.highlighted, flowColorHighlighted), + empty: emptyColor, + outlineEmptyMix: inputColors?.locationCircles?.outlineEmptyMix ?? 0.4 + } + }; + } + function getBaseColorsRGBA(colors) { + const darkMode = colors && colors.darkMode ? true : false; + return { + darkMode, + locationAreas: getLocationAreaColorsRGBA(colors && colors.locationAreas, darkMode), + outlineColor: colorAsRgba(colors && colors.outlineColor || DEFAULT_OUTLINE_COLOR), + dimmedOpacity: colors && colors.dimmedOpacity != null ? colors.dimmedOpacity : DEFAULT_DIMMED_OPACITY + }; + } + function getColorsRGBA(colors) { + const baseColorsRGBA = getBaseColorsRGBA(colors); + return { + ...baseColorsRGBA, + ...getFlowAndCircleColors(colors, DEFAULT_FLOW_COLOR_SCHEME, baseColorsRGBA.darkMode) + }; + } + function getDiffColorsRGBA(colors) { + const baseColorsRGBA = getBaseColorsRGBA(colors); + return { + ...baseColorsRGBA, + positive: getFlowAndCircleColors(colors && colors.positive, DEFAULT_FLOW_COLOR_SCHEME_POSITIVE, baseColorsRGBA.darkMode), + negative: getFlowAndCircleColors(colors && colors.negative, DEFAULT_FLOW_COLOR_SCHEME_NEGATIVE, baseColorsRGBA.darkMode) + }; + } + var colors_default2 = getColors; + + // node_modules/kdbush/index.js + var ARRAY_TYPES = [ + Int8Array, + Uint8Array, + Uint8ClampedArray, + Int16Array, + Uint16Array, + Int32Array, + Uint32Array, + Float32Array, + Float64Array + ]; + var VERSION6 = 1; + var HEADER_SIZE = 8; + var STACK = new Uint32Array(96); + var KDBush = class _KDBush { + /** + * Creates an index from raw `ArrayBuffer` data. + * @param {ArrayBufferLike} data + */ + static from(data) { + if (!data || data.byteLength === void 0 || data.buffer) { + throw new Error("Data must be an instance of ArrayBuffer or SharedArrayBuffer."); + } + const [magic, versionAndType] = new Uint8Array(data, 0, 2); + if (magic !== 219) { + throw new Error("Data does not appear to be in a KDBush format."); + } + const version2 = versionAndType >> 4; + if (version2 !== VERSION6) { + throw new Error(`Got v${version2} data when expected v${VERSION6}.`); + } + const ArrayType = ARRAY_TYPES[versionAndType & 15]; + if (!ArrayType) { + throw new Error("Unrecognized array type."); + } + const [nodeSize] = new Uint16Array(data, 2, 1); + const [numItems] = new Uint32Array(data, 4, 1); + return new _KDBush(numItems, nodeSize, ArrayType, void 0, data); + } + /** + * Creates an index that will hold a given number of items. + * @param {number} numItems + * @param {number} [nodeSize=64] Size of the KD-tree node (64 by default). + * @param {TypedArrayConstructor} [ArrayType=Float64Array] The array type used for coordinates storage (`Float64Array` by default). + * @param {ArrayBufferConstructor | SharedArrayBufferConstructor} [ArrayBufferType=ArrayBuffer] The array buffer type used for storage (`ArrayBuffer` by default). + * @param {ArrayBufferLike} [data] (For internal use only) + */ + constructor(numItems, nodeSize = 64, ArrayType = Float64Array, ArrayBufferType = ArrayBuffer, data) { + if (isNaN(numItems) || numItems < 0) throw new Error(`Unexpected numItems value: ${numItems}.`); + this.numItems = +numItems; + this.nodeSize = Math.min(Math.max(+nodeSize, 2), 65535); + this.ArrayType = ArrayType; + this.IndexArrayType = numItems < 65536 ? Uint16Array : Uint32Array; + const arrayTypeIndex = ARRAY_TYPES.indexOf(this.ArrayType); + const coordsByteSize = numItems * 2 * this.ArrayType.BYTES_PER_ELEMENT; + const idsByteSize = numItems * this.IndexArrayType.BYTES_PER_ELEMENT; + const padCoords = (8 - idsByteSize % 8) % 8; + if (arrayTypeIndex < 0) { + throw new Error(`Unexpected typed array class: ${ArrayType}.`); + } + if (data) { + this.data = data; + this.ids = new this.IndexArrayType(data, HEADER_SIZE, numItems); + this.coords = new ArrayType(data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2); + this._pos = numItems * 2; + this._finished = true; + } else { + const data2 = this.data = new ArrayBufferType(HEADER_SIZE + coordsByteSize + idsByteSize + padCoords); + this.ids = new this.IndexArrayType(data2, HEADER_SIZE, numItems); + this.coords = new ArrayType(data2, HEADER_SIZE + idsByteSize + padCoords, numItems * 2); + this._pos = 0; + this._finished = false; + new Uint8Array(data2, 0, 2).set([219, (VERSION6 << 4) + arrayTypeIndex]); + new Uint16Array(data2, 2, 1)[0] = nodeSize; + new Uint32Array(data2, 4, 1)[0] = numItems; + } + } + /** + * Add a point to the index. + * @param {number} x + * @param {number} y + * @returns {number} An incremental index associated with the added item (starting from `0`). + */ + add(x, y) { + const index2 = this._pos >> 1; + this.ids[index2] = index2; + this.coords[this._pos++] = x; + this.coords[this._pos++] = y; + return index2; + } + /** + * Perform indexing of the added points. + */ + finish() { + const numAdded = this._pos >> 1; + if (numAdded !== this.numItems) { + throw new Error(`Added ${numAdded} items when expected ${this.numItems}.`); + } + sort(this.ids, this.coords, this.nodeSize, 0, this.numItems - 1, 0); + this._finished = true; + return this; + } + /** + * Search the index for items within a given bounding box. + * @param {number} minX + * @param {number} minY + * @param {number} maxX + * @param {number} maxY + * @returns {number[]} An array of indices correponding to the found items. + */ + range(minX, minY, maxX, maxY) { + if (!this._finished) throw new Error("Data not yet indexed - call index.finish()."); + const { ids, coords, nodeSize } = this; + STACK[0] = 0; + STACK[1] = ids.length - 1; + STACK[2] = 0; + let sp = 3; + const result = []; + while (sp > 0) { + const axis = STACK[--sp]; + const right = STACK[--sp]; + const left = STACK[--sp]; + if (right - left <= nodeSize) { + for (let i = left; i <= right; i++) { + const x2 = coords[2 * i]; + const y2 = coords[2 * i + 1]; + if (x2 >= minX && x2 <= maxX && y2 >= minY && y2 <= maxY) result.push(ids[i]); + } + continue; + } + const m = left + right >> 1; + const x = coords[2 * m]; + const y = coords[2 * m + 1]; + if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[m]); + if (axis === 0 ? minX <= x : minY <= y) { + STACK[sp++] = left; + STACK[sp++] = m - 1; + STACK[sp++] = 1 - axis; + } + if (axis === 0 ? maxX >= x : maxY >= y) { + STACK[sp++] = m + 1; + STACK[sp++] = right; + STACK[sp++] = 1 - axis; + } + } + return result; + } + /** + * Search the index for items within a given radius. + * @param {number} qx + * @param {number} qy + * @param {number} r Query radius. + * @returns {number[]} An array of indices correponding to the found items. + */ + within(qx, qy, r) { + const result = ( + /** @type {number[]} */ + [] + ); + this.withinInto(qx, qy, r, result); + return result; + } + /** + * Search the index for items within a given radius, writing matching ids into `out` + * via indexed assignment (`out[i] = id`). Accepts any indexed-writable container — + * a typed array sized to the expected upper bound (allocation-free, fast) or a plain + * `Array` (which will grow as needed). Returns the number of matches written. + * @param {number} qx + * @param {number} qy + * @param {number} r Query radius. + * @param {number[] | TypedArray} out Container to write matching ids into. + * @returns {number} The number of matches written to `out`. + */ + withinInto(qx, qy, r, out) { + if (!this._finished) throw new Error("Data not yet indexed - call index.finish()."); + const { ids, coords, nodeSize } = this; + STACK[0] = 0; + STACK[1] = ids.length - 1; + STACK[2] = 0; + let sp = 3; + let count2 = 0; + const r2 = r * r; + while (sp > 0) { + const axis = STACK[--sp]; + const right = STACK[--sp]; + const left = STACK[--sp]; + if (right - left <= nodeSize) { + for (let i = left; i <= right; i++) { + if (sqDist(coords[2 * i], coords[2 * i + 1], qx, qy) <= r2) out[count2++] = ids[i]; + } + continue; + } + const m = left + right >> 1; + const x = coords[2 * m]; + const y = coords[2 * m + 1]; + if (sqDist(x, y, qx, qy) <= r2) out[count2++] = ids[m]; + if (axis === 0 ? qx - r <= x : qy - r <= y) { + STACK[sp++] = left; + STACK[sp++] = m - 1; + STACK[sp++] = 1 - axis; + } + if (axis === 0 ? qx + r >= x : qy + r >= y) { + STACK[sp++] = m + 1; + STACK[sp++] = right; + STACK[sp++] = 1 - axis; + } + } + return count2; + } + }; + function sort(ids, coords, nodeSize, left, right, axis) { + if (right - left <= nodeSize) return; + const m = left + right >> 1; + select(ids, coords, m, left, right, axis); + sort(ids, coords, nodeSize, left, m - 1, 1 - axis); + sort(ids, coords, nodeSize, m + 1, right, 1 - axis); + } + function select(ids, coords, k, left, right, axis) { + while (right > left) { + if (right - left > 600) { + const n = right - left + 1; + const m = k - left + 1; + const z = Math.log(n); + const s = 0.5 * Math.exp(2 * z / 3); + const sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1); + const newLeft = Math.max(left, Math.floor(k - m * s / n + sd)); + const newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd)); + select(ids, coords, k, newLeft, newRight, axis); + } + const t = coords[2 * k + axis]; + let i = left; + let j = right; + swapItem(ids, coords, left, k); + if (coords[2 * right + axis] > t) swapItem(ids, coords, left, right); + while (i < j) { + swapItem(ids, coords, i, j); + i++; + j--; + while (coords[2 * i + axis] < t) i++; + while (coords[2 * j + axis] > t) j--; + } + if (coords[2 * left + axis] === t) swapItem(ids, coords, left, j); + else { + j++; + swapItem(ids, coords, j, right); + } + if (j <= k) left = j + 1; + if (k <= j) right = j - 1; + } + } + function swapItem(ids, coords, i, j) { + swap(ids, i, j); + swap(coords, 2 * i, 2 * j); + swap(coords, 2 * i + 1, 2 * j + 1); + } + function swap(arr, i, j) { + const tmp = arr[i]; + arr[i] = arr[j]; + arr[j] = tmp; + } + function sqDist(ax, ay, bx, by) { + const dx = ax - bx; + const dy = ay - by; + return dx * dx + dy * dy; + } + + // node_modules/reselect/dist/reselect.mjs + var runIdentityFunctionCheck = (resultFunc, inputSelectorsResults, outputSelectorResult) => { + if (inputSelectorsResults.length === 1 && inputSelectorsResults[0] === outputSelectorResult) { + let isInputSameAsOutput = false; + try { + const emptyObject = {}; + if (resultFunc(emptyObject) === emptyObject) isInputSameAsOutput = true; + } catch { + } + if (isInputSameAsOutput) { + let stack = void 0; + try { + throw new Error(); + } catch (e) { + ; + ({ stack } = e); + } + console.warn( + "The result function returned its own inputs without modification. e.g\n`createSelector([state => state.todos], todos => todos)`\nThis could lead to inefficient memoization and unnecessary re-renders.\nEnsure transformation logic is in the result function, and extraction logic is in the input selectors.", + { stack } + ); + } + } + }; + var runInputStabilityCheck = (inputSelectorResultsObject, options, inputSelectorArgs) => { + const { memoize: memoize2, memoizeOptions } = options; + const { inputSelectorResults, inputSelectorResultsCopy } = inputSelectorResultsObject; + const createAnEmptyObject = memoize2(() => ({}), ...memoizeOptions); + const areInputSelectorResultsEqual = createAnEmptyObject.apply(null, inputSelectorResults) === createAnEmptyObject.apply(null, inputSelectorResultsCopy); + if (!areInputSelectorResultsEqual) { + let stack = void 0; + try { + throw new Error(); + } catch (e) { + ; + ({ stack } = e); + } + console.warn( + "An input selector returned a different result when passed same arguments.\nThis means your output selector will likely run more frequently than intended.\nAvoid returning a new reference inside your input selector, e.g.\n`createSelector([state => state.todos.map(todo => todo.id)], todoIds => todoIds.length)`", + { + arguments: inputSelectorArgs, + firstInputs: inputSelectorResults, + secondInputs: inputSelectorResultsCopy, + stack + } + ); + } + }; + var globalDevModeChecks = { + inputStabilityCheck: "once", + identityFunctionCheck: "once" + }; + var NOT_FOUND = /* @__PURE__ */ Symbol("NOT_FOUND"); + function assertIsFunction(func, errorMessage = `expected a function, instead received ${typeof func}`) { + if (typeof func !== "function") { + throw new TypeError(errorMessage); + } + } + function assertIsArrayOfFunctions(array, errorMessage = `expected all items to be functions, instead received the following types: `) { + if (!array.every((item) => typeof item === "function")) { + const itemTypes = array.map( + (item) => typeof item === "function" ? `function ${item.name || "unnamed"}()` : typeof item + ).join(", "); + throw new TypeError(`${errorMessage}[${itemTypes}]`); + } + } + var ensureIsArray = (item) => { + return Array.isArray(item) ? item : [item]; + }; + function getDependencies(createSelectorArgs) { + const dependencies = Array.isArray(createSelectorArgs[0]) ? createSelectorArgs[0] : createSelectorArgs; + assertIsArrayOfFunctions( + dependencies, + `createSelector expects all input-selectors to be functions, but received the following types: ` + ); + return dependencies; + } + function collectInputSelectorResults(dependencies, inputSelectorArgs) { + const inputSelectorResults = []; + const { length: length4 } = dependencies; + for (let i = 0; i < length4; i++) { + inputSelectorResults.push(dependencies[i].apply(null, inputSelectorArgs)); + } + return inputSelectorResults; + } + var getDevModeChecksExecutionInfo = (firstRun, devModeChecks) => { + const { identityFunctionCheck, inputStabilityCheck } = { + ...globalDevModeChecks, + ...devModeChecks + }; + return { + identityFunctionCheck: { + shouldRun: identityFunctionCheck === "always" || identityFunctionCheck === "once" && firstRun, + run: runIdentityFunctionCheck + }, + inputStabilityCheck: { + shouldRun: inputStabilityCheck === "always" || inputStabilityCheck === "once" && firstRun, + run: runInputStabilityCheck + } + }; + }; + function createSingletonCache(equals6) { + let entry; + return { + get(key) { + if (entry && equals6(entry.key, key)) { + return entry.value; + } + return NOT_FOUND; + }, + put(key, value) { + entry = { key, value }; + }, + getEntries() { + return entry ? [entry] : []; + }, + clear() { + entry = void 0; + } + }; + } + function createLruCache(maxSize, equals6) { + let entries = []; + function get(key) { + const cacheIndex = entries.findIndex((entry) => equals6(key, entry.key)); + if (cacheIndex > -1) { + const entry = entries[cacheIndex]; + if (cacheIndex > 0) { + entries.splice(cacheIndex, 1); + entries.unshift(entry); + } + return entry.value; + } + return NOT_FOUND; + } + function put(key, value) { + if (get(key) === NOT_FOUND) { + entries.unshift({ key, value }); + if (entries.length > maxSize) { + entries.pop(); + } + } + } + function getEntries() { + return entries; + } + function clear() { + entries = []; + } + return { get, put, getEntries, clear }; + } + var referenceEqualityCheck = (a, b) => a === b; + function createCacheKeyComparator(equalityCheck) { + return function areArgumentsShallowlyEqual(prev, next) { + if (prev === null || next === null || prev.length !== next.length) { + return false; + } + const { length: length4 } = prev; + for (let i = 0; i < length4; i++) { + if (!equalityCheck(prev[i], next[i])) { + return false; + } + } + return true; + }; + } + function lruMemoize(func, equalityCheckOrOptions) { + const providedOptions = typeof equalityCheckOrOptions === "object" ? equalityCheckOrOptions : { equalityCheck: equalityCheckOrOptions }; + const { + equalityCheck = referenceEqualityCheck, + maxSize = 1, + resultEqualityCheck + } = providedOptions; + const comparator = createCacheKeyComparator(equalityCheck); + let resultsCount = 0; + const cache2 = maxSize <= 1 ? createSingletonCache(comparator) : createLruCache(maxSize, comparator); + function memoized() { + let value = cache2.get(arguments); + if (value === NOT_FOUND) { + value = func.apply(null, arguments); + resultsCount++; + if (resultEqualityCheck) { + const entries = cache2.getEntries(); + const matchingEntry = entries.find( + (entry) => resultEqualityCheck(entry.value, value) + ); + if (matchingEntry) { + value = matchingEntry.value; + resultsCount !== 0 && resultsCount--; + } + } + cache2.put(arguments, value); + } + return value; + } + memoized.clearCache = () => { + cache2.clear(); + memoized.resetResultsCount(); + }; + memoized.resultsCount = () => resultsCount; + memoized.resetResultsCount = () => { + resultsCount = 0; + }; + return memoized; + } + var StrongRef = class { + constructor(value) { + this.value = value; + } + deref() { + return this.value; + } + }; + var getWeakRef = () => typeof WeakRef === "undefined" ? StrongRef : WeakRef; + var Ref = /* @__PURE__ */ getWeakRef(); + var UNTERMINATED = 0; + var TERMINATED = 1; + function createCacheNode() { + return { + s: UNTERMINATED, + v: void 0, + o: null, + p: null + }; + } + function maybeDeref(r) { + if (r instanceof Ref) { + return r.deref(); + } + return r; + } + function weakMapMemoize(func, options = {}) { + let fnNode = createCacheNode(); + const { resultEqualityCheck } = options; + let lastResult; + let resultsCount = 0; + function memoized() { + let cacheNode = fnNode; + const { length: length4 } = arguments; + for (let i = 0, l = length4; i < l; i++) { + const arg = arguments[i]; + if (typeof arg === "function" || typeof arg === "object" && arg !== null) { + let objectCache = cacheNode.o; + if (objectCache === null) { + cacheNode.o = objectCache = /* @__PURE__ */ new WeakMap(); + } + const objectNode = objectCache.get(arg); + if (objectNode === void 0) { + cacheNode = createCacheNode(); + objectCache.set(arg, cacheNode); + } else { + cacheNode = objectNode; + } + } else { + let primitiveCache = cacheNode.p; + if (primitiveCache === null) { + cacheNode.p = primitiveCache = /* @__PURE__ */ new Map(); + } + const primitiveNode = primitiveCache.get(arg); + if (primitiveNode === void 0) { + cacheNode = createCacheNode(); + primitiveCache.set(arg, cacheNode); + } else { + cacheNode = primitiveNode; + } + } + } + const terminatedNode = cacheNode; + let result; + if (cacheNode.s === TERMINATED) { + result = cacheNode.v; + } else { + result = func.apply(null, arguments); + resultsCount++; + if (resultEqualityCheck) { + const lastResultValue = maybeDeref(lastResult); + if (lastResultValue != null && resultEqualityCheck(lastResultValue, result)) { + result = lastResultValue; + resultsCount !== 0 && resultsCount--; + } + const needsWeakRef = typeof result === "object" && result !== null || typeof result === "function"; + lastResult = needsWeakRef ? /* @__PURE__ */ new Ref(result) : result; + } + } + terminatedNode.s = TERMINATED; + terminatedNode.v = result; + return result; + } + memoized.clearCache = () => { + fnNode = createCacheNode(); + memoized.resetResultsCount(); + }; + memoized.resultsCount = () => resultsCount; + memoized.resetResultsCount = () => { + resultsCount = 0; + }; + return memoized; + } + function createSelectorCreator(memoizeOrOptions, ...memoizeOptionsFromArgs) { + const createSelectorCreatorOptions = typeof memoizeOrOptions === "function" ? { + memoize: memoizeOrOptions, + memoizeOptions: memoizeOptionsFromArgs + } : memoizeOrOptions; + const createSelector2 = (...createSelectorArgs) => { + let recomputations = 0; + let dependencyRecomputations = 0; + let lastResult; + let directlyPassedOptions = {}; + let resultFunc = createSelectorArgs.pop(); + if (typeof resultFunc === "object") { + directlyPassedOptions = resultFunc; + resultFunc = createSelectorArgs.pop(); + } + assertIsFunction( + resultFunc, + `createSelector expects an output function after the inputs, but received: [${typeof resultFunc}]` + ); + const combinedOptions = { + ...createSelectorCreatorOptions, + ...directlyPassedOptions + }; + const { + memoize: memoize2, + memoizeOptions = [], + argsMemoize = weakMapMemoize, + argsMemoizeOptions = [] + } = combinedOptions; + const finalMemoizeOptions = ensureIsArray(memoizeOptions); + const finalArgsMemoizeOptions = ensureIsArray(argsMemoizeOptions); + const dependencies = getDependencies(createSelectorArgs); + const memoizedResultFunc = memoize2(function recomputationWrapper() { + recomputations++; + return resultFunc.apply( + null, + arguments + ); + }, ...finalMemoizeOptions); + let firstRun = true; + const selector = argsMemoize(function dependenciesChecker() { + dependencyRecomputations++; + const inputSelectorResults = collectInputSelectorResults( + dependencies, + arguments + ); + lastResult = memoizedResultFunc.apply(null, inputSelectorResults); + if (true) { + const { devModeChecks = {} } = combinedOptions; + const { identityFunctionCheck, inputStabilityCheck } = getDevModeChecksExecutionInfo(firstRun, devModeChecks); + if (identityFunctionCheck.shouldRun) { + identityFunctionCheck.run( + resultFunc, + inputSelectorResults, + lastResult + ); + } + if (inputStabilityCheck.shouldRun) { + const inputSelectorResultsCopy = collectInputSelectorResults( + dependencies, + arguments + ); + inputStabilityCheck.run( + { inputSelectorResults, inputSelectorResultsCopy }, + { memoize: memoize2, memoizeOptions: finalMemoizeOptions }, + arguments + ); + } + if (firstRun) firstRun = false; + } + return lastResult; + }, ...finalArgsMemoizeOptions); + return Object.assign(selector, { + resultFunc, + memoizedResultFunc, + dependencies, + dependencyRecomputations: () => dependencyRecomputations, + resetDependencyRecomputations: () => { + dependencyRecomputations = 0; + }, + lastResult: () => lastResult, + recomputations: () => recomputations, + resetRecomputations: () => { + recomputations = 0; + }, + memoize: memoize2, + argsMemoize + }); + }; + Object.assign(createSelector2, { + withTypes: () => createSelector2 + }); + return createSelector2; + } + var createSelector = /* @__PURE__ */ createSelectorCreator(weakMapMemoize); + + // node_modules/@flowmap.gl/data/dist/FlowmapSelectors.js + var import_seedrandom = __toESM(require_seedrandom2(), 1); + + // node_modules/@flowmap.gl/data/dist/FlowmapAggregateAccessors.js + var FlowmapAggregateAccessors = class { + constructor(accessors) { + this.getLocationId = (location) => isLocationClusterNode(location) ? location.id : this.accessors.getLocationId(location); + this.getLocationName = (location) => { + let name2; + if (isLocationClusterNode(location) && isCluster(location)) { + name2 = location.name; + } else if (this.accessors.getLocationName) { + name2 = this.accessors.getLocationName(location); + } + if (!name2) + name2 = `${this.getLocationId(location)}`; + return name2; + }; + this.getLocationLat = (location) => isLocationClusterNode(location) ? location.lat : this.accessors.getLocationLat(location); + this.getLocationLon = (location) => isLocationClusterNode(location) ? location.lon : this.accessors.getLocationLon(location); + this.getFlowOriginId = (f) => { + return isAggregateFlow(f) ? f.origin : this.accessors.getFlowOriginId(f); + }; + this.getFlowDestId = (f) => { + return isAggregateFlow(f) ? f.dest : this.accessors.getFlowDestId(f); + }; + this.getFlowMagnitude = (f) => { + return isAggregateFlow(f) ? f.count : this.accessors.getFlowMagnitude(f); + }; + this.getFlowTime = (f) => { + const { getFlowTime } = this.accessors; + return getFlowTime ? getFlowTime(f) : void 0; + }; + this.accessors = accessors; + } + setAccessors(accessors) { + this.accessors = accessors; + } + getFlowmapDataAccessors() { + return this.accessors; + } + }; + + // node_modules/@flowmap.gl/data/dist/cluster/ClusterIndex.js + function buildIndex(clusterLevels) { + const nodesByZoom = /* @__PURE__ */ new Map(); + const clustersById = /* @__PURE__ */ new Map(); + const minZoomByLocationId = /* @__PURE__ */ new Map(); + for (const { zoom, nodes } of clusterLevels) { + nodesByZoom.set(zoom, nodes); + for (const node of nodes) { + if (isCluster(node)) { + clustersById.set(node.id, node); + } else { + const { id } = node; + const mz = minZoomByLocationId.get(id); + if (mz == null || mz > zoom) { + minZoomByLocationId.set(id, zoom); + } + } + } + } + const [minZoom, maxZoom] = extent(clusterLevels, (cl) => cl.zoom); + if (minZoom == null || maxZoom == null) { + throw new Error("Could not determine minZoom or maxZoom"); + } + const leavesToClustersByZoom = /* @__PURE__ */ new Map(); + for (const cluster2 of clustersById.values()) { + const { zoom } = cluster2; + let leavesToClusters = leavesToClustersByZoom.get(zoom); + if (!leavesToClusters) { + leavesToClusters = /* @__PURE__ */ new Map(); + leavesToClustersByZoom.set(zoom, leavesToClusters); + } + visitClusterLeaves(cluster2, (leafId) => { + leavesToClusters?.set(leafId, cluster2); + }); + } + function visitClusterLeaves(cluster2, visit) { + for (const childId of cluster2.children) { + const child = clustersById.get(childId); + if (child) { + visitClusterLeaves(child, visit); + } else { + visit(childId); + } + } + } + const expandCluster = (cluster2, targetZoom = maxZoom) => { + const ids = []; + const visit = (c2, expandedIds) => { + if (targetZoom > c2.zoom) { + for (const childId of c2.children) { + const child = clustersById.get(childId); + if (child) { + visit(child, expandedIds); + } else { + expandedIds.push(childId); + } + } + } else { + expandedIds.push(c2.id); + } + }; + visit(cluster2, ids); + return ids; + }; + function findClusterFor(locationId, zoom) { + const leavesToClusters = leavesToClustersByZoom.get(zoom); + if (!leavesToClusters) { + return void 0; + } + const cluster2 = leavesToClusters.get(locationId); + return cluster2 ? cluster2.id : void 0; + } + const availableZoomLevels = clusterLevels.map((cl) => +cl.zoom).sort((a, b) => ascending(a, b)); + return { + availableZoomLevels, + getClusterNodesFor: (zoom) => { + if (zoom === void 0) { + return void 0; + } + return nodesByZoom.get(zoom); + }, + getClusterById: (clusterId) => clustersById.get(clusterId), + getMinZoomForLocation: (locationId) => minZoomByLocationId.get(locationId) || minZoom, + expandCluster, + findClusterFor, + aggregateFlows: (flows, zoom, { getFlowOriginId, getFlowDestId, getFlowMagnitude }, options = {}) => { + if (zoom > maxZoom) { + return flows; + } + const result = []; + const aggFlowsByKey = /* @__PURE__ */ new Map(); + const makeKey = (origin, dest) => `${origin}:${dest}`; + const { flowCountsMapReduce = { + map: getFlowMagnitude, + reduce: (acc, count2) => (acc || 0) + count2 + } } = options; + for (const flow of flows) { + const origin = getFlowOriginId(flow); + const dest = getFlowDestId(flow); + const originCluster = findClusterFor(origin, zoom) || origin; + const destCluster = findClusterFor(dest, zoom) || dest; + const key = makeKey(originCluster, destCluster); + if (originCluster === origin && destCluster === dest) { + result.push(flow); + } else { + let aggregateFlow = aggFlowsByKey.get(key); + if (!aggregateFlow) { + aggregateFlow = { + origin: originCluster, + dest: destCluster, + count: flowCountsMapReduce.map(flow), + aggregate: true + }; + result.push(aggregateFlow); + aggFlowsByKey.set(key, aggregateFlow); + } else { + aggregateFlow.count = flowCountsMapReduce.reduce(aggregateFlow.count, flowCountsMapReduce.map(flow)); + } + } + } + return result; + } + }; + } + function makeLocationWeightGetter(flows, { getFlowOriginId, getFlowDestId, getFlowMagnitude }) { + const locationTotals = { + incoming: /* @__PURE__ */ new Map(), + outgoing: /* @__PURE__ */ new Map() + }; + for (const flow of flows) { + const origin = getFlowOriginId(flow); + const dest = getFlowDestId(flow); + const count2 = getFlowMagnitude(flow); + locationTotals.incoming.set(dest, (locationTotals.incoming.get(dest) || 0) + count2); + locationTotals.outgoing.set(origin, (locationTotals.outgoing.get(origin) || 0) + count2); + } + return (id) => Math.max(Math.abs(locationTotals.incoming.get(id) || 0), Math.abs(locationTotals.outgoing.get(id) || 0)); + } + function findAppropriateZoomLevel(availableZoomLevels, targetZoom) { + if (!availableZoomLevels.length) { + throw new Error("No available zoom levels"); + } + return availableZoomLevels[Math.min(bisectLeft(availableZoomLevels, Math.floor(targetZoom)), availableZoomLevels.length - 1)]; + } + + // node_modules/@flowmap.gl/data/dist/cluster/cluster.js + var defaultOptions2 = { + minZoom: 0, + maxZoom: 16, + radius: 40, + extent: 512, + nodeSize: 64, + makeClusterName: (id, numPoints) => void 0, + makeClusterId: (id) => `{[${id}]}` + }; + function isLeafPoint(p) { + const { index: index2 } = p; + return index2 != null; + } + function isClusterPoint(p) { + const { id } = p; + return id != null; + } + function clusterLocations(locations, locationAccessors, getLocationWeight, options) { + const { getLocationLon, getLocationLat, getLocationId } = locationAccessors; + const opts = { + ...defaultOptions2, + ...options + }; + const { minZoom, maxZoom, nodeSize, makeClusterName, makeClusterId } = opts; + const trees = new Array(maxZoom + 1); + let clusters = new Array(); + let locationsCount = 0; + for (const location of locations) { + const x = getLocationLon(location); + const y = getLocationLat(location); + clusters.push({ + x: lngX(x), + // projected point coordinates + y: latY(y), + weight: getLocationWeight(getLocationId(location)), + zoom: Infinity, + // the last zoom the point was processed at + index: locationsCount, + // index of the source feature in the original input array, + parentId: -1, + // parent cluster id + location + }); + locationsCount++; + } + const makeBush = (points) => { + const bush = new KDBush(points.length, nodeSize, Float32Array); + for (let i = 0; i < points.length; i++) { + bush.add(points[i].x, points[i].y); + } + bush.finish(); + bush.points = points; + return bush; + }; + trees[maxZoom + 1] = makeBush(clusters); + let prevZoom = maxZoom + 1; + for (let z = maxZoom; z >= minZoom; z--) { + const _clusters = cluster(clusters, z, trees[prevZoom], opts); + if (_clusters.length === clusters.length) { + trees[z] = trees[prevZoom]; + trees[prevZoom] = void 0; + prevZoom = z; + clusters = _clusters; + } else { + prevZoom = z; + clusters = _clusters; + trees[z] = makeBush(clusters); + } + } + if (trees.length === 0) { + return []; + } + const numbersOfClusters = trees.map((d) => d?.points.length); + const minClusters = min4(numbersOfClusters.filter((d) => d > 0)); + let maxAvailZoom = findIndexOfMax(numbersOfClusters) ?? numbersOfClusters.length - 1; + const numUniqueLocations = countUniqueLocations(locations, locationAccessors); + if (numUniqueLocations < locationsCount) { + const maxClustersZoom = findLastIndex(numbersOfClusters, (d) => d <= numUniqueLocations); + if (maxClustersZoom >= 0) { + if (maxClustersZoom < maxAvailZoom) { + trees[maxClustersZoom + 1] = trees[maxAvailZoom]; + trees.splice(maxClustersZoom + 2); + } + maxAvailZoom = maxClustersZoom + 1; + } + } + const minAvailZoom = Math.min(maxAvailZoom, minClusters ? numbersOfClusters.lastIndexOf(minClusters) : maxAvailZoom); + const clusterLevels = new Array(); + prevZoom = NaN; + for (let zoom = maxAvailZoom; zoom >= minAvailZoom; zoom--) { + let childrenByParent; + const tree = trees[zoom]; + if (!tree) + continue; + if (trees[prevZoom] && zoom < maxAvailZoom) { + childrenByParent = rollup(trees[prevZoom].points, (points) => points.map((p) => p.id ? makeClusterId(p.id) : getLocationId(p.location)), (point) => point.parentId); + } + const nodes = []; + for (const point of tree.points) { + const { x, y, numPoints, location } = point; + if (isLeafPoint(point)) { + nodes.push({ + id: getLocationId(location), + zoom, + lat: getLocationLat(location), + lon: getLocationLon(location) + }); + } else if (isClusterPoint(point)) { + const { id } = point; + const children = childrenByParent && childrenByParent.get(id); + if (!children) { + console.warn(`Omitting cluster with no children, point:`, point); + continue; + } + const cluster2 = { + id: makeClusterId(id), + name: makeClusterName(id, numPoints), + zoom, + lat: yLat(y), + lon: xLng(x), + children: children ?? [] + }; + nodes.push(cluster2); + } + } + clusterLevels.push({ + zoom, + nodes + }); + prevZoom = zoom; + } + return clusterLevels; + } + function createCluster(x, y, id, numPoints, weight) { + return { + x, + // weighted cluster center + y, + zoom: Infinity, + // the last zoom the cluster was processed at + id, + // encodes index of the first child of the cluster and its zoom level + parentId: -1, + // parent cluster id + numPoints, + weight + }; + } + function cluster(points, zoom, tree, options) { + const clusters = []; + const { radius, extent: extent2 } = options; + const r = radius / (extent2 * Math.pow(2, zoom)); + for (let i = 0; i < points.length; i++) { + const p = points[i]; + if (p.zoom <= zoom) { + continue; + } + p.zoom = zoom; + const neighborIds = tree.within(p.x, p.y, r); + let weight = p.weight || 1; + let numPoints = isClusterPoint(p) ? p.numPoints : 1; + let wx = p.x * weight; + let wy = p.y * weight; + const id = (i << 5) + (zoom + 1); + for (const neighborId of neighborIds) { + const b = tree.points[neighborId]; + if (b.zoom <= zoom) { + continue; + } + b.zoom = zoom; + const weight2 = b.weight || 1; + const numPoints2 = b.numPoints || 1; + wx += b.x * weight2; + wy += b.y * weight2; + weight += weight2; + numPoints += numPoints2; + b.parentId = id; + } + if (numPoints === 1) { + clusters.push(p); + } else { + p.parentId = id; + clusters.push(createCluster(wx / weight, wy / weight, id, numPoints, weight)); + } + } + return clusters; + } + function xLng(x) { + return (x - 0.5) * 360; + } + function yLat(y) { + const y2 = (180 - y * 360) * Math.PI / 180; + return 360 * Math.atan(Math.exp(y2)) / Math.PI - 90; + } + function lngX(lng) { + return lng / 360 + 0.5; + } + function latY(lat) { + const sin3 = Math.sin(lat * Math.PI / 180); + const y = 0.5 - 0.25 * Math.log((1 + sin3) / (1 - sin3)) / Math.PI; + return y < 0 ? 0 : y > 1 ? 1 : y; + } + function countUniqueLocations(locations, locationAccessors) { + const { getLocationLon, getLocationLat } = locationAccessors; + const countByLatLon = /* @__PURE__ */ new Map(); + let uniqueCnt = 0; + for (const loc of locations) { + const lon = getLocationLon(loc); + const lat = getLocationLat(loc); + const key = `${lon},${lat}`; + const prev = countByLatLon.get(key); + if (!prev) { + uniqueCnt++; + } + countByLatLon.set(key, prev ? prev + 1 : 1); + } + return uniqueCnt; + } + function findIndexOfMax(arr) { + let max4 = -Infinity; + let maxIndex = void 0; + for (let i = 0; i < arr.length; i++) { + const value = arr[i]; + if (typeof value === "number") { + if (value > max4) { + max4 = value; + maxIndex = i; + } + } + } + return maxIndex; + } + function findLastIndex(arr, predicate) { + for (let i = arr.length - 1; i >= 0; i--) { + if (predicate(arr[i], i, arr)) { + return i; + } + } + return -1; + } + + // node_modules/@flowmap.gl/data/dist/selector-functions.js + var getViewportBoundingBox = (viewport, maxLocationCircleSize = 0) => { + const pad2 = maxLocationCircleSize; + const bounds = new WebMercatorViewport({ + ...viewport, + width: viewport.width + pad2 * 2, + height: viewport.height + pad2 * 2 + }).getBounds(); + return [bounds[0][0], bounds[0][1], bounds[1][0], bounds[1][1]]; + }; + var getFlowThicknessScale = (magnitudeExtent) => { + if (!magnitudeExtent) + return void 0; + return linear2().range([0.025, 0.5]).domain([ + 0, + // should support diff mode too + Math.max.apply(null, magnitudeExtent.map((x) => Math.abs(x || 0))) + ]); + }; + function addClusterNames(clusterIndex, clusterLevels, locationsById, locationAccessors, getLocationWeight) { + const { getLocationId, getLocationName, getLocationClusterName } = locationAccessors; + const getName = (id) => { + const loc = locationsById.get(id); + if (loc) { + return getLocationName ? getLocationName(loc) : getLocationId(loc) || id; + } + return `"${id}"`; + }; + for (const level of clusterLevels) { + for (const node of level.nodes) { + if (isCluster(node)) { + const leaves = clusterIndex.expandCluster(node); + leaves.sort((a, b) => descending(getLocationWeight(a), getLocationWeight(b))); + if (getLocationClusterName) { + node.name = getLocationClusterName(leaves); + } else { + const topId = leaves[0]; + const otherId = leaves.length === 2 ? leaves[1] : void 0; + node.name = `"${getName(topId)}" and ${otherId ? `"${getName(otherId)}"` : `${leaves.length - 1} others`}`; + } + } else { + node.name = getName(node.id); + } + } + } + } + + // node_modules/@flowmap.gl/data/dist/time.js + var dateParsers = [ + timeParse("%Y-%m-%d"), + timeParse("%Y-%m-%d %H:%M"), + timeParse("%Y-%m-%d %H:%M:%S"), + timeParse("%Y"), + timeParse("%Y-%m") + ]; + var TimeGranularityKey; + (function(TimeGranularityKey2) { + TimeGranularityKey2["SECOND"] = "SECOND"; + TimeGranularityKey2["MINUTE"] = "MINUTE"; + TimeGranularityKey2["HOUR"] = "HOUR"; + TimeGranularityKey2["DAY"] = "DAY"; + TimeGranularityKey2["MONTH"] = "MONTH"; + TimeGranularityKey2["YEAR"] = "YEAR"; + })(TimeGranularityKey || (TimeGranularityKey = {})); + var formatMillisecond = timeFormat(".%L"); + var formatSecond = timeFormat(":%S"); + var formatMinute = timeFormat("%I:%M"); + var formatHour = timeFormat("%I %p"); + var formatDay = timeFormat("%a %d"); + var formatWeek = timeFormat("%b %d"); + var formatMonth = timeFormat("%b"); + var formatYear2 = timeFormat("%Y"); + var TIME_GRANULARITIES = [ + { + order: 0, + key: TimeGranularityKey.SECOND, + interval: second, + format: formatSecond, + formatFull: timeFormat("%Y-%m-%d %H:%M:%S") + }, + { + order: 1, + key: TimeGranularityKey.MINUTE, + interval: timeMinute, + format: formatMinute, + formatFull: timeFormat("%Y-%m-%d %H:%M") + }, + { + order: 2, + key: TimeGranularityKey.HOUR, + interval: timeHour, + // format: (d: Date) => d.toLocaleString(preferredLocale, { hour: 'numeric', minute: '2-digit' }), + format: formatHour, + formatFull: timeFormat("%a %d %b %Y, %I %p") + }, + { + order: 3, + key: TimeGranularityKey.DAY, + interval: timeDay, + format: formatDay, + formatFull: timeFormat("%a %d %b %Y") + }, + { + order: 4, + key: TimeGranularityKey.MONTH, + interval: timeMonth, + format: formatMonth, + formatFull: timeFormat("%b %Y") + }, + { + order: 5, + key: TimeGranularityKey.YEAR, + interval: timeYear, + format: formatYear2, + formatFull: timeFormat("%Y") + } + ]; + function getTimeGranularityByKey(key) { + return TIME_GRANULARITIES.find((s) => s.key === key); + } + function getTimeGranularityByOrder(order) { + return TIME_GRANULARITIES.find((s) => s.order === order); + } + function getTimeGranularityForDate(date) { + let prev = void 0; + for (const current of TIME_GRANULARITIES) { + const { interval } = current; + const floored = interval(date); + if (floored < date) { + if (!prev) + return current; + return prev; + } + prev = current; + } + return TIME_GRANULARITIES[TIME_GRANULARITIES.length - 1]; + } + + // node_modules/@flowmap.gl/data/dist/FlowmapSelectors.js + var MAX_CLUSTER_ZOOM_LEVEL = 20; + var FlowmapSelectors = class { + constructor(accessors) { + this.getFlowsFromProps = (state, props) => props.flows; + this.getLocationsFromProps = (state, props) => props.locations; + this.getClusterLevelsFromProps = (state, props) => { + return props.clusterLevels; + }; + this.getMaxTopFlowsDisplayNum = (state, props) => state.settings.maxTopFlowsDisplayNum; + this.getFlowEndpointsInViewportMode = (state, props) => state.settings.flowEndpointsInViewportMode; + this.getSelectedLocations = (state, props) => state.filter?.selectedLocations; + this.getLocationFilterMode = (state, props) => state.filter?.locationFilterMode; + this.getClusteringEnabled = (state, props) => state.settings.clusteringEnabled; + this.getLocationTotalsEnabled = (state, props) => state.settings.locationTotalsEnabled; + this.getLocationLabelsEnabled = (state, props) => state.settings.locationLabelsEnabled; + this.getZoom = (state, props) => state.viewport.zoom; + this.getViewport = (state, props) => state.viewport; + this.getSelectedTimeRange = (state, props) => state.filter?.selectedTimeRange; + this.getSelectedTimeRanges = (state, props) => state.filter?.selectedTimeRanges; + this.getTemporalScaleDomain = (state, props) => state.settings.temporalScaleDomain; + this.getColorScheme = (state, props) => state.settings.colorScheme; + this.getDarkMode = (state, props) => state.settings.darkMode; + this.getFadeEnabled = (state, props) => state.settings.fadeEnabled; + this.getFadeOpacityEnabled = (state, props) => state.settings.fadeOpacityEnabled; + this.getFadeAmount = (state, props) => state.settings.fadeAmount; + this.getFlowLinesRenderingMode = (state, props) => state.settings.flowLinesRenderingMode; + this.getAnimate = createSelector(this.getFlowLinesRenderingMode, (flowLinesRenderingMode) => flowLinesRenderingMode === "animated-straight"); + this.getInvalidLocationIds = createSelector(this.getLocationsFromProps, (locations) => { + if (!locations) + return void 0; + const invalid = []; + for (const location of locations) { + const id = this.accessors.getLocationId(location); + const lon = this.accessors.getLocationLon(location); + const lat = this.accessors.getLocationLat(location); + if (!(-90 <= lat && lat <= 90) || !(-180 <= lon && lon <= 180)) { + invalid.push(id); + } + } + return invalid.length > 0 ? invalid : void 0; + }); + this.getLocations = createSelector(this.getLocationsFromProps, this.getInvalidLocationIds, (locations, invalidIds) => { + if (!locations) + return void 0; + if (!invalidIds || invalidIds.length === 0) + return locations; + const invalid = new Set(invalidIds); + const filtered = []; + for (const location of locations) { + const id = this.accessors.getLocationId(location); + if (!invalid.has(id)) { + filtered.push(location); + } + } + return filtered; + }); + this.getLocationIds = createSelector(this.getLocations, (locations) => { + if (!locations) + return void 0; + const ids = /* @__PURE__ */ new Set(); + for (const id of locations) { + ids.add(this.accessors.getLocationId(id)); + } + return ids; + }); + this.getSelectedLocationsSet = createSelector(this.getSelectedLocations, (ids) => ids && ids.length > 0 ? new Set(ids) : void 0); + this.getSortedFlowsForKnownLocations = createSelector(this.getFlowsFromProps, this.getLocationIds, (flows, ids) => { + if (!ids || !flows) + return void 0; + const filtered = []; + for (const flow of flows) { + const srcId = this.accessors.getFlowOriginId(flow); + const dstId = this.accessors.getFlowDestId(flow); + if (ids.has(srcId) && ids.has(dstId)) { + filtered.push(flow); + } + } + return filtered.sort((a, b) => descending(Math.abs(this.accessors.getFlowMagnitude(a)), Math.abs(this.accessors.getFlowMagnitude(b)))); + }); + this.getActualTimeExtent = createSelector(this.getSortedFlowsForKnownLocations, (flows) => { + if (!flows) + return void 0; + let start = null; + let end = null; + for (const flow of flows) { + const time = this.accessors.getFlowTime(flow); + if (time) { + if (start == null || start > time) + start = time; + if (end == null || end < time) + end = time; + } + } + if (!start || !end) + return void 0; + return [start, end]; + }); + this.getTimeGranularityKey = createSelector(this.getSortedFlowsForKnownLocations, this.getActualTimeExtent, (flows, timeExtent) => { + if (!flows || !timeExtent) + return void 0; + const minOrder = min4(flows, (d) => { + const t = this.accessors.getFlowTime(d); + return t ? getTimeGranularityForDate(t).order : null; + }); + if (minOrder == null) + return void 0; + const timeGranularity = getTimeGranularityByOrder(minOrder); + return timeGranularity ? timeGranularity.key : void 0; + }); + this.getTimeExtent = createSelector(this.getActualTimeExtent, this.getTimeGranularityKey, (timeExtent, timeGranularityKey) => { + const timeGranularity = timeGranularityKey ? getTimeGranularityByKey(timeGranularityKey) : void 0; + if (!timeExtent || !timeGranularity?.interval) + return void 0; + const { interval } = timeGranularity; + return [timeExtent[0], interval.offset(interval.floor(timeExtent[1]), 1)]; + }); + this.getSortedFlowsForKnownLocationsFilteredByTime = createSelector(this.getSortedFlowsForKnownLocations, this.getTimeExtent, this.getSelectedTimeRange, this.getSelectedTimeRanges, (flows, timeExtent, timeRange, timeRanges) => { + if (!flows) + return void 0; + const selectedRanges = Array.isArray(timeRanges) && timeRanges.length > 0 ? timeRanges : timeRange ? [timeRange] : null; + if (!timeExtent || !selectedRanges || selectedRanges.length === 0) { + return flows; + } + if (selectedRanges.length === 1 && timeExtent[0] === selectedRanges[0][0] && timeExtent[1] === selectedRanges[0][1]) { + return flows; + } + return flows.filter((flow) => { + const time = this.accessors.getFlowTime(flow); + return time && selectedRanges.some((range3) => range3[0] <= time && time < range3[1]); + }); + }); + this.getLocationsHavingFlows = createSelector(this.getSortedFlowsForKnownLocations, this.getLocations, (flows, locations) => { + if (!locations || !flows) + return locations; + const withFlows = /* @__PURE__ */ new Set(); + for (const flow of flows) { + withFlows.add(this.accessors.getFlowOriginId(flow)); + withFlows.add(this.accessors.getFlowDestId(flow)); + } + const filtered = []; + for (const location of locations) { + if (withFlows.has(this.accessors.getLocationId(location))) { + filtered.push(location); + } + } + return filtered; + }); + this.getLocationsById = createSelector(this.getLocationsHavingFlows, (locations) => { + if (!locations) + return void 0; + const locationsById = /* @__PURE__ */ new Map(); + for (const location of locations) { + locationsById.set(this.accessors.getLocationId(location), location); + } + return locationsById; + }); + this.getLocationWeightGetter = createSelector(this.getSortedFlowsForKnownLocations, (flows) => { + if (!flows) + return void 0; + const getLocationWeight = makeLocationWeightGetter(flows, this.accessors.getFlowmapDataAccessors()); + return getLocationWeight; + }); + this.getClusterLevels = createSelector(this.getClusterLevelsFromProps, this.getLocationsHavingFlows, this.getLocationWeightGetter, (clusterLevelsFromProps, locations, getLocationWeight) => { + if (clusterLevelsFromProps) + return clusterLevelsFromProps; + if (!locations || !getLocationWeight) + return void 0; + const clusterLevels = clusterLocations(locations, this.accessors.getFlowmapDataAccessors(), getLocationWeight, { + maxZoom: MAX_CLUSTER_ZOOM_LEVEL + }); + return clusterLevels; + }); + this.getClusterIndex = createSelector(this.getLocationsById, this.getLocationWeightGetter, this.getClusterLevels, (locationsById, getLocationWeight, clusterLevels) => { + if (!locationsById || !getLocationWeight || !clusterLevels) + return void 0; + const clusterIndex = buildIndex(clusterLevels); + addClusterNames(clusterIndex, clusterLevels, locationsById, this.accessors.getFlowmapDataAccessors(), getLocationWeight); + return clusterIndex; + }); + this.getAvailableClusterZoomLevels = createSelector(this.getClusterIndex, this.getSelectedLocations, (clusterIndex, selectedLocations) => { + if (!clusterIndex) { + return void 0; + } + let maxZoom = Number.POSITIVE_INFINITY; + let minZoom = Number.NEGATIVE_INFINITY; + const adjust = (zoneId) => { + const cluster2 = clusterIndex.getClusterById(zoneId); + if (cluster2) { + minZoom = Math.max(minZoom, cluster2.zoom); + maxZoom = Math.min(maxZoom, cluster2.zoom); + } else { + const zoom = clusterIndex.getMinZoomForLocation(zoneId); + minZoom = Math.max(minZoom, zoom); + } + }; + if (selectedLocations) { + for (const id of selectedLocations) { + adjust(id); + } + } + return clusterIndex.availableZoomLevels.filter((level) => minZoom <= level && level <= maxZoom); + }); + this._getClusterZoom = createSelector(this.getClusterIndex, this.getZoom, this.getAvailableClusterZoomLevels, (clusterIndex, mapZoom, availableClusterZoomLevels) => { + if (!clusterIndex) + return void 0; + if (!availableClusterZoomLevels || mapZoom == null) { + return void 0; + } + const clusterZoom = findAppropriateZoomLevel(availableClusterZoomLevels, mapZoom); + return clusterZoom; + }); + this.getClusterZoom = (state, props) => { + const { settings } = state; + if (!settings.clusteringEnabled) + return void 0; + if (settings.clusteringAuto || settings.clusteringLevel == null) { + return this._getClusterZoom(state, props); + } + return settings.clusteringLevel; + }; + this.getLocationsForSearchBox = createSelector(this.getClusteringEnabled, this.getLocationsHavingFlows, this.getSelectedLocations, this.getClusterZoom, this.getClusterIndex, (clusteringEnabled, locations, selectedLocations, clusterZoom, clusterIndex) => { + if (!locations) + return void 0; + let result = Array.from(locations); + if (clusterIndex && selectedLocations) { + const toAppend = []; + for (const id of selectedLocations) { + const cluster2 = clusterIndex.getClusterById(id); + if (cluster2 && !result.find((d) => (isLocationClusterNode(d) ? d.id : this.accessors.getLocationId(d)) === id)) { + toAppend.push(cluster2); + } + } + if (toAppend.length > 0) { + result = result.concat(toAppend); + } + } + return result; + }); + this.getDiffMode = createSelector(this.getFlowsFromProps, (flows) => { + if (flows) { + for (const f of flows) { + if (this.accessors.getFlowMagnitude(f) < 0) { + return true; + } + } + } + return false; + }); + this._getFlowmapColors = createSelector(this.getDiffMode, this.getColorScheme, this.getDarkMode, this.getFadeEnabled, this.getFadeOpacityEnabled, this.getFadeAmount, this.getAnimate, colors_default2); + this.getFlowmapColorsRGBA = createSelector(this._getFlowmapColors, (flowmapColors) => { + return isDiffColors(flowmapColors) ? getDiffColorsRGBA(flowmapColors) : getColorsRGBA(flowmapColors); + }); + this.getUnknownLocations = createSelector(this.getLocationIds, this.getFlowsFromProps, this.getSortedFlowsForKnownLocations, (ids, flows, flowsForKnownLocations) => { + if (!ids || !flows) + return void 0; + if (flowsForKnownLocations) + return void 0; + const missing = /* @__PURE__ */ new Set(); + for (const flow of flows) { + if (!ids.has(this.accessors.getFlowOriginId(flow))) + missing.add(this.accessors.getFlowOriginId(flow)); + if (!ids.has(this.accessors.getFlowDestId(flow))) + missing.add(this.accessors.getFlowDestId(flow)); + } + return missing; + }); + this.getSortedAggregatedFlows = createSelector(this.getClusterIndex, this.getClusteringEnabled, this.getSortedFlowsForKnownLocations, this.getClusterZoom, (clusterTree, isClusteringEnabled, flows, clusterZoom) => { + if (!flows) + return void 0; + let aggregated; + if (isClusteringEnabled && clusterTree && clusterZoom != null) { + aggregated = clusterTree.aggregateFlows(flows, clusterZoom, this.accessors.getFlowmapDataAccessors()); + } else { + aggregated = aggregateFlows(flows, this.accessors.getFlowmapDataAccessors()); + } + aggregated.sort((a, b) => descending(Math.abs(this.accessors.getFlowMagnitude(a)), Math.abs(this.accessors.getFlowMagnitude(b)))); + return aggregated; + }); + this.getSortedAggregatedFilteredFlows = createSelector(this.getClusterIndex, this.getClusteringEnabled, this.getSortedFlowsForKnownLocationsFilteredByTime, this.getClusterZoom, this.getTimeExtent, (clusterTree, isClusteringEnabled, flows, clusterZoom, timeExtent) => { + if (!flows) + return void 0; + let aggregated; + if (isClusteringEnabled && clusterTree && clusterZoom != null) { + aggregated = clusterTree.aggregateFlows( + // TODO: aggregate across time + // timeExtent != null + // ? aggregateFlows(flows) // clusterTree.aggregateFlows won't aggregate unclustered across time + // : flows, + flows, + clusterZoom, + this.accessors.getFlowmapDataAccessors() + ); + } else { + aggregated = aggregateFlows(flows, this.accessors.getFlowmapDataAccessors()); + } + aggregated.sort((a, b) => descending(Math.abs(this.accessors.getFlowMagnitude(a)), Math.abs(this.accessors.getFlowMagnitude(b)))); + return aggregated; + }); + this.getFlowsForScaleDomain = createSelector(this.getTemporalScaleDomain, this.getSortedAggregatedFlows, this.getSortedAggregatedFilteredFlows, (temporalScaleDomain, allFlows, selectedFlows) => { + return temporalScaleDomain === "all" ? allFlows : selectedFlows; + }); + this.getExpandedSelectedLocationsSet = createSelector(this.getClusteringEnabled, this.getSelectedLocationsSet, this.getClusterIndex, (clusteringEnabled, selectedLocations, clusterIndex) => { + if (!selectedLocations || !clusterIndex) { + return selectedLocations; + } + const result = /* @__PURE__ */ new Set(); + for (const locationId of selectedLocations) { + const cluster2 = clusterIndex.getClusterById(locationId); + if (cluster2) { + const expanded = clusterIndex.expandCluster(cluster2); + for (const id of expanded) { + result.add(id); + } + } else { + result.add(locationId); + } + } + return result; + }); + this.getTotalCountsByTime = createSelector(this.getSortedFlowsForKnownLocations, this.getTimeGranularityKey, this.getTimeExtent, this.getExpandedSelectedLocationsSet, this.getLocationFilterMode, (flows, timeGranularityKey, timeExtent, selectedLocationSet, locationFilterMode) => { + const timeGranularity = timeGranularityKey ? getTimeGranularityByKey(timeGranularityKey) : void 0; + if (!flows || !timeGranularity || !timeExtent) + return void 0; + const byTime = flows.reduce((m, flow) => { + if (this.isFlowInSelection(flow, selectedLocationSet, locationFilterMode)) { + const key = timeGranularity.interval(this.accessors.getFlowTime(flow)).getTime(); + m.set(key, (m.get(key) ?? 0) + this.accessors.getFlowMagnitude(flow)); + } + return m; + }, /* @__PURE__ */ new Map()); + return Array.from(byTime.entries()).map(([millis, count2]) => ({ + time: new Date(millis), + count: count2 + })); + }); + this.getMaxLocationCircleSize = createSelector(this.getLocationTotalsEnabled, (locationTotalsEnabled) => locationTotalsEnabled ? 17 : 1); + this.getViewportBoundingBox = createSelector(this.getViewport, this.getMaxLocationCircleSize, getViewportBoundingBox); + this.getLocationsForZoom = createSelector(this.getClusteringEnabled, this.getLocationsHavingFlows, this.getClusterIndex, this.getClusterZoom, (clusteringEnabled, locationsHavingFlows, clusterIndex, clusterZoom) => { + if (clusteringEnabled && clusterIndex) { + return clusterIndex.getClusterNodesFor(clusterZoom); + } else { + return locationsHavingFlows; + } + }); + this.getLocationTotals = createSelector(this.getLocationsForZoom, this.getSortedAggregatedFilteredFlows, this.getSelectedLocationsSet, this.getLocationFilterMode, (locations, flows, selectedLocationsSet, locationFilterMode) => { + if (!flows) + return void 0; + const totals = /* @__PURE__ */ new Map(); + const add6 = (id, d) => { + const rv = totals.get(id) ?? { + incomingCount: 0, + outgoingCount: 0, + internalCount: 0 + }; + if (d.incomingCount != null) + rv.incomingCount += d.incomingCount; + if (d.outgoingCount != null) + rv.outgoingCount += d.outgoingCount; + if (d.internalCount != null) + rv.internalCount += d.internalCount; + return rv; + }; + for (const f of flows) { + if (this.isFlowInSelection(f, selectedLocationsSet, locationFilterMode)) { + const originId = this.accessors.getFlowOriginId(f); + const destId = this.accessors.getFlowDestId(f); + const count2 = this.accessors.getFlowMagnitude(f); + if (originId === destId) { + totals.set(originId, add6(originId, { internalCount: count2 })); + } else { + totals.set(originId, add6(originId, { outgoingCount: count2 })); + totals.set(destId, add6(destId, { incomingCount: count2 })); + } + } + } + return totals; + }); + this.getLocationsTree = createSelector(this.getLocationsForZoom, (locations) => { + if (!locations) { + return void 0; + } + const nodes = Array.isArray(locations) ? locations : Array.from(locations); + const bush = new KDBush(nodes.length, 64, Float32Array); + for (let i = 0; i < nodes.length; i++) { + const node = nodes[i]; + bush.add(lngX2(this.accessors.getLocationLon(node)), latY2(this.accessors.getLocationLat(node))); + } + bush.finish(); + bush.points = nodes; + return bush; + }); + this._getLocationIdsInViewport = createSelector(this.getLocationsTree, this.getViewportBoundingBox, (tree, bbox) => { + const ids = this._getLocationsInBboxIndices(tree, bbox); + if (ids) { + return new Set(ids.map((idx) => this.accessors.getLocationId(tree.points[idx]))); + } + return void 0; + }); + this.getLocationIdsInViewport = createSelectorCreator({ + memoize: lruMemoize, + memoizeOptions: { + equalityCheck: (s1, s2) => { + if (s1 === s2) + return true; + if (s1 == null || s2 == null) + return false; + if (s1.size !== s2.size) + return false; + for (const item of s1) + if (!s2.has(item)) + return false; + return true; + } + } + })(this._getLocationIdsInViewport, (locationIds) => { + if (!locationIds) + return void 0; + return locationIds; + }); + this.getTotalUnfilteredCount = createSelector(this.getSortedFlowsForKnownLocations, (flows) => { + if (!flows) + return void 0; + return flows.reduce((m, flow) => m + this.accessors.getFlowMagnitude(flow), 0); + }); + this.getTotalFilteredCount = createSelector(this.getSortedAggregatedFilteredFlows, this.getSelectedLocationsSet, this.getLocationFilterMode, (flows, selectedLocationSet, locationFilterMode) => { + if (!flows) + return void 0; + const count2 = flows.reduce((m, flow) => { + if (this.isFlowInSelection(flow, selectedLocationSet, locationFilterMode)) { + return m + this.accessors.getFlowMagnitude(flow); + } + return m; + }, 0); + return count2; + }); + this._getLocationTotalsExtent = createSelector(this.getLocationTotals, (locationTotals) => calcLocationTotalsExtent(locationTotals, void 0)); + this._getLocationTotalsForViewportExtent = createSelector(this.getLocationTotals, this.getLocationIdsInViewport, (locationTotals, locationsInViewport) => calcLocationTotalsExtent(locationTotals, locationsInViewport)); + this.getLocationTotalsExtent = (state, props) => { + if (state.settings.adaptiveScalesEnabled) { + return this._getLocationTotalsForViewportExtent(state, props); + } else { + return this._getLocationTotalsExtent(state, props); + } + }; + this.getFlowsForFlowmapLayer = createSelector(this.getSortedAggregatedFilteredFlows, this.getLocationIdsInViewport, this.getSelectedLocationsSet, this.getLocationFilterMode, this.getMaxTopFlowsDisplayNum, this.getFlowEndpointsInViewportMode, (flows, locationIdsInViewport, selectedLocationsSet, locationFilterMode, maxTopFlowsDisplayNum, flowEndpointsInViewportMode) => { + if (!flows || !locationIdsInViewport) + return void 0; + const picked = []; + let pickedCount = 0; + for (const flow of flows) { + const origin = this.accessors.getFlowOriginId(flow); + const dest = this.accessors.getFlowDestId(flow); + const originInView = locationIdsInViewport.has(origin); + const destInView = locationIdsInViewport.has(dest); + const isInViewport = flowEndpointsInViewportMode === "both" ? originInView && destInView : originInView || destInView; + if (isInViewport) { + if (this.isFlowInSelection(flow, selectedLocationsSet, locationFilterMode)) { + if (origin !== dest) { + picked.push(flow); + pickedCount++; + } + } + } + if (pickedCount > maxTopFlowsDisplayNum) + break; + } + return picked.reverse(); + }); + this._getFlowMagnitudeExtent = createSelector(this.getFlowsForScaleDomain, this.getSelectedLocationsSet, this.getLocationFilterMode, (flows, selectedLocationsSet, locationFilterMode) => { + if (!flows) + return void 0; + let rv = void 0; + for (const f of flows) { + if (this.accessors.getFlowOriginId(f) !== this.accessors.getFlowDestId(f) && this.isFlowInSelection(f, selectedLocationsSet, locationFilterMode)) { + const count2 = this.accessors.getFlowMagnitude(f); + if (rv == null) { + rv = [count2, count2]; + } else { + if (count2 < rv[0]) + rv[0] = count2; + if (count2 > rv[1]) + rv[1] = count2; + } + } + } + return rv; + }); + this._getAdaptiveFlowMagnitudeExtent = createSelector(this.getFlowsForScaleDomain, this.getLocationIdsInViewport, this.getSelectedLocationsSet, this.getLocationFilterMode, this.getMaxTopFlowsDisplayNum, this.getFlowEndpointsInViewportMode, (flows, locationIdsInViewport, selectedLocationsSet, locationFilterMode, maxTopFlowsDisplayNum, flowEndpointsInViewportMode) => { + if (!flows || !locationIdsInViewport) + return void 0; + const picked = []; + let pickedCount = 0; + for (const flow of flows) { + const origin = this.accessors.getFlowOriginId(flow); + const dest = this.accessors.getFlowDestId(flow); + const originInView = locationIdsInViewport.has(origin); + const destInView = locationIdsInViewport.has(dest); + const isInViewport = flowEndpointsInViewportMode === "both" ? originInView && destInView : originInView || destInView; + if (isInViewport) { + if (this.isFlowInSelection(flow, selectedLocationsSet, locationFilterMode)) { + if (origin !== dest) { + picked.push(flow); + pickedCount++; + } + } + } + if (pickedCount > maxTopFlowsDisplayNum) + break; + } + const rv = extent(picked, this.accessors.getFlowMagnitude); + return rv[0] !== void 0 && rv[1] !== void 0 ? rv : void 0; + }); + this.getFlowMagnitudeExtent = (state, props) => { + if (state.settings.adaptiveScalesEnabled) { + return this._getAdaptiveFlowMagnitudeExtent(state, props); + } else { + return this._getFlowMagnitudeExtent(state, props); + } + }; + this.getLocationMaxAbsTotalGetter = createSelector(this.getLocationTotals, (locationTotals) => { + return (locationId) => { + const total = locationTotals?.get(locationId); + if (!total) + return void 0; + return Math.max(Math.abs(total.incomingCount + total.internalCount), Math.abs(total.outgoingCount + total.internalCount)); + }; + }); + this.getFlowThicknessScale = createSelector(this.getFlowMagnitudeExtent, getFlowThicknessScale); + this.getCircleSizeScale = createSelector(this.getMaxLocationCircleSize, this.getLocationTotalsEnabled, this.getLocationTotalsExtent, (maxLocationCircleSize, locationTotalsEnabled, locationTotalsExtent) => { + if (!locationTotalsEnabled) { + return () => maxLocationCircleSize; + } + if (!locationTotalsExtent) + return void 0; + return sqrt().range([0, maxLocationCircleSize]).domain([ + 0, + // should support diff mode too + Math.max.apply(null, locationTotalsExtent.map((x) => Math.abs(x || 0))) + ]); + }); + this.getInCircleSizeGetter = createSelector(this.getCircleSizeScale, this.getLocationTotals, (circleSizeScale, locationTotals) => { + return (locationId) => { + const total = locationTotals?.get(locationId); + if (total && circleSizeScale) { + return circleSizeScale(Math.abs(total.incomingCount + total.internalCount)) || 0; + } + return 0; + }; + }); + this.getOutCircleSizeGetter = createSelector(this.getCircleSizeScale, this.getLocationTotals, (circleSizeScale, locationTotals) => { + return (locationId) => { + const total = locationTotals?.get(locationId); + if (total && circleSizeScale) { + return circleSizeScale(Math.abs(total.outgoingCount + total.internalCount)) || 0; + } + return 0; + }; + }); + this.getSortedLocationsForZoom = createSelector(this.getLocationsForZoom, this.getInCircleSizeGetter, this.getOutCircleSizeGetter, (locations, getInCircleSize, getOutCircleSize) => { + if (!locations) + return void 0; + const nextLocations = [...locations]; + return nextLocations.sort((a, b) => { + const idA = this.accessors.getLocationId(a); + const idB = this.accessors.getLocationId(b); + return ascending(Math.max(getInCircleSize(idA), getOutCircleSize(idA)), Math.max(getInCircleSize(idB), getOutCircleSize(idB))); + }); + }); + this.getLocationsForFlowmapLayer = createSelector( + this.getSortedLocationsForZoom, + // this.getLocationIdsInViewport, + (locations) => { + return locations; + } + ); + this.getLocationsForFlowmapLayerById = createSelector(this.getLocationsForFlowmapLayer, (locations) => { + if (!locations) + return void 0; + return locations.reduce((m, d) => (m.set(this.accessors.getLocationId(d), d), m), /* @__PURE__ */ new Map()); + }); + this.getLocationOrClusterByIdGetter = createSelector(this.getClusterIndex, this.getLocationsById, (clusterIndex, locationsById) => { + return (id) => clusterIndex?.getClusterById(id) ?? locationsById?.get(id); + }); + this.getLayersData = createSelector(this.getLocationsForFlowmapLayer, this.getFlowsForFlowmapLayer, this.getFlowmapColorsRGBA, this.getLocationsForFlowmapLayerById, this.getLocationIdsInViewport, this.getInCircleSizeGetter, this.getOutCircleSizeGetter, this.getFlowThicknessScale, this.getFlowMagnitudeExtent, this.getViewport, this.getFlowLinesRenderingMode, this.getLocationLabelsEnabled, (locations, flows, flowmapColors, locationsById, locationIdsInViewport, getInCircleSize, getOutCircleSize, flowThicknessScale, flowMagnitudeExtent, viewport, flowLinesRenderingMode, locationLabelsEnabled) => { + return this._prepareLayersData(locations, flows, flowmapColors, locationsById, locationIdsInViewport, getInCircleSize, getOutCircleSize, flowThicknessScale, flowMagnitudeExtent, viewport, flowLinesRenderingMode, locationLabelsEnabled); + }); + this.accessors = new FlowmapAggregateAccessors(accessors); + this.setAccessors(accessors); + } + setAccessors(accessors) { + this.accessors = new FlowmapAggregateAccessors(accessors); + } + getAggregateAccessors() { + return this.accessors; + } + prepareLayersData(state, props) { + const locations = this.getLocationsForFlowmapLayer(state, props) || []; + const flows = this.getFlowsForFlowmapLayer(state, props) || []; + const flowmapColors = this.getFlowmapColorsRGBA(state, props); + const locationsById = this.getLocationsForFlowmapLayerById(state, props); + const locationIdsInViewport = this.getLocationIdsInViewport(state, props); + const getInCircleSize = this.getInCircleSizeGetter(state, props); + const getOutCircleSize = this.getOutCircleSizeGetter(state, props); + const flowThicknessScale = this.getFlowThicknessScale(state, props); + const flowMagnitudeExtent = this.getFlowMagnitudeExtent(state, props); + const locationLabelsEnabled = this.getLocationLabelsEnabled(state, props); + const viewport = this.getViewport(state, props); + return this._prepareLayersData(locations, flows, flowmapColors, locationsById, locationIdsInViewport, getInCircleSize, getOutCircleSize, flowThicknessScale, flowMagnitudeExtent, viewport, state.settings.flowLinesRenderingMode, locationLabelsEnabled); + } + _prepareLayersData(locations, flows, flowmapColors, locationsById, locationIdsInViewport, getInCircleSize, getOutCircleSize, flowThicknessScale, flowMagnitudeExtent, viewport, flowLinesRenderingMode, locationLabelsEnabled) { + if (!locations) + locations = []; + if (!flows) + flows = []; + const { getFlowOriginId, getFlowDestId, getFlowMagnitude, getLocationId, getLocationLon, getLocationLat, getLocationName } = this.accessors; + const flowColorScale = getFlowColorScale(flowmapColors, flowMagnitudeExtent, flowLinesRenderingMode === "animated-straight"); + const circlePositions = Float64Array.from((function* () { + for (const location of locations) { + yield getLocationLon(location); + yield getLocationLat(location); + yield 0; + } + })()); + const circleColor = isDiffColorsRGBA(flowmapColors) ? flowmapColors.positive.locationCircles.inner : flowmapColors.locationCircles.inner; + const circleColors = Uint8Array.from((function* () { + for (const location of locations) { + yield* circleColor; + } + })()); + const inCircleRadii = Float32Array.from((function* () { + for (const location of locations) { + const id = getLocationId(location); + yield locationIdsInViewport?.has(id) ? getInCircleSize(id) : 1; + } + })()); + const outCircleRadii = Float32Array.from((function* () { + for (const location of locations) { + const id = getLocationId(location); + yield locationIdsInViewport?.has(id) ? getOutCircleSize(id) : 1; + } + })()); + const sourcePositions = Float64Array.from((function* () { + for (const flow of flows) { + const loc = locationsById?.get(getFlowOriginId(flow)); + yield loc ? getLocationLon(loc) : 0; + yield loc ? getLocationLat(loc) : 0; + yield 0; + } + })()); + const targetPositions = Float64Array.from((function* () { + for (const flow of flows) { + const loc = locationsById?.get(getFlowDestId(flow)); + yield loc ? getLocationLon(loc) : 0; + yield loc ? getLocationLat(loc) : 0; + yield 0; + } + })()); + const thicknesses = Float32Array.from((function* () { + for (const flow of flows) { + yield flowThicknessScale ? flowThicknessScale(getFlowMagnitude(flow)) || 0 : 0; + } + })()); + const endpointOffsets = Float32Array.from((function* () { + for (const flow of flows) { + const originId = getFlowOriginId(flow); + const destId = getFlowDestId(flow); + yield Math.max(getInCircleSize(originId), getOutCircleSize(originId)); + yield Math.max(getInCircleSize(destId), getOutCircleSize(destId)); + } + })()); + const flowLineColors = Uint8Array.from((function* () { + for (const flow of flows) { + yield* flowColorScale(getFlowMagnitude(flow)); + } + })()); + const staggeringValues = flowLinesRenderingMode === "animated-straight" ? Float32Array.from((function* () { + for (const f of flows) { + yield new import_seedrandom.alea(`${getFlowOriginId(f)}-${getFlowDestId(f)}`)(); + } + })()) : void 0; + const curveOffsets = flowLinesRenderingMode === "curved" ? calculateCurveOffsets(flows, viewport, locationsById, getFlowOriginId, getFlowDestId, getLocationLon, getLocationLat) : void 0; + return { + circleAttributes: { + length: locations.length, + attributes: { + getPosition: { value: circlePositions, size: 3 }, + getColor: { value: circleColors, size: 4 }, + getInRadius: { value: inCircleRadii, size: 1 }, + getOutRadius: { value: outCircleRadii, size: 1 } + } + }, + lineAttributes: { + length: flows.length, + attributes: { + getSourcePosition: { value: sourcePositions, size: 3 }, + getTargetPosition: { value: targetPositions, size: 3 }, + getThickness: { value: thicknesses, size: 1 }, + getColor: { value: flowLineColors, size: 4 }, + getEndpointOffsets: { value: endpointOffsets, size: 2 }, + ...staggeringValues ? { getStaggering: { value: staggeringValues, size: 1 } } : {}, + ...curveOffsets ? { getCurveOffset: { value: curveOffsets, size: 1 } } : {} + } + }, + ...locationLabelsEnabled ? { locationLabels: locations.map(getLocationName) } : void 0 + }; + } + getLocationsInBbox(tree, bbox) { + if (!tree) + return void 0; + return this._getLocationsInBboxIndices(tree, bbox).map((idx) => tree.points[idx]); + } + _getLocationsInBboxIndices(tree, bbox) { + if (!tree) + return void 0; + const [lon1, lat1, lon2, lat2] = bbox; + const [x1, y1, x2, y2] = [lngX2(lon1), latY2(lat1), lngX2(lon2), latY2(lat2)]; + return tree.range(Math.min(x1, x2), Math.min(y1, y2), Math.max(x1, x2), Math.max(y1, y2)); + } + isFlowInSelection(flow, selectedLocationsSet, locationFilterMode) { + const origin = this.accessors.getFlowOriginId(flow); + const dest = this.accessors.getFlowDestId(flow); + if (selectedLocationsSet) { + switch (locationFilterMode) { + case LocationFilterMode.ALL: + return selectedLocationsSet.has(origin) || selectedLocationsSet.has(dest); + case LocationFilterMode.BETWEEN: + return selectedLocationsSet.has(origin) && selectedLocationsSet.has(dest); + case LocationFilterMode.INCOMING: + return selectedLocationsSet.has(dest); + case LocationFilterMode.OUTGOING: + return selectedLocationsSet.has(origin); + } + } + return true; + } + }; + function calcLocationTotalsExtent(locationTotals, locationIdsInViewport) { + if (!locationTotals) + return void 0; + let rv = void 0; + for (const [id, { incomingCount, outgoingCount, internalCount }] of locationTotals.entries()) { + if (locationIdsInViewport == null || locationIdsInViewport.has(id)) { + const lo = Math.min(incomingCount + internalCount, outgoingCount + internalCount, internalCount); + const hi = Math.max(incomingCount + internalCount, outgoingCount + internalCount, internalCount); + if (!rv) { + rv = [lo, hi]; + } else { + if (lo < rv[0]) + rv[0] = lo; + if (hi > rv[1]) + rv[1] = hi; + } + } + } + return rv; + } + function lngX2(lng) { + return lng / 360 + 0.5; + } + function latY2(lat) { + const sin3 = Math.sin(lat * Math.PI / 180); + const y = 0.5 - 0.25 * Math.log((1 + sin3) / (1 - sin3)) / Math.PI; + return y < 0 ? 0 : y > 1 ? 1 : y; + } + function aggregateFlows(flows, flowAccessors) { + const byOriginDest = rollup(flows, (ff) => { + const origin = flowAccessors.getFlowOriginId(ff[0]); + const dest = flowAccessors.getFlowDestId(ff[0]); + const rv2 = { + aggregate: true, + origin, + dest, + count: ff.reduce((m, f) => { + const count2 = flowAccessors.getFlowMagnitude(f); + if (count2) { + if (!isNaN(count2) && isFinite(count2)) + return m + count2; + } + return m; + }, 0) + // time: undefined, + }; + return rv2; + }, flowAccessors.getFlowOriginId, flowAccessors.getFlowDestId); + const rv = []; + for (const values of byOriginDest.values()) { + for (const value of values.values()) { + rv.push(value); + } + } + return rv; + } + function getOuterCircleRadiusByIndex(circleAttributes, index2) { + const { getInRadius, getOutRadius } = circleAttributes.attributes; + return Math.max(getInRadius.value[index2], getOutRadius.value[index2]); + } + function getLocationCoordsByIndex(circleAttributes, index2) { + const { getPosition: getPosition2 } = circleAttributes.attributes; + const offset = index2 * getPosition2.size; + return [getPosition2.value[offset], getPosition2.value[offset + 1]]; + } + function getFlowLineAttributesByIndex(lineAttributes, index2) { + const { getColor: getColor2, getCurveOffset, getEndpointOffsets, getSourcePosition, getTargetPosition, getThickness, getStaggering } = lineAttributes.attributes; + return { + length: 1, + attributes: { + getColor: { + value: getColor2.value.subarray(index2 * 4, (index2 + 1) * 4), + size: 4 + }, + getEndpointOffsets: { + value: getEndpointOffsets.value.subarray(index2 * 2, (index2 + 1) * 2), + size: 2 + }, + getSourcePosition: { + value: getSourcePosition.value.subarray(index2 * getSourcePosition.size, (index2 + 1) * getSourcePosition.size), + size: getSourcePosition.size + }, + getTargetPosition: { + value: getTargetPosition.value.subarray(index2 * getTargetPosition.size, (index2 + 1) * getTargetPosition.size), + size: getTargetPosition.size + }, + getThickness: { + value: getThickness.value.subarray(index2, index2 + 1), + size: 1 + }, + ...getStaggering ? { + getStaggering: { + value: getStaggering.value.subarray(index2, index2 + 1), + size: 1 + } + } : void 0, + ...getCurveOffset ? { + getCurveOffset: { + value: getCurveOffset.value.subarray(index2, index2 + 1), + size: 1 + } + } : void 0 + } + }; + } + function calculateCurveOffsets(flows, viewport, locationsById, getFlowOriginId, getFlowDestId, getLocationLon, getLocationLat) { + const curveOffsets = new Float32Array(flows.length); + const corridorBuckets = /* @__PURE__ */ new Map(); + const worldScale = 512 * Math.pow(2, viewport.zoom ?? 0); + flows.forEach((flow, index2) => { + const originId = getFlowOriginId(flow); + const destId = getFlowDestId(flow); + const origin = locationsById?.get(originId); + const dest = locationsById?.get(destId); + if (!origin || !dest) { + return; + } + const sourceLon = getLocationLon(origin); + const sourceLat = getLocationLat(origin); + const targetLon = getLocationLon(dest); + const targetLat = getLocationLat(dest); + const sx = lngX2(sourceLon) * worldScale; + const sy = latY2(sourceLat) * worldScale; + const tx = lngX2(targetLon) * worldScale; + const ty = latY2(targetLat) * worldScale; + let corridorSourceX = sx; + let corridorSourceY = sy; + let corridorTargetX = tx; + let corridorTargetY = ty; + if (corridorSourceX > corridorTargetX || corridorSourceX === corridorTargetX && corridorSourceY > corridorTargetY) { + [corridorSourceX, corridorTargetX] = [corridorTargetX, corridorSourceX]; + [corridorSourceY, corridorTargetY] = [corridorTargetY, corridorSourceY]; + } + const dx = corridorTargetX - corridorSourceX; + const dy = corridorTargetY - corridorSourceY; + const chordLengthPx = Math.hypot(dx, dy); + if (!isFinite(chordLengthPx) || chordLengthPx < 1) { + return; + } + const angle4 = (Math.atan2(dy, dx) % Math.PI + Math.PI) % Math.PI; + const signedDistance = (corridorSourceX * corridorTargetY - corridorSourceY * corridorTargetX) / chordLengthPx; + const key = [ + Math.round(angle4 / (6 * Math.PI / 180)), + Math.round(signedDistance / 18), + Math.round(chordLengthPx / 24) + ].join(":"); + const bucket = corridorBuckets.get(key) ?? []; + bucket.push({ index: index2, originId, destId, sx, sy, tx, ty, chordLengthPx }); + corridorBuckets.set(key, bucket); + }); + corridorBuckets.forEach((bucket) => { + bucket.sort((a, b) => { + const originCompare = compareIds(a.originId, b.originId); + if (originCompare !== 0) + return originCompare; + const destCompare = compareIds(a.destId, b.destId); + if (destCompare !== 0) + return destCompare; + return a.index - b.index; + }).forEach((entry, bucketIndex) => { + const maxOffsetPx = Math.min(72, entry.chordLengthPx * 0.35); + curveOffsets[entry.index] = Math.min(maxOffsetPx, (bucketIndex + 1) * 18); + }); + }); + return curveOffsets; + } + function compareIds(a, b) { + if (typeof a === "number" && typeof b === "number") { + return a - b; + } + const aString = String(a); + const bString = String(b); + if (aString < bString) + return -1; + if (aString > bString) + return 1; + return 0; + } + + // node_modules/d3-geo/src/math.js + var epsilon = 1e-6; + var pi = Math.PI; + var halfPi = pi / 2; + var quarterPi = pi / 4; + var tau = pi * 2; + var degrees3 = 180 / pi; + var radians3 = pi / 180; + var abs = Math.abs; + var atan2 = Math.atan2; + var cos2 = Math.cos; + var sin2 = Math.sin; + var sqrt2 = Math.sqrt; + function asin2(x) { + return x > 1 ? halfPi : x < -1 ? -halfPi : Math.asin(x); + } + + // node_modules/d3-geo/src/noop.js + function noop5() { + } + + // node_modules/d3-geo/src/stream.js + function streamGeometry(geometry, stream) { + if (geometry && streamGeometryType.hasOwnProperty(geometry.type)) { + streamGeometryType[geometry.type](geometry, stream); + } + } + var streamObjectType = { + Feature: function(object, stream) { + streamGeometry(object.geometry, stream); + }, + FeatureCollection: function(object, stream) { + var features = object.features, i = -1, n = features.length; + while (++i < n) streamGeometry(features[i].geometry, stream); + } + }; + var streamGeometryType = { + Sphere: function(object, stream) { + stream.sphere(); + }, + Point: function(object, stream) { + object = object.coordinates; + stream.point(object[0], object[1], object[2]); + }, + MultiPoint: function(object, stream) { + var coordinates = object.coordinates, i = -1, n = coordinates.length; + while (++i < n) object = coordinates[i], stream.point(object[0], object[1], object[2]); + }, + LineString: function(object, stream) { + streamLine(object.coordinates, stream, 0); + }, + MultiLineString: function(object, stream) { + var coordinates = object.coordinates, i = -1, n = coordinates.length; + while (++i < n) streamLine(coordinates[i], stream, 0); + }, + Polygon: function(object, stream) { + streamPolygon(object.coordinates, stream); + }, + MultiPolygon: function(object, stream) { + var coordinates = object.coordinates, i = -1, n = coordinates.length; + while (++i < n) streamPolygon(coordinates[i], stream); + }, + GeometryCollection: function(object, stream) { + var geometries = object.geometries, i = -1, n = geometries.length; + while (++i < n) streamGeometry(geometries[i], stream); + } + }; + function streamLine(coordinates, stream, closed) { + var i = -1, n = coordinates.length - closed, coordinate; + stream.lineStart(); + while (++i < n) coordinate = coordinates[i], stream.point(coordinate[0], coordinate[1], coordinate[2]); + stream.lineEnd(); + } + function streamPolygon(coordinates, stream) { + var i = -1, n = coordinates.length; + stream.polygonStart(); + while (++i < n) streamLine(coordinates[i], stream, 1); + stream.polygonEnd(); + } + function stream_default(object, stream) { + if (object && streamObjectType.hasOwnProperty(object.type)) { + streamObjectType[object.type](object, stream); + } else { + streamGeometry(object, stream); + } + } + + // node_modules/d3-geo/src/area.js + var areaRingSum = new Adder(); + var areaSum = new Adder(); + var lambda00; + var phi00; + var lambda0; + var cosPhi0; + var sinPhi0; + var areaStream = { + point: noop5, + lineStart: noop5, + lineEnd: noop5, + polygonStart: function() { + areaRingSum = new Adder(); + areaStream.lineStart = areaRingStart; + areaStream.lineEnd = areaRingEnd; + }, + polygonEnd: function() { + var areaRing = +areaRingSum; + areaSum.add(areaRing < 0 ? tau + areaRing : areaRing); + this.lineStart = this.lineEnd = this.point = noop5; + }, + sphere: function() { + areaSum.add(tau); + } + }; + function areaRingStart() { + areaStream.point = areaPointFirst; + } + function areaRingEnd() { + areaPoint(lambda00, phi00); + } + function areaPointFirst(lambda, phi) { + areaStream.point = areaPoint; + lambda00 = lambda, phi00 = phi; + lambda *= radians3, phi *= radians3; + lambda0 = lambda, cosPhi0 = cos2(phi = phi / 2 + quarterPi), sinPhi0 = sin2(phi); + } + function areaPoint(lambda, phi) { + lambda *= radians3, phi *= radians3; + phi = phi / 2 + quarterPi; + var dLambda = lambda - lambda0, sdLambda = dLambda >= 0 ? 1 : -1, adLambda = sdLambda * dLambda, cosPhi = cos2(phi), sinPhi = sin2(phi), k = sinPhi0 * sinPhi, u = cosPhi0 * cosPhi + k * cos2(adLambda), v = k * sdLambda * sin2(adLambda); + areaRingSum.add(atan2(v, u)); + lambda0 = lambda, cosPhi0 = cosPhi, sinPhi0 = sinPhi; + } + + // node_modules/d3-geo/src/cartesian.js + function spherical(cartesian2) { + return [atan2(cartesian2[1], cartesian2[0]), asin2(cartesian2[2])]; + } + function cartesian(spherical2) { + var lambda = spherical2[0], phi = spherical2[1], cosPhi = cos2(phi); + return [cosPhi * cos2(lambda), cosPhi * sin2(lambda), sin2(phi)]; + } + function cartesianCross(a, b) { + return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; + } + function cartesianNormalizeInPlace(d) { + var l = sqrt2(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]); + d[0] /= l, d[1] /= l, d[2] /= l; + } + + // node_modules/d3-geo/src/bounds.js + var lambda02; + var phi0; + var lambda1; + var phi1; + var lambda2; + var lambda002; + var phi002; + var p0; + var deltaSum; + var ranges; + var range2; + var boundsStream = { + point: boundsPoint, + lineStart: boundsLineStart, + lineEnd: boundsLineEnd, + polygonStart: function() { + boundsStream.point = boundsRingPoint; + boundsStream.lineStart = boundsRingStart; + boundsStream.lineEnd = boundsRingEnd; + deltaSum = new Adder(); + areaStream.polygonStart(); + }, + polygonEnd: function() { + areaStream.polygonEnd(); + boundsStream.point = boundsPoint; + boundsStream.lineStart = boundsLineStart; + boundsStream.lineEnd = boundsLineEnd; + if (areaRingSum < 0) lambda02 = -(lambda1 = 180), phi0 = -(phi1 = 90); + else if (deltaSum > epsilon) phi1 = 90; + else if (deltaSum < -epsilon) phi0 = -90; + range2[0] = lambda02, range2[1] = lambda1; + }, + sphere: function() { + lambda02 = -(lambda1 = 180), phi0 = -(phi1 = 90); + } + }; + function boundsPoint(lambda, phi) { + ranges.push(range2 = [lambda02 = lambda, lambda1 = lambda]); + if (phi < phi0) phi0 = phi; + if (phi > phi1) phi1 = phi; + } + function linePoint(lambda, phi) { + var p = cartesian([lambda * radians3, phi * radians3]); + if (p0) { + var normal = cartesianCross(p0, p), equatorial = [normal[1], -normal[0], 0], inflection = cartesianCross(equatorial, normal); + cartesianNormalizeInPlace(inflection); + inflection = spherical(inflection); + var delta = lambda - lambda2, sign = delta > 0 ? 1 : -1, lambdai = inflection[0] * degrees3 * sign, phii, antimeridian = abs(delta) > 180; + if (antimeridian ^ (sign * lambda2 < lambdai && lambdai < sign * lambda)) { + phii = inflection[1] * degrees3; + if (phii > phi1) phi1 = phii; + } else if (lambdai = (lambdai + 360) % 360 - 180, antimeridian ^ (sign * lambda2 < lambdai && lambdai < sign * lambda)) { + phii = -inflection[1] * degrees3; + if (phii < phi0) phi0 = phii; + } else { + if (phi < phi0) phi0 = phi; + if (phi > phi1) phi1 = phi; + } + if (antimeridian) { + if (lambda < lambda2) { + if (angle3(lambda02, lambda) > angle3(lambda02, lambda1)) lambda1 = lambda; + } else { + if (angle3(lambda, lambda1) > angle3(lambda02, lambda1)) lambda02 = lambda; + } + } else { + if (lambda1 >= lambda02) { + if (lambda < lambda02) lambda02 = lambda; + if (lambda > lambda1) lambda1 = lambda; + } else { + if (lambda > lambda2) { + if (angle3(lambda02, lambda) > angle3(lambda02, lambda1)) lambda1 = lambda; + } else { + if (angle3(lambda, lambda1) > angle3(lambda02, lambda1)) lambda02 = lambda; + } + } + } + } else { + ranges.push(range2 = [lambda02 = lambda, lambda1 = lambda]); + } + if (phi < phi0) phi0 = phi; + if (phi > phi1) phi1 = phi; + p0 = p, lambda2 = lambda; + } + function boundsLineStart() { + boundsStream.point = linePoint; + } + function boundsLineEnd() { + range2[0] = lambda02, range2[1] = lambda1; + boundsStream.point = boundsPoint; + p0 = null; + } + function boundsRingPoint(lambda, phi) { + if (p0) { + var delta = lambda - lambda2; + deltaSum.add(abs(delta) > 180 ? delta + (delta > 0 ? 360 : -360) : delta); + } else { + lambda002 = lambda, phi002 = phi; + } + areaStream.point(lambda, phi); + linePoint(lambda, phi); + } + function boundsRingStart() { + areaStream.lineStart(); + } + function boundsRingEnd() { + boundsRingPoint(lambda002, phi002); + areaStream.lineEnd(); + if (abs(deltaSum) > epsilon) lambda02 = -(lambda1 = 180); + range2[0] = lambda02, range2[1] = lambda1; + p0 = null; + } + function angle3(lambda03, lambda12) { + return (lambda12 -= lambda03) < 0 ? lambda12 + 360 : lambda12; + } + function rangeCompare(a, b) { + return a[0] - b[0]; + } + function rangeContains(range3, x) { + return range3[0] <= range3[1] ? range3[0] <= x && x <= range3[1] : x < range3[0] || range3[1] < x; + } + function bounds_default(feature) { + var i, n, a, b, merged, deltaMax, delta; + phi1 = lambda1 = -(lambda02 = phi0 = Infinity); + ranges = []; + stream_default(feature, boundsStream); + if (n = ranges.length) { + ranges.sort(rangeCompare); + for (i = 1, a = ranges[0], merged = [a]; i < n; ++i) { + b = ranges[i]; + if (rangeContains(a, b[0]) || rangeContains(a, b[1])) { + if (angle3(a[0], b[1]) > angle3(a[0], a[1])) a[1] = b[1]; + if (angle3(b[0], a[1]) > angle3(a[0], a[1])) a[0] = b[0]; + } else { + merged.push(a = b); + } + } + for (deltaMax = -Infinity, n = merged.length - 1, i = 0, a = merged[n]; i <= n; a = b, ++i) { + b = merged[i]; + if ((delta = angle3(a[1], b[0])) > deltaMax) deltaMax = delta, lambda02 = b[0], lambda1 = a[1]; + } + } + ranges = range2 = null; + return lambda02 === Infinity || phi0 === Infinity ? [[NaN, NaN], [NaN, NaN]] : [[lambda02, phi0], [lambda1, phi1]]; + } + + // node_modules/@flowmap.gl/data/dist/getViewStateForLocations.js + function getViewStateForFeatures(featureCollection, size, opts) { + const { pad: pad2 = 0.05, maxZoom = 100 } = opts || {}; + const bounds = bounds_default(featureCollection); + const [[x1, y1], [x2, y2]] = bounds; + const paddedBounds = pad2 ? [ + [x1 - pad2 * (x2 - x1), y1 - pad2 * (y2 - y1)], + [x2 + pad2 * (x2 - x1), y2 + pad2 * (y2 - y1)] + ] : bounds; + const [width, height] = size; + return { + ...fitBounds({ + width, + height, + bounds: paddedBounds, + padding: opts?.padding, + // minZoom, + maxZoom + }), + width, + height, + bearing: 0, + pitch: 0 + }; + } + function getViewStateForLocations(locations, getLocationCoords, size, opts) { + const asGeometry = (location) => ({ + type: "Point", + coordinates: getLocationCoords(location) + }); + let geometries; + if (Array.isArray(locations)) { + geometries = locations.map(asGeometry); + } else { + geometries = []; + for (const location of locations) { + geometries.push(asGeometry(location)); + } + } + return getViewStateForFeatures({ + type: "GeometryCollection", + geometries + }, size, opts); + } + + // node_modules/@flowmap.gl/data/dist/provider/FlowmapDataProvider.js + function isFlowmapData(data) { + return data && data.locations && data.flows; + } + function isFlowmapDataProvider(dataProvider) { + return dataProvider && typeof dataProvider.setFlowmapState === "function" && typeof dataProvider.getViewportForLocations === "function" && typeof dataProvider.getFlowByIndex === "function" && typeof dataProvider.getLocationById === "function" && typeof dataProvider.getLocationByIndex === "function" && typeof dataProvider.getLayersData === "function"; + } + + // node_modules/@flowmap.gl/data/dist/provider/LocalFlowmapDataProvider.js + var LocalFlowmapDataProvider = class { + constructor(accessors) { + this.selectors = new FlowmapSelectors(accessors); + this.flowmapData = void 0; + this.flowmapState = void 0; + } + setAccessors(accessors) { + this.selectors.setAccessors(accessors); + } + setFlowmapData(flowmapData) { + this.flowmapData = flowmapData; + } + getSelectors() { + return this.selectors; + } + getFlowmapData() { + return this.flowmapData; + } + async setFlowmapState(flowmapState) { + this.flowmapState = flowmapState; + } + getFlowmapState() { + return this.flowmapState; + } + async getFlowByIndex(idx) { + if (!this.flowmapState || !this.flowmapData) { + return void 0; + } + const flows = this.selectors.getFlowsForFlowmapLayer(this.flowmapState, this.flowmapData); + return flows?.[idx]; + } + // TODO: this is unreliable, should replace by unqiue ID + async getLocationByIndex(idx) { + if (!this.flowmapState || !this.flowmapData) { + return void 0; + } + const locations = this.selectors.getLocationsForFlowmapLayer(this.flowmapState, this.flowmapData); + return locations?.[idx]; + } + async getLayersData() { + if (!this.flowmapState || !this.flowmapData) { + return void 0; + } + return this.selectors.getLayersData(this.flowmapState, this.flowmapData); + } + async getLocationById(id) { + if (!this.flowmapState || !this.flowmapData) { + return void 0; + } + const clusterIndex = this.selectors.getClusterIndex(this.flowmapState, this.flowmapData); + if (clusterIndex) { + const cluster2 = clusterIndex.getClusterById(id); + if (cluster2) { + return cluster2; + } + } + const locationsById = this.selectors.getLocationsById(this.flowmapState, this.flowmapData); + return locationsById?.get(id); + } + async getTotalsForLocation(id) { + if (!this.flowmapState || !this.flowmapData) { + return void 0; + } + return this.selectors.getLocationTotals(this.flowmapState, this.flowmapData)?.get(id); + } + async getViewportForLocations(dims, opts) { + if (!this.flowmapData?.locations) { + return void 0; + } + return getViewStateForLocations(this.flowmapData.locations, (loc) => [ + this.selectors.accessors.getLocationLon(loc), + this.selectors.accessors.getLocationLat(loc) + ], dims, opts); + } + async updateLayersData(setLayersData) { + setLayersData(await this.getLayersData()); + } + getClusterZoom() { + return this.flowmapState && this.flowmapData ? this.selectors.getClusterZoom(this.flowmapState, this.flowmapData) : void 0; + } + getClusterIndex() { + return this.flowmapState && this.flowmapData ? this.selectors.getClusterIndex(this.flowmapState, this.flowmapData) : void 0; + } + getLocationsById() { + return this.flowmapState && this.flowmapData ? this.selectors.getLocationsById(this.flowmapState, this.flowmapData) : void 0; + } + getLocationTotals() { + return this.flowmapState && this.flowmapData ? this.selectors.getLocationTotals(this.flowmapState, this.flowmapData) : void 0; + } + getFlowsForFlowmapLayer() { + return this.flowmapState && this.flowmapData ? this.selectors.getFlowsForFlowmapLayer(this.flowmapState, this.flowmapData) : void 0; + } + }; + + // node_modules/@flowmap.gl/layers/dist/types.js + var PickingType; + (function(PickingType2) { + PickingType2["LOCATION"] = "location"; + PickingType2["FLOW"] = "flow"; + })(PickingType || (PickingType = {})); + + // node_modules/@flowmap.gl/layers/dist/FlowmapLayer.js + var PROPS_TO_CAUSE_LAYER_DATA_UPDATE = [ + "filter", + "locationsEnabled", + "locationTotalsEnabled", + "locationLabelsEnabled", + "adaptiveScalesEnabled", + "flowLinesRenderingMode", + "animationEnabled", + "clusteringEnabled", + "clusteringLevel", + "fadeEnabled", + "fadeOpacityEnabled", + "clusteringAuto", + "darkMode", + "fadeAmount", + "colorScheme", + "highlightColor", + "temporalScaleDomain", + "maxTopFlowsDisplayNum", + "flowEndpointsInViewportMode" + ]; + var DEFAULT_FLOW_LINES_RENDERING_MODE = "straight"; + var HighlightType; + (function(HighlightType2) { + HighlightType2["LOCATION"] = "location"; + HighlightType2["FLOW"] = "flow"; + })(HighlightType || (HighlightType = {})); + var FlowmapLayer = class _FlowmapLayer extends composite_layer_default { + get typedProps() { + return this.props; + } + constructor(props) { + super({ + ...props, + onHover: ((info, event) => { + const startTime = Date.now(); + this.setState({ + highlightedObject: this._getHighlightedObject(info), + lastHoverTime: startTime + }); + const { onHover } = props; + if (onHover) { + this._getFlowmapLayerPickingInfo(info).then((info2) => { + if ((this.state?.lastHoverTime ?? 0) <= startTime) { + this.setState({ pickingInfo: info2 }); + onHover(info2, event); + } else { + } + }); + } + }), + onClick: ((info, event) => { + const { onClick } = props; + const startTime = Date.now(); + this.setState({ + lastClickTime: startTime + }); + if (onClick) { + this._getFlowmapLayerPickingInfo(info).then((info2) => { + if ((this.state?.lastClickTime ?? 0) <= startTime) { + this.setState({ pickingInfo: info2 }); + if (info2) { + onClick(info2, event); + } + } else { + } + }); + } + }) + }); + this._didWarnAboutAnimationEnabledDeprecation = false; + this._didWarnAboutAnimationEnabledConflict = false; + } + initializeState() { + this.state = { + accessors: new FlowmapAggregateAccessors(this.typedProps), + dataProvider: this._getOrMakeDataProvider(), + layersData: void 0, + highlightedObject: void 0, + pickingInfo: void 0, + lastHoverTime: void 0, + lastClickTime: void 0 + }; + } + getPickingInfo({ info }) { + if (!info.object) { + const object = this.state?.pickingInfo?.object; + if (object) { + return { + ...info, + object, + picked: true + }; + } + } + return info; + } + // private _updateAccessors() { + // this.state?.dataProvider?.setAccessors(this.props); + // this.setState({accessors: new FlowmapAggregateAccessors(this.props)}); + // } + _getOrMakeDataProvider() { + const { data, dataProvider } = this.typedProps; + if (dataProvider && isFlowmapDataProvider(dataProvider)) { + return dataProvider; + } else if (data && isFlowmapData(data)) { + const dataProvider2 = new LocalFlowmapDataProvider(this.typedProps); + dataProvider2.setFlowmapData(data); + return dataProvider2; + } + throw new Error("FlowmapLayer: data must be a FlowmapDataProvider or FlowmapData"); + } + _updateDataProvider() { + this.setState({ dataProvider: this._getOrMakeDataProvider() }); + } + shouldUpdateState(params) { + const { changeFlags } = params; + if (changeFlags.viewportChanged) { + return true; + } + return super.shouldUpdateState(params); + } + updateState(params) { + super.updateState(params); + const { oldProps, props, changeFlags } = params; + if (changeFlags.propsChanged) { + } + if (changeFlags.dataChanged) { + this._updateDataProvider(); + } + if (changeFlags.viewportChanged || changeFlags.dataChanged) { + this.setState({ highlightedObject: void 0 }); + } + if (changeFlags.viewportChanged || changeFlags.dataChanged || changeFlags.propsChanged && PROPS_TO_CAUSE_LAYER_DATA_UPDATE.some((prop) => oldProps[prop] !== props[prop])) { + const { dataProvider } = this.state || {}; + if (dataProvider) { + dataProvider.setFlowmapState(this._getFlowmapState()); + dataProvider.updateLayersData((layersData) => { + this.setState({ layersData, highlightedObject: void 0 }); + }, changeFlags); + } + } + } + _getSettingsState() { + const props = this.typedProps; + const defaults = _FlowmapLayer.defaultProps; + const { locationsEnabled, locationTotalsEnabled, locationLabelsEnabled, adaptiveScalesEnabled, flowLinesRenderingMode, clusteringEnabled, clusteringLevel, fadeEnabled, fadeOpacityEnabled, clusteringAuto, darkMode, fadeAmount, colorScheme, highlightColor, temporalScaleDomain, maxTopFlowsDisplayNum, flowEndpointsInViewportMode } = props; + return { + locationsEnabled: locationsEnabled ?? defaults.locationsEnabled, + locationTotalsEnabled: locationTotalsEnabled ?? defaults.locationTotalsEnabled, + locationLabelsEnabled: locationLabelsEnabled ?? defaults.locationLabelsEnabled, + adaptiveScalesEnabled: adaptiveScalesEnabled ?? defaults.adaptiveScalesEnabled, + flowLinesRenderingMode: flowLinesRenderingMode ?? this._getResolvedFlowLinesRenderingMode(), + clusteringEnabled: clusteringEnabled ?? defaults.clusteringEnabled, + clusteringLevel, + fadeEnabled: fadeEnabled ?? defaults.fadeEnabled, + fadeOpacityEnabled: fadeOpacityEnabled ?? defaults.fadeOpacityEnabled, + clusteringAuto: clusteringAuto ?? defaults.clusteringAuto, + darkMode: darkMode ?? defaults.darkMode, + fadeAmount: fadeAmount ?? defaults.fadeAmount, + colorScheme, + highlightColor: highlightColor ?? defaults.highlightColor, + temporalScaleDomain: temporalScaleDomain ?? defaults.temporalScaleDomain, + maxTopFlowsDisplayNum: maxTopFlowsDisplayNum ?? defaults.maxTopFlowsDisplayNum, + flowEndpointsInViewportMode: flowEndpointsInViewportMode ?? defaults.flowEndpointsInViewportMode + }; + } + _getResolvedFlowLinesRenderingMode() { + const { animationEnabled, flowLinesRenderingMode } = this.typedProps; + if (flowLinesRenderingMode !== void 0) { + if (animationEnabled !== void 0 && !this._didWarnAboutAnimationEnabledConflict) { + this._didWarnAboutAnimationEnabledConflict = true; + console.warn("FlowmapLayer: `animationEnabled` is deprecated and ignored when `flowLinesRenderingMode` is provided."); + } + return flowLinesRenderingMode; + } + if (animationEnabled !== void 0) { + if (!this._didWarnAboutAnimationEnabledDeprecation) { + this._didWarnAboutAnimationEnabledDeprecation = true; + console.warn("FlowmapLayer: `animationEnabled` is deprecated; use `flowLinesRenderingMode` instead."); + } + return animationEnabled ? "animated-straight" : "straight"; + } + return DEFAULT_FLOW_LINES_RENDERING_MODE; + } + _getFlowmapState() { + const props = this.typedProps; + return { + viewport: pickViewportProps(this.context.viewport), + filter: props.filter, + settings: this._getSettingsState() + }; + } + async _getFlowmapLayerPickingInfo(info) { + const { index: index2, sourceLayer } = info; + const { dataProvider, accessors } = this.state || {}; + if (!dataProvider || !accessors) { + return void 0; + } + const commonInfo = { + ...info, + picked: info.picked, + layer: info.layer, + index: info.index, + x: info.x, + y: info.y, + coordinate: info.coordinate, + event: info.event + }; + if (sourceLayer instanceof FlowLinesLayer_default2 || sourceLayer instanceof AnimatedFlowLinesLayer_default2 || sourceLayer instanceof CurvedFlowLinesLayer_default2) { + const flow = index2 === -1 ? void 0 : await dataProvider.getFlowByIndex(index2); + if (flow) { + const origin = await dataProvider.getLocationById(accessors.getFlowOriginId(flow)); + const dest = await dataProvider.getLocationById(accessors.getFlowDestId(flow)); + if (origin && dest) { + return { + ...commonInfo, + object: { + type: PickingType.FLOW, + flow, + origin, + dest, + count: accessors.getFlowMagnitude(flow) + } + }; + } + } + } else if (sourceLayer instanceof FlowCirclesLayer_default2) { + const location = index2 === -1 ? void 0 : await dataProvider.getLocationByIndex(index2); + if (location) { + const id = accessors.getLocationId(location); + const name2 = accessors.getLocationName(location); + const totals = await dataProvider.getTotalsForLocation(id); + const { circleAttributes } = this.state?.layersData || {}; + if (totals && circleAttributes) { + const circleRadius = getOuterCircleRadiusByIndex(circleAttributes, info.index); + return { + ...commonInfo, + object: { + type: PickingType.LOCATION, + location, + id, + name: name2, + totals, + circleRadius + } + }; + } + } + } + return void 0; + } + _getHighlightedObject(info) { + const { index: index2, sourceLayer } = info; + if (index2 < 0) + return void 0; + if (sourceLayer instanceof FlowLinesLayer_default2 || sourceLayer instanceof AnimatedFlowLinesLayer_default2 || sourceLayer instanceof CurvedFlowLinesLayer_default2) { + const { lineAttributes } = this.state?.layersData || {}; + if (lineAttributes) { + let attrs = getFlowLineAttributesByIndex(lineAttributes, index2); + if (this.typedProps.fadeOpacityEnabled) { + attrs = { + ...attrs, + attributes: { + ...attrs.attributes, + getColor: { + ...attrs.attributes.getColor, + value: new Uint8Array([ + ...attrs.attributes.getColor.value.slice(0, 3), + 255 + // the highlight color should be always opaque + ]) + } + } + }; + } + return { + type: HighlightType.FLOW, + lineAttributes: attrs + }; + } + } else if (sourceLayer instanceof FlowCirclesLayer_default2) { + const { circleAttributes } = this.state?.layersData || {}; + if (circleAttributes) { + return { + type: HighlightType.LOCATION, + coords: getLocationCoordsByIndex(circleAttributes, index2), + radius: getOuterCircleRadiusByIndex(circleAttributes, index2) + }; + } + } + return void 0; + } + renderLayers() { + const props = this.typedProps; + const flowLinesRenderingMode = this._getResolvedFlowLinesRenderingMode(); + const highlightColor = props.highlightColor ?? _FlowmapLayer.defaultProps.highlightColor; + const flowLineThicknessScale = props.flowLineThicknessScale ?? _FlowmapLayer.defaultProps.flowLineThicknessScale; + const flowLineCurviness = props.flowLineCurviness ?? _FlowmapLayer.defaultProps.flowLineCurviness; + const layers = []; + if (this.state?.layersData) { + const { layersData, highlightedObject } = this.state; + const { circleAttributes, lineAttributes, locationLabels } = layersData || {}; + if (circleAttributes && lineAttributes) { + const flowmapColors = getFlowmapColors(this._getSettingsState()); + const outlineColor = colorAsRgba(flowmapColors.outlineColor || (props.darkMode ? "#000" : "#fff")); + const commonLineLayerProps = { + data: lineAttributes, + parameters: { + ...props.parameters ?? {}, + // prevent z-fighting at non-zero bearing/pitch + depthTest: false + } + }; + switch (flowLinesRenderingMode) { + case "animated-straight": + layers.push( + // @ts-ignore + new AnimatedFlowLinesLayer_default2({ + ...this.getSubLayerProps({ + ...commonLineLayerProps, + id: "animated-flow-lines", + drawOutline: false, + thicknessUnit: 10 * flowLineThicknessScale + }) + }) + ); + break; + case "curved": + layers.push(new CurvedFlowLinesLayer_default2({ + ...this.getSubLayerProps({ + ...commonLineLayerProps, + id: "curved-flow-lines", + drawOutline: true, + outlineColor, + thicknessUnit: 12 * flowLineThicknessScale, + curviness: flowLineCurviness + }) + })); + break; + case "straight": + default: + layers.push(new FlowLinesLayer_default2({ + ...this.getSubLayerProps({ + ...commonLineLayerProps, + id: "flow-lines", + drawOutline: true, + outlineColor, + thicknessUnit: 12 * flowLineThicknessScale + }) + })); + break; + } + layers.push(new FlowCirclesLayer_default2(this.getSubLayerProps({ + id: "circles", + data: circleAttributes, + emptyColor: props.darkMode ? [0, 0, 0, 255] : [255, 255, 255, 255], + outlineEmptyMix: 0.4 + }))); + if (highlightedObject) { + switch (highlightedObject.type) { + case HighlightType.LOCATION: + layers.push(new scatterplot_layer_default({ + ...this.getSubLayerProps({ + id: "location-highlight", + data: [highlightedObject], + pickable: false, + antialiasing: true, + stroked: true, + filled: false, + lineWidthUnits: "pixels", + getLineWidth: 2, + radiusUnits: "pixels", + getRadius: (d) => d.radius, + getLineColor: colorAsRgba(highlightColor), + getPosition: (d) => d.coords + }) + })); + break; + case HighlightType.FLOW: + if (flowLinesRenderingMode === "curved") { + layers.push(new CurvedFlowLinesLayer_default2({ + ...this.getSubLayerProps({ + id: "flow-highlight", + data: highlightedObject.lineAttributes, + drawOutline: true, + pickable: false, + outlineColor: colorAsRgba(highlightColor), + outlineThickness: 1.5, + thicknessUnit: 12 * flowLineThicknessScale, + curviness: flowLineCurviness, + parameters: { + depthTest: false + } + }) + })); + } else { + layers.push(new FlowLinesLayer_default2({ + ...this.getSubLayerProps({ + id: "flow-highlight", + data: highlightedObject.lineAttributes, + drawOutline: true, + pickable: false, + outlineColor: colorAsRgba(highlightColor), + outlineThickness: 1.5, + thicknessUnit: 12 * flowLineThicknessScale, + parameters: { + depthTest: false + } + }) + })); + } + break; + } + } + } + if (locationLabels) { + layers.push(new text_layer_default(this.getSubLayerProps({ + id: "location-labels", + data: locationLabels, + maxWidth: 1e3, + pickable: false, + fontFamily: "Helvetica", + getPixelOffset: (d, { index: index2 }) => { + const r = getOuterCircleRadiusByIndex(circleAttributes, index2); + return [0, r + 5]; + }, + getPosition: (d, { index: index2 }) => { + const pos = getLocationCoordsByIndex(circleAttributes, index2); + return pos; + }, + getText: (d) => d, + getSize: 10, + getColor: [255, 255, 255, 255], + getAngle: 0, + getTextAnchor: "middle", + getAlignmentBaseline: "top" + }))); + } + } + return layers; + } + }; + FlowmapLayer.defaultProps = { + darkMode: true, + fadeAmount: 50, + locationsEnabled: true, + locationTotalsEnabled: true, + locationLabelsEnabled: false, + clusteringEnabled: true, + fadeEnabled: true, + fadeOpacityEnabled: false, + clusteringAuto: true, + clusteringLevel: void 0, + adaptiveScalesEnabled: true, + temporalScaleDomain: "selected", + flowLineThicknessScale: 1, + flowLineCurviness: 1, + colorScheme: "Teal", + highlightColor: "orange", + maxTopFlowsDisplayNum: 5e3, + flowEndpointsInViewportMode: "any" + }; + var FlowmapLayer_default = FlowmapLayer; + function pickViewportProps(viewport) { + const { width, height, longitude, latitude, zoom, pitch, bearing } = viewport; + return { + width, + height, + longitude, + latitude, + zoom, + pitch, + bearing + }; + } + + // entry.js + window.FlowmapGL = { + Deck: deck_default, + FlowmapLayer: FlowmapLayer_default, + MapboxOverlay + }; +})(); +//# sourceMappingURL=flowmap-gl-bundle.js.map diff --git a/inst/htmlwidgets/lib/flowmap-gl/flowmap-gl-bundle.js.map b/inst/htmlwidgets/lib/flowmap-gl/flowmap-gl-bundle.js.map new file mode 100644 index 0000000..bb15724 --- /dev/null +++ b/inst/htmlwidgets/lib/flowmap-gl/flowmap-gl-bundle.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["node_modules/@probe.gl/env/src/lib/globals.ts","node_modules/@probe.gl/env/src/lib/is-electron.ts","node_modules/@probe.gl/env/src/lib/is-browser.ts","node_modules/@probe.gl/env/src/lib/get-browser.ts","node_modules/@probe.gl/env/src/index.ts","node_modules/@probe.gl/log/src/utils/assert.ts","node_modules/@probe.gl/log/src/loggers/log-utils.ts","node_modules/@probe.gl/log/src/loggers/base-log.ts","node_modules/@probe.gl/log/src/utils/local-storage.ts","node_modules/@probe.gl/log/src/utils/formatters.ts","node_modules/@probe.gl/log/src/utils/color.ts","node_modules/@probe.gl/log/src/utils/autobind.ts","node_modules/@probe.gl/log/src/utils/hi-res-timestamp.ts","node_modules/@probe.gl/log/src/loggers/probe-log.ts","node_modules/@probe.gl/log/src/init.ts","node_modules/@probe.gl/log/src/index.ts","node_modules/@probe.gl/stats/src/utils/hi-res-timestamp.ts","node_modules/@probe.gl/stats/src/lib/stat.ts","node_modules/@probe.gl/stats/src/lib/stats.ts","node_modules/@probe.gl/stats/src/index.ts","node_modules/@luma.gl/core/src/utils/stats-manager.ts","node_modules/@luma.gl/core/src/utils/log.ts","node_modules/@luma.gl/core/src/utils/uid.ts","node_modules/@luma.gl/core/src/adapter/resources/resource.ts","node_modules/@luma.gl/core/src/adapter/resources/buffer.ts","node_modules/@luma.gl/core/src/shadertypes/data-types/data-type-decoder.ts","node_modules/@luma.gl/core/src/shadertypes/vertex-types/vertex-format-decoder.ts","node_modules/@luma.gl/core/src/shadertypes/texture-types/texture-format-table.ts","node_modules/@luma.gl/core/src/shadertypes/texture-types/texture-format-decoder.ts","node_modules/@luma.gl/core/src/shadertypes/image-types/image-types.ts","node_modules/@luma.gl/core/src/adapter/device.ts","node_modules/@luma.gl/core/src/adapter/luma.ts","node_modules/@luma.gl/core/src/adapter/adapter.ts","node_modules/@luma.gl/core/src/adapter/canvas-observer.ts","node_modules/@luma.gl/core/src/utils/promise-utils.ts","node_modules/@luma.gl/core/src/utils/assert.ts","node_modules/@luma.gl/core/src/adapter/canvas-surface.ts","node_modules/@luma.gl/core/src/adapter/canvas-context.ts","node_modules/@luma.gl/core/src/adapter/presentation-context.ts","node_modules/@luma.gl/core/src/adapter/resources/sampler.ts","node_modules/@luma.gl/core/src/adapter/resources/texture.ts","node_modules/@luma.gl/core/src/adapter/resources/texture-view.ts","node_modules/@luma.gl/core/src/adapter-utils/format-compiler-log.ts","node_modules/@luma.gl/core/src/adapter/resources/shader.ts","node_modules/@luma.gl/core/src/adapter/resources/framebuffer.ts","node_modules/@luma.gl/core/src/adapter/resources/render-pipeline.ts","node_modules/@luma.gl/core/src/adapter/resources/shared-render-pipeline.ts","node_modules/@luma.gl/core/src/adapter/resources/compute-pipeline.ts","node_modules/@luma.gl/core/src/factories/pipeline-factory.ts","node_modules/@luma.gl/core/src/factories/shader-factory.ts","node_modules/@luma.gl/core/src/adapter-utils/bind-groups.ts","node_modules/@luma.gl/core/src/adapter/resources/render-pass.ts","node_modules/@luma.gl/core/src/adapter/resources/command-encoder.ts","node_modules/@luma.gl/core/src/adapter/resources/command-buffer.ts","node_modules/@luma.gl/core/src/shadertypes/shader-types/shader-type-decoder.ts","node_modules/@luma.gl/core/src/adapter-utils/get-attribute-from-layouts.ts","node_modules/@luma.gl/core/src/adapter/resources/vertex-array.ts","node_modules/@luma.gl/core/src/adapter/resources/transform-feedback.ts","node_modules/@luma.gl/core/src/adapter/resources/query-set.ts","node_modules/@luma.gl/core/src/adapter/resources/fence.ts","node_modules/@luma.gl/core/src/shadertypes/data-types/decode-data-types.ts","node_modules/@luma.gl/core/src/shadertypes/shader-types/shader-block-layout.ts","node_modules/@luma.gl/core/src/utils/array-utils-flat.ts","node_modules/@luma.gl/core/src/utils/is-array.ts","node_modules/@luma.gl/core/src/portable/shader-block-writer.ts","node_modules/@luma.gl/core/src/utils/array-equal.ts","node_modules/@luma.gl/core/src/portable/uniform-block.ts","node_modules/@luma.gl/core/src/portable/uniform-store.ts","node_modules/@luma.gl/core/src/index.ts","node_modules/@luma.gl/webgl/src/constants/webgl-constants.ts","node_modules/@luma.gl/webgl/src/constants/index.ts","node_modules/@luma.gl/webgl/src/context/polyfills/polyfill-webgl1-extensions.ts","node_modules/@luma.gl/webgl/src/utils/load-script.ts","node_modules/@luma.gl/webgl/src/context/helpers/webgl-context-data.ts","node_modules/@luma.gl/webgl/src/context/debug/spector.ts","node_modules/@luma.gl/webgl/src/context/debug/webgl-developer-tools.ts","node_modules/@luma.gl/webgl/src/context/parameters/webgl-parameter-tables.ts","node_modules/@luma.gl/webgl/src/context/parameters/unified-parameter-api.ts","node_modules/@luma.gl/webgl/src/context/state-tracker/deep-array-equal.ts","node_modules/@luma.gl/webgl/src/context/state-tracker/webgl-state-tracker.ts","node_modules/@luma.gl/webgl/src/context/helpers/create-browser-context.ts","node_modules/@luma.gl/webgl/src/context/helpers/webgl-extensions.ts","node_modules/@luma.gl/webgl/src/adapter/device-helpers/webgl-device-info.ts","node_modules/@luma.gl/webgl/src/adapter/converters/webgl-vertex-formats.ts","node_modules/@luma.gl/webgl/src/adapter/converters/webgl-texture-table.ts","node_modules/@luma.gl/webgl/src/adapter/device-helpers/webgl-device-features.ts","node_modules/@luma.gl/webgl/src/adapter/device-helpers/webgl-device-limits.ts","node_modules/@luma.gl/webgl/src/adapter/resources/webgl-framebuffer.ts","node_modules/@luma.gl/webgl/src/adapter/webgl-canvas-context.ts","node_modules/@luma.gl/webgl/src/adapter/webgl-presentation-context.ts","node_modules/@luma.gl/webgl/src/utils/uid.ts","node_modules/@luma.gl/webgl/src/adapter/resources/webgl-buffer.ts","node_modules/@luma.gl/webgl/src/adapter/helpers/parse-shader-compiler-log.ts","node_modules/@luma.gl/webgl/src/adapter/resources/webgl-shader.ts","node_modules/@luma.gl/webgl/src/adapter/converters/device-parameters.ts","node_modules/@luma.gl/webgl/src/adapter/converters/sampler-parameters.ts","node_modules/@luma.gl/webgl/src/adapter/resources/webgl-sampler.ts","node_modules/@luma.gl/webgl/src/context/state-tracker/with-parameters.ts","node_modules/@luma.gl/webgl/src/adapter/resources/webgl-texture-view.ts","node_modules/@luma.gl/webgl/src/adapter/converters/shader-formats.ts","node_modules/@luma.gl/webgl/src/adapter/resources/webgl-texture.ts","node_modules/@luma.gl/webgl/src/adapter/helpers/set-uniform.ts","node_modules/@luma.gl/webgl/src/adapter/helpers/webgl-topology-utils.ts","node_modules/@luma.gl/webgl/src/adapter/resources/webgl-render-pipeline.ts","node_modules/@luma.gl/webgl/src/adapter/converters/webgl-shadertypes.ts","node_modules/@luma.gl/webgl/src/adapter/helpers/get-shader-layout-from-glsl.ts","node_modules/@luma.gl/webgl/src/adapter/resources/webgl-shared-render-pipeline.ts","node_modules/@luma.gl/webgl/src/adapter/resources/webgl-command-buffer.ts","node_modules/@luma.gl/webgl/src/adapter/resources/webgl-render-pass.ts","node_modules/@luma.gl/webgl/src/adapter/resources/webgl-command-encoder.ts","node_modules/@luma.gl/webgl/src/utils/fill-array.ts","node_modules/@luma.gl/webgl/src/adapter/resources/webgl-vertex-array.ts","node_modules/@luma.gl/webgl/src/adapter/resources/webgl-transform-feedback.ts","node_modules/@luma.gl/webgl/src/adapter/resources/webgl-query-set.ts","node_modules/@luma.gl/webgl/src/adapter/resources/webgl-fence.ts","node_modules/@luma.gl/webgl/src/adapter/helpers/format-utils.ts","node_modules/@luma.gl/webgl/src/adapter/helpers/webgl-texture-utils.ts","node_modules/@luma.gl/webgl/src/adapter/webgl-device.ts","node_modules/@luma.gl/webgl/src/adapter/webgl-adapter.ts","node_modules/@luma.gl/webgl/src/index.ts","node_modules/seedrandom/lib/alea.js","node_modules/seedrandom/lib/xor128.js","node_modules/seedrandom/lib/xorwow.js","node_modules/seedrandom/lib/xorshift7.js","node_modules/seedrandom/lib/xor4096.js","node_modules/seedrandom/lib/tychei.js","node_modules/seedrandom/seedrandom.js","node_modules/seedrandom/index.js","node_modules/@loaders.gl/loader-utils/src/lib/env-utils/assert.ts","node_modules/@loaders.gl/loader-utils/src/lib/env-utils/globals.ts","node_modules/@loaders.gl/loader-utils/src/lib/log-utils/log.ts","node_modules/@loaders.gl/loader-utils/src/lib/javascript-utils/is-type.ts","node_modules/@loaders.gl/loader-utils/src/lib/option-utils/merge-options.ts","node_modules/@loaders.gl/worker-utils/src/lib/npm-tag.ts","node_modules/@loaders.gl/worker-utils/src/lib/env-utils/version.ts","node_modules/@loaders.gl/worker-utils/src/lib/env-utils/assert.ts","node_modules/@loaders.gl/worker-utils/src/lib/env-utils/globals.ts","node_modules/@loaders.gl/worker-utils/src/lib/worker-farm/worker-job.ts","node_modules/@loaders.gl/worker-utils/src/lib/node/worker_threads-browser.ts","node_modules/@loaders.gl/worker-utils/src/lib/worker-utils/get-loadable-worker-url.ts","node_modules/@loaders.gl/worker-utils/src/lib/worker-utils/get-transfer-list.ts","node_modules/@loaders.gl/worker-utils/src/lib/worker-farm/worker-thread.ts","node_modules/@loaders.gl/worker-utils/src/lib/worker-farm/worker-pool.ts","node_modules/@loaders.gl/worker-utils/src/lib/worker-farm/worker-farm.ts","node_modules/@loaders.gl/worker-utils/src/lib/worker-api/get-worker-url.ts","node_modules/@loaders.gl/worker-utils/src/lib/worker-api/validate-worker-version.ts","node_modules/@loaders.gl/loader-utils/src/lib/worker-loader-utils/parse-with-worker.ts","node_modules/@loaders.gl/loader-utils/src/lib/binary-utils/array-buffer-utils.ts","node_modules/@loaders.gl/loader-utils/src/lib/iterators/async-iteration.ts","node_modules/@loaders.gl/loader-utils/src/lib/path-utils/file-aliases.ts","node_modules/@loaders.gl/loader-utils/src/lib/node/buffer.browser.ts","node_modules/@loaders.gl/loader-utils/src/lib/binary-utils/memory-conversion-utils.ts","node_modules/@loaders.gl/loader-utils/src/lib/path-utils/path.ts","node_modules/@loaders.gl/loader-utils/src/lib/path-utils/get-cwd.ts","node_modules/@loaders.gl/core/src/lib/fetch/fetch-error.ts","node_modules/@loaders.gl/core/src/lib/utils/mime-type-utils.ts","node_modules/@loaders.gl/core/src/lib/utils/url-utils.ts","node_modules/@loaders.gl/core/src/lib/utils/resource-utils.ts","node_modules/@loaders.gl/core/src/lib/utils/response-utils.ts","node_modules/@loaders.gl/core/src/lib/fetch/fetch-file.ts","node_modules/@loaders.gl/core/src/lib/loader-utils/loggers.ts","node_modules/@loaders.gl/core/src/lib/loader-utils/option-defaults.ts","node_modules/@loaders.gl/core/src/lib/loader-utils/option-utils.ts","node_modules/@loaders.gl/core/src/lib/loader-utils/normalize-loader.ts","node_modules/@loaders.gl/core/src/lib/api/register-loaders.ts","node_modules/@loaders.gl/core/src/lib/api/select-loader.ts","node_modules/@loaders.gl/core/src/iterators/make-iterator/make-string-iterator.ts","node_modules/@loaders.gl/core/src/iterators/make-iterator/make-array-buffer-iterator.ts","node_modules/@loaders.gl/core/src/iterators/make-iterator/make-blob-iterator.ts","node_modules/@loaders.gl/core/src/iterators/make-iterator/make-stream-iterator.ts","node_modules/@loaders.gl/core/src/iterators/make-iterator/make-iterator.ts","node_modules/@loaders.gl/core/src/lib/loader-utils/get-data.ts","node_modules/@loaders.gl/core/src/lib/loader-utils/get-fetch-function.ts","node_modules/@loaders.gl/core/src/lib/loader-utils/loader-context.ts","node_modules/@loaders.gl/core/src/lib/api/parse.ts","node_modules/@math.gl/types/src/is-array.ts","node_modules/@loaders.gl/core/src/lib/api/load.ts","node_modules/@loaders.gl/images/src/lib/utils/version.ts","node_modules/@loaders.gl/images/src/lib/category-api/image-type.ts","node_modules/@loaders.gl/images/src/lib/category-api/parsed-image-api.ts","node_modules/@loaders.gl/images/src/lib/parsers/svg-utils.ts","node_modules/@loaders.gl/images/src/lib/parsers/parse-to-image.ts","node_modules/@loaders.gl/images/src/lib/parsers/parse-to-image-bitmap.ts","node_modules/@loaders.gl/images/src/lib/category-api/parse-isobmff-binary.ts","node_modules/@loaders.gl/images/src/lib/category-api/binary-image-api.ts","node_modules/@loaders.gl/images/src/lib/parsers/parse-to-node-image.ts","node_modules/@loaders.gl/images/src/lib/parsers/parse-image.ts","node_modules/@loaders.gl/images/src/image-loader.ts","node_modules/@deck.gl/core/src/utils/log.ts","node_modules/@deck.gl/core/src/debug/loggers.ts","node_modules/@deck.gl/core/src/debug/index.ts","node_modules/@deck.gl/core/src/utils/json-loader.ts","node_modules/@deck.gl/core/src/lib/init.ts","node_modules/@luma.gl/shadertools/src/lib/utils/assert.ts","node_modules/@luma.gl/shadertools/src/lib/filters/prop-types.ts","node_modules/@luma.gl/shadertools/src/module-injectors.ts","node_modules/@luma.gl/shadertools/src/lib/shader-assembly/shader-injections.ts","node_modules/@luma.gl/shadertools/src/lib/shader-module/shader-module.ts","node_modules/@luma.gl/shadertools/src/lib/shader-module/shader-module-dependencies.ts","node_modules/@luma.gl/shadertools/src/lib/shader-module/shader-module-uniform-layout.ts","node_modules/@luma.gl/shadertools/src/lib/shader-assembly/platform-defines.ts","node_modules/@luma.gl/shadertools/src/lib/shader-transpiler/transpile-glsl-shader.ts","node_modules/@luma.gl/shadertools/src/lib/shader-assembly/shader-hooks.ts","node_modules/@luma.gl/shadertools/src/lib/glsl-utils/get-shader-info.ts","node_modules/@luma.gl/shadertools/src/lib/shader-assembly/wgsl-binding-scan.ts","node_modules/@luma.gl/shadertools/src/lib/shader-assembly/wgsl-binding-debug.ts","node_modules/@luma.gl/shadertools/src/lib/shader-assembly/assemble-shaders.ts","node_modules/@luma.gl/shadertools/src/lib/preprocessor/preprocessor.ts","node_modules/@luma.gl/shadertools/src/lib/shader-assembler.ts","node_modules/@luma.gl/shadertools/src/lib/glsl-utils/shader-utils.ts","node_modules/@math.gl/core/src/lib/common.ts","node_modules/@math.gl/core/src/classes/base/math-array.ts","node_modules/@math.gl/core/src/lib/validators.ts","node_modules/@math.gl/core/src/lib/assert.ts","node_modules/@math.gl/core/src/classes/base/vector.ts","node_modules/@math.gl/core/src/gl-matrix/vec2.ts","node_modules/@math.gl/core/src/gl-matrix/common.js","node_modules/@math.gl/core/src/lib/gl-matrix-extras.ts","node_modules/@math.gl/core/src/gl-matrix/vec3.ts","node_modules/@math.gl/core/src/classes/vector3.ts","node_modules/@math.gl/core/src/classes/base/matrix.ts","node_modules/@math.gl/core/src/gl-matrix/mat4.ts","node_modules/@math.gl/core/src/gl-matrix/vec4.ts","node_modules/@math.gl/core/src/classes/matrix4.ts","node_modules/@luma.gl/shadertools/src/modules/math/fp64/fp64-utils.ts","node_modules/@luma.gl/shadertools/src/lib/color/normalize-byte-colors.ts","node_modules/@luma.gl/shadertools/src/modules/math/fp32/fp32.ts","node_modules/@luma.gl/shadertools/src/modules/math/fp64/fp64-arithmetic-glsl.ts","node_modules/@luma.gl/shadertools/src/modules/math/fp64/fp64-arithmetic-wgsl.ts","node_modules/@luma.gl/shadertools/src/modules/math/fp64/fp64.ts","node_modules/@luma.gl/shadertools/src/modules/engine/picking/picking.ts","node_modules/@deck.gl/core/src/shaderlib/misc/layer-uniforms.ts","node_modules/@deck.gl/core/src/shaderlib/color/color.ts","node_modules/@deck.gl/core/src/shaderlib/misc/geometry.ts","node_modules/mjolnir.js/src/hammerjs/input/input-consts.ts","node_modules/mjolnir.js/src/hammerjs/recognizer/recognizer-state.ts","node_modules/mjolnir.js/src/hammerjs/touchaction/touchaction-Consts.ts","node_modules/mjolnir.js/src/hammerjs/touchaction/clean-touch-actions.ts","node_modules/mjolnir.js/src/hammerjs/touchaction/touchaction.ts","node_modules/mjolnir.js/src/hammerjs/utils/split-str.ts","node_modules/mjolnir.js/src/hammerjs/utils/event-listeners.ts","node_modules/mjolnir.js/src/hammerjs/utils/get-window-for-element.ts","node_modules/mjolnir.js/src/hammerjs/utils/has-parent.ts","node_modules/mjolnir.js/src/hammerjs/input/get-center.ts","node_modules/mjolnir.js/src/hammerjs/input/simple-clone-input-data.ts","node_modules/mjolnir.js/src/hammerjs/input/get-distance.ts","node_modules/mjolnir.js/src/hammerjs/input/get-angle.ts","node_modules/mjolnir.js/src/hammerjs/input/get-direction.ts","node_modules/mjolnir.js/src/hammerjs/input/get-delta-xy.ts","node_modules/mjolnir.js/src/hammerjs/input/get-velocity.ts","node_modules/mjolnir.js/src/hammerjs/input/get-scale.ts","node_modules/mjolnir.js/src/hammerjs/input/get-rotation.ts","node_modules/mjolnir.js/src/hammerjs/input/compute-interval-input-data.ts","node_modules/mjolnir.js/src/hammerjs/input/compute-input-data.ts","node_modules/mjolnir.js/src/hammerjs/input/input-handler.ts","node_modules/mjolnir.js/src/hammerjs/input/input.ts","node_modules/mjolnir.js/src/hammerjs/inputs/pointerevent.ts","node_modules/mjolnir.js/src/hammerjs/utils/prefixed.ts","node_modules/mjolnir.js/src/hammerjs/manager.ts","node_modules/mjolnir.js/src/hammerjs/utils/unique-id.ts","node_modules/mjolnir.js/src/hammerjs/recognizer/state-str.ts","node_modules/mjolnir.js/src/hammerjs/recognizer/recognizer.ts","node_modules/mjolnir.js/src/hammerjs/recognizers/attribute.ts","node_modules/mjolnir.js/src/hammerjs/recognizers/tap.ts","node_modules/mjolnir.js/src/hammerjs/recognizers/pan.ts","node_modules/mjolnir.js/src/hammerjs/recognizers/pinch.ts","node_modules/mjolnir.js/src/inputs/input.ts","node_modules/mjolnir.js/src/utils/globals.ts","node_modules/mjolnir.js/src/inputs/wheel-input.ts","node_modules/mjolnir.js/src/inputs/move-input.ts","node_modules/mjolnir.js/src/inputs/key-input.ts","node_modules/mjolnir.js/src/inputs/contextmenu-input.ts","node_modules/mjolnir.js/src/utils/event-utils.ts","node_modules/mjolnir.js/src/utils/event-registrar.ts","node_modules/mjolnir.js/src/event-manager.ts","node_modules/@deck.gl/core/src/lib/constants.ts","node_modules/@deck.gl/core/src/utils/memoize.ts","node_modules/@deck.gl/core/src/shaderlib/project/viewport-uniforms.ts","node_modules/@deck.gl/core/src/shaderlib/project/project.wgsl.ts","node_modules/@deck.gl/core/src/shaderlib/project/project.glsl.ts","node_modules/@deck.gl/core/src/shaderlib/project/project.ts","node_modules/@deck.gl/core/src/shaderlib/project32/project32.ts","node_modules/@math.gl/web-mercator/src/math-utils.ts","node_modules/@math.gl/web-mercator/src/assert.ts","node_modules/@math.gl/web-mercator/src/web-mercator-utils.ts","node_modules/@math.gl/web-mercator/src/fit-bounds.ts","node_modules/@math.gl/web-mercator/src/get-bounds.ts","node_modules/@math.gl/web-mercator/src/web-mercator-viewport.ts","node_modules/@deck.gl/core/src/shaderlib/shadow/shadow.ts","node_modules/@deck.gl/core/src/shaderlib/picking/picking.ts","node_modules/@deck.gl/core/src/shaderlib/index.ts","node_modules/@deck.gl/core/src/effects/lighting/ambient-light.ts","node_modules/@deck.gl/core/src/effects/lighting/directional-light.ts","node_modules/@deck.gl/core/src/passes/pass.ts","node_modules/@deck.gl/core/src/passes/layers-pass.ts","node_modules/@deck.gl/core/src/passes/shadow-pass.ts","node_modules/@deck.gl/core/src/effects/lighting/lighting-effect.ts","node_modules/@deck.gl/core/src/utils/typed-array-manager.ts","node_modules/@deck.gl/core/src/utils/math-utils.ts","node_modules/@deck.gl/core/src/viewports/viewport.ts","node_modules/@deck.gl/core/src/viewports/web-mercator-viewport.ts","node_modules/@deck.gl/core/src/shaderlib/project/project-functions.ts","node_modules/@luma.gl/engine/src/animation/timeline.ts","node_modules/@luma.gl/engine/src/animation-loop/animation-loop.ts","node_modules/@luma.gl/engine/src/animation-loop/request-animation-frame.ts","node_modules/@luma.gl/engine/src/model/model.ts","node_modules/@luma.gl/engine/src/geometry/gpu-geometry.ts","node_modules/@luma.gl/engine/src/utils/uid.ts","node_modules/@luma.gl/engine/src/debug/debug-shader-layout.ts","node_modules/@luma.gl/engine/src/debug/debug-framebuffer.ts","node_modules/@luma.gl/engine/src/utils/deep-equal.ts","node_modules/@luma.gl/engine/src/utils/buffer-layout-helper.ts","node_modules/@luma.gl/engine/src/utils/buffer-layout-order.ts","node_modules/@luma.gl/engine/src/utils/shader-module-utils.ts","node_modules/@luma.gl/engine/src/shader-inputs.ts","node_modules/@luma.gl/engine/src/model/split-uniforms-and-bindings.ts","node_modules/@luma.gl/engine/src/dynamic-texture/dynamic-texture.ts","node_modules/@luma.gl/engine/src/dynamic-texture/texture-data.ts","node_modules/@luma.gl/engine/src/compute/buffer-transform.ts","node_modules/@luma.gl/engine/src/geometry/geometry.ts","node_modules/@deck.gl/core/src/passes/pick-layers-pass.ts","node_modules/@deck.gl/core/src/lifecycle/constants.ts","node_modules/@deck.gl/core/src/utils/flatten.ts","node_modules/@deck.gl/core/src/lib/layer-manager.ts","node_modules/@deck.gl/core/src/lib/resource/resource.ts","node_modules/@deck.gl/core/src/lib/resource/resource-manager.ts","node_modules/@deck.gl/core/src/utils/deep-equal.ts","node_modules/@deck.gl/core/src/lib/view-manager.ts","node_modules/@deck.gl/core/src/utils/positions.ts","node_modules/@deck.gl/core/src/utils/deep-merge.ts","node_modules/@deck.gl/core/src/views/view.ts","node_modules/@deck.gl/core/src/transitions/transition.ts","node_modules/@deck.gl/core/src/controllers/transition-manager.ts","node_modules/@deck.gl/core/src/utils/assert.ts","node_modules/@deck.gl/core/src/transitions/transition-interpolator.ts","node_modules/@deck.gl/core/src/viewports/globe-viewport.ts","node_modules/@deck.gl/core/src/transitions/linear-interpolator.ts","node_modules/@deck.gl/core/src/controllers/controller.ts","node_modules/@deck.gl/core/src/controllers/view-state.ts","node_modules/@deck.gl/core/src/controllers/map-controller.ts","node_modules/@deck.gl/core/src/views/map-view.ts","node_modules/@deck.gl/core/src/lib/effect-manager.ts","node_modules/@deck.gl/core/src/passes/draw-layers-pass.ts","node_modules/@deck.gl/core/src/lib/deck-renderer.ts","node_modules/@deck.gl/core/src/lib/deck-picker.ts","node_modules/@deck.gl/core/src/lib/picking/query-object.ts","node_modules/@deck.gl/core/src/lib/picking/pick-info.ts","node_modules/@deck.gl/core/src/lib/widget-manager.ts","node_modules/@deck.gl/core/src/utils/apply-styles.ts","node_modules/@deck.gl/core/src/lib/widget.ts","node_modules/@deck.gl/core/src/lib/tooltip-widget.ts","node_modules/@deck.gl/core/src/lib/deck.ts","node_modules/@deck.gl/core/src/lib/attribute/data-column.ts","node_modules/@deck.gl/core/src/lib/attribute/gl-utils.ts","node_modules/@deck.gl/core/src/utils/iterable-utils.ts","node_modules/@deck.gl/core/src/utils/range.ts","node_modules/@deck.gl/core/src/lib/attribute/transition-settings.ts","node_modules/@deck.gl/core/src/lib/attribute/attribute.ts","node_modules/@deck.gl/core/src/utils/array-utils.ts","node_modules/@deck.gl/core/src/transitions/gpu-transition-utils.ts","node_modules/@deck.gl/core/src/transitions/gpu-transition.ts","node_modules/@deck.gl/core/src/transitions/gpu-interpolation-transition.ts","node_modules/@deck.gl/core/src/transitions/gpu-spring-transition.ts","node_modules/@deck.gl/core/src/lib/attribute/attribute-transition-manager.ts","node_modules/@deck.gl/core/src/lib/attribute/attribute-manager.ts","node_modules/@deck.gl/core/src/lib/layer.ts","node_modules/@deck.gl/core/src/transitions/cpu-interpolation-transition.ts","node_modules/@deck.gl/core/src/transitions/cpu-spring-transition.ts","node_modules/@deck.gl/core/src/lib/uniform-transition-manager.ts","node_modules/@deck.gl/core/src/lifecycle/props.ts","node_modules/@deck.gl/core/src/utils/count.ts","node_modules/@deck.gl/core/src/utils/shader.ts","node_modules/@deck.gl/core/src/utils/texture.ts","node_modules/@deck.gl/core/src/lifecycle/prop-types.ts","node_modules/@deck.gl/core/src/lifecycle/create-props.ts","node_modules/@deck.gl/core/src/lifecycle/component.ts","node_modules/@deck.gl/core/src/lifecycle/component-state.ts","node_modules/@deck.gl/core/src/lib/layer-state.ts","node_modules/@deck.gl/core/src/lib/composite-layer.ts","node_modules/@deck.gl/core/src/controllers/globe-controller.ts","node_modules/@deck.gl/core/src/views/globe-view.ts","node_modules/@deck.gl/mapbox/src/mapbox-layer-group.ts","node_modules/@deck.gl/mapbox/src/resolve-layer-groups.ts","node_modules/@deck.gl/mapbox/src/deck-utils.ts","node_modules/@deck.gl/mapbox/src/mapbox-overlay.ts","node_modules/@flowmap.gl/layers/src/AnimatedFlowLinesLayer/AnimatedFlowLinesLayerFragment.glsl.ts","node_modules/@flowmap.gl/layers/src/AnimatedFlowLinesLayer/AnimatedFlowLinesLayerVertex.glsl.ts","node_modules/@flowmap.gl/layers/src/AnimatedFlowLinesLayer/AnimatedFlowLinesLayerUniforms.ts","node_modules/@flowmap.gl/layers/src/AnimatedFlowLinesLayer/AnimatedFlowLinesLayer.ts","node_modules/@flowmap.gl/layers/src/AnimatedFlowLinesLayer/index.ts","node_modules/@flowmap.gl/layers/src/FlowLinesLayer/FlowLinesLayerUniforms.ts","node_modules/@flowmap.gl/layers/src/CurvedFlowLinesLayer/CurvedFlowLinesLayerFragment.glsl.ts","node_modules/@flowmap.gl/layers/src/CurvedFlowLinesLayer/CurvedFlowLinesLayerVertex.glsl.ts","node_modules/@flowmap.gl/layers/src/CurvedFlowLinesLayer/CurvedFlowLinesLayer.ts","node_modules/@flowmap.gl/layers/src/CurvedFlowLinesLayer/index.ts","node_modules/@flowmap.gl/layers/src/FlowLinesLayer/FlowLinesLayerFragment.glsl.ts","node_modules/@flowmap.gl/layers/src/FlowLinesLayer/FlowLinesLayerVertex.glsl.ts","node_modules/@flowmap.gl/layers/src/FlowLinesLayer/FlowLinesLayer.ts","node_modules/@flowmap.gl/layers/src/FlowLinesLayer/index.ts","node_modules/@flowmap.gl/layers/src/FlowCirclesLayer/FlowCirclesLayerFragment.glsl.ts","node_modules/@flowmap.gl/layers/src/FlowCirclesLayer/FlowCirclesLayerVertex.glsl.ts","node_modules/@flowmap.gl/layers/src/FlowCirclesLayer/FlowCirclesLayerUniforms.ts","node_modules/@flowmap.gl/layers/src/FlowCirclesLayer/FlowCirclesLayer.ts","node_modules/@flowmap.gl/layers/src/FlowCirclesLayer/index.ts","node_modules/@deck.gl/layers/src/icon-layer/icon-layer-uniforms.ts","node_modules/@deck.gl/layers/src/icon-layer/icon-layer-vertex.glsl.ts","node_modules/@deck.gl/layers/src/icon-layer/icon-layer-fragment.glsl.ts","node_modules/@deck.gl/layers/src/icon-layer/icon-layer.wgsl.ts","node_modules/@deck.gl/layers/src/icon-layer/icon-manager.ts","node_modules/@deck.gl/layers/src/icon-layer/icon-layer.ts","node_modules/@deck.gl/layers/src/scatterplot-layer/scatterplot-layer-uniforms.ts","node_modules/@deck.gl/layers/src/scatterplot-layer/scatterplot-layer-vertex.glsl.ts","node_modules/@deck.gl/layers/src/scatterplot-layer/scatterplot-layer-fragment.glsl.ts","node_modules/@deck.gl/layers/src/scatterplot-layer/scatterplot-layer.wgsl.ts","node_modules/@deck.gl/layers/src/scatterplot-layer/scatterplot-layer.ts","node_modules/@deck.gl/layers/src/text-layer/multi-icon-layer/sdf-uniforms.ts","node_modules/@deck.gl/layers/src/text-layer/text-uniforms.ts","node_modules/@deck.gl/layers/src/text-layer/multi-icon-layer/multi-icon-layer-vertex.glsl.ts","node_modules/@deck.gl/layers/src/text-layer/multi-icon-layer/multi-icon-layer-fragment.glsl.ts","node_modules/@deck.gl/layers/src/text-layer/multi-icon-layer/multi-icon-layer.ts","node_modules/@mapbox/tiny-sdf/index.js","node_modules/@deck.gl/layers/src/text-layer/utils.ts","node_modules/@deck.gl/layers/src/text-layer/lru-cache.ts","node_modules/@deck.gl/layers/src/text-layer/font-atlas-manager.ts","node_modules/@deck.gl/layers/src/text-layer/text-background-layer/text-background-layer-uniforms.ts","node_modules/@deck.gl/layers/src/text-layer/text-background-layer/text-background-layer-vertex.glsl.ts","node_modules/@deck.gl/layers/src/text-layer/text-background-layer/text-background-layer-fragment.glsl.ts","node_modules/@deck.gl/layers/src/text-layer/text-background-layer/text-background-layer.ts","node_modules/@deck.gl/layers/src/text-layer/text-layer.ts","node_modules/@flowmap.gl/data/src/types.ts","node_modules/d3-scale-chromatic/src/colors.js","node_modules/d3-color/src/define.js","node_modules/d3-color/src/color.js","node_modules/d3-color/src/math.js","node_modules/d3-color/src/lab.js","node_modules/d3-color/src/cubehelix.js","node_modules/d3-interpolate/src/basis.js","node_modules/d3-interpolate/src/basisClosed.js","node_modules/d3-interpolate/src/constant.js","node_modules/d3-interpolate/src/color.js","node_modules/d3-interpolate/src/rgb.js","node_modules/d3-interpolate/src/numberArray.js","node_modules/d3-interpolate/src/array.js","node_modules/d3-interpolate/src/date.js","node_modules/d3-interpolate/src/number.js","node_modules/d3-interpolate/src/object.js","node_modules/d3-interpolate/src/string.js","node_modules/d3-interpolate/src/value.js","node_modules/d3-interpolate/src/round.js","node_modules/d3-interpolate/src/cubehelix.js","node_modules/d3-scale-chromatic/src/ramp.js","node_modules/d3-scale-chromatic/src/sequential-multi/BuGn.js","node_modules/d3-scale-chromatic/src/sequential-multi/BuPu.js","node_modules/d3-scale-chromatic/src/sequential-multi/GnBu.js","node_modules/d3-scale-chromatic/src/sequential-multi/OrRd.js","node_modules/d3-scale-chromatic/src/sequential-multi/PuBuGn.js","node_modules/d3-scale-chromatic/src/sequential-multi/PuBu.js","node_modules/d3-scale-chromatic/src/sequential-multi/PuRd.js","node_modules/d3-scale-chromatic/src/sequential-multi/RdPu.js","node_modules/d3-scale-chromatic/src/sequential-multi/YlGnBu.js","node_modules/d3-scale-chromatic/src/sequential-multi/YlGn.js","node_modules/d3-scale-chromatic/src/sequential-multi/YlOrBr.js","node_modules/d3-scale-chromatic/src/sequential-multi/YlOrRd.js","node_modules/d3-scale-chromatic/src/sequential-single/Blues.js","node_modules/d3-scale-chromatic/src/sequential-single/Greens.js","node_modules/d3-scale-chromatic/src/sequential-single/Greys.js","node_modules/d3-scale-chromatic/src/sequential-single/Purples.js","node_modules/d3-scale-chromatic/src/sequential-single/Reds.js","node_modules/d3-scale-chromatic/src/sequential-single/Oranges.js","node_modules/d3-scale-chromatic/src/sequential-multi/rainbow.js","node_modules/d3-scale-chromatic/src/sequential-multi/viridis.js","node_modules/d3-array/src/ascending.js","node_modules/d3-array/src/descending.js","node_modules/d3-array/src/bisector.js","node_modules/d3-array/src/number.js","node_modules/d3-array/src/bisect.js","node_modules/d3-array/src/extent.js","node_modules/d3-array/src/fsum.js","node_modules/internmap/src/index.js","node_modules/d3-array/src/identity.js","node_modules/d3-array/src/group.js","node_modules/d3-array/src/ticks.js","node_modules/d3-array/src/min.js","node_modules/d3-array/src/range.js","node_modules/d3-scale/src/init.js","node_modules/d3-scale/src/constant.js","node_modules/d3-scale/src/number.js","node_modules/d3-scale/src/continuous.js","node_modules/d3-format/src/formatDecimal.js","node_modules/d3-format/src/exponent.js","node_modules/d3-format/src/formatGroup.js","node_modules/d3-format/src/formatNumerals.js","node_modules/d3-format/src/formatSpecifier.js","node_modules/d3-format/src/formatTrim.js","node_modules/d3-format/src/formatPrefixAuto.js","node_modules/d3-format/src/formatRounded.js","node_modules/d3-format/src/formatTypes.js","node_modules/d3-format/src/identity.js","node_modules/d3-format/src/locale.js","node_modules/d3-format/src/defaultLocale.js","node_modules/d3-format/src/precisionFixed.js","node_modules/d3-format/src/precisionPrefix.js","node_modules/d3-format/src/precisionRound.js","node_modules/d3-scale/src/tickFormat.js","node_modules/d3-scale/src/linear.js","node_modules/d3-scale/src/pow.js","node_modules/d3-time/src/interval.js","node_modules/d3-time/src/duration.js","node_modules/d3-time/src/second.js","node_modules/d3-time/src/minute.js","node_modules/d3-time/src/hour.js","node_modules/d3-time/src/day.js","node_modules/d3-time/src/week.js","node_modules/d3-time/src/month.js","node_modules/d3-time/src/year.js","node_modules/d3-time-format/src/locale.js","node_modules/d3-time-format/src/defaultLocale.js","node_modules/d3-scale/src/sequential.js","node_modules/@flowmap.gl/data/src/colors.ts","node_modules/kdbush/index.js","node_modules/reselect/src/devModeChecks/identityFunctionCheck.ts","node_modules/reselect/src/devModeChecks/inputStabilityCheck.ts","node_modules/reselect/src/devModeChecks/setGlobalDevModeChecks.ts","node_modules/reselect/src/utils.ts","node_modules/reselect/src/autotrackMemoize/autotracking.ts","node_modules/reselect/src/autotrackMemoize/tracking.ts","node_modules/reselect/src/autotrackMemoize/proxy.ts","node_modules/reselect/src/lruMemoize.ts","node_modules/reselect/src/autotrackMemoize/autotrackMemoize.ts","node_modules/reselect/src/weakMapMemoize.ts","node_modules/reselect/src/createSelectorCreator.ts","node_modules/reselect/src/createStructuredSelector.ts","node_modules/@flowmap.gl/data/src/FlowmapSelectors.ts","node_modules/@flowmap.gl/data/src/FlowmapAggregateAccessors.ts","node_modules/@flowmap.gl/data/src/cluster/ClusterIndex.ts","node_modules/@flowmap.gl/data/src/cluster/cluster.ts","node_modules/@flowmap.gl/data/src/selector-functions.ts","node_modules/@flowmap.gl/data/src/time.ts","node_modules/d3-geo/src/math.js","node_modules/d3-geo/src/noop.js","node_modules/d3-geo/src/stream.js","node_modules/d3-geo/src/area.js","node_modules/d3-geo/src/cartesian.js","node_modules/d3-geo/src/bounds.js","node_modules/@flowmap.gl/data/src/getViewStateForLocations.ts","node_modules/@flowmap.gl/data/src/provider/FlowmapDataProvider.ts","node_modules/@flowmap.gl/data/src/provider/LocalFlowmapDataProvider.ts","node_modules/@flowmap.gl/layers/src/types.ts","node_modules/@flowmap.gl/layers/src/FlowmapLayer.ts","entry.js"],"sourcesContent":["// Do not name these variables the same as the global objects - will break bundling\nconst global_ = globalThis;\nconst window_ = globalThis as unknown as Window;\nconst document_ = globalThis.document || ({} as Document);\nconst process_ = globalThis.process || {};\nconst console_ = globalThis.console;\nconst navigator_ = globalThis.navigator || ({} as Navigator);\n\nexport {\n global_ as global,\n global_ as self,\n window_ as window,\n document_ as document,\n process_ as process,\n console_ as console,\n navigator_ as navigator\n};\n","// based on https://github.com/cheton/is-electron\n// https://github.com/electron/electron/issues/2288\n/* eslint-disable complexity */\nexport function isElectron(mockUserAgent?: string): boolean {\n // Renderer process\n // @ts-expect-error\n if (typeof window !== 'undefined' && window.process?.type === 'renderer') {\n return true;\n }\n // Main process\n // eslint-disable-next-line\n if (typeof process !== 'undefined' && Boolean(process.versions?.['electron'])) {\n return true;\n }\n // Detect the user agent when the `nodeIntegration` option is set to true\n const realUserAgent = typeof navigator !== 'undefined' && navigator.userAgent;\n const userAgent = mockUserAgent || realUserAgent;\n return Boolean(userAgent && userAgent.indexOf('Electron') >= 0);\n}\n","// This function is needed in initialization stages,\n// make sure it can be imported in isolation\n\nimport {isElectron} from './is-electron';\n\n/** Check if in browser by duck-typing Node context */\nexport function isBrowser(): boolean {\n const isNode =\n // @ts-expect-error\n typeof process === 'object' && String(process) === '[object process]' && !process?.browser;\n return !isNode || isElectron();\n}\n","// Copyright (c) 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n// This function is needed in initialization stages,\n// make sure it can be imported in isolation\n\nimport {isBrowser} from './is-browser';\nimport {isElectron} from './is-electron';\nimport {navigator} from './globals';\n\ndeclare global {\n var chrome: boolean; // eslint-disable-line no-var\n var safari: boolean; // eslint-disable-line no-var\n var mozInnerScreenX: number; // eslint-disable-line no-var\n}\n\nexport function isMobile(): boolean {\n return typeof globalThis.orientation !== 'undefined';\n}\n\n// Simple browser detection\n// `mockUserAgent` parameter allows user agent to be overridden for testing\n/* eslint-disable complexity */\nexport function getBrowser(\n mockUserAgent?: string\n): 'Node' | 'Electron' | 'Chrome' | 'Firefox' | 'Safari' | 'Edge' | 'Unknown' {\n if (!mockUserAgent && !isBrowser()) {\n return 'Node';\n }\n if (isElectron(mockUserAgent)) {\n return 'Electron';\n }\n\n const userAgent = mockUserAgent || navigator.userAgent || '';\n\n // NOTE: Order of tests matter, as many agents list Chrome etc.\n if (userAgent.indexOf('Edge') > -1) {\n return 'Edge';\n }\n if (globalThis.chrome) {\n return 'Chrome';\n }\n if (globalThis.safari) {\n return 'Safari';\n }\n if (globalThis.mozInnerScreenX) {\n return 'Firefox';\n }\n return 'Unknown';\n}\n","// Extract injected version from package.json (injected by babel plugin)\n// @ts-expect-error\nexport const VERSION = typeof __VERSION__ !== 'undefined' ? __VERSION__ : 'untranspiled source';\n\n// ENVIRONMENT\nexport {self, window, global, document, process, console} from './lib/globals';\nexport {isBrowser} from './lib/is-browser';\nexport {getBrowser, isMobile} from './lib/get-browser';\nexport {isElectron} from './lib/is-electron';\n\n// ENVIRONMENT'S ASSERT IS 5-15KB, SO WE PROVIDE OUR OWN\nexport {assert} from './utils/assert';\n\n// TODO - wish we could just export a constant\n// export const isBrowser = checkIfBrowser();\n","export default function assert(condition: unknown, message?: string): asserts condition {\n if (!condition) {\n throw new Error(message || 'Assertion failed');\n }\n}\n","// probe.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport assert from '../utils/assert';\n\n/**\n * Get logLevel from first argument:\n * - log(logLevel, message, args) => logLevel\n * - log(message, args) => 0\n * - log({logLevel, ...}, message, args) => logLevel\n * - log({logLevel, message, args}) => logLevel\n */\nexport function normalizeLogLevel(logLevel: unknown): number {\n if (!logLevel) {\n return 0;\n }\n let resolvedLevel;\n\n switch (typeof logLevel) {\n case 'number':\n resolvedLevel = logLevel;\n break;\n\n case 'object':\n // Backward compatibility\n // TODO - deprecate `priority`\n // @ts-expect-error\n resolvedLevel = logLevel.logLevel || logLevel.priority || 0;\n break;\n\n default:\n return 0;\n }\n // 'log level must be a number'\n assert(Number.isFinite(resolvedLevel) && resolvedLevel >= 0);\n\n return resolvedLevel;\n}\n\n/**\n * \"Normalizes\" the various argument patterns into an object with known types\n * - log(logLevel, message, args) => {logLevel, message, args}\n * - log(message, args) => {logLevel: 0, message, args}\n * - log({logLevel, ...}, message, args) => {logLevel, message, args}\n * - log({logLevel, message, args}) => {logLevel, message, args}\n */\nexport function normalizeArguments(opts: {\n logLevel;\n message;\n collapsed?: boolean;\n args?: IArguments | any[] | undefined;\n opts?;\n}): NormalizedArguments {\n const {logLevel, message} = opts;\n opts.logLevel = normalizeLogLevel(logLevel);\n\n // We use `arguments` instead of rest parameters (...args) because IE\n // does not support the syntax. Rest parameters is transpiled to code with\n // perf impact. Doing it here instead avoids constructing args when logging is\n // disabled.\n // TODO - remove when/if IE support is dropped\n const args: any[] = opts.args ? Array.from(opts.args) : [];\n // args should only contain arguments that appear after `message`\n // eslint-disable-next-line no-empty\n while (args.length && args.shift() !== message) {}\n\n switch (typeof logLevel) {\n case 'string':\n case 'function':\n if (message !== undefined) {\n args.unshift(message);\n }\n opts.message = logLevel;\n break;\n\n case 'object':\n Object.assign(opts, logLevel);\n break;\n\n default:\n }\n\n // Resolve functions into strings by calling them\n if (typeof opts.message === 'function') {\n opts.message = opts.message();\n }\n const messageType = typeof opts.message;\n // 'log message must be a string' or object\n assert(messageType === 'string' || messageType === 'object');\n\n // original opts + normalized opts + opts arg + fixed up message\n return Object.assign(opts, {args}, opts.opts);\n}\nexport type NormalizedArguments = {\n logLevel: number;\n message: any;\n args: any[];\n tag?: unknown;\n method?: Function;\n once?: boolean;\n total?: number;\n delta?: number;\n [key: string]: any;\n};\n","// probe.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Logger, LogFunction} from './logger';\nimport {NormalizedArguments, normalizeArguments, normalizeLogLevel} from './log-utils';\n\nconst noop = () => {};\n\nexport type NormalizedLogArguments = NormalizedArguments;\ntype LogType = 'log' | 'info' | 'once' | 'warn' | 'error' | 'table' | 'group' | 'groupEnd' | 'time';\n\ntype LogOptions = Partial;\n\n/**\n * Base logger that implements log level handling and once de-duplication.\n * Concrete loggers implement `_emit` to perform actual output.\n */\nexport abstract class BaseLog implements Logger {\n userData: Record = {};\n\n protected _level: number;\n protected _onceCache = new Set();\n\n constructor({level = 0}: {level?: number} = {}) {\n this._level = level;\n }\n\n set level(newLevel: number) {\n this.setLevel(newLevel);\n }\n\n get level(): number {\n return this.getLevel();\n }\n\n setLevel(level: number): this {\n this._level = level;\n return this;\n }\n\n getLevel(): number {\n return this._level;\n }\n\n // Unconditional logging\n\n warn(message: string, ...args: unknown[]): LogFunction {\n return this._log('warn', 0, message, args, {once: true});\n }\n\n error(message: string, ...args: unknown[]): LogFunction {\n return this._log('error', 0, message, args);\n }\n\n // Conditional logging\n\n log(logLevel, message?, ...args: unknown[]): LogFunction {\n return this._log('log', logLevel, message, args);\n }\n\n info(logLevel, message?, ...args: unknown[]): LogFunction {\n return this._log('info', logLevel, message, args);\n }\n\n once(logLevel, message?, ...args: unknown[]): LogFunction {\n return this._log('once', logLevel, message, args, {once: true});\n }\n\n protected _log(\n type: LogType,\n logLevel: unknown,\n message: unknown,\n args: unknown[],\n options: LogOptions = {}\n ): LogFunction {\n const normalized = normalizeArguments({\n logLevel,\n message,\n args: this._buildArgs(logLevel, message, args),\n opts: options\n });\n\n return this._createLogFunction(type, normalized, options);\n }\n\n protected _buildArgs(logLevel: unknown, message: unknown, args: unknown[]): unknown[] {\n return [logLevel, message, ...args];\n }\n\n protected _createLogFunction(\n type: LogType,\n normalized: NormalizedLogArguments,\n options: LogOptions\n ): LogFunction {\n if (!this._shouldLog(normalized.logLevel)) {\n return noop;\n }\n\n const tag = this._getOnceTag(options.tag ?? normalized.tag ?? normalized.message);\n if ((options.once || normalized.once) && tag !== undefined) {\n if (this._onceCache.has(tag)) {\n return noop;\n }\n this._onceCache.add(tag);\n }\n\n return this._emit(type, normalized);\n }\n\n protected _shouldLog(logLevel: unknown): boolean {\n return this.getLevel() >= normalizeLogLevel(logLevel);\n }\n\n protected _getOnceTag(tag: unknown): unknown {\n if (tag === undefined) {\n return undefined;\n }\n try {\n return typeof tag === 'string' ? tag : String(tag);\n } catch {\n return undefined;\n }\n }\n\n /** Create the actual log function for this logger implementation. */\n protected abstract _emit(type: LogType, normalized: NormalizedLogArguments): LogFunction;\n}\n\nexport {noop};\n","// probe.gl, MIT license\n\nexport type StorageType = 'sessionStorage' | 'localStorage';\n\nfunction getStorage(type: StorageType): Storage | null {\n try {\n const storage: Storage = window[type];\n const x = '__storage_test__';\n storage.setItem(x, x);\n storage.removeItem(x);\n return storage;\n } catch (e) {\n return null;\n }\n}\n\n// Store keys in local storage via simple interface\nexport class LocalStorage {\n storage: Storage | null;\n id: string;\n config: Required;\n\n constructor(\n id: string,\n defaultConfig: Required,\n type: StorageType = 'sessionStorage'\n ) {\n this.storage = getStorage(type);\n this.id = id;\n this.config = defaultConfig;\n this._loadConfiguration();\n }\n\n getConfiguration(): Required {\n return this.config;\n }\n\n setConfiguration(configuration: Configuration): void {\n Object.assign(this.config, configuration);\n if (this.storage) {\n const serialized = JSON.stringify(this.config);\n this.storage.setItem(this.id, serialized);\n }\n }\n\n // Get config from persistent store, if available\n _loadConfiguration() {\n let configuration = {};\n if (this.storage) {\n const serializedConfiguration = this.storage.getItem(this.id);\n configuration = serializedConfiguration ? JSON.parse(serializedConfiguration) : {};\n }\n Object.assign(this.config, configuration);\n return this;\n }\n}\n","// probe.gl, MIT license\n\nexport type FormatValueOptions = {\n isInteger?: boolean;\n maxElts?: number;\n size?: number;\n};\n\n/**\n * Format time\n */\nexport function formatTime(ms: number): string {\n let formatted;\n if (ms < 10) {\n formatted = `${ms.toFixed(2)}ms`;\n } else if (ms < 100) {\n formatted = `${ms.toFixed(1)}ms`;\n } else if (ms < 1000) {\n formatted = `${ms.toFixed(0)}ms`;\n } else {\n formatted = `${(ms / 1000).toFixed(2)}s`;\n }\n return formatted;\n}\n\nexport function leftPad(string: string, length: number = 8): string {\n const padLength = Math.max(length - string.length, 0);\n return `${' '.repeat(padLength)}${string}`;\n}\n\nexport function rightPad(string: string, length: number = 8): string {\n const padLength = Math.max(length - string.length, 0);\n return `${string}${' '.repeat(padLength)}`;\n}\n\nexport function formatValue(v: unknown, options: FormatValueOptions = {}): string {\n const EPSILON = 1e-16;\n const {isInteger = false} = options;\n if (Array.isArray(v) || ArrayBuffer.isView(v)) {\n return formatArrayValue(v, options);\n }\n if (!Number.isFinite(v)) {\n return String(v);\n }\n // @ts-expect-error\n if (Math.abs(v) < EPSILON) {\n return isInteger ? '0' : '0.';\n }\n if (isInteger) {\n // @ts-expect-error\n return v.toFixed(0);\n }\n // @ts-expect-error\n if (Math.abs(v) > 100 && Math.abs(v) < 10000) {\n // @ts-expect-error\n return v.toFixed(0);\n }\n // @ts-expect-error\n const string = v.toPrecision(2);\n const decimal = string.indexOf('.0');\n return decimal === string.length - 2 ? string.slice(0, -1) : string;\n}\n\n/** Helper to formatValue */\nfunction formatArrayValue(v: any, options: FormatValueOptions) {\n const {maxElts = 16, size = 1} = options;\n let string = '[';\n for (let i = 0; i < v.length && i < maxElts; ++i) {\n if (i > 0) {\n string += `,${i % size === 0 ? ' ' : ''}`;\n }\n string += formatValue(v[i], options);\n }\n const terminator = v.length > maxElts ? '...' : ']';\n return `${string}${terminator}`;\n}\n","import {isBrowser} from '@probe.gl/env';\n\nexport enum COLOR {\n BLACK = 30,\n RED = 31,\n GREEN = 32,\n YELLOW = 33,\n BLUE = 34,\n MAGENTA = 35,\n CYAN = 36,\n WHITE = 37,\n\n BRIGHT_BLACK = 90,\n BRIGHT_RED = 91,\n BRIGHT_GREEN = 92,\n BRIGHT_YELLOW = 93,\n BRIGHT_BLUE = 94,\n BRIGHT_MAGENTA = 95,\n BRIGHT_CYAN = 96,\n BRIGHT_WHITE = 97\n}\n\nconst BACKGROUND_INCREMENT = 10;\n\nfunction getColor(color: string | COLOR): number {\n if (typeof color !== 'string') {\n return color;\n }\n color = color.toUpperCase();\n return COLOR[color] || COLOR.WHITE;\n}\n\nexport function addColor(\n string: string,\n color: string | COLOR,\n background?: string | COLOR\n): string {\n if (!isBrowser && typeof string === 'string') {\n if (color) {\n const colorCode = getColor(color);\n string = `\\u001b[${colorCode}m${string}\\u001b[39m`;\n }\n if (background) {\n // background colors values are +10\n const colorCode = getColor(background);\n string = `\\u001b[${colorCode + BACKGROUND_INCREMENT}m${string}\\u001b[49m`;\n }\n }\n return string;\n}\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n/**\n * Binds the \"this\" argument of all functions on a class instance to the instance\n * @param obj - class instance (typically a react component)\n */\nexport function autobind(obj: object, predefined = ['constructor']): void {\n const proto = Object.getPrototypeOf(obj);\n const propNames = Object.getOwnPropertyNames(proto);\n\n const object = obj as Record;\n for (const key of propNames) {\n const value = object[key];\n if (typeof value === 'function') {\n if (!predefined.find((name) => key === name)) {\n object[key] = value.bind(obj);\n }\n }\n }\n}\n","// probe.gl, MIT license\n\nimport {window, process, isBrowser} from '@probe.gl/env';\n\n/** Get best timer available. */\nexport function getHiResTimestamp() {\n let timestamp;\n if (isBrowser() && window.performance) {\n timestamp = window?.performance?.now?.();\n } else if ('hrtime' in process) {\n // @ts-ignore\n const timeParts = process?.hrtime?.();\n timestamp = timeParts[0] * 1000 + timeParts[1] / 1e6;\n } else {\n timestamp = Date.now();\n }\n\n return timestamp;\n}\n","// probe.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/* eslint-disable no-console,prefer-rest-params */\nimport {VERSION, isBrowser} from '@probe.gl/env';\nimport {LogFunction} from './logger';\nimport {BaseLog, NormalizedLogArguments, noop} from './base-log';\nimport {LocalStorage} from '../utils/local-storage';\nimport {formatTime, leftPad} from '../utils/formatters';\nimport {addColor} from '../utils/color';\nimport {autobind} from '../utils/autobind';\nimport assert from '../utils/assert';\nimport {getHiResTimestamp} from '../utils/hi-res-timestamp';\n\n/** \"Global\" log configuration settings */\ntype ProbeLogConfiguration = {\n enabled?: boolean;\n level?: number;\n [key: string]: unknown;\n};\n\ntype Table = Record;\n\n// Instrumentation in other packages may override console methods, so preserve them here\nconst originalConsole = {\n debug: isBrowser() ? console.debug || console.log : console.log,\n log: console.log,\n info: console.info,\n warn: console.warn,\n error: console.error\n};\n\nconst DEFAULT_LOG_CONFIGURATION: Required = {\n enabled: true,\n level: 0\n};\n\n/** A console wrapper */\n\nexport class ProbeLog extends BaseLog {\n static VERSION = VERSION;\n\n id: string;\n VERSION: string = VERSION;\n _startTs: number = getHiResTimestamp();\n _deltaTs: number = getHiResTimestamp();\n _storage: LocalStorage>;\n override userData = {};\n\n // TODO - fix support from throttling groups\n LOG_THROTTLE_TIMEOUT: number = 0; // Time before throttled messages are logged again\n\n constructor({id} = {id: ''}) {\n super({level: 0});\n this.id = id;\n this.userData = {};\n this._storage = new LocalStorage>(\n `__probe-${this.id}__`,\n {[this.id]: DEFAULT_LOG_CONFIGURATION}\n );\n\n this.timeStamp(`${this.id} started`);\n\n autobind(this);\n Object.seal(this);\n }\n\n isEnabled(): boolean {\n return this._getConfiguration().enabled;\n }\n\n override getLevel(): number {\n return this._getConfiguration().level;\n }\n\n /** @return milliseconds, with fractions */\n getTotal(): number {\n return Number((getHiResTimestamp() - this._startTs).toPrecision(10));\n }\n\n /** @return milliseconds, with fractions */\n getDelta(): number {\n return Number((getHiResTimestamp() - this._deltaTs).toPrecision(10));\n }\n\n /** @deprecated use logLevel */\n set priority(newPriority: number) {\n this.level = newPriority;\n }\n\n /** @deprecated use logLevel */\n get priority(): number {\n return this.level;\n }\n\n /** @deprecated use logLevel */\n getPriority(): number {\n return this.level;\n }\n\n // Configure\n\n enable(enabled: boolean = true): this {\n this._updateConfiguration({enabled});\n return this;\n }\n\n override setLevel(level: number): this {\n this._updateConfiguration({level});\n return this;\n }\n\n /** return the current status of the setting */\n get(setting: string): any {\n return this._getConfiguration()[setting];\n }\n\n // update the status of the setting\n set(setting: string, value: any): void {\n this._updateConfiguration({[setting]: value});\n }\n\n /** Logs the current settings as a table */\n settings(): void {\n if (console.table) {\n console.table(this._storage.config);\n } else {\n console.log(this._storage.config);\n }\n }\n\n // Unconditional logging\n\n assert(condition: unknown, message?: string): asserts condition {\n if (!condition) {\n throw new Error(message || 'Assertion failed');\n }\n }\n\n /** Warn, but only once, no console flooding */\n override warn(message: string, ...args: unknown[]): LogFunction;\n override warn(message: string, ...args: unknown[]): LogFunction {\n return this._log('warn', 0, message, args, {\n method: originalConsole.warn,\n once: true\n });\n }\n\n /** Print an error */\n override error(message: string, ...args: unknown[]): LogFunction;\n override error(message: string, ...args: unknown[]): LogFunction {\n return this._log('error', 0, message, args, {\n method: originalConsole.error\n });\n }\n\n /** Print a deprecation warning */\n deprecated(oldUsage: string, newUsage: string): LogFunction {\n return this.warn(`\\`${oldUsage}\\` is deprecated and will be removed \\\nin a later version. Use \\`${newUsage}\\` instead`);\n }\n\n /** Print a removal warning */\n removed(oldUsage: string, newUsage: string): LogFunction {\n return this.error(`\\`${oldUsage}\\` has been removed. Use \\`${newUsage}\\` instead`);\n }\n\n // Conditional logging\n\n /** Log to a group */\n probe(logLevel, message?, ...args: unknown[]): LogFunction;\n probe(logLevel, message?, ...args: unknown[]): LogFunction {\n return this._log('log', logLevel, message, args, {\n method: originalConsole.log,\n time: true,\n once: true\n });\n }\n\n /** Log a debug message */\n override log(logLevel, message?, ...args: unknown[]): LogFunction;\n override log(logLevel, message?, ...args: unknown[]): LogFunction {\n return this._log('log', logLevel, message, args, {\n method: originalConsole.debug\n });\n }\n\n /** Log a normal message */\n override info(logLevel, message?, ...args: unknown[]): LogFunction;\n override info(logLevel, message?, ...args: unknown[]): LogFunction {\n return this._log('info', logLevel, message, args, {method: console.info});\n }\n\n /** Log a normal message, but only once, no console flooding */\n override once(logLevel, message?, ...args: unknown[]): LogFunction;\n override once(logLevel, message?, ...args: unknown[]): LogFunction {\n return this._log('once', logLevel, message, args, {\n method: originalConsole.debug || originalConsole.info,\n once: true\n });\n }\n\n /** Logs an object as a table */\n table(logLevel, table?, columns?): LogFunction {\n if (table) {\n return this._log('table', logLevel, table, (columns && [columns]) || [], {\n method: console.table || noop,\n tag: getTableHeader(table)\n });\n }\n return noop;\n }\n\n time(logLevel, message) {\n return this._log('time', logLevel, message, [], {\n method: console.time ? console.time : console.info\n });\n }\n\n timeEnd(logLevel, message) {\n return this._log('time', logLevel, message, [], {\n method: console.timeEnd ? console.timeEnd : console.info\n });\n }\n\n timeStamp(logLevel, message?) {\n return this._log('time', logLevel, message, [], {\n method: console.timeStamp || noop\n });\n }\n\n group(logLevel, message, opts = {collapsed: false}) {\n const method = (opts.collapsed ? console.groupCollapsed : console.group) || console.info;\n return this._log('group', logLevel, message, [], {method});\n }\n\n groupCollapsed(logLevel, message, opts = {}) {\n return this.group(logLevel, message, Object.assign({}, opts, {collapsed: true}));\n }\n\n groupEnd(logLevel) {\n return this._log('groupEnd', logLevel, '', [], {\n method: console.groupEnd || noop\n });\n }\n\n // EXPERIMENTAL\n\n withGroup(logLevel: number, message: string, func: Function): void {\n this.group(logLevel, message)();\n\n try {\n func();\n } finally {\n this.groupEnd(logLevel)();\n }\n }\n\n trace(): void {\n if (console.trace) {\n console.trace();\n }\n }\n\n protected override _shouldLog(logLevel: unknown): boolean {\n return this.isEnabled() && super._shouldLog(logLevel);\n }\n\n protected override _emit(_type: string, normalized: NormalizedLogArguments): LogFunction {\n const method = normalized.method;\n assert(method);\n\n normalized.total = this.getTotal();\n normalized.delta = this.getDelta();\n // reset delta timer\n this._deltaTs = getHiResTimestamp();\n\n const message = decorateMessage(this.id, normalized.message, normalized);\n\n // Bind console function so that it can be called after being returned\n return method.bind(console, message, ...normalized.args);\n }\n\n _getConfiguration(): Required {\n if (!this._storage.config[this.id]) {\n this._updateConfiguration(DEFAULT_LOG_CONFIGURATION);\n }\n\n // @ts-expect-error guaranteed to be defined\n return this._storage.config[this.id];\n }\n\n _updateConfiguration(configuration: ProbeLogConfiguration): void {\n const currentConfiguration = this._storage.config[this.id] || {\n ...DEFAULT_LOG_CONFIGURATION\n };\n this._storage.setConfiguration({\n [this.id]: {...currentConfiguration, ...configuration}\n });\n }\n}\n\nfunction decorateMessage(id, message, opts) {\n if (typeof message === 'string') {\n const time = opts.time ? leftPad(formatTime(opts.total)) : '';\n message = opts.time ? `${id}: ${time} ${message}` : `${id}: ${message}`;\n message = addColor(message, opts.color, opts.background);\n }\n return message;\n}\n\nfunction getTableHeader(table: Table): string {\n for (const key in table) {\n for (const title in table[key]) {\n return title || 'untitled';\n }\n }\n return 'empty';\n}\n\nexport {normalizeArguments} from './log-utils';\nexport {normalizeLogLevel} from './log-utils';\n","// @ts-nocheck\n/* eslint-disable */\nglobalThis.probe = {};\n","import {ProbeLog} from './loggers/probe-log';\n\n// DEFAULT EXPORT IS A LOG INSTANCE\nexport default new ProbeLog({id: '@probe.gl/log'});\n\n// LOGGING\nexport type {Logger} from './loggers/logger';\nexport {ProbeLog, ProbeLog as Log} from './loggers/probe-log';\nexport {ConsoleLog} from './loggers/console-log';\nexport {BaseLog} from './loggers/base-log';\nexport type {MemoryLogMessage} from './loggers/memory-log';\nexport {MemoryLog} from './loggers/memory-log';\n\n// UTILITIES\nexport {COLOR} from './utils/color';\nexport {addColor} from './utils/color';\nexport {leftPad, rightPad} from './utils/formatters';\nexport {autobind} from './utils/autobind';\nexport {LocalStorage} from './utils/local-storage';\nexport {getHiResTimestamp} from './utils/hi-res-timestamp';\n\nimport './init';\n","// Copyright (c) 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nexport default function getHiResTimestamp(): number {\n let timestamp;\n // Get best timer available.\n if (typeof window !== 'undefined' && window.performance) {\n timestamp = window.performance.now();\n } else if (typeof process !== 'undefined' && process.hrtime) {\n const timeParts = process.hrtime();\n timestamp = timeParts[0] * 1000 + timeParts[1] / 1e6;\n } else {\n timestamp = Date.now();\n }\n\n return timestamp;\n}\n","import getHiResTimestamp from '../utils/hi-res-timestamp';\n\nexport default class Stat {\n readonly name: string;\n readonly type: string | undefined;\n sampleSize: number = 1;\n time: number = 0;\n count: number = 0;\n samples: number = 0;\n lastTiming: number = 0;\n lastSampleTime: number = 0;\n lastSampleCount: number = 0;\n\n _count: number = 0;\n _time: number = 0;\n _samples: number = 0;\n _startTime: number = 0;\n _timerPending: boolean = false;\n\n constructor(name: string, type?: string) {\n this.name = name;\n this.type = type;\n this.reset();\n }\n\n reset(): this {\n this.time = 0;\n this.count = 0;\n this.samples = 0;\n this.lastTiming = 0;\n this.lastSampleTime = 0;\n this.lastSampleCount = 0;\n this._count = 0;\n this._time = 0;\n this._samples = 0;\n this._startTime = 0;\n this._timerPending = false;\n\n return this;\n }\n\n setSampleSize(samples: number): this {\n this.sampleSize = samples;\n return this;\n }\n\n /** Call to increment count (+1) */\n incrementCount(): this {\n this.addCount(1);\n\n return this;\n }\n\n /** Call to decrement count (-1) */\n decrementCount(): this {\n this.subtractCount(1);\n\n return this;\n }\n\n /** Increase count */\n addCount(value: number): this {\n this._count += value;\n this._samples++;\n this._checkSampling();\n\n return this;\n }\n\n /** Decrease count */\n subtractCount(value: number): this {\n this._count -= value;\n this._samples++;\n this._checkSampling();\n\n return this;\n }\n\n /** Add an arbitrary timing and bump the count */\n addTime(time: number): this {\n this._time += time;\n this.lastTiming = time;\n this._samples++;\n this._checkSampling();\n\n return this;\n }\n\n /** Start a timer */\n timeStart(): this {\n this._startTime = getHiResTimestamp();\n this._timerPending = true;\n\n return this;\n }\n\n /** End a timer. Adds to time and bumps the timing count. */\n timeEnd(): this {\n if (!this._timerPending) {\n return this;\n }\n this.addTime(getHiResTimestamp() - this._startTime);\n this._timerPending = false;\n this._checkSampling();\n\n return this;\n }\n\n getSampleAverageCount(): number {\n return this.sampleSize > 0 ? this.lastSampleCount / this.sampleSize : 0;\n }\n\n /** Calculate average time / count for the previous window */\n getSampleAverageTime(): number {\n return this.sampleSize > 0 ? this.lastSampleTime / this.sampleSize : 0;\n }\n\n /** Calculate counts per second for the previous window */\n getSampleHz(): number {\n return this.lastSampleTime > 0 ? this.sampleSize / (this.lastSampleTime / 1000) : 0;\n }\n\n getAverageCount(): number {\n return this.samples > 0 ? this.count / this.samples : 0;\n }\n\n /** Calculate average time / count */\n getAverageTime(): number {\n return this.samples > 0 ? this.time / this.samples : 0;\n }\n\n /** Calculate counts per second */\n getHz(): number {\n return this.time > 0 ? this.samples / (this.time / 1000) : 0;\n }\n\n _checkSampling(): void {\n if (this._samples === this.sampleSize) {\n this.lastSampleTime = this._time;\n this.lastSampleCount = this._count;\n this.count += this._count;\n this.time += this._time;\n this.samples += this._samples;\n this._time = 0;\n this._count = 0;\n this._samples = 0;\n }\n }\n}\n","// probe.gl, MIT license\n\nimport Stat from './stat';\n\ntype TableEntry = {\n time: number;\n count: number;\n average: number;\n hz: number;\n};\n\n/** A \"bag\" of `Stat` objects, can be visualized using `StatsWidget` */\nexport default class Stats {\n readonly id: string;\n readonly stats: Record = {};\n\n constructor(options: {id: string; stats?: Stats | Stat[] | {name: string; type?: string}[]}) {\n this.id = options.id;\n this.stats = {};\n\n this._initializeStats(options.stats);\n\n Object.seal(this);\n }\n\n /** Acquire a stat. Create if it doesn't exist. */\n get(name: string, type: string = 'count'): Stat {\n return this._getOrCreate({name, type});\n }\n\n get size(): number {\n return Object.keys(this.stats).length;\n }\n\n /** Reset all stats */\n reset(): this {\n for (const stat of Object.values(this.stats)) {\n stat.reset();\n }\n\n return this;\n }\n\n forEach(fn: (stat: Stat) => void): void {\n for (const stat of Object.values(this.stats)) {\n fn(stat);\n }\n }\n\n getTable(): Record {\n const table: Record = {};\n this.forEach(stat => {\n table[stat.name] = {\n time: stat.time || 0,\n count: stat.count || 0,\n average: stat.getAverageTime() || 0,\n hz: stat.getHz() || 0\n };\n });\n\n return table;\n }\n\n _initializeStats(stats: Stats | Stat[] | {name: string; type?: string}[] = []): void {\n stats.forEach(stat => this._getOrCreate(stat));\n }\n\n _getOrCreate(stat: Stat | {name: string, type?: string}): Stat {\n const {name, type} = stat;\n let result = this.stats[name];\n if (!result) {\n if (stat instanceof Stat) {\n result = stat;\n } else {\n result = new Stat(name, type);\n }\n this.stats[name] = result;\n }\n return result;\n }\n}\n","export {default as Stats} from './lib/stats';\nexport {default as Stat} from './lib/stat';\n\n// UTILITIES\nexport {default as _getHiResTimestamp} from './utils/hi-res-timestamp';\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Stat, Stats} from '@probe.gl/stats';\n\nconst GPU_TIME_AND_MEMORY_STATS = 'GPU Time and Memory';\nconst GPU_TIME_AND_MEMORY_STAT_ORDER = [\n 'Adapter',\n 'GPU',\n 'GPU Type',\n 'GPU Backend',\n 'Frame Rate',\n 'CPU Time',\n 'GPU Time',\n 'GPU Memory',\n 'Buffer Memory',\n 'Texture Memory',\n 'Referenced Buffer Memory',\n 'Referenced Texture Memory',\n 'Swap Chain Texture'\n] as const;\nconst ORDERED_STATS_CACHE = new WeakMap<\n Stats,\n {orderedStatNames: readonly string[]; statCount: number}\n>();\nconst ORDERED_STAT_NAME_SET_CACHE = new WeakMap>();\n\n/**\n * Helper class managing a collection of probe.gl stats objects\n */\nexport class StatsManager {\n stats = new Map();\n\n getStats(name: string): Stats {\n return this.get(name);\n }\n\n get(name: string): Stats {\n if (!this.stats.has(name)) {\n this.stats.set(name, new Stats({id: name}));\n }\n\n const stats = this.stats.get(name);\n if (name === GPU_TIME_AND_MEMORY_STATS) {\n initializeStats(stats, GPU_TIME_AND_MEMORY_STAT_ORDER);\n }\n\n return stats;\n }\n}\n\n/** Global stats for all luma.gl devices */\nexport const lumaStats: StatsManager = new StatsManager();\n\nfunction initializeStats(stats: Stats, orderedStatNames: readonly string[]): void {\n const statsMap = stats.stats;\n let addedOrderedStat = false;\n for (const statName of orderedStatNames) {\n if (!statsMap[statName]) {\n stats.get(statName);\n addedOrderedStat = true;\n }\n }\n\n const statCount = Object.keys(statsMap).length;\n const cachedStats = ORDERED_STATS_CACHE.get(stats);\n if (\n !addedOrderedStat &&\n cachedStats?.orderedStatNames === orderedStatNames &&\n cachedStats.statCount === statCount\n ) {\n return;\n }\n\n const reorderedStats: Record = {};\n let orderedStatNamesSet = ORDERED_STAT_NAME_SET_CACHE.get(orderedStatNames);\n if (!orderedStatNamesSet) {\n orderedStatNamesSet = new Set(orderedStatNames);\n ORDERED_STAT_NAME_SET_CACHE.set(orderedStatNames, orderedStatNamesSet);\n }\n\n for (const statName of orderedStatNames) {\n if (statsMap[statName]) {\n reorderedStats[statName] = statsMap[statName];\n }\n }\n\n for (const [statName, stat] of Object.entries(statsMap)) {\n if (!orderedStatNamesSet.has(statName)) {\n reorderedStats[statName] = stat;\n }\n }\n\n for (const statName of Object.keys(statsMap)) {\n delete statsMap[statName];\n }\n\n Object.assign(statsMap, reorderedStats);\n ORDERED_STATS_CACHE.set(stats, {orderedStatNames, statCount});\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Log} from '@probe.gl/log';\n\n/** Global log instance */\nexport const log: Log = new Log({id: 'luma.gl'});\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nconst uidCounters: Record = {};\n\n/**\n * Returns a UID.\n * @param id= - Identifier base name\n * @return uid\n **/\nexport function uid(id: string = 'id'): string {\n uidCounters[id] = uidCounters[id] || 1;\n const count = uidCounters[id]++;\n return `${id}-${count}`;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport type {Stat, Stats} from '@probe.gl/stats';\nimport {uid} from '../../utils/uid';\n\nconst CPU_HOTSPOT_PROFILER_MODULE = 'cpu-hotspot-profiler';\nconst RESOURCE_COUNTS_STATS = 'GPU Resource Counts';\nconst LEGACY_RESOURCE_COUNTS_STATS = 'Resource Counts';\nconst GPU_TIME_AND_MEMORY_STATS = 'GPU Time and Memory';\nconst BASE_RESOURCE_COUNT_ORDER = [\n 'Resources',\n 'Buffers',\n 'Textures',\n 'Samplers',\n 'TextureViews',\n 'Framebuffers',\n 'QuerySets',\n 'Shaders',\n 'RenderPipelines',\n 'ComputePipelines',\n 'PipelineLayouts',\n 'VertexArrays',\n 'RenderPasss',\n 'ComputePasss',\n 'CommandEncoders',\n 'CommandBuffers'\n] as const;\nconst WEBGL_RESOURCE_COUNT_ORDER = [\n 'Resources',\n 'Buffers',\n 'Textures',\n 'Samplers',\n 'TextureViews',\n 'Framebuffers',\n 'QuerySets',\n 'Shaders',\n 'RenderPipelines',\n 'SharedRenderPipelines',\n 'ComputePipelines',\n 'PipelineLayouts',\n 'VertexArrays',\n 'RenderPasss',\n 'ComputePasss',\n 'CommandEncoders',\n 'CommandBuffers'\n] as const;\nconst BASE_RESOURCE_COUNT_STAT_ORDER = BASE_RESOURCE_COUNT_ORDER.flatMap(resourceType => [\n `${resourceType} Created`,\n `${resourceType} Active`\n]);\nconst WEBGL_RESOURCE_COUNT_STAT_ORDER = WEBGL_RESOURCE_COUNT_ORDER.flatMap(resourceType => [\n `${resourceType} Created`,\n `${resourceType} Active`\n]);\nconst ORDERED_STATS_CACHE = new WeakMap<\n Stats,\n {orderedStatNames: readonly string[]; statCount: number}\n>();\nconst ORDERED_STAT_NAME_SET_CACHE = new WeakMap>();\n\ntype CpuHotspotProfiler = {\n enabled?: boolean;\n activeDefaultFramebufferAcquireDepth?: number;\n statsBookkeepingTimeMs?: number;\n statsBookkeepingCalls?: number;\n transientCanvasResourceCreates?: number;\n transientCanvasTextureCreates?: number;\n transientCanvasTextureViewCreates?: number;\n transientCanvasSamplerCreates?: number;\n transientCanvasFramebufferCreates?: number;\n};\n\nexport type ResourceProps = {\n /** Name of resource, mainly for debugging purposes. A unique name will be assigned if not provided */\n id?: string;\n /** Handle for the underlying resources (WebGL object or WebGPU handle) */\n handle?: any;\n /** User provided data stored on this resource */\n userData?: {[key: string]: any};\n};\n\n/**\n * Base class for GPU (WebGPU/WebGL) Resources\n */\nexport abstract class Resource {\n /** Default properties for resource */\n static defaultProps: Required = {\n id: 'undefined',\n handle: undefined,\n userData: undefined!\n };\n\n abstract get [Symbol.toStringTag](): string;\n\n toString(): string {\n return `${this[Symbol.toStringTag] || this.constructor.name}:\"${this.id}\"`;\n }\n\n /** props.id, for debugging. */\n id: string;\n /** The props that this resource was created with */\n readonly props: Required;\n /** User data object, reserved for the application */\n readonly userData: Record = {};\n /** The device that this resource is associated with */\n abstract readonly device: Device;\n /** The handle for the underlying resource, e.g. WebGL object or WebGPU handle */\n abstract readonly handle: unknown;\n /** The device that this resource is associated with - TODO can we remove this dup? */\n private _device: Device;\n\n /** Whether this resource has been destroyed */\n destroyed: boolean = false;\n /** For resources that allocate GPU memory */\n private allocatedBytes: number = 0;\n /** Stats bucket currently holding the tracked allocation */\n private allocatedBytesName: string | null = null;\n /** Attached resources will be destroyed when this resource is destroyed. Tracks auto-created \"sub\" resources. */\n private _attachedResources = new Set>();\n\n /**\n * Create a new Resource. Called from Subclass\n */\n constructor(device: Device, props: Props, defaultProps: Required) {\n if (!device) {\n throw new Error('no device');\n }\n this._device = device;\n this.props = selectivelyMerge(props, defaultProps);\n\n const id =\n this.props.id !== 'undefined' ? (this.props.id as string) : uid(this[Symbol.toStringTag]);\n this.props.id = id;\n this.id = id;\n this.userData = this.props.userData || {};\n\n this.addStats();\n }\n\n /**\n * destroy can be called on any resource to release it before it is garbage collected.\n */\n destroy(): void {\n if (this.destroyed) {\n return;\n }\n this.destroyResource();\n }\n\n /** @deprecated Use destroy() */\n delete(): this {\n this.destroy();\n return this;\n }\n\n /**\n * Combines a map of user props and default props, only including props from defaultProps\n * @returns returns a map of overridden default props\n */\n getProps(): object {\n return this.props;\n }\n\n // ATTACHED RESOURCES\n\n /**\n * Attaches a resource. Attached resources are auto destroyed when this resource is destroyed\n * Called automatically when sub resources are auto created but can be called by application\n */\n attachResource(resource: Resource): void {\n this._attachedResources.add(resource);\n }\n\n /**\n * Detach an attached resource. The resource will no longer be auto-destroyed when this resource is destroyed.\n */\n detachResource(resource: Resource): void {\n this._attachedResources.delete(resource);\n }\n\n /**\n * Destroys a resource (only if owned), and removes from the owned (auto-destroy) list for this resource.\n */\n destroyAttachedResource(resource: Resource): void {\n if (this._attachedResources.delete(resource)) {\n resource.destroy();\n }\n }\n\n /** Destroy all owned resources. Make sure the resources are no longer needed before calling. */\n destroyAttachedResources(): void {\n for (const resource of this._attachedResources) {\n resource.destroy();\n }\n // don't remove while we are iterating\n this._attachedResources = new Set>();\n }\n\n // PROTECTED METHODS\n\n /** Perform all destroy steps. Can be called by derived resources when overriding destroy() */\n protected destroyResource(): void {\n if (this.destroyed) {\n return;\n }\n this.destroyAttachedResources();\n this.removeStats();\n this.destroyed = true;\n }\n\n /** Called by .destroy() to track object destruction. Subclass must call if overriding destroy() */\n protected removeStats(): void {\n const profiler = getCpuHotspotProfiler(this._device);\n const startTime = profiler ? getTimestamp() : 0;\n const statsObjects = [\n this._device.statsManager.getStats(RESOURCE_COUNTS_STATS),\n this._device.statsManager.getStats(LEGACY_RESOURCE_COUNTS_STATS)\n ];\n const orderedStatNames = getResourceCountStatOrder(this._device);\n for (const stats of statsObjects) {\n initializeStats(stats, orderedStatNames);\n }\n const name = this.getStatsName();\n for (const stats of statsObjects) {\n stats.get('Resources Active').decrementCount();\n stats.get(`${name}s Active`).decrementCount();\n }\n if (profiler) {\n profiler.statsBookkeepingCalls = (profiler.statsBookkeepingCalls || 0) + 1;\n profiler.statsBookkeepingTimeMs =\n (profiler.statsBookkeepingTimeMs || 0) + (getTimestamp() - startTime);\n }\n }\n\n /** Called by subclass to track memory allocations */\n protected trackAllocatedMemory(bytes: number, name = this.getStatsName()): void {\n const profiler = getCpuHotspotProfiler(this._device);\n const startTime = profiler ? getTimestamp() : 0;\n const stats = this._device.statsManager.getStats(GPU_TIME_AND_MEMORY_STATS);\n\n if (this.allocatedBytes > 0 && this.allocatedBytesName) {\n stats.get('GPU Memory').subtractCount(this.allocatedBytes);\n stats.get(`${this.allocatedBytesName} Memory`).subtractCount(this.allocatedBytes);\n }\n\n stats.get('GPU Memory').addCount(bytes);\n stats.get(`${name} Memory`).addCount(bytes);\n if (profiler) {\n profiler.statsBookkeepingCalls = (profiler.statsBookkeepingCalls || 0) + 1;\n profiler.statsBookkeepingTimeMs =\n (profiler.statsBookkeepingTimeMs || 0) + (getTimestamp() - startTime);\n }\n this.allocatedBytes = bytes;\n this.allocatedBytesName = name;\n }\n\n /** Called by subclass to track handle-backed memory allocations separately from owned allocations */\n protected trackReferencedMemory(bytes: number, name = this.getStatsName()): void {\n this.trackAllocatedMemory(bytes, `Referenced ${name}`);\n }\n\n /** Called by subclass to track memory deallocations */\n protected trackDeallocatedMemory(name = this.getStatsName()): void {\n if (this.allocatedBytes === 0) {\n this.allocatedBytesName = null;\n return;\n }\n\n const profiler = getCpuHotspotProfiler(this._device);\n const startTime = profiler ? getTimestamp() : 0;\n const stats = this._device.statsManager.getStats(GPU_TIME_AND_MEMORY_STATS);\n stats.get('GPU Memory').subtractCount(this.allocatedBytes);\n stats.get(`${this.allocatedBytesName || name} Memory`).subtractCount(this.allocatedBytes);\n if (profiler) {\n profiler.statsBookkeepingCalls = (profiler.statsBookkeepingCalls || 0) + 1;\n profiler.statsBookkeepingTimeMs =\n (profiler.statsBookkeepingTimeMs || 0) + (getTimestamp() - startTime);\n }\n this.allocatedBytes = 0;\n this.allocatedBytesName = null;\n }\n\n /** Called by subclass to deallocate handle-backed memory tracked via trackReferencedMemory() */\n protected trackDeallocatedReferencedMemory(name = this.getStatsName()): void {\n this.trackDeallocatedMemory(`Referenced ${name}`);\n }\n\n /** Called by resource constructor to track object creation */\n private addStats(): void {\n const name = this.getStatsName();\n const profiler = getCpuHotspotProfiler(this._device);\n const startTime = profiler ? getTimestamp() : 0;\n const statsObjects = [\n this._device.statsManager.getStats(RESOURCE_COUNTS_STATS),\n this._device.statsManager.getStats(LEGACY_RESOURCE_COUNTS_STATS)\n ];\n const orderedStatNames = getResourceCountStatOrder(this._device);\n for (const stats of statsObjects) {\n initializeStats(stats, orderedStatNames);\n }\n for (const stats of statsObjects) {\n stats.get('Resources Created').incrementCount();\n stats.get('Resources Active').incrementCount();\n stats.get(`${name}s Created`).incrementCount();\n stats.get(`${name}s Active`).incrementCount();\n }\n if (profiler) {\n profiler.statsBookkeepingCalls = (profiler.statsBookkeepingCalls || 0) + 1;\n profiler.statsBookkeepingTimeMs =\n (profiler.statsBookkeepingTimeMs || 0) + (getTimestamp() - startTime);\n }\n recordTransientCanvasResourceCreate(this._device, name);\n }\n\n /** Canonical resource name used for stats buckets. */\n protected getStatsName(): string {\n return getCanonicalResourceName(this);\n }\n}\n\n/**\n * Combines a map of user props and default props, only including props from defaultProps\n * @param props\n * @param defaultProps\n * @returns returns a map of overridden default props\n */\nfunction selectivelyMerge(props: Props, defaultProps: Required): Required {\n const mergedProps = {...defaultProps};\n for (const key in props) {\n if (props[key] !== undefined) {\n mergedProps[key] = props[key];\n }\n }\n return mergedProps;\n}\n\nfunction initializeStats(stats: Stats, orderedStatNames: readonly string[]): void {\n const statsMap = stats.stats;\n let addedOrderedStat = false;\n for (const statName of orderedStatNames) {\n if (!statsMap[statName]) {\n stats.get(statName);\n addedOrderedStat = true;\n }\n }\n\n const statCount = Object.keys(statsMap).length;\n const cachedStats = ORDERED_STATS_CACHE.get(stats);\n if (\n !addedOrderedStat &&\n cachedStats?.orderedStatNames === orderedStatNames &&\n cachedStats.statCount === statCount\n ) {\n return;\n }\n\n const reorderedStats: Record = {};\n let orderedStatNamesSet = ORDERED_STAT_NAME_SET_CACHE.get(orderedStatNames);\n if (!orderedStatNamesSet) {\n orderedStatNamesSet = new Set(orderedStatNames);\n ORDERED_STAT_NAME_SET_CACHE.set(orderedStatNames, orderedStatNamesSet);\n }\n\n for (const statName of orderedStatNames) {\n if (statsMap[statName]) {\n reorderedStats[statName] = statsMap[statName];\n }\n }\n\n for (const [statName, stat] of Object.entries(statsMap)) {\n if (!orderedStatNamesSet.has(statName)) {\n reorderedStats[statName] = stat;\n }\n }\n\n for (const statName of Object.keys(statsMap)) {\n delete statsMap[statName];\n }\n\n Object.assign(statsMap, reorderedStats);\n ORDERED_STATS_CACHE.set(stats, {orderedStatNames, statCount});\n}\n\nfunction getResourceCountStatOrder(device: Device): readonly string[] {\n return device.type === 'webgl' ? WEBGL_RESOURCE_COUNT_STAT_ORDER : BASE_RESOURCE_COUNT_STAT_ORDER;\n}\n\nfunction getCpuHotspotProfiler(device: Device): CpuHotspotProfiler | null {\n const profiler = device.userData[CPU_HOTSPOT_PROFILER_MODULE] as CpuHotspotProfiler | undefined;\n return profiler?.enabled ? profiler : null;\n}\n\nfunction getTimestamp(): number {\n return globalThis.performance?.now?.() ?? Date.now();\n}\n\nfunction recordTransientCanvasResourceCreate(device: Device, name: string): void {\n const profiler = getCpuHotspotProfiler(device);\n if (!profiler || !profiler.activeDefaultFramebufferAcquireDepth) {\n return;\n }\n\n profiler.transientCanvasResourceCreates = (profiler.transientCanvasResourceCreates || 0) + 1;\n\n switch (name) {\n case 'Texture':\n profiler.transientCanvasTextureCreates = (profiler.transientCanvasTextureCreates || 0) + 1;\n break;\n case 'TextureView':\n profiler.transientCanvasTextureViewCreates =\n (profiler.transientCanvasTextureViewCreates || 0) + 1;\n break;\n case 'Sampler':\n profiler.transientCanvasSamplerCreates = (profiler.transientCanvasSamplerCreates || 0) + 1;\n break;\n case 'Framebuffer':\n profiler.transientCanvasFramebufferCreates =\n (profiler.transientCanvasFramebufferCreates || 0) + 1;\n break;\n default:\n break;\n }\n}\n\nfunction getCanonicalResourceName(resource: Resource): string {\n let prototype = Object.getPrototypeOf(resource);\n\n while (prototype) {\n const parentPrototype = Object.getPrototypeOf(prototype);\n if (!parentPrototype || parentPrototype === Resource.prototype) {\n return (\n getPrototypeToStringTag(prototype) ||\n resource[Symbol.toStringTag] ||\n resource.constructor.name\n );\n }\n prototype = parentPrototype;\n }\n\n return resource[Symbol.toStringTag] || resource.constructor.name;\n}\n\nfunction getPrototypeToStringTag(prototype: object): string | null {\n const descriptor = Object.getOwnPropertyDescriptor(prototype, Symbol.toStringTag);\n if (typeof descriptor?.get === 'function') {\n return descriptor.get.call(prototype);\n }\n if (typeof descriptor?.value === 'string') {\n return descriptor.value;\n }\n return null;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport {Resource, ResourceProps} from './resource';\n\n/** Callback for Buffer.mapAndReadAsync */\nexport type BufferMapCallback = (arrayBuffer: ArrayBuffer, lifetime: 'mapped' | 'copied') => T;\n\nexport type BufferProps = ResourceProps & {\n /** Supply a handle to connect to an existing device-specific buffer */\n handle?: WebGLBuffer;\n /** Specifies how this buffer can be used */\n usage?: number;\n /** Length in bytes of memory to be allocated. If not specified, `byteLength` of `props.data` will be used. */\n byteLength?: number;\n /** Byte offset into the newly created Buffer to store data at */\n byteOffset?: number;\n /** If props.usage includes Buffer.INDEX. Note: uint8 indices are automatically converted to uint16 for WebGPU compatibility */\n indexType?: 'uint8' | 'uint16' | 'uint32';\n /** Data to initialize the buffer with. */\n data?: ArrayBuffer | ArrayBufferView | null;\n /** Callback to initialize data without copy */\n onMapped?: BufferMapCallback;\n};\n\n/** Abstract GPU buffer */\nexport abstract class Buffer extends Resource {\n /** Index buffer */\n static INDEX = 0x0010;\n /** Vertex buffer */\n static VERTEX = 0x0020;\n /** Uniform buffer */\n static UNIFORM = 0x0040;\n /** Storage buffer */\n static STORAGE = 0x0080;\n static INDIRECT = 0x0100;\n static QUERY_RESOLVE = 0x0200;\n\n // Usage Flags\n static MAP_READ = 0x01;\n static MAP_WRITE = 0x02;\n static COPY_SRC = 0x0004;\n static COPY_DST = 0x0008;\n\n override get [Symbol.toStringTag](): string {\n return 'Buffer';\n }\n\n /** The usage with which this buffer was created */\n readonly usage: number;\n /** For index buffers, whether indices are 8, 16 or 32 bit. Note: uint8 indices are automatically converted to uint16 for WebGPU compatibility */\n readonly indexType?: 'uint8' | 'uint16' | 'uint32';\n /** Length of buffer in bytes */\n abstract byteLength: number;\n /** \"Time\" of last update, can be used to check if redraw is needed */\n updateTimestamp: number;\n\n constructor(device: Device, props: BufferProps) {\n const deducedProps = {...props};\n\n // Deduce indexType\n if ((props.usage || 0) & Buffer.INDEX && !props.indexType) {\n if (props.data instanceof Uint32Array) {\n deducedProps.indexType = 'uint32';\n } else if (props.data instanceof Uint16Array) {\n deducedProps.indexType = 'uint16';\n } else if (props.data instanceof Uint8Array) {\n deducedProps.indexType = 'uint8';\n }\n }\n\n // Remove data from props before storing, we don't want to hold on to a big chunk of memory\n delete deducedProps.data;\n\n super(device, deducedProps, Buffer.defaultProps);\n\n this.usage = deducedProps.usage || 0;\n this.indexType = deducedProps.indexType;\n\n // TODO - perhaps this should be set on async write completion?\n this.updateTimestamp = device.incrementTimestamp();\n }\n\n /**\n * Create a copy of this Buffer with new byteLength, with same props but of the specified size.\n * @note Does not copy contents of the cloned Buffer.\n */\n clone(props: {byteLength: number}): Buffer {\n return this.device.createBuffer({...this.props, ...props});\n }\n\n /** Write data to buffer */\n abstract write(\n data: ArrayBufferLike | ArrayBufferView | SharedArrayBuffer,\n byteOffset?: number\n ): void;\n\n abstract mapAndWriteAsync(\n onMapped: BufferMapCallback>,\n byteOffset?: number,\n byteLength?: number\n ): Promise;\n\n /** Reads data asynchronously, returns a copy of the buffer data */\n abstract readAsync(byteOffset?: number, byteLength?: number): Promise;\n\n /** Maps buffer data to CPU memory. Mapped memory is only accessible in the callback */\n abstract mapAndReadAsync(\n onMapped: BufferMapCallback,\n byteOffset?: number,\n byteLength?: number\n ): Promise;\n\n /** Read data synchronously. @note WebGL2 only */\n abstract readSyncWebGL(byteOffset?: number, byteLength?: number): Uint8Array;\n\n // PROTECTED METHODS (INTENDED FOR USE BY OTHER FRAMEWORK CODE ONLY)\n\n /** Max amount of debug data saved. Two vec4's */\n static DEBUG_DATA_MAX_LENGTH = 32;\n\n /** A partial CPU-side copy of the data in this buffer, for debugging purposes */\n debugData: ArrayBuffer = new ArrayBuffer(0);\n\n /** This doesn't handle partial non-zero offset updates correctly */\n protected _setDebugData(\n data: ArrayBufferView | ArrayBufferLike | null,\n _byteOffset: number,\n byteLength: number\n ): void {\n let arrayBufferView: ArrayBufferView | null = null;\n let arrayBuffer: ArrayBufferLike | null;\n if (ArrayBuffer.isView(data)) {\n arrayBufferView = data;\n arrayBuffer = data.buffer;\n } else {\n arrayBuffer = data;\n }\n const debugDataLength = Math.min(\n data ? data.byteLength : byteLength,\n Buffer.DEBUG_DATA_MAX_LENGTH\n );\n if (arrayBuffer === null) {\n this.debugData = new ArrayBuffer(debugDataLength);\n } else {\n const sourceByteOffset = Math.min(arrayBufferView?.byteOffset || 0, arrayBuffer.byteLength);\n const availableByteLength = Math.max(0, arrayBuffer.byteLength - sourceByteOffset);\n const copyByteLength = Math.min(debugDataLength, availableByteLength);\n this.debugData = new Uint8Array(arrayBuffer, sourceByteOffset, copyByteLength).slice().buffer;\n }\n }\n\n static override defaultProps: Required = {\n ...Resource.defaultProps,\n usage: 0, // Buffer.COPY_DST | Buffer.COPY_SRC\n byteLength: 0,\n byteOffset: 0,\n data: null,\n indexType: 'uint16',\n onMapped: undefined!\n };\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {TypedArray, TypedArrayConstructor} from '../../types';\nimport {\n PrimitiveDataType,\n SignedDataType,\n NormalizedDataType,\n DataTypeInfo,\n TypedArrayConstructorT\n} from './data-types';\n\nexport class DataTypeDecoder {\n /**\n * Gets info about a data type constant (signed or normalized)\n * @returns underlying primitive / signed types, byte length, normalization, integer, signed flags\n */\n getDataTypeInfo(type: T): DataTypeInfo {\n const [signedType, primitiveType, byteLength] = NORMALIZED_TYPE_MAP[type];\n const normalized: boolean = type.includes('norm');\n const integer: boolean = !normalized && !type.startsWith('float');\n const signed: boolean = type.startsWith('s');\n return {\n signedType: signedType as DataTypeInfo['signedType'],\n primitiveType: primitiveType as DataTypeInfo['primitiveType'],\n byteLength: byteLength as DataTypeInfo['byteLength'],\n normalized: normalized as DataTypeInfo['normalized'],\n integer: integer as DataTypeInfo['integer'],\n signed: signed as DataTypeInfo['signed']\n // TODO - add webglOnly flag\n };\n }\n\n /** Build a vertex format from a signed data type and a component */\n getNormalizedDataType(signedDataType: SignedDataType): NormalizedDataType {\n const dataType: NormalizedDataType = signedDataType;\n // biome-ignore format: preserve layout\n switch (dataType) {\n case 'uint8': return 'unorm8';\n case 'sint8': return 'snorm8';\n case 'uint16': return 'unorm16';\n case 'sint16': return 'snorm16';\n default: return dataType;\n }\n }\n\n /** Align offset to 1, 2 or 4 elements (4, 8 or 16 bytes) */\n alignTo(size: number, count: number): number {\n // biome-ignore format: preserve layout\n switch (count) {\n case 1: return size; // Pad upwards to even multiple of 2\n case 2: return size + (size % 2); // Pad upwards to even multiple of 2\n default: return size + ((4 - (size % 4)) % 4); // Pad upwards to even multiple of 4\n }\n }\n\n /** Returns the VariableShaderType that corresponds to a typed array */\n getDataType(arrayOrType: TypedArray | TypedArrayConstructor): SignedDataType {\n const Constructor = ArrayBuffer.isView(arrayOrType) ? arrayOrType.constructor : arrayOrType;\n if (Constructor === Uint8ClampedArray) {\n return 'uint8';\n }\n const info = Object.values(NORMALIZED_TYPE_MAP).find(entry => Constructor === entry[4]);\n if (!info) {\n throw new Error(Constructor.name);\n }\n return info[0];\n }\n\n /** Returns the TypedArray that corresponds to a shader data type */\n getTypedArrayConstructor(\n type: NormalizedDataType\n ): TypedArrayConstructorT {\n const [, , , , Constructor] = NORMALIZED_TYPE_MAP[type];\n return Constructor as unknown as TypedArrayConstructorT;\n }\n}\n\n/** Entry point for decoding luma.gl data types */\nexport const dataTypeDecoder = new DataTypeDecoder();\n\nconst NORMALIZED_TYPE_MAP = {\n uint8: ['uint8', 'u32', 1, false, Uint8Array],\n sint8: ['sint8', 'i32', 1, false, Int8Array],\n unorm8: ['uint8', 'f32', 1, true, Uint8Array],\n snorm8: ['sint8', 'f32', 1, true, Int8Array],\n uint16: ['uint16', 'u32', 2, false, Uint16Array],\n sint16: ['sint16', 'i32', 2, false, Int16Array],\n unorm16: ['uint16', 'u32', 2, true, Uint16Array],\n snorm16: ['sint16', 'i32', 2, true, Int16Array],\n float16: ['float16', 'f16', 2, false, Uint16Array],\n float32: ['float32', 'f32', 4, false, Float32Array],\n uint32: ['uint32', 'u32', 4, false, Uint32Array],\n sint32: ['sint32', 'i32', 4, false, Int32Array]\n} satisfies Record<\n NormalizedDataType,\n [\n SignedDataType,\n PrimitiveDataType,\n bytes: 1 | 2 | 4,\n normalized: boolean,\n arrayConstructor: TypedArrayConstructor\n ]\n>;\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {TypedArray} from '../../types';\nimport type {NormalizedDataType, PrimitiveDataType, SignedDataType} from '../data-types/data-types';\nimport type {VertexFormat, VertexFormatInfo} from './vertex-formats';\nimport {dataTypeDecoder} from '../data-types/data-type-decoder';\n\nexport class VertexFormatDecoder {\n /**\n * Decodes a vertex format, returning type, components, byte length and flags (integer, signed, normalized)\n */\n getVertexFormatInfo(format: T): VertexFormatInfo {\n // Strip the -webgl ending if present\n let webglOnly: boolean | undefined;\n if (format.endsWith('-webgl')) {\n format.replace('-webgl', '');\n webglOnly = true;\n }\n // split components from type\n const [type_, count] = format.split('x');\n const type = type_ as NormalizedDataType;\n const components = (count ? parseInt(count) : 1) as 1 | 2 | 3 | 4;\n // decode the type\n const decodedType = dataTypeDecoder.getDataTypeInfo(type);\n const result: VertexFormatInfo = {\n type,\n components,\n byteLength: decodedType.byteLength * components,\n integer: decodedType.integer,\n signed: decodedType.signed,\n normalized: decodedType.normalized\n };\n if (webglOnly) {\n result.webglOnly = true;\n }\n return result;\n }\n\n /** Build a vertex format from a signed data type and a component */\n makeVertexFormat(\n signedDataType: SignedDataType,\n components: 1 | 2 | 3 | 4,\n normalized?: boolean\n ): VertexFormat {\n const dataType: NormalizedDataType = normalized\n ? dataTypeDecoder.getNormalizedDataType(signedDataType)\n : signedDataType;\n\n switch (dataType) {\n // Special cases for WebGL-only x3 formats that WebGPU does not support.\n case 'unorm8':\n if (components === 1) {\n return 'unorm8';\n }\n if (components === 3) {\n return 'unorm8x3-webgl';\n }\n return `${dataType}x${components}`;\n\n case 'snorm8':\n if (components === 1) {\n return 'snorm8';\n }\n if (components === 3) {\n return 'snorm8x3-webgl';\n }\n return `${dataType}x${components}`;\n\n case 'uint8':\n case 'sint8':\n // WebGPU 8 bit formats must be aligned to 16 bit boundaries.\n if (components === 1 || components === 3) {\n throw new Error(`size: ${components}`);\n }\n return `${dataType}x${components}`;\n\n case 'uint16':\n if (components === 1) {\n return 'uint16';\n }\n if (components === 3) {\n return 'uint16x3-webgl';\n }\n return `${dataType}x${components}`;\n\n case 'sint16':\n if (components === 1) {\n return 'sint16';\n }\n if (components === 3) {\n return 'sint16x3-webgl';\n }\n return `${dataType}x${components}`;\n\n case 'unorm16':\n if (components === 1) {\n return 'unorm16';\n }\n if (components === 3) {\n return 'unorm16x3-webgl';\n }\n return `${dataType}x${components}`;\n\n case 'snorm16':\n if (components === 1) {\n return 'snorm16';\n }\n if (components === 3) {\n return 'snorm16x3-webgl';\n }\n return `${dataType}x${components}`;\n\n case 'float16':\n // WebGPU 16 bit formats must be aligned to 32 bit boundaries\n if (components === 1 || components === 3) {\n throw new Error(`size: ${components}`);\n }\n return `${dataType}x${components}`;\n\n default:\n return components === 1 ? dataType : `${dataType}x${components}`;\n }\n }\n\n /** Get the vertex format for an attribute with TypedArray and size */\n getVertexFormatFromAttribute(\n typedArray: TypedArray,\n size: number,\n normalized?: boolean\n ): VertexFormat {\n if (!size || size > 4) {\n throw new Error(`size ${size}`);\n }\n\n const components = size as 1 | 2 | 3 | 4;\n const signedDataType = dataTypeDecoder.getDataType(typedArray);\n return this.makeVertexFormat(signedDataType, components, normalized);\n }\n\n /**\n * Return a \"default\" vertex format for a certain shader data type\n * The simplest vertex format that matches the shader attribute's data type\n */\n\n getCompatibleVertexFormat(opts: {\n primitiveType: PrimitiveDataType;\n components: 1 | 2 | 3 | 4;\n }): VertexFormat {\n let vertexType: NormalizedDataType;\n switch (opts.primitiveType) {\n case 'f32':\n vertexType = 'float32';\n break;\n case 'i32':\n vertexType = 'sint32';\n break;\n case 'u32':\n vertexType = 'uint32';\n break;\n case 'f16':\n return opts.components <= 2 ? 'float16x2' : 'float16x4';\n }\n\n // TODO logic does not work for float16\n if (opts.components === 1) {\n return vertexType;\n }\n return `${vertexType}x${opts.components}`;\n }\n}\n\n/** Decoder for luma.gl vertex types */\nexport const vertexFormatDecoder = new VertexFormatDecoder();\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {\n TextureFormat,\n TextureFormatColorUncompressed,\n TextureFormatDepthStencil,\n TextureFeature,\n TextureFormatInfo,\n TextureFormatCompressed\n} from './texture-formats';\n/* eslint-disable camelcase */\n\n// Define local device feature strings to optimize minification\nconst texture_compression_bc: TextureFeature = 'texture-compression-bc';\nconst texture_compression_astc: TextureFeature = 'texture-compression-astc';\nconst texture_compression_etc2: TextureFeature = 'texture-compression-etc2';\nconst texture_compression_etc1_webgl: TextureFeature = 'texture-compression-etc1-webgl';\nconst texture_compression_pvrtc_webgl: TextureFeature = 'texture-compression-pvrtc-webgl';\nconst texture_compression_atc_webgl: TextureFeature = 'texture-compression-atc-webgl';\n\nconst float32_renderable: TextureFeature = 'float32-renderable-webgl';\nconst float16_renderable: TextureFeature = 'float16-renderable-webgl';\nconst rgb9e5ufloat_renderable: TextureFeature = 'rgb9e5ufloat-renderable-webgl';\nconst snorm8_renderable: TextureFeature = 'snorm8-renderable-webgl';\nconst norm16_webgl: TextureFeature = 'norm16-webgl';\nconst norm16_renderable: TextureFeature = 'norm16-renderable-webgl';\nconst snorm16_renderable: TextureFeature = 'snorm16-renderable-webgl';\n\nconst float32_filterable: TextureFeature = 'float32-filterable';\nconst float16_filterable: TextureFeature = 'float16-filterable-webgl';\n\n/** https://www.w3.org/TR/webgpu/#texture-format-caps */\n\n/** Internal type representing texture capabilities */\ntype TextureFormatDefinition = Partial & {\n /** for compressed texture formats */\n f?: TextureFeature;\n /** renderable if feature is present. false means the spec does not support this format */\n render?: TextureFeature | false;\n /** filterable if feature is present. false means the spec does not support this format */\n filter?: TextureFeature | false;\n blend?: TextureFeature | false;\n store?: TextureFeature | false;\n\n /** (bytes per pixel), for memory usage calculations. */\n b?: number;\n /** channels */\n c?: number;\n bpp?: number;\n /** packed */\n p?: number;\n\n /** If not supported on WebGPU */\n wgpu?: false;\n};\n\nexport function getTextureFormatDefinition(format: TextureFormat): TextureFormatDefinition {\n const info = TEXTURE_FORMAT_TABLE[format];\n if (!info) {\n throw new Error(`Unsupported texture format ${format}`);\n }\n return info;\n}\n\nexport function getTextureFormatTable(): Readonly> {\n return TEXTURE_FORMAT_TABLE;\n}\n\n// biome-ignore format: preserve layout\nconst TEXTURE_FORMAT_COLOR_DEPTH_TABLE: Readonly> = {\n // 8-bit formats\n 'r8unorm': {},\n 'rg8unorm': {},\n 'rgb8unorm-webgl': {},\n 'rgba8unorm': {},\n 'rgba8unorm-srgb': {},\n\n 'r8snorm': {render: snorm8_renderable},\n 'rg8snorm': {render: snorm8_renderable},\n 'rgb8snorm-webgl': {},\n 'rgba8snorm': {render: snorm8_renderable},\n\n 'r8uint': {},\n 'rg8uint': {},\n 'rgba8uint': {},\n\n 'r8sint': {},\n 'rg8sint': {},\n 'rgba8sint': {},\n\n 'bgra8unorm': {},\n 'bgra8unorm-srgb': {},\n\n\n 'r16unorm': {f: norm16_webgl, render: norm16_renderable},\n 'rg16unorm': {f: norm16_webgl, render: norm16_renderable},\n 'rgb16unorm-webgl': {f: norm16_webgl, render: false}, // rgb not renderable\n 'rgba16unorm': {f: norm16_webgl, render: norm16_renderable},\n\n 'r16snorm': {f: norm16_webgl, render: snorm16_renderable},\n 'rg16snorm': {f: norm16_webgl, render: snorm16_renderable},\n 'rgb16snorm-webgl': {f: norm16_webgl, render: false}, // rgb not renderable\n 'rgba16snorm': {f: norm16_webgl, render: snorm16_renderable},\n\n 'r16uint': {},\n 'rg16uint': {},\n 'rgba16uint': {},\n\n 'r16sint': {},\n 'rg16sint': {},\n 'rgba16sint': {},\n\n 'r16float': {render: float16_renderable, filter: 'float16-filterable-webgl'},\n 'rg16float': {render: float16_renderable, filter: float16_filterable},\n 'rgba16float': {render: float16_renderable, filter: float16_filterable},\n\n 'r32uint': {},\n 'rg32uint': {},\n 'rgba32uint': {},\n\n 'r32sint': {},\n 'rg32sint': {},\n 'rgba32sint': {},\n\n 'r32float': {render: float32_renderable, filter: float32_filterable},\n 'rg32float': {render: false, filter: float32_filterable},\n 'rgb32float-webgl': {render: float32_renderable, filter: float32_filterable},\n 'rgba32float': {render: float32_renderable, filter: float32_filterable},\n\n // Packed 16-bit formats\n 'rgba4unorm-webgl': {channels: 'rgba', bitsPerChannel: [4, 4, 4, 4], packed: true},\n 'rgb565unorm-webgl': {channels: 'rgb', bitsPerChannel: [5, 6, 5, 0], packed: true},\n 'rgb5a1unorm-webgl': {channels: 'rgba', bitsPerChannel: [5, 5, 5, 1], packed: true},\n\n // Packed 32 bit formats\n 'rgb9e5ufloat': {channels: 'rgb', packed: true, render: rgb9e5ufloat_renderable}, // , filter: true},\n 'rg11b10ufloat': {channels: 'rgb', bitsPerChannel: [11, 11, 10, 0], packed: true, p: 1,render: float32_renderable},\n 'rgb10a2unorm': {channels: 'rgba', bitsPerChannel: [10, 10, 10, 2], packed: true, p: 1},\n 'rgb10a2uint': {channels: 'rgba', bitsPerChannel: [10, 10, 10, 2], packed: true, p: 1},\n\n // Depth/stencil Formats\n \n // Depth and stencil formats\n stencil8: {attachment: 'stencil', bitsPerChannel: [8, 0, 0, 0], dataType: 'uint8'},\n 'depth16unorm': {attachment: 'depth', bitsPerChannel: [16, 0, 0, 0], dataType: 'uint16'},\n 'depth24plus': {attachment: 'depth', bitsPerChannel: [24, 0, 0, 0], dataType: 'uint32'},\n 'depth32float': {attachment: 'depth', bitsPerChannel: [32, 0, 0, 0], dataType: 'float32'},\n // The depth component of the \"depth24plus\" and \"depth24plus-stencil8\" formats may be implemented as either a 24-bit depth value or a \"depth32float\" value.\n 'depth24plus-stencil8': {attachment: 'depth-stencil', bitsPerChannel: [24, 8, 0, 0], packed: true},\n // \"depth32float-stencil8\" feature\n 'depth32float-stencil8': {attachment: 'depth-stencil', bitsPerChannel: [32, 8, 0, 0], packed: true},\n};\n\n// biome-ignore format: preserve layout\nconst TEXTURE_FORMAT_COMPRESSED_TABLE: Readonly> = {\n\n // BC compressed formats: check device.features.has(\"texture-compression-bc\");\n\n 'bc1-rgb-unorm-webgl': {f: texture_compression_bc},\n 'bc1-rgb-unorm-srgb-webgl': {f: texture_compression_bc},\n\n 'bc1-rgba-unorm': {f: texture_compression_bc},\n 'bc1-rgba-unorm-srgb': {f: texture_compression_bc},\n 'bc2-rgba-unorm': {f: texture_compression_bc},\n 'bc2-rgba-unorm-srgb': {f: texture_compression_bc},\n 'bc3-rgba-unorm': {f: texture_compression_bc},\n 'bc3-rgba-unorm-srgb': {f: texture_compression_bc},\n 'bc4-r-unorm': {f: texture_compression_bc},\n 'bc4-r-snorm': {f: texture_compression_bc},\n 'bc5-rg-unorm': {f: texture_compression_bc},\n 'bc5-rg-snorm': {f: texture_compression_bc},\n 'bc6h-rgb-ufloat': {f: texture_compression_bc},\n 'bc6h-rgb-float': {f: texture_compression_bc},\n 'bc7-rgba-unorm': {f: texture_compression_bc},\n 'bc7-rgba-unorm-srgb': {f: texture_compression_bc},\n\n // WEBGL_compressed_texture_etc: device.features.has(\"texture-compression-etc2\")\n // Note: Supposedly guaranteed availability compressed formats in WebGL2, but through CPU decompression\n\n 'etc2-rgb8unorm': {f: texture_compression_etc2},\n 'etc2-rgb8unorm-srgb': {f: texture_compression_etc2},\n 'etc2-rgb8a1unorm': {f: texture_compression_etc2},\n 'etc2-rgb8a1unorm-srgb': {f: texture_compression_etc2},\n 'etc2-rgba8unorm': {f: texture_compression_etc2},\n 'etc2-rgba8unorm-srgb': {f: texture_compression_etc2},\n\n 'eac-r11unorm': {f: texture_compression_etc2},\n 'eac-r11snorm': {f: texture_compression_etc2},\n 'eac-rg11unorm': {f: texture_compression_etc2},\n 'eac-rg11snorm': {f: texture_compression_etc2},\n\n // X_ASTC compressed formats: device.features.has(\"texture-compression-astc\")\n\n 'astc-4x4-unorm': {f: texture_compression_astc},\n 'astc-4x4-unorm-srgb': {f: texture_compression_astc},\n 'astc-5x4-unorm': {f: texture_compression_astc},\n 'astc-5x4-unorm-srgb': {f: texture_compression_astc},\n 'astc-5x5-unorm': {f: texture_compression_astc},\n 'astc-5x5-unorm-srgb': {f: texture_compression_astc},\n 'astc-6x5-unorm': {f: texture_compression_astc},\n 'astc-6x5-unorm-srgb': {f: texture_compression_astc},\n 'astc-6x6-unorm': {f: texture_compression_astc},\n 'astc-6x6-unorm-srgb': {f: texture_compression_astc},\n 'astc-8x5-unorm': {f: texture_compression_astc},\n 'astc-8x5-unorm-srgb': {f: texture_compression_astc},\n 'astc-8x6-unorm': {f: texture_compression_astc},\n 'astc-8x6-unorm-srgb': {f: texture_compression_astc},\n 'astc-8x8-unorm': {f: texture_compression_astc},\n 'astc-8x8-unorm-srgb': {f: texture_compression_astc},\n 'astc-10x5-unorm': {f: texture_compression_astc},\n 'astc-10x5-unorm-srgb': {f: texture_compression_astc},\n 'astc-10x6-unorm': {f: texture_compression_astc},\n 'astc-10x6-unorm-srgb': {f: texture_compression_astc},\n 'astc-10x8-unorm': {f: texture_compression_astc},\n 'astc-10x8-unorm-srgb': {f: texture_compression_astc},\n 'astc-10x10-unorm': {f: texture_compression_astc},\n 'astc-10x10-unorm-srgb': {f: texture_compression_astc},\n 'astc-12x10-unorm': {f: texture_compression_astc},\n 'astc-12x10-unorm-srgb': {f: texture_compression_astc},\n 'astc-12x12-unorm': {f: texture_compression_astc},\n 'astc-12x12-unorm-srgb': {f: texture_compression_astc},\n\n // WEBGL_compressed_texture_pvrtc\n\n 'pvrtc-rgb4unorm-webgl': {f: texture_compression_pvrtc_webgl},\n 'pvrtc-rgba4unorm-webgl': {f: texture_compression_pvrtc_webgl},\n 'pvrtc-rgb2unorm-webgl': {f: texture_compression_pvrtc_webgl},\n 'pvrtc-rgba2unorm-webgl': {f: texture_compression_pvrtc_webgl},\n\n // WEBGL_compressed_texture_etc1\n\n 'etc1-rbg-unorm-webgl': {f: texture_compression_etc1_webgl},\n\n // WEBGL_compressed_texture_atc\n\n 'atc-rgb-unorm-webgl': {f: texture_compression_atc_webgl},\n 'atc-rgba-unorm-webgl': {f: texture_compression_atc_webgl},\n 'atc-rgbai-unorm-webgl': {f: texture_compression_atc_webgl}\n};\n\nexport const TEXTURE_FORMAT_TABLE: Readonly> = {\n ...TEXTURE_FORMAT_COLOR_DEPTH_TABLE,\n ...TEXTURE_FORMAT_COMPRESSED_TABLE\n};\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {NormalizedDataType} from '../data-types/data-types';\nimport {dataTypeDecoder} from '../data-types/data-type-decoder';\nimport type {\n TextureFormat,\n TextureFormatCompressed,\n TextureFormatInfo,\n TextureFormatCapabilities,\n TextureFormatColor,\n TextureMemoryLayout,\n TextureFormatDepthStencil\n} from './texture-formats';\nimport {getTextureFormatDefinition} from './texture-format-table';\n\nconst RGB_FORMAT_REGEX = /^(r|rg|rgb|rgba|bgra)([0-9]*)([a-z]*)(-srgb)?(-webgl)?$/;\nconst COLOR_FORMAT_PREFIXES = ['rgb', 'rgba', 'bgra'];\nconst DEPTH_FORMAT_PREFIXES = ['depth', 'stencil'];\n// biome-ignore format: preserve layout\nconst COMPRESSED_TEXTURE_FORMAT_PREFIXES = [\n 'bc1', 'bc2', 'bc3', 'bc4', 'bc5', 'bc6', 'bc7', 'etc1', 'etc2', 'eac', 'atc', 'astc', 'pvrtc'\n];\n\n// HELPERS - MEMORY LAYOUT\n\n/** Options to calculate a texture layout */\nexport type TextureMemoryLayoutOptions = {\n /** Number of bytes per pixel */\n format: TextureFormat;\n /** Width of the texture in pixels */\n width: number;\n /** Height of the texture in pixels */\n height: number;\n /** Number of images in the texture */\n depth: number;\n /** Alignment of each row */\n byteAlignment: number;\n};\n\n/** Class that helps applications work with texture formats */\nexport class TextureFormatDecoder {\n /** Checks if a texture format is color */\n isColor(format: TextureFormat): format is TextureFormatColor {\n return COLOR_FORMAT_PREFIXES.some(prefix => format.startsWith(prefix));\n }\n\n /** Checks if a texture format is depth or stencil */\n isDepthStencil(format: TextureFormat): format is TextureFormatDepthStencil {\n return DEPTH_FORMAT_PREFIXES.some(prefix => format.startsWith(prefix));\n }\n\n /** Checks if a texture format is compressed */\n isCompressed(format: TextureFormat): format is TextureFormatCompressed {\n return COMPRESSED_TEXTURE_FORMAT_PREFIXES.some(prefix => format.startsWith(prefix));\n }\n\n /** Returns information about a texture format, e.g. attachment type, components, byte length and flags (integer, signed, normalized) */\n getInfo(format: TextureFormat): TextureFormatInfo {\n return getTextureFormatInfo(format);\n }\n\n /** \"static\" capabilities of a texture format. @note Needs to be adjusted against current device */\n getCapabilities(format: TextureFormat): TextureFormatCapabilities {\n return getTextureFormatCapabilities(format);\n }\n\n /** Computes the memory layout for a texture, in particular including row byte alignment */\n computeMemoryLayout(opts: TextureMemoryLayoutOptions): TextureMemoryLayout {\n return computeTextureMemoryLayout(opts);\n }\n}\n\n/** Decoder for luma.gl texture types */\nexport const textureFormatDecoder = new TextureFormatDecoder();\n\n// HELPERS - MEMORY LAYOUT\n\n/** Get the memory layout of a texture */\nfunction computeTextureMemoryLayout({\n format,\n width,\n height,\n depth,\n byteAlignment\n}: TextureMemoryLayoutOptions): TextureMemoryLayout {\n const formatInfo = textureFormatDecoder.getInfo(format);\n const {\n bytesPerPixel,\n bytesPerBlock = bytesPerPixel,\n blockWidth = 1,\n blockHeight = 1,\n compressed = false\n } = formatInfo;\n const blockColumns = compressed ? Math.ceil(width / blockWidth) : width;\n const blockRows = compressed ? Math.ceil(height / blockHeight) : height;\n // byteAlignment comes from the backend/call site. WebGPU buffer copies use 256, queue.writeTexture uses 1.\n const unpaddedBytesPerRow = blockColumns * bytesPerBlock;\n const bytesPerRow = Math.ceil(unpaddedBytesPerRow / byteAlignment) * byteAlignment;\n const rowsPerImage = blockRows;\n const byteLength = bytesPerRow * rowsPerImage * depth;\n\n return {\n bytesPerPixel,\n bytesPerRow,\n rowsPerImage,\n depthOrArrayLayers: depth,\n bytesPerImage: bytesPerRow * rowsPerImage,\n byteLength\n };\n}\n\n// HELPERS - CAPABILITIES\n\nfunction getTextureFormatCapabilities(format: TextureFormat): TextureFormatCapabilities {\n const info = getTextureFormatDefinition(format);\n\n const formatCapabilities: Required = {\n format,\n create: info.f ?? true,\n render: info.render ?? true,\n filter: info.filter ?? true,\n blend: info.blend ?? true,\n store: info.store ?? true\n };\n\n const formatInfo = getTextureFormatInfo(format);\n const isDepthStencil = format.startsWith('depth') || format.startsWith('stencil');\n const isSigned = formatInfo?.signed;\n const isInteger = formatInfo?.integer;\n const isWebGLSpecific = formatInfo?.webgl;\n const isCompressed = Boolean(formatInfo?.compressed);\n\n // Only uncompressed color formats can be used as color-renderable attachments.\n formatCapabilities.render &&= !isDepthStencil && !isCompressed;\n // signed and integer formats are not filterable\n formatCapabilities.filter &&= !isDepthStencil && !isSigned && !isInteger && !isWebGLSpecific;\n\n return formatCapabilities;\n}\n\n// HELPER - FORMAT INFO\n\n/**\n * Decodes a texture format, returning e.g. attatchment type, components, byte length and flags (integer, signed, normalized)\n */\nexport function getTextureFormatInfo(format: TextureFormat): TextureFormatInfo {\n let formatInfo: TextureFormatInfo = getTextureFormatInfoUsingTable(format);\n\n if (textureFormatDecoder.isCompressed(format)) {\n formatInfo.channels = 'rgb';\n formatInfo.components = 3;\n formatInfo.bytesPerPixel = 1;\n formatInfo.srgb = false;\n formatInfo.compressed = true;\n formatInfo.bytesPerBlock = getCompressedTextureBlockByteLength(format);\n\n const blockSize = getCompressedTextureBlockSize(format);\n if (blockSize) {\n formatInfo.blockWidth = blockSize.blockWidth;\n formatInfo.blockHeight = blockSize.blockHeight;\n }\n }\n\n // Fill in missing information that can be derived from the format string\n const matches = !formatInfo.packed ? RGB_FORMAT_REGEX.exec(format as string) : null;\n if (matches) {\n const [, channels, length, type, srgb, suffix] = matches;\n const dataType = `${type}${length}` as NormalizedDataType;\n const decodedType = dataTypeDecoder.getDataTypeInfo(dataType);\n const bits = decodedType.byteLength * 8;\n const components = (channels?.length ?? 1) as 1 | 2 | 3 | 4;\n const bitsPerChannel: [number, number, number, number] = [\n bits,\n components >= 2 ? bits : 0,\n components >= 3 ? bits : 0,\n components >= 4 ? bits : 0\n ];\n\n formatInfo = {\n format,\n attachment: formatInfo.attachment,\n dataType: decodedType.signedType,\n components,\n channels: channels as 'r' | 'rg' | 'rgb' | 'rgba',\n integer: decodedType.integer,\n signed: decodedType.signed,\n normalized: decodedType.normalized,\n bitsPerChannel,\n bytesPerPixel: decodedType.byteLength * components,\n packed: formatInfo.packed,\n srgb: formatInfo.srgb\n };\n\n if (suffix === '-webgl') {\n formatInfo.webgl = true;\n }\n // dataType - overwritten by decodedType\n if (srgb === '-srgb') {\n formatInfo.srgb = true;\n }\n }\n\n if (format.endsWith('-webgl')) {\n formatInfo.webgl = true;\n }\n if (format.endsWith('-srgb')) {\n formatInfo.srgb = true;\n }\n\n return formatInfo;\n}\n\n/** Decode texture format info from the table */\nfunction getTextureFormatInfoUsingTable(format: TextureFormat): TextureFormatInfo {\n const info = getTextureFormatDefinition(format);\n\n const bytesPerPixel = info.bytesPerPixel || 1;\n const bitsPerChannel = info.bitsPerChannel || [8, 8, 8, 8];\n delete info.bitsPerChannel;\n delete info.bytesPerPixel;\n delete info.f;\n delete info.render;\n delete info.filter;\n delete info.blend;\n delete info.store;\n\n const formatInfo: TextureFormatInfo = {\n ...info,\n format,\n attachment: info.attachment || 'color',\n channels: info.channels || 'r',\n components: (info.components || info.channels?.length || 1) as 1 | 2 | 3 | 4,\n bytesPerPixel,\n bitsPerChannel,\n dataType: info.dataType || 'uint8',\n srgb: info.srgb ?? false,\n packed: info.packed ?? false,\n webgl: info.webgl ?? false,\n integer: info.integer ?? false,\n signed: info.signed ?? false,\n normalized: info.normalized ?? false,\n compressed: info.compressed ?? false\n };\n\n return formatInfo;\n}\n\n/** Parses ASTC block widths from format string */\nfunction getCompressedTextureBlockSize(\n format: TextureFormatCompressed\n): {blockWidth: number; blockHeight: number} | null {\n const REGEX = /.*-(\\d+)x(\\d+)-.*/;\n const matches = REGEX.exec(format as string);\n if (matches) {\n const [, blockWidth, blockHeight] = matches;\n return {blockWidth: Number(blockWidth), blockHeight: Number(blockHeight)};\n }\n\n if (\n format.startsWith('bc') ||\n format.startsWith('etc1') ||\n format.startsWith('etc2') ||\n format.startsWith('eac') ||\n format.startsWith('atc')\n ) {\n return {blockWidth: 4, blockHeight: 4};\n }\n\n if (format.startsWith('pvrtc-rgb4') || format.startsWith('pvrtc-rgba4')) {\n return {blockWidth: 4, blockHeight: 4};\n }\n\n if (format.startsWith('pvrtc-rgb2') || format.startsWith('pvrtc-rgba2')) {\n return {blockWidth: 8, blockHeight: 4};\n }\n\n return null;\n}\n\nfunction getCompressedTextureBlockByteLength(format: TextureFormatCompressed): number {\n if (\n format.startsWith('bc1') ||\n format.startsWith('bc4') ||\n format.startsWith('etc1') ||\n format.startsWith('etc2-rgb8') ||\n format.startsWith('etc2-rgb8a1') ||\n format.startsWith('eac-r11') ||\n format === 'atc-rgb-unorm-webgl'\n ) {\n return 8;\n }\n\n if (\n format.startsWith('bc2') ||\n format.startsWith('bc3') ||\n format.startsWith('bc5') ||\n format.startsWith('bc6h') ||\n format.startsWith('bc7') ||\n format.startsWith('etc2-rgba8') ||\n format.startsWith('eac-rg11') ||\n format.startsWith('astc') ||\n format === 'atc-rgba-unorm-webgl' ||\n format === 'atc-rgbai-unorm-webgl'\n ) {\n return 16;\n }\n\n if (format.startsWith('pvrtc')) {\n return 8;\n }\n\n return 16;\n}\n\n/*\n'r8unorm':\t{s: \"float\"}, // \t✓\t✓\t✓\t},\n'r8snorm':\t{s: \"float\"}, // \t\t✓\t\t},\n'r8uint':\t{s: \"uint\"}, // \t✓\t✓\t\t},\n'r8sint':\t{s: \"sint\"}, // \t✓\t✓\t\t},\n'rg8unorm':\t{s: \"float\"}, // \t✓\t✓\t✓\t},\n'rg8snorm':\t{s: \"float\"}, // \t\t✓\t\t},\n'rg8uint':\t{s: \"uint\"}, // \t✓\t✓\t\t},\n'rg8sint':\t{s: \"sint\"}, // \t✓\t✓\t\t},\n'rgba8unorm':\t{s: \"float\"}, // \t✓\t✓\t✓\t✓},\n'rgba8unorm-srgb': {s: \"float\"}, // \t✓\t✓\t✓\t},\n'rgba8snorm':\t{s: \"float\"}, // \t\t✓\t\t✓},\n'rgba8uint':\t{s: \"uint\"}, // \t✓\t✓\t\t✓},\n'rgba8sint':\t{s: \"sint\"}, // \t✓\t✓\t\t✓},\n'bgra8unorm':\t{s: \"float\"}, // \t✓\t✓\t✓\t},\n'bgra8unorm-srgb': {s: \"float\"}, // \t✓\t✓\t✓\t},\n// 16-bit per component\t\t\t\t\t\n'r16uint': {s: \"uint\"}, // \t✓\t✓\t\t},\n'r16sint': {s: \"sint\"}, // \t✓\t✓\t\t},\n'r16float': {s: \"float\"}, // \t✓\t✓\t✓\t},\n'rg16uint': {s: \"uint\"}, // \t✓\t✓\t\t},\n'rg16sint': {s: \"sint\"}, // \t✓\t✓\t\t},\n'rg16float': {s: \"float\"}, // \t✓\t✓\t✓\t},\n'rgba16uint': {s: \"uint\"}, // \t✓\t✓\t\t✓},\n'rgba16sint': {s: \"sint\"}, // \t✓\t✓\t\t✓},\n'rgba16float': {s: \"float\"}, // \t✓\t✓\t✓\t✓},\n// 32-bit per component\t\t\t\t\t\n'r32uint': {s: \"uint\"}, // \t✓\t\t\t✓},\n'r32sint': {s: \"sint\"}, // \t✓\t\t\t✓},\n'r32float': {\"unfilterable-float\"\t✓\t✓\t\t✓},\n'rg32uint': {s: \"uint\"}, // \t✓\t\t\t✓},\n'rg32sint': {s: \"sint\"}, // \t✓\t\t\t✓},\n'rg32float': {\"unfilterable-float\"\t✓\t\t\t✓},\n'rgba32uint': {s: \"uint\"}, // \t✓\t\t\t✓},\n'rgba32sint': {s: \"sint\"}, // \t✓\t\t\t✓},\n'rgba32float': {\"unfilterable-float\"\t✓\t\t\t✓},\n// mixed component width\t\t\t\t\t\n'rgb10a2unorm': {s: \"float\"}, // \t✓\t✓\t✓\t}\n'rg11b10ufloat': {s: \"float\"}, // \t\t✓\t\t}\n// Format\tBytes per texel\tAspect\tGPUTextureSampleType\tValid image copy source\tValid image copy destination\n'stencil8': {1 − 4\tstencil\t\"uint\"\t✓}\n'depth16unorm': {2\tdepth\t\"depth\"\t✓}\n'depth24plus': {4\tdepth\t\"depth\"\t✗}\n'depth24plus': {stencil8\t4 − 8\tdepth\t\"depth\"\t✗}\n'stencil': {s: \"uint\"}, // \t✓}\n'depth32float': {4\tdepth\t\"depth\"\t✓\t✗}\n'depth24unorm': {stencil8\t4\tdepth\t\"depth\"\t✗}\n'stencil': {s: \"uint\"}, // \t✓}\n'depth32float': {stencil8}\n\n// Format\tBytes per block\tGPUTextureSampleType\tBlock Size\tFeature\n'rgb9e5ufloat': {c: 4, s: \"float\",\tbpp: 4/(1*1)},\n\n'bc1-rgba-unorm': {c: 4. s: \"float\", bpp: 8/(4 * 4) f: 'texture-compression-bc'},\n'bc1-rgba-unorm-srgb': {c: 4. s: \"float\", bpp: 8/(4 * 4) f: 'texture-compression-bc'},\n'bc2-rgba-unorm': {c: 4. s: \"float\", bpp: 16/(4 * 4) f: 'texture-compression-bc'},\n'bc2-rgba-unorm-srgb': {c: 4. s: \"float\", bpp: 16/(4 * 4) f: 'texture-compression-bc'},\n'bc3-rgba-unorm': {c: 4. s: \"float\", bpp: 16/(4 * 4) f: 'texture-compression-bc'},\n'bc3-rgba-unorm-srgb': {c: 4. s: \"float\", bpp: 16/(4 * 4) f: 'texture-compression-bc'},\n'bc4-r-unorm': {c: 1. s: \"float\", bpp: 8/(4 * 4) f: 'texture-compression-bc'},\n'bc4-r-snorm': {c: 1. s: \"float\", bpp: 8/(4 * 4) f: 'texture-compression-bc'},\n'bc5-rg-unorm': {c: 2. s: \"float\", bpp: 16/(4 * 4) f: 'texture-compression-bc'},\n'bc5-rg-snorm': { },\n'bc6h-rgb-ufloat': {\t16 },\n'bc6h-rgb-float': { },\n'bc7-rgba-unorm': {\t16 },\n'bc7-rgba-unorm-srgb': { },\n\n'etc2-rgb8unorm': {\t8\t\"float\"\t4 × 4\ttexture-compression-etc2 },\n'etc2-rgb8unorm-srgb': { },\n'etc2-rgb8a1unorm': {\t8 },\n'etc2-rgb8a1unorm-srgb': { },\n'etc2-rgba8unorm': {\t16 },\n'etc2-rgba8unorm-srgb': { },\n\n'eac-r11unorm': {\t8 },\n'eac-r11snorm': { },\n'eac-rg11unorm': {\t16 },\n'eac-rg11snorm': { },\n\n'astc-4x4-unorm': {\t16\t\"float\"\t4 × 4\ttexture-compression-astc },\n'astc-4x4-unorm-srgb': { },\n'astc-5x4-unorm': {\t16\t5 × 4 },\n'astc-5x4-unorm-srgb': { },\n'astc-5x5-unorm': {\t16\t5 × 5 },\n'astc-5x5-unorm-srgb': { },\n'astc-6x5-unorm': {\t16\t6 × 5 },\n'astc-6x5-unorm-srgb': { },\n'astc-6x6-unorm': {\t16\t6 × 6 },\n'astc-6x6-unorm-srgb': { },\n'astc-8x5-unorm': {\t16\t8 × 5 },\n'astc-8x5-unorm-srgb': { },\n'astc-8x6-unorm': {\t16\t8 × 6 },\n'astc-8x6-unorm-srgb': { },\n'astc-8x8-unorm': {\t16\t8 × 8 },\n'astc-8x8-unorm-srgb': { },\n'astc-10x5-unorm': {\t16\t10 × 5 },\n'astc-10x5-unorm-srgb': { },\n'astc-10x6-unorm': {\t16\t10 × 6 },\n'astc-10x6-unorm-srgb': { },\n'astc-10x8-unorm': {\t16\t10 × 8 },\n'astc-10x8-unorm-srgb': { },\n'astc-10x10-unorm': {\t16\t10 × 10 },\n'astc-10x10-unorm-srgb': { },\n'astc-12x10-unorm': {\t16\t12 × 10 },\n'astc-12x10-unorm-srgb': { },\n'astc-12x12-unorm': {\t16 },\n*/\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/**\n * Built-in data types that can be used to initialize textures\n * @note ImageData can be used for contiguous 8 bit data via Uint8ClampedArray\n */\nexport type ExternalImage =\n | ImageBitmap\n | ImageData\n | HTMLImageElement\n | HTMLVideoElement\n | VideoFrame\n | HTMLCanvasElement\n | OffscreenCanvas;\n\n/** Check if data is an external image */\nexport function isExternalImage(data: unknown): data is ExternalImage {\n return (\n (typeof ImageData !== 'undefined' && data instanceof ImageData) ||\n (typeof ImageBitmap !== 'undefined' && data instanceof ImageBitmap) ||\n (typeof HTMLImageElement !== 'undefined' && data instanceof HTMLImageElement) ||\n (typeof HTMLVideoElement !== 'undefined' && data instanceof HTMLVideoElement) ||\n (typeof VideoFrame !== 'undefined' && data instanceof VideoFrame) ||\n (typeof HTMLCanvasElement !== 'undefined' && data instanceof HTMLCanvasElement) ||\n (typeof OffscreenCanvas !== 'undefined' && data instanceof OffscreenCanvas)\n );\n}\n\n/** Determine size (width and height) of provided image data */\nexport function getExternalImageSize(data: ExternalImage): {width: number; height: number} {\n if (\n (typeof ImageData !== 'undefined' && data instanceof ImageData) ||\n (typeof ImageBitmap !== 'undefined' && data instanceof ImageBitmap) ||\n (typeof HTMLCanvasElement !== 'undefined' && data instanceof HTMLCanvasElement) ||\n (typeof OffscreenCanvas !== 'undefined' && data instanceof OffscreenCanvas)\n ) {\n return {width: data.width, height: data.height};\n }\n if (typeof HTMLImageElement !== 'undefined' && data instanceof HTMLImageElement) {\n return {width: data.naturalWidth, height: data.naturalHeight};\n }\n if (typeof HTMLVideoElement !== 'undefined' && data instanceof HTMLVideoElement) {\n return {width: data.videoWidth, height: data.videoHeight};\n }\n if (typeof VideoFrame !== 'undefined' && data instanceof VideoFrame) {\n // TODO: is this the right choice for width and height?\n return {width: data.displayWidth, height: data.displayHeight};\n }\n throw new Error('Unknown image type');\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {StatsManager, lumaStats} from '../utils/stats-manager';\nimport {log} from '../utils/log';\nimport {uid} from '../utils/uid';\nimport type {VertexFormat, VertexFormatInfo} from '../shadertypes/vertex-types/vertex-formats';\nimport type {\n TextureFormat,\n TextureFormatInfo,\n CompressedTextureFormat\n} from '../shadertypes/texture-types/texture-formats';\nimport type {CanvasContext, CanvasContextProps} from './canvas-context';\nimport type {PresentationContext, PresentationContextProps} from './presentation-context';\nimport type {BufferProps} from './resources/buffer';\nimport {Buffer} from './resources/buffer';\nimport type {RenderPipeline, RenderPipelineProps} from './resources/render-pipeline';\nimport type {SharedRenderPipeline} from './resources/shared-render-pipeline';\nimport type {ComputePipeline, ComputePipelineProps} from './resources/compute-pipeline';\nimport type {Sampler, SamplerProps} from './resources/sampler';\nimport type {Shader, ShaderProps} from './resources/shader';\nimport type {Texture, TextureProps} from './resources/texture';\nimport type {ExternalTexture, ExternalTextureProps} from './resources/external-texture';\nimport type {Framebuffer, FramebufferProps} from './resources/framebuffer';\nimport type {RenderPass, RenderPassProps} from './resources/render-pass';\nimport type {ComputePass, ComputePassProps} from './resources/compute-pass';\nimport type {CommandEncoder, CommandEncoderProps} from './resources/command-encoder';\nimport type {CommandBuffer} from './resources/command-buffer';\nimport type {VertexArray, VertexArrayProps} from './resources/vertex-array';\nimport type {TransformFeedback, TransformFeedbackProps} from './resources/transform-feedback';\nimport type {QuerySet, QuerySetProps} from './resources/query-set';\nimport type {Fence} from './resources/fence';\nimport type {Bindings, ComputeShaderLayout, ShaderLayout} from './types/shader-layout';\n\nimport {vertexFormatDecoder} from '../shadertypes/vertex-types/vertex-format-decoder';\nimport {textureFormatDecoder} from '../shadertypes/texture-types/texture-format-decoder';\nimport type {ExternalImage} from '../shadertypes/image-types/image-types';\nimport {isExternalImage, getExternalImageSize} from '../shadertypes/image-types/image-types';\nimport {getTextureFormatTable} from '../shadertypes/texture-types/texture-format-table';\n\n/**\n * Identifies the GPU vendor and driver.\n * @note Chrome WebGPU does not provide much information, though more can be enabled with\n * @see https://developer.chrome.com/blog/new-in-webgpu-120#adapter_information_updates\n * chrome://flags/#enable-webgpu-developer-features\n */\nexport type DeviceInfo = {\n /** Type of device */\n type: 'webgl' | 'webgpu' | 'null' | 'unknown';\n /** Vendor (name of GPU vendor, Apple, nVidia etc */\n vendor: string;\n /** Renderer (usually driver name) */\n renderer: string;\n /** version of driver */\n version: string;\n /** family of GPU */\n gpu: 'nvidia' | 'amd' | 'intel' | 'apple' | 'software' | 'unknown';\n /** Type of GPU () */\n gpuType: 'discrete' | 'integrated' | 'cpu' | 'unknown';\n /** GPU architecture */\n gpuArchitecture?: string; // 'common-3' on Apple\n /** GPU driver backend. Can sometimes be sniffed */\n gpuBackend?: 'opengl' | 'opengles' | 'metal' | 'd3d11' | 'd3d12' | 'vulkan' | 'unknown';\n /** If this is a fallback adapter */\n fallback?: boolean;\n /** Shader language supported by device.createShader() */\n shadingLanguage: 'wgsl' | 'glsl';\n /** Highest supported shader language version: GLSL 3.00 = 300, WGSL 1.00 = 100 */\n shadingLanguageVersion: number;\n};\n\n/** Limits for a device (max supported sizes of resources, max number of bindings etc) */\nexport abstract class DeviceLimits {\n /** max number of TextureDimension1D */\n abstract maxTextureDimension1D: number;\n /** max number of TextureDimension2D */\n abstract maxTextureDimension2D: number;\n /** max number of TextureDimension3D */\n abstract maxTextureDimension3D: number;\n /** max number of TextureArrayLayers */\n abstract maxTextureArrayLayers: number;\n /** max number of BindGroups */\n abstract maxBindGroups: number;\n /** max number of DynamicUniformBuffers per PipelineLayout */\n abstract maxDynamicUniformBuffersPerPipelineLayout: number;\n /** max number of DynamicStorageBuffers per PipelineLayout */\n abstract maxDynamicStorageBuffersPerPipelineLayout: number;\n /** max number of SampledTextures per ShaderStage */\n abstract maxSampledTexturesPerShaderStage: number;\n /** max number of Samplers per ShaderStage */\n abstract maxSamplersPerShaderStage: number;\n /** max number of StorageBuffers per ShaderStage */\n abstract maxStorageBuffersPerShaderStage: number;\n /** max number of StorageTextures per ShaderStage */\n abstract maxStorageTexturesPerShaderStage: number;\n /** max number of UniformBuffers per ShaderStage */\n abstract maxUniformBuffersPerShaderStage: number;\n /** max number of UniformBufferBindingSize */\n abstract maxUniformBufferBindingSize: number;\n /** max number of StorageBufferBindingSize */\n abstract maxStorageBufferBindingSize: number;\n /** min UniformBufferOffsetAlignment */\n abstract minUniformBufferOffsetAlignment: number;\n /** min StorageBufferOffsetAlignment */\n abstract minStorageBufferOffsetAlignment: number;\n /** max number of VertexBuffers */\n abstract maxVertexBuffers: number;\n /** max number of VertexAttributes */\n abstract maxVertexAttributes: number;\n /** max number of VertexBufferArrayStride */\n abstract maxVertexBufferArrayStride: number;\n /** max number of InterStageShaderComponents */\n abstract maxInterStageShaderVariables: number;\n /** max number of ComputeWorkgroupStorageSize */\n abstract maxComputeWorkgroupStorageSize: number;\n /** max number of ComputeInvocations per Workgroup */\n abstract maxComputeInvocationsPerWorkgroup: number;\n /** max ComputeWorkgroupSizeX */\n abstract maxComputeWorkgroupSizeX: number;\n /** max ComputeWorkgroupSizeY */\n abstract maxComputeWorkgroupSizeY: number;\n /** max ComputeWorkgroupSizeZ */\n abstract maxComputeWorkgroupSizeZ: number;\n /** max ComputeWorkgroupsPerDimension */\n abstract maxComputeWorkgroupsPerDimension: number;\n}\n\nfunction formatErrorLogArguments(context: unknown, args: unknown[]): unknown[] {\n const formattedContext = formatErrorLogValue(context);\n const formattedArgs = args.map(formatErrorLogValue).filter(arg => arg !== undefined);\n return [formattedContext, ...formattedArgs].filter(arg => arg !== undefined);\n}\n\nfunction formatErrorLogValue(value: unknown): unknown {\n if (value === undefined) {\n return undefined;\n }\n if (\n value === null ||\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ) {\n return value;\n }\n if (value instanceof Error) {\n return value.message;\n }\n if (Array.isArray(value)) {\n return value.map(formatErrorLogValue);\n }\n if (typeof value === 'object') {\n if (hasCustomToString(value)) {\n const stringValue = String(value);\n if (stringValue !== '[object Object]') {\n return stringValue;\n }\n }\n\n if (looksLikeGPUCompilationMessage(value)) {\n return formatGPUCompilationMessage(value);\n }\n\n return value.constructor?.name || 'Object';\n }\n\n return String(value);\n}\n\nfunction hasCustomToString(value: object): boolean {\n return (\n 'toString' in value &&\n typeof value.toString === 'function' &&\n value.toString !== Object.prototype.toString\n );\n}\n\nfunction looksLikeGPUCompilationMessage(value: object): value is {\n message?: unknown;\n type?: unknown;\n lineNum?: unknown;\n linePos?: unknown;\n} {\n return 'message' in value && 'type' in value;\n}\n\nfunction formatGPUCompilationMessage(value: {\n message?: unknown;\n type?: unknown;\n lineNum?: unknown;\n linePos?: unknown;\n}): string {\n const type = typeof value.type === 'string' ? value.type : 'message';\n const message = typeof value.message === 'string' ? value.message : '';\n const lineNum = typeof value.lineNum === 'number' ? value.lineNum : null;\n const linePos = typeof value.linePos === 'number' ? value.linePos : null;\n const location =\n lineNum !== null && linePos !== null\n ? ` @ ${lineNum}:${linePos}`\n : lineNum !== null\n ? ` @ ${lineNum}`\n : '';\n return `${type}${location}: ${message}`.trim();\n}\n\n/** Set-like class for features (lets apps check for WebGL / WebGPU extensions) */\nexport class DeviceFeatures {\n protected features: Set;\n protected disabledFeatures?: Partial>;\n\n constructor(\n features: DeviceFeature[] = [],\n disabledFeatures: Partial>\n ) {\n this.features = new Set(features);\n this.disabledFeatures = disabledFeatures || {};\n }\n\n *[Symbol.iterator](): IterableIterator {\n yield* this.features;\n }\n\n has(feature: DeviceFeature): boolean {\n return !this.disabledFeatures?.[feature] && this.features.has(feature);\n }\n}\n\n/** Device feature names */\nexport type DeviceFeature =\n | WebGPUDeviceFeature\n | WebGLDeviceFeature\n | WebGLCompressedTextureFeatures;\n// | ChromeExperimentalFeatures\n\n/** Chrome-specific extensions. Expected to eventually become standard features. */\n// export type ChromeExperimentalFeatures = ;\n\nexport type WebGPUDeviceFeature =\n | 'depth-clip-control'\n | 'depth32float-stencil8'\n | 'texture-compression-bc'\n | 'texture-compression-bc-sliced-3d'\n | 'texture-compression-etc2'\n | 'texture-compression-astc'\n | 'texture-compression-astc-sliced-3d'\n | 'timestamp-query'\n | 'indirect-first-instance'\n | 'shader-f16'\n | 'rg11b10ufloat-renderable' // Is the rg11b10ufloat texture format renderable?\n | 'bgra8unorm-storage' // Can the bgra8unorm texture format be used in storage buffers?\n | 'float32-filterable' // Is the float32 format filterable?\n | 'float32-blendable' // Is the float32 format blendable?\n | 'clip-distances'\n | 'dual-source-blending'\n | 'subgroups';\n// | 'depth-clamping' // removed from the WebGPU spec...\n// | 'pipeline-statistics-query' // removed from the WebGPU spec...\n\nexport type WebGLDeviceFeature =\n // webgl extension features\n | 'compilation-status-async-webgl' // Non-blocking shader compile/link status query available\n | 'provoking-vertex-webgl' // parameters.provokingVertex\n | 'polygon-mode-webgl' // parameters.polygonMode and parameters.polygonOffsetLine\n\n // GLSL extension features\n | 'shader-noperspective-interpolation-webgl' // Vertex outputs & fragment inputs can have a `noperspective` interpolation qualifier.\n | 'shader-conservative-depth-webgl' // GLSL `gl_FragDepth` qualifiers `depth_unchanged` etc can enable early depth test\n | 'shader-clip-cull-distance-webgl' // Makes gl_ClipDistance and gl_CullDistance available in shaders\n\n // texture rendering\n | 'float32-renderable-webgl'\n | 'float16-renderable-webgl'\n | 'rgb9e5ufloat-renderable-webgl'\n | 'snorm8-renderable-webgl'\n | 'norm16-webgl'\n | 'norm16-renderable-webgl'\n | 'snorm16-renderable-webgl'\n\n // texture filtering\n | 'float16-filterable-webgl'\n | 'texture-filterable-anisotropic-webgl'\n\n // texture storage bindings\n | 'bgra8unorm-storage'\n\n // texture blending\n | 'texture-blend-float-webgl';\n\ntype WebGLCompressedTextureFeatures =\n | 'texture-compression-bc5-webgl'\n | 'texture-compression-bc7-webgl'\n | 'texture-compression-etc1-webgl'\n | 'texture-compression-pvrtc-webgl'\n | 'texture-compression-atc-webgl';\n\n/** Texture format capabilities that have been checked against a specific device */\nexport type DeviceTextureFormatCapabilities = {\n format: TextureFormat;\n /** Can the format be created and sampled?*/\n create: boolean;\n /** Is the format renderable. */\n render: boolean;\n /** Is the format filterable. */\n filter: boolean;\n /** Is the format blendable. */\n blend: boolean;\n /** Is the format storeable. */\n store: boolean;\n};\n\n/** Device properties */\nexport type DeviceProps = {\n /** string id for debugging. Stored on the object, used in logging and set on underlying GPU objects when feasible. */\n id?: string;\n /** Properties for creating a default canvas context */\n createCanvasContext?: CanvasContextProps | true;\n /** Control which type of GPU is preferred on systems with both integrated and discrete GPU. Defaults to \"high-performance\" / discrete GPU. */\n powerPreference?: 'default' | 'high-performance' | 'low-power';\n /** Hints that device creation should fail if no hardware GPU is available (if the system performance is \"low\"). */\n failIfMajorPerformanceCaveat?: boolean;\n\n /** WebGL specific: Properties passed through to WebGL2RenderingContext creation: `canvas.getContext('webgl2', props.webgl)` */\n webgl?: WebGLContextProps;\n\n // CALLBACKS\n\n /** Error handler. If it returns a probe logger style function, it will be called at the site of the error to optimize console error links. */\n onError?: (error: Error, context?: unknown) => unknown;\n /** Called when the size of a CanvasContext's canvas changes */\n onResize?: (\n ctx: CanvasContext | PresentationContext,\n info: {oldPixelSize: [number, number]}\n ) => unknown;\n /** Called when the absolute position of a CanvasContext's canvas changes. Must set `CanvasContextProps.trackPosition: true` */\n onPositionChange?: (\n ctx: CanvasContext | PresentationContext,\n info: {oldPosition: [number, number]}\n ) => unknown;\n /** Called when the visibility of a CanvasContext's canvas changes */\n onVisibilityChange?: (ctx: CanvasContext | PresentationContext) => unknown;\n /** Called when the device pixel ratio of a CanvasContext's canvas changes */\n onDevicePixelRatioChange?: (\n ctx: CanvasContext | PresentationContext,\n info: {oldRatio: number}\n ) => unknown;\n\n // DEBUG SETTINGS\n\n /** Turn on implementation defined checks that slow down execution but help break where errors occur */\n debug?: boolean;\n /** Enable GPU timestamp collection without enabling all debug validation paths. */\n debugGPUTime?: boolean;\n /** Show shader source in browser? The default is `'error'`, meaning that logs are shown when shader compilation has errors */\n debugShaders?: 'never' | 'errors' | 'warnings' | 'always';\n /** Renders a small version of updated Framebuffers into the primary canvas context. Can be set in console luma.log.set('debug-framebuffers', true) */\n debugFramebuffers?: boolean;\n /** Traces resource caching, reuse, and destroys in the PipelineFactory */\n debugFactories?: boolean;\n /** WebGL specific - Trace WebGL calls (instruments WebGL2RenderingContext at the expense of performance). Can be set in console luma.log.set('debug-webgl', true) */\n debugWebGL?: boolean;\n /** WebGL specific - Initialize the SpectorJS WebGL debugger. Can be set in console luma.log.set('debug-spectorjs', true) */\n debugSpectorJS?: boolean;\n /** WebGL specific - SpectorJS URL. Override if CDN is down or different SpectorJS version is desired. */\n debugSpectorJSUrl?: string;\n\n // EXPERIMENTAL SETTINGS - subject to change\n\n /** adapter.create() returns the existing Device if the provided canvas' WebGL context is already associated with a Device. */\n _reuseDevices?: boolean;\n /** WebGPU specific - Request a Device with the highest limits supported by platform. On WebGPU devices can be created with minimal limits. */\n _requestMaxLimits?: boolean;\n /** Disable specific features */\n _disabledFeatures?: Partial>;\n /** WebGL specific - Initialize all features on startup */\n _initializeFeatures?: boolean;\n /** Enable shader caching (via ShaderFactory) */\n _cacheShaders?: boolean;\n /**\n * Destroy cached shaders when they become unused.\n * Defaults to `false` so repeated create/destroy cycles can still reuse cached shaders.\n * Enable this if the application creates very large numbers of distinct shaders and needs cache eviction.\n */\n _destroyShaders?: boolean;\n /** Enable pipeline caching (via PipelineFactory) */\n _cachePipelines?: boolean;\n /** Enable sharing of backend render-pipeline implementations when caching is enabled. Currently used by WebGL. */\n _sharePipelines?: boolean;\n /**\n * Destroy cached pipelines when they become unused.\n * Defaults to `false` so repeated create/destroy cycles can still reuse cached pipelines.\n * Enable this if the application creates very large numbers of distinct pipelines and needs cache eviction.\n */\n _destroyPipelines?: boolean;\n\n /** @deprecated Internal, Do not use directly! Use `luma.attachDevice()` to attach to pre-created contexts/devices. */\n _handle?: unknown; // WebGL2RenderingContext | GPUDevice | null;\n};\n\ntype DeviceFactories = {\n bindGroupFactory?: unknown;\n};\n\n/** WebGL independent copy of WebGLContextAttributes */\ntype WebGLContextProps = {\n /** indicates if the canvas contains an alpha buffer. */\n alpha?: boolean;\n /** hints the user agent to reduce the latency by desynchronizing the canvas paint cycle from the event loop */\n desynchronized?: boolean;\n /** indicates whether or not to perform anti-aliasing. */\n antialias?: boolean;\n /** indicates that the render target has a stencil buffer of at least `8` bits. */\n stencil?: boolean;\n /** indicates that the drawing buffer has a depth buffer of at least 16 bits. */\n depth?: boolean;\n /** indicates if a context will be created if the system performance is low or if no hardware GPU is available. */\n failIfMajorPerformanceCaveat?: boolean;\n /** Selects GPU */\n powerPreference?: 'default' | 'high-performance' | 'low-power';\n /** page compositor will assume the drawing buffer contains colors with pre-multiplied alpha. */\n premultipliedAlpha?: boolean;\n /** buffers will not be cleared and will preserve their values until cleared or overwritten by the author. */\n preserveDrawingBuffer?: boolean;\n};\n\n/**\n * Create and attach devices for a specific backend. Currently static methods on each device\n */\nexport interface DeviceFactory {\n // new (props: DeviceProps): Device; Constructor isn't used\n type: string;\n isSupported(): boolean;\n create(props: DeviceProps): Promise;\n attach?(handle: unknown): Device;\n}\n\n/**\n * WebGPU Device/WebGL context abstraction\n */\nexport abstract class Device {\n static defaultProps: Required = {\n id: null!,\n powerPreference: 'high-performance',\n failIfMajorPerformanceCaveat: false,\n createCanvasContext: undefined!,\n // WebGL specific\n webgl: {},\n\n // Callbacks\n // eslint-disable-next-line handle-callback-err\n onError: (error: Error, context: unknown) => {},\n onResize: (context: CanvasContext, info: {oldPixelSize: [number, number]}) => {\n const [width, height] = context.getDevicePixelSize();\n log.log(1, `${context} resized => ${width}x${height}px`)();\n },\n onPositionChange: (context: CanvasContext, info: {oldPosition: [number, number]}) => {\n const [left, top] = context.getPosition();\n log.log(1, `${context} repositioned => ${left},${top}`)();\n },\n onVisibilityChange: (context: CanvasContext) =>\n log.log(1, `${context} Visibility changed ${context.isVisible}`)(),\n onDevicePixelRatioChange: (context: CanvasContext, info: {oldRatio: number}) =>\n log.log(1, `${context} DPR changed ${info.oldRatio} => ${context.devicePixelRatio}`)(),\n\n // Debug flags\n debug: getDefaultDebugValue(),\n debugGPUTime: false,\n debugShaders: log.get('debug-shaders') || undefined!,\n debugFramebuffers: Boolean(log.get('debug-framebuffers')),\n debugFactories: Boolean(log.get('debug-factories')),\n debugWebGL: Boolean(log.get('debug-webgl')),\n debugSpectorJS: undefined!, // Note: log setting is queried by the spector.js code\n debugSpectorJSUrl: undefined!,\n\n // Experimental\n _reuseDevices: false,\n _requestMaxLimits: true,\n _cacheShaders: true,\n _destroyShaders: false,\n _cachePipelines: true,\n _sharePipelines: true,\n _destroyPipelines: false,\n // TODO - Change these after confirming things work as expected\n _initializeFeatures: true,\n _disabledFeatures: {\n 'compilation-status-async-webgl': true\n },\n\n // INTERNAL\n _handle: undefined!\n };\n\n get [Symbol.toStringTag](): string {\n return 'Device';\n }\n\n toString(): string {\n return `Device(${this.id})`;\n }\n\n /** id of this device, primarily for debugging */\n readonly id: string;\n /** type of this device */\n abstract readonly type: 'webgl' | 'webgpu' | 'null' | 'unknown';\n abstract readonly handle: unknown;\n abstract commandEncoder: CommandEncoder;\n\n /** A copy of the device props */\n readonly props: Required;\n /** Available for the application to store data on the device */\n userData: {[key: string]: unknown} = {};\n /** stats */\n readonly statsManager: StatsManager = lumaStats;\n /** Internal per-device factory storage */\n _factories: DeviceFactories = {};\n /** An abstract timestamp used for change tracking */\n timestamp: number = 0;\n\n /** True if this device has been reused during device creation (app has multiple references) */\n _reused: boolean = false;\n /** Used by other luma.gl modules to store data on the device */\n private _moduleData: Record> = {};\n\n // Capabilities\n\n /** Information about the device (vendor, versions etc) */\n abstract info: DeviceInfo;\n /** Optional capability discovery */\n abstract features: DeviceFeatures;\n /** WebGPU style device limits */\n abstract get limits(): DeviceLimits;\n\n // Texture helpers\n\n /** Optimal TextureFormat for displaying 8-bit depth, standard dynamic range content on this system. */\n abstract preferredColorFormat: 'rgba8unorm' | 'bgra8unorm';\n /** Default depth format used on this system */\n abstract preferredDepthFormat: 'depth16' | 'depth24plus' | 'depth32float';\n\n protected _textureCaps: Partial> = {};\n /** Internal timestamp query set used when GPU timing collection is enabled for this device. */\n protected _debugGPUTimeQuery: QuerySet | null = null;\n\n constructor(props: DeviceProps) {\n this.props = {...Device.defaultProps, ...props};\n this.id = this.props.id || uid(this[Symbol.toStringTag].toLowerCase());\n }\n\n abstract destroy(): void;\n\n // TODO - just expose the shadertypes decoders?\n\n getVertexFormatInfo(format: VertexFormat): VertexFormatInfo {\n return vertexFormatDecoder.getVertexFormatInfo(format);\n }\n\n isVertexFormatSupported(format: VertexFormat): boolean {\n return true;\n }\n\n /** Returns information about a texture format, such as data type, channels, bits per channel, compression etc */\n getTextureFormatInfo(format: TextureFormat): TextureFormatInfo {\n return textureFormatDecoder.getInfo(format);\n }\n\n /** Determines what operations are supported on a texture format on this particular device (checks against supported device features) */\n getTextureFormatCapabilities(format: TextureFormat): DeviceTextureFormatCapabilities {\n let textureCaps = this._textureCaps[format];\n if (!textureCaps) {\n const capabilities = this._getDeviceTextureFormatCapabilities(format);\n textureCaps = this._getDeviceSpecificTextureFormatCapabilities(capabilities);\n this._textureCaps[format] = textureCaps;\n }\n return textureCaps;\n }\n\n /** Calculates the number of mip levels for a texture of width, height and in case of 3d textures only, depth */\n getMipLevelCount(width: number, height: number, depth3d: number = 1): number {\n const maxSize = Math.max(width, height, depth3d);\n return 1 + Math.floor(Math.log2(maxSize));\n }\n\n /** Check if data is an external image */\n isExternalImage(data: unknown): data is ExternalImage {\n return isExternalImage(data);\n }\n\n /** Get the size of an external image */\n getExternalImageSize(data: ExternalImage): {width: number; height: number} {\n return getExternalImageSize(data);\n }\n\n /** Check if device supports a specific texture format (creation and `nearest` sampling) */\n isTextureFormatSupported(format: TextureFormat): boolean {\n return this.getTextureFormatCapabilities(format).create;\n }\n\n /** Check if linear filtering (sampler interpolation) is supported for a specific texture format */\n isTextureFormatFilterable(format: TextureFormat): boolean {\n return this.getTextureFormatCapabilities(format).filter;\n }\n\n /** Check if device supports rendering to a framebuffer color attachment of a specific texture format */\n isTextureFormatRenderable(format: TextureFormat): boolean {\n return this.getTextureFormatCapabilities(format).render;\n }\n\n /** Check if a specific texture format is GPU compressed */\n isTextureFormatCompressed(format: TextureFormat): boolean {\n return textureFormatDecoder.isCompressed(format);\n }\n\n /** Returns the compressed texture formats that can be created and sampled on this device */\n getSupportedCompressedTextureFormats(): CompressedTextureFormat[] {\n const supportedFormats: CompressedTextureFormat[] = [];\n\n for (const format of Object.keys(getTextureFormatTable()) as TextureFormat[]) {\n if (this.isTextureFormatCompressed(format) && this.isTextureFormatSupported(format)) {\n supportedFormats.push(format as CompressedTextureFormat);\n }\n }\n\n return supportedFormats;\n }\n\n // DEBUG METHODS\n\n pushDebugGroup(groupLabel: string): void {\n this.commandEncoder.pushDebugGroup(groupLabel);\n }\n\n popDebugGroup(): void {\n this.commandEncoder?.popDebugGroup();\n }\n\n insertDebugMarker(markerLabel: string): void {\n this.commandEncoder?.insertDebugMarker(markerLabel);\n }\n\n // Device loss\n\n /** `true` if device is already lost */\n abstract get isLost(): boolean;\n\n /** Promise that resolves when device is lost */\n abstract readonly lost: Promise<{reason: 'destroyed'; message: string}>;\n\n /**\n * Trigger device loss.\n * @returns `true` if context loss could actually be triggered.\n * @note primarily intended for testing how application reacts to device loss\n */\n loseDevice(): boolean {\n return false;\n }\n\n /** A monotonic counter for tracking buffer and texture updates */\n incrementTimestamp(): number {\n return this.timestamp++;\n }\n\n /**\n * Reports Device errors in a way that optimizes for developer experience / debugging.\n * - Logs so that the console error links directly to the source code that generated the error.\n * - Includes the object that reported the error in the log message, even if the error is asynchronous.\n *\n * Conventions when calling reportError():\n * - Always call the returned function - to ensure error is logged, at the error site\n * - Follow with a call to device.debug() - to ensure that the debugger breaks at the error site\n *\n * @param error - the error to report. If needed, just create a new Error object with the appropriate message.\n * @param context - pass `this` as context, otherwise it may not be available in the debugger for async errors.\n * @returns the logger function returned by device.props.onError() so that it can be called from the error site.\n *\n * @example\n * device.reportError(new Error(...), this)();\n * device.debug();\n */\n reportError(error: Error, context: unknown, ...args: unknown[]): () => unknown {\n // Call the error handler\n const isHandled = this.props.onError(error, context);\n if (!isHandled) {\n const logArguments = formatErrorLogArguments(context, args);\n // Note: Returns a function that must be called: `device.reportError(...)()`\n return log.error(\n this.type === 'webgl' ? '%cWebGL' : '%cWebGPU',\n 'color: white; background: red; padding: 2px 6px; border-radius: 3px;',\n error.message,\n ...logArguments\n );\n }\n return () => {};\n }\n\n /** Break in the debugger - if device.props.debug is true */\n debug(): void {\n if (this.props.debug) {\n // @ts-ignore\n // biome-ignore lint/suspicious/noDebugger: explicit debug break when device debugging is enabled.\n debugger;\n } else {\n // TODO(ibgreen): Does not appear to be printed in the console\n const message = `\\\n'Type luma.log.set({debug: true}) in console to enable debug breakpoints',\nor create a device with the 'debug: true' prop.`;\n log.once(0, message)();\n }\n }\n\n // Canvas context\n\n /** Default / primary canvas context. Can be null as WebGPU devices can be created without a CanvasContext */\n abstract canvasContext: CanvasContext | null;\n\n /** Returns the default / primary canvas context. Throws an error if no canvas context is available (a WebGPU compute device) */\n getDefaultCanvasContext(): CanvasContext {\n if (!this.canvasContext) {\n throw new Error('Device has no default CanvasContext. See props.createCanvasContext');\n }\n return this.canvasContext;\n }\n\n /** Creates a new CanvasContext (WebGPU only) */\n abstract createCanvasContext(props?: CanvasContextProps): CanvasContext;\n\n /** Creates a presentation context for a destination canvas. WebGL requires the default canvas context to use an OffscreenCanvas. */\n abstract createPresentationContext(props?: PresentationContextProps): PresentationContext;\n\n /** Call after rendering a frame (necessary e.g. on WebGL OffscreenCanvas) */\n abstract submit(commandBuffer?: CommandBuffer): void;\n\n // Resource creation\n\n /** Create a buffer */\n abstract createBuffer(props: BufferProps | ArrayBuffer | ArrayBufferView): Buffer;\n\n /** Create a texture */\n abstract createTexture(props: TextureProps): Texture;\n\n /** Create a temporary texture view of a video source */\n abstract createExternalTexture(props: ExternalTextureProps): ExternalTexture;\n\n /** Create a sampler */\n abstract createSampler(props: SamplerProps): Sampler;\n\n /** Create a Framebuffer. Must have at least one attachment. */\n abstract createFramebuffer(props: FramebufferProps): Framebuffer;\n\n /** Create a shader */\n abstract createShader(props: ShaderProps): Shader;\n\n /** Create a render pipeline (aka program) */\n abstract createRenderPipeline(props: RenderPipelineProps): RenderPipeline;\n\n /** Create a compute pipeline (aka program). WebGPU only. */\n abstract createComputePipeline(props: ComputePipelineProps): ComputePipeline;\n\n /** Create a vertex array */\n abstract createVertexArray(props: VertexArrayProps): VertexArray;\n\n abstract createCommandEncoder(props?: CommandEncoderProps): CommandEncoder;\n\n /** Create a transform feedback (immutable set of output buffer bindings). WebGL only. */\n abstract createTransformFeedback(props: TransformFeedbackProps): TransformFeedback;\n\n abstract createQuerySet(props: QuerySetProps): QuerySet;\n\n /** Create a fence sync object */\n createFence(): Fence {\n throw new Error('createFence() not implemented');\n }\n\n /** Create a RenderPass using the default CommandEncoder */\n beginRenderPass(props?: RenderPassProps): RenderPass {\n return this.commandEncoder.beginRenderPass(props);\n }\n\n /** Create a ComputePass using the default CommandEncoder*/\n beginComputePass(props?: ComputePassProps): ComputePass {\n return this.commandEncoder.beginComputePass(props);\n }\n\n /**\n * Generate mipmaps for a WebGPU texture.\n * WebGPU textures must be created up front with the required mip count, usage flags, and a format that supports the chosen generation path.\n * WebGL uses `Texture.generateMipmapsWebGL()` directly because the backend manages mip generation on the texture object itself.\n */\n generateMipmapsWebGPU(_texture: Texture): void {\n throw new Error('not implemented');\n }\n\n /** Internal helper for creating a shareable WebGL render-pipeline implementation. */\n _createSharedRenderPipelineWebGL(_props: RenderPipelineProps): SharedRenderPipeline {\n throw new Error('_createSharedRenderPipelineWebGL() not implemented');\n }\n\n /** Internal WebGPU-only helper for retrieving the native bind-group layout for a pipeline group. */\n _createBindGroupLayoutWebGPU(\n _pipeline: RenderPipeline | ComputePipeline,\n _group: number\n ): unknown {\n throw new Error('_createBindGroupLayoutWebGPU() not implemented');\n }\n\n /** Internal WebGPU-only helper for creating a native bind group. */\n _createBindGroupWebGPU(\n _bindGroupLayout: unknown,\n _shaderLayout: ShaderLayout | ComputeShaderLayout,\n _bindings: Bindings,\n _group: number,\n _label?: string\n ): unknown {\n throw new Error('_createBindGroupWebGPU() not implemented');\n }\n\n /**\n * Internal helper that returns `true` when timestamp-query GPU timing should be\n * collected for this device.\n */\n _supportsDebugGPUTime(): boolean {\n return (\n this.features.has('timestamp-query') && Boolean(this.props.debug || this.props.debugGPUTime)\n );\n }\n\n /**\n * Internal helper that enables device-managed GPU timing collection on the\n * default command encoder. Reuses the existing query set if timing is already enabled.\n *\n * @param queryCount - Number of timestamp slots reserved for profiled passes.\n * @returns The device-managed timestamp QuerySet, or `null` when timing is not supported or could not be enabled.\n */\n _enableDebugGPUTime(queryCount: number = 256): QuerySet | null {\n if (!this._supportsDebugGPUTime()) {\n return null;\n }\n\n if (this._debugGPUTimeQuery) {\n return this._debugGPUTimeQuery;\n }\n\n try {\n this._debugGPUTimeQuery = this.createQuerySet({type: 'timestamp', count: queryCount});\n this.commandEncoder = this.createCommandEncoder({\n id: this.commandEncoder.props.id,\n timeProfilingQuerySet: this._debugGPUTimeQuery\n });\n } catch {\n this._debugGPUTimeQuery = null;\n }\n\n return this._debugGPUTimeQuery;\n }\n\n /**\n * Internal helper that disables device-managed GPU timing collection and restores\n * the default command encoder to an unprofiled state.\n */\n _disableDebugGPUTime(): void {\n if (!this._debugGPUTimeQuery) {\n return;\n }\n\n if (this.commandEncoder.getTimeProfilingQuerySet() === this._debugGPUTimeQuery) {\n this.commandEncoder = this.createCommandEncoder({\n id: this.commandEncoder.props.id\n });\n }\n\n this._debugGPUTimeQuery.destroy();\n this._debugGPUTimeQuery = null;\n }\n\n /** Internal helper that returns `true` when device-managed GPU timing is currently active. */\n _isDebugGPUTimeEnabled(): boolean {\n return this._debugGPUTimeQuery !== null;\n }\n\n /**\n * Determines what operations are supported on a texture format, checking against supported device features\n * Subclasses override to apply additional checks\n */\n protected abstract _getDeviceSpecificTextureFormatCapabilities(\n format: DeviceTextureFormatCapabilities\n ): DeviceTextureFormatCapabilities;\n\n // DEPRECATED METHODS\n\n /** @deprecated Use getDefaultCanvasContext() */\n getCanvasContext(): CanvasContext {\n return this.getDefaultCanvasContext();\n }\n\n // WebGL specific HACKS - enables app to remove webgl import\n // Use until we have a better way to handle these\n\n /** @deprecated - will be removed - should use command encoder */\n readPixelsToArrayWebGL(\n source: Framebuffer | Texture,\n options?: {\n sourceX?: number;\n sourceY?: number;\n sourceFormat?: number;\n sourceAttachment?: number;\n target?: Uint8Array | Uint16Array | Float32Array;\n // following parameters are auto deduced if not provided\n sourceWidth?: number;\n sourceHeight?: number;\n sourceType?: number;\n }\n ): Uint8Array | Uint16Array | Float32Array {\n throw new Error('not implemented');\n }\n\n /** @deprecated - will be removed - should use command encoder */\n readPixelsToBufferWebGL(\n source: Framebuffer | Texture,\n options?: {\n sourceX?: number;\n sourceY?: number;\n sourceFormat?: number;\n target?: Buffer; // A new Buffer object is created when not provided.\n targetByteOffset?: number; // byte offset in buffer object\n // following parameters are auto deduced if not provided\n sourceWidth?: number;\n sourceHeight?: number;\n sourceType?: number;\n }\n ): Buffer {\n throw new Error('not implemented');\n }\n\n /** @deprecated - will be removed - should use WebGPU parameters (pipeline) */\n setParametersWebGL(parameters: any): void {\n throw new Error('not implemented');\n }\n\n /** @deprecated - will be removed - should use WebGPU parameters (pipeline) */\n getParametersWebGL(parameters: any): void {\n throw new Error('not implemented');\n }\n\n /** @deprecated - will be removed - should use WebGPU parameters (pipeline) */\n withParametersWebGL(parameters: any, func: any): any {\n throw new Error('not implemented');\n }\n\n /** @deprecated - will be removed - should use clear arguments in RenderPass */\n clearWebGL(options?: {framebuffer?: Framebuffer; color?: any; depth?: any; stencil?: any}): void {\n throw new Error('not implemented');\n }\n\n /** @deprecated - will be removed - should use for debugging only */\n resetWebGL(): void {\n throw new Error('not implemented');\n }\n\n // INTERNAL LUMA.GL METHODS\n\n getModuleData>(moduleName: string): ModuleDataT {\n this._moduleData[moduleName] ||= {};\n return this._moduleData[moduleName] as ModuleDataT;\n }\n\n // INTERNAL HELPERS\n\n // IMPLEMENTATION\n\n /** Helper to get the canvas context props */\n static _getCanvasContextProps(props: DeviceProps): CanvasContextProps | undefined {\n return props.createCanvasContext === true ? {} : props.createCanvasContext;\n }\n\n protected _getDeviceTextureFormatCapabilities(\n format: TextureFormat\n ): DeviceTextureFormatCapabilities {\n const genericCapabilities = textureFormatDecoder.getCapabilities(format);\n\n // Check standard features\n const checkFeature = (feature: DeviceFeature | boolean | undefined) =>\n (typeof feature === 'string' ? this.features.has(feature) : feature) ?? true;\n\n const supported = checkFeature(genericCapabilities.create);\n return {\n format,\n create: supported,\n render: supported && checkFeature(genericCapabilities.render),\n filter: supported && checkFeature(genericCapabilities.filter),\n blend: supported && checkFeature(genericCapabilities.blend),\n store: supported && checkFeature(genericCapabilities.store)\n } as const satisfies DeviceTextureFormatCapabilities;\n }\n\n /** Subclasses use this to support .createBuffer() overloads */\n protected _normalizeBufferProps(props: BufferProps | ArrayBuffer | ArrayBufferView): BufferProps {\n if (props instanceof ArrayBuffer || ArrayBuffer.isView(props)) {\n props = {data: props};\n }\n\n // TODO(ibgreen) - fragile, as this is done before we merge with default options\n // inside the Buffer constructor\n\n const newProps = {...props};\n // Deduce indexType\n const usage = props.usage || 0;\n if (usage & Buffer.INDEX) {\n if (!props.indexType) {\n if (props.data instanceof Uint32Array) {\n newProps.indexType = 'uint32';\n } else if (props.data instanceof Uint16Array) {\n newProps.indexType = 'uint16';\n } else if (props.data instanceof Uint8Array) {\n // Convert uint8 to uint16 for WebGPU compatibility (WebGPU doesn't support uint8 indices)\n newProps.data = new Uint16Array(props.data);\n newProps.indexType = 'uint16';\n }\n }\n if (!newProps.indexType) {\n throw new Error('indices buffer content must be of type uint16 or uint32');\n }\n }\n\n return newProps;\n }\n}\n\n/**\n * Internal helper for resolving the default `debug` prop.\n * Precedence is: explicit log debug value first, then `NODE_ENV`, then `false`.\n */\nexport function _getDefaultDebugValue(logDebugValue: unknown, nodeEnv?: string): boolean {\n if (logDebugValue !== undefined && logDebugValue !== null) {\n return Boolean(logDebugValue);\n }\n\n if (nodeEnv !== undefined) {\n return nodeEnv !== 'production';\n }\n\n return false;\n}\n\nfunction getDefaultDebugValue(): boolean {\n return _getDefaultDebugValue(log.get('debug'), getNodeEnv());\n}\n\nfunction getNodeEnv(): string | undefined {\n const processObject = (\n globalThis as typeof globalThis & {\n process?: {env?: Record};\n }\n ).process;\n if (!processObject?.env) {\n return undefined;\n }\n\n return processObject.env['NODE_ENV'];\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Log} from '@probe.gl/log';\nimport type {DeviceProps} from './device';\nimport {Device} from './device';\nimport {Adapter} from './adapter';\nimport {StatsManager, lumaStats} from '../utils/stats-manager';\nimport {log} from '../utils/log';\n\ndeclare global {\n // eslint-disable-next-line no-var\n var luma: Luma;\n}\n\nconst STARTUP_MESSAGE = 'set luma.log.level=1 (or higher) to trace rendering';\n\nconst ERROR_MESSAGE =\n 'No matching device found. Ensure `@luma.gl/webgl` and/or `@luma.gl/webgpu` modules are imported.';\n\n/** Properties for creating a new device */\nexport type CreateDeviceProps = {\n /** Selects the type of device. `best-available` uses webgpu if available, then webgl. */\n type?: 'webgl' | 'webgpu' | 'null' | 'unknown' | 'best-available';\n /** List of adapters. Will also search any pre-registered adapters */\n adapters?: Adapter[];\n /**\n * Whether to wait for page to be loaded so that CanvasContext's can access the DOM.\n * The browser only supports one 'load' event listener so it may be necessary for the application to set this to false to avoid conflicts.\n */\n waitForPageLoad?: boolean;\n} & DeviceProps;\n\n/** Properties for attaching an existing WebGL context or WebGPU device to a new luma Device */\nexport type AttachDeviceProps = {\n /** List of adapters. Will also search any pre-registered adapters */\n adapters?: Adapter[];\n} & DeviceProps;\n\n/**\n * Entry point to the luma.gl GPU abstraction\n * Register WebGPU and/or WebGL adapters (controls application bundle size)\n * Run-time selection of the first available Device\n */\nexport class Luma {\n static defaultProps: Required = {\n ...Device.defaultProps,\n type: 'best-available',\n adapters: undefined!,\n waitForPageLoad: true\n };\n\n /** Global stats for all devices */\n readonly stats: StatsManager = lumaStats;\n\n /**\n * Global log\n *\n * Assign luma.log.level in console to control logging: \\\n * 0: none, 1: minimal, 2: verbose, 3: attribute/uniforms, 4: gl logs\n * luma.log.break[], set to gl funcs, luma.log.profile[] set to model names`;\n */\n readonly log: Log = log;\n\n /** Version of luma.gl */\n readonly VERSION: string =\n // Version detection using build plugin\n // @ts-expect-error no-undef\n typeof __VERSION__ !== 'undefined' ? __VERSION__ : 'running from source';\n\n spector: unknown;\n\n protected preregisteredAdapters = new Map();\n\n constructor() {\n if (globalThis.luma) {\n if (globalThis.luma.VERSION !== this.VERSION) {\n log.error(`Found luma.gl ${globalThis.luma.VERSION} while initialzing ${this.VERSION}`)();\n log.error(`'yarn why @luma.gl/core' can help identify the source of the conflict`)();\n throw new Error(`luma.gl - multiple versions detected: see console log`);\n }\n\n log.error('This version of luma.gl has already been initialized')();\n }\n\n log.log(1, `${this.VERSION} - ${STARTUP_MESSAGE}`)();\n\n globalThis.luma = this;\n }\n\n /** Creates a device. Asynchronously. */\n async createDevice(props_: CreateDeviceProps = {}): Promise {\n const props: Required = {...Luma.defaultProps, ...props_};\n\n const adapter = this.selectAdapter(props.type, props.adapters);\n if (!adapter) {\n throw new Error(ERROR_MESSAGE);\n }\n\n // Wait for page to load so that CanvasContext's can access the DOM.\n if (props.waitForPageLoad) {\n await adapter.pageLoaded;\n }\n\n return await adapter.create(props);\n }\n\n /**\n * Attach to an existing GPU API handle (WebGL2RenderingContext or GPUDevice).\n * @param handle Externally created WebGL context or WebGPU device\n */\n async attachDevice(handle: unknown, props: AttachDeviceProps): Promise {\n const type = this._getTypeFromHandle(handle, props.adapters);\n\n const adapter = type && this.selectAdapter(type, props.adapters);\n if (!adapter) {\n throw new Error(ERROR_MESSAGE);\n }\n\n return await adapter?.attach?.(handle, props);\n }\n\n /**\n * Global adapter registration.\n * @deprecated Use props.adapters instead\n */\n registerAdapters(adapters: Adapter[]): void {\n for (const deviceClass of adapters) {\n this.preregisteredAdapters.set(deviceClass.type, deviceClass);\n }\n }\n\n /** Get type strings for supported Devices */\n getSupportedAdapters(adapters: Adapter[] = []): string[] {\n const adapterMap = this._getAdapterMap(adapters);\n return Array.from(adapterMap)\n .map(([, adapter]) => adapter)\n .filter(adapter => adapter.isSupported?.())\n .map(adapter => adapter.type);\n }\n\n /** Get type strings for best available Device */\n getBestAvailableAdapterType(adapters: Adapter[] = []): 'webgpu' | 'webgl' | 'null' | null {\n const KNOWN_ADAPTERS: ('webgpu' | 'webgl' | 'null')[] = ['webgpu', 'webgl', 'null'];\n const adapterMap = this._getAdapterMap(adapters);\n for (const type of KNOWN_ADAPTERS) {\n if (adapterMap.get(type)?.isSupported?.()) {\n return type;\n }\n }\n return null;\n }\n\n /** Select adapter of type from registered adapters */\n selectAdapter(type: string, adapters: Adapter[] = []): Adapter | null {\n let selectedType: string | null = type;\n if (type === 'best-available') {\n selectedType = this.getBestAvailableAdapterType(adapters);\n }\n\n const adapterMap = this._getAdapterMap(adapters);\n return (selectedType && adapterMap.get(selectedType)) || null;\n }\n\n /**\n * Override `HTMLCanvasContext.getCanvas()` to always create WebGL2 contexts with additional WebGL1 compatibility.\n * Useful when attaching luma to a context from an external library does not support creating WebGL2 contexts.\n */\n enforceWebGL2(enforce: boolean = true, adapters: Adapter[] = []): void {\n const adapterMap = this._getAdapterMap(adapters);\n const webgl2Adapter = adapterMap.get('webgl');\n if (!webgl2Adapter) {\n log.warn('enforceWebGL2: webgl adapter not found')();\n }\n (webgl2Adapter as any)?.enforceWebGL2?.(enforce);\n }\n\n // DEPRECATED\n\n /** @deprecated */\n setDefaultDeviceProps(props: CreateDeviceProps): void {\n Object.assign(Luma.defaultProps, props);\n }\n\n // HELPERS\n\n /** Convert a list of adapters to a map */\n protected _getAdapterMap(adapters: Adapter[] = []): Map {\n const map = new Map(this.preregisteredAdapters);\n for (const adapter of adapters) {\n map.set(adapter.type, adapter);\n }\n return map;\n }\n\n /** Get type of a handle (for attachDevice) */\n protected _getTypeFromHandle(\n handle: unknown,\n adapters: Adapter[] = []\n ): 'webgpu' | 'webgl' | 'null' | null {\n // TODO - delegate handle identification to adapters\n\n // WebGL\n if (handle instanceof WebGL2RenderingContext) {\n return 'webgl';\n }\n\n if (typeof GPUDevice !== 'undefined' && handle instanceof GPUDevice) {\n return 'webgpu';\n }\n\n // TODO - WebGPU does not yet seem to have a stable in-browser API, so we \"sniff\" for members instead\n if ((handle as any)?.queue) {\n return 'webgpu';\n }\n\n // null\n if (handle === null) {\n return 'null';\n }\n\n if (handle instanceof WebGLRenderingContext) {\n log.warn('WebGL1 is not supported', handle)();\n } else {\n log.warn('Unknown handle type', handle)();\n }\n\n return null;\n }\n}\n\n/**\n * Entry point to the luma.gl GPU abstraction\n * Register WebGPU and/or WebGL adapters (controls application bundle size)\n * Run-time selection of the first available Device\n */\n// biome-ignore lint/suspicious/noRedeclare: the exported singleton intentionally mirrors the global debug handle.\nexport const luma = new Luma();\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {isBrowser} from '@probe.gl/env';\nimport {Device, DeviceProps} from './device';\n\n/**\n * Create and attach devices for a specific backend.\n */\nexport abstract class Adapter {\n // new (props: DeviceProps): Device; Constructor isn't used\n abstract type: string;\n /** Check if this backend is supported */\n abstract isSupported(): boolean;\n /** Check if the given handle is a valid device handle for this backend */\n abstract isDeviceHandle(handle: unknown): boolean;\n /** Create a new device for this backend */\n abstract create(props: DeviceProps): Promise;\n /** Attach a Device to a valid handle for this backend (GPUDevice, WebGL2RenderingContext etc) */\n abstract attach(handle: unknown, props: DeviceProps): Promise;\n\n /**\n * Page load promise\n * Resolves when the DOM is loaded.\n * @note Since are be limitations on number of `load` event listeners,\n * it is recommended avoid calling this accessor until actually needed.\n * I.e. we don't call it unless you know that you will be looking up a string in the DOM.\n */\n get pageLoaded(): Promise {\n return getPageLoadPromise();\n }\n}\n\n// HELPER FUNCTIONS\n\nconst isPage: boolean = isBrowser() && typeof document !== 'undefined';\nconst isPageLoaded: () => boolean = () => isPage && document.readyState === 'complete';\nlet pageLoadPromise: Promise | null = null;\n\n/** Returns a promise that resolves when the page is loaded */\nfunction getPageLoadPromise(): Promise {\n if (!pageLoadPromise) {\n if (isPageLoaded() || typeof window === 'undefined') {\n pageLoadPromise = Promise.resolve();\n } else {\n pageLoadPromise = new Promise(resolve => window.addEventListener('load', () => resolve()));\n }\n }\n return pageLoadPromise;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\ntype CanvasObserverProps = {\n canvas?: HTMLCanvasElement;\n trackPosition: boolean;\n onResize: (entries: ResizeObserverEntry[]) => void;\n onIntersection: (entries: IntersectionObserverEntry[]) => void;\n onDevicePixelRatioChange: () => void;\n onPositionChange: () => void;\n};\n\n/**\n * Internal DOM observer orchestration for HTML canvas surfaces.\n *\n * CanvasSurface owns the tracked state and device callback dispatch. This helper only manages\n * browser observers, timers, and polling loops, then reports events through callbacks.\n */\nexport class CanvasObserver {\n readonly props: CanvasObserverProps;\n\n private _resizeObserver: ResizeObserver | undefined;\n private _intersectionObserver: IntersectionObserver | undefined;\n private _observeDevicePixelRatioTimeout: ReturnType | null = null;\n private _observeDevicePixelRatioMediaQuery: MediaQueryList | null = null;\n private readonly _handleDevicePixelRatioChange = () => this._refreshDevicePixelRatio();\n private _trackPositionInterval: ReturnType | null = null;\n private _started = false;\n\n get started(): boolean {\n return this._started;\n }\n\n constructor(props: CanvasObserverProps) {\n this.props = props;\n }\n\n start(): void {\n if (this._started || !this.props.canvas) {\n return;\n }\n\n this._started = true;\n this._intersectionObserver ||= new IntersectionObserver(entries =>\n this.props.onIntersection(entries)\n );\n this._resizeObserver ||= new ResizeObserver(entries => this.props.onResize(entries));\n\n this._intersectionObserver.observe(this.props.canvas);\n try {\n this._resizeObserver.observe(this.props.canvas, {box: 'device-pixel-content-box'});\n } catch {\n this._resizeObserver.observe(this.props.canvas, {box: 'content-box'});\n }\n\n this._observeDevicePixelRatioTimeout = setTimeout(() => this._refreshDevicePixelRatio(), 0);\n\n if (this.props.trackPosition) {\n this._trackPosition();\n }\n }\n\n stop(): void {\n if (!this._started) {\n return;\n }\n\n this._started = false;\n\n if (this._observeDevicePixelRatioTimeout) {\n clearTimeout(this._observeDevicePixelRatioTimeout);\n this._observeDevicePixelRatioTimeout = null;\n }\n\n if (this._observeDevicePixelRatioMediaQuery) {\n this._observeDevicePixelRatioMediaQuery.removeEventListener(\n 'change',\n this._handleDevicePixelRatioChange\n );\n this._observeDevicePixelRatioMediaQuery = null;\n }\n\n if (this._trackPositionInterval) {\n clearInterval(this._trackPositionInterval);\n this._trackPositionInterval = null;\n }\n\n this._resizeObserver?.disconnect();\n this._intersectionObserver?.disconnect();\n }\n\n private _refreshDevicePixelRatio(): void {\n if (!this._started) {\n return;\n }\n\n this.props.onDevicePixelRatioChange();\n\n this._observeDevicePixelRatioMediaQuery?.removeEventListener(\n 'change',\n this._handleDevicePixelRatioChange\n );\n this._observeDevicePixelRatioMediaQuery = matchMedia(\n `(resolution: ${window.devicePixelRatio}dppx)`\n );\n this._observeDevicePixelRatioMediaQuery.addEventListener(\n 'change',\n this._handleDevicePixelRatioChange,\n {once: true}\n );\n }\n\n private _trackPosition(intervalMs: number = 100): void {\n if (this._trackPositionInterval) {\n return;\n }\n\n this._trackPositionInterval = setInterval(() => {\n if (!this._started) {\n if (this._trackPositionInterval) {\n clearInterval(this._trackPositionInterval);\n this._trackPositionInterval = null;\n }\n } else {\n this.props.onPositionChange();\n }\n }, intervalMs);\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// TODO - replace with Promise.withResolvers once we upgrade TS baseline\nexport function withResolvers(): {\n promise: Promise;\n resolve: (t: T) => void;\n reject: (error: Error) => void;\n} {\n let resolve: (t: T) => void;\n let reject: (error: Error) => void;\n const promise = new Promise((_resolve, _reject) => {\n resolve = _resolve;\n reject = _reject;\n });\n // @ts-expect-error - in fact these are no used before initialized\n return {promise, resolve, reject};\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/** Throws if condition is true and narrows type */\nexport function assert(condition: unknown, message?: string): asserts condition {\n if (!condition) {\n const error = new Error(message ?? 'luma.gl assertion failed.');\n Error.captureStackTrace?.(error, assert);\n throw error;\n }\n}\n\n/** Throws if value is not defined, narrows type */\nexport function assertDefined(value: T | undefined, message?: string): T {\n assert(value, message);\n return value;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {isBrowser} from '@probe.gl/env';\nimport type {Device} from './device';\nimport type {CanvasContext} from './canvas-context';\nimport {CanvasObserver} from './canvas-observer';\nimport type {PresentationContext} from './presentation-context';\nimport type {Framebuffer} from './resources/framebuffer';\nimport type {TextureFormatDepthStencil} from '../shadertypes/texture-types/texture-formats';\nimport {uid} from '../utils/uid';\nimport {withResolvers} from '../utils/promise-utils';\nimport {assertDefined} from '../utils/assert';\n\n/** Properties for a CanvasContext */\nexport type CanvasContextProps = {\n /** Identifier, for debugging */\n id?: string;\n /** If a canvas not supplied, one will be created and added to the DOM. If a string, a canvas with that id will be looked up in the DOM */\n canvas?: HTMLCanvasElement | OffscreenCanvas | string | null;\n /** If new canvas is created, it will be created in the specified container, otherwise is appended as a child of document.body */\n container?: HTMLElement | string | null;\n /** Width in pixels of the canvas - used when creating a new canvas */\n width?: number;\n /** Height in pixels of the canvas - used when creating a new canvas */\n height?: number;\n /** Visibility (only used if new canvas is created). */\n visible?: boolean;\n /** Whether to size the drawing buffer to the pixel size during auto resize. If a number is provided it is used as a static pixel ratio */\n useDevicePixels?: boolean | number;\n /** Whether to track window resizes. */\n autoResize?: boolean;\n /** @see https://developer.mozilla.org/en-US/docs/Web/API/GPUCanvasContext/configure#alphamode */\n alphaMode?: 'opaque' | 'premultiplied';\n /** @see https://developer.mozilla.org/en-US/docs/Web/API/GPUCanvasContext/configure#colorspace */\n colorSpace?: 'srgb'; // GPUPredefinedColorSpace\n /** Whether to track position changes. Calls this.device.onPositionChange */\n trackPosition?: boolean;\n};\n\nexport type MutableCanvasContextProps = {\n /** Whether to size the drawing buffer to the pixel size during auto resize. If a number is provided it is used as a static pixel ratio */\n useDevicePixels?: boolean | number;\n};\n\n/**\n * Shared tracked-canvas lifecycle used by both renderable and presentation contexts.\n * - Creates a new canvas or looks up a canvas from the DOM\n * - Provides check for DOM loaded\n * @todo commit() @see https://github.com/w3ctag/design-reviews/issues/288\n * @todo transferControlToOffscreen: @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/transferControlToOffscreen\n */\nexport abstract class CanvasSurface {\n static isHTMLCanvas(canvas: unknown): canvas is HTMLCanvasElement {\n return typeof HTMLCanvasElement !== 'undefined' && canvas instanceof HTMLCanvasElement;\n }\n\n static isOffscreenCanvas(canvas: unknown): canvas is OffscreenCanvas {\n return typeof OffscreenCanvas !== 'undefined' && canvas instanceof OffscreenCanvas;\n }\n\n static defaultProps: Required = {\n id: undefined!,\n canvas: null,\n width: 800,\n height: 600,\n useDevicePixels: true,\n autoResize: true,\n container: null,\n visible: true,\n alphaMode: 'opaque',\n colorSpace: 'srgb',\n trackPosition: false\n };\n\n abstract readonly device: Device;\n abstract readonly handle: unknown;\n readonly id: string;\n\n readonly props: Required;\n readonly canvas: HTMLCanvasElement | OffscreenCanvas;\n /** Handle to HTML canvas */\n readonly htmlCanvas?: HTMLCanvasElement;\n /** Handle to wrapped OffScreenCanvas */\n readonly offscreenCanvas?: OffscreenCanvas;\n readonly type: 'html-canvas' | 'offscreen-canvas' | 'node';\n\n /** Promise that resolved once the resize observer has updated the pixel size */\n initialized: Promise;\n isInitialized: boolean = false;\n\n /** Visibility is automatically updated (via an IntersectionObserver) */\n isVisible: boolean = true;\n\n /** Width of canvas in CSS units (tracked by a ResizeObserver) */\n cssWidth: number;\n /** Height of canvas in CSS units (tracked by a ResizeObserver) */\n cssHeight: number;\n\n /** Device pixel ratio. Automatically updated via media queries */\n devicePixelRatio: number;\n /** Exact width of canvas in physical pixels (tracked by a ResizeObserver) */\n devicePixelWidth: number;\n /** Exact height of canvas in physical pixels (tracked by a ResizeObserver) */\n devicePixelHeight: number;\n\n /** Width of drawing buffer: automatically tracks this.pixelWidth if props.autoResize is true */\n drawingBufferWidth: number;\n /** Height of drawing buffer: automatically tracks this.pixelHeight if props.autoResize is true */\n drawingBufferHeight: number;\n\n /** Resolves when the canvas is initialized, i.e. when the ResizeObserver has updated the pixel size */\n protected _initializedResolvers = withResolvers();\n protected _canvasObserver: CanvasObserver;\n /** Position of the canvas in the document, updated by a timer */\n protected _position: [number, number] = [0, 0];\n /** Whether this canvas context has been destroyed */\n protected destroyed = false;\n /** Whether the drawing buffer size needs to be resized (deferred resizing to avoid flicker) */\n protected _needsDrawingBufferResize: boolean = true;\n\n abstract get [Symbol.toStringTag](): string;\n\n toString(): string {\n return `${this[Symbol.toStringTag]}(${this.id})`;\n }\n\n constructor(props?: CanvasContextProps) {\n this.props = {...CanvasSurface.defaultProps, ...props};\n props = this.props;\n\n this.initialized = this._initializedResolvers.promise;\n\n if (!isBrowser()) {\n this.canvas = {width: props.width || 1, height: props.height || 1} as OffscreenCanvas;\n } else if (!props.canvas) {\n this.canvas = createCanvasElement(props);\n } else if (typeof props.canvas === 'string') {\n this.canvas = getCanvasFromDOM(props.canvas);\n } else {\n this.canvas = props.canvas;\n }\n\n if (CanvasSurface.isHTMLCanvas(this.canvas)) {\n this.id = props.id || this.canvas.id;\n this.type = 'html-canvas';\n this.htmlCanvas = this.canvas;\n } else if (CanvasSurface.isOffscreenCanvas(this.canvas)) {\n this.id = props.id || 'offscreen-canvas';\n this.type = 'offscreen-canvas';\n this.offscreenCanvas = this.canvas;\n } else {\n this.id = props.id || 'node-canvas-context';\n this.type = 'node';\n }\n\n this.cssWidth = this.htmlCanvas?.clientWidth || this.canvas.width;\n this.cssHeight = this.htmlCanvas?.clientHeight || this.canvas.height;\n this.devicePixelWidth = this.canvas.width;\n this.devicePixelHeight = this.canvas.height;\n this.drawingBufferWidth = this.canvas.width;\n this.drawingBufferHeight = this.canvas.height;\n this.devicePixelRatio = globalThis.devicePixelRatio || 1;\n this._position = [0, 0];\n this._canvasObserver = new CanvasObserver({\n canvas: this.htmlCanvas,\n trackPosition: this.props.trackPosition,\n onResize: entries => this._handleResize(entries),\n onIntersection: entries => this._handleIntersection(entries),\n onDevicePixelRatioChange: () => this._observeDevicePixelRatio(),\n onPositionChange: () => this.updatePosition()\n });\n }\n\n destroy() {\n if (!this.destroyed) {\n this.destroyed = true;\n this._stopObservers();\n // @ts-expect-error Clear the device to make sure we don't access it after destruction.\n this.device = null;\n }\n }\n\n setProps(props: MutableCanvasContextProps): this {\n if ('useDevicePixels' in props) {\n this.props.useDevicePixels = props.useDevicePixels || false;\n this._updateDrawingBufferSize();\n }\n return this;\n }\n\n /** Returns a framebuffer with properly resized current 'swap chain' textures */\n getCurrentFramebuffer(options?: {\n depthStencilFormat?: TextureFormatDepthStencil | false;\n }): Framebuffer {\n this._resizeDrawingBufferIfNeeded();\n return this._getCurrentFramebuffer(options);\n }\n\n getCSSSize(): [number, number] {\n return [this.cssWidth, this.cssHeight];\n }\n\n getPosition() {\n return this._position;\n }\n\n getDevicePixelSize(): [number, number] {\n return [this.devicePixelWidth, this.devicePixelHeight];\n }\n\n getDrawingBufferSize(): [number, number] {\n return [this.drawingBufferWidth, this.drawingBufferHeight];\n }\n\n getMaxDrawingBufferSize(): [number, number] {\n const maxTextureDimension = this.device.limits.maxTextureDimension2D;\n return [maxTextureDimension, maxTextureDimension];\n }\n\n setDrawingBufferSize(width: number, height: number) {\n width = Math.floor(width);\n height = Math.floor(height);\n if (this.drawingBufferWidth === width && this.drawingBufferHeight === height) {\n return;\n }\n this.drawingBufferWidth = width;\n this.drawingBufferHeight = height;\n this._needsDrawingBufferResize = true;\n }\n\n getDevicePixelRatio(): number {\n const devicePixelRatio = typeof window !== 'undefined' && window.devicePixelRatio;\n return devicePixelRatio || 1;\n }\n\n cssToDevicePixels(\n cssPixel: [number, number],\n yInvert: boolean = true\n ): {\n x: number;\n y: number;\n width: number;\n height: number;\n } {\n const ratio = this.cssToDeviceRatio();\n const [width, height] = this.getDrawingBufferSize();\n return scalePixels(cssPixel, ratio, width, height, yInvert);\n }\n\n /** @deprecated - use .getDevicePixelSize() */\n getPixelSize() {\n return this.getDevicePixelSize();\n }\n\n /** @deprecated Use the current drawing buffer size for projection setup. */\n getAspect(): number {\n const [width, height] = this.getDrawingBufferSize();\n return width > 0 && height > 0 ? width / height : 1;\n }\n\n /** @deprecated Returns multiplier need to convert CSS size to Device size */\n cssToDeviceRatio(): number {\n try {\n const [drawingBufferWidth] = this.getDrawingBufferSize();\n const [cssWidth] = this.getCSSSize();\n return cssWidth ? drawingBufferWidth / cssWidth : 1;\n } catch {\n return 1;\n }\n }\n\n /** @deprecated Use canvasContext.setDrawingBufferSize() */\n resize(size: {width: number; height: number}): void {\n this.setDrawingBufferSize(size.width, size.height);\n }\n\n protected abstract _configureDevice(): void;\n\n protected abstract _getCurrentFramebuffer(options?: {\n depthStencilFormat?: TextureFormatDepthStencil | false;\n }): Framebuffer;\n\n protected _setAutoCreatedCanvasId(id: string) {\n if (this.htmlCanvas?.id === 'lumagl-auto-created-canvas') {\n this.htmlCanvas.id = id;\n }\n }\n\n /**\n * Starts DOM observation after the derived context and its device are fully initialized.\n *\n * `CanvasSurface` construction runs before subclasses can assign `this.device`, and the\n * default WebGL canvas context is created before `WebGLDevice` has initialized `limits`,\n * `features`, and the rest of its runtime state. Deferring observer startup avoids early\n * `ResizeObserver` and DPR callbacks running against a partially initialized device.\n */\n _startObservers(): void {\n if (this.destroyed) {\n return;\n }\n this._canvasObserver.start();\n }\n\n /**\n * Stops all DOM observation and timers associated with a canvas surface.\n *\n * This pairs with `_startObservers()` so teardown uses the same lifecycle whether a context is\n * explicitly destroyed, abandoned during device reuse, or temporarily has not started observing\n * yet. Centralizing shutdown here keeps resize/DPR/position watchers from surviving past the\n * lifetime of the owning device.\n */\n _stopObservers(): void {\n this._canvasObserver.stop();\n }\n\n protected _handleIntersection(entries: IntersectionObserverEntry[]) {\n if (this.destroyed) {\n return;\n }\n\n const entry = entries.find(entry_ => entry_.target === this.canvas);\n if (!entry) {\n return;\n }\n const isVisible = entry.isIntersecting;\n if (this.isVisible !== isVisible) {\n this.isVisible = isVisible;\n this.device.props.onVisibilityChange(this as CanvasContext | PresentationContext);\n }\n }\n\n protected _handleResize(entries: ResizeObserverEntry[]) {\n if (this.destroyed) {\n return;\n }\n\n const entry = entries.find(entry_ => entry_.target === this.canvas);\n if (!entry) {\n return;\n }\n\n const contentBoxSize = assertDefined(entry.contentBoxSize?.[0]);\n this.cssWidth = contentBoxSize.inlineSize;\n this.cssHeight = contentBoxSize.blockSize;\n\n const oldPixelSize = this.getDevicePixelSize();\n\n const devicePixelWidth =\n entry.devicePixelContentBoxSize?.[0]?.inlineSize ||\n contentBoxSize.inlineSize * devicePixelRatio;\n\n const devicePixelHeight =\n entry.devicePixelContentBoxSize?.[0]?.blockSize ||\n contentBoxSize.blockSize * devicePixelRatio;\n\n const [maxDevicePixelWidth, maxDevicePixelHeight] = this.getMaxDrawingBufferSize();\n this.devicePixelWidth = Math.max(1, Math.min(devicePixelWidth, maxDevicePixelWidth));\n this.devicePixelHeight = Math.max(1, Math.min(devicePixelHeight, maxDevicePixelHeight));\n\n this._updateDrawingBufferSize();\n\n this.device.props.onResize(this as CanvasContext | PresentationContext, {oldPixelSize});\n }\n\n protected _updateDrawingBufferSize() {\n if (this.props.autoResize) {\n if (typeof this.props.useDevicePixels === 'number') {\n const devicePixelRatio = this.props.useDevicePixels;\n this.setDrawingBufferSize(\n this.cssWidth * devicePixelRatio,\n this.cssHeight * devicePixelRatio\n );\n } else if (this.props.useDevicePixels) {\n this.setDrawingBufferSize(this.devicePixelWidth, this.devicePixelHeight);\n } else {\n this.setDrawingBufferSize(this.cssWidth, this.cssHeight);\n }\n }\n\n this._initializedResolvers.resolve();\n this.isInitialized = true;\n\n this.updatePosition();\n }\n\n _resizeDrawingBufferIfNeeded() {\n if (this._needsDrawingBufferResize) {\n this._needsDrawingBufferResize = false;\n const sizeChanged =\n this.drawingBufferWidth !== this.canvas.width ||\n this.drawingBufferHeight !== this.canvas.height;\n if (sizeChanged) {\n this.canvas.width = this.drawingBufferWidth;\n this.canvas.height = this.drawingBufferHeight;\n this._configureDevice();\n }\n }\n }\n\n _observeDevicePixelRatio() {\n if (this.destroyed || !this._canvasObserver.started) {\n return;\n }\n const oldRatio = this.devicePixelRatio;\n this.devicePixelRatio = window.devicePixelRatio;\n\n this.updatePosition();\n\n this.device.props.onDevicePixelRatioChange?.(this as CanvasContext | PresentationContext, {\n oldRatio\n });\n }\n\n updatePosition() {\n if (this.destroyed) {\n return;\n }\n const newRect = this.htmlCanvas?.getBoundingClientRect();\n if (newRect) {\n const position: [number, number] = [newRect.left, newRect.top];\n this._position ??= position;\n const positionChanged =\n position[0] !== this._position[0] || position[1] !== this._position[1];\n if (positionChanged) {\n const oldPosition = this._position;\n this._position = position;\n this.device.props.onPositionChange?.(this as CanvasContext | PresentationContext, {\n oldPosition\n });\n }\n }\n }\n}\n\nfunction getContainer(container: HTMLElement | string | null): HTMLElement {\n if (typeof container === 'string') {\n const element = document.getElementById(container);\n if (!element) {\n throw new Error(`${container} is not an HTML element`);\n }\n return element;\n }\n if (container) {\n return container;\n }\n return document.body;\n}\n\nfunction getCanvasFromDOM(canvasId: string): HTMLCanvasElement {\n const canvas = document.getElementById(canvasId);\n if (!CanvasSurface.isHTMLCanvas(canvas)) {\n throw new Error('Object is not a canvas element');\n }\n return canvas;\n}\n\nfunction createCanvasElement(props: CanvasContextProps) {\n const {width, height} = props;\n const newCanvas = document.createElement('canvas');\n newCanvas.id = uid('lumagl-auto-created-canvas');\n newCanvas.width = width || 1;\n newCanvas.height = height || 1;\n newCanvas.style.width = Number.isFinite(width) ? `${width}px` : '100%';\n newCanvas.style.height = Number.isFinite(height) ? `${height}px` : '100%';\n if (!props?.visible) {\n newCanvas.style.visibility = 'hidden';\n }\n const container = getContainer(props?.container || null);\n container.insertBefore(newCanvas, container.firstChild);\n\n return newCanvas;\n}\n\nfunction scalePixels(\n pixel: [number, number],\n ratio: number,\n width: number,\n height: number,\n yInvert: boolean\n): {\n x: number;\n y: number;\n width: number;\n height: number;\n} {\n const point = pixel;\n\n const x = scaleX(point[0], ratio, width);\n let y = scaleY(point[1], ratio, height, yInvert);\n\n let temporary = scaleX(point[0] + 1, ratio, width);\n const xHigh = temporary === width - 1 ? temporary : temporary - 1;\n\n temporary = scaleY(point[1] + 1, ratio, height, yInvert);\n let yHigh;\n if (yInvert) {\n temporary = temporary === 0 ? temporary : temporary + 1;\n yHigh = y;\n y = temporary;\n } else {\n yHigh = temporary === height - 1 ? temporary : temporary - 1;\n }\n return {\n x,\n y,\n width: Math.max(xHigh - x + 1, 1),\n height: Math.max(yHigh - y + 1, 1)\n };\n}\n\nfunction scaleX(x: number, ratio: number, width: number): number {\n return Math.min(Math.round(x * ratio), width - 1);\n}\n\nfunction scaleY(y: number, ratio: number, height: number, yInvert: boolean): number {\n return yInvert\n ? Math.max(0, height - 1 - Math.round(y * ratio))\n : Math.min(Math.round(y * ratio), height - 1);\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport type {CanvasContextProps, MutableCanvasContextProps} from './canvas-surface';\nimport {CanvasSurface} from './canvas-surface';\n\n/**\n * Manages a renderable backend canvas. Supports both HTML or offscreen canvas\n * and returns backend framebuffers sourced from the canvas itself.\n */\nexport abstract class CanvasContext extends CanvasSurface {\n static override defaultProps = CanvasSurface.defaultProps;\n\n abstract override readonly handle: unknown;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {CanvasSurface} from './canvas-surface';\n\nexport type {CanvasContextProps as PresentationContextProps} from './canvas-surface';\n\n/**\n * Tracks a destination canvas for presentation.\n * Backend implementations either borrow the default GPU-backed canvas (WebGL)\n * or render directly into the destination canvas (WebGPU).\n */\nexport abstract class PresentationContext extends CanvasSurface {\n abstract present(): void;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport {CompareFunction} from '../types/parameters';\nimport {Resource, ResourceProps} from './resource';\n\n/** Edge values sampling mode */\nexport type SamplerAddressMode = 'clamp-to-edge' | 'repeat' | 'mirror-repeat';\n\n/** Sampler filtering mode */\nexport type SamplerFilterMode = 'nearest' | 'linear';\n\n/**\n * Properties for initializing a sampler\n */\nexport type SamplerProps = ResourceProps & {\n /** Comparison / shadow samplers are used with depth textures. See the `Sampler.compare` field */\n type?: 'color-sampler' | 'comparison-sampler';\n /** Edge value sampling in X direction */\n addressModeU?: 'clamp-to-edge' | 'repeat' | 'mirror-repeat';\n /** Edge value sampling in Y direction */\n addressModeV?: 'clamp-to-edge' | 'repeat' | 'mirror-repeat';\n /** Edge value sampling in Z direction */\n addressModeW?: 'clamp-to-edge' | 'repeat' | 'mirror-repeat';\n\n /** Magnification: the area of the fragment in texture space is smaller than a texel */\n magFilter?: 'nearest' | 'linear';\n /** Minification: the area of the fragment in texture space is larger than a texel */\n minFilter?: 'nearest' | 'linear';\n /** mipmapping: select between multiple mipmaps based on angle and size of the texture relative to the screen. */\n mipmapFilter?: 'none' | 'nearest' | 'linear';\n /** Affects the mipmap image selection */\n lodMinClamp?: number;\n /** Affects the mipmap image selection */\n lodMaxClamp?: number;\n /** Maximum number of samples that can be taken of the texture during any one texture fetch */\n maxAnisotropy?: number;\n /** How to compare reference values provided in shader shadow sampler calls with those pulled from the texture */\n compare?: CompareFunction;\n};\n\nexport type SamplerParameters = Omit;\n\n/** Immutable Sampler object */\nexport abstract class Sampler extends Resource {\n static override defaultProps: Required = {\n ...Resource.defaultProps,\n type: 'color-sampler',\n addressModeU: 'clamp-to-edge',\n addressModeV: 'clamp-to-edge',\n addressModeW: 'clamp-to-edge',\n magFilter: 'nearest',\n minFilter: 'nearest',\n mipmapFilter: 'none',\n lodMinClamp: 0,\n lodMaxClamp: 32, // Per WebGPU spec\n compare: 'less-equal',\n maxAnisotropy: 1\n };\n\n override get [Symbol.toStringTag](): string {\n return 'Sampler';\n }\n\n constructor(device: Device, props: SamplerProps) {\n props = Sampler.normalizeProps(device, props);\n super(device, props, Sampler.defaultProps);\n }\n\n protected static normalizeProps(device: Device, props: SamplerProps): SamplerProps {\n return props;\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {type TypedArray} from '@math.gl/types';\nimport {type Device} from '../device';\nimport {\n type TextureFormat,\n type TextureMemoryLayout,\n type TextureFormatInfo\n} from '../../shadertypes/texture-types/texture-formats';\nimport {type ExternalImage} from '../../shadertypes/image-types/image-types';\nimport {type TextureView, type TextureViewProps} from './texture-view';\nimport {Resource, type ResourceProps} from './resource';\nimport {Sampler, type SamplerProps} from './sampler';\nimport {Buffer} from './buffer';\nimport {log} from '../../utils/log';\nimport {textureFormatDecoder} from '../../shadertypes/texture-types/texture-format-decoder';\n\n/** Options for Texture.copyExternalImage */\nexport type CopyExternalImageOptions = {\n /** Image */\n image: ExternalImage;\n /** Copy from image x offset (default 0) */\n sourceX?: number;\n /** Copy from image y offset (default 0) */\n sourceY?: number;\n /** Copy area width (default 1) */\n width?: number;\n /** Copy area height (default 1) */\n height?: number;\n /** Copy depth, number of layers/depth slices(default 1) */\n depth?: number;\n /** Start copying into offset x (default 0) */\n x?: number;\n /** Start copying into offset y (default 0) */\n y?: number;\n /** Start copying into layer / depth slice z (default 0) */\n z?: number;\n /** Which mip-level to copy into (default 0) */\n mipLevel?: number;\n /** When copying into depth stencil textures (default 'all') */\n aspect?: 'all' | 'stencil-only' | 'depth-only';\n /** Specific color space of image data */\n colorSpace?: 'srgb';\n /** load as premultiplied alpha */\n premultipliedAlpha?: boolean;\n /** Whether to flip the image vertically */\n flipY?: boolean;\n};\n\n/** Options for copyImageData */\nexport type CopyImageDataOptions = {\n /** Data to copy (array of bytes) */\n data: ArrayBuffer | SharedArrayBuffer | ArrayBufferView;\n /** Offset into the data (in addition to any offset built-in to the ArrayBufferView) */\n byteOffset?: number;\n /** The stride, in bytes, between successive texel rows in the CPU source data. Tightly packed uploads can omit this. */\n bytesPerRow?: number;\n /** Number of rows that make up one image when uploading multiple layers or depth slices from CPU memory. */\n rowsPerImage?: number;\n /** Width to copy */\n width?: number;\n /** Height to copy */\n height?: number;\n /** Copy depth or number of layers */\n depthOrArrayLayers?: number;\n /** @deprecated Use `depthOrArrayLayers` */\n depth?: number;\n /** Start copying into offset x (default 0) */\n x?: number;\n /** Start copying into offset y (default 0) */\n y?: number;\n /** Start copying from depth layer z (default 0) */\n z?: number;\n /** Which mip-level to copy into (default 0) */\n mipLevel?: number;\n /** When copying into depth stencil textures (default 'all') */\n aspect?: 'all' | 'stencil-only' | 'depth-only';\n};\n\nexport type TextureReadOptions = {\n /** Start reading from offset x (default 0) */\n x?: number;\n /** Start reading from offset y (default 0) */\n y?: number;\n /** Start reading from layer / depth slice z (default 0) */\n z?: number;\n /** Width of the region to read. Defaults to the mip width. */\n width?: number;\n /** Height of the region to read. Defaults to the mip height. */\n height?: number;\n /** Number of array layers or depth slices to read. Defaults to 1. */\n depthOrArrayLayers?: number;\n /** Which mip-level to read from (default 0) */\n mipLevel?: number;\n /** When reading from depth stencil textures (default 'all') */\n aspect?: 'all' | 'stencil-only' | 'depth-only';\n};\n\nexport type TextureWriteOptions = {\n /** Offset into the source data or buffer, in bytes. */\n byteOffset?: number;\n /** The stride, in bytes, between successive texel rows in the source data or buffer. */\n bytesPerRow?: number;\n /** The number of rows that make up one image when writing multiple layers or slices. */\n rowsPerImage?: number;\n /** Start writing into offset x (default 0) */\n x?: number;\n /** Start writing into offset y (default 0) */\n y?: number;\n /** Start writing into layer / depth slice z (default 0) */\n z?: number;\n /** Width of the region to write. Defaults to the mip width. */\n width?: number;\n /** Height of the region to write. Defaults to the mip height. */\n height?: number;\n /** Number of array layers or depth slices to write. Defaults to 1, or the full mip depth for 3D textures. */\n depthOrArrayLayers?: number;\n /** Which mip-level to write into (default 0) */\n mipLevel?: number;\n /** When writing into depth stencil textures (default 'all') */\n aspect?: 'all' | 'stencil-only' | 'depth-only';\n};\n\nconst BASE_DIMENSIONS = {\n '1d': '1d',\n '2d': '2d',\n '2d-array': '2d',\n cube: '2d',\n 'cube-array': '2d',\n '3d': '3d'\n} as const satisfies Record;\n\n/** Texture properties */\nexport type TextureProps = ResourceProps & {\n /** @deprecated Use DynamicTexture to create textures with data. */\n data?: ExternalImage | TypedArray | null;\n /** Dimension of this texture. Defaults to '2d' */\n dimension?: '1d' | '2d' | '2d-array' | 'cube' | 'cube-array' | '3d';\n /** The format (bit layout) of the textures pixel data */\n format?: TextureFormat;\n /** Width in texels */\n width: number;\n /** Width in texels */\n height: number;\n /** Number of depth layers */\n depth?: number;\n /** How this texture will be used. Defaults to TEXTURE | COPY_DST | RENDER_ATTACHMENT */\n usage?: number;\n /** How many mip levels */\n mipLevels?: number;\n /** Multi sampling */\n samples?: number;\n\n /** Sampler (or SamplerProps) for the default sampler for this texture. Used if no sampler provided. Note that other samplers can still be used. */\n sampler?: Sampler | SamplerProps;\n /** Props for the default TextureView for this texture. Note that other views can still be created and used. */\n view?: TextureViewProps;\n};\n\n/**\n * Abstract Texture interface\n * Texture Object\n * https://gpuweb.github.io/gpuweb/#gputexture\n */\nexport abstract class Texture extends Resource {\n /** The texture can be bound for use as a sampled texture in a shader */\n static SAMPLE = 0x04;\n /** The texture can be bound for use as a storage texture in a shader */\n static STORAGE = 0x08;\n /** The texture can be used as a color or depth/stencil attachment in a render pass */\n static RENDER = 0x10;\n /** The texture can be used as the source of a copy operation */\n static COPY_SRC = 0x01;\n /** he texture can be used as the destination of a copy or write operation */\n static COPY_DST = 0x02;\n\n /** @deprecated Use Texture.SAMPLE */\n static TEXTURE = 0x04;\n /** @deprecated Use Texture.RENDER */\n static RENDER_ATTACHMENT = 0x10;\n\n /** dimension of this texture */\n readonly dimension: '1d' | '2d' | '2d-array' | 'cube' | 'cube-array' | '3d';\n /** base dimension of this texture */\n readonly baseDimension: '1d' | '2d' | '3d';\n /** format of this texture */\n readonly format: TextureFormat;\n /** width in pixels of this texture */\n readonly width: number;\n /** height in pixels of this texture */\n readonly height: number;\n /** depth of this texture */\n readonly depth: number;\n /** mip levels in this texture */\n readonly mipLevels: number;\n /** sample count */\n readonly samples: number;\n /** Rows are multiples of this length, padded with extra bytes if needed */\n readonly byteAlignment: number;\n /** Default sampler for this texture */\n abstract sampler: Sampler;\n /** Default view for this texture */\n abstract view: TextureView;\n\n /** The ready promise is always resolved. It is provided for type compatibility with DynamicTexture. */\n readonly ready: Promise = Promise.resolve(this);\n /** isReady is always true. It is provided for type compatibility with DynamicTexture. */\n readonly isReady: boolean = true;\n\n /** \"Time\" of last update. Monotonically increasing timestamp. TODO move to DynamicTexture? */\n updateTimestamp: number;\n\n override get [Symbol.toStringTag](): string {\n return 'Texture';\n }\n\n override toString(): string {\n return `Texture(${this.id},${this.format},${this.width}x${this.height})`;\n }\n\n /** Do not use directly. Create with device.createTexture() */\n constructor(device: Device, props: TextureProps, backendProps?: {byteAlignment?: number}) {\n props = Texture.normalizeProps(device, props);\n super(device, props, Texture.defaultProps);\n this.dimension = this.props.dimension;\n this.baseDimension = BASE_DIMENSIONS[this.dimension];\n this.format = this.props.format;\n\n // Size\n this.width = this.props.width;\n this.height = this.props.height;\n this.depth = this.props.depth;\n this.mipLevels = this.props.mipLevels;\n this.samples = this.props.samples || 1;\n\n if (this.dimension === 'cube') {\n this.depth = 6;\n }\n\n // Calculate size, if not provided\n if (this.props.width === undefined || this.props.height === undefined) {\n if (device.isExternalImage(props.data)) {\n const size = device.getExternalImageSize(props.data);\n this.width = size?.width || 1;\n this.height = size?.height || 1;\n } else {\n this.width = 1;\n this.height = 1;\n if (this.props.width === undefined || this.props.height === undefined) {\n log.warn(\n `${this} created with undefined width or height. This is deprecated. Use DynamicTexture instead.`\n )();\n }\n }\n }\n\n this.byteAlignment = backendProps?.byteAlignment || 1;\n\n // TODO - perhaps this should be set on async write completion?\n this.updateTimestamp = device.incrementTimestamp();\n }\n\n /**\n * Create a new texture with the same parameters and optionally a different size\n * @note Textures are immutable and cannot be resized after creation, but we can create a similar texture with the same parameters but a new size.\n * @note Does not copy contents of the texture\n */\n clone(size?: {width: number; height: number}): Texture {\n return this.device.createTexture({...this.props, ...size});\n }\n\n /** Set sampler props associated with this texture */\n setSampler(sampler: Sampler | SamplerProps): void {\n this.sampler = sampler instanceof Sampler ? sampler : this.device.createSampler(sampler);\n }\n\n /** Create a texture view for this texture */\n abstract createView(props: TextureViewProps): TextureView;\n\n /** Copy an image (e.g an ImageBitmap) into the texture */\n abstract copyExternalImage(options: CopyExternalImageOptions): {width: number; height: number};\n\n /**\n * Copy raw image data (bytes) into the texture.\n *\n * @note Deprecated compatibility wrapper over {@link writeData}.\n * @note Uses the same layout defaults and alignment rules as {@link writeData}.\n * @note Tightly packed CPU uploads can omit `bytesPerRow` and `rowsPerImage`.\n * @note If the CPU source rows are padded, pass explicit `bytesPerRow` and `rowsPerImage`.\n * @deprecated Use writeData()\n */\n copyImageData(options: CopyImageDataOptions): void {\n const {data, depth, ...writeOptions} = options;\n this.writeData(data, {\n ...writeOptions,\n depthOrArrayLayers: writeOptions.depthOrArrayLayers ?? depth\n });\n }\n\n /**\n * Calculates the memory layout of the texture, required when reading and writing data.\n * @return the backend-aligned linear layout, in particular bytesPerRow which includes any required padding for buffer copy/read paths\n */\n computeMemoryLayout(options_: TextureReadOptions = {}): TextureMemoryLayout {\n const options = this._normalizeTextureReadOptions(options_);\n const {width = this.width, height = this.height, depthOrArrayLayers = this.depth} = options;\n const {format, byteAlignment} = this;\n\n // TODO - does the overriding above make sense?\n // return textureFormatDecoder.computeMemoryLayout(this);\n return textureFormatDecoder.computeMemoryLayout({\n format,\n width,\n height,\n depth: depthOrArrayLayers,\n byteAlignment\n });\n }\n\n /**\n * Read the contents of a texture into a GPU Buffer.\n * @returns A Buffer containing the texture data.\n *\n * @note The memory layout of the texture data is determined by the texture format and dimensions.\n * @note The application can call Texture.computeMemoryLayout() to compute the backend-aligned layout.\n * @note The application can call Buffer.readAsync() to read the returned buffer on the CPU.\n * @note The destination buffer must be supplied by the caller and must be large enough for the requested region.\n * @note On WebGPU this corresponds to a texture-to-buffer copy and uses buffer-copy alignment rules.\n * @note On WebGL, luma.gl emulates the same logical readback behavior.\n */\n readBuffer(options?: TextureReadOptions, buffer?: Buffer): Buffer {\n throw new Error('readBuffer not implemented');\n }\n\n /**\n * Reads data from a texture into an ArrayBuffer.\n * @returns An ArrayBuffer containing the texture data.\n *\n * @note The memory layout of the texture data is determined by the texture format and dimensions.\n * @note The application can call Texture.computeMemoryLayout() to compute the layout.\n * @deprecated Use Texture.readBuffer() with an explicit destination buffer, or DynamicTexture.readAsync() for convenience readback.\n */\n readDataAsync(options?: TextureReadOptions): Promise {\n throw new Error('readBuffer not implemented');\n }\n\n /**\n * Writes a GPU Buffer into a texture.\n *\n * @param buffer - Source GPU buffer.\n * @param options - Destination subresource, extent, and source layout options.\n * @note The memory layout of the texture data is determined by the texture format and dimensions.\n * @note The application can call Texture.computeMemoryLayout() to compute the backend-aligned layout.\n * @note On WebGPU this corresponds to a buffer-to-texture copy and uses buffer-copy alignment rules.\n * @note On WebGL, luma.gl emulates the same destination and layout semantics.\n */\n writeBuffer(buffer: Buffer, options?: TextureWriteOptions): void {\n throw new Error('readBuffer not implemented');\n }\n\n /**\n * Writes an array buffer into a texture.\n *\n * @param data - Source texel data.\n * @param options - Destination subresource, extent, and source layout options.\n * @note If `bytesPerRow` and `rowsPerImage` are omitted, luma.gl computes a tightly packed CPU-memory layout for the requested region.\n * @note On WebGPU this corresponds to `GPUQueue.writeTexture()` and does not implicitly pad rows to 256 bytes.\n * @note On WebGL, padded CPU data is supported via the same `bytesPerRow` and `rowsPerImage` options.\n */\n writeData(\n data: ArrayBuffer | SharedArrayBuffer | ArrayBufferView,\n options?: TextureWriteOptions\n ): void {\n throw new Error('readBuffer not implemented');\n }\n\n // IMPLEMENTATION SPECIFIC\n\n /**\n * WebGL can read data synchronously.\n * @note While it is convenient, the performance penalty is very significant\n */\n readDataSyncWebGL(options?: TextureReadOptions): ArrayBuffer | ArrayBufferView {\n throw new Error('readDataSyncWebGL not available');\n }\n\n /** Generate mipmaps (WebGL only) */\n generateMipmapsWebGL(): void {\n throw new Error('generateMipmapsWebGL not available');\n }\n\n // HELPERS\n\n /** Ensure we have integer coordinates */\n protected static normalizeProps(device: Device, props: TextureProps): TextureProps {\n const newProps = {...props};\n\n // Ensure we have integer coordinates\n const {width, height} = newProps;\n if (typeof width === 'number') {\n newProps.width = Math.max(1, Math.ceil(width));\n }\n if (typeof height === 'number') {\n newProps.height = Math.max(1, Math.ceil(height));\n }\n return newProps;\n }\n\n /** Initialize texture with supplied props */\n // eslint-disable-next-line max-statements\n _initializeData(data: TextureProps['data']): void {\n // Store opts for accessors\n\n if (this.device.isExternalImage(data)) {\n this.copyExternalImage({\n image: data,\n width: this.width,\n height: this.height,\n depth: this.depth,\n mipLevel: 0,\n x: 0,\n y: 0,\n z: 0,\n aspect: 'all',\n colorSpace: 'srgb',\n premultipliedAlpha: false,\n flipY: false\n });\n } else if (data) {\n this.copyImageData({\n data,\n // width: this.width,\n // height: this.height,\n // depth: this.depth,\n mipLevel: 0,\n x: 0,\n y: 0,\n z: 0,\n aspect: 'all'\n });\n }\n }\n\n _normalizeCopyImageDataOptions(options_: CopyImageDataOptions): Required {\n const {data, depth, ...writeOptions} = options_;\n const options = this._normalizeTextureWriteOptions({\n ...writeOptions,\n depthOrArrayLayers: writeOptions.depthOrArrayLayers ?? depth\n });\n return {data, depth: options.depthOrArrayLayers, ...options};\n }\n\n _normalizeCopyExternalImageOptions(\n options_: CopyExternalImageOptions\n ): Required {\n const optionsWithoutUndefined = Texture._omitUndefined(options_);\n const mipLevel = optionsWithoutUndefined.mipLevel ?? 0;\n const mipLevelSize = this._getMipLevelSize(mipLevel);\n const size = this.device.getExternalImageSize(options_.image);\n const options = {\n ...Texture.defaultCopyExternalImageOptions,\n ...mipLevelSize,\n ...size,\n ...optionsWithoutUndefined\n };\n // WebGL will error if we try to copy outside the bounds of the texture\n options.width = Math.min(options.width, mipLevelSize.width - options.x);\n options.height = Math.min(options.height, mipLevelSize.height - options.y);\n options.depth = Math.min(options.depth, mipLevelSize.depthOrArrayLayers - options.z);\n return options;\n }\n\n _normalizeTextureReadOptions(options_: TextureReadOptions): Required {\n const optionsWithoutUndefined = Texture._omitUndefined(options_);\n const mipLevel = optionsWithoutUndefined.mipLevel ?? 0;\n const mipLevelSize = this._getMipLevelSize(mipLevel);\n const options = {\n ...Texture.defaultTextureReadOptions,\n ...mipLevelSize,\n ...optionsWithoutUndefined\n };\n // WebGL will error if we try to copy outside the bounds of the texture\n options.width = Math.min(options.width, mipLevelSize.width - options.x);\n options.height = Math.min(options.height, mipLevelSize.height - options.y);\n options.depthOrArrayLayers = Math.min(\n options.depthOrArrayLayers,\n mipLevelSize.depthOrArrayLayers - options.z\n );\n return options;\n }\n\n /**\n * Normalizes a texture read request and validates the color-only readback contract used by the\n * current texture read APIs. Supported dimensions are `2d`, `cube`, `cube-array`,\n * `2d-array`, and `3d`.\n *\n * @throws if the texture format, aspect, or dimension is not supported by the first-pass\n * color-read implementation.\n */\n protected _getSupportedColorReadOptions(\n options_: TextureReadOptions\n ): Required {\n const options = this._normalizeTextureReadOptions(options_);\n const formatInfo = textureFormatDecoder.getInfo(this.format);\n\n this._validateColorReadAspect(options);\n this._validateColorReadFormat(formatInfo);\n\n switch (this.dimension) {\n case '2d':\n case 'cube':\n case 'cube-array':\n case '2d-array':\n case '3d':\n return options;\n\n default:\n throw new Error(`${this} color readback does not support ${this.dimension} textures`);\n }\n }\n\n /** Validates that a read request targets the full color aspect of the texture. */\n protected _validateColorReadAspect(options: Required): void {\n if (options.aspect !== 'all') {\n throw new Error(`${this} color readback only supports aspect 'all'`);\n }\n }\n\n /** Validates that a read request targets an uncompressed color-renderable texture format. */\n protected _validateColorReadFormat(formatInfo: TextureFormatInfo): void {\n if (formatInfo.compressed) {\n throw new Error(\n `${this} color readback does not support compressed formats (${this.format})`\n );\n }\n\n switch (formatInfo.attachment) {\n case 'color':\n return;\n\n case 'depth':\n throw new Error(`${this} color readback does not support depth formats (${this.format})`);\n\n case 'stencil':\n throw new Error(`${this} color readback does not support stencil formats (${this.format})`);\n\n case 'depth-stencil':\n throw new Error(\n `${this} color readback does not support depth-stencil formats (${this.format})`\n );\n\n default:\n throw new Error(`${this} color readback does not support format ${this.format}`);\n }\n }\n\n _normalizeTextureWriteOptions(options_: TextureWriteOptions): Required {\n const optionsWithoutUndefined = Texture._omitUndefined(options_);\n const mipLevel = optionsWithoutUndefined.mipLevel ?? 0;\n const mipLevelSize = this._getMipLevelSize(mipLevel);\n const options = {\n ...Texture.defaultTextureWriteOptions,\n ...mipLevelSize,\n ...optionsWithoutUndefined\n };\n\n options.width = Math.min(options.width, mipLevelSize.width - options.x);\n options.height = Math.min(options.height, mipLevelSize.height - options.y);\n options.depthOrArrayLayers = Math.min(\n options.depthOrArrayLayers,\n mipLevelSize.depthOrArrayLayers - options.z\n );\n\n const layout = textureFormatDecoder.computeMemoryLayout({\n format: this.format,\n width: options.width,\n height: options.height,\n depth: options.depthOrArrayLayers,\n byteAlignment: this.byteAlignment\n });\n\n const minimumBytesPerRow = layout.bytesPerPixel * options.width;\n options.bytesPerRow = optionsWithoutUndefined.bytesPerRow ?? layout.bytesPerRow;\n options.rowsPerImage = optionsWithoutUndefined.rowsPerImage ?? options.height;\n\n if (options.bytesPerRow < minimumBytesPerRow) {\n throw new Error(\n `bytesPerRow (${options.bytesPerRow}) must be at least ${minimumBytesPerRow} for ${this.format}`\n );\n }\n if (options.rowsPerImage < options.height) {\n throw new Error(\n `rowsPerImage (${options.rowsPerImage}) must be at least ${options.height} for ${this.format}`\n );\n }\n\n const bytesPerPixel = this.device.getTextureFormatInfo(this.format).bytesPerPixel;\n if (bytesPerPixel && options.bytesPerRow % bytesPerPixel !== 0) {\n throw new Error(\n `bytesPerRow (${options.bytesPerRow}) must be a multiple of bytesPerPixel (${bytesPerPixel}) for ${this.format}`\n );\n }\n\n return options;\n }\n\n protected _getMipLevelSize(\n mipLevel: number\n ): Required> {\n const width = Math.max(1, this.width >> mipLevel);\n const height = this.baseDimension === '1d' ? 1 : Math.max(1, this.height >> mipLevel);\n const depthOrArrayLayers =\n this.dimension === '3d' ? Math.max(1, this.depth >> mipLevel) : this.depth;\n\n return {width, height, depthOrArrayLayers};\n }\n\n protected getAllocatedByteLength(): number {\n let allocatedByteLength = 0;\n\n for (let mipLevel = 0; mipLevel < this.mipLevels; mipLevel++) {\n const {width, height, depthOrArrayLayers} = this._getMipLevelSize(mipLevel);\n allocatedByteLength += textureFormatDecoder.computeMemoryLayout({\n format: this.format,\n width,\n height,\n depth: depthOrArrayLayers,\n byteAlignment: 1\n }).byteLength;\n }\n\n return allocatedByteLength * this.samples;\n }\n\n protected static _omitUndefined(options: T): Partial {\n return Object.fromEntries(\n Object.entries(options).filter(([, value]) => value !== undefined)\n ) as Partial;\n }\n\n static override defaultProps: Required = {\n ...Resource.defaultProps,\n data: null,\n dimension: '2d',\n format: 'rgba8unorm',\n usage: Texture.SAMPLE | Texture.RENDER | Texture.COPY_DST,\n width: undefined!,\n height: undefined!,\n depth: 1,\n mipLevels: 1,\n samples: undefined!,\n sampler: {},\n view: undefined!\n };\n\n protected static defaultCopyDataOptions: Required = {\n data: undefined!,\n byteOffset: 0,\n bytesPerRow: undefined!,\n rowsPerImage: undefined!,\n width: undefined!,\n height: undefined!,\n depthOrArrayLayers: undefined!,\n depth: 1,\n mipLevel: 0,\n x: 0,\n y: 0,\n z: 0,\n aspect: 'all'\n };\n\n /** Default options */\n protected static defaultCopyExternalImageOptions: Required = {\n image: undefined!,\n sourceX: 0,\n sourceY: 0,\n width: undefined!,\n height: undefined!,\n depth: 1,\n mipLevel: 0,\n x: 0,\n y: 0,\n z: 0,\n aspect: 'all',\n colorSpace: 'srgb',\n premultipliedAlpha: false,\n flipY: false\n };\n\n protected static defaultTextureReadOptions: Required = {\n x: 0,\n y: 0,\n z: 0,\n width: undefined!,\n height: undefined!,\n depthOrArrayLayers: 1,\n mipLevel: 0,\n aspect: 'all'\n };\n\n protected static defaultTextureWriteOptions: Required = {\n byteOffset: 0,\n bytesPerRow: undefined!,\n rowsPerImage: undefined!,\n x: 0,\n y: 0,\n z: 0,\n width: undefined!,\n height: undefined!,\n depthOrArrayLayers: 1,\n mipLevel: 0,\n aspect: 'all'\n };\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport type {Texture} from './texture';\nimport type {TextureFormat} from '../../shadertypes/texture-types/texture-formats';\nimport {Resource, ResourceProps} from './resource';\n\n/** Properties for initializing a texture view */\nexport type TextureViewProps = ResourceProps & {\n /** The format of the texture view. Must be either the format of the texture or one of the viewFormats specified during its creation. */\n format?: TextureFormat;\n /** The dimension to view the texture as. */\n dimension?: '1d' | '2d' | '2d-array' | 'cube' | 'cube-array' | '3d';\n /** Which aspect(s) of the texture are accessible to the texture view. default \"all\"*/\n aspect?: 'all' | 'stencil-only' | 'depth-only';\n /** The first (most detailed) mipmap level accessible to the texture view. default 0*/\n baseMipLevel?: number;\n /** How many mipmap levels, starting with baseMipLevel, are accessible to the texture view. */\n mipLevelCount: number;\n /** The index of the first array layer accessible to the texture view. default 0 */\n baseArrayLayer?: number;\n /** How many array layers, starting with baseArrayLayer, are accessible to the texture view. */\n arrayLayerCount: number;\n};\n\n/** Immutable TextureView object */\nexport abstract class TextureView extends Resource {\n abstract texture: Texture;\n\n override get [Symbol.toStringTag](): string {\n return 'TextureView';\n }\n\n /** Should not be constructed directly. Use `texture.createView(props)` */\n constructor(device: Device, props: TextureViewProps & {texture: Texture}) {\n super(device, props, TextureView.defaultProps);\n }\n\n static override defaultProps: Required = {\n ...Resource.defaultProps,\n format: undefined!,\n dimension: undefined!,\n aspect: 'all',\n baseMipLevel: 0,\n mipLevelCount: undefined!,\n baseArrayLayer: 0,\n arrayLayerCount: undefined!\n };\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {CompilerMessage} from '../adapter/types/compiler-message';\n\n/** @returns annotated errors or warnings */\nexport function formatCompilerLog(\n shaderLog: readonly CompilerMessage[],\n source: string,\n options?: {\n /** Include source code in the log. Either just the lines before issues or all source code */\n showSourceCode?: 'no' | 'issues' | 'all';\n html?: boolean;\n }\n): string {\n let formattedLog = '';\n const lines = source.split(/\\r?\\n/);\n const log = shaderLog.slice().sort((a, b) => a.lineNum - b.lineNum);\n\n switch (options?.showSourceCode || 'no') {\n case 'all':\n // Parse the error - note: browser and driver dependent\n let currentMessageIndex = 0;\n for (let lineNum = 1; lineNum <= lines.length; lineNum++) {\n const line = lines[lineNum - 1];\n const currentMessage = log[currentMessageIndex];\n if (line && currentMessage) {\n formattedLog += getNumberedLine(line, lineNum, options);\n }\n while (log.length > currentMessageIndex && currentMessage.lineNum === lineNum) {\n const message = log[currentMessageIndex++];\n if (message) {\n formattedLog += formatCompilerMessage(message, lines, message.lineNum, {\n ...options,\n inlineSource: false\n });\n }\n }\n }\n // Print any remaining messages\n while (log.length > currentMessageIndex) {\n const message = log[currentMessageIndex++];\n if (message) {\n formattedLog += formatCompilerMessage(message, [], 0, {\n ...options,\n inlineSource: false\n });\n }\n }\n return formattedLog;\n\n case 'issues':\n case 'no':\n // Parse the error - note: browser and driver dependent\n for (const message of shaderLog) {\n formattedLog += formatCompilerMessage(message, lines, message.lineNum, {\n inlineSource: options?.showSourceCode !== 'no'\n });\n }\n return formattedLog;\n }\n}\n\n// Helpers\n\n/** Format one message */\nfunction formatCompilerMessage(\n message: CompilerMessage,\n lines: readonly string[],\n lineNum: number,\n options: {\n inlineSource?: boolean;\n html?: boolean;\n }\n): string {\n if (options?.inlineSource) {\n const numberedLines = getNumberedLines(lines, lineNum);\n // If we got error position on line add a `^^^` indicator on next line\n const positionIndicator = message.linePos > 0 ? `${' '.repeat(message.linePos + 5)}^^^\\n` : '';\n return `\n${numberedLines}${positionIndicator}${message.type.toUpperCase()}: ${message.message}\n\n`;\n }\n const color = message.type === 'error' ? 'red' : 'orange';\n return options?.html\n ? `
${message.type.toUpperCase()}: ${\n message.message\n }
`\n : `${message.type.toUpperCase()}: ${message.message}`;\n}\n\nfunction getNumberedLines(\n lines: readonly string[],\n lineNum: number,\n options?: {html?: boolean}\n): string {\n let numberedLines = '';\n for (let lineIndex = lineNum - 2; lineIndex <= lineNum; lineIndex++) {\n const sourceLine = lines[lineIndex - 1];\n if (sourceLine !== undefined) {\n numberedLines += getNumberedLine(sourceLine, lineNum, options);\n }\n }\n return numberedLines;\n}\n\nfunction getNumberedLine(line: string, lineNum: number, options?: {html?: boolean}): string {\n const escapedLine = options?.html ? escapeHTML(line) : line;\n return `${padLeft(String(lineNum), 4)}: ${escapedLine}${options?.html ? '
' : '\\n'}`;\n}\n\n/**\n * Pads a string with a number of spaces (space characters) to the left\n * @param {String} string - string to pad\n * @param {Number} digits - number of spaces to add\n * @return {String} string - The padded string\n */\nfunction padLeft(string: string, paddedLength: number): string {\n let result = '';\n for (let i = string.length; i < paddedLength; ++i) {\n result += ' ';\n }\n return result + string;\n}\n\nfunction escapeHTML(unsafe: string): string {\n return unsafe\n .replaceAll('&', '&')\n .replaceAll('<', '<')\n .replaceAll('>', '>')\n .replaceAll('\"', '"')\n .replaceAll(\"'\", ''');\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport {Resource, ResourceProps} from './resource';\n// import { log } from '../../utils/log';\nimport {uid} from '../../utils/uid';\nimport {CompilerMessage} from '../types/compiler-message';\nimport {formatCompilerLog} from '../../adapter-utils/format-compiler-log';\n\n/**\n * Properties for a Shader\n */\nexport type ShaderProps = ResourceProps & {\n /** Shader language (defaults to auto) */\n language?: 'glsl' | 'wgsl' | 'auto';\n /** Which stage are we compiling? Required for GLSL. Ignored for WGSL. */\n stage?: 'vertex' | 'fragment' | 'compute';\n /** Shader source code */\n source: string;\n /** Optional shader source map (WebGPU only) */\n sourceMap?: string | null;\n /** Optional shader entry point (WebGPU only) */\n entryPoint?: string;\n /** Show shader source in browser? Overrides the device.props.debugShaders setting */\n debugShaders?: 'never' | 'errors' | 'warnings' | 'always';\n};\n\n/**\n * Immutable Shader object\n * In WebGPU the handle can be copied between threads\n */\nexport abstract class Shader extends Resource {\n override get [Symbol.toStringTag](): string {\n return 'Shader';\n }\n\n /** The stage of this shader */\n readonly stage: 'vertex' | 'fragment' | 'compute';\n /** The source code of this shader */\n readonly source: string;\n /** The compilation status of the shader. 'pending' if compilation is asynchronous, and on production */\n compilationStatus: 'pending' | 'success' | 'error' = 'pending';\n\n /** Create a new Shader instance */\n constructor(device: Device, props: ShaderProps) {\n props = {...props, debugShaders: props.debugShaders || device.props.debugShaders || 'errors'};\n super(device, {id: getShaderIdFromProps(props), ...props}, Shader.defaultProps);\n this.stage = this.props.stage;\n this.source = this.props.source;\n }\n\n abstract get asyncCompilationStatus(): Promise<'pending' | 'success' | 'error'>;\n\n /** Get compiler log asynchronously */\n abstract getCompilationInfo(): Promise;\n\n /** Get compiler log synchronously (WebGL only) */\n getCompilationInfoSync(): readonly CompilerMessage[] | null {\n return null;\n }\n\n /** Get translated shader source in host platform's native language (HLSL, GLSL, and even GLSL ES), if available */\n getTranslatedSource(): string | null {\n return null;\n }\n\n // PORTABLE HELPERS\n\n /** In browser logging of errors */\n async debugShader(): Promise {\n const trigger = this.props.debugShaders;\n switch (trigger) {\n case 'never':\n return;\n case 'errors':\n // On WebGL - Don't extract the log unless errors\n if (this.compilationStatus === 'success') {\n return;\n }\n break;\n case 'warnings':\n case 'always':\n break;\n }\n\n const messages = await this.getCompilationInfo();\n if (trigger === 'warnings' && messages?.length === 0) {\n return;\n }\n this._displayShaderLog(messages, this.id);\n }\n\n // PRIVATE\n\n /**\n * In-browser UI logging of errors\n * TODO - this HTML formatting code should not be in Device, should be pluggable\n */\n protected _displayShaderLog(messages: readonly CompilerMessage[], shaderId: string): void {\n // Return if under Node.js / incomplete `document` polyfills\n if (typeof document === 'undefined' || !document?.createElement) {\n return;\n }\n\n const shaderName: string = shaderId; // getShaderName(this.source) || ;\n const shaderTitle: string = `${this.stage} shader \"${shaderName}\"`;\n const htmlLog = formatCompilerLog(messages, this.source, {showSourceCode: 'all', html: true});\n // Show translated source if available\n const translatedSource = this.getTranslatedSource();\n\n const container = document.createElement('div');\n container.innerHTML = `\\\n

Compilation error in ${shaderTitle}

\n
\n
\n\n
\n
${htmlLog}
`;\n if (translatedSource) {\n container.innerHTML += `

Translated Source



${translatedSource}
`;\n }\n container.style.top = '0';\n container.style.left = '0';\n container.style.background = 'white';\n container.style.position = 'fixed';\n container.style.zIndex = '9999';\n container.style.maxWidth = '100vw';\n container.style.maxHeight = '100vh';\n container.style.overflowY = 'auto';\n document.body.appendChild(container);\n const error = container.querySelector('.luma-compiler-log-error');\n error?.scrollIntoView();\n (container.querySelector('button#close') as HTMLButtonElement).onclick = () => {\n container.remove();\n };\n (container.querySelector('button#copy') as HTMLButtonElement).onclick = () => {\n navigator.clipboard.writeText(this.source);\n };\n }\n\n static override defaultProps: Required = {\n ...Resource.defaultProps,\n language: 'auto',\n stage: undefined!,\n source: '',\n sourceMap: null,\n entryPoint: 'main',\n debugShaders: undefined!\n };\n}\n\n// HELPERS\n\n/** Deduce an id, from shader source, or supplied id, or shader type */\nfunction getShaderIdFromProps(props: ShaderProps): string {\n return getShaderName(props.source) || props.id || uid(`unnamed ${props.stage}-shader`);\n}\n\n/** Extracts GLSLIFY style naming of shaders: `#define SHADER_NAME ...` */\nfunction getShaderName(shader: string, defaultName: string = 'unnamed'): string {\n const SHADER_NAME_REGEXP = /#define[\\s*]SHADER_NAME[\\s*]([A-Za-z0-9_-]+)[\\s*]/;\n const match = SHADER_NAME_REGEXP.exec(shader);\n return match?.[1] ?? defaultName;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {\n TextureFormatColor,\n TextureFormatDepthStencil,\n TextureFormat\n} from '../../shadertypes/texture-types/texture-formats';\nimport type {Device} from '../device';\nimport {Resource, ResourceProps} from './resource';\nimport {Texture} from './texture';\nimport {TextureView} from './texture-view';\nimport {log} from '../../utils/log';\n\nexport type FramebufferProps = ResourceProps & {\n width?: number;\n height?: number;\n colorAttachments?: (TextureView | Texture | TextureFormatColor)[];\n depthStencilAttachment?: (TextureView | Texture | TextureFormatDepthStencil) | null;\n};\n\n/**\n * Create new textures with correct size for all attachments.\n * @note resize() destroys existing textures (if size has changed).\n */\nexport abstract class Framebuffer extends Resource {\n override get [Symbol.toStringTag](): string {\n return 'Framebuffer';\n }\n\n /** Width of all attachments in this framebuffer */\n width: number;\n /** Height of all attachments in this framebuffer */\n height: number;\n /** Color attachments */\n abstract colorAttachments: TextureView[];\n /** Depth-stencil attachment, if provided */\n abstract depthStencilAttachment: TextureView | null;\n\n constructor(device: Device, props: FramebufferProps = {}) {\n super(device, props, Framebuffer.defaultProps);\n this.width = this.props.width;\n this.height = this.props.height;\n }\n\n /**\n * Create a copy of this framebuffer with new attached textures, with same props but of the specified size.\n * @note Does not copy contents of the attached textures.\n */\n clone(size?: {width: number; height: number}): Framebuffer {\n const colorAttachments = this.colorAttachments.map(colorAttachment =>\n colorAttachment.texture.clone(size)\n );\n\n const depthStencilAttachment =\n this.depthStencilAttachment && this.depthStencilAttachment.texture.clone(size);\n\n return this.device.createFramebuffer({\n ...this.props,\n ...size,\n colorAttachments,\n depthStencilAttachment\n });\n }\n\n /**\n * Resizes all attachments\n * @note resize() destroys existing textures (if size has changed).\n * @deprecated Use framebuffer.clone()\n */\n resize(size: {width: number; height: number}): void;\n resize(size: [width: number, height: number]): void;\n resize(): void;\n resize(size?: {width: number; height: number} | [width: number, height: number]): void {\n let updateSize: boolean = !size;\n if (size) {\n const [width, height] = Array.isArray(size) ? size : [size.width, size.height];\n updateSize = updateSize || height !== this.height || width !== this.width;\n this.width = width;\n this.height = height;\n }\n if (updateSize) {\n log.log(2, `Resizing framebuffer ${this.id} to ${this.width}x${this.height}`)();\n this.resizeAttachments(this.width, this.height);\n }\n }\n\n /** Auto creates any textures */\n protected autoCreateAttachmentTextures(): void {\n if (this.props.colorAttachments.length === 0 && !this.props.depthStencilAttachment) {\n throw new Error('Framebuffer has noattachments');\n }\n\n this.colorAttachments = this.props.colorAttachments.map((attachment, index) => {\n if (typeof attachment === 'string') {\n const texture = this.createColorTexture(attachment, index);\n this.attachResource(texture);\n return texture.view;\n }\n if (attachment instanceof Texture) {\n return attachment.view;\n }\n return attachment;\n });\n\n const attachment = this.props.depthStencilAttachment;\n if (attachment) {\n if (typeof attachment === 'string') {\n const texture = this.createDepthStencilTexture(attachment);\n this.attachResource(texture);\n this.depthStencilAttachment = texture.view;\n } else if (attachment instanceof Texture) {\n this.depthStencilAttachment = attachment.view;\n } else {\n this.depthStencilAttachment = attachment;\n }\n }\n }\n\n /** Create a color texture */\n protected createColorTexture(format: TextureFormat, index: number): Texture {\n return this.device.createTexture({\n id: `${this.id}-color-attachment-${index}`,\n usage: Texture.RENDER_ATTACHMENT,\n format,\n width: this.width,\n height: this.height,\n // TODO deprecated? - luma.gl v8 compatibility\n sampler: {\n magFilter: 'linear',\n minFilter: 'linear'\n }\n });\n }\n\n /** Create depth stencil texture */\n protected createDepthStencilTexture(format: TextureFormat): Texture {\n return this.device.createTexture({\n id: `${this.id}-depth-stencil-attachment`,\n usage: Texture.RENDER_ATTACHMENT,\n format,\n width: this.width,\n height: this.height\n });\n }\n\n /**\n * Default implementation of resize\n * Creates new textures with correct size for all attachments.\n * and destroys existing textures if owned\n */\n protected resizeAttachments(width: number, height: number): void {\n this.colorAttachments.forEach((colorAttachment, i) => {\n const resizedTexture = colorAttachment.texture.clone({\n width,\n height\n });\n this.destroyAttachedResource(colorAttachment);\n this.colorAttachments[i] = resizedTexture.view;\n this.attachResource(resizedTexture.view);\n });\n\n if (this.depthStencilAttachment) {\n const resizedTexture = this.depthStencilAttachment.texture.clone({\n width,\n height\n });\n this.destroyAttachedResource(this.depthStencilAttachment);\n this.depthStencilAttachment = resizedTexture.view;\n this.attachResource(resizedTexture);\n }\n\n this.updateAttachments();\n }\n\n /** Implementation is expected to update any underlying binding (WebGL framebuffer attachment) */\n protected abstract updateAttachments(): void;\n\n static override defaultProps: Required = {\n ...Resource.defaultProps,\n width: 1,\n height: 1,\n colorAttachments: [], // ['rgba8unorm'],\n depthStencilAttachment: null // 'depth24plus-stencil8'\n };\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport type {PrimitiveTopology, RenderPipelineParameters} from '../types/parameters';\nimport type {ShaderLayout, Bindings, BindingsByGroup} from '../types/shader-layout';\nimport type {BufferLayout} from '../types/buffer-layout';\nimport type {\n TextureFormatColor,\n TextureFormatDepthStencil\n} from '@luma.gl/core/shadertypes/texture-types/texture-formats';\nimport type {Shader} from './shader';\nimport type {SharedRenderPipeline} from './shared-render-pipeline';\nimport type {RenderPass} from './render-pass';\nimport {Resource, ResourceProps} from './resource';\nimport {VertexArray} from './vertex-array';\nimport {TransformFeedback} from './transform-feedback';\n\nexport type RenderPipelineProps = ResourceProps & {\n // Shaders and shader layout\n\n /** Compiled vertex shader */\n vs?: Shader | null;\n /** Name of vertex shader stage main function (defaults to 'main'). WGSL only */\n vertexEntryPoint?: string; //\n /** Constant values to apply to compiled vertex shader. Do not require re-compilation. (WGSL only) */\n vsConstants?: Record; // WGSL only\n /** Compiled fragment shader */\n fs?: Shader | null;\n /** Name of fragment shader stage main function (defaults to 'main'). WGSL only */\n fragmentEntryPoint?: string; // WGSL only\n /** Constant values to apply to compiled fragment shader. Do not require re-compilation. (WGSL only) */\n fsConstants?: Record;\n\n /** Describes the attributes and bindings exposed by the pipeline shader(s). */\n shaderLayout?: ShaderLayout | null;\n /** Describes the buffers accepted by this pipeline and how they are mapped to shader attributes. */\n bufferLayout?: BufferLayout[]; // Record\n\n /** Determines how vertices are read from the 'vertex' attributes */\n topology?: PrimitiveTopology;\n\n // color attachment information (needed on WebGPU)\n\n /** Color attachments expected by this pipeline. Defaults to [device.preferredColorFormat]. Array needs not be contiguous. */\n colorAttachmentFormats?: (TextureFormatColor | null)[];\n /** Depth attachment expected by this pipeline. Defaults to device.preferredDepthFormat, if depthWriteEnables parameter is set */\n depthStencilAttachmentFormat?: TextureFormatDepthStencil;\n\n /** Parameters that are controlled by pipeline */\n parameters?: RenderPipelineParameters;\n\n /** Transform feedback varyings captured when linking a WebGL render pipeline. WebGL only. */\n varyings?: string[];\n /** Transform feedback buffer mode used when linking a WebGL render pipeline. WebGL only. */\n bufferMode?: number;\n\n /** Some applications intentionally supply unused attributes and bindings, and want to disable warnings */\n disableWarnings?: boolean;\n\n /** Internal hook for backend-specific shared pipeline implementations. */\n _sharedRenderPipeline?: SharedRenderPipeline;\n\n // Dynamic bindings (TODO - pipelines should be immutable, move to RenderPass)\n /** Buffers, Textures, Samplers for the shader bindings */\n bindings?: Bindings;\n /** Bindings grouped by bind-group index */\n bindGroups?: BindingsByGroup;\n};\n\n/**\n * A compiled and linked shader program\n */\nexport abstract class RenderPipeline extends Resource {\n override get [Symbol.toStringTag](): string {\n return 'RenderPipeline';\n }\n\n abstract readonly vs: Shader;\n abstract readonly fs: Shader | null;\n\n /** The merged layout */\n shaderLayout: ShaderLayout;\n /** Buffer map describing buffer interleaving etc */\n readonly bufferLayout: BufferLayout[];\n /** The linking status of the pipeline. 'pending' if linking is asynchronous, and on production */\n linkStatus: 'pending' | 'success' | 'error' = 'pending';\n /** The hash of the pipeline */\n hash: string = '';\n /** Optional shared backend implementation */\n sharedRenderPipeline: SharedRenderPipeline | null = null;\n\n /** Whether shader or pipeline compilation/linking is still in progress */\n get isPending(): boolean {\n return (\n this.linkStatus === 'pending' ||\n this.vs.compilationStatus === 'pending' ||\n this.fs?.compilationStatus === 'pending'\n );\n }\n\n /** Whether shader or pipeline compilation/linking has failed */\n get isErrored(): boolean {\n return (\n this.linkStatus === 'error' ||\n this.vs.compilationStatus === 'error' ||\n this.fs?.compilationStatus === 'error'\n );\n }\n\n constructor(device: Device, props: RenderPipelineProps) {\n super(device, props, RenderPipeline.defaultProps);\n this.shaderLayout = this.props.shaderLayout!;\n this.bufferLayout = this.props.bufferLayout || [];\n this.sharedRenderPipeline = this.props._sharedRenderPipeline || null;\n }\n\n /** Draw call. Returns false if the draw call was aborted (due to resources still initializing) */\n abstract draw(options: {\n /** Render pass to draw into (targeting screen or framebuffer) */\n renderPass?: RenderPass;\n /** Parameters to be set during draw call. Note that most parameters can only be overridden in WebGL. */\n parameters?: RenderPipelineParameters;\n /** Topology. Note can only be overridden in WebGL. */\n topology?: PrimitiveTopology;\n /** vertex attributes */\n vertexArray: VertexArray;\n /** Use instanced rendering? */\n isInstanced?: boolean;\n /** Number of \"rows\" in 'instance' buffers */\n instanceCount?: number;\n /** Number of \"rows\" in 'vertex' buffers */\n vertexCount?: number;\n /** Number of \"rows\" in index buffer */\n indexCount?: number;\n /** First vertex to draw from */\n firstVertex?: number;\n /** First index to draw from */\n firstIndex?: number;\n /** First instance to draw from */\n firstInstance?: number;\n baseVertex?: number;\n /** Transform feedback. WebGL only. */\n transformFeedback?: TransformFeedback;\n /** Bindings applied for this draw (textures, samplers, uniform buffers) */\n bindings?: Bindings;\n /** Bindings grouped by bind-group index */\n bindGroups?: BindingsByGroup;\n /** Optional stable cache keys for backend bind-group reuse */\n _bindGroupCacheKeys?: Partial>;\n /** WebGL-only uniforms */\n uniforms?: Record;\n }): boolean;\n\n static override defaultProps: Required = {\n ...Resource.defaultProps,\n\n vs: null,\n vertexEntryPoint: 'vertexMain',\n vsConstants: {},\n\n fs: null,\n fragmentEntryPoint: 'fragmentMain',\n fsConstants: {},\n\n shaderLayout: null,\n bufferLayout: [],\n topology: 'triangle-list',\n\n colorAttachmentFormats: undefined!,\n depthStencilAttachmentFormat: undefined!,\n\n parameters: {},\n varyings: undefined!,\n bufferMode: undefined!,\n disableWarnings: false,\n _sharedRenderPipeline: undefined!,\n bindings: undefined!,\n bindGroups: undefined!\n };\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport type {Shader} from './shader';\nimport {Resource, type ResourceProps} from './resource';\n\nexport type SharedRenderPipelineProps = ResourceProps & {\n handle?: unknown;\n vs: Shader;\n fs: Shader;\n varyings?: string[];\n bufferMode?: number;\n};\n\n/**\n * Internal base class for backend-specific shared render-pipeline implementations.\n * Backends may use this to share expensive linked/program state across multiple\n * `RenderPipeline` wrappers.\n */\nexport abstract class SharedRenderPipeline extends Resource {\n override get [Symbol.toStringTag](): string {\n return 'SharedRenderPipeline';\n }\n\n abstract override readonly device: Device;\n abstract override readonly handle: unknown;\n\n constructor(device: Device, props: SharedRenderPipelineProps) {\n super(device, props, {\n ...Resource.defaultProps,\n handle: undefined!,\n vs: undefined!,\n fs: undefined!,\n varyings: undefined!,\n bufferMode: undefined!\n });\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Resource, ResourceProps} from './resource';\nimport type {ComputeShaderLayout, Bindings, BindingsByGroup} from '../types/shader-layout';\nimport type {Device} from '../device';\nimport type {Shader} from './shader';\n\n/**\n * Properties for a compute pipeline\n */\nexport type ComputePipelineProps = ResourceProps & {\n handle?: unknown;\n /** Compiled shader object */\n shader: Shader;\n /** The entry point, defaults to main */\n entryPoint?: string;\n /** These are WGSL constant values - different from GLSL defines in that shader does not need to be recompiled */\n constants?: Record;\n /** Describes the attributes and bindings exposed by the pipeline shader(s). */\n shaderLayout?: ComputeShaderLayout | null;\n};\n\n/**\n * A compiled and linked shader program for compute\n */\nexport abstract class ComputePipeline extends Resource {\n override get [Symbol.toStringTag](): string {\n return 'ComputePipeline';\n }\n\n hash: string = '';\n /** The merged shader layout */\n shaderLayout: ComputeShaderLayout;\n\n constructor(device: Device, props: ComputePipelineProps) {\n super(device, props, ComputePipeline.defaultProps);\n this.shaderLayout = props.shaderLayout!;\n }\n\n /**\n * @todo Use renderpass.setBindings() ?\n * @todo Do we want to expose BindGroups in the API and remove this?\n */\n abstract setBindings(bindings: Bindings | BindingsByGroup): void;\n\n static override defaultProps: Required = {\n ...Resource.defaultProps,\n shader: undefined!,\n entryPoint: undefined!,\n constants: {},\n shaderLayout: undefined!\n };\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Device} from '../adapter/device';\nimport {ComputePipeline, type ComputePipelineProps} from '../adapter/resources/compute-pipeline';\nimport {RenderPipeline, type RenderPipelineProps} from '../adapter/resources/render-pipeline';\nimport {Resource} from '../adapter/resources/resource';\nimport type {SharedRenderPipeline} from '../adapter/resources/shared-render-pipeline';\nimport {log} from '../utils/log';\nimport {uid} from '../utils/uid';\nimport type {CoreModuleState} from './core-module-state';\n\nexport type PipelineFactoryProps = RenderPipelineProps;\n\ntype CacheItem> = {resource: ResourceT; useCount: number};\n\n/**\n * Efficiently creates / caches pipelines\n */\nexport class PipelineFactory {\n static defaultProps: Required = {...RenderPipeline.defaultProps};\n\n /** Get the singleton default pipeline factory for the specified device */\n static getDefaultPipelineFactory(device: Device): PipelineFactory {\n const moduleData = device.getModuleData('@luma.gl/core');\n moduleData.defaultPipelineFactory ||= new PipelineFactory(device);\n return moduleData.defaultPipelineFactory;\n }\n\n readonly device: Device;\n\n private _hashCounter: number = 0;\n private readonly _hashes: Record = {};\n private readonly _renderPipelineCache: Record> = {};\n private readonly _computePipelineCache: Record> = {};\n private readonly _sharedRenderPipelineCache: Record> = {};\n\n get [Symbol.toStringTag](): string {\n return 'PipelineFactory';\n }\n\n toString(): string {\n return `PipelineFactory(${this.device.id})`;\n }\n\n constructor(device: Device) {\n this.device = device;\n }\n\n /**\n * WebGL has two cache layers with different priorities:\n * - `_sharedRenderPipelineCache` owns `WEBGLSharedRenderPipeline` / `WebGLProgram` reuse.\n * - `_renderPipelineCache` owns `RenderPipeline` wrapper reuse.\n *\n * Shared WebGL program reuse is the hard requirement. Wrapper reuse is beneficial,\n * but wrapper cache misses are acceptable if that keeps the cache logic simple and\n * prevents incorrect cache hits.\n *\n * In particular, wrapper hash logic must never force program creation or linked-program\n * introspection just to decide whether a shared WebGL program can be reused.\n */\n /** Return a RenderPipeline matching supplied props. Reuses an equivalent pipeline if already created. */\n createRenderPipeline(props: RenderPipelineProps): RenderPipeline {\n if (!this.device.props._cachePipelines) {\n return this.device.createRenderPipeline(props);\n }\n\n const allProps: Required = {...RenderPipeline.defaultProps, ...props};\n\n const cache = this._renderPipelineCache;\n const hash = this._hashRenderPipeline(allProps);\n\n let pipeline: RenderPipeline = cache[hash]?.resource;\n if (!pipeline) {\n const sharedRenderPipeline =\n this.device.type === 'webgl' && this.device.props._sharePipelines\n ? this.createSharedRenderPipeline(allProps)\n : undefined;\n pipeline = this.device.createRenderPipeline({\n ...allProps,\n id: allProps.id ? `${allProps.id}-cached` : uid('unnamed-cached'),\n _sharedRenderPipeline: sharedRenderPipeline\n });\n pipeline.hash = hash;\n cache[hash] = {resource: pipeline, useCount: 1};\n if (this.device.props.debugFactories) {\n log.log(3, `${this}: ${pipeline} created, count=${cache[hash].useCount}`)();\n }\n } else {\n cache[hash].useCount++;\n if (this.device.props.debugFactories) {\n log.log(\n 3,\n `${this}: ${cache[hash].resource} reused, count=${cache[hash].useCount}, (id=${props.id})`\n )();\n }\n }\n\n return pipeline;\n }\n\n /** Return a ComputePipeline matching supplied props. Reuses an equivalent pipeline if already created. */\n createComputePipeline(props: ComputePipelineProps): ComputePipeline {\n if (!this.device.props._cachePipelines) {\n return this.device.createComputePipeline(props);\n }\n\n const allProps: Required = {...ComputePipeline.defaultProps, ...props};\n\n const cache = this._computePipelineCache;\n const hash = this._hashComputePipeline(allProps);\n\n let pipeline: ComputePipeline = cache[hash]?.resource;\n if (!pipeline) {\n pipeline = this.device.createComputePipeline({\n ...allProps,\n id: allProps.id ? `${allProps.id}-cached` : undefined\n });\n pipeline.hash = hash;\n cache[hash] = {resource: pipeline, useCount: 1};\n if (this.device.props.debugFactories) {\n log.log(3, `${this}: ${pipeline} created, count=${cache[hash].useCount}`)();\n }\n } else {\n cache[hash].useCount++;\n if (this.device.props.debugFactories) {\n log.log(\n 3,\n `${this}: ${cache[hash].resource} reused, count=${cache[hash].useCount}, (id=${props.id})`\n )();\n }\n }\n\n return pipeline;\n }\n\n release(pipeline: RenderPipeline | ComputePipeline): void {\n if (!this.device.props._cachePipelines) {\n pipeline.destroy();\n return;\n }\n\n const cache = this._getCache(pipeline);\n const hash = pipeline.hash;\n\n cache[hash].useCount--;\n if (cache[hash].useCount === 0) {\n this._destroyPipeline(pipeline);\n if (this.device.props.debugFactories) {\n log.log(3, `${this}: ${pipeline} released and destroyed`)();\n }\n } else if (cache[hash].useCount < 0) {\n log.error(`${this}: ${pipeline} released, useCount < 0, resetting`)();\n cache[hash].useCount = 0;\n } else if (this.device.props.debugFactories) {\n log.log(3, `${this}: ${pipeline} released, count=${cache[hash].useCount}`)();\n }\n }\n\n createSharedRenderPipeline(props: RenderPipelineProps): SharedRenderPipeline {\n const sharedPipelineHash = this._hashSharedRenderPipeline(props);\n let sharedCacheItem = this._sharedRenderPipelineCache[sharedPipelineHash];\n if (!sharedCacheItem) {\n const sharedRenderPipeline = this.device._createSharedRenderPipelineWebGL(props);\n sharedCacheItem = {resource: sharedRenderPipeline, useCount: 0};\n this._sharedRenderPipelineCache[sharedPipelineHash] = sharedCacheItem;\n }\n sharedCacheItem.useCount++;\n return sharedCacheItem.resource;\n }\n\n releaseSharedRenderPipeline(pipeline: RenderPipeline): void {\n if (!pipeline.sharedRenderPipeline) {\n return;\n }\n\n const sharedPipelineHash = this._hashSharedRenderPipeline(pipeline.sharedRenderPipeline.props);\n const sharedCacheItem = this._sharedRenderPipelineCache[sharedPipelineHash];\n if (!sharedCacheItem) {\n return;\n }\n\n sharedCacheItem.useCount--;\n if (sharedCacheItem.useCount === 0) {\n sharedCacheItem.resource.destroy();\n delete this._sharedRenderPipelineCache[sharedPipelineHash];\n }\n }\n\n // PRIVATE\n\n /** Destroy a cached pipeline, removing it from the cache if configured to do so. */\n private _destroyPipeline(pipeline: RenderPipeline | ComputePipeline): boolean {\n const cache = this._getCache(pipeline);\n\n if (!this.device.props._destroyPipelines) {\n return false;\n }\n\n delete cache[pipeline.hash];\n pipeline.destroy();\n if (pipeline instanceof RenderPipeline) {\n this.releaseSharedRenderPipeline(pipeline);\n }\n return true;\n }\n\n /** Get the appropriate cache for the type of pipeline */\n private _getCache(\n pipeline: RenderPipeline | ComputePipeline\n ): Record> | Record> {\n let cache:\n | Record>\n | Record>\n | undefined;\n if (pipeline instanceof ComputePipeline) {\n cache = this._computePipelineCache;\n }\n if (pipeline instanceof RenderPipeline) {\n cache = this._renderPipelineCache;\n }\n if (!cache) {\n throw new Error(`${this}`);\n }\n if (!cache[pipeline.hash]) {\n throw new Error(`${this}: ${pipeline} matched incorrect entry`);\n }\n return cache;\n }\n\n /** Calculate a hash based on all the inputs for a compute pipeline */\n private _hashComputePipeline(props: ComputePipelineProps): string {\n const {type} = this.device;\n const shaderHash = this._getHash(props.shader.source);\n const shaderLayoutHash = this._getHash(JSON.stringify(props.shaderLayout));\n return `${type}/C/${shaderHash}SL${shaderLayoutHash}`;\n }\n\n /** Calculate a hash based on all the inputs for a render pipeline */\n private _hashRenderPipeline(props: RenderPipelineProps): string {\n // Backend-specific hashing requirements:\n // - WebGPU hash keys must include every immutable descriptor-shaping input that can\n // change the created `GPURenderPipeline`, including attachment formats.\n // - WebGL hash keys only govern wrapper reuse. They must remain compatible with\n // shared-program reuse and must not depend on linked-program introspection just\n // to decide whether a shared `WebGLProgram` can be reused.\n //\n // General exclusions:\n // - `id`, `handle`: resource identity / caller-supplied handles, not cache shape\n // - `bindings`: mutable per-pipeline compatibility state\n // - `disableWarnings`: logging only, no rendering impact\n // - `vsConstants`, `fsConstants`: currently unused by pipeline creation\n const vsHash = props.vs ? this._getHash(props.vs.source) : 0;\n const fsHash = props.fs ? this._getHash(props.fs.source) : 0;\n const varyingHash = this._getWebGLVaryingHash(props);\n const shaderLayoutHash = this._getHash(JSON.stringify(props.shaderLayout));\n const bufferLayoutHash = this._getHash(JSON.stringify(props.bufferLayout));\n\n const {type} = this.device;\n switch (type) {\n case 'webgl':\n // WebGL wrappers preserve default topology and parameter semantics for direct\n // callers, even though the underlying linked program may be shared separately.\n // Future WebGL-only additions here must not turn wrapper reuse into a prerequisite\n // for shared `WebGLProgram` reuse.\n const webglParameterHash = this._getHash(JSON.stringify(props.parameters));\n return `${type}/R/${vsHash}/${fsHash}V${varyingHash}T${props.topology}P${webglParameterHash}SL${shaderLayoutHash}BL${bufferLayoutHash}`;\n\n case 'webgpu':\n default:\n // On WebGPU we need to rebuild the pipeline if topology, entry points,\n // shader/layout data, parameters, bufferLayout or attachment formats change.\n // Attachment formats must stay in the key so screen and offscreen passes do not\n // accidentally alias the same cached `GPURenderPipeline`.\n const entryPointHash = this._getHash(\n JSON.stringify({\n vertexEntryPoint: props.vertexEntryPoint,\n fragmentEntryPoint: props.fragmentEntryPoint\n })\n );\n const parameterHash = this._getHash(JSON.stringify(props.parameters));\n const attachmentHash = this._getWebGPUAttachmentHash(props);\n // TODO - Can json.stringify() generate different strings for equivalent objects if order of params is different?\n // create a deepHash() to deduplicate?\n return `${type}/R/${vsHash}/${fsHash}V${varyingHash}T${props.topology}EP${entryPointHash}P${parameterHash}SL${shaderLayoutHash}BL${bufferLayoutHash}A${attachmentHash}`;\n }\n }\n\n // This is the only gate for shared `WebGLProgram` reuse.\n // Only include inputs that affect program linking or transform-feedback linkage.\n // Wrapper-only concerns such as topology, parameters, attachment formats and layout\n // overrides must not be added here.\n private _hashSharedRenderPipeline(props: RenderPipelineProps): string {\n const vsHash = props.vs ? this._getHash(props.vs.source) : 0;\n const fsHash = props.fs ? this._getHash(props.fs.source) : 0;\n const varyingHash = this._getWebGLVaryingHash(props);\n return `webgl/S/${vsHash}/${fsHash}V${varyingHash}`;\n }\n\n private _getHash(key: string): number {\n if (this._hashes[key] === undefined) {\n this._hashes[key] = this._hashCounter++;\n }\n return this._hashes[key];\n }\n\n private _getWebGLVaryingHash(props: RenderPipelineProps): number {\n const {varyings = [], bufferMode = null} = props;\n return this._getHash(JSON.stringify({varyings, bufferMode}));\n }\n\n private _getWebGPUAttachmentHash(props: RenderPipelineProps): number {\n const colorAttachmentFormats = props.colorAttachmentFormats ?? [\n this.device.preferredColorFormat\n ];\n const depthStencilAttachmentFormat = props.parameters?.depthWriteEnabled\n ? props.depthStencilAttachmentFormat || this.device.preferredDepthFormat\n : null;\n\n return this._getHash(\n JSON.stringify({\n colorAttachmentFormats,\n depthStencilAttachmentFormat\n })\n );\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Device} from '../adapter/device';\nimport {Shader, type ShaderProps} from '../adapter/resources/shader';\nimport {log} from '../utils/log';\nimport type {CoreModuleState} from './core-module-state';\n\ntype CacheItem = {resource: Shader; useCount: number};\n\n/** Manages a cached pool of Shaders for reuse. */\nexport class ShaderFactory {\n static readonly defaultProps: Required = {...Shader.defaultProps};\n\n /** Returns the default ShaderFactory for the given {@link Device}, creating one if necessary. */\n static getDefaultShaderFactory(device: Device): ShaderFactory {\n const moduleData = device.getModuleData('@luma.gl/core');\n moduleData.defaultShaderFactory ||= new ShaderFactory(device);\n return moduleData.defaultShaderFactory;\n }\n\n public readonly device: Device;\n\n private readonly _cache: Record = {};\n\n get [Symbol.toStringTag](): string {\n return 'ShaderFactory';\n }\n\n toString(): string {\n return `${this[Symbol.toStringTag]}(${this.device.id})`;\n }\n\n /** @internal */\n constructor(device: Device) {\n this.device = device;\n }\n\n /** Requests a {@link Shader} from the cache, creating a new Shader only if necessary. */\n createShader(props: ShaderProps): Shader {\n if (!this.device.props._cacheShaders) {\n return this.device.createShader(props);\n }\n\n const key = this._hashShader(props);\n\n let cacheEntry = this._cache[key];\n if (!cacheEntry) {\n const resource = this.device.createShader({\n ...props,\n id: props.id ? `${props.id}-cached` : undefined\n });\n this._cache[key] = cacheEntry = {resource, useCount: 1};\n if (this.device.props.debugFactories) {\n log.log(3, `${this}: Created new shader ${resource.id}`)();\n }\n } else {\n cacheEntry.useCount++;\n if (this.device.props.debugFactories) {\n log.log(\n 3,\n `${this}: Reusing shader ${cacheEntry.resource.id} count=${cacheEntry.useCount}`\n )();\n }\n }\n\n return cacheEntry.resource;\n }\n\n /** Releases a previously-requested {@link Shader}, destroying it if no users remain. */\n release(shader: Shader): void {\n if (!this.device.props._cacheShaders) {\n shader.destroy();\n return;\n }\n\n const key = this._hashShader(shader);\n const cacheEntry = this._cache[key];\n if (cacheEntry) {\n cacheEntry.useCount--;\n if (cacheEntry.useCount === 0) {\n if (this.device.props._destroyShaders) {\n delete this._cache[key];\n cacheEntry.resource.destroy();\n if (this.device.props.debugFactories) {\n log.log(3, `${this}: Releasing shader ${shader.id}, destroyed`)();\n }\n }\n } else if (cacheEntry.useCount < 0) {\n throw new Error(`ShaderFactory: Shader ${shader.id} released too many times`);\n } else if (this.device.props.debugFactories) {\n log.log(3, `${this}: Releasing shader ${shader.id} count=${cacheEntry.useCount}`)();\n }\n }\n }\n\n // PRIVATE\n\n protected _hashShader(value: Shader | ShaderProps): string {\n return `${value.stage}:${value.source}`;\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {\n BindingDeclaration,\n Bindings,\n BindingsByGroup,\n ComputeShaderLayout,\n ShaderLayout\n} from '../adapter/types/shader-layout';\nimport {log} from '../utils/log';\n\ntype AnyShaderLayout = Pick;\n\nexport function getShaderLayoutBinding(\n shaderLayout: AnyShaderLayout,\n bindingName: string,\n options?: {ignoreWarnings?: boolean}\n): BindingDeclaration | null {\n const bindingLayout = shaderLayout.bindings.find(\n binding =>\n binding.name === bindingName ||\n `${binding.name.toLocaleLowerCase()}uniforms` === bindingName.toLocaleLowerCase()\n );\n\n if (!bindingLayout && !options?.ignoreWarnings) {\n log.warn(`Binding ${bindingName} not set: Not found in shader layout.`)();\n }\n\n return bindingLayout || null;\n}\n\nexport function normalizeBindingsByGroup(\n shaderLayout: AnyShaderLayout,\n bindingsOrBindGroups?: Bindings | BindingsByGroup\n): BindingsByGroup {\n if (!bindingsOrBindGroups) {\n return {};\n }\n\n if (areBindingsGrouped(bindingsOrBindGroups)) {\n const bindGroups = bindingsOrBindGroups as BindingsByGroup;\n return Object.fromEntries(\n Object.entries(bindGroups).map(([group, bindings]) => [Number(group), {...bindings}])\n ) as BindingsByGroup;\n }\n\n const bindGroups: BindingsByGroup = {};\n for (const [bindingName, binding] of Object.entries(bindingsOrBindGroups as Bindings)) {\n const bindingLayout = getShaderLayoutBinding(shaderLayout, bindingName);\n const group = bindingLayout?.group ?? 0;\n bindGroups[group] ||= {};\n bindGroups[group][bindingName] = binding;\n }\n\n return bindGroups;\n}\n\nexport function flattenBindingsByGroup(bindGroups: BindingsByGroup): Bindings {\n const bindings: Bindings = {};\n for (const groupBindings of Object.values(bindGroups)) {\n Object.assign(bindings, groupBindings);\n }\n return bindings;\n}\n\nfunction areBindingsGrouped(bindingsOrBindGroups: Bindings | BindingsByGroup): boolean {\n const keys = Object.keys(bindingsOrBindGroups);\n return keys.length > 0 && keys.every(key => /^\\d+$/.test(key));\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {NumberArray4, TypedArray} from '@math.gl/types';\nimport type {Device} from '../device';\nimport type {RenderPassParameters} from '../types/parameters';\n// import {Binding} from '../types/shader-layout';\nimport {Resource, ResourceProps} from './resource';\nimport {Framebuffer} from './framebuffer';\nimport {QuerySet} from './query-set';\n\n/**\n * Properties for a RenderPass instance is a required parameter to all draw calls.\n */\nexport type RenderPassProps = ResourceProps & {\n /** Framebuffer specifies which textures to render into. Default gets framebuffer from canvas context. */\n framebuffer?: Framebuffer | null;\n /** Control viewport, scissor rect, blend constant and stencil ref */\n parameters?: RenderPassParameters;\n\n // TODO - API needs to be able to control multiple render targets\n\n /** Clear value for color attachment, or false to preserve the previous value */\n clearColor?: NumberArray4 | TypedArray | false;\n /** Experimental: Clear color values for multiple color attachments. Must specify typed arrays. props.clearColor will be ignored. */\n clearColors?: (TypedArray | false)[];\n /** Clear value for depth attachment (true === `1`), or false to preserve the previous value. Must be between 0.0 (near) and 1.0 (far), inclusive. */\n clearDepth?: number | false;\n /** Clear value for stencil attachment (true === `0`), or false to preserve the previous value. Converted to the type and number of LSBs as the number of bits in the stencil aspect */\n clearStencil?: number | false;\n\n /** Indicates that the depth component is read only. */\n depthReadOnly?: boolean;\n /** Indicates that the stencil component is read only. */\n stencilReadOnly?: boolean;\n\n /** Whether to disable / discard the output of the rasterizer */\n discard?: boolean;\n\n /** QuerySet to write begin/end timestamps to */\n occlusionQuerySet?: QuerySet;\n /** QuerySet to write begin/end timestamps to */\n timestampQuerySet?: QuerySet;\n /** QuerySet index to write begin timestamp to. No timestamp is written if not provided. */\n beginTimestampIndex?: number;\n /** QuerySet index to write end timestamp to. No timestamp is written if not provided. */\n endTimestampIndex?: number;\n};\n\n/**\n * A RenderPass instance is a required parameter to all draw calls.\n *\n * It holds a combination of\n * - render targets (specified via a framebuffer)\n * - clear colors, read/write, discard information for the framebuffer attachments\n * - a couple of mutable parameters ()\n */\nexport abstract class RenderPass extends Resource {\n /** TODO - should be [0, 0, 0, 0], update once deck.gl tests run clean */\n static defaultClearColor: [number, number, number, number] = [0, 0, 0, 1];\n /** Depth 1.0 represents the far plance */\n static defaultClearDepth = 1;\n /** Clears all stencil bits */\n static defaultClearStencil = 0;\n\n override get [Symbol.toStringTag](): string {\n return 'RenderPass';\n }\n\n constructor(device: Device, props: RenderPassProps) {\n props = RenderPass.normalizeProps(device, props);\n super(device, props, RenderPass.defaultProps);\n }\n\n /** Call when rendering is done in this pass. */\n abstract end(): void;\n\n /** A few parameters can be changed at any time (viewport, scissorRect, blendColor, stencilReference) */\n abstract setParameters(parameters: RenderPassParameters): void;\n\n // executeBundles(bundles: Iterable): void;\n\n /** Being an occlusion query. Value will be stored in the occlusionQuerySet at the index. Occlusion queries cannot be nested. */\n abstract beginOcclusionQuery(queryIndex: number): void;\n /** End an occlusion query. Stores result in the index specified in beginOcclusionQuery. */\n abstract endOcclusionQuery(): void;\n\n /** Begins a labeled debug group containing subsequent commands */\n abstract pushDebugGroup(groupLabel: string): void;\n /** Ends the labeled debug group most recently started by pushDebugGroup() */\n abstract popDebugGroup(): void;\n /** Marks a point in a stream of commands with a label */\n abstract insertDebugMarker(markerLabel: string): void;\n\n protected static normalizeProps(device: Device, props: RenderPassProps): RenderPassProps {\n return props;\n }\n\n /** Default properties for RenderPass */\n static override defaultProps: Required = {\n ...Resource.defaultProps,\n framebuffer: null,\n parameters: undefined!,\n clearColor: RenderPass.defaultClearColor,\n clearColors: undefined!,\n clearDepth: RenderPass.defaultClearDepth,\n clearStencil: RenderPass.defaultClearStencil,\n depthReadOnly: false,\n stencilReadOnly: false,\n discard: false,\n\n occlusionQuerySet: undefined!,\n timestampQuerySet: undefined!,\n beginTimestampIndex: undefined!,\n endTimestampIndex: undefined!\n };\n}\n\n// TODO - Can we align WebGL implementation with WebGPU API?\n// In WebGPU the following methods are on the renderpass instead of the renderpipeline\n// luma.gl keeps them on the pipeline for now, but that has some issues.\n\n// abstract setPipeline(pipeline: RenderPipeline): void {}\n// abstract setIndexBuffer()\n// abstract setVertexBuffer(slot: number, buffer: Buffer, offset: number): void;\n// abstract setBindings(bindings: Record): void;\n// abstract setParameters(parameters: RenderPassParameters);\n// abstract draw(options: {\n// abstract drawIndirect(indirectBuffer: GPUBuffer, indirectOffset: number): void;\n// abstract drawIndexedIndirect(indirectBuffer: GPUBuffer, indirectOffset: number): void;\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// import type {TypedArray} from '@math.gl/types';\nimport {Device} from '../device';\nimport {Resource, ResourceProps} from './resource';\nimport {QuerySet} from './query-set';\nimport {Buffer} from './buffer';\nimport {Texture} from './texture';\nimport type {RenderPass, RenderPassProps} from './render-pass';\nimport type {ComputePass, ComputePassProps} from './compute-pass';\nimport type {CommandBuffer, CommandBufferProps} from './command-buffer';\n\n// WEBGPU COMMAND ENCODER OPERATIONS\n\nexport type CopyBufferToBufferOptions = {\n sourceBuffer: Buffer;\n sourceOffset?: number;\n destinationBuffer: Buffer;\n destinationOffset?: number;\n size: number;\n};\n\nexport type CopyBufferToTextureOptions = {\n sourceBuffer: Buffer;\n byteOffset?: number;\n destinationTexture: Texture;\n mipLevel?: number; // = 0;\n origin?: [number, number, number];\n aspect?: 'all' | 'stencil-only' | 'depth-only';\n bytesPerRow: number;\n rowsPerImage: number;\n size: [number, number, number];\n};\n\nexport type CopyTextureToBufferOptions = {\n /** Texture to copy to/from. */\n sourceTexture: Texture;\n /** Mip-map level of the texture to copy to/from. (Default 0) */\n mipLevel?: number;\n /** Defines the origin of the copy - the minimum corner of the texture sub-region to copy to/from.\n * Together with `copySize`, defines the full copy sub-region.\n */\n /** Defines which aspects of the texture to copy to/from. */\n aspect?: 'all' | 'stencil-only' | 'depth-only';\n\n /** Width to copy */\n width?: number;\n height?: number;\n depthOrArrayLayers?: number;\n origin?: [number, number, number];\n\n /** Destination buffer */\n destinationBuffer: Buffer;\n /** Offset, in bytes, from the beginning of the buffer to the start of the image data (default 0) */\n byteOffset?: number;\n /**\n * The stride, in bytes, between the beginning of each block row and the subsequent block row.\n * Required if there are multiple block rows (i.e. the copy height or depth is more than one block).\n */\n bytesPerRow?: number;\n /**\n * Number of block rows per single image of the texture.\n * rowsPerImage × bytesPerRow is the stride, in bytes, between the beginning of each image of data and the subsequent image.\n * Required if there are multiple images (i.e. the copy depth is more than one).\n */\n rowsPerImage?: number;\n};\n\nexport type CopyTextureToTextureOptions = {\n /** Texture to copy to/from. */\n sourceTexture: Texture;\n /** Mip-map level of the texture to copy to/from. (Default 0) */\n mipLevel?: number;\n /** Defines the origin of the copy - the minimum corner of the texture sub-region to copy from. */\n origin?: [number, number, number];\n /** Defines which aspects of the {@link GPUImageCopyTexture#texture} to copy to/from. */\n aspect?: 'all' | 'stencil-only' | 'depth-only';\n\n /** Texture to copy to/from. */\n destinationTexture: Texture;\n /** Mip-map level of the texture to copy to/from. (Default 0) */\n destinationMipLevel?: number;\n /** Defines the origin of the copy - the minimum corner of the texture sub-region to copy to. */\n destinationOrigin?: [number, number, number];\n /** Defines which aspects of the {@link GPUImageCopyTexture#texture} to copy to/from. */\n destinationAspect?: 'all' | 'stencil-only' | 'depth-only';\n\n /** Width to copy */\n width?: number;\n height?: number;\n depthOrArrayLayers?: number;\n};\n\n// ADDITIONAL COMMAND ENCODER OPERATIONS DEFINED BY LUMA.GL\n\n/** Options for clearing a texture mip level */\nexport type ClearTextureOptions = {\n /** Texture to Clear. */\n texture: Texture;\n /** Mip-map level of the texture clear. (Default 0) */\n mipLevel?: number;\n /** Defines which aspects of the Texture to clear. */\n aspect?: 'all' | 'stencil-only' | 'depth-only';\n};\n\n// export type WriteBufferOptions = {\n// buffer: Buffer;\n// bufferOffset?: number;\n// data: BufferSource;\n// dataOffset?: number;\n// size?: number;\n// };\n\n// export type TextureWriteOptions = {\n// destination: Texture;\n// mipLevel?: number; // = 0;\n// origin?: [number, number, number] | number[];\n// aspect?: 'all' | 'stencil-only' | 'depth-only';\n// data: BufferSource;\n// // dataLayout;\n// offset: number;\n// bytesPerRow: number;\n// rowsPerImage: number;\n// size: [number, number, number] | number[];\n// };\n\nexport type CommandEncoderProps = ResourceProps & {\n measureExecutionTime?: boolean;\n timeProfilingQuerySet?: QuerySet | null;\n};\n\ntype PassWithTimestamps = {\n timestampQuerySet?: QuerySet;\n beginTimestampIndex?: number;\n endTimestampIndex?: number;\n};\n\n/**\n * Records commands onto a single backend command encoder and can finish them into one command\n * buffer. Resource helpers invoked through a CommandEncoder must record onto that encoder rather\n * than allocating hidden encoders or submitting work eagerly.\n */\nexport abstract class CommandEncoder extends Resource {\n override get [Symbol.toStringTag](): string {\n return 'CommandEncoder';\n }\n\n protected _timeProfilingQuerySet: QuerySet | null = null;\n protected _timeProfilingSlotCount: number = 0;\n _gpuTimeMs?: number;\n\n constructor(device: Device, props: CommandEncoderProps) {\n super(device, props, CommandEncoder.defaultProps);\n this._timeProfilingQuerySet = props.timeProfilingQuerySet ?? null;\n this._timeProfilingSlotCount = 0;\n this._gpuTimeMs = undefined;\n }\n\n /** Completes recording of the commands sequence */\n abstract finish(props?: CommandBufferProps): CommandBuffer;\n\n /** Create a RenderPass using the default CommandEncoder */\n abstract beginRenderPass(props?: RenderPassProps): RenderPass;\n\n /** Create a ComputePass using the default CommandEncoder*/\n abstract beginComputePass(props?: ComputePassProps): ComputePass;\n\n /** Add a command that that copies data from a sub-region of a Buffer to a sub-region of another Buffer. */\n abstract copyBufferToBuffer(options: CopyBufferToBufferOptions): void;\n\n /** Add a command that copies data from a sub-region of a GPUBuffer to a sub-region of one or multiple continuous texture subresources. */\n abstract copyBufferToTexture(options: CopyBufferToTextureOptions): void;\n\n /** Add a command that copies data from a sub-region of one or multiple continuous texture subresources to a sub-region of a Buffer. */\n abstract copyTextureToBuffer(options: CopyTextureToBufferOptions): void;\n\n /** Add a command that copies data from a sub-region of one or multiple contiguous texture subresources to another sub-region of one or multiple continuous texture subresources. */\n abstract copyTextureToTexture(options: CopyTextureToTextureOptions): void;\n\n /** Add a command that clears a texture mip level. */\n // abstract clearTexture(options: ClearTextureOptions): void;\n\n // abstract readTexture(options: TextureReadOptions): Promise;\n\n /** Reads results from a query set into a GPU buffer. Values are 64 bits so byteLength must be querySet.props.count * 8 */\n abstract resolveQuerySet(\n querySet: QuerySet,\n destination: Buffer,\n options?: {\n firstQuery?: number;\n queryCount?: number;\n destinationOffset?: number;\n }\n ): void;\n\n /**\n * Reads all resolved timestamp pairs on the current profiler query set and caches the sum\n * as milliseconds on this encoder.\n */\n async resolveTimeProfilingQuerySet(): Promise {\n this._gpuTimeMs = undefined;\n\n if (!this._timeProfilingQuerySet) {\n return;\n }\n\n const pairCount = Math.floor(this._timeProfilingSlotCount / 2);\n if (pairCount <= 0) {\n return;\n }\n\n const queryCount = pairCount * 2;\n const results = await this._timeProfilingQuerySet.readResults({\n firstQuery: 0,\n queryCount\n });\n\n let totalDurationNanoseconds = 0n;\n for (let queryIndex = 0; queryIndex < queryCount; queryIndex += 2) {\n totalDurationNanoseconds += results[queryIndex + 1] - results[queryIndex];\n }\n\n this._gpuTimeMs = Number(totalDurationNanoseconds) / 1e6;\n }\n\n /** Returns the number of query slots consumed by automatic pass profiling on this encoder. */\n getTimeProfilingSlotCount(): number {\n return this._timeProfilingSlotCount;\n }\n\n getTimeProfilingQuerySet(): QuerySet | null {\n return this._timeProfilingQuerySet;\n }\n\n /** Internal helper for auto-assigning timestamp slots to render/compute passes on this encoder. */\n protected _applyTimeProfilingToPassProps

(props?: P): P {\n const passProps = (props || {}) as P;\n\n if (!this._supportsTimestampQueries() || !this._timeProfilingQuerySet) {\n return passProps;\n }\n\n if (\n passProps.timestampQuerySet !== undefined ||\n passProps.beginTimestampIndex !== undefined ||\n passProps.endTimestampIndex !== undefined\n ) {\n return passProps;\n }\n\n const beginTimestampIndex = this._timeProfilingSlotCount;\n if (beginTimestampIndex + 1 >= this._timeProfilingQuerySet.props.count) {\n return passProps;\n }\n\n this._timeProfilingSlotCount += 2;\n\n return {\n ...passProps,\n timestampQuerySet: this._timeProfilingQuerySet,\n beginTimestampIndex,\n endTimestampIndex: beginTimestampIndex + 1\n };\n }\n\n protected _supportsTimestampQueries(): boolean {\n return this.device.features.has('timestamp-query');\n }\n\n /** Begins a labeled debug group containing subsequent commands */\n abstract pushDebugGroup(groupLabel: string): void;\n /** Ends the labeled debug group most recently started by pushDebugGroup() */\n abstract popDebugGroup(): void;\n /** Marks a point in a stream of commands with a label */\n abstract insertDebugMarker(markerLabel: string): void;\n\n // TODO - luma.gl has these on the device, should we align with WebGPU API?\n // beginRenderPass(GPURenderPassDescriptor descriptor): GPURenderPassEncoder;\n // beginComputePass(optional GPUComputePassDescriptor descriptor = {}): GPUComputePassEncoder;\n\n static override defaultProps: Required = {\n ...Resource.defaultProps,\n measureExecutionTime: undefined!,\n timeProfilingQuerySet: undefined!\n };\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Device} from '../device';\nimport {Resource, ResourceProps} from './resource';\n\n// interface Queue {\n// submit(commandBuffers);\n\n// // onSubmittedWorkDone(): Promise;\n\n// writeBuffer(options: WriteBufferOptions): void;\n// writeTexture(options: TextureWriteOptions): void;\n\n// // copyExternalImageToTexture(\n// // GPUImageCopyExternalImage source,\n// // GPUImageCopyTextureTagged destination,\n// // GPUExtent3D copySize\n// // ): void;\n// }\n\nexport type CommandBufferProps = ResourceProps & {};\n\n/**\n * Represents the finished contents of exactly one CommandEncoder. Backends may store native\n * command buffers or replayable command lists internally, but submission must preserve the same\n * recorded command ordering.\n */\nexport abstract class CommandBuffer extends Resource {\n override get [Symbol.toStringTag](): string {\n return 'CommandBuffer';\n }\n\n constructor(device: Device, props: CommandBufferProps) {\n super(device, props, CommandBuffer.defaultProps);\n }\n\n static override defaultProps: Required = {\n ...Resource.defaultProps\n };\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {type PrimitiveDataType} from '../data-types/data-types';\nimport {\n type VariableShaderType,\n type AttributeShaderType,\n type VariableShaderTypeAlias,\n type AttributeShaderTypeAlias\n} from './shader-types';\n\n/** Information extracted from a VariableShaderType constant */\nexport type VariableShaderTypeInfo = {\n type: PrimitiveDataType;\n components: number;\n};\n\n/** Information extracted from a AttributeShaderType constant */\nexport type AttributeShaderTypeInfo = {\n /** WGSL-style primitive data type, f32, i32, u32 */\n primitiveType: PrimitiveDataType;\n /** Whether this is a normalized integer (that must be used as float) */\n components: 1 | 2 | 3 | 4;\n /** Length in bytes of the data for one vertex */\n byteLength?: number;\n /** Whether this is for integer or float vert */\n integer: boolean;\n /** Whether this data type is signed */\n signed: boolean;\n};\n\n/** Split a uniform type string into type and components */\nexport function getVariableShaderTypeInfo(\n format: VariableShaderType | VariableShaderTypeAlias\n): VariableShaderTypeInfo {\n const resolvedFormat = resolveVariableShaderTypeAlias(format);\n const decoded = UNIFORM_FORMATS[resolvedFormat];\n if (!decoded) {\n throw new Error(`Unsupported variable shader type: ${format}`);\n }\n return decoded;\n}\n\n/** Decodes a vertex type, returning byte length and flags (integer, signed, normalized) */\nexport function getAttributeShaderTypeInfo(\n attributeType: AttributeShaderType | AttributeShaderTypeAlias\n): AttributeShaderTypeInfo {\n const resolvedAttributeType = resolveAttributeShaderTypeAlias(attributeType);\n const decoded = TYPE_INFO[resolvedAttributeType];\n if (!decoded) {\n throw new Error(`Unsupported attribute shader type: ${attributeType}`);\n }\n const [primitiveType, components] = decoded;\n const integer: boolean = primitiveType === 'i32' || primitiveType === 'u32';\n const signed: boolean = primitiveType !== 'u32';\n\n const byteLength = PRIMITIVE_TYPE_SIZES[primitiveType] * components;\n return {\n primitiveType,\n components,\n byteLength,\n integer,\n signed\n };\n}\n\nexport class ShaderTypeDecoder {\n getVariableShaderTypeInfo(\n format: VariableShaderType | VariableShaderTypeAlias\n ): VariableShaderTypeInfo {\n return getVariableShaderTypeInfo(format);\n }\n\n getAttributeShaderTypeInfo(\n attributeType: AttributeShaderType | AttributeShaderTypeAlias\n ): AttributeShaderTypeInfo {\n return getAttributeShaderTypeInfo(attributeType);\n }\n\n makeShaderAttributeType(\n primitiveType: PrimitiveDataType,\n components: 1 | 2 | 3 | 4\n ): AttributeShaderType {\n return makeShaderAttributeType(primitiveType, components);\n }\n\n resolveAttributeShaderTypeAlias(\n alias: AttributeShaderTypeAlias | AttributeShaderType\n ): AttributeShaderType {\n return resolveAttributeShaderTypeAlias(alias);\n }\n\n resolveVariableShaderTypeAlias(\n alias: VariableShaderTypeAlias | VariableShaderType\n ): VariableShaderType {\n return resolveVariableShaderTypeAlias(alias);\n }\n}\n\nexport function makeShaderAttributeType(\n primitiveType: PrimitiveDataType,\n components: 1 | 2 | 3 | 4\n): AttributeShaderType {\n return components === 1 ? primitiveType : `vec${components}<${primitiveType}>`;\n}\n\nexport function resolveAttributeShaderTypeAlias(\n alias: AttributeShaderTypeAlias | AttributeShaderType\n): AttributeShaderType {\n return WGSL_ATTRIBUTE_TYPE_ALIAS_MAP[alias as AttributeShaderTypeAlias] || alias;\n}\n\nexport function resolveVariableShaderTypeAlias(\n alias: VariableShaderTypeAlias | VariableShaderType\n): VariableShaderType {\n return WGSL_VARIABLE_TYPE_ALIAS_MAP[alias as VariableShaderTypeAlias] || alias;\n}\n\n/** Decoder for luma.gl shader types */\nexport const shaderTypeDecoder = new ShaderTypeDecoder();\n\n// TABLES\n\nconst PRIMITIVE_TYPE_SIZES: Record = {\n f32: 4,\n f16: 2,\n i32: 4,\n u32: 4\n // 'bool-webgl': 4,\n};\n\n/** All valid shader attribute types. A table guarantees exhaustive list and fast execution */\nconst TYPE_INFO: Record = {\n f32: ['f32', 1],\n 'vec2': ['f32', 2],\n 'vec3': ['f32', 3],\n 'vec4': ['f32', 4],\n f16: ['f16', 1],\n 'vec2': ['f16', 2],\n 'vec3': ['f16', 3],\n 'vec4': ['f16', 4],\n i32: ['i32', 1],\n 'vec2': ['i32', 2],\n 'vec3': ['i32', 3],\n 'vec4': ['i32', 4],\n u32: ['u32', 1],\n 'vec2': ['u32', 2],\n 'vec3': ['u32', 3],\n 'vec4': ['u32', 4]\n};\n\n/** @todo These tables are quite big, consider parsing type strings instead */\nconst UNIFORM_FORMATS: Record = {\n f32: {type: 'f32', components: 1},\n f16: {type: 'f16', components: 1},\n i32: {type: 'i32', components: 1},\n u32: {type: 'u32', components: 1},\n // 'bool-webgl': {type: 'bool-webgl', components: 1},\n 'vec2': {type: 'f32', components: 2},\n 'vec3': {type: 'f32', components: 3},\n 'vec4': {type: 'f32', components: 4},\n 'vec2': {type: 'f16', components: 2},\n 'vec3': {type: 'f16', components: 3},\n 'vec4': {type: 'f16', components: 4},\n 'vec2': {type: 'i32', components: 2},\n 'vec3': {type: 'i32', components: 3},\n 'vec4': {type: 'i32', components: 4},\n 'vec2': {type: 'u32', components: 2},\n 'vec3': {type: 'u32', components: 3},\n 'vec4': {type: 'u32', components: 4},\n\n 'mat2x2': {type: 'f32', components: 4},\n 'mat2x3': {type: 'f32', components: 6},\n 'mat2x4': {type: 'f32', components: 8},\n 'mat3x2': {type: 'f32', components: 6},\n 'mat3x3': {type: 'f32', components: 9},\n 'mat3x4': {type: 'f32', components: 12},\n 'mat4x2': {type: 'f32', components: 8},\n 'mat4x3': {type: 'f32', components: 12},\n 'mat4x4': {type: 'f32', components: 16},\n\n 'mat2x2': {type: 'f16', components: 4},\n 'mat2x3': {type: 'f16', components: 6},\n 'mat2x4': {type: 'f16', components: 8},\n 'mat3x2': {type: 'f16', components: 6},\n 'mat3x3': {type: 'f16', components: 9},\n 'mat3x4': {type: 'f16', components: 12},\n 'mat4x2': {type: 'f16', components: 8},\n 'mat4x3': {type: 'f16', components: 12},\n 'mat4x4': {type: 'f16', components: 16},\n\n 'mat2x2': {type: 'i32', components: 4},\n 'mat2x3': {type: 'i32', components: 6},\n 'mat2x4': {type: 'i32', components: 8},\n 'mat3x2': {type: 'i32', components: 6},\n 'mat3x3': {type: 'i32', components: 9},\n 'mat3x4': {type: 'i32', components: 12},\n 'mat4x2': {type: 'i32', components: 8},\n 'mat4x3': {type: 'i32', components: 12},\n 'mat4x4': {type: 'i32', components: 16},\n\n 'mat2x2': {type: 'u32', components: 4},\n 'mat2x3': {type: 'u32', components: 6},\n 'mat2x4': {type: 'u32', components: 8},\n 'mat3x2': {type: 'u32', components: 6},\n 'mat3x3': {type: 'u32', components: 9},\n 'mat3x4': {type: 'u32', components: 12},\n 'mat4x2': {type: 'u32', components: 8},\n 'mat4x3': {type: 'u32', components: 12},\n 'mat4x4': {type: 'u32', components: 16}\n};\n\n/** Predeclared aliases @see https://www.w3.org/TR/WGSL/#vector-types */\nexport const WGSL_ATTRIBUTE_TYPE_ALIAS_MAP: Record =\n {\n vec2i: 'vec2',\n vec3i: 'vec3',\n vec4i: 'vec4',\n vec2u: 'vec2',\n vec3u: 'vec3',\n vec4u: 'vec4',\n vec2f: 'vec2',\n vec3f: 'vec3',\n vec4f: 'vec4',\n // Requires the f16 extension.\n vec2h: 'vec2',\n vec3h: 'vec3',\n vec4h: 'vec4'\n };\n\n/** @todo These tables are quite big, consider parsing alias strings instead */\nexport const WGSL_VARIABLE_TYPE_ALIAS_MAP: Record = {\n vec2i: 'vec2',\n vec3i: 'vec3',\n vec4i: 'vec4',\n vec2u: 'vec2',\n vec3u: 'vec3',\n vec4u: 'vec4',\n vec2f: 'vec2',\n vec3f: 'vec3',\n vec4f: 'vec4',\n vec2h: 'vec2',\n vec3h: 'vec3',\n vec4h: 'vec4',\n mat2x2f: 'mat2x2',\n mat2x3f: 'mat2x3',\n mat2x4f: 'mat2x4',\n mat3x2f: 'mat3x2',\n mat3x3f: 'mat3x3',\n mat3x4f: 'mat3x4',\n mat4x2f: 'mat4x2',\n mat4x3f: 'mat4x3',\n mat4x4f: 'mat4x4',\n\n mat2x2i: 'mat2x2',\n mat2x3i: 'mat2x3',\n mat2x4i: 'mat2x4',\n mat3x2i: 'mat3x2',\n mat3x3i: 'mat3x3',\n mat3x4i: 'mat3x4',\n mat4x2i: 'mat4x2',\n mat4x3i: 'mat4x3',\n mat4x4i: 'mat4x4',\n\n mat2x2u: 'mat2x2',\n mat2x3u: 'mat2x3',\n mat2x4u: 'mat2x4',\n mat3x2u: 'mat3x2',\n mat3x3u: 'mat3x3',\n mat3x4u: 'mat3x4',\n mat4x2u: 'mat4x2',\n mat4x3u: 'mat4x3',\n mat4x4u: 'mat4x4',\n\n mat2x2h: 'mat2x2',\n mat2x3h: 'mat2x3',\n mat2x4h: 'mat2x4',\n mat3x2h: 'mat3x2',\n mat3x3h: 'mat3x3',\n mat3x4h: 'mat3x4',\n mat4x2h: 'mat4x2',\n mat4x3h: 'mat4x3',\n mat4x4h: 'mat4x4'\n};\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {log} from '../utils/log';\nimport type {PrimitiveDataType, NormalizedDataType} from '../shadertypes/data-types/data-types';\nimport type {AttributeShaderType} from '../shadertypes/shader-types/shader-types';\nimport type {VertexFormat} from '../shadertypes/vertex-types/vertex-formats';\nimport {shaderTypeDecoder} from '../shadertypes/shader-types/shader-type-decoder';\nimport {vertexFormatDecoder} from '../shadertypes/vertex-types/vertex-format-decoder';\nimport type {ShaderLayout, AttributeDeclaration} from '../adapter/types/shader-layout';\nimport type {BufferLayout} from '../adapter/types/buffer-layout';\n\n/** Resolved info for a buffer / attribute combination to help backend configure it correctly */\nexport type AttributeInfo = {\n /** Attribute name */\n attributeName: string;\n /** Location in shader */\n location: number;\n /** Type / precision used in shader (buffer values may be converted) */\n shaderType: AttributeShaderType;\n /** Calculations are done in this type in the shader's attribute declaration */\n primitiveType: PrimitiveDataType;\n /** Components refer to the number of components in the shader's attribute declaration */\n shaderComponents: 1 | 2 | 3 | 4;\n /** It is the shader attribute declaration that determines whether GPU will process as integer or float */\n integer: boolean;\n\n /** BufferName */\n bufferName: string;\n /** Format of buffer data */\n vertexFormat: VertexFormat;\n /** Memory data type refers to the data type in the buffer */\n bufferDataType: NormalizedDataType;\n /** Components refer to the number of components in the buffer's vertex format */\n bufferComponents: 1 | 2 | 3 | 4;\n /** Normalization is encoded in the buffer layout's vertex format... */\n normalized: boolean;\n\n /** If not specified, the step mode is inferred from the attribute name in the shader (contains string instance) */\n stepMode: 'vertex' | 'instance';\n\n /** The byteOffset is encoded in or calculated from the buffer layout */\n byteOffset: number;\n /** The byteStride is encoded in or calculated from the buffer layout */\n byteStride: number;\n};\n\ntype BufferAttributeInfo = {\n attributeName: string;\n bufferName: string;\n stepMode?: 'vertex' | 'instance';\n vertexFormat: VertexFormat;\n byteOffset: number;\n byteStride: number;\n};\n\n/**\n * Map from \"attribute names\" to \"resolved attribute infos\"\n * containing information about both buffer layouts and shader attribute declarations\n */\nexport function getAttributeInfosFromLayouts(\n shaderLayout: ShaderLayout,\n bufferLayout: BufferLayout[]\n): Record {\n const attributeInfos: Record = {};\n for (const attribute of shaderLayout.attributes) {\n const attributeInfo = getAttributeInfoFromLayouts(shaderLayout, bufferLayout, attribute.name);\n if (attributeInfo) {\n attributeInfos[attribute.name] = attributeInfo;\n }\n }\n return attributeInfos;\n}\n\n/**\n * Array indexed by \"location\" holding \"resolved attribute infos\"\n */\nexport function getAttributeInfosByLocation(\n shaderLayout: ShaderLayout,\n bufferLayout: BufferLayout[],\n maxVertexAttributes: number = 16\n): AttributeInfo[] {\n const attributeInfos = getAttributeInfosFromLayouts(shaderLayout, bufferLayout);\n const locationInfos: AttributeInfo[] = new Array(maxVertexAttributes).fill(null);\n for (const attributeInfo of Object.values(attributeInfos)) {\n locationInfos[attributeInfo.location] = attributeInfo;\n }\n return locationInfos;\n}\n\n/**\n * Get the combined information from a shader layout and a buffer layout for a specific attribute\n */\nfunction getAttributeInfoFromLayouts(\n shaderLayout: ShaderLayout,\n bufferLayout: BufferLayout[],\n name: string\n): AttributeInfo | null {\n const shaderDeclaration = getAttributeFromShaderLayout(shaderLayout, name);\n const bufferMapping: BufferAttributeInfo | null = getAttributeFromBufferLayout(\n bufferLayout,\n name\n );\n\n // TODO should no longer happen\n if (!shaderDeclaration) {\n // || !bufferMapping\n return null;\n }\n\n const attributeTypeInfo = shaderTypeDecoder.getAttributeShaderTypeInfo(shaderDeclaration.type);\n const defaultVertexFormat = vertexFormatDecoder.getCompatibleVertexFormat(attributeTypeInfo);\n const vertexFormat = bufferMapping?.vertexFormat || defaultVertexFormat;\n const vertexFormatInfo = vertexFormatDecoder.getVertexFormatInfo(vertexFormat);\n\n return {\n attributeName: bufferMapping?.attributeName || shaderDeclaration.name,\n bufferName: bufferMapping?.bufferName || shaderDeclaration.name,\n location: shaderDeclaration.location,\n shaderType: shaderDeclaration.type,\n primitiveType: attributeTypeInfo.primitiveType,\n shaderComponents: attributeTypeInfo.components,\n vertexFormat,\n bufferDataType: vertexFormatInfo.type,\n bufferComponents: vertexFormatInfo.components,\n // normalized is a property of the buffer's vertex format\n normalized: vertexFormatInfo.normalized,\n // integer is a property of the shader declaration\n integer: attributeTypeInfo.integer,\n stepMode: bufferMapping?.stepMode || shaderDeclaration.stepMode || 'vertex',\n byteOffset: bufferMapping?.byteOffset || 0,\n byteStride: bufferMapping?.byteStride || 0\n };\n}\n\nfunction getAttributeFromShaderLayout(\n shaderLayout: ShaderLayout,\n name: string\n): AttributeDeclaration | null {\n const attribute = shaderLayout.attributes.find(attr => attr.name === name);\n if (!attribute) {\n log.warn(`shader layout attribute \"${name}\" not present in shader`);\n }\n return attribute || null;\n}\n\nfunction getAttributeFromBufferLayout(\n bufferLayouts: BufferLayout[],\n name: string\n): BufferAttributeInfo | null {\n // Check that bufferLayouts are valid (each either has format or attribute)\n checkBufferLayouts(bufferLayouts);\n\n let bufferLayoutInfo = getAttributeFromShortHand(bufferLayouts, name);\n if (bufferLayoutInfo) {\n return bufferLayoutInfo;\n }\n\n bufferLayoutInfo = getAttributeFromAttributesList(bufferLayouts, name);\n if (bufferLayoutInfo) {\n return bufferLayoutInfo;\n }\n\n // Didn't find...\n log.warn(`layout for attribute \"${name}\" not present in buffer layout`);\n return null;\n}\n\n/** Check that bufferLayouts are valid (each either has format or attribute) */\nfunction checkBufferLayouts(bufferLayouts: BufferLayout[]) {\n for (const bufferLayout of bufferLayouts) {\n if (\n (bufferLayout.attributes && bufferLayout.format) ||\n (!bufferLayout.attributes && !bufferLayout.format)\n ) {\n log.warn(`BufferLayout ${name} must have either 'attributes' or 'format' field`);\n }\n }\n}\n\n/** Get attribute from format shorthand if specified */\nfunction getAttributeFromShortHand(\n bufferLayouts: BufferLayout[],\n name: string\n): BufferAttributeInfo | null {\n for (const bufferLayout of bufferLayouts) {\n if (bufferLayout.format && bufferLayout.name === name) {\n return {\n attributeName: bufferLayout.name,\n bufferName: name,\n stepMode: bufferLayout.stepMode,\n vertexFormat: bufferLayout.format,\n // If offset is needed, use `attributes` field.\n byteOffset: 0,\n byteStride: bufferLayout.byteStride || 0\n };\n }\n }\n return null;\n}\n\n/**\n * Search attribute mappings (e.g. interleaved attributes) for buffer mapping.\n * Not the name of the buffer might be the same as one of the interleaved attributes.\n */\nfunction getAttributeFromAttributesList(\n bufferLayouts: BufferLayout[],\n name: string\n): BufferAttributeInfo | null {\n for (const bufferLayout of bufferLayouts) {\n let byteStride: number | undefined = bufferLayout.byteStride;\n\n // Calculate a default byte stride if not provided\n if (typeof bufferLayout.byteStride !== 'number') {\n for (const attributeMapping of bufferLayout.attributes || []) {\n const info = vertexFormatDecoder.getVertexFormatInfo(attributeMapping.format);\n // @ts-ignore\n byteStride += info.byteLength;\n }\n }\n\n const attributeMapping = bufferLayout.attributes?.find(mapping => mapping.attribute === name);\n if (attributeMapping) {\n return {\n attributeName: attributeMapping.attribute,\n bufferName: bufferLayout.name,\n stepMode: bufferLayout.stepMode,\n vertexFormat: attributeMapping.format,\n byteOffset: attributeMapping.byteOffset,\n // @ts-ignore\n byteStride\n };\n }\n }\n\n return null;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {TypedArray} from '../../types';\nimport {\n AttributeInfo,\n getAttributeInfosByLocation\n} from '../../adapter-utils/get-attribute-from-layouts';\nimport type {Device} from '../device';\nimport type {Buffer} from './buffer';\nimport type {RenderPass} from './render-pass';\nimport {Resource, ResourceProps} from './resource';\nimport {ShaderLayout} from '../types/shader-layout';\nimport {BufferLayout} from '../types/buffer-layout';\n\n/** Properties for initializing a VertexArray */\nexport type VertexArrayProps = ResourceProps & {\n shaderLayout: ShaderLayout;\n bufferLayout: BufferLayout[];\n};\n\n/**\n * Stores attribute bindings.\n * Makes it easy to share a render pipeline and use separate vertex arrays.\n * @note On WebGL, VertexArray allows non-constant bindings to be performed in advance\n * reducing the number of WebGL calls per draw call.\n * @note On WebGPU this is just a convenience class that collects the bindings.\n */\nexport abstract class VertexArray extends Resource {\n static override defaultProps: Required = {\n ...Resource.defaultProps,\n shaderLayout: undefined!,\n bufferLayout: []\n };\n\n override get [Symbol.toStringTag](): string {\n return 'VertexArray';\n }\n\n /** Max number of vertex attributes */\n readonly maxVertexAttributes: number;\n /** Attribute infos indexed by location - TODO only needed by webgl module? */\n protected readonly attributeInfos: AttributeInfo[];\n\n /** Index buffer */\n indexBuffer: Buffer | null = null;\n /** Attributes indexed by buffer slot */\n attributes: (Buffer | TypedArray | null)[];\n\n constructor(device: Device, props: VertexArrayProps) {\n super(device, props, VertexArray.defaultProps);\n this.maxVertexAttributes = device.limits.maxVertexAttributes;\n this.attributes = new Array(this.maxVertexAttributes).fill(null);\n this.attributeInfos = getAttributeInfosByLocation(\n props.shaderLayout,\n props.bufferLayout,\n this.maxVertexAttributes\n );\n }\n\n /** Set attributes (stored on pipeline and set before each call) */\n abstract setIndexBuffer(indices: Buffer | null): void;\n /** Set attributes (stored on pipeline and set before each call) */\n abstract setBuffer(bufferSlot: number, buffer: Buffer | null): void;\n\n abstract bindBeforeRender(renderPass: RenderPass): void;\n abstract unbindAfterRender(renderPass: RenderPass): void;\n\n // DEPRECATED METHODS\n\n /** @deprecated Set constant attributes (WebGL only) */\n setConstantWebGL(location: number, value: TypedArray | null): void {\n this.device.reportError(new Error('constant attributes not supported'), this)();\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport {PrimitiveTopology} from '../types/parameters';\nimport {ShaderLayout} from '../types/shader-layout';\nimport type {Buffer} from './buffer';\nimport {Resource, ResourceProps} from './resource';\n\n/** For bindRange */\nexport type BufferRange = {\n buffer: Buffer;\n byteOffset?: number;\n byteLength?: number;\n};\n\n/** Configures a set of output buffers for pipeline (WebGL only) */\nexport type TransformFeedbackProps = ResourceProps & {\n /** Layout of shader (for varyings) */\n layout: ShaderLayout;\n /** Buffer bindings (for varyings) */\n buffers: Record;\n};\n\n/** Holds a set of output buffers for pipeline (WebGL only) */\nexport abstract class TransformFeedback extends Resource {\n static override defaultProps: Required = {\n ...Resource.defaultProps,\n layout: undefined!,\n buffers: {}\n };\n\n get [Symbol.toStringTag](): string {\n return 'TransformFeedback';\n }\n\n constructor(device: Device, props: TransformFeedbackProps) {\n super(device, props, TransformFeedback.defaultProps);\n }\n\n abstract begin(topology?: PrimitiveTopology): void;\n abstract end(): void;\n\n abstract setBuffers(buffers: Record): void;\n abstract setBuffer(locationOrName: string | number, bufferOrRange: Buffer | BufferRange): void;\n abstract getBuffer(locationOrName: string | number): Buffer | BufferRange | null;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport {Resource, ResourceProps} from './resource';\n\n/**\n * Properties for creating a QuerySet\n * - 'timestamp' - query the GPU timestamp counter at the start and end of render passes\n * timestamp queries are available if the 'timestamp-query' feature is present.\n * - 'occlusion' - query the number of fragment samples that pass all per-fragment tests for a set of drawing commands\n * including scissor, sample mask, alpha to coverage, stencil, and depth tests\n */\nexport type QuerySetProps = ResourceProps & {\n /**\n * The type of query set\n * occlusion - query the number of fragment samples that pass all the per-fragment tests for a set of drawing commands, including scissor, sample mask, alpha to coverage, stencil, and depth tests\n * timestamp - query the GPU timestamp counter. Timestamp queries are available if the\n * `timestamp-query` feature is present.\n */\n type: 'occlusion' | 'timestamp';\n /** The number of queries managed by the query set */\n count: number;\n};\n\n/** Immutable QuerySet object */\nexport abstract class QuerySet extends Resource {\n get [Symbol.toStringTag](): string {\n return 'QuerySet';\n }\n\n constructor(device: Device, props: QuerySetProps) {\n super(device, props, QuerySet.defaultProps);\n }\n\n static override defaultProps: Required = {\n ...Resource.defaultProps,\n type: undefined!,\n count: undefined!\n };\n\n /**\n * Returns true if the requested result has been captured and can be read without blocking.\n * Backends may implement this conservatively.\n */\n abstract isResultAvailable(queryIndex?: number): boolean;\n\n /** Reads query results as 64-bit values. */\n abstract readResults(options?: {firstQuery?: number; queryCount?: number}): Promise;\n\n /**\n * Reads a timestamp duration in milliseconds between a begin and end query index.\n * Portable duration profiling requires adjacent indices that identify one logical pair.\n */\n abstract readTimestampDuration(beginIndex: number, endIndex: number): Promise;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport {Resource, type ResourceProps} from './resource';\n\nexport type FenceProps = ResourceProps;\n\n/** Synchronization primitive that resolves when GPU work is completed */\nexport abstract class Fence extends Resource {\n static override defaultProps: Required = {\n ...Resource.defaultProps\n };\n\n override get [Symbol.toStringTag](): string {\n return 'Fence';\n }\n\n /** Promise that resolves when the fence is signaled */\n abstract readonly signaled: Promise;\n\n constructor(device: Device, props: FenceProps = {}) {\n super(device, props, Fence.defaultProps);\n }\n\n /** Destroy the fence and release any resources */\n abstract override destroy(): void;\n\n /** Check if the fence has been signaled */\n abstract isSignaled(): boolean;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {TypedArray, TypedArrayConstructor} from '../../types';\nimport {PrimitiveDataType, SignedDataType, NormalizedDataType, DataTypeInfo} from './data-types';\n\n/**\n * Gets info about a data type constant (signed or normalized)\n * @returns underlying primitive / signed types, byte length, normalization, integer, signed flags\n */\nexport function getDataTypeInfo(type: NormalizedDataType): DataTypeInfo {\n const normalized: boolean = type.includes('norm');\n const integer: boolean = !normalized && !type.startsWith('float');\n const signed: boolean = type.startsWith('s');\n const typeInfo = NORMALIZED_TYPE_MAP[type];\n const [signedType, primitiveType, byteLength] = typeInfo || ['uint8 ', 'i32', 1];\n return {\n signedType,\n primitiveType,\n byteLength,\n normalized,\n integer,\n signed\n };\n}\n\n/** Build a vertex format from a signed data type and a component */\nexport function getNormalizedDataType(signedDataType: SignedDataType): NormalizedDataType {\n const dataType: NormalizedDataType = signedDataType;\n // biome-ignore format: preserve layout\n switch (dataType) {\n case 'uint8': return 'unorm8';\n case 'sint8': return 'snorm8';\n case 'uint16': return 'unorm16';\n case 'sint16': return 'snorm16';\n default: return dataType;\n }\n}\n\n/** Align offset to 1, 2 or 4 elements (4, 8 or 16 bytes) */\nexport function alignTo(size: number, count: number): number {\n // biome-ignore format: preserve layout\n switch (count) {\n case 1: return size; // Pad upwards to even multiple of 2\n case 2: return size + (size % 2); // Pad upwards to even multiple of 2\n default: return size + ((4 - (size % 4)) % 4); // Pad upwards to even multiple of 4\n }\n}\n\n/** Returns the VariableShaderType that corresponds to a typed array */\nexport function getDataType(arrayOrType: TypedArray | TypedArrayConstructor): SignedDataType {\n const Constructor = ArrayBuffer.isView(arrayOrType) ? arrayOrType.constructor : arrayOrType;\n if (Constructor === Uint8ClampedArray) {\n return 'uint8';\n }\n const info = Object.values(NORMALIZED_TYPE_MAP).find(entry => Constructor === entry[4]);\n if (!info) {\n throw new Error(Constructor.name);\n }\n return info[0];\n}\n\n/** Returns the TypedArray that corresponds to a shader data type */\nexport function getTypedArrayConstructor(type: NormalizedDataType): TypedArrayConstructor {\n const [, , , , Constructor] = NORMALIZED_TYPE_MAP[type];\n return Constructor;\n}\n\nconst NORMALIZED_TYPE_MAP: Record<\n NormalizedDataType,\n [\n SignedDataType,\n PrimitiveDataType,\n bytes: 1 | 2 | 4,\n normalized: boolean,\n arrayConstructor: TypedArrayConstructor\n ]\n> = {\n uint8: ['uint8', 'u32', 1, false, Uint8Array],\n sint8: ['sint8', 'i32', 1, false, Int8Array],\n unorm8: ['uint8', 'f32', 1, true, Uint8Array],\n snorm8: ['sint8', 'f32', 1, true, Int8Array],\n uint16: ['uint16', 'u32', 2, false, Uint16Array],\n sint16: ['sint16', 'i32', 2, false, Int16Array],\n unorm16: ['uint16', 'u32', 2, true, Uint16Array],\n snorm16: ['sint16', 'i32', 2, true, Int16Array],\n float16: ['float16', 'f16', 2, false, Uint16Array],\n float32: ['float32', 'f32', 4, false, Float32Array],\n uint32: ['uint32', 'u32', 4, false, Uint32Array],\n sint32: ['sint32', 'i32', 4, false, Int32Array]\n};\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {PrimitiveDataType} from '../data-types/data-types';\nimport type {CompositeShaderType, VariableShaderType} from './shader-types';\nimport {alignTo} from '../data-types/decode-data-types';\nimport {getVariableShaderTypeInfo, resolveVariableShaderTypeAlias} from './shader-type-decoder';\n\n/**\n * Describes the packing for one flattened field in a shader block.\n *\n * Offsets, sizes, and strides are expressed in 32-bit words so the result can\n * be consumed directly by typed-array writers.\n */\nexport type ShaderBlockLayoutEntry = {\n /** Offset in 32-bit words from the start of the block. */\n offset: number;\n /** Occupied size in 32-bit words, excluding external array stride. */\n size: number;\n /** Number of logical scalar components in the declared value. */\n components: number;\n /** Number of matrix columns, or `1` for scalars and vectors. */\n columns: number;\n /** Number of rows in each column, or vector length for vectors. */\n rows: number;\n /** Distance between matrix columns in 32-bit words. */\n columnStride: number;\n /** Canonical shader type after alias resolution. */\n shaderType: VariableShaderType;\n /** Scalar data type used to write the value. */\n type: PrimitiveDataType;\n};\n\n/**\n * Options for {@link makeShaderBlockLayout}.\n */\nexport type ShaderBlockLayoutOptions = {\n /**\n * Packing rules to apply when building the layout.\n *\n * Defaults to `'std140'`.\n */\n layout?: 'std140' | 'wgsl-uniform' | 'wgsl-storage';\n};\n\n/**\n * Immutable layout metadata for a uniform or storage-style shader block.\n */\nexport type ShaderBlockLayout = {\n /** Packing rules used when this layout was created. */\n layout: 'std140' | 'wgsl-uniform' | 'wgsl-storage';\n /** Exact number of packed bytes required by the block. */\n byteLength: number;\n /** Original composite shader type declarations keyed by top-level field. */\n uniformTypes: Record;\n /** Flattened leaf field layouts keyed by field path. */\n fields: Record;\n};\n\n/**\n * Builds a deterministic shader-block layout from composite shader type declarations.\n *\n * The returned value is pure layout metadata. It records the packed field\n * offsets and exact packed byte length, but it does not allocate buffers or\n * serialize values.\n */\nexport function makeShaderBlockLayout(\n uniformTypes: Readonly>,\n options: ShaderBlockLayoutOptions = {}\n): ShaderBlockLayout {\n const copiedUniformTypes = {...uniformTypes};\n const layout = options.layout ?? 'std140';\n const fields: Record = {};\n\n let size = 0;\n for (const [key, uniformType] of Object.entries(copiedUniformTypes)) {\n size = addToLayout(fields, key, uniformType, size, layout);\n }\n\n size = alignTo(size, getTypeAlignment(copiedUniformTypes, layout));\n\n return {\n layout,\n byteLength: size * 4,\n uniformTypes: copiedUniformTypes,\n fields\n };\n}\n\n/**\n * Returns the layout metadata for a scalar, vector, or matrix leaf type.\n *\n * The result includes both the occupied size in 32-bit words and the alignment\n * requirement that must be applied before placing the value in a shader block.\n */\nexport function getLeafLayoutInfo(\n type: VariableShaderType,\n layout: 'std140' | 'wgsl-uniform' | 'wgsl-storage'\n): Omit & {alignment: 1 | 2 | 4} {\n const resolvedType = resolveVariableShaderTypeAlias(type);\n const decodedType = getVariableShaderTypeInfo(resolvedType);\n const matrixMatch = /^mat(\\d)x(\\d)<.+>$/.exec(resolvedType);\n\n if (matrixMatch) {\n const columns = Number(matrixMatch[1]);\n const rows = Number(matrixMatch[2]);\n const columnInfo = getVectorLayoutInfo(\n rows as 2 | 3 | 4,\n resolvedType,\n decodedType.type,\n layout\n );\n const columnStride = getMatrixColumnStride(columnInfo.size, columnInfo.alignment, layout);\n\n return {\n alignment: columnInfo.alignment,\n size: columns * columnStride,\n components: columns * rows,\n columns,\n rows,\n columnStride,\n shaderType: resolvedType,\n type: decodedType.type\n };\n }\n\n const vectorMatch = /^vec(\\d)<.+>$/.exec(resolvedType);\n if (vectorMatch) {\n return getVectorLayoutInfo(\n Number(vectorMatch[1]) as 2 | 3 | 4,\n resolvedType,\n decodedType.type,\n layout\n );\n }\n\n return {\n alignment: 1,\n size: 1,\n components: 1,\n columns: 1,\n rows: 1,\n columnStride: 1,\n shaderType: resolvedType,\n type: decodedType.type\n };\n}\n\n/**\n * Type guard for composite struct declarations.\n */\nexport function isCompositeShaderTypeStruct(\n value: CompositeShaderType\n): value is Record {\n return Boolean(value) && typeof value === 'object' && !Array.isArray(value);\n}\n\n/**\n * Recursively adds a composite type to the flattened field map.\n *\n * @returns The next free 32-bit-word offset after the inserted type.\n */\nfunction addToLayout(\n fields: Record,\n name: string,\n type: CompositeShaderType,\n offset: number,\n layout: 'std140' | 'wgsl-uniform' | 'wgsl-storage'\n): number {\n if (typeof type === 'string') {\n const info = getLeafLayoutInfo(type, layout);\n const alignedOffset = alignTo(offset, info.alignment);\n fields[name] = {\n offset: alignedOffset,\n ...info\n };\n return alignedOffset + info.size;\n }\n\n if (Array.isArray(type)) {\n if (Array.isArray(type[0])) {\n throw new Error(`Nested arrays are not supported for ${name}`);\n }\n\n const elementType = type[0] as CompositeShaderType;\n const length = type[1] as number;\n const stride = getArrayStride(elementType, layout);\n const arrayOffset = alignTo(offset, getTypeAlignment(type, layout));\n\n for (let i = 0; i < length; i++) {\n addToLayout(fields, `${name}[${i}]`, elementType, arrayOffset + i * stride, layout);\n }\n return arrayOffset + stride * length;\n }\n\n if (isCompositeShaderTypeStruct(type)) {\n const structAlignment = getTypeAlignment(type, layout);\n let structOffset = alignTo(offset, structAlignment);\n for (const [memberName, memberType] of Object.entries(type)) {\n structOffset = addToLayout(fields, `${name}.${memberName}`, memberType, structOffset, layout);\n }\n return alignTo(structOffset, structAlignment);\n }\n\n throw new Error(`Unsupported CompositeShaderType for ${name}`);\n}\n\n/**\n * Returns the occupied size of a composite type in 32-bit words.\n */\nfunction getTypeSize(\n type: CompositeShaderType,\n layout: 'std140' | 'wgsl-uniform' | 'wgsl-storage'\n): number {\n if (typeof type === 'string') {\n return getLeafLayoutInfo(type, layout).size;\n }\n\n if (Array.isArray(type)) {\n const elementType = type[0] as CompositeShaderType;\n const length = type[1] as number;\n\n if (Array.isArray(elementType)) {\n throw new Error('Nested arrays are not supported');\n }\n\n return getArrayStride(elementType, layout) * length;\n }\n\n let size = 0;\n for (const memberType of Object.values(type)) {\n const compositeMemberType = memberType as CompositeShaderType;\n size = alignTo(size, getTypeAlignment(compositeMemberType, layout));\n size += getTypeSize(compositeMemberType, layout);\n }\n\n return alignTo(size, getTypeAlignment(type, layout));\n}\n\n/**\n * Returns the required alignment of a composite type in 32-bit words.\n */\nfunction getTypeAlignment(\n type: CompositeShaderType,\n layout: 'std140' | 'wgsl-uniform' | 'wgsl-storage'\n): 1 | 2 | 4 {\n if (typeof type === 'string') {\n return getLeafLayoutInfo(type, layout).alignment;\n }\n\n if (Array.isArray(type)) {\n const elementType = type[0] as CompositeShaderType;\n const elementAlignment = getTypeAlignment(elementType, layout);\n return uses16ByteArrayAlignment(layout)\n ? (Math.max(elementAlignment, 4) as 1 | 2 | 4)\n : elementAlignment;\n }\n\n let maxAlignment: 1 | 2 | 4 = 1;\n for (const memberType of Object.values(type)) {\n const memberAlignment = getTypeAlignment(memberType as CompositeShaderType, layout);\n maxAlignment = Math.max(maxAlignment, memberAlignment) as 1 | 2 | 4;\n }\n\n return uses16ByteStructAlignment(layout)\n ? (Math.max(maxAlignment, 4) as 1 | 2 | 4)\n : maxAlignment;\n}\n\n/**\n * Returns the layout metadata for a vector leaf type.\n */\nfunction getVectorLayoutInfo(\n components: 2 | 3 | 4,\n shaderType: VariableShaderType,\n type: PrimitiveDataType,\n layout: 'std140' | 'wgsl-uniform' | 'wgsl-storage'\n): Omit & {alignment: 1 | 2 | 4} {\n return {\n alignment: components === 2 ? 2 : 4,\n size: components === 3 ? 3 : components,\n components,\n columns: 1,\n rows: components,\n columnStride: components === 3 ? 3 : components,\n shaderType,\n type\n };\n}\n\n/**\n * Returns the stride of an array element in 32-bit words.\n *\n * This includes any layout-specific padding between adjacent array elements.\n */\nfunction getArrayStride(\n elementType: CompositeShaderType,\n layout: 'std140' | 'wgsl-uniform' | 'wgsl-storage'\n): number {\n const elementSize = getTypeSize(elementType, layout);\n const elementAlignment = getTypeAlignment(elementType, layout);\n return getArrayLikeStride(elementSize, elementAlignment, layout);\n}\n\n/**\n * Returns the common stride rule shared by array-like elements in the target layout.\n */\nfunction getArrayLikeStride(\n size: number,\n alignment: 1 | 2 | 4,\n layout: 'std140' | 'wgsl-uniform' | 'wgsl-storage'\n): number {\n return alignTo(size, uses16ByteArrayAlignment(layout) ? 4 : alignment);\n}\n\n/**\n * Returns the stride of a matrix column in 32-bit words.\n */\nfunction getMatrixColumnStride(\n size: number,\n alignment: 1 | 2 | 4,\n layout: 'std140' | 'wgsl-uniform' | 'wgsl-storage'\n): number {\n return layout === 'std140' ? 4 : alignTo(size, alignment);\n}\n\n/**\n * Returns `true` when arrays must be rounded up to 16-byte boundaries.\n */\nfunction uses16ByteArrayAlignment(layout: 'std140' | 'wgsl-uniform' | 'wgsl-storage'): boolean {\n return layout === 'std140' || layout === 'wgsl-uniform';\n}\n\n/**\n * Returns `true` when structs must be rounded up to 16-byte boundaries.\n */\nfunction uses16ByteStructAlignment(layout: 'std140' | 'wgsl-uniform' | 'wgsl-storage'): boolean {\n return layout === 'std140' || layout === 'wgsl-uniform';\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {TypedArray} from '../types';\n\nlet arrayBuffer: ArrayBuffer;\n\nexport function getScratchArrayBuffer(byteLength: number): ArrayBuffer {\n if (!arrayBuffer || arrayBuffer.byteLength < byteLength) {\n arrayBuffer = new ArrayBuffer(byteLength);\n }\n return arrayBuffer;\n}\n\nexport function getScratchArray(Type: any, length: number): TypedArray {\n const scratchArrayBuffer = getScratchArrayBuffer(Type.BYTES_PER_ELEMENT * length);\n return new Type(scratchArrayBuffer, 0, length); // arrayBuffer, byteOffset, length (in elements)\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {TypedArray, NumberArray} from '../types';\n\n/**\n * Check is an array is a typed array\n * @param value value to be tested\n * @returns input as TypedArray, or null\n * @todo this should be provided by @math.gl/types\n */\nexport function isTypedArray(value: unknown): value is TypedArray {\n return ArrayBuffer.isView(value) && !(value instanceof DataView);\n}\n\n/**\n * Check is an array is a numeric array (typed array or array of numbers)\n * @param value value to be tested\n * @returns input as NumberArray, or null\n * @todo this should be provided by @math.gl/types\n */\nexport function isNumberArray(value: unknown): value is NumberArray {\n if (Array.isArray(value)) {\n return value.length === 0 || typeof value[0] === 'number';\n }\n return isTypedArray(value);\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {CompositeUniformValue, UniformValue} from '../adapter/types/uniforms';\nimport {getScratchArrayBuffer} from '../utils/array-utils-flat';\nimport {isNumberArray} from '../utils/is-array';\nimport {log} from '../utils/log';\nimport type {\n CompositeShaderType,\n VariableShaderType\n} from '../shadertypes/shader-types/shader-types';\nimport {\n getLeafLayoutInfo,\n isCompositeShaderTypeStruct,\n type ShaderBlockLayout\n} from '../shadertypes/shader-types/shader-block-layout';\n\n/**\n * Serializes nested JavaScript uniform values according to a {@link ShaderBlockLayout}.\n */\nexport class ShaderBlockWriter {\n /** Layout metadata used to flatten and serialize values. */\n readonly layout: ShaderBlockLayout;\n\n /**\n * Creates a writer for a precomputed shader-block layout.\n */\n constructor(layout: ShaderBlockLayout) {\n this.layout = layout;\n }\n\n /**\n * Returns `true` if the flattened layout contains the given field.\n */\n has(name: string): boolean {\n return Boolean(this.layout.fields[name]);\n }\n\n /**\n * Returns offset and size metadata for a flattened field.\n */\n get(name: string): {offset: number; size: number} | undefined {\n const entry = this.layout.fields[name];\n return entry ? {offset: entry.offset, size: entry.size} : undefined;\n }\n\n /**\n * Flattens nested composite values into leaf-path values understood by {@link UniformBlock}.\n *\n * Top-level values may be supplied either in nested object form matching the\n * declared composite shader types or as already-flattened leaf-path values.\n */\n getFlatUniformValues(\n uniformValues: Readonly>\n ): Record {\n const flattenedUniformValues: Record = {};\n\n for (const [name, value] of Object.entries(uniformValues)) {\n const uniformType = this.layout.uniformTypes[name];\n if (uniformType) {\n this._flattenCompositeValue(flattenedUniformValues, name, uniformType, value);\n } else if (this.layout.fields[name]) {\n flattenedUniformValues[name] = value as UniformValue;\n }\n }\n\n return flattenedUniformValues;\n }\n\n /**\n * Serializes the supplied values into buffer-backed binary data.\n *\n * The returned view length matches {@link ShaderBlockLayout.byteLength}, which\n * is the exact packed size of the block.\n */\n getData(uniformValues: Readonly>): Uint8Array {\n const buffer = getScratchArrayBuffer(this.layout.byteLength);\n new Uint8Array(buffer, 0, this.layout.byteLength).fill(0);\n const typedArrays = {\n i32: new Int32Array(buffer),\n u32: new Uint32Array(buffer),\n f32: new Float32Array(buffer),\n f16: new Uint16Array(buffer)\n };\n\n const flattenedUniformValues = this.getFlatUniformValues(uniformValues);\n for (const [name, value] of Object.entries(flattenedUniformValues)) {\n this._writeLeafValue(typedArrays, name, value);\n }\n\n return new Uint8Array(buffer, 0, this.layout.byteLength);\n }\n\n /**\n * Recursively flattens nested values using the declared composite shader type.\n */\n private _flattenCompositeValue(\n flattenedUniformValues: Record,\n baseName: string,\n uniformType: CompositeShaderType,\n value: CompositeUniformValue | undefined\n ): void {\n if (value === undefined) {\n return;\n }\n\n if (typeof uniformType === 'string' || this.layout.fields[baseName]) {\n flattenedUniformValues[baseName] = value as UniformValue;\n return;\n }\n\n if (Array.isArray(uniformType)) {\n const elementType = uniformType[0] as CompositeShaderType;\n const length = uniformType[1] as number;\n\n if (Array.isArray(elementType)) {\n throw new Error(`Nested arrays are not supported for ${baseName}`);\n }\n\n if (typeof elementType === 'string' && isNumberArray(value)) {\n this._flattenPackedArray(flattenedUniformValues, baseName, elementType, length, value);\n return;\n }\n\n if (!Array.isArray(value)) {\n log.warn(`Unsupported uniform array value for ${baseName}:`, value)();\n return;\n }\n\n for (let index = 0; index < Math.min(value.length, length); index++) {\n const elementValue = value[index];\n if (elementValue === undefined) {\n continue;\n }\n\n this._flattenCompositeValue(\n flattenedUniformValues,\n `${baseName}[${index}]`,\n elementType,\n elementValue\n );\n }\n return;\n }\n\n if (isCompositeShaderTypeStruct(uniformType) && isCompositeUniformObject(value)) {\n for (const [key, subValue] of Object.entries(value)) {\n if (subValue === undefined) {\n continue;\n }\n\n const nestedName = `${baseName}.${key}`;\n this._flattenCompositeValue(flattenedUniformValues, nestedName, uniformType[key], subValue);\n }\n return;\n }\n\n log.warn(`Unsupported uniform value for ${baseName}:`, value)();\n }\n\n /**\n * Expands tightly packed numeric arrays into per-element leaf fields.\n */\n private _flattenPackedArray(\n flattenedUniformValues: Record,\n baseName: string,\n elementType: VariableShaderType,\n length: number,\n value: UniformValue\n ): void {\n const numericValue = value as Readonly>;\n const elementLayout = getLeafLayoutInfo(elementType, this.layout.layout);\n const packedElementLength = elementLayout.components;\n\n for (let index = 0; index < length; index++) {\n const start = index * packedElementLength;\n if (start >= numericValue.length) {\n break;\n }\n\n if (packedElementLength === 1) {\n flattenedUniformValues[`${baseName}[${index}]`] = Number(numericValue[start]);\n } else {\n flattenedUniformValues[`${baseName}[${index}]`] = sliceNumericArray(\n value,\n start,\n start + packedElementLength\n ) as UniformValue;\n }\n }\n }\n\n /**\n * Writes one flattened leaf value into its typed-array view.\n */\n private _writeLeafValue(\n typedArrays: Record,\n name: string,\n value: UniformValue\n ): void {\n const entry = this.layout.fields[name];\n if (!entry) {\n log.warn(`Uniform ${name} not found in layout`)();\n return;\n }\n\n const {type, components, columns, rows, offset, columnStride} = entry;\n const array = typedArrays[type];\n\n if (components === 1) {\n array[offset] = Number(value);\n return;\n }\n\n const sourceValue = value as Readonly>;\n\n if (columns === 1) {\n for (let componentIndex = 0; componentIndex < components; componentIndex++) {\n array[offset + componentIndex] = Number(sourceValue[componentIndex] ?? 0);\n }\n return;\n }\n\n let sourceIndex = 0;\n for (let columnIndex = 0; columnIndex < columns; columnIndex++) {\n const columnOffset = offset + columnIndex * columnStride;\n for (let rowIndex = 0; rowIndex < rows; rowIndex++) {\n array[columnOffset + rowIndex] = Number(sourceValue[sourceIndex++] ?? 0);\n }\n }\n }\n}\n\n/**\n * Type guard for nested uniform objects.\n */\nfunction isCompositeUniformObject(\n value: CompositeUniformValue\n): value is Record {\n return (\n Boolean(value) &&\n typeof value === 'object' &&\n !Array.isArray(value) &&\n !ArrayBuffer.isView(value)\n );\n}\n\n/**\n * Slices a numeric array-like value without changing its numeric representation.\n */\nfunction sliceNumericArray(value: UniformValue, start: number, end: number): number[] {\n return Array.prototype.slice.call(value, start, end) as number[];\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {isNumberArray} from './is-array';\n\nconst MAX_ELEMENTWISE_ARRAY_COMPARE_LENGTH = 128;\n\n/** Test if two arrays are deep equal, with a small-array length limit that defaults to 16 */\nexport function arrayEqual(a: unknown, b: unknown, limit: number = 16) {\n if (a === b) {\n return true;\n }\n\n const arrayA = a;\n const arrayB = b;\n if (!isNumberArray(arrayA) || !isNumberArray(arrayB)) {\n return false;\n }\n\n if (arrayA.length !== arrayB.length) {\n return false;\n }\n\n const maxCompareLength = Math.min(limit, MAX_ELEMENTWISE_ARRAY_COMPARE_LENGTH);\n if (arrayA.length > maxCompareLength) {\n return false;\n }\n\n for (let i = 0; i < arrayA.length; ++i) {\n if (arrayB[i] !== arrayA[i]) {\n return false;\n }\n }\n\n return true;\n}\n\n/** Copy a value */\nexport function arrayCopy(a: T): T {\n if (isNumberArray(a)) {\n return a.slice() as T;\n }\n return a;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {VariableShaderType} from '../shadertypes/shader-types/shader-types';\nimport type {UniformValue} from '../adapter/types/uniforms';\nimport {\n ShaderLayout,\n UniformInfo,\n UniformBufferBindingLayout\n} from '../adapter/types/shader-layout';\nimport {arrayEqual, arrayCopy} from '../utils/array-equal';\n\n/**\n * A uniform block holds values of the of uniform values for one uniform block / buffer.\n * It also does some book keeping on what has changed, to minimize unnecessary writes to uniform buffers.\n */\nexport class UniformBlock<\n TUniforms extends Record = Record\n> {\n name: string;\n\n uniforms: Record = {} as Record;\n modifiedUniforms: Record = {} as Record;\n modified: boolean = true;\n\n readonly bindingLayout: Record = {};\n needsRedraw: string | false = 'initialized';\n\n constructor(props?: {\n name?: string;\n shaderLayout?: ShaderLayout;\n uniformTypes?: Record>;\n }) {\n this.name = props?.name || 'unnamed';\n\n // TODO - Extract uniform layout from the shaderLayout object\n if (props?.name && props?.shaderLayout) {\n const binding = props?.shaderLayout.bindings?.find(\n binding_ => binding_.type === 'uniform' && binding_.name === props?.name\n );\n if (!binding) {\n throw new Error(props?.name);\n }\n\n const uniformBlock = binding as UniformBufferBindingLayout;\n for (const uniform of uniformBlock.uniforms || []) {\n this.bindingLayout[uniform.name] = uniform;\n }\n }\n }\n\n /** Set a map of uniforms */\n setUniforms(uniforms: Partial): void {\n for (const [key, value] of Object.entries(uniforms)) {\n this._setUniform(key, value);\n if (!this.needsRedraw) {\n this.setNeedsRedraw(`${this.name}.${key}=${value}`);\n }\n }\n }\n\n setNeedsRedraw(reason: string): void {\n this.needsRedraw = this.needsRedraw || reason;\n }\n\n /** Returns all uniforms */\n getAllUniforms(): Record {\n // @ts-expect-error\n this.modifiedUniforms = {};\n this.needsRedraw = false;\n return (this.uniforms || {}) as Record;\n }\n\n /** Set a single uniform */\n private _setUniform(key: keyof TUniforms, value: UniformValue) {\n if (arrayEqual(this.uniforms[key], value)) {\n return;\n }\n this.uniforms[key] = arrayCopy(value);\n this.modifiedUniforms[key] = true;\n this.modified = true;\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {CompositeShaderType} from '../shadertypes/shader-types/shader-types';\nimport type {CompositeUniformValue} from '../adapter/types/uniforms';\nimport type {Device} from '../adapter/device';\nimport {Buffer} from '../adapter/resources/buffer';\nimport {log} from '../utils/log';\nimport {\n makeShaderBlockLayout,\n type ShaderBlockLayout\n} from '../shadertypes/shader-types/shader-block-layout';\nimport {UniformBlock} from './uniform-block';\nimport {ShaderBlockWriter} from './shader-block-writer';\n\n/** Definition of a single managed uniform block. */\nexport type UniformStoreBlockDefinition = {\n /** Declared shader types for the block's uniforms. */\n uniformTypes?: Record;\n /** Reserved for future prop-level defaults. */\n defaultProps?: Record;\n /** Initial uniform values written into the backing block. */\n defaultUniforms?: Record;\n /** Explicit shader-block layout override. */\n layout?: 'std140' | 'wgsl-uniform' | 'wgsl-storage';\n};\n\n/** Uniform block definitions keyed by block name. */\nexport type UniformStoreBlocks>> =\n Record;\n\n/**\n * Smallest buffer size that can be used for uniform buffers.\n *\n * This is an allocation policy rather than part of {@link ShaderBlockLayout}.\n * Layouts report the exact packed size, while the store applies any minimum\n * buffer-size rule when allocating GPU buffers.\n *\n * TODO - does this depend on device?\n */\nconst minUniformBufferSize = 1024;\n\n/**\n * A uniform store holds a uniform values for one or more uniform blocks,\n * - It can generate binary data for any uniform buffer\n * - It can manage a uniform buffer for each block\n * - It can update managed uniform buffers with a single call\n * - It performs some book keeping on what has changed to minimize unnecessary writes to uniform buffers.\n */\nexport class UniformStore<\n TPropGroups extends Record> = Record<\n string,\n Record\n >\n> {\n /** Device used to infer layout and allocate buffers. */\n readonly device: Device;\n /** Stores the uniform values for each uniform block */\n uniformBlocks = new Map();\n /** Flattened layout metadata for each block. */\n shaderBlockLayouts = new Map();\n /** Serializers for block-backed uniform data. */\n shaderBlockWriters = new Map();\n /** Actual buffer for the blocks */\n uniformBuffers = new Map();\n\n /**\n * Creates a new {@link UniformStore} for the supplied device and block definitions.\n */\n constructor(device: Device, blocks: UniformStoreBlocks) {\n this.device = device;\n\n for (const [bufferName, block] of Object.entries(blocks)) {\n const uniformBufferName = bufferName as keyof TPropGroups;\n\n // Create a layout object to help us generate correctly formatted binary uniform buffers\n const shaderBlockLayout = makeShaderBlockLayout(block.uniformTypes ?? {}, {\n layout: block.layout ?? getDefaultUniformBufferLayout(device)\n });\n const shaderBlockWriter = new ShaderBlockWriter(shaderBlockLayout);\n this.shaderBlockLayouts.set(uniformBufferName, shaderBlockLayout);\n this.shaderBlockWriters.set(uniformBufferName, shaderBlockWriter);\n\n // Create a Uniform block to store the uniforms for each buffer.\n const uniformBlock = new UniformBlock({name: bufferName});\n uniformBlock.setUniforms(shaderBlockWriter.getFlatUniformValues(block.defaultUniforms || {}));\n this.uniformBlocks.set(uniformBufferName, uniformBlock);\n }\n }\n\n /** Destroy any managed uniform buffers */\n destroy(): void {\n for (const uniformBuffer of this.uniformBuffers.values()) {\n uniformBuffer.destroy();\n }\n }\n\n /**\n * Set uniforms\n *\n * Makes all group properties partial and eagerly propagates changes to any\n * managed GPU buffers.\n */\n setUniforms(\n uniforms: Partial<{[group in keyof TPropGroups]: Partial}>\n ): void {\n for (const [blockName, uniformValues] of Object.entries(uniforms)) {\n const uniformBufferName = blockName as keyof TPropGroups;\n const shaderBlockWriter = this.shaderBlockWriters.get(uniformBufferName);\n const flattenedUniforms = shaderBlockWriter?.getFlatUniformValues(\n (uniformValues || {}) as Record\n );\n this.uniformBlocks.get(uniformBufferName)?.setUniforms(flattenedUniforms || {});\n // We leverage logging in updateUniformBuffers(), even though slightly less efficient\n // this.updateUniformBuffer(blockName);\n }\n\n this.updateUniformBuffers();\n }\n\n /**\n * Returns the allocation size for the named uniform buffer.\n *\n * This may exceed the packed layout size because minimum buffer-size policy is\n * applied at the store layer.\n */\n getUniformBufferByteLength(uniformBufferName: keyof TPropGroups): number {\n const packedByteLength = this.shaderBlockLayouts.get(uniformBufferName)?.byteLength || 0;\n return Math.max(packedByteLength, minUniformBufferSize);\n }\n\n /**\n * Returns packed binary data that can be uploaded to the named uniform buffer.\n *\n * The returned view length matches the packed block size and is not padded to\n * the store's minimum allocation size.\n */\n getUniformBufferData(uniformBufferName: keyof TPropGroups): Uint8Array {\n const uniformValues = this.uniformBlocks.get(uniformBufferName)?.getAllUniforms() || {};\n const shaderBlockWriter = this.shaderBlockWriters.get(uniformBufferName);\n return shaderBlockWriter?.getData(uniformValues) || new Uint8Array(0);\n }\n\n /**\n * Creates an unmanaged uniform buffer initialized with the current or supplied values.\n */\n createUniformBuffer(\n uniformBufferName: keyof TPropGroups,\n uniforms?: Partial<{[group in keyof TPropGroups]: Partial}>\n ): Buffer {\n if (uniforms) {\n this.setUniforms(uniforms);\n }\n const byteLength = this.getUniformBufferByteLength(uniformBufferName);\n const uniformBuffer = this.device.createBuffer({\n usage: Buffer.UNIFORM | Buffer.COPY_DST,\n byteLength\n });\n // Note that this clears the needs redraw flag\n const uniformBufferData = this.getUniformBufferData(uniformBufferName);\n uniformBuffer.write(uniformBufferData);\n return uniformBuffer;\n }\n\n /** Returns the managed uniform buffer for the named block. */\n getManagedUniformBuffer(uniformBufferName: keyof TPropGroups): Buffer {\n if (!this.uniformBuffers.get(uniformBufferName)) {\n const byteLength = this.getUniformBufferByteLength(uniformBufferName);\n const uniformBuffer = this.device.createBuffer({\n usage: Buffer.UNIFORM | Buffer.COPY_DST,\n byteLength\n });\n this.uniformBuffers.set(uniformBufferName, uniformBuffer);\n }\n // this.updateUniformBuffers();\n // @ts-ignore\n return this.uniformBuffers.get(uniformBufferName);\n }\n\n /**\n * Updates every managed uniform buffer whose source uniforms have changed.\n *\n * @returns The first redraw reason encountered, or `false` if nothing changed.\n */\n updateUniformBuffers(): false | string {\n let reason: false | string = false;\n for (const uniformBufferName of this.uniformBlocks.keys()) {\n const bufferReason = this.updateUniformBuffer(uniformBufferName);\n reason ||= bufferReason;\n }\n if (reason) {\n log.log(3, `UniformStore.updateUniformBuffers(): ${reason}`)();\n }\n return reason;\n }\n\n /**\n * Updates one managed uniform buffer if its corresponding block is dirty.\n *\n * @returns The redraw reason for the update, or `false` if no write occurred.\n */\n updateUniformBuffer(uniformBufferName: keyof TPropGroups): false | string {\n const uniformBlock = this.uniformBlocks.get(uniformBufferName);\n let uniformBuffer = this.uniformBuffers.get(uniformBufferName);\n\n let reason: false | string = false;\n if (uniformBuffer && uniformBlock?.needsRedraw) {\n reason ||= uniformBlock.needsRedraw;\n // This clears the needs redraw flag\n const uniformBufferData = this.getUniformBufferData(uniformBufferName);\n\n uniformBuffer = this.uniformBuffers.get(uniformBufferName);\n uniformBuffer?.write(uniformBufferData);\n\n // logging - TODO - don't query the values unnecessarily\n const uniformValues = this.uniformBlocks.get(uniformBufferName)?.getAllUniforms();\n log.log(\n 4,\n `Writing to uniform buffer ${String(uniformBufferName)}`,\n uniformBufferData,\n uniformValues\n )();\n }\n return reason;\n }\n}\n\n/**\n * Returns the default uniform-buffer layout for the supplied device.\n */\nfunction getDefaultUniformBufferLayout(device: Device): 'std140' | 'wgsl-uniform' | 'wgsl-storage' {\n return device.type === 'webgpu' ? 'wgsl-uniform' : 'std140';\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// MAIN API ACCESS POINT\nexport type {AttachDeviceProps, CreateDeviceProps} from './adapter/luma';\nexport {luma} from './adapter/luma';\n\n// ADAPTER (DEVICE AND GPU RESOURCE INTERFACES)\nexport {Adapter} from './adapter/adapter';\n\nexport type {\n DeviceProps,\n DeviceInfo,\n DeviceFeature,\n DeviceTextureFormatCapabilities\n} from './adapter/device';\nexport {Device, DeviceFeatures, DeviceLimits} from './adapter/device';\n\nexport type {CanvasContextProps} from './adapter/canvas-context';\nexport {CanvasContext} from './adapter/canvas-context';\nexport type {PresentationContextProps} from './adapter/presentation-context';\nexport {PresentationContext} from './adapter/presentation-context';\n\n// GPU RESOURCES\nexport {Resource, type ResourceProps} from './adapter/resources/resource';\n\nexport {Buffer, type BufferProps, type BufferMapCallback} from './adapter/resources/buffer';\n\nexport {Texture, type TextureProps} from './adapter/resources/texture';\n\nexport {TextureView, type TextureViewProps} from './adapter/resources/texture-view';\n\nexport type {ExternalTextureProps} from './adapter/resources/external-texture';\nexport {ExternalTexture} from './adapter/resources/external-texture';\n\nexport type {ShaderProps} from './adapter/resources/shader';\nexport {Shader} from './adapter/resources/shader';\n\nexport type {SamplerProps, SamplerParameters} from './adapter/resources/sampler';\nexport {Sampler} from './adapter/resources/sampler';\n\nexport type {FramebufferProps} from './adapter/resources/framebuffer';\nexport {Framebuffer} from './adapter/resources/framebuffer';\n\nexport type {RenderPipelineProps} from './adapter/resources/render-pipeline';\nexport {RenderPipeline} from './adapter/resources/render-pipeline';\nexport {\n SharedRenderPipeline,\n type SharedRenderPipelineProps\n} from './adapter/resources/shared-render-pipeline';\nexport type {PipelineFactoryProps} from './factories/pipeline-factory';\nexport {PipelineFactory} from './factories/pipeline-factory';\nexport {ShaderFactory} from './factories/shader-factory';\nexport {_getDefaultBindGroupFactory} from './factories/bind-group-factory';\n\nexport type {RenderPassProps} from './adapter/resources/render-pass';\nexport {RenderPass} from './adapter/resources/render-pass';\n\nexport type {ComputePipelineProps} from './adapter/resources/compute-pipeline';\nexport {ComputePipeline} from './adapter/resources/compute-pipeline';\n\nexport type {ComputePassProps} from './adapter/resources/compute-pass';\nexport {ComputePass} from './adapter/resources/compute-pass';\n\nexport type {CommandEncoderProps} from './adapter/resources/command-encoder';\nexport {CommandEncoder} from './adapter/resources/command-encoder';\n\nexport type {CommandBufferProps} from './adapter/resources/command-buffer';\nexport {CommandBuffer} from './adapter/resources/command-buffer';\n\nexport type {VertexArrayProps} from './adapter/resources/vertex-array';\nexport {VertexArray} from './adapter/resources/vertex-array';\n\nexport type {TransformFeedbackProps, BufferRange} from './adapter/resources/transform-feedback';\nexport {TransformFeedback} from './adapter/resources/transform-feedback';\n\nexport type {QuerySetProps} from './adapter/resources/query-set';\nexport {QuerySet} from './adapter/resources/query-set';\n\nexport {Fence, type FenceProps} from './adapter/resources/fence';\n\nexport type {PipelineLayoutProps} from './adapter/resources/pipeline-layout';\nexport {PipelineLayout} from './adapter/resources/pipeline-layout';\n\n// PORTABLE API - UNIFORM BUFFERS\nexport {\n makeShaderBlockLayout,\n type ShaderBlockLayout,\n type ShaderBlockLayoutEntry,\n type ShaderBlockLayoutOptions\n} from './shadertypes/shader-types/shader-block-layout';\nexport {ShaderBlockWriter} from './portable/shader-block-writer';\nexport {UniformBlock} from './portable/uniform-block';\nexport {UniformStore} from './portable/uniform-store';\n// TEXTURE TYPES\n\n// API TYPES\nexport type {CompilerMessage} from './adapter/types/compiler-message';\n\nexport type {ExternalImage} from './shadertypes/image-types/image-types';\n\nexport {\n type CopyExternalImageOptions,\n type CopyImageDataOptions,\n type TextureReadOptions,\n type TextureWriteOptions\n} from './adapter/resources/texture';\n\nexport type {Parameters, PrimitiveTopology, IndexFormat} from './adapter/types/parameters';\n\nexport type {\n CullMode,\n FrontFace,\n RasterizationParameters,\n CompareFunction,\n StencilOperation,\n DepthStencilParameters,\n BlendFactor,\n BlendOperation,\n ColorParameters,\n MultisampleParameters,\n RenderPassParameters,\n RenderPipelineParameters,\n PolygonMode,\n ProvokingVertex\n} from './adapter/types/parameters';\n\nexport type {ColorAttachment, DepthStencilAttachment} from './adapter/types/attachments';\n\nexport type {\n ShaderLayout,\n ComputeShaderLayout,\n AttributeDeclaration,\n BindingDeclaration,\n Binding,\n Bindings,\n BindingsByGroup,\n UniformBufferBindingLayout,\n StorageBufferBindingLayout,\n TextureBindingLayout,\n SamplerBindingLayout,\n StorageTextureBindingLayout\n} from './adapter/types/shader-layout';\nexport type {BufferLayout, BufferAttributeLayout} from './adapter/types/buffer-layout';\nexport type {\n // Deprecated, todo\n AttributeBinding,\n UniformBinding,\n UniformBlockBinding,\n VaryingBinding\n} from './adapter/types/shader-layout';\n\nexport type {UniformValue} from './adapter/types/uniforms';\nexport type {\n CompositeUniformValue,\n CompositeUniformValueArray,\n CompositeUniformValueStruct\n} from './adapter/types/uniforms';\n\n// TYPED ARRAY TYPES\n\nexport type {\n NumberArray,\n TypedArray,\n TypedArrayConstructor,\n BigTypedArray,\n BigTypedArrayConstructor\n} from './types';\n\n// GPU TYPE UTILS - BASIC DATA TYPES\n\nexport {\n type PrimitiveDataType,\n type SignedDataType,\n type NormalizedDataType,\n type DataTypeInfo,\n type PrimitiveDataTypeT,\n type SignedDataTypeT,\n type TypedArrayConstructorT,\n type NormalizedTypedArrayConstructorT\n} from './shadertypes/data-types/data-types';\nexport {dataTypeDecoder} from './shadertypes/data-types/data-type-decoder';\nexport {getTypedArrayConstructor} from './shadertypes/data-types/decode-data-types';\n\nexport {\n type AttributeShaderTypeT,\n type AttributeShaderType,\n type ArrayShaderType,\n type CompositeShaderType,\n type StructShaderType,\n type VariableShaderTypeT,\n type VariableShaderType\n} from './shadertypes/shader-types/shader-types';\nexport {\n shaderTypeDecoder,\n getAttributeShaderTypeInfo,\n getVariableShaderTypeInfo,\n type AttributeShaderTypeInfo\n} from './shadertypes/shader-types/shader-type-decoder';\n\n// GPU TYPE UTILS - VERTEX ARRAYs\n\nexport {\n type VertexFormat,\n type VertexFormatDataTypeT\n} from './shadertypes/vertex-types/vertex-formats';\n\nexport {vertexFormatDecoder} from './shadertypes/vertex-types/vertex-format-decoder';\n\n// GPU TYPE UTILS - Texture Formats\n\nexport {\n type TextureFormat,\n type TextureFormatColor,\n type TextureFormatDepthStencil,\n type CompressedTextureFormat,\n type TextureCompression,\n type TextureFormatInfo,\n type TextureFormatCapabilities,\n type TextureMemoryLayout\n} from './shadertypes/texture-types/texture-formats';\nexport {type TextureFormatDataTypeT} from './shadertypes/texture-types/texture-format-generics';\n\nexport {\n type TextureFormatDecoder,\n textureFormatDecoder\n} from './shadertypes/texture-types/texture-format-decoder';\n\nexport {getTextureImageView, setTextureImageData} from './shadertypes/texture-types/texture-layout';\nexport {type PixelData, readPixel, writePixel} from './shadertypes/texture-types/pixel-utils';\n\nexport {isExternalImage, getExternalImageSize} from './shadertypes/image-types/image-types';\n\n// GENERAL EXPORTS - FOR APPLICATIONS\n\nexport type {StatsManager} from './utils/stats-manager'; // TODO - should this be moved to probe.gl?\n\n// ADAPTER UTILS - for implementing Device adapters (@luma.gl/webgl and @luma.gl/webgpu)\n\nexport type {\n CopyBufferToBufferOptions,\n CopyBufferToTextureOptions,\n CopyTextureToBufferOptions,\n CopyTextureToTextureOptions\n} from './adapter/resources/command-encoder';\n\n// INTERNAL UTILS - for use in other luma.gl modules only\nexport {log} from './utils/log';\nexport {\n getShaderLayoutBinding,\n normalizeBindingsByGroup,\n flattenBindingsByGroup\n} from './adapter-utils/bind-groups';\nexport {assert, assertDefined} from './utils/assert';\nexport {getScratchArray} from './utils/array-utils-flat';\nexport type {AttributeInfo} from './adapter-utils/get-attribute-from-layouts';\nexport {getAttributeInfosFromLayouts} from './adapter-utils/get-attribute-from-layouts';\n\n// TEST EXPORTS\nexport {\n getTextureFormatDefinition as _getTextureFormatDefinition,\n getTextureFormatTable as _getTextureFormatTable\n} from './shadertypes/texture-types/texture-format-table';\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/* eslint-disable key-spacing, max-len, no-inline-comments, camelcase */\n\n/**\n * Standard WebGL, WebGL2 and extension constants (OpenGL constants)\n * @note (Most) of these constants are also defined on the WebGLRenderingContext interface.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Constants\n * @privateRemarks Locally called `GLEnum` instead of `GL`, because `babel-plugin-inline-webl-constants`\n * both depends on and processes this module, but shouldn't replace these declarations.\n */\n// eslint-disable-next-line no-shadow\nenum GLEnum {\n // Clearing buffers\n // Constants passed to clear() to clear buffer masks.\n\n /** Passed to clear to clear the current depth buffer. */\n DEPTH_BUFFER_BIT = 0x00000100,\n /** Passed to clear to clear the current stencil buffer. */\n STENCIL_BUFFER_BIT = 0x00000400,\n /** Passed to clear to clear the current color buffer. */\n COLOR_BUFFER_BIT = 0x00004000,\n\n // Rendering primitives\n // Constants passed to drawElements() or drawArrays() to specify what kind of primitive to render.\n\n /** Passed to drawElements or drawArrays to draw single points. */\n POINTS = 0x0000,\n /** Passed to drawElements or drawArrays to draw lines. Each vertex connects to the one after it. */\n LINES = 0x0001,\n /** Passed to drawElements or drawArrays to draw lines. Each set of two vertices is treated as a separate line segment. */\n LINE_LOOP = 0x0002,\n /** Passed to drawElements or drawArrays to draw a connected group of line segments from the first vertex to the last. */\n LINE_STRIP = 0x0003,\n /** Passed to drawElements or drawArrays to draw triangles. Each set of three vertices creates a separate triangle. */\n TRIANGLES = 0x0004,\n /** Passed to drawElements or drawArrays to draw a connected group of triangles. */\n TRIANGLE_STRIP = 0x0005,\n /** Passed to drawElements or drawArrays to draw a connected group of triangles. Each vertex connects to the previous and the first vertex in the fan. */\n TRIANGLE_FAN = 0x0006,\n\n // Blending modes\n // Constants passed to blendFunc() or blendFuncSeparate() to specify the blending mode (for both, RBG and alpha, or separately).\n /** Passed to blendFunc or blendFuncSeparate to turn off a component. */\n ZERO = 0,\n /** Passed to blendFunc or blendFuncSeparate to turn on a component. */\n ONE = 1,\n /** Passed to blendFunc or blendFuncSeparate to multiply a component by the source elements color. */\n SRC_COLOR = 0x0300,\n /** Passed to blendFunc or blendFuncSeparate to multiply a component by one minus the source elements color. */\n ONE_MINUS_SRC_COLOR = 0x0301,\n /** Passed to blendFunc or blendFuncSeparate to multiply a component by the source's alpha. */\n SRC_ALPHA = 0x0302,\n /** Passed to blendFunc or blendFuncSeparate to multiply a component by one minus the source's alpha. */\n ONE_MINUS_SRC_ALPHA = 0x0303,\n /** Passed to blendFunc or blendFuncSeparate to multiply a component by the destination's alpha. */\n DST_ALPHA = 0x0304,\n /** Passed to blendFunc or blendFuncSeparate to multiply a component by one minus the destination's alpha. */\n ONE_MINUS_DST_ALPHA = 0x0305,\n /** Passed to blendFunc or blendFuncSeparate to multiply a component by the destination's color. */\n DST_COLOR = 0x0306,\n /** Passed to blendFunc or blendFuncSeparate to multiply a component by one minus the destination's color. */\n ONE_MINUS_DST_COLOR = 0x0307,\n /** Passed to blendFunc or blendFuncSeparate to multiply a component by the minimum of source's alpha or one minus the destination's alpha. */\n SRC_ALPHA_SATURATE = 0x0308,\n /** Passed to blendFunc or blendFuncSeparate to specify a constant color blend function. */\n CONSTANT_COLOR = 0x8001,\n /** Passed to blendFunc or blendFuncSeparate to specify one minus a constant color blend function. */\n ONE_MINUS_CONSTANT_COLOR = 0x8002,\n /** Passed to blendFunc or blendFuncSeparate to specify a constant alpha blend function. */\n CONSTANT_ALPHA = 0x8003,\n /** Passed to blendFunc or blendFuncSeparate to specify one minus a constant alpha blend function. */\n ONE_MINUS_CONSTANT_ALPHA = 0x8004,\n\n // Blending equations\n // Constants passed to blendEquation() or blendEquationSeparate() to control\n // how the blending is calculated (for both, RBG and alpha, or separately).\n\n /** Passed to blendEquation or blendEquationSeparate to set an addition blend function. */\n /** Passed to blendEquation or blendEquationSeparate to specify a subtraction blend function (source - destination). */\n /** Passed to blendEquation or blendEquationSeparate to specify a reverse subtraction blend function (destination - source). */\n FUNC_ADD = 0x8006,\n FUNC_SUBTRACT = 0x800a,\n FUNC_REVERSE_SUBTRACT = 0x800b,\n\n // Getting GL parameter information\n // Constants passed to getParameter() to specify what information to return.\n\n /** Passed to getParameter to get the current RGB blend function. */\n BLEND_EQUATION = 0x8009,\n /** Passed to getParameter to get the current RGB blend function. Same as BLEND_EQUATION */\n BLEND_EQUATION_RGB = 0x8009,\n /** Passed to getParameter to get the current alpha blend function. Same as BLEND_EQUATION */\n BLEND_EQUATION_ALPHA = 0x883d,\n /** Passed to getParameter to get the current destination RGB blend function. */\n BLEND_DST_RGB = 0x80c8,\n /** Passed to getParameter to get the current destination RGB blend function. */\n BLEND_SRC_RGB = 0x80c9,\n /** Passed to getParameter to get the current destination alpha blend function. */\n BLEND_DST_ALPHA = 0x80ca,\n /** Passed to getParameter to get the current source alpha blend function. */\n BLEND_SRC_ALPHA = 0x80cb,\n\n /** Passed to getParameter to return a the current blend color. */\n BLEND_COLOR = 0x8005,\n /** Passed to getParameter to get the array buffer binding. */\n ARRAY_BUFFER_BINDING = 0x8894,\n /** Passed to getParameter to get the current element array buffer. */\n ELEMENT_ARRAY_BUFFER_BINDING = 0x8895,\n /** Passed to getParameter to get the current lineWidth (set by the lineWidth method). */\n LINE_WIDTH = 0x0b21,\n /** Passed to getParameter to get the current size of a point drawn with gl.POINTS */\n ALIASED_POINT_SIZE_RANGE = 0x846d,\n /** Passed to getParameter to get the range of available widths for a line. Returns a length-2 array with the lo value at 0, and hight at 1. */\n ALIASED_LINE_WIDTH_RANGE = 0x846e,\n /** Passed to getParameter to get the current value of cullFace. Should return FRONT, BACK, or FRONT_AND_BACK */\n CULL_FACE_MODE = 0x0b45,\n /** Passed to getParameter to determine the current value of frontFace. Should return CW or CCW. */\n FRONT_FACE = 0x0b46,\n /** Passed to getParameter to return a length-2 array of floats giving the current depth range. */\n DEPTH_RANGE = 0x0b70,\n /** Passed to getParameter to determine if the depth write mask is enabled. */\n\n DEPTH_WRITEMASK = 0x0b72,\n /** Passed to getParameter to determine the current depth clear value. */\n DEPTH_CLEAR_VALUE = 0x0b73,\n /** Passed to getParameter to get the current depth function. Returns NEVER, ALWAYS, LESS, EQUAL, LEQUAL, GREATER, GEQUAL, or NOTEQUAL. */\n DEPTH_FUNC = 0x0b74,\n /** Passed to getParameter to get the value the stencil will be cleared to. */\n STENCIL_CLEAR_VALUE = 0x0b91,\n /** Passed to getParameter to get the current stencil function. Returns NEVER, ALWAYS, LESS, EQUAL, LEQUAL, GREATER, GEQUAL, or NOTEQUAL. */\n STENCIL_FUNC = 0x0b92,\n /** Passed to getParameter to get the current stencil fail function. Should return KEEP, REPLACE, INCR, DECR, INVERT, INCR_WRAP, or DECR_WRAP. */\n STENCIL_FAIL = 0x0b94,\n /** Passed to getParameter to get the current stencil fail function should the depth buffer test fail. Should return KEEP, REPLACE, INCR, DECR, INVERT, INCR_WRAP, or DECR_WRAP. */\n STENCIL_PASS_DEPTH_FAIL = 0x0b95,\n /** Passed to getParameter to get the current stencil fail function should the depth buffer test pass. Should return KEEP, REPLACE, INCR, DECR, INVERT, INCR_WRAP, or DECR_WRAP. */\n STENCIL_PASS_DEPTH_PASS = 0x0b96,\n /** Passed to getParameter to get the reference value used for stencil tests. */\n STENCIL_REF = 0x0b97,\n STENCIL_VALUE_MASK = 0x0b93,\n STENCIL_WRITEMASK = 0x0b98,\n STENCIL_BACK_FUNC = 0x8800,\n STENCIL_BACK_FAIL = 0x8801,\n STENCIL_BACK_PASS_DEPTH_FAIL = 0x8802,\n STENCIL_BACK_PASS_DEPTH_PASS = 0x8803,\n STENCIL_BACK_REF = 0x8ca3,\n STENCIL_BACK_VALUE_MASK = 0x8ca4,\n STENCIL_BACK_WRITEMASK = 0x8ca5,\n\n /** An Int32Array with four elements for the current viewport dimensions. */\n VIEWPORT = 0x0ba2,\n /** An Int32Array with four elements for the current scissor box dimensions. */\n SCISSOR_BOX = 0x0c10,\n COLOR_CLEAR_VALUE = 0x0c22,\n COLOR_WRITEMASK = 0x0c23,\n UNPACK_ALIGNMENT = 0x0cf5,\n PACK_ALIGNMENT = 0x0d05,\n MAX_TEXTURE_SIZE = 0x0d33,\n MAX_VIEWPORT_DIMS = 0x0d3a,\n SUBPIXEL_BITS = 0x0d50,\n RED_BITS = 0x0d52,\n GREEN_BITS = 0x0d53,\n BLUE_BITS = 0x0d54,\n ALPHA_BITS = 0x0d55,\n DEPTH_BITS = 0x0d56,\n STENCIL_BITS = 0x0d57,\n POLYGON_OFFSET_UNITS = 0x2a00,\n POLYGON_OFFSET_FACTOR = 0x8038,\n TEXTURE_BINDING_2D = 0x8069,\n SAMPLE_BUFFERS = 0x80a8,\n SAMPLES = 0x80a9,\n SAMPLE_COVERAGE_VALUE = 0x80aa,\n SAMPLE_COVERAGE_INVERT = 0x80ab,\n COMPRESSED_TEXTURE_FORMATS = 0x86a3,\n VENDOR = 0x1f00,\n RENDERER = 0x1f01,\n VERSION = 0x1f02,\n IMPLEMENTATION_COLOR_READ_TYPE = 0x8b9a,\n IMPLEMENTATION_COLOR_READ_FORMAT = 0x8b9b,\n BROWSER_DEFAULT_WEBGL = 0x9244,\n\n // Buffers\n // Constants passed to bufferData(), bufferSubData(), bindBuffer(), or\n // getBufferParameter().\n\n /** Passed to bufferData as a hint about whether the contents of the buffer are likely to be used often and not change often. */\n STATIC_DRAW = 0x88e4,\n /** Passed to bufferData as a hint about whether the contents of the buffer are likely to not be used often. */\n STREAM_DRAW = 0x88e0,\n /** Passed to bufferData as a hint about whether the contents of the buffer are likely to be used often and change often. */\n DYNAMIC_DRAW = 0x88e8,\n /** Passed to bindBuffer or bufferData to specify the type of buffer being used. */\n ARRAY_BUFFER = 0x8892,\n /** Passed to bindBuffer or bufferData to specify the type of buffer being used. */\n ELEMENT_ARRAY_BUFFER = 0x8893,\n /** Passed to getBufferParameter to get a buffer's size. */\n BUFFER_SIZE = 0x8764,\n /** Passed to getBufferParameter to get the hint for the buffer passed in when it was created. */\n BUFFER_USAGE = 0x8765,\n\n // Vertex attributes\n // Constants passed to getVertexAttrib().\n\n /** Passed to getVertexAttrib to read back the current vertex attribute. */\n CURRENT_VERTEX_ATTRIB = 0x8626,\n VERTEX_ATTRIB_ARRAY_ENABLED = 0x8622,\n VERTEX_ATTRIB_ARRAY_SIZE = 0x8623,\n VERTEX_ATTRIB_ARRAY_STRIDE = 0x8624,\n VERTEX_ATTRIB_ARRAY_TYPE = 0x8625,\n VERTEX_ATTRIB_ARRAY_NORMALIZED = 0x886a,\n VERTEX_ATTRIB_ARRAY_POINTER = 0x8645,\n VERTEX_ATTRIB_ARRAY_BUFFER_BINDING = 0x889f,\n\n // Culling\n // Constants passed to cullFace().\n\n /** Passed to enable/disable to turn on/off culling. Can also be used with getParameter to find the current culling method. */\n CULL_FACE = 0x0b44,\n /** Passed to cullFace to specify that only front faces should be culled. */\n FRONT = 0x0404,\n /** Passed to cullFace to specify that only back faces should be culled. */\n BACK = 0x0405,\n /** Passed to cullFace to specify that front and back faces should be culled. */\n FRONT_AND_BACK = 0x0408,\n\n // Enabling and disabling\n // Constants passed to enable() or disable().\n\n /** Passed to enable/disable to turn on/off blending. Can also be used with getParameter to find the current blending method. */\n BLEND = 0x0be2,\n /** Passed to enable/disable to turn on/off the depth test. Can also be used with getParameter to query the depth test. */\n DEPTH_TEST = 0x0b71,\n /** Passed to enable/disable to turn on/off dithering. Can also be used with getParameter to find the current dithering method. */\n DITHER = 0x0bd0,\n /** Passed to enable/disable to turn on/off the polygon offset. Useful for rendering hidden-line images, decals, and or solids with highlighted edges. Can also be used with getParameter to query the scissor test. */\n POLYGON_OFFSET_FILL = 0x8037,\n /** Passed to enable/disable to turn on/off the alpha to coverage. Used in multi-sampling alpha channels. */\n SAMPLE_ALPHA_TO_COVERAGE = 0x809e,\n /** Passed to enable/disable to turn on/off the sample coverage. Used in multi-sampling. */\n SAMPLE_COVERAGE = 0x80a0,\n /** Passed to enable/disable to turn on/off the scissor test. Can also be used with getParameter to query the scissor test. */\n SCISSOR_TEST = 0x0c11,\n /** Passed to enable/disable to turn on/off the stencil test. Can also be used with getParameter to query the stencil test. */\n STENCIL_TEST = 0x0b90,\n\n // Errors\n // Constants returned from getError().\n\n /** Returned from getError(). */\n NO_ERROR = 0,\n /** Returned from getError(). */\n INVALID_ENUM = 0x0500,\n /** Returned from getError(). */\n INVALID_VALUE = 0x0501,\n /** Returned from getError(). */\n INVALID_OPERATION = 0x0502,\n /** Returned from getError(). */\n OUT_OF_MEMORY = 0x0505,\n /** Returned from getError(). */\n CONTEXT_LOST_WEBGL = 0x9242,\n\n // Front face directions\n // Constants passed to frontFace().\n\n /** Passed to frontFace to specify the front face of a polygon is drawn in the clockwise direction */\n CW = 0x0900,\n /** Passed to frontFace to specify the front face of a polygon is drawn in the counter clockwise direction */\n CCW = 0x0901,\n\n // Hints\n // Constants passed to hint()\n\n /** There is no preference for this behavior. */\n DONT_CARE = 0x1100,\n /** The most efficient behavior should be used. */\n FASTEST = 0x1101,\n /** The most correct or the highest quality option should be used. */\n NICEST = 0x1102,\n /** Hint for the quality of filtering when generating mipmap images with WebGLRenderingContext.generateMipmap(). */\n GENERATE_MIPMAP_HINT = 0x8192,\n\n // Data types\n\n BYTE = 0x1400,\n UNSIGNED_BYTE = 0x1401,\n SHORT = 0x1402,\n UNSIGNED_SHORT = 0x1403,\n INT = 0x1404,\n UNSIGNED_INT = 0x1405,\n FLOAT = 0x1406,\n DOUBLE = 0x140a,\n\n // Pixel formats\n\n DEPTH_COMPONENT = 0x1902,\n ALPHA = 0x1906,\n RGB = 0x1907,\n RGBA = 0x1908,\n LUMINANCE = 0x1909,\n LUMINANCE_ALPHA = 0x190a,\n\n // Pixel types\n\n // UNSIGNED_BYTE = 0x1401,\n UNSIGNED_SHORT_4_4_4_4 = 0x8033,\n UNSIGNED_SHORT_5_5_5_1 = 0x8034,\n UNSIGNED_SHORT_5_6_5 = 0x8363,\n\n // Shaders\n // Constants passed to createShader() or getShaderParameter()\n\n /** Passed to createShader to define a fragment shader. */\n FRAGMENT_SHADER = 0x8b30,\n /** Passed to createShader to define a vertex shader */\n VERTEX_SHADER = 0x8b31,\n /** Passed to getShaderParameter to get the status of the compilation. Returns false if the shader was not compiled. You can then query getShaderInfoLog to find the exact error */\n COMPILE_STATUS = 0x8b81,\n /** Passed to getShaderParameter to determine if a shader was deleted via deleteShader. Returns true if it was, false otherwise. */\n DELETE_STATUS = 0x8b80,\n /** Passed to getProgramParameter after calling linkProgram to determine if a program was linked correctly. Returns false if there were errors. Use getProgramInfoLog to find the exact error. */\n LINK_STATUS = 0x8b82,\n /** Passed to getProgramParameter after calling validateProgram to determine if it is valid. Returns false if errors were found. */\n VALIDATE_STATUS = 0x8b83,\n /** Passed to getProgramParameter after calling attachShader to determine if the shader was attached correctly. Returns false if errors occurred. */\n ATTACHED_SHADERS = 0x8b85,\n /** Passed to getProgramParameter to get the number of attributes active in a program. */\n ACTIVE_ATTRIBUTES = 0x8b89,\n /** Passed to getProgramParameter to get the number of uniforms active in a program. */\n ACTIVE_UNIFORMS = 0x8b86,\n /** The maximum number of entries possible in the vertex attribute list. */\n MAX_VERTEX_ATTRIBS = 0x8869,\n MAX_VERTEX_UNIFORM_VECTORS = 0x8dfb,\n MAX_VARYING_VECTORS = 0x8dfc,\n MAX_COMBINED_TEXTURE_IMAGE_UNITS = 0x8b4d,\n MAX_VERTEX_TEXTURE_IMAGE_UNITS = 0x8b4c,\n /** Implementation dependent number of maximum texture units. At least 8. */\n MAX_TEXTURE_IMAGE_UNITS = 0x8872,\n MAX_FRAGMENT_UNIFORM_VECTORS = 0x8dfd,\n SHADER_TYPE = 0x8b4f,\n SHADING_LANGUAGE_VERSION = 0x8b8c,\n CURRENT_PROGRAM = 0x8b8d,\n\n // Depth or stencil tests\n // Constants passed to depthFunc() or stencilFunc().\n\n /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass, i.e., nothing will be drawn. */\n NEVER = 0x0200,\n /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value. */\n LESS = 0x0201,\n /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value. */\n EQUAL = 0x0202,\n /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value. */\n LEQUAL = 0x0203,\n /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value. */\n GREATER = 0x0204,\n /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value. */\n NOTEQUAL = 0x0205,\n /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value. */\n GEQUAL = 0x0206,\n /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass, i.e., pixels will be drawn in the order they are drawn. */\n ALWAYS = 0x0207,\n\n // Stencil actions\n // Constants passed to stencilOp().\n\n KEEP = 0x1e00,\n REPLACE = 0x1e01,\n INCR = 0x1e02,\n DECR = 0x1e03,\n INVERT = 0x150a,\n INCR_WRAP = 0x8507,\n DECR_WRAP = 0x8508,\n\n // Textures\n // Constants passed to texParameteri(),\n // texParameterf(), bindTexture(), texImage2D(), and others.\n\n NEAREST = 0x2600,\n LINEAR = 0x2601,\n NEAREST_MIPMAP_NEAREST = 0x2700,\n LINEAR_MIPMAP_NEAREST = 0x2701,\n NEAREST_MIPMAP_LINEAR = 0x2702,\n LINEAR_MIPMAP_LINEAR = 0x2703,\n /** The texture magnification function is used when the pixel being textured maps to an area less than or equal to one texture element. It sets the texture magnification function to either GL_NEAREST or GL_LINEAR (see below). GL_NEAREST is generally faster than GL_LINEAR, but it can produce textured images with sharper edges because the transition between texture elements is not as smooth. Default: GL_LINEAR. */\n TEXTURE_MAG_FILTER = 0x2800,\n /** The texture minifying function is used whenever the pixel being textured maps to an area greater than one texture element. There are six defined minifying functions. Two of them use the nearest one or nearest four texture elements to compute the texture value. The other four use mipmaps. Default: GL_NEAREST_MIPMAP_LINEAR */\n TEXTURE_MIN_FILTER = 0x2801,\n /** Sets the wrap parameter for texture coordinate to either GL_CLAMP_TO_EDGE, GL_MIRRORED_REPEAT, or GL_REPEAT. G */\n TEXTURE_WRAP_S = 0x2802,\n /** Sets the wrap parameter for texture coordinate to either GL_CLAMP_TO_EDGE, GL_MIRRORED_REPEAT, or GL_REPEAT. G */\n TEXTURE_WRAP_T = 0x2803,\n TEXTURE_2D = 0x0de1,\n TEXTURE = 0x1702,\n TEXTURE_CUBE_MAP = 0x8513,\n TEXTURE_BINDING_CUBE_MAP = 0x8514,\n TEXTURE_CUBE_MAP_POSITIVE_X = 0x8515,\n TEXTURE_CUBE_MAP_NEGATIVE_X = 0x8516,\n TEXTURE_CUBE_MAP_POSITIVE_Y = 0x8517,\n TEXTURE_CUBE_MAP_NEGATIVE_Y = 0x8518,\n TEXTURE_CUBE_MAP_POSITIVE_Z = 0x8519,\n TEXTURE_CUBE_MAP_NEGATIVE_Z = 0x851a,\n MAX_CUBE_MAP_TEXTURE_SIZE = 0x851c,\n // TEXTURE0 - 31 0x84C0 - 0x84DF A texture unit.\n TEXTURE0 = 0x84c0,\n ACTIVE_TEXTURE = 0x84e0,\n REPEAT = 0x2901,\n CLAMP_TO_EDGE = 0x812f,\n MIRRORED_REPEAT = 0x8370,\n\n // Emulation\n TEXTURE_WIDTH = 0x1000,\n TEXTURE_HEIGHT = 0x1001,\n\n // Uniform types\n\n FLOAT_VEC2 = 0x8b50,\n FLOAT_VEC3 = 0x8b51,\n FLOAT_VEC4 = 0x8b52,\n INT_VEC2 = 0x8b53,\n INT_VEC3 = 0x8b54,\n INT_VEC4 = 0x8b55,\n BOOL = 0x8b56,\n BOOL_VEC2 = 0x8b57,\n BOOL_VEC3 = 0x8b58,\n BOOL_VEC4 = 0x8b59,\n FLOAT_MAT2 = 0x8b5a,\n FLOAT_MAT3 = 0x8b5b,\n FLOAT_MAT4 = 0x8b5c,\n SAMPLER_2D = 0x8b5e,\n SAMPLER_CUBE = 0x8b60,\n\n // Shader precision-specified types\n\n LOW_FLOAT = 0x8df0,\n MEDIUM_FLOAT = 0x8df1,\n HIGH_FLOAT = 0x8df2,\n LOW_INT = 0x8df3,\n MEDIUM_INT = 0x8df4,\n HIGH_INT = 0x8df5,\n\n // Framebuffers and renderbuffers\n\n FRAMEBUFFER = 0x8d40,\n RENDERBUFFER = 0x8d41,\n RGBA4 = 0x8056,\n RGB5_A1 = 0x8057,\n RGB565 = 0x8d62,\n DEPTH_COMPONENT16 = 0x81a5,\n STENCIL_INDEX = 0x1901,\n STENCIL_INDEX8 = 0x8d48,\n DEPTH_STENCIL = 0x84f9,\n RENDERBUFFER_WIDTH = 0x8d42,\n RENDERBUFFER_HEIGHT = 0x8d43,\n RENDERBUFFER_INTERNAL_FORMAT = 0x8d44,\n RENDERBUFFER_RED_SIZE = 0x8d50,\n RENDERBUFFER_GREEN_SIZE = 0x8d51,\n RENDERBUFFER_BLUE_SIZE = 0x8d52,\n RENDERBUFFER_ALPHA_SIZE = 0x8d53,\n RENDERBUFFER_DEPTH_SIZE = 0x8d54,\n RENDERBUFFER_STENCIL_SIZE = 0x8d55,\n FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = 0x8cd0,\n FRAMEBUFFER_ATTACHMENT_OBJECT_NAME = 0x8cd1,\n FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL = 0x8cd2,\n FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE = 0x8cd3,\n COLOR_ATTACHMENT0 = 0x8ce0,\n DEPTH_ATTACHMENT = 0x8d00,\n STENCIL_ATTACHMENT = 0x8d20,\n DEPTH_STENCIL_ATTACHMENT = 0x821a,\n NONE = 0,\n FRAMEBUFFER_COMPLETE = 0x8cd5,\n FRAMEBUFFER_INCOMPLETE_ATTACHMENT = 0x8cd6,\n FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = 0x8cd7,\n FRAMEBUFFER_INCOMPLETE_DIMENSIONS = 0x8cd9,\n FRAMEBUFFER_UNSUPPORTED = 0x8cdd,\n FRAMEBUFFER_BINDING = 0x8ca6,\n RENDERBUFFER_BINDING = 0x8ca7,\n READ_FRAMEBUFFER = 0x8ca8,\n DRAW_FRAMEBUFFER = 0x8ca9,\n MAX_RENDERBUFFER_SIZE = 0x84e8,\n INVALID_FRAMEBUFFER_OPERATION = 0x0506,\n\n // Pixel storage modes\n // Constants passed to pixelStorei().\n\n UNPACK_FLIP_Y_WEBGL = 0x9240,\n UNPACK_PREMULTIPLY_ALPHA_WEBGL = 0x9241,\n UNPACK_COLORSPACE_CONVERSION_WEBGL = 0x9243,\n\n // Additional constants defined WebGL 2\n // These constants are defined on the WebGL2RenderingContext interface.\n // All WebGL 1 constants are also available in a WebGL 2 context.\n\n // Getting GL parameter information\n // Constants passed to getParameter()\n // to specify what information to return.\n\n READ_BUFFER = 0x0c02,\n UNPACK_ROW_LENGTH = 0x0cf2,\n UNPACK_SKIP_ROWS = 0x0cf3,\n UNPACK_SKIP_PIXELS = 0x0cf4,\n PACK_ROW_LENGTH = 0x0d02,\n PACK_SKIP_ROWS = 0x0d03,\n PACK_SKIP_PIXELS = 0x0d04,\n TEXTURE_BINDING_3D = 0x806a,\n UNPACK_SKIP_IMAGES = 0x806d,\n UNPACK_IMAGE_HEIGHT = 0x806e,\n MAX_3D_TEXTURE_SIZE = 0x8073,\n MAX_ELEMENTS_VERTICES = 0x80e8,\n MAX_ELEMENTS_INDICES = 0x80e9,\n MAX_TEXTURE_LOD_BIAS = 0x84fd,\n MAX_FRAGMENT_UNIFORM_COMPONENTS = 0x8b49,\n MAX_VERTEX_UNIFORM_COMPONENTS = 0x8b4a,\n MAX_ARRAY_TEXTURE_LAYERS = 0x88ff,\n MIN_PROGRAM_TEXEL_OFFSET = 0x8904,\n MAX_PROGRAM_TEXEL_OFFSET = 0x8905,\n MAX_VARYING_COMPONENTS = 0x8b4b,\n FRAGMENT_SHADER_DERIVATIVE_HINT = 0x8b8b,\n RASTERIZER_DISCARD = 0x8c89,\n VERTEX_ARRAY_BINDING = 0x85b5,\n MAX_VERTEX_OUTPUT_COMPONENTS = 0x9122,\n MAX_FRAGMENT_INPUT_COMPONENTS = 0x9125,\n MAX_SERVER_WAIT_TIMEOUT = 0x9111,\n MAX_ELEMENT_INDEX = 0x8d6b,\n\n // Textures\n // Constants passed to texParameteri(),\n // texParameterf(), bindTexture(), texImage2D(), and others.\n\n RED = 0x1903,\n RGB8 = 0x8051,\n RGBA8 = 0x8058,\n RGB10_A2 = 0x8059,\n TEXTURE_3D = 0x806f,\n /** Sets the wrap parameter for texture coordinate to either GL_CLAMP_TO_EDGE, GL_MIRRORED_REPEAT, or GL_REPEAT. G */\n TEXTURE_WRAP_R = 0x8072,\n TEXTURE_MIN_LOD = 0x813a,\n TEXTURE_MAX_LOD = 0x813b,\n TEXTURE_BASE_LEVEL = 0x813c,\n TEXTURE_MAX_LEVEL = 0x813d,\n TEXTURE_COMPARE_MODE = 0x884c,\n TEXTURE_COMPARE_FUNC = 0x884d,\n SRGB = 0x8c40,\n SRGB8 = 0x8c41,\n SRGB8_ALPHA8 = 0x8c43,\n COMPARE_REF_TO_TEXTURE = 0x884e,\n RGBA32F = 0x8814,\n RGB32F = 0x8815,\n RGBA16F = 0x881a,\n RGB16F = 0x881b,\n TEXTURE_2D_ARRAY = 0x8c1a,\n TEXTURE_BINDING_2D_ARRAY = 0x8c1d,\n R11F_G11F_B10F = 0x8c3a,\n RGB9_E5 = 0x8c3d,\n RGBA32UI = 0x8d70,\n RGB32UI = 0x8d71,\n RGBA16UI = 0x8d76,\n RGB16UI = 0x8d77,\n RGBA8UI = 0x8d7c,\n RGB8UI = 0x8d7d,\n RGBA32I = 0x8d82,\n RGB32I = 0x8d83,\n RGBA16I = 0x8d88,\n RGB16I = 0x8d89,\n RGBA8I = 0x8d8e,\n RGB8I = 0x8d8f,\n RED_INTEGER = 0x8d94,\n RGB_INTEGER = 0x8d98,\n RGBA_INTEGER = 0x8d99,\n R8 = 0x8229,\n RG8 = 0x822b,\n R16F = 0x822d,\n R32F = 0x822e,\n RG16F = 0x822f,\n RG32F = 0x8230,\n R8I = 0x8231,\n R8UI = 0x8232,\n R16I = 0x8233,\n R16UI = 0x8234,\n R32I = 0x8235,\n R32UI = 0x8236,\n RG8I = 0x8237,\n RG8UI = 0x8238,\n RG16I = 0x8239,\n RG16UI = 0x823a,\n RG32I = 0x823b,\n RG32UI = 0x823c,\n R8_SNORM = 0x8f94,\n RG8_SNORM = 0x8f95,\n RGB8_SNORM = 0x8f96,\n RGBA8_SNORM = 0x8f97,\n RGB10_A2UI = 0x906f,\n\n /* covered by extension\n COMPRESSED_R11_EAC = 0x9270,\n COMPRESSED_SIGNED_R11_EAC = 0x9271,\n COMPRESSED_RG11_EAC = 0x9272,\n COMPRESSED_SIGNED_RG11_EAC = 0x9273,\n COMPRESSED_RGB8_ETC2 = 0x9274,\n COMPRESSED_SRGB8_ETC2 = 0x9275,\n COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9276,\n COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC = 0x9277,\n COMPRESSED_RGBA8_ETC2_EAC = 0x9278,\n COMPRESSED_SRGB8_ALPHA8_ETC2_EAC = 0x9279,\n */\n TEXTURE_IMMUTABLE_FORMAT = 0x912f,\n TEXTURE_IMMUTABLE_LEVELS = 0x82df,\n\n // Pixel types\n\n UNSIGNED_INT_2_10_10_10_REV = 0x8368,\n UNSIGNED_INT_10F_11F_11F_REV = 0x8c3b,\n UNSIGNED_INT_5_9_9_9_REV = 0x8c3e,\n FLOAT_32_UNSIGNED_INT_24_8_REV = 0x8dad,\n UNSIGNED_INT_24_8 = 0x84fa,\n HALF_FLOAT = 0x140b,\n RG = 0x8227,\n RG_INTEGER = 0x8228,\n INT_2_10_10_10_REV = 0x8d9f,\n\n // Queries\n\n CURRENT_QUERY = 0x8865,\n /** Returns a GLuint containing the query result. */\n QUERY_RESULT = 0x8866,\n /** Whether query result is available. */\n QUERY_RESULT_AVAILABLE = 0x8867,\n /** Occlusion query (if drawing passed depth test) */\n ANY_SAMPLES_PASSED = 0x8c2f,\n /** Occlusion query less accurate/faster version */\n ANY_SAMPLES_PASSED_CONSERVATIVE = 0x8d6a,\n\n // Draw buffers\n\n MAX_DRAW_BUFFERS = 0x8824,\n DRAW_BUFFER0 = 0x8825,\n DRAW_BUFFER1 = 0x8826,\n DRAW_BUFFER2 = 0x8827,\n DRAW_BUFFER3 = 0x8828,\n DRAW_BUFFER4 = 0x8829,\n DRAW_BUFFER5 = 0x882a,\n DRAW_BUFFER6 = 0x882b,\n DRAW_BUFFER7 = 0x882c,\n DRAW_BUFFER8 = 0x882d,\n DRAW_BUFFER9 = 0x882e,\n DRAW_BUFFER10 = 0x882f,\n DRAW_BUFFER11 = 0x8830,\n DRAW_BUFFER12 = 0x8831,\n DRAW_BUFFER13 = 0x8832,\n DRAW_BUFFER14 = 0x8833,\n DRAW_BUFFER15 = 0x8834,\n MAX_COLOR_ATTACHMENTS = 0x8cdf,\n COLOR_ATTACHMENT1 = 0x8ce1,\n COLOR_ATTACHMENT2 = 0x8ce2,\n COLOR_ATTACHMENT3 = 0x8ce3,\n COLOR_ATTACHMENT4 = 0x8ce4,\n COLOR_ATTACHMENT5 = 0x8ce5,\n COLOR_ATTACHMENT6 = 0x8ce6,\n COLOR_ATTACHMENT7 = 0x8ce7,\n COLOR_ATTACHMENT8 = 0x8ce8,\n COLOR_ATTACHMENT9 = 0x8ce9,\n COLOR_ATTACHMENT10 = 0x8cea,\n COLOR_ATTACHMENT11 = 0x8ceb,\n COLOR_ATTACHMENT12 = 0x8cec,\n COLOR_ATTACHMENT13 = 0x8ced,\n COLOR_ATTACHMENT14 = 0x8cee,\n COLOR_ATTACHMENT15 = 0x8cef,\n\n // Samplers\n\n SAMPLER_3D = 0x8b5f,\n SAMPLER_2D_SHADOW = 0x8b62,\n SAMPLER_2D_ARRAY = 0x8dc1,\n SAMPLER_2D_ARRAY_SHADOW = 0x8dc4,\n SAMPLER_CUBE_SHADOW = 0x8dc5,\n INT_SAMPLER_2D = 0x8dca,\n INT_SAMPLER_3D = 0x8dcb,\n INT_SAMPLER_CUBE = 0x8dcc,\n INT_SAMPLER_2D_ARRAY = 0x8dcf,\n UNSIGNED_INT_SAMPLER_2D = 0x8dd2,\n UNSIGNED_INT_SAMPLER_3D = 0x8dd3,\n UNSIGNED_INT_SAMPLER_CUBE = 0x8dd4,\n UNSIGNED_INT_SAMPLER_2D_ARRAY = 0x8dd7,\n MAX_SAMPLES = 0x8d57,\n SAMPLER_BINDING = 0x8919,\n\n // Buffers\n\n PIXEL_PACK_BUFFER = 0x88eb,\n PIXEL_UNPACK_BUFFER = 0x88ec,\n PIXEL_PACK_BUFFER_BINDING = 0x88ed,\n PIXEL_UNPACK_BUFFER_BINDING = 0x88ef,\n COPY_READ_BUFFER = 0x8f36,\n COPY_WRITE_BUFFER = 0x8f37,\n COPY_READ_BUFFER_BINDING = 0x8f36,\n COPY_WRITE_BUFFER_BINDING = 0x8f37,\n\n // Data types\n\n FLOAT_MAT2x3 = 0x8b65,\n FLOAT_MAT2x4 = 0x8b66,\n FLOAT_MAT3x2 = 0x8b67,\n FLOAT_MAT3x4 = 0x8b68,\n FLOAT_MAT4x2 = 0x8b69,\n FLOAT_MAT4x3 = 0x8b6a,\n UNSIGNED_INT_VEC2 = 0x8dc6,\n UNSIGNED_INT_VEC3 = 0x8dc7,\n UNSIGNED_INT_VEC4 = 0x8dc8,\n UNSIGNED_NORMALIZED = 0x8c17,\n SIGNED_NORMALIZED = 0x8f9c,\n\n // Vertex attributes\n\n VERTEX_ATTRIB_ARRAY_INTEGER = 0x88fd,\n VERTEX_ATTRIB_ARRAY_DIVISOR = 0x88fe,\n\n // Transform feedback\n\n TRANSFORM_FEEDBACK_BUFFER_MODE = 0x8c7f,\n MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS = 0x8c80,\n TRANSFORM_FEEDBACK_VARYINGS = 0x8c83,\n TRANSFORM_FEEDBACK_BUFFER_START = 0x8c84,\n TRANSFORM_FEEDBACK_BUFFER_SIZE = 0x8c85,\n TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN = 0x8c88,\n MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS = 0x8c8a,\n MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS = 0x8c8b,\n INTERLEAVED_ATTRIBS = 0x8c8c,\n SEPARATE_ATTRIBS = 0x8c8d,\n TRANSFORM_FEEDBACK_BUFFER = 0x8c8e,\n TRANSFORM_FEEDBACK_BUFFER_BINDING = 0x8c8f,\n TRANSFORM_FEEDBACK = 0x8e22,\n TRANSFORM_FEEDBACK_PAUSED = 0x8e23,\n TRANSFORM_FEEDBACK_ACTIVE = 0x8e24,\n TRANSFORM_FEEDBACK_BINDING = 0x8e25,\n\n // Framebuffers and renderbuffers\n\n FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING = 0x8210,\n FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE = 0x8211,\n FRAMEBUFFER_ATTACHMENT_RED_SIZE = 0x8212,\n FRAMEBUFFER_ATTACHMENT_GREEN_SIZE = 0x8213,\n FRAMEBUFFER_ATTACHMENT_BLUE_SIZE = 0x8214,\n FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE = 0x8215,\n FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE = 0x8216,\n FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE = 0x8217,\n FRAMEBUFFER_DEFAULT = 0x8218,\n // DEPTH_STENCIL_ATTACHMENT = 0x821A,\n // DEPTH_STENCIL = 0x84F9,\n DEPTH24_STENCIL8 = 0x88f0,\n DRAW_FRAMEBUFFER_BINDING = 0x8ca6,\n READ_FRAMEBUFFER_BINDING = 0x8caa,\n RENDERBUFFER_SAMPLES = 0x8cab,\n FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER = 0x8cd4,\n FRAMEBUFFER_INCOMPLETE_MULTISAMPLE = 0x8d56,\n\n // Uniforms\n\n UNIFORM_BUFFER = 0x8a11,\n UNIFORM_BUFFER_BINDING = 0x8a28,\n UNIFORM_BUFFER_START = 0x8a29,\n UNIFORM_BUFFER_SIZE = 0x8a2a,\n MAX_VERTEX_UNIFORM_BLOCKS = 0x8a2b,\n MAX_FRAGMENT_UNIFORM_BLOCKS = 0x8a2d,\n MAX_COMBINED_UNIFORM_BLOCKS = 0x8a2e,\n MAX_UNIFORM_BUFFER_BINDINGS = 0x8a2f,\n MAX_UNIFORM_BLOCK_SIZE = 0x8a30,\n MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS = 0x8a31,\n MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS = 0x8a33,\n UNIFORM_BUFFER_OFFSET_ALIGNMENT = 0x8a34,\n ACTIVE_UNIFORM_BLOCKS = 0x8a36,\n UNIFORM_TYPE = 0x8a37,\n UNIFORM_SIZE = 0x8a38,\n UNIFORM_BLOCK_INDEX = 0x8a3a,\n UNIFORM_OFFSET = 0x8a3b,\n UNIFORM_ARRAY_STRIDE = 0x8a3c,\n UNIFORM_MATRIX_STRIDE = 0x8a3d,\n UNIFORM_IS_ROW_MAJOR = 0x8a3e,\n UNIFORM_BLOCK_BINDING = 0x8a3f,\n UNIFORM_BLOCK_DATA_SIZE = 0x8a40,\n UNIFORM_BLOCK_ACTIVE_UNIFORMS = 0x8a42,\n UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES = 0x8a43,\n UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER = 0x8a44,\n UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER = 0x8a46,\n\n // Sync objects\n\n OBJECT_TYPE = 0x9112,\n SYNC_CONDITION = 0x9113,\n SYNC_STATUS = 0x9114,\n SYNC_FLAGS = 0x9115,\n SYNC_FENCE = 0x9116,\n SYNC_GPU_COMMANDS_COMPLETE = 0x9117,\n UNSIGNALED = 0x9118,\n SIGNALED = 0x9119,\n ALREADY_SIGNALED = 0x911a,\n TIMEOUT_EXPIRED = 0x911b,\n CONDITION_SATISFIED = 0x911c,\n WAIT_FAILED = 0x911d,\n SYNC_FLUSH_COMMANDS_BIT = 0x00000001,\n\n // Miscellaneous constants\n\n COLOR = 0x1800,\n DEPTH = 0x1801,\n STENCIL = 0x1802,\n MIN = 0x8007,\n MAX = 0x8008,\n DEPTH_COMPONENT24 = 0x81a6,\n STREAM_READ = 0x88e1,\n STREAM_COPY = 0x88e2,\n STATIC_READ = 0x88e5,\n STATIC_COPY = 0x88e6,\n DYNAMIC_READ = 0x88e9,\n DYNAMIC_COPY = 0x88ea,\n DEPTH_COMPONENT32F = 0x8cac,\n DEPTH32F_STENCIL8 = 0x8cad,\n INVALID_INDEX = 0xffffffff,\n TIMEOUT_IGNORED = -1,\n MAX_CLIENT_WAIT_TIMEOUT_WEBGL = 0x9247,\n\n // Constants defined in WebGL extensions\n\n // WEBGL_debug_renderer_info\n\n /** Passed to getParameter to get the vendor string of the graphics driver. */\n UNMASKED_VENDOR_WEBGL = 0x9245,\n /** Passed to getParameter to get the renderer string of the graphics driver. */\n UNMASKED_RENDERER_WEBGL = 0x9246,\n\n // EXT_texture_filter_anisotropic\n\n /** Returns the maximum available anisotropy. */\n MAX_TEXTURE_MAX_ANISOTROPY_EXT = 0x84ff,\n /** Passed to texParameter to set the desired maximum anisotropy for a texture. */\n TEXTURE_MAX_ANISOTROPY_EXT = 0x84fe,\n\n // EXT_texture_norm16 - https://khronos.org/registry/webgl/extensions/EXT_texture_norm16/\n\n R16_EXT = 0x822a,\n RG16_EXT = 0x822c,\n RGB16_EXT = 0x8054,\n RGBA16_EXT = 0x805b,\n R16_SNORM_EXT = 0x8f98,\n RG16_SNORM_EXT = 0x8f99,\n RGB16_SNORM_EXT = 0x8f9a,\n RGBA16_SNORM_EXT = 0x8f9b,\n\n // WEBGL_compressed_texture_s3tc (BC1, BC2, BC3)\n\n /** A DXT1-compressed image in an RGB image format. */\n COMPRESSED_RGB_S3TC_DXT1_EXT = 0x83f0,\n /** A DXT1-compressed image in an RGB image format with a simple on/off alpha value. */\n COMPRESSED_RGBA_S3TC_DXT1_EXT = 0x83f1,\n /** A DXT3-compressed image in an RGBA image format. Compared to a 32-bit RGBA texture, it offers 4:1 compression. */\n COMPRESSED_RGBA_S3TC_DXT3_EXT = 0x83f2,\n /** A DXT5-compressed image in an RGBA image format. It also provides a 4:1 compression, but differs to the DXT3 compression in how the alpha compression is done. */\n COMPRESSED_RGBA_S3TC_DXT5_EXT = 0x83f3,\n\n // WEBGL_compressed_texture_s3tc_srgb (BC1, BC2, BC3 - SRGB)\n\n COMPRESSED_SRGB_S3TC_DXT1_EXT = 0x8c4c,\n COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT = 0x8c4d,\n COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT = 0x8c4e,\n COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT = 0x8c4f,\n\n // WEBGL_compressed_texture_rgtc (BC4, BC5)\n\n COMPRESSED_RED_RGTC1_EXT = 0x8dbb,\n COMPRESSED_SIGNED_RED_RGTC1_EXT = 0x8dbc,\n COMPRESSED_RED_GREEN_RGTC2_EXT = 0x8dbd,\n COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT = 0x8dbe,\n\n // WEBGL_compressed_texture_bptc (BC6, BC7)\n\n COMPRESSED_RGBA_BPTC_UNORM_EXT = 0x8e8c,\n COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT = 0x8e8d,\n COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT = 0x8e8e,\n COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT = 0x8e8f,\n\n // WEBGL_compressed_texture_es3\n\n /** One-channel (red) unsigned format compression. */\n COMPRESSED_R11_EAC = 0x9270,\n /** One-channel (red) signed format compression. */\n COMPRESSED_SIGNED_R11_EAC = 0x9271,\n /** Two-channel (red and green) unsigned format compression. */\n COMPRESSED_RG11_EAC = 0x9272,\n /** Two-channel (red and green) signed format compression. */\n COMPRESSED_SIGNED_RG11_EAC = 0x9273,\n /** Compresses RGB8 data with no alpha channel. */\n COMPRESSED_RGB8_ETC2 = 0x9274,\n /** Compresses RGBA8 data. The RGB part is encoded the same as RGB_ETC2, but the alpha part is encoded separately. */\n COMPRESSED_RGBA8_ETC2_EAC = 0x9275,\n /** Compresses sRGB8 data with no alpha channel. */\n COMPRESSED_SRGB8_ETC2 = 0x9276,\n /** Compresses sRGBA8 data. The sRGB part is encoded the same as SRGB_ETC2, but the alpha part is encoded separately. */\n COMPRESSED_SRGB8_ALPHA8_ETC2_EAC = 0x9277,\n /** Similar to RGB8_ETC, but with ability to punch through the alpha channel, which means to make it completely opaque or transparent. */\n COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9278,\n /** Similar to SRGB8_ETC, but with ability to punch through the alpha channel, which means to make it completely opaque or transparent. */\n COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9279,\n\n // WEBGL_compressed_texture_pvrtc\n\n /** RGB compression in 4-bit mode. One block for each 4×4 pixels. */\n COMPRESSED_RGB_PVRTC_4BPPV1_IMG = 0x8c00,\n /** RGBA compression in 4-bit mode. One block for each 4×4 pixels. */\n COMPRESSED_RGBA_PVRTC_4BPPV1_IMG = 0x8c02,\n /** RGB compression in 2-bit mode. One block for each 8×4 pixels. */\n COMPRESSED_RGB_PVRTC_2BPPV1_IMG = 0x8c01,\n /** RGBA compression in 2-bit mode. One block for each 8×4 pixels. */\n COMPRESSED_RGBA_PVRTC_2BPPV1_IMG = 0x8c03,\n\n // WEBGL_compressed_texture_etc1\n\n /** Compresses 24-bit RGB data with no alpha channel. */\n COMPRESSED_RGB_ETC1_WEBGL = 0x8d64,\n\n // WEBGL_compressed_texture_atc\n\n COMPRESSED_RGB_ATC_WEBGL = 0x8c92,\n COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL = 0x8c92,\n COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL = 0x87ee,\n\n // WEBGL_compressed_texture_astc\n\n COMPRESSED_RGBA_ASTC_4x4_KHR = 0x93b0,\n COMPRESSED_RGBA_ASTC_5x4_KHR = 0x93b1,\n COMPRESSED_RGBA_ASTC_5x5_KHR = 0x93b2,\n COMPRESSED_RGBA_ASTC_6x5_KHR = 0x93b3,\n COMPRESSED_RGBA_ASTC_6x6_KHR = 0x93b4,\n COMPRESSED_RGBA_ASTC_8x5_KHR = 0x93b5,\n COMPRESSED_RGBA_ASTC_8x6_KHR = 0x93b6,\n COMPRESSED_RGBA_ASTC_8x8_KHR = 0x93b7,\n COMPRESSED_RGBA_ASTC_10x5_KHR = 0x93b8,\n COMPRESSED_RGBA_ASTC_10x6_KHR = 0x93b9,\n COMPRESSED_RGBA_ASTC_10x8_KHR = 0x93ba,\n COMPRESSED_RGBA_ASTC_10x10_KHR = 0x93bb,\n COMPRESSED_RGBA_ASTC_12x10_KHR = 0x93bc,\n COMPRESSED_RGBA_ASTC_12x12_KHR = 0x93bd,\n COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR = 0x93d0,\n COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR = 0x93d1,\n COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR = 0x93d2,\n COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR = 0x93d3,\n COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR = 0x93d4,\n COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR = 0x93d5,\n COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR = 0x93d6,\n COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR = 0x93d7,\n COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR = 0x93d8,\n COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR = 0x93d9,\n COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR = 0x93da,\n COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR = 0x93db,\n COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR = 0x93dc,\n COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR = 0x93dd,\n\n // EXT_disjoint_timer_query\n\n /** The number of bits used to hold the query result for the given target. */\n QUERY_COUNTER_BITS_EXT = 0x8864,\n /** The currently active query. */\n CURRENT_QUERY_EXT = 0x8865,\n /** The query result. */\n QUERY_RESULT_EXT = 0x8866,\n /** A Boolean indicating whether or not a query result is available. */\n QUERY_RESULT_AVAILABLE_EXT = 0x8867,\n /** Elapsed time (in nanoseconds). */\n TIME_ELAPSED_EXT = 0x88bf,\n /** The current time. */\n TIMESTAMP_EXT = 0x8e28,\n /** A Boolean indicating whether or not the GPU performed any disjoint operation (lost context) */\n GPU_DISJOINT_EXT = 0x8fbb,\n\n // KHR_parallel_shader_compile https://registry.khronos.org/webgl/extensions/KHR_parallel_shader_compile\n\n /** a non-blocking poll operation, so that compile/link status availability can be queried without potentially incurring stalls */\n COMPLETION_STATUS_KHR = 0x91b1,\n\n // EXT_depth_clamp https://registry.khronos.org/webgl/extensions/EXT_depth_clamp/\n\n /** Disables depth clipping */\n DEPTH_CLAMP_EXT = 0x864f,\n\n // WEBGL_provoking_vertex https://registry.khronos.org/webgl/extensions/WEBGL_provoking_vertex/\n\n /** Values of first vertex in primitive are used for flat shading */\n FIRST_VERTEX_CONVENTION_WEBGL = 0x8e4d,\n /** Values of first vertex in primitive are used for flat shading */\n LAST_VERTEX_CONVENTION_WEBGL = 0x8e4e, // default\n /** Controls which vertex in primitive is used for flat shading */\n PROVOKING_VERTEX_WEBL = 0x8e4f,\n\n // WEBGL_polygon_mode https://registry.khronos.org/webgl/extensions/WEBGL_polygon_mode/\n\n POLYGON_MODE_WEBGL = 0x0b40,\n POLYGON_OFFSET_LINE_WEBGL = 0x2a02,\n LINE_WEBGL = 0x1b01,\n FILL_WEBGL = 0x1b02,\n\n // WEBGL_clip_cull_distance https://registry.khronos.org/webgl/extensions/WEBGL_clip_cull_distance/\n\n /** Max clip distances */\n MAX_CLIP_DISTANCES_WEBGL = 0x0d32,\n /** Max cull distances */\n MAX_CULL_DISTANCES_WEBGL = 0x82f9,\n /** Max clip and cull distances */\n MAX_COMBINED_CLIP_AND_CULL_DISTANCES_WEBGL = 0x82fa,\n\n /** Enable gl_ClipDistance[0] and gl_CullDistance[0] */\n CLIP_DISTANCE0_WEBGL = 0x3000,\n /** Enable gl_ClipDistance[1] and gl_CullDistance[1] */\n CLIP_DISTANCE1_WEBGL = 0x3001,\n /** Enable gl_ClipDistance[2] and gl_CullDistance[2] */\n CLIP_DISTANCE2_WEBGL = 0x3002,\n /** Enable gl_ClipDistance[3] and gl_CullDistance[3] */\n CLIP_DISTANCE3_WEBGL = 0x3003,\n /** Enable gl_ClipDistance[4] and gl_CullDistance[4] */\n CLIP_DISTANCE4_WEBGL = 0x3004,\n /** Enable gl_ClipDistance[5] and gl_CullDistance[5] */\n CLIP_DISTANCE5_WEBGL = 0x3005,\n /** Enable gl_ClipDistance[6] and gl_CullDistance[6] */\n CLIP_DISTANCE6_WEBGL = 0x3006,\n /** Enable gl_ClipDistance[7] and gl_CullDistance[7] */\n CLIP_DISTANCE7_WEBGL = 0x3007,\n\n /** EXT_polygon_offset_clamp https://registry.khronos.org/webgl/extensions/EXT_polygon_offset_clamp/ */\n POLYGON_OFFSET_CLAMP_EXT = 0x8e1b,\n\n /** EXT_clip_control https://registry.khronos.org/webgl/extensions/EXT_clip_control/ */\n LOWER_LEFT_EXT = 0x8ca1,\n UPPER_LEFT_EXT = 0x8ca2,\n\n NEGATIVE_ONE_TO_ONE_EXT = 0x935e,\n ZERO_TO_ONE_EXT = 0x935f,\n\n CLIP_ORIGIN_EXT = 0x935c,\n CLIP_DEPTH_MODE_EXT = 0x935d,\n\n /** WEBGL_blend_func_extended https://registry.khronos.org/webgl/extensions/WEBGL_blend_func_extended/ */\n SRC1_COLOR_WEBGL = 0x88f9,\n SRC1_ALPHA_WEBGL = 0x8589,\n ONE_MINUS_SRC1_COLOR_WEBGL = 0x88fa,\n ONE_MINUS_SRC1_ALPHA_WEBGL = 0x88fb,\n MAX_DUAL_SOURCE_DRAW_BUFFERS_WEBGL = 0x88fc,\n\n /** EXT_texture_mirror_clamp_to_edge https://registry.khronos.org/webgl/extensions/EXT_texture_mirror_clamp_to_edge/ */\n MIRROR_CLAMP_TO_EDGE_EXT = 0x8743\n}\n\nexport {GLEnum as GL};\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport {GL} from './webgl-constants';\n\nexport type {\n GLTextureTarget,\n GLTextureCubeMapTarget,\n GLTexelDataFormat,\n GLPrimitiveTopology,\n GLPrimitive,\n GLDataType,\n GLPixelType,\n GLUniformType,\n GLSamplerType,\n GLFunction,\n GLBlendEquation,\n GLBlendFunction,\n GLStencilOp,\n GLSamplerParameters,\n GLValueParameters,\n GLPackParameters,\n GLUnpackParameters,\n GLFunctionParameters,\n GLParameters,\n GLLimits,\n GLExtensions,\n GLPolygonMode,\n GLProvokingVertex\n} from './webgl-types';\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// Goal is to make WebGL2 contexts look like WebGL1\n// @note Partly inspired by with some older code from the `regl` library\n\n/* eslint-disable camelcase */\n\nimport {GL} from '@luma.gl/webgl/constants';\n\n// webgl1 extensions natively supported by webgl2\nconst WEBGL1_STATIC_EXTENSIONS = {\n WEBGL_depth_texture: {\n UNSIGNED_INT_24_8_WEBGL: GL.UNSIGNED_INT_24_8\n } as const satisfies WEBGL_depth_texture,\n OES_element_index_uint: {} as const satisfies OES_element_index_uint,\n OES_texture_float: {} as const satisfies OES_texture_float,\n OES_texture_half_float: {\n // @ts-expect-error different numbers?\n HALF_FLOAT_OES: GL.HALF_FLOAT\n } as const satisfies OES_texture_half_float,\n EXT_color_buffer_float: {} as const satisfies EXT_color_buffer_float,\n OES_standard_derivatives: {\n FRAGMENT_SHADER_DERIVATIVE_HINT_OES: GL.FRAGMENT_SHADER_DERIVATIVE_HINT\n } as const satisfies OES_standard_derivatives,\n EXT_frag_depth: {} as const satisfies EXT_frag_depth,\n EXT_blend_minmax: {\n MIN_EXT: GL.MIN,\n MAX_EXT: GL.MAX\n } as const satisfies EXT_blend_minmax,\n EXT_shader_texture_lod: {} as const satisfies EXT_shader_texture_lod\n};\n\nconst getWEBGL_draw_buffers = (gl: WebGL2RenderingContext) =>\n ({\n drawBuffersWEBGL(buffers: number[]) {\n return gl.drawBuffers(buffers);\n },\n COLOR_ATTACHMENT0_WEBGL: GL.COLOR_ATTACHMENT0,\n COLOR_ATTACHMENT1_WEBGL: GL.COLOR_ATTACHMENT1,\n COLOR_ATTACHMENT2_WEBGL: GL.COLOR_ATTACHMENT2,\n COLOR_ATTACHMENT3_WEBGL: GL.COLOR_ATTACHMENT3\n }) as const satisfies Partial; // - too many fields\n\nconst getOES_vertex_array_object = (gl: WebGL2RenderingContext) =>\n ({\n VERTEX_ARRAY_BINDING_OES: GL.VERTEX_ARRAY_BINDING,\n createVertexArrayOES() {\n return gl.createVertexArray();\n },\n deleteVertexArrayOES(vertexArray: WebGLVertexArrayObject): void {\n return gl.deleteVertexArray(vertexArray);\n },\n isVertexArrayOES(vertexArray: WebGLVertexArrayObject): boolean {\n return gl.isVertexArray(vertexArray);\n },\n bindVertexArrayOES(vertexArray: WebGLVertexArrayObject): void {\n return gl.bindVertexArray(vertexArray);\n }\n }) as const satisfies OES_vertex_array_object;\n\nconst getANGLE_instanced_arrays = (gl: WebGL2RenderingContext) =>\n ({\n VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: 0x88fe,\n drawArraysInstancedANGLE(...args) {\n return gl.drawArraysInstanced(...args);\n },\n drawElementsInstancedANGLE(...args) {\n return gl.drawElementsInstanced(...args);\n },\n vertexAttribDivisorANGLE(...args) {\n return gl.vertexAttribDivisor(...args);\n }\n }) as const satisfies ANGLE_instanced_arrays;\n\n/**\n * Make browser return WebGL2 contexts even if WebGL1 contexts are requested\n * @param enforce\n * @returns\n */\nexport function enforceWebGL2(enforce: boolean = true): void {\n const prototype = HTMLCanvasElement.prototype as any;\n if (!enforce && prototype.originalGetContext) {\n // Reset the original getContext function\n prototype.getContext = prototype.originalGetContext;\n prototype.originalGetContext = undefined;\n return;\n }\n\n // Store the original getContext function\n prototype.originalGetContext = prototype.getContext;\n\n // Override the getContext function\n prototype.getContext = function (contextId: string, options?: WebGLContextAttributes) {\n // Attempt to force WebGL2 for all WebGL1 contexts\n if (contextId === 'webgl' || contextId === 'experimental-webgl') {\n const context = this.originalGetContext('webgl2', options) as WebGL2RenderingContext;\n // Work around test mocking\n if (context instanceof HTMLElement) {\n polyfillWebGL1Extensions(context);\n }\n return context;\n }\n // For any other type, return the original context\n return this.originalGetContext(contextId, options);\n };\n}\n\n/** Install WebGL1-only extensions on WebGL2 contexts */\nexport function polyfillWebGL1Extensions(gl: WebGL2RenderingContext): void {\n // Enable, to support float and half-float textures\n gl.getExtension('EXT_color_buffer_float');\n\n // WebGL1 extensions implemented using WebGL2 APIs\n const boundExtensions = {\n ...WEBGL1_STATIC_EXTENSIONS,\n WEBGL_disjoint_timer_query: gl.getExtension('EXT_disjoint_timer_query_webgl2'),\n WEBGL_draw_buffers: getWEBGL_draw_buffers(gl),\n OES_vertex_array_object: getOES_vertex_array_object(gl),\n ANGLE_instanced_arrays: getANGLE_instanced_arrays(gl)\n };\n\n // Override gl.getExtension\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalGetExtension = gl.getExtension;\n gl.getExtension = function (extensionName: string) {\n const ext = originalGetExtension.call(gl, extensionName);\n if (ext) {\n return ext;\n }\n\n // Injected extensions\n if (extensionName in boundExtensions) {\n // @ts-ignore TODO string index\n return boundExtensions[extensionName];\n }\n\n return null;\n };\n\n // Override gl.getSupportedExtensions\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalGetSupportedExtensions = gl.getSupportedExtensions;\n gl.getSupportedExtensions = function (): string[] | null {\n const extensions = originalGetSupportedExtensions.apply(gl) || [];\n return extensions?.concat(Object.keys(boundExtensions));\n };\n}\n\n// Update unsized WebGL1 formats to sized WebGL2 formats\n// todo move to texture format file\n// export function getInternalFormat(gl: WebGL2RenderingContext, format: GL, type: GL): GL {\n// // webgl2 texture formats\n// // https://webgl2fundamentals.org/webgl/lessons/webgl-data-textures.html\n// switch (format) {\n// case GL.DEPTH_COMPONENT:\n// return GL.DEPTH_COMPONENT24;\n// case GL.DEPTH_STENCIL:\n// return GL.DEPTH24_STENCIL8;\n// case GL.RGBA:\n// return type === GL.HALF_FLOAT ? GL.RGBA16F : GL.RGBA32F;\n// case GL.RGB:\n// return type === GL.HALF_FLOAT ? GL.RGB16F : GL.RGB32F;\n// default:\n// return format;\n// }\n// }\n\n/*\n// texture type to update on the fly\nexport function getTextureType(gl: WebGL2RenderingContext, type: GL): GL {\n if (type === HALF_FLOAT_OES) {\n return GL.HALF_FLOAT;\n }\n return type;\n}\n\n // And texImage2D to convert the internalFormat to webgl2.\n const webgl2 = this;\n const origTexImage = gl.texImage2D;\n gl.texImage2D = function (target, miplevel, iformat, a, typeFor6, c, d, typeFor9, f) {\n if (arguments.length == 6) {\n var ifmt = webgl2.getInternalFormat(gl, iformat, typeFor6);\n origTexImage.apply(gl, [target, miplevel, ifmt, a, webgl.getTextureType(gl, typeFor6), c]);\n } else {\n // arguments.length == 9\n var ifmt = webgl2.getInternalFormat(gl, iformat, typeFor9);\n origTexImage.apply(gl, [\n target,\n miplevel,\n ifmt,\n a,\n typeFor6,\n c,\n d,\n webgl2.getTextureType(gl, typeFor9),\n f\n ]);\n }\n };\n};\n*/\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/**\n * Load a script (identified by an url). When the url returns, the\n * content of this file is added into a new script element, attached to the DOM (body element)\n * @param scriptUrl defines the url of the script to laod\n * @param scriptId defines the id of the script element\n */\nexport async function loadScript(scriptUrl: string, scriptId?: string): Promise {\n const head = document.getElementsByTagName('head')[0];\n if (!head) {\n throw new Error('loadScript');\n }\n\n const script = document.createElement('script');\n script.setAttribute('type', 'text/javascript');\n script.setAttribute('src', scriptUrl);\n if (scriptId) {\n script.id = scriptId;\n }\n\n return new Promise((resolve, reject) => {\n script.onload = resolve;\n script.onerror = error =>\n reject(new Error(`Unable to load script '${scriptUrl}': ${error as string}`));\n head.appendChild(script);\n });\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {GLExtensions} from '@luma.gl/webgl/constants';\n\n/**\n * Stores luma.gl specific state associated with a context\n */\nexport interface WebGLContextData {\n /** This type is used by lower level code that is not aware of the Device type */\n device?: unknown;\n _polyfilled: boolean;\n extensions: GLExtensions;\n softwareRenderer?: boolean;\n}\n\n/**\n * Gets luma.gl specific state from a context\n * @returns context state\n */\nexport function getWebGLContextData(gl: WebGL2RenderingContext): WebGLContextData {\n // @ts-expect-error\n const contextData = (gl.luma as WebGLContextData | null) || {\n _polyfilled: false,\n extensions: {},\n softwareRenderer: false\n };\n\n contextData._polyfilled ??= false;\n contextData.extensions ||= {};\n\n // @ts-expect-error\n gl.luma = contextData;\n\n return contextData;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {log} from '@luma.gl/core';\nimport {loadScript} from '../../utils/load-script';\nimport {getWebGLContextData} from '../helpers/webgl-context-data';\n\nimport type {Spector} from './spector-types';\n\n/** Spector debug initialization options */\ntype SpectorProps = {\n /** Whether spector.js is enabled */\n debugSpectorJS?: boolean;\n /** URL to load spector script from. Typically a CDN URL */\n debugSpectorJSUrl?: string;\n /** Canvas to monitor */\n gl?: WebGL2RenderingContext;\n};\n\nconst LOG_LEVEL = 1;\n\nlet spector: Spector | null = null;\nlet initialized: boolean = false;\n\ndeclare global {\n // @ts-ignore\n // eslint-disable-next-line no-var\n var SPECTOR: Spector;\n}\n\nexport const DEFAULT_SPECTOR_PROPS: Required = {\n debugSpectorJS: log.get('debug-spectorjs'),\n // https://github.com/BabylonJS/Spector.js#basic-usage\n // https://forum.babylonjs.com/t/spectorcdn-is-temporarily-off/48241\n // spectorUrl: 'https://spectorcdn.babylonjs.com/spector.bundle.js';\n debugSpectorJSUrl: 'https://cdn.jsdelivr.net/npm/spectorjs@0.9.30/dist/spector.bundle.js',\n gl: undefined!\n};\n\n/** Loads spector from CDN if not already installed */\nexport async function loadSpectorJS(props: {debugSpectorJSUrl?: string}): Promise {\n if (!globalThis.SPECTOR) {\n try {\n await loadScript(props.debugSpectorJSUrl || DEFAULT_SPECTOR_PROPS.debugSpectorJSUrl);\n } catch (error) {\n log.warn(String(error));\n }\n }\n}\n\nexport function initializeSpectorJS(props: SpectorProps): Spector | null {\n props = {...DEFAULT_SPECTOR_PROPS, ...props};\n if (!props.debugSpectorJS) {\n return null;\n }\n\n if (!spector && globalThis.SPECTOR && !globalThis.luma?.spector) {\n log.probe(LOG_LEVEL, 'SPECTOR found and initialized. Start with `luma.spector.displayUI()`')();\n const {Spector: SpectorJS} = globalThis.SPECTOR as any;\n spector = new SpectorJS();\n if (globalThis.luma) {\n (globalThis.luma as any).spector = spector;\n }\n }\n\n if (!spector) {\n return null;\n }\n\n if (!initialized) {\n initialized = true;\n\n // enables recording some extra information merged in the capture like texture memory sizes and formats\n spector.spyCanvases();\n // A callback when results are ready\n spector?.onCaptureStarted.add((capture: unknown) =>\n log.info('Spector capture started:', capture)()\n );\n spector?.onCapture.add((capture: unknown) => {\n log.info('Spector capture complete:', capture)();\n // Use undocumented Spector API to open the UI with our capture\n // See https://github.com/BabylonJS/Spector.js/blob/767ad1195a25b85a85c381f400eb50a979239eca/src/spector.ts#L124\n spector?.getResultUI();\n // @ts-expect-error private\n spector?.resultView.display();\n // @ts-expect-error private\n spector?.resultView.addCapture(capture);\n });\n }\n\n if (props.gl) {\n // capture startup\n const gl = props.gl;\n const contextData = getWebGLContextData(gl);\n const device = contextData.device;\n spector?.startCapture(props.gl, 500); // 500 commands\n contextData.device = device;\n\n new Promise(resolve => setTimeout(resolve, 2000)).then(_ => {\n log.info('Spector capture stopped after 2 seconds')();\n spector?.stopCapture();\n // spector?.displayUI();\n });\n }\n\n return spector;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {log} from '@luma.gl/core';\n// Rename constant to prevent inlining. We need the full set of constants for generating debug strings.\nimport {GL as GLEnum} from '@luma.gl/webgl/constants';\nimport {isBrowser} from '@probe.gl/env';\nimport {loadScript} from '../../utils/load-script';\n\nconst WEBGL_DEBUG_CDN_URL = 'https://unpkg.com/webgl-debug@2.0.1/index.js';\n\ntype DebugContextProps = {\n debugWebGL?: boolean;\n traceWebGL?: boolean;\n};\n\ntype ContextData = {\n realContext?: WebGL2RenderingContext;\n debugContext?: WebGL2RenderingContext;\n};\n\n// Helper to get shared context data\nfunction getWebGLContextData(gl: any): ContextData {\n gl.luma = gl.luma || {};\n return gl.luma;\n}\n\ndeclare global {\n // eslint-disable-next-line no-var\n var WebGLDebugUtils: any;\n}\n\n/**\n * Loads Khronos WebGLDeveloperTools from CDN if not already installed\n * const WebGLDebugUtils = require('webgl-debug');\n * @see https://github.com/KhronosGroup/WebGLDeveloperTools\n * @see https://github.com/vorg/webgl-debug\n */\nexport async function loadWebGLDeveloperTools(): Promise {\n if (isBrowser() && !globalThis.WebGLDebugUtils) {\n globalThis.global = globalThis.global || globalThis;\n // @ts-expect-error Developer tools expects global to be set\n globalThis.global.module = {};\n await loadScript(WEBGL_DEBUG_CDN_URL);\n }\n}\n\n// Returns (a potentially new) context with debug instrumentation turned off or on.\n// Note that this actually returns a new context\nexport function makeDebugContext(\n gl: WebGL2RenderingContext,\n props: DebugContextProps = {}\n): WebGL2RenderingContext {\n return props.debugWebGL || props.traceWebGL ? getDebugContext(gl, props) : getRealContext(gl);\n}\n\n// Returns the real context from either of the real/debug contexts\nfunction getRealContext(gl: WebGL2RenderingContext): WebGL2RenderingContext {\n const data = getWebGLContextData(gl);\n // If the context has a realContext member, it is a debug context so return the realContext\n return data.realContext ? data.realContext : gl;\n}\n\n// Returns the debug context from either of the real/debug contexts\nfunction getDebugContext(\n gl: WebGL2RenderingContext,\n props: DebugContextProps\n): WebGL2RenderingContext {\n if (!globalThis.WebGLDebugUtils) {\n log.warn('webgl-debug not loaded')();\n return gl;\n }\n\n const data = getWebGLContextData(gl);\n\n // If this already has a debug context, return it.\n if (data.debugContext) {\n return data.debugContext;\n }\n\n // Create a new debug context\n globalThis.WebGLDebugUtils.init({...GLEnum, ...gl});\n const glDebug = globalThis.WebGLDebugUtils.makeDebugContext(\n gl,\n onGLError.bind(null, props),\n onValidateGLFunc.bind(null, props)\n );\n\n // Make sure we have all WebGL2 and extension constants (todo dynamic import to circumvent minification?)\n for (const key in GLEnum) {\n if (!(key in glDebug) && typeof GLEnum[key] === 'number') {\n glDebug[key] = GLEnum[key];\n }\n }\n\n // Ensure we have a clean prototype on the instrumented object\n // Note: setPrototypeOf does come with perf warnings, but we already take a bigger perf reduction\n // by synchronizing the WebGL errors after each WebGL call.\n class WebGLDebugContext {}\n Object.setPrototypeOf(glDebug, Object.getPrototypeOf(gl));\n Object.setPrototypeOf(WebGLDebugContext, glDebug);\n const debugContext = Object.create(WebGLDebugContext);\n // Store the debug context\n data.realContext = gl;\n data.debugContext = debugContext;\n // Share the context metadata object with the debug context so lookups stay consistent.\n (debugContext as {luma?: unknown}).luma = data;\n debugContext.debug = true;\n\n // Return it\n return debugContext;\n}\n\n// DEBUG TRACING\n\nfunction getFunctionString(functionName: string, functionArgs: unknown[]): string {\n // Cover bug in webgl-debug-tools\n functionArgs = Array.from(functionArgs).map(arg => (arg === undefined ? 'undefined' : arg));\n let args = globalThis.WebGLDebugUtils.glFunctionArgsToString(functionName, functionArgs);\n args = `${args.slice(0, 100)}${args.length > 100 ? '...' : ''}`;\n return `gl.${functionName}(${args})`;\n}\n\nfunction onGLError(\n props: DebugContextProps,\n err: number,\n functionName: string,\n args: unknown[]\n): void {\n // Cover bug in webgl-debug-tools\n args = Array.from(args).map(arg => (arg === undefined ? 'undefined' : arg));\n const errorMessage = globalThis.WebGLDebugUtils.glEnumToString(err);\n const functionArgs = globalThis.WebGLDebugUtils.glFunctionArgsToString(functionName, args);\n const message = `${errorMessage} in gl.${functionName}(${functionArgs})`;\n // TODO - call device.reportError\n log.error(\n '%cWebGL',\n 'color: white; background: red; padding: 2px 6px; border-radius: 3px;',\n message\n )();\n // biome-ignore lint/suspicious/noDebugger: pause immediately on WebGL debug utility errors.\n debugger;\n throw new Error(message);\n}\n\n// Don't generate function string until it is needed\nfunction onValidateGLFunc(\n props: DebugContextProps,\n functionName: string,\n functionArgs: unknown[]\n): void {\n let functionString: string = '';\n if (props.traceWebGL && log.level >= 1) {\n functionString = getFunctionString(functionName, functionArgs);\n log.info(\n 1,\n '%cWebGL',\n 'color: white; background: blue; padding: 2px 6px; border-radius: 3px;',\n functionString\n )();\n }\n\n for (const arg of functionArgs) {\n if (arg === undefined) {\n functionString = functionString || getFunctionString(functionName, functionArgs);\n // biome-ignore lint/suspicious/noDebugger: pause when validating undefined WebGL call arguments.\n debugger;\n // throw new Error(`Undefined argument: ${functionString}`);\n }\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// @ts-nocheck TODO fix\n\n// Tables describing WebGL parameters\nimport {GL, GLParameters} from '@luma.gl/webgl/constants';\n\n// DEFAULT SETTINGS - FOR FAST CACHE INITIALIZATION AND CONTEXT RESETS\n\n/* eslint-disable no-shadow */\n\nexport const GL_PARAMETER_DEFAULTS: GLParameters = {\n [GL.BLEND]: false,\n [GL.BLEND_COLOR]: new Float32Array([0, 0, 0, 0]),\n [GL.BLEND_EQUATION_RGB]: GL.FUNC_ADD,\n [GL.BLEND_EQUATION_ALPHA]: GL.FUNC_ADD,\n [GL.BLEND_SRC_RGB]: GL.ONE,\n [GL.BLEND_DST_RGB]: GL.ZERO,\n [GL.BLEND_SRC_ALPHA]: GL.ONE,\n [GL.BLEND_DST_ALPHA]: GL.ZERO,\n [GL.COLOR_CLEAR_VALUE]: new Float32Array([0, 0, 0, 0]), // TBD\n [GL.COLOR_WRITEMASK]: [true, true, true, true],\n [GL.CULL_FACE]: false,\n [GL.CULL_FACE_MODE]: GL.BACK,\n [GL.DEPTH_TEST]: false,\n [GL.DEPTH_CLEAR_VALUE]: 1,\n [GL.DEPTH_FUNC]: GL.LESS,\n [GL.DEPTH_RANGE]: new Float32Array([0, 1]), // TBD\n [GL.DEPTH_WRITEMASK]: true,\n [GL.DITHER]: true,\n [GL.CURRENT_PROGRAM]: null,\n // FRAMEBUFFER_BINDING and DRAW_FRAMEBUFFER_BINDING(WebGL2) refer same state.\n [GL.FRAMEBUFFER_BINDING]: null,\n [GL.RENDERBUFFER_BINDING]: null,\n [GL.VERTEX_ARRAY_BINDING]: null,\n [GL.ARRAY_BUFFER_BINDING]: null,\n [GL.FRONT_FACE]: GL.CCW,\n [GL.GENERATE_MIPMAP_HINT]: GL.DONT_CARE,\n [GL.LINE_WIDTH]: 1,\n [GL.POLYGON_OFFSET_FILL]: false,\n [GL.POLYGON_OFFSET_FACTOR]: 0,\n [GL.POLYGON_OFFSET_UNITS]: 0,\n [GL.SAMPLE_ALPHA_TO_COVERAGE]: false,\n [GL.SAMPLE_COVERAGE]: false,\n [GL.SAMPLE_COVERAGE_VALUE]: 1.0,\n [GL.SAMPLE_COVERAGE_INVERT]: false,\n [GL.SCISSOR_TEST]: false,\n // Note: Dynamic value. If scissor test enabled we expect users to set correct scissor box\n [GL.SCISSOR_BOX]: new Int32Array([0, 0, 1024, 1024]),\n [GL.STENCIL_TEST]: false,\n [GL.STENCIL_CLEAR_VALUE]: 0,\n [GL.STENCIL_WRITEMASK]: 0xffffffff,\n [GL.STENCIL_BACK_WRITEMASK]: 0xffffffff,\n [GL.STENCIL_FUNC]: GL.ALWAYS,\n [GL.STENCIL_REF]: 0,\n [GL.STENCIL_VALUE_MASK]: 0xffffffff,\n [GL.STENCIL_BACK_FUNC]: GL.ALWAYS,\n [GL.STENCIL_BACK_REF]: 0,\n [GL.STENCIL_BACK_VALUE_MASK]: 0xffffffff,\n [GL.STENCIL_FAIL]: GL.KEEP,\n [GL.STENCIL_PASS_DEPTH_FAIL]: GL.KEEP,\n [GL.STENCIL_PASS_DEPTH_PASS]: GL.KEEP,\n [GL.STENCIL_BACK_FAIL]: GL.KEEP,\n [GL.STENCIL_BACK_PASS_DEPTH_FAIL]: GL.KEEP,\n [GL.STENCIL_BACK_PASS_DEPTH_PASS]: GL.KEEP,\n // Dynamic value: We use [0, 0, 1024, 1024] as default, but usually this is updated in each frame.\n [GL.VIEWPORT]: [0, 0, 1024, 1024],\n\n [GL.TRANSFORM_FEEDBACK_BINDING]: null,\n [GL.COPY_READ_BUFFER_BINDING]: null,\n [GL.COPY_WRITE_BUFFER_BINDING]: null,\n [GL.PIXEL_PACK_BUFFER_BINDING]: null,\n [GL.PIXEL_UNPACK_BUFFER_BINDING]: null,\n [GL.FRAGMENT_SHADER_DERIVATIVE_HINT]: GL.DONT_CARE,\n [GL.READ_FRAMEBUFFER_BINDING]: null,\n [GL.RASTERIZER_DISCARD]: false,\n\n [GL.PACK_ALIGNMENT]: 4,\n [GL.UNPACK_ALIGNMENT]: 4,\n [GL.UNPACK_FLIP_Y_WEBGL]: false,\n [GL.UNPACK_PREMULTIPLY_ALPHA_WEBGL]: false,\n [GL.UNPACK_COLORSPACE_CONVERSION_WEBGL]: GL.BROWSER_DEFAULT_WEBGL,\n [GL.PACK_ROW_LENGTH]: 0,\n [GL.PACK_SKIP_PIXELS]: 0,\n [GL.PACK_SKIP_ROWS]: 0,\n [GL.UNPACK_ROW_LENGTH]: 0,\n [GL.UNPACK_IMAGE_HEIGHT]: 0,\n [GL.UNPACK_SKIP_PIXELS]: 0,\n [GL.UNPACK_SKIP_ROWS]: 0,\n [GL.UNPACK_SKIP_IMAGES]: 0\n};\n\n// SETTER TABLES - ENABLES SETTING ANY PARAMETER WITH A COMMON API\n\nconst enable = (gl: WebGL2RenderingContext, value: unknown, key: GL) =>\n value ? gl.enable(key) : gl.disable(key);\nconst hint = (gl: WebGL2RenderingContext, value: GL, key: GL) => gl.hint(key, value);\nconst pixelStorei = (gl: WebGL2RenderingContext, value: number | boolean, key: GL) =>\n gl.pixelStorei(key, value);\n\nconst bindFramebuffer = (gl: WebGL2RenderingContext, value: unknown, key: GL) => {\n const target = key === GL.FRAMEBUFFER_BINDING ? GL.DRAW_FRAMEBUFFER : GL.READ_FRAMEBUFFER;\n return gl.bindFramebuffer(target, value as WebGLFramebuffer);\n};\n\nconst bindBuffer = (gl: WebGL2RenderingContext, value: unknown, key: GL) => {\n const bindingMap: Partial> = {\n [GL.ARRAY_BUFFER_BINDING]: GL.ARRAY_BUFFER,\n [GL.COPY_READ_BUFFER_BINDING]: GL.COPY_READ_BUFFER,\n [GL.COPY_WRITE_BUFFER_BINDING]: GL.COPY_WRITE_BUFFER,\n [GL.PIXEL_PACK_BUFFER_BINDING]: GL.PIXEL_PACK_BUFFER,\n [GL.PIXEL_UNPACK_BUFFER_BINDING]: GL.PIXEL_UNPACK_BUFFER\n };\n const glTarget = bindingMap[key];\n\n gl.bindBuffer(glTarget as number, value as WebGLBuffer | null);\n};\n\n// Utility\nfunction isArray(array: unknown): boolean {\n return Array.isArray(array) || (ArrayBuffer.isView(array) && !(array instanceof DataView));\n}\n\n// Map from WebGL parameter names to corresponding WebGL setter functions\n// WegGL constants are read by parameter names, but set by function names\n// NOTE: When value type is a string, it will be handled by 'GL_COMPOSITE_PARAMETER_SETTERS'\nexport const GL_PARAMETER_SETTERS = {\n [GL.BLEND]: enable,\n [GL.BLEND_COLOR]: (gl: WebGL2RenderingContext, value: [number, number, number, number]) =>\n gl.blendColor(...value),\n [GL.BLEND_EQUATION_RGB]: 'blendEquation',\n [GL.BLEND_EQUATION_ALPHA]: 'blendEquation',\n [GL.BLEND_SRC_RGB]: 'blendFunc',\n [GL.BLEND_DST_RGB]: 'blendFunc',\n [GL.BLEND_SRC_ALPHA]: 'blendFunc',\n [GL.BLEND_DST_ALPHA]: 'blendFunc',\n [GL.COLOR_CLEAR_VALUE]: (gl: WebGL2RenderingContext, value: [number, number, number, number]) =>\n gl.clearColor(...value),\n [GL.COLOR_WRITEMASK]: (gl: WebGL2RenderingContext, value: [boolean, boolean, boolean, boolean]) =>\n gl.colorMask(...value),\n [GL.CULL_FACE]: enable,\n [GL.CULL_FACE_MODE]: (gl: WebGL2RenderingContext, value) => gl.cullFace(value),\n [GL.DEPTH_TEST]: enable,\n [GL.DEPTH_CLEAR_VALUE]: (gl: WebGL2RenderingContext, value) => gl.clearDepth(value),\n [GL.DEPTH_FUNC]: (gl: WebGL2RenderingContext, value) => gl.depthFunc(value),\n [GL.DEPTH_RANGE]: (gl: WebGL2RenderingContext, value: [number, number]) =>\n gl.depthRange(...value),\n [GL.DEPTH_WRITEMASK]: (gl: WebGL2RenderingContext, value) => gl.depthMask(value),\n [GL.DITHER]: enable,\n [GL.FRAGMENT_SHADER_DERIVATIVE_HINT]: hint,\n\n [GL.CURRENT_PROGRAM]: (gl: WebGL2RenderingContext, value) => gl.useProgram(value),\n [GL.RENDERBUFFER_BINDING]: (gl: WebGL2RenderingContext, value) =>\n gl.bindRenderbuffer(GL.RENDERBUFFER, value),\n [GL.TRANSFORM_FEEDBACK_BINDING]: (gl: WebGL2RenderingContext, value) =>\n gl.bindTransformFeedback?.(GL.TRANSFORM_FEEDBACK, value),\n [GL.VERTEX_ARRAY_BINDING]: (gl: WebGL2RenderingContext, value) => gl.bindVertexArray(value),\n // NOTE: FRAMEBUFFER_BINDING and DRAW_FRAMEBUFFER_BINDING(WebGL2) refer same state.\n [GL.FRAMEBUFFER_BINDING]: bindFramebuffer,\n [GL.READ_FRAMEBUFFER_BINDING]: bindFramebuffer,\n\n // Buffers\n [GL.ARRAY_BUFFER_BINDING]: bindBuffer,\n [GL.COPY_READ_BUFFER_BINDING]: bindBuffer,\n [GL.COPY_WRITE_BUFFER_BINDING]: bindBuffer,\n [GL.PIXEL_PACK_BUFFER_BINDING]: bindBuffer,\n [GL.PIXEL_UNPACK_BUFFER_BINDING]: bindBuffer,\n\n [GL.FRONT_FACE]: (gl: WebGL2RenderingContext, value) => gl.frontFace(value),\n [GL.GENERATE_MIPMAP_HINT]: hint,\n [GL.LINE_WIDTH]: (gl: WebGL2RenderingContext, value) => gl.lineWidth(value),\n [GL.POLYGON_OFFSET_FILL]: enable,\n [GL.POLYGON_OFFSET_FACTOR]: 'polygonOffset',\n [GL.POLYGON_OFFSET_UNITS]: 'polygonOffset',\n [GL.RASTERIZER_DISCARD]: enable,\n [GL.SAMPLE_ALPHA_TO_COVERAGE]: enable,\n [GL.SAMPLE_COVERAGE]: enable,\n [GL.SAMPLE_COVERAGE_VALUE]: 'sampleCoverage',\n [GL.SAMPLE_COVERAGE_INVERT]: 'sampleCoverage',\n [GL.SCISSOR_TEST]: enable,\n [GL.SCISSOR_BOX]: (gl: WebGL2RenderingContext, value: [number, number, number, number]) =>\n gl.scissor(...value),\n [GL.STENCIL_TEST]: enable,\n [GL.STENCIL_CLEAR_VALUE]: (gl: WebGL2RenderingContext, value) => gl.clearStencil(value),\n [GL.STENCIL_WRITEMASK]: (gl: WebGL2RenderingContext, value) =>\n gl.stencilMaskSeparate(GL.FRONT, value),\n [GL.STENCIL_BACK_WRITEMASK]: (gl: WebGL2RenderingContext, value) =>\n gl.stencilMaskSeparate(GL.BACK, value),\n [GL.STENCIL_FUNC]: 'stencilFuncFront',\n [GL.STENCIL_REF]: 'stencilFuncFront',\n [GL.STENCIL_VALUE_MASK]: 'stencilFuncFront',\n [GL.STENCIL_BACK_FUNC]: 'stencilFuncBack',\n [GL.STENCIL_BACK_REF]: 'stencilFuncBack',\n [GL.STENCIL_BACK_VALUE_MASK]: 'stencilFuncBack',\n [GL.STENCIL_FAIL]: 'stencilOpFront',\n [GL.STENCIL_PASS_DEPTH_FAIL]: 'stencilOpFront',\n [GL.STENCIL_PASS_DEPTH_PASS]: 'stencilOpFront',\n [GL.STENCIL_BACK_FAIL]: 'stencilOpBack',\n [GL.STENCIL_BACK_PASS_DEPTH_FAIL]: 'stencilOpBack',\n [GL.STENCIL_BACK_PASS_DEPTH_PASS]: 'stencilOpBack',\n [GL.VIEWPORT]: (gl: WebGL2RenderingContext, value: [number, number, number, number]) =>\n gl.viewport(...value),\n\n // WEBGL2 EXTENSIONS\n\n // EXT_depth_clamp https://registry.khronos.org/webgl/extensions/EXT_depth_clamp/\n\n [GL.DEPTH_CLAMP_EXT]: enable,\n\n // WEBGL_provoking_vertex https://registry.khronos.org/webgl/extensions/WEBGL_provoking_vertex/\n\n // [GL.PROVOKING_VERTEX_WEBL]: TODO - extension function needed\n\n // WEBGL_polygon_mode https://registry.khronos.org/webgl/extensions/WEBGL_polygon_mode/\n\n // POLYGON_MODE_WEBGL TODO - extension function needed\n [GL.POLYGON_OFFSET_LINE_WEBGL]: enable,\n\n // WEBGL_clip_cull_distance https://registry.khronos.org/webgl/extensions/WEBGL_clip_cull_distance/\n\n [GL.CLIP_DISTANCE0_WEBGL]: enable,\n [GL.CLIP_DISTANCE1_WEBGL]: enable,\n [GL.CLIP_DISTANCE2_WEBGL]: enable,\n [GL.CLIP_DISTANCE3_WEBGL]: enable,\n [GL.CLIP_DISTANCE4_WEBGL]: enable,\n [GL.CLIP_DISTANCE5_WEBGL]: enable,\n [GL.CLIP_DISTANCE6_WEBGL]: enable,\n [GL.CLIP_DISTANCE7_WEBGL]: enable,\n\n // PIXEL PACK/UNPACK MODES\n [GL.PACK_ALIGNMENT]: pixelStorei,\n [GL.UNPACK_ALIGNMENT]: pixelStorei,\n [GL.UNPACK_FLIP_Y_WEBGL]: pixelStorei,\n [GL.UNPACK_PREMULTIPLY_ALPHA_WEBGL]: pixelStorei,\n [GL.UNPACK_COLORSPACE_CONVERSION_WEBGL]: pixelStorei,\n [GL.PACK_ROW_LENGTH]: pixelStorei,\n [GL.PACK_SKIP_PIXELS]: pixelStorei,\n [GL.PACK_SKIP_ROWS]: pixelStorei,\n [GL.UNPACK_ROW_LENGTH]: pixelStorei,\n [GL.UNPACK_IMAGE_HEIGHT]: pixelStorei,\n [GL.UNPACK_SKIP_PIXELS]: pixelStorei,\n [GL.UNPACK_SKIP_ROWS]: pixelStorei,\n [GL.UNPACK_SKIP_IMAGES]: pixelStorei,\n\n // Function-style setters\n framebuffer: (gl: WebGL2RenderingContext, framebuffer) => {\n // accepts 1) a WebGLFramebuffer 2) null (default framebuffer), or 3) luma.gl Framebuffer class\n // framebuffer is null when restoring to default framebuffer, otherwise use the WebGL handle.\n const handle = framebuffer && 'handle' in framebuffer ? framebuffer.handle : framebuffer;\n return gl.bindFramebuffer(GL.FRAMEBUFFER, handle);\n },\n blend: (gl: WebGL2RenderingContext, value) =>\n value ? gl.enable(GL.BLEND) : gl.disable(GL.BLEND),\n blendColor: (gl: WebGL2RenderingContext, value: [number, number, number, number]) =>\n gl.blendColor(...value),\n blendEquation: (gl: WebGL2RenderingContext, args: number | [number, number]) => {\n const separateModes = typeof args === 'number' ? ([args, args] as [number, number]) : args;\n gl.blendEquationSeparate(...separateModes);\n },\n blendFunc: (\n gl: WebGL2RenderingContext,\n args: [number, number] | [number, number, number, number]\n ) => {\n const separateFuncs =\n args?.length === 2 ? ([...args, ...args] as [number, number, number, number]) : args;\n gl.blendFuncSeparate(...separateFuncs);\n },\n\n clearColor: (gl: WebGL2RenderingContext, value: [number, number, number, number]) =>\n gl.clearColor(...value),\n clearDepth: (gl: WebGL2RenderingContext, value) => gl.clearDepth(value),\n clearStencil: (gl: WebGL2RenderingContext, value) => gl.clearStencil(value),\n\n colorMask: (gl: WebGL2RenderingContext, value: [boolean, boolean, boolean, boolean]) =>\n gl.colorMask(...value),\n\n cull: (gl: WebGL2RenderingContext, value) =>\n value ? gl.enable(GL.CULL_FACE) : gl.disable(GL.CULL_FACE),\n cullFace: (gl: WebGL2RenderingContext, value) => gl.cullFace(value),\n\n depthTest: (gl: WebGL2RenderingContext, value) =>\n value ? gl.enable(GL.DEPTH_TEST) : gl.disable(GL.DEPTH_TEST),\n depthFunc: (gl: WebGL2RenderingContext, value) => gl.depthFunc(value),\n depthMask: (gl: WebGL2RenderingContext, value) => gl.depthMask(value),\n depthRange: (gl: WebGL2RenderingContext, value: [number, number]) => gl.depthRange(...value),\n\n dither: (gl: WebGL2RenderingContext, value) =>\n value ? gl.enable(GL.DITHER) : gl.disable(GL.DITHER),\n\n derivativeHint: (gl: WebGL2RenderingContext, value) => {\n // gl1: 'OES_standard_derivatives'\n gl.hint(GL.FRAGMENT_SHADER_DERIVATIVE_HINT, value);\n },\n\n frontFace: (gl: WebGL2RenderingContext, value) => gl.frontFace(value),\n\n mipmapHint: (gl: WebGL2RenderingContext, value) => gl.hint(GL.GENERATE_MIPMAP_HINT, value),\n\n lineWidth: (gl: WebGL2RenderingContext, value) => gl.lineWidth(value),\n\n polygonOffsetFill: (gl: WebGL2RenderingContext, value) =>\n value ? gl.enable(GL.POLYGON_OFFSET_FILL) : gl.disable(GL.POLYGON_OFFSET_FILL),\n polygonOffset: (gl: WebGL2RenderingContext, value: [number, number]) =>\n gl.polygonOffset(...value),\n\n sampleCoverage: (gl: WebGL2RenderingContext, value: [number, boolean?]) =>\n gl.sampleCoverage(value[0], value[1] || false),\n\n scissorTest: (gl: WebGL2RenderingContext, value) =>\n value ? gl.enable(GL.SCISSOR_TEST) : gl.disable(GL.SCISSOR_TEST),\n scissor: (gl: WebGL2RenderingContext, value: [number, number, number, number]) =>\n gl.scissor(...value),\n\n stencilTest: (gl: WebGL2RenderingContext, value) =>\n value ? gl.enable(GL.STENCIL_TEST) : gl.disable(GL.STENCIL_TEST),\n stencilMask: (gl: WebGL2RenderingContext, value) => {\n value = isArray(value) ? value : [value, value];\n const [mask, backMask] = value;\n gl.stencilMaskSeparate(GL.FRONT, mask);\n gl.stencilMaskSeparate(GL.BACK, backMask);\n },\n stencilFunc: (gl: WebGL2RenderingContext, args) => {\n args = isArray(args) && args.length === 3 ? [...args, ...args] : args;\n const [func, ref, mask, backFunc, backRef, backMask] = args;\n gl.stencilFuncSeparate(GL.FRONT, func, ref, mask);\n gl.stencilFuncSeparate(GL.BACK, backFunc, backRef, backMask);\n },\n stencilOp: (gl: WebGL2RenderingContext, args) => {\n args = isArray(args) && args.length === 3 ? [...args, ...args] : args;\n const [sfail, dpfail, dppass, backSfail, backDpfail, backDppass] = args;\n gl.stencilOpSeparate(GL.FRONT, sfail, dpfail, dppass);\n gl.stencilOpSeparate(GL.BACK, backSfail, backDpfail, backDppass);\n },\n\n viewport: (gl: WebGL2RenderingContext, value: [number, number, number, number]) =>\n gl.viewport(...value)\n};\n\nfunction getValue(glEnum, values, cache) {\n return values[glEnum] !== undefined ? values[glEnum] : cache[glEnum];\n}\n\n// COMPOSITE_WEBGL_PARAMETER_\nexport const GL_COMPOSITE_PARAMETER_SETTERS = {\n blendEquation: (gl: WebGL2RenderingContext, values, cache) =>\n gl.blendEquationSeparate(\n getValue(GL.BLEND_EQUATION_RGB, values, cache),\n getValue(GL.BLEND_EQUATION_ALPHA, values, cache)\n ),\n blendFunc: (gl: WebGL2RenderingContext, values, cache) =>\n gl.blendFuncSeparate(\n getValue(GL.BLEND_SRC_RGB, values, cache),\n getValue(GL.BLEND_DST_RGB, values, cache),\n getValue(GL.BLEND_SRC_ALPHA, values, cache),\n getValue(GL.BLEND_DST_ALPHA, values, cache)\n ),\n polygonOffset: (gl: WebGL2RenderingContext, values, cache) =>\n gl.polygonOffset(\n getValue(GL.POLYGON_OFFSET_FACTOR, values, cache),\n getValue(GL.POLYGON_OFFSET_UNITS, values, cache)\n ),\n sampleCoverage: (gl: WebGL2RenderingContext, values, cache) =>\n gl.sampleCoverage(\n getValue(GL.SAMPLE_COVERAGE_VALUE, values, cache),\n getValue(GL.SAMPLE_COVERAGE_INVERT, values, cache)\n ),\n stencilFuncFront: (gl: WebGL2RenderingContext, values, cache) =>\n gl.stencilFuncSeparate(\n GL.FRONT,\n getValue(GL.STENCIL_FUNC, values, cache),\n getValue(GL.STENCIL_REF, values, cache),\n getValue(GL.STENCIL_VALUE_MASK, values, cache)\n ),\n stencilFuncBack: (gl: WebGL2RenderingContext, values, cache) =>\n gl.stencilFuncSeparate(\n GL.BACK,\n getValue(GL.STENCIL_BACK_FUNC, values, cache),\n getValue(GL.STENCIL_BACK_REF, values, cache),\n getValue(GL.STENCIL_BACK_VALUE_MASK, values, cache)\n ),\n stencilOpFront: (gl: WebGL2RenderingContext, values, cache) =>\n gl.stencilOpSeparate(\n GL.FRONT,\n getValue(GL.STENCIL_FAIL, values, cache),\n getValue(GL.STENCIL_PASS_DEPTH_FAIL, values, cache),\n getValue(GL.STENCIL_PASS_DEPTH_PASS, values, cache)\n ),\n stencilOpBack: (gl: WebGL2RenderingContext, values, cache) =>\n gl.stencilOpSeparate(\n GL.BACK,\n getValue(GL.STENCIL_BACK_FAIL, values, cache),\n getValue(GL.STENCIL_BACK_PASS_DEPTH_FAIL, values, cache),\n getValue(GL.STENCIL_BACK_PASS_DEPTH_PASS, values, cache)\n )\n};\n\ntype UpdateFunc = (params: Record) => void;\n\n// Setter functions intercepted for cache updates\nexport const GL_HOOKED_SETTERS = {\n // GENERIC SETTERS\n\n enable: (update: UpdateFunc, capability: GL) =>\n update({\n [capability]: true\n }),\n disable: (update: UpdateFunc, capability: GL) =>\n update({\n [capability]: false\n }),\n pixelStorei: (update: UpdateFunc, pname: GL, value) =>\n update({\n [pname]: value\n }),\n hint: (update: UpdateFunc, pname: GL, value: GL) =>\n update({\n [pname]: value\n }),\n\n // SPECIFIC SETTERS\n useProgram: (update: UpdateFunc, value) =>\n update({\n [GL.CURRENT_PROGRAM]: value\n }),\n bindRenderbuffer: (update: UpdateFunc, target, value) =>\n update({\n [GL.RENDERBUFFER_BINDING]: value\n }),\n bindTransformFeedback: (update: UpdateFunc, target, value) =>\n update({\n [GL.TRANSFORM_FEEDBACK_BINDING]: value\n }),\n bindVertexArray: (update: UpdateFunc, value) =>\n update({\n [GL.VERTEX_ARRAY_BINDING]: value\n }),\n\n bindFramebuffer: (update: UpdateFunc, target, framebuffer) => {\n switch (target) {\n case GL.FRAMEBUFFER:\n return update({\n [GL.DRAW_FRAMEBUFFER_BINDING]: framebuffer,\n [GL.READ_FRAMEBUFFER_BINDING]: framebuffer\n });\n case GL.DRAW_FRAMEBUFFER:\n return update({[GL.DRAW_FRAMEBUFFER_BINDING]: framebuffer});\n case GL.READ_FRAMEBUFFER:\n return update({[GL.READ_FRAMEBUFFER_BINDING]: framebuffer});\n default:\n return null;\n }\n },\n bindBuffer: (update: UpdateFunc, target, buffer) => {\n const pname = {\n [GL.ARRAY_BUFFER]: [GL.ARRAY_BUFFER_BINDING],\n [GL.COPY_READ_BUFFER]: [GL.COPY_READ_BUFFER_BINDING],\n [GL.COPY_WRITE_BUFFER]: [GL.COPY_WRITE_BUFFER_BINDING],\n [GL.PIXEL_PACK_BUFFER]: [GL.PIXEL_PACK_BUFFER_BINDING],\n [GL.PIXEL_UNPACK_BUFFER]: [GL.PIXEL_UNPACK_BUFFER_BINDING]\n }[target];\n\n if (pname) {\n return update({[pname]: buffer});\n }\n // targets that should not be cached\n return {valueChanged: true};\n },\n\n blendColor: (update: UpdateFunc, r: number, g: number, b: number, a: number) =>\n update({\n [GL.BLEND_COLOR]: new Float32Array([r, g, b, a])\n }),\n\n blendEquation: (update: UpdateFunc, mode) =>\n update({\n [GL.BLEND_EQUATION_RGB]: mode,\n [GL.BLEND_EQUATION_ALPHA]: mode\n }),\n\n blendEquationSeparate: (update: UpdateFunc, modeRGB, modeAlpha) =>\n update({\n [GL.BLEND_EQUATION_RGB]: modeRGB,\n [GL.BLEND_EQUATION_ALPHA]: modeAlpha\n }),\n\n blendFunc: (update: UpdateFunc, src, dst) =>\n update({\n [GL.BLEND_SRC_RGB]: src,\n [GL.BLEND_DST_RGB]: dst,\n [GL.BLEND_SRC_ALPHA]: src,\n [GL.BLEND_DST_ALPHA]: dst\n }),\n\n blendFuncSeparate: (update: UpdateFunc, srcRGB, dstRGB, srcAlpha, dstAlpha) =>\n update({\n [GL.BLEND_SRC_RGB]: srcRGB,\n [GL.BLEND_DST_RGB]: dstRGB,\n [GL.BLEND_SRC_ALPHA]: srcAlpha,\n [GL.BLEND_DST_ALPHA]: dstAlpha\n }),\n\n clearColor: (update: UpdateFunc, r: number, g: number, b: number, a: number) =>\n update({\n [GL.COLOR_CLEAR_VALUE]: new Float32Array([r, g, b, a])\n }),\n\n clearDepth: (update: UpdateFunc, depth: number) =>\n update({\n [GL.DEPTH_CLEAR_VALUE]: depth\n }),\n\n clearStencil: (update: UpdateFunc, s: number) =>\n update({\n [GL.STENCIL_CLEAR_VALUE]: s\n }),\n\n colorMask: (update: UpdateFunc, r: number, g: number, b: number, a: number) =>\n update({\n [GL.COLOR_WRITEMASK]: [r, g, b, a]\n }),\n\n cullFace: (update: UpdateFunc, mode) =>\n update({\n [GL.CULL_FACE_MODE]: mode\n }),\n\n depthFunc: (update: UpdateFunc, func) =>\n update({\n [GL.DEPTH_FUNC]: func\n }),\n\n depthRange: (update: UpdateFunc, zNear: number, zFar: number) =>\n update({\n [GL.DEPTH_RANGE]: new Float32Array([zNear, zFar])\n }),\n\n depthMask: (update: UpdateFunc, mask: number) =>\n update({\n [GL.DEPTH_WRITEMASK]: mask\n }),\n\n frontFace: (update: UpdateFunc, face) =>\n update({\n [GL.FRONT_FACE]: face\n }),\n\n lineWidth: (update: UpdateFunc, width) =>\n update({\n [GL.LINE_WIDTH]: width\n }),\n\n polygonOffset: (update: UpdateFunc, factor, units) =>\n update({\n [GL.POLYGON_OFFSET_FACTOR]: factor,\n [GL.POLYGON_OFFSET_UNITS]: units\n }),\n\n sampleCoverage: (update: UpdateFunc, value, invert) =>\n update({\n [GL.SAMPLE_COVERAGE_VALUE]: value,\n [GL.SAMPLE_COVERAGE_INVERT]: invert\n }),\n\n scissor: (update: UpdateFunc, x, y, width, height) =>\n update({\n [GL.SCISSOR_BOX]: new Int32Array([x, y, width, height])\n }),\n\n stencilMask: (update: UpdateFunc, mask) =>\n update({\n [GL.STENCIL_WRITEMASK]: mask,\n [GL.STENCIL_BACK_WRITEMASK]: mask\n }),\n\n stencilMaskSeparate: (update: UpdateFunc, face, mask) =>\n update({\n [face === GL.FRONT ? GL.STENCIL_WRITEMASK : GL.STENCIL_BACK_WRITEMASK]: mask\n }),\n\n stencilFunc: (update: UpdateFunc, func, ref, mask) =>\n update({\n [GL.STENCIL_FUNC]: func,\n [GL.STENCIL_REF]: ref,\n [GL.STENCIL_VALUE_MASK]: mask,\n [GL.STENCIL_BACK_FUNC]: func,\n [GL.STENCIL_BACK_REF]: ref,\n [GL.STENCIL_BACK_VALUE_MASK]: mask\n }),\n\n stencilFuncSeparate: (update: UpdateFunc, face, func, ref, mask) =>\n update({\n [face === GL.FRONT ? GL.STENCIL_FUNC : GL.STENCIL_BACK_FUNC]: func,\n [face === GL.FRONT ? GL.STENCIL_REF : GL.STENCIL_BACK_REF]: ref,\n [face === GL.FRONT ? GL.STENCIL_VALUE_MASK : GL.STENCIL_BACK_VALUE_MASK]: mask\n }),\n\n stencilOp: (update: UpdateFunc, fail, zfail, zpass) =>\n update({\n [GL.STENCIL_FAIL]: fail,\n [GL.STENCIL_PASS_DEPTH_FAIL]: zfail,\n [GL.STENCIL_PASS_DEPTH_PASS]: zpass,\n [GL.STENCIL_BACK_FAIL]: fail,\n [GL.STENCIL_BACK_PASS_DEPTH_FAIL]: zfail,\n [GL.STENCIL_BACK_PASS_DEPTH_PASS]: zpass\n }),\n\n stencilOpSeparate: (update: UpdateFunc, face, fail, zfail, zpass) =>\n update({\n [face === GL.FRONT ? GL.STENCIL_FAIL : GL.STENCIL_BACK_FAIL]: fail,\n [face === GL.FRONT ? GL.STENCIL_PASS_DEPTH_FAIL : GL.STENCIL_BACK_PASS_DEPTH_FAIL]: zfail,\n [face === GL.FRONT ? GL.STENCIL_PASS_DEPTH_PASS : GL.STENCIL_BACK_PASS_DEPTH_PASS]: zpass\n }),\n\n viewport: (update: UpdateFunc, x, y, width, height) =>\n update({\n [GL.VIEWPORT]: [x, y, width, height]\n })\n};\n\n// GETTER TABLE - FOR READING OUT AN ENTIRE CONTEXT\n\nconst isEnabled = (gl: WebGL2RenderingContext, key) => gl.isEnabled(key);\n\n// Exceptions for any keys that cannot be queried by gl.getParameters\nexport const GL_PARAMETER_GETTERS = {\n [GL.BLEND]: isEnabled,\n [GL.CULL_FACE]: isEnabled,\n [GL.DEPTH_TEST]: isEnabled,\n [GL.DITHER]: isEnabled,\n [GL.POLYGON_OFFSET_FILL]: isEnabled,\n [GL.SAMPLE_ALPHA_TO_COVERAGE]: isEnabled,\n [GL.SAMPLE_COVERAGE]: isEnabled,\n [GL.SCISSOR_TEST]: isEnabled,\n [GL.STENCIL_TEST]: isEnabled,\n [GL.RASTERIZER_DISCARD]: isEnabled\n};\n\nexport const NON_CACHE_PARAMETERS = new Set([\n // setter not intercepted\n GL.ACTIVE_TEXTURE,\n GL.TRANSFORM_FEEDBACK_ACTIVE,\n GL.TRANSFORM_FEEDBACK_PAUSED,\n\n // setters bindBufferRange/bindBufferBase cannot be pruned based on cache\n GL.TRANSFORM_FEEDBACK_BUFFER_BINDING,\n GL.UNIFORM_BUFFER_BINDING,\n\n // states depending on VERTEX_ARRAY_BINDING\n GL.ELEMENT_ARRAY_BUFFER_BINDING,\n // states depending on READ_FRAMEBUFFER_BINDING\n GL.IMPLEMENTATION_COLOR_READ_FORMAT,\n GL.IMPLEMENTATION_COLOR_READ_TYPE,\n // states depending on FRAMEBUFFER_BINDING\n GL.READ_BUFFER,\n GL.DRAW_BUFFER0,\n GL.DRAW_BUFFER1,\n GL.DRAW_BUFFER2,\n GL.DRAW_BUFFER3,\n GL.DRAW_BUFFER4,\n GL.DRAW_BUFFER5,\n GL.DRAW_BUFFER6,\n GL.DRAW_BUFFER7,\n GL.DRAW_BUFFER8,\n GL.DRAW_BUFFER9,\n GL.DRAW_BUFFER10,\n GL.DRAW_BUFFER11,\n GL.DRAW_BUFFER12,\n GL.DRAW_BUFFER13,\n GL.DRAW_BUFFER14,\n GL.DRAW_BUFFER15,\n // states depending on ACTIVE_TEXTURE\n GL.SAMPLER_BINDING,\n GL.TEXTURE_BINDING_2D,\n GL.TEXTURE_BINDING_2D_ARRAY,\n GL.TEXTURE_BINDING_3D,\n GL.TEXTURE_BINDING_CUBE_MAP\n]);\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// Provides a unified API for getting and setting any WebGL parameter\n// Also knows default values of all parameters, enabling fast cache initialization\n// Provides base functionality for the state caching.\nimport type {GLParameters} from '@luma.gl/webgl/constants';\nimport {\n GL_PARAMETER_DEFAULTS,\n GL_PARAMETER_SETTERS,\n GL_COMPOSITE_PARAMETER_SETTERS,\n GL_PARAMETER_GETTERS\n} from './webgl-parameter-tables';\n\nexport type {GLParameters};\n\n/**\n * Sets any GL parameter regardless of function (gl.blendMode, ...)\n *\n * @note requires a `cache` object to be set on the context (lumaState.cache)\n * This object is used to fill in any missing values for composite setter functions\n */\nexport function setGLParameters(gl: WebGL2RenderingContext, parameters: GLParameters): void {\n if (isObjectEmpty(parameters)) {\n return;\n }\n\n const compositeSetters = {};\n\n // HANDLE PRIMITIVE SETTERS (and make note of any composite setters)\n\n for (const key in parameters) {\n const glConstant = Number(key);\n // @ts-ignore TODO\n const setter = GL_PARAMETER_SETTERS[key];\n if (setter) {\n // Composite setters should only be called once, so save them\n if (typeof setter === 'string') {\n // @ts-ignore TODO\n compositeSetters[setter] = true;\n } else {\n // if (gl[glConstant] !== undefined) {\n // TODO - added above check since this is being called on WebGL2 parameters in WebGL1...\n // TODO - deep equal on values? only call setter if value has changed?\n // NOTE - the setter will automatically update this.state\n // @ts-ignore TODO\n setter(gl, parameters[key], glConstant);\n }\n }\n }\n\n // HANDLE COMPOSITE SETTERS\n\n // NOTE: any non-provided values needed by composite setters are filled in from state cache\n // The cache parameter is automatically retrieved from the context\n // This depends on `trackContextState`, which is technically a \"circular\" dependency.\n // But it is too inconvenient to always require a cache parameter here.\n // This is the ONLY external dependency in this module/\n // @ts-expect-error\n const cache = gl.lumaState?.cache;\n if (cache) {\n for (const key in compositeSetters) {\n // TODO - avoid calling composite setters if values have not changed.\n // @ts-ignore TODO\n const compositeSetter = GL_COMPOSITE_PARAMETER_SETTERS[key];\n // Note - if `trackContextState` has been called,\n // the setter will automatically update this.state.cache\n compositeSetter(gl, parameters, cache);\n }\n }\n\n // Add a log for the else case?\n}\n\n/**\n * Reads the entire WebGL state from a context\n\n // default to querying all parameters\n\n * @returns - a newly created map, with values keyed by GL parameters\n *\n * @note Copies the state from a context (gl.getParameter should not be overriden)\n * Reads the entire WebGL state from a context\n *\n * @note This can generates a huge amount of synchronous driver roundtrips and should be\n * considered a very slow operation, to be used only if/when a context already manipulated\n * by external code needs to be synchronized for the first time\n */\nexport function getGLParameters(\n gl: WebGL2RenderingContext,\n parameters: keyof GLParameters | (keyof GLParameters)[] | GLParameters = GL_PARAMETER_DEFAULTS\n): GLParameters {\n // support both arrays of parameters and objects (keys represent parameters)\n\n if (typeof parameters === 'number') {\n // single GL enum\n const key = parameters;\n // @ts-ignore TODO\n const getter = GL_PARAMETER_GETTERS[key];\n return getter ? getter(gl, key) : gl.getParameter(key);\n }\n\n const parameterKeys = Array.isArray(parameters) ? parameters : Object.keys(parameters);\n\n const state: GLParameters = {};\n for (const key of parameterKeys) {\n // @ts-ignore TODO\n const getter = GL_PARAMETER_GETTERS[key];\n // @ts-ignore TODO\n state[key] = getter ? getter(gl, Number(key)) : gl.getParameter(Number(key));\n }\n return state;\n}\n\n/**\n * Reset all parameters to a (almost) pure context state\n * @note viewport and scissor will be set to the values in GL_PARAMETER_DEFAULTS,\n * NOT the canvas size dimensions, so they will have to be properly set after\n * calling this function.\n */\nexport function resetGLParameters(gl: WebGL2RenderingContext): void {\n setGLParameters(gl, GL_PARAMETER_DEFAULTS);\n}\n\n// Helpers\n\n// Returns true if given object is empty, false otherwise.\nfunction isObjectEmpty(object: Record): boolean {\n // @ts-ignore dummy key variable\n for (const key in object) {\n return false;\n }\n return true;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {TypedArray} from '@luma.gl/core';\n\n/** deeply compare two arrays */\nexport function deepArrayEqual(\n x: unknown | unknown[] | TypedArray,\n y: unknown | unknown[] | TypedArray\n): boolean {\n if (x === y) {\n return true;\n }\n if (isArray(x) && isArray(y) && x.length === y.length) {\n for (let i = 0; i < x.length; ++i) {\n if (x[i] !== y[i]) {\n return false;\n }\n }\n return true;\n }\n return false;\n}\n\nfunction isArray(x: unknown): x is unknown[] {\n return Array.isArray(x) || ArrayBuffer.isView(x);\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// @ts-nocheck TODO - fix\n\nimport {setGLParameters, getGLParameters} from '../parameters/unified-parameter-api';\nimport {deepArrayEqual} from './deep-array-equal';\nimport {\n GL_PARAMETER_DEFAULTS,\n GL_HOOKED_SETTERS,\n NON_CACHE_PARAMETERS\n} from '../parameters/webgl-parameter-tables';\n\n// HELPER CLASS - WebGLStateTracker\n\n/**\n * Support for listening to context state changes and intercepting state queries\n * NOTE: this system does not handle buffer bindings\n */\nexport class WebGLStateTracker {\n static get(gl: WebGL2RenderingContext): WebGLStateTracker {\n // @ts-expect-error\n return gl.lumaState as WebGLStateTracker;\n }\n\n gl: WebGL2RenderingContext;\n program: unknown = null;\n stateStack: object[] = [];\n enable = true;\n cache: Record = null!;\n log;\n\n protected initialized = false;\n\n constructor(\n gl: WebGL2RenderingContext,\n props?: {\n log; // Logging function, called when gl parameter change calls are actually issued\n }\n ) {\n this.gl = gl;\n this.log = props?.log || (() => {});\n\n this._updateCache = this._updateCache.bind(this);\n Object.seal(this);\n }\n\n push(values = {}) {\n this.stateStack.push({});\n }\n\n pop() {\n // assert(this.stateStack.length > 0);\n // Use the saved values in the state stack to restore parameters\n const oldValues = this.stateStack[this.stateStack.length - 1];\n setGLParameters(this.gl, oldValues);\n // Don't pop until we have reset parameters (to make sure other \"stack frames\" are not affected)\n this.stateStack.pop();\n }\n\n /**\n * Initialize WebGL state caching on a context\n * can be called multiple times to enable/disable\n *\n * @note After calling this function, context state will be cached\n * .push() and .pop() will be available for saving,\n * temporarily modifying, and then restoring state.\n */\n trackState(gl: WebGL2RenderingContext, options?: {copyState?: boolean}): void {\n this.cache = options?.copyState\n ? getGLParameters(gl)\n : Object.assign({}, GL_PARAMETER_DEFAULTS);\n\n if (this.initialized) {\n throw new Error('WebGLStateTracker');\n }\n this.initialized = true;\n\n // @ts-expect-error\n this.gl.lumaState = this;\n\n installProgramSpy(gl);\n\n // intercept all setter functions in the table\n for (const key in GL_HOOKED_SETTERS) {\n const setter = GL_HOOKED_SETTERS[key];\n installSetterSpy(gl, key, setter);\n }\n\n // intercept all getter functions in the table\n installGetterOverride(gl, 'getParameter');\n installGetterOverride(gl, 'isEnabled');\n }\n\n /**\n // interceptor for context set functions - update our cache and our stack\n // values (Object) - the key values for this setter\n * @param values\n * @returns\n */\n _updateCache(values: {[key: number | string]: any}) {\n let valueChanged = false;\n let oldValue; // = undefined\n\n const oldValues: {[key: number | string]: any} | null =\n this.stateStack.length > 0 ? this.stateStack[this.stateStack.length - 1] : null;\n\n for (const key in values) {\n // assert(key !== undefined);\n const value = values[key];\n const cached = this.cache[key];\n // Check that value hasn't already been shadowed\n if (!deepArrayEqual(value, cached)) {\n valueChanged = true;\n oldValue = cached;\n\n // First, save current value being shadowed\n // If a state stack frame is active, save the current parameter values for pop\n // but first check that value hasn't already been shadowed and saved\n if (oldValues && !(key in oldValues)) {\n oldValues[key] = cached;\n }\n\n // Save current value being shadowed\n this.cache[key] = value;\n }\n }\n\n return {valueChanged, oldValue};\n }\n}\n\n// HELPER FUNCTIONS - INSTALL GET/SET INTERCEPTORS (SPYS) ON THE CONTEXT\n\n/**\n// Overrides a WebGL2RenderingContext state \"getter\" function\n// to return values directly from cache\n * @param gl\n * @param functionName\n */\nfunction installGetterOverride(gl: WebGL2RenderingContext, functionName: string) {\n // Get the original function from the WebGL2RenderingContext\n const originalGetterFunc = gl[functionName].bind(gl);\n\n // Wrap it with a spy so that we can update our state cache when it gets called\n gl[functionName] = function get(pname) {\n if (pname === undefined || NON_CACHE_PARAMETERS.has(pname)) {\n // Invalid or blacklisted parameter, do not cache\n return originalGetterFunc(pname);\n }\n\n const glState = WebGLStateTracker.get(gl);\n if (!(pname in glState.cache)) {\n // WebGL limits are not prepopulated in the cache, call the original getter when first queried.\n glState.cache[pname] = originalGetterFunc(pname);\n }\n\n // Optionally call the original function to do a \"hard\" query from the WebGL2RenderingContext\n return glState.enable\n ? // Call the getter the params so that it can e.g. serve from a cache\n glState.cache[pname]\n : // Optionally call the original function to do a \"hard\" query from the WebGL2RenderingContext\n originalGetterFunc(pname);\n };\n\n // Set the name of this anonymous function to help in debugging and profiling\n Object.defineProperty(gl[functionName], 'name', {\n value: `${functionName}-from-cache`,\n configurable: false\n });\n}\n\n/**\n// Overrides a WebGL2RenderingContext state \"setter\" function\n// to call a setter spy before the actual setter. Allows us to keep a cache\n// updated with a copy of the WebGL context state.\n * @param gl\n * @param functionName\n * @param setter\n * @returns\n */\nfunction installSetterSpy(gl: WebGL2RenderingContext, functionName: string, setter: Function) {\n // Get the original function from the WebGL2RenderingContext\n if (!gl[functionName]) {\n // TODO - remove?\n // This could happen if we try to intercept WebGL2 method on a WebGL1 context\n return;\n }\n\n const originalSetterFunc = gl[functionName].bind(gl);\n\n // Wrap it with a spy so that we can update our state cache when it gets called\n gl[functionName] = function set(...params) {\n // Update the value\n // Call the setter with the state cache and the params so that it can store the parameters\n const glState = WebGLStateTracker.get(gl);\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const {valueChanged, oldValue} = setter(glState._updateCache, ...params);\n\n // Call the original WebGL2RenderingContext func to make sure the context actually gets updated\n if (valueChanged) {\n originalSetterFunc(...params);\n }\n\n // Note: if the original function fails to set the value, our state cache will be bad\n // No solution for this at the moment, but assuming that this is unlikely to be a real problem\n // We could call the setter after the originalSetterFunc. Concern is that this would\n // cause different behavior in debug mode, where originalSetterFunc can throw exceptions\n\n return oldValue;\n };\n\n // Set the name of this anonymous function to help in debugging and profiling\n Object.defineProperty(gl[functionName], 'name', {\n value: `${functionName}-to-cache`,\n configurable: false\n });\n}\n\nfunction installProgramSpy(gl: WebGL2RenderingContext): void {\n const originalUseProgram = gl.useProgram.bind(gl);\n\n gl.useProgram = function useProgramLuma(handle) {\n const glState = WebGLStateTracker.get(gl);\n if (glState.program !== handle) {\n originalUseProgram(handle);\n glState.program = handle;\n }\n };\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {getWebGLContextData} from './webgl-context-data';\n\n/**\n * ContextProps\n * @param onContextLost\n * @param onContextRestored *\n */\ntype ContextProps = {\n /** Called when a context is lost */\n onContextLost: (event: Event) => void;\n /** Called when a context is restored */\n onContextRestored: (event: Event) => void;\n};\n\n/**\n * Create a WebGL context for a canvas\n * Note calling this multiple time on the same canvas does return the same context\n * @param canvas A canvas element or offscreen canvas\n */\nexport function createBrowserContext(\n canvas: HTMLCanvasElement | OffscreenCanvas,\n props: ContextProps,\n webglContextAttributes: WebGLContextAttributes\n): WebGL2RenderingContext {\n // Try to extract any extra information about why context creation failed\n let errorMessage = '';\n const onCreateError = (event: Event) => {\n const statusMessage = (event as WebGLContextEvent).statusMessage;\n if (statusMessage) {\n errorMessage ||= statusMessage;\n }\n };\n canvas.addEventListener('webglcontextcreationerror', onCreateError, false);\n\n const allowSoftwareRenderer = webglContextAttributes.failIfMajorPerformanceCaveat !== true;\n\n const webglProps: WebGLContextAttributes = {\n preserveDrawingBuffer: true,\n ...webglContextAttributes,\n // Always start by requesting a high-performance context.\n failIfMajorPerformanceCaveat: true\n };\n\n // Create the desired context\n let gl: WebGL2RenderingContext | null = null;\n\n try {\n // Create a webgl2 context\n gl ||= canvas.getContext('webgl2', webglProps);\n if (!gl && webglProps.failIfMajorPerformanceCaveat) {\n errorMessage ||=\n 'Only software GPU is available. Set `failIfMajorPerformanceCaveat: false` to allow.';\n }\n\n // Creation failed with failIfMajorPerformanceCaveat - Try a Software GPU\n let softwareRenderer = false;\n if (!gl && allowSoftwareRenderer) {\n webglProps.failIfMajorPerformanceCaveat = false;\n gl = canvas.getContext('webgl2', webglProps);\n softwareRenderer = true;\n }\n\n if (!gl) {\n gl = canvas.getContext('webgl', {}) as WebGL2RenderingContext;\n if (gl) {\n gl = null;\n errorMessage ||= 'Your browser only supports WebGL1';\n }\n }\n\n if (!gl) {\n errorMessage ||= 'Your browser does not support WebGL';\n throw new Error(`Failed to create WebGL context: ${errorMessage}`);\n }\n\n // Initialize luma.gl specific context data\n const luma = getWebGLContextData(gl);\n luma.softwareRenderer = softwareRenderer;\n\n // Carefully extract and wrap callbacks to prevent addEventListener from rebinding them.\n const {onContextLost, onContextRestored} = props;\n canvas.addEventListener('webglcontextlost', (event: Event) => onContextLost(event), false);\n canvas.addEventListener(\n 'webglcontextrestored',\n (event: Event) => onContextRestored(event),\n false\n );\n\n return gl;\n } finally {\n canvas.removeEventListener('webglcontextcreationerror', onCreateError, false);\n }\n}\n\n/* TODO - can we call this asynchronously to catch the error events?\nexport async function createBrowserContextAsync(canvas: HTMLCanvasElement | OffscreenCanvas, props: ContextProps): Promise {\n props = {...DEFAULT_CONTEXT_PROPS, ...props};\n\n // Try to extract any extra information about why context creation failed\n let errorMessage = null;\n const onCreateError = (error) => (errorMessage = error.statusMessage || errorMessage);\n canvas.addEventListener('webglcontextcreationerror', onCreateError, false);\n\n const gl = createBrowserContext(canvas, props);\n\n // Give the listener a chance to fire\n await new Promise(resolve => setTimeout(resolve, 0));\n\n canvas.removeEventListener('webglcontextcreationerror', onCreateError, false);\n\n return gl;\n}\n*/\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {GLExtensions} from '@luma.gl/webgl/constants';\n\n/** Ensure extensions are only requested once */\nexport function getWebGLExtension(\n gl: WebGL2RenderingContext,\n name: string,\n extensions: GLExtensions\n): unknown {\n // @ts-ignore TODO\n if (extensions[name] === undefined) {\n // @ts-ignore TODO\n extensions[name] = gl.getExtension(name) || null;\n }\n // @ts-ignore TODO\n return extensions[name];\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {DeviceInfo} from '@luma.gl/core';\nimport {GL, GLExtensions} from '@luma.gl/webgl/constants';\nimport {getWebGLExtension} from '../../context/helpers/webgl-extensions';\n\n/** @returns strings identifying the GPU vendor and driver. */\nexport function getDeviceInfo(gl: WebGL2RenderingContext, extensions: GLExtensions): DeviceInfo {\n // \"Masked\" info is always available, but don't contain much useful information\n const vendorMasked = gl.getParameter(GL.VENDOR);\n const rendererMasked = gl.getParameter(GL.RENDERER);\n\n // If we are lucky, unmasked info is available\n // https://www.khronos.org/registry/webgl/extensions/WEBGL_debug_renderer_info/\n getWebGLExtension(gl, 'WEBGL_debug_renderer_info', extensions);\n const ext = extensions.WEBGL_debug_renderer_info;\n const vendorUnmasked = gl.getParameter(ext ? ext.UNMASKED_VENDOR_WEBGL : GL.VENDOR);\n const rendererUnmasked = gl.getParameter(ext ? ext.UNMASKED_RENDERER_WEBGL : GL.RENDERER);\n const vendor = vendorUnmasked || vendorMasked;\n const renderer = rendererUnmasked || rendererMasked;\n\n // Driver version\n const version = gl.getParameter(GL.VERSION) as string;\n\n // \"Sniff\" the GPU type and backend from the info. This works best if unmasked info is available.\n const gpu = identifyGPUVendor(vendor, renderer);\n const gpuBackend = identifyGPUBackend(vendor, renderer);\n const gpuType = identifyGPUType(vendor, renderer);\n\n // Determine GLSL version\n // For now, skip parsing of the long version string, just use context type below to deduce version\n // const version = gl.getParameter(GL.SHADING_LANGUAGE_VERSION) as string;\n // const shadingLanguageVersion = parseGLSLVersion(version);\n const shadingLanguage = 'glsl';\n const shadingLanguageVersion = 300;\n\n return {\n type: 'webgl',\n gpu,\n gpuType,\n gpuBackend,\n vendor,\n renderer,\n version,\n shadingLanguage,\n shadingLanguageVersion\n };\n}\n\n/** \"Sniff\" the GPU type from the info. This works best if unmasked info is available. */\nfunction identifyGPUVendor(\n vendor: string,\n renderer: string\n): 'nvidia' | 'intel' | 'apple' | 'amd' | 'software' | 'unknown' {\n if (/NVIDIA/i.exec(vendor) || /NVIDIA/i.exec(renderer)) {\n return 'nvidia';\n }\n if (/INTEL/i.exec(vendor) || /INTEL/i.exec(renderer)) {\n return 'intel';\n }\n if (/Apple/i.exec(vendor) || /Apple/i.exec(renderer)) {\n return 'apple';\n }\n if (\n /AMD/i.exec(vendor) ||\n /AMD/i.exec(renderer) ||\n /ATI/i.exec(vendor) ||\n /ATI/i.exec(renderer)\n ) {\n return 'amd';\n }\n if (/SwiftShader/i.exec(vendor) || /SwiftShader/i.exec(renderer)) {\n return 'software';\n }\n\n return 'unknown';\n}\n\n/** \"Sniff\" the GPU backend from the info. This works best if unmasked info is available. */\nfunction identifyGPUBackend(vendor: string, renderer: string): 'opengl' | 'metal' | 'unknown' {\n if (/Metal/i.exec(vendor) || /Metal/i.exec(renderer)) {\n return 'metal';\n }\n if (/ANGLE/i.exec(vendor) || /ANGLE/i.exec(renderer)) {\n return 'opengl';\n }\n return 'unknown';\n}\n\nfunction identifyGPUType(\n vendor: string,\n renderer: string\n): 'discrete' | 'integrated' | 'cpu' | 'unknown' {\n if (/SwiftShader/i.exec(vendor) || /SwiftShader/i.exec(renderer)) {\n return 'cpu';\n }\n\n const gpuVendor = identifyGPUVendor(vendor, renderer);\n switch (gpuVendor) {\n case 'apple':\n return isAppleSiliconGPU(vendor, renderer) ? 'integrated' : 'unknown';\n case 'intel':\n return 'integrated';\n case 'software':\n return 'cpu';\n case 'unknown':\n return 'unknown';\n default:\n return 'discrete';\n }\n}\n\nfunction isAppleSiliconGPU(vendor: string, renderer: string): boolean {\n return /Apple (M\\d|A\\d|GPU)/i.test(`${vendor} ${renderer}`);\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {GL} from '@luma.gl/webgl/constants';\nimport {VertexFormat, NormalizedDataType} from '@luma.gl/core';\n\ntype GLDataType =\n | GL.UNSIGNED_BYTE\n | GL.BYTE\n | GL.UNSIGNED_SHORT\n | GL.SHORT\n | GL.UNSIGNED_INT\n | GL.INT\n | GL.HALF_FLOAT\n | GL.FLOAT;\n\n/** Get vertex format from GL constants */\nexport function getVertexFormatFromGL(type: GLDataType, components: 1 | 2 | 3 | 4): VertexFormat {\n const base = getVertexTypeFromGL(type);\n // biome-ignore format: preserve layout\n switch (components) {\n case 1: return base;\n case 2: return `${base}x2`;\n // @ts-expect-error TODO deal with lack of \"unaligned\" formats\n case 3: return `${base}x3`;\n case 4: return `${base}x4`;\n }\n // @ts-ignore unreachable\n throw new Error(String(components));\n}\n\n/** Get data type from GL constants */\nexport function getVertexTypeFromGL(type: GLDataType, normalized = false): NormalizedDataType {\n // biome-ignore format: preserve layout\n switch (type) {\n // WebGPU does not support normalized 32 bit integer attributes\n case GL.INT: return normalized ? 'sint32' : 'sint32';\n case GL.UNSIGNED_INT: return normalized ? 'uint32' : 'uint32';\n case GL.SHORT: return normalized ? 'sint16' : 'unorm16';\n case GL.UNSIGNED_SHORT: return normalized ? 'uint16' : 'unorm16';\n case GL.BYTE: return normalized ? 'sint8' : 'snorm16';\n case GL.UNSIGNED_BYTE: return normalized ? 'uint8' : 'unorm8';\n case GL.FLOAT: return 'float32';\n case GL.HALF_FLOAT: return 'float16';\n }\n // @ts-ignore unreachable\n throw new Error(String(type));\n}\n\nexport function getGLFromVertexType(\n dataType: NormalizedDataType\n):\n | GL.UNSIGNED_BYTE\n | GL.BYTE\n | GL.UNSIGNED_SHORT\n | GL.SHORT\n | GL.UNSIGNED_INT\n | GL.INT\n | GL.HALF_FLOAT\n | GL.FLOAT {\n // biome-ignore format: preserve layout\n switch (dataType) {\n case 'uint8': return GL.UNSIGNED_BYTE;\n case 'sint8': return GL.BYTE;\n case 'unorm8': return GL.UNSIGNED_BYTE;\n case 'snorm8': return GL.BYTE;\n case 'uint16': return GL.UNSIGNED_SHORT;\n case 'sint16': return GL.SHORT;\n case 'unorm16': return GL.UNSIGNED_SHORT;\n case 'snorm16': return GL.SHORT;\n case 'uint32': return GL.UNSIGNED_INT;\n case 'sint32': return GL.INT;\n // WebGPU does not support normalized 32 bit integer attributes\n // case 'unorm32': return GL.UNSIGNED_INT;\n // case 'snorm32': return GL.INT;\n case 'float16': return GL.HALF_FLOAT;\n case 'float32': return GL.FLOAT;\n }\n // @ts-ignore unreachable\n throw new Error(String(dataType));\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {\n DeviceFeature,\n TextureFormat,\n TextureFormatCapabilities,\n DeviceTextureFormatCapabilities\n} from '@luma.gl/core';\nimport {textureFormatDecoder} from '@luma.gl/core';\nimport {GL, GLPixelType, GLExtensions, GLTexelDataFormat} from '@luma.gl/webgl/constants';\nimport {getWebGLExtension} from '../../context/helpers/webgl-extensions';\nimport {getGLFromVertexType} from './webgl-vertex-formats';\n\n/* eslint-disable camelcase */\n\n// TEXTURE FEATURES\n\n// Define local webgl extension strings to optimize minification\nconst X_S3TC = 'WEBGL_compressed_texture_s3tc'; // BC1, BC2, BC3\nconst X_S3TC_SRGB = 'WEBGL_compressed_texture_s3tc_srgb'; // BC1, BC2, BC3\nconst X_RGTC = 'EXT_texture_compression_rgtc'; // BC4, BC5\nconst X_BPTC = 'EXT_texture_compression_bptc'; // BC6, BC7\nconst X_ETC2 = 'WEBGL_compressed_texture_etc'; // Renamed from 'WEBGL_compressed_texture_es3'\nconst X_ASTC = 'WEBGL_compressed_texture_astc';\nconst X_ETC1 = 'WEBGL_compressed_texture_etc1';\nconst X_PVRTC = 'WEBGL_compressed_texture_pvrtc';\nconst X_ATC = 'WEBGL_compressed_texture_atc';\n\n// Define local webgl extension strings to optimize minification\nconst EXT_texture_norm16 = 'EXT_texture_norm16';\nconst EXT_render_snorm = 'EXT_render_snorm';\nconst EXT_color_buffer_float = 'EXT_color_buffer_float';\nconst SNORM8_COLOR_RENDERABLE: DeviceFeature = 'snorm8-renderable-webgl';\nconst NORM16_COLOR_RENDERABLE: DeviceFeature = 'norm16-renderable-webgl';\nconst SNORM16_COLOR_RENDERABLE: DeviceFeature = 'snorm16-renderable-webgl';\nconst FLOAT16_COLOR_RENDERABLE: DeviceFeature = 'float16-renderable-webgl';\nconst FLOAT32_COLOR_RENDERABLE: DeviceFeature = 'float32-renderable-webgl';\nconst RGB9E5UFLOAT_COLOR_RENDERABLE: DeviceFeature = 'rgb9e5ufloat-renderable-webgl';\n\ntype TextureFeatureDefinition = {\n extensions?: string[];\n features?: DeviceFeature[];\n};\n\n// biome-ignore format: preserve layout\nexport const TEXTURE_FEATURES: Partial> = {\n 'float32-renderable-webgl': {extensions: [EXT_color_buffer_float]},\n 'float16-renderable-webgl': {extensions: ['EXT_color_buffer_half_float']},\n 'rgb9e5ufloat-renderable-webgl': {extensions: ['WEBGL_render_shared_exponent']},\n 'snorm8-renderable-webgl': {extensions: [EXT_render_snorm]},\n 'norm16-webgl': {extensions: [EXT_texture_norm16]},\n 'norm16-renderable-webgl': {features: ['norm16-webgl']},\n 'snorm16-renderable-webgl': {features: ['norm16-webgl'], extensions: [EXT_render_snorm]},\n\n 'float32-filterable': {extensions: ['OES_texture_float_linear']},\n 'float16-filterable-webgl': {extensions: ['OES_texture_half_float_linear']},\n 'texture-filterable-anisotropic-webgl': {extensions: ['EXT_texture_filter_anisotropic']},\n\n 'texture-blend-float-webgl': {extensions: ['EXT_float_blend']},\n\n 'texture-compression-bc': {extensions: [X_S3TC, X_S3TC_SRGB, X_RGTC, X_BPTC]},\n // 'texture-compression-bc3-srgb-webgl': [X_S3TC_SRGB],\n // 'texture-compression-bc3-webgl': [X_S3TC],\n 'texture-compression-bc5-webgl': {extensions: [X_RGTC]},\n 'texture-compression-bc7-webgl': {extensions: [X_BPTC]},\n 'texture-compression-etc2': {extensions: [X_ETC2]},\n 'texture-compression-astc': {extensions: [X_ASTC]},\n 'texture-compression-etc1-webgl': {extensions: [X_ETC1]},\n 'texture-compression-pvrtc-webgl': {extensions: [X_PVRTC]},\n 'texture-compression-atc-webgl': {extensions: [X_ATC]}\n};\n\nexport function isTextureFeature(feature: DeviceFeature): boolean {\n return feature in TEXTURE_FEATURES;\n}\n\n/** Checks a texture feature (for Device.features). Mainly compressed texture support */\nexport function checkTextureFeature(\n gl: WebGL2RenderingContext,\n feature: DeviceFeature,\n extensions: GLExtensions\n): boolean {\n return hasTextureFeature(gl, feature, extensions, new Set());\n}\n\nfunction hasTextureFeature(\n gl: WebGL2RenderingContext,\n feature: DeviceFeature,\n extensions: GLExtensions,\n seenFeatures: Set\n): boolean {\n const definition = TEXTURE_FEATURES[feature];\n if (!definition) {\n return false;\n }\n\n if (seenFeatures.has(feature)) {\n return false;\n }\n\n seenFeatures.add(feature);\n const hasDependentFeatures = (definition.features || []).every(dependentFeature =>\n hasTextureFeature(gl, dependentFeature, extensions, seenFeatures)\n );\n seenFeatures.delete(feature);\n if (!hasDependentFeatures) {\n return false;\n }\n\n return (definition.extensions || []).every(extension =>\n Boolean(getWebGLExtension(gl, extension, extensions))\n );\n}\n\n// TEXTURE FORMATS\n\n/** Map a format to webgl and constants */\ntype WebGLFormatInfo = {\n gl?: GL;\n /** compressed */\n x?: string;\n /** color-renderable capability gate. false means never color-renderable on WebGL. */\n r?: DeviceFeature | false;\n types?: GLPixelType[];\n dataFormat?: GLTexelDataFormat;\n /** if depthTexture is set this is a depth/stencil format that can be set to a texture */\n depthTexture?: boolean;\n /** @deprecated can this format be used with renderbuffers */\n rb?: boolean;\n};\n\n// TABLES\n\n/**\n * Texture format data -\n * Exported but can change without notice\n */\n// biome-ignore format: preserve layout\nexport const WEBGL_TEXTURE_FORMATS: Record = {\n // 8-bit formats\n 'r8unorm': {gl: GL.R8, rb: true},\n 'r8snorm': {gl: GL.R8_SNORM, r: SNORM8_COLOR_RENDERABLE},\n 'r8uint': {gl: GL.R8UI, rb: true},\n 'r8sint': {gl: GL.R8I, rb: true},\n\n // 16-bit formats\n 'rg8unorm': {gl: GL.RG8, rb: true},\n 'rg8snorm': {gl: GL.RG8_SNORM, r: SNORM8_COLOR_RENDERABLE},\n 'rg8uint': {gl: GL.RG8UI, rb: true},\n 'rg8sint': {gl: GL.RG8I, rb: true},\n\n 'r16uint': {gl: GL.R16UI, rb: true},\n 'r16sint': {gl: GL.R16I, rb: true},\n 'r16float': {gl: GL.R16F, rb: true, r: FLOAT16_COLOR_RENDERABLE},\n 'r16unorm': {gl: GL.R16_EXT, rb: true, r: NORM16_COLOR_RENDERABLE},\n 'r16snorm': {gl: GL.R16_SNORM_EXT, r: SNORM16_COLOR_RENDERABLE},\n\n // Packed 16-bit formats\n 'rgba4unorm-webgl': {gl: GL.RGBA4, rb: true},\n 'rgb565unorm-webgl': {gl: GL.RGB565, rb: true},\n 'rgb5a1unorm-webgl': {gl: GL.RGB5_A1, rb: true},\n\n // 24-bit formats\n 'rgb8unorm-webgl': {gl: GL.RGB8},\n 'rgb8snorm-webgl': {gl: GL.RGB8_SNORM},\n\n // 32-bit formats\n 'rgba8unorm': {gl: GL.RGBA8},\n 'rgba8unorm-srgb': {gl: GL.SRGB8_ALPHA8},\n 'rgba8snorm': {gl: GL.RGBA8_SNORM, r: SNORM8_COLOR_RENDERABLE},\n 'rgba8uint': {gl: GL.RGBA8UI},\n 'rgba8sint': {gl: GL.RGBA8I},\n // reverse colors, webgpu only\n 'bgra8unorm': {},\n 'bgra8unorm-srgb': {},\n\n 'rg16uint': {gl: GL.RG16UI},\n 'rg16sint': {gl: GL.RG16I},\n 'rg16float': {gl: GL.RG16F, rb: true, r: FLOAT16_COLOR_RENDERABLE},\n 'rg16unorm': {gl: GL.RG16_EXT, r: NORM16_COLOR_RENDERABLE},\n 'rg16snorm': {gl: GL.RG16_SNORM_EXT, r: SNORM16_COLOR_RENDERABLE},\n\n 'r32uint': {gl: GL.R32UI, rb: true},\n 'r32sint': {gl: GL.R32I, rb: true},\n 'r32float': {gl: GL.R32F, r: FLOAT32_COLOR_RENDERABLE},\n\n // Packed 32-bit formats\n 'rgb9e5ufloat': {gl: GL.RGB9_E5, r: RGB9E5UFLOAT_COLOR_RENDERABLE}, // , filter: true},\n 'rg11b10ufloat': {gl: GL.R11F_G11F_B10F, rb: true},\n 'rgb10a2unorm': {gl: GL.RGB10_A2, rb: true},\n 'rgb10a2uint': {gl: GL.RGB10_A2UI, rb: true},\n\n // 48-bit formats\n 'rgb16unorm-webgl': {gl: GL.RGB16_EXT, r: false}, // rgb not renderable\n 'rgb16snorm-webgl': {gl: GL.RGB16_SNORM_EXT, r: false}, // rgb not renderable\n\n // 64-bit formats\n 'rg32uint': {gl: GL.RG32UI, rb: true},\n 'rg32sint': {gl: GL.RG32I, rb: true},\n 'rg32float': {gl: GL.RG32F, rb: true, r: FLOAT32_COLOR_RENDERABLE},\n 'rgba16uint': {gl: GL.RGBA16UI, rb: true},\n 'rgba16sint': {gl: GL.RGBA16I, rb: true},\n 'rgba16float': {gl: GL.RGBA16F, r: FLOAT16_COLOR_RENDERABLE},\n 'rgba16unorm': {gl: GL.RGBA16_EXT, rb: true, r: NORM16_COLOR_RENDERABLE},\n 'rgba16snorm': {gl: GL.RGBA16_SNORM_EXT, r: SNORM16_COLOR_RENDERABLE},\n\n // 96-bit formats (deprecated!)\n 'rgb32float-webgl': {gl: GL.RGB32F, x: EXT_color_buffer_float, r: FLOAT32_COLOR_RENDERABLE, dataFormat: GL.RGB, types: [GL.FLOAT]},\n\n // 128-bit formats\n 'rgba32uint': {gl: GL.RGBA32UI, rb: true},\n 'rgba32sint': {gl: GL.RGBA32I, rb: true},\n 'rgba32float': {gl: GL.RGBA32F, rb: true, r: FLOAT32_COLOR_RENDERABLE},\n\n // Depth and stencil formats\n 'stencil8': {gl: GL.STENCIL_INDEX8, rb: true}, // 8 stencil bits\n\n 'depth16unorm': {gl: GL.DEPTH_COMPONENT16, dataFormat: GL.DEPTH_COMPONENT, types: [GL.UNSIGNED_SHORT], rb: true}, // 16 depth bits\n 'depth24plus': {gl: GL.DEPTH_COMPONENT24, dataFormat: GL.DEPTH_COMPONENT, types: [GL.UNSIGNED_INT]},\n 'depth32float': {gl: GL.DEPTH_COMPONENT32F, dataFormat: GL.DEPTH_COMPONENT, types: [GL.FLOAT], rb: true},\n\n // The depth component of the \"depth24plus\" and \"depth24plus-stencil8\" formats may be implemented as either a 24-bit depth value or a \"depth32float\" value.\n 'depth24plus-stencil8': {gl: GL.DEPTH24_STENCIL8, rb: true, depthTexture: true, dataFormat: GL.DEPTH_STENCIL, types: [GL.UNSIGNED_INT_24_8]},\n // \"depth32float-stencil8\" feature - TODO below is render buffer only?\n 'depth32float-stencil8': {gl: GL.DEPTH32F_STENCIL8, dataFormat: GL.DEPTH_STENCIL, types: [GL.FLOAT_32_UNSIGNED_INT_24_8_REV], rb: true},\n\n // BC compressed formats: check device.features.has(\"texture-compression-bc\");\n\n 'bc1-rgb-unorm-webgl': {gl: GL.COMPRESSED_RGB_S3TC_DXT1_EXT, x: X_S3TC},\n 'bc1-rgb-unorm-srgb-webgl': {gl: GL.COMPRESSED_SRGB_S3TC_DXT1_EXT, x: X_S3TC_SRGB},\n\n 'bc1-rgba-unorm': {gl: GL.COMPRESSED_RGBA_S3TC_DXT1_EXT, x: X_S3TC},\n 'bc1-rgba-unorm-srgb': {gl: GL.COMPRESSED_SRGB_S3TC_DXT1_EXT, x: X_S3TC_SRGB},\n 'bc2-rgba-unorm': {gl: GL.COMPRESSED_RGBA_S3TC_DXT3_EXT, x: X_S3TC},\n 'bc2-rgba-unorm-srgb': {gl: GL.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT, x: X_S3TC_SRGB},\n 'bc3-rgba-unorm': {gl: GL.COMPRESSED_RGBA_S3TC_DXT5_EXT, x: X_S3TC},\n 'bc3-rgba-unorm-srgb': {gl: GL.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT, x: X_S3TC_SRGB},\n 'bc4-r-unorm': {gl: GL.COMPRESSED_RED_RGTC1_EXT, x: X_RGTC},\n 'bc4-r-snorm': {gl: GL.COMPRESSED_SIGNED_RED_RGTC1_EXT, x: X_RGTC},\n 'bc5-rg-unorm': {gl: GL.COMPRESSED_RED_GREEN_RGTC2_EXT, x: X_RGTC},\n 'bc5-rg-snorm': {gl: GL.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT, x: X_RGTC},\n 'bc6h-rgb-ufloat': {gl: GL.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT, x: X_BPTC},\n 'bc6h-rgb-float': {gl: GL.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT, x: X_BPTC},\n 'bc7-rgba-unorm': {gl: GL.COMPRESSED_RGBA_BPTC_UNORM_EXT, x: X_BPTC},\n 'bc7-rgba-unorm-srgb': {gl: GL.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT, x: X_BPTC},\n\n // WEBGL_compressed_texture_etc: device.features.has(\"texture-compression-etc2\")\n // Note: Supposedly guaranteed availability compressed formats in WebGL2, but through CPU decompression\n\n 'etc2-rgb8unorm': {gl: GL.COMPRESSED_RGB8_ETC2},\n 'etc2-rgb8unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ETC2},\n 'etc2-rgb8a1unorm': {gl: GL.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2},\n 'etc2-rgb8a1unorm-srgb': {gl: GL.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2},\n 'etc2-rgba8unorm': {gl: GL.COMPRESSED_RGBA8_ETC2_EAC},\n 'etc2-rgba8unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC},\n\n 'eac-r11unorm': {gl: GL.COMPRESSED_R11_EAC},\n 'eac-r11snorm': {gl: GL.COMPRESSED_SIGNED_R11_EAC},\n 'eac-rg11unorm': {gl: GL.COMPRESSED_RG11_EAC},\n 'eac-rg11snorm': {gl: GL.COMPRESSED_SIGNED_RG11_EAC},\n\n // X_ASTC compressed formats: device.features.has(\"texture-compression-astc\")\n\n 'astc-4x4-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_4x4_KHR},\n 'astc-4x4-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR},\n 'astc-5x4-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_5x4_KHR},\n 'astc-5x4-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR},\n 'astc-5x5-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_5x5_KHR},\n 'astc-5x5-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR},\n 'astc-6x5-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_6x5_KHR},\n 'astc-6x5-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR},\n 'astc-6x6-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_6x6_KHR},\n 'astc-6x6-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR},\n 'astc-8x5-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_8x5_KHR},\n 'astc-8x5-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR},\n 'astc-8x6-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_8x6_KHR},\n 'astc-8x6-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR},\n 'astc-8x8-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_8x8_KHR},\n 'astc-8x8-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR},\n 'astc-10x5-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_10x5_KHR},\n 'astc-10x5-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR},\n 'astc-10x6-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_10x6_KHR},\n 'astc-10x6-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR},\n 'astc-10x8-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_10x8_KHR},\n 'astc-10x8-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR},\n 'astc-10x10-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_10x10_KHR},\n 'astc-10x10-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR},\n 'astc-12x10-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_12x10_KHR},\n 'astc-12x10-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR},\n 'astc-12x12-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_12x12_KHR},\n 'astc-12x12-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR},\n\n // WEBGL_compressed_texture_pvrtc\n\n 'pvrtc-rgb4unorm-webgl': {gl: GL.COMPRESSED_RGB_PVRTC_4BPPV1_IMG},\n 'pvrtc-rgba4unorm-webgl': {gl: GL.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG},\n 'pvrtc-rgb2unorm-webgl': {gl: GL.COMPRESSED_RGB_PVRTC_2BPPV1_IMG},\n 'pvrtc-rgba2unorm-webgl': {gl: GL.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG},\n\n // WEBGL_compressed_texture_etc1\n\n 'etc1-rbg-unorm-webgl': {gl: GL.COMPRESSED_RGB_ETC1_WEBGL},\n\n // WEBGL_compressed_texture_atc\n\n 'atc-rgb-unorm-webgl': {gl: GL.COMPRESSED_RGB_ATC_WEBGL},\n 'atc-rgba-unorm-webgl': {gl: GL.COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL},\n 'atc-rgbai-unorm-webgl': {gl: GL.COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL}\n};\n\n// FUNCTIONS\n\n/** Checks if a texture format is supported, renderable, filterable etc */\nexport function getTextureFormatCapabilitiesWebGL(\n gl: WebGL2RenderingContext,\n formatSupport: TextureFormatCapabilities,\n extensions: GLExtensions\n): DeviceTextureFormatCapabilities {\n let supported = formatSupport.create;\n const webglFormatInfo = WEBGL_TEXTURE_FORMATS[formatSupport.format];\n\n // Support Check that we have a GL constant\n if (webglFormatInfo?.gl === undefined) {\n supported = false;\n }\n\n if (webglFormatInfo?.x) {\n supported = supported && Boolean(getWebGLExtension(gl, webglFormatInfo.x, extensions));\n }\n\n // WebGL2 exposes STENCIL_INDEX8 for renderbuffers, but standalone stencil textures are not\n // valid texture storage targets. Report them as unsupported texture formats to avoid invalid\n // constructor paths and misleading capability checks.\n if (formatSupport.format === 'stencil8') {\n supported = false;\n }\n\n const renderFeatureSupported =\n webglFormatInfo?.r === false\n ? false\n : webglFormatInfo?.r === undefined || checkTextureFeature(gl, webglFormatInfo.r, extensions);\n const renderable =\n supported &&\n formatSupport.render &&\n renderFeatureSupported &&\n isColorRenderableTextureFormat(gl, formatSupport.format, extensions);\n\n return {\n format: formatSupport.format,\n // @ts-ignore\n create: supported && formatSupport.create,\n // @ts-ignore\n render: renderable,\n // @ts-ignore\n filter: supported && formatSupport.filter,\n // @ts-ignore\n blend: supported && formatSupport.blend,\n // @ts-ignore\n store: supported && formatSupport.store\n };\n}\n\nfunction isColorRenderableTextureFormat(\n gl: WebGL2RenderingContext,\n format: TextureFormat,\n extensions: GLExtensions\n): boolean {\n const webglFormatInfo = WEBGL_TEXTURE_FORMATS[format];\n const internalFormat = webglFormatInfo?.gl;\n if (internalFormat === undefined) {\n return false;\n }\n\n if (webglFormatInfo?.x && !getWebGLExtension(gl, webglFormatInfo.x, extensions)) {\n return false;\n }\n\n const previousTexture = gl.getParameter(GL.TEXTURE_BINDING_2D) as WebGLTexture | null;\n const previousFramebuffer = gl.getParameter(GL.FRAMEBUFFER_BINDING) as WebGLFramebuffer | null;\n const texture = gl.createTexture();\n const framebuffer = gl.createFramebuffer();\n if (!texture || !framebuffer) {\n return false;\n }\n\n // Isolate the probe from any prior driver errors so the result reflects only this format.\n const noError = Number(GL.NO_ERROR);\n let error = Number(gl.getError());\n while (error !== noError) {\n error = gl.getError();\n }\n\n let renderable = false;\n try {\n gl.bindTexture(GL.TEXTURE_2D, texture);\n gl.texStorage2D(GL.TEXTURE_2D, 1, internalFormat, 1, 1);\n if (Number(gl.getError()) !== noError) {\n return false;\n }\n\n gl.bindFramebuffer(GL.FRAMEBUFFER, framebuffer);\n gl.framebufferTexture2D(GL.FRAMEBUFFER, GL.COLOR_ATTACHMENT0, GL.TEXTURE_2D, texture, 0);\n renderable =\n Number(gl.checkFramebufferStatus(GL.FRAMEBUFFER)) === Number(GL.FRAMEBUFFER_COMPLETE) &&\n Number(gl.getError()) === noError;\n } finally {\n gl.bindFramebuffer(GL.FRAMEBUFFER, previousFramebuffer);\n gl.deleteFramebuffer(framebuffer);\n gl.bindTexture(GL.TEXTURE_2D, previousTexture);\n gl.deleteTexture(texture);\n }\n\n return renderable;\n}\n\n/** Get parameters necessary to work with format in WebGL: internalFormat, dataFormat, type, compressed, */\nexport function getTextureFormatWebGL(format: TextureFormat): {\n internalFormat: GL;\n format: GLTexelDataFormat;\n type: GLPixelType;\n compressed: boolean;\n} {\n const formatData = WEBGL_TEXTURE_FORMATS[format];\n const webglFormat = convertTextureFormatToGL(format);\n const decoded = textureFormatDecoder.getInfo(format);\n\n if (decoded.compressed) {\n // TODO: Unclear whether this is always valid, this may be why ETC2 RGBA8 fails.\n formatData.dataFormat = webglFormat as GLTexelDataFormat;\n }\n\n return {\n internalFormat: webglFormat,\n format:\n formatData?.dataFormat ||\n getWebGLPixelDataFormat(decoded.channels, decoded.integer, decoded.normalized, webglFormat),\n // depth formats don't have a type\n type: decoded.dataType\n ? getGLFromVertexType(decoded.dataType)\n : formatData?.types?.[0] || GL.UNSIGNED_BYTE,\n compressed: decoded.compressed || false\n };\n}\n\nexport function getDepthStencilAttachmentWebGL(\n format: TextureFormat\n): GL.DEPTH_ATTACHMENT | GL.STENCIL_ATTACHMENT | GL.DEPTH_STENCIL_ATTACHMENT {\n const formatInfo = textureFormatDecoder.getInfo(format);\n switch (formatInfo.attachment) {\n case 'depth':\n return GL.DEPTH_ATTACHMENT;\n case 'stencil':\n return GL.STENCIL_ATTACHMENT;\n case 'depth-stencil':\n return GL.DEPTH_STENCIL_ATTACHMENT;\n default:\n throw new Error(`Not a depth stencil format: ${format}`);\n }\n}\n\n/** TODO - VERY roundabout legacy way of calculating bytes per pixel */\nexport function getTextureFormatBytesPerPixel(format: TextureFormat): number {\n const formatInfo = textureFormatDecoder.getInfo(format);\n return formatInfo.bytesPerPixel;\n}\n\n// DATA TYPE HELPERS\n\nexport function getWebGLPixelDataFormat(\n channels: 'r' | 'rg' | 'rgb' | 'rgba' | 'bgra',\n integer: boolean,\n normalized: boolean,\n format: GL\n): GLTexelDataFormat {\n // WebGL1 formats use same internalFormat\n if (format === GL.RGBA || format === GL.RGB) {\n return format;\n }\n // biome-ignore format: preserve layout\n switch (channels) {\n case 'r': return integer && !normalized ? GL.RED_INTEGER : GL.RED;\n case 'rg': return integer && !normalized ? GL.RG_INTEGER : GL.RG;\n case 'rgb': return integer && !normalized ? GL.RGB_INTEGER : GL.RGB;\n case 'rgba': return integer && !normalized ? GL.RGBA_INTEGER : GL.RGBA;\n case 'bgra': throw new Error('bgra pixels not supported by WebGL');\n default: return GL.RGBA;\n }\n}\n\n/**\n * Map WebGPU style texture format strings to GL constants\n */\nfunction convertTextureFormatToGL(format: TextureFormat): GL {\n const formatInfo = WEBGL_TEXTURE_FORMATS[format];\n const webglFormat = formatInfo?.gl;\n if (webglFormat === undefined) {\n throw new Error(`Unsupported texture format ${format}`);\n }\n return webglFormat;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// Feature detection for WebGL\n// Provides a function that enables simple checking of which WebGL features are\n\nimport {DeviceFeature, DeviceFeatures} from '@luma.gl/core';\nimport {GLExtensions} from '@luma.gl/webgl/constants';\nimport {getWebGLExtension} from '../../context/helpers/webgl-extensions';\nimport {\n isTextureFeature,\n checkTextureFeature,\n TEXTURE_FEATURES\n} from '../converters/webgl-texture-table';\n\n/**\n * Defines luma.gl \"feature\" names and semantics\n * when value is 'string' it is the name of the extension that enables this feature\n */\nconst WEBGL_FEATURES: Partial> = {\n // optional WebGPU features\n 'depth-clip-control': 'EXT_depth_clamp', // TODO these seem subtly different\n 'timestamp-query': 'EXT_disjoint_timer_query_webgl2',\n // \"indirect-first-instance\"\n // Textures are handled by getTextureFeatures()\n // 'depth32float-stencil8' // GPUTextureFormat 'depth32float-stencil8'\n\n // optional WebGL features\n 'compilation-status-async-webgl': 'KHR_parallel_shader_compile',\n 'polygon-mode-webgl': 'WEBGL_polygon_mode',\n 'provoking-vertex-webgl': 'WEBGL_provoking_vertex',\n 'shader-clip-cull-distance-webgl': 'WEBGL_clip_cull_distance',\n 'shader-noperspective-interpolation-webgl': 'NV_shader_noperspective_interpolation',\n 'shader-conservative-depth-webgl': 'EXT_conservative_depth'\n\n // Textures are handled by getTextureFeatures()\n};\n\n/**\n * WebGL extensions exposed as luma.gl features\n * To minimize GL log noise and improve performance, this class ensures that\n * - WebGL extensions are not queried until the corresponding feature is checked.\n * - WebGL extensions are only queried once.\n */\nexport class WebGLDeviceFeatures extends DeviceFeatures {\n protected gl: WebGL2RenderingContext;\n protected extensions: GLExtensions;\n protected testedFeatures = new Set();\n\n constructor(\n gl: WebGL2RenderingContext,\n extensions: GLExtensions,\n disabledFeatures: Partial>\n ) {\n super([], disabledFeatures);\n this.gl = gl;\n this.extensions = extensions;\n // TODO - is this really needed?\n // Enable EXT_float_blend first: https://developer.mozilla.org/en-US/docs/Web/API/EXT_float_blend\n getWebGLExtension(gl, 'EXT_color_buffer_float', extensions);\n }\n\n override *[Symbol.iterator](): IterableIterator {\n const features = this.getFeatures();\n for (const feature of features) {\n if (this.has(feature)) {\n yield feature;\n }\n }\n return [];\n }\n\n override has(feature: DeviceFeature): boolean {\n if (this.disabledFeatures?.[feature]) {\n return false;\n }\n\n // We have already tested this feature\n if (!this.testedFeatures.has(feature)) {\n this.testedFeatures.add(feature);\n\n // Check the feature once\n if (isTextureFeature(feature) && checkTextureFeature(this.gl, feature, this.extensions)) {\n this.features.add(feature);\n }\n\n if (this.getWebGLFeature(feature)) {\n this.features.add(feature);\n }\n }\n return this.features.has(feature);\n }\n\n // FOR DEVICE\n\n initializeFeatures() {\n // Initialize all features by checking them.\n // Except WEBGL_polygon_mode since Chrome logs ugly console warnings\n const features = this.getFeatures().filter(feature => feature !== 'polygon-mode-webgl');\n for (const feature of features) {\n this.has(feature);\n }\n }\n\n // IMPLEMENTATION\n\n getFeatures() {\n return [...Object.keys(WEBGL_FEATURES), ...Object.keys(TEXTURE_FEATURES)] as DeviceFeature[];\n }\n\n /** Extract all WebGL features */\n protected getWebGLFeature(feature: DeviceFeature): boolean {\n const featureInfo = WEBGL_FEATURES[feature];\n // string value requires checking the corresponding WebGL extension\n const isSupported =\n typeof featureInfo === 'string'\n ? Boolean(getWebGLExtension(this.gl, featureInfo, this.extensions))\n : Boolean(featureInfo);\n\n return isSupported;\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {DeviceLimits} from '@luma.gl/core';\nimport {GL} from '@luma.gl/webgl/constants';\n\n// biome-ignore format: preserve layout\nexport class WebGLDeviceLimits extends DeviceLimits {\n get maxTextureDimension1D() { return 0; } // WebGL does not support 1D textures\n get maxTextureDimension2D() { return this.getParameter(GL.MAX_TEXTURE_SIZE); }\n get maxTextureDimension3D() { return this.getParameter(GL.MAX_3D_TEXTURE_SIZE); }\n get maxTextureArrayLayers() { return this.getParameter(GL.MAX_ARRAY_TEXTURE_LAYERS); }\n get maxBindGroups() { return 0; }\n get maxDynamicUniformBuffersPerPipelineLayout() { return 0; } // TBD\n get maxDynamicStorageBuffersPerPipelineLayout() { return 0; } // TBD\n get maxSampledTexturesPerShaderStage() { return this.getParameter(GL.MAX_VERTEX_TEXTURE_IMAGE_UNITS); } // ) TBD\n get maxSamplersPerShaderStage() { return this.getParameter(GL.MAX_COMBINED_TEXTURE_IMAGE_UNITS); }\n get maxStorageBuffersPerShaderStage() { return 0; } // TBD\n get maxStorageTexturesPerShaderStage() { return 0; } // TBD\n get maxUniformBuffersPerShaderStage() { return this.getParameter(GL.MAX_UNIFORM_BUFFER_BINDINGS); }\n get maxUniformBufferBindingSize() { return this.getParameter(GL.MAX_UNIFORM_BLOCK_SIZE); }\n get maxStorageBufferBindingSize() { return 0; }\n get minUniformBufferOffsetAlignment() { return this.getParameter(GL.UNIFORM_BUFFER_OFFSET_ALIGNMENT); }\n get minStorageBufferOffsetAlignment() { return 0; } \n get maxVertexBuffers() { return 16; } // WebGL 2 supports 16 buffers, see https://github.com/gpuweb/gpuweb/issues/4284\n get maxVertexAttributes() { return this.getParameter(GL.MAX_VERTEX_ATTRIBS); }\n get maxVertexBufferArrayStride() { return 2048; } // TBD, this is just the default value from WebGPU\n get maxInterStageShaderVariables() { return this.getParameter(GL.MAX_VARYING_COMPONENTS); }\n get maxComputeWorkgroupStorageSize() { return 0; } // WebGL does not support compute shaders\n get maxComputeInvocationsPerWorkgroup() { return 0; } // WebGL does not support compute shaders\n get maxComputeWorkgroupSizeX() { return 0; } // WebGL does not support compute shaders\n get maxComputeWorkgroupSizeY() { return 0; } // WebGL does not support compute shaders\n get maxComputeWorkgroupSizeZ() { return 0; } // WebGL does not support compute shaders\n get maxComputeWorkgroupsPerDimension() { return 0;} // WebGL does not support compute shaders\n\n // PRIVATE\n\n protected gl: WebGL2RenderingContext;\n protected limits: Partial> = {};\n\n constructor(gl: WebGL2RenderingContext) {\n super();\n this.gl = gl;\n }\n\n protected getParameter(parameter: GL): number {\n if (this.limits[parameter] === undefined) {\n this.limits[parameter] = this.gl.getParameter(parameter);\n }\n return this.limits[parameter] || 0;\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {FramebufferProps} from '@luma.gl/core';\nimport {Framebuffer} from '@luma.gl/core';\nimport {GL} from '@luma.gl/webgl/constants';\nimport {WebGLDevice} from '../webgl-device';\nimport {WEBGLTexture} from './webgl-texture';\nimport {WEBGLTextureView} from './webgl-texture-view';\nimport {getDepthStencilAttachmentWebGL} from '../converters/webgl-texture-table';\n\nexport type Attachment = WEBGLTextureView | WEBGLTexture; // | WEBGLRenderbuffer;\n\n/** luma.gl Framebuffer, WebGL implementation */\nexport class WEBGLFramebuffer extends Framebuffer {\n readonly device: WebGLDevice;\n gl: WebGL2RenderingContext;\n readonly handle: WebGLFramebuffer;\n\n colorAttachments: WEBGLTextureView[] = [];\n depthStencilAttachment: WEBGLTextureView | null = null;\n\n constructor(device: WebGLDevice, props: FramebufferProps) {\n super(device, props);\n\n // WebGL default framebuffer handle is null\n const isDefaultFramebuffer = props.handle === null;\n\n this.device = device;\n this.gl = device.gl;\n this.handle =\n this.props.handle || isDefaultFramebuffer ? this.props.handle : this.gl.createFramebuffer();\n\n if (!isDefaultFramebuffer) {\n // default framebuffer handle is null, so we can't set debug metadata...\n device._setWebGLDebugMetadata(this.handle, this, {spector: this.props});\n\n if (!props.handle) {\n // Auto create textures for attachments if needed\n this.autoCreateAttachmentTextures();\n\n this.updateAttachments();\n }\n }\n }\n\n /** destroys any auto created resources etc. */\n override destroy(): void {\n super.destroy(); // destroys owned resources etc.\n if (!this.destroyed && this.handle !== null && !this.props.handle) {\n this.gl.deleteFramebuffer(this.handle);\n }\n }\n\n protected updateAttachments(): void {\n /** Attach from a map of attachments */\n // @ts-expect-error native bindFramebuffer is overridden by our state tracker\n const prevHandle: WebGLFramebuffer | null = this.gl.bindFramebuffer(\n GL.FRAMEBUFFER,\n this.handle\n );\n\n // Walk the attachments\n for (let i = 0; i < this.colorAttachments.length; ++i) {\n const attachment = this.colorAttachments[i];\n if (attachment) {\n const attachmentPoint = GL.COLOR_ATTACHMENT0 + i;\n this._attachTextureView(attachmentPoint, attachment);\n }\n }\n\n if (this.depthStencilAttachment) {\n const attachmentPoint = getDepthStencilAttachmentWebGL(\n this.depthStencilAttachment.props.format\n );\n this._attachTextureView(attachmentPoint, this.depthStencilAttachment);\n }\n\n /** Check the status */\n if (this.device.props.debug) {\n const status = this.gl.checkFramebufferStatus(GL.FRAMEBUFFER) as GL;\n if (status !== GL.FRAMEBUFFER_COMPLETE) {\n throw new Error(`Framebuffer ${_getFrameBufferStatus(status)}`);\n }\n }\n\n this.gl.bindFramebuffer(GL.FRAMEBUFFER, prevHandle);\n }\n\n // PRIVATE\n\n /** In WebGL we must use renderbuffers for depth/stencil attachments (unless we have extensions) */\n // protected override createDepthStencilTexture(format: TextureFormat): Texture {\n // // return new WEBGLRenderbuffer(this.device, {\n // return new WEBGLTexture(this.device, {\n // id: `${this.id}-depth-stencil`,\n // format,\n // width: this.width,\n // height: this.height,\n // mipmaps: false\n // });\n // }\n\n /**\n * @param attachment\n * @param texture\n * @param layer = 0 - index into WEBGLTextureArray and Texture3D or face for `TextureCubeMap`\n * @param level = 0 - mipmapLevel\n */\n protected _attachTextureView(attachment: GL, textureView: WEBGLTextureView): void {\n const {gl} = this.device;\n const {texture} = textureView;\n const level = textureView.props.baseMipLevel;\n const layer = textureView.props.baseArrayLayer;\n\n gl.bindTexture(texture.glTarget, texture.handle);\n\n switch (texture.glTarget) {\n case GL.TEXTURE_2D_ARRAY:\n case GL.TEXTURE_3D:\n gl.framebufferTextureLayer(GL.FRAMEBUFFER, attachment, texture.handle, level, layer);\n break;\n\n case GL.TEXTURE_CUBE_MAP:\n // layer must be a cubemap face (or if index, converted to cube map face)\n const face = mapIndexToCubeMapFace(layer);\n gl.framebufferTexture2D(GL.FRAMEBUFFER, attachment, face, texture.handle, level);\n break;\n\n case GL.TEXTURE_2D:\n gl.framebufferTexture2D(GL.FRAMEBUFFER, attachment, GL.TEXTURE_2D, texture.handle, level);\n break;\n\n default:\n throw new Error('Illegal texture type');\n }\n\n gl.bindTexture(texture.glTarget, null);\n }\n\n /** Default framebuffer resize is managed by canvas size and should be a no-op. */\n protected override resizeAttachments(width: number, height: number): void {\n if (this.handle === null) {\n this.width = width;\n this.height = height;\n return;\n }\n\n super.resizeAttachments(width, height);\n }\n}\n\n// Helper functions\n\n// Map an index to a cube map face constant\nfunction mapIndexToCubeMapFace(layer: number | GL): GL {\n // TEXTURE_CUBE_MAP_POSITIVE_X is a big value (0x8515)\n // if smaller assume layer is index, otherwise assume it is already a cube map face constant\n return layer < (GL.TEXTURE_CUBE_MAP_POSITIVE_X as number)\n ? layer + GL.TEXTURE_CUBE_MAP_POSITIVE_X\n : layer;\n}\n\n// Helper METHODS\n// Get a string describing the framebuffer error if installed\nfunction _getFrameBufferStatus(status: GL) {\n switch (status) {\n case GL.FRAMEBUFFER_COMPLETE:\n return 'success';\n case GL.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:\n return 'Mismatched attachments';\n case GL.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:\n return 'No attachments';\n case GL.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:\n return 'Height/width mismatch';\n case GL.FRAMEBUFFER_UNSUPPORTED:\n return 'Unsupported or split attachments';\n // WebGL2\n case GL.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:\n return 'Samples mismatch';\n // OVR_multiview2 extension\n // case GL.FRAMEBUFFER_INCOMPLETE_VIEW_TARGETS_OVR: return 'baseViewIndex mismatch';\n default:\n return `${status}`;\n }\n}\n\n/**\n * Attachment resize is expected to be a noop if size is same\n *\nprotected override resizeAttachments(width: number, height: number): this {\n // for default framebuffer, just update the stored size\n if (this.handle === null) {\n // assert(width === undefined && height === undefined);\n this.width = this.gl.drawingBufferWidth;\n this.height = this.gl.drawingBufferHeight;\n return this;\n }\n\n if (width === undefined) {\n width = this.gl.drawingBufferWidth;\n }\n if (height === undefined) {\n height = this.gl.drawingBufferHeight;\n }\n\n // TODO Not clear that this is better than default destroy/create implementation\n\n for (const colorAttachment of this.colorAttachments) {\n colorAttachment.texture.clone({width, height});\n }\n if (this.depthStencilAttachment) {\n this.depthStencilAttachment.texture.resize({width, height});\n }\n return this;\n}\n*/\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {CanvasContextProps} from '@luma.gl/core';\nimport {CanvasContext} from '@luma.gl/core';\nimport {WebGLDevice} from './webgl-device';\nimport {WEBGLFramebuffer} from './resources/webgl-framebuffer';\n\n/**\n * A WebGL Canvas Context which manages the canvas and handles drawing buffer resizing etc\n */\nexport class WebGLCanvasContext extends CanvasContext {\n readonly device: WebGLDevice;\n readonly handle: unknown = null;\n\n private _framebuffer: WEBGLFramebuffer | null = null;\n\n get [Symbol.toStringTag](): string {\n return 'WebGLCanvasContext';\n }\n\n constructor(device: WebGLDevice, props: CanvasContextProps) {\n // Note: Base class creates / looks up the canvas (unless under Node.js)\n super(props);\n this.device = device;\n\n // Base class constructor cannot access derived methods/fields, so we need to call these functions in the subclass constructor\n this._setAutoCreatedCanvasId(`${this.device.id}-canvas`);\n this._configureDevice();\n }\n\n // IMPLEMENTATION OF ABSTRACT METHODS\n\n _configureDevice(): void {\n const shouldResize =\n this.drawingBufferWidth !== this._framebuffer?.width ||\n this.drawingBufferHeight !== this._framebuffer?.height;\n if (shouldResize) {\n this._framebuffer?.resize([this.drawingBufferWidth, this.drawingBufferHeight]);\n }\n }\n\n _getCurrentFramebuffer(): WEBGLFramebuffer {\n this._framebuffer ||= new WEBGLFramebuffer(this.device, {\n id: 'canvas-context-framebuffer',\n handle: null, // Setting handle to null returns a reference to the default WebGL framebuffer\n width: this.drawingBufferWidth,\n height: this.drawingBufferHeight\n });\n return this._framebuffer;\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {PresentationContextProps, TextureFormatDepthStencil, Framebuffer} from '@luma.gl/core';\nimport {PresentationContext} from '@luma.gl/core';\nimport type {WebGLDevice} from './webgl-device';\n\ntype PresentationCanvasRenderingContext2D =\n | CanvasRenderingContext2D\n | OffscreenCanvasRenderingContext2D;\n\n/**\n * Tracks a non-WebGL destination canvas while rendering into the device's default canvas context.\n */\nexport class WebGLPresentationContext extends PresentationContext {\n readonly device: WebGLDevice;\n readonly handle = null;\n readonly context2d: PresentationCanvasRenderingContext2D;\n\n get [Symbol.toStringTag](): string {\n return 'WebGLPresentationContext';\n }\n\n constructor(device: WebGLDevice, props: PresentationContextProps = {}) {\n super(props);\n this.device = device;\n const contextLabel = `${this[Symbol.toStringTag]}(${this.id})`;\n\n const defaultCanvasContext = this.device.getDefaultCanvasContext();\n if (!defaultCanvasContext.offscreenCanvas) {\n throw new Error(\n `${contextLabel}: WebGL PresentationContext requires the default CanvasContext canvas to be an OffscreenCanvas`\n );\n }\n\n const context2d = this.canvas.getContext('2d');\n if (!context2d) {\n throw new Error(`${contextLabel}: Failed to create 2d presentation context`);\n }\n this.context2d = context2d;\n\n this._setAutoCreatedCanvasId(`${this.device.id}-presentation-canvas`);\n this._configureDevice();\n this._startObservers();\n }\n\n present(): void {\n this._resizeDrawingBufferIfNeeded();\n this.device.submit();\n\n const defaultCanvasContext = this.device.getDefaultCanvasContext();\n const [sourceWidth, sourceHeight] = defaultCanvasContext.getDrawingBufferSize();\n\n // Responsive layouts can transiently collapse presentation canvases to 0x0 during reflow.\n // In that case WebGL has nothing meaningful to present, and drawImage() would throw when the\n // offscreen source canvas has zero width or height.\n if (\n this.drawingBufferWidth === 0 ||\n this.drawingBufferHeight === 0 ||\n sourceWidth === 0 ||\n sourceHeight === 0 ||\n defaultCanvasContext.canvas.width === 0 ||\n defaultCanvasContext.canvas.height === 0\n ) {\n return;\n }\n\n if (\n sourceWidth !== this.drawingBufferWidth ||\n sourceHeight !== this.drawingBufferHeight ||\n defaultCanvasContext.canvas.width !== this.drawingBufferWidth ||\n defaultCanvasContext.canvas.height !== this.drawingBufferHeight\n ) {\n throw new Error(\n `${this[Symbol.toStringTag]}(${this.id}): Default canvas context size ${sourceWidth}x${sourceHeight} does not match presentation size ${this.drawingBufferWidth}x${this.drawingBufferHeight}`\n );\n }\n\n this.context2d.clearRect(0, 0, this.drawingBufferWidth, this.drawingBufferHeight);\n this.context2d.drawImage(defaultCanvasContext.canvas, 0, 0);\n }\n\n protected override _configureDevice(): void {}\n\n protected override _getCurrentFramebuffer(options?: {\n depthStencilFormat?: TextureFormatDepthStencil | false;\n }): Framebuffer {\n const defaultCanvasContext = this.device.getDefaultCanvasContext();\n defaultCanvasContext.setDrawingBufferSize(this.drawingBufferWidth, this.drawingBufferHeight);\n return defaultCanvasContext.getCurrentFramebuffer(options);\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nconst uidCounters: Record = {};\n\n/**\n * Returns a UID.\n * @param id= - Identifier base name\n * @return uid\n **/\nexport function uid(id: string = 'id'): string {\n uidCounters[id] = uidCounters[id] || 1;\n const count = uidCounters[id]++;\n return `${id}-${count}`;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {BufferMapCallback, BufferProps} from '@luma.gl/core';\nimport {Buffer} from '@luma.gl/core';\nimport {GL} from '@luma.gl/webgl/constants';\nimport {WebGLDevice} from '../webgl-device';\n\n/** WebGL Buffer interface */\nexport class WEBGLBuffer extends Buffer {\n readonly device: WebGLDevice;\n readonly gl: WebGL2RenderingContext;\n readonly handle: WebGLBuffer;\n\n /** Target in OpenGL defines the type of buffer */\n readonly glTarget: GL.ARRAY_BUFFER | GL.ELEMENT_ARRAY_BUFFER | GL.UNIFORM_BUFFER;\n /** Usage is a hint on how frequently the buffer will be updates */\n readonly glUsage: GL.STATIC_DRAW | GL.DYNAMIC_DRAW;\n /** Index type is needed when issuing draw calls, so we pre-compute it */\n readonly glIndexType: GL.UNSIGNED_SHORT | GL.UNSIGNED_INT = GL.UNSIGNED_SHORT;\n\n /** Number of bytes allocated on the GPU for this buffer */\n byteLength: number = 0;\n /** Number of bytes used */\n bytesUsed: number = 0;\n\n constructor(device: WebGLDevice, props: BufferProps = {}) {\n super(device, props);\n\n this.device = device;\n this.gl = this.device.gl;\n\n const handle = typeof props === 'object' ? props.handle : undefined;\n this.handle = handle || this.gl.createBuffer();\n device._setWebGLDebugMetadata(this.handle, this, {\n spector: {...this.props, data: typeof this.props.data}\n });\n\n // - In WebGL1, need to make sure we use GL.ELEMENT_ARRAY_BUFFER when initializing element buffers\n // otherwise buffer type will lock to generic (non-element) buffer\n // - In WebGL2, we can use GL.COPY_READ_BUFFER which avoids locking the type here\n this.glTarget = getWebGLTarget(this.props.usage);\n this.glUsage = getWebGLUsage(this.props.usage);\n // Note: uint8 indices are converted to uint16 during device normalization for WebGPU compatibility\n this.glIndexType = this.props.indexType === 'uint32' ? GL.UNSIGNED_INT : GL.UNSIGNED_SHORT;\n\n // Set data: (re)initializes the buffer\n if (props.data) {\n this._initWithData(props.data, props.byteOffset, props.byteLength);\n } else {\n this._initWithByteLength(props.byteLength || 0);\n }\n }\n\n override destroy(): void {\n if (!this.destroyed && this.handle) {\n this.removeStats();\n if (!this.props.handle) {\n this.trackDeallocatedMemory();\n this.gl.deleteBuffer(this.handle);\n } else {\n this.trackDeallocatedReferencedMemory('Buffer');\n }\n this.destroyed = true;\n // @ts-expect-error\n this.handle = null;\n }\n }\n\n /** Allocate a new buffer and initialize to contents of typed array */\n _initWithData(\n data: ArrayBuffer | ArrayBufferView,\n byteOffset: number = 0,\n byteLength: number = data.byteLength + byteOffset\n ): void {\n // const glTarget = this.device.isWebGL2 ? GL.COPY_WRITE_BUFFER : this.glTarget;\n const glTarget = this.glTarget;\n this.gl.bindBuffer(glTarget, this.handle);\n this.gl.bufferData(glTarget, byteLength, this.glUsage);\n this.gl.bufferSubData(glTarget, byteOffset, data);\n this.gl.bindBuffer(glTarget, null);\n\n this.bytesUsed = byteLength;\n this.byteLength = byteLength;\n\n this._setDebugData(data, byteOffset, byteLength);\n if (!this.props.handle) {\n this.trackAllocatedMemory(byteLength);\n } else {\n this.trackReferencedMemory(byteLength, 'Buffer');\n }\n }\n\n // Allocate a GPU buffer of specified size.\n _initWithByteLength(byteLength: number): this {\n // assert(byteLength >= 0);\n\n // Workaround needed for Safari (#291):\n // gl.bufferData with size equal to 0 crashes. Instead create zero sized array.\n let data = byteLength;\n if (byteLength === 0) {\n // @ts-expect-error\n data = new Float32Array(0);\n }\n\n // const glTarget = this.device.isWebGL2 ? GL.COPY_WRITE_BUFFER : this.glTarget;\n const glTarget = this.glTarget;\n\n this.gl.bindBuffer(glTarget, this.handle);\n this.gl.bufferData(glTarget, data, this.glUsage);\n this.gl.bindBuffer(glTarget, null);\n\n this.bytesUsed = byteLength;\n this.byteLength = byteLength;\n\n this._setDebugData(null, 0, byteLength);\n if (!this.props.handle) {\n this.trackAllocatedMemory(byteLength);\n } else {\n this.trackReferencedMemory(byteLength, 'Buffer');\n }\n\n return this;\n }\n\n write(data: ArrayBufferLike | ArrayBufferView, byteOffset: number = 0): void {\n const dataView = ArrayBuffer.isView(data) ? data : new Uint8Array(data);\n const srcOffset = 0;\n const byteLength = undefined; // data.byteLength;\n\n // Create the buffer - binding it here for the first time locks the type\n // In WebGL2, use GL.COPY_WRITE_BUFFER to avoid locking the type\n const glTarget = GL.COPY_WRITE_BUFFER;\n this.gl.bindBuffer(glTarget, this.handle);\n // WebGL2: subData supports additional srcOffset and length parameters\n if (srcOffset !== 0 || byteLength !== undefined) {\n this.gl.bufferSubData(glTarget, byteOffset, dataView, srcOffset, byteLength);\n } else {\n this.gl.bufferSubData(glTarget, byteOffset, dataView);\n }\n this.gl.bindBuffer(glTarget, null);\n\n this._setDebugData(data, byteOffset, data.byteLength);\n }\n\n async mapAndWriteAsync(\n callback: BufferMapCallback,\n byteOffset: number = 0,\n byteLength: number = this.byteLength - byteOffset\n ): Promise {\n const arrayBuffer = new ArrayBuffer(byteLength);\n // eslint-disable-next-line @typescript-eslint/await-thenable\n await callback(arrayBuffer, 'copied');\n this.write(arrayBuffer, byteOffset);\n }\n\n async readAsync(byteOffset = 0, byteLength?: number): Promise> {\n return this.readSyncWebGL(byteOffset, byteLength);\n }\n\n async mapAndReadAsync(\n callback: BufferMapCallback,\n byteOffset = 0,\n byteLength?: number\n ): Promise {\n const data = await this.readAsync(byteOffset, byteLength);\n // eslint-disable-next-line @typescript-eslint/await-thenable\n return await callback(data.buffer, 'copied');\n }\n\n readSyncWebGL(byteOffset = 0, byteLength?: number): Uint8Array {\n byteLength = byteLength ?? this.byteLength - byteOffset;\n const data = new Uint8Array(byteLength);\n const dstOffset = 0;\n\n // Use GL.COPY_READ_BUFFER to avoid disturbing other targets and locking type\n this.gl.bindBuffer(GL.COPY_READ_BUFFER, this.handle);\n this.gl.getBufferSubData(GL.COPY_READ_BUFFER, byteOffset, data, dstOffset, byteLength);\n this.gl.bindBuffer(GL.COPY_READ_BUFFER, null);\n\n // Update local `data` if offsets are 0\n this._setDebugData(data, byteOffset, byteLength);\n\n return data;\n }\n}\n\n/**\n * Returns a WebGL buffer target\n *\n * @param usage\n * static MAP_READ = 0x01;\n * static MAP_WRITE = 0x02;\n * static COPY_SRC = 0x0004;\n * static COPY_DST = 0x0008;\n * static INDEX = 0x0010;\n * static VERTEX = 0x0020;\n * static UNIFORM = 0x0040;\n * static STORAGE = 0x0080;\n * static INDIRECT = 0x0100;\n * static QUERY_RESOLVE = 0x0200;\n *\n * @returns WebGL buffer targe\n *\n * Buffer bind points in WebGL2\n * gl.COPY_READ_BUFFER: Buffer for copying from one buffer object to another.\n * gl.COPY_WRITE_BUFFER: Buffer for copying from one buffer object to another.\n * gl.TRANSFORM_FEEDBACK_BUFFER: Buffer for transform feedback operations.\n * gl.PIXEL_PACK_BUFFER: Buffer used for pixel transfer operations.\n * gl.PIXEL_UNPACK_BUFFER: Buffer used for pixel transfer operations.\n */\nfunction getWebGLTarget(\n usage: number\n): GL.ARRAY_BUFFER | GL.ELEMENT_ARRAY_BUFFER | GL.UNIFORM_BUFFER {\n if (usage & Buffer.INDEX) {\n return GL.ELEMENT_ARRAY_BUFFER;\n }\n if (usage & Buffer.VERTEX) {\n return GL.ARRAY_BUFFER;\n }\n if (usage & Buffer.UNIFORM) {\n return GL.UNIFORM_BUFFER;\n }\n\n // Binding a buffer for the first time locks the type\n // In WebGL2, we can use GL.COPY_WRITE_BUFFER to avoid locking the type\n return GL.ARRAY_BUFFER;\n}\n\n/** @todo usage is not passed correctly */\nfunction getWebGLUsage(usage: number): GL.STATIC_DRAW | GL.DYNAMIC_DRAW {\n if (usage & Buffer.INDEX) {\n return GL.STATIC_DRAW;\n }\n if (usage & Buffer.VERTEX) {\n return GL.STATIC_DRAW;\n }\n if (usage & Buffer.UNIFORM) {\n return GL.DYNAMIC_DRAW;\n }\n return GL.STATIC_DRAW;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {type CompilerMessage} from '@luma.gl/core';\n\n/**\n * Parse a WebGL-format GLSL compilation log into an array of WebGPU style message records.\n * This follows documented WebGL conventions for compilation logs.\n * Based on https://github.com/wwwtyro/gl-format-compiler-error (public domain)\n */\nexport function parseShaderCompilerLog(errLog: string): readonly CompilerMessage[] {\n // Parse the error - note: browser and driver dependent\n const lines = errLog.split(/\\r?\\n/);\n\n const messages: CompilerMessage[] = [];\n\n for (const line of lines) {\n if (line.length <= 1) {\n continue; // eslint-disable-line no-continue\n }\n\n const lineWithTrimmedWhitespace = line.trim();\n\n const segments: string[] = line.split(':');\n const trimmedMessageType = segments[0]?.trim();\n\n // Check for messages with no line information `ERROR: unsupported shader version`\n if (segments.length === 2) {\n const [messageType, message] = segments;\n if (!messageType || !message) {\n messages.push({\n message: lineWithTrimmedWhitespace,\n type: getMessageType(trimmedMessageType || 'info'),\n lineNum: 0,\n linePos: 0\n });\n continue; // eslint-disable-line no-continue\n }\n messages.push({\n message: message.trim(),\n type: getMessageType(messageType),\n lineNum: 0,\n linePos: 0\n });\n\n continue; // eslint-disable-line no-continue\n }\n\n const [messageType, linePosition, lineNumber, ...rest] = segments;\n if (!messageType || !linePosition || !lineNumber) {\n messages.push({\n message: segments.slice(1).join(':').trim() || lineWithTrimmedWhitespace,\n type: getMessageType(trimmedMessageType || 'info'),\n lineNum: 0,\n linePos: 0\n });\n continue; // eslint-disable-line no-continue\n }\n\n let lineNum = parseInt(lineNumber, 10);\n if (Number.isNaN(lineNum)) {\n lineNum = 0;\n }\n\n let linePos = parseInt(linePosition, 10);\n if (Number.isNaN(linePos)) {\n linePos = 0;\n }\n\n messages.push({\n message: rest.join(':').trim(),\n type: getMessageType(messageType),\n lineNum,\n linePos // TODO\n });\n }\n\n return messages;\n}\n\n/** Ensure supported type */\nfunction getMessageType(messageType: string): 'warning' | 'error' | 'info' {\n const MESSAGE_TYPES = ['warning', 'error', 'info'];\n const lowerCaseType = messageType.toLowerCase();\n return (MESSAGE_TYPES.includes(lowerCaseType) ? lowerCaseType : 'info') as\n | 'warning'\n | 'error'\n | 'info';\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Shader, ShaderProps, CompilerMessage, log} from '@luma.gl/core';\nimport {GL} from '@luma.gl/webgl/constants';\nimport {parseShaderCompilerLog} from '../helpers/parse-shader-compiler-log';\nimport {WebGLDevice} from '../webgl-device';\n\n/**\n * An immutable compiled shader program that execute portions of the GPU Pipeline\n */\nexport class WEBGLShader extends Shader {\n readonly device: WebGLDevice;\n readonly handle: WebGLShader;\n\n constructor(device: WebGLDevice, props: ShaderProps) {\n super(device, props);\n this.device = device;\n switch (this.props.stage) {\n case 'vertex':\n this.handle = this.props.handle || this.device.gl.createShader(GL.VERTEX_SHADER);\n break;\n case 'fragment':\n this.handle = this.props.handle || this.device.gl.createShader(GL.FRAGMENT_SHADER);\n break;\n default:\n throw new Error(this.props.stage);\n }\n\n // default framebuffer handle is null, so we can't set spector metadata...\n device._setWebGLDebugMetadata(this.handle, this, {spector: this.props});\n\n const compilationStatus = this._compile(this.source);\n if (compilationStatus && typeof compilationStatus.catch === 'function') {\n compilationStatus.catch(() => {\n // Ensure any async compile status errors are consumed.\n this.compilationStatus = 'error';\n });\n }\n }\n\n override destroy(): void {\n if (this.handle) {\n this.removeStats();\n this.device.gl.deleteShader(this.handle);\n this.destroyed = true;\n // @ts-expect-error\n this.handle.destroyed = true;\n // this.handle = null;\n }\n }\n\n get asyncCompilationStatus(): Promise<'pending' | 'success' | 'error'> {\n return this._waitForCompilationComplete().then(() => {\n this._getCompilationStatus();\n return this.compilationStatus;\n });\n }\n\n override async getCompilationInfo(): Promise {\n await this._waitForCompilationComplete();\n return this.getCompilationInfoSync();\n }\n\n override getCompilationInfoSync(): readonly CompilerMessage[] {\n const shaderLog = this.device.gl.getShaderInfoLog(this.handle);\n return shaderLog ? parseShaderCompilerLog(shaderLog) : [];\n }\n\n override getTranslatedSource(): string | null {\n const extensions = this.device.getExtension('WEBGL_debug_shaders');\n const ext = extensions.WEBGL_debug_shaders;\n return ext?.getTranslatedShaderSource(this.handle) || null;\n }\n\n // PRIVATE METHODS\n\n /** Compile a shader and get compilation status */\n protected _compile(source: string): void | Promise {\n source = source.startsWith('#version ') ? source : `#version 300 es\\n${source}`;\n\n const {gl} = this.device;\n gl.shaderSource(this.handle, source);\n gl.compileShader(this.handle);\n\n // For performance reasons, avoid checking shader compilation errors on production\n if (!this.device.props.debug) {\n this.compilationStatus = 'pending';\n return;\n }\n\n // Sync case - slower, but advantage is that it throws in the constructor, making break on error more useful\n if (!this.device.features.has('compilation-status-async-webgl')) {\n this._getCompilationStatus();\n // The `Shader` base class will determine if debug window should be opened based on this.compilationStatus\n this.debugShader();\n if (this.compilationStatus === 'error') {\n throw new Error(`GLSL compilation errors in ${this.props.stage} shader ${this.props.id}`);\n }\n return;\n }\n\n // async case\n log.once(1, 'Shader compilation is asynchronous')();\n return this._waitForCompilationComplete().then(() => {\n log.info(2, `Shader ${this.id} - async compilation complete: ${this.compilationStatus}`)();\n this._getCompilationStatus();\n\n // The `Shader` base class will determine if debug window should be opened based on this.compilationStatus\n this.debugShader();\n });\n }\n\n /** Use KHR_parallel_shader_compile extension if available */\n protected async _waitForCompilationComplete(): Promise {\n const waitMs = async (ms: number) => await new Promise(resolve => setTimeout(resolve, ms));\n const DELAY_MS = 10; // Shader compilation is typically quite fast (with some exceptions)\n\n // If status polling is not available, we can't wait for completion. Just wait a little to minimize blocking\n if (!this.device.features.has('compilation-status-async-webgl')) {\n await waitMs(DELAY_MS);\n return;\n }\n\n const {gl} = this.device;\n for (;;) {\n const complete = gl.getShaderParameter(this.handle, GL.COMPLETION_STATUS_KHR);\n if (complete) {\n return;\n }\n await waitMs(DELAY_MS);\n }\n }\n\n /**\n * Get the shader compilation status\n * TODO - Load log even when no error reported, to catch warnings?\n * https://gamedev.stackexchange.com/questions/30429/how-to-detect-glsl-warnings\n */\n protected _getCompilationStatus() {\n this.compilationStatus = this.device.gl.getShaderParameter(this.handle, GL.COMPILE_STATUS)\n ? 'success'\n : 'error';\n }\n}\n\n// TODO - Original code from luma.gl v8 - keep until new debug functionality has matured\n// if (!compilationSuccess) {\n// const parsedLog = shaderLog ? parseShaderCompilerLog(shaderLog) : [];\n// const messages = parsedLog.filter(message => message.type === 'error');\n// const formattedLog = formatCompilerLog(messages, source, {showSourceCode: 'all', html: true});\n// const shaderDescription = `${this.stage} shader ${shaderName}`;\n// log.error(`GLSL compilation errors in ${shaderDescription}\\n${formattedLog}`)();\n// displayShaderLog(parsedLog, source, shaderName);\n// }\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {CompareFunction, StencilOperation, BlendOperation, BlendFactor} from '@luma.gl/core';\nimport {Device, log, Parameters, PolygonMode, ProvokingVertex} from '@luma.gl/core';\nimport {GL} from '@luma.gl/webgl/constants';\nimport type {\n GLBlendEquation,\n GLBlendFunction,\n GLFunction,\n GLParameters,\n GLPolygonMode,\n GLProvokingVertex,\n GLStencilOp\n} from '@luma.gl/webgl/constants';\nimport {setGLParameters} from '../../context/parameters/unified-parameter-api';\nimport {WebGLDevice} from '../webgl-device';\n\n/* eslint-disable no-unused-expressions */ // For expression ? gl.enable() : gl.disable()\n\n/**\n * Execute a function with a set of temporary WebGL parameter overrides\n * - Saves current \"global\" WebGL context settings\n * - Sets the supplies WebGL context parameters,\n * - Executes supplied function\n * - Restores parameters\n * - Returns the return value of the supplied function\n */\nexport function withDeviceAndGLParameters(\n device: Device,\n parameters: Parameters,\n glParameters: GLParameters,\n func: (_?: Device) => T\n): T {\n if (isObjectEmpty(parameters)) {\n // Avoid setting state if no parameters provided. Just call and return\n return func(device);\n }\n\n // Wrap in a try-catch to ensure that parameters are restored on exceptions\n const webglDevice = device as WebGLDevice;\n webglDevice.pushState();\n try {\n setDeviceParameters(device, parameters);\n setGLParameters(webglDevice.gl, glParameters);\n return func(device);\n } finally {\n webglDevice.popState();\n }\n}\n\n/**\n * Execute a function with a set of temporary WebGL parameter overrides\n * - Saves current \"global\" WebGL context settings\n * - Sets the supplies WebGL context parameters,\n * - Executes supplied function\n * - Restores parameters\n * - Returns the return value of the supplied function\n * @deprecated use withDeviceParameters instead\n */\nexport function withGLParameters(\n device: Device,\n parameters: GLParameters,\n func: (_?: Device) => T\n): T {\n if (isObjectEmpty(parameters)) {\n // Avoid setting state if no parameters provided. Just call and return\n return func(device);\n }\n\n // Wrap in a try-catch to ensure that parameters are restored on exceptions\n const webglDevice = device as WebGLDevice;\n webglDevice.pushState();\n try {\n setGLParameters(webglDevice.gl, parameters);\n return func(device);\n } finally {\n webglDevice.popState();\n }\n}\n\n/**\n * Execute a function with a set of temporary WebGL parameter overrides\n * - Saves current \"global\" WebGL context settings\n * - Sets the supplies WebGL context parameters,\n * - Executes supplied function\n * - Restores parameters\n * - Returns the return value of the supplied function\n */\nexport function withDeviceParameters(\n device: Device,\n parameters: Parameters,\n func: (_?: Device) => T\n): T {\n if (isObjectEmpty(parameters)) {\n // Avoid setting state if no parameters provided. Just call and return\n return func(device);\n }\n\n // Wrap in a try-catch to ensure that parameters are restored on exceptions'\n const webglDevice = device as WebGLDevice;\n webglDevice.pushState();\n try {\n setDeviceParameters(device, parameters);\n return func(device);\n } finally {\n webglDevice.popState();\n }\n}\n\n/** Set WebGPU Style Parameters */\nexport function setDeviceParameters(device: Device, parameters: Parameters) {\n const webglDevice = device as WebGLDevice;\n const {gl} = webglDevice;\n\n // RASTERIZATION SETTINGS\n if (parameters.cullMode) {\n switch (parameters.cullMode) {\n case 'none':\n gl.disable(GL.CULL_FACE);\n break;\n case 'front':\n gl.enable(GL.CULL_FACE);\n gl.cullFace(GL.FRONT);\n break;\n case 'back':\n gl.enable(GL.CULL_FACE);\n gl.cullFace(GL.BACK);\n break;\n }\n }\n\n if (parameters.frontFace) {\n gl.frontFace(\n map('frontFace', parameters.frontFace, {\n ccw: GL.CCW,\n cw: GL.CW\n })\n );\n }\n\n if (parameters.unclippedDepth) {\n if (device.features.has('depth-clip-control')) {\n // EXT_depth_clamp\n gl.enable(GL.DEPTH_CLAMP_EXT);\n }\n }\n\n if (parameters.depthBias !== undefined) {\n gl.enable(GL.POLYGON_OFFSET_FILL);\n gl.polygonOffset(parameters.depthBias, parameters.depthBiasSlopeScale || 0);\n }\n\n // depthBiasSlopeScale: {\n // // Handled by depthBias\n // },\n\n // WEBGL EXTENSIONS\n\n if (parameters.provokingVertex) {\n if (device.features.has('provoking-vertex-webgl')) {\n const extensions = webglDevice.getExtension('WEBGL_provoking_vertex');\n const ext = extensions.WEBGL_provoking_vertex;\n\n const vertex = map(\n 'provokingVertex',\n parameters.provokingVertex,\n {\n first: GL.FIRST_VERTEX_CONVENTION_WEBGL,\n last: GL.LAST_VERTEX_CONVENTION_WEBGL\n }\n );\n ext?.provokingVertexWEBGL(vertex);\n }\n }\n\n if (parameters.polygonMode || parameters.polygonOffsetLine) {\n if (device.features.has('polygon-mode-webgl')) {\n if (parameters.polygonMode) {\n const extensions = webglDevice.getExtension('WEBGL_polygon_mode');\n const ext = extensions.WEBGL_polygon_mode;\n const mode = map('polygonMode', parameters.polygonMode, {\n fill: GL.FILL_WEBGL,\n line: GL.LINE_WEBGL\n });\n ext?.polygonModeWEBGL(GL.FRONT, mode);\n ext?.polygonModeWEBGL(GL.BACK, mode);\n }\n\n if (parameters.polygonOffsetLine) {\n gl.enable(GL.POLYGON_OFFSET_LINE_WEBGL);\n }\n }\n }\n\n if (device.features.has('shader-clip-cull-distance-webgl')) {\n if (parameters.clipDistance0) {\n gl.enable(GL.CLIP_DISTANCE0_WEBGL);\n }\n if (parameters.clipDistance1) {\n gl.enable(GL.CLIP_DISTANCE1_WEBGL);\n }\n if (parameters.clipDistance2) {\n gl.enable(GL.CLIP_DISTANCE2_WEBGL);\n }\n if (parameters.clipDistance3) {\n gl.enable(GL.CLIP_DISTANCE3_WEBGL);\n }\n if (parameters.clipDistance4) {\n gl.enable(GL.CLIP_DISTANCE4_WEBGL);\n }\n if (parameters.clipDistance5) {\n gl.enable(GL.CLIP_DISTANCE5_WEBGL);\n }\n if (parameters.clipDistance6) {\n gl.enable(GL.CLIP_DISTANCE6_WEBGL);\n }\n if (parameters.clipDistance7) {\n gl.enable(GL.CLIP_DISTANCE7_WEBGL);\n }\n }\n\n // DEPTH STENCIL\n\n if (parameters.depthWriteEnabled !== undefined) {\n gl.depthMask(mapBoolean('depthWriteEnabled', parameters.depthWriteEnabled));\n }\n\n if (parameters.depthCompare) {\n parameters.depthCompare !== 'always' ? gl.enable(GL.DEPTH_TEST) : gl.disable(GL.DEPTH_TEST);\n gl.depthFunc(convertCompareFunction('depthCompare', parameters.depthCompare));\n }\n\n if (parameters.clearDepth !== undefined) {\n gl.clearDepth(parameters.clearDepth);\n }\n\n if (parameters.stencilWriteMask) {\n const mask = parameters.stencilWriteMask;\n gl.stencilMaskSeparate(GL.FRONT, mask);\n gl.stencilMaskSeparate(GL.BACK, mask);\n }\n\n if (parameters.stencilReadMask) {\n // stencilReadMask is handle inside stencil***Compare.\n log.warn('stencilReadMask not supported under WebGL');\n }\n\n if (parameters.stencilCompare) {\n const mask = parameters.stencilReadMask || 0xffffffff;\n const glValue = convertCompareFunction('depthCompare', parameters.stencilCompare);\n // TODO - ensure back doesn't overwrite\n parameters.stencilCompare !== 'always'\n ? gl.enable(GL.STENCIL_TEST)\n : gl.disable(GL.STENCIL_TEST);\n gl.stencilFuncSeparate(GL.FRONT, glValue, 0, mask);\n gl.stencilFuncSeparate(GL.BACK, glValue, 0, mask);\n }\n\n if (\n parameters.stencilPassOperation &&\n parameters.stencilFailOperation &&\n parameters.stencilDepthFailOperation\n ) {\n const dppass = convertStencilOperation('stencilPassOperation', parameters.stencilPassOperation);\n const sfail = convertStencilOperation('stencilFailOperation', parameters.stencilFailOperation);\n const dpfail = convertStencilOperation(\n 'stencilDepthFailOperation',\n parameters.stencilDepthFailOperation\n );\n gl.stencilOpSeparate(GL.FRONT, sfail, dpfail, dppass);\n gl.stencilOpSeparate(GL.BACK, sfail, dpfail, dppass);\n }\n\n // stencilDepthFailOperation() {\n // // handled by stencilPassOperation\n // },\n\n // stencilFailOperation() {\n // // handled by stencilPassOperation\n // },\n\n // COLOR STATE\n switch (parameters.blend) {\n case true:\n gl.enable(GL.BLEND);\n break;\n case false:\n gl.disable(GL.BLEND);\n break;\n default:\n // leave WebGL blend state unchanged if `parameters.blend` is not set\n }\n\n if (parameters.blendColorOperation || parameters.blendAlphaOperation) {\n const colorEquation = convertBlendOperationToEquation(\n 'blendColorOperation',\n parameters.blendColorOperation || 'add'\n );\n const alphaEquation = convertBlendOperationToEquation(\n 'blendAlphaOperation',\n parameters.blendAlphaOperation || 'add'\n );\n gl.blendEquationSeparate(colorEquation, alphaEquation);\n\n const colorSrcFactor = convertBlendFactorToFunction(\n 'blendColorSrcFactor',\n parameters.blendColorSrcFactor || 'one'\n );\n const colorDstFactor = convertBlendFactorToFunction(\n 'blendColorDstFactor',\n parameters.blendColorDstFactor || 'zero'\n );\n const alphaSrcFactor = convertBlendFactorToFunction(\n 'blendAlphaSrcFactor',\n parameters.blendAlphaSrcFactor || 'one'\n );\n const alphaDstFactor = convertBlendFactorToFunction(\n 'blendAlphaDstFactor',\n parameters.blendAlphaDstFactor || 'zero'\n );\n gl.blendFuncSeparate(colorSrcFactor, colorDstFactor, alphaSrcFactor, alphaDstFactor);\n }\n}\n\n/*\n rasterizationState: {\n cullMode: \"back\",\n },\n\n depthStencilState: {\n depthWriteEnabled: true,\n depthCompare: \"less\",\n format: \"depth24plus-stencil8\",\n },\n\n colorStates: [\n {\n format: \"bgra8unorm\",\n // colorBlend.srcFactor = wgpu::BlendFactor::SrcAlpha;\n // colorBlend.dstFactor = wgpu::BlendFactor::OneMinusSrcAlpha;\n // alphaBlend.srcFactor = wgpu::BlendFactor::SrcAlpha;\n // alphaBlend.dstFactor = wgpu::BlendFactor::OneMinusSrcAlpha;\n },\n ],\n });\n*/\n\nexport function convertCompareFunction(parameter: string, value: CompareFunction): GLFunction {\n return map(parameter, value, {\n never: GL.NEVER,\n less: GL.LESS,\n equal: GL.EQUAL,\n 'less-equal': GL.LEQUAL,\n greater: GL.GREATER,\n 'not-equal': GL.NOTEQUAL,\n 'greater-equal': GL.GEQUAL,\n always: GL.ALWAYS\n });\n}\n\nexport function convertToCompareFunction(parameter: string, value: GLFunction): CompareFunction {\n return map(parameter, value, {\n [GL.NEVER]: 'never',\n [GL.LESS]: 'less',\n [GL.EQUAL]: 'equal',\n [GL.LEQUAL]: 'less-equal',\n [GL.GREATER]: 'greater',\n [GL.NOTEQUAL]: 'not-equal',\n [GL.GEQUAL]: 'greater-equal',\n [GL.ALWAYS]: 'always'\n });\n}\n\nfunction convertStencilOperation(parameter: string, value: StencilOperation): GL {\n return map(parameter, value, {\n keep: GL.KEEP,\n zero: GL.ZERO,\n replace: GL.REPLACE,\n invert: GL.INVERT,\n 'increment-clamp': GL.INCR,\n 'decrement-clamp': GL.DECR,\n 'increment-wrap': GL.INCR_WRAP,\n 'decrement-wrap': GL.DECR_WRAP\n });\n}\n\nfunction convertBlendOperationToEquation(\n parameter: string,\n value: BlendOperation\n): GLBlendEquation {\n return map(parameter, value, {\n add: GL.FUNC_ADD,\n subtract: GL.FUNC_SUBTRACT,\n 'reverse-subtract': GL.FUNC_REVERSE_SUBTRACT,\n min: GL.MIN,\n max: GL.MAX\n });\n}\n\nfunction convertBlendFactorToFunction(\n parameter: string,\n value: BlendFactor,\n type: 'color' | 'alpha' = 'color'\n): GLBlendFunction {\n return map(parameter, value, {\n one: GL.ONE,\n zero: GL.ZERO,\n src: GL.SRC_COLOR,\n 'one-minus-src': GL.ONE_MINUS_SRC_COLOR,\n dst: GL.DST_COLOR,\n 'one-minus-dst': GL.ONE_MINUS_DST_COLOR,\n 'src-alpha': GL.SRC_ALPHA,\n 'one-minus-src-alpha': GL.ONE_MINUS_SRC_ALPHA,\n 'dst-alpha': GL.DST_ALPHA,\n 'one-minus-dst-alpha': GL.ONE_MINUS_DST_ALPHA,\n 'src-alpha-saturated': GL.SRC_ALPHA_SATURATE,\n constant: type === 'color' ? GL.CONSTANT_COLOR : GL.CONSTANT_ALPHA,\n 'one-minus-constant':\n type === 'color' ? GL.ONE_MINUS_CONSTANT_COLOR : GL.ONE_MINUS_CONSTANT_ALPHA,\n // 'constant-alpha': GL.CONSTANT_ALPHA,\n // 'one-minus-constant-alpha': GL.ONE_MINUS_CONSTANT_ALPHA,\n // TODO not supported in WebGL2\n src1: GL.SRC_COLOR,\n 'one-minus-src1': GL.ONE_MINUS_SRC_COLOR,\n 'src1-alpha': GL.SRC_ALPHA,\n 'one-minus-src1-alpha': GL.ONE_MINUS_SRC_ALPHA\n });\n}\n\nfunction message(parameter: string, value: any): string {\n return `Illegal parameter ${value} for ${parameter}`;\n}\n\nfunction map(parameter: string, value: K, valueMap: Record): V {\n if (!(value in valueMap)) {\n throw new Error(message(parameter, value));\n }\n return valueMap[value];\n}\n\nfunction mapBoolean(parameter: string, value: boolean): boolean {\n return value;\n}\n\n/** Returns true if given object is empty, false otherwise. */\nfunction isObjectEmpty(obj: object): boolean {\n let isEmpty = true;\n // @ts-ignore key is unused\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n for (const key in obj) {\n isEmpty = false;\n break;\n }\n return isEmpty;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// SAMPLER FILTERS\nimport {SamplerProps} from '@luma.gl/core';\nimport {GL, GLSamplerParameters} from '@luma.gl/webgl/constants';\nimport {convertCompareFunction} from './device-parameters';\n\n/**\n * Convert WebGPU-style sampler props to WebGL\n * @param props\n * @returns\n */\nexport function convertSamplerParametersToWebGL(props: SamplerProps): GLSamplerParameters {\n const params: GLSamplerParameters = {};\n if (props.addressModeU) {\n params[GL.TEXTURE_WRAP_S] = convertAddressMode(props.addressModeU);\n }\n if (props.addressModeV) {\n params[GL.TEXTURE_WRAP_T] = convertAddressMode(props.addressModeV);\n }\n if (props.addressModeW) {\n params[GL.TEXTURE_WRAP_R] = convertAddressMode(props.addressModeW);\n }\n if (props.magFilter) {\n params[GL.TEXTURE_MAG_FILTER] = convertMaxFilterMode(props.magFilter);\n }\n if (props.minFilter || props.mipmapFilter) {\n // TODO - arbitrary choice of linear?\n params[GL.TEXTURE_MIN_FILTER] = convertMinFilterMode(\n props.minFilter || 'linear',\n props.mipmapFilter\n );\n }\n if (props.lodMinClamp !== undefined) {\n params[GL.TEXTURE_MIN_LOD] = props.lodMinClamp;\n }\n if (props.lodMaxClamp !== undefined) {\n params[GL.TEXTURE_MAX_LOD] = props.lodMaxClamp;\n }\n if (props.type === 'comparison-sampler') {\n // Setting prop.compare turns this into a comparison sampler\n params[GL.TEXTURE_COMPARE_MODE] = GL.COMPARE_REF_TO_TEXTURE;\n }\n if (props.compare) {\n params[GL.TEXTURE_COMPARE_FUNC] = convertCompareFunction('compare', props.compare);\n }\n // Note depends on WebGL extension\n if (props.maxAnisotropy) {\n params[GL.TEXTURE_MAX_ANISOTROPY_EXT] = props.maxAnisotropy;\n }\n return params;\n}\n\n// HELPERS\n\n/** Convert address more */\nfunction convertAddressMode(\n addressMode: 'clamp-to-edge' | 'repeat' | 'mirror-repeat'\n): GL.CLAMP_TO_EDGE | GL.REPEAT | GL.MIRRORED_REPEAT {\n switch (addressMode) {\n case 'clamp-to-edge':\n return GL.CLAMP_TO_EDGE;\n case 'repeat':\n return GL.REPEAT;\n case 'mirror-repeat':\n return GL.MIRRORED_REPEAT;\n }\n}\n\nfunction convertMaxFilterMode(maxFilter: 'nearest' | 'linear'): GL.NEAREST | GL.LINEAR {\n switch (maxFilter) {\n case 'nearest':\n return GL.NEAREST;\n case 'linear':\n return GL.LINEAR;\n }\n}\n\n/**\n * WebGPU has separate min filter and mipmap filter,\n * WebGL is combined and effectively offers 6 options\n */\nfunction convertMinFilterMode(\n minFilter: 'nearest' | 'linear',\n mipmapFilter: 'none' | 'nearest' | 'linear' = 'none'\n):\n | GL.NEAREST\n | GL.LINEAR\n | GL.NEAREST_MIPMAP_NEAREST\n | GL.LINEAR_MIPMAP_NEAREST\n | GL.NEAREST_MIPMAP_LINEAR\n | GL.LINEAR_MIPMAP_LINEAR {\n if (!mipmapFilter) {\n return convertMaxFilterMode(minFilter);\n }\n switch (mipmapFilter) {\n case 'none':\n return convertMaxFilterMode(minFilter);\n case 'nearest':\n switch (minFilter) {\n case 'nearest':\n return GL.NEAREST_MIPMAP_NEAREST;\n case 'linear':\n return GL.LINEAR_MIPMAP_NEAREST;\n }\n break;\n case 'linear':\n switch (minFilter) {\n case 'nearest':\n return GL.NEAREST_MIPMAP_LINEAR;\n case 'linear':\n return GL.LINEAR_MIPMAP_LINEAR;\n }\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Sampler, SamplerProps} from '@luma.gl/core';\nimport {GL, GLSamplerParameters} from '@luma.gl/webgl/constants';\nimport {convertSamplerParametersToWebGL} from '../converters/sampler-parameters';\nimport type {WebGLDevice} from '../webgl-device';\n\n/**\n * Sampler object -\n * so that they can be set directly on the texture\n * https://github.com/WebGLSamples/WebGL2Samples/blob/master/samples/sampler_object.html\n */\nexport class WEBGLSampler extends Sampler {\n readonly device: WebGLDevice;\n readonly handle: WebGLSampler;\n readonly parameters: GLSamplerParameters;\n\n constructor(device: WebGLDevice, props: SamplerProps) {\n super(device, props);\n this.device = device;\n this.parameters = convertSamplerParametersToWebGL(props);\n this.handle = props.handle || this.device.gl.createSampler();\n this._setSamplerParameters(this.parameters);\n }\n\n override destroy(): void {\n if (this.handle) {\n this.device.gl.deleteSampler(this.handle);\n // @ts-expect-error read-only/undefined\n this.handle = undefined;\n }\n }\n\n override toString(): string {\n return `Sampler(${this.id},${JSON.stringify(this.props)})`;\n }\n\n /** Set sampler parameters on the sampler */\n private _setSamplerParameters(parameters: GLSamplerParameters): void {\n for (const [pname, value] of Object.entries(parameters)) {\n // Apparently there are integer/float conversion issues requires two parameter setting functions in JavaScript.\n // For now, pick the float version for parameters specified as GLfloat.\n const param = Number(pname) as GL.TEXTURE_MIN_LOD | GL.TEXTURE_MAX_LOD;\n switch (param) {\n case GL.TEXTURE_MIN_LOD:\n case GL.TEXTURE_MAX_LOD:\n this.device.gl.samplerParameterf(this.handle, param, value);\n break;\n default:\n this.device.gl.samplerParameteri(this.handle, param, value);\n break;\n }\n }\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {GLParameters, setGLParameters} from '../parameters/unified-parameter-api';\nimport {WebGLStateTracker} from './webgl-state-tracker';\n\n/**\n * Execute a function with a set of temporary WebGL parameter overrides\n * - Saves current \"global\" WebGL context settings\n * - Sets the supplies WebGL context parameters,\n * - Executes supplied function\n * - Restores parameters\n * - Returns the return value of the supplied function\n */\nexport function withGLParameters(\n gl: WebGL2RenderingContext,\n parameters: GLParameters & {nocatch?: boolean},\n func: any\n): any {\n if (isObjectEmpty(parameters)) {\n // Avoid setting state if no parameters provided. Just call and return\n return func(gl);\n }\n\n const {nocatch = true} = parameters;\n\n const webglState = WebGLStateTracker.get(gl);\n webglState.push();\n setGLParameters(gl, parameters);\n\n // Setup is done, call the function\n let value;\n\n if (nocatch) {\n // Avoid try catch to minimize stack size impact for safe execution paths\n value = func(gl);\n webglState.pop();\n } else {\n // Wrap in a try-catch to ensure that parameters are restored on exceptions\n try {\n value = func(gl);\n } finally {\n webglState.pop();\n }\n }\n\n return value;\n}\n\n// Helpers\n\n// Returns true if given object is empty, false otherwise.\nfunction isObjectEmpty(object: unknown): boolean {\n // @ts-ignore - dummy key variable\n for (const key in object) {\n return false;\n }\n return true;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device, TextureViewProps} from '@luma.gl/core';\n// import {getTextureFormatInfo} from '@luma.gl/core';\nimport {TextureView, Texture} from '@luma.gl/core';\n\nimport {WebGLDevice} from '../webgl-device';\nimport {WEBGLTexture} from './webgl-texture';\n\nexport class WEBGLTextureView extends TextureView {\n readonly device: WebGLDevice;\n readonly gl: WebGL2RenderingContext;\n readonly handle: null; // Does not have a WebGL representation\n readonly texture: WEBGLTexture;\n\n constructor(device: Device, props: TextureViewProps & {texture: WEBGLTexture}) {\n super(device, {...Texture.defaultProps, ...props});\n\n this.device = device as WebGLDevice;\n this.gl = this.device.gl;\n this.handle = null;\n this.texture = props.texture;\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {GL, GLDataType, GLPixelType} from '@luma.gl/webgl/constants';\nimport {SignedDataType} from '@luma.gl/core';\n\n/** Get shadertypes data type from GL constants */\nexport function convertGLDataTypeToDataType(type: GLDataType | GLPixelType): SignedDataType {\n return GL_DATA_TYPE_MAP[type];\n}\n\nconst GL_DATA_TYPE_MAP: Record = {\n [GL.INT]: 'sint32',\n [GL.UNSIGNED_INT]: 'uint32',\n [GL.SHORT]: 'sint16',\n [GL.UNSIGNED_SHORT]: 'uint16',\n [GL.BYTE]: 'sint8',\n [GL.UNSIGNED_BYTE]: 'uint8',\n [GL.FLOAT]: 'float32',\n [GL.HALF_FLOAT]: 'float16',\n [GL.UNSIGNED_SHORT_5_6_5]: 'uint16',\n [GL.UNSIGNED_SHORT_4_4_4_4]: 'uint16',\n [GL.UNSIGNED_SHORT_5_5_5_1]: 'uint16',\n [GL.UNSIGNED_INT_2_10_10_10_REV]: 'uint32',\n [GL.UNSIGNED_INT_10F_11F_11F_REV]: 'uint32',\n [GL.UNSIGNED_INT_5_9_9_9_REV]: 'uint32',\n [GL.UNSIGNED_INT_24_8]: 'uint32',\n [GL.FLOAT_32_UNSIGNED_INT_24_8_REV]: 'uint32'\n};\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// @ts-nocheck\n\nimport {\n type Device,\n type TextureProps,\n type TextureViewProps,\n type Sampler,\n type SamplerProps,\n type CopyExternalImageOptions,\n type TextureReadOptions,\n type TextureWriteOptions,\n type TextureFormat,\n Buffer,\n getTypedArrayConstructor,\n Texture,\n log\n} from '@luma.gl/core';\n\nimport {\n GLSamplerParameters,\n GLValueParameters,\n GL,\n GLTextureTarget,\n GLTextureCubeMapTarget,\n GLTexelDataFormat,\n GLPixelType\n} from '@luma.gl/webgl/constants';\n\nimport {getTextureFormatWebGL} from '../converters/webgl-texture-table';\nimport {convertSamplerParametersToWebGL} from '../converters/sampler-parameters';\nimport {withGLParameters} from '../../context/state-tracker/with-parameters';\nimport {WebGLDevice} from '../webgl-device';\nimport {WEBGLBuffer} from './webgl-buffer';\nimport {WEBGLFramebuffer} from './webgl-framebuffer';\nimport {WEBGLSampler} from './webgl-sampler';\nimport {WEBGLTextureView} from './webgl-texture-view';\nimport {convertGLDataTypeToDataType} from '../converters/shader-formats';\n\n/**\n * WebGL... the texture API from hell... hopefully made simpler\n */\nexport class WEBGLTexture extends Texture {\n // readonly MAX_ATTRIBUTES: number;\n readonly device: WebGLDevice;\n readonly gl: WebGL2RenderingContext;\n handle: WebGLTexture;\n\n // @ts-ignore TODO - currently unused in WebGL. Create dummy sampler?\n sampler: WEBGLSampler = undefined;\n view: WEBGLTextureView;\n\n /**\n * The WebGL target corresponding to the texture type\n * @note `target` cannot be modified by bind:\n * textures are special because when you first bind them to a target,\n * When you first bind a texture as a GL_TEXTURE_2D, you are saying that this texture is a 2D texture.\n * And it will always be a 2D texture; this state cannot be changed ever.\n * A texture that was first bound as a GL_TEXTURE_2D, must always be bound as a GL_TEXTURE_2D;\n * attempting to bind it as GL_TEXTURE_3D will give rise to a run-time error\n */\n glTarget: GLTextureTarget;\n /** The WebGL format - essentially channel structure */\n glFormat: GLTexelDataFormat;\n /** The WebGL data format - the type of each channel */\n glType: GLPixelType;\n /** The WebGL constant corresponding to the WebGPU style constant in format */\n glInternalFormat: GL;\n /** Whether the internal format is compressed */\n compressed: boolean;\n\n // state\n /** Texture binding slot - TODO - move to texture view? */\n _textureUnit: number = 0;\n /** Cached framebuffer reused for color texture readback. */\n _framebuffer: WEBGLFramebuffer | null = null;\n /** Cache key for the currently attached readback subresource `${mipLevel}:${layer}`. */\n _framebufferAttachmentKey: string | null = null;\n\n constructor(device: Device, props: TextureProps) {\n // const byteAlignment = this._getRowByteAlignment(props.format, props.width);\n super(device, props, {byteAlignment: 1});\n\n this.device = device as WebGLDevice;\n this.gl = this.device.gl;\n\n const formatInfo = getTextureFormatWebGL(this.props.format);\n\n // Note: In WebGL the texture target defines the type of texture on first bind.\n this.glTarget = getWebGLTextureTarget(this.props.dimension);\n this.glInternalFormat = formatInfo.internalFormat;\n this.glFormat = formatInfo.format;\n this.glType = formatInfo.type;\n this.compressed = formatInfo.compressed;\n\n this.handle = this.props.handle || this.gl.createTexture();\n this.device._setWebGLDebugMetadata(this.handle, this, {spector: this.props});\n\n /**\n * Use WebGL immutable texture storage to allocate and clear texture memory.\n * - texStorage2D should be considered a preferred alternative to texImage2D. It may have lower memory costs than texImage2D in some implementations.\n * - Once texStorage*D has been called, the texture is immutable and can only be updated with texSubImage*(), not texImage()\n * @see https://registry.khronos.org/webgl/specs/latest/2.0/ WebGL 2 spec section 3.7.6\n */\n this.gl.bindTexture(this.glTarget, this.handle);\n const {dimension, width, height, depth, mipLevels, glTarget, glInternalFormat} = this;\n if (!this.compressed) {\n switch (dimension) {\n case '2d':\n case 'cube':\n this.gl.texStorage2D(glTarget, mipLevels, glInternalFormat, width, height);\n break;\n case '2d-array':\n case '3d':\n this.gl.texStorage3D(glTarget, mipLevels, glInternalFormat, width, height, depth);\n break;\n default:\n throw new Error(dimension);\n }\n }\n this.gl.bindTexture(this.glTarget, null);\n\n // Set data\n this._initializeData(props.data);\n\n if (!this.props.handle) {\n this.trackAllocatedMemory(this.getAllocatedByteLength(), 'Texture');\n } else {\n this.trackReferencedMemory(this.getAllocatedByteLength(), 'Texture');\n }\n\n // Set texture sampler parameters\n this.setSampler(this.props.sampler);\n // @ts-ignore TODO - fix types\n this.view = new WEBGLTextureView(this.device, {...this.props, texture: this});\n\n Object.seal(this);\n }\n\n override destroy(): void {\n if (this.handle) {\n // Destroy any cached framebuffer\n this._framebuffer?.destroy();\n this._framebuffer = null;\n this._framebufferAttachmentKey = null;\n\n this.removeStats();\n if (!this.props.handle) {\n this.gl.deleteTexture(this.handle);\n this.trackDeallocatedMemory('Texture');\n } else {\n this.trackDeallocatedReferencedMemory('Texture');\n }\n // this.handle = null;\n this.destroyed = true;\n }\n }\n\n createView(props: TextureViewProps): WEBGLTextureView {\n return new WEBGLTextureView(this.device, {...props, texture: this});\n }\n\n override setSampler(sampler: Sampler | SamplerProps = {}): void {\n super.setSampler(sampler);\n // Apply sampler parameters to texture\n const parameters = convertSamplerParametersToWebGL(this.sampler.props);\n this._setSamplerParameters(parameters);\n }\n\n copyExternalImage(options_: CopyExternalImageOptions): {width: number; height: number} {\n const options = this._normalizeCopyExternalImageOptions(options_);\n\n if (options.sourceX || options.sourceY) {\n // requires copyTexSubImage2D from a framebuffer'\n throw new Error('WebGL does not support sourceX/sourceY)');\n }\n\n const {glFormat, glType} = this;\n const {image, depth, mipLevel, x, y, z, width, height} = options;\n\n // WebGL cube maps specify faces by overriding target instead of using the z parameter\n const glTarget = getWebGLCubeFaceTarget(this.glTarget, this.dimension, z);\n const glParameters: GLValueParameters = options.flipY ? {[GL.UNPACK_FLIP_Y_WEBGL]: true} : {};\n\n this.gl.bindTexture(this.glTarget, this.handle);\n\n withGLParameters(this.gl, glParameters, () => {\n switch (this.dimension) {\n case '2d':\n case 'cube':\n // biome-ignore format: preserve layout\n this.gl.texSubImage2D(glTarget, mipLevel, x, y, width, height, glFormat, glType, image);\n break;\n case '2d-array':\n case '3d':\n // biome-ignore format: preserve layout\n this.gl.texSubImage3D(glTarget, mipLevel, x, y, z, width, height, depth, glFormat, glType, image);\n break;\n default:\n // Can never happen in WebGL\n }\n });\n\n this.gl.bindTexture(this.glTarget, null);\n\n return {width: options.width, height: options.height};\n }\n\n override copyImageData(options_): void {\n super.copyImageData(options_);\n }\n\n /**\n * Reads a color texture subresource into a GPU buffer using `PIXEL_PACK_BUFFER`.\n *\n * @note Only first-pass color readback is supported. Unsupported formats and aspects throw\n * before any WebGL calls are issued.\n */\n readBuffer(options: TextureReadOptions & {byteOffset?: number} = {}, buffer?: Buffer): Buffer {\n if (!buffer) {\n throw new Error(`${this} readBuffer requires a destination buffer`);\n }\n const normalizedOptions = this._getSupportedColorReadOptions(options);\n const byteOffset = options.byteOffset ?? 0;\n const memoryLayout = this.computeMemoryLayout(normalizedOptions);\n\n if (buffer.byteLength < byteOffset + memoryLayout.byteLength) {\n throw new Error(\n `${this} readBuffer target is too small (${buffer.byteLength} < ${byteOffset + memoryLayout.byteLength})`\n );\n }\n\n const webglBuffer = buffer as WEBGLBuffer;\n this.gl.bindBuffer(GL.PIXEL_PACK_BUFFER, webglBuffer.handle);\n try {\n this._readColorTextureLayers(normalizedOptions, memoryLayout, destinationByteOffset => {\n this.gl.readPixels(\n normalizedOptions.x,\n normalizedOptions.y,\n normalizedOptions.width,\n normalizedOptions.height,\n this.glFormat,\n this.glType,\n byteOffset + destinationByteOffset\n );\n });\n } finally {\n this.gl.bindBuffer(GL.PIXEL_PACK_BUFFER, null);\n }\n\n return buffer;\n }\n\n async readDataAsync(options: TextureReadOptions = {}): Promise {\n throw new Error(\n `${this} readDataAsync is deprecated; use readBuffer() with an explicit destination buffer or DynamicTexture.readAsync()`\n );\n }\n\n writeBuffer(buffer: Buffer, options_: TextureWriteOptions = {}) {\n const options = this._normalizeTextureWriteOptions(options_);\n const {width, height, depthOrArrayLayers, mipLevel, byteOffset, x, y, z} = options;\n const {glFormat, glType, compressed} = this;\n const glTarget = getWebGLCubeFaceTarget(this.glTarget, this.dimension, z);\n\n if (compressed) {\n throw new Error('writeBuffer for compressed textures is not implemented in WebGL');\n }\n\n const {bytesPerPixel} = this.device.getTextureFormatInfo(this.format);\n const unpackRowLength = bytesPerPixel ? options.bytesPerRow / bytesPerPixel : undefined;\n const glParameters: GLValueParameters = {\n [GL.UNPACK_ALIGNMENT]: this.byteAlignment,\n ...(unpackRowLength !== undefined ? {[GL.UNPACK_ROW_LENGTH]: unpackRowLength} : {}),\n [GL.UNPACK_IMAGE_HEIGHT]: options.rowsPerImage\n };\n\n this.gl.bindTexture(this.glTarget, this.handle);\n this.gl.bindBuffer(GL.PIXEL_UNPACK_BUFFER, buffer.handle);\n\n withGLParameters(this.gl, glParameters, () => {\n switch (this.dimension) {\n case '2d':\n case 'cube':\n this.gl.texSubImage2D(\n glTarget,\n mipLevel,\n x,\n y,\n width,\n height,\n glFormat,\n glType,\n byteOffset\n );\n break;\n case '2d-array':\n case '3d':\n this.gl.texSubImage3D(\n glTarget,\n mipLevel,\n x,\n y,\n z,\n width,\n height,\n depthOrArrayLayers,\n glFormat,\n glType,\n byteOffset\n );\n break;\n default:\n }\n });\n\n this.gl.bindBuffer(GL.PIXEL_UNPACK_BUFFER, null);\n this.gl.bindTexture(this.glTarget, null);\n }\n\n writeData(\n data: ArrayBuffer | SharedArrayBuffer | ArrayBufferView,\n options_: TextureWriteOptions = {}\n ): void {\n const options = this._normalizeTextureWriteOptions(options_);\n\n const typedArray = ArrayBuffer.isView(data) ? data : new Uint8Array(data);\n const {width, height, depthOrArrayLayers, mipLevel, x, y, z, byteOffset} = options;\n const {glFormat, glType, compressed} = this;\n const glTarget = getWebGLCubeFaceTarget(this.glTarget, this.dimension, z);\n\n let unpackRowLength: number | undefined;\n if (!compressed) {\n const {bytesPerPixel} = this.device.getTextureFormatInfo(this.format);\n if (bytesPerPixel) {\n unpackRowLength = options.bytesPerRow / bytesPerPixel;\n }\n }\n\n const glParameters: GLValueParameters = !this.compressed\n ? {\n [GL.UNPACK_ALIGNMENT]: this.byteAlignment,\n ...(unpackRowLength !== undefined ? {[GL.UNPACK_ROW_LENGTH]: unpackRowLength} : {}),\n [GL.UNPACK_IMAGE_HEIGHT]: options.rowsPerImage\n }\n : {};\n const sourceElementOffset = getWebGLTextureSourceElementOffset(typedArray, byteOffset);\n const compressedData = compressed ? getArrayBufferView(typedArray, byteOffset) : typedArray;\n const mipLevelSize = this._getMipLevelSize(mipLevel);\n const isFullMipUpload =\n x === 0 &&\n y === 0 &&\n z === 0 &&\n width === mipLevelSize.width &&\n height === mipLevelSize.height &&\n depthOrArrayLayers === mipLevelSize.depthOrArrayLayers;\n\n this.gl.bindTexture(this.glTarget, this.handle);\n this.gl.bindBuffer(GL.PIXEL_UNPACK_BUFFER, null);\n\n withGLParameters(this.gl, glParameters, () => {\n switch (this.dimension) {\n case '2d':\n case 'cube':\n if (compressed) {\n if (isFullMipUpload) {\n // biome-ignore format: preserve layout\n this.gl.compressedTexImage2D(glTarget, mipLevel, glFormat, width, height, 0, compressedData);\n } else {\n // biome-ignore format: preserve layout\n this.gl.compressedTexSubImage2D(glTarget, mipLevel, x, y, width, height, glFormat, compressedData);\n }\n } else {\n // biome-ignore format: preserve layout\n this.gl.texSubImage2D(glTarget, mipLevel, x, y, width, height, glFormat, glType, typedArray, sourceElementOffset);\n }\n break;\n case '2d-array':\n case '3d':\n if (compressed) {\n if (isFullMipUpload) {\n // biome-ignore format: preserve layout\n this.gl.compressedTexImage3D(\n glTarget,\n mipLevel,\n glFormat,\n width,\n height,\n depthOrArrayLayers,\n 0,\n compressedData\n );\n } else {\n // biome-ignore format: preserve layout\n this.gl.compressedTexSubImage3D(\n glTarget,\n mipLevel,\n x,\n y,\n z,\n width,\n height,\n depthOrArrayLayers,\n glFormat,\n compressedData\n );\n }\n } else {\n // biome-ignore format: preserve layout\n this.gl.texSubImage3D(glTarget, mipLevel, x, y, z, width, height, depthOrArrayLayers, glFormat, glType, typedArray, sourceElementOffset);\n }\n break;\n default:\n // Can never happen in WebGL\n }\n });\n\n this.gl.bindTexture(this.glTarget, null);\n }\n\n // IMPLEMENTATION SPECIFIC\n\n /** @todo - for now we always use 1 for maximum compatibility, we can fine tune later */\n private _getRowByteAlignment(format: TextureFormat, width: number): 1 | 2 | 4 | 8 {\n // For best texture data read/write performance, calculate the biggest pack/unpack alignment\n // that fits with the provided texture row byte length\n // Note: Any RGBA or 32 bit type will be at least 4 bytes, which should result in good performance.\n // const info = this.device.getTextureFormatInfo(format);\n // const rowByteLength = width * info.bytesPerPixel;\n // if (rowByteLength % 8 === 0) return 8;\n // if (rowByteLength % 4 === 0) return 4;\n // if (rowByteLength % 2 === 0) return 2;\n return 1;\n }\n\n /**\n * Wraps a given texture into a framebuffer object, that can be further used\n * to read data from the texture object.\n */\n _getFramebuffer() {\n this._framebuffer ||= this.device.createFramebuffer({\n id: `framebuffer-for-${this.id}`,\n width: this.width,\n height: this.height,\n colorAttachments: [this]\n });\n return this._framebuffer;\n }\n\n // WEBGL SPECIFIC\n\n override readDataSyncWebGL(options_: TextureReadOptions = {}): ArrayBuffer {\n const options = this._getSupportedColorReadOptions(options_);\n const memoryLayout = this.computeMemoryLayout(options);\n\n // const formatInfo = getTextureFormatInfo(format);\n // Allocate pixel array if not already available, using supplied type\n const shaderType = convertGLDataTypeToDataType(this.glType);\n const ArrayType = getTypedArrayConstructor(shaderType);\n const targetArray = new ArrayType(memoryLayout.byteLength / ArrayType.BYTES_PER_ELEMENT) as\n | Uint8Array\n | Uint16Array\n | Float32Array\n | Int8Array\n | Int16Array\n | Int32Array\n | Uint32Array;\n\n this._readColorTextureLayers(options, memoryLayout, destinationByteOffset => {\n const layerView = new ArrayType(\n targetArray.buffer,\n targetArray.byteOffset + destinationByteOffset,\n memoryLayout.bytesPerImage / ArrayType.BYTES_PER_ELEMENT\n );\n this.gl.readPixels(\n options.x,\n options.y,\n options.width,\n options.height,\n this.glFormat,\n this.glType,\n layerView\n );\n });\n\n return targetArray.buffer as ArrayBuffer;\n }\n\n /**\n * Iterates the requested mip/layer/slice range, reattaching the cached read framebuffer as\n * needed before delegating the actual `readPixels()` call to the supplied callback.\n */\n private _readColorTextureLayers(\n options: Required,\n memoryLayout: ReturnType,\n readLayer: (destinationByteOffset: number) => void\n ): void {\n const framebuffer = this._getFramebuffer();\n const packRowLength = memoryLayout.bytesPerRow / memoryLayout.bytesPerPixel;\n const glParameters: GLValueParameters = {\n [GL.PACK_ALIGNMENT]: this.byteAlignment,\n ...(packRowLength !== options.width ? {[GL.PACK_ROW_LENGTH]: packRowLength} : {})\n };\n\n // Note: luma.gl overrides bindFramebuffer so that we can reliably restore the previous framebuffer.\n const prevReadBuffer = this.gl.getParameter(GL.READ_BUFFER) as GL;\n const prevHandle = this.gl.bindFramebuffer(\n GL.FRAMEBUFFER,\n framebuffer.handle\n ) as unknown as WebGLFramebuffer | null;\n\n try {\n this.gl.readBuffer(GL.COLOR_ATTACHMENT0);\n withGLParameters(this.gl, glParameters, () => {\n for (let layerIndex = 0; layerIndex < options.depthOrArrayLayers; layerIndex++) {\n this._attachReadSubresource(framebuffer, options.mipLevel, options.z + layerIndex);\n readLayer(layerIndex * memoryLayout.bytesPerImage);\n }\n });\n } finally {\n this.gl.bindFramebuffer(GL.FRAMEBUFFER, prevHandle || null);\n this.gl.readBuffer(prevReadBuffer);\n }\n }\n\n /**\n * Attaches a single color subresource to the cached read framebuffer.\n *\n * @note Repeated attachments of the same `(mipLevel, layer)` tuple are skipped.\n */\n private _attachReadSubresource(\n framebuffer: WEBGLFramebuffer,\n mipLevel: number,\n layer: number\n ): void {\n const attachmentKey = `${mipLevel}:${layer}`;\n if (this._framebufferAttachmentKey === attachmentKey) {\n return;\n }\n\n switch (this.dimension) {\n case '2d':\n this.gl.framebufferTexture2D(\n GL.FRAMEBUFFER,\n GL.COLOR_ATTACHMENT0,\n GL.TEXTURE_2D,\n this.handle,\n mipLevel\n );\n break;\n\n case 'cube':\n this.gl.framebufferTexture2D(\n GL.FRAMEBUFFER,\n GL.COLOR_ATTACHMENT0,\n getWebGLCubeFaceTarget(this.glTarget, this.dimension, layer),\n this.handle,\n mipLevel\n );\n break;\n\n case '2d-array':\n case '3d':\n this.gl.framebufferTextureLayer(\n GL.FRAMEBUFFER,\n GL.COLOR_ATTACHMENT0,\n this.handle,\n mipLevel,\n layer\n );\n break;\n\n default:\n throw new Error(`${this} color readback does not support ${this.dimension} textures`);\n }\n\n if (this.device.props.debug) {\n const status = Number(this.gl.checkFramebufferStatus(GL.FRAMEBUFFER));\n if (status !== Number(GL.FRAMEBUFFER_COMPLETE)) {\n throw new Error(`${framebuffer} incomplete for ${this} readback (${status})`);\n }\n }\n\n this._framebufferAttachmentKey = attachmentKey;\n }\n\n /**\n * @note - this is used by the DynamicTexture class to generate mipmaps on WebGL\n */\n override generateMipmapsWebGL(options?: {force?: boolean}): void {\n const isFilterableAndRenderable =\n this.device.isTextureFormatRenderable(this.props.format) &&\n this.device.isTextureFormatFilterable(this.props.format);\n if (!isFilterableAndRenderable) {\n log.warn(`${this} is not renderable or filterable, may not be able to generate mipmaps`)();\n if (!options?.force) {\n return;\n }\n }\n\n try {\n this.gl.bindTexture(this.glTarget, this.handle);\n this.gl.generateMipmap(this.glTarget);\n } catch (error) {\n log.warn(`Error generating mipmap for ${this}: ${(error as Error).message}`)();\n } finally {\n this.gl.bindTexture(this.glTarget, null);\n }\n }\n\n // INTERNAL\n\n /**\n * Sets sampler parameters on texture\n */\n _setSamplerParameters(parameters: GLSamplerParameters): void {\n log.log(2, `${this.id} sampler parameters`, this.device.getGLKeys(parameters))();\n\n this.gl.bindTexture(this.glTarget, this.handle);\n\n for (const [pname, pvalue] of Object.entries(parameters)) {\n const param = Number(pname) as keyof GLSamplerParameters;\n const value = pvalue;\n\n // Apparently integer/float issues require two different texture parameter setting functions in JavaScript.\n // For now, pick the float version for parameters specified as GLfloat.\n switch (param) {\n case GL.TEXTURE_MIN_LOD:\n case GL.TEXTURE_MAX_LOD:\n this.gl.texParameterf(this.glTarget, param, value);\n break;\n\n case GL.TEXTURE_MAG_FILTER:\n case GL.TEXTURE_MIN_FILTER:\n this.gl.texParameteri(this.glTarget, param, value);\n break;\n\n case GL.TEXTURE_WRAP_S:\n case GL.TEXTURE_WRAP_T:\n case GL.TEXTURE_WRAP_R:\n this.gl.texParameteri(this.glTarget, param, value);\n break;\n\n case GL.TEXTURE_MAX_ANISOTROPY_EXT:\n // We have to query feature before using it\n if (this.device.features.has('texture-filterable-anisotropic-webgl')) {\n this.gl.texParameteri(this.glTarget, param, value);\n }\n break;\n\n case GL.TEXTURE_COMPARE_MODE:\n case GL.TEXTURE_COMPARE_FUNC:\n this.gl.texParameteri(this.glTarget, param, value);\n break;\n }\n }\n\n this.gl.bindTexture(this.glTarget, null);\n }\n\n _getActiveUnit(): number {\n return this.gl.getParameter(GL.ACTIVE_TEXTURE) - GL.TEXTURE0;\n }\n\n _bind(_textureUnit?: number): number {\n const {gl} = this;\n\n if (_textureUnit !== undefined) {\n this._textureUnit = _textureUnit;\n gl.activeTexture(gl.TEXTURE0 + _textureUnit);\n }\n\n gl.bindTexture(this.glTarget, this.handle);\n // @ts-ignore TODO fix types\n return _textureUnit;\n }\n\n _unbind(_textureUnit?: number): number | undefined {\n const {gl} = this;\n\n if (_textureUnit !== undefined) {\n this._textureUnit = _textureUnit;\n gl.activeTexture(gl.TEXTURE0 + _textureUnit);\n }\n\n gl.bindTexture(this.glTarget, null);\n return _textureUnit;\n }\n}\n\nfunction getArrayBufferView(typedArray: ArrayBufferView, byteOffset = 0): ArrayBufferView {\n if (!byteOffset) {\n return typedArray;\n }\n\n return new typedArray.constructor(\n typedArray.buffer,\n typedArray.byteOffset + byteOffset,\n (typedArray.byteLength - byteOffset) / typedArray.BYTES_PER_ELEMENT\n ) as ArrayBufferView;\n}\n\nfunction getWebGLTextureSourceElementOffset(\n typedArray: ArrayBufferView,\n byteOffset: number\n): number {\n if (byteOffset % typedArray.BYTES_PER_ELEMENT !== 0) {\n throw new Error(\n `Texture byteOffset ${byteOffset} must align to typed array element size ${typedArray.BYTES_PER_ELEMENT}`\n );\n }\n\n return byteOffset / typedArray.BYTES_PER_ELEMENT;\n}\n\n// INTERNAL HELPERS\n\n/** Convert a WebGPU style texture constant to a WebGL style texture constant */\nexport function getWebGLTextureTarget(\n dimension: '1d' | '2d' | '2d-array' | 'cube' | 'cube-array' | '3d'\n): GLTextureTarget {\n // biome-ignore format: preserve layout\n switch (dimension) {\n case '1d': break; // not supported in any WebGL version\n case '2d': return GL.TEXTURE_2D; // supported in WebGL1\n case '3d': return GL.TEXTURE_3D; // supported in WebGL2\n case 'cube': return GL.TEXTURE_CUBE_MAP; // supported in WebGL1\n case '2d-array': return GL.TEXTURE_2D_ARRAY; // supported in WebGL2\n case 'cube-array': break; // not supported in any WebGL version\n }\n throw new Error(dimension);\n}\n\n/**\n * In WebGL, cube maps specify faces by overriding target instead of using the depth parameter.\n * @note We still bind the texture using GL.TEXTURE_CUBE_MAP, but we need to use the face-specific target when setting mip levels.\n * @returns glTarget unchanged, if dimension !== 'cube'.\n */\nexport function getWebGLCubeFaceTarget(\n glTarget: GLTextureTarget,\n dimension: '1d' | '2d' | '2d-array' | 'cube' | 'cube-array' | '3d',\n level: number\n): GLTextureTarget | GLTextureCubeMapTarget {\n return dimension === 'cube' ? GL.TEXTURE_CUBE_MAP_POSITIVE_X + level : glTarget;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/* eslint-disable */\n\n// Uniforms\nimport type {UniformValue} from '@luma.gl/core';\nimport {GL, GLUniformType, GLSamplerType} from '@luma.gl/webgl/constants';\n\n/** Set a raw uniform (without type conversion and caching) */\n/* eslint-disable max-len */\nexport function setUniform(\n gl: WebGL2RenderingContext,\n location: WebGLUniformLocation,\n type: GLUniformType | GLSamplerType,\n value: UniformValue\n): void {\n const gl2 = gl as WebGL2RenderingContext;\n\n // Prepare the value for WebGL setters\n let uniformValue = value;\n if (uniformValue === true) {\n uniformValue = 1;\n }\n if (uniformValue === false) {\n uniformValue = 0;\n }\n const arrayValue = typeof uniformValue === 'number' ? [uniformValue] : uniformValue;\n\n // biome-ignore format: preserve layout\n switch (type) {\n case GL.SAMPLER_2D:\n case GL.SAMPLER_CUBE:\n case GL.SAMPLER_3D:\n case GL.SAMPLER_2D_SHADOW:\n case GL.SAMPLER_2D_ARRAY:\n case GL.SAMPLER_2D_ARRAY_SHADOW:\n case GL.SAMPLER_CUBE_SHADOW:\n case GL.INT_SAMPLER_2D:\n case GL.INT_SAMPLER_3D:\n case GL.INT_SAMPLER_CUBE:\n case GL.INT_SAMPLER_2D_ARRAY:\n case GL.UNSIGNED_INT_SAMPLER_2D:\n case GL.UNSIGNED_INT_SAMPLER_3D:\n case GL.UNSIGNED_INT_SAMPLER_CUBE:\n case GL.UNSIGNED_INT_SAMPLER_2D_ARRAY:\n if (typeof value !== 'number') {\n throw new Error('samplers must be set to integers');\n }\n return gl.uniform1i(location, value);\n\n case GL.FLOAT: return gl.uniform1fv(location, arrayValue);\n case GL.FLOAT_VEC2: return gl.uniform2fv(location, arrayValue);\n case GL.FLOAT_VEC3: return gl.uniform3fv(location, arrayValue);\n case GL.FLOAT_VEC4: return gl.uniform4fv(location, arrayValue);\n\n case GL.INT: return gl.uniform1iv(location, arrayValue);\n case GL.INT_VEC2: return gl.uniform2iv(location, arrayValue);\n case GL.INT_VEC3: return gl.uniform3iv(location, arrayValue);\n case GL.INT_VEC4: return gl.uniform4iv(location, arrayValue);\n\n case GL.BOOL: return gl.uniform1iv(location, arrayValue);\n case GL.BOOL_VEC2: return gl.uniform2iv(location, arrayValue);\n case GL.BOOL_VEC3: return gl.uniform3iv(location, arrayValue);\n case GL.BOOL_VEC4: return gl.uniform4iv(location, arrayValue);\n\n // WEBGL2 - unsigned integers\n case GL.UNSIGNED_INT: return gl2.uniform1uiv(location, arrayValue, 1);\n case GL.UNSIGNED_INT_VEC2: return gl2.uniform2uiv(location, arrayValue, 2);\n case GL.UNSIGNED_INT_VEC3: return gl2.uniform3uiv(location, arrayValue, 3);\n case GL.UNSIGNED_INT_VEC4: return gl2.uniform4uiv(location, arrayValue, 4);\n\n // WebGL2 - quadratic matrices\n // false: don't transpose the matrix\n case GL.FLOAT_MAT2: return gl.uniformMatrix2fv(location, false, arrayValue);\n case GL.FLOAT_MAT3: return gl.uniformMatrix3fv(location, false, arrayValue);\n case GL.FLOAT_MAT4: return gl.uniformMatrix4fv(location, false, arrayValue);\n\n // WebGL2 - rectangular matrices\n case GL.FLOAT_MAT2x3: return gl2.uniformMatrix2x3fv(location, false, arrayValue);\n case GL.FLOAT_MAT2x4: return gl2.uniformMatrix2x4fv(location, false, arrayValue);\n case GL.FLOAT_MAT3x2: return gl2.uniformMatrix3x2fv(location, false, arrayValue);\n case GL.FLOAT_MAT3x4: return gl2.uniformMatrix3x4fv(location, false, arrayValue);\n case GL.FLOAT_MAT4x2: return gl2.uniformMatrix4x2fv(location, false, arrayValue);\n case GL.FLOAT_MAT4x3: return gl2.uniformMatrix4x3fv(location, false, arrayValue);\n }\n\n throw new Error('Illegal uniform');\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {GL, GLPrimitiveTopology, GLPrimitive} from '@luma.gl/webgl/constants';\nimport {PrimitiveTopology} from '@luma.gl/core';\n\n// Counts the number of complete primitives given a number of vertices and a drawMode\nexport function getPrimitiveDrawMode(drawMode: GLPrimitiveTopology): GLPrimitive {\n switch (drawMode) {\n case GL.POINTS:\n return GL.POINTS;\n case GL.LINES:\n return GL.LINES;\n case GL.LINE_STRIP:\n return GL.LINES;\n case GL.LINE_LOOP:\n return GL.LINES;\n case GL.TRIANGLES:\n return GL.TRIANGLES;\n case GL.TRIANGLE_STRIP:\n return GL.TRIANGLES;\n case GL.TRIANGLE_FAN:\n return GL.TRIANGLES;\n default:\n throw new Error('drawMode');\n }\n}\n\n// Counts the number of complete \"primitives\" given a number of vertices and a drawMode\nexport function getPrimitiveCount(options: {\n drawMode: GLPrimitiveTopology;\n vertexCount: number;\n}): number {\n const {drawMode, vertexCount} = options;\n switch (drawMode) {\n case GL.POINTS:\n case GL.LINE_LOOP:\n return vertexCount;\n case GL.LINES:\n return vertexCount / 2;\n case GL.LINE_STRIP:\n return vertexCount - 1;\n case GL.TRIANGLES:\n return vertexCount / 3;\n case GL.TRIANGLE_STRIP:\n case GL.TRIANGLE_FAN:\n return vertexCount - 2;\n default:\n throw new Error('drawMode');\n }\n}\n\n// Counts the number of vertices after splitting the vertex stream into separate \"primitives\"\nexport function getVertexCount(options: {\n drawMode: GLPrimitiveTopology;\n vertexCount: number;\n}): number {\n const {drawMode, vertexCount} = options;\n const primitiveCount = getPrimitiveCount({drawMode, vertexCount});\n switch (getPrimitiveDrawMode(drawMode)) {\n case GL.POINTS:\n return primitiveCount;\n case GL.LINES:\n return primitiveCount * 2;\n case GL.TRIANGLES:\n return primitiveCount * 3;\n default:\n throw new Error('drawMode');\n }\n}\n\n/** Get the primitive type for draw */\nexport function getGLDrawMode(\n topology: PrimitiveTopology\n):\n | GL.POINTS\n | GL.LINES\n | GL.LINE_STRIP\n | GL.LINE_LOOP\n | GL.TRIANGLES\n | GL.TRIANGLE_STRIP\n | GL.TRIANGLE_FAN {\n // biome-ignore format: preserve layout\n switch (topology) {\n case 'point-list': return GL.POINTS;\n case 'line-list': return GL.LINES;\n case 'line-strip': return GL.LINE_STRIP;\n case 'triangle-list': return GL.TRIANGLES;\n case 'triangle-strip': return GL.TRIANGLE_STRIP;\n default: throw new Error(topology);\n }\n}\n\n/** Get the primitive type for transform feedback */\nexport function getGLPrimitive(topology: PrimitiveTopology): GL.POINTS | GL.LINES | GL.TRIANGLES {\n // biome-ignore format: preserve layout\n switch (topology) {\n case 'point-list': return GL.POINTS;\n case 'line-list': return GL.LINES;\n case 'line-strip': return GL.LINES;\n case 'triangle-list': return GL.TRIANGLES;\n case 'triangle-strip': return GL.TRIANGLES;\n default: throw new Error(topology);\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {\n RenderPipelineProps,\n RenderPipelineParameters,\n PrimitiveTopology,\n ShaderLayout,\n UniformValue,\n Bindings,\n BindingsByGroup,\n RenderPass,\n VertexArray\n} from '@luma.gl/core';\nimport {RenderPipeline, flattenBindingsByGroup, log, normalizeBindingsByGroup} from '@luma.gl/core';\n// import {getAttributeInfosFromLayouts} from '@luma.gl/core';\nimport {GL} from '@luma.gl/webgl/constants';\n\nimport {withDeviceAndGLParameters} from '../converters/device-parameters';\nimport {setUniform} from '../helpers/set-uniform';\n// import {copyUniform, checkUniformValues} from '../../classes/uniforms';\n\nimport {WebGLDevice} from '../webgl-device';\nimport {WEBGLBuffer} from './webgl-buffer';\nimport {WEBGLShader} from './webgl-shader';\nimport {WEBGLFramebuffer} from './webgl-framebuffer';\nimport {WEBGLTexture} from './webgl-texture';\nimport {WEBGLTextureView} from './webgl-texture-view';\nimport {WEBGLRenderPass} from './webgl-render-pass';\nimport {WEBGLTransformFeedback} from './webgl-transform-feedback';\nimport {getGLDrawMode} from '../helpers/webgl-topology-utils';\nimport {WEBGLSharedRenderPipeline} from './webgl-shared-render-pipeline';\n\n/** Creates a new render pipeline */\nexport class WEBGLRenderPipeline extends RenderPipeline {\n /** The WebGL device that created this render pipeline */\n readonly device: WebGLDevice;\n /** Handle to underlying WebGL program */\n readonly handle: WebGLProgram;\n /** vertex shader */\n vs: WEBGLShader;\n /** fragment shader */\n fs: WEBGLShader;\n /** The layout extracted from shader by WebGL introspection APIs */\n introspectedLayout: ShaderLayout;\n\n /** Compatibility path for direct pipeline.setBindings() usage */\n bindings: Bindings = {};\n /** Compatibility path for direct pipeline.uniforms usage */\n uniforms: Record = {};\n /** WebGL varyings */\n varyings: string[] | null = null;\n\n _uniformCount: number = 0;\n _uniformSetters: Record = {}; // TODO are these used?\n\n override get [Symbol.toStringTag]() {\n return 'WEBGLRenderPipeline';\n }\n\n constructor(device: WebGLDevice, props: RenderPipelineProps) {\n super(device, props);\n this.device = device;\n const webglSharedRenderPipeline =\n (this.sharedRenderPipeline as WEBGLSharedRenderPipeline | null) ||\n (this.device._createSharedRenderPipelineWebGL(props) as WEBGLSharedRenderPipeline);\n\n this.sharedRenderPipeline = webglSharedRenderPipeline;\n this.handle = webglSharedRenderPipeline.handle;\n this.vs = webglSharedRenderPipeline.vs;\n this.fs = webglSharedRenderPipeline.fs;\n this.linkStatus = webglSharedRenderPipeline.linkStatus;\n this.introspectedLayout = webglSharedRenderPipeline.introspectedLayout;\n this.device._setWebGLDebugMetadata(this.handle, this, {spector: {id: this.props.id}});\n\n // WebGL only honors shaderLayout overrides for attributes that already exist in the\n // linked program, and only the `type` / `stepMode` fields participate in the merge.\n // Bindings and unknown attributes are ignored. If WebGL cache keys ever depend on\n // `shaderLayout`, they need to match these merge semantics rather than the raw prop.\n this.shaderLayout = props.shaderLayout\n ? mergeShaderLayout(this.introspectedLayout, props.shaderLayout)\n : this.introspectedLayout;\n }\n\n override destroy(): void {\n if (this.destroyed) {\n return;\n }\n if (this.sharedRenderPipeline && !this.props._sharedRenderPipeline) {\n this.sharedRenderPipeline.destroy();\n }\n this.destroyResource();\n }\n\n /**\n * Compatibility shim for code paths that still set bindings on the pipeline.\n * Shared-model draws pass bindings per draw and do not rely on this state.\n */\n setBindings(bindings: Bindings | BindingsByGroup, options?: {disableWarnings?: boolean}): void {\n const flatBindings = flattenBindingsByGroup(\n normalizeBindingsByGroup(this.shaderLayout, bindings)\n );\n for (const [name, value] of Object.entries(flatBindings)) {\n const binding = getShaderLayoutBindingByName(this.shaderLayout, name);\n\n if (!binding) {\n const validBindings = this.shaderLayout.bindings\n .map(binding_ => `\"${binding_.name}\"`)\n .join(', ');\n if (!options?.disableWarnings) {\n log.warn(\n `No binding \"${name}\" in render pipeline \"${this.id}\", expected one of ${validBindings}`,\n value\n )();\n }\n } else {\n if (!value) {\n log.warn(`Unsetting binding \"${name}\" in render pipeline \"${this.id}\"`)();\n }\n switch (binding.type) {\n case 'uniform':\n // @ts-expect-error\n if (!(value instanceof WEBGLBuffer) && !(value.buffer instanceof WEBGLBuffer)) {\n throw new Error('buffer value');\n }\n break;\n case 'texture':\n if (\n !(\n value instanceof WEBGLTextureView ||\n value instanceof WEBGLTexture ||\n value instanceof WEBGLFramebuffer\n )\n ) {\n throw new Error(`${this} Bad texture binding for ${name}`);\n }\n break;\n case 'sampler':\n log.warn(`Ignoring sampler ${name}`)();\n break;\n default:\n throw new Error(binding.type);\n }\n\n this.bindings[name] = value;\n }\n }\n }\n\n /** @todo needed for portable model\n * @note The WebGL API is offers many ways to draw things\n * This function unifies those ways into a single call using common parameters with sane defaults\n */\n draw(options: {\n renderPass: RenderPass;\n parameters?: RenderPipelineParameters;\n topology?: PrimitiveTopology;\n vertexArray: VertexArray;\n isInstanced?: boolean;\n vertexCount?: number;\n indexCount?: number;\n instanceCount?: number;\n firstVertex?: number;\n firstIndex?: number;\n firstInstance?: number;\n baseVertex?: number;\n transformFeedback?: WEBGLTransformFeedback;\n bindings?: Bindings;\n bindGroups?: BindingsByGroup;\n _bindGroupCacheKeys?: Partial>;\n uniforms?: Record;\n }): boolean {\n this._syncLinkStatus();\n const drawBindings = options.bindGroups\n ? flattenBindingsByGroup(options.bindGroups)\n : options.bindings || this.bindings;\n\n const {\n renderPass,\n parameters = this.props.parameters,\n topology = this.props.topology,\n vertexArray,\n vertexCount,\n // indexCount,\n instanceCount,\n isInstanced = false,\n firstVertex = 0,\n // firstIndex,\n // firstInstance,\n // baseVertex,\n transformFeedback,\n uniforms = this.uniforms\n } = options;\n\n const glDrawMode = getGLDrawMode(topology);\n const isIndexed: boolean = Boolean(vertexArray.indexBuffer);\n const glIndexType = (vertexArray.indexBuffer as WEBGLBuffer)?.glIndexType;\n // Note that we sometimes get called with 0 instances\n\n // If we are using async linking, we need to wait until linking completes\n if (this.linkStatus !== 'success') {\n log.info(2, `RenderPipeline:${this.id}.draw() aborted - waiting for shader linking`)();\n return false;\n }\n\n // Avoid WebGL draw call when not rendering any data or values are incomplete\n // Note: async textures set as uniforms might still be loading.\n // Now that all uniforms have been updated, check if any texture\n // in the uniforms is not yet initialized, then we don't draw\n if (!this._areTexturesRenderable(drawBindings)) {\n log.info(2, `RenderPipeline:${this.id}.draw() aborted - textures not yet loaded`)();\n // Note: false means that the app needs to redraw the pipeline again.\n return false;\n }\n\n // (isInstanced && instanceCount === 0)\n // if (vertexCount === 0) {\n // log.info(2, `RenderPipeline:${this.id}.draw() aborted - no vertices to draw`)();\n // Note: false means that the app needs to redraw the pipeline again.\n // return true;\n // }\n\n this.device.gl.useProgram(this.handle);\n\n // Note: Rebinds constant attributes before each draw call\n vertexArray.bindBeforeRender(renderPass);\n\n if (transformFeedback) {\n transformFeedback.begin(this.props.topology);\n }\n\n // We have to apply bindings before every draw call since other draw calls will overwrite\n this._applyBindings(drawBindings, {disableWarnings: this.props.disableWarnings});\n this._applyUniforms(uniforms);\n\n const webglRenderPass = renderPass as WEBGLRenderPass;\n\n withDeviceAndGLParameters(this.device, parameters, webglRenderPass.glParameters, () => {\n if (isIndexed && isInstanced) {\n this.device.gl.drawElementsInstanced(\n glDrawMode,\n vertexCount || 0, // indexCount?\n glIndexType,\n firstVertex,\n instanceCount || 0\n );\n // } else if (isIndexed && this.device.isWebGL2 && !isNaN(start) && !isNaN(end)) {\n // this.device.gldrawRangeElements(glDrawMode, start, end, vertexCount, glIndexType, offset);\n } else if (isIndexed) {\n this.device.gl.drawElements(glDrawMode, vertexCount || 0, glIndexType, firstVertex); // indexCount?\n } else if (isInstanced) {\n this.device.gl.drawArraysInstanced(\n glDrawMode,\n firstVertex,\n vertexCount || 0,\n instanceCount || 0\n );\n } else {\n this.device.gl.drawArrays(glDrawMode, firstVertex, vertexCount || 0);\n }\n\n if (transformFeedback) {\n transformFeedback.end();\n }\n });\n\n vertexArray.unbindAfterRender(renderPass);\n\n return true;\n }\n\n /**\n * Checks if all texture-values uniforms are renderable (i.e. loaded)\n * Update a texture if needed (e.g. from video)\n * Note: This is currently done before every draw call\n */\n _areTexturesRenderable(bindings: Bindings) {\n let texturesRenderable = true;\n\n for (const bindingInfo of this.shaderLayout.bindings) {\n if (!getBindingValueForLayoutBinding(bindings, bindingInfo.name)) {\n log.warn(`Binding ${bindingInfo.name} not found in ${this.id}`)();\n texturesRenderable = false;\n }\n }\n\n // TODO - remove this should be handled by ExternalTexture\n // for (const [, texture] of Object.entries(this.bindings)) {\n // if (texture instanceof WEBGLTexture) {\n // texture.update();\n // }\n // }\n\n return texturesRenderable;\n }\n\n /** Apply any bindings (before each draw call) */\n _applyBindings(bindings: Bindings, _options?: {disableWarnings?: boolean}) {\n this._syncLinkStatus();\n\n // If we are using async linking, we need to wait until linking completes\n if (this.linkStatus !== 'success') {\n return;\n }\n\n const {gl} = this.device;\n gl.useProgram(this.handle);\n\n let textureUnit = 0;\n let uniformBufferIndex = 0;\n for (const binding of this.shaderLayout.bindings) {\n const value = getBindingValueForLayoutBinding(bindings, binding.name);\n if (!value) {\n throw new Error(`No value for binding ${binding.name} in ${this.id}`);\n }\n switch (binding.type) {\n case 'uniform':\n // Set buffer\n const {name} = binding;\n const location = gl.getUniformBlockIndex(this.handle, name);\n if ((location as GL) === GL.INVALID_INDEX) {\n throw new Error(`Invalid uniform block name ${name}`);\n }\n gl.uniformBlockBinding(this.handle, location, uniformBufferIndex);\n if (value instanceof WEBGLBuffer) {\n gl.bindBufferBase(GL.UNIFORM_BUFFER, uniformBufferIndex, value.handle);\n } else {\n const bufferBinding = value as {buffer: WEBGLBuffer; offset?: number; size?: number};\n gl.bindBufferRange(\n GL.UNIFORM_BUFFER,\n uniformBufferIndex,\n bufferBinding.buffer.handle,\n bufferBinding.offset || 0,\n bufferBinding.size || bufferBinding.buffer.byteLength - (bufferBinding.offset || 0)\n );\n }\n uniformBufferIndex += 1;\n break;\n\n case 'texture':\n if (\n !(\n value instanceof WEBGLTextureView ||\n value instanceof WEBGLTexture ||\n value instanceof WEBGLFramebuffer\n )\n ) {\n throw new Error('texture');\n }\n let texture: WEBGLTexture;\n if (value instanceof WEBGLTextureView) {\n texture = value.texture;\n } else if (value instanceof WEBGLTexture) {\n texture = value;\n } else if (\n value instanceof WEBGLFramebuffer &&\n value.colorAttachments[0] instanceof WEBGLTextureView\n ) {\n log.warn(\n 'Passing framebuffer in texture binding may be deprecated. Use fbo.colorAttachments[0] instead'\n )();\n texture = value.colorAttachments[0].texture;\n } else {\n throw new Error('No texture');\n }\n\n gl.activeTexture(GL.TEXTURE0 + textureUnit);\n gl.bindTexture(texture.glTarget, texture.handle);\n // gl.bindSampler(textureUnit, sampler.handle);\n textureUnit += 1;\n break;\n\n case 'sampler':\n // ignore\n break;\n\n case 'storage':\n case 'read-only-storage':\n throw new Error(`binding type '${binding.type}' not supported in WebGL`);\n }\n }\n }\n\n /**\n * Due to program sharing, uniforms need to be reset before every draw call\n * (though caching will avoid redundant WebGL calls)\n */\n _applyUniforms(uniforms: Record) {\n for (const uniformLayout of this.shaderLayout.uniforms || []) {\n const {name, location, type, textureUnit} = uniformLayout;\n const value = uniforms[name] ?? textureUnit;\n if (value !== undefined) {\n setUniform(this.device.gl, location, type, value);\n }\n }\n }\n\n private _syncLinkStatus(): void {\n this.linkStatus = (this.sharedRenderPipeline as WEBGLSharedRenderPipeline).linkStatus;\n }\n}\n\n/**\n * Merges an provided shader layout into a base shader layout\n * In WebGL, this allows the auto generated shader layout to be overridden by the application\n * Typically to change the format of the vertex attributes (from float32x4 to uint8x4 etc).\n * @todo Drop this? Aren't all use cases covered by mergeBufferLayout()?\n */\nfunction mergeShaderLayout(baseLayout: ShaderLayout, overrideLayout: ShaderLayout): ShaderLayout {\n // Deep clone the base layout\n const mergedLayout: ShaderLayout = {\n ...baseLayout,\n attributes: baseLayout.attributes.map(attribute => ({...attribute})),\n bindings: baseLayout.bindings.map(binding => ({...binding}))\n };\n // Merge the attributes\n for (const attribute of overrideLayout?.attributes || []) {\n const baseAttribute = mergedLayout.attributes.find(attr => attr.name === attribute.name);\n if (!baseAttribute) {\n log.warn(`shader layout attribute ${attribute.name} not present in shader`);\n } else {\n baseAttribute.type = attribute.type || baseAttribute.type;\n baseAttribute.stepMode = attribute.stepMode || baseAttribute.stepMode;\n }\n }\n\n for (const binding of overrideLayout?.bindings || []) {\n const baseBinding = getShaderLayoutBindingByName(mergedLayout, binding.name);\n if (!baseBinding) {\n log.warn(`shader layout binding ${binding.name} not present in shader`);\n continue;\n }\n Object.assign(baseBinding, binding);\n }\n return mergedLayout;\n}\n\nfunction getShaderLayoutBindingByName(\n shaderLayout: ShaderLayout,\n bindingName: string\n): ShaderLayout['bindings'][number] | undefined {\n return shaderLayout.bindings.find(\n binding =>\n binding.name === bindingName ||\n binding.name === `${bindingName}Uniforms` ||\n `${binding.name}Uniforms` === bindingName\n );\n}\n\nfunction getBindingValueForLayoutBinding(\n bindings: Bindings,\n bindingName: string\n): Bindings[string] | undefined {\n return (\n bindings[bindingName] ||\n bindings[`${bindingName}Uniforms`] ||\n bindings[bindingName.replace(/Uniforms$/, '')]\n );\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {VariableShaderType, SignedDataType, VertexFormat, NormalizedDataType} from '@luma.gl/core';\nimport {GL, GLUniformType, GLSamplerType, GLDataType} from '@luma.gl/webgl/constants';\n\nexport type TextureBindingInfo = {\n viewDimension: '1d' | '2d' | '2d-array' | 'cube' | 'cube-array' | '3d';\n sampleType: 'float' | 'unfilterable-float' | 'depth' | 'sint' | 'uint';\n};\n\n/** Converts to a luma shadertype to a GL data type (GL.BYTE, GL.FLOAT32 etc) */\nexport function convertDataTypeToGLDataType(normalizedType: NormalizedDataType): GLDataType {\n return NORMALIZED_SHADER_TYPE_TO_WEBGL[normalizedType];\n}\n\n/** Convert a WebGL \"compisite type (e.g. GL.VEC3) into the corresponding luma shader uniform type */\nexport function convertGLUniformTypeToShaderVariableType(\n glUniformType: GLUniformType\n): VariableShaderType {\n return WEBGL_SHADER_TYPES[glUniformType];\n}\n\n/** Check if a WebGL \"uniform:\" is a texture binding */\nexport function isGLSamplerType(type: GLUniformType | GLSamplerType): type is GLSamplerType {\n // @ts-ignore TODO\n return Boolean(WEBGL_SAMPLER_TO_TEXTURE_BINDINGS[type]);\n}\n\n/* Get luma texture binding info (viewDimension and sampleType) from a WebGL \"sampler\" binding */\nexport function getTextureBindingFromGLSamplerType(\n glSamplerType: GLSamplerType\n): TextureBindingInfo {\n return WEBGL_SAMPLER_TO_TEXTURE_BINDINGS[glSamplerType];\n}\n\n/** Get vertex format from GL constants */\nexport function getVertexFormatFromGL(type: GLDataType, components: 1 | 2 | 3 | 4): VertexFormat {\n const base = getVertexTypeFromGL(type);\n // biome-ignore format: preserve layout\n switch (components) {\n case 1: return base;\n case 2: return `${base}x2`;\n // @ts-expect-error - deal with lack of \"unaligned\" formats\n case 3: return `${base}x3`;\n case 4: return `${base}x4`;\n }\n // @ts-ignore unreachable\n throw new Error(String(components));\n}\n\n/** Get data type from GL constants */\nexport function getVertexTypeFromGL(glType: GLDataType, normalized = false): NormalizedDataType {\n const index = normalized ? 1 : 0;\n return WEBGL_TO_NORMALIZED_DATA_TYPE[glType][index];\n}\n\n// Composite types table\n// @ts-ignore TODO - fix the type confusion here\nconst WEBGL_SHADER_TYPES: Record = {\n [GL.FLOAT]: 'f32',\n [GL.FLOAT_VEC2]: 'vec2',\n [GL.FLOAT_VEC3]: 'vec3',\n [GL.FLOAT_VEC4]: 'vec4',\n\n [GL.INT]: 'i32',\n [GL.INT_VEC2]: 'vec2',\n [GL.INT_VEC3]: 'vec3',\n [GL.INT_VEC4]: 'vec4',\n\n [GL.UNSIGNED_INT]: 'u32',\n [GL.UNSIGNED_INT_VEC2]: 'vec2',\n [GL.UNSIGNED_INT_VEC3]: 'vec3',\n [GL.UNSIGNED_INT_VEC4]: 'vec4',\n\n [GL.BOOL]: 'f32',\n [GL.BOOL_VEC2]: 'vec2',\n [GL.BOOL_VEC3]: 'vec3',\n [GL.BOOL_VEC4]: 'vec4',\n\n // TODO - are sizes/components below correct?\n [GL.FLOAT_MAT2]: 'mat2x2',\n [GL.FLOAT_MAT2x3]: 'mat2x3',\n [GL.FLOAT_MAT2x4]: 'mat2x4',\n\n [GL.FLOAT_MAT3x2]: 'mat3x2',\n [GL.FLOAT_MAT3]: 'mat3x3',\n [GL.FLOAT_MAT3x4]: 'mat3x4',\n\n [GL.FLOAT_MAT4x2]: 'mat4x2',\n [GL.FLOAT_MAT4x3]: 'mat4x3',\n [GL.FLOAT_MAT4]: 'mat4x4'\n};\n\nconst WEBGL_SAMPLER_TO_TEXTURE_BINDINGS: Record = {\n [GL.SAMPLER_2D]: {viewDimension: '2d', sampleType: 'float'},\n [GL.SAMPLER_CUBE]: {viewDimension: 'cube', sampleType: 'float'},\n [GL.SAMPLER_3D]: {viewDimension: '3d', sampleType: 'float'},\n [GL.SAMPLER_2D_SHADOW]: {viewDimension: '3d', sampleType: 'depth'},\n [GL.SAMPLER_2D_ARRAY]: {viewDimension: '2d-array', sampleType: 'float'},\n [GL.SAMPLER_2D_ARRAY_SHADOW]: {viewDimension: '2d-array', sampleType: 'depth'},\n [GL.SAMPLER_CUBE_SHADOW]: {viewDimension: 'cube', sampleType: 'float'},\n [GL.INT_SAMPLER_2D]: {viewDimension: '2d', sampleType: 'sint'},\n [GL.INT_SAMPLER_3D]: {viewDimension: '3d', sampleType: 'sint'},\n [GL.INT_SAMPLER_CUBE]: {viewDimension: 'cube', sampleType: 'sint'},\n [GL.INT_SAMPLER_2D_ARRAY]: {viewDimension: '2d-array', sampleType: 'uint'},\n [GL.UNSIGNED_INT_SAMPLER_2D]: {viewDimension: '2d', sampleType: 'uint'},\n [GL.UNSIGNED_INT_SAMPLER_3D]: {viewDimension: '3d', sampleType: 'uint'},\n [GL.UNSIGNED_INT_SAMPLER_CUBE]: {viewDimension: 'cube', sampleType: 'uint'},\n [GL.UNSIGNED_INT_SAMPLER_2D_ARRAY]: {viewDimension: '2d-array', sampleType: 'uint'}\n};\n\n/** Map from WebGL normalized types to WebGL */\nconst NORMALIZED_SHADER_TYPE_TO_WEBGL: Record = {\n uint8: GL.UNSIGNED_BYTE,\n sint8: GL.BYTE,\n unorm8: GL.UNSIGNED_BYTE,\n snorm8: GL.BYTE,\n uint16: GL.UNSIGNED_SHORT,\n sint16: GL.SHORT,\n unorm16: GL.UNSIGNED_SHORT,\n snorm16: GL.SHORT,\n uint32: GL.UNSIGNED_INT,\n sint32: GL.INT,\n // WebGPU does not support normalized 32 bit integer attributes\n // 'unorm32': GL.UNSIGNED_INT,\n // 'snorm32': GL.INT,\n float16: GL.HALF_FLOAT,\n float32: GL.FLOAT\n};\n\n/* Map from WebGL types to webgpu normalized types */\nconst WEBGL_TO_NORMALIZED_DATA_TYPE: Record = {\n [GL.BYTE]: ['sint8', 'snorm16'],\n [GL.UNSIGNED_BYTE]: ['uint8', 'unorm8'],\n [GL.SHORT]: ['sint16', 'unorm16'],\n [GL.UNSIGNED_SHORT]: ['uint16', 'unorm16'],\n [GL.INT]: ['sint32', 'sint32'],\n [GL.UNSIGNED_INT]: ['uint32', 'uint32'],\n [GL.FLOAT]: ['float32', 'float32'],\n [GL.HALF_FLOAT]: ['float16', 'float16']\n};\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {\n ShaderLayout,\n UniformBinding,\n UniformBlockBinding,\n AttributeDeclaration,\n VaryingBinding,\n AttributeShaderType\n} from '@luma.gl/core';\nimport {getVariableShaderTypeInfo, assertDefined, log} from '@luma.gl/core';\n\nimport {GL, GLUniformType} from '@luma.gl/webgl/constants';\nimport {\n isGLSamplerType,\n getTextureBindingFromGLSamplerType,\n convertGLUniformTypeToShaderVariableType\n} from '../converters/webgl-shadertypes';\n\n/**\n * Extract metadata describing binding information for a program's shaders\n * Note: `linkProgram()` needs to have been called\n * (although linking does not need to have been successful).\n */\nexport function getShaderLayoutFromGLSL(\n gl: WebGL2RenderingContext,\n program: WebGLProgram\n): ShaderLayout {\n const shaderLayout: ShaderLayout = {\n attributes: [],\n bindings: []\n };\n\n shaderLayout.attributes = readAttributeDeclarations(gl, program);\n\n // Uniform blocks\n const uniformBlocks: UniformBlockBinding[] = readUniformBlocks(gl, program);\n for (const uniformBlock of uniformBlocks) {\n const uniforms = uniformBlock.uniforms.map(uniform => ({\n name: uniform.name,\n format: uniform.format,\n byteOffset: uniform.byteOffset,\n byteStride: uniform.byteStride,\n arrayLength: uniform.arrayLength\n }));\n shaderLayout.bindings.push({\n type: 'uniform',\n name: uniformBlock.name,\n group: 0,\n location: uniformBlock.location,\n visibility: (uniformBlock.vertex ? 0x1 : 0) & (uniformBlock.fragment ? 0x2 : 0),\n minBindingSize: uniformBlock.byteLength,\n uniforms\n });\n }\n\n const uniforms: UniformBinding[] = readUniformBindings(gl, program);\n let textureUnit = 0;\n for (const uniform of uniforms) {\n if (isGLSamplerType(uniform.type)) {\n const {viewDimension, sampleType} = getTextureBindingFromGLSamplerType(uniform.type);\n shaderLayout.bindings.push({\n type: 'texture',\n name: uniform.name,\n group: 0,\n location: textureUnit,\n viewDimension,\n sampleType\n });\n\n // @ts-expect-error\n uniform.textureUnit = textureUnit;\n textureUnit += 1;\n }\n }\n\n if (uniforms.length) {\n shaderLayout.uniforms = uniforms;\n }\n\n // Varyings\n const varyings: VaryingBinding[] = readVaryings(gl, program);\n // Note - samplers are always in unform bindings, even if uniform blocks are used\n if (varyings?.length) {\n shaderLayout.varyings = varyings;\n }\n\n return shaderLayout;\n}\n\n// HELPERS\n\n/**\n * Extract info about all transform feedback varyings\n *\n * linkProgram needs to have been called, although linking does not need to have been successful\n */\nfunction readAttributeDeclarations(\n gl: WebGL2RenderingContext,\n program: WebGLProgram\n): AttributeDeclaration[] {\n const attributes: AttributeDeclaration[] = [];\n\n const count = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);\n\n for (let index = 0; index < count; index++) {\n const activeInfo = gl.getActiveAttrib(program, index);\n if (!activeInfo) {\n throw new Error('activeInfo');\n }\n const {name, type: compositeType /* , size*/} = activeInfo;\n const location = gl.getAttribLocation(program, name);\n // Add only user provided attributes, for built-in attributes like `gl_InstanceID` location will be < 0\n if (location >= 0) {\n const attributeType = convertGLUniformTypeToShaderVariableType(compositeType);\n\n // Whether an attribute is instanced is essentially fixed by the structure of the shader code,\n // so it is arguably a static property of the shader.\n // There is no hint in the shader declarations\n // Heuristic: Any attribute name containing the word \"instance\" will be assumed to be instanced\n const stepMode = /instance/i.test(name) ? 'instance' : 'vertex';\n\n attributes.push({\n name,\n location,\n stepMode,\n type: attributeType as AttributeShaderType\n // size - for arrays, size is the number of elements in the array\n });\n }\n }\n\n // Sort by declaration order\n attributes.sort((a: AttributeDeclaration, b: AttributeDeclaration) => a.location - b.location);\n return attributes;\n}\n\n/**\n * Extract info about all transform feedback varyings\n *\n * linkProgram needs to have been called, although linking does not need to have been successful\n */\nfunction readVaryings(gl: WebGL2RenderingContext, program: WebGLProgram): VaryingBinding[] {\n const varyings: VaryingBinding[] = [];\n\n const count = gl.getProgramParameter(program, GL.TRANSFORM_FEEDBACK_VARYINGS);\n for (let location = 0; location < count; location++) {\n const activeInfo = gl.getTransformFeedbackVarying(program, location);\n if (!activeInfo) {\n throw new Error('activeInfo');\n }\n const {name, type: glUniformType, size} = activeInfo;\n const uniformType = convertGLUniformTypeToShaderVariableType(glUniformType as GLUniformType);\n const {type, components} = getVariableShaderTypeInfo(uniformType);\n varyings.push({location, name, type, size: size * components});\n }\n\n varyings.sort((a, b) => a.location - b.location);\n return varyings;\n}\n\n/**\n * Extract info about all uniforms\n *\n * Query uniform locations and build name to setter map.\n */\nfunction readUniformBindings(gl: WebGL2RenderingContext, program: WebGLProgram): UniformBinding[] {\n const uniforms: UniformBinding[] = [];\n\n const uniformCount = gl.getProgramParameter(program, GL.ACTIVE_UNIFORMS);\n for (let i = 0; i < uniformCount; i++) {\n const activeInfo = gl.getActiveUniform(program, i);\n if (!activeInfo) {\n throw new Error('activeInfo');\n }\n const {name: rawName, size, type} = activeInfo;\n const {name, isArray} = parseUniformName(rawName);\n let webglLocation = gl.getUniformLocation(program, name);\n const uniformInfo = {\n // WebGL locations are uniquely typed but just numbers\n location: webglLocation as number,\n name,\n size,\n type,\n isArray\n };\n uniforms.push(uniformInfo);\n\n // Array (e.g. matrix) uniforms can occupy several 4x4 byte banks\n if (uniformInfo.size > 1) {\n for (let j = 0; j < uniformInfo.size; j++) {\n const elementName = `${name}[${j}]`;\n\n webglLocation = gl.getUniformLocation(program, elementName);\n\n const arrayElementUniformInfo = {\n ...uniformInfo,\n name: elementName,\n location: webglLocation as number\n };\n\n uniforms.push(arrayElementUniformInfo);\n }\n }\n }\n return uniforms;\n}\n\n/**\n * Extract info about all \"active\" uniform blocks\n * @note In WebGL, \"active\" just means that unused (inactive) blocks may have been optimized away during linking)\n */\nfunction readUniformBlocks(\n gl: WebGL2RenderingContext,\n program: WebGLProgram\n): UniformBlockBinding[] {\n const getBlockParameter = (blockIndex: number, pname: GL): any =>\n gl.getActiveUniformBlockParameter(program, blockIndex, pname);\n\n const uniformBlocks: UniformBlockBinding[] = [];\n\n const blockCount = gl.getProgramParameter(program, GL.ACTIVE_UNIFORM_BLOCKS);\n for (let blockIndex = 0; blockIndex < blockCount; blockIndex++) {\n const blockInfo: UniformBlockBinding = {\n name: gl.getActiveUniformBlockName(program, blockIndex) || '',\n location: getBlockParameter(blockIndex, GL.UNIFORM_BLOCK_BINDING),\n byteLength: getBlockParameter(blockIndex, GL.UNIFORM_BLOCK_DATA_SIZE),\n vertex: getBlockParameter(blockIndex, GL.UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER),\n fragment: getBlockParameter(blockIndex, GL.UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER),\n uniformCount: getBlockParameter(blockIndex, GL.UNIFORM_BLOCK_ACTIVE_UNIFORMS),\n uniforms: [] as any[]\n };\n\n const uniformIndices =\n (getBlockParameter(blockIndex, GL.UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES) as number[]) || [];\n\n const uniformType = gl.getActiveUniforms(program, uniformIndices, GL.UNIFORM_TYPE); // Array of GLenum indicating the types of the uniforms.\n const uniformArrayLength = gl.getActiveUniforms(program, uniformIndices, GL.UNIFORM_SIZE); // Array of GLuint indicating the sizes of the uniforms.\n // const uniformBlockIndex = gl.getActiveUniforms(\n // program,\n // uniformIndices,\n // GL.UNIFORM_BLOCK_INDEX\n // ); // Array of GLint indicating the block indices of the uniforms.\n const uniformOffset = gl.getActiveUniforms(program, uniformIndices, GL.UNIFORM_OFFSET); // Array of GLint indicating the uniform buffer offsets.\n const uniformStride = gl.getActiveUniforms(program, uniformIndices, GL.UNIFORM_ARRAY_STRIDE); // Array of GLint indicating the strides between the elements.\n // const uniformMatrixStride = gl.getActiveUniforms(\n // program,\n // uniformIndices,\n // GL.UNIFORM_MATRIX_STRIDE\n // ); // Array of GLint indicating the strides between columns of a column-major matrix or a row-major matrix.\n // const uniformRowMajor = gl.getActiveUniforms(program, uniformIndices, GL.UNIFORM_IS_ROW_MAJOR);\n for (let i = 0; i < blockInfo.uniformCount; ++i) {\n const uniformIndex = uniformIndices[i];\n if (uniformIndex !== undefined) {\n const activeInfo = gl.getActiveUniform(program, uniformIndex);\n if (!activeInfo) {\n throw new Error('activeInfo');\n }\n\n const format = convertGLUniformTypeToShaderVariableType(uniformType[i]);\n\n blockInfo.uniforms.push({\n name: activeInfo.name,\n format,\n type: uniformType[i],\n arrayLength: uniformArrayLength[i],\n byteOffset: uniformOffset[i],\n byteStride: uniformStride[i]\n // matrixStride: uniformStride[i],\n // rowMajor: uniformRowMajor[i]\n });\n }\n }\n\n const uniformInstancePrefixes = new Set(\n blockInfo.uniforms\n .map(uniform => uniform.name.split('.')[0])\n .filter((instanceName): instanceName is string => Boolean(instanceName))\n );\n const blockAlias = blockInfo.name.replace(/Uniforms$/, '');\n if (\n uniformInstancePrefixes.size === 1 &&\n !uniformInstancePrefixes.has(blockInfo.name) &&\n !uniformInstancePrefixes.has(blockAlias)\n ) {\n const [instanceName] = uniformInstancePrefixes;\n log.warn(\n `Uniform block \"${blockInfo.name}\" uses GLSL instance \"${instanceName}\". ` +\n `luma.gl binds uniform buffers by block name (\"${blockInfo.name}\") and alias (\"${blockAlias}\"). ` +\n 'Prefer matching the instance name to one of those to avoid confusing silent mismatches.'\n )();\n }\n\n uniformBlocks.push(blockInfo);\n }\n\n uniformBlocks.sort((a, b) => a.location - b.location);\n return uniformBlocks;\n}\n\n/**\n * TOOD - compare with a above, confirm copy, then delete\n const bindings: Binding[] = [];\n const count = gl.getProgramParameter(program, gl.ACTIVE_UNIFORM_BLOCKS);\n for (let blockIndex = 0; blockIndex < count; blockIndex++) {\n const vertex = gl.getActiveUniformBlockParameter(program, blockIndex, gl.UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER),\n const fragment = gl.getActiveUniformBlockParameter(program, blockIndex, gl.UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER),\n const visibility = (vertex) + (fragment);\n const binding: BufferBinding = {\n location: gl.getActiveUniformBlockParameter(program, blockIndex, gl.UNIFORM_BLOCK_BINDING),\n // name: gl.getActiveUniformBlockName(program, blockIndex),\n type: 'uniform',\n visibility,\n minBindingSize: gl.getActiveUniformBlockParameter(program, blockIndex, gl.UNIFORM_BLOCK_DATA_SIZE),\n // uniformCount: gl.getActiveUniformBlockParameter(program, blockIndex, gl.UNIFORM_BLOCK_ACTIVE_UNIFORMS),\n // uniformIndices: gl.getActiveUniformBlockParameter(program, blockIndex, gl.UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES),\n }\n bindings.push(binding);\n }\n*/\n\n// HELPERS\n\nfunction parseUniformName(name: string): {name: string; length: number; isArray: boolean} {\n // Shortcut to avoid redundant or bad matches\n if (name[name.length - 1] !== ']') {\n return {\n name,\n length: 1,\n isArray: false\n };\n }\n\n // if array name then clean the array brackets\n const UNIFORM_NAME_REGEXP = /([^[]*)(\\[[0-9]+\\])?/;\n const matches = UNIFORM_NAME_REGEXP.exec(name);\n const uniformName = assertDefined(matches?.[1], `Failed to parse GLSL uniform name ${name}`);\n return {\n name: uniformName,\n // TODO - is this a bug, shouldn't we return the value?\n length: matches?.[2] ? 1 : 0,\n isArray: Boolean(matches?.[2])\n };\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {GL} from '@luma.gl/webgl/constants';\nimport {\n SharedRenderPipeline,\n log,\n type ShaderLayout,\n type SharedRenderPipelineProps\n} from '@luma.gl/core';\n\nimport {getShaderLayoutFromGLSL} from '../helpers/get-shader-layout-from-glsl';\nimport {isGLSamplerType} from '../converters/webgl-shadertypes';\nimport type {WebGLDevice} from '../webgl-device';\nimport type {WEBGLShader} from './webgl-shader';\n\nconst LOG_PROGRAM_PERF_PRIORITY = 4;\n\nexport class WEBGLSharedRenderPipeline extends SharedRenderPipeline {\n readonly device: WebGLDevice;\n readonly handle: WebGLProgram;\n readonly vs: WEBGLShader;\n readonly fs: WEBGLShader;\n introspectedLayout: ShaderLayout = {attributes: [], bindings: [], uniforms: []};\n linkStatus: 'pending' | 'success' | 'error' = 'pending';\n\n constructor(\n device: WebGLDevice,\n props: SharedRenderPipelineProps & {\n handle?: WebGLProgram;\n vs: WEBGLShader;\n fs: WEBGLShader;\n }\n ) {\n super(device, props);\n this.device = device;\n this.handle = props.handle || this.device.gl.createProgram();\n this.vs = props.vs;\n this.fs = props.fs;\n\n if (props.varyings && props.varyings.length > 0) {\n this.device.gl.transformFeedbackVaryings(\n this.handle,\n props.varyings,\n props.bufferMode || GL.SEPARATE_ATTRIBS\n );\n }\n\n this._linkShaders();\n // Introspection happens after linking to build wrapper-facing layout metadata.\n // It is not a prerequisite for deciding whether a shared `WebGLProgram` can be\n // reused; that decision must remain based on the shared-pipeline cache key alone.\n log.time(3, `RenderPipeline ${this.id} - shaderLayout introspection`)();\n this.introspectedLayout = getShaderLayoutFromGLSL(this.device.gl, this.handle);\n log.timeEnd(3, `RenderPipeline ${this.id} - shaderLayout introspection`)();\n }\n\n override destroy(): void {\n if (this.destroyed) {\n return;\n }\n\n this.device.gl.useProgram(null);\n this.device.gl.deleteProgram(this.handle);\n // @ts-expect-error\n this.handle.destroyed = true;\n this.destroyResource();\n }\n\n protected async _linkShaders() {\n const {gl} = this.device;\n gl.attachShader(this.handle, this.vs.handle);\n gl.attachShader(this.handle, this.fs.handle);\n log.time(LOG_PROGRAM_PERF_PRIORITY, `linkProgram for ${this.id}`)();\n gl.linkProgram(this.handle);\n log.timeEnd(LOG_PROGRAM_PERF_PRIORITY, `linkProgram for ${this.id}`)();\n\n if (!this.device.features.has('compilation-status-async-webgl')) {\n const status = this._getLinkStatus();\n this._reportLinkStatus(status);\n return;\n }\n\n log.once(1, 'RenderPipeline linking is asynchronous')();\n await this._waitForLinkComplete();\n log.info(2, `RenderPipeline ${this.id} - async linking complete: ${this.linkStatus}`)();\n const status = this._getLinkStatus();\n this._reportLinkStatus(status);\n }\n\n async _reportLinkStatus(status: 'success' | 'link-error' | 'validation-error'): Promise {\n switch (status) {\n case 'success':\n return;\n\n default:\n const errorType = status === 'link-error' ? 'Link error' : 'Validation error';\n switch (this.vs.compilationStatus) {\n case 'error':\n this.vs.debugShader();\n throw new Error(`${this} ${errorType} during compilation of ${this.vs}`);\n case 'pending':\n await this.vs.asyncCompilationStatus;\n this.vs.debugShader();\n break;\n case 'success':\n break;\n }\n\n switch (this.fs?.compilationStatus) {\n case 'error':\n this.fs.debugShader();\n throw new Error(`${this} ${errorType} during compilation of ${this.fs}`);\n case 'pending':\n await this.fs.asyncCompilationStatus;\n this.fs.debugShader();\n break;\n case 'success':\n break;\n }\n\n const linkErrorLog = this.device.gl.getProgramInfoLog(this.handle);\n this.device.reportError(\n new Error(`${errorType} during ${status}: ${linkErrorLog}`),\n this\n )();\n this.device.debug();\n }\n }\n\n _getLinkStatus(): 'success' | 'link-error' | 'validation-error' {\n const {gl} = this.device;\n const linked = gl.getProgramParameter(this.handle, GL.LINK_STATUS);\n if (!linked) {\n this.linkStatus = 'error';\n return 'link-error';\n }\n\n this._initializeSamplerUniforms();\n gl.validateProgram(this.handle);\n const validated = gl.getProgramParameter(this.handle, GL.VALIDATE_STATUS);\n if (!validated) {\n this.linkStatus = 'error';\n return 'validation-error';\n }\n\n this.linkStatus = 'success';\n return 'success';\n }\n\n _initializeSamplerUniforms(): void {\n const {gl} = this.device;\n gl.useProgram(this.handle);\n\n let textureUnit = 0;\n const uniformCount = gl.getProgramParameter(this.handle, GL.ACTIVE_UNIFORMS);\n for (let uniformIndex = 0; uniformIndex < uniformCount; uniformIndex++) {\n const activeInfo = gl.getActiveUniform(this.handle, uniformIndex);\n if (activeInfo && isGLSamplerType(activeInfo.type)) {\n const isArray = activeInfo.name.endsWith('[0]');\n const uniformName = isArray ? activeInfo.name.slice(0, -3) : activeInfo.name;\n const location = gl.getUniformLocation(this.handle, uniformName);\n\n if (location !== null) {\n textureUnit = this._assignSamplerUniform(location, activeInfo, isArray, textureUnit);\n }\n }\n }\n }\n\n _assignSamplerUniform(\n location: WebGLUniformLocation,\n activeInfo: WebGLActiveInfo,\n isArray: boolean,\n textureUnit: number\n ): number {\n const {gl} = this.device;\n\n if (isArray && activeInfo.size > 1) {\n const textureUnits = Int32Array.from(\n {length: activeInfo.size},\n (_, arrayIndex) => textureUnit + arrayIndex\n );\n gl.uniform1iv(location, textureUnits);\n return textureUnit + activeInfo.size;\n }\n\n gl.uniform1i(location, textureUnit);\n return textureUnit + 1;\n }\n\n async _waitForLinkComplete(): Promise {\n const waitMs = async (ms: number) => await new Promise(resolve => setTimeout(resolve, ms));\n const DELAY_MS = 10;\n\n if (!this.device.features.has('compilation-status-async-webgl')) {\n await waitMs(DELAY_MS);\n return;\n }\n\n const {gl} = this.device;\n for (;;) {\n const complete = gl.getProgramParameter(this.handle, GL.COMPLETION_STATUS_KHR);\n if (complete) {\n return;\n }\n await waitMs(DELAY_MS);\n }\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {\n type CommandBufferProps,\n type CopyBufferToBufferOptions,\n type CopyBufferToTextureOptions,\n type CopyTextureToBufferOptions,\n type CopyTextureToTextureOptions,\n type TextureReadOptions,\n // type ClearTextureOptions,\n CommandBuffer,\n Texture,\n Framebuffer,\n assertDefined\n} from '@luma.gl/core';\nimport {GL, type GLTextureTarget, type GLTextureCubeMapTarget} from '@luma.gl/webgl/constants';\n\nimport {getTextureFormatWebGL} from '../converters/webgl-texture-table';\nimport {WebGLDevice} from '../webgl-device';\nimport {WEBGLBuffer} from './webgl-buffer';\nimport {WEBGLTexture} from './webgl-texture';\nimport {WEBGLFramebuffer} from './webgl-framebuffer';\n\ntype CopyBufferToBufferCommand = {\n name: 'copy-buffer-to-buffer';\n options: CopyBufferToBufferOptions;\n};\n\ntype CopyBufferToTextureCommand = {\n name: 'copy-buffer-to-texture';\n options: CopyBufferToTextureOptions;\n};\n\ntype CopyTextureToBufferCommand = {\n name: 'copy-texture-to-buffer';\n options: CopyTextureToBufferOptions;\n};\n\ntype CopyTextureToTextureCommand = {\n name: 'copy-texture-to-texture';\n options: CopyTextureToTextureOptions;\n};\n\ntype ClearTextureCommand = {\n name: 'clear-texture';\n options: {}; // ClearTextureOptions;\n};\n\ntype ReadTextureCommand = {\n name: 'read-texture';\n options: {}; // TextureReadOptions;\n};\n\ntype Command =\n | CopyBufferToBufferCommand\n | CopyBufferToTextureCommand\n | CopyTextureToBufferCommand\n | CopyTextureToTextureCommand\n | ClearTextureCommand\n | ReadTextureCommand;\n\nexport class WEBGLCommandBuffer extends CommandBuffer {\n readonly device: WebGLDevice;\n readonly handle = null;\n commands: Command[] = [];\n\n constructor(device: WebGLDevice, props: CommandBufferProps = {}) {\n super(device, props);\n this.device = device;\n }\n\n _executeCommands(commands: Command[] = this.commands) {\n for (const command of commands) {\n switch (command.name) {\n case 'copy-buffer-to-buffer':\n _copyBufferToBuffer(this.device, command.options);\n break;\n case 'copy-buffer-to-texture':\n _copyBufferToTexture(this.device, command.options);\n break;\n case 'copy-texture-to-buffer':\n _copyTextureToBuffer(this.device, command.options);\n break;\n case 'copy-texture-to-texture':\n _copyTextureToTexture(this.device, command.options);\n break;\n // case 'clear-texture':\n // _clearTexture(this.device, command.options);\n // break;\n default:\n throw new Error(command.name);\n }\n }\n }\n}\n\nfunction _copyBufferToBuffer(device: WebGLDevice, options: CopyBufferToBufferOptions): void {\n const source = options.sourceBuffer as WEBGLBuffer;\n const destination = options.destinationBuffer as WEBGLBuffer;\n\n // {In WebGL2 we can p}erform the copy on the GPU\n // Use GL.COPY_READ_BUFFER+GL.COPY_WRITE_BUFFER avoid disturbing other targets and locking type\n device.gl.bindBuffer(GL.COPY_READ_BUFFER, source.handle);\n device.gl.bindBuffer(GL.COPY_WRITE_BUFFER, destination.handle);\n device.gl.copyBufferSubData(\n GL.COPY_READ_BUFFER,\n GL.COPY_WRITE_BUFFER,\n options.sourceOffset ?? 0,\n options.destinationOffset ?? 0,\n options.size\n );\n device.gl.bindBuffer(GL.COPY_READ_BUFFER, null);\n device.gl.bindBuffer(GL.COPY_WRITE_BUFFER, null);\n}\n\n/**\n * Copies data from a Buffer object into a Texture object\n * NOTE: doesn't wait for copy to be complete\n */\nfunction _copyBufferToTexture(_device: WebGLDevice, _options: CopyBufferToTextureOptions): void {\n throw new Error('copyBufferToTexture is not supported in WebGL');\n}\n\n/**\n * Copies data from a Texture object into a Buffer object.\n * NOTE: doesn't wait for copy to be complete\n */\nfunction _copyTextureToBuffer(device: WebGLDevice, options: CopyTextureToBufferOptions): void {\n const {\n sourceTexture,\n mipLevel = 0,\n aspect = 'all',\n width = options.sourceTexture.width,\n height = options.sourceTexture.height,\n depthOrArrayLayers,\n origin = [0, 0, 0],\n destinationBuffer,\n byteOffset = 0,\n bytesPerRow,\n rowsPerImage\n } = options;\n\n if (sourceTexture instanceof Texture) {\n sourceTexture.readBuffer(\n {\n x: origin[0] ?? 0,\n y: origin[1] ?? 0,\n z: origin[2] ?? 0,\n width,\n height,\n depthOrArrayLayers,\n mipLevel,\n aspect,\n byteOffset\n } as TextureReadOptions & {byteOffset?: number},\n destinationBuffer\n );\n return;\n }\n\n // TODO - Not possible to read just stencil or depth part in WebGL?\n if (aspect !== 'all') {\n throw new Error('aspect not supported in WebGL');\n }\n\n // TODO - mipLevels are set when attaching texture to framebuffer\n if (mipLevel !== 0 || depthOrArrayLayers !== undefined || bytesPerRow || rowsPerImage) {\n throw new Error('not implemented');\n }\n\n // Asynchronous read (PIXEL_PACK_BUFFER) is WebGL2 only feature\n const {framebuffer, destroyFramebuffer} = getFramebuffer(sourceTexture);\n let prevHandle: WebGLFramebuffer | null | undefined;\n try {\n const webglBuffer = destinationBuffer as WEBGLBuffer;\n const sourceWidth = width || framebuffer.width;\n const sourceHeight = height || framebuffer.height;\n const colorAttachment0 = assertDefined(framebuffer.colorAttachments[0]);\n\n const sourceParams = getTextureFormatWebGL(colorAttachment0.texture.props.format);\n const sourceFormat = sourceParams.format;\n const sourceType = sourceParams.type;\n\n // if (!target) {\n // // Create new buffer with enough size\n // const components = glFormatToComponents(sourceFormat);\n // const byteCount = glTypeToBytes(sourceType);\n // const byteLength = byteOffset + sourceWidth * sourceHeight * components * byteCount;\n // target = device.createBuffer({byteLength});\n // }\n\n device.gl.bindBuffer(GL.PIXEL_PACK_BUFFER, webglBuffer.handle);\n // @ts-expect-error native bindFramebuffer is overridden by our state tracker\n prevHandle = device.gl.bindFramebuffer(GL.FRAMEBUFFER, framebuffer.handle);\n\n device.gl.readPixels(\n origin[0],\n origin[1],\n sourceWidth,\n sourceHeight,\n sourceFormat,\n sourceType,\n byteOffset\n );\n } finally {\n device.gl.bindBuffer(GL.PIXEL_PACK_BUFFER, null);\n // prevHandle may be unassigned if the try block failed before binding\n if (prevHandle !== undefined) {\n device.gl.bindFramebuffer(GL.FRAMEBUFFER, prevHandle);\n }\n\n if (destroyFramebuffer) {\n framebuffer.destroy();\n }\n }\n}\n\n/**\n * Copies data from a Framebuffer or a Texture object into a Buffer object.\n * NOTE: doesn't wait for copy to be complete, it programs GPU to perform a DMA transfer.\nexport function readPixelsToBuffer(\n source: Framebuffer | Texture,\n options?: {\n sourceX?: number;\n sourceY?: number;\n sourceFormat?: number;\n target?: Buffer; // A new Buffer object is created when not provided.\n targetByteOffset?: number; // byte offset in buffer object\n // following parameters are auto deduced if not provided\n sourceWidth?: number;\n sourceHeight?: number;\n sourceType?: number;\n }\n): Buffer\n */\n\n/**\n * Copy a rectangle from a Framebuffer or Texture object into a texture (at an offset)\n */\n// eslint-disable-next-line complexity, max-statements\nfunction _copyTextureToTexture(device: WebGLDevice, options: CopyTextureToTextureOptions): void {\n const {\n /** Texture to copy to/from. */\n sourceTexture,\n /** Mip-map level of the texture to copy to (Default 0) */\n destinationMipLevel = 0,\n /** Defines which aspects of the texture to copy to/from. */\n // aspect = 'all',\n /** Defines the origin of the copy - the minimum corner of the texture sub-region to copy from. */\n origin = [0, 0],\n\n /** Defines the origin of the copy - the minimum corner of the texture sub-region to copy to. */\n destinationOrigin = [0, 0, 0],\n\n /** Texture to copy to/from. */\n destinationTexture\n /** Mip-map level of the texture to copy to/from. (Default 0) */\n // destinationMipLevel = options.mipLevel,\n /** Defines the origin of the copy - the minimum corner of the texture sub-region to copy to/from. */\n // destinationOrigin = [0, 0],\n /** Defines which aspects of the texture to copy to/from. */\n // destinationAspect = options.aspect,\n } = options;\n\n let {\n width = options.destinationTexture.width,\n height = options.destinationTexture.height\n // depthOrArrayLayers = 0\n } = options;\n\n const {framebuffer, destroyFramebuffer} = getFramebuffer(sourceTexture);\n const [sourceX = 0, sourceY = 0] = origin;\n const [destinationX, destinationY, destinationZ] = destinationOrigin;\n\n // @ts-expect-error native bindFramebuffer is overridden by our state tracker\n const prevHandle: WebGLFramebuffer | null = device.gl.bindFramebuffer(\n GL.FRAMEBUFFER,\n framebuffer.handle\n );\n // TODO - support gl.readBuffer (WebGL2 only)\n // const prevBuffer = gl.readBuffer(attachment);\n\n let texture: WEBGLTexture;\n let textureTarget: GL;\n if (destinationTexture instanceof WEBGLTexture) {\n texture = destinationTexture;\n width = Number.isFinite(width) ? width : texture.width;\n height = Number.isFinite(height) ? height : texture.height;\n texture._bind(0);\n textureTarget = texture.glTarget;\n } else {\n throw new Error('invalid destination');\n }\n\n switch (textureTarget) {\n case GL.TEXTURE_2D:\n case GL.TEXTURE_CUBE_MAP:\n device.gl.copyTexSubImage2D(\n textureTarget,\n destinationMipLevel,\n destinationX,\n destinationY,\n sourceX,\n sourceY,\n width,\n height\n );\n break;\n case GL.TEXTURE_2D_ARRAY:\n case GL.TEXTURE_3D:\n device.gl.copyTexSubImage3D(\n textureTarget,\n destinationMipLevel,\n destinationX,\n destinationY,\n destinationZ,\n sourceX,\n sourceY,\n width,\n height\n );\n break;\n default:\n }\n\n if (texture) {\n texture._unbind();\n }\n device.gl.bindFramebuffer(GL.FRAMEBUFFER, prevHandle);\n if (destroyFramebuffer) {\n framebuffer.destroy();\n }\n}\n\n/** Clear one mip level of a texture *\nfunction _clearTexture(device: WebGLDevice, options: ClearTextureOptions) {\n const BORDER = 0;\n const {dimension, width, height, depth = 0, mipLevel = 0} = options;\n const {glInternalFormat, glFormat, glType, compressed} = options;\n const glTarget = getWebGLCubeFaceTarget(options.glTarget, dimension, depth);\n\n switch (dimension) {\n case '2d-array':\n case '3d':\n if (compressed) {\n // biome-ignore format: preserve layout\n device.gl.compressedTexImage3D(glTarget, mipLevel, glInternalFormat, width, height, depth, BORDER, null);\n } else {\n // biome-ignore format: preserve layout\n device.gl.texImage3D( glTarget, mipLevel, glInternalFormat, width, height, depth, BORDER, glFormat, glType, null);\n }\n break;\n\n case '2d':\n case 'cube':\n if (compressed) {\n // biome-ignore format: preserve layout\n device.gl.compressedTexImage2D(glTarget, mipLevel, glInternalFormat, width, height, BORDER, null);\n } else {\n // biome-ignore format: preserve layout\n device.gl.texImage2D(glTarget, mipLevel, glInternalFormat, width, height, BORDER, glFormat, glType, null);\n }\n break;\n\n default:\n throw new Error(dimension);\n }\n}\n */\n\n// function _readTexture(device: WebGLDevice, options: CopyTextureToBufferOptions) {}\n\n// HELPERS\n\n/**\n * In WebGL, cube maps specify faces by overriding target instead of using the depth parameter.\n * @note We still bind the texture using GL.TEXTURE_CUBE_MAP, but we need to use the face-specific target when setting mip levels.\n * @returns glTarget unchanged, if dimension !== 'cube'.\n */\nexport function getWebGLCubeFaceTarget(\n glTarget: GLTextureTarget,\n dimension: '1d' | '2d' | '2d-array' | 'cube' | 'cube-array' | '3d',\n level: number\n): GLTextureTarget | GLTextureCubeMapTarget {\n return dimension === 'cube' ? GL.TEXTURE_CUBE_MAP_POSITIVE_X + level : glTarget;\n}\n\n/** Wrap a texture in a framebuffer so that we can use WebGL APIs that work on framebuffers */\nfunction getFramebuffer(source: Texture | Framebuffer): {\n framebuffer: WEBGLFramebuffer;\n destroyFramebuffer: boolean;\n} {\n if (source instanceof Texture) {\n const {width, height, id} = source;\n const framebuffer = source.device.createFramebuffer({\n id: `framebuffer-for-${id}`,\n width,\n height,\n colorAttachments: [source]\n }) as unknown as WEBGLFramebuffer;\n\n return {framebuffer, destroyFramebuffer: true};\n }\n return {framebuffer: source as unknown as WEBGLFramebuffer, destroyFramebuffer: false};\n}\n\n/**\n * Returns number of components in a specific readPixels WebGL format\n * @todo use shadertypes utils instead?\n */\nexport function glFormatToComponents(format: GL): 1 | 2 | 3 | 4 {\n switch (format) {\n case GL.ALPHA:\n case GL.R32F:\n case GL.RED:\n return 1;\n case GL.RG32F:\n case GL.RG:\n return 2;\n case GL.RGB:\n case GL.RGB32F:\n return 3;\n case GL.RGBA:\n case GL.RGBA32F:\n return 4;\n // TODO: Add support for additional WebGL2 formats\n default:\n throw new Error('GLFormat');\n }\n}\n\n/**\n * Return byte count for given readPixels WebGL type\n * @todo use shadertypes utils instead?\n */\nexport function glTypeToBytes(type: GL): 1 | 2 | 4 {\n switch (type) {\n case GL.UNSIGNED_BYTE:\n return 1;\n case GL.UNSIGNED_SHORT_5_6_5:\n case GL.UNSIGNED_SHORT_4_4_4_4:\n case GL.UNSIGNED_SHORT_5_5_5_1:\n return 2;\n case GL.FLOAT:\n return 4;\n // TODO: Add support for additional WebGL2 types\n default:\n throw new Error('GLType');\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {NumericArray, NumberArray4} from '@math.gl/types';\nimport {RenderPass, RenderPassProps, RenderPassParameters} from '@luma.gl/core';\nimport {WebGLDevice} from '../webgl-device';\nimport {GL, GLParameters} from '@luma.gl/webgl/constants';\nimport {withGLParameters} from '../../context/state-tracker/with-parameters';\nimport {setGLParameters} from '../../context/parameters/unified-parameter-api';\nimport {WEBGLQuerySet} from './webgl-query-set';\nimport {WEBGLFramebuffer} from './webgl-framebuffer';\n\nconst COLOR_CHANNELS: NumberArray4 = [0x1, 0x2, 0x4, 0x8]; // GPUColorWrite RED, GREEN, BLUE, ALPHA\n\nexport class WEBGLRenderPass extends RenderPass {\n readonly device: WebGLDevice;\n readonly handle = null;\n\n /** Parameters that should be applied before each draw call */\n glParameters: GLParameters = {};\n\n constructor(device: WebGLDevice, props: RenderPassProps) {\n super(device, props);\n this.device = device;\n const webglFramebuffer = this.props.framebuffer as WEBGLFramebuffer | null;\n const isDefaultFramebuffer = !webglFramebuffer || webglFramebuffer.handle === null;\n\n if (isDefaultFramebuffer) {\n // Treat an explicit wrapper around the default framebuffer the same as the\n // implicit default path so draw buffer and viewport state stay valid.\n device.getDefaultCanvasContext()._resizeDrawingBufferIfNeeded();\n }\n\n // If no viewport is provided, apply reasonably defaults\n let viewport: NumberArray4 | undefined;\n if (!props?.parameters?.viewport) {\n if (!isDefaultFramebuffer && webglFramebuffer) {\n // Set the viewport to the size of the framebuffer\n const {width, height} = webglFramebuffer;\n viewport = [0, 0, width, height];\n } else {\n // Instead of using our own book-keeping, we can just read the values from the WebGL context\n const [width, height] = device.getDefaultCanvasContext().getDrawingBufferSize();\n viewport = [0, 0, width, height];\n }\n }\n\n // TODO - do parameters (scissorRect) affect the clear operation?\n this.device.pushState();\n this.setParameters({viewport, ...this.props.parameters});\n\n // Specify mapping of draw buffer locations to color attachments\n if (!isDefaultFramebuffer && webglFramebuffer?.colorAttachments.length) {\n const drawBuffers = webglFramebuffer.colorAttachments.map((_, i) => GL.COLOR_ATTACHMENT0 + i);\n this.device.gl.drawBuffers(drawBuffers);\n } else if (isDefaultFramebuffer) {\n // Default framebuffer only supports GL.BACK/GL.NONE draw buffers\n this.device.gl.drawBuffers([GL.BACK]);\n }\n\n // Hack - for now WebGL draws in \"immediate mode\" (instead of queueing the operations)...\n this.clear();\n\n if (this.props.timestampQuerySet && this.props.beginTimestampIndex !== undefined) {\n const webglQuerySet = this.props.timestampQuerySet as WEBGLQuerySet;\n webglQuerySet.writeTimestamp(this.props.beginTimestampIndex);\n }\n }\n\n end(): void {\n if (this.destroyed) {\n return;\n }\n if (this.props.timestampQuerySet && this.props.endTimestampIndex !== undefined) {\n const webglQuerySet = this.props.timestampQuerySet as WEBGLQuerySet;\n webglQuerySet.writeTimestamp(this.props.endTimestampIndex);\n }\n this.device.popState();\n // should add commands to CommandEncoder.\n this.destroy();\n }\n\n pushDebugGroup(groupLabel: string): void {}\n popDebugGroup(): void {}\n insertDebugMarker(markerLabel: string): void {}\n\n // beginOcclusionQuery(queryIndex: number): void;\n // endOcclusionQuery(): void;\n\n // executeBundles(bundles: Iterable): void;\n\n /**\n * Maps RenderPass parameters to GL parameters\n */\n setParameters(parameters: RenderPassParameters = {}): void {\n const glParameters: GLParameters = {...this.glParameters};\n\n // Framebuffers are specified using parameters in WebGL\n glParameters.framebuffer = this.props.framebuffer || null;\n\n if (this.props.depthReadOnly) {\n glParameters.depthMask = !this.props.depthReadOnly;\n }\n\n glParameters.stencilMask = this.props.stencilReadOnly ? 0 : 1;\n\n glParameters[GL.RASTERIZER_DISCARD] = this.props.discard;\n\n // Map the four renderpass parameters to WebGL parameters\n if (parameters.viewport) {\n // WebGPU viewports are 6 coordinates (X, Y, Z)\n if (parameters.viewport.length >= 6) {\n glParameters.viewport = parameters.viewport.slice(0, 4) as NumberArray4;\n glParameters.depthRange = [\n parameters.viewport[4] as number,\n parameters.viewport[5] as number\n ];\n } else {\n // WebGL viewports are 4 coordinates (X, Y)\n glParameters.viewport = parameters.viewport as NumberArray4;\n }\n }\n if (parameters.scissorRect) {\n glParameters.scissorTest = true;\n glParameters.scissor = parameters.scissorRect;\n }\n if (parameters.blendConstant) {\n glParameters.blendColor = parameters.blendConstant;\n }\n if (parameters.stencilReference !== undefined) {\n glParameters[GL.STENCIL_REF] = parameters.stencilReference;\n glParameters[GL.STENCIL_BACK_REF] = parameters.stencilReference;\n }\n\n if ('colorMask' in parameters) {\n glParameters.colorMask = COLOR_CHANNELS.map(channel =>\n Boolean(channel & (parameters.colorMask as number))\n );\n }\n\n this.glParameters = glParameters;\n\n setGLParameters(this.device.gl, glParameters);\n }\n\n beginOcclusionQuery(queryIndex: number): void {\n const webglQuerySet = this.props.occlusionQuerySet as WEBGLQuerySet;\n webglQuerySet?.beginOcclusionQuery();\n }\n\n override endOcclusionQuery(): void {\n const webglQuerySet = this.props.occlusionQuerySet as WEBGLQuerySet;\n webglQuerySet?.endOcclusionQuery();\n }\n\n // PRIVATE\n\n /**\n * Optionally clears depth, color and stencil buffers based on parameters\n */\n protected clear(): void {\n const glParameters: GLParameters = {...this.glParameters};\n\n let clearMask = 0;\n\n if (this.props.clearColors) {\n this.props.clearColors.forEach((color, drawBufferIndex) => {\n if (color) {\n this.clearColorBuffer(drawBufferIndex, color);\n }\n });\n }\n\n if (this.props.clearColor !== false && this.props.clearColors === undefined) {\n clearMask |= GL.COLOR_BUFFER_BIT;\n glParameters.clearColor = this.props.clearColor;\n }\n if (this.props.clearDepth !== false) {\n clearMask |= GL.DEPTH_BUFFER_BIT;\n glParameters.clearDepth = this.props.clearDepth;\n }\n if (this.props.clearStencil !== false) {\n clearMask |= GL.STENCIL_BUFFER_BIT;\n glParameters.clearStencil = this.props.clearStencil;\n }\n\n if (clearMask !== 0) {\n // Temporarily set any clear \"colors\" and call clear\n withGLParameters(this.device.gl, glParameters, () => {\n this.device.gl.clear(clearMask);\n });\n }\n }\n\n /**\n * WebGL2 - clear a specific color buffer\n */\n protected clearColorBuffer(drawBuffer: number = 0, value: NumericArray = [0, 0, 0, 0]) {\n withGLParameters(this.device.gl, {framebuffer: this.props.framebuffer}, () => {\n // Method selection per OpenGL ES 3 docs\n switch (value.constructor) {\n case Int8Array:\n case Int16Array:\n case Int32Array:\n this.device.gl.clearBufferiv(GL.COLOR, drawBuffer, value);\n break;\n case Uint8Array:\n case Uint8ClampedArray:\n case Uint16Array:\n case Uint32Array:\n this.device.gl.clearBufferuiv(GL.COLOR, drawBuffer, value);\n break;\n case Float32Array:\n this.device.gl.clearBufferfv(GL.COLOR, drawBuffer, value);\n break;\n default:\n throw new Error('clearColorBuffer: color must be typed array');\n }\n });\n }\n\n /*\n clearDepthStencil() {\n case GL.DEPTH:\n this.device.gl.clearBufferfv(GL.DEPTH, 0, [value]);\n break;\n\n case GL_STENCIL:\n this.device.gl.clearBufferiv(GL.STENCIL, 0, [value]);\n break;\n\n case GL.DEPTH_STENCIL:\n const [depth, stencil] = value;\n this.device.gl.clearBufferfi(GL.DEPTH_STENCIL, 0, depth, stencil);\n break;\n\n default:\n assert(false, ERR_ARGUMENTS);\n }\n });\n */\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {CommandBufferProps, CommandEncoder, CommandEncoderProps} from '@luma.gl/core';\nimport type {\n RenderPassProps,\n ComputePass,\n ComputePassProps,\n QuerySet,\n Buffer,\n CopyBufferToBufferOptions,\n CopyBufferToTextureOptions,\n CopyTextureToBufferOptions,\n CopyTextureToTextureOptions\n // ClearTextureOptions,\n // TextureReadOptions,\n} from '@luma.gl/core';\n\nimport {WEBGLCommandBuffer} from './webgl-command-buffer';\nimport {WEBGLRenderPass} from './webgl-render-pass';\nimport {WebGLDevice} from '../webgl-device';\nimport {WEBGLQuerySet} from './webgl-query-set';\n\nexport class WEBGLCommandEncoder extends CommandEncoder {\n readonly device: WebGLDevice;\n readonly handle = null;\n\n readonly commandBuffer: WEBGLCommandBuffer;\n\n constructor(device: WebGLDevice, props: CommandEncoderProps) {\n super(device, props);\n this.device = device;\n this.commandBuffer = new WEBGLCommandBuffer(device, {\n id: `${this.props.id}-command-buffer`\n });\n }\n\n override destroy(): void {\n this.destroyResource();\n }\n\n override finish(props?: CommandBufferProps): WEBGLCommandBuffer {\n if (props?.id && this.commandBuffer.id !== props.id) {\n this.commandBuffer.id = props.id;\n this.commandBuffer.props.id = props.id;\n }\n this.destroy();\n return this.commandBuffer;\n }\n\n beginRenderPass(props: RenderPassProps = {}): WEBGLRenderPass {\n return new WEBGLRenderPass(this.device, this._applyTimeProfilingToPassProps(props));\n }\n\n beginComputePass(props: ComputePassProps = {}): ComputePass {\n throw new Error('ComputePass not supported in WebGL');\n }\n\n copyBufferToBuffer(options: CopyBufferToBufferOptions): void {\n this.commandBuffer.commands.push({name: 'copy-buffer-to-buffer', options});\n }\n\n copyBufferToTexture(options: CopyBufferToTextureOptions) {\n this.commandBuffer.commands.push({name: 'copy-buffer-to-texture', options});\n }\n\n copyTextureToBuffer(options: CopyTextureToBufferOptions): void {\n this.commandBuffer.commands.push({name: 'copy-texture-to-buffer', options});\n }\n\n copyTextureToTexture(options: CopyTextureToTextureOptions): void {\n this.commandBuffer.commands.push({name: 'copy-texture-to-texture', options});\n }\n\n // clearTexture(options: ClearTextureOptions): void {\n // this.commandBuffer.commands.push({name: 'copy-texture-to-texture', options});\n // }\n\n override pushDebugGroup(groupLabel: string): void {}\n override popDebugGroup() {}\n\n override insertDebugMarker(markerLabel: string): void {}\n\n override resolveQuerySet(\n _querySet: QuerySet,\n _destination: Buffer,\n _options?: {\n firstQuery?: number;\n queryCount?: number;\n destinationOffset?: number;\n }\n ): void {\n throw new Error('resolveQuerySet is not supported in WebGL');\n }\n\n writeTimestamp(querySet: QuerySet, queryIndex: number): void {\n const webglQuerySet = querySet as WEBGLQuerySet;\n webglQuerySet.writeTimestamp(queryIndex);\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {NumericArray} from '@math.gl/types';\n\n// Uses copyWithin to significantly speed up typed array value filling\nexport function fillArray(options: {\n target: NumericArray;\n source: NumericArray;\n start?: number;\n count?: number;\n}): NumericArray {\n const {target, source, start = 0, count = 1} = options;\n const length = source.length;\n const total = count * length;\n let copied = 0;\n for (let i = start; copied < length; copied++) {\n target[i++] = source[copied] ?? 0;\n }\n\n while (copied < total) {\n // If we have copied less than half, copy everything we got\n // else copy remaining in one operation\n if (copied < total - copied) {\n target.copyWithin(start + copied, start, start + copied);\n copied *= 2;\n } else {\n target.copyWithin(start + copied, start, start + total - copied);\n copied = total;\n }\n }\n\n return options.target;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {TypedArray, NumericArray} from '@math.gl/types';\nimport type {Device, Buffer, VertexArrayProps} from '@luma.gl/core';\nimport {VertexArray, getScratchArray} from '@luma.gl/core';\nimport {GL} from '@luma.gl/webgl/constants';\nimport {getBrowser} from '@probe.gl/env';\n\nimport {WebGLDevice} from '../webgl-device';\nimport {WEBGLBuffer} from '../resources/webgl-buffer';\n\nimport {getGLFromVertexType} from '../converters/webgl-vertex-formats';\nimport {fillArray} from '../../utils/fill-array';\n\n/** VertexArrayObject wrapper */\nexport class WEBGLVertexArray extends VertexArray {\n override get [Symbol.toStringTag](): string {\n return 'VertexArray';\n }\n\n readonly device: WebGLDevice;\n readonly handle: WebGLVertexArrayObject;\n\n /** Attribute 0 buffer constant */\n private buffer: WEBGLBuffer | null = null;\n private bufferValue: TypedArray | null = null;\n\n /** * Attribute 0 can not be disable on most desktop OpenGL based browsers */\n static isConstantAttributeZeroSupported(device: Device): boolean {\n return getBrowser() === 'Chrome';\n }\n\n // Create a VertexArray\n constructor(device: WebGLDevice, props: VertexArrayProps) {\n super(device, props);\n this.device = device;\n this.handle = this.device.gl.createVertexArray()!;\n }\n\n override destroy(): void {\n super.destroy();\n if (this.buffer) {\n this.buffer?.destroy();\n }\n if (this.handle) {\n this.device.gl.deleteVertexArray(this.handle);\n // @ts-expect-error read-only/undefined\n this.handle = undefined!;\n }\n\n // Auto-delete elements?\n // return [this.elements];\n }\n\n /**\n // Set (bind/unbind) an elements buffer, for indexed rendering.\n // Must be a Buffer bound to GL.ELEMENT_ARRAY_BUFFER or null. Constants not supported\n *\n * @param elementBuffer\n */\n setIndexBuffer(indexBuffer: Buffer | null): void {\n const buffer = indexBuffer as WEBGLBuffer;\n // Explicitly allow `null` to support clearing the index buffer\n if (buffer && buffer.glTarget !== GL.ELEMENT_ARRAY_BUFFER) {\n throw new Error('Use .setBuffer()');\n }\n // In WebGL The GL.ELEMENT_ARRAY_BUFFER_BINDING is stored on the VertexArrayObject\n this.device.gl.bindVertexArray(this.handle);\n this.device.gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, buffer ? buffer.handle : null);\n\n this.indexBuffer = buffer;\n\n // Unbind to prevent unintended changes to the VAO.\n this.device.gl.bindVertexArray(null);\n }\n\n /** Set a location in vertex attributes array to a buffer, enables the location, sets divisor */\n setBuffer(location: number, attributeBuffer: Buffer): void {\n const buffer = attributeBuffer as WEBGLBuffer;\n // Sanity check target\n if (buffer.glTarget === GL.ELEMENT_ARRAY_BUFFER) {\n throw new Error('Use .setIndexBuffer()');\n }\n\n const {size, type, stride, offset, normalized, integer, divisor} = this._getAccessor(location);\n\n this.device.gl.bindVertexArray(this.handle);\n // A non-zero buffer object must be bound to the GL_ARRAY_BUFFER target\n this.device.gl.bindBuffer(GL.ARRAY_BUFFER, buffer.handle);\n\n // WebGL2 supports *integer* data formats, i.e. GPU will see integer values\n if (integer) {\n this.device.gl.vertexAttribIPointer(location, size, type, stride, offset);\n } else {\n // Attaches ARRAY_BUFFER with specified buffer format to location\n this.device.gl.vertexAttribPointer(location, size, type, normalized, stride, offset);\n }\n // Clear binding - keeping it may cause [.WebGL-0x12804417100]\n // GL_INVALID_OPERATION: A transform feedback buffer that would be written to is also bound to a non-transform-feedback target\n this.device.gl.bindBuffer(GL.ARRAY_BUFFER, null);\n\n // Mark as non-constant\n this.device.gl.enableVertexAttribArray(location);\n // Set the step mode 0=vertex, 1=instance\n this.device.gl.vertexAttribDivisor(location, divisor || 0);\n\n this.attributes[location] = buffer;\n\n // Unbind to prevent unintended changes to the VAO.\n this.device.gl.bindVertexArray(null);\n }\n\n /** Set a location in vertex attributes array to a constant value, disables the location */\n override setConstantWebGL(location: number, value: TypedArray): void {\n this._enable(location, false);\n this.attributes[location] = value;\n }\n\n override bindBeforeRender(): void {\n this.device.gl.bindVertexArray(this.handle);\n this._applyConstantAttributes();\n }\n\n override unbindAfterRender(): void {\n // Unbind to prevent unintended changes to the VAO.\n this.device.gl.bindVertexArray(null);\n }\n\n // Internal methods\n\n /**\n * Constant attributes need to be reset before every draw call\n * Any attribute that is disabled in the current vertex array object\n * is read from the context's global constant value for that attribute location.\n * @note Constant attributes are only supported in WebGL, not in WebGPU\n */\n protected _applyConstantAttributes(): void {\n for (let location = 0; location < this.maxVertexAttributes; ++location) {\n const constant = this.attributes[location];\n // A typed array means this is a constant\n if (ArrayBuffer.isView(constant)) {\n this.device.setConstantAttributeWebGL(location, constant);\n }\n }\n }\n\n /**\n * Set a location in vertex attributes array to a buffer, enables the location, sets divisor\n * @note requires vertex array to be bound\n */\n // protected _setAttributeLayout(location: number): void {\n // const {size, type, stride, offset, normalized, integer, divisor} = this._getAccessor(location);\n\n // // WebGL2 supports *integer* data formats, i.e. GPU will see integer values\n // if (integer) {\n // this.device.gl.vertexAttribIPointer(location, size, type, stride, offset);\n // } else {\n // // Attaches ARRAY_BUFFER with specified buffer format to location\n // this.device.gl.vertexAttribPointer(location, size, type, normalized, stride, offset);\n // }\n // this.device.gl.vertexAttribDivisor(location, divisor || 0);\n // }\n\n /** Get an accessor from the */\n protected _getAccessor(location: number) {\n const attributeInfo = this.attributeInfos[location];\n if (!attributeInfo) {\n throw new Error(`Unknown attribute location ${location}`);\n }\n const glType = getGLFromVertexType(attributeInfo.bufferDataType);\n return {\n size: attributeInfo.bufferComponents,\n type: glType,\n stride: attributeInfo.byteStride,\n offset: attributeInfo.byteOffset,\n normalized: attributeInfo.normalized,\n // it is the shader attribute declaration, not the vertex memory format,\n // that determines if the data in the buffer will be treated as integers.\n //\n // Also note that WebGL supports assigning non-normalized integer data to floating point attributes,\n // but as far as we can tell, WebGPU does not.\n integer: attributeInfo.integer,\n divisor: attributeInfo.stepMode === 'instance' ? 1 : 0\n };\n }\n\n /**\n * Enabling an attribute location makes it reference the currently bound buffer\n * Disabling an attribute location makes it reference the global constant value\n * TODO - handle single values for size 1 attributes?\n * TODO - convert classic arrays based on known type?\n */\n protected _enable(location: number, enable = true): void {\n // Attribute 0 cannot be disabled in most desktop OpenGL based browsers...\n const canDisableAttributeZero = WEBGLVertexArray.isConstantAttributeZeroSupported(this.device);\n const canDisableAttribute = canDisableAttributeZero || location !== 0;\n\n if (enable || canDisableAttribute) {\n location = Number(location);\n this.device.gl.bindVertexArray(this.handle);\n if (enable) {\n this.device.gl.enableVertexAttribArray(location);\n } else {\n this.device.gl.disableVertexAttribArray(location);\n }\n this.device.gl.bindVertexArray(null);\n }\n }\n\n /**\n * Provide a means to create a buffer that is equivalent to a constant.\n * NOTE: Desktop OpenGL cannot disable attribute 0.\n * https://stackoverflow.com/questions/20305231/webgl-warning-attribute-0-is-disabled-\n * this-has-significant-performance-penalty\n */\n getConstantBuffer(elementCount: number, value: TypedArray): Buffer {\n // Create buffer only when needed, and reuse it (avoids inflating buffer creation statistics)\n\n const constantValue = normalizeConstantArrayValue(value);\n\n const byteLength = constantValue.byteLength * elementCount;\n const length = constantValue.length * elementCount;\n\n if (this.buffer && byteLength !== this.buffer.byteLength) {\n throw new Error(\n `Buffer size is immutable, byte length ${byteLength} !== ${this.buffer.byteLength}.`\n );\n }\n let updateNeeded = !this.buffer;\n\n this.buffer = this.buffer || this.device.createBuffer({byteLength});\n\n // Reallocate and update contents if needed\n // @ts-ignore TODO fix types\n updateNeeded ||= !compareConstantArrayValues(constantValue, this.bufferValue);\n\n if (updateNeeded) {\n // Create a typed array that is big enough, and fill it with the required data\n const typedArray = getScratchArray(value.constructor, length);\n fillArray({target: typedArray, source: constantValue, start: 0, count: length});\n this.buffer.write(typedArray);\n this.bufferValue = value;\n }\n\n return this.buffer;\n }\n}\n\n// HELPER FUNCTIONS\n\n/**\n * TODO - convert Arrays based on known type? (read type from accessor, don't assume Float32Array)\n * TODO - handle single values for size 1 attributes?\n */\nfunction normalizeConstantArrayValue(arrayValue: NumericArray) {\n if (Array.isArray(arrayValue)) {\n return new Float32Array(arrayValue);\n }\n return arrayValue;\n}\n\n/**\n *\n */\nfunction compareConstantArrayValues(v1: NumericArray, v2: NumericArray): boolean {\n if (!v1 || !v2 || v1.length !== v2.length || v1.constructor !== v2.constructor) {\n return false;\n }\n for (let i = 0; i < v1.length; ++i) {\n if (v1[i] !== v2[i]) {\n return false;\n }\n }\n return true;\n}\n","import type {PrimitiveTopology, ShaderLayout, TransformFeedbackProps} from '@luma.gl/core';\nimport {log, TransformFeedback, Buffer, BufferRange} from '@luma.gl/core';\nimport {GL} from '@luma.gl/webgl/constants';\nimport {WebGLDevice} from '../webgl-device';\nimport {WEBGLBuffer} from '../../index';\nimport {getGLPrimitive} from '../helpers/webgl-topology-utils';\n\nexport class WEBGLTransformFeedback extends TransformFeedback {\n readonly device: WebGLDevice;\n readonly gl: WebGL2RenderingContext;\n readonly handle: WebGLTransformFeedback;\n\n /**\n * NOTE: The Model already has this information while drawing, but\n * TransformFeedback currently needs it internally, to look up\n * varying information outside of a draw() call.\n */\n readonly layout: ShaderLayout;\n buffers: Record = {};\n unusedBuffers: Record = {};\n /**\n * Allows us to avoid a Chrome bug where a buffer that is already bound to a\n * different target cannot be bound to 'TRANSFORM_FEEDBACK_BUFFER' target.\n * This a major workaround, see: https://github.com/KhronosGroup/WebGL/issues/2346\n */\n bindOnUse = true;\n private _bound: boolean = false;\n\n constructor(device: WebGLDevice, props: TransformFeedbackProps) {\n super(device, props);\n\n this.device = device;\n this.gl = device.gl;\n this.handle = this.props.handle || this.gl.createTransformFeedback();\n this.layout = this.props.layout;\n\n if (props.buffers) {\n this.setBuffers(props.buffers);\n }\n\n Object.seal(this);\n }\n\n override destroy(): void {\n this.gl.deleteTransformFeedback(this.handle);\n super.destroy();\n }\n\n begin(topology: PrimitiveTopology = 'point-list'): void {\n this.gl.bindTransformFeedback(GL.TRANSFORM_FEEDBACK, this.handle);\n if (this.bindOnUse) {\n this._bindBuffers();\n }\n this.gl.beginTransformFeedback(getGLPrimitive(topology));\n }\n\n end(): void {\n this.gl.endTransformFeedback();\n if (this.bindOnUse) {\n this._unbindBuffers();\n }\n this.gl.bindTransformFeedback(GL.TRANSFORM_FEEDBACK, null);\n }\n\n // SUBCLASS\n\n setBuffers(buffers: Record): void {\n this.buffers = {};\n this.unusedBuffers = {};\n\n this.bind(() => {\n for (const [bufferName, buffer] of Object.entries(buffers)) {\n this.setBuffer(bufferName, buffer);\n }\n });\n }\n\n setBuffer(locationOrName: string | number, bufferOrRange: Buffer | BufferRange): void {\n const location = this._getVaryingIndex(locationOrName);\n const {buffer, byteLength, byteOffset} = this._getBufferRange(bufferOrRange);\n\n if (location < 0) {\n this.unusedBuffers[locationOrName] = buffer;\n log.warn(`${this.id} unusedBuffers varying buffer ${locationOrName}`)();\n return;\n }\n\n this.buffers[location] = {buffer, byteLength, byteOffset};\n\n // Need to avoid chrome bug where buffer that is already bound to a different target\n // cannot be bound to 'TRANSFORM_FEEDBACK_BUFFER' target.\n if (!this.bindOnUse) {\n this._bindBuffer(location, buffer, byteOffset, byteLength);\n }\n }\n\n getBuffer(locationOrName: string | number): Buffer | BufferRange | null {\n if (isIndex(locationOrName)) {\n return this.buffers[locationOrName] || null;\n }\n const location = this._getVaryingIndex(locationOrName);\n return this.buffers[location] ?? null;\n }\n\n bind(funcOrHandle: (() => void) | WebGLTransformFeedback | null = this.handle) {\n if (typeof funcOrHandle !== 'function') {\n this.gl.bindTransformFeedback(GL.TRANSFORM_FEEDBACK, funcOrHandle);\n return this;\n }\n\n let value: unknown;\n\n if (!this._bound) {\n this.gl.bindTransformFeedback(GL.TRANSFORM_FEEDBACK, this.handle);\n this._bound = true;\n value = funcOrHandle();\n this._bound = false;\n this.gl.bindTransformFeedback(GL.TRANSFORM_FEEDBACK, null);\n } else {\n value = funcOrHandle();\n }\n\n return value;\n }\n\n unbind() {\n this.bind(null);\n }\n\n // PRIVATE METHODS\n\n /** Extract offsets for bindBufferRange */\n protected _getBufferRange(\n bufferOrRange: Buffer | {buffer: Buffer; byteOffset?: number; byteLength?: number}\n ): Required {\n if (bufferOrRange instanceof WEBGLBuffer) {\n return {buffer: bufferOrRange, byteOffset: 0, byteLength: bufferOrRange.byteLength};\n }\n\n // To use bindBufferRange either offset or size must be specified.\n // @ts-expect-error Must be a BufferRange.\n const {buffer, byteOffset = 0, byteLength = bufferOrRange.buffer.byteLength} = bufferOrRange;\n return {buffer, byteOffset, byteLength};\n }\n\n protected _getVaryingIndex(locationOrName: string | number): number {\n if (isIndex(locationOrName)) {\n return Number(locationOrName);\n }\n\n for (const varying of this.layout.varyings || []) {\n if (locationOrName === varying.name) {\n return varying.location;\n }\n }\n\n return -1;\n }\n\n /**\n * Need to avoid chrome bug where buffer that is already bound to a different target\n * cannot be bound to 'TRANSFORM_FEEDBACK_BUFFER' target.\n */\n protected _bindBuffers(): void {\n for (const [bufferIndex, bufferEntry] of Object.entries(this.buffers)) {\n const {buffer, byteLength, byteOffset} = this._getBufferRange(bufferEntry);\n this._bindBuffer(Number(bufferIndex), buffer, byteOffset, byteLength);\n }\n }\n\n protected _unbindBuffers(): void {\n for (const bufferIndex in this.buffers) {\n this.gl.bindBufferBase(GL.TRANSFORM_FEEDBACK_BUFFER, Number(bufferIndex), null);\n }\n }\n\n protected _bindBuffer(index: number, buffer: Buffer, byteOffset = 0, byteLength?: number): void {\n const handle = buffer && (buffer as WEBGLBuffer).handle;\n if (!handle || byteLength === undefined) {\n this.gl.bindBufferBase(GL.TRANSFORM_FEEDBACK_BUFFER, index, handle);\n } else {\n this.gl.bindBufferRange(GL.TRANSFORM_FEEDBACK_BUFFER, index, handle, byteOffset, byteLength);\n }\n }\n}\n\n/**\n * Returns true if the given value is an integer, or a string that\n * trivially converts to an integer (only numeric characters).\n */\nfunction isIndex(value: string | number): boolean {\n if (typeof value === 'number') {\n return Number.isInteger(value);\n }\n return /^\\d+$/.test(value);\n}\n","// WebGL2 QuerySet (also handles disjoint timer extensions)\nimport {QuerySet, QuerySetProps} from '@luma.gl/core';\nimport {GL} from '@luma.gl/webgl/constants';\nimport {WebGLDevice} from '../webgl-device';\n\ntype WebGLPendingQuery = {\n handle: WebGLQuery;\n promise: Promise | null;\n result: bigint | null;\n disjoint: boolean;\n cancelled: boolean;\n pollRequestId: number | null;\n resolve: ((value: bigint) => void) | null;\n reject: ((error: Error) => void) | null;\n};\n\ntype WebGLTimestampPair = {\n activeQuery: WebGLPendingQuery | null;\n completedQueries: WebGLPendingQuery[];\n};\n\n/**\n * Asynchronous queries for different kinds of information\n */\nexport class WEBGLQuerySet extends QuerySet {\n readonly device: WebGLDevice;\n readonly handle: WebGLQuery | null;\n\n protected _timestampPairs: WebGLTimestampPair[] = [];\n protected _pendingReads: Set = new Set();\n protected _occlusionQuery: WebGLPendingQuery | null = null;\n protected _occlusionActive = false;\n\n override get [Symbol.toStringTag](): string {\n return 'QuerySet';\n }\n\n constructor(device: WebGLDevice, props: QuerySetProps) {\n super(device, props);\n this.device = device;\n\n if (props.type === 'timestamp') {\n if (props.count < 2) {\n throw new Error('Timestamp QuerySet requires at least two query slots');\n }\n this._timestampPairs = new Array(Math.ceil(props.count / 2))\n .fill(null)\n .map(() => ({activeQuery: null, completedQueries: []}));\n this.handle = null;\n } else {\n if (props.count > 1) {\n throw new Error('WebGL occlusion QuerySet can only have one value');\n }\n const handle = this.device.gl.createQuery();\n if (!handle) {\n throw new Error('WebGL query not supported');\n }\n this.handle = handle;\n }\n\n Object.seal(this);\n }\n\n override destroy(): void {\n if (this.destroyed) {\n return;\n }\n\n if (this.handle) {\n this.device.gl.deleteQuery(this.handle);\n }\n\n for (const pair of this._timestampPairs) {\n if (pair.activeQuery) {\n this._cancelPendingQuery(pair.activeQuery);\n this.device.gl.deleteQuery(pair.activeQuery.handle);\n }\n for (const query of pair.completedQueries) {\n this._cancelPendingQuery(query);\n this.device.gl.deleteQuery(query.handle);\n }\n }\n\n if (this._occlusionQuery) {\n this._cancelPendingQuery(this._occlusionQuery);\n this.device.gl.deleteQuery(this._occlusionQuery.handle);\n }\n\n for (const query of Array.from(this._pendingReads)) {\n this._cancelPendingQuery(query);\n }\n\n this.destroyResource();\n }\n\n isResultAvailable(queryIndex?: number): boolean {\n if (this.props.type === 'timestamp') {\n if (queryIndex === undefined) {\n return this._timestampPairs.some((_, pairIndex) =>\n this._isTimestampPairAvailable(pairIndex)\n );\n }\n return this._isTimestampPairAvailable(this._getTimestampPairIndex(queryIndex));\n }\n\n if (!this._occlusionQuery) {\n return false;\n }\n\n return this._pollQueryAvailability(this._occlusionQuery);\n }\n\n async readResults(options?: {firstQuery?: number; queryCount?: number}): Promise {\n const firstQuery = options?.firstQuery || 0;\n const queryCount = options?.queryCount || this.props.count - firstQuery;\n this._validateRange(firstQuery, queryCount);\n\n if (this.props.type === 'timestamp') {\n const results = new Array(queryCount).fill(0n);\n const startPairIndex = Math.floor(firstQuery / 2);\n const endPairIndex = Math.floor((firstQuery + queryCount - 1) / 2);\n\n for (let pairIndex = startPairIndex; pairIndex <= endPairIndex; pairIndex++) {\n const duration = await this._consumeTimestampPairResult(pairIndex);\n const beginSlot = pairIndex * 2;\n const endSlot = beginSlot + 1;\n\n if (beginSlot >= firstQuery && beginSlot < firstQuery + queryCount) {\n results[beginSlot - firstQuery] = 0n;\n }\n if (endSlot >= firstQuery && endSlot < firstQuery + queryCount) {\n results[endSlot - firstQuery] = duration;\n }\n }\n\n return results;\n }\n\n if (!this._occlusionQuery) {\n throw new Error('Occlusion query has not been started');\n }\n\n return [await this._consumeQueryResult(this._occlusionQuery)];\n }\n\n async readTimestampDuration(beginIndex: number, endIndex: number): Promise {\n if (this.props.type !== 'timestamp') {\n throw new Error('Timestamp durations require a timestamp QuerySet');\n }\n if (beginIndex < 0 || endIndex >= this.props.count || endIndex <= beginIndex) {\n throw new Error('Timestamp duration range is out of bounds');\n }\n if (beginIndex % 2 !== 0 || endIndex !== beginIndex + 1) {\n throw new Error('WebGL timestamp durations require adjacent even/odd query indices');\n }\n\n const result = await this._consumeTimestampPairResult(this._getTimestampPairIndex(beginIndex));\n return Number(result) / 1e6;\n }\n\n beginOcclusionQuery(): void {\n if (this.props.type !== 'occlusion') {\n throw new Error('Occlusion queries require an occlusion QuerySet');\n }\n if (!this.handle) {\n throw new Error('WebGL occlusion query is not available');\n }\n if (this._occlusionActive) {\n throw new Error('Occlusion query is already active');\n }\n\n this.device.gl.beginQuery(GL.ANY_SAMPLES_PASSED, this.handle);\n this._occlusionQuery = {\n handle: this.handle,\n promise: null,\n result: null,\n disjoint: false,\n cancelled: false,\n pollRequestId: null,\n resolve: null,\n reject: null\n };\n this._occlusionActive = true;\n }\n\n endOcclusionQuery(): void {\n if (!this._occlusionActive) {\n throw new Error('Occlusion query is not active');\n }\n\n this.device.gl.endQuery(GL.ANY_SAMPLES_PASSED);\n this._occlusionActive = false;\n }\n\n writeTimestamp(queryIndex: number): void {\n if (this.props.type !== 'timestamp') {\n throw new Error('Timestamp writes require a timestamp QuerySet');\n }\n\n const pairIndex = this._getTimestampPairIndex(queryIndex);\n const pair = this._timestampPairs[pairIndex];\n\n if (queryIndex % 2 === 0) {\n if (pair.activeQuery) {\n throw new Error('Timestamp query pair is already active');\n }\n\n const handle = this.device.gl.createQuery();\n if (!handle) {\n throw new Error('WebGL query not supported');\n }\n\n const query: WebGLPendingQuery = {\n handle,\n promise: null,\n result: null,\n disjoint: false,\n cancelled: false,\n pollRequestId: null,\n resolve: null,\n reject: null\n };\n\n this.device.gl.beginQuery(GL.TIME_ELAPSED_EXT, handle);\n pair.activeQuery = query;\n return;\n }\n\n if (!pair.activeQuery) {\n throw new Error('Timestamp query pair was ended before it was started');\n }\n\n this.device.gl.endQuery(GL.TIME_ELAPSED_EXT);\n pair.completedQueries.push(pair.activeQuery);\n pair.activeQuery = null;\n }\n\n protected _validateRange(firstQuery: number, queryCount: number): void {\n if (firstQuery < 0 || queryCount < 0 || firstQuery + queryCount > this.props.count) {\n throw new Error('Query read range is out of bounds');\n }\n }\n\n protected _getTimestampPairIndex(queryIndex: number): number {\n if (queryIndex < 0 || queryIndex >= this.props.count) {\n throw new Error('Query index is out of bounds');\n }\n\n return Math.floor(queryIndex / 2);\n }\n\n protected _isTimestampPairAvailable(pairIndex: number): boolean {\n const pair = this._timestampPairs[pairIndex];\n if (!pair || pair.completedQueries.length === 0) {\n return false;\n }\n\n return this._pollQueryAvailability(pair.completedQueries[0]);\n }\n\n protected _pollQueryAvailability(query: WebGLPendingQuery): boolean {\n if (query.cancelled || this.destroyed) {\n query.result = 0n;\n return true;\n }\n\n if (query.result !== null || query.disjoint) {\n return true;\n }\n\n const resultAvailable = this.device.gl.getQueryParameter(\n query.handle,\n GL.QUERY_RESULT_AVAILABLE\n );\n if (!resultAvailable) {\n return false;\n }\n\n const isDisjoint = Boolean(this.device.gl.getParameter(GL.GPU_DISJOINT_EXT));\n query.disjoint = isDisjoint;\n query.result = isDisjoint\n ? 0n\n : BigInt(this.device.gl.getQueryParameter(query.handle, GL.QUERY_RESULT));\n return true;\n }\n\n protected async _consumeTimestampPairResult(pairIndex: number): Promise {\n const pair = this._timestampPairs[pairIndex];\n if (!pair || pair.completedQueries.length === 0) {\n throw new Error('Timestamp query pair has no completed result');\n }\n\n const query = pair.completedQueries.shift()!;\n\n try {\n return await this._consumeQueryResult(query);\n } finally {\n this.device.gl.deleteQuery(query.handle);\n }\n }\n\n protected _consumeQueryResult(query: WebGLPendingQuery): Promise {\n if (query.promise) {\n return query.promise;\n }\n\n this._pendingReads.add(query);\n query.promise = new Promise((resolve, reject) => {\n query.resolve = resolve;\n query.reject = reject;\n\n const poll = () => {\n query.pollRequestId = null;\n\n if (query.cancelled || this.destroyed) {\n this._pendingReads.delete(query);\n query.promise = null;\n query.resolve = null;\n query.reject = null;\n resolve(0n);\n return;\n }\n\n if (!this._pollQueryAvailability(query)) {\n query.pollRequestId = this._requestAnimationFrame(poll);\n return;\n }\n\n this._pendingReads.delete(query);\n query.promise = null;\n query.resolve = null;\n query.reject = null;\n if (query.disjoint) {\n reject(new Error('GPU timestamp query was invalidated by a disjoint event'));\n } else {\n resolve(query.result || 0n);\n }\n };\n\n poll();\n });\n\n return query.promise;\n }\n\n protected _cancelPendingQuery(query: WebGLPendingQuery): void {\n this._pendingReads.delete(query);\n query.cancelled = true;\n if (query.pollRequestId !== null) {\n this._cancelAnimationFrame(query.pollRequestId);\n query.pollRequestId = null;\n }\n if (query.resolve) {\n const resolve = query.resolve;\n query.promise = null;\n query.resolve = null;\n query.reject = null;\n resolve(0n);\n }\n }\n\n protected _requestAnimationFrame(callback: FrameRequestCallback): number {\n return requestAnimationFrame(callback);\n }\n\n protected _cancelAnimationFrame(requestId: number): void {\n cancelAnimationFrame(requestId);\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Fence, type FenceProps} from '@luma.gl/core';\nimport {WebGLDevice} from '../webgl-device';\n\n/** WebGL fence implemented with gl.fenceSync */\nexport class WEBGLFence extends Fence {\n readonly device: WebGLDevice;\n readonly gl: WebGL2RenderingContext;\n readonly handle: WebGLSync;\n readonly signaled: Promise;\n private _signaled = false;\n\n constructor(device: WebGLDevice, props: FenceProps = {}) {\n super(device, {});\n this.device = device;\n this.gl = device.gl;\n\n const sync = this.props.handle || this.gl.fenceSync(this.gl.SYNC_GPU_COMMANDS_COMPLETE, 0);\n if (!sync) {\n throw new Error('Failed to create WebGL fence');\n }\n this.handle = sync;\n\n this.signaled = new Promise(resolve => {\n const poll = () => {\n const status = this.gl.clientWaitSync(this.handle, 0, 0);\n if (status === this.gl.ALREADY_SIGNALED || status === this.gl.CONDITION_SATISFIED) {\n this._signaled = true;\n resolve();\n } else {\n setTimeout(poll, 1);\n }\n };\n poll();\n });\n }\n\n isSignaled(): boolean {\n if (this._signaled) {\n return true;\n }\n const status = this.gl.getSyncParameter(this.handle, this.gl.SYNC_STATUS);\n this._signaled = status === this.gl.SIGNALED;\n return this._signaled;\n }\n\n destroy(): void {\n if (!this.destroyed) {\n this.gl.deleteSync(this.handle);\n }\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {GL} from '@luma.gl/webgl/constants';\n\n// Returns number of components in a specific readPixels WebGL format\nexport function glFormatToComponents(format: GL): 0 | 1 | 2 | 3 | 4 {\n switch (format) {\n case GL.ALPHA:\n case GL.R32F:\n case GL.RED:\n case GL.RED_INTEGER:\n return 1;\n case GL.RG32I:\n case GL.RG32UI:\n case GL.RG32F:\n case GL.RG_INTEGER:\n case GL.RG:\n return 2;\n case GL.RGB:\n case GL.RGB_INTEGER:\n case GL.RGB32F:\n return 3;\n case GL.RGBA:\n case GL.RGBA_INTEGER:\n case GL.RGBA32F:\n return 4;\n // TODO: Add support for additional WebGL2 formats\n default:\n return 0;\n }\n}\n\n// Return byte count for given readPixels WebGL type\nexport function glTypeToBytes(type: GL): 0 | 1 | 2 | 4 {\n switch (type) {\n case GL.UNSIGNED_BYTE:\n return 1;\n case GL.UNSIGNED_SHORT_5_6_5:\n case GL.UNSIGNED_SHORT_4_4_4_4:\n case GL.UNSIGNED_SHORT_5_5_5_1:\n return 2;\n case GL.FLOAT:\n return 4;\n // TODO: Add support for additional WebGL2 types\n default:\n return 0;\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// @ts-nocheck This file will be deleted in upcoming refactor\n\nimport type {Buffer, Texture, FramebufferProps} from '@luma.gl/core';\nimport {Framebuffer, dataTypeDecoder} from '@luma.gl/core';\nimport {\n GL,\n GLTextureTarget,\n GLTextureCubeMapTarget,\n GLTexelDataFormat,\n GLPixelType,\n GLDataType\n} from '@luma.gl/webgl/constants';\n\nimport {convertDataTypeToGLDataType} from '../converters/webgl-shadertypes';\nimport {WEBGLFramebuffer} from '../resources/webgl-framebuffer';\nimport {glFormatToComponents, glTypeToBytes} from './format-utils';\nimport {WEBGLBuffer} from '../resources/webgl-buffer';\nimport {WEBGLTexture} from '../resources/webgl-texture';\nimport {convertGLDataTypeToDataType} from '../converters/shader-formats';\n\n/** A \"border\" parameter is required in many WebGL texture APIs, but must always be 0... */\nconst BORDER = 0;\n\n/**\n * Options for setting data into a texture\n */\nexport type WebGLSetTextureOptions = {\n dimension: '1d' | '2d' | '2d-array' | 'cube' | 'cube-array' | '3d';\n height: number;\n width: number;\n depth: number;\n mipLevel?: number;\n glTarget: GLTextureTarget;\n glInternalFormat: GL;\n glFormat: GLTexelDataFormat;\n glType: GLPixelType;\n compressed?: boolean;\n byteOffset?: number;\n byteLength?: number;\n};\n\n/**\n * Options for copying an image or data into a texture\n *\n * @param {GLenum} format - internal format of image data.\n * @param {GLenum} type\n * - format of array (autodetect from type) or\n * - (WEBGL2) format of buffer or ArrayBufferView\n * @param {GLenum} dataFormat - format of image data.\n * @param {Number} offset - (WEBGL2) offset from start of buffer\n * @parameters - temporary settings to be applied, can be used to supply pixel store settings.\n */\nexport type WebGLCopyTextureOptions = {\n dimension: '1d' | '2d' | '2d-array' | 'cube' | 'cube-array' | '3d';\n /** mip level to be updated */\n mipLevel?: number;\n /** width of the sub image to be updated */\n width: number;\n /** height of the sub image to be updated */\n height: number;\n /** depth of texture to be updated */\n depth?: number;\n /** xOffset from where texture to be updated */\n x?: number;\n /** yOffset from where texture to be updated */\n y?: number;\n /** yOffset from where texture to be updated */\n z?: number;\n\n glTarget: GLTextureTarget;\n glInternalFormat: GL;\n glFormat: GL;\n glType: GL;\n compressed?: boolean;\n byteOffset?: number;\n byteLength?: number;\n};\n\n/**\n * Copy a region of compressed data from a GPU memory buffer into this texture.\n */\nexport function copyGPUBufferToMipLevel(\n gl: WebGL2RenderingContext,\n webglBuffer: WebGLBuffer,\n byteLength: number,\n options: WebGLCopyTextureOptions\n): void {\n const {dimension, width, height, depth = 0, mipLevel = 0, byteOffset = 0} = options;\n const {x = 0, y = 0, z = 0} = options;\n const {glFormat, glType, compressed} = options;\n const glTarget = getWebGLCubeFaceTarget(options.glTarget, dimension, depth);\n\n gl.bindBuffer(GL.PIXEL_UNPACK_BUFFER, webglBuffer);\n\n switch (dimension) {\n case '2d-array':\n case '3d':\n // 3 dimensional textures requires 3D texture functions\n if (compressed) {\n // TODO enable extension?\n // biome-ignore format: preserve layout\n gl.compressedTexSubImage3D(glTarget, mipLevel, x, y, z, width, height, depth, glFormat, byteLength, byteOffset);\n } else {\n // biome-ignore format: preserve layout\n gl.texSubImage3D(glTarget, mipLevel, x, y, z, width, height, depth, glFormat, glType, byteOffset);\n }\n break;\n\n case '2d':\n case 'cube':\n if (compressed) {\n // biome-ignore format: preserve layout\n gl.compressedTexSubImage2D(glTarget, mipLevel, x, y, width, height, glFormat, byteLength, byteOffset);\n } else {\n // biome-ignore format: preserve layout\n gl.texSubImage2D(glTarget, mipLevel, x, y, width, height, BORDER, glFormat, byteOffset);\n }\n break;\n\n default:\n throw new Error(dimension);\n }\n}\n\n// INTERNAL HELPERS\n\n/** Convert a WebGPU style texture constant to a WebGL style texture constant */\nexport function getWebGLTextureTarget(\n dimension: '1d' | '2d' | '2d-array' | 'cube' | 'cube-array' | '3d'\n): GLTextureTarget {\n // biome-ignore format: preserve layout\n switch (dimension) {\n case '1d': break; // not supported in any WebGL version\n case '2d': return GL.TEXTURE_2D; // supported in WebGL1\n case '3d': return GL.TEXTURE_3D; // supported in WebGL2\n case 'cube': return GL.TEXTURE_CUBE_MAP; // supported in WebGL1\n case '2d-array': return GL.TEXTURE_2D_ARRAY; // supported in WebGL2\n case 'cube-array': break; // not supported in any WebGL version\n }\n throw new Error(dimension);\n}\n\n/**\n * In WebGL, cube maps specify faces by overriding target instead of using the depth parameter.\n * @note We still bind the texture using GL.TEXTURE_CUBE_MAP, but we need to use the face-specific target when setting mip levels.\n * @returns glTarget unchanged, if dimension !== 'cube'.\n */\nexport function getWebGLCubeFaceTarget(\n glTarget: GLTextureTarget,\n dimension: '1d' | '2d' | '2d-array' | 'cube' | 'cube-array' | '3d',\n level: number\n): GLTextureTarget | GLTextureCubeMapTarget {\n return dimension === 'cube' ? GL.TEXTURE_CUBE_MAP_POSITIVE_X + level : glTarget;\n}\nexport type ReadPixelsToArrayOptions = {\n sourceX?: number;\n sourceY?: number;\n sourceFormat?: number;\n sourceAttachment?: number;\n target?: Uint8Array | Uint16Array | Float32Array;\n // following parameters are auto deduced if not provided\n sourceWidth?: number;\n sourceHeight?: number;\n sourceDepth?: number;\n sourceType?: number;\n};\n\nexport type ReadPixelsToBufferOptions = {\n sourceX?: number;\n sourceY?: number;\n sourceFormat?: number;\n target?: Buffer; // A new Buffer object is created when not provided.\n targetByteOffset?: number; // byte offset in buffer object\n // following parameters are auto deduced if not provided\n sourceWidth?: number;\n sourceHeight?: number;\n sourceType?: number;\n};\n\n/**\n * Copies data from a type or a Texture object into ArrayBuffer object.\n * App can provide targetPixelArray or have it auto allocated by this method\n * newly allocated by this method unless provided by app.\n * @deprecated Use CommandEncoder.copyTextureToBuffer and Buffer.read\n * @note Slow requires roundtrip to GPU\n *\n * @param source\n * @param options\n * @returns pixel array,\n */\nexport function readPixelsToArray(\n source: Framebuffer | Texture,\n options?: ReadPixelsToArrayOptions\n): Uint8Array | Uint16Array | Float32Array {\n const {\n sourceX = 0,\n sourceY = 0,\n sourceAttachment = 0 // TODO - support gl.readBuffer\n } = options || {};\n let {\n target = null,\n // following parameters are auto deduced if not provided\n sourceWidth,\n sourceHeight,\n sourceDepth,\n sourceFormat,\n sourceType\n } = options || {};\n\n const {framebuffer, deleteFramebuffer} = getFramebuffer(source);\n // assert(framebuffer);\n const {gl, handle} = framebuffer;\n\n sourceWidth ||= framebuffer.width;\n sourceHeight ||= framebuffer.height;\n\n const texture = framebuffer.colorAttachments[sourceAttachment]?.texture;\n if (!texture) {\n throw new Error(`Invalid framebuffer attachment ${sourceAttachment}`);\n }\n sourceDepth = texture?.depth || 1;\n\n sourceFormat ||= texture?.glFormat || GL.RGBA;\n // Deduce the type from color attachment if not provided.\n sourceType ||= texture?.glType || GL.UNSIGNED_BYTE;\n\n // Deduce type and allocated pixelArray if needed\n target = getPixelArray(target, sourceType, sourceFormat, sourceWidth, sourceHeight, sourceDepth);\n\n // Pixel array available, if necessary, deduce type from it.\n const signedType = dataTypeDecoder.getDataType(target);\n sourceType = sourceType || convertDataTypeToGLDataType(signedType);\n\n // Note: luma.gl overrides bindFramebuffer so that we can reliably restore the previous framebuffer (this is the only function for which we do that)\n const prevHandle = gl.bindFramebuffer(\n GL.FRAMEBUFFER,\n handle\n ) as unknown as WebGLFramebuffer | null;\n\n // Select the color attachment to read from\n gl.readBuffer(gl.COLOR_ATTACHMENT0 + sourceAttachment);\n\n // There is a lot of hedging in the WebGL2 spec about what formats are guaranteed to be readable\n // (It should always be possible to read RGBA/UNSIGNED_BYTE, but most other combinations are not guaranteed)\n // Querying is possible but expensive:\n // const {device} = framebuffer;\n // texture.glReadFormat ||= gl.getParameter(gl.IMPLEMENTATION_COLOR_READ_FORMAT);\n // texture.glReadType ||= gl.getParameter(gl.IMPLEMENTATION_COLOR_READ_TYPE);\n // console.log('params', device.getGLKey(texture.glReadFormat), device.getGLKey(texture.glReadType));\n\n gl.readPixels(sourceX, sourceY, sourceWidth, sourceHeight, sourceFormat, sourceType, target);\n gl.readBuffer(gl.COLOR_ATTACHMENT0);\n gl.bindFramebuffer(GL.FRAMEBUFFER, prevHandle || null);\n\n if (deleteFramebuffer) {\n framebuffer.destroy();\n }\n\n return target;\n}\n\n/**\n * Copies data from a Framebuffer or a Texture object into a Buffer object.\n * NOTE: doesn't wait for copy to be complete, it programs GPU to perform a DMA transffer.\n * @deprecated Use CommandEncoder\n * @param source\n * @param options\n */\nexport function readPixelsToBuffer(\n source: Framebuffer | Texture,\n options?: ReadPixelsToBufferOptions\n): WEBGLBuffer {\n const {\n target,\n sourceX = 0,\n sourceY = 0,\n sourceFormat = GL.RGBA,\n targetByteOffset = 0\n } = options || {};\n // following parameters are auto deduced if not provided\n let {sourceWidth, sourceHeight, sourceType} = options || {};\n const {framebuffer, deleteFramebuffer} = getFramebuffer(source);\n // assert(framebuffer);\n sourceWidth = sourceWidth || framebuffer.width;\n sourceHeight = sourceHeight || framebuffer.height;\n\n // Asynchronous read (PIXEL_PACK_BUFFER) is WebGL2 only feature\n const webglFramebuffer = framebuffer;\n\n // deduce type if not available.\n sourceType = sourceType || GL.UNSIGNED_BYTE;\n\n let webglBufferTarget = target as unknown as WEBGLBuffer | undefined;\n if (!webglBufferTarget) {\n // Create new buffer with enough size\n const components = glFormatToComponents(sourceFormat);\n const byteCount = glTypeToBytes(sourceType);\n const byteLength = targetByteOffset + sourceWidth * sourceHeight * components * byteCount;\n webglBufferTarget = webglFramebuffer.device.createBuffer({byteLength});\n }\n\n // TODO(donmccurdy): Do we have tests to confirm this is working?\n const commandEncoder = source.device.createCommandEncoder();\n commandEncoder.copyTextureToBuffer({\n sourceTexture: source as Texture,\n width: sourceWidth,\n height: sourceHeight,\n origin: [sourceX, sourceY],\n destinationBuffer: webglBufferTarget,\n byteOffset: targetByteOffset\n });\n commandEncoder.destroy();\n\n if (deleteFramebuffer) {\n framebuffer.destroy();\n }\n\n return webglBufferTarget;\n}\n\n/**\n * Copy a rectangle from a Framebuffer or Texture object into a texture (at an offset)\n * @deprecated Use CommandEncoder\n */\n// eslint-disable-next-line complexity, max-statements\nexport function copyToTexture(\n sourceTexture: Framebuffer | Texture,\n destinationTexture: Texture | GL,\n options?: {\n sourceX?: number;\n sourceY?: number;\n\n targetX?: number;\n targetY?: number;\n targetZ?: number;\n targetMipmaplevel?: number;\n targetInternalFormat?: number;\n\n width?: number; // defaults to target width\n height?: number; // defaults to target height\n }\n): Texture {\n const {\n sourceX = 0,\n sourceY = 0,\n // attachment = GL.COLOR_ATTACHMENT0, // TODO - support gl.readBuffer\n targetMipmaplevel = 0,\n targetInternalFormat = GL.RGBA\n } = options || {};\n let {\n targetX,\n targetY,\n targetZ,\n width, // defaults to target width\n height // defaults to target height\n } = options || {};\n\n const {framebuffer, deleteFramebuffer} = getFramebuffer(sourceTexture);\n // assert(framebuffer);\n const webglFramebuffer = framebuffer;\n const {device, handle} = webglFramebuffer;\n const isSubCopy =\n typeof targetX !== 'undefined' ||\n typeof targetY !== 'undefined' ||\n typeof targetZ !== 'undefined';\n targetX = targetX || 0;\n targetY = targetY || 0;\n targetZ = targetZ || 0;\n const prevHandle = device.gl.bindFramebuffer(GL.FRAMEBUFFER, handle);\n // TODO - support gl.readBuffer (WebGL2 only)\n // const prevBuffer = gl.readBuffer(attachment);\n // assert(target);\n let texture: WEBGLTexture | null = null;\n let textureTarget: GL;\n if (destinationTexture instanceof WEBGLTexture) {\n texture = destinationTexture;\n width = Number.isFinite(width) ? width : texture.width;\n height = Number.isFinite(height) ? height : texture.height;\n texture?._bind(0);\n // @ts-ignore\n textureTarget = texture.target;\n } else {\n // @ts-ignore\n textureTarget = target;\n }\n\n if (!isSubCopy) {\n device.gl.copyTexImage2D(\n textureTarget,\n targetMipmaplevel,\n targetInternalFormat,\n sourceX,\n sourceY,\n width,\n height,\n 0 /* border must be 0 */\n );\n } else {\n switch (textureTarget) {\n case GL.TEXTURE_2D:\n case GL.TEXTURE_CUBE_MAP:\n device.gl.copyTexSubImage2D(\n textureTarget,\n targetMipmaplevel,\n targetX,\n targetY,\n sourceX,\n sourceY,\n width,\n height\n );\n break;\n case GL.TEXTURE_2D_ARRAY:\n case GL.TEXTURE_3D:\n device.gl.copyTexSubImage3D(\n textureTarget,\n targetMipmaplevel,\n targetX,\n targetY,\n targetZ,\n sourceX,\n sourceY,\n width,\n height\n );\n break;\n default:\n }\n }\n if (texture) {\n texture._unbind();\n }\n // @ts-expect-error\n device.gl.bindFramebuffer(GL.FRAMEBUFFER, prevHandle || null);\n if (deleteFramebuffer) {\n framebuffer.destroy();\n }\n return texture;\n}\n\nfunction getFramebuffer(source: Texture | Framebuffer): {\n framebuffer: WEBGLFramebuffer;\n deleteFramebuffer: boolean;\n} {\n if (!(source instanceof Framebuffer)) {\n return {framebuffer: toFramebuffer(source), deleteFramebuffer: true};\n }\n return {framebuffer: source as WEBGLFramebuffer, deleteFramebuffer: false};\n}\n\n/**\n * Wraps a given texture into a framebuffer object, that can be further used\n * to read data from the texture object.\n */\nexport function toFramebuffer(texture: Texture, props?: FramebufferProps): WEBGLFramebuffer {\n const {device, width, height, id} = texture;\n const framebuffer = device.createFramebuffer({\n ...props,\n id: `framebuffer-for-${id}`,\n width,\n height,\n colorAttachments: [texture]\n });\n return framebuffer as WEBGLFramebuffer;\n}\n\n// eslint-disable-next-line max-params\nfunction getPixelArray(\n pixelArray,\n glType: GLDataType | GLPixelType,\n glFormat: GL,\n width: number,\n height: number,\n depth?: number\n): Uint8Array | Uint16Array | Float32Array {\n if (pixelArray) {\n return pixelArray;\n }\n // const formatInfo = getTextureFormatInfo(format);\n // Allocate pixel array if not already available, using supplied type\n glType ||= GL.UNSIGNED_BYTE;\n const shaderType = convertGLDataTypeToDataType(glType);\n const ArrayType = dataTypeDecoder.getTypedArrayConstructor(shaderType);\n const components = glFormatToComponents(glFormat);\n // TODO - check for composite type (components = 1).\n return new ArrayType(width * height * components) as Uint8Array | Uint16Array | Float32Array;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {TypedArray} from '@math.gl/types';\nimport type {\n DeviceProps,\n DeviceInfo,\n DeviceTextureFormatCapabilities,\n CanvasContextProps,\n PresentationContextProps,\n PresentationContext,\n Buffer,\n Texture,\n Framebuffer,\n VertexArray,\n VertexArrayProps,\n BufferProps,\n ShaderProps,\n // Sampler,\n SamplerProps,\n TextureProps,\n ExternalTexture,\n ExternalTextureProps,\n FramebufferProps,\n // RenderPipeline,\n RenderPipelineProps,\n SharedRenderPipeline,\n ComputePipeline,\n ComputePipelineProps,\n // CommandEncoder,\n CommandEncoderProps,\n TransformFeedbackProps,\n QuerySetProps,\n Resource,\n VertexFormat\n} from '@luma.gl/core';\nimport {Device, CanvasContext, log} from '@luma.gl/core';\nimport type {GLExtensions} from '@luma.gl/webgl/constants';\nimport {WebGLStateTracker} from '../context/state-tracker/webgl-state-tracker';\nimport {createBrowserContext} from '../context/helpers/create-browser-context';\nimport {getWebGLContextData} from '../context/helpers/webgl-context-data';\nimport {getDeviceInfo} from './device-helpers/webgl-device-info';\nimport {WebGLDeviceFeatures} from './device-helpers/webgl-device-features';\nimport {WebGLDeviceLimits} from './device-helpers/webgl-device-limits';\nimport {WebGLCanvasContext} from './webgl-canvas-context';\nimport {WebGLPresentationContext} from './webgl-presentation-context';\nimport type {Spector} from '../context/debug/spector-types';\nimport {initializeSpectorJS} from '../context/debug/spector';\nimport {makeDebugContext} from '../context/debug/webgl-developer-tools';\nimport {getTextureFormatCapabilitiesWebGL} from './converters/webgl-texture-table';\nimport {uid} from '../utils/uid';\n\nimport {WEBGLBuffer} from './resources/webgl-buffer';\nimport {WEBGLShader} from './resources/webgl-shader';\nimport {WEBGLSampler} from './resources/webgl-sampler';\nimport {WEBGLTexture} from './resources/webgl-texture';\nimport {WEBGLFramebuffer} from './resources/webgl-framebuffer';\nimport {WEBGLRenderPipeline} from './resources/webgl-render-pipeline';\nimport {WEBGLSharedRenderPipeline} from './resources/webgl-shared-render-pipeline';\nimport {WEBGLCommandEncoder} from './resources/webgl-command-encoder';\nimport {WEBGLCommandBuffer} from './resources/webgl-command-buffer';\nimport {WEBGLVertexArray} from './resources/webgl-vertex-array';\nimport {WEBGLTransformFeedback} from './resources/webgl-transform-feedback';\nimport {WEBGLQuerySet} from './resources/webgl-query-set';\nimport {WEBGLFence} from './resources/webgl-fence';\n\nimport {readPixelsToArray, readPixelsToBuffer} from './helpers/webgl-texture-utils';\nimport {\n setGLParameters,\n getGLParameters,\n resetGLParameters\n} from '../context/parameters/unified-parameter-api';\nimport {withGLParameters} from '../context/state-tracker/with-parameters';\nimport {getWebGLExtension} from '../context/helpers/webgl-extensions';\n\n/** WebGPU style Device API for a WebGL context */\nexport class WebGLDevice extends Device {\n static getDeviceFromContext(gl: WebGL2RenderingContext | null): WebGLDevice | null {\n if (!gl) {\n return null;\n }\n // @ts-expect-error Ingore WebGL2RenderingContext type\n return gl.luma?.device ?? null;\n }\n // Public `Device` API\n\n /** type of this device */\n readonly type = 'webgl';\n\n // Use the ! assertion to handle the case where _reuseDevices causes the constructor to return early\n /** The underlying WebGL context */\n readonly handle!: WebGL2RenderingContext;\n features!: WebGLDeviceFeatures;\n limits!: WebGLDeviceLimits;\n readonly info!: DeviceInfo;\n readonly canvasContext!: WebGLCanvasContext;\n\n readonly preferredColorFormat = 'rgba8unorm';\n readonly preferredDepthFormat = 'depth24plus';\n\n commandEncoder!: WEBGLCommandEncoder;\n\n readonly lost: Promise<{reason: 'destroyed'; message: string}>;\n\n private _resolveContextLost?: (value: {reason: 'destroyed'; message: string}) => void;\n\n /** WebGL2 context. */\n readonly gl!: WebGL2RenderingContext;\n\n /** Store constants */\n // @ts-ignore TODO fix\n _constants: (TypedArray | null)[];\n\n /** State used by luma.gl classes - TODO - not used? */\n readonly extensions!: GLExtensions;\n _polyfilled: boolean = false;\n\n /** Instance of Spector.js (if initialized) */\n spectorJS!: Spector | null;\n\n //\n // Public API\n //\n\n override get [Symbol.toStringTag](): string {\n return 'WebGLDevice';\n }\n\n override toString(): string {\n return `${this[Symbol.toStringTag]}(${this.id})`;\n }\n\n override isVertexFormatSupported(format: VertexFormat): boolean {\n switch (format) {\n case 'unorm8x4-bgra':\n return false;\n default:\n return true;\n }\n }\n\n constructor(props: DeviceProps) {\n super({...props, id: props.id || uid('webgl-device')});\n\n const canvasContextProps = Device._getCanvasContextProps(props)!;\n\n // WebGL requires a canvas to be created before creating the context\n if (!canvasContextProps) {\n throw new Error('WebGLDevice requires props.createCanvasContext to be set');\n }\n\n // Check if the WebGL context is already associated with a device\n // Note that this can be avoided in webgl2adapter.create() if\n // DeviceProps._reuseDevices is set.\n // @ts-expect-error device is attached to context\n const existingContext = canvasContextProps.canvas?.gl ?? null;\n let device: WebGLDevice | null = WebGLDevice.getDeviceFromContext(existingContext);\n if (device) {\n throw new Error(`WebGL context already attached to device ${device.id}`);\n }\n\n // Create and instrument context\n this.canvasContext = new WebGLCanvasContext(this, canvasContextProps);\n\n this.lost = new Promise<{reason: 'destroyed'; message: string}>(resolve => {\n this._resolveContextLost = resolve;\n });\n\n const webglContextAttributes: WebGLContextAttributes = {...props.webgl};\n // Copy props from CanvasContextProps\n if (canvasContextProps.alphaMode === 'premultiplied') {\n webglContextAttributes.premultipliedAlpha = true;\n }\n if (props.powerPreference !== undefined) {\n webglContextAttributes.powerPreference = props.powerPreference;\n }\n if (props.failIfMajorPerformanceCaveat !== undefined) {\n webglContextAttributes.failIfMajorPerformanceCaveat = props.failIfMajorPerformanceCaveat;\n }\n\n // Check if we should attach to an externally created context or create a new context\n const externalGLContext = this.props._handle as WebGL2RenderingContext | null;\n\n const gl =\n externalGLContext ||\n createBrowserContext(\n this.canvasContext.canvas,\n {\n onContextLost: (event: Event) =>\n this._resolveContextLost?.({\n reason: 'destroyed',\n message: 'Entered sleep mode, or too many apps or browser tabs are using the GPU.'\n }),\n // eslint-disable-next-line no-console\n onContextRestored: (event: Event) => console.log('WebGL context restored')\n },\n webglContextAttributes\n );\n\n if (!gl) {\n throw new Error('WebGL context creation failed');\n }\n\n // Note that the browser will only create one WebGL context per canvas.\n // This means that a newly created gl context may already have a device attached to it.\n device = WebGLDevice.getDeviceFromContext(gl);\n if (device) {\n if (props._reuseDevices) {\n log.log(\n 1,\n `Not creating a new Device, instead returning a reference to Device ${device.id} already attached to WebGL context`,\n device\n )();\n // Destroy the orphaned canvas context that was created above (line 149)\n // to prevent its ResizeObserver from firing callbacks with undefined device\n this.canvasContext.destroy();\n device._reused = true;\n return device;\n }\n throw new Error(`WebGL context already attached to device ${device.id}`);\n }\n\n this.handle = gl;\n this.gl = gl;\n\n // Add spector debug instrumentation to context\n // We need to trust spector integration to decide if spector should be initialized\n // We also run spector instrumentation first, otherwise spector can clobber luma instrumentation.\n this.spectorJS = initializeSpectorJS({...this.props, gl: this.handle});\n\n // Instrument context\n const contextData = getWebGLContextData(this.handle);\n contextData.device = this; // Update GL context: Link webgl context back to device\n\n if (!contextData.extensions) {\n contextData.extensions = {};\n }\n this.extensions = contextData.extensions;\n\n // initialize luma Device fields\n this.info = getDeviceInfo(this.gl, this.extensions);\n this.limits = new WebGLDeviceLimits(this.gl);\n this.features = new WebGLDeviceFeatures(this.gl, this.extensions, this.props._disabledFeatures);\n if (this.props._initializeFeatures) {\n this.features.initializeFeatures();\n }\n\n // Install context state tracking\n const glState = new WebGLStateTracker(this.gl, {\n log: (...args: any[]) => log.log(1, ...args)()\n });\n glState.trackState(this.gl, {copyState: false});\n\n // props.debug - instrument the WebGL context with Khronos debug tools\n // props.debugWebGL - activate WebGL context tracing, force log level to at least 1\n if (props.debug || props.debugWebGL) {\n this.gl = makeDebugContext(this.gl, {debugWebGL: true, traceWebGL: props.debugWebGL});\n log.warn('WebGL debug mode activated. Performance reduced.')();\n }\n if (props.debugWebGL) {\n log.level = Math.max(log.level, 1);\n }\n\n this.commandEncoder = new WEBGLCommandEncoder(this, {id: `${this}-command-encoder`});\n this.canvasContext._startObservers();\n }\n\n /**\n * Destroys the device\n *\n * @note \"Detaches\" from the WebGL context unless _reuseDevices is true.\n *\n * @note The underlying WebGL context is not immediately destroyed,\n * but may be destroyed later through normal JavaScript garbage collection.\n * This is a fundamental limitation since WebGL does not offer any\n * browser API for destroying WebGL contexts.\n */\n destroy(): void {\n this.commandEncoder?.destroy();\n // Note that deck.gl (especially in React strict mode) depends on being able\n // to asynchronously create a Device against the same canvas (i.e. WebGL context)\n // multiple times and getting the same device back. Since deck.gl is not aware\n // of this sharing, it might call destroy() multiple times on the same device.\n // Therefore we must do nothing in destroy() if props._reuseDevices is true\n if (!this.props._reuseDevices && !this._reused) {\n // Delete the reference to the device that we store on the WebGL context\n const contextData = getWebGLContextData(this.handle);\n contextData.device = null;\n }\n }\n\n get isLost(): boolean {\n return this.gl.isContextLost();\n }\n\n // IMPLEMENTATION OF ABSTRACT DEVICE\n\n createCanvasContext(props?: CanvasContextProps): CanvasContext {\n throw new Error('WebGL only supports a single canvas');\n }\n\n createPresentationContext(props?: PresentationContextProps): PresentationContext {\n return new WebGLPresentationContext(this, props || {});\n }\n\n createBuffer(props: BufferProps | ArrayBuffer | ArrayBufferView): WEBGLBuffer {\n const newProps = this._normalizeBufferProps(props);\n return new WEBGLBuffer(this, newProps);\n }\n\n createTexture(props: TextureProps): WEBGLTexture {\n return new WEBGLTexture(this, props);\n }\n\n createExternalTexture(props: ExternalTextureProps): ExternalTexture {\n throw new Error('createExternalTexture() not implemented'); // return new Program(props);\n }\n\n createSampler(props: SamplerProps): WEBGLSampler {\n return new WEBGLSampler(this, props);\n }\n\n createShader(props: ShaderProps): WEBGLShader {\n return new WEBGLShader(this, props);\n }\n\n createFramebuffer(props: FramebufferProps): WEBGLFramebuffer {\n return new WEBGLFramebuffer(this, props);\n }\n\n createVertexArray(props: VertexArrayProps): VertexArray {\n return new WEBGLVertexArray(this, props);\n }\n\n createTransformFeedback(props: TransformFeedbackProps): WEBGLTransformFeedback {\n return new WEBGLTransformFeedback(this, props);\n }\n\n createQuerySet(props: QuerySetProps): WEBGLQuerySet {\n return new WEBGLQuerySet(this, props);\n }\n\n override createFence(): WEBGLFence {\n return new WEBGLFence(this);\n }\n\n createRenderPipeline(props: RenderPipelineProps): WEBGLRenderPipeline {\n return new WEBGLRenderPipeline(this, props);\n }\n\n override _createSharedRenderPipelineWebGL(props: RenderPipelineProps): SharedRenderPipeline {\n return new WEBGLSharedRenderPipeline(\n this,\n props as RenderPipelineProps & {vs: WEBGLShader; fs: WEBGLShader}\n );\n }\n\n createComputePipeline(props?: ComputePipelineProps): ComputePipeline {\n throw new Error('ComputePipeline not supported in WebGL');\n }\n\n override createCommandEncoder(props: CommandEncoderProps = {}): WEBGLCommandEncoder {\n return new WEBGLCommandEncoder(this, props);\n }\n\n /**\n * Offscreen Canvas Support: Commit the frame\n * https://developer.mozilla.org/en-US/docs/Web/API/WebGL2RenderingContext/commit\n * Chrome's offscreen canvas does not require gl.commit\n */\n submit(commandBuffer?: WEBGLCommandBuffer): void {\n let submittedCommandEncoder: WEBGLCommandEncoder | null = null;\n if (!commandBuffer) {\n ({submittedCommandEncoder, commandBuffer} = this._finalizeDefaultCommandEncoderForSubmit());\n }\n\n try {\n commandBuffer._executeCommands();\n\n if (submittedCommandEncoder) {\n submittedCommandEncoder\n .resolveTimeProfilingQuerySet()\n .then(() => {\n this.commandEncoder._gpuTimeMs = submittedCommandEncoder._gpuTimeMs;\n })\n .catch(() => {});\n }\n } finally {\n commandBuffer.destroy();\n }\n }\n\n private _finalizeDefaultCommandEncoderForSubmit(): {\n submittedCommandEncoder: WEBGLCommandEncoder;\n commandBuffer: WEBGLCommandBuffer;\n } {\n const submittedCommandEncoder = this.commandEncoder;\n const commandBuffer = submittedCommandEncoder.finish();\n this.commandEncoder.destroy();\n this.commandEncoder = this.createCommandEncoder({\n id: submittedCommandEncoder.props.id,\n timeProfilingQuerySet: submittedCommandEncoder.getTimeProfilingQuerySet()\n });\n return {submittedCommandEncoder, commandBuffer};\n }\n\n //\n // TEMPORARY HACKS - will be removed in v9.1\n //\n\n /** @deprecated - should use command encoder */\n override readPixelsToArrayWebGL(\n source: Framebuffer | Texture,\n options?: {\n sourceX?: number;\n sourceY?: number;\n sourceFormat?: number;\n sourceAttachment?: number;\n target?: Uint8Array | Uint16Array | Float32Array;\n // following parameters are auto deduced if not provided\n sourceWidth?: number;\n sourceHeight?: number;\n sourceType?: number;\n }\n ): Uint8Array | Uint16Array | Float32Array {\n return readPixelsToArray(source, options);\n }\n\n /** @deprecated - should use command encoder */\n override readPixelsToBufferWebGL(\n source: Framebuffer | Texture,\n options?: {\n sourceX?: number;\n sourceY?: number;\n sourceFormat?: number;\n target?: Buffer; // A new Buffer object is created when not provided.\n targetByteOffset?: number; // byte offset in buffer object\n // following parameters are auto deduced if not provided\n sourceWidth?: number;\n sourceHeight?: number;\n sourceType?: number;\n }\n ): Buffer {\n return readPixelsToBuffer(source, options);\n }\n\n override setParametersWebGL(parameters: any): void {\n setGLParameters(this.gl, parameters);\n }\n\n override getParametersWebGL(parameters: any): any {\n return getGLParameters(this.gl, parameters);\n }\n\n override withParametersWebGL(parameters: any, func: any): any {\n return withGLParameters(this.gl, parameters, func);\n }\n\n override resetWebGL(): void {\n log.warn('WebGLDevice.resetWebGL is deprecated, use only for debugging')();\n resetGLParameters(this.gl);\n }\n\n override _getDeviceSpecificTextureFormatCapabilities(\n capabilities: DeviceTextureFormatCapabilities\n ): DeviceTextureFormatCapabilities {\n return getTextureFormatCapabilitiesWebGL(this.gl, capabilities, this.extensions);\n }\n\n //\n // WebGL-only API (not part of `Device` API)\n //\n\n /**\n * Triggers device (or WebGL context) loss.\n * @note primarily intended for testing how application reacts to device loss\n */\n override loseDevice(): boolean {\n let deviceLossTriggered = false;\n const extensions = this.getExtension('WEBGL_lose_context');\n const ext = extensions.WEBGL_lose_context;\n if (ext) {\n deviceLossTriggered = true;\n ext.loseContext();\n // ext.loseContext should trigger context loss callback but the platform may not do this, so do it explicitly\n }\n this._resolveContextLost?.({\n reason: 'destroyed',\n message: 'Application triggered context loss'\n });\n return deviceLossTriggered;\n }\n\n /** Save current WebGL context state onto an internal stack */\n pushState(): void {\n const webglState = WebGLStateTracker.get(this.gl);\n webglState.push();\n }\n\n /** Restores previously saved context state */\n popState(): void {\n const webglState = WebGLStateTracker.get(this.gl);\n webglState.pop();\n }\n\n /**\n * Returns the GL. constant that corresponds to a numeric value of a GL constant\n * Be aware that there are some duplicates especially for constants that are 0,\n * so this isn't guaranteed to return the right key in all cases.\n */\n getGLKey(value: unknown, options?: {emptyIfUnknown?: boolean}): string {\n const number = Number(value);\n for (const key in this.gl) {\n // @ts-ignore expect-error depends on settings\n if (this.gl[key] === number) {\n return `GL.${key}`;\n }\n }\n // No constant found. Stringify the value and return it.\n return options?.emptyIfUnknown ? '' : String(value);\n }\n\n /**\n * Returns a map with any GL. constants mapped to strings, both for keys and values\n */\n getGLKeys(glParameters: Record): Record {\n const opts = {emptyIfUnknown: true};\n return Object.entries(glParameters).reduce>((keys, [key, value]) => {\n // eslint-disable-next-line @typescript-eslint/no-base-to-string\n keys[`${key}:${this.getGLKey(key, opts)}`] = `${value}:${this.getGLKey(value, opts)}`;\n return keys;\n }, {});\n }\n\n /**\n * Set a constant value for a location. Disabled attributes at that location will read from this value\n * @note WebGL constants are stored globally on the WebGL context, not the VertexArray\n * so they need to be updated before every render\n * @todo - remember/cache values to avoid setting them unnecessarily?\n */\n setConstantAttributeWebGL(location: number, constant: TypedArray): void {\n const maxVertexAttributes = this.limits.maxVertexAttributes;\n this._constants = this._constants || new Array(maxVertexAttributes).fill(null);\n const currentConstant = this._constants[location];\n if (currentConstant && compareConstantArrayValues(currentConstant, constant)) {\n log.info(\n 1,\n `setConstantAttributeWebGL(${location}) could have been skipped, value unchanged`\n )();\n }\n this._constants[location] = constant;\n\n switch (constant.constructor) {\n case Float32Array:\n setConstantFloatArray(this, location, constant as Float32Array);\n break;\n case Int32Array:\n setConstantIntArray(this, location, constant as Int32Array);\n break;\n case Uint32Array:\n setConstantUintArray(this, location, constant as Uint32Array);\n break;\n default:\n throw new Error('constant');\n }\n }\n\n /** Ensure extensions are only requested once */\n getExtension(name: keyof GLExtensions): GLExtensions {\n getWebGLExtension(this.gl, name, this.extensions);\n return this.extensions;\n }\n\n // INTERNAL SUPPORT METHODS FOR WEBGL RESOURCES\n\n /**\n * Storing data on a special field on WebGLObjects makes that data visible in SPECTOR chrome debug extension\n * luma.gl ids and props can be inspected\n */\n _setWebGLDebugMetadata(\n handle: unknown,\n resource: Resource,\n options: {spector: Record}\n ): void {\n // @ts-expect-error\n handle.luma = resource;\n\n const spectorMetadata = {props: options.spector, id: options.spector['id']};\n // @ts-expect-error\n // eslint-disable-next-line camelcase\n handle.__SPECTOR_Metadata = spectorMetadata;\n }\n}\n\n/** Set constant float array attribute */\nfunction setConstantFloatArray(device: WebGLDevice, location: number, array: Float32Array): void {\n switch (array.length) {\n case 1:\n device.gl.vertexAttrib1fv(location, array);\n break;\n case 2:\n device.gl.vertexAttrib2fv(location, array);\n break;\n case 3:\n device.gl.vertexAttrib3fv(location, array);\n break;\n case 4:\n device.gl.vertexAttrib4fv(location, array);\n break;\n default:\n // assert(false);\n }\n}\n\n/** Set constant signed int array attribute */\nfunction setConstantIntArray(device: WebGLDevice, location: number, array: Int32Array): void {\n device.gl.vertexAttribI4iv(location, array);\n // TODO - not clear if we need to use the special forms, more testing needed\n // switch (array.length) {\n // case 1:\n // gl.vertexAttribI1iv(location, array);\n // break;\n // case 2:\n // gl.vertexAttribI2iv(location, array);\n // break;\n // case 3:\n // gl.vertexAttribI3iv(location, array);\n // break;\n // case 4:\n // break;\n // default:\n // assert(false);\n // }\n}\n\n/** Set constant unsigned int array attribute */\nfunction setConstantUintArray(device: WebGLDevice, location: number, array: Uint32Array) {\n device.gl.vertexAttribI4uiv(location, array);\n // TODO - not clear if we need to use the special forms, more testing needed\n // switch (array.length) {\n // case 1:\n // gl.vertexAttribI1uiv(location, array);\n // break;\n // case 2:\n // gl.vertexAttribI2uiv(location, array);\n // break;\n // case 3:\n // gl.vertexAttribI3uiv(location, array);\n // break;\n // case 4:\n // gl.vertexAttribI4uiv(location, array);\n // break;\n // default:\n // assert(false);\n // }\n}\n\n/**\n * Compares contents of two typed arrays\n * @todo max length?\n */\nfunction compareConstantArrayValues(v1: TypedArray, v2: TypedArray): boolean {\n if (!v1 || !v2 || v1.length !== v2.length || v1.constructor !== v2.constructor) {\n return false;\n }\n for (let i = 0; i < v1.length; ++i) {\n if (v1[i] !== v2[i]) {\n return false;\n }\n }\n return true;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {WebGLDevice} from './webgl-device';\nimport {Adapter, Device, DeviceProps, log} from '@luma.gl/core';\nimport {enforceWebGL2} from '../context/polyfills/polyfill-webgl1-extensions';\nimport {loadSpectorJS, DEFAULT_SPECTOR_PROPS} from '../context/debug/spector';\nimport {loadWebGLDeveloperTools} from '../context/debug/webgl-developer-tools';\n\nconst LOG_LEVEL = 1;\n\nexport class WebGLAdapter extends Adapter {\n /** type of device's created by this adapter */\n readonly type: Device['type'] = 'webgl';\n\n constructor() {\n super();\n // Add spector default props to device default props, so that runtime settings are observed\n Device.defaultProps = {...Device.defaultProps, ...DEFAULT_SPECTOR_PROPS};\n }\n\n /** Force any created WebGL contexts to be WebGL2 contexts, polyfilled with WebGL1 extensions */\n enforceWebGL2(enable: boolean): void {\n enforceWebGL2(enable);\n }\n\n /** Check if WebGL 2 is available */\n isSupported(): boolean {\n return typeof WebGL2RenderingContext !== 'undefined';\n }\n\n override isDeviceHandle(handle: unknown): boolean {\n // WebGL\n if (typeof WebGL2RenderingContext !== 'undefined' && handle instanceof WebGL2RenderingContext) {\n return true;\n }\n\n if (typeof WebGLRenderingContext !== 'undefined' && handle instanceof WebGLRenderingContext) {\n log.warn('WebGL1 is not supported', handle)();\n }\n\n return false;\n }\n\n /**\n * Get a device instance from a GL context\n * Creates a WebGLCanvasContext against the contexts canvas\n * @note autoResize will be disabled, assuming that whoever created the external context will be handling resizes.\n * @param gl\n * @returns\n */\n async attach(gl: Device | WebGL2RenderingContext, props: DeviceProps = {}): Promise {\n const {WebGLDevice} = await import('./webgl-device');\n if (gl instanceof WebGLDevice) {\n return gl;\n }\n const existingDevice = WebGLDevice.getDeviceFromContext(gl as WebGL2RenderingContext | null);\n if (existingDevice) {\n return existingDevice;\n }\n if (!isWebGL(gl)) {\n throw new Error('Invalid WebGL2RenderingContext');\n }\n\n const createCanvasContext = props.createCanvasContext === true ? {} : props.createCanvasContext;\n\n // We create a new device using the provided WebGL context and its canvas\n // Assume that whoever created the external context will be handling resizes.\n return new WebGLDevice({\n ...props,\n _handle: gl,\n createCanvasContext: {canvas: gl.canvas, autoResize: false, ...createCanvasContext}\n });\n }\n\n async create(props: DeviceProps = {}): Promise {\n const {WebGLDevice} = await import('./webgl-device');\n\n const promises: Promise[] = [];\n\n // Load webgl and spector debug scripts from CDN if requested\n if (props.debugWebGL || props.debug) {\n promises.push(loadWebGLDeveloperTools());\n }\n\n if (props.debugSpectorJS) {\n promises.push(loadSpectorJS(props));\n }\n\n // Wait for all the loads to settle before creating the context.\n // The Device.create() functions are async, so in contrast to the constructor, we can `await` here.\n const results = await Promise.allSettled(promises);\n for (const result of results) {\n if (result.status === 'rejected') {\n log.error(`Failed to initialize debug libraries ${result.reason}`)();\n }\n }\n\n try {\n const device = new WebGLDevice(props);\n\n log.groupCollapsed(LOG_LEVEL, `WebGLDevice ${device.id} created`)();\n // Log some debug info about the newly created context\n const message = `\\\n${device._reused ? 'Reusing' : 'Created'} device with WebGL2 ${device.props.debug ? 'debug ' : ''}context: \\\n${device.info.vendor}, ${device.info.renderer} for canvas: ${device.canvasContext.id}`;\n log.probe(LOG_LEVEL, message)();\n log.table(LOG_LEVEL, device.info)();\n return device;\n } finally {\n log.groupEnd(LOG_LEVEL)();\n log.info(\n LOG_LEVEL,\n `%cWebGL call tracing: luma.log.set('debug-webgl') `,\n 'color: white; background: blue; padding: 2px 6px; border-radius: 3px;'\n )();\n }\n }\n}\n\n/** Check if supplied parameter is a WebGL2RenderingContext */\nfunction isWebGL(gl: any): gl is WebGL2RenderingContext {\n if (typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext) {\n return true;\n }\n return Boolean(gl && typeof gl.createVertexArray === 'function');\n}\n\nexport const webgl2Adapter = new WebGLAdapter();\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// luma.gl Base WebGL wrapper library\n// Provides simple class/function wrappers around the low level webgl objects\n// These classes are intentionally close to the WebGL API\n// but make it easier to use.\n// Higher level abstractions can be built on these classes\n\n// Types\nexport type {WebGLDeviceLimits} from './adapter/device-helpers/webgl-device-limits';\nexport {GL} from './constants/webgl-constants';\nexport type {\n GLTextureTarget,\n GLTextureCubeMapTarget,\n GLTexelDataFormat,\n GLPrimitiveTopology,\n GLPrimitive,\n GLDataType,\n GLPixelType,\n GLUniformType,\n GLSamplerType,\n GLFunction,\n GLBlendEquation,\n GLBlendFunction,\n GLStencilOp,\n GLSamplerParameters,\n GLValueParameters,\n GLPackParameters,\n GLUnpackParameters,\n GLFunctionParameters,\n GLParameters,\n GLLimits,\n GLExtensions,\n GLPolygonMode,\n GLProvokingVertex\n} from './constants/webgl-types';\n\n// WebGL adapter classes\nexport {webgl2Adapter} from './adapter/webgl-adapter';\nexport type {WebGLAdapter} from './adapter/webgl-adapter';\n\n// WebGL Device classes\nexport {WebGLDevice} from './adapter/webgl-device';\nexport {WebGLCanvasContext} from './adapter/webgl-canvas-context';\n\n// WebGL Resource classes\nexport {WEBGLBuffer} from './adapter/resources/webgl-buffer';\nexport {WEBGLTexture} from './adapter/resources/webgl-texture';\n// export {WEBGLExternalTexture} from './adapter/resources/webgl-external-texture';\nexport {WEBGLShader} from './adapter/resources/webgl-shader';\nexport {WEBGLSampler} from './adapter/resources/webgl-sampler';\nexport {WEBGLFramebuffer} from './adapter/resources/webgl-framebuffer';\nexport {WEBGLFence} from './adapter/resources/webgl-fence';\n\nexport {WEBGLRenderPipeline} from './adapter/resources/webgl-render-pipeline';\n// export {WEBGLComputePipeline} from './adapter/resources/webgl-compute-pipeline';\nexport {WEBGLCommandEncoder} from './adapter/resources/webgl-command-encoder';\nexport {WEBGLRenderPass} from './adapter/resources/webgl-render-pass';\n// export {WEBGLComputePass} from './adapter/resources/webgl-compute-pass';\nexport {WEBGLVertexArray} from './adapter/resources/webgl-vertex-array';\n\n// WebGL adapter classes\nexport {WEBGLTransformFeedback} from './adapter/resources/webgl-transform-feedback';\n\n// Unified parameter API\n\nexport {setDeviceParameters, withDeviceParameters} from './adapter/converters/device-parameters';\n\n// HELPERS - EXPERIMENTAL\nexport {getShaderLayoutFromGLSL} from './adapter/helpers/get-shader-layout-from-glsl';\nexport {WebGLStateTracker} from './context/state-tracker/webgl-state-tracker';\n\n// DEPRECATED TEST EXPORTS\nexport {\n resetGLParameters,\n setGLParameters,\n getGLParameters\n} from './context/parameters/unified-parameter-api';\n\nexport {withGLParameters} from './context/state-tracker/with-parameters';\n","// A port of an algorithm by Johannes Baagøe , 2010\n// http://baagoe.com/en/RandomMusings/javascript/\n// https://github.com/nquinlan/better-random-numbers-for-javascript-mirror\n// Original work is under MIT license -\n\n// Copyright (C) 2010 by Johannes Baagøe \n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n\n\n(function(global, module, define) {\n\nfunction Alea(seed) {\n var me = this, mash = Mash();\n\n me.next = function() {\n var t = 2091639 * me.s0 + me.c * 2.3283064365386963e-10; // 2^-32\n me.s0 = me.s1;\n me.s1 = me.s2;\n return me.s2 = t - (me.c = t | 0);\n };\n\n // Apply the seeding algorithm from Baagoe.\n me.c = 1;\n me.s0 = mash(' ');\n me.s1 = mash(' ');\n me.s2 = mash(' ');\n me.s0 -= mash(seed);\n if (me.s0 < 0) { me.s0 += 1; }\n me.s1 -= mash(seed);\n if (me.s1 < 0) { me.s1 += 1; }\n me.s2 -= mash(seed);\n if (me.s2 < 0) { me.s2 += 1; }\n mash = null;\n}\n\nfunction copy(f, t) {\n t.c = f.c;\n t.s0 = f.s0;\n t.s1 = f.s1;\n t.s2 = f.s2;\n return t;\n}\n\nfunction impl(seed, opts) {\n var xg = new Alea(seed),\n state = opts && opts.state,\n prng = xg.next;\n prng.int32 = function() { return (xg.next() * 0x100000000) | 0; }\n prng.double = function() {\n return prng() + (prng() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53\n };\n prng.quick = prng;\n if (state) {\n if (typeof(state) == 'object') copy(state, xg);\n prng.state = function() { return copy(xg, {}); }\n }\n return prng;\n}\n\nfunction Mash() {\n var n = 0xefc8249d;\n\n var mash = function(data) {\n data = String(data);\n for (var i = 0; i < data.length; i++) {\n n += data.charCodeAt(i);\n var h = 0.02519603282416938 * n;\n n = h >>> 0;\n h -= n;\n h *= n;\n n = h >>> 0;\n h -= n;\n n += h * 0x100000000; // 2^32\n }\n return (n >>> 0) * 2.3283064365386963e-10; // 2^-32\n };\n\n return mash;\n}\n\n\nif (module && module.exports) {\n module.exports = impl;\n} else if (define && define.amd) {\n define(function() { return impl; });\n} else {\n this.alea = impl;\n}\n\n})(\n this,\n (typeof module) == 'object' && module, // present in node.js\n (typeof define) == 'function' && define // present with an AMD loader\n);\n\n\n","// A Javascript implementaion of the \"xor128\" prng algorithm by\n// George Marsaglia. See http://www.jstatsoft.org/v08/i14/paper\n\n(function(global, module, define) {\n\nfunction XorGen(seed) {\n var me = this, strseed = '';\n\n me.x = 0;\n me.y = 0;\n me.z = 0;\n me.w = 0;\n\n // Set up generator function.\n me.next = function() {\n var t = me.x ^ (me.x << 11);\n me.x = me.y;\n me.y = me.z;\n me.z = me.w;\n return me.w ^= (me.w >>> 19) ^ t ^ (t >>> 8);\n };\n\n if (seed === (seed | 0)) {\n // Integer seed.\n me.x = seed;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (var k = 0; k < strseed.length + 64; k++) {\n me.x ^= strseed.charCodeAt(k) | 0;\n me.next();\n }\n}\n\nfunction copy(f, t) {\n t.x = f.x;\n t.y = f.y;\n t.z = f.z;\n t.w = f.w;\n return t;\n}\n\nfunction impl(seed, opts) {\n var xg = new XorGen(seed),\n state = opts && opts.state,\n prng = function() { return (xg.next() >>> 0) / 0x100000000; };\n prng.double = function() {\n do {\n var top = xg.next() >>> 11,\n bot = (xg.next() >>> 0) / 0x100000000,\n result = (top + bot) / (1 << 21);\n } while (result === 0);\n return result;\n };\n prng.int32 = xg.next;\n prng.quick = prng;\n if (state) {\n if (typeof(state) == 'object') copy(state, xg);\n prng.state = function() { return copy(xg, {}); }\n }\n return prng;\n}\n\nif (module && module.exports) {\n module.exports = impl;\n} else if (define && define.amd) {\n define(function() { return impl; });\n} else {\n this.xor128 = impl;\n}\n\n})(\n this,\n (typeof module) == 'object' && module, // present in node.js\n (typeof define) == 'function' && define // present with an AMD loader\n);\n\n\n","// A Javascript implementaion of the \"xorwow\" prng algorithm by\n// George Marsaglia. See http://www.jstatsoft.org/v08/i14/paper\n\n(function(global, module, define) {\n\nfunction XorGen(seed) {\n var me = this, strseed = '';\n\n // Set up generator function.\n me.next = function() {\n var t = (me.x ^ (me.x >>> 2));\n me.x = me.y; me.y = me.z; me.z = me.w; me.w = me.v;\n return (me.d = (me.d + 362437 | 0)) +\n (me.v = (me.v ^ (me.v << 4)) ^ (t ^ (t << 1))) | 0;\n };\n\n me.x = 0;\n me.y = 0;\n me.z = 0;\n me.w = 0;\n me.v = 0;\n\n if (seed === (seed | 0)) {\n // Integer seed.\n me.x = seed;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (var k = 0; k < strseed.length + 64; k++) {\n me.x ^= strseed.charCodeAt(k) | 0;\n if (k == strseed.length) {\n me.d = me.x << 10 ^ me.x >>> 4;\n }\n me.next();\n }\n}\n\nfunction copy(f, t) {\n t.x = f.x;\n t.y = f.y;\n t.z = f.z;\n t.w = f.w;\n t.v = f.v;\n t.d = f.d;\n return t;\n}\n\nfunction impl(seed, opts) {\n var xg = new XorGen(seed),\n state = opts && opts.state,\n prng = function() { return (xg.next() >>> 0) / 0x100000000; };\n prng.double = function() {\n do {\n var top = xg.next() >>> 11,\n bot = (xg.next() >>> 0) / 0x100000000,\n result = (top + bot) / (1 << 21);\n } while (result === 0);\n return result;\n };\n prng.int32 = xg.next;\n prng.quick = prng;\n if (state) {\n if (typeof(state) == 'object') copy(state, xg);\n prng.state = function() { return copy(xg, {}); }\n }\n return prng;\n}\n\nif (module && module.exports) {\n module.exports = impl;\n} else if (define && define.amd) {\n define(function() { return impl; });\n} else {\n this.xorwow = impl;\n}\n\n})(\n this,\n (typeof module) == 'object' && module, // present in node.js\n (typeof define) == 'function' && define // present with an AMD loader\n);\n\n\n","// A Javascript implementaion of the \"xorshift7\" algorithm by\n// François Panneton and Pierre L'ecuyer:\n// \"On the Xorgshift Random Number Generators\"\n// http://saluc.engr.uconn.edu/refs/crypto/rng/panneton05onthexorshift.pdf\n\n(function(global, module, define) {\n\nfunction XorGen(seed) {\n var me = this;\n\n // Set up generator function.\n me.next = function() {\n // Update xor generator.\n var X = me.x, i = me.i, t, v, w;\n t = X[i]; t ^= (t >>> 7); v = t ^ (t << 24);\n t = X[(i + 1) & 7]; v ^= t ^ (t >>> 10);\n t = X[(i + 3) & 7]; v ^= t ^ (t >>> 3);\n t = X[(i + 4) & 7]; v ^= t ^ (t << 7);\n t = X[(i + 7) & 7]; t = t ^ (t << 13); v ^= t ^ (t << 9);\n X[i] = v;\n me.i = (i + 1) & 7;\n return v;\n };\n\n function init(me, seed) {\n var j, w, X = [];\n\n if (seed === (seed | 0)) {\n // Seed state array using a 32-bit integer.\n w = X[0] = seed;\n } else {\n // Seed state using a string.\n seed = '' + seed;\n for (j = 0; j < seed.length; ++j) {\n X[j & 7] = (X[j & 7] << 15) ^\n (seed.charCodeAt(j) + X[(j + 1) & 7] << 13);\n }\n }\n // Enforce an array length of 8, not all zeroes.\n while (X.length < 8) X.push(0);\n for (j = 0; j < 8 && X[j] === 0; ++j);\n if (j == 8) w = X[7] = -1; else w = X[j];\n\n me.x = X;\n me.i = 0;\n\n // Discard an initial 256 values.\n for (j = 256; j > 0; --j) {\n me.next();\n }\n }\n\n init(me, seed);\n}\n\nfunction copy(f, t) {\n t.x = f.x.slice();\n t.i = f.i;\n return t;\n}\n\nfunction impl(seed, opts) {\n if (seed == null) seed = +(new Date);\n var xg = new XorGen(seed),\n state = opts && opts.state,\n prng = function() { return (xg.next() >>> 0) / 0x100000000; };\n prng.double = function() {\n do {\n var top = xg.next() >>> 11,\n bot = (xg.next() >>> 0) / 0x100000000,\n result = (top + bot) / (1 << 21);\n } while (result === 0);\n return result;\n };\n prng.int32 = xg.next;\n prng.quick = prng;\n if (state) {\n if (state.x) copy(state, xg);\n prng.state = function() { return copy(xg, {}); }\n }\n return prng;\n}\n\nif (module && module.exports) {\n module.exports = impl;\n} else if (define && define.amd) {\n define(function() { return impl; });\n} else {\n this.xorshift7 = impl;\n}\n\n})(\n this,\n (typeof module) == 'object' && module, // present in node.js\n (typeof define) == 'function' && define // present with an AMD loader\n);\n\n","// A Javascript implementaion of Richard Brent's Xorgens xor4096 algorithm.\n//\n// This fast non-cryptographic random number generator is designed for\n// use in Monte-Carlo algorithms. It combines a long-period xorshift\n// generator with a Weyl generator, and it passes all common batteries\n// of stasticial tests for randomness while consuming only a few nanoseconds\n// for each prng generated. For background on the generator, see Brent's\n// paper: \"Some long-period random number generators using shifts and xors.\"\n// http://arxiv.org/pdf/1004.3115v1.pdf\n//\n// Usage:\n//\n// var xor4096 = require('xor4096');\n// random = xor4096(1); // Seed with int32 or string.\n// assert.equal(random(), 0.1520436450538547); // (0, 1) range, 53 bits.\n// assert.equal(random.int32(), 1806534897); // signed int32, 32 bits.\n//\n// For nonzero numeric keys, this impelementation provides a sequence\n// identical to that by Brent's xorgens 3 implementaion in C. This\n// implementation also provides for initalizing the generator with\n// string seeds, or for saving and restoring the state of the generator.\n//\n// On Chrome, this prng benchmarks about 2.1 times slower than\n// Javascript's built-in Math.random().\n\n(function(global, module, define) {\n\nfunction XorGen(seed) {\n var me = this;\n\n // Set up generator function.\n me.next = function() {\n var w = me.w,\n X = me.X, i = me.i, t, v;\n // Update Weyl generator.\n me.w = w = (w + 0x61c88647) | 0;\n // Update xor generator.\n v = X[(i + 34) & 127];\n t = X[i = ((i + 1) & 127)];\n v ^= v << 13;\n t ^= t << 17;\n v ^= v >>> 15;\n t ^= t >>> 12;\n // Update Xor generator array state.\n v = X[i] = v ^ t;\n me.i = i;\n // Result is the combination.\n return (v + (w ^ (w >>> 16))) | 0;\n };\n\n function init(me, seed) {\n var t, v, i, j, w, X = [], limit = 128;\n if (seed === (seed | 0)) {\n // Numeric seeds initialize v, which is used to generates X.\n v = seed;\n seed = null;\n } else {\n // String seeds are mixed into v and X one character at a time.\n seed = seed + '\\0';\n v = 0;\n limit = Math.max(limit, seed.length);\n }\n // Initialize circular array and weyl value.\n for (i = 0, j = -32; j < limit; ++j) {\n // Put the unicode characters into the array, and shuffle them.\n if (seed) v ^= seed.charCodeAt((j + 32) % seed.length);\n // After 32 shuffles, take v as the starting w value.\n if (j === 0) w = v;\n v ^= v << 10;\n v ^= v >>> 15;\n v ^= v << 4;\n v ^= v >>> 13;\n if (j >= 0) {\n w = (w + 0x61c88647) | 0; // Weyl.\n t = (X[j & 127] ^= (v + w)); // Combine xor and weyl to init array.\n i = (0 == t) ? i + 1 : 0; // Count zeroes.\n }\n }\n // We have detected all zeroes; make the key nonzero.\n if (i >= 128) {\n X[(seed && seed.length || 0) & 127] = -1;\n }\n // Run the generator 512 times to further mix the state before using it.\n // Factoring this as a function slows the main generator, so it is just\n // unrolled here. The weyl generator is not advanced while warming up.\n i = 127;\n for (j = 4 * 128; j > 0; --j) {\n v = X[(i + 34) & 127];\n t = X[i = ((i + 1) & 127)];\n v ^= v << 13;\n t ^= t << 17;\n v ^= v >>> 15;\n t ^= t >>> 12;\n X[i] = v ^ t;\n }\n // Storing state as object members is faster than using closure variables.\n me.w = w;\n me.X = X;\n me.i = i;\n }\n\n init(me, seed);\n}\n\nfunction copy(f, t) {\n t.i = f.i;\n t.w = f.w;\n t.X = f.X.slice();\n return t;\n};\n\nfunction impl(seed, opts) {\n if (seed == null) seed = +(new Date);\n var xg = new XorGen(seed),\n state = opts && opts.state,\n prng = function() { return (xg.next() >>> 0) / 0x100000000; };\n prng.double = function() {\n do {\n var top = xg.next() >>> 11,\n bot = (xg.next() >>> 0) / 0x100000000,\n result = (top + bot) / (1 << 21);\n } while (result === 0);\n return result;\n };\n prng.int32 = xg.next;\n prng.quick = prng;\n if (state) {\n if (state.X) copy(state, xg);\n prng.state = function() { return copy(xg, {}); }\n }\n return prng;\n}\n\nif (module && module.exports) {\n module.exports = impl;\n} else if (define && define.amd) {\n define(function() { return impl; });\n} else {\n this.xor4096 = impl;\n}\n\n})(\n this, // window object or global\n (typeof module) == 'object' && module, // present in node.js\n (typeof define) == 'function' && define // present with an AMD loader\n);\n","// A Javascript implementaion of the \"Tyche-i\" prng algorithm by\n// Samuel Neves and Filipe Araujo.\n// See https://eden.dei.uc.pt/~sneves/pubs/2011-snfa2.pdf\n\n(function(global, module, define) {\n\nfunction XorGen(seed) {\n var me = this, strseed = '';\n\n // Set up generator function.\n me.next = function() {\n var b = me.b, c = me.c, d = me.d, a = me.a;\n b = (b << 25) ^ (b >>> 7) ^ c;\n c = (c - d) | 0;\n d = (d << 24) ^ (d >>> 8) ^ a;\n a = (a - b) | 0;\n me.b = b = (b << 20) ^ (b >>> 12) ^ c;\n me.c = c = (c - d) | 0;\n me.d = (d << 16) ^ (c >>> 16) ^ a;\n return me.a = (a - b) | 0;\n };\n\n /* The following is non-inverted tyche, which has better internal\n * bit diffusion, but which is about 25% slower than tyche-i in JS.\n me.next = function() {\n var a = me.a, b = me.b, c = me.c, d = me.d;\n a = (me.a + me.b | 0) >>> 0;\n d = me.d ^ a; d = d << 16 ^ d >>> 16;\n c = me.c + d | 0;\n b = me.b ^ c; b = b << 12 ^ d >>> 20;\n me.a = a = a + b | 0;\n d = d ^ a; me.d = d = d << 8 ^ d >>> 24;\n me.c = c = c + d | 0;\n b = b ^ c;\n return me.b = (b << 7 ^ b >>> 25);\n }\n */\n\n me.a = 0;\n me.b = 0;\n me.c = 2654435769 | 0;\n me.d = 1367130551;\n\n if (seed === Math.floor(seed)) {\n // Integer seed.\n me.a = (seed / 0x100000000) | 0;\n me.b = seed | 0;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (var k = 0; k < strseed.length + 20; k++) {\n me.b ^= strseed.charCodeAt(k) | 0;\n me.next();\n }\n}\n\nfunction copy(f, t) {\n t.a = f.a;\n t.b = f.b;\n t.c = f.c;\n t.d = f.d;\n return t;\n};\n\nfunction impl(seed, opts) {\n var xg = new XorGen(seed),\n state = opts && opts.state,\n prng = function() { return (xg.next() >>> 0) / 0x100000000; };\n prng.double = function() {\n do {\n var top = xg.next() >>> 11,\n bot = (xg.next() >>> 0) / 0x100000000,\n result = (top + bot) / (1 << 21);\n } while (result === 0);\n return result;\n };\n prng.int32 = xg.next;\n prng.quick = prng;\n if (state) {\n if (typeof(state) == 'object') copy(state, xg);\n prng.state = function() { return copy(xg, {}); }\n }\n return prng;\n}\n\nif (module && module.exports) {\n module.exports = impl;\n} else if (define && define.amd) {\n define(function() { return impl; });\n} else {\n this.tychei = impl;\n}\n\n})(\n this,\n (typeof module) == 'object' && module, // present in node.js\n (typeof define) == 'function' && define // present with an AMD loader\n);\n\n\n","/*\nCopyright 2019 David Bau.\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n*/\n\n(function (global, pool, math) {\n//\n// The following constants are related to IEEE 754 limits.\n//\n\nvar width = 256, // each RC4 output is 0 <= x < 256\n chunks = 6, // at least six RC4 outputs for each double\n digits = 52, // there are 52 significant digits in a double\n rngname = 'random', // rngname: name for Math.random and Math.seedrandom\n startdenom = math.pow(width, chunks),\n significance = math.pow(2, digits),\n overflow = significance * 2,\n mask = width - 1,\n nodecrypto; // node.js crypto module, initialized at the bottom.\n\n//\n// seedrandom()\n// This is the seedrandom function described above.\n//\nfunction seedrandom(seed, options, callback) {\n var key = [];\n options = (options == true) ? { entropy: true } : (options || {});\n\n // Flatten the seed string or build one from local entropy if needed.\n var shortseed = mixkey(flatten(\n options.entropy ? [seed, tostring(pool)] :\n (seed == null) ? autoseed() : seed, 3), key);\n\n // Use the seed to initialize an ARC4 generator.\n var arc4 = new ARC4(key);\n\n // This function returns a random double in [0, 1) that contains\n // randomness in every bit of the mantissa of the IEEE 754 value.\n var prng = function() {\n var n = arc4.g(chunks), // Start with a numerator n < 2 ^ 48\n d = startdenom, // and denominator d = 2 ^ 48.\n x = 0; // and no 'extra last byte'.\n while (n < significance) { // Fill up all significant digits by\n n = (n + x) * width; // shifting numerator and\n d *= width; // denominator and generating a\n x = arc4.g(1); // new least-significant-byte.\n }\n while (n >= overflow) { // To avoid rounding up, before adding\n n /= 2; // last byte, shift everything\n d /= 2; // right using integer math until\n x >>>= 1; // we have exactly the desired bits.\n }\n return (n + x) / d; // Form the number within [0, 1).\n };\n\n prng.int32 = function() { return arc4.g(4) | 0; }\n prng.quick = function() { return arc4.g(4) / 0x100000000; }\n prng.double = prng;\n\n // Mix the randomness into accumulated entropy.\n mixkey(tostring(arc4.S), pool);\n\n // Calling convention: what to return as a function of prng, seed, is_math.\n return (options.pass || callback ||\n function(prng, seed, is_math_call, state) {\n if (state) {\n // Load the arc4 state from the given state if it has an S array.\n if (state.S) { copy(state, arc4); }\n // Only provide the .state method if requested via options.state.\n prng.state = function() { return copy(arc4, {}); }\n }\n\n // If called as a method of Math (Math.seedrandom()), mutate\n // Math.random because that is how seedrandom.js has worked since v1.0.\n if (is_math_call) { math[rngname] = prng; return seed; }\n\n // Otherwise, it is a newer calling convention, so return the\n // prng directly.\n else return prng;\n })(\n prng,\n shortseed,\n 'global' in options ? options.global : (this == math),\n options.state);\n}\n\n//\n// ARC4\n//\n// An ARC4 implementation. The constructor takes a key in the form of\n// an array of at most (width) integers that should be 0 <= x < (width).\n//\n// The g(count) method returns a pseudorandom integer that concatenates\n// the next (count) outputs from ARC4. Its return value is a number x\n// that is in the range 0 <= x < (width ^ count).\n//\nfunction ARC4(key) {\n var t, keylen = key.length,\n me = this, i = 0, j = me.i = me.j = 0, s = me.S = [];\n\n // The empty key [] is treated as [0].\n if (!keylen) { key = [keylen++]; }\n\n // Set up S using the standard key scheduling algorithm.\n while (i < width) {\n s[i] = i++;\n }\n for (i = 0; i < width; i++) {\n s[i] = s[j = mask & (j + key[i % keylen] + (t = s[i]))];\n s[j] = t;\n }\n\n // The \"g\" method returns the next (count) outputs as one number.\n (me.g = function(count) {\n // Using instance members instead of closure state nearly doubles speed.\n var t, r = 0,\n i = me.i, j = me.j, s = me.S;\n while (count--) {\n t = s[i = mask & (i + 1)];\n r = r * width + s[mask & ((s[i] = s[j = mask & (j + t)]) + (s[j] = t))];\n }\n me.i = i; me.j = j;\n return r;\n // For robust unpredictability, the function call below automatically\n // discards an initial batch of values. This is called RC4-drop[256].\n // See http://google.com/search?q=rsa+fluhrer+response&btnI\n })(width);\n}\n\n//\n// copy()\n// Copies internal state of ARC4 to or from a plain object.\n//\nfunction copy(f, t) {\n t.i = f.i;\n t.j = f.j;\n t.S = f.S.slice();\n return t;\n};\n\n//\n// flatten()\n// Converts an object tree to nested arrays of strings.\n//\nfunction flatten(obj, depth) {\n var result = [], typ = (typeof obj), prop;\n if (depth && typ == 'object') {\n for (prop in obj) {\n try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {}\n }\n }\n return (result.length ? result : typ == 'string' ? obj : obj + '\\0');\n}\n\n//\n// mixkey()\n// Mixes a string seed into a key that is an array of integers, and\n// returns a shortened string seed that is equivalent to the result key.\n//\nfunction mixkey(seed, key) {\n var stringseed = seed + '', smear, j = 0;\n while (j < stringseed.length) {\n key[mask & j] =\n mask & ((smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++));\n }\n return tostring(key);\n}\n\n//\n// autoseed()\n// Returns an object for autoseeding, using window.crypto and Node crypto\n// module if available.\n//\nfunction autoseed() {\n try {\n var out;\n if (nodecrypto && (out = nodecrypto.randomBytes)) {\n // The use of 'out' to remember randomBytes makes tight minified code.\n out = out(width);\n } else {\n out = new Uint8Array(width);\n (global.crypto || global.msCrypto).getRandomValues(out);\n }\n return tostring(out);\n } catch (e) {\n var browser = global.navigator,\n plugins = browser && browser.plugins;\n return [+new Date, global, plugins, global.screen, tostring(pool)];\n }\n}\n\n//\n// tostring()\n// Converts an array of charcodes to a string\n//\nfunction tostring(a) {\n return String.fromCharCode.apply(0, a);\n}\n\n//\n// When seedrandom.js is loaded, we immediately mix a few bits\n// from the built-in RNG into the entropy pool. Because we do\n// not want to interfere with deterministic PRNG state later,\n// seedrandom will not call math.random on its own again after\n// initialization.\n//\nmixkey(math.random(), pool);\n\n//\n// Nodejs and AMD support: export the implementation as a module using\n// either convention.\n//\nif ((typeof module) == 'object' && module.exports) {\n module.exports = seedrandom;\n // When in node.js, try using crypto package for autoseeding.\n try {\n nodecrypto = require('crypto');\n } catch (ex) {}\n} else if ((typeof define) == 'function' && define.amd) {\n define(function() { return seedrandom; });\n} else {\n // When included as a plain script, set up Math.seedrandom global.\n math['seed' + rngname] = seedrandom;\n}\n\n\n// End anonymous scope, and pass initial values.\n})(\n // global: `self` in browsers (including strict mode and web workers),\n // otherwise `this` in Node and other environments\n (typeof self !== 'undefined') ? self : this,\n [], // pool: entropy pool starts empty\n Math // math: package containing random, pow, and seedrandom\n);\n","// A library of seedable RNGs implemented in Javascript.\n//\n// Usage:\n//\n// var seedrandom = require('seedrandom');\n// var random = seedrandom(1); // or any seed.\n// var x = random(); // 0 <= x < 1. Every bit is random.\n// var x = random.quick(); // 0 <= x < 1. 32 bits of randomness.\n\n// alea, a 53-bit multiply-with-carry generator by Johannes Baagøe.\n// Period: ~2^116\n// Reported to pass all BigCrush tests.\nvar alea = require('./lib/alea');\n\n// xor128, a pure xor-shift generator by George Marsaglia.\n// Period: 2^128-1.\n// Reported to fail: MatrixRank and LinearComp.\nvar xor128 = require('./lib/xor128');\n\n// xorwow, George Marsaglia's 160-bit xor-shift combined plus weyl.\n// Period: 2^192-2^32\n// Reported to fail: CollisionOver, SimpPoker, and LinearComp.\nvar xorwow = require('./lib/xorwow');\n\n// xorshift7, by François Panneton and Pierre L'ecuyer, takes\n// a different approach: it adds robustness by allowing more shifts\n// than Marsaglia's original three. It is a 7-shift generator\n// with 256 bits, that passes BigCrush with no systmatic failures.\n// Period 2^256-1.\n// No systematic BigCrush failures reported.\nvar xorshift7 = require('./lib/xorshift7');\n\n// xor4096, by Richard Brent, is a 4096-bit xor-shift with a\n// very long period that also adds a Weyl generator. It also passes\n// BigCrush with no systematic failures. Its long period may\n// be useful if you have many generators and need to avoid\n// collisions.\n// Period: 2^4128-2^32.\n// No systematic BigCrush failures reported.\nvar xor4096 = require('./lib/xor4096');\n\n// Tyche-i, by Samuel Neves and Filipe Araujo, is a bit-shifting random\n// number generator derived from ChaCha, a modern stream cipher.\n// https://eden.dei.uc.pt/~sneves/pubs/2011-snfa2.pdf\n// Period: ~2^127\n// No systematic BigCrush failures reported.\nvar tychei = require('./lib/tychei');\n\n// The original ARC4-based prng included in this library.\n// Period: ~2^1600\nvar sr = require('./seedrandom');\n\nsr.alea = alea;\nsr.xor128 = xor128;\nsr.xorwow = xorwow;\nsr.xorshift7 = xorshift7;\nsr.xor4096 = xor4096;\nsr.tychei = tychei;\n\nmodule.exports = sr;\n","/**\n * Throws an `Error` with the optional `message` if `condition` is falsy\n * @note Replacement for the external assert method to reduce bundle size\n */\nexport function assert(condition: any, message?: string): void {\n if (!condition) {\n throw new Error(message || 'loader assertion failed.');\n }\n}\n","// Purpose: include this in your module to avoid\n// dependencies on micro modules like 'global' and 'is-browser';\n\n/* eslint-disable no-restricted-globals */\nconst globals = {\n self: typeof self !== 'undefined' && self,\n window: typeof window !== 'undefined' && window,\n global: typeof global !== 'undefined' && global,\n document: typeof document !== 'undefined' && document\n};\n\ntype obj = {[key: string]: any};\nconst self_: obj = globals.self || globals.window || globals.global || {};\nconst window_: obj = globals.window || globals.self || globals.global || {};\nconst global_: obj = globals.global || globals.self || globals.window || {};\nconst document_: obj = globals.document || {};\n\nexport {self_ as self, window_ as window, global_ as global, document_ as document};\n\n/** true if running in a browser */\nexport const isBrowser: boolean =\n // @ts-ignore process does not exist on browser\n Boolean(typeof process !== 'object' || String(process) !== '[object process]' || process.browser);\n\n/** true if running in a worker thread */\nexport const isWorker: boolean = typeof importScripts === 'function';\n\n// Extract node major version\nconst matches =\n typeof process !== 'undefined' && process.version && /v([0-9]*)/.exec(process.version);\n/** Major Node version (as a number) */\nexport const nodeVersion: number = (matches && parseFloat(matches[1])) || 0;\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Log} from '@probe.gl/log';\n\n// Version constant cannot be imported, it needs to correspond to the build version of **this** module.\n// __VERSION__ is injected by babel-plugin-version-inline\n// @ts-ignore TS2304: Cannot find name '__VERSION__'.\nexport const VERSION = typeof __VERSION__ !== 'undefined' ? __VERSION__ : 'latest';\n\nconst version = VERSION[0] >= '0' && VERSION[0] <= '9' ? `v${VERSION}` : '';\n\n// Make sure we set the global variable\nfunction createLog() {\n const log = new Log({id: 'loaders.gl'});\n\n globalThis.loaders ||= {};\n globalThis.loaders.log = log;\n globalThis.loaders.version = version;\n\n globalThis.probe ||= {};\n globalThis.probe.loaders = log;\n\n return log;\n}\n\nexport const log = createLog();\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/* eslint-disable @typescript-eslint/unbound-method */\n\nimport type {Readable} from 'stream';\n\n/** Minimal shape for Node.js Buffer-like values */\ntype NodeBufferLike = {buffer: ArrayBufferLike; isBuffer: true};\n\n/** Minimal shape for Node.js writable streams */\ntype NodeWritableStream = {\n end: (...args: unknown[]) => unknown;\n write: (...args: unknown[]) => unknown;\n writable: boolean;\n};\n\n/** Minimal shape for WritableStream-like DOM implementations */\ntype WritableDOMStreamLike = WritableStream | {abort: () => unknown; getWriter: () => unknown};\n\n/** A DOM or Node readable stream */\nexport type ReadableStreamType = ReadableStream | Readable;\n\n/** Checks whether a value is a boolean */\nconst isBoolean = (value: unknown): value is boolean => typeof value === 'boolean';\n\n/** Checks whether a value is a function */\nconst isFunction = (value: unknown): value is (...args: unknown[]) => unknown =>\n typeof value === 'function';\n\n/** Checks whether a value is a non-null object */\nexport const isObject = (value: unknown): value is object =>\n value !== null && typeof value === 'object';\n\n/** Checks whether a value is a plain object (created by the Object constructor) */\nexport const isPureObject = (value: unknown): value is Record =>\n isObject(value) && value.constructor === {}.constructor;\n\n/** Checks whether a value is an ArrayBuffer */\nexport const isArrayBuffer = (value: unknown): value is ArrayBuffer =>\n typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer;\n\n/** Checks whether a value is an ArrayBuffer */\nexport const isSharedArrayBuffer = (value: unknown): value is SharedArrayBuffer =>\n typeof SharedArrayBuffer !== 'undefined' && value instanceof SharedArrayBuffer;\n\n/** Checks whether a value is ArrayBuffer-like */\nexport const isArrayBufferLike = (value: unknown): value is ArrayBufferLike =>\n isObject(value) &&\n typeof (value as ArrayBufferLike).byteLength === 'number' &&\n typeof (value as ArrayBufferLike).slice === 'function';\n\n/** Checks whether a value behaves like a promise */\nexport const isPromise = (value: unknown): value is Promise =>\n isObject(value) && 'then' in value && isFunction((value as {then: unknown}).then);\n\n/** Checks whether a value implements the iterable protocol */\nexport const isIterable = (value: unknown): value is Iterable =>\n Boolean(value) && isFunction((value as Iterable)[Symbol.iterator]);\n\n/** Checks whether a value implements the async iterable protocol */\nexport const isAsyncIterable = (value: unknown): value is AsyncIterable =>\n Boolean(value) && isFunction((value as AsyncIterable)[Symbol.asyncIterator]);\n\n/** Checks whether a value is an iterator (has a next function) */\nexport const isIterator = (value: unknown): value is Iterator =>\n Boolean(value) && isFunction((value as Iterator).next);\n\n/** Checks whether a value is a fetch Response or a duck-typed equivalent */\nexport const isResponse = (value: unknown): value is Response =>\n (typeof Response !== 'undefined' && value instanceof Response) ||\n (isObject(value) &&\n isFunction((value as {arrayBuffer?: unknown}).arrayBuffer) &&\n isFunction((value as {text?: unknown}).text) &&\n isFunction((value as {json?: unknown}).json));\n\n/** Checks whether a value is a File */\nexport const isFile = (value: unknown): value is File =>\n typeof File !== 'undefined' && value instanceof File;\n\n/** Checks whether a value is a Blob */\nexport const isBlob = (value: unknown): value is Blob =>\n typeof Blob !== 'undefined' && value instanceof Blob;\n\n/** Checks for Node.js Buffers without triggering bundlers to include the Buffer polyfill */\nexport const isBuffer = (value: unknown): value is NodeBufferLike =>\n Boolean(\n value &&\n typeof value === 'object' &&\n (value as Partial).isBuffer &&\n 'buffer' in (value as NodeBufferLike)\n );\n\n/** Checks whether a value looks like a DOM WritableStream */\nexport const isWritableDOMStream = (value: unknown): value is WritableDOMStreamLike =>\n isObject(value) &&\n isFunction((value as WritableDOMStreamLike).abort) &&\n isFunction((value as WritableDOMStreamLike).getWriter);\n\n/** Checks whether a value looks like a DOM ReadableStream */\nexport const isReadableDOMStream = (value: unknown): value is ReadableStream =>\n (typeof ReadableStream !== 'undefined' && value instanceof ReadableStream) ||\n (isObject(value) &&\n isFunction((value as ReadableStream).tee) &&\n isFunction((value as ReadableStream).cancel) &&\n isFunction((value as ReadableStream).getReader));\n// Not implemented in Firefox: && isFunction(x.pipeTo)\n\n/** Checks whether a value looks like a Node.js writable stream */\nexport const isWritableNodeStream = (value: unknown): value is NodeWritableStream =>\n isObject(value) &&\n isFunction((value as NodeWritableStream).end) &&\n isFunction((value as NodeWritableStream).write) &&\n isBoolean((value as NodeWritableStream).writable);\n\n/** Checks whether a value looks like a Node.js readable stream */\nexport const isReadableNodeStream = (value: unknown): value is Readable =>\n isObject(value) &&\n isFunction((value as Readable).read) &&\n isFunction((value as Readable).pipe) &&\n isBoolean((value as Readable).readable);\n\n/** Checks whether a value is any readable stream (DOM or Node.js) */\nexport const isReadableStream = (value: unknown): value is ReadableStreamType =>\n isReadableDOMStream(value) || isReadableNodeStream(value);\n\n/** Checks whether a value is any writable stream (DOM or Node.js) */\nexport const isWritableStream = (value: unknown): value is WritableStream | NodeWritableStream =>\n isWritableDOMStream(value) || isWritableNodeStream(value);\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport type RequiredOptions = Required<{[K in keyof T]: Required}>;\n\nexport function getRequiredOptions(options: T): RequiredOptions {\n return options as RequiredOptions;\n}\n\n/**\n *\n * @param baseOptions Can be undefined, in which case a fresh options object will be minted\n * @param newOptions\n * @returns\n */\nexport function mergeOptions>(\n baseOptions: OptionsT | undefined,\n newOptions: OptionsT\n): OptionsT {\n return mergeOptionsRecursively(baseOptions || {}, newOptions) as OptionsT;\n}\n\nfunction mergeOptionsRecursively(\n baseOptions: Record,\n newOptions: Record,\n level = 0\n): Record {\n // Sanity check (jest test runner overwrites the console object which can lead to infinite recursion)\n if (level > 3) {\n return newOptions;\n }\n\n const options = {...baseOptions};\n for (const [key, newValue] of Object.entries(newOptions)) {\n if (newValue && typeof newValue === 'object' && !Array.isArray(newValue)) {\n options[key] = mergeOptionsRecursively(\n (options[key] as Record) || {},\n newOptions[key] as Record,\n level + 1\n );\n // Object.assign(options[key] as object, newOptions[key]);\n } else {\n options[key] = newOptions[key];\n }\n }\n return options as Record;\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/**\n * NPM tag to use when loading modules from unpkg.com\n * 'beta' on beta branch, 'latest' on prod branch\n * @note Change between 'beta' and 'latest' depending on whether publishing alpha or prod releases\n * @todo - unpkg.com doesn't seem to have a `latest` specifier for alpha releases...\n */\nexport const NPM_TAG = 'latest';\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {NPM_TAG} from '../npm-tag';\n\n// Version constant cannot be imported, it needs to correspond to the build version of **this** module.\ndeclare let __VERSION__: string;\n\nlet warningIssued = false;\n\nfunction getVersion() {\n if (!globalThis._loadersgl_?.version) {\n globalThis._loadersgl_ = globalThis._loadersgl_ || {};\n // __VERSION__ is injected by babel-plugin-version-inline\n if (typeof __VERSION__ === 'undefined' && !warningIssued) {\n // eslint-disable-next-line\n console.warn(\n 'loaders.gl: The __VERSION__ variable is not injected using babel plugin. Latest unstable workers would be fetched from the CDN.'\n );\n globalThis._loadersgl_.version = NPM_TAG;\n warningIssued = true;\n } else {\n globalThis._loadersgl_.version = __VERSION__;\n }\n }\n\n return globalThis._loadersgl_.version;\n}\n\nexport const VERSION = getVersion();\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// Replacement for the external assert method to reduce bundle size\n// Note: We don't use the second \"message\" argument in calling code,\n// so no need to support it here\n\n/** Throws an `Error` with the optional `message` if `condition` is falsy */\nexport function assert(condition: any, message?: string): void {\n if (!condition) {\n throw new Error(message || 'loaders.gl assertion failed.');\n }\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// Purpose: include this in your module to avoids adding dependencies on\n// micro modules like 'global' and 'is-browser';\n\n/* eslint-disable no-restricted-globals */\nconst globals = {\n self: typeof self !== 'undefined' && self,\n window: typeof window !== 'undefined' && window,\n global: typeof global !== 'undefined' && global,\n document: typeof document !== 'undefined' && document\n};\n\nconst self_: {[key: string]: any} = globals.self || globals.window || globals.global || {};\nconst window_: {[key: string]: any} = globals.window || globals.self || globals.global || {};\nconst global_: {[key: string]: any} = globals.global || globals.self || globals.window || {};\nconst document_: {[key: string]: any} = globals.document || {};\n\nexport {self_ as self, window_ as window, global_ as global, document_ as document};\n\n/** true if running in the browser, false if running in Node.js */\nexport const isBrowser: boolean =\n // @ts-ignore process.browser\n typeof process !== 'object' || String(process) !== '[object process]' || process.browser;\n\n/** true if running on a worker thread */\nexport const isWorker: boolean = typeof importScripts === 'function';\n\n/** true if running on a mobile device */\nexport const isMobile: boolean =\n typeof window !== 'undefined' && typeof window.orientation !== 'undefined';\n\n// Extract node major version\nconst matches =\n typeof process !== 'undefined' && process.version && /v([0-9]*)/.exec(process.version);\n\n/** Version of Node.js if running under Node, otherwise 0 */\nexport const nodeVersion: number = (matches && parseFloat(matches[1])) || 0;\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {WorkerMessageType, WorkerMessagePayload} from '../../types';\nimport WorkerThread from './worker-thread';\nimport {assert} from '../env-utils/assert';\n\n/**\n * Represents one Job handled by a WorkerPool or WorkerFarm\n */\nexport default class WorkerJob {\n readonly name: string;\n readonly workerThread: WorkerThread;\n isRunning: boolean = true;\n /** Promise that resolves when Job is done */\n readonly result: Promise;\n\n private _resolve: (value: any) => void = () => {};\n private _reject: (reason?: any) => void = () => {};\n\n constructor(jobName: string, workerThread: WorkerThread) {\n this.name = jobName;\n this.workerThread = workerThread;\n this.result = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n\n /**\n * Send a message to the job's worker thread\n * @param data any data structure, ideally consisting mostly of transferrable objects\n */\n postMessage(type: WorkerMessageType, payload: WorkerMessagePayload): void {\n this.workerThread.postMessage({\n source: 'loaders.gl', // Lets worker ignore unrelated messages\n type,\n payload\n });\n }\n\n /**\n * Call to resolve the `result` Promise with the supplied value\n */\n done(value: any): void {\n assert(this.isRunning);\n this.isRunning = false;\n this._resolve(value);\n }\n\n /**\n * Call to reject the `result` Promise with the supplied error\n */\n error(error: Error): void {\n assert(this.isRunning);\n this.isRunning = false;\n this._reject(error);\n }\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/** Browser polyfill for Node.js built-in `worker_threads` module.\n * These fills are non-functional, and just intended to ensure that\n * `import 'worker_threads` doesn't break browser builds.\n * The replacement is done in package.json browser field\n */\nexport class NodeWorker {\n terminate() {}\n}\n\nexport type {NodeWorker as NodeWorkerType};\n\nexport const parentPort = null;\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {assert} from '../env-utils/assert';\n\nconst workerURLCache = new Map();\n\n/**\n * Creates a loadable URL from worker source or URL\n * that can be used to create `Worker` instances.\n * Due to CORS issues it may be necessary to wrap a URL in a small importScripts\n * @param props\n * @param props.source Worker source\n * @param props.url Worker URL\n * @returns loadable url\n */\nexport function getLoadableWorkerURL(props: {source?: string; url?: string}) {\n assert((props.source && !props.url) || (!props.source && props.url)); // Either source or url must be defined\n\n let workerURL = workerURLCache.get(props.source || props.url);\n if (!workerURL) {\n // Differentiate worker urls from worker source code\n if (props.url) {\n workerURL = getLoadableWorkerURLFromURL(props.url);\n workerURLCache.set(props.url, workerURL);\n }\n\n if (props.source) {\n workerURL = getLoadableWorkerURLFromSource(props.source);\n workerURLCache.set(props.source, workerURL);\n }\n }\n\n assert(workerURL);\n return workerURL;\n}\n\n/**\n * Build a loadable worker URL from worker URL\n * @param url\n * @returns loadable URL\n */\nfunction getLoadableWorkerURLFromURL(url: string): string {\n // A local script url, we can use it to initialize a Worker directly\n if (!url.startsWith('http')) {\n return url;\n }\n\n // A remote script, we need to use `importScripts` to load from different origin\n const workerSource = buildScriptSource(url);\n return getLoadableWorkerURLFromSource(workerSource);\n}\n\n/**\n * Build a loadable worker URL from worker source\n * @param workerSource\n * @returns loadable url\n */\nfunction getLoadableWorkerURLFromSource(workerSource: string): string {\n const blob = new Blob([workerSource], {type: 'application/javascript'});\n return URL.createObjectURL(blob);\n}\n\n/**\n * Per spec, worker cannot be initialized with a script from a different origin\n * However a local worker script can still import scripts from other origins,\n * so we simply build a wrapper script.\n *\n * @param workerUrl\n * @returns source\n */\nfunction buildScriptSource(workerUrl: string): string {\n return `\\\ntry {\n importScripts('${workerUrl}');\n} catch (error) {\n console.error(error);\n throw error;\n}`;\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// NOTE - there is a copy of this function is both in core and loader-utils\n// core does not need all the utils in loader-utils, just this one.\n\n/**\n * Returns an array of Transferrable objects that can be used with postMessage\n * https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage\n * @param object data to be sent via postMessage\n * @param recursive - not for application use\n * @param transfers - not for application use\n * @returns a transfer list that can be passed to postMessage\n */\nexport function getTransferList(\n object: any,\n recursive: boolean = true,\n transfers?: Set\n): Transferable[] {\n // Make sure that items in the transfer list is unique\n const transfersSet = transfers || new Set();\n\n if (!object) {\n // ignore\n } else if (isTransferable(object)) {\n transfersSet.add(object);\n } else if (isTransferable(object.buffer)) {\n // Typed array\n transfersSet.add(object.buffer);\n } else if (ArrayBuffer.isView(object)) {\n // object is a TypeArray viewing into a SharedArrayBuffer (not transferable)\n // Do not iterate through the content in this case\n } else if (recursive && typeof object === 'object') {\n for (const key in object) {\n // Avoid perf hit - only go one level deep\n getTransferList(object[key], recursive, transfersSet);\n }\n }\n\n // If transfers is defined, is internal recursive call\n // Otherwise it's called by the user\n return transfers === undefined ? Array.from(transfersSet) : [];\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/API/Transferable\nfunction isTransferable(object: unknown) {\n if (!object) {\n return false;\n }\n if (object instanceof ArrayBuffer) {\n return true;\n }\n if (typeof MessagePort !== 'undefined' && object instanceof MessagePort) {\n return true;\n }\n if (typeof ImageBitmap !== 'undefined' && object instanceof ImageBitmap) {\n return true;\n }\n // @ts-ignore\n if (typeof OffscreenCanvas !== 'undefined' && object instanceof OffscreenCanvas) {\n return true;\n }\n return false;\n}\n\n/**\n * Recursively drop non serializable values like functions and regexps.\n * @param object\n */\nexport function getTransferListForWriter(object: object | null): object {\n if (object === null) {\n return {};\n }\n const clone = Object.assign({}, object);\n\n Object.keys(clone).forEach((key) => {\n // Typed Arrays and Arrays are passed with no change\n if (\n typeof object[key] === 'object' &&\n !ArrayBuffer.isView(object[key]) &&\n !(object[key] instanceof Array)\n ) {\n clone[key] = getTransferListForWriter(object[key]);\n } else if (typeof clone[key] === 'function' || clone[key] instanceof RegExp) {\n clone[key] = {};\n } else {\n clone[key] = object[key];\n }\n });\n\n return clone;\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {NodeWorker, NodeWorkerType} from '../node/worker_threads';\nimport {isBrowser} from '../env-utils/globals';\nimport {assert} from '../env-utils/assert';\nimport {getLoadableWorkerURL} from '../worker-utils/get-loadable-worker-url';\nimport {getTransferList} from '../worker-utils/get-transfer-list';\n\nconst NOOP = () => {};\n\nexport type WorkerThreadProps = {\n name: string;\n source?: string;\n url?: string;\n};\n\n/**\n * Represents one worker thread\n */\nexport default class WorkerThread {\n readonly name: string;\n readonly source: string | undefined;\n readonly url: string | undefined;\n terminated: boolean = false;\n worker: Worker | NodeWorkerType;\n onMessage: (message: any) => void;\n onError: (error: Error) => void;\n\n private _loadableURL: string = '';\n\n /** Checks if workers are supported on this platform */\n static isSupported(): boolean {\n return (\n (typeof Worker !== 'undefined' && isBrowser) ||\n (typeof NodeWorker !== 'undefined' && !isBrowser)\n );\n }\n\n constructor(props: WorkerThreadProps) {\n const {name, source, url} = props;\n assert(source || url); // Either source or url must be defined\n this.name = name;\n this.source = source;\n this.url = url;\n this.onMessage = NOOP;\n this.onError = (error) => console.log(error); // eslint-disable-line\n\n this.worker = isBrowser ? this._createBrowserWorker() : this._createNodeWorker();\n }\n\n /**\n * Terminate this worker thread\n * @note Can free up significant memory\n */\n destroy(): void {\n this.onMessage = NOOP;\n this.onError = NOOP;\n this.worker.terminate(); // eslint-disable-line @typescript-eslint/no-floating-promises\n this.terminated = true;\n }\n\n get isRunning() {\n return Boolean(this.onMessage);\n }\n\n /**\n * Send a message to this worker thread\n * @param data any data structure, ideally consisting mostly of transferrable objects\n * @param transferList If not supplied, calculated automatically by traversing data\n */\n postMessage(data: any, transferList?: any[]): void {\n transferList = transferList || getTransferList(data);\n // @ts-ignore\n this.worker.postMessage(data, transferList);\n }\n\n // PRIVATE\n\n /**\n * Generate a standard Error from an ErrorEvent\n * @param event\n */\n _getErrorFromErrorEvent(event: ErrorEvent): Error {\n // Note Error object does not have the expected fields if loading failed completely\n // https://developer.mozilla.org/en-US/docs/Web/API/Worker#Event_handlers\n // https://developer.mozilla.org/en-US/docs/Web/API/ErrorEvent\n let message = 'Failed to load ';\n message += `worker ${this.name} from ${this.url}. `;\n if (event.message) {\n message += `${event.message} in `;\n }\n // const hasFilename = event.filename && !event.filename.startsWith('blob:');\n // message += hasFilename ? event.filename : this.source.slice(0, 100);\n if (event.lineno) {\n message += `:${event.lineno}:${event.colno}`;\n }\n return new Error(message);\n }\n\n /**\n * Creates a worker thread on the browser\n */\n _createBrowserWorker(): Worker {\n this._loadableURL = getLoadableWorkerURL({source: this.source, url: this.url});\n const worker = new Worker(this._loadableURL, {name: this.name});\n\n worker.onmessage = (event) => {\n if (!event.data) {\n this.onError(new Error('No data received'));\n } else {\n this.onMessage(event.data);\n }\n };\n // This callback represents an uncaught exception in the worker thread\n worker.onerror = (error: ErrorEvent): void => {\n this.onError(this._getErrorFromErrorEvent(error));\n this.terminated = true;\n };\n // TODO - not clear when this would be called, for now just log in case it happens\n worker.onmessageerror = (event) => console.error(event); // eslint-disable-line\n\n return worker;\n }\n\n /**\n * Creates a worker thread in node.js\n * @todo https://nodejs.org/api/async_hooks.html#async-resource-worker-pool\n */\n _createNodeWorker(): NodeWorkerType {\n let worker: NodeWorkerType;\n if (this.url) {\n // Make sure relative URLs start with './'\n const absolute = this.url.includes(':/') || this.url.startsWith('/');\n const url = absolute ? this.url : `./${this.url}`;\n const type = this.url.endsWith('.ts') || this.url.endsWith('.mjs') ? 'module' : 'commonjs';\n // console.log('Starting work from', url);\n // @ts-expect-error type is not known\n worker = new NodeWorker(url, {eval: false, type});\n } else if (this.source) {\n worker = new NodeWorker(this.source, {eval: true});\n } else {\n throw new Error('no worker');\n }\n worker.on('message', (data) => {\n // console.error('message', data);\n this.onMessage(data);\n });\n worker.on('error', (error) => {\n this.onError(error as Error);\n });\n worker.on('exit', (code) => {\n // console.error('exit', code);\n });\n return worker;\n }\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {WorkerMessageType, WorkerMessagePayload} from '../../types';\nimport {isMobile, isBrowser} from '../env-utils/globals';\nimport WorkerThread from './worker-thread';\nimport WorkerJob from './worker-job';\n\n/** WorkerPool onDebug Callback Parameters */\ntype OnDebugParameters = {\n message: string;\n worker: string;\n name: string;\n job: string;\n backlog: number;\n workerThread: WorkerThread;\n};\n\n/** WorkerPool Properties */\nexport type WorkerPoolProps = {\n name?: string;\n source?: string; // | Function;\n url?: string;\n maxConcurrency?: number;\n maxMobileConcurrency?: number;\n onDebug?: (options: OnDebugParameters) => any;\n reuseWorkers?: boolean;\n};\n\n/** Private helper types */\ntype OnMessage = (job: WorkerJob, type: WorkerMessageType, payload: WorkerMessagePayload) => void;\ntype OnError = (job: WorkerJob, error: Error) => void;\n\ntype QueuedJob = {\n name: string;\n onMessage: OnMessage;\n onError: OnError;\n onStart: (value: any) => void; // Resolve job start promise\n};\n\n/**\n * Process multiple data messages with small pool of identical workers\n */\nexport default class WorkerPool {\n name: string = 'unnamed';\n source?: string; // | Function;\n url?: string;\n maxConcurrency: number = 1;\n maxMobileConcurrency: number = 1;\n onDebug: (options: OnDebugParameters) => any = () => {};\n reuseWorkers: boolean = true;\n\n private props: WorkerPoolProps = {};\n private jobQueue: QueuedJob[] = [];\n private idleQueue: WorkerThread[] = [];\n private count = 0;\n private isDestroyed = false;\n\n /** Checks if workers are supported on this platform */\n static isSupported(): boolean {\n return WorkerThread.isSupported();\n }\n\n /**\n * @param processor - worker function\n * @param maxConcurrency - max count of workers\n */\n constructor(props: WorkerPoolProps) {\n this.source = props.source;\n this.url = props.url;\n this.setProps(props);\n }\n\n /**\n * Terminates all workers in the pool\n * @note Can free up significant memory\n */\n destroy(): void {\n // Destroy idle workers, active Workers will be destroyed on completion\n this.idleQueue.forEach((worker) => worker.destroy());\n this.isDestroyed = true;\n }\n\n setProps(props: WorkerPoolProps) {\n this.props = {...this.props, ...props};\n\n if (props.name !== undefined) {\n this.name = props.name;\n }\n if (props.maxConcurrency !== undefined) {\n this.maxConcurrency = props.maxConcurrency;\n }\n if (props.maxMobileConcurrency !== undefined) {\n this.maxMobileConcurrency = props.maxMobileConcurrency;\n }\n if (props.reuseWorkers !== undefined) {\n this.reuseWorkers = props.reuseWorkers;\n }\n if (props.onDebug !== undefined) {\n this.onDebug = props.onDebug;\n }\n }\n\n async startJob(\n name: string,\n onMessage: OnMessage = (job, type, data) => job.done(data),\n onError: OnError = (job, error) => job.error(error)\n ): Promise {\n // Promise resolves when thread starts working on this job\n const startPromise = new Promise((onStart) => {\n // Promise resolves when thread completes or fails working on this job\n this.jobQueue.push({name, onMessage, onError, onStart});\n return this;\n });\n this._startQueuedJob(); // eslint-disable-line @typescript-eslint/no-floating-promises\n return await startPromise;\n }\n\n // PRIVATE\n\n /**\n * Starts first queued job if worker is available or can be created\n * Called when job is started and whenever a worker returns to the idleQueue\n */\n async _startQueuedJob(): Promise {\n if (!this.jobQueue.length) {\n return;\n }\n\n const workerThread = this._getAvailableWorker();\n if (!workerThread) {\n return;\n }\n\n // We have a worker, dequeue and start the job\n const queuedJob = this.jobQueue.shift();\n if (queuedJob) {\n // Emit a debug event\n // @ts-ignore\n this.onDebug({\n message: 'Starting job',\n name: queuedJob.name,\n workerThread,\n backlog: this.jobQueue.length\n });\n\n // Create a worker job to let the app access thread and manage job completion\n const job = new WorkerJob(queuedJob.name, workerThread);\n\n // Set the worker thread's message handlers\n workerThread.onMessage = (data) => queuedJob.onMessage(job, data.type, data.payload);\n workerThread.onError = (error) => queuedJob.onError(job, error);\n\n // Resolve the start promise so that the app can start sending messages to worker\n queuedJob.onStart(job);\n\n // Wait for the app to signal that the job is complete, then return worker to queue\n try {\n await job.result;\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error(`Worker exception: ${error}`);\n } finally {\n this.returnWorkerToQueue(workerThread);\n }\n }\n }\n\n /**\n * Returns a worker to the idle queue\n * Destroys the worker if\n * - pool is destroyed\n * - if this pool doesn't reuse workers\n * - if maxConcurrency has been lowered\n * @param worker\n */\n returnWorkerToQueue(worker: WorkerThread) {\n const shouldDestroyWorker =\n // Workers on Node.js prevent the process from exiting.\n // Until we figure out how to close them before exit, we always destroy them\n !isBrowser ||\n // If the pool is destroyed, there is no reason to keep the worker around\n this.isDestroyed ||\n // If the app has disabled worker reuse, any completed workers should be destroyed\n !this.reuseWorkers ||\n // If concurrency has been lowered, this worker might be surplus to requirements\n this.count > this._getMaxConcurrency();\n\n if (shouldDestroyWorker) {\n worker.destroy();\n this.count--;\n } else {\n this.idleQueue.push(worker);\n }\n\n if (!this.isDestroyed) {\n this._startQueuedJob(); // eslint-disable-line @typescript-eslint/no-floating-promises\n }\n }\n\n /**\n * Returns idle worker or creates new worker if maxConcurrency has not been reached\n */\n _getAvailableWorker(): WorkerThread | null {\n // If a worker has completed and returned to the queue, it can be used\n if (this.idleQueue.length > 0) {\n return this.idleQueue.shift() || null;\n }\n\n // Create fresh worker if we haven't yet created the max amount of worker threads for this worker source\n if (this.count < this._getMaxConcurrency()) {\n this.count++;\n const name = `${this.name.toLowerCase()} (#${this.count} of ${this.maxConcurrency})`;\n return new WorkerThread({name, source: this.source, url: this.url});\n }\n\n // No worker available, have to wait\n return null;\n }\n\n _getMaxConcurrency() {\n return isMobile ? this.maxMobileConcurrency : this.maxConcurrency;\n }\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport WorkerPool from './worker-pool';\nimport WorkerThread from './worker-thread';\n\n/**\n * @param maxConcurrency - max count of workers\n * @param maxMobileConcurrency - max count of workers on mobile\n * @param maxConcurrency - max count of workers\n * @param reuseWorkers - if false, destroys workers when task is completed\n * @param onDebug - callback intended to allow application to log worker pool activity\n */\nexport type WorkerFarmProps = {\n maxConcurrency?: number;\n maxMobileConcurrency?: number;\n reuseWorkers?: boolean;\n onDebug?: () => void;\n};\n\nconst DEFAULT_PROPS: Required = {\n maxConcurrency: 3,\n maxMobileConcurrency: 1,\n reuseWorkers: true,\n onDebug: () => {}\n};\n\n/**\n * Process multiple jobs with a \"farm\" of different workers in worker pools.\n */\nexport default class WorkerFarm {\n private props: WorkerFarmProps;\n private workerPools = new Map();\n // singleton\n private static _workerFarm?: WorkerFarm;\n\n /** Checks if workers are supported on this platform */\n static isSupported(): boolean {\n return WorkerThread.isSupported();\n }\n\n /** Get the singleton instance of the global worker farm */\n static getWorkerFarm(props: WorkerFarmProps = {}): WorkerFarm {\n WorkerFarm._workerFarm = WorkerFarm._workerFarm || new WorkerFarm({});\n WorkerFarm._workerFarm.setProps(props);\n return WorkerFarm._workerFarm;\n }\n\n /** get global instance with WorkerFarm.getWorkerFarm() */\n private constructor(props: WorkerFarmProps) {\n this.props = {...DEFAULT_PROPS};\n this.setProps(props);\n /** @type Map} */\n this.workerPools = new Map();\n }\n\n /**\n * Terminate all workers in the farm\n * @note Can free up significant memory\n */\n destroy(): void {\n for (const workerPool of this.workerPools.values()) {\n workerPool.destroy();\n }\n this.workerPools = new Map();\n }\n\n /**\n * Set props used when initializing worker pools\n * @param props\n */\n setProps(props: WorkerFarmProps): void {\n this.props = {...this.props, ...props};\n // Update worker pool props\n for (const workerPool of this.workerPools.values()) {\n workerPool.setProps(this._getWorkerPoolProps());\n }\n }\n\n /**\n * Returns a worker pool for the specified worker\n * @param options - only used first time for a specific worker name\n * @param options.name - the name of the worker - used to identify worker pool\n * @param options.url -\n * @param options.source -\n * @example\n * const job = WorkerFarm.getWorkerFarm().getWorkerPool({name, url}).startJob(...);\n */\n getWorkerPool(options: {name: string; source?: string; url?: string}): WorkerPool {\n const {name, source, url} = options;\n let workerPool = this.workerPools.get(name);\n if (!workerPool) {\n workerPool = new WorkerPool({\n name,\n source,\n url\n });\n workerPool.setProps(this._getWorkerPoolProps());\n this.workerPools.set(name, workerPool);\n }\n return workerPool;\n }\n\n _getWorkerPoolProps() {\n return {\n maxConcurrency: this.props.maxConcurrency,\n maxMobileConcurrency: this.props.maxMobileConcurrency,\n reuseWorkers: this.props.reuseWorkers,\n onDebug: this.props.onDebug\n };\n }\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {WorkerObject, WorkerOptions} from '../../types';\nimport {assert} from '../env-utils/assert';\nimport {isBrowser} from '../env-utils/globals';\nimport {VERSION} from '../env-utils/version';\nimport {NPM_TAG} from '../npm-tag';\n\n/**\n * Gets worker object's name (for debugging in Chrome thread inspector window)\n */\nexport function getWorkerName(worker: WorkerObject): string {\n const warning = worker.version !== VERSION ? ` (worker-utils@${VERSION})` : '';\n return `${worker.name}@${worker.version}${warning}`;\n}\n\n/**\n * Generate a worker URL based on worker object and options\n * @returns A URL to one of the following:\n * - a published worker on unpkg CDN\n * - a local test worker\n * - a URL provided by the user in options\n */\nexport function getWorkerURL(worker: WorkerObject, options: WorkerOptions = {}): string {\n const workerOptions = options[worker.id] || {};\n\n const workerFile = isBrowser ? `${worker.id}-worker.js` : `${worker.id}-worker-node.js`;\n\n let url = workerOptions.workerUrl;\n\n // HACK: Allow for non-nested workerUrl for the CompressionWorker.\n // For the compression worker, workerOptions is currently not nested correctly. For most loaders,\n // you'd have options within an object, i.e. `{mvt: {coordinates: ...}}` but the CompressionWorker\n // puts options at the top level, not within a `compression` key (its `id`). For this reason, the\n // above `workerOptions` will always be a string (i.e. `'gzip'`) for the CompressionWorker. To not\n // break backwards compatibility, we allow the CompressionWorker to have options at the top level.\n if (!url && worker.id === 'compression') {\n url = options.workerUrl;\n }\n\n // If URL is test, generate local loaders.gl url\n // @ts-ignore _workerType\n const workerType = (options as any)._workerType || (options as any)?.core?._workerType;\n if (workerType === 'test') {\n if (isBrowser) {\n url = `modules/${worker.module}/dist/${workerFile}`;\n } else {\n // In the test environment the ts-node loader requires TypeScript code\n url = `modules/${worker.module}/src/workers/${worker.id}-worker-node.ts`;\n }\n }\n\n // If url override is not provided, generate a URL to published version on npm CDN unpkg.com\n if (!url) {\n // GENERATE\n let version = worker.version;\n // On master we need to load npm alpha releases published with the `beta` tag\n if (version === 'latest') {\n // throw new Error('latest worker version specified');\n version = NPM_TAG;\n }\n const versionTag = version ? `@${version}` : '';\n url = `https://unpkg.com/@loaders.gl/${worker.module}${versionTag}/dist/${workerFile}`;\n }\n\n assert(url);\n\n // Allow user to override location\n return url;\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {WorkerObject} from '../../types';\nimport {assert} from '../env-utils/assert';\nimport {VERSION} from '../env-utils/version';\n\n/**\n * Check if worker is compatible with this library version\n * @param worker\n * @param libVersion\n * @returns `true` if the two versions are compatible\n */\nexport function validateWorkerVersion(\n worker: WorkerObject,\n coreVersion: string = VERSION\n): boolean {\n assert(worker, 'no worker provided');\n\n const workerVersion = worker.version;\n if (!coreVersion || !workerVersion) {\n return false;\n }\n\n // TODO enable when fix the __version__ injection\n // const coreVersions = parseVersion(coreVersion);\n // const workerVersions = parseVersion(workerVersion);\n // assert(\n // coreVersion.major === workerVersion.major && coreVersion.minor <= workerVersion.minor,\n // `worker: ${worker.name} is not compatible. ${coreVersion.major}.${\n // coreVersion.minor\n // }+ is required.`\n // );\n\n return true;\n}\n\n// @ts-ignore\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nfunction parseVersion(version) {\n const parts = version.split('.').map(Number);\n return {major: parts[0], minor: parts[1]};\n}\n","import {\n WorkerJob,\n WorkerMessageType,\n WorkerMessagePayload,\n isBrowser,\n WorkerFarm,\n getWorkerURL\n} from '@loaders.gl/worker-utils';\nimport type {Loader, LoaderOptions, LoaderContext} from '../../loader-types';\n\n/**\n * Determines if a loader can parse with worker\n * @param loader\n * @param options\n */\nexport function canParseWithWorker(loader: Loader, options?: LoaderOptions) {\n if (!WorkerFarm.isSupported()) {\n return false;\n }\n\n // Node workers are still experimental\n const nodeWorkers = options?._nodeWorkers ?? options?.core?._nodeWorkers;\n if (!isBrowser && !nodeWorkers) {\n return false;\n }\n\n const useWorkers = options?.worker ?? options?.core?.worker;\n return Boolean(loader.worker && useWorkers);\n}\n\n/**\n * this function expects that the worker function sends certain messages,\n * this can be automated if the worker is wrapper by a call to createLoaderWorker in @loaders.gl/loader-utils.\n */\nexport async function parseWithWorker(\n loader: Loader,\n data: any,\n options?: LoaderOptions,\n context?: LoaderContext,\n parseOnMainThread?: (arrayBuffer: ArrayBuffer, options: {[key: string]: any}) => Promise\n) {\n const name = loader.id; // TODO\n const url = getWorkerURL(loader, options);\n\n const workerFarm = WorkerFarm.getWorkerFarm(options?.core);\n const workerPool = workerFarm.getWorkerPool({name, url});\n\n // options.log object contains functions which cannot be transferred\n // context.fetch & context.parse functions cannot be transferred\n // TODO - decide how to handle logging on workers\n options = JSON.parse(JSON.stringify(options));\n context = JSON.parse(JSON.stringify(context || {}));\n\n const job = await workerPool.startJob(\n 'process-on-worker',\n // @ts-expect-error\n onMessage.bind(null, parseOnMainThread) // eslint-disable-line @typescript-eslint/no-misused-promises\n );\n\n job.postMessage('process', {\n // @ts-ignore\n input: data,\n options,\n context\n });\n\n const result = await job.result;\n // TODO - what is going on here?\n return await result.result;\n}\n\n/**\n * Handle worker's responses to the main thread\n * @param job\n * @param type\n * @param payload\n */\nasync function onMessage(\n parseOnMainThread: (arrayBuffer: ArrayBuffer, options?: {[key: string]: any}) => Promise,\n job: WorkerJob,\n type: WorkerMessageType,\n payload: WorkerMessagePayload\n) {\n switch (type) {\n case 'done':\n job.done(payload);\n break;\n\n case 'error':\n job.error(new Error(payload.error));\n break;\n\n case 'process':\n // Worker is asking for main thread to parseO\n const {id, input, options} = payload;\n try {\n const result = await parseOnMainThread(input, options);\n job.postMessage('done', {id, result});\n } catch (error) {\n const message = error instanceof Error ? error.message : 'unknown error';\n job.postMessage('error', {id, error: message});\n }\n break;\n\n default:\n // eslint-disable-next-line\n console.warn(`parse-with-worker unknown message ${type}`);\n }\n}\n","import {TypedArray} from '../../types';\n\n/**\n * compare two binary arrays for equality\n * @param a\n * @param b\n * @param byteLength\n */\nexport function compareArrayBuffers(\n arrayBuffer1: ArrayBufferLike,\n arrayBuffer2: ArrayBufferLike,\n byteLength?: number\n): boolean {\n byteLength = byteLength || arrayBuffer1.byteLength;\n if (arrayBuffer1.byteLength < byteLength || arrayBuffer2.byteLength < byteLength) {\n return false;\n }\n const array1 = new Uint8Array(arrayBuffer1);\n const array2 = new Uint8Array(arrayBuffer2);\n for (let i = 0; i < array1.length; ++i) {\n if (array1[i] !== array2[i]) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Concatenate a sequence of ArrayBuffers from arguments\n * @return A concatenated ArrayBuffer\n */\nexport function concatenateArrayBuffers(...sources: (ArrayBuffer | Uint8Array)[]): ArrayBuffer {\n return concatenateArrayBuffersFromArray(sources);\n}\n\n/**\n * Concatenate a sequence of ArrayBuffers from array\n * @return A concatenated ArrayBuffer\n */\nexport function concatenateArrayBuffersFromArray(\n sources: (ArrayBuffer | Uint8Array)[]\n): ArrayBuffer {\n // Make sure all inputs are wrapped in typed arrays\n const sourceArrays = sources.map((source2) =>\n source2 instanceof ArrayBuffer ? new Uint8Array(source2) : source2\n );\n\n // Get length of all inputs\n const byteLength = sourceArrays.reduce((length, typedArray) => length + typedArray.byteLength, 0);\n\n // Allocate array with space for all inputs\n const result = new Uint8Array(byteLength);\n\n // Copy the subarrays\n let offset = 0;\n for (const sourceArray of sourceArrays) {\n result.set(sourceArray, offset);\n offset += sourceArray.byteLength;\n }\n\n // We work with ArrayBuffers, discard the typed array wrapper\n return result.buffer;\n}\n\n/**\n * Concatenate arbitrary count of typed arrays\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays\n * @param - list of arrays. All arrays should be the same type\n * @return A concatenated TypedArray\n */\nexport function concatenateTypedArrays(...typedArrays: T[]): T {\n // @ts-ignore\n const arrays = typedArrays as TypedArray[];\n // @ts-ignore\n const TypedArrayConstructor = (arrays && arrays.length > 1 && arrays[0].constructor) || null;\n if (!TypedArrayConstructor) {\n throw new Error(\n '\"concatenateTypedArrays\" - incorrect quantity of arguments or arguments have incompatible data types'\n );\n }\n\n const sumLength = arrays.reduce((acc, value) => acc + value.length, 0);\n // @ts-ignore typescript does not like dynamic constructors\n const result = new TypedArrayConstructor(sumLength);\n let offset = 0;\n for (const array of arrays) {\n result.set(array, offset);\n offset += array.length;\n }\n return result;\n}\n\n/**\n * Copy a view of an ArrayBuffer into new ArrayBuffer with byteOffset = 0\n * @param arrayBuffer\n * @param byteOffset\n * @param byteLength\n */\nexport function sliceArrayBuffer(\n arrayBuffer: ArrayBufferLike,\n byteOffset: number,\n byteLength?: number\n): ArrayBuffer {\n const subArray =\n byteLength !== undefined\n ? new Uint8Array(arrayBuffer).subarray(byteOffset, byteOffset + byteLength)\n : new Uint8Array(arrayBuffer).subarray(byteOffset);\n const arrayCopy = new Uint8Array(subArray);\n return arrayCopy.buffer;\n}\n","import {concatenateArrayBuffers} from '../binary-utils/array-buffer-utils';\n\n// GENERAL UTILITIES\n\n/**\n * Iterates over an {@link AsyncIterable} or {@link Iterable}, invoking `visitor` for each yielded\n * value without rewinding the iterator when exiting early. This enables the caller to continue\n * iterating in another loop after `visitor` signals cancellation.\n */\nexport async function forEach(\n iterable: AsyncIterable | Iterable | AsyncIterator,\n visitor: (value: TValue) => any\n) {\n const iterator = toAsyncIterator(iterable);\n // eslint-disable-next-line\n while (true) {\n const {done, value} = await iterator.next();\n if (done) {\n if (iterator.return) {\n iterator.return();\n }\n return;\n }\n const cancel = visitor(value);\n if (cancel) {\n return;\n }\n }\n}\n\n/**\n * Concatenates all binary chunks yielded by an async or sync iterator.\n * Supports `ArrayBuffer`, typed array views, and `ArrayBufferLike` sources (e.g. `SharedArrayBuffer`).\n * This allows atomic parsers to operate on iterator inputs by materializing them into a single buffer.\n */\nexport async function concatenateArrayBuffersAsync(\n asyncIterator:\n | AsyncIterable\n | Iterable\n): Promise {\n const arrayBuffers: ArrayBuffer[] = [];\n for await (const chunk of asyncIterator) {\n arrayBuffers.push(copyToArrayBuffer(chunk));\n }\n return concatenateArrayBuffers(...arrayBuffers);\n}\n\nexport async function concatenateStringsAsync(\n asyncIterator: AsyncIterable | Iterable\n): Promise {\n const strings: string[] = [];\n for await (const chunk of asyncIterator) {\n strings.push(chunk);\n }\n return strings.join('');\n}\n\n/**\n * Normalizes binary chunk iterators to yield `ArrayBuffer` instances.\n * Accepts `ArrayBuffer`, `ArrayBufferView`, and `ArrayBufferLike` sources\n * (e.g. `SharedArrayBuffer`) and returns a copied `ArrayBuffer` for each chunk.\n */\nexport async function* toArrayBufferIterator(\n asyncIterator:\n | AsyncIterable\n | Iterable\n): AsyncIterable {\n for await (const chunk of asyncIterator) {\n yield copyToArrayBuffer(chunk);\n }\n}\n\nfunction copyToArrayBuffer(chunk: ArrayBufferLike | ArrayBufferView | ArrayBuffer): ArrayBuffer {\n if (chunk instanceof ArrayBuffer) {\n return chunk;\n }\n\n if (ArrayBuffer.isView(chunk)) {\n const {buffer, byteOffset, byteLength} = chunk;\n return copyFromBuffer(buffer, byteOffset, byteLength);\n }\n\n return copyFromBuffer(chunk as ArrayBufferLike);\n}\n\nfunction copyFromBuffer(\n buffer: ArrayBufferLike,\n byteOffset = 0,\n byteLength = buffer.byteLength - byteOffset\n): ArrayBuffer {\n const view = new Uint8Array(buffer, byteOffset, byteLength);\n const copy = new Uint8Array(view.length);\n copy.set(view);\n return copy.buffer;\n}\n\nfunction toAsyncIterator(\n iterable: AsyncIterable | Iterable | AsyncIterator\n): AsyncIterator {\n if (typeof iterable[Symbol.asyncIterator] === 'function') {\n return iterable[Symbol.asyncIterator]();\n }\n\n if (typeof iterable[Symbol.iterator] === 'function') {\n const iterator = iterable[Symbol.iterator]();\n return iteratorToAsyncIterator(iterator);\n }\n\n return iterable as AsyncIterator;\n}\n\nfunction iteratorToAsyncIterator(iterator: Iterator): AsyncIterator {\n return {\n next(value?: any) {\n return Promise.resolve(iterator.next(value));\n },\n\n return(value?: any) {\n if (typeof iterator.return === 'function') {\n return Promise.resolve(iterator.return(value));\n }\n return Promise.resolve({done: true, value});\n },\n\n throw(error?: any) {\n if (typeof iterator.throw === 'function') {\n return Promise.resolve(iterator.throw(error));\n }\n return Promise.reject(error);\n }\n };\n}\n","// Simple file alias mechanisms for tests.\n\nlet pathPrefix = '';\nconst fileAliases: {[aliasPath: string]: string} = {};\n\n/*\n * Set a relative path prefix\n */\nexport function setPathPrefix(prefix: string): void {\n pathPrefix = prefix;\n}\n\n/*\n * Get the relative path prefix\n */\nexport function getPathPrefix(): string {\n return pathPrefix;\n}\n\n/**\n *\n * @param aliases\n *\n * Note: addAliases are an experimental export, they are only for testing of loaders.gl loaders\n * not intended as a generic aliasing mechanism\n */\nexport function addAliases(aliases: {[aliasPath: string]: string}): void {\n Object.assign(fileAliases, aliases);\n}\n\n/**\n * Resolves aliases and adds path-prefix to paths\n */\nexport function resolvePath(filename: string): string {\n for (const alias in fileAliases) {\n if (filename.startsWith(alias)) {\n const replacement = fileAliases[alias];\n filename = filename.replace(alias, replacement);\n }\n }\n if (!filename.startsWith('http://') && !filename.startsWith('https://')) {\n filename = `${pathPrefix}${filename}`;\n }\n return filename;\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// Isolates Buffer references to ensure they are only bundled under Node.js (avoids big webpack polyfill)\n// this file is selected by the package.json \"browser\" field).\n\n/**\n * Convert Buffer to ArrayBuffer\n * Converts Node.js `Buffer` to `ArrayBuffer` (without triggering bundler to include Buffer polyfill on browser)\n * @todo better data type\n */\nexport function toArrayBuffer(buffer) {\n return buffer;\n}\n\n/**\n * Convert (copy) ArrayBuffer to Buffer\n */\nexport function toBuffer(binaryData: ArrayBuffer | Buffer): Buffer {\n throw new Error('Buffer not supported in browser');\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {isSharedArrayBuffer} from '../javascript-utils/is-type';\nimport * as node from '../node/buffer';\n\n/**\n * Check for Node.js `Buffer` (without triggering bundler to include Buffer polyfill on browser)\n */\nexport function isBuffer(value: any): value is Buffer {\n return value && typeof value === 'object' && value.isBuffer;\n}\n\n/**\n * Converts to Node.js `Buffer` (without triggering bundler to include Buffer polyfill on browser)\n * @todo better data type\n */\nexport function toBuffer(data: unknown): Buffer {\n return node.toBuffer ? node.toBuffer(data as any) : (data as Buffer);\n}\n\n/**\n * Convert an object to an array buffer. Handles SharedArrayBuffers.\n */\nexport function toArrayBuffer(\n data: Buffer | ArrayBufferLike | ArrayBufferView | string | Blob\n): ArrayBuffer {\n // Note: Should be called first, Buffers can trigger other detections below\n if (isBuffer(data)) {\n return node.toArrayBuffer(data);\n }\n\n if (data instanceof ArrayBuffer) {\n return data;\n }\n\n if (isSharedArrayBuffer(data)) {\n return copyToArrayBuffer(data);\n }\n\n // Node Buffers look like Uint8Arrays (Check isBuffer first)\n if (ArrayBuffer.isView(data)) {\n // TODO - ArrayBufferLike type mess\n const buffer = data.buffer as ArrayBuffer;\n if (data.byteOffset === 0 && data.byteLength === data.buffer.byteLength) {\n return buffer;\n }\n return buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);\n }\n\n if (typeof data === 'string') {\n const text = data;\n const uint8Array = new TextEncoder().encode(text);\n return uint8Array.buffer;\n }\n\n // HACK to support Blob polyfill\n if (data && typeof data === 'object' && (data as any)._toArrayBuffer) {\n return (data as any)._toArrayBuffer();\n }\n\n throw new Error('toArrayBuffer');\n}\n\n/** Ensure that SharedArrayBuffers are copied into ArrayBuffers */\nexport function ensureArrayBuffer(bufferSource: ArrayBufferLike | ArrayBufferView): ArrayBuffer {\n if (bufferSource instanceof ArrayBuffer) {\n return bufferSource;\n }\n\n if (isSharedArrayBuffer(bufferSource)) {\n return copyToArrayBuffer(bufferSource);\n }\n\n const {buffer, byteOffset, byteLength} = bufferSource;\n if (buffer instanceof ArrayBuffer && byteOffset === 0 && byteLength === buffer.byteLength) {\n return buffer;\n }\n return copyToArrayBuffer(buffer, byteOffset, byteLength);\n}\n\n/** Copies an ArrayBuffer or a section of an ArrayBuffer to a new ArrayBuffer, handles SharedArrayBuffers */\nexport function copyToArrayBuffer(\n buffer: ArrayBufferLike,\n byteOffset = 0,\n byteLength = buffer.byteLength - byteOffset\n): ArrayBuffer {\n const view = new Uint8Array(buffer, byteOffset, byteLength);\n const copy = new Uint8Array(view.length);\n copy.set(view);\n return copy.buffer;\n}\n\n/** Convert an object to an ArrayBufferView, handles SharedArrayBuffers */\nexport function toArrayBufferView(\n data: ArrayBufferLike | ArrayBufferView\n): ArrayBuffer | ArrayBufferView {\n if (ArrayBuffer.isView(data)) {\n return data;\n }\n\n // Create a view to support ArrayBufferLike sources such as SharedArrayBuffer\n return new Uint8Array(data);\n}\n","// Beginning of a minimal implementation of the Node.js path API, that doesn't pull in big polyfills.\n\nimport {getCWD} from './get-cwd';\n\n/**\n * Replacement for Node.js path.filename\n * @param url\n */\nexport function filename(url: string): string {\n const slashIndex = url ? url.lastIndexOf('/') : -1;\n return slashIndex >= 0 ? url.substr(slashIndex + 1) : url;\n}\n\n/**\n * Replacement for Node.js path.dirname\n * @param url\n */\nexport function dirname(url: string): string {\n const slashIndex = url ? url.lastIndexOf('/') : -1;\n return slashIndex >= 0 ? url.substr(0, slashIndex) : '';\n}\n\n/**\n * Replacement for Node.js path.join\n * @param parts\n */\nexport function join(...parts: string[]): string {\n const separator = '/';\n parts = parts.map((part, index) => {\n if (index) {\n part = part.replace(new RegExp(`^${separator}`), '');\n }\n if (index !== parts.length - 1) {\n part = part.replace(new RegExp(`${separator}$`), '');\n }\n return part;\n });\n return parts.join(separator);\n}\n\n/* eslint-disable no-continue */\n\n/**\n * https://nodejs.org/api/path.html#path_path_resolve_paths\n * @param paths A sequence of paths or path segments.\n * @return resolved path\n * Forked from BTOdell/path-resolve under MIT license\n * @see https://github.com/BTOdell/path-resolve/blob/master/LICENSE\n */\nexport function resolve(...components: string[]): string {\n const paths: string[] = [];\n for (let _i = 0; _i < components.length; _i++) {\n paths[_i] = components[_i];\n }\n let resolvedPath = '';\n let resolvedAbsolute = false;\n let cwd: string | undefined;\n for (let i = paths.length - 1; i >= -1 && !resolvedAbsolute; i--) {\n let path: string | undefined;\n if (i >= 0) {\n path = paths[i];\n } else {\n if (cwd === undefined) {\n cwd = getCWD();\n }\n path = cwd;\n }\n // Skip empty entries\n if (path.length === 0) {\n continue;\n }\n resolvedPath = `${path}/${resolvedPath}`;\n resolvedAbsolute = path.charCodeAt(0) === SLASH;\n }\n // At this point the path should be resolved to a full absolute path, but\n // handle relative paths to be safe (might happen when process.cwd() fails)\n // Normalize the path (removes leading slash)\n resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute);\n if (resolvedAbsolute) {\n return `/${resolvedPath}`;\n } else if (resolvedPath.length > 0) {\n return resolvedPath;\n }\n return '.';\n}\n\nconst SLASH = 47;\nconst DOT = 46;\n\n/**\n * Resolves . and .. elements in a path with directory names\n * Forked from BTOdell/path-resolve under MIT license\n * @see https://github.com/BTOdell/path-resolve/blob/master/LICENSE\n */\n/* eslint-disable max-depth */\n// eslint-disable-next-line complexity, max-statements\nfunction normalizeStringPosix(path: string, allowAboveRoot: boolean): string {\n let res = '';\n let lastSlash = -1;\n let dots = 0;\n let code: number | undefined;\n let isAboveRoot = false;\n\n for (let i = 0; i <= path.length; ++i) {\n if (i < path.length) {\n code = path.charCodeAt(i);\n } else if (code === SLASH) {\n break;\n } else {\n code = SLASH;\n }\n if (code === SLASH) {\n if (lastSlash === i - 1 || dots === 1) {\n // NOOP\n } else if (lastSlash !== i - 1 && dots === 2) {\n if (\n res.length < 2 ||\n !isAboveRoot ||\n res.charCodeAt(res.length - 1) !== DOT ||\n res.charCodeAt(res.length - 2) !== DOT\n ) {\n if (res.length > 2) {\n const start = res.length - 1;\n let j = start;\n for (; j >= 0; --j) {\n if (res.charCodeAt(j) === SLASH) {\n break;\n }\n }\n if (j !== start) {\n res = j === -1 ? '' : res.slice(0, j);\n lastSlash = i;\n dots = 0;\n isAboveRoot = false;\n continue;\n }\n } else if (res.length === 2 || res.length === 1) {\n res = '';\n lastSlash = i;\n dots = 0;\n isAboveRoot = false;\n continue;\n }\n }\n if (allowAboveRoot) {\n if (res.length > 0) {\n res += '/..';\n } else {\n res = '..';\n }\n isAboveRoot = true;\n }\n } else {\n const slice = path.slice(lastSlash + 1, i);\n if (res.length > 0) {\n res += `/${slice}`;\n } else {\n res = slice;\n }\n isAboveRoot = false;\n }\n lastSlash = i;\n dots = 0;\n } else if (code === DOT && dots !== -1) {\n ++dots;\n } else {\n dots = -1;\n }\n }\n return res;\n}\n","// loaders.gl MIT license\n\nexport function getCWD() {\n if (typeof process !== 'undefined' && typeof process.cwd !== 'undefined') {\n return process.cwd();\n }\n const pathname = window.location?.pathname;\n return pathname?.slice(0, pathname.lastIndexOf('/') + 1) || '';\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport class FetchError extends Error {\n constructor(message: string, info: {url: string; reason: string; response?: Response}) {\n super(message);\n this.reason = info.reason;\n this.url = info.url;\n this.response = info.response;\n }\n /** A best effort reason for why the fetch failed */\n reason: string;\n /** The URL that failed to load. Empty string if not available. */\n url: string;\n /** The Response object, if any. */\n response?: Response;\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// TODO - build/integrate proper MIME type parsing\n// https://mimesniff.spec.whatwg.org/\n\nconst DATA_URL_PATTERN = /^data:([-\\w.]+\\/[-\\w.+]+)(;|,)/;\nconst MIME_TYPE_PATTERN = /^([-\\w.]+\\/[-\\w.+]+)/;\n\n/**\n * Compare two MIME types, case insensitively etc.\n * @param mimeType1\n * @param mimeType2\n * @returns true if the MIME types are equivalent\n * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types#structure_of_a_mime_type\n */\nexport function compareMIMETypes(mimeType1: string, mimeType2: string): boolean {\n if (mimeType1.toLowerCase() === mimeType2.toLowerCase()) {\n return true;\n }\n return false;\n}\n\n/**\n * Remove extra data like `charset` from MIME types\n * @param mimeString\n * @returns A clean MIME type, or an empty string\n *\n * @todo - handle more advanced MIMETYpes, multiple types\n * @todo - extract charset etc\n */\nexport function parseMIMEType(mimeString: string): string {\n // If resource is a data url, extract any embedded mime type\n const matches = MIME_TYPE_PATTERN.exec(mimeString);\n if (matches) {\n return matches[1];\n }\n return mimeString;\n}\n\n/**\n * Extract MIME type from data URL\n *\n * @param mimeString\n * @returns A clean MIME type, or an empty string\n *\n * @todo - handle more advanced MIMETYpes, multiple types\n * @todo - extract charset etc\n */\nexport function parseMIMETypeFromURL(url: string): string {\n // If resource is a data URL, extract any embedded mime type\n const matches = DATA_URL_PATTERN.exec(url);\n if (matches) {\n return matches[1];\n }\n return '';\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nconst QUERY_STRING_PATTERN = /\\?.*/;\n\nexport function extractQueryString(url): string {\n const matches = url.match(QUERY_STRING_PATTERN);\n return matches && matches[0];\n}\n\nexport function stripQueryString(url): string {\n return url.replace(QUERY_STRING_PATTERN, '');\n}\n\nexport function shortenUrlForDisplay(url: string): string {\n if (url.length < 50) {\n return url;\n }\n const urlEnd = url.slice(url.length - 15);\n const urlStart = url.substr(0, 32);\n return `${urlStart}...${urlEnd}`;\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {isResponse, isBlob} from '@loaders.gl/loader-utils';\nimport {parseMIMEType, parseMIMETypeFromURL} from './mime-type-utils';\nimport {stripQueryString} from './url-utils';\n\n/**\n * A loadable resource. Includes:\n * `Response`, `Blob` (`File` is a subclass), string URLs and data URLs\n */\nexport type Resource = Response | Blob | string;\n\n/**\n * Returns the URL associated with this resource.\n * The returned value may include a query string and need further processing.\n * If it cannot determine url, the corresponding value will be an empty string\n *\n * @todo string parameters are assumed to be URLs\n */\nexport function getResourceUrl(resource: unknown): string {\n // If resource is a `Response`, it contains the information directly as a field\n if (isResponse(resource)) {\n return resource.url;\n }\n\n // If the resource is a Blob or a File (subclass of Blob)\n if (isBlob(resource)) {\n // File objects have a \"name\" property. Blob objects don't have any\n // url (name) information\n const fileName = 'name' in resource ? (resource as File).name : '';\n return fileName || '';\n }\n\n if (typeof resource === 'string') {\n return resource;\n }\n\n // Unknown\n return '';\n}\n\n/**\n * Returns the URL associated with this resource.\n * The returned value may include a query string and need further processing.\n * If it cannot determine url, the corresponding value will be an empty string\n *\n * @todo string parameters are assumed to be URLs\n */\nexport function getResourceMIMEType(resource: unknown): string {\n // If resource is a response, it contains the information directly\n if (isResponse(resource)) {\n const contentTypeHeader = resource.headers.get('content-type') || '';\n const noQueryUrl = stripQueryString(resource.url);\n return parseMIMEType(contentTypeHeader) || parseMIMETypeFromURL(noQueryUrl);\n }\n\n // If the resource is a Blob or a File (subclass of Blob)\n if (isBlob(resource)) {\n return resource.type || '';\n }\n\n if (typeof resource === 'string') {\n return parseMIMETypeFromURL(resource);\n }\n\n // Unknown\n return '';\n}\n\n/**\n * Returns (approximate) content length for a resource if it can be determined.\n * Returns -1 if content length cannot be determined.\n * @param resource\n\n * @note string parameters are NOT assumed to be URLs\n */\nexport function getResourceContentLength(resource: unknown): number {\n if (isResponse(resource)) {\n const response = resource;\n return response.headers['content-length'] || -1;\n }\n if (isBlob(resource)) {\n const blob = resource;\n return blob.size;\n }\n if (typeof resource === 'string') {\n // TODO - handle data URL?\n return resource.length;\n }\n if (resource instanceof ArrayBuffer) {\n return resource.byteLength;\n }\n if (ArrayBuffer.isView(resource)) {\n return resource.byteLength;\n }\n return -1;\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {isResponse} from '@loaders.gl/loader-utils';\nimport {FetchError} from '../fetch/fetch-error';\nimport {getResourceContentLength, getResourceUrl, getResourceMIMEType} from './resource-utils';\nimport {shortenUrlForDisplay} from './url-utils';\n\n/**\n * Returns a Response object\n * Adds content-length header when possible\n *\n * @param resource\n */\nexport async function makeResponse(resource: unknown): Promise {\n if (isResponse(resource)) {\n return resource;\n }\n\n // Add content-length header if possible\n const headers: {[header: string]: string} = {};\n\n const contentLength = getResourceContentLength(resource);\n if (contentLength >= 0) {\n headers['content-length'] = String(contentLength);\n }\n\n // `new Response(File)` does not preserve content-type and URL\n // so we add them here\n const url = getResourceUrl(resource);\n const type = getResourceMIMEType(resource);\n if (type) {\n headers['content-type'] = type;\n }\n\n // Add a custom header with initial bytes if available\n const initialDataUrl = await getInitialDataUrl(resource);\n if (initialDataUrl) {\n headers['x-first-bytes'] = initialDataUrl;\n }\n\n // TODO - is this the best way of handling strings?\n // Maybe package as data URL instead?\n if (typeof resource === 'string') {\n // Convert to ArrayBuffer to avoid Response treating it as a URL\n resource = new TextEncoder().encode(resource);\n }\n\n // Attempt to create a Response from the resource, adding headers and setting url\n const response = new Response(resource as any, {headers});\n // We can't control `Response.url` via constructor, use a property override to record URL.\n Object.defineProperty(response, 'url', {value: url});\n return response;\n}\n\n/**\n * Checks response status (async) and throws a helpful error message if status is not OK.\n * @param response\n */\nexport async function checkResponse(response: Response): Promise {\n if (!response.ok) {\n const error = await getResponseError(response);\n throw error;\n }\n}\n\n/**\n * Checks response status (sync) and throws a helpful error message if status is not OK.\n * @param response\n */\nexport function checkResponseSync(response: Response): void {\n if (!response.ok) {\n let message = `${response.status} ${response.statusText}`;\n message = message.length > 60 ? `${message.slice(0, 60)}...` : message;\n throw new Error(message);\n }\n}\n\n// HELPERS\n\nasync function getResponseError(response: Response): Promise {\n const shortUrl = shortenUrlForDisplay(response.url);\n let message = `Failed to fetch resource (${response.status}) ${response.statusText}: ${shortUrl}`;\n message = message.length > 100 ? `${message.slice(0, 100)}...` : message;\n\n const info = {\n reason: response.statusText,\n url: response.url,\n response\n };\n\n // See if we got an error message in the body\n try {\n const contentType = response.headers.get('Content-Type');\n info.reason =\n !response.bodyUsed && contentType?.includes('application/json')\n ? await response.json()\n : await response.text();\n } catch (error) {\n // eslint forbids return in a finally statement, so we just catch here\n }\n return new FetchError(message, info);\n}\n\nasync function getInitialDataUrl(\n resource: string | Blob | ArrayBuffer | unknown\n): Promise {\n const INITIAL_DATA_LENGTH = 5;\n if (typeof resource === 'string') {\n return `data:,${resource.slice(0, INITIAL_DATA_LENGTH)}`;\n }\n if (resource instanceof Blob) {\n const blobSlice = resource.slice(0, 5);\n return await new Promise((resolve) => {\n const reader = new FileReader();\n reader.onload = (event) => resolve(event?.target?.result as string);\n reader.readAsDataURL(blobSlice);\n });\n }\n if (resource instanceof ArrayBuffer) {\n const slice = resource.slice(0, INITIAL_DATA_LENGTH);\n const base64 = arrayBufferToBase64(slice);\n return `data:base64,${base64}`;\n }\n return null;\n}\n\n// https://stackoverflow.com/questions/9267899/arraybuffer-to-base64-encoded-string\nfunction arrayBufferToBase64(buffer: ArrayBuffer): string {\n let binary = '';\n const bytes = new Uint8Array(buffer);\n for (let i = 0; i < bytes.byteLength; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n return btoa(binary);\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {resolvePath} from '@loaders.gl/loader-utils';\nimport {makeResponse} from '../utils/response-utils';\n// import {FetchError} from './fetch-error';\n\nexport function isNodePath(url: string): boolean {\n return !isRequestURL(url) && !isDataURL(url);\n}\n\nexport function isRequestURL(url: string): boolean {\n return url.startsWith('http:') || url.startsWith('https:');\n}\n\nexport function isDataURL(url: string): boolean {\n return url.startsWith('data:');\n}\n\n/**\n * fetch API compatible function\n * - Supports fetching from Node.js local file system paths\n * - Respects pathPrefix and file aliases\n */\nexport async function fetchFile(\n urlOrData: string | Blob,\n fetchOptions?: RequestInit\n): Promise {\n if (typeof urlOrData === 'string') {\n const url = resolvePath(urlOrData);\n\n // Support fetching from local file system\n if (isNodePath(url)) {\n if (globalThis.loaders?.fetchNode) {\n return globalThis.loaders?.fetchNode(url, fetchOptions);\n }\n // throw new Error(\n // 'fetchFile: globalThis.loaders.fetchNode not defined. Install @loaders.gl/polyfills'\n // );\n }\n\n // Call global fetch\n return await fetch(url, fetchOptions);\n }\n\n // TODO - should we still call fetch on non-URL inputs?\n return await makeResponse(urlOrData);\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// probe.gl Log compatible loggers\n\nimport {Log} from '@probe.gl/log';\n\nexport const probeLog = new Log({id: 'loaders.gl'});\n\ntype LogFunction = () => void;\n\n// Logs nothing\nexport class NullLog {\n log(): LogFunction {\n return () => {};\n }\n info(): LogFunction {\n return () => {};\n }\n warn(): LogFunction {\n return () => {};\n }\n error(): LogFunction {\n return () => {};\n }\n}\n\n// Logs to console\nexport class ConsoleLog {\n console;\n\n constructor() {\n this.console = console; // eslint-disable-line\n }\n log(...args: unknown[]): LogFunction {\n return this.console.log.bind(this.console, ...args);\n }\n info(...args: unknown[]): LogFunction {\n return this.console.info.bind(this.console, ...args);\n }\n warn(...args: unknown[]): LogFunction {\n return this.console.warn.bind(this.console, ...args);\n }\n error(...args: unknown[]): LogFunction {\n return this.console.error.bind(this.console, ...args);\n }\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {LoaderOptions} from '@loaders.gl/loader-utils';\nimport {isBrowser} from '@loaders.gl/loader-utils';\nimport {ConsoleLog} from './loggers';\n\nexport const DEFAULT_LOADER_OPTIONS: LoaderOptions = {\n core: {\n baseUrl: undefined,\n // baseUrl\n fetch: null,\n mimeType: undefined,\n fallbackMimeType: undefined,\n ignoreRegisteredLoaders: undefined,\n nothrow: false,\n log: new ConsoleLog(), // A probe.gl compatible (`log.log()()` syntax) that just logs to console\n useLocalLibraries: false,\n\n CDN: 'https://unpkg.com/@loaders.gl',\n worker: true, // By default, use worker if provided by loader.\n maxConcurrency: 3, // How many worker instances should be created for each loader.\n maxMobileConcurrency: 1, // How many worker instances should be created for each loader on mobile devices.\n reuseWorkers: isBrowser, // By default reuse workers in browser (Node.js refuses to terminate if browsers are running)\n _nodeWorkers: false, // By default do not support node workers\n _workerType: '', // 'test' to use locally generated workers\n\n limit: 0,\n _limitMB: 0,\n batchSize: 'auto',\n batchDebounceMs: 0,\n metadata: false, // TODO - currently only implemented for parseInBatches, adds initial metadata batch,\n transforms: []\n }\n};\n\nexport const REMOVED_LOADER_OPTIONS = {\n // deprecated top-level alias\n baseUri: 'core.baseUrl',\n fetch: 'core.fetch',\n mimeType: 'core.mimeType',\n fallbackMimeType: 'core.fallbackMimeType',\n ignoreRegisteredLoaders: 'core.ignoreRegisteredLoaders',\n nothrow: 'core.nothrow',\n log: 'core.log',\n useLocalLibraries: 'core.useLocalLibraries',\n\n CDN: 'core.CDN',\n worker: 'core.worker',\n maxConcurrency: 'core.maxConcurrency',\n maxMobileConcurrency: 'core.maxMobileConcurrency',\n reuseWorkers: 'core.reuseWorkers',\n _nodeWorkers: 'core.nodeWorkers',\n _workerType: 'core._workerType',\n _worker: 'core._workerType',\n\n limit: 'core.limit',\n _limitMB: 'core._limitMB',\n batchSize: 'core.batchSize',\n batchDebounceMs: 'core.batchDebounceMs',\n metadata: 'core.metadata',\n transforms: 'core.transforms',\n\n // Older deprecations\n throws: 'nothrow',\n dataType: '(no longer used)',\n uri: 'core.baseUrl',\n\n // Warn if fetch options are used on toplevel\n method: 'core.fetch.method',\n headers: 'core.fetch.headers',\n body: 'core.fetch.body',\n mode: 'core.fetch.mode',\n credentials: 'core.fetch.credentials',\n cache: 'core.fetch.cache',\n redirect: 'core.fetch.redirect',\n referrer: 'core.fetch.referrer',\n referrerPolicy: 'core.fetch.referrerPolicy',\n integrity: 'core.fetch.integrity',\n keepalive: 'core.fetch.keepalive',\n signal: 'core.fetch.signal'\n};\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {\n Loader,\n LoaderOptions,\n registerJSModules,\n isPureObject,\n isObject,\n StrictLoaderOptions,\n path\n} from '@loaders.gl/loader-utils';\nimport {probeLog, NullLog} from './loggers';\nimport {DEFAULT_LOADER_OPTIONS, REMOVED_LOADER_OPTIONS} from './option-defaults';\nimport {stripQueryString} from '../utils/url-utils';\n\nconst CORE_LOADER_OPTION_KEYS = [\n 'baseUrl',\n 'fetch',\n 'mimeType',\n 'fallbackMimeType',\n 'ignoreRegisteredLoaders',\n 'nothrow',\n 'log',\n 'useLocalLibraries',\n 'CDN',\n 'worker',\n 'maxConcurrency',\n 'maxMobileConcurrency',\n 'reuseWorkers',\n '_nodeWorkers',\n '_workerType',\n 'limit',\n '_limitMB',\n 'batchSize',\n 'batchDebounceMs',\n 'metadata',\n 'transforms'\n] as const;\n\n/**\n * Global state for loaders.gl. Stored on `globalThis.loaders._state`\n */\ntype GlobalLoaderState = {\n loaderRegistry: Loader[];\n globalOptions: LoaderOptions;\n};\n\n/**\n * Helper for safely accessing global loaders.gl variables\n * Wraps initialization of global variable in function to defeat overly aggressive tree-shakers\n */\nexport function getGlobalLoaderState(): GlobalLoaderState {\n // @ts-ignore\n globalThis.loaders = globalThis.loaders || {};\n // @ts-ignore\n const {loaders} = globalThis;\n\n // Add _state object to keep separate from modules added to globalThis.loaders\n if (!loaders._state) {\n loaders._state = {};\n }\n return loaders._state;\n}\n\n/**\n * Store global loader options on the global object to increase chances of cross loaders-version interoperability\n * NOTE: This use case is not reliable but can help when testing new versions of loaders.gl with existing frameworks\n * @returns global loader options merged with default loader options\n */\nexport function getGlobalLoaderOptions(): StrictLoaderOptions {\n const state = getGlobalLoaderState();\n // Ensure all default loader options from this library are mentioned\n state.globalOptions = state.globalOptions || {\n ...DEFAULT_LOADER_OPTIONS,\n core: {...DEFAULT_LOADER_OPTIONS.core}\n };\n return normalizeLoaderOptions(state.globalOptions);\n}\n\n/**\n * Set global loader options\n * @param options\n */\nexport function setGlobalOptions(options: LoaderOptions): void {\n const state = getGlobalLoaderState();\n const globalOptions = getGlobalLoaderOptions();\n // @ts-expect-error First param looks incorrect\n state.globalOptions = normalizeOptionsInternal(globalOptions, options);\n // Make sure any new modules are registered\n registerJSModules(options.modules);\n}\n\n/**\n * Merges options with global opts and loader defaults, also injects baseUrl\n * @param options\n * @param loader\n * @param loaders\n * @param url\n */\nexport function normalizeOptions(\n options: LoaderOptions,\n loader: Loader,\n loaders?: Loader[],\n url?: string\n): StrictLoaderOptions {\n loaders = loaders || [];\n loaders = Array.isArray(loaders) ? loaders : [loaders];\n\n validateOptions(options, loaders);\n return normalizeLoaderOptions(normalizeOptionsInternal(loader, options, url));\n}\n\n/**\n * Returns a copy of the provided options with deprecated top-level core fields moved into `core`\n * and removed from the top level. This keeps global options from leaking deprecated aliases into\n * loader-specific option maps during normalization.\n */\nexport function normalizeLoaderOptions(options: LoaderOptions): StrictLoaderOptions {\n const normalized = cloneLoaderOptions(options);\n moveDeprecatedTopLevelOptionsToCore(normalized);\n for (const key of CORE_LOADER_OPTION_KEYS) {\n if (normalized.core && normalized.core[key] !== undefined) {\n delete (normalized as Record)[key];\n }\n }\n if (normalized.core && normalized.core._workerType !== undefined) {\n delete (normalized as any)._worker;\n }\n return normalized as StrictLoaderOptions;\n}\n\n// VALIDATE OPTIONS\n\n/**\n * Warn for unsupported options\n * @param options\n * @param loaders\n */\nfunction validateOptions(options: LoaderOptions, loaders: Loader[]): void {\n // Check top level options\n validateOptionsObject(options, null, DEFAULT_LOADER_OPTIONS, REMOVED_LOADER_OPTIONS, loaders);\n for (const loader of loaders) {\n // Get the scoped, loader specific options from the user supplied options\n const idOptions: Record =\n ((options && options[loader.id]) as Record) || {};\n\n // Get scoped, loader specific default and deprecated options from the selected loader\n const loaderOptions = (loader.options && loader.options[loader.id]) || {};\n const deprecatedOptions =\n (loader.deprecatedOptions && loader.deprecatedOptions[loader.id]) || {};\n\n // Validate loader specific options\n // @ts-ignore\n validateOptionsObject(idOptions, loader.id, loaderOptions, deprecatedOptions, loaders);\n }\n}\n\n// eslint-disable-next-line max-params, complexity\nfunction validateOptionsObject(\n options: LoaderOptions,\n id: string | null,\n defaultOptions: Record,\n deprecatedOptions: Record,\n loaders: Loader[]\n): void {\n const loaderName = id || 'Top level';\n const prefix = id ? `${id}.` : '';\n\n for (const key in options) {\n // If top level option value is an object it could options for a loader, so ignore\n const isSubOptions = !id && isObject(options[key]);\n const isBaseUriOption = key === 'baseUri' && !id;\n const isWorkerUrlOption = key === 'workerUrl' && id;\n // .workerUrl requires special handling as it is now auto-generated and no longer specified as a default option.\n if (!(key in defaultOptions) && !isBaseUriOption && !isWorkerUrlOption) {\n // Issue deprecation warnings\n if (key in deprecatedOptions) {\n if (probeLog.level > 0) {\n probeLog.warn(\n `${loaderName} loader option \\'${prefix}${key}\\' no longer supported, use \\'${deprecatedOptions[key]}\\'`\n )();\n }\n } else if (!isSubOptions) {\n if (probeLog.level > 0) {\n const suggestion = findSimilarOption(key, loaders);\n probeLog.warn(\n `${loaderName} loader option \\'${prefix}${key}\\' not recognized. ${suggestion}`\n )();\n }\n }\n }\n }\n}\n\nfunction findSimilarOption(optionKey: string, loaders: Loader[]): string {\n const lowerCaseOptionKey = optionKey.toLowerCase();\n let bestSuggestion = '';\n for (const loader of loaders) {\n for (const key in loader.options) {\n if (optionKey === key) {\n return `Did you mean \\'${loader.id}.${key}\\'?`;\n }\n const lowerCaseKey = key.toLowerCase();\n const isPartialMatch =\n lowerCaseOptionKey.startsWith(lowerCaseKey) || lowerCaseKey.startsWith(lowerCaseOptionKey);\n if (isPartialMatch) {\n bestSuggestion = bestSuggestion || `Did you mean \\'${loader.id}.${key}\\'?`;\n }\n }\n }\n return bestSuggestion;\n}\n\nfunction normalizeOptionsInternal(\n loader: Loader,\n options: LoaderOptions,\n url?: string\n): LoaderOptions {\n const loaderDefaultOptions = loader.options || {};\n\n const mergedOptions = {...loaderDefaultOptions};\n if (loaderDefaultOptions.core) {\n mergedOptions.core = {...loaderDefaultOptions.core};\n }\n moveDeprecatedTopLevelOptionsToCore(mergedOptions);\n\n // LOGGING: options.log can be set to `null` to defeat logging\n if (mergedOptions.core?.log === null) {\n mergedOptions.core = {...mergedOptions.core, log: new NullLog()};\n }\n\n mergeNestedFields(mergedOptions, normalizeLoaderOptions(getGlobalLoaderOptions()));\n\n const userOptions = normalizeLoaderOptions(options);\n mergeNestedFields(mergedOptions, userOptions);\n\n addUrlOptions(mergedOptions, url);\n addDeprecatedTopLevelOptions(mergedOptions);\n\n return mergedOptions;\n}\n\n// Merge nested options objects\nfunction mergeNestedFields(mergedOptions: LoaderOptions, options: LoaderOptions): void {\n for (const key in options) {\n // Check for nested options\n // object in options => either no key in defaultOptions or object in defaultOptions\n if (key in options) {\n const value = options[key];\n if (isPureObject(value) && isPureObject(mergedOptions[key])) {\n mergedOptions[key] = {\n ...(mergedOptions[key] as object),\n ...(options[key] as object)\n };\n } else {\n mergedOptions[key] = options[key];\n }\n }\n // else: No need to merge nested opts, and the initial merge already copied over the nested options\n }\n}\n\n/**\n * Harvest information from the url\n * @deprecated This is mainly there to support loaders that still resolve from options\n * TODO - extract extension?\n * TODO - extract query parameters?\n * TODO - should these be injected on context instead of options?\n */\nfunction addUrlOptions(options: LoaderOptions, url?: string): void {\n if (!url) {\n return;\n }\n const hasCoreBaseUrl = options.core?.baseUrl !== undefined;\n if (!hasCoreBaseUrl) {\n options.core ||= {};\n options.core.baseUrl = path.dirname(stripQueryString(url));\n }\n}\n\nfunction cloneLoaderOptions(options: LoaderOptions): LoaderOptions {\n const clonedOptions = {...options};\n if (options.core) {\n clonedOptions.core = {...options.core};\n }\n return clonedOptions;\n}\n\nfunction moveDeprecatedTopLevelOptionsToCore(options: LoaderOptions): void {\n if (options.baseUri !== undefined) {\n options.core ||= {};\n if (options.core.baseUrl === undefined) {\n options.core.baseUrl = options.baseUri;\n }\n }\n\n for (const key of CORE_LOADER_OPTION_KEYS) {\n if ((options as Record)[key] !== undefined) {\n const coreOptions = (options.core = options.core || {});\n const coreRecord = coreOptions as Record;\n // Treat deprecated top-level core options as aliases to `options.core`, but never override an explicitly\n // provided `options.core` value.\n if (coreRecord[key] === undefined) {\n coreRecord[key] = (options as Record)[key];\n }\n }\n }\n\n // Support the older internal `_worker` alias (used by some tests and integrations) for `_workerType`.\n const workerTypeAlias = (options as any)._worker;\n if (workerTypeAlias !== undefined) {\n options.core ||= {};\n if (options.core._workerType === undefined) {\n options.core._workerType = workerTypeAlias;\n }\n }\n}\n\nfunction addDeprecatedTopLevelOptions(options: LoaderOptions): void {\n const coreOptions = options.core as Record | undefined;\n if (!coreOptions) {\n return;\n }\n for (const key of CORE_LOADER_OPTION_KEYS) {\n if (coreOptions[key] !== undefined) {\n (options as Record)[key] = coreOptions[key];\n }\n }\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Loader} from '@loaders.gl/loader-utils';\nimport {assert} from '@loaders.gl/loader-utils';\n\nexport function isLoaderObject(loader?: any): boolean {\n if (!loader) {\n return false;\n }\n\n if (Array.isArray(loader)) {\n loader = loader[0];\n }\n\n const hasExtensions = Array.isArray(loader?.extensions);\n\n /* Now handled by types and worker loaders do not have these\n let hasParser =\n loader.parseTextSync ||\n loader.parseSync ||\n loader.parse ||\n loader.parseStream || // TODO Remove, Replace with parseInBatches\n loader.parseInBatches;\n */\n\n return hasExtensions;\n}\n\nexport function normalizeLoader(loader: Loader): Loader {\n // This error is fairly easy to trigger by mixing up import statements etc\n // So we make an exception and add a developer error message for this case\n // To help new users from getting stuck here\n assert(loader, 'null loader');\n assert(isLoaderObject(loader), 'invalid loader');\n\n // NORMALIZE [LOADER, OPTIONS] => LOADER\n\n // If [loader, options], create a new loaders object with options merged in\n let options;\n if (Array.isArray(loader)) {\n options = loader[1];\n loader = loader[0];\n loader = {\n ...loader,\n options: {...loader.options, ...options}\n };\n }\n\n // NORMALIZE text and binary flags\n // Ensure at least one of text/binary flags are properly set\n\n // @ts-expect-error\n if (loader?.parseTextSync || loader?.parseText) {\n loader.text = true;\n }\n\n if (!loader.text) {\n loader.binary = true;\n }\n\n return loader;\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Loader} from '@loaders.gl/loader-utils';\nimport {normalizeLoader} from '../loader-utils/normalize-loader';\nimport {getGlobalLoaderState} from '../loader-utils/option-utils';\n\n/**\n * Store global registered loaders on the global object to increase chances of cross loaders-version interoperability\n * This use case is not reliable but can help when testing new versions of loaders.gl with existing frameworks\n */\nconst getGlobalLoaderRegistry = () => {\n const state = getGlobalLoaderState();\n state.loaderRegistry = state.loaderRegistry || [];\n return state.loaderRegistry;\n};\n\n/**\n * Register a list of global loaders\n * @note Registration erases loader type information.\n * @deprecated It is recommended that applications manage loader registration. This function will likely be remove in loaders.gl v5\n */\nexport function registerLoaders(loaders: Loader[] | Loader) {\n const loaderRegistry = getGlobalLoaderRegistry();\n\n loaders = Array.isArray(loaders) ? loaders : [loaders];\n\n for (const loader of loaders) {\n const normalizedLoader = normalizeLoader(loader);\n if (!loaderRegistry.find((registeredLoader) => normalizedLoader === registeredLoader)) {\n // add to the beginning of the loaderRegistry, so the last registeredLoader get picked\n loaderRegistry.unshift(normalizedLoader);\n }\n }\n}\n\n/**\n * @deprecated It is recommended that applications manage loader registration. This function will likely be remove in loaders.gl v5\n */\nexport function getRegisteredLoaders(): Loader[] {\n return getGlobalLoaderRegistry();\n}\n\n/** @deprecated For testing only */\nexport function _unregisterLoaders() {\n const state = getGlobalLoaderState();\n state.loaderRegistry = [];\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {LoaderContext, LoaderOptions, Loader, DataType} from '@loaders.gl/loader-utils';\nimport {\n compareArrayBuffers,\n path,\n log,\n isBlob,\n ensureArrayBuffer,\n isArrayBufferLike\n} from '@loaders.gl/loader-utils';\nimport {TypedArray} from '@loaders.gl/schema';\nimport {normalizeLoader} from '../loader-utils/normalize-loader';\nimport {normalizeLoaderOptions} from '../loader-utils/option-utils';\nimport {getResourceUrl, getResourceMIMEType} from '../utils/resource-utils';\nimport {compareMIMETypes} from '../utils/mime-type-utils';\nimport {getRegisteredLoaders} from './register-loaders';\nimport {stripQueryString} from '../utils/url-utils';\n\nconst EXT_PATTERN = /\\.([^.]+)$/;\n\n// TODO - Need a variant that peeks at streams for parseInBatches\n// TODO - Detect multiple matching loaders? Use heuristics to grade matches?\n// TODO - Allow apps to pass context to disambiguate between multiple matches (e.g. multiple .json formats)?\n\n/**\n * Find a loader that matches file extension and/or initial file content\n * Search the loaders array argument for a loader that matches url extension or initial data\n * Returns: a normalized loader\n * @param data data to assist\n * @param loaders\n * @param options\n * @param context used internally, applications should not provide this parameter\n */\nexport async function selectLoader(\n data: DataType,\n loaders: Loader[] | Loader = [],\n options?: LoaderOptions,\n context?: LoaderContext\n): Promise {\n if (!validHTTPResponse(data)) {\n return null;\n }\n\n const normalizedOptions = normalizeLoaderOptions(options || {});\n normalizedOptions.core ||= {};\n\n if (data instanceof Response && mayContainText(data)) {\n const text = await data.clone().text();\n const textLoader = selectLoaderSync(\n text,\n loaders,\n {...normalizedOptions, core: {...normalizedOptions.core, nothrow: true}},\n context\n );\n if (textLoader) {\n return textLoader;\n }\n }\n\n // First make a sync attempt, disabling exceptions\n let loader = selectLoaderSync(\n data,\n loaders,\n {...normalizedOptions, core: {...normalizedOptions.core, nothrow: true}},\n context\n );\n if (loader) {\n return loader;\n }\n\n // For Blobs and Files, try to asynchronously read a small initial slice and test again with that\n // to see if we can detect by initial content\n if (isBlob(data)) {\n data = await data.slice(0, 10).arrayBuffer();\n loader = selectLoaderSync(data, loaders, normalizedOptions, context);\n }\n\n if (!loader && data instanceof Response && mayContainText(data)) {\n const text = await data.clone().text();\n loader = selectLoaderSync(text, loaders, normalizedOptions, context);\n }\n\n // no loader available\n if (!loader && !normalizedOptions.core.nothrow) {\n throw new Error(getNoValidLoaderMessage(data));\n }\n\n return loader;\n}\n\nfunction mayContainText(response: Response): boolean {\n const mimeType = getResourceMIMEType(response);\n return Boolean(\n mimeType &&\n (mimeType.startsWith('text/') || mimeType === 'application/json' || mimeType.endsWith('+json'))\n );\n}\n\n/**\n * Find a loader that matches file extension and/or initial file content\n * Search the loaders array argument for a loader that matches url extension or initial data\n * Returns: a normalized loader\n * @param data data to assist\n * @param loaders\n * @param options\n * @param context used internally, applications should not provide this parameter\n */\nexport function selectLoaderSync(\n data: DataType,\n loaders: Loader[] | Loader = [],\n options?: LoaderOptions,\n context?: LoaderContext\n): Loader | null {\n if (!validHTTPResponse(data)) {\n return null;\n }\n\n const normalizedOptions = normalizeLoaderOptions(options || {});\n normalizedOptions.core ||= {};\n\n // eslint-disable-next-line complexity\n // if only a single loader was provided (not as array), force its use\n // TODO - Should this behavior be kept and documented?\n if (loaders && !Array.isArray(loaders)) {\n // TODO - remove support for legacy loaders\n return normalizeLoader(loaders);\n }\n\n // Build list of candidate loaders that will be searched in order for a match\n let candidateLoaders: Loader[] = [];\n // First search supplied loaders\n if (loaders) {\n candidateLoaders = candidateLoaders.concat(loaders);\n }\n // Then fall back to registered loaders\n if (!normalizedOptions.core.ignoreRegisteredLoaders) {\n candidateLoaders.push(...getRegisteredLoaders());\n }\n\n // TODO - remove support for legacy loaders\n normalizeLoaders(candidateLoaders);\n\n const loader = selectLoaderInternal(data, candidateLoaders, normalizedOptions, context);\n\n // no loader available\n if (!loader && !normalizedOptions.core.nothrow) {\n throw new Error(getNoValidLoaderMessage(data));\n }\n\n return loader;\n}\n\n/** Implements loaders selection logic */\n// eslint-disable-next-line complexity\nfunction selectLoaderInternal(\n data: DataType,\n loaders: Loader[],\n options?: LoaderOptions,\n context?: LoaderContext\n) {\n const url = getResourceUrl(data);\n const type = getResourceMIMEType(data);\n\n const testUrl = stripQueryString(url) || context?.url;\n\n let loader: Loader | null = null;\n let reason: string = '';\n\n // if options.mimeType is supplied, it takes precedence\n if (options?.core?.mimeType) {\n loader = findLoaderByMIMEType(loaders, options?.core?.mimeType);\n reason = `match forced by supplied MIME type ${options?.core?.mimeType}`;\n }\n\n // Look up loader by url\n loader = loader || findLoaderByUrl(loaders, testUrl);\n reason = reason || (loader ? `matched url ${testUrl}` : '');\n\n // Look up loader by mime type\n loader = loader || findLoaderByMIMEType(loaders, type);\n reason = reason || (loader ? `matched MIME type ${type}` : '');\n\n // Look for loader via initial bytes (Note: not always accessible (e.g. Response, stream, async iterator)\n // @ts-ignore Blob | Response\n loader = loader || findLoaderByInitialBytes(loaders, data);\n // @ts-ignore Blob | Response\n reason = reason || (loader ? `matched initial data ${getFirstCharacters(data)}` : '');\n\n // Look up loader by fallback mime type\n if (options?.core?.fallbackMimeType) {\n loader = loader || findLoaderByMIMEType(loaders, options?.core?.fallbackMimeType);\n reason = reason || (loader ? `matched fallback MIME type ${type}` : '');\n }\n\n if (reason) {\n log.log(1, `selectLoader selected ${loader?.name}: ${reason}.`);\n }\n\n return loader;\n}\n\n/** Check HTTP Response */\nfunction validHTTPResponse(data: unknown): boolean {\n // HANDLE HTTP status\n if (data instanceof Response) {\n // 204 - NO CONTENT. This handles cases where e.g. a tile server responds with 204 for a missing tile\n if (data.status === 204) {\n return false;\n }\n }\n return true;\n}\n\n/** Generate a helpful message to help explain why loader selection failed. */\nfunction getNoValidLoaderMessage(data: DataType): string {\n const url = getResourceUrl(data);\n const type = getResourceMIMEType(data);\n\n let message = 'No valid loader found (';\n message += url ? `${path.filename(url)}, ` : 'no url provided, ';\n message += `MIME type: ${type ? `\"${type}\"` : 'not provided'}, `;\n // First characters are only accessible when called on data (string or arrayBuffer).\n // @ts-ignore Blob | Response\n const firstCharacters: string = data ? getFirstCharacters(data) : '';\n message += firstCharacters ? ` first bytes: \"${firstCharacters}\"` : 'first bytes: not available';\n message += ')';\n return message;\n}\n\nfunction normalizeLoaders(loaders: Loader[]): void {\n for (const loader of loaders) {\n normalizeLoader(loader);\n }\n}\n\n// TODO - Would be nice to support http://example.com/file.glb?parameter=1\n// E.g: x = new URL('http://example.com/file.glb?load=1'; x.pathname\nfunction findLoaderByUrl(loaders: Loader[], url?: string): Loader | null {\n // Get extension\n const match = url && EXT_PATTERN.exec(url);\n const extension = match && match[1];\n return extension ? findLoaderByExtension(loaders, extension) : null;\n}\n\nfunction findLoaderByExtension(loaders: Loader[], extension: string): Loader | null {\n extension = extension.toLowerCase();\n\n for (const loader of loaders) {\n for (const loaderExtension of loader.extensions) {\n if (loaderExtension.toLowerCase() === extension) {\n return loader;\n }\n }\n }\n return null;\n}\n\nfunction findLoaderByMIMEType(loaders: Loader[], mimeType: string): Loader | null {\n for (const loader of loaders) {\n if (loader.mimeTypes?.some((mimeType1) => compareMIMETypes(mimeType, mimeType1))) {\n return loader;\n }\n\n // Support referring to loaders using the \"unregistered tree\"\n // https://en.wikipedia.org/wiki/Media_type#Unregistered_tree\n if (compareMIMETypes(mimeType, `application/x.${loader.id}`)) {\n return loader;\n }\n }\n return null;\n}\n\nfunction findLoaderByInitialBytes(loaders: Loader[], data: string | ArrayBuffer): Loader | null {\n if (!data) {\n return null;\n }\n\n for (const loader of loaders) {\n if (typeof data === 'string') {\n if (testDataAgainstText(data, loader)) {\n return loader;\n }\n } else if (ArrayBuffer.isView(data)) {\n // Typed Arrays can have offsets into underlying buffer\n if (testDataAgainstBinary(data.buffer, data.byteOffset, loader)) {\n return loader;\n }\n } else if (data instanceof ArrayBuffer) {\n const byteOffset = 0;\n if (testDataAgainstBinary(data, byteOffset, loader)) {\n return loader;\n }\n }\n // TODO Handle streaming case (requires creating a new AsyncIterator)\n }\n return null;\n}\n\nfunction testDataAgainstText(data: string, loader: Loader): boolean {\n if (loader.testText) {\n return loader.testText(data);\n }\n\n const tests = Array.isArray(loader.tests) ? loader.tests : [loader.tests];\n return tests.some((test) => data.startsWith(test as string));\n}\n\nfunction testDataAgainstBinary(data: ArrayBufferLike, byteOffset: number, loader: Loader): boolean {\n const tests = Array.isArray(loader.tests) ? loader.tests : [loader.tests];\n return tests.some((test) => testBinary(data, byteOffset, loader, test));\n}\n\nfunction testBinary(\n data: ArrayBufferLike,\n byteOffset: number,\n loader: Loader,\n test?: ArrayBuffer | string | ((b: ArrayBuffer) => boolean)\n): boolean {\n if (isArrayBufferLike(test)) {\n return compareArrayBuffers(test, data, test.byteLength);\n }\n switch (typeof test) {\n case 'function':\n return test(ensureArrayBuffer(data));\n\n case 'string':\n // Magic bytes check: If `test` is a string, check if binary data starts with that strings\n const magic = getMagicString(data, byteOffset, test.length);\n return test === magic;\n\n default:\n return false;\n }\n}\n\nfunction getFirstCharacters(data: string | ArrayBuffer | TypedArray, length: number = 5) {\n if (typeof data === 'string') {\n return data.slice(0, length);\n } else if (ArrayBuffer.isView(data)) {\n // Typed Arrays can have offsets into underlying buffer\n return getMagicString(data.buffer, data.byteOffset, length);\n } else if (data instanceof ArrayBuffer) {\n const byteOffset = 0;\n return getMagicString(data, byteOffset, length);\n }\n return '';\n}\n\nfunction getMagicString(arrayBuffer: ArrayBufferLike, byteOffset: number, length: number): string {\n if (arrayBuffer.byteLength < byteOffset + length) {\n return '';\n }\n const dataView = new DataView(arrayBuffer);\n let magic = '';\n for (let i = 0; i < length; i++) {\n magic += String.fromCharCode(dataView.getUint8(byteOffset + i));\n }\n return magic;\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {ensureArrayBuffer} from '@loaders.gl/loader-utils';\nimport type {IteratorOptions} from './make-iterator';\n\nconst DEFAULT_CHUNK_SIZE = 256 * 1024;\n\n/**\n * Returns an iterator that breaks a big string into chunks and yields them one-by-one as ArrayBuffers\n * @param blob string to iterate over\n * @param options\n * @param options.chunkSize\n */\nexport function* makeStringIterator(\n string: string,\n options?: IteratorOptions\n): Iterable {\n const chunkSize = options?.chunkSize || DEFAULT_CHUNK_SIZE;\n\n let offset = 0;\n const textEncoder = new TextEncoder();\n while (offset < string.length) {\n // Create a chunk of the right size\n const chunkLength = Math.min(string.length - offset, chunkSize);\n const chunk = string.slice(offset, offset + chunkLength);\n offset += chunkLength;\n\n // yield an ArrayBuffer chunk\n yield ensureArrayBuffer(textEncoder.encode(chunk));\n }\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {IteratorOptions} from './make-iterator';\n\nconst DEFAULT_CHUNK_SIZE = 256 * 1024;\n\n/**\n * Returns an iterator that breaks a big ArrayBuffer into chunks and yields them one-by-one\n * @param blob ArrayBuffer to iterate over\n * @param options\n * @param options.chunkSize\n */\nexport function* makeArrayBufferIterator(\n arrayBuffer: ArrayBuffer,\n options: IteratorOptions = {}\n): Iterable {\n const {chunkSize = DEFAULT_CHUNK_SIZE} = options;\n\n let byteOffset = 0;\n\n while (byteOffset < arrayBuffer.byteLength) {\n // Create a chunk of the right size\n const chunkByteLength = Math.min(arrayBuffer.byteLength - byteOffset, chunkSize);\n const chunk = new ArrayBuffer(chunkByteLength);\n\n // Copy data from the big chunk\n const sourceArray = new Uint8Array(arrayBuffer, byteOffset, chunkByteLength);\n const chunkArray = new Uint8Array(chunk);\n chunkArray.set(sourceArray);\n\n // yield the chunk\n byteOffset += chunkByteLength;\n yield chunk;\n }\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {IteratorOptions} from './make-iterator';\n\nconst DEFAULT_CHUNK_SIZE = 1024 * 1024; // 1MB — biggest value that keeps UI responsive\n\n/**\n * Returns an iterator that breaks a big Blob into chunks and yields them one-by-one\n * @param blob Blob or File object\n * @param options\n * @param options.chunkSize\n */\nexport async function* makeBlobIterator(\n blob: Blob,\n options?: IteratorOptions\n): AsyncIterable {\n const chunkSize = options?.chunkSize || DEFAULT_CHUNK_SIZE;\n\n let offset = 0;\n while (offset < blob.size) {\n const end = offset + chunkSize;\n\n const chunk = await blob.slice(offset, end).arrayBuffer();\n\n offset = end;\n yield chunk;\n }\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Readable} from 'stream';\nimport {isBrowser, toArrayBuffer} from '@loaders.gl/loader-utils';\n\nexport type StreamIteratorOptions = {\n _streamReadAhead?: boolean;\n};\n\n/**\n * Returns an async iterable that reads from a stream (works in both Node.js and browsers)\n * @param stream stream to iterator over\n */\nexport function makeStreamIterator(\n stream: ReadableStream | Readable,\n options?: StreamIteratorOptions\n): AsyncIterable {\n return isBrowser\n ? makeBrowserStreamIterator(stream as ReadableStream, options)\n : makeNodeStreamIterator(stream as Readable, options);\n}\n\n/**\n * Returns an async iterable that reads from a DOM (browser) stream\n * @param stream stream to iterate from\n * @see https://jakearchibald.com/2017/async-iterators-and-generators/#making-streams-iterate\n */\nasync function* makeBrowserStreamIterator(\n stream: ReadableStream,\n options?: StreamIteratorOptions\n): AsyncIterable {\n // WhatWG: stream is supposed to have a `getIterator` method\n // if (typeof stream.getIterator === 'function') {\n // return stream.getIterator();\n // }\n // if (typeof stream[Symbol.asyncIterator] === 'function') {\n // return makeToArrayBufferIterator(stream);\n // }\n\n // In the browser, we first need to get a lock on the stream\n const reader = stream.getReader();\n\n let nextBatchPromise: Promise<{done?: boolean; value?: Uint8Array}> | undefined;\n\n try {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const currentBatchPromise = nextBatchPromise || reader.read();\n // Issue a read for an additional batch, while we await the next batch\n // Idea is to make fetching happen in parallel with processing / parsing\n if (options?._streamReadAhead) {\n nextBatchPromise = reader.read();\n }\n // Read from the stream\n // value is a Uint8Array\n const {done, value} = await currentBatchPromise;\n // Exit if we're done\n if (done) {\n return;\n }\n // Else yield the chunk\n yield toArrayBuffer(value);\n }\n } catch (error) {\n // TODO - examples makes it look like this should always be called,\n // but that generates exceptions so only call it if we do not reach the end\n reader.releaseLock();\n }\n}\n\n/**\n * Returns an async iterable that reads from a DOM (browser) stream\n * @param stream stream to iterate from\n * @note Requires Node.js >= 10\n */\nasync function* makeNodeStreamIterator(\n stream: Readable,\n options?: StreamIteratorOptions\n): AsyncIterable {\n // Hacky test for node version to ensure we don't call bad polyfills\n // NODE 10+: stream is an asyncIterator\n for await (const chunk of stream) {\n yield toArrayBuffer(chunk); // Coerce each chunk to ArrayBuffer\n }\n}\n/* TODO - remove NODE < 10\n * @see https://github.com/bustle/streaming-iterables, MIT license\n *\n if (typeof stream[Symbol.asyncIterator] === 'function') {\n return;\n }\n\n // TODO - check if is this ever used in Node 10+?\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const data = stream.read();\n if (data !== null) {\n yield toArrayBuffer(data);\n // eslint-disable-next-line no-continue\n continue;\n }\n if (stream._readableState?.ended) {\n return;\n }\n await onceReadable(stream);\n }\n\nasync function onceReadable(stream: Readable): Promise {\n return new Promise((resolve) => {\n stream.once('readable', resolve);\n });\n}\n */\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ReadStream} from 'fs';\n\nimport {makeStringIterator} from './make-string-iterator';\nimport {makeArrayBufferIterator} from './make-array-buffer-iterator';\nimport {makeBlobIterator} from './make-blob-iterator';\nimport type {StreamIteratorOptions} from './make-stream-iterator';\nimport {makeStreamIterator} from './make-stream-iterator';\nimport {isBlob, isReadableStream, isResponse} from '@loaders.gl/loader-utils';\n\n/**\n * @param [options.chunkSize]\n */\nexport type IteratorOptions = StreamIteratorOptions & {\n chunkSize?: number;\n};\n\n/**\n * Returns an iterator that breaks its input into chunks and yields them one-by-one.\n * @param data\n * @param options\n * @returns\n * This function can e.g. be used to enable data sources that can only be read atomically\n * (such as `Blob` and `File` via `FileReader`) to still be parsed in batches.\n */\nexport function makeIterator(\n data: ArrayBuffer | string | Blob | Response | ReadableStream | ReadStream,\n options?: IteratorOptions\n): AsyncIterable | Iterable {\n if (typeof data === 'string') {\n // Note: Converts string chunks to binary\n return makeStringIterator(data, options);\n }\n if (data instanceof ArrayBuffer) {\n return makeArrayBufferIterator(data, options);\n }\n if (isBlob(data)) {\n return makeBlobIterator(data, options);\n }\n if (isReadableStream(data)) {\n return makeStreamIterator(data, options);\n }\n if (isResponse(data)) {\n const responseBody = data.body;\n if (!responseBody) {\n throw new Error('Readable stream not available on Response');\n }\n return makeStreamIterator(responseBody as ReadableStream, options);\n }\n throw new Error('makeIterator');\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {\n DataType,\n SyncDataType,\n BatchableDataType,\n Loader,\n LoaderOptions\n} from '@loaders.gl/loader-utils';\nimport {\n concatenateArrayBuffersAsync,\n isPromise,\n isResponse,\n isReadableStream,\n isAsyncIterable,\n isIterable,\n isIterator,\n isBlob,\n isBuffer,\n isArrayBufferLike,\n toArrayBuffer,\n toArrayBufferView\n} from '@loaders.gl/loader-utils';\nimport {makeIterator} from '../../iterators/make-iterator/make-iterator';\nimport {checkResponse, makeResponse} from '../utils/response-utils';\n\nconst ERR_DATA = 'Cannot convert supplied data type';\n\n/**\n * Returns an {@link ArrayBuffer} or string from the provided data synchronously.\n * Supports `ArrayBuffer`, `ArrayBufferView`, and `ArrayBufferLike` (e.g. `SharedArrayBuffer`)\n * while preserving typed array view offsets.\n */\n// eslint-disable-next-line complexity\nexport function getArrayBufferOrStringFromDataSync(\n data: SyncDataType,\n loader: Loader,\n options: LoaderOptions\n): ArrayBuffer | string {\n if (loader.text && typeof data === 'string') {\n return data;\n }\n\n if (isBuffer(data)) {\n data = data.buffer;\n }\n\n if (isArrayBufferLike(data)) {\n const bufferSource = toArrayBufferView(data);\n if (loader.text && !loader.binary) {\n const textDecoder = new TextDecoder('utf8');\n return textDecoder.decode(bufferSource);\n }\n return toArrayBuffer(bufferSource);\n }\n\n throw new Error(ERR_DATA);\n}\n\n/**\n * Resolves the provided data into an {@link ArrayBuffer} or string asynchronously.\n * Accepts the full {@link DataType} surface including responses and async iterables.\n */\nexport async function getArrayBufferOrStringFromData(\n data: DataType,\n loader: Loader,\n options: LoaderOptions\n): Promise {\n if (typeof data === 'string' || isArrayBufferLike(data)) {\n return getArrayBufferOrStringFromDataSync(data as SyncDataType, loader, options);\n }\n\n // Blobs and files are FileReader compatible\n if (isBlob(data)) {\n data = await makeResponse(data);\n }\n\n if (isResponse(data)) {\n await checkResponse(data);\n return loader.binary ? await data.arrayBuffer() : await data.text();\n }\n\n if (isReadableStream(data)) {\n // @ts-expect-error TS2559 options type\n data = makeIterator(data as ReadableStream, options);\n }\n\n if (isIterable(data) || isAsyncIterable(data)) {\n // Assume arrayBuffer iterator - attempt to concatenate\n return concatenateArrayBuffersAsync(data as AsyncIterable);\n }\n\n throw new Error(ERR_DATA);\n}\n\n/**\n * Normalizes batchable inputs into async iterables for batch parsing flows.\n * Supports synchronous iterables, async iterables, fetch responses, readable streams, and\n * single binary chunks (including typed array views and `ArrayBufferLike` values).\n */\nexport async function getAsyncIterableFromData(\n data: BatchableDataType,\n options: LoaderOptions\n): Promise<\n AsyncIterable | Iterable\n> {\n if (isPromise(data)) {\n data = await data;\n }\n\n if (isIterator(data)) {\n return data as AsyncIterable;\n }\n\n if (isResponse(data)) {\n // Note Since this function is not async, we currently can't load error message, just status\n await checkResponse(data);\n // TODO - bug in polyfill, body can be a Promise under Node.js\n // eslint-disable-next-line @typescript-eslint/await-thenable\n const body = await data.body;\n if (!body) {\n throw new Error(ERR_DATA);\n }\n return makeIterator(body, options as any);\n }\n\n if (isBlob(data) || isReadableStream(data)) {\n return makeIterator(data as Blob | ReadableStream, options as any);\n }\n\n if (isAsyncIterable(data)) {\n return data as AsyncIterable;\n }\n\n if (isIterable(data)) {\n return data as Iterable;\n }\n\n // @ts-expect-error TODO - fix type mess\n return getIterableFromData(data);\n}\n\n/**\n * Returns a readable stream for streaming loader inputs when available.\n */\nexport async function getReadableStream(data: BatchableDataType): Promise {\n if (isReadableStream(data)) {\n return data as ReadableStream;\n }\n if (isResponse(data)) {\n // @ts-ignore\n if (!data.body) {\n throw new Error(ERR_DATA);\n }\n return data.body;\n }\n const response = await makeResponse(data);\n // @ts-ignore\n if (!response.body) {\n throw new Error(ERR_DATA);\n }\n return response.body;\n}\n\n// HELPERS\n\nfunction getIterableFromData(data: string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView) {\n // generate an iterator that emits a single chunk\n if (ArrayBuffer.isView(data)) {\n return (function* oneChunk() {\n yield toArrayBuffer(data);\n })();\n }\n\n if (isArrayBufferLike(data)) {\n return (function* oneChunk() {\n yield toArrayBuffer(data);\n })();\n }\n\n if (isIterator(data)) {\n return data;\n }\n\n if (isIterable(data)) {\n return data[Symbol.iterator]();\n }\n\n throw new Error(ERR_DATA);\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {LoaderContext, LoaderOptions, FetchLike} from '@loaders.gl/loader-utils';\nimport {isObject} from '@loaders.gl/loader-utils';\nimport {fetchFile} from '../fetch/fetch-file';\nimport {getGlobalLoaderOptions} from './option-utils';\n\n/**\n * Gets the current fetch function from options and context\n * @param options\n * @param context\n */\nexport function getFetchFunction(\n options?: LoaderOptions,\n context?: Omit & Partial>\n): FetchLike {\n const globalOptions = getGlobalLoaderOptions();\n\n const loaderOptions = options || globalOptions;\n const fetchOption = loaderOptions.fetch ?? loaderOptions.core?.fetch;\n\n // options.fetch can be a function\n if (typeof fetchOption === 'function') {\n return fetchOption;\n }\n\n // options.fetch can be an options object\n if (isObject(fetchOption)) {\n return (url) => fetchFile(url, fetchOption as RequestInit);\n }\n\n // else refer to context (from parent loader) if available\n if (context?.fetch) {\n return context?.fetch;\n }\n\n // else return the default fetch function\n return fetchFile;\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Loader, LoaderContext, StrictLoaderOptions} from '@loaders.gl/loader-utils';\nimport {getFetchFunction} from './get-fetch-function';\nimport {extractQueryString, stripQueryString} from '../utils/url-utils';\nimport {path} from '@loaders.gl/loader-utils';\n\n/** Properties for creating an updated context */\ntype LoaderContextProps = Omit & Partial>;\n\n/**\n * \"sub\" loaders invoked by other loaders get a \"context\" injected on `this`\n * The context will inject core methods like `parse` and contain information\n * about loaders and options passed in to the top-level `parse` call.\n *\n * @param context\n * @param options\n * @param previousContext\n */\nexport function getLoaderContext(\n context: LoaderContextProps,\n options: StrictLoaderOptions,\n parentContext: LoaderContext | null\n): LoaderContext {\n // For recursive calls, we already have a context\n // TODO - add any additional loaders to context?\n if (parentContext) {\n return parentContext;\n }\n\n const newContext: LoaderContext = {\n fetch: getFetchFunction(options, context),\n ...context\n };\n\n // Parse URLs so that subloaders can easily generate correct strings\n if (newContext.url) {\n const baseUrl = stripQueryString(newContext.url);\n newContext.baseUrl = baseUrl;\n newContext.queryString = extractQueryString(newContext.url);\n newContext.filename = path.filename(baseUrl);\n newContext.baseUrl = path.dirname(baseUrl);\n }\n\n // Recursive loading does not use single loader\n if (!Array.isArray(newContext.loaders)) {\n newContext.loaders = null;\n }\n\n return newContext;\n}\n\n// eslint-disable-next-line complexity\nexport function getLoadersFromContext(\n loaders: Loader[] | Loader | undefined,\n context?: LoaderContext\n): Loader | Loader[] | undefined {\n // A single loader (non-array) indicates no selection desired. Force select.\n if (loaders && !Array.isArray(loaders)) {\n return loaders;\n }\n\n // Create a merged list\n let candidateLoaders;\n if (loaders) {\n candidateLoaders = Array.isArray(loaders) ? loaders : [loaders];\n }\n if (context && context.loaders) {\n const contextLoaders = Array.isArray(context.loaders) ? context.loaders : [context.loaders];\n candidateLoaders = candidateLoaders ? [...candidateLoaders, ...contextLoaders] : contextLoaders;\n }\n // If no loaders, return null to look in globally registered loaders\n return candidateLoaders && candidateLoaders.length ? candidateLoaders : undefined;\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {\n Loader,\n LoaderContext,\n LoaderOptions,\n DataType,\n LoaderWithParser,\n LoaderOptionsType,\n LoaderReturnType,\n LoaderArrayOptionsType,\n LoaderArrayReturnType,\n StrictLoaderOptions\n} from '@loaders.gl/loader-utils';\nimport {\n parseWithWorker,\n canParseWithWorker,\n mergeOptions,\n isResponse\n} from '@loaders.gl/loader-utils';\nimport {assert, validateWorkerVersion} from '@loaders.gl/worker-utils';\nimport {isLoaderObject} from '../loader-utils/normalize-loader';\nimport {normalizeOptions} from '../loader-utils/option-utils';\nimport {getArrayBufferOrStringFromData} from '../loader-utils/get-data';\nimport {getLoaderContext, getLoadersFromContext} from '../loader-utils/loader-context';\nimport {getResourceUrl} from '../utils/resource-utils';\nimport {selectLoader} from './select-loader';\n\n// type LoaderArrayType = T extends (infer Loader)[] ? LoaderOptionsType : T\n\n/**\n * Parses `data` asynchronously using the supplied loader\n */\nexport async function parse<\n LoaderT extends Loader,\n OptionsT extends LoaderOptions = LoaderOptionsType\n>(\n data: DataType | Promise,\n loader: LoaderT,\n options?: OptionsT,\n context?: LoaderContext\n): Promise>;\n\n/**\n * Parses `data` asynchronously by matching one of the supplied loader\n */\nexport async function parse<\n LoaderArrayT extends Loader[],\n OptionsT extends LoaderOptions = LoaderArrayOptionsType\n>(\n data: DataType | Promise,\n loaders: LoaderArrayT,\n options?: OptionsT,\n context?: LoaderContext\n): Promise>;\n\n/**\n * Parses data asynchronously by matching a pre-registered loader\n * @deprecated Loader registration is deprecated, use parse(data, loaders, options) instead\n */\nexport async function parse(\n data: DataType | Promise,\n options?: LoaderOptions\n): Promise;\n\n/**\n * Parses `data` using a specified loader\n * @param data\n * @param loaders\n * @param options\n * @param context\n */\n// implementation signature\nexport async function parse(\n data: DataType | Promise,\n loaders?: Loader | Loader[] | LoaderOptions,\n options?: LoaderOptions,\n context?: LoaderContext\n): Promise {\n // Signature: parse(data, options, context | url)\n // Uses registered loaders\n if (loaders && !Array.isArray(loaders) && !isLoaderObject(loaders)) {\n context = undefined; // context not supported in short signature\n options = loaders as LoaderOptions;\n loaders = undefined;\n }\n\n data = await data; // Resolve any promise\n options = options || ({} as LoaderOptions); // Could be invalid...\n\n // Extract a url for auto detection\n const url = getResourceUrl(data);\n\n // Chooses a loader (and normalizes it)\n // Also use any loaders in the context, new loaders take priority\n const typedLoaders = loaders as Loader | Loader[] | undefined;\n const candidateLoaders = getLoadersFromContext(typedLoaders, context);\n // todo hacky type cast\n const loader = await selectLoader(data as ArrayBuffer, candidateLoaders, options);\n // Note: if no loader was found, if so just return null\n if (!loader) {\n return null;\n }\n\n // Normalize options\n // @ts-expect-error candidateLoaders\n const strictOptions = normalizeOptions(options, loader, candidateLoaders, url); // Could be invalid...\n\n // Get a context (if already present, will be unchanged)\n context = getLoaderContext(\n // @ts-expect-error\n {url, _parse: parse, loaders: candidateLoaders},\n strictOptions,\n context || null\n );\n\n return await parseWithLoader(loader, data, strictOptions, context);\n}\n\n// TODO: support progress and abort\n// TODO - should accept loader.parseAsyncIterator and concatenate.\nasync function parseWithLoader(\n loader: Loader,\n data,\n options: StrictLoaderOptions,\n context: LoaderContext\n): Promise {\n validateWorkerVersion(loader);\n\n options = mergeOptions(loader.options, options);\n\n if (isResponse(data)) {\n // Serialize to support passing the response to web worker\n const {ok, redirected, status, statusText, type, url} = data;\n const headers = Object.fromEntries(data.headers.entries());\n // @ts-expect-error TODO - fix this\n context.response = {headers, ok, redirected, status, statusText, type, url};\n }\n\n data = await getArrayBufferOrStringFromData(data, loader, options);\n\n const loaderWithParser = loader as LoaderWithParser;\n\n // First check for synchronous text parser, wrap results in promises\n if (loaderWithParser.parseTextSync && typeof data === 'string') {\n return loaderWithParser.parseTextSync(data, options, context);\n }\n\n // If we have a workerUrl and the loader can parse the given options efficiently in a worker\n if (canParseWithWorker(loader, options)) {\n return await parseWithWorker(loader, data, options, context, parse);\n }\n\n // Check for asynchronous parser\n if (loaderWithParser.parseText && typeof data === 'string') {\n return await loaderWithParser.parseText(data, options, context);\n }\n\n if (loaderWithParser.parse) {\n return await loaderWithParser.parse(data, options, context);\n }\n\n // This should not happen, all sync loaders should also offer `parse` function\n assert(!loaderWithParser.parseSync);\n\n // TBD - If asynchronous parser not available, return null\n throw new Error(`${loader.id} loader - no parser found and worker is disabled`);\n}\n","// math.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {TypedArray, NumericArray, NumberArray} from './array-types';\n\n/**\n * Check is an array is a typed array\n * @param value value to be tested\n * @returns input with type narrowed to TypedArray, or null\n */\nexport function isTypedArray(value: unknown): value is TypedArray {\n return ArrayBuffer.isView(value) && !(value instanceof DataView);\n}\n\n/**\n * Check is an array is an array of numbers)\n * @param value value to be tested\n * @returns input with type narrowed to NumberArray, or null\n */\nexport function isNumberArray(value: unknown): value is NumberArray {\n if (Array.isArray(value)) {\n return value.length === 0 || typeof value[0] === 'number';\n }\n return false;\n}\n\n/**\n * Check is an array is a numeric array (typed array or array of numbers)\n * @param value value to be tested\n * @returns input with type narrowed to NumericArray, or null\n */\nexport function isNumericArray(value: unknown): value is NumericArray {\n return isTypedArray(value) || isNumberArray(value);\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {\n DataType,\n Loader,\n LoaderContext,\n LoaderOptions,\n LoaderOptionsType,\n LoaderReturnType,\n LoaderArrayOptionsType,\n LoaderArrayReturnType\n} from '@loaders.gl/loader-utils';\nimport {isBlob} from '@loaders.gl/loader-utils';\nimport {isLoaderObject} from '../loader-utils/normalize-loader';\nimport {getFetchFunction} from '../loader-utils/get-fetch-function';\nimport {normalizeLoaderOptions} from '../loader-utils/option-utils';\n\nimport {parse} from './parse';\n\n/**\n * Parses `data` using a specified loader\n * Note: Load does duplicate a lot of parse.\n * it can also call fetchFile on string urls, which `parse` won't do.\n * @param data\n * @param loaders\n * @param options\n * @param context\n */\n\nexport async function load<\n LoaderT extends Loader,\n OptionsT extends LoaderOptions = LoaderOptionsType\n>(\n url: string | DataType,\n loader: LoaderT,\n options?: OptionsT,\n context?: LoaderContext\n): Promise>;\n\nexport async function load<\n LoaderArrayT extends Loader[],\n OptionsT extends LoaderOptions = LoaderArrayOptionsType\n>(\n url: string | DataType,\n loaders: LoaderArrayT,\n options?: OptionsT,\n context?: LoaderContext\n): Promise>;\n\n/**\n * Loads data asynchronously by matching a pre-registered loader\n * @deprecated Loader registration is deprecated, use load(data, loaders, options) instead\n */\nexport async function load(\n url: string | DataType,\n loaders?: LoaderOptions,\n context?: LoaderContext\n): Promise;\n\n// export async function load(url: string | DataType, loaders: LoaderOptions): Promise;\n\n// implementation signature\nexport async function load(\n url: string | DataType,\n loaders?: Loader[] | LoaderOptions,\n options?: LoaderOptions | LoaderContext,\n context?: LoaderContext\n): Promise {\n let resolvedLoaders: Loader | Loader[];\n let resolvedOptions: LoaderOptions | undefined;\n\n // Signature: load(url, options)\n if (!Array.isArray(loaders) && !isLoaderObject(loaders)) {\n resolvedLoaders = [];\n resolvedOptions = loaders as LoaderOptions;\n context = undefined; // context not supported in short signature\n } else {\n resolvedLoaders = loaders as Loader | Loader[];\n resolvedOptions = options as LoaderOptions;\n }\n\n // Select fetch function\n const fetch = getFetchFunction(resolvedOptions);\n\n // at this point, `url` could be already loaded binary data\n let data = url;\n // url is a string, fetch the url\n if (typeof url === 'string') {\n data = await fetch(url);\n // URL is Blob or File, fetchFile handles it (alt: we could generate ObjectURL here)\n }\n\n if (isBlob(url)) {\n // The fetch response object will contain blob.name\n // @ts-expect-error TODO - This may not work for overridden fetch functions\n data = await fetch(url);\n }\n\n if (typeof url === 'string') {\n const normalizedOptions = normalizeLoaderOptions(resolvedOptions || {});\n if (!normalizedOptions.core?.baseUrl) {\n resolvedOptions = {\n ...resolvedOptions,\n core: {\n ...resolvedOptions?.core,\n baseUrl: url\n }\n };\n }\n }\n\n // Data is loaded (at least we have a `Response` object) so time to hand over to `parse`\n // return await parse(data, loaders as Loader[], options);\n return Array.isArray(resolvedLoaders)\n ? await parse(data, resolvedLoaders, resolvedOptions) // loader array overload\n : await parse(data, resolvedLoaders, resolvedOptions); // single loader overload\n}\n","// Version constant cannot be imported, it needs to correspond to the build version of **this** module.\n// __VERSION__ is injected by babel-plugin-version-inline\n// @ts-ignore TS2304: Cannot find name '__VERSION__'.\nexport const VERSION = typeof __VERSION__ !== 'undefined' ? __VERSION__ : 'latest';\n","import {isBrowser} from '@loaders.gl/loader-utils';\nimport type {ImageTypeEnum} from '../../types';\n\n// @ts-ignore TS2339: Property does not exist on type\nconst parseImageNode = globalThis.loaders?.parseImageNode;\n\nconst IMAGE_SUPPORTED = typeof Image !== 'undefined'; // NOTE: \"false\" positives if jsdom is installed\nconst IMAGE_BITMAP_SUPPORTED = typeof ImageBitmap !== 'undefined';\nconst NODE_IMAGE_SUPPORTED = Boolean(parseImageNode);\nconst DATA_SUPPORTED = isBrowser ? true : NODE_IMAGE_SUPPORTED;\n\n/**\n * Checks if a loaders.gl image type is supported\n * @param type image type string\n */\nexport function isImageTypeSupported(type: string): boolean {\n switch (type) {\n case 'auto':\n // Should only ever be false in Node.js, if polyfills have not been installed...\n return IMAGE_BITMAP_SUPPORTED || IMAGE_SUPPORTED || DATA_SUPPORTED;\n\n case 'imagebitmap':\n return IMAGE_BITMAP_SUPPORTED;\n case 'image':\n return IMAGE_SUPPORTED;\n case 'data':\n return DATA_SUPPORTED;\n\n default:\n throw new Error(`@loaders.gl/images: image ${type} not supported in this environment`);\n }\n}\n\n/**\n * Returns the \"most performant\" supported image type on this platform\n * @returns image type string\n */\nexport function getDefaultImageType(): ImageTypeEnum {\n if (IMAGE_BITMAP_SUPPORTED) {\n return 'imagebitmap';\n }\n if (IMAGE_SUPPORTED) {\n return 'image';\n }\n if (DATA_SUPPORTED) {\n return 'data';\n }\n\n // This should only happen in Node.js\n throw new Error('Install \\'@loaders.gl/polyfills\\' to parse images under Node.js');\n}\n","import type {ImageType, ImageTypeEnum, ImageDataType} from '../../types';\n\nexport function isImage(image: ImageType): boolean {\n return Boolean(getImageTypeOrNull(image));\n}\n\nexport function deleteImage(image: ImageType): void {\n switch (getImageType(image)) {\n case 'imagebitmap':\n (image as ImageBitmap).close();\n break;\n default:\n // Nothing to do for images and image data objects\n }\n}\n\nexport function getImageType(image: ImageType): ImageTypeEnum {\n const format = getImageTypeOrNull(image);\n if (!format) {\n throw new Error('Not an image');\n }\n return format;\n}\n\nexport function getImageSize(image: ImageType): {width: number; height: number} {\n return getImageData(image);\n}\n\nexport function getImageData(image: ImageType): ImageDataType | ImageData {\n switch (getImageType(image)) {\n case 'data':\n return image as unknown as ImageData;\n\n case 'image':\n case 'imagebitmap':\n // Extract the image data from the image via a canvas\n const canvas = document.createElement('canvas');\n // TODO - reuse the canvas?\n const context = canvas.getContext('2d');\n if (!context) {\n throw new Error('getImageData');\n }\n // @ts-ignore\n canvas.width = image.width;\n // @ts-ignore\n canvas.height = image.height;\n // @ts-ignore\n context.drawImage(image, 0, 0);\n // @ts-ignore\n return context.getImageData(0, 0, image.width, image.height);\n\n default:\n throw new Error('getImageData');\n }\n}\n\n// PRIVATE\n\n// eslint-disable-next-line complexity\nfunction getImageTypeOrNull(image) {\n if (typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {\n return 'imagebitmap';\n }\n if (typeof Image !== 'undefined' && image instanceof Image) {\n return 'image';\n }\n if (image && typeof image === 'object' && image.data && image.width && image.height) {\n return 'data';\n }\n return null;\n}\n","// SVG parsing has limitations, e.g:\n// https://bugs.chromium.org/p/chromium/issues/detail?id=606319\n\nconst SVG_DATA_URL_PATTERN = /^data:image\\/svg\\+xml/;\nconst SVG_URL_PATTERN = /\\.svg((\\?|#).*)?$/;\n\nexport function isSVG(url) {\n return url && (SVG_DATA_URL_PATTERN.test(url) || SVG_URL_PATTERN.test(url));\n}\n\nexport function getBlobOrSVGDataUrl(arrayBuffer: ArrayBuffer, url?: string): Blob | string {\n if (isSVG(url)) {\n // Prepare a properly tagged data URL, and load using normal mechanism\n const textDecoder = new TextDecoder();\n let xmlText = textDecoder.decode(arrayBuffer);\n // TODO Escape in browser to support e.g. Chinese characters\n try {\n if (typeof unescape === 'function' && typeof encodeURIComponent === 'function') {\n xmlText = unescape(encodeURIComponent(xmlText));\n }\n } catch (error) {\n throw new Error((error as Error).message);\n }\n // base64 encoding is safer. utf-8 fails in some browsers\n const src = `data:image/svg+xml;base64,${btoa(xmlText)}`;\n return src;\n }\n return getBlob(arrayBuffer, url);\n}\n\nexport function getBlob(arrayBuffer: ArrayBuffer, url?: string): Blob {\n if (isSVG(url)) {\n // https://bugs.chromium.org/p/chromium/issues/detail?id=606319\n // return new Blob([new Uint8Array(arrayBuffer)], {type: 'image/svg+xml'});\n throw new Error('SVG cannot be parsed directly to imagebitmap');\n }\n // TODO - how to determine mime type? Param? Sniff here?\n return new Blob([new Uint8Array(arrayBuffer)]); // MIME type not needed?\n}\n","import type {ImageLoaderOptions} from '../../image-loader';\nimport {getBlobOrSVGDataUrl} from './svg-utils';\n\n// Parses html image from array buffer\nexport async function parseToImage(\n arrayBuffer: ArrayBuffer,\n options: ImageLoaderOptions,\n url?: string\n): Promise {\n // Note: image parsing requires conversion to Blob (for createObjectURL).\n // Potentially inefficient for not using `response.blob()` (and for File / Blob inputs)...\n // But presumably not worth adding 'blob' flag to loader objects?\n\n const blobOrDataUrl = getBlobOrSVGDataUrl(arrayBuffer, url);\n const URL = self.URL || self.webkitURL;\n const objectUrl = typeof blobOrDataUrl !== 'string' && URL.createObjectURL(blobOrDataUrl);\n try {\n return await loadToImage(objectUrl || blobOrDataUrl, options);\n } finally {\n if (objectUrl) {\n URL.revokeObjectURL(objectUrl);\n }\n }\n}\n\nexport async function loadToImage(url, options): Promise {\n const image = new Image();\n image.src = url;\n\n // The `image.onload()` callback does not guarantee that the image has been decoded\n // so a main thread \"freeze\" can be incurred when using the image for the first time.\n // `Image.decode()` returns a promise that completes when image is decoded.\n\n // https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/decode\n // Note: When calling `img.decode()`, we do not need to wait for `img.onload()`\n // Note: `HTMLImageElement.decode()` is not available in Edge and IE11\n if (options.image && options.image.decode && image.decode) {\n await image.decode();\n return image;\n }\n\n // Create a promise that tracks onload/onerror callbacks\n return await new Promise((resolve, reject) => {\n try {\n image.onload = () => resolve(image);\n image.onerror = (error) => {\n const message = error instanceof Error ? error.message : 'error';\n reject(new Error(message));\n };\n } catch (error) {\n reject(error);\n }\n });\n}\n","import type {ImageLoaderOptions} from '../../image-loader';\nimport {isSVG, getBlob} from './svg-utils';\nimport {parseToImage} from './parse-to-image';\n\nlet imagebitmapOptionsSupported = true;\n\n/**\n * Asynchronously parses an array buffer into an ImageBitmap - this contains the decoded data\n * ImageBitmaps are supported on worker threads, but not supported on Edge, IE11 and Safari\n * https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap#Browser_compatibility\n *\n * TODO - createImageBitmap supports source rect (5 param overload), pass through?\n */\nexport async function parseToImageBitmap(\n arrayBuffer: ArrayBuffer,\n options: ImageLoaderOptions,\n url?: string\n): Promise {\n let blob;\n\n // Cannot parse SVG directly to ImageBitmap, parse to Image first\n if (isSVG(url)) {\n // Note: this only works on main thread\n const image = await parseToImage(arrayBuffer, options, url);\n blob = image;\n } else {\n // Create blob from the array buffer\n blob = getBlob(arrayBuffer, url);\n }\n\n const imagebitmapOptions = (options && options.imagebitmap) as\n | ImageBitmapOptions\n | null\n | undefined;\n\n return await safeCreateImageBitmap(blob, imagebitmapOptions);\n}\n\n/**\n * Safely creates an imageBitmap with options\n * *\n * Firefox crashes if imagebitmapOptions is supplied\n * Avoid supplying if not provided or supported, remember if not supported\n */\nasync function safeCreateImageBitmap(\n blob: Blob,\n imagebitmapOptions: ImageBitmapOptions | null = null\n): Promise {\n if (isEmptyObject(imagebitmapOptions) || !imagebitmapOptionsSupported) {\n imagebitmapOptions = null;\n }\n\n if (imagebitmapOptions) {\n try {\n // @ts-ignore Options\n return await createImageBitmap(blob, imagebitmapOptions);\n } catch (error) {\n console.warn(error); // eslint-disable-line\n imagebitmapOptionsSupported = false;\n }\n }\n\n return await createImageBitmap(blob);\n}\n\nfunction isEmptyObject(object: object | null | undefined) {\n if (!object) {\n return true;\n }\n\n for (const key in object) {\n if (Object.prototype.hasOwnProperty.call(object, key)) {\n return false;\n }\n }\n\n return true;\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n// code adapted from https://github.com/sindresorhus/file-type under MIT license\n\n/**\n * Box is a container format that can contain a variety of media related files,\n * so we want to return information about which type of file is actually contained inside\n */\nexport type BoxFileType = {extension: string; mimeType: string};\n\n/**\n * Tests if a buffer is in ISO base media file format (ISOBMFF) @see https://en.wikipedia.org/wiki/ISO_base_media_file_format\n * (ISOBMFF is a media container standard based on the Apple QuickTime container format)\n */\nexport function getISOBMFFMediaType(buffer: Uint8Array): BoxFileType | null {\n // Almost all ISO base media files start with `ftyp` box. (It's not required to be first, but it's recommended to be.)\n if (!checkString(buffer, 'ftyp', 4)) {\n return null;\n }\n\n // Extra check: test for 8859-1 printable characters (for simplicity, it's a mask which also catches one non-printable character).\n if ((buffer[8] & 0x60) === 0x00) {\n return null;\n }\n\n // `ftyp` box must contain a brand major identifier, which must consist of ISO 8859-1 printable characters.\n return decodeMajorBrand(buffer);\n}\n\n/**\n * brands explained @see https://github.com/strukturag/libheif/issues/83\n * code adapted from @see https://github.com/sindresorhus/file-type/blob/main/core.js#L489-L492\n */\nexport function decodeMajorBrand(buffer: Uint8Array): BoxFileType | null {\n const brandMajor = getUTF8String(buffer, 8, 12).replace('\\0', ' ').trim();\n\n switch (brandMajor) {\n case 'avif':\n case 'avis':\n return {extension: 'avif', mimeType: 'image/avif'};\n default:\n return null;\n }\n // We don't need these now, but they are easy to add\n // case 'mif1':\n // return {extension: 'heic', mimeType: 'image/heif'};\n // case 'msf1':\n // return {extension: 'heic', mimeType: 'image/heif-sequence'};\n // case 'heic':\n // case 'heix':\n // return {extension: 'heic', mimeType: 'image/heic'};\n // case 'hevc':\n // case 'hevx':\n // return {extension: 'heic', mimeType: 'image/heic-sequence'};\n // case 'qt':\n // return {ext: 'mov', mime: 'video/quicktime'};\n // case 'M4V':\n // case 'M4VH':\n // case 'M4VP':\n // return {ext: 'm4v', mime: 'video/x-m4v'};\n // case 'M4P':\n // return {ext: 'm4p', mime: 'video/mp4'};\n // case 'M4B':\n // return {ext: 'm4b', mime: 'audio/mp4'};\n // case 'M4A':\n // return {ext: 'm4a', mime: 'audio/x-m4a'};\n // case 'F4V':\n // return {ext: 'f4v', mime: 'video/mp4'};\n // case 'F4P':\n // return {ext: 'f4p', mime: 'video/mp4'};\n // case 'F4A':\n // return {ext: 'f4a', mime: 'audio/mp4'};\n // case 'F4B':\n // return {ext: 'f4b', mime: 'audio/mp4'};\n // case 'crx':\n // return {ext: 'cr3', mime: 'image/x-canon-cr3'};\n // default:\n // if (brandMajor.startsWith('3g')) {\n // if (brandMajor.startsWith('3g2')) {\n // return {ext: '3g2', mime: 'video/3gpp2'};\n // }\n // return {ext: '3gp', mime: 'video/3gpp'};\n // }\n // return {ext: 'mp4', mime: 'video/mp4'};\n}\n\n/** Interpret a chunk of bytes as a UTF8 string */\nfunction getUTF8String(array: Uint8Array, start: number, end: number): string {\n return String.fromCharCode(...array.slice(start, end));\n}\n\nfunction stringToBytes(string: string): number[] {\n return [...string].map((character) => character.charCodeAt(0));\n}\n\nfunction checkString(buffer: ArrayLike, header: string, offset: number = 0): boolean {\n const headerBytes = stringToBytes(header);\n\n for (let i = 0; i < headerBytes.length; ++i) {\n if (headerBytes[i] !== buffer[i + offset]) {\n return false;\n }\n }\n\n return true;\n}\n","// Attributions\n// * Based on binary-gltf-utils under MIT license: Copyright (c) 2016-17 Karl Cheng\n\nimport {getISOBMFFMediaType} from './parse-isobmff-binary';\n\n/** MIME type, width and height extracted from binary compressed image data */\nexport type BinaryImageMetadata = {\n mimeType: string;\n width: number;\n height: number;\n};\n\nconst BIG_ENDIAN = false;\nconst LITTLE_ENDIAN = true;\n\n/**\n * Extracts `{mimeType, width and height}` from a memory buffer containing a known image format\n * Currently supports `image/png`, `image/jpeg`, `image/bmp` and `image/gif`.\n * @param binaryData: DataView | ArrayBuffer image file memory to parse\n * @returns metadata or null if memory is not a valid image file format layout.\n */\nexport function getBinaryImageMetadata(\n binaryData: DataView | ArrayBuffer\n): BinaryImageMetadata | null {\n const dataView = toDataView(binaryData);\n return (\n getPngMetadata(dataView) ||\n getJpegMetadata(dataView) ||\n getGifMetadata(dataView) ||\n getBmpMetadata(dataView) ||\n getISOBMFFMetadata(dataView)\n );\n}\n\n// ISOBMFF\n\nfunction getISOBMFFMetadata(binaryData: DataView | ArrayBuffer): BinaryImageMetadata | null {\n const buffer = new Uint8Array(binaryData instanceof DataView ? binaryData.buffer : binaryData);\n const mediaType = getISOBMFFMediaType(buffer);\n if (!mediaType) {\n return null;\n }\n return {\n mimeType: mediaType.mimeType,\n // TODO - decode width and height\n width: 0,\n height: 0\n };\n}\n\n// PNG\n\nfunction getPngMetadata(binaryData: DataView | ArrayBuffer): BinaryImageMetadata | null {\n const dataView = toDataView(binaryData);\n // Check file contains the first 4 bytes of the PNG signature.\n const isPng = dataView.byteLength >= 24 && dataView.getUint32(0, BIG_ENDIAN) === 0x89504e47;\n if (!isPng) {\n return null;\n }\n\n // Extract size from a binary PNG file\n return {\n mimeType: 'image/png',\n width: dataView.getUint32(16, BIG_ENDIAN),\n height: dataView.getUint32(20, BIG_ENDIAN)\n };\n}\n\n// GIF\n\n// Extract size from a binary GIF file\n// TODO: GIF is not this simple\nfunction getGifMetadata(binaryData: DataView | ArrayBuffer): BinaryImageMetadata | null {\n const dataView = toDataView(binaryData);\n // Check first 4 bytes of the GIF signature (\"GIF8\").\n const isGif = dataView.byteLength >= 10 && dataView.getUint32(0, BIG_ENDIAN) === 0x47494638;\n if (!isGif) {\n return null;\n }\n\n // GIF is little endian.\n return {\n mimeType: 'image/gif',\n width: dataView.getUint16(6, LITTLE_ENDIAN),\n height: dataView.getUint16(8, LITTLE_ENDIAN)\n };\n}\n\n// BMP\n\n// TODO: BMP is not this simple\nexport function getBmpMetadata(binaryData: DataView | ArrayBuffer): BinaryImageMetadata | null {\n const dataView = toDataView(binaryData);\n // Check magic number is valid (first 2 characters should be \"BM\").\n // The mandatory bitmap file header is 14 bytes long.\n const isBmp =\n dataView.byteLength >= 14 &&\n dataView.getUint16(0, BIG_ENDIAN) === 0x424d &&\n dataView.getUint32(2, LITTLE_ENDIAN) === dataView.byteLength;\n\n if (!isBmp) {\n return null;\n }\n\n // BMP is little endian.\n return {\n mimeType: 'image/bmp',\n width: dataView.getUint32(18, LITTLE_ENDIAN),\n height: dataView.getUint32(22, LITTLE_ENDIAN)\n };\n}\n\n// JPEG\n\n// Extract width and height from a binary JPEG file\nfunction getJpegMetadata(binaryData: DataView | ArrayBuffer): BinaryImageMetadata | null {\n const dataView = toDataView(binaryData);\n // Check file contains the JPEG \"start of image\" (SOI) marker\n // followed by another marker.\n const isJpeg =\n dataView.byteLength >= 3 &&\n dataView.getUint16(0, BIG_ENDIAN) === 0xffd8 &&\n dataView.getUint8(2) === 0xff;\n\n if (!isJpeg) {\n return null;\n }\n\n const {tableMarkers, sofMarkers} = getJpegMarkers();\n\n // Exclude the two byte SOI marker.\n let i = 2;\n while (i + 9 < dataView.byteLength) {\n const marker = dataView.getUint16(i, BIG_ENDIAN);\n\n // The frame that contains the width and height of the JPEG image.\n if (sofMarkers.has(marker)) {\n return {\n mimeType: 'image/jpeg',\n height: dataView.getUint16(i + 5, BIG_ENDIAN), // Number of lines\n width: dataView.getUint16(i + 7, BIG_ENDIAN) // Number of pixels per line\n };\n }\n\n // Miscellaneous tables/data preceding the frame header.\n if (!tableMarkers.has(marker)) {\n return null;\n }\n\n // Length includes size of length parameter but not the two byte header.\n i += 2;\n i += dataView.getUint16(i, BIG_ENDIAN);\n }\n\n return null;\n}\n\nfunction getJpegMarkers() {\n // Tables/misc header markers.\n // DQT, DHT, DAC, DRI, COM, APP_n\n const tableMarkers = new Set([0xffdb, 0xffc4, 0xffcc, 0xffdd, 0xfffe]);\n for (let i = 0xffe0; i < 0xfff0; ++i) {\n tableMarkers.add(i);\n }\n\n // SOF markers and DHP marker.\n // These markers are after tables/misc data.\n const sofMarkers = new Set([\n 0xffc0, 0xffc1, 0xffc2, 0xffc3, 0xffc5, 0xffc6, 0xffc7, 0xffc9, 0xffca, 0xffcb, 0xffcd, 0xffce,\n 0xffcf, 0xffde\n ]);\n\n return {tableMarkers, sofMarkers};\n}\n\n// TODO - move into image module?\nfunction toDataView(data) {\n if (data instanceof DataView) {\n return data;\n }\n if (ArrayBuffer.isView(data)) {\n return new DataView(data.buffer);\n }\n\n // TODO: make these functions work for Node.js buffers?\n // if (bufferToArrayBuffer) {\n // data = bufferToArrayBuffer(data);\n // }\n\n // Careful - Node Buffers will look like ArrayBuffers (keep after isBuffer)\n if (data instanceof ArrayBuffer) {\n return new DataView(data);\n }\n throw new Error('toDataView');\n}\n","import type {ImageLoaderOptions} from '../../image-loader';\nimport type {ImageDataType} from '../../types';\nimport {assert} from '@loaders.gl/loader-utils';\nimport {getBinaryImageMetadata} from '../category-api/binary-image-api';\n\n// Note: These types should be consistent with loaders.gl/polyfills\n\ntype NDArray = {\n shape: number[];\n data: Uint8Array;\n width: number;\n height: number;\n components: number;\n layers: number[];\n};\n\ntype ParseImageNode = (arrayBuffer: ArrayBuffer, mimeType: string) => Promise;\n\n// Use polyfills if installed to parsed image using get-pixels\nexport async function parseToNodeImage(\n arrayBuffer: ArrayBuffer,\n options: ImageLoaderOptions\n): Promise {\n const {mimeType} = getBinaryImageMetadata(arrayBuffer) || {};\n\n // @ts-ignore\n const parseImageNode: ParseImageNode = globalThis.loaders?.parseImageNode;\n assert(parseImageNode); // '@loaders.gl/polyfills not installed'\n\n // @ts-expect-error TODO should we throw error in this case?\n return await parseImageNode(arrayBuffer, mimeType);\n}\n","import type {LoaderContext} from '@loaders.gl/loader-utils';\nimport {assert} from '@loaders.gl/loader-utils';\nimport type {ImageType} from '../../types';\nimport type {ImageLoaderOptions} from '../../image-loader';\nimport {isImageTypeSupported, getDefaultImageType} from '../category-api/image-type';\nimport {getImageData} from '../category-api/parsed-image-api';\nimport {parseToImage} from './parse-to-image';\nimport {parseToImageBitmap} from './parse-to-image-bitmap';\nimport {parseToNodeImage} from './parse-to-node-image';\n\n// Parse to platform defined image type (data on node, ImageBitmap or HTMLImage on browser)\n// eslint-disable-next-line complexity\nexport async function parseImage(\n arrayBuffer: ArrayBuffer,\n options?: ImageLoaderOptions,\n context?: LoaderContext\n): Promise {\n options = options || {};\n const imageOptions = options.image || {};\n\n // The user can request a specific output format via `options.image.type`\n const imageType = imageOptions.type || 'auto';\n\n const {url} = context || {};\n\n // Note: For options.image.type === `data`, we may still need to load as `image` or `imagebitmap`\n const loadType = getLoadableImageType(imageType);\n\n let image;\n switch (loadType) {\n case 'imagebitmap':\n image = await parseToImageBitmap(arrayBuffer, options, url);\n break;\n case 'image':\n image = await parseToImage(arrayBuffer, options, url);\n break;\n case 'data':\n // Node.js loads imagedata directly\n image = await parseToNodeImage(arrayBuffer, options);\n break;\n default:\n assert(false);\n }\n\n // Browser: if options.image.type === 'data', we can now extract data from the loaded image\n if (imageType === 'data') {\n image = getImageData(image);\n }\n\n return image;\n}\n\n// Get a loadable image type from image type\nfunction getLoadableImageType(type) {\n switch (type) {\n case 'auto':\n case 'data':\n // Browser: For image data we need still need to load using an image format\n // Node: the default image type is `data`.\n return getDefaultImageType();\n default:\n // Throw an error if not supported\n isImageTypeSupported(type);\n return type;\n }\n}\n","import type {LoaderWithParser, StrictLoaderOptions} from '@loaders.gl/loader-utils';\nimport type {ImageType} from './types';\n// import type { ImageType } from '@loaders.gl/schema';\nimport {VERSION} from './lib/utils/version';\nimport {parseImage} from './lib/parsers/parse-image';\nimport {getBinaryImageMetadata} from './lib/category-api/binary-image-api';\n\nconst EXTENSIONS = ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'ico', 'svg', 'avif'];\nconst MIME_TYPES = [\n 'image/png',\n 'image/jpeg',\n 'image/gif',\n 'image/webp',\n 'image/avif',\n 'image/bmp',\n 'image/vnd.microsoft.icon',\n 'image/svg+xml'\n];\n\nexport type ImageLoaderOptions = StrictLoaderOptions & {\n image?: {\n type?: 'auto' | 'data' | 'imagebitmap' | 'image';\n decode?: boolean;\n imagebitmap?: ImageBitmapOptions;\n };\n};\n\nconst DEFAULT_IMAGE_LOADER_OPTIONS: ImageLoaderOptions = {\n image: {\n type: 'auto',\n decode: true // if format is HTML\n }\n // imagebitmap: {} - passes (platform dependent) parameters to ImageBitmap constructor\n};\n\n/**\n * Loads a platform-specific image type\n * Note: This type can be used as input data to WebGL texture creation\n */\nexport const ImageLoader = {\n dataType: null as unknown as ImageType,\n batchType: null as never,\n id: 'image',\n module: 'images',\n name: 'Images',\n version: VERSION,\n mimeTypes: MIME_TYPES,\n extensions: EXTENSIONS,\n parse: parseImage,\n // TODO: byteOffset, byteLength;\n tests: [(arrayBuffer) => Boolean(getBinaryImageMetadata(new DataView(arrayBuffer)))],\n options: DEFAULT_IMAGE_LOADER_OPTIONS\n} as const satisfies LoaderWithParser;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Log} from '@probe.gl/log';\n\nconst defaultLogger: Log = new Log({id: 'deck'});\n\nexport default defaultLogger;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Log} from '@probe.gl/log';\n\nconst logState: {\n attributeUpdateStart: number;\n attributeManagerUpdateStart: number;\n attributeUpdateMessages: string[];\n} = {\n attributeUpdateStart: -1,\n attributeManagerUpdateStart: -1,\n attributeUpdateMessages: []\n};\n\nconst LOG_LEVEL_MAJOR_UPDATE = 1; // Events with direct perf impact\nconst LOG_LEVEL_MINOR_UPDATE = 2; // Events that may affect perf\nconst LOG_LEVEL_UPDATE_DETAIL = 3;\nconst LOG_LEVEL_INFO = 4;\nconst LOG_LEVEL_DRAW = 2;\n\nexport const getLoggers = (log: Log): Record => ({\n /* Layer events */\n\n 'layer.changeFlag': (layer, key, flags) => {\n log.log(LOG_LEVEL_UPDATE_DETAIL, `${layer.id} ${key}: `, flags[key])();\n },\n\n 'layer.initialize': layer => {\n log.log(LOG_LEVEL_MAJOR_UPDATE, `Initializing ${layer}`)();\n },\n 'layer.update': (layer, needsUpdate) => {\n if (needsUpdate) {\n const flags = layer.getChangeFlags();\n log.log(\n LOG_LEVEL_MINOR_UPDATE,\n `Updating ${layer} because: ${Object.keys(flags)\n .filter(key => flags[key])\n .join(', ')}`\n )();\n } else {\n log.log(LOG_LEVEL_INFO, `${layer} does not need update`)();\n }\n },\n 'layer.matched': (layer, changed) => {\n if (changed) {\n log.log(LOG_LEVEL_INFO, `Matched ${layer}, state transfered`)();\n }\n },\n 'layer.finalize': layer => {\n log.log(LOG_LEVEL_MAJOR_UPDATE, `Finalizing ${layer}`)();\n },\n\n /* CompositeLayer events */\n\n 'compositeLayer.renderLayers': (layer, updated, subLayers) => {\n if (updated) {\n log.log(\n LOG_LEVEL_MINOR_UPDATE,\n `Composite layer rendered new subLayers ${layer}`,\n subLayers\n )();\n } else {\n log.log(LOG_LEVEL_INFO, `Composite layer reused subLayers ${layer}`, subLayers)();\n }\n },\n\n /* LayerManager events */\n\n 'layerManager.setLayers': (layerManager, updated, layers) => {\n if (updated) {\n log.log(LOG_LEVEL_MINOR_UPDATE, `Updating ${layers.length} deck layers`)();\n }\n },\n\n 'layerManager.activateViewport': (layerManager, viewport) => {\n log.log(LOG_LEVEL_UPDATE_DETAIL, 'Viewport changed', viewport)();\n },\n\n /* AttributeManager events */\n\n 'attributeManager.invalidate': (attributeManager, trigger, attributeNames) => {\n log.log(\n LOG_LEVEL_MAJOR_UPDATE,\n attributeNames\n ? `invalidated attributes ${attributeNames} (${trigger}) for ${attributeManager.id}`\n : `invalidated all attributes for ${attributeManager.id}`\n )();\n },\n\n 'attributeManager.updateStart': attributeManager => {\n logState.attributeUpdateMessages.length = 0;\n logState.attributeManagerUpdateStart = Date.now();\n },\n 'attributeManager.updateEnd': (attributeManager, numInstances) => {\n const timeMs = Math.round(Date.now() - logState.attributeManagerUpdateStart);\n log.groupCollapsed(\n LOG_LEVEL_MINOR_UPDATE,\n `Updated attributes for ${numInstances} instances in ${attributeManager.id} in ${timeMs}ms`\n )();\n for (const updateMessage of logState.attributeUpdateMessages) {\n log.log(LOG_LEVEL_UPDATE_DETAIL, updateMessage)();\n }\n log.groupEnd(LOG_LEVEL_MINOR_UPDATE)();\n },\n\n /* Attribute events */\n\n 'attribute.updateStart': attribute => {\n logState.attributeUpdateStart = Date.now();\n },\n 'attribute.allocate': (attribute, numInstances) => {\n const message = `${attribute.id} allocated ${numInstances}`;\n logState.attributeUpdateMessages.push(message);\n },\n 'attribute.updateEnd': (attribute, numInstances) => {\n const timeMs = Math.round(Date.now() - logState.attributeUpdateStart);\n const message = `${attribute.id} updated ${numInstances} in ${timeMs}ms`;\n logState.attributeUpdateMessages.push(message);\n },\n\n /* Render events */\n\n 'deckRenderer.renderLayers': (deckRenderer, renderStats, opts) => {\n const {pass, redrawReason} = opts;\n for (const status of renderStats) {\n const {totalCount, visibleCount, compositeCount, pickableCount} = status;\n const primitiveCount = totalCount - compositeCount;\n const hiddenCount = primitiveCount - visibleCount;\n\n log.log(\n LOG_LEVEL_DRAW,\n `RENDER #${deckRenderer.renderCount} \\\n ${visibleCount} (of ${totalCount} layers) to ${pass} because ${redrawReason} \\\n (${hiddenCount} hidden, ${compositeCount} composite ${pickableCount} pickable)`\n )();\n }\n }\n});\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport deckLog from '../utils/log';\nimport {getLoggers} from './loggers';\n\n/* debug utility */\n\nlet loggers: Record = {};\n\n// Conditionally load default loggers in development mode\n// eslint-disable-next-line\nif (process.env.NODE_ENV !== 'production') {\n loggers = getLoggers(deckLog);\n}\n\nexport function register(handlers: Record): void {\n loggers = handlers;\n}\n\nexport default function debug(eventType: string, arg1?: any, arg2?: any, arg3?: any): void {\n if (deckLog.level > 0 && loggers[eventType]) {\n // Not using rest parameters to defeat perf hit from array construction\n loggers[eventType].call(null, arg1, arg2, arg3);\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Loader} from '@loaders.gl/loader-utils';\n\nfunction isJSON(text: string): boolean {\n const firstChar = text[0];\n const lastChar = text[text.length - 1];\n return (firstChar === '{' && lastChar === '}') || (firstChar === '[' && lastChar === ']');\n}\n\n// A light weight version instead of @loaders.gl/json (stream processing etc.)\nexport default {\n dataType: null as any,\n batchType: null as never,\n id: 'JSON',\n name: 'JSON',\n module: '',\n version: '',\n options: {},\n extensions: ['json', 'geojson'],\n mimeTypes: ['application/json', 'application/geo+json'],\n testText: isJSON,\n parseTextSync: JSON.parse\n} as Loader;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {registerLoaders} from '@loaders.gl/core';\nimport {ImageLoader} from '@loaders.gl/images';\n\nimport log from '../utils/log';\nimport {register} from '../debug/index';\nimport jsonLoader from '../utils/json-loader';\n\ndeclare global {\n const __VERSION__: string;\n}\n\nfunction checkVersion() {\n // Version detection using typescript plugin.\n // Fallback for tests and SSR since global variable is defined by esbuild.\n const version =\n typeof __VERSION__ !== 'undefined'\n ? __VERSION__\n : globalThis.DECK_VERSION || 'untranspiled source';\n\n // Note: a `deck` object not created by deck.gl may exist in the global scope\n const existingVersion = globalThis.deck && globalThis.deck.VERSION;\n\n if (existingVersion && existingVersion !== version) {\n throw new Error(`deck.gl - multiple versions detected: ${existingVersion} vs ${version}`);\n }\n\n if (!existingVersion) {\n log.log(1, `deck.gl ${version}`)();\n\n globalThis.deck = {\n ...globalThis.deck,\n VERSION: version,\n version,\n log,\n // experimental\n _registerLoggers: register\n };\n\n registerLoaders([\n jsonLoader,\n // @ts-expect-error non-standard Loader format\n [ImageLoader, {imagebitmap: {premultiplyAlpha: 'none'}}]\n ]);\n }\n\n return version;\n}\n\nexport const VERSION = checkVersion();\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// Recommendation is to ignore message but current test suite checks agains the\n// message so keep it for now.\nexport function assert(condition: unknown, message?: string): void {\n if (!condition) {\n const error = new Error(message || 'shadertools: assertion failed.');\n Error.captureStackTrace?.(error, assert);\n throw error;\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {assert} from '../utils/assert';\n\n/**\n * For use by shader module and shader pass writers to describe the types of the\n * properties they expose (properties ultimately map to uniforms).\n */\nexport type PropType =\n | {\n type?: string;\n value?: unknown;\n max?: number;\n min?: number;\n softMax?: number;\n softMin?: number;\n hint?: string;\n /** @deprecated internal uniform */\n private?: boolean;\n }\n | number;\n\n/**\n * Internal property validators generated by processing the prop types ,\n * The `validate()` method can be used to validate the type of properties passed in to\n * shader module or shader pass\n */\nexport type PropValidator = {\n type: string;\n value?: unknown;\n max?: number;\n min?: number;\n private?: boolean;\n validate?(value: unknown, propDef: PropValidator): boolean;\n};\n\n/** Minimal validators for number and array types */\nconst DEFAULT_PROP_VALIDATORS: Record = {\n number: {\n type: 'number',\n validate(value: unknown, propType: PropType) {\n return (\n Number.isFinite(value) &&\n typeof propType === 'object' &&\n (propType.max === undefined || (value as number) <= propType.max) &&\n (propType.min === undefined || (value as number) >= propType.min)\n );\n }\n },\n array: {\n type: 'array',\n validate(value: unknown, propType: PropType) {\n return Array.isArray(value) || ArrayBuffer.isView(value);\n }\n }\n};\n\n/**\n * Parse a list of property types into property definitions that can be used to validate\n * values passed in by applications.\n * @param propTypes\n * @returns\n */\nexport function makePropValidators(\n propTypes: Record\n): Record {\n const propValidators: Record = {};\n for (const [name, propType] of Object.entries(propTypes)) {\n propValidators[name] = makePropValidator(propType);\n }\n return propValidators;\n}\n\n/**\n * Validate a map of user supplied properties against a map of validators\n * Inject default values when user doesn't supply a property\n * @param properties\n * @param propValidators\n * @returns\n */\nexport function getValidatedProperties(\n properties: Record,\n propValidators: Record,\n errorMessage: string\n): Record {\n const validated: Record = {};\n\n for (const [key, propsValidator] of Object.entries(propValidators)) {\n if (properties && key in properties && !propsValidator.private) {\n if (propsValidator.validate) {\n assert(\n propsValidator.validate(properties[key], propsValidator),\n `${errorMessage}: invalid ${key}`\n );\n }\n validated[key] = properties[key];\n } else {\n // property not supplied - use default value\n validated[key] = propsValidator.value;\n }\n }\n\n // TODO - warn for unused properties that don't match a validator?\n\n return validated;\n}\n\n/**\n * Creates a property validator for a prop type. Either contains:\n * - a valid prop type object ({type, ...})\n * - or just a default value, in which case type and name inference is used\n */\nfunction makePropValidator(propType: PropType): PropValidator {\n let type = getTypeOf(propType);\n\n if (type !== 'object') {\n return {value: propType, ...DEFAULT_PROP_VALIDATORS[type], type};\n }\n\n // Special handling for objects\n if (typeof propType === 'object') {\n if (!propType) {\n return {type: 'object', value: null};\n }\n if (propType.type !== undefined) {\n return {...propType, ...DEFAULT_PROP_VALIDATORS[propType.type], type: propType.type};\n }\n // If no type and value this object is likely the value\n if (propType.value === undefined) {\n return {type: 'object', value: propType};\n }\n\n type = getTypeOf(propType.value);\n return {...propType, ...DEFAULT_PROP_VALIDATORS[type], type};\n }\n\n throw new Error('props');\n}\n\n/**\n * \"improved\" version of javascript typeof that can distinguish arrays and null values\n */\nfunction getTypeOf(value: unknown): string {\n if (Array.isArray(value) || ArrayBuffer.isView(value)) {\n return 'array';\n }\n return typeof value;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport const MODULE_INJECTORS_VS = /* glsl */ `\\\n#ifdef MODULE_LOGDEPTH\n logdepth_adjustPosition(gl_Position);\n#endif\n`;\n\nexport const MODULE_INJECTORS_FS = /* glsl */ `\\\n#ifdef MODULE_MATERIAL\n fragColor = material_filterColor(fragColor);\n#endif\n\n#ifdef MODULE_LIGHTING\n fragColor = lighting_filterColor(fragColor);\n#endif\n\n#ifdef MODULE_FOG\n fragColor = fog_filterColor(fragColor);\n#endif\n\n#ifdef MODULE_PICKING\n fragColor = picking_filterHighlightColor(fragColor);\n fragColor = picking_filterPickingColor(fragColor);\n#endif\n\n#ifdef MODULE_LOGDEPTH\n logdepth_setFragDepth();\n#endif\n`;\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {MODULE_INJECTORS_VS, MODULE_INJECTORS_FS} from '../../module-injectors';\nimport {assert} from '../utils/assert';\n\n// TODO - experimental\nconst MODULE_INJECTORS = {\n vertex: MODULE_INJECTORS_VS,\n fragment: MODULE_INJECTORS_FS\n};\n\nconst REGEX_START_OF_MAIN = /void\\s+main\\s*\\([^)]*\\)\\s*\\{\\n?/; // Beginning of main\nconst REGEX_END_OF_MAIN = /}\\n?[^{}]*$/; // End of main, assumes main is last function\nconst fragments: string[] = [];\n\nexport const DECLARATION_INJECT_MARKER = '__LUMA_INJECT_DECLARATIONS__';\n\n/**\n *\n */\nexport type ShaderInjection = {\n injection: string;\n order: number;\n};\n\n/**\n * ShaderInjections, parsed and split per shader\n */\nexport type ShaderInjections = {\n vertex: Record;\n fragment: Record;\n};\n\n/**\n *\n */\nexport function normalizeInjections(\n injections: Record\n): ShaderInjections {\n const result: ShaderInjections = {vertex: {}, fragment: {}};\n\n for (const hook in injections) {\n let injection = injections[hook];\n const stage = getHookStage(hook);\n if (typeof injection === 'string') {\n injection = {\n order: 0,\n injection\n };\n }\n\n result[stage][hook] = injection;\n }\n\n return result;\n}\n\nfunction getHookStage(hook: string): 'vertex' | 'fragment' {\n const type = hook.slice(0, 2);\n switch (type) {\n case 'vs':\n return 'vertex';\n case 'fs':\n return 'fragment';\n default:\n throw new Error(type);\n }\n}\n\n/**\n// A minimal shader injection/templating system.\n// RFC: https://github.com/visgl/luma.gl/blob/7.0-release/dev-docs/RFCs/v6.0/shader-injection-rfc.md\n * @param source \n * @param type \n * @param inject \n * @param injectStandardStubs \n * @returns \n */\n// eslint-disable-next-line complexity\nexport function injectShader(\n source: string,\n stage: 'vertex' | 'fragment',\n inject: Record,\n injectStandardStubs = false\n): string {\n const isVertex = stage === 'vertex';\n\n for (const key in inject) {\n const fragmentData = inject[key];\n fragmentData.sort((a: ShaderInjection, b: ShaderInjection): number => a.order - b.order);\n fragments.length = fragmentData.length;\n for (let i = 0, len = fragmentData.length; i < len; ++i) {\n fragments[i] = fragmentData[i].injection;\n }\n const fragmentString = `${fragments.join('\\n')}\\n`;\n switch (key) {\n // declarations are injected before the main function\n case 'vs:#decl':\n if (isVertex) {\n source = source.replace(DECLARATION_INJECT_MARKER, fragmentString);\n }\n break;\n // inject code at the beginning of the main function\n case 'vs:#main-start':\n if (isVertex) {\n source = source.replace(REGEX_START_OF_MAIN, (match: string) => match + fragmentString);\n }\n break;\n // inject code at the end of main function\n case 'vs:#main-end':\n if (isVertex) {\n source = source.replace(REGEX_END_OF_MAIN, (match: string) => fragmentString + match);\n }\n break;\n // declarations are injected before the main function\n case 'fs:#decl':\n if (!isVertex) {\n source = source.replace(DECLARATION_INJECT_MARKER, fragmentString);\n }\n break;\n // inject code at the beginning of the main function\n case 'fs:#main-start':\n if (!isVertex) {\n source = source.replace(REGEX_START_OF_MAIN, (match: string) => match + fragmentString);\n }\n break;\n // inject code at the end of main function\n case 'fs:#main-end':\n if (!isVertex) {\n source = source.replace(REGEX_END_OF_MAIN, (match: string) => fragmentString + match);\n }\n break;\n\n default:\n // TODO(Tarek): I think this usage should be deprecated.\n\n // inject code after key, leaving key in place\n source = source.replace(key, (match: string) => match + fragmentString);\n }\n }\n\n // Remove if it hasn't already been replaced\n source = source.replace(DECLARATION_INJECT_MARKER, '');\n\n // Finally, if requested, insert an automatic module injector chunk\n if (injectStandardStubs) {\n source = source.replace(/\\}\\s*$/, (match: string) => match + MODULE_INJECTORS[stage]);\n }\n\n return source;\n}\n\n// Takes an array of inject objects and combines them into one\nexport function combineInjects(injects: any[]): Record {\n const result: Record = {};\n assert(Array.isArray(injects) && injects.length > 1);\n injects.forEach(inject => {\n for (const key in inject) {\n result[key] = result[key] ? `${result[key]}\\n${inject[key]}` : inject[key];\n }\n });\n return result;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {UniformFormat} from '../../types';\nimport {\n PropType,\n PropValidator,\n makePropValidators,\n getValidatedProperties\n} from '../filters/prop-types';\nimport type {ShaderModuleUniformValue, UniformTypes, UniformValue} from '../utils/uniform-types';\nimport {ShaderInjection, normalizeInjections} from '../shader-assembly/shader-injections';\n\n// To avoid dependency on core module, do not import `Binding` type.\n// The ShaderModule is not concerned with the type of `Binding`,\n// it is the repsonsibility of `splitUniformsAndBindings` in\n// ShaderInputs to type the result of `getUniforms()`\ntype Binding = unknown; // import type {Binding} from '@luma.gl/core';\n\nexport type UniformInfo = {\n format?: UniformFormat;\n} & PropType;\n\nexport type ShaderModuleBindingLayout = {\n name: string;\n group: number;\n};\n\n// Helper types\ntype BindingKeys = {[K in keyof T]: T[K] extends UniformValue ? never : K}[keyof T];\ntype UniformKeys = {[K in keyof T]: T[K] extends UniformValue ? K : never}[keyof T];\nexport type PickBindings = {[K in BindingKeys>]: T[K]};\nexport type PickUniforms = {[K in UniformKeys>]: T[K]};\n\n/**\n * A shader module definition object\n *\n * @note Needs to be initialized with `initializeShaderModules`\n * @note `UniformsT` & `BindingsT` are deduced from `PropsT` by default. If\n * a custom type for `UniformsT` is used, `BindingsT` should be also be provided.\n */\nexport type ShaderModule<\n PropsT extends Record = Record,\n UniformsT extends Record = PickUniforms,\n BindingsT extends Record = PickBindings\n> = {\n /** Used for type inference not for values */\n props?: PropsT;\n /** Used for type inference, not currently used for values */\n uniforms?: UniformsT;\n /** Used for type inference, not currently used for values */\n bindings?: BindingsT;\n /** Logical bind-group assignment for bindings declared by this module */\n bindingLayout?: readonly ShaderModuleBindingLayout[];\n /** Preferred starting binding slot for this module's WGSL `@binding(auto)` declarations. */\n firstBindingSlot?: number;\n\n name: string;\n\n /** WGSL code */\n source?: string;\n /** GLSL fragment shader code */\n fs?: string;\n /** GLSL vertex shader code */\n vs?: string;\n\n /** Uniform shader types @note: Both order and types MUST match uniform block declarations in shader */\n uniformTypes?: Required>; // Record;\n /** Uniform JS prop types */\n propTypes?: Record;\n /** Default uniform values */\n defaultUniforms?: Required; // Record;\n\n /** Function that maps props to uniforms & bindings */\n getUniforms?: (\n props: Partial,\n prevUniforms?: UniformsT\n ) => Partial;\n\n defines?: Record;\n /** Injections */\n inject?: Record;\n dependencies?: ShaderModule[];\n /** Information on deprecated properties */\n deprecations?: ShaderModuleDeprecation[];\n\n /** The instance field contains information that is generated at run-time */\n instance?: {\n propValidators?: Record;\n parsedDeprecations: ShaderModuleDeprecation[];\n\n normalizedInjections: {\n vertex: Record;\n fragment: Record;\n };\n };\n};\n\n/** Use to generate deprecations when shader module is used */\nexport type ShaderModuleDeprecation = {\n type: string;\n regex?: RegExp;\n new: string;\n old: string;\n deprecated?: boolean;\n};\n\n// SHNDER MODULE API\n\nexport function initializeShaderModules(modules: ShaderModule[]): void {\n modules.map((module: ShaderModule) => initializeShaderModule(module));\n}\n\nexport function initializeShaderModule(module: ShaderModule): void {\n if (module.instance) {\n return;\n }\n\n initializeShaderModules(module.dependencies || []);\n\n const {\n propTypes = {},\n deprecations = [],\n // defines = {},\n inject = {}\n } = module;\n\n const instance: Required['instance'] = {\n normalizedInjections: normalizeInjections(inject),\n parsedDeprecations: parseDeprecationDefinitions(deprecations)\n };\n\n if (propTypes) {\n instance.propValidators = makePropValidators(propTypes);\n }\n\n module.instance = instance;\n\n // TODO(ib) - we need to apply the original prop types to the default uniforms\n let defaultProps: ShaderModule['props'] = {};\n if (propTypes) {\n defaultProps = Object.entries(propTypes).reduce(\n (obj: ShaderModule['props'], [key, propType]) => {\n // @ts-expect-error\n const value = propType?.value;\n if (value) {\n // @ts-expect-error\n obj[key] = value;\n }\n return obj;\n },\n {} as ShaderModule['props']\n );\n }\n\n module.defaultUniforms = {...module.defaultUniforms, ...defaultProps} as any;\n}\n\n/** Convert module props to uniforms */\nexport function getShaderModuleUniforms<\n ShaderModuleT extends ShaderModule<\n Record,\n Record\n >\n>(\n module: ShaderModuleT,\n props?: ShaderModuleT['props'],\n oldUniforms?: ShaderModuleT['uniforms']\n): Record {\n initializeShaderModule(module);\n\n const uniforms = oldUniforms || {...module.defaultUniforms};\n // If module has a getUniforms function, use it\n if (props && module.getUniforms) {\n return module.getUniforms(props, uniforms);\n }\n\n // Build uniforms from the uniforms array\n // @ts-expect-error\n return getValidatedProperties(props, module.instance?.propValidators, module.name);\n}\n\n/* TODO this looks like it was unused code\n _defaultGetUniforms(opts: Record = {}): Record {\n const uniforms: Record = {};\n const propTypes = this.uniforms;\n\n for (const key in propTypes) {\n const propDef = propTypes[key];\n if (key in opts && !propDef.private) {\n if (propDef.validate) {\n assert(propDef.validate(opts[key], propDef), `${this.name}: invalid ${key}`);\n }\n uniforms[key] = opts[key];\n } else {\n uniforms[key] = propDef.value;\n }\n }\n\n return uniforms;\n }\n}\n*/\n// Warn about deprecated uniforms or functions\nexport function checkShaderModuleDeprecations(\n shaderModule: ShaderModule,\n shaderSource: string,\n log: any\n): void {\n shaderModule.deprecations?.forEach(def => {\n if (def.regex?.test(shaderSource)) {\n if (def.deprecated) {\n log.deprecated(def.old, def.new)();\n } else {\n log.removed(def.old, def.new)();\n }\n }\n });\n}\n\n// HELPERS\n\nfunction parseDeprecationDefinitions(deprecations: ShaderModuleDeprecation[]) {\n deprecations.forEach(def => {\n switch (def.type) {\n case 'function':\n def.regex = new RegExp(`\\\\b${def.old}\\\\(`);\n break;\n default:\n def.regex = new RegExp(`${def.type} ${def.old};`);\n }\n });\n\n return deprecations;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {ShaderModule, initializeShaderModules} from './shader-module';\n\n// import type {ShaderModule} from '../shader-module/shader-module';\n\ntype AbstractModule = {\n name: string;\n dependencies?: AbstractModule[];\n};\n\n/**\n * Takes a list of shader module names and returns a new list of\n * shader module names that includes all dependencies, sorted so\n * that modules that are dependencies of other modules come first.\n *\n * If the shader glsl code from the returned modules is concatenated\n * in the reverse order, it is guaranteed that all functions be resolved and\n * that all function and variable definitions come before use.\n *\n * @param modules - Array of modules (inline modules or module names)\n * @return - Array of modules\n */\nexport function getShaderModuleDependencies(modules: T[]): T[] {\n initializeShaderModules(modules);\n const moduleMap: Record = {};\n const moduleDepth: Record = {};\n getDependencyGraph({modules, level: 0, moduleMap, moduleDepth});\n\n // Return a reverse sort so that dependencies come before the modules that use them\n const dependencies = Object.keys(moduleDepth)\n .sort((a, b) => moduleDepth[b] - moduleDepth[a])\n .map(name => moduleMap[name]);\n initializeShaderModules(dependencies);\n return dependencies;\n}\n\n/**\n * Recursively checks module dependencies to calculate dependency level of each module.\n *\n * @param options.modules - Array of modules\n * @param options.level - Current level\n * @param options.moduleMap -\n * @param options.moduleDepth - Current level\n * @return - Map of module name to its level\n */\n// Adds another level of dependencies to the result map\nexport function getDependencyGraph(options: {\n modules: T[];\n level: number;\n moduleMap: Record;\n moduleDepth: Record;\n}) {\n const {modules, level, moduleMap, moduleDepth} = options;\n if (level >= 5) {\n throw new Error('Possible loop in shader dependency graph');\n }\n\n // Update level on all current modules\n for (const module of modules) {\n moduleMap[module.name] = module;\n if (moduleDepth[module.name] === undefined || moduleDepth[module.name] < level) {\n moduleDepth[module.name] = level;\n }\n }\n\n // Recurse\n for (const module of modules) {\n if (module.dependencies) {\n getDependencyGraph({modules: module.dependencies, level: level + 1, moduleMap, moduleDepth});\n }\n }\n}\n\n/**\n * Takes a list of shader module names and returns a new list of\n * shader module names that includes all dependencies, sorted so\n * that modules that are dependencies of other modules come first.\n *\n * If the shader glsl code from the returned modules is concatenated\n * in the reverse order, it is guaranteed that all functions be resolved and\n * that all function and variable definitions come before use.\n *\n * @param modules - Array of modules (inline modules or module names)\n * @return - Array of modules\n */\nexport function getShaderDependencies(modules: ShaderModule[]): ShaderModule[] {\n initializeShaderModules(modules);\n const moduleMap: Record = {};\n const moduleDepth: Record = {};\n getDependencyGraph({modules, level: 0, moduleMap, moduleDepth});\n\n // Return a reverse sort so that dependencies come before the modules that use them\n modules = Object.keys(moduleDepth)\n .sort((a, b) => moduleDepth[b] - moduleDepth[a])\n .map(name => moduleMap[name]);\n initializeShaderModules(modules);\n return modules;\n}\n\n// DEPRECATED\n\n/**\n * Instantiate shader modules and resolve any dependencies\n * @deprecated Use getShaderDpendencies\n */\nexport function resolveModules(modules: ShaderModule[]): ShaderModule[] {\n return getShaderDependencies(modules);\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ShaderModule} from './shader-module';\nimport {assert} from '../utils/assert';\n\n/**\n * Shader stages supported by shader-module uniform-layout validation helpers.\n */\nexport type ShaderModuleUniformLayoutStage = 'vertex' | 'fragment' | 'wgsl';\n\n/**\n * Describes the result of comparing declared `uniformTypes` with the fields\n * found in a shader uniform block.\n */\nexport type ShaderModuleUniformLayoutValidationResult = {\n /** Name of the shader module being validated. */\n moduleName: string;\n /** Expected block name derived from the shader module name. */\n uniformBlockName: string;\n /** Shader stage that was inspected. */\n stage: ShaderModuleUniformLayoutStage;\n /** Field names declared by the module metadata. */\n expectedUniformNames: string[];\n /** Field names parsed from the shader source. */\n actualUniformNames: string[];\n /** Whether the declared and parsed field lists match exactly. */\n matches: boolean;\n};\n\n/**\n * Parsed information about one GLSL uniform block declaration.\n */\nexport type GLSLUniformBlockInfo = {\n /** Declared block type name. */\n blockName: string;\n /** Optional instance name that follows the block declaration. */\n instanceName: string | null;\n /** Raw layout qualifier text, if present. */\n layoutQualifier: string | null;\n /** Whether any explicit layout qualifier was present. */\n hasLayoutQualifier: boolean;\n /** Whether the block explicitly declares `layout(std140)`. */\n isStd140: boolean;\n /** Raw source text inside the block braces. */\n body: string;\n};\n\n/**\n * Logging surface used by validation and warning helpers.\n */\ntype Logger = {\n /** Error logger compatible with luma's deferred log API. */\n error?: (...args: unknown[]) => () => unknown;\n /** Warning logger compatible with luma's deferred log API. */\n warn?: (...args: unknown[]) => () => unknown;\n};\n\n/**\n * Matches one field declaration inside a GLSL uniform block body.\n */\nconst GLSL_UNIFORM_BLOCK_FIELD_REGEXP =\n /^(?:uniform\\s+)?(?:(?:lowp|mediump|highp)\\s+)?[A-Za-z0-9_]+(?:<[^>]+>)?\\s+([A-Za-z0-9_]+)(?:\\s*\\[[^\\]]+\\])?\\s*;/;\n/**\n * Matches full GLSL uniform block declarations, including optional layout qualifiers.\n */\nconst GLSL_UNIFORM_BLOCK_REGEXP =\n /((?:layout\\s*\\([^)]*\\)\\s*)*)uniform\\s+([A-Za-z_][A-Za-z0-9_]*)\\s*\\{([\\s\\S]*?)\\}\\s*([A-Za-z_][A-Za-z0-9_]*)?\\s*;/g;\n\n/**\n * Returns the uniform block type name expected for the supplied shader module.\n */\nexport function getShaderModuleUniformBlockName(module: ShaderModule): string {\n return `${module.name}Uniforms`;\n}\n\n/**\n * Returns the ordered field names parsed from a shader module's uniform block.\n *\n * @returns `null` when the stage has no source or the expected block is absent.\n */\nexport function getShaderModuleUniformBlockFields(\n module: ShaderModule,\n stage: ShaderModuleUniformLayoutStage\n): string[] | null {\n const shaderSource =\n stage === 'wgsl' ? module.source : stage === 'vertex' ? module.vs : module.fs;\n\n if (!shaderSource) {\n return null;\n }\n\n const uniformBlockName = getShaderModuleUniformBlockName(module);\n return extractShaderUniformBlockFieldNames(\n shaderSource,\n stage === 'wgsl' ? 'wgsl' : 'glsl',\n uniformBlockName\n );\n}\n\n/**\n * Computes the validation result for a shader module's declared and parsed\n * uniform-block field lists.\n *\n * @returns `null` when the module has no declared uniform types or no matching block.\n */\nexport function getShaderModuleUniformLayoutValidationResult(\n module: ShaderModule,\n stage: ShaderModuleUniformLayoutStage\n): ShaderModuleUniformLayoutValidationResult | null {\n const expectedUniformNames = Object.keys(module.uniformTypes || {});\n if (!expectedUniformNames.length) {\n return null;\n }\n\n const actualUniformNames = getShaderModuleUniformBlockFields(module, stage);\n if (!actualUniformNames) {\n return null;\n }\n\n return {\n moduleName: module.name,\n uniformBlockName: getShaderModuleUniformBlockName(module),\n stage,\n expectedUniformNames,\n actualUniformNames,\n matches: areStringArraysEqual(expectedUniformNames, actualUniformNames)\n };\n}\n\n/**\n * Validates that a shader module's parsed uniform block matches `uniformTypes`.\n *\n * When a mismatch is detected, the helper logs a formatted error and optionally\n * throws via {@link assert}.\n */\nexport function validateShaderModuleUniformLayout(\n module: ShaderModule,\n stage: ShaderModuleUniformLayoutStage,\n options: {\n log?: Logger;\n throwOnError?: boolean;\n } = {}\n): ShaderModuleUniformLayoutValidationResult | null {\n const validationResult = getShaderModuleUniformLayoutValidationResult(module, stage);\n if (!validationResult || validationResult.matches) {\n return validationResult;\n }\n\n const message = formatShaderModuleUniformLayoutError(validationResult);\n options.log?.error?.(message, validationResult)();\n\n if (options.throwOnError !== false) {\n assert(false, message);\n }\n\n return validationResult;\n}\n\n/**\n * Parses all GLSL uniform blocks in a shader source string.\n */\nexport function getGLSLUniformBlocks(shaderSource: string): GLSLUniformBlockInfo[] {\n const blocks: GLSLUniformBlockInfo[] = [];\n const uncommentedSource = stripShaderComments(shaderSource);\n\n for (const sourceMatch of uncommentedSource.matchAll(GLSL_UNIFORM_BLOCK_REGEXP)) {\n const layoutQualifier = sourceMatch[1]?.trim() || null;\n blocks.push({\n blockName: sourceMatch[2],\n body: sourceMatch[3],\n instanceName: sourceMatch[4] || null,\n layoutQualifier,\n hasLayoutQualifier: Boolean(layoutQualifier),\n isStd140: Boolean(\n layoutQualifier && /\\blayout\\s*\\([^)]*\\bstd140\\b[^)]*\\)/.exec(layoutQualifier)\n )\n });\n }\n\n return blocks;\n}\n\n/**\n * Emits warnings for GLSL uniform blocks that do not explicitly declare\n * `layout(std140)`.\n *\n * @returns The list of parsed blocks that were considered non-compliant.\n */\nexport function warnIfGLSLUniformBlocksAreNotStd140(\n shaderSource: string,\n stage: Exclude,\n log?: Logger,\n context?: {label?: string}\n): GLSLUniformBlockInfo[] {\n const nonStd140Blocks = getGLSLUniformBlocks(shaderSource).filter(block => !block.isStd140);\n const seenBlockNames = new Set();\n\n for (const block of nonStd140Blocks) {\n if (seenBlockNames.has(block.blockName)) {\n continue;\n }\n seenBlockNames.add(block.blockName);\n\n const shaderLabel = context?.label ? `${context.label} ` : '';\n const actualLayout = block.hasLayoutQualifier\n ? `declares ${normalizeWhitespace(block.layoutQualifier!)} instead of layout(std140)`\n : 'does not declare layout(std140)';\n const message = `${shaderLabel}${stage} shader uniform block ${\n block.blockName\n } ${actualLayout}. luma.gl host-side shader block packing assumes explicit layout(std140) for GLSL uniform blocks. Add \\`layout(std140)\\` to the block declaration.`;\n log?.warn?.(message, block)();\n }\n\n return nonStd140Blocks;\n}\n\n/**\n * Extracts field names from the named GLSL or WGSL uniform block/struct.\n */\nfunction extractShaderUniformBlockFieldNames(\n shaderSource: string,\n language: 'glsl' | 'wgsl',\n uniformBlockName: string\n): string[] | null {\n const sourceBody =\n language === 'wgsl'\n ? extractWGSLStructBody(shaderSource, uniformBlockName)\n : extractGLSLUniformBlockBody(shaderSource, uniformBlockName);\n\n if (!sourceBody) {\n return null;\n }\n\n const fieldNames: string[] = [];\n\n for (const sourceLine of sourceBody.split('\\n')) {\n const line = sourceLine.replace(/\\/\\/.*$/, '').trim();\n if (!line || line.startsWith('#')) {\n continue;\n }\n\n const fieldMatch =\n language === 'wgsl'\n ? line.match(/^([A-Za-z0-9_]+)\\s*:/)\n : line.match(GLSL_UNIFORM_BLOCK_FIELD_REGEXP);\n\n if (fieldMatch) {\n fieldNames.push(fieldMatch[1]);\n }\n }\n\n return fieldNames;\n}\n\n/**\n * Extracts the body of a WGSL struct with the supplied name.\n */\nfunction extractWGSLStructBody(shaderSource: string, uniformBlockName: string): string | null {\n const structMatch = new RegExp(`\\\\bstruct\\\\s+${uniformBlockName}\\\\b`, 'm').exec(shaderSource);\n if (!structMatch) {\n return null;\n }\n\n const openBraceIndex = shaderSource.indexOf('{', structMatch.index);\n if (openBraceIndex < 0) {\n return null;\n }\n\n let braceDepth = 0;\n for (let index = openBraceIndex; index < shaderSource.length; index++) {\n const character = shaderSource[index];\n if (character === '{') {\n braceDepth++;\n continue;\n }\n if (character !== '}') {\n continue;\n }\n\n braceDepth--;\n if (braceDepth === 0) {\n return shaderSource.slice(openBraceIndex + 1, index);\n }\n }\n\n return null;\n}\n\n/**\n * Extracts the body of a named GLSL uniform block from shader source.\n */\nfunction extractGLSLUniformBlockBody(\n shaderSource: string,\n uniformBlockName: string\n): string | null {\n const block = getGLSLUniformBlocks(shaderSource).find(\n candidate => candidate.blockName === uniformBlockName\n );\n return block?.body || null;\n}\n\n/**\n * Returns `true` when the two arrays contain the same strings in the same order.\n */\nfunction areStringArraysEqual(leftValues: string[], rightValues: string[]): boolean {\n if (leftValues.length !== rightValues.length) {\n return false;\n }\n\n for (let valueIndex = 0; valueIndex < leftValues.length; valueIndex++) {\n if (leftValues[valueIndex] !== rightValues[valueIndex]) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Formats the standard validation error message for a shader-module layout mismatch.\n */\nfunction formatShaderModuleUniformLayoutError(\n validationResult: ShaderModuleUniformLayoutValidationResult\n): string {\n const {expectedUniformNames, actualUniformNames} = validationResult;\n const missingUniformNames = expectedUniformNames.filter(\n uniformName => !actualUniformNames.includes(uniformName)\n );\n const unexpectedUniformNames = actualUniformNames.filter(\n uniformName => !expectedUniformNames.includes(uniformName)\n );\n const mismatchDetails = [\n `Expected ${expectedUniformNames.length} fields, found ${actualUniformNames.length}.`\n ];\n const firstMismatchDescription = getFirstUniformMismatchDescription(\n expectedUniformNames,\n actualUniformNames\n );\n if (firstMismatchDescription) {\n mismatchDetails.push(firstMismatchDescription);\n }\n if (missingUniformNames.length) {\n mismatchDetails.push(\n `Missing from shader block (${missingUniformNames.length}): ${formatUniformNameList(\n missingUniformNames\n )}.`\n );\n }\n if (unexpectedUniformNames.length) {\n mismatchDetails.push(\n `Unexpected in shader block (${unexpectedUniformNames.length}): ${formatUniformNameList(\n unexpectedUniformNames\n )}.`\n );\n }\n if (\n expectedUniformNames.length <= 12 &&\n actualUniformNames.length <= 12 &&\n (missingUniformNames.length || unexpectedUniformNames.length)\n ) {\n mismatchDetails.push(`Expected: ${expectedUniformNames.join(', ')}.`);\n mismatchDetails.push(`Actual: ${actualUniformNames.join(', ')}.`);\n }\n\n return `${validationResult.moduleName}: ${validationResult.stage} shader uniform block ${\n validationResult.uniformBlockName\n } does not match module.uniformTypes. ${mismatchDetails.join(' ')}`;\n}\n\n/**\n * Removes line and block comments from shader source before lightweight parsing.\n */\nfunction stripShaderComments(shaderSource: string): string {\n return shaderSource.replace(/\\/\\*[\\s\\S]*?\\*\\//g, '').replace(/\\/\\/.*$/gm, '');\n}\n\n/**\n * Collapses repeated whitespace in a layout qualifier for log-friendly output.\n */\nfunction normalizeWhitespace(value: string): string {\n return value.replace(/\\s+/g, ' ').trim();\n}\n\nfunction getFirstUniformMismatchDescription(\n expectedUniformNames: string[],\n actualUniformNames: string[]\n): string | null {\n const minimumLength = Math.min(expectedUniformNames.length, actualUniformNames.length);\n for (let index = 0; index < minimumLength; index++) {\n if (expectedUniformNames[index] !== actualUniformNames[index]) {\n return `First mismatch at field ${index + 1}: expected ${\n expectedUniformNames[index]\n }, found ${actualUniformNames[index]}.`;\n }\n }\n\n if (expectedUniformNames.length > actualUniformNames.length) {\n return `Shader block ends after field ${actualUniformNames.length}; expected next field ${\n expectedUniformNames[actualUniformNames.length]\n }.`;\n }\n if (actualUniformNames.length > expectedUniformNames.length) {\n return `Shader block has extra field ${actualUniformNames.length}: ${\n actualUniformNames[expectedUniformNames.length]\n }.`;\n }\n\n return null;\n}\n\nfunction formatUniformNameList(uniformNames: string[], maxNames = 8): string {\n if (uniformNames.length <= maxNames) {\n return uniformNames.join(', ');\n }\n\n const remainingCount = uniformNames.length - maxNames;\n return `${uniformNames.slice(0, maxNames).join(', ')}, ... (${remainingCount} more)`;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {PlatformInfo} from './platform-info';\n\n/** Adds defines to help identify GPU architecture / platform */\nexport function getPlatformShaderDefines(platformInfo: PlatformInfo): string {\n switch (platformInfo?.gpu.toLowerCase()) {\n case 'apple':\n return /* glsl */ `\\\n#define APPLE_GPU\n// Apple optimizes away the calculation necessary for emulated fp64\n#define LUMA_FP64_CODE_ELIMINATION_WORKAROUND 1\n#define LUMA_FP32_TAN_PRECISION_WORKAROUND 1\n// Intel GPU doesn't have full 32 bits precision in same cases, causes overflow\n#define LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND 1\n`;\n\n case 'nvidia':\n return /* glsl */ `\\\n#define NVIDIA_GPU\n// Nvidia optimizes away the calculation necessary for emulated fp64\n#define LUMA_FP64_CODE_ELIMINATION_WORKAROUND 1\n`;\n\n case 'intel':\n return /* glsl */ `\\\n#define INTEL_GPU\n// Intel optimizes away the calculation necessary for emulated fp64\n#define LUMA_FP64_CODE_ELIMINATION_WORKAROUND 1\n// Intel's built-in 'tan' function doesn't have acceptable precision\n#define LUMA_FP32_TAN_PRECISION_WORKAROUND 1\n// Intel GPU doesn't have full 32 bits precision in same cases, causes overflow\n#define LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND 1\n`;\n\n case 'amd':\n // AMD Does not eliminate fp64 code\n return /* glsl */ `\\\n#define AMD_GPU\n`;\n\n default:\n // We don't know what GPU it is, could be that the GPU driver or\n // browser is not implementing UNMASKED_RENDERER constant and not\n // reporting a correct name\n return /* glsl */ `\\\n#define DEFAULT_GPU\n// Prevent driver from optimizing away the calculation necessary for emulated fp64\n#define LUMA_FP64_CODE_ELIMINATION_WORKAROUND 1\n// Headless Chrome's software shader 'tan' function doesn't have acceptable precision\n#define LUMA_FP32_TAN_PRECISION_WORKAROUND 1\n// If the GPU doesn't have full 32 bits precision, will causes overflow\n#define LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND 1\n`;\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// TRANSPILATION TABLES\n\n/**\n * Transpiles GLSL 3.00 shader source code to target GLSL version (3.00 or 1.00)\n *\n * @note We always run transpiler even if same version e.g. 3.00 => 3.00\n * @note For texture sampling transpilation, apps need to use non-standard texture* calls in GLSL 3.00 source\n * RFC: https://github.com/visgl/luma.gl/blob/7.0-release/dev-docs/RFCs/v6.0/portable-glsl-300-rfc.md\n */\nexport function transpileGLSLShader(source: string, stage: 'vertex' | 'fragment'): string {\n const sourceGLSLVersion = Number(source.match(/^#version[ \\t]+(\\d+)/m)?.[1] || 100);\n if (sourceGLSLVersion !== 300) {\n // TODO - we splurge on a longer error message to help deck.gl custom layer developers\n throw new Error('luma.gl v9 only supports GLSL 3.00 shader sources');\n }\n\n switch (stage) {\n case 'vertex':\n source = convertShader(source, ES300_VERTEX_REPLACEMENTS);\n return source;\n case 'fragment':\n source = convertShader(source, ES300_FRAGMENT_REPLACEMENTS);\n return source;\n default:\n // Unknown shader stage\n throw new Error(stage);\n }\n}\n\ntype GLSLReplacement = [RegExp, string];\n\n/** Simple regex replacements for GLSL ES 1.00 syntax that has changed in GLSL ES 3.00 */\nconst ES300_REPLACEMENTS: GLSLReplacement[] = [\n // Fix poorly formatted version directive\n [/^(#version[ \\t]+(100|300[ \\t]+es))?[ \\t]*\\n/, '#version 300 es\\n'],\n // The individual `texture...()` functions were replaced with `texture()` overloads\n [/\\btexture(2D|2DProj|Cube)Lod(EXT)?\\(/g, 'textureLod('],\n [/\\btexture(2D|2DProj|Cube)(EXT)?\\(/g, 'texture(']\n];\n\nconst ES300_VERTEX_REPLACEMENTS: GLSLReplacement[] = [\n ...ES300_REPLACEMENTS,\n // `attribute` keyword replaced with `in`\n [makeVariableTextRegExp('attribute'), 'in $1'],\n // `varying` keyword replaced with `out`\n [makeVariableTextRegExp('varying'), 'out $1']\n];\n\n/** Simple regex replacements for GLSL ES 1.00 syntax that has changed in GLSL ES 3.00 */\nconst ES300_FRAGMENT_REPLACEMENTS: GLSLReplacement[] = [\n ...ES300_REPLACEMENTS,\n // `varying` keyword replaced with `in`\n [makeVariableTextRegExp('varying'), 'in $1']\n];\n\nfunction convertShader(source: string, replacements: GLSLReplacement[]) {\n for (const [pattern, replacement] of replacements) {\n source = source.replace(pattern, replacement);\n }\n return source;\n}\n\n/**\n * Creates a regexp that tests for a specific variable type\n * @example\n * should match:\n * in float weight;\n * out vec4 positions[2];\n * should not match:\n * void f(out float a, in float b) {}\n */\nfunction makeVariableTextRegExp(qualifier: 'attribute' | 'varying' | 'in' | 'out'): RegExp {\n return new RegExp(`\\\\b${qualifier}[ \\\\t]+(\\\\w+[ \\\\t]+\\\\w+(\\\\[\\\\w+\\\\])?;)`, 'g');\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {ShaderInjection} from './shader-injections';\n\n// A normalized hook function\n/**\n * The shader hook mechanism allows the application to create shaders\n * that can be automatically extended by the shader modules the application\n * includes.\n *\n * A shader hook function that shader modules can inject code into.\n * Shaders can call these functions, which will be no-ops by default.\n *\n * If a shader module injects code it will be executed upon the hook\n * function call.\n */\nexport type ShaderHook = {\n /** `vs:` or `fs:` followed by the name and arguments of the function, e.g. `vs:MYHOOK_func(inout vec4 value)`. Hook name without arguments\n will also be used as the name of the shader hook */\n hook: string;\n /** Code always included at the beginning of a hook function */\n header: string;\n /** Code always included at the end of a hook function */\n footer: string;\n /** To Be Documented */\n signature?: string;\n};\n\n/** Normalized shader hooks per shader */\nexport type ShaderHooks = {\n /** Normalized shader hooks for vertex shader */\n vertex: Record;\n /** Normalized shader hooks for fragment shader */\n fragment: Record;\n};\n\n/** Generate hook source code */\nexport function getShaderHooks(\n hookFunctions: Record,\n hookInjections: Record\n): string {\n let result = '';\n for (const hookName in hookFunctions) {\n const hookFunction = hookFunctions[hookName];\n result += `void ${hookFunction.signature} {\\n`;\n if (hookFunction.header) {\n result += ` ${hookFunction.header}`;\n }\n if (hookInjections[hookName]) {\n const injections = hookInjections[hookName];\n injections.sort((a: {order: number}, b: {order: number}): number => a.order - b.order);\n for (const injection of injections) {\n result += ` ${injection.injection}\\n`;\n }\n }\n if (hookFunction.footer) {\n result += ` ${hookFunction.footer}`;\n }\n result += '}\\n';\n }\n\n return result;\n}\n\n/**\n * Parse string based hook functions\n * And split per shader\n */\nexport function normalizeShaderHooks(hookFunctions: (string | ShaderHook)[]): ShaderHooks {\n const result: ShaderHooks = {vertex: {}, fragment: {}};\n\n for (const hookFunction of hookFunctions) {\n let opts: ShaderHook;\n let hook: string;\n if (typeof hookFunction !== 'string') {\n opts = hookFunction;\n hook = opts.hook;\n } else {\n opts = {} as ShaderHook;\n hook = hookFunction;\n }\n hook = hook.trim();\n const [shaderStage, signature] = hook.split(':');\n const name = hook.replace(/\\(.+/, '');\n const normalizedHook: ShaderHook = Object.assign(opts, {signature});\n switch (shaderStage) {\n case 'vs':\n result.vertex[name] = normalizedHook;\n break;\n case 'fs':\n result.fragment[name] = normalizedHook;\n break;\n default:\n throw new Error(shaderStage);\n }\n }\n\n return result;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/** Information extracted from shader source code */\nexport type ShaderInfo = {\n name: string;\n language: 'glsl' | 'wgsl';\n version: number;\n};\n\n/** Extracts information from shader source code */\nexport function getShaderInfo(source: string, defaultName?: string): ShaderInfo {\n return {\n name: getShaderName(source, defaultName),\n language: 'glsl',\n version: getShaderVersion(source)\n };\n}\n\n/** Extracts GLSLIFY style naming of shaders: `#define SHADER_NAME ...` */\nfunction getShaderName(shader: string, defaultName: string = 'unnamed'): string {\n const SHADER_NAME_REGEXP = /#define[^\\S\\r\\n]*SHADER_NAME[^\\S\\r\\n]*([A-Za-z0-9_-]+)\\s*/;\n const match = SHADER_NAME_REGEXP.exec(shader);\n return match ? match[1] : defaultName;\n}\n\n/** returns GLSL shader version of given shader string */\nfunction getShaderVersion(source: string): 100 | 300 {\n let version = 100;\n const words = source.match(/[^\\s]+/g);\n if (words && words.length >= 2 && words[0] === '#version') {\n const parsedVersion = parseInt(words[1], 10);\n if (Number.isFinite(parsedVersion)) {\n version = parsedVersion;\n }\n }\n if (version !== 100 && version !== 300) {\n throw new Error(`Invalid GLSL version ${version}`);\n }\n return version;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport const WGSL_BINDABLE_VARIABLE_PATTERN =\n '(?:var<\\\\s*(uniform|storage(?:\\\\s*,\\\\s*[A-Za-z_][A-Za-z0-9_]*)?)\\\\s*>|var)\\\\s+([A-Za-z_][A-Za-z0-9_]*)';\nconst WGSL_BINDING_DECLARATION_SEPARATOR_PATTERN = '\\\\s*';\n\nexport const MODULE_WGSL_BINDING_DECLARATION_REGEXES = [\n new RegExp(\n `@binding\\\\(\\\\s*(auto|\\\\d+)\\\\s*\\\\)${WGSL_BINDING_DECLARATION_SEPARATOR_PATTERN}@group\\\\(\\\\s*(\\\\d+)\\\\s*\\\\)${WGSL_BINDING_DECLARATION_SEPARATOR_PATTERN}${WGSL_BINDABLE_VARIABLE_PATTERN}`,\n 'g'\n ),\n new RegExp(\n `@group\\\\(\\\\s*(\\\\d+)\\\\s*\\\\)${WGSL_BINDING_DECLARATION_SEPARATOR_PATTERN}@binding\\\\(\\\\s*(auto|\\\\d+)\\\\s*\\\\)${WGSL_BINDING_DECLARATION_SEPARATOR_PATTERN}${WGSL_BINDABLE_VARIABLE_PATTERN}`,\n 'g'\n )\n] as const;\n\nexport const WGSL_BINDING_DECLARATION_REGEXES = [\n new RegExp(\n `@binding\\\\(\\\\s*(auto|\\\\d+)\\\\s*\\\\)${WGSL_BINDING_DECLARATION_SEPARATOR_PATTERN}@group\\\\(\\\\s*(\\\\d+)\\\\s*\\\\)${WGSL_BINDING_DECLARATION_SEPARATOR_PATTERN}${WGSL_BINDABLE_VARIABLE_PATTERN}`,\n 'g'\n ),\n new RegExp(\n `@group\\\\(\\\\s*(\\\\d+)\\\\s*\\\\)${WGSL_BINDING_DECLARATION_SEPARATOR_PATTERN}@binding\\\\(\\\\s*(auto|\\\\d+)\\\\s*\\\\)${WGSL_BINDING_DECLARATION_SEPARATOR_PATTERN}${WGSL_BINDABLE_VARIABLE_PATTERN}`,\n 'g'\n )\n] as const;\n\nexport const WGSL_EXPLICIT_BINDING_DECLARATION_REGEXES = [\n new RegExp(\n `@binding\\\\(\\\\s*(\\\\d+)\\\\s*\\\\)${WGSL_BINDING_DECLARATION_SEPARATOR_PATTERN}@group\\\\(\\\\s*(\\\\d+)\\\\s*\\\\)${WGSL_BINDING_DECLARATION_SEPARATOR_PATTERN}${WGSL_BINDABLE_VARIABLE_PATTERN}`,\n 'g'\n ),\n new RegExp(\n `@group\\\\(\\\\s*(\\\\d+)\\\\s*\\\\)${WGSL_BINDING_DECLARATION_SEPARATOR_PATTERN}@binding\\\\(\\\\s*(\\\\d+)\\\\s*\\\\)${WGSL_BINDING_DECLARATION_SEPARATOR_PATTERN}${WGSL_BINDABLE_VARIABLE_PATTERN}`,\n 'g'\n )\n] as const;\n\nconst WGSL_AUTO_BINDING_DECLARATION_REGEXES = [\n new RegExp(\n `@binding\\\\(\\\\s*(auto)\\\\s*\\\\)\\\\s*@group\\\\(\\\\s*(\\\\d+)\\\\s*\\\\)\\\\s*${WGSL_BINDABLE_VARIABLE_PATTERN}`,\n 'g'\n ),\n new RegExp(\n `@group\\\\(\\\\s*(\\\\d+)\\\\s*\\\\)\\\\s*@binding\\\\(\\\\s*(auto)\\\\s*\\\\)\\\\s*${WGSL_BINDABLE_VARIABLE_PATTERN}`,\n 'g'\n ),\n new RegExp(\n `@binding\\\\(\\\\s*(auto)\\\\s*\\\\)\\\\s*@group\\\\(\\\\s*(\\\\d+)\\\\s*\\\\)(?:[\\\\s\\\\n\\\\r]*@[A-Za-z_][^\\\\n\\\\r]*)*[\\\\s\\\\n\\\\r]*${WGSL_BINDABLE_VARIABLE_PATTERN}`,\n 'g'\n ),\n new RegExp(\n `@group\\\\(\\\\s*(\\\\d+)\\\\s*\\\\)\\\\s*@binding\\\\(\\\\s*(auto)\\\\s*\\\\)(?:[\\\\s\\\\n\\\\r]*@[A-Za-z_][^\\\\n\\\\r]*)*[\\\\s\\\\n\\\\r]*${WGSL_BINDABLE_VARIABLE_PATTERN}`,\n 'g'\n )\n] as const;\n\nexport type WGSLBindingDeclarationMatch = {\n match: string;\n index: number;\n length: number;\n bindingToken: string;\n groupToken: string;\n accessDeclaration?: string;\n name: string;\n};\n\nexport function maskWGSLComments(source: string): string {\n const maskedCharacters = source.split('');\n let index = 0;\n let blockCommentDepth = 0;\n let inLineComment = false;\n let inString = false;\n let isEscaped = false;\n\n while (index < source.length) {\n const character = source[index];\n const nextCharacter = source[index + 1];\n\n if (inString) {\n if (isEscaped) {\n isEscaped = false;\n } else if (character === '\\\\') {\n isEscaped = true;\n } else if (character === '\"') {\n inString = false;\n }\n index++;\n continue;\n }\n\n if (inLineComment) {\n if (character === '\\n' || character === '\\r') {\n inLineComment = false;\n } else {\n maskedCharacters[index] = ' ';\n }\n index++;\n continue;\n }\n\n if (blockCommentDepth > 0) {\n if (character === '/' && nextCharacter === '*') {\n maskedCharacters[index] = ' ';\n maskedCharacters[index + 1] = ' ';\n blockCommentDepth++;\n index += 2;\n continue;\n }\n\n if (character === '*' && nextCharacter === '/') {\n maskedCharacters[index] = ' ';\n maskedCharacters[index + 1] = ' ';\n blockCommentDepth--;\n index += 2;\n continue;\n }\n\n if (character !== '\\n' && character !== '\\r') {\n maskedCharacters[index] = ' ';\n }\n index++;\n continue;\n }\n\n if (character === '\"') {\n inString = true;\n index++;\n continue;\n }\n\n if (character === '/' && nextCharacter === '/') {\n maskedCharacters[index] = ' ';\n maskedCharacters[index + 1] = ' ';\n inLineComment = true;\n index += 2;\n continue;\n }\n\n if (character === '/' && nextCharacter === '*') {\n maskedCharacters[index] = ' ';\n maskedCharacters[index + 1] = ' ';\n blockCommentDepth = 1;\n index += 2;\n continue;\n }\n\n index++;\n }\n\n return maskedCharacters.join('');\n}\n\nexport function getWGSLBindingDeclarationMatches(\n source: string,\n regexes: readonly RegExp[]\n): WGSLBindingDeclarationMatch[] {\n const maskedSource = maskWGSLComments(source);\n const matches: WGSLBindingDeclarationMatch[] = [];\n\n for (const regex of regexes) {\n regex.lastIndex = 0;\n let match: RegExpExecArray | null;\n match = regex.exec(maskedSource);\n while (match) {\n const isBindingFirst = regex === regexes[0];\n const index = match.index;\n const length = match[0].length;\n matches.push({\n match: source.slice(index, index + length),\n index,\n length,\n bindingToken: match[isBindingFirst ? 1 : 2],\n groupToken: match[isBindingFirst ? 2 : 1],\n accessDeclaration: match[3]?.trim(),\n name: match[4]\n });\n match = regex.exec(maskedSource);\n }\n }\n\n return matches.sort((left, right) => left.index - right.index);\n}\n\nexport function replaceWGSLBindingDeclarationMatches(\n source: string,\n regexes: readonly RegExp[],\n replacer: (match: WGSLBindingDeclarationMatch) => string\n): string {\n const matches = getWGSLBindingDeclarationMatches(source, regexes);\n if (!matches.length) {\n return source;\n }\n\n let relocatedSource = '';\n let lastIndex = 0;\n\n for (const match of matches) {\n relocatedSource += source.slice(lastIndex, match.index);\n relocatedSource += replacer(match);\n lastIndex = match.index + match.length;\n }\n\n relocatedSource += source.slice(lastIndex);\n return relocatedSource;\n}\n\nexport function hasWGSLAutoBinding(source: string): boolean {\n return /@binding\\(\\s*auto\\s*\\)/.test(maskWGSLComments(source));\n}\n\nexport function getFirstWGSLAutoBindingDeclarationMatch(\n source: string,\n regexes: readonly RegExp[]\n): WGSLBindingDeclarationMatch | undefined {\n const autoBindingRegexes =\n regexes === MODULE_WGSL_BINDING_DECLARATION_REGEXES ||\n regexes === WGSL_BINDING_DECLARATION_REGEXES\n ? WGSL_AUTO_BINDING_DECLARATION_REGEXES\n : regexes;\n\n return getWGSLBindingDeclarationMatches(source, autoBindingRegexes).find(\n declarationMatch => declarationMatch.bindingToken === 'auto'\n );\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {WGSL_BINDABLE_VARIABLE_PATTERN, maskWGSLComments} from './wgsl-binding-scan';\n\ntype ShaderBindingAssignment = {\n moduleName: string;\n name: string;\n group: number;\n location: number;\n};\n\nconst WGSL_BINDING_DEBUG_REGEXES = [\n new RegExp(\n `@binding\\\\(\\\\s*(\\\\d+)\\\\s*\\\\)\\\\s*@group\\\\(\\\\s*(\\\\d+)\\\\s*\\\\)\\\\s*${WGSL_BINDABLE_VARIABLE_PATTERN}\\\\s*:\\\\s*([^;]+);`,\n 'g'\n ),\n new RegExp(\n `@group\\\\(\\\\s*(\\\\d+)\\\\s*\\\\)\\\\s*@binding\\\\(\\\\s*(\\\\d+)\\\\s*\\\\)\\\\s*${WGSL_BINDABLE_VARIABLE_PATTERN}\\\\s*:\\\\s*([^;]+);`,\n 'g'\n )\n] as const;\n\n/** One debug row describing a WGSL binding in the assembled shader source. */\nexport type ShaderBindingDebugRow = {\n /** Binding name as declared in WGSL. */\n name: string;\n /** Bind-group index. */\n group: number;\n /** Binding slot within the bind group. */\n binding: number;\n /** Resource kind inferred from the WGSL declaration. */\n kind:\n | 'uniform'\n | 'storage'\n | 'read-only-storage'\n | 'texture'\n | 'sampler'\n | 'storage-texture'\n | 'unknown';\n /** Whether the binding came from application WGSL or a shader module. */\n owner: 'application' | 'module';\n /** Shader module name when the binding was contributed by a module. */\n moduleName?: string;\n /** Full WGSL resource type text from the declaration. */\n resourceType?: string;\n /** WGSL access mode when cheaply available. */\n access?: string;\n /** Texture view dimension when cheaply available. */\n viewDimension?: string;\n /** Texture sample type when cheaply available. */\n sampleType?: string;\n /** Sampler kind when cheaply available. */\n samplerKind?: string;\n /** Whether the texture is multisampled when cheaply available. */\n multisampled?: boolean;\n};\n\n/** Builds a stable, table-friendly binding summary from assembled WGSL source. */\nexport function getShaderBindingDebugRowsFromWGSL(\n source: string,\n bindingAssignments: ShaderBindingAssignment[] = []\n): ShaderBindingDebugRow[] {\n const maskedSource = maskWGSLComments(source);\n const assignmentMap = new Map();\n for (const bindingAssignment of bindingAssignments) {\n assignmentMap.set(\n getBindingAssignmentKey(\n bindingAssignment.name,\n bindingAssignment.group,\n bindingAssignment.location\n ),\n bindingAssignment.moduleName\n );\n }\n\n const rows: ShaderBindingDebugRow[] = [];\n for (const regex of WGSL_BINDING_DEBUG_REGEXES) {\n regex.lastIndex = 0;\n let match: RegExpExecArray | null;\n match = regex.exec(maskedSource);\n while (match) {\n const isBindingFirst = regex === WGSL_BINDING_DEBUG_REGEXES[0];\n const binding = Number(match[isBindingFirst ? 1 : 2]);\n const group = Number(match[isBindingFirst ? 2 : 1]);\n const accessDeclaration = match[3]?.trim();\n const name = match[4];\n const resourceType = match[5].trim();\n const moduleName = assignmentMap.get(getBindingAssignmentKey(name, group, binding));\n\n rows.push(\n normalizeShaderBindingDebugRow({\n name,\n group,\n binding,\n owner: moduleName ? 'module' : 'application',\n moduleName,\n accessDeclaration,\n resourceType\n })\n );\n match = regex.exec(maskedSource);\n }\n }\n\n return rows.sort((left, right) => {\n if (left.group !== right.group) {\n return left.group - right.group;\n }\n if (left.binding !== right.binding) {\n return left.binding - right.binding;\n }\n return left.name.localeCompare(right.name);\n });\n}\n\nfunction normalizeShaderBindingDebugRow(row: {\n name: string;\n group: number;\n binding: number;\n owner: 'application' | 'module';\n moduleName?: string;\n accessDeclaration?: string;\n resourceType: string;\n}): ShaderBindingDebugRow {\n const baseRow: ShaderBindingDebugRow = {\n name: row.name,\n group: row.group,\n binding: row.binding,\n owner: row.owner,\n kind: 'unknown',\n moduleName: row.moduleName,\n resourceType: row.resourceType\n };\n\n if (row.accessDeclaration) {\n const access = row.accessDeclaration.split(',').map(value => value.trim());\n if (access[0] === 'uniform') {\n return {...baseRow, kind: 'uniform', access: 'uniform'};\n }\n if (access[0] === 'storage') {\n const storageAccess = access[1] || 'read_write';\n return {\n ...baseRow,\n kind: storageAccess === 'read' ? 'read-only-storage' : 'storage',\n access: storageAccess\n };\n }\n }\n\n if (row.resourceType === 'sampler' || row.resourceType === 'sampler_comparison') {\n return {\n ...baseRow,\n kind: 'sampler',\n samplerKind: row.resourceType === 'sampler_comparison' ? 'comparison' : 'filtering'\n };\n }\n\n if (row.resourceType.startsWith('texture_storage_')) {\n return {\n ...baseRow,\n kind: 'storage-texture',\n access: getStorageTextureAccess(row.resourceType),\n viewDimension: getTextureViewDimension(row.resourceType)\n };\n }\n\n if (row.resourceType.startsWith('texture_')) {\n return {\n ...baseRow,\n kind: 'texture',\n viewDimension: getTextureViewDimension(row.resourceType),\n sampleType: getTextureSampleType(row.resourceType),\n multisampled: row.resourceType.startsWith('texture_multisampled_')\n };\n }\n\n return baseRow;\n}\n\nfunction getBindingAssignmentKey(name: string, group: number, binding: number): string {\n return `${group}:${binding}:${name}`;\n}\n\nfunction getTextureViewDimension(resourceType: string): string | undefined {\n if (resourceType.includes('cube_array')) {\n return 'cube-array';\n }\n if (resourceType.includes('2d_array')) {\n return '2d-array';\n }\n if (resourceType.includes('cube')) {\n return 'cube';\n }\n if (resourceType.includes('3d')) {\n return '3d';\n }\n if (resourceType.includes('2d')) {\n return '2d';\n }\n if (resourceType.includes('1d')) {\n return '1d';\n }\n return undefined;\n}\n\nfunction getTextureSampleType(resourceType: string): string | undefined {\n if (resourceType.startsWith('texture_depth_')) {\n return 'depth';\n }\n if (resourceType.includes('')) {\n return 'sint';\n }\n if (resourceType.includes('')) {\n return 'uint';\n }\n if (resourceType.includes('')) {\n return 'float';\n }\n return undefined;\n}\n\nfunction getStorageTextureAccess(resourceType: string): string | undefined {\n const match = /,\\s*([A-Za-z_][A-Za-z0-9_]*)\\s*>$/.exec(resourceType);\n return match?.[1];\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {getShaderModuleDependencies} from '../shader-module/shader-module-dependencies';\nimport {PlatformInfo} from './platform-info';\nimport {getPlatformShaderDefines} from './platform-defines';\nimport {injectShader, DECLARATION_INJECT_MARKER} from './shader-injections';\nimport {transpileGLSLShader} from '../shader-transpiler/transpile-glsl-shader';\nimport {checkShaderModuleDeprecations} from '../shader-module/shader-module';\nimport {\n validateShaderModuleUniformLayout,\n warnIfGLSLUniformBlocksAreNotStd140\n} from '../shader-module/shader-module-uniform-layout';\nimport type {ShaderInjection} from './shader-injections';\nimport type {ShaderModule} from '../shader-module/shader-module';\nimport {ShaderHook, normalizeShaderHooks, getShaderHooks} from './shader-hooks';\nimport {assert} from '../utils/assert';\nimport {getShaderInfo} from '../glsl-utils/get-shader-info';\nimport {getShaderBindingDebugRowsFromWGSL, type ShaderBindingDebugRow} from './wgsl-binding-debug';\nimport {\n MODULE_WGSL_BINDING_DECLARATION_REGEXES,\n WGSL_BINDING_DECLARATION_REGEXES,\n WGSL_EXPLICIT_BINDING_DECLARATION_REGEXES,\n getFirstWGSLAutoBindingDeclarationMatch,\n getWGSLBindingDeclarationMatches,\n hasWGSLAutoBinding,\n replaceWGSLBindingDeclarationMatches,\n type WGSLBindingDeclarationMatch\n} from './wgsl-binding-scan';\n\nconst INJECT_SHADER_DECLARATIONS = `\\n\\n${DECLARATION_INJECT_MARKER}\\n`;\nconst RESERVED_APPLICATION_GROUP_0_BINDING_LIMIT = 100;\n\n/**\n * Precision prologue to inject before functions are injected in shader\n * TODO - extract any existing prologue in the fragment source and move it up...\n */\nconst FRAGMENT_SHADER_PROLOGUE = /* glsl */ `\\\nprecision highp float;\n`;\n\n/**\n * Options for `ShaderAssembler.assembleShaders()`\n */\nexport type AssembleShaderProps = AssembleShaderOptions & {\n platformInfo: PlatformInfo;\n /** WGSL: single shader source. */\n source?: string | null;\n /** GLSL vertex shader source. */\n vs?: string | null;\n /** GLSL fragment shader source. */\n fs?: string | null;\n};\n\nexport type AssembleShaderOptions = {\n /** information about the platform (which shader language & version, extensions etc.) */\n platformInfo: PlatformInfo;\n /** Inject shader id #defines */\n id?: string;\n /** Modules to be injected */\n modules?: ShaderModule[];\n /** Defines to be injected */\n defines?: Record;\n /** GLSL only: Overrides to be injected. In WGSL these are supplied during Pipeline creation time */\n constants?: Record;\n /** Hook functions */\n hookFunctions?: (ShaderHook | string)[];\n /** Code injections */\n inject?: Record;\n /** Whether to inject prologue */\n prologue?: boolean;\n /** logger object */\n log?: any;\n};\n\ntype AssembleStageOptions = {\n /** Inject shader id #defines */\n id?: string;\n /** Vertex shader */\n source: string;\n stage: 'vertex' | 'fragment';\n /** Modules to be injected */\n modules: any[];\n /** Defines to be injected */\n defines?: Record;\n /** GLSL only: Overrides to be injected. In WGSL these are supplied during Pipeline creation time */\n constants?: Record;\n /** Hook functions */\n hookFunctions?: (ShaderHook | string)[];\n /** Code injections */\n inject?: Record;\n /** Whether to inject prologue */\n prologue?: boolean;\n /** logger object */\n log?: any;\n /** @internal Stable per-assembler WGSL binding assignments. */\n _bindingRegistry?: Map;\n};\n\nexport type HookFunction = {hook: string; header: string; footer: string; signature?: string};\n\n/**\n * getUniforms function returned from the shader module system\n */\nexport type GetUniformsFunc = (opts: Record) => Record;\n\n/**\n * Inject a list of shader modules into a single shader source for WGSL\n */\nexport function assembleWGSLShader(\n options: AssembleShaderOptions & {\n /** Single WGSL shader */\n source: string;\n /** @internal Stable per-assembler WGSL binding assignments. */\n _bindingRegistry?: Map;\n }\n): {\n source: string;\n getUniforms: GetUniformsFunc;\n bindingAssignments: {moduleName: string; name: string; group: number; location: number}[];\n bindingTable: ShaderBindingDebugRow[];\n} {\n const modules = getShaderModuleDependencies(options.modules || []);\n const {source, bindingAssignments} = assembleShaderWGSL(options.platformInfo, {\n ...options,\n source: options.source,\n stage: 'vertex',\n modules\n });\n\n return {\n source,\n getUniforms: assembleGetUniforms(modules),\n bindingAssignments,\n bindingTable: getShaderBindingDebugRowsFromWGSL(source, bindingAssignments)\n };\n}\n\n/**\n * Injects dependent shader module sources into pair of main vertex/fragment shader sources for GLSL\n */\nexport function assembleGLSLShaderPair(\n options: AssembleShaderOptions & {\n /** Vertex shader */\n vs: string;\n /** Fragment shader */\n fs?: string;\n }\n): {\n vs: string;\n fs: string;\n getUniforms: GetUniformsFunc;\n} {\n const {vs, fs} = options;\n const modules = getShaderModuleDependencies(options.modules || []);\n\n return {\n vs: assembleShaderGLSL(options.platformInfo, {\n ...options,\n source: vs,\n stage: 'vertex',\n modules\n }),\n fs: assembleShaderGLSL(options.platformInfo, {\n ...options,\n // @ts-expect-error\n source: fs,\n stage: 'fragment',\n modules\n }),\n getUniforms: assembleGetUniforms(modules)\n };\n}\n\n/**\n * Pulls together complete source code for either a vertex or a fragment shader\n * adding prologues, requested module chunks, and any final injections.\n * @param gl\n * @param options\n * @returns\n */\nexport function assembleShaderWGSL(\n platformInfo: PlatformInfo,\n options: AssembleStageOptions\n): {source: string; bindingAssignments: WGSLBindingAssignment[]} {\n const {\n // id,\n source,\n stage,\n modules,\n // defines = {},\n hookFunctions = [],\n inject = {},\n log\n } = options;\n\n assert(typeof source === 'string', 'shader source must be a string');\n\n // const isVertex = type === 'vs';\n // const sourceLines = source.split('\\n');\n\n const coreSource = source;\n\n // Combine Module and Application Defines\n // const allDefines = {};\n // modules.forEach(module => {\n // Object.assign(allDefines, module.getDefines());\n // });\n // Object.assign(allDefines, defines);\n\n // Add platform defines (use these to work around platform-specific bugs and limitations)\n // Add common defines (GLSL version compatibility, feature detection)\n // Add precision declaration for fragment shaders\n let assembledSource = '';\n // prologue\n // ? `\\\n // ${getShaderNameDefine({id, source, type})}\n // ${getShaderType(type)}\n // ${getPlatformShaderDefines(platformInfo)}\n // ${getApplicationDefines(allDefines)}\n // ${isVertex ? '' : FRAGMENT_SHADER_PROLOGUE}\n // `\n // `;\n\n const hookFunctionMap = normalizeShaderHooks(hookFunctions);\n\n // Add source of dependent modules in resolved order\n const hookInjections: Record = {};\n const declInjections: Record = {};\n const mainInjections: Record = {};\n\n for (const key in inject) {\n const injection =\n typeof inject[key] === 'string' ? {injection: inject[key], order: 0} : inject[key];\n const match = /^(v|f)s:(#)?([\\w-]+)$/.exec(key);\n if (match) {\n const hash = match[2];\n const name = match[3];\n if (hash) {\n if (name === 'decl') {\n declInjections[key] = [injection as any];\n } else {\n mainInjections[key] = [injection as any];\n }\n } else {\n hookInjections[key] = [injection as any];\n }\n } else {\n // Regex injection\n mainInjections[key] = [injection as any];\n }\n }\n\n // TODO - hack until shadertool modules support WebGPU\n const modulesToInject = modules;\n const applicationRelocation = relocateWGSLApplicationBindings(coreSource);\n const usedBindingsByGroup = getUsedBindingsByGroupFromApplicationWGSL(\n applicationRelocation.source\n );\n const reservedBindingKeysByGroup = reserveRegisteredModuleBindings(\n modulesToInject,\n options._bindingRegistry,\n usedBindingsByGroup\n );\n const bindingAssignments: WGSLBindingAssignment[] = [];\n\n for (const module of modulesToInject) {\n if (log) {\n checkShaderModuleDeprecations(module, coreSource, log);\n }\n const relocation = relocateWGSLModuleBindings(\n getShaderModuleSource(module, 'wgsl', log),\n module,\n {\n usedBindingsByGroup,\n bindingRegistry: options._bindingRegistry,\n reservedBindingKeysByGroup\n }\n );\n bindingAssignments.push(...relocation.bindingAssignments);\n const moduleSource = relocation.source;\n // Add the module source, and a #define that declares it presence\n assembledSource += moduleSource;\n\n const injections = module.injections?.[stage] || {};\n for (const key in injections) {\n const match = /^(v|f)s:#([\\w-]+)$/.exec(key);\n if (match) {\n const name = match[2];\n const injectionType = name === 'decl' ? declInjections : mainInjections;\n injectionType[key] = injectionType[key] || [];\n injectionType[key].push(injections[key]);\n } else {\n hookInjections[key] = hookInjections[key] || [];\n hookInjections[key].push(injections[key]);\n }\n }\n }\n\n // For injectShader\n assembledSource += INJECT_SHADER_DECLARATIONS;\n\n assembledSource = injectShader(assembledSource, stage, declInjections);\n\n assembledSource += getShaderHooks(hookFunctionMap[stage], hookInjections);\n assembledSource += formatWGSLBindingAssignmentComments(bindingAssignments);\n\n // Add the version directive and actual source of this shader\n assembledSource += applicationRelocation.source;\n\n // Apply any requested shader injections\n assembledSource = injectShader(assembledSource, stage, mainInjections);\n\n assertNoUnresolvedAutoBindings(assembledSource);\n\n return {source: assembledSource, bindingAssignments};\n}\n\n/**\n * Pulls together complete source code for either a vertex or a fragment shader\n * adding prologues, requested module chunks, and any final injections.\n * @param gl\n * @param options\n * @returns\n */\nfunction assembleShaderGLSL(\n platformInfo: PlatformInfo,\n options: {\n id?: string;\n source: string;\n language?: 'glsl' | 'wgsl';\n stage: 'vertex' | 'fragment';\n modules: ShaderModule[];\n defines?: Record;\n hookFunctions?: any[];\n inject?: Record;\n prologue?: boolean;\n log?: any;\n }\n) {\n const {\n source,\n stage,\n language = 'glsl',\n modules,\n defines = {},\n hookFunctions = [],\n inject = {},\n prologue = true,\n log\n } = options;\n\n assert(typeof source === 'string', 'shader source must be a string');\n\n const sourceVersion = language === 'glsl' ? getShaderInfo(source).version : -1;\n const targetVersion = platformInfo.shaderLanguageVersion;\n\n const sourceVersionDirective = sourceVersion === 100 ? '#version 100' : '#version 300 es';\n\n const sourceLines = source.split('\\n');\n // TODO : keep all pre-processor statements at the beginning of the shader.\n const coreSource = sourceLines.slice(1).join('\\n');\n\n // Combine Module and Application Defines\n const allDefines = {};\n modules.forEach(module => {\n Object.assign(allDefines, module.defines);\n });\n Object.assign(allDefines, defines);\n\n // Add platform defines (use these to work around platform-specific bugs and limitations)\n // Add common defines (GLSL version compatibility, feature detection)\n // Add precision declaration for fragment shaders\n let assembledSource = '';\n switch (language) {\n case 'wgsl':\n break;\n case 'glsl':\n assembledSource = prologue\n ? `\\\n${sourceVersionDirective}\n\n// ----- PROLOGUE -------------------------\n${`#define SHADER_TYPE_${stage.toUpperCase()}`}\n\n${getPlatformShaderDefines(platformInfo)}\n${stage === 'fragment' ? FRAGMENT_SHADER_PROLOGUE : ''}\n\n// ----- APPLICATION DEFINES -------------------------\n\n${getApplicationDefines(allDefines)}\n\n`\n : `${sourceVersionDirective}\n`;\n break;\n }\n\n const hookFunctionMap = normalizeShaderHooks(hookFunctions);\n\n // Add source of dependent modules in resolved order\n const hookInjections: Record = {};\n const declInjections: Record = {};\n const mainInjections: Record = {};\n\n for (const key in inject) {\n const injection: ShaderInjection =\n typeof inject[key] === 'string' ? {injection: inject[key], order: 0} : inject[key];\n const match = /^(v|f)s:(#)?([\\w-]+)$/.exec(key);\n if (match) {\n const hash = match[2];\n const name = match[3];\n if (hash) {\n if (name === 'decl') {\n declInjections[key] = [injection];\n } else {\n mainInjections[key] = [injection];\n }\n } else {\n hookInjections[key] = [injection];\n }\n } else {\n // Regex injection\n mainInjections[key] = [injection];\n }\n }\n\n for (const module of modules) {\n if (log) {\n checkShaderModuleDeprecations(module, coreSource, log);\n }\n const moduleSource = getShaderModuleSource(module, stage, log);\n // Add the module source, and a #define that declares it presence\n assembledSource += moduleSource;\n\n const injections = module.instance?.normalizedInjections[stage] || {};\n for (const key in injections) {\n const match = /^(v|f)s:#([\\w-]+)$/.exec(key);\n if (match) {\n const name = match[2];\n const injectionType = name === 'decl' ? declInjections : mainInjections;\n injectionType[key] = injectionType[key] || [];\n injectionType[key].push(injections[key]);\n } else {\n hookInjections[key] = hookInjections[key] || [];\n hookInjections[key].push(injections[key]);\n }\n }\n }\n\n assembledSource += '// ----- MAIN SHADER SOURCE -------------------------';\n\n // For injectShader\n assembledSource += INJECT_SHADER_DECLARATIONS;\n\n assembledSource = injectShader(assembledSource, stage, declInjections);\n\n assembledSource += getShaderHooks(hookFunctionMap[stage], hookInjections);\n\n // Add the version directive and actual source of this shader\n assembledSource += coreSource;\n\n // Apply any requested shader injections\n assembledSource = injectShader(assembledSource, stage, mainInjections);\n\n if (language === 'glsl' && sourceVersion !== targetVersion) {\n assembledSource = transpileGLSLShader(assembledSource, stage);\n }\n\n if (language === 'glsl') {\n warnIfGLSLUniformBlocksAreNotStd140(assembledSource, stage, log);\n }\n\n return assembledSource.trim();\n}\n\n/**\n * Returns a combined `getUniforms` covering the options for all the modules,\n * the created function will pass on options to the inidividual `getUniforms`\n * function of each shader module and combine the results into one object that\n * can be passed to setUniforms.\n * @param modules\n * @returns\n */\nexport function assembleGetUniforms(modules: ShaderModule[]) {\n return function getUniforms(opts: Record): Record {\n const uniforms = {};\n for (const module of modules) {\n // `modules` is already sorted by dependency level. This guarantees that\n // modules have access to the uniforms that are generated by their dependencies.\n const moduleUniforms = module.getUniforms?.(opts, uniforms);\n Object.assign(uniforms, moduleUniforms);\n }\n return uniforms;\n };\n}\n\n/**\n * NOTE: Removed as id injection defeated caching of shaders\n * \n * Generate \"glslify-compatible\" SHADER_NAME defines\n * These are understood by the GLSL error parsing function\n * If id is provided and no SHADER_NAME constant is present in source, create one\n unction getShaderNameDefine(options: {\n id?: string;\n source: string;\n stage: 'vertex' | 'fragment';\n}): string {\n const {id, source, stage} = options;\n const injectShaderName = id && source.indexOf('SHADER_NAME') === -1;\n return injectShaderName\n ? `\n#define SHADER_NAME ${id}_${stage}`\n : '';\n}\n*/\n\n/** Generates application defines from an object of key value pairs */\nfunction getApplicationDefines(defines: Record = {}): string {\n let sourceText = '';\n for (const define in defines) {\n const value = defines[define];\n if (value || Number.isFinite(value)) {\n sourceText += `#define ${define.toUpperCase()} ${defines[define]}\\n`;\n }\n }\n return sourceText;\n}\n\n/** Extracts the source code chunk for the specified shader type from the named shader module */\nexport function getShaderModuleSource(\n module: ShaderModule,\n stage: 'vertex' | 'fragment' | 'wgsl',\n log?: any\n): string {\n let moduleSource;\n switch (stage) {\n case 'vertex':\n moduleSource = module.vs || '';\n break;\n case 'fragment':\n moduleSource = module.fs || '';\n break;\n case 'wgsl':\n moduleSource = module.source || '';\n break;\n default:\n assert(false);\n }\n\n if (!module.name) {\n throw new Error('Shader module must have a name');\n }\n\n validateShaderModuleUniformLayout(module, stage, {log});\n\n const moduleName = module.name.toUpperCase().replace(/[^0-9a-z]/gi, '_');\n let source = `\\\n// ----- MODULE ${module.name} ---------------\n\n`;\n if (stage !== 'wgsl') {\n source += `#define MODULE_${moduleName}\\n`;\n }\n source += `${moduleSource}\\n`;\n return source;\n}\n\ntype BindingRelocationContext = {\n usedBindingsByGroup: Map>;\n bindingRegistry?: Map;\n reservedBindingKeysByGroup: Map>;\n};\n\ntype WGSLBindingAssignment = {\n moduleName: string;\n name: string;\n group: number;\n location: number;\n};\n\ntype WGSLApplicationRelocationState = {\n sawSupportedBindingDeclaration: boolean;\n};\n\ntype WGSLRelocationState = {\n sawSupportedBindingDeclaration: boolean;\n nextHintedBindingLocation: number | null;\n};\n\ntype WGSLRelocationParams = {\n module: ShaderModule;\n context: BindingRelocationContext;\n bindingAssignments: WGSLBindingAssignment[];\n relocationState: WGSLRelocationState;\n};\n\nfunction getUsedBindingsByGroupFromApplicationWGSL(source: string): Map> {\n const usedBindingsByGroup = new Map>();\n\n for (const match of getWGSLBindingDeclarationMatches(\n source,\n WGSL_EXPLICIT_BINDING_DECLARATION_REGEXES\n )) {\n const location = Number(match.bindingToken);\n const group = Number(match.groupToken);\n\n validateApplicationWGSLBinding(group, location, match.name);\n registerUsedBindingLocation(\n usedBindingsByGroup,\n group,\n location,\n `application binding \"${match.name}\"`\n );\n }\n\n return usedBindingsByGroup;\n}\n\nfunction relocateWGSLApplicationBindings(source: string): {source: string} {\n const declarationMatches = getWGSLBindingDeclarationMatches(\n source,\n WGSL_BINDING_DECLARATION_REGEXES\n );\n const usedBindingsByGroup = new Map>();\n\n for (const declarationMatch of declarationMatches) {\n if (declarationMatch.bindingToken === 'auto') {\n continue;\n }\n\n const location = Number(declarationMatch.bindingToken);\n const group = Number(declarationMatch.groupToken);\n\n validateApplicationWGSLBinding(group, location, declarationMatch.name);\n registerUsedBindingLocation(\n usedBindingsByGroup,\n group,\n location,\n `application binding \"${declarationMatch.name}\"`\n );\n }\n\n const relocationState: WGSLApplicationRelocationState = {\n sawSupportedBindingDeclaration: declarationMatches.length > 0\n };\n\n const relocatedSource = replaceWGSLBindingDeclarationMatches(\n source,\n WGSL_BINDING_DECLARATION_REGEXES,\n declarationMatch =>\n relocateWGSLApplicationBindingMatch(declarationMatch, usedBindingsByGroup, relocationState)\n );\n\n if (hasWGSLAutoBinding(source) && !relocationState.sawSupportedBindingDeclaration) {\n throw new Error(\n 'Unsupported @binding(auto) declaration form in application WGSL. ' +\n 'Use adjacent \"@group(N)\" and \"@binding(auto)\" decorators followed by a bindable \"var\" declaration.'\n );\n }\n\n return {source: relocatedSource};\n}\n\nfunction relocateWGSLModuleBindings(\n moduleSource: string,\n module: ShaderModule,\n context: BindingRelocationContext\n): {source: string; bindingAssignments: WGSLBindingAssignment[]} {\n const bindingAssignments: WGSLBindingAssignment[] = [];\n const declarationMatches = getWGSLBindingDeclarationMatches(\n moduleSource,\n MODULE_WGSL_BINDING_DECLARATION_REGEXES\n );\n const relocationState: WGSLRelocationState = {\n sawSupportedBindingDeclaration: declarationMatches.length > 0,\n nextHintedBindingLocation:\n typeof module.firstBindingSlot === 'number' ? module.firstBindingSlot : null\n };\n\n const relocatedSource = replaceWGSLBindingDeclarationMatches(\n moduleSource,\n MODULE_WGSL_BINDING_DECLARATION_REGEXES,\n declarationMatch =>\n relocateWGSLModuleBindingMatch(declarationMatch, {\n module,\n context,\n bindingAssignments,\n relocationState\n })\n );\n\n if (hasWGSLAutoBinding(moduleSource) && !relocationState.sawSupportedBindingDeclaration) {\n throw new Error(\n `Unsupported @binding(auto) declaration form in module \"${module.name}\". ` +\n 'Use adjacent \"@group(N)\" and \"@binding(auto)\" decorators followed by a bindable \"var\" declaration.'\n );\n }\n\n return {source: relocatedSource, bindingAssignments};\n}\n\nfunction relocateWGSLModuleBindingMatch(\n declarationMatch: WGSLBindingDeclarationMatch,\n params: WGSLRelocationParams\n): string {\n const {module, context, bindingAssignments, relocationState} = params;\n\n const {match, bindingToken, groupToken, name} = declarationMatch;\n const group = Number(groupToken);\n\n if (bindingToken === 'auto') {\n const registryKey = getBindingRegistryKey(group, module.name, name);\n const registryLocation = context.bindingRegistry?.get(registryKey);\n const location =\n registryLocation !== undefined\n ? registryLocation\n : relocationState.nextHintedBindingLocation === null\n ? allocateAutoBindingLocation(group, context.usedBindingsByGroup)\n : allocateAutoBindingLocation(\n group,\n context.usedBindingsByGroup,\n relocationState.nextHintedBindingLocation\n );\n validateModuleWGSLBinding(module.name, group, location, name);\n if (\n registryLocation !== undefined &&\n claimReservedBindingLocation(context.reservedBindingKeysByGroup, group, location, registryKey)\n ) {\n bindingAssignments.push({moduleName: module.name, name, group, location});\n return match.replace(/@binding\\(\\s*auto\\s*\\)/, `@binding(${location})`);\n }\n registerUsedBindingLocation(\n context.usedBindingsByGroup,\n group,\n location,\n `module \"${module.name}\" binding \"${name}\"`\n );\n context.bindingRegistry?.set(registryKey, location);\n bindingAssignments.push({moduleName: module.name, name, group, location});\n if (relocationState.nextHintedBindingLocation !== null && registryLocation === undefined) {\n relocationState.nextHintedBindingLocation = location + 1;\n }\n return match.replace(/@binding\\(\\s*auto\\s*\\)/, `@binding(${location})`);\n }\n\n const location = Number(bindingToken);\n validateModuleWGSLBinding(module.name, group, location, name);\n registerUsedBindingLocation(\n context.usedBindingsByGroup,\n group,\n location,\n `module \"${module.name}\" binding \"${name}\"`\n );\n bindingAssignments.push({moduleName: module.name, name, group, location});\n return match;\n}\n\nfunction relocateWGSLApplicationBindingMatch(\n declarationMatch: WGSLBindingDeclarationMatch,\n usedBindingsByGroup: Map>,\n relocationState: WGSLApplicationRelocationState\n): string {\n const {match, bindingToken, groupToken, name} = declarationMatch;\n const group = Number(groupToken);\n\n if (bindingToken === 'auto') {\n const location = allocateApplicationAutoBindingLocation(group, usedBindingsByGroup);\n validateApplicationWGSLBinding(group, location, name);\n registerUsedBindingLocation(\n usedBindingsByGroup,\n group,\n location,\n `application binding \"${name}\"`\n );\n return match.replace(/@binding\\(\\s*auto\\s*\\)/, `@binding(${location})`);\n }\n\n relocationState.sawSupportedBindingDeclaration = true;\n return match;\n}\n\nfunction reserveRegisteredModuleBindings(\n modules: ShaderModule[],\n bindingRegistry: Map | undefined,\n usedBindingsByGroup: Map>\n): Map> {\n const reservedBindingKeysByGroup = new Map>();\n if (!bindingRegistry) {\n return reservedBindingKeysByGroup;\n }\n\n for (const module of modules) {\n for (const binding of getModuleWGSLBindingDeclarations(module)) {\n const registryKey = getBindingRegistryKey(binding.group, module.name, binding.name);\n const location = bindingRegistry.get(registryKey);\n if (location !== undefined) {\n const reservedBindingKeys =\n reservedBindingKeysByGroup.get(binding.group) || new Map();\n const existingReservation = reservedBindingKeys.get(location);\n if (existingReservation && existingReservation !== registryKey) {\n throw new Error(\n `Duplicate WGSL binding reservation for modules \"${existingReservation}\" and \"${registryKey}\": group ${binding.group}, binding ${location}.`\n );\n }\n\n registerUsedBindingLocation(\n usedBindingsByGroup,\n binding.group,\n location,\n `registered module binding \"${registryKey}\"`\n );\n reservedBindingKeys.set(location, registryKey);\n reservedBindingKeysByGroup.set(binding.group, reservedBindingKeys);\n }\n }\n }\n\n return reservedBindingKeysByGroup;\n}\n\nfunction claimReservedBindingLocation(\n reservedBindingKeysByGroup: Map>,\n group: number,\n location: number,\n registryKey: string\n): boolean {\n const reservedBindingKeys = reservedBindingKeysByGroup.get(group);\n if (!reservedBindingKeys) {\n return false;\n }\n\n const reservedKey = reservedBindingKeys.get(location);\n if (!reservedKey) {\n return false;\n }\n if (reservedKey !== registryKey) {\n throw new Error(\n `Registered module binding \"${registryKey}\" collided with \"${reservedKey}\": group ${group}, binding ${location}.`\n );\n }\n return true;\n}\n\nfunction getModuleWGSLBindingDeclarations(module: ShaderModule): {name: string; group: number}[] {\n const declarations: {name: string; group: number}[] = [];\n const moduleSource = module.source || '';\n\n for (const match of getWGSLBindingDeclarationMatches(\n moduleSource,\n MODULE_WGSL_BINDING_DECLARATION_REGEXES\n )) {\n declarations.push({\n name: match.name,\n group: Number(match.groupToken)\n });\n }\n\n return declarations;\n}\n\nfunction validateApplicationWGSLBinding(group: number, location: number, name: string): void {\n if (group === 0 && location >= RESERVED_APPLICATION_GROUP_0_BINDING_LIMIT) {\n throw new Error(\n `Application binding \"${name}\" in group 0 uses reserved binding ${location}. ` +\n `Application-owned explicit group-0 bindings must stay below ${RESERVED_APPLICATION_GROUP_0_BINDING_LIMIT}.`\n );\n }\n}\n\nfunction validateModuleWGSLBinding(\n moduleName: string,\n group: number,\n location: number,\n name: string\n): void {\n if (group === 0 && location < RESERVED_APPLICATION_GROUP_0_BINDING_LIMIT) {\n throw new Error(\n `Module \"${moduleName}\" binding \"${name}\" in group 0 uses reserved application binding ${location}. ` +\n `Module-owned explicit group-0 bindings must be ${RESERVED_APPLICATION_GROUP_0_BINDING_LIMIT} or higher.`\n );\n }\n}\n\nfunction registerUsedBindingLocation(\n usedBindingsByGroup: Map>,\n group: number,\n location: number,\n label: string\n): void {\n const usedBindings = usedBindingsByGroup.get(group) || new Set();\n if (usedBindings.has(location)) {\n throw new Error(\n `Duplicate WGSL binding assignment for ${label}: group ${group}, binding ${location}.`\n );\n }\n usedBindings.add(location);\n usedBindingsByGroup.set(group, usedBindings);\n}\n\nfunction allocateAutoBindingLocation(\n group: number,\n usedBindingsByGroup: Map>,\n preferredBindingLocation?: number\n): number {\n const usedBindings = usedBindingsByGroup.get(group) || new Set();\n let nextBinding =\n preferredBindingLocation ??\n (group === 0\n ? RESERVED_APPLICATION_GROUP_0_BINDING_LIMIT\n : usedBindings.size > 0\n ? Math.max(...usedBindings) + 1\n : 0);\n\n while (usedBindings.has(nextBinding)) {\n nextBinding++;\n }\n\n return nextBinding;\n}\n\nfunction allocateApplicationAutoBindingLocation(\n group: number,\n usedBindingsByGroup: Map>\n): number {\n const usedBindings = usedBindingsByGroup.get(group) || new Set();\n let nextBinding = 0;\n\n while (usedBindings.has(nextBinding)) {\n nextBinding++;\n }\n\n return nextBinding;\n}\n\nfunction assertNoUnresolvedAutoBindings(source: string): void {\n const unresolvedBinding = getFirstWGSLAutoBindingDeclarationMatch(\n source,\n MODULE_WGSL_BINDING_DECLARATION_REGEXES\n );\n if (!unresolvedBinding) {\n return;\n }\n\n const moduleName = getWGSLModuleNameAtIndex(source, unresolvedBinding.index);\n if (moduleName) {\n throw new Error(\n `Unresolved @binding(auto) for module \"${moduleName}\" binding \"${unresolvedBinding.name}\" remained in assembled WGSL source.`\n );\n }\n\n if (isInApplicationWGSLSection(source, unresolvedBinding.index)) {\n throw new Error(\n `Unresolved @binding(auto) for application binding \"${unresolvedBinding.name}\" remained in assembled WGSL source.`\n );\n }\n\n throw new Error(\n `Unresolved @binding(auto) remained in assembled WGSL source near \"${formatWGSLSourceSnippet(unresolvedBinding.match)}\".`\n );\n}\n\nfunction formatWGSLBindingAssignmentComments(bindingAssignments: WGSLBindingAssignment[]): string {\n if (bindingAssignments.length === 0) {\n return '';\n }\n\n let source = '// ----- MODULE WGSL BINDING ASSIGNMENTS ---------------\\n';\n for (const bindingAssignment of bindingAssignments) {\n source += `// ${bindingAssignment.moduleName}.${bindingAssignment.name} -> @group(${bindingAssignment.group}) @binding(${bindingAssignment.location})\\n`;\n }\n source += '\\n';\n return source;\n}\n\nfunction getBindingRegistryKey(group: number, moduleName: string, bindingName: string): string {\n return `${group}:${moduleName}:${bindingName}`;\n}\n\nfunction getWGSLModuleNameAtIndex(source: string, index: number): string | undefined {\n const moduleHeaderRegex = /^\\/\\/ ----- MODULE ([^\\n]+) ---------------$/gm;\n let moduleName: string | undefined;\n let match: RegExpExecArray | null;\n\n match = moduleHeaderRegex.exec(source);\n while (match && match.index <= index) {\n moduleName = match[1];\n match = moduleHeaderRegex.exec(source);\n }\n\n return moduleName;\n}\n\nfunction isInApplicationWGSLSection(source: string, index: number): boolean {\n const injectionMarkerIndex = source.indexOf(INJECT_SHADER_DECLARATIONS);\n return injectionMarkerIndex >= 0 ? index > injectionMarkerIndex : true;\n}\n\nfunction formatWGSLSourceSnippet(source: string): string {\n return source.replace(/\\s+/g, ' ').trim();\n}\n\n/*\nfunction getHookFunctions(\n hookFunctions: Record,\n hookInjections: Record\n): string {\n let result = '';\n for (const hookName in hookFunctions) {\n const hookFunction = hookFunctions[hookName];\n result += `void ${hookFunction.signature} {\\n`;\n if (hookFunction.header) {\n result += ` ${hookFunction.header}`;\n }\n if (hookInjections[hookName]) {\n const injections = hookInjections[hookName];\n injections.sort((a: {order: number}, b: {order: number}): number => a.order - b.order);\n for (const injection of injections) {\n result += ` ${injection.injection}\\n`;\n }\n }\n if (hookFunction.footer) {\n result += ` ${hookFunction.footer}`;\n }\n result += '}\\n';\n }\n\n return result;\n}\n\nfunction normalizeHookFunctions(hookFunctions: (string | HookFunction)[]): {\n vs: Record;\n fs: Record;\n} {\n const result: {vs: Record; fs: Record} = {\n vs: {},\n fs: {}\n };\n\n hookFunctions.forEach((hookFunction: string | HookFunction) => {\n let opts: HookFunction;\n let hook: string;\n if (typeof hookFunction !== 'string') {\n opts = hookFunction;\n hook = opts.hook;\n } else {\n opts = {} as HookFunction;\n hook = hookFunction;\n }\n hook = hook.trim();\n const [stage, signature] = hook.split(':');\n const name = hook.replace(/\\(.+/, '');\n if (stage !== 'vs' && stage !== 'fs') {\n throw new Error(stage);\n }\n result[stage][name] = Object.assign(opts, {signature});\n });\n\n return result;\n}\n*/\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nconst DEFINE_NAME_PATTERN = '([a-zA-Z_][a-zA-Z0-9_]*)';\nconst IFDEF_REGEXP = new RegExp(`^\\\\s*\\\\#\\\\s*ifdef\\\\s*${DEFINE_NAME_PATTERN}\\\\s*$`);\nconst IFNDEF_REGEXP = new RegExp(`^\\\\s*\\\\#\\\\s*ifndef\\\\s*${DEFINE_NAME_PATTERN}\\\\s*(?:\\\\/\\\\/.*)?$`);\nconst ELSE_REGEXP = /^\\s*\\#\\s*else\\s*(?:\\/\\/.*)?$/;\nconst ENDIF_REGEXP = /^\\s*\\#\\s*endif\\s*$/;\nconst IFDEF_WITH_COMMENT_REGEXP = new RegExp(\n `^\\\\s*\\\\#\\\\s*ifdef\\\\s*${DEFINE_NAME_PATTERN}\\\\s*(?:\\\\/\\\\/.*)?$`\n);\nconst ENDIF_WITH_COMMENT_REGEXP = /^\\s*\\#\\s*endif\\s*(?:\\/\\/.*)?$/;\n\nexport type PreprocessorOptions = {\n defines?: Record;\n};\n\nexport function preprocess(source: string, options?: PreprocessorOptions): string {\n const lines = source.split('\\n');\n const output: string[] = [];\n\n const conditionalStack: Array<{\n parentActive: boolean;\n branchTaken: boolean;\n active: boolean;\n }> = [];\n let conditional = true;\n\n for (const line of lines) {\n const matchIf = line.match(IFDEF_WITH_COMMENT_REGEXP) || line.match(IFDEF_REGEXP);\n const matchIfNot = line.match(IFNDEF_REGEXP);\n const matchElse = line.match(ELSE_REGEXP);\n const matchEnd = line.match(ENDIF_WITH_COMMENT_REGEXP) || line.match(ENDIF_REGEXP);\n\n if (matchIf || matchIfNot) {\n const defineName = (matchIf || matchIfNot)?.[1];\n const defineValue: boolean = Boolean(options?.defines?.[defineName!]);\n const branchTaken: boolean = matchIf ? defineValue : !defineValue;\n const active: boolean = conditional && branchTaken;\n conditionalStack.push({parentActive: conditional, branchTaken, active});\n conditional = active;\n } else if (matchElse) {\n const currentConditional = conditionalStack[conditionalStack.length - 1];\n if (!currentConditional) {\n throw new Error('Encountered #else without matching #ifdef or #ifndef');\n }\n currentConditional.active =\n currentConditional.parentActive && !currentConditional.branchTaken;\n currentConditional.branchTaken = true;\n conditional = currentConditional.active;\n } else if (matchEnd) {\n conditionalStack.pop();\n conditional = conditionalStack.length\n ? conditionalStack[conditionalStack.length - 1].active\n : true;\n } else if (conditional) {\n output.push(line);\n }\n }\n\n if (conditionalStack.length > 0) {\n throw new Error('Unterminated conditional block in shader source');\n }\n\n return output.join('\\n');\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ShaderModule} from './shader-module/shader-module';\nimport {initializeShaderModules} from './shader-module/shader-module';\nimport {\n AssembleShaderProps,\n GetUniformsFunc,\n assembleWGSLShader,\n assembleGLSLShaderPair\n} from './shader-assembly/assemble-shaders';\nimport {\n getShaderBindingDebugRowsFromWGSL,\n type ShaderBindingDebugRow\n} from './shader-assembly/wgsl-binding-debug';\nimport {preprocess} from './preprocessor/preprocessor';\n\n/**\n * A stateful version of `assembleShaders` that can be used to assemble shaders.\n * Supports setting of default modules and hooks.\n */\nexport class ShaderAssembler {\n /** Default ShaderAssembler instance */\n static defaultShaderAssembler: ShaderAssembler;\n /** Hook functions */\n private readonly _hookFunctions: any[] = [];\n /** Shader modules */\n private _defaultModules: ShaderModule[] = [];\n /** Stable per-run WGSL auto-binding assignments keyed by group/module/binding. */\n private readonly _wgslBindingRegistry = new Map();\n\n /**\n * A default shader assembler instance - the natural place to register default modules and hooks\n * @returns\n */\n static getDefaultShaderAssembler(): ShaderAssembler {\n ShaderAssembler.defaultShaderAssembler =\n ShaderAssembler.defaultShaderAssembler || new ShaderAssembler();\n return ShaderAssembler.defaultShaderAssembler;\n }\n\n /**\n * Add a default module that does not have to be provided with every call to assembleShaders()\n */\n addDefaultModule(module: ShaderModule): void {\n if (\n !this._defaultModules.find(\n m => m.name === (typeof module === 'string' ? module : module.name)\n )\n ) {\n this._defaultModules.push(module);\n }\n }\n\n /**\n * Remove a default module\n */\n removeDefaultModule(module: ShaderModule): void {\n const moduleName = typeof module === 'string' ? module : module.name;\n this._defaultModules = this._defaultModules.filter(m => m.name !== moduleName);\n }\n\n /**\n * Register a shader hook\n * @param hook\n * @param opts\n */\n addShaderHook(hook: string, opts?: any): void {\n if (opts) {\n hook = Object.assign(opts, {hook});\n }\n this._hookFunctions.push(hook);\n }\n\n /**\n * Assemble a WGSL unified shader\n * @param platformInfo\n * @param props\n * @returns\n */\n assembleWGSLShader(props: AssembleShaderProps): {\n source: string;\n getUniforms: GetUniformsFunc;\n modules: ShaderModule[];\n bindingAssignments: {moduleName: string; name: string; group: number; location: number}[];\n bindingTable: ShaderBindingDebugRow[];\n } {\n const modules = this._getModuleList(props.modules); // Combine with default modules\n const hookFunctions = this._hookFunctions; // TODO - combine with default hook functions\n const {source, getUniforms, bindingAssignments} = assembleWGSLShader({\n ...props,\n // @ts-expect-error\n source: props.source,\n _bindingRegistry: this._wgslBindingRegistry,\n modules,\n hookFunctions\n });\n const defines = {\n ...modules.reduce>((accumulator, module) => {\n Object.assign(accumulator, module.defines);\n return accumulator;\n }, {}),\n ...props.defines\n };\n // WGSL does not have built-in preprocessing support (just compile time constants)\n const preprocessedSource =\n props.platformInfo.shaderLanguage === 'wgsl' ? preprocess(source, {defines}) : source;\n return {\n source: preprocessedSource,\n getUniforms,\n modules,\n bindingAssignments,\n bindingTable: getShaderBindingDebugRowsFromWGSL(preprocessedSource, bindingAssignments)\n };\n }\n\n /**\n * Assemble a pair of shaders into a single shader program\n * @param platformInfo\n * @param props\n * @returns\n */\n assembleGLSLShaderPair(props: AssembleShaderProps): {\n vs: string;\n fs: string;\n getUniforms: GetUniformsFunc;\n modules: ShaderModule[];\n } {\n const modules = this._getModuleList(props.modules); // Combine with default modules\n const hookFunctions = this._hookFunctions; // TODO - combine with default hook functions\n const assembled = assembleGLSLShaderPair({\n ...props,\n // @ts-expect-error\n vs: props.vs,\n // @ts-expect-error\n fs: props.fs,\n modules,\n hookFunctions\n });\n\n return {...assembled, modules};\n }\n\n /**\n * Dedupe and combine with default modules\n */\n _getModuleList(appModules: ShaderModule[] = []): ShaderModule[] {\n const modules = new Array(this._defaultModules.length + appModules.length);\n const seen: Record = {};\n let count = 0;\n\n for (let i = 0, len = this._defaultModules.length; i < len; ++i) {\n const module = this._defaultModules[i];\n const name = module.name;\n modules[count++] = module;\n seen[name] = true;\n }\n\n for (let i = 0, len = appModules.length; i < len; ++i) {\n const module = appModules[i];\n const name = module.name;\n if (!seen[name]) {\n modules[count++] = module;\n seen[name] = true;\n }\n }\n\n modules.length = count;\n\n initializeShaderModules(modules);\n return modules;\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nconst FS_GLES = /* glsl */ `\\\nout vec4 transform_output;\nvoid main() {\n transform_output = vec4(0);\n}`;\nconst FS300 = `#version 300 es\\n${FS_GLES}`;\n\ntype QualifierInfo = {\n qualifier: string;\n type: string;\n name: string;\n};\n\n// Prase given glsl line and return qualifier details or null\nexport function getQualifierDetails(\n line: string,\n qualifiers: string | string[]\n): QualifierInfo | null {\n qualifiers = Array.isArray(qualifiers) ? qualifiers : [qualifiers];\n const words = line.replace(/^\\s+/, '').split(/\\s+/);\n // TODO add support for precession qualifiers (highp, mediump and lowp)\n const [qualifier, type, definition] = words;\n if (!qualifiers.includes(qualifier) || !type || !definition) {\n return null;\n }\n const name = definition.split(';')[0];\n return {qualifier, type, name};\n}\n\n/**\n * Given the shader input and output variable names,\n * builds and return a pass through fragment shader.\n */\nexport function getPassthroughFS(options?: {\n input?: string;\n inputChannels?: 1 | 2 | 3 | 4;\n output?: string;\n}): string {\n const {input, inputChannels, output} = options || {};\n if (!input) {\n // Default shader\n return FS300;\n }\n if (!inputChannels) {\n throw new Error('inputChannels');\n }\n const inputType = channelCountToType(inputChannels);\n const outputValue = convertToVec4(input, inputChannels);\n return `\\\n#version 300 es\nin ${inputType} ${input};\nout vec4 ${output};\nvoid main() {\n ${output} = ${outputValue};\n}`;\n}\n\n/** convert glsl type to suffix */\nexport function typeToChannelSuffix(type: string): 'x' | 'xy' | 'xyz' | 'xyzw' {\n // biome-ignore format: preserve layout\n switch (type) {\n case 'float': return 'x';\n case 'vec2': return 'xy';\n case 'vec3': return 'xyz';\n case 'vec4': return 'xyzw';\n default:\n throw new Error(type);\n }\n}\n\n/** convert glsl type to channel count */\nexport function typeToChannelCount(type: string): 1 | 2 | 3 | 4 {\n // biome-ignore format: preserve layout\n switch (type) {\n case 'float': return 1;\n case 'vec2': return 2;\n case 'vec3': return 3;\n case 'vec4': return 4;\n default:\n throw new Error(type);\n }\n}\nfunction channelCountToType(channels: 1 | 2 | 3 | 4): 'float' | 'vec2' | 'vec3' | 'vec4' {\n // biome-ignore format: preserve layout\n switch (channels) {\n case 1: return 'float';\n case 2: return 'vec2';\n case 3: return 'vec3';\n case 4: return 'vec4';\n default:\n throw new Error(`invalid channels: ${channels}`);\n }\n}\n\n/** Returns glsl instruction for converting to vec4 */\nexport function convertToVec4(variable: string, channels: 1 | 2 | 3 | 4): string {\n // biome-ignore format: preserve layout\n switch (channels) {\n case 1: return `vec4(${variable}, 0.0, 0.0, 1.0)`;\n case 2: return `vec4(${variable}, 0.0, 1.0)`;\n case 3: return `vec4(${variable}, 1.0)`;\n case 4: return variable;\n default:\n throw new Error(`invalid channels: ${channels}`);\n }\n}\n","// math.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/* eslint-disable no-shadow */ // radians and degrees are common variable names\n\nimport type {NumericArray} from '@math.gl/types';\n\nimport type {MathArray} from '../classes/base/math-array';\n\nconst RADIANS_TO_DEGREES = (1 / Math.PI) * 180;\nconst DEGREES_TO_RADIANS = (1 / 180) * Math.PI;\n\nexport type ConfigurationOptions = {\n EPSILON: number;\n debug?: boolean;\n precision: number;\n printTypes?: boolean;\n printDegrees?: boolean;\n printRowMajor?: boolean;\n _cartographicRadians?: boolean;\n};\n\nconst DEFAULT_CONFIG: Required = {\n EPSILON: 1e-12,\n debug: false,\n precision: 4,\n printTypes: false,\n printDegrees: false,\n printRowMajor: true,\n _cartographicRadians: false\n};\n\n// We use a global field to store the config\ndeclare global {\n // eslint-disable-next-line no-var\n var mathgl: {\n config: Required;\n };\n}\n\n// Configuration is truly global as of v3.6 to ensure single config even if multiple copies of math.gl\n// Multiple copies of config can be quite tricky to debug...\nglobalThis.mathgl = globalThis.mathgl || {config: {...DEFAULT_CONFIG}};\n\nexport const config = globalThis.mathgl.config;\n\nexport function configure(options: Partial): ConfigurationOptions {\n // Only copy existing keys\n Object.assign(config, options);\n return config;\n}\n\n/**\n * Formats a value into a string\n * @param value\n * @param param1\n * @returns\n */\nexport function formatValue(\n value: number,\n {precision = config.precision}: {precision?: number} = {}\n): string {\n value = round(value);\n // get rid of trailing zeros\n return `${parseFloat(value.toPrecision(precision))}`;\n}\n\n/**\n * Check if value is an \"array\"\n * Returns `true` if value is either an array or a typed array\n * Note: returns `false` for `ArrayBuffer` and `DataView` instances\n * @note isTypedArray and isNumericArray are often more useful in TypeScript\n */\nexport function isArray(value: unknown): boolean {\n return Array.isArray(value) || (ArrayBuffer.isView(value) && !(value instanceof DataView));\n}\n\nexport function clone(array: NumericArray | MathArray): NumericArray {\n return 'clone' in array ? array.clone() : array.slice();\n}\n\nexport function toRadians(degrees: number): number;\nexport function toRadians(degrees: NumericArray): NumericArray;\n\nexport function toRadians(degrees: number | NumericArray): number | NumericArray {\n return radians(degrees as NumericArray);\n}\n\nexport function toDegrees(degrees: number): number;\nexport function toDegrees(degrees: NumericArray): NumericArray;\n\nexport function toDegrees(radians: number | NumericArray): number | NumericArray {\n return degrees(radians as NumericArray);\n}\n\n// GLSL math function equivalents - Works on both single values and vectors\n\n/**\n * \"GLSL equivalent\" radians: Works on single values and vectors\n */\nexport function radians(degrees: number): number;\nexport function radians(degrees: NumericArray, result?: NumericArray): NumericArray;\n\nexport function radians(\n degrees: number | NumericArray,\n result?: NumericArray\n): number | NumericArray {\n return map(degrees, (degrees) => degrees * DEGREES_TO_RADIANS, result);\n}\n\n/**\n * \"GLSL equivalent\" degrees: Works on single values and vectors\n */\nexport function degrees(radians: number): number;\nexport function degrees(radians: NumericArray, result?: NumericArray): NumericArray;\n\nexport function degrees(\n radians: number | NumericArray,\n result?: NumericArray\n): number | NumericArray {\n return map(radians, (radians) => radians * RADIANS_TO_DEGREES, result);\n}\n\n/**\n * \"GLSL equivalent\" of `Math.sin`: Works on single values and vectors\n * @deprecated\n */\nexport function sin(radians: number | NumericArray, result?: NumericArray): number | NumericArray {\n return map(radians, (angle) => Math.sin(angle), result);\n}\n\n/**\n * \"GLSL equivalent\" of `Math.cos`: Works on single values and vectors\n * @deprecated\n */\nexport function cos(radians: number | NumericArray, result?: NumericArray): number | NumericArray {\n return map(radians, (angle) => Math.cos(angle), result);\n}\n\n/**\n * \"GLSL equivalent\" of `Math.tan`: Works on single values and vectors\n * @deprecated\n */\nexport function tan(radians: number | NumericArray, result?: NumericArray): number | NumericArray {\n return map(radians, (angle) => Math.tan(angle), result);\n}\n\n/**\n * \"GLSL equivalent\" of `Math.asin`: Works on single values and vectors\n * @deprecated\n */\nexport function asin(radians: number | NumericArray, result?: NumericArray): number | NumericArray {\n return map(radians, (angle) => Math.asin(angle), result);\n}\n\n/**\n * \"GLSL equivalent\" of `Math.acos`: Works on single values and vectors\n * @deprecated\n */\nexport function acos(radians: number | NumericArray, result?: NumericArray): number | NumericArray {\n return map(radians, (angle) => Math.acos(angle), result);\n}\n\n/**\n * \"GLSL equivalent\" of `Math.atan`: Works on single values and vectors\n * @deprecated\n */\nexport function atan(radians: number | NumericArray, result?: NumericArray): number | NumericArray {\n return map(radians, (angle) => Math.atan(angle), result);\n}\n\n/**\n * GLSL style value clamping: Works on single values and vectors\n */\nexport function clamp(value: number, min: number, max: number): number;\nexport function clamp(value: NumericArray, min: number, max: number): NumericArray;\n\nexport function clamp(\n value: number | NumericArray,\n min: number,\n max: number\n): number | NumericArray {\n return map(value, (value) => Math.max(min, Math.min(max, value)));\n}\n\n/**\n * Interpolate between two numbers or two arrays\n */\nexport function lerp(a: number, b: number, t: number): number;\nexport function lerp(a: NumericArray, b: NumericArray, t: number): NumericArray;\n\nexport function lerp(\n a: number | NumericArray,\n b: number | NumericArray,\n t: number\n): number | NumericArray {\n if (isArray(a)) {\n return (a as NumericArray).map((ai: number, i: number) => lerp(ai, (b as NumericArray)[i], t));\n }\n return t * (b as number) + (1 - t) * (a as number);\n}\n\n/* eslint-disable */\n\n/**\n * Compares any two math objects, using `equals` method if available.\n * @param a\n * @param b\n * @param epsilon\n * @returns\n */\nexport function equals(a: any, b: any, epsilon?: number): boolean {\n const oldEpsilon = config.EPSILON;\n if (epsilon) {\n config.EPSILON = epsilon;\n }\n try {\n if (a === b) {\n return true;\n }\n if (isArray(a) && isArray(b)) {\n if (a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; ++i) {\n // eslint-disable-next-line max-depth\n if (!equals(a[i], b[i])) {\n return false;\n }\n }\n return true;\n }\n if (a && a.equals) {\n return a.equals(b);\n }\n if (b && b.equals) {\n return b.equals(a);\n }\n if (typeof a === 'number' && typeof b === 'number') {\n return Math.abs(a - b) <= config.EPSILON * Math.max(1, Math.abs(a), Math.abs(b));\n }\n return false;\n } finally {\n config.EPSILON = oldEpsilon;\n }\n}\n\nexport function exactEquals(a: any, b: any): boolean {\n if (a === b) {\n return true;\n }\n if (a && typeof a === 'object' && b && typeof b === 'object') {\n if (a.constructor !== b.constructor) {\n return false;\n }\n if (a.exactEquals) {\n return a.exactEquals(b);\n }\n }\n if (isArray(a) && isArray(b)) {\n if (a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; ++i) {\n if (!exactEquals(a[i], b[i])) {\n return false;\n }\n }\n return true;\n }\n return false;\n}\n\n/* eslint-enable */\n\nexport function withEpsilon(epsilon: number, func: () => T): T {\n const oldPrecision = config.EPSILON;\n config.EPSILON = epsilon;\n let value: T;\n try {\n value = func();\n } finally {\n config.EPSILON = oldPrecision;\n }\n return value;\n}\n\n// HELPERS\n\nfunction round(value: number): number {\n return Math.round(value / config.EPSILON) * config.EPSILON;\n}\n\n// If the array has a clone function, calls it, otherwise returns a copy\nfunction duplicateArray(array: NumericArray): NumericArray {\n // @ts-expect-error We check for math.gl class methods\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n return array.clone ? (array.clone() as NumericArray) : (new Array(array.length) as number[]);\n}\n\n// If the argument value is an array, applies the func element wise,\n// otherwise applies func to the argument value\nfunction map(\n value: number | NumericArray,\n func: (x: number, index?: number, resultArray?: NumericArray) => number,\n result?: NumericArray\n): number | NumericArray {\n if (isArray(value)) {\n const array = value as NumericArray;\n result = result || duplicateArray(array);\n for (let i = 0; i < result.length && i < array.length; ++i) {\n const val = typeof value === 'number' ? value : value[i];\n result[i] = func(val, i, result);\n }\n return result;\n }\n return func(value as number);\n}\n","// math.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {NumericArray} from '@math.gl/types';\nimport {ConfigurationOptions, config, formatValue, equals, isArray} from '../../lib/common';\n\n/** Base class for vectors and matrices */\nexport abstract class MathArray extends Array {\n /** Number of elements (values) in this array */\n abstract get ELEMENTS(): number;\n\n abstract copy(vector: Readonly): this;\n\n abstract fromObject(object: Record): this;\n\n // Common methods\n\n /**\n * Clone the current object\n * @returns a new copy of this object\n */\n clone(): this {\n // @ts-expect-error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature.\n return new this.constructor().copy(this); // eslint-disable-line\n }\n\n fromArray(array: Readonly, offset: number = 0): this {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] = array[i + offset];\n }\n return this.check();\n }\n\n toArray(targetArray: TypedArray, offset?: number): TypedArray;\n toArray(targetArray?: number[], offset?: number): NumericArray;\n\n toArray(targetArray: NumericArray = [], offset: number = 0): NumericArray {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n targetArray[offset + i] = this[i];\n }\n return targetArray;\n }\n\n toObject(targetObject: Record): Record {\n return targetObject;\n }\n\n from(arrayOrObject: Readonly | Record): this {\n return Array.isArray(arrayOrObject)\n ? this.copy(arrayOrObject)\n : // @ts-ignore\n this.fromObject(arrayOrObject);\n }\n\n to>(arrayOrObject: T): T {\n // @ts-ignore\n if (arrayOrObject === this) {\n return this as T;\n }\n // @ts-expect-error TS2339: Property 'toObject' does not exist on type 'MathArray'.\n return isArray(arrayOrObject) ? this.toArray(arrayOrObject) : this.toObject(arrayOrObject);\n }\n\n toTarget(target: this): this {\n return target ? this.to(target) : this;\n }\n\n /** @deprecated */\n toFloat32Array(): Float32Array {\n return new Float32Array(this);\n }\n\n override toString(): string {\n return this.formatString(config);\n }\n\n /** Formats string according to options */\n formatString(opts: ConfigurationOptions): string {\n let string = '';\n for (let i = 0; i < this.ELEMENTS; ++i) {\n string += (i > 0 ? ', ' : '') + formatValue(this[i], opts);\n }\n return `${opts.printTypes ? this.constructor.name : ''}[${string}]`;\n }\n\n equals(array: Readonly): boolean {\n if (!array || this.length !== array.length) {\n return false;\n }\n for (let i = 0; i < this.ELEMENTS; ++i) {\n if (!equals(this[i], array[i])) {\n return false;\n }\n }\n return true;\n }\n\n exactEquals(array: Readonly): boolean {\n if (!array || this.length !== array.length) {\n return false;\n }\n for (let i = 0; i < this.ELEMENTS; ++i) {\n if (this[i] !== array[i]) {\n return false;\n }\n }\n return true;\n }\n\n // Modifiers\n\n /** Negates all values in this object */\n negate(): this {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] = -this[i];\n }\n return this.check();\n }\n\n /** Linearly interpolates between two values */\n lerp(a: Readonly, t: number): this;\n lerp(a: Readonly, b: Readonly, t: number): this;\n\n lerp(a: Readonly, b: Readonly | number, t?: number): this {\n if (t === undefined) {\n return this.lerp(this, a, b as number);\n }\n for (let i = 0; i < this.ELEMENTS; ++i) {\n const ai = a[i];\n const endValue = typeof b === 'number' ? b : b[i];\n this[i] = ai + t * (endValue - ai);\n }\n return this.check();\n }\n\n /** Minimal */\n min(vector: Readonly): this {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] = Math.min(vector[i], this[i]);\n }\n return this.check();\n }\n\n /** Maximal */\n max(vector: Readonly): this {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] = Math.max(vector[i], this[i]);\n }\n return this.check();\n }\n\n clamp(minVector: Readonly, maxVector: Readonly): this {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] = Math.min(Math.max(this[i], minVector[i]), maxVector[i]);\n }\n return this.check();\n }\n\n add(...vectors: Readonly[]): this {\n for (const vector of vectors) {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] += vector[i];\n }\n }\n return this.check();\n }\n\n subtract(...vectors: Readonly[]): this {\n for (const vector of vectors) {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] -= vector[i];\n }\n }\n return this.check();\n }\n\n scale(scale: number | Readonly): this {\n if (typeof scale === 'number') {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] *= scale;\n }\n } else {\n for (let i = 0; i < this.ELEMENTS && i < scale.length; ++i) {\n this[i] *= scale[i];\n }\n }\n return this.check();\n }\n\n /**\n * Multiplies all elements by `scale`\n * Note: `Matrix4.multiplyByScalar` only scales its 3x3 \"minor\"\n */\n multiplyByScalar(scalar: number): this {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] *= scalar;\n }\n return this.check();\n }\n\n // Debug checks\n\n /** Throws an error if array length is incorrect or contains illegal values */\n check(): this {\n if (config.debug && !this.validate()) {\n throw new Error(`math.gl: ${this.constructor.name} some fields set to invalid numbers'`);\n }\n return this;\n }\n\n /** Returns false if the array length is incorrect or contains illegal values */\n validate(): boolean {\n let valid = this.length === this.ELEMENTS;\n for (let i = 0; i < this.ELEMENTS; ++i) {\n valid = valid && Number.isFinite(this[i]);\n }\n return valid;\n }\n\n // three.js compatibility\n\n /** @deprecated */\n sub(a: Readonly): this {\n return this.subtract(a);\n }\n\n /** @deprecated */\n setScalar(a: number): this {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] = a;\n }\n return this.check();\n }\n\n /** @deprecated */\n addScalar(a: number): this {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] += a;\n }\n return this.check();\n }\n\n /** @deprecated */\n subScalar(a: number): this {\n return this.addScalar(-a);\n }\n\n /** @deprecated */\n multiplyScalar(scalar: number): this {\n // Multiplies all elements\n // `Matrix4.scale` only scales its 3x3 \"minor\"\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] *= scalar;\n }\n return this.check();\n }\n\n /** @deprecated */\n divideScalar(a: number): this {\n return this.multiplyByScalar(1 / a);\n }\n\n /** @deprecated */\n clampScalar(min: number, max: number): this {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] = Math.min(Math.max(this[i], min), max);\n }\n return this.check();\n }\n\n /** @deprecated */\n get elements(): NumericArray {\n return this;\n }\n}\n","// math.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {NumericArray} from '@math.gl/types';\nimport {config} from './common';\n\nexport function validateVector(v: NumericArray, length: number): boolean {\n if (v.length !== length) {\n return false;\n }\n // Could be arguments \"array\" (v.every not availasble)\n for (let i = 0; i < v.length; ++i) {\n if (!Number.isFinite(v[i])) {\n return false;\n }\n }\n return true;\n}\n\nexport function checkNumber(value: unknown): number {\n if (!Number.isFinite(value)) {\n throw new Error(`Invalid number ${JSON.stringify(value)}`);\n }\n return value as number;\n}\n\nexport function checkVector(\n v: T,\n length: number,\n callerName: string = ''\n): T {\n if (config.debug && !validateVector(v, length)) {\n throw new Error(`math.gl: ${callerName} some fields set to invalid numbers'`);\n }\n return v;\n}\n\nconst map: Record = {};\n\nexport function deprecated(method: string, version: string): void {\n if (!map[method]) {\n map[method] = true;\n // eslint-disable-next-line\n console.warn(\n `${method} has been removed in version ${version}, see upgrade guide for more information`\n );\n }\n}\n","// math.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport function assert(condition: unknown, message?: string): void {\n if (!condition) {\n throw new Error(`math.gl assertion ${message}`);\n }\n}\n","// math.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n// Copyright (c) 2017 Uber Technologies, Inc.\n\nimport {NumericArray} from '@math.gl/types';\nimport {MathArray} from './math-array';\nimport {checkNumber} from '../../lib/validators';\nimport {assert} from '../../lib/assert';\n\n/** Base class for vectors with at least 2 elements */\nexport abstract class Vector extends MathArray {\n // ACCESSORS\n\n get x(): number {\n return this[0];\n }\n\n set x(value: number) {\n this[0] = checkNumber(value);\n }\n\n get y(): number {\n return this[1];\n }\n\n set y(value: number) {\n this[1] = checkNumber(value);\n }\n\n /**\n * Returns the length of the vector from the origin to the point described by this vector\n *\n * @note `length` is a reserved word for Arrays, so `v.length()` will return number of elements\n * Instead we provide `len` and `magnitude`\n */\n len(): number {\n return Math.sqrt(this.lengthSquared());\n }\n\n /**\n * Returns the length of the vector from the origin to the point described by this vector\n */\n magnitude(): number {\n return this.len();\n }\n\n /**\n * Returns the squared length of the vector from the origin to the point described by this vector\n */\n lengthSquared(): number {\n let length = 0;\n for (let i = 0; i < this.ELEMENTS; ++i) {\n length += this[i] * this[i];\n }\n return length;\n }\n\n /**\n * Returns the squared length of the vector from the origin to the point described by this vector\n */\n magnitudeSquared(): number {\n return this.lengthSquared();\n }\n\n distance(mathArray: Readonly): number {\n return Math.sqrt(this.distanceSquared(mathArray));\n }\n\n distanceSquared(mathArray: Readonly): number {\n let length = 0;\n for (let i = 0; i < this.ELEMENTS; ++i) {\n const dist = this[i] - mathArray[i];\n length += dist * dist;\n }\n return checkNumber(length);\n }\n\n dot(mathArray: Readonly): number {\n let product = 0;\n for (let i = 0; i < this.ELEMENTS; ++i) {\n product += this[i] * mathArray[i];\n }\n return checkNumber(product);\n }\n\n // MODIFIERS\n\n normalize(): this {\n const length = this.magnitude();\n if (length !== 0) {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] /= length;\n }\n }\n return this.check();\n }\n\n multiply(...vectors: Readonly[]): this {\n for (const vector of vectors) {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] *= vector[i];\n }\n }\n return this.check();\n }\n\n divide(...vectors: Readonly[]): this {\n for (const vector of vectors) {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] /= vector[i];\n }\n }\n return this.check();\n }\n\n // THREE.js compatibility\n\n lengthSq(): number {\n return this.lengthSquared();\n }\n distanceTo(vector: Readonly): number {\n return this.distance(vector);\n }\n distanceToSquared(vector: Readonly): number {\n return this.distanceSquared(vector);\n }\n\n getComponent(i: number): number {\n assert(i >= 0 && i < this.ELEMENTS, 'index is out of range');\n return checkNumber(this[i]);\n }\n\n setComponent(i: number, value: number): this {\n assert(i >= 0 && i < this.ELEMENTS, 'index is out of range');\n this[i] = value;\n return this.check();\n }\n\n addVectors(a: Readonly, b: Readonly): this {\n return this.copy(a).add(b);\n }\n\n subVectors(a: Readonly, b: Readonly): this {\n return this.copy(a).subtract(b);\n }\n\n multiplyVectors(a: Readonly, b: Readonly): this {\n return this.copy(a).multiply(b);\n }\n\n addScaledVector(a: Readonly, b: number): this {\n // @ts-expect-error error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature.\n return this.add((new this.constructor(a) as this).multiplyScalar(b));\n }\n}\n","// @eslint-disable\n// @ts-nocheck\n\nimport type {NumericArray} from '@math.gl/types';\nimport * as glMatrix from './common.js';\n\n/**\n * 2 Dimensional Vector\n * @module vec2\n */\n\n/**\n * Creates a new, empty vec2\n *\n * @returns a new 2D vector\n */\nexport function create(): NumericArray {\n const out = new glMatrix.ARRAY_TYPE(2);\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[0] = 0;\n out[1] = 0;\n }\n return out;\n}\n\n/**\n * Creates a new vec2 initialized with values from an existing vector\n *\n * @param a vector to clone\n * @returns a new 2D vector\n */\nexport function clone(a: Readonly): NumericArray {\n const out = new glMatrix.ARRAY_TYPE(2);\n out[0] = a[0];\n out[1] = a[1];\n return out;\n}\n\n/**\n * Creates a new vec2 initialized with the given values\n *\n * @param x X component\n * @param y Y component\n * @returns a new 2D vector\n */\nexport function fromValues(x: number, y: number): NumericArray {\n const out = new glMatrix.ARRAY_TYPE(2);\n out[0] = x;\n out[1] = y;\n return out;\n}\n\n/**\n * Copy the values from one vec2 to another\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a the source vector\n * @returns {NumericArray} out\n */\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n return out;\n}\n\n/**\n * Set the components of a vec2 to the given values\n *\n * @param {NumericArray} out the receiving vector\n * @param {Number} x X component\n * @param {Number} y Y component\n * @returns {NumericArray} out\n */\nexport function set(out, x, y) {\n out[0] = x;\n out[1] = y;\n return out;\n}\n\n/**\n * Adds two vec2's\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a the first operand\n * @param {Readonly} b the second operand\n * @returns {NumericArray} out\n */\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n return out;\n}\n\n/**\n * Subtracts vector b from vector a\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a the first operand\n * @param {Readonly} b the second operand\n * @returns {NumericArray} out\n */\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n return out;\n}\n\n/**\n * Multiplies two vec2's\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a the first operand\n * @param {Readonly} b the second operand\n * @returns {NumericArray} out\n */\nexport function multiply(out, a, b) {\n out[0] = a[0] * b[0];\n out[1] = a[1] * b[1];\n return out;\n}\n\n/**\n * Divides two vec2's\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a the first operand\n * @param {Readonly} b the second operand\n * @returns {NumericArray} out\n */\nexport function divide(out, a, b) {\n out[0] = a[0] / b[0];\n out[1] = a[1] / b[1];\n return out;\n}\n\n/**\n * Math.ceil the components of a vec2\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a vector to ceil\n * @returns {NumericArray} out\n */\nexport function ceil(out, a) {\n out[0] = Math.ceil(a[0]);\n out[1] = Math.ceil(a[1]);\n return out;\n}\n\n/**\n * Math.floor the components of a vec2\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a vector to floor\n * @returns {NumericArray} out\n */\nexport function floor(out, a) {\n out[0] = Math.floor(a[0]);\n out[1] = Math.floor(a[1]);\n return out;\n}\n\n/**\n * Returns the minimum of two vec2's\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a the first operand\n * @param {Readonly} b the second operand\n * @returns {NumericArray} out\n */\nexport function min(out, a, b) {\n out[0] = Math.min(a[0], b[0]);\n out[1] = Math.min(a[1], b[1]);\n return out;\n}\n\n/**\n * Returns the maximum of two vec2's\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a the first operand\n * @param {Readonly} b the second operand\n * @returns {NumericArray} out\n */\nexport function max(out, a, b) {\n out[0] = Math.max(a[0], b[0]);\n out[1] = Math.max(a[1], b[1]);\n return out;\n}\n\n/**\n * symmetric round the components of a vec2\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a vector to round\n * @returns {NumericArray} out\n */\nexport function round(out, a) {\n out[0] = glMatrix.round(a[0]);\n out[1] = glMatrix.round(a[1]);\n return out;\n}\n\n/**\n * Scales a vec2 by a scalar number\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a the vector to scale\n * @param {Number} b amount to scale the vector by\n * @returns {NumericArray} out\n */\nexport function scale(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n return out;\n}\n\n/**\n * Adds two vec2's after scaling the second operand by a scalar value\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a the first operand\n * @param {Readonly} b the second operand\n * @param {Number} scale the amount to scale b by before adding\n * @returns {NumericArray} out\n */\nexport function scaleAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n return out;\n}\n\n/**\n * Calculates the euclidian distance between two vec2's\n *\n * @param {Readonly} a the first operand\n * @param {Readonly} b the second operand\n * @returns {Number} distance between a and b\n */\nexport function distance(a, b) {\n const x = b[0] - a[0];\n const y = b[1] - a[1];\n return Math.sqrt(x * x + y * y);\n}\n\n/**\n * Calculates the squared euclidian distance between two vec2's\n *\n * @param {Readonly} a the first operand\n * @param {Readonly} b the second operand\n * @returns {Number} squared distance between a and b\n */\nexport function squaredDistance(a, b) {\n const x = b[0] - a[0];\n const y = b[1] - a[1];\n return x * x + y * y;\n}\n\n/**\n * Calculates the length of a vec2\n *\n * @param {Readonly} a vector to calculate length of\n * @returns {Number} length of a\n */\nexport function length(a) {\n const x = a[0];\n const y = a[1];\n return Math.sqrt(x * x + y * y);\n}\n\n/**\n * Calculates the squared length of a vec2\n *\n * @param {Readonly} a vector to calculate squared length of\n * @returns {Number} squared length of a\n */\nexport function squaredLength(a) {\n const x = a[0];\n const y = a[1];\n return x * x + y * y;\n}\n\n/**\n * Negates the components of a vec2\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a vector to negate\n * @returns {NumericArray} out\n */\nexport function negate(out, a) {\n out[0] = -a[0];\n out[1] = -a[1];\n return out;\n}\n\n/**\n * Returns the inverse of the components of a vec2\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a vector to invert\n * @returns {NumericArray} out\n */\nexport function inverse(out, a) {\n out[0] = 1.0 / a[0];\n out[1] = 1.0 / a[1];\n return out;\n}\n\n/**\n * Normalize a vec2\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a vector to normalize\n * @returns {NumericArray} out\n */\nexport function normalize(out, a) {\n const x = a[0];\n const y = a[1];\n let len = x * x + y * y;\n if (len > 0) {\n // TODO: evaluate use of glm_invsqrt here?\n len = 1 / Math.sqrt(len);\n }\n out[0] = a[0] * len;\n out[1] = a[1] * len;\n return out;\n}\n\n/**\n * Calculates the dot product of two vec2's\n *\n * @param {Readonly} a the first operand\n * @param {Readonly} b the second operand\n * @returns {Number} dot product of a and b\n */\nexport function dot(a, b) {\n return a[0] * b[0] + a[1] * b[1];\n}\n\n/**\n * Computes the cross product of two vec2's\n * Note that the cross product must by definition produce a 3D vector\n *\n * @param {vec3} out the receiving vector\n * @param {Readonly} a the first operand\n * @param {Readonly} b the second operand\n * @returns {vec3} out\n */\nexport function cross(out, a, b) {\n const z = a[0] * b[1] - a[1] * b[0];\n out[0] = out[1] = 0;\n out[2] = z;\n return out;\n}\n\n/**\n * Performs a linear interpolation between two vec2's\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a the first operand\n * @param {Readonly} b the second operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {NumericArray} out\n */\nexport function lerp(out, a, b, t) {\n const ax = a[0];\n const ay = a[1];\n out[0] = ax + t * (b[0] - ax);\n out[1] = ay + t * (b[1] - ay);\n return out;\n}\n\n/**\n * Generates a random vector with the given scale\n *\n * @param {NumericArray} out the receiving vector\n * @param {Number} [scale] Length of the resulting vector. If omitted, a unit vector will be returned\n * @returns {NumericArray} out\n */\nexport function random(out, scale) {\n scale = scale === undefined ? 1.0 : scale;\n const r = glMatrix.RANDOM() * 2.0 * Math.PI;\n out[0] = Math.cos(r) * scale;\n out[1] = Math.sin(r) * scale;\n return out;\n}\n\n/**\n * Transforms the vec2 with a mat2\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a the vector to transform\n * @param {ReadonlyMat2} m matrix to transform with\n * @returns {NumericArray} out\n */\nexport function transformMat2(out, a, m) {\n const x = a[0];\n const y = a[1];\n out[0] = m[0] * x + m[2] * y;\n out[1] = m[1] * x + m[3] * y;\n return out;\n}\n\n/**\n * Transforms the vec2 with a mat2d\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a the vector to transform\n * @param {ReadonlyMat2d} m matrix to transform with\n * @returns {NumericArray} out\n */\nexport function transformMat2d(out, a, m) {\n const x = a[0];\n const y = a[1];\n out[0] = m[0] * x + m[2] * y + m[4];\n out[1] = m[1] * x + m[3] * y + m[5];\n return out;\n}\n\n/**\n * Transforms the vec2 with a mat3\n * 3rd vector component is implicitly '1'\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a the vector to transform\n * @param {ReadonlyMat3} m matrix to transform with\n * @returns {NumericArray} out\n */\nexport function transformMat3(out, a, m) {\n const x = a[0];\n const y = a[1];\n out[0] = m[0] * x + m[3] * y + m[6];\n out[1] = m[1] * x + m[4] * y + m[7];\n return out;\n}\n\n/**\n * Transforms the vec2 with a mat4\n * 3rd vector component is implicitly '0'\n * 4th vector component is implicitly '1'\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a the vector to transform\n * @param {ReadonlyMat4} m matrix to transform with\n * @returns {NumericArray} out\n */\nexport function transformMat4(out, a, m) {\n const x = a[0];\n const y = a[1];\n out[0] = m[0] * x + m[4] * y + m[12];\n out[1] = m[1] * x + m[5] * y + m[13];\n return out;\n}\n\n/**\n * Rotate a 2D vector\n * @param {NumericArray} out The receiving vec2\n * @param {Readonly} a The vec2 point to rotate\n * @param {Readonly} b The origin of the rotation\n * @param {Number} rad The angle of rotation in radians\n * @returns {NumericArray} out\n */\nexport function rotate(out, a, b, rad) {\n // Translate point to the origin\n const p0 = a[0] - b[0];\n const p1 = a[1] - b[1];\n const sinC = Math.sin(rad);\n const cosC = Math.cos(rad);\n\n // perform rotation and translate to correct position\n out[0] = p0 * cosC - p1 * sinC + b[0];\n out[1] = p0 * sinC + p1 * cosC + b[1];\n\n return out;\n}\n\n/**\n * Get the angle between two 2D vectors\n * @param {Readonly} a The first operand\n * @param {Readonly} b The second operand\n * @returns {Number} The angle in radians\n */\nexport function angle(a, b) {\n const x1 = a[0];\n const y1 = a[1];\n const x2 = b[0];\n const y2 = b[1];\n // mag is the product of the magnitudes of a and b\n const mag = Math.sqrt((x1 * x1 + y1 * y1) * (x2 * x2 + y2 * y2));\n // mag &&.. short circuits if mag == 0\n const cosine = mag && (x1 * x2 + y1 * y2) / mag;\n // Math.min(Math.max(cosine, -1), 1) clamps the cosine between -1 and 1\n return Math.acos(Math.min(Math.max(cosine, -1), 1));\n}\n\n/**\n * Set the components of a vec2 to zero\n *\n * @param {NumericArray} out the receiving vector\n * @returns {NumericArray} out\n */\nexport function zero(out) {\n out[0] = 0.0;\n out[1] = 0.0;\n return out;\n}\n\n/**\n * Returns a string representation of a vector\n *\n * @param {Readonly} a vector to represent as a string\n * @returns {String} string representation of the vector\n */\nexport function str(a) {\n return `vec2(${a[0]}, ${a[1]})`;\n}\n\n/**\n * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===)\n *\n * @param {Readonly} a The first vector.\n * @param {Readonly} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1];\n}\n\n/**\n * Returns whether or not the vectors have approximately the same elements in the same position.\n *\n * @param {Readonly} a The first vector.\n * @param {Readonly} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\nexport function equals(a, b) {\n const a0 = a[0];\n const a1 = a[1];\n const b0 = b[0];\n const b1 = b[1];\n return (\n Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) &&\n Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1))\n );\n}\n\n/**\n * Alias for {@link vec2.length}\n * @function\n */\nexport const len = length;\n\n/**\n * Alias for {@link vec2.subtract}\n * @function\n */\nexport const sub = subtract;\n\n/**\n * Alias for {@link vec2.multiply}\n * @function\n */\nexport const mul = multiply;\n\n/**\n * Alias for {@link vec2.divide}\n * @function\n */\nexport const div = divide;\n\n/**\n * Alias for {@link vec2.distance}\n * @function\n */\nexport const dist = distance;\n\n/**\n * Alias for {@link vec2.squaredDistance}\n * @function\n */\nexport const sqrDist = squaredDistance;\n\n/**\n * Alias for {@link vec2.squaredLength}\n * @function\n */\nexport const sqrLen = squaredLength;\n\n/**\n * Perform some operation over an array of vec2s.\n *\n * @param {Array} a the array of vectors to iterate over\n * @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed\n * @param {Number} offset Number of elements to skip at the beginning of the array\n * @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array\n * @param {Function} fn Function to call for each vector in the array\n * @param {Object} [arg] additional argument to pass to fn\n * @returns {Array} a\n * @function\n */\nexport const forEach = (function () {\n const vec = create();\n\n return function (a, stride, offset, count, fn, arg) {\n let i;\n let l;\n if (!stride) {\n stride = 2;\n }\n\n if (!offset) {\n offset = 0;\n }\n\n if (count) {\n l = Math.min(count * stride + offset, a.length);\n } else {\n l = a.length;\n }\n\n for (i = offset; i < l; i += stride) {\n vec[0] = a[i];\n vec[1] = a[i + 1];\n fn(vec, vec, arg);\n a[i] = vec[0];\n a[i + 1] = vec[1];\n }\n\n return a;\n };\n})();\n","// @eslint-disable\n// @ts-nocheck\n\n/**\n * Common utilities\n * @module glMatrix\n */\n\n// Configuration Constants\nexport const EPSILON = 0.000001;\nexport let ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array;\nexport const RANDOM = Math.random;\nexport const ANGLE_ORDER = 'zyx';\n\n/**\n * Symmetric round\n * see https://www.npmjs.com/package/round-half-up-symmetric#user-content-detailed-background\n *\n * @param {Number} a value to round\n */\nexport function round(a) {\n if (a >= 0) return Math.round(a);\n\n return a % 0.5 === 0 ? Math.floor(a) : Math.round(a);\n}\n\n/**\n * Sets the type of array used when creating new vectors and matrices\n *\n * @param {Float32ArrayConstructor | ArrayConstructor} type Array type, such as Float32Array or Array\n */\nexport function setMatrixArrayType(type) {\n ARRAY_TYPE = type;\n}\n\nconst degree = Math.PI / 180;\n\n/**\n * Convert Degree To Radian\n *\n * @param {Number} a Angle in Degrees\n */\nexport function toRadian(a) {\n return a * degree;\n}\n\n/**\n * Tests whether or not the arguments have approximately the same value, within an absolute\n * or relative tolerance of glMatrix.EPSILON (an absolute tolerance is used for values less\n * than or equal to 1.0, and a relative tolerance is used for larger values)\n *\n * @param {Number} a The first number to test.\n * @param {Number} b The second number to test.\n * @returns {Boolean} True if the numbers are approximately equal, false otherwise.\n */\nexport function equals(a, b) {\n return Math.abs(a - b) <= EPSILON * Math.max(1.0, Math.abs(a), Math.abs(b));\n}\n","// math.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/* eslint-disable camelcase */\nimport {NumericArray} from '@math.gl/types';\n// vec2 additions\n\nexport function vec2_transformMat4AsVector(\n out: T,\n a: Readonly,\n m: Readonly\n): T {\n const x = a[0];\n const y = a[1];\n const w = m[3] * x + m[7] * y || 1.0;\n out[0] = (m[0] * x + m[4] * y) / w;\n out[1] = (m[1] * x + m[5] * y) / w;\n return out;\n}\n\n// vec3 additions\n\n// Transform as vector, only uses 3x3 minor matrix\nexport function vec3_transformMat4AsVector(\n out: T,\n a: Readonly,\n m: Readonly\n): T {\n const x = a[0];\n const y = a[1];\n const z = a[2];\n const w = m[3] * x + m[7] * y + m[11] * z || 1.0;\n out[0] = (m[0] * x + m[4] * y + m[8] * z) / w;\n out[1] = (m[1] * x + m[5] * y + m[9] * z) / w;\n out[2] = (m[2] * x + m[6] * y + m[10] * z) / w;\n return out;\n}\n\nexport function vec3_transformMat2(\n out: T,\n a: Readonly,\n m: Readonly\n): T {\n const x = a[0];\n const y = a[1];\n out[0] = m[0] * x + m[2] * y;\n out[1] = m[1] * x + m[3] * y;\n out[2] = a[2];\n return out;\n}\n\n// vec4 additions\n\nexport function vec4_transformMat2(\n out: T,\n a: Readonly,\n m: Readonly\n): T {\n const x = a[0];\n const y = a[1];\n out[0] = m[0] * x + m[2] * y;\n out[1] = m[1] * x + m[3] * y;\n out[2] = a[2];\n out[3] = a[3];\n return out;\n}\n\nexport function vec4_transformMat3(\n out: T,\n a: Readonly,\n m: Readonly\n): T {\n const x = a[0];\n const y = a[1];\n const z = a[2];\n out[0] = m[0] * x + m[3] * y + m[6] * z;\n out[1] = m[1] * x + m[4] * y + m[7] * z;\n out[2] = m[2] * x + m[5] * y + m[8] * z;\n out[3] = a[3];\n return out;\n}\n","// @eslint-disable\n// @ts-nocheck\n\nimport * as glMatrix from './common.js';\n\n/**\n * 3 Dimensional Vector\n * @module vec3\n */\n\n/**\n * Creates a new, empty vec3\n *\n * @returns {vec3} a new 3D vector\n */\nexport function create() {\n const out = new glMatrix.ARRAY_TYPE(3);\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[0] = 0;\n out[1] = 0;\n out[2] = 0;\n }\n return out;\n}\n\n/**\n * Creates a new vec3 initialized with values from an existing vector\n *\n * @param {ReadonlyVec3} a vector to clone\n * @returns {vec3} a new 3D vector\n */\nexport function clone(a) {\n const out = new glMatrix.ARRAY_TYPE(3);\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n return out;\n}\n\n/**\n * Calculates the length of a vec3\n *\n * @param {ReadonlyVec3} a vector to calculate length of\n * @returns {Number} length of a\n */\nexport function length(a) {\n const x = a[0];\n const y = a[1];\n const z = a[2];\n return Math.sqrt(x * x + y * y + z * z);\n}\n\n/**\n * Creates a new vec3 initialized with the given values\n *\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @returns {vec3} a new 3D vector\n */\nexport function fromValues(x, y, z) {\n const out = new glMatrix.ARRAY_TYPE(3);\n out[0] = x;\n out[1] = y;\n out[2] = z;\n return out;\n}\n\n/**\n * Copy the values from one vec3 to another\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the source vector\n * @returns {vec3} out\n */\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n return out;\n}\n\n/**\n * Set the components of a vec3 to the given values\n *\n * @param {vec3} out the receiving vector\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @returns {vec3} out\n */\nexport function set(out, x, y, z) {\n out[0] = x;\n out[1] = y;\n out[2] = z;\n return out;\n}\n\n/**\n * Adds two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n out[2] = a[2] + b[2];\n return out;\n}\n\n/**\n * Subtracts vector b from vector a\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n out[2] = a[2] - b[2];\n return out;\n}\n\n/**\n * Multiplies two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\nexport function multiply(out, a, b) {\n out[0] = a[0] * b[0];\n out[1] = a[1] * b[1];\n out[2] = a[2] * b[2];\n return out;\n}\n\n/**\n * Divides two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\nexport function divide(out, a, b) {\n out[0] = a[0] / b[0];\n out[1] = a[1] / b[1];\n out[2] = a[2] / b[2];\n return out;\n}\n\n/**\n * Math.ceil the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to ceil\n * @returns {vec3} out\n */\nexport function ceil(out, a) {\n out[0] = Math.ceil(a[0]);\n out[1] = Math.ceil(a[1]);\n out[2] = Math.ceil(a[2]);\n return out;\n}\n\n/**\n * Math.floor the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to floor\n * @returns {vec3} out\n */\nexport function floor(out, a) {\n out[0] = Math.floor(a[0]);\n out[1] = Math.floor(a[1]);\n out[2] = Math.floor(a[2]);\n return out;\n}\n\n/**\n * Returns the minimum of two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\nexport function min(out, a, b) {\n out[0] = Math.min(a[0], b[0]);\n out[1] = Math.min(a[1], b[1]);\n out[2] = Math.min(a[2], b[2]);\n return out;\n}\n\n/**\n * Returns the maximum of two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\nexport function max(out, a, b) {\n out[0] = Math.max(a[0], b[0]);\n out[1] = Math.max(a[1], b[1]);\n out[2] = Math.max(a[2], b[2]);\n return out;\n}\n\n/**\n * symmetric round the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to round\n * @returns {vec3} out\n */\nexport function round(out, a) {\n out[0] = glMatrix.round(a[0]);\n out[1] = glMatrix.round(a[1]);\n out[2] = glMatrix.round(a[2]);\n return out;\n}\n\n/**\n * Scales a vec3 by a scalar number\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the vector to scale\n * @param {Number} b amount to scale the vector by\n * @returns {vec3} out\n */\nexport function scale(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n out[2] = a[2] * b;\n return out;\n}\n\n/**\n * Adds two vec3's after scaling the second operand by a scalar value\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {Number} scale the amount to scale b by before adding\n * @returns {vec3} out\n */\nexport function scaleAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n out[2] = a[2] + b[2] * scale;\n return out;\n}\n\n/**\n * Calculates the euclidian distance between two vec3's\n *\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {Number} distance between a and b\n */\nexport function distance(a, b) {\n const x = b[0] - a[0];\n const y = b[1] - a[1];\n const z = b[2] - a[2];\n return Math.sqrt(x * x + y * y + z * z);\n}\n\n/**\n * Calculates the squared euclidian distance between two vec3's\n *\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {Number} squared distance between a and b\n */\nexport function squaredDistance(a, b) {\n const x = b[0] - a[0];\n const y = b[1] - a[1];\n const z = b[2] - a[2];\n return x * x + y * y + z * z;\n}\n\n/**\n * Calculates the squared length of a vec3\n *\n * @param {ReadonlyVec3} a vector to calculate squared length of\n * @returns {Number} squared length of a\n */\nexport function squaredLength(a) {\n const x = a[0];\n const y = a[1];\n const z = a[2];\n return x * x + y * y + z * z;\n}\n\n/**\n * Negates the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to negate\n * @returns {vec3} out\n */\nexport function negate(out, a) {\n out[0] = -a[0];\n out[1] = -a[1];\n out[2] = -a[2];\n return out;\n}\n\n/**\n * Returns the inverse of the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to invert\n * @returns {vec3} out\n */\nexport function inverse(out, a) {\n out[0] = 1.0 / a[0];\n out[1] = 1.0 / a[1];\n out[2] = 1.0 / a[2];\n return out;\n}\n\n/**\n * Normalize a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to normalize\n * @returns {vec3} out\n */\nexport function normalize(out, a) {\n const x = a[0];\n const y = a[1];\n const z = a[2];\n let len = x * x + y * y + z * z;\n if (len > 0) {\n // TODO: evaluate use of glm_invsqrt here?\n len = 1 / Math.sqrt(len);\n }\n out[0] = a[0] * len;\n out[1] = a[1] * len;\n out[2] = a[2] * len;\n return out;\n}\n\n/**\n * Calculates the dot product of two vec3's\n *\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {Number} dot product of a and b\n */\nexport function dot(a, b) {\n return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];\n}\n\n/**\n * Computes the cross product of two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\nexport function cross(out, a, b) {\n const ax = a[0];\n const ay = a[1];\n const az = a[2];\n const bx = b[0];\n const by = b[1];\n const bz = b[2];\n\n out[0] = ay * bz - az * by;\n out[1] = az * bx - ax * bz;\n out[2] = ax * by - ay * bx;\n return out;\n}\n\n/**\n * Performs a linear interpolation between two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec3} out\n */\nexport function lerp(out, a, b, t) {\n const ax = a[0];\n const ay = a[1];\n const az = a[2];\n out[0] = ax + t * (b[0] - ax);\n out[1] = ay + t * (b[1] - ay);\n out[2] = az + t * (b[2] - az);\n return out;\n}\n\n/**\n * Performs a spherical linear interpolation between two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec3} out\n */\nexport function slerp(out, a, b, t) {\n const angle = Math.acos(Math.min(Math.max(dot(a, b), -1), 1));\n const sinTotal = Math.sin(angle);\n\n const ratioA = Math.sin((1 - t) * angle) / sinTotal;\n const ratioB = Math.sin(t * angle) / sinTotal;\n out[0] = ratioA * a[0] + ratioB * b[0];\n out[1] = ratioA * a[1] + ratioB * b[1];\n out[2] = ratioA * a[2] + ratioB * b[2];\n\n return out;\n}\n\n/**\n * Performs a hermite interpolation with two control points\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {ReadonlyVec3} c the third operand\n * @param {ReadonlyVec3} d the fourth operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec3} out\n */\nexport function hermite(out, a, b, c, d, t) {\n const factorTimes2 = t * t;\n const factor1 = factorTimes2 * (2 * t - 3) + 1;\n const factor2 = factorTimes2 * (t - 2) + t;\n const factor3 = factorTimes2 * (t - 1);\n const factor4 = factorTimes2 * (3 - 2 * t);\n\n out[0] = a[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4;\n out[1] = a[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4;\n out[2] = a[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4;\n\n return out;\n}\n\n/**\n * Performs a bezier interpolation with two control points\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {ReadonlyVec3} c the third operand\n * @param {ReadonlyVec3} d the fourth operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec3} out\n */\nexport function bezier(out, a, b, c, d, t) {\n const inverseFactor = 1 - t;\n const inverseFactorTimesTwo = inverseFactor * inverseFactor;\n const factorTimes2 = t * t;\n const factor1 = inverseFactorTimesTwo * inverseFactor;\n const factor2 = 3 * t * inverseFactorTimesTwo;\n const factor3 = 3 * factorTimes2 * inverseFactor;\n const factor4 = factorTimes2 * t;\n\n out[0] = a[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4;\n out[1] = a[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4;\n out[2] = a[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4;\n\n return out;\n}\n\n/**\n * Generates a random vector with the given scale\n *\n * @param {vec3} out the receiving vector\n * @param {Number} [scale] Length of the resulting vector. If omitted, a unit vector will be returned\n * @returns {vec3} out\n */\nexport function random(out, scale) {\n scale = scale === undefined ? 1.0 : scale;\n\n const r = glMatrix.RANDOM() * 2.0 * Math.PI;\n const z = glMatrix.RANDOM() * 2.0 - 1.0;\n const zScale = Math.sqrt(1.0 - z * z) * scale;\n\n out[0] = Math.cos(r) * zScale;\n out[1] = Math.sin(r) * zScale;\n out[2] = z * scale;\n return out;\n}\n\n/**\n * Transforms the vec3 with a mat4.\n * 4th vector component is implicitly '1'\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the vector to transform\n * @param {ReadonlyMat4} m matrix to transform with\n * @returns {vec3} out\n */\nexport function transformMat4(out, a, m) {\n const x = a[0];\n const y = a[1];\n const z = a[2];\n let w = m[3] * x + m[7] * y + m[11] * z + m[15];\n w = w || 1.0;\n out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w;\n out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w;\n out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w;\n return out;\n}\n\n/**\n * Transforms the vec3 with a mat3.\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the vector to transform\n * @param {ReadonlyMat3} m the 3x3 matrix to transform with\n * @returns {vec3} out\n */\nexport function transformMat3(out, a, m) {\n const x = a[0];\n const y = a[1];\n const z = a[2];\n out[0] = x * m[0] + y * m[3] + z * m[6];\n out[1] = x * m[1] + y * m[4] + z * m[7];\n out[2] = x * m[2] + y * m[5] + z * m[8];\n return out;\n}\n\n/**\n * Transforms the vec3 with a quat\n * Can also be used for dual quaternions. (Multiply it with the real part)\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the vector to transform\n * @param {ReadonlyQuat} q quaternion to transform with\n * @returns {vec3} out\n */\nexport function transformQuat(out, a, q) {\n // benchmarks: https://jsperf.com/quaternion-transform-vec3-implementations-fixed\n const qx = q[0];\n const qy = q[1];\n const qz = q[2];\n const qw = q[3];\n const x = a[0];\n const y = a[1];\n const z = a[2];\n // var qvec = [qx, qy, qz];\n // var uv = vec3.cross([], qvec, a);\n let uvx = qy * z - qz * y;\n let uvy = qz * x - qx * z;\n let uvz = qx * y - qy * x;\n // var uuv = vec3.cross([], qvec, uv);\n let uuvx = qy * uvz - qz * uvy;\n let uuvy = qz * uvx - qx * uvz;\n let uuvz = qx * uvy - qy * uvx;\n // vec3.scale(uv, uv, 2 * w);\n const w2 = qw * 2;\n uvx *= w2;\n uvy *= w2;\n uvz *= w2;\n // vec3.scale(uuv, uuv, 2);\n uuvx *= 2;\n uuvy *= 2;\n uuvz *= 2;\n // return vec3.add(out, a, vec3.add(out, uv, uuv));\n out[0] = x + uvx + uuvx;\n out[1] = y + uvy + uuvy;\n out[2] = z + uvz + uuvz;\n return out;\n}\n\n/**\n * Rotate a 3D vector around the x-axis\n * @param {vec3} out The receiving vec3\n * @param {ReadonlyVec3} a The vec3 point to rotate\n * @param {ReadonlyVec3} b The origin of the rotation\n * @param {Number} rad The angle of rotation in radians\n * @returns {vec3} out\n */\nexport function rotateX(out, a, b, rad) {\n const p = [];\n const r = [];\n // Translate point to the origin\n p[0] = a[0] - b[0];\n p[1] = a[1] - b[1];\n p[2] = a[2] - b[2];\n\n // perform rotation\n r[0] = p[0];\n r[1] = p[1] * Math.cos(rad) - p[2] * Math.sin(rad);\n r[2] = p[1] * Math.sin(rad) + p[2] * Math.cos(rad);\n\n // translate to correct position\n out[0] = r[0] + b[0];\n out[1] = r[1] + b[1];\n out[2] = r[2] + b[2];\n\n return out;\n}\n\n/**\n * Rotate a 3D vector around the y-axis\n * @param {vec3} out The receiving vec3\n * @param {ReadonlyVec3} a The vec3 point to rotate\n * @param {ReadonlyVec3} b The origin of the rotation\n * @param {Number} rad The angle of rotation in radians\n * @returns {vec3} out\n */\nexport function rotateY(out, a, b, rad) {\n const p = [];\n const r = [];\n // Translate point to the origin\n p[0] = a[0] - b[0];\n p[1] = a[1] - b[1];\n p[2] = a[2] - b[2];\n\n // perform rotation\n r[0] = p[2] * Math.sin(rad) + p[0] * Math.cos(rad);\n r[1] = p[1];\n r[2] = p[2] * Math.cos(rad) - p[0] * Math.sin(rad);\n\n // translate to correct position\n out[0] = r[0] + b[0];\n out[1] = r[1] + b[1];\n out[2] = r[2] + b[2];\n\n return out;\n}\n\n/**\n * Rotate a 3D vector around the z-axis\n * @param {vec3} out The receiving vec3\n * @param {ReadonlyVec3} a The vec3 point to rotate\n * @param {ReadonlyVec3} b The origin of the rotation\n * @param {Number} rad The angle of rotation in radians\n * @returns {vec3} out\n */\nexport function rotateZ(out, a, b, rad) {\n const p = [];\n const r = [];\n // Translate point to the origin\n p[0] = a[0] - b[0];\n p[1] = a[1] - b[1];\n p[2] = a[2] - b[2];\n\n // perform rotation\n r[0] = p[0] * Math.cos(rad) - p[1] * Math.sin(rad);\n r[1] = p[0] * Math.sin(rad) + p[1] * Math.cos(rad);\n r[2] = p[2];\n\n // translate to correct position\n out[0] = r[0] + b[0];\n out[1] = r[1] + b[1];\n out[2] = r[2] + b[2];\n\n return out;\n}\n\n/**\n * Get the angle between two 3D vectors\n * @param {ReadonlyVec3} a The first operand\n * @param {ReadonlyVec3} b The second operand\n * @returns {Number} The angle in radians\n */\nexport function angle(a, b) {\n const ax = a[0];\n const ay = a[1];\n const az = a[2];\n const bx = b[0];\n const by = b[1];\n const bz = b[2];\n const mag = Math.sqrt((ax * ax + ay * ay + az * az) * (bx * bx + by * by + bz * bz));\n const cosine = mag && dot(a, b) / mag;\n return Math.acos(Math.min(Math.max(cosine, -1), 1));\n}\n\n/**\n * Set the components of a vec3 to zero\n *\n * @param {vec3} out the receiving vector\n * @returns {vec3} out\n */\nexport function zero(out) {\n out[0] = 0.0;\n out[1] = 0.0;\n out[2] = 0.0;\n return out;\n}\n\n/**\n * Returns a string representation of a vector\n *\n * @param {ReadonlyVec3} a vector to represent as a string\n * @returns {String} string representation of the vector\n */\nexport function str(a) {\n return `vec3(${a[0]}, ${a[1]}, ${a[2]})`;\n}\n\n/**\n * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyVec3} a The first vector.\n * @param {ReadonlyVec3} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1] && a[2] === b[2];\n}\n\n/**\n * Returns whether or not the vectors have approximately the same elements in the same position.\n *\n * @param {ReadonlyVec3} a The first vector.\n * @param {ReadonlyVec3} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\nexport function equals(a, b) {\n const a0 = a[0];\n const a1 = a[1];\n const a2 = a[2];\n const b0 = b[0];\n const b1 = b[1];\n const b2 = b[2];\n return (\n Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) &&\n Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) &&\n Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2))\n );\n}\n\n/**\n * Alias for {@link vec3.subtract}\n * @function\n */\nexport const sub = subtract;\n\n/**\n * Alias for {@link vec3.multiply}\n * @function\n */\nexport const mul = multiply;\n\n/**\n * Alias for {@link vec3.divide}\n * @function\n */\nexport const div = divide;\n\n/**\n * Alias for {@link vec3.distance}\n * @function\n */\nexport const dist = distance;\n\n/**\n * Alias for {@link vec3.squaredDistance}\n * @function\n */\nexport const sqrDist = squaredDistance;\n\n/**\n * Alias for {@link vec3.length}\n * @function\n */\nexport const len = length;\n\n/**\n * Alias for {@link vec3.squaredLength}\n * @function\n */\nexport const sqrLen = squaredLength;\n\n/**\n * Perform some operation over an array of vec3s.\n *\n * @param {Array} a the array of vectors to iterate over\n * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed\n * @param {Number} offset Number of elements to skip at the beginning of the array\n * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array\n * @param {Function} fn Function to call for each vector in the array\n * @param {Object} [arg] additional argument to pass to fn\n * @returns {Array} a\n * @function\n */\nexport const forEach = (function () {\n const vec = create();\n\n return function (a, stride, offset, count, fn, arg) {\n let i;\n let l;\n if (!stride) {\n stride = 3;\n }\n\n if (!offset) {\n offset = 0;\n }\n\n if (count) {\n l = Math.min(count * stride + offset, a.length);\n } else {\n l = a.length;\n }\n\n for (i = offset; i < l; i += stride) {\n vec[0] = a[i];\n vec[1] = a[i + 1];\n vec[2] = a[i + 2];\n fn(vec, vec, arg);\n a[i] = vec[0];\n a[i + 1] = vec[1];\n a[i + 2] = vec[2];\n }\n\n return a;\n };\n})();\n","// math.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n// Copyright (c) 2017 Uber Technologies, Inc.\n\nimport {NumericArray, NumericArray3} from '@math.gl/types';\nimport {Vector} from './base/vector';\nimport {config, isArray} from '../lib/common';\nimport {checkNumber} from '../lib/validators';\n// @ts-ignore gl-matrix types\nimport {\n angle as vec3_angle,\n cross as vec3_cross,\n rotateX as vec3_rotateX,\n rotateY as vec3_rotateY,\n rotateZ as vec3_rotateZ,\n transformMat4 as vec3_transformMat4,\n transformMat3 as vec3_transformMat3,\n transformQuat as vec3_transformQuat\n} from '../gl-matrix/vec3';\n/* eslint-disable camelcase */\nimport {vec3_transformMat2, vec3_transformMat4AsVector} from '../lib/gl-matrix-extras';\n\nconst ORIGIN = [0, 0, 0];\n\nlet ZERO: Vector3;\n\n/** Helper type that captures array length for a 3 element vector */\nexport type Vector3Like = Vector3 | NumericArray3;\n\n/**\n * Three-element vector class with common linear algebra operations.\n * Subclass of Array meaning that it is highly compatible with other libraries\n */\nexport class Vector3 extends Vector {\n static get ZERO(): Vector3 {\n if (!ZERO) {\n ZERO = new Vector3(0, 0, 0);\n Object.freeze(ZERO);\n }\n return ZERO;\n }\n\n /**\n * @class\n * @param x\n * @param y\n * @param z\n */\n constructor(x: number | Readonly = 0, y: number = 0, z: number = 0) {\n // PERF NOTE: initialize elements as double precision numbers\n super(-0, -0, -0);\n if (arguments.length === 1 && isArray(x)) {\n this.copy(x as NumericArray);\n } else {\n // this.set(x, y, z);\n if (config.debug) {\n checkNumber(x);\n checkNumber(y);\n checkNumber(z);\n }\n // @ts-expect-error TS2412: Property '0' of type 'number | [number, number, number]' is not assignable to numeric index type 'number'\n this[0] = x;\n this[1] = y;\n this[2] = z;\n }\n }\n\n set(x: number, y: number, z: number): this {\n this[0] = x;\n this[1] = y;\n this[2] = z;\n return this.check();\n }\n\n copy(array: Readonly): this {\n this[0] = array[0];\n this[1] = array[1];\n this[2] = array[2];\n return this.check();\n }\n\n fromObject(object: {x: number; y: number; z: number}): this {\n if (config.debug) {\n checkNumber(object.x);\n checkNumber(object.y);\n checkNumber(object.z);\n }\n this[0] = object.x;\n this[1] = object.y;\n this[2] = object.z;\n return this.check();\n }\n\n override toObject(object: {x?: number; y?: number; z?: number}): {\n x: number;\n y: number;\n z: number;\n } {\n object.x = this[0];\n object.y = this[1];\n object.z = this[2];\n return object as {x: number; y: number; z: number};\n }\n\n // Getters/setters\n\n get ELEMENTS(): number {\n return 3;\n }\n get z(): number {\n return this[2];\n }\n set z(value: number) {\n this[2] = checkNumber(value);\n }\n\n // ACCESSORS\n\n angle(vector: Readonly): number {\n return vec3_angle(this, vector);\n }\n\n // MODIFIERS\n\n cross(vector: Readonly): this {\n vec3_cross(this, this, vector);\n return this.check();\n }\n\n rotateX({radians, origin = ORIGIN}: {radians: number; origin?: Readonly}): this {\n vec3_rotateX(this, this, origin, radians);\n return this.check();\n }\n\n rotateY({radians, origin = ORIGIN}: {radians: number; origin?: Readonly}): this {\n vec3_rotateY(this, this, origin, radians);\n return this.check();\n }\n\n rotateZ({radians, origin = ORIGIN}: {radians: number; origin?: Readonly}): this {\n vec3_rotateZ(this, this, origin, radians);\n return this.check();\n }\n\n // Transforms\n\n // transforms as point (4th component is implicitly 1)\n transform(matrix4: Readonly): this {\n return this.transformAsPoint(matrix4);\n }\n\n // transforms as point (4th component is implicitly 1)\n transformAsPoint(matrix4: Readonly): this {\n vec3_transformMat4(this, this, matrix4);\n return this.check();\n }\n\n // transforms as vector (4th component is implicitly 0, ignores translation. slightly faster)\n transformAsVector(matrix4: Readonly): this {\n vec3_transformMat4AsVector(this, this, matrix4);\n return this.check();\n }\n\n transformByMatrix3(matrix3: Readonly): this {\n vec3_transformMat3(this, this, matrix3);\n return this.check();\n }\n\n transformByMatrix2(matrix2: Readonly): this {\n vec3_transformMat2(this, this, matrix2);\n return this.check();\n }\n\n transformByQuaternion(quaternion: Readonly): this {\n vec3_transformQuat(this, this, quaternion);\n return this.check();\n }\n}\n","// math.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n// Copyright (c) 2017 Uber Technologies, Inc.\n\nimport {NumericArray} from '@math.gl/types';\nimport {MathArray} from './math-array';\nimport {checkNumber} from '../../lib/validators';\nimport {config} from '../../lib/common';\n\n/** Base class for matrices */\nexport abstract class Matrix extends MathArray {\n abstract get RANK(): number;\n\n // fromObject(object) {\n // const array = object.elements;\n // return this.fromRowMajor(array);\n // }\n // toObject(object) {\n // const array = object.elements;\n // this.toRowMajor(array);\n // return object;\n // }\n\n // TODO better override formatString?\n override toString(): string {\n let string = '[';\n if (config.printRowMajor) {\n string += 'row-major:';\n for (let row = 0; row < this.RANK; ++row) {\n for (let col = 0; col < this.RANK; ++col) {\n string += ` ${this[col * this.RANK + row]}`;\n }\n }\n } else {\n string += 'column-major:';\n for (let i = 0; i < this.ELEMENTS; ++i) {\n string += ` ${this[i]}`;\n }\n }\n string += ']';\n return string;\n }\n\n getElementIndex(row: number, col: number): number {\n return col * this.RANK + row;\n }\n\n // By default assumes row major indices\n getElement(row: number, col: number): number {\n return this[col * this.RANK + row];\n }\n\n // By default assumes row major indices\n setElement(row: number, col: number, value: number): this {\n this[col * this.RANK + row] = checkNumber(value);\n return this;\n }\n getColumn(columnIndex: number, result: NumArrayT): NumArrayT;\n getColumn(columnIndex: number): number[];\n\n getColumn(\n columnIndex: number,\n result: number[] = new Array(this.RANK).fill(-0)\n ): number[] {\n const firstIndex = columnIndex * this.RANK;\n for (let i = 0; i < this.RANK; ++i) {\n result[i] = this[firstIndex + i];\n }\n return result;\n }\n\n setColumn(columnIndex: number, columnVector: Readonly): this {\n const firstIndex = columnIndex * this.RANK;\n for (let i = 0; i < this.RANK; ++i) {\n this[firstIndex + i] = columnVector[i];\n }\n return this;\n }\n}\n","// @eslint-disable\n// @ts-nocheck\n\nimport * as glMatrix from './common.js';\n\n/**\n * 4x4 Matrix
Format: column-major, when typed out it looks like row-major
The matrices are being post multiplied.\n * @module mat4\n */\n\n/**\n * Creates a new identity mat4\n *\n * @returns a new 4x4 matrix\n */\nexport function create() {\n const out = new glMatrix.ARRAY_TYPE(16);\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n }\n out[0] = 1;\n out[5] = 1;\n out[10] = 1;\n out[15] = 1;\n return out;\n}\n\n/**\n * Creates a new mat4 initialized with values from an existing matrix\n *\n * @param {ReadonlyMat4} a matrix to clone\n * @returns {mat4} a new 4x4 matrix\n */\nexport function clone(a) {\n const out = new glMatrix.ARRAY_TYPE(16);\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n out[9] = a[9];\n out[10] = a[10];\n out[11] = a[11];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n return out;\n}\n\n/**\n * Copy the values from one mat4 to another\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4} out\n */\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n out[9] = a[9];\n out[10] = a[10];\n out[11] = a[11];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n return out;\n}\n\n/**\n * Create a new mat4 with the given values\n *\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\n * @param {Number} m03 Component in column 0, row 3 position (index 3)\n * @param {Number} m10 Component in column 1, row 0 position (index 4)\n * @param {Number} m11 Component in column 1, row 1 position (index 5)\n * @param {Number} m12 Component in column 1, row 2 position (index 6)\n * @param {Number} m13 Component in column 1, row 3 position (index 7)\n * @param {Number} m20 Component in column 2, row 0 position (index 8)\n * @param {Number} m21 Component in column 2, row 1 position (index 9)\n * @param {Number} m22 Component in column 2, row 2 position (index 10)\n * @param {Number} m23 Component in column 2, row 3 position (index 11)\n * @param {Number} m30 Component in column 3, row 0 position (index 12)\n * @param {Number} m31 Component in column 3, row 1 position (index 13)\n * @param {Number} m32 Component in column 3, row 2 position (index 14)\n * @param {Number} m33 Component in column 3, row 3 position (index 15)\n * @returns {mat4} A new mat4\n */\nexport function fromValues(\n m00,\n m01,\n m02,\n m03,\n m10,\n m11,\n m12,\n m13,\n m20,\n m21,\n m22,\n m23,\n m30,\n m31,\n m32,\n m33\n) {\n const out = new glMatrix.ARRAY_TYPE(16);\n out[0] = m00;\n out[1] = m01;\n out[2] = m02;\n out[3] = m03;\n out[4] = m10;\n out[5] = m11;\n out[6] = m12;\n out[7] = m13;\n out[8] = m20;\n out[9] = m21;\n out[10] = m22;\n out[11] = m23;\n out[12] = m30;\n out[13] = m31;\n out[14] = m32;\n out[15] = m33;\n return out;\n}\n\n/**\n * Set the components of a mat4 to the given values\n *\n * @param {mat4} out the receiving matrix\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\n * @param {Number} m03 Component in column 0, row 3 position (index 3)\n * @param {Number} m10 Component in column 1, row 0 position (index 4)\n * @param {Number} m11 Component in column 1, row 1 position (index 5)\n * @param {Number} m12 Component in column 1, row 2 position (index 6)\n * @param {Number} m13 Component in column 1, row 3 position (index 7)\n * @param {Number} m20 Component in column 2, row 0 position (index 8)\n * @param {Number} m21 Component in column 2, row 1 position (index 9)\n * @param {Number} m22 Component in column 2, row 2 position (index 10)\n * @param {Number} m23 Component in column 2, row 3 position (index 11)\n * @param {Number} m30 Component in column 3, row 0 position (index 12)\n * @param {Number} m31 Component in column 3, row 1 position (index 13)\n * @param {Number} m32 Component in column 3, row 2 position (index 14)\n * @param {Number} m33 Component in column 3, row 3 position (index 15)\n * @returns {mat4} out\n */\nexport function set(\n out,\n m00,\n m01,\n m02,\n m03,\n m10,\n m11,\n m12,\n m13,\n m20,\n m21,\n m22,\n m23,\n m30,\n m31,\n m32,\n m33\n) {\n out[0] = m00;\n out[1] = m01;\n out[2] = m02;\n out[3] = m03;\n out[4] = m10;\n out[5] = m11;\n out[6] = m12;\n out[7] = m13;\n out[8] = m20;\n out[9] = m21;\n out[10] = m22;\n out[11] = m23;\n out[12] = m30;\n out[13] = m31;\n out[14] = m32;\n out[15] = m33;\n return out;\n}\n\n/**\n * Set a mat4 to the identity matrix\n *\n * @param {mat4} out the receiving matrix\n * @returns {mat4} out\n */\nexport function identity(out) {\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = 1;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 1;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n\n/**\n * Transpose the values of a mat4\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4} out\n */\nexport function transpose(out, a) {\n // If we are transposing ourselves we can skip a few steps but have to cache some values\n if (out === a) {\n const a01 = a[1];\n const a02 = a[2];\n const a03 = a[3];\n const a12 = a[6];\n const a13 = a[7];\n const a23 = a[11];\n\n out[1] = a[4];\n out[2] = a[8];\n out[3] = a[12];\n out[4] = a01;\n out[6] = a[9];\n out[7] = a[13];\n out[8] = a02;\n out[9] = a12;\n out[11] = a[14];\n out[12] = a03;\n out[13] = a13;\n out[14] = a23;\n } else {\n out[0] = a[0];\n out[1] = a[4];\n out[2] = a[8];\n out[3] = a[12];\n out[4] = a[1];\n out[5] = a[5];\n out[6] = a[9];\n out[7] = a[13];\n out[8] = a[2];\n out[9] = a[6];\n out[10] = a[10];\n out[11] = a[14];\n out[12] = a[3];\n out[13] = a[7];\n out[14] = a[11];\n out[15] = a[15];\n }\n\n return out;\n}\n\n/**\n * Inverts a mat4\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4} out\n */\nexport function invert(out, a) {\n const a00 = a[0];\n const a01 = a[1];\n const a02 = a[2];\n const a03 = a[3];\n const a10 = a[4];\n const a11 = a[5];\n const a12 = a[6];\n const a13 = a[7];\n const a20 = a[8];\n const a21 = a[9];\n const a22 = a[10];\n const a23 = a[11];\n const a30 = a[12];\n const a31 = a[13];\n const a32 = a[14];\n const a33 = a[15];\n\n const b00 = a00 * a11 - a01 * a10;\n const b01 = a00 * a12 - a02 * a10;\n const b02 = a00 * a13 - a03 * a10;\n const b03 = a01 * a12 - a02 * a11;\n const b04 = a01 * a13 - a03 * a11;\n const b05 = a02 * a13 - a03 * a12;\n const b06 = a20 * a31 - a21 * a30;\n const b07 = a20 * a32 - a22 * a30;\n const b08 = a20 * a33 - a23 * a30;\n const b09 = a21 * a32 - a22 * a31;\n const b10 = a21 * a33 - a23 * a31;\n const b11 = a22 * a33 - a23 * a32;\n\n // Calculate the determinant\n let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n if (!det) {\n return null;\n }\n det = 1.0 / det;\n\n out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;\n out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;\n out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;\n out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;\n out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;\n out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;\n out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;\n out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;\n out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;\n out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;\n out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;\n out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;\n out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;\n out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;\n out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;\n out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;\n\n return out;\n}\n\n/**\n * Calculates the adjugate of a mat4\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4} out\n */\nexport function adjoint(out, a) {\n const a00 = a[0];\n const a01 = a[1];\n const a02 = a[2];\n const a03 = a[3];\n const a10 = a[4];\n const a11 = a[5];\n const a12 = a[6];\n const a13 = a[7];\n const a20 = a[8];\n const a21 = a[9];\n const a22 = a[10];\n const a23 = a[11];\n const a30 = a[12];\n const a31 = a[13];\n const a32 = a[14];\n const a33 = a[15];\n\n const b00 = a00 * a11 - a01 * a10;\n const b01 = a00 * a12 - a02 * a10;\n const b02 = a00 * a13 - a03 * a10;\n const b03 = a01 * a12 - a02 * a11;\n const b04 = a01 * a13 - a03 * a11;\n const b05 = a02 * a13 - a03 * a12;\n const b06 = a20 * a31 - a21 * a30;\n const b07 = a20 * a32 - a22 * a30;\n const b08 = a20 * a33 - a23 * a30;\n const b09 = a21 * a32 - a22 * a31;\n const b10 = a21 * a33 - a23 * a31;\n const b11 = a22 * a33 - a23 * a32;\n\n out[0] = a11 * b11 - a12 * b10 + a13 * b09;\n out[1] = a02 * b10 - a01 * b11 - a03 * b09;\n out[2] = a31 * b05 - a32 * b04 + a33 * b03;\n out[3] = a22 * b04 - a21 * b05 - a23 * b03;\n out[4] = a12 * b08 - a10 * b11 - a13 * b07;\n out[5] = a00 * b11 - a02 * b08 + a03 * b07;\n out[6] = a32 * b02 - a30 * b05 - a33 * b01;\n out[7] = a20 * b05 - a22 * b02 + a23 * b01;\n out[8] = a10 * b10 - a11 * b08 + a13 * b06;\n out[9] = a01 * b08 - a00 * b10 - a03 * b06;\n out[10] = a30 * b04 - a31 * b02 + a33 * b00;\n out[11] = a21 * b02 - a20 * b04 - a23 * b00;\n out[12] = a11 * b07 - a10 * b09 - a12 * b06;\n out[13] = a00 * b09 - a01 * b07 + a02 * b06;\n out[14] = a31 * b01 - a30 * b03 - a32 * b00;\n out[15] = a20 * b03 - a21 * b01 + a22 * b00;\n return out;\n}\n\n/**\n * Calculates the determinant of a mat4\n *\n * @param {ReadonlyMat4} a the source matrix\n * @returns {Number} determinant of a\n */\nexport function determinant(a) {\n const a00 = a[0];\n const a01 = a[1];\n const a02 = a[2];\n const a03 = a[3];\n const a10 = a[4];\n const a11 = a[5];\n const a12 = a[6];\n const a13 = a[7];\n const a20 = a[8];\n const a21 = a[9];\n const a22 = a[10];\n const a23 = a[11];\n const a30 = a[12];\n const a31 = a[13];\n const a32 = a[14];\n const a33 = a[15];\n\n const b0 = a00 * a11 - a01 * a10;\n const b1 = a00 * a12 - a02 * a10;\n const b2 = a01 * a12 - a02 * a11;\n const b3 = a20 * a31 - a21 * a30;\n const b4 = a20 * a32 - a22 * a30;\n const b5 = a21 * a32 - a22 * a31;\n const b6 = a00 * b5 - a01 * b4 + a02 * b3;\n const b7 = a10 * b5 - a11 * b4 + a12 * b3;\n const b8 = a20 * b2 - a21 * b1 + a22 * b0;\n const b9 = a30 * b2 - a31 * b1 + a32 * b0;\n\n // Calculate the determinant\n return a13 * b6 - a03 * b7 + a33 * b8 - a23 * b9;\n}\n\n/**\n * Multiplies two mat4s\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @returns {mat4} out\n */\nexport function multiply(out, a, b) {\n const a00 = a[0];\n const a01 = a[1];\n const a02 = a[2];\n const a03 = a[3];\n const a10 = a[4];\n const a11 = a[5];\n const a12 = a[6];\n const a13 = a[7];\n const a20 = a[8];\n const a21 = a[9];\n const a22 = a[10];\n const a23 = a[11];\n const a30 = a[12];\n const a31 = a[13];\n const a32 = a[14];\n const a33 = a[15];\n\n // Cache only the current line of the second matrix\n let b0 = b[0];\n let b1 = b[1];\n let b2 = b[2];\n let b3 = b[3];\n out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n\n b0 = b[4];\n b1 = b[5];\n b2 = b[6];\n b3 = b[7];\n out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n\n b0 = b[8];\n b1 = b[9];\n b2 = b[10];\n b3 = b[11];\n out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n\n b0 = b[12];\n b1 = b[13];\n b2 = b[14];\n b3 = b[15];\n out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n return out;\n}\n\n/**\n * Translate a mat4 by the given vector\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to translate\n * @param {ReadonlyVec3} v vector to translate by\n * @returns {mat4} out\n */\nexport function translate(out, a, v) {\n const x = v[0];\n const y = v[1];\n const z = v[2];\n let a00;\n let a01;\n let a02;\n let a03;\n let a10;\n let a11;\n let a12;\n let a13;\n let a20;\n let a21;\n let a22;\n let a23;\n\n if (a === out) {\n out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];\n out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];\n out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];\n out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];\n } else {\n a00 = a[0];\n a01 = a[1];\n a02 = a[2];\n a03 = a[3];\n a10 = a[4];\n a11 = a[5];\n a12 = a[6];\n a13 = a[7];\n a20 = a[8];\n a21 = a[9];\n a22 = a[10];\n a23 = a[11];\n\n out[0] = a00;\n out[1] = a01;\n out[2] = a02;\n out[3] = a03;\n out[4] = a10;\n out[5] = a11;\n out[6] = a12;\n out[7] = a13;\n out[8] = a20;\n out[9] = a21;\n out[10] = a22;\n out[11] = a23;\n\n out[12] = a00 * x + a10 * y + a20 * z + a[12];\n out[13] = a01 * x + a11 * y + a21 * z + a[13];\n out[14] = a02 * x + a12 * y + a22 * z + a[14];\n out[15] = a03 * x + a13 * y + a23 * z + a[15];\n }\n\n return out;\n}\n\n/**\n * Scales the mat4 by the dimensions in the given vec3 not using vectorization\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to scale\n * @param {ReadonlyVec3} v the vec3 to scale the matrix by\n * @returns {mat4} out\n **/\nexport function scale(out, a, v) {\n const x = v[0];\n const y = v[1];\n const z = v[2];\n\n out[0] = a[0] * x;\n out[1] = a[1] * x;\n out[2] = a[2] * x;\n out[3] = a[3] * x;\n out[4] = a[4] * y;\n out[5] = a[5] * y;\n out[6] = a[6] * y;\n out[7] = a[7] * y;\n out[8] = a[8] * z;\n out[9] = a[9] * z;\n out[10] = a[10] * z;\n out[11] = a[11] * z;\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n return out;\n}\n\n/**\n * Rotates a mat4 by the given angle around the given axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @param {ReadonlyVec3} axis the axis to rotate around\n * @returns {mat4} out\n */\nexport function rotate(out, a, rad, axis) {\n let x = axis[0];\n let y = axis[1];\n let z = axis[2];\n let len = Math.sqrt(x * x + y * y + z * z);\n let c;\n let s;\n let t;\n let a00;\n let a01;\n let a02;\n let a03;\n let a10;\n let a11;\n let a12;\n let a13;\n let a20;\n let a21;\n let a22;\n let a23;\n let b00;\n let b01;\n let b02;\n let b10;\n let b11;\n let b12;\n let b20;\n let b21;\n let b22;\n\n if (len < glMatrix.EPSILON) {\n return null;\n }\n\n len = 1 / len;\n x *= len;\n y *= len;\n z *= len;\n\n s = Math.sin(rad);\n c = Math.cos(rad);\n t = 1 - c;\n\n a00 = a[0];\n a01 = a[1];\n a02 = a[2];\n a03 = a[3];\n a10 = a[4];\n a11 = a[5];\n a12 = a[6];\n a13 = a[7];\n a20 = a[8];\n a21 = a[9];\n a22 = a[10];\n a23 = a[11];\n\n // Construct the elements of the rotation matrix\n b00 = x * x * t + c;\n b01 = y * x * t + z * s;\n b02 = z * x * t - y * s;\n b10 = x * y * t - z * s;\n b11 = y * y * t + c;\n b12 = z * y * t + x * s;\n b20 = x * z * t + y * s;\n b21 = y * z * t - x * s;\n b22 = z * z * t + c;\n\n // Perform rotation-specific matrix multiplication\n out[0] = a00 * b00 + a10 * b01 + a20 * b02;\n out[1] = a01 * b00 + a11 * b01 + a21 * b02;\n out[2] = a02 * b00 + a12 * b01 + a22 * b02;\n out[3] = a03 * b00 + a13 * b01 + a23 * b02;\n out[4] = a00 * b10 + a10 * b11 + a20 * b12;\n out[5] = a01 * b10 + a11 * b11 + a21 * b12;\n out[6] = a02 * b10 + a12 * b11 + a22 * b12;\n out[7] = a03 * b10 + a13 * b11 + a23 * b12;\n out[8] = a00 * b20 + a10 * b21 + a20 * b22;\n out[9] = a01 * b20 + a11 * b21 + a21 * b22;\n out[10] = a02 * b20 + a12 * b21 + a22 * b22;\n out[11] = a03 * b20 + a13 * b21 + a23 * b22;\n\n if (a !== out) {\n // If the source and destination differ, copy the unchanged last row\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n }\n return out;\n}\n\n/**\n * Rotates a matrix by the given angle around the X axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\nexport function rotateX(out, a, rad) {\n const s = Math.sin(rad);\n const c = Math.cos(rad);\n const a10 = a[4];\n const a11 = a[5];\n const a12 = a[6];\n const a13 = a[7];\n const a20 = a[8];\n const a21 = a[9];\n const a22 = a[10];\n const a23 = a[11];\n\n if (a !== out) {\n // If the source and destination differ, copy the unchanged rows\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n }\n\n // Perform axis-specific matrix multiplication\n out[4] = a10 * c + a20 * s;\n out[5] = a11 * c + a21 * s;\n out[6] = a12 * c + a22 * s;\n out[7] = a13 * c + a23 * s;\n out[8] = a20 * c - a10 * s;\n out[9] = a21 * c - a11 * s;\n out[10] = a22 * c - a12 * s;\n out[11] = a23 * c - a13 * s;\n return out;\n}\n\n/**\n * Rotates a matrix by the given angle around the Y axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\nexport function rotateY(out, a, rad) {\n const s = Math.sin(rad);\n const c = Math.cos(rad);\n const a00 = a[0];\n const a01 = a[1];\n const a02 = a[2];\n const a03 = a[3];\n const a20 = a[8];\n const a21 = a[9];\n const a22 = a[10];\n const a23 = a[11];\n\n if (a !== out) {\n // If the source and destination differ, copy the unchanged rows\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n }\n\n // Perform axis-specific matrix multiplication\n out[0] = a00 * c - a20 * s;\n out[1] = a01 * c - a21 * s;\n out[2] = a02 * c - a22 * s;\n out[3] = a03 * c - a23 * s;\n out[8] = a00 * s + a20 * c;\n out[9] = a01 * s + a21 * c;\n out[10] = a02 * s + a22 * c;\n out[11] = a03 * s + a23 * c;\n return out;\n}\n\n/**\n * Rotates a matrix by the given angle around the Z axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\nexport function rotateZ(out, a, rad) {\n const s = Math.sin(rad);\n const c = Math.cos(rad);\n const a00 = a[0];\n const a01 = a[1];\n const a02 = a[2];\n const a03 = a[3];\n const a10 = a[4];\n const a11 = a[5];\n const a12 = a[6];\n const a13 = a[7];\n\n if (a !== out) {\n // If the source and destination differ, copy the unchanged last row\n out[8] = a[8];\n out[9] = a[9];\n out[10] = a[10];\n out[11] = a[11];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n }\n\n // Perform axis-specific matrix multiplication\n out[0] = a00 * c + a10 * s;\n out[1] = a01 * c + a11 * s;\n out[2] = a02 * c + a12 * s;\n out[3] = a03 * c + a13 * s;\n out[4] = a10 * c - a00 * s;\n out[5] = a11 * c - a01 * s;\n out[6] = a12 * c - a02 * s;\n out[7] = a13 * c - a03 * s;\n return out;\n}\n\n/**\n * Creates a matrix from a vector translation\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.translate(dest, dest, vec);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {ReadonlyVec3} v Translation vector\n * @returns {mat4} out\n */\nexport function fromTranslation(out, v) {\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = 1;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 1;\n out[11] = 0;\n out[12] = v[0];\n out[13] = v[1];\n out[14] = v[2];\n out[15] = 1;\n return out;\n}\n\n/**\n * Creates a matrix from a vector scaling\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.scale(dest, dest, vec);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {ReadonlyVec3} v Scaling vector\n * @returns {mat4} out\n */\nexport function fromScaling(out, v) {\n out[0] = v[0];\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = v[1];\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = v[2];\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n\n/**\n * Creates a matrix from a given angle around a given axis\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.rotate(dest, dest, rad, axis);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @param {ReadonlyVec3} axis the axis to rotate around\n * @returns {mat4} out\n */\nexport function fromRotation(out, rad, axis) {\n let x = axis[0];\n let y = axis[1];\n let z = axis[2];\n let len = Math.sqrt(x * x + y * y + z * z);\n let c;\n let s;\n let t;\n\n if (len < glMatrix.EPSILON) {\n return null;\n }\n\n len = 1 / len;\n x *= len;\n y *= len;\n z *= len;\n\n s = Math.sin(rad);\n c = Math.cos(rad);\n t = 1 - c;\n\n // Perform rotation-specific matrix multiplication\n out[0] = x * x * t + c;\n out[1] = y * x * t + z * s;\n out[2] = z * x * t - y * s;\n out[3] = 0;\n out[4] = x * y * t - z * s;\n out[5] = y * y * t + c;\n out[6] = z * y * t + x * s;\n out[7] = 0;\n out[8] = x * z * t + y * s;\n out[9] = y * z * t - x * s;\n out[10] = z * z * t + c;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n\n/**\n * Creates a matrix from the given angle around the X axis\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.rotateX(dest, dest, rad);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\nexport function fromXRotation(out, rad) {\n const s = Math.sin(rad);\n const c = Math.cos(rad);\n\n // Perform axis-specific matrix multiplication\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = c;\n out[6] = s;\n out[7] = 0;\n out[8] = 0;\n out[9] = -s;\n out[10] = c;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n\n/**\n * Creates a matrix from the given angle around the Y axis\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.rotateY(dest, dest, rad);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\nexport function fromYRotation(out, rad) {\n const s = Math.sin(rad);\n const c = Math.cos(rad);\n\n // Perform axis-specific matrix multiplication\n out[0] = c;\n out[1] = 0;\n out[2] = -s;\n out[3] = 0;\n out[4] = 0;\n out[5] = 1;\n out[6] = 0;\n out[7] = 0;\n out[8] = s;\n out[9] = 0;\n out[10] = c;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n\n/**\n * Creates a matrix from the given angle around the Z axis\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.rotateZ(dest, dest, rad);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\nexport function fromZRotation(out, rad) {\n const s = Math.sin(rad);\n const c = Math.cos(rad);\n\n // Perform axis-specific matrix multiplication\n out[0] = c;\n out[1] = s;\n out[2] = 0;\n out[3] = 0;\n out[4] = -s;\n out[5] = c;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 1;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n\n/**\n * Creates a matrix from a quaternion rotation and vector translation\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.translate(dest, vec);\n * let quatMat = mat4.create();\n * quat4.toMat4(quat, quatMat);\n * mat4.multiply(dest, quatMat);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {quat4} q Rotation quaternion\n * @param {ReadonlyVec3} v Translation vector\n * @returns {mat4} out\n */\nexport function fromRotationTranslation(out, q, v) {\n // Quaternion math\n const x = q[0];\n const y = q[1];\n const z = q[2];\n const w = q[3];\n const x2 = x + x;\n const y2 = y + y;\n const z2 = z + z;\n\n const xx = x * x2;\n const xy = x * y2;\n const xz = x * z2;\n const yy = y * y2;\n const yz = y * z2;\n const zz = z * z2;\n const wx = w * x2;\n const wy = w * y2;\n const wz = w * z2;\n\n out[0] = 1 - (yy + zz);\n out[1] = xy + wz;\n out[2] = xz - wy;\n out[3] = 0;\n out[4] = xy - wz;\n out[5] = 1 - (xx + zz);\n out[6] = yz + wx;\n out[7] = 0;\n out[8] = xz + wy;\n out[9] = yz - wx;\n out[10] = 1 - (xx + yy);\n out[11] = 0;\n out[12] = v[0];\n out[13] = v[1];\n out[14] = v[2];\n out[15] = 1;\n\n return out;\n}\n\n/**\n * Creates a new mat4 from a dual quat.\n *\n * @param {mat4} out Matrix\n * @param {ReadonlyQuat2} a Dual Quaternion\n * @returns {mat4} mat4 receiving operation result\n */\nexport function fromQuat2(out, a) {\n const translation = new glMatrix.ARRAY_TYPE(3);\n const bx = -a[0];\n const by = -a[1];\n const bz = -a[2];\n const bw = a[3];\n const ax = a[4];\n const ay = a[5];\n const az = a[6];\n const aw = a[7];\n\n const magnitude = bx * bx + by * by + bz * bz + bw * bw;\n // Only scale if it makes sense\n if (magnitude > 0) {\n translation[0] = ((ax * bw + aw * bx + ay * bz - az * by) * 2) / magnitude;\n translation[1] = ((ay * bw + aw * by + az * bx - ax * bz) * 2) / magnitude;\n translation[2] = ((az * bw + aw * bz + ax * by - ay * bx) * 2) / magnitude;\n } else {\n translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2;\n translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2;\n translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2;\n }\n fromRotationTranslation(out, a, translation);\n return out;\n}\n\n/**\n * Returns the translation vector component of a transformation\n * matrix. If a matrix is built with fromRotationTranslation,\n * the returned vector will be the same as the translation vector\n * originally supplied.\n * @param {vec3} out Vector to receive translation component\n * @param {ReadonlyMat4} mat Matrix to be decomposed (input)\n * @return {vec3} out\n */\nexport function getTranslation(out, mat) {\n out[0] = mat[12];\n out[1] = mat[13];\n out[2] = mat[14];\n\n return out;\n}\n\n/**\n * Returns the scaling factor component of a transformation\n * matrix. If a matrix is built with fromRotationTranslationScale\n * with a normalized Quaternion paramter, the returned vector will be\n * the same as the scaling vector\n * originally supplied.\n * @param {vec3} out Vector to receive scaling factor component\n * @param {ReadonlyMat4} mat Matrix to be decomposed (input)\n * @return {vec3} out\n */\nexport function getScaling(out, mat) {\n const m11 = mat[0];\n const m12 = mat[1];\n const m13 = mat[2];\n const m21 = mat[4];\n const m22 = mat[5];\n const m23 = mat[6];\n const m31 = mat[8];\n const m32 = mat[9];\n const m33 = mat[10];\n\n out[0] = Math.sqrt(m11 * m11 + m12 * m12 + m13 * m13);\n out[1] = Math.sqrt(m21 * m21 + m22 * m22 + m23 * m23);\n out[2] = Math.sqrt(m31 * m31 + m32 * m32 + m33 * m33);\n\n return out;\n}\n\n/**\n * Returns a quaternion representing the rotational component\n * of a transformation matrix. If a matrix is built with\n * fromRotationTranslation, the returned quaternion will be the\n * same as the quaternion originally supplied.\n * @param {quat} out Quaternion to receive the rotation component\n * @param {ReadonlyMat4} mat Matrix to be decomposed (input)\n * @return {quat} out\n */\nexport function getRotation(out, mat) {\n const scaling = new glMatrix.ARRAY_TYPE(3);\n getScaling(scaling, mat);\n\n const is1 = 1 / scaling[0];\n const is2 = 1 / scaling[1];\n const is3 = 1 / scaling[2];\n\n const sm11 = mat[0] * is1;\n const sm12 = mat[1] * is2;\n const sm13 = mat[2] * is3;\n const sm21 = mat[4] * is1;\n const sm22 = mat[5] * is2;\n const sm23 = mat[6] * is3;\n const sm31 = mat[8] * is1;\n const sm32 = mat[9] * is2;\n const sm33 = mat[10] * is3;\n\n const trace = sm11 + sm22 + sm33;\n let S = 0;\n\n if (trace > 0) {\n S = Math.sqrt(trace + 1.0) * 2;\n out[3] = 0.25 * S;\n out[0] = (sm23 - sm32) / S;\n out[1] = (sm31 - sm13) / S;\n out[2] = (sm12 - sm21) / S;\n } else if (sm11 > sm22 && sm11 > sm33) {\n S = Math.sqrt(1.0 + sm11 - sm22 - sm33) * 2;\n out[3] = (sm23 - sm32) / S;\n out[0] = 0.25 * S;\n out[1] = (sm12 + sm21) / S;\n out[2] = (sm31 + sm13) / S;\n } else if (sm22 > sm33) {\n S = Math.sqrt(1.0 + sm22 - sm11 - sm33) * 2;\n out[3] = (sm31 - sm13) / S;\n out[0] = (sm12 + sm21) / S;\n out[1] = 0.25 * S;\n out[2] = (sm23 + sm32) / S;\n } else {\n S = Math.sqrt(1.0 + sm33 - sm11 - sm22) * 2;\n out[3] = (sm12 - sm21) / S;\n out[0] = (sm31 + sm13) / S;\n out[1] = (sm23 + sm32) / S;\n out[2] = 0.25 * S;\n }\n\n return out;\n}\n\n/**\n * Decomposes a transformation matrix into its rotation, translation\n * and scale components. Returns only the rotation component\n * @param {quat} out_r Quaternion to receive the rotation component\n * @param {vec3} out_t Vector to receive the translation vector\n * @param {vec3} out_s Vector to receive the scaling factor\n * @param {ReadonlyMat4} mat Matrix to be decomposed (input)\n * @returns {quat} out_r\n */\nexport function decompose(out_r, out_t, out_s, mat) {\n out_t[0] = mat[12];\n out_t[1] = mat[13];\n out_t[2] = mat[14];\n\n const m11 = mat[0];\n const m12 = mat[1];\n const m13 = mat[2];\n const m21 = mat[4];\n const m22 = mat[5];\n const m23 = mat[6];\n const m31 = mat[8];\n const m32 = mat[9];\n const m33 = mat[10];\n\n out_s[0] = Math.sqrt(m11 * m11 + m12 * m12 + m13 * m13);\n out_s[1] = Math.sqrt(m21 * m21 + m22 * m22 + m23 * m23);\n out_s[2] = Math.sqrt(m31 * m31 + m32 * m32 + m33 * m33);\n\n const is1 = 1 / out_s[0];\n const is2 = 1 / out_s[1];\n const is3 = 1 / out_s[2];\n\n const sm11 = m11 * is1;\n const sm12 = m12 * is2;\n const sm13 = m13 * is3;\n const sm21 = m21 * is1;\n const sm22 = m22 * is2;\n const sm23 = m23 * is3;\n const sm31 = m31 * is1;\n const sm32 = m32 * is2;\n const sm33 = m33 * is3;\n\n const trace = sm11 + sm22 + sm33;\n let S = 0;\n\n if (trace > 0) {\n S = Math.sqrt(trace + 1.0) * 2;\n out_r[3] = 0.25 * S;\n out_r[0] = (sm23 - sm32) / S;\n out_r[1] = (sm31 - sm13) / S;\n out_r[2] = (sm12 - sm21) / S;\n } else if (sm11 > sm22 && sm11 > sm33) {\n S = Math.sqrt(1.0 + sm11 - sm22 - sm33) * 2;\n out_r[3] = (sm23 - sm32) / S;\n out_r[0] = 0.25 * S;\n out_r[1] = (sm12 + sm21) / S;\n out_r[2] = (sm31 + sm13) / S;\n } else if (sm22 > sm33) {\n S = Math.sqrt(1.0 + sm22 - sm11 - sm33) * 2;\n out_r[3] = (sm31 - sm13) / S;\n out_r[0] = (sm12 + sm21) / S;\n out_r[1] = 0.25 * S;\n out_r[2] = (sm23 + sm32) / S;\n } else {\n S = Math.sqrt(1.0 + sm33 - sm11 - sm22) * 2;\n out_r[3] = (sm12 - sm21) / S;\n out_r[0] = (sm31 + sm13) / S;\n out_r[1] = (sm23 + sm32) / S;\n out_r[2] = 0.25 * S;\n }\n\n return out_r;\n}\n\n/**\n * Creates a matrix from a quaternion rotation, vector translation and vector scale\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.translate(dest, vec);\n * let quatMat = mat4.create();\n * quat4.toMat4(quat, quatMat);\n * mat4.multiply(dest, quatMat);\n * mat4.scale(dest, scale)\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {quat4} q Rotation quaternion\n * @param {ReadonlyVec3} v Translation vector\n * @param {ReadonlyVec3} s Scaling vector\n * @returns {mat4} out\n */\nexport function fromRotationTranslationScale(out, q, v, s) {\n // Quaternion math\n const x = q[0];\n const y = q[1];\n const z = q[2];\n const w = q[3];\n const x2 = x + x;\n const y2 = y + y;\n const z2 = z + z;\n\n const xx = x * x2;\n const xy = x * y2;\n const xz = x * z2;\n const yy = y * y2;\n const yz = y * z2;\n const zz = z * z2;\n const wx = w * x2;\n const wy = w * y2;\n const wz = w * z2;\n const sx = s[0];\n const sy = s[1];\n const sz = s[2];\n\n out[0] = (1 - (yy + zz)) * sx;\n out[1] = (xy + wz) * sx;\n out[2] = (xz - wy) * sx;\n out[3] = 0;\n out[4] = (xy - wz) * sy;\n out[5] = (1 - (xx + zz)) * sy;\n out[6] = (yz + wx) * sy;\n out[7] = 0;\n out[8] = (xz + wy) * sz;\n out[9] = (yz - wx) * sz;\n out[10] = (1 - (xx + yy)) * sz;\n out[11] = 0;\n out[12] = v[0];\n out[13] = v[1];\n out[14] = v[2];\n out[15] = 1;\n\n return out;\n}\n\n/**\n * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.translate(dest, vec);\n * mat4.translate(dest, origin);\n * let quatMat = mat4.create();\n * quat4.toMat4(quat, quatMat);\n * mat4.multiply(dest, quatMat);\n * mat4.scale(dest, scale)\n * mat4.translate(dest, negativeOrigin);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {quat4} q Rotation quaternion\n * @param {ReadonlyVec3} v Translation vector\n * @param {ReadonlyVec3} s Scaling vector\n * @param {ReadonlyVec3} o The origin vector around which to scale and rotate\n * @returns {mat4} out\n */\nexport function fromRotationTranslationScaleOrigin(out, q, v, s, o) {\n // Quaternion math\n const x = q[0];\n const y = q[1];\n const z = q[2];\n const w = q[3];\n const x2 = x + x;\n const y2 = y + y;\n const z2 = z + z;\n\n const xx = x * x2;\n const xy = x * y2;\n const xz = x * z2;\n const yy = y * y2;\n const yz = y * z2;\n const zz = z * z2;\n const wx = w * x2;\n const wy = w * y2;\n const wz = w * z2;\n\n const sx = s[0];\n const sy = s[1];\n const sz = s[2];\n\n const ox = o[0];\n const oy = o[1];\n const oz = o[2];\n\n const out0 = (1 - (yy + zz)) * sx;\n const out1 = (xy + wz) * sx;\n const out2 = (xz - wy) * sx;\n const out4 = (xy - wz) * sy;\n const out5 = (1 - (xx + zz)) * sy;\n const out6 = (yz + wx) * sy;\n const out8 = (xz + wy) * sz;\n const out9 = (yz - wx) * sz;\n const out10 = (1 - (xx + yy)) * sz;\n\n out[0] = out0;\n out[1] = out1;\n out[2] = out2;\n out[3] = 0;\n out[4] = out4;\n out[5] = out5;\n out[6] = out6;\n out[7] = 0;\n out[8] = out8;\n out[9] = out9;\n out[10] = out10;\n out[11] = 0;\n out[12] = v[0] + ox - (out0 * ox + out4 * oy + out8 * oz);\n out[13] = v[1] + oy - (out1 * ox + out5 * oy + out9 * oz);\n out[14] = v[2] + oz - (out2 * ox + out6 * oy + out10 * oz);\n out[15] = 1;\n\n return out;\n}\n\n/**\n * Calculates a 4x4 matrix from the given quaternion\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {ReadonlyQuat} q Quaternion to create matrix from\n *\n * @returns {mat4} out\n */\nexport function fromQuat(out, q) {\n const x = q[0];\n const y = q[1];\n const z = q[2];\n const w = q[3];\n const x2 = x + x;\n const y2 = y + y;\n const z2 = z + z;\n\n const xx = x * x2;\n const yx = y * x2;\n const yy = y * y2;\n const zx = z * x2;\n const zy = z * y2;\n const zz = z * z2;\n const wx = w * x2;\n const wy = w * y2;\n const wz = w * z2;\n\n out[0] = 1 - yy - zz;\n out[1] = yx + wz;\n out[2] = zx - wy;\n out[3] = 0;\n\n out[4] = yx - wz;\n out[5] = 1 - xx - zz;\n out[6] = zy + wx;\n out[7] = 0;\n\n out[8] = zx + wy;\n out[9] = zy - wx;\n out[10] = 1 - xx - yy;\n out[11] = 0;\n\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n\n return out;\n}\n\n/**\n * Generates a frustum matrix with the given bounds\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {Number} left Left bound of the frustum\n * @param {Number} right Right bound of the frustum\n * @param {Number} bottom Bottom bound of the frustum\n * @param {Number} top Top bound of the frustum\n * @param {Number} near Near bound of the frustum\n * @param {Number} far Far bound of the frustum\n * @returns {mat4} out\n */\nexport function frustum(out, left, right, bottom, top, near, far) {\n const rl = 1 / (right - left);\n const tb = 1 / (top - bottom);\n const nf = 1 / (near - far);\n out[0] = near * 2 * rl;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = near * 2 * tb;\n out[6] = 0;\n out[7] = 0;\n out[8] = (right + left) * rl;\n out[9] = (top + bottom) * tb;\n out[10] = (far + near) * nf;\n out[11] = -1;\n out[12] = 0;\n out[13] = 0;\n out[14] = far * near * 2 * nf;\n out[15] = 0;\n return out;\n}\n\n/**\n * Generates a perspective projection matrix with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1],\n * which matches WebGL/OpenGL's clip volume.\n * Passing null/undefined/no value for far will generate infinite projection matrix.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} fovy Vertical field of view in radians\n * @param {number} aspect Aspect ratio. typically viewport width/height\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum, can be null or Infinity\n * @returns {mat4} out\n */\nexport function perspectiveNO(out, fovy, aspect, near, far) {\n const f = 1.0 / Math.tan(fovy / 2);\n out[0] = f / aspect;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = f;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[11] = -1;\n out[12] = 0;\n out[13] = 0;\n out[15] = 0;\n if (far != null && far !== Infinity) {\n const nf = 1 / (near - far);\n out[10] = (far + near) * nf;\n out[14] = 2 * far * near * nf;\n } else {\n out[10] = -1;\n out[14] = -2 * near;\n }\n return out;\n}\n\n/**\n * Alias for {@link mat4.perspectiveNO}\n * @function\n */\nexport const perspective = perspectiveNO;\n\n/**\n * Generates a perspective projection matrix suitable for WebGPU with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [0, 1],\n * which matches WebGPU/Vulkan/DirectX/Metal's clip volume.\n * Passing null/undefined/no value for far will generate infinite projection matrix.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} fovy Vertical field of view in radians\n * @param {number} aspect Aspect ratio. typically viewport width/height\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum, can be null or Infinity\n * @returns {mat4} out\n */\nexport function perspectiveZO(out, fovy, aspect, near, far) {\n const f = 1.0 / Math.tan(fovy / 2);\n out[0] = f / aspect;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = f;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[11] = -1;\n out[12] = 0;\n out[13] = 0;\n out[15] = 0;\n if (far != null && far !== Infinity) {\n const nf = 1 / (near - far);\n out[10] = far * nf;\n out[14] = far * near * nf;\n } else {\n out[10] = -1;\n out[14] = -near;\n }\n return out;\n}\n\n/**\n * Generates a perspective projection matrix with the given field of view.\n * This is primarily useful for generating projection matrices to be used\n * with the still experiemental WebVR API.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {Object} fov Object containing the following values: upDegrees, downDegrees, leftDegrees, rightDegrees\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum\n * @returns {mat4} out\n */\nexport function perspectiveFromFieldOfView(out, fov, near, far) {\n const upTan = Math.tan((fov.upDegrees * Math.PI) / 180.0);\n const downTan = Math.tan((fov.downDegrees * Math.PI) / 180.0);\n const leftTan = Math.tan((fov.leftDegrees * Math.PI) / 180.0);\n const rightTan = Math.tan((fov.rightDegrees * Math.PI) / 180.0);\n const xScale = 2.0 / (leftTan + rightTan);\n const yScale = 2.0 / (upTan + downTan);\n\n out[0] = xScale;\n out[1] = 0.0;\n out[2] = 0.0;\n out[3] = 0.0;\n out[4] = 0.0;\n out[5] = yScale;\n out[6] = 0.0;\n out[7] = 0.0;\n out[8] = -((leftTan - rightTan) * xScale * 0.5);\n out[9] = (upTan - downTan) * yScale * 0.5;\n out[10] = far / (near - far);\n out[11] = -1.0;\n out[12] = 0.0;\n out[13] = 0.0;\n out[14] = (far * near) / (near - far);\n out[15] = 0.0;\n return out;\n}\n\n/**\n * Generates a orthogonal projection matrix with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1],\n * which matches WebGL/OpenGL's clip volume.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} left Left bound of the frustum\n * @param {number} right Right bound of the frustum\n * @param {number} bottom Bottom bound of the frustum\n * @param {number} top Top bound of the frustum\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum\n * @returns {mat4} out\n */\nexport function orthoNO(out, left, right, bottom, top, near, far) {\n const lr = 1 / (left - right);\n const bt = 1 / (bottom - top);\n const nf = 1 / (near - far);\n out[0] = -2 * lr;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = -2 * bt;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 2 * nf;\n out[11] = 0;\n out[12] = (left + right) * lr;\n out[13] = (top + bottom) * bt;\n out[14] = (far + near) * nf;\n out[15] = 1;\n return out;\n}\n\n/**\n * Alias for {@link mat4.orthoNO}\n * @function\n */\nexport const ortho = orthoNO;\n\n/**\n * Generates a orthogonal projection matrix with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [0, 1],\n * which matches WebGPU/Vulkan/DirectX/Metal's clip volume.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} left Left bound of the frustum\n * @param {number} right Right bound of the frustum\n * @param {number} bottom Bottom bound of the frustum\n * @param {number} top Top bound of the frustum\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum\n * @returns {mat4} out\n */\nexport function orthoZO(out, left, right, bottom, top, near, far) {\n const lr = 1 / (left - right);\n const bt = 1 / (bottom - top);\n const nf = 1 / (near - far);\n out[0] = -2 * lr;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = -2 * bt;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = nf;\n out[11] = 0;\n out[12] = (left + right) * lr;\n out[13] = (top + bottom) * bt;\n out[14] = near * nf;\n out[15] = 1;\n return out;\n}\n\n/**\n * Generates a look-at matrix with the given eye position, focal point, and up axis.\n * If you want a matrix that actually makes an object look at another object, you should use targetTo instead.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {ReadonlyVec3} eye Position of the viewer\n * @param {ReadonlyVec3} center Point the viewer is looking at\n * @param {ReadonlyVec3} up vec3 pointing up\n * @returns {mat4} out\n */\nexport function lookAt(out, eye, center, up) {\n let len;\n let x0;\n let x1;\n let x2;\n let y0;\n let y1;\n let y2;\n let z0;\n let z1;\n let z2;\n const eyex = eye[0];\n const eyey = eye[1];\n const eyez = eye[2];\n const upx = up[0];\n const upy = up[1];\n const upz = up[2];\n const centerx = center[0];\n const centery = center[1];\n const centerz = center[2];\n\n if (\n Math.abs(eyex - centerx) < glMatrix.EPSILON &&\n Math.abs(eyey - centery) < glMatrix.EPSILON &&\n Math.abs(eyez - centerz) < glMatrix.EPSILON\n ) {\n return identity(out);\n }\n\n z0 = eyex - centerx;\n z1 = eyey - centery;\n z2 = eyez - centerz;\n\n len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2);\n z0 *= len;\n z1 *= len;\n z2 *= len;\n\n x0 = upy * z2 - upz * z1;\n x1 = upz * z0 - upx * z2;\n x2 = upx * z1 - upy * z0;\n len = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2);\n if (!len) {\n x0 = 0;\n x1 = 0;\n x2 = 0;\n } else {\n len = 1 / len;\n x0 *= len;\n x1 *= len;\n x2 *= len;\n }\n\n y0 = z1 * x2 - z2 * x1;\n y1 = z2 * x0 - z0 * x2;\n y2 = z0 * x1 - z1 * x0;\n\n len = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2);\n if (!len) {\n y0 = 0;\n y1 = 0;\n y2 = 0;\n } else {\n len = 1 / len;\n y0 *= len;\n y1 *= len;\n y2 *= len;\n }\n\n out[0] = x0;\n out[1] = y0;\n out[2] = z0;\n out[3] = 0;\n out[4] = x1;\n out[5] = y1;\n out[6] = z1;\n out[7] = 0;\n out[8] = x2;\n out[9] = y2;\n out[10] = z2;\n out[11] = 0;\n out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);\n out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);\n out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);\n out[15] = 1;\n\n return out;\n}\n\n/**\n * Generates a matrix that makes something look at something else.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {ReadonlyVec3} eye Position of the viewer\n * @param {ReadonlyVec3} center Point the viewer is looking at\n * @param {ReadonlyVec3} up vec3 pointing up\n * @returns {mat4} out\n */\nexport function targetTo(out, eye, target, up) {\n const eyex = eye[0];\n const eyey = eye[1];\n const eyez = eye[2];\n const upx = up[0];\n const upy = up[1];\n const upz = up[2];\n\n let z0 = eyex - target[0];\n let z1 = eyey - target[1];\n let z2 = eyez - target[2];\n\n let len = z0 * z0 + z1 * z1 + z2 * z2;\n if (len > 0) {\n len = 1 / Math.sqrt(len);\n z0 *= len;\n z1 *= len;\n z2 *= len;\n }\n\n let x0 = upy * z2 - upz * z1;\n let x1 = upz * z0 - upx * z2;\n let x2 = upx * z1 - upy * z0;\n\n len = x0 * x0 + x1 * x1 + x2 * x2;\n if (len > 0) {\n len = 1 / Math.sqrt(len);\n x0 *= len;\n x1 *= len;\n x2 *= len;\n }\n\n out[0] = x0;\n out[1] = x1;\n out[2] = x2;\n out[3] = 0;\n out[4] = z1 * x2 - z2 * x1;\n out[5] = z2 * x0 - z0 * x2;\n out[6] = z0 * x1 - z1 * x0;\n out[7] = 0;\n out[8] = z0;\n out[9] = z1;\n out[10] = z2;\n out[11] = 0;\n out[12] = eyex;\n out[13] = eyey;\n out[14] = eyez;\n out[15] = 1;\n return out;\n}\n\n/**\n * Returns a string representation of a mat4\n *\n * @param {ReadonlyMat4} a matrix to represent as a string\n * @returns {String} string representation of the matrix\n */\nexport function str(a) {\n return `mat4(${a[0]}, ${a[1]}, ${a[2]}, ${a[3]}, ${a[4]}, ${a[5]}, ${a[6]}, ${a[7]}, ${a[8]}, ${a[9]}, ${a[10]}, ${a[11]}, ${a[12]}, ${a[13]}, ${a[14]}, ${a[15]})`;\n}\n\n/**\n * Returns Frobenius norm of a mat4\n *\n * @param {ReadonlyMat4} a the matrix to calculate Frobenius norm of\n * @returns {Number} Frobenius norm\n */\nexport function frob(a) {\n return Math.sqrt(\n a[0] * a[0] +\n a[1] * a[1] +\n a[2] * a[2] +\n a[3] * a[3] +\n a[4] * a[4] +\n a[5] * a[5] +\n a[6] * a[6] +\n a[7] * a[7] +\n a[8] * a[8] +\n a[9] * a[9] +\n a[10] * a[10] +\n a[11] * a[11] +\n a[12] * a[12] +\n a[13] * a[13] +\n a[14] * a[14] +\n a[15] * a[15]\n );\n}\n\n/**\n * Adds two mat4's\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @returns {mat4} out\n */\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n out[2] = a[2] + b[2];\n out[3] = a[3] + b[3];\n out[4] = a[4] + b[4];\n out[5] = a[5] + b[5];\n out[6] = a[6] + b[6];\n out[7] = a[7] + b[7];\n out[8] = a[8] + b[8];\n out[9] = a[9] + b[9];\n out[10] = a[10] + b[10];\n out[11] = a[11] + b[11];\n out[12] = a[12] + b[12];\n out[13] = a[13] + b[13];\n out[14] = a[14] + b[14];\n out[15] = a[15] + b[15];\n return out;\n}\n\n/**\n * Subtracts matrix b from matrix a\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @returns {mat4} out\n */\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n out[2] = a[2] - b[2];\n out[3] = a[3] - b[3];\n out[4] = a[4] - b[4];\n out[5] = a[5] - b[5];\n out[6] = a[6] - b[6];\n out[7] = a[7] - b[7];\n out[8] = a[8] - b[8];\n out[9] = a[9] - b[9];\n out[10] = a[10] - b[10];\n out[11] = a[11] - b[11];\n out[12] = a[12] - b[12];\n out[13] = a[13] - b[13];\n out[14] = a[14] - b[14];\n out[15] = a[15] - b[15];\n return out;\n}\n\n/**\n * Multiply each element of the matrix by a scalar.\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to scale\n * @param {Number} b amount to scale the matrix's elements by\n * @returns {mat4} out\n */\nexport function multiplyScalar(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n out[2] = a[2] * b;\n out[3] = a[3] * b;\n out[4] = a[4] * b;\n out[5] = a[5] * b;\n out[6] = a[6] * b;\n out[7] = a[7] * b;\n out[8] = a[8] * b;\n out[9] = a[9] * b;\n out[10] = a[10] * b;\n out[11] = a[11] * b;\n out[12] = a[12] * b;\n out[13] = a[13] * b;\n out[14] = a[14] * b;\n out[15] = a[15] * b;\n return out;\n}\n\n/**\n * Adds two mat4's after multiplying each element of the second operand by a scalar value.\n *\n * @param {mat4} out the receiving vector\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @param {Number} scale the amount to scale b's elements by before adding\n * @returns {mat4} out\n */\nexport function multiplyScalarAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n out[2] = a[2] + b[2] * scale;\n out[3] = a[3] + b[3] * scale;\n out[4] = a[4] + b[4] * scale;\n out[5] = a[5] + b[5] * scale;\n out[6] = a[6] + b[6] * scale;\n out[7] = a[7] + b[7] * scale;\n out[8] = a[8] + b[8] * scale;\n out[9] = a[9] + b[9] * scale;\n out[10] = a[10] + b[10] * scale;\n out[11] = a[11] + b[11] * scale;\n out[12] = a[12] + b[12] * scale;\n out[13] = a[13] + b[13] * scale;\n out[14] = a[14] + b[14] * scale;\n out[15] = a[15] + b[15] * scale;\n return out;\n}\n\n/**\n * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyMat4} a The first matrix.\n * @param {ReadonlyMat4} b The second matrix.\n * @returns {Boolean} True if the matrices are equal, false otherwise.\n */\nexport function exactEquals(a, b) {\n return (\n a[0] === b[0] &&\n a[1] === b[1] &&\n a[2] === b[2] &&\n a[3] === b[3] &&\n a[4] === b[4] &&\n a[5] === b[5] &&\n a[6] === b[6] &&\n a[7] === b[7] &&\n a[8] === b[8] &&\n a[9] === b[9] &&\n a[10] === b[10] &&\n a[11] === b[11] &&\n a[12] === b[12] &&\n a[13] === b[13] &&\n a[14] === b[14] &&\n a[15] === b[15]\n );\n}\n\n/**\n * Returns whether or not the matrices have approximately the same elements in the same position.\n *\n * @param {ReadonlyMat4} a The first matrix.\n * @param {ReadonlyMat4} b The second matrix.\n * @returns {Boolean} True if the matrices are equal, false otherwise.\n */\nexport function equals(a, b) {\n const a0 = a[0];\n const a1 = a[1];\n const a2 = a[2];\n const a3 = a[3];\n const a4 = a[4];\n const a5 = a[5];\n const a6 = a[6];\n const a7 = a[7];\n const a8 = a[8];\n const a9 = a[9];\n const a10 = a[10];\n const a11 = a[11];\n const a12 = a[12];\n const a13 = a[13];\n const a14 = a[14];\n const a15 = a[15];\n\n const b0 = b[0];\n const b1 = b[1];\n const b2 = b[2];\n const b3 = b[3];\n const b4 = b[4];\n const b5 = b[5];\n const b6 = b[6];\n const b7 = b[7];\n const b8 = b[8];\n const b9 = b[9];\n const b10 = b[10];\n const b11 = b[11];\n const b12 = b[12];\n const b13 = b[13];\n const b14 = b[14];\n const b15 = b[15];\n\n return (\n Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) &&\n Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) &&\n Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) &&\n Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) &&\n Math.abs(a4 - b4) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) &&\n Math.abs(a5 - b5) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) &&\n Math.abs(a6 - b6) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) &&\n Math.abs(a7 - b7) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) &&\n Math.abs(a8 - b8) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8)) &&\n Math.abs(a9 - b9) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a9), Math.abs(b9)) &&\n Math.abs(a10 - b10) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a10), Math.abs(b10)) &&\n Math.abs(a11 - b11) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a11), Math.abs(b11)) &&\n Math.abs(a12 - b12) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a12), Math.abs(b12)) &&\n Math.abs(a13 - b13) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a13), Math.abs(b13)) &&\n Math.abs(a14 - b14) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a14), Math.abs(b14)) &&\n Math.abs(a15 - b15) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a15), Math.abs(b15))\n );\n}\n\n/**\n * Alias for {@link mat4.multiply}\n * @function\n */\nexport const mul = multiply;\n\n/**\n * Alias for {@link mat4.subtract}\n * @function\n */\nexport const sub = subtract;\n","// @eslint-disable\n// @ts-nocheck\n\nimport * as glMatrix from './common.js';\n\n/**\n * 4 Dimensional Vector\n * @module vec4\n */\n\n/**\n * Creates a new, empty vec4\n *\n * @returns {vec4} a new 4D vector\n */\nexport function create() {\n const out = new glMatrix.ARRAY_TYPE(4);\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[0] = 0;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n }\n return out;\n}\n\n/**\n * Creates a new vec4 initialized with values from an existing vector\n *\n * @param {ReadonlyVec4} a vector to clone\n * @returns {vec4} a new 4D vector\n */\nexport function clone(a) {\n const out = new glMatrix.ARRAY_TYPE(4);\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n return out;\n}\n\n/**\n * Creates a new vec4 initialized with the given values\n *\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @param {Number} w W component\n * @returns {vec4} a new 4D vector\n */\nexport function fromValues(x, y, z, w) {\n const out = new glMatrix.ARRAY_TYPE(4);\n out[0] = x;\n out[1] = y;\n out[2] = z;\n out[3] = w;\n return out;\n}\n\n/**\n * Copy the values from one vec4 to another\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the source vector\n * @returns {vec4} out\n */\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n return out;\n}\n\n/**\n * Set the components of a vec4 to the given values\n *\n * @param {vec4} out the receiving vector\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @param {Number} w W component\n * @returns {vec4} out\n */\nexport function set(out, x, y, z, w) {\n out[0] = x;\n out[1] = y;\n out[2] = z;\n out[3] = w;\n return out;\n}\n\n/**\n * Adds two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n out[2] = a[2] + b[2];\n out[3] = a[3] + b[3];\n return out;\n}\n\n/**\n * Subtracts vector b from vector a\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n out[2] = a[2] - b[2];\n out[3] = a[3] - b[3];\n return out;\n}\n\n/**\n * Multiplies two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\nexport function multiply(out, a, b) {\n out[0] = a[0] * b[0];\n out[1] = a[1] * b[1];\n out[2] = a[2] * b[2];\n out[3] = a[3] * b[3];\n return out;\n}\n\n/**\n * Divides two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\nexport function divide(out, a, b) {\n out[0] = a[0] / b[0];\n out[1] = a[1] / b[1];\n out[2] = a[2] / b[2];\n out[3] = a[3] / b[3];\n return out;\n}\n\n/**\n * Math.ceil the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to ceil\n * @returns {vec4} out\n */\nexport function ceil(out, a) {\n out[0] = Math.ceil(a[0]);\n out[1] = Math.ceil(a[1]);\n out[2] = Math.ceil(a[2]);\n out[3] = Math.ceil(a[3]);\n return out;\n}\n\n/**\n * Math.floor the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to floor\n * @returns {vec4} out\n */\nexport function floor(out, a) {\n out[0] = Math.floor(a[0]);\n out[1] = Math.floor(a[1]);\n out[2] = Math.floor(a[2]);\n out[3] = Math.floor(a[3]);\n return out;\n}\n\n/**\n * Returns the minimum of two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\nexport function min(out, a, b) {\n out[0] = Math.min(a[0], b[0]);\n out[1] = Math.min(a[1], b[1]);\n out[2] = Math.min(a[2], b[2]);\n out[3] = Math.min(a[3], b[3]);\n return out;\n}\n\n/**\n * Returns the maximum of two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\nexport function max(out, a, b) {\n out[0] = Math.max(a[0], b[0]);\n out[1] = Math.max(a[1], b[1]);\n out[2] = Math.max(a[2], b[2]);\n out[3] = Math.max(a[3], b[3]);\n return out;\n}\n\n/**\n * symmetric round the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to round\n * @returns {vec4} out\n */\nexport function round(out, a) {\n out[0] = glMatrix.round(a[0]);\n out[1] = glMatrix.round(a[1]);\n out[2] = glMatrix.round(a[2]);\n out[3] = glMatrix.round(a[3]);\n return out;\n}\n\n/**\n * Scales a vec4 by a scalar number\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the vector to scale\n * @param {Number} b amount to scale the vector by\n * @returns {vec4} out\n */\nexport function scale(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n out[2] = a[2] * b;\n out[3] = a[3] * b;\n return out;\n}\n\n/**\n * Adds two vec4's after scaling the second operand by a scalar value\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @param {Number} scale the amount to scale b by before adding\n * @returns {vec4} out\n */\nexport function scaleAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n out[2] = a[2] + b[2] * scale;\n out[3] = a[3] + b[3] * scale;\n return out;\n}\n\n/**\n * Calculates the euclidian distance between two vec4's\n *\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {Number} distance between a and b\n */\nexport function distance(a, b) {\n const x = b[0] - a[0];\n const y = b[1] - a[1];\n const z = b[2] - a[2];\n const w = b[3] - a[3];\n return Math.sqrt(x * x + y * y + z * z + w * w);\n}\n\n/**\n * Calculates the squared euclidian distance between two vec4's\n *\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {Number} squared distance between a and b\n */\nexport function squaredDistance(a, b) {\n const x = b[0] - a[0];\n const y = b[1] - a[1];\n const z = b[2] - a[2];\n const w = b[3] - a[3];\n return x * x + y * y + z * z + w * w;\n}\n\n/**\n * Calculates the length of a vec4\n *\n * @param {ReadonlyVec4} a vector to calculate length of\n * @returns {Number} length of a\n */\nexport function length(a) {\n const x = a[0];\n const y = a[1];\n const z = a[2];\n const w = a[3];\n return Math.sqrt(x * x + y * y + z * z + w * w);\n}\n\n/**\n * Calculates the squared length of a vec4\n *\n * @param {ReadonlyVec4} a vector to calculate squared length of\n * @returns {Number} squared length of a\n */\nexport function squaredLength(a) {\n const x = a[0];\n const y = a[1];\n const z = a[2];\n const w = a[3];\n return x * x + y * y + z * z + w * w;\n}\n\n/**\n * Negates the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to negate\n * @returns {vec4} out\n */\nexport function negate(out, a) {\n out[0] = -a[0];\n out[1] = -a[1];\n out[2] = -a[2];\n out[3] = -a[3];\n return out;\n}\n\n/**\n * Returns the inverse of the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to invert\n * @returns {vec4} out\n */\nexport function inverse(out, a) {\n out[0] = 1.0 / a[0];\n out[1] = 1.0 / a[1];\n out[2] = 1.0 / a[2];\n out[3] = 1.0 / a[3];\n return out;\n}\n\n/**\n * Normalize a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to normalize\n * @returns {vec4} out\n */\nexport function normalize(out, a) {\n const x = a[0];\n const y = a[1];\n const z = a[2];\n const w = a[3];\n let len = x * x + y * y + z * z + w * w;\n if (len > 0) {\n len = 1 / Math.sqrt(len);\n }\n out[0] = x * len;\n out[1] = y * len;\n out[2] = z * len;\n out[3] = w * len;\n return out;\n}\n\n/**\n * Calculates the dot product of two vec4's\n *\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {Number} dot product of a and b\n */\nexport function dot(a, b) {\n return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];\n}\n\n/**\n * Returns the cross-product of three vectors in a 4-dimensional space\n *\n * @param {ReadonlyVec4} result the receiving vector\n * @param {ReadonlyVec4} U the first vector\n * @param {ReadonlyVec4} V the second vector\n * @param {ReadonlyVec4} W the third vector\n * @returns {vec4} result\n */\nexport function cross(out, u, v, w) {\n const A = v[0] * w[1] - v[1] * w[0];\n const B = v[0] * w[2] - v[2] * w[0];\n const C = v[0] * w[3] - v[3] * w[0];\n const D = v[1] * w[2] - v[2] * w[1];\n const E = v[1] * w[3] - v[3] * w[1];\n const F = v[2] * w[3] - v[3] * w[2];\n const G = u[0];\n const H = u[1];\n const I = u[2];\n const J = u[3];\n\n out[0] = H * F - I * E + J * D;\n out[1] = -(G * F) + I * C - J * B;\n out[2] = G * E - H * C + J * A;\n out[3] = -(G * D) + H * B - I * A;\n\n return out;\n}\n\n/**\n * Performs a linear interpolation between two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec4} out\n */\nexport function lerp(out, a, b, t) {\n const ax = a[0];\n const ay = a[1];\n const az = a[2];\n const aw = a[3];\n out[0] = ax + t * (b[0] - ax);\n out[1] = ay + t * (b[1] - ay);\n out[2] = az + t * (b[2] - az);\n out[3] = aw + t * (b[3] - aw);\n return out;\n}\n\n/**\n * Generates a random vector with the given scale\n *\n * @param {vec4} out the receiving vector\n * @param {Number} [scale] Length of the resulting vector. If omitted, a unit vector will be returned\n * @returns {vec4} out\n */\nexport function random(out, scale) {\n scale = scale === undefined ? 1.0 : scale;\n\n // Marsaglia, George. Choosing a Point from the Surface of a\n // Sphere. Ann. Math. Statist. 43 (1972), no. 2, 645--646.\n // http://projecteuclid.org/euclid.aoms/1177692644;\n let v1;\n let v2;\n let v3;\n let v4;\n let s1;\n let s2;\n do {\n v1 = glMatrix.RANDOM() * 2 - 1;\n v2 = glMatrix.RANDOM() * 2 - 1;\n s1 = v1 * v1 + v2 * v2;\n } while (s1 >= 1);\n do {\n v3 = glMatrix.RANDOM() * 2 - 1;\n v4 = glMatrix.RANDOM() * 2 - 1;\n s2 = v3 * v3 + v4 * v4;\n } while (s2 >= 1);\n\n const d = Math.sqrt((1 - s1) / s2);\n out[0] = scale * v1;\n out[1] = scale * v2;\n out[2] = scale * v3 * d;\n out[3] = scale * v4 * d;\n return out;\n}\n\n/**\n * Transforms the vec4 with a mat4.\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the vector to transform\n * @param {ReadonlyMat4} m matrix to transform with\n * @returns {vec4} out\n */\nexport function transformMat4(out, a, m) {\n const x = a[0];\n const y = a[1];\n const z = a[2];\n const w = a[3];\n out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w;\n out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w;\n out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w;\n out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w;\n return out;\n}\n\n/**\n * Transforms the vec4 with a quat\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the vector to transform\n * @param {ReadonlyQuat} q quaternion to transform with\n * @returns {vec4} out\n */\nexport function transformQuat(out, a, q) {\n const x = a[0];\n const y = a[1];\n const z = a[2];\n const qx = q[0];\n const qy = q[1];\n const qz = q[2];\n const qw = q[3];\n\n // calculate quat * vec\n const ix = qw * x + qy * z - qz * y;\n const iy = qw * y + qz * x - qx * z;\n const iz = qw * z + qx * y - qy * x;\n const iw = -qx * x - qy * y - qz * z;\n\n // calculate result * inverse quat\n out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy;\n out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;\n out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;\n out[3] = a[3];\n return out;\n}\n\n/**\n * Set the components of a vec4 to zero\n *\n * @param {vec4} out the receiving vector\n * @returns {vec4} out\n */\nexport function zero(out) {\n out[0] = 0.0;\n out[1] = 0.0;\n out[2] = 0.0;\n out[3] = 0.0;\n return out;\n}\n\n/**\n * Returns a string representation of a vector\n *\n * @param {ReadonlyVec4} a vector to represent as a string\n * @returns {String} string representation of the vector\n */\nexport function str(a) {\n return `vec4(${a[0]}, ${a[1]}, ${a[2]}, ${a[3]})`;\n}\n\n/**\n * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyVec4} a The first vector.\n * @param {ReadonlyVec4} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3];\n}\n\n/**\n * Returns whether or not the vectors have approximately the same elements in the same position.\n *\n * @param {ReadonlyVec4} a The first vector.\n * @param {ReadonlyVec4} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\nexport function equals(a, b) {\n const a0 = a[0];\n const a1 = a[1];\n const a2 = a[2];\n const a3 = a[3];\n const b0 = b[0];\n const b1 = b[1];\n const b2 = b[2];\n const b3 = b[3];\n return (\n Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) &&\n Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) &&\n Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) &&\n Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3))\n );\n}\n\n/**\n * Alias for {@link vec4.subtract}\n * @function\n */\nexport const sub = subtract;\n\n/**\n * Alias for {@link vec4.multiply}\n * @function\n */\nexport const mul = multiply;\n\n/**\n * Alias for {@link vec4.divide}\n * @function\n */\nexport const div = divide;\n\n/**\n * Alias for {@link vec4.distance}\n * @function\n */\nexport const dist = distance;\n\n/**\n * Alias for {@link vec4.squaredDistance}\n * @function\n */\nexport const sqrDist = squaredDistance;\n\n/**\n * Alias for {@link vec4.length}\n * @function\n */\nexport const len = length;\n\n/**\n * Alias for {@link vec4.squaredLength}\n * @function\n */\nexport const sqrLen = squaredLength;\n\n/**\n * Perform some operation over an array of vec4s.\n *\n * @param {Array} a the array of vectors to iterate over\n * @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed\n * @param {Number} offset Number of elements to skip at the beginning of the array\n * @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array\n * @param {Function} fn Function to call for each vector in the array\n * @param {Object} [arg] additional argument to pass to fn\n * @returns {Array} a\n * @function\n */\nexport const forEach = (function () {\n const vec = create();\n\n return function (a, stride, offset, count, fn, arg) {\n let i;\n let l;\n if (!stride) {\n stride = 4;\n }\n\n if (!offset) {\n offset = 0;\n }\n\n if (count) {\n l = Math.min(count * stride + offset, a.length);\n } else {\n l = a.length;\n }\n\n for (i = offset; i < l; i += stride) {\n vec[0] = a[i];\n vec[1] = a[i + 1];\n vec[2] = a[i + 2];\n vec[3] = a[i + 3];\n fn(vec, vec, arg);\n a[i] = vec[0];\n a[i + 1] = vec[1];\n a[i + 2] = vec[2];\n a[i + 3] = vec[3];\n }\n\n return a;\n };\n})();\n","// math.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n// Copyright (c) 2017 Uber Technologies, Inc.\n\nimport {NumericArray, NumericArray16} from '@math.gl/types';\nimport {Matrix} from './base/matrix';\nimport {checkVector} from '../lib/validators';\n\n/* eslint-disable camelcase */\nimport {vec2_transformMat4AsVector, vec3_transformMat4AsVector} from '../lib/gl-matrix-extras';\n// @ts-ignore gl-matrix types...\nimport {\n fromQuat as mat4_fromQuat,\n frustum as mat4_frustum,\n lookAt as mat4_lookAt,\n ortho as mat4_ortho,\n perspective as mat4_perspective,\n determinant as mat4_determinant,\n transpose as mat4_transpose,\n invert as mat4_invert,\n multiply as mat4_multiply,\n rotateX as mat4_rotateX,\n rotateY as mat4_rotateY,\n rotateZ as mat4_rotateZ,\n rotate as mat4_rotate,\n scale as mat4_scale,\n translate as mat4_translate\n} from '../gl-matrix/mat4';\nimport {transformMat4 as vec2_transformMat4} from '../gl-matrix/vec2';\nimport {transformMat4 as vec3_transformMat4} from '../gl-matrix/vec3';\nimport {transformMat4 as vec4_transformMat4} from '../gl-matrix/vec4';\n\n// eslint-disable-next-line no-shadow\nenum INDICES {\n COL0ROW0 = 0,\n COL0ROW1 = 1,\n COL0ROW2 = 2,\n COL0ROW3 = 3,\n COL1ROW0 = 4,\n COL1ROW1 = 5,\n COL1ROW2 = 6,\n COL1ROW3 = 7,\n COL2ROW0 = 8,\n COL2ROW1 = 9,\n COL2ROW2 = 10,\n COL2ROW3 = 11,\n COL3ROW0 = 12,\n COL3ROW1 = 13,\n COL3ROW2 = 14,\n COL3ROW3 = 15\n}\n\nconst DEFAULT_FOVY = (45 * Math.PI) / 180;\nconst DEFAULT_ASPECT = 1;\nconst DEFAULT_NEAR = 0.1;\nconst DEFAULT_FAR = 500;\n\nconst IDENTITY_MATRIX = Object.freeze([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);\n\n/** Helper type that captures array length for a 4x4 matrix */\nexport type Matrix4Like = Matrix4 | NumericArray16;\n\n/**\n * A 4x4 matrix with common linear algebra operations\n * Subclass of Array meaning that it is highly compatible with other libraries\n */\nexport class Matrix4 extends Matrix {\n static get IDENTITY(): Readonly {\n return getIdentityMatrix();\n }\n\n static get ZERO(): Readonly {\n return getZeroMatrix();\n }\n\n get ELEMENTS(): number {\n return 16;\n }\n\n get RANK(): number {\n return 4;\n }\n\n get INDICES(): typeof INDICES {\n return INDICES;\n }\n\n constructor(array?: Readonly) {\n // PERF NOTE: initialize elements as double precision numbers\n super(-0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0);\n if (arguments.length === 1 && Array.isArray(array)) {\n this.copy(array);\n } else {\n this.identity();\n }\n }\n\n copy(array: Readonly): this {\n this[0] = array[0];\n this[1] = array[1];\n this[2] = array[2];\n this[3] = array[3];\n this[4] = array[4];\n this[5] = array[5];\n this[6] = array[6];\n this[7] = array[7];\n this[8] = array[8];\n this[9] = array[9];\n this[10] = array[10];\n this[11] = array[11];\n this[12] = array[12];\n this[13] = array[13];\n this[14] = array[14];\n this[15] = array[15];\n return this.check();\n }\n\n // eslint-disable-next-line max-params\n set(\n m00: number,\n m10: number,\n m20: number,\n m30: number,\n m01: number,\n m11: number,\n m21: number,\n m31: number,\n m02: number,\n m12: number,\n m22: number,\n m32: number,\n m03: number,\n m13: number,\n m23: number,\n m33: number\n ): this {\n this[0] = m00;\n this[1] = m10;\n this[2] = m20;\n this[3] = m30;\n this[4] = m01;\n this[5] = m11;\n this[6] = m21;\n this[7] = m31;\n this[8] = m02;\n this[9] = m12;\n this[10] = m22;\n this[11] = m32;\n this[12] = m03;\n this[13] = m13;\n this[14] = m23;\n this[15] = m33;\n return this.check();\n }\n\n // accepts row major order, stores as column major\n // eslint-disable-next-line max-params\n setRowMajor(\n m00: number,\n m01: number,\n m02: number,\n m03: number,\n m10: number,\n m11: number,\n m12: number,\n m13: number,\n m20: number,\n m21: number,\n m22: number,\n m23: number,\n m30: number,\n m31: number,\n m32: number,\n m33: number\n ): this {\n this[0] = m00;\n this[1] = m10;\n this[2] = m20;\n this[3] = m30;\n this[4] = m01;\n this[5] = m11;\n this[6] = m21;\n this[7] = m31;\n this[8] = m02;\n this[9] = m12;\n this[10] = m22;\n this[11] = m32;\n this[12] = m03;\n this[13] = m13;\n this[14] = m23;\n this[15] = m33;\n return this.check();\n }\n\n toRowMajor(result: NumericArray): NumericArray {\n result[0] = this[0];\n result[1] = this[4];\n result[2] = this[8];\n result[3] = this[12];\n result[4] = this[1];\n result[5] = this[5];\n result[6] = this[9];\n result[7] = this[13];\n result[8] = this[2];\n result[9] = this[6];\n result[10] = this[10];\n result[11] = this[14];\n result[12] = this[3];\n result[13] = this[7];\n result[14] = this[11];\n result[15] = this[15];\n return result;\n }\n\n // Constructors\n\n /** Set to identity matrix */\n identity(): this {\n return this.copy(IDENTITY_MATRIX);\n }\n\n /**\n *\n * @param object\n * @returns self\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n fromObject(object: {[key: string]: any}): this {\n return this.check();\n }\n\n /**\n * Calculates a 4x4 matrix from the given quaternion\n * @param quaternion Quaternion to create matrix from\n * @returns self\n */\n fromQuaternion(quaternion: Readonly): this {\n mat4_fromQuat(this, quaternion);\n return this.check();\n }\n\n /**\n * Generates a frustum matrix with the given bounds\n * @param view.left - Left bound of the frustum\n * @param view.right - Right bound of the frustum\n * @param view.bottom - Bottom bound of the frustum\n * @param view.top - Top bound of the frustum\n * @param view.near - Near bound of the frustum\n * @param view.far - Far bound of the frustum. Can be set to Infinity.\n * @returns self\n */\n frustum(view: {\n left: number;\n right: number;\n bottom: number;\n top: number;\n near: number;\n far?: number;\n }): this {\n const {left, right, bottom, top, near = DEFAULT_NEAR, far = DEFAULT_FAR} = view;\n if (far === Infinity) {\n computeInfinitePerspectiveOffCenter(this, left, right, bottom, top, near);\n } else {\n mat4_frustum(this, left, right, bottom, top, near, far);\n }\n return this.check();\n }\n\n /**\n * Generates a look-at matrix with the given eye position, focal point,\n * and up axis\n * @param view.eye - (vector) Position of the viewer\n * @param view.center - (vector) Point the viewer is looking at\n * @param view.up - (vector) Up axis\n * @returns self\n */\n lookAt(view: {\n eye: Readonly;\n center?: Readonly;\n up?: Readonly;\n }): this {\n const {eye, center = [0, 0, 0], up = [0, 1, 0]} = view;\n mat4_lookAt(this, eye, center, up);\n return this.check();\n }\n\n /**\n * Generates a orthogonal projection matrix with the given bounds\n * from \"traditional\" view space parameters\n * @param view.left - Left bound of the frustum\n * @param view.right number Right bound of the frustum\n * @param view.bottom - Bottom bound of the frustum\n * @param view.top number Top bound of the frustum\n * @param view.near - Near bound of the frustum\n * @param view.far number Far bound of the frustum\n * @returns self\n */\n ortho(view: {\n left: number;\n right: number;\n bottom: number;\n top: number;\n near?: number;\n far?: number;\n }): this {\n const {left, right, bottom, top, near = DEFAULT_NEAR, far = DEFAULT_FAR} = view;\n mat4_ortho(this, left, right, bottom, top, near, far);\n return this.check();\n }\n\n /**\n * Generates an orthogonal projection matrix with the same parameters\n * as a perspective matrix (plus focalDistance)\n * @param view.fovy Vertical field of view in radians\n * @param view.aspect Aspect ratio. Typically viewport width / viewport height\n * @param view.focalDistance Distance in the view frustum used for extent calculations\n * @param view.near Near bound of the frustum\n * @param view.far Far bound of the frustum\n * @returns self\n */\n orthographic(view: {\n fovy?: number;\n aspect?: number;\n focalDistance?: number;\n near?: number;\n far?: number;\n }): this {\n const {\n fovy = DEFAULT_FOVY,\n aspect = DEFAULT_ASPECT,\n focalDistance = 1,\n near = DEFAULT_NEAR,\n far = DEFAULT_FAR\n } = view;\n\n checkRadians(fovy);\n\n const halfY = fovy / 2;\n const top = focalDistance * Math.tan(halfY); // focus_plane is the distance from the camera\n const right = top * aspect;\n\n return this.ortho({\n left: -right,\n right,\n bottom: -top,\n top,\n near,\n far\n });\n }\n\n /**\n * Generates a perspective projection matrix with the given bounds\n * @param view.fovy Vertical field of view in radians\n * @param view.aspect Aspect ratio. typically viewport width/height\n * @param view.near Near bound of the frustum\n * @param view.far Far bound of the frustum\n * @returns self\n */\n perspective(view: {fovy: number; aspect?: number; near?: number; far?: number}): this {\n const {fovy = (45 * Math.PI) / 180, aspect = 1, near = 0.1, far = 500} = view;\n checkRadians(fovy);\n mat4_perspective(this, fovy, aspect, near, far);\n return this.check();\n }\n\n // Accessors\n\n determinant(): number {\n return mat4_determinant(this);\n }\n\n /**\n * Extracts the non-uniform scale assuming the matrix is an affine transformation.\n * The scales are the \"lengths\" of the column vectors in the upper-left 3x3 matrix.\n * @param result\n * @returns self\n */\n getScale(result: NumericArray = [-0, -0, -0]): NumericArray {\n // explicit is faster than hypot...\n result[0] = Math.sqrt(this[0] * this[0] + this[1] * this[1] + this[2] * this[2]);\n result[1] = Math.sqrt(this[4] * this[4] + this[5] * this[5] + this[6] * this[6]);\n result[2] = Math.sqrt(this[8] * this[8] + this[9] * this[9] + this[10] * this[10]);\n // result[0] = Math.hypot(this[0], this[1], this[2]);\n // result[1] = Math.hypot(this[4], this[5], this[6]);\n // result[2] = Math.hypot(this[8], this[9], this[10]);\n return result;\n }\n\n /**\n * Gets the translation portion, assuming the matrix is a affine transformation matrix.\n * @param result\n * @returns self\n */\n getTranslation(result: NumericArray = [-0, -0, -0]): NumericArray {\n result[0] = this[12];\n result[1] = this[13];\n result[2] = this[14];\n return result;\n }\n\n /**\n * Gets upper left 3x3 pure rotation matrix (non-scaling), assume affine transformation matrix\n * @param result\n * @param scaleResult\n * @returns self\n */\n getRotation(result?: NumericArray, scaleResult?: NumericArray): NumericArray {\n result = result || [-0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0];\n scaleResult = scaleResult || [-0, -0, -0];\n const scale = this.getScale(scaleResult);\n const inverseScale0 = 1 / scale[0];\n const inverseScale1 = 1 / scale[1];\n const inverseScale2 = 1 / scale[2];\n result[0] = this[0] * inverseScale0;\n result[1] = this[1] * inverseScale1;\n result[2] = this[2] * inverseScale2;\n result[3] = 0;\n result[4] = this[4] * inverseScale0;\n result[5] = this[5] * inverseScale1;\n result[6] = this[6] * inverseScale2;\n result[7] = 0;\n result[8] = this[8] * inverseScale0;\n result[9] = this[9] * inverseScale1;\n result[10] = this[10] * inverseScale2;\n result[11] = 0;\n result[12] = 0;\n result[13] = 0;\n result[14] = 0;\n result[15] = 1;\n return result;\n }\n\n /**\n *\n * @param result\n * @param scaleResult\n * @returns self\n */\n getRotationMatrix3(result?: NumericArray, scaleResult?: NumericArray): NumericArray {\n result = result || [-0, -0, -0, -0, -0, -0, -0, -0, -0];\n scaleResult = scaleResult || [-0, -0, -0];\n const scale = this.getScale(scaleResult);\n const inverseScale0 = 1 / scale[0];\n const inverseScale1 = 1 / scale[1];\n const inverseScale2 = 1 / scale[2];\n result[0] = this[0] * inverseScale0;\n result[1] = this[1] * inverseScale1;\n result[2] = this[2] * inverseScale2;\n result[3] = this[4] * inverseScale0;\n result[4] = this[5] * inverseScale1;\n result[5] = this[6] * inverseScale2;\n result[6] = this[8] * inverseScale0;\n result[7] = this[9] * inverseScale1;\n result[8] = this[10] * inverseScale2;\n return result;\n }\n\n // Modifiers\n\n transpose(): this {\n mat4_transpose(this, this);\n return this.check();\n }\n\n invert(): this {\n mat4_invert(this, this);\n return this.check();\n }\n\n // Operations\n\n multiplyLeft(a: Readonly): this {\n mat4_multiply(this, a, this);\n return this.check();\n }\n\n multiplyRight(a: Readonly): this {\n mat4_multiply(this, this, a);\n return this.check();\n }\n\n // Rotates a matrix by the given angle around the X axis\n rotateX(radians: number): this {\n mat4_rotateX(this, this, radians);\n // mat4_rotate(this, this, radians, [1, 0, 0]);\n return this.check();\n }\n\n // Rotates a matrix by the given angle around the Y axis.\n rotateY(radians: number): this {\n mat4_rotateY(this, this, radians);\n // mat4_rotate(this, this, radians, [0, 1, 0]);\n return this.check();\n }\n\n /**\n * Rotates a matrix by the given angle around the Z axis.\n * @param radians\n * @returns self\n */\n rotateZ(radians: number): this {\n mat4_rotateZ(this, this, radians);\n // mat4_rotate(this, this, radians, [0, 0, 1]);\n return this.check();\n }\n\n /**\n *\n * @param param0\n * @returns self\n */\n rotateXYZ(angleXYZ: Readonly): this {\n return this.rotateX(angleXYZ[0]).rotateY(angleXYZ[1]).rotateZ(angleXYZ[2]);\n }\n\n /**\n *\n * @param radians\n * @param axis\n * @returns self\n */\n rotateAxis(radians: number, axis: Readonly): this {\n mat4_rotate(this, this, radians, axis);\n return this.check();\n }\n\n /**\n *\n * @param factor\n * @returns self\n */\n override scale(factor: number | Readonly): this {\n mat4_scale(this, this, Array.isArray(factor) ? factor : [factor, factor, factor]);\n return this.check();\n }\n\n /**\n *\n * @param vec\n * @returns self\n */\n translate(vector: Readonly): this {\n mat4_translate(this, this, vector);\n return this.check();\n }\n\n // Transforms\n\n /**\n * Transforms any 2, 3 or 4 element vector. 2 and 3 elements are treated as points\n * @param vector\n * @param result\n * @returns self\n */\n transform(vector: Readonly, result?: NumericArray): NumericArray {\n if (vector.length === 4) {\n result = vec4_transformMat4(result || [-0, -0, -0, -0], vector, this) as NumericArray;\n checkVector(result, 4);\n return result;\n }\n return this.transformAsPoint(vector, result);\n }\n\n /**\n * Transforms any 2 or 3 element array as point (w implicitly 1)\n * @param vector\n * @param result\n * @returns self\n */\n transformAsPoint(vector: Readonly, result?: NumericArray): NumericArray {\n const {length} = vector;\n let out: NumericArray;\n switch (length) {\n case 2:\n out = vec2_transformMat4(result || [-0, -0], vector, this) as NumericArray;\n break;\n case 3:\n out = vec3_transformMat4(result || [-0, -0, -0], vector, this) as NumericArray;\n break;\n default:\n throw new Error('Illegal vector');\n }\n checkVector(out, vector.length);\n return out;\n }\n\n /**\n * Transforms any 2 or 3 element array as vector (w implicitly 0)\n * @param vector\n * @param result\n * @returns self\n */\n transformAsVector(vector: Readonly, result?: NumericArray): NumericArray {\n let out: NumericArray;\n switch (vector.length) {\n case 2:\n out = vec2_transformMat4AsVector(result || [-0, -0], vector, this);\n break;\n case 3:\n out = vec3_transformMat4AsVector(result || [-0, -0, -0], vector, this);\n break;\n default:\n throw new Error('Illegal vector');\n }\n checkVector(out, vector.length);\n return out;\n }\n\n /** @deprecated */\n transformPoint(vector: Readonly, result?: NumericArray): NumericArray {\n return this.transformAsPoint(vector, result);\n }\n\n /** @deprecated */\n transformVector(vector: Readonly, result?: NumericArray): NumericArray {\n return this.transformAsPoint(vector, result);\n }\n\n /** @deprecated */\n transformDirection(vector: Readonly, result?: NumericArray): NumericArray {\n return this.transformAsVector(vector, result);\n }\n\n // three.js math API compatibility\n\n makeRotationX(radians: number): this {\n return this.identity().rotateX(radians);\n }\n\n makeTranslation(x: number, y: number, z: number): this {\n return this.identity().translate([x, y, z]);\n }\n}\n\n// TODO initializing static members directly is an option, but make sure no tree-shaking issues\nlet ZERO: Matrix4;\nlet IDENTITY: Matrix4;\n\nfunction getZeroMatrix(): Readonly {\n if (!ZERO) {\n ZERO = new Matrix4([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);\n Object.freeze(ZERO);\n }\n return ZERO;\n}\n\nfunction getIdentityMatrix(): Matrix4 {\n if (!IDENTITY) {\n IDENTITY = new Matrix4();\n Object.freeze(IDENTITY);\n }\n return IDENTITY;\n}\n\n// HELPER FUNCTIONS\n\nfunction checkRadians(possiblyDegrees: number) {\n if (possiblyDegrees > Math.PI * 2) {\n throw Error('expected radians');\n }\n}\n\n// eslint-disable-next-line max-params\nfunction computeInfinitePerspectiveOffCenter(\n result: NumericArray,\n left: number,\n right: number,\n bottom: number,\n top: number,\n near: number\n): NumericArray {\n const column0Row0 = (2 * near) / (right - left);\n const column1Row1 = (2 * near) / (top - bottom);\n const column2Row0 = (right + left) / (right - left);\n const column2Row1 = (top + bottom) / (top - bottom);\n const column2Row2 = -1;\n const column2Row3 = -1;\n const column3Row2 = -2 * near;\n result[0] = column0Row0;\n result[1] = 0;\n result[2] = 0;\n result[3] = 0;\n result[4] = 0;\n result[5] = column1Row1;\n result[6] = 0;\n result[7] = 0;\n result[8] = column2Row0;\n result[9] = column2Row1;\n result[10] = column2Row2;\n result[11] = column2Row3;\n result[12] = 0;\n result[13] = 0;\n result[14] = column3Row2;\n result[15] = 0;\n return result;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {NumericArray} from '@math.gl/types';\n\n/**\n * Calculate WebGL 64 bit float\n * @param a - the input float number\n * @param out - the output array. If not supplied, a new array is created.\n * @param startIndex - the index in the output array to fill from. Default 0.\n * @returns - the fp64 representation of the input number\n */\nexport function fp64ify(a: number, out: NumericArray = [], startIndex: number = 0): NumericArray {\n const hiPart = Math.fround(a);\n const loPart = a - hiPart;\n out[startIndex] = hiPart;\n out[startIndex + 1] = loPart;\n return out;\n}\n\n/**\n * Calculate the low part of a WebGL 64 bit float\n * @param a the input float number\n * @returns the lower 32 bit of the number\n */\nexport function fp64LowPart(a: number): number {\n return a - Math.fround(a);\n}\n\n/**\n * Calculate WebGL 64 bit matrix (transposed \"Float64Array\")\n * @param matrix the input matrix\n * @returns the fp64 representation of the input matrix\n */\nexport function fp64ifyMatrix4(matrix: NumericArray): Float32Array {\n // Transpose the projection matrix to column major for GLSL.\n const matrixFP64 = new Float32Array(32);\n for (let i = 0; i < 4; ++i) {\n for (let j = 0; j < 4; ++j) {\n const index = i * 4 + j;\n fp64ify(matrix[j * 4 + i], matrixFP64, index * 2);\n }\n }\n return matrixFP64;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {NumberArray3, NumberArray4} from '@math.gl/types';\n\n/**\n * Resolves whether semantic colors should be interpreted as byte-style `0..255` values.\n * @param useByteColors - Explicit color interpretation flag.\n * @param defaultUseByteColors - Fallback value when `useByteColors` is omitted.\n * @returns `true` when semantic colors should be normalized from bytes, otherwise `false`.\n */\nexport function resolveUseByteColors(\n useByteColors?: boolean,\n defaultUseByteColors: boolean = true\n): boolean {\n return useByteColors ?? defaultUseByteColors;\n}\n\n/**\n * Normalizes an RGB semantic color to float space when byte-style colors are enabled.\n * @param color - Input RGB semantic color.\n * @param useByteColors - When `true`, divide components by `255`.\n * @returns The normalized RGB color.\n */\nexport function normalizeByteColor3(\n color: Readonly = [0, 0, 0],\n useByteColors: boolean = true\n): NumberArray3 {\n if (!useByteColors) {\n return [...color] as NumberArray3;\n }\n\n return color.map(component => component / 255) as NumberArray3;\n}\n\n/**\n * Normalizes an RGBA semantic color to float space when byte-style colors are enabled.\n * @param color - Input RGB or RGBA semantic color.\n * @param useByteColors - When `true`, divide components by `255`.\n * @returns The normalized RGBA color, adding an opaque alpha channel when needed.\n */\nexport function normalizeByteColor4(\n color: Readonly | Readonly,\n useByteColors: boolean = true\n): NumberArray4 {\n const normalizedColor = normalizeByteColor3(color.slice(0, 3) as NumberArray3, useByteColors);\n const hasAlpha = Number.isFinite(color[3]);\n const alpha = hasAlpha ? (color[3] as number) : 1;\n\n return [\n normalizedColor[0],\n normalizedColor[1],\n normalizedColor[2],\n useByteColors && hasAlpha ? alpha / 255 : alpha\n ] as NumberArray4;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// import {ShaderModule} from '../../types';\n\nconst fp32shader = /* glsl */ `\\\n#ifdef LUMA_FP32_TAN_PRECISION_WORKAROUND\n\n// All these functions are for substituting tan() function from Intel GPU only\nconst float TWO_PI = 6.2831854820251465;\nconst float PI_2 = 1.5707963705062866;\nconst float PI_16 = 0.1963495463132858;\n\nconst float SIN_TABLE_0 = 0.19509032368659973;\nconst float SIN_TABLE_1 = 0.3826834261417389;\nconst float SIN_TABLE_2 = 0.5555702447891235;\nconst float SIN_TABLE_3 = 0.7071067690849304;\n\nconst float COS_TABLE_0 = 0.9807852506637573;\nconst float COS_TABLE_1 = 0.9238795042037964;\nconst float COS_TABLE_2 = 0.8314695954322815;\nconst float COS_TABLE_3 = 0.7071067690849304;\n\nconst float INVERSE_FACTORIAL_3 = 1.666666716337204e-01; // 1/3!\nconst float INVERSE_FACTORIAL_5 = 8.333333767950535e-03; // 1/5!\nconst float INVERSE_FACTORIAL_7 = 1.9841270113829523e-04; // 1/7!\nconst float INVERSE_FACTORIAL_9 = 2.75573188446287533e-06; // 1/9!\n\nfloat sin_taylor_fp32(float a) {\n float r, s, t, x;\n\n if (a == 0.0) {\n return 0.0;\n }\n\n x = -a * a;\n s = a;\n r = a;\n\n r = r * x;\n t = r * INVERSE_FACTORIAL_3;\n s = s + t;\n\n r = r * x;\n t = r * INVERSE_FACTORIAL_5;\n s = s + t;\n\n r = r * x;\n t = r * INVERSE_FACTORIAL_7;\n s = s + t;\n\n r = r * x;\n t = r * INVERSE_FACTORIAL_9;\n s = s + t;\n\n return s;\n}\n\nvoid sincos_taylor_fp32(float a, out float sin_t, out float cos_t) {\n if (a == 0.0) {\n sin_t = 0.0;\n cos_t = 1.0;\n }\n sin_t = sin_taylor_fp32(a);\n cos_t = sqrt(1.0 - sin_t * sin_t);\n}\n\nfloat tan_taylor_fp32(float a) {\n float sin_a;\n float cos_a;\n\n if (a == 0.0) {\n return 0.0;\n }\n\n // 2pi range reduction\n float z = floor(a / TWO_PI);\n float r = a - TWO_PI * z;\n\n float t;\n float q = floor(r / PI_2 + 0.5);\n int j = int(q);\n\n if (j < -2 || j > 2) {\n return 1.0 / 0.0;\n }\n\n t = r - PI_2 * q;\n\n q = floor(t / PI_16 + 0.5);\n int k = int(q);\n int abs_k = int(abs(float(k)));\n\n if (abs_k > 4) {\n return 1.0 / 0.0;\n } else {\n t = t - PI_16 * q;\n }\n\n float u = 0.0;\n float v = 0.0;\n\n float sin_t, cos_t;\n float s, c;\n sincos_taylor_fp32(t, sin_t, cos_t);\n\n if (k == 0) {\n s = sin_t;\n c = cos_t;\n } else {\n if (abs(float(abs_k) - 1.0) < 0.5) {\n u = COS_TABLE_0;\n v = SIN_TABLE_0;\n } else if (abs(float(abs_k) - 2.0) < 0.5) {\n u = COS_TABLE_1;\n v = SIN_TABLE_1;\n } else if (abs(float(abs_k) - 3.0) < 0.5) {\n u = COS_TABLE_2;\n v = SIN_TABLE_2;\n } else if (abs(float(abs_k) - 4.0) < 0.5) {\n u = COS_TABLE_3;\n v = SIN_TABLE_3;\n }\n if (k > 0) {\n s = u * sin_t + v * cos_t;\n c = u * cos_t - v * sin_t;\n } else {\n s = u * sin_t - v * cos_t;\n c = u * cos_t + v * sin_t;\n }\n }\n\n if (j == 0) {\n sin_a = s;\n cos_a = c;\n } else if (j == 1) {\n sin_a = c;\n cos_a = -s;\n } else if (j == -1) {\n sin_a = -c;\n cos_a = s;\n } else {\n sin_a = -s;\n cos_a = -c;\n }\n return sin_a / cos_a;\n}\n#endif\n\nfloat tan_fp32(float a) {\n#ifdef LUMA_FP32_TAN_PRECISION_WORKAROUND\n return tan_taylor_fp32(a);\n#else\n return tan(a);\n#endif\n}\n`;\n\n/**\n * 32 bit math library (fixups for GPUs)\n */\nexport const fp32 = {\n name: 'fp32',\n vs: fp32shader\n};\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport const fp64arithmeticShader = /* glsl */ `\\\n\nlayout(std140) uniform fp64arithmeticUniforms {\n uniform float ONE;\n uniform float SPLIT;\n} fp64;\n\n/*\nAbout LUMA_FP64_CODE_ELIMINATION_WORKAROUND\n\nThe purpose of this workaround is to prevent shader compilers from\noptimizing away necessary arithmetic operations by swapping their sequences\nor transform the equation to some 'equivalent' form.\n\nThese helpers implement Dekker/Veltkamp-style error tracking. If the compiler\nfolds constants or reassociates the arithmetic, the high/low split can stop\ntracking the rounding error correctly. That failure mode tends to look fine in\nsimple coordinate setup, but then breaks down inside iterative arithmetic such\nas fp64 Mandelbrot loops.\n\nThe method is to multiply an artifical variable, ONE, which will be known to\nthe compiler to be 1 only at runtime. The whole expression is then represented\nas a polynomial with respective to ONE. In the coefficients of all terms, only one a\nand one b should appear\n\nerr = (a + b) * ONE^6 - a * ONE^5 - (a + b) * ONE^4 + a * ONE^3 - b - (a + b) * ONE^2 + a * ONE\n*/\n\nfloat prevent_fp64_optimization(float value) {\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n return value + fp64.ONE * 0.0;\n#else\n return value;\n#endif\n}\n\n// Divide float number to high and low floats to extend fraction bits\nvec2 split(float a) {\n // Keep SPLIT as a runtime uniform so the compiler cannot fold the Dekker\n // split into a constant expression and reassociate the recovery steps.\n float split = prevent_fp64_optimization(fp64.SPLIT);\n float t = prevent_fp64_optimization(a * split);\n float temp = t - a;\n float a_hi = t - temp;\n float a_lo = a - a_hi;\n return vec2(a_hi, a_lo);\n}\n\n// Divide float number again when high float uses too many fraction bits\nvec2 split2(vec2 a) {\n vec2 b = split(a.x);\n b.y += a.y;\n return b;\n}\n\n// Special sum operation when a > b\nvec2 quickTwoSum(float a, float b) {\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n float sum = (a + b) * fp64.ONE;\n float err = b - (sum - a) * fp64.ONE;\n#else\n float sum = a + b;\n float err = b - (sum - a);\n#endif\n return vec2(sum, err);\n}\n\n// General sum operation\nvec2 twoSum(float a, float b) {\n float s = (a + b);\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n float v = (s * fp64.ONE - a) * fp64.ONE;\n float err = (a - (s - v) * fp64.ONE) * fp64.ONE * fp64.ONE * fp64.ONE + (b - v);\n#else\n float v = s - a;\n float err = (a - (s - v)) + (b - v);\n#endif\n return vec2(s, err);\n}\n\nvec2 twoSub(float a, float b) {\n float s = (a - b);\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n float v = (s * fp64.ONE - a) * fp64.ONE;\n float err = (a - (s - v) * fp64.ONE) * fp64.ONE * fp64.ONE * fp64.ONE - (b + v);\n#else\n float v = s - a;\n float err = (a - (s - v)) - (b + v);\n#endif\n return vec2(s, err);\n}\n\nvec2 twoSqr(float a) {\n float prod = a * a;\n vec2 a_fp64 = split(a);\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n float err = ((a_fp64.x * a_fp64.x - prod) * fp64.ONE + 2.0 * a_fp64.x *\n a_fp64.y * fp64.ONE * fp64.ONE) + a_fp64.y * a_fp64.y * fp64.ONE * fp64.ONE * fp64.ONE;\n#else\n float err = ((a_fp64.x * a_fp64.x - prod) + 2.0 * a_fp64.x * a_fp64.y) + a_fp64.y * a_fp64.y;\n#endif\n return vec2(prod, err);\n}\n\nvec2 twoProd(float a, float b) {\n float prod = a * b;\n vec2 a_fp64 = split(a);\n vec2 b_fp64 = split(b);\n // twoProd is especially sensitive because mul_fp64 and div_fp64 both depend\n // on the split terms and cross terms staying in the original evaluation\n // order. If the compiler folds or reassociates them, the low part tends to\n // collapse to zero or NaN on some drivers.\n float highProduct = prevent_fp64_optimization(a_fp64.x * b_fp64.x);\n float crossProduct1 = prevent_fp64_optimization(a_fp64.x * b_fp64.y);\n float crossProduct2 = prevent_fp64_optimization(a_fp64.y * b_fp64.x);\n float lowProduct = prevent_fp64_optimization(a_fp64.y * b_fp64.y);\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n float err1 = (highProduct - prod) * fp64.ONE;\n float err2 = crossProduct1 * fp64.ONE * fp64.ONE;\n float err3 = crossProduct2 * fp64.ONE * fp64.ONE * fp64.ONE;\n float err4 = lowProduct * fp64.ONE * fp64.ONE * fp64.ONE * fp64.ONE;\n#else\n float err1 = highProduct - prod;\n float err2 = crossProduct1;\n float err3 = crossProduct2;\n float err4 = lowProduct;\n#endif\n float err = ((err1 + err2) + err3) + err4;\n return vec2(prod, err);\n}\n\nvec2 sum_fp64(vec2 a, vec2 b) {\n vec2 s, t;\n s = twoSum(a.x, b.x);\n t = twoSum(a.y, b.y);\n s.y += t.x;\n s = quickTwoSum(s.x, s.y);\n s.y += t.y;\n s = quickTwoSum(s.x, s.y);\n return s;\n}\n\nvec2 sub_fp64(vec2 a, vec2 b) {\n vec2 s, t;\n s = twoSub(a.x, b.x);\n t = twoSub(a.y, b.y);\n s.y += t.x;\n s = quickTwoSum(s.x, s.y);\n s.y += t.y;\n s = quickTwoSum(s.x, s.y);\n return s;\n}\n\nvec2 mul_fp64(vec2 a, vec2 b) {\n vec2 prod = twoProd(a.x, b.x);\n // y component is for the error\n prod.y += a.x * b.y;\n#if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND)\n prod = split2(prod);\n#endif\n prod = quickTwoSum(prod.x, prod.y);\n prod.y += a.y * b.x;\n#if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND)\n prod = split2(prod);\n#endif\n prod = quickTwoSum(prod.x, prod.y);\n return prod;\n}\n\nvec2 div_fp64(vec2 a, vec2 b) {\n float xn = 1.0 / b.x;\n#if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND)\n vec2 yn = mul_fp64(a, vec2(xn, 0));\n#else\n vec2 yn = a * xn;\n#endif\n float diff = (sub_fp64(a, mul_fp64(b, yn))).x;\n vec2 prod = twoProd(xn, diff);\n return sum_fp64(yn, prod);\n}\n\nvec2 sqrt_fp64(vec2 a) {\n if (a.x == 0.0 && a.y == 0.0) return vec2(0.0, 0.0);\n if (a.x < 0.0) return vec2(0.0 / 0.0, 0.0 / 0.0);\n\n float x = 1.0 / sqrt(a.x);\n float yn = a.x * x;\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n vec2 yn_sqr = twoSqr(yn) * fp64.ONE;\n#else\n vec2 yn_sqr = twoSqr(yn);\n#endif\n float diff = sub_fp64(a, yn_sqr).x;\n vec2 prod = twoProd(x * 0.5, diff);\n#if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND)\n return sum_fp64(split(yn), prod);\n#else\n return sum_fp64(vec2(yn, 0.0), prod);\n#endif\n}\n`;\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport const fp64arithmeticWGSL = /* wgsl */ `\\\nstruct Fp64ArithmeticUniforms {\n ONE: f32,\n SPLIT: f32,\n};\n\n@group(0) @binding(auto) var fp64arithmetic : Fp64ArithmeticUniforms;\n\nfn fp64_nan(seed: f32) -> f32 {\n let nanBits = 0x7fc00000u | select(0u, 1u, seed < 0.0);\n return bitcast(nanBits);\n}\n\nfn fp64_runtime_zero() -> f32 {\n return fp64arithmetic.ONE * 0.0;\n}\n\nfn prevent_fp64_optimization(value: f32) -> f32 {\n#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND\n return value + fp64_runtime_zero();\n#else\n return value;\n#endif\n}\n\nfn split(a: f32) -> vec2f {\n let splitValue = prevent_fp64_optimization(fp64arithmetic.SPLIT + fp64_runtime_zero());\n let t = prevent_fp64_optimization(a * splitValue);\n let temp = prevent_fp64_optimization(t - a);\n let aHi = prevent_fp64_optimization(t - temp);\n let aLo = prevent_fp64_optimization(a - aHi);\n return vec2f(aHi, aLo);\n}\n\nfn split2(a: vec2f) -> vec2f {\n var b = split(a.x);\n b.y = b.y + a.y;\n return b;\n}\n\nfn quickTwoSum(a: f32, b: f32) -> vec2f {\n#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND\n let sum = prevent_fp64_optimization((a + b) * fp64arithmetic.ONE);\n let err = prevent_fp64_optimization(b - (sum - a) * fp64arithmetic.ONE);\n#else\n let sum = prevent_fp64_optimization(a + b);\n let err = prevent_fp64_optimization(b - (sum - a));\n#endif\n return vec2f(sum, err);\n}\n\nfn twoSum(a: f32, b: f32) -> vec2f {\n let s = prevent_fp64_optimization(a + b);\n#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND\n let v = prevent_fp64_optimization((s * fp64arithmetic.ONE - a) * fp64arithmetic.ONE);\n let err =\n prevent_fp64_optimization((a - (s - v) * fp64arithmetic.ONE) *\n fp64arithmetic.ONE *\n fp64arithmetic.ONE *\n fp64arithmetic.ONE) +\n prevent_fp64_optimization(b - v);\n#else\n let v = prevent_fp64_optimization(s - a);\n let err = prevent_fp64_optimization(a - (s - v)) + prevent_fp64_optimization(b - v);\n#endif\n return vec2f(s, err);\n}\n\nfn twoSub(a: f32, b: f32) -> vec2f {\n let s = prevent_fp64_optimization(a - b);\n#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND\n let v = prevent_fp64_optimization((s * fp64arithmetic.ONE - a) * fp64arithmetic.ONE);\n let err =\n prevent_fp64_optimization((a - (s - v) * fp64arithmetic.ONE) *\n fp64arithmetic.ONE *\n fp64arithmetic.ONE *\n fp64arithmetic.ONE) -\n prevent_fp64_optimization(b + v);\n#else\n let v = prevent_fp64_optimization(s - a);\n let err = prevent_fp64_optimization(a - (s - v)) - prevent_fp64_optimization(b + v);\n#endif\n return vec2f(s, err);\n}\n\nfn twoSqr(a: f32) -> vec2f {\n let prod = prevent_fp64_optimization(a * a);\n let aFp64 = split(a);\n let highProduct = prevent_fp64_optimization(aFp64.x * aFp64.x);\n let crossProduct = prevent_fp64_optimization(2.0 * aFp64.x * aFp64.y);\n let lowProduct = prevent_fp64_optimization(aFp64.y * aFp64.y);\n#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND\n let err =\n (prevent_fp64_optimization(highProduct - prod) * fp64arithmetic.ONE +\n crossProduct * fp64arithmetic.ONE * fp64arithmetic.ONE) +\n lowProduct * fp64arithmetic.ONE * fp64arithmetic.ONE * fp64arithmetic.ONE;\n#else\n let err = ((prevent_fp64_optimization(highProduct - prod) + crossProduct) + lowProduct);\n#endif\n return vec2f(prod, err);\n}\n\nfn twoProd(a: f32, b: f32) -> vec2f {\n let prod = prevent_fp64_optimization(a * b);\n let aFp64 = split(a);\n let bFp64 = split(b);\n let highProduct = prevent_fp64_optimization(aFp64.x * bFp64.x);\n let crossProduct1 = prevent_fp64_optimization(aFp64.x * bFp64.y);\n let crossProduct2 = prevent_fp64_optimization(aFp64.y * bFp64.x);\n let lowProduct = prevent_fp64_optimization(aFp64.y * bFp64.y);\n#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND\n let err1 = (highProduct - prod) * fp64arithmetic.ONE;\n let err2 = crossProduct1 * fp64arithmetic.ONE * fp64arithmetic.ONE;\n let err3 = crossProduct2 * fp64arithmetic.ONE * fp64arithmetic.ONE * fp64arithmetic.ONE;\n let err4 =\n lowProduct *\n fp64arithmetic.ONE *\n fp64arithmetic.ONE *\n fp64arithmetic.ONE *\n fp64arithmetic.ONE;\n#else\n let err1 = highProduct - prod;\n let err2 = crossProduct1;\n let err3 = crossProduct2;\n let err4 = lowProduct;\n#endif\n let err12InputA = prevent_fp64_optimization(err1);\n let err12InputB = prevent_fp64_optimization(err2);\n let err12 = prevent_fp64_optimization(err12InputA + err12InputB);\n let err123InputA = prevent_fp64_optimization(err12);\n let err123InputB = prevent_fp64_optimization(err3);\n let err123 = prevent_fp64_optimization(err123InputA + err123InputB);\n let err1234InputA = prevent_fp64_optimization(err123);\n let err1234InputB = prevent_fp64_optimization(err4);\n let err = prevent_fp64_optimization(err1234InputA + err1234InputB);\n return vec2f(prod, err);\n}\n\nfn sum_fp64(a: vec2f, b: vec2f) -> vec2f {\n var s = twoSum(a.x, b.x);\n let t = twoSum(a.y, b.y);\n s.y = prevent_fp64_optimization(s.y + t.x);\n s = quickTwoSum(s.x, s.y);\n s.y = prevent_fp64_optimization(s.y + t.y);\n s = quickTwoSum(s.x, s.y);\n return s;\n}\n\nfn sub_fp64(a: vec2f, b: vec2f) -> vec2f {\n var s = twoSub(a.x, b.x);\n let t = twoSub(a.y, b.y);\n s.y = prevent_fp64_optimization(s.y + t.x);\n s = quickTwoSum(s.x, s.y);\n s.y = prevent_fp64_optimization(s.y + t.y);\n s = quickTwoSum(s.x, s.y);\n return s;\n}\n\nfn mul_fp64(a: vec2f, b: vec2f) -> vec2f {\n var prod = twoProd(a.x, b.x);\n let crossProduct1 = prevent_fp64_optimization(a.x * b.y);\n prod.y = prevent_fp64_optimization(prod.y + crossProduct1);\n#ifdef LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND\n prod = split2(prod);\n#endif\n prod = quickTwoSum(prod.x, prod.y);\n let crossProduct2 = prevent_fp64_optimization(a.y * b.x);\n prod.y = prevent_fp64_optimization(prod.y + crossProduct2);\n#ifdef LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND\n prod = split2(prod);\n#endif\n prod = quickTwoSum(prod.x, prod.y);\n return prod;\n}\n\nfn div_fp64(a: vec2f, b: vec2f) -> vec2f {\n let xn = prevent_fp64_optimization(1.0 / b.x);\n let yn = mul_fp64(a, vec2f(xn, fp64_runtime_zero()));\n let diff = prevent_fp64_optimization(sub_fp64(a, mul_fp64(b, yn)).x);\n let prod = twoProd(xn, diff);\n return sum_fp64(yn, prod);\n}\n\nfn sqrt_fp64(a: vec2f) -> vec2f {\n if (a.x == 0.0 && a.y == 0.0) {\n return vec2f(0.0, 0.0);\n }\n if (a.x < 0.0) {\n let nanValue = fp64_nan(a.x);\n return vec2f(nanValue, nanValue);\n }\n\n let x = prevent_fp64_optimization(1.0 / sqrt(a.x));\n let yn = prevent_fp64_optimization(a.x * x);\n#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND\n let ynSqr = twoSqr(yn) * fp64arithmetic.ONE;\n#else\n let ynSqr = twoSqr(yn);\n#endif\n let diff = prevent_fp64_optimization(sub_fp64(a, ynSqr).x);\n let prod = twoProd(prevent_fp64_optimization(x * 0.5), diff);\n#ifdef LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND\n return sum_fp64(split(yn), prod);\n#else\n return sum_fp64(vec2f(yn, 0.0), prod);\n#endif\n}\n`;\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {ShaderModule} from '../../../lib/shader-module/shader-module';\n\nimport {fp64ify, fp64LowPart, fp64ifyMatrix4} from '../../../modules/math/fp64/fp64-utils';\nimport {fp64arithmeticShader} from './fp64-arithmetic-glsl';\nimport {fp64arithmeticWGSL} from './fp64-arithmetic-wgsl';\nimport {fp64functionShader} from './fp64-functions-glsl';\n\ntype FP64Props = {};\ntype FP64Uniforms = {ONE: number; SPLIT: number};\ntype FP64Bindings = {};\n\ntype FP64Utilities = {\n fp64ify: typeof fp64ify;\n fp64LowPart: typeof fp64LowPart;\n fp64ifyMatrix4: typeof fp64ifyMatrix4;\n};\n\nconst defaultUniforms: FP64Uniforms = {\n // Used in LUMA_FP64_CODE_ELIMINATION_WORKAROUND\n ONE: 1.0,\n // Runtime split factor for Dekker splitting. Keeping this as a uniform helps\n // prevent aggressive constant folding in shader compilers.\n SPLIT: 4097.0\n};\n\n/**\n * 64bit arithmetic: add, sub, mul, div (small subset of fp64 module)\n */\nexport const fp64arithmetic: ShaderModule & FP64Utilities = {\n name: 'fp64arithmetic',\n source: fp64arithmeticWGSL,\n fs: fp64arithmeticShader,\n vs: fp64arithmeticShader,\n defaultUniforms,\n uniformTypes: {ONE: 'f32', SPLIT: 'f32'},\n\n // Additional Functions\n fp64ify,\n fp64LowPart,\n fp64ifyMatrix4\n};\n\n/**\n * Full 64 bit math library\n */\nexport const fp64: ShaderModule<{}> & FP64Utilities = {\n name: 'fp64',\n vs: fp64functionShader,\n dependencies: [fp64arithmetic],\n\n // Additional Functions\n fp64ify,\n fp64LowPart,\n fp64ifyMatrix4\n};\n\nexport {fp64ify, fp64LowPart, fp64ifyMatrix4};\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {ShaderModule} from '../../../lib/shader-module/shader-module';\nimport type {NumberArray3, NumberArray4} from '@math.gl/core';\nimport {normalizeByteColor4, resolveUseByteColors} from '../../../lib/color/normalize-byte-colors';\n\n// cyan color\nconst DEFAULT_HIGHLIGHT_COLOR: NumberArray4 = [0, 1, 1, 1];\n\n/**\n * Props for the picking module, which depending on mode renders picking colors or highlighted item.\n * When active, renders picking colors, assumed to be rendered to off-screen \"picking\" buffer.\n * When inactive, renders normal colors, with the exception of selected object which is rendered with highlight\n */\nexport type PickingProps = {\n /** Are we picking? I.e. rendering picking colors? */\n isActive?: boolean;\n /** Set to true when picking an attribute value instead of object index */\n isAttribute?: boolean;\n /** Set to a picking color to visually highlight that item, or `null` to explicitly clear **/\n highlightedObjectColor?: NumberArray3 | null;\n /** Color of visual highlight of \"selected\" item */\n highlightColor?: NumberArray3 | NumberArray4;\n /** Interpret highlight colors as byte-style 0-255 values. */\n useByteColors?: boolean;\n};\n\n/**\n * Uniforms for the picking module, which renders picking colors and highlighted item.\n * When active, renders picking colors, assumed to be rendered to off-screen \"picking\" buffer.\n * When inactive, renders normal colors, with the exception of selected object which is rendered with highlight\n */\nexport type PickingUniforms = {\n /**\n * When true, renders picking colors. Set when rendering to off-screen \"picking\" buffer.\n * When false, renders normal colors, with the exception of selected object which is rendered with highlight\n */\n isActive?: boolean;\n /** Set to true when picking an attribute value instead of object index */\n isAttribute?: boolean;\n /** Interpret highlight colors as byte-style 0-255 values. */\n useByteColors?: boolean;\n /** Do we have a highlighted item? */\n isHighlightActive?: boolean;\n /** Set to a picking color to visually highlight that item */\n highlightedObjectColor?: NumberArray3;\n /** Color of visual highlight of \"selected\" item */\n highlightColor?: NumberArray4;\n};\n\nconst vs = /* glsl */ `\\\nlayout(std140) uniform pickingUniforms {\n float isActive;\n float isAttribute;\n float isHighlightActive;\n float useByteColors;\n vec3 highlightedObjectColor;\n vec4 highlightColor;\n} picking;\n\nout vec4 picking_vRGBcolor_Avalid;\n\n// Normalize unsigned byte color to 0-1 range\nvec3 picking_normalizeColor(vec3 color) {\n return picking.useByteColors > 0.5 ? color / 255.0 : color;\n}\n\n// Normalize unsigned byte color to 0-1 range\nvec4 picking_normalizeColor(vec4 color) {\n return picking.useByteColors > 0.5 ? color / 255.0 : color;\n}\n\nbool picking_isColorZero(vec3 color) {\n return dot(color, vec3(1.0)) < 0.00001;\n}\n\nbool picking_isColorValid(vec3 color) {\n return dot(color, vec3(1.0)) > 0.00001;\n}\n\n// Check if this vertex is highlighted \nbool isVertexHighlighted(vec3 vertexColor) {\n vec3 highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor);\n return\n bool(picking.isHighlightActive) && picking_isColorZero(abs(vertexColor - highlightedObjectColor));\n}\n\n// Set the current picking color\nvoid picking_setPickingColor(vec3 pickingColor) {\n pickingColor = picking_normalizeColor(pickingColor);\n\n if (bool(picking.isActive)) {\n // Use alpha as the validity flag. If pickingColor is [0, 0, 0] fragment is non-pickable\n picking_vRGBcolor_Avalid.a = float(picking_isColorValid(pickingColor));\n\n if (!bool(picking.isAttribute)) {\n // Stores the picking color so that the fragment shader can render it during picking\n picking_vRGBcolor_Avalid.rgb = pickingColor;\n }\n } else {\n // Do the comparison with selected item color in vertex shader as it should mean fewer compares\n picking_vRGBcolor_Avalid.a = float(isVertexHighlighted(pickingColor));\n }\n}\n\nvoid picking_setPickingAttribute(float value) {\n if (bool(picking.isAttribute)) {\n picking_vRGBcolor_Avalid.r = value;\n }\n}\n\nvoid picking_setPickingAttribute(vec2 value) {\n if (bool(picking.isAttribute)) {\n picking_vRGBcolor_Avalid.rg = value;\n }\n}\n\nvoid picking_setPickingAttribute(vec3 value) {\n if (bool(picking.isAttribute)) {\n picking_vRGBcolor_Avalid.rgb = value;\n }\n}\n`;\n\nconst fs = /* glsl */ `\\\nlayout(std140) uniform pickingUniforms {\n float isActive;\n float isAttribute;\n float isHighlightActive;\n float useByteColors;\n vec3 highlightedObjectColor;\n vec4 highlightColor;\n} picking;\n\nin vec4 picking_vRGBcolor_Avalid;\n\n/*\n * Returns highlight color if this item is selected.\n */\nvec4 picking_filterHighlightColor(vec4 color) {\n // If we are still picking, we don't highlight\n if (picking.isActive > 0.5) {\n return color;\n }\n\n bool selected = bool(picking_vRGBcolor_Avalid.a);\n\n if (selected) {\n // Blend in highlight color based on its alpha value\n float highLightAlpha = picking.highlightColor.a;\n float blendedAlpha = highLightAlpha + color.a * (1.0 - highLightAlpha);\n float highLightRatio = highLightAlpha / blendedAlpha;\n\n vec3 blendedRGB = mix(color.rgb, picking.highlightColor.rgb, highLightRatio);\n return vec4(blendedRGB, blendedAlpha);\n } else {\n return color;\n }\n}\n\n/*\n * Returns picking color if picking enabled else unmodified argument.\n */\nvec4 picking_filterPickingColor(vec4 color) {\n if (bool(picking.isActive)) {\n if (picking_vRGBcolor_Avalid.a == 0.0) {\n discard;\n }\n return picking_vRGBcolor_Avalid;\n }\n return color;\n}\n\n/*\n * Returns picking color if picking is enabled if not\n * highlight color if this item is selected, otherwise unmodified argument.\n */\nvec4 picking_filterColor(vec4 color) {\n vec4 highlightColor = picking_filterHighlightColor(color);\n return picking_filterPickingColor(highlightColor);\n}\n`;\n\n/**\n * Deprecated legacy picking module retained for compatibility with existing\n * shadertools users such as deck.gl. Keep the shader contract stable.\n *\n * Provides support for color-coding-based picking and highlighting.\n * In particular, supports picking a specific instance in an instanced\n * draw call and highlighting an instance based on its picking color,\n * and correspondingly, supports picking and highlighting groups of\n * primitives with the same picking color in non-instanced draw-calls\n */\nexport const picking = {\n props: {} as PickingProps,\n uniforms: {} as PickingUniforms,\n\n name: 'picking',\n\n uniformTypes: {\n isActive: 'f32',\n isAttribute: 'f32',\n isHighlightActive: 'f32',\n useByteColors: 'f32',\n highlightedObjectColor: 'vec3',\n highlightColor: 'vec4'\n },\n defaultUniforms: {\n isActive: false,\n isAttribute: false,\n isHighlightActive: false,\n useByteColors: true,\n highlightedObjectColor: [0, 0, 0],\n highlightColor: DEFAULT_HIGHLIGHT_COLOR\n },\n\n vs,\n fs,\n getUniforms\n} as const satisfies ShaderModule;\n\nfunction getUniforms(opts: PickingProps = {}, prevUniforms?: PickingUniforms): PickingUniforms {\n const uniforms = {} as PickingUniforms;\n const useByteColors = resolveUseByteColors(opts.useByteColors, true);\n\n if (opts.highlightedObjectColor === undefined) {\n // Unless highlightedObjectColor explicitly null or set, do not update state\n } else if (opts.highlightedObjectColor === null) {\n uniforms.isHighlightActive = false;\n } else {\n uniforms.isHighlightActive = true;\n const highlightedObjectColor = opts.highlightedObjectColor.slice(0, 3) as NumberArray3;\n uniforms.highlightedObjectColor = highlightedObjectColor;\n }\n\n if (opts.highlightColor) {\n uniforms.highlightColor = normalizeByteColor4(opts.highlightColor, useByteColors);\n }\n\n if (opts.isActive !== undefined) {\n uniforms.isActive = Boolean(opts.isActive);\n uniforms.isAttribute = Boolean(opts.isAttribute);\n }\n\n if (opts.useByteColors !== undefined) {\n uniforms.useByteColors = Boolean(opts.useByteColors);\n }\n\n return uniforms;\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ShaderModule} from '@luma.gl/shadertools';\nimport type {LayerProps} from '../../types/layer-props';\n\nconst uniformBlockWGSL = /* wgsl */ `\\\nstruct LayerUniforms {\n opacity: f32,\n};\n\n@group(0) @binding(auto)\nvar layer: LayerUniforms;\n`;\n\nconst uniformBlock = `\\\nlayout(std140) uniform layerUniforms {\n uniform float opacity;\n} layer;\n`;\n\nexport type LayerUniforms = {\n opacity?: number;\n};\n\nexport const layerUniforms = {\n name: 'layer',\n source: uniformBlockWGSL,\n vs: uniformBlock,\n fs: uniformBlock,\n getUniforms: (props: Partial) => {\n return {\n // apply gamma to opacity to make it visually \"linear\"\n // TODO - v10: use raw opacity?\n opacity: Math.pow(props.opacity!, 1 / 2.2)\n };\n },\n uniformTypes: {\n opacity: 'f32'\n }\n} as const satisfies ShaderModule;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {ShaderModule} from '@luma.gl/shadertools';\nimport {LayerProps} from '../../types/layer-props';\n\nconst colorWGSL = /* WGSL */ `\n\n@must_use\nfn deckgl_premultiplied_alpha(fragColor: vec4) -> vec4 {\n return vec4(fragColor.rgb * fragColor.a, fragColor.a); \n};\n`;\n\nexport type ColorProps = {\n /**\n * Opacity of the layer, between 0 and 1. Default 1.\n */\n opacity?: number;\n};\n\nexport type ColorUniforms = {\n opacity?: number;\n};\n\nexport default {\n name: 'color',\n dependencies: [],\n source: colorWGSL,\n getUniforms: (_props: Partial) => {\n // TODO (kaapp) Handle layer opacity\n // apply gamma to opacity to make it visually \"linear\"\n // TODO - v10: use raw opacity?\n // opacity: Math.pow(props.opacity!, 1 / 2.2)\n return {};\n }\n // @ts-ignore TODO v9.1\n} as const satisfies ShaderModule;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ShaderModule} from '@luma.gl/shadertools';\n\nconst source = /* wgsl */ `\\\nconst SMOOTH_EDGE_RADIUS: f32 = 0.5;\n\nstruct VertexGeometry {\n position: vec4,\n worldPosition: vec3,\n worldPositionAlt: vec3,\n normal: vec3,\n uv: vec2,\n pickingColor: vec3,\n};\n\nvar geometry_: VertexGeometry = VertexGeometry(\n vec4(0.0, 0.0, 1.0, 0.0),\n vec3(0.0, 0.0, 0.0),\n vec3(0.0, 0.0, 0.0),\n vec3(0.0, 0.0, 0.0),\n vec2(0.0, 0.0),\n vec3(0.0, 0.0, 0.0)\n);\n\nstruct FragmentGeometry {\n uv: vec2,\n};\n\nvar fragmentGeometry: FragmentGeometry;\n\nfn smoothedge(edge: f32, x: f32) -> f32 {\n return smoothstep(edge - SMOOTH_EDGE_RADIUS, edge + SMOOTH_EDGE_RADIUS, x);\n}\n`;\n\nconst defines = '#define SMOOTH_EDGE_RADIUS 0.5';\n\nconst vs = /* glsl */ `\\\n${defines}\n\nstruct VertexGeometry {\n vec4 position;\n vec3 worldPosition;\n vec3 worldPositionAlt;\n vec3 normal;\n vec2 uv;\n vec3 pickingColor;\n} geometry = VertexGeometry(\n vec4(0.0, 0.0, 1.0, 0.0),\n vec3(0.0),\n vec3(0.0),\n vec3(0.0),\n vec2(0.0),\n vec3(0.0)\n);\n`;\n\nconst fs = /* glsl */ `\\\n${defines}\n\nstruct FragmentGeometry {\n vec2 uv;\n} geometry;\n\nfloat smoothedge(float edge, float x) {\n return smoothstep(edge - SMOOTH_EDGE_RADIUS, edge + SMOOTH_EDGE_RADIUS, x);\n}\n`;\n\nexport default {\n name: 'geometry',\n source,\n vs,\n fs\n} as const satisfies ShaderModule;\n","export const MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;\n\nexport const COMPUTE_INTERVAL = 25;\n\nexport enum InputEvent {\n Start = 1,\n Move = 2,\n End = 4,\n Cancel = 8\n}\n\nexport enum InputDirection {\n None = 0,\n Left = 1,\n Right = 2,\n Up = 4,\n Down = 8,\n Horizontal = 3,\n Vertical = 12,\n All = 15\n}\n","export enum RecognizerState {\n Possible = 1,\n Began = 2,\n Changed = 4,\n Ended = 8,\n Recognized = 8, // eslint-disable-line\n Cancelled = 16,\n Failed = 32\n}\n","// magical touchAction value\nexport const TOUCH_ACTION_COMPUTE = 'compute';\nexport const TOUCH_ACTION_AUTO = 'auto';\nexport const TOUCH_ACTION_MANIPULATION = 'manipulation'; // not implemented\nexport const TOUCH_ACTION_NONE = 'none';\nexport const TOUCH_ACTION_PAN_X = 'pan-x';\nexport const TOUCH_ACTION_PAN_Y = 'pan-y';\n","import {\n TOUCH_ACTION_NONE,\n TOUCH_ACTION_PAN_X,\n TOUCH_ACTION_PAN_Y,\n TOUCH_ACTION_MANIPULATION,\n TOUCH_ACTION_AUTO\n} from './touchaction-Consts';\n\n/**\n * when the touchActions are collected they are not a valid value, so we need to clean things up. *\n * @returns valid touchAction\n */\nexport default function cleanTouchActions(actions: string): string {\n // none\n if (actions.includes(TOUCH_ACTION_NONE)) {\n return TOUCH_ACTION_NONE;\n }\n\n const hasPanX = actions.includes(TOUCH_ACTION_PAN_X);\n const hasPanY = actions.includes(TOUCH_ACTION_PAN_Y);\n\n // if both pan-x and pan-y are set (different recognizers\n // for different directions, e.g. horizontal pan but vertical swipe?)\n // we need none (as otherwise with pan-x pan-y combined none of these\n // recognizers will work, since the browser would handle all panning\n if (hasPanX && hasPanY) {\n return TOUCH_ACTION_NONE;\n }\n\n // pan-x OR pan-y\n if (hasPanX || hasPanY) {\n return hasPanX ? TOUCH_ACTION_PAN_X : TOUCH_ACTION_PAN_Y;\n }\n\n // manipulation\n if (actions.includes(TOUCH_ACTION_MANIPULATION)) {\n return TOUCH_ACTION_MANIPULATION;\n }\n\n return TOUCH_ACTION_AUTO;\n}\n","import {TOUCH_ACTION_COMPUTE} from './touchaction-Consts';\nimport cleanTouchActions from './clean-touch-actions';\n\nimport type {Manager} from '../manager';\n\n/**\n * Touch Action\n * sets the touchAction property or uses the js alternative\n */\nexport class TouchAction {\n manager: Manager;\n actions: string = '';\n\n constructor(manager: Manager, value: string) {\n this.manager = manager;\n this.set(value);\n }\n\n /**\n * set the touchAction value on the element or enable the polyfill\n */\n set(value: string) {\n // find out the touch-action by the event handlers\n if (value === TOUCH_ACTION_COMPUTE) {\n value = this.compute();\n }\n\n if (this.manager.element) {\n this.manager.element.style.touchAction = value;\n this.actions = value;\n }\n }\n\n /**\n * just re-set the touchAction value\n */\n update() {\n this.set(this.manager.options.touchAction);\n }\n\n /**\n * compute the value for the touchAction property based on the recognizer's settings\n */\n compute(): string {\n let actions: string[] = [];\n for (const recognizer of this.manager.recognizers) {\n if (recognizer.options.enable) {\n actions = actions.concat(recognizer.getTouchAction());\n }\n }\n return cleanTouchActions(actions.join(' '));\n }\n}\n","/**\n * split string on whitespace\n * @returns {Array} words\n */\nexport function splitStr(str: string): string[] {\n return str.trim().split(/\\s+/g);\n}\n","import {splitStr} from './split-str';\n\n/**\n * addEventListener with multiple events at once\n */\nexport function addEventListeners(\n target: EventTarget | null,\n types: string,\n handler: EventListener\n) {\n if (!target) {\n return;\n }\n for (const type of splitStr(types)) {\n target.addEventListener(type, handler, false);\n }\n}\n\n/**\n * removeEventListener with multiple events at once\n */\nexport function removeEventListeners(\n target: EventTarget | null,\n types: string,\n handler: EventListener\n) {\n if (!target) {\n return;\n }\n for (const type of splitStr(types)) {\n target.removeEventListener(type, handler, false);\n }\n}\n","/**\n * get the window object of an element\n */\nexport function getWindowForElement(element: HTMLElement): Window | null {\n const doc = element.ownerDocument || (element as unknown as Document);\n return doc.defaultView;\n}\n","/**\n * find if a node is in the given parent\n */\nexport default function hasParent(node: HTMLElement, parent: HTMLElement): boolean {\n let ancestor: Node | null = node;\n while (ancestor) {\n if (ancestor === parent) {\n return true;\n }\n ancestor = ancestor.parentNode;\n }\n return false;\n}\n","import type {Point, PointerEventLike} from './types';\n\n/**\n * get the center of all the pointers\n */\nexport function getCenter(pointers: PointerEventLike[]): Point {\n const pointersLength = pointers.length;\n\n // no need to loop when only one touch\n if (pointersLength === 1) {\n return {\n x: Math.round(pointers[0].clientX),\n y: Math.round(pointers[0].clientY)\n };\n }\n\n let x = 0;\n let y = 0;\n let i = 0;\n while (i < pointersLength) {\n x += pointers[i].clientX;\n y += pointers[i].clientY;\n i++;\n }\n\n return {\n x: Math.round(x / pointersLength),\n y: Math.round(y / pointersLength)\n };\n}\n","import {getCenter} from './get-center';\nimport type {RawInput, PointerEventLike, SimpleInput} from './types';\n\n/**\n * create a simple clone from the input used for storage of firstInput and firstMultiple\n */\nexport function simpleCloneInputData(input: RawInput): SimpleInput {\n // make a simple copy of the pointers because we will get a reference if we don't\n const pointers: PointerEventLike[] = [];\n let i = 0;\n while (i < input.pointers.length) {\n pointers[i] = {\n clientX: Math.round(input.pointers[i].clientX),\n clientY: Math.round(input.pointers[i].clientY)\n };\n i++;\n }\n\n return {\n timeStamp: Date.now(),\n pointers,\n center: getCenter(pointers),\n deltaX: input.deltaX,\n deltaY: input.deltaY\n };\n}\n","import type {Point, PointerEventLike} from './types';\n\n/**\n * calculate the absolute distance between two points\n * @returns distance\n */\nexport function getPointDistance(p1: Point, p2: Point): number {\n const x = p2.x - p1.x;\n const y = p2.y - p1.y;\n return Math.sqrt(x * x + y * y);\n}\n\n/**\n * calculate the absolute distance between two pointer events\n * @returns distance\n */\nexport function getEventDistance(p1: PointerEventLike, p2: PointerEventLike): number {\n const x = p2.clientX - p1.clientX;\n const y = p2.clientY - p1.clientY;\n return Math.sqrt(x * x + y * y);\n}\n","import {Point, PointerEventLike} from './types';\n\n/**\n * calculate the angle between two coordinates\n * @returns angle in degrees\n */\nexport function getPointAngle(p1: Point, p2: Point) {\n const x: number = p2.x - p1.x;\n const y: number = p2.y - p1.y;\n return (Math.atan2(y, x) * 180) / Math.PI;\n}\n\n/**\n * calculate the angle between two pointer events\n * @returns angle in degrees\n */\nexport function getEventAngle(p1: PointerEventLike, p2: PointerEventLike) {\n const x: number = p2.clientX - p1.clientX;\n const y: number = p2.clientY - p1.clientY;\n return (Math.atan2(y, x) * 180) / Math.PI;\n}\n","import {InputDirection} from './input-consts';\n\n/**\n * get the direction between two points\n * @returns direction\n */\nexport function getDirection(dx: number, dy: number): InputDirection {\n if (dx === dy) {\n return InputDirection.None;\n }\n\n if (Math.abs(dx) >= Math.abs(dy)) {\n return dx < 0 ? InputDirection.Left : InputDirection.Right;\n }\n return dy < 0 ? InputDirection.Up : InputDirection.Down;\n}\n","import {InputEvent} from './input-consts';\nimport type {RawInput, Session} from './types';\n\n/** Populates input.deltaX, input.deltaY */\nexport function computeDeltaXY(\n session: Session,\n input: RawInput\n): {\n deltaX: number;\n deltaY: number;\n} {\n // getCenter is called before computeDeltaXY\n const center = input.center!;\n let offset = session.offsetDelta;\n let prevDelta = session.prevDelta;\n const prevInput = session.prevInput;\n\n if (input.eventType === InputEvent.Start || prevInput?.eventType === InputEvent.End) {\n prevDelta = session.prevDelta = {\n x: prevInput?.deltaX || 0,\n y: prevInput?.deltaY || 0\n };\n\n offset = session.offsetDelta = {\n x: center.x,\n y: center.y\n };\n }\n\n return {\n deltaX: prevDelta!.x + (center.x - offset!.x),\n deltaY: prevDelta!.y + (center.y - offset!.y)\n };\n}\n","import type {Vector} from './types';\n\n/**\n * calculate the velocity between two points. unit is in px per ms.\n */\nexport function getVelocity(deltaTime: number, x: number, y: number): Vector {\n return {\n x: x / deltaTime || 0,\n y: y / deltaTime || 0\n };\n}\n","import {getEventDistance} from './get-distance';\nimport type {PointerEventLike} from './types';\n\n/**\n * calculate the scale factor between two pointersets\n * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out\n */\nexport function getScale(start: PointerEventLike[], end: PointerEventLike[]): number {\n return getEventDistance(end[0], end[1]) / getEventDistance(start[0], start[1]);\n}\n","import {getEventAngle} from './get-angle';\nimport {PointerEventLike} from './types';\n\n/**\n * calculate the rotation degrees between two pointer sets\n * @returns rotation in degrees\n */\nexport function getRotation(start: PointerEventLike[], end: PointerEventLike[]): number {\n return getEventAngle(end[1], end[0]) - getEventAngle(start[1], start[0]);\n}\n","import {InputEvent, COMPUTE_INTERVAL} from './input-consts';\nimport {getVelocity} from './get-velocity';\nimport {getDirection} from './get-direction';\n\nimport type {Session, HammerInput} from './types';\n\n/**\n * velocity is calculated every x ms\n */\nexport function computeIntervalInputData(session: Session, input: HammerInput) {\n const last = session.lastInterval || input;\n const deltaTime = input.timeStamp - last.timeStamp;\n let velocity;\n let velocityX;\n let velocityY;\n let direction;\n\n if (\n input.eventType !== InputEvent.Cancel &&\n (deltaTime > COMPUTE_INTERVAL || last.velocity === undefined)\n ) {\n const deltaX = input.deltaX - last.deltaX;\n const deltaY = input.deltaY - last.deltaY;\n\n const v = getVelocity(deltaTime, deltaX, deltaY);\n velocityX = v.x;\n velocityY = v.y;\n velocity = Math.abs(v.x) > Math.abs(v.y) ? v.x : v.y;\n direction = getDirection(deltaX, deltaY);\n\n session.lastInterval = input;\n } else {\n // use latest velocity info if it doesn't overtake a minimum period\n velocity = last.velocity;\n velocityX = last.velocityX;\n velocityY = last.velocityY;\n direction = last.direction;\n }\n\n input.velocity = velocity;\n input.velocityX = velocityX;\n input.velocityY = velocityY;\n input.direction = direction;\n}\n","import hasParent from '../utils/has-parent';\nimport {simpleCloneInputData} from './simple-clone-input-data';\nimport {getCenter} from './get-center';\nimport {getPointDistance} from './get-distance';\nimport {getPointAngle} from './get-angle';\nimport {getDirection} from './get-direction';\nimport {computeDeltaXY} from './get-delta-xy';\nimport {getVelocity} from './get-velocity';\nimport {getScale} from './get-scale';\nimport {getRotation} from './get-rotation';\nimport {computeIntervalInputData} from './compute-interval-input-data';\n\nimport type {Manager} from '../manager';\nimport type {RawInput, HammerInput} from './types';\n\n/**\n * extend the data with some usable properties like scale, rotate, velocity etc\n */\nexport function computeInputData(manager: Manager, input: RawInput): HammerInput {\n const {session} = manager;\n const {pointers} = input;\n const {length: pointersLength} = pointers;\n\n // store the first input to calculate the distance and direction\n if (!session.firstInput) {\n session.firstInput = simpleCloneInputData(input);\n }\n\n // to compute scale and rotation we need to store the multiple touches\n if (pointersLength > 1 && !session.firstMultiple) {\n session.firstMultiple = simpleCloneInputData(input);\n } else if (pointersLength === 1) {\n session.firstMultiple = false;\n }\n\n const {firstInput, firstMultiple} = session;\n const offsetCenter = firstMultiple ? firstMultiple.center : firstInput.center;\n\n const center = (input.center = getCenter(pointers));\n input.timeStamp = Date.now();\n input.deltaTime = input.timeStamp - firstInput.timeStamp;\n\n input.angle = getPointAngle(offsetCenter, center);\n input.distance = getPointDistance(offsetCenter, center);\n\n const {deltaX, deltaY} = computeDeltaXY(session, input);\n input.deltaX = deltaX;\n input.deltaY = deltaY;\n input.offsetDirection = getDirection(input.deltaX, input.deltaY);\n\n const overallVelocity = getVelocity(input.deltaTime, input.deltaX, input.deltaY);\n input.overallVelocityX = overallVelocity.x;\n input.overallVelocityY = overallVelocity.y;\n input.overallVelocity =\n Math.abs(overallVelocity.x) > Math.abs(overallVelocity.y)\n ? overallVelocity.x\n : overallVelocity.y;\n\n input.scale = firstMultiple ? getScale(firstMultiple.pointers, pointers) : 1;\n input.rotation = firstMultiple ? getRotation(firstMultiple.pointers, pointers) : 0;\n\n input.maxPointers = !session.prevInput\n ? input.pointers.length\n : input.pointers.length > session.prevInput.maxPointers\n ? input.pointers.length\n : session.prevInput.maxPointers;\n\n // find the correct target\n let target = manager.element!;\n if (hasParent(input.srcEvent.target as HTMLElement, target)) {\n target = input.srcEvent.target as HTMLElement;\n }\n input.target = target;\n\n computeIntervalInputData(session, input as HammerInput);\n\n // All the optional fields have been populated\n return input as HammerInput;\n}\n","import {InputEvent} from './input-consts';\nimport {computeInputData} from './compute-input-data';\n\nimport type {Manager} from '../manager';\nimport type {RawInput} from './types';\n\n/**\n * handle input events\n */\nexport function inputHandler(manager: Manager, eventType: InputEvent, input: RawInput) {\n const pointersLen = input.pointers.length;\n const changedPointersLen = input.changedPointers.length;\n const isFirst = eventType & InputEvent.Start && pointersLen - changedPointersLen === 0;\n const isFinal =\n eventType & (InputEvent.End | InputEvent.Cancel) && pointersLen - changedPointersLen === 0;\n\n input.isFirst = Boolean(isFirst);\n input.isFinal = Boolean(isFinal);\n\n if (isFirst) {\n manager.session = {};\n }\n\n // source event is the normalized value of the domEvents\n // like 'touchstart, mouseup, pointerdown'\n input.eventType = eventType;\n\n // compute scale, rotation etc\n const processedInput = computeInputData(manager, input);\n\n // emit secret event\n manager.emit('hammer.input', processedInput);\n\n manager.recognize(processedInput);\n manager.session.prevInput = processedInput;\n}\n","import {addEventListeners, removeEventListeners} from '../utils/event-listeners';\nimport {getWindowForElement} from '../utils/get-window-for-element';\nimport {inputHandler} from './input-handler';\n\nimport {InputEvent} from './input-consts';\nimport type {RawInput} from './types';\nimport type {Manager} from '../manager';\n\n/**\n * create new input type manager\n */\nexport abstract class Input {\n manager: Manager;\n element: HTMLElement;\n target: EventTarget;\n\n evEl: string = '';\n evWin: string = '';\n evTarget: string = '';\n\n constructor(manager: Manager) {\n this.manager = manager;\n this.element = manager.element!;\n this.target = manager.options.inputTarget || manager.element!;\n }\n\n /** smaller wrapper around the handler, for the scope and the enabled state of the manager,\n * so when disabled the input events are completely bypassed.\n */\n protected domHandler = (ev: Event) => {\n if (this.manager.options.enable) {\n this.handler(ev);\n }\n };\n\n protected callback(eventType: InputEvent, input: RawInput) {\n inputHandler(this.manager, eventType, input);\n }\n\n /**\n * should handle the inputEvent data and trigger the callback\n */\n abstract handler(ev: Event): void;\n\n // eslint-disable @typescript-eslint/unbound-method\n /**\n * bind the events\n */\n init() {\n addEventListeners(this.element, this.evEl, this.domHandler);\n addEventListeners(this.target, this.evTarget, this.domHandler);\n addEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);\n }\n\n /**\n * unbind the events\n */\n destroy() {\n removeEventListeners(this.element, this.evEl, this.domHandler);\n removeEventListeners(this.target, this.evTarget, this.domHandler);\n removeEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);\n }\n // eslint-enable @typescript-eslint/unbound-method\n}\n","import {InputEvent} from '../input/input-consts';\nimport {Input} from '../input/input';\nimport type {Manager} from '../manager';\n\nconst POINTER_INPUT_MAP = {\n pointerdown: InputEvent.Start,\n pointermove: InputEvent.Move,\n pointerup: InputEvent.End,\n pointercancel: InputEvent.Cancel,\n pointerout: InputEvent.Cancel\n} as const;\n\nconst POINTER_ELEMENT_EVENTS = 'pointerdown';\nconst POINTER_WINDOW_EVENTS = 'pointermove pointerup pointercancel';\n\n/**\n * Pointer events input\n */\nexport class PointerEventInput extends Input {\n store: PointerEvent[];\n\n constructor(manager: Manager) {\n super(manager);\n this.evEl = POINTER_ELEMENT_EVENTS;\n this.evWin = POINTER_WINDOW_EVENTS;\n\n this.store = this.manager.session.pointerEvents = [];\n this.init();\n }\n\n /**\n * handle mouse events\n */\n handler(ev: PointerEvent) {\n const {store} = this;\n let removePointer = false;\n\n // @ts-ignore\n const eventType = POINTER_INPUT_MAP[ev.type];\n const pointerType = ev.pointerType;\n\n const isTouch = pointerType === 'touch';\n\n // get index of the event in the store\n let storeIndex = store.findIndex((e) => e.pointerId === ev.pointerId);\n\n // start and mouse must be down\n if (eventType & InputEvent.Start && (ev.buttons || isTouch)) {\n if (storeIndex < 0) {\n store.push(ev);\n storeIndex = store.length - 1;\n }\n } else if (eventType & (InputEvent.End | InputEvent.Cancel)) {\n removePointer = true;\n }\n\n // it not found, so the pointer hasn't been down (so it's probably a hover)\n if (storeIndex < 0) {\n return;\n }\n\n // update the event in the store\n store[storeIndex] = ev;\n\n this.callback(eventType, {\n pointers: store,\n changedPointers: [ev],\n eventType,\n pointerType,\n srcEvent: ev\n });\n\n if (removePointer) {\n // remove from the store\n store.splice(storeIndex, 1);\n }\n }\n}\n","const VENDOR_PREFIXES = ['', 'webkit', 'Moz', 'MS', 'ms', 'o'];\n\n/**\n * get the prefixed property\n * @returns prefixed property name\n */\nexport function prefixed(obj: Record, property: string): string | undefined {\n const camelProp = property[0].toUpperCase() + property.slice(1);\n\n for (const prefix of VENDOR_PREFIXES) {\n const prop = prefix ? prefix + camelProp : property;\n\n if (prop in obj) {\n return prop;\n }\n }\n return undefined;\n}\n","import {TouchAction} from './touchaction/touchaction';\nimport {PointerEventInput} from './inputs/pointerevent';\nimport {splitStr} from './utils/split-str';\nimport {prefixed} from './utils/prefixed';\nimport {RecognizerState} from './recognizer/recognizer-state';\n\nimport type {Input} from './input/input';\nimport type {Recognizer} from './recognizer/recognizer';\nimport type {Session, HammerInput} from './input/types';\n\nconst STOP = 1;\nconst FORCED_STOP = 2;\n\nexport type ManagerOptions = {\n /**\n * The value for the touchAction property/fallback.\n * When set to `compute` it will magically set the correct value based on the added recognizers.\n * @default compute\n */\n touchAction?: string;\n\n /**\n * @default true\n */\n enable?: boolean;\n\n /**\n * EXPERIMENTAL FEATURE -- can be removed/changed\n * Change the parent input target element.\n * If Null, then it is being set the to main element.\n * @default null\n */\n inputTarget?: null | EventTarget;\n\n /**\n * Some CSS properties can be used to improve the working of Hammer.\n * Add them to this method and they will be set when creating a new Manager.\n */\n cssProps?: Partial;\n};\n\nexport type HammerEvent = HammerInput & {\n type: string;\n preventDefault: () => void;\n};\nexport type EventHandler = (event: HammerEvent) => void;\n\nconst defaultOptions: Required = {\n touchAction: 'compute',\n enable: true,\n inputTarget: null,\n cssProps: {\n /**\n * Disables text selection to improve the dragging gesture. Mainly for desktop browsers.\n */\n userSelect: 'none',\n /**\n * (Webkit) Disable default dragging behavior\n */\n // @ts-ignore\n userDrag: 'none',\n /**\n * (iOS only) Disables the default callout shown when you touch and hold a touch target.\n * When you touch and hold a touch target such as a link, Safari displays\n * a callout containing information about the link. This property allows you to disable that callout.\n */\n // @ts-ignore\n touchCallout: 'none',\n /**\n * (iOS only) Sets the color of the highlight that appears over a link while it's being tapped.\n */\n // @ts-ignore\n tapHighlightColor: 'rgba(0,0,0,0)'\n }\n};\n\n/**\n * Manager\n */\nexport class Manager {\n options: Required;\n\n element: HTMLElement | null;\n touchAction: TouchAction;\n oldCssProps: {[prop: string]: any};\n session: Session;\n recognizers: Recognizer[];\n input: Input;\n handlers: {[event: string]: EventHandler[]};\n\n constructor(element: HTMLElement, options: ManagerOptions) {\n this.options = {\n ...defaultOptions,\n ...options,\n cssProps: {...defaultOptions.cssProps, ...options.cssProps},\n inputTarget: options.inputTarget || element\n };\n\n this.handlers = {};\n this.session = {};\n this.recognizers = [];\n this.oldCssProps = {};\n\n this.element = element;\n this.input = new PointerEventInput(this);\n this.touchAction = new TouchAction(this, this.options.touchAction);\n\n this.toggleCssProps(true);\n }\n\n /**\n * set options\n */\n set(options: Partial) {\n Object.assign(this.options, options);\n\n // Options that need a little more setup\n if (options.touchAction) {\n this.touchAction.update();\n }\n if (options.inputTarget) {\n // Clean up existing event listeners and reinitialize\n this.input.destroy();\n this.input.target = options.inputTarget;\n this.input.init();\n }\n return this;\n }\n\n /**\n * stop recognizing for this session.\n * This session will be discarded, when a new [input]start event is fired.\n * When forced, the recognizer cycle is stopped immediately.\n */\n stop(force?: boolean) {\n this.session.stopped = force ? FORCED_STOP : STOP;\n }\n\n /**\n * run the recognizers!\n * called by the inputHandler function on every movement of the pointers (touches)\n * it walks through all the recognizers and tries to detect the gesture that is being made\n */\n recognize(inputData: HammerInput) {\n const {session} = this;\n if (session.stopped) {\n return;\n }\n\n // run the touch-action polyfill\n if (this.session.prevented) {\n inputData.srcEvent.preventDefault();\n }\n\n let recognizer;\n const {recognizers} = this;\n\n // this holds the recognizer that is being recognized.\n // so the recognizer's state needs to be BEGAN, CHANGED, ENDED or RECOGNIZED\n // if no recognizer is detecting a thing, it is set to `null`\n let {curRecognizer} = session;\n\n // reset when the last recognizer is recognized\n // or when we're in a new session\n if (!curRecognizer || (curRecognizer && curRecognizer.state & RecognizerState.Recognized)) {\n curRecognizer = session.curRecognizer = null;\n }\n\n let i = 0;\n while (i < recognizers.length) {\n recognizer = recognizers[i];\n\n // find out if we are allowed try to recognize the input for this one.\n // 1. allow if the session is NOT forced stopped (see the .stop() method)\n // 2. allow if we still haven't recognized a gesture in this session, or the this recognizer is the one\n // that is being recognized.\n // 3. allow if the recognizer is allowed to run simultaneous with the current recognized recognizer.\n // this can be setup with the `recognizeWith()` method on the recognizer.\n if (\n session.stopped !== FORCED_STOP && // 1\n (!curRecognizer ||\n recognizer === curRecognizer || // 2\n recognizer.canRecognizeWith(curRecognizer))\n ) {\n // 3\n recognizer.recognize(inputData);\n } else {\n recognizer.reset();\n }\n\n // if the recognizer has been recognizing the input as a valid gesture, we want to store this one as the\n // current active recognizer. but only if we don't already have an active recognizer\n if (\n !curRecognizer &&\n recognizer.state & (RecognizerState.Began | RecognizerState.Changed | RecognizerState.Ended)\n ) {\n curRecognizer = session.curRecognizer = recognizer;\n }\n i++;\n }\n }\n\n /**\n * get a recognizer by its event name.\n */\n get(recognizerName: string): Recognizer | null {\n const {recognizers} = this;\n for (let i = 0; i < recognizers.length; i++) {\n if (recognizers[i].options.event === recognizerName) {\n return recognizers[i];\n }\n }\n return null;\n }\n\n /**\n * add a recognizer to the manager\n * existing recognizers with the same event name will be removed\n */\n add(recognizer: Recognizer | Recognizer[]) {\n if (Array.isArray(recognizer)) {\n for (const item of recognizer) {\n this.add(item);\n }\n return this;\n }\n\n // remove existing\n const existing = this.get(recognizer.options.event);\n if (existing) {\n this.remove(existing);\n }\n\n this.recognizers.push(recognizer);\n recognizer.manager = this;\n\n this.touchAction.update();\n return recognizer;\n }\n\n /**\n * remove a recognizer by name or instance\n */\n remove(recognizerOrName: Recognizer | string | (Recognizer | string)[]) {\n if (Array.isArray(recognizerOrName)) {\n for (const item of recognizerOrName) {\n this.remove(item);\n }\n return this;\n }\n\n const recognizer =\n typeof recognizerOrName === 'string' ? this.get(recognizerOrName) : recognizerOrName;\n\n // let's make sure this recognizer exists\n if (recognizer) {\n const {recognizers} = this;\n const index = recognizers.indexOf(recognizer);\n\n if (index !== -1) {\n recognizers.splice(index, 1);\n this.touchAction.update();\n }\n }\n\n return this;\n }\n\n /**\n * bind event\n */\n on(events: string, handler: EventHandler) {\n if (!events || !handler) {\n return;\n }\n const {handlers} = this;\n for (const event of splitStr(events)) {\n handlers[event] = handlers[event] || [];\n handlers[event].push(handler);\n }\n }\n\n /**\n * unbind event, leave hander blank to remove all handlers\n */\n off(events: string, handler?: EventHandler) {\n if (!events) {\n return;\n }\n\n const {handlers} = this;\n for (const event of splitStr(events)) {\n if (!handler) {\n delete handlers[event];\n } else if (handlers[event]) {\n handlers[event].splice(handlers[event].indexOf(handler), 1);\n }\n }\n }\n\n /**\n * emit event to the listeners\n */\n emit(event: string, data: HammerInput) {\n // no handlers, so skip it all\n const handlers = this.handlers[event] && this.handlers[event].slice();\n if (!handlers || !handlers.length) {\n return;\n }\n\n const evt = data as HammerEvent;\n evt.type = event;\n evt.preventDefault = function () {\n data.srcEvent.preventDefault();\n };\n\n let i = 0;\n while (i < handlers.length) {\n handlers[i](evt);\n i++;\n }\n }\n\n /**\n * destroy the manager and unbinds all events\n * it doesn't unbind dom events, that is the user own responsibility\n */\n destroy() {\n this.toggleCssProps(false);\n\n this.handlers = {};\n this.session = {};\n this.input.destroy();\n this.element = null;\n }\n\n /**\n * add/remove the css properties as defined in manager.options.cssProps\n */\n private toggleCssProps(add: boolean) {\n const {element} = this;\n if (!element) {\n return;\n }\n for (const [name, value] of Object.entries(this.options.cssProps)) {\n const prop = prefixed(element.style, name) as any;\n if (add) {\n this.oldCssProps[prop] = element.style[prop];\n element.style[prop] = value as any;\n } else {\n element.style[prop] = this.oldCssProps[prop] || '';\n }\n }\n if (!add) {\n this.oldCssProps = {};\n }\n }\n}\n","/**\n * get a unique id\n */\nlet _uniqueId = 1;\nexport function uniqueId(): number {\n return _uniqueId++;\n}\n","import {RecognizerState} from './recognizer-state';\n\n/**\n * get a usable string, used as event postfix\n */\nexport function stateStr(state: RecognizerState) {\n if (state & RecognizerState.Cancelled) {\n return 'cancel';\n } else if (state & RecognizerState.Ended) {\n return 'end';\n } else if (state & RecognizerState.Changed) {\n return 'move';\n } else if (state & RecognizerState.Began) {\n return 'start';\n }\n return '';\n}\n","import {RecognizerState} from './recognizer-state';\nimport {uniqueId} from '../utils/unique-id';\nimport {stateStr} from './state-str';\n\nimport type {Manager} from '../manager';\nimport type {HammerInput} from '../input/types';\n\nexport type RecognizerOptions = {\n /** Name of the event */\n event: string;\n /** Enable this recognizer */\n enable: boolean;\n};\n\n/**\n * Recognizer flow explained; *\n * All recognizers have the initial state of POSSIBLE when a input session starts.\n * The definition of a input session is from the first input until the last input, with all it's movement in it. *\n * Example session for mouse-input: mousedown -> mousemove -> mouseup\n *\n * On each recognizing cycle (see Manager.recognize) the .recognize() method is executed\n * which determines with state it should be.\n *\n * If the recognizer has the state FAILED, CANCELLED or RECOGNIZED (equals ENDED), it is reset to\n * POSSIBLE to give it another change on the next cycle.\n *\n * Possible\n * |\n * +-----+---------------+\n * | |\n * +-----+-----+ |\n * | | |\n * Failed Cancelled |\n * +-------+------+\n * | |\n * Recognized Began\n * |\n * Changed\n * |\n * Ended/Recognized\n */\n\n/**\n * Recognizer\n * Every recognizer needs to extend from this class.\n */\nexport abstract class Recognizer {\n id: number;\n state: RecognizerState;\n manager!: Manager;\n\n readonly options: OptionsT;\n\n protected simultaneous: {[id: string]: Recognizer};\n protected requireFail: Recognizer[];\n\n constructor(options: OptionsT) {\n this.options = options;\n\n this.id = uniqueId();\n\n this.state = RecognizerState.Possible;\n this.simultaneous = {};\n this.requireFail = [];\n }\n\n /**\n * set options\n */\n set(options: Partial) {\n Object.assign(this.options, options);\n\n // also update the touchAction, in case something changed about the directions/enabled state\n this.manager.touchAction.update();\n return this;\n }\n\n /**\n * recognize simultaneous with an other recognizer.\n */\n recognizeWith(recognizerOrName: Recognizer | string | (Recognizer | string)[]) {\n if (Array.isArray(recognizerOrName)) {\n for (const item of recognizerOrName) {\n this.recognizeWith(item);\n }\n return this;\n }\n\n let otherRecognizer: Recognizer | null;\n if (typeof recognizerOrName === 'string') {\n otherRecognizer = this.manager.get(recognizerOrName);\n if (!otherRecognizer) {\n throw new Error(`Cannot find recognizer ${recognizerOrName}`);\n }\n } else {\n otherRecognizer = recognizerOrName;\n }\n const {simultaneous} = this;\n if (!simultaneous[otherRecognizer.id]) {\n simultaneous[otherRecognizer.id] = otherRecognizer;\n otherRecognizer.recognizeWith(this);\n }\n return this;\n }\n\n /**\n * drop the simultaneous link. it doesnt remove the link on the other recognizer.\n */\n dropRecognizeWith(recognizerOrName: Recognizer | string | (Recognizer | string)[]) {\n if (Array.isArray(recognizerOrName)) {\n for (const item of recognizerOrName) {\n this.dropRecognizeWith(item);\n }\n return this;\n }\n\n let otherRecognizer: Recognizer | null;\n if (typeof recognizerOrName === 'string') {\n otherRecognizer = this.manager.get(recognizerOrName);\n } else {\n otherRecognizer = recognizerOrName;\n }\n if (otherRecognizer) {\n delete this.simultaneous[otherRecognizer.id];\n }\n return this;\n }\n\n /**\n * recognizer can only run when an other is failing\n */\n requireFailure(recognizerOrName: Recognizer | string | (Recognizer | string)[]) {\n if (Array.isArray(recognizerOrName)) {\n for (const item of recognizerOrName) {\n this.requireFailure(item);\n }\n return this;\n }\n\n let otherRecognizer: Recognizer | null;\n if (typeof recognizerOrName === 'string') {\n otherRecognizer = this.manager.get(recognizerOrName);\n if (!otherRecognizer) {\n throw new Error(`Cannot find recognizer ${recognizerOrName}`);\n }\n } else {\n otherRecognizer = recognizerOrName;\n }\n const {requireFail} = this;\n if (requireFail.indexOf(otherRecognizer) === -1) {\n requireFail.push(otherRecognizer);\n otherRecognizer.requireFailure(this);\n }\n return this;\n }\n\n /**\n * drop the requireFailure link. it does not remove the link on the other recognizer.\n */\n dropRequireFailure(recognizerOrName: Recognizer | string | (Recognizer | string)[]) {\n if (Array.isArray(recognizerOrName)) {\n for (const item of recognizerOrName) {\n this.dropRequireFailure(item);\n }\n return this;\n }\n\n let otherRecognizer: Recognizer | null;\n if (typeof recognizerOrName === 'string') {\n otherRecognizer = this.manager.get(recognizerOrName);\n } else {\n otherRecognizer = recognizerOrName;\n }\n if (otherRecognizer) {\n const index = this.requireFail.indexOf(otherRecognizer);\n if (index > -1) {\n this.requireFail.splice(index, 1);\n }\n }\n return this;\n }\n\n /**\n * has require failures boolean\n */\n hasRequireFailures(): boolean {\n return Boolean(this.requireFail.find((recognier) => recognier.options.enable));\n }\n\n /**\n * if the recognizer can recognize simultaneous with an other recognizer\n */\n canRecognizeWith(otherRecognizer: Recognizer): boolean {\n return Boolean(this.simultaneous[otherRecognizer.id]);\n }\n\n /**\n * You should use `tryEmit` instead of `emit` directly to check\n * that all the needed recognizers has failed before emitting.\n */\n protected emit(input?: HammerInput) {\n // Some recognizers override emit() with their own logic\n if (!input) return;\n\n const {state} = this;\n\n // 'panstart' and 'panmove'\n if (state < RecognizerState.Ended) {\n this.manager.emit(this.options.event + stateStr(state), input);\n }\n\n // simple 'eventName' events\n this.manager.emit(this.options.event, input);\n\n // additional event(panleft, panright, pinchin, pinchout...)\n if (input.additionalEvent) {\n this.manager.emit(input.additionalEvent, input);\n }\n\n // panend and pancancel\n if (state >= RecognizerState.Ended) {\n this.manager.emit(this.options.event + stateStr(state), input);\n }\n }\n\n /**\n * Check that all the require failure recognizers has failed,\n * if true, it emits a gesture event,\n * otherwise, setup the state to FAILED.\n */\n protected tryEmit(input?: HammerInput) {\n if (this.canEmit()) {\n this.emit(input);\n } else {\n // it's failing anyway\n this.state = RecognizerState.Failed;\n }\n }\n\n /**\n * can we emit?\n */\n protected canEmit(): boolean {\n let i = 0;\n while (i < this.requireFail.length) {\n if (!(this.requireFail[i].state & (RecognizerState.Failed | RecognizerState.Possible))) {\n return false;\n }\n i++;\n }\n return true;\n }\n\n /**\n * update the recognizer\n */\n recognize(inputData: HammerInput) {\n // make a new copy of the inputData\n // so we can change the inputData without messing up the other recognizers\n const inputDataClone = {...inputData};\n\n // is is enabled and allow recognizing?\n if (!this.options.enable) {\n this.reset();\n this.state = RecognizerState.Failed;\n return;\n }\n\n // reset when we've reached the end\n if (\n this.state &\n (RecognizerState.Recognized | RecognizerState.Cancelled | RecognizerState.Failed)\n ) {\n this.state = RecognizerState.Possible;\n }\n\n this.state = this.process(inputDataClone);\n\n // the recognizer has recognized a gesture\n // so trigger an event\n if (\n this.state &\n (RecognizerState.Began |\n RecognizerState.Changed |\n RecognizerState.Ended |\n RecognizerState.Cancelled)\n ) {\n this.tryEmit(inputDataClone);\n }\n }\n\n /**\n * return the state of the recognizer\n * the actual recognizing happens in this method\n */\n\n abstract process(inputData: HammerInput): RecognizerState;\n\n /**\n * return the preferred touch-action\n */\n abstract getTouchAction(): string[];\n\n /**\n * return the event names that are emitted by this recognizer\n */\n getEventNames(): string[] {\n return [this.options.event];\n }\n\n /**\n * called when the gesture isn't allowed to recognize\n * like when another is being recognized or it is disabled\n */\n reset(): void {}\n}\n","import {Recognizer, RecognizerOptions} from '../recognizer/recognizer';\nimport {RecognizerState} from '../recognizer/recognizer-state';\nimport {InputEvent} from '../input/input-consts';\nimport type {HammerInput} from '../input/types';\n\ntype AttrRecognizerOptions = RecognizerOptions & {\n pointers: number;\n};\n\n/**\n * This recognizer is just used as a base for the simple attribute recognizers.\n */\nexport abstract class AttrRecognizer<\n OptionsT extends AttrRecognizerOptions\n> extends Recognizer {\n /**\n * Used to check if it the recognizer receives valid input, like input.distance > 10.\n */\n attrTest(input: HammerInput): boolean {\n const optionPointers = this.options.pointers;\n return optionPointers === 0 || input.pointers.length === optionPointers;\n }\n\n /**\n * Process the input and return the state for the recognizer\n */\n process(input: HammerInput) {\n const {state} = this;\n const {eventType} = input;\n\n const isRecognized = state & (RecognizerState.Began | RecognizerState.Changed);\n const isValid = this.attrTest(input);\n\n // on cancel input and we've recognized before, return STATE_CANCELLED\n if (isRecognized && (eventType & InputEvent.Cancel || !isValid)) {\n return state | RecognizerState.Cancelled;\n } else if (isRecognized || isValid) {\n if (eventType & InputEvent.End) {\n return state | RecognizerState.Ended;\n } else if (!(state & RecognizerState.Began)) {\n return RecognizerState.Began;\n }\n return state | RecognizerState.Changed;\n }\n return RecognizerState.Failed;\n }\n}\n","/* global setTimeout, clearTimeout */\nimport {Recognizer} from '../recognizer/recognizer';\nimport {TOUCH_ACTION_MANIPULATION} from '../touchaction/touchaction-Consts';\nimport {InputEvent} from '../input/input-consts';\nimport {RecognizerState} from '../recognizer/recognizer-state';\nimport {getPointDistance} from '../input/get-distance';\nimport type {Point, HammerInput} from '../input/types';\n\nexport type TapRecognizerOptions = {\n /** Name of the event.\n * @default 'tap'\n */\n event?: string;\n /** Enable this event.\n * @default true\n */\n enable?: boolean;\n /** Required pointers.\n * @default 1\n */\n pointers?: number;\n /** Required number of taps in succession.\n * @default 1\n */\n taps?: number;\n /** Maximum time in ms between multiple taps.\n * @default 300\n */\n interval?: number;\n /** Maximum press time in ms.\n * @default 250\n */\n time?: number;\n /** While doing a tap some small movement is allowed.\n * @default 9\n */\n threshold?: number;\n /** The maximum position difference between multiple taps.\n * @default 10\n */\n posThreshold?: number;\n};\n\n/**\n * A tap is recognized when the pointer is doing a small tap/click. Multiple taps are recognized if they occur\n * between the given interval and position. The delay option can be used to recognize multi-taps without firing\n * a single tap.\n *\n * The eventData from the emitted event contains the property `tapCount`, which contains the amount of\n * multi-taps being recognized.\n */\nexport class TapRecognizer extends Recognizer> {\n /** previous time for tap counting */\n private pTime: number | null = null;\n /** previous center for tap counting */\n private pCenter: Point | null = null;\n\n private _timer: any = null;\n private _input: HammerInput | null = null;\n\n private count: number = 0;\n\n constructor(options: TapRecognizerOptions = {}) {\n super({\n enable: true,\n event: 'tap',\n pointers: 1,\n taps: 1,\n interval: 300,\n time: 250,\n threshold: 9,\n posThreshold: 10,\n ...options\n });\n }\n\n getTouchAction() {\n return [TOUCH_ACTION_MANIPULATION];\n }\n\n process(input: HammerInput) {\n const {options} = this;\n\n const validPointers = input.pointers.length === options.pointers;\n const validMovement = input.distance < options.threshold;\n const validTouchTime = input.deltaTime < options.time;\n\n this.reset();\n\n if (input.eventType & InputEvent.Start && this.count === 0) {\n return this.failTimeout();\n }\n\n // we only allow little movement\n // and we've reached an end event, so a tap is possible\n if (validMovement && validTouchTime && validPointers) {\n if (input.eventType !== InputEvent.End) {\n return this.failTimeout();\n }\n\n const validInterval = this.pTime ? input.timeStamp - this.pTime < options.interval : true;\n const validMultiTap =\n !this.pCenter || getPointDistance(this.pCenter, input.center) < options.posThreshold;\n\n this.pTime = input.timeStamp;\n this.pCenter = input.center;\n\n if (!validMultiTap || !validInterval) {\n this.count = 1;\n } else {\n this.count += 1;\n }\n\n this._input = input;\n\n // if tap count matches we have recognized it,\n // else it has began recognizing...\n const tapCount = this.count % options.taps;\n if (tapCount === 0) {\n // no failing requirements, immediately trigger the tap event\n // or wait as long as the multitap interval to trigger\n if (!this.hasRequireFailures()) {\n return RecognizerState.Recognized;\n }\n this._timer = setTimeout(() => {\n this.state = RecognizerState.Recognized;\n this.tryEmit(this._input!);\n }, options.interval);\n return RecognizerState.Began;\n }\n }\n return RecognizerState.Failed;\n }\n\n failTimeout() {\n this._timer = setTimeout(() => {\n this.state = RecognizerState.Failed;\n }, this.options.interval);\n return RecognizerState.Failed;\n }\n\n reset() {\n clearTimeout(this._timer);\n }\n\n emit(input: HammerInput) {\n if (this.state === RecognizerState.Recognized) {\n input.tapCount = this.count;\n this.manager.emit(this.options.event, input);\n }\n }\n}\n","import {AttrRecognizer} from './attribute';\nimport {InputDirection} from '../input/input-consts';\nimport {RecognizerState} from '../recognizer/recognizer-state';\nimport {TOUCH_ACTION_PAN_X, TOUCH_ACTION_PAN_Y} from '../touchaction/touchaction-Consts';\nimport type {HammerInput} from '../input/types';\n\nexport type PanRecognizerOptions = {\n /** Name of the event.\n * @default 'pan'\n */\n event?: string;\n /** Enable this event.\n * @default true\n */\n enable?: boolean;\n /** Required number of pointers. 0 for all pointers.\n * @default 1\n */\n pointers?: number;\n /** Required direction of panning.\n * @default InputDirection.All\n */\n direction?: InputDirection;\n /** Minimal pan distance required before recognizing.\n * @default 10\n */\n threshold?: number;\n};\n\nconst EVENT_NAMES = ['', 'start', 'move', 'end', 'cancel', 'up', 'down', 'left', 'right'] as const;\n\n/**\n * Pan\n * Recognized when the pointer is down and moved in the allowed direction.\n */\nexport class PanRecognizer extends AttrRecognizer> {\n pX: number | null;\n pY: number | null;\n\n constructor(options: PanRecognizerOptions = {}) {\n super({\n enable: true,\n pointers: 1,\n event: 'pan',\n threshold: 10,\n direction: InputDirection.All,\n ...options\n });\n this.pX = null;\n this.pY = null;\n }\n\n getTouchAction(): string[] {\n const {\n options: {direction}\n } = this;\n const actions: string[] = [];\n if (direction & InputDirection.Horizontal) {\n actions.push(TOUCH_ACTION_PAN_Y);\n }\n if (direction & InputDirection.Vertical) {\n actions.push(TOUCH_ACTION_PAN_X);\n }\n return actions;\n }\n\n getEventNames(): string[] {\n return EVENT_NAMES.map((suffix) => this.options.event + suffix);\n }\n\n directionTest(input: HammerInput): boolean {\n const {options} = this;\n let hasMoved = true;\n let {distance} = input;\n let {direction} = input;\n const x = input.deltaX;\n const y = input.deltaY;\n\n // lock to axis?\n if (!(direction & options.direction)) {\n if (options.direction & InputDirection.Horizontal) {\n direction =\n x === 0 ? InputDirection.None : x < 0 ? InputDirection.Left : InputDirection.Right;\n hasMoved = x !== this.pX;\n distance = Math.abs(input.deltaX);\n } else {\n direction = y === 0 ? InputDirection.None : y < 0 ? InputDirection.Up : InputDirection.Down;\n hasMoved = y !== this.pY;\n distance = Math.abs(input.deltaY);\n }\n }\n input.direction = direction;\n return hasMoved && distance > options.threshold && Boolean(direction & options.direction);\n }\n\n attrTest(input: HammerInput): boolean {\n return (\n super.attrTest(input) &&\n (Boolean(this.state & RecognizerState.Began) ||\n (!(this.state & RecognizerState.Began) && this.directionTest(input)))\n );\n }\n\n emit(input: HammerInput) {\n this.pX = input.deltaX;\n this.pY = input.deltaY;\n\n const direction = InputDirection[input.direction].toLowerCase();\n\n if (direction) {\n input.additionalEvent = this.options.event + direction;\n }\n super.emit(input);\n }\n}\n","import {AttrRecognizer} from './attribute';\nimport {TOUCH_ACTION_NONE} from '../touchaction/touchaction-Consts';\nimport {RecognizerState} from '../recognizer/recognizer-state';\nimport type {HammerInput} from '../input/types';\n\nexport type PinchRecognizerOptions = {\n /** Name of the event.\n * @default 'pinch'\n */\n event?: string;\n /** Enable this event.\n * @default true\n */\n enable?: boolean;\n /** Required number of pointers, with a minimum of 2.\n * @default 2\n */\n pointers?: number;\n /** Minimal scale before recognizing.\n * @default 0\n */\n threshold?: number;\n};\n\nconst EVENT_NAMES = ['', 'start', 'move', 'end', 'cancel', 'in', 'out'] as const;\n\n/**\n * Pinch\n * Recognized when two or more pointers are moving toward (zoom-in) or away from each other (zoom-out).\n */\nexport class PinchRecognizer extends AttrRecognizer> {\n constructor(options: PinchRecognizerOptions = {}) {\n super({\n enable: true,\n event: 'pinch',\n threshold: 0,\n pointers: 2,\n ...options\n });\n }\n\n getTouchAction() {\n return [TOUCH_ACTION_NONE];\n }\n\n getEventNames(): string[] {\n return EVENT_NAMES.map((suffix) => this.options.event + suffix);\n }\n\n attrTest(input: HammerInput): boolean {\n return (\n super.attrTest(input) &&\n (Math.abs(input.scale - 1) > this.options.threshold ||\n Boolean(this.state & RecognizerState.Began))\n );\n }\n\n emit(input: HammerInput) {\n if (input.scale !== 1) {\n const inOut = input.scale < 1 ? 'in' : 'out';\n input.additionalEvent = this.options.event + inOut;\n }\n super.emit(input);\n }\n}\n","// mjolnir.js\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {MjolnirEventRaw} from '../types';\n\nexport interface InputOptions {\n enable?: boolean;\n}\n\nexport class Input {\n element: HTMLElement;\n options: Options;\n callback: (e: EventType) => void;\n\n constructor(element: HTMLElement, callback: (e: EventType) => void, options: Options) {\n this.element = element;\n this.callback = callback;\n this.options = options;\n }\n}\n","// mjolnir.js\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// Purpose: include this in your module to avoids adding dependencies on\n// micro modules like 'global'\n\n/* global window, global, document, navigator */\nexport const userAgent =\n typeof navigator !== 'undefined' && navigator.userAgent ? navigator.userAgent.toLowerCase() : '';\n\nconst window_ = typeof window !== 'undefined' ? window : global;\nconst global_ = typeof global !== 'undefined' ? global : window;\nconst document_ = typeof document !== 'undefined' ? document : {};\n\nexport {window_ as window, global_ as global, document_ as document};\n","// mjolnir.js\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {MjolnirWheelEventRaw} from '../types';\nimport {Input, InputOptions} from './input';\n\nimport {userAgent} from '../utils/globals';\n\nconst firefox = userAgent.indexOf('firefox') !== -1;\n\n// Constants for normalizing input delta\nconst WHEEL_DELTA_MAGIC_SCALER = 4.000244140625;\nconst WHEEL_DELTA_PER_LINE = 40;\n// Slow down zoom if shift key is held for more precise zooming\nconst SHIFT_MULTIPLIER = 0.25;\n\nexport class WheelInput extends Input> {\n constructor(\n element: HTMLElement,\n callback: (event: MjolnirWheelEventRaw) => void,\n options: InputOptions\n ) {\n super(element, callback, {enable: true, ...options});\n\n element.addEventListener('wheel', this.handleEvent, {passive: false});\n }\n\n destroy() {\n this.element.removeEventListener('wheel', this.handleEvent);\n }\n\n /**\n * Enable this input (begin processing events)\n * if the specified event type is among those handled by this input.\n */\n enableEventType(eventType: string, enabled: boolean) {\n if (eventType === 'wheel') {\n this.options.enable = enabled;\n }\n }\n\n /* eslint-disable complexity, max-statements */\n handleEvent = (event: WheelEvent) => {\n if (!this.options.enable) {\n return;\n }\n\n let value = event.deltaY;\n if (globalThis.WheelEvent) {\n // Firefox doubles the values on retina screens...\n if (firefox && event.deltaMode === globalThis.WheelEvent.DOM_DELTA_PIXEL) {\n value /= globalThis.devicePixelRatio;\n }\n if (event.deltaMode === globalThis.WheelEvent.DOM_DELTA_LINE) {\n value *= WHEEL_DELTA_PER_LINE;\n }\n }\n\n if (value !== 0 && value % WHEEL_DELTA_MAGIC_SCALER === 0) {\n // This one is definitely a mouse wheel event.\n // Normalize this value to match trackpad.\n value = Math.floor(value / WHEEL_DELTA_MAGIC_SCALER);\n }\n\n if (event.shiftKey && value) {\n value = value * SHIFT_MULTIPLIER;\n }\n\n this.callback({\n type: 'wheel',\n center: {\n x: event.clientX,\n y: event.clientY\n },\n delta: -value,\n srcEvent: event,\n pointerType: 'mouse',\n target: event.target as HTMLElement\n });\n };\n}\n","// mjolnir.js\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {MjolnirPointerEventRaw} from '../types';\nimport {Input, InputOptions} from './input';\n\nconst MOUSE_EVENTS = [\n 'mousedown',\n 'mousemove',\n 'mouseup',\n 'mouseover',\n 'mouseout',\n 'mouseleave'\n] as const;\n\ntype MoveEventType = 'pointermove' | 'pointerover' | 'pointerout' | 'pointerenter' | 'pointerleave';\n\n/**\n * Hammer.js swallows 'move' events (for pointer/touch/mouse)\n * when the pointer is not down. This class sets up a handler\n * specifically for these events to work around this limitation.\n * Note that this could be extended to more intelligently handle\n * move events across input types, e.g. storing multiple simultaneous\n * pointer/touch events, calculating speed/direction, etc.\n */\nexport class MoveInput extends Input> {\n pressed: boolean;\n enableMoveEvent: boolean;\n enableEnterEvent: boolean;\n enableLeaveEvent: boolean;\n enableOutEvent: boolean;\n enableOverEvent: boolean;\n\n constructor(\n element: HTMLElement,\n callback: (event: MjolnirPointerEventRaw) => void,\n options: InputOptions\n ) {\n super(element, callback, {enable: true, ...options});\n\n this.pressed = false;\n const {enable} = this.options;\n\n this.enableMoveEvent = enable;\n this.enableLeaveEvent = enable;\n this.enableEnterEvent = enable;\n this.enableOutEvent = enable;\n this.enableOverEvent = enable;\n\n MOUSE_EVENTS.forEach((event) => element.addEventListener(event, this.handleEvent));\n }\n\n destroy() {\n MOUSE_EVENTS.forEach((event) => this.element.removeEventListener(event, this.handleEvent));\n }\n\n /**\n * Enable this input (begin processing events)\n * if the specified event type is among those handled by this input.\n */\n enableEventType(eventType: string, enabled: boolean) {\n switch (eventType) {\n case 'pointermove':\n this.enableMoveEvent = enabled;\n break;\n case 'pointerover':\n this.enableOverEvent = enabled;\n break;\n case 'pointerout':\n this.enableOutEvent = enabled;\n break;\n case 'pointerenter':\n this.enableEnterEvent = enabled;\n break;\n case 'pointerleave':\n this.enableLeaveEvent = enabled;\n break;\n default:\n // ignore\n }\n }\n\n handleEvent = (event: MouseEvent) => {\n this.handleOverEvent(event);\n this.handleOutEvent(event);\n this.handleEnterEvent(event);\n this.handleLeaveEvent(event);\n this.handleMoveEvent(event);\n };\n\n handleOverEvent(event: MouseEvent) {\n if (this.enableOverEvent && event.type === 'mouseover') {\n this._emit('pointerover', event);\n }\n }\n\n handleOutEvent(event: MouseEvent) {\n if (this.enableOutEvent && event.type === 'mouseout') {\n this._emit('pointerout', event);\n }\n }\n\n handleEnterEvent(event: MouseEvent) {\n if (this.enableEnterEvent && event.type === 'mouseenter') {\n this._emit('pointerenter', event);\n }\n }\n\n handleLeaveEvent(event: MouseEvent) {\n if (this.enableLeaveEvent && event.type === 'mouseleave') {\n this._emit('pointerleave', event);\n }\n }\n\n handleMoveEvent(event: MouseEvent) {\n if (this.enableMoveEvent) {\n switch (event.type) {\n case 'mousedown':\n if (event.button >= 0) {\n // Button is down\n this.pressed = true;\n }\n break;\n case 'mousemove':\n // Move events use `bottons` to track the button being pressed\n if (event.buttons === 0) {\n // Button is not down\n this.pressed = false;\n }\n if (!this.pressed) {\n // Drag events are emitted by hammer already\n // we just need to emit the move event on hover\n this._emit('pointermove', event);\n }\n break;\n case 'mouseup':\n this.pressed = false;\n break;\n default:\n }\n }\n }\n\n _emit(type: MoveEventType, event: MouseEvent) {\n this.callback({\n type,\n center: {\n x: event.clientX,\n y: event.clientY\n },\n srcEvent: event,\n pointerType: 'mouse',\n target: event.target as HTMLElement\n });\n }\n}\n","// mjolnir.js\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {MjolnirKeyEventRaw} from '../types';\nimport {Input, InputOptions} from './input';\n\nconst KEY_EVENTS = ['keydown', 'keyup'] as const;\n\ntype KeyInputOptions = InputOptions & {\n tabIndex?: number;\n};\n\nexport class KeyInput extends Input> {\n enableDownEvent: boolean;\n enableUpEvent: boolean;\n\n constructor(\n element: HTMLElement,\n callback: (event: MjolnirKeyEventRaw) => void,\n options: KeyInputOptions\n ) {\n super(element, callback, {enable: true, tabIndex: 0, ...options});\n\n this.enableDownEvent = this.options.enable;\n this.enableUpEvent = this.options.enable;\n\n element.tabIndex = this.options.tabIndex;\n element.style.outline = 'none';\n KEY_EVENTS.forEach((event) => element.addEventListener(event, this.handleEvent));\n }\n\n destroy() {\n KEY_EVENTS.forEach((event) => this.element.removeEventListener(event, this.handleEvent));\n }\n\n /**\n * Enable this input (begin processing events)\n * if the specified event type is among those handled by this input.\n */\n enableEventType(eventType: string, enabled: boolean) {\n if (eventType === 'keydown') {\n this.enableDownEvent = enabled;\n }\n if (eventType === 'keyup') {\n this.enableUpEvent = enabled;\n }\n }\n\n handleEvent = (event: KeyboardEvent) => {\n // Ignore if focused on text input\n const targetElement = (event.target || event.srcElement) as HTMLElement;\n if (\n (targetElement.tagName === 'INPUT' && (targetElement as HTMLInputElement).type === 'text') ||\n targetElement.tagName === 'TEXTAREA'\n ) {\n return;\n }\n\n if (this.enableDownEvent && event.type === 'keydown') {\n this.callback({\n type: 'keydown',\n srcEvent: event,\n key: event.key,\n target: event.target as HTMLElement\n });\n }\n\n if (this.enableUpEvent && event.type === 'keyup') {\n this.callback({\n type: 'keyup',\n srcEvent: event,\n key: event.key,\n target: event.target as HTMLElement\n });\n }\n };\n}\n","// mjolnir.js\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {MjolnirPointerEventRaw} from '../types';\nimport {Input, InputOptions} from './input';\n\nexport class ContextmenuInput extends Input {\n constructor(\n element: HTMLElement,\n callback: (event: MjolnirPointerEventRaw) => void,\n options: InputOptions\n ) {\n super(element, callback, options);\n\n element.addEventListener('contextmenu', this.handleEvent);\n }\n\n destroy() {\n this.element.removeEventListener('contextmenu', this.handleEvent);\n }\n\n /**\n * Enable this input (begin processing events)\n * if the specified event type is among those handled by this input.\n */\n enableEventType(eventType: string, enabled: boolean) {\n if (eventType === 'contextmenu') {\n this.options.enable = enabled;\n }\n }\n\n handleEvent = (event: MouseEvent) => {\n if (!this.options.enable) {\n return;\n }\n\n this.callback({\n type: 'contextmenu',\n center: {\n x: event.clientX,\n y: event.clientY\n },\n srcEvent: event,\n pointerType: 'mouse',\n target: event.target as HTMLElement\n });\n };\n}\n","// mjolnir.js\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {MjolnirEventRaw, Point} from '../types';\nimport type {HammerEvent} from '../hammerjs/index';\n\n/* Constants */\nconst DOWN_EVENT = 1;\nconst MOVE_EVENT = 2;\nconst UP_EVENT = 4;\nconst MOUSE_EVENTS = {\n pointerdown: DOWN_EVENT,\n pointermove: MOVE_EVENT,\n pointerup: UP_EVENT,\n mousedown: DOWN_EVENT,\n mousemove: MOVE_EVENT,\n mouseup: UP_EVENT\n};\n\n// MouseEvent.button https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button\nconst MOUSE_EVENT_BUTTON_LEFT = 0;\nconst MOUSE_EVENT_BUTTON_MIDDLE = 1;\nconst MOUSE_EVENT_BUTTON_RIGHT = 2;\n// MouseEvent.buttons https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons\nconst MOUSE_EVENT_BUTTONS_LEFT_MASK = 1;\nconst MOUSE_EVENT_BUTTONS_RIGHT_MASK = 2;\nconst MOUSE_EVENT_BUTTONS_MIDDLE_MASK = 4;\n\n/**\n * Extract the involved mouse button\n */\nexport function whichButtons(event: MjolnirEventRaw): {\n leftButton: boolean;\n middleButton: boolean;\n rightButton: boolean;\n} | null {\n const eventType = MOUSE_EVENTS[event.srcEvent.type];\n if (!eventType) {\n // Not a mouse evet\n return null;\n }\n\n const {buttons, button} = event.srcEvent as PointerEvent;\n let leftButton = false;\n let middleButton = false;\n let rightButton = false;\n\n if (eventType === MOVE_EVENT) {\n leftButton = Boolean(buttons & MOUSE_EVENT_BUTTONS_LEFT_MASK);\n middleButton = Boolean(buttons & MOUSE_EVENT_BUTTONS_MIDDLE_MASK);\n rightButton = Boolean(buttons & MOUSE_EVENT_BUTTONS_RIGHT_MASK);\n } else {\n leftButton = button === MOUSE_EVENT_BUTTON_LEFT;\n middleButton = button === MOUSE_EVENT_BUTTON_MIDDLE;\n rightButton = button === MOUSE_EVENT_BUTTON_RIGHT;\n }\n\n return {leftButton, middleButton, rightButton};\n}\n\n/**\n * Calculate event position relative to the root element\n */\nexport function getOffsetPosition(\n event: MjolnirEventRaw,\n rootElement: HTMLElement\n): {\n center: Point;\n offsetCenter: Point;\n} | null {\n const center = (event as HammerEvent).center;\n\n // `center` is a hammer.js event property\n if (!center) {\n // Not a gestural event\n return null;\n }\n\n const rect = rootElement.getBoundingClientRect();\n\n // Fix scale for map affected by a CSS transform.\n // See https://stackoverflow.com/a/26893663/3528533\n const scaleX = rect.width / rootElement.offsetWidth || 1;\n const scaleY = rect.height / rootElement.offsetHeight || 1;\n\n // Calculate center relative to the root element\n const offsetCenter = {\n x: (center.x - rect.left - rootElement.clientLeft) / scaleX,\n y: (center.y - rect.top - rootElement.clientTop) / scaleY\n };\n\n return {center, offsetCenter};\n}\n","// mjolnir.js\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {EventManager} from '../event-manager';\nimport {whichButtons, getOffsetPosition} from './event-utils';\nimport type {\n MjolnirEventRaw,\n MjolnirEventWrapper,\n MjolnirEvent,\n MjolnirEventHandler\n} from '../types';\n\nexport type HandlerOptions = {\n /** Optional element from which the event is originated from.\n * @default 'root'\n */\n srcElement?: 'root' | HTMLElement;\n /** Handler with higher priority will be called first.\n * Handler with the same priority will be called in the order of registration.\n * @default 0\n */\n priority?: number;\n};\n\ntype EventHandler = {\n type: string;\n handler: (event: MjolnirEvent) => void;\n once?: boolean;\n passive?: boolean;\n srcElement: 'root' | HTMLElement;\n priority: number;\n};\n\nconst DEFAULT_OPTIONS: Required = {\n srcElement: 'root',\n priority: 0\n};\n\nexport class EventRegistrar {\n eventManager: EventManager;\n recognizerName: string;\n handlers: EventHandler[];\n handlersByElement: Map<'root' | HTMLElement, EventHandler[]>;\n _active: boolean;\n\n constructor(eventManager: EventManager, recognizerName: string) {\n this.eventManager = eventManager;\n this.recognizerName = recognizerName;\n this.handlers = [];\n // Element -> handler map\n this.handlersByElement = new Map();\n\n this._active = false;\n }\n\n // Returns true if there are no non-passive handlers\n isEmpty(): boolean {\n return !this._active;\n }\n\n add(\n type: string,\n handler: MjolnirEventHandler,\n options?: HandlerOptions,\n once: boolean = false,\n passive: boolean = false\n ) {\n const {handlers, handlersByElement} = this;\n const opts: Required = {...DEFAULT_OPTIONS, ...options};\n\n let entries = handlersByElement.get(opts.srcElement);\n if (!entries) {\n entries = [];\n handlersByElement.set(opts.srcElement, entries);\n }\n const entry: EventHandler = {\n type,\n handler,\n srcElement: opts.srcElement,\n priority: opts.priority\n };\n if (once) {\n entry.once = true;\n }\n if (passive) {\n entry.passive = true;\n }\n handlers.push(entry);\n this._active = this._active || !entry.passive;\n\n // Sort handlers by descending priority\n // Handlers with the same priority are excuted in the order of registration\n let insertPosition = entries.length - 1;\n while (insertPosition >= 0) {\n if (entries[insertPosition].priority >= entry.priority) {\n break;\n }\n insertPosition--;\n }\n entries.splice(insertPosition + 1, 0, entry);\n }\n\n remove(type: string, handler: MjolnirEventHandler) {\n const {handlers, handlersByElement} = this;\n\n for (let i = handlers.length - 1; i >= 0; i--) {\n const entry = handlers[i];\n\n if (entry.type === type && entry.handler === handler) {\n handlers.splice(i, 1);\n const entries = handlersByElement.get(entry.srcElement)!;\n entries.splice(entries.indexOf(entry), 1);\n if (entries.length === 0) {\n handlersByElement.delete(entry.srcElement);\n }\n }\n }\n this._active = handlers.some((entry) => !entry.passive);\n }\n\n /**\n * Handles hammerjs event\n */\n handleEvent = (event: MjolnirEventRaw) => {\n if (this.isEmpty()) {\n return;\n }\n\n const mjolnirEvent = this._normalizeEvent(event);\n let target = event.srcEvent.target as HTMLElement;\n\n while (target && target !== mjolnirEvent.rootElement) {\n this._emit(mjolnirEvent, target);\n if (mjolnirEvent.handled) {\n return;\n }\n target = target.parentNode as HTMLElement;\n }\n this._emit(mjolnirEvent, 'root');\n };\n\n /**\n * Invoke handlers on a particular element\n */\n _emit(\n event: MjolnirEventWrapper,\n srcElement: 'root' | HTMLElement\n ) {\n const entries = this.handlersByElement.get(srcElement);\n\n if (entries) {\n let immediatePropagationStopped = false;\n\n // Prevents the current event from bubbling up\n const stopPropagation = () => {\n event.handled = true;\n };\n // Prevent any remaining listeners from being called\n const stopImmediatePropagation = () => {\n event.handled = true;\n immediatePropagationStopped = true;\n };\n const entriesToRemove: EventHandler[] = [];\n\n for (let i = 0; i < entries.length; i++) {\n const {type, handler, once} = entries[i];\n // @ts-ignore\n handler({\n ...event,\n type,\n stopPropagation,\n stopImmediatePropagation\n });\n if (once) {\n entriesToRemove.push(entries[i]);\n }\n if (immediatePropagationStopped) {\n break;\n }\n }\n\n for (let i = 0; i < entriesToRemove.length; i++) {\n const {type, handler} = entriesToRemove[i];\n this.remove(type, handler);\n }\n }\n }\n\n /**\n * Normalizes hammerjs and custom events to have predictable fields.\n */\n _normalizeEvent(event: T): MjolnirEventWrapper {\n const rootElement = this.eventManager.getElement();\n\n // @ts-ignore\n return {\n ...event,\n ...whichButtons(event),\n ...getOffsetPosition(event, rootElement!),\n preventDefault: () => {\n event.srcEvent.preventDefault();\n },\n stopImmediatePropagation: null,\n stopPropagation: null,\n handled: false,\n rootElement\n };\n }\n}\n","// mjolnir.js\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Manager as HammerManager, Recognizer} from './hammerjs/index';\nimport type {\n MjolnirEventRaw,\n MjolnirEvent,\n MjolnirEventHandler,\n MjolnirEventHandlers\n} from './types';\n\nimport {WheelInput} from './inputs/wheel-input';\nimport {MoveInput} from './inputs/move-input';\nimport {KeyInput} from './inputs/key-input';\nimport {ContextmenuInput} from './inputs/contextmenu-input';\n\nimport {EventRegistrar, HandlerOptions} from './utils/event-registrar';\n\ntype RecognizerConstructor = {new (options: any): Recognizer};\n\ntype RecognizerTupleNormalized = {\n recognizer: Recognizer;\n /** Allow another gesture to be recognized simultaneously with this one.\n * For example an interaction can trigger pinch and rotate at the same time. */\n recognizeWith?: string[];\n /** Another recognizer is mutually exclusive with this one.\n * For example an interaction could be singletap or doubletap; pan-horizontal or pan-vertical; but never both. */\n requireFailure?: string[];\n};\n\nexport type RecognizerTuple =\n | Recognizer\n | RecognizerConstructor\n | RecognizerTupleNormalized\n /** hammer.js/mjolnir.js@2 style */\n | [\n recognizer: RecognizerConstructor,\n options?: any,\n /** Allow another gesture to be recognized simultaneously with this one.\n * For example an interaction can trigger pinch and rotate at the same time. */\n recognizeWith?: string | string[],\n /** Another recognizer is mutually exclusive with this one.\n * For example an interaction could be singletap or doubletap; pan-horizontal or pan-vertical; but never both. */\n requireFailure?: string | string[]\n ];\n\nexport type EventManagerOptions = {\n /** Event listeners */\n events?: MjolnirEventHandlers;\n /** Gesture recognizers */\n recognizers?: RecognizerTuple[];\n /** Touch action to set on the target element.\n * Use 'compute' to automatically set as the least restrictive value to support the recognizers.\n * https://developer.mozilla.org/en-US/docs/Web/CSS/touch-action\n * @default 'compute'\n */\n touchAction?: 'none' | 'compute' | 'manipulation' | 'pan-x' | 'pan-y' | 'pan-x pan-y';\n /** Tab index of the target element */\n tabIndex?: number;\n /**\n * Optional CSS properties to be applied to the target element.\n */\n cssProps?: Partial;\n};\n\nfunction normalizeRecognizer(item: RecognizerTuple): RecognizerTupleNormalized {\n if ('recognizer' in item) {\n return item;\n }\n let recognizer: Recognizer;\n const itemArray = Array.isArray(item) ? [...item] : [item];\n if (typeof itemArray[0] === 'function') {\n // Backward compatibility: v2 / hammerjs style\n const RecognizerType = itemArray.shift();\n const options = itemArray.shift() || {};\n recognizer = new RecognizerType(options);\n } else {\n recognizer = itemArray.shift();\n }\n return {\n recognizer,\n recognizeWith: typeof itemArray[0] === 'string' ? [itemArray[0]] : itemArray[0],\n requireFailure: typeof itemArray[1] === 'string' ? [itemArray[1]] : itemArray[1]\n };\n}\n\n// Unified API for subscribing to events about both\n// basic input events (e.g. 'mousemove', 'touchstart', 'wheel')\n// and gestural input (e.g. 'click', 'tap', 'panstart').\n// Delegates gesture related event registration and handling to Hammer.js.\nexport class EventManager {\n private element: HTMLElement | null;\n private manager: HammerManager;\n private options: Required;\n private events: Map;\n\n // Custom handlers\n private wheelInput: WheelInput;\n private moveInput: MoveInput;\n private contextmenuInput: ContextmenuInput;\n private keyInput: KeyInput;\n\n constructor(element: HTMLElement | null = null, options: EventManagerOptions = {}) {\n this.options = {\n recognizers: [],\n events: {},\n touchAction: 'compute',\n tabIndex: 0,\n cssProps: {},\n ...options\n };\n this.events = new Map();\n this.element = element;\n\n if (!element) return;\n\n this.manager = new HammerManager(element, this.options);\n for (const item of this.options.recognizers) {\n const {recognizer, recognizeWith, requireFailure} = normalizeRecognizer(item);\n this.manager.add(recognizer);\n if (recognizeWith) {\n recognizer.recognizeWith(recognizeWith);\n }\n if (requireFailure) {\n recognizer.requireFailure(requireFailure);\n }\n }\n\n this.manager.on('hammer.input', this._onBasicInput);\n\n // Handle events not handled by Hammer.js:\n // - mouse wheel\n // - pointer/touch/mouse move\n this.wheelInput = new WheelInput(element, this._onOtherEvent, {\n enable: false\n });\n this.moveInput = new MoveInput(element, this._onOtherEvent, {\n enable: false\n });\n this.keyInput = new KeyInput(element, this._onOtherEvent, {\n enable: false,\n tabIndex: options.tabIndex\n });\n this.contextmenuInput = new ContextmenuInput(element, this._onOtherEvent, {\n enable: false\n });\n\n // Register all passed events.\n this.on(this.options.events);\n }\n\n getElement(): HTMLElement | null {\n return this.element;\n }\n\n // Tear down internal event management implementations.\n destroy(): void {\n // manager etc. cannot exist if there is no element\n if (!this.element) return;\n\n this.wheelInput.destroy();\n this.moveInput.destroy();\n this.keyInput.destroy();\n this.contextmenuInput.destroy();\n this.manager.destroy();\n }\n\n /** Register multiple event handlers */\n on(events: MjolnirEventHandlers, opts?: HandlerOptions): void;\n on(\n event: EventT['type'],\n handler: (ev: EventT) => void,\n opts?: HandlerOptions\n ): void;\n\n /** Register an event handler function to be called on `event` */\n on(event: any, handler: any, opts?: any) {\n this._addEventHandler(event, handler, opts, false);\n }\n\n /** Register an event handler function to be called on `event`, then remove it */\n once(events: MjolnirEventHandlers, opts?: HandlerOptions): void;\n once(\n event: EventT['type'],\n handler: (ev: EventT) => void,\n opts?: HandlerOptions\n ): void;\n\n once(event: any, handler: any, opts?: any) {\n this._addEventHandler(event, handler, opts, true);\n }\n\n /** Register an event handler function to be called on `event`\n * This handler does not ask the event to be recognized at all times.\n * Instead, it only \"intercepts\" the event if some other handler is getting it.\n */\n watch(events: MjolnirEventHandlers, opts?: HandlerOptions): void;\n watch(\n event: EventT['type'],\n handler: (ev: EventT) => void,\n opts?: HandlerOptions\n ): void;\n\n watch(event: any, handler: any, opts?: any) {\n this._addEventHandler(event, handler, opts, false, true);\n }\n\n /**\n * Deregister a previously-registered event handler.\n */\n off(events: MjolnirEventHandlers): void;\n off(event: EventT['type'], handler: (ev: EventT) => void): void;\n\n off(event: any, handler?: any) {\n this._removeEventHandler(event, handler);\n }\n\n /*\n * Enable/disable recognizer for the given event\n */\n private _toggleRecognizer(name: string, enabled: boolean): void {\n const {manager} = this;\n if (!manager) {\n return;\n }\n const recognizer = manager.get(name);\n if (recognizer) {\n recognizer.set({enable: enabled});\n manager.touchAction.update();\n }\n this.wheelInput?.enableEventType(name, enabled);\n this.moveInput?.enableEventType(name, enabled);\n this.keyInput?.enableEventType(name, enabled);\n this.contextmenuInput?.enableEventType(name, enabled);\n }\n\n /**\n * Process the event registration for a single event + handler.\n */\n private _addEventHandler(\n event: string | MjolnirEventHandlers,\n handler: MjolnirEventHandler,\n opts?: HandlerOptions,\n once?: boolean,\n passive?: boolean\n ) {\n if (typeof event !== 'string') {\n // @ts-ignore\n opts = handler;\n // If `event` is a map, call `on()` for each entry.\n for (const [eventName, eventHandler] of Object.entries(event)) {\n this._addEventHandler(eventName, eventHandler, opts, once, passive);\n }\n return;\n }\n\n const {manager, events} = this;\n if (!manager) return;\n\n let eventRegistrar = events.get(event);\n if (!eventRegistrar) {\n // Enable recognizer for this event.\n const recognizerName = this._getRecognizerName(event) || event;\n\n eventRegistrar = new EventRegistrar(this, recognizerName);\n events.set(event, eventRegistrar);\n // Listen to the event\n if (manager) {\n manager.on(event, eventRegistrar.handleEvent);\n }\n }\n eventRegistrar.add(event, handler, opts, once, passive);\n if (!eventRegistrar.isEmpty()) {\n this._toggleRecognizer(eventRegistrar.recognizerName, true);\n }\n }\n\n /**\n * Process the event deregistration for a single event + handler.\n */\n private _removeEventHandler(event: string | MjolnirEventHandlers, handler?: MjolnirEventHandler) {\n if (typeof event !== 'string') {\n // If `event` is a map, call `off()` for each entry.\n for (const [eventName, eventHandler] of Object.entries(event)) {\n this._removeEventHandler(eventName, eventHandler);\n }\n return;\n }\n\n const {events} = this;\n\n const eventRegistrar = events.get(event);\n\n if (!eventRegistrar) {\n return;\n }\n\n eventRegistrar.remove(event, handler!);\n\n if (eventRegistrar.isEmpty()) {\n const {recognizerName} = eventRegistrar;\n // Disable recognizer if no more handlers are attached to its events\n let isRecognizerUsed = false;\n for (const eh of events.values()) {\n if (eh.recognizerName === recognizerName && !eh.isEmpty()) {\n isRecognizerUsed = true;\n break;\n }\n }\n if (!isRecognizerUsed) {\n this._toggleRecognizer(recognizerName, false);\n }\n }\n }\n\n private _getRecognizerName(event: string): string | undefined {\n return this.manager.recognizers.find((recognizer) => {\n return recognizer.getEventNames().includes(event);\n })?.options.event;\n }\n\n /**\n * Handle basic events using the 'hammer.input' Hammer.js API:\n * Before running Recognizers, Hammer emits a 'hammer.input' event\n * with the basic event info. This function emits all basic events\n * aliased to the \"class\" of event received.\n * See constants.BASIC_EVENT_CLASSES basic event class definitions.\n */\n private _onBasicInput = (event: MjolnirEventRaw) => {\n this.manager.emit(event.srcEvent.type, event as any);\n };\n\n /**\n * Handle events not supported by Hammer.js,\n * and pipe back out through same (Hammer) channel used by other events.\n */\n private _onOtherEvent = (event: MjolnirEventRaw) => {\n // console.log('onotherevent', event.type, event)\n this.manager.emit(event.type, event as any);\n };\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport log from '../utils/log';\nimport {Pan, InputDirection, Pinch, Tap} from 'mjolnir.js';\nimport type {PanRecognizerOptions, PinchRecognizerOptions, TapRecognizerOptions} from 'mjolnir.js';\n\n/**\n * The coordinate system that positions/dimensions are defined in.\n */\nexport type CoordinateSystem =\n | 'default'\n | 'lnglat'\n | 'meter-offsets'\n | 'lnglat-offsets'\n | 'cartesian';\n\n/**\n * The coordinate system that positions/dimensions are defined in.\n * String constants are the public API.\n * @deprecated Use string constants directly.\n */\nexport const COORDINATE_SYSTEM = {\n /**\n * `LNGLAT` if rendering into a geospatial viewport, `CARTESIAN` otherwise\n */\n DEFAULT: 'default',\n /**\n * Positions are interpreted as [longitude, latitude, elevation]\n * longitude/latitude are in degrees, elevation is in meters.\n * Dimensions are in meters.\n */\n LNGLAT: 'lnglat',\n\n /**\n * Positions are interpreted as [x, y, z] in meter offsets from the coordinate origin.\n * Dimensions are in meters.\n */\n METER_OFFSETS: 'meter-offsets',\n\n /**\n * Positions are interpreted as [deltaLng, deltaLat, elevation] from the coordinate origin.\n * deltaLng/deltaLat are in degrees, elevation is in meters.\n * Dimensions are in meters.\n */\n LNGLAT_OFFSETS: 'lnglat-offsets',\n\n /**\n * Positions and dimensions are in the common units of the viewport.\n */\n CARTESIAN: 'cartesian'\n} as const;\n\n// Deprecated\n/* eslint-disable accessor-pairs */\nObject.defineProperty(COORDINATE_SYSTEM, 'IDENTITY', {\n get: () => {\n log.deprecated('COORDINATE_SYSTEM.IDENTITY', 'COORDINATE_SYSTEM.CARTESIAN')();\n return COORDINATE_SYSTEM.CARTESIAN;\n }\n});\n/* eslint-enable accessor-pairs */\n\n/**\n * How coordinates are transformed from the world space into the common space.\n */\nexport const PROJECTION_MODE = {\n /**\n * Render geospatial data in Web Mercator projection\n */\n WEB_MERCATOR: 1,\n /**\n * Render geospatial data as a 3D globe\n */\n GLOBE: 2,\n\n /**\n * (Internal use only) Web Mercator projection at high zoom\n */\n WEB_MERCATOR_AUTO_OFFSET: 4,\n\n /**\n * No transformation\n */\n IDENTITY: 0\n} as const;\n\nexport const UNIT = {\n common: 0,\n meters: 1,\n pixels: 2\n} as const;\n\nexport const EVENT_HANDLERS = {\n click: 'onClick',\n dblclick: 'onClick',\n panstart: 'onDragStart',\n panmove: 'onDrag',\n panend: 'onDragEnd'\n} as const satisfies {[eventName: string]: string};\n\nexport const RECOGNIZERS = {\n multipan: [Pan, {threshold: 10, direction: InputDirection.Vertical, pointers: 2}],\n pinch: [Pinch, {}, null, ['multipan']],\n pan: [Pan, {threshold: 1}, ['pinch'], ['multipan']],\n dblclick: [Tap, {event: 'dblclick', taps: 2}],\n click: [Tap, {event: 'click'}, null, ['dblclick']]\n} as const;\n\nexport type RecognizerOptions = {\n pinch?: Omit;\n multipan?: Omit;\n pan?: Omit;\n dblclick?: Omit;\n click?: Omit;\n};\n\n/**\n * @deprecated Use string constants directly\n */\nexport const OPERATION = {\n DRAW: 'draw',\n MASK: 'mask',\n TERRAIN: 'terrain'\n} as const;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nfunction isEqual(a, b) {\n if (a === b) {\n return true;\n }\n if (Array.isArray(a)) {\n // Special treatment for arrays: compare 1-level deep\n // This is to support equality of matrix/coordinate props\n const len = a.length;\n if (!b || b.length !== len) {\n return false;\n }\n\n for (let i = 0; i < len; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n }\n return false;\n}\n\n/**\n * Speed up consecutive function calls by caching the result of calls with identical input\n * https://en.wikipedia.org/wiki/Memoization\n * @param {function} compute - the function to be memoized\n */\nexport default function memoize(compute: (args: In) => Out): (args: In) => Out {\n let cachedArgs: any = {};\n let cachedResult: Out;\n\n return (args: In) => {\n for (const key in args) {\n if (!isEqual(args[key], cachedArgs[key])) {\n cachedResult = compute(args);\n cachedArgs = args;\n break;\n }\n }\n return cachedResult;\n };\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/* eslint-disable complexity, camelcase */\n\nimport {mat4, Matrix4Like, vec4} from '@math.gl/core';\n\nimport {PROJECTION_MODE} from '../../lib/constants';\n\nimport memoize from '../../utils/memoize';\n\nimport type Viewport from '../../viewports/viewport';\nimport type {CoordinateSystem} from '../../lib/constants';\n\ntype Vec3 = [number, number, number];\ntype Vec4 = [number, number, number, number];\n\n// To quickly set a vector to zero\nconst ZERO_VECTOR: Vec4 = [0, 0, 0, 0];\n// 4x4 matrix that drops 4th component of vector\nconst VECTOR_TO_POINT_MATRIX: Matrix4Like = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0];\nconst IDENTITY_MATRIX: Matrix4Like = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];\nconst DEFAULT_PIXELS_PER_UNIT2: Vec3 = [0, 0, 0];\nconst DEFAULT_COORDINATE_ORIGIN: Vec3 = [0, 0, 0];\n\n/** Coordinate system constants */\nconst COORDINATE_SYSTEM_NUMBERS = {\n default: -1,\n cartesian: 0,\n lnglat: 1,\n 'meter-offsets': 2,\n 'lnglat-offsets': 3\n} as const satisfies Record;\n\nexport function getShaderCoordinateSystem(coordinateSystem: CoordinateSystem) {\n const shaderCoordinateSystem = COORDINATE_SYSTEM_NUMBERS[coordinateSystem];\n if (shaderCoordinateSystem === undefined) {\n throw new Error(`Invalid coordinateSystem: ${coordinateSystem}`);\n }\n return shaderCoordinateSystem;\n}\n\nconst getMemoizedViewportUniforms = memoize(calculateViewportUniforms);\n\nexport function getOffsetOrigin(\n viewport: Viewport,\n coordinateSystem: CoordinateSystem,\n coordinateOrigin: Vec3 = DEFAULT_COORDINATE_ORIGIN\n): {\n geospatialOrigin: Vec3 | null;\n shaderCoordinateOrigin: Vec3;\n offsetMode: boolean;\n} {\n if (coordinateOrigin.length < 3) {\n coordinateOrigin = [coordinateOrigin[0], coordinateOrigin[1], 0];\n }\n\n let shaderCoordinateOrigin = coordinateOrigin;\n let geospatialOrigin: Vec3 | null;\n let offsetMode = true;\n\n if (coordinateSystem === 'lnglat-offsets' || coordinateSystem === 'meter-offsets') {\n geospatialOrigin = coordinateOrigin;\n } else {\n geospatialOrigin = viewport.isGeospatial\n ? // @ts-expect-error longitude and latitude are not defined on the base Viewport, but is expected on geospatial viewports\n [Math.fround(viewport.longitude), Math.fround(viewport.latitude), 0]\n : null;\n }\n\n switch (viewport.projectionMode) {\n case PROJECTION_MODE.WEB_MERCATOR:\n if (coordinateSystem === 'lnglat' || coordinateSystem === 'cartesian') {\n geospatialOrigin = [0, 0, 0];\n offsetMode = false;\n }\n break;\n\n case PROJECTION_MODE.WEB_MERCATOR_AUTO_OFFSET:\n if (coordinateSystem === 'lnglat') {\n // viewport center in world space\n // @ts-expect-error when using LNGLAT coordinates, we expect the viewport to be geospatial, in which case geospatialOrigin is defined\n shaderCoordinateOrigin = geospatialOrigin;\n } else if (coordinateSystem === 'cartesian') {\n // viewport center in common space\n shaderCoordinateOrigin = [\n Math.fround(viewport.center[0]),\n Math.fround(viewport.center[1]),\n 0\n ];\n // Geospatial origin (wgs84) must match shaderCoordinateOrigin (common)\n geospatialOrigin = viewport.unprojectPosition(shaderCoordinateOrigin);\n shaderCoordinateOrigin[0] -= coordinateOrigin[0];\n shaderCoordinateOrigin[1] -= coordinateOrigin[1];\n shaderCoordinateOrigin[2] -= coordinateOrigin[2];\n }\n break;\n\n case PROJECTION_MODE.IDENTITY:\n shaderCoordinateOrigin = viewport.position.map(Math.fround) as Vec3;\n shaderCoordinateOrigin[2] = shaderCoordinateOrigin[2] || 0;\n break;\n\n case PROJECTION_MODE.GLOBE:\n offsetMode = false;\n geospatialOrigin = null;\n break;\n\n default:\n // Unknown projection mode\n offsetMode = false;\n }\n\n return {geospatialOrigin, shaderCoordinateOrigin, offsetMode};\n}\n\n// The code that utilizes Matrix4 does the same calculation as their mat4 counterparts,\n// has lower performance but provides error checking.\nfunction calculateMatrixAndOffset(\n viewport: Viewport,\n coordinateSystem: CoordinateSystem,\n coordinateOrigin: Vec3\n): {\n viewMatrix: Matrix4Like;\n viewProjectionMatrix: Matrix4Like;\n projectionCenter: Vec4;\n originCommon: Vec4;\n cameraPosCommon: Vec3;\n shaderCoordinateOrigin: Vec3;\n geospatialOrigin: Vec3 | null;\n} {\n const {viewMatrixUncentered, projectionMatrix} = viewport;\n let {viewMatrix, viewProjectionMatrix} = viewport;\n\n let projectionCenter = ZERO_VECTOR;\n let originCommon: Vec4 = ZERO_VECTOR;\n let cameraPosCommon: Vec3 = viewport.cameraPosition as Vec3;\n const {geospatialOrigin, shaderCoordinateOrigin, offsetMode} = getOffsetOrigin(\n viewport,\n coordinateSystem,\n coordinateOrigin\n );\n\n if (offsetMode) {\n // Calculate transformed projectionCenter (using 64 bit precision JS)\n // This is the key to offset mode precision\n // (avoids doing this addition in 32 bit precision in GLSL)\n // @ts-expect-error the 4th component is assigned below\n originCommon = viewport.projectPosition(geospatialOrigin || shaderCoordinateOrigin);\n\n cameraPosCommon = [\n cameraPosCommon[0] - originCommon[0],\n cameraPosCommon[1] - originCommon[1],\n cameraPosCommon[2] - originCommon[2]\n ];\n\n originCommon[3] = 1;\n\n // projectionCenter = new Matrix4(viewProjectionMatrix)\n // .transformVector([positionPixels[0], positionPixels[1], 0.0, 1.0]);\n projectionCenter = vec4.transformMat4([], originCommon, viewProjectionMatrix);\n\n // Always apply uncentered projection matrix if available (shader adds center)\n viewMatrix = viewMatrixUncentered || viewMatrix;\n\n // Zero out 4th coordinate (\"after\" model matrix) - avoids further translations\n // viewMatrix = new Matrix4(viewMatrixUncentered || viewMatrix)\n // .multiplyRight(VECTOR_TO_POINT_MATRIX);\n viewProjectionMatrix = mat4.multiply([], projectionMatrix, viewMatrix);\n viewProjectionMatrix = mat4.multiply([], viewProjectionMatrix, VECTOR_TO_POINT_MATRIX);\n }\n\n return {\n viewMatrix: viewMatrix as Matrix4Like,\n viewProjectionMatrix: viewProjectionMatrix as Matrix4Like,\n projectionCenter,\n originCommon,\n cameraPosCommon,\n shaderCoordinateOrigin,\n geospatialOrigin\n };\n}\n\nexport type ProjectUniforms = {\n coordinateSystem: number;\n projectionMode: number;\n coordinateOrigin: Vec3;\n commonOrigin: Vec3;\n center: Vec4;\n // Backward compatibility\n // TODO: remove in v9\n pseudoMeters: boolean;\n\n // Screen size\n viewportSize: [number, number];\n devicePixelRatio: number;\n\n focalDistance: number;\n commonUnitsPerMeter: Vec3;\n commonUnitsPerWorldUnit: Vec3;\n commonUnitsPerWorldUnit2: Vec3;\n /** 2^zoom */\n scale: number;\n wrapLongitude: boolean;\n\n viewProjectionMatrix: Matrix4Like;\n modelMatrix: Matrix4Like;\n\n // This is for lighting calculations\n cameraPosition: Vec3;\n};\n\nexport type ProjectProps = {\n viewport: Viewport;\n devicePixelRatio?: number;\n modelMatrix?: Matrix4Like | null;\n coordinateSystem?: CoordinateSystem;\n coordinateOrigin?: Vec3;\n autoWrapLongitude?: boolean;\n};\n\n/**\n * Returns uniforms for shaders based on current projection\n * includes: projection matrix suitable for shaders\n *\n * TODO - Ensure this works with any viewport, not just WebMercatorViewports\n *\n * @param {WebMercatorViewport} viewport -\n * @return {Float32Array} - 4x4 projection matrix that can be used in shaders\n */\nexport function getUniformsFromViewport({\n viewport,\n devicePixelRatio = 1,\n modelMatrix = null,\n // Match Layer.defaultProps\n coordinateSystem = 'default',\n coordinateOrigin = DEFAULT_COORDINATE_ORIGIN,\n autoWrapLongitude = false\n}: ProjectProps): ProjectUniforms {\n if (coordinateSystem === 'default') {\n coordinateSystem = viewport.isGeospatial ? 'lnglat' : 'cartesian';\n }\n\n const uniforms = getMemoizedViewportUniforms({\n viewport,\n devicePixelRatio,\n coordinateSystem,\n coordinateOrigin\n });\n\n uniforms.wrapLongitude = autoWrapLongitude;\n uniforms.modelMatrix = modelMatrix || IDENTITY_MATRIX;\n\n return uniforms;\n}\n\nfunction calculateViewportUniforms({\n viewport,\n devicePixelRatio,\n coordinateSystem,\n coordinateOrigin\n}: {\n viewport: Viewport;\n devicePixelRatio: number;\n coordinateSystem: CoordinateSystem;\n coordinateOrigin: Vec3;\n}): ProjectUniforms {\n const {\n projectionCenter,\n viewProjectionMatrix,\n originCommon,\n cameraPosCommon,\n shaderCoordinateOrigin,\n geospatialOrigin\n } = calculateMatrixAndOffset(viewport, coordinateSystem, coordinateOrigin);\n\n // Calculate projection pixels per unit\n const distanceScales = viewport.getDistanceScales();\n\n const viewportSize: [number, number] = [\n viewport.width * devicePixelRatio,\n viewport.height * devicePixelRatio\n ];\n\n // Distance at which screen pixels are projected.\n // Used to scale sizes in clipspace to match screen pixels.\n // When using Viewport class's default projection matrix, this yields 1 for orthographic\n // and `viewport.focalDistance` for perspective views\n const focalDistance =\n vec4.transformMat4([], [0, 0, -viewport.focalDistance, 1], viewport.projectionMatrix)[3] || 1;\n\n const uniforms: ProjectUniforms = {\n // Projection mode values\n coordinateSystem: getShaderCoordinateSystem(coordinateSystem),\n projectionMode: viewport.projectionMode,\n coordinateOrigin: shaderCoordinateOrigin,\n commonOrigin: originCommon.slice(0, 3) as Vec3,\n center: projectionCenter,\n\n // Backward compatibility\n // TODO: remove in v9\n // @ts-expect-error _pseudoMeters is only defined on WebMercator viewport\n pseudoMeters: Boolean(viewport._pseudoMeters),\n\n // Screen size\n viewportSize,\n devicePixelRatio,\n\n focalDistance,\n commonUnitsPerMeter: distanceScales.unitsPerMeter as Vec3,\n commonUnitsPerWorldUnit: distanceScales.unitsPerMeter as Vec3,\n commonUnitsPerWorldUnit2: DEFAULT_PIXELS_PER_UNIT2,\n scale: viewport.scale, // This is the mercator scale (2 ** zoom)\n wrapLongitude: false,\n\n viewProjectionMatrix,\n modelMatrix: IDENTITY_MATRIX,\n\n // This is for lighting calculations\n cameraPosition: cameraPosCommon\n };\n\n if (geospatialOrigin) {\n // Get high-precision DistanceScales from geospatial viewport\n // TODO: stricter types in Viewport classes\n const distanceScalesAtOrigin = viewport.getDistanceScales(geospatialOrigin) as {\n unitsPerMeter: Vec3;\n metersPerUnit: Vec3;\n unitsPerMeter2: Vec3;\n unitsPerDegree: Vec3;\n degreesPerUnit: Vec3;\n unitsPerDegree2: Vec3;\n };\n switch (coordinateSystem) {\n case 'meter-offsets':\n uniforms.commonUnitsPerWorldUnit = distanceScalesAtOrigin.unitsPerMeter;\n uniforms.commonUnitsPerWorldUnit2 = distanceScalesAtOrigin.unitsPerMeter2;\n break;\n\n case 'lnglat':\n case 'lnglat-offsets':\n // @ts-expect-error _pseudoMeters only exists on WebMercatorView\n if (!viewport._pseudoMeters) {\n uniforms.commonUnitsPerMeter = distanceScalesAtOrigin.unitsPerMeter;\n }\n uniforms.commonUnitsPerWorldUnit = distanceScalesAtOrigin.unitsPerDegree;\n uniforms.commonUnitsPerWorldUnit2 = distanceScalesAtOrigin.unitsPerDegree2;\n break;\n\n // a.k.a \"preprojected\" positions\n case 'cartesian':\n uniforms.commonUnitsPerWorldUnit = [1, 1, distanceScalesAtOrigin.unitsPerMeter[2]];\n uniforms.commonUnitsPerWorldUnit2 = [0, 0, distanceScalesAtOrigin.unitsPerMeter2[2]];\n break;\n\n default:\n break;\n }\n }\n\n return uniforms;\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {PROJECTION_MODE, UNIT} from '../../lib/constants';\nimport {getShaderCoordinateSystem} from './viewport-uniforms';\n\nconst SHADER_COORDINATE_SYSTEMS = [\n 'default',\n 'lnglat',\n 'meter-offsets',\n 'lnglat-offsets',\n 'cartesian'\n] as const;\n\nconst COORDINATE_SYSTEM_WGSL_CONSTANTS = SHADER_COORDINATE_SYSTEMS.map(\n coordinateSystem =>\n `const COORDINATE_SYSTEM_${coordinateSystem.toUpperCase().replaceAll('-', '_')}: i32 = ${getShaderCoordinateSystem(coordinateSystem)};`\n).join('');\nconst PROJECTION_MODE_WGSL_CONSTANTS = Object.keys(PROJECTION_MODE)\n .map(key => `const PROJECTION_MODE_${key}: i32 = ${PROJECTION_MODE[key]};`)\n .join('');\nconst UNIT_WGSL_CONSTANTS = Object.keys(UNIT)\n .map(key => `const UNIT_${key.toUpperCase()}: i32 = ${UNIT[key]};`)\n .join('');\n\nexport const projectWGSLHeader = /* wgsl */ `\\\n${COORDINATE_SYSTEM_WGSL_CONSTANTS}\n${PROJECTION_MODE_WGSL_CONSTANTS}\n${UNIT_WGSL_CONSTANTS}\n\nconst TILE_SIZE: f32 = 512.0;\nconst PI: f32 = 3.1415926536;\nconst WORLD_SCALE: f32 = TILE_SIZE / (PI * 2.0);\nconst ZERO_64_LOW: vec3 = vec3(0.0, 0.0, 0.0);\nconst EARTH_RADIUS: f32 = 6370972.0; // meters\nconst GLOBE_RADIUS: f32 = 256.0;\n\n// -----------------------------------------------------------------------------\n// Uniform block (converted from GLSL uniform block)\n// -----------------------------------------------------------------------------\nstruct ProjectUniforms {\n wrapLongitude: i32,\n coordinateSystem: i32,\n commonUnitsPerMeter: vec3,\n projectionMode: i32,\n scale: f32,\n commonUnitsPerWorldUnit: vec3,\n commonUnitsPerWorldUnit2: vec3,\n center: vec4,\n modelMatrix: mat4x4,\n viewProjectionMatrix: mat4x4,\n viewportSize: vec2,\n devicePixelRatio: f32,\n focalDistance: f32,\n cameraPosition: vec3,\n coordinateOrigin: vec3,\n commonOrigin: vec3,\n pseudoMeters: i32,\n};\n\n@group(0) @binding(auto)\nvar project: ProjectUniforms;\n\n// -----------------------------------------------------------------------------\n// Geometry data shared across the project helpers.\n// The active layer shader is responsible for populating this private module\n// state before calling the project functions below.\n// -----------------------------------------------------------------------------\n\n// Structure to carry additional geometry data used by deck.gl filters.\nstruct Geometry {\n worldPosition: vec3,\n worldPositionAlt: vec3,\n position: vec4,\n normal: vec3,\n uv: vec2,\n pickingColor: vec3,\n};\n\nvar geometry: Geometry;\n`;\n\nexport const projectWGSL = /* wgsl */ `\\\n${projectWGSLHeader}\n\n// -----------------------------------------------------------------------------\n// Functions\n// -----------------------------------------------------------------------------\n\n// Returns an adjustment factor for commonUnitsPerMeter\nfn _project_size_at_latitude(lat: f32) -> f32 {\n let y = clamp(lat, -89.9, 89.9);\n return 1.0 / cos(radians(y));\n}\n\n// Overloaded version: scales a value in meters at a given latitude.\nfn _project_size_at_latitude_m(meters: f32, lat: f32) -> f32 {\n return meters * project.commonUnitsPerMeter.z * _project_size_at_latitude(lat);\n}\n\n// Computes a non-linear scale factor based on geometry.\n// (Note: This function relies on \"geometry\" being provided.)\nfn project_size() -> f32 {\n if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR &&\n project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT &&\n project.pseudoMeters == 0) {\n if (geometry.position.w == 0.0) {\n return _project_size_at_latitude(geometry.worldPosition.y);\n }\n let y: f32 = geometry.position.y / TILE_SIZE * 2.0 - 1.0;\n let y2 = y * y;\n let y4 = y2 * y2;\n let y6 = y4 * y2;\n return 1.0 + 4.9348 * y2 + 4.0587 * y4 + 1.5642 * y6;\n }\n return 1.0;\n}\n\n// Overloads to scale offsets (meters to world units)\nfn project_size_float(meters: f32) -> f32 {\n return meters * project.commonUnitsPerMeter.z * project_size();\n}\n\nfn project_size_vec2(meters: vec2) -> vec2 {\n return meters * project.commonUnitsPerMeter.xy * project_size();\n}\n\nfn project_size_vec3(meters: vec3) -> vec3 {\n return meters * project.commonUnitsPerMeter * project_size();\n}\n\nfn project_size_vec4(meters: vec4) -> vec4 {\n return vec4(meters.xyz * project.commonUnitsPerMeter, meters.w);\n}\n\n// Returns a rotation matrix aligning the z‑axis with the given up vector.\nfn project_get_orientation_matrix(up: vec3) -> mat3x3 {\n let uz = normalize(up);\n let ux = select(\n vec3(1.0, 0.0, 0.0),\n normalize(vec3(uz.y, -uz.x, 0.0)),\n abs(uz.z) == 1.0\n );\n let uy = cross(uz, ux);\n return mat3x3(ux, uy, uz);\n}\n\n// Since WGSL does not support \"out\" parameters, we return a struct.\nstruct RotationResult {\n needsRotation: bool,\n transform: mat3x3,\n};\n\nfn project_needs_rotation(commonPosition: vec3) -> RotationResult {\n if (project.projectionMode == PROJECTION_MODE_GLOBE) {\n return RotationResult(true, project_get_orientation_matrix(commonPosition));\n } else {\n return RotationResult(false, mat3x3()); // identity alternative if needed\n };\n}\n\n// Projects a normal vector from the current coordinate system to world space.\nfn project_normal(vector: vec3) -> vec3 {\n let normal_modelspace = project.modelMatrix * vec4(vector, 0.0);\n var n = normalize(normal_modelspace.xyz * project.commonUnitsPerMeter);\n let rotResult = project_needs_rotation(geometry.position.xyz);\n if (rotResult.needsRotation) {\n n = rotResult.transform * n;\n }\n return n;\n}\n\n// Applies a scale offset based on y-offset (dy)\nfn project_offset_(offset: vec4) -> vec4 {\n let dy: f32 = offset.y;\n let commonUnitsPerWorldUnit = project.commonUnitsPerWorldUnit + project.commonUnitsPerWorldUnit2 * dy;\n return vec4(offset.xyz * commonUnitsPerWorldUnit, offset.w);\n}\n\n// Projects lng/lat coordinates to a unit tile [0,1]\nfn project_mercator_(lnglat: vec2) -> vec2 {\n var x = lnglat.x;\n if (project.wrapLongitude != 0) {\n x = ((x + 180.0) % 360.0) - 180.0;\n }\n let y = clamp(lnglat.y, -89.9, 89.9);\n return vec2(\n radians(x) + PI,\n PI + log(tan(PI * 0.25 + radians(y) * 0.5))\n ) * WORLD_SCALE;\n}\n\n// Projects lng/lat/z coordinates for a globe projection.\nfn project_globe_(lnglatz: vec3) -> vec3 {\n let lambda = radians(lnglatz.x);\n let phi = radians(lnglatz.y);\n let cosPhi = cos(phi);\n let D = (lnglatz.z / EARTH_RADIUS + 1.0) * GLOBE_RADIUS;\n return vec3(\n sin(lambda) * cosPhi,\n -cos(lambda) * cosPhi,\n sin(phi)\n ) * D;\n}\n\n// Projects positions (with an optional 64-bit low part) from the input\n// coordinate system to the common space.\nfn project_position_vec4_f64(position: vec4, position64Low: vec3) -> vec4 {\n var position_world = project.modelMatrix * position;\n\n // Work around for a Mac+NVIDIA bug:\n if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR) {\n if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) {\n return vec4(\n project_mercator_(position_world.xy),\n _project_size_at_latitude_m(position_world.z, position_world.y),\n position_world.w\n );\n }\n if (project.coordinateSystem == COORDINATE_SYSTEM_CARTESIAN) {\n position_world = vec4f(position_world.xyz + project.coordinateOrigin, position_world.w);\n }\n }\n if (project.projectionMode == PROJECTION_MODE_GLOBE) {\n if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) {\n return vec4(\n project_globe_(position_world.xyz),\n position_world.w\n );\n }\n }\n if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR_AUTO_OFFSET) {\n if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) {\n if (abs(position_world.y - project.coordinateOrigin.y) > 0.25) {\n return vec4(\n project_mercator_(position_world.xy) - project.commonOrigin.xy,\n project_size_float(position_world.z),\n position_world.w\n );\n }\n }\n }\n if (project.projectionMode == PROJECTION_MODE_IDENTITY ||\n (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR_AUTO_OFFSET &&\n (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT ||\n project.coordinateSystem == COORDINATE_SYSTEM_CARTESIAN))) {\n position_world = vec4f(position_world.xyz - project.coordinateOrigin, position_world.w);\n }\n\n return project_offset_(position_world) +\n project_offset_(project.modelMatrix * vec4(position64Low, 0.0));\n}\n\n// Overloaded versions for different input types.\nfn project_position_vec4_f32(position: vec4) -> vec4 {\n return project_position_vec4_f64(position, ZERO_64_LOW);\n}\n\nfn project_position_vec3_f64(position: vec3, position64Low: vec3) -> vec3 {\n let projected_position = project_position_vec4_f64(vec4(position, 1.0), position64Low);\n return projected_position.xyz;\n}\n\nfn project_position_vec3_f32(position: vec3) -> vec3 {\n let projected_position = project_position_vec4_f64(vec4(position, 1.0), ZERO_64_LOW);\n return projected_position.xyz;\n}\n\nfn project_position_vec2_f32(position: vec2) -> vec2 {\n let projected_position = project_position_vec4_f64(vec4(position, 0.0, 1.0), ZERO_64_LOW);\n return projected_position.xy;\n}\n\n// Transforms a common space position to clip space.\nfn project_common_position_to_clipspace_with_projection(position: vec4, viewProjectionMatrix: mat4x4, center: vec4) -> vec4 {\n return viewProjectionMatrix * position + center;\n}\n\n// Uses the project viewProjectionMatrix and center.\nfn project_common_position_to_clipspace(position: vec4) -> vec4 {\n return project_common_position_to_clipspace_with_projection(position, project.viewProjectionMatrix, project.center);\n}\n\n// Returns a clip space offset corresponding to a given number of screen pixels.\nfn project_pixel_size_to_clipspace(pixels: vec2) -> vec2 {\n let offset = pixels / project.viewportSize * project.devicePixelRatio * 2.0;\n return offset * project.focalDistance;\n}\n\nfn project_meter_size_to_pixel(meters: f32) -> f32 {\n return project_size_float(meters) * project.scale;\n}\n\nfn project_unit_size_to_pixel(size: f32, unit: i32) -> f32 {\n if (unit == UNIT_METERS) {\n return project_meter_size_to_pixel(size);\n } else if (unit == UNIT_COMMON) {\n return size * project.scale;\n }\n // UNIT_PIXELS: no scaling applied.\n return size;\n}\n\nfn project_pixel_size_float(pixels: f32) -> f32 {\n return pixels / project.scale;\n}\n\nfn project_pixel_size_vec2(pixels: vec2) -> vec2 {\n return pixels / project.scale;\n}\n`;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {PROJECTION_MODE, UNIT} from '../../lib/constants';\nimport {getShaderCoordinateSystem} from './viewport-uniforms';\n\nconst SHADER_COORDINATE_SYSTEMS = [\n 'default',\n 'lnglat',\n 'meter-offsets',\n 'lnglat-offsets',\n 'cartesian'\n] as const;\n\nconst COORDINATE_SYSTEM_GLSL_CONSTANTS = SHADER_COORDINATE_SYSTEMS.map(\n coordinateSystem =>\n `const int COORDINATE_SYSTEM_${coordinateSystem.toUpperCase().replaceAll('-', '_')} = ${getShaderCoordinateSystem(coordinateSystem)};`\n).join('');\nconst PROJECTION_MODE_GLSL_CONSTANTS = Object.keys(PROJECTION_MODE)\n .map(key => `const int PROJECTION_MODE_${key} = ${PROJECTION_MODE[key]};`)\n .join('');\nconst UNIT_GLSL_CONSTANTS = Object.keys(UNIT)\n .map(key => `const int UNIT_${key.toUpperCase()} = ${UNIT[key]};`)\n .join('');\n\nexport const projectGLSL = /* glsl */ `\\\n${COORDINATE_SYSTEM_GLSL_CONSTANTS}\n${PROJECTION_MODE_GLSL_CONSTANTS}\n${UNIT_GLSL_CONSTANTS}\n\nlayout(std140) uniform projectUniforms {\n bool wrapLongitude;\n int coordinateSystem;\n vec3 commonUnitsPerMeter;\n int projectionMode;\n float scale;\n vec3 commonUnitsPerWorldUnit;\n vec3 commonUnitsPerWorldUnit2;\n vec4 center;\n mat4 modelMatrix;\n mat4 viewProjectionMatrix;\n vec2 viewportSize;\n float devicePixelRatio;\n float focalDistance;\n vec3 cameraPosition;\n vec3 coordinateOrigin;\n vec3 commonOrigin;\n bool pseudoMeters;\n} project;\n\n\nconst float TILE_SIZE = 512.0;\nconst float PI = 3.1415926536;\nconst float WORLD_SCALE = TILE_SIZE / (PI * 2.0);\nconst vec3 ZERO_64_LOW = vec3(0.0);\nconst float EARTH_RADIUS = 6370972.0; // meters\nconst float GLOBE_RADIUS = 256.0;\n\n// returns an adjustment factor for uCommonUnitsPerMeter\nfloat project_size_at_latitude(float lat) {\n float y = clamp(lat, -89.9, 89.9);\n return 1.0 / cos(radians(y));\n}\n\nfloat project_size() {\n if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR &&\n project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT &&\n project.pseudoMeters == false) {\n\n // uCommonUnitsPerMeter in low-zoom Web Mercator is non-linear\n // Adjust by 1 / cos(latitude)\n // If geometry.position (vertex in common space) is populated, use it\n // Otherwise use geometry.worldPosition (anchor in world space)\n \n if (geometry.position.w == 0.0) {\n return project_size_at_latitude(geometry.worldPosition.y);\n }\n\n // latitude from common y: 2.0 * (atan(exp(y / TILE_SIZE * 2.0 * PI - PI)) - PI / 4.0)\n // Taylor series of 1 / cos(latitude)\n // Max error < 0.003\n \n float y = geometry.position.y / TILE_SIZE * 2.0 - 1.0;\n float y2 = y * y;\n float y4 = y2 * y2;\n float y6 = y4 * y2;\n return 1.0 + 4.9348 * y2 + 4.0587 * y4 + 1.5642 * y6;\n }\n return 1.0;\n}\n\nfloat project_size_at_latitude(float meters, float lat) {\n return meters * project.commonUnitsPerMeter.z * project_size_at_latitude(lat);\n}\n\n//\n// Scaling offsets - scales meters to \"world distance\"\n// Note the scalar version of project_size is for scaling the z component only\n//\nfloat project_size(float meters) {\n // For scatter relevant\n return meters * project.commonUnitsPerMeter.z * project_size();\n}\n\nvec2 project_size(vec2 meters) {\n return meters * project.commonUnitsPerMeter.xy * project_size();\n}\n\nvec3 project_size(vec3 meters) {\n return meters * project.commonUnitsPerMeter * project_size();\n}\n\nvec4 project_size(vec4 meters) {\n return vec4(meters.xyz * project.commonUnitsPerMeter, meters.w);\n}\n\n// Get rotation matrix that aligns the z axis with the given up vector\n// Find 3 unit vectors ux, uy, uz that are perpendicular to each other and uz == up\nmat3 project_get_orientation_matrix(vec3 up) {\n vec3 uz = normalize(up);\n // Tangent on XY plane\n vec3 ux = abs(uz.z) == 1.0 ? vec3(1.0, 0.0, 0.0) : normalize(vec3(uz.y, -uz.x, 0));\n vec3 uy = cross(uz, ux);\n return mat3(ux, uy, uz);\n}\n\nbool project_needs_rotation(vec3 commonPosition, out mat3 transform) {\n if (project.projectionMode == PROJECTION_MODE_GLOBE) {\n transform = project_get_orientation_matrix(commonPosition);\n return true;\n }\n return false;\n}\n\n//\n// Projecting normal - transform deltas from current coordinate system to\n// normals in the worldspace\n//\nvec3 project_normal(vec3 vector) {\n // Apply model matrix\n vec4 normal_modelspace = project.modelMatrix * vec4(vector, 0.0);\n vec3 n = normalize(normal_modelspace.xyz * project.commonUnitsPerMeter);\n mat3 rotation;\n if (project_needs_rotation(geometry.position.xyz, rotation)) {\n n = rotation * n;\n }\n return n;\n}\n\nvec4 project_offset_(vec4 offset) {\n float dy = offset.y;\n vec3 commonUnitsPerWorldUnit = project.commonUnitsPerWorldUnit + project.commonUnitsPerWorldUnit2 * dy;\n return vec4(offset.xyz * commonUnitsPerWorldUnit, offset.w);\n}\n\n//\n// Projecting positions - non-linear projection: lnglats => unit tile [0-1, 0-1]\n//\nvec2 project_mercator_(vec2 lnglat) {\n float x = lnglat.x;\n if (project.wrapLongitude) {\n x = mod(x + 180., 360.0) - 180.;\n }\n float y = clamp(lnglat.y, -89.9, 89.9);\n return vec2(\n radians(x) + PI,\n PI + log(tan_fp32(PI * 0.25 + radians(y) * 0.5))\n ) * WORLD_SCALE;\n}\n\nvec3 project_globe_(vec3 lnglatz) {\n float lambda = radians(lnglatz.x);\n float phi = radians(lnglatz.y);\n float cosPhi = cos(phi);\n float D = (lnglatz.z / EARTH_RADIUS + 1.0) * GLOBE_RADIUS;\n\n return vec3(\n sin(lambda) * cosPhi,\n -cos(lambda) * cosPhi,\n sin(phi)\n ) * D;\n}\n\n//\n// Projects positions (defined by project.coordinateSystem) to common space (defined by project.projectionMode)\n//\nvec4 project_position(vec4 position, vec3 position64Low) {\n vec4 position_world = project.modelMatrix * position;\n\n // Work around for a Mac+NVIDIA bug https://github.com/visgl/deck.gl/issues/4145\n if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR) {\n if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) {\n return vec4(\n project_mercator_(position_world.xy),\n project_size_at_latitude(position_world.z, position_world.y),\n position_world.w\n );\n }\n if (project.coordinateSystem == COORDINATE_SYSTEM_CARTESIAN) {\n position_world.xyz += project.coordinateOrigin;\n }\n }\n if (project.projectionMode == PROJECTION_MODE_GLOBE) {\n if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) {\n return vec4(\n project_globe_(position_world.xyz),\n position_world.w\n );\n }\n }\n if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR_AUTO_OFFSET) {\n if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) {\n if (abs(position_world.y - project.coordinateOrigin.y) > 0.25) {\n // Too far from the projection center for offset mode to be accurate\n // Only use high parts\n return vec4(\n project_mercator_(position_world.xy) - project.commonOrigin.xy,\n project_size(position_world.z),\n position_world.w\n );\n }\n }\n }\n if (project.projectionMode == PROJECTION_MODE_IDENTITY ||\n (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR_AUTO_OFFSET &&\n (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT ||\n project.coordinateSystem == COORDINATE_SYSTEM_CARTESIAN))) {\n // Subtract high part of 64 bit value. Convert remainder to float32, preserving precision.\n position_world.xyz -= project.coordinateOrigin;\n }\n\n // Translation is already added to the high parts\n return project_offset_(position_world) + project_offset_(project.modelMatrix * vec4(position64Low, 0.0));\n}\n\nvec4 project_position(vec4 position) {\n return project_position(position, ZERO_64_LOW);\n}\n\nvec3 project_position(vec3 position, vec3 position64Low) {\n vec4 projected_position = project_position(vec4(position, 1.0), position64Low);\n return projected_position.xyz;\n}\n\nvec3 project_position(vec3 position) {\n vec4 projected_position = project_position(vec4(position, 1.0), ZERO_64_LOW);\n return projected_position.xyz;\n}\n\nvec2 project_position(vec2 position) {\n vec4 projected_position = project_position(vec4(position, 0.0, 1.0), ZERO_64_LOW);\n return projected_position.xy;\n}\n\nvec4 project_common_position_to_clipspace(vec4 position, mat4 viewProjectionMatrix, vec4 center) {\n return viewProjectionMatrix * position + center;\n}\n\n//\n// Projects from common space coordinates to clip space.\n// Uses project.viewProjectionMatrix\n//\nvec4 project_common_position_to_clipspace(vec4 position) {\n return project_common_position_to_clipspace(position, project.viewProjectionMatrix, project.center);\n}\n\n// Returns a clip space offset that corresponds to a given number of screen pixels\nvec2 project_pixel_size_to_clipspace(vec2 pixels) {\n vec2 offset = pixels / project.viewportSize * project.devicePixelRatio * 2.0;\n return offset * project.focalDistance;\n}\n\nfloat project_size_to_pixel(float meters) {\n return project_size(meters) * project.scale;\n}\nvec2 project_size_to_pixel(vec2 meters) {\n return project_size(meters) * project.scale;\n}\nfloat project_size_to_pixel(float size, int unit) {\n if (unit == UNIT_METERS) return project_size_to_pixel(size);\n if (unit == UNIT_COMMON) return size * project.scale;\n // UNIT_PIXELS\n return size;\n}\nfloat project_pixel_size(float pixels) {\n return pixels / project.scale;\n}\nvec2 project_pixel_size(vec2 pixels) {\n return pixels / project.scale;\n}\n`;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {fp32, ShaderModule} from '@luma.gl/shadertools';\nimport geometry from '../misc/geometry';\nimport {getUniformsFromViewport} from './viewport-uniforms';\nimport {projectWGSL} from './project.wgsl';\nimport {projectGLSL} from './project.glsl';\n\nimport type {ProjectProps, ProjectUniforms} from './viewport-uniforms';\n\nconst INITIAL_MODULE_OPTIONS = {};\n\nfunction getUniforms(opts: ProjectProps | {} = INITIAL_MODULE_OPTIONS) {\n if ('viewport' in opts) {\n return getUniformsFromViewport(opts);\n }\n return {};\n}\n\nexport default {\n name: 'project',\n dependencies: [fp32, geometry],\n source: projectWGSL,\n vs: projectGLSL,\n getUniforms,\n uniformTypes: {\n wrapLongitude: 'f32',\n coordinateSystem: 'i32',\n commonUnitsPerMeter: 'vec3',\n projectionMode: 'i32',\n scale: 'f32',\n commonUnitsPerWorldUnit: 'vec3',\n commonUnitsPerWorldUnit2: 'vec3',\n center: 'vec4',\n modelMatrix: 'mat4x4',\n viewProjectionMatrix: 'mat4x4',\n viewportSize: 'vec2',\n devicePixelRatio: 'f32',\n focalDistance: 'f32',\n cameraPosition: 'vec3',\n coordinateOrigin: 'vec3',\n commonOrigin: 'vec3',\n pseudoMeters: 'f32'\n }\n // @ts-ignore TODO v9.1\n} as const satisfies ShaderModule;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ShaderModule} from '@luma.gl/shadertools';\nimport project from '../project/project';\n\nconst source = /* wgsl */ `\\\n// Define a structure to hold both the clip-space position and the common position.\nstruct ProjectResult {\n clipPosition: vec4,\n commonPosition: vec4,\n};\n\n// This function mimics the GLSL version with the 'out' parameter by returning both values.\nfn project_position_to_clipspace_and_commonspace(\n position: vec3,\n position64Low: vec3,\n offset: vec3\n) -> ProjectResult {\n // Compute the projected position.\n let projectedPosition: vec3 = project_position_vec3_f64(position, position64Low);\n\n // Start with the provided offset.\n var finalOffset: vec3 = offset;\n\n // Get whether a rotation is needed and the rotation matrix.\n let rotationResult = project_needs_rotation(projectedPosition);\n\n // If rotation is needed, update the offset.\n if (rotationResult.needsRotation) {\n finalOffset = rotationResult.transform * offset;\n }\n\n // Compute the common position.\n let commonPosition: vec4 = vec4(projectedPosition + finalOffset, 1.0);\n\n // Convert to clip-space.\n let clipPosition: vec4 = project_common_position_to_clipspace(commonPosition);\n\n return ProjectResult(clipPosition, commonPosition);\n}\n\n// A convenience overload that returns only the clip-space position.\nfn project_position_to_clipspace(\n position: vec3,\n position64Low: vec3,\n offset: vec3\n) -> vec4 {\n return project_position_to_clipspace_and_commonspace(position, position64Low, offset).clipPosition;\n}\n`;\n\nconst vs = /* glsl */ `\\\nvec4 project_position_to_clipspace(\n vec3 position, vec3 position64Low, vec3 offset, out vec4 commonPosition\n) {\n vec3 projectedPosition = project_position(position, position64Low);\n mat3 rotation;\n if (project_needs_rotation(projectedPosition, rotation)) {\n // offset is specified as ENU\n // when in globe projection, rotate offset so that the ground alighs with the surface of the globe\n offset = rotation * offset;\n }\n commonPosition = vec4(projectedPosition + offset, 1.0);\n return project_common_position_to_clipspace(commonPosition);\n}\n\nvec4 project_position_to_clipspace(\n vec3 position, vec3 position64Low, vec3 offset\n) {\n vec4 commonPosition;\n return project_position_to_clipspace(position, position64Low, offset, commonPosition);\n}\n`;\n\nexport default {\n name: 'project32',\n dependencies: [project],\n source,\n vs\n} as ShaderModule;\n","import {vec4} from '@math.gl/core';\n\n// Helper, avoids low-precision 32 bit matrices from gl-matrix mat4.create()\nexport function createMat4(): number[] {\n return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];\n}\n\n// Transforms a vec4 with a projection matrix\nexport function transformVector(matrix: number[], vector: number[]): number[] {\n const result = vec4.transformMat4([] as number[], vector, matrix);\n vec4.scale(result, result, 1 / result[3]);\n return result;\n}\n\nexport function mod(value: number, divisor: number): number {\n const modulus = value % divisor;\n return modulus < 0 ? divisor + modulus : modulus;\n}\n\nexport function lerp(start: number, end: number, step: number): number {\n return step * end + (1 - step) * start;\n}\n\nexport function clamp(x: number, min: number, max: number): number {\n return x < min ? min : x > max ? max : x;\n}\n\nfunction ieLog2(x: number): number {\n return Math.log(x) * Math.LOG2E;\n}\n// Handle missing log2 in IE 11\nexport const log2 = Math.log2 || ieLog2;\n","// Replacement for the external assert method to reduce bundle size\n// Note: We don't use the second \"message\" argument in calling code,\n// so no need to support it here\nexport function assert(condition: unknown, message?: string): void {\n if (!condition) {\n throw new Error(message || '@math.gl/web-mercator: assertion failed.');\n }\n}\n","// TODO - THE UTILITIES IN THIS FILE SHOULD BE IMPORTED FROM WEB-MERCATOR-VIEWPORT MODULE\n\nimport {createMat4, transformVector, clamp, log2} from './math-utils';\n\nimport {mat4, vec2, vec3} from '@math.gl/core';\nimport {assert} from './assert';\n\n// CONSTANTS\nconst PI = Math.PI;\nconst PI_4 = PI / 4;\nconst DEGREES_TO_RADIANS = PI / 180;\nconst RADIANS_TO_DEGREES = 180 / PI;\nconst TILE_SIZE = 512;\n// Average circumference (40075 km equatorial, 40007 km meridional)\nconst EARTH_CIRCUMFERENCE = 40.03e6;\n// Latitude that makes a square world, 2 * atan(E ** PI) - PI / 2\nexport const MAX_LATITUDE = 85.051129;\n\n// Mapbox default altitude\nexport const DEFAULT_ALTITUDE = 1.5;\n\nexport type DistanceScales = {\n unitsPerMeter: number[];\n metersPerUnit: number[];\n unitsPerMeter2?: number[];\n unitsPerDegree: number[];\n degreesPerUnit: number[];\n unitsPerDegree2?: number[];\n};\n\n/**\n * PROJECTION MATRIX PARAMETERS\n *\n * TODO how to document mebers\n * @param fov in radians. fov is variable, depends on pitch and altitude\n * @param aspect width/height\n * @param focalDistance distance at which visual scale factor is 1\n * @param near near clipping plane\n * @param far far clipping plane\n */\ntype ProjectionParameters = {\n fov: number;\n aspect: number;\n focalDistance: number;\n near: number;\n far: number;\n};\n\n/** Logarithimic zoom to linear scale **/\nexport function zoomToScale(zoom: number): number {\n return Math.pow(2, zoom);\n}\n\n/** Linear scale to logarithimic zoom **/\nexport function scaleToZoom(scale: number): number {\n return log2(scale);\n}\n\n/**\n * Project [lng,lat] on sphere onto [x,y] on 512*512 Mercator Zoom 0 tile.\n * Performs the nonlinear part of the web mercator projection.\n * Remaining projection is done with 4x4 matrices which also handles\n * perspective.\n *\n * @param lngLat - [lng, lat] coordinates\n * Specifies a point on the sphere to project onto the map.\n * @return [x,y] coordinates.\n */\nexport function lngLatToWorld(lngLat: number[]): [number, number] {\n const [lng, lat] = lngLat;\n assert(Number.isFinite(lng));\n assert(Number.isFinite(lat) && lat >= -90 && lat <= 90, 'invalid latitude');\n\n const lambda2 = lng * DEGREES_TO_RADIANS;\n const phi2 = lat * DEGREES_TO_RADIANS;\n const x = (TILE_SIZE * (lambda2 + PI)) / (2 * PI);\n const y = (TILE_SIZE * (PI + Math.log(Math.tan(PI_4 + phi2 * 0.5)))) / (2 * PI);\n return [x, y];\n}\n\n/**\n * Unproject world point [x,y] on map onto {lat, lon} on sphere\n *\n * @param xy - array with [x,y] members\n * representing point on projected map plane\n * @return - array with [x,y] of point on sphere.\n * Has toArray method if you need a GeoJSON Array.\n * Per cartographic tradition, lat and lon are specified as degrees.\n */\nexport function worldToLngLat(xy: number[]): [number, number] {\n const [x, y] = xy;\n const lambda2 = (x / TILE_SIZE) * (2 * PI) - PI;\n const phi2 = 2 * (Math.atan(Math.exp((y / TILE_SIZE) * (2 * PI) - PI)) - PI_4);\n return [lambda2 * RADIANS_TO_DEGREES, phi2 * RADIANS_TO_DEGREES];\n}\n\n/**\n * Returns the zoom level that gives a 1 meter pixel at a certain latitude\n * 1 = C*cos(y)/2^z/TILE_SIZE = C*cos(y)/2^(z+9)\n */\nexport function getMeterZoom(options: {latitude: number}): number {\n const {latitude} = options;\n assert(Number.isFinite(latitude));\n const latCosine = Math.cos(latitude * DEGREES_TO_RADIANS);\n return scaleToZoom(EARTH_CIRCUMFERENCE * latCosine) - 9;\n}\n\n/**\n * Calculate the conversion from meter to common units at a given latitude\n * This is a cheaper version of `getDistanceScales`\n * @param latitude center latitude in degrees\n * @returns common units per meter\n */\nexport function unitsPerMeter(latitude: number): number {\n const latCosine = Math.cos(latitude * DEGREES_TO_RADIANS);\n return TILE_SIZE / EARTH_CIRCUMFERENCE / latCosine;\n}\n\n/**\n * Calculate distance scales in meters around current lat/lon, both for\n * degrees and pixels.\n * In mercator projection mode, the distance scales vary significantly\n * with latitude.\n */\nexport function getDistanceScales(options: {\n latitude: number;\n longitude: number;\n highPrecision?: boolean;\n}): DistanceScales {\n const {latitude, longitude, highPrecision = false} = options;\n assert(Number.isFinite(latitude) && Number.isFinite(longitude));\n\n const worldSize = TILE_SIZE;\n const latCosine = Math.cos(latitude * DEGREES_TO_RADIANS);\n\n /**\n * Number of pixels occupied by one degree longitude around current lat/lon:\n unitsPerDegreeX = d(lngLatToWorld([lng, lat])[0])/d(lng)\n = scale * TILE_SIZE * DEGREES_TO_RADIANS / (2 * PI)\n unitsPerDegreeY = d(lngLatToWorld([lng, lat])[1])/d(lat)\n = -scale * TILE_SIZE * DEGREES_TO_RADIANS / cos(lat * DEGREES_TO_RADIANS) / (2 * PI)\n */\n const unitsPerDegreeX = worldSize / 360;\n const unitsPerDegreeY = unitsPerDegreeX / latCosine;\n\n /**\n * Number of pixels occupied by one meter around current lat/lon:\n */\n const altUnitsPerMeter = worldSize / EARTH_CIRCUMFERENCE / latCosine;\n\n /**\n * LngLat: longitude -> east and latitude -> north (bottom left)\n * UTM meter offset: x -> east and y -> north (bottom left)\n * World space: x -> east and y -> south (top left)\n *\n * Y needs to be flipped when converting delta degree/meter to delta pixels\n */\n const result: DistanceScales = {\n unitsPerMeter: [altUnitsPerMeter, altUnitsPerMeter, altUnitsPerMeter],\n metersPerUnit: [1 / altUnitsPerMeter, 1 / altUnitsPerMeter, 1 / altUnitsPerMeter],\n\n unitsPerDegree: [unitsPerDegreeX, unitsPerDegreeY, altUnitsPerMeter],\n degreesPerUnit: [1 / unitsPerDegreeX, 1 / unitsPerDegreeY, 1 / altUnitsPerMeter]\n };\n\n /**\n * Taylor series 2nd order for 1/latCosine\n f'(a) * (x - a)\n = d(1/cos(lat * DEGREES_TO_RADIANS))/d(lat) * dLat\n = DEGREES_TO_RADIANS * tan(lat * DEGREES_TO_RADIANS) / cos(lat * DEGREES_TO_RADIANS) * dLat\n */\n if (highPrecision) {\n const latCosine2 = (DEGREES_TO_RADIANS * Math.tan(latitude * DEGREES_TO_RADIANS)) / latCosine;\n const unitsPerDegreeY2 = (unitsPerDegreeX * latCosine2) / 2;\n const altUnitsPerDegree2 = (worldSize / EARTH_CIRCUMFERENCE) * latCosine2;\n const altUnitsPerMeter2 = (altUnitsPerDegree2 / unitsPerDegreeY) * altUnitsPerMeter;\n\n result.unitsPerDegree2 = [0, unitsPerDegreeY2, altUnitsPerDegree2];\n result.unitsPerMeter2 = [altUnitsPerMeter2, 0, altUnitsPerMeter2];\n }\n\n // Main results, used for converting meters to latlng deltas and scaling offsets\n return result;\n}\n\n/**\n * Offset a lng/lat position by meterOffset (northing, easting)\n */\nexport function addMetersToLngLat(lngLatZ: number[], xyz: number[]): number[] {\n const [longitude, latitude, z0] = lngLatZ;\n const [x, y, z] = xyz;\n\n // eslint-disable-next-line no-shadow\n const {unitsPerMeter, unitsPerMeter2} = getDistanceScales({\n longitude,\n latitude,\n highPrecision: true\n });\n\n const worldspace = lngLatToWorld(lngLatZ);\n worldspace[0] += x * (unitsPerMeter[0] + unitsPerMeter2[0] * y);\n worldspace[1] += y * (unitsPerMeter[1] + unitsPerMeter2[1] * y);\n\n const newLngLat = worldToLngLat(worldspace);\n const newZ = (z0 || 0) + (z || 0);\n\n return Number.isFinite(z0) || Number.isFinite(z) ? [newLngLat[0], newLngLat[1], newZ] : newLngLat;\n}\n\n/**\n *\n * view and projection matrix creation is intentionally kept compatible with\n * mapbox-gl's implementation to ensure that seamless interoperation\n * with mapbox and react-map-gl. See: https://github.com/mapbox/mapbox-gl-js\n */\nexport function getViewMatrix(options: {\n // Viewport props\n height: number;\n pitch: number;\n bearing: number;\n altitude: number;\n // Pre-calculated parameters\n scale: number;\n center?: number[];\n}): number[] {\n const {\n // Viewport props\n height,\n pitch,\n bearing,\n altitude,\n // Pre-calculated parameters\n scale,\n center\n } = options;\n // VIEW MATRIX: PROJECTS MERCATOR WORLD COORDINATES\n // Note that mercator world coordinates typically need to be flipped\n //\n // Note: As usual, matrix operation orders should be read in reverse\n // since vectors will be multiplied from the right during transformation\n const vm = createMat4();\n\n // Move camera to altitude (along the pitch & bearing direction)\n mat4.translate(vm, vm, [0, 0, -altitude]);\n\n // Rotate by bearing, and then by pitch (which tilts the view)\n mat4.rotateX(vm, vm, -pitch * DEGREES_TO_RADIANS);\n mat4.rotateZ(vm, vm, bearing * DEGREES_TO_RADIANS);\n\n const relativeScale = scale / height;\n mat4.scale(vm, vm, [relativeScale, relativeScale, relativeScale]);\n\n if (center) {\n mat4.translate(vm, vm, vec3.negate([], center));\n }\n\n return vm;\n}\n\n/**\n * Calculates mapbox compatible projection matrix from parameters\n *\n * @param options.width Width of \"viewport\" or window\n * @param options.height Height of \"viewport\" or window\n * @param options.scale Scale at the current zoom\n * @param options.center Offset of the target, vec3 in world space\n * @param options.offset Offset of the focal point, vec2 in screen space\n * @param options.pitch Camera angle in degrees (0 is straight down)\n * @param options.fovy field of view in degrees\n * @param options.altitude if provided, field of view is calculated using `altitudeToFovy()`\n * @param options.nearZMultiplier control z buffer\n * @param options.farZMultiplier control z buffer\n * @returns project parameters object\n */\nexport function getProjectionParameters(options: {\n width: number;\n height: number;\n scale?: number;\n center?: number[];\n offset?: [number, number];\n fovy?: number;\n altitude?: number;\n pitch?: number;\n nearZMultiplier?: number;\n farZMultiplier?: number;\n}): ProjectionParameters {\n const {\n width,\n height,\n altitude,\n pitch = 0,\n offset,\n center,\n scale,\n nearZMultiplier = 1,\n farZMultiplier = 1\n } = options;\n let {fovy = altitudeToFovy(DEFAULT_ALTITUDE)} = options;\n\n // For back-compatibility allow field of view to be\n // derived from altitude\n if (altitude !== undefined) {\n fovy = altitudeToFovy(altitude);\n }\n\n const fovRadians = fovy * DEGREES_TO_RADIANS;\n const pitchRadians = pitch * DEGREES_TO_RADIANS;\n\n // Distance from camera to the target\n const focalDistance = fovyToAltitude(fovy);\n\n let cameraToSeaLevelDistance = focalDistance;\n\n if (center) {\n cameraToSeaLevelDistance += (center[2] * scale) / Math.cos(pitchRadians) / height;\n }\n\n const fovAboveCenter = fovRadians * (0.5 + (offset ? offset[1] : 0) / height);\n\n // Find the distance from the center point to the center top\n // in focal distance units using law of sines.\n const topHalfSurfaceDistance =\n (Math.sin(fovAboveCenter) * cameraToSeaLevelDistance) /\n Math.sin(clamp(Math.PI / 2 - pitchRadians - fovAboveCenter, 0.01, Math.PI - 0.01));\n\n // Calculate z distance of the farthest fragment that should be rendered.\n const furthestDistance =\n Math.sin(pitchRadians) * topHalfSurfaceDistance + cameraToSeaLevelDistance;\n // Matches mapbox limit\n const horizonDistance = cameraToSeaLevelDistance * 10;\n\n // Calculate z value of the farthest fragment that should be rendered.\n const farZ = Math.min(furthestDistance * farZMultiplier, horizonDistance);\n\n return {\n fov: fovRadians,\n aspect: width / height,\n focalDistance,\n near: nearZMultiplier,\n far: farZ\n };\n}\n\n/**\n * CALCULATE PROJECTION MATRIX: PROJECTS FROM CAMERA (VIEW) SPACE TO CLIPSPACE\n *\n * To match mapbox's z buffer:\n * - \\<= 0.28: nearZMultiplier: 0.1, farZmultiplier: 1\n * - \\>= 0.29: nearZMultiplier: 1 / height, farZMultiplier: 1.01\n *\n * @param options Viewport options\n * @param options.width Width of \"viewport\" or window\n * @param options.height Height of \"viewport\" or window\n * @param options.scale Scale at the current zoom\n * @param options.center Offset of the target, vec3 in world space\n * @param options.offset Offset of the focal point, vec2 in screen space\n * @param options.pitch Camera angle in degrees (0 is straight down)\n * @param options.fovy field of view in degrees\n * @param options.altitude if provided, field of view is calculated using `altitudeToFovy()`\n * @param options.nearZMultiplier control z buffer\n * @param options.farZMultiplier control z buffer\n * @returns 4x4 projection matrix\n */\nexport function getProjectionMatrix(options: {\n width: number;\n height: number;\n pitch: number;\n scale?: number;\n center?: number[];\n offset?: [number, number];\n fovy?: number;\n altitude?: number;\n nearZMultiplier: number;\n farZMultiplier: number;\n}): number[] {\n const {fov, aspect, near, far} = getProjectionParameters(options);\n\n const projectionMatrix = mat4.perspective(\n [] as number[],\n fov, // fov in radians\n aspect, // aspect ratio\n near, // near plane\n far // far plane\n );\n\n return projectionMatrix;\n}\n\n/**\n *\n * Convert an altitude to field of view such that the\n * focal distance is equal to the altitude\n *\n * @param altitude - altitude of camera in screen units\n * @return fovy field of view in degrees\n */\nexport function altitudeToFovy(altitude: number): number {\n return 2 * Math.atan(0.5 / altitude) * RADIANS_TO_DEGREES;\n}\n\n/**\n *\n * Convert an field of view such that the\n * focal distance is equal to the altitude\n *\n * @param fovy - field of view in degrees\n * @return altitude altitude of camera in screen units\n */\nexport function fovyToAltitude(fovy: number): number {\n return 0.5 / Math.tan(0.5 * fovy * DEGREES_TO_RADIANS);\n}\n\n/**\n * Project flat coordinates to pixels on screen.\n *\n * @param xyz - flat coordinate on 512*512 Mercator Zoom 0 tile\n * @param pixelProjectionMatrix - projection matrix 4x4\n * @return [x, y, depth] pixel coordinate on screen.\n */\nexport function worldToPixels(xyz: number[], pixelProjectionMatrix: number[]): number[];\n\n// Project flat coordinates to pixels on screen.\nexport function worldToPixels(xyz: number[], pixelProjectionMatrix: number[]): number[] {\n const [x, y, z = 0] = xyz;\n assert(Number.isFinite(x) && Number.isFinite(y) && Number.isFinite(z));\n\n return transformVector(pixelProjectionMatrix, [x, y, z, 1]);\n}\n\n/**\n * Unproject pixels on screen to flat coordinates.\n *\n * @param xyz - pixel coordinate on screen.\n * @param pixelUnprojectionMatrix - unprojection matrix 4x4\n * @param targetZ - if pixel coordinate does not have a 3rd component (depth),\n * targetZ is used as the elevation plane to unproject onto\n * @return [x, y, Z] flat coordinates on 512*512 Mercator Zoom 0 tile.\n */\nexport function pixelsToWorld(\n xyz: number[],\n pixelUnprojectionMatrix: number[],\n targetZ: number = 0\n): number[] {\n const [x, y, z] = xyz;\n assert(Number.isFinite(x) && Number.isFinite(y), 'invalid pixel coordinate');\n\n if (Number.isFinite(z)) {\n // Has depth component\n const coord = transformVector(pixelUnprojectionMatrix, [x, y, z, 1]);\n return coord;\n }\n\n // since we don't know the correct projected z value for the point,\n // unproject two points to get a line and then find the point on that line with z=0\n const coord0 = transformVector(pixelUnprojectionMatrix, [x, y, 0, 1]);\n const coord1 = transformVector(pixelUnprojectionMatrix, [x, y, 1, 1]);\n\n const z0 = coord0[2];\n const z1 = coord1[2];\n\n const t = z0 === z1 ? 0 : ((targetZ || 0) - z0) / (z1 - z0);\n return vec2.lerp([] as number[], coord0, coord1, t);\n}\n","import {assert} from './assert';\nimport {log2, clamp} from './math-utils';\nimport {MAX_LATITUDE, lngLatToWorld, worldToLngLat} from './web-mercator-utils';\n\n/**\n * Options for fitBounds\n */\nexport type FitBoundsOptions = {\n /** viewport width */\n width: number;\n /** viewport height */\n height: number;\n /** [[lon, lat], [lon, lat]] */\n bounds: [[number, number], [number, number]];\n /** The width/height of the bounded area will never be smaller than this. 0.01 would be about 1000 meters (degree is ~110KM) */\n minExtent?: number;\n /** The maximum zoom level to fit the bounds within. */\n maxZoom?: number; // ~x4,000,000 => About 10 meter extents\n /**\n * padding - The amount of padding in pixels to add to the given bounds.\n * Can also be an object with top, bottom, left and right properties defining the padding.\n */\n padding?: number | Padding;\n /** The center of the given bounds relative to the map's center, */\n offset?: number[];\n};\n\n/**\n * An object describing the padding to add to the bounds.\n */\nexport type Padding = {\n /** Padding from top in pixels to add to the given bounds */\n top: number;\n /** Padding from bottom in pixels to add to the given bounds */\n bottom: number;\n /** Padding from left in pixels to add to the given bounds */\n left: number;\n /** Padding from right in pixels to add to the given bounds */\n right: number;\n};\n\ntype ViewportProps = {\n longitude: number;\n latitude: number;\n zoom: number;\n};\n\n/**\n * Returns map settings {latitude, longitude, zoom}\n * that will contain the provided corners within the provided width.\n *\n * > _Note: Only supports non-perspective mode._\n *\n * @param options fit bounds parameters\n * @returns - latitude, longitude and zoom\n */\nexport function fitBounds(options: FitBoundsOptions): ViewportProps {\n const {\n width,\n height,\n bounds,\n minExtent = 0, // 0.01 would be about 1000 meters (degree is ~110KM)\n maxZoom = 24, // ~x4,000,000 => About 10 meter extents\n offset = [0, 0]\n } = options;\n\n const [[west, south], [east, north]] = bounds;\n const padding = getPaddingObject(options.padding);\n\n const nw = lngLatToWorld([west, clamp(north, -MAX_LATITUDE, MAX_LATITUDE)]);\n const se = lngLatToWorld([east, clamp(south, -MAX_LATITUDE, MAX_LATITUDE)]);\n\n // width/height on the Web Mercator plane\n const size = [\n Math.max(Math.abs(se[0] - nw[0]), minExtent),\n Math.max(Math.abs(se[1] - nw[1]), minExtent)\n ];\n\n const targetSize = [\n width - padding.left - padding.right - Math.abs(offset[0]) * 2,\n height - padding.top - padding.bottom - Math.abs(offset[1]) * 2\n ];\n\n assert(targetSize[0] > 0 && targetSize[1] > 0);\n\n // scale = screen pixels per unit on the Web Mercator plane\n const scaleX = targetSize[0] / size[0];\n const scaleY = targetSize[1] / size[1];\n\n // Find how much we need to shift the center\n const offsetX = (padding.right - padding.left) / 2 / scaleX;\n const offsetY = (padding.top - padding.bottom) / 2 / scaleY;\n\n const center = [(se[0] + nw[0]) / 2 + offsetX, (se[1] + nw[1]) / 2 + offsetY];\n\n const centerLngLat = worldToLngLat(center);\n const zoom = Math.min(maxZoom, log2(Math.abs(Math.min(scaleX, scaleY))));\n\n assert(Number.isFinite(zoom));\n\n return {\n longitude: centerLngLat[0],\n latitude: centerLngLat[1],\n zoom\n };\n}\n\n// Helpers\nfunction getPaddingObject(padding: number | Padding = 0): Padding {\n if (typeof padding === 'number') {\n return {\n top: padding,\n bottom: padding,\n left: padding,\n right: padding\n };\n }\n\n // Make sure all the required properties are set\n assert(\n Number.isFinite(padding.top) &&\n Number.isFinite(padding.bottom) &&\n Number.isFinite(padding.left) &&\n Number.isFinite(padding.right)\n );\n\n return padding;\n}\n","/* eslint-disable camelcase */\nimport {vec2} from '@math.gl/core';\nimport type {WebMercatorViewport} from './web-mercator-viewport';\nimport {worldToLngLat} from './web-mercator-utils';\nimport {transformVector} from './math-utils';\n\nconst DEGREES_TO_RADIANS = Math.PI / 180;\n\n/*\n * Returns the quad at the intersection of the frustum and the given z plane\n * @param {WebMercatorViewport} viewport\n * @param {Number} z - elevation in meters\n */\nexport function getBounds(viewport: WebMercatorViewport, z: number = 0): number[][] {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const {width, height, unproject} = viewport;\n const unprojectOps = {targetZ: z};\n const bottomLeft = unproject([0, height], unprojectOps);\n const bottomRight = unproject([width, height], unprojectOps);\n let topLeft: number[];\n let topRight: number[];\n\n const halfFov = viewport.fovy\n ? 0.5 * viewport.fovy * DEGREES_TO_RADIANS\n : Math.atan(0.5 / viewport.altitude);\n const angleToGround = (90 - viewport.pitch) * DEGREES_TO_RADIANS;\n // The top plane is parallel to the ground if halfFov == angleToGround\n if (halfFov > angleToGround - 0.01) {\n // intersect with the far plane\n topLeft = unprojectOnFarPlane(viewport, 0, z);\n topRight = unprojectOnFarPlane(viewport, width, z);\n } else {\n // intersect with the top plane\n topLeft = unproject([0, 0], unprojectOps);\n topRight = unproject([width, 0], unprojectOps);\n }\n\n return [bottomLeft, bottomRight, topRight, topLeft];\n}\n\n/*\n * Find a point on the far clipping plane of the viewport\n * @param {WebMercatorViewport} viewport\n * @param {Number} x - projected x in screen space\n * @param {Number} targetZ - the elevation of the point in meters\n */\nfunction unprojectOnFarPlane(viewport: WebMercatorViewport, x: number, targetZ: number): number[] {\n const {pixelUnprojectionMatrix} = viewport;\n const coord0 = transformVector(pixelUnprojectionMatrix, [x, 0, 1, 1]);\n const coord1 = transformVector(pixelUnprojectionMatrix, [x, viewport.height, 1, 1]);\n\n const z = targetZ * viewport.distanceScales.unitsPerMeter[2];\n const t = (z - coord0[2]) / (coord1[2] - coord0[2]);\n const coord = vec2.lerp([], coord0, coord1, t);\n\n const result = worldToLngLat(coord);\n result.push(targetZ);\n return result;\n}\n","// View and Projection Matrix calculations for mapbox-js style map view properties\nimport {createMat4} from './math-utils';\n\nimport {\n zoomToScale,\n pixelsToWorld,\n lngLatToWorld,\n worldToLngLat,\n worldToPixels,\n altitudeToFovy,\n fovyToAltitude,\n DEFAULT_ALTITUDE,\n getProjectionMatrix,\n getDistanceScales,\n getViewMatrix,\n DistanceScales\n} from './web-mercator-utils';\nimport {fitBounds} from './fit-bounds';\nimport {getBounds} from './get-bounds';\nimport type {FitBoundsOptions} from './fit-bounds';\n\nimport {mat4, vec2, vec3} from '@math.gl/core';\n\n/**\n * @param width=1 - Width of \"viewport\" or window\n * @param height=1 - Height of \"viewport\" or window\n * @param scale=1 - Either use scale or zoom\n * @param pitch=0 - Camera angle in degrees (0 is straight down)\n * @param bearing=0 - Map rotation in degrees (0 means north is up)\n * @param fovy= - Field of view of camera in degrees\n * @param altitude= - Altitude of camera in screen units \n *\n * Web mercator projection short-hand parameters\n * @param latitude - Center of viewport on map\n * @param longitude - Center of viewport on map\n * @param zoom - Scale = Math.pow(2,zoom) on map\n\n * Notes:\n * - Only one of center or [latitude, longitude] can be specified\n * - [latitude, longitude] can only be specified when \"mercator\" is true\n * - Altitude has a default value that matches assumptions in mapbox-gl\n * - Field of view is independent from altitude, provide `altitudeToFovy(1.5)` (default value) to match assumptions in mapbox-gl\n * - width and height are forced to 1 if supplied as 0, to avoid\n * division by zero. This is intended to reduce the burden of apps to\n * to check values before instantiating a Viewport.\n */\nexport type WebMercatorViewportProps = {\n // Map state\n width: number;\n height: number;\n latitude?: number;\n longitude?: number;\n position?: number[];\n zoom?: number;\n pitch?: number;\n bearing?: number;\n altitude?: number;\n fovy?: number;\n nearZMultiplier?: number;\n farZMultiplier?: number;\n};\n\n/**\n * The WebMercatorViewport class creates\n * - view/projection matrices\n * - \"uniform values\" (for shaders) from mercator params\n *\n * Note: Instances are immutable in the sense that they only have accessors.\n * A new viewport instance should be created if any parameters have changed.\n */\nexport class WebMercatorViewport {\n readonly latitude: number;\n readonly longitude: number;\n readonly zoom: number;\n readonly pitch: number;\n readonly bearing: number;\n readonly altitude: number;\n readonly fovy: number;\n\n readonly meterOffset: number[];\n readonly center: number[];\n\n readonly width: number;\n readonly height: number;\n readonly scale: number;\n readonly distanceScales: DistanceScales;\n\n readonly viewMatrix: number[];\n readonly projectionMatrix: number[];\n\n viewProjectionMatrix: number[];\n pixelProjectionMatrix: number[];\n pixelUnprojectionMatrix: number[];\n\n /**\n * @classdesc\n * Creates view/projection matrices from mercator params\n * Note: The Viewport is immutable in the sense that it only has accessors.\n * A new viewport instance should be created if any parameters have changed.\n */\n // eslint-disable-next-line max-statements\n constructor(props: WebMercatorViewportProps = {width: 1, height: 1}) {\n let {\n // Map state\n width,\n height,\n altitude = null,\n fovy = null\n } = props;\n const {\n latitude = 0,\n longitude = 0,\n zoom = 0,\n pitch = 0,\n bearing = 0,\n position = null,\n nearZMultiplier = 0.02,\n farZMultiplier = 1.01\n } = props;\n\n // Silently allow apps to send in 0,0 to facilitate isomorphic render etc\n width = width || 1;\n height = height || 1;\n\n // `fovy` & `altitude` are independent parameters, one for the\n // projection and the latter for the view matrix. In the past,\n // the `fovy` was always derived from the `altitude`\n if (fovy === null && altitude === null) {\n altitude = DEFAULT_ALTITUDE;\n fovy = altitudeToFovy(altitude);\n } else if (fovy === null) {\n fovy = altitudeToFovy(altitude);\n } else if (altitude === null) {\n altitude = fovyToAltitude(fovy);\n }\n\n const scale = zoomToScale(zoom);\n // Altitude - prevent division by 0\n // TODO - just throw an Error instead?\n altitude = Math.max(0.75, altitude);\n\n const distanceScales = getDistanceScales({longitude, latitude});\n\n const center: number[] = lngLatToWorld([longitude, latitude]);\n center.push(0);\n\n if (position) {\n vec3.add(center, center, vec3.mul([], position, distanceScales.unitsPerMeter));\n }\n\n this.projectionMatrix = getProjectionMatrix({\n width,\n height,\n scale,\n center,\n pitch,\n fovy,\n nearZMultiplier,\n farZMultiplier\n });\n\n this.viewMatrix = getViewMatrix({\n height,\n scale,\n center,\n pitch,\n bearing,\n altitude\n });\n\n // Save parameters\n this.width = width;\n this.height = height;\n this.scale = scale;\n\n this.latitude = latitude;\n this.longitude = longitude;\n this.zoom = zoom;\n this.pitch = pitch;\n this.bearing = bearing;\n this.altitude = altitude;\n this.fovy = fovy;\n this.center = center;\n this.meterOffset = position || [0, 0, 0];\n\n this.distanceScales = distanceScales;\n\n this._initMatrices();\n\n Object.freeze(this);\n }\n\n _initMatrices(): void {\n const {width, height, projectionMatrix, viewMatrix} = this;\n\n // Note: As usual, matrix operations should be applied in \"reverse\" order\n // since vectors will be multiplied in from the right during transformation\n const vpm = createMat4();\n mat4.multiply(vpm, vpm, projectionMatrix);\n mat4.multiply(vpm, vpm, viewMatrix);\n this.viewProjectionMatrix = vpm;\n\n // Calculate matrices and scales needed for projection\n /**\n * Builds matrices that converts preprojected lngLats to screen pixels\n * and vice versa.\n * Note: Currently returns bottom-left coordinates!\n * Note: Starts with the GL projection matrix and adds steps to the\n * scale and translate that matrix onto the window.\n * Note: WebGL controls clip space to screen projection with gl.viewport\n * and does not need this step.\n */\n const m = createMat4();\n\n // matrix for conversion from location to screen coordinates\n mat4.scale(m, m, [width / 2, -height / 2, 1]);\n mat4.translate(m, m, [1, -1, 0]);\n mat4.multiply(m, m, vpm);\n\n const mInverse = mat4.invert(createMat4(), m);\n if (!mInverse) {\n throw new Error('Pixel project matrix not invertible');\n }\n\n this.pixelProjectionMatrix = m;\n this.pixelUnprojectionMatrix = mInverse;\n }\n\n /** Two viewports are equal if width and height are identical, and if\n * their view and projection matrices are (approximately) equal.\n */\n equals = (viewport: WebMercatorViewport | null): boolean => {\n if (!(viewport instanceof WebMercatorViewport)) {\n return false;\n }\n\n return (\n viewport.width === this.width &&\n viewport.height === this.height &&\n mat4.equals(viewport.projectionMatrix, this.projectionMatrix) &&\n mat4.equals(viewport.viewMatrix, this.viewMatrix)\n );\n };\n\n /**\n * Projects xyz (possibly latitude and longitude) to pixel coordinates in window\n * using viewport projection parameters\n * - [longitude, latitude] to [x, y]\n * - [longitude, latitude, Z] => [x, y, z]\n * Note: By default, returns top-left coordinates for canvas/SVG type render\n *\n * @param lngLatZ - [lng, lat] or [lng, lat, Z]\n * @param options - options\n * @param options.topLeft=true - Whether projected coords are top left\n * @return - screen coordinates [x, y] or [x, y, z], z as pixel depth\n */\n project = (lngLatZ: number[], options: {topLeft?: boolean} = {}): number[] => {\n const {topLeft = true} = options;\n const worldPosition = this.projectPosition(lngLatZ);\n const coord = worldToPixels(worldPosition, this.pixelProjectionMatrix);\n\n const [x, y] = coord;\n const y2 = topLeft ? y : this.height - y;\n return lngLatZ.length === 2 ? [x, y2] : [x, y2, coord[2]];\n };\n\n /**\n * Unproject pixel coordinates on screen onto world coordinates, possibly `[lon, lat]` on map.\n *\n * - [x, y] => [lng, lat]\n * - [x, y, z] => [lng, lat, Z]\n *\n * @param xyz - screen coordinates, z as pixel depth\n * @param options - options\n * @param options.topLeft=true - Whether projected coords are top left\n * @param options.targetZ=0 - If pixel depth is unknown, targetZ is used as\n * the elevation plane to unproject onto\n * @return - [lng, lat, Z] or [X, Y, Z]\n */\n unproject = (xyz: number[], options: {topLeft?: boolean; targetZ?: number} = {}): number[] => {\n const {topLeft = true, targetZ = undefined} = options;\n const [x, y, z] = xyz;\n\n const y2 = topLeft ? y : this.height - y;\n const targetZWorld = targetZ && targetZ * this.distanceScales.unitsPerMeter[2];\n const coord = pixelsToWorld([x, y2, z], this.pixelUnprojectionMatrix, targetZWorld);\n const [X, Y, Z] = this.unprojectPosition(coord);\n\n if (Number.isFinite(z)) {\n return [X, Y, Z];\n }\n return Number.isFinite(targetZ) ? [X, Y, targetZ] : [X, Y];\n };\n\n // NON_LINEAR PROJECTION HOOKS\n // Used for web meractor projection\n\n projectPosition = (xyz: number[]): [number, number, number] => {\n const [X, Y] = lngLatToWorld(xyz);\n const Z = (xyz[2] || 0) * this.distanceScales.unitsPerMeter[2];\n return [X, Y, Z];\n };\n\n unprojectPosition = (xyz: number[]): [number, number, number] => {\n const [X, Y] = worldToLngLat(xyz);\n const Z = (xyz[2] || 0) * this.distanceScales.metersPerUnit[2];\n return [X, Y, Z];\n };\n\n /**\n * Project [lng,lat] on sphere onto [x,y] on 512*512 Mercator Zoom 0 tile.\n * Performs the nonlinear part of the web mercator projection.\n * Remaining projection is done with 4x4 matrices which also handles\n * perspective.\n *\n * @param lngLat - [lng, lat] coordinates\n * Specifies a point on the sphere to project onto the map.\n * @return [x,y] coordinates.\n */\n projectFlat(lngLat: number[]): number[] {\n return lngLatToWorld(lngLat);\n }\n\n /**\n * Unproject world point [x,y] on map onto {lat, lon} on sphere\n *\n * @param xy - array with [x,y] members\n * representing point on projected map plane\n * @return - array with [lat,lon] of point on sphere.\n * Has toArray method if you need a GeoJSON Array.\n * Per cartographic tradition, lat and lon are specified as degrees.\n */\n unprojectFlat(xy: number[]): number[] {\n return worldToLngLat(xy);\n }\n\n /**\n * Get the map center that place a given [lng, lat] coordinate at screen point [x, y]\n * @param opt\n * @param opt.lngLat - [lng,lat] coordinates\n * Specifies a point on the sphere.\n * @param opt.pos - [x,y] coordinates\n * Specifies a point on the screen.\n * @return [lng,lat] new map center.\n */\n getMapCenterByLngLatPosition({lngLat, pos}: {lngLat: number[]; pos: number[]}): number[] {\n const fromLocation = pixelsToWorld(pos, this.pixelUnprojectionMatrix);\n const toLocation = lngLatToWorld(lngLat);\n const translate = vec2.add([], toLocation, vec2.negate([], fromLocation));\n const newCenter = vec2.add([], this.center, translate);\n return worldToLngLat(newCenter);\n }\n\n /**\n * Returns a new viewport that fit around the given rectangle.\n * Only supports non-perspective mode.\n * @param bounds - [[lon, lat], [lon, lat]]\n * @param [options]\n * @param [options.padding] - The amount of padding in pixels to add to the given bounds.\n * @param [options.offset] - The center of the given bounds relative to the map's center,\n * [x, y] measured in pixels.\n * @returns {WebMercatorViewport}\n */\n fitBounds(\n bounds: [[number, number], [number, number]],\n options: Omit = {}\n ): WebMercatorViewport {\n const {width, height} = this;\n const {longitude, latitude, zoom} = fitBounds(Object.assign({width, height, bounds}, options));\n return new WebMercatorViewport({width, height, longitude, latitude, zoom});\n }\n\n /**\n * Returns the bounding box of the viewport.\n * @param [options]\n * @param [options.z] - The altitude at which the bounds should be calculated.\n * @returns {Array} bounds - [[lon, lat], [lon, lat]]\n */\n getBounds(options?: {z?: number}): number[][] {\n const corners = this.getBoundingRegion(options);\n\n const west = Math.min(...corners.map((p) => p[0]));\n const east = Math.max(...corners.map((p) => p[0]));\n const south = Math.min(...corners.map((p) => p[1]));\n const north = Math.max(...corners.map((p) => p[1]));\n return [\n [west, south],\n [east, north]\n ];\n }\n\n /**\n * Returns the bounding box of the viewport.\n * @param [options]\n * @param [options.z] - The altitude at which the bounds should be calculated.\n * @returns {Array} an array of 4 points that define the visible region\n */\n getBoundingRegion(options: {z?: number} = {}): number[][] {\n return getBounds(this, options.z || 0);\n }\n\n // DEPRECATED\n\n /** @deprecated Legacy method name */\n getLocationAtPoint({lngLat, pos}: {lngLat: number[]; pos: number[]}): number[] {\n return this.getMapCenterByLngLatPosition({lngLat, pos});\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {COORDINATE_SYSTEM, PROJECTION_MODE} from '../../lib/constants';\nimport project from '../project/project';\nimport {Vector3, Matrix4} from '@math.gl/core';\nimport type {NumericArray} from '@math.gl/core';\nimport memoize from '../../utils/memoize';\nimport {pixelsToWorld} from '@math.gl/web-mercator';\n\nimport type {Texture} from '@luma.gl/core';\nimport {ShaderModule} from '@luma.gl/shadertools';\nimport type Viewport from '../../viewports/viewport';\nimport {\n ProjectProps,\n ProjectUniforms,\n getShaderCoordinateSystem\n} from '../project/viewport-uniforms';\n\nconst uniformBlock = /* glsl */ `\nlayout(std140) uniform shadowUniforms {\n bool drawShadowMap;\n bool useShadowMap;\n vec4 color;\n highp int lightId;\n float lightCount;\n mat4 viewProjectionMatrix0;\n mat4 viewProjectionMatrix1;\n vec4 projectCenter0;\n vec4 projectCenter1;\n} shadow;\n`;\n\nconst vertex = /* glsl */ `\nconst int max_lights = 2;\n\nout vec3 shadow_vPosition[max_lights];\n\nvec4 shadow_setVertexPosition(vec4 position_commonspace) {\n mat4 viewProjectionMatrices[max_lights];\n viewProjectionMatrices[0] = shadow.viewProjectionMatrix0;\n viewProjectionMatrices[1] = shadow.viewProjectionMatrix1;\n vec4 projectCenters[max_lights];\n projectCenters[0] = shadow.projectCenter0;\n projectCenters[1] = shadow.projectCenter1;\n\n if (shadow.drawShadowMap) {\n return project_common_position_to_clipspace(position_commonspace, viewProjectionMatrices[shadow.lightId], projectCenters[shadow.lightId]);\n }\n if (shadow.useShadowMap) {\n for (int i = 0; i < max_lights; i++) {\n if(i < int(shadow.lightCount)) {\n vec4 shadowMap_position = project_common_position_to_clipspace(position_commonspace, viewProjectionMatrices[i], projectCenters[i]);\n shadow_vPosition[i] = (shadowMap_position.xyz / shadowMap_position.w + 1.0) / 2.0;\n }\n }\n }\n return gl_Position;\n}\n`;\n\nconst vs = `\n${uniformBlock}\n${vertex}\n`;\n\nconst fragment = /* glsl */ `\nconst int max_lights = 2;\nuniform sampler2D shadow_uShadowMap0;\nuniform sampler2D shadow_uShadowMap1;\n\nin vec3 shadow_vPosition[max_lights];\n\nconst vec4 bitPackShift = vec4(1.0, 255.0, 65025.0, 16581375.0);\nconst vec4 bitUnpackShift = 1.0 / bitPackShift;\nconst vec4 bitMask = vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0);\n\nfloat shadow_getShadowWeight(vec3 position, sampler2D shadowMap) {\n vec4 rgbaDepth = texture(shadowMap, position.xy);\n\n float z = dot(rgbaDepth, bitUnpackShift);\n return smoothstep(0.001, 0.01, position.z - z);\n}\n\nvec4 shadow_filterShadowColor(vec4 color) {\n if (shadow.drawShadowMap) {\n vec4 rgbaDepth = fract(gl_FragCoord.z * bitPackShift);\n rgbaDepth -= rgbaDepth.gbaa * bitMask;\n return rgbaDepth;\n }\n if (shadow.useShadowMap) {\n float shadowAlpha = 0.0;\n shadowAlpha += shadow_getShadowWeight(shadow_vPosition[0], shadow_uShadowMap0);\n if(shadow.lightCount > 1.0) {\n shadowAlpha += shadow_getShadowWeight(shadow_vPosition[1], shadow_uShadowMap1);\n }\n shadowAlpha *= shadow.color.a / shadow.lightCount;\n float blendedAlpha = shadowAlpha + color.a * (1.0 - shadowAlpha);\n\n return vec4(\n mix(color.rgb, shadow.color.rgb, shadowAlpha / blendedAlpha),\n blendedAlpha\n );\n }\n return color;\n}\n`;\n\nconst fs = `\n${uniformBlock}\n${fragment}\n`;\n\nconst getMemoizedViewportCenterPosition = memoize(getViewportCenterPosition);\nconst getMemoizedViewProjectionMatrices = memoize(getViewProjectionMatrices);\n\nconst DEFAULT_SHADOW_COLOR: NumberArray4 = [0, 0, 0, 1.0];\nconst VECTOR_TO_POINT_MATRIX = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0];\n\nexport type ShadowModuleProps = {\n project: ProjectProps;\n shadowEnabled?: boolean;\n drawToShadowMap?: boolean;\n shadowMaps?: Texture[];\n dummyShadowMap: Texture;\n shadowColor?: NumberArray4;\n shadowMatrices?: Matrix4[];\n shadowLightId?: number;\n};\n\ntype ShadowModuleUniforms = {\n drawShadowMap: boolean;\n useShadowMap: boolean;\n color?: NumberArray4;\n lightId?: number;\n lightCount?: number;\n viewProjectionMatrix0?: NumberArray16;\n viewProjectionMatrix1?: NumberArray16;\n projectCenter0?: NumberArray4;\n projectCenter1?: NumberArray4;\n};\n\ntype ShadowModuleBindings = {\n shadow_uShadowMap0: Texture;\n shadow_uShadowMap1: Texture;\n};\n\nfunction screenToCommonSpace(xyz: number[], pixelUnprojectionMatrix: number[]): number[] {\n const [x, y, z] = xyz;\n const coord = pixelsToWorld([x, y, z], pixelUnprojectionMatrix);\n\n if (Number.isFinite(z)) {\n return coord;\n }\n return [coord[0], coord[1], 0];\n}\n\nfunction getViewportCenterPosition({\n viewport,\n center\n}: {\n viewport: Viewport;\n center: NumericArray;\n}): NumericArray {\n return new Matrix4(viewport.viewProjectionMatrix).invert().transform(center);\n}\n\nfunction getViewProjectionMatrices({\n viewport,\n shadowMatrices\n}: {\n viewport: Viewport;\n shadowMatrices: Matrix4[];\n}): Matrix4[] {\n const projectionMatrices: Matrix4[] = [];\n const pixelUnprojectionMatrix = viewport.pixelUnprojectionMatrix;\n const farZ = viewport.isGeospatial ? undefined : 1;\n const corners = [\n [0, 0, farZ], // top left ground\n [viewport.width, 0, farZ], // top right ground\n [0, viewport.height, farZ], // bottom left ground\n [viewport.width, viewport.height, farZ], // bottom right ground\n [0, 0, -1], // top left near\n [viewport.width, 0, -1], // top right near\n [0, viewport.height, -1], // bottom left near\n [viewport.width, viewport.height, -1] // bottom right near\n ].map(pixel =>\n // @ts-expect-error z may be undefined\n screenToCommonSpace(pixel, pixelUnprojectionMatrix)\n );\n\n for (const shadowMatrix of shadowMatrices) {\n const viewMatrix = shadowMatrix.clone().translate(new Vector3(viewport.center).negate());\n const positions = corners.map(corner => viewMatrix.transform(corner));\n const projectionMatrix = new Matrix4().ortho({\n left: Math.min(...positions.map(position => position[0])),\n right: Math.max(...positions.map(position => position[0])),\n bottom: Math.min(...positions.map(position => position[1])),\n top: Math.max(...positions.map(position => position[1])),\n near: Math.min(...positions.map(position => -position[2])),\n far: Math.max(...positions.map(position => -position[2]))\n });\n projectionMatrices.push(projectionMatrix.multiplyRight(shadowMatrix));\n }\n return projectionMatrices;\n}\n\n/* eslint-disable camelcase */\n\n// eslint-disable-next-line complexity\nfunction createShadowUniforms(\n opts: Partial\n): ShadowModuleBindings & ShadowModuleUniforms {\n const {shadowEnabled = true, project: projectProps} = opts;\n if (!shadowEnabled || !projectProps || !opts.shadowMatrices || !opts.shadowMatrices.length) {\n return {\n drawShadowMap: false,\n useShadowMap: false,\n shadow_uShadowMap0: opts.dummyShadowMap!,\n shadow_uShadowMap1: opts.dummyShadowMap!\n };\n }\n const projectUniforms = project.getUniforms(projectProps) as ProjectUniforms;\n const center = getMemoizedViewportCenterPosition({\n viewport: projectProps.viewport,\n center: projectUniforms.center\n });\n\n const projectCenters: NumericArray[] = [];\n const viewProjectionMatrices = getMemoizedViewProjectionMatrices({\n shadowMatrices: opts.shadowMatrices,\n viewport: projectProps.viewport\n }).slice();\n\n for (let i = 0; i < opts.shadowMatrices.length; i++) {\n const viewProjectionMatrix = viewProjectionMatrices[i];\n const viewProjectionMatrixCentered = viewProjectionMatrix\n .clone()\n .translate(new Vector3(projectProps.viewport.center).negate());\n\n if (\n projectUniforms.coordinateSystem === getShaderCoordinateSystem('lnglat') &&\n projectUniforms.projectionMode === PROJECTION_MODE.WEB_MERCATOR\n ) {\n viewProjectionMatrices[i] = viewProjectionMatrixCentered;\n projectCenters[i] = center;\n } else {\n viewProjectionMatrices[i] = viewProjectionMatrix\n .clone()\n .multiplyRight(VECTOR_TO_POINT_MATRIX);\n projectCenters[i] = viewProjectionMatrixCentered.transform(center);\n }\n }\n\n const uniforms: ShadowModuleUniforms & ShadowModuleBindings = {\n drawShadowMap: Boolean(opts.drawToShadowMap),\n useShadowMap: opts.shadowMaps ? opts.shadowMaps.length > 0 : false,\n color: opts.shadowColor || DEFAULT_SHADOW_COLOR,\n lightId: opts.shadowLightId || 0,\n lightCount: opts.shadowMatrices.length,\n shadow_uShadowMap0: opts.dummyShadowMap!,\n shadow_uShadowMap1: opts.dummyShadowMap!\n };\n\n for (let i = 0; i < viewProjectionMatrices.length; i++) {\n uniforms[`viewProjectionMatrix${i}`] = viewProjectionMatrices[i];\n uniforms[`projectCenter${i}`] = projectCenters[i];\n }\n\n for (let i = 0; i < 2; i++) {\n uniforms[`shadow_uShadowMap${i}`] =\n (opts.shadowMaps && opts.shadowMaps[i]) || opts.dummyShadowMap;\n }\n return uniforms;\n}\n\nexport default {\n name: 'shadow',\n dependencies: [project],\n vs,\n fs,\n inject: {\n 'vs:DECKGL_FILTER_GL_POSITION': `\n position = shadow_setVertexPosition(geometry.position);\n `,\n 'fs:DECKGL_FILTER_COLOR': `\n color = shadow_filterShadowColor(color);\n `\n },\n getUniforms: createShadowUniforms,\n uniformTypes: {\n drawShadowMap: 'f32',\n useShadowMap: 'f32',\n color: 'vec4',\n lightId: 'i32',\n lightCount: 'f32',\n viewProjectionMatrix0: 'mat4x4',\n viewProjectionMatrix1: 'mat4x4',\n projectCenter0: 'vec4',\n projectCenter1: 'vec4'\n }\n} as const satisfies ShaderModule;\n\n// TODO replace with type from math.gl\ntype NumberArray4 = [number, number, number, number];\ntype NumberArray16 = [\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n number\n];\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {picking} from '@luma.gl/shadertools';\n\nconst sourceWGSL = /* wgsl */ `\\\nstruct pickingUniforms {\n isActive: f32,\n isAttribute: f32,\n isHighlightActive: f32,\n useByteColors: f32,\n highlightedObjectColor: vec3,\n highlightColor: vec4,\n};\n\n@group(0) @binding(auto) var picking: pickingUniforms;\n\nfn picking_normalizeColor(color: vec3) -> vec3 {\n return select(color, color / 255.0, picking.useByteColors > 0.5);\n}\n\nfn picking_normalizeColor4(color: vec4) -> vec4 {\n return select(color, color / 255.0, picking.useByteColors > 0.5);\n}\n\nfn picking_isColorZero(color: vec3) -> bool {\n return dot(color, vec3(1.0)) < 0.00001;\n}\n\nfn picking_isColorValid(color: vec3) -> bool {\n return dot(color, vec3(1.0)) > 0.00001;\n}\n`;\n\nexport default {\n ...picking,\n source: sourceWGSL,\n defaultUniforms: {...picking.defaultUniforms, useByteColors: true},\n inject: {\n 'vs:DECKGL_FILTER_GL_POSITION': `\n // for picking depth values\n picking_setPickingAttribute(position.z / position.w);\n `,\n 'vs:DECKGL_FILTER_COLOR': `\n picking_setPickingColor(geometry.pickingColor);\n `,\n 'fs:DECKGL_FILTER_COLOR': {\n order: 99,\n injection: `\n // use highlight color if this fragment belongs to the selected object.\n color = picking_filterHighlightColor(color);\n\n // use picking color if rendering to picking FBO.\n color = picking_filterPickingColor(color);\n `\n }\n }\n};\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {ShaderAssembler, gouraudMaterial, phongMaterial} from '@luma.gl/shadertools';\nimport {layerUniforms} from './misc/layer-uniforms';\nimport color from './color/color';\nimport geometry from './misc/geometry';\nimport project from './project/project';\nimport project32 from './project32/project32';\nimport shadow from './shadow/shadow';\nimport picking from './picking/picking';\n\nconst DEFAULT_MODULES = [geometry];\n\nconst SHADER_HOOKS_GLSL = [\n 'vs:DECKGL_FILTER_SIZE(inout vec3 size, VertexGeometry geometry)',\n 'vs:DECKGL_FILTER_GL_POSITION(inout vec4 position, VertexGeometry geometry)',\n 'vs:DECKGL_FILTER_COLOR(inout vec4 color, VertexGeometry geometry)',\n 'fs:DECKGL_FILTER_COLOR(inout vec4 color, FragmentGeometry geometry)'\n];\n\nconst SHADER_HOOKS_WGSL = [\n // Not yet supported\n];\n\nexport function getShaderAssembler(language: 'glsl' | 'wgsl'): ShaderAssembler {\n const shaderAssembler = ShaderAssembler.getDefaultShaderAssembler();\n\n for (const shaderModule of DEFAULT_MODULES) {\n shaderAssembler.addDefaultModule(shaderModule);\n }\n\n // if we're recreating the device we may have changed language\n // and must not inject hooks for the wrong language\n // shaderAssembler.resetShaderHooks();\n (shaderAssembler as any)._hookFunctions.length = 0;\n\n // Add shader hooks based on language\n // TODO(ibgreen) - should the luma shader assembler support both sets of hooks?\n const shaderHooks = language === 'glsl' ? SHADER_HOOKS_GLSL : SHADER_HOOKS_WGSL;\n for (const shaderHook of shaderHooks) {\n shaderAssembler.addShaderHook(shaderHook);\n }\n\n return shaderAssembler;\n}\n\nexport {layerUniforms, color, picking, project, project32, gouraudMaterial, phongMaterial, shadow};\n\n// Useful for custom shader modules\nexport type {ProjectProps, ProjectUniforms} from './project/viewport-uniforms';\n\n// TODO - these should be imported from luma.gl\n/* eslint-disable camelcase */\nexport type PickingUniforms = {\n picking_uActive: boolean;\n picking_uAttribute: boolean;\n picking_uSelectedColor: [number, number, number];\n picking_uSelectedColorValid: boolean;\n picking_uHighlightColor: [number, number, number, number];\n};\n\nexport type LightingModuleSettings = {\n material:\n | boolean\n | {\n ambient?: number;\n diffuse?: number;\n shininess?: number;\n specularColor?: [number, number, number];\n };\n};\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nconst DEFAULT_LIGHT_COLOR = [255, 255, 255] as [number, number, number];\nconst DEFAULT_LIGHT_INTENSITY = 1.0;\n\nlet idCount = 0;\n\nexport type AmbientLightOptions = {\n id?: string;\n /** Light color, [r, g, b] in the 0-255 range\n * @default [255, 255, 255]\n */\n color?: [number, number, number];\n /** Light intensity, higher number is brighter\n * @default 1.0\n */\n intensity?: number;\n};\n\nexport class AmbientLight {\n id: string;\n color: [number, number, number];\n intensity: number;\n type = 'ambient' as const;\n\n constructor(props: AmbientLightOptions = {}) {\n const {color = DEFAULT_LIGHT_COLOR} = props;\n const {intensity = DEFAULT_LIGHT_INTENSITY} = props;\n\n this.id = props.id || `ambient-${idCount++}`;\n this.color = color;\n this.intensity = intensity;\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Vector3} from '@math.gl/core';\nimport type Layer from '../../lib/layer';\n\nconst DEFAULT_LIGHT_COLOR = [255, 255, 255] as [number, number, number];\nconst DEFAULT_LIGHT_INTENSITY = 1.0;\nconst DEFAULT_LIGHT_DIRECTION = [0.0, 0.0, -1.0] as [number, number, number];\n\nlet idCount = 0;\n\nexport type DirectionalLightOptions = {\n id?: string;\n /** Light color, [r, g, b] in the 0-255 range\n * @default [255, 255, 255]\n */\n color?: [number, number, number];\n /** Light intensity, higher number is brighter\n * @default 1.0\n */\n intensity?: number;\n /** Light direction in the common space\n * @default [0.0, 0.0, -1.0]\n */\n direction?: [number, number, number];\n /** (Experimental) render shadows cast by this light\n * @default false\n */\n _shadow?: boolean;\n};\n\nexport class DirectionalLight {\n id: string;\n color: [number, number, number];\n intensity: number;\n type = 'directional' as const;\n direction: [number, number, number];\n shadow: boolean;\n\n constructor(props: DirectionalLightOptions = {}) {\n const {color = DEFAULT_LIGHT_COLOR} = props;\n const {intensity = DEFAULT_LIGHT_INTENSITY} = props;\n const {direction = DEFAULT_LIGHT_DIRECTION} = props;\n const {_shadow = false} = props;\n\n this.id = props.id || `directional-${idCount++}`;\n this.color = color;\n this.intensity = intensity;\n this.type = 'directional';\n this.direction = new Vector3(direction).normalize().toArray() as [number, number, number];\n this.shadow = _shadow;\n }\n\n getProjectedLight(opts: {layer: Layer}): DirectionalLight {\n return this;\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '@luma.gl/core';\n\n/**\n * Base class for passes\n * @todo v9 - should the luma.gl RenderPass be owned by this class?\n * Currently owned by subclasses\n */\nexport default class Pass {\n /** string id, mainly for debugging */\n id: string;\n /** The luma.gl Device that this pass is associated with */\n device: Device;\n /** TODO v9 - inject prop types from parent */\n props: any;\n\n /** Create a new Pass instance */\n constructor(device: Device, props: {id: string} = {id: 'pass'}) {\n const {id} = props;\n this.id = id; // id of this pass\n this.device = device;\n this.props = {...props};\n }\n\n setProps(props): void {\n Object.assign(this.props, props);\n }\n\n render(params): void {} // eslint-disable-line @typescript-eslint/no-empty-function\n\n cleanup() {} // eslint-disable-line @typescript-eslint/no-empty-function\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {\n Device,\n Parameters,\n RenderPassParameters,\n RenderPipelineParameters\n} from '@luma.gl/core';\nimport type {Framebuffer, RenderPass} from '@luma.gl/core';\nimport type {NumberArray4} from '@math.gl/core';\n\nimport Pass from './pass';\nimport type Viewport from '../viewports/viewport';\nimport type View from '../views/view';\nimport type Layer from '../lib/layer';\nimport type {Effect} from '../lib/effect';\nimport type {ProjectProps} from '../shaderlib/project/viewport-uniforms';\nimport type {PickingProps} from '@luma.gl/shadertools';\n\nexport type Rect = {x: number; y: number; width: number; height: number};\n\n// WebGPU complication: Matching attachment state of the renderpass requires including a depth buffer\nconst WEBGPU_DEFAULT_DRAW_PARAMETERS: RenderPipelineParameters = {\n depthWriteEnabled: true,\n depthCompare: 'less-equal',\n blendColorOperation: 'add',\n blendColorSrcFactor: 'src-alpha',\n blendColorDstFactor: 'one',\n blendAlphaOperation: 'add',\n blendAlphaSrcFactor: 'one-minus-dst-alpha',\n blendAlphaDstFactor: 'one'\n};\n\nexport type LayersPassRenderOptions = {\n /** @deprecated TODO v9 recommend we rename this to framebuffer to minimize confusion */\n target?: Framebuffer | null;\n isPicking?: boolean;\n pass: string;\n layers: Layer[];\n viewports: Viewport[];\n onViewportActive?: (viewport: Viewport) => void;\n cullRect?: Rect;\n views?: Record;\n effects?: Effect[];\n /** If true, recalculates render index (z) from 0. Set to false if a stack of layers are rendered in multiple passes. */\n clearStack?: boolean;\n clearCanvas?: boolean;\n clearColor?: number[];\n colorMask?: number;\n scissorRect?: number[];\n layerFilter?: ((context: FilterContext) => boolean) | null;\n shaderModuleProps?: any;\n /** Stores returned results from Effect.preRender, for use downstream in the render pipeline */\n preRenderStats?: Record;\n};\n\nexport type DrawLayerParameters = {\n shouldDrawLayer: boolean;\n layerRenderIndex: number;\n shaderModuleProps: any;\n layerParameters: Parameters;\n};\n\nexport type FilterContext = {\n layer: Layer;\n viewport: Viewport;\n isPicking: boolean;\n renderPass: string;\n cullRect?: Rect;\n};\n\nexport type RenderStats = {\n totalCount: number;\n visibleCount: number;\n compositeCount: number;\n pickableCount: number;\n};\n\n/** A Pass that renders all layers */\nexport default class LayersPass extends Pass {\n _lastRenderIndex: number = -1;\n\n render(options: LayersPassRenderOptions): void {\n this._render(options);\n }\n\n protected _render(options: LayersPassRenderOptions): RenderStats[] {\n const canvasContext = this.device.canvasContext!;\n const framebuffer = options.target ?? canvasContext.getCurrentFramebuffer();\n const [width, height] = canvasContext.getDrawingBufferSize();\n\n // Explicitly specify clearColor and clearDepth, overriding render pass defaults.\n const clearCanvas = options.clearCanvas ?? true;\n const clearColor = options.clearColor ?? (clearCanvas ? [0, 0, 0, 0] : false);\n const clearDepth = clearCanvas ? 1 : false;\n const clearStencil = clearCanvas ? 0 : false;\n const colorMask = options.colorMask ?? 0xf;\n\n const parameters: RenderPassParameters = {viewport: [0, 0, width, height]};\n if (options.colorMask) {\n parameters.colorMask = colorMask;\n }\n if (options.scissorRect) {\n parameters.scissorRect = options.scissorRect as NumberArray4;\n }\n\n const renderPass = this.device.beginRenderPass({\n framebuffer,\n parameters,\n clearColor: clearColor as NumberArray4,\n clearDepth,\n clearStencil\n });\n\n try {\n return this._drawLayers(renderPass, options);\n } finally {\n renderPass.end();\n // TODO(ibgreen): WebGPU - submit may not be needed here but initial port had issues with out of render loop rendering\n this.device.submit();\n }\n }\n\n /** Draw a list of layers in a list of viewports */\n private _drawLayers(renderPass: RenderPass, options: LayersPassRenderOptions) {\n const {\n target,\n shaderModuleProps,\n viewports,\n views,\n onViewportActive,\n clearStack = true\n } = options;\n options.pass = options.pass || 'unknown';\n\n if (clearStack) {\n this._lastRenderIndex = -1;\n }\n\n const renderStats: RenderStats[] = [];\n\n for (const viewport of viewports) {\n const view = views && views[viewport.id];\n\n // Update context to point to this viewport\n onViewportActive?.(viewport);\n\n const drawLayerParams = this._getDrawLayerParams(viewport, options);\n\n // render this viewport\n const subViewports = viewport.subViewports || [viewport];\n for (const subViewport of subViewports) {\n const stats = this._drawLayersInViewport(\n renderPass,\n {\n target,\n shaderModuleProps,\n viewport: subViewport,\n view,\n pass: options.pass,\n layers: options.layers\n },\n drawLayerParams\n );\n renderStats.push(stats);\n }\n }\n return renderStats;\n }\n\n // When a viewport contains multiple subviewports (e.g. repeated web mercator map),\n // this is only done once for the parent viewport\n /* Resolve the parameters needed to draw each layer */\n protected _getDrawLayerParams(\n viewport: Viewport,\n {\n layers,\n pass,\n isPicking = false,\n layerFilter,\n cullRect,\n effects,\n shaderModuleProps\n }: LayersPassRenderOptions,\n /** Internal flag, true if only used to determine whether each layer should be drawn */\n evaluateShouldDrawOnly: boolean = false\n ): DrawLayerParameters[] {\n const drawLayerParams: DrawLayerParameters[] = [];\n const indexResolver = layerIndexResolver(this._lastRenderIndex + 1);\n const drawContext: FilterContext = {\n layer: layers[0],\n viewport,\n isPicking,\n renderPass: pass,\n cullRect\n };\n const layerFilterCache = {};\n for (let layerIndex = 0; layerIndex < layers.length; layerIndex++) {\n const layer = layers[layerIndex];\n // Check if we should draw layer\n const shouldDrawLayer = this._shouldDrawLayer(\n layer,\n drawContext,\n layerFilter,\n layerFilterCache\n );\n\n const layerParam = {shouldDrawLayer} as DrawLayerParameters;\n\n if (shouldDrawLayer && !evaluateShouldDrawOnly) {\n layerParam.shouldDrawLayer = true;\n\n // This is the \"logical\" index for ordering this layer in the stack\n // used to calculate polygon offsets\n // It can be the same as another layer\n layerParam.layerRenderIndex = indexResolver(layer, shouldDrawLayer);\n\n layerParam.shaderModuleProps = this._getShaderModuleProps(\n layer,\n effects,\n pass,\n shaderModuleProps\n );\n const defaultParams =\n layer.context.device.type === 'webgpu' ? WEBGPU_DEFAULT_DRAW_PARAMETERS : null;\n layerParam.layerParameters = {\n ...defaultParams,\n ...layer.context.deck?.props.parameters,\n ...this.getLayerParameters(layer, layerIndex, viewport)\n };\n }\n\n drawLayerParams[layerIndex] = layerParam;\n }\n return drawLayerParams;\n }\n\n // Draws a list of layers in one viewport\n // TODO - when picking we could completely skip rendering viewports that dont\n // intersect with the picking rect\n /* eslint-disable max-depth, max-statements, complexity */\n private _drawLayersInViewport(\n renderPass: RenderPass,\n {\n layers,\n shaderModuleProps: globalModuleParameters,\n pass,\n target,\n viewport,\n view\n }: {\n layers: Layer[];\n shaderModuleProps: Record;\n pass: string;\n target?: Framebuffer | null;\n viewport: Viewport;\n view?: View;\n },\n drawLayerParams: DrawLayerParameters[]\n ): RenderStats {\n const glViewport = getGLViewport(this.device, {\n shaderModuleProps: globalModuleParameters,\n target,\n viewport\n });\n\n if (view) {\n const {clear, clearColor, clearDepth, clearStencil} = view.props;\n if (clear) {\n // If clear option is set, clear all buffers by default.\n let colorToUse: NumberArray4 | false = [0, 0, 0, 0];\n let depthToUse: number | false = 1.0;\n let stencilToUse: number | false = 0;\n\n if (Array.isArray(clearColor)) {\n colorToUse = [...clearColor.slice(0, 3), clearColor[3] || 255].map(\n c => c / 255\n ) as NumberArray4;\n } else if (clearColor === false) {\n colorToUse = false;\n }\n\n if (clearDepth !== undefined) {\n depthToUse = clearDepth;\n }\n\n if (clearStencil !== undefined) {\n stencilToUse = clearStencil;\n }\n\n const clearRenderPass = this.device.beginRenderPass({\n framebuffer: target,\n parameters: {\n viewport: glViewport,\n scissorRect: glViewport\n },\n clearColor: colorToUse,\n clearDepth: depthToUse,\n clearStencil: stencilToUse\n });\n clearRenderPass.end();\n }\n }\n\n // render layers in normal colors\n const renderStatus = {\n totalCount: layers.length,\n visibleCount: 0,\n compositeCount: 0,\n pickableCount: 0\n };\n\n renderPass.setParameters({viewport: glViewport});\n\n // render layers in normal colors\n for (let layerIndex = 0; layerIndex < layers.length; layerIndex++) {\n const layer = layers[layerIndex];\n const drawLayerParameters = drawLayerParams[layerIndex];\n const {shouldDrawLayer} = drawLayerParameters;\n\n // Calculate stats\n if (shouldDrawLayer && layer.props.pickable) {\n renderStatus.pickableCount++;\n }\n if (layer.isComposite) {\n renderStatus.compositeCount++;\n }\n if (layer.isDrawable && drawLayerParameters.shouldDrawLayer) {\n const {layerRenderIndex, shaderModuleProps, layerParameters} = drawLayerParameters;\n // Draw the layer\n renderStatus.visibleCount++;\n\n this._lastRenderIndex = Math.max(this._lastRenderIndex, layerRenderIndex);\n\n // overwrite layer.context.viewport with the sub viewport\n if (shaderModuleProps.project) {\n shaderModuleProps.project.viewport = viewport;\n }\n\n // TODO v9 - we are sending renderPass both as a parameter and through the context.\n // Long-term, it is likely better not to have user defined layer methods have to access\n // the \"global\" layer context.\n layer.context.renderPass = renderPass;\n\n try {\n layer._drawLayer({\n renderPass,\n shaderModuleProps,\n uniforms: {layerIndex: layerRenderIndex},\n parameters: layerParameters\n });\n } catch (err) {\n layer.raiseError(err as Error, `drawing ${layer} to ${pass}`);\n }\n }\n }\n\n return renderStatus;\n }\n /* eslint-enable max-depth, max-statements */\n\n /* Methods for subclass overrides */\n shouldDrawLayer(layer: Layer): boolean {\n return true;\n }\n\n protected getShaderModuleProps(\n layer: Layer,\n effects: Effect[] | undefined,\n otherShaderModuleProps: Record\n ): any {\n return null;\n }\n\n protected getLayerParameters(layer: Layer, layerIndex: number, viewport: Viewport): Parameters {\n return layer.props.parameters;\n }\n\n /* Private */\n private _shouldDrawLayer(\n layer: Layer,\n drawContext: FilterContext,\n layerFilter: ((params: FilterContext) => boolean) | undefined | null,\n layerFilterCache: Record\n ) {\n const shouldDrawLayer = layer.props.visible && this.shouldDrawLayer(layer);\n\n if (!shouldDrawLayer) {\n return false;\n }\n\n drawContext.layer = layer;\n\n let parent = layer.parent;\n while (parent) {\n // @ts-ignore\n if (!parent.props.visible || !parent.filterSubLayer(drawContext)) {\n return false;\n }\n drawContext.layer = parent;\n parent = parent.parent;\n }\n\n if (layerFilter) {\n const rootLayerId = drawContext.layer.id;\n if (!(rootLayerId in layerFilterCache)) {\n layerFilterCache[rootLayerId] = layerFilter(drawContext);\n }\n if (!layerFilterCache[rootLayerId]) {\n return false;\n }\n }\n\n // If a layer is drawn, update its viewportChanged flag\n layer.activateViewport(drawContext.viewport);\n\n return true;\n }\n\n private _getShaderModuleProps(\n layer: Layer,\n effects: Effect[] | undefined,\n pass: string,\n overrides: any\n ): any {\n // @ts-expect-error TODO - assuming WebGL context\n const devicePixelRatio = this.device.canvasContext.cssToDeviceRatio();\n const layerProps = layer.internalState?.propsInTransition || layer.props;\n\n const shaderModuleProps = {\n layer: layerProps,\n picking: {\n isActive: false\n } satisfies PickingProps,\n project: {\n viewport: layer.context.viewport,\n devicePixelRatio,\n modelMatrix: layerProps.modelMatrix,\n coordinateSystem: layerProps.coordinateSystem,\n coordinateOrigin: layerProps.coordinateOrigin,\n autoWrapLongitude: layer.wrapLongitude\n } satisfies ProjectProps\n };\n\n if (effects) {\n for (const effect of effects) {\n mergeModuleParameters(\n shaderModuleProps,\n effect.getShaderModuleProps?.(layer, shaderModuleProps)\n );\n }\n }\n\n return mergeModuleParameters(\n shaderModuleProps,\n this.getShaderModuleProps(layer, effects, shaderModuleProps),\n overrides\n );\n }\n}\n\n// If the _index prop is defined, return a layer index that's relative to its parent\n// Otherwise return the index of the layer among all rendered layers\n// This is done recursively, i.e. if the user overrides a layer's default index,\n// all its descendants will be resolved relative to that index.\n// This implementation assumes that parent layers always appear before its children\n// which is true if the layer array comes from the LayerManager\nexport function layerIndexResolver(\n startIndex: number = 0,\n layerIndices: Record = {}\n): (layer: Layer, isDrawn: boolean) => number {\n const resolvers = {};\n\n const resolveLayerIndex = (layer, isDrawn) => {\n const indexOverride = layer.props._offset;\n const layerId = layer.id;\n const parentId = layer.parent && layer.parent.id;\n\n let index;\n\n if (parentId && !(parentId in layerIndices)) {\n // Populate layerIndices with the parent layer's index\n resolveLayerIndex(layer.parent, false);\n }\n\n if (parentId in resolvers) {\n const resolver = (resolvers[parentId] =\n resolvers[parentId] || layerIndexResolver(layerIndices[parentId], layerIndices));\n index = resolver(layer, isDrawn);\n resolvers[layerId] = resolver;\n } else if (Number.isFinite(indexOverride)) {\n index = indexOverride + (layerIndices[parentId] || 0);\n // Mark layer as needing its own resolver\n // We don't actually create it until it's used for the first time\n resolvers[layerId] = null;\n } else {\n index = startIndex;\n }\n\n if (isDrawn && index >= startIndex) {\n startIndex = index + 1;\n }\n\n layerIndices[layerId] = index;\n return index;\n };\n return resolveLayerIndex;\n}\n\n// Convert viewport top-left CSS coordinates to bottom up WebGL coordinates\nfunction getGLViewport(\n device: Device,\n {\n shaderModuleProps,\n target,\n viewport\n }: {\n shaderModuleProps: any;\n target?: Framebuffer | null;\n viewport: Viewport;\n }\n): [number, number, number, number] {\n const pixelRatio =\n shaderModuleProps?.project?.devicePixelRatio ??\n // @ts-expect-error TODO - assuming WebGL context\n device.canvasContext.cssToDeviceRatio();\n\n // Default framebuffer is used when writing to canvas\n // @ts-expect-error TODO - assuming WebGL context\n const [, drawingBufferHeight] = device.canvasContext.getDrawingBufferSize();\n const height = target ? target.height : drawingBufferHeight;\n\n // Convert viewport top-left CSS coordinates to bottom up WebGL coordinates\n const dimensions = viewport;\n return [\n dimensions.x * pixelRatio,\n height - (dimensions.y + dimensions.height) * pixelRatio,\n dimensions.width * pixelRatio,\n dimensions.height * pixelRatio\n ];\n}\n\nfunction mergeModuleParameters(\n target: Record,\n ...sources: Record[]\n): Record {\n for (const source of sources) {\n if (source) {\n for (const key in source) {\n if (target[key]) {\n Object.assign(target[key], source[key]);\n } else {\n target[key] = source[key];\n }\n }\n }\n }\n return target;\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Device, Framebuffer, Parameters, Texture} from '@luma.gl/core';\nimport type Layer from '../lib/layer';\nimport type Viewport from '../viewports/viewport';\nimport LayersPass from './layers-pass';\n\nexport default class ShadowPass extends LayersPass {\n fbo: Framebuffer;\n\n constructor(\n device: Device,\n props?: {\n id;\n }\n ) {\n super(device, props);\n\n // The shadowMap texture\n const shadowMap = device.createTexture({\n format: 'rgba8unorm',\n width: 1,\n height: 1,\n sampler: {\n minFilter: 'linear',\n magFilter: 'linear',\n addressModeU: 'clamp-to-edge',\n addressModeV: 'clamp-to-edge'\n }\n // TODO - texture API change in luma.gl v9.2\n // mipmaps: true\n });\n\n const depthBuffer = device.createTexture({format: 'depth16unorm', width: 1, height: 1});\n\n this.fbo = device.createFramebuffer({\n id: 'shadowmap',\n width: 1,\n height: 1,\n colorAttachments: [shadowMap],\n // Depth attachment has to be specified for depth test to work\n depthStencilAttachment: depthBuffer\n });\n }\n\n delete() {\n if (this.fbo) {\n this.fbo.destroy();\n this.fbo = null!;\n }\n }\n\n getShadowMap(): Texture {\n return this.fbo.colorAttachments[0].texture;\n }\n\n render(params) {\n const target = this.fbo;\n\n // @ts-expect-error TODO - assuming WebGL context\n const pixelRatio = this.device.canvasContext.cssToDeviceRatio();\n\n const viewport = params.viewports[0];\n const width = viewport.width * pixelRatio;\n const height = viewport.height * pixelRatio;\n const clearColor = [1, 1, 1, 1];\n if (width !== target.width || height !== target.height) {\n target.resize({width, height});\n }\n\n super.render({...params, clearColor, target, pass: 'shadow'});\n }\n\n protected getLayerParameters(\n layer: Layer<{}>,\n layerIndex: number,\n viewport: Viewport\n ): Parameters {\n return {\n ...layer.props.parameters,\n blend: false,\n depthWriteEnabled: true,\n depthCompare: 'less-equal'\n };\n }\n\n shouldDrawLayer(layer) {\n return layer.props.shadowEnabled !== false;\n }\n\n getShaderModuleProps(layer: Layer, effects: any, otherShaderModuleProps: Record) {\n return {\n shadow: {\n project: otherShaderModuleProps.project,\n drawToShadowMap: true\n }\n };\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '@luma.gl/core';\nimport {Texture} from '@luma.gl/core';\nimport {AmbientLight} from './ambient-light';\nimport {DirectionalLight} from './directional-light';\nimport {PointLight} from './point-light';\nimport {Matrix4, Vector3} from '@math.gl/core';\nimport ShadowPass from '../../passes/shadow-pass';\nimport shadow from '../../shaderlib/shadow/shadow';\n\nimport type {Light, LightingProps} from '@luma.gl/shadertools';\nimport type {ShadowModuleProps} from '../../shaderlib/shadow/shadow';\nimport type Layer from '../../lib/layer';\nimport type {Effect, EffectContext, PreRenderOptions} from '../../lib/effect';\n\nconst DEFAULT_AMBIENT_LIGHT_PROPS = {\n color: [255, 255, 255] as [number, number, number],\n intensity: 1.0\n};\nconst DEFAULT_DIRECTIONAL_LIGHT_PROPS = [\n {\n color: [255, 255, 255] as [number, number, number],\n intensity: 1.0,\n direction: [-1, 3, -1] as [number, number, number]\n },\n {\n color: [255, 255, 255] as [number, number, number],\n intensity: 0.9,\n direction: [1, -8, -2.5] as [number, number, number]\n }\n];\nconst DEFAULT_SHADOW_COLOR = [0, 0, 0, 200 / 255] as [number, number, number, number];\n\nexport type LightingEffectProps = Record;\n\n// Class to manage ambient, point and directional light sources in deck\nexport default class LightingEffect implements Effect {\n id = 'lighting-effect';\n props!: LightingEffectProps;\n shadowColor: [number, number, number, number] = DEFAULT_SHADOW_COLOR;\n context?: EffectContext;\n\n private shadow: boolean = false;\n private ambientLight?: AmbientLight;\n private directionalLights: DirectionalLight[] = [];\n private pointLights: PointLight[] = [];\n private shadowPasses: ShadowPass[] = [];\n private dummyShadowMap: Texture | null = null;\n private shadowMatrices?: Matrix4[];\n\n constructor(props: LightingEffectProps = {}) {\n this.setProps(props);\n }\n\n setup(context: EffectContext) {\n this.context = context;\n const {device, deck} = context;\n\n if (this.shadow && !this.dummyShadowMap) {\n this._createShadowPasses(device);\n\n deck._addDefaultShaderModule(shadow);\n\n this.dummyShadowMap = device.createTexture({\n width: 1,\n height: 1\n });\n }\n }\n\n setProps(props: LightingEffectProps) {\n this.ambientLight = undefined;\n this.directionalLights = [];\n this.pointLights = [];\n\n for (const key in props) {\n const lightSource = props[key];\n\n switch (lightSource.type) {\n case 'ambient':\n this.ambientLight = lightSource;\n break;\n\n case 'directional':\n this.directionalLights.push(lightSource);\n break;\n\n case 'point':\n this.pointLights.push(lightSource);\n break;\n default:\n }\n }\n this._applyDefaultLights();\n\n this.shadow = this.directionalLights.some(light => light.shadow);\n if (this.context) {\n // Create resources if necessary\n this.setup(this.context);\n }\n this.props = props;\n }\n\n preRender({layers, layerFilter, viewports, onViewportActive, views}: PreRenderOptions) {\n if (!this.shadow) return;\n\n // create light matrix every frame to make sure always updated from light source\n this.shadowMatrices = this._calculateMatrices();\n\n for (let i = 0; i < this.shadowPasses.length; i++) {\n const shadowPass = this.shadowPasses[i];\n shadowPass.render({\n layers,\n layerFilter,\n viewports,\n onViewportActive,\n views,\n shaderModuleProps: {\n shadow: {\n shadowLightId: i,\n dummyShadowMap: this.dummyShadowMap,\n shadowMatrices: this.shadowMatrices\n }\n }\n });\n }\n }\n\n getShaderModuleProps(layer: Layer, otherShaderModuleProps: Record) {\n const shadowProps = this.shadow\n ? ({\n project: otherShaderModuleProps.project,\n shadowMaps: this.shadowPasses.map(shadowPass => shadowPass.getShadowMap()),\n dummyShadowMap: this.dummyShadowMap!,\n shadowColor: this.shadowColor,\n shadowMatrices: this.shadowMatrices\n } satisfies ShadowModuleProps)\n : {};\n\n const lightingProps: LightingProps = {\n enabled: true,\n lights: this._getLights(layer)\n };\n // @ts-expect-error material is not a Layer prop\n const materialProps = layer.props.material;\n\n return {\n shadow: shadowProps,\n lighting: lightingProps,\n phongMaterial: materialProps,\n gouraudMaterial: materialProps\n };\n }\n\n cleanup(context: EffectContext): void {\n for (const shadowPass of this.shadowPasses) {\n shadowPass.delete();\n }\n this.shadowPasses.length = 0;\n\n if (this.dummyShadowMap) {\n this.dummyShadowMap.destroy();\n this.dummyShadowMap = null;\n context.deck._removeDefaultShaderModule(shadow);\n }\n }\n\n private _calculateMatrices(): Matrix4[] {\n const lightMatrices: Matrix4[] = [];\n for (const light of this.directionalLights) {\n const viewMatrix = new Matrix4().lookAt({\n eye: new Vector3(light.direction).negate()\n });\n\n lightMatrices.push(viewMatrix);\n }\n return lightMatrices;\n }\n\n private _createShadowPasses(device: Device): void {\n for (let i = 0; i < this.directionalLights.length; i++) {\n const shadowPass = new ShadowPass(device);\n this.shadowPasses[i] = shadowPass;\n }\n }\n\n private _applyDefaultLights(): void {\n const {ambientLight, pointLights, directionalLights} = this;\n if (!ambientLight && pointLights.length === 0 && directionalLights.length === 0) {\n this.ambientLight = new AmbientLight(DEFAULT_AMBIENT_LIGHT_PROPS);\n this.directionalLights.push(\n new DirectionalLight(DEFAULT_DIRECTIONAL_LIGHT_PROPS[0]),\n new DirectionalLight(DEFAULT_DIRECTIONAL_LIGHT_PROPS[1])\n );\n }\n }\n\n private _getLights(layer: Layer): Light[] {\n const lights: Light[] = [];\n\n if (this.ambientLight) {\n lights.push(this.ambientLight);\n }\n\n for (const pointLight of this.pointLights) {\n lights.push(pointLight.getProjectedLight({layer}));\n }\n\n for (const directionalLight of this.directionalLights) {\n lights.push(directionalLight.getProjectedLight({layer}));\n }\n\n return lights;\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {TypedArray, TypedArrayConstructor} from '../types/types';\n\nexport type TypedArrayManagerOptions = {\n overAlloc?: number;\n poolSize?: number;\n};\n\nexport class TypedArrayManager {\n private _pool: ArrayBuffer[] = [];\n opts: {\n overAlloc: number;\n poolSize: number;\n } = {overAlloc: 2, poolSize: 100};\n\n constructor(options: TypedArrayManagerOptions = {}) {\n this.setOptions(options);\n }\n\n setOptions(options: TypedArrayManagerOptions) {\n Object.assign(this.opts, options);\n }\n\n allocate(\n typedArray: T | null | undefined,\n count: number,\n {\n size = 1,\n type,\n padding = 0,\n copy = false,\n initialize = false,\n maxCount\n }: {\n size?: number;\n type?: TypedArrayConstructor;\n padding?: number;\n copy?: boolean;\n initialize?: boolean;\n maxCount?: number;\n }\n ): T {\n const Type =\n type || (typedArray && (typedArray.constructor as TypedArrayConstructor)) || Float32Array;\n\n const newSize = count * size + padding;\n if (ArrayBuffer.isView(typedArray)) {\n if (newSize <= typedArray.length) {\n return typedArray;\n }\n if (newSize * typedArray.BYTES_PER_ELEMENT <= typedArray.buffer.byteLength) {\n return new Type(typedArray.buffer as ArrayBuffer, 0, newSize) as T;\n }\n }\n\n let maxSize: number = Infinity;\n if (maxCount) {\n maxSize = maxCount * size + padding;\n }\n\n const newArray = this._allocate(Type, newSize, initialize, maxSize);\n\n if (typedArray && copy) {\n newArray.set(typedArray);\n } else if (!initialize) {\n // Hack - always initialize the first 4 elements. NaNs crash the Attribute validation\n newArray.fill(0, 0, 4);\n }\n\n this._release(typedArray);\n return newArray as T;\n }\n\n release(typedArray: TypedArray | null | undefined) {\n this._release(typedArray);\n }\n\n private _allocate(\n Type: TypedArrayConstructor,\n size: number,\n initialize: boolean,\n maxSize: number\n ): TypedArray {\n // Allocate at least one element to ensure a valid buffer\n let sizeToAllocate = Math.max(Math.ceil(size * this.opts.overAlloc), 1);\n // Don't over allocate after certain specified number of elements\n if (sizeToAllocate > maxSize) {\n sizeToAllocate = maxSize;\n }\n\n // Check if available in pool\n const pool = this._pool;\n const byteLength = Type.BYTES_PER_ELEMENT * sizeToAllocate;\n const i = pool.findIndex(b => b.byteLength >= byteLength);\n if (i >= 0) {\n // Create a new array using an existing buffer\n const array = new Type(pool.splice(i, 1)[0], 0, sizeToAllocate);\n if (initialize) {\n // Viewing a buffer with a different type may create NaNs\n array.fill(0);\n }\n return array;\n }\n return new Type(sizeToAllocate);\n }\n\n private _release(typedArray: TypedArray | null | undefined): void {\n if (!ArrayBuffer.isView(typedArray)) {\n return;\n }\n const pool = this._pool;\n const {buffer} = typedArray;\n // Save the buffer of the released array into the pool\n // Sort buffers by size\n // TODO - implement binary search?\n const {byteLength} = buffer;\n const i = pool.findIndex(b => b.byteLength >= byteLength);\n if (i < 0) {\n pool.push(buffer as ArrayBuffer);\n } else if (i > 0 || pool.length < this.opts.poolSize) {\n pool.splice(i, 0, buffer as ArrayBuffer);\n }\n if (pool.length > this.opts.poolSize) {\n // Drop the smallest one\n pool.shift();\n }\n }\n}\n\nexport default new TypedArrayManager();\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// Extensions to math.gl library. Intended to be folded back.\nimport typedArrayManager from './typed-array-manager';\nimport {Vector3, NumericArray} from '@math.gl/core';\n\nimport type {Matrix4} from '@math.gl/core';\n\n// Helper, avoids low-precision 32 bit matrices from gl-matrix mat4.create()\nexport function createMat4(): number[] {\n return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];\n}\n\nexport function mod(value: number, divisor: number): number {\n const modulus = value % divisor;\n return modulus < 0 ? divisor + modulus : modulus;\n}\n\n// Extract camera vectors (move to math library?)\nexport function getCameraPosition(\n viewMatrixInverse: Matrix4 | NumericArray\n): [number, number, number] {\n // Read the translation from the inverse view matrix\n return [viewMatrixInverse[12], viewMatrixInverse[13], viewMatrixInverse[14]];\n}\n\nexport function getProjectionParameters(projectionMatrix: Matrix4 | NumericArray): {\n near: number;\n far: number;\n} {\n const m22 = projectionMatrix[10];\n const m23 = projectionMatrix[14];\n return {\n near: m23 / (m22 - 1),\n far: m23 / (m22 + 1)\n };\n}\n\nexport type FrustumPlane = {\n distance: number;\n normal: Vector3;\n};\n\n// https://www.gamedevs.org/uploads/fast-extraction-viewing-frustum-planes-from-world-view-projection-matrix.pdf\nexport function getFrustumPlanes(viewProjectionMatrix: Matrix4 | NumericArray): {\n left: FrustumPlane;\n right: FrustumPlane;\n top: FrustumPlane;\n bottom: FrustumPlane;\n near: FrustumPlane;\n far: FrustumPlane;\n} {\n return {\n left: getFrustumPlane(\n viewProjectionMatrix[3] + viewProjectionMatrix[0],\n viewProjectionMatrix[7] + viewProjectionMatrix[4],\n viewProjectionMatrix[11] + viewProjectionMatrix[8],\n viewProjectionMatrix[15] + viewProjectionMatrix[12]\n ),\n right: getFrustumPlane(\n viewProjectionMatrix[3] - viewProjectionMatrix[0],\n viewProjectionMatrix[7] - viewProjectionMatrix[4],\n viewProjectionMatrix[11] - viewProjectionMatrix[8],\n viewProjectionMatrix[15] - viewProjectionMatrix[12]\n ),\n bottom: getFrustumPlane(\n viewProjectionMatrix[3] + viewProjectionMatrix[1],\n viewProjectionMatrix[7] + viewProjectionMatrix[5],\n viewProjectionMatrix[11] + viewProjectionMatrix[9],\n viewProjectionMatrix[15] + viewProjectionMatrix[13]\n ),\n top: getFrustumPlane(\n viewProjectionMatrix[3] - viewProjectionMatrix[1],\n viewProjectionMatrix[7] - viewProjectionMatrix[5],\n viewProjectionMatrix[11] - viewProjectionMatrix[9],\n viewProjectionMatrix[15] - viewProjectionMatrix[13]\n ),\n near: getFrustumPlane(\n viewProjectionMatrix[3] + viewProjectionMatrix[2],\n viewProjectionMatrix[7] + viewProjectionMatrix[6],\n viewProjectionMatrix[11] + viewProjectionMatrix[10],\n viewProjectionMatrix[15] + viewProjectionMatrix[14]\n ),\n far: getFrustumPlane(\n viewProjectionMatrix[3] - viewProjectionMatrix[2],\n viewProjectionMatrix[7] - viewProjectionMatrix[6],\n viewProjectionMatrix[11] - viewProjectionMatrix[10],\n viewProjectionMatrix[15] - viewProjectionMatrix[14]\n )\n };\n}\n\nconst scratchVector = new Vector3();\n\nfunction getFrustumPlane(a: number, b: number, c: number, d: number): FrustumPlane {\n scratchVector.set(a, b, c);\n const L = scratchVector.len();\n return {distance: d / L, normal: new Vector3(-a / L, -b / L, -c / L)};\n}\n\n/**\n * Calculate the low part of a WebGL 64 bit float\n * @param x {number} - the input float number\n * @returns {number} - the lower 32 bit of the number\n */\nexport function fp64LowPart(x: number): number {\n return x - Math.fround(x);\n}\n\nlet scratchArray;\n\n/**\n * Split a Float64Array into a double-length Float32Array\n * @param typedArray\n * @param options\n * @param options.size - per attribute size\n * @param options.startIndex - start index in the source array\n * @param options.endIndex - end index in the source array\n * @returns {} - high part, low part for each attribute:\n [1xHi, 1yHi, 1zHi, 1xLow, 1yLow, 1zLow, 2xHi, ...]\n */\nexport function toDoublePrecisionArray(\n typedArray: Float64Array,\n options: {size?: number; startIndex?: number; endIndex?: number}\n): Float32Array {\n const {size = 1, startIndex = 0} = options;\n\n const endIndex = options.endIndex !== undefined ? options.endIndex : typedArray.length;\n\n const count = (endIndex - startIndex) / size;\n scratchArray = typedArrayManager.allocate(scratchArray, count, {\n type: Float32Array,\n size: size * 2\n });\n\n let sourceIndex = startIndex;\n let targetIndex = 0;\n while (sourceIndex < endIndex) {\n for (let j = 0; j < size; j++) {\n const value = typedArray[sourceIndex++];\n scratchArray[targetIndex + j] = value;\n scratchArray[targetIndex + j + size] = fp64LowPart(value);\n }\n targetIndex += size * 2;\n }\n\n return scratchArray.subarray(0, count * size * 2);\n}\n\ntype LayerBounds = [number[], number[]];\nexport function mergeBounds(boundsList: (LayerBounds | null)[]): LayerBounds | null {\n let mergedBounds: LayerBounds | null = null;\n let isMerged = false;\n\n for (const bounds of boundsList) {\n /* eslint-disable-next-line no-continue */\n if (!bounds) continue;\n if (!mergedBounds) {\n mergedBounds = bounds;\n } else {\n if (!isMerged) {\n // Copy to avoid mutating input bounds\n mergedBounds = [\n [mergedBounds[0][0], mergedBounds[0][1]],\n [mergedBounds[1][0], mergedBounds[1][1]]\n ];\n isMerged = true;\n }\n\n mergedBounds[0][0] = Math.min(mergedBounds[0][0], bounds[0][0]);\n mergedBounds[0][1] = Math.min(mergedBounds[0][1], bounds[0][1]);\n mergedBounds[1][0] = Math.max(mergedBounds[1][0], bounds[1][0]);\n mergedBounds[1][1] = Math.max(mergedBounds[1][1], bounds[1][1]);\n }\n }\n\n return mergedBounds;\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport log from '../utils/log';\nimport {createMat4, getCameraPosition, getFrustumPlanes, FrustumPlane} from '../utils/math-utils';\n\nimport {Matrix4, Vector3, equals, clamp, mat4} from '@math.gl/core';\n\nimport {\n getDistanceScales,\n getMeterZoom,\n lngLatToWorld,\n worldToLngLat,\n worldToPixels,\n pixelsToWorld\n} from '@math.gl/web-mercator';\n\nimport {PROJECTION_MODE} from '../lib/constants';\n\nexport type DistanceScales = {\n unitsPerMeter: number[];\n metersPerUnit: number[];\n};\n\nexport type Padding = {\n left?: number;\n right?: number;\n top?: number;\n bottom?: number;\n};\n\nexport type ViewportOptions = {\n /** Name of the viewport */\n id?: string;\n /** Left offset from the canvas edge, in pixels */\n x?: number;\n /** Top offset from the canvas edge, in pixels */\n y?: number;\n /** Viewport width in pixels */\n width?: number;\n /** Viewport height in pixels */\n height?: number;\n /** Longitude in degrees (geospatial only) */\n longitude?: number;\n /** Latitude in degrees (geospatial only) */\n latitude?: number;\n /** Viewport center in world space. If geospatial, refers to meter offsets from lng, lat, elevation */\n position?: number[];\n /** Zoom level */\n zoom?: number;\n /** Padding around the viewport, in pixels. */\n padding?: Padding | null;\n distanceScales?: DistanceScales;\n /** Model matrix of viewport center */\n modelMatrix?: number[] | null;\n /** Custom view matrix */\n viewMatrix?: number[];\n /** Custom projection matrix */\n projectionMatrix?: number[];\n /** Modifier of viewport scale. Corresponds to the number of pixels per common unit at zoom 0. */\n focalDistance?: number;\n /** Use orthographic projection */\n orthographic?: boolean;\n /** fovy in radians. If supplied, overrides fovy */\n fovyRadians?: number;\n /** fovy in degrees. */\n fovy?: number;\n /** Near plane of the projection matrix */\n near?: number;\n /** Far plane of the projection matrix */\n far?: number;\n};\n\nconst DEGREES_TO_RADIANS = Math.PI / 180;\n\nconst IDENTITY = createMat4();\n\nconst ZERO_VECTOR = [0, 0, 0];\n\nconst DEFAULT_DISTANCE_SCALES: DistanceScales = {\n unitsPerMeter: [1, 1, 1],\n metersPerUnit: [1, 1, 1]\n};\n\n// / Helpers\nfunction createProjectionMatrix({\n width,\n height,\n orthographic,\n fovyRadians,\n focalDistance,\n padding,\n near,\n far\n}: {\n width: number;\n height: number;\n orthographic: boolean;\n fovyRadians: number;\n focalDistance: number;\n padding: Padding | null;\n near: number;\n far: number;\n}) {\n const aspect = width / height;\n const matrix = orthographic\n ? new Matrix4().orthographic({fovy: fovyRadians, aspect, focalDistance, near, far})\n : new Matrix4().perspective({fovy: fovyRadians, aspect, near, far});\n if (padding) {\n const {left = 0, right = 0, top = 0, bottom = 0} = padding;\n const offsetX = clamp((left + width - right) / 2, 0, width) - width / 2;\n const offsetY = clamp((top + height - bottom) / 2, 0, height) - height / 2;\n // pixels to clip space\n matrix[8] -= (offsetX * 2) / width;\n matrix[9] += (offsetY * 2) / height;\n }\n return matrix;\n}\n\n/**\n * Manages coordinate system transformations.\n *\n * Note: The Viewport is immutable in the sense that it only has accessors.\n * A new viewport instance should be created if any parameters have changed.\n */\nexport default class Viewport {\n static displayName = 'Viewport';\n\n /** Init parameters */\n\n id: string;\n x: number;\n y: number;\n width: number;\n height: number;\n padding?: Padding | null;\n isGeospatial: boolean;\n zoom: number;\n focalDistance: number;\n position: number[];\n modelMatrix: number[] | null;\n\n /** Derived parameters */\n\n // `!` post-fix expression operator asserts that its operand is non-null and non-undefined in contexts\n // where the type checker is unable to conclude that fact.\n\n distanceScales: DistanceScales; /** scale factors between world space and common space */\n scale!: number; /** scale factor, equals 2^zoom */\n center!: number[]; /** viewport center in common space */\n cameraPosition!: number[]; /** Camera position in common space */\n projectionMatrix!: number[];\n viewMatrix!: number[];\n viewMatrixUncentered!: number[];\n viewMatrixInverse!: number[];\n viewProjectionMatrix!: number[];\n pixelProjectionMatrix!: number[];\n pixelUnprojectionMatrix!: number[];\n resolution?: number;\n\n private _frustumPlanes: {[name: string]: FrustumPlane} = {};\n\n // eslint-disable-next-line complexity\n constructor(opts: ViewportOptions = {}) {\n // @ts-ignore\n this.id = opts.id || this.constructor.displayName || 'viewport';\n\n this.x = opts.x || 0;\n this.y = opts.y || 0;\n // Silently allow apps to send in w,h = 0,0\n this.width = opts.width || 1;\n this.height = opts.height || 1;\n this.zoom = opts.zoom || 0;\n this.padding = opts.padding;\n this.distanceScales = opts.distanceScales || DEFAULT_DISTANCE_SCALES;\n this.focalDistance = opts.focalDistance || 1;\n this.position = opts.position || ZERO_VECTOR;\n this.modelMatrix = opts.modelMatrix || null;\n\n const {longitude, latitude} = opts;\n this.isGeospatial = Number.isFinite(latitude) && Number.isFinite(longitude);\n\n this._initProps(opts);\n this._initMatrices(opts);\n\n // Bind methods for easy access\n this.equals = this.equals.bind(this);\n this.project = this.project.bind(this);\n this.unproject = this.unproject.bind(this);\n this.projectPosition = this.projectPosition.bind(this);\n this.unprojectPosition = this.unprojectPosition.bind(this);\n this.projectFlat = this.projectFlat.bind(this);\n this.unprojectFlat = this.unprojectFlat.bind(this);\n }\n\n get subViewports(): Viewport[] | null {\n return null;\n }\n\n get metersPerPixel(): number {\n return this.distanceScales.metersPerUnit[2] / this.scale;\n }\n\n get projectionMode(): number {\n if (this.isGeospatial) {\n return this.zoom < 12\n ? PROJECTION_MODE.WEB_MERCATOR\n : PROJECTION_MODE.WEB_MERCATOR_AUTO_OFFSET;\n }\n return PROJECTION_MODE.IDENTITY;\n }\n\n // Two viewports are equal if width and height are identical, and if\n // their view and projection matrices are (approximately) equal.\n equals(viewport: Viewport): boolean {\n if (!(viewport instanceof Viewport)) {\n return false;\n }\n if (this === viewport) {\n return true;\n }\n\n return (\n viewport.width === this.width &&\n viewport.height === this.height &&\n viewport.scale === this.scale &&\n equals(viewport.projectionMatrix, this.projectionMatrix) &&\n equals(viewport.viewMatrix, this.viewMatrix)\n );\n // TODO - check distance scales?\n }\n\n /**\n * Projects xyz (possibly latitude and longitude) to pixel coordinates in window\n * using viewport projection parameters\n * - [longitude, latitude] to [x, y]\n * - [longitude, latitude, Z] => [x, y, z]\n * Note: By default, returns top-left coordinates for canvas/SVG type render\n *\n * @param {Array} lngLatZ - [lng, lat] or [lng, lat, Z]\n * @param {Object} opts - options\n * @param {Object} opts.topLeft=true - Whether projected coords are top left\n * @return {Array} - [x, y] or [x, y, z] in top left coords\n */\n project(xyz: number[], {topLeft = true}: {topLeft?: boolean} = {}): number[] {\n const worldPosition = this.projectPosition(xyz);\n const coord = worldToPixels(worldPosition, this.pixelProjectionMatrix);\n\n const [x, y] = coord;\n const y2 = topLeft ? y : this.height - y;\n return xyz.length === 2 ? [x, y2] : [x, y2, coord[2]];\n }\n\n /**\n * Unproject pixel coordinates on screen onto world coordinates,\n * (possibly [lon, lat]) on map.\n * - [x, y] => [lng, lat]\n * - [x, y, z] => [lng, lat, Z]\n * @param {Array} xyz -\n * @param {Object} opts - options\n * @param {Object} opts.topLeft=true - Whether origin is top left\n * @return {Array|null} - [lng, lat, Z] or [X, Y, Z]\n */\n unproject(\n xyz: number[],\n {topLeft = true, targetZ}: {topLeft?: boolean; targetZ?: number} = {}\n ): number[] {\n const [x, y, z] = xyz;\n\n const y2 = topLeft ? y : this.height - y;\n const targetZWorld = targetZ && targetZ * this.distanceScales.unitsPerMeter[2];\n const coord = pixelsToWorld([x, y2, z], this.pixelUnprojectionMatrix, targetZWorld);\n const [X, Y, Z] = this.unprojectPosition(coord);\n\n if (Number.isFinite(z)) {\n return [X, Y, Z];\n }\n return Number.isFinite(targetZ) ? [X, Y, targetZ as number] : [X, Y];\n }\n\n // NON_LINEAR PROJECTION HOOKS\n // Used for web meractor projection\n\n projectPosition(xyz: number[]): [number, number, number] {\n const [X, Y] = this.projectFlat(xyz);\n const Z = (xyz[2] || 0) * this.distanceScales.unitsPerMeter[2];\n return [X, Y, Z];\n }\n\n unprojectPosition(xyz: number[]): [number, number, number] {\n const [X, Y] = this.unprojectFlat(xyz);\n const Z = (xyz[2] || 0) * this.distanceScales.metersPerUnit[2];\n return [X, Y, Z];\n }\n\n /**\n * Project [lng,lat] on sphere onto [x,y] on 512*512 Mercator Zoom 0 tile.\n * Performs the nonlinear part of the web mercator projection.\n * Remaining projection is done with 4x4 matrices which also handles\n * perspective.\n * @param {Array} lngLat - [lng, lat] coordinates\n * Specifies a point on the sphere to project onto the map.\n * @return {Array} [x,y] coordinates.\n */\n projectFlat(xyz: number[]): [number, number] {\n if (this.isGeospatial) {\n // Shader clamps latitude to +-89.9, see /shaderlib/project/project.glsl.js\n // lngLatToWorld([0, -89.9])[1] = -317.9934163758329\n // lngLatToWorld([0, 89.9])[1] = 829.9934163758271\n const result = lngLatToWorld(xyz);\n result[1] = clamp(result[1], -318, 830);\n return result;\n }\n return xyz as [number, number];\n }\n\n /**\n * Unproject world point [x,y] on map onto {lat, lon} on sphere\n * @param {object|Vector} xy - object with {x,y} members\n * representing point on projected map plane\n * @return {GeoCoordinates} - object with {lat,lon} of point on sphere.\n * Has toArray method if you need a GeoJSON Array.\n * Per cartographic tradition, lat and lon are specified as degrees.\n */\n unprojectFlat(xyz: number[]): [number, number] {\n if (this.isGeospatial) {\n return worldToLngLat(xyz);\n }\n return xyz as [number, number];\n }\n\n /**\n * Get bounds of the current viewport\n * @return {Array} - [minX, minY, maxX, maxY]\n */\n getBounds(options: {z?: number} = {}): [number, number, number, number] {\n const unprojectOption = {targetZ: options.z || 0};\n\n const topLeft = this.unproject([0, 0], unprojectOption);\n const topRight = this.unproject([this.width, 0], unprojectOption);\n const bottomLeft = this.unproject([0, this.height], unprojectOption);\n const bottomRight = this.unproject([this.width, this.height], unprojectOption);\n\n return [\n Math.min(topLeft[0], topRight[0], bottomLeft[0], bottomRight[0]),\n Math.min(topLeft[1], topRight[1], bottomLeft[1], bottomRight[1]),\n Math.max(topLeft[0], topRight[0], bottomLeft[0], bottomRight[0]),\n Math.max(topLeft[1], topRight[1], bottomLeft[1], bottomRight[1])\n ];\n }\n\n getDistanceScales(coordinateOrigin?: number[]): DistanceScales {\n if (coordinateOrigin && this.isGeospatial) {\n return getDistanceScales({\n longitude: coordinateOrigin[0],\n latitude: coordinateOrigin[1],\n highPrecision: true\n });\n }\n return this.distanceScales;\n }\n\n containsPixel({\n x,\n y,\n width = 1,\n height = 1\n }: {\n x: number;\n y: number;\n width?: number;\n height?: number;\n }): boolean {\n return (\n x < this.x + this.width &&\n this.x < x + width &&\n y < this.y + this.height &&\n this.y < y + height\n );\n }\n\n // Extract frustum planes in common space\n getFrustumPlanes(): {\n left: FrustumPlane;\n right: FrustumPlane;\n bottom: FrustumPlane;\n top: FrustumPlane;\n near: FrustumPlane;\n far: FrustumPlane;\n } {\n if (this._frustumPlanes.near) {\n // @ts-ignore\n return this._frustumPlanes;\n }\n\n Object.assign(this._frustumPlanes, getFrustumPlanes(this.viewProjectionMatrix));\n\n // @ts-ignore\n return this._frustumPlanes;\n }\n\n // EXPERIMENTAL METHODS\n\n /**\n * Needed by panning and linear transition\n * Pan the viewport to place a given world coordinate at screen point [x, y]\n *\n * @param {Array} coords - world coordinates\n * @param {Array} pixel - [x,y] coordinates on screen\n * @param {Array} startPixel - [x,y] screen position where pan started (optional, for delta-based panning)\n * @return {Object} props of the new viewport\n */\n panByPosition(coords: number[], pixel: number[], startPixel?: number[]): any {\n return null;\n }\n\n // INTERNAL METHODS\n\n /* eslint-disable complexity, max-statements */\n private _initProps(opts: ViewportOptions) {\n const longitude = opts.longitude as number;\n const latitude = opts.latitude as number;\n\n if (this.isGeospatial) {\n if (!Number.isFinite(opts.zoom)) {\n this.zoom = getMeterZoom({latitude}) + Math.log2(this.focalDistance);\n }\n this.distanceScales = opts.distanceScales || getDistanceScales({latitude, longitude});\n }\n const scale = Math.pow(2, this.zoom);\n this.scale = scale;\n\n const {position, modelMatrix} = opts;\n let meterOffset: number[] = ZERO_VECTOR;\n if (position) {\n meterOffset = modelMatrix\n ? (new Matrix4(modelMatrix).transformAsVector(position, []) as number[])\n : position;\n }\n\n if (this.isGeospatial) {\n // Determine camera center in common space\n const center = this.projectPosition([longitude, latitude, 0]);\n\n this.center = new Vector3(meterOffset)\n // Convert to pixels in current zoom\n .scale(this.distanceScales.unitsPerMeter)\n .add(center);\n } else {\n this.center = this.projectPosition(meterOffset);\n }\n }\n /* eslint-enable complexity, max-statements */\n\n private _initMatrices(opts: ViewportOptions) {\n const {\n // View matrix\n viewMatrix = IDENTITY,\n // Projection matrix\n projectionMatrix = null,\n\n // Projection matrix parameters, used if projectionMatrix not supplied\n orthographic = false,\n fovyRadians,\n fovy = 75,\n near = 0.1, // Distance of near clipping plane\n far = 1000, // Distance of far clipping plane\n padding = null, // Center offset in pixels\n focalDistance = 1\n } = opts;\n\n this.viewMatrixUncentered = viewMatrix;\n // Make a centered version of the matrix for projection modes without an offset\n this.viewMatrix = new Matrix4()\n // Apply the uncentered view matrix\n .multiplyRight(viewMatrix)\n // And center it\n .translate(new Vector3(this.center).negate());\n\n this.projectionMatrix =\n projectionMatrix ||\n createProjectionMatrix({\n width: this.width,\n height: this.height,\n orthographic,\n fovyRadians: fovyRadians || fovy * DEGREES_TO_RADIANS,\n focalDistance,\n padding,\n near,\n far\n });\n\n // Note: As usual, matrix operations should be applied in \"reverse\" order\n // since vectors will be multiplied in from the right during transformation\n const vpm = createMat4();\n mat4.multiply(vpm, vpm, this.projectionMatrix);\n mat4.multiply(vpm, vpm, this.viewMatrix);\n this.viewProjectionMatrix = vpm;\n\n // console.log('VPM', this.viewMatrix, this.projectionMatrix, this.viewProjectionMatrix);\n\n // Calculate inverse view matrix\n this.viewMatrixInverse = mat4.invert([], this.viewMatrix) || this.viewMatrix;\n\n // Decompose camera parameters\n this.cameraPosition = getCameraPosition(this.viewMatrixInverse);\n\n /*\n * Builds matrices that converts preprojected lngLats to screen pixels\n * and vice versa.\n * Note: Currently returns bottom-left coordinates!\n * Note: Starts with the GL projection matrix and adds steps to the\n * scale and translate that matrix onto the window.\n * Note: WebGL controls clip space to screen projection with gl.viewport\n * and does not need this step.\n */\n\n // matrix for conversion from world location to screen (pixel) coordinates\n const viewportMatrix = createMat4(); // matrix from NDC to viewport.\n const pixelProjectionMatrix = createMat4(); // matrix from world space to viewport.\n mat4.scale(viewportMatrix, viewportMatrix, [this.width / 2, -this.height / 2, 1]);\n mat4.translate(viewportMatrix, viewportMatrix, [1, -1, 0]);\n mat4.multiply(pixelProjectionMatrix, viewportMatrix, this.viewProjectionMatrix);\n this.pixelProjectionMatrix = pixelProjectionMatrix;\n\n this.pixelUnprojectionMatrix = mat4.invert(createMat4(), this.pixelProjectionMatrix);\n if (!this.pixelUnprojectionMatrix) {\n log.warn('Pixel project matrix not invertible')();\n // throw new Error('Pixel project matrix not invertible');\n }\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// View and Projection Matrix calculations for mapbox-js style\n// map view properties\nimport Viewport from './viewport';\n\nimport {\n pixelsToWorld,\n getViewMatrix,\n addMetersToLngLat,\n unitsPerMeter,\n getProjectionParameters,\n altitudeToFovy,\n fovyToAltitude,\n fitBounds,\n getBounds\n} from '@math.gl/web-mercator';\nimport {Padding} from './viewport';\n\nimport {Matrix4, clamp, vec2} from '@math.gl/core';\n\nexport type WebMercatorViewportOptions = {\n /** Name of the viewport */\n id?: string;\n /** Left offset from the canvas edge, in pixels */\n x?: number;\n /** Top offset from the canvas edge, in pixels */\n y?: number;\n /** Viewport width in pixels */\n width?: number;\n /** Viewport height in pixels */\n height?: number;\n /** Longitude in degrees */\n longitude?: number;\n /** Latitude in degrees */\n latitude?: number;\n /** Tilt of the camera in degrees */\n pitch?: number;\n /** Heading of the camera in degrees */\n bearing?: number;\n /** Camera altitude relative to the viewport height, legacy property used to control the FOV. Default `1.5` */\n altitude?: number;\n /** Camera fovy in degrees. If provided, overrides `altitude` */\n fovy?: number;\n /** Viewport center in world space. If geospatial, refers to meter offsets from lng, lat, elevation */\n position?: number[];\n /** Zoom level */\n zoom?: number;\n /** Padding around the viewport, in pixels. */\n padding?: Padding | null;\n /** Model matrix of viewport center */\n modelMatrix?: number[] | null;\n /** Custom projection matrix */\n projectionMatrix?: number[];\n /** Use orthographic projection */\n orthographic?: boolean;\n /** Scaler for the near plane, 1 unit equals to the height of the viewport. Default `0.1` */\n nearZMultiplier?: number;\n /** Scaler for the far plane, 1 unit equals to the distance from the camera to the edge of the screen. Default `1.01` */\n farZMultiplier?: number;\n /** Optionally override the near plane position. `nearZMultiplier` is ignored if `nearZ` is supplied. */\n nearZ?: number;\n /** Optionally override the far plane position. `farZMultiplier` is ignored if `farZ` is supplied. */\n farZ?: number;\n /** Render multiple copies of the world */\n repeat?: boolean;\n /** Internal use */\n worldOffset?: number;\n /** @deprecated Revert to approximated meter size calculation prior to v8.5 */\n legacyMeterSizes?: boolean;\n};\n\n/**\n * Manages transformations to/from WGS84 coordinates using the Web Mercator Projection.\n */\nexport default class WebMercatorViewport extends Viewport {\n static displayName = 'WebMercatorViewport';\n\n longitude: number;\n latitude: number;\n pitch: number;\n bearing: number;\n altitude: number;\n fovy: number;\n orthographic: boolean;\n\n /** Each sub viewport renders one copy of the world if repeat:true. The list is generated and cached on first request. */\n private _subViewports: WebMercatorViewport[] | null;\n /** @deprecated Revert to approximated meter size calculation prior to v8.5 */\n private _pseudoMeters: boolean;\n\n /* eslint-disable complexity, max-statements */\n constructor(opts: WebMercatorViewportOptions = {}) {\n const {\n latitude = 0,\n longitude = 0,\n zoom = 0,\n pitch = 0,\n bearing = 0,\n nearZMultiplier = 0.1,\n farZMultiplier = 1.01,\n nearZ,\n farZ,\n orthographic = false,\n projectionMatrix,\n\n repeat = false,\n worldOffset = 0,\n position,\n padding,\n\n // backward compatibility\n // TODO: remove in v9\n legacyMeterSizes = false\n } = opts;\n\n let {width, height, altitude = 1.5} = opts;\n const scale = Math.pow(2, zoom);\n\n // Silently allow apps to send in 0,0 to facilitate isomorphic render etc\n width = width || 1;\n height = height || 1;\n\n let fovy;\n let projectionParameters: any = null;\n if (projectionMatrix) {\n altitude = projectionMatrix[5] / 2;\n fovy = altitudeToFovy(altitude);\n } else {\n if (opts.fovy) {\n fovy = opts.fovy;\n altitude = fovyToAltitude(fovy);\n } else {\n fovy = altitudeToFovy(altitude);\n }\n\n let offset: [number, number] | undefined;\n if (padding) {\n const {top = 0, bottom = 0} = padding;\n offset = [0, clamp((top + height - bottom) / 2, 0, height) - height / 2];\n }\n\n projectionParameters = getProjectionParameters({\n width,\n height,\n scale,\n center: position && [0, 0, position[2] * unitsPerMeter(latitude)],\n offset,\n pitch,\n fovy,\n nearZMultiplier,\n farZMultiplier\n });\n\n if (Number.isFinite(nearZ)) {\n projectionParameters.near = nearZ;\n }\n if (Number.isFinite(farZ)) {\n projectionParameters.far = farZ;\n }\n }\n\n // The uncentered matrix allows us two move the center addition to the\n // shader (cheap) which gives a coordinate system that has its center in\n // the layer's center position. This makes rotations and other modelMatrx\n // transforms much more useful.\n let viewMatrixUncentered = getViewMatrix({\n height,\n pitch,\n bearing,\n scale,\n altitude\n });\n\n if (worldOffset) {\n const viewOffset = new Matrix4().translate([512 * worldOffset, 0, 0]);\n viewMatrixUncentered = viewOffset.multiplyLeft(viewMatrixUncentered);\n }\n\n super({\n ...opts,\n // x, y,\n width,\n height,\n\n // view matrix\n viewMatrix: viewMatrixUncentered,\n longitude,\n latitude,\n zoom,\n\n // projection matrix parameters\n ...projectionParameters,\n fovy,\n focalDistance: altitude\n });\n\n // Save parameters\n this.latitude = latitude;\n this.longitude = longitude;\n this.zoom = zoom;\n this.pitch = pitch;\n this.bearing = bearing;\n this.altitude = altitude;\n this.fovy = fovy;\n\n this.orthographic = orthographic;\n\n this._subViewports = repeat ? [] : null;\n this._pseudoMeters = legacyMeterSizes;\n\n Object.freeze(this);\n }\n /* eslint-enable complexity, max-statements */\n\n get subViewports(): WebMercatorViewport[] | null {\n if (this._subViewports && !this._subViewports.length) {\n // Cache sub viewports so that we only calculate them once\n const bounds = this.getBounds();\n\n const minOffset = Math.floor((bounds[0] + 180) / 360);\n const maxOffset = Math.ceil((bounds[2] - 180) / 360);\n\n for (let x = minOffset; x <= maxOffset; x++) {\n const offsetViewport = x\n ? new WebMercatorViewport({\n ...this,\n worldOffset: x\n })\n : this;\n this._subViewports.push(offsetViewport);\n }\n }\n return this._subViewports;\n }\n\n projectPosition(xyz: number[]): [number, number, number] {\n if (this._pseudoMeters) {\n // Backward compatibility\n return super.projectPosition(xyz);\n }\n const [X, Y] = this.projectFlat(xyz);\n const Z = (xyz[2] || 0) * unitsPerMeter(xyz[1]);\n return [X, Y, Z];\n }\n\n unprojectPosition(xyz: number[]): [number, number, number] {\n if (this._pseudoMeters) {\n // Backward compatibility\n return super.unprojectPosition(xyz);\n }\n const [X, Y] = this.unprojectFlat(xyz);\n const Z = (xyz[2] || 0) / unitsPerMeter(Y);\n return [X, Y, Z];\n }\n\n /**\n * Add a meter delta to a base lnglat coordinate, returning a new lnglat array\n *\n * Note: Uses simple linear approximation around the viewport center\n * Error increases with size of offset (roughly 1% per 100km)\n *\n * @param {[Number,Number]|[Number,Number,Number]) lngLatZ - base coordinate\n * @param {[Number,Number]|[Number,Number,Number]) xyz - array of meter deltas\n * @return {[Number,Number]|[Number,Number,Number]) array of [lng,lat,z] deltas\n */\n addMetersToLngLat(lngLatZ: number[], xyz: number[]): number[] {\n return addMetersToLngLat(lngLatZ, xyz);\n }\n\n panByPosition(\n coords: number[],\n pixel: number[],\n startPixel?: number[]\n ): WebMercatorViewportOptions {\n const fromLocation = pixelsToWorld(pixel, this.pixelUnprojectionMatrix);\n const toLocation = this.projectFlat(coords);\n\n const translate = vec2.add([], toLocation, vec2.negate([], fromLocation));\n const newCenter = vec2.add([], this.center, translate);\n\n const [longitude, latitude] = this.unprojectFlat(newCenter);\n return {longitude, latitude};\n }\n\n /**\n * Returns a new longitude and latitude that keeps a 3D world coordinate at a given screen pixel\n * This version handles the z-component (altitude) properly for cameras positioned above ground\n */\n panByPosition3D(coords: number[], pixel: number[]): WebMercatorViewportOptions {\n const targetZ = coords[2] || 0;\n const deltaLngLat = vec2.sub([], coords, this.unproject(pixel, {targetZ}));\n return {longitude: this.longitude + deltaLngLat[0], latitude: this.latitude + deltaLngLat[1]};\n }\n\n getBounds(options: {z?: number} = {}): [number, number, number, number] {\n // @ts-ignore\n const corners = getBounds(this, options.z || 0);\n\n return [\n Math.min(corners[0][0], corners[1][0], corners[2][0], corners[3][0]),\n Math.min(corners[0][1], corners[1][1], corners[2][1], corners[3][1]),\n Math.max(corners[0][0], corners[1][0], corners[2][0], corners[3][0]),\n Math.max(corners[0][1], corners[1][1], corners[2][1], corners[3][1])\n ];\n }\n\n /**\n * Returns a new viewport that fit around the given rectangle.\n * Only supports non-perspective mode.\n */\n fitBounds(\n /** [[lon, lat], [lon, lat]] */\n bounds: [[number, number], [number, number]],\n options: {\n /** If not supplied, will use the current width of the viewport (default `1`) */\n width?: number;\n /** If not supplied, will use the current height of the viewport (default `1`) */\n height?: number;\n /** In degrees, 0.01 would be about 1000 meters */\n minExtent?: number;\n /** Max zoom level */\n maxZoom?: number;\n /** Extra padding in pixels */\n padding?: number | Required;\n /** Center shift in pixels */\n offset?: number[];\n } = {}\n ) {\n const {width, height} = this;\n const {longitude, latitude, zoom} = fitBounds({width, height, bounds, ...options});\n return new WebMercatorViewport({width, height, longitude, latitude, zoom});\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/**\n * Projection utils\n * TODO: move to Viewport class?\n */\nimport {getOffsetOrigin} from './viewport-uniforms';\nimport WebMercatorViewport from '../../viewports/web-mercator-viewport';\n\nimport {vec3, vec4} from '@math.gl/core';\nimport {addMetersToLngLat} from '@math.gl/web-mercator';\n\nimport type {CoordinateSystem} from '../../lib/constants';\nimport type Viewport from '../../viewports/viewport';\nimport type {NumericArray} from '../../types/types';\n\nconst DEFAULT_COORDINATE_ORIGIN = [0, 0, 0];\n\n// In project.glsl, offset modes calculate z differently from LNG_LAT mode.\n// offset modes apply the y adjustment (unitsPerMeter2) when projecting z\n// LNG_LAT mode only use the linear scale.\nfunction lngLatZToWorldPosition(\n lngLatZ: [number, number, number],\n viewport: Viewport,\n offsetMode: boolean = false\n): [number, number, number] {\n const p = viewport.projectPosition(lngLatZ);\n\n // TODO - avoid using instanceof\n if (offsetMode && viewport instanceof WebMercatorViewport) {\n const [longitude, latitude, z = 0] = lngLatZ;\n const distanceScales = viewport.getDistanceScales([longitude, latitude]);\n p[2] = z * distanceScales.unitsPerMeter[2];\n }\n return p;\n}\n\nfunction normalizeParameters(opts: {\n viewport: Viewport;\n coordinateSystem: CoordinateSystem;\n coordinateOrigin: [number, number, number];\n modelMatrix?: NumericArray | null;\n fromCoordinateSystem?: CoordinateSystem;\n fromCoordinateOrigin?: [number, number, number];\n}): {\n viewport: Viewport;\n coordinateSystem: CoordinateSystem;\n coordinateOrigin: [number, number, number];\n modelMatrix?: NumericArray | null;\n fromCoordinateSystem: CoordinateSystem;\n fromCoordinateOrigin: [number, number, number];\n} {\n const {viewport, modelMatrix, coordinateOrigin} = opts;\n let {coordinateSystem, fromCoordinateSystem, fromCoordinateOrigin} = opts;\n\n if (coordinateSystem === 'default') {\n coordinateSystem = viewport.isGeospatial ? 'lnglat' : 'cartesian';\n }\n\n if (fromCoordinateSystem === undefined) {\n fromCoordinateSystem = coordinateSystem;\n } else if (fromCoordinateSystem === 'default') {\n fromCoordinateSystem = viewport.isGeospatial ? 'lnglat' : 'cartesian';\n }\n if (fromCoordinateOrigin === undefined) {\n fromCoordinateOrigin = coordinateOrigin;\n }\n\n return {\n viewport,\n coordinateSystem,\n coordinateOrigin,\n modelMatrix,\n fromCoordinateSystem,\n fromCoordinateOrigin\n };\n}\n\n/** Get the common space position from world coordinates in the given coordinate system */\nexport function getWorldPosition(\n position: number[],\n {\n viewport,\n modelMatrix,\n coordinateSystem,\n coordinateOrigin,\n offsetMode\n }: {\n viewport: Viewport;\n modelMatrix?: NumericArray | null;\n coordinateSystem: CoordinateSystem;\n coordinateOrigin: [number, number, number];\n offsetMode?: boolean;\n }\n): [number, number, number] {\n let [x, y, z = 0] = position;\n\n if (modelMatrix) {\n [x, y, z] = vec4.transformMat4([], [x, y, z, 1.0], modelMatrix);\n }\n\n switch (coordinateSystem) {\n case 'default':\n return getWorldPosition(position, {\n viewport,\n modelMatrix,\n coordinateSystem: viewport.isGeospatial ? 'lnglat' : 'cartesian',\n coordinateOrigin,\n offsetMode\n });\n\n case 'lnglat':\n return lngLatZToWorldPosition([x, y, z], viewport, offsetMode);\n\n case 'lnglat-offsets':\n return lngLatZToWorldPosition(\n [x + coordinateOrigin[0], y + coordinateOrigin[1], z + (coordinateOrigin[2] || 0)],\n viewport,\n offsetMode\n );\n\n case 'meter-offsets':\n return lngLatZToWorldPosition(\n addMetersToLngLat(coordinateOrigin, [x, y, z]) as [number, number, number],\n viewport,\n offsetMode\n );\n\n case 'cartesian':\n return viewport.isGeospatial\n ? [x + coordinateOrigin[0], y + coordinateOrigin[1], z + coordinateOrigin[2]]\n : viewport.projectPosition([x, y, z]);\n\n default:\n throw new Error(`Invalid coordinateSystem: ${coordinateSystem}`);\n }\n}\n\n/**\n * Equivalent to project_position in project.glsl\n * projects a user supplied position to world position directly with or without\n * a reference coordinate system\n */\nexport function projectPosition(\n position: number[],\n params: {\n /** The current viewport */\n viewport: Viewport;\n /** The reference coordinate system used to align world position */\n coordinateSystem: CoordinateSystem;\n /** The reference coordinate origin used to align world position */\n coordinateOrigin: [number, number, number];\n /** The model matrix of the supplied position */\n modelMatrix?: NumericArray | null;\n /** The coordinate system that the supplied position is in. Default to the same as `coordinateSystem`. */\n fromCoordinateSystem?: CoordinateSystem;\n /** The coordinate origin that the supplied position is in. Default to the same as `coordinateOrigin`. */\n fromCoordinateOrigin?: [number, number, number];\n /** Whether to apply offset mode automatically as does the project shader module.\n * Offset mode places the origin of the common space at the given viewport's center. It is used in some use cases\n * to improve precision in the vertex shader due to the fp32 float limitation.\n * Use `autoOffset:false` if the returned position should not be dependent on the current viewport.\n * Default `true` */\n autoOffset?: boolean;\n }\n): [number, number, number] {\n const {\n viewport,\n coordinateSystem,\n coordinateOrigin,\n modelMatrix,\n fromCoordinateSystem,\n fromCoordinateOrigin\n } = normalizeParameters(params);\n const {autoOffset = true} = params;\n\n const {\n geospatialOrigin = DEFAULT_COORDINATE_ORIGIN,\n shaderCoordinateOrigin = DEFAULT_COORDINATE_ORIGIN,\n offsetMode = false\n } = autoOffset ? getOffsetOrigin(viewport, coordinateSystem, coordinateOrigin) : {};\n\n const worldPosition = getWorldPosition(position, {\n viewport,\n modelMatrix,\n coordinateSystem: fromCoordinateSystem,\n coordinateOrigin: fromCoordinateOrigin,\n offsetMode\n });\n\n if (offsetMode) {\n const positionCommonSpace = viewport.projectPosition(\n geospatialOrigin || shaderCoordinateOrigin\n );\n vec3.sub(worldPosition, worldPosition, positionCommonSpace);\n }\n\n return worldPosition;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/**\n * Timeline channel properties\n * @param delay = 0;\n * @param duration = Number.POSITIVE_INFINITY;\n * @param rate = 1\n * @param repeat = 1\n */\nexport type ChannelOptions = {\n delay?: number;\n duration?: number;\n rate?: number;\n repeat?: number;\n};\n\nexport type AnimationOptions = {\n setTime: (time: number) => void;\n};\n\ntype Channel = {\n time: number;\n delay: number;\n duration: number;\n rate: number;\n repeat: number;\n};\n\ntype Animation = {\n channel?: number;\n animation: {\n setTime: (time: number) => void;\n };\n};\n\nlet channelHandles = 1;\nlet animationHandles = 1;\n\nexport class Timeline {\n time: number = 0;\n channels = new Map();\n animations = new Map();\n playing: boolean = false;\n lastEngineTime: number = -1;\n\n constructor() {}\n\n addChannel(props: ChannelOptions): number {\n const {delay = 0, duration = Number.POSITIVE_INFINITY, rate = 1, repeat = 1} = props;\n\n const channelId = channelHandles++;\n const channel: Channel = {\n time: 0,\n delay,\n duration,\n rate,\n repeat\n };\n this._setChannelTime(channel, this.time);\n this.channels.set(channelId, channel);\n\n return channelId;\n }\n\n removeChannel(channelId: number): void {\n this.channels.delete(channelId);\n\n for (const [animationHandle, animation] of this.animations) {\n if (animation.channel === channelId) {\n this.detachAnimation(animationHandle);\n }\n }\n }\n\n isFinished(channelId: number): boolean {\n const channel = this.channels.get(channelId);\n if (channel === undefined) {\n return false;\n }\n\n return this.time >= channel.delay + channel.duration * channel.repeat;\n }\n\n getTime(channelId?: number): number {\n if (channelId === undefined) {\n return this.time;\n }\n\n const channel = this.channels.get(channelId);\n\n if (channel === undefined) {\n return -1;\n }\n\n return channel.time;\n }\n\n setTime(time: number): void {\n this.time = Math.max(0, time);\n\n const channels = this.channels.values();\n for (const channel of channels) {\n this._setChannelTime(channel, this.time);\n }\n\n const animations = this.animations.values();\n for (const animationData of animations) {\n const {animation, channel} = animationData;\n animation.setTime(this.getTime(channel));\n }\n }\n\n play(): void {\n this.playing = true;\n }\n\n pause(): void {\n this.playing = false;\n this.lastEngineTime = -1;\n }\n\n reset(): void {\n this.setTime(0);\n }\n\n attachAnimation(animation: AnimationOptions, channelHandle?: number): number {\n const animationHandle = animationHandles++;\n\n this.animations.set(animationHandle, {\n animation,\n channel: channelHandle\n });\n\n animation.setTime(this.getTime(channelHandle));\n\n return animationHandle;\n }\n\n detachAnimation(channelId: number): void {\n this.animations.delete(channelId);\n }\n\n update(engineTime: number): void {\n if (this.playing) {\n if (this.lastEngineTime === -1) {\n this.lastEngineTime = engineTime;\n }\n this.setTime(this.time + (engineTime - this.lastEngineTime));\n this.lastEngineTime = engineTime;\n }\n }\n\n _setChannelTime(channel: Channel, time: number): void {\n const offsetTime = time - channel.delay;\n const totalDuration = channel.duration * channel.repeat;\n // Note(Tarek): Don't loop on final repeat.\n if (offsetTime >= totalDuration) {\n channel.time = channel.duration * channel.rate;\n } else {\n channel.time = Math.max(0, offsetTime) % channel.duration;\n channel.time *= channel.rate;\n }\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {luma, Device} from '@luma.gl/core';\nimport {\n requestAnimationFramePolyfill,\n cancelAnimationFramePolyfill\n} from './request-animation-frame';\nimport {Timeline} from '../animation/timeline';\nimport {AnimationProps} from './animation-props';\nimport {Stats, Stat} from '@probe.gl/stats';\n\nlet statIdCounter = 0;\nconst ANIMATION_LOOP_STATS = 'Animation Loop';\n\n/** AnimationLoop properties */\nexport type AnimationLoopProps = {\n device: Device | Promise;\n\n onAddHTML?: (div: HTMLDivElement) => string; // innerHTML\n onInitialize?: (animationProps: AnimationProps) => Promise;\n onRender?: (animationProps: AnimationProps) => unknown;\n onFinalize?: (animationProps: AnimationProps) => void;\n onError?: (reason: Error) => void;\n\n stats?: Stats;\n\n // view parameters - TODO move to CanvasContext?\n autoResizeViewport?: boolean;\n};\n\nexport type MutableAnimationLoopProps = {\n // view parameters\n autoResizeViewport?: boolean;\n};\n\n/** Convenient animation loop */\nexport class AnimationLoop {\n static defaultAnimationLoopProps = {\n device: null!,\n\n onAddHTML: () => '',\n onInitialize: async () => null,\n onRender: () => {},\n onFinalize: () => {},\n onError: error => console.error(error), // eslint-disable-line no-console\n\n stats: undefined!,\n\n // view parameters\n autoResizeViewport: false\n } as const satisfies Readonly>;\n\n device: Device | null = null;\n canvas: HTMLCanvasElement | OffscreenCanvas | null = null;\n\n props: Required;\n animationProps: AnimationProps | null = null;\n timeline: Timeline | null = null;\n stats: Stats;\n sharedStats: Stats;\n cpuTime: Stat;\n gpuTime: Stat;\n frameRate: Stat;\n\n display: any;\n\n private _needsRedraw: string | false = 'initialized';\n\n _initialized: boolean = false;\n _running: boolean = false;\n _animationFrameId: any = null;\n _nextFramePromise: Promise | null = null;\n _resolveNextFrame: ((animationLoop: AnimationLoop) => void) | null = null;\n _cpuStartTime: number = 0;\n _error: Error | null = null;\n _lastFrameTime: number = 0;\n\n /*\n * @param {HTMLCanvasElement} canvas - if provided, width and height will be passed to context\n */\n constructor(props: AnimationLoopProps) {\n this.props = {...AnimationLoop.defaultAnimationLoopProps, ...props};\n props = this.props;\n\n if (!props.device) {\n throw new Error('No device provided');\n }\n\n // state\n this.stats = props.stats || new Stats({id: `animation-loop-${statIdCounter++}`});\n this.sharedStats = luma.stats.get(ANIMATION_LOOP_STATS);\n this.frameRate = this.stats.get('Frame Rate');\n this.frameRate.setSampleSize(1);\n this.cpuTime = this.stats.get('CPU Time');\n this.gpuTime = this.stats.get('GPU Time');\n\n this.setProps({autoResizeViewport: props.autoResizeViewport});\n\n // Bind methods\n this.start = this.start.bind(this);\n this.stop = this.stop.bind(this);\n\n this._onMousemove = this._onMousemove.bind(this);\n this._onMouseleave = this._onMouseleave.bind(this);\n }\n\n destroy(): void {\n this.stop();\n this._setDisplay(null);\n this.device?._disableDebugGPUTime();\n }\n\n /** @deprecated Use .destroy() */\n delete(): void {\n this.destroy();\n }\n\n reportError(error: Error): void {\n this.props.onError(error);\n this._error = error;\n }\n\n /** Flags this animation loop as needing redraw */\n setNeedsRedraw(reason: string): this {\n this._needsRedraw = this._needsRedraw || reason;\n return this;\n }\n\n /** Query redraw status. Clears the flag. */\n needsRedraw(): false | string {\n const reason = this._needsRedraw;\n this._needsRedraw = false;\n return reason;\n }\n\n setProps(props: MutableAnimationLoopProps): this {\n if ('autoResizeViewport' in props) {\n this.props.autoResizeViewport = props.autoResizeViewport || false;\n }\n return this;\n }\n\n /** Starts a render loop if not already running */\n async start() {\n if (this._running) {\n return this;\n }\n this._running = true;\n\n try {\n let appContext;\n if (!this._initialized) {\n this._initialized = true;\n // Create the WebGL context\n await this._initDevice();\n this._initialize();\n if (!this._running) {\n return null;\n }\n\n // Note: onIntialize can return a promise (e.g. in case app needs to load resources)\n await this.props.onInitialize(this._getAnimationProps());\n }\n\n // check that we haven't been stopped\n if (!this._running) {\n return null;\n }\n\n // Start the loop\n if (appContext !== false) {\n // cancel any pending renders to ensure only one loop can ever run\n this._cancelAnimationFrame();\n this._requestAnimationFrame();\n }\n\n return this;\n } catch (err: unknown) {\n const error = err instanceof Error ? err : new Error('Unknown error');\n this.props.onError(error);\n // this._running = false; // TODO\n throw error;\n }\n }\n\n /** Stops a render loop if already running, finalizing */\n stop() {\n // console.debug(`Stopping ${this.constructor.name}`);\n if (this._running) {\n // call callback\n // If stop is called immediately, we can end up in a state where props haven't been initialized...\n if (this.animationProps && !this._error) {\n this.props.onFinalize(this.animationProps);\n }\n\n this._cancelAnimationFrame();\n this._nextFramePromise = null;\n this._resolveNextFrame = null;\n this._running = false;\n this._lastFrameTime = 0;\n }\n return this;\n }\n\n /** Explicitly draw a frame */\n redraw(time?: number): this {\n if (this.device?.isLost || this._error) {\n return this;\n }\n\n this._beginFrameTimers(time);\n\n this._setupFrame();\n this._updateAnimationProps();\n\n this._renderFrame(this._getAnimationProps());\n\n // clear needsRedraw flag\n this._clearNeedsRedraw();\n\n if (this._resolveNextFrame) {\n this._resolveNextFrame(this);\n this._nextFramePromise = null;\n this._resolveNextFrame = null;\n }\n\n this._endFrameTimers();\n\n return this;\n }\n\n /** Add a timeline, it will be automatically updated by the animation loop. */\n attachTimeline(timeline: Timeline): Timeline {\n this.timeline = timeline;\n return this.timeline;\n }\n\n /** Remove a timeline */\n detachTimeline(): void {\n this.timeline = null;\n }\n\n /** Wait until a render completes */\n waitForRender(): Promise {\n this.setNeedsRedraw('waitForRender');\n\n if (!this._nextFramePromise) {\n this._nextFramePromise = new Promise(resolve => {\n this._resolveNextFrame = resolve;\n });\n }\n return this._nextFramePromise;\n }\n\n /** TODO - should use device.deviceContext */\n async toDataURL(): Promise {\n this.setNeedsRedraw('toDataURL');\n await this.waitForRender();\n if (this.canvas instanceof HTMLCanvasElement) {\n return this.canvas.toDataURL();\n }\n throw new Error('OffscreenCanvas');\n }\n\n // PRIVATE METHODS\n\n _initialize(): void {\n this._startEventHandling();\n\n // Initialize the callback data\n this._initializeAnimationProps();\n this._updateAnimationProps();\n\n // Default viewport setup, in case onInitialize wants to render\n this._resizeViewport();\n\n this.device?._enableDebugGPUTime();\n }\n\n _setDisplay(display: any): void {\n if (this.display) {\n this.display.destroy();\n this.display.animationLoop = null;\n }\n\n // store animation loop on the display\n if (display) {\n display.animationLoop = this;\n }\n\n this.display = display;\n }\n\n _requestAnimationFrame(): void {\n if (!this._running) {\n return;\n }\n\n // VR display has a separate animation frame to sync with headset\n // TODO WebVR API discontinued, replaced by WebXR: https://immersive-web.github.io/webxr/\n // See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/requestAnimationFrame\n // if (this.display && this.display.requestAnimationFrame) {\n // this._animationFrameId = this.display.requestAnimationFrame(this._animationFrame.bind(this));\n // }\n this._animationFrameId = requestAnimationFramePolyfill(this._animationFrame.bind(this));\n }\n\n _cancelAnimationFrame(): void {\n if (this._animationFrameId === null) {\n return;\n }\n\n // VR display has a separate animation frame to sync with headset\n // TODO WebVR API discontinued, replaced by WebXR: https://immersive-web.github.io/webxr/\n // See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/requestAnimationFrame\n // if (this.display && this.display.cancelAnimationFramePolyfill) {\n // this.display.cancelAnimationFrame(this._animationFrameId);\n // }\n cancelAnimationFramePolyfill(this._animationFrameId);\n this._animationFrameId = null;\n }\n\n _animationFrame(time: number): void {\n if (!this._running) {\n return;\n }\n this.redraw(time);\n this._requestAnimationFrame();\n }\n\n // Called on each frame, can be overridden to call onRender multiple times\n // to support e.g. stereoscopic rendering\n _renderFrame(animationProps: AnimationProps): void {\n // Allow e.g. VR display to render multiple frames.\n if (this.display) {\n this.display._renderFrame(animationProps);\n return;\n }\n\n // call callback\n this.props.onRender(this._getAnimationProps());\n // end callback\n\n // Submit commands (necessary on WebGPU)\n this.device?.submit();\n }\n\n _clearNeedsRedraw(): void {\n this._needsRedraw = false;\n }\n\n _setupFrame(): void {\n this._resizeViewport();\n }\n\n // Initialize the object that will be passed to app callbacks\n _initializeAnimationProps(): void {\n const canvasContext = this.device?.getDefaultCanvasContext();\n if (!this.device || !canvasContext) {\n throw new Error('loop');\n }\n\n const canvas = canvasContext?.canvas;\n const useDevicePixels = canvasContext.props.useDevicePixels;\n\n this.animationProps = {\n animationLoop: this,\n\n device: this.device,\n canvasContext,\n canvas,\n // @ts-expect-error Deprecated\n useDevicePixels,\n\n timeline: this.timeline,\n\n needsRedraw: false,\n\n // Placeholders\n width: 1,\n height: 1,\n aspect: 1,\n\n // Animation props\n time: 0,\n startTime: Date.now(),\n engineTime: 0,\n tick: 0,\n tock: 0,\n\n // Experimental\n _mousePosition: null // Event props\n };\n }\n\n _getAnimationProps(): AnimationProps {\n if (!this.animationProps) {\n throw new Error('animationProps');\n }\n return this.animationProps;\n }\n\n // Update the context object that will be passed to app callbacks\n _updateAnimationProps(): void {\n if (!this.animationProps) {\n return;\n }\n\n // Can this be replaced with canvas context?\n const {width, height, aspect} = this._getSizeAndAspect();\n if (width !== this.animationProps.width || height !== this.animationProps.height) {\n this.setNeedsRedraw('drawing buffer resized');\n }\n if (aspect !== this.animationProps.aspect) {\n this.setNeedsRedraw('drawing buffer aspect changed');\n }\n\n this.animationProps.width = width;\n this.animationProps.height = height;\n this.animationProps.aspect = aspect;\n\n this.animationProps.needsRedraw = this._needsRedraw;\n\n // Update time properties\n this.animationProps.engineTime = Date.now() - this.animationProps.startTime;\n\n if (this.timeline) {\n this.timeline.update(this.animationProps.engineTime);\n }\n\n this.animationProps.tick = Math.floor((this.animationProps.time / 1000) * 60);\n this.animationProps.tock++;\n\n // For back compatibility\n this.animationProps.time = this.timeline\n ? this.timeline.getTime()\n : this.animationProps.engineTime;\n }\n\n /** Wait for supplied device */\n async _initDevice() {\n this.device = await this.props.device;\n if (!this.device) {\n throw new Error('No device provided');\n }\n this.canvas = this.device.getDefaultCanvasContext().canvas || null;\n // this._createInfoDiv();\n }\n\n _createInfoDiv(): void {\n if (this.canvas && this.props.onAddHTML) {\n const wrapperDiv = document.createElement('div');\n document.body.appendChild(wrapperDiv);\n wrapperDiv.style.position = 'relative';\n const div = document.createElement('div');\n div.style.position = 'absolute';\n div.style.left = '10px';\n div.style.bottom = '10px';\n div.style.width = '300px';\n div.style.background = 'white';\n if (this.canvas instanceof HTMLCanvasElement) {\n wrapperDiv.appendChild(this.canvas);\n }\n wrapperDiv.appendChild(div);\n const html = this.props.onAddHTML(div);\n if (html) {\n div.innerHTML = html;\n }\n }\n }\n\n _getSizeAndAspect(): {width: number; height: number; aspect: number} {\n if (!this.device) {\n return {width: 1, height: 1, aspect: 1};\n }\n // Match projection setup to the actual render target dimensions, which may\n // differ from the CSS size when device-pixel scaling or backend clamping applies.\n const [width, height] = this.device.getDefaultCanvasContext().getDrawingBufferSize();\n const aspect = width > 0 && height > 0 ? width / height : 1;\n\n return {width, height, aspect};\n }\n\n /** @deprecated Default viewport setup */\n _resizeViewport(): void {\n // TODO can we use canvas context to code this in a portable way?\n // @ts-expect-error Expose on canvasContext\n if (this.props.autoResizeViewport && this.device.gl) {\n // @ts-expect-error Expose canvasContext\n this.device.gl.viewport(\n 0,\n 0,\n // @ts-expect-error Expose canvasContext\n this.device.gl.drawingBufferWidth,\n // @ts-expect-error Expose canvasContext\n this.device.gl.drawingBufferHeight\n );\n }\n }\n\n _beginFrameTimers(time?: number) {\n const now = time ?? (typeof performance !== 'undefined' ? performance.now() : Date.now());\n if (this._lastFrameTime) {\n const frameTime = now - this._lastFrameTime;\n if (frameTime > 0) {\n this.frameRate.addTime(frameTime);\n }\n }\n this._lastFrameTime = now;\n\n if (this.device?._isDebugGPUTimeEnabled()) {\n this._consumeEncodedGpuTime();\n }\n\n this.cpuTime.timeStart();\n }\n\n _endFrameTimers() {\n if (this.device?._isDebugGPUTimeEnabled()) {\n this._consumeEncodedGpuTime();\n }\n\n this.cpuTime.timeEnd();\n this._updateSharedStats();\n }\n\n _consumeEncodedGpuTime(): void {\n if (!this.device) {\n return;\n }\n\n const gpuTimeMs = this.device.commandEncoder._gpuTimeMs;\n if (gpuTimeMs !== undefined) {\n this.gpuTime.addTime(gpuTimeMs);\n this.device.commandEncoder._gpuTimeMs = undefined;\n }\n }\n\n _updateSharedStats(): void {\n if (this.stats === this.sharedStats) {\n return;\n }\n\n for (const name of Object.keys(this.sharedStats.stats)) {\n if (!this.stats.stats[name]) {\n delete this.sharedStats.stats[name];\n }\n }\n\n this.stats.forEach(sourceStat => {\n const targetStat = this.sharedStats.get(sourceStat.name, sourceStat.type);\n targetStat.sampleSize = sourceStat.sampleSize;\n targetStat.time = sourceStat.time;\n targetStat.count = sourceStat.count;\n targetStat.samples = sourceStat.samples;\n targetStat.lastTiming = sourceStat.lastTiming;\n targetStat.lastSampleTime = sourceStat.lastSampleTime;\n targetStat.lastSampleCount = sourceStat.lastSampleCount;\n targetStat._count = sourceStat._count;\n targetStat._time = sourceStat._time;\n targetStat._samples = sourceStat._samples;\n targetStat._startTime = sourceStat._startTime;\n targetStat._timerPending = sourceStat._timerPending;\n });\n }\n\n // Event handling\n\n _startEventHandling() {\n if (this.canvas) {\n this.canvas.addEventListener('mousemove', this._onMousemove.bind(this));\n this.canvas.addEventListener('mouseleave', this._onMouseleave.bind(this));\n }\n }\n\n _onMousemove(event: Event) {\n if (event instanceof MouseEvent) {\n this._getAnimationProps()._mousePosition = [event.offsetX, event.offsetY];\n }\n }\n\n _onMouseleave(event: Event) {\n this._getAnimationProps()._mousePosition = null;\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/* global window, setTimeout, clearTimeout */\n\n/** Node.js polyfill for requestAnimationFrame */\n// / \nexport function requestAnimationFramePolyfill(callback: (time?: any) => void): any {\n const browserRequestAnimationFrame =\n typeof window !== 'undefined'\n ? window.requestAnimationFrame ||\n (window as Window & {webkitRequestAnimationFrame?: (cb: FrameRequestCallback) => number})\n .webkitRequestAnimationFrame ||\n (window as Window & {mozRequestAnimationFrame?: (cb: FrameRequestCallback) => number})\n .mozRequestAnimationFrame\n : null;\n\n if (browserRequestAnimationFrame) {\n return browserRequestAnimationFrame.call(window, callback);\n }\n\n return setTimeout(\n () => callback(typeof performance !== 'undefined' ? performance.now() : Date.now()),\n 1000 / 60\n );\n}\n\n/** Node.js polyfill for cancelAnimationFrame */\nexport function cancelAnimationFramePolyfill(timerId: any): void {\n const browserCancelAnimationFrame =\n typeof window !== 'undefined'\n ? window.cancelAnimationFrame ||\n (window as Window & {webkitCancelAnimationFrame?: (handle: number) => void})\n .webkitCancelAnimationFrame ||\n (window as Window & {mozCancelAnimationFrame?: (handle: number) => void})\n .mozCancelAnimationFrame\n : null;\n\n if (browserCancelAnimationFrame) {\n browserCancelAnimationFrame.call(window, timerId);\n return;\n }\n\n clearTimeout(timerId);\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// A lot of imports, but then Model is where it all comes together...\nimport {type TypedArray} from '@math.gl/types';\nimport {\n type RenderPipelineProps,\n type RenderPipelineParameters,\n type BufferLayout,\n type Shader,\n type VertexArray,\n type TransformFeedback,\n type AttributeInfo,\n type Binding,\n type BindingsByGroup,\n type PrimitiveTopology,\n Device,\n DeviceFeature,\n Buffer,\n Texture,\n TextureView,\n Sampler,\n RenderPipeline,\n RenderPass,\n PipelineFactory,\n ShaderFactory,\n UniformStore,\n log,\n dataTypeDecoder,\n getAttributeInfosFromLayouts,\n normalizeBindingsByGroup\n} from '@luma.gl/core';\n\nimport type {ShaderBindingDebugRow, ShaderModule, PlatformInfo} from '@luma.gl/shadertools';\nimport {ShaderAssembler} from '@luma.gl/shadertools';\n\nimport type {Geometry} from '../geometry/geometry';\nimport {GPUGeometry, makeGPUGeometry} from '../geometry/gpu-geometry';\nimport {getDebugTableForShaderLayout} from '../debug/debug-shader-layout';\nimport {debugFramebuffer} from '../debug/debug-framebuffer';\nimport {deepEqual} from '../utils/deep-equal';\nimport {BufferLayoutHelper} from '../utils/buffer-layout-helper';\nimport {sortedBufferLayoutByShaderSourceLocations} from '../utils/buffer-layout-order';\nimport {\n mergeShaderModuleBindingsIntoLayout,\n shaderModuleHasUniforms\n} from '../utils/shader-module-utils';\nimport {uid} from '../utils/uid';\nimport {ShaderInputs} from '../shader-inputs';\nimport {DynamicTexture} from '../dynamic-texture/dynamic-texture';\nimport {Material} from '../material/material';\n\nconst LOG_DRAW_PRIORITY = 2;\nconst LOG_DRAW_TIMEOUT = 10000;\nconst PIPELINE_INITIALIZATION_FAILED = 'render pipeline initialization failed';\n\nexport type ModelProps = Omit & {\n source?: string;\n vs?: string | null;\n fs?: string | null;\n\n /** shadertool shader modules (added to shader code) */\n modules?: ShaderModule[];\n /** Shadertool module defines (configures shader code)*/\n defines?: Record;\n // TODO - injections, hooks etc?\n\n /** Shader inputs, used to generated uniform buffers and bindings */\n shaderInputs?: ShaderInputs;\n /** Material-owned group-3 bindings */\n material?: Material;\n /** Bindings */\n bindings?: Record;\n /** WebGL-only uniforms */\n uniforms?: Record;\n /** Parameters that are built into the pipeline */\n parameters?: RenderPipelineParameters;\n\n /** Geometry */\n geometry?: GPUGeometry | Geometry | null;\n\n /** @deprecated Use instanced rendering? Will be auto-detected in 9.1 */\n isInstanced?: boolean;\n /** instance count */\n instanceCount?: number;\n /** Vertex count */\n vertexCount?: number;\n\n indexBuffer?: Buffer | null;\n /** @note this is really a map of buffers, not a map of attributes */\n attributes?: Record;\n /** */\n constantAttributes?: Record;\n\n /** Some applications intentionally supply unused attributes and bindings, and want to disable warnings */\n disableWarnings?: boolean;\n\n /** @internal For use with {@link TransformFeedback}, WebGL only. */\n varyings?: string[];\n\n transformFeedback?: TransformFeedback;\n\n /** Show shader source in browser? */\n debugShaders?: 'never' | 'errors' | 'warnings' | 'always';\n\n /** Factory used to create a {@link RenderPipeline}. Defaults to {@link Device} default factory. */\n pipelineFactory?: PipelineFactory;\n /** Factory used to create a {@link Shader}. Defaults to {@link Device} default factory. */\n shaderFactory?: ShaderFactory;\n /** Shader assembler. Defaults to the ShaderAssembler.getShaderAssembler() */\n shaderAssembler?: ShaderAssembler;\n};\n\n/**\n * High level draw API for luma.gl.\n *\n * A `Model` encapsulates shaders, geometry attributes, bindings and render\n * pipeline state into a single object. It automatically reuses and rebuilds\n * pipelines as render parameters change and exposes convenient hooks for\n * updating uniforms and attributes.\n *\n * Features:\n * - Reuses and lazily recompiles {@link RenderPipeline | pipelines} as needed.\n * - Integrates with `@luma.gl/shadertools` to assemble GLSL or WGSL from shader modules.\n * - Manages geometry attributes and buffer bindings.\n * - Accepts textures, samplers and uniform buffers as bindings, including `DynamicTexture`.\n * - Provides detailed debug logging and optional shader source inspection.\n */\nexport class Model {\n static defaultProps: Required = {\n ...RenderPipeline.defaultProps,\n source: undefined!,\n vs: null,\n fs: null,\n id: 'unnamed',\n handle: undefined,\n userData: {},\n defines: {},\n modules: [],\n geometry: null,\n indexBuffer: null,\n attributes: {},\n constantAttributes: {},\n bindings: {},\n uniforms: {},\n varyings: [],\n\n isInstanced: undefined!,\n instanceCount: 0,\n vertexCount: 0,\n\n shaderInputs: undefined!,\n material: undefined!,\n pipelineFactory: undefined!,\n shaderFactory: undefined!,\n transformFeedback: undefined!,\n shaderAssembler: ShaderAssembler.getDefaultShaderAssembler(),\n\n debugShaders: undefined!,\n disableWarnings: undefined!\n };\n\n /** Device that created this model */\n readonly device: Device;\n /** Application provided identifier */\n readonly id: string;\n /** WGSL shader source when using unified shader */\n // @ts-expect-error assigned in function called from constructor\n readonly source: string;\n /** GLSL vertex shader source */\n // @ts-expect-error assigned in function called from constructor\n readonly vs: string;\n /** GLSL fragment shader source */\n // @ts-expect-error assigned in function called from constructor\n readonly fs: string;\n /** Factory used to create render pipelines */\n readonly pipelineFactory: PipelineFactory;\n /** Factory used to create shaders */\n readonly shaderFactory: ShaderFactory;\n /** User-supplied per-model data */\n userData: {[key: string]: any} = {};\n\n // Fixed properties (change can trigger pipeline rebuild)\n\n /** The render pipeline GPU parameters, depth testing etc */\n parameters: RenderPipelineParameters;\n\n /** The primitive topology */\n topology: PrimitiveTopology;\n /** Buffer layout */\n bufferLayout: BufferLayout[];\n\n // Dynamic properties\n\n /** Use instanced rendering */\n isInstanced: boolean | undefined = undefined;\n /** instance count. `undefined` means not instanced */\n instanceCount: number = 0;\n /** Vertex count */\n vertexCount: number;\n\n /** Index buffer */\n indexBuffer: Buffer | null = null;\n /** Buffer-valued attributes */\n bufferAttributes: Record = {};\n /** Constant-valued attributes */\n constantAttributes: Record = {};\n /** Bindings (textures, samplers, uniform buffers) */\n bindings: Record = {};\n\n /**\n * VertexArray\n * @note not implemented: if bufferLayout is updated, vertex array has to be rebuilt!\n * @todo - allow application to define multiple vertex arrays?\n * */\n vertexArray: VertexArray;\n\n /** TransformFeedback, WebGL 2 only. */\n transformFeedback: TransformFeedback | null = null;\n\n /** The underlying GPU \"program\". @note May be recreated if parameters change */\n pipeline: RenderPipeline;\n\n /** ShaderInputs instance */\n // @ts-expect-error Assigned in function called by constructor\n shaderInputs: ShaderInputs;\n material: Material | null = null;\n // @ts-expect-error Assigned in function called by constructor\n _uniformStore: UniformStore;\n\n _attributeInfos: Record = {};\n _gpuGeometry: GPUGeometry | null = null;\n private props: Required;\n\n _pipelineNeedsUpdate: string | false = 'newly created';\n private _needsRedraw: string | false = 'initializing';\n private _destroyed = false;\n\n /** \"Time\" of last draw. Monotonically increasing timestamp */\n _lastDrawTimestamp: number = -1;\n private _bindingTable: ShaderBindingDebugRow[] = [];\n\n get [Symbol.toStringTag](): string {\n return 'Model';\n }\n\n toString(): string {\n return `Model(${this.id})`;\n }\n\n constructor(device: Device, props: ModelProps) {\n this.props = {...Model.defaultProps, ...props};\n props = this.props;\n this.id = props.id || uid('model');\n this.device = device;\n\n Object.assign(this.userData, props.userData);\n\n this.material = props.material || null;\n\n // Setup shader module inputs\n const moduleMap = Object.fromEntries(\n this.props.modules?.map(module => [module.name, module]) || []\n );\n\n const shaderInputs =\n props.shaderInputs ||\n new ShaderInputs(moduleMap, {disableWarnings: this.props.disableWarnings});\n // @ts-ignore\n this.setShaderInputs(shaderInputs);\n\n // Setup shader assembler\n const platformInfo = getPlatformInfo(device);\n\n // Extract modules from shader inputs if not supplied\n const modules =\n // @ts-ignore shaderInputs is assigned in setShaderInputs above.\n (this.props.modules?.length > 0 ? this.props.modules : this.shaderInputs?.getModules()) || [];\n\n this.props.shaderLayout =\n mergeShaderModuleBindingsIntoLayout(this.props.shaderLayout, modules) || null;\n\n const isWebGPU = this.device.type === 'webgpu';\n\n // WebGPU\n // TODO - hack to support unified WGSL shader\n // TODO - this is wrong, compile a single shader\n if (isWebGPU && this.props.source) {\n // WGSL\n const {source, getUniforms, bindingTable} = this.props.shaderAssembler.assembleWGSLShader({\n platformInfo,\n ...this.props,\n modules\n });\n this.source = source;\n // @ts-expect-error\n this._getModuleUniforms = getUniforms;\n this._bindingTable = bindingTable;\n // Extract shader layout after modules have been added to WGSL source, to include any bindings added by modules\n const inferredShaderLayout = (\n device as Device & {getShaderLayout?: (source: string) => any}\n ).getShaderLayout?.(this.source);\n this.props.shaderLayout =\n mergeShaderModuleBindingsIntoLayout(\n this.props.shaderLayout || inferredShaderLayout || null,\n modules\n ) || null;\n } else {\n // GLSL\n const {vs, fs, getUniforms} = this.props.shaderAssembler.assembleGLSLShaderPair({\n platformInfo,\n ...this.props,\n modules\n });\n\n this.vs = vs;\n this.fs = fs;\n // @ts-expect-error\n this._getModuleUniforms = getUniforms;\n this._bindingTable = [];\n }\n\n this.vertexCount = this.props.vertexCount;\n this.instanceCount = this.props.instanceCount;\n\n this.topology = this.props.topology;\n this.bufferLayout = this.props.bufferLayout;\n this.parameters = this.props.parameters;\n\n // Geometry, if provided, sets topology and vertex cound\n if (props.geometry) {\n this.setGeometry(props.geometry);\n }\n\n this.pipelineFactory =\n props.pipelineFactory || PipelineFactory.getDefaultPipelineFactory(this.device);\n this.shaderFactory = props.shaderFactory || ShaderFactory.getDefaultShaderFactory(this.device);\n\n // Create the pipeline\n // @note order is important\n this.pipeline = this._updatePipeline();\n\n this.vertexArray = device.createVertexArray({\n shaderLayout: this.pipeline.shaderLayout,\n bufferLayout: this.pipeline.bufferLayout\n });\n\n // Now we can apply geometry attributes\n if (this._gpuGeometry) {\n this._setGeometryAttributes(this._gpuGeometry);\n }\n\n // Apply any dynamic settings that will not trigger pipeline change\n if ('isInstanced' in props) {\n this.isInstanced = props.isInstanced;\n }\n\n if (props.instanceCount) {\n this.setInstanceCount(props.instanceCount);\n }\n if (props.vertexCount) {\n this.setVertexCount(props.vertexCount);\n }\n if (props.indexBuffer) {\n this.setIndexBuffer(props.indexBuffer);\n }\n if (props.attributes) {\n this.setAttributes(props.attributes);\n }\n if (props.constantAttributes) {\n this.setConstantAttributes(props.constantAttributes);\n }\n if (props.bindings) {\n this.setBindings(props.bindings);\n }\n if (props.transformFeedback) {\n this.transformFeedback = props.transformFeedback;\n }\n }\n\n destroy(): void {\n if (!this._destroyed) {\n // Release pipeline before we destroy the shaders used by the pipeline\n this.pipelineFactory.release(this.pipeline);\n // Release the shaders\n this.shaderFactory.release(this.pipeline.vs);\n if (this.pipeline.fs && this.pipeline.fs !== this.pipeline.vs) {\n this.shaderFactory.release(this.pipeline.fs);\n }\n this._uniformStore.destroy();\n // TODO - mark resource as managed and destroyIfManaged() ?\n this._gpuGeometry?.destroy();\n this._destroyed = true;\n }\n }\n\n // Draw call\n\n /** Query redraw status. Clears the status. */\n needsRedraw(): false | string {\n // Catch any writes to already bound resources\n if (this._getBindingsUpdateTimestamp() > this._lastDrawTimestamp) {\n this.setNeedsRedraw('contents of bound textures or buffers updated');\n }\n const needsRedraw = this._needsRedraw;\n this._needsRedraw = false;\n return needsRedraw;\n }\n\n /** Mark the model as needing a redraw */\n setNeedsRedraw(reason: string): void {\n this._needsRedraw ||= reason;\n }\n\n /** Returns WGSL binding debug rows for the assembled shader. Returns an empty array for GLSL models. */\n getBindingDebugTable(): readonly ShaderBindingDebugRow[] {\n return this._bindingTable;\n }\n\n /** Update uniforms and pipeline state prior to drawing. */\n predraw(): void {\n // Update uniform buffers if needed\n this.updateShaderInputs();\n // Check if the pipeline is invalidated\n this.pipeline = this._updatePipeline();\n }\n\n /**\n * Issue one draw call.\n * @param renderPass - render pass to draw into\n * @returns `true` if the draw call was executed, `false` if resources were not ready.\n */\n draw(renderPass: RenderPass): boolean {\n const loadingBinding = this._areBindingsLoading();\n if (loadingBinding) {\n log.info(LOG_DRAW_PRIORITY, `>>> DRAWING ABORTED ${this.id}: ${loadingBinding} not loaded`)();\n return false;\n }\n\n try {\n renderPass.pushDebugGroup(`${this}.predraw(${renderPass})`);\n this.predraw();\n } finally {\n renderPass.popDebugGroup();\n }\n\n let drawSuccess: boolean;\n let pipelineErrored = this.pipeline.isErrored;\n try {\n renderPass.pushDebugGroup(`${this}.draw(${renderPass})`);\n this._logDrawCallStart();\n\n // Update the pipeline if invalidated\n // TODO - inside RenderPass is likely the worst place to do this from performance perspective.\n // Application can call Model.predraw() to avoid this.\n this.pipeline = this._updatePipeline();\n pipelineErrored = this.pipeline.isErrored;\n\n if (pipelineErrored) {\n log.info(\n LOG_DRAW_PRIORITY,\n `>>> DRAWING ABORTED ${this.id}: ${PIPELINE_INITIALIZATION_FAILED}`\n )();\n drawSuccess = false;\n } else {\n const syncBindings = this._getBindings();\n const syncBindGroups = this._getBindGroups();\n\n const {indexBuffer} = this.vertexArray;\n const indexCount = indexBuffer\n ? indexBuffer.byteLength / (indexBuffer.indexType === 'uint32' ? 4 : 2)\n : undefined;\n\n drawSuccess = this.pipeline.draw({\n renderPass,\n vertexArray: this.vertexArray,\n isInstanced: this.isInstanced,\n vertexCount: this.vertexCount,\n instanceCount: this.instanceCount,\n indexCount,\n transformFeedback: this.transformFeedback || undefined,\n // Pipelines may be shared across models when caching is enabled, so bindings\n // and WebGL uniforms must be supplied on every draw instead of being stored\n // on the pipeline instance.\n bindings: syncBindings,\n bindGroups: syncBindGroups,\n _bindGroupCacheKeys: this._getBindGroupCacheKeys(),\n uniforms: this.props.uniforms,\n // WebGL shares underlying cached pipelines even for models that have different parameters and topology,\n // so we must provide our unique parameters to each draw\n // (In WebGPU most parameters are encoded in the pipeline and cannot be changed per draw call)\n parameters: this.parameters,\n topology: this.topology\n });\n }\n } finally {\n renderPass.popDebugGroup();\n this._logDrawCallEnd();\n }\n this._logFramebuffer(renderPass);\n\n // Update needsRedraw flag\n if (drawSuccess) {\n this._lastDrawTimestamp = this.device.timestamp;\n this._needsRedraw = false;\n } else if (pipelineErrored) {\n this._needsRedraw = PIPELINE_INITIALIZATION_FAILED;\n } else {\n this._needsRedraw = 'waiting for resource initialization';\n }\n return drawSuccess;\n }\n\n // Update fixed fields (can trigger pipeline rebuild)\n\n /**\n * Updates the optional geometry\n * Geometry, set topology and bufferLayout\n * @note Can trigger a pipeline rebuild / pipeline cache fetch on WebGPU\n */\n setGeometry(geometry: GPUGeometry | Geometry | null): void {\n this._gpuGeometry?.destroy();\n const gpuGeometry = geometry && makeGPUGeometry(this.device, geometry);\n if (gpuGeometry) {\n this.setTopology(gpuGeometry.topology || 'triangle-list');\n const bufferLayoutHelper = new BufferLayoutHelper(this.bufferLayout);\n this.bufferLayout = bufferLayoutHelper.mergeBufferLayouts(\n gpuGeometry.bufferLayout,\n this.bufferLayout\n );\n if (this.vertexArray) {\n this._setGeometryAttributes(gpuGeometry);\n }\n }\n this._gpuGeometry = gpuGeometry;\n }\n\n /**\n * Updates the primitive topology ('triangle-list', 'triangle-strip' etc).\n * @note Triggers a pipeline rebuild / pipeline cache fetch on WebGPU\n */\n setTopology(topology: PrimitiveTopology): void {\n if (topology !== this.topology) {\n this.topology = topology;\n this._setPipelineNeedsUpdate('topology');\n }\n }\n\n /**\n * Updates the buffer layout.\n * @note Triggers a pipeline rebuild / pipeline cache fetch\n */\n setBufferLayout(bufferLayout: BufferLayout[]): void {\n const bufferLayoutHelper = new BufferLayoutHelper(this.bufferLayout);\n this.bufferLayout = this._gpuGeometry\n ? bufferLayoutHelper.mergeBufferLayouts(bufferLayout, this._gpuGeometry.bufferLayout)\n : bufferLayout;\n this._setPipelineNeedsUpdate('bufferLayout');\n\n // Recreate the pipeline\n this.pipeline = this._updatePipeline();\n\n // vertex array needs to be updated if we update buffer layout,\n // but not if we update parameters\n this.vertexArray = this.device.createVertexArray({\n shaderLayout: this.pipeline.shaderLayout,\n bufferLayout: this.pipeline.bufferLayout\n });\n\n // Reapply geometry attributes to the new vertex array\n if (this._gpuGeometry) {\n this._setGeometryAttributes(this._gpuGeometry);\n }\n }\n\n /**\n * Set GPU parameters.\n * @note Can trigger a pipeline rebuild / pipeline cache fetch.\n * @param parameters\n */\n setParameters(parameters: RenderPipelineParameters) {\n if (!deepEqual(parameters, this.parameters, 2)) {\n this.parameters = parameters;\n this._setPipelineNeedsUpdate('parameters');\n }\n }\n\n // Update dynamic fields\n\n /**\n * Updates the instance count (used in draw calls)\n * @note Any attributes with stepMode=instance need to be at least this big\n */\n setInstanceCount(instanceCount: number): void {\n this.instanceCount = instanceCount;\n // luma.gl examples don't set props.isInstanced and rely on auto-detection\n // but deck.gl sets instanceCount even for models that are not instanced.\n if (this.isInstanced === undefined && instanceCount > 0) {\n this.isInstanced = true;\n }\n this.setNeedsRedraw('instanceCount');\n }\n\n /**\n * Updates the vertex count (used in draw calls)\n * @note Any attributes with stepMode=vertex need to be at least this big\n */\n setVertexCount(vertexCount: number): void {\n this.vertexCount = vertexCount;\n this.setNeedsRedraw('vertexCount');\n }\n\n /** Set the shader inputs */\n setShaderInputs(shaderInputs: ShaderInputs): void {\n this.shaderInputs = shaderInputs;\n this._uniformStore = new UniformStore(this.device, this.shaderInputs.modules);\n // Create uniform buffer bindings for all modules that actually have uniforms\n for (const [moduleName, module] of Object.entries(this.shaderInputs.modules)) {\n if (shaderModuleHasUniforms(module) && !this.material?.ownsModule(moduleName)) {\n const uniformBuffer = this._uniformStore.getManagedUniformBuffer(moduleName);\n this.bindings[`${moduleName}Uniforms`] = uniformBuffer;\n }\n }\n this.setNeedsRedraw('shaderInputs');\n }\n\n setMaterial(material: Material | null): void {\n this.material = material;\n this.setNeedsRedraw('material');\n }\n\n /** Update uniform buffers from the model's shader inputs */\n updateShaderInputs(): void {\n this._uniformStore.setUniforms(this.shaderInputs.getUniformValues());\n this.setBindings(this._getNonMaterialBindings(this.shaderInputs.getBindingValues()));\n // TODO - this is already tracked through buffer/texture update times?\n this.setNeedsRedraw('shaderInputs');\n }\n\n /**\n * Sets bindings (textures, samplers, uniform buffers)\n */\n setBindings(bindings: Record): void {\n Object.assign(this.bindings, bindings);\n this.setNeedsRedraw('bindings');\n }\n\n /**\n * Updates optional transform feedback. WebGL only.\n */\n setTransformFeedback(transformFeedback: TransformFeedback | null): void {\n this.transformFeedback = transformFeedback;\n this.setNeedsRedraw('transformFeedback');\n }\n\n /**\n * Sets the index buffer\n * @todo - how to unset it if we change geometry?\n */\n setIndexBuffer(indexBuffer: Buffer | null): void {\n this.vertexArray.setIndexBuffer(indexBuffer);\n this.setNeedsRedraw('indexBuffer');\n }\n\n /**\n * Sets attributes (buffers)\n * @note Overrides any attributes previously set with the same name\n */\n setAttributes(buffers: Record, options?: {disableWarnings?: boolean}): void {\n const disableWarnings = options?.disableWarnings ?? this.props.disableWarnings;\n if (buffers['indices']) {\n log.warn(\n `Model:${this.id} setAttributes() - indexBuffer should be set using setIndexBuffer()`\n )();\n }\n\n // ensure bufferLayout order matches source layout so we bind\n // the correct buffers to the correct indices in webgpu.\n this.bufferLayout = sortedBufferLayoutByShaderSourceLocations(\n this.pipeline.shaderLayout,\n this.bufferLayout\n );\n const bufferLayoutHelper = new BufferLayoutHelper(this.bufferLayout);\n\n // Check if all buffers have a layout\n for (const [bufferName, buffer] of Object.entries(buffers)) {\n const bufferLayout = bufferLayoutHelper.getBufferLayout(bufferName);\n if (!bufferLayout) {\n if (!disableWarnings) {\n log.warn(`Model(${this.id}): Missing layout for buffer \"${bufferName}\".`)();\n }\n continue; // eslint-disable-line no-continue\n }\n\n // In WebGL, for an interleaved attribute we may need to set multiple attributes\n // but in WebGPU, we set it according to the buffer's position in the vertexArray\n const attributeNames = bufferLayoutHelper.getAttributeNamesForBuffer(bufferLayout);\n let set = false;\n for (const attributeName of attributeNames) {\n const attributeInfo = this._attributeInfos[attributeName];\n if (attributeInfo) {\n const location =\n this.device.type === 'webgpu'\n ? bufferLayoutHelper.getBufferIndex(attributeInfo.bufferName)\n : attributeInfo.location;\n\n this.vertexArray.setBuffer(location, buffer);\n set = true;\n }\n }\n if (!set && !disableWarnings) {\n log.warn(\n `Model(${this.id}): Ignoring buffer \"${buffer.id}\" for unknown attribute \"${bufferName}\"`\n )();\n }\n }\n this.setNeedsRedraw('attributes');\n }\n\n /**\n * Sets constant attributes\n * @note Overrides any attributes previously set with the same name\n * Constant attributes are only supported in WebGL, not in WebGPU\n * Any attribute that is disabled in the current vertex array object\n * is read from the context's global constant value for that attribute location.\n * @param constantAttributes\n */\n setConstantAttributes(\n attributes: Record,\n options?: {disableWarnings?: boolean}\n ): void {\n for (const [attributeName, value] of Object.entries(attributes)) {\n const attributeInfo = this._attributeInfos[attributeName];\n if (attributeInfo) {\n this.vertexArray.setConstantWebGL(attributeInfo.location, value);\n } else if (!(options?.disableWarnings ?? this.props.disableWarnings)) {\n log.warn(\n `Model \"${this.id}: Ignoring constant supplied for unknown attribute \"${attributeName}\"`\n )();\n }\n }\n this.setNeedsRedraw('constants');\n }\n\n // INTERNAL METHODS\n\n /** Check that bindings are loaded. Returns id of first binding that is still loading. */\n _areBindingsLoading(): string | false {\n for (const binding of Object.values(this.bindings)) {\n if (binding instanceof DynamicTexture && !binding.isReady) {\n return binding.id;\n }\n }\n for (const binding of Object.values(this.material?.bindings || {})) {\n if (binding instanceof DynamicTexture && !binding.isReady) {\n return binding.id;\n }\n }\n return false;\n }\n\n /** Extracts texture view from loaded async textures. Returns null if any textures have not yet been loaded. */\n _getBindings(): Record {\n const validBindings: Record = {};\n\n for (const [name, binding] of Object.entries(this.bindings)) {\n if (binding instanceof DynamicTexture) {\n // Check that async textures are loaded\n if (binding.isReady) {\n validBindings[name] = binding.texture;\n }\n } else {\n validBindings[name] = binding;\n }\n }\n\n return validBindings;\n }\n\n _getBindGroups(): BindingsByGroup {\n const shaderLayout = this.pipeline?.shaderLayout || this.props.shaderLayout || {bindings: []};\n const bindGroups = shaderLayout.bindings.length\n ? normalizeBindingsByGroup(shaderLayout, this._getBindings())\n : {0: this._getBindings()};\n\n if (!this.material) {\n return bindGroups;\n }\n\n for (const [groupKey, groupBindings] of Object.entries(this.material.getBindingsByGroup())) {\n const group = Number(groupKey);\n bindGroups[group] = {\n ...(bindGroups[group] || {}),\n ...groupBindings\n };\n }\n\n return bindGroups;\n }\n\n _getBindGroupCacheKeys(): Partial> {\n const bindGroupCacheKey = this.material?.getBindGroupCacheKey(3);\n return bindGroupCacheKey ? {3: bindGroupCacheKey} : {};\n }\n\n /** Get the timestamp of the latest updated bound GPU memory resource (buffer/texture). */\n _getBindingsUpdateTimestamp(): number {\n let timestamp = 0;\n for (const binding of Object.values(this.bindings)) {\n if (binding instanceof TextureView) {\n timestamp = Math.max(timestamp, binding.texture.updateTimestamp);\n } else if (binding instanceof Buffer || binding instanceof Texture) {\n timestamp = Math.max(timestamp, binding.updateTimestamp);\n } else if (binding instanceof DynamicTexture) {\n timestamp = binding.texture\n ? Math.max(timestamp, binding.texture.updateTimestamp)\n : // The texture will become available in the future\n Infinity;\n } else if (!(binding instanceof Sampler)) {\n timestamp = Math.max(timestamp, binding.buffer.updateTimestamp);\n }\n }\n return Math.max(timestamp, this.material?.getBindingsUpdateTimestamp() || 0);\n }\n\n /**\n * Updates the optional geometry attributes\n * Geometry, sets several attributes, indexBuffer, and also vertex count\n * @note Can trigger a pipeline rebuild / pipeline cache fetch on WebGPU\n */\n _setGeometryAttributes(gpuGeometry: GPUGeometry): void {\n // Filter geometry attribute so that we don't issue warnings for unused attributes\n const attributes = {...gpuGeometry.attributes};\n for (const [attributeName] of Object.entries(attributes)) {\n if (\n !this.pipeline.shaderLayout.attributes.find(layout => layout.name === attributeName) &&\n attributeName !== 'positions'\n ) {\n delete attributes[attributeName];\n }\n }\n\n // TODO - delete previous geometry?\n this.vertexCount = gpuGeometry.vertexCount;\n this.setIndexBuffer(gpuGeometry.indices || null);\n this.setAttributes(gpuGeometry.attributes, {disableWarnings: true});\n this.setAttributes(attributes, {disableWarnings: this.props.disableWarnings});\n\n this.setNeedsRedraw('geometry attributes');\n }\n\n /** Mark pipeline as needing update */\n _setPipelineNeedsUpdate(reason: string): void {\n this._pipelineNeedsUpdate ||= reason;\n this.setNeedsRedraw(reason);\n }\n\n /** Update pipeline if needed */\n _updatePipeline(): RenderPipeline {\n if (this._pipelineNeedsUpdate) {\n let prevShaderVs: Shader | null = null;\n let prevShaderFs: Shader | null = null;\n if (this.pipeline) {\n log.log(\n 1,\n `Model ${this.id}: Recreating pipeline because \"${this._pipelineNeedsUpdate}\".`\n )();\n prevShaderVs = this.pipeline.vs;\n prevShaderFs = this.pipeline.fs;\n }\n\n this._pipelineNeedsUpdate = false;\n\n const vs = this.shaderFactory.createShader({\n id: `${this.id}-vertex`,\n stage: 'vertex',\n source: this.source || this.vs,\n debugShaders: this.props.debugShaders\n });\n\n let fs: Shader | null = null;\n if (this.source) {\n fs = vs;\n } else if (this.fs) {\n fs = this.shaderFactory.createShader({\n id: `${this.id}-fragment`,\n stage: 'fragment',\n source: this.source || this.fs,\n debugShaders: this.props.debugShaders\n });\n }\n\n this.pipeline = this.pipelineFactory.createRenderPipeline({\n ...this.props,\n bindings: undefined,\n bufferLayout: this.bufferLayout,\n topology: this.topology,\n parameters: this.parameters,\n bindGroups: this._getBindGroups(),\n vs,\n fs\n });\n\n this._attributeInfos = getAttributeInfosFromLayouts(\n this.pipeline.shaderLayout,\n this.bufferLayout\n );\n\n if (prevShaderVs) this.shaderFactory.release(prevShaderVs);\n if (prevShaderFs && prevShaderFs !== prevShaderVs) {\n this.shaderFactory.release(prevShaderFs);\n }\n }\n return this.pipeline;\n }\n\n /** Throttle draw call logging */\n _lastLogTime = 0;\n _logOpen = false;\n\n _logDrawCallStart(): void {\n // IF level is 4 or higher, log every frame.\n const logDrawTimeout = log.level > 3 ? 0 : LOG_DRAW_TIMEOUT;\n if (log.level < 2 || Date.now() - this._lastLogTime < logDrawTimeout) {\n return;\n }\n\n this._lastLogTime = Date.now();\n this._logOpen = true;\n\n log.group(LOG_DRAW_PRIORITY, `>>> DRAWING MODEL ${this.id}`, {collapsed: log.level <= 2})();\n }\n\n _logDrawCallEnd(): void {\n if (this._logOpen) {\n const shaderLayoutTable = getDebugTableForShaderLayout(this.pipeline.shaderLayout, this.id);\n\n // log.table(logLevel, attributeTable)();\n // log.table(logLevel, uniformTable)();\n log.table(LOG_DRAW_PRIORITY, shaderLayoutTable)();\n\n const uniformTable = this.shaderInputs.getDebugTable();\n log.table(LOG_DRAW_PRIORITY, uniformTable)();\n\n const attributeTable = this._getAttributeDebugTable();\n log.table(LOG_DRAW_PRIORITY, this._attributeInfos)();\n log.table(LOG_DRAW_PRIORITY, attributeTable)();\n\n log.groupEnd(LOG_DRAW_PRIORITY)();\n this._logOpen = false;\n }\n }\n\n protected _drawCount = 0;\n _logFramebuffer(renderPass: RenderPass): void {\n const debugFramebuffers = this.device.props.debugFramebuffers;\n this._drawCount++;\n // Update first 3 frames and then every 60 frames\n if (!debugFramebuffers) {\n // } || (this._drawCount++ > 3 && this._drawCount % 60)) {\n return;\n }\n const framebuffer = renderPass.props.framebuffer;\n debugFramebuffer(renderPass, framebuffer, {\n id: framebuffer?.id || `${this.id}-framebuffer`,\n minimap: true\n });\n }\n\n _getAttributeDebugTable(): Record> {\n const table: Record> = {};\n for (const [name, attributeInfo] of Object.entries(this._attributeInfos)) {\n const values = this.vertexArray.attributes[attributeInfo.location];\n table[attributeInfo.location] = {\n name,\n type: attributeInfo.shaderType,\n values: values\n ? this._getBufferOrConstantValues(values, attributeInfo.bufferDataType)\n : 'null'\n };\n }\n if (this.vertexArray.indexBuffer) {\n const {indexBuffer} = this.vertexArray;\n const values =\n indexBuffer.indexType === 'uint32'\n ? new Uint32Array(indexBuffer.debugData)\n : new Uint16Array(indexBuffer.debugData);\n table['indices'] = {\n name: 'indices',\n type: indexBuffer.indexType,\n values: values.toString()\n };\n }\n return table;\n }\n\n // TODO - fix typing of luma data types\n _getBufferOrConstantValues(attribute: Buffer | TypedArray, dataType: any): string {\n const TypedArrayConstructor = dataTypeDecoder.getTypedArrayConstructor(dataType);\n const typedArray =\n attribute instanceof Buffer ? new TypedArrayConstructor(attribute.debugData) : attribute;\n return typedArray.toString();\n }\n\n private _getNonMaterialBindings(\n bindings: Record\n ): Record {\n if (!this.material) {\n return bindings;\n }\n\n const filteredBindings: Record = {};\n for (const [name, binding] of Object.entries(bindings)) {\n if (!this.material.ownsBinding(name)) {\n filteredBindings[name] = binding;\n }\n }\n return filteredBindings;\n }\n}\n\n// HELPERS\n\n/** Create a shadertools platform info from the Device */\nexport function getPlatformInfo(device: Device): PlatformInfo {\n return {\n type: device.type,\n shaderLanguage: device.info.shadingLanguage,\n shaderLanguageVersion: device.info.shadingLanguageVersion as 100 | 300,\n gpu: device.info.gpu,\n // HACK - we pretend that the DeviceFeatures is a Set, it has a similar API\n features: device.features as unknown as Set\n };\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {PrimitiveTopology, BufferLayout} from '@luma.gl/core';\nimport {Device, Buffer, vertexFormatDecoder} from '@luma.gl/core';\nimport type {Geometry} from '../geometry/geometry';\nimport {uid} from '../utils/uid';\n\nexport type GPUGeometryProps = {\n id?: string;\n /** Determines how vertices are read from the 'vertex' attributes */\n topology: 'point-list' | 'line-list' | 'line-strip' | 'triangle-list' | 'triangle-strip';\n /** Auto calculated from attributes if not provided */\n vertexCount: number;\n bufferLayout: BufferLayout[];\n indices?: Buffer | null;\n attributes: Record;\n};\n\nexport class GPUGeometry {\n readonly id: string;\n userData: Record = {};\n\n /** Determines how vertices are read from the 'vertex' attributes */\n readonly topology?: PrimitiveTopology;\n readonly bufferLayout: BufferLayout[] = [];\n\n readonly vertexCount: number;\n readonly indices?: Buffer | null;\n readonly attributes: Record;\n\n constructor(props: GPUGeometryProps) {\n this.id = props.id || uid('geometry');\n this.topology = props.topology;\n this.indices = props.indices || null;\n this.attributes = props.attributes;\n\n this.vertexCount = props.vertexCount;\n\n this.bufferLayout = props.bufferLayout || [];\n\n if (this.indices) {\n if (!(this.indices.usage & Buffer.INDEX)) {\n throw new Error('Index buffer must have INDEX usage');\n }\n }\n }\n\n destroy(): void {\n this.indices?.destroy();\n for (const attribute of Object.values(this.attributes)) {\n attribute.destroy();\n }\n }\n\n getVertexCount(): number {\n return this.vertexCount;\n }\n\n getAttributes(): Record {\n return this.attributes;\n }\n\n getIndexes(): Buffer | null {\n return this.indices || null;\n }\n\n _calculateVertexCount(positions: Buffer): number {\n // Assume that positions is a fully packed float32x3 buffer\n const vertexCount = positions.byteLength / 12;\n return vertexCount;\n }\n}\n\nexport function makeGPUGeometry(device: Device, geometry: Geometry | GPUGeometry): GPUGeometry {\n if (geometry instanceof GPUGeometry) {\n return geometry;\n }\n\n const indices = getIndexBufferFromGeometry(device, geometry);\n const {attributes, bufferLayout} = getAttributeBuffersFromGeometry(device, geometry);\n return new GPUGeometry({\n topology: geometry.topology || 'triangle-list',\n bufferLayout,\n vertexCount: geometry.vertexCount,\n indices,\n attributes\n });\n}\n\nexport function getIndexBufferFromGeometry(device: Device, geometry: Geometry): Buffer | undefined {\n if (!geometry.indices) {\n return undefined;\n }\n const data = geometry.indices.value;\n return device.createBuffer({usage: Buffer.INDEX, data});\n}\n\nexport function getAttributeBuffersFromGeometry(\n device: Device,\n geometry: Geometry\n): {attributes: Record; bufferLayout: BufferLayout[]; vertexCount: number} {\n const bufferLayout: BufferLayout[] = [];\n\n const attributes: Record = {};\n for (const [attributeName, attribute] of Object.entries(geometry.attributes)) {\n let name: string = attributeName;\n // TODO Map some GLTF attribute names (is this still needed?)\n switch (attributeName) {\n case 'POSITION':\n name = 'positions';\n break;\n case 'NORMAL':\n name = 'normals';\n break;\n case 'TEXCOORD_0':\n name = 'texCoords';\n break;\n case 'TEXCOORD_1':\n name = 'texCoords1';\n break;\n case 'COLOR_0':\n name = 'colors';\n break;\n }\n if (attribute) {\n attributes[name] = device.createBuffer({\n data: attribute.value,\n id: `${attributeName}-buffer`\n });\n const {value, size, normalized} = attribute;\n if (size === undefined) {\n throw new Error(`Attribute ${attributeName} is missing a size`);\n }\n bufferLayout.push({\n name,\n format: vertexFormatDecoder.getVertexFormatFromAttribute(value, size, normalized)\n });\n }\n }\n\n const vertexCount = geometry._calculateVertexCount(geometry.attributes, geometry.indices);\n\n return {attributes, bufferLayout, vertexCount};\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nconst uidCounters: Record = {};\n\n/**\n * Returns a UID.\n * @param id= - Identifier base name\n * @return uid\n **/\nexport function uid(id: string = 'id'): string {\n uidCounters[id] = uidCounters[id] || 1;\n const count = uidCounters[id]++;\n return `${id}-${count}`;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ShaderLayout} from '@luma.gl/core';\n\n/**\n * Extracts a table suitable for `console.table()` from a shader layout to assist in debugging.\n * @param layout shader layout\n * @param name app should provide the most meaningful name, usually the model or pipeline name / id.\n * @returns\n */\nexport function getDebugTableForShaderLayout(\n layout: ShaderLayout,\n name: string\n): Record> {\n const table: Record> = {};\n\n const header = 'Values'; // '`Shader Layout for ${name}`;\n\n if (layout.attributes.length === 0 && !layout.varyings?.length) {\n return {'No attributes or varyings': {[header]: 'N/A'}};\n }\n\n for (const attributeDeclaration of layout.attributes) {\n if (attributeDeclaration) {\n const glslDeclaration = `${attributeDeclaration.location} ${attributeDeclaration.name}: ${attributeDeclaration.type}`;\n table[`in ${glslDeclaration}`] = {[header]: attributeDeclaration.stepMode || 'vertex'};\n }\n }\n\n for (const varyingDeclaration of layout.varyings || []) {\n const glslDeclaration = `${varyingDeclaration.location} ${varyingDeclaration.name}`;\n table[`out ${glslDeclaration}`] = {[header]: JSON.stringify(varyingDeclaration)};\n }\n\n return table;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device, Framebuffer, RenderPass, Texture} from '@luma.gl/core';\n\nconst DEBUG_FRAMEBUFFER_STATE_KEY = '__debugFramebufferState';\nconst DEFAULT_MARGIN_PX = 8;\n\ntype DebugFramebufferOptions = {\n id: string;\n minimap?: boolean;\n opaque?: boolean;\n top?: string;\n left?: string;\n rgbaScale?: number;\n};\n\ntype DebugFramebufferState = {\n flushing: boolean;\n queuedFramebuffers: Framebuffer[];\n};\n\n/**\n * Debug utility to blit queued offscreen framebuffers into the default framebuffer\n * without CPU readback. Currently implemented for WebGL only.\n */\nexport function debugFramebuffer(\n renderPass: RenderPass,\n source: Framebuffer | Texture | null,\n options: DebugFramebufferOptions\n): void {\n if (renderPass.device.type !== 'webgl') {\n return;\n }\n\n const state = getDebugFramebufferState(renderPass.device);\n if (state.flushing) {\n return;\n }\n\n if (isDefaultRenderPass(renderPass)) {\n flushDebugFramebuffers(renderPass, options, state);\n return;\n }\n\n if (source && isFramebuffer(source) && source.handle !== null) {\n if (!state.queuedFramebuffers.includes(source)) {\n state.queuedFramebuffers.push(source);\n }\n }\n}\n\nfunction flushDebugFramebuffers(\n renderPass: RenderPass,\n options: DebugFramebufferOptions,\n state: DebugFramebufferState\n): void {\n if (state.queuedFramebuffers.length === 0) {\n return;\n }\n\n const webglDevice = renderPass.device as Device & {gl: WebGL2RenderingContext};\n const {gl} = webglDevice;\n const previousReadFramebuffer = gl.getParameter(gl.READ_FRAMEBUFFER_BINDING);\n const previousDrawFramebuffer = gl.getParameter(gl.DRAW_FRAMEBUFFER_BINDING);\n const [targetWidth, targetHeight] = renderPass.device\n .getDefaultCanvasContext()\n .getDrawingBufferSize();\n\n let topPx = parseCssPixel(options.top, DEFAULT_MARGIN_PX);\n const leftPx = parseCssPixel(options.left, DEFAULT_MARGIN_PX);\n\n state.flushing = true;\n try {\n for (const framebuffer of state.queuedFramebuffers) {\n const [targetX0, targetY0, targetX1, targetY1, previewHeight] = getOverlayRect({\n framebuffer,\n targetWidth,\n targetHeight,\n topPx,\n leftPx,\n minimap: options.minimap\n });\n\n gl.bindFramebuffer(gl.READ_FRAMEBUFFER, framebuffer.handle as WebGLFramebuffer | null);\n gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);\n gl.blitFramebuffer(\n 0,\n 0,\n framebuffer.width,\n framebuffer.height,\n targetX0,\n targetY0,\n targetX1,\n targetY1,\n gl.COLOR_BUFFER_BIT,\n gl.NEAREST\n );\n\n topPx += previewHeight + DEFAULT_MARGIN_PX;\n }\n } finally {\n gl.bindFramebuffer(gl.READ_FRAMEBUFFER, previousReadFramebuffer);\n gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, previousDrawFramebuffer);\n state.flushing = false;\n }\n}\n\nfunction getOverlayRect(options: {\n framebuffer: Framebuffer;\n targetWidth: number;\n targetHeight: number;\n topPx: number;\n leftPx: number;\n minimap?: boolean;\n}): [number, number, number, number, number] {\n const {framebuffer, targetWidth, targetHeight, topPx, leftPx, minimap} = options;\n const maxWidth = minimap ? Math.max(Math.floor(targetWidth / 4), 1) : targetWidth;\n const maxHeight = minimap ? Math.max(Math.floor(targetHeight / 4), 1) : targetHeight;\n const scale = Math.min(maxWidth / framebuffer.width, maxHeight / framebuffer.height);\n const previewWidth = Math.max(Math.floor(framebuffer.width * scale), 1);\n const previewHeight = Math.max(Math.floor(framebuffer.height * scale), 1);\n const targetX0 = leftPx;\n const targetY0 = Math.max(targetHeight - topPx - previewHeight, 0);\n const targetX1 = targetX0 + previewWidth;\n const targetY1 = targetY0 + previewHeight;\n return [targetX0, targetY0, targetX1, targetY1, previewHeight];\n}\n\nfunction getDebugFramebufferState(device: Device): DebugFramebufferState {\n device.userData[DEBUG_FRAMEBUFFER_STATE_KEY] ||= {\n flushing: false,\n queuedFramebuffers: []\n } satisfies DebugFramebufferState;\n return device.userData[DEBUG_FRAMEBUFFER_STATE_KEY] as DebugFramebufferState;\n}\n\nfunction isFramebuffer(value: Framebuffer | Texture): value is Framebuffer {\n return 'colorAttachments' in value;\n}\n\nfunction isDefaultRenderPass(renderPass: RenderPass): boolean {\n const framebuffer = renderPass.props.framebuffer as {handle?: unknown} | null;\n return !framebuffer || framebuffer.handle === null;\n}\n\nfunction parseCssPixel(value: string | undefined, defaultValue: number): number {\n if (!value) {\n return defaultValue;\n }\n const parsedValue = Number.parseInt(value, 10);\n return Number.isFinite(parsedValue) ? parsedValue : defaultValue;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/**\n * Fast partial deep equal for prop.\n *\n * @param a Prop\n * @param b Prop to compare against `a`\n * @param depth Depth to which to recurse in nested Objects/Arrays. Use 0 (default) for shallow comparison, -1 for infinite depth\n */\n/* eslint-disable complexity */\nexport function deepEqual(a: any, b: any, depth: number): boolean {\n if (a === b) {\n return true;\n }\n if (!depth || !a || !b) {\n return false;\n }\n if (Array.isArray(a)) {\n if (!Array.isArray(b) || a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (!deepEqual(a[i], b[i], depth - 1)) {\n return false;\n }\n }\n return true;\n }\n if (Array.isArray(b)) {\n return false;\n }\n if (typeof a === 'object' && typeof b === 'object') {\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n if (aKeys.length !== bKeys.length) {\n return false;\n }\n for (const key of aKeys) {\n if (!b.hasOwnProperty(key)) {\n return false;\n }\n if (!deepEqual(a[key], b[key], depth - 1)) {\n return false;\n }\n }\n return true;\n }\n return false;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {log, type BufferLayout} from '@luma.gl/core';\n\n/** BufferLayoutHelper is a helper class that should not be used directly by applications */\nexport class BufferLayoutHelper {\n bufferLayouts: BufferLayout[];\n\n constructor(bufferLayouts: BufferLayout[]) {\n this.bufferLayouts = bufferLayouts;\n }\n\n getBufferLayout(name: string): BufferLayout | null {\n return this.bufferLayouts.find(layout => layout.name === name) || null;\n }\n\n /** Get attribute names from a BufferLayout */\n getAttributeNamesForBuffer(bufferLayout: BufferLayout): string[] {\n return bufferLayout.attributes\n ? bufferLayout.attributes?.map(layout => layout.attribute)\n : [bufferLayout.name];\n }\n\n mergeBufferLayouts(\n bufferLayouts1: BufferLayout[],\n bufferLayouts2: BufferLayout[]\n ): BufferLayout[] {\n const mergedLayouts = [...bufferLayouts1];\n for (const attribute of bufferLayouts2) {\n const index = mergedLayouts.findIndex(attribute2 => attribute2.name === attribute.name);\n if (index < 0) {\n mergedLayouts.push(attribute);\n } else {\n mergedLayouts[index] = attribute;\n }\n }\n return mergedLayouts;\n }\n\n getBufferIndex(bufferName: string): number {\n const bufferIndex = this.bufferLayouts.findIndex(layout => layout.name === bufferName);\n\n if (bufferIndex === -1) {\n log.warn(`BufferLayout: Missing buffer for \"${bufferName}\".`)();\n }\n\n return bufferIndex;\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {type BufferLayout, type ShaderLayout} from '@luma.gl/core';\n\nfunction getMinLocation(\n attributeNames: string[],\n shaderLayoutMap: Record\n): number {\n let minLocation = Infinity;\n\n for (const name of attributeNames) {\n const location = shaderLayoutMap[name];\n if (location !== undefined) {\n minLocation = Math.min(minLocation, location);\n }\n }\n\n return minLocation;\n}\n\nexport function sortedBufferLayoutByShaderSourceLocations(\n shaderLayout: ShaderLayout,\n bufferLayout: BufferLayout[]\n): BufferLayout[] {\n const shaderLayoutMap = Object.fromEntries(\n shaderLayout.attributes.map(attr => [attr.name, attr.location])\n );\n\n const sortedLayout = bufferLayout.slice();\n sortedLayout.sort((a, b) => {\n const attributeNamesA = a.attributes ? a.attributes.map(attr => attr.attribute) : [a.name];\n const attributeNamesB = b.attributes ? b.attributes.map(attr => attr.attribute) : [b.name];\n const minLocationA = getMinLocation(attributeNamesA, shaderLayoutMap);\n const minLocationB = getMinLocation(attributeNamesB, shaderLayoutMap);\n\n return minLocationA - minLocationB;\n });\n\n return sortedLayout;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ComputeShaderLayout, ShaderLayout} from '@luma.gl/core';\nimport type {ShaderModule} from '@luma.gl/shadertools';\n\ntype AnyShaderLayout = ShaderLayout | ComputeShaderLayout;\n\nexport function mergeShaderModuleBindingsIntoLayout(\n shaderLayout: TShaderLayout | null | undefined,\n modules: ShaderModule[]\n): TShaderLayout | null | undefined {\n if (!shaderLayout || !modules.some(module => module.bindingLayout?.length)) {\n return shaderLayout;\n }\n\n const mergedLayout = {\n ...shaderLayout,\n bindings: shaderLayout.bindings.map(binding => ({...binding}))\n } as TShaderLayout;\n\n if ('attributes' in (shaderLayout || {})) {\n (mergedLayout as ShaderLayout).attributes = (shaderLayout as ShaderLayout)?.attributes || [];\n }\n\n for (const module of modules) {\n for (const bindingLayout of module.bindingLayout || []) {\n for (const relatedBindingName of getRelatedBindingNames(bindingLayout.name)) {\n const binding = mergedLayout.bindings.find(\n candidate => candidate.name === relatedBindingName\n );\n if (binding?.group === 0) {\n binding.group = bindingLayout.group;\n }\n }\n }\n }\n\n return mergedLayout;\n}\n\nexport function shaderModuleHasUniforms(module: ShaderModule): boolean {\n return Boolean(module.uniformTypes && !isObjectEmpty(module.uniformTypes));\n}\n\n/** Returns binding-name aliases that should share the module-declared bind group. */\nfunction getRelatedBindingNames(bindingName: string): string[] {\n const bindingNames = new Set([bindingName, `${bindingName}Uniforms`]);\n\n if (!bindingName.endsWith('Uniforms')) {\n bindingNames.add(`${bindingName}Sampler`);\n }\n\n return [...bindingNames];\n}\n\nfunction isObjectEmpty(obj: object): boolean {\n // @ts-ignore key is intentionally unused\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n for (const key in obj) {\n return false;\n }\n return true;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Binding, CompositeShaderType} from '@luma.gl/core';\nimport {log} from '@luma.gl/core';\n// import type {VariableShaderType, UniformValue, UniformFormat, UniformInfoDevice, Texture, Sampler} from '@luma.gl/core';\nimport {\n getShaderModuleDependencies,\n ShaderModule,\n ShaderModuleUniformValue\n} from '@luma.gl/shadertools';\nimport {splitUniformsAndBindings} from './model/split-uniforms-and-bindings';\n\nexport type ShaderInputsOptions = {\n disableWarnings?: boolean;\n};\n\ntype ShaderInputsModule = Pick<\n ShaderModule,\n 'bindingLayout' | 'defaultUniforms' | 'dependencies' | 'getUniforms' | 'name' | 'uniformTypes'\n>;\n\n/**\n * ShaderInputs holds uniform and binding values for one or more shader modules,\n * - It can generate binary data for any uniform buffer\n * - It can manage a uniform buffer for each block\n * - It can update managed uniform buffers with a single call\n * - It performs some book keeping on what has changed to minimize unnecessary writes to uniform buffers.\n */\nexport class ShaderInputs<\n ShaderPropsT extends Partial>> = Partial<\n Record>\n >\n> {\n options: Required = {\n disableWarnings: false\n };\n\n /**\n * The map of modules\n * @todo should should this include the resolved dependencies?\n */\n // @ts-ignore Fix typings\n modules: Readonly<{[P in keyof ShaderPropsT]: ShaderInputsModule}>;\n\n /** Stores the uniform values for each module */\n moduleUniforms: Record>;\n /** Stores the uniform bindings for each module */\n moduleBindings: Record>;\n /** Tracks if uniforms have changed */\n // moduleUniformsChanged: Record;\n\n /**\n * Create a new UniformStore instance\n * @param modules\n */\n constructor(\n // @ts-ignore Fix typings\n modules: {[P in keyof ShaderPropsT]?: ShaderInputsModule},\n options?: ShaderInputsOptions\n ) {\n Object.assign(this.options, options);\n\n // Extract modules with dependencies\n const resolvedModules = getShaderModuleDependencies(\n Object.values(modules).filter(isShaderInputsModuleWithDependencies)\n );\n for (const resolvedModule of resolvedModules) {\n // @ts-ignore\n modules[resolvedModule.name] = resolvedModule;\n }\n\n log.log(1, 'Creating ShaderInputs with modules', Object.keys(modules))();\n\n // Store the module definitions and create storage for uniform values and binding values, per module\n // @ts-ignore Fix typings\n this.modules = modules as {[P in keyof ShaderPropsT]: ShaderInputsModule};\n this.moduleUniforms = {} as Record<\n keyof ShaderPropsT,\n Record\n >;\n this.moduleBindings = {} as Record>;\n\n // Initialize the modules\n for (const [name, module] of Object.entries(modules)) {\n if (module) {\n this._addModule(module);\n if (module.name && name !== module.name && !this.options.disableWarnings) {\n log.warn(`Module name: ${name} vs ${module.name}`)();\n }\n }\n }\n }\n\n /** Destroy */\n destroy(): void {}\n\n /**\n * Set module props\n */\n setProps(props: Partial<{[P in keyof ShaderPropsT]?: Partial}>): void {\n for (const name of Object.keys(props)) {\n const moduleName = name as keyof ShaderPropsT;\n const moduleProps = props[moduleName] || {};\n const module = this.modules[moduleName];\n if (!module) {\n // Ignore props for unregistered modules\n if (!this.options.disableWarnings) {\n log.warn(`Module ${name} not found`)();\n }\n } else {\n const oldUniforms = this.moduleUniforms[moduleName];\n const oldBindings = this.moduleBindings[moduleName];\n const uniformsAndBindings =\n module.getUniforms?.(moduleProps, oldUniforms) || (moduleProps as any);\n\n const {uniforms, bindings} = splitUniformsAndBindings(\n uniformsAndBindings,\n module.uniformTypes as Readonly>\n );\n this.moduleUniforms[moduleName] = mergeModuleUniforms(\n oldUniforms as Record,\n uniforms,\n module.uniformTypes as Readonly>\n );\n this.moduleBindings[moduleName] = {...oldBindings, ...bindings};\n // this.moduleUniformsChanged ||= moduleName;\n }\n\n // console.log(`setProps(${String(moduleName)}`, moduleName, this.moduleUniforms[moduleName])\n }\n }\n\n /**\n * Return the map of modules\n * @todo should should this include the resolved dependencies?\n */\n getModules(): ShaderModule[] {\n return Object.values(this.modules) as ShaderModule[];\n }\n\n /** Get all uniform values for all modules */\n getUniformValues(): Partial<\n Record>\n > {\n return this.moduleUniforms;\n }\n\n /** Merges all bindings for the shader (from the various modules) */\n getBindingValues(): Record {\n const bindings = {} as Record;\n for (const moduleBindings of Object.values(this.moduleBindings)) {\n Object.assign(bindings, moduleBindings);\n }\n return bindings;\n }\n\n // INTERNAL\n\n /** Return a debug table that can be used for console.table() or log.table() */\n getDebugTable(): Record> {\n const table: Record> = {};\n for (const [moduleName, module] of Object.entries(this.moduleUniforms)) {\n for (const [key, value] of Object.entries(module)) {\n table[`${moduleName}.${key}`] = {\n type: this.modules[moduleName].uniformTypes?.[key as keyof ShaderPropsT],\n value: String(value)\n };\n }\n }\n return table;\n }\n\n _addModule(module: ShaderInputsModule): void {\n const moduleName = module.name as keyof ShaderPropsT;\n // Get default uniforms from module\n this.moduleUniforms[moduleName] = mergeModuleUniforms(\n {},\n (module.defaultUniforms || {}) as Record,\n module.uniformTypes as Readonly>\n );\n this.moduleBindings[moduleName] = {};\n }\n}\n\nfunction mergeModuleUniforms(\n currentUniforms: Record = {},\n nextUniforms: Record = {},\n uniformTypes: Readonly> = {}\n): Record {\n const mergedUniforms = {...currentUniforms};\n for (const [key, value] of Object.entries(nextUniforms)) {\n if (value !== undefined) {\n mergedUniforms[key] = mergeModuleUniformValue(currentUniforms[key], value, uniformTypes[key]);\n }\n }\n return mergedUniforms;\n}\n\nfunction mergeModuleUniformValue(\n currentValue: ShaderModuleUniformValue | undefined,\n nextValue: ShaderModuleUniformValue,\n uniformType: CompositeShaderType | undefined\n): ShaderModuleUniformValue {\n if (!uniformType || typeof uniformType === 'string') {\n return cloneModuleUniformValue(nextValue);\n }\n\n if (Array.isArray(uniformType)) {\n if (isPackedUniformArrayValue(nextValue) || !Array.isArray(nextValue)) {\n return cloneModuleUniformValue(nextValue);\n }\n\n const currentArray: Array =\n Array.isArray(currentValue) && !isPackedUniformArrayValue(currentValue)\n ? [...currentValue]\n : [];\n const mergedArray = currentArray.slice();\n for (let index = 0; index < nextValue.length; index++) {\n const elementValue = nextValue[index];\n if (elementValue !== undefined) {\n mergedArray[index] = mergeModuleUniformValue(\n currentArray[index],\n elementValue,\n uniformType[0] as CompositeShaderType\n );\n }\n }\n return mergedArray;\n }\n\n if (!isPlainUniformObject(nextValue)) {\n return cloneModuleUniformValue(nextValue);\n }\n\n const uniformStruct = uniformType as Record;\n const currentObject = isPlainUniformObject(currentValue) ? currentValue : {};\n const mergedObject: Record = {...currentObject};\n for (const [key, value] of Object.entries(nextValue)) {\n if (value !== undefined) {\n mergedObject[key] = mergeModuleUniformValue(currentObject[key], value, uniformStruct[key]);\n }\n }\n return mergedObject as ShaderModuleUniformValue;\n}\n\nfunction cloneModuleUniformValue(value: ShaderModuleUniformValue): ShaderModuleUniformValue {\n if (ArrayBuffer.isView(value)) {\n return Array.prototype.slice.call(value) as ShaderModuleUniformValue;\n }\n\n if (Array.isArray(value)) {\n if (isPackedUniformArrayValue(value)) {\n return value.slice() as ShaderModuleUniformValue;\n }\n\n const compositeArray = value as ReadonlyArray;\n return compositeArray.map(element =>\n element === undefined ? undefined : cloneModuleUniformValue(element)\n ) as ShaderModuleUniformValue;\n }\n\n if (isPlainUniformObject(value)) {\n return Object.fromEntries(\n Object.entries(value).map(([key, nestedValue]) => [\n key,\n nestedValue === undefined ? undefined : cloneModuleUniformValue(nestedValue)\n ])\n ) as ShaderModuleUniformValue;\n }\n\n return value;\n}\n\nfunction isPackedUniformArrayValue(\n value: unknown\n): value is ReadonlyArray | ArrayBufferView {\n return (\n ArrayBuffer.isView(value) ||\n (Array.isArray(value) && (value.length === 0 || typeof value[0] === 'number'))\n );\n}\n\nfunction isPlainUniformObject(\n value: unknown\n): value is Record {\n return (\n Boolean(value) &&\n typeof value === 'object' &&\n !Array.isArray(value) &&\n !ArrayBuffer.isView(value)\n );\n}\n\nfunction isShaderInputsModuleWithDependencies(\n module: ShaderInputsModule | undefined\n): module is ShaderInputsModule & {dependencies: NonNullable} {\n return Boolean(module?.dependencies);\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Binding, CompositeShaderType, UniformValue} from '@luma.gl/core';\nimport type {ShaderModuleUniformValue} from '@luma.gl/shadertools';\nimport {isNumericArray} from '@math.gl/types';\n\nexport function isUniformValue(value: unknown): value is UniformValue {\n return isNumericArray(value) || typeof value === 'number' || typeof value === 'boolean';\n}\n\ntype UniformsAndBindings = {\n bindings: Record;\n uniforms: Record;\n};\n\nexport function splitUniformsAndBindings(\n uniforms: Record,\n uniformTypes: Readonly> = {}\n): UniformsAndBindings {\n const result: UniformsAndBindings = {bindings: {}, uniforms: {}};\n Object.keys(uniforms).forEach(name => {\n const uniform = uniforms[name];\n if (Object.prototype.hasOwnProperty.call(uniformTypes, name) || isUniformValue(uniform)) {\n result.uniforms[name] = uniform as ShaderModuleUniformValue;\n } else {\n result.bindings[name] = uniform as Binding;\n }\n });\n\n return result;\n}\n","// luma.gl, MIT license\n// Copyright (c) vis.gl contributors\n\nimport type {\n TextureProps,\n SamplerProps,\n TextureView,\n Device,\n TextureFormat,\n TextureReadOptions\n} from '@luma.gl/core';\n\nimport {Buffer, Texture, Sampler, log} from '@luma.gl/core';\n\n// import {loadImageBitmap} from '../application-utils/load-file';\nimport {uid} from '../utils/uid';\nimport {\n // cube constants\n type TextureCubeFace,\n TEXTURE_CUBE_FACE_MAP,\n // texture slice/mip data types\n type TextureSubresource,\n // props (dimension + data)\n type TextureDataProps,\n type TextureDataAsyncProps,\n // combined data for different texture types\n type Texture1DData,\n type Texture2DData,\n type Texture3DData,\n type TextureArrayData,\n type TextureCubeArrayData,\n type TextureCubeData,\n // Helpers\n getTextureSizeFromData,\n resolveTextureImageFormat,\n getTexture1DSubresources,\n getTexture2DSubresources,\n getTexture3DSubresources,\n getTextureCubeSubresources,\n getTextureArraySubresources,\n getTextureCubeArraySubresources\n} from './texture-data';\n\n/**\n * Properties for a dynamic texture\n */\nexport type DynamicTextureProps = Omit &\n TextureDataAsyncProps & {\n /** Generate mipmaps after creating textures and setting data */\n mipmaps?: boolean;\n /** nipLevels can be set to 'auto' to generate max number of mipLevels */\n mipLevels?: number | 'auto';\n /** Width - can be auto-calculated when initializing from ExternalImage */\n width?: number;\n /** Height - can be auto-calculated when initializing from ExternalImage */\n height?: number;\n };\n\n/**\n * Dynamic Textures\n *\n * - Mipmaps - DynamicTexture can generate mipmaps for textures (WebGPU does not provide built-in mipmap generation).\n *\n * - Texture initialization and updates - complex textures (2d array textures, cube textures, 3d textures) need multiple images\n * `DynamicTexture` provides an API that makes it easy to provide the required data.\n *\n * - Texture resizing - Textures are immutable in WebGPU, meaning that they cannot be resized after creation.\n * DynamicTexture provides a `resize()` method that internally creates a new texture with the same parameters\n * but a different size.\n *\n * - Async image data initialization - It is often very convenient to be able to initialize textures with promises\n * returned by image or data loading functions, as it allows a callback-free linear style of programming.\n *\n * @note GPU Textures are quite complex objects, with many subresources and modes of usage.\n * The `DynamicTexture` class allows luma.gl to provide some support for working with textures\n * without accumulating excessive complexity in the core Texture class which is designed as an immutable nature of GPU resource.\n */\nexport class DynamicTexture {\n readonly device: Device;\n readonly id: string;\n\n /** Props with defaults resolved (except `data` which is processed separately) */\n props: Readonly>;\n\n /** Created resources */\n private _texture: Texture | null = null;\n private _sampler: Sampler | null = null;\n private _view: TextureView | null = null;\n\n /** Ready when GPU texture has been created and data (if any) uploaded */\n readonly ready: Promise;\n isReady = false;\n destroyed = false;\n\n private resolveReady: (t: Texture) => void = () => {};\n private rejectReady: (error: Error) => void = () => {};\n\n get texture(): Texture {\n if (!this._texture) throw new Error('Texture not initialized yet');\n return this._texture;\n }\n get sampler(): Sampler {\n if (!this._sampler) throw new Error('Sampler not initialized yet');\n return this._sampler;\n }\n get view(): TextureView {\n if (!this._view) throw new Error('View not initialized yet');\n return this._view;\n }\n\n get [Symbol.toStringTag]() {\n return 'DynamicTexture';\n }\n toString(): string {\n const width = this._texture?.width ?? this.props.width ?? '?';\n const height = this._texture?.height ?? this.props.height ?? '?';\n return `DynamicTexture:\"${this.id}\":${width}x${height}px:(${this.isReady ? 'ready' : 'loading...'})`;\n }\n\n constructor(device: Device, props: DynamicTextureProps) {\n this.device = device;\n\n const id = uid('dynamic-texture');\n // NOTE: We avoid holding on to data to make sure it can be garbage collected.\n const originalPropsWithAsyncData = props;\n this.props = {...DynamicTexture.defaultProps, id, ...props, data: null};\n this.id = this.props.id;\n\n this.ready = new Promise((resolve, reject) => {\n this.resolveReady = resolve;\n this.rejectReady = reject;\n });\n\n this.initAsync(originalPropsWithAsyncData);\n }\n\n /** @note Fire and forget; caller can await `ready` */\n async initAsync(originalPropsWithAsyncData: DynamicTextureProps): Promise {\n try {\n // TODO - Accept URL string for 2D: turn into ExternalImage promise\n // const dataProps =\n // typeof props.data === 'string' && (props.dimension ?? '2d') === '2d'\n // ? ({dimension: '2d', data: loadImageBitmap(props.data)} as const)\n // : {};\n\n const propsWithSyncData = await this._loadAllData(originalPropsWithAsyncData);\n this._checkNotDestroyed();\n const subresources = propsWithSyncData.data\n ? getTextureSubresources({\n ...propsWithSyncData,\n width: originalPropsWithAsyncData.width,\n height: originalPropsWithAsyncData.height,\n format: originalPropsWithAsyncData.format\n })\n : [];\n const userProvidedFormat =\n 'format' in originalPropsWithAsyncData && originalPropsWithAsyncData.format !== undefined;\n const userProvidedUsage =\n 'usage' in originalPropsWithAsyncData && originalPropsWithAsyncData.usage !== undefined;\n\n // Deduce size when not explicitly provided\n // TODO - what about depth?\n const deduceSize = (): {width: number; height: number} => {\n if (this.props.width && this.props.height) {\n return {width: this.props.width, height: this.props.height};\n }\n\n const size = getTextureSizeFromData(propsWithSyncData);\n if (size) {\n return size;\n }\n\n return {width: this.props.width || 1, height: this.props.height || 1};\n };\n\n const size = deduceSize();\n if (!size || size.width <= 0 || size.height <= 0) {\n throw new Error(`${this} size could not be determined or was zero`);\n }\n\n // Normalize caller-provided subresources into one validated mip chain description.\n const textureData = analyzeTextureSubresources(this.device, subresources, size, {\n format: userProvidedFormat ? originalPropsWithAsyncData.format : undefined\n });\n const resolvedFormat = textureData.format ?? this.props.format;\n\n // Create a minimal TextureProps and validate via `satisfies`\n const baseTextureProps = {\n ...this.props,\n ...size,\n format: resolvedFormat,\n mipLevels: 1, // temporary; updated below\n data: undefined\n } satisfies TextureProps;\n\n if (this.device.isTextureFormatCompressed(resolvedFormat) && !userProvidedUsage) {\n baseTextureProps.usage = Texture.SAMPLE | Texture.COPY_DST;\n }\n\n // Explicit mip arrays take ownership of the mip chain; otherwise we may auto-generate it.\n const shouldGenerateMipmaps =\n this.props.mipmaps &&\n !textureData.hasExplicitMipChain &&\n !this.device.isTextureFormatCompressed(resolvedFormat);\n\n if (this.device.type === 'webgpu' && shouldGenerateMipmaps) {\n const requiredUsage =\n this.props.dimension === '3d'\n ? Texture.SAMPLE | Texture.STORAGE | Texture.COPY_DST | Texture.COPY_SRC\n : Texture.SAMPLE | Texture.RENDER | Texture.COPY_DST | Texture.COPY_SRC;\n baseTextureProps.usage |= requiredUsage;\n }\n\n // Compute mip levels (auto clamps to max)\n const maxMips = this.device.getMipLevelCount(baseTextureProps.width, baseTextureProps.height);\n const desired = textureData.hasExplicitMipChain\n ? textureData.mipLevels\n : this.props.mipLevels === 'auto'\n ? maxMips\n : Math.max(1, Math.min(maxMips, this.props.mipLevels ?? 1));\n\n const finalTextureProps: TextureProps = {...baseTextureProps, mipLevels: desired};\n\n this._texture = this.device.createTexture(finalTextureProps);\n this._sampler = this.texture.sampler;\n this._view = this.texture.view;\n\n // Upload data if provided\n if (textureData.subresources.length) {\n this._setTextureSubresources(textureData.subresources);\n }\n\n if (this.props.mipmaps && !textureData.hasExplicitMipChain && !shouldGenerateMipmaps) {\n log.warn(`${this} skipping auto-generated mipmaps for compressed texture format`)();\n }\n\n if (shouldGenerateMipmaps) {\n this.generateMipmaps();\n }\n\n this.isReady = true;\n this.resolveReady(this.texture);\n\n log.info(0, `${this} created`)();\n } catch (e) {\n const err = e instanceof Error ? e : new Error(String(e));\n this.rejectReady(err);\n }\n }\n\n destroy(): void {\n if (this._texture) {\n this._texture.destroy();\n this._texture = null;\n this._sampler = null;\n this._view = null;\n }\n this.destroyed = true;\n }\n\n generateMipmaps(): void {\n if (this.device.type === 'webgl') {\n this.texture.generateMipmapsWebGL();\n } else if (this.device.type === 'webgpu') {\n this.device.generateMipmapsWebGPU(this.texture);\n } else {\n log.warn(`${this} mipmaps not supported on ${this.device.type}`);\n }\n }\n\n /** Set sampler or create one from props */\n setSampler(sampler: Sampler | SamplerProps = {}): void {\n this._checkReady();\n const s = sampler instanceof Sampler ? sampler : this.device.createSampler(sampler);\n this.texture.setSampler(s);\n this._sampler = s;\n }\n\n /**\n * Copies texture contents into a GPU buffer and waits until the copy is complete.\n * The caller owns the returned buffer and must destroy it when finished.\n */\n async readBuffer(options: TextureReadOptions = {}): Promise {\n if (!this.isReady) {\n await this.ready;\n }\n\n const width = options.width ?? this.texture.width;\n const height = options.height ?? this.texture.height;\n const depthOrArrayLayers = options.depthOrArrayLayers ?? this.texture.depth;\n const layout = this.texture.computeMemoryLayout({width, height, depthOrArrayLayers});\n\n const buffer = this.device.createBuffer({\n byteLength: layout.byteLength,\n usage: Buffer.COPY_DST | Buffer.MAP_READ\n });\n\n this.texture.readBuffer(\n {\n ...options,\n width,\n height,\n depthOrArrayLayers\n },\n buffer\n );\n\n const fence = this.device.createFence();\n await fence.signaled;\n fence.destroy();\n\n return buffer;\n }\n\n /** Reads texture contents back to CPU memory. */\n async readAsync(options: TextureReadOptions = {}): Promise {\n if (!this.isReady) {\n await this.ready;\n }\n\n const width = options.width ?? this.texture.width;\n const height = options.height ?? this.texture.height;\n const depthOrArrayLayers = options.depthOrArrayLayers ?? this.texture.depth;\n const layout = this.texture.computeMemoryLayout({width, height, depthOrArrayLayers});\n\n const buffer = await this.readBuffer(options);\n const data = await buffer.readAsync(0, layout.byteLength);\n buffer.destroy();\n return data.buffer;\n }\n\n /**\n * Resize by cloning the underlying immutable texture.\n * Does not copy contents; caller may need to re-upload and/or regenerate mips.\n */\n resize(size: {width: number; height: number}): boolean {\n this._checkReady();\n\n if (size.width === this.texture.width && size.height === this.texture.height) {\n return false;\n }\n const prev = this.texture;\n this._texture = prev.clone(size);\n this._sampler = this.texture.sampler;\n this._view = this.texture.view;\n\n prev.destroy();\n log.info(`${this} resized`);\n return true;\n }\n\n /** Convert cube face label to texture slice index. Index can be used with `setTexture2DData()`. */\n getCubeFaceIndex(face: TextureCubeFace): number {\n const index = TEXTURE_CUBE_FACE_MAP[face];\n if (index === undefined) throw new Error(`Invalid cube face: ${face}`);\n return index;\n }\n\n /** Convert cube face label to texture slice index. Index can be used with `setTexture2DData()`. */\n getCubeArrayFaceIndex(cubeIndex: number, face: TextureCubeFace): number {\n return 6 * cubeIndex + this.getCubeFaceIndex(face);\n }\n\n /** @note experimental: Set multiple mip levels (1D) */\n setTexture1DData(data: Texture1DData): void {\n this._checkReady();\n if (this.texture.props.dimension !== '1d') {\n throw new Error(`${this} is not 1d`);\n }\n const subresources = getTexture1DSubresources(data);\n this._setTextureSubresources(subresources);\n }\n\n /** @note experimental: Set multiple mip levels (2D), optionally at `z`, slice (depth/array level) index */\n setTexture2DData(lodData: Texture2DData, z: number = 0): void {\n this._checkReady();\n if (this.texture.props.dimension !== '2d') {\n throw new Error(`${this} is not 2d`);\n }\n\n const subresources = getTexture2DSubresources(z, lodData);\n this._setTextureSubresources(subresources);\n }\n\n /** 3D: multiple depth slices, each may carry multiple mip levels */\n setTexture3DData(data: Texture3DData): void {\n if (this.texture.props.dimension !== '3d') {\n throw new Error(`${this} is not 3d`);\n }\n const subresources = getTexture3DSubresources(data);\n this._setTextureSubresources(subresources);\n }\n\n /** 2D array: multiple layers, each may carry multiple mip levels */\n setTextureArrayData(data: TextureArrayData): void {\n if (this.texture.props.dimension !== '2d-array') {\n throw new Error(`${this} is not 2d-array`);\n }\n const subresources = getTextureArraySubresources(data);\n this._setTextureSubresources(subresources);\n }\n\n /** Cube: 6 faces, each may carry multiple mip levels */\n setTextureCubeData(data: TextureCubeData): void {\n if (this.texture.props.dimension !== 'cube') {\n throw new Error(`${this} is not cube`);\n }\n const subresources = getTextureCubeSubresources(data);\n this._setTextureSubresources(subresources);\n }\n\n /** Cube array: multiple cubes (faces×layers), each face may carry multiple mips */\n setTextureCubeArrayData(data: TextureCubeArrayData): void {\n if (this.texture.props.dimension !== 'cube-array') {\n throw new Error(`${this} is not cube-array`);\n }\n const subresources = getTextureCubeArraySubresources(data);\n this._setTextureSubresources(subresources);\n }\n\n /** Sets multiple mip levels on different `z` slices (depth/array index) */\n private _setTextureSubresources(subresources: TextureSubresource[]): void {\n // If user supplied multiple mip levels, warn if auto-mips also requested\n // if (lodArray.length > 1 && this.props.mipmaps !== false) {\n // log.warn(\n // `Texture ${this.id}: provided multiple LODs and also requested mipmap generation.`\n // )();\n // }\n\n for (const subresource of subresources) {\n const {z, mipLevel} = subresource;\n switch (subresource.type) {\n case 'external-image':\n const {image, flipY} = subresource;\n this.texture.copyExternalImage({image, z, mipLevel, flipY});\n break;\n case 'texture-data':\n const {data, textureFormat} = subresource;\n if (textureFormat && textureFormat !== this.texture.format) {\n throw new Error(\n `${this} mip level ${mipLevel} uses format \"${textureFormat}\" but texture format is \"${this.texture.format}\"`\n );\n }\n this.texture.writeData(data.data, {\n x: 0,\n y: 0,\n z,\n width: data.width,\n height: data.height,\n depthOrArrayLayers: 1,\n mipLevel\n });\n break;\n default:\n throw new Error('Unsupported 2D mip-level payload');\n }\n }\n }\n\n // ------------------ helpers ------------------\n\n /** Recursively resolve all promises in data structures */\n private async _loadAllData(props: TextureDataAsyncProps): Promise {\n const syncData = await awaitAllPromises(props.data);\n const dimension = (props.dimension ?? '2d') as TextureDataProps['dimension'];\n return {dimension, data: syncData ?? null} as TextureDataProps;\n }\n\n private _checkNotDestroyed() {\n if (this.destroyed) {\n log.warn(`${this} already destroyed`);\n }\n }\n\n private _checkReady() {\n if (!this.isReady) {\n log.warn(`${this} Cannot perform this operation before ready`);\n }\n }\n\n static defaultProps: Required = {\n ...Texture.defaultProps,\n dimension: '2d',\n data: null,\n mipmaps: false\n };\n}\n\ntype TextureSubresourceAnalysis = {\n readonly subresources: TextureSubresource[];\n readonly mipLevels: number;\n readonly format?: TextureFormat;\n readonly hasExplicitMipChain: boolean;\n};\n\n// Flatten dimension-specific texture data into one list of uploadable subresources.\nfunction getTextureSubresources(\n props: TextureDataProps & Partial>\n): TextureSubresource[] {\n if (!props.data) {\n return [];\n }\n\n const baseLevelSize =\n props.width && props.height ? {width: props.width, height: props.height} : undefined;\n const textureFormat = 'format' in props ? props.format : undefined;\n\n switch (props.dimension) {\n case '1d':\n return getTexture1DSubresources(props.data);\n case '2d':\n return getTexture2DSubresources(0, props.data, baseLevelSize, textureFormat);\n case '3d':\n return getTexture3DSubresources(props.data);\n case '2d-array':\n return getTextureArraySubresources(props.data);\n case 'cube':\n return getTextureCubeSubresources(props.data);\n case 'cube-array':\n return getTextureCubeArraySubresources(props.data);\n default:\n throw new Error(`Unhandled dimension ${(props as TextureDataProps).dimension}`);\n }\n}\n\n// Resolve a consistent texture format and the longest mip chain valid across all slices.\nfunction analyzeTextureSubresources(\n device: Device,\n subresources: TextureSubresource[],\n size: {width: number; height: number},\n options: {format?: TextureFormat}\n): TextureSubresourceAnalysis {\n if (subresources.length === 0) {\n return {\n subresources,\n mipLevels: 1,\n format: options.format,\n hasExplicitMipChain: false\n };\n }\n\n const groupedSubresources = new Map();\n for (const subresource of subresources) {\n const group = groupedSubresources.get(subresource.z) ?? [];\n group.push(subresource);\n groupedSubresources.set(subresource.z, group);\n }\n\n const hasExplicitMipChain = subresources.some(subresource => subresource.mipLevel > 0);\n let resolvedFormat = options.format;\n let resolvedMipLevels = Number.POSITIVE_INFINITY;\n const validSubresources: TextureSubresource[] = [];\n\n for (const [z, sliceSubresources] of groupedSubresources) {\n // Validate each slice independently, then keep only the mip levels that are valid everywhere.\n const sortedSubresources = [...sliceSubresources].sort(\n (left, right) => left.mipLevel - right.mipLevel\n );\n const baseLevel = sortedSubresources[0];\n if (!baseLevel || baseLevel.mipLevel !== 0) {\n throw new Error(`DynamicTexture: slice ${z} is missing mip level 0`);\n }\n\n const baseSize = getTextureSubresourceSize(device, baseLevel);\n if (baseSize.width !== size.width || baseSize.height !== size.height) {\n throw new Error(\n `DynamicTexture: slice ${z} base level dimensions ${baseSize.width}x${baseSize.height} do not match expected ${size.width}x${size.height}`\n );\n }\n\n const baseFormat = getTextureSubresourceFormat(baseLevel);\n if (baseFormat) {\n if (resolvedFormat && resolvedFormat !== baseFormat) {\n throw new Error(\n `DynamicTexture: slice ${z} base level format \"${baseFormat}\" does not match texture format \"${resolvedFormat}\"`\n );\n }\n resolvedFormat = baseFormat;\n }\n\n const mipLevelLimit =\n resolvedFormat && device.isTextureFormatCompressed(resolvedFormat)\n ? // Block-compressed formats cannot have mips smaller than a single compression block.\n getMaxCompressedMipLevels(device, baseSize.width, baseSize.height, resolvedFormat)\n : device.getMipLevelCount(baseSize.width, baseSize.height);\n\n let validMipLevelsForSlice = 0;\n for (\n let expectedMipLevel = 0;\n expectedMipLevel < sortedSubresources.length;\n expectedMipLevel++\n ) {\n const subresource = sortedSubresources[expectedMipLevel];\n // Stop at the first gap so callers can provide extra trailing data without breaking creation.\n if (!subresource || subresource.mipLevel !== expectedMipLevel) {\n break;\n }\n if (expectedMipLevel >= mipLevelLimit) {\n break;\n }\n\n const subresourceSize = getTextureSubresourceSize(device, subresource);\n const expectedWidth = Math.max(1, baseSize.width >> expectedMipLevel);\n const expectedHeight = Math.max(1, baseSize.height >> expectedMipLevel);\n if (subresourceSize.width !== expectedWidth || subresourceSize.height !== expectedHeight) {\n break;\n }\n\n const subresourceFormat = getTextureSubresourceFormat(subresource);\n if (subresourceFormat) {\n if (!resolvedFormat) {\n resolvedFormat = subresourceFormat;\n }\n // Later mip levels must stay on the same format as the validated base level.\n if (subresourceFormat !== resolvedFormat) {\n break;\n }\n }\n\n validMipLevelsForSlice++;\n validSubresources.push(subresource);\n }\n\n resolvedMipLevels = Math.min(resolvedMipLevels, validMipLevelsForSlice);\n }\n\n const mipLevels = Number.isFinite(resolvedMipLevels) ? Math.max(1, resolvedMipLevels) : 1;\n\n return {\n // Keep every slice trimmed to the same mip count so the texture shape stays internally consistent.\n subresources: validSubresources.filter(subresource => subresource.mipLevel < mipLevels),\n mipLevels,\n format: resolvedFormat,\n hasExplicitMipChain\n };\n}\n\n// Read the per-level format using the transitional textureFormat -> format fallback rules.\nfunction getTextureSubresourceFormat(subresource: TextureSubresource): TextureFormat | undefined {\n if (subresource.type !== 'texture-data') {\n return undefined;\n }\n return subresource.textureFormat ?? resolveTextureImageFormat(subresource.data);\n}\n\n// Resolve dimensions from either raw bytes or external-image subresources.\nfunction getTextureSubresourceSize(\n device: Device,\n subresource: TextureSubresource\n): {width: number; height: number} {\n switch (subresource.type) {\n case 'external-image':\n return device.getExternalImageSize(subresource.image);\n case 'texture-data':\n return {width: subresource.data.width, height: subresource.data.height};\n default:\n throw new Error('Unsupported texture subresource');\n }\n}\n\n// Count the mip levels that stay at or above one compression block in each dimension.\nfunction getMaxCompressedMipLevels(\n device: Device,\n baseWidth: number,\n baseHeight: number,\n format: TextureFormat\n): number {\n const {blockWidth = 1, blockHeight = 1} = device.getTextureFormatInfo(format);\n let mipLevels = 1;\n for (let mipLevel = 1; ; mipLevel++) {\n const width = Math.max(1, baseWidth >> mipLevel);\n const height = Math.max(1, baseHeight >> mipLevel);\n if (width < blockWidth || height < blockHeight) {\n break;\n }\n mipLevels++;\n }\n return mipLevels;\n}\n\n// HELPERS\n\n/** Resolve all promises in a nested data structure */\nasync function awaitAllPromises(x: any): Promise {\n x = await x;\n if (Array.isArray(x)) {\n return await Promise.all(x.map(awaitAllPromises));\n }\n if (x && typeof x === 'object' && x.constructor === Object) {\n const object: Record = x;\n const values = await Promise.all(Object.values(object).map(awaitAllPromises));\n const keys = Object.keys(object);\n const resolvedObject: Record = {};\n for (let i = 0; i < keys.length; i++) {\n resolvedObject[keys[i]] = values[i];\n }\n return resolvedObject;\n }\n return x;\n}\n\n// /** @note experimental: Set multiple mip levels (2D), optionally at `z`, slice (depth/array level) index */\n// setTexture2DData(lodData: Texture2DData, z: number = 0): void {\n// this._checkReady();\n\n// const lodArray = this._normalizeTexture2DData(lodData);\n\n// // If user supplied multiple mip levels, warn if auto-mips also requested\n// if (lodArray.length > 1 && this.props.mipmaps !== false) {\n// log.warn(\n// `Texture ${this.id}: provided multiple LODs and also requested mipmap generation.`\n// )();\n// }\n\n// for (let mipLevel = 0; mipLevel < lodArray.length; mipLevel++) {\n// const imageData = lodArray[mipLevel];\n// if (this.device.isExternalImage(imageData)) {\n// this.texture.copyExternalImage({image: imageData, z, mipLevel, flipY: true});\n// } else if (this._isTextureImageData(imageData)) {\n// this.texture.copyImageData({data: imageData.data, z, mipLevel});\n// } else {\n// throw new Error('Unsupported 2D mip-level payload');\n// }\n// }\n// }\n\n// /** Normalize 2D layer payload into an array of mip-level items */\n// private _normalizeTexture2DData(data: Texture2DData): (TextureImageData | ExternalImage)[] {\n// return Array.isArray(data) ? data : [data];\n// }\n","import type {TypedArray, TextureFormat, ExternalImage} from '@luma.gl/core';\nimport {isExternalImage, getExternalImageSize} from '@luma.gl/core';\n\nexport type TextureImageSource = ExternalImage;\n\n/**\n * One mip level\n * Basic data structure is similar to `ImageData`\n * additional optional fields can describe compressed texture data.\n */\nexport type TextureImageData = {\n /** Preferred WebGPU style format string. */\n textureFormat?: TextureFormat;\n /** WebGPU style format string. Defaults to 'rgba8unorm' */\n format?: TextureFormat;\n /** Typed Array with the bytes of the image. @note beware row byte alignment requirements */\n data: TypedArray;\n /** Width of the image, in pixels, @note beware row byte alignment requirements */\n width: number;\n /** Height of the image, in rows */\n height: number;\n};\n\n/**\n * A single mip-level can be initialized by data or an ImageBitmap etc\n * @note in the WebGPU spec a mip-level is called a subresource\n */\nexport type TextureMipLevelData = TextureImageData | TextureImageSource;\n\n/**\n * Texture data for one image \"slice\" (which can consist of multiple miplevels)\n * Thus data for one slice be a single mip level or an array of miplevels\n * @note in the WebGPU spec each cross-section image in a 3D texture is called a \"slice\",\n * in a array texture each image in the array is called an array \"layer\"\n * luma.gl calls one image in a GPU texture a \"slice\" regardless of context.\n */\nexport type TextureSliceData = TextureMipLevelData | TextureMipLevelData[];\n\n/** Names of cube texture faces */\nexport type TextureCubeFace = '+X' | '-X' | '+Y' | '-Y' | '+Z' | '-Z';\n\n/** Array of cube texture faces. @note: index in array is the face index */\n// biome-ignore format: preserve layout\nexport const TEXTURE_CUBE_FACES = ['+X', '-X', '+Y', '-Y', '+Z', '-Z'] as const satisfies readonly TextureCubeFace[];\n\n/** Map of cube texture face names to face indexes */\n// biome-ignore format: preserve layout\nexport const TEXTURE_CUBE_FACE_MAP = {'+X': 0, '-X': 1, '+Y': 2, '-Y': 3, '+Z': 4, '-Z': 5} as const satisfies Record;\n\n/** @todo - Define what data type is supported for 1D textures. TextureImageData with height = 1 */\nexport type Texture1DData = TextureSliceData;\n\n/** Texture data can be one or more mip levels */\nexport type Texture2DData = TextureSliceData;\n\n/** 6 face textures */\nexport type TextureCubeData = Record;\n\n/** Array of textures */\nexport type Texture3DData = TextureSliceData[];\n\n/** Array of textures */\nexport type TextureArrayData = TextureSliceData[];\n\n/** Array of 6 face textures */\nexport type TextureCubeArrayData = Record[];\n\ntype TextureData =\n | Texture1DData\n | Texture3DData\n | TextureArrayData\n | TextureCubeArrayData\n | TextureCubeData;\n\n/** Sync data props */\nexport type TextureDataProps =\n | {dimension: '1d'; data: Texture1DData | null}\n | {dimension?: '2d'; data: Texture2DData | null}\n | {dimension: '3d'; data: Texture3DData | null}\n | {dimension: '2d-array'; data: TextureArrayData | null}\n | {dimension: 'cube'; data: TextureCubeData | null}\n | {dimension: 'cube-array'; data: TextureCubeArrayData | null};\n\n/** Async data props */\nexport type TextureDataAsyncProps =\n | {dimension: '1d'; data?: Promise | Texture1DData | null}\n | {dimension?: '2d'; data?: Promise | Texture2DData | null}\n | {dimension: '3d'; data?: Promise | Texture3DData | null}\n | {dimension: '2d-array'; data?: Promise | TextureArrayData | null}\n | {dimension: 'cube'; data?: Promise | TextureCubeData | null}\n | {dimension: 'cube-array'; data?: Promise | TextureCubeArrayData | null};\n\n/** Describes data for one sub resource (one mip level of one slice (depth or array layer)) */\nexport type TextureSubresource = {\n /** slice (depth or array layer)) */\n z: number;\n /** mip level (0 - max mip levels) */\n mipLevel: number;\n} & (\n | {\n type: 'external-image';\n image: ExternalImage;\n /** @deprecated is this an appropriate place for this flag? */\n flipY?: boolean;\n }\n | {\n type: 'texture-data';\n data: TextureImageData;\n textureFormat?: TextureFormat;\n }\n);\n\n/** Check if texture data is a typed array */\nexport function isTextureSliceData(data: TextureData): data is TextureImageData {\n const typedArray = (data as TextureImageData)?.data;\n return ArrayBuffer.isView(typedArray);\n}\n\nexport function getFirstMipLevel(layer: TextureSliceData | null): TextureMipLevelData | null {\n if (!layer) return null;\n return Array.isArray(layer) ? (layer[0] ?? null) : layer;\n}\n\nexport function getTextureSizeFromData(\n props: TextureDataProps\n): {width: number; height: number} | null {\n const {dimension, data} = props;\n if (!data) {\n return null;\n }\n\n switch (dimension) {\n case '1d': {\n const mipLevel = getFirstMipLevel(data);\n if (!mipLevel) return null;\n const {width} = getTextureMipLevelSize(mipLevel);\n return {width, height: 1};\n }\n case '2d': {\n const mipLevel = getFirstMipLevel(data);\n return mipLevel ? getTextureMipLevelSize(mipLevel) : null;\n }\n case '3d':\n case '2d-array': {\n if (!Array.isArray(data) || data.length === 0) return null;\n const mipLevel = getFirstMipLevel(data[0]);\n return mipLevel ? getTextureMipLevelSize(mipLevel) : null;\n }\n case 'cube': {\n const face = (Object.keys(data)[0] as TextureCubeFace) ?? null;\n if (!face) return null;\n const faceData = (data as Record)[face];\n const mipLevel = getFirstMipLevel(faceData);\n return mipLevel ? getTextureMipLevelSize(mipLevel) : null;\n }\n case 'cube-array': {\n if (!Array.isArray(data) || data.length === 0) return null;\n const firstCube = data[0];\n const face = (Object.keys(firstCube)[0] as TextureCubeFace) ?? null;\n if (!face) return null;\n const mipLevel = getFirstMipLevel(firstCube[face]);\n return mipLevel ? getTextureMipLevelSize(mipLevel) : null;\n }\n default:\n return null;\n }\n}\n\nfunction getTextureMipLevelSize(data: TextureMipLevelData): {width: number; height: number} {\n if (isExternalImage(data)) {\n return getExternalImageSize(data);\n }\n if (typeof data === 'object' && 'width' in data && 'height' in data) {\n return {width: data.width, height: data.height};\n }\n throw new Error('Unsupported mip-level data');\n}\n\n/** Type guard: is a mip-level `TextureImageData` (vs ExternalImage or bare typed array) */\nfunction isTextureImageData(data: unknown): data is TextureImageData {\n return (\n typeof data === 'object' &&\n data !== null &&\n 'data' in data &&\n 'width' in data &&\n 'height' in data\n );\n}\n\nfunction isTypedArrayMipLevelData(data: unknown): data is TypedArray {\n return ArrayBuffer.isView(data);\n}\n\nexport function resolveTextureImageFormat(data: TextureImageData): TextureFormat | undefined {\n const {textureFormat, format} = data;\n if (textureFormat && format && textureFormat !== format) {\n throw new Error(\n `Conflicting texture formats \"${textureFormat}\" and \"${format}\" provided for the same mip level`\n );\n }\n return textureFormat ?? format;\n}\n\n/** Resolve size for a single mip-level datum */\n// function getTextureMipLevelSizeFromData(data: TextureMipLevelData): {\n// width: number;\n// height: number;\n// } {\n// if (this.device.isExternalImage(data)) {\n// return this.device.getExternalImageSize(data);\n// }\n// if (this.isTextureImageData(data)) {\n// return {width: data.width, height: data.height};\n// }\n// // Fallback (should not happen with current types)\n// throw new Error('Unsupported mip-level data');\n// }\n\n/** Convert cube face label to depth index */\nexport function getCubeFaceIndex(face: TextureCubeFace): number {\n const idx = TEXTURE_CUBE_FACE_MAP[face];\n if (idx === undefined) throw new Error(`Invalid cube face: ${face}`);\n return idx;\n}\n\n/** Convert cube face label to texture slice index. Index can be used with `setTexture2DData()`. */\nexport function getCubeArrayFaceIndex(cubeIndex: number, face: TextureCubeFace): number {\n return 6 * cubeIndex + getCubeFaceIndex(face);\n}\n\n// ------------------ Upload helpers ------------------\n\n/** Experimental: Set multiple mip levels (1D) */\nexport function getTexture1DSubresources(data: Texture1DData): TextureSubresource[] {\n // Not supported in WebGL; left explicit\n throw new Error('setTexture1DData not supported in WebGL.');\n // const subresources: TextureSubresource[] = [];\n // return subresources;\n}\n\n/** Normalize 2D layer payload into an array of mip-level items */\nfunction _normalizeTexture2DData(\n data: Texture2DData\n): (TextureImageData | ExternalImage | TypedArray)[] {\n return Array.isArray(data) ? data : [data];\n}\n\n/** Experimental: Set multiple mip levels (2D), optionally at `z` (depth/array index) */\nexport function getTexture2DSubresources(\n slice: number,\n lodData: Texture2DData,\n baseLevelSize?: {width: number; height: number},\n textureFormat?: TextureFormat\n): TextureSubresource[] {\n const lodArray = _normalizeTexture2DData(lodData);\n const z = slice;\n\n const subresources: TextureSubresource[] = [];\n\n for (let mipLevel = 0; mipLevel < lodArray.length; mipLevel++) {\n const imageData = lodArray[mipLevel];\n if (isExternalImage(imageData)) {\n subresources.push({\n type: 'external-image',\n image: imageData,\n z,\n mipLevel\n });\n } else if (isTextureImageData(imageData)) {\n subresources.push({\n type: 'texture-data',\n data: imageData,\n textureFormat: resolveTextureImageFormat(imageData),\n z,\n mipLevel\n });\n } else if (isTypedArrayMipLevelData(imageData) && baseLevelSize) {\n subresources.push({\n type: 'texture-data',\n data: {\n data: imageData,\n width: Math.max(1, baseLevelSize.width >> mipLevel),\n height: Math.max(1, baseLevelSize.height >> mipLevel),\n ...(textureFormat ? {format: textureFormat} : {})\n },\n textureFormat,\n z,\n mipLevel\n });\n } else {\n throw new Error('Unsupported 2D mip-level payload');\n }\n }\n\n return subresources;\n}\n\n/** 3D: multiple depth slices, each may carry multiple mip levels */\nexport function getTexture3DSubresources(data: Texture3DData): TextureSubresource[] {\n const subresources: TextureSubresource[] = [];\n for (let depth = 0; depth < data.length; depth++) {\n subresources.push(...getTexture2DSubresources(depth, data[depth]));\n }\n return subresources;\n}\n\n/** 2D array: multiple layers, each may carry multiple mip levels */\nexport function getTextureArraySubresources(data: TextureArrayData): TextureSubresource[] {\n const subresources: TextureSubresource[] = [];\n for (let layer = 0; layer < data.length; layer++) {\n subresources.push(...getTexture2DSubresources(layer, data[layer]));\n }\n return subresources;\n}\n\n/** Cube: 6 faces, each may carry multiple mip levels */\nexport function getTextureCubeSubresources(data: TextureCubeData): TextureSubresource[] {\n const subresources: TextureSubresource[] = [];\n for (const [face, faceData] of Object.entries(data) as [TextureCubeFace, TextureSliceData][]) {\n const faceDepth = getCubeFaceIndex(face);\n subresources.push(...getTexture2DSubresources(faceDepth, faceData));\n }\n return subresources;\n}\n\n/** Cube array: multiple cubes (faces×layers), each face may carry multiple mips */\nexport function getTextureCubeArraySubresources(data: TextureCubeArrayData): TextureSubresource[] {\n const subresources: TextureSubresource[] = [];\n data.forEach((cubeData, cubeIndex) => {\n for (const [face, faceData] of Object.entries(cubeData)) {\n const faceDepth = getCubeArrayFaceIndex(cubeIndex, face as TextureCubeFace);\n subresources.push(...getTexture2DSubresources(faceDepth, faceData));\n }\n });\n return subresources;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Device, Buffer, BufferRange, TransformFeedback, RenderPassProps} from '@luma.gl/core';\nimport {getPassthroughFS} from '@luma.gl/shadertools';\nimport {Model} from '../model/model';\nimport type {ModelProps} from '../model/model';\n\n/**\n * Properties for creating a {@link BufferTransform}\n * @note Only works under WebGL2.\n */\nexport type BufferTransformProps = Omit & {\n /** Optional fragment shader - normally not used in transforms */\n fs?: ModelProps['fs']; // override as optional\n /** A list of named outputs corresponding to shader declarations (varyings in WebGL) */\n outputs?: string[];\n /** @deprecated Use run({outputBuffers}) instead - Map of output buffers that the shaders will write results of computations to */\n feedbackBuffers?: Record;\n};\n\n/**\n * Manages a WebGL program (pipeline) for buffer→buffer transforms.\n * @note Only works under WebGL2.\n */\nexport class BufferTransform {\n readonly device: Device;\n readonly model: Model;\n readonly transformFeedback: TransformFeedback;\n\n static defaultProps: Required = {\n ...Model.defaultProps,\n outputs: undefined!,\n feedbackBuffers: undefined!\n };\n\n static isSupported(device: Device): boolean {\n return device?.info?.type === 'webgl';\n }\n\n constructor(device: Device, props: BufferTransformProps = BufferTransform.defaultProps) {\n if (!BufferTransform.isSupported(device)) {\n throw new Error('BufferTransform not yet implemented on WebGPU');\n }\n\n this.device = device;\n\n this.model = new Model(this.device, {\n id: props.id || 'buffer-transform-model',\n fs: props.fs || getPassthroughFS(),\n topology: props.topology || 'point-list',\n varyings: props.outputs || props.varyings,\n ...props\n });\n\n this.transformFeedback = this.device.createTransformFeedback({\n layout: this.model.pipeline.shaderLayout,\n // @ts-expect-error TODO\n buffers: props.feedbackBuffers\n });\n\n this.model.setTransformFeedback(this.transformFeedback);\n\n Object.seal(this);\n }\n\n /** Destroy owned resources. */\n destroy(): void {\n if (this.model) {\n this.model.destroy();\n }\n }\n\n /** @deprecated Use {@link destroy}. */\n delete(): void {\n this.destroy();\n }\n\n /** Run one transform loop. */\n run(\n options?: RenderPassProps & {\n inputBuffers?: Record;\n outputBuffers?: Record;\n }\n ): void {\n if (options?.inputBuffers) {\n this.model.setAttributes(options.inputBuffers);\n }\n if (options?.outputBuffers) {\n this.transformFeedback.setBuffers(options.outputBuffers);\n }\n const renderPass = this.device.beginRenderPass(options);\n this.model.draw(renderPass);\n renderPass.end();\n }\n\n // DEPRECATED METHODS\n\n /** @deprecated App knows what buffers it is passing in - Returns the {@link Buffer} or {@link BufferRange} for given varying name. */\n getBuffer(varyingName: string): Buffer | BufferRange | null {\n return this.transformFeedback.getBuffer(varyingName);\n }\n\n /** @deprecated App knows what buffers it is passing in - Reads the {@link Buffer} or {@link BufferRange} for given varying name. */\n readAsync(varyingName: string): Promise {\n const result = this.getBuffer(varyingName);\n if (!result) {\n throw new Error('BufferTransform#getBuffer');\n }\n if (result instanceof Buffer) {\n return result.readAsync();\n }\n const {buffer, byteOffset = 0, byteLength = buffer.byteLength} = result;\n return buffer.readAsync(byteOffset, byteLength);\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {TypedArray} from '@math.gl/core';\nimport type {PrimitiveTopology} from '@luma.gl/core';\nimport {uid} from '../utils/uid';\n\nexport type GeometryProps = {\n id?: string;\n /** Determines how vertices are read from the 'vertex' attributes */\n topology: 'point-list' | 'line-list' | 'line-strip' | 'triangle-list' | 'triangle-strip';\n /** Auto calculated from attributes if not provided */\n vertexCount?: number;\n attributes: Record;\n indices?: GeometryAttribute | TypedArray;\n};\n\nexport type GeometryAttributes = {\n POSITION: GeometryAttribute;\n NORMAL: GeometryAttribute;\n TEXCOORD_0: GeometryAttribute;\n COLOR_0?: GeometryAttribute;\n indices?: GeometryAttribute & {size: 1; value: Uint32Array | Uint16Array};\n};\n\nexport type GeometryAttribute = {\n size?: number;\n value: TypedArray;\n [key: string]: any;\n};\n\nexport class Geometry {\n readonly id: string;\n /** Determines how vertices are read from the 'vertex' attributes */\n readonly topology?: PrimitiveTopology;\n readonly vertexCount: number;\n readonly indices?: GeometryAttribute;\n readonly attributes: {\n POSITION: GeometryAttribute;\n NORMAL: GeometryAttribute;\n TEXCOORD_0: GeometryAttribute;\n COLOR_0?: GeometryAttribute;\n [key: string]: GeometryAttribute | undefined;\n };\n\n userData: Record = {};\n\n constructor(props: GeometryProps) {\n const {attributes = {}, indices = null, vertexCount = null} = props;\n\n this.id = props.id || uid('geometry');\n this.topology = props.topology;\n\n if (indices) {\n this.indices = ArrayBuffer.isView(indices) ? {value: indices, size: 1} : indices;\n }\n\n // @ts-expect-error\n this.attributes = {};\n\n for (const [attributeName, attributeValue] of Object.entries(attributes)) {\n // Wrap \"unwrapped\" arrays and try to autodetect their type\n const attribute: GeometryAttribute = ArrayBuffer.isView(attributeValue)\n ? {value: attributeValue}\n : attributeValue;\n\n if (!ArrayBuffer.isView(attribute.value)) {\n throw new Error(\n `${this._print(attributeName)}: must be typed array or object with value as typed array`\n );\n }\n\n if ((attributeName === 'POSITION' || attributeName === 'positions') && !attribute.size) {\n attribute.size = 3;\n }\n\n // Move indices to separate field\n if (attributeName === 'indices') {\n if (this.indices) {\n throw new Error('Multiple indices detected');\n }\n this.indices = attribute;\n } else {\n this.attributes[attributeName] = attribute;\n }\n }\n\n if (this.indices && this.indices['isIndexed'] !== undefined) {\n this.indices = Object.assign({}, this.indices);\n delete this.indices['isIndexed'];\n }\n\n this.vertexCount = vertexCount || this._calculateVertexCount(this.attributes, this.indices);\n }\n\n getVertexCount(): number {\n return this.vertexCount;\n }\n\n /**\n * Return an object with all attributes plus indices added as a field.\n * TODO Geometry types are a mess\n */\n getAttributes(): GeometryAttributes {\n // @ts-ignore\n return this.indices ? {indices: this.indices, ...this.attributes} : this.attributes;\n }\n\n // PRIVATE\n\n _print(attributeName: string): string {\n return `Geometry ${this.id} attribute ${attributeName}`;\n }\n\n /**\n * GeometryAttribute\n * value: typed array\n * type: indices, vertices, uvs\n * size: elements per vertex\n * target: WebGL buffer type (string or constant)\n *\n * @param attributes\n * @param indices\n * @returns\n */\n _setAttributes(attributes: Record, indices: any): this {\n return this;\n }\n\n _calculateVertexCount(attributes: GeometryAttributes, indices?: GeometryAttribute): number {\n if (indices) {\n return indices.value.length;\n }\n let vertexCount = Infinity;\n for (const attribute of Object.values(attributes)) {\n const {value, size, constant} = attribute;\n if (!constant && value && size !== undefined && size >= 1) {\n vertexCount = Math.min(vertexCount, value.length / size);\n }\n }\n\n // assert(Number.isFinite(vertexCount));\n return vertexCount;\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport LayersPass, {LayersPassRenderOptions, RenderStats, Rect} from './layers-pass';\nimport type {Framebuffer, Parameters, RenderPipelineParameters} from '@luma.gl/core';\nimport log from '../utils/log';\n\nimport type {Effect} from '../lib/effect';\nimport type Viewport from '../viewports/viewport';\nimport type Layer from '../lib/layer';\n\nconst PICKING_BLENDING: RenderPipelineParameters = {\n blendColorOperation: 'add',\n blendColorSrcFactor: 'one',\n blendColorDstFactor: 'zero',\n blendAlphaOperation: 'add',\n blendAlphaSrcFactor: 'constant',\n blendAlphaDstFactor: 'zero'\n};\n\ntype PickLayersPassRenderOptions = LayersPassRenderOptions & {\n pickingFBO: Framebuffer;\n deviceRect: Rect;\n pickZ: boolean;\n};\n\ntype EncodedPickingColors = {\n a: number;\n layer: Layer;\n viewports: Viewport[];\n};\n\nexport type PickingColorDecoder = (pickedColor: number[] | Uint8Array) =>\n | {\n pickedLayer: Layer;\n pickedViewports: Viewport[];\n pickedObjectIndex: number;\n }\n | undefined;\n\nexport default class PickLayersPass extends LayersPass {\n private pickZ?: boolean;\n private _colorEncoderState: {\n byLayer: Map;\n byAlpha: EncodedPickingColors[];\n } | null = null;\n\n render(props: LayersPassRenderOptions | PickLayersPassRenderOptions): {\n decodePickingColor: PickingColorDecoder | null;\n stats: RenderStats[];\n } {\n if ('pickingFBO' in props) {\n // When drawing into an off-screen buffer, use the alpha channel to encode layer index\n return this._drawPickingBuffer(props);\n }\n // When drawing to screen (debug mode), do not use the alpha channel so that result is always visible\n const stats = super._render(props);\n return {decodePickingColor: null, stats};\n }\n\n // Private\n // Draws list of layers and viewports into the picking buffer\n // Note: does not sample the buffer, that has to be done by the caller\n _drawPickingBuffer({\n layers,\n layerFilter,\n views,\n viewports,\n onViewportActive,\n pickingFBO,\n deviceRect: {x, y, width, height},\n cullRect,\n effects,\n pass = 'picking',\n pickZ,\n shaderModuleProps,\n clearColor\n }: PickLayersPassRenderOptions): {\n decodePickingColor: PickingColorDecoder | null;\n stats: RenderStats[];\n } {\n this.pickZ = pickZ;\n const colorEncoderState = this._resetColorEncoder(pickZ);\n const scissorRect = [x, y, width, height];\n\n // Make sure we clear scissor test and fbo bindings in case of exceptions\n // We are only interested in one pixel, no need to render anything else\n // Note that the callback here is called synchronously.\n // Set blend mode for picking\n // always overwrite existing pixel with [r,g,b,layerIndex]\n const renderStatus = super._render({\n target: pickingFBO,\n layers,\n layerFilter,\n views,\n viewports,\n onViewportActive,\n cullRect,\n effects: effects?.filter(e => e.useInPicking),\n pass,\n isPicking: true,\n shaderModuleProps,\n clearColor: clearColor ?? [0, 0, 0, 0],\n colorMask: 0xf,\n scissorRect\n });\n\n // Clear the temp field\n this._colorEncoderState = null;\n const decodePickingColor = colorEncoderState && decodeColor.bind(null, colorEncoderState);\n return {decodePickingColor, stats: renderStatus};\n }\n\n shouldDrawLayer(layer: Layer): boolean {\n const {pickable, operation} = layer.props;\n return (\n (pickable && operation.includes('draw')) ||\n operation.includes('terrain') ||\n operation.includes('mask')\n );\n }\n\n protected getShaderModuleProps(\n layer: Layer,\n effects: Effect[] | undefined,\n otherShaderModuleProps: Record\n ): any {\n return {\n picking: {\n isActive: 1,\n isAttribute: this.pickZ\n },\n lighting: {enabled: false}\n };\n }\n\n protected getLayerParameters(layer: Layer, layerIndex: number, viewport: Viewport): Parameters {\n // TODO use Parameters type\n const pickParameters: any = {\n ...layer.props.parameters\n };\n const {pickable, operation} = layer.props;\n\n if (!this._colorEncoderState) {\n pickParameters.blend = false;\n } else if (pickable && operation.includes('draw')) {\n // Encode pickable layers that include 'draw' operation (including 'terrain+draw')\n Object.assign(pickParameters, PICKING_BLENDING);\n pickParameters.blend = true;\n if (this.device.type === 'webgpu') {\n // WebGPU uses render-pass dynamic state for constant blending.\n pickParameters.blendConstant = encodeColor(this._colorEncoderState, layer, viewport);\n } else {\n pickParameters.blendColor = encodeColor(this._colorEncoderState, layer, viewport);\n }\n if (operation.includes('terrain') && layer.state?._hasPickingCover) {\n // For terrain+draw layers with a valid cover FBO, the terrain shader outputs the\n // cover FBO pixel which already has correctly encoded alpha from the cover encoder.\n // Use srcFactor 'one' to pass through the cover alpha without double-encoding.\n // Without a cover FBO, keep 'constant' so the layer's own picking colors encode correctly.\n pickParameters.blendAlphaSrcFactor = 'one';\n }\n } else if (operation.includes('terrain')) {\n // Pure terrain layers (without 'draw') don't need picking colors\n pickParameters.blend = false;\n }\n\n return pickParameters;\n }\n\n protected _resetColorEncoder(pickZ: boolean) {\n // Track encoded layer indices\n this._colorEncoderState = pickZ\n ? null\n : {\n byLayer: new Map(),\n byAlpha: []\n };\n // Temporarily store it on the instance so that it can be accessed by this.getLayerParameters\n return this._colorEncoderState;\n }\n}\n\n// Assign an unique alpha value for each pickable layer and track the encoding in the cache object\n// Returns normalized blend color\nfunction encodeColor(\n encoded: {\n byLayer: Map;\n byAlpha: EncodedPickingColors[];\n },\n layer: Layer,\n viewport: Viewport\n): number[] {\n const {byLayer, byAlpha} = encoded;\n let a;\n\n // Encode layerIndex in the alpha channel\n // TODO - combine small layers to better utilize the picking color space\n let entry = byLayer.get(layer);\n if (entry) {\n entry.viewports.push(viewport);\n a = entry.a;\n } else {\n a = byLayer.size + 1;\n if (a <= 255) {\n entry = {a, layer, viewports: [viewport]};\n byLayer.set(layer, entry);\n byAlpha[a] = entry;\n } else {\n log.warn('Too many pickable layers, only picking the first 255')();\n a = 0;\n }\n }\n return [0, 0, 0, a / 255];\n}\n\n// Given a picked color, retrieve the corresponding layer and viewports from cache\nfunction decodeColor(\n encoded: {\n byLayer: Map;\n byAlpha: EncodedPickingColors[];\n },\n pickedColor: number[] | Uint8Array\n):\n | {\n pickedLayer: Layer;\n pickedViewports: Viewport[];\n pickedObjectIndex: number;\n }\n | undefined {\n const entry = encoded.byAlpha[pickedColor[3]];\n return (\n entry && {\n pickedLayer: entry.layer,\n pickedViewports: entry.viewports,\n pickedObjectIndex: entry.layer.decodePickingColor(pickedColor)\n }\n );\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport const LIFECYCLE = {\n NO_STATE: 'Awaiting state',\n MATCHED: 'Matched. State transferred from previous layer',\n INITIALIZED: 'Initialized',\n AWAITING_GC: 'Discarded. Awaiting garbage collection',\n AWAITING_FINALIZATION: 'No longer matched. Awaiting garbage collection',\n FINALIZED: 'Finalized! Awaiting garbage collection'\n} as const;\n\nexport type Lifecycle = (typeof LIFECYCLE)[keyof typeof LIFECYCLE];\n\n/* Secret props keys */\n// Symbols are non-enumerable by default, does not show in for...in or Object.keys\n// but are copied with Object.assign ¯\\_(ツ)_/¯\n// Supported everywhere except IE11, can be polyfilled with core-js\nexport const COMPONENT_SYMBOL: unique symbol = Symbol.for('component');\nexport const PROP_TYPES_SYMBOL: unique symbol = Symbol.for('propTypes');\nexport const DEPRECATED_PROPS_SYMBOL: unique symbol = Symbol.for('deprecatedProps');\nexport const ASYNC_DEFAULTS_SYMBOL: unique symbol = Symbol.for('asyncPropDefaults');\nexport const ASYNC_ORIGINAL_SYMBOL: unique symbol = Symbol.for('asyncPropOriginal');\nexport const ASYNC_RESOLVED_SYMBOL: unique symbol = Symbol.for('asyncPropResolved');\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\ntype NestedArray = (T | NestedArray)[];\n\n/**\n * Flattens a nested array into a single level array,\n * or a single value into an array with one value\n * @example flatten([[1, [2]], [3], 4]) => [1, 2, 3, 4]\n * @example flatten(1) => [1]\n * @param array The array to flatten.\n * @param filter= - Optional predicate called on each `value` to\n * determine if it should be included (pushed onto) the resulting array.\n * @return Returns the new flattened array (new array or `result` if provided)\n */\nexport function flatten(\n array: T | NestedArray,\n filter: (element: T) => boolean = () => true\n): T[] {\n // Wrap single object in array\n if (!Array.isArray(array)) {\n return filter(array) ? [array] : [];\n }\n // Deep flatten and filter the array\n return flattenArray(array, filter, []);\n}\n\n/** Deep flattens an array. Helper to `flatten`, see its parameters */\nfunction flattenArray(array: NestedArray, filter: (element: T) => boolean, result: T[]): T[] {\n let index = -1;\n while (++index < array.length) {\n const value = array[index];\n if (Array.isArray(value)) {\n flattenArray(value, filter, result);\n } else if (filter(value)) {\n result.push(value);\n }\n }\n return result;\n}\n\n/** Uses copyWithin to significantly speed up typed array value filling */\nexport function fillArray({target, source, start = 0, count = 1}) {\n const length = source.length;\n const total = count * length;\n let copied = 0;\n for (let i = start; copied < length; copied++) {\n target[i++] = source[copied];\n }\n\n while (copied < total) {\n // If we have copied less than half, copy everything we got\n // else copy remaining in one operation\n if (copied < total - copied) {\n target.copyWithin(start + copied, start, start + copied);\n copied *= 2;\n } else {\n target.copyWithin(start + copied, start, start + total - copied);\n copied = total;\n }\n }\n\n return target;\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device, RenderPass} from '@luma.gl/core';\nimport {Timeline} from '@luma.gl/engine';\nimport type {ShaderAssembler, ShaderModule} from '@luma.gl/shadertools';\nimport {getShaderAssembler, layerUniforms} from '../shaderlib/index';\nimport {LIFECYCLE} from '../lifecycle/constants';\nimport log from '../utils/log';\nimport debug from '../debug/index';\nimport {flatten} from '../utils/flatten';\nimport {Stats} from '@probe.gl/stats';\nimport ResourceManager from './resource/resource-manager';\n\nimport Viewport from '../viewports/viewport';\n\nimport type Layer from './layer';\nimport type CompositeLayer from './composite-layer';\nimport type Deck from './deck';\n\nconst TRACE_SET_LAYERS = 'layerManager.setLayers';\nconst TRACE_ACTIVATE_VIEWPORT = 'layerManager.activateViewport';\n\nexport type LayerContext = {\n layerManager: LayerManager;\n resourceManager: ResourceManager;\n deck?: Deck;\n device: Device;\n shaderAssembler: ShaderAssembler;\n defaultShaderModules: ShaderModule[];\n renderPass: RenderPass;\n stats: Stats;\n viewport: Viewport;\n timeline: Timeline;\n mousePosition: {x: number; y: number} | null;\n userData: any;\n onError?: (error: Error, source: Layer) => void;\n /** @deprecated Use context.device */\n gl: WebGL2RenderingContext;\n};\n\nexport type LayersList = (Layer | undefined | false | null | LayersList)[];\n\nexport type LayerManagerProps = {\n deck?: Deck;\n stats?: Stats;\n viewport?: Viewport;\n timeline?: Timeline;\n};\nexport default class LayerManager {\n layers: Layer[];\n context: LayerContext;\n resourceManager: ResourceManager;\n\n private _lastRenderedLayers: LayersList = [];\n private _needsRedraw: string | false = false;\n private _needsUpdate: string | false = false;\n private _nextLayers: LayersList | null = null;\n private _debug: boolean = false;\n // This flag is separate from _needsUpdate because it can be set during an update and should trigger another full update\n private _defaultShaderModulesChanged: boolean = false;\n\n /**\n * @param device\n * @param param1\n */\n // eslint-disable-next-line\n constructor(device: Device, props: LayerManagerProps) {\n const {deck, stats, viewport, timeline} = props || {};\n\n // Currently deck.gl expects the DeckGL.layers array to be different\n // whenever React rerenders. If the same layers array is used, the\n // LayerManager's diffing algorithm will generate a fatal error and\n // break the rendering.\n\n // `this._lastRenderedLayers` stores the UNFILTERED layers sent\n // down to LayerManager, so that `layers` reference can be compared.\n // If it's the same across two React render calls, the diffing logic\n // will be skipped.\n this.layers = [];\n this.resourceManager = new ResourceManager({device, protocol: 'deck://'});\n\n this.context = {\n mousePosition: null,\n userData: {},\n layerManager: this,\n device,\n // @ts-expect-error\n gl: device?.gl,\n deck,\n shaderAssembler: getShaderAssembler(device?.info?.shadingLanguage || 'glsl'),\n defaultShaderModules: [layerUniforms],\n renderPass: undefined!,\n stats: stats || new Stats({id: 'deck.gl'}),\n // Make sure context.viewport is not empty on the first layer initialization\n viewport: viewport || new Viewport({id: 'DEFAULT-INITIAL-VIEWPORT'}), // Current viewport, exposed to layers for project* function\n timeline: timeline || new Timeline(),\n resourceManager: this.resourceManager,\n onError: undefined\n };\n\n Object.seal(this);\n }\n\n /** Method to call when the layer manager is not needed anymore. */\n finalize() {\n this.resourceManager.finalize();\n // Finalize all layers\n for (const layer of this.layers) {\n this._finalizeLayer(layer);\n }\n }\n\n /** Check if a redraw is needed */\n needsRedraw(\n opts: {\n /** Reset redraw flags to false after the call */\n clearRedrawFlags: boolean;\n } = {clearRedrawFlags: false}\n ): string | false {\n let redraw = this._needsRedraw;\n if (opts.clearRedrawFlags) {\n this._needsRedraw = false;\n }\n\n // This layers list doesn't include sublayers, relying on composite layers\n for (const layer of this.layers) {\n // Call every layer to clear their flags\n const layerNeedsRedraw = layer.getNeedsRedraw(opts);\n redraw = redraw || layerNeedsRedraw;\n }\n\n return redraw;\n }\n\n /** Check if a deep update of all layers is needed */\n needsUpdate(): string | false {\n if (this._nextLayers && this._nextLayers !== this._lastRenderedLayers) {\n // New layers array may be the same as the old one if `setProps` is called by React\n return 'layers changed';\n }\n if (this._defaultShaderModulesChanged) {\n return 'shader modules changed';\n }\n return this._needsUpdate;\n }\n\n /** Layers will be redrawn (in next animation frame) */\n setNeedsRedraw(reason: string): void {\n this._needsRedraw = this._needsRedraw || reason;\n }\n\n /** Layers will be updated deeply (in next animation frame)\n Potentially regenerating attributes and sub layers */\n setNeedsUpdate(reason: string): void {\n this._needsUpdate = this._needsUpdate || reason;\n }\n\n /** Gets a list of currently rendered layers. Optionally filter by id. */\n getLayers({layerIds}: {layerIds?: string[]} = {}): Layer[] {\n // Filtering by layerId compares beginning of strings, so that sublayers will be included\n // Dependes on the convention of adding suffixes to the parent's layer name\n return layerIds\n ? this.layers.filter(layer => layerIds.find(layerId => layer.id.indexOf(layerId) === 0))\n : this.layers;\n }\n\n /** Set props needed for layer rendering and picking. */\n setProps(props: any): void {\n if ('debug' in props) {\n this._debug = props.debug;\n }\n\n // A way for apps to add data to context that can be accessed in layers\n if ('userData' in props) {\n this.context.userData = props.userData;\n }\n\n // New layers will be processed in `updateLayers` in the next update cycle\n if ('layers' in props) {\n this._nextLayers = props.layers;\n }\n\n if ('onError' in props) {\n this.context.onError = props.onError;\n }\n }\n\n /** Supply a new layer list, initiating sublayer generation and layer matching */\n setLayers(newLayers: LayersList, reason?: string): void {\n debug(TRACE_SET_LAYERS, this, reason, newLayers);\n\n this._lastRenderedLayers = newLayers;\n\n const flatLayers = flatten(newLayers, Boolean) as Layer[];\n\n for (const layer of flatLayers) {\n layer.context = this.context;\n }\n\n this._updateLayers(this.layers, flatLayers);\n }\n\n /** Update layers from last cycle if `setNeedsUpdate()` has been called */\n updateLayers(): void {\n // NOTE: For now, even if only some layer has changed, we update all layers\n // to ensure that layer id maps etc remain consistent even if different\n // sublayers are rendered\n const reason = this.needsUpdate();\n if (reason) {\n this.setNeedsRedraw(`updating layers: ${reason}`);\n // Force a full update\n this.setLayers(this._nextLayers || this._lastRenderedLayers, reason);\n }\n // Updated, clear the backlog\n this._nextLayers = null;\n }\n\n //\n // INTERNAL METHODS\n //\n\n /** Make a viewport \"current\" in layer context, updating viewportChanged flags */\n activateViewport = (viewport: Viewport) => {\n debug(TRACE_ACTIVATE_VIEWPORT, this, viewport);\n if (viewport) {\n this.context.viewport = viewport;\n }\n };\n\n /** Register a default shader module */\n addDefaultShaderModule(module: ShaderModule) {\n const {defaultShaderModules} = this.context;\n if (!defaultShaderModules.find(m => m.name === module.name)) {\n defaultShaderModules.push(module);\n this._defaultShaderModulesChanged = true;\n }\n }\n\n /** Deregister a default shader module */\n removeDefaultShaderModule(module: ShaderModule) {\n const {defaultShaderModules} = this.context;\n const i = defaultShaderModules.findIndex(m => m.name === module.name);\n if (i >= 0) {\n defaultShaderModules.splice(i, 1);\n this._defaultShaderModulesChanged = true;\n }\n }\n\n private _handleError(stage: string, error: Error, layer: Layer) {\n layer.raiseError(error, `${stage} of ${layer}`);\n }\n\n // TODO - mark layers with exceptions as bad and remove from rendering cycle?\n /** Match all layers, checking for caught errors\n to avoid having an exception in one layer disrupt other layers */\n private _updateLayers(oldLayers: Layer[], newLayers: Layer[]): void {\n // Create old layer map\n const oldLayerMap: {[layerId: string]: Layer | null} = {};\n for (const oldLayer of oldLayers) {\n if (oldLayerMap[oldLayer.id]) {\n log.warn(`Multiple old layers with same id ${oldLayer.id}`)();\n } else {\n oldLayerMap[oldLayer.id] = oldLayer;\n }\n }\n\n if (this._defaultShaderModulesChanged) {\n for (const layer of oldLayers) {\n layer.setNeedsUpdate();\n layer.setChangeFlags({extensionsChanged: true});\n }\n this._defaultShaderModulesChanged = false;\n }\n\n // Allocate array for generated layers\n const generatedLayers: Layer[] = [];\n\n // Match sublayers\n this._updateSublayersRecursively(newLayers, oldLayerMap, generatedLayers);\n\n // Finalize unmatched layers\n this._finalizeOldLayers(oldLayerMap);\n\n let needsUpdate: string | false = false;\n for (const layer of generatedLayers) {\n if (layer.hasUniformTransition()) {\n needsUpdate = `Uniform transition in ${layer}`;\n break;\n }\n }\n\n this._needsUpdate = needsUpdate;\n this.layers = generatedLayers;\n }\n\n /* eslint-disable complexity,max-statements */\n // Note: adds generated layers to `generatedLayers` array parameter\n private _updateSublayersRecursively(\n newLayers: Layer[],\n oldLayerMap: {[layerId: string]: Layer | null},\n generatedLayers: Layer[]\n ) {\n for (const newLayer of newLayers) {\n newLayer.context = this.context;\n\n // Given a new coming layer, find its matching old layer (if any)\n const oldLayer = oldLayerMap[newLayer.id];\n if (oldLayer === null) {\n // null, rather than undefined, means this id was originally there\n log.warn(`Multiple new layers with same id ${newLayer.id}`)();\n }\n // Remove the old layer from candidates, as it has been matched with this layer\n oldLayerMap[newLayer.id] = null;\n\n let sublayers: Layer[] | null = null;\n\n // We must not generate exceptions until after layer matching is complete\n try {\n if (this._debug && oldLayer !== newLayer) {\n newLayer.validateProps();\n }\n\n if (!oldLayer) {\n this._initializeLayer(newLayer);\n } else {\n this._transferLayerState(oldLayer, newLayer);\n this._updateLayer(newLayer);\n }\n generatedLayers.push(newLayer);\n\n // Call layer lifecycle method: render sublayers\n sublayers = newLayer.isComposite ? (newLayer as CompositeLayer).getSubLayers() : null;\n // End layer lifecycle method: render sublayers\n } catch (err) {\n this._handleError('matching', err as Error, newLayer); // Record first exception\n }\n\n if (sublayers) {\n this._updateSublayersRecursively(sublayers, oldLayerMap, generatedLayers);\n }\n }\n }\n /* eslint-enable complexity,max-statements */\n\n // Finalize any old layers that were not matched\n private _finalizeOldLayers(oldLayerMap: {[layerId: string]: Layer | null}): void {\n for (const layerId in oldLayerMap) {\n const layer = oldLayerMap[layerId];\n if (layer) {\n this._finalizeLayer(layer);\n }\n }\n }\n\n // / EXCEPTION SAFE LAYER ACCESS\n\n /** Safely initializes a single layer, calling layer methods */\n private _initializeLayer(layer: Layer): void {\n try {\n layer._initialize();\n layer.lifecycle = LIFECYCLE.INITIALIZED;\n } catch (err) {\n this._handleError('initialization', err as Error, layer);\n // TODO - what should the lifecycle state be here? LIFECYCLE.INITIALIZATION_FAILED?\n }\n }\n\n /** Transfer state from one layer to a newer version */\n private _transferLayerState(oldLayer: Layer, newLayer: Layer): void {\n newLayer._transferState(oldLayer);\n newLayer.lifecycle = LIFECYCLE.MATCHED;\n\n if (newLayer !== oldLayer) {\n oldLayer.lifecycle = LIFECYCLE.AWAITING_GC;\n }\n }\n\n /** Safely updates a single layer, cleaning all flags */\n private _updateLayer(layer: Layer): void {\n try {\n layer._update();\n } catch (err) {\n this._handleError('update', err as Error, layer);\n }\n }\n\n /** Safely finalizes a single layer, removing all resources */\n private _finalizeLayer(layer: Layer): void {\n this._needsRedraw = this._needsRedraw || `finalized ${layer}`;\n\n layer.lifecycle = LIFECYCLE.AWAITING_FINALIZATION;\n\n try {\n layer._finalize();\n layer.lifecycle = LIFECYCLE.FINALIZED;\n } catch (err) {\n this._handleError('finalization', err as Error, layer);\n }\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {load} from '@loaders.gl/core';\n\nimport type {ResourceManagerContext} from './resource-manager';\n\nexport type ResourceSubscriber = {\n onChange: (data: T | Promise) => void;\n};\n\nexport default class Resource {\n id: string;\n context: ResourceManagerContext;\n isLoaded!: boolean;\n persistent?: boolean;\n\n private _loadCount: number = 0;\n private _subscribers = new Set>();\n private _data!: T | Promise | string;\n private _loader?: Promise;\n private _error?: Error;\n private _content?: T;\n\n constructor(id: string, data: T | Promise | string, context: ResourceManagerContext) {\n this.id = id;\n this.context = context;\n\n this.setData(data);\n }\n\n // consumer: {onChange: Function}\n subscribe(consumer: ResourceSubscriber): void {\n this._subscribers.add(consumer);\n }\n\n unsubscribe(consumer: ResourceSubscriber): void {\n this._subscribers.delete(consumer);\n }\n\n inUse(): boolean {\n return this._subscribers.size > 0;\n }\n\n delete(): void {\n // Remove any resources created\n }\n\n getData(): T | Promise {\n return this.isLoaded\n ? this._error\n ? Promise.reject(this._error)\n : this._content!\n : this._loader!.then(() => this.getData());\n }\n\n setData(data: any, forceUpdate?: boolean) {\n if (data === this._data && !forceUpdate) {\n return;\n }\n this._data = data;\n const loadCount = ++this._loadCount;\n\n let loader = data;\n if (typeof data === 'string') {\n loader = load(data);\n }\n if (loader instanceof Promise) {\n this.isLoaded = false;\n this._loader = loader\n .then(result => {\n // check if source has changed\n if (this._loadCount === loadCount) {\n this.isLoaded = true;\n this._error = undefined;\n this._content = result;\n }\n })\n .catch(error => {\n if (this._loadCount === loadCount) {\n this.isLoaded = true;\n this._error = error || true;\n }\n });\n } else {\n this.isLoaded = true;\n this._error = undefined;\n this._content = data;\n }\n\n for (const subscriber of this._subscribers) {\n subscriber.onChange(this.getData());\n }\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/* global setTimeout */\nimport {Device} from '@luma.gl/core';\nimport Resource from './resource';\nimport type {ResourceSubscriber} from './resource';\n\nexport type ResourceManagerContext = {\n device: Device;\n resourceManager: ResourceManager;\n /** @deprecated */\n gl: WebGL2RenderingContext;\n};\n\ntype Consumer = Record;\n\nexport default class ResourceManager {\n protocol: string;\n\n private _context: ResourceManagerContext;\n private _resources: Record;\n private _consumers: Record;\n private _pruneRequest: number | null;\n\n constructor(props: {device: Device; protocol?: string}) {\n this.protocol = props.protocol || 'resource://';\n\n this._context = {\n device: props.device,\n // @ts-expect-error\n gl: props.device?.gl,\n resourceManager: this\n };\n this._resources = {};\n this._consumers = {};\n\n this._pruneRequest = null;\n }\n\n contains(resourceId: string): boolean {\n if (resourceId.startsWith(this.protocol)) {\n return true;\n }\n return resourceId in this._resources;\n }\n\n add({\n resourceId,\n data,\n forceUpdate = false,\n persistent = true\n }: {\n resourceId: string;\n data: any;\n forceUpdate?: boolean;\n persistent?: boolean;\n }) {\n let res = this._resources[resourceId];\n\n if (res) {\n res.setData(data, forceUpdate);\n } else {\n res = new Resource(resourceId, data, this._context);\n this._resources[resourceId] = res;\n }\n // persistent resources can only be removed by calling `remove`\n // non-persistent resources may be released when there are no more consumers\n res.persistent = persistent;\n }\n\n remove(resourceId: string): void {\n const res = this._resources[resourceId];\n\n if (res) {\n res.delete();\n delete this._resources[resourceId];\n }\n }\n\n unsubscribe({consumerId}: {consumerId: string}): void {\n const consumer = this._consumers[consumerId];\n if (consumer) {\n for (const requestId in consumer) {\n const request = consumer[requestId];\n const resource = this._resources[request.resourceId];\n if (resource) {\n resource.unsubscribe(request);\n }\n }\n delete this._consumers[consumerId];\n this.prune();\n }\n }\n\n subscribe({\n resourceId,\n onChange,\n consumerId,\n requestId = 'default'\n }: {\n resourceId: string;\n onChange: (data: T | Promise) => void;\n consumerId: string;\n requestId: string;\n }): T | Promise | undefined {\n const {_resources: resources, protocol} = this;\n if (resourceId.startsWith(protocol)) {\n resourceId = resourceId.replace(protocol, '');\n if (!resources[resourceId]) {\n // Add placeholder. When this resource becomes available, the consumer will be notified.\n this.add({resourceId, data: null, persistent: false});\n }\n }\n const res: Resource = resources[resourceId];\n this._track(consumerId, requestId, res, onChange);\n if (res) {\n return res.getData();\n }\n\n return undefined;\n }\n\n prune(): void {\n if (!this._pruneRequest) {\n // prune() may be called multiple times in the same animation frame.\n // Batch multiple requests together\n // @ts-ignore setTimeout returns NodeJS.Timeout in node\n this._pruneRequest = setTimeout(() => this._prune(), 0);\n }\n }\n\n finalize(): void {\n for (const key in this._resources) {\n this._resources[key].delete();\n }\n }\n\n private _track(\n consumerId: string,\n requestId: string,\n resource: Resource,\n onChange: (data: any) => void\n ) {\n const consumers = this._consumers;\n const consumer = (consumers[consumerId] = consumers[consumerId] || {});\n let request = consumer[requestId];\n\n const oldResource = request && request.resourceId && this._resources[request.resourceId];\n if (oldResource) {\n oldResource.unsubscribe(request);\n this.prune();\n }\n if (resource) {\n if (request) {\n request.onChange = onChange;\n request.resourceId = resource.id;\n } else {\n request = {\n onChange,\n resourceId: resource.id\n };\n }\n consumer[requestId] = request;\n resource.subscribe(request);\n }\n }\n\n private _prune(): void {\n this._pruneRequest = null;\n\n for (const key of Object.keys(this._resources)) {\n const res = this._resources[key];\n if (!res.persistent && !res.inUse()) {\n res.delete();\n delete this._resources[key];\n }\n }\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/**\n * Fast partial deep equal for prop.\n *\n * @param a Prop\n * @param b Prop to compare against `a`\n * @param depth Depth to which to recurse in nested Objects/Arrays. Use 0 (default) for shallow comparison, -1 for infinite depth\n */\n/* eslint-disable complexity */\nexport function deepEqual(a: any, b: any, depth: number): boolean {\n if (a === b) {\n return true;\n }\n if (!depth || !a || !b) {\n return false;\n }\n if (Array.isArray(a)) {\n if (!Array.isArray(b) || a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (!deepEqual(a[i], b[i], depth - 1)) {\n return false;\n }\n }\n return true;\n }\n if (Array.isArray(b)) {\n return false;\n }\n if (typeof a === 'object' && typeof b === 'object') {\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n if (aKeys.length !== bKeys.length) {\n return false;\n }\n for (const key of aKeys) {\n if (!b.hasOwnProperty(key)) {\n return false;\n }\n if (!deepEqual(a[key], b[key], depth - 1)) {\n return false;\n }\n }\n return true;\n }\n return false;\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {deepEqual} from '../utils/deep-equal';\nimport log from '../utils/log';\nimport {flatten} from '../utils/flatten';\n\nimport type Controller from '../controllers/controller';\nimport type {ViewStateChangeParameters, InteractionState} from '../controllers/controller';\nimport type Viewport from '../viewports/viewport';\nimport type View from '../views/view';\nimport type {Timeline} from '@luma.gl/engine';\nimport type {EventManager} from 'mjolnir.js';\nimport type {ConstructorOf} from '../types/types';\nimport type {default as MapView, MapViewState} from '../views/map-view';\n\nexport type ViewOrViews = View | View[] | null;\ntype ViewStateOf = ViewT extends View ? ViewStateT : never;\ntype OneOfViews = ViewsT extends null\n ? MapView\n : ViewsT extends View[]\n ? ViewsT[number]\n : ViewsT;\nexport type AnyViewStateOf = ViewStateOf>;\nexport type ViewStateMap = ViewsT extends null\n ? MapViewState\n : ViewsT extends View\n ? ViewStateOf\n : {[viewId: string]: AnyViewStateOf};\n\n/** This is a very lose type of all \"acceptable\" viewState\n * It's not good for type hinting but matches what may exist internally\n */\nexport type ViewStateObject =\n | ViewStateMap\n | AnyViewStateOf\n | {[viewId: string]: AnyViewStateOf};\n\n/** ViewManager props directly supplied by the user */\ntype ViewManagerProps = {\n views: ViewsT;\n viewState: ViewStateObject | null;\n onViewStateChange?: (params: ViewStateChangeParameters>) => void;\n onInteractionStateChange?: (state: InteractionState) => void;\n pickPosition?: (x: number, y: number) => {coordinate?: number[]} | null;\n width?: number;\n height?: number;\n};\n\nexport default class ViewManager {\n width: number;\n height: number;\n views: View[];\n viewState: ViewStateObject;\n controllers: {[viewId: string]: Controller | null};\n timeline: Timeline;\n\n private _viewports: Viewport[];\n private _viewportMap: {[viewId: string]: Viewport};\n private _isUpdating: boolean;\n private _needsRedraw: string | false;\n private _needsUpdate: string | false;\n private _eventManager: EventManager;\n private _eventCallbacks: {\n onViewStateChange?: (params: ViewStateChangeParameters) => void;\n onInteractionStateChange?: (state: InteractionState) => void;\n };\n private _pickPosition?: (x: number, y: number) => {coordinate?: number[]} | null;\n\n constructor(\n props: ViewManagerProps & {\n // Initial options\n timeline: Timeline;\n eventManager: EventManager;\n }\n ) {\n // List of view descriptors, gets re-evaluated when width/height changes\n this.views = [];\n this.width = 100;\n this.height = 100;\n this.viewState = {} as any;\n this.controllers = {};\n this.timeline = props.timeline;\n\n this._viewports = []; // Generated viewports\n this._viewportMap = {};\n this._isUpdating = false;\n this._needsRedraw = 'First render';\n this._needsUpdate = 'Initialize';\n\n this._eventManager = props.eventManager;\n this._eventCallbacks = {\n onViewStateChange: props.onViewStateChange,\n onInteractionStateChange: props.onInteractionStateChange\n };\n this._pickPosition = props.pickPosition;\n\n Object.seal(this);\n\n // Init with default map viewport\n this.setProps(props);\n }\n\n /** Remove all resources and event listeners */\n finalize(): void {\n for (const key in this.controllers) {\n const controller = this.controllers[key];\n if (controller) {\n controller.finalize();\n }\n }\n this.controllers = {};\n }\n\n /** Check if a redraw is needed */\n needsRedraw(\n opts: {\n /** Reset redraw flags to false */\n clearRedrawFlags?: boolean;\n } = {clearRedrawFlags: false}\n ): string | false {\n const redraw = this._needsRedraw;\n if (opts.clearRedrawFlags) {\n this._needsRedraw = false;\n }\n return redraw;\n }\n\n /** Mark the manager as dirty. Will rebuild all viewports and update controllers. */\n setNeedsUpdate(reason: string): void {\n this._needsUpdate = this._needsUpdate || reason;\n this._needsRedraw = this._needsRedraw || reason;\n }\n\n /** Checks each viewport for transition updates */\n updateViewStates(): void {\n for (const viewId in this.controllers) {\n const controller = this.controllers[viewId];\n if (controller) {\n controller.updateTransition();\n }\n }\n }\n\n /** Get a set of viewports for a given width and height\n * TODO - Intention is for deck.gl to autodeduce width and height and drop the need for props\n * @param rect (object, optional) - filter the viewports\n * + not provided - return all viewports\n * + {x, y} - only return viewports that contain this pixel\n * + {x, y, width, height} - only return viewports that overlap with this rectangle\n */\n getViewports(rect?: {x: number; y: number; width?: number; height?: number}): Viewport[] {\n if (rect) {\n return this._viewports.filter(viewport => viewport.containsPixel(rect));\n }\n return this._viewports;\n }\n\n /** Get a map of all views */\n getViews(): {[viewId: string]: View} {\n const viewMap = {};\n this.views.forEach(view => {\n viewMap[view.id] = view;\n });\n return viewMap;\n }\n\n /** Resolves a viewId string to a View */\n getView(viewId: string): View | undefined {\n return this.views.find(view => view.id === viewId);\n }\n\n /** Returns the viewState for a specific viewId. Matches the viewState by\n 1. view.viewStateId\n 2. view.id\n 3. root viewState\n then applies the view's filter if any */\n getViewState(viewOrViewId: string | View): AnyViewStateOf {\n const view: View | undefined =\n typeof viewOrViewId === 'string' ? this.getView(viewOrViewId) : viewOrViewId;\n // Backward compatibility: view state for single view\n const viewState = (view && this.viewState[view.getViewStateId()]) || this.viewState;\n return (view ? view.filterViewState(viewState) : viewState) as AnyViewStateOf;\n }\n\n getViewport(viewId: string): Viewport | undefined {\n return this._viewportMap[viewId];\n }\n\n /**\n * Unproject pixel coordinates on screen onto world coordinates,\n * (possibly [lon, lat]) on map.\n * - [x, y] => [lng, lat]\n * - [x, y, z] => [lng, lat, Z]\n * @param {Array} xyz -\n * @param {Object} opts - options\n * @param {Object} opts.topLeft=true - Whether origin is top left\n * @return {Array|null} - [lng, lat, Z] or [X, Y, Z]\n */\n unproject(xyz: number[], opts?: {topLeft?: boolean}): number[] | null {\n const viewports = this.getViewports();\n const pixel = {x: xyz[0], y: xyz[1]};\n for (let i = viewports.length - 1; i >= 0; --i) {\n const viewport = viewports[i];\n if (viewport.containsPixel(pixel)) {\n const p = xyz.slice();\n p[0] -= viewport.x;\n p[1] -= viewport.y;\n return viewport.unproject(p, opts);\n }\n }\n return null;\n }\n\n /** Update the manager with new Deck props */\n setProps(props: Partial>) {\n if (props.views) {\n this._setViews(props.views);\n }\n\n if (props.viewState) {\n this._setViewState(props.viewState);\n }\n\n if ('width' in props || 'height' in props) {\n this._setSize(props.width as number, props.height as number);\n }\n\n if ('pickPosition' in props) {\n this._pickPosition = props.pickPosition;\n }\n\n // Important: avoid invoking _update() inside itself\n // Nested updates result in unexpected side effects inside _rebuildViewports()\n // when using auto control in pure-js\n if (!this._isUpdating) {\n this._update();\n }\n }\n\n //\n // PRIVATE METHODS\n //\n\n private _update(): void {\n this._isUpdating = true;\n\n // Only rebuild viewports if the update flag is set\n if (this._needsUpdate) {\n this._needsUpdate = false;\n this._rebuildViewports();\n }\n\n // If viewport transition(s) are triggered during viewports update, controller(s)\n // will immediately call `onViewStateChange` which calls `viewManager.setProps` again.\n if (this._needsUpdate) {\n this._needsUpdate = false;\n this._rebuildViewports();\n }\n\n this._isUpdating = false;\n }\n\n private _setSize(width: number, height: number): void {\n if (width !== this.width || height !== this.height) {\n this.width = width;\n this.height = height;\n this.setNeedsUpdate('Size changed');\n }\n }\n\n // Update the view descriptor list and set change flag if needed\n // Does not actually rebuild the `Viewport`s until `getViewports` is called\n private _setViews(views: View[]): void {\n views = flatten(views, Boolean);\n\n const viewsChanged = this._diffViews(views, this.views);\n if (viewsChanged) {\n this.setNeedsUpdate('views changed');\n }\n\n this.views = views;\n }\n\n private _setViewState(viewState: ViewStateObject): void {\n if (viewState) {\n // depth = 3 when comparing viewStates: viewId.position.0\n const viewStateChanged = !deepEqual(viewState, this.viewState, 3);\n\n if (viewStateChanged) {\n this.setNeedsUpdate('viewState changed');\n }\n\n this.viewState = viewState;\n } else {\n log.warn('missing `viewState` or `initialViewState`')();\n }\n }\n\n private _createController(\n view: View,\n props: {id: string; type: ConstructorOf>}\n ): Controller {\n const Controller = props.type;\n\n const controller = new Controller({\n timeline: this.timeline,\n eventManager: this._eventManager,\n // Set an internal callback that calls the prop callback if provided\n onViewStateChange: this._eventCallbacks.onViewStateChange,\n onStateChange: this._eventCallbacks.onInteractionStateChange,\n makeViewport: viewState =>\n this.getView(view.id)?.makeViewport({\n viewState,\n width: this.width,\n height: this.height\n }),\n pickPosition: this._pickPosition\n });\n\n return controller;\n }\n\n private _updateController(\n view: View,\n viewState: AnyViewStateOf,\n viewport: Viewport | null,\n controller?: Controller | null\n ): Controller | null {\n const controllerProps = view.controller;\n if (controllerProps && viewport) {\n const resolvedProps = {\n ...viewState,\n ...controllerProps,\n id: view.id,\n x: viewport.x,\n y: viewport.y,\n width: viewport.width,\n height: viewport.height\n };\n\n // Create controller if not already existing or if the type of the\n // controller has changed.\n if (!controller || controller.constructor !== controllerProps.type) {\n controller = this._createController(view, resolvedProps);\n }\n if (controller) {\n controller.setProps(resolvedProps);\n }\n return controller;\n }\n return null;\n }\n\n // Rebuilds viewports from descriptors towards a certain window size\n private _rebuildViewports(): void {\n const {views} = this;\n\n const oldControllers = this.controllers;\n this._viewports = [];\n this.controllers = {};\n\n let invalidateControllers = false;\n // Create controllers in reverse order, so that views on top receive events first\n for (let i = views.length; i--; ) {\n const view = views[i];\n const viewState = this.getViewState(view);\n const viewport = view.makeViewport({viewState, width: this.width, height: this.height});\n\n let oldController = oldControllers[view.id];\n const hasController = Boolean(view.controller);\n if (hasController && !oldController) {\n // When a new controller is added, invalidate all controllers below it so that\n // events are registered in the correct order\n invalidateControllers = true;\n }\n if ((invalidateControllers || !hasController) && oldController) {\n // Remove and reattach invalidated controller\n oldController.finalize();\n oldController = null;\n }\n\n // Update the controller\n this.controllers[view.id] = this._updateController(view, viewState, viewport, oldController);\n\n if (viewport) {\n this._viewports.unshift(viewport);\n }\n }\n\n // Remove unused controllers\n for (const id in oldControllers) {\n const oldController = oldControllers[id];\n if (oldController && !this.controllers[id]) {\n oldController.finalize();\n }\n }\n\n this._buildViewportMap();\n }\n\n _buildViewportMap(): void {\n // Build a view id to view index\n this._viewportMap = {};\n this._viewports.forEach(viewport => {\n if (viewport.id) {\n // TODO - issue warning if multiple viewports use same id\n this._viewportMap[viewport.id] = this._viewportMap[viewport.id] || viewport;\n }\n });\n }\n\n // Check if viewport array has changed, returns true if any change\n // Note that descriptors can be the same\n _diffViews(newViews: View[], oldViews: View[]): boolean {\n if (newViews.length !== oldViews.length) {\n return true;\n }\n\n return newViews.some((_, i) => !newViews[i].equals(oldViews[i]));\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport type LayoutExpression =\n | {type: 'literal'; value: number}\n | {type: 'percentage'; value: number}\n | {type: 'binary'; operator: '+' | '-'; left: LayoutExpression; right: LayoutExpression};\n\ntype Token =\n | {type: 'number'; value: number}\n | {type: 'word'; value: string}\n | {type: 'symbol'; value: string};\n\nconst NUMBER_REGEX = /^(?:\\d+\\.?\\d*|\\.\\d+)$/;\n\n// Takes a number or a string expression that may include numbers, percentages, `px` units or\n// CSS-style `calc()` expressions containing `+`/`-` operations and parentheses.\nexport function parsePosition(value: number | string): LayoutExpression {\n switch (typeof value) {\n case 'number':\n if (!Number.isFinite(value)) {\n throw new Error(`Could not parse position string ${value}`);\n }\n return {type: 'literal', value};\n\n case 'string':\n try {\n const tokens = tokenize(value);\n const parser = new LayoutExpressionParser(tokens);\n return parser.parseExpression();\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n throw new Error(`Could not parse position string ${value}: ${reason}`);\n }\n\n default:\n throw new Error(`Could not parse position string ${value}`);\n }\n}\n\nexport function evaluateLayoutExpression(expression: LayoutExpression, extent: number): number {\n switch (expression.type) {\n case 'literal':\n return expression.value;\n case 'percentage':\n return Math.round(expression.value * extent);\n case 'binary':\n const left = evaluateLayoutExpression(expression.left, extent);\n const right = evaluateLayoutExpression(expression.right, extent);\n return expression.operator === '+' ? left + right : left - right;\n default:\n throw new Error('Unknown layout expression type');\n }\n}\n\nexport function getPosition(expression: LayoutExpression, extent: number): number {\n return evaluateLayoutExpression(expression, extent);\n}\n\nfunction tokenize(input: string): Token[] {\n const tokens: Token[] = [];\n let index = 0;\n while (index < input.length) {\n const char = input[index];\n if (/\\s/.test(char)) {\n index++;\n continue;\n }\n if (char === '+' || char === '-' || char === '(' || char === ')' || char === '%') {\n tokens.push({type: 'symbol', value: char});\n index++;\n continue;\n }\n if (isDigit(char) || char === '.') {\n const start = index;\n let hasDecimal = char === '.';\n index++;\n while (index < input.length) {\n const next = input[index];\n if (isDigit(next)) {\n index++;\n continue;\n }\n if (next === '.' && !hasDecimal) {\n hasDecimal = true;\n index++;\n continue;\n }\n break;\n }\n const numberString = input.slice(start, index);\n if (!NUMBER_REGEX.test(numberString)) {\n throw new Error('Invalid number token');\n }\n tokens.push({type: 'number', value: parseFloat(numberString)});\n continue;\n }\n if (isAlpha(char)) {\n const start = index;\n while (index < input.length && isAlpha(input[index])) {\n index++;\n }\n const word = input.slice(start, index).toLowerCase();\n tokens.push({type: 'word', value: word});\n continue;\n }\n throw new Error('Invalid token in position string');\n }\n return tokens;\n}\n\nclass LayoutExpressionParser {\n private tokens: Token[];\n private index = 0;\n\n constructor(tokens: Token[]) {\n this.tokens = tokens;\n }\n\n parseExpression(): LayoutExpression {\n const expression = this.parseBinaryExpression();\n if (this.index < this.tokens.length) {\n throw new Error('Unexpected token at end of expression');\n }\n return expression;\n }\n\n private parseBinaryExpression(): LayoutExpression {\n let expression = this.parseFactor();\n let token = this.peek();\n while (isAddSubSymbol(token)) {\n this.index++;\n const right = this.parseFactor();\n expression = {type: 'binary', operator: token.value, left: expression, right};\n token = this.peek();\n }\n return expression;\n }\n\n private parseFactor(): LayoutExpression {\n const token = this.peek();\n if (!token) {\n throw new Error('Unexpected end of expression');\n }\n\n if (token.type === 'symbol' && token.value === '+') {\n this.index++;\n return this.parseFactor();\n }\n if (token.type === 'symbol' && token.value === '-') {\n this.index++;\n const factor = this.parseFactor();\n return {type: 'binary', operator: '-', left: {type: 'literal', value: 0}, right: factor};\n }\n if (token.type === 'symbol' && token.value === '(') {\n this.index++;\n const expression = this.parseBinaryExpression();\n if (!this.consumeSymbol(')')) {\n throw new Error('Missing closing parenthesis');\n }\n return expression;\n }\n if (token.type === 'word' && token.value === 'calc') {\n this.index++;\n if (!this.consumeSymbol('(')) {\n throw new Error('Missing opening parenthesis after calc');\n }\n const expression = this.parseBinaryExpression();\n if (!this.consumeSymbol(')')) {\n throw new Error('Missing closing parenthesis');\n }\n return expression;\n }\n if (token.type === 'number') {\n this.index++;\n const numberValue = token.value;\n const nextToken = this.peek();\n if (nextToken && nextToken.type === 'symbol' && nextToken.value === '%') {\n this.index++;\n return {type: 'percentage', value: numberValue / 100};\n }\n if (nextToken && nextToken.type === 'word' && nextToken.value === 'px') {\n this.index++;\n return {type: 'literal', value: numberValue};\n }\n return {type: 'literal', value: numberValue};\n }\n\n throw new Error('Unexpected token in expression');\n }\n\n private consumeSymbol(value: string): boolean {\n const token = this.peek();\n if (token && token.type === 'symbol' && token.value === value) {\n this.index++;\n return true;\n }\n return false;\n }\n\n private peek(): Token | null {\n return this.tokens[this.index] || null;\n }\n}\n\nfunction isDigit(char: string): boolean {\n return char >= '0' && char <= '9';\n}\n\nfunction isAlpha(char: string): boolean {\n return (char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z');\n}\n\nfunction isAddSubSymbol(token: Token | null): token is Token & {type: 'symbol'; value: '+' | '-'} {\n return Boolean(token && token.type === 'symbol' && (token.value === '+' || token.value === '-'));\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/** Merge two viewstates, except `id`\n * For position arrays such as `target`, only override the components that are defined.\n */\nexport function deepMergeViewState>(\n a: ViewStateT,\n b: ViewStateT\n): ViewStateT {\n const result = {...a};\n for (const key in b) {\n if (key === 'id') continue;\n if (Array.isArray(result[key]) && Array.isArray(b[key])) {\n result[key] = mergeNumericArray(result[key], b[key]) as any;\n } else {\n result[key] = b[key];\n }\n }\n return result;\n}\n\nfunction mergeNumericArray(target: number[], source: number[]): number[] {\n target = target.slice();\n for (let i = 0; i < source.length; i++) {\n const v = source[i];\n if (Number.isFinite(v)) {\n target[i] = v;\n }\n }\n return target;\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport Viewport from '../viewports/viewport';\nimport {parsePosition, getPosition, LayoutExpression} from '../utils/positions';\nimport {deepEqual} from '../utils/deep-equal';\nimport {deepMergeViewState} from '../utils/deep-merge';\nimport type Controller from '../controllers/controller';\nimport type {ControllerOptions} from '../controllers/controller';\nimport type {TransitionProps} from '../controllers/transition-manager';\nimport type {Padding} from '../viewports/viewport';\nimport type {ConstructorOf} from '../types/types';\n\nexport type CommonViewState = TransitionProps;\n\nexport type CommonViewProps = {\n /** A unique id of the view. In a multi-view use case, this is important for matching view states and place contents into this view. */\n id?: string;\n /** A relative (e.g. `'50%'`) or absolute position. Default `0`. */\n x?: number | string;\n /** A relative (e.g. `'50%'`) or absolute position. Default `0`. */\n y?: number | string;\n /** A relative (e.g. `'50%'`) or absolute extent. Default `'100%'`. */\n width?: number | string;\n /** A relative (e.g. `'50%'`) or absolute extent. Default `'100%'`. */\n height?: number | string;\n /** Padding around the view, expressed in either relative (e.g. `'50%'`) or absolute pixels. Default `null`. */\n padding?: {\n left?: number | string;\n right?: number | string;\n top?: number | string;\n bottom?: number | string;\n } | null;\n /** When using multiple views, set this flag to wipe the pixels drawn by other overlapping views. Default `false` */\n clear?: boolean;\n /** Color to clear the viewport with, in RGBA format [r, g, b, a?]. Values are 0-255. Default `[0, 0, 0, 0]` (transparent). */\n clearColor?: number[] | false;\n /** Depth buffer value to clear the viewport with, between 0.0 - 1.0. Default `1.0` (far plane). */\n clearDepth?: number | false;\n /** Stencil buffer Value to clear the viewport with, between 0 - 255. Default `0` (clear). */\n clearStencil?: number | false;\n /** State of the view */\n viewState?:\n | string\n | ({\n id?: string;\n } & Partial);\n /** Options for viewport interactivity. */\n controller?:\n | null\n | boolean\n | ConstructorOf>\n | (ControllerOptions & {\n type?: ConstructorOf>;\n });\n};\n\nexport default abstract class View<\n ViewState extends CommonViewState = CommonViewState,\n ViewProps extends CommonViewProps = CommonViewProps\n> {\n id: string;\n abstract getViewportType(viewState: ViewState): ConstructorOf;\n protected abstract get ControllerType(): ConstructorOf>;\n\n private _x: LayoutExpression;\n private _y: LayoutExpression;\n private _width: LayoutExpression;\n private _height: LayoutExpression;\n private _padding: {\n left: LayoutExpression;\n right: LayoutExpression;\n top: LayoutExpression;\n bottom: LayoutExpression;\n } | null;\n\n readonly props: ViewProps;\n\n constructor(props: ViewProps) {\n const {id, x = 0, y = 0, width = '100%', height = '100%', padding = null} = props;\n\n // @ts-ignore\n this.id = id || this.constructor.displayName || 'view';\n\n this.props = {...props, id: this.id};\n\n // Extents\n this._x = parsePosition(x);\n this._y = parsePosition(y);\n this._width = parsePosition(width);\n this._height = parsePosition(height);\n this._padding = padding && {\n left: parsePosition(padding.left || 0),\n right: parsePosition(padding.right || 0),\n top: parsePosition(padding.top || 0),\n bottom: parsePosition(padding.bottom || 0)\n };\n\n // Bind methods for easy access\n this.equals = this.equals.bind(this);\n\n Object.seal(this);\n }\n\n equals(view: this): boolean {\n if (this === view) {\n return true;\n }\n\n // To correctly compare padding use depth=2\n return this.constructor === view.constructor && deepEqual(this.props, view.props, 2);\n }\n\n /** Clone this view with modified props */\n clone(newProps: Partial): this {\n const ViewConstructor = this.constructor as new (props: ViewProps) => this;\n return new ViewConstructor({...this.props, ...newProps});\n }\n\n /** Make viewport from canvas dimensions and view state */\n makeViewport({width, height, viewState}: {width: number; height: number; viewState: ViewState}) {\n viewState = this.filterViewState(viewState);\n\n // Resolve relative viewport dimensions\n const viewportDimensions = this.getDimensions({width, height});\n if (!viewportDimensions.height || !viewportDimensions.width) {\n return null;\n }\n const ViewportType = this.getViewportType(viewState);\n return new ViewportType({...viewState, ...this.props, ...viewportDimensions});\n }\n\n getViewStateId(): string {\n const {viewState} = this.props;\n if (typeof viewState === 'string') {\n // if View.viewState is a string, return it\n return viewState;\n }\n return viewState?.id || this.id;\n }\n\n // Allows view to override (or completely define) viewState\n filterViewState(viewState: ViewState): ViewState {\n if (this.props.viewState && typeof this.props.viewState === 'object') {\n // If we have specified an id, then intent is to override,\n // If not, completely specify the view state\n if (!this.props.viewState.id) {\n return this.props.viewState as ViewState;\n }\n\n return deepMergeViewState(viewState, this.props.viewState as ViewState);\n }\n\n return viewState;\n }\n\n /** Resolve the dimensions of the view from overall canvas dimensions */\n getDimensions({width, height}: {width: number; height: number}): {\n x: number;\n y: number;\n width: number;\n height: number;\n padding?: Padding;\n } {\n const dimensions: {\n x: number;\n y: number;\n width: number;\n height: number;\n padding?: Padding;\n } = {\n x: getPosition(this._x, width),\n y: getPosition(this._y, height),\n width: getPosition(this._width, width),\n height: getPosition(this._height, height)\n };\n\n if (this._padding) {\n dimensions.padding = {\n left: getPosition(this._padding.left, width),\n top: getPosition(this._padding.top, height),\n right: getPosition(this._padding.right, width),\n bottom: getPosition(this._padding.bottom, height)\n };\n }\n return dimensions;\n }\n\n // Used by sub classes to resolve controller props\n get controller(): (ControllerOptions & {type: ConstructorOf>}) | null {\n const opts = this.props.controller;\n\n if (!opts) {\n return null;\n }\n if (opts === true) {\n return {type: this.ControllerType};\n }\n if (typeof opts === 'function') {\n return {type: opts};\n }\n return {type: this.ControllerType, ...opts};\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Timeline} from '@luma.gl/engine';\n\nexport type TransitionSettings = {\n duration: number;\n onStart?: (transition: Transition) => void;\n onUpdate?: (transition: Transition) => void;\n onInterrupt?: (transition: Transition) => void;\n onEnd?: (transition: Transition) => void;\n};\n\nexport default class Transition {\n private _inProgress: boolean = false;\n private _handle: number | null = null;\n private _timeline: Timeline;\n\n time: number = 0;\n // @ts-expect-error\n settings: TransitionSettings & {fromValue; toValue; duration; easing; damping; stiffness} = {\n duration: 0\n };\n\n /**\n * @params timeline {Timeline}\n */\n constructor(timeline: Timeline) {\n this._timeline = timeline;\n }\n\n /* Public API */\n get inProgress(): boolean {\n return this._inProgress;\n }\n\n /**\n * (re)start this transition.\n * @params props {object} - optional overriding props. see constructor\n */\n start(settings: TransitionSettings) {\n this.cancel();\n // @ts-expect-error\n this.settings = settings;\n this._inProgress = true;\n this.settings.onStart?.(this);\n }\n\n /**\n * end this transition if it is in progress.\n */\n end() {\n if (this._inProgress) {\n this._timeline.removeChannel(this._handle as number);\n this._handle = null;\n this._inProgress = false;\n this.settings.onEnd?.(this);\n }\n }\n\n /**\n * cancel this transition if it is in progress.\n */\n cancel() {\n if (this._inProgress) {\n this.settings.onInterrupt?.(this);\n this._timeline.removeChannel(this._handle as number);\n this._handle = null;\n this._inProgress = false;\n }\n }\n\n /**\n * update this transition. Returns `true` if updated.\n */\n update() {\n if (!this._inProgress) {\n return false;\n }\n\n // It is important to initialize the handle during `update` instead of `start`.\n // The CPU time that the `start` frame takes should not be counted towards the duration.\n // On the other hand, `update` always happens during a render cycle. The clock starts when the\n // transition is rendered for the first time.\n if (this._handle === null) {\n const {_timeline: timeline, settings} = this;\n this._handle = timeline.addChannel({\n delay: timeline.getTime(),\n duration: settings.duration\n });\n }\n\n this.time = this._timeline.getTime(this._handle);\n // Call subclass method\n this._onUpdate();\n // Call user callback\n this.settings.onUpdate?.(this);\n\n // This only works if `settings.duration` is set\n // Spring transition must call `end` manually\n if (this._timeline.isFinished(this._handle)) {\n this.end();\n }\n return true;\n }\n\n /* Private API */\n\n protected _onUpdate() {\n // for subclass override\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport Transition, {TransitionSettings as BaseTransitionSettings} from '../transitions/transition';\nimport TransitionInterpolator from '../transitions/transition-interpolator';\nimport type {IViewState} from './view-state';\n\nimport type {Timeline} from '@luma.gl/engine';\nimport type {InteractionState} from './controller';\n\nconst noop = () => {};\n\n// Enums cannot be directly exported as they are not transpiled correctly into ES5, see https://github.com/visgl/deck.gl/issues/7130\nexport const TRANSITION_EVENTS = {\n BREAK: 1,\n SNAP_TO_END: 2,\n IGNORE: 3\n} as const;\n\ntype TransitionEvent = 1 | 2 | 3;\n\nexport type TransitionProps = {\n /** Transition duration in milliseconds, default value 0, implies no transition. When using `FlyToInterpolator`, it can also be set to `'auto'`. */\n transitionDuration?: number | 'auto';\n /** An interpolator object that defines the transition behavior between two viewports. */\n transitionInterpolator?: TransitionInterpolator;\n /** Easing function that can be used to achieve effects like \"Ease-In-Cubic\", \"Ease-Out-Cubic\", etc. Default value performs Linear easing. */\n transitionEasing?: (t: number) => number;\n /** Controls how to process a new view state change that occurs during an existing transition. */\n transitionInterruption?: TransitionEvent;\n /** Callback fired when requested transition starts. */\n onTransitionStart?: (transition: Transition) => void;\n /** Callback fired when requested transition is interrupted. */\n onTransitionInterrupt?: (transition: Transition) => void;\n /** Callback fired when requested transition ends. */\n onTransitionEnd?: (transition: Transition) => void;\n};\n\nconst DEFAULT_EASING = t => t;\nconst DEFAULT_INTERRUPTION = TRANSITION_EVENTS.BREAK;\n\ntype TransitionSettings = BaseTransitionSettings & {\n interpolator: TransitionInterpolator;\n easing: (t: number) => number;\n interruption: TransitionEvent;\n startProps: Record;\n endProps: Record;\n};\n\nexport default class TransitionManager> {\n getControllerState: (props: any) => ControllerState;\n props?: TransitionProps;\n propsInTransition: Record | null;\n transition: Transition;\n onViewStateChange: (params: {\n viewState: Record;\n oldViewState: Record;\n }) => void;\n onStateChange: (state: InteractionState) => void;\n\n constructor(opts: {\n timeline: Timeline;\n getControllerState: (props: any) => ControllerState;\n onViewStateChange?: (params: {\n viewState: Record;\n oldViewState: Record;\n }) => void;\n onStateChange?: (state: InteractionState) => void;\n }) {\n this.getControllerState = opts.getControllerState;\n this.propsInTransition = null;\n this.transition = new Transition(opts.timeline);\n\n this.onViewStateChange = opts.onViewStateChange || noop;\n this.onStateChange = opts.onStateChange || noop;\n }\n\n finalize(): void {\n this.transition.cancel();\n }\n\n // Returns current transitioned viewport.\n getViewportInTransition(): Record | null {\n return this.propsInTransition;\n }\n\n // Process the vewiport change, either ignore or trigger a new transition.\n // Return true if a new transition is triggered, false otherwise.\n processViewStateChange(nextProps: TransitionProps) {\n let transitionTriggered = false;\n const currentProps = this.props;\n // Set this.props here as '_triggerTransition' calls '_updateViewport' that uses this.props.\n this.props = nextProps;\n\n // NOTE: Be cautious re-ordering statements in this function.\n if (!currentProps || this._shouldIgnoreViewportChange(currentProps, nextProps)) {\n return false;\n }\n\n if (this._isTransitionEnabled(nextProps)) {\n let startProps = currentProps;\n if (this.transition.inProgress) {\n // @ts-expect-error\n const {interruption, endProps} = this.transition.settings as TransitionSettings;\n startProps = {\n ...currentProps,\n ...(interruption === TRANSITION_EVENTS.SNAP_TO_END\n ? endProps\n : this.propsInTransition || currentProps)\n };\n }\n\n this._triggerTransition(startProps, nextProps);\n\n transitionTriggered = true;\n } else {\n this.transition.cancel();\n }\n\n return transitionTriggered;\n }\n\n updateTransition() {\n this.transition.update();\n }\n\n // Helper methods\n\n _isTransitionEnabled(props: TransitionProps): boolean {\n const {transitionDuration, transitionInterpolator} = props;\n return (\n ((transitionDuration as number) > 0 || transitionDuration === 'auto') &&\n Boolean(transitionInterpolator)\n );\n }\n\n _isUpdateDueToCurrentTransition(props: TransitionProps): boolean {\n if (this.transition.inProgress && this.propsInTransition) {\n // @ts-expect-error\n return (this.transition.settings as TransitionSettings).interpolator.arePropsEqual(\n props,\n this.propsInTransition\n );\n }\n return false;\n }\n\n _shouldIgnoreViewportChange(currentProps: TransitionProps, nextProps: TransitionProps): boolean {\n if (this.transition.inProgress) {\n // @ts-expect-error\n const transitionSettings = this.transition.settings as TransitionSettings;\n // Ignore update if it is requested to be ignored\n return (\n transitionSettings.interruption === TRANSITION_EVENTS.IGNORE ||\n // Ignore update if it is due to current active transition.\n this._isUpdateDueToCurrentTransition(nextProps)\n );\n }\n if (this._isTransitionEnabled(nextProps)) {\n // Ignore if none of the viewport props changed.\n return (nextProps.transitionInterpolator as TransitionInterpolator).arePropsEqual(\n currentProps,\n nextProps\n );\n }\n return true;\n }\n\n _triggerTransition(startProps: TransitionProps, endProps: TransitionProps): void {\n const startViewstate = this.getControllerState(startProps);\n const endViewStateProps = this.getControllerState(endProps).shortestPathFrom(startViewstate);\n\n // update transitionDuration for 'auto' mode\n const transitionInterpolator = endProps.transitionInterpolator as TransitionInterpolator;\n const duration = transitionInterpolator.getDuration\n ? transitionInterpolator.getDuration(startProps, endProps)\n : (endProps.transitionDuration as number);\n\n if (duration === 0) {\n return;\n }\n\n const initialProps = transitionInterpolator.initializeProps(startProps, endViewStateProps);\n\n this.propsInTransition = {};\n const transitionSettings: TransitionSettings = {\n duration,\n easing: endProps.transitionEasing || DEFAULT_EASING,\n interpolator: transitionInterpolator,\n interruption: endProps.transitionInterruption || DEFAULT_INTERRUPTION,\n\n startProps: initialProps.start,\n endProps: initialProps.end,\n\n onStart: endProps.onTransitionStart,\n onUpdate: this._onTransitionUpdate,\n onInterrupt: this._onTransitionEnd(endProps.onTransitionInterrupt),\n onEnd: this._onTransitionEnd(endProps.onTransitionEnd)\n };\n this.transition.start(transitionSettings);\n\n this.onStateChange({inTransition: true});\n\n this.updateTransition();\n }\n\n _onTransitionEnd(callback?: (transition: Transition) => void) {\n return transition => {\n this.propsInTransition = null;\n\n this.onStateChange({\n inTransition: false,\n isZooming: false,\n isPanning: false,\n isRotating: false\n });\n\n callback?.(transition);\n };\n }\n\n _onTransitionUpdate = transition => {\n // NOTE: Be cautious re-ordering statements in this function.\n const {\n time,\n settings: {interpolator, startProps, endProps, duration, easing}\n } = transition;\n const t = easing(time / duration);\n const viewport = interpolator.interpolateProps(startProps, endProps, t);\n\n // This gurantees all props (e.g. bearing, longitude) are normalized\n // So when viewports are compared they are in same range.\n this.propsInTransition = this.getControllerState({\n ...this.props,\n ...viewport\n }).getViewportProps();\n\n this.onViewStateChange({\n viewState: this.propsInTransition,\n oldViewState: this.props as TransitionProps\n });\n };\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// Replacement for the external assert method to reduce bundle size\n// Note: We don't use the second \"message\" argument in calling code,\n// so no need to support it here\nexport default function assert(condition: any, message?: string): asserts condition {\n if (!condition) {\n throw new Error(message || 'deck.gl: assertion failed.');\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {equals} from '@math.gl/core';\nimport assert from '../utils/assert';\n\nexport default abstract class TransitionInterpolator {\n protected _propsToCompare: string[];\n protected _propsToExtract: string[];\n protected _requiredProps?: string[];\n\n /**\n * @param opts {array|object}\n * @param opts.compare {array} - prop names used in equality check\n * @param opts.extract {array} - prop names needed for interpolation\n * @param opts.required {array} - prop names that must be supplied\n * alternatively, supply one list of prop names as `opts` if all of the above are the same.\n */\n constructor(opts: {compare: string[]; extract?: string[]; required?: string[]}) {\n const {compare, extract, required} = opts;\n\n this._propsToCompare = compare;\n this._propsToExtract = extract || compare;\n this._requiredProps = required;\n }\n\n /**\n * Checks if two sets of props need transition in between\n * @param currentProps {object} - a list of viewport props\n * @param nextProps {object} - a list of viewport props\n * @returns {bool} - true if two props are equivalent\n */\n arePropsEqual(currentProps: Record, nextProps: Record): boolean {\n for (const key of this._propsToCompare) {\n if (\n !(key in currentProps) ||\n !(key in nextProps) ||\n !equals(currentProps[key], nextProps[key])\n ) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Called before transition starts to validate/pre-process start and end props\n * @param startProps {object} - a list of starting viewport props\n * @param endProps {object} - a list of target viewport props\n * @returns {Object} {start, end} - start and end props to be passed\n * to `interpolateProps`\n */\n initializeProps(\n startProps: Record,\n endProps: Record\n ): {\n start: Record;\n end: Record;\n } {\n const startViewStateProps = {};\n const endViewStateProps = {};\n\n for (const key of this._propsToExtract) {\n if (key in startProps || key in endProps) {\n startViewStateProps[key] = startProps[key];\n endViewStateProps[key] = endProps[key];\n }\n }\n\n this._checkRequiredProps(startViewStateProps);\n this._checkRequiredProps(endViewStateProps);\n\n return {start: startViewStateProps, end: endViewStateProps};\n }\n\n /**\n * Returns viewport props in transition\n * @param startProps {object} - a list of starting viewport props\n * @param endProps {object} - a list of target viewport props\n * @param t {number} - a time factor between [0, 1]\n * @returns {object} - a list of interpolated viewport props\n */\n abstract interpolateProps(\n startProps: Record,\n endProps: Record,\n t: number\n ): Record;\n\n /**\n * Returns transition duration\n * @param startProps {object} - a list of starting viewport props\n * @param endProps {object} - a list of target viewport props\n * @returns {Number} - transition duration in milliseconds\n */\n getDuration(startProps: Record, endProps: Record): number {\n return endProps.transitionDuration;\n }\n\n _checkRequiredProps(props) {\n if (!this._requiredProps) {\n return;\n }\n\n this._requiredProps.forEach(propName => {\n const value = props[propName];\n assert(\n Number.isFinite(value) || Array.isArray(value),\n `${propName} is required for transition`\n );\n });\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Matrix4} from '@math.gl/core';\nimport Viewport from './viewport';\nimport {PROJECTION_MODE} from '../lib/constants';\nimport {altitudeToFovy, fovyToAltitude} from '@math.gl/web-mercator';\nimport {MAX_LATITUDE} from '@math.gl/web-mercator';\n\nimport {vec3, vec4} from '@math.gl/core';\n\nconst DEGREES_TO_RADIANS = Math.PI / 180;\nconst RADIANS_TO_DEGREES = 180 / Math.PI;\nconst EARTH_RADIUS = 6370972;\nexport const GLOBE_RADIUS = 256;\n\nfunction getDistanceScales() {\n const unitsPerMeter = GLOBE_RADIUS / EARTH_RADIUS;\n const unitsPerDegree = (Math.PI / 180) * GLOBE_RADIUS;\n\n return {\n unitsPerMeter: [unitsPerMeter, unitsPerMeter, unitsPerMeter],\n unitsPerMeter2: [0, 0, 0],\n metersPerUnit: [1 / unitsPerMeter, 1 / unitsPerMeter, 1 / unitsPerMeter],\n unitsPerDegree: [unitsPerDegree, unitsPerDegree, unitsPerMeter],\n unitsPerDegree2: [0, 0, 0],\n degreesPerUnit: [1 / unitsPerDegree, 1 / unitsPerDegree, 1 / unitsPerMeter]\n };\n}\n\nexport type GlobeViewportOptions = {\n /** Name of the viewport */\n id?: string;\n /** Left offset from the canvas edge, in pixels */\n x?: number;\n /** Top offset from the canvas edge, in pixels */\n y?: number;\n /** Viewport width in pixels */\n width?: number;\n /** Viewport height in pixels */\n height?: number;\n /** Longitude in degrees */\n longitude?: number;\n /** Latitude in degrees */\n latitude?: number;\n /** Camera altitude relative to the viewport height, used to control the FOV. Default `1.5` */\n altitude?: number;\n /* Meter offsets of the viewport center from lng, lat, elevation */\n position?: number[];\n /** Zoom level */\n zoom?: number;\n /** Use orthographic projection */\n orthographic?: boolean;\n /** Camera fovy in degrees. If provided, overrides `altitude` */\n fovy?: number;\n /** Scaler for the near plane, 1 unit equals to the height of the viewport. Default `0.5` */\n nearZMultiplier?: number;\n /** Scaler for the far plane, 1 unit equals to the distance from the camera to the edge of the screen. Default `1` */\n farZMultiplier?: number;\n /** Optionally override the near plane position. `nearZMultiplier` is ignored if `nearZ` is supplied. */\n nearZ?: number;\n /** Optionally override the far plane position. `farZMultiplier` is ignored if `farZ` is supplied. */\n farZ?: number;\n /** The resolution at which to turn flat features into 3D meshes, in degrees. Smaller numbers will generate more detailed mesh. Default `10` */\n resolution?: number;\n};\n\nexport default class GlobeViewport extends Viewport {\n static displayName = 'GlobeViewport';\n\n longitude: number;\n latitude: number;\n fovy: number;\n resolution: number;\n\n constructor(opts: GlobeViewportOptions = {}) {\n const {\n longitude = 0,\n zoom = 0,\n // Matches Maplibre defaults\n // https://github.com/maplibre/maplibre-gl-js/blob/f8ab4b48d59ab8fe7b068b102538793bbdd4c848/src/geo/projection/globe_transform.ts#L632-L633\n nearZMultiplier = 0.5,\n farZMultiplier = 1,\n resolution = 10\n } = opts;\n\n let {latitude = 0, height, altitude = 1.5, fovy} = opts;\n\n // Clamp to web mercator limit to prevent bad inputs\n latitude = Math.max(Math.min(latitude, MAX_LATITUDE), -MAX_LATITUDE);\n\n height = height || 1;\n if (fovy) {\n altitude = fovyToAltitude(fovy);\n } else {\n fovy = altitudeToFovy(altitude);\n }\n // Exagerate distance by latitude to match the Web Mercator distortion\n // The goal is that globe and web mercator projection results converge at high zoom\n // https://github.com/maplibre/maplibre-gl-js/blob/f8ab4b48d59ab8fe7b068b102538793bbdd4c848/src/geo/projection/globe_transform.ts#L575-L577\n const scale = Math.pow(2, zoom - zoomAdjust(latitude));\n const nearZ = opts.nearZ ?? nearZMultiplier;\n const farZ = opts.farZ ?? (altitude + (GLOBE_RADIUS * 2 * scale) / height) * farZMultiplier;\n\n // Calculate view matrix\n const viewMatrix = new Matrix4().lookAt({eye: [0, -altitude, 0], up: [0, 0, 1]});\n viewMatrix.rotateX(latitude * DEGREES_TO_RADIANS);\n viewMatrix.rotateZ(-longitude * DEGREES_TO_RADIANS);\n viewMatrix.scale(scale / height);\n\n super({\n ...opts,\n // x, y, width,\n height,\n\n // view matrix\n viewMatrix,\n longitude,\n latitude,\n zoom,\n\n // projection matrix parameters\n distanceScales: getDistanceScales(),\n fovy,\n focalDistance: altitude,\n near: nearZ,\n far: farZ\n });\n\n this.scale = scale;\n this.latitude = latitude;\n this.longitude = longitude;\n this.fovy = fovy;\n this.resolution = resolution;\n }\n\n get projectionMode() {\n return PROJECTION_MODE.GLOBE;\n }\n\n getDistanceScales() {\n return this.distanceScales;\n }\n\n getBounds(options: {z?: number} = {}): [number, number, number, number] {\n const unprojectOption = {targetZ: options.z || 0};\n\n const left = this.unproject([0, this.height / 2], unprojectOption);\n const top = this.unproject([this.width / 2, 0], unprojectOption);\n const right = this.unproject([this.width, this.height / 2], unprojectOption);\n const bottom = this.unproject([this.width / 2, this.height], unprojectOption);\n\n if (right[0] < this.longitude) right[0] += 360;\n if (left[0] > this.longitude) left[0] -= 360;\n\n return [\n Math.min(left[0], right[0], top[0], bottom[0]),\n Math.min(left[1], right[1], top[1], bottom[1]),\n Math.max(left[0], right[0], top[0], bottom[0]),\n Math.max(left[1], right[1], top[1], bottom[1])\n ];\n }\n\n unproject(\n xyz: number[],\n {topLeft = true, targetZ}: {topLeft?: boolean; targetZ?: number} = {}\n ): number[] {\n const [x, y, z] = xyz;\n\n const y2 = topLeft ? y : this.height - y;\n const {pixelUnprojectionMatrix} = this;\n\n let coord;\n if (Number.isFinite(z)) {\n // Has depth component\n coord = transformVector(pixelUnprojectionMatrix, [x, y2, z, 1]);\n } else {\n // since we don't know the correct projected z value for the point,\n // unproject two points to get a line and then find the point on that line that intersects with the sphere\n const coord0 = transformVector(pixelUnprojectionMatrix, [x, y2, -1, 1]);\n const coord1 = transformVector(pixelUnprojectionMatrix, [x, y2, 1, 1]);\n\n const lt = ((targetZ || 0) / EARTH_RADIUS + 1) * GLOBE_RADIUS;\n const lSqr = vec3.sqrLen(vec3.sub([], coord0, coord1));\n const l0Sqr = vec3.sqrLen(coord0);\n const l1Sqr = vec3.sqrLen(coord1);\n const sSqr = (4 * l0Sqr * l1Sqr - (lSqr - l0Sqr - l1Sqr) ** 2) / 16;\n const dSqr = (4 * sSqr) / lSqr;\n const r0 = Math.sqrt(l0Sqr - dSqr);\n const dr = Math.sqrt(Math.max(0, lt * lt - dSqr));\n const t = (r0 - dr) / Math.sqrt(lSqr);\n\n coord = vec3.lerp([], coord0, coord1, t);\n }\n const [X, Y, Z] = this.unprojectPosition(coord);\n\n if (Number.isFinite(z)) {\n return [X, Y, Z];\n }\n return Number.isFinite(targetZ) ? [X, Y, targetZ as number] : [X, Y];\n }\n\n projectPosition(xyz: number[]): [number, number, number] {\n const [lng, lat, Z = 0] = xyz;\n const lambda = lng * DEGREES_TO_RADIANS;\n const phi = lat * DEGREES_TO_RADIANS;\n const cosPhi = Math.cos(phi);\n const D = (Z / EARTH_RADIUS + 1) * GLOBE_RADIUS;\n\n return [Math.sin(lambda) * cosPhi * D, -Math.cos(lambda) * cosPhi * D, Math.sin(phi) * D];\n }\n\n unprojectPosition(xyz: number[]): [number, number, number] {\n const [x, y, z] = xyz;\n const D = vec3.len(xyz);\n const phi = Math.asin(z / D);\n const lambda = Math.atan2(x, -y);\n\n const lng = lambda * RADIANS_TO_DEGREES;\n const lat = phi * RADIANS_TO_DEGREES;\n const Z = (D / GLOBE_RADIUS - 1) * EARTH_RADIUS;\n return [lng, lat, Z];\n }\n\n projectFlat(xyz: number[]): [number, number] {\n return xyz as [number, number];\n }\n\n unprojectFlat(xyz: number[]): [number, number] {\n return xyz as [number, number];\n }\n\n /**\n * Pan the globe using delta-based movement\n * @param coords - the geographic coordinates where the pan started\n * @param pixel - the current screen position\n * @param startPixel - the screen position where the pan started\n * @returns updated viewport options with new longitude/latitude\n */\n panByPosition(\n [startLng, startLat, startZoom]: number[],\n pixel: number[],\n startPixel: number[]\n ): GlobeViewportOptions {\n // Scale rotation speed inversely with zoom, to approximate constant panning speed\n const scale = Math.pow(2, this.zoom - zoomAdjust(this.latitude));\n const rotationSpeed = 0.25 / scale;\n\n const longitude = startLng + rotationSpeed * (startPixel[0] - pixel[0]);\n let latitude = startLat - rotationSpeed * (startPixel[1] - pixel[1]);\n latitude = Math.max(Math.min(latitude, MAX_LATITUDE), -MAX_LATITUDE);\n const out = {longitude, latitude, zoom: startZoom - zoomAdjust(startLat)};\n out.zoom += zoomAdjust(out.latitude);\n return out;\n }\n}\n\nexport function zoomAdjust(latitude: number): number {\n const scaleAdjust = Math.PI * Math.cos((latitude * Math.PI) / 180);\n return Math.log2(scaleAdjust);\n}\n\nfunction transformVector(matrix: number[], vector: number[]): number[] {\n const result = vec4.transformMat4([], vector, matrix);\n vec4.scale(result, result, 1 / result[3]);\n return result;\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport TransitionInterpolator from './transition-interpolator';\nimport {lerp} from '@math.gl/core';\n\nimport log from '../utils/log';\nimport type Viewport from '../viewports/viewport';\nimport GlobeViewport from '../viewports/globe-viewport';\n\nconst DEFAULT_PROPS = ['longitude', 'latitude', 'zoom', 'bearing', 'pitch'];\nconst DEFAULT_REQUIRED_PROPS = ['longitude', 'latitude', 'zoom'];\n\ntype PropsWithAnchor = {\n around?: number[];\n aroundPosition?: number[];\n [key: string]: any;\n};\n\n/**\n * Performs linear interpolation of two view states.\n */\nexport default class LinearInterpolator extends TransitionInterpolator {\n opts: {\n around?: number[];\n makeViewport?: (props: Record) => Viewport;\n };\n\n /**\n * @param {Object} opts\n * @param {Array} opts.transitionProps - list of props to apply linear transition to.\n * @param {Array} opts.around - a screen point to zoom/rotate around.\n * @param {Function} opts.makeViewport - construct a viewport instance with given props.\n */\n constructor(\n opts:\n | string[]\n | {\n transitionProps?:\n | string[]\n | {\n compare: string[];\n extract?: string[];\n required?: string[];\n };\n around?: number[];\n makeViewport?: (props: Record) => Viewport;\n } = {}\n ) {\n // Backward compatibility\n const transitionProps = Array.isArray(opts) ? opts : opts.transitionProps;\n\n const normalizedOpts = Array.isArray(opts) ? {} : opts;\n normalizedOpts.transitionProps = Array.isArray(transitionProps)\n ? {\n compare: transitionProps,\n required: transitionProps\n }\n : transitionProps || {\n compare: DEFAULT_PROPS,\n required: DEFAULT_REQUIRED_PROPS\n };\n\n super(normalizedOpts.transitionProps);\n this.opts = normalizedOpts;\n }\n\n initializeProps(\n startProps: Record,\n endProps: Record\n ): {\n start: PropsWithAnchor;\n end: PropsWithAnchor;\n } {\n const result = super.initializeProps(startProps, endProps);\n\n const {makeViewport, around} = this.opts;\n\n if (makeViewport && around) {\n const TestViewport = makeViewport(startProps);\n if (TestViewport instanceof GlobeViewport) {\n log.warn('around not supported in GlobeView')();\n } else {\n const startViewport = makeViewport(startProps);\n const endViewport = makeViewport(endProps);\n const aroundPosition = startViewport.unproject(around);\n result.start.around = around;\n Object.assign(result.end, {\n around: endViewport.project(aroundPosition),\n aroundPosition,\n width: endProps.width,\n height: endProps.height\n });\n }\n }\n\n return result;\n }\n\n interpolateProps(\n startProps: PropsWithAnchor,\n endProps: PropsWithAnchor,\n t: number\n ): Record {\n const propsInTransition = {};\n for (const key of this._propsToExtract) {\n propsInTransition[key] = lerp(startProps[key] || 0, endProps[key] || 0, t);\n }\n\n if (endProps.aroundPosition && this.opts.makeViewport) {\n // Linear transition should be performed in common space\n const viewport = this.opts.makeViewport({...endProps, ...propsInTransition});\n Object.assign(\n propsInTransition,\n viewport.panByPosition(\n endProps.aroundPosition,\n // anchor point in current screen coordinates\n lerp(startProps.around as number[], endProps.around as number[], t) as number[]\n )\n );\n }\n return propsInTransition;\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/* eslint-disable max-statements, complexity */\nimport TransitionManager, {TransitionProps} from './transition-manager';\nimport LinearInterpolator from '../transitions/linear-interpolator';\nimport {IViewState} from './view-state';\nimport {ConstructorOf} from '../types/types';\nimport {deepEqual} from '../utils/deep-equal';\n\nimport type Viewport from '../viewports/viewport';\n\nimport type {EventManager, MjolnirEvent, MjolnirGestureEvent, MjolnirWheelEvent, MjolnirKeyEvent} from 'mjolnir.js';\nimport type {Timeline} from '@luma.gl/engine';\n\nconst NO_TRANSITION_PROPS = {\n transitionDuration: 0\n} as const;\n\nconst DEFAULT_INERTIA = 300;\nconst INERTIA_EASING = t => 1 - (1 - t) * (1 - t);\n\nconst EVENT_TYPES = {\n WHEEL: ['wheel'],\n PAN: ['panstart', 'panmove', 'panend'],\n PINCH: ['pinchstart', 'pinchmove', 'pinchend'],\n MULTI_PAN: ['multipanstart', 'multipanmove', 'multipanend'],\n DOUBLE_CLICK: ['dblclick'],\n KEYBOARD: ['keydown']\n} as const;\n\n/** Configuration of how user input is handled */\nexport type ControllerOptions = {\n /** Enable zooming with mouse wheel. Default `true`. */\n scrollZoom?: boolean | {\n /** Scaler that translates wheel delta to the change of viewport scale. Default `0.01`. */\n speed?: number;\n /** Smoothly transition to the new zoom. If enabled, will provide a slightly lagged but smoother experience. Default `false`. */\n smooth?: boolean\n };\n /** Enable panning with pointer drag. Default `true` */\n dragPan?: boolean;\n /** Enable rotating with pointer drag. Default `true` */\n dragRotate?: boolean;\n /** Enable zooming with double click. Default `true` */\n doubleClickZoom?: boolean;\n /** Enable zooming with multi-touch. Default `true` */\n touchZoom?: boolean;\n /** Enable rotating with multi-touch. Use two-finger rotating gesture for horizontal and three-finger swiping gesture for vertical rotation. Default `false` */\n touchRotate?: boolean;\n /** Enable interaction with keyboard. Default `true`. */\n keyboard?:\n | boolean\n | {\n /** Speed of zoom using +/- keys. Default `2` */\n zoomSpeed?: number;\n /** Speed of movement using arrow keys, in pixels. */\n moveSpeed?: number;\n /** Speed of rotation using shift + left/right arrow keys, in degrees. Default 15. */\n rotateSpeedX?: number;\n /** Speed of rotation using shift + up/down arrow keys, in degrees. Default 10. */\n rotateSpeedY?: number;\n };\n /** Drag behavior without pressing function keys, one of `pan` and `rotate`. */\n dragMode?: 'pan' | 'rotate';\n /** Enable inertia after panning/pinching. If a number is provided, indicates the duration of time over which the velocity reduces to zero, in milliseconds. Default `false`. */\n inertia?: boolean | number;\n /** Bounding box of content that the controller is constrained in */\n maxBounds?: [min: [number, number], max: [number, number]] | [min: [number, number, number], max: [number, number, number]] | null;\n};\n\nexport type ControllerProps = {\n /** Identifier of the controller */\n id: string;\n /** Viewport x position */\n x: number;\n /** Viewport y position */\n y: number;\n /** Viewport width */\n width: number;\n /** Viewport height */\n height: number;\n} & ControllerOptions & TransitionProps;\n\n/** The state of a controller */\nexport type InteractionState = {\n /** If the view state is in transition */\n inTransition?: boolean;\n /** If the user is dragging */\n isDragging?: boolean;\n /** If the view is being panned, either from user input or transition */\n isPanning?: boolean;\n /** If the view is being rotated, either from user input or transition */\n isRotating?: boolean;\n /** If the view is being zoomed, either from user input or transition */\n isZooming?: boolean;\n /** World coordinate [lng, lat, altitude] of rotation pivot point when rotating */\n rotationPivotPosition?: [number, number, number];\n}\n\n/** Parameters passed to the onViewStateChange callback */\nexport type ViewStateChangeParameters = {\n viewId: string;\n /** The next view state, either from user input or transition */\n viewState: ViewStateT;\n /** Object describing the nature of the view state change */\n interactionState: InteractionState;\n /** The current view state */\n oldViewState?: ViewStateT;\n}\n\nconst pinchEventWorkaround: any = {};\n\nexport default abstract class Controller> {\n abstract get ControllerState(): ConstructorOf;\n abstract get transition(): TransitionProps;\n\n // @ts-expect-error (2564) - not assigned in the constructor\n protected props: ControllerProps;\n protected state: Record = {};\n\n protected transitionManager: TransitionManager;\n protected eventManager: EventManager;\n protected onViewStateChange: (params: ViewStateChangeParameters) => void;\n protected onStateChange: (state: InteractionState) => void;\n protected makeViewport: (opts: Record) => Viewport;\n protected pickPosition?: (x: number, y: number) => {coordinate?: number[]} | null;\n\n private _controllerState?: ControllerState;\n private _events: Record = {};\n private _interactionState: InteractionState = {\n isDragging: false\n };\n private _customEvents: string[] = [];\n private _eventStartBlocked: any = null;\n private _panMove: boolean = false;\n\n protected invertPan: boolean = false;\n protected dragMode: 'pan' | 'rotate' = 'rotate';\n protected inertia: number = 0;\n protected scrollZoom: boolean | {speed?: number; smooth?: boolean} = true;\n protected dragPan: boolean = true;\n protected dragRotate: boolean = true;\n protected doubleClickZoom: boolean = true;\n protected touchZoom: boolean = true;\n protected touchRotate: boolean = false;\n protected keyboard:\n | boolean\n | {\n zoomSpeed?: number; // speed of zoom using +/- keys. Default 2.\n moveSpeed?: number; // speed of movement using arrow keys, in pixels.\n rotateSpeedX?: number; // speed of rotation using shift + left/right arrow keys, in degrees. Default 15.\n rotateSpeedY?: number; // speed of rotation using shift + up/down arrow keys, in degrees. Default 10.\n } = true;\n\n constructor(opts: {\n timeline: Timeline,\n eventManager: EventManager;\n makeViewport: (opts: Record) => Viewport;\n onViewStateChange: (params: ViewStateChangeParameters) => void;\n onStateChange: (state: InteractionState) => void;\n pickPosition?: (x: number, y: number) => {coordinate?: number[]} | null;\n }) {\n this.transitionManager = new TransitionManager({\n ...opts,\n getControllerState: props => new this.ControllerState(props),\n onViewStateChange: this._onTransition.bind(this),\n onStateChange: this._setInteractionState.bind(this)\n });\n\n this.handleEvent = this.handleEvent.bind(this);\n\n this.eventManager = opts.eventManager;\n this.onViewStateChange = opts.onViewStateChange || (() => {});\n this.onStateChange = opts.onStateChange || (() => {});\n this.makeViewport = opts.makeViewport;\n this.pickPosition = opts.pickPosition;\n }\n\n set events(customEvents) {\n this.toggleEvents(this._customEvents, false);\n this.toggleEvents(customEvents, true);\n this._customEvents = customEvents;\n // Make sure default events are not overwritten\n if (this.props) {\n this.setProps(this.props);\n }\n }\n\n finalize() {\n for (const eventName in this._events) {\n if (this._events[eventName]) {\n // @ts-ignore (2345) event type string cannot be assifned to enum\n // eslint-disable-next-line @typescript-eslint/unbound-method\n this.eventManager?.off(eventName, this.handleEvent);\n }\n }\n this.transitionManager.finalize();\n }\n\n /**\n * Callback for events\n */\n handleEvent(event: MjolnirEvent) {\n // Force recalculate controller state\n this._controllerState = undefined;\n const eventStartBlocked = this._eventStartBlocked;\n\n switch (event.type) {\n case 'panstart':\n return eventStartBlocked ? false : this._onPanStart(event);\n case 'panmove':\n return this._onPan(event);\n case 'panend':\n return this._onPanEnd(event);\n case 'pinchstart':\n return eventStartBlocked ? false : this._onPinchStart(event);\n case 'pinchmove':\n return this._onPinch(event);\n case 'pinchend':\n return this._onPinchEnd(event);\n case 'multipanstart':\n return eventStartBlocked ? false : this._onMultiPanStart(event);\n case 'multipanmove':\n return this._onMultiPan(event);\n case 'multipanend':\n return this._onMultiPanEnd(event);\n case 'dblclick':\n return this._onDoubleClick(event);\n case 'wheel':\n return this._onWheel(event as MjolnirWheelEvent);\n case 'keydown':\n return this._onKeyDown(event as MjolnirKeyEvent);\n default:\n return false;\n }\n }\n\n /* Event utils */\n // Event object: http://hammerjs.github.io/api/#event-object\n get controllerState(): ControllerState {\n this._controllerState = this._controllerState || new this.ControllerState({\n makeViewport: this.makeViewport,\n ...this.props,\n ...this.state\n });\n return this._controllerState;\n }\n\n getCenter(event: MjolnirGestureEvent | MjolnirWheelEvent) : [number, number] {\n const {x, y} = this.props;\n const {offsetCenter} = event;\n return [offsetCenter.x - x, offsetCenter.y - y];\n }\n\n isPointInBounds(pos: [number, number], event: MjolnirEvent): boolean {\n const {width, height} = this.props;\n if (event && event.handled) {\n return false;\n }\n\n const inside = pos[0] >= 0 && pos[0] <= width && pos[1] >= 0 && pos[1] <= height;\n if (inside && event) {\n event.stopPropagation();\n }\n return inside;\n }\n\n isFunctionKeyPressed(event: MjolnirEvent): boolean {\n const {srcEvent} = event;\n return Boolean(srcEvent.metaKey || srcEvent.altKey || srcEvent.ctrlKey || srcEvent.shiftKey);\n }\n\n isDragging(): boolean {\n return this._interactionState.isDragging || false;\n }\n\n // When a multi-touch event ends, e.g. pinch, not all pointers are lifted at the same time.\n // This triggers a brief `pan` event.\n // Calling this method will temporarily disable *start events to avoid conflicting transitions.\n blockEvents(timeout: number): void {\n /* global setTimeout */\n const timer = setTimeout(() => {\n if (this._eventStartBlocked === timer) {\n this._eventStartBlocked = null;\n }\n }, timeout);\n this._eventStartBlocked = timer;\n }\n\n /**\n * Extract interactivity options\n */\n setProps(props: ControllerProps) {\n if (props.dragMode) {\n this.dragMode = props.dragMode;\n }\n const oldProps = this.props;\n this.props = props;\n\n if (!('transitionInterpolator' in props)) {\n // Add default transition interpolator\n props.transitionInterpolator = this._getTransitionProps().transitionInterpolator;\n }\n\n this.transitionManager.processViewStateChange(props);\n\n const {inertia} = props;\n this.inertia = Number.isFinite(inertia) ? (inertia as number) : (inertia === true ? DEFAULT_INERTIA : 0);\n\n // TODO - make sure these are not reset on every setProps\n const {\n scrollZoom = true,\n dragPan = true,\n dragRotate = true,\n doubleClickZoom = true,\n touchZoom = true,\n touchRotate = false,\n keyboard = true\n } = props;\n\n // Register/unregister events\n const isInteractive = Boolean(this.onViewStateChange);\n this.toggleEvents(EVENT_TYPES.WHEEL, isInteractive && scrollZoom);\n // We always need the pan events to set the correct isDragging state, even if dragPan & dragRotate are both false\n this.toggleEvents(EVENT_TYPES.PAN, isInteractive);\n this.toggleEvents(EVENT_TYPES.PINCH, isInteractive && (touchZoom || touchRotate));\n this.toggleEvents(EVENT_TYPES.MULTI_PAN, isInteractive && touchRotate);\n this.toggleEvents(EVENT_TYPES.DOUBLE_CLICK, isInteractive && doubleClickZoom);\n this.toggleEvents(EVENT_TYPES.KEYBOARD, isInteractive && keyboard);\n\n // Interaction toggles\n this.scrollZoom = scrollZoom;\n this.dragPan = dragPan;\n this.dragRotate = dragRotate;\n this.doubleClickZoom = doubleClickZoom;\n this.touchZoom = touchZoom;\n this.touchRotate = touchRotate;\n this.keyboard = keyboard;\n\n // Normalize view state if maxBounds is defined\n const dimensionChanged = !oldProps || oldProps.height !== props.height || oldProps.width !== props.width || oldProps.maxBounds !== props.maxBounds;\n if (dimensionChanged && props.maxBounds) {\n // Dimensions changed, try re-normalize the props\n const controllerState = new this.ControllerState({...props, makeViewport: this.makeViewport});\n const normalizedProps = controllerState.getViewportProps();\n const changed = Object.keys(normalizedProps).some(key => !deepEqual(normalizedProps[key], props[key], 1));\n if (changed) {\n // some props are updated after normalization\n this.updateViewport(controllerState);\n }\n }\n }\n\n updateTransition() {\n this.transitionManager.updateTransition();\n }\n\n toggleEvents(eventNames, enabled) {\n if (this.eventManager) {\n eventNames.forEach(eventName => {\n if (this._events[eventName] !== enabled) {\n this._events[eventName] = enabled;\n if (enabled) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n this.eventManager.on(eventName, this.handleEvent);\n } else {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n this.eventManager.off(eventName, this.handleEvent);\n }\n }\n });\n }\n }\n\n // Private Methods\n\n /* Callback util */\n // formats map state and invokes callback function\n protected updateViewport(newControllerState: ControllerState, extraProps: Record | null = null, interactionState: InteractionState = {}) {\n const viewState = {...newControllerState.getViewportProps(), ...extraProps};\n\n // TODO - to restore diffing, we need to include interactionState\n const changed = this.controllerState !== newControllerState;\n // const oldViewState = this.controllerState.getViewportProps();\n // const changed = Object.keys(viewState).some(key => oldViewState[key] !== viewState[key]);\n\n this.state = newControllerState.getState();\n this._setInteractionState(interactionState);\n\n if (changed) {\n const oldViewState = this.controllerState && this.controllerState.getViewportProps();\n if (this.onViewStateChange) {\n this.onViewStateChange({viewState, interactionState: this._interactionState, oldViewState, viewId: this.props.id});\n }\n }\n }\n\n private _onTransition(params: {viewState: Record, oldViewState: Record}) {\n this.onViewStateChange({...params, interactionState: this._interactionState, viewId: this.props.id});\n }\n\n private _setInteractionState(newStates: InteractionState) {\n Object.assign(this._interactionState, newStates);\n this.onStateChange(this._interactionState);\n }\n\n /* Event handlers */\n // Default handler for the `panstart` event.\n protected _onPanStart(event: MjolnirGestureEvent): boolean {\n const pos = this.getCenter(event);\n if (!this.isPointInBounds(pos, event)) {\n return false;\n }\n let alternateMode = this.isFunctionKeyPressed(event) || event.rightButton || false;\n if (this.invertPan || this.dragMode === 'pan') {\n // invertPan is replaced by props.dragMode, keeping for backward compatibility\n alternateMode = !alternateMode;\n }\n\n const newControllerState = this.controllerState[alternateMode ? 'panStart' : 'rotateStart']({\n pos\n });\n this._panMove = alternateMode;\n this.updateViewport(newControllerState, NO_TRANSITION_PROPS, {isDragging: true});\n return true;\n }\n\n // Default handler for the `panmove` and `panend` event.\n protected _onPan(event: MjolnirGestureEvent): boolean {\n if (!this.isDragging()) {\n return false;\n }\n return this._panMove ? this._onPanMove(event) : this._onPanRotate(event);\n }\n\n protected _onPanEnd(event: MjolnirGestureEvent): boolean {\n if (!this.isDragging()) {\n return false;\n }\n return this._panMove ? this._onPanMoveEnd(event) : this._onPanRotateEnd(event);\n }\n\n // Default handler for panning to move.\n // Called by `_onPan` when panning without function key pressed.\n protected _onPanMove(event: MjolnirGestureEvent): boolean {\n if (!this.dragPan) {\n return false;\n }\n const pos = this.getCenter(event);\n const newControllerState = this.controllerState.pan({pos});\n this.updateViewport(newControllerState, NO_TRANSITION_PROPS, {\n isDragging: true,\n isPanning: true\n });\n return true;\n }\n\n protected _onPanMoveEnd(event: MjolnirGestureEvent): boolean {\n const {inertia} = this;\n if (this.dragPan && inertia && event.velocity) {\n const pos = this.getCenter(event);\n const endPos: [number, number] = [\n pos[0] + (event.velocityX * inertia) / 2,\n pos[1] + (event.velocityY * inertia) / 2\n ];\n const newControllerState = this.controllerState.pan({pos: endPos}).panEnd();\n this.updateViewport(\n newControllerState,\n {\n ...this._getTransitionProps(),\n transitionDuration: inertia,\n transitionEasing: INERTIA_EASING\n },\n {\n isDragging: false,\n isPanning: true\n }\n );\n } else {\n const newControllerState = this.controllerState.panEnd();\n this.updateViewport(newControllerState, null, {\n isDragging: false,\n isPanning: false\n });\n }\n return true;\n }\n\n // Default handler for panning to rotate.\n // Called by `_onPan` when panning with function key pressed.\n protected _onPanRotate(event: MjolnirGestureEvent): boolean {\n if (!this.dragRotate) {\n return false;\n }\n\n const pos = this.getCenter(event);\n const newControllerState = this.controllerState.rotate({pos});\n this.updateViewport(newControllerState, NO_TRANSITION_PROPS, {\n isDragging: true,\n isRotating: true\n });\n return true;\n }\n\n protected _onPanRotateEnd(event): boolean {\n const {inertia} = this;\n if (this.dragRotate && inertia && event.velocity) {\n const pos = this.getCenter(event);\n const endPos: [number, number] = [\n pos[0] + (event.velocityX * inertia) / 2,\n pos[1] + (event.velocityY * inertia) / 2\n ];\n const newControllerState = this.controllerState.rotate({pos: endPos}).rotateEnd();\n this.updateViewport(\n newControllerState,\n {\n ...this._getTransitionProps(),\n transitionDuration: inertia,\n transitionEasing: INERTIA_EASING\n },\n {\n isDragging: false,\n isRotating: true\n }\n );\n } else {\n const newControllerState = this.controllerState.rotateEnd();\n this.updateViewport(newControllerState, null, {\n isDragging: false,\n isRotating: false\n });\n }\n return true;\n }\n\n // Default handler for the `wheel` event.\n protected _onWheel(event: MjolnirWheelEvent): boolean {\n if (!this.scrollZoom) {\n return false;\n }\n\n const pos = this.getCenter(event);\n if (!this.isPointInBounds(pos, event)) {\n return false;\n }\n event.srcEvent.preventDefault();\n\n const {speed = 0.01, smooth = false} = this.scrollZoom === true ? {} : this.scrollZoom;\n const {delta} = event;\n\n // Map wheel delta to relative scale\n let scale = 2 / (1 + Math.exp(-Math.abs(delta * speed)));\n if (delta < 0 && scale !== 0) {\n scale = 1 / scale;\n }\n\n const transitionProps = smooth\n ? {...this._getTransitionProps({around: pos}), transitionDuration: 250}\n : NO_TRANSITION_PROPS;\n\n const newControllerState = this.controllerState.zoom({pos, scale});\n this.updateViewport(\n newControllerState,\n transitionProps,\n {\n isZooming: true,\n isPanning: true\n }\n );\n\n // When there's no transition (duration = 0), immediately reset interaction state\n // since _onTransitionEnd callback won't fire\n if (!smooth) {\n this._setInteractionState({isZooming: false, isPanning: false});\n }\n return true;\n }\n\n protected _onMultiPanStart(event: MjolnirGestureEvent): boolean {\n const pos = this.getCenter(event);\n if (!this.isPointInBounds(pos, event)) {\n return false;\n }\n const newControllerState = this.controllerState.rotateStart({pos});\n this.updateViewport(newControllerState, NO_TRANSITION_PROPS, {isDragging: true});\n return true;\n }\n\n protected _onMultiPan(event: MjolnirGestureEvent): boolean {\n if (!this.touchRotate) {\n return false;\n }\n if (!this.isDragging()) {\n return false;\n }\n\n const pos = this.getCenter(event);\n pos[0] -= event.deltaX;\n\n const newControllerState = this.controllerState.rotate({pos});\n this.updateViewport(newControllerState, NO_TRANSITION_PROPS, {\n isDragging: true,\n isRotating: true\n });\n return true;\n }\n\n protected _onMultiPanEnd(event: MjolnirGestureEvent): boolean {\n if (!this.isDragging()) {\n return false;\n }\n const {inertia} = this;\n if (this.touchRotate && inertia && event.velocityY) {\n const pos = this.getCenter(event);\n const endPos: [number, number] = [pos[0], (pos[1] += (event.velocityY * inertia) / 2)];\n const newControllerState = this.controllerState.rotate({pos: endPos});\n this.updateViewport(\n newControllerState,\n {\n ...this._getTransitionProps(),\n transitionDuration: inertia,\n transitionEasing: INERTIA_EASING\n },\n {\n isDragging: false,\n isRotating: true\n }\n );\n this.blockEvents(inertia);\n } else {\n const newControllerState = this.controllerState.rotateEnd();\n this.updateViewport(newControllerState, null, {\n isDragging: false,\n isRotating: false\n });\n }\n return true;\n }\n\n // Default handler for the `pinchstart` event.\n protected _onPinchStart(event: MjolnirGestureEvent): boolean {\n const pos = this.getCenter(event);\n if (!this.isPointInBounds(pos, event)) {\n return false;\n }\n\n const newControllerState = this.controllerState.zoomStart({pos}).rotateStart({pos});\n // hack - hammer's `rotation` field doesn't seem to produce the correct angle\n pinchEventWorkaround._startPinchRotation = event.rotation;\n pinchEventWorkaround._lastPinchEvent = event;\n this.updateViewport(newControllerState, NO_TRANSITION_PROPS, {isDragging: true});\n return true;\n }\n\n // Default handler for the `pinchmove` and `pinchend` events.\n protected _onPinch(event: MjolnirGestureEvent): boolean {\n if (!this.touchZoom && !this.touchRotate) {\n return false;\n }\n if (!this.isDragging()) {\n return false;\n }\n\n let newControllerState = this.controllerState;\n if (this.touchZoom) {\n const {scale} = event;\n const pos = this.getCenter(event);\n newControllerState = newControllerState.zoom({pos, scale});\n }\n if (this.touchRotate) {\n const {rotation} = event;\n newControllerState = newControllerState.rotate({\n deltaAngleX: pinchEventWorkaround._startPinchRotation - rotation\n });\n }\n\n this.updateViewport(newControllerState, NO_TRANSITION_PROPS, {\n isDragging: true,\n isPanning: this.touchZoom,\n isZooming: this.touchZoom,\n isRotating: this.touchRotate\n });\n pinchEventWorkaround._lastPinchEvent = event;\n return true;\n }\n\n protected _onPinchEnd(event: MjolnirGestureEvent): boolean {\n if (!this.isDragging()) {\n return false;\n }\n const {inertia} = this;\n const {_lastPinchEvent} = pinchEventWorkaround;\n if (this.touchZoom && inertia && _lastPinchEvent && event.scale !== _lastPinchEvent.scale) {\n const pos = this.getCenter(event);\n let newControllerState = this.controllerState.rotateEnd();\n const z = Math.log2(event.scale);\n const velocityZ =\n (z - Math.log2(_lastPinchEvent.scale)) / (event.deltaTime - _lastPinchEvent.deltaTime);\n const endScale = Math.pow(2, z + (velocityZ * inertia) / 2);\n newControllerState = newControllerState.zoom({pos, scale: endScale}).zoomEnd();\n\n this.updateViewport(\n newControllerState,\n {\n ...this._getTransitionProps({around: pos}),\n transitionDuration: inertia,\n transitionEasing: INERTIA_EASING\n },\n {\n isDragging: false,\n isPanning: this.touchZoom,\n isZooming: this.touchZoom,\n isRotating: false\n }\n );\n this.blockEvents(inertia);\n } else {\n const newControllerState = this.controllerState.zoomEnd().rotateEnd();\n this.updateViewport(newControllerState, null, {\n isDragging: false,\n isPanning: false,\n isZooming: false,\n isRotating: false\n });\n }\n pinchEventWorkaround._startPinchRotation = null;\n pinchEventWorkaround._lastPinchEvent = null;\n return true;\n }\n\n // Default handler for the `dblclick` event.\n protected _onDoubleClick(event: MjolnirGestureEvent): boolean {\n if (!this.doubleClickZoom) {\n return false;\n }\n const pos = this.getCenter(event);\n if (!this.isPointInBounds(pos, event)) {\n return false;\n }\n\n const isZoomOut = this.isFunctionKeyPressed(event);\n\n const newControllerState = this.controllerState.zoom({pos, scale: isZoomOut ? 0.5 : 2});\n this.updateViewport(newControllerState, this._getTransitionProps({around: pos}), {\n isZooming: true,\n isPanning: true\n });\n this.blockEvents(100);\n return true;\n }\n\n // Default handler for the `keydown` event\n protected _onKeyDown(event: MjolnirKeyEvent): boolean {\n if (!this.keyboard) {\n return false;\n }\n const funcKey = this.isFunctionKeyPressed(event);\n // @ts-ignore\n const {zoomSpeed, moveSpeed, rotateSpeedX, rotateSpeedY} = this.keyboard === true ? {} : this.keyboard;\n const {controllerState} = this;\n let newControllerState;\n const interactionState: InteractionState = {};\n\n switch (event.srcEvent.code) {\n case 'Minus':\n newControllerState = funcKey\n ? controllerState.zoomOut(zoomSpeed).zoomOut(zoomSpeed)\n : controllerState.zoomOut(zoomSpeed);\n interactionState.isZooming = true;\n break;\n case 'Equal':\n newControllerState = funcKey\n ? controllerState.zoomIn(zoomSpeed).zoomIn(zoomSpeed)\n : controllerState.zoomIn(zoomSpeed);\n interactionState.isZooming = true;\n break;\n case 'ArrowLeft':\n if (funcKey) {\n newControllerState = controllerState.rotateLeft(rotateSpeedX);\n interactionState.isRotating = true;\n } else {\n newControllerState = controllerState.moveLeft(moveSpeed);\n interactionState.isPanning = true;\n }\n break;\n case 'ArrowRight':\n if (funcKey) {\n newControllerState = controllerState.rotateRight(rotateSpeedX);\n interactionState.isRotating = true;\n } else {\n newControllerState = controllerState.moveRight(moveSpeed);\n interactionState.isPanning = true;\n }\n break;\n case 'ArrowUp':\n if (funcKey) {\n newControllerState = controllerState.rotateUp(rotateSpeedY);\n interactionState.isRotating = true;\n } else {\n newControllerState = controllerState.moveUp(moveSpeed);\n interactionState.isPanning = true;\n }\n break;\n case 'ArrowDown':\n if (funcKey) {\n newControllerState = controllerState.rotateDown(rotateSpeedY);\n interactionState.isRotating = true;\n } else {\n newControllerState = controllerState.moveDown(moveSpeed);\n interactionState.isPanning = true;\n }\n break;\n default:\n return false;\n }\n this.updateViewport(newControllerState, this._getTransitionProps(), interactionState);\n return true;\n }\n\n protected _getTransitionProps(opts?: any): TransitionProps {\n const {transition} = this;\n\n if (!transition || !transition.transitionInterpolator) {\n return NO_TRANSITION_PROPS;\n }\n\n // Enables Transitions on double-tap and key-down events.\n return opts\n ? {\n ...transition,\n transitionInterpolator: new LinearInterpolator({\n ...opts,\n ...(transition.transitionInterpolator as LinearInterpolator).opts,\n makeViewport: this.controllerState.makeViewport\n })\n }\n : transition;\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type Viewport from '../viewports/viewport';\n\nexport default abstract class ViewState<\n T,\n Props extends Record,\n State extends Record\n> implements IViewState\n{\n private _viewportProps: Required;\n private _state: State;\n\n makeViewport: (props: Record) => Viewport;\n\n constructor(\n props: Required,\n state: State,\n makeViewport: (props: Record) => Viewport\n ) {\n this.makeViewport = makeViewport;\n this._viewportProps = this.applyConstraints(props);\n this._state = state;\n }\n\n getViewportProps(): Required {\n return this._viewportProps;\n }\n\n getState(): State {\n return this._state;\n }\n\n abstract applyConstraints(props: Required): Required;\n\n abstract shortestPathFrom(viewState: T): Props;\n\n abstract panStart(params: {pos: [number, number]}): T;\n abstract pan({pos, startPos}: {pos: [number, number]; startPos?: [number, number]}): T;\n abstract panEnd(): T;\n\n abstract rotateStart(params: {pos: [number, number]; altitude?: number}): T;\n abstract rotate(params: {pos?: [number, number]; deltaAngleX?: number; deltaAngleY: number}): T;\n abstract rotateEnd(): T;\n\n abstract zoomStart({pos}: {pos: [number, number]}): T;\n abstract zoom({\n pos,\n startPos,\n scale\n }: {\n pos: [number, number];\n startPos?: [number, number];\n scale: number;\n }): T;\n abstract zoomEnd(): T;\n\n abstract zoomIn(speed?: number): T;\n abstract zoomOut(speed?: number): T;\n\n abstract moveLeft(speed?: number): T;\n abstract moveRight(speed?: number): T;\n abstract moveUp(speed?: number): T;\n abstract moveDown(speed?: number): T;\n\n abstract rotateLeft(speed?: number): T;\n abstract rotateRight(speed?: number): T;\n abstract rotateUp(speed?: number): T;\n abstract rotateDown(speed?: number): T;\n}\n\nexport interface IViewState {\n makeViewport?: (props: Record) => Viewport;\n\n getViewportProps(): Record;\n\n getState(): Record;\n\n shortestPathFrom(viewState: T): Record;\n\n panStart(params: {pos: [number, number]}): T;\n pan({pos, startPos}: {pos: [number, number]; startPos?: [number, number]}): T;\n panEnd(): T;\n\n rotateStart(params: {pos: [number, number]; altitude?: number}): T;\n rotate(params: {pos?: [number, number]; deltaAngleX?: number; deltaAngleY?: number}): T;\n rotateEnd(): T;\n\n zoomStart({pos}: {pos: [number, number]}): T;\n zoom({\n pos,\n startPos,\n scale\n }: {\n pos: [number, number];\n startPos?: [number, number];\n scale: number;\n }): T;\n zoomEnd(): T;\n\n zoomIn(speed?: number): T;\n zoomOut(speed?: number): T;\n\n moveLeft(speed?: number): T;\n moveRight(speed?: number): T;\n moveUp(speed?: number): T;\n moveDown(speed?: number): T;\n\n rotateLeft(speed?: number): T;\n rotateRight(speed?: number): T;\n rotateUp(speed?: number): T;\n rotateDown(speed?: number): T;\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {clamp} from '@math.gl/core';\nimport Controller, {ControllerProps, InteractionState} from './controller';\nimport ViewState from './view-state';\nimport {worldToLngLat, lngLatToWorld as _lngLatToWorld} from '@math.gl/web-mercator';\nimport assert from '../utils/assert';\nimport {mod} from '../utils/math-utils';\n\nimport LinearInterpolator from '../transitions/linear-interpolator';\nimport type Viewport from '../viewports/viewport';\n\nconst PITCH_MOUSE_THRESHOLD = 5;\nconst PITCH_ACCEL = 1.2;\nconst WEB_MERCATOR_TILE_SIZE = 512;\nconst WEB_MERCATOR_MAX_BOUNDS = [\n [-Infinity, -90],\n [Infinity, 90]\n] satisfies ControllerProps['maxBounds'];\n\n/** The web mercator utility `lngLatToWorld` throws if invalid coordinates are provided.\n * This wrapper clamps user input to calculate common positions safely. */\nfunction lngLatToWorld([lng, lat]: number[]): number[] {\n if (Math.abs(lat) > 90) {\n lat = Math.sign(lat) * 90;\n }\n if (Number.isFinite(lng)) {\n const [x, y] = _lngLatToWorld([lng, lat]);\n return [x, clamp(y, 0, WEB_MERCATOR_TILE_SIZE)];\n }\n const [, y] = _lngLatToWorld([0, lat]);\n return [lng, clamp(y, 0, WEB_MERCATOR_TILE_SIZE)];\n}\n\nexport type MapStateProps = {\n /** Mapbox viewport properties */\n /** The width of the viewport */\n width: number;\n /** The height of the viewport */\n height: number;\n /** The latitude at the center of the viewport */\n latitude: number;\n /** The longitude at the center of the viewport */\n longitude: number;\n /** The tile zoom level of the map. */\n zoom: number;\n /** The bearing of the viewport in degrees */\n bearing?: number;\n /** The pitch of the viewport in degrees */\n pitch?: number;\n /**\n * Specify the altitude of the viewport camera\n * Unit: map heights, default 1.5\n * Non-public API, see https://github.com/mapbox/mapbox-gl-js/issues/1137\n */\n altitude?: number;\n /** Viewport position */\n position?: [number, number, number];\n\n /** Viewport constraints */\n maxZoom?: number;\n minZoom?: number;\n maxPitch?: number;\n minPitch?: number;\n\n /** Normalize viewport props to fit map height into viewport. Default `true` */\n normalize?: boolean;\n\n maxBounds?: ControllerProps['maxBounds'];\n};\n\nexport type MapStateInternal = {\n /** Interaction states, required to calculate change during transform */\n /* The point on map being grabbed when the operation first started */\n startPanLngLat?: [number, number];\n /* Center of the zoom when the operation first started */\n startZoomLngLat?: [number, number];\n /* Pointer position when rotation started */\n startRotatePos?: [number, number];\n /* The lng/lat/altitude point at the rotation pivot (where rotation started) */\n startRotateLngLat?: [number, number, number];\n /** Bearing when current perspective rotate operation started */\n startBearing?: number;\n /** Pitch when current perspective rotate operation started */\n startPitch?: number;\n /** Zoom when current zoom operation started */\n startZoom?: number;\n};\n\n/* Utils */\n\nexport class MapState extends ViewState {\n /* get optional altitude for rotation pivot\n * - undefined: rotate around viewport center (no pivot point)\n * - 0: rotate around pointer position at ground level\n * - other value: rotate around pointer position at specified altitude\n */\n getAltitude?: (pos: [number, number]) => number | undefined;\n\n constructor(\n options: MapStateProps &\n MapStateInternal & {\n makeViewport: (props: Record) => Viewport;\n getAltitude?: (pos: [number, number]) => number | undefined;\n }\n ) {\n const {\n /** Mapbox viewport properties */\n /** The width of the viewport */\n width,\n /** The height of the viewport */\n height,\n /** The latitude at the center of the viewport */\n latitude,\n /** The longitude at the center of the viewport */\n longitude,\n /** The tile zoom level of the map. */\n zoom,\n /** The bearing of the viewport in degrees */\n bearing = 0,\n /** The pitch of the viewport in degrees */\n pitch = 0,\n /**\n * Specify the altitude of the viewport camera\n * Unit: map heights, default 1.5\n * Non-public API, see https://github.com/mapbox/mapbox-gl-js/issues/1137\n */\n altitude = 1.5,\n /** Viewport position */\n position = [0, 0, 0],\n\n /** Viewport constraints */\n maxZoom = 20,\n minZoom = 0,\n maxPitch = 60,\n minPitch = 0,\n\n /** Interaction states, required to calculate change during transform */\n /* The point on map being grabbed when the operation first started */\n startPanLngLat,\n /* Center of the zoom when the operation first started */\n startZoomLngLat,\n /* Pointer position when rotation started */\n startRotatePos,\n /* The lng/lat point at the rotation pivot (where rotation started) */\n startRotateLngLat,\n /** Bearing when current perspective rotate operation started */\n startBearing,\n /** Pitch when current perspective rotate operation started */\n startPitch,\n /** Zoom when current zoom operation started */\n startZoom,\n\n /** Normalize viewport props to fit map height into viewport */\n normalize = true\n } = options;\n\n assert(Number.isFinite(longitude)); // `longitude` must be supplied\n assert(Number.isFinite(latitude)); // `latitude` must be supplied\n assert(Number.isFinite(zoom)); // `zoom` must be supplied\n\n const maxBounds = options.maxBounds || (normalize ? WEB_MERCATOR_MAX_BOUNDS : null);\n\n super(\n {\n width,\n height,\n latitude,\n longitude,\n zoom,\n bearing,\n pitch,\n altitude,\n maxZoom,\n minZoom,\n maxPitch,\n minPitch,\n normalize,\n position,\n maxBounds\n },\n {\n startPanLngLat,\n startZoomLngLat,\n startRotatePos,\n startRotateLngLat,\n startBearing,\n startPitch,\n startZoom\n },\n options.makeViewport\n );\n\n this.getAltitude = options.getAltitude;\n }\n\n /**\n * Start panning\n * @param {[Number, Number]} pos - position on screen where the pointer grabs\n */\n panStart({pos}: {pos: [number, number]}): MapState {\n return this._getUpdatedState({\n startPanLngLat: this._unproject(pos)\n });\n }\n\n /**\n * Pan\n * @param {[Number, Number]} pos - position on screen where the pointer is\n * @param {[Number, Number], optional} startPos - where the pointer grabbed at\n * the start of the operation. Must be supplied of `panStart()` was not called\n */\n pan({pos, startPos}: {pos: [number, number]; startPos?: [number, number]}): MapState {\n const startPanLngLat = this.getState().startPanLngLat || this._unproject(startPos);\n\n if (!startPanLngLat) {\n return this;\n }\n\n const viewport = this.makeViewport(this.getViewportProps());\n const newProps = viewport.panByPosition(startPanLngLat, pos);\n\n return this._getUpdatedState(newProps);\n }\n\n /**\n * End panning\n * Must call if `panStart()` was called\n */\n panEnd(): MapState {\n return this._getUpdatedState({\n startPanLngLat: null\n });\n }\n\n /**\n * Start rotating\n * @param {[Number, Number]} pos - position on screen where the center is\n */\n rotateStart({pos}: {pos: [number, number]}): MapState {\n const altitude = this.getAltitude?.(pos);\n\n return this._getUpdatedState({\n startRotatePos: pos,\n startRotateLngLat: altitude !== undefined ? this._unproject3D(pos, altitude) : undefined,\n startBearing: this.getViewportProps().bearing,\n startPitch: this.getViewportProps().pitch\n });\n }\n\n /**\n * Rotate\n * @param {[Number, Number]} pos - position on screen where the center is\n */\n rotate({\n pos,\n deltaAngleX = 0,\n deltaAngleY = 0\n }: {\n pos?: [number, number];\n deltaAngleX?: number;\n deltaAngleY?: number;\n }): MapState {\n const {startRotatePos, startRotateLngLat, startBearing, startPitch} = this.getState();\n\n if (!startRotatePos || startBearing === undefined || startPitch === undefined) {\n return this;\n }\n let newRotation;\n if (pos) {\n newRotation = this._getNewRotation(pos, startRotatePos, startPitch, startBearing);\n } else {\n newRotation = {\n bearing: startBearing + deltaAngleX,\n pitch: startPitch + deltaAngleY\n };\n }\n\n // If we have a pivot point, adjust the camera position to keep the pivot point fixed\n if (startRotateLngLat) {\n const rotatedViewport = this.makeViewport({\n ...this.getViewportProps(),\n ...newRotation\n });\n // Use panByPosition3D if available (WebMercatorViewport), otherwise fall back to panByPosition\n const panMethod = 'panByPosition3D' in rotatedViewport ? 'panByPosition3D' : 'panByPosition';\n return this._getUpdatedState({\n ...newRotation,\n ...rotatedViewport[panMethod](startRotateLngLat, startRotatePos)\n });\n }\n\n return this._getUpdatedState(newRotation);\n }\n\n /**\n * End rotating\n * Must call if `rotateStart()` was called\n */\n rotateEnd(): MapState {\n return this._getUpdatedState({\n startRotatePos: null,\n startRotateLngLat: null,\n startBearing: null,\n startPitch: null\n });\n }\n\n /**\n * Start zooming\n * @param {[Number, Number]} pos - position on screen where the center is\n */\n zoomStart({pos}: {pos: [number, number]}): MapState {\n return this._getUpdatedState({\n startZoomLngLat: this._unproject(pos),\n startZoom: this.getViewportProps().zoom\n });\n }\n\n /**\n * Zoom\n * @param {[Number, Number]} pos - position on screen where the current center is\n * @param {[Number, Number]} startPos - the center position at\n * the start of the operation. Must be supplied of `zoomStart()` was not called\n * @param {Number} scale - a number between [0, 1] specifying the accumulated\n * relative scale.\n */\n zoom({\n pos,\n startPos,\n scale\n }: {\n pos: [number, number];\n startPos?: [number, number];\n scale: number;\n }): MapState {\n // Make sure we zoom around the current mouse position rather than map center\n let {startZoom, startZoomLngLat} = this.getState();\n\n if (!startZoomLngLat) {\n // We have two modes of zoom:\n // scroll zoom that are discrete events (transform from the current zoom level),\n // and pinch zoom that are continuous events (transform from the zoom level when\n // pinch started).\n // If startZoom state is defined, then use the startZoom state;\n // otherwise assume discrete zooming\n startZoom = this.getViewportProps().zoom;\n startZoomLngLat = this._unproject(startPos) || this._unproject(pos);\n }\n if (!startZoomLngLat) {\n return this;\n }\n\n const zoom = this._constrainZoom((startZoom as number) + Math.log2(scale));\n const zoomedViewport = this.makeViewport({...this.getViewportProps(), zoom});\n\n return this._getUpdatedState({\n zoom,\n ...zoomedViewport.panByPosition(startZoomLngLat, pos)\n });\n }\n\n /**\n * End zooming\n * Must call if `zoomStart()` was called\n */\n zoomEnd(): MapState {\n return this._getUpdatedState({\n startZoomLngLat: null,\n startZoom: null\n });\n }\n\n zoomIn(speed: number = 2): MapState {\n return this._zoomFromCenter(speed);\n }\n\n zoomOut(speed: number = 2): MapState {\n return this._zoomFromCenter(1 / speed);\n }\n\n moveLeft(speed: number = 100): MapState {\n return this._panFromCenter([speed, 0]);\n }\n\n moveRight(speed: number = 100): MapState {\n return this._panFromCenter([-speed, 0]);\n }\n\n moveUp(speed: number = 100): MapState {\n return this._panFromCenter([0, speed]);\n }\n\n moveDown(speed: number = 100): MapState {\n return this._panFromCenter([0, -speed]);\n }\n\n rotateLeft(speed: number = 15): MapState {\n return this._getUpdatedState({\n bearing: this.getViewportProps().bearing - speed\n });\n }\n\n rotateRight(speed: number = 15): MapState {\n return this._getUpdatedState({\n bearing: this.getViewportProps().bearing + speed\n });\n }\n\n rotateUp(speed: number = 10): MapState {\n return this._getUpdatedState({\n pitch: this.getViewportProps().pitch + speed\n });\n }\n\n rotateDown(speed: number = 10): MapState {\n return this._getUpdatedState({\n pitch: this.getViewportProps().pitch - speed\n });\n }\n\n shortestPathFrom(viewState: MapState): MapStateProps {\n // const endViewStateProps = new this.ControllerState(endProps).shortestPathFrom(startViewstate);\n const fromProps = viewState.getViewportProps();\n const props = {...this.getViewportProps()};\n const {bearing, longitude} = props;\n\n if (Math.abs(bearing - fromProps.bearing) > 180) {\n props.bearing = bearing < 0 ? bearing + 360 : bearing - 360;\n }\n if (Math.abs(longitude - fromProps.longitude) > 180) {\n props.longitude = longitude < 0 ? longitude + 360 : longitude - 360;\n }\n return props;\n }\n\n // Apply any constraints (mathematical or defined by _viewportProps) to map state\n applyConstraints(props: Required): Required {\n // Ensure pitch is within specified range\n const {maxPitch, minPitch, pitch, longitude, bearing, normalize, maxBounds} = props;\n\n if (normalize) {\n if (longitude < -180 || longitude > 180) {\n props.longitude = mod(longitude + 180, 360) - 180;\n }\n if (bearing < -180 || bearing > 180) {\n props.bearing = mod(bearing + 180, 360) - 180;\n }\n }\n props.pitch = clamp(pitch, minPitch, maxPitch);\n\n props.zoom = this._constrainZoom(props.zoom, props);\n\n if (maxBounds) {\n const bl = lngLatToWorld(maxBounds[0]);\n const tr = lngLatToWorld(maxBounds[1]);\n // calculate center and zoom ranges at pitch=0 and bearing=0\n // to maintain visual stability when rotating\n const scale = 2 ** props.zoom;\n const halfWidth = props.width / 2 / scale;\n const halfHeight = props.height / 2 / scale;\n const [minLng, minLat] = worldToLngLat([bl[0] + halfWidth, bl[1] + halfHeight]);\n const [maxLng, maxLat] = worldToLngLat([tr[0] - halfWidth, tr[1] - halfHeight]);\n props.longitude = clamp(props.longitude, minLng, maxLng);\n props.latitude = clamp(props.latitude, minLat, maxLat);\n }\n\n return props;\n }\n\n /* Private methods */\n\n _constrainZoom(zoom: number, props?: Required): number {\n props ||= this.getViewportProps();\n const {maxZoom, maxBounds} = props;\n\n const shouldApplyMaxBounds = maxBounds !== null && props.width > 0 && props.height > 0;\n let {minZoom} = props;\n\n if (shouldApplyMaxBounds) {\n const bl = lngLatToWorld(maxBounds[0]);\n const tr = lngLatToWorld(maxBounds[1]);\n const w = tr[0] - bl[0];\n const h = tr[1] - bl[1];\n // ignore bound size of 0 or Infinity\n if (Number.isFinite(w) && w > 0) {\n minZoom = Math.max(minZoom, Math.log2(props.width / w));\n }\n if (Number.isFinite(h) && h > 0) {\n minZoom = Math.max(minZoom, Math.log2(props.height / h));\n }\n if (minZoom > maxZoom) minZoom = maxZoom;\n }\n return clamp(zoom, minZoom, maxZoom);\n }\n\n _zoomFromCenter(scale) {\n const {width, height} = this.getViewportProps();\n return this.zoom({\n pos: [width / 2, height / 2],\n scale\n });\n }\n\n _panFromCenter(offset) {\n const {width, height} = this.getViewportProps();\n return this.pan({\n startPos: [width / 2, height / 2],\n pos: [width / 2 + offset[0], height / 2 + offset[1]]\n });\n }\n\n _getUpdatedState(newProps): MapState {\n // @ts-ignore\n return new this.constructor({\n makeViewport: this.makeViewport,\n ...this.getViewportProps(),\n ...this.getState(),\n ...newProps\n });\n }\n\n _unproject(pos?: [number, number]): [number, number] | undefined {\n const viewport = this.makeViewport(this.getViewportProps());\n // @ts-ignore\n return pos && viewport.unproject(pos);\n }\n\n _unproject3D(pos: [number, number], altitude: number): [number, number, number] {\n const viewport = this.makeViewport(this.getViewportProps());\n return viewport.unproject(pos, {targetZ: altitude}) as [number, number, number];\n }\n\n _getNewRotation(\n pos: [number, number],\n startPos: [number, number],\n startPitch: number,\n startBearing: number\n ): {\n pitch: number;\n bearing: number;\n } {\n const deltaX = pos[0] - startPos[0];\n const deltaY = pos[1] - startPos[1];\n const centerY = pos[1];\n const startY = startPos[1];\n const {width, height} = this.getViewportProps();\n\n const deltaScaleX = deltaX / width;\n let deltaScaleY = 0;\n\n if (deltaY > 0) {\n if (Math.abs(height - startY) > PITCH_MOUSE_THRESHOLD) {\n // Move from 0 to -1 as we drag upwards\n deltaScaleY = (deltaY / (startY - height)) * PITCH_ACCEL;\n }\n } else if (deltaY < 0) {\n if (startY > PITCH_MOUSE_THRESHOLD) {\n // Move from 0 to 1 as we drag upwards\n deltaScaleY = 1 - centerY / startY;\n }\n }\n // clamp deltaScaleY to [-1, 1] so that rotation is constrained between minPitch and maxPitch.\n // deltaScaleX does not need to be clamped as bearing does not have constraints.\n deltaScaleY = clamp(deltaScaleY, -1, 1);\n\n const {minPitch, maxPitch} = this.getViewportProps();\n\n const bearing = startBearing + 180 * deltaScaleX;\n let pitch = startPitch;\n if (deltaScaleY > 0) {\n // Gradually increase pitch\n pitch = startPitch + deltaScaleY * (maxPitch - startPitch);\n } else if (deltaScaleY < 0) {\n // Gradually decrease pitch\n pitch = startPitch - deltaScaleY * (minPitch - startPitch);\n }\n\n return {\n pitch,\n bearing\n };\n }\n}\n\nexport default class MapController extends Controller {\n ControllerState = MapState;\n\n transition = {\n transitionDuration: 300,\n transitionInterpolator: new LinearInterpolator({\n transitionProps: {\n compare: ['longitude', 'latitude', 'zoom', 'bearing', 'pitch', 'position'],\n required: ['longitude', 'latitude', 'zoom']\n }\n })\n };\n\n dragMode: 'pan' | 'rotate' = 'pan';\n\n /**\n * Rotation pivot behavior:\n * - 'center': Rotate around viewport center (default)\n * - '2d': Rotate around pointer position at ground level (z=0)\n * - '3d': Rotate around 3D picked point (requires pickPosition callback)\n */\n protected rotationPivot: 'center' | '2d' | '3d' = 'center';\n\n setProps(\n props: ControllerProps &\n MapStateProps & {\n rotationPivot?: 'center' | '2d' | '3d';\n getAltitude?: (pos: [number, number]) => number | undefined;\n }\n ) {\n if ('rotationPivot' in props) {\n this.rotationPivot = props.rotationPivot || 'center';\n }\n // this will be passed to MapState constructor\n props.getAltitude = this._getAltitude;\n props.position = props.position || [0, 0, 0];\n props.maxBounds =\n props.maxBounds || (props.normalize === false ? null : WEB_MERCATOR_MAX_BOUNDS);\n\n super.setProps(props);\n }\n\n protected updateViewport(\n newControllerState: MapState,\n extraProps: Record | null = null,\n interactionState: InteractionState = {}\n ): void {\n // Inject rotation pivot position during rotation for visual feedback\n const state = newControllerState.getState();\n if (interactionState.isDragging && state.startRotateLngLat) {\n interactionState = {\n ...interactionState,\n rotationPivotPosition: state.startRotateLngLat\n };\n } else if (interactionState.isDragging === false) {\n // Clear pivot when drag ends\n interactionState = {...interactionState, rotationPivotPosition: undefined};\n }\n\n super.updateViewport(newControllerState, extraProps, interactionState);\n }\n\n /** Add altitude to rotateStart params based on rotationPivot mode */\n protected _getAltitude = (pos: [number, number]): number | undefined => {\n if (this.rotationPivot === '2d') {\n return 0;\n } else if (this.rotationPivot === '3d') {\n if (this.pickPosition) {\n const {x, y} = this.props;\n const pickResult = this.pickPosition(x + pos[0], y + pos[1]);\n if (pickResult && pickResult.coordinate && pickResult.coordinate.length >= 3) {\n return pickResult.coordinate[2];\n }\n }\n }\n return undefined;\n };\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport View, {CommonViewState, CommonViewProps} from './view';\nimport WebMercatorViewport from '../viewports/web-mercator-viewport';\nimport MapController from '../controllers/map-controller';\n\nimport type {NumericArray} from '../types/types';\n\nexport type MapViewState = {\n /** Longitude of the map center */\n longitude: number;\n /** Latitude of the map center */\n latitude: number;\n /** Zoom level */\n zoom: number;\n /** Pitch (tilt) of the map, in degrees. `0` looks top down */\n pitch?: number;\n /** Bearing (rotation) of the map, in degrees. `0` is north up */\n bearing?: number;\n /** Min zoom, default `0` */\n minZoom?: number;\n /** Max zoom, default `20` */\n maxZoom?: number;\n /** Min pitch, default `0` */\n minPitch?: number;\n /** Max pitch, default `60` */\n maxPitch?: number;\n /** Viewport center offsets from lng, lat in meters */\n position?: number[];\n /** The near plane position */\n nearZ?: number;\n /** The far plane position */\n farZ?: number;\n} & CommonViewState;\n\nexport type MapViewProps = {\n /** Whether to render multiple copies of the map at low zoom levels. Default `false`. */\n repeat?: boolean;\n /** Scaler for the near plane, 1 unit equals to the height of the viewport. Default to `0.1`. Overwrites the `near` parameter. */\n nearZMultiplier?: number;\n /** Scaler for the far plane, 1 unit equals to the distance from the camera to the top edge of the screen. Default to `1.01`. Overwrites the `far` parameter. */\n farZMultiplier?: number;\n /** Custom projection matrix */\n projectionMatrix?: NumericArray;\n /** Field of view covered by the camera, in the perspective case. In degrees. If not supplied, will be calculated from `altitude`. */\n fovy?: number;\n /** Distance of the camera relative to viewport height. Default `1.5`. */\n altitude?: number;\n /** Whether to create an orthographic or perspective projection matrix. Default is `false` (perspective projection). */\n orthographic?: boolean;\n} & CommonViewProps;\n\nexport default class MapView extends View {\n static displayName = 'MapView';\n\n constructor(props: MapViewProps = {}) {\n super(props);\n }\n\n getViewportType() {\n return WebMercatorViewport;\n }\n\n get ControllerType() {\n return MapController;\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {deepEqual} from '../utils/deep-equal';\nimport LightingEffect from '../effects/lighting/lighting-effect';\nimport type {Effect, EffectContext} from './effect';\n\nconst DEFAULT_LIGHTING_EFFECT = new LightingEffect();\n\n/** Sort two effects. Returns 0 if equal, negative if e1 < e2, positive if e1 > e2 */\nfunction compareEffects(e1: Effect, e2: Effect): number {\n const o1 = e1.order ?? Infinity;\n const o2 = e2.order ?? Infinity;\n return o1 - o2;\n}\n\nexport default class EffectManager {\n effects: Effect[];\n private _resolvedEffects: Effect[] = [];\n /** Effect instances and order preference pairs, sorted by order */\n private _defaultEffects: Effect[] = [];\n private _needsRedraw: false | string;\n private _context: EffectContext;\n\n constructor(context: EffectContext) {\n this.effects = [];\n this._context = context;\n this._needsRedraw = 'Initial render';\n this._setEffects([]);\n }\n\n /**\n * Register a new default effect, i.e. an effect presents regardless of user supplied props.effects\n */\n addDefaultEffect(effect: Effect) {\n const defaultEffects = this._defaultEffects;\n if (!defaultEffects.find(e => e.id === effect.id)) {\n const index = defaultEffects.findIndex(e => compareEffects(e, effect) > 0);\n if (index < 0) {\n defaultEffects.push(effect);\n } else {\n defaultEffects.splice(index, 0, effect);\n }\n effect.setup(this._context);\n this._setEffects(this.effects);\n }\n }\n\n setProps(props) {\n if ('effects' in props) {\n // Compare effects against each other shallowly\n if (!deepEqual(props.effects, this.effects, 1)) {\n this._setEffects(props.effects);\n }\n }\n }\n\n needsRedraw(opts = {clearRedrawFlags: false}): false | string {\n const redraw = this._needsRedraw;\n if (opts.clearRedrawFlags) {\n this._needsRedraw = false;\n }\n return redraw;\n }\n\n getEffects() {\n return this._resolvedEffects;\n }\n\n private _setEffects(effects: Effect[]) {\n const oldEffectsMap: Record = {};\n for (const effect of this.effects) {\n oldEffectsMap[effect.id] = effect;\n }\n\n const nextEffects: Effect[] = [];\n for (const effect of effects) {\n const oldEffect = oldEffectsMap[effect.id];\n let effectToAdd = effect;\n if (oldEffect && oldEffect !== effect) {\n if (oldEffect.setProps) {\n oldEffect.setProps(effect.props);\n effectToAdd = oldEffect;\n } else {\n oldEffect.cleanup(this._context);\n }\n } else if (!oldEffect) {\n effect.setup(this._context);\n }\n nextEffects.push(effectToAdd);\n delete oldEffectsMap[effect.id];\n }\n for (const removedEffectId in oldEffectsMap) {\n oldEffectsMap[removedEffectId].cleanup(this._context);\n }\n this.effects = nextEffects;\n\n this._resolvedEffects = nextEffects.concat(this._defaultEffects);\n // Special case for lighting: only add default instance if no LightingEffect is specified\n if (!effects.some(effect => effect instanceof LightingEffect)) {\n this._resolvedEffects.push(DEFAULT_LIGHTING_EFFECT);\n }\n this._needsRedraw = 'effects changed';\n }\n\n finalize() {\n for (const effect of this._resolvedEffects) {\n effect.cleanup(this._context);\n }\n\n this.effects.length = 0;\n this._resolvedEffects.length = 0;\n this._defaultEffects.length = 0;\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport LayersPass from './layers-pass';\nimport type {LayersPassRenderOptions, RenderStats} from './layers-pass';\n\nexport default class DrawLayersPass extends LayersPass {\n shouldDrawLayer(layer) {\n const {operation} = layer.props;\n return operation.includes('draw') || operation.includes('terrain');\n }\n\n render(options: LayersPassRenderOptions): RenderStats[] {\n return this._render(options);\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '@luma.gl/core';\nimport {Framebuffer} from '@luma.gl/core';\nimport debug from '../debug/index';\nimport DrawLayersPass from '../passes/draw-layers-pass';\nimport PickLayersPass from '../passes/pick-layers-pass';\nimport type {RenderStats} from '../passes/layers-pass';\nimport type {Stats} from '@probe.gl/stats';\nimport type Layer from './layer';\nimport type Viewport from '../viewports/viewport';\nimport type View from '../views/view';\nimport type {Effect, PostRenderOptions} from './effect';\nimport type {LayersPassRenderOptions, FilterContext} from '../passes/layers-pass';\n\nconst TRACE_RENDER_LAYERS = 'deckRenderer.renderLayers';\n\ntype LayerFilter = ((context: FilterContext) => boolean) | null;\n\nexport default class DeckRenderer {\n device: Device;\n layerFilter: LayerFilter;\n drawPickingColors: boolean;\n drawLayersPass: DrawLayersPass;\n pickLayersPass: PickLayersPass;\n stats?: Stats;\n\n private renderCount: number;\n private _needsRedraw: string | false;\n private renderBuffers: Framebuffer[];\n private lastPostProcessEffect: string | null;\n\n constructor(device: Device, opts: {stats?: Stats} = {}) {\n this.device = device;\n this.stats = opts.stats;\n this.layerFilter = null;\n this.drawPickingColors = false;\n this.drawLayersPass = new DrawLayersPass(device);\n this.pickLayersPass = new PickLayersPass(device);\n this.renderCount = 0;\n this._needsRedraw = 'Initial render';\n this.renderBuffers = [];\n this.lastPostProcessEffect = null;\n }\n\n setProps(props: {layerFilter: LayerFilter; drawPickingColors: boolean}) {\n if (this.layerFilter !== props.layerFilter) {\n this.layerFilter = props.layerFilter;\n this._needsRedraw = 'layerFilter changed';\n }\n\n if (this.drawPickingColors !== props.drawPickingColors) {\n this.drawPickingColors = props.drawPickingColors;\n this._needsRedraw = 'drawPickingColors changed';\n }\n }\n\n renderLayers(opts: {\n pass: string;\n layers: Layer[];\n viewports: Viewport[];\n views: {[viewId: string]: View};\n onViewportActive: (viewport: Viewport) => void;\n effects: Effect[];\n target?: Framebuffer | null;\n layerFilter?: LayerFilter;\n clearStack?: boolean;\n clearCanvas?: boolean;\n }) {\n if (!opts.viewports.length) {\n return;\n }\n\n const layerPass = this.drawPickingColors ? this.pickLayersPass : this.drawLayersPass;\n\n const renderOpts: LayersPassRenderOptions = {\n layerFilter: this.layerFilter,\n isPicking: this.drawPickingColors,\n ...opts\n };\n\n if (renderOpts.effects) {\n this._preRender(renderOpts.effects, renderOpts);\n }\n\n const outputBuffer = this.lastPostProcessEffect ? this.renderBuffers[0] : renderOpts.target;\n\n if (this.lastPostProcessEffect) {\n renderOpts.clearColor = [0, 0, 0, 0];\n renderOpts.clearCanvas = true;\n }\n const renderResult = layerPass.render({...renderOpts, target: outputBuffer});\n const renderStats = 'stats' in renderResult ? renderResult.stats : renderResult;\n\n if (renderOpts.effects) {\n if (this.lastPostProcessEffect) {\n // Interleaved basemap rendering requires clearCanvas to be false\n renderOpts.clearCanvas = opts.clearCanvas === undefined ? true : opts.clearCanvas;\n }\n\n this._postRender(renderOpts.effects, renderOpts);\n }\n\n this.renderCount++;\n\n debug(TRACE_RENDER_LAYERS, this, renderStats, opts);\n this._updateStats(renderStats);\n }\n\n needsRedraw(opts: {clearRedrawFlags: boolean} = {clearRedrawFlags: false}): string | false {\n const redraw = this._needsRedraw;\n if (opts.clearRedrawFlags) {\n this._needsRedraw = false;\n }\n return redraw;\n }\n\n finalize() {\n const {renderBuffers} = this;\n for (const buffer of renderBuffers) {\n buffer.delete();\n }\n renderBuffers.length = 0;\n }\n\n private _updateStats(source: RenderStats[]) {\n if (!this.stats) return;\n let layersCount = 0;\n for (const {visibleCount} of source) {\n layersCount += visibleCount;\n }\n this.stats.get('Layers rendered').addCount(layersCount);\n }\n\n private _preRender(effects: Effect[], opts: LayersPassRenderOptions) {\n this.lastPostProcessEffect = null;\n opts.preRenderStats = opts.preRenderStats || {};\n\n for (const effect of effects) {\n opts.preRenderStats[effect.id] = effect.preRender(opts);\n if (effect.postRender) {\n this.lastPostProcessEffect = effect.id;\n }\n }\n\n if (this.lastPostProcessEffect) {\n this._resizeRenderBuffers();\n }\n }\n\n private _resizeRenderBuffers() {\n const {renderBuffers} = this;\n const size = this.device.canvasContext!.getDrawingBufferSize();\n const [width, height] = size;\n if (renderBuffers.length === 0) {\n [0, 1].map(i => {\n const texture = this.device.createTexture({\n sampler: {minFilter: 'linear', magFilter: 'linear'},\n width,\n height\n });\n renderBuffers.push(\n this.device.createFramebuffer({\n id: `deck-renderbuffer-${i}`,\n colorAttachments: [texture]\n })\n );\n });\n }\n for (const buffer of renderBuffers) {\n buffer.resize(size);\n }\n }\n\n private _postRender(effects: Effect[], opts: LayersPassRenderOptions) {\n const {renderBuffers} = this;\n const params: PostRenderOptions = {\n ...opts,\n inputBuffer: renderBuffers[0],\n swapBuffer: renderBuffers[1]\n };\n for (const effect of effects) {\n if (effect.postRender) {\n // If not the last post processing effect, unset the target so that\n // it only renders between the swap buffers\n params.target = effect.id === this.lastPostProcessEffect ? opts.target : undefined;\n const buffer = effect.postRender(params);\n // Buffer cannot be null if target is unset\n params.inputBuffer = buffer!;\n params.swapBuffer = buffer === renderBuffers[0] ? renderBuffers[1] : renderBuffers[0];\n }\n }\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Buffer, Texture} from '@luma.gl/core';\nimport type {Device} from '@luma.gl/core';\nimport PickLayersPass, {PickingColorDecoder} from '../passes/pick-layers-pass';\nimport log from '../utils/log';\nimport {getClosestObject, getUniqueObjects, PickedPixel} from './picking/query-object';\nimport {\n processPickInfo,\n getLayerPickingInfo,\n getEmptyPickingInfo,\n PickingInfo\n} from './picking/pick-info';\nimport type {RenderStats} from '../passes/layers-pass';\nimport type {Stats} from '@probe.gl/stats';\nimport type {Framebuffer} from '@luma.gl/core';\nimport type {FilterContext, Rect} from '../passes/layers-pass';\nimport type Layer from './layer';\nimport type {Effect} from './effect';\nimport type View from '../views/view';\nimport type Viewport from '../viewports/viewport';\n\nexport type PickByPointOptions = {\n x: number;\n y: number;\n radius?: number;\n depth?: number;\n mode?: string;\n unproject3D?: boolean;\n};\n\nexport type PickByRectOptions = {\n x: number;\n y: number;\n width?: number;\n height?: number;\n mode?: string;\n maxObjects?: number | null;\n};\n\ntype PickOperationContext = {\n layers: Layer[];\n views: Record;\n viewports: Viewport[];\n onViewportActive: (viewport: Viewport) => void;\n effects: Effect[];\n};\n\n/** Manages picking in a Deck context */\nexport default class DeckPicker {\n device: Device;\n pickingFBO?: Framebuffer;\n depthFBO?: Framebuffer;\n pickLayersPass: PickLayersPass;\n layerFilter?: (context: FilterContext) => boolean;\n stats?: Stats;\n\n /** Identifiers of the previously picked object, for callback tracking and auto highlight */\n lastPickedInfo: {\n index: number;\n layerId: string | null;\n info: PickingInfo | null;\n };\n\n _pickable: boolean = true;\n\n constructor(device: Device, opts: {stats?: Stats} = {}) {\n this.device = device;\n this.stats = opts.stats;\n this.pickLayersPass = new PickLayersPass(device);\n this.lastPickedInfo = {\n index: -1,\n layerId: null,\n info: null\n };\n }\n\n setProps(props: any): void {\n if ('layerFilter' in props) {\n this.layerFilter = props.layerFilter;\n }\n\n if ('_pickable' in props) {\n this._pickable = props._pickable;\n }\n }\n\n finalize() {\n if (this.pickingFBO) {\n this.pickingFBO.destroy();\n }\n if (this.depthFBO) {\n this.depthFBO.destroy();\n }\n }\n\n /**\n * Pick the closest info at given coordinate\n * @returns Promise that resolves with picking info\n */\n pickObjectAsync(opts: PickByPointOptions & PickOperationContext): Promise<{\n result: PickingInfo[];\n emptyInfo: PickingInfo;\n }> {\n return this._pickClosestObjectAsync(opts);\n }\n\n /**\n * Picks a list of unique infos within a bounding box\n * @returns Promise that resolves to all unique infos within a bounding box\n */\n pickObjectsAsync(opts: PickByRectOptions & PickOperationContext): Promise {\n return this._pickVisibleObjectsAsync(opts);\n }\n\n /**\n * Pick the closest info at given coordinate\n * @returns picking info\n * @note WebGL only - use pickObjectAsync instead\n */\n pickObject(opts: PickByPointOptions & PickOperationContext) {\n return this._pickClosestObject(opts);\n }\n\n /**\n * Get all unique infos within a bounding box\n * @returns all unique infos within a bounding box\n * @note WebGL only - use pickObjectAsync instead\n */\n pickObjects(opts: PickByRectOptions & PickOperationContext) {\n return this._pickVisibleObjects(opts);\n }\n\n // Returns a new picking info object by assuming the last picked object is still picked\n getLastPickedObject({x, y, layers, viewports}, lastPickedInfo = this.lastPickedInfo.info) {\n const lastPickedLayerId = lastPickedInfo && lastPickedInfo.layer && lastPickedInfo.layer.id;\n const lastPickedViewportId =\n lastPickedInfo && lastPickedInfo.viewport && lastPickedInfo.viewport.id;\n const layer = lastPickedLayerId ? layers.find(l => l.id === lastPickedLayerId) : null;\n const viewport =\n (lastPickedViewportId && viewports.find(v => v.id === lastPickedViewportId)) || viewports[0];\n const coordinate = viewport && viewport.unproject([x - viewport.x, y - viewport.y]);\n\n const info = {\n x,\n y,\n viewport,\n coordinate,\n layer\n };\n\n return {...lastPickedInfo, ...info};\n }\n\n // Private\n\n /** Ensures that picking framebuffer exists and matches the canvas size */\n _resizeBuffer() {\n // Create a frame buffer if not already available\n if (!this.pickingFBO) {\n const pickingColorTexture = this.device.createTexture({\n format: 'rgba8unorm',\n width: 1,\n height: 1,\n usage: Texture.RENDER_ATTACHMENT | Texture.COPY_SRC\n });\n this.pickingFBO = this.device.createFramebuffer({\n colorAttachments: [pickingColorTexture],\n depthStencilAttachment: 'depth16unorm'\n });\n\n if (this.device.isTextureFormatRenderable('rgba32float')) {\n const depthColorTexture = this.device.createTexture({\n format: 'rgba32float',\n width: 1,\n height: 1,\n usage: Texture.RENDER_ATTACHMENT | Texture.COPY_SRC\n });\n const depthFBO = this.device.createFramebuffer({\n colorAttachments: [depthColorTexture],\n depthStencilAttachment: 'depth16unorm'\n });\n this.depthFBO = depthFBO;\n }\n }\n\n // Resize it to current canvas size (this is a noop if size hasn't changed)\n const {canvas} = this.device.getDefaultCanvasContext();\n this.pickingFBO?.resize({width: canvas.width, height: canvas.height});\n this.depthFBO?.resize({width: canvas.width, height: canvas.height});\n }\n\n /** Preliminary filtering of the layers list. Skid picking pass if no layer is pickable. */\n _getPickable(layers: Layer[]): Layer[] | null {\n if (this._pickable === false) {\n return null;\n }\n const pickableLayers = layers.filter(\n layer => this.pickLayersPass.shouldDrawLayer(layer) && !layer.isComposite\n );\n return pickableLayers.length ? pickableLayers : null;\n }\n\n /**\n * Pick the closest object at the given coordinate\n */\n // eslint-disable-next-line max-statements,complexity\n async _pickClosestObjectAsync({\n layers,\n views,\n viewports,\n x,\n y,\n radius = 0,\n depth = 1,\n mode = 'query',\n unproject3D,\n onViewportActive,\n effects\n }: PickByPointOptions & PickOperationContext): Promise<{\n result: PickingInfo[];\n emptyInfo: PickingInfo;\n }> {\n // @ts-expect-error TODO - assuming WebGL context\n const pixelRatio = this.device.canvasContext.cssToDeviceRatio();\n\n const pickableLayers = this._getPickable(layers);\n\n if (!pickableLayers || viewports.length === 0) {\n return {\n result: [],\n emptyInfo: getEmptyPickingInfo({viewports, x, y, pixelRatio})\n };\n }\n\n this._resizeBuffer();\n\n // Convert from canvas top-left to WebGL bottom-left coordinates\n // Top-left coordinates [x, y] to bottom-left coordinates [deviceX, deviceY]\n // And compensate for pixelRatio\n // @ts-expect-error TODO - assuming WebGL context\n const devicePixelRange = this.device.canvasContext.cssToDevicePixels([x, y], true);\n const devicePixel = [\n devicePixelRange.x + Math.floor(devicePixelRange.width / 2),\n devicePixelRange.y + Math.floor(devicePixelRange.height / 2)\n ];\n\n const deviceRadius = Math.round(radius * pixelRatio);\n const {width, height} = this.pickingFBO as Framebuffer;\n const deviceRect = this._getPickingRect({\n deviceX: devicePixel[0],\n deviceY: devicePixel[1],\n deviceRadius,\n deviceWidth: width,\n deviceHeight: height\n });\n\n const cullRect: Rect = {\n x: x - radius,\n y: y - radius,\n width: radius * 2 + 1,\n height: radius * 2 + 1\n };\n\n let infos: Map;\n const result: PickingInfo[] = [];\n const affectedLayers = new Set();\n\n for (let i = 0; i < depth; i++) {\n let pickInfo: PickedPixel;\n\n if (deviceRect) {\n const pickedResult = await this._drawAndSampleAsync({\n layers: pickableLayers,\n views,\n viewports,\n onViewportActive,\n deviceRect,\n cullRect,\n effects,\n pass: `picking:${mode}`\n });\n\n pickInfo = getClosestObject({\n ...pickedResult,\n deviceX: devicePixel[0],\n deviceY: devicePixel[1],\n deviceRadius,\n deviceRect\n });\n } else {\n pickInfo = {\n pickedColor: null,\n pickedObjectIndex: -1\n };\n }\n\n let z;\n const depthLayers = this._getDepthLayers(pickInfo, pickableLayers, unproject3D);\n if (depthLayers.length > 0) {\n const {pickedColors: pickedColors2} = await this._drawAndSampleAsync(\n {\n layers: depthLayers,\n views,\n viewports,\n onViewportActive,\n deviceRect: {\n x: pickInfo.pickedX ?? devicePixel[0],\n y: pickInfo.pickedY ?? devicePixel[1],\n width: 1,\n height: 1\n },\n cullRect,\n effects,\n pass: `picking:${mode}:z`\n },\n true\n );\n // picked value is in common space (pixels) from the camera target (viewport.position)\n // convert it to meters from the ground\n if (pickedColors2[3]) {\n z = pickedColors2[0];\n }\n }\n\n // Only exclude if we need to run picking again.\n // We need to run picking again if an object is detected AND\n // we have not exhausted the requested depth.\n if (pickInfo.pickedLayer && i + 1 < depth) {\n affectedLayers.add(pickInfo.pickedLayer);\n pickInfo.pickedLayer.disablePickingIndex(pickInfo.pickedObjectIndex);\n }\n\n // This logic needs to run even if no object is picked.\n infos = processPickInfo({\n pickInfo,\n lastPickedInfo: this.lastPickedInfo,\n mode,\n layers: pickableLayers,\n viewports,\n x,\n y,\n z,\n pixelRatio\n });\n\n for (const info of infos.values()) {\n if (info.layer) {\n result.push(info);\n }\n }\n\n // If no object is picked stop.\n if (!pickInfo.pickedColor) {\n break;\n }\n }\n\n // reset only affected buffers\n for (const layer of affectedLayers) {\n layer.restorePickingColors();\n }\n\n return {result, emptyInfo: infos!.get(null) as PickingInfo};\n }\n\n /**\n * Pick the closest object at the given coordinate\n * @deprecated WebGL only\n */\n // eslint-disable-next-line max-statements,complexity\n _pickClosestObject({\n layers,\n views,\n viewports,\n x,\n y,\n radius = 0,\n depth = 1,\n mode = 'query',\n unproject3D,\n onViewportActive,\n effects\n }: PickByPointOptions & PickOperationContext): {\n result: PickingInfo[];\n emptyInfo: PickingInfo;\n } {\n // @ts-expect-error TODO - assuming WebGL context\n const pixelRatio = this.device.canvasContext.cssToDeviceRatio();\n\n const pickableLayers = this._getPickable(layers);\n\n if (!pickableLayers || viewports.length === 0) {\n return {\n result: [],\n emptyInfo: getEmptyPickingInfo({viewports, x, y, pixelRatio})\n };\n }\n\n this._resizeBuffer();\n\n // Convert from canvas top-left to WebGL bottom-left coordinates\n // Top-left coordinates [x, y] to bottom-left coordinates [deviceX, deviceY]\n // And compensate for pixelRatio\n // @ts-expect-error TODO - assuming WebGL context\n const devicePixelRange = this.device.canvasContext.cssToDevicePixels([x, y], true);\n const devicePixel = [\n devicePixelRange.x + Math.floor(devicePixelRange.width / 2),\n devicePixelRange.y + Math.floor(devicePixelRange.height / 2)\n ];\n\n const deviceRadius = Math.round(radius * pixelRatio);\n const {width, height} = this.pickingFBO as Framebuffer;\n const deviceRect = this._getPickingRect({\n deviceX: devicePixel[0],\n deviceY: devicePixel[1],\n deviceRadius,\n deviceWidth: width,\n deviceHeight: height\n });\n\n const cullRect: Rect = {\n x: x - radius,\n y: y - radius,\n width: radius * 2 + 1,\n height: radius * 2 + 1\n };\n\n let infos: Map;\n const result: PickingInfo[] = [];\n const affectedLayers = new Set();\n\n for (let i = 0; i < depth; i++) {\n let pickInfo: PickedPixel;\n\n if (deviceRect) {\n const pickedResult = this._drawAndSample({\n layers: pickableLayers,\n views,\n viewports,\n onViewportActive,\n deviceRect,\n cullRect,\n effects,\n pass: `picking:${mode}`\n });\n\n pickInfo = getClosestObject({\n ...pickedResult,\n deviceX: devicePixel[0],\n deviceY: devicePixel[1],\n deviceRadius,\n deviceRect\n });\n } else {\n pickInfo = {\n pickedColor: null,\n pickedObjectIndex: -1\n };\n }\n\n let z;\n const depthLayers = this._getDepthLayers(pickInfo, pickableLayers, unproject3D);\n if (depthLayers.length > 0) {\n const {pickedColors: pickedColors2} = this._drawAndSample(\n {\n layers: depthLayers,\n views,\n viewports,\n onViewportActive,\n deviceRect: {\n x: pickInfo.pickedX ?? devicePixel[0],\n y: pickInfo.pickedY ?? devicePixel[1],\n width: 1,\n height: 1\n },\n cullRect,\n effects,\n pass: `picking:${mode}:z`\n },\n true\n );\n // picked value is in common space (pixels) from the camera target (viewport.position)\n // convert it to meters from the ground\n if (pickedColors2[3]) {\n z = pickedColors2[0];\n }\n }\n\n // Only exclude if we need to run picking again.\n // We need to run picking again if an object is detected AND\n // we have not exhausted the requested depth.\n if (pickInfo.pickedLayer && i + 1 < depth) {\n affectedLayers.add(pickInfo.pickedLayer);\n pickInfo.pickedLayer.disablePickingIndex(pickInfo.pickedObjectIndex);\n }\n\n // This logic needs to run even if no object is picked.\n infos = processPickInfo({\n pickInfo,\n lastPickedInfo: this.lastPickedInfo,\n mode,\n layers: pickableLayers,\n viewports,\n x,\n y,\n z,\n pixelRatio\n });\n\n for (const info of infos.values()) {\n if (info.layer) {\n result.push(info);\n }\n }\n\n // If no object is picked stop.\n if (!pickInfo.pickedColor) {\n break;\n }\n }\n\n // reset only affected buffers\n for (const layer of affectedLayers) {\n layer.restorePickingColors();\n }\n\n return {result, emptyInfo: infos!.get(null) as PickingInfo};\n }\n\n /**\n * Pick all objects within the given bounding box\n */\n // eslint-disable-next-line max-statements\n async _pickVisibleObjectsAsync({\n layers,\n views,\n viewports,\n x,\n y,\n width = 1,\n height = 1,\n mode = 'query',\n maxObjects = null,\n onViewportActive,\n effects\n }: PickByRectOptions & PickOperationContext): Promise {\n const pickableLayers = this._getPickable(layers);\n\n if (!pickableLayers || viewports.length === 0) {\n return [];\n }\n\n this._resizeBuffer();\n\n // Convert from canvas top-left to WebGL bottom-left coordinates\n // And compensate for pixelRatio\n // @ts-expect-error TODO - assuming WebGL context\n const pixelRatio = this.device.canvasContext.cssToDeviceRatio();\n // @ts-expect-error TODO - assuming WebGL context\n const leftTop = this.device.canvasContext.cssToDevicePixels([x, y], true);\n\n // take left and top (y inverted in device pixels) from start location\n const deviceLeft = leftTop.x;\n const deviceTop = leftTop.y + leftTop.height;\n\n // take right and bottom (y inverted in device pixels) from end location\n // @ts-expect-error TODO - assuming WebGL context\n const rightBottom = this.device.canvasContext.cssToDevicePixels([x + width, y + height], true);\n const deviceRight = rightBottom.x + rightBottom.width;\n const deviceBottom = rightBottom.y;\n\n const deviceRect = {\n x: deviceLeft,\n y: deviceBottom,\n // deviceTop and deviceRight represent the first pixel outside the desired rect\n width: deviceRight - deviceLeft,\n height: deviceTop - deviceBottom\n };\n\n const pickedResult = await this._drawAndSampleAsync({\n layers: pickableLayers,\n views,\n viewports,\n onViewportActive,\n deviceRect,\n cullRect: {x, y, width, height},\n effects,\n pass: `picking:${mode}`\n });\n\n const pickInfos = getUniqueObjects(pickedResult);\n\n // `getUniqueObjects` dedup by picked color\n // However different picked color may be linked to the same picked object, e.g. stroke and fill of the same polygon\n // picked from different sub layers of a GeoJsonLayer\n // Here after resolving the picked index with `layer.getPickingInfo`, we need to dedup again by unique picked objects\n const uniquePickedObjects = new Map>();\n const uniqueInfos: PickingInfo[] = [];\n\n const limitMaxObjects = Number.isFinite(maxObjects);\n\n for (let i = 0; i < pickInfos.length; i++) {\n if (limitMaxObjects && uniqueInfos.length >= maxObjects!) {\n break;\n }\n const pickInfo = pickInfos[i];\n let info: PickingInfo = {\n color: pickInfo.pickedColor,\n layer: null,\n index: pickInfo.pickedObjectIndex,\n picked: true,\n x,\n y,\n pixelRatio\n };\n\n info = getLayerPickingInfo({layer: pickInfo.pickedLayer as Layer, info, mode});\n // info.layer is always populated because it's a picked pixel\n const pickedLayerId = info.layer!.id;\n if (!uniquePickedObjects.has(pickedLayerId)) {\n uniquePickedObjects.set(pickedLayerId, new Set());\n }\n const uniqueObjectsInLayer = uniquePickedObjects.get(pickedLayerId) as Set;\n // info.object may be null if the layer is using non-iterable data.\n // Fall back to using index as identifier.\n const pickedObjectKey = info.object ?? info.index;\n if (!uniqueObjectsInLayer.has(pickedObjectKey)) {\n uniqueObjectsInLayer.add(pickedObjectKey);\n uniqueInfos.push(info);\n }\n }\n\n return uniqueInfos;\n }\n\n /**\n * Pick all objects within the given bounding box\n * @deprecated WebGL only\n */\n // eslint-disable-next-line max-statements\n _pickVisibleObjects({\n layers,\n views,\n viewports,\n x,\n y,\n width = 1,\n height = 1,\n mode = 'query',\n maxObjects = null,\n onViewportActive,\n effects\n }: PickByRectOptions & PickOperationContext): PickingInfo[] {\n const pickableLayers = this._getPickable(layers);\n\n if (!pickableLayers || viewports.length === 0) {\n return [];\n }\n\n this._resizeBuffer();\n\n // Convert from canvas top-left to WebGL bottom-left coordinates\n // And compensate for pixelRatio\n // @ts-expect-error TODO - assuming WebGL context\n const pixelRatio = this.device.canvasContext.cssToDeviceRatio();\n // @ts-expect-error TODO - assuming WebGL context\n const leftTop = this.device.canvasContext.cssToDevicePixels([x, y], true);\n\n // take left and top (y inverted in device pixels) from start location\n const deviceLeft = leftTop.x;\n const deviceTop = leftTop.y + leftTop.height;\n\n // take right and bottom (y inverted in device pixels) from end location\n // @ts-expect-error TODO - assuming WebGL context\n const rightBottom = this.device.canvasContext.cssToDevicePixels([x + width, y + height], true);\n const deviceRight = rightBottom.x + rightBottom.width;\n const deviceBottom = rightBottom.y;\n\n const deviceRect = {\n x: deviceLeft,\n y: deviceBottom,\n // deviceTop and deviceRight represent the first pixel outside the desired rect\n width: deviceRight - deviceLeft,\n height: deviceTop - deviceBottom\n };\n\n const pickedResult = this._drawAndSample({\n layers: pickableLayers,\n views,\n viewports,\n onViewportActive,\n deviceRect,\n cullRect: {x, y, width, height},\n effects,\n pass: `picking:${mode}`\n });\n\n const pickInfos = getUniqueObjects(pickedResult);\n\n // `getUniqueObjects` dedup by picked color\n // However different picked color may be linked to the same picked object, e.g. stroke and fill of the same polygon\n // picked from different sub layers of a GeoJsonLayer\n // Here after resolving the picked index with `layer.getPickingInfo`, we need to dedup again by unique picked objects\n const uniquePickedObjects = new Map>();\n const uniqueInfos: PickingInfo[] = [];\n\n const limitMaxObjects = Number.isFinite(maxObjects);\n\n for (let i = 0; i < pickInfos.length; i++) {\n if (limitMaxObjects && uniqueInfos.length >= maxObjects!) {\n break;\n }\n const pickInfo = pickInfos[i];\n let info: PickingInfo = {\n color: pickInfo.pickedColor,\n layer: null,\n index: pickInfo.pickedObjectIndex,\n picked: true,\n x,\n y,\n pixelRatio\n };\n\n info = getLayerPickingInfo({layer: pickInfo.pickedLayer as Layer, info, mode});\n // info.layer is always populated because it's a picked pixel\n const pickedLayerId = info.layer!.id;\n if (!uniquePickedObjects.has(pickedLayerId)) {\n uniquePickedObjects.set(pickedLayerId, new Set());\n }\n const uniqueObjectsInLayer = uniquePickedObjects.get(pickedLayerId) as Set;\n // info.object may be null if the layer is using non-iterable data.\n // Fall back to using index as identifier.\n const pickedObjectKey = info.object ?? info.index;\n if (!uniqueObjectsInLayer.has(pickedObjectKey)) {\n uniqueObjectsInLayer.add(pickedObjectKey);\n uniqueInfos.push(info);\n }\n }\n\n return uniqueInfos;\n }\n\n /** Renders layers into the picking buffer with picking colors and read the pixels. */\n _drawAndSampleAsync(params: {\n deviceRect: Rect;\n pass: string;\n layers: Layer[];\n views: Record;\n viewports: Viewport[];\n onViewportActive: (viewport: Viewport) => void;\n cullRect?: Rect;\n effects: Effect[];\n }): Promise<{\n pickedColors: Uint8Array;\n decodePickingColor: PickingColorDecoder;\n }>;\n\n /** Renders layers into the picking buffer with encoded z values and read the pixels. */\n _drawAndSampleAsync(\n params: {\n deviceRect: Rect;\n pass: string;\n layers: Layer[];\n views: Record;\n viewports: Viewport[];\n onViewportActive: (viewport: Viewport) => void;\n cullRect?: Rect;\n effects: Effect[];\n },\n pickZ: true\n ): Promise<{\n pickedColors: Float32Array;\n decodePickingColor: null;\n }>;\n\n // Note: Implementation of the overloaded signatures above, TSDoc is on the signatures\n async _drawAndSampleAsync(\n {\n layers,\n views,\n viewports,\n onViewportActive,\n deviceRect,\n cullRect,\n effects,\n pass\n }: {\n deviceRect: Rect;\n pass: string;\n layers: Layer[];\n views: Record;\n viewports: Viewport[];\n onViewportActive: (viewport: Viewport) => void;\n cullRect?: Rect;\n effects: Effect[];\n },\n pickZ: boolean = false\n ): Promise<{\n pickedColors: Uint8Array | Float32Array;\n decodePickingColor: PickingColorDecoder | null;\n }> {\n const pickingFBO = pickZ ? this.depthFBO : this.pickingFBO;\n const opts = {\n layers,\n layerFilter: this.layerFilter,\n views,\n viewports,\n onViewportActive,\n pickingFBO,\n deviceRect,\n cullRect,\n effects,\n pass,\n pickZ,\n preRenderStats: {},\n isPicking: true\n };\n\n for (const effect of effects) {\n if (effect.useInPicking) {\n opts.preRenderStats[effect.id] = effect.preRender(opts);\n }\n }\n\n const {decodePickingColor, stats} = this.pickLayersPass.render(opts);\n this._updateStats(stats);\n\n const {x, y, width, height} = deviceRect;\n const texture = (pickingFBO as Framebuffer).colorAttachments[0]?.texture;\n if (!texture) {\n throw new Error('Picking framebuffer color attachment is missing');\n }\n\n const pickedColors = await this._readTextureDataAsync(\n texture,\n {x, y, width, height},\n pickZ ? Float32Array : Uint8Array\n );\n\n if (!pickZ) {\n let hasNonZeroAlpha = false;\n for (let i = 3; i < pickedColors.length; i += 4) {\n if (pickedColors[i] !== 0) {\n hasNonZeroAlpha = true;\n break;\n }\n }\n if (!hasNonZeroAlpha && pickedColors.length > 0) {\n log.warn('Async pick readback returned only zero alpha values', {\n deviceRect,\n bytes: Array.from(pickedColors.subarray(0, Math.min(pickedColors.length, 16)))\n })();\n }\n }\n\n return {pickedColors, decodePickingColor};\n }\n\n private async _readTextureDataAsync(\n texture: Texture,\n options: {x: number; y: number; width: number; height: number},\n ArrayType: Uint8ArrayConstructor | Float32ArrayConstructor\n ): Promise {\n const {width, height} = options;\n const layout = texture.computeMemoryLayout(options);\n const readBuffer = this.device.createBuffer({\n byteLength: layout.byteLength,\n usage: Buffer.COPY_DST | Buffer.MAP_READ\n });\n\n try {\n texture.readBuffer(options, readBuffer);\n const readData = await readBuffer.readAsync(0, layout.byteLength);\n const bytesPerElement = ArrayType.BYTES_PER_ELEMENT;\n if (layout.bytesPerRow % bytesPerElement !== 0) {\n throw new Error(\n `Texture readback row stride ${layout.bytesPerRow} is not aligned to ${bytesPerElement}-byte elements.`\n );\n }\n const source = new ArrayType(\n readData.buffer,\n readData.byteOffset,\n layout.byteLength / bytesPerElement\n );\n // Picking textures are RGBA. WebGPU rows may be padded to satisfy GPU alignment\n // requirements, so repack each row into a tightly packed CPU array before decode.\n const packedRowLength = width * 4;\n const sourceRowLength = layout.bytesPerRow / bytesPerElement;\n if (sourceRowLength < packedRowLength) {\n throw new Error(\n `Texture readback row stride ${sourceRowLength} is smaller than packed row length ${packedRowLength}.`\n );\n }\n const packed = new ArrayType(width * height * 4);\n\n for (let row = 0; row < height; row++) {\n const sourceStart = row * sourceRowLength;\n packed.set(\n source.subarray(sourceStart, sourceStart + packedRowLength),\n row * packedRowLength\n );\n }\n\n return packed as T;\n } finally {\n readBuffer.destroy();\n }\n }\n\n /**\n * Renders layers into the picking buffer with picking colors and read the pixels.\n * @deprecated WebGL only, use _drawAndSampleAsync instead\n */\n _drawAndSample(params: {\n deviceRect: Rect;\n pass: string;\n layers: Layer[];\n views: Record;\n viewports: Viewport[];\n onViewportActive: (viewport: Viewport) => void;\n cullRect?: Rect;\n effects: Effect[];\n }): {\n pickedColors: Uint8Array;\n decodePickingColor: PickingColorDecoder;\n };\n\n /**\n * Renders layers into the picking buffer with encoded z values and read the pixels.\n * @deprecated WebGL only, use _drawAndSampleAsync instead\n */\n _drawAndSample(\n params: {\n deviceRect: Rect;\n pass: string;\n layers: Layer[];\n views: Record;\n viewports: Viewport[];\n onViewportActive: (viewport: Viewport) => void;\n cullRect?: Rect;\n effects: Effect[];\n },\n pickZ: true\n ): {\n pickedColors: Float32Array;\n decodePickingColor: null;\n };\n\n // Note: Implementation of the overloaded signatures above, TSDoc is on the signatures\n _drawAndSample(\n {\n layers,\n views,\n viewports,\n onViewportActive,\n deviceRect,\n cullRect,\n effects,\n pass\n }: {\n deviceRect: Rect;\n pass: string;\n layers: Layer[];\n views: Record;\n viewports: Viewport[];\n onViewportActive: (viewport: Viewport) => void;\n cullRect?: Rect;\n effects: Effect[];\n },\n pickZ: boolean = false\n ): {\n pickedColors: Uint8Array | Float32Array;\n decodePickingColor: PickingColorDecoder | null;\n } {\n const pickingFBO = pickZ ? this.depthFBO : this.pickingFBO;\n const opts = {\n layers,\n layerFilter: this.layerFilter,\n views,\n viewports,\n onViewportActive,\n pickingFBO,\n deviceRect,\n cullRect,\n effects,\n pass,\n pickZ,\n preRenderStats: {},\n isPicking: true\n };\n\n for (const effect of effects) {\n if (effect.useInPicking) {\n opts.preRenderStats[effect.id] = effect.preRender(opts);\n }\n }\n\n const {decodePickingColor, stats} = this.pickLayersPass.render(opts);\n this._updateStats(stats);\n\n // Read from an already rendered picking buffer\n // Returns an Uint8ClampedArray of picked pixels\n const {x, y, width, height} = deviceRect;\n const pickedColors = new (pickZ ? Float32Array : Uint8Array)(width * height * 4);\n this.device.readPixelsToArrayWebGL(pickingFBO as Framebuffer, {\n sourceX: x,\n sourceY: y,\n sourceWidth: width,\n sourceHeight: height,\n target: pickedColors\n });\n\n return {pickedColors, decodePickingColor};\n }\n\n private _updateStats(source: RenderStats[]) {\n if (!this.stats) return;\n let layersCount = 0;\n for (const {visibleCount} of source) {\n layersCount += visibleCount;\n }\n this.stats.get('Layers picked').addCount(layersCount);\n }\n\n /**\n * Determine which layers to use for the depth (pickZ) pass.\n * - If a non-draped layer was picked, use just that layer.\n * - If a draped layer was picked (geometry is at z=0) or no layer was picked\n * (e.g. no-FBO tiles at extreme zoom), fall back to terrain layers.\n */\n _getDepthLayers(pickInfo: PickedPixel, pickableLayers: Layer[], unproject3D?: boolean): Layer[] {\n if (!unproject3D || !this.depthFBO) {\n return [];\n }\n const {pickedLayer} = pickInfo;\n const isDraped = pickedLayer?.state?.terrainDrawMode === 'drape';\n if (pickedLayer && !isDraped) {\n return [pickedLayer];\n }\n // For draped layers or when no layer was picked, use terrain layers for depth\n return pickableLayers.filter(l => l.props.operation.includes('terrain'));\n }\n\n /**\n * Calculate a picking rect centered on deviceX and deviceY and clipped to device\n * @returns null if pixel is outside of device\n */\n _getPickingRect({\n deviceX,\n deviceY,\n deviceRadius,\n deviceWidth,\n deviceHeight\n }: {\n deviceX: number;\n deviceY: number;\n deviceRadius: number;\n deviceWidth: number;\n deviceHeight: number;\n }): Rect | null {\n // Create a box of size `radius * 2 + 1` centered at [deviceX, deviceY]\n const x = Math.max(0, deviceX - deviceRadius);\n const y = Math.max(0, deviceY - deviceRadius);\n const width = Math.min(deviceWidth, deviceX + deviceRadius + 1) - x;\n const height = Math.min(deviceHeight, deviceY + deviceRadius + 1) - y;\n\n // x, y out of bounds.\n if (width <= 0 || height <= 0) {\n return null;\n }\n\n return {x, y, width, height};\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport log from '../../utils/log';\nimport type Layer from '../layer';\nimport type Viewport from '../../viewports/viewport';\nimport type {PickingColorDecoder} from '../../passes/pick-layers-pass';\n\nexport type PickedPixel = {\n pickedColor: Uint8Array | null;\n pickedLayer?: Layer;\n pickedViewports?: Viewport[];\n pickedX?: number;\n pickedY?: number;\n pickedObjectIndex: number;\n};\n\nconst NO_PICKED_OBJECT = {\n pickedColor: null,\n pickedObjectIndex: -1\n};\n\n/* eslint-disable max-depth, max-statements */\n/**\n * Pick at a specified pixel with a tolerance radius\n * Returns the closest object to the pixel in shape `{pickedColor, pickedLayer, pickedObjectIndex}`\n */\nexport function getClosestObject({\n pickedColors,\n decodePickingColor,\n deviceX,\n deviceY,\n deviceRadius,\n deviceRect\n}: {\n pickedColors: Uint8Array;\n decodePickingColor: PickingColorDecoder;\n deviceX: number;\n deviceY: number;\n deviceRadius: number;\n deviceRect: {x: number; y: number; width: number; height: number};\n}): PickedPixel {\n // Traverse all pixels in picking results and find the one closest to the supplied\n // [deviceX, deviceY]\n const {x, y, width, height} = deviceRect;\n let minSquareDistanceToCenter = deviceRadius * deviceRadius;\n let closestPixelIndex = -1;\n let i = 0;\n\n for (let row = 0; row < height; row++) {\n const dy = row + y - deviceY;\n const dy2 = dy * dy;\n\n if (dy2 > minSquareDistanceToCenter) {\n // skip this row\n i += 4 * width;\n } else {\n for (let col = 0; col < width; col++) {\n // Decode picked layer from color\n const pickedLayerIndex = pickedColors[i + 3] - 1;\n\n if (pickedLayerIndex >= 0) {\n const dx = col + x - deviceX;\n const d2 = dx * dx + dy2;\n\n if (d2 <= minSquareDistanceToCenter) {\n minSquareDistanceToCenter = d2;\n closestPixelIndex = i;\n }\n }\n i += 4;\n }\n }\n }\n\n if (closestPixelIndex >= 0) {\n // Decode picked object index from color\n const pickedColor = pickedColors.slice(closestPixelIndex, closestPixelIndex + 4);\n const pickedObject = decodePickingColor(pickedColor);\n if (pickedObject) {\n const dy = Math.floor(closestPixelIndex / 4 / width);\n const dx = closestPixelIndex / 4 - dy * width;\n return {\n ...pickedObject,\n pickedColor,\n pickedX: x + dx,\n pickedY: y + dy\n };\n }\n log.error('Picked non-existent layer. Is picking buffer corrupt?')();\n }\n return NO_PICKED_OBJECT;\n}\n\n/**\n * Examines a picking buffer for unique colors\n * Returns array of unique objects in shape `{x, y, pickedColor, pickedLayer, pickedObjectIndex}`\n */\nexport function getUniqueObjects({\n pickedColors,\n decodePickingColor\n}: {\n pickedColors: Uint8Array;\n decodePickingColor: PickingColorDecoder;\n}): PickedPixel[] {\n const uniqueColors = new Map();\n\n // Traverse all pixels in picking results and get unique colors\n if (pickedColors) {\n for (let i = 0; i < pickedColors.length; i += 4) {\n // Decode picked layer from color\n const pickedLayerIndex = pickedColors[i + 3] - 1;\n\n if (pickedLayerIndex >= 0) {\n const pickedColor = pickedColors.slice(i, i + 4);\n const colorKey = pickedColor.join(',');\n // eslint-disable-next-line\n if (!uniqueColors.has(colorKey)) {\n const pickedObject = decodePickingColor(pickedColor);\n // eslint-disable-next-line\n if (pickedObject) {\n uniqueColors.set(colorKey, {\n ...pickedObject,\n color: pickedColor\n });\n } else {\n log.error('Picked non-existent layer. Is picking buffer corrupt?')();\n }\n }\n }\n }\n }\n\n return Array.from(uniqueColors.values());\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type Layer from '../layer';\nimport type Viewport from '../../viewports/viewport';\nimport type {PickedPixel} from './query-object';\n\nexport type PickingInfo = ExtraInfo & {\n color: Uint8Array | null;\n layer: Layer | null;\n sourceLayer?: Layer | null;\n viewport?: Viewport;\n index: number;\n picked: boolean;\n object?: DataT;\n x: number;\n y: number;\n pixel?: [number, number];\n coordinate?: number[];\n devicePixel?: [number, number];\n pixelRatio: number;\n};\n\nexport interface GetPickingInfoParams {\n info: PickingInfo;\n mode: string;\n sourceLayer: Layer | null;\n}\n\n/** Generates some basic information of the picking action: x, y, coordinates etc.\n * Regardless if anything is picked\n */\nexport function getEmptyPickingInfo({\n pickInfo,\n viewports,\n pixelRatio,\n x,\n y,\n z\n}: {\n pickInfo?: PickedPixel;\n viewports: Viewport[];\n pixelRatio: number;\n x: number;\n y: number;\n z?: number;\n}): PickingInfo {\n // If more than one viewports are used in the picking pass, locate the viewport that\n // drew the picked pixel\n let pickedViewport = viewports[0];\n if (viewports.length > 1) {\n // Find the viewport that contain the picked pixel\n pickedViewport = getViewportFromCoordinates(pickInfo?.pickedViewports || viewports, {x, y});\n }\n let coordinate: number[] | undefined;\n if (pickedViewport) {\n const point = [x - pickedViewport.x, y - pickedViewport.y];\n if (z !== undefined) {\n point[2] = z;\n }\n coordinate = pickedViewport.unproject(point);\n }\n\n return {\n color: null,\n layer: null,\n viewport: pickedViewport,\n index: -1,\n picked: false,\n x,\n y,\n pixel: [x, y],\n coordinate,\n devicePixel:\n pickInfo && 'pickedX' in pickInfo\n ? [pickInfo.pickedX as number, pickInfo.pickedY as number]\n : undefined,\n pixelRatio\n };\n}\n\n/* eslint-disable max-depth */\n/** Generates the picking info of a picking operation */\nexport function processPickInfo(opts: {\n pickInfo: PickedPixel;\n lastPickedInfo: {\n index: number;\n layerId: string | null;\n info: PickingInfo | null;\n };\n mode: string;\n layers: Layer[];\n viewports: Viewport[];\n pixelRatio: number;\n x: number;\n y: number;\n z?: number;\n}): Map {\n const {pickInfo, lastPickedInfo, mode, layers} = opts;\n const {pickedColor, pickedLayer, pickedObjectIndex} = pickInfo;\n\n const affectedLayers = pickedLayer ? [pickedLayer] : [];\n\n if (mode === 'hover') {\n // only invoke onHover events if picked object has changed\n const lastPickedPixelIndex = lastPickedInfo.index;\n const lastPickedLayerId = lastPickedInfo.layerId;\n const pickedLayerId = pickedLayer ? pickedLayer.props.id : null;\n\n // proceed only if picked object changed\n if (pickedLayerId !== lastPickedLayerId || pickedObjectIndex !== lastPickedPixelIndex) {\n if (pickedLayerId !== lastPickedLayerId) {\n // We cannot store a ref to lastPickedLayer in the context because\n // the state of an outdated layer is no longer valid\n // and the props may have changed\n const lastPickedLayer = layers.find(layer => layer.props.id === lastPickedLayerId);\n if (lastPickedLayer) {\n // Let leave event fire before enter event\n affectedLayers.unshift(lastPickedLayer);\n }\n }\n\n // Update layer manager context\n lastPickedInfo.layerId = pickedLayerId;\n lastPickedInfo.index = pickedObjectIndex;\n lastPickedInfo.info = null;\n }\n }\n\n const baseInfo = getEmptyPickingInfo(opts);\n\n // Use a Map to store all picking infos.\n // The following two forEach loops are the result of\n // https://github.com/visgl/deck.gl/issues/443\n // Please be very careful when changing this pattern\n const infos = new Map();\n\n // Make sure infos always contain something even if no layer is affected\n infos.set(null, baseInfo);\n\n affectedLayers.forEach(layer => {\n let info = {...baseInfo};\n\n if (layer === pickedLayer) {\n info.color = pickedColor;\n info.index = pickedObjectIndex;\n info.picked = true;\n }\n\n info = getLayerPickingInfo({layer, info, mode});\n const rootLayer = info.layer as Layer;\n\n if (layer === pickedLayer && mode === 'hover') {\n lastPickedInfo.info = info;\n }\n\n // This guarantees that there will be only one copy of info for\n // one composite layer\n infos.set(rootLayer.id, info);\n\n if (mode === 'hover') {\n rootLayer.updateAutoHighlight(info);\n }\n });\n\n return infos;\n}\n\n/** Walk up the layer composite chain to populate the info object */\nexport function getLayerPickingInfo({\n layer,\n info,\n mode\n}: {\n layer: Layer;\n info: PickingInfo;\n mode: string;\n}): PickingInfo {\n while (layer && info) {\n // For a composite layer, sourceLayer will point to the sublayer\n // where the event originates from.\n // It provides additional context for the composite layer's\n // getPickingInfo() method to populate the info object\n const sourceLayer = info.layer || null;\n info.sourceLayer = sourceLayer;\n info.layer = layer;\n // layer.pickLayer() function requires a non-null ```layer.state```\n // object to function properly. So the layer referenced here\n // must be the \"current\" layer, not an \"out-dated\" / \"invalidated\" layer\n info = layer.getPickingInfo({info, mode, sourceLayer});\n layer = layer.parent as Layer;\n }\n return info;\n}\n\n/** Indentifies which viewport, if any corresponds to x and y\n If multiple viewports contain the target pixel, last viewport drawn is returend\n Returns first viewport if no match */\nfunction getViewportFromCoordinates(\n viewports: Viewport[],\n pixel: {x: number; y: number}\n): Viewport {\n // find the last viewport that contains the pixel\n for (let i = viewports.length - 1; i >= 0; i--) {\n const viewport = viewports[i];\n if (viewport.containsPixel(pixel)) {\n return viewport;\n }\n }\n return viewports[0];\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type Deck from './deck';\nimport type Viewport from '../viewports/viewport';\nimport type {PickingInfo} from './picking/pick-info';\nimport type {MjolnirPointerEvent, MjolnirGestureEvent} from 'mjolnir.js';\nimport type Layer from './layer';\nimport {Widget} from './widget';\n\nimport {EVENT_HANDLERS} from './constants';\nimport {deepEqual} from '../utils/deep-equal';\n\nconst PLACEMENTS = {\n 'top-left': {top: 0, left: 0},\n 'top-right': {top: 0, right: 0},\n 'bottom-left': {bottom: 0, left: 0},\n 'bottom-right': {bottom: 0, right: 0},\n fill: {top: 0, left: 0, bottom: 0, right: 0}\n} as const;\nconst DEFAULT_PLACEMENT = 'top-left';\n\nexport type WidgetPlacement = keyof typeof PLACEMENTS;\n\nconst ROOT_CONTAINER_ID = 'root';\n\nexport type WidgetManagerProps = {\n deck: Deck;\n parentElement?: HTMLElement | null;\n};\nexport class WidgetManager {\n deck: Deck;\n parentElement?: HTMLElement | null;\n\n /** Widgets added via the imperative API */\n private defaultWidgets: Widget[] = [];\n /** Widgets received from the declarative API */\n private widgets: Widget[] = [];\n /** Resolved widgets from both imperative and declarative APIs */\n private resolvedWidgets: Widget[] = [];\n\n /** Mounted HTML containers */\n private containers: {[id: string]: HTMLDivElement} = {};\n /** Viewport provided to widget on redraw */\n private lastViewports: {[id: string]: Viewport} = {};\n\n constructor({deck, parentElement}: WidgetManagerProps) {\n this.deck = deck;\n parentElement?.classList.add('deck-widget-container');\n this.parentElement = parentElement;\n }\n\n getWidgets(): Widget[] {\n return this.resolvedWidgets;\n }\n\n /** Declarative API to configure widgets */\n setProps(props: {widgets?: (Widget | null | undefined)[]}) {\n if (props.widgets && !deepEqual(props.widgets, this.widgets, 1)) {\n // Allow application to supply null widgets\n const nextWidgets = props.widgets.filter(Boolean) as Widget[];\n this._setWidgets(nextWidgets);\n }\n }\n\n finalize() {\n for (const widget of this.getWidgets()) {\n this._removeWidget(widget);\n }\n this.defaultWidgets.length = 0;\n this.resolvedWidgets.length = 0;\n for (const id in this.containers) {\n this.containers[id].remove();\n }\n }\n\n /** Imperative API. Widgets added this way are not affected by the declarative prop. */\n addDefault(widget: Widget) {\n if (!this.defaultWidgets.find(w => w.id === widget.id)) {\n this._addWidget(widget);\n this.defaultWidgets.push(widget);\n // Update widget list\n this._setWidgets(this.widgets);\n }\n }\n\n onRedraw({viewports, layers}: {viewports: Viewport[]; layers: Layer[]}) {\n const viewportsById: {[id: string]: Viewport} = viewports.reduce((acc, v) => {\n acc[v.id] = v;\n return acc;\n }, {});\n\n for (const widget of this.getWidgets()) {\n const {viewId} = widget;\n if (viewId) {\n // Attached to a specific view\n const viewport = viewportsById[viewId];\n if (viewport) {\n if (widget.onViewportChange) {\n widget.onViewportChange(viewport);\n }\n widget.onRedraw?.({viewports: [viewport], layers});\n }\n } else {\n // Not attached to a specific view\n if (widget.onViewportChange) {\n for (const viewport of viewports) {\n widget.onViewportChange(viewport);\n }\n }\n widget.onRedraw?.({viewports, layers});\n }\n }\n this.lastViewports = viewportsById;\n this._updateContainers();\n }\n\n onHover(info: PickingInfo, event: MjolnirPointerEvent) {\n for (const widget of this.getWidgets()) {\n const {viewId} = widget;\n if (!viewId || viewId === info.viewport?.id) {\n widget.onHover?.(info, event);\n }\n }\n }\n\n onEvent(info: PickingInfo, event: MjolnirGestureEvent) {\n const eventHandlerProp = EVENT_HANDLERS[event.type];\n if (!eventHandlerProp) {\n return;\n }\n for (const widget of this.getWidgets()) {\n const {viewId} = widget;\n if (!viewId || viewId === info.viewport?.id) {\n widget[eventHandlerProp]?.(info, event);\n }\n }\n }\n\n // INTERNAL METHODS\n\n /**\n * Resolve widgets from the declarative prop\n * Initialize new widgets and remove old ones\n * Update props of existing widgets\n */\n private _setWidgets(nextWidgets: Widget[]) {\n const oldWidgetMap: Record = {};\n\n for (const widget of this.resolvedWidgets) {\n oldWidgetMap[widget.id] = widget;\n }\n // Clear and rebuild the list\n this.resolvedWidgets.length = 0;\n\n // Add all default widgets\n for (const widget of this.defaultWidgets) {\n oldWidgetMap[widget.id] = null;\n this.resolvedWidgets.push(widget);\n }\n\n for (let widget of nextWidgets) {\n const oldWidget = oldWidgetMap[widget.id];\n if (!oldWidget) {\n // Widget is new\n this._addWidget(widget);\n } else if (\n // Widget placement changed\n oldWidget.viewId !== widget.viewId ||\n oldWidget.placement !== widget.placement\n ) {\n this._removeWidget(oldWidget);\n this._addWidget(widget);\n } else if (widget !== oldWidget) {\n // Widget props changed\n oldWidget.setProps(widget.props);\n widget = oldWidget;\n }\n\n // mark as matched\n oldWidgetMap[widget.id] = null;\n this.resolvedWidgets.push(widget);\n }\n\n for (const id in oldWidgetMap) {\n const oldWidget = oldWidgetMap[id];\n if (oldWidget) {\n // No longer exists\n this._removeWidget(oldWidget);\n }\n }\n this.widgets = nextWidgets;\n }\n\n /** Initialize new widget */\n private _addWidget(widget: Widget) {\n const {viewId = null, placement = DEFAULT_PLACEMENT} = widget;\n const container = widget.props._container ?? viewId;\n\n widget.widgetManager = this;\n widget.deck = this.deck;\n\n // Create an attach the HTML root element\n widget.rootElement = widget._onAdd({deck: this.deck, viewId});\n if (widget.rootElement) {\n this._getContainer(container, placement).append(widget.rootElement);\n }\n\n widget.updateHTML();\n }\n\n /** Destroy an old widget */\n private _removeWidget(widget: Widget) {\n widget.onRemove?.();\n\n if (widget.rootElement) {\n widget.rootElement.remove();\n }\n widget.rootElement = undefined;\n widget.deck = undefined;\n widget.widgetManager = undefined;\n }\n\n /** Get a container element based on view and placement */\n private _getContainer(\n viewIdOrContainer: string | HTMLDivElement | null,\n placement: WidgetPlacement\n ): HTMLDivElement {\n if (viewIdOrContainer && typeof viewIdOrContainer !== 'string') {\n return viewIdOrContainer;\n }\n const containerId = viewIdOrContainer || ROOT_CONTAINER_ID;\n let viewContainer = this.containers[containerId];\n if (!viewContainer) {\n viewContainer = document.createElement('div');\n viewContainer.style.pointerEvents = 'none';\n viewContainer.style.position = 'absolute';\n viewContainer.style.overflow = 'hidden';\n this.parentElement?.append(viewContainer);\n this.containers[containerId] = viewContainer;\n }\n let container = viewContainer.querySelector(`.${placement}`);\n if (!container) {\n container = globalThis.document.createElement('div');\n container.className = placement;\n container.style.position = 'absolute';\n container.style.zIndex = '2';\n Object.assign(container.style, PLACEMENTS[placement]);\n viewContainer.append(container);\n }\n return container;\n }\n\n private _updateContainers() {\n const canvasWidth = this.deck.width;\n const canvasHeight = this.deck.height;\n for (const id in this.containers) {\n const viewport = this.lastViewports[id] || null;\n const visible = id === ROOT_CONTAINER_ID || viewport;\n\n const container = this.containers[id];\n if (visible) {\n container.style.display = 'block';\n // Align the container with the view\n container.style.left = `${viewport ? viewport.x : 0}px`;\n container.style.top = `${viewport ? viewport.y : 0}px`;\n container.style.width = `${viewport ? viewport.width : canvasWidth}px`;\n container.style.height = `${viewport ? viewport.height : canvasHeight}px`;\n } else {\n container.style.display = 'none';\n }\n }\n }\n}\n","export function applyStyles(element: HTMLElement, style?: Partial): void {\n if (style) {\n Object.entries(style).map(([key, value]) => {\n if (key.startsWith('--')) {\n // Assume CSS variable\n element.style.setProperty(key, value as string);\n } else {\n // Assume camelCase\n element.style[key] = value;\n }\n });\n }\n}\n\nexport function removeStyles(element: HTMLElement, style?: Partial): void {\n if (style) {\n Object.keys(style).map(key => {\n if (key.startsWith('--')) {\n // Assume CSS variable\n element.style.removeProperty(key);\n } else {\n // Assume camelCase\n element.style[key] = '';\n }\n });\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type Deck from './deck';\nimport type Viewport from '../viewports/viewport';\nimport type {PickingInfo} from './picking/pick-info';\nimport type {MjolnirPointerEvent, MjolnirGestureEvent} from 'mjolnir.js';\nimport type Layer from './layer';\nimport type {WidgetManager, WidgetPlacement} from './widget-manager';\nimport type {ViewOrViews} from './view-manager';\nimport {deepEqual} from '../utils/deep-equal';\nimport {applyStyles, removeStyles} from '../utils/apply-styles';\n\nexport type WidgetProps = {\n id?: string;\n /** CSS inline style overrides. */\n style?: Partial;\n /** Additional CSS class. */\n className?: string;\n /**\n * The container that this widget is being attached to. Default to `viewId`.\n * If set to `'root'`, the widget is placed relative to the whole deck.gl canvas.\n * If set to a valid view id, the widget is placed relative to that view.\n * If set to a HTMLElement, `placement` is ignored and the widget is appended into the given element.\n */\n _container?: string | HTMLDivElement | null;\n};\n\nexport abstract class Widget<\n PropsT extends WidgetProps = WidgetProps,\n ViewsT extends ViewOrViews = null\n> {\n static defaultProps: Required = {\n id: 'widget',\n style: {},\n _container: null,\n className: ''\n };\n\n /** Unique identifier of the widget. */\n id: string;\n /** Widget props, with defaults applied */\n props: Required;\n /**\n * The view id that this widget controls. Default `null`.\n * If assigned, this widget will only respond to events occurred inside the specific view that matches this id.\n */\n viewId?: string | null = null;\n\n /** Widget positioning within the view. Default 'top-left'. */\n abstract placement: WidgetPlacement;\n /** Class name for this widget */\n abstract className: string;\n\n // Populated by core when mounted\n widgetManager?: WidgetManager;\n deck?: Deck;\n rootElement?: HTMLDivElement | null;\n\n constructor(props: PropsT) {\n this.props = {\n // @ts-expect-error `defaultProps` may not exist on constructor\n ...(this.constructor.defaultProps as Required),\n ...props\n };\n // @ts-expect-error TODO(ib) - why is id considered optional even though we use Required<>\n this.id = this.props.id;\n }\n\n /** Called to update widget options */\n setProps(props: Partial): void {\n const oldProps = this.props;\n const el = this.rootElement;\n\n // Update className and style\n if (el && oldProps.className !== props.className) {\n if (oldProps.className) el.classList.remove(oldProps.className);\n if (props.className) el.classList.add(props.className);\n }\n\n // Update style\n if (el && !deepEqual(oldProps.style, props.style, 1)) {\n removeStyles(el, oldProps.style);\n applyStyles(el, props.style);\n }\n\n Object.assign(this.props, props);\n\n // Update the HTML to match the new props\n this.updateHTML();\n }\n\n /** Update the HTML to reflect latest props and state */\n updateHTML(): void {\n if (this.rootElement) {\n this.onRenderHTML(this.rootElement);\n }\n }\n\n // VIEW STATE HELPERS\n protected get viewIds(): string[] {\n return this.viewId ? [this.viewId] : (this.deck?.getViews().map(v => v.id) ?? []);\n }\n\n /** Returns the current view state for the given view */\n protected getViewState(viewId: string): Record {\n // @ts-ignore viewManager is private\n return this.deck?.viewManager?.getViewState(viewId) || {};\n }\n\n /** Updates the view state for the given view */\n protected setViewState(viewId: string, viewState: Record): void {\n // @ts-ignore Using private method temporary until there's a public one\n this.deck?._onViewStateChange({viewId, viewState, interactionState: {}});\n }\n\n // @note empty method calls have an overhead in V8 but it is very low, ~1ns\n\n /**\n * Common utility to create the root DOM element for this widget\n * Configures the top-level styles and adds basic class names for theming\n * @returns an UI element that should be appended to the Deck container\n */\n protected onCreateRootElement(): HTMLDivElement {\n const CLASS_NAMES = [\n // Add class names for theming\n 'deck-widget',\n this.className,\n // plus any app-supplied class name\n this.props.className\n ];\n\n const element = document.createElement('div');\n CLASS_NAMES.filter((cls): cls is string => typeof cls === 'string' && cls.length > 0).forEach(\n className => element.classList.add(className)\n );\n applyStyles(element, this.props.style);\n return element;\n }\n\n // WIDGET LIFECYCLE\n\n /** Called to render HTML into the root element */\n abstract onRenderHTML(rootElement: HTMLElement): void;\n\n /** Internal API called by Deck when the widget is first added to a Deck instance */\n _onAdd(params: {deck: Deck; viewId: string | null}): HTMLDivElement {\n return this.onAdd(params) ?? this.onCreateRootElement();\n }\n\n /** Overridable by subclass - called when the widget is first added to a Deck instance\n * @returns an optional UI element that should be appended to the Deck container\n */\n onAdd(params: {\n /** The Deck instance that the widget is attached to */\n deck: Deck;\n /** The id of the view that the widget is attached to */\n viewId: string | null;\n }): HTMLDivElement | void {}\n\n /** Called when the widget is removed */\n onRemove(): void {}\n\n // deck integration - Event hooks\n\n /** Called when the containing view is changed */\n onViewportChange(viewport: Viewport): void {}\n /** Called when the containing view is redrawn */\n onRedraw(params: {viewports: Viewport[]; layers: Layer[]}): void {}\n /** Called when a hover event occurs */\n onHover(info: PickingInfo, event: MjolnirPointerEvent): void {}\n /** Called when a click event occurs */\n onClick(info: PickingInfo, event: MjolnirGestureEvent): void {}\n /** Called when a drag event occurs */\n onDrag(info: PickingInfo, event: MjolnirGestureEvent): void {}\n /** Called when a dragstart event occurs */\n onDragStart(info: PickingInfo, event: MjolnirGestureEvent): void {}\n /** Called when a dragend event occurs */\n onDragEnd(info: PickingInfo, event: MjolnirGestureEvent): void {}\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Widget, WidgetProps} from './widget';\nimport type {WidgetPlacement} from './widget-manager';\nimport type {PickingInfo} from './picking/pick-info';\nimport type Viewport from '../viewports/viewport';\n\n/* global document */\nconst defaultStyle: Partial = {\n zIndex: '1',\n position: 'absolute',\n pointerEvents: 'none',\n color: '#a0a7b4',\n backgroundColor: '#29323c',\n padding: '10px',\n top: '0',\n left: '0',\n display: 'none'\n};\n\nexport type TooltipContent =\n | null\n | string\n | {\n text?: string;\n html?: string;\n className?: string;\n style?: Partial;\n };\n\nexport type TooltipWidgetProps = WidgetProps;\n\nexport class TooltipWidget extends Widget {\n static defaultProps: Required = {\n ...Widget.defaultProps\n };\n\n id = 'default-tooltip';\n placement: WidgetPlacement = 'fill';\n className = 'deck-tooltip';\n\n isVisible: boolean = false;\n lastViewport?: Viewport;\n\n constructor(props: TooltipWidgetProps = {}) {\n super(props);\n this.setProps(props);\n }\n\n // TODO(ib) - does this really need to be overridden?\n onCreateRootElement() {\n const el = document.createElement('div');\n el.className = this.className;\n Object.assign(el.style, defaultStyle);\n return el;\n }\n\n onRenderHTML(rootElement: HTMLElement): void {}\n\n onViewportChange(viewport: Viewport) {\n if (\n this.isVisible &&\n viewport.id === this.lastViewport?.id &&\n !viewport.equals(this.lastViewport)\n ) {\n // Camera has moved, clear tooltip\n this.setTooltip(null);\n }\n // Always update lastViewport from the render loop to ensure consistent\n // viewport source for comparisons (avoids mismatches with picking viewports)\n this.lastViewport = viewport;\n }\n\n onHover(info: PickingInfo) {\n const {deck} = this;\n const getTooltip = deck && deck.props.getTooltip;\n if (!getTooltip) {\n return;\n }\n const displayInfo = getTooltip(info);\n this.setTooltip(displayInfo, info.x, info.y);\n }\n\n setTooltip(displayInfo: TooltipContent, x?: number, y?: number): void {\n const el = this.rootElement;\n if (!el) {\n return;\n }\n\n if (typeof displayInfo === 'string') {\n el.innerText = displayInfo;\n } else if (!displayInfo) {\n this.isVisible = false;\n el.style.display = 'none';\n return;\n } else {\n if (displayInfo.text) {\n el.innerText = displayInfo.text;\n }\n if (displayInfo.html) {\n el.innerHTML = displayInfo.html;\n }\n if (displayInfo.className) {\n el.className = displayInfo.className;\n }\n }\n this.isVisible = true;\n el.style.display = 'block';\n el.style.transform = `translate(${x}px, ${y}px)`;\n\n if (displayInfo && typeof displayInfo === 'object' && 'style' in displayInfo) {\n Object.assign(el.style, displayInfo.style);\n }\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport LayerManager from './layer-manager';\nimport ViewManager from './view-manager';\nimport MapView from '../views/map-view';\nimport EffectManager from './effect-manager';\nimport DeckRenderer from './deck-renderer';\nimport DeckPicker from './deck-picker';\nimport {Widget} from './widget';\nimport {WidgetManager} from './widget-manager';\nimport {TooltipWidget} from './tooltip-widget';\nimport log from '../utils/log';\nimport {deepEqual} from '../utils/deep-equal';\nimport typedArrayManager from '../utils/typed-array-manager';\nimport {VERSION} from './init';\n\nimport {luma} from '@luma.gl/core';\nimport {webgl2Adapter} from '@luma.gl/webgl';\nimport {GL} from '@luma.gl/webgl/constants';\nimport {Timeline} from '@luma.gl/engine';\nimport {AnimationLoop} from '@luma.gl/engine';\nimport type {CanvasContextProps, Device, DeviceProps, Framebuffer, Parameters} from '@luma.gl/core';\nimport type {ShaderModule} from '@luma.gl/shadertools';\n\nimport {Stats} from '@probe.gl/stats';\nimport {EventManager} from 'mjolnir.js';\n\nimport assert from '../utils/assert';\nimport {EVENT_HANDLERS, RECOGNIZERS, RecognizerOptions} from './constants';\n\nimport type {Effect} from './effect';\nimport type {FilterContext} from '../passes/layers-pass';\nimport type Layer from './layer';\nimport type View from '../views/view';\nimport type Viewport from '../viewports/viewport';\nimport type {EventManagerOptions, MjolnirGestureEvent, MjolnirPointerEvent} from 'mjolnir.js';\nimport type {TypedArrayManagerOptions} from '../utils/typed-array-manager';\nimport type {ViewStateChangeParameters, InteractionState} from '../controllers/controller';\nimport type {PickingInfo} from './picking/pick-info';\nimport type {PickByPointOptions, PickByRectOptions} from './deck-picker';\nimport type {LayersList} from './layer-manager';\nimport type {TooltipContent} from './tooltip-widget';\nimport type {ViewStateMap, AnyViewStateOf, ViewOrViews, ViewStateObject} from './view-manager';\nimport {CreateDeviceProps} from '@luma.gl/core';\n\n/* global document */\n\n// eslint-disable-next-line @typescript-eslint/no-empty-function\nfunction noop() {}\n\nconst getCursor = ({isDragging}) => (isDragging ? 'grabbing' : 'grab');\n\nexport type DeckMetrics = {\n fps: number;\n setPropsTime: number;\n layersCount: number;\n drawLayersCount: number;\n updateLayersCount: number;\n updateAttributesTime: number;\n updateAttributesCount: number;\n framesRedrawn: number;\n pickTime: number;\n pickCount: number;\n pickLayersCount: number;\n gpuTime: number;\n gpuTimePerFrame: number;\n cpuTime: number;\n cpuTimePerFrame: number;\n bufferMemory: number;\n textureMemory: number;\n renderbufferMemory: number;\n gpuMemory: number;\n};\n\ntype CursorState = {\n /** Whether the cursor is over a pickable object */\n isHovering: boolean;\n /** Whether the cursor is down */\n isDragging: boolean;\n};\n\ntype InternalPickingMode = 'sync' | 'async';\ntype PointPickResult = {\n result: PickingInfo[];\n emptyInfo: PickingInfo;\n};\n\nexport type DeckProps = {\n /** Id of this Deck instance */\n id?: string;\n /** Width of the canvas, a number in pixels or a valid CSS string.\n * @default `'100%'`\n */\n width?: string | number | null;\n /** Height of the canvas, a number in pixels or a valid CSS string.\n * @default `'100%'`\n */\n height?: string | number | null;\n /** Additional CSS styles for the canvas. */\n style?: Partial | null;\n\n /** Controls the resolution of drawing buffer used for rendering.\n * @default `true` (use browser devicePixelRatio)\n */\n useDevicePixels?: boolean | number;\n /** Extra pixels around the pointer to include while picking.\n * @default `0`\n */\n pickingRadius?: number;\n /** Selects the internal picking policy used by deck-managed events and controllers.\n * @default `'auto'`\n */\n pickAsync?: InternalPickingMode | 'auto';\n\n /** WebGL parameters to be set before each frame is rendered. */\n parameters?: Parameters;\n /** If supplied, will be called before a layer is drawn to determine whether it should be rendered. */\n layerFilter?: ((context: FilterContext) => boolean) | null;\n\n /** The container to append the auto-created canvas to.\n * @default `document.body`\n */\n parent?: HTMLDivElement | null;\n\n /** The canvas to render into.\n * Can be either a HTMLCanvasElement or the element id.\n * Will be auto-created if not supplied.\n */\n canvas?: HTMLCanvasElement | string | null;\n\n /** Use an existing luma.gl GPU device. @note If not supplied, a new device will be created using props.deviceProps */\n device?: Device | null;\n\n /** A new device will be created using these props, assuming that an existing device is not supplied using props.device) */\n deviceProps?: CreateDeviceProps;\n\n /** WebGL context @deprecated Use props.deviceProps.webgl. Also note that preserveDrawingBuffers is true by default */\n gl?: WebGL2RenderingContext | null;\n\n /**\n * The array of Layer instances to be rendered.\n * Nested arrays are accepted, as well as falsy values (`null`, `false`, `undefined`)\n */\n layers?: LayersList;\n /** The array of effects to be rendered. A lighting effect will be added if an empty array is supplied. */\n effects?: Effect[];\n /** A single View instance, or an array of `View` instances.\n * @default `new MapView()`\n */\n views?: ViewsT;\n /** Options for viewport interactivity, e.g. pan, rotate and zoom with mouse, touch and keyboard.\n * This is a shorthand for defining interaction with the `views` prop if you are using the default view (i.e. a single `MapView`)\n */\n controller?: View['props']['controller'];\n /**\n * An object that describes the view state for each view in the `views` prop.\n * Use if the camera state should be managed external to the `Deck` instance.\n */\n viewState?: ViewStateMap | null;\n /**\n * If provided, the `Deck` instance will track camera state changes automatically,\n * with `initialViewState` as its initial settings.\n */\n initialViewState?: ViewStateMap | null;\n\n /** Allow browser default touch actions.\n * @default `'none'`\n */\n touchAction?: EventManagerOptions['touchAction'];\n /**\n * Optional mjolnir.js recognizer options\n */\n eventRecognizerOptions?: RecognizerOptions;\n\n /** (Experimental) Render to a custom frame buffer other than to screen. */\n _framebuffer?: Framebuffer | null;\n /** (Experimental) Forces deck.gl to redraw layers every animation frame. */\n _animate?: boolean;\n /** (Experimental) If set to `false`, force disables all picking features, disregarding the `pickable` prop set in any layer. */\n _pickable?: boolean;\n /** (Experimental) Fine-tune attribute memory usage. See documentation for details. */\n _typedArrayManagerProps?: TypedArrayManagerOptions;\n /** An array of Widget instances to be added to the parent element. */\n widgets?: Widget[];\n\n /** Called once the GPU Device has been initiated. */\n onDeviceInitialized?: (device: Device) => void;\n /** @deprecated Called once the WebGL context has been initiated. */\n onWebGLInitialized?: (gl: WebGL2RenderingContext) => void;\n /** Called when the canvas resizes. */\n onResize?: (dimensions: {width: number; height: number}) => void;\n /** Called when the user has interacted with the deck.gl canvas, e.g. using mouse, touch or keyboard. */\n onViewStateChange?: >(\n params: ViewStateChangeParameters\n ) => ViewStateT | null | void;\n /** Called when the user has interacted with the deck.gl canvas, e.g. using mouse, touch or keyboard. */\n onInteractionStateChange?: (state: InteractionState) => void;\n /** Called just before the canvas rerenders. */\n onBeforeRender?: (context: {device: Device; gl: WebGL2RenderingContext}) => void;\n /** Called right after the canvas rerenders. */\n onAfterRender?: (context: {device: Device; gl: WebGL2RenderingContext}) => void;\n /** Called once after gl context and all Deck components are created. */\n onLoad?: () => void;\n /** Called if deck.gl encounters an error.\n * If this callback is set to `null`, errors are silently ignored.\n * @default `console.error`\n */\n onError?: ((error: Error, layer?: Layer) => void) | null;\n /** Called when the pointer moves over the canvas. */\n onHover?: ((info: PickingInfo, event: MjolnirPointerEvent) => void) | null;\n /** Called when clicking on the canvas. */\n onClick?: ((info: PickingInfo, event: MjolnirGestureEvent) => void) | null;\n /** Called when the user starts dragging on the canvas. */\n onDragStart?: ((info: PickingInfo, event: MjolnirGestureEvent) => void) | null;\n /** Called when dragging the canvas. */\n onDrag?: ((info: PickingInfo, event: MjolnirGestureEvent) => void) | null;\n /** Called when the user releases from dragging the canvas. */\n onDragEnd?: ((info: PickingInfo, event: MjolnirGestureEvent) => void) | null;\n\n /** (Experimental) Replace the default redraw procedure */\n _customRender?: ((reason: string) => void) | null;\n /** (Experimental) Called once every second with performance metrics. */\n _onMetrics?: ((metrics: DeckMetrics) => void) | null;\n\n /** A custom callback to retrieve the cursor type. */\n getCursor?: (state: CursorState) => string;\n /** Callback that takes a hovered-over point and renders a tooltip. */\n getTooltip?: ((info: PickingInfo) => TooltipContent) | null;\n\n /** (Debug) Flag to enable WebGL debug mode. Requires importing `@luma.gl/debug`. */\n debug?: boolean;\n /** (Debug) Render the picking buffer to screen. */\n drawPickingColors?: boolean;\n};\n\nconst defaultProps: DeckProps = {\n id: '',\n width: '100%',\n height: '100%',\n style: null,\n viewState: null,\n initialViewState: null,\n pickingRadius: 0,\n pickAsync: 'auto',\n layerFilter: null,\n parameters: {},\n parent: null,\n device: null,\n deviceProps: {} as DeviceProps,\n gl: null,\n canvas: null,\n layers: [],\n effects: [],\n views: null,\n controller: null, // Rely on external controller, e.g. react-map-gl\n useDevicePixels: true,\n touchAction: 'none',\n eventRecognizerOptions: {},\n _framebuffer: null,\n _animate: false,\n _pickable: true,\n _typedArrayManagerProps: {},\n _customRender: null,\n widgets: [],\n\n onDeviceInitialized: noop,\n onWebGLInitialized: noop,\n onResize: noop,\n onViewStateChange: noop,\n onInteractionStateChange: noop,\n onBeforeRender: noop,\n onAfterRender: noop,\n onLoad: noop,\n onError: (error: Error) => log.error(error.message, error.cause)(),\n onHover: null,\n onClick: null,\n onDragStart: null,\n onDrag: null,\n onDragEnd: null,\n _onMetrics: null,\n\n getCursor,\n getTooltip: null,\n\n debug: false,\n drawPickingColors: false\n};\n\n/* eslint-disable max-statements */\nexport default class Deck {\n static defaultProps = defaultProps;\n // This is used to defeat tree shaking of init.js\n // https://github.com/visgl/deck.gl/issues/3213\n static VERSION = VERSION;\n\n readonly props: Required>;\n readonly width: number = 0;\n readonly height: number = 0;\n // Allows attaching arbitrary data to the instance\n readonly userData: Record = {};\n\n protected device: Device | null = null;\n\n protected canvas: HTMLCanvasElement | null = null;\n protected viewManager: ViewManager | null = null;\n protected layerManager: LayerManager | null = null;\n protected effectManager: EffectManager | null = null;\n protected deckRenderer: DeckRenderer | null = null;\n protected deckPicker: DeckPicker | null = null;\n protected eventManager: EventManager | null = null;\n protected widgetManager: WidgetManager | null = null;\n protected tooltip: TooltipWidget | null = null;\n protected animationLoop: AnimationLoop | null = null;\n\n /** Internal view state if no callback is supplied */\n protected viewState: ViewStateObject | null;\n protected cursorState: CursorState = {\n isHovering: false,\n isDragging: false\n };\n\n protected stats = new Stats({id: 'deck.gl'});\n protected metrics: DeckMetrics = {\n fps: 0,\n setPropsTime: 0,\n layersCount: 0,\n drawLayersCount: 0,\n updateLayersCount: 0,\n updateAttributesCount: 0,\n updateAttributesTime: 0,\n framesRedrawn: 0,\n pickTime: 0,\n pickCount: 0,\n pickLayersCount: 0,\n gpuTime: 0,\n gpuTimePerFrame: 0,\n cpuTime: 0,\n cpuTimePerFrame: 0,\n bufferMemory: 0,\n textureMemory: 0,\n renderbufferMemory: 0,\n gpuMemory: 0\n };\n private _metricsCounter: number = 0;\n private _hoverPickSequence: number = 0;\n private _pointerDownPickSequence: number = 0;\n\n private _needsRedraw: false | string = 'Initial render';\n private _pickRequest: {\n mode: string;\n event: MjolnirPointerEvent | null;\n x: number;\n y: number;\n radius: number;\n unproject3D?: boolean;\n } = {\n mode: 'hover',\n x: -1,\n y: -1,\n radius: 0,\n event: null,\n unproject3D: false\n };\n\n /**\n * Pick and store the object under the pointer on `pointerdown`.\n * This object is reused for subsequent `onClick` and `onDrag*` callbacks.\n */\n private _lastPointerDownInfo: PickingInfo | null = null;\n private _lastPointerDownInfoPromise: Promise | null = null;\n\n constructor(props: DeckProps) {\n // @ts-ignore views\n this.props = {...defaultProps, ...props};\n props = this.props;\n\n if (props.viewState && props.initialViewState) {\n log.warn(\n 'View state tracking is disabled. Use either `initialViewState` for auto update or `viewState` for manual update.'\n )();\n }\n this.viewState = this.props.initialViewState;\n\n // See if we already have a device\n if (props.device) {\n this.device = props.device;\n }\n\n let deviceOrPromise: Device | Promise | null = this.device;\n\n // Attach a new luma.gl device to a WebGL2 context if supplied\n if (!deviceOrPromise && props.gl) {\n if (props.gl instanceof WebGLRenderingContext) {\n log.error('WebGL1 context not supported.')();\n }\n // Preserve user's callbacks and add resize handling\n const userOnResize = this.props.deviceProps?.onResize;\n\n deviceOrPromise = webgl2Adapter.attach(props.gl, {\n // Enable shader and pipeline caching for attached devices (matches _createDevice defaults)\n // Without this, interleaved mode (e.g., MapboxOverlay) creates new pipelines every frame\n _cacheShaders: true,\n _cachePipelines: true,\n ...this.props.deviceProps,\n onResize: (canvasContext, info) => {\n // Sync drawing buffer dimensions with externally-managed canvas\n const {width, height} = canvasContext.canvas;\n canvasContext.setDrawingBufferSize(width, height);\n\n this._needsRedraw = 'Canvas resized';\n userOnResize?.(canvasContext, info);\n }\n });\n }\n\n // Create a new device\n if (!deviceOrPromise) {\n deviceOrPromise = this._createDevice(props);\n }\n\n this.animationLoop = this._createAnimationLoop(deviceOrPromise, props);\n\n this.setProps(props);\n\n // UNSAFE/experimental prop: only set at initialization to avoid performance hit\n if (props._typedArrayManagerProps) {\n typedArrayManager.setOptions(props._typedArrayManagerProps);\n }\n\n this.animationLoop.start();\n }\n\n /** Stop rendering and dispose all resources */\n finalize() {\n this.animationLoop?.stop();\n this.animationLoop?.destroy();\n this.animationLoop = null;\n this._hoverPickSequence++;\n this._pointerDownPickSequence++;\n this._lastPointerDownInfo = null;\n this._lastPointerDownInfoPromise = null;\n\n this.layerManager?.finalize();\n this.layerManager = null;\n\n this.viewManager?.finalize();\n this.viewManager = null;\n\n this.effectManager?.finalize();\n this.effectManager = null;\n\n this.deckRenderer?.finalize();\n this.deckRenderer = null;\n\n this.deckPicker?.finalize();\n this.deckPicker = null;\n\n this.eventManager?.destroy();\n this.eventManager = null;\n\n this.widgetManager?.finalize();\n this.widgetManager = null;\n\n if (!this.props.canvas && !this.props.device && !this.props.gl && this.canvas) {\n // remove internally created canvas\n this.canvas.parentElement?.removeChild(this.canvas);\n this.canvas = null;\n }\n }\n\n /** Partially update props */\n setProps(props: DeckProps): void {\n this.stats.get('setProps Time').timeStart();\n\n if ('onLayerHover' in props) {\n log.removed('onLayerHover', 'onHover')();\n }\n if ('onLayerClick' in props) {\n log.removed('onLayerClick', 'onClick')();\n }\n if (\n props.initialViewState &&\n // depth = 3 when comparing viewStates: viewId.position.0\n !deepEqual(this.props.initialViewState, props.initialViewState, 3)\n ) {\n // Overwrite internal view state\n this.viewState = props.initialViewState;\n }\n\n // Merge with existing props\n Object.assign(this.props, props);\n this._validateInternalPickingMode();\n\n // Update CSS size of canvas\n this._setCanvasSize(this.props);\n\n // We need to overwrite CSS style width and height with actual, numeric values\n const resolvedProps: Required & {\n width: number;\n height: number;\n views: View[];\n viewState: ViewStateObject | null;\n } = Object.create(this.props);\n Object.assign(resolvedProps, {\n views: this._getViews(),\n width: this.width,\n height: this.height,\n viewState: this._getViewState()\n });\n\n if (props.device && props.device.id !== this.device?.id) {\n this.animationLoop?.stop();\n if (this.canvas !== props.device.canvasContext?.canvas) {\n // remove old canvas if new one being used and de-register events\n // TODO (ck): We might not own this canvas depending it's source, so removing it from the\n // DOM here might be a bit unexpected but it should be ok for most users.\n this.canvas?.remove();\n this.eventManager?.destroy();\n\n // ensure we will re-attach ourselves after createDevice callbacks\n this.canvas = null;\n }\n\n log.log(`recreating animation loop for new device! id=${props.device.id}`)();\n\n this.animationLoop = this._createAnimationLoop(props.device, props);\n this.animationLoop.start();\n }\n\n // Update the animation loop\n this.animationLoop?.setProps(resolvedProps);\n\n if (props.useDevicePixels !== undefined && this.device?.canvasContext?.setProps) {\n this.device.canvasContext.setProps({useDevicePixels: props.useDevicePixels});\n }\n\n // If initialized, update sub manager props\n if (this.layerManager) {\n this.viewManager!.setProps(resolvedProps);\n // Make sure that any new layer gets initialized with the current viewport\n this.layerManager.activateViewport(this.getViewports()[0]);\n this.layerManager.setProps(resolvedProps);\n this.effectManager!.setProps(resolvedProps);\n this.deckRenderer!.setProps(resolvedProps);\n this.deckPicker!.setProps(resolvedProps);\n this.widgetManager!.setProps(resolvedProps);\n }\n\n this.stats.get('setProps Time').timeEnd();\n }\n\n // Public API\n\n /**\n * Check if a redraw is needed\n * @returns `false` or a string summarizing the redraw reason\n */\n needsRedraw(\n opts: {\n /** Reset the redraw flag afterwards. Default `true` */\n clearRedrawFlags: boolean;\n } = {clearRedrawFlags: false}\n ): false | string {\n if (!this.layerManager) {\n // Not initialized or already finalized\n return false;\n }\n if (this.props._animate) {\n return 'Deck._animate';\n }\n\n let redraw: false | string = this._needsRedraw;\n\n if (opts.clearRedrawFlags) {\n this._needsRedraw = false;\n }\n\n const viewManagerNeedsRedraw = this.viewManager!.needsRedraw(opts);\n const layerManagerNeedsRedraw = this.layerManager.needsRedraw(opts);\n const effectManagerNeedsRedraw = this.effectManager!.needsRedraw(opts);\n const deckRendererNeedsRedraw = this.deckRenderer!.needsRedraw(opts);\n\n redraw =\n redraw ||\n viewManagerNeedsRedraw ||\n layerManagerNeedsRedraw ||\n effectManagerNeedsRedraw ||\n deckRendererNeedsRedraw;\n return redraw;\n }\n\n /**\n * Redraw the GL context\n * @param reason If not provided, only redraw if deemed necessary. Otherwise redraw regardless of internal states.\n * @returns\n */\n redraw(reason?: string): void {\n if (!this.layerManager) {\n // Not yet initialized\n return;\n }\n // Check if we need to redraw\n let redrawReason = this.needsRedraw({clearRedrawFlags: true});\n // User-supplied should take precedent, however the redraw flags get cleared regardless\n redrawReason = reason || redrawReason;\n\n if (!redrawReason) {\n return;\n }\n\n this.stats.get('Redraw Count').incrementCount();\n if (this.props._customRender) {\n this.props._customRender(redrawReason);\n } else {\n this._drawLayers(redrawReason);\n }\n }\n\n /** Flag indicating that the Deck instance has initialized its resources and it's safe to call public methods. */\n get isInitialized(): boolean {\n return this.viewManager !== null;\n }\n\n /** Get a list of views that are currently rendered */\n getViews(): View[] {\n assert(this.viewManager);\n return this.viewManager.views;\n }\n\n /** Get a view by id */\n getView(viewId: string): View | undefined {\n assert(this.viewManager);\n return this.viewManager.getView(viewId);\n }\n\n /** Get a list of viewports that are currently rendered.\n * @param rect If provided, only returns viewports within the given bounding box.\n */\n getViewports(rect?: {x: number; y: number; width?: number; height?: number}): Viewport[] {\n assert(this.viewManager);\n return this.viewManager.getViewports(rect);\n }\n\n /** Get the current canvas element. */\n getCanvas(): HTMLCanvasElement | null {\n return this.canvas;\n }\n\n /** Query the object rendered on top at a given point */\n async pickObjectAsync(opts: {\n /** x position in pixels */\n x: number;\n /** y position in pixels */\n y: number;\n /** Radius of tolerance in pixels. Default `0`. */\n radius?: number;\n /** A list of layer ids to query from. If not specified, then all pickable and visible layers are queried. */\n layerIds?: string[];\n /** If `true`, `info.coordinate` will be a 3D point by unprojecting the `x, y` screen coordinates onto the picked geometry. Default `false`. */\n unproject3D?: boolean;\n }): Promise {\n const infos = (await this._pickAsync('pickObjectAsync', 'pickObject Time', opts)).result;\n return infos.length ? infos[0] : null;\n }\n\n /**\n * Query all objects rendered on top within a bounding box\n * @note Caveat: this method performs multiple async GPU queries, so state could potentially change between calls.\n */\n async pickObjectsAsync(opts: {\n /** Left of the bounding box in pixels */\n x: number;\n /** Top of the bounding box in pixels */\n y: number;\n /** Width of the bounding box in pixels. Default `1` */\n width?: number;\n /** Height of the bounding box in pixels. Default `1` */\n height?: number;\n /** A list of layer ids to query from. If not specified, then all pickable and visible layers are queried. */\n layerIds?: string[];\n /** If specified, limits the number of objects that can be returned. */\n maxObjects?: number | null;\n }): Promise {\n return await this._pickAsync('pickObjectsAsync', 'pickObjects Time', opts);\n }\n\n /**\n * Query the object rendered on top at a given point\n * @deprecated WebGL only. Use `pickObjectsAsync` instead\n */\n pickObject(opts: {\n /** x position in pixels */\n x: number;\n /** y position in pixels */\n y: number;\n /** Radius of tolerance in pixels. Default `0`. */\n radius?: number;\n /** A list of layer ids to query from. If not specified, then all pickable and visible layers are queried. */\n layerIds?: string[];\n /** If `true`, `info.coordinate` will be a 3D point by unprojecting the `x, y` screen coordinates onto the picked geometry. Default `false`. */\n unproject3D?: boolean;\n }): PickingInfo | null {\n const infos = this._pick('pickObject', 'pickObject Time', opts).result;\n return infos.length ? infos[0] : null;\n }\n\n /**\n * Query all rendered objects at a given point\n * @deprecated WebGL only. Use `pickObjectsAsync` instead\n */\n pickMultipleObjects(opts: {\n /** x position in pixels */\n x: number;\n /** y position in pixels */\n y: number;\n /** Radius of tolerance in pixels. Default `0`. */\n radius?: number;\n /** Specifies the max number of objects to return. Default `10`. */\n depth?: number;\n /** A list of layer ids to query from. If not specified, then all pickable and visible layers are queried. */\n layerIds?: string[];\n /** If `true`, `info.coordinate` will be a 3D point by unprojecting the `x, y` screen coordinates onto the picked geometry. Default `false`. */\n unproject3D?: boolean;\n }): PickingInfo[] {\n opts.depth = opts.depth || 10;\n return this._pick('pickObject', 'pickMultipleObjects Time', opts).result;\n }\n\n /**\n * Query all objects rendered on top within a bounding box\n * @deprecated WebGL only. Use `pickObjectsAsync` instead\n */\n pickObjects(opts: {\n /** Left of the bounding box in pixels */\n x: number;\n /** Top of the bounding box in pixels */\n y: number;\n /** Width of the bounding box in pixels. Default `1` */\n width?: number;\n /** Height of the bounding box in pixels. Default `1` */\n height?: number;\n /** A list of layer ids to query from. If not specified, then all pickable and visible layers are queried. */\n layerIds?: string[];\n /** If specified, limits the number of objects that can be returned. */\n maxObjects?: number | null;\n }): PickingInfo[] {\n return this._pick('pickObjects', 'pickObjects Time', opts);\n }\n\n /**\n * Internal method used by controllers to pick 3D position at a screen coordinate\n * @private\n */\n private _pickPositionForController(x: number, y: number): {coordinate?: number[]} | null {\n const internalPickingMode = this._getInternalPickingMode();\n if (internalPickingMode !== 'sync') {\n return null;\n }\n\n return this.pickObject({x, y, radius: 0, unproject3D: true});\n }\n\n /** Experimental\n * Add a global resource for sharing among layers\n */\n _addResources(\n resources: {\n [id: string]: any;\n },\n forceUpdate = false\n ) {\n for (const id in resources) {\n this.layerManager!.resourceManager.add({resourceId: id, data: resources[id], forceUpdate});\n }\n }\n\n /** Experimental\n * Remove a global resource\n */\n _removeResources(resourceIds: string[]) {\n for (const id of resourceIds) {\n this.layerManager!.resourceManager.remove(id);\n }\n }\n\n /** Experimental\n * Register a default effect. Effects will be sorted by order, those with a low order will be rendered first\n */\n _addDefaultEffect(effect: Effect) {\n this.effectManager!.addDefaultEffect(effect);\n }\n\n _addDefaultShaderModule(module: ShaderModule>) {\n this.layerManager!.addDefaultShaderModule(module);\n }\n\n _removeDefaultShaderModule(module: ShaderModule>) {\n this.layerManager?.removeDefaultShaderModule(module);\n }\n\n // Private Methods\n\n private _resolveInternalPickingMode(): InternalPickingMode {\n const {pickAsync} = this.props;\n const deviceType = this.device?.type || this.props.deviceProps?.type;\n\n if (pickAsync === 'auto') {\n return deviceType === 'webgpu' ? 'async' : 'sync';\n }\n if (pickAsync === 'sync' && deviceType === 'webgpu') {\n throw new Error('`pickAsync: \"sync\"` is not supported when Deck is using a WebGPU device.');\n }\n return pickAsync;\n }\n\n private _getInternalPickingMode(): InternalPickingMode | null {\n try {\n return this._resolveInternalPickingMode();\n } catch (error) {\n this.props.onError?.(error as Error);\n return null;\n }\n }\n\n private _validateInternalPickingMode(): void {\n this._getInternalPickingMode();\n }\n\n private _getFirstPickedInfo({result, emptyInfo}: PointPickResult): PickingInfo {\n return result[0] || emptyInfo;\n }\n\n private _shouldUnproject3D(layers = this.layerManager?.getLayers() || []): boolean {\n return layers.some(layer => layer.props.pickable === '3d');\n }\n\n private _getPointPickOptions(\n x: number,\n y: number,\n opts: Partial = {},\n layers = this.layerManager?.getLayers() || []\n ): PickByPointOptions {\n return {\n x,\n y,\n radius: this.props.pickingRadius,\n unproject3D: this._shouldUnproject3D(layers),\n ...opts\n };\n }\n\n private _pickPointSync(opts: PickByPointOptions): PointPickResult {\n return this._pick('pickObject', 'pickObject Time', opts);\n }\n\n private _pickPointAsync(opts: PickByPointOptions): Promise {\n return this._pickAsync('pickObjectAsync', 'pickObject Time', opts);\n }\n\n private _getLastPointerDownPickingInfo(\n x: number,\n y: number,\n layers = this.layerManager?.getLayers() || []\n ): PickingInfo {\n return this.deckPicker!.getLastPickedObject(\n {\n x,\n y,\n layers,\n viewports: this.getViewports({x, y})\n },\n this._lastPointerDownInfo\n ) as PickingInfo;\n }\n\n private _applyHoverCallbacks(\n {result, emptyInfo}: PointPickResult,\n event: MjolnirPointerEvent\n ): void {\n if (!this.widgetManager) {\n return;\n }\n\n this.cursorState.isHovering = result.length > 0;\n\n let pickedInfo = emptyInfo;\n let handled = false;\n for (const info of result) {\n pickedInfo = info;\n handled = info.layer?.onHover(info, event) || handled;\n }\n if (!handled) {\n this.props.onHover?.(pickedInfo, event);\n this.widgetManager.onHover(pickedInfo, event);\n }\n }\n\n private _dispatchPickingEvent(info: PickingInfo, event: MjolnirGestureEvent): void {\n if (!this.layerManager || !this.widgetManager) {\n return;\n }\n\n const eventHandlerProp = EVENT_HANDLERS[event.type];\n if (!eventHandlerProp) {\n return;\n }\n\n const {layer} = info;\n const layerHandler = layer && (layer[eventHandlerProp] || layer.props[eventHandlerProp]);\n const rootHandler = this.props[eventHandlerProp];\n let handled = false;\n\n if (layerHandler) {\n handled = layerHandler.call(layer, info, event);\n }\n if (!handled) {\n rootHandler?.(info, event);\n this.widgetManager.onEvent(info, event);\n }\n }\n\n private _pickAsync(\n method: 'pickObjectAsync',\n statKey: string,\n opts: PickByPointOptions & {layerIds?: string[]}\n ): Promise<{\n result: PickingInfo[];\n emptyInfo: PickingInfo;\n }>;\n private _pickAsync(\n method: 'pickObjectsAsync',\n statKey: string,\n opts: PickByRectOptions & {layerIds?: string[]}\n ): Promise;\n\n private _pickAsync(\n method: 'pickObjectAsync' | 'pickObjectsAsync',\n statKey: string,\n opts: (PickByPointOptions | PickByRectOptions) & {layerIds?: string[]}\n ) {\n assert(this.deckPicker);\n\n const {stats} = this;\n\n stats.get('Pick Count').incrementCount();\n stats.get(statKey).timeStart();\n\n const infos = this.deckPicker[method]({\n // layerManager, viewManager and effectManager are always defined if deckPicker is\n layers: this.layerManager!.getLayers(opts),\n views: this.viewManager!.getViews(),\n viewports: this.getViewports(opts),\n onViewportActive: this.layerManager!.activateViewport,\n effects: this.effectManager!.getEffects(),\n ...opts\n });\n\n stats.get(statKey).timeEnd();\n\n return infos;\n }\n\n private _pick(\n method: 'pickObject',\n statKey: string,\n opts: PickByPointOptions & {layerIds?: string[]}\n ): {\n result: PickingInfo[];\n emptyInfo: PickingInfo;\n };\n private _pick(\n method: 'pickObjects',\n statKey: string,\n opts: PickByRectOptions & {layerIds?: string[]}\n ): PickingInfo[];\n\n private _pick(\n method: 'pickObject' | 'pickObjects',\n statKey: string,\n opts: (PickByPointOptions | PickByRectOptions) & {layerIds?: string[]}\n ) {\n assert(this.deckPicker);\n\n const {stats} = this;\n\n stats.get('Pick Count').incrementCount();\n stats.get(statKey).timeStart();\n\n const infos = this.deckPicker[method]({\n // layerManager, viewManager and effectManager are always defined if deckPicker is\n layers: this.layerManager!.getLayers(opts),\n views: this.viewManager!.getViews(),\n viewports: this.getViewports(opts),\n onViewportActive: this.layerManager!.activateViewport,\n effects: this.effectManager!.getEffects(),\n ...opts\n });\n\n stats.get(statKey).timeEnd();\n\n return infos;\n }\n\n /** Resolve props.canvas to element */\n private _createCanvas(props: DeckProps): HTMLCanvasElement {\n let canvas = props.canvas;\n\n // TODO EventManager should accept element id\n if (typeof canvas === 'string') {\n canvas = document.getElementById(canvas) as HTMLCanvasElement;\n assert(canvas);\n }\n\n if (!canvas) {\n canvas = document.createElement('canvas');\n canvas.id = props.id || 'deckgl-overlay';\n\n // TODO this is a hack, investigate why these are not set for the picking\n // tests\n if (props.width && typeof props.width === 'number') {\n canvas.width = props.width;\n }\n if (props.height && typeof props.height === 'number') {\n canvas.height = props.height;\n }\n const parent = props.parent || document.body;\n parent.appendChild(canvas);\n }\n\n Object.assign(canvas.style, props.style);\n\n return canvas;\n }\n\n /** Updates canvas width and/or height, if provided as props */\n private _setCanvasSize(props: Required>): void {\n if (!this.canvas) {\n return;\n }\n\n const {width, height} = props;\n // Set size ONLY if props are being provided, otherwise let canvas be layouted freely\n if (width || width === 0) {\n const cssWidth = Number.isFinite(width) ? `${width}px` : (width as string);\n this.canvas.style.width = cssWidth;\n }\n if (height || height === 0) {\n const cssHeight = Number.isFinite(height) ? `${height}px` : (height as string);\n // Note: position==='absolute' required for height 100% to work\n this.canvas.style.position = props.style?.position || 'absolute';\n this.canvas.style.height = cssHeight;\n }\n }\n\n /** If canvas size has changed, reads out the new size and update */\n private _updateCanvasSize(): void {\n const {canvas} = this;\n if (!canvas) {\n return;\n }\n // Fallback to width/height when clientWidth/clientHeight are undefined (OffscreenCanvas).\n const newWidth = canvas.clientWidth ?? canvas.width;\n const newHeight = canvas.clientHeight ?? canvas.height;\n if (newWidth !== this.width || newHeight !== this.height) {\n // @ts-expect-error private assign to read-only property\n this.width = newWidth;\n // @ts-expect-error private assign to read-only property\n this.height = newHeight;\n this.viewManager?.setProps({width: newWidth, height: newHeight});\n // Make sure that any new layer gets initialized with the current viewport\n this.layerManager?.activateViewport(this.getViewports()[0]);\n this.props.onResize({width: newWidth, height: newHeight});\n }\n }\n\n private _createAnimationLoop(\n deviceOrPromise: Device | Promise,\n props: DeckProps\n ): AnimationLoop {\n const {\n // width,\n // height,\n gl,\n // debug,\n onError\n // onBeforeRender,\n // onAfterRender,\n } = props;\n\n return new AnimationLoop({\n device: deviceOrPromise,\n // TODO v9\n autoResizeDrawingBuffer: !gl, // do not auto resize external context\n autoResizeViewport: false,\n // @ts-expect-error luma.gl needs to accept Promise return value\n onInitialize: context => this._setDevice(context.device),\n onRender: this._onRenderFrame.bind(this),\n // @ts-expect-error typing mismatch: AnimationLoop does not accept onError:null\n onError\n\n // onBeforeRender,\n // onAfterRender,\n });\n }\n\n // Create a device from the deviceProps, assigning required defaults\n private _createDevice(props: DeckProps): Promise {\n const canvasContextUserProps = this.props.deviceProps?.createCanvasContext;\n const canvasContextProps =\n typeof canvasContextUserProps === 'object' ? canvasContextUserProps : undefined;\n\n // In deck.gl v9, Deck always bundles and adds a webgl2Adapter.\n // This behavior is expected to change in deck.gl v10 to support WebGPU only builds.\n const deviceProps = {\n adapters: [],\n _cacheShaders: true,\n _cachePipelines: true,\n ...props.deviceProps\n };\n if (!deviceProps.adapters.includes(webgl2Adapter)) {\n deviceProps.adapters.push(webgl2Adapter);\n }\n\n const defaultCanvasProps: CanvasContextProps = {\n // we must use 'premultiplied' canvas for webgpu to enable transparency and match shaders\n alphaMode: this.props.deviceProps?.type === 'webgpu' ? 'premultiplied' : undefined\n };\n\n // Preserve user's onResize callback\n const userOnResize = this.props.deviceProps?.onResize;\n\n // Create the \"best\" device supported from the registered adapters\n return luma.createDevice({\n // luma by default throws if a device is already attached\n // asynchronous device creation could happen after finalize() is called\n // TODO - createDevice should support AbortController?\n _reuseDevices: true,\n // tests can't handle WebGPU devices yet so we force WebGL2 unless overridden\n type: 'webgl',\n ...deviceProps,\n // In deck.gl v10 we may emphasize multi canvas support and unwind this prop wrapping\n createCanvasContext: {\n ...defaultCanvasProps,\n ...canvasContextProps,\n canvas: this._createCanvas(props),\n useDevicePixels: this.props.useDevicePixels,\n autoResize: true\n },\n onResize: (canvasContext, info) => {\n // Set redraw flag when luma.gl's CanvasContext detects a resize\n // This restores pre-9.2 behavior where resize automatically triggered redraws\n this._needsRedraw = 'Canvas resized';\n // Call user's onResize if provided\n userOnResize?.(canvasContext, info);\n }\n });\n }\n\n // Get the most relevant view state: props.viewState, if supplied, shadows internal viewState\n // TODO: For backwards compatibility ensure numeric width and height is added to the viewState\n private _getViewState(): ViewStateObject | null {\n return this.props.viewState || this.viewState;\n }\n\n // Get the view descriptor list\n private _getViews(): View[] {\n const {views} = this.props;\n const normalizedViews: View[] = Array.isArray(views)\n ? views\n : // If null, default to a full screen map view port\n views\n ? [views]\n : [new MapView({id: 'default-view'})];\n if (normalizedViews.length && this.props.controller) {\n // Backward compatibility: support controller prop\n normalizedViews[0].props.controller = this.props.controller;\n }\n return normalizedViews;\n }\n\n private _onContextLost() {\n const {onError} = this.props;\n if (this.animationLoop && onError) {\n onError(new Error('WebGL context is lost'));\n }\n }\n\n // The `pointermove` event may fire multiple times in between two animation frames,\n // it's a waste of time to run picking without rerender. Instead we save the last pick\n // request and only do it once on the next animation frame.\n /** Internal use only: event handler for pointerdown */\n _onPointerMove = (event: MjolnirPointerEvent) => {\n const {_pickRequest} = this;\n if (event.type === 'pointerleave') {\n _pickRequest.x = -1;\n _pickRequest.y = -1;\n _pickRequest.radius = 0;\n } else if (event.leftButton || event.rightButton) {\n // Do not trigger onHover callbacks if mouse button is down.\n return;\n } else {\n const pos = event.offsetCenter;\n // Do not trigger callbacks when click/hover position is invalid. Doing so will cause a\n // assertion error when attempting to unproject the position.\n if (!pos) {\n return;\n }\n _pickRequest.x = pos.x;\n _pickRequest.y = pos.y;\n _pickRequest.radius = this.props.pickingRadius;\n }\n\n if (this.layerManager) {\n this.layerManager.context.mousePosition = {x: _pickRequest.x, y: _pickRequest.y};\n }\n\n _pickRequest.event = event;\n };\n\n /** Actually run picking */\n private _pickAndCallback() {\n const {_pickRequest} = this;\n\n if (_pickRequest.event) {\n const event = _pickRequest.event;\n const layers = this.layerManager?.getLayers() || [];\n const pickOptions = this._getPointPickOptions(\n _pickRequest.x,\n _pickRequest.y,\n {\n radius: _pickRequest.radius,\n mode: _pickRequest.mode\n },\n layers\n );\n const internalPickingMode = this._getInternalPickingMode();\n const hoverPickSequence = ++this._hoverPickSequence;\n\n _pickRequest.event = null;\n\n if (!internalPickingMode) {\n return;\n }\n\n if (internalPickingMode === 'sync') {\n this._applyHoverCallbacks(this._pickPointSync(pickOptions), event);\n return;\n }\n\n this._pickPointAsync(pickOptions)\n .then(({result, emptyInfo}) => {\n if (hoverPickSequence === this._hoverPickSequence) {\n this._applyHoverCallbacks({result, emptyInfo}, event);\n }\n })\n .catch(error => this.props.onError?.(error));\n }\n }\n\n private _updateCursor(): void {\n const container = this.props.parent || this.canvas;\n if (container) {\n container.style.cursor = this.props.getCursor(this.cursorState);\n }\n }\n\n private _setDevice(device: Device) {\n this.device = device;\n this._validateInternalPickingMode();\n\n if (!this.animationLoop) {\n // finalize() has been called\n return;\n }\n\n // if external context...\n if (!this.canvas) {\n this.canvas = this.device.canvasContext?.canvas as HTMLCanvasElement;\n\n // external canvas may not be in DOM\n if (!this.canvas.isConnected && this.props.parent) {\n this.props.parent.insertBefore(this.canvas, this.props.parent.firstChild);\n }\n // TODO v9\n // ts-expect-error - Currently luma.gl v9 does not expose these options\n // All WebGLDevice contexts are instrumented, but it seems the device\n // should have a method to start state tracking even if not enabled?\n // instrumentGLContext(this.device.gl, {enable: true, copyState: true});\n }\n\n if (this.device.type === 'webgl') {\n this.device.setParametersWebGL({\n blend: true,\n blendFunc: [GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA, GL.ONE, GL.ONE_MINUS_SRC_ALPHA],\n polygonOffsetFill: true,\n depthTest: true,\n depthFunc: GL.LEQUAL\n });\n }\n\n this.props.onDeviceInitialized(this.device);\n if (this.device.type === 'webgl') {\n // Legacy callback - warn?\n // @ts-expect-error gl is not visible on Device base class\n this.props.onWebGLInitialized(this.device.gl);\n }\n\n // timeline for transitions\n const timeline = new Timeline();\n timeline.play();\n this.animationLoop.attachTimeline(timeline);\n\n const eventRoot =\n this.props.parent?.querySelector('.deck-events-root') || this.canvas;\n this.eventManager = new EventManager(eventRoot, {\n touchAction: this.props.touchAction,\n recognizers: Object.keys(RECOGNIZERS).map((eventName: string) => {\n // Resolve recognizer settings\n const [RecognizerConstructor, defaultOptions, recognizeWith, requestFailure] =\n RECOGNIZERS[eventName];\n const optionsOverride = this.props.eventRecognizerOptions?.[eventName];\n const options = {...defaultOptions, ...optionsOverride, event: eventName};\n return {\n recognizer: new RecognizerConstructor(options),\n recognizeWith,\n requestFailure\n };\n }),\n events: {\n pointerdown: this._onPointerDown,\n pointermove: this._onPointerMove,\n pointerleave: this._onPointerMove\n }\n });\n for (const eventType in EVENT_HANDLERS) {\n this.eventManager.on(eventType, this._onEvent);\n }\n\n this.viewManager = new ViewManager({\n timeline,\n eventManager: this.eventManager,\n onViewStateChange: this._onViewStateChange.bind(this),\n onInteractionStateChange: this._onInteractionStateChange.bind(this),\n pickPosition: this._pickPositionForController.bind(this),\n views: this._getViews(),\n viewState: this._getViewState(),\n width: this.width,\n height: this.height\n });\n\n // viewManager must be initialized before layerManager\n // layerManager depends on viewport created by viewManager.\n const viewport = this.viewManager.getViewports()[0];\n\n // Note: avoid React setState due GL animation loop / setState timing issue\n this.layerManager = new LayerManager(this.device, {\n deck: this,\n stats: this.stats,\n viewport,\n timeline\n });\n\n this.effectManager = new EffectManager({\n deck: this,\n device: this.device\n });\n\n this.deckRenderer = new DeckRenderer(this.device, {stats: this.stats});\n\n this.deckPicker = new DeckPicker(this.device, {stats: this.stats});\n\n const widgetParent =\n this.props.parent?.querySelector('.deck-widgets-root') ||\n this.canvas?.parentElement;\n\n this.widgetManager = new WidgetManager({\n deck: this,\n parentElement: widgetParent\n });\n this.widgetManager.addDefault(new TooltipWidget());\n\n this.setProps(this.props);\n\n this._updateCanvasSize();\n this.props.onLoad();\n }\n\n /** Internal only: default render function (redraw all layers and views) */\n _drawLayers(\n redrawReason: string,\n renderOptions?: {\n target?: Framebuffer;\n layerFilter?: (context: FilterContext) => boolean;\n layers?: Layer[];\n viewports?: Viewport[];\n views?: {[viewId: string]: View};\n pass?: string;\n effects?: Effect[];\n clearStack?: boolean;\n clearCanvas?: boolean;\n }\n ) {\n const {device, gl} = this.layerManager!.context;\n\n this.props.onBeforeRender({device, gl});\n\n const opts = {\n target: this.props._framebuffer,\n layers: this.layerManager!.getLayers(),\n viewports: this.viewManager!.getViewports(),\n onViewportActive: this.layerManager!.activateViewport,\n views: this.viewManager!.getViews(),\n pass: 'screen',\n effects: this.effectManager!.getEffects(),\n ...renderOptions\n };\n this.deckRenderer?.renderLayers(opts);\n\n if (opts.pass === 'screen') {\n // This method could be called when drawing to picking buffer, texture etc.\n // Only when drawing to screen, update all widgets (UI components)\n this.widgetManager!.onRedraw({\n viewports: opts.viewports,\n layers: opts.layers\n });\n }\n\n this.props.onAfterRender({device, gl});\n }\n\n // Callbacks\n\n private _onRenderFrame() {\n this._getFrameStats();\n\n // Log perf stats every second\n if (this._metricsCounter++ % 60 === 0) {\n this._getMetrics();\n this.stats.reset();\n log.table(4, this.metrics)();\n\n // Experimental: report metrics\n if (this.props._onMetrics) {\n this.props._onMetrics(this.metrics);\n }\n }\n\n this._updateCanvasSize();\n\n this._updateCursor();\n\n // Update layers if needed (e.g. some async prop has loaded)\n // Note: This can trigger a redraw\n this.layerManager!.updateLayers();\n\n // Perform picking request if any\n this._pickAndCallback();\n\n // Redraw if necessary\n this.redraw();\n\n // Update viewport transition if needed\n // Note: this can trigger `onViewStateChange`, and affect layers\n // We want to defer these changes to the next frame\n if (this.viewManager) {\n this.viewManager.updateViewStates();\n }\n }\n\n // Callbacks\n\n private _onViewStateChange(params: ViewStateChangeParameters & {viewId: string}) {\n // Let app know that view state is changing, and give it a chance to change it\n const viewState = this.props.onViewStateChange(params) || params.viewState;\n\n // If initialViewState was set on creation, auto track position\n if (this.viewState) {\n this.viewState = {...this.viewState, [params.viewId]: viewState};\n if (!this.props.viewState) {\n // Apply internal view state\n if (this.viewManager) {\n this.viewManager.setProps({viewState: this.viewState});\n }\n }\n }\n }\n\n private _onInteractionStateChange(interactionState: InteractionState) {\n this.cursorState.isDragging = interactionState.isDragging || false;\n this.props.onInteractionStateChange(interactionState);\n }\n\n /** Internal use only: event handler for click & drag */\n _onEvent = (event: MjolnirGestureEvent) => {\n const eventHandlerProp = EVENT_HANDLERS[event.type];\n const pos = event.offsetCenter;\n\n if (!eventHandlerProp || !pos || !this.layerManager) {\n return;\n }\n\n const layers = this.layerManager.getLayers();\n const internalPickingMode = this._getInternalPickingMode();\n\n if (!internalPickingMode) {\n return;\n }\n\n if (internalPickingMode === 'sync') {\n const info =\n event.type === 'click' && this._shouldUnproject3D(layers)\n ? this._getFirstPickedInfo(\n this._pickPointSync(\n this._getPointPickOptions(pos.x, pos.y, {unproject3D: true}, layers)\n )\n )\n : this._getLastPointerDownPickingInfo(pos.x, pos.y, layers);\n\n this._dispatchPickingEvent(info, event);\n return;\n }\n\n const pointerDownInfoPromise =\n this._lastPointerDownInfoPromise ||\n Promise.resolve(this._getLastPointerDownPickingInfo(pos.x, pos.y, layers));\n\n pointerDownInfoPromise\n .then(info => {\n this._dispatchPickingEvent(info, event);\n })\n .catch(error => this.props.onError?.(error));\n };\n\n /** Internal use only: evnet handler for pointerdown */\n _onPointerDown = (event: MjolnirPointerEvent) => {\n const pos = event.offsetCenter;\n if (!pos) {\n return;\n }\n\n const internalPickingMode = this._getInternalPickingMode();\n if (!internalPickingMode) {\n return;\n }\n\n const layers = this.layerManager?.getLayers() || [];\n const pointerDownPickSequence = ++this._pointerDownPickSequence;\n\n if (internalPickingMode === 'sync') {\n const pickedInfo = this._pickPointSync({\n x: pos.x,\n y: pos.y,\n radius: this.props.pickingRadius\n });\n const info = this._getFirstPickedInfo(pickedInfo);\n this._lastPointerDownInfo = info;\n this._lastPointerDownInfoPromise = Promise.resolve(info);\n return;\n }\n\n const pickPromise = this._pickPointAsync(this._getPointPickOptions(pos.x, pos.y, {}, layers))\n .then(pickResult => this._getFirstPickedInfo(pickResult))\n .then(info => {\n if (pointerDownPickSequence === this._pointerDownPickSequence) {\n this._lastPointerDownInfo = info;\n }\n return info;\n })\n .catch(error => {\n this.props.onError?.(error);\n const fallbackInfo =\n this.deckPicker && this.viewManager\n ? this._getLastPointerDownPickingInfo(pos.x, pos.y, layers)\n : ({} as PickingInfo);\n if (pointerDownPickSequence === this._pointerDownPickSequence) {\n this._lastPointerDownInfo = fallbackInfo;\n }\n return fallbackInfo;\n });\n\n this._lastPointerDownInfo = null;\n this._lastPointerDownInfoPromise = pickPromise;\n };\n\n private _getFrameStats(): void {\n const {stats} = this;\n stats.get('frameRate').timeEnd();\n stats.get('frameRate').timeStart();\n\n // Get individual stats from luma.gl so reset works\n const animationLoopStats = this.animationLoop!.stats;\n stats.get('GPU Time').addTime(animationLoopStats.get('GPU Time').lastTiming);\n stats.get('CPU Time').addTime(animationLoopStats.get('CPU Time').lastTiming);\n }\n\n private _getMetrics(): void {\n const {metrics, stats} = this;\n metrics.fps = stats.get('frameRate').getHz();\n metrics.setPropsTime = stats.get('setProps Time').time;\n metrics.updateAttributesTime = stats.get('Update Attributes').time;\n metrics.framesRedrawn = stats.get('Redraw Count').count;\n metrics.pickTime =\n stats.get('pickObject Time').time +\n stats.get('pickMultipleObjects Time').time +\n stats.get('pickObjects Time').time;\n metrics.pickCount = stats.get('Pick Count').count;\n\n metrics.layersCount = this.layerManager?.layers.length ?? 0;\n metrics.drawLayersCount = stats.get('Layers rendered').lastSampleCount;\n metrics.pickLayersCount = stats.get('Layers picked').lastSampleCount;\n metrics.updateAttributesCount = stats.get('Layers updated').count;\n metrics.updateAttributesCount = stats.get('Attributes updated').count;\n\n // Luma stats\n metrics.gpuTime = stats.get('GPU Time').time;\n metrics.cpuTime = stats.get('CPU Time').time;\n metrics.gpuTimePerFrame = stats.get('GPU Time').getAverageTime();\n metrics.cpuTimePerFrame = stats.get('CPU Time').getAverageTime();\n\n const memoryStats = luma.stats.get('GPU Time and Memory');\n metrics.bufferMemory = memoryStats.get('Buffer Memory').count;\n metrics.textureMemory = memoryStats.get('Texture Memory').count;\n metrics.renderbufferMemory = memoryStats.get('Renderbuffer Memory').count;\n metrics.gpuMemory = memoryStats.get('GPU Memory').count;\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/* eslint-disable complexity */\nimport type {Device, NormalizedDataType} from '@luma.gl/core';\nimport {Buffer, BufferLayout, BufferAttributeLayout} from '@luma.gl/core';\n\nimport {\n typedArrayFromDataType,\n getBufferAttributeLayout,\n getStride,\n dataTypeFromTypedArray\n} from './gl-utils';\nimport typedArrayManager from '../../utils/typed-array-manager';\nimport {toDoublePrecisionArray} from '../../utils/math-utils';\nimport log from '../../utils/log';\n\nimport type {TypedArray, NumericArray, TypedArrayConstructor} from '../../types/types';\n\nexport type DataType = Exclude;\nexport type LogicalDataType = DataType | 'float64';\n\nexport type BufferAccessor = {\n /** Vertex data type. */\n type?: DataType;\n /** The number of elements per vertex attribute. */\n size?: number;\n /** Offset of the first vertex attribute into the buffer, in bytes. */\n offset?: number;\n /** The offset between the beginning of consecutive vertex attributes, in bytes. */\n stride?: number;\n};\n\nexport type ShaderAttributeOptions = Partial & {\n offset: number;\n stride: number;\n vertexOffset?: number;\n elementOffset?: number;\n};\n\nfunction resolveShaderAttribute(\n baseAccessor: DataColumnSettings,\n shaderAttributeOptions: Partial\n): ShaderAttributeOptions {\n if (shaderAttributeOptions.offset) {\n log.removed('shaderAttribute.offset', 'vertexOffset, elementOffset')();\n }\n\n // All shader attributes share the parent's stride\n const stride = getStride(baseAccessor);\n // `vertexOffset` is used to access the neighboring vertex's value\n // e.g. `nextPositions` in polygon\n const vertexOffset =\n shaderAttributeOptions.vertexOffset !== undefined\n ? shaderAttributeOptions.vertexOffset\n : baseAccessor.vertexOffset || 0;\n // `elementOffset` is defined when shader attribute's size is smaller than the parent's\n // e.g. `translations` in transform matrix\n const elementOffset = shaderAttributeOptions.elementOffset || 0;\n const offset =\n // offsets defined by the attribute\n vertexOffset * stride +\n elementOffset * baseAccessor.bytesPerElement +\n // offsets defined by external buffers if any\n (baseAccessor.offset || 0);\n\n return {\n ...shaderAttributeOptions,\n offset,\n stride\n };\n}\n\nfunction resolveDoublePrecisionShaderAttributes(\n baseAccessor: DataColumnSettings,\n shaderAttributeOptions: Partial\n): {\n high: ShaderAttributeOptions;\n low: ShaderAttributeOptions;\n} {\n const resolvedOptions = resolveShaderAttribute(baseAccessor, shaderAttributeOptions);\n\n return {\n high: resolvedOptions,\n low: {\n ...resolvedOptions,\n offset: resolvedOptions.offset + baseAccessor.size * 4\n }\n };\n}\n\nexport type DataColumnOptions = Options &\n Omit & {\n id?: string;\n vertexOffset?: number;\n fp64?: boolean;\n /** Vertex data type.\n * @default 'float32'\n */\n type?: LogicalDataType;\n /** Internal API, use `type` instead */\n logicalType?: LogicalDataType;\n isIndexed?: boolean;\n defaultValue?: number | Readonly;\n };\n\nexport type DataColumnSettings = DataColumnOptions & {\n type: DataType;\n size: number;\n logicalType?: LogicalDataType;\n normalized: boolean;\n bytesPerElement: number;\n defaultValue: number[];\n defaultType: TypedArrayConstructor;\n};\n\ntype DataColumnInternalState = State & {\n externalBuffer: Buffer | null;\n bufferAccessor: DataColumnSettings;\n allocatedValue: TypedArray | null;\n numInstances: number;\n bounds: [number[], number[]] | null;\n constant: boolean;\n};\n\nexport default class DataColumn {\n device: Device;\n id: string;\n size: number;\n settings: DataColumnSettings;\n value: NumericArray | null;\n doublePrecision: boolean;\n\n protected _buffer: Buffer | null = null;\n protected state: DataColumnInternalState;\n\n /* eslint-disable max-statements */\n constructor(device: Device, opts: DataColumnOptions, state: State) {\n this.device = device;\n this.id = opts.id || '';\n this.size = opts.size || 1;\n\n const logicalType = opts.logicalType || opts.type;\n const doublePrecision = logicalType === 'float64';\n\n let {defaultValue} = opts;\n defaultValue = Number.isFinite(defaultValue)\n ? [defaultValue]\n : defaultValue || new Array(this.size).fill(0);\n\n let bufferType: DataType;\n if (doublePrecision) {\n bufferType = 'float32';\n } else if (!logicalType && opts.isIndexed) {\n bufferType = 'uint32';\n } else {\n bufferType = logicalType || 'float32';\n }\n\n // This is the attribute type defined by the layer\n // If an external buffer is provided, this.type may be overwritten\n // But we always want to use defaultType for allocation\n let defaultType = typedArrayFromDataType(logicalType || bufferType);\n this.doublePrecision = doublePrecision;\n\n // `fp64: false` tells a double-precision attribute to allocate Float32Arrays\n // by default when using auto-packing. This is more efficient in use cases where\n // high precision is unnecessary, but the `64Low` attribute is still required\n // by the shader.\n if (doublePrecision && opts.fp64 === false) {\n defaultType = Float32Array;\n }\n\n this.value = null;\n this.settings = {\n ...opts,\n defaultType,\n defaultValue: defaultValue as number[],\n logicalType,\n type: bufferType,\n normalized: bufferType.includes('norm'),\n size: this.size,\n bytesPerElement: defaultType.BYTES_PER_ELEMENT\n };\n this.state = {\n ...state,\n externalBuffer: null,\n bufferAccessor: this.settings,\n allocatedValue: null,\n numInstances: 0,\n bounds: null,\n constant: false\n };\n }\n /* eslint-enable max-statements */\n\n get isConstant(): boolean {\n return this.state.constant;\n }\n\n get buffer(): Buffer {\n return this._buffer!;\n }\n\n get byteOffset(): number {\n const accessor = this.getAccessor();\n if (accessor.vertexOffset) {\n return accessor.vertexOffset * getStride(accessor);\n }\n return 0;\n }\n\n get numInstances(): number {\n return this.state.numInstances;\n }\n\n set numInstances(n: number) {\n this.state.numInstances = n;\n }\n\n delete(): void {\n if (this._buffer) {\n this._buffer.delete();\n this._buffer = null;\n }\n typedArrayManager.release(this.state.allocatedValue);\n }\n\n getBuffer(): Buffer | null {\n if (this.state.constant) {\n return null;\n }\n return this.state.externalBuffer || this._buffer;\n }\n\n getValue(\n attributeName: string = this.id,\n options: Partial | null = null\n ): Record {\n const result: Record = {};\n if (this.state.constant) {\n const value = this.value as TypedArray;\n if (options) {\n const shaderAttributeDef = resolveShaderAttribute(this.getAccessor(), options);\n const offset = shaderAttributeDef.offset / value.BYTES_PER_ELEMENT;\n const size = shaderAttributeDef.size || this.size;\n result[attributeName] = value.subarray(offset, offset + size);\n } else {\n result[attributeName] = value;\n }\n } else {\n result[attributeName] = this.getBuffer();\n }\n if (this.doublePrecision) {\n if (this.value instanceof Float64Array) {\n result[`${attributeName}64Low`] = result[attributeName];\n } else {\n // Disable fp64 low part\n result[`${attributeName}64Low`] = new Float32Array(this.size);\n }\n }\n return result;\n }\n\n protected _getBufferLayout(\n attributeName: string = this.id,\n options: Partial | null = null\n ): BufferLayout {\n const accessor = this.getAccessor();\n const attributes: (BufferAttributeLayout | null)[] = [];\n const result: BufferLayout = {\n name: this.id,\n byteStride: getStride(accessor)\n };\n\n if (this.doublePrecision) {\n const doubleShaderAttributeDefs = resolveDoublePrecisionShaderAttributes(\n accessor,\n options || {}\n );\n attributes.push(\n getBufferAttributeLayout(\n attributeName,\n {...accessor, ...doubleShaderAttributeDefs.high},\n this.device.type\n ),\n getBufferAttributeLayout(\n `${attributeName}64Low`,\n {\n ...accessor,\n ...doubleShaderAttributeDefs.low\n },\n this.device.type\n )\n );\n } else if (options) {\n const shaderAttributeDef = resolveShaderAttribute(accessor, options);\n attributes.push(\n getBufferAttributeLayout(\n attributeName,\n {...accessor, ...shaderAttributeDef},\n this.device.type\n )\n );\n } else {\n attributes.push(getBufferAttributeLayout(attributeName, accessor, this.device.type));\n }\n result.attributes = attributes.filter(Boolean) as BufferAttributeLayout[];\n return result;\n }\n\n setAccessor(accessor: DataColumnSettings) {\n this.state.bufferAccessor = accessor;\n }\n\n getAccessor(): DataColumnSettings {\n return this.state.bufferAccessor;\n }\n\n // Returns [min: Array(size), max: Array(size)]\n /* eslint-disable max-depth */\n getBounds(): [number[], number[]] | null {\n if (this.state.bounds) {\n return this.state.bounds;\n }\n let result: [number[], number[]] | null = null;\n if (this.state.constant && this.value) {\n const min = Array.from(this.value);\n result = [min, min];\n } else {\n const {value, numInstances, size} = this;\n const len = numInstances * size;\n if (value && len && value.length >= len) {\n const min = new Array(size).fill(Infinity);\n const max = new Array(size).fill(-Infinity);\n for (let i = 0; i < len; ) {\n for (let j = 0; j < size; j++) {\n const v = value[i++];\n if (v < min[j]) min[j] = v;\n if (v > max[j]) max[j] = v;\n }\n }\n result = [min, max];\n }\n }\n this.state.bounds = result;\n return result;\n }\n\n // returns true if success\n // eslint-disable-next-line max-statements\n setData(\n data:\n | TypedArray\n | Buffer\n | ({\n constant?: boolean;\n value?: NumericArray;\n buffer?: Buffer;\n /** Set to `true` if supplying float values to a unorm attribute */\n normalized?: boolean;\n } & Partial)\n ): boolean {\n const {state} = this;\n\n let opts: {\n constant?: boolean;\n value?: NumericArray;\n buffer?: Buffer;\n } & Partial;\n if (ArrayBuffer.isView(data)) {\n opts = {value: data};\n } else if (data instanceof Buffer) {\n opts = {buffer: data};\n } else {\n opts = data;\n }\n\n const accessor: DataColumnSettings = {...this.settings, ...opts};\n\n if (ArrayBuffer.isView(opts.value)) {\n if (!opts.type) {\n // Deduce data type\n const is64Bit = this.doublePrecision && opts.value instanceof Float64Array;\n if (is64Bit) {\n accessor.type = 'float32';\n } else {\n const type = dataTypeFromTypedArray(opts.value);\n // (lint wants to remove the cast)\n // eslint-disable-next-line\n accessor.type = (accessor.normalized ? type.replace('int', 'norm') : type) as DataType;\n }\n }\n accessor.bytesPerElement = opts.value.BYTES_PER_ELEMENT;\n accessor.stride = getStride(accessor);\n }\n\n state.bounds = null; // clear cached bounds\n\n if (opts.constant) {\n // set constant\n let value = opts.value;\n value = this._normalizeValue(value, [], 0);\n if (this.settings.normalized) {\n value = this.normalizeConstant(value);\n }\n const hasChanged = !state.constant || !this._areValuesEqual(value, this.value);\n\n if (!hasChanged) {\n return false;\n }\n state.externalBuffer = null;\n state.constant = true;\n this.value = ArrayBuffer.isView(value) ? value : new Float32Array(value);\n } else if (opts.buffer) {\n const buffer = opts.buffer;\n state.externalBuffer = buffer;\n state.constant = false;\n this.value = opts.value || null;\n } else if (opts.value) {\n this._checkExternalBuffer(opts);\n\n let value = opts.value as TypedArray;\n state.externalBuffer = null;\n state.constant = false;\n this.value = value;\n\n let {buffer} = this;\n const stride = getStride(accessor);\n const byteOffset = (accessor.vertexOffset || 0) * stride;\n\n if (this.doublePrecision && value instanceof Float64Array) {\n value = toDoublePrecisionArray(value, accessor);\n }\n if (this.settings.isIndexed) {\n const ArrayType = this.settings.defaultType;\n if (value.constructor !== ArrayType) {\n // Cast the index buffer to expected type\n value = new ArrayType(value);\n }\n }\n\n // A small over allocation is used as safety margin\n // Shader attributes may try to access this buffer with bigger offsets\n const requiredBufferSize = value.byteLength + byteOffset + stride * 2;\n if (!buffer || buffer.byteLength < requiredBufferSize) {\n buffer = this._createBuffer(requiredBufferSize);\n }\n\n buffer.write(value, byteOffset);\n }\n\n this.setAccessor(accessor);\n\n return true;\n }\n\n updateSubBuffer(\n opts: {\n startOffset?: number;\n endOffset?: number;\n } = {}\n ): void {\n this.state.bounds = null; // clear cached bounds\n\n const value = this.value as TypedArray;\n const {startOffset = 0, endOffset} = opts;\n this.buffer.write(\n this.doublePrecision && value instanceof Float64Array\n ? toDoublePrecisionArray(value, {\n size: this.size,\n startIndex: startOffset,\n endIndex: endOffset\n })\n : value.subarray(startOffset, endOffset),\n startOffset * value.BYTES_PER_ELEMENT + this.byteOffset\n );\n }\n\n allocate(numInstances: number, copy: boolean = false): boolean {\n const {state} = this;\n const oldValue = state.allocatedValue;\n\n // Allocate at least one element to ensure a valid buffer\n const value = typedArrayManager.allocate(oldValue, numInstances + 1, {\n size: this.size,\n type: this.settings.defaultType,\n copy\n });\n\n this.value = value;\n\n const {byteOffset} = this;\n let {buffer} = this;\n\n if (!buffer || buffer.byteLength < value.byteLength + byteOffset) {\n buffer = this._createBuffer(value.byteLength + byteOffset);\n if (copy && oldValue) {\n // Upload the full existing attribute value to the GPU, so that updateBuffer\n // can choose to only update a partial range.\n // TODO - copy old buffer to new buffer on the GPU\n buffer.write(\n oldValue instanceof Float64Array ? toDoublePrecisionArray(oldValue, this) : oldValue,\n byteOffset\n );\n }\n }\n\n state.allocatedValue = value;\n state.constant = false;\n state.externalBuffer = null;\n this.setAccessor(this.settings);\n return true;\n }\n\n // PRIVATE HELPER METHODS\n protected _checkExternalBuffer(opts: {value?: NumericArray; normalized?: boolean}): void {\n const {value} = opts;\n if (!ArrayBuffer.isView(value)) {\n throw new Error(`Attribute ${this.id} value is not TypedArray`);\n }\n const ArrayType = this.settings.defaultType;\n\n let illegalArrayType = false;\n if (this.doublePrecision) {\n // not 32bit or 64bit\n illegalArrayType = value.BYTES_PER_ELEMENT < 4;\n }\n if (illegalArrayType) {\n throw new Error(`Attribute ${this.id} does not support ${value.constructor.name}`);\n }\n if (!(value instanceof ArrayType) && this.settings.normalized && !('normalized' in opts)) {\n log.warn(`Attribute ${this.id} is normalized`)();\n }\n }\n\n // https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/vertexAttribPointer\n normalizeConstant(value: NumericArray): NumericArray {\n /* eslint-disable complexity */\n switch (this.settings.type) {\n case 'snorm8':\n // normalize [-128, 127] to [-1, 1]\n return new Float32Array(value).map(x => ((x + 128) / 255) * 2 - 1);\n\n case 'snorm16':\n // normalize [-32768, 32767] to [-1, 1]\n return new Float32Array(value).map(x => ((x + 32768) / 65535) * 2 - 1);\n\n case 'unorm8':\n // normalize [0, 255] to [0, 1]\n return new Float32Array(value).map(x => x / 255);\n\n case 'unorm16':\n // normalize [0, 65535] to [0, 1]\n return new Float32Array(value).map(x => x / 65535);\n\n default:\n // No normalization for gl.FLOAT and gl.HALF_FLOAT\n return value;\n }\n }\n\n /* check user supplied values and apply fallback */\n protected _normalizeValue(value: any, out: NumericArray, start: number): NumericArray {\n const {defaultValue, size} = this.settings;\n\n if (Number.isFinite(value)) {\n out[start] = value;\n return out;\n }\n if (!value) {\n let i = size;\n while (--i >= 0) {\n out[start + i] = defaultValue[i];\n }\n return out;\n }\n\n // Important - switch cases are 5x more performant than a for loop!\n /* eslint-disable no-fallthrough, default-case */\n switch (size) {\n case 4:\n out[start + 3] = Number.isFinite(value[3]) ? value[3] : defaultValue[3];\n case 3:\n out[start + 2] = Number.isFinite(value[2]) ? value[2] : defaultValue[2];\n case 2:\n out[start + 1] = Number.isFinite(value[1]) ? value[1] : defaultValue[1];\n case 1:\n out[start + 0] = Number.isFinite(value[0]) ? value[0] : defaultValue[0];\n break;\n\n default:\n // In the rare case where the attribute size > 4, do it the slow way\n // This is used for e.g. transform matrices\n let i = size;\n while (--i >= 0) {\n out[start + i] = Number.isFinite(value[i]) ? value[i] : defaultValue[i];\n }\n }\n\n return out;\n }\n\n protected _areValuesEqual(value1: any, value2: any): boolean {\n if (!value1 || !value2) {\n return false;\n }\n const {size} = this;\n for (let i = 0; i < size; i++) {\n if (value1[i] !== value2[i]) {\n return false;\n }\n }\n return true;\n }\n\n protected _createBuffer(byteLength: number): Buffer {\n if (this._buffer) {\n this._buffer.destroy();\n }\n\n const {isIndexed, type} = this.settings;\n this._buffer = this.device.createBuffer({\n ...this._buffer?.props,\n id: this.id,\n // TODO(ibgreen) - WebGPU requires COPY_DST and COPY_SRC to allow write / read\n usage: (isIndexed ? Buffer.INDEX : Buffer.VERTEX) | Buffer.COPY_DST,\n indexType: isIndexed ? (type as 'uint16' | 'uint32') : undefined,\n byteLength\n });\n\n return this._buffer;\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {dataTypeDecoder, getTypedArrayConstructor} from '@luma.gl/core';\nimport type {BufferAttributeLayout, VertexFormat} from '@luma.gl/core';\nimport type {TypedArrayConstructor} from '../../types/types';\nimport type {BufferAccessor, DataColumnSettings, LogicalDataType} from './data-column';\n\nexport function typedArrayFromDataType(type: LogicalDataType): TypedArrayConstructor {\n // Sorted in some order of likelihood to reduce amount of comparisons\n switch (type) {\n case 'float64':\n return Float64Array;\n case 'uint8':\n case 'unorm8':\n return Uint8ClampedArray;\n default:\n return getTypedArrayConstructor(type);\n }\n}\n\nexport const dataTypeFromTypedArray = dataTypeDecoder.getDataType.bind(dataTypeDecoder);\n\nexport function getBufferAttributeLayout(\n name: string,\n accessor: BufferAccessor,\n deviceType: 'webgpu' | 'wegbgl' | string\n): BufferAttributeLayout | null {\n if ((accessor.size as number) > 4) {\n // Definitely not valid. TODO - stricter validation?\n return null;\n }\n // TODO(ibgreen): WebGPU change. Currently we always use normalized 8 bit integers\n const type = deviceType === 'webgpu' && accessor.type === 'uint8' ? 'unorm8' : accessor.type;\n return {\n attribute: name,\n // @ts-expect-error Not all combinations are valid vertex formats; it's up to DataColumn to ensure\n format:\n (accessor.size as number) > 1 ? (`${type}x${accessor.size}` as VertexFormat) : accessor.type,\n byteOffset: accessor.offset || 0\n // Note stride is set on the top level\n };\n}\n\nexport function getStride(accessor: DataColumnSettings): number {\n return accessor.stride || accessor.size * accessor.bytesPerElement;\n}\n\nexport function bufferLayoutEqual(\n accessor1: DataColumnSettings,\n accessor2: DataColumnSettings\n) {\n return (\n accessor1.type === accessor2.type &&\n accessor1.size === accessor2.size &&\n getStride(accessor1) === getStride(accessor2) &&\n (accessor1.offset || 0) === (accessor2.offset || 0)\n );\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {NumericArray} from '../types/types';\nimport type {AccessorFunction} from '../types/layer-props';\n\nconst EMPTY_ARRAY = [];\nconst placeholderArray = [];\n\n/*\n * Create an Iterable\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols\n * and a \"context\" tracker from the given data\n */\nexport function createIterable(\n data,\n startRow = 0,\n endRow = Infinity\n): {\n iterable: Iterable;\n objectInfo: {\n index: number;\n data: any;\n target: any[];\n };\n} {\n let iterable: Iterable = EMPTY_ARRAY;\n\n const objectInfo = {\n index: -1,\n data,\n // visitor can optionally utilize this to avoid constructing a new array for every object\n target: []\n };\n\n if (!data) {\n iterable = EMPTY_ARRAY;\n } else if (typeof data[Symbol.iterator] === 'function') {\n // data is already an iterable\n iterable = data;\n } else if (data.length > 0) {\n placeholderArray.length = data.length;\n iterable = placeholderArray;\n }\n\n if (startRow > 0 || Number.isFinite(endRow)) {\n iterable = (Array.isArray(iterable) ? iterable : Array.from(iterable)).slice(startRow, endRow);\n objectInfo.index = startRow - 1;\n }\n\n return {iterable, objectInfo};\n}\n\n/*\n * Returns true if data is an async iterable object\n */\nexport function isAsyncIterable(data): boolean {\n return data && data[Symbol.asyncIterator];\n}\n\n/*\n * Create an accessor function from a flat buffer that yields the value at each object index\n */\nexport function getAccessorFromBuffer(\n typedArray,\n options: {\n size: number;\n stride?: number;\n offset?: number;\n startIndices?: NumericArray;\n nested?: boolean;\n }\n): AccessorFunction {\n const {size, stride, offset, startIndices, nested} = options;\n const bytesPerElement = typedArray.BYTES_PER_ELEMENT;\n const elementStride = stride ? stride / bytesPerElement : size;\n const elementOffset = offset ? offset / bytesPerElement : 0;\n const vertexCount = Math.floor((typedArray.length - elementOffset) / elementStride);\n\n return (_, {index, target}) => {\n if (!startIndices) {\n const sourceIndex = index * elementStride + elementOffset;\n for (let j = 0; j < size; j++) {\n target[j] = typedArray[sourceIndex + j];\n }\n return target;\n }\n const startIndex = startIndices[index];\n const endIndex = startIndices[index + 1] || vertexCount;\n let result;\n\n if (nested) {\n result = new Array(endIndex - startIndex);\n for (let i = startIndex; i < endIndex; i++) {\n const sourceIndex = i * elementStride + elementOffset;\n target = new Array(size);\n for (let j = 0; j < size; j++) {\n target[j] = typedArray[sourceIndex + j];\n }\n result[i - startIndex] = target;\n }\n } else if (elementStride === size) {\n result = typedArray.subarray(\n startIndex * size + elementOffset,\n endIndex * size + elementOffset\n );\n } else {\n result = new typedArray.constructor((endIndex - startIndex) * size);\n let targetIndex = 0;\n for (let i = startIndex; i < endIndex; i++) {\n const sourceIndex = i * elementStride + elementOffset;\n for (let j = 0; j < size; j++) {\n result[targetIndex++] = typedArray[sourceIndex + j];\n }\n }\n }\n\n return result;\n };\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/*\n * range (Array)\n * + start (Number) - the start index (incl.)\n * + end (Number) - the end index (excl.)\n * rangeList (Array) - array of sorted, combined ranges\n */\nexport const EMPTY = [];\nexport const FULL = [[0, Infinity]];\n\n// Insert a range into a range collection\nexport function add(rangeList, range) {\n // Noop if range collection already covers all\n if (rangeList === FULL) {\n return rangeList;\n }\n\n // Validate the input range\n if (range[0] < 0) {\n range[0] = 0;\n }\n if (range[0] >= range[1]) {\n return rangeList;\n }\n\n // TODO - split off to tree-shakable Range class\n const newRangeList: number[] = [];\n const len = rangeList.length;\n let insertPosition = 0;\n\n for (let i = 0; i < len; i++) {\n const range0 = rangeList[i];\n\n if (range0[1] < range[0]) {\n // the current range is to the left of the new range\n newRangeList.push(range0);\n insertPosition = i + 1;\n } else if (range0[0] > range[1]) {\n // the current range is to the right of the new range\n newRangeList.push(range0);\n } else {\n range = [Math.min(range0[0], range[0]), Math.max(range0[1], range[1])];\n }\n }\n newRangeList.splice(insertPosition, 0, range);\n return newRangeList;\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {NumericArray} from '../../types/types';\n\nexport interface TransitionSettings {\n type: string;\n /** Callback to get the value that the entering vertices are transitioning from. */\n enter?: (toValue: NumericArray, chunk?: NumericArray) => NumericArray;\n /** Callback when the transition is started */\n onStart?: () => void;\n /** Callback when the transition is done */\n onEnd?: () => void;\n /** Callback when the transition is interrupted */\n onInterrupt?: () => void;\n}\n\nexport type InterpolationTransitionSettings = TransitionSettings & {\n type?: 'interpolation';\n /** Duration of the transition animation, in milliseconds */\n duration: number;\n /** Easing function that maps a value from [0, 1] to [0, 1], see [http://easings.net/](http://easings.net/) */\n easing?: (t: number) => number;\n};\n\nexport type SpringTransitionSettings = TransitionSettings & {\n type: 'spring';\n /** \"Tension\" factor for the spring */\n stiffness: number;\n /** \"Friction\" factor that counteracts the spring's acceleration */\n damping: number;\n};\n\nconst DEFAULT_TRANSITION_SETTINGS = {\n interpolation: {\n duration: 0,\n easing: t => t\n },\n spring: {\n stiffness: 0.05,\n damping: 0.5\n }\n};\n\nexport function normalizeTransitionSettings(\n userSettings: number | InterpolationTransitionSettings | SpringTransitionSettings,\n layerSettings?: boolean | Partial\n): TransitionSettings | null {\n if (!userSettings) {\n return null;\n }\n if (Number.isFinite(userSettings)) {\n userSettings = {type: 'interpolation', duration: userSettings as number};\n }\n const type = (userSettings as TransitionSettings).type || 'interpolation';\n return {\n ...DEFAULT_TRANSITION_SETTINGS[type],\n ...(layerSettings as TransitionSettings),\n ...(userSettings as TransitionSettings),\n type\n };\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/* eslint-disable complexity */\nimport DataColumn, {\n DataColumnOptions,\n ShaderAttributeOptions,\n BufferAccessor,\n DataColumnSettings\n} from './data-column';\nimport assert from '../../utils/assert';\nimport {createIterable, getAccessorFromBuffer} from '../../utils/iterable-utils';\nimport {fillArray} from '../../utils/flatten';\nimport * as range from '../../utils/range';\nimport {bufferLayoutEqual} from './gl-utils';\nimport {normalizeTransitionSettings, TransitionSettings} from './transition-settings';\nimport type {Device, Buffer, BufferLayout} from '@luma.gl/core';\n\nimport type {NumericArray, TypedArray} from '../../types/types';\n\nexport type Accessor = (\n object: DataType,\n context: {\n data: any;\n index: number;\n target: number[];\n }\n) => ReturnType;\n\nexport type Updater = (\n attribute: Attribute,\n {\n data,\n startRow,\n endRow,\n props,\n numInstances\n }: {\n data: any;\n startRow: number;\n endRow: number;\n props: any;\n numInstances: number;\n }\n) => void;\n\nexport type AttributeOptions = DataColumnOptions<{\n transition?: boolean | Partial;\n stepMode?: 'vertex' | 'instance' | 'dynamic';\n noAlloc?: boolean;\n update?: Updater;\n accessor?: Accessor | string | string[];\n transform?: (value: any) => any;\n shaderAttributes?: Record>;\n}>;\n\nexport type BinaryAttribute = Partial & {value?: TypedArray; buffer?: Buffer};\n\ntype AttributeInternalState = {\n startIndices: NumericArray | null;\n /** Legacy: external binary supplied via attribute name */\n lastExternalBuffer: TypedArray | Buffer | BinaryAttribute | null;\n /** External binary supplied via accessor name */\n binaryValue: TypedArray | Buffer | BinaryAttribute | null;\n binaryAccessor: Accessor | null;\n needsUpdate: string | boolean;\n needsRedraw: string | boolean;\n layoutChanged: boolean;\n updateRanges: number[][];\n};\n\nexport default class Attribute extends DataColumn {\n /** Legacy approach to set attribute value - read `isConstant` instead for attribute state */\n constant: boolean = false;\n\n constructor(device: Device, opts: AttributeOptions) {\n super(device, opts, {\n startIndices: null,\n lastExternalBuffer: null,\n binaryValue: null,\n binaryAccessor: null,\n needsUpdate: true,\n needsRedraw: false,\n layoutChanged: false,\n updateRanges: range.FULL\n });\n\n // eslint-disable-next-line\n this.settings.update = opts.update || (opts.accessor ? this._autoUpdater : undefined);\n\n Object.seal(this.settings);\n Object.seal(this.state);\n\n // Check all fields and generate helpful error messages\n this._validateAttributeUpdaters();\n }\n\n get startIndices(): NumericArray | null {\n return this.state.startIndices;\n }\n\n set startIndices(layout: NumericArray | null) {\n this.state.startIndices = layout;\n }\n\n needsUpdate(): string | boolean {\n return this.state.needsUpdate;\n }\n\n needsRedraw({clearChangedFlags = false}: {clearChangedFlags?: boolean} = {}): string | boolean {\n const needsRedraw = this.state.needsRedraw;\n this.state.needsRedraw = needsRedraw && !clearChangedFlags;\n return needsRedraw;\n }\n\n layoutChanged(): boolean {\n return this.state.layoutChanged;\n }\n\n setAccessor(accessor: DataColumnSettings) {\n this.state.layoutChanged ||= !bufferLayoutEqual(accessor, this.getAccessor());\n super.setAccessor(accessor);\n }\n\n getUpdateTriggers(): string[] {\n const {accessor} = this.settings;\n\n // Backards compatibility: allow attribute name to be used as update trigger key\n return [this.id].concat((typeof accessor !== 'function' && accessor) || []);\n }\n\n supportsTransition(): boolean {\n return Boolean(this.settings.transition);\n }\n\n // Resolve transition settings object if transition is enabled, otherwise `null`\n getTransitionSetting(opts: Record): TransitionSettings | null {\n if (!opts || !this.supportsTransition()) {\n return null;\n }\n const {accessor} = this.settings;\n // TODO: have the layer resolve these transition settings itself?\n const layerSettings = this.settings.transition;\n // these are the transition settings passed in by the user\n const userSettings = Array.isArray(accessor)\n ? // @ts-ignore\n opts[accessor.find(a => opts[a])]\n : // @ts-ignore\n opts[accessor];\n\n // Shorthand: use duration instead of parameter object\n return normalizeTransitionSettings(userSettings, layerSettings);\n }\n\n setNeedsUpdate(reason: string = this.id, dataRange?: {startRow?: number; endRow?: number}): void {\n this.state.needsUpdate = this.state.needsUpdate || reason;\n this.setNeedsRedraw(reason);\n if (dataRange) {\n const {startRow = 0, endRow = Infinity} = dataRange;\n this.state.updateRanges = range.add(this.state.updateRanges, [startRow, endRow]);\n } else {\n this.state.updateRanges = range.FULL;\n }\n }\n\n clearNeedsUpdate(): void {\n this.state.needsUpdate = false;\n this.state.updateRanges = range.EMPTY;\n }\n\n setNeedsRedraw(reason: string = this.id): void {\n this.state.needsRedraw = this.state.needsRedraw || reason;\n }\n\n allocate(numInstances: number): boolean {\n const {state, settings} = this;\n\n if (settings.noAlloc) {\n // Data is provided through a Buffer object.\n return false;\n }\n\n if (settings.update) {\n super.allocate(numInstances, state.updateRanges !== range.FULL);\n return true;\n }\n\n return false;\n }\n\n updateBuffer({\n numInstances,\n data,\n props,\n context\n }: {\n numInstances: number;\n data: any;\n props: any;\n context: any;\n }): boolean {\n if (!this.needsUpdate()) {\n return false;\n }\n\n const {\n state: {updateRanges},\n settings: {update, noAlloc}\n } = this;\n\n let updated = true;\n if (update) {\n // Custom updater - typically for non-instanced layers\n for (const [startRow, endRow] of updateRanges) {\n update.call(context, this, {data, startRow, endRow, props, numInstances});\n }\n if (!this.value) {\n // no value was assigned during update\n } else if (\n this.constant ||\n !this.buffer ||\n this.buffer.byteLength < (this.value as TypedArray).byteLength + this.byteOffset\n ) {\n if (this.constant) {\n // Route constant updater output through the same path used by constant accessors\n // so WebGPU can materialize a real buffer while WebGL keeps a constant attribute.\n this.setConstantValue(context, this.value);\n } else {\n this.setData({\n value: this.value,\n constant: this.constant\n });\n }\n // Setting attribute.constant in updater is a legacy approach that interferes with allocation in the next cycle\n // Respect it here but reset after use\n this.constant = false;\n } else {\n for (const [startRow, endRow] of updateRanges) {\n const startOffset = Number.isFinite(startRow) ? this.getVertexOffset(startRow) : 0;\n const endOffset = Number.isFinite(endRow)\n ? this.getVertexOffset(endRow)\n : noAlloc || !Number.isFinite(numInstances)\n ? this.value.length\n : numInstances * this.size;\n\n super.updateSubBuffer({startOffset, endOffset});\n }\n }\n this._checkAttributeArray();\n } else {\n updated = false;\n }\n\n this.clearNeedsUpdate();\n this.setNeedsRedraw();\n\n return updated;\n }\n\n // Use generic value\n // Returns true if successful\n setConstantValue(context: any, value?: any): boolean {\n if (value === undefined || typeof value === 'function') {\n return false;\n }\n\n const transformedValue =\n this.settings.transform && context ? this.settings.transform.call(context, value) : value;\n\n if (this.device.type === 'webgpu') {\n // WebGPU has no equivalent of WebGL constant vertex attributes, so we expand the\n // constant into a full per-instance buffer before passing it to luma.gl.\n return this.setConstantBufferValue(transformedValue, this.numInstances);\n }\n\n // WebGL can bind the normalized/transformed value directly as a constant attribute.\n const hasChanged = this.setData({constant: true, value: transformedValue});\n\n if (hasChanged) {\n this.setNeedsRedraw();\n }\n this.clearNeedsUpdate();\n return true;\n }\n\n setConstantBufferValue(value: any, numInstances: number): boolean {\n const ArrayType = this.settings.defaultType;\n const constantValue = this._normalizeValue(value, new ArrayType(this.size), 0) as TypedArray;\n if (this._hasConstantBufferValue(constantValue, numInstances)) {\n // The emulated buffer already matches this constant, so avoid a redundant upload.\n this.constant = false;\n this.clearNeedsUpdate();\n return false;\n }\n\n const repeatedValue = new ArrayType(Math.max(numInstances, 1) * this.size);\n\n for (let i = 0; i < repeatedValue.length; i += this.size) {\n repeatedValue.set(constantValue, i);\n }\n\n const hasChanged = this.setData({value: repeatedValue});\n this.constant = false;\n this.clearNeedsUpdate();\n\n if (hasChanged) {\n this.setNeedsRedraw();\n }\n\n return hasChanged;\n }\n\n private _hasConstantBufferValue(value: NumericArray, numInstances: number): boolean {\n const currentValue = this.value;\n const expectedLength = Math.max(numInstances, 1) * this.size;\n\n if (\n !ArrayBuffer.isView(currentValue) ||\n currentValue.length !== expectedLength ||\n currentValue.length % this.size !== 0\n ) {\n return false;\n }\n\n for (let i = 0; i < currentValue.length; i += this.size) {\n for (let j = 0; j < this.size; j++) {\n if (currentValue[i + j] !== value[j]) {\n return false;\n }\n }\n }\n\n return true;\n }\n\n // Use external buffer\n // Returns true if successful\n // eslint-disable-next-line max-statements\n setExternalBuffer(buffer?: TypedArray | Buffer | BinaryAttribute): boolean {\n const {state} = this;\n\n if (!buffer) {\n state.lastExternalBuffer = null;\n return false;\n }\n\n this.clearNeedsUpdate();\n\n if (state.lastExternalBuffer === buffer) {\n return true;\n }\n state.lastExternalBuffer = buffer;\n this.setNeedsRedraw();\n this.setData(buffer);\n return true;\n }\n\n // Binary value is a typed array packed from mapping the source data with the accessor\n // If the returned value from the accessor is the same as the attribute value, set it directly\n // Otherwise use the auto updater for transform/normalization\n setBinaryValue(\n buffer?: TypedArray | Buffer | BinaryAttribute,\n startIndices: NumericArray | null = null\n ): boolean {\n const {state, settings} = this;\n\n if (!buffer) {\n state.binaryValue = null;\n state.binaryAccessor = null;\n return false;\n }\n\n if (settings.noAlloc) {\n // Let the layer handle this\n return false;\n }\n\n if (state.binaryValue === buffer) {\n this.clearNeedsUpdate();\n return true;\n }\n state.binaryValue = buffer;\n this.setNeedsRedraw();\n\n const needsUpdate = settings.transform || startIndices !== this.startIndices;\n\n if (needsUpdate) {\n if (ArrayBuffer.isView(buffer)) {\n buffer = {value: buffer};\n }\n const binaryValue = buffer as BinaryAttribute;\n assert(ArrayBuffer.isView(binaryValue.value), `invalid ${settings.accessor}`);\n const needsNormalize = Boolean(binaryValue.size) && binaryValue.size !== this.size;\n\n state.binaryAccessor = getAccessorFromBuffer(binaryValue.value, {\n size: binaryValue.size || this.size,\n stride: binaryValue.stride,\n offset: binaryValue.offset,\n startIndices: startIndices as NumericArray,\n nested: needsNormalize\n });\n // Fall through to auto updater\n return false;\n }\n\n this.clearNeedsUpdate();\n this.setData(buffer);\n return true;\n }\n\n getVertexOffset(row: number): number {\n const {startIndices} = this;\n const vertexIndex = startIndices\n ? row < startIndices.length\n ? startIndices[row]\n : this.numInstances\n : row;\n return vertexIndex * this.size;\n }\n\n getValue(): Record {\n const shaderAttributeDefs = this.settings.shaderAttributes;\n const result = super.getValue();\n if (!shaderAttributeDefs) {\n return result;\n }\n for (const shaderAttributeName in shaderAttributeDefs) {\n Object.assign(\n result,\n super.getValue(shaderAttributeName, shaderAttributeDefs[shaderAttributeName])\n );\n }\n return result;\n }\n\n /** Generate WebGPU-style buffer layout descriptor from this attribute */\n getBufferLayout(\n /** A luma.gl Model-shaped object that supplies additional hint to attribute resolution */\n modelInfo?: {isInstanced?: boolean}\n ): BufferLayout {\n // Clear change flag\n this.state.layoutChanged = false;\n\n const shaderAttributeDefs = this.settings.shaderAttributes;\n const result: BufferLayout = super._getBufferLayout();\n const {stepMode} = this.settings;\n if (stepMode === 'dynamic') {\n // If model info is provided, use isInstanced flag to determine step mode\n // If no model info is provided, assume it's an instanced model (most common use case)\n result.stepMode = modelInfo ? (modelInfo.isInstanced ? 'instance' : 'vertex') : 'instance';\n } else {\n result.stepMode = stepMode ?? 'vertex';\n }\n\n if (!shaderAttributeDefs) {\n return result;\n }\n\n for (const shaderAttributeName in shaderAttributeDefs) {\n const map = super._getBufferLayout(\n shaderAttributeName,\n shaderAttributeDefs[shaderAttributeName]\n );\n // @ts-ignore\n result.attributes.push(...map.attributes);\n }\n return result;\n }\n\n /* eslint-disable max-depth, max-statements */\n private _autoUpdater(\n attribute: Attribute,\n {\n data,\n startRow,\n endRow,\n props,\n numInstances\n }: {\n data: any;\n startRow: number;\n endRow: number;\n props: any;\n numInstances: number;\n }\n ): void {\n const {settings, state, value, size, startIndices} = attribute;\n\n const {accessor, transform} = settings;\n const accessorFunc: Accessor =\n state.binaryAccessor ||\n // @ts-ignore\n (typeof accessor === 'function' ? accessor : props[accessor]);\n assert(typeof accessorFunc === 'function', `accessor \"${accessor}\" is not a function`);\n\n let i = attribute.getVertexOffset(startRow);\n const {iterable, objectInfo} = createIterable(data, startRow, endRow);\n for (const object of iterable) {\n objectInfo.index++;\n\n let objectValue = accessorFunc(object, objectInfo);\n if (transform) {\n // transform callbacks could be bound to a particular layer instance.\n // always point `this` to the current layer.\n objectValue = transform.call(this, objectValue);\n }\n\n if (startIndices) {\n const numVertices =\n (objectInfo.index < startIndices.length - 1\n ? startIndices[objectInfo.index + 1]\n : numInstances) - startIndices[objectInfo.index];\n if (objectValue && Array.isArray(objectValue[0])) {\n let startIndex = i;\n for (const item of objectValue) {\n attribute._normalizeValue(item, value as TypedArray, startIndex);\n startIndex += size;\n }\n } else if (objectValue && objectValue.length > size) {\n (value as TypedArray).set(objectValue, i);\n } else {\n attribute._normalizeValue(objectValue, objectInfo.target, 0);\n fillArray({\n target: value,\n source: objectInfo.target,\n start: i,\n count: numVertices\n });\n }\n i += numVertices * size;\n } else {\n attribute._normalizeValue(objectValue, value as TypedArray, i);\n i += size;\n }\n }\n }\n /* eslint-enable max-depth, max-statements */\n\n // Validate deck.gl level fields\n private _validateAttributeUpdaters() {\n const {settings} = this;\n\n // Check that 'update' is a valid function\n const hasUpdater = settings.noAlloc || typeof settings.update === 'function';\n if (!hasUpdater) {\n throw new Error(`Attribute ${this.id} missing update or accessor`);\n }\n }\n\n // check that the first few elements of the attribute are reasonable\n /* eslint-disable no-fallthrough */\n private _checkAttributeArray() {\n const {value} = this;\n const limit = Math.min(4, this.size);\n if (value && value.length >= limit) {\n let valid = true;\n switch (limit) {\n case 4:\n valid = valid && Number.isFinite(value[3]);\n case 3:\n valid = valid && Number.isFinite(value[2]);\n case 2:\n valid = valid && Number.isFinite(value[1]);\n case 1:\n valid = valid && Number.isFinite(value[0]);\n break;\n default:\n valid = false;\n }\n\n if (!valid) {\n throw new Error(`Illegal attribute generated for ${this.id}`);\n }\n }\n }\n /* eslint-enable no-fallthrough */\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {NumericArray, TypedArray} from '../types/types';\n\n/*\n * Helper function for padArray\n */\nfunction padArrayChunk(options: {\n /** original data */\n source: TypedArray;\n /** output data */\n target: TypedArray;\n /** length per datum */\n size: number;\n /** callback to get new data when source is short */\n getData: (index: number, context: NumericArray) => NumericArray;\n /** start index */\n start?: number;\n /** end index */\n end?: number;\n}): void {\n const {source, target, start = 0, size, getData} = options;\n const end = options.end || target.length;\n\n const sourceLength = source.length;\n const targetLength = end - start;\n\n if (sourceLength > targetLength) {\n target.set(source.subarray(0, targetLength), start);\n return;\n }\n\n target.set(source, start);\n\n if (!getData) {\n return;\n }\n\n // source is not large enough to fill target space, call `getData` to get filler data\n let i = sourceLength;\n while (i < targetLength) {\n const datum = getData(i, source);\n for (let j = 0; j < size; j++) {\n target[start + i] = datum[j] || 0;\n i++;\n }\n }\n}\n\n/*\n * The padArray function stretches a source array to the size of a target array.\n The arrays can have internal structures (like the attributes of PathLayer and\n SolidPolygonLayer), defined by the optional sourceStartIndices and targetStartIndices parameters.\n If the target array is larger, the getData callback is used to fill in the blanks.\n */\nexport function padArray({\n source,\n target,\n size,\n getData,\n sourceStartIndices,\n targetStartIndices\n}: {\n /** original data */\n source: TypedArray;\n /** output data */\n target: TypedArray;\n /** length per datum */\n size: number;\n /** callback to get new data when source is short */\n getData: (index: number, context: NumericArray) => NumericArray;\n /** subdivision of the original data in [object0StartIndex, object1StartIndex, ...] */\n sourceStartIndices?: NumericArray | null;\n /** subdivision of the output data in [object0StartIndex, object1StartIndex, ...] */\n targetStartIndices?: NumericArray | null;\n}): TypedArray {\n if (!sourceStartIndices || !targetStartIndices) {\n // Flat arrays\n padArrayChunk({\n source,\n target,\n size,\n getData\n });\n return target;\n }\n\n // Arrays have internal structure\n let sourceIndex = 0;\n let targetIndex = 0;\n const getChunkData = getData && ((i, chunk) => getData(i + targetIndex, chunk));\n\n const n = Math.min(sourceStartIndices.length, targetStartIndices.length);\n\n for (let i = 1; i < n; i++) {\n const nextSourceIndex = sourceStartIndices[i] * size;\n const nextTargetIndex = targetStartIndices[i] * size;\n\n padArrayChunk({\n source: source.subarray(sourceIndex, nextSourceIndex),\n target,\n start: targetIndex,\n end: nextTargetIndex,\n size,\n getData: getChunkData\n });\n\n sourceIndex = nextSourceIndex;\n targetIndex = nextTargetIndex;\n }\n\n if (targetIndex < target.length) {\n padArrayChunk({\n // @ts-ignore\n source: [],\n target,\n start: targetIndex,\n size,\n getData: getChunkData\n });\n }\n\n return target;\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device, Buffer, VertexFormat} from '@luma.gl/core';\nimport {padArray} from '../utils/array-utils';\nimport {NumericArray, TypedArray, TypedArrayConstructor} from '../types/types';\nimport Attribute from '../lib/attribute/attribute';\nimport {GL} from '@luma.gl/webgl/constants';\n\n/** Create a new empty attribute with the same settings: type, shader layout etc. */\nexport function cloneAttribute(attribute: Attribute): Attribute {\n // `attribute.settings` is the original options passed when constructing the attribute.\n // This ensures that we set the proper `doublePrecision` flag and shader attributes.\n const {device, settings, value} = attribute;\n const newAttribute = new Attribute(device, settings);\n // Placeholder value - necessary for generating the correct buffer layout\n newAttribute.setData({\n value: value instanceof Float64Array ? new Float64Array(0) : new Float32Array(0),\n normalized: settings.normalized\n });\n return newAttribute;\n}\n\n/** Returns the GLSL attribute type for the given number of float32 components. */\nexport function getAttributeTypeFromSize(size: number): string {\n switch (size) {\n case 1:\n return 'float';\n case 2:\n return 'vec2';\n case 3:\n return 'vec3';\n case 4:\n return 'vec4';\n default:\n throw new Error(`No defined attribute type for size \"${size}\"`);\n }\n}\n\n/** Returns the {@link VertexFormat} for the given number of float32 components. */\nexport function getFloat32VertexFormat(size: number): VertexFormat {\n switch (size) {\n case 1:\n return 'float32';\n case 2:\n return 'float32x2';\n case 3:\n return 'float32x3';\n case 4:\n return 'float32x4';\n default:\n throw new Error('invalid type size');\n }\n}\n\nexport function cycleBuffers(buffers: Buffer[]): void {\n buffers.push(buffers.shift() as Buffer);\n}\n\nexport function getAttributeBufferLength(attribute: Attribute, numInstances: number): number {\n const {doublePrecision, settings, value, size} = attribute;\n const multiplier = doublePrecision && value instanceof Float64Array ? 2 : 1;\n let maxVertexOffset = 0;\n const {shaderAttributes} = attribute.settings;\n if (shaderAttributes) {\n for (const shaderAttribute of Object.values(shaderAttributes)) {\n maxVertexOffset = Math.max(maxVertexOffset, shaderAttribute.vertexOffset ?? 0);\n }\n }\n return (\n (settings.noAlloc ? (value as NumericArray).length : (numInstances + maxVertexOffset) * size) *\n multiplier\n );\n}\n\nexport function matchBuffer({\n device,\n source,\n target\n}: {\n device: Device;\n source: Buffer;\n target?: Buffer;\n}): Buffer {\n if (!target || target.byteLength < source.byteLength) {\n target?.destroy();\n target = device.createBuffer({\n byteLength: source.byteLength,\n usage: source.usage\n });\n }\n return target;\n}\n\n/* eslint-disable complexity */\n// This helper is used when transitioning attributes from a set of values in one buffer layout\n// to a set of values in a different buffer layout. (Buffer layouts are used when attribute values\n// within a buffer should be grouped for drawElements, like the Polygon layer.) For example, a\n// buffer layout of [3, 4] might have data [A1, A2, A3, B1, B2, B3, B4]. If it needs to transition\n// to a buffer layout of [4, 2], it should produce a buffer, using the transition setting's `enter`\n// function, that looks like this: [A1, A2, A3, A4 (user `enter` fn), B1, B2, 0]. Note: the final\n// 0 in this buffer is because we never shrink buffers, only grow them, for performance reasons.\n//\n// padBuffer may return either the original buffer, or a new buffer if the size of the original\n// was insufficient. Callers are responsible for disposing of the original buffer if needed.\nexport function padBuffer({\n device,\n buffer,\n attribute,\n fromLength,\n toLength,\n fromStartIndices,\n getData = x => x\n}: {\n device: Device;\n buffer?: Buffer;\n attribute: Attribute;\n fromLength: number;\n toLength: number;\n fromStartIndices?: NumericArray | null;\n getData?: (toValue: NumericArray, chunk?: NumericArray) => NumericArray;\n}): Buffer {\n // TODO: move the precisionMultiplier logic to the attribute when retrieving\n // its `size` and `elementOffset`?\n const precisionMultiplier =\n attribute.doublePrecision && attribute.value instanceof Float64Array ? 2 : 1;\n const size = attribute.size * precisionMultiplier;\n const byteOffset = attribute.byteOffset;\n // Transform feedback can only write to float varyings\n // Attributes of format unorm8/uint8 (1 byte per element) etc will be padded to float32 (4 bytes per element)\n const targetByteOffset =\n attribute.settings.bytesPerElement < 4\n ? (byteOffset / attribute.settings.bytesPerElement) * 4\n : byteOffset;\n const toStartIndices = attribute.startIndices;\n const hasStartIndices = fromStartIndices && toStartIndices;\n const isConstant = attribute.isConstant;\n\n // check if buffer needs to be padded\n if (!hasStartIndices && buffer && fromLength >= toLength) {\n return buffer;\n }\n\n const ArrayType =\n attribute.value instanceof Float64Array\n ? Float32Array\n : ((attribute.value as TypedArray).constructor as TypedArrayConstructor);\n const toData = isConstant\n ? (attribute.value as TypedArray)\n : // TODO(v9.1): Avoid non-portable synchronous reads.\n new ArrayType(\n attribute.getBuffer()!.readSyncWebGL(byteOffset, toLength * ArrayType.BYTES_PER_ELEMENT)\n .buffer as ArrayBuffer\n );\n if (attribute.settings.normalized && !isConstant) {\n const getter = getData;\n getData = (value, chunk) => attribute.normalizeConstant(getter(value, chunk));\n }\n\n const getMissingData = isConstant\n ? (i: number, chunk: NumericArray) => getData(toData, chunk)\n : (i: number, chunk: NumericArray) =>\n getData(toData.subarray(i + byteOffset, i + byteOffset + size), chunk);\n\n // TODO(v9.1): Avoid non-portable synchronous reads.\n const source = buffer\n ? new Float32Array(buffer.readSyncWebGL(targetByteOffset, fromLength * 4).buffer as ArrayBuffer)\n : new Float32Array(0);\n const target = new Float32Array(toLength);\n padArray({\n source,\n target,\n sourceStartIndices: fromStartIndices,\n targetStartIndices: toStartIndices,\n size,\n getData: getMissingData\n });\n\n if (!buffer || buffer.byteLength < target.byteLength + targetByteOffset) {\n buffer?.destroy();\n buffer = device.createBuffer({\n byteLength: target.byteLength + targetByteOffset,\n usage: GL.DYNAMIC_COPY\n });\n }\n buffer.write(target, targetByteOffset);\n return buffer;\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport Transition from './transition';\nimport {cloneAttribute, getAttributeBufferLength} from './gpu-transition-utils';\n\nimport type {Device, Buffer} from '@luma.gl/core';\nimport type {Timeline} from '@luma.gl/engine';\nimport type Attribute from '../lib/attribute/attribute';\nimport type {TransitionSettings} from '../lib/attribute/transition-settings';\nimport type {NumericArray} from '../types/types';\n\nexport interface GPUTransition {\n get type(): string;\n get inProgress(): boolean;\n get attributeInTransition(): Attribute;\n\n /** Called when an attribute's values have changed and we need to start animating towards the new values */\n start(transitionSettings: TransitionSettings, numInstances: number): void;\n /** Called while transition is in progress */\n update(): boolean;\n /** Called when transition is interrupted */\n cancel(): void;\n /** Called when transition is disposed */\n delete(): void;\n}\n\nexport abstract class GPUTransitionBase\n implements GPUTransition\n{\n abstract get type(): string;\n\n device: Device;\n attribute: Attribute;\n transition: Transition;\n settings?: SettingsT;\n /** The attribute that holds the buffer in transition */\n attributeInTransition: Attribute;\n protected buffers: Buffer[] = [];\n /** The vertex count of the last buffer.\n * Buffer may be larger than the actual length we want to use\n * because we only reallocate buffers when they grow, not when they shrink,\n * due to performance costs */\n protected currentLength: number = 0;\n /** The start indices of the last buffer. */\n protected currentStartIndices: NumericArray | null;\n\n constructor({\n device,\n attribute,\n timeline\n }: {\n device: Device;\n attribute: Attribute;\n timeline: Timeline;\n }) {\n this.device = device;\n this.transition = new Transition(timeline);\n this.attribute = attribute;\n this.attributeInTransition = cloneAttribute(attribute);\n this.currentStartIndices = attribute.startIndices;\n }\n\n get inProgress(): boolean {\n return this.transition.inProgress;\n }\n\n start(transitionSettings: SettingsT, numInstances: number, duration: number = Infinity) {\n this.settings = transitionSettings;\n this.currentStartIndices = this.attribute.startIndices;\n this.currentLength = getAttributeBufferLength(this.attribute, numInstances);\n this.transition.start({...transitionSettings, duration});\n }\n\n update(): boolean {\n const updated = this.transition.update();\n if (updated) {\n this.onUpdate();\n }\n return updated;\n }\n\n abstract onUpdate(): void;\n\n protected setBuffer(buffer: Buffer) {\n this.attributeInTransition.setData({\n buffer,\n normalized: this.attribute.settings.normalized,\n // Retain placeholder value to generate correct shader layout\n value: this.attributeInTransition.value as NumericArray\n });\n }\n\n cancel(): void {\n this.transition.cancel();\n }\n\n delete(): void {\n this.cancel();\n for (const buffer of this.buffers) {\n buffer.destroy();\n }\n this.buffers.length = 0;\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '@luma.gl/core';\nimport {Timeline, BufferTransform} from '@luma.gl/engine';\nimport {fp64arithmetic} from '@luma.gl/shadertools';\nimport type {ShaderModule} from '@luma.gl/shadertools';\nimport {GL} from '@luma.gl/webgl/constants';\nimport Attribute from '../lib/attribute/attribute';\nimport {\n getAttributeTypeFromSize,\n cycleBuffers,\n padBuffer,\n matchBuffer,\n getFloat32VertexFormat\n} from './gpu-transition-utils';\nimport {GPUTransitionBase} from './gpu-transition';\n\nimport type {InterpolationTransitionSettings} from '../lib/attribute/transition-settings';\nimport type {TypedArray} from '../types/types';\n\nexport default class GPUInterpolationTransition extends GPUTransitionBase {\n type = 'interpolation';\n\n private transform: BufferTransform;\n\n constructor({\n device,\n attribute,\n timeline\n }: {\n device: Device;\n attribute: Attribute;\n timeline: Timeline;\n }) {\n super({device, attribute, timeline});\n this.transform = getTransform(device, attribute);\n }\n\n override start(transitionSettings: InterpolationTransitionSettings, numInstances: number): void {\n const prevLength = this.currentLength;\n const prevStartIndices = this.currentStartIndices;\n\n super.start(transitionSettings, numInstances, transitionSettings.duration);\n\n if (transitionSettings.duration <= 0) {\n this.transition.cancel();\n return;\n }\n\n const {buffers, attribute} = this;\n // Alternate between two buffers when new transitions start.\n // Last destination buffer is used as an attribute (from state),\n // And the other buffer is now the current buffer.\n cycleBuffers(buffers);\n\n buffers[0] = padBuffer({\n device: this.device,\n buffer: buffers[0],\n attribute,\n fromLength: prevLength,\n toLength: this.currentLength,\n fromStartIndices: prevStartIndices,\n getData: transitionSettings.enter\n });\n buffers[1] = matchBuffer({\n device: this.device,\n source: buffers[0],\n target: buffers[1]\n });\n\n this.setBuffer(buffers[1]);\n\n const {transform} = this;\n const model = transform.model;\n let vertexCount = Math.floor(this.currentLength / attribute.size);\n if (useFp64(attribute)) {\n vertexCount /= 2;\n }\n model.setVertexCount(vertexCount);\n if (attribute.isConstant) {\n model.setAttributes({aFrom: buffers[0]});\n model.setConstantAttributes({aTo: attribute.value as TypedArray});\n } else {\n model.setAttributes({\n aFrom: buffers[0],\n aTo: attribute.getBuffer()!\n });\n }\n transform.transformFeedback.setBuffers({vCurrent: buffers[1]});\n }\n\n onUpdate() {\n const {duration, easing} = this.settings!;\n const {time} = this.transition;\n let t = time / duration;\n if (easing) {\n t = easing(t);\n }\n const {model} = this.transform;\n const interpolationProps: InterpolationProps = {time: t};\n model.shaderInputs.setProps({interpolation: interpolationProps});\n\n this.transform.run({discard: true});\n }\n\n override delete() {\n super.delete();\n this.transform.destroy();\n }\n}\n\nconst uniformBlock = `\\\nlayout(std140) uniform interpolationUniforms {\n float time;\n} interpolation;\n`;\n\ntype InterpolationProps = {time: number};\n\nconst interpolationUniforms = {\n name: 'interpolation',\n vs: uniformBlock,\n uniformTypes: {\n time: 'f32'\n }\n} as const satisfies ShaderModule;\n\nconst vs = `\\\n#version 300 es\n#define SHADER_NAME interpolation-transition-vertex-shader\n\nin ATTRIBUTE_TYPE aFrom;\nin ATTRIBUTE_TYPE aTo;\nout ATTRIBUTE_TYPE vCurrent;\n\nvoid main(void) {\n vCurrent = mix(aFrom, aTo, interpolation.time);\n gl_Position = vec4(0.0);\n}\n`;\nconst vs64 = `\\\n#version 300 es\n#define SHADER_NAME interpolation-transition-vertex-shader\n\nin ATTRIBUTE_TYPE aFrom;\nin ATTRIBUTE_TYPE aFrom64Low;\nin ATTRIBUTE_TYPE aTo;\nin ATTRIBUTE_TYPE aTo64Low;\nout ATTRIBUTE_TYPE vCurrent;\nout ATTRIBUTE_TYPE vCurrent64Low;\n\nvec2 mix_fp64(vec2 a, vec2 b, float x) {\n vec2 range = sub_fp64(b, a);\n return sum_fp64(a, mul_fp64(range, vec2(x, 0.0)));\n}\n\nvoid main(void) {\n for (int i=0; i {\n type = 'spring';\n\n private texture: Texture;\n private framebuffer: Framebuffer;\n private transform: BufferTransform;\n\n constructor({\n device,\n attribute,\n timeline\n }: {\n device: Device;\n attribute: Attribute;\n timeline: Timeline;\n }) {\n super({device, attribute, timeline});\n this.texture = getTexture(device);\n this.framebuffer = getFramebuffer(device, this.texture);\n this.transform = getTransform(device, attribute);\n }\n\n override start(transitionSettings: SpringTransitionSettings, numInstances: number): void {\n const prevLength = this.currentLength;\n const prevStartIndices = this.currentStartIndices;\n super.start(transitionSettings, numInstances);\n\n const {buffers, attribute} = this;\n\n for (let i = 0; i < 2; i++) {\n buffers[i] = padBuffer({\n device: this.device,\n buffer: buffers[i],\n attribute,\n fromLength: prevLength,\n toLength: this.currentLength,\n fromStartIndices: prevStartIndices,\n getData: transitionSettings.enter\n });\n }\n buffers[2] = matchBuffer({\n device: this.device,\n source: buffers[0],\n target: buffers[2]\n });\n\n this.setBuffer(buffers[1]);\n\n const {model} = this.transform;\n model.setVertexCount(Math.floor(this.currentLength / attribute.size));\n if (attribute.isConstant) {\n model.setConstantAttributes({aTo: attribute.value as TypedArray});\n } else {\n model.setAttributes({aTo: attribute.getBuffer()!});\n }\n }\n\n onUpdate() {\n const {buffers, transform, framebuffer, transition} = this;\n\n const settings = this.settings as SpringTransitionSettings;\n\n transform.model.setAttributes({\n aPrev: buffers[0],\n aCur: buffers[1]\n });\n transform.transformFeedback.setBuffers({vNext: buffers[2]});\n const springProps: SpringProps = {\n stiffness: settings.stiffness,\n damping: settings.damping\n };\n transform.model.shaderInputs.setProps({spring: springProps});\n transform.run({\n framebuffer,\n discard: false,\n parameters: {viewport: [0, 0, 1, 1]},\n clearColor: [0, 0, 0, 0]\n });\n\n cycleBuffers(buffers);\n this.setBuffer(buffers[1]);\n\n const isTransitioning = this.device.readPixelsToArrayWebGL(framebuffer)[0] > 0;\n\n if (!isTransitioning) {\n transition.end();\n }\n }\n\n override delete() {\n super.delete();\n this.transform.destroy();\n this.texture.destroy();\n this.framebuffer.destroy();\n }\n}\n\nconst uniformBlock = `\\\nlayout(std140) uniform springUniforms {\n float damping;\n float stiffness;\n} spring;\n`;\n\ntype SpringProps = {\n damping: number;\n stiffness: number;\n};\n\nconst springUniforms = {\n name: 'spring',\n vs: uniformBlock,\n uniformTypes: {\n damping: 'f32',\n stiffness: 'f32'\n }\n} as const satisfies ShaderModule;\n\nconst vs = `\\\n#version 300 es\n#define SHADER_NAME spring-transition-vertex-shader\n\n#define EPSILON 0.00001\n\nin ATTRIBUTE_TYPE aPrev;\nin ATTRIBUTE_TYPE aCur;\nin ATTRIBUTE_TYPE aTo;\nout ATTRIBUTE_TYPE vNext;\nout float vIsTransitioningFlag;\n\nATTRIBUTE_TYPE getNextValue(ATTRIBUTE_TYPE cur, ATTRIBUTE_TYPE prev, ATTRIBUTE_TYPE dest) {\n ATTRIBUTE_TYPE velocity = cur - prev;\n ATTRIBUTE_TYPE delta = dest - cur;\n ATTRIBUTE_TYPE force = delta * spring.stiffness;\n ATTRIBUTE_TYPE resistance = velocity * spring.damping;\n return force - resistance + velocity + cur;\n}\n\nvoid main(void) {\n bool isTransitioning = length(aCur - aPrev) > EPSILON || length(aTo - aCur) > EPSILON;\n vIsTransitioningFlag = isTransitioning ? 1.0 : 0.0;\n\n vNext = getNextValue(aCur, aPrev, aTo);\n gl_Position = vec4(0, 0, 0, 1);\n gl_PointSize = 100.0;\n}\n`;\n\nconst fs = `\\\n#version 300 es\n#define SHADER_NAME spring-transition-is-transitioning-fragment-shader\n\nin float vIsTransitioningFlag;\n\nout vec4 fragColor;\n\nvoid main(void) {\n if (vIsTransitioningFlag == 0.0) {\n discard;\n }\n fragColor = vec4(1.0);\n}`;\n\nfunction getTransform(device: Device, attribute: Attribute): BufferTransform {\n const attributeType = getAttributeTypeFromSize(attribute.size);\n const format = getFloat32VertexFormat(attribute.size);\n return new BufferTransform(device, {\n vs,\n fs,\n bufferLayout: [\n {name: 'aPrev', format},\n {name: 'aCur', format},\n {name: 'aTo', format: attribute.getBufferLayout().attributes![0].format}\n ],\n varyings: ['vNext'],\n modules: [springUniforms],\n // @ts-expect-error TODO fix luma type\n defines: {ATTRIBUTE_TYPE: attributeType},\n parameters: {\n depthCompare: 'always',\n blendColorOperation: 'max',\n blendColorSrcFactor: 'one',\n blendColorDstFactor: 'one',\n blendAlphaOperation: 'max',\n blendAlphaSrcFactor: 'one',\n blendAlphaDstFactor: 'one'\n }\n });\n}\n\nfunction getTexture(device: Device): Texture {\n return device.createTexture({\n data: new Uint8Array(4),\n format: 'rgba8unorm',\n width: 1,\n height: 1\n });\n}\n\nfunction getFramebuffer(device: Device, texture: Texture): Framebuffer {\n return device.createFramebuffer({\n id: 'spring-transition-is-transitioning-framebuffer',\n width: 1,\n height: 1,\n colorAttachments: [texture]\n });\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// deck.gl, MIT license\n\nimport GPUInterpolationTransition from '../../transitions/gpu-interpolation-transition';\nimport GPUSpringTransition from '../../transitions/gpu-spring-transition';\nimport log from '../../utils/log';\n\nimport type {Device} from '@luma.gl/core';\nimport type {Timeline} from '@luma.gl/engine';\nimport type {GPUTransition} from '../../transitions/gpu-transition';\nimport type {ConstructorOf} from '../../types/types';\nimport type Attribute from './attribute';\nimport type {TransitionSettings} from './transition-settings';\n\nconst TRANSITION_TYPES: Record> = {\n interpolation: GPUInterpolationTransition,\n spring: GPUSpringTransition\n};\n\nexport default class AttributeTransitionManager {\n id: string;\n\n private device: Device;\n private timeline?: Timeline;\n\n private transitions: {[id: string]: GPUTransition};\n private needsRedraw: boolean;\n private numInstances: number;\n\n constructor(\n device: Device,\n {\n id,\n timeline\n }: {\n id: string;\n timeline?: Timeline;\n }\n ) {\n if (!device) throw new Error('AttributeTransitionManager is constructed without device');\n this.id = id;\n this.device = device;\n this.timeline = timeline;\n\n this.transitions = {};\n this.needsRedraw = false;\n this.numInstances = 1;\n }\n\n finalize(): void {\n for (const attributeName in this.transitions) {\n this._removeTransition(attributeName);\n }\n }\n\n /* Public methods */\n\n // Called when attribute manager updates\n // Check the latest attributes for updates.\n update({\n attributes,\n transitions,\n numInstances\n }: {\n attributes: {[id: string]: Attribute};\n transitions: any;\n numInstances: number;\n }): void {\n // Transform class will crash if elementCount is 0\n this.numInstances = numInstances || 1;\n\n for (const attributeName in attributes) {\n const attribute = attributes[attributeName];\n const settings = attribute.getTransitionSetting(transitions);\n\n // this attribute might not support transitions?\n if (!settings) continue; // eslint-disable-line no-continue\n this._updateAttribute(attributeName, attribute, settings);\n }\n\n for (const attributeName in this.transitions) {\n const attribute = attributes[attributeName];\n if (!attribute || !attribute.getTransitionSetting(transitions)) {\n // Animated attribute has been removed\n this._removeTransition(attributeName);\n }\n }\n }\n\n // Returns `true` if attribute is transition-enabled\n hasAttribute(attributeName: string): boolean {\n const transition = this.transitions[attributeName];\n return transition && transition.inProgress;\n }\n\n // Get all the animated attributes\n getAttributes(): {[id: string]: Attribute} {\n const animatedAttributes = {};\n\n for (const attributeName in this.transitions) {\n const transition = this.transitions[attributeName];\n if (transition.inProgress) {\n animatedAttributes[attributeName] = transition.attributeInTransition;\n }\n }\n\n return animatedAttributes;\n }\n\n /* eslint-disable max-statements */\n // Called every render cycle, run transform feedback\n // Returns `true` if anything changes\n run(): boolean {\n if (this.numInstances === 0) {\n return false;\n }\n\n for (const attributeName in this.transitions) {\n const updated = this.transitions[attributeName].update();\n if (updated) {\n this.needsRedraw = true;\n }\n }\n\n const needsRedraw = this.needsRedraw;\n this.needsRedraw = false;\n return needsRedraw;\n }\n /* eslint-enable max-statements */\n\n /* Private methods */\n private _removeTransition(attributeName: string): void {\n this.transitions[attributeName].delete();\n delete this.transitions[attributeName];\n }\n\n // Check an attributes for updates\n // Returns a transition object if a new transition is triggered.\n private _updateAttribute(\n attributeName: string,\n attribute: Attribute,\n settings: TransitionSettings\n ): void {\n const transition = this.transitions[attributeName];\n // an attribute can change transition type when it updates\n // let's remove the transition when that happens so we can create the new transition type\n // TODO: when switching transition types, make sure to carry over the attribute's\n // previous buffers, currentLength, startIndices, etc, to be used as the starting point\n // for the next transition\n let isNew = !transition || transition.type !== settings.type;\n\n if (isNew) {\n if (transition) {\n this._removeTransition(attributeName);\n }\n\n const TransitionType = TRANSITION_TYPES[settings.type];\n if (TransitionType) {\n this.transitions[attributeName] = new TransitionType({\n attribute,\n timeline: this.timeline,\n device: this.device\n });\n } else {\n log.error(`unsupported transition type '${settings.type}'`)();\n isNew = false;\n }\n }\n\n if (isNew || attribute.needsRedraw()) {\n this.needsRedraw = true;\n this.transitions[attributeName].start(settings, this.numInstances);\n }\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/* eslint-disable guard-for-in */\nimport Attribute, {AttributeOptions} from './attribute';\nimport log from '../../utils/log';\nimport memoize from '../../utils/memoize';\nimport {mergeBounds} from '../../utils/math-utils';\nimport debug from '../../debug/index';\nimport {NumericArray} from '../../types/types';\n\nimport AttributeTransitionManager from './attribute-transition-manager';\n\nimport type {Device, BufferLayout} from '@luma.gl/core';\nimport type {Stats} from '@probe.gl/stats';\nimport type {Timeline} from '@luma.gl/engine';\n\nconst TRACE_INVALIDATE = 'attributeManager.invalidate';\nconst TRACE_UPDATE_START = 'attributeManager.updateStart';\nconst TRACE_UPDATE_END = 'attributeManager.updateEnd';\nconst TRACE_ATTRIBUTE_UPDATE_START = 'attribute.updateStart';\nconst TRACE_ATTRIBUTE_ALLOCATE = 'attribute.allocate';\nconst TRACE_ATTRIBUTE_UPDATE_END = 'attribute.updateEnd';\n\nexport default class AttributeManager {\n /**\n * @classdesc\n * Automated attribute generation and management. Suitable when a set of\n * vertex shader attributes are generated by iteration over a data array,\n * and updates to these attributes are needed either when the data itself\n * changes, or when other data relevant to the calculations change.\n *\n * - First the application registers descriptions of its dynamic vertex\n * attributes using AttributeManager.add().\n * - Then, when any change that affects attributes is detected by the\n * application, the app will call AttributeManager.invalidate().\n * - Finally before it renders, it calls AttributeManager.update() to\n * ensure that attributes are automatically rebuilt if anything has been\n * invalidated.\n *\n * The application provided update functions describe how attributes\n * should be updated from a data array and are expected to traverse\n * that data array (or iterable) and fill in the attribute's typed array.\n *\n * Note that the attribute manager intentionally does not do advanced\n * change detection, but instead makes it easy to build such detection\n * by offering the ability to \"invalidate\" each attribute separately.\n */\n id: string;\n device: Device;\n attributes: Record;\n updateTriggers: {[name: string]: string[]};\n needsRedraw: string | boolean;\n userData: any;\n\n private stats?: Stats;\n private attributeTransitionManager: AttributeTransitionManager;\n private mergeBoundsMemoized: any = memoize(mergeBounds);\n\n constructor(\n device: Device,\n {\n id = 'attribute-manager',\n stats,\n timeline\n }: {\n id?: string;\n stats?: Stats;\n timeline?: Timeline;\n } = {}\n ) {\n this.id = id;\n this.device = device;\n\n this.attributes = {};\n\n this.updateTriggers = {};\n this.needsRedraw = true;\n\n this.userData = {};\n this.stats = stats;\n\n this.attributeTransitionManager = new AttributeTransitionManager(device, {\n id: `${id}-transitions`,\n timeline\n });\n\n // For debugging sanity, prevent uninitialized members\n Object.seal(this);\n }\n\n finalize() {\n for (const attributeName in this.attributes) {\n this.attributes[attributeName].delete();\n }\n this.attributeTransitionManager.finalize();\n }\n\n // Returns the redraw flag, optionally clearing it.\n // Redraw flag will be set if any attributes attributes changed since\n // flag was last cleared.\n //\n // @param {String} [clearRedrawFlags=false] - whether to clear the flag\n // @return {false|String} - reason a redraw is needed.\n getNeedsRedraw(opts: {clearRedrawFlags?: boolean} = {clearRedrawFlags: false}): string | false {\n const redraw = this.needsRedraw;\n this.needsRedraw = this.needsRedraw && !opts.clearRedrawFlags;\n return redraw && this.id;\n }\n\n // Sets the redraw flag.\n // @param {Boolean} redraw=true\n setNeedsRedraw() {\n this.needsRedraw = true;\n }\n\n // Adds attributes\n add(attributes: {[id: string]: AttributeOptions}) {\n this._add(attributes);\n }\n\n // Adds attributes\n addInstanced(attributes: {[id: string]: AttributeOptions}) {\n this._add(attributes, {stepMode: 'instance'});\n }\n\n /**\n * Removes attributes\n * Takes an array of attribute names and delete them from\n * the attribute map if they exists\n *\n * @example\n * attributeManager.remove(['position']);\n *\n * @param {Object} attributeNameArray - attribute name array (see above)\n */\n remove(attributeNameArray: string[]) {\n for (const name of attributeNameArray) {\n if (this.attributes[name] !== undefined) {\n this.attributes[name].delete();\n delete this.attributes[name];\n }\n }\n }\n\n // Marks an attribute for update\n invalidate(triggerName: string, dataRange?: {startRow?: number; endRow?: number}) {\n const invalidatedAttributes = this._invalidateTrigger(triggerName, dataRange);\n // For performance tuning\n debug(TRACE_INVALIDATE, this, triggerName, invalidatedAttributes);\n }\n\n invalidateAll(dataRange?: {startRow?: number; endRow?: number}) {\n for (const attributeName in this.attributes) {\n this.attributes[attributeName].setNeedsUpdate(attributeName, dataRange);\n }\n // For performance tuning\n debug(TRACE_INVALIDATE, this, 'all');\n }\n\n // Ensure all attribute buffers are updated from props or data.\n // eslint-disable-next-line complexity\n update({\n data,\n numInstances,\n startIndices = null,\n transitions,\n props = {},\n buffers = {},\n context = {}\n }: {\n data: any;\n numInstances: number;\n startIndices?: NumericArray | null;\n transitions: any;\n props: any;\n buffers: any;\n context: any;\n }) {\n // keep track of whether some attributes are updated\n let updated = false;\n\n debug(TRACE_UPDATE_START, this);\n if (this.stats) {\n this.stats.get('Update Attributes').timeStart();\n }\n\n for (const attributeName in this.attributes) {\n const attribute = this.attributes[attributeName];\n const accessorName = attribute.settings.accessor;\n attribute.startIndices = startIndices;\n attribute.numInstances = numInstances;\n\n if (props[attributeName]) {\n log.removed(`props.${attributeName}`, `data.attributes.${attributeName}`)();\n }\n\n if (attribute.setExternalBuffer(buffers[attributeName])) {\n // Step 1: try update attribute directly from external buffers\n } else if (\n attribute.setBinaryValue(\n typeof accessorName === 'string' ? buffers[accessorName] : undefined,\n data.startIndices\n )\n ) {\n // Step 2: try set packed value from external typed array\n } else if (\n typeof accessorName === 'string' &&\n !buffers[accessorName] &&\n attribute.setConstantValue(context, props[accessorName])\n ) {\n // Step 3: try set constant value from props\n // Note: if buffers[accessorName] is supplied, ignore props[accessorName]\n // This may happen when setBinaryValue falls through to use the auto updater\n } else if (attribute.needsUpdate()) {\n // Step 4: update via updater callback\n updated = true;\n this._updateAttribute({\n attribute,\n numInstances,\n data,\n props,\n context\n });\n }\n\n this.needsRedraw = this.needsRedraw || attribute.needsRedraw();\n }\n\n if (updated) {\n // Only initiate alloc/update (and logging) if actually needed\n debug(TRACE_UPDATE_END, this, numInstances);\n }\n\n if (this.stats) {\n this.stats.get('Update Attributes').timeEnd();\n if (updated) this.stats.get('Attributes updated').incrementCount();\n }\n\n this.attributeTransitionManager.update({\n attributes: this.attributes,\n numInstances,\n transitions\n });\n }\n\n // Update attribute transition to the current timestamp\n // Returns `true` if any transition is in progress\n updateTransition() {\n const {attributeTransitionManager} = this;\n const transitionUpdated = attributeTransitionManager.run();\n this.needsRedraw = this.needsRedraw || transitionUpdated;\n return transitionUpdated;\n }\n\n /**\n * Returns all attribute descriptors\n * Note: Format matches luma.gl Model/Program.setAttributes()\n * @return {Object} attributes - descriptors\n */\n getAttributes(): {[id: string]: Attribute} {\n return {...this.attributes, ...this.attributeTransitionManager.getAttributes()};\n }\n\n /**\n * Computes the spatial bounds of a given set of attributes\n */\n getBounds(attributeNames: string[]) {\n const bounds = attributeNames.map(attributeName => this.attributes[attributeName]?.getBounds());\n return this.mergeBoundsMemoized(bounds);\n }\n\n /**\n * Returns changed attribute descriptors\n * This indicates which WebGLBuffers need to be updated\n * @return {Object} attributes - descriptors\n */\n getChangedAttributes(opts: {clearChangedFlags?: boolean} = {clearChangedFlags: false}): {\n [id: string]: Attribute;\n } {\n const {attributes, attributeTransitionManager} = this;\n\n const changedAttributes = {...attributeTransitionManager.getAttributes()};\n\n for (const attributeName in attributes) {\n const attribute = attributes[attributeName];\n if (attribute.needsRedraw(opts) && !attributeTransitionManager.hasAttribute(attributeName)) {\n changedAttributes[attributeName] = attribute;\n }\n }\n\n return changedAttributes;\n }\n\n /** Generate WebGPU-style buffer layout descriptors from all attributes */\n getBufferLayouts(\n /** A luma.gl Model-shaped object that supplies additional hint to attribute resolution */\n modelInfo?: {\n /** Whether the model is instanced */\n isInstanced?: boolean;\n }\n ): BufferLayout[] {\n return Object.values(this.getAttributes()).map(attribute =>\n attribute.getBufferLayout(modelInfo)\n );\n }\n\n // PRIVATE METHODS\n\n /** Register new attributes */\n private _add(\n /** A map from attribute name to attribute descriptors */\n attributes: {[id: string]: AttributeOptions},\n /** Additional attribute settings to pass to all attributes */\n overrideOptions?: Partial\n ) {\n for (const attributeName in attributes) {\n const attribute = attributes[attributeName];\n\n const props: AttributeOptions = {\n ...attribute,\n id: attributeName,\n size: (attribute.isIndexed && 1) || attribute.size || 1,\n ...overrideOptions\n };\n\n // Initialize the attribute descriptor, with WebGL and metadata fields\n this.attributes[attributeName] = new Attribute(this.device, props);\n }\n\n this._mapUpdateTriggersToAttributes();\n }\n\n // build updateTrigger name to attribute name mapping\n private _mapUpdateTriggersToAttributes() {\n const triggers: {[name: string]: string[]} = {};\n\n for (const attributeName in this.attributes) {\n const attribute = this.attributes[attributeName];\n attribute.getUpdateTriggers().forEach(triggerName => {\n if (!triggers[triggerName]) {\n triggers[triggerName] = [];\n }\n triggers[triggerName].push(attributeName);\n });\n }\n\n this.updateTriggers = triggers;\n }\n\n private _invalidateTrigger(\n triggerName: string,\n dataRange?: {startRow?: number; endRow?: number}\n ): string[] {\n const {attributes, updateTriggers} = this;\n const invalidatedAttributes = updateTriggers[triggerName];\n\n if (invalidatedAttributes) {\n invalidatedAttributes.forEach(name => {\n const attribute = attributes[name];\n if (attribute) {\n attribute.setNeedsUpdate(attribute.id, dataRange);\n }\n });\n }\n return invalidatedAttributes;\n }\n\n private _updateAttribute(opts: {\n attribute: Attribute;\n numInstances: number;\n data: any;\n props: any;\n context: any;\n }) {\n const {attribute, numInstances} = opts;\n debug(TRACE_ATTRIBUTE_UPDATE_START, attribute);\n\n if (attribute.constant) {\n // The attribute is flagged as constant outside of an update cycle\n // Skip allocation and updater call\n // @ts-ignore value can be set to an array by user but always cast to typed array during attribute update\n attribute.setConstantValue(opts.context, attribute.value);\n return;\n }\n\n if (attribute.allocate(numInstances)) {\n debug(TRACE_ATTRIBUTE_ALLOCATE, attribute, numInstances);\n }\n\n // Calls update on any buffers that need update\n const updated = attribute.updateBuffer(opts);\n if (updated) {\n this.needsRedraw = true;\n debug(TRACE_ATTRIBUTE_UPDATE_END, attribute, numInstances);\n }\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/* eslint-disable react/no-direct-mutation-state */\nimport {Buffer, Parameters as LumaParameters, TypedArray} from '@luma.gl/core';\nimport {WebGLDevice} from '@luma.gl/webgl';\nimport AttributeManager from './attribute/attribute-manager';\nimport UniformTransitionManager from './uniform-transition-manager';\nimport {diffProps, validateProps} from '../lifecycle/props';\nimport {LIFECYCLE, Lifecycle} from '../lifecycle/constants';\nimport {count} from '../utils/count';\nimport log from '../utils/log';\nimport debug from '../debug/index';\nimport assert from '../utils/assert';\nimport memoize from '../utils/memoize';\nimport {mergeShaders} from '../utils/shader';\nimport {projectPosition, getWorldPosition} from '../shaderlib/project/project-functions';\nimport typedArrayManager from '../utils/typed-array-manager';\n\nimport Component from '../lifecycle/component';\nimport LayerState, {ChangeFlags} from './layer-state';\n\nimport {worldToPixels} from '@math.gl/web-mercator';\n\nimport {load} from '@loaders.gl/core';\n\nimport type {Loader} from '@loaders.gl/loader-utils';\nimport type {CoordinateSystem} from './constants';\nimport type Attribute from './attribute/attribute';\nimport type {Model} from '@luma.gl/engine';\nimport type {PickingInfo, GetPickingInfoParams} from './picking/pick-info';\nimport type Viewport from '../viewports/viewport';\nimport type {NumericArray} from '../types/types';\nimport type {DefaultProps} from '../lifecycle/prop-types';\nimport type {LayerData, LayerProps} from '../types/layer-props';\nimport type {LayerContext} from './layer-manager';\nimport type {BinaryAttribute} from './attribute/attribute';\nimport {RenderPass} from '@luma.gl/core';\nimport {PickingProps} from '@luma.gl/shadertools';\n\nconst TRACE_CHANGE_FLAG = 'layer.changeFlag';\nconst TRACE_INITIALIZE = 'layer.initialize';\nconst TRACE_UPDATE = 'layer.update';\nconst TRACE_FINALIZE = 'layer.finalize';\nconst TRACE_MATCHED = 'layer.matched';\n\nconst MAX_PICKING_COLOR_CACHE_SIZE = 2 ** 24 - 1;\n\nconst EMPTY_ARRAY = Object.freeze([]);\n\n// Only compare the same two viewports once\nconst areViewportsEqual = memoize(\n ({oldViewport, viewport}: {oldViewport: Viewport; viewport: Viewport}): boolean => {\n return oldViewport.equals(viewport);\n }\n);\n\nlet pickingColorCache = new Uint8ClampedArray(0);\n\nconst defaultProps: DefaultProps = {\n // data: Special handling for null, see below\n data: {type: 'data', value: EMPTY_ARRAY, async: true},\n dataComparator: {type: 'function', value: null, optional: true},\n _dataDiff: {\n type: 'function',\n // @ts-ignore __diff is not defined on data\n value: data => data && data.__diff,\n optional: true\n },\n dataTransform: {type: 'function', value: null, optional: true},\n onDataLoad: {type: 'function', value: null, optional: true},\n onError: {type: 'function', value: null, optional: true},\n fetch: {\n type: 'function',\n value: (\n url: string,\n {\n propName,\n layer,\n loaders,\n loadOptions,\n signal\n }: {\n propName: string;\n layer: LayerT;\n loaders?: Loader[];\n loadOptions?: any;\n signal?: AbortSignal;\n }\n ) => {\n const {resourceManager} = layer.context;\n loadOptions = loadOptions || layer.getLoadOptions();\n loaders = loaders || layer.props.loaders;\n if (signal) {\n loadOptions = {\n ...loadOptions,\n core: {\n ...loadOptions?.core,\n fetch: {\n ...loadOptions?.core?.fetch,\n signal\n }\n }\n };\n }\n\n let inResourceManager = resourceManager.contains(url);\n\n if (!inResourceManager && !loadOptions) {\n // If there is no layer-specific load options, then attempt to cache this resource in the data manager\n resourceManager.add({resourceId: url, data: load(url, loaders), persistent: false});\n inResourceManager = true;\n }\n if (inResourceManager) {\n return resourceManager.subscribe({\n resourceId: url,\n onChange: data => layer.internalState?.reloadAsyncProp(propName, data),\n consumerId: layer.id,\n requestId: propName\n });\n }\n\n return load(url, loaders, loadOptions);\n }\n },\n updateTriggers: {}, // Update triggers: a core change detection mechanism in deck.gl\n\n visible: true,\n pickable: false,\n opacity: {type: 'number', min: 0, max: 1, value: 1},\n operation: 'draw',\n\n onHover: {type: 'function', value: null, optional: true},\n onClick: {type: 'function', value: null, optional: true},\n onDragStart: {type: 'function', value: null, optional: true},\n onDrag: {type: 'function', value: null, optional: true},\n onDragEnd: {type: 'function', value: null, optional: true},\n\n coordinateSystem: 'default',\n coordinateOrigin: {type: 'array', value: [0, 0, 0], compare: true},\n modelMatrix: {type: 'array', value: null, compare: true, optional: true},\n wrapLongitude: false,\n positionFormat: 'XYZ',\n colorFormat: 'RGBA',\n\n parameters: {type: 'object', value: {}, optional: true, compare: 2},\n loadOptions: {type: 'object', value: null, optional: true, ignore: true},\n transitions: null,\n extensions: [],\n loaders: {type: 'array', value: [], optional: true, ignore: true},\n\n // Offset depth based on layer index to avoid z-fighting.\n // Negative values pull layer towards the camera\n // https://www.opengl.org/archives/resources/faq/technical/polygonoffset.htm\n getPolygonOffset: {\n type: 'function',\n value: ({layerIndex}) => [0, -layerIndex * 100]\n },\n\n // Selection/Highlighting\n highlightedObjectIndex: null,\n autoHighlight: false,\n highlightColor: {type: 'accessor', value: [0, 0, 128, 128]}\n};\n\nexport type UpdateParameters = {\n props: LayerT['props'];\n oldProps: LayerT['props'];\n context: LayerContext;\n changeFlags: ChangeFlags;\n};\n\ntype DrawOptions = {\n renderPass: RenderPass;\n shaderModuleProps: any;\n uniforms: any;\n parameters: any;\n context: LayerContext;\n};\n\ntype SharedLayerState = {\n [key: string]: unknown;\n};\n\nexport default abstract class Layer extends Component<\n PropsT & Required\n> {\n static defaultProps: DefaultProps = defaultProps;\n static layerName: string = 'Layer';\n\n static override get componentName() {\n return Object.prototype.hasOwnProperty.call(this, 'layerName') ? this.layerName : '';\n }\n\n internalState: LayerState | null = null;\n lifecycle: Lifecycle = LIFECYCLE.NO_STATE; // Helps track and debug the life cycle of the layers\n\n // context and state can technically be null before a layer is initialized/matched.\n // However, they are most extensively accessed in a layer's lifecycle methods, where they are always defined.\n // Checking for null state constantly in layer implementation is unnecessarily verbose.\n context!: LayerContext; // Will reference layer manager's context, contains state shared by layers\n state!: SharedLayerState; // Will be set to the shared layer state object during layer matching\n\n parent: Layer | null = null;\n\n get root(): Layer {\n // eslint-disable-next-line\n let layer: Layer = this;\n while (layer.parent) {\n layer = layer.parent;\n }\n return layer;\n }\n\n toString(): string {\n const className = (this.constructor as typeof Layer).layerName || this.constructor.name;\n return `${className}({id: '${this.props.id}'})`;\n }\n\n // Public API for users\n\n /** Projects a point with current view state from the current layer's coordinate system to screen */\n project(xyz: number[]): number[] {\n assert(this.internalState);\n const viewport = this.internalState.viewport || this.context.viewport;\n\n const worldPosition = getWorldPosition(xyz, {\n viewport,\n modelMatrix: this.props.modelMatrix,\n coordinateOrigin: this.props.coordinateOrigin,\n coordinateSystem: this.props.coordinateSystem\n });\n const [x, y, z] = worldToPixels(worldPosition, viewport.pixelProjectionMatrix);\n return xyz.length === 2 ? [x, y] : [x, y, z];\n }\n\n /** Unprojects a screen pixel to the current view's default coordinate system\n Note: this does not reverse `project`. */\n unproject(xy: number[]): number[] {\n assert(this.internalState);\n const viewport = this.internalState.viewport || this.context.viewport;\n return viewport.unproject(xy);\n }\n\n /** Projects a point with current view state from the current layer's coordinate system to the world space */\n projectPosition(\n xyz: number[],\n params?: {\n /** The viewport to use */\n viewport?: Viewport;\n /** The coordinate system that the supplied position is in. Default to the same as `coordinateSystem`. */\n fromCoordinateSystem?: CoordinateSystem;\n /** The coordinate origin that the supplied position is in. Default to the same as `coordinateOrigin`. */\n fromCoordinateOrigin?: [number, number, number];\n /** Whether to apply offset mode automatically as does the project shader module.\n * Offset mode places the origin of the common space at the given viewport's center. It is used in some use cases\n * to improve precision in the vertex shader due to the fp32 float limitation.\n * Use `autoOffset:false` if the returned position should not be dependent on the current viewport.\n * Default `true` */\n autoOffset?: boolean;\n }\n ): [number, number, number] {\n assert(this.internalState);\n const viewport = this.internalState.viewport || this.context.viewport;\n\n return projectPosition(xyz, {\n viewport,\n modelMatrix: this.props.modelMatrix,\n coordinateOrigin: this.props.coordinateOrigin,\n coordinateSystem: this.props.coordinateSystem,\n ...params\n });\n }\n\n // Public API for custom layer implementation\n\n /** `true` if this layer renders other layers */\n get isComposite(): boolean {\n return false;\n }\n\n /** `true` if the layer renders to screen */\n get isDrawable(): boolean {\n return true;\n }\n\n /** Updates selected state members and marks the layer for redraw */\n setState(partialState: any): void {\n this.setChangeFlags({stateChanged: true});\n Object.assign(this.state, partialState);\n this.setNeedsRedraw();\n }\n\n /** Sets the redraw flag for this layer, will trigger a redraw next animation frame */\n setNeedsRedraw(): void {\n if (this.internalState) {\n this.internalState.needsRedraw = true;\n }\n }\n\n /** Mark this layer as needs a deep update */\n setNeedsUpdate() {\n if (this.internalState) {\n this.context.layerManager.setNeedsUpdate(String(this));\n this.internalState.needsUpdate = true;\n }\n }\n\n /** Returns true if all async resources are loaded */\n get isLoaded(): boolean {\n return this.internalState ? !this.internalState.isAsyncPropLoading() : false;\n }\n\n /** Returns true if using shader-based WGS84 longitude wrapping */\n get wrapLongitude(): boolean {\n return this.props.wrapLongitude;\n }\n\n /** @deprecated Returns true if the layer is visible in the picking pass */\n isPickable(): boolean {\n return this.props.pickable && this.props.visible;\n }\n\n /** Returns an array of models used by this layer, can be overriden by layer subclass */\n getModels(): Model[] {\n const state = this.state as {\n models?: Model[];\n model: Model;\n };\n return (state && (state.models || (state.model && [state.model]))) || [];\n }\n\n /** Update shader input parameters */\n setShaderModuleProps(...props: Parameters): void {\n for (const model of this.getModels()) {\n model.shaderInputs.setProps(...props);\n }\n }\n\n /** Returns the attribute manager of this layer */\n getAttributeManager(): AttributeManager | null {\n return this.internalState && this.internalState.attributeManager;\n }\n\n /** Returns the most recent layer that matched to this state\n (When reacting to an async event, this layer may no longer be the latest) */\n getCurrentLayer(): Layer | null {\n return this.internalState && this.internalState.layer;\n }\n\n /** Returns the default parse options for async props */\n getLoadOptions(): any {\n return this.props.loadOptions;\n }\n\n use64bitPositions(): boolean {\n const {coordinateSystem} = this.props;\n return (\n coordinateSystem === 'default' ||\n coordinateSystem === 'lnglat' ||\n coordinateSystem === 'cartesian'\n );\n }\n\n // Event handling\n onHover(info: PickingInfo, pickingEvent): boolean {\n if (this.props.onHover) {\n return this.props.onHover(info, pickingEvent) || false;\n }\n return false;\n }\n\n onClick(info: PickingInfo, pickingEvent): boolean {\n if (this.props.onClick) {\n return this.props.onClick(info, pickingEvent) || false;\n }\n return false;\n }\n\n // Returns the picking color that doesn't match any subfeature\n // Use if some graphics do not belong to any pickable subfeature\n // @return {Array} - a black color\n nullPickingColor() {\n return [0, 0, 0];\n }\n\n // Returns the picking color that doesn't match any subfeature\n // Use if some graphics do not belong to any pickable subfeature\n encodePickingColor(i, target: number[] = []): [number, number, number] {\n target[0] = (i + 1) & 255;\n target[1] = ((i + 1) >> 8) & 255;\n target[2] = (((i + 1) >> 8) >> 8) & 255;\n return target as [number, number, number];\n }\n\n // Returns the index corresponding to a picking color that doesn't match any subfeature\n // @param {Uint8Array} color - color array to be decoded\n // @return {Array} - the decoded picking color\n decodePickingColor(color) {\n assert(color instanceof Uint8Array);\n const [i1, i2, i3] = color;\n // 1 was added to seperate from no selection\n const index = i1 + i2 * 256 + i3 * 65536 - 1;\n return index;\n }\n\n /** Deduces number of instances. Intention is to support:\n - Explicit setting of numInstances\n - Auto-deduction for ES6 containers that define a size member\n - Auto-deduction for Classic Arrays via the built-in length attribute\n - Auto-deduction via arrays */\n getNumInstances(): number {\n // First Check if app has provided an explicit value\n if (Number.isFinite(this.props.numInstances)) {\n return this.props.numInstances as number;\n }\n\n // Second check if the layer has set its own value\n if (this.state && this.state.numInstances !== undefined) {\n return this.state.numInstances as number;\n }\n\n // Use container library to get a count for any ES6 container or object\n return count(this.props.data);\n }\n\n /** Buffer layout describes how many attribute values are packed for each data object\n The default (null) is one value each object.\n Some data formats (e.g. paths, polygons) have various length. Their buffer layout\n is in the form of [L0, L1, L2, ...] */\n getStartIndices(): NumericArray | null {\n // First Check if startIndices is provided as an explicit value\n if (this.props.startIndices) {\n return this.props.startIndices;\n }\n\n // Second check if the layer has set its own value\n if (this.state && this.state.startIndices) {\n return this.state.startIndices as NumericArray;\n }\n\n return null;\n }\n\n // Default implementation\n getBounds(): [number[], number[]] | null {\n return this.getAttributeManager()?.getBounds(['positions', 'instancePositions']);\n }\n\n // / LIFECYCLE METHODS - overridden by the layer subclasses\n\n /** Called once to set up the initial state. Layers can create WebGL resources here. */\n abstract initializeState(context: LayerContext): void;\n\n getShaders(shaders: any): any {\n shaders = mergeShaders(shaders, {\n disableWarnings: true,\n modules: this.context.defaultShaderModules\n });\n for (const extension of this.props.extensions) {\n shaders = mergeShaders(shaders, extension.getShaders.call(this, extension));\n }\n return shaders;\n }\n\n /** Controls if updateState should be called. By default returns true if any prop has changed */\n shouldUpdateState(params: UpdateParameters>): boolean {\n return params.changeFlags.propsOrDataChanged;\n }\n\n /** Default implementation, all attributes will be invalidated and updated when data changes */\n // eslint-disable-next-line complexity\n updateState(params: UpdateParameters>): void {\n const attributeManager = this.getAttributeManager();\n const {dataChanged} = params.changeFlags;\n if (dataChanged && attributeManager) {\n if (Array.isArray(dataChanged)) {\n // is partial update\n for (const dataRange of dataChanged) {\n attributeManager.invalidateAll(dataRange);\n }\n } else {\n attributeManager.invalidateAll();\n }\n }\n\n // Enable/disable picking buffer\n if (attributeManager) {\n const {props} = params;\n const hasPickingBuffer = this.internalState!.hasPickingBuffer;\n const needsPickingBuffer =\n Number.isInteger(props.highlightedObjectIndex) ||\n Boolean(props.pickable) ||\n props.extensions.some(extension => extension.getNeedsPickingBuffer.call(this, extension));\n\n // Only generate picking buffer if needed\n if (hasPickingBuffer !== needsPickingBuffer) {\n this.internalState!.hasPickingBuffer = needsPickingBuffer;\n const {pickingColors, instancePickingColors} = attributeManager.attributes;\n const pickingColorsAttribute = pickingColors || instancePickingColors;\n if (pickingColorsAttribute) {\n if (needsPickingBuffer && pickingColorsAttribute.constant) {\n pickingColorsAttribute.constant = false;\n attributeManager.invalidate(pickingColorsAttribute.id);\n }\n if (!pickingColorsAttribute.value && !needsPickingBuffer) {\n pickingColorsAttribute.constant = true;\n pickingColorsAttribute.value = [0, 0, 0];\n }\n }\n }\n }\n }\n\n /** Called once when layer is no longer matched and state will be discarded. Layers can destroy WebGL resources here. */\n finalizeState(context: LayerContext): void {\n for (const model of this.getModels()) {\n model.destroy();\n }\n const attributeManager = this.getAttributeManager();\n if (attributeManager) {\n attributeManager.finalize();\n }\n if (this.context) {\n this.context.resourceManager.unsubscribe({consumerId: this.id});\n }\n if (this.internalState) {\n this.internalState.uniformTransitions.clear();\n this.internalState.finalize();\n }\n }\n\n // If state has a model, draw it with supplied uniforms\n draw(opts: DrawOptions) {\n for (const model of this.getModels()) {\n model.draw(opts.renderPass);\n }\n }\n\n // called to populate the info object that is passed to the event handler\n // @return null to cancel event\n getPickingInfo({info, mode, sourceLayer}: GetPickingInfoParams) {\n const {index} = info;\n\n if (index >= 0) {\n // If props.data is an indexable array, get the object\n if (Array.isArray(this.props.data)) {\n info.object = this.props.data[index];\n }\n }\n\n return info;\n }\n\n // END LIFECYCLE METHODS\n\n // / INTERNAL METHODS - called by LayerManager, DeckRenderer and DeckPicker\n\n /** (Internal) Propagate an error event through the system */\n raiseError(error: Error, message: string): void {\n if (message) {\n // Duplicating error message for backward compatibility, see #7986\n // TODO - revisit in v9\n error = new Error(`${message}: ${error.message}`, {cause: error});\n }\n if (!this.props.onError?.(error)) {\n this.context?.onError?.(error, this);\n }\n }\n\n /** (Internal) Checks if this layer needs redraw */\n getNeedsRedraw(\n opts: {\n /** Reset redraw flags to false after the check */\n clearRedrawFlags: boolean;\n } = {clearRedrawFlags: false}\n ): string | false {\n return this._getNeedsRedraw(opts);\n }\n\n /** (Internal) Checks if this layer needs a deep update */\n needsUpdate(): boolean {\n if (!this.internalState) {\n return false;\n }\n\n // Call subclass lifecycle method\n return (\n this.internalState.needsUpdate ||\n this.hasUniformTransition() ||\n this.shouldUpdateState(this._getUpdateParams())\n );\n // End lifecycle method\n }\n\n /** Checks if this layer has ongoing uniform transition */\n hasUniformTransition(): boolean {\n return this.internalState?.uniformTransitions.active || false;\n }\n\n /** Called when this layer is rendered into the given viewport */\n activateViewport(viewport: Viewport): void {\n if (!this.internalState) {\n return;\n }\n\n const oldViewport = this.internalState.viewport;\n this.internalState.viewport = viewport;\n\n if (!oldViewport || !areViewportsEqual({oldViewport, viewport})) {\n this.setChangeFlags({viewportChanged: true});\n\n if (this.isComposite) {\n if (this.needsUpdate()) {\n // Composite layers may add/remove sublayers on viewport change\n // Because we cannot change the layers list during a draw cycle, we don't want to update sublayers right away\n // This will not call update immediately, but mark the layerManager as needs update on the next frame\n this.setNeedsUpdate();\n }\n } else {\n this._update();\n }\n }\n }\n\n /** Default implementation of attribute invalidation, can be redefined */\n protected invalidateAttribute(name = 'all'): void {\n const attributeManager = this.getAttributeManager();\n if (!attributeManager) {\n return;\n }\n\n if (name === 'all') {\n attributeManager.invalidateAll();\n } else {\n attributeManager.invalidate(name);\n }\n }\n\n /** Send updated attributes to the WebGL model */\n protected updateAttributes(changedAttributes: {[id: string]: Attribute}) {\n // If some buffer layout changed\n let bufferLayoutChanged = false;\n for (const id in changedAttributes) {\n if (changedAttributes[id].layoutChanged()) {\n bufferLayoutChanged = true;\n }\n }\n\n for (const model of this.getModels()) {\n this._setModelAttributes(model, changedAttributes, bufferLayoutChanged);\n }\n }\n\n /** Recalculate any attributes if needed */\n protected _updateAttributes(): void {\n const attributeManager = this.getAttributeManager();\n if (!attributeManager) {\n return;\n }\n const props = this.props;\n\n // Figure out data length\n const numInstances = this.getNumInstances();\n const startIndices = this.getStartIndices();\n\n attributeManager.update({\n data: props.data,\n numInstances,\n startIndices,\n props,\n transitions: props.transitions,\n // @ts-ignore (TS2339) property attribute is not present on some acceptable data types\n buffers: props.data.attributes,\n context: this\n });\n\n const changedAttributes = attributeManager.getChangedAttributes({clearChangedFlags: true});\n this.updateAttributes(changedAttributes);\n }\n\n /** Update attribute transitions. This is called in drawLayer, no model updates required. */\n private _updateAttributeTransition() {\n const attributeManager = this.getAttributeManager();\n if (attributeManager) {\n attributeManager.updateTransition();\n }\n }\n\n /** Update uniform (prop) transitions. This is called in updateState, may result in model updates. */\n private _updateUniformTransition(): Layer['props'] {\n // @ts-ignore (TS2339) internalState is alwasy defined when this method is called\n const {uniformTransitions} = this.internalState;\n if (uniformTransitions.active) {\n // clone props\n const propsInTransition = uniformTransitions.update();\n const props = Object.create(this.props);\n for (const key in propsInTransition) {\n Object.defineProperty(props, key, {value: propsInTransition[key]});\n }\n return props;\n }\n return this.props;\n }\n\n /** Updater for the automatically populated instancePickingColors attribute */\n protected calculateInstancePickingColors(\n attribute: Attribute,\n {numInstances}: {numInstances: number}\n ) {\n if (attribute.constant) {\n return;\n }\n\n // calculateInstancePickingColors always generates the same sequence.\n // pickingColorCache saves the largest generated sequence for reuse\n const cacheSize = Math.floor(pickingColorCache.length / 4);\n\n // Record when using the picking buffer cache, so that layers can always point at the most recently allocated cache\n // @ts-ignore (TS2531) internalState is always defined when this method is called\n this.internalState.usesPickingColorCache = true;\n\n if (cacheSize < numInstances) {\n if (numInstances > MAX_PICKING_COLOR_CACHE_SIZE) {\n log.warn(\n 'Layer has too many data objects. Picking might not be able to distinguish all objects.'\n )();\n }\n\n pickingColorCache = typedArrayManager.allocate(pickingColorCache, numInstances, {\n size: 4,\n copy: true,\n maxCount: Math.max(numInstances, MAX_PICKING_COLOR_CACHE_SIZE)\n });\n\n // If the attribute is larger than the cache, resize the cache and populate the missing chunk\n const newCacheSize = Math.floor(pickingColorCache.length / 4);\n const pickingColor: [number, number, number] = [0, 0, 0];\n for (let i = cacheSize; i < newCacheSize; i++) {\n this.encodePickingColor(i, pickingColor);\n pickingColorCache[i * 4 + 0] = pickingColor[0];\n pickingColorCache[i * 4 + 1] = pickingColor[1];\n pickingColorCache[i * 4 + 2] = pickingColor[2];\n pickingColorCache[i * 4 + 3] = 0;\n }\n }\n\n attribute.value = pickingColorCache.subarray(0, numInstances * 4);\n }\n\n /** Apply changed attributes to model */\n protected _setModelAttributes(\n model: Model,\n changedAttributes: {\n [id: string]: Attribute;\n },\n bufferLayoutChanged = false\n ) {\n if (!Object.keys(changedAttributes).length) {\n return;\n }\n\n if (bufferLayoutChanged) {\n // AttributeManager is always defined when this method is called\n const attributeManager = this.getAttributeManager()!;\n model.setBufferLayout(attributeManager.getBufferLayouts(model));\n // All attributes must be reset after buffer layout change\n changedAttributes = attributeManager.getAttributes();\n }\n\n // @ts-ignore luma.gl type issue\n const excludeAttributes = model.userData?.excludeAttributes || {};\n const attributeBuffers: Record = {};\n const constantAttributes: Record = {};\n\n for (const name in changedAttributes) {\n if (excludeAttributes[name]) {\n continue;\n }\n const values = changedAttributes[name].getValue();\n for (const attributeName in values) {\n const value = values[attributeName];\n if (value instanceof Buffer) {\n if (changedAttributes[name].settings.isIndexed) {\n model.setIndexBuffer(value);\n } else {\n attributeBuffers[attributeName] = value;\n }\n } else if (value) {\n constantAttributes[attributeName] = value;\n }\n }\n }\n // TODO - update buffer map?\n model.setAttributes(attributeBuffers);\n model.setConstantAttributes(constantAttributes);\n }\n\n /** (Internal) Sets the picking color at the specified index to null picking color. Used for multi-depth picking.\n This method may be overriden by layer implementations */\n disablePickingIndex(objectIndex: number) {\n const data = this.props.data as LayerData;\n if (!('attributes' in data)) {\n this._disablePickingIndex(objectIndex);\n return;\n }\n\n // @ts-ignore (TS2531) this method is only called internally with attributeManager defined\n const {pickingColors, instancePickingColors} = this.getAttributeManager().attributes;\n const colors = pickingColors || instancePickingColors;\n const externalColorAttribute =\n colors && data.attributes && (data.attributes[colors.id] as BinaryAttribute);\n if (externalColorAttribute && externalColorAttribute.value) {\n const values = externalColorAttribute.value;\n const objectColor = this.encodePickingColor(objectIndex);\n for (let index = 0; index < data.length; index++) {\n const i = colors.getVertexOffset(index);\n if (\n values[i] === objectColor[0] &&\n values[i + 1] === objectColor[1] &&\n values[i + 2] === objectColor[2]\n ) {\n this._disablePickingIndex(index);\n }\n }\n } else {\n this._disablePickingIndex(objectIndex);\n }\n }\n\n // TODO - simplify subclassing interface\n protected _disablePickingIndex(objectIndex: number): void {\n // @ts-ignore (TS2531) this method is only called internally with attributeManager defined\n const {pickingColors, instancePickingColors} = this.getAttributeManager().attributes;\n const colors = pickingColors || instancePickingColors;\n if (!colors) {\n return;\n }\n\n const start = colors.getVertexOffset(objectIndex);\n const end = colors.getVertexOffset(objectIndex + 1);\n\n // Fill the sub buffer with 0s, 1 byte per element\n colors.buffer.write(new Uint8Array(end - start), start);\n }\n\n /** (Internal) Re-enable all picking indices after multi-depth picking */\n restorePickingColors(): void {\n // @ts-ignore (TS2531) this method is only called internally with attributeManager defined\n const {pickingColors, instancePickingColors} = this.getAttributeManager().attributes;\n const colors = pickingColors || instancePickingColors;\n if (!colors) {\n return;\n }\n // The picking color cache may have been freed and then reallocated. This ensures we read from the currently allocated cache.\n if (\n // @ts-ignore (TS2531) this method is only called internally with internalState defined\n this.internalState.usesPickingColorCache &&\n (colors.value as Uint8ClampedArray).buffer !== pickingColorCache.buffer\n ) {\n colors.value = pickingColorCache.subarray(0, (colors.value as Uint8ClampedArray).length);\n }\n colors.updateSubBuffer({startOffset: 0});\n }\n\n /* eslint-disable max-statements */\n /* (Internal) Called by layer manager when a new layer is found */\n _initialize() {\n assert(!this.internalState); // finalized layer cannot be reused\n\n debug(TRACE_INITIALIZE, this);\n\n const attributeManager = this._getAttributeManager();\n\n if (attributeManager) {\n // All instanced layers get instancePickingColors attribute by default\n // Their shaders can use it to render a picking scene\n // TODO - this slightly slows down non instanced layers\n attributeManager.addInstanced({\n instancePickingColors: {\n type: 'uint8',\n size: 4,\n noAlloc: true,\n // Updaters are always called with `this` pointing to the layer\n // eslint-disable-next-line @typescript-eslint/unbound-method\n update: this.calculateInstancePickingColors\n }\n });\n }\n\n this.internalState = new LayerState({\n attributeManager,\n layer: this\n });\n this._clearChangeFlags(); // populate this.internalState.changeFlags\n\n this.state = {};\n // for backwards compatibility with older layers\n // TODO - remove in next release\n /* eslint-disable accessor-pairs */\n Object.defineProperty(this.state, 'attributeManager', {\n get: () => {\n log.deprecated('layer.state.attributeManager', 'layer.getAttributeManager()')();\n return attributeManager;\n }\n });\n /* eslint-enable accessor-pairs */\n\n this.internalState.uniformTransitions = new UniformTransitionManager(this.context.timeline);\n this.internalState.onAsyncPropUpdated = this._onAsyncPropUpdated.bind(this);\n\n // Ensure any async props are updated\n this.internalState.setAsyncProps(this.props);\n\n // Call subclass lifecycle methods\n this.initializeState(this.context);\n\n // Initialize extensions\n for (const extension of this.props.extensions) {\n extension.initializeState.call(this, this.context, extension);\n }\n // End subclass lifecycle methods\n\n // initializeState callback tends to clear state\n this.setChangeFlags({\n dataChanged: 'init',\n propsChanged: 'init',\n viewportChanged: true,\n extensionsChanged: true\n });\n\n this._update();\n }\n\n /** (Internal) Called by layer manager to transfer state from an old layer */\n _transferState(oldLayer: Layer): void {\n debug(TRACE_MATCHED, this, this === oldLayer);\n\n const {state, internalState} = oldLayer;\n\n if (this === oldLayer) {\n return;\n }\n\n // Move internalState\n this.internalState = internalState as LayerState;\n\n // Move state\n this.state = state;\n // We keep the state ref on old layers to support async actions\n // oldLayer.state = null;\n\n // Ensure any async props are updated\n this.internalState.setAsyncProps(this.props);\n\n this._diffProps(this.props, this.internalState.getOldProps() as Layer['props']);\n }\n\n /** (Internal) Called by layer manager when a new layer is added or an existing layer is matched with a new instance */\n _update(): void {\n // Call subclass lifecycle method\n const stateNeedsUpdate = this.needsUpdate();\n // End lifecycle method\n debug(TRACE_UPDATE, this, stateNeedsUpdate);\n\n if (!stateNeedsUpdate) {\n return;\n }\n this.context.stats.get('Layer updates').incrementCount();\n\n const currentProps = this.props;\n const context = this.context;\n const internalState = this.internalState as LayerState;\n\n const currentViewport = context.viewport;\n const propsInTransition = this._updateUniformTransition();\n internalState.propsInTransition = propsInTransition;\n // Overwrite this.context.viewport during update to use the last activated viewport on this layer\n // In multi-view applications, a layer may only be drawn in one of the views\n // Which would make the \"active\" viewport different from the shared context\n context.viewport = internalState.viewport || currentViewport;\n // Overwrite this.props during update to use in-transition prop values\n this.props = propsInTransition;\n\n try {\n const updateParams = this._getUpdateParams();\n const oldModels = this.getModels();\n\n // Safely call subclass lifecycle methods\n if (context.device) {\n this.updateState(updateParams);\n } else {\n try {\n this.updateState(updateParams);\n } catch (error) {\n // ignore error if gl context is missing\n }\n }\n // Execute extension updates\n for (const extension of this.props.extensions) {\n extension.updateState.call(this, updateParams, extension);\n }\n\n this.setNeedsRedraw();\n // Check if attributes need recalculation\n this._updateAttributes();\n\n const modelChanged = this.getModels()[0] !== oldModels[0];\n this._postUpdate(updateParams, modelChanged);\n // End subclass lifecycle methods\n } finally {\n // Restore shared context\n context.viewport = currentViewport;\n this.props = currentProps;\n this._clearChangeFlags();\n internalState.needsUpdate = false;\n internalState.resetOldProps();\n }\n }\n /* eslint-enable max-statements */\n\n /** (Internal) Called by manager when layer is about to be disposed \n Note: not guaranteed to be called on application shutdown */\n _finalize(): void {\n debug(TRACE_FINALIZE, this);\n\n // Call subclass lifecycle method\n this.finalizeState(this.context);\n // Finalize extensions\n for (const extension of this.props.extensions) {\n extension.finalizeState.call(this, this.context, extension);\n }\n }\n\n // Calculates uniforms\n _drawLayer({\n renderPass,\n shaderModuleProps = null,\n uniforms = {},\n parameters = {}\n }: {\n renderPass: RenderPass;\n shaderModuleProps: any;\n uniforms: any;\n parameters: LumaParameters;\n }): void {\n this._updateAttributeTransition();\n\n const currentProps = this.props;\n const context = this.context;\n // Overwrite this.props during redraw to use in-transition prop values\n // `internalState.propsInTransition` could be missing if `updateState` failed\n // @ts-ignore (TS2339) internalState is alwasy defined when this method is called\n this.props = this.internalState.propsInTransition || currentProps;\n\n try {\n // TODO/ib - hack move to luma Model.draw\n if (shaderModuleProps) {\n this.setShaderModuleProps(shaderModuleProps);\n }\n\n // Apply polygon offset to avoid z-fighting\n // TODO - move to draw-layers\n const {getPolygonOffset} = this.props;\n const offsets = (getPolygonOffset && getPolygonOffset(uniforms)) || [0, 0];\n\n if (context.device instanceof WebGLDevice) {\n context.device.setParametersWebGL({polygonOffset: offsets});\n }\n\n const webGPUDrawParameters =\n context.device instanceof WebGLDevice ? null : splitWebGPUDrawParameters(parameters);\n\n applyModelParameters(this.getModels(), renderPass, parameters, webGPUDrawParameters);\n\n // Call subclass lifecycle method\n if (context.device instanceof WebGLDevice) {\n context.device.withParametersWebGL(parameters, () => {\n const opts: DrawOptions = {renderPass, shaderModuleProps, uniforms, parameters, context};\n\n // extensions\n for (const extension of this.props.extensions) {\n extension.draw.call(this, opts, extension);\n }\n\n this.draw(opts);\n });\n } else {\n if (webGPUDrawParameters?.renderPassParameters) {\n renderPass.setParameters(webGPUDrawParameters.renderPassParameters);\n }\n const opts: DrawOptions = {renderPass, shaderModuleProps, uniforms, parameters, context};\n\n // extensions\n for (const extension of this.props.extensions) {\n extension.draw.call(this, opts, extension);\n }\n\n this.draw(opts);\n }\n } finally {\n this.props = currentProps;\n }\n\n // End lifecycle method\n }\n\n // Helper methods\n /** Returns the current change flags */\n getChangeFlags(): ChangeFlags | undefined {\n return this.internalState?.changeFlags;\n }\n\n /* eslint-disable complexity */\n /** Dirty some change flags, will be handled by updateLayer */\n setChangeFlags(flags: Partial): void {\n if (!this.internalState) {\n return;\n }\n const {changeFlags} = this.internalState;\n\n /* eslint-disable no-fallthrough, max-depth */\n for (const key in flags) {\n if (flags[key]) {\n let flagChanged = false;\n switch (key) {\n case 'dataChanged':\n // changeFlags.dataChanged may be `false`, a string (reason) or an array of ranges\n const dataChangedReason = flags[key];\n const prevDataChangedReason = changeFlags[key];\n if (dataChangedReason && Array.isArray(prevDataChangedReason)) {\n // Merge partial updates\n changeFlags.dataChanged = Array.isArray(dataChangedReason)\n ? prevDataChangedReason.concat(dataChangedReason)\n : dataChangedReason;\n flagChanged = true;\n }\n\n default:\n if (!changeFlags[key]) {\n changeFlags[key] = flags[key];\n flagChanged = true;\n }\n }\n if (flagChanged) {\n debug(TRACE_CHANGE_FLAG, this, key, flags);\n }\n }\n }\n /* eslint-enable no-fallthrough, max-depth */\n\n // Update composite flags\n const propsOrDataChanged = Boolean(\n changeFlags.dataChanged ||\n changeFlags.updateTriggersChanged ||\n changeFlags.propsChanged ||\n changeFlags.extensionsChanged\n );\n changeFlags.propsOrDataChanged = propsOrDataChanged;\n changeFlags.somethingChanged =\n propsOrDataChanged || changeFlags.viewportChanged || changeFlags.stateChanged;\n }\n /* eslint-enable complexity */\n\n /** Clear all changeFlags, typically after an update */\n private _clearChangeFlags(): void {\n // @ts-ignore TS2531 this method can only be called internally with internalState assigned\n this.internalState.changeFlags = {\n dataChanged: false,\n propsChanged: false,\n updateTriggersChanged: false,\n viewportChanged: false,\n stateChanged: false,\n extensionsChanged: false,\n propsOrDataChanged: false,\n somethingChanged: false\n };\n }\n\n /** Compares the layers props with old props from a matched older layer\n and extracts change flags that describe what has change so that state\n can be update correctly with minimal effort */\n private _diffProps(newProps: Layer['props'], oldProps: Layer['props']) {\n const changeFlags = diffProps(newProps, oldProps);\n\n // iterate over changedTriggers\n if (changeFlags.updateTriggersChanged) {\n for (const key in changeFlags.updateTriggersChanged) {\n if (changeFlags.updateTriggersChanged[key]) {\n this.invalidateAttribute(key);\n }\n }\n }\n\n // trigger uniform transitions\n if (changeFlags.transitionsChanged) {\n for (const key in changeFlags.transitionsChanged) {\n // prop changed and transition is enabled\n // @ts-ignore (TS2531) internalState is always defined when this method is called\n this.internalState.uniformTransitions.add(\n key,\n oldProps[key],\n newProps[key],\n newProps.transitions?.[key]\n );\n }\n }\n\n return this.setChangeFlags(changeFlags);\n }\n\n /** (Internal) called by layer manager to perform extra props validation (in development only) */\n validateProps(): void {\n validateProps(this.props);\n }\n\n /** (Internal) Called by deck picker when the hovered object changes to update the auto highlight */\n updateAutoHighlight(info: PickingInfo): void {\n if (this.props.autoHighlight && !Number.isInteger(this.props.highlightedObjectIndex)) {\n this._updateAutoHighlight(info);\n }\n }\n\n // May be overriden by subclasses\n\n // TODO - simplify subclassing interface\n /** Update picking module parameters to highlight the hovered object */\n protected _updateAutoHighlight(info: PickingInfo): void {\n const picking: PickingProps = {\n // @ts-ignore\n highlightedObjectColor: info.picked ? info.color : null\n };\n const {highlightColor} = this.props;\n if (info.picked && typeof highlightColor === 'function') {\n // @ts-ignore\n picking.highlightColor = highlightColor(info);\n }\n this.setShaderModuleProps({picking});\n // setShaderModuleProps does not trigger redraw\n this.setNeedsRedraw();\n }\n\n /** Create new attribute manager */\n protected _getAttributeManager(): AttributeManager | null {\n const context = this.context;\n return new AttributeManager(context.device, {\n id: this.props.id,\n stats: context.stats,\n timeline: context.timeline\n });\n }\n\n // Private methods\n\n /** Called after updateState to perform common tasks */\n // eslint-disable-next-line complexity\n protected _postUpdate(updateParams: UpdateParameters>, forceUpdate: boolean) {\n const {props, oldProps} = updateParams;\n\n // Note: Automatic instance count update only works for single layers\n const model = this.state.model as Model | undefined;\n if (model?.isInstanced) {\n model.setInstanceCount(this.getNumInstances());\n }\n\n // Set picking module parameters to match props\n const {autoHighlight, highlightedObjectIndex, highlightColor} = props;\n if (\n forceUpdate ||\n oldProps.autoHighlight !== autoHighlight ||\n oldProps.highlightedObjectIndex !== highlightedObjectIndex ||\n oldProps.highlightColor !== highlightColor\n ) {\n const picking: PickingProps = {};\n\n if (Array.isArray(highlightColor)) {\n picking.highlightColor = highlightColor as [number, number, number];\n }\n\n // highlightedObjectIndex will overwrite any settings from auto highlighting.\n // Do not reset unless the value has changed.\n if (\n forceUpdate ||\n oldProps.autoHighlight !== autoHighlight ||\n highlightedObjectIndex !== oldProps.highlightedObjectIndex\n ) {\n picking.highlightedObjectColor =\n Number.isFinite(highlightedObjectIndex) && (highlightedObjectIndex as number) >= 0\n ? this.encodePickingColor(highlightedObjectIndex)\n : null;\n }\n\n this.setShaderModuleProps({picking});\n }\n }\n\n private _getUpdateParams(): UpdateParameters> {\n return {\n props: this.props,\n // @ts-ignore TS2531 this method can only be called internally with internalState assigned\n oldProps: this.internalState.getOldProps() as PropsT,\n context: this.context,\n // @ts-ignore TS2531 this method can only be called internally with internalState assigned\n changeFlags: this.internalState.changeFlags\n };\n }\n\n /** Checks state of attributes and model */\n private _getNeedsRedraw(opts: {clearRedrawFlags: boolean}): string | false {\n // this method may be called by the render loop as soon a the layer\n // has been created, so guard against uninitialized state\n if (!this.internalState) {\n return false;\n }\n\n let redraw: string | false = false;\n redraw = redraw || (this.internalState.needsRedraw && this.id);\n\n // TODO - is attribute manager needed? - Model should be enough.\n const attributeManager = this.getAttributeManager();\n const attributeManagerNeedsRedraw = attributeManager\n ? attributeManager.getNeedsRedraw(opts)\n : false;\n redraw = redraw || attributeManagerNeedsRedraw;\n\n if (redraw) {\n for (const extension of this.props.extensions) {\n extension.onNeedsRedraw.call(this, extension);\n }\n }\n\n this.internalState.needsRedraw = this.internalState.needsRedraw && !opts.clearRedrawFlags;\n return redraw;\n }\n\n /** Callback when asyn prop is loaded */\n private _onAsyncPropUpdated(): void {\n // @ts-ignore TS2531 this method can only be called internally with internalState assigned\n this._diffProps(this.props, this.internalState.getOldProps());\n this.setNeedsUpdate();\n }\n}\n\nfunction splitWebGPUDrawParameters(parameters: LumaParameters): {\n pipelineParameters: LumaParameters;\n renderPassParameters?: {blendConstant: [number, number, number, number]};\n} {\n const {blendConstant, ...pipelineParameters} = parameters as LumaParameters & {\n blendConstant?: [number, number, number, number];\n };\n\n return blendConstant\n ? {\n pipelineParameters,\n renderPassParameters: {blendConstant}\n }\n : {pipelineParameters};\n}\n\nfunction applyModelParameters(\n models: Model[],\n renderPass: RenderPass,\n parameters: LumaParameters,\n webGPUDrawParameters: ReturnType | null\n): void {\n for (const model of models) {\n if (model.device.type === 'webgpu') {\n syncModelAttachmentFormats(model, renderPass);\n // TODO(ibgreen): model.setParameters currently wipes parameters. Semantics TBD.\n model.setParameters({\n ...model.parameters,\n ...webGPUDrawParameters?.pipelineParameters\n });\n } else {\n model.setParameters(parameters);\n }\n }\n}\n\nfunction syncModelAttachmentFormats(model: Model, renderPass: RenderPass): void {\n const framebuffer =\n renderPass.props.framebuffer ||\n ((\n renderPass as RenderPass & {\n framebuffer?: {\n colorAttachments: Array<{texture: {format: string}}>;\n depthStencilAttachment: {texture: {format: string}} | null;\n };\n }\n ).framebuffer ??\n null);\n\n if (!framebuffer) {\n return;\n }\n\n const colorAttachmentFormats = framebuffer.colorAttachments.map(\n attachment => attachment?.texture?.format ?? null\n );\n const depthStencilAttachmentFormat = framebuffer.depthStencilAttachment?.texture?.format;\n\n const modelWithProps = model as unknown as {\n props: {\n colorAttachmentFormats?: (string | null)[];\n depthStencilAttachmentFormat?: string;\n };\n _setPipelineNeedsUpdate(reason: string): void;\n };\n\n if (\n !equalAttachmentFormats(modelWithProps.props.colorAttachmentFormats, colorAttachmentFormats) ||\n modelWithProps.props.depthStencilAttachmentFormat !== depthStencilAttachmentFormat\n ) {\n modelWithProps.props.colorAttachmentFormats = colorAttachmentFormats;\n modelWithProps.props.depthStencilAttachmentFormat = depthStencilAttachmentFormat;\n modelWithProps._setPipelineNeedsUpdate('attachment formats');\n }\n}\n\nfunction equalAttachmentFormats(left?: (string | null)[], right?: (string | null)[]): boolean {\n if (left === right) {\n return true;\n }\n if (!left || !right || left.length !== right.length) {\n return false;\n }\n for (let i = 0; i < left.length; i++) {\n if (left[i] !== right[i]) {\n return false;\n }\n }\n return true;\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {lerp} from '@math.gl/core';\nimport Transition from './transition';\n\nexport default class CPUInterpolationTransition extends Transition {\n _value;\n\n get value() {\n return this._value;\n }\n\n _onUpdate() {\n const {\n time,\n settings: {fromValue, toValue, duration, easing}\n } = this;\n const t = easing(time / duration);\n this._value = lerp(fromValue, toValue, t);\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport Transition from './transition';\n\nconst EPSILON = 1e-5;\n\n/*\n * Calculate the next value in the spring transition\n * @param prev {Number} - previous value\n * @param cur {Number} - current value\n * @param dest {Number} - destination value\n * @param damping {Number}\n * @param stiffness {Number}\n */\nfunction updateSpringElement(\n prev: number,\n cur: number,\n dest: number,\n damping: number,\n stiffness: number\n): number {\n const velocity = cur - prev;\n const delta = dest - cur;\n const spring = delta * stiffness;\n const damper = -velocity * damping;\n return spring + damper + velocity + cur;\n}\n\n/*\n * Calculate the next value in the spring transition\n * @param prev {Number|Array} - previous value\n * @param cur {Number|Array} - current value\n * @param dest {Number|Array} - destination value\n * @param damping {Number}\n * @param stiffness {Number}\n */\nfunction updateSpring(prev: number, cur: number, dest: number, damping: number, stiffness: number);\nfunction updateSpring(\n prev: number[],\n cur: number[],\n dest: number[],\n damping: number,\n stiffness: number\n): number[];\n\nfunction updateSpring(\n prev: number | number[],\n cur: number | number[],\n dest: number | number[],\n damping: number,\n stiffness: number\n): number | number[] {\n if (Array.isArray(dest)) {\n const next: number[] = [];\n for (let i = 0; i < dest.length; i++) {\n next[i] = updateSpringElement(prev[i], cur[i], dest[i], damping, stiffness);\n }\n return next;\n }\n return updateSpringElement(prev as number, cur as number, dest, damping, stiffness);\n}\n\n/*\n * Calculate the distance between two numbers or two vectors\n */\nfunction distance(value1, value2) {\n if (Array.isArray(value1)) {\n let distanceSquare = 0;\n for (let i = 0; i < value1.length; i++) {\n const d = value1[i] - value2[i];\n distanceSquare += d * d;\n }\n return Math.sqrt(distanceSquare);\n }\n return Math.abs(value1 - value2);\n}\n\nexport default class CPUSpringTransition extends Transition {\n _prevValue;\n _currValue;\n\n get value() {\n return this._currValue;\n }\n\n _onUpdate() {\n // TODO - use timeline\n // const {time} = this;\n\n const {fromValue, toValue, damping, stiffness} = this.settings;\n const {_prevValue = fromValue, _currValue = fromValue} = this;\n let nextValue = updateSpring(_prevValue, _currValue, toValue, damping, stiffness);\n const delta = distance(nextValue, toValue);\n const velocity = distance(nextValue, _currValue);\n\n if (delta < EPSILON && velocity < EPSILON) {\n nextValue = toValue;\n this.end();\n }\n\n this._prevValue = _currValue;\n this._currValue = nextValue;\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {normalizeTransitionSettings} from './attribute/transition-settings';\nimport CPUInterpolationTransition from '../transitions/cpu-interpolation-transition';\nimport CPUSpringTransition from '../transitions/cpu-spring-transition';\nimport log from '../utils/log';\n\nconst TRANSITION_TYPES = {\n interpolation: CPUInterpolationTransition,\n spring: CPUSpringTransition\n};\n\nexport default class UniformTransitionManager {\n transitions = new Map();\n timeline;\n\n constructor(timeline) {\n this.timeline = timeline;\n }\n\n get active() {\n return this.transitions.size > 0;\n }\n\n add(key, fromValue, toValue, settings) {\n const {transitions} = this;\n if (transitions.has(key)) {\n const transition = transitions.get(key);\n // value may not be available if `update()` has not been called. Fallback to `fromValue`\n const {value = transition.settings.fromValue} = transition;\n // start from interrupted position\n fromValue = value;\n this.remove(key);\n }\n\n settings = normalizeTransitionSettings(settings);\n if (!settings) {\n return;\n }\n\n const TransitionType = TRANSITION_TYPES[settings.type];\n if (!TransitionType) {\n log.error(`unsupported transition type '${settings.type}'`)();\n return;\n }\n const transition = new TransitionType(this.timeline);\n transition.start({\n ...settings,\n fromValue,\n toValue\n });\n transitions.set(key, transition);\n }\n\n remove(key) {\n const {transitions} = this;\n if (transitions.has(key)) {\n transitions.get(key).cancel();\n transitions.delete(key);\n }\n }\n\n update() {\n const propsInTransition = {};\n\n for (const [key, transition] of this.transitions) {\n transition.update();\n propsInTransition[key] = transition.value;\n if (!transition.inProgress) {\n // transition ended\n this.remove(key);\n }\n }\n\n return propsInTransition;\n }\n\n clear() {\n for (const key of this.transitions.keys()) {\n this.remove(key);\n }\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {PROP_TYPES_SYMBOL} from './constants';\n\nexport function validateProps(props) {\n const propTypes = props[PROP_TYPES_SYMBOL];\n\n for (const propName in propTypes) {\n const propType = propTypes[propName];\n const {validate} = propType;\n if (validate && !validate(props[propName], propType)) {\n throw new Error(`Invalid prop ${propName}: ${props[propName]}`);\n }\n }\n}\n\n// Returns an object with \"change flags\", either false or strings indicating reason for change\nexport function diffProps(\n props,\n oldProps\n): {\n dataChanged: string | false | {startRow: number; endRow?: number}[];\n propsChanged: string | false;\n updateTriggersChanged: Record | false;\n extensionsChanged: boolean;\n transitionsChanged: Record | false;\n} {\n // First check if any props have changed (ignore props that will be examined separately)\n const propsChangedReason = compareProps({\n newProps: props,\n oldProps,\n propTypes: props[PROP_TYPES_SYMBOL],\n ignoreProps: {data: null, updateTriggers: null, extensions: null, transitions: null}\n });\n\n // Now check if any data related props have changed\n const dataChangedReason = diffDataProps(props, oldProps);\n\n // Check update triggers to determine if any attributes need regeneration\n // Note - if data has changed, all attributes will need regeneration, so skip this step\n let updateTriggersChangedReason: false | string | Record = false;\n if (!dataChangedReason) {\n updateTriggersChangedReason = diffUpdateTriggers(props, oldProps);\n }\n\n return {\n dataChanged: dataChangedReason,\n propsChanged: propsChangedReason,\n updateTriggersChanged: updateTriggersChangedReason,\n extensionsChanged: diffExtensions(props, oldProps),\n transitionsChanged: diffTransitions(props, oldProps)\n };\n}\n\nfunction diffTransitions(props, oldProps): false | Record {\n if (!props.transitions) {\n return false;\n }\n const result: Record = {};\n const propTypes = props[PROP_TYPES_SYMBOL];\n let changed = false;\n\n for (const key in props.transitions) {\n const propType = propTypes[key];\n const type = propType && propType.type;\n const isTransitionable = type === 'number' || type === 'color' || type === 'array';\n if (isTransitionable && comparePropValues(props[key], oldProps[key], propType)) {\n result[key] = true;\n changed = true;\n }\n }\n return changed ? result : false;\n}\n\n/**\n * Performs equality by iterating through keys on an object and returning false\n * when any key has values which are not strictly equal between the arguments.\n * @param {Object} opt.oldProps - object with old key/value pairs\n * @param {Object} opt.newProps - object with new key/value pairs\n * @param {Object} opt.ignoreProps={} - object, keys that should not be compared\n * @returns {null|String} - null when values of all keys are strictly equal.\n * if unequal, returns a string explaining what changed.\n */\n/* eslint-disable max-statements, max-depth, complexity */\n/*\n * Note: for better performance, this function assumes that both oldProps and newProps\n inherit the same prototype (defaultProps). That is, if neither object contains own\n property , assume `oldProps.` and `newProps.` are equal.\n */\nexport function compareProps({\n newProps,\n oldProps,\n ignoreProps = {},\n propTypes = {},\n triggerName = 'props'\n}): string | false {\n // shallow equality => deep equality\n if (oldProps === newProps) {\n return false;\n }\n\n // TODO - do we need these checks? Should never happen...\n if (typeof newProps !== 'object' || newProps === null) {\n return `${triggerName} changed shallowly`;\n }\n\n if (typeof oldProps !== 'object' || oldProps === null) {\n return `${triggerName} changed shallowly`;\n }\n\n // Compare explicitly defined new props against old/default values\n for (const key of Object.keys(newProps)) {\n if (!(key in ignoreProps)) {\n if (!(key in oldProps)) {\n return `${triggerName}.${key} added`;\n }\n const changed = comparePropValues(newProps[key], oldProps[key], propTypes[key]);\n if (changed) {\n return `${triggerName}.${key} ${changed}`;\n }\n }\n }\n\n // Test if any old props have been dropped\n for (const key of Object.keys(oldProps)) {\n if (!(key in ignoreProps)) {\n if (!(key in newProps)) {\n return `${triggerName}.${key} dropped`;\n }\n if (!Object.hasOwnProperty.call(newProps, key)) {\n // Compare dropped old prop against default value\n const changed = comparePropValues(newProps[key], oldProps[key], propTypes[key]);\n if (changed) {\n return `${triggerName}.${key} ${changed}`;\n }\n }\n }\n }\n\n return false;\n}\n/* eslint-enable max-statements, max-depth, complexity */\n\n// HELPERS\nfunction comparePropValues(newProp, oldProp, propType) {\n // If prop type has an equal function, invoke it\n let equal = propType && propType.equal;\n if (equal && !equal(newProp, oldProp, propType)) {\n return 'changed deeply';\n }\n\n if (!equal) {\n // If object has an equals function, invoke it\n equal = newProp && oldProp && newProp.equals;\n if (equal && !equal.call(newProp, oldProp)) {\n return 'changed deeply';\n }\n }\n\n if (!equal && oldProp !== newProp) {\n return 'changed shallowly';\n }\n\n return null;\n}\n\n// The comparison of the data prop requires special handling\n// the dataComparator should be used if supplied\nfunction diffDataProps(props, oldProps): string | false | {startRow: number; endRow?: number}[] {\n if (oldProps === null) {\n return 'oldProps is null, initial diff';\n }\n\n let dataChanged: string | false | {startRow: number; endRow?: number}[] = false;\n // Support optional app defined comparison of data\n const {dataComparator, _dataDiff} = props;\n if (dataComparator) {\n if (!dataComparator(props.data, oldProps.data)) {\n dataChanged = 'Data comparator detected a change';\n }\n // Otherwise, do a shallow equal on props\n } else if (props.data !== oldProps.data) {\n dataChanged = 'A new data container was supplied';\n }\n if (dataChanged && _dataDiff) {\n dataChanged = _dataDiff(props.data, oldProps.data) || dataChanged;\n }\n\n return dataChanged;\n}\n\n// Checks if any update triggers have changed\n// also calls callback to invalidate attributes accordingly.\nfunction diffUpdateTriggers(props, oldProps): Record | false {\n if (oldProps === null) {\n return {all: true};\n }\n\n // If the 'all' updateTrigger fires, ignore testing others\n if ('all' in props.updateTriggers) {\n const diffReason = diffUpdateTrigger(props, oldProps, 'all');\n if (diffReason) {\n return {all: true};\n }\n }\n\n const reason: Record = {};\n let changed = false;\n // If the 'all' updateTrigger didn't fire, need to check all others\n for (const triggerName in props.updateTriggers) {\n if (triggerName !== 'all') {\n const diffReason = diffUpdateTrigger(props, oldProps, triggerName);\n if (diffReason) {\n reason[triggerName] = true;\n changed = true;\n }\n }\n }\n\n return changed ? reason : false;\n}\n\n// Returns true if any extensions have changed\nfunction diffExtensions(props, oldProps): boolean {\n if (oldProps === null) {\n return true;\n }\n\n const oldExtensions = oldProps.extensions;\n const {extensions} = props;\n\n if (extensions === oldExtensions) {\n return false;\n }\n if (!oldExtensions || !extensions) {\n return true;\n }\n if (extensions.length !== oldExtensions.length) {\n return true;\n }\n for (let i = 0; i < extensions.length; i++) {\n if (!extensions[i].equals(oldExtensions[i])) {\n return true;\n }\n }\n return false;\n}\n\nfunction diffUpdateTrigger(props, oldProps, triggerName) {\n let newTriggers = props.updateTriggers[triggerName];\n newTriggers = newTriggers === undefined || newTriggers === null ? {} : newTriggers;\n let oldTriggers = oldProps.updateTriggers[triggerName];\n oldTriggers = oldTriggers === undefined || oldTriggers === null ? {} : oldTriggers;\n const diffReason = compareProps({\n oldProps: oldTriggers,\n newProps: newTriggers,\n triggerName\n });\n return diffReason;\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nconst ERR_NOT_OBJECT = 'count(): argument not an object';\nconst ERR_NOT_CONTAINER = 'count(): argument not a container';\n\n/**\n * Deduces numer of elements in a JavaScript container.\n * - Auto-deduction for ES6 containers that define a count() method\n * - Auto-deduction for ES6 containers that define a size member\n * - Auto-deduction for Classic Arrays via the built-in length attribute\n * - Also handles objects, although note that this an O(N) operation\n */\nexport function count(container: any): number {\n if (!isObject(container)) {\n throw new Error(ERR_NOT_OBJECT);\n }\n\n // Check if ES6 collection \"count\" function is available\n if (typeof container.count === 'function') {\n return container.count();\n }\n\n // Check if ES6 collection \"size\" attribute is set\n if (Number.isFinite(container.size)) {\n return container.size;\n }\n\n // Check if array length attribute is set\n // Note: checking this last since some ES6 collections (Immutable.js)\n // emit profuse warnings when trying to access `length` attribute\n if (Number.isFinite(container.length)) {\n return container.length;\n }\n\n // Note that getting the count of an object is O(N)\n if (isPlainObject(container)) {\n return Object.keys(container).length;\n }\n\n throw new Error(ERR_NOT_CONTAINER);\n}\n\n/**\n * Checks if argument is a plain object (not a class or array etc)\n * @param {*} value - JavaScript value to be tested\n * @return {Boolean} - true if argument is a plain JavaScript object\n */\nfunction isPlainObject(value) {\n return value !== null && typeof value === 'object' && value.constructor === Object;\n}\n\n/**\n * Checks if argument is an indexable object (not a primitive value, nor null)\n * @param {*} value - JavaScript value to be tested\n * @return {Boolean} - true if argument is a JavaScript object\n */\nfunction isObject(value) {\n return value !== null && typeof value === 'object';\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// Merge two luma.gl shader descriptors\nexport function mergeShaders(target, source) {\n if (!source) {\n return target;\n }\n const result = {...target, ...source};\n\n if ('defines' in source) {\n result.defines = {...target.defines, ...source.defines};\n }\n if ('modules' in source) {\n result.modules = (target.modules || []).concat(source.modules);\n\n // Hack: prject32 and project64 cannot co-exist\n if (source.modules.some(module => module.name === 'project64')) {\n const index = result.modules.findIndex(module => module.name === 'project32');\n if (index >= 0) {\n result.modules.splice(index, 1);\n }\n }\n }\n if ('inject' in source) {\n if (!target.inject) {\n result.inject = source.inject;\n } else {\n const mergedInjection = {...target.inject};\n for (const key in source.inject) {\n mergedInjection[key] = (mergedInjection[key] || '') + source.inject[key];\n }\n result.inject = mergedInjection;\n }\n }\n return result;\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Device, Texture, SamplerProps} from '@luma.gl/core';\n\nconst DEFAULT_TEXTURE_PARAMETERS: SamplerProps = {\n minFilter: 'linear',\n mipmapFilter: 'linear',\n magFilter: 'linear',\n addressModeU: 'clamp-to-edge',\n addressModeV: 'clamp-to-edge'\n};\n\n// Track the textures that are created by us. They need to be released when they are no longer used.\nconst internalTextures: Record = {};\n\n/**\n *\n * @param owner\n * @param device\n * @param image could be one of:\n * - Texture\n * - Browser object: Image, ImageData, ImageData, HTMLCanvasElement, HTMLVideoElement, ImageBitmap\n * - Plain object: {width: , height: , data: }\n * @param parameters\n * @returns\n */\nexport function createTexture(\n owner: string,\n device: Device,\n image: any,\n sampler: SamplerProps\n): Texture | null {\n if (image instanceof Texture) {\n return image;\n } else if (image.constructor && image.constructor.name !== 'Object') {\n // Browser object\n image = {data: image};\n }\n\n let samplerParameters: SamplerProps | null = null;\n if (image.compressed) {\n samplerParameters = {\n minFilter: 'linear',\n mipmapFilter: image.data.length > 1 ? 'nearest' : 'linear'\n };\n }\n\n const {width, height} = image.data;\n const texture = device.createTexture({\n ...image,\n sampler: {\n ...DEFAULT_TEXTURE_PARAMETERS,\n ...samplerParameters,\n ...sampler\n },\n mipLevels: device.getMipLevelCount(width, height)\n });\n if (device.type === 'webgl') {\n texture.generateMipmapsWebGL();\n } else if (device.type === 'webgpu') {\n device.generateMipmapsWebGPU(texture);\n }\n\n // Track this texture\n internalTextures[texture.id] = owner;\n return texture;\n}\n\nexport function destroyTexture(owner: string, texture: Texture) {\n if (!texture || !(texture instanceof Texture)) {\n return;\n }\n // Only delete the texture if requested by the same layer that created it\n if (internalTextures[texture.id] === owner) {\n texture.delete();\n delete internalTextures[texture.id];\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {createTexture, destroyTexture} from '../utils/texture';\nimport {deepEqual} from '../utils/deep-equal';\n\nimport type Component from './component';\nimport type {Color, TextureSource} from '../types/layer-props';\nimport type Layer from '../lib/layer';\nimport type {SamplerProps} from '@luma.gl/core';\n\ntype BasePropType = {\n value: ValueT;\n async?: boolean;\n validate?: (value: any, propType: PropType) => boolean;\n equal?: (value1: ValueT, value2: ValueT, propType: PropType) => boolean;\n};\n\n/**\n * Normalized prop type definition\n */\nexport type PropType = BasePropType & {\n type: string;\n name: string;\n transform?: (value: any, propType: PropType, component: Component) => any;\n release?: (value: any, propType: PropType, component: Component) => void;\n};\n\ntype DefaultProp =\n | T\n | DeprecatedProp\n | BooleanPropType\n | NumberPropType\n | ColorPropType\n | ImagePropType\n | DataPropType\n | ArrayPropType\n | ObjectPropType\n | AccessorPropType\n | FunctionPropType;\n\nexport type DefaultProps = {\n [propName in keyof PropsT]?: DefaultProp[propName]>;\n};\n\ntype BooleanPropType = BasePropType & {\n type: 'boolean';\n};\ntype NumberPropType = BasePropType & {\n type: 'number';\n min?: number;\n max?: number;\n};\ntype ColorPropType = BasePropType & {\n type: 'color';\n optional?: boolean;\n};\ntype ArrayPropType = BasePropType & {\n type: 'array';\n optional?: boolean;\n /** Ignore change in the prop value.\n * @default false\n */\n ignore?: boolean;\n /** Deep-compare two prop values. Only used if `ignore: false`.\n * When a number is supplied, used as the depth of deep-comparison. 0 is equivalent to shallow comparison, -1 is infinite depth\n * When a boolean is supplied, `true` is equivalent to `1` (shallow compare all child fields)\n * @default false\n */\n compare?: boolean | number;\n};\ntype AccessorPropType = BasePropType & {\n type: 'accessor';\n};\ntype FunctionPropType = BasePropType & {\n type: 'function';\n optional?: boolean;\n /** @deprecated use `ignore` instead */\n compare?: boolean;\n /** Ignore change in the prop value.\n * @default true\n */\n ignore?: boolean;\n};\ntype DataPropType = BasePropType & {\n type: 'data';\n};\ntype ImagePropType = BasePropType & {\n type: 'image';\n parameters?: SamplerProps;\n};\ntype ObjectPropType = BasePropType & {\n type: 'object';\n optional?: boolean;\n /** Ignore change in the prop value.\n * @default false\n */\n ignore?: boolean;\n /** Deep-compare two prop values. Only used if `ignore: false`.\n * When a number is supplied, used as the depth of deep-comparison. 0 is equivalent to shallow comparison, -1 is infinite depth\n * When a boolean is supplied, `true` is equivalent to `1` (shallow compare all child fields)\n * @default false\n */\n compare?: boolean | number;\n};\ntype DeprecatedProp = {\n deprecatedFor?: string | string[];\n};\ntype PropTypeDef =\n | DeprecatedProp\n | boolean\n | BooleanPropType\n | number\n | NumberPropType\n | string\n | DataPropType\n | number[]\n | ColorPropType\n | ArrayPropType\n | AccessorPropType\n | FunctionPropType\n | ImagePropType\n | ObjectPropType\n | null;\n\nconst TYPE_DEFINITIONS = {\n boolean: {\n validate(value, propType: BooleanPropType) {\n return true;\n },\n equal(value1, value2, propType: BooleanPropType) {\n return Boolean(value1) === Boolean(value2);\n }\n },\n number: {\n validate(value, propType: NumberPropType) {\n return (\n Number.isFinite(value) &&\n (!('max' in propType) || value <= propType.max!) &&\n (!('min' in propType) || value >= propType.min!)\n );\n }\n },\n color: {\n validate(value, propType: ColorPropType) {\n return (\n (propType.optional && !value) ||\n (isArray(value) && (value.length === 3 || value.length === 4))\n );\n },\n equal(value1, value2, propType: ColorPropType) {\n return deepEqual(value1, value2, 1);\n }\n },\n accessor: {\n validate(value, propType: AccessorPropType) {\n const valueType = getTypeOf(value);\n return valueType === 'function' || valueType === getTypeOf(propType.value);\n },\n equal(value1, value2, propType: AccessorPropType) {\n if (typeof value2 === 'function') {\n return true;\n }\n return deepEqual(value1, value2, 1);\n }\n },\n array: {\n validate(value, propType: ArrayPropType) {\n return (propType.optional && !value) || isArray(value);\n },\n equal(value1, value2, propType: ArrayPropType) {\n const {compare} = propType;\n const depth = Number.isInteger(compare as unknown) ? (compare as number) : compare ? 1 : 0;\n return compare ? deepEqual(value1, value2, depth) : value1 === value2;\n }\n },\n object: {\n equal(value1, value2, propType: ObjectPropType) {\n if (propType.ignore) {\n return true;\n }\n const {compare} = propType;\n const depth = Number.isInteger(compare as unknown) ? (compare as number) : compare ? 1 : 0;\n return compare ? deepEqual(value1, value2, depth) : value1 === value2;\n }\n },\n function: {\n validate(value, propType: FunctionPropType) {\n return (propType.optional && !value) || typeof value === 'function';\n },\n equal(value1, value2, propType: FunctionPropType) {\n // Backward compatibility - {compare: true} and {ignore: false} are equivalent\n const shouldIgnore = !propType.compare && propType.ignore !== false;\n return shouldIgnore || value1 === value2;\n }\n },\n data: {\n transform: (value, propType: DataPropType, component) => {\n if (!value) {\n return value;\n }\n const {dataTransform} = component.props;\n if (dataTransform) {\n return dataTransform(value);\n }\n // Detect loaders.gl v4 table format\n if (\n typeof value.shape === 'string' &&\n value.shape.endsWith('-table') &&\n Array.isArray(value.data)\n ) {\n return value.data;\n }\n return value;\n }\n },\n image: {\n transform: (value, propType: ImagePropType, component) => {\n const context = (component as Layer).context;\n if (!context || !context.device) {\n return null;\n }\n return createTexture(component.id, context.device, value, {\n ...propType.parameters,\n ...component.props.textureParameters\n });\n },\n release: (value, propType: ImagePropType, component) => {\n destroyTexture(component.id, value);\n }\n }\n} as const;\n\nexport function parsePropTypes(propDefs: Record): {\n propTypes: Record;\n defaultProps: Record;\n deprecatedProps: Record;\n} {\n const propTypes = {};\n const defaultProps = {};\n const deprecatedProps = {};\n\n for (const [propName, propDef] of Object.entries(propDefs)) {\n const deprecated = (propDef as DeprecatedProp)?.deprecatedFor;\n if (deprecated) {\n deprecatedProps[propName] = Array.isArray(deprecated) ? deprecated : [deprecated];\n } else {\n const propType = parsePropType(propName, propDef);\n propTypes[propName] = propType;\n defaultProps[propName] = propType.value;\n }\n }\n return {propTypes, defaultProps, deprecatedProps};\n}\n\n// Parses one property definition entry. Either contains:\n// * a valid prop type object ({type, ...})\n// * or just a default value, in which case type and name inference is used\nfunction parsePropType(name: string, propDef: PropTypeDef): PropType {\n switch (getTypeOf(propDef)) {\n case 'object':\n return normalizePropDefinition(name, propDef);\n\n case 'array':\n return normalizePropDefinition(name, {type: 'array', value: propDef, compare: false});\n\n case 'boolean':\n return normalizePropDefinition(name, {type: 'boolean', value: propDef});\n\n case 'number':\n return normalizePropDefinition(name, {type: 'number', value: propDef});\n\n case 'function':\n // return guessFunctionType(name, propDef);\n return normalizePropDefinition(name, {type: 'function', value: propDef, compare: true});\n\n default:\n return {name, type: 'unknown', value: propDef};\n }\n}\n\nfunction normalizePropDefinition(name, propDef): PropType {\n if (!('type' in propDef)) {\n if (!('value' in propDef)) {\n // If no type and value this object is likely the value\n return {name, type: 'object', value: propDef};\n }\n return {name, type: getTypeOf(propDef.value), ...propDef};\n }\n return {name, ...TYPE_DEFINITIONS[propDef.type], ...propDef};\n}\n\nfunction isArray(value: any): boolean {\n return Array.isArray(value) || ArrayBuffer.isView(value);\n}\n\n// improved version of javascript typeof that can distinguish arrays and null values\nfunction getTypeOf(value: any): string {\n if (isArray(value)) {\n return 'array';\n }\n if (value === null) {\n return 'null';\n }\n return typeof value;\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport log from '../utils/log';\nimport {isAsyncIterable} from '../utils/iterable-utils';\nimport {parsePropTypes} from './prop-types';\nimport {\n COMPONENT_SYMBOL,\n PROP_TYPES_SYMBOL,\n DEPRECATED_PROPS_SYMBOL,\n ASYNC_ORIGINAL_SYMBOL,\n ASYNC_RESOLVED_SYMBOL,\n ASYNC_DEFAULTS_SYMBOL\n} from './constants';\nimport {StatefulComponentProps} from './component';\nimport Component from './component';\n\n// Create a property object\nexport function createProps(\n component: Component,\n propObjects: Partial[]\n): StatefulComponentProps {\n // Resolve extension value\n let extensions: any[] | undefined;\n for (let i = propObjects.length - 1; i >= 0; i--) {\n const props = propObjects[i];\n if ('extensions' in props) {\n // @ts-expect-error TS(2339) extensions not defined\n extensions = props.extensions;\n }\n }\n\n // Create a new prop object with empty default props object\n const propsPrototype = getPropsPrototype(component.constructor, extensions);\n // The true default props object will be found later\n const propsInstance = Object.create(propsPrototype);\n\n // Props need a back pointer to the owning component\n propsInstance[COMPONENT_SYMBOL] = component;\n // The supplied (original) values for those async props that are set to url strings or Promises.\n // In this case, the actual (i.e. resolved) values are looked up from component.internalState\n propsInstance[ASYNC_ORIGINAL_SYMBOL] = {};\n // Note: the actual (resolved) values for props that are NOT set to urls or Promises.\n // in this case the values are served directly from this map\n propsInstance[ASYNC_RESOLVED_SYMBOL] = {};\n\n // \"Copy\" all sync props\n for (let i = 0; i < propObjects.length; ++i) {\n const props = propObjects[i];\n // Do not use Object.assign here to avoid Symbols in props overwriting our private fields\n // This might happen if one of the arguments is another props instance\n for (const key in props) {\n propsInstance[key] = props[key];\n }\n }\n\n // Props must be immutable\n Object.freeze(propsInstance);\n\n return propsInstance;\n}\n\nconst MergedDefaultPropsCacheKey = '_mergedDefaultProps';\n\n// Return precalculated defaultProps and propType objects if available\n// build them if needed\nfunction getPropsPrototype(componentClass, extensions?: any[]) {\n // Bail out if we're not looking at a component - for two reasons:\n // 1. There's no reason for an ancestor of component to have props\n // 2. If we don't bail out, we'll follow the prototype chain all the way back to the global\n // function prototype and add _mergedDefaultProps to it, which may break other frameworks\n // (e.g. the react-three-fiber reconciler)\n if (!(componentClass instanceof Component.constructor)) return {};\n\n // A string that uniquely identifies the extensions involved\n let cacheKey = MergedDefaultPropsCacheKey;\n if (extensions) {\n for (const extension of extensions) {\n const ExtensionClass = extension.constructor;\n if (ExtensionClass) {\n cacheKey += `:${ExtensionClass.extensionName || ExtensionClass.name}`;\n }\n }\n }\n\n const defaultProps = getOwnProperty(componentClass, cacheKey);\n if (!defaultProps) {\n return (componentClass[cacheKey] = createPropsPrototypeAndTypes(\n componentClass,\n extensions || []\n ));\n }\n return defaultProps;\n}\n\n// Build defaultProps and propType objects by walking component prototype chain\nfunction createPropsPrototypeAndTypes(\n componentClass,\n extensions: any[]\n): Record | null {\n const parent = componentClass.prototype;\n if (!parent) {\n return null;\n }\n\n const parentClass = Object.getPrototypeOf(componentClass);\n const parentDefaultProps = getPropsPrototype(parentClass);\n\n // Parse propTypes from Component.defaultProps\n const componentDefaultProps = getOwnProperty(componentClass, 'defaultProps') || {};\n const componentPropDefs = parsePropTypes(componentDefaultProps);\n\n // Merged default props object. Order: parent, self, extensions\n const defaultProps: any = Object.assign(\n Object.create(null),\n parentDefaultProps,\n componentPropDefs.defaultProps\n );\n // Merged prop type definitions. Order: parent, self, extensions\n const propTypes = Object.assign(\n Object.create(null),\n parentDefaultProps?.[PROP_TYPES_SYMBOL],\n componentPropDefs.propTypes\n );\n // Merged deprecation list. Order: parent, self, extensions\n const deprecatedProps = Object.assign(\n Object.create(null),\n parentDefaultProps?.[DEPRECATED_PROPS_SYMBOL],\n componentPropDefs.deprecatedProps\n );\n\n for (const extension of extensions) {\n const extensionDefaultProps = getPropsPrototype(extension.constructor);\n if (extensionDefaultProps) {\n Object.assign(defaultProps, extensionDefaultProps);\n Object.assign(propTypes, extensionDefaultProps[PROP_TYPES_SYMBOL]);\n Object.assign(deprecatedProps, extensionDefaultProps[DEPRECATED_PROPS_SYMBOL]);\n }\n }\n\n // Create any necessary property descriptors and create the default prop object\n // Assign merged default props\n createPropsPrototype(defaultProps, componentClass);\n\n // Add getters/setters for async props\n addAsyncPropsToPropPrototype(defaultProps, propTypes);\n\n // Add setters for deprecated props\n addDeprecatedPropsToPropPrototype(defaultProps, deprecatedProps);\n\n // Store the precalculated props\n defaultProps[PROP_TYPES_SYMBOL] = propTypes;\n defaultProps[DEPRECATED_PROPS_SYMBOL] = deprecatedProps;\n\n // Backwards compatibility\n // TODO: remove access of hidden property from the rest of the code base\n if (extensions.length === 0 && !hasOwnProperty(componentClass, '_propTypes')) {\n componentClass._propTypes = propTypes;\n }\n return defaultProps;\n}\n\n// Builds a pre-merged default props object that component props can inherit from\nfunction createPropsPrototype(defaultProps, componentClass) {\n // Avoid freezing `id` prop\n const id = getComponentName(componentClass);\n\n Object.defineProperties(defaultProps, {\n // `id` is treated specially because layer might need to override it\n id: {\n writable: true,\n value: id\n }\n });\n}\n\nfunction addDeprecatedPropsToPropPrototype(defaultProps, deprecatedProps) {\n for (const propName in deprecatedProps) {\n /* eslint-disable accessor-pairs */\n Object.defineProperty(defaultProps, propName, {\n enumerable: false,\n set(newValue) {\n const nameStr = `${this.id}: ${propName}`;\n\n for (const newPropName of deprecatedProps[propName]) {\n if (!hasOwnProperty(this, newPropName)) {\n this[newPropName] = newValue;\n }\n }\n\n log.deprecated(nameStr, deprecatedProps[propName].join('/'))();\n }\n });\n /* eslint-enable accessor-pairs */\n }\n}\n\n// Create descriptors for overridable props\nfunction addAsyncPropsToPropPrototype(defaultProps, propTypes) {\n const defaultValues = {};\n\n const descriptors = {};\n\n // Move async props into shadow values\n for (const propName in propTypes) {\n const propType = propTypes[propName];\n const {name, value} = propType;\n\n // Note: async is ES7 keyword, can't destructure\n if (propType.async) {\n defaultValues[name] = value;\n descriptors[name] = getDescriptorForAsyncProp(name);\n }\n }\n\n // Default \"resolved\" values for async props, returned if value not yet resolved/set.\n defaultProps[ASYNC_DEFAULTS_SYMBOL] = defaultValues;\n // Shadowed object, just to make sure \"early indexing\" into the instance does not fail\n defaultProps[ASYNC_ORIGINAL_SYMBOL] = {};\n\n Object.defineProperties(defaultProps, descriptors);\n}\n\n// Helper: Configures getter and setter for one async prop\nfunction getDescriptorForAsyncProp(name) {\n return {\n enumerable: true,\n // Save the provided value for async props in a special map\n set(newValue) {\n if (\n typeof newValue === 'string' ||\n newValue instanceof Promise ||\n isAsyncIterable(newValue)\n ) {\n this[ASYNC_ORIGINAL_SYMBOL][name] = newValue;\n } else {\n this[ASYNC_RESOLVED_SYMBOL][name] = newValue;\n }\n },\n // Only the component's state knows the true value of async prop\n get() {\n if (this[ASYNC_RESOLVED_SYMBOL]) {\n // Prop value isn't async, so just return it\n if (name in this[ASYNC_RESOLVED_SYMBOL]) {\n const value = this[ASYNC_RESOLVED_SYMBOL][name];\n\n return value || this[ASYNC_DEFAULTS_SYMBOL][name];\n }\n\n if (name in this[ASYNC_ORIGINAL_SYMBOL]) {\n // It's an async prop value: look into component state\n const state = this[COMPONENT_SYMBOL] && this[COMPONENT_SYMBOL].internalState;\n if (state && state.hasAsyncProp(name)) {\n return state.getAsyncProp(name) || this[ASYNC_DEFAULTS_SYMBOL][name];\n }\n }\n }\n\n // the prop is not supplied, or\n // component not yet initialized/matched, return the component's default value for the prop\n return this[ASYNC_DEFAULTS_SYMBOL][name];\n }\n };\n}\n\n// HELPER METHODS\n\nfunction hasOwnProperty(object, prop) {\n return Object.prototype.hasOwnProperty.call(object, prop);\n}\n\n// Constructors have their super class constructors as prototypes\nfunction getOwnProperty(object, prop) {\n return hasOwnProperty(object, prop) && object[prop];\n}\n\nfunction getComponentName(componentClass) {\n const componentName = componentClass.componentName;\n if (!componentName) {\n log.warn(`${componentClass.name}.componentName not specified`)();\n }\n return componentName || componentClass.name;\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {\n COMPONENT_SYMBOL,\n PROP_TYPES_SYMBOL,\n ASYNC_ORIGINAL_SYMBOL,\n ASYNC_RESOLVED_SYMBOL,\n ASYNC_DEFAULTS_SYMBOL\n} from './constants';\nimport {PropType} from './prop-types';\nimport {createProps} from './create-props';\n\nlet counter = 0;\n\nexport type StatefulComponentProps = PropsT & {\n id: string;\n [COMPONENT_SYMBOL]: Component;\n [PROP_TYPES_SYMBOL]: Record;\n [ASYNC_DEFAULTS_SYMBOL]: Partial;\n [ASYNC_ORIGINAL_SYMBOL]: Partial;\n [ASYNC_RESOLVED_SYMBOL]: Partial;\n};\n\nexport default class Component {\n static componentName: string = 'Component';\n static defaultProps: Readonly<{}> = {};\n\n id: string;\n props: StatefulComponentProps;\n count: number;\n\n constructor(...propObjects: Partial[]) {\n // Merge supplied props with default props and freeze them.\n /* eslint-disable prefer-spread */\n this.props = createProps(this, propObjects);\n /* eslint-enable prefer-spread */\n\n this.id = this.props.id; // The layer's id, used for matching with layers from last render cycle\n this.count = counter++; // Keep track of how many layer instances you are generating\n }\n\n // clone this layer with modified props\n clone(newProps: Partial) {\n const {props} = this;\n\n // Async props cannot be copied with Object.assign, copy them separately\n const asyncProps: Partial = {};\n\n // See async props definition in create-props.js\n for (const key in props[ASYNC_DEFAULTS_SYMBOL]) {\n if (key in props[ASYNC_RESOLVED_SYMBOL]) {\n asyncProps[key] = props[ASYNC_RESOLVED_SYMBOL][key];\n } else if (key in props[ASYNC_ORIGINAL_SYMBOL]) {\n asyncProps[key] = props[ASYNC_ORIGINAL_SYMBOL][key];\n }\n }\n\n // Some custom layer implementation may not support multiple arguments in the constructor\n // @ts-ignore\n return new this.constructor({...props, ...asyncProps, ...newProps});\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {isAsyncIterable} from '../utils/iterable-utils';\nimport {\n COMPONENT_SYMBOL,\n PROP_TYPES_SYMBOL,\n ASYNC_ORIGINAL_SYMBOL,\n ASYNC_RESOLVED_SYMBOL,\n ASYNC_DEFAULTS_SYMBOL\n} from './constants';\nimport type Component from './component';\nimport {PropType} from './prop-types';\n\nconst EMPTY_PROPS = Object.freeze({});\n\n/** Internal state of an async prop */\ntype AsyncPropState = {\n /** The prop type definition from component.defaultProps, if exists */\n type: PropType | null;\n /** Supplied prop value (can be url/promise, not visible to the component) */\n lastValue: any;\n /** Resolved prop value (valid data, can be \"shown\" to the component) */\n resolvedValue: any;\n /** How many loads have been issued */\n pendingLoadCount: number;\n /** Latest resolved load, (earlier loads will be ignored) */\n resolvedLoadCount: number;\n};\n\nexport default class ComponentState {\n /** The component that this state instance belongs to. `null` if this state has been finalized. */\n component: ComponentT | null;\n onAsyncPropUpdated: (propName: string, value: any) => void;\n\n private asyncProps: Partial>;\n private oldProps: ComponentT['props'] | null;\n private oldAsyncProps: ComponentT['props'] | null;\n\n constructor(component: ComponentT) {\n this.component = component;\n this.asyncProps = {}; // Prop values that the layer sees\n this.onAsyncPropUpdated = () => {};\n this.oldProps = null; // Last props before update\n this.oldAsyncProps = null; // Last props before update, with async values copied.\n }\n\n finalize() {\n for (const propName in this.asyncProps) {\n const asyncProp = this.asyncProps[propName];\n if (asyncProp && asyncProp.type && asyncProp.type.release) {\n // Release any resources created by transforms\n asyncProp.type.release(\n asyncProp.resolvedValue,\n asyncProp.type,\n this.component as Component\n );\n }\n }\n this.asyncProps = {};\n this.component = null;\n this.resetOldProps();\n }\n\n /* Layer-facing props API */\n\n getOldProps(): ComponentT['props'] | typeof EMPTY_PROPS {\n return this.oldAsyncProps || this.oldProps || EMPTY_PROPS;\n }\n\n resetOldProps() {\n this.oldAsyncProps = null;\n this.oldProps = this.component ? this.component.props : null;\n }\n\n // Checks if a prop is overridden\n hasAsyncProp(propName: string): boolean {\n return propName in this.asyncProps;\n }\n\n // Returns value of an overriden prop\n getAsyncProp(propName: string): any {\n const asyncProp = this.asyncProps[propName];\n return asyncProp && asyncProp.resolvedValue;\n }\n\n isAsyncPropLoading(propName?: string): boolean {\n if (propName) {\n const asyncProp = this.asyncProps[propName];\n return Boolean(\n asyncProp &&\n asyncProp.pendingLoadCount > 0 &&\n asyncProp.pendingLoadCount !== asyncProp.resolvedLoadCount\n );\n }\n for (const key in this.asyncProps) {\n if (this.isAsyncPropLoading(key)) {\n return true;\n }\n }\n return false;\n }\n\n // Without changing the original prop value, swap out the data resolution under the hood\n reloadAsyncProp(propName: string, value: any) {\n this._watchPromise(propName, Promise.resolve(value));\n }\n\n // Updates all async/overridden props (when new props come in)\n // Checks if urls have changed, starts loading, or removes override\n setAsyncProps(props: ComponentT['props']) {\n this.component = (props[COMPONENT_SYMBOL] as ComponentT) || this.component;\n\n // NOTE: prop param and default values are only support for testing\n const resolvedValues = props[ASYNC_RESOLVED_SYMBOL] || {};\n const originalValues = props[ASYNC_ORIGINAL_SYMBOL] || props;\n const defaultValues = props[ASYNC_DEFAULTS_SYMBOL] || {};\n\n // TODO - use async props from the layer's prop types\n for (const propName in resolvedValues) {\n const value = resolvedValues[propName];\n this._createAsyncPropData(propName, defaultValues[propName]);\n this._updateAsyncProp(propName, value);\n // Use transformed value\n resolvedValues[propName] = this.getAsyncProp(propName);\n }\n\n for (const propName in originalValues) {\n const value = originalValues[propName];\n // Makes sure a record exists for this prop\n this._createAsyncPropData(propName, defaultValues[propName]);\n this._updateAsyncProp(propName, value);\n }\n }\n\n /* Placeholder methods for subclassing */\n\n protected _fetch(propName: string, url: string): any {\n return null;\n }\n\n protected _onResolve(propName: string, value: any) {} // eslint-disable-line @typescript-eslint/no-empty-function\n\n protected _onError(propName: string, error: Error) {} // eslint-disable-line @typescript-eslint/no-empty-function\n\n // Intercept strings (URLs) and Promises and activates loading and prop rewriting\n private _updateAsyncProp(propName: string, value: any) {\n if (!this._didAsyncInputValueChange(propName, value)) {\n return;\n }\n\n // interpret value string as url and start a new load tracked by a promise\n if (typeof value === 'string') {\n value = this._fetch(propName, value);\n }\n\n // interprets promise and track the \"loading\"\n if (value instanceof Promise) {\n this._watchPromise(propName, value);\n return;\n }\n\n if (isAsyncIterable(value)) {\n this._resolveAsyncIterable(propName, value); // eslint-disable-line @typescript-eslint/no-floating-promises\n return;\n }\n\n // else, normal, non-async value. Just store value for now\n this._setPropValue(propName, value);\n }\n\n // Whenever async props are changing, we need to make a copy of oldProps\n // otherwise the prop rewriting will affect the value both in props and oldProps.\n // While the copy is relatively expensive, this only happens on load completion.\n private _freezeAsyncOldProps() {\n if (!this.oldAsyncProps && this.oldProps) {\n // 1. inherit all synchronous props from oldProps\n // 2. reconfigure the async prop descriptors to fixed values\n this.oldAsyncProps = Object.create(this.oldProps);\n for (const propName in this.asyncProps) {\n Object.defineProperty(this.oldAsyncProps, propName, {\n enumerable: true,\n value: this.oldProps[propName]\n });\n }\n }\n }\n\n // Checks if an input value actually changed (to avoid reloading/rewatching promises/urls)\n private _didAsyncInputValueChange(propName: string, value: any): boolean {\n // @ts-ignore\n const asyncProp: AsyncPropState = this.asyncProps[propName];\n if (value === asyncProp.resolvedValue || value === asyncProp.lastValue) {\n return false;\n }\n asyncProp.lastValue = value;\n return true;\n }\n\n // Set normal, non-async value\n private _setPropValue(propName: string, value: any) {\n // Save the current value before overwriting so that diffProps can access both\n this._freezeAsyncOldProps();\n\n const asyncProp = this.asyncProps[propName];\n if (asyncProp) {\n value = this._postProcessValue(asyncProp, value);\n asyncProp.resolvedValue = value;\n asyncProp.pendingLoadCount++;\n asyncProp.resolvedLoadCount = asyncProp.pendingLoadCount;\n }\n }\n\n // Set a just resolved async value, calling onAsyncPropUpdates if value changes asynchronously\n private _setAsyncPropValue(propName: string, value: any, loadCount: number) {\n // Only update if loadCount is larger or equal to resolvedLoadCount\n // otherwise a more recent load has already completed\n const asyncProp = this.asyncProps[propName];\n if (asyncProp && loadCount >= asyncProp.resolvedLoadCount && value !== undefined) {\n // Save the current value before overwriting so that diffProps can access both\n this._freezeAsyncOldProps();\n\n asyncProp.resolvedValue = value;\n asyncProp.resolvedLoadCount = loadCount;\n\n // Call callback to inform listener\n this.onAsyncPropUpdated(propName, value);\n }\n }\n\n // Tracks a promise, sets the prop when loaded, handles load count\n private _watchPromise(propName: string, promise: Promise) {\n const asyncProp = this.asyncProps[propName];\n if (asyncProp) {\n asyncProp.pendingLoadCount++;\n const loadCount = asyncProp.pendingLoadCount;\n promise\n .then(data => {\n if (!this.component) {\n // This component state has been finalized\n return;\n }\n data = this._postProcessValue(asyncProp, data);\n this._setAsyncPropValue(propName, data, loadCount);\n this._onResolve(propName, data);\n })\n .catch(error => {\n this._onError(propName, error);\n });\n }\n }\n\n private async _resolveAsyncIterable(\n propName: string,\n iterable: AsyncIterable\n ): Promise {\n if (propName !== 'data') {\n // we only support data as async iterable\n this._setPropValue(propName, iterable);\n return;\n }\n\n const asyncProp = this.asyncProps[propName];\n if (!asyncProp) {\n return;\n }\n\n asyncProp.pendingLoadCount++;\n const loadCount = asyncProp.pendingLoadCount;\n let data: any[] = [];\n let count = 0;\n\n for await (const chunk of iterable) {\n if (!this.component) {\n // This component state has been finalized\n return;\n }\n\n // @ts-expect-error (2339) dataTransform is not decared in base component props\n const {dataTransform} = this.component.props;\n if (dataTransform) {\n data = dataTransform(chunk, data) as any[];\n } else {\n data = data.concat(chunk);\n }\n\n // Used by the default _dataDiff function\n Object.defineProperty(data, '__diff', {\n enumerable: false,\n value: [{startRow: count, endRow: data.length}]\n });\n\n count = data.length;\n this._setAsyncPropValue(propName, data, loadCount);\n }\n\n this._onResolve(propName, data);\n }\n\n // Give the app a chance to post process the loaded data\n private _postProcessValue(asyncProp: AsyncPropState, value: any) {\n const propType = asyncProp.type;\n if (propType && this.component) {\n if (propType.release) {\n propType.release(asyncProp.resolvedValue, propType, this.component);\n }\n if (propType.transform) {\n return propType.transform(value, propType, this.component);\n }\n }\n return value;\n }\n\n // Creating an asyncProp record if needed\n private _createAsyncPropData(propName: string, defaultValue: any) {\n const asyncProp = this.asyncProps[propName];\n if (!asyncProp) {\n const propTypes = this.component && this.component.props[PROP_TYPES_SYMBOL];\n // assert(defaultValue !== undefined);\n this.asyncProps[propName] = {\n type: propTypes && propTypes[propName],\n lastValue: null,\n resolvedValue: defaultValue,\n pendingLoadCount: 0,\n resolvedLoadCount: 0\n };\n }\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// deck.gl, MIT license\nimport ComponentState from '../lifecycle/component-state';\n\nimport type Layer from './layer';\nimport type AttributeManager from './attribute/attribute-manager';\nimport type Viewport from '../viewports/viewport';\nimport type UniformTransitionManager from './uniform-transition-manager';\n\nexport type ChangeFlags = {\n // Primary changeFlags, can be strings stating reason for change\n dataChanged: string | false | {startRow: number; endRow?: number}[];\n propsChanged: string | false;\n updateTriggersChanged: Record | false;\n extensionsChanged: boolean;\n viewportChanged: boolean;\n stateChanged: boolean;\n\n // Derived changeFlags\n propsOrDataChanged: boolean;\n somethingChanged: boolean;\n};\n\nexport default class LayerState extends ComponentState {\n attributeManager: AttributeManager | null;\n needsRedraw: boolean;\n needsUpdate: boolean;\n /**\n * Sublayers rendered in a previous cycle\n */\n subLayers: Layer[] | null;\n /**\n * If the layer is using the shared instancedPickingColors buffer\n */\n usesPickingColorCache: boolean;\n /**\n * If the layer has picking buffer (pickingColors or instancePickingColors)\n */\n hasPickingBuffer?: boolean;\n /**\n * Dirty flags of the layer's props and state\n */\n changeFlags!: ChangeFlags;\n\n /** The last viewport rendered by this layer */\n viewport?: Viewport;\n\n uniformTransitions!: UniformTransitionManager;\n /** Populated during uniform transition to replace user-supplied values */\n propsInTransition?: LayerT['props'];\n\n constructor({\n attributeManager,\n layer\n }: {\n attributeManager: AttributeManager | null;\n layer: LayerT;\n }) {\n super(layer);\n this.attributeManager = attributeManager;\n this.needsRedraw = true;\n this.needsUpdate = true;\n this.subLayers = null;\n this.usesPickingColorCache = false;\n }\n\n get layer(): LayerT | null {\n return this.component;\n }\n\n /* Override base Component methods with Layer-specific handling */\n\n protected _fetch(propName, url: string) {\n const layer = this.layer;\n const fetch = layer?.props.fetch;\n if (fetch) {\n return fetch(url, {propName, layer});\n }\n return super._fetch(propName, url);\n }\n\n protected _onResolve(propName: string, value: any) {\n const layer = this.layer;\n if (layer) {\n const onDataLoad = layer.props.onDataLoad;\n if (propName === 'data' && onDataLoad) {\n onDataLoad(value, {propName, layer});\n }\n }\n }\n\n protected _onError(propName: string, error: Error) {\n const layer = this.layer;\n if (layer) {\n layer.raiseError(error, `loading ${propName} of ${this.layer}`);\n }\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport Layer, {UpdateParameters} from './layer';\nimport debug from '../debug/index';\nimport {flatten} from '../utils/flatten';\n\nimport type AttributeManager from './attribute/attribute-manager';\nimport type {PickingInfo, GetPickingInfoParams} from './picking/pick-info';\nimport type {FilterContext} from '../passes/layers-pass';\nimport type {LayersList, LayerContext} from './layer-manager';\nimport type {CompositeLayerProps, Accessor, AccessorContext} from '../types/layer-props';\nimport {ConstructorOf} from '../types/types';\nimport {PROP_TYPES_SYMBOL} from '../lifecycle/constants';\n\nconst TRACE_RENDER_LAYERS = 'compositeLayer.renderLayers';\n\nexport default abstract class CompositeLayer extends Layer<\n PropsT & Required\n> {\n static layerName: string = 'CompositeLayer';\n\n /** `true` if this layer renders other layers */\n get isComposite(): boolean {\n return true;\n }\n\n /** `true` if the layer renders to screen */\n get isDrawable(): boolean {\n return false;\n }\n\n /** Returns true if all async resources are loaded */\n get isLoaded(): boolean {\n return super.isLoaded && this.getSubLayers().every(layer => layer.isLoaded);\n }\n\n /** Return last rendered sub layers */\n getSubLayers(): Layer[] {\n return (this.internalState && this.internalState.subLayers) || [];\n }\n\n // initializeState is usually not needed for composite layers\n // Provide empty definition to disable check for missing definition\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n initializeState(context: LayerContext): void {}\n\n /** Updates selected state members and marks the composite layer to need rerender */\n setState(updateObject: any): void {\n super.setState(updateObject);\n // Trigger a layer update\n // Although conceptually layer.draw and compositeLayer.renderLayers are equivalent,\n // they are executed during different lifecycles.\n // draw can be called without calling updateState (e.g. most viewport changes),\n // while renderLayers can only be called during a recursive layer update.\n this.setNeedsUpdate();\n }\n\n /** called to augment the info object that is bubbled up from a sublayer\n override Layer.getPickingInfo() because decoding / setting uniform do\n not apply to a composite layer. */\n getPickingInfo({info}: GetPickingInfoParams): PickingInfo {\n const {object} = info;\n const isDataWrapped =\n object && object.__source && object.__source.parent && object.__source.parent.id === this.id;\n\n if (!isDataWrapped) {\n return info;\n }\n\n // override object with picked data\n info.object = object.__source.object;\n info.index = object.__source.index;\n\n return info;\n }\n\n // Implement to generate subLayers\n abstract renderLayers(): Layer | null | LayersList;\n\n /**\n * Filters sub layers at draw time. Return true if the sub layer should be drawn.\n */\n filterSubLayer(context: FilterContext): boolean {\n return true;\n }\n\n /** Returns true if sub layer needs to be rendered */\n protected shouldRenderSubLayer(subLayerId: string, data: any): boolean {\n return data && data.length;\n }\n\n /** Returns sub layer class for a specific sublayer */\n protected getSubLayerClass(\n subLayerId: string,\n DefaultLayerClass: ConstructorOf\n ): ConstructorOf {\n const {_subLayerProps: overridingProps} = this.props;\n\n return (\n (overridingProps &&\n overridingProps[subLayerId] &&\n (overridingProps[subLayerId].type as ConstructorOf)) ||\n DefaultLayerClass\n );\n }\n\n /** When casting user data into another format to pass to sublayers,\n add reference to the original object and object index */\n protected getSubLayerRow(row: T, sourceObject: any, sourceObjectIndex: number): T {\n // @ts-ignore (TS2339) adding undefined property\n row.__source = {\n parent: this,\n object: sourceObject,\n index: sourceObjectIndex\n };\n return row;\n }\n\n /** Some composite layers cast user data into another format before passing to sublayers\n We need to unwrap them before calling the accessor so that they see the original data\n objects */\n protected getSubLayerAccessor(accessor: Accessor): Accessor {\n if (typeof accessor === 'function') {\n const objectInfo: AccessorContext = {\n index: -1,\n // @ts-ignore accessing resolved data\n data: this.props.data,\n target: []\n };\n return (x: any, i: AccessorContext) => {\n if (x && x.__source) {\n objectInfo.index = x.__source.index;\n // @ts-ignore (TS2349) Out is never a function\n return accessor(x.__source.object as In, objectInfo);\n }\n // @ts-ignore (TS2349) Out is never a function\n return accessor(x as In, i);\n };\n }\n return accessor;\n }\n\n /** Returns sub layer props for a specific sublayer */\n // eslint-disable-next-line complexity\n protected getSubLayerProps(\n sublayerProps: {\n id?: string;\n updateTriggers?: Record;\n [propName: string]: any;\n } = {}\n ): any {\n const {\n opacity,\n pickable,\n visible,\n parameters,\n getPolygonOffset,\n highlightedObjectIndex,\n autoHighlight,\n highlightColor,\n coordinateSystem,\n coordinateOrigin,\n wrapLongitude,\n positionFormat,\n modelMatrix,\n extensions,\n fetch,\n operation,\n _subLayerProps: overridingProps\n } = this.props;\n const newProps = {\n id: '',\n updateTriggers: {},\n opacity,\n pickable,\n visible,\n parameters,\n getPolygonOffset,\n highlightedObjectIndex,\n autoHighlight,\n highlightColor,\n coordinateSystem,\n coordinateOrigin,\n wrapLongitude,\n positionFormat,\n modelMatrix,\n extensions,\n fetch,\n operation\n };\n\n const overridingSublayerProps =\n overridingProps && sublayerProps.id && overridingProps[sublayerProps.id];\n const overridingSublayerTriggers =\n overridingSublayerProps && overridingSublayerProps.updateTriggers;\n const sublayerId = sublayerProps.id || 'sublayer';\n\n if (overridingSublayerProps) {\n const propTypes = this.props[PROP_TYPES_SYMBOL];\n const subLayerPropTypes = sublayerProps.type ? sublayerProps.type._propTypes : {};\n for (const key in overridingSublayerProps) {\n const propType = subLayerPropTypes[key] || propTypes[key];\n // eslint-disable-next-line\n if (propType && propType.type === 'accessor') {\n overridingSublayerProps[key] = this.getSubLayerAccessor(overridingSublayerProps[key]);\n }\n }\n }\n\n Object.assign(\n newProps,\n sublayerProps,\n // experimental feature that allows users to override sublayer props via parent layer prop\n overridingSublayerProps\n );\n newProps.id = `${this.props.id}-${sublayerId}`;\n newProps.updateTriggers = {\n all: this.props.updateTriggers?.all,\n ...sublayerProps.updateTriggers,\n ...overridingSublayerTriggers\n };\n\n // Pass through extension props\n // @ts-ignore (TS2532) extensions is always defined after merging with default props\n for (const extension of extensions) {\n const passThroughProps = extension.getSubLayerProps.call(this, extension);\n if (passThroughProps) {\n Object.assign(newProps, passThroughProps, {\n updateTriggers: Object.assign(newProps.updateTriggers, passThroughProps.updateTriggers)\n });\n }\n }\n\n return newProps;\n }\n\n /** Update sub layers to highlight the hovered object */\n protected _updateAutoHighlight(info: PickingInfo): void {\n for (const layer of this.getSubLayers()) {\n layer.updateAutoHighlight(info);\n }\n }\n\n /** Override base Layer method */\n protected _getAttributeManager(): AttributeManager | null {\n return null;\n }\n\n /** (Internal) Called after an update to rerender sub layers */\n protected _postUpdate(updateParams: UpdateParameters, forceUpdate: boolean) {\n // @ts-ignore (TS2531) this method is only called internally when internalState is defined\n let subLayers = this.internalState.subLayers as Layer[];\n const shouldUpdate = !subLayers || this.needsUpdate();\n if (shouldUpdate) {\n const subLayersList = this.renderLayers();\n // Flatten the returned array, removing any null, undefined or false\n // this allows layers to render sublayers conditionally\n // (see CompositeLayer.renderLayers docs)\n subLayers = flatten(subLayersList, Boolean) as Layer[];\n // @ts-ignore (TS2531) this method is only called internally when internalState is defined\n this.internalState.subLayers = subLayers;\n }\n debug(TRACE_RENDER_LAYERS, this, shouldUpdate, subLayers);\n\n // populate reference to parent layer (this layer)\n // NOTE: needs to be done even when reusing layers as the parent may have changed\n for (const layer of subLayers) {\n layer.parent = this;\n }\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {clamp} from '@math.gl/core';\nimport Controller, {ControllerProps} from './controller';\n\nimport {MapState, MapStateProps} from './map-controller';\nimport type {MapStateInternal} from './map-controller';\nimport {mod} from '../utils/math-utils';\nimport LinearInterpolator from '../transitions/linear-interpolator';\nimport {zoomAdjust, GLOBE_RADIUS} from '../viewports/globe-viewport';\n\nimport {MAX_LATITUDE} from '@math.gl/web-mercator';\n\nconst DEGREES_TO_RADIANS = Math.PI / 180;\nconst RADIANS_TO_DEGREES = 180 / Math.PI;\n\nfunction degreesToPixels(angle: number, zoom: number = 0): number {\n const radians = Math.min(180, angle) * DEGREES_TO_RADIANS;\n const size = GLOBE_RADIUS * 2 * Math.sin(radians / 2);\n return size * Math.pow(2, zoom);\n}\nfunction pixelsToDegrees(pixels: number, zoom: number = 0): number {\n const size = pixels / Math.pow(2, zoom);\n const radians = Math.asin(Math.min(1, size / GLOBE_RADIUS / 2)) * 2;\n return radians * RADIANS_TO_DEGREES;\n}\n\ntype GlobeStateInternal = MapStateInternal & {\n startPanPos?: [number, number];\n};\n\nclass GlobeState extends MapState {\n constructor(\n options: MapStateProps &\n GlobeStateInternal & {\n makeViewport: (props: Record) => any;\n }\n ) {\n const {startPanPos, ...mapStateOptions} = options;\n mapStateOptions.normalize = false; // disable MapState default normalization\n super(mapStateOptions);\n\n if (startPanPos !== undefined) {\n (this as any)._state.startPanPos = startPanPos;\n }\n }\n\n panStart({pos}: {pos: [number, number]}): GlobeState {\n const {latitude, longitude, zoom} = this.getViewportProps();\n return this._getUpdatedState({\n startPanLngLat: [longitude, latitude],\n startPanPos: pos,\n startZoom: zoom\n }) as GlobeState;\n }\n\n pan({pos, startPos}: {pos: [number, number]; startPos?: [number, number]}): GlobeState {\n const state = this.getState() as GlobeStateInternal;\n const startPanLngLat = state.startPanLngLat || this._unproject(startPos);\n if (!startPanLngLat) return this;\n const startZoom = state.startZoom ?? this.getViewportProps().zoom;\n const startPanPos = state.startPanPos || startPos;\n\n const coords = [startPanLngLat[0], startPanLngLat[1], startZoom];\n const viewport = this.makeViewport(this.getViewportProps());\n const newProps = viewport.panByPosition(coords, pos, startPanPos);\n return this._getUpdatedState(newProps) as GlobeState;\n }\n\n panEnd(): GlobeState {\n return this._getUpdatedState({\n startPanLngLat: null,\n startPanPos: null,\n startZoom: null\n }) as GlobeState;\n }\n\n zoom({scale}: {scale: number}): MapState {\n // In Globe view zoom does not take into account the mouse position\n const startZoom = this.getState().startZoom || this.getViewportProps().zoom;\n const zoom = startZoom + Math.log2(scale);\n return this._getUpdatedState({zoom});\n }\n\n applyConstraints(props: Required): Required {\n // Ensure zoom is within specified range\n const {longitude, latitude, maxBounds} = props;\n\n props.zoom = this._constrainZoom(props.zoom, props);\n\n if (longitude < -180 || longitude > 180) {\n props.longitude = mod(longitude + 180, 360) - 180;\n }\n props.latitude = clamp(latitude, -MAX_LATITUDE, MAX_LATITUDE);\n if (maxBounds) {\n props.longitude = clamp(props.longitude, maxBounds[0][0], maxBounds[1][0]);\n props.latitude = clamp(props.latitude, maxBounds[0][1], maxBounds[1][1]);\n }\n\n if (maxBounds) {\n // calculate center and zoom ranges at pitch=0 and bearing=0\n // to maintain visual stability when rotating\n const effectiveZoom = props.zoom - zoomAdjust(latitude);\n const lngSpan = maxBounds[1][0] - maxBounds[0][0];\n const latSpan = maxBounds[1][1] - maxBounds[0][1];\n if (latSpan > 0 && latSpan < MAX_LATITUDE * 2) {\n const halfHeightDegrees =\n Math.min(pixelsToDegrees(props.height, effectiveZoom), latSpan) / 2;\n props.latitude = clamp(\n props.latitude,\n maxBounds[0][1] + halfHeightDegrees,\n maxBounds[1][1] - halfHeightDegrees\n );\n }\n if (lngSpan > 0 && lngSpan < 360) {\n const halfWidthDegrees =\n Math.min(\n pixelsToDegrees(\n props.width / Math.cos(props.latitude * DEGREES_TO_RADIANS),\n effectiveZoom\n ),\n lngSpan\n ) / 2;\n props.longitude = clamp(\n props.longitude,\n maxBounds[0][0] + halfWidthDegrees,\n maxBounds[1][0] - halfWidthDegrees\n );\n }\n }\n if (props.latitude !== latitude) {\n props.zoom += zoomAdjust(props.latitude) - zoomAdjust(latitude);\n }\n\n return props;\n }\n\n _constrainZoom(zoom: number, props?: Required): number {\n props ||= this.getViewportProps();\n const {latitude, maxZoom, maxBounds} = props;\n let {minZoom} = props;\n const ZOOM0 = zoomAdjust(0);\n const zoomAdjustment = zoomAdjust(latitude) - ZOOM0;\n\n const shouldApplyMaxBounds = maxBounds !== null && props.width > 0 && props.height > 0;\n if (shouldApplyMaxBounds) {\n const minLatitude = maxBounds[0][1];\n const maxLatitude = maxBounds[1][1];\n // latitude at which the bounding box is the widest\n const fitLatitude =\n Math.sign(minLatitude) === Math.sign(maxLatitude)\n ? Math.min(Math.abs(minLatitude), Math.abs(maxLatitude))\n : 0;\n const w =\n degreesToPixels(maxBounds[1][0] - maxBounds[0][0]) *\n Math.cos(fitLatitude * DEGREES_TO_RADIANS);\n const h = degreesToPixels(maxBounds[1][1] - maxBounds[0][1]);\n if (w > 0) {\n minZoom = Math.max(minZoom, Math.log2(props.width / w) + ZOOM0);\n }\n if (h > 0) {\n minZoom = Math.max(minZoom, Math.log2(props.height / h) + ZOOM0);\n }\n if (minZoom > maxZoom) minZoom = maxZoom;\n }\n\n return clamp(zoom, minZoom + zoomAdjustment, maxZoom + zoomAdjustment);\n }\n}\n\nexport default class GlobeController extends Controller {\n ControllerState = GlobeState;\n\n transition = {\n transitionDuration: 300,\n transitionInterpolator: new LinearInterpolator(['longitude', 'latitude', 'zoom'])\n };\n\n dragMode: 'pan' | 'rotate' = 'pan';\n\n setProps(props: ControllerProps) {\n super.setProps(props);\n\n // TODO - support pitching?\n this.dragRotate = false;\n this.touchRotate = false;\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport View, {CommonViewState, CommonViewProps} from './view';\nimport GlobeViewport from '../viewports/globe-viewport';\nimport WebMercatorViewport from '../viewports/web-mercator-viewport';\nimport GlobeController from '../controllers/globe-controller';\n\nexport type GlobeViewState = {\n /** Longitude of the map center */\n longitude: number;\n /** Latitude of the map center */\n latitude: number;\n /** Zoom level */\n zoom: number;\n /** Min zoom, default `0` */\n minZoom?: number;\n /** Max zoom, default `20` */\n maxZoom?: number;\n /** The near plane position */\n nearZ?: number;\n /** The far plane position */\n farZ?: number;\n} & CommonViewState;\n\nexport type GlobeViewProps = {\n /** The resolution at which to turn flat features into 3D meshes, in degrees. Smaller numbers will generate more detailed mesh. Default `10`. */\n resolution?: number;\n /** Scaler for the near plane, 1 unit equals to the height of the viewport. Default to `0.1`. Overwrites the `near` parameter. */\n nearZMultiplier?: number;\n /** Scaler for the far plane, 1 unit equals to the distance from the camera to the top edge of the screen. Default to `1.01`. Overwrites the `far` parameter. */\n farZMultiplier?: number;\n /** Distance of the camera relative to viewport height. Default `1.5`. */\n altitude?: number;\n} & CommonViewProps;\n\nexport default class GlobeView extends View {\n static displayName = 'GlobeView';\n\n constructor(props: GlobeViewProps = {}) {\n super(props);\n }\n\n getViewportType(viewState: GlobeViewState) {\n return viewState.zoom > 12 ? WebMercatorViewport : GlobeViewport;\n }\n\n get ControllerType() {\n return GlobeController;\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {drawLayerGroup} from './deck-utils';\nimport type {Map, CustomLayerInterface} from './types';\nimport {assert, type Deck} from '@deck.gl/core';\n\ntype MapWithDeck = Map & {__deck: Deck};\n\nexport type MapboxLayerGroupProps = {\n id: string;\n renderingMode?: '2d' | '3d';\n /* Mapbox v3 Standard style */\n slot?: 'bottom' | 'middle' | 'top';\n beforeId?: string;\n};\n\nexport default class MapboxLayerGroup implements CustomLayerInterface {\n id: string;\n type: 'custom';\n renderingMode: '2d' | '3d';\n /* Mapbox v3 Standard style */\n slot?: 'bottom' | 'middle' | 'top';\n beforeId?: string;\n map: MapWithDeck | null;\n\n /* eslint-disable no-this-before-super */\n constructor(props: MapboxLayerGroupProps) {\n assert(props.id, 'id is required');\n\n this.id = props.id;\n this.type = 'custom';\n this.renderingMode = props.renderingMode || '3d';\n this.slot = props.slot;\n this.beforeId = props.beforeId;\n this.map = null;\n }\n\n /* Mapbox custom layer methods */\n\n onAdd(map: MapWithDeck, gl: WebGL2RenderingContext): void {\n this.map = map;\n }\n\n render(gl, renderParameters) {\n if (!this.map) return;\n\n drawLayerGroup(this.map.__deck, this.map, this, renderParameters);\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {_flatten as flatten} from '@deck.gl/core';\n\nimport type {Layer, LayersList} from '@deck.gl/core';\nimport type {Map, LayerOverlayProps} from './types';\nimport MapboxLayerGroup from './mapbox-layer-group';\n\nconst UNDEFINED_BEFORE_ID = '__UNDEFINED__';\n\nexport function getLayerGroupId(layer: Layer): string {\n if (layer.props.beforeId) {\n return `deck-layer-group-before:${layer.props.beforeId}`;\n } else if (layer.props.slot) {\n return `deck-layer-group-slot:${layer.props.slot}`;\n }\n return 'deck-layer-group-last';\n}\n\n/** Group Deck layers into buckets (by beforeId or slot) and insert them\n * into the mapbox Map according to the user-defined order\n **/\n// eslint-disable-next-line complexity, max-statements\nexport function resolveLayerGroups(map?: Map, oldLayers?: LayersList, newLayers?: LayersList) {\n // Wait until map style is loaded\n // @ts-ignore non-public map property\n if (!map || !map.style || !map.style._loaded) {\n return;\n }\n\n const layers = flatten(newLayers, Boolean) as Layer[];\n\n if (oldLayers !== newLayers) {\n // Step 1: remove \"group\" layers that no longer exist\n const prevLayers = flatten(oldLayers, Boolean) as Layer[];\n const prevLayerGroupIds = new Set(prevLayers.map(l => getLayerGroupId(l)));\n const newLayerGroupIds = new Set(layers.map(l => getLayerGroupId(l)));\n\n for (const groupId of prevLayerGroupIds) {\n if (!newLayerGroupIds.has(groupId)) {\n if (map.getLayer(groupId)) {\n map.removeLayer(groupId);\n }\n }\n }\n }\n\n // Step 2: add missing \"group\" layers\n const layerGroups: Record = {};\n for (const layer of layers) {\n const groupId = getLayerGroupId(layer);\n const mapboxGroup = map.getLayer(groupId) as MapboxLayerGroup;\n if (mapboxGroup) {\n // Mapbox's map.getLayer() had a breaking change in v3.6.0, see https://github.com/visgl/deck.gl/issues/9086\n // @ts-expect-error not typed\n const groupInstance = mapboxGroup.implementation || mapboxGroup;\n layerGroups[groupId] = groupInstance;\n } else {\n const newGroup = new MapboxLayerGroup({\n id: groupId,\n slot: layer.props.slot,\n beforeId: layer.props.beforeId\n });\n layerGroups[groupId] = newGroup;\n map.addLayer(newGroup, layer.props.beforeId);\n }\n }\n\n // Step 3: check the order of layers\n // If beforeId move \"group\" layers to proper position in the mapbox layer order\n // @ts-ignore non-public map property\n const mapLayers: string[] = map.style._order;\n\n for (const [groupId, group] of Object.entries(layerGroups)) {\n const beforeId = group.beforeId || UNDEFINED_BEFORE_ID;\n\n const expectedGroupIndex =\n beforeId === UNDEFINED_BEFORE_ID ? mapLayers.length : mapLayers.indexOf(beforeId);\n\n const currentGropupIndex = mapLayers.indexOf(groupId);\n if (currentGropupIndex !== expectedGroupIndex - 1) {\n const moveBeforeId = beforeId === UNDEFINED_BEFORE_ID ? undefined : beforeId;\n map.moveLayer(groupId, moveBeforeId);\n }\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Deck, MapView, _GlobeView as GlobeView, _flatten as flatten} from '@deck.gl/core';\nimport type {Viewport, MapViewState, Layer} from '@deck.gl/core';\nimport type {Parameters} from '@luma.gl/core';\nimport type MapboxLayerGroup from './mapbox-layer-group';\nimport type {LayerOverlayProps, Map} from './types';\nimport {getLayerGroupId} from './resolve-layer-groups';\n\nimport {lngLatToWorld, unitsPerMeter} from '@math.gl/web-mercator';\n\nexport const MAPBOX_VIEW_ID = 'mapbox';\n\ntype UserData = {\n currentViewport?: Viewport | null;\n};\n\n// Mercator constants\nconst TILE_SIZE = 512;\nconst DEGREES_TO_RADIANS = Math.PI / 180;\n\n// Create an interleaved deck instance.\nexport function getDeckInstance({\n map,\n deck\n}: {\n map: Map & {__deck?: Deck | null};\n deck: Deck;\n}): Deck {\n // Only create one deck instance per context\n if (map.__deck) {\n return map.__deck;\n }\n\n // Only initialize certain props once per context\n const customRender = deck.props._customRender;\n const onLoad = deck.props.onLoad;\n\n const deckProps = {\n ...deck.props,\n _customRender: () => {\n map.triggerRepaint();\n // customRender may be subscribed by DeckGL React component to update child props\n // make sure it is still called\n // Hack - do not pass a redraw reason here to prevent the React component from clearing the context\n // Rerender will be triggered by MapboxLayerGroup's render()\n customRender?.('');\n }\n };\n deckProps.views ||= getDefaultView(map);\n\n // deck is using the WebGLContext created by mapbox,\n // block deck from setting the canvas size, and use the map's viewState to drive deck.\n Object.assign(deckProps, {\n width: null,\n height: null,\n touchAction: 'unset',\n viewState: getViewState(map)\n });\n if (deck.isInitialized) {\n watchMapMove(deck, map);\n } else {\n deckProps.onLoad = () => {\n onLoad?.();\n watchMapMove(deck, map);\n };\n }\n\n deck.setProps(deckProps);\n\n map.__deck = deck;\n map.on('render', () => {\n if (deck.isInitialized) afterRender(deck, map);\n });\n\n return deck;\n}\n\nfunction watchMapMove(deck: Deck, map: Map & {__deck?: Deck | null}) {\n const _handleMapMove = () => {\n if (deck.isInitialized) {\n // call view state methods\n onMapMove(deck, map);\n } else {\n // deregister itself when deck is finalized\n map.off('move', _handleMapMove);\n }\n };\n map.on('move', _handleMapMove);\n}\n\nexport function removeDeckInstance(map: Map & {__deck?: Deck | null}) {\n map.__deck?.finalize();\n map.__deck = null;\n}\n\nexport function getDefaultParameters(map: Map, interleaved: boolean): Parameters {\n const result: Parameters = interleaved\n ? {\n depthWriteEnabled: true,\n depthCompare: 'less-equal',\n depthBias: 0,\n blend: true,\n blendColorSrcFactor: 'src-alpha',\n blendColorDstFactor: 'one-minus-src-alpha',\n blendAlphaSrcFactor: 'one',\n blendAlphaDstFactor: 'one-minus-src-alpha',\n blendColorOperation: 'add',\n blendAlphaOperation: 'add'\n }\n : {};\n if (getProjection(map) === 'globe') {\n result.cullMode = 'back';\n }\n return result;\n}\n\nexport function drawLayerGroup(\n deck: Deck,\n map: Map,\n group: MapboxLayerGroup,\n renderParameters: any\n): void {\n if (!deck.isInitialized) {\n return;\n }\n\n let {currentViewport} = deck.userData as UserData;\n let clearStack: boolean = false;\n if (!currentViewport) {\n // This is the first layer drawn in this render cycle.\n // Generate viewport from the current map state.\n currentViewport = getViewport(deck, map, renderParameters);\n (deck.userData as UserData).currentViewport = currentViewport;\n clearStack = true;\n }\n\n if (!currentViewport) {\n return;\n }\n\n deck._drawLayers('mapbox-repaint', {\n viewports: [currentViewport],\n layerFilter: params => {\n if (deck.props.layerFilter && !deck.props.layerFilter(params)) {\n return false;\n }\n\n const layer = params.layer as Layer;\n if (layer.props.beforeId === group.beforeId && layer.props.slot === group.slot) {\n return true;\n }\n return false;\n },\n clearStack,\n clearCanvas: false\n });\n}\n\nexport function getProjection(map: Map): 'mercator' | 'globe' {\n const projection = map.getProjection?.();\n const type =\n // maplibre projection spec\n projection?.type ||\n // mapbox projection spec\n projection?.name;\n if (type === 'globe') {\n return 'globe';\n }\n if (type && type !== 'mercator') {\n throw new Error('Unsupported projection');\n }\n return 'mercator';\n}\n\nexport function getDefaultView(map: Map): GlobeView | MapView {\n if (getProjection(map) === 'globe') {\n return new GlobeView({id: MAPBOX_VIEW_ID});\n }\n return new MapView({id: MAPBOX_VIEW_ID});\n}\n\nexport function getViewState(map: Map): MapViewState & {\n repeat: boolean;\n padding: {\n left: number;\n right: number;\n top: number;\n bottom: number;\n };\n} {\n const {lng, lat} = map.getCenter();\n\n const viewState: MapViewState & {\n repeat: boolean;\n padding: {\n left: number;\n right: number;\n top: number;\n bottom: number;\n };\n } = {\n // Longitude returned by getCenter can be outside of [-180, 180] when zooming near the anti meridian\n // https://github.com/visgl/deck.gl/issues/6894\n longitude: ((lng + 540) % 360) - 180,\n latitude: lat,\n zoom: map.getZoom(),\n bearing: map.getBearing(),\n pitch: map.getPitch(),\n padding: map.getPadding(),\n repeat: map.getRenderWorldCopies()\n };\n\n if (map.getTerrain?.()) {\n // When the base map has terrain, we need to target the camera at the terrain surface\n centerCameraOnTerrain(map, viewState);\n }\n\n return viewState;\n}\n\nfunction centerCameraOnTerrain(map: Map, viewState: MapViewState) {\n if (map.getFreeCameraOptions) {\n // mapbox-gl v2\n const {position} = map.getFreeCameraOptions();\n if (!position || position.z === undefined) {\n return;\n }\n\n // @ts-ignore transform is not typed\n const height = map.transform.height;\n const {longitude, latitude, pitch} = viewState;\n\n // Convert mapbox mercator coordinate to deck common space\n const cameraX = position.x * TILE_SIZE;\n const cameraY = (1 - position.y) * TILE_SIZE;\n const cameraZ = position.z * TILE_SIZE;\n\n // Mapbox manipulates zoom in terrain mode, see discussion here: https://github.com/mapbox/mapbox-gl-js/issues/12040\n const center = lngLatToWorld([longitude, latitude]);\n const dx = cameraX - center[0];\n const dy = cameraY - center[1];\n const cameraToCenterDistanceGround = Math.sqrt(dx * dx + dy * dy);\n\n const pitchRadians = pitch! * DEGREES_TO_RADIANS;\n const altitudePixels = 1.5 * height;\n const scale =\n pitchRadians < 0.001\n ? // Pitch angle too small to deduce the look at point, assume elevation is 0\n (altitudePixels * Math.cos(pitchRadians)) / cameraZ\n : (altitudePixels * Math.sin(pitchRadians)) / cameraToCenterDistanceGround;\n viewState.zoom = Math.log2(scale);\n\n const cameraZFromSurface = (altitudePixels * Math.cos(pitchRadians)) / scale;\n const surfaceElevation = cameraZ - cameraZFromSurface;\n viewState.position = [0, 0, surfaceElevation / unitsPerMeter(latitude)];\n }\n // @ts-ignore transform is not typed\n else if (typeof map.transform.elevation === 'number') {\n // maplibre-gl\n // @ts-ignore transform is not typed\n viewState.position = [0, 0, map.transform.elevation];\n }\n}\n\n// Since maplibre-gl@5\n// https://github.com/maplibre/maplibre-gl-js/blob/main/src/style/style_layer/custom_style_layer.ts\ntype MaplibreRenderParameters = {\n farZ: number;\n nearZ: number;\n fov: number;\n modelViewProjectionMatrix: number[];\n projectionMatrix: number[];\n};\n\nfunction getViewport(deck: Deck, map: Map, renderParameters?: unknown): Viewport | null {\n const viewState = getViewState(map);\n // View is always MapView or GlobeView in this context\n const view = (deck.getView(MAPBOX_VIEW_ID) || getDefaultView(map)) as MapView | GlobeView;\n\n if (renderParameters) {\n // Called from MapboxLayerGroup.render\n // Magic number, matches mapbox-gl@>=1.3.0's projection matrix\n view.props.nearZMultiplier = 0.2;\n }\n\n // Get the base map near/far plane\n // renderParameters is maplibre API but not mapbox\n // Transform is not an official API, properties could be undefined for older versions\n const nearZ = (renderParameters as MaplibreRenderParameters)?.nearZ ?? map.transform._nearZ;\n const farZ = (renderParameters as MaplibreRenderParameters)?.farZ ?? map.transform._farZ;\n if (Number.isFinite(nearZ)) {\n viewState.nearZ = nearZ / map.transform.height;\n viewState.farZ = farZ / map.transform.height;\n }\n // Otherwise fallback to default calculation using nearZMultiplier/farZMultiplier\n\n return view.makeViewport({\n width: deck.width,\n height: deck.height,\n viewState\n });\n}\n\nfunction afterRender(deck: Deck, map: Map): void {\n // Draw non-Mapbox layers (layers that don't have a corresponding MapboxLayerGroup on the map)\n const deckLayers = flatten(deck.props.layers, Boolean) as Layer[];\n const hasNonMapboxLayers = deckLayers.some(\n layer => layer && !map.getLayer(getLayerGroupId(layer))\n );\n let viewports = deck.getViewports();\n const mapboxViewportIdx = viewports.findIndex(vp => vp.id === MAPBOX_VIEW_ID);\n const hasNonMapboxViews = viewports.length > 1 || mapboxViewportIdx < 0;\n\n if (hasNonMapboxLayers || hasNonMapboxViews) {\n if (mapboxViewportIdx >= 0) {\n viewports = viewports.slice();\n const mapboxViewport = getViewport(deck, map);\n if (mapboxViewport) {\n viewports[mapboxViewportIdx] = mapboxViewport;\n } else {\n viewports.splice(mapboxViewportIdx, 1);\n }\n }\n\n deck._drawLayers('mapbox-repaint', {\n viewports,\n layerFilter: params =>\n (!deck.props.layerFilter || deck.props.layerFilter(params)) &&\n (params.viewport.id !== MAPBOX_VIEW_ID ||\n !map.getLayer(getLayerGroupId(params.layer as Layer))),\n clearCanvas: false\n });\n } else {\n // Even when there are no non-Mapbox layers to draw, fire lifecycle callbacks\n // so that consumers can still track view state changes via onAfterRender\n const device = (deck as any).device;\n const gl = device?.gl;\n deck.props.onBeforeRender?.({device, gl});\n deck.props.onAfterRender?.({device, gl});\n }\n\n // End of render cycle, clear generated viewport\n (deck.userData as UserData).currentViewport = null;\n}\n\nfunction onMapMove(deck: Deck, map: Map): void {\n deck.setProps({\n viewState: getViewState(map)\n });\n // Camera changed, will trigger a map repaint right after this\n // Clear any change flag triggered by setting viewState so that deck does not request\n // a second repaint\n deck.needsRedraw({clearRedrawFlags: true});\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Deck, assert, log} from '@deck.gl/core';\nimport {\n getViewState,\n getDefaultView,\n getDeckInstance,\n removeDeckInstance,\n getDefaultParameters,\n getProjection,\n MAPBOX_VIEW_ID\n} from './deck-utils';\n\nimport type {Map, IControl, MapMouseEvent, ControlPosition} from './types';\nimport type {MjolnirGestureEvent, MjolnirPointerEvent} from 'mjolnir.js';\nimport type {DeckProps, LayersList} from '@deck.gl/core';\n\nimport {resolveLayerGroups} from './resolve-layer-groups';\n\nexport type MapboxOverlayProps = Omit<\n DeckProps,\n | 'width'\n | 'height'\n | 'gl'\n | 'parent'\n | 'canvas'\n | '_customRender'\n | 'viewState'\n | 'initialViewState'\n | 'controller'\n> & {\n /**\n * deck.gl layers are inserted into mapbox-gl's layer stack, and share the same WebGL2RenderingContext as the base map.\n */\n interleaved?: boolean;\n};\n\n/**\n * Implements Mapbox [IControl](https://docs.mapbox.com/mapbox-gl-js/api/markers/#icontrol) interface\n * Renders deck.gl layers over the base map and automatically synchronizes with the map's camera\n */\nexport default class MapboxOverlay implements IControl {\n private _props: MapboxOverlayProps;\n private _deck?: Deck;\n private _map?: Map;\n private _container?: HTMLDivElement;\n private _interleaved: boolean;\n private _lastMouseDownPoint?: {x: number; y: number; clientX: number; clientY: number};\n\n constructor(props: MapboxOverlayProps) {\n const {interleaved = false} = props;\n this._interleaved = interleaved;\n this._props = this.filterProps(props);\n }\n\n /** Filter out props to pass to Deck **/\n filterProps(props: MapboxOverlayProps): MapboxOverlayProps {\n const {interleaved = false, useDevicePixels, ...deckProps} = props;\n if (!interleaved && useDevicePixels !== undefined) {\n // useDevicePixels cannot be used in interleaved mode\n (deckProps as MapboxOverlayProps).useDevicePixels = useDevicePixels;\n }\n return deckProps;\n }\n\n /** Update (partial) props of the underlying Deck instance. */\n setProps(props: MapboxOverlayProps): void {\n if (this._interleaved && props.layers) {\n this._resolveLayers(this._map, this._deck, this._props.layers, props.layers);\n }\n\n Object.assign(this._props, this.filterProps(props));\n\n if (this._deck && this._map) {\n this._deck.setProps({\n ...this._props,\n views: this._getViews(this._map),\n parameters: {\n ...getDefaultParameters(this._map, this._interleaved),\n ...this._props.parameters\n }\n });\n }\n }\n\n // The local Map type is for internal typecheck only. It does not necesarily satisefy mapbox/maplibre types at runtime.\n // Do not restrict the argument type here to avoid type conflict.\n /** Called when the control is added to a map */\n onAdd(map: unknown): HTMLDivElement {\n this._map = map as Map;\n return this._interleaved ? this._onAddInterleaved(map as Map) : this._onAddOverlaid(map as Map);\n }\n\n private _onAddOverlaid(map: Map): HTMLDivElement {\n /* global document */\n const container = document.createElement('div');\n Object.assign(container.style, {\n position: 'absolute',\n left: 0,\n top: 0,\n textAlign: 'initial',\n pointerEvents: 'none'\n });\n this._container = container;\n\n this._deck = new Deck({\n ...this._props,\n parent: container,\n parameters: {...getDefaultParameters(map, false), ...this._props.parameters},\n views: this._getViews(map),\n viewState: getViewState(map)\n });\n\n map.on('resize', this._updateContainerSize);\n map.on('render', this._updateViewState);\n map.on('mousedown', this._handleMouseEvent);\n map.on('dragstart', this._handleMouseEvent);\n map.on('drag', this._handleMouseEvent);\n map.on('dragend', this._handleMouseEvent);\n map.on('mousemove', this._handleMouseEvent);\n map.on('mouseout', this._handleMouseEvent);\n map.on('click', this._handleMouseEvent);\n map.on('dblclick', this._handleMouseEvent);\n\n this._updateContainerSize();\n return container;\n }\n\n private _onAddInterleaved(map: Map): HTMLDivElement {\n // @ts-ignore non-public map property\n const gl: WebGL2RenderingContext = map.painter.context.gl;\n if (gl instanceof WebGLRenderingContext) {\n log.warn(\n 'Incompatible basemap library. See: https://deck.gl/docs/api-reference/mapbox/overview#compatibility'\n )();\n }\n this._deck = getDeckInstance({\n map,\n deck: new Deck({\n ...this._props,\n views: this._getViews(map),\n gl,\n parameters: {...getDefaultParameters(map, true), ...this._props.parameters}\n })\n });\n\n map.on('styledata', this._handleStyleChange);\n this._resolveLayers(map, this._deck, [], this._props.layers);\n\n return document.createElement('div');\n }\n\n private _resolveLayers(\n map: Map | undefined,\n _deck: Deck | undefined,\n prevLayers: LayersList | undefined,\n newLayers: LayersList | undefined\n ): void {\n resolveLayerGroups(map, prevLayers, newLayers);\n }\n\n /** Called when the control is removed from a map */\n onRemove(): void {\n const map = this._map;\n\n if (map) {\n if (this._interleaved) {\n this._onRemoveInterleaved(map);\n } else {\n this._onRemoveOverlaid(map);\n }\n }\n\n this._deck = undefined;\n this._map = undefined;\n this._container = undefined;\n }\n\n private _onRemoveOverlaid(map: Map): void {\n map.off('resize', this._updateContainerSize);\n map.off('render', this._updateViewState);\n map.off('mousedown', this._handleMouseEvent);\n map.off('dragstart', this._handleMouseEvent);\n map.off('drag', this._handleMouseEvent);\n map.off('dragend', this._handleMouseEvent);\n map.off('mousemove', this._handleMouseEvent);\n map.off('mouseout', this._handleMouseEvent);\n map.off('click', this._handleMouseEvent);\n map.off('dblclick', this._handleMouseEvent);\n this._deck?.finalize();\n }\n\n private _onRemoveInterleaved(map: Map): void {\n map.off('styledata', this._handleStyleChange);\n this._resolveLayers(map, this._deck, this._props.layers, []);\n removeDeckInstance(map);\n }\n\n getDefaultPosition(): ControlPosition {\n return 'top-left';\n }\n\n /** Forwards the Deck.pickObject method */\n pickObject(params: Parameters[0]): ReturnType {\n assert(this._deck);\n return this._deck.pickObject(params);\n }\n\n /** Forwards the Deck.pickMultipleObjects method */\n pickMultipleObjects(\n params: Parameters[0]\n ): ReturnType {\n assert(this._deck);\n return this._deck.pickMultipleObjects(params);\n }\n\n /** Forwards the Deck.pickObjects method */\n pickObjects(params: Parameters[0]): ReturnType {\n assert(this._deck);\n return this._deck.pickObjects(params);\n }\n\n /** Remove from map and releases all resources */\n finalize() {\n if (this._map) {\n this._map.removeControl(this);\n }\n }\n\n /** If interleaved: true, returns base map's canvas, otherwise forwards the Deck.getCanvas method. */\n getCanvas(): HTMLCanvasElement | null {\n if (!this._map) {\n return null;\n }\n return this._interleaved ? this._map.getCanvas() : this._deck!.getCanvas();\n }\n\n private _handleStyleChange = () => {\n this._resolveLayers(this._map, this._deck, this._props.layers, this._props.layers);\n if (!this._map) return;\n\n // getProjection() returns undefined before style is loaded\n const projection = getProjection(this._map);\n if (projection) {\n // Update views to match new projection (MapView vs GlobeView)\n this._deck?.setProps({views: this._getViews(this._map)});\n }\n };\n\n private _updateContainerSize = () => {\n if (this._map && this._container) {\n const {clientWidth, clientHeight} = this._map.getContainer();\n Object.assign(this._container.style, {\n width: `${clientWidth}px`,\n height: `${clientHeight}px`\n });\n }\n };\n\n private _getViews(map: Map) {\n if (!this._props.views) {\n return getDefaultView(map);\n }\n // Check if custom views already include a 'mapbox' view\n const views = Array.isArray(this._props.views) ? this._props.views : [this._props.views];\n const hasMapboxView = views.some((v: any) => v.id === MAPBOX_VIEW_ID);\n if (hasMapboxView) {\n return this._props.views;\n }\n // Add default 'mapbox' view to custom views for consistency with interleaved mode\n return [getDefaultView(map), ...views];\n }\n\n private _updateViewState = () => {\n const deck = this._deck;\n const map = this._map;\n if (deck && map) {\n deck.setProps({\n views: this._getViews(map),\n viewState: getViewState(map)\n });\n // Redraw immediately if view state has changed\n if (deck.isInitialized) {\n deck.redraw();\n }\n }\n };\n\n // eslint-disable-next-line complexity\n private _handleMouseEvent = (event: MapMouseEvent) => {\n const deck = this._deck;\n if (!deck || !deck.isInitialized) {\n return;\n }\n\n const mockEvent: {\n type: string;\n deltaX?: number;\n deltaY?: number;\n offsetCenter: {x: number; y: number};\n srcEvent: MapMouseEvent;\n tapCount?: number;\n } = {\n type: event.type,\n offsetCenter: event.point,\n srcEvent: event\n };\n\n const lastDown = this._lastMouseDownPoint;\n if (!event.point && lastDown) {\n // drag* events do not contain a `point` field\n mockEvent.deltaX = event.originalEvent.clientX - lastDown.clientX;\n mockEvent.deltaY = event.originalEvent.clientY - lastDown.clientY;\n mockEvent.offsetCenter = {\n x: lastDown.x + mockEvent.deltaX,\n y: lastDown.y + mockEvent.deltaY\n };\n }\n\n switch (mockEvent.type) {\n case 'mousedown':\n deck._onPointerDown(mockEvent as unknown as MjolnirPointerEvent);\n this._lastMouseDownPoint = {\n ...event.point,\n clientX: event.originalEvent.clientX,\n clientY: event.originalEvent.clientY\n };\n break;\n\n case 'dragstart':\n mockEvent.type = 'panstart';\n deck._onEvent(mockEvent as unknown as MjolnirGestureEvent);\n break;\n\n case 'drag':\n mockEvent.type = 'panmove';\n deck._onEvent(mockEvent as unknown as MjolnirGestureEvent);\n break;\n\n case 'dragend':\n mockEvent.type = 'panend';\n deck._onEvent(mockEvent as unknown as MjolnirGestureEvent);\n break;\n\n case 'click':\n mockEvent.tapCount = 1;\n deck._onEvent(mockEvent as unknown as MjolnirGestureEvent);\n break;\n\n case 'dblclick':\n mockEvent.type = 'click';\n mockEvent.tapCount = 2;\n deck._onEvent(mockEvent as unknown as MjolnirGestureEvent);\n break;\n\n case 'mousemove':\n mockEvent.type = 'pointermove';\n deck._onPointerMove(mockEvent as unknown as MjolnirPointerEvent);\n break;\n\n case 'mouseout':\n mockEvent.type = 'pointerleave';\n deck._onPointerMove(mockEvent as unknown as MjolnirPointerEvent);\n break;\n\n default:\n return;\n }\n };\n}\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport default `\\\n#version 300 es\n#define SHADER_NAME animated-flow-lines-layer-fragment-shader\n\nprecision highp float;\n\nin vec4 vColor;\nin float sourceToTarget;\nin vec2 uv;\n\nout vec4 fragColor;\n \nvoid main(void) {\n geometry.uv = uv;\n\n fragColor = vec4(vColor.xyz, vColor.w * smoothstep(1.0 - animatedFlowLines.animationTailLength, 1.0, fract(sourceToTarget)));\n\n DECKGL_FILTER_COLOR(fragColor, geometry);\n}\n`;\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\nexport default `\\\n#version 300 es\n#define SHADER_NAME animated-flow-lines-layer-vertex-shader\n#define SPEED 0.015\n#define NUM_PARTS 5.0\n\nin vec3 positions;\nin vec3 instanceSourcePositions;\nin vec3 instanceTargetPositions;\nin vec3 instanceSourcePositions64Low;\nin vec3 instanceTargetPositions64Low;\nin vec4 instanceColors;\nin vec3 instancePickingColors;\nin float instanceWidths;\nin float instancePickable;\nin float instanceStaggering;\n\nout vec4 vColor;\nout float sourceToTarget;\nout vec2 uv;\n\n// offset vector by strokeWidth pixels\n// offset_direction is -1 (left) or 1 (right)\nvec2 getExtrusionOffset(vec2 line_clipspace, float offset_direction, float width) {\n // normalized direction of the line\n vec2 dir_screenspace = normalize(line_clipspace * project.viewportSize);\n // rotate by 90 degrees\n dir_screenspace = vec2(-dir_screenspace.y, dir_screenspace.x);\n\n return dir_screenspace * offset_direction * width / 2.0;\n}\n\nvoid main(void) {\n geometry.worldPosition = instanceSourcePositions;\n geometry.worldPositionAlt = instanceTargetPositions;\n\n // Position\n vec4 source_commonspace;\n vec4 target_commonspace;\n vec4 source = project_position_to_clipspace(instanceSourcePositions, instanceSourcePositions64Low, vec3(0.), source_commonspace);\n vec4 target = project_position_to_clipspace(instanceTargetPositions, instanceTargetPositions64Low, vec3(0.), target_commonspace);\n\n float widthPixels = instanceWidths * animatedFlowLines.thicknessUnit;\n \n \n // linear interpolation of source & target to pick right coord\n float segmentIndex = positions.x;\n vec4 p = mix(source, target, segmentIndex);\n geometry.position = mix(source_commonspace, target_commonspace, segmentIndex);\n uv = positions.xy;\n geometry.uv = uv;\n if (instancePickable > 0.5) {\n geometry.pickingColor = instancePickingColors;\n }\n \n // extrude\n vec3 offset = vec3(\n getExtrusionOffset(target.xy - source.xy, positions.y, widthPixels),\n 0.0);\n DECKGL_FILTER_SIZE(offset, geometry);\n gl_Position = p + vec4(project_pixel_size_to_clipspace(offset.xy), 0.0, 0.0);\n DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n\n // Color\n vColor = vec4(instanceColors.rgb, instanceColors.a * layer.opacity);\n DECKGL_FILTER_COLOR(vColor, geometry);\n\n sourceToTarget = positions.x * length(source - target) * NUM_PARTS - animatedFlowLines.currentTime * SPEED + instanceStaggering; \n}\n`;\n","import type {ShaderModule} from '@luma.gl/shadertools';\n\nconst uniformBlock = `\\\nlayout(std140) uniform animatedFlowLinesUniforms {\n float thicknessUnit;\n float animationTailLength;\n float currentTime;\n} animatedFlowLines;\n`;\n\nexport type AnimatedFlowLinesProps = {\n thicknessUnit: number;\n animationTailLength: number;\n currentTime: number;\n};\n\nexport const animatedFlowLinesUniforms = {\n name: 'animatedFlowLines',\n vs: uniformBlock,\n fs: uniformBlock,\n uniformTypes: {\n thicknessUnit: 'f32',\n animationTailLength: 'f32',\n currentTime: 'f32',\n },\n} as const satisfies ShaderModule;\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {Layer, picking, project32} from '@deck.gl/core';\nimport {Geometry, Model} from '@luma.gl/engine';\nimport FragmentShader from './AnimatedFlowLinesLayerFragment.glsl';\nimport VertexShader from './AnimatedFlowLinesLayerVertex.glsl';\nimport {FlowLinesLayerAttributes, RGBA} from '@flowmap.gl/data';\nimport {LayerProps} from '../types';\nimport {animatedFlowLinesUniforms} from './AnimatedFlowLinesLayerUniforms';\nexport interface Props extends LayerProps {\n id: string;\n opacity?: number;\n pickable?: boolean;\n updateTriggers?: {[key: string]: Record};\n data: F[] | FlowLinesLayerAttributes;\n drawOutline: boolean;\n outlineColor?: RGBA;\n outlineThickness?: number;\n currentTime?: number;\n thicknessUnit?: number;\n animationTailLength?: number;\n getSourcePosition?: (d: F) => [number, number];\n getTargetPosition?: (d: F) => [number, number];\n getStaggering?: (d: F, info: AccessorObjectInfo) => number;\n getPickable?: (d: F, {index}: {index: number}) => number; // >= 1.0 -> true\n getColor?: (d: F) => RGBA;\n getThickness?: (d: F) => number;\n getEndpointOffsets?: (d: F) => [number, number];\n}\n\n// https://deck.gl/#/documentation/developer-guide/using-layers?section=accessors\nexport interface AccessorObjectInfo {\n index: number;\n data: any;\n target: any;\n}\n\nconst DEFAULT_COLOR: RGBA = [0, 132, 193, 255];\nconst loopLength = 1800;\nconst animationSpeed = 20;\nconst loopTime = loopLength / animationSpeed;\n\nexport default class AnimatedFlowLinesLayer extends Layer {\n state!: {\n model?: Model;\n };\n\n static defaultProps = {\n currentTime: 0,\n animationTailLength: 0.7,\n getSourcePosition: {type: 'accessor', value: (d: any) => [0, 0]},\n getTargetPosition: {type: 'accessor', value: (d: any) => [0, 0]},\n getPickable: {type: 'accessor', value: (d: any) => 1.0},\n getStaggering: {\n type: 'accessor',\n value: (d: any, {index}: {index: number}) => Math.random(),\n },\n getColor: {type: 'accessor', value: DEFAULT_COLOR},\n getThickness: {type: 'accessor', value: 1},\n thicknessUnit: 15 * 2,\n parameters: {\n depthTest: false,\n },\n };\n\n constructor(props: Props) {\n super(props);\n }\n\n getShaders(): Record {\n return super.getShaders({\n vs: VertexShader,\n fs: FragmentShader,\n modules: [project32, picking, animatedFlowLinesUniforms],\n });\n }\n\n initializeState(): void {\n this.getAttributeManager()!.addInstanced({\n instanceSourcePositions: {\n size: 3,\n type: 'float64',\n transition: true,\n accessor: 'getSourcePosition',\n },\n instanceTargetPositions: {\n size: 3,\n type: 'float64',\n transition: true,\n accessor: 'getTargetPosition',\n },\n instanceColors: {\n size: 4,\n type: 'unorm8',\n transition: true,\n accessor: 'getColor',\n defaultValue: [0, 0, 0, 255],\n },\n instanceWidths: {\n size: 1,\n transition: true,\n accessor: 'getThickness',\n defaultValue: 1,\n },\n instanceStaggering: {\n accessor: 'getStaggering',\n size: 1,\n transition: false,\n },\n instancePickable: {\n accessor: 'getPickable',\n size: 1,\n transition: false,\n },\n });\n this.setState({model: this._getModel()});\n }\n\n getNeedsRedraw(): string | false {\n return 'animation';\n }\n\n updateState(params: any): void {\n super.updateState(params);\n const {changeFlags} = params;\n\n if (!this.state.model || changeFlags.extensionsChanged) {\n this.state.model?.destroy();\n this.setState({model: this._getModel()});\n this.getAttributeManager()!.invalidateAll();\n }\n }\n\n draw(): void {\n const {thicknessUnit = 15 * 2, animationTailLength = 0.7} = this\n .props as unknown as Props;\n const timestamp = Date.now() / 1000;\n const animationTime = ((timestamp % loopTime) / loopTime) * loopLength;\n\n const model = this.state.model;\n if (!model) {\n return;\n }\n model.shaderInputs.setProps({\n animatedFlowLines: {\n thicknessUnit: thicknessUnit * 4,\n animationTailLength,\n currentTime: animationTime,\n },\n });\n model.draw(this.context.renderPass as any);\n }\n\n _getModel(): Model {\n const {id} = this.props as unknown as Props;\n /*\n * (0, -1)-------------_(1, -1)\n * | _,-\" |\n * o _,-\" o\n * | _,-\" |\n * (0, 1)\"-------------(1, 1)\n */\n const positions = [0, -1, 0, 0, 1, 0, 1, -1, 0, 1, 1, 0];\n\n return new Model(this.context.device as any, {\n ...this.getShaders(),\n id,\n bufferLayout: this.getAttributeManager()!.getBufferLayouts(),\n geometry: new Geometry({\n topology: 'triangle-strip',\n attributes: {\n positions: {size: 3, value: new Float32Array(positions)},\n },\n }),\n isInstanced: true,\n });\n }\n}\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport AnimatedFlowLinesLayer from './AnimatedFlowLinesLayer';\n\nexport default AnimatedFlowLinesLayer;\n","import type {ShaderModule} from '@luma.gl/shadertools';\n\nconst uniformBlock = `\\\nlayout(std140) uniform flowLinesUniforms {\n vec4 outlineColor;\n float thicknessUnit;\n float outlineThickness;\n float drawOutline;\n float gap;\n float curviness;\n} flowLines;\n`;\n\nexport type FlowLinesProps = {\n outlineColor: [number, number, number, number];\n thicknessUnit: number;\n outlineThickness: number;\n drawOutline: number;\n gap: number;\n curviness: number;\n};\n\nexport const flowLinesUniforms = {\n name: 'flowLines',\n vs: uniformBlock,\n fs: uniformBlock,\n uniformTypes: {\n outlineColor: 'vec4',\n thicknessUnit: 'f32',\n outlineThickness: 'f32',\n drawOutline: 'f32',\n gap: 'f32',\n curviness: 'f32',\n },\n} as const satisfies ShaderModule;\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\nexport default `\\\n#version 300 es\n#define SHADER_NAME curved-flow-line-layer-fragment-shader\n\nprecision highp float;\n\nin vec4 vColor;\nin vec2 uv;\nin vec3 vBarycentrics;\nflat in vec3 vEdgeMask;\n\nout vec4 fragColor;\n\nvoid main(void) {\n if (vColor.a == 0.0) {\n discard;\n }\n\n geometry.uv = uv;\n fragColor = vColor;\n\n if (flowLines.drawOutline > 0.5 && !bool(picking.isActive)) {\n vec3 edgeDistancePx = vBarycentrics / max(fwidth(vBarycentrics), vec3(1e-4));\n vec3 maskedDistancePx = mix(vec3(1e6), edgeDistancePx, step(vec3(0.5), vEdgeMask));\n float minBoundaryDistancePx = min(\n maskedDistancePx.x,\n min(maskedDistancePx.y, maskedDistancePx.z)\n );\n float outlineMix = 1.0 - smoothstep(\n max(flowLines.outlineThickness - 1.0, 0.0),\n flowLines.outlineThickness,\n minBoundaryDistancePx\n );\n fragColor = mix(\n fragColor,\n vec4(flowLines.outlineColor.rgb, flowLines.outlineColor.a * fragColor.a),\n outlineMix\n );\n }\n\n DECKGL_FILTER_COLOR(fragColor, geometry);\n}\n`;\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\nconst HEAD_START_T = (1 - 1 / 24).toFixed(8);\n\nexport default `\\\n#version 300 es\n#define SHADER_NAME curved-flow-line-layer-vertex-shader\n\nin vec3 positions;\nin vec3 barycentrics;\nin vec3 edgeMasks;\nin vec4 instanceColors;\nin float instanceThickness;\nin vec3 instanceSourcePositions;\nin vec3 instanceTargetPositions;\nin vec3 instanceSourcePositions64Low;\nin vec3 instanceTargetPositions64Low;\nin vec3 instancePickingColors;\nin vec2 instanceEndpointOffsets;\nin float instancePickable;\nin float instanceCurveOffset;\n\nout vec4 vColor;\nout vec2 uv;\nout vec3 vBarycentrics;\nflat out vec3 vEdgeMask;\n\nvec3 quadraticBezier(vec3 p0, vec3 p1, vec3 p2, float t) {\n float oneMinusT = 1.0 - t;\n return\n oneMinusT * oneMinusT * p0 +\n 2.0 * oneMinusT * t * p1 +\n t * t * p2;\n}\n\nvec3 quadraticBezierTangent(vec3 p0, vec3 p1, vec3 p2, float t) {\n return 2.0 * (1.0 - t) * (p1 - p0) + 2.0 * t * (p2 - p1);\n}\n\nvoid main(void) {\n geometry.worldPosition = instanceSourcePositions;\n geometry.worldPositionAlt = instanceTargetPositions;\n\n vec4 source_commonspace;\n vec4 target_commonspace;\n project_position_to_clipspace(\n instanceSourcePositions,\n instanceSourcePositions64Low,\n vec3(0.0),\n source_commonspace\n );\n project_position_to_clipspace(\n instanceTargetPositions,\n instanceTargetPositions64Low,\n vec3(0.0),\n target_commonspace\n );\n\n vec2 chord = target_commonspace.xy - source_commonspace.xy;\n float chordLengthCommon = max(length(chord), 1e-6);\n float startTrim = clamp(\n project_pixel_size(instanceEndpointOffsets.x) / chordLengthCommon,\n 0.0,\n 0.35\n );\n float endTrim = 1.0 - clamp(\n project_pixel_size(instanceEndpointOffsets.y) / chordLengthCommon,\n 0.0,\n 0.35\n );\n endTrim = max(startTrim + 0.05, endTrim);\n float baseHeadBacktrackT = project_pixel_size(\n instanceThickness * 3.0 * flowLines.thicknessUnit\n ) / chordLengthCommon;\n float availableSpanT = max(endTrim - startTrim, 0.0);\n float headBacktrackT = min(baseHeadBacktrackT, availableSpanT * 0.45);\n float headScale = baseHeadBacktrackT > 1e-6\n ? clamp(headBacktrackT / baseHeadBacktrackT, 0.0, 1.0)\n : 1.0;\n // A soft nonlinear fade of the head deformation avoids tiny heads folding\n // into themselves while still allowing them to collapse back toward the strip.\n float headDeformation = smoothstep(0.0, 1.0, headScale);\n float shaftEndTrim = max(startTrim + 0.02, endTrim - headBacktrackT);\n\n float curveT = positions.x < 1.0\n ? mix(startTrim, shaftEndTrim, positions.x / ${HEAD_START_T})\n : endTrim;\n float headWeight = smoothstep(${HEAD_START_T}, 1.0, positions.x);\n float tangentT = mix(curveT, endTrim, headWeight);\n vec2 curveNormal = normalize(vec2(chord.y, -chord.x));\n if (length(curveNormal) < 1e-6) {\n curveNormal = vec2(0.0, 1.0);\n }\n vec3 control_commonspace = mix(\n source_commonspace.xyz,\n target_commonspace.xyz,\n 0.5\n );\n control_commonspace.xy += curveNormal * project_pixel_size(abs(instanceCurveOffset)) * flowLines.curviness;\n\n vec3 curvePoint = quadraticBezier(\n source_commonspace.xyz,\n control_commonspace,\n target_commonspace.xyz,\n curveT\n );\n vec3 tangent = quadraticBezierTangent(\n source_commonspace.xyz,\n control_commonspace,\n target_commonspace.xyz,\n tangentT\n );\n if (length(tangent.xy) < 1e-6) {\n tangent = target_commonspace.xyz - source_commonspace.xyz;\n }\n\n vec2 flowlineDir = normalize(tangent.xy);\n vec2 perpendicularDir = vec2(-flowlineDir.y, flowlineDir.x);\n float widthScale = mix(1.0, headScale, headWeight);\n float lengthScale = mix(1.0, headScale, headWeight);\n float shapeY = mix(min(positions.y, 1.0), positions.y, headDeformation);\n float shapeZ = positions.z * headDeformation;\n float normalDistanceCommon = clamp(\n project_pixel_size(\n instanceThickness * shapeY * widthScale * flowLines.thicknessUnit\n ),\n -chordLengthCommon * 0.8,\n chordLengthCommon * 0.8\n );\n float tangentDistanceCommon = clamp(\n project_pixel_size(\n instanceThickness * shapeZ * lengthScale * flowLines.thicknessUnit\n ),\n -chordLengthCommon * 0.8,\n chordLengthCommon * 0.8\n );\n float gapCommon = project_pixel_size(flowLines.gap);\n vec3 offsetCommon = vec3(\n flowlineDir * tangentDistanceCommon -\n perpendicularDir * (normalDistanceCommon + gapCommon),\n 0.0\n );\n\n geometry.position = vec4(curvePoint, 1.0);\n uv = vec2(curveT, positions.y);\n geometry.uv = uv;\n vBarycentrics = barycentrics;\n vEdgeMask = edgeMasks;\n if (instancePickable > 0.5) {\n geometry.pickingColor = instancePickingColors;\n }\n\n DECKGL_FILTER_SIZE(offsetCommon, geometry);\n vec4 position_commonspace = vec4(curvePoint + offsetCommon, 1.0);\n gl_Position = project_common_position_to_clipspace(position_commonspace);\n DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n\n vec4 fillColor = vec4(instanceColors.rgb, instanceColors.a * layer.opacity);\n vColor = fillColor;\n DECKGL_FILTER_COLOR(vColor, geometry);\n}\n`;\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {Layer, picking, project32} from '@deck.gl/core';\nimport {FlowLinesLayerAttributes, RGBA} from '@flowmap.gl/data';\nimport {Geometry, Model} from '@luma.gl/engine';\nimport {flowLinesUniforms} from '../FlowLinesLayer/FlowLinesLayerUniforms';\nimport {LayerProps} from '../types';\nimport FragmentShader from './CurvedFlowLinesLayerFragment.glsl';\nimport VertexShader from './CurvedFlowLinesLayerVertex.glsl';\n\nexport interface Props extends LayerProps {\n id: string;\n opacity?: number;\n pickable?: boolean;\n updateTriggers?: {[key: string]: Record};\n data: F[] | FlowLinesLayerAttributes;\n drawOutline: boolean;\n outlineColor?: RGBA;\n outlineThickness?: number;\n thicknessUnit?: number;\n getSourcePosition?: (d: F) => [number, number];\n getTargetPosition?: (d: F) => [number, number];\n getColor?: (d: F) => RGBA;\n getThickness?: (d: F) => number;\n getPickable?: (d: F, {index}: {index: number}) => number;\n getEndpointOffsets?: (d: F) => [number, number];\n getCurveOffset?: (d: F) => number;\n curviness?: number;\n}\n\nconst DEFAULT_COLOR: RGBA = [0, 132, 193, 255];\nconst SHAFT_SEGMENTS = 24;\nconst HEAD_START_T = 1 - 1 / SHAFT_SEGMENTS;\n\ntype GeometryBuffers = {\n positions: Float32Array;\n barycentrics: Float32Array;\n edgeMasks: Float32Array;\n};\n\nexport default class CurvedFlowLinesLayer extends Layer {\n static layerName = 'CurvedFlowLinesLayer';\n\n state!: {\n model?: Model;\n };\n\n static defaultProps = {\n getSourcePosition: {type: 'accessor', value: (d: any) => [0, 0]},\n getTargetPosition: {type: 'accessor', value: (d: any) => [0, 0]},\n getColor: {type: 'accessor', value: DEFAULT_COLOR},\n getThickness: {type: 'accessor', value: (d: any) => d.count},\n getPickable: {type: 'accessor', value: () => 1.0},\n getCurveOffset: {type: 'accessor', value: () => 0},\n drawOutline: true,\n thicknessUnit: 12,\n outlineThickness: 1,\n outlineColor: [255, 255, 255, 255],\n curviness: 1,\n parameters: {\n depthTest: false,\n },\n };\n\n getShaders(): Record {\n return super.getShaders({\n vs: VertexShader,\n fs: FragmentShader,\n modules: [project32, picking, flowLinesUniforms],\n });\n }\n\n initializeState(): void {\n this.getAttributeManager()!.addInstanced({\n instanceSourcePositions: {\n accessor: 'getSourcePosition',\n size: 3,\n transition: false,\n type: 'float64',\n },\n instanceTargetPositions: {\n accessor: 'getTargetPosition',\n size: 3,\n transition: false,\n type: 'float64',\n },\n instanceThickness: {\n accessor: 'getThickness',\n size: 1,\n transition: false,\n },\n instanceEndpointOffsets: {\n accessor: 'getEndpointOffsets',\n size: 2,\n transition: false,\n },\n instanceCurveOffset: {\n accessor: 'getCurveOffset',\n size: 1,\n transition: false,\n },\n instanceColors: {\n accessor: 'getColor',\n size: 4,\n type: 'unorm8',\n transition: false,\n },\n instancePickable: {\n accessor: 'getPickable',\n size: 1,\n transition: false,\n },\n });\n this.setState({model: this._getModel()});\n }\n\n updateState(params: any): void {\n super.updateState(params);\n const {changeFlags} = params;\n\n if (!this.state.model || changeFlags.extensionsChanged) {\n this.state.model?.destroy();\n this.setState({model: this._getModel()});\n this.getAttributeManager()!.invalidateAll();\n }\n }\n\n draw(): void {\n const {\n drawOutline = true,\n outlineColor = [255, 255, 255, 255],\n outlineThickness = 1,\n thicknessUnit = 12,\n curviness = 1,\n } = this.props as unknown as Props;\n const model = this.state.model;\n if (!model) {\n return;\n }\n model.shaderInputs.setProps({\n flowLines: {\n outlineColor: outlineColor.map((x: number) => x / 255) as [\n number,\n number,\n number,\n number,\n ],\n thicknessUnit: thicknessUnit * 2.0,\n outlineThickness,\n drawOutline: drawOutline ? 1 : 0,\n gap: 0.5,\n curviness,\n },\n });\n model.draw(this.context.renderPass as any);\n }\n\n _getModel(): Model {\n const {id} = this.props as unknown as Props;\n const geometry = buildGeometry();\n\n return new Model(this.context.device as any, {\n id,\n ...this.getShaders(),\n bufferLayout: this.getAttributeManager()!.getBufferLayouts(),\n geometry: new Geometry({\n topology: 'triangle-list',\n attributes: {\n positions: {size: 3, value: geometry.positions},\n barycentrics: {size: 3, value: geometry.barycentrics},\n edgeMasks: {size: 3, value: geometry.edgeMasks},\n },\n }),\n isInstanced: true,\n });\n }\n}\n\nfunction buildGeometry(): GeometryBuffers {\n const positions: number[] = [];\n const barycentrics: number[] = [];\n const edgeMasks: number[] = [];\n\n const pushTriangle = (\n a: [number, number, number],\n b: [number, number, number],\n c: [number, number, number],\n mask: [number, number, number],\n ) => {\n positions.push(...a, ...b, ...c);\n barycentrics.push(1, 0, 0, 0, 1, 0, 0, 0, 1);\n edgeMasks.push(...mask, ...mask, ...mask);\n };\n\n for (let index = 0; index < SHAFT_SEGMENTS - 1; index++) {\n const t0 = index / SHAFT_SEGMENTS;\n const t1 = (index + 1) / SHAFT_SEGMENTS;\n pushTriangle(\n [t0, 1, 0],\n [t1, 1, 0],\n [t0, 0, 0],\n [0, index === 0 ? 1 : 0, 1],\n );\n pushTriangle([t0, 0, 0], [t1, 1, 0], [t1, 0, 0], [0, 1, 0]);\n }\n\n pushTriangle(\n [HEAD_START_T, 1, 0],\n [1, 1.7, -4.4],\n [HEAD_START_T, 0, 0],\n [0, 0, 1],\n );\n pushTriangle([HEAD_START_T, 0, 0], [1, 1.7, -4.4], [1, 0, 0], [1, 1, 0]);\n\n return {\n positions: new Float32Array(positions),\n barycentrics: new Float32Array(barycentrics),\n edgeMasks: new Float32Array(edgeMasks),\n };\n}\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport CurvedFlowLinesLayer from './CurvedFlowLinesLayer';\n\nexport default CurvedFlowLinesLayer;\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\nexport default `\\\n#version 300 es\n#define SHADER_NAME flow-line-layer-fragment-shader\n\nprecision highp float;\n\nin vec4 vColor;\nin vec2 uv;\nin vec3 vBarycentrics;\nflat in vec3 vEdgeMask;\n\nout vec4 fragColor;\n\nvoid main(void) {\n if (vColor.a == 0.0) {\n discard;\n }\n\n geometry.uv = uv;\n fragColor = vColor;\n\n if (flowLines.drawOutline > 0.5 && !bool(picking.isActive)) {\n // For barycentric coordinates, each component trends to 0 on one triangle edge.\n // Dividing by fwidth converts that into an approximate edge distance in pixels.\n vec3 edgeDistancePx = vBarycentrics / max(fwidth(vBarycentrics), vec3(1e-4));\n // Ignore edges that are only part of the internal triangulation by assigning\n // them a large sentinel distance, so only true boundary edges contribute.\n vec3 maskedDistancePx = mix(vec3(1e6), edgeDistancePx, step(vec3(0.5), vEdgeMask));\n float minBoundaryDistancePx = min(\n maskedDistancePx.x,\n min(maskedDistancePx.y, maskedDistancePx.z)\n );\n // The outline is inset: fragments within 'outlineThickness' pixels of an\n // active boundary edge are mixed toward the outline color.\n float outlineMix = 1.0 - smoothstep(\n max(flowLines.outlineThickness - 1.0, 0.0),\n flowLines.outlineThickness,\n minBoundaryDistancePx\n );\n fragColor = mix(\n fragColor,\n vec4(flowLines.outlineColor.rgb, flowLines.outlineColor.a * fragColor.a),\n outlineMix\n );\n }\n\n DECKGL_FILTER_COLOR(fragColor, geometry);\n}\n`;\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\nexport default `\\\n#version 300 es\n#define SHADER_NAME flow-line-layer-vertex-shader\n\nin vec3 positions;\nin vec2 pixelOffsets;\nin vec2 outlineOffsetCoefficients;\nin vec2 outlineOffsetConstants;\nin vec3 barycentrics;\nin vec3 edgeMasks;\nin vec4 instanceColors;\nin float instanceThickness; // 0..0.5\nin vec3 instanceSourcePositions;\nin vec3 instanceTargetPositions;\nin vec3 instanceSourcePositions64Low;\nin vec3 instanceTargetPositions64Low;\nin vec3 instancePickingColors;\nin vec2 instanceEndpointOffsets;\nin float instancePickable;\n\nout vec4 vColor;\nout vec2 uv;\n// Interpolated barycentric coordinates let the fragment shader measure distance\n// to triangle edges in screen pixels without extra geometry.\nout vec3 vBarycentrics;\n// The edge mask is constant per triangle and tells the fragment shader which\n// barycentric edges are real outline candidates vs internal triangulation seams.\nflat out vec3 vEdgeMask;\n\nvoid main(void) {\n geometry.worldPosition = instanceSourcePositions;\n geometry.worldPositionAlt = instanceTargetPositions;\n \n // Position\n vec4 source_commonspace; \n vec4 target_commonspace;\n project_position_to_clipspace(instanceSourcePositions, instanceSourcePositions64Low, vec3(0.), source_commonspace);\n project_position_to_clipspace(instanceTargetPositions, instanceTargetPositions64Low, vec3(0.), target_commonspace);\n\n // linear interpolation of source & target to pick right coord\n float sourceOrTarget = positions.x;\n geometry.position = mix(source_commonspace, target_commonspace, sourceOrTarget);\n uv = positions.xy;\n geometry.uv = uv;\n vBarycentrics = barycentrics;\n vEdgeMask = edgeMasks;\n if (instancePickable > 0.5) {\n geometry.pickingColor = instancePickingColors;\n }\n \n // set the clamp limits in pixel size \n float lengthCommon = length(target_commonspace - source_commonspace); \n vec2 limitedOffsetDistances = clamp( \n project_pixel_size(positions.yz) * flowLines.thicknessUnit,\n -lengthCommon*.8, lengthCommon*.8\n );\n float startOffsetCommon = project_pixel_size(instanceEndpointOffsets[0]);\n float endOffsetCommon = project_pixel_size(instanceEndpointOffsets[1]);\n float endpointOffset = mix(\n clamp(startOffsetCommon, 0.0, lengthCommon*.2),\n -clamp(endOffsetCommon, 0.0, lengthCommon*.2),\n positions.x\n );\n\n vec2 flowlineDir = normalize(target_commonspace.xy - source_commonspace.xy);\n vec2 perpendicularDir = vec2(-flowlineDir.y, flowlineDir.x);\n vec2 outlinePixelOffset = (\n outlineOffsetCoefficients * flowLines.outlineThickness +\n outlineOffsetConstants\n ) * flowLines.drawOutline;\n vec2 pixelOffsetCommon = project_pixel_size(pixelOffsets + outlinePixelOffset);\n float gapCommon = project_pixel_size(flowLines.gap);\n vec3 offsetCommon = vec3(\n flowlineDir * (instanceThickness * limitedOffsetDistances[1] + pixelOffsetCommon.y + endpointOffset * 1.05) -\n perpendicularDir * (instanceThickness * limitedOffsetDistances[0] + gapCommon + pixelOffsetCommon.x),\n 0.0\n );\n \n DECKGL_FILTER_SIZE(offsetCommon, geometry);\n vec4 position_commonspace = mix(source_commonspace, target_commonspace, sourceOrTarget);\n vec4 offset_commonspace = vec4(offsetCommon, 0.0);\n gl_Position = project_common_position_to_clipspace(position_commonspace + offset_commonspace);\n \n DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n \n vec4 fillColor = vec4(instanceColors.rgb, instanceColors.a * layer.opacity);\n vColor = fillColor;\n DECKGL_FILTER_COLOR(vColor, geometry);\n}\n`;\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {Layer, picking, project32} from '@deck.gl/core';\nimport {FlowLinesLayerAttributes, RGBA} from '@flowmap.gl/data';\nimport {Geometry, Model} from '@luma.gl/engine';\nimport {LayerProps} from '../types';\nimport FragmentShader from './FlowLinesLayerFragment.glsl';\nimport {flowLinesUniforms} from './FlowLinesLayerUniforms';\nimport VertexShader from './FlowLinesLayerVertex.glsl';\n\nexport interface Props extends LayerProps {\n id: string;\n opacity?: number;\n pickable?: boolean;\n updateTriggers?: {[key: string]: Record};\n data: F[] | FlowLinesLayerAttributes;\n drawOutline: boolean;\n outlineColor?: RGBA;\n outlineThickness?: number;\n thicknessUnit?: number;\n getSourcePosition?: (d: F) => [number, number];\n getTargetPosition?: (d: F) => [number, number];\n getColor?: (d: F) => RGBA;\n getThickness?: (d: F) => number;\n getPickable?: (d: F, {index}: {index: number}) => number; // >= 1.0 -> true\n getEndpointOffsets?: (d: F) => [number, number];\n}\n\nconst DEFAULT_COLOR: RGBA = [0, 132, 193, 255];\n\n// source_target_mix, perpendicular_offset_in_thickness_units, direction_of_travel_offset_in_thickness_units\n// prettier-ignore\nconst POSITIONS = [\n 1, 0, 0, // 0\n 1, 2, -3, // 1\n 1, 1, -3, // 2\n\n\n 1, 0, 0, // 0\n 1, 1, -3, // 2\n 0, 1, 0, // 3\n\n\n 1, 0, 0, // 0\n 0, 1, 0, // 3\n 0, 0, 0, // 4\n];\n/**\n 1\n ··\n · ··\n · ··\n 3 2 · ··\n ······························· ··\n · ······· ···· ··\n · ········ ····· ··\n · ··············· ····· ··\n · ········ ········\n · ················\n 4 ························································ 0\n\n */\nconst INNER_SIDE_OUTLINE_THICKNESS = 0.5;\n\n// Base per-vertex pixel offsets for the fill shape.\nconst PIXEL_OFFSETS = new Float32Array(9 * 2);\n\n// Coefficients for the extra per-vertex expansion when outline rendering is enabled.\n// Multiplied by `outlineThickness` in the vertex shader.\n// prettier-ignore\nconst OUTLINE_OFFSET_COEFFICIENTS = new Float32Array([\n 0, 2,\n 2, -1,\n 1, -1,\n\n 0, 2,\n 1, -1,\n 1, -1,\n\n 0, 2,\n 1, -1,\n 0, -1,\n]);\n\n// Constant pixel tweaks applied regardless of outline thickness to keep the\n// leading arrowhead from visually swallowing the opposite edge.\n// prettier-ignore\nconst OUTLINE_OFFSET_CONSTANTS = new Float32Array([\n -INNER_SIDE_OUTLINE_THICKNESS, 0,\n 0, 0,\n 0, 0,\n\n -INNER_SIDE_OUTLINE_THICKNESS, 0,\n 0, 0,\n 0, 0,\n\n -INNER_SIDE_OUTLINE_THICKNESS, 0,\n 0, 0,\n -INNER_SIDE_OUTLINE_THICKNESS, 0,\n]);\n\n// One barycentric basis per triangle. After interpolation in the fragment shader,\n// each component goes to 0 on the edge opposite its vertex, which lets us compute\n// a stable pixel distance to each triangle edge using `fwidth`.\n// prettier-ignore\nconst BARYCENTRICS = new Float32Array([\n 1, 0, 0,\n 0, 1, 0,\n 0, 0, 1,\n\n 1, 0, 0,\n 0, 1, 0,\n 0, 0, 1,\n\n 1, 0, 0,\n 0, 1, 0,\n 0, 0, 1,\n]);\n\n// Each component maps to the edge opposite the matching barycentric component.\n// A value of 1 means \"this is a real polygon boundary edge that may receive the\n// inset outline\"; 0 means \"ignore this edge\" so the fragment shader does not draw\n// seams along the internal triangle splits used to build the arrow shape.\n// prettier-ignore\nconst EDGE_MASKS = new Float32Array([\n 1, 0, 1,\n 1, 0, 1,\n 1, 0, 1,\n\n 1, 0, 0,\n 1, 0, 0,\n 1, 0, 0,\n\n 1, 1, 0,\n 1, 1, 0,\n 1, 1, 0,\n]);\n\nclass FlowLinesLayer extends Layer {\n static layerName = 'FlowLinesLayer';\n\n state!: {\n model?: Model;\n };\n\n static defaultProps = {\n getSourcePosition: {type: 'accessor', value: (d: any) => [0, 0]},\n getTargetPosition: {type: 'accessor', value: (d: any) => [0, 0]},\n getColor: {type: 'accessor', value: DEFAULT_COLOR},\n getThickness: {type: 'accessor', value: (d: any) => d.count}, // 0..0.5\n getPickable: {type: 'accessor', value: (d: any) => 1.0},\n drawOutline: true,\n thicknessUnit: 12,\n outlineThickness: 1,\n outlineColor: [255, 255, 255, 255],\n parameters: {\n depthTest: false,\n },\n };\n // props!: Props;\n\n constructor(props: Props) {\n super(props);\n }\n\n getShaders(): Record {\n return super.getShaders({\n vs: VertexShader,\n fs: FragmentShader,\n modules: [project32, picking, flowLinesUniforms],\n });\n }\n\n initializeState(): void {\n this.getAttributeManager()!.addInstanced({\n instanceSourcePositions: {\n accessor: 'getSourcePosition',\n size: 3,\n transition: false,\n type: 'float64',\n },\n instanceTargetPositions: {\n accessor: 'getTargetPosition',\n size: 3,\n transition: false,\n type: 'float64',\n },\n instanceThickness: {\n accessor: 'getThickness',\n size: 1,\n transition: false,\n },\n instanceEndpointOffsets: {\n accessor: 'getEndpointOffsets',\n size: 2,\n transition: false,\n },\n instanceColors: {\n accessor: 'getColor',\n size: 4,\n type: 'unorm8',\n transition: false,\n },\n instancePickable: {\n accessor: 'getPickable',\n size: 1,\n transition: false,\n },\n });\n this.setState({model: this._getModel()});\n }\n\n updateState(params: any): void {\n super.updateState(params);\n const {changeFlags} = params;\n\n if (!this.state.model || changeFlags.extensionsChanged) {\n this.state.model?.destroy();\n this.setState({model: this._getModel()});\n this.getAttributeManager()!.invalidateAll();\n }\n }\n\n draw(): void {\n const {\n drawOutline = true,\n outlineColor = [255, 255, 255, 255],\n outlineThickness = 1,\n thicknessUnit = 12,\n } = this.props as unknown as Props;\n const model = this.state.model;\n if (!model) {\n return;\n }\n model.shaderInputs.setProps({\n flowLines: {\n outlineColor: outlineColor.map((x: number) => x / 255) as [\n number,\n number,\n number,\n number,\n ],\n thicknessUnit: thicknessUnit * 2.0,\n outlineThickness,\n drawOutline: drawOutline ? 1 : 0,\n gap: 0.5,\n curviness: 1.0,\n },\n });\n model.draw(this.context.renderPass as any);\n }\n\n _getModel(): Model {\n const {id} = this.props as unknown as Props;\n\n return new Model(this.context.device as any, {\n id,\n ...this.getShaders(),\n bufferLayout: this.getAttributeManager()!.getBufferLayouts(),\n geometry: new Geometry({\n topology: 'triangle-list',\n attributes: {\n positions: {size: 3, value: new Float32Array(POSITIONS)},\n pixelOffsets: {size: 2, value: PIXEL_OFFSETS},\n outlineOffsetCoefficients: {\n size: 2,\n value: OUTLINE_OFFSET_COEFFICIENTS,\n },\n outlineOffsetConstants: {\n size: 2,\n value: OUTLINE_OFFSET_CONSTANTS,\n },\n barycentrics: {size: 3, value: BARYCENTRICS},\n edgeMasks: {size: 3, value: EDGE_MASKS},\n },\n }),\n isInstanced: true,\n });\n }\n}\n\nexport default FlowLinesLayer;\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport FlowLinesLayer from './FlowLinesLayer';\n\nexport default FlowLinesLayer;\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\nexport default `\\\n#version 300 es\n#define SHADER_NAME flow-circles-layer-fragment-shader\n#define SOFT_OUTLINE 0.05\n#define EPS 0.05\nprecision highp float;\n\nin vec4 vColor;\nin vec2 unitPosition;\nin float unitInRadius;\nin float unitOutRadius;\n\nout vec4 fragColor;\n\nfloat when_gt(float x, float y) {\n return max(sign(x - y), 0.0);\n}\n\nvoid main(void) {\n geometry.uv = unitPosition;\n float distToCenter = length(unitPosition);\n if (distToCenter > 1.0) {\n discard;\n }\n\n // See https://stackoverflow.com/questions/47285778\n vec4 ringColor = mix(\n flowCircles.emptyColor, vColor,\n when_gt(unitInRadius, unitOutRadius)\n );\n vec4 outlineColor = mix(\n mix(vColor, flowCircles.emptyColor, flowCircles.outlineEmptyMix),\n vColor,\n when_gt(unitInRadius, unitOutRadius)\n );\n \n float innerR = min(unitInRadius, unitOutRadius) * (1.0 - SOFT_OUTLINE);\n \n // Inner circle\n float step2 = innerR - 2.0 * EPS; \n float step3 = innerR - EPS;\n \n // Ring\n float step4 = innerR;\n // float step5 = 1.0 - SOFT_OUTLINE - EPS;\n // float step6 = 1.0 - SOFT_OUTLINE;\n float step5 = 1.0 - 5.0 * EPS;\n float step6 = 1.0;\n \n fragColor = vColor;\n fragColor = mix(fragColor, flowCircles.emptyColor, smoothstep(step2, step3, distToCenter));\n fragColor = mix(fragColor, ringColor, smoothstep(step3, step4, distToCenter));\n fragColor = mix(fragColor, outlineColor, smoothstep(step5, step6, distToCenter));\n fragColor.a = vColor.a;\n fragColor.a *= smoothstep(0.0, SOFT_OUTLINE, 1.0 - distToCenter);\n DECKGL_FILTER_COLOR(fragColor, geometry);\n}\n`;\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\nexport default `\\\n#version 300 es\n#define SHADER_NAME flow-circles-layer-vertex-shader\n#define radiusScale 100\n\nin vec3 positions;\n\nin vec3 instancePositions;\nin vec3 instancePositions64Low;\nin float instanceInRadius;\nin float instanceOutRadius;\nin vec4 instanceColors;\nin vec3 instancePickingColors;\n\nout vec4 vColor;\nout vec2 unitPosition;\nout float unitInRadius;\nout float unitOutRadius;\n\nvoid main(void) {\n geometry.worldPosition = instancePositions;\n\n float outerRadiusPixels = max(instanceInRadius, instanceOutRadius);\n unitInRadius = instanceInRadius / outerRadiusPixels; \n unitOutRadius = instanceOutRadius / outerRadiusPixels; \n\n // position on the containing square in [-1, 1] space\n unitPosition = positions.xy;\n geometry.uv = unitPosition;\n geometry.pickingColor = instancePickingColors;\n \n // Find the center of the point and add the current vertex\n vec3 offset = positions * project_pixel_size(outerRadiusPixels);\n DECKGL_FILTER_SIZE(offset, geometry);\n gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset, geometry.position);\n DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n \n // Apply opacity to instance color, or return instance picking color\n vColor = vec4(instanceColors.rgb, instanceColors.a * layer.opacity);\n DECKGL_FILTER_COLOR(vColor, geometry);\n}\n`;\n","import type {ShaderModule} from '@luma.gl/shadertools';\n\nconst uniformBlock = `\\\nlayout(std140) uniform flowCirclesUniforms {\n vec4 emptyColor;\n float outlineEmptyMix;\n} flowCircles;\n`;\n\nexport type FlowCirclesProps = {\n emptyColor: [number, number, number, number];\n outlineEmptyMix: number;\n};\n\nexport const flowCirclesUniforms = {\n name: 'flowCircles',\n vs: uniformBlock,\n fs: uniformBlock,\n uniformTypes: {\n emptyColor: 'vec4',\n outlineEmptyMix: 'f32',\n },\n} as const satisfies ShaderModule;\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {Layer, picking, project32} from '@deck.gl/core';\nimport {Geometry, Model} from '@luma.gl/engine';\nimport FragmentShader from './FlowCirclesLayerFragment.glsl';\nimport VertexShader from './FlowCirclesLayerVertex.glsl';\nimport {FlowCirclesLayerAttributes, RGBA} from '@flowmap.gl/data';\nimport {LayerProps} from '../types';\nimport {flowCirclesUniforms} from './FlowCirclesLayerUniforms';\n\nexport type FlowCirclesDatum = Record;\n\nexport interface Props extends LayerProps {\n id: string;\n opacity?: number;\n pickable?: boolean;\n emptyColor?: RGBA;\n outlineEmptyMix?: number;\n getColor?: (d: FlowCirclesDatum) => RGBA;\n getPosition?: (d: FlowCirclesDatum) => [number, number];\n getInRadius?: (d: FlowCirclesDatum) => number;\n getOutRadius?: (d: FlowCirclesDatum) => number;\n data: FlowCirclesDatum[] | FlowCirclesLayerAttributes;\n updateTriggers?: {[key: string]: Record};\n}\n\nconst DEFAULT_COLOR = [0, 0, 0, 255];\nconst DEFAULT_EMPTY_COLOR = [255, 255, 255, 255];\nconst DEFAULT_OUTLINE_EMPTY_MIX = 0.4;\n\nclass FlowCirclesLayer extends Layer {\n static layerName = 'FlowCirclesLayer';\n\n state!: {\n model?: Model;\n };\n\n static defaultProps = {\n getColor: {type: 'accessor', value: DEFAULT_COLOR},\n emptyColor: {type: 'accessor', value: DEFAULT_EMPTY_COLOR},\n outlineEmptyMix: {type: 'accessor', value: DEFAULT_OUTLINE_EMPTY_MIX},\n getPosition: {type: 'accessor', value: (d: FlowCirclesDatum) => d.position},\n getInRadius: {type: 'accessor', value: 1},\n getOutRadius: {type: 'accessor', value: 1},\n parameters: {\n depthTest: false,\n },\n };\n // props!: Props;\n\n constructor(props: Props) {\n super(props);\n }\n\n getShaders() {\n return super.getShaders({\n vs: VertexShader,\n fs: FragmentShader,\n modules: [project32, picking, flowCirclesUniforms],\n });\n }\n\n initializeState() {\n this.getAttributeManager()!.addInstanced({\n instancePositions: {\n size: 3,\n type: 'float64',\n fp64: this.use64bitPositions(),\n transition: true,\n accessor: 'getPosition',\n },\n instanceInRadius: {\n size: 1,\n transition: true,\n accessor: 'getInRadius',\n defaultValue: 1,\n },\n instanceOutRadius: {\n size: 1,\n transition: true,\n accessor: 'getOutRadius',\n defaultValue: 1,\n },\n instanceColors: {\n size: 4,\n transition: true,\n type: 'unorm8',\n accessor: 'getColor',\n defaultValue: DEFAULT_COLOR,\n },\n });\n this.setState({model: this._getModel()});\n }\n\n updateState(params: any) {\n super.updateState(params);\n const {changeFlags} = params;\n if (!this.state.model || changeFlags.extensionsChanged) {\n this.state.model?.destroy();\n this.setState({model: this._getModel()});\n this.getAttributeManager()!.invalidateAll();\n }\n }\n\n draw() {\n const {\n emptyColor = DEFAULT_EMPTY_COLOR,\n outlineEmptyMix = DEFAULT_OUTLINE_EMPTY_MIX,\n } = this.props as unknown as Props;\n const model = this.state.model;\n if (!model) {\n return;\n }\n model.shaderInputs.setProps({\n flowCircles: {\n emptyColor: emptyColor.map((x: number) => x / 255) as [\n number,\n number,\n number,\n number,\n ],\n outlineEmptyMix,\n },\n });\n model.draw(this.context.renderPass as any);\n }\n\n _getModel(): Model {\n const {id} = this.props as unknown as Props;\n // a square that minimally cover the unit circle\n const positions = [-1, -1, 0, 1, -1, 0, -1, 1, 0, 1, 1, 0];\n\n return new Model(this.context.device as any, {\n ...this.getShaders(),\n id,\n bufferLayout: this.getAttributeManager()!.getBufferLayouts(),\n geometry: new Geometry({\n topology: 'triangle-strip',\n attributes: {\n positions: {size: 3, value: new Float32Array(positions)},\n },\n }),\n isInstanced: true,\n });\n }\n}\n\nexport default FlowCirclesLayer;\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport FlowCirclesLayer from './FlowCirclesLayer';\n\nexport default FlowCirclesLayer;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ShaderModule} from '@luma.gl/shadertools';\nimport {Texture} from '@luma.gl/core';\n\nconst uniformBlock = `\\\nlayout(std140) uniform iconUniforms {\n float sizeScale;\n vec2 iconsTextureDim;\n float sizeBasis;\n float sizeMinPixels;\n float sizeMaxPixels;\n bool billboard;\n highp int sizeUnits;\n float alphaCutoff;\n} icon;\n`;\n\ntype IconBindingProps = {\n iconsTexture: Texture;\n};\n\ntype IconUniformProps = {\n sizeScale: number;\n iconsTextureDim: [number, number];\n sizeBasis: number;\n sizeMinPixels: number;\n sizeMaxPixels: number;\n billboard: boolean;\n sizeUnits: number;\n alphaCutoff: number;\n};\n\nexport type IconProps = IconBindingProps & IconUniformProps;\n\nexport const iconUniforms = {\n name: 'icon',\n vs: uniformBlock,\n fs: uniformBlock,\n uniformTypes: {\n sizeScale: 'f32',\n iconsTextureDim: 'vec2',\n sizeBasis: 'f32',\n sizeMinPixels: 'f32',\n sizeMaxPixels: 'f32',\n billboard: 'f32',\n sizeUnits: 'i32',\n alphaCutoff: 'f32'\n }\n} as const satisfies ShaderModule;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport default `\\\n#version 300 es\n#define SHADER_NAME icon-layer-vertex-shader\n\nin vec2 positions;\n\nin vec3 instancePositions;\nin vec3 instancePositions64Low;\nin float instanceSizes;\nin float instanceAngles;\nin vec4 instanceColors;\nin vec3 instancePickingColors;\nin vec4 instanceIconFrames;\nin float instanceColorModes;\nin vec2 instanceOffsets;\nin vec2 instancePixelOffset;\n\nout float vColorMode;\nout vec4 vColor;\nout vec2 vTextureCoords;\nout vec2 uv;\n\nvec2 rotate_by_angle(vec2 vertex, float angle) {\n float angle_radian = angle * PI / 180.0;\n float cos_angle = cos(angle_radian);\n float sin_angle = sin(angle_radian);\n mat2 rotationMatrix = mat2(cos_angle, -sin_angle, sin_angle, cos_angle);\n return rotationMatrix * vertex;\n}\n\nvoid main(void) {\n geometry.worldPosition = instancePositions;\n geometry.uv = positions;\n geometry.pickingColor = instancePickingColors;\n uv = positions;\n\n vec2 iconSize = instanceIconFrames.zw;\n // convert size in meters to pixels, then scaled and clamp\n \n // project meters to pixels and clamp to limits \n float sizePixels = clamp(\n project_size_to_pixel(instanceSizes * icon.sizeScale, icon.sizeUnits),\n icon.sizeMinPixels, icon.sizeMaxPixels\n );\n\n // Choose correct constraint based on the 'sizeBasis' value (0.0 = width, 1.0 = height)\n float iconConstraint = icon.sizeBasis == 0.0 ? iconSize.x : iconSize.y;\n float instanceScale = iconConstraint == 0.0 ? 0.0 : sizePixels / iconConstraint;\n\n // scale and rotate vertex in \"pixel\" value and convert back to fraction in clipspace\n vec2 pixelOffset = positions / 2.0 * iconSize + instanceOffsets;\n pixelOffset = rotate_by_angle(pixelOffset, instanceAngles) * instanceScale;\n pixelOffset += instancePixelOffset;\n pixelOffset.y *= -1.0;\n\n if (icon.billboard) {\n gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0), geometry.position);\n DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n vec3 offset = vec3(pixelOffset, 0.0);\n DECKGL_FILTER_SIZE(offset, geometry);\n gl_Position.xy += project_pixel_size_to_clipspace(offset.xy);\n } else {\n vec3 offset_common = vec3(project_pixel_size(pixelOffset), 0.0);\n DECKGL_FILTER_SIZE(offset_common, geometry);\n gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset_common, geometry.position); \n DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n }\n\n vTextureCoords = mix(\n instanceIconFrames.xy,\n instanceIconFrames.xy + iconSize,\n (positions.xy + 1.0) / 2.0\n ) / icon.iconsTextureDim;\n\n vColor = instanceColors;\n DECKGL_FILTER_COLOR(vColor, geometry);\n\n vColorMode = instanceColorModes;\n}\n`;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport default `\\\n#version 300 es\n#define SHADER_NAME icon-layer-fragment-shader\n\nprecision highp float;\n\nuniform sampler2D iconsTexture;\n\nin float vColorMode;\nin vec4 vColor;\nin vec2 vTextureCoords;\nin vec2 uv;\n\nout vec4 fragColor;\n\nvoid main(void) {\n geometry.uv = uv;\n\n vec4 texColor = texture(iconsTexture, vTextureCoords);\n\n // if colorMode == 0, use pixel color from the texture\n // if colorMode == 1 or rendering picking buffer, use texture as transparency mask\n vec3 color = mix(texColor.rgb, vColor.rgb, vColorMode);\n // Take the global opacity and the alpha from vColor into account for the alpha component\n float a = texColor.a * layer.opacity * vColor.a;\n\n if (a < icon.alphaCutoff) {\n discard;\n }\n\n fragColor = vec4(color, a);\n DECKGL_FILTER_COLOR(fragColor, geometry);\n}\n`;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport const shaderWGSL = /* wgsl */ `\\\nstruct IconUniforms {\n sizeScale: f32,\n iconsTextureDim: vec2,\n sizeBasis: f32,\n sizeMinPixels: f32,\n sizeMaxPixels: f32,\n billboard: i32,\n sizeUnits: i32,\n alphaCutoff: f32\n};\n\n@group(0) @binding(auto) var icon: IconUniforms;\n@group(0) @binding(auto) var iconsTexture : texture_2d;\n@group(0) @binding(auto) var iconsTextureSampler : sampler;\n\nfn rotate_by_angle(vertex: vec2, angle_deg: f32) -> vec2 {\n let angle_radian = angle_deg * PI / 180.0;\n let c = cos(angle_radian);\n let s = sin(angle_radian);\n let rotation = mat2x2(vec2(c, s), vec2(-s, c));\n return rotation * vertex;\n}\n\nstruct Attributes {\n @location(0) positions: vec2,\n\n @location(1) instancePositions: vec3,\n @location(2) instancePositions64Low: vec3,\n @location(3) instanceSizes: f32,\n @location(4) instanceAngles: f32,\n @location(5) instanceColors: vec4,\n @location(6) instancePickingColors: vec3,\n @location(7) instanceIconFrames: vec4,\n @location(8) instanceColorModes: f32,\n @location(9) instanceOffsets: vec2,\n @location(10) instancePixelOffset: vec2,\n};\n\nstruct Varyings {\n @builtin(position) position: vec4,\n\n @location(0) vColorMode: f32,\n @location(1) vColor: vec4,\n @location(2) vTextureCoords: vec2,\n @location(3) uv: vec2,\n @location(4) pickingColor: vec3,\n};\n\n@vertex\nfn vertexMain(inp: Attributes) -> Varyings {\n // write geometry fields used by filters + FS\n geometry.worldPosition = inp.instancePositions;\n geometry.uv = inp.positions;\n geometry.pickingColor = inp.instancePickingColors;\n\n var outp: Varyings;\n outp.uv = inp.positions;\n\n let iconSize = inp.instanceIconFrames.zw;\n\n // convert size in meters to pixels, then clamp\n let sizePixels = clamp(\n project_unit_size_to_pixel(inp.instanceSizes * icon.sizeScale, icon.sizeUnits),\n icon.sizeMinPixels, icon.sizeMaxPixels\n );\n\n // scale icon height to match instanceSize\n let iconConstraint = select(iconSize.y, iconSize.x, icon.sizeBasis == 0.0);\n let instanceScale = select(sizePixels / iconConstraint, 0.0, iconConstraint == 0.0);\n\n // scale and rotate vertex in \"pixel\" units; then add per-instance pixel offset\n var pixelOffset = inp.positions / 2.0 * iconSize + inp.instanceOffsets;\n pixelOffset = rotate_by_angle(pixelOffset, inp.instanceAngles) * instanceScale;\n pixelOffset = pixelOffset + inp.instancePixelOffset;\n pixelOffset.y = pixelOffset.y * -1.0;\n\n if (icon.billboard != 0) {\n var pos = project_position_to_clipspace(inp.instancePositions, inp.instancePositions64Low, vec3(0.0)); // TODO, &geometry.position);\n // DECKGL_FILTER_GL_POSITION(pos, geometry);\n\n var offset = vec3(pixelOffset, 0.0);\n // DECKGL_FILTER_SIZE(offset, geometry);\n let clipOffset = project_pixel_size_to_clipspace(offset.xy);\n pos = vec4(pos.x + clipOffset.x, pos.y + clipOffset.y, pos.z, pos.w);\n outp.position = pos;\n } else {\n var offset_common = vec3(project_pixel_size_vec2(pixelOffset), 0.0);\n // DECKGL_FILTER_SIZE(offset_common, geometry);\n var pos = project_position_to_clipspace(inp.instancePositions, inp.instancePositions64Low, offset_common); // TODO, &geometry.position);\n // DECKGL_FILTER_GL_POSITION(pos, geometry);\n outp.position = pos;\n }\n\n let uvMix = (inp.positions.xy + vec2(1.0, 1.0)) * 0.5;\n outp.vTextureCoords = mix(inp.instanceIconFrames.xy, inp.instanceIconFrames.xy + iconSize, uvMix) / icon.iconsTextureDim;\n\n outp.vColor = inp.instanceColors;\n // DECKGL_FILTER_COLOR(outp.vColor, geometry);\n\n outp.vColorMode = inp.instanceColorModes;\n outp.pickingColor = inp.instancePickingColors;\n\n return outp;\n}\n\n@fragment\nfn fragmentMain(inp: Varyings) -> @location(0) vec4 {\n // expose to deck.gl filter hooks\n geometry.uv = inp.uv;\n\n let texColor = textureSample(iconsTexture, iconsTextureSampler, inp.vTextureCoords);\n\n // if colorMode == 0, use pixel color from the texture\n // if colorMode == 1 (or picking), use texture as transparency mask\n let rgb = mix(texColor.rgb, inp.vColor.rgb, inp.vColorMode);\n let a = texColor.a * layer.opacity * inp.vColor.a;\n\n if (a < icon.alphaCutoff) {\n discard;\n }\n\n if (picking.isActive > 0.5) {\n if (!picking_isColorValid(inp.pickingColor)) {\n discard;\n }\n return vec4(inp.pickingColor, 1.0);\n }\n\n var fragColor = deckgl_premultiplied_alpha(vec4(rgb, a));\n\n if (picking.isHighlightActive > 0.5) {\n let highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor);\n if (picking_isColorZero(abs(inp.pickingColor - highlightedObjectColor))) {\n let highLightAlpha = picking.highlightColor.a;\n let blendedAlpha = highLightAlpha + fragColor.a * (1.0 - highLightAlpha);\n if (blendedAlpha > 0.0) {\n let highLightRatio = highLightAlpha / blendedAlpha;\n fragColor = vec4(\n mix(fragColor.rgb, picking.highlightColor.rgb, highLightRatio),\n blendedAlpha\n );\n } else {\n fragColor = vec4(fragColor.rgb, 0.0);\n }\n }\n }\n\n return fragColor;\n}\n`;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/* global document */\nimport {Device, Texture, SamplerProps} from '@luma.gl/core';\nimport {AsyncTexture} from '@luma.gl/engine';\nimport {load} from '@loaders.gl/core';\nimport {createIterable} from '@deck.gl/core';\n\nimport type {AccessorFunction} from '@deck.gl/core';\n\nconst DEFAULT_CANVAS_WIDTH = 1024;\nconst DEFAULT_BUFFER = 4;\n\nconst noop = () => {};\n\nconst DEFAULT_SAMPLER_PARAMETERS: SamplerProps = {\n minFilter: 'linear',\n mipmapFilter: 'linear',\n // LINEAR is the default value but explicitly set it here\n magFilter: 'linear',\n // minimize texture boundary artifacts\n addressModeU: 'clamp-to-edge',\n addressModeV: 'clamp-to-edge'\n};\n\ntype IconDef = {\n /** Width of the icon */\n width: number;\n /** Height of the icon */\n height: number;\n /** Horizontal position of icon anchor. Default: half width. */\n anchorX?: number;\n /** Vertical position of icon anchor. Default: half height. */\n anchorY?: number;\n /**\n * Whether the icon is treated as a transparency mask.\n * If `true`, color defined by `getColor` is applied.\n * If `false`, pixel color from the icon image is applied.\n * @default false\n */\n mask?: boolean;\n};\n\nexport type UnpackedIcon = {\n /** Url to fetch the icon */\n url: string;\n /** Unique identifier of the icon. Icons of the same id are only fetched once. Fallback to `url` if not specified. */\n id?: string;\n} & IconDef;\n\ntype PrepackedIcon = {\n /** Left position of the icon on the atlas */\n x: number;\n /** Top position of the icon on the atlas */\n y: number;\n} & IconDef;\n\nconst MISSING_ICON: PrepackedIcon = {\n x: 0,\n y: 0,\n width: 0,\n height: 0\n};\n\nexport type IconMapping = Record;\n\nexport type LoadIconErrorContext = {\n error: Error;\n /** The URL that was trying to fetch */\n url: string;\n /** The original data object that requested this icon */\n source: any;\n /** The index of the original data object that requested this icon */\n sourceIndex: number;\n /** The load options used for the fetch */\n loadOptions: any;\n};\n\nfunction nextPowOfTwo(number: number): number {\n return Math.pow(2, Math.ceil(Math.log2(number)));\n}\n\n// update comment to create a new texture and copy original data.\nfunction resizeImage(\n ctx: CanvasRenderingContext2D,\n imageData: HTMLImageElement | ImageBitmap,\n maxWidth: number,\n maxHeight: number\n): {\n image: HTMLImageElement | HTMLCanvasElement | ImageBitmap;\n width: number;\n height: number;\n} {\n const resizeRatio = Math.min(maxWidth / imageData.width, maxHeight / imageData.height);\n const width = Math.floor(imageData.width * resizeRatio);\n const height = Math.floor(imageData.height * resizeRatio);\n\n if (resizeRatio === 1) {\n // No resizing required\n return {image: imageData, width, height};\n }\n\n ctx.canvas.height = height;\n ctx.canvas.width = width;\n\n ctx.clearRect(0, 0, width, height);\n\n // image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight\n ctx.drawImage(imageData, 0, 0, imageData.width, imageData.height, 0, 0, width, height);\n return {image: ctx.canvas, width, height};\n}\n\nfunction getIconId(icon: UnpackedIcon): string {\n return icon && (icon.id || icon.url);\n}\n\nfunction regenerateMipmaps(texture: Texture) {\n const {device} = texture;\n if (device.type === 'webgl') {\n texture.generateMipmapsWebGL();\n } else if (device.type === 'webgpu') {\n device.generateMipmapsWebGPU(texture);\n }\n}\n\n// resize texture without losing original data\nfunction resizeTexture(\n texture: Texture,\n width: number,\n height: number,\n sampler: SamplerProps\n): Texture {\n const {width: oldWidth, height: oldHeight, device} = texture;\n\n const newTexture = device.createTexture({\n format: 'rgba8unorm',\n width,\n height,\n sampler,\n mipLevels: device.getMipLevelCount(width, height)\n });\n\n const commandEncoder = device.createCommandEncoder();\n commandEncoder.copyTextureToTexture({\n sourceTexture: texture,\n destinationTexture: newTexture,\n width: oldWidth,\n height: oldHeight\n });\n const commandBuffer = commandEncoder.finish();\n device.submit(commandBuffer);\n regenerateMipmaps(newTexture);\n\n texture.destroy();\n return newTexture;\n}\n\n// traverse icons in a row of icon atlas\n// extend each icon with left-top coordinates\nfunction buildRowMapping(\n mapping: IconMapping,\n columns: {\n icon: UnpackedIcon;\n xOffset: number;\n }[],\n yOffset: number\n): void {\n for (let i = 0; i < columns.length; i++) {\n const {icon, xOffset} = columns[i];\n const id = getIconId(icon);\n mapping[id] = {\n ...icon,\n x: xOffset,\n y: yOffset\n };\n }\n}\n\n/**\n * Generate coordinate mapping to retrieve icon left-top position from an icon atlas\n */\nexport function buildMapping({\n icons,\n buffer,\n mapping = {},\n xOffset = 0,\n yOffset = 0,\n rowHeight = 0,\n canvasWidth\n}: {\n /** list of icon definitions */\n icons: UnpackedIcon[];\n /** add bleeding buffer to the right and bottom side of the image */\n buffer: number;\n /** right position of last icon in old mapping */\n xOffset: number;\n /** top position in last icon in old mapping */\n yOffset: number;\n /** height of the last icon's row */\n rowHeight: number;\n /** max width of canvas */\n canvasWidth: number;\n mapping: IconMapping;\n}): {\n mapping: IconMapping;\n rowHeight: number;\n xOffset: number;\n yOffset: number;\n canvasWidth: number;\n canvasHeight: number;\n} {\n let columns: {\n icon: UnpackedIcon;\n xOffset: number;\n }[] = [];\n // Strategy to layout all the icons into a texture:\n // traverse the icons sequentially, layout the icons from left to right, top to bottom\n // when the sum of the icons width is equal or larger than canvasWidth,\n // move to next row starting from total height so far plus max height of the icons in previous row\n // row width is equal to canvasWidth\n // row height is decided by the max height of the icons in that row\n // mapping coordinates of each icon is its left-top position in the texture\n for (let i = 0; i < icons.length; i++) {\n const icon = icons[i];\n const id = getIconId(icon);\n\n if (!mapping[id]) {\n const {height, width} = icon;\n\n // fill one row\n if (xOffset + width + buffer > canvasWidth) {\n buildRowMapping(mapping, columns, yOffset);\n\n xOffset = 0;\n yOffset = rowHeight + yOffset + buffer;\n rowHeight = 0;\n columns = [];\n }\n\n columns.push({\n icon,\n xOffset\n });\n\n xOffset = xOffset + width + buffer;\n rowHeight = Math.max(rowHeight, height);\n }\n }\n\n if (columns.length > 0) {\n buildRowMapping(mapping, columns, yOffset);\n }\n\n return {\n mapping,\n rowHeight,\n xOffset,\n yOffset,\n canvasWidth,\n canvasHeight: nextPowOfTwo(rowHeight + yOffset + buffer)\n };\n}\n\n// extract icons from data\n// return icons should be unique, and not cached or cached but url changed\nexport function getDiffIcons(\n data: any,\n getIcon: AccessorFunction | null,\n cachedIcons: Record\n): Record<\n string,\n UnpackedIcon & {\n source: any;\n sourceIndex: number;\n }\n> | null {\n if (!data || !getIcon) {\n return null;\n }\n\n cachedIcons = cachedIcons || {};\n const icons = {};\n const {iterable, objectInfo} = createIterable(data);\n for (const object of iterable) {\n objectInfo.index++;\n const icon = getIcon(object, objectInfo);\n const id = getIconId(icon);\n\n if (!icon) {\n throw new Error('Icon is missing.');\n }\n\n if (!icon.url) {\n throw new Error('Icon url is missing.');\n }\n\n if (!icons[id] && (!cachedIcons[id] || icon.url !== cachedIcons[id].url)) {\n icons[id] = {...icon, source: object, sourceIndex: objectInfo.index};\n }\n }\n return icons;\n}\n\nexport default class IconManager {\n device: Device;\n\n private onUpdate: (didFrameChange: boolean) => void;\n private onError: (context: LoadIconErrorContext) => void;\n private _loadOptions: any = null;\n private _texture: Texture | null = null;\n private _externalTexture: Texture | null = null;\n private _mapping: IconMapping = {};\n private _samplerParameters: SamplerProps | null = null;\n\n /** count of pending requests to fetch icons */\n private _pendingCount: number = 0;\n\n private _autoPacking: boolean = false;\n\n // / internal state used for autoPacking\n\n private _xOffset: number = 0;\n private _yOffset: number = 0;\n private _rowHeight: number = 0;\n private _buffer: number = DEFAULT_BUFFER;\n private _canvasWidth: number = DEFAULT_CANVAS_WIDTH;\n private _canvasHeight: number = 0;\n private _canvas: HTMLCanvasElement | null = null;\n\n constructor(\n device: Device,\n {\n onUpdate = noop,\n onError = noop\n }: {\n /** Callback when the texture updates */\n onUpdate: (didFrameChange: boolean) => void;\n /** Callback when an error is encountered */\n onError: (context: LoadIconErrorContext) => void;\n }\n ) {\n this.device = device;\n this.onUpdate = onUpdate;\n this.onError = onError;\n }\n\n finalize(): void {\n this._texture?.delete();\n }\n\n getTexture(): Texture | null {\n return this._texture || this._externalTexture;\n }\n\n getIconMapping(icon: string | UnpackedIcon): PrepackedIcon {\n const id = this._autoPacking ? getIconId(icon as UnpackedIcon) : (icon as string);\n return this._mapping[id] || MISSING_ICON;\n }\n\n setProps({\n loadOptions,\n autoPacking,\n iconAtlas,\n iconMapping,\n textureParameters\n }: {\n loadOptions?: any;\n autoPacking?: boolean;\n iconAtlas?: Texture | null;\n iconMapping?: IconMapping | null;\n textureParameters?: SamplerProps | null;\n }) {\n if (loadOptions) {\n this._loadOptions = loadOptions;\n }\n\n if (autoPacking !== undefined) {\n this._autoPacking = autoPacking;\n }\n\n if (iconMapping) {\n this._mapping = iconMapping;\n }\n\n if (iconAtlas) {\n this._texture?.delete();\n this._texture = null;\n this._externalTexture = iconAtlas;\n }\n\n if (textureParameters) {\n this._samplerParameters = textureParameters;\n }\n }\n\n get isLoaded(): boolean {\n return this._pendingCount === 0;\n }\n\n packIcons(data: any, getIcon: AccessorFunction): void {\n if (!this._autoPacking || typeof document === 'undefined') {\n return;\n }\n\n const icons = Object.values(getDiffIcons(data, getIcon, this._mapping) || {});\n\n if (icons.length > 0) {\n // generate icon mapping\n const {mapping, xOffset, yOffset, rowHeight, canvasHeight} = buildMapping({\n icons,\n buffer: this._buffer,\n canvasWidth: this._canvasWidth,\n mapping: this._mapping,\n rowHeight: this._rowHeight,\n xOffset: this._xOffset,\n yOffset: this._yOffset\n });\n\n this._rowHeight = rowHeight;\n this._mapping = mapping;\n this._xOffset = xOffset;\n this._yOffset = yOffset;\n this._canvasHeight = canvasHeight;\n\n // create new texture\n if (!this._texture) {\n this._texture = this.device.createTexture({\n format: 'rgba8unorm',\n data: null,\n width: this._canvasWidth,\n height: this._canvasHeight,\n sampler: this._samplerParameters || DEFAULT_SAMPLER_PARAMETERS,\n mipLevels: this.device.getMipLevelCount(this._canvasWidth, this._canvasHeight)\n });\n }\n\n if (this._texture.height !== this._canvasHeight) {\n this._texture = resizeTexture(\n this._texture,\n this._canvasWidth,\n this._canvasHeight,\n this._samplerParameters || DEFAULT_SAMPLER_PARAMETERS\n );\n }\n\n this.onUpdate(true);\n\n // load images\n this._canvas = this._canvas || document.createElement('canvas');\n this._loadIcons(icons);\n }\n }\n\n private _loadIcons(\n icons: (UnpackedIcon & {\n source: any;\n sourceIndex: number;\n })[]\n ): void {\n // This method is only called in the auto packing case, where _canvas is defined\n const ctx = this._canvas!.getContext('2d', {\n willReadFrequently: true\n }) as CanvasRenderingContext2D;\n\n for (const icon of icons) {\n this._pendingCount++;\n load(icon.url, this._loadOptions)\n .then(imageData => {\n const id = getIconId(icon);\n\n const iconDef = this._mapping[id];\n const {x: initialX, y: initialY, width: maxWidth, height: maxHeight} = iconDef;\n\n const {image, width, height} = resizeImage(\n ctx,\n imageData as ImageBitmap,\n maxWidth,\n maxHeight\n );\n\n const x = initialX + (maxWidth - width) / 2;\n const y = initialY + (maxHeight - height) / 2;\n\n this._texture?.copyExternalImage({\n image,\n x,\n y,\n width,\n height\n });\n iconDef.x = x;\n iconDef.y = y;\n iconDef.width = width;\n iconDef.height = height;\n\n // Call to regenerate mipmaps after modifying texture(s)\n if (this._texture) {\n regenerateMipmaps(this._texture);\n }\n\n this.onUpdate(width !== maxWidth || height !== maxHeight);\n })\n .catch(error => {\n this.onError({\n url: icon.url,\n source: icon.source,\n sourceIndex: icon.sourceIndex,\n loadOptions: this._loadOptions,\n error\n });\n })\n .finally(() => {\n this._pendingCount--;\n });\n }\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Layer, color, project32, picking, log, UNIT} from '@deck.gl/core';\nimport {SamplerProps, Texture} from '@luma.gl/core';\nimport {Model, Geometry} from '@luma.gl/engine';\n\nimport {iconUniforms, IconProps} from './icon-layer-uniforms';\nimport vs from './icon-layer-vertex.glsl';\nimport fs from './icon-layer-fragment.glsl';\nimport {shaderWGSL as source} from './icon-layer.wgsl';\nimport IconManager from './icon-manager';\n\nimport type {\n LayerProps,\n LayerDataSource,\n Accessor,\n AccessorFunction,\n Position,\n Color,\n Unit,\n UpdateParameters,\n LayerContext,\n DefaultProps\n} from '@deck.gl/core';\n\nimport type {UnpackedIcon, IconMapping, LoadIconErrorContext} from './icon-manager';\n\ntype _IconLayerProps = {\n data: LayerDataSource;\n /** A prepacked image that contains all icons. */\n iconAtlas?: string | Texture;\n /** Icon names mapped to icon definitions, or a URL to load such mapping from a JSON file. */\n iconMapping?: string | IconMapping;\n\n /** Icon size multiplier.\n * @default 1\n */\n sizeScale?: number;\n /**\n * The units of the icon size, one of `meters`, `common`, and `pixels`.\n *\n * @default 'pixels'\n */\n sizeUnits?: Unit;\n /**\n * The dimension to scale the image\n */\n sizeBasis?: 'height' | 'width';\n /**\n * The minimum size in pixels. When using non-pixel `sizeUnits`, this prop can be used to prevent the icon from getting too small when zoomed out.\n */\n sizeMinPixels?: number;\n /**\n * The maximum size in pixels. When using non-pixel `sizeUnits`, this prop can be used to prevent the icon from getting too big when zoomed in.\n */\n sizeMaxPixels?: number;\n /** If `true`, the icon always faces camera. Otherwise the icon faces up (z)\n * @default true\n */\n billboard?: boolean;\n /**\n * Discard pixels whose opacity is below this threshold.\n * A discarded pixel would create a \"hole\" in the icon that is not considered part of the object.\n * @default 0.05\n */\n alphaCutoff?: number;\n\n /** Anchor position accessor. */\n getPosition?: Accessor;\n /** Icon definition accessor.\n * Should return the icon id if using pre-packed icons (`iconAtlas` + `iconMapping`).\n * Return an object that defines the icon if using auto-packing.\n */\n getIcon?: AccessorFunction | AccessorFunction;\n /** Icon color accessor.\n * @default [0, 0, 0, 255]\n */\n getColor?: Accessor;\n /** Icon size accessor.\n * @default 1\n */\n getSize?: Accessor;\n /** Icon rotation accessor, in degrees.\n * @default 0\n */\n getAngle?: Accessor;\n /**\n * Icon offsest accessor, in pixels.\n * @default [0, 0]\n */\n getPixelOffset?: Accessor>;\n /**\n * Callback called if the attempt to fetch an icon returned by `getIcon` fails.\n */\n onIconError?: ((context: LoadIconErrorContext) => void) | null;\n\n /** Customize the [texture parameters](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/texParameter). */\n textureParameters?: SamplerProps | null;\n};\n\nexport type IconLayerProps = _IconLayerProps & LayerProps;\n\nconst DEFAULT_COLOR = [0, 0, 0, 255] as const;\n\nconst defaultProps: DefaultProps = {\n iconAtlas: {type: 'image', value: null, async: true},\n iconMapping: {type: 'object', value: {}, async: true},\n sizeScale: {type: 'number', value: 1, min: 0},\n billboard: true,\n sizeUnits: 'pixels',\n sizeBasis: 'height',\n sizeMinPixels: {type: 'number', min: 0, value: 0}, // min point radius in pixels\n sizeMaxPixels: {type: 'number', min: 0, value: Number.MAX_SAFE_INTEGER}, // max point radius in pixels\n alphaCutoff: {type: 'number', value: 0.05, min: 0, max: 1},\n\n getPosition: {type: 'accessor', value: (x: any) => x.position},\n getIcon: {type: 'accessor', value: (x: any) => x.icon},\n getColor: {type: 'accessor', value: DEFAULT_COLOR},\n getSize: {type: 'accessor', value: 1},\n getAngle: {type: 'accessor', value: 0},\n getPixelOffset: {type: 'accessor', value: [0, 0]},\n\n onIconError: {type: 'function', value: null, optional: true},\n\n textureParameters: {type: 'object', ignore: true, value: null}\n};\n\n/** Render raster icons at given coordinates. */\nexport default class IconLayer extends Layer<\n ExtraPropsT & Required<_IconLayerProps>\n> {\n static defaultProps = defaultProps;\n static layerName = 'IconLayer';\n\n state!: {\n model?: Model;\n iconManager: IconManager;\n };\n\n getShaders() {\n return super.getShaders({vs, fs, source, modules: [project32, color, picking, iconUniforms]});\n }\n\n initializeState() {\n this.state = {\n iconManager: new IconManager(this.context.device, {\n onUpdate: this._onUpdate.bind(this),\n onError: this._onError.bind(this)\n })\n };\n\n const attributeManager = this.getAttributeManager();\n /* eslint-disable max-len */\n attributeManager!.addInstanced({\n instancePositions: {\n size: 3,\n type: 'float64',\n fp64: this.use64bitPositions(),\n transition: true,\n accessor: 'getPosition'\n },\n instanceSizes: {\n size: 1,\n transition: true,\n accessor: 'getSize',\n defaultValue: 1\n },\n instanceIconDefs: {\n size: 7,\n accessor: 'getIcon',\n // eslint-disable-next-line @typescript-eslint/unbound-method\n transform: this.getInstanceIconDef,\n shaderAttributes: {\n instanceOffsets: {\n size: 2,\n elementOffset: 0\n },\n instanceIconFrames: {\n size: 4,\n elementOffset: 2\n },\n instanceColorModes: {\n size: 1,\n elementOffset: 6\n }\n }\n },\n instanceColors: {\n size: this.props.colorFormat.length,\n type: 'unorm8',\n transition: true,\n accessor: 'getColor',\n defaultValue: DEFAULT_COLOR\n },\n instanceAngles: {\n size: 1,\n transition: true,\n accessor: 'getAngle'\n },\n instancePixelOffset: {\n size: 2,\n transition: true,\n accessor: 'getPixelOffset'\n }\n });\n /* eslint-enable max-len */\n }\n\n /* eslint-disable max-statements, complexity */\n updateState(params: UpdateParameters) {\n super.updateState(params);\n const {props, oldProps, changeFlags} = params;\n\n const attributeManager = this.getAttributeManager();\n const {iconAtlas, iconMapping, data, getIcon, textureParameters} = props;\n const {iconManager} = this.state;\n\n if (typeof iconAtlas === 'string') {\n return;\n }\n\n // internalState is always defined during updateState\n const prePacked = iconAtlas || this.internalState!.isAsyncPropLoading('iconAtlas');\n iconManager.setProps({\n loadOptions: props.loadOptions,\n autoPacking: !prePacked,\n iconAtlas,\n iconMapping: prePacked ? (iconMapping as IconMapping) : null,\n textureParameters\n });\n\n // prepacked iconAtlas from user\n if (prePacked) {\n if (oldProps.iconMapping !== props.iconMapping) {\n attributeManager!.invalidate('getIcon');\n }\n } else if (\n changeFlags.dataChanged ||\n (changeFlags.updateTriggersChanged &&\n (changeFlags.updateTriggersChanged.all || changeFlags.updateTriggersChanged.getIcon))\n ) {\n // Auto packing - getIcon is expected to return an object\n iconManager.packIcons(data, getIcon as AccessorFunction);\n }\n\n if (changeFlags.extensionsChanged) {\n this.state.model?.destroy();\n this.state.model = this._getModel();\n attributeManager!.invalidateAll();\n }\n }\n /* eslint-enable max-statements, complexity */\n\n get isLoaded(): boolean {\n return super.isLoaded && this.state.iconManager.isLoaded;\n }\n\n finalizeState(context: LayerContext): void {\n super.finalizeState(context);\n // Release resources held by the icon manager\n this.state.iconManager.finalize();\n }\n\n draw({uniforms}): void {\n const {sizeScale, sizeBasis, sizeMinPixels, sizeMaxPixels, sizeUnits, billboard, alphaCutoff} =\n this.props;\n const {iconManager} = this.state;\n const iconsTexture = iconManager.getTexture();\n if (iconsTexture) {\n const model = this.state.model!;\n const iconProps: IconProps = {\n iconsTexture,\n iconsTextureDim: [iconsTexture.width, iconsTexture.height],\n sizeUnits: UNIT[sizeUnits],\n sizeScale,\n sizeBasis: sizeBasis === 'height' ? 1.0 : 0.0,\n sizeMinPixels,\n sizeMaxPixels,\n billboard,\n alphaCutoff\n };\n\n model.shaderInputs.setProps({icon: iconProps});\n model.draw(this.context.renderPass);\n }\n }\n\n protected _getModel(): Model {\n // The icon-layer vertex shader uses 2d positions\n // specifed via: in vec2 positions;\n const positions = [-1, -1, 1, -1, -1, 1, 1, 1];\n\n return new Model(this.context.device, {\n ...this.getShaders(),\n id: this.props.id,\n bufferLayout: this.getAttributeManager()!.getBufferLayouts(),\n geometry: new Geometry({\n topology: 'triangle-strip',\n attributes: {\n // The size must be explicitly passed here otherwise luma.gl\n // will default to assuming that positions are 3D (x,y,z)\n positions: {\n size: 2,\n value: new Float32Array(positions)\n }\n }\n }),\n isInstanced: true\n });\n }\n\n private _onUpdate(didFrameChange: boolean): void {\n if (didFrameChange) {\n this.getAttributeManager()?.invalidate('getIcon');\n this.setNeedsUpdate();\n } else {\n this.setNeedsRedraw();\n }\n }\n\n private _onError(evt: LoadIconErrorContext): void {\n const onIconError = this.getCurrentLayer()?.props.onIconError;\n if (onIconError) {\n onIconError(evt);\n } else {\n log.error(evt.error.message)();\n }\n }\n\n protected getInstanceIconDef(icon: string): number[] {\n const {\n x,\n y,\n width,\n height,\n mask,\n anchorX = width / 2,\n anchorY = height / 2\n } = this.state.iconManager.getIconMapping(icon);\n\n return [width / 2 - anchorX, height / 2 - anchorY, x, y, width, height, mask ? 1 : 0];\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ShaderModule} from '@luma.gl/shadertools';\n\nconst glslUniformBlock = `\\\nlayout(std140) uniform scatterplotUniforms {\n float radiusScale;\n float radiusMinPixels;\n float radiusMaxPixels;\n float lineWidthScale;\n float lineWidthMinPixels;\n float lineWidthMaxPixels;\n float stroked;\n float filled;\n bool antialiasing;\n bool billboard;\n highp int radiusUnits;\n highp int lineWidthUnits;\n} scatterplot;\n`;\n\nexport type ScatterplotProps = {\n radiusScale: number;\n radiusMinPixels: number;\n radiusMaxPixels: number;\n lineWidthScale: number;\n lineWidthMinPixels: number;\n lineWidthMaxPixels: number;\n stroked: boolean;\n filled: boolean;\n antialiasing: boolean;\n billboard: boolean;\n radiusUnits: number;\n lineWidthUnits: number;\n};\n\nexport const scatterplotUniforms = {\n name: 'scatterplot',\n vs: glslUniformBlock,\n fs: glslUniformBlock,\n source: '',\n uniformTypes: {\n radiusScale: 'f32',\n radiusMinPixels: 'f32',\n radiusMaxPixels: 'f32',\n lineWidthScale: 'f32',\n lineWidthMinPixels: 'f32',\n lineWidthMaxPixels: 'f32',\n stroked: 'f32',\n filled: 'f32',\n antialiasing: 'f32',\n billboard: 'f32',\n radiusUnits: 'i32',\n lineWidthUnits: 'i32'\n }\n} as const satisfies ShaderModule;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport default /* glsl */ `\\\n#version 300 es\n#define SHADER_NAME scatterplot-layer-vertex-shader\n\nin vec3 positions;\n\nin vec3 instancePositions;\nin vec3 instancePositions64Low;\nin float instanceRadius;\nin float instanceLineWidths;\nin vec4 instanceFillColors;\nin vec4 instanceLineColors;\nin vec3 instancePickingColors;\n\nout vec4 vFillColor;\nout vec4 vLineColor;\nout vec2 unitPosition;\nout float innerUnitRadius;\nout float outerRadiusPixels;\n\n\nvoid main(void) {\n geometry.worldPosition = instancePositions;\n\n // Multiply out radius and clamp to limits\n outerRadiusPixels = clamp(\n project_size_to_pixel(scatterplot.radiusScale * instanceRadius, scatterplot.radiusUnits),\n scatterplot.radiusMinPixels, scatterplot.radiusMaxPixels\n );\n \n // Multiply out line width and clamp to limits\n float lineWidthPixels = clamp(\n project_size_to_pixel(scatterplot.lineWidthScale * instanceLineWidths, scatterplot.lineWidthUnits),\n scatterplot.lineWidthMinPixels, scatterplot.lineWidthMaxPixels\n );\n\n // outer radius needs to offset by half stroke width\n outerRadiusPixels += scatterplot.stroked * lineWidthPixels / 2.0;\n // Expand geometry to accomodate edge smoothing\n float edgePadding = scatterplot.antialiasing ? (outerRadiusPixels + SMOOTH_EDGE_RADIUS) / outerRadiusPixels : 1.0;\n\n // position on the containing square in [-1, 1] space\n unitPosition = edgePadding * positions.xy;\n geometry.uv = unitPosition;\n geometry.pickingColor = instancePickingColors;\n\n innerUnitRadius = 1.0 - scatterplot.stroked * lineWidthPixels / outerRadiusPixels;\n \n if (scatterplot.billboard) {\n gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0), geometry.position);\n DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n vec3 offset = edgePadding * positions * outerRadiusPixels;\n DECKGL_FILTER_SIZE(offset, geometry);\n gl_Position.xy += project_pixel_size_to_clipspace(offset.xy);\n } else {\n vec3 offset = edgePadding * positions * project_pixel_size(outerRadiusPixels);\n DECKGL_FILTER_SIZE(offset, geometry);\n gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset, geometry.position);\n DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n }\n\n // Apply opacity to instance color, or return instance picking color\n vFillColor = vec4(instanceFillColors.rgb, instanceFillColors.a * layer.opacity);\n DECKGL_FILTER_COLOR(vFillColor, geometry);\n vLineColor = vec4(instanceLineColors.rgb, instanceLineColors.a * layer.opacity);\n DECKGL_FILTER_COLOR(vLineColor, geometry);\n}\n`;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport default /* glsl */ `\\\n#version 300 es\n#define SHADER_NAME scatterplot-layer-fragment-shader\n\nprecision highp float;\n\nin vec4 vFillColor;\nin vec4 vLineColor;\nin vec2 unitPosition;\nin float innerUnitRadius;\nin float outerRadiusPixels;\n\nout vec4 fragColor;\n\nvoid main(void) {\n geometry.uv = unitPosition;\n\n float distToCenter = length(unitPosition) * outerRadiusPixels;\n float inCircle = scatterplot.antialiasing ?\n smoothedge(distToCenter, outerRadiusPixels) :\n step(distToCenter, outerRadiusPixels);\n\n if (inCircle == 0.0) {\n discard;\n }\n\n if (scatterplot.stroked > 0.5) {\n float isLine = scatterplot.antialiasing ?\n smoothedge(innerUnitRadius * outerRadiusPixels, distToCenter) :\n step(innerUnitRadius * outerRadiusPixels, distToCenter);\n\n if (scatterplot.filled > 0.5) {\n fragColor = mix(vFillColor, vLineColor, isLine);\n } else {\n if (isLine == 0.0) {\n discard;\n }\n fragColor = vec4(vLineColor.rgb, vLineColor.a * isLine);\n }\n } else if (scatterplot.filled < 0.5) {\n discard;\n } else {\n fragColor = vFillColor;\n }\n\n fragColor.a *= inCircle;\n DECKGL_FILTER_COLOR(fragColor, geometry);\n}\n`;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport default /* wgsl */ `\\\n// Main shaders\n\nstruct ScatterplotUniforms {\n radiusScale: f32,\n radiusMinPixels: f32,\n radiusMaxPixels: f32,\n lineWidthScale: f32,\n lineWidthMinPixels: f32,\n lineWidthMaxPixels: f32,\n stroked: f32,\n filled: i32,\n antialiasing: i32,\n billboard: i32,\n radiusUnits: i32,\n lineWidthUnits: i32,\n};\n\nstruct ConstantAttributeUniforms {\n instancePositions: vec3,\n instancePositions64Low: vec3,\n instanceRadius: f32,\n instanceLineWidths: f32,\n instanceFillColors: vec4,\n instanceLineColors: vec4,\n instancePickingColors: vec3,\n\n instancePositionsConstant: i32,\n instancePositions64LowConstant: i32,\n instanceRadiusConstant: i32,\n instanceLineWidthsConstant: i32,\n instanceFillColorsConstant: i32,\n instanceLineColorsConstant: i32,\n instancePickingColorsConstant: i32\n};\n\n@group(0) @binding(0) var scatterplot: ScatterplotUniforms;\n\nstruct ConstantAttributes {\n instancePositions: vec3,\n instancePositions64Low: vec3,\n instanceRadius: f32,\n instanceLineWidths: f32,\n instanceFillColors: vec4,\n instanceLineColors: vec4,\n instancePickingColors: vec3\n};\n\nconst constants = ConstantAttributes(\n vec3(0.0),\n vec3(0.0),\n 0.0,\n 0.0,\n vec4(0.0, 0.0, 0.0, 1.0),\n vec4(0.0, 0.0, 0.0, 1.0),\n vec3(0.0)\n);\n\nstruct Attributes {\n @builtin(instance_index) instanceIndex : u32,\n @builtin(vertex_index) vertexIndex : u32,\n @location(0) positions: vec3,\n @location(1) instancePositions: vec3,\n @location(2) instancePositions64Low: vec3,\n @location(3) instanceRadius: f32,\n @location(4) instanceLineWidths: f32,\n @location(5) instanceFillColors: vec4,\n @location(6) instanceLineColors: vec4,\n @location(7) instancePickingColors: vec3,\n};\n\nstruct Varyings {\n @builtin(position) position: vec4,\n @location(0) vFillColor: vec4,\n @location(1) vLineColor: vec4,\n @location(2) unitPosition: vec2,\n @location(3) innerUnitRadius: f32,\n @location(4) outerRadiusPixels: f32,\n @location(5) pickingColor: vec3,\n};\n\n@vertex\nfn vertexMain(attributes: Attributes) -> Varyings {\n var varyings: Varyings;\n\n // Draw an inline geometry constant array clip space triangle to verify that rendering works.\n // var positions = array, 3>(vec2(0.0, 0.5), vec2(-0.5, -0.5), vec2(0.5, -0.5));\n // if (attributes.instanceIndex == 0) {\n // varyings.position = vec4(positions[attributes.vertexIndex], 0.0, 1.0);\n // return varyings;\n // }\n\n geometry.worldPosition = attributes.instancePositions;\n\n // Multiply out radius and clamp to limits\n varyings.outerRadiusPixels = clamp(\n project_unit_size_to_pixel(scatterplot.radiusScale * attributes.instanceRadius, scatterplot.radiusUnits),\n scatterplot.radiusMinPixels, scatterplot.radiusMaxPixels\n );\n\n // Multiply out line width and clamp to limits\n let lineWidthPixels = clamp(\n project_unit_size_to_pixel(scatterplot.lineWidthScale * attributes.instanceLineWidths, scatterplot.lineWidthUnits),\n scatterplot.lineWidthMinPixels, scatterplot.lineWidthMaxPixels\n );\n\n // outer radius needs to offset by half stroke width\n varyings.outerRadiusPixels += scatterplot.stroked * lineWidthPixels / 2.0;\n // Expand geometry to accommodate edge smoothing\n let edgePadding = select(\n (varyings.outerRadiusPixels + SMOOTH_EDGE_RADIUS) / varyings.outerRadiusPixels,\n 1.0,\n scatterplot.antialiasing != 0\n );\n\n // position on the containing square in [-1, 1] space\n varyings.unitPosition = edgePadding * attributes.positions.xy;\n geometry.uv = varyings.unitPosition;\n geometry.pickingColor = attributes.instancePickingColors;\n\n varyings.innerUnitRadius = 1.0 - scatterplot.stroked * lineWidthPixels / varyings.outerRadiusPixels;\n\n if (scatterplot.billboard != 0) {\n varyings.position = project_position_to_clipspace(attributes.instancePositions, attributes.instancePositions64Low, vec3(0.0)); // TODO , geometry.position);\n // DECKGL_FILTER_GL_POSITION(varyings.position, geometry);\n let offset = attributes.positions; // * edgePadding * varyings.outerRadiusPixels;\n // DECKGL_FILTER_SIZE(offset, geometry);\n let clipPixels = project_pixel_size_to_clipspace(offset.xy);\n varyings.position.x = clipPixels.x;\n varyings.position.y = clipPixels.y;\n } else {\n let offset = edgePadding * attributes.positions * project_pixel_size_float(varyings.outerRadiusPixels);\n // DECKGL_FILTER_SIZE(offset, geometry);\n varyings.position = project_position_to_clipspace(attributes.instancePositions, attributes.instancePositions64Low, offset); // TODO , geometry.position);\n // DECKGL_FILTER_GL_POSITION(varyings.position, geometry);\n }\n\n // Apply opacity to instance color, or return instance picking color\n varyings.vFillColor = vec4(attributes.instanceFillColors.rgb, attributes.instanceFillColors.a * layer.opacity);\n // DECKGL_FILTER_COLOR(varyings.vFillColor, geometry);\n varyings.vLineColor = vec4(attributes.instanceLineColors.rgb, attributes.instanceLineColors.a * layer.opacity);\n // DECKGL_FILTER_COLOR(varyings.vLineColor, geometry);\n varyings.pickingColor = attributes.instancePickingColors;\n\n return varyings;\n}\n\n@fragment\nfn fragmentMain(varyings: Varyings) -> @location(0) vec4 {\n // var geometry: Geometry;\n // geometry.uv = unitPosition;\n\n let distToCenter = length(varyings.unitPosition) * varyings.outerRadiusPixels;\n let inCircle = select(\n smoothedge(distToCenter, varyings.outerRadiusPixels),\n step(distToCenter, varyings.outerRadiusPixels),\n scatterplot.antialiasing != 0\n );\n\n if (inCircle == 0.0) {\n discard;\n }\n\n var fragColor: vec4;\n\n if (scatterplot.stroked != 0) {\n let isLine = select(\n smoothedge(varyings.innerUnitRadius * varyings.outerRadiusPixels, distToCenter),\n step(varyings.innerUnitRadius * varyings.outerRadiusPixels, distToCenter),\n scatterplot.antialiasing != 0\n );\n\n if (scatterplot.filled != 0) {\n fragColor = mix(varyings.vFillColor, varyings.vLineColor, isLine);\n } else {\n if (isLine == 0.0) {\n discard;\n }\n fragColor = vec4(varyings.vLineColor.rgb, varyings.vLineColor.a * isLine);\n }\n } else if (scatterplot.filled == 0) {\n discard;\n } else {\n fragColor = varyings.vFillColor;\n }\n\n fragColor.a *= inCircle;\n\n if (picking.isActive > 0.5) {\n if (!picking_isColorValid(varyings.pickingColor)) {\n discard;\n }\n return vec4(varyings.pickingColor, 1.0);\n }\n\n if (picking.isHighlightActive > 0.5) {\n let highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor);\n if (picking_isColorZero(abs(varyings.pickingColor - highlightedObjectColor))) {\n let highLightAlpha = picking.highlightColor.a;\n let blendedAlpha = highLightAlpha + fragColor.a * (1.0 - highLightAlpha);\n if (blendedAlpha > 0.0) {\n let highLightRatio = highLightAlpha / blendedAlpha;\n fragColor = vec4(\n mix(fragColor.rgb, picking.highlightColor.rgb, highLightRatio),\n blendedAlpha\n );\n } else {\n fragColor = vec4(fragColor.rgb, 0.0);\n }\n }\n }\n\n // Apply premultiplied alpha as required by transparent canvas\n fragColor = deckgl_premultiplied_alpha(fragColor);\n\n return fragColor;\n // return vec4(0, 0, 1, 1);\n}\n`;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Layer, color, project32, picking, UNIT} from '@deck.gl/core';\nimport {Model, Geometry} from '@luma.gl/engine';\n\nimport {scatterplotUniforms, ScatterplotProps} from './scatterplot-layer-uniforms';\nimport vs from './scatterplot-layer-vertex.glsl';\nimport fs from './scatterplot-layer-fragment.glsl';\nimport source from './scatterplot-layer.wgsl';\n\nimport type {\n LayerProps,\n LayerDataSource,\n UpdateParameters,\n Accessor,\n Unit,\n Position,\n Color,\n DefaultProps\n} from '@deck.gl/core';\n\nconst DEFAULT_COLOR = [0, 0, 0, 255] as const;\n\n/** All props supported by the ScatterplotLayer */\nexport type ScatterplotLayerProps = _ScatterplotLayerProps & LayerProps;\n\n/** Props added by the ScatterplotLayer */\ntype _ScatterplotLayerProps = {\n data: LayerDataSource;\n /**\n * The units of the radius, one of `'meters'`, `'common'`, and `'pixels'`.\n * @default 'meters'\n */\n radiusUnits?: Unit;\n /**\n * Radius multiplier.\n * @default 1\n */\n radiusScale?: number;\n /**\n * The minimum radius in pixels. This prop can be used to prevent the circle from getting too small when zoomed out.\n * @default 0\n */\n radiusMinPixels?: number;\n /**\n * The maximum radius in pixels. This prop can be used to prevent the circle from getting too big when zoomed in.\n * @default Number.MAX_SAFE_INTEGER\n */\n radiusMaxPixels?: number;\n\n /**\n * The units of the stroke width, one of `'meters'`, `'common'`, and `'pixels'`.\n * @default 'meters'\n */\n lineWidthUnits?: Unit;\n /**\n * Stroke width multiplier.\n * @default 1\n */\n lineWidthScale?: number;\n /**\n * The minimum stroke width in pixels. This prop can be used to prevent the line from getting too thin when zoomed out.\n * @default 0\n */\n lineWidthMinPixels?: number;\n /**\n * The maximum stroke width in pixels. This prop can be used to prevent the circle from getting too thick when zoomed in.\n * @default Number.MAX_SAFE_INTEGER\n */\n lineWidthMaxPixels?: number;\n\n /**\n * Draw the outline of points.\n * @default false\n */\n stroked?: boolean;\n /**\n * Draw the filled area of points.\n * @default true\n */\n filled?: boolean;\n /**\n * If `true`, rendered circles always face the camera. If `false` circles face up (i.e. are parallel with the ground plane).\n * @default false\n */\n billboard?: boolean;\n /**\n * If `true`, circles are rendered with smoothed edges. If `false`, circles are rendered with rough edges. Antialiasing can cause artifacts on edges of overlapping circles.\n * @default true\n */\n antialiasing?: boolean;\n\n /**\n * Center position accessor.\n */\n getPosition?: Accessor;\n /**\n * Radius accessor.\n * @default 1\n */\n getRadius?: Accessor;\n /**\n * Fill color accessor.\n * @default [0, 0, 0, 255]\n */\n getFillColor?: Accessor;\n /**\n * Stroke color accessor.\n * @default [0, 0, 0, 255]\n */\n getLineColor?: Accessor;\n /**\n * Stroke width accessor.\n * @default 1\n */\n getLineWidth?: Accessor;\n /**\n * @deprecated Use `getLineWidth` instead\n */\n strokeWidth?: number;\n /**\n * @deprecated Use `stroked` instead\n */\n outline?: boolean;\n /**\n * @deprecated Use `getFillColor` and `getLineColor` instead\n */\n getColor?: Accessor;\n};\n\nconst defaultProps: DefaultProps = {\n radiusUnits: 'meters',\n radiusScale: {type: 'number', min: 0, value: 1},\n radiusMinPixels: {type: 'number', min: 0, value: 0}, // min point radius in pixels\n radiusMaxPixels: {type: 'number', min: 0, value: Number.MAX_SAFE_INTEGER}, // max point radius in pixels\n\n lineWidthUnits: 'meters',\n lineWidthScale: {type: 'number', min: 0, value: 1},\n lineWidthMinPixels: {type: 'number', min: 0, value: 0},\n lineWidthMaxPixels: {type: 'number', min: 0, value: Number.MAX_SAFE_INTEGER},\n\n stroked: false,\n filled: true,\n billboard: false,\n antialiasing: true,\n\n getPosition: {type: 'accessor', value: (x: any) => x.position},\n getRadius: {type: 'accessor', value: 1},\n getFillColor: {type: 'accessor', value: DEFAULT_COLOR},\n getLineColor: {type: 'accessor', value: DEFAULT_COLOR},\n getLineWidth: {type: 'accessor', value: 1},\n\n // deprecated\n strokeWidth: {deprecatedFor: 'getLineWidth'},\n outline: {deprecatedFor: 'stroked'},\n getColor: {deprecatedFor: ['getFillColor', 'getLineColor']}\n};\n\n/** Render circles at given coordinates. */\nexport default class ScatterplotLayer extends Layer<\n ExtraPropsT & Required<_ScatterplotLayerProps>\n> {\n static defaultProps = defaultProps;\n static layerName: string = 'ScatterplotLayer';\n\n state!: {\n model?: Model;\n };\n\n getShaders() {\n return super.getShaders({\n vs,\n fs,\n source,\n modules: [project32, color, picking, scatterplotUniforms]\n });\n }\n\n initializeState() {\n this.getAttributeManager()!.addInstanced({\n instancePositions: {\n size: 3,\n type: 'float64',\n fp64: this.use64bitPositions(),\n transition: true,\n accessor: 'getPosition'\n },\n instanceRadius: {\n size: 1,\n transition: true,\n accessor: 'getRadius',\n defaultValue: 1\n },\n instanceFillColors: {\n size: this.props.colorFormat.length,\n transition: true,\n type: 'unorm8',\n accessor: 'getFillColor',\n defaultValue: [0, 0, 0, 255]\n },\n instanceLineColors: {\n size: this.props.colorFormat.length,\n transition: true,\n type: 'unorm8',\n accessor: 'getLineColor',\n defaultValue: [0, 0, 0, 255]\n },\n instanceLineWidths: {\n size: 1,\n transition: true,\n accessor: 'getLineWidth',\n defaultValue: 1\n }\n });\n }\n\n updateState(params: UpdateParameters) {\n super.updateState(params);\n\n if (params.changeFlags.extensionsChanged) {\n this.state.model?.destroy();\n this.state.model = this._getModel();\n this.getAttributeManager()!.invalidateAll();\n }\n }\n\n draw({uniforms}) {\n const {\n radiusUnits,\n radiusScale,\n radiusMinPixels,\n radiusMaxPixels,\n stroked,\n filled,\n billboard,\n antialiasing,\n lineWidthUnits,\n lineWidthScale,\n lineWidthMinPixels,\n lineWidthMaxPixels\n } = this.props;\n const scatterplotProps: ScatterplotProps = {\n stroked,\n filled,\n billboard,\n antialiasing,\n radiusUnits: UNIT[radiusUnits],\n radiusScale,\n radiusMinPixels,\n radiusMaxPixels,\n lineWidthUnits: UNIT[lineWidthUnits],\n lineWidthScale,\n lineWidthMinPixels,\n lineWidthMaxPixels\n };\n const model = this.state.model!;\n model.shaderInputs.setProps({scatterplot: scatterplotProps});\n model.draw(this.context.renderPass);\n }\n\n protected _getModel() {\n // a square that minimally cover the unit circle\n const positions = [-1, -1, 0, 1, -1, 0, -1, 1, 0, 1, 1, 0];\n return new Model(this.context.device, {\n ...this.getShaders(),\n id: this.props.id,\n bufferLayout: this.getAttributeManager()!.getBufferLayouts(),\n geometry: new Geometry({\n topology: 'triangle-strip',\n attributes: {\n positions: {size: 3, value: new Float32Array(positions)}\n }\n }),\n isInstanced: true\n });\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ShaderModule} from '@luma.gl/shadertools';\n\nconst uniformBlock = `\\\nlayout(std140) uniform sdfUniforms {\n float gamma;\n bool enabled;\n float buffer;\n float outlineBuffer;\n vec4 outlineColor;\n} sdf;\n`;\n\nexport type SdfProps = {\n gamma: number;\n enabled: boolean;\n buffer: number;\n outlineBuffer: number;\n outlineColor: [number, number, number, number];\n};\n\nexport const sdfUniforms = {\n name: 'sdf',\n vs: uniformBlock,\n fs: uniformBlock,\n uniformTypes: {\n gamma: 'f32',\n enabled: 'f32',\n buffer: 'f32',\n outlineBuffer: 'f32',\n outlineColor: 'vec4'\n }\n} as const satisfies ShaderModule;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ShaderModule} from '@luma.gl/shadertools';\nimport type {Viewport, OrthographicViewport} from '@deck.gl/core';\n\nexport type ContentAlignModes = keyof typeof CONTENT_ALIGN;\n\nconst CONTENT_ALIGN = {\n none: 0,\n start: 1,\n center: 2,\n end: 3\n} as const;\n\nconst glslUniformBlock = `\\\nlayout(std140) uniform textUniforms {\n highp vec2 cutoffPixels;\n highp ivec2 align;\n highp float fontSize;\n bool flipY;\n} text;\n\n#define ALIGN_MODE_START ${CONTENT_ALIGN.start}\n#define ALIGN_MODE_CENTER ${CONTENT_ALIGN.center}\n#define ALIGN_MODE_END ${CONTENT_ALIGN.end}\n`;\n\nexport type TextModuleProps = {\n contentCutoffPixels?: [number, number];\n contentAlignHorizontal?: ContentAlignModes;\n contentAlignVertical?: ContentAlignModes;\n fontSize: number;\n viewport: Viewport;\n};\n\ntype TextUniforms = {\n cutoffPixels: [number, number];\n align: [number, number];\n fontSize: number;\n // If true, content's x,y is the top-left corner instead of bottom-left\n flipY: boolean;\n};\n\nexport const textUniforms = {\n name: 'text',\n vs: glslUniformBlock,\n getUniforms: ({\n contentCutoffPixels = [0, 0],\n contentAlignHorizontal = 'none',\n contentAlignVertical = 'none',\n fontSize,\n viewport\n }: Partial) => ({\n cutoffPixels: contentCutoffPixels,\n align: [CONTENT_ALIGN[contentAlignHorizontal], CONTENT_ALIGN[contentAlignVertical]],\n fontSize,\n flipY: (viewport as OrthographicViewport)?.flipY ?? false\n }),\n uniformTypes: {\n cutoffPixels: 'vec2',\n align: 'vec2',\n fontSize: 'f32',\n flipY: 'f32'\n }\n} as const satisfies ShaderModule;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport default /* glsl */ `\\\n#version 300 es\n#define SHADER_NAME multi-icon-layer-vertex-shader\n\nin vec2 positions;\n\nin vec3 instancePositions;\nin vec3 instancePositions64Low;\nin float instanceSizes;\nin float instanceAngles;\nin vec4 instanceColors;\nin vec3 instancePickingColors;\nin vec4 instanceIconFrames;\nin float instanceColorModes;\nin vec2 instanceOffsets;\nin vec2 instancePixelOffset;\nin vec4 instanceClipRect;\n\nout float vColorMode;\nout vec4 vColor;\nout vec2 vTextureCoords;\nout vec2 uv;\n\nvec2 rotate_by_angle(vec2 vertex, float angle) {\n float angle_radian = angle * PI / 180.0;\n float cos_angle = cos(angle_radian);\n float sin_angle = sin(angle_radian);\n mat2 rotationMatrix = mat2(cos_angle, -sin_angle, sin_angle, cos_angle);\n return rotationMatrix * vertex;\n}\n\nfloat getPixelOffsetFromAlignment(float anchor, float extent, float clipStart, float clipEnd, int mode) {\n if (clipEnd < clipStart) return 0.0;\n if (mode == ALIGN_MODE_START) {\n return max(- (anchor + clipStart), 0.0);\n }\n if (mode == ALIGN_MODE_CENTER) {\n float _min = max(0., anchor + clipStart);\n float _max = min(extent, anchor + clipEnd);\n return _min < _max ? (_min + _max) / 2.0 - anchor : 0.0;\n }\n if (mode == ALIGN_MODE_END) {\n return min(extent - (anchor + clipEnd), 0.);\n }\n return 0.0;\n}\n\nvoid main(void) {\n geometry.worldPosition = instancePositions;\n geometry.uv = positions;\n geometry.pickingColor = instancePickingColors;\n uv = positions;\n\n vec2 iconSize = instanceIconFrames.zw;\n // convert size in meters to pixels, then scaled and clamp\n \n // project meters to pixels and clamp to limits \n float sizePixels = clamp(\n project_size_to_pixel(instanceSizes * icon.sizeScale, icon.sizeUnits),\n icon.sizeMinPixels, icon.sizeMaxPixels\n );\n\n float instanceScale = sizePixels / text.fontSize;\n\n // scale and rotate vertex in \"pixel\" value and convert back to fraction in clipspace\n vec2 pixelOffset = positions / 2.0 * iconSize + instanceOffsets;\n pixelOffset = rotate_by_angle(pixelOffset, instanceAngles) * instanceScale;\n pixelOffset += instancePixelOffset;\n pixelOffset.y *= -1.0;\n\n vec2 anchorPosScreen;\n if (icon.billboard) {\n gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0), geometry.position);\n anchorPosScreen = gl_Position.xy / gl_Position.w;\n DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n vec3 offset = vec3(pixelOffset, 0.0);\n DECKGL_FILTER_SIZE(offset, geometry);\n gl_Position.xy += project_pixel_size_to_clipspace(offset.xy);\n } else {\n vec3 offset_common = vec3(project_pixel_size(pixelOffset), 0.0);\n if (text.flipY) {\n offset_common.y *= -1.;\n }\n DECKGL_FILTER_SIZE(offset_common, geometry);\n vec4 anchorPos = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0));\n anchorPosScreen = anchorPos.xy / anchorPos.w;\n gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset_common, geometry.position); \n DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n }\n\n anchorPosScreen = vec2(anchorPosScreen.x + 1.0, 1.0 - anchorPosScreen.y) / 2.0 * project.viewportSize / project.devicePixelRatio;\n vec2 xy = project_size_to_pixel(instanceClipRect.xy);\n vec2 wh = project_size_to_pixel(instanceClipRect.zw);\n if (text.flipY) {\n xy.y = -xy.y - wh.y;\n }\n if (text.align.x > 0 || text.align.y > 0) {\n vec2 viewportPixels = project.viewportSize / project.devicePixelRatio;\n vec2 scrollPixels = vec2(\n getPixelOffsetFromAlignment(anchorPosScreen.x, viewportPixels.x, xy.x, xy.x + wh.x, text.align.x),\n -getPixelOffsetFromAlignment(anchorPosScreen.y, viewportPixels.y, -xy.y - wh.y, -xy.y, text.align.y)\n );\n pixelOffset += scrollPixels;\n gl_Position.xy += project_pixel_size_to_clipspace(scrollPixels);\n }\n\n if (instanceClipRect.z >= 0.) {\n if (pixelOffset.x < xy.x || pixelOffset.x > xy.x + wh.x) {\n gl_Position = vec4(0.0);\n }\n else if (text.cutoffPixels.x > 0.) {\n float vpWidth = project.viewportSize.x / project.devicePixelRatio;\n float l = max(anchorPosScreen.x + xy.x, 0.0);\n float r = min(anchorPosScreen.x + xy.x + wh.x, vpWidth);\n if (r - l < text.cutoffPixels.x) {\n gl_Position = vec4(0.0);\n }\n }\n }\n if (instanceClipRect.w >= 0.) {\n if (pixelOffset.y < xy.y || pixelOffset.y > xy.y + wh.y) {\n gl_Position = vec4(0.0);\n }\n else if (text.cutoffPixels.y > 0.) {\n float vpHeight = project.viewportSize.y / project.devicePixelRatio;\n float t = max(anchorPosScreen.y - xy.y - wh.y, 0.0);\n float b = min(anchorPosScreen.y - xy.y, vpHeight);\n if (b - t < text.cutoffPixels.y) {\n gl_Position = vec4(0.0);\n }\n }\n }\n\n vTextureCoords = mix(\n instanceIconFrames.xy,\n instanceIconFrames.xy + iconSize,\n (positions.xy + 1.0) / 2.0\n ) / icon.iconsTextureDim;\n\n vColor = instanceColors;\n DECKGL_FILTER_COLOR(vColor, geometry);\n\n vColorMode = instanceColorModes;\n}\n`;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport default `\\\n#version 300 es\n#define SHADER_NAME multi-icon-layer-fragment-shader\n\nprecision highp float;\n\nuniform sampler2D iconsTexture;\n\nin vec4 vColor;\nin vec2 vTextureCoords;\nin vec2 uv;\n\nout vec4 fragColor;\n\nvoid main(void) {\n geometry.uv = uv;\n\n if (!bool(picking.isActive)) {\n float alpha = texture(iconsTexture, vTextureCoords).a;\n vec4 color = vColor;\n\n // if enable sdf (signed distance fields)\n if (sdf.enabled) {\n float distance = alpha;\n alpha = smoothstep(sdf.buffer - sdf.gamma, sdf.buffer + sdf.gamma, distance);\n\n if (sdf.outlineBuffer > 0.0) {\n float inFill = alpha;\n float inBorder = smoothstep(sdf.outlineBuffer - sdf.gamma, sdf.outlineBuffer + sdf.gamma, distance);\n color = mix(sdf.outlineColor, vColor, inFill);\n alpha = inBorder;\n }\n }\n\n // Take the global opacity and the alpha from color into account for the alpha component\n float a = alpha * color.a;\n \n if (a < icon.alphaCutoff) {\n discard;\n }\n\n fragColor = vec4(color.rgb, a * layer.opacity);\n }\n\n DECKGL_FILTER_COLOR(fragColor, geometry);\n}\n`;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {log, createIterable} from '@deck.gl/core';\nimport IconLayer from '../../icon-layer/icon-layer';\n\nimport {SdfProps, sdfUniforms} from './sdf-uniforms';\nimport {TextModuleProps, textUniforms, ContentAlignModes} from '../text-uniforms';\n\nimport vs from './multi-icon-layer-vertex.glsl';\nimport fs from './multi-icon-layer-fragment.glsl';\n\nimport type {IconLayerProps} from '../../icon-layer/icon-layer';\nimport type {\n Attribute,\n Accessor,\n AccessorFunction,\n Color,\n UpdateParameters,\n DefaultProps\n} from '@deck.gl/core';\n\n// TODO expose as layer properties\nconst DEFAULT_BUFFER = 192.0 / 256;\nconst EMPTY_ARRAY = [];\n\ntype _MultiIconLayerProps = {\n getIconOffsets?: AccessorFunction;\n getContentBox?: Accessor;\n\n fontSize?: number;\n sdf?: boolean;\n smoothing?: number;\n outlineWidth?: number;\n outlineColor?: Color;\n\n contentCutoffPixels?: [width: number, height: number];\n contentAlignHorizontal?: ContentAlignModes;\n contentAlignVertical?: ContentAlignModes;\n};\n\nexport type MultiIconLayerProps = _MultiIconLayerProps &\n IconLayerProps;\n\nconst defaultProps: DefaultProps = {\n getIconOffsets: {type: 'accessor', value: (x: any) => x.offsets},\n getContentBox: {type: 'accessor', value: [0, 0, -1, -1]},\n fontSize: 1,\n alphaCutoff: 0.001,\n smoothing: 0.1,\n outlineWidth: 0,\n outlineColor: {type: 'color', value: [0, 0, 0, 255]},\n contentCutoffPixels: {type: 'array', value: [0, 0]},\n contentAlignHorizontal: 'none',\n contentAlignVertical: 'none'\n};\n\nexport default class MultiIconLayer extends IconLayer<\n DataT,\n ExtraPropsT & Required<_MultiIconLayerProps>\n> {\n static defaultProps = defaultProps;\n static layerName = 'MultiIconLayer';\n\n state!: IconLayer['state'] & {\n outlineColor: [number, number, number, number];\n };\n\n getShaders() {\n const shaders = super.getShaders();\n return {...shaders, modules: [...shaders.modules, textUniforms, sdfUniforms], vs, fs};\n }\n\n initializeState() {\n super.initializeState();\n\n const attributeManager = this.getAttributeManager();\n const instanceIconDefs = attributeManager!.attributes.instanceIconDefs;\n // eslint-disable-next-line @typescript-eslint/unbound-method\n instanceIconDefs.settings.update = this.calculateInstanceIconDefs;\n attributeManager!.addInstanced({\n instancePickingColors: {\n type: 'uint8',\n size: 4,\n accessor: (object, {index, target: value}) => this.encodePickingColor(index, value)\n },\n instanceClipRect: {\n size: 4,\n accessor: 'getContentBox',\n defaultValue: [0, 0, -1, -1]\n }\n });\n }\n\n updateState(params: UpdateParameters) {\n super.updateState(params);\n const {props, oldProps, changeFlags} = params;\n const {outlineColor} = props;\n\n if (\n changeFlags.updateTriggersChanged &&\n (changeFlags.updateTriggersChanged.getIcon ||\n changeFlags.updateTriggersChanged.getIconOffsets)\n ) {\n this.getAttributeManager()!.invalidate('instanceIconDefs');\n }\n if (outlineColor !== oldProps.outlineColor) {\n const normalizedOutlineColor = [\n outlineColor[0] / 255,\n outlineColor[1] / 255,\n outlineColor[2] / 255,\n (outlineColor[3] ?? 255) / 255\n ];\n\n this.setState({\n outlineColor: normalizedOutlineColor\n });\n }\n if (!props.sdf && props.outlineWidth) {\n log.warn(`${this.id}: fontSettings.sdf is required to render outline`)();\n }\n }\n\n draw(params) {\n const {\n sdf,\n smoothing,\n fontSize,\n outlineWidth,\n contentCutoffPixels,\n contentAlignHorizontal,\n contentAlignVertical\n } = this.props;\n const {outlineColor} = this.state;\n const outlineBuffer = outlineWidth\n ? Math.max(smoothing, DEFAULT_BUFFER * (1 - outlineWidth))\n : -1;\n\n const model = this.state.model!;\n const sdfProps: SdfProps = {\n buffer: DEFAULT_BUFFER,\n outlineBuffer,\n gamma: smoothing,\n enabled: Boolean(sdf),\n outlineColor\n };\n const textProps: TextModuleProps = {\n contentCutoffPixels,\n contentAlignHorizontal,\n contentAlignVertical,\n fontSize,\n viewport: this.context.viewport\n };\n model.shaderInputs.setProps({sdf: sdfProps, text: textProps});\n super.draw(params);\n\n // draw text without outline on top to ensure a thick outline won't occlude other characters\n if (sdf && outlineWidth) {\n const {iconManager} = this.state;\n const iconsTexture = iconManager.getTexture();\n\n if (iconsTexture) {\n model.shaderInputs.setProps({sdf: {...sdfProps, outlineBuffer: DEFAULT_BUFFER}});\n model.draw(this.context.renderPass);\n }\n }\n }\n\n protected calculateInstanceIconDefs(\n attribute: Attribute,\n {startRow, endRow}: {startRow: number; endRow: number}\n ) {\n const {data, getIcon, getIconOffsets} = this.props;\n let i = attribute.getVertexOffset(startRow);\n const output = attribute.value as Float32Array;\n const {iterable, objectInfo} = createIterable(data, startRow, endRow);\n for (const object of iterable) {\n objectInfo.index++;\n const text = getIcon(object, objectInfo) as string; // forwarded getText\n const offsets = getIconOffsets(object, objectInfo); // text length x 2\n if (text) {\n let j = 0;\n for (const char of Array.from(text)) {\n const def = super.getInstanceIconDef(char);\n def[0] = offsets[j * 2];\n def[1] += offsets[j * 2 + 1];\n def[6] = 1; // mask\n output.set(def, i);\n i += attribute.size;\n j++;\n }\n }\n }\n }\n}\n","const INF = 1e20;\n\n// lookup table for gamma-corrected, signed squared alpha distance values\nconst alphaTable = new Float64Array(256);\nfor (let i = 0; i < 256; i++) {\n const d = 0.5 - Math.pow(i / 255, 1 / 2.2);\n alphaTable[i] = d * Math.abs(d);\n}\nalphaTable[255] = -INF;\n\nexport default class TinySDF {\n constructor({\n fontSize = 24,\n buffer = 3,\n radius = 8,\n cutoff = 0.25,\n fontFamily = 'sans-serif',\n fontWeight = 'normal',\n fontStyle = 'normal',\n lang = null\n } = {}) {\n this.buffer = buffer; // padding around a glyph's bounding box\n this.radius = radius; // how many pixels around the glyph edge are encoded as signed distances\n this.cutoff = cutoff; // how much of the SDF byte range represents inside vs outside the edge\n this.lang = lang; // language of the Canvas drawing context\n\n // make the canvas size big enough to both have the specified buffer around the glyph\n // for \"halo\", and account for some glyphs possibly being larger than their font size\n const size = this.size = fontSize + buffer * 4;\n\n const canvas = this._createCanvas(size);\n const ctx = this.ctx = canvas.getContext('2d', {willReadFrequently: true});\n ctx.font = `${fontStyle} ${fontWeight} ${fontSize}px ${fontFamily}`;\n\n ctx.textBaseline = 'alphabetic';\n ctx.textAlign = 'left'; // Necessary so that RTL text doesn't have different alignment\n ctx.fillStyle = 'black';\n\n // two grids of squared distances: one for the outside of the glyph shape, one for the inside;\n // the signed distance is derived as sqrt(outer) - sqrt(inner)\n this.gridOuter = new Float64Array(size * size);\n this.gridInner = new Float64Array(size * size);\n this.f = new Float64Array(size);\n this.z = new Float64Array(size + 1);\n this.v = new Uint16Array(size);\n }\n\n _createCanvas(size) {\n if (typeof OffscreenCanvas !== 'undefined') {\n return new OffscreenCanvas(size, size);\n }\n const canvas = document.createElement('canvas');\n canvas.width = canvas.height = size;\n return canvas;\n }\n\n draw(char) {\n const {\n width: glyphAdvance,\n actualBoundingBoxAscent,\n actualBoundingBoxDescent,\n actualBoundingBoxLeft,\n actualBoundingBoxRight\n } = this.ctx.measureText(char);\n\n // The integer/pixel part of the alignment is encoded in metrics.glyphTop/glyphLeft\n // The remainder is implicitly encoded in the rasterization\n const glyphTop = Math.ceil(actualBoundingBoxAscent);\n // actualBoundingBoxLeft is positive when ink extends LEFT of the origin (per spec),\n // so negate to get the ink's left edge in canvas x-coords (positive = right of origin)\n const glyphLeft = Math.floor(-actualBoundingBoxLeft);\n\n // If the glyph overflows the canvas size, it will be clipped at the bottom/right\n const glyphWidth = Math.max(0, Math.min(this.size - this.buffer, Math.ceil(actualBoundingBoxRight) - glyphLeft));\n const glyphHeight = Math.max(0, Math.min(this.size - this.buffer, glyphTop + Math.ceil(actualBoundingBoxDescent)));\n\n const width = glyphWidth + 2 * this.buffer;\n const height = glyphHeight + 2 * this.buffer;\n\n const len = Math.max(width * height, 0);\n const data = new Uint8ClampedArray(len);\n const glyph = {data, width, height, glyphWidth, glyphHeight, glyphTop, glyphLeft, glyphAdvance};\n if (glyphWidth === 0 || glyphHeight === 0) return glyph;\n\n const {ctx, buffer, gridInner, gridOuter} = this;\n if (this.lang) ctx.lang = this.lang;\n ctx.clearRect(buffer, buffer, glyphWidth, glyphHeight);\n ctx.fillText(char, buffer - glyphLeft, buffer + glyphTop);\n const imgData = ctx.getImageData(buffer, buffer, glyphWidth, glyphHeight);\n\n // default: outside the glyph (INF distance) for outer, inside (0 distance) for inner\n gridOuter.fill(INF, 0, len);\n gridInner.fill(0, 0, len);\n\n // for anti-aliased pixels, treat partial coverage as a distance approximation:\n // a fully covered pixel gets 0 outer / INF inner; a partial pixel gets a small\n // non-zero outer or inner distance based on how far its coverage deviates from 0.5\n let imgIdx = 3; // start at the alpha channel of the first pixel\n for (let y = 0; y < glyphHeight; y++) {\n let j = (y + buffer) * width + buffer;\n for (let x = 0; x < glyphWidth; x++, imgIdx += 4, j++) {\n const a = imgData.data[imgIdx]; // alpha value\n if (a === 0) continue; // empty pixels\n const t = alphaTable[a];\n gridOuter[j] = Math.max(0, t);\n gridInner[j] = Math.max(0, -t);\n }\n }\n\n edt(gridOuter, 0, 0, width, height, width, this.f, this.v, this.z);\n // Pad the inner EDT region by 1 px so ink pixels touching the bbox edge can see the\n // outside-ink seeds in the buffer region; clamp to buffer so we don't underflow when buffer=0\n const pad = Math.min(buffer, 1);\n edt(gridInner, buffer - pad, buffer - pad, glyphWidth + 2 * pad, glyphHeight + 2 * pad, width, this.f, this.v, this.z);\n\n // encode signed distance as a byte: inside the glyph maps to high values, outside to low,\n // with the edge gradient spanning [-radius * cutoff, radius * (1 - cutoff)] pixels around the edge;\n // Uint8ClampedArray clamps beyond that\n const scale = 255 / this.radius;\n const base = 255 * (1 - this.cutoff);\n for (let i = 0; i < len; i++) {\n const d = Math.sqrt(gridOuter[i]) - Math.sqrt(gridInner[i]);\n data[i] = Math.round(base - scale * d);\n }\n\n return glyph;\n }\n}\n\n// 2D Euclidean squared distance transform by Felzenszwalb & Huttenlocher https://cs.brown.edu/~pff/papers/dt-final.pdf\nfunction edt(data, x0, y0, width, height, gridSize, f, v, z) {\n for (let x = x0; x < x0 + width; x++) edt1d(data, y0 * gridSize + x, gridSize, height, f, v, z);\n for (let y = y0; y < y0 + height; y++) edt1d(data, y * gridSize + x0, 1, width, f, v, z);\n}\n\n// 1D squared distance transform\nfunction edt1d(grid, offset, stride, length, f, v, z) {\n v[0] = 0;\n z[0] = -INF;\n z[1] = INF;\n f[0] = grid[offset];\n\n for (let q = 1, k = 0, s = 0; q < length; q++) {\n f[q] = grid[offset + q * stride];\n const q2 = q * q;\n do {\n const r = v[k];\n s = (f[q] - f[r] + q2 - r * r) / (q - r) / 2;\n } while (s <= z[k] && --k > -1);\n\n k++;\n v[k] = q;\n z[k] = s;\n z[k + 1] = INF;\n }\n\n for (let q = 0, k = 0; q < length; q++) {\n while (z[k + 1] < q) k++;\n const r = v[k];\n const qr = q - r;\n grid[offset + q * stride] = f[r] + qr * qr;\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/* eslint-disable max-statements, max-params, complexity, max-depth */\n// TODO merge with icon-layer/icon-manager\nimport {log} from '@deck.gl/core';\nimport type {NumericArray} from '@math.gl/core';\n\nconst MISSING_CHAR_WIDTH = 32;\nconst SINGLE_LINE = [];\n\nexport type Character = {\n x: number;\n y: number;\n width: number;\n height: number;\n anchorX: number;\n anchorY: number;\n advance: number;\n};\n\nexport type CharacterMapping = Record;\n\nexport function nextPowOfTwo(number: number): number {\n return Math.pow(2, Math.ceil(Math.log2(number)));\n}\n\n/**\n * Generate character mapping table or update from an existing mapping table\n */\nexport function buildMapping({\n characterSet,\n measureText,\n buffer,\n maxCanvasWidth,\n mapping = {},\n xOffset = 0,\n yOffsetMin = 0,\n yOffsetMax = 0\n}: {\n /** list of characters */\n characterSet: Set;\n /** function to get width of each character */\n measureText: (char: string) => {advance: number; width: number; ascent: number; descent: number};\n /** bleeding buffer surround each character */\n buffer: number;\n /** max width of font atlas */\n maxCanvasWidth: number;\n /** cached mapping table */\n mapping?: CharacterMapping;\n /** x position of last character in the existing mapping table */\n xOffset?: number;\n /** y position of last character in the existing mapping table */\n yOffsetMin?: number;\n /** bottom position of any character in the existing mapping table */\n yOffsetMax?: number;\n}): {\n /** new mapping table */\n mapping: CharacterMapping;\n /** x position of last character in the new mapping table */\n xOffset: number;\n /** y position of last character in the new mapping table */\n yOffsetMin: number;\n /** bottom position of any character in the new mapping table */\n yOffsetMax: number;\n /** height of the font atlas canvas, power of 2 */\n canvasHeight: number;\n} {\n const row = 0;\n // continue from x position of last character in the old mapping\n let x = xOffset;\n let yMin = yOffsetMin;\n let yMax = yOffsetMax;\n\n for (const char of characterSet) {\n if (!mapping[char]) {\n // measure texts\n const {advance, width, ascent, descent} = measureText(char);\n const height = ascent + descent;\n\n if (x + width + buffer * 2 > maxCanvasWidth) {\n x = 0;\n yMin = yMax;\n }\n mapping[char] = {\n x: x + buffer,\n y: yMin + buffer,\n width,\n height,\n advance,\n anchorX: width / 2,\n anchorY: ascent\n };\n x += width + buffer * 2;\n yMax = Math.max(yMax, yMin + height + buffer * 2);\n }\n }\n\n return {\n mapping,\n xOffset: x,\n yOffsetMin: yMin,\n yOffsetMax: yMax,\n canvasHeight: nextPowOfTwo(yMax)\n };\n}\n\nfunction getTextWidth(\n text: string[],\n startIndex: number,\n endIndex: number,\n mapping: CharacterMapping\n): number {\n let width = 0;\n for (let i = startIndex; i < endIndex; i++) {\n const character = text[i];\n width += mapping[character]?.advance || 0;\n }\n\n return width;\n}\n\nfunction breakAll(\n text: string[],\n startIndex: number,\n endIndex: number,\n maxWidth: number,\n iconMapping: CharacterMapping,\n target: number[]\n): number {\n let rowStartCharIndex = startIndex;\n let rowOffsetLeft = 0;\n\n for (let i = startIndex; i < endIndex; i++) {\n // 2. figure out where to break lines\n const textWidth = getTextWidth(text, i, i + 1, iconMapping);\n if (rowOffsetLeft + textWidth > maxWidth) {\n if (rowStartCharIndex < i) {\n target.push(i);\n }\n rowStartCharIndex = i;\n rowOffsetLeft = 0;\n }\n rowOffsetLeft += textWidth;\n }\n\n return rowOffsetLeft;\n}\n\nfunction breakWord(\n text: string[],\n startIndex: number,\n endIndex: number,\n maxWidth: number,\n iconMapping: CharacterMapping,\n target: number[]\n): number {\n let rowStartCharIndex = startIndex;\n let groupStartCharIndex = startIndex;\n let groupEndCharIndex = startIndex;\n let rowOffsetLeft = 0;\n\n for (let i = startIndex; i < endIndex; i++) {\n // 1. break text into word groups\n // - if current char is white space\n // - else if next char is white space\n // - else if reach last char\n if (text[i] === ' ') {\n groupEndCharIndex = i + 1;\n } else if (text[i + 1] === ' ' || i + 1 === endIndex) {\n groupEndCharIndex = i + 1;\n }\n\n if (groupEndCharIndex > groupStartCharIndex) {\n // 2. break text into next row at maxWidth\n let groupWidth = getTextWidth(text, groupStartCharIndex, groupEndCharIndex, iconMapping);\n if (rowOffsetLeft + groupWidth > maxWidth) {\n if (rowStartCharIndex < groupStartCharIndex) {\n target.push(groupStartCharIndex);\n rowStartCharIndex = groupStartCharIndex;\n rowOffsetLeft = 0;\n }\n\n // if a single text group is bigger than maxWidth, then `break-all`\n if (groupWidth > maxWidth) {\n groupWidth = breakAll(\n text,\n groupStartCharIndex,\n groupEndCharIndex,\n maxWidth,\n iconMapping,\n target\n );\n // move reference to last row\n rowStartCharIndex = target[target.length - 1];\n }\n }\n groupStartCharIndex = groupEndCharIndex;\n rowOffsetLeft += groupWidth;\n }\n }\n\n return rowOffsetLeft;\n}\n\n/**\n * Wrap the given text so that each line does not exceed the given max width.\n * Returns a list of indices where line breaks should be inserted.\n */\nexport function autoWrapping(\n text: string[],\n wordBreak: 'break-all' | 'break-word',\n maxWidth: number,\n iconMapping: CharacterMapping,\n startIndex: number = 0,\n endIndex: number\n): number[] {\n if (endIndex === undefined) {\n endIndex = text.length;\n }\n const result = [];\n if (wordBreak === 'break-all') {\n breakAll(text, startIndex, endIndex, maxWidth, iconMapping, result);\n } else {\n breakWord(text, startIndex, endIndex, maxWidth, iconMapping, result);\n }\n return result;\n}\n\nfunction transformRow(\n line: string[],\n startIndex: number,\n endIndex: number,\n iconMapping: CharacterMapping,\n leftOffsets: number[],\n rowSize: [number, number]\n) {\n let x = 0;\n let rowHeight = 0;\n\n for (let i = startIndex; i < endIndex; i++) {\n const character = line[i];\n const frame = iconMapping[character];\n if (frame) {\n rowHeight = Math.max(rowHeight, frame.height);\n }\n }\n\n for (let i = startIndex; i < endIndex; i++) {\n const character = line[i];\n const frame = iconMapping[character];\n if (frame) {\n leftOffsets[i] = x + frame.anchorX;\n x += frame.advance;\n } else {\n log.warn(`Missing character: ${character} (${character.codePointAt(0)})`)();\n leftOffsets[i] = x;\n x += MISSING_CHAR_WIDTH;\n }\n }\n\n rowSize[0] = x;\n rowSize[1] = rowHeight;\n}\n\n/**\n * Transform a text paragraph to an array of characters, each character contains\n */\nexport function transformParagraph(\n paragraph: string,\n /** font property - distance from baseline to vertical center */\n baselineOffset: number,\n /** line-height in pixels */\n lineHeight: number,\n /** CSS word-break option */\n wordBreak: 'break-word' | 'break-all',\n /** CSS max-width */\n maxWidth: number,\n /** character mapping table for retrieving a character from font atlas */\n iconMapping: CharacterMapping\n): {\n /** x position of each character */\n x: number[];\n /** y position of each character */\n y: number[];\n /** the current row width of each character */\n rowWidth: number[];\n /** the width and height of the paragraph */\n size: [number, number];\n} {\n // Break into an array of characters\n // When dealing with double-length unicode characters, `str.length` or `str[i]` do not work\n const characters = Array.from(paragraph);\n const numCharacters = characters.length;\n const x = new Array(numCharacters) as number[];\n const y = new Array(numCharacters) as number[];\n const rowWidth = new Array(numCharacters) as number[];\n const autoWrappingEnabled =\n (wordBreak === 'break-word' || wordBreak === 'break-all') && isFinite(maxWidth) && maxWidth > 0;\n\n // maxWidth and height of the paragraph\n const size: [number, number] = [0, 0];\n const rowSize: [number, number] = [0, 0];\n let rowCount = 0;\n let rowOffsetTop = baselineOffset + lineHeight / 2; // this places the top of the first row at 0\n let lineStartIndex = 0;\n let lineEndIndex = 0;\n\n for (let i = 0; i <= numCharacters; i++) {\n const char = characters[i];\n if (char === '\\n' || i === numCharacters) {\n lineEndIndex = i;\n }\n\n if (lineEndIndex > lineStartIndex) {\n const rows = autoWrappingEnabled\n ? autoWrapping(characters, wordBreak, maxWidth, iconMapping, lineStartIndex, lineEndIndex)\n : SINGLE_LINE;\n\n for (let rowIndex = 0; rowIndex <= rows.length; rowIndex++) {\n const rowStart = rowIndex === 0 ? lineStartIndex : rows[rowIndex - 1];\n const rowEnd = rowIndex < rows.length ? rows[rowIndex] : lineEndIndex;\n\n transformRow(characters, rowStart, rowEnd, iconMapping, x, rowSize);\n for (let j = rowStart; j < rowEnd; j++) {\n y[j] = rowOffsetTop;\n rowWidth[j] = rowSize[0];\n }\n\n rowCount++;\n rowOffsetTop += lineHeight;\n size[0] = Math.max(size[0], rowSize[0]);\n }\n lineStartIndex = lineEndIndex;\n }\n\n if (char === '\\n') {\n // Make sure result.length matches paragraph.length\n x[lineStartIndex] = 0;\n y[lineStartIndex] = 0;\n rowWidth[lineStartIndex] = 0;\n lineStartIndex++;\n }\n }\n\n // last row\n size[1] = rowCount * lineHeight;\n return {x, y, rowWidth, size};\n}\n\nexport function getTextFromBuffer({\n value,\n length,\n stride,\n offset,\n startIndices,\n characterSet\n}: {\n value: Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array;\n length: number;\n stride?: number;\n offset?: number;\n startIndices: NumericArray;\n characterSet?: Set;\n}): {\n texts: string[];\n characterCount: number;\n} {\n const bytesPerElement = value.BYTES_PER_ELEMENT;\n const elementStride = stride ? stride / bytesPerElement : 1;\n const elementOffset = offset ? offset / bytesPerElement : 0;\n const characterCount =\n startIndices[length] || Math.ceil((value.length - elementOffset) / elementStride);\n const autoCharacterSet = characterSet && new Set();\n\n const texts = new Array(length);\n\n let codes = value;\n if (elementStride > 1 || elementOffset > 0) {\n const ArrayType = value.constructor as\n | Uint8ArrayConstructor\n | Uint8ClampedArrayConstructor\n | Uint16ArrayConstructor\n | Uint32ArrayConstructor;\n codes = new ArrayType(characterCount);\n for (let i = 0; i < characterCount; i++) {\n codes[i] = value[i * elementStride + elementOffset];\n }\n }\n\n for (let index = 0; index < length; index++) {\n const startIndex = startIndices[index];\n const endIndex = startIndices[index + 1] || characterCount;\n const codesAtIndex = codes.subarray(startIndex, endIndex);\n // @ts-ignore TS wants the argument to be number[] but typed array works too\n texts[index] = String.fromCodePoint.apply(null, codesAtIndex);\n if (autoCharacterSet) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n codesAtIndex.forEach(autoCharacterSet.add, autoCharacterSet);\n }\n }\n\n if (autoCharacterSet) {\n for (const charCode of autoCharacterSet) {\n characterSet.add(String.fromCodePoint(charCode));\n }\n }\n\n return {texts, characterCount};\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/**\n * LRU Cache class with limit\n *\n * Update order for each get/set operation\n * Delete oldest when reach given limit\n */\n\nexport default class LRUCache {\n private limit: number;\n private _cache: Record = {};\n /** access/update order, first item is oldest, last item is newest */\n private _order: string[] = [];\n\n constructor(limit: number = 5) {\n this.limit = limit;\n }\n\n get(key: string): ValueT {\n const value = this._cache[key];\n if (value) {\n // update order\n this._deleteOrder(key);\n this._appendOrder(key);\n }\n return value;\n }\n\n set(key: string, value: ValueT): void {\n if (!this._cache[key]) {\n // if reach limit, delete the oldest\n if (Object.keys(this._cache).length === this.limit) {\n this.delete(this._order[0]);\n }\n\n this._cache[key] = value;\n this._appendOrder(key);\n } else {\n // if found in cache, delete the old one, insert new one to the first of list\n this.delete(key);\n\n this._cache[key] = value;\n this._appendOrder(key);\n }\n }\n\n delete(key: string): void {\n const value = this._cache[key];\n if (value) {\n delete this._cache[key];\n this._deleteOrder(key);\n }\n }\n\n private _deleteOrder(key: string): void {\n const index = this._order.indexOf(key);\n if (index >= 0) {\n this._order.splice(index, 1);\n }\n }\n\n private _appendOrder(key: string): void {\n this._order.push(key);\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/* global document */\nimport TinySDF from '@mapbox/tiny-sdf';\n\nimport {log} from '@deck.gl/core';\n\nimport {buildMapping, CharacterMapping} from './utils';\nimport LRUCache from './lru-cache';\n\n// import type {Texture} from '@deck.gl/core';\n\nfunction getDefaultCharacterSet() {\n const charSet: string[] = [];\n for (let i = 32; i < 128; i++) {\n charSet.push(String.fromCharCode(i));\n }\n return charSet;\n}\n\nexport interface FontRenderer {\n /**\n * Measure the dimensions of a given character. If no parameter is passed, returns the bounding metrics of the font.\n *\n * Returned metrics:\n * - `advance`: horizontal distance to move the cursor before placing the next glyph, in pixels.\n * - `width`: width of the visible glyph bounds, in pixels.\n * - `ascent`: distance from the baseline to the top of the glyph, in pixels.\n * - `descent`: distance from the baseline to the bottom of the glyph, in pixels.\n */\n measure(char?: string): {\n advance: number;\n width: number;\n ascent: number;\n descent: number;\n };\n /**\n * Render the given character to an image.\n *\n * Returned image data:\n * - `data`: rasterized glyph pixels.\n * - `left`: x offset from the glyph origin to the left edge of `data`, in pixels. Default `0`.\n * - `top`: y offset from the glyph origin to the top edge of `data`, in pixels. Default `0`.\n */\n draw(char: string): {\n data: ImageData;\n left?: number;\n top?: number;\n };\n}\n\nexport type FontSettings = {\n /** CSS font family\n * @default 'Monaco, monospace'\n */\n fontFamily?: string;\n /** CSS font weight\n * @default 'normal'\n */\n fontWeight?: string | number;\n /** Specifies a list of characters to include in the font.\n * @default (ASCII characters 32-128)\n */\n characterSet?: Set | string[] | string;\n /** Font size in pixels. This option is only applied for generating `fontAtlas`, it does not impact the size of displayed text labels. Larger `fontSize` will give you a sharper look when rendering text labels with very large font sizes. But larger `fontSize` requires more time and space to generate the `fontAtlas`.\n * @default 64\n */\n fontSize?: number;\n /** Whitespace buffer around each side of the character. In general, bigger `fontSize` requires bigger `buffer`. Increase `buffer` will add more space between each character when layout `characterSet` in `fontAtlas`. This option could be tuned to provide sufficient space for drawing each character and avoiding overlapping of neighboring characters.\n * @default 4\n */\n buffer?: number;\n /** Flag to enable / disable `sdf`. [`sdf` (Signed Distance Fields)](http://cs.brown.edu/people/pfelzens/papers/dt-final.pdf) will provide a sharper look when rendering with very large or small font sizes. `TextLayer` integrates with [`TinySDF`](https://github.com/mapbox/tiny-sdf) which implements the `sdf` algorithm.\n * @default false\n */\n sdf?: boolean;\n /** How much of the radius (relative) is used for the inside part the glyph. Bigger `cutoff` makes character thinner. Smaller `cutoff` makes character look thicker. Only applies when `sdf: true`.\n * @default 0.25\n */\n cutoff?: number;\n /** How many pixels around the glyph shape to use for encoding distance. Bigger radius yields higher quality outcome. Only applies when `sdf: true`.\n * @default 12\n */\n radius?: number;\n /** How much smoothing to apply to the text edges. Only applies when `sdf: true`.\n * @default 0.1\n */\n smoothing?: number;\n};\n\nexport const DEFAULT_FONT_SETTINGS: Required = {\n fontFamily: 'Monaco, monospace',\n fontWeight: 'normal',\n characterSet: getDefaultCharacterSet(),\n fontSize: 64,\n buffer: 4,\n sdf: false,\n cutoff: 0.25,\n radius: 12,\n smoothing: 0.1\n};\n\nconst MAX_CANVAS_WIDTH = 1024;\n\nconst DEFAULT_ASCENT = 0.9;\nconst DEFAULT_DESCENT = 0.3;\n\n// only preserve latest three fontAtlas\nconst CACHE_LIMIT = 3;\n\ntype FontAtlas = {\n baselineOffset: number;\n /** x position of last character in mapping */\n xOffset: number;\n /** y position of last character in mapping */\n yOffsetMin: number;\n /** bottom position of any character in mapping */\n yOffsetMax: number;\n /** bounding box of each character in the texture */\n mapping: CharacterMapping;\n /** packed texture */\n data: HTMLCanvasElement;\n /** texture width */\n width: number;\n /** texture height */\n height: number;\n};\n\nlet cache = new LRUCache(CACHE_LIMIT);\n\n/**\n * get all the chars not in cache\n * @returns chars not in cache\n */\nfunction getNewChars(cacheKey: string, characterSet: Set | string[] | string): Set {\n let newCharSet: Set;\n if (typeof characterSet === 'string') {\n newCharSet = new Set(Array.from(characterSet));\n } else {\n newCharSet = new Set(characterSet);\n }\n\n const cachedFontAtlas = cache.get(cacheKey);\n if (!cachedFontAtlas) {\n return newCharSet;\n }\n\n for (const char in cachedFontAtlas.mapping) {\n if (newCharSet.has(char)) {\n newCharSet.delete(char);\n }\n }\n return newCharSet;\n}\n\nfunction populateAlphaChannel(\n alphaChannel: Uint8ClampedArray | Uint8Array,\n imageData: ImageData\n): void {\n // populate distance value from tinySDF to image alpha channel\n for (let i = 0; i < alphaChannel.length; i++) {\n imageData.data[4 * i + 3] = alphaChannel[i];\n }\n}\n\nfunction setTextStyle(\n ctx: CanvasRenderingContext2D,\n fontFamily: string,\n fontSize: number,\n fontWeight: string | number\n): void {\n ctx.font = `${fontWeight} ${fontSize}px ${fontFamily}`;\n ctx.fillStyle = '#000';\n ctx.textBaseline = 'alphabetic';\n ctx.textAlign = 'left';\n}\n\nfunction measureText(\n ctx: CanvasRenderingContext2D,\n fontSize: number,\n char: string | undefined\n): {advance: number; width: number; ascent: number; descent: number} {\n if (char === undefined) {\n const fontMetrics = ctx.measureText('A');\n if (fontMetrics.fontBoundingBoxAscent) {\n return {\n advance: 0,\n width: 0,\n ascent: Math.ceil(fontMetrics.fontBoundingBoxAscent),\n descent: Math.ceil(fontMetrics.fontBoundingBoxDescent)\n };\n }\n return {\n advance: 0,\n width: 0,\n ascent: fontSize * DEFAULT_ASCENT,\n descent: fontSize * DEFAULT_DESCENT\n };\n }\n\n const metrics = ctx.measureText(char);\n if (!metrics.actualBoundingBoxAscent) {\n // TextMetrics not fully supported\n return {\n advance: metrics.width,\n width: metrics.width,\n ascent: fontSize * DEFAULT_ASCENT,\n descent: fontSize * DEFAULT_DESCENT\n };\n }\n return {\n advance: metrics.width,\n width: Math.ceil(metrics.actualBoundingBoxRight - metrics.actualBoundingBoxLeft),\n ascent: Math.ceil(metrics.actualBoundingBoxAscent),\n descent: Math.ceil(metrics.actualBoundingBoxDescent)\n };\n}\n\n/**\n * Sets the Font Atlas LRU Cache Limit\n * @param {number} limit LRU Cache limit\n */\nexport function setFontAtlasCacheLimit(limit: number): void {\n log.assert(Number.isFinite(limit) && limit >= CACHE_LIMIT, 'Invalid cache limit');\n\n cache = new LRUCache(limit);\n}\n\nexport default class FontAtlasManager {\n /** Font settings */\n props: Required = {...DEFAULT_FONT_SETTINGS};\n\n /** Cache key of the current font atlas */\n private _key?: string;\n /** The current font atlas */\n private _atlas?: FontAtlas;\n\n private _getFontRenderer?: (settings: Required) => FontRenderer;\n\n get atlas(): Readonly | undefined {\n return this._atlas;\n }\n\n // TODO - cut during v9 porting as types reveal this is not correct\n // get texture(): Texture | undefined {\n // return this._atlas;\n // }\n\n get mapping(): CharacterMapping | undefined {\n return this._atlas && this._atlas.mapping;\n }\n\n setProps(\n props: FontSettings & {\n _getFontRenderer?: (settings: Required) => FontRenderer;\n } = {}\n ) {\n Object.assign(this.props, props);\n if (props._getFontRenderer) {\n this._getFontRenderer = props._getFontRenderer;\n }\n\n // update cache key\n this._key = this._getKey();\n\n const charSet = getNewChars(this._key, this.props.characterSet);\n const cachedFontAtlas = cache.get(this._key);\n\n // if a fontAtlas associated with the new settings is cached and\n // there are no new chars\n if (cachedFontAtlas && charSet.size === 0) {\n // update texture with cached fontAtlas\n if (this._atlas !== cachedFontAtlas) {\n this._atlas = cachedFontAtlas;\n }\n return;\n }\n\n // update fontAtlas with new settings\n const fontAtlas = this._generateFontAtlas(charSet, cachedFontAtlas);\n this._atlas = fontAtlas;\n\n // update cache\n cache.set(this._key, fontAtlas);\n }\n\n // eslint-disable-next-line max-statements\n private _generateFontAtlas(characterSet: Set, cachedFontAtlas?: FontAtlas): FontAtlas {\n const {fontFamily, fontWeight, fontSize, buffer, sdf, radius, cutoff} = this.props;\n let canvas = cachedFontAtlas && cachedFontAtlas.data;\n if (!canvas) {\n canvas = document.createElement('canvas');\n canvas.width = MAX_CANVAS_WIDTH;\n }\n const ctx = canvas.getContext('2d', {willReadFrequently: true})!;\n setTextStyle(ctx, fontFamily, fontSize, fontWeight);\n const defaultMeasure = (char?: string) => measureText(ctx, fontSize, char);\n\n let renderer: FontRenderer | undefined;\n if (this._getFontRenderer) {\n renderer = this._getFontRenderer(this.props);\n } else if (sdf) {\n renderer = {\n measure: defaultMeasure,\n draw: getSdfFontRenderer(this.props)\n };\n }\n\n // 1. build mapping\n const {mapping, canvasHeight, xOffset, yOffsetMin, yOffsetMax} = buildMapping({\n measureText: char => (renderer ? renderer.measure(char) : defaultMeasure(char)),\n buffer,\n characterSet,\n maxCanvasWidth: MAX_CANVAS_WIDTH,\n ...(cachedFontAtlas && {\n mapping: cachedFontAtlas.mapping,\n xOffset: cachedFontAtlas.xOffset,\n yOffsetMin: cachedFontAtlas.yOffsetMin,\n yOffsetMax: cachedFontAtlas.yOffsetMax\n })\n });\n\n // 2. update canvas\n // copy old canvas data to new canvas only when height changed\n if (canvas.height !== canvasHeight) {\n const imageData =\n canvas.height > 0 ? ctx.getImageData(0, 0, canvas.width, canvas.height) : null;\n canvas.height = canvasHeight;\n if (imageData) {\n ctx.putImageData(imageData, 0, 0);\n }\n }\n setTextStyle(ctx, fontFamily, fontSize, fontWeight);\n\n // 3. layout characters\n if (renderer) {\n for (const char of characterSet) {\n const frame = mapping[char];\n const {data, left = 0, top = 0} = renderer.draw(char);\n const x = frame.x - left;\n const y = frame.y - top;\n // snap origin to the nearest pixel\n const x0 = Math.max(0, Math.round(x));\n const y0 = Math.max(0, Math.round(y));\n const w = Math.min(data.width, canvas.width - x0);\n const h = Math.min(data.height, canvas.height - y0);\n ctx.putImageData(data, x0, y0, 0, 0, w, h);\n\n frame.x += x0 - x;\n frame.y += y0 - y;\n }\n } else {\n for (const char of characterSet) {\n const frame = mapping[char];\n ctx.fillText(char, frame.x, frame.y + frame.anchorY);\n }\n }\n\n const fontMetrics = renderer ? renderer.measure() : defaultMeasure();\n\n return {\n baselineOffset: (fontMetrics.ascent - fontMetrics.descent) / 2,\n xOffset,\n yOffsetMin,\n yOffsetMax,\n mapping,\n data: canvas,\n width: canvas.width,\n height: canvas.height\n };\n }\n\n private _getKey(): string {\n const {fontFamily, fontWeight, fontSize, buffer, sdf, radius, cutoff} = this.props;\n if (sdf) {\n return `${fontFamily} ${fontWeight} ${fontSize} ${buffer} ${radius} ${cutoff}`;\n }\n return `${fontFamily} ${fontWeight} ${fontSize} ${buffer}`;\n }\n}\n\nfunction getSdfFontRenderer({\n fontSize,\n buffer,\n radius,\n cutoff,\n fontFamily,\n fontWeight\n}: Required): FontRenderer['draw'] {\n const tinySDF = new TinySDF({\n fontSize,\n buffer,\n radius,\n cutoff,\n fontFamily,\n fontWeight: `${fontWeight}`\n });\n\n return (char: string) => {\n const {data, width, height} = tinySDF.draw(char);\n const imageData = new ImageData(width, height);\n populateAlphaChannel(data, imageData);\n return {data: imageData, left: buffer, top: buffer};\n };\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ShaderModule} from '@luma.gl/shadertools';\n\nconst uniformBlock = `\\\nlayout(std140) uniform textBackgroundUniforms {\n bool billboard;\n float sizeScale;\n float sizeMinPixels;\n float sizeMaxPixels;\n vec4 borderRadius;\n vec4 padding;\n highp int sizeUnits;\n bool stroked;\n} textBackground;\n`;\n\nexport type TextBackgroundProps = {\n billboard: boolean;\n sizeScale: number;\n sizeMinPixels: number;\n sizeMaxPixels: number;\n borderRadius: Readonly<[number, number, number, number]>;\n padding: Readonly<[number, number, number, number]>;\n sizeUnits: number;\n stroked: boolean;\n};\n\nexport const textBackgroundUniforms = {\n name: 'textBackground',\n vs: uniformBlock,\n fs: uniformBlock,\n uniformTypes: {\n billboard: 'f32',\n sizeScale: 'f32',\n sizeMinPixels: 'f32',\n sizeMaxPixels: 'f32',\n borderRadius: 'vec4',\n padding: 'vec4',\n sizeUnits: 'i32',\n stroked: 'f32'\n }\n} as const satisfies ShaderModule;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport default /* glsl */ `\\\n#version 300 es\n#define SHADER_NAME text-background-layer-vertex-shader\n\nin vec2 positions;\n\nin vec3 instancePositions;\nin vec3 instancePositions64Low;\nin vec4 instanceRects;\nin vec4 instanceClipRect;\nin float instanceSizes;\nin float instanceAngles;\nin vec2 instancePixelOffsets;\nin float instanceLineWidths;\nin vec4 instanceFillColors;\nin vec4 instanceLineColors;\nin vec3 instancePickingColors;\n\nout vec4 vFillColor;\nout vec4 vLineColor;\nout float vLineWidth;\nout vec2 uv;\nout vec2 dimensions;\n\nvec2 rotate_by_angle(vec2 vertex, float angle) {\n float angle_radian = radians(angle);\n float cos_angle = cos(angle_radian);\n float sin_angle = sin(angle_radian);\n mat2 rotationMatrix = mat2(cos_angle, -sin_angle, sin_angle, cos_angle);\n return rotationMatrix * vertex;\n}\n\nvoid main(void) {\n geometry.worldPosition = instancePositions;\n geometry.uv = positions;\n geometry.pickingColor = instancePickingColors;\n uv = positions;\n vLineWidth = instanceLineWidths;\n\n // convert size in meters to pixels, then scaled and clamp\n\n // project meters to pixels and clamp to limits\n float sizePixels = clamp(\n project_size_to_pixel(instanceSizes * textBackground.sizeScale, textBackground.sizeUnits),\n textBackground.sizeMinPixels, textBackground.sizeMaxPixels\n );\n float instanceScale = sizePixels / text.fontSize;\n\n dimensions = instanceRects.zw * instanceScale + textBackground.padding.xy + textBackground.padding.zw;\n\n vec2 pixelOffset = (positions * instanceRects.zw + instanceRects.xy) * instanceScale + mix(-textBackground.padding.xy, textBackground.padding.zw, positions);\n pixelOffset = rotate_by_angle(pixelOffset, instanceAngles);\n pixelOffset += instancePixelOffsets;\n pixelOffset.y *= -1.0;\n\n // apply clipping\n vec2 xy = project_size_to_pixel(instanceClipRect.xy);\n vec2 wh = project_size_to_pixel(instanceClipRect.zw);\n if (text.flipY) {\n xy.y = -xy.y - wh.y;\n }\n if (instanceClipRect.z >= 0.0) {\n dimensions.x = wh.x;\n pixelOffset.x = xy.x + uv.x * wh.x + mix(-textBackground.padding.x, textBackground.padding.z, uv.x);\n }\n if (instanceClipRect.w >= 0.0) {\n dimensions.y = wh.y;\n pixelOffset.y = xy.y + uv.y * wh.y + mix(-textBackground.padding.y, textBackground.padding.w, uv.y);\n }\n\n if (textBackground.billboard) {\n gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0), geometry.position);\n DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n vec3 offset = vec3(pixelOffset, 0.0);\n DECKGL_FILTER_SIZE(offset, geometry);\n gl_Position.xy += project_pixel_size_to_clipspace(offset.xy);\n } else {\n vec3 offset_common = vec3(project_pixel_size(pixelOffset), 0.0);\n if (text.flipY) {\n offset_common.y *= -1.;\n }\n DECKGL_FILTER_SIZE(offset_common, geometry);\n gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset_common, geometry.position);\n DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n }\n\n // Apply opacity to instance color, or return instance picking color\n vFillColor = vec4(instanceFillColors.rgb, instanceFillColors.a * layer.opacity);\n DECKGL_FILTER_COLOR(vFillColor, geometry);\n vLineColor = vec4(instanceLineColors.rgb, instanceLineColors.a * layer.opacity);\n DECKGL_FILTER_COLOR(vLineColor, geometry);\n}\n`;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport default `\\\n#version 300 es\n#define SHADER_NAME text-background-layer-fragment-shader\n\nprecision highp float;\n\nin vec4 vFillColor;\nin vec4 vLineColor;\nin float vLineWidth;\nin vec2 uv;\nin vec2 dimensions;\n\nout vec4 fragColor;\n\nfloat round_rect(vec2 p, vec2 size, vec4 radii) {\n // Convert p and size to center-based coordinates [-0.5, 0.5]\n vec2 pixelPositionCB = (p - 0.5) * size;\n vec2 sizeCB = size * 0.5;\n\n float maxBorderRadius = min(size.x, size.y) * 0.5;\n vec4 borderRadius = vec4(min(radii, maxBorderRadius));\n\n // from https://www.shadertoy.com/view/4llXD7\n borderRadius.xy =\n (pixelPositionCB.x > 0.0) ? borderRadius.xy : borderRadius.zw;\n borderRadius.x = (pixelPositionCB.y > 0.0) ? borderRadius.x : borderRadius.y;\n vec2 q = abs(pixelPositionCB) - sizeCB + borderRadius.x;\n return -(min(max(q.x, q.y), 0.0) + length(max(q, 0.0)) - borderRadius.x);\n}\n\nfloat rect(vec2 p, vec2 size) {\n vec2 pixelPosition = p * size;\n return min(min(pixelPosition.x, size.x - pixelPosition.x),\n min(pixelPosition.y, size.y - pixelPosition.y));\n}\n\nvec4 get_stroked_fragColor(float dist) {\n float isBorder = smoothedge(dist, vLineWidth);\n return mix(vFillColor, vLineColor, isBorder);\n}\n\nvoid main(void) {\n geometry.uv = uv;\n\n if (textBackground.borderRadius != vec4(0.0)) {\n float distToEdge = round_rect(uv, dimensions, textBackground.borderRadius);\n float shapeAlpha = smoothedge(-distToEdge, 0.0);\n if (shapeAlpha == 0.0) {\n discard;\n }\n if (textBackground.stroked) {\n fragColor = get_stroked_fragColor(distToEdge);\n } else {\n fragColor = vFillColor;\n }\n fragColor.a *= shapeAlpha;\n } else {\n if (textBackground.stroked) {\n float distToEdge = rect(uv, dimensions);\n fragColor = get_stroked_fragColor(distToEdge);\n } else {\n fragColor = vFillColor;\n }\n }\n DECKGL_FILTER_COLOR(fragColor, geometry);\n}\n`;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Layer, project32, picking, UNIT} from '@deck.gl/core';\nimport {Geometry} from '@luma.gl/engine';\nimport {Model} from '@luma.gl/engine';\n\nimport {TextBackgroundProps, textBackgroundUniforms} from './text-background-layer-uniforms';\nimport {TextModuleProps, textUniforms} from '../text-uniforms';\nimport vs from './text-background-layer-vertex.glsl';\nimport fs from './text-background-layer-fragment.glsl';\n\nimport type {\n LayerProps,\n LayerDataSource,\n Accessor,\n Unit,\n Position,\n Color,\n UpdateParameters,\n DefaultProps\n} from '@deck.gl/core';\n\ntype _TextBackgroundLayerProps = {\n data: LayerDataSource;\n billboard?: boolean;\n sizeScale?: number;\n sizeUnits?: Unit;\n sizeMinPixels?: number;\n sizeMaxPixels?: number;\n fontSize?: number;\n\n borderRadius?: number | Readonly<[number, number, number, number]>;\n padding?: Readonly<[number, number]> | Readonly<[number, number, number, number]>;\n\n getPosition?: Accessor;\n getSize?: Accessor;\n getAngle?: Accessor;\n getPixelOffset?: Accessor>;\n getBoundingRect?: Accessor>;\n getClipRect?: Accessor;\n getFillColor?: Accessor;\n getLineColor?: Accessor;\n getLineWidth?: Accessor;\n};\n\nexport type TextBackgroundLayerProps = _TextBackgroundLayerProps &\n LayerProps;\n\nconst defaultProps: DefaultProps = {\n billboard: true,\n sizeScale: 1,\n sizeUnits: 'pixels',\n sizeMinPixels: 0,\n sizeMaxPixels: Number.MAX_SAFE_INTEGER,\n fontSize: 1,\n\n borderRadius: {type: 'object', value: 0},\n padding: {type: 'array', value: [0, 0, 0, 0]},\n\n getPosition: {type: 'accessor', value: (x: any) => x.position},\n getSize: {type: 'accessor', value: 1},\n getAngle: {type: 'accessor', value: 0},\n getPixelOffset: {type: 'accessor', value: [0, 0]},\n getBoundingRect: {type: 'accessor', value: [0, 0, 0, 0]},\n getClipRect: {type: 'accessor', value: [0, 0, -1, -1]},\n getFillColor: {type: 'accessor', value: [0, 0, 0, 255]},\n getLineColor: {type: 'accessor', value: [0, 0, 0, 255]},\n getLineWidth: {type: 'accessor', value: 1}\n};\n\nexport default class TextBackgroundLayer extends Layer<\n ExtraPropsT & Required<_TextBackgroundLayerProps>\n> {\n static defaultProps = defaultProps;\n static layerName = 'TextBackgroundLayer';\n\n state!: {\n model?: Model;\n };\n\n getShaders() {\n return super.getShaders({\n vs,\n fs,\n modules: [project32, picking, textBackgroundUniforms, textUniforms]\n });\n }\n\n initializeState() {\n this.getAttributeManager()!.addInstanced({\n instancePositions: {\n size: 3,\n type: 'float64',\n fp64: this.use64bitPositions(),\n transition: true,\n accessor: 'getPosition'\n },\n instanceSizes: {\n size: 1,\n transition: true,\n accessor: 'getSize',\n defaultValue: 1\n },\n instanceAngles: {\n size: 1,\n transition: true,\n accessor: 'getAngle'\n },\n instanceRects: {\n size: 4,\n accessor: 'getBoundingRect'\n },\n instanceClipRect: {\n size: 4,\n accessor: 'getClipRect',\n defaultValue: [0, 0, -1, -1]\n },\n instancePixelOffsets: {\n size: 2,\n transition: true,\n accessor: 'getPixelOffset'\n },\n instanceFillColors: {\n size: 4,\n transition: true,\n type: 'unorm8',\n accessor: 'getFillColor',\n defaultValue: [0, 0, 0, 255]\n },\n instanceLineColors: {\n size: 4,\n transition: true,\n type: 'unorm8',\n accessor: 'getLineColor',\n defaultValue: [0, 0, 0, 255]\n },\n instanceLineWidths: {\n size: 1,\n transition: true,\n accessor: 'getLineWidth',\n defaultValue: 1\n }\n });\n }\n\n updateState(params: UpdateParameters) {\n super.updateState(params);\n const {changeFlags} = params;\n if (changeFlags.extensionsChanged) {\n this.state.model?.destroy();\n this.state.model = this._getModel();\n this.getAttributeManager()!.invalidateAll();\n }\n }\n\n draw({uniforms}) {\n const {billboard, sizeScale, sizeUnits, sizeMinPixels, sizeMaxPixels, getLineWidth, fontSize} =\n this.props;\n let {padding, borderRadius} = this.props;\n\n if (padding.length < 4) {\n padding = [padding[0], padding[1], padding[0], padding[1]];\n }\n\n if (!Array.isArray(borderRadius)) {\n borderRadius = [\n borderRadius as number,\n borderRadius as number,\n borderRadius as number,\n borderRadius as number\n ];\n }\n\n const model = this.state.model!;\n const textBackgroundProps: TextBackgroundProps = {\n billboard,\n stroked: Boolean(getLineWidth),\n borderRadius: borderRadius as [number, number, number, number],\n padding: padding as [number, number, number, number],\n sizeUnits: UNIT[sizeUnits],\n sizeScale,\n sizeMinPixels,\n sizeMaxPixels\n };\n const textProps: TextModuleProps = {\n fontSize,\n viewport: this.context.viewport\n };\n model.shaderInputs.setProps({textBackground: textBackgroundProps, text: textProps});\n model.draw(this.context.renderPass);\n }\n\n protected _getModel(): Model {\n // a square that minimally cover the unit circle\n const positions = [0, 0, 1, 0, 0, 1, 1, 1];\n\n return new Model(this.context.device, {\n ...this.getShaders(),\n id: this.props.id,\n bufferLayout: this.getAttributeManager()!.getBufferLayouts(),\n geometry: new Geometry({\n topology: 'triangle-strip',\n vertexCount: 4,\n attributes: {\n positions: {size: 2, value: new Float32Array(positions)}\n }\n }),\n isInstanced: true\n });\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {CompositeLayer, createIterable, log} from '@deck.gl/core';\nimport MultiIconLayer from './multi-icon-layer/multi-icon-layer';\nimport FontAtlasManager, {\n DEFAULT_FONT_SETTINGS,\n setFontAtlasCacheLimit\n} from './font-atlas-manager';\nimport {transformParagraph, getTextFromBuffer} from './utils';\n\nimport TextBackgroundLayer from './text-background-layer/text-background-layer';\nimport type {ContentAlignModes} from './text-uniforms';\n\nimport type {FontSettings, FontRenderer} from './font-atlas-manager';\nimport type {\n LayerProps,\n LayerDataSource,\n Accessor,\n AccessorFunction,\n AccessorContext,\n Unit,\n Position,\n Color,\n UpdateParameters,\n GetPickingInfoParams,\n PickingInfo,\n DefaultProps\n} from '@deck.gl/core';\n\nconst TEXT_ANCHOR = {\n start: 1,\n middle: 0,\n end: -1\n} as const;\n\nconst ALIGNMENT_BASELINE = {\n top: 1,\n center: 0,\n bottom: -1\n} as const;\n\nconst DEFAULT_COLOR = [0, 0, 0, 255] as const;\n\nconst DEFAULT_LINE_HEIGHT = 1.0;\n\ntype _TextLayerProps = {\n data: LayerDataSource;\n /** If `true`, the text always faces camera. Otherwise the text faces up (z).\n * @default true\n */\n billboard?: boolean;\n /**\n * Text size multiplier.\n * @default 1\n */\n sizeScale?: number;\n /**\n * The units of the size, one of `'meters'`, `'common'`, and `'pixels'`.\n * @default 'pixels'\n */\n sizeUnits?: Unit;\n /**\n * The minimum size in pixels. When using non-pixel `sizeUnits`, this prop can be used to prevent the icon from getting too small when zoomed out.\n * @default 0\n */\n sizeMinPixels?: number;\n /**\n * The maximum size in pixels. When using non-pixel `sizeUnits`, this prop can be used to prevent the icon from getting too big when zoomed in.\n * @default Number.MAX_SAFE_INTEGER\n */\n sizeMaxPixels?: number;\n\n /** Whether to render background for the text blocks.\n * @default false\n */\n background?: boolean;\n /** Background color accessor.\n * @default [255, 255, 255, 255]\n */\n getBackgroundColor?: Accessor;\n /** Border color accessor.\n * @default [0, 0, 0, 255]\n */\n getBorderColor?: Accessor;\n /** Border width accessor.\n * @default 0\n */\n getBorderWidth?: Accessor;\n /** The border radius of the background.\n * If a number is supplied, it is the same border radius in pixel for all corners.\n * If an array of 4 is supplied, it is interpreted as `[bottom_right_corner, top_right_corner, bottom_left_corner, top_left_corner]` border radius in pixel.\n * @default 0\n */\n backgroundBorderRadius?: number | Readonly<[number, number, number, number]>;\n /**\n * The padding around the text to position the background. Only effective if content box is unset.\n * If an array of 2 is supplied, it is interpreted as `[padding_x, padding_y]` in pixels.\n * If an array of 4 is supplied, it is interpreted as `[padding_left, padding_top, padding_right, padding_bottom]` in pixels.\n * @default [0, 0, 0, 0]\n */\n backgroundPadding?: Readonly<[number, number]> | Readonly<[number, number, number, number]>;\n /**\n * Specifies a list of characters to include in the font. If set to 'auto', will be automatically generated from the data set.\n * @default (ASCII characters 32-128)\n */\n characterSet?: FontSettings['characterSet'] | 'auto';\n /** CSS font family\n * @default 'Monaco, monospace'\n */\n fontFamily?: FontSettings['fontFamily'];\n /** CSS font weight\n * @default 'normal'\n */\n fontWeight?: FontSettings['fontWeight'];\n /** A unitless number that will be multiplied with the current text size to set the line height.\n * @default 'normal'\n */\n lineHeight?: number;\n /**\n * Width of outline around the text, relative to the text size. Only effective if `fontSettings.sdf` is `true`.\n * @default 0\n */\n outlineWidth?: number;\n /**\n * Color of outline around the text, in `[r, g, b, [a]]`. Each channel is a number between 0-255 and `a` is 255 if not supplied.\n * @default [0, 0, 0, 255]\n */\n outlineColor?: Color;\n /**\n * Advance options for fine tuning the appearance and performance of the generated shared `fontAtlas`.\n */\n fontSettings?: FontSettings;\n /**\n * Available options are `break-all` and `break-word`. A valid `maxWidth` has to be provided to use `wordBreak`.\n * @default 'break-word'\n */\n wordBreak?: 'break-word' | 'break-all';\n /**\n * A unitless number that will be multiplied with the current text size to set the width limit of a string.\n * If specified, when the text is longer than the width limit, it will be wrapped into multiple lines using\n * the strategy of `wordBreak`.\n * @default -1\n */\n maxWidth?: number;\n /**\n * Label text accessor\n */\n getText?: AccessorFunction;\n /**\n * Anchor position accessor\n */\n getPosition?: Accessor;\n /**\n * Label color accessor\n * @default [0, 0, 0, 255]\n */\n getColor?: Accessor;\n /**\n * Label size accessor\n * @default 32\n */\n getSize?: Accessor;\n /**\n * Label rotation accessor, in degrees\n * @default 0\n */\n getAngle?: Accessor;\n /**\n * Horizontal alignment accessor\n * @default 'middle'\n */\n getTextAnchor?: Accessor;\n /**\n * Vertical alignment accessor\n * @default 'center'\n */\n getAlignmentBaseline?: Accessor;\n /**\n * Label offset from the anchor position, [x, y] in pixels\n * @default [0, 0]\n */\n getPixelOffset?: Accessor>;\n /**\n * @deprecated Use `background` and `getBackgroundColor` instead\n */\n backgroundColor?: Color;\n\n /** Container limits for each object, as meter offsets from the anchor position.\n * Characters that overflow the area are not displayed.\n * Use negative width/height to disable clipping.\n * @default [0, 0, -1, -1]\n */\n getContentBox?: Accessor;\n\n /**\n * Minimum visible region of the content box in screen pixels. If the visible width or height is smaller than the specified cutoff, the corresponding text is hidden completely.\n * This prop can be used to set the minimum length of clipped texts to improve readability.\n * @default [0, 0]\n */\n contentCutoffPixels?: [width: number, height: number];\n\n /**\n * Align the text horizontally to the visible region of the content box.\n * @default 'none'\n */\n contentAlignHorizontal?: ContentAlignModes;\n\n /**\n * Align the text vertically to the visible region of the content box.\n * @default 'none'\n */\n contentAlignVertical?: ContentAlignModes;\n\n /**\n * Experimental.\n * Custom font rendering methods.\n */\n _getFontRenderer?: (settings: Required) => FontRenderer;\n};\n\nexport type TextLayerProps = _TextLayerProps & LayerProps;\n\nconst defaultProps: DefaultProps = {\n billboard: true,\n sizeScale: 1,\n sizeUnits: 'pixels',\n sizeMinPixels: 0,\n sizeMaxPixels: Number.MAX_SAFE_INTEGER,\n\n background: false,\n getBackgroundColor: {type: 'accessor', value: [255, 255, 255, 255]},\n getBorderColor: {type: 'accessor', value: DEFAULT_COLOR},\n getBorderWidth: {type: 'accessor', value: 0},\n backgroundBorderRadius: {type: 'object', value: 0},\n backgroundPadding: {type: 'array', value: [0, 0, 0, 0]},\n\n characterSet: {type: 'object', value: DEFAULT_FONT_SETTINGS.characterSet},\n fontFamily: DEFAULT_FONT_SETTINGS.fontFamily,\n fontWeight: DEFAULT_FONT_SETTINGS.fontWeight,\n lineHeight: DEFAULT_LINE_HEIGHT,\n outlineWidth: {type: 'number', value: 0, min: 0},\n outlineColor: {type: 'color', value: DEFAULT_COLOR},\n fontSettings: {type: 'object', value: {}, compare: 1},\n\n // auto wrapping options\n wordBreak: 'break-word',\n maxWidth: {type: 'number', value: -1},\n contentCutoffPixels: {type: 'array', value: [0, 0]},\n contentAlignHorizontal: 'none',\n contentAlignVertical: 'none',\n\n getText: {type: 'accessor', value: (x: any) => x.text},\n getPosition: {type: 'accessor', value: (x: any) => x.position},\n getColor: {type: 'accessor', value: DEFAULT_COLOR},\n getSize: {type: 'accessor', value: 32},\n getAngle: {type: 'accessor', value: 0},\n getTextAnchor: {type: 'accessor', value: 'middle'},\n getAlignmentBaseline: {type: 'accessor', value: 'center'},\n getPixelOffset: {type: 'accessor', value: [0, 0]},\n getContentBox: {type: 'accessor', value: [0, 0, -1, -1]},\n\n // deprecated\n backgroundColor: {deprecatedFor: ['background', 'getBackgroundColor']}\n};\n\n/** Render text labels at given coordinates. */\nexport default class TextLayer extends CompositeLayer<\n ExtraPropsT & Required<_TextLayerProps>\n> {\n static defaultProps = defaultProps;\n static layerName = 'TextLayer';\n\n state!: {\n styleVersion: number;\n fontAtlasManager: FontAtlasManager;\n characterSet?: Set;\n startIndices?: number[];\n numInstances?: number;\n getText?: AccessorFunction;\n };\n\n initializeState() {\n this.state = {\n styleVersion: 0,\n fontAtlasManager: new FontAtlasManager()\n };\n\n // Breaking change in v8.9\n if (this.props.maxWidth > 0) {\n log.once(1, 'v8.9 breaking change: TextLayer maxWidth is now relative to text size')();\n }\n }\n\n // eslint-disable-next-line complexity\n updateState(params: UpdateParameters) {\n const {props, oldProps, changeFlags} = params;\n const textChanged =\n changeFlags.dataChanged ||\n (changeFlags.updateTriggersChanged &&\n (changeFlags.updateTriggersChanged.all || changeFlags.updateTriggersChanged.getText));\n\n if (textChanged) {\n this._updateText();\n }\n\n const fontChanged = this._updateFontAtlas();\n\n const styleChanged =\n fontChanged ||\n props.lineHeight !== oldProps.lineHeight ||\n props.wordBreak !== oldProps.wordBreak ||\n props.maxWidth !== oldProps.maxWidth;\n\n if (styleChanged) {\n this.setState({\n styleVersion: this.state.styleVersion + 1\n });\n }\n }\n\n getPickingInfo({info}: GetPickingInfoParams): PickingInfo {\n // because `TextLayer` assign the same pickingInfoIndex for one text label,\n // here info.index refers the index of text label in props.data\n info.object = info.index >= 0 ? (this.props.data as any[])[info.index] : null;\n return info;\n }\n\n /** Returns true if font has changed */\n private _updateFontAtlas(): boolean {\n const {fontSettings, fontFamily, fontWeight, _getFontRenderer} = this.props;\n const {fontAtlasManager, characterSet} = this.state;\n\n const fontProps = {\n ...fontSettings,\n characterSet,\n fontFamily,\n fontWeight,\n _getFontRenderer\n };\n\n if (!fontAtlasManager.mapping) {\n // This is the first update\n fontAtlasManager.setProps(fontProps);\n return true;\n }\n\n for (const key in fontProps) {\n if (fontProps[key] !== fontAtlasManager.props[key]) {\n fontAtlasManager.setProps(fontProps);\n return true;\n }\n }\n\n return false;\n }\n\n // Text strings are variable width objects\n // Count characters and start offsets\n private _updateText() {\n const {data, characterSet} = this.props;\n const textBuffer = (data as any).attributes?.getText;\n let {getText} = this.props;\n let startIndices: number[] = (data as any).startIndices;\n let numInstances: number;\n\n const autoCharacterSet = characterSet === 'auto' && new Set();\n\n if (textBuffer && startIndices) {\n const {texts, characterCount} = getTextFromBuffer({\n ...(ArrayBuffer.isView(textBuffer) ? {value: textBuffer} : textBuffer),\n // @ts-ignore if data.attribute is defined then length is expected\n length: data.length,\n startIndices,\n characterSet: autoCharacterSet\n });\n numInstances = characterCount;\n getText = (_, {index}) => texts[index];\n } else {\n const {iterable, objectInfo} = createIterable(data);\n startIndices = [0];\n numInstances = 0;\n\n for (const object of iterable) {\n objectInfo.index++;\n // Break into an array of characters\n // When dealing with double-length unicode characters, `str.length` or `str[i]` do not work\n const text = Array.from(getText(object, objectInfo) || '');\n if (autoCharacterSet) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n text.forEach(autoCharacterSet.add, autoCharacterSet);\n }\n numInstances += text.length;\n startIndices.push(numInstances);\n }\n }\n\n this.setState({\n getText,\n startIndices,\n numInstances,\n characterSet: autoCharacterSet || characterSet\n });\n }\n\n /** There are two size systems in this layer:\n\n + Pixel size: user-specified text size, via getSize, sizeScale, sizeUnits etc.\n The layer roughly matches the output of the layer to CSS pixels, e.g. getSize: 12, sizeScale: 2\n in layer props is roughly equivalent to font-size: 24px in CSS.\n + Texture size: internally, character positions in a text blob are calculated using the sizes of iconMapping,\n which depends on how large each character is drawn into the font atlas. This is controlled by\n fontSettings.fontSize (default 64) and most users do not set it manually.\n These numbers are intended to be used in the vertex shader and never to be exposed to the end user.\n\n All surfaces exposed to the user should either use the pixel size or a multiplier relative to the pixel size. */\n\n /** Calculate the size and position of each character in a text string.\n * Values are in texture size */\n private transformParagraph(\n object: DataT,\n objectInfo: AccessorContext\n ): ReturnType {\n const {fontAtlasManager} = this.state;\n const iconMapping = fontAtlasManager.mapping!;\n const {baselineOffset} = fontAtlasManager.atlas!;\n const {fontSize} = fontAtlasManager.props;\n const getText = this.state.getText!;\n const {wordBreak, lineHeight, maxWidth} = this.props;\n\n const paragraph = getText(object, objectInfo) || '';\n return transformParagraph(\n paragraph,\n baselineOffset,\n lineHeight * fontSize,\n wordBreak,\n maxWidth * fontSize,\n iconMapping\n );\n }\n\n /** Returns the x, y, width, height of each text string, relative to pixel size.\n * Used to render the background.\n */\n private getBoundingRect: AccessorFunction = (\n object,\n objectInfo\n ) => {\n const {\n size: [width, height]\n } = this.transformParagraph(object, objectInfo);\n\n const {getTextAnchor, getAlignmentBaseline} = this.props;\n const anchorX =\n TEXT_ANCHOR[\n typeof getTextAnchor === 'function' ? getTextAnchor(object, objectInfo) : getTextAnchor\n ];\n const anchorY =\n ALIGNMENT_BASELINE[\n typeof getAlignmentBaseline === 'function'\n ? getAlignmentBaseline(object, objectInfo)\n : getAlignmentBaseline\n ];\n\n return [((anchorX - 1) * width) / 2, ((anchorY - 1) * height) / 2, width, height];\n };\n\n /** Returns the x, y offsets of each character in a text string, in texture size.\n * Used to layout characters in the vertex shader.\n */\n private getIconOffsets: AccessorFunction = (object, objectInfo) => {\n const {getTextAnchor, getAlignmentBaseline} = this.props;\n\n const {\n x,\n y,\n rowWidth,\n size: [, height]\n } = this.transformParagraph(object, objectInfo);\n const anchorX =\n TEXT_ANCHOR[\n typeof getTextAnchor === 'function' ? getTextAnchor(object, objectInfo) : getTextAnchor\n ];\n const anchorY =\n ALIGNMENT_BASELINE[\n typeof getAlignmentBaseline === 'function'\n ? getAlignmentBaseline(object, objectInfo)\n : getAlignmentBaseline\n ];\n\n const numCharacters = x.length;\n const offsets = new Array(numCharacters * 2);\n let index = 0;\n\n for (let i = 0; i < numCharacters; i++) {\n // For a multi-line object, offset in x-direction needs consider\n // the row offset in the paragraph and the object offset in the row\n offsets[index++] = ((anchorX - 1) * rowWidth[i]) / 2 + x[i];\n offsets[index++] = ((anchorY - 1) * height) / 2 + y[i];\n }\n return offsets;\n };\n\n renderLayers() {\n const {\n startIndices,\n numInstances,\n getText,\n fontAtlasManager: {atlas, mapping},\n styleVersion\n } = this.state;\n\n const {\n data,\n _dataDiff,\n getPosition,\n getColor,\n getSize,\n getAngle,\n getPixelOffset,\n getBackgroundColor,\n getBorderColor,\n getBorderWidth,\n getContentBox,\n backgroundBorderRadius,\n backgroundPadding,\n background,\n billboard,\n fontSettings,\n outlineWidth,\n outlineColor,\n sizeScale,\n sizeUnits,\n sizeMinPixels,\n sizeMaxPixels,\n contentCutoffPixels,\n contentAlignHorizontal,\n contentAlignVertical,\n transitions,\n updateTriggers\n } = this.props;\n\n const CharactersLayerClass = this.getSubLayerClass('characters', MultiIconLayer);\n const BackgroundLayerClass = this.getSubLayerClass('background', TextBackgroundLayer);\n const {fontSize} = this.state.fontAtlasManager.props;\n\n return [\n background &&\n new BackgroundLayerClass(\n {\n // background props\n getFillColor: getBackgroundColor,\n getLineColor: getBorderColor,\n getLineWidth: getBorderWidth,\n borderRadius: backgroundBorderRadius,\n padding: backgroundPadding,\n\n // props shared with characters layer\n getPosition,\n getSize,\n getAngle,\n getPixelOffset,\n getClipRect: getContentBox,\n billboard,\n sizeScale,\n sizeUnits,\n sizeMinPixels,\n sizeMaxPixels,\n fontSize,\n\n transitions: transitions && {\n getPosition: transitions.getPosition,\n getAngle: transitions.getAngle,\n getSize: transitions.getSize,\n getFillColor: transitions.getBackgroundColor,\n getLineColor: transitions.getBorderColor,\n getLineWidth: transitions.getBorderWidth,\n getPixelOffset: transitions.getPixelOffset\n }\n },\n this.getSubLayerProps({\n id: 'background',\n updateTriggers: {\n getPosition: updateTriggers.getPosition,\n getAngle: updateTriggers.getAngle,\n getSize: updateTriggers.getSize,\n getFillColor: updateTriggers.getBackgroundColor,\n getLineColor: updateTriggers.getBorderColor,\n getLineWidth: updateTriggers.getBorderWidth,\n getPixelOffset: updateTriggers.getPixelOffset,\n getBoundingRect: {\n getText: updateTriggers.getText,\n getTextAnchor: updateTriggers.getTextAnchor,\n getAlignmentBaseline: updateTriggers.getAlignmentBaseline,\n styleVersion\n }\n }\n }),\n {\n data:\n // @ts-ignore (2339) attribute is not defined on all data types\n data.attributes && data.attributes.background\n ? // @ts-ignore (2339) attribute is not defined on all data types\n {length: data.length, attributes: data.attributes.background}\n : data,\n _dataDiff,\n // Maintain the same background behavior as <=8.3. Remove in v9?\n autoHighlight: false,\n getBoundingRect: this.getBoundingRect\n }\n ),\n new CharactersLayerClass(\n {\n sdf: fontSettings.sdf,\n smoothing: Number.isFinite(fontSettings.smoothing)\n ? fontSettings.smoothing\n : DEFAULT_FONT_SETTINGS.smoothing,\n outlineWidth: outlineWidth / (fontSettings.radius || DEFAULT_FONT_SETTINGS.radius),\n outlineColor,\n iconAtlas: atlas,\n iconMapping: mapping,\n\n getPosition,\n getColor,\n getSize,\n getAngle,\n getPixelOffset,\n getContentBox,\n\n billboard,\n sizeScale,\n sizeUnits,\n sizeMinPixels,\n sizeMaxPixels,\n fontSize,\n contentCutoffPixels,\n contentAlignHorizontal,\n contentAlignVertical,\n\n transitions: transitions && {\n getPosition: transitions.getPosition,\n getAngle: transitions.getAngle,\n getColor: transitions.getColor,\n getSize: transitions.getSize,\n getPixelOffset: transitions.getPixelOffset,\n getContentBox: transitions.getContentBox\n }\n },\n this.getSubLayerProps({\n id: 'characters',\n updateTriggers: {\n all: updateTriggers.getText,\n getPosition: updateTriggers.getPosition,\n getAngle: updateTriggers.getAngle,\n getColor: updateTriggers.getColor,\n getSize: updateTriggers.getSize,\n getPixelOffset: updateTriggers.getPixelOffset,\n getContentBox: updateTriggers.getContentBox,\n getIconOffsets: {\n getTextAnchor: updateTriggers.getTextAnchor,\n getAlignmentBaseline: updateTriggers.getAlignmentBaseline,\n styleVersion\n }\n }\n }),\n {\n data,\n _dataDiff,\n startIndices,\n numInstances,\n getIconOffsets: this.getIconOffsets,\n getIcon: getText\n }\n )\n ];\n }\n\n static set fontAtlasCacheLimit(limit: number) {\n setFontAtlasCacheLimit(limit);\n }\n}\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport type FlowmapData = {\n locations: Iterable | undefined;\n flows: Iterable | undefined;\n clusterLevels?: ClusterLevels;\n};\n\nexport interface ViewState {\n latitude: number;\n longitude: number;\n zoom: number;\n bearing?: number;\n pitch?: number;\n altitude?: number;\n}\n\nexport type FlowAccessor = (flow: F) => T; // objectInfo?: AccessorObjectInfo,\nexport type LocationAccessor = (location: L) => T;\nexport type FlowLinesRenderingMode =\n | 'straight'\n | 'animated-straight'\n | 'curved';\n\nexport interface FlowAccessors {\n getFlowOriginId: FlowAccessor;\n getFlowDestId: FlowAccessor;\n getFlowMagnitude: FlowAccessor;\n getFlowTime?: FlowAccessor; // TODO: use number instead of Date\n // getFlowColor?: FlowAccessor;\n}\n\nexport interface LocationAccessors {\n getLocationId: LocationAccessor;\n getLocationName?: LocationAccessor;\n getLocationLat: LocationAccessor;\n getLocationLon: LocationAccessor;\n getLocationClusterName?: (locationIds: (string | number)[]) => string;\n // getLocationTotalIn?: LocationAccessor;\n // getLocationTotalOut?: LocationAccessor;\n // getLocationTotalInternal?: LocationAccessor;\n}\n\nexport type FlowmapDataAccessors = LocationAccessors &\n FlowAccessors;\n\nexport interface LocationTotals {\n incomingCount: number;\n outgoingCount: number;\n internalCount: number;\n}\n\n// export interface LocationsTotals {\n// incoming: {[id: string]: number};\n// outgoing: {[id: string]: number};\n// internal: {[id: string]: number};\n// }\n\nexport interface CountByTime {\n time: Date;\n count: number;\n}\n\nexport interface ViewportProps {\n width: number;\n height: number;\n latitude: number;\n longitude: number;\n zoom?: number;\n bearing?: number;\n pitch?: number;\n altitude?: number;\n maxZoom?: number;\n minZoom?: number;\n maxPitch?: number;\n minPitch?: number;\n transitionDuration?: number | 'auto';\n transitionInterpolator?: any;\n transitionInterruption?: any;\n transitionEasing?: any;\n}\n\nexport interface ClusterNode {\n id: string | number;\n zoom: number;\n lat: number;\n lon: number;\n}\n\nexport interface ClusterLevel {\n zoom: number;\n nodes: ClusterNode[];\n}\n\nexport type ClusterLevels = ClusterLevel[];\n\n// non-leaf cluster node\nexport interface Cluster extends ClusterNode {\n name?: string;\n children: string[];\n}\n\nexport function isCluster(c: ClusterNode): c is Cluster {\n const {children} = c as Cluster;\n return children && children.length > 0;\n}\n\nexport function isLocationClusterNode(l: L | ClusterNode): l is ClusterNode {\n const {zoom} = l as ClusterNode;\n return zoom !== undefined;\n}\n\nexport interface AggregateFlow {\n origin: string | number;\n dest: string | number;\n count: number;\n aggregate: true;\n}\n\nexport function isAggregateFlow(\n flow: Record,\n): flow is AggregateFlow {\n return (\n flow &&\n // flow.origin !== undefined &&\n // flow.dest !== undefined &&\n // flow.count !== undefined &&\n (flow.aggregate ? true : false)\n );\n}\n\nexport interface FlowCountsMapReduce {\n map: (flow: F) => T;\n reduce: (accumulated: T, val: T) => T;\n}\n\nexport enum LocationFilterMode {\n ALL = 'ALL',\n INCOMING = 'INCOMING',\n OUTGOING = 'OUTGOING',\n BETWEEN = 'BETWEEN',\n}\n\nexport interface FlowCirclesLayerAttributes {\n length: number;\n attributes: {\n getPosition: LayersDataAttrValues;\n getColor: LayersDataAttrValues;\n getInRadius: LayersDataAttrValues;\n getOutRadius: LayersDataAttrValues;\n };\n}\n\nexport interface FlowLinesLayerAttributes {\n length: number;\n attributes: {\n getSourcePosition: LayersDataAttrValues;\n getTargetPosition: LayersDataAttrValues;\n getThickness: LayersDataAttrValues;\n getColor: LayersDataAttrValues;\n getEndpointOffsets: LayersDataAttrValues;\n getStaggering?: LayersDataAttrValues;\n getCurveOffset?: LayersDataAttrValues;\n };\n}\n\nexport interface LayersData {\n circleAttributes: FlowCirclesLayerAttributes;\n lineAttributes: FlowLinesLayerAttributes;\n locationLabels?: string[];\n}\n\nexport type LayersDataAttrValues = {value: T; size: number};\n","export default function(specifier) {\n var n = specifier.length / 6 | 0, colors = new Array(n), i = 0;\n while (i < n) colors[i] = \"#\" + specifier.slice(i * 6, ++i * 6);\n return colors;\n}\n","export default function(constructor, factory, prototype) {\n constructor.prototype = factory.prototype = prototype;\n prototype.constructor = constructor;\n}\n\nexport function extend(parent, definition) {\n var prototype = Object.create(parent.prototype);\n for (var key in definition) prototype[key] = definition[key];\n return prototype;\n}\n","import define, {extend} from \"./define.js\";\n\nexport function Color() {}\n\nexport var darker = 0.7;\nexport var brighter = 1 / darker;\n\nvar reI = \"\\\\s*([+-]?\\\\d+)\\\\s*\",\n reN = \"\\\\s*([+-]?(?:\\\\d*\\\\.)?\\\\d+(?:[eE][+-]?\\\\d+)?)\\\\s*\",\n reP = \"\\\\s*([+-]?(?:\\\\d*\\\\.)?\\\\d+(?:[eE][+-]?\\\\d+)?)%\\\\s*\",\n reHex = /^#([0-9a-f]{3,8})$/,\n reRgbInteger = new RegExp(`^rgb\\\\(${reI},${reI},${reI}\\\\)$`),\n reRgbPercent = new RegExp(`^rgb\\\\(${reP},${reP},${reP}\\\\)$`),\n reRgbaInteger = new RegExp(`^rgba\\\\(${reI},${reI},${reI},${reN}\\\\)$`),\n reRgbaPercent = new RegExp(`^rgba\\\\(${reP},${reP},${reP},${reN}\\\\)$`),\n reHslPercent = new RegExp(`^hsl\\\\(${reN},${reP},${reP}\\\\)$`),\n reHslaPercent = new RegExp(`^hsla\\\\(${reN},${reP},${reP},${reN}\\\\)$`);\n\nvar named = {\n aliceblue: 0xf0f8ff,\n antiquewhite: 0xfaebd7,\n aqua: 0x00ffff,\n aquamarine: 0x7fffd4,\n azure: 0xf0ffff,\n beige: 0xf5f5dc,\n bisque: 0xffe4c4,\n black: 0x000000,\n blanchedalmond: 0xffebcd,\n blue: 0x0000ff,\n blueviolet: 0x8a2be2,\n brown: 0xa52a2a,\n burlywood: 0xdeb887,\n cadetblue: 0x5f9ea0,\n chartreuse: 0x7fff00,\n chocolate: 0xd2691e,\n coral: 0xff7f50,\n cornflowerblue: 0x6495ed,\n cornsilk: 0xfff8dc,\n crimson: 0xdc143c,\n cyan: 0x00ffff,\n darkblue: 0x00008b,\n darkcyan: 0x008b8b,\n darkgoldenrod: 0xb8860b,\n darkgray: 0xa9a9a9,\n darkgreen: 0x006400,\n darkgrey: 0xa9a9a9,\n darkkhaki: 0xbdb76b,\n darkmagenta: 0x8b008b,\n darkolivegreen: 0x556b2f,\n darkorange: 0xff8c00,\n darkorchid: 0x9932cc,\n darkred: 0x8b0000,\n darksalmon: 0xe9967a,\n darkseagreen: 0x8fbc8f,\n darkslateblue: 0x483d8b,\n darkslategray: 0x2f4f4f,\n darkslategrey: 0x2f4f4f,\n darkturquoise: 0x00ced1,\n darkviolet: 0x9400d3,\n deeppink: 0xff1493,\n deepskyblue: 0x00bfff,\n dimgray: 0x696969,\n dimgrey: 0x696969,\n dodgerblue: 0x1e90ff,\n firebrick: 0xb22222,\n floralwhite: 0xfffaf0,\n forestgreen: 0x228b22,\n fuchsia: 0xff00ff,\n gainsboro: 0xdcdcdc,\n ghostwhite: 0xf8f8ff,\n gold: 0xffd700,\n goldenrod: 0xdaa520,\n gray: 0x808080,\n green: 0x008000,\n greenyellow: 0xadff2f,\n grey: 0x808080,\n honeydew: 0xf0fff0,\n hotpink: 0xff69b4,\n indianred: 0xcd5c5c,\n indigo: 0x4b0082,\n ivory: 0xfffff0,\n khaki: 0xf0e68c,\n lavender: 0xe6e6fa,\n lavenderblush: 0xfff0f5,\n lawngreen: 0x7cfc00,\n lemonchiffon: 0xfffacd,\n lightblue: 0xadd8e6,\n lightcoral: 0xf08080,\n lightcyan: 0xe0ffff,\n lightgoldenrodyellow: 0xfafad2,\n lightgray: 0xd3d3d3,\n lightgreen: 0x90ee90,\n lightgrey: 0xd3d3d3,\n lightpink: 0xffb6c1,\n lightsalmon: 0xffa07a,\n lightseagreen: 0x20b2aa,\n lightskyblue: 0x87cefa,\n lightslategray: 0x778899,\n lightslategrey: 0x778899,\n lightsteelblue: 0xb0c4de,\n lightyellow: 0xffffe0,\n lime: 0x00ff00,\n limegreen: 0x32cd32,\n linen: 0xfaf0e6,\n magenta: 0xff00ff,\n maroon: 0x800000,\n mediumaquamarine: 0x66cdaa,\n mediumblue: 0x0000cd,\n mediumorchid: 0xba55d3,\n mediumpurple: 0x9370db,\n mediumseagreen: 0x3cb371,\n mediumslateblue: 0x7b68ee,\n mediumspringgreen: 0x00fa9a,\n mediumturquoise: 0x48d1cc,\n mediumvioletred: 0xc71585,\n midnightblue: 0x191970,\n mintcream: 0xf5fffa,\n mistyrose: 0xffe4e1,\n moccasin: 0xffe4b5,\n navajowhite: 0xffdead,\n navy: 0x000080,\n oldlace: 0xfdf5e6,\n olive: 0x808000,\n olivedrab: 0x6b8e23,\n orange: 0xffa500,\n orangered: 0xff4500,\n orchid: 0xda70d6,\n palegoldenrod: 0xeee8aa,\n palegreen: 0x98fb98,\n paleturquoise: 0xafeeee,\n palevioletred: 0xdb7093,\n papayawhip: 0xffefd5,\n peachpuff: 0xffdab9,\n peru: 0xcd853f,\n pink: 0xffc0cb,\n plum: 0xdda0dd,\n powderblue: 0xb0e0e6,\n purple: 0x800080,\n rebeccapurple: 0x663399,\n red: 0xff0000,\n rosybrown: 0xbc8f8f,\n royalblue: 0x4169e1,\n saddlebrown: 0x8b4513,\n salmon: 0xfa8072,\n sandybrown: 0xf4a460,\n seagreen: 0x2e8b57,\n seashell: 0xfff5ee,\n sienna: 0xa0522d,\n silver: 0xc0c0c0,\n skyblue: 0x87ceeb,\n slateblue: 0x6a5acd,\n slategray: 0x708090,\n slategrey: 0x708090,\n snow: 0xfffafa,\n springgreen: 0x00ff7f,\n steelblue: 0x4682b4,\n tan: 0xd2b48c,\n teal: 0x008080,\n thistle: 0xd8bfd8,\n tomato: 0xff6347,\n turquoise: 0x40e0d0,\n violet: 0xee82ee,\n wheat: 0xf5deb3,\n white: 0xffffff,\n whitesmoke: 0xf5f5f5,\n yellow: 0xffff00,\n yellowgreen: 0x9acd32\n};\n\ndefine(Color, color, {\n copy(channels) {\n return Object.assign(new this.constructor, this, channels);\n },\n displayable() {\n return this.rgb().displayable();\n },\n hex: color_formatHex, // Deprecated! Use color.formatHex.\n formatHex: color_formatHex,\n formatHex8: color_formatHex8,\n formatHsl: color_formatHsl,\n formatRgb: color_formatRgb,\n toString: color_formatRgb\n});\n\nfunction color_formatHex() {\n return this.rgb().formatHex();\n}\n\nfunction color_formatHex8() {\n return this.rgb().formatHex8();\n}\n\nfunction color_formatHsl() {\n return hslConvert(this).formatHsl();\n}\n\nfunction color_formatRgb() {\n return this.rgb().formatRgb();\n}\n\nexport default function color(format) {\n var m, l;\n format = (format + \"\").trim().toLowerCase();\n return (m = reHex.exec(format)) ? (l = m[1].length, m = parseInt(m[1], 16), l === 6 ? rgbn(m) // #ff0000\n : l === 3 ? new Rgb((m >> 8 & 0xf) | (m >> 4 & 0xf0), (m >> 4 & 0xf) | (m & 0xf0), ((m & 0xf) << 4) | (m & 0xf), 1) // #f00\n : l === 8 ? rgba(m >> 24 & 0xff, m >> 16 & 0xff, m >> 8 & 0xff, (m & 0xff) / 0xff) // #ff000000\n : l === 4 ? rgba((m >> 12 & 0xf) | (m >> 8 & 0xf0), (m >> 8 & 0xf) | (m >> 4 & 0xf0), (m >> 4 & 0xf) | (m & 0xf0), (((m & 0xf) << 4) | (m & 0xf)) / 0xff) // #f000\n : null) // invalid hex\n : (m = reRgbInteger.exec(format)) ? new Rgb(m[1], m[2], m[3], 1) // rgb(255, 0, 0)\n : (m = reRgbPercent.exec(format)) ? new Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) // rgb(100%, 0%, 0%)\n : (m = reRgbaInteger.exec(format)) ? rgba(m[1], m[2], m[3], m[4]) // rgba(255, 0, 0, 1)\n : (m = reRgbaPercent.exec(format)) ? rgba(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) // rgb(100%, 0%, 0%, 1)\n : (m = reHslPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, 1) // hsl(120, 50%, 50%)\n : (m = reHslaPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, m[4]) // hsla(120, 50%, 50%, 1)\n : named.hasOwnProperty(format) ? rgbn(named[format]) // eslint-disable-line no-prototype-builtins\n : format === \"transparent\" ? new Rgb(NaN, NaN, NaN, 0)\n : null;\n}\n\nfunction rgbn(n) {\n return new Rgb(n >> 16 & 0xff, n >> 8 & 0xff, n & 0xff, 1);\n}\n\nfunction rgba(r, g, b, a) {\n if (a <= 0) r = g = b = NaN;\n return new Rgb(r, g, b, a);\n}\n\nexport function rgbConvert(o) {\n if (!(o instanceof Color)) o = color(o);\n if (!o) return new Rgb;\n o = o.rgb();\n return new Rgb(o.r, o.g, o.b, o.opacity);\n}\n\nexport function rgb(r, g, b, opacity) {\n return arguments.length === 1 ? rgbConvert(r) : new Rgb(r, g, b, opacity == null ? 1 : opacity);\n}\n\nexport function Rgb(r, g, b, opacity) {\n this.r = +r;\n this.g = +g;\n this.b = +b;\n this.opacity = +opacity;\n}\n\ndefine(Rgb, rgb, extend(Color, {\n brighter(k) {\n k = k == null ? brighter : Math.pow(brighter, k);\n return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);\n },\n darker(k) {\n k = k == null ? darker : Math.pow(darker, k);\n return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);\n },\n rgb() {\n return this;\n },\n clamp() {\n return new Rgb(clampi(this.r), clampi(this.g), clampi(this.b), clampa(this.opacity));\n },\n displayable() {\n return (-0.5 <= this.r && this.r < 255.5)\n && (-0.5 <= this.g && this.g < 255.5)\n && (-0.5 <= this.b && this.b < 255.5)\n && (0 <= this.opacity && this.opacity <= 1);\n },\n hex: rgb_formatHex, // Deprecated! Use color.formatHex.\n formatHex: rgb_formatHex,\n formatHex8: rgb_formatHex8,\n formatRgb: rgb_formatRgb,\n toString: rgb_formatRgb\n}));\n\nfunction rgb_formatHex() {\n return `#${hex(this.r)}${hex(this.g)}${hex(this.b)}`;\n}\n\nfunction rgb_formatHex8() {\n return `#${hex(this.r)}${hex(this.g)}${hex(this.b)}${hex((isNaN(this.opacity) ? 1 : this.opacity) * 255)}`;\n}\n\nfunction rgb_formatRgb() {\n const a = clampa(this.opacity);\n return `${a === 1 ? \"rgb(\" : \"rgba(\"}${clampi(this.r)}, ${clampi(this.g)}, ${clampi(this.b)}${a === 1 ? \")\" : `, ${a})`}`;\n}\n\nfunction clampa(opacity) {\n return isNaN(opacity) ? 1 : Math.max(0, Math.min(1, opacity));\n}\n\nfunction clampi(value) {\n return Math.max(0, Math.min(255, Math.round(value) || 0));\n}\n\nfunction hex(value) {\n value = clampi(value);\n return (value < 16 ? \"0\" : \"\") + value.toString(16);\n}\n\nfunction hsla(h, s, l, a) {\n if (a <= 0) h = s = l = NaN;\n else if (l <= 0 || l >= 1) h = s = NaN;\n else if (s <= 0) h = NaN;\n return new Hsl(h, s, l, a);\n}\n\nexport function hslConvert(o) {\n if (o instanceof Hsl) return new Hsl(o.h, o.s, o.l, o.opacity);\n if (!(o instanceof Color)) o = color(o);\n if (!o) return new Hsl;\n if (o instanceof Hsl) return o;\n o = o.rgb();\n var r = o.r / 255,\n g = o.g / 255,\n b = o.b / 255,\n min = Math.min(r, g, b),\n max = Math.max(r, g, b),\n h = NaN,\n s = max - min,\n l = (max + min) / 2;\n if (s) {\n if (r === max) h = (g - b) / s + (g < b) * 6;\n else if (g === max) h = (b - r) / s + 2;\n else h = (r - g) / s + 4;\n s /= l < 0.5 ? max + min : 2 - max - min;\n h *= 60;\n } else {\n s = l > 0 && l < 1 ? 0 : h;\n }\n return new Hsl(h, s, l, o.opacity);\n}\n\nexport function hsl(h, s, l, opacity) {\n return arguments.length === 1 ? hslConvert(h) : new Hsl(h, s, l, opacity == null ? 1 : opacity);\n}\n\nfunction Hsl(h, s, l, opacity) {\n this.h = +h;\n this.s = +s;\n this.l = +l;\n this.opacity = +opacity;\n}\n\ndefine(Hsl, hsl, extend(Color, {\n brighter(k) {\n k = k == null ? brighter : Math.pow(brighter, k);\n return new Hsl(this.h, this.s, this.l * k, this.opacity);\n },\n darker(k) {\n k = k == null ? darker : Math.pow(darker, k);\n return new Hsl(this.h, this.s, this.l * k, this.opacity);\n },\n rgb() {\n var h = this.h % 360 + (this.h < 0) * 360,\n s = isNaN(h) || isNaN(this.s) ? 0 : this.s,\n l = this.l,\n m2 = l + (l < 0.5 ? l : 1 - l) * s,\n m1 = 2 * l - m2;\n return new Rgb(\n hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2),\n hsl2rgb(h, m1, m2),\n hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2),\n this.opacity\n );\n },\n clamp() {\n return new Hsl(clamph(this.h), clampt(this.s), clampt(this.l), clampa(this.opacity));\n },\n displayable() {\n return (0 <= this.s && this.s <= 1 || isNaN(this.s))\n && (0 <= this.l && this.l <= 1)\n && (0 <= this.opacity && this.opacity <= 1);\n },\n formatHsl() {\n const a = clampa(this.opacity);\n return `${a === 1 ? \"hsl(\" : \"hsla(\"}${clamph(this.h)}, ${clampt(this.s) * 100}%, ${clampt(this.l) * 100}%${a === 1 ? \")\" : `, ${a})`}`;\n }\n}));\n\nfunction clamph(value) {\n value = (value || 0) % 360;\n return value < 0 ? value + 360 : value;\n}\n\nfunction clampt(value) {\n return Math.max(0, Math.min(1, value || 0));\n}\n\n/* From FvD 13.37, CSS Color Module Level 3 */\nfunction hsl2rgb(h, m1, m2) {\n return (h < 60 ? m1 + (m2 - m1) * h / 60\n : h < 180 ? m2\n : h < 240 ? m1 + (m2 - m1) * (240 - h) / 60\n : m1) * 255;\n}\n","export const radians = Math.PI / 180;\nexport const degrees = 180 / Math.PI;\n","import define, {extend} from \"./define.js\";\nimport {Color, rgbConvert, Rgb} from \"./color.js\";\nimport {degrees, radians} from \"./math.js\";\n\n// https://observablehq.com/@mbostock/lab-and-rgb\nconst K = 18,\n Xn = 0.96422,\n Yn = 1,\n Zn = 0.82521,\n t0 = 4 / 29,\n t1 = 6 / 29,\n t2 = 3 * t1 * t1,\n t3 = t1 * t1 * t1;\n\nfunction labConvert(o) {\n if (o instanceof Lab) return new Lab(o.l, o.a, o.b, o.opacity);\n if (o instanceof Hcl) return hcl2lab(o);\n if (!(o instanceof Rgb)) o = rgbConvert(o);\n var r = rgb2lrgb(o.r),\n g = rgb2lrgb(o.g),\n b = rgb2lrgb(o.b),\n y = xyz2lab((0.2225045 * r + 0.7168786 * g + 0.0606169 * b) / Yn), x, z;\n if (r === g && g === b) x = z = y; else {\n x = xyz2lab((0.4360747 * r + 0.3850649 * g + 0.1430804 * b) / Xn);\n z = xyz2lab((0.0139322 * r + 0.0971045 * g + 0.7141733 * b) / Zn);\n }\n return new Lab(116 * y - 16, 500 * (x - y), 200 * (y - z), o.opacity);\n}\n\nexport function gray(l, opacity) {\n return new Lab(l, 0, 0, opacity == null ? 1 : opacity);\n}\n\nexport default function lab(l, a, b, opacity) {\n return arguments.length === 1 ? labConvert(l) : new Lab(l, a, b, opacity == null ? 1 : opacity);\n}\n\nexport function Lab(l, a, b, opacity) {\n this.l = +l;\n this.a = +a;\n this.b = +b;\n this.opacity = +opacity;\n}\n\ndefine(Lab, lab, extend(Color, {\n brighter(k) {\n return new Lab(this.l + K * (k == null ? 1 : k), this.a, this.b, this.opacity);\n },\n darker(k) {\n return new Lab(this.l - K * (k == null ? 1 : k), this.a, this.b, this.opacity);\n },\n rgb() {\n var y = (this.l + 16) / 116,\n x = isNaN(this.a) ? y : y + this.a / 500,\n z = isNaN(this.b) ? y : y - this.b / 200;\n x = Xn * lab2xyz(x);\n y = Yn * lab2xyz(y);\n z = Zn * lab2xyz(z);\n return new Rgb(\n lrgb2rgb( 3.1338561 * x - 1.6168667 * y - 0.4906146 * z),\n lrgb2rgb(-0.9787684 * x + 1.9161415 * y + 0.0334540 * z),\n lrgb2rgb( 0.0719453 * x - 0.2289914 * y + 1.4052427 * z),\n this.opacity\n );\n }\n}));\n\nfunction xyz2lab(t) {\n return t > t3 ? Math.pow(t, 1 / 3) : t / t2 + t0;\n}\n\nfunction lab2xyz(t) {\n return t > t1 ? t * t * t : t2 * (t - t0);\n}\n\nfunction lrgb2rgb(x) {\n return 255 * (x <= 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055);\n}\n\nfunction rgb2lrgb(x) {\n return (x /= 255) <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);\n}\n\nfunction hclConvert(o) {\n if (o instanceof Hcl) return new Hcl(o.h, o.c, o.l, o.opacity);\n if (!(o instanceof Lab)) o = labConvert(o);\n if (o.a === 0 && o.b === 0) return new Hcl(NaN, 0 < o.l && o.l < 100 ? 0 : NaN, o.l, o.opacity);\n var h = Math.atan2(o.b, o.a) * degrees;\n return new Hcl(h < 0 ? h + 360 : h, Math.sqrt(o.a * o.a + o.b * o.b), o.l, o.opacity);\n}\n\nexport function lch(l, c, h, opacity) {\n return arguments.length === 1 ? hclConvert(l) : new Hcl(h, c, l, opacity == null ? 1 : opacity);\n}\n\nexport function hcl(h, c, l, opacity) {\n return arguments.length === 1 ? hclConvert(h) : new Hcl(h, c, l, opacity == null ? 1 : opacity);\n}\n\nexport function Hcl(h, c, l, opacity) {\n this.h = +h;\n this.c = +c;\n this.l = +l;\n this.opacity = +opacity;\n}\n\nfunction hcl2lab(o) {\n if (isNaN(o.h)) return new Lab(o.l, 0, 0, o.opacity);\n var h = o.h * radians;\n return new Lab(o.l, Math.cos(h) * o.c, Math.sin(h) * o.c, o.opacity);\n}\n\ndefine(Hcl, hcl, extend(Color, {\n brighter(k) {\n return new Hcl(this.h, this.c, this.l + K * (k == null ? 1 : k), this.opacity);\n },\n darker(k) {\n return new Hcl(this.h, this.c, this.l - K * (k == null ? 1 : k), this.opacity);\n },\n rgb() {\n return hcl2lab(this).rgb();\n }\n}));\n","import define, {extend} from \"./define.js\";\nimport {Color, rgbConvert, Rgb, darker, brighter} from \"./color.js\";\nimport {degrees, radians} from \"./math.js\";\n\nvar A = -0.14861,\n B = +1.78277,\n C = -0.29227,\n D = -0.90649,\n E = +1.97294,\n ED = E * D,\n EB = E * B,\n BC_DA = B * C - D * A;\n\nfunction cubehelixConvert(o) {\n if (o instanceof Cubehelix) return new Cubehelix(o.h, o.s, o.l, o.opacity);\n if (!(o instanceof Rgb)) o = rgbConvert(o);\n var r = o.r / 255,\n g = o.g / 255,\n b = o.b / 255,\n l = (BC_DA * b + ED * r - EB * g) / (BC_DA + ED - EB),\n bl = b - l,\n k = (E * (g - l) - C * bl) / D,\n s = Math.sqrt(k * k + bl * bl) / (E * l * (1 - l)), // NaN if l=0 or l=1\n h = s ? Math.atan2(k, bl) * degrees - 120 : NaN;\n return new Cubehelix(h < 0 ? h + 360 : h, s, l, o.opacity);\n}\n\nexport default function cubehelix(h, s, l, opacity) {\n return arguments.length === 1 ? cubehelixConvert(h) : new Cubehelix(h, s, l, opacity == null ? 1 : opacity);\n}\n\nexport function Cubehelix(h, s, l, opacity) {\n this.h = +h;\n this.s = +s;\n this.l = +l;\n this.opacity = +opacity;\n}\n\ndefine(Cubehelix, cubehelix, extend(Color, {\n brighter(k) {\n k = k == null ? brighter : Math.pow(brighter, k);\n return new Cubehelix(this.h, this.s, this.l * k, this.opacity);\n },\n darker(k) {\n k = k == null ? darker : Math.pow(darker, k);\n return new Cubehelix(this.h, this.s, this.l * k, this.opacity);\n },\n rgb() {\n var h = isNaN(this.h) ? 0 : (this.h + 120) * radians,\n l = +this.l,\n a = isNaN(this.s) ? 0 : this.s * l * (1 - l),\n cosh = Math.cos(h),\n sinh = Math.sin(h);\n return new Rgb(\n 255 * (l + a * (A * cosh + B * sinh)),\n 255 * (l + a * (C * cosh + D * sinh)),\n 255 * (l + a * (E * cosh)),\n this.opacity\n );\n }\n}));\n","export function basis(t1, v0, v1, v2, v3) {\n var t2 = t1 * t1, t3 = t2 * t1;\n return ((1 - 3 * t1 + 3 * t2 - t3) * v0\n + (4 - 6 * t2 + 3 * t3) * v1\n + (1 + 3 * t1 + 3 * t2 - 3 * t3) * v2\n + t3 * v3) / 6;\n}\n\nexport default function(values) {\n var n = values.length - 1;\n return function(t) {\n var i = t <= 0 ? (t = 0) : t >= 1 ? (t = 1, n - 1) : Math.floor(t * n),\n v1 = values[i],\n v2 = values[i + 1],\n v0 = i > 0 ? values[i - 1] : 2 * v1 - v2,\n v3 = i < n - 1 ? values[i + 2] : 2 * v2 - v1;\n return basis((t - i / n) * n, v0, v1, v2, v3);\n };\n}\n","import {basis} from \"./basis.js\";\n\nexport default function(values) {\n var n = values.length;\n return function(t) {\n var i = Math.floor(((t %= 1) < 0 ? ++t : t) * n),\n v0 = values[(i + n - 1) % n],\n v1 = values[i % n],\n v2 = values[(i + 1) % n],\n v3 = values[(i + 2) % n];\n return basis((t - i / n) * n, v0, v1, v2, v3);\n };\n}\n","export default x => () => x;\n","import constant from \"./constant.js\";\n\nfunction linear(a, d) {\n return function(t) {\n return a + t * d;\n };\n}\n\nfunction exponential(a, b, y) {\n return a = Math.pow(a, y), b = Math.pow(b, y) - a, y = 1 / y, function(t) {\n return Math.pow(a + t * b, y);\n };\n}\n\nexport function hue(a, b) {\n var d = b - a;\n return d ? linear(a, d > 180 || d < -180 ? d - 360 * Math.round(d / 360) : d) : constant(isNaN(a) ? b : a);\n}\n\nexport function gamma(y) {\n return (y = +y) === 1 ? nogamma : function(a, b) {\n return b - a ? exponential(a, b, y) : constant(isNaN(a) ? b : a);\n };\n}\n\nexport default function nogamma(a, b) {\n var d = b - a;\n return d ? linear(a, d) : constant(isNaN(a) ? b : a);\n}\n","import {rgb as colorRgb} from \"d3-color\";\nimport basis from \"./basis.js\";\nimport basisClosed from \"./basisClosed.js\";\nimport nogamma, {gamma} from \"./color.js\";\n\nexport default (function rgbGamma(y) {\n var color = gamma(y);\n\n function rgb(start, end) {\n var r = color((start = colorRgb(start)).r, (end = colorRgb(end)).r),\n g = color(start.g, end.g),\n b = color(start.b, end.b),\n opacity = nogamma(start.opacity, end.opacity);\n return function(t) {\n start.r = r(t);\n start.g = g(t);\n start.b = b(t);\n start.opacity = opacity(t);\n return start + \"\";\n };\n }\n\n rgb.gamma = rgbGamma;\n\n return rgb;\n})(1);\n\nfunction rgbSpline(spline) {\n return function(colors) {\n var n = colors.length,\n r = new Array(n),\n g = new Array(n),\n b = new Array(n),\n i, color;\n for (i = 0; i < n; ++i) {\n color = colorRgb(colors[i]);\n r[i] = color.r || 0;\n g[i] = color.g || 0;\n b[i] = color.b || 0;\n }\n r = spline(r);\n g = spline(g);\n b = spline(b);\n color.opacity = 1;\n return function(t) {\n color.r = r(t);\n color.g = g(t);\n color.b = b(t);\n return color + \"\";\n };\n };\n}\n\nexport var rgbBasis = rgbSpline(basis);\nexport var rgbBasisClosed = rgbSpline(basisClosed);\n","export default function(a, b) {\n if (!b) b = [];\n var n = a ? Math.min(b.length, a.length) : 0,\n c = b.slice(),\n i;\n return function(t) {\n for (i = 0; i < n; ++i) c[i] = a[i] * (1 - t) + b[i] * t;\n return c;\n };\n}\n\nexport function isNumberArray(x) {\n return ArrayBuffer.isView(x) && !(x instanceof DataView);\n}\n","import value from \"./value.js\";\nimport numberArray, {isNumberArray} from \"./numberArray.js\";\n\nexport default function(a, b) {\n return (isNumberArray(b) ? numberArray : genericArray)(a, b);\n}\n\nexport function genericArray(a, b) {\n var nb = b ? b.length : 0,\n na = a ? Math.min(nb, a.length) : 0,\n x = new Array(na),\n c = new Array(nb),\n i;\n\n for (i = 0; i < na; ++i) x[i] = value(a[i], b[i]);\n for (; i < nb; ++i) c[i] = b[i];\n\n return function(t) {\n for (i = 0; i < na; ++i) c[i] = x[i](t);\n return c;\n };\n}\n","export default function(a, b) {\n var d = new Date;\n return a = +a, b = +b, function(t) {\n return d.setTime(a * (1 - t) + b * t), d;\n };\n}\n","export default function(a, b) {\n return a = +a, b = +b, function(t) {\n return a * (1 - t) + b * t;\n };\n}\n","import value from \"./value.js\";\n\nexport default function(a, b) {\n var i = {},\n c = {},\n k;\n\n if (a === null || typeof a !== \"object\") a = {};\n if (b === null || typeof b !== \"object\") b = {};\n\n for (k in b) {\n if (k in a) {\n i[k] = value(a[k], b[k]);\n } else {\n c[k] = b[k];\n }\n }\n\n return function(t) {\n for (k in i) c[k] = i[k](t);\n return c;\n };\n}\n","import number from \"./number.js\";\n\nvar reA = /[-+]?(?:\\d+\\.?\\d*|\\.?\\d+)(?:[eE][-+]?\\d+)?/g,\n reB = new RegExp(reA.source, \"g\");\n\nfunction zero(b) {\n return function() {\n return b;\n };\n}\n\nfunction one(b) {\n return function(t) {\n return b(t) + \"\";\n };\n}\n\nexport default function(a, b) {\n var bi = reA.lastIndex = reB.lastIndex = 0, // scan index for next number in b\n am, // current match in a\n bm, // current match in b\n bs, // string preceding current number in b, if any\n i = -1, // index in s\n s = [], // string constants and placeholders\n q = []; // number interpolators\n\n // Coerce inputs to strings.\n a = a + \"\", b = b + \"\";\n\n // Interpolate pairs of numbers in a & b.\n while ((am = reA.exec(a))\n && (bm = reB.exec(b))) {\n if ((bs = bm.index) > bi) { // a string precedes the next number in b\n bs = b.slice(bi, bs);\n if (s[i]) s[i] += bs; // coalesce with previous string\n else s[++i] = bs;\n }\n if ((am = am[0]) === (bm = bm[0])) { // numbers in a & b match\n if (s[i]) s[i] += bm; // coalesce with previous string\n else s[++i] = bm;\n } else { // interpolate non-matching numbers\n s[++i] = null;\n q.push({i: i, x: number(am, bm)});\n }\n bi = reB.lastIndex;\n }\n\n // Add remains of b.\n if (bi < b.length) {\n bs = b.slice(bi);\n if (s[i]) s[i] += bs; // coalesce with previous string\n else s[++i] = bs;\n }\n\n // Special optimization for only a single match.\n // Otherwise, interpolate each of the numbers and rejoin the string.\n return s.length < 2 ? (q[0]\n ? one(q[0].x)\n : zero(b))\n : (b = q.length, function(t) {\n for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t);\n return s.join(\"\");\n });\n}\n","import {color} from \"d3-color\";\nimport rgb from \"./rgb.js\";\nimport {genericArray} from \"./array.js\";\nimport date from \"./date.js\";\nimport number from \"./number.js\";\nimport object from \"./object.js\";\nimport string from \"./string.js\";\nimport constant from \"./constant.js\";\nimport numberArray, {isNumberArray} from \"./numberArray.js\";\n\nexport default function(a, b) {\n var t = typeof b, c;\n return b == null || t === \"boolean\" ? constant(b)\n : (t === \"number\" ? number\n : t === \"string\" ? ((c = color(b)) ? (b = c, rgb) : string)\n : b instanceof color ? rgb\n : b instanceof Date ? date\n : isNumberArray(b) ? numberArray\n : Array.isArray(b) ? genericArray\n : typeof b.valueOf !== \"function\" && typeof b.toString !== \"function\" || isNaN(b) ? object\n : number)(a, b);\n}\n","export default function(a, b) {\n return a = +a, b = +b, function(t) {\n return Math.round(a * (1 - t) + b * t);\n };\n}\n","import {cubehelix as colorCubehelix} from \"d3-color\";\nimport color, {hue} from \"./color.js\";\n\nfunction cubehelix(hue) {\n return (function cubehelixGamma(y) {\n y = +y;\n\n function cubehelix(start, end) {\n var h = hue((start = colorCubehelix(start)).h, (end = colorCubehelix(end)).h),\n s = color(start.s, end.s),\n l = color(start.l, end.l),\n opacity = color(start.opacity, end.opacity);\n return function(t) {\n start.h = h(t);\n start.s = s(t);\n start.l = l(Math.pow(t, y));\n start.opacity = opacity(t);\n return start + \"\";\n };\n }\n\n cubehelix.gamma = cubehelixGamma;\n\n return cubehelix;\n })(1);\n}\n\nexport default cubehelix(hue);\nexport var cubehelixLong = cubehelix(color);\n","import {interpolateRgbBasis} from \"d3-interpolate\";\n\nexport default scheme => interpolateRgbBasis(scheme[scheme.length - 1]);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"e5f5f999d8c92ca25f\",\n \"edf8fbb2e2e266c2a4238b45\",\n \"edf8fbb2e2e266c2a42ca25f006d2c\",\n \"edf8fbccece699d8c966c2a42ca25f006d2c\",\n \"edf8fbccece699d8c966c2a441ae76238b45005824\",\n \"f7fcfde5f5f9ccece699d8c966c2a441ae76238b45005824\",\n \"f7fcfde5f5f9ccece699d8c966c2a441ae76238b45006d2c00441b\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"e0ecf49ebcda8856a7\",\n \"edf8fbb3cde38c96c688419d\",\n \"edf8fbb3cde38c96c68856a7810f7c\",\n \"edf8fbbfd3e69ebcda8c96c68856a7810f7c\",\n \"edf8fbbfd3e69ebcda8c96c68c6bb188419d6e016b\",\n \"f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d6e016b\",\n \"f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d810f7c4d004b\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"e0f3dba8ddb543a2ca\",\n \"f0f9e8bae4bc7bccc42b8cbe\",\n \"f0f9e8bae4bc7bccc443a2ca0868ac\",\n \"f0f9e8ccebc5a8ddb57bccc443a2ca0868ac\",\n \"f0f9e8ccebc5a8ddb57bccc44eb3d32b8cbe08589e\",\n \"f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe08589e\",\n \"f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe0868ac084081\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"fee8c8fdbb84e34a33\",\n \"fef0d9fdcc8afc8d59d7301f\",\n \"fef0d9fdcc8afc8d59e34a33b30000\",\n \"fef0d9fdd49efdbb84fc8d59e34a33b30000\",\n \"fef0d9fdd49efdbb84fc8d59ef6548d7301f990000\",\n \"fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301f990000\",\n \"fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301fb300007f0000\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"ece2f0a6bddb1c9099\",\n \"f6eff7bdc9e167a9cf02818a\",\n \"f6eff7bdc9e167a9cf1c9099016c59\",\n \"f6eff7d0d1e6a6bddb67a9cf1c9099016c59\",\n \"f6eff7d0d1e6a6bddb67a9cf3690c002818a016450\",\n \"fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016450\",\n \"fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016c59014636\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"ece7f2a6bddb2b8cbe\",\n \"f1eef6bdc9e174a9cf0570b0\",\n \"f1eef6bdc9e174a9cf2b8cbe045a8d\",\n \"f1eef6d0d1e6a6bddb74a9cf2b8cbe045a8d\",\n \"f1eef6d0d1e6a6bddb74a9cf3690c00570b0034e7b\",\n \"fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0034e7b\",\n \"fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0045a8d023858\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"e7e1efc994c7dd1c77\",\n \"f1eef6d7b5d8df65b0ce1256\",\n \"f1eef6d7b5d8df65b0dd1c77980043\",\n \"f1eef6d4b9dac994c7df65b0dd1c77980043\",\n \"f1eef6d4b9dac994c7df65b0e7298ace125691003f\",\n \"f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125691003f\",\n \"f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125698004367001f\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"fde0ddfa9fb5c51b8a\",\n \"feebe2fbb4b9f768a1ae017e\",\n \"feebe2fbb4b9f768a1c51b8a7a0177\",\n \"feebe2fcc5c0fa9fb5f768a1c51b8a7a0177\",\n \"feebe2fcc5c0fa9fb5f768a1dd3497ae017e7a0177\",\n \"fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a0177\",\n \"fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a017749006a\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"edf8b17fcdbb2c7fb8\",\n \"ffffcca1dab441b6c4225ea8\",\n \"ffffcca1dab441b6c42c7fb8253494\",\n \"ffffccc7e9b47fcdbb41b6c42c7fb8253494\",\n \"ffffccc7e9b47fcdbb41b6c41d91c0225ea80c2c84\",\n \"ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea80c2c84\",\n \"ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea8253494081d58\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"f7fcb9addd8e31a354\",\n \"ffffccc2e69978c679238443\",\n \"ffffccc2e69978c67931a354006837\",\n \"ffffccd9f0a3addd8e78c67931a354006837\",\n \"ffffccd9f0a3addd8e78c67941ab5d238443005a32\",\n \"ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443005a32\",\n \"ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443006837004529\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"fff7bcfec44fd95f0e\",\n \"ffffd4fed98efe9929cc4c02\",\n \"ffffd4fed98efe9929d95f0e993404\",\n \"ffffd4fee391fec44ffe9929d95f0e993404\",\n \"ffffd4fee391fec44ffe9929ec7014cc4c028c2d04\",\n \"ffffe5fff7bcfee391fec44ffe9929ec7014cc4c028c2d04\",\n \"ffffe5fff7bcfee391fec44ffe9929ec7014cc4c02993404662506\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"ffeda0feb24cf03b20\",\n \"ffffb2fecc5cfd8d3ce31a1c\",\n \"ffffb2fecc5cfd8d3cf03b20bd0026\",\n \"ffffb2fed976feb24cfd8d3cf03b20bd0026\",\n \"ffffb2fed976feb24cfd8d3cfc4e2ae31a1cb10026\",\n \"ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cb10026\",\n \"ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cbd0026800026\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"deebf79ecae13182bd\",\n \"eff3ffbdd7e76baed62171b5\",\n \"eff3ffbdd7e76baed63182bd08519c\",\n \"eff3ffc6dbef9ecae16baed63182bd08519c\",\n \"eff3ffc6dbef9ecae16baed64292c62171b5084594\",\n \"f7fbffdeebf7c6dbef9ecae16baed64292c62171b5084594\",\n \"f7fbffdeebf7c6dbef9ecae16baed64292c62171b508519c08306b\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"e5f5e0a1d99b31a354\",\n \"edf8e9bae4b374c476238b45\",\n \"edf8e9bae4b374c47631a354006d2c\",\n \"edf8e9c7e9c0a1d99b74c47631a354006d2c\",\n \"edf8e9c7e9c0a1d99b74c47641ab5d238b45005a32\",\n \"f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45005a32\",\n \"f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45006d2c00441b\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"f0f0f0bdbdbd636363\",\n \"f7f7f7cccccc969696525252\",\n \"f7f7f7cccccc969696636363252525\",\n \"f7f7f7d9d9d9bdbdbd969696636363252525\",\n \"f7f7f7d9d9d9bdbdbd969696737373525252252525\",\n \"fffffff0f0f0d9d9d9bdbdbd969696737373525252252525\",\n \"fffffff0f0f0d9d9d9bdbdbd969696737373525252252525000000\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"efedf5bcbddc756bb1\",\n \"f2f0f7cbc9e29e9ac86a51a3\",\n \"f2f0f7cbc9e29e9ac8756bb154278f\",\n \"f2f0f7dadaebbcbddc9e9ac8756bb154278f\",\n \"f2f0f7dadaebbcbddc9e9ac8807dba6a51a34a1486\",\n \"fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a34a1486\",\n \"fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a354278f3f007d\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"fee0d2fc9272de2d26\",\n \"fee5d9fcae91fb6a4acb181d\",\n \"fee5d9fcae91fb6a4ade2d26a50f15\",\n \"fee5d9fcbba1fc9272fb6a4ade2d26a50f15\",\n \"fee5d9fcbba1fc9272fb6a4aef3b2ccb181d99000d\",\n \"fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181d99000d\",\n \"fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181da50f1567000d\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"fee6cefdae6be6550d\",\n \"feeddefdbe85fd8d3cd94701\",\n \"feeddefdbe85fd8d3ce6550da63603\",\n \"feeddefdd0a2fdae6bfd8d3ce6550da63603\",\n \"feeddefdd0a2fdae6bfd8d3cf16913d948018c2d04\",\n \"fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d948018c2d04\",\n \"fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d94801a636037f2704\"\n).map(colors);\n\nexport default ramp(scheme);\n","import {cubehelix} from \"d3-color\";\nimport {interpolateCubehelixLong} from \"d3-interpolate\";\n\nexport var warm = interpolateCubehelixLong(cubehelix(-100, 0.75, 0.35), cubehelix(80, 1.50, 0.8));\n\nexport var cool = interpolateCubehelixLong(cubehelix(260, 0.75, 0.35), cubehelix(80, 1.50, 0.8));\n\nvar c = cubehelix();\n\nexport default function(t) {\n if (t < 0 || t > 1) t -= Math.floor(t);\n var ts = Math.abs(t - 0.5);\n c.h = 360 * t - 100;\n c.s = 1.5 - 1.5 * ts;\n c.l = 0.8 - 0.9 * ts;\n return c + \"\";\n}\n","import colors from \"../colors.js\";\n\nfunction ramp(range) {\n var n = range.length;\n return function(t) {\n return range[Math.max(0, Math.min(n - 1, Math.floor(t * n)))];\n };\n}\n\nexport default ramp(colors(\"44015444025645045745055946075a46085c460a5d460b5e470d60470e6147106347116447136548146748166848176948186a481a6c481b6d481c6e481d6f481f70482071482173482374482475482576482677482878482979472a7a472c7a472d7b472e7c472f7d46307e46327e46337f463480453581453781453882443983443a83443b84433d84433e85423f854240864241864142874144874045884046883f47883f48893e49893e4a893e4c8a3d4d8a3d4e8a3c4f8a3c508b3b518b3b528b3a538b3a548c39558c39568c38588c38598c375a8c375b8d365c8d365d8d355e8d355f8d34608d34618d33628d33638d32648e32658e31668e31678e31688e30698e306a8e2f6b8e2f6c8e2e6d8e2e6e8e2e6f8e2d708e2d718e2c718e2c728e2c738e2b748e2b758e2a768e2a778e2a788e29798e297a8e297b8e287c8e287d8e277e8e277f8e27808e26818e26828e26828e25838e25848e25858e24868e24878e23888e23898e238a8d228b8d228c8d228d8d218e8d218f8d21908d21918c20928c20928c20938c1f948c1f958b1f968b1f978b1f988b1f998a1f9a8a1e9b8a1e9c891e9d891f9e891f9f881fa0881fa1881fa1871fa28720a38620a48621a58521a68522a78522a88423a98324aa8325ab8225ac8226ad8127ad8128ae8029af7f2ab07f2cb17e2db27d2eb37c2fb47c31b57b32b67a34b67935b77937b87838b9773aba763bbb753dbc743fbc7340bd7242be7144bf7046c06f48c16e4ac16d4cc26c4ec36b50c46a52c56954c56856c66758c7655ac8645cc8635ec96260ca6063cb5f65cb5e67cc5c69cd5b6ccd5a6ece5870cf5773d05675d05477d1537ad1517cd2507fd34e81d34d84d44b86d54989d5488bd6468ed64590d74393d74195d84098d83e9bd93c9dd93ba0da39a2da37a5db36a8db34aadc32addc30b0dd2fb2dd2db5de2bb8de29bade28bddf26c0df25c2df23c5e021c8e020cae11fcde11dd0e11cd2e21bd5e21ad8e219dae319dde318dfe318e2e418e5e419e7e419eae51aece51befe51cf1e51df4e61ef6e620f8e621fbe723fde725\"));\n\nexport var magma = ramp(colors(\"00000401000501010601010802010902020b02020d03030f03031204041405041606051806051a07061c08071e0907200a08220b09240c09260d0a290e0b2b100b2d110c2f120d31130d34140e36150e38160f3b180f3d19103f1a10421c10441d11471e114920114b21114e22115024125325125527125829115a2a115c2c115f2d11612f116331116533106734106936106b38106c390f6e3b0f703d0f713f0f72400f74420f75440f764510774710784910784a10794c117a4e117b4f127b51127c52137c54137d56147d57157e59157e5a167e5c167f5d177f5f187f601880621980641a80651a80671b80681c816a1c816b1d816d1d816e1e81701f81721f817320817521817621817822817922827b23827c23827e24828025828125818326818426818627818827818928818b29818c29818e2a81902a81912b81932b80942c80962c80982d80992d809b2e7f9c2e7f9e2f7fa02f7fa1307ea3307ea5317ea6317da8327daa337dab337cad347cae347bb0357bb2357bb3367ab5367ab73779b83779ba3878bc3978bd3977bf3a77c03a76c23b75c43c75c53c74c73d73c83e73ca3e72cc3f71cd4071cf4070d0416fd2426fd3436ed5446dd6456cd8456cd9466bdb476adc4869de4968df4a68e04c67e24d66e34e65e44f64e55064e75263e85362e95462ea5661eb5760ec5860ed5a5fee5b5eef5d5ef05f5ef1605df2625df2645cf3655cf4675cf4695cf56b5cf66c5cf66e5cf7705cf7725cf8745cf8765cf9785df9795df97b5dfa7d5efa7f5efa815ffb835ffb8560fb8761fc8961fc8a62fc8c63fc8e64fc9065fd9266fd9467fd9668fd9869fd9a6afd9b6bfe9d6cfe9f6dfea16efea36ffea571fea772fea973feaa74feac76feae77feb078feb27afeb47bfeb67cfeb77efeb97ffebb81febd82febf84fec185fec287fec488fec68afec88cfeca8dfecc8ffecd90fecf92fed194fed395fed597fed799fed89afdda9cfddc9efddea0fde0a1fde2a3fde3a5fde5a7fde7a9fde9aafdebacfcecaefceeb0fcf0b2fcf2b4fcf4b6fcf6b8fcf7b9fcf9bbfcfbbdfcfdbf\"));\n\nexport var inferno = ramp(colors(\"00000401000501010601010802010a02020c02020e03021004031204031405041706041907051b08051d09061f0a07220b07240c08260d08290e092b10092d110a30120a32140b34150b37160b39180c3c190c3e1b0c411c0c431e0c451f0c48210c4a230c4c240c4f260c51280b53290b552b0b572d0b592f0a5b310a5c320a5e340a5f3609613809623909633b09643d09653e0966400a67420a68440a68450a69470b6a490b6a4a0c6b4c0c6b4d0d6c4f0d6c510e6c520e6d540f6d550f6d57106e59106e5a116e5c126e5d126e5f136e61136e62146e64156e65156e67166e69166e6a176e6c186e6d186e6f196e71196e721a6e741a6e751b6e771c6d781c6d7a1d6d7c1d6d7d1e6d7f1e6c801f6c82206c84206b85216b87216b88226a8a226a8c23698d23698f24699025689225689326679526679727669827669a28659b29649d29649f2a63a02a63a22b62a32c61a52c60a62d60a82e5fa92e5eab2f5ead305dae305cb0315bb1325ab3325ab43359b63458b73557b93556ba3655bc3754bd3853bf3952c03a51c13a50c33b4fc43c4ec63d4dc73e4cc83f4bca404acb4149cc4248ce4347cf4446d04545d24644d34743d44842d54a41d74b3fd84c3ed94d3dda4e3cdb503bdd513ade5238df5337e05536e15635e25734e35933e45a31e55c30e65d2fe75e2ee8602de9612bea632aeb6429eb6628ec6726ed6925ee6a24ef6c23ef6e21f06f20f1711ff1731df2741cf3761bf37819f47918f57b17f57d15f67e14f68013f78212f78410f8850ff8870ef8890cf98b0bf98c0af98e09fa9008fa9207fa9407fb9606fb9706fb9906fb9b06fb9d07fc9f07fca108fca309fca50afca60cfca80dfcaa0ffcac11fcae12fcb014fcb216fcb418fbb61afbb81dfbba1ffbbc21fbbe23fac026fac228fac42afac62df9c72ff9c932f9cb35f8cd37f8cf3af7d13df7d340f6d543f6d746f5d949f5db4cf4dd4ff4df53f4e156f3e35af3e55df2e661f2e865f2ea69f1ec6df1ed71f1ef75f1f179f2f27df2f482f3f586f3f68af4f88ef5f992f6fa96f8fb9af9fc9dfafda1fcffa4\"));\n\nexport var plasma = ramp(colors(\"0d088710078813078916078a19068c1b068d1d068e20068f2206902406912605912805922a05932c05942e05952f059631059733059735049837049938049a3a049a3c049b3e049c3f049c41049d43039e44039e46039f48039f4903a04b03a14c02a14e02a25002a25102a35302a35502a45601a45801a45901a55b01a55c01a65e01a66001a66100a76300a76400a76600a76700a86900a86a00a86c00a86e00a86f00a87100a87201a87401a87501a87701a87801a87a02a87b02a87d03a87e03a88004a88104a78305a78405a78606a68707a68808a68a09a58b0aa58d0ba58e0ca48f0da4910ea3920fa39410a29511a19613a19814a099159f9a169f9c179e9d189d9e199da01a9ca11b9ba21d9aa31e9aa51f99a62098a72197a82296aa2395ab2494ac2694ad2793ae2892b02991b12a90b22b8fb32c8eb42e8db52f8cb6308bb7318ab83289ba3388bb3488bc3587bd3786be3885bf3984c03a83c13b82c23c81c33d80c43e7fc5407ec6417dc7427cc8437bc9447aca457acb4679cc4778cc4977cd4a76ce4b75cf4c74d04d73d14e72d24f71d35171d45270d5536fd5546ed6556dd7566cd8576bd9586ada5a6ada5b69db5c68dc5d67dd5e66de5f65de6164df6263e06363e16462e26561e26660e3685fe4695ee56a5de56b5de66c5ce76e5be76f5ae87059e97158e97257ea7457eb7556eb7655ec7754ed7953ed7a52ee7b51ef7c51ef7e50f07f4ff0804ef1814df1834cf2844bf3854bf3874af48849f48948f58b47f58c46f68d45f68f44f79044f79143f79342f89441f89540f9973ff9983ef99a3efa9b3dfa9c3cfa9e3bfb9f3afba139fba238fca338fca537fca636fca835fca934fdab33fdac33fdae32fdaf31fdb130fdb22ffdb42ffdb52efeb72dfeb82cfeba2cfebb2bfebd2afebe2afec029fdc229fdc328fdc527fdc627fdc827fdca26fdcb26fccd25fcce25fcd025fcd225fbd324fbd524fbd724fad824fada24f9dc24f9dd25f8df25f8e125f7e225f7e425f6e626f6e826f5e926f5eb27f4ed27f3ee27f3f027f2f227f1f426f1f525f0f724f0f921\"));\n","export default function ascending(a, b) {\n return a == null || b == null ? NaN : a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;\n}\n","export default function descending(a, b) {\n return a == null || b == null ? NaN\n : b < a ? -1\n : b > a ? 1\n : b >= a ? 0\n : NaN;\n}\n","import ascending from \"./ascending.js\";\nimport descending from \"./descending.js\";\n\nexport default function bisector(f) {\n let compare1, compare2, delta;\n\n // If an accessor is specified, promote it to a comparator. In this case we\n // can test whether the search value is (self-) comparable. We can’t do this\n // for a comparator (except for specific, known comparators) because we can’t\n // tell if the comparator is symmetric, and an asymmetric comparator can’t be\n // used to test whether a single value is comparable.\n if (f.length !== 2) {\n compare1 = ascending;\n compare2 = (d, x) => ascending(f(d), x);\n delta = (d, x) => f(d) - x;\n } else {\n compare1 = f === ascending || f === descending ? f : zero;\n compare2 = f;\n delta = f;\n }\n\n function left(a, x, lo = 0, hi = a.length) {\n if (lo < hi) {\n if (compare1(x, x) !== 0) return hi;\n do {\n const mid = (lo + hi) >>> 1;\n if (compare2(a[mid], x) < 0) lo = mid + 1;\n else hi = mid;\n } while (lo < hi);\n }\n return lo;\n }\n\n function right(a, x, lo = 0, hi = a.length) {\n if (lo < hi) {\n if (compare1(x, x) !== 0) return hi;\n do {\n const mid = (lo + hi) >>> 1;\n if (compare2(a[mid], x) <= 0) lo = mid + 1;\n else hi = mid;\n } while (lo < hi);\n }\n return lo;\n }\n\n function center(a, x, lo = 0, hi = a.length) {\n const i = left(a, x, lo, hi - 1);\n return i > lo && delta(a[i - 1], x) > -delta(a[i], x) ? i - 1 : i;\n }\n\n return {left, center, right};\n}\n\nfunction zero() {\n return 0;\n}\n","export default function number(x) {\n return x === null ? NaN : +x;\n}\n\nexport function* numbers(values, valueof) {\n if (valueof === undefined) {\n for (let value of values) {\n if (value != null && (value = +value) >= value) {\n yield value;\n }\n }\n } else {\n let index = -1;\n for (let value of values) {\n if ((value = valueof(value, ++index, values)) != null && (value = +value) >= value) {\n yield value;\n }\n }\n }\n}\n","import ascending from \"./ascending.js\";\nimport bisector from \"./bisector.js\";\nimport number from \"./number.js\";\n\nconst ascendingBisect = bisector(ascending);\nexport const bisectRight = ascendingBisect.right;\nexport const bisectLeft = ascendingBisect.left;\nexport const bisectCenter = bisector(number).center;\nexport default bisectRight;\n","export default function extent(values, valueof) {\n let min;\n let max;\n if (valueof === undefined) {\n for (const value of values) {\n if (value != null) {\n if (min === undefined) {\n if (value >= value) min = max = value;\n } else {\n if (min > value) min = value;\n if (max < value) max = value;\n }\n }\n }\n } else {\n let index = -1;\n for (let value of values) {\n if ((value = valueof(value, ++index, values)) != null) {\n if (min === undefined) {\n if (value >= value) min = max = value;\n } else {\n if (min > value) min = value;\n if (max < value) max = value;\n }\n }\n }\n }\n return [min, max];\n}\n","// https://github.com/python/cpython/blob/a74eea238f5baba15797e2e8b570d153bc8690a7/Modules/mathmodule.c#L1423\nexport class Adder {\n constructor() {\n this._partials = new Float64Array(32);\n this._n = 0;\n }\n add(x) {\n const p = this._partials;\n let i = 0;\n for (let j = 0; j < this._n && j < 32; j++) {\n const y = p[j],\n hi = x + y,\n lo = Math.abs(x) < Math.abs(y) ? x - (hi - y) : y - (hi - x);\n if (lo) p[i++] = lo;\n x = hi;\n }\n p[i] = x;\n this._n = i + 1;\n return this;\n }\n valueOf() {\n const p = this._partials;\n let n = this._n, x, y, lo, hi = 0;\n if (n > 0) {\n hi = p[--n];\n while (n > 0) {\n x = hi;\n y = p[--n];\n hi = x + y;\n lo = y - (hi - x);\n if (lo) break;\n }\n if (n > 0 && ((lo < 0 && p[n - 1] < 0) || (lo > 0 && p[n - 1] > 0))) {\n y = lo * 2;\n x = hi + y;\n if (y == x - hi) hi = x;\n }\n }\n return hi;\n }\n}\n\nexport function fsum(values, valueof) {\n const adder = new Adder();\n if (valueof === undefined) {\n for (let value of values) {\n if (value = +value) {\n adder.add(value);\n }\n }\n } else {\n let index = -1;\n for (let value of values) {\n if (value = +valueof(value, ++index, values)) {\n adder.add(value);\n }\n }\n }\n return +adder;\n}\n\nexport function fcumsum(values, valueof) {\n const adder = new Adder();\n let index = -1;\n return Float64Array.from(values, valueof === undefined\n ? v => adder.add(+v || 0)\n : v => adder.add(+valueof(v, ++index, values) || 0)\n );\n}\n","export class InternMap extends Map {\n constructor(entries, key = keyof) {\n super();\n Object.defineProperties(this, {_intern: {value: new Map()}, _key: {value: key}});\n if (entries != null) for (const [key, value] of entries) this.set(key, value);\n }\n get(key) {\n return super.get(intern_get(this, key));\n }\n has(key) {\n return super.has(intern_get(this, key));\n }\n set(key, value) {\n return super.set(intern_set(this, key), value);\n }\n delete(key) {\n return super.delete(intern_delete(this, key));\n }\n}\n\nexport class InternSet extends Set {\n constructor(values, key = keyof) {\n super();\n Object.defineProperties(this, {_intern: {value: new Map()}, _key: {value: key}});\n if (values != null) for (const value of values) this.add(value);\n }\n has(value) {\n return super.has(intern_get(this, value));\n }\n add(value) {\n return super.add(intern_set(this, value));\n }\n delete(value) {\n return super.delete(intern_delete(this, value));\n }\n}\n\nfunction intern_get({_intern, _key}, value) {\n const key = _key(value);\n return _intern.has(key) ? _intern.get(key) : value;\n}\n\nfunction intern_set({_intern, _key}, value) {\n const key = _key(value);\n if (_intern.has(key)) return _intern.get(key);\n _intern.set(key, value);\n return value;\n}\n\nfunction intern_delete({_intern, _key}, value) {\n const key = _key(value);\n if (_intern.has(key)) {\n value = _intern.get(key);\n _intern.delete(key);\n }\n return value;\n}\n\nfunction keyof(value) {\n return value !== null && typeof value === \"object\" ? value.valueOf() : value;\n}\n","export default function identity(x) {\n return x;\n}\n","import {InternMap} from \"internmap\";\nimport identity from \"./identity.js\";\n\nexport default function group(values, ...keys) {\n return nest(values, identity, identity, keys);\n}\n\nexport function groups(values, ...keys) {\n return nest(values, Array.from, identity, keys);\n}\n\nfunction flatten(groups, keys) {\n for (let i = 1, n = keys.length; i < n; ++i) {\n groups = groups.flatMap(g => g.pop().map(([key, value]) => [...g, key, value]));\n }\n return groups;\n}\n\nexport function flatGroup(values, ...keys) {\n return flatten(groups(values, ...keys), keys);\n}\n\nexport function flatRollup(values, reduce, ...keys) {\n return flatten(rollups(values, reduce, ...keys), keys);\n}\n\nexport function rollup(values, reduce, ...keys) {\n return nest(values, identity, reduce, keys);\n}\n\nexport function rollups(values, reduce, ...keys) {\n return nest(values, Array.from, reduce, keys);\n}\n\nexport function index(values, ...keys) {\n return nest(values, identity, unique, keys);\n}\n\nexport function indexes(values, ...keys) {\n return nest(values, Array.from, unique, keys);\n}\n\nfunction unique(values) {\n if (values.length !== 1) throw new Error(\"duplicate key\");\n return values[0];\n}\n\nfunction nest(values, map, reduce, keys) {\n return (function regroup(values, i) {\n if (i >= keys.length) return reduce(values);\n const groups = new InternMap();\n const keyof = keys[i++];\n let index = -1;\n for (const value of values) {\n const key = keyof(value, ++index, values);\n const group = groups.get(key);\n if (group) group.push(value);\n else groups.set(key, [value]);\n }\n for (const [key, values] of groups) {\n groups.set(key, regroup(values, i));\n }\n return map(groups);\n })(values, 0);\n}\n","const e10 = Math.sqrt(50),\n e5 = Math.sqrt(10),\n e2 = Math.sqrt(2);\n\nfunction tickSpec(start, stop, count) {\n const step = (stop - start) / Math.max(0, count),\n power = Math.floor(Math.log10(step)),\n error = step / Math.pow(10, power),\n factor = error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1;\n let i1, i2, inc;\n if (power < 0) {\n inc = Math.pow(10, -power) / factor;\n i1 = Math.round(start * inc);\n i2 = Math.round(stop * inc);\n if (i1 / inc < start) ++i1;\n if (i2 / inc > stop) --i2;\n inc = -inc;\n } else {\n inc = Math.pow(10, power) * factor;\n i1 = Math.round(start / inc);\n i2 = Math.round(stop / inc);\n if (i1 * inc < start) ++i1;\n if (i2 * inc > stop) --i2;\n }\n if (i2 < i1 && 0.5 <= count && count < 2) return tickSpec(start, stop, count * 2);\n return [i1, i2, inc];\n}\n\nexport default function ticks(start, stop, count) {\n stop = +stop, start = +start, count = +count;\n if (!(count > 0)) return [];\n if (start === stop) return [start];\n const reverse = stop < start, [i1, i2, inc] = reverse ? tickSpec(stop, start, count) : tickSpec(start, stop, count);\n if (!(i2 >= i1)) return [];\n const n = i2 - i1 + 1, ticks = new Array(n);\n if (reverse) {\n if (inc < 0) for (let i = 0; i < n; ++i) ticks[i] = (i2 - i) / -inc;\n else for (let i = 0; i < n; ++i) ticks[i] = (i2 - i) * inc;\n } else {\n if (inc < 0) for (let i = 0; i < n; ++i) ticks[i] = (i1 + i) / -inc;\n else for (let i = 0; i < n; ++i) ticks[i] = (i1 + i) * inc;\n }\n return ticks;\n}\n\nexport function tickIncrement(start, stop, count) {\n stop = +stop, start = +start, count = +count;\n return tickSpec(start, stop, count)[2];\n}\n\nexport function tickStep(start, stop, count) {\n stop = +stop, start = +start, count = +count;\n const reverse = stop < start, inc = reverse ? tickIncrement(stop, start, count) : tickIncrement(start, stop, count);\n return (reverse ? -1 : 1) * (inc < 0 ? 1 / -inc : inc);\n}\n","export default function min(values, valueof) {\n let min;\n if (valueof === undefined) {\n for (const value of values) {\n if (value != null\n && (min > value || (min === undefined && value >= value))) {\n min = value;\n }\n }\n } else {\n let index = -1;\n for (let value of values) {\n if ((value = valueof(value, ++index, values)) != null\n && (min > value || (min === undefined && value >= value))) {\n min = value;\n }\n }\n }\n return min;\n}\n","export default function range(start, stop, step) {\n start = +start, stop = +stop, step = (n = arguments.length) < 2 ? (stop = start, start = 0, 1) : n < 3 ? 1 : +step;\n\n var i = -1,\n n = Math.max(0, Math.ceil((stop - start) / step)) | 0,\n range = new Array(n);\n\n while (++i < n) {\n range[i] = start + i * step;\n }\n\n return range;\n}\n","export function initRange(domain, range) {\n switch (arguments.length) {\n case 0: break;\n case 1: this.range(domain); break;\n default: this.range(range).domain(domain); break;\n }\n return this;\n}\n\nexport function initInterpolator(domain, interpolator) {\n switch (arguments.length) {\n case 0: break;\n case 1: {\n if (typeof domain === \"function\") this.interpolator(domain);\n else this.range(domain);\n break;\n }\n default: {\n this.domain(domain);\n if (typeof interpolator === \"function\") this.interpolator(interpolator);\n else this.range(interpolator);\n break;\n }\n }\n return this;\n}\n","export default function constants(x) {\n return function() {\n return x;\n };\n}\n","export default function number(x) {\n return +x;\n}\n","import {bisect} from \"d3-array\";\nimport {interpolate as interpolateValue, interpolateNumber, interpolateRound} from \"d3-interpolate\";\nimport constant from \"./constant.js\";\nimport number from \"./number.js\";\n\nvar unit = [0, 1];\n\nexport function identity(x) {\n return x;\n}\n\nfunction normalize(a, b) {\n return (b -= (a = +a))\n ? function(x) { return (x - a) / b; }\n : constant(isNaN(b) ? NaN : 0.5);\n}\n\nfunction clamper(a, b) {\n var t;\n if (a > b) t = a, a = b, b = t;\n return function(x) { return Math.max(a, Math.min(b, x)); };\n}\n\n// normalize(a, b)(x) takes a domain value x in [a,b] and returns the corresponding parameter t in [0,1].\n// interpolate(a, b)(t) takes a parameter t in [0,1] and returns the corresponding range value x in [a,b].\nfunction bimap(domain, range, interpolate) {\n var d0 = domain[0], d1 = domain[1], r0 = range[0], r1 = range[1];\n if (d1 < d0) d0 = normalize(d1, d0), r0 = interpolate(r1, r0);\n else d0 = normalize(d0, d1), r0 = interpolate(r0, r1);\n return function(x) { return r0(d0(x)); };\n}\n\nfunction polymap(domain, range, interpolate) {\n var j = Math.min(domain.length, range.length) - 1,\n d = new Array(j),\n r = new Array(j),\n i = -1;\n\n // Reverse descending domains.\n if (domain[j] < domain[0]) {\n domain = domain.slice().reverse();\n range = range.slice().reverse();\n }\n\n while (++i < j) {\n d[i] = normalize(domain[i], domain[i + 1]);\n r[i] = interpolate(range[i], range[i + 1]);\n }\n\n return function(x) {\n var i = bisect(domain, x, 1, j) - 1;\n return r[i](d[i](x));\n };\n}\n\nexport function copy(source, target) {\n return target\n .domain(source.domain())\n .range(source.range())\n .interpolate(source.interpolate())\n .clamp(source.clamp())\n .unknown(source.unknown());\n}\n\nexport function transformer() {\n var domain = unit,\n range = unit,\n interpolate = interpolateValue,\n transform,\n untransform,\n unknown,\n clamp = identity,\n piecewise,\n output,\n input;\n\n function rescale() {\n var n = Math.min(domain.length, range.length);\n if (clamp !== identity) clamp = clamper(domain[0], domain[n - 1]);\n piecewise = n > 2 ? polymap : bimap;\n output = input = null;\n return scale;\n }\n\n function scale(x) {\n return x == null || isNaN(x = +x) ? unknown : (output || (output = piecewise(domain.map(transform), range, interpolate)))(transform(clamp(x)));\n }\n\n scale.invert = function(y) {\n return clamp(untransform((input || (input = piecewise(range, domain.map(transform), interpolateNumber)))(y)));\n };\n\n scale.domain = function(_) {\n return arguments.length ? (domain = Array.from(_, number), rescale()) : domain.slice();\n };\n\n scale.range = function(_) {\n return arguments.length ? (range = Array.from(_), rescale()) : range.slice();\n };\n\n scale.rangeRound = function(_) {\n return range = Array.from(_), interpolate = interpolateRound, rescale();\n };\n\n scale.clamp = function(_) {\n return arguments.length ? (clamp = _ ? true : identity, rescale()) : clamp !== identity;\n };\n\n scale.interpolate = function(_) {\n return arguments.length ? (interpolate = _, rescale()) : interpolate;\n };\n\n scale.unknown = function(_) {\n return arguments.length ? (unknown = _, scale) : unknown;\n };\n\n return function(t, u) {\n transform = t, untransform = u;\n return rescale();\n };\n}\n\nexport default function continuous() {\n return transformer()(identity, identity);\n}\n","export default function(x) {\n return Math.abs(x = Math.round(x)) >= 1e21\n ? x.toLocaleString(\"en\").replace(/,/g, \"\")\n : x.toString(10);\n}\n\n// Computes the decimal coefficient and exponent of the specified number x with\n// significant digits p, where x is positive and p is in [1, 21] or undefined.\n// For example, formatDecimalParts(1.23) returns [\"123\", 0].\nexport function formatDecimalParts(x, p) {\n if (!isFinite(x) || x === 0) return null; // NaN, ±Infinity, ±0\n var i = (x = p ? x.toExponential(p - 1) : x.toExponential()).indexOf(\"e\"), coefficient = x.slice(0, i);\n\n // The string returned by toExponential either has the form \\d\\.\\d+e[-+]\\d+\n // (e.g., 1.2e+3) or the form \\de[-+]\\d+ (e.g., 1e+3).\n return [\n coefficient.length > 1 ? coefficient[0] + coefficient.slice(2) : coefficient,\n +x.slice(i + 1)\n ];\n}\n","import {formatDecimalParts} from \"./formatDecimal.js\";\n\nexport default function(x) {\n return x = formatDecimalParts(Math.abs(x)), x ? x[1] : NaN;\n}\n","export default function(grouping, thousands) {\n return function(value, width) {\n var i = value.length,\n t = [],\n j = 0,\n g = grouping[0],\n length = 0;\n\n while (i > 0 && g > 0) {\n if (length + g + 1 > width) g = Math.max(1, width - length);\n t.push(value.substring(i -= g, i + g));\n if ((length += g + 1) > width) break;\n g = grouping[j = (j + 1) % grouping.length];\n }\n\n return t.reverse().join(thousands);\n };\n}\n","export default function(numerals) {\n return function(value) {\n return value.replace(/[0-9]/g, function(i) {\n return numerals[+i];\n });\n };\n}\n","// [[fill]align][sign][symbol][0][width][,][.precision][~][type]\nvar re = /^(?:(.)?([<>=^]))?([+\\-( ])?([$#])?(0)?(\\d+)?(,)?(\\.\\d+)?(~)?([a-z%])?$/i;\n\nexport default function formatSpecifier(specifier) {\n if (!(match = re.exec(specifier))) throw new Error(\"invalid format: \" + specifier);\n var match;\n return new FormatSpecifier({\n fill: match[1],\n align: match[2],\n sign: match[3],\n symbol: match[4],\n zero: match[5],\n width: match[6],\n comma: match[7],\n precision: match[8] && match[8].slice(1),\n trim: match[9],\n type: match[10]\n });\n}\n\nformatSpecifier.prototype = FormatSpecifier.prototype; // instanceof\n\nexport function FormatSpecifier(specifier) {\n this.fill = specifier.fill === undefined ? \" \" : specifier.fill + \"\";\n this.align = specifier.align === undefined ? \">\" : specifier.align + \"\";\n this.sign = specifier.sign === undefined ? \"-\" : specifier.sign + \"\";\n this.symbol = specifier.symbol === undefined ? \"\" : specifier.symbol + \"\";\n this.zero = !!specifier.zero;\n this.width = specifier.width === undefined ? undefined : +specifier.width;\n this.comma = !!specifier.comma;\n this.precision = specifier.precision === undefined ? undefined : +specifier.precision;\n this.trim = !!specifier.trim;\n this.type = specifier.type === undefined ? \"\" : specifier.type + \"\";\n}\n\nFormatSpecifier.prototype.toString = function() {\n return this.fill\n + this.align\n + this.sign\n + this.symbol\n + (this.zero ? \"0\" : \"\")\n + (this.width === undefined ? \"\" : Math.max(1, this.width | 0))\n + (this.comma ? \",\" : \"\")\n + (this.precision === undefined ? \"\" : \".\" + Math.max(0, this.precision | 0))\n + (this.trim ? \"~\" : \"\")\n + this.type;\n};\n","// Trims insignificant zeros, e.g., replaces 1.2000k with 1.2k.\nexport default function(s) {\n out: for (var n = s.length, i = 1, i0 = -1, i1; i < n; ++i) {\n switch (s[i]) {\n case \".\": i0 = i1 = i; break;\n case \"0\": if (i0 === 0) i0 = i; i1 = i; break;\n default: if (!+s[i]) break out; if (i0 > 0) i0 = 0; break;\n }\n }\n return i0 > 0 ? s.slice(0, i0) + s.slice(i1 + 1) : s;\n}\n","import {formatDecimalParts} from \"./formatDecimal.js\";\n\nexport var prefixExponent;\n\nexport default function(x, p) {\n var d = formatDecimalParts(x, p);\n if (!d) return prefixExponent = undefined, x.toPrecision(p);\n var coefficient = d[0],\n exponent = d[1],\n i = exponent - (prefixExponent = Math.max(-8, Math.min(8, Math.floor(exponent / 3))) * 3) + 1,\n n = coefficient.length;\n return i === n ? coefficient\n : i > n ? coefficient + new Array(i - n + 1).join(\"0\")\n : i > 0 ? coefficient.slice(0, i) + \".\" + coefficient.slice(i)\n : \"0.\" + new Array(1 - i).join(\"0\") + formatDecimalParts(x, Math.max(0, p + i - 1))[0]; // less than 1y!\n}\n","import {formatDecimalParts} from \"./formatDecimal.js\";\n\nexport default function(x, p) {\n var d = formatDecimalParts(x, p);\n if (!d) return x + \"\";\n var coefficient = d[0],\n exponent = d[1];\n return exponent < 0 ? \"0.\" + new Array(-exponent).join(\"0\") + coefficient\n : coefficient.length > exponent + 1 ? coefficient.slice(0, exponent + 1) + \".\" + coefficient.slice(exponent + 1)\n : coefficient + new Array(exponent - coefficient.length + 2).join(\"0\");\n}\n","import formatDecimal from \"./formatDecimal.js\";\nimport formatPrefixAuto from \"./formatPrefixAuto.js\";\nimport formatRounded from \"./formatRounded.js\";\n\nexport default {\n \"%\": (x, p) => (x * 100).toFixed(p),\n \"b\": (x) => Math.round(x).toString(2),\n \"c\": (x) => x + \"\",\n \"d\": formatDecimal,\n \"e\": (x, p) => x.toExponential(p),\n \"f\": (x, p) => x.toFixed(p),\n \"g\": (x, p) => x.toPrecision(p),\n \"o\": (x) => Math.round(x).toString(8),\n \"p\": (x, p) => formatRounded(x * 100, p),\n \"r\": formatRounded,\n \"s\": formatPrefixAuto,\n \"X\": (x) => Math.round(x).toString(16).toUpperCase(),\n \"x\": (x) => Math.round(x).toString(16)\n};\n","export default function(x) {\n return x;\n}\n","import exponent from \"./exponent.js\";\nimport formatGroup from \"./formatGroup.js\";\nimport formatNumerals from \"./formatNumerals.js\";\nimport formatSpecifier from \"./formatSpecifier.js\";\nimport formatTrim from \"./formatTrim.js\";\nimport formatTypes from \"./formatTypes.js\";\nimport {prefixExponent} from \"./formatPrefixAuto.js\";\nimport identity from \"./identity.js\";\n\nvar map = Array.prototype.map,\n prefixes = [\"y\",\"z\",\"a\",\"f\",\"p\",\"n\",\"µ\",\"m\",\"\",\"k\",\"M\",\"G\",\"T\",\"P\",\"E\",\"Z\",\"Y\"];\n\nexport default function(locale) {\n var group = locale.grouping === undefined || locale.thousands === undefined ? identity : formatGroup(map.call(locale.grouping, Number), locale.thousands + \"\"),\n currencyPrefix = locale.currency === undefined ? \"\" : locale.currency[0] + \"\",\n currencySuffix = locale.currency === undefined ? \"\" : locale.currency[1] + \"\",\n decimal = locale.decimal === undefined ? \".\" : locale.decimal + \"\",\n numerals = locale.numerals === undefined ? identity : formatNumerals(map.call(locale.numerals, String)),\n percent = locale.percent === undefined ? \"%\" : locale.percent + \"\",\n minus = locale.minus === undefined ? \"−\" : locale.minus + \"\",\n nan = locale.nan === undefined ? \"NaN\" : locale.nan + \"\";\n\n function newFormat(specifier, options) {\n specifier = formatSpecifier(specifier);\n\n var fill = specifier.fill,\n align = specifier.align,\n sign = specifier.sign,\n symbol = specifier.symbol,\n zero = specifier.zero,\n width = specifier.width,\n comma = specifier.comma,\n precision = specifier.precision,\n trim = specifier.trim,\n type = specifier.type;\n\n // The \"n\" type is an alias for \",g\".\n if (type === \"n\") comma = true, type = \"g\";\n\n // The \"\" type, and any invalid type, is an alias for \".12~g\".\n else if (!formatTypes[type]) precision === undefined && (precision = 12), trim = true, type = \"g\";\n\n // If zero fill is specified, padding goes after sign and before digits.\n if (zero || (fill === \"0\" && align === \"=\")) zero = true, fill = \"0\", align = \"=\";\n\n // Compute the prefix and suffix.\n // For SI-prefix, the suffix is lazily computed.\n var prefix = (options && options.prefix !== undefined ? options.prefix : \"\") + (symbol === \"$\" ? currencyPrefix : symbol === \"#\" && /[boxX]/.test(type) ? \"0\" + type.toLowerCase() : \"\"),\n suffix = (symbol === \"$\" ? currencySuffix : /[%p]/.test(type) ? percent : \"\") + (options && options.suffix !== undefined ? options.suffix : \"\");\n\n // What format function should we use?\n // Is this an integer type?\n // Can this type generate exponential notation?\n var formatType = formatTypes[type],\n maybeSuffix = /[defgprs%]/.test(type);\n\n // Set the default precision if not specified,\n // or clamp the specified precision to the supported range.\n // For significant precision, it must be in [1, 21].\n // For fixed precision, it must be in [0, 20].\n precision = precision === undefined ? 6\n : /[gprs]/.test(type) ? Math.max(1, Math.min(21, precision))\n : Math.max(0, Math.min(20, precision));\n\n function format(value) {\n var valuePrefix = prefix,\n valueSuffix = suffix,\n i, n, c;\n\n if (type === \"c\") {\n valueSuffix = formatType(value) + valueSuffix;\n value = \"\";\n } else {\n value = +value;\n\n // Determine the sign. -0 is not less than 0, but 1 / -0 is!\n var valueNegative = value < 0 || 1 / value < 0;\n\n // Perform the initial formatting.\n value = isNaN(value) ? nan : formatType(Math.abs(value), precision);\n\n // Trim insignificant zeros.\n if (trim) value = formatTrim(value);\n\n // If a negative value rounds to zero after formatting, and no explicit positive sign is requested, hide the sign.\n if (valueNegative && +value === 0 && sign !== \"+\") valueNegative = false;\n\n // Compute the prefix and suffix.\n valuePrefix = (valueNegative ? (sign === \"(\" ? sign : minus) : sign === \"-\" || sign === \"(\" ? \"\" : sign) + valuePrefix;\n valueSuffix = (type === \"s\" && !isNaN(value) && prefixExponent !== undefined ? prefixes[8 + prefixExponent / 3] : \"\") + valueSuffix + (valueNegative && sign === \"(\" ? \")\" : \"\");\n\n // Break the formatted value into the integer “value” part that can be\n // grouped, and fractional or exponential “suffix” part that is not.\n if (maybeSuffix) {\n i = -1, n = value.length;\n while (++i < n) {\n if (c = value.charCodeAt(i), 48 > c || c > 57) {\n valueSuffix = (c === 46 ? decimal + value.slice(i + 1) : value.slice(i)) + valueSuffix;\n value = value.slice(0, i);\n break;\n }\n }\n }\n }\n\n // If the fill character is not \"0\", grouping is applied before padding.\n if (comma && !zero) value = group(value, Infinity);\n\n // Compute the padding.\n var length = valuePrefix.length + value.length + valueSuffix.length,\n padding = length < width ? new Array(width - length + 1).join(fill) : \"\";\n\n // If the fill character is \"0\", grouping is applied after padding.\n if (comma && zero) value = group(padding + value, padding.length ? width - valueSuffix.length : Infinity), padding = \"\";\n\n // Reconstruct the final output based on the desired alignment.\n switch (align) {\n case \"<\": value = valuePrefix + value + valueSuffix + padding; break;\n case \"=\": value = valuePrefix + padding + value + valueSuffix; break;\n case \"^\": value = padding.slice(0, length = padding.length >> 1) + valuePrefix + value + valueSuffix + padding.slice(length); break;\n default: value = padding + valuePrefix + value + valueSuffix; break;\n }\n\n return numerals(value);\n }\n\n format.toString = function() {\n return specifier + \"\";\n };\n\n return format;\n }\n\n function formatPrefix(specifier, value) {\n var e = Math.max(-8, Math.min(8, Math.floor(exponent(value) / 3))) * 3,\n k = Math.pow(10, -e),\n f = newFormat((specifier = formatSpecifier(specifier), specifier.type = \"f\", specifier), {suffix: prefixes[8 + e / 3]});\n return function(value) {\n return f(k * value);\n };\n }\n\n return {\n format: newFormat,\n formatPrefix: formatPrefix\n };\n}\n","import formatLocale from \"./locale.js\";\n\nvar locale;\nexport var format;\nexport var formatPrefix;\n\ndefaultLocale({\n thousands: \",\",\n grouping: [3],\n currency: [\"$\", \"\"]\n});\n\nexport default function defaultLocale(definition) {\n locale = formatLocale(definition);\n format = locale.format;\n formatPrefix = locale.formatPrefix;\n return locale;\n}\n","import exponent from \"./exponent.js\";\n\nexport default function(step) {\n return Math.max(0, -exponent(Math.abs(step)));\n}\n","import exponent from \"./exponent.js\";\n\nexport default function(step, value) {\n return Math.max(0, Math.max(-8, Math.min(8, Math.floor(exponent(value) / 3))) * 3 - exponent(Math.abs(step)));\n}\n","import exponent from \"./exponent.js\";\n\nexport default function(step, max) {\n step = Math.abs(step), max = Math.abs(max) - step;\n return Math.max(0, exponent(max) - exponent(step)) + 1;\n}\n","import {tickStep} from \"d3-array\";\nimport {format, formatPrefix, formatSpecifier, precisionFixed, precisionPrefix, precisionRound} from \"d3-format\";\n\nexport default function tickFormat(start, stop, count, specifier) {\n var step = tickStep(start, stop, count),\n precision;\n specifier = formatSpecifier(specifier == null ? \",f\" : specifier);\n switch (specifier.type) {\n case \"s\": {\n var value = Math.max(Math.abs(start), Math.abs(stop));\n if (specifier.precision == null && !isNaN(precision = precisionPrefix(step, value))) specifier.precision = precision;\n return formatPrefix(specifier, value);\n }\n case \"\":\n case \"e\":\n case \"g\":\n case \"p\":\n case \"r\": {\n if (specifier.precision == null && !isNaN(precision = precisionRound(step, Math.max(Math.abs(start), Math.abs(stop))))) specifier.precision = precision - (specifier.type === \"e\");\n break;\n }\n case \"f\":\n case \"%\": {\n if (specifier.precision == null && !isNaN(precision = precisionFixed(step))) specifier.precision = precision - (specifier.type === \"%\") * 2;\n break;\n }\n }\n return format(specifier);\n}\n","import {ticks, tickIncrement} from \"d3-array\";\nimport continuous, {copy} from \"./continuous.js\";\nimport {initRange} from \"./init.js\";\nimport tickFormat from \"./tickFormat.js\";\n\nexport function linearish(scale) {\n var domain = scale.domain;\n\n scale.ticks = function(count) {\n var d = domain();\n return ticks(d[0], d[d.length - 1], count == null ? 10 : count);\n };\n\n scale.tickFormat = function(count, specifier) {\n var d = domain();\n return tickFormat(d[0], d[d.length - 1], count == null ? 10 : count, specifier);\n };\n\n scale.nice = function(count) {\n if (count == null) count = 10;\n\n var d = domain();\n var i0 = 0;\n var i1 = d.length - 1;\n var start = d[i0];\n var stop = d[i1];\n var prestep;\n var step;\n var maxIter = 10;\n\n if (stop < start) {\n step = start, start = stop, stop = step;\n step = i0, i0 = i1, i1 = step;\n }\n \n while (maxIter-- > 0) {\n step = tickIncrement(start, stop, count);\n if (step === prestep) {\n d[i0] = start\n d[i1] = stop\n return domain(d);\n } else if (step > 0) {\n start = Math.floor(start / step) * step;\n stop = Math.ceil(stop / step) * step;\n } else if (step < 0) {\n start = Math.ceil(start * step) / step;\n stop = Math.floor(stop * step) / step;\n } else {\n break;\n }\n prestep = step;\n }\n\n return scale;\n };\n\n return scale;\n}\n\nexport default function linear() {\n var scale = continuous();\n\n scale.copy = function() {\n return copy(scale, linear());\n };\n\n initRange.apply(scale, arguments);\n\n return linearish(scale);\n}\n","import {linearish} from \"./linear.js\";\nimport {copy, identity, transformer} from \"./continuous.js\";\nimport {initRange} from \"./init.js\";\n\nfunction transformPow(exponent) {\n return function(x) {\n return x < 0 ? -Math.pow(-x, exponent) : Math.pow(x, exponent);\n };\n}\n\nfunction transformSqrt(x) {\n return x < 0 ? -Math.sqrt(-x) : Math.sqrt(x);\n}\n\nfunction transformSquare(x) {\n return x < 0 ? -x * x : x * x;\n}\n\nexport function powish(transform) {\n var scale = transform(identity, identity),\n exponent = 1;\n\n function rescale() {\n return exponent === 1 ? transform(identity, identity)\n : exponent === 0.5 ? transform(transformSqrt, transformSquare)\n : transform(transformPow(exponent), transformPow(1 / exponent));\n }\n\n scale.exponent = function(_) {\n return arguments.length ? (exponent = +_, rescale()) : exponent;\n };\n\n return linearish(scale);\n}\n\nexport default function pow() {\n var scale = powish(transformer());\n\n scale.copy = function() {\n return copy(scale, pow()).exponent(scale.exponent());\n };\n\n initRange.apply(scale, arguments);\n\n return scale;\n}\n\nexport function sqrt() {\n return pow.apply(null, arguments).exponent(0.5);\n}\n","const t0 = new Date, t1 = new Date;\n\nexport function timeInterval(floori, offseti, count, field) {\n\n function interval(date) {\n return floori(date = arguments.length === 0 ? new Date : new Date(+date)), date;\n }\n\n interval.floor = (date) => {\n return floori(date = new Date(+date)), date;\n };\n\n interval.ceil = (date) => {\n return floori(date = new Date(date - 1)), offseti(date, 1), floori(date), date;\n };\n\n interval.round = (date) => {\n const d0 = interval(date), d1 = interval.ceil(date);\n return date - d0 < d1 - date ? d0 : d1;\n };\n\n interval.offset = (date, step) => {\n return offseti(date = new Date(+date), step == null ? 1 : Math.floor(step)), date;\n };\n\n interval.range = (start, stop, step) => {\n const range = [];\n start = interval.ceil(start);\n step = step == null ? 1 : Math.floor(step);\n if (!(start < stop) || !(step > 0)) return range; // also handles Invalid Date\n let previous;\n do range.push(previous = new Date(+start)), offseti(start, step), floori(start);\n while (previous < start && start < stop);\n return range;\n };\n\n interval.filter = (test) => {\n return timeInterval((date) => {\n if (date >= date) while (floori(date), !test(date)) date.setTime(date - 1);\n }, (date, step) => {\n if (date >= date) {\n if (step < 0) while (++step <= 0) {\n while (offseti(date, -1), !test(date)) {} // eslint-disable-line no-empty\n } else while (--step >= 0) {\n while (offseti(date, +1), !test(date)) {} // eslint-disable-line no-empty\n }\n }\n });\n };\n\n if (count) {\n interval.count = (start, end) => {\n t0.setTime(+start), t1.setTime(+end);\n floori(t0), floori(t1);\n return Math.floor(count(t0, t1));\n };\n\n interval.every = (step) => {\n step = Math.floor(step);\n return !isFinite(step) || !(step > 0) ? null\n : !(step > 1) ? interval\n : interval.filter(field\n ? (d) => field(d) % step === 0\n : (d) => interval.count(0, d) % step === 0);\n };\n }\n\n return interval;\n}\n","export const durationSecond = 1000;\nexport const durationMinute = durationSecond * 60;\nexport const durationHour = durationMinute * 60;\nexport const durationDay = durationHour * 24;\nexport const durationWeek = durationDay * 7;\nexport const durationMonth = durationDay * 30;\nexport const durationYear = durationDay * 365;\n","import {timeInterval} from \"./interval.js\";\nimport {durationSecond} from \"./duration.js\";\n\nexport const second = timeInterval((date) => {\n date.setTime(date - date.getMilliseconds());\n}, (date, step) => {\n date.setTime(+date + step * durationSecond);\n}, (start, end) => {\n return (end - start) / durationSecond;\n}, (date) => {\n return date.getUTCSeconds();\n});\n\nexport const seconds = second.range;\n","import {timeInterval} from \"./interval.js\";\nimport {durationMinute, durationSecond} from \"./duration.js\";\n\nexport const timeMinute = timeInterval((date) => {\n date.setTime(date - date.getMilliseconds() - date.getSeconds() * durationSecond);\n}, (date, step) => {\n date.setTime(+date + step * durationMinute);\n}, (start, end) => {\n return (end - start) / durationMinute;\n}, (date) => {\n return date.getMinutes();\n});\n\nexport const timeMinutes = timeMinute.range;\n\nexport const utcMinute = timeInterval((date) => {\n date.setUTCSeconds(0, 0);\n}, (date, step) => {\n date.setTime(+date + step * durationMinute);\n}, (start, end) => {\n return (end - start) / durationMinute;\n}, (date) => {\n return date.getUTCMinutes();\n});\n\nexport const utcMinutes = utcMinute.range;\n","import {timeInterval} from \"./interval.js\";\nimport {durationHour, durationMinute, durationSecond} from \"./duration.js\";\n\nexport const timeHour = timeInterval((date) => {\n date.setTime(date - date.getMilliseconds() - date.getSeconds() * durationSecond - date.getMinutes() * durationMinute);\n}, (date, step) => {\n date.setTime(+date + step * durationHour);\n}, (start, end) => {\n return (end - start) / durationHour;\n}, (date) => {\n return date.getHours();\n});\n\nexport const timeHours = timeHour.range;\n\nexport const utcHour = timeInterval((date) => {\n date.setUTCMinutes(0, 0, 0);\n}, (date, step) => {\n date.setTime(+date + step * durationHour);\n}, (start, end) => {\n return (end - start) / durationHour;\n}, (date) => {\n return date.getUTCHours();\n});\n\nexport const utcHours = utcHour.range;\n","import {timeInterval} from \"./interval.js\";\nimport {durationDay, durationMinute} from \"./duration.js\";\n\nexport const timeDay = timeInterval(\n date => date.setHours(0, 0, 0, 0),\n (date, step) => date.setDate(date.getDate() + step),\n (start, end) => (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationDay,\n date => date.getDate() - 1\n);\n\nexport const timeDays = timeDay.range;\n\nexport const utcDay = timeInterval((date) => {\n date.setUTCHours(0, 0, 0, 0);\n}, (date, step) => {\n date.setUTCDate(date.getUTCDate() + step);\n}, (start, end) => {\n return (end - start) / durationDay;\n}, (date) => {\n return date.getUTCDate() - 1;\n});\n\nexport const utcDays = utcDay.range;\n\nexport const unixDay = timeInterval((date) => {\n date.setUTCHours(0, 0, 0, 0);\n}, (date, step) => {\n date.setUTCDate(date.getUTCDate() + step);\n}, (start, end) => {\n return (end - start) / durationDay;\n}, (date) => {\n return Math.floor(date / durationDay);\n});\n\nexport const unixDays = unixDay.range;\n","import {timeInterval} from \"./interval.js\";\nimport {durationMinute, durationWeek} from \"./duration.js\";\n\nfunction timeWeekday(i) {\n return timeInterval((date) => {\n date.setDate(date.getDate() - (date.getDay() + 7 - i) % 7);\n date.setHours(0, 0, 0, 0);\n }, (date, step) => {\n date.setDate(date.getDate() + step * 7);\n }, (start, end) => {\n return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationWeek;\n });\n}\n\nexport const timeSunday = timeWeekday(0);\nexport const timeMonday = timeWeekday(1);\nexport const timeTuesday = timeWeekday(2);\nexport const timeWednesday = timeWeekday(3);\nexport const timeThursday = timeWeekday(4);\nexport const timeFriday = timeWeekday(5);\nexport const timeSaturday = timeWeekday(6);\n\nexport const timeSundays = timeSunday.range;\nexport const timeMondays = timeMonday.range;\nexport const timeTuesdays = timeTuesday.range;\nexport const timeWednesdays = timeWednesday.range;\nexport const timeThursdays = timeThursday.range;\nexport const timeFridays = timeFriday.range;\nexport const timeSaturdays = timeSaturday.range;\n\nfunction utcWeekday(i) {\n return timeInterval((date) => {\n date.setUTCDate(date.getUTCDate() - (date.getUTCDay() + 7 - i) % 7);\n date.setUTCHours(0, 0, 0, 0);\n }, (date, step) => {\n date.setUTCDate(date.getUTCDate() + step * 7);\n }, (start, end) => {\n return (end - start) / durationWeek;\n });\n}\n\nexport const utcSunday = utcWeekday(0);\nexport const utcMonday = utcWeekday(1);\nexport const utcTuesday = utcWeekday(2);\nexport const utcWednesday = utcWeekday(3);\nexport const utcThursday = utcWeekday(4);\nexport const utcFriday = utcWeekday(5);\nexport const utcSaturday = utcWeekday(6);\n\nexport const utcSundays = utcSunday.range;\nexport const utcMondays = utcMonday.range;\nexport const utcTuesdays = utcTuesday.range;\nexport const utcWednesdays = utcWednesday.range;\nexport const utcThursdays = utcThursday.range;\nexport const utcFridays = utcFriday.range;\nexport const utcSaturdays = utcSaturday.range;\n","import {timeInterval} from \"./interval.js\";\n\nexport const timeMonth = timeInterval((date) => {\n date.setDate(1);\n date.setHours(0, 0, 0, 0);\n}, (date, step) => {\n date.setMonth(date.getMonth() + step);\n}, (start, end) => {\n return end.getMonth() - start.getMonth() + (end.getFullYear() - start.getFullYear()) * 12;\n}, (date) => {\n return date.getMonth();\n});\n\nexport const timeMonths = timeMonth.range;\n\nexport const utcMonth = timeInterval((date) => {\n date.setUTCDate(1);\n date.setUTCHours(0, 0, 0, 0);\n}, (date, step) => {\n date.setUTCMonth(date.getUTCMonth() + step);\n}, (start, end) => {\n return end.getUTCMonth() - start.getUTCMonth() + (end.getUTCFullYear() - start.getUTCFullYear()) * 12;\n}, (date) => {\n return date.getUTCMonth();\n});\n\nexport const utcMonths = utcMonth.range;\n","import {timeInterval} from \"./interval.js\";\n\nexport const timeYear = timeInterval((date) => {\n date.setMonth(0, 1);\n date.setHours(0, 0, 0, 0);\n}, (date, step) => {\n date.setFullYear(date.getFullYear() + step);\n}, (start, end) => {\n return end.getFullYear() - start.getFullYear();\n}, (date) => {\n return date.getFullYear();\n});\n\n// An optimized implementation for this simple case.\ntimeYear.every = (k) => {\n return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : timeInterval((date) => {\n date.setFullYear(Math.floor(date.getFullYear() / k) * k);\n date.setMonth(0, 1);\n date.setHours(0, 0, 0, 0);\n }, (date, step) => {\n date.setFullYear(date.getFullYear() + step * k);\n });\n};\n\nexport const timeYears = timeYear.range;\n\nexport const utcYear = timeInterval((date) => {\n date.setUTCMonth(0, 1);\n date.setUTCHours(0, 0, 0, 0);\n}, (date, step) => {\n date.setUTCFullYear(date.getUTCFullYear() + step);\n}, (start, end) => {\n return end.getUTCFullYear() - start.getUTCFullYear();\n}, (date) => {\n return date.getUTCFullYear();\n});\n\n// An optimized implementation for this simple case.\nutcYear.every = (k) => {\n return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : timeInterval((date) => {\n date.setUTCFullYear(Math.floor(date.getUTCFullYear() / k) * k);\n date.setUTCMonth(0, 1);\n date.setUTCHours(0, 0, 0, 0);\n }, (date, step) => {\n date.setUTCFullYear(date.getUTCFullYear() + step * k);\n });\n};\n\nexport const utcYears = utcYear.range;\n","import {\n timeDay,\n timeSunday,\n timeMonday,\n timeThursday,\n timeYear,\n utcDay,\n utcSunday,\n utcMonday,\n utcThursday,\n utcYear\n} from \"d3-time\";\n\nfunction localDate(d) {\n if (0 <= d.y && d.y < 100) {\n var date = new Date(-1, d.m, d.d, d.H, d.M, d.S, d.L);\n date.setFullYear(d.y);\n return date;\n }\n return new Date(d.y, d.m, d.d, d.H, d.M, d.S, d.L);\n}\n\nfunction utcDate(d) {\n if (0 <= d.y && d.y < 100) {\n var date = new Date(Date.UTC(-1, d.m, d.d, d.H, d.M, d.S, d.L));\n date.setUTCFullYear(d.y);\n return date;\n }\n return new Date(Date.UTC(d.y, d.m, d.d, d.H, d.M, d.S, d.L));\n}\n\nfunction newDate(y, m, d) {\n return {y: y, m: m, d: d, H: 0, M: 0, S: 0, L: 0};\n}\n\nexport default function formatLocale(locale) {\n var locale_dateTime = locale.dateTime,\n locale_date = locale.date,\n locale_time = locale.time,\n locale_periods = locale.periods,\n locale_weekdays = locale.days,\n locale_shortWeekdays = locale.shortDays,\n locale_months = locale.months,\n locale_shortMonths = locale.shortMonths;\n\n var periodRe = formatRe(locale_periods),\n periodLookup = formatLookup(locale_periods),\n weekdayRe = formatRe(locale_weekdays),\n weekdayLookup = formatLookup(locale_weekdays),\n shortWeekdayRe = formatRe(locale_shortWeekdays),\n shortWeekdayLookup = formatLookup(locale_shortWeekdays),\n monthRe = formatRe(locale_months),\n monthLookup = formatLookup(locale_months),\n shortMonthRe = formatRe(locale_shortMonths),\n shortMonthLookup = formatLookup(locale_shortMonths);\n\n var formats = {\n \"a\": formatShortWeekday,\n \"A\": formatWeekday,\n \"b\": formatShortMonth,\n \"B\": formatMonth,\n \"c\": null,\n \"d\": formatDayOfMonth,\n \"e\": formatDayOfMonth,\n \"f\": formatMicroseconds,\n \"g\": formatYearISO,\n \"G\": formatFullYearISO,\n \"H\": formatHour24,\n \"I\": formatHour12,\n \"j\": formatDayOfYear,\n \"L\": formatMilliseconds,\n \"m\": formatMonthNumber,\n \"M\": formatMinutes,\n \"p\": formatPeriod,\n \"q\": formatQuarter,\n \"Q\": formatUnixTimestamp,\n \"s\": formatUnixTimestampSeconds,\n \"S\": formatSeconds,\n \"u\": formatWeekdayNumberMonday,\n \"U\": formatWeekNumberSunday,\n \"V\": formatWeekNumberISO,\n \"w\": formatWeekdayNumberSunday,\n \"W\": formatWeekNumberMonday,\n \"x\": null,\n \"X\": null,\n \"y\": formatYear,\n \"Y\": formatFullYear,\n \"Z\": formatZone,\n \"%\": formatLiteralPercent\n };\n\n var utcFormats = {\n \"a\": formatUTCShortWeekday,\n \"A\": formatUTCWeekday,\n \"b\": formatUTCShortMonth,\n \"B\": formatUTCMonth,\n \"c\": null,\n \"d\": formatUTCDayOfMonth,\n \"e\": formatUTCDayOfMonth,\n \"f\": formatUTCMicroseconds,\n \"g\": formatUTCYearISO,\n \"G\": formatUTCFullYearISO,\n \"H\": formatUTCHour24,\n \"I\": formatUTCHour12,\n \"j\": formatUTCDayOfYear,\n \"L\": formatUTCMilliseconds,\n \"m\": formatUTCMonthNumber,\n \"M\": formatUTCMinutes,\n \"p\": formatUTCPeriod,\n \"q\": formatUTCQuarter,\n \"Q\": formatUnixTimestamp,\n \"s\": formatUnixTimestampSeconds,\n \"S\": formatUTCSeconds,\n \"u\": formatUTCWeekdayNumberMonday,\n \"U\": formatUTCWeekNumberSunday,\n \"V\": formatUTCWeekNumberISO,\n \"w\": formatUTCWeekdayNumberSunday,\n \"W\": formatUTCWeekNumberMonday,\n \"x\": null,\n \"X\": null,\n \"y\": formatUTCYear,\n \"Y\": formatUTCFullYear,\n \"Z\": formatUTCZone,\n \"%\": formatLiteralPercent\n };\n\n var parses = {\n \"a\": parseShortWeekday,\n \"A\": parseWeekday,\n \"b\": parseShortMonth,\n \"B\": parseMonth,\n \"c\": parseLocaleDateTime,\n \"d\": parseDayOfMonth,\n \"e\": parseDayOfMonth,\n \"f\": parseMicroseconds,\n \"g\": parseYear,\n \"G\": parseFullYear,\n \"H\": parseHour24,\n \"I\": parseHour24,\n \"j\": parseDayOfYear,\n \"L\": parseMilliseconds,\n \"m\": parseMonthNumber,\n \"M\": parseMinutes,\n \"p\": parsePeriod,\n \"q\": parseQuarter,\n \"Q\": parseUnixTimestamp,\n \"s\": parseUnixTimestampSeconds,\n \"S\": parseSeconds,\n \"u\": parseWeekdayNumberMonday,\n \"U\": parseWeekNumberSunday,\n \"V\": parseWeekNumberISO,\n \"w\": parseWeekdayNumberSunday,\n \"W\": parseWeekNumberMonday,\n \"x\": parseLocaleDate,\n \"X\": parseLocaleTime,\n \"y\": parseYear,\n \"Y\": parseFullYear,\n \"Z\": parseZone,\n \"%\": parseLiteralPercent\n };\n\n // These recursive directive definitions must be deferred.\n formats.x = newFormat(locale_date, formats);\n formats.X = newFormat(locale_time, formats);\n formats.c = newFormat(locale_dateTime, formats);\n utcFormats.x = newFormat(locale_date, utcFormats);\n utcFormats.X = newFormat(locale_time, utcFormats);\n utcFormats.c = newFormat(locale_dateTime, utcFormats);\n\n function newFormat(specifier, formats) {\n return function(date) {\n var string = [],\n i = -1,\n j = 0,\n n = specifier.length,\n c,\n pad,\n format;\n\n if (!(date instanceof Date)) date = new Date(+date);\n\n while (++i < n) {\n if (specifier.charCodeAt(i) === 37) {\n string.push(specifier.slice(j, i));\n if ((pad = pads[c = specifier.charAt(++i)]) != null) c = specifier.charAt(++i);\n else pad = c === \"e\" ? \" \" : \"0\";\n if (format = formats[c]) c = format(date, pad);\n string.push(c);\n j = i + 1;\n }\n }\n\n string.push(specifier.slice(j, i));\n return string.join(\"\");\n };\n }\n\n function newParse(specifier, Z) {\n return function(string) {\n var d = newDate(1900, undefined, 1),\n i = parseSpecifier(d, specifier, string += \"\", 0),\n week, day;\n if (i != string.length) return null;\n\n // If a UNIX timestamp is specified, return it.\n if (\"Q\" in d) return new Date(d.Q);\n if (\"s\" in d) return new Date(d.s * 1000 + (\"L\" in d ? d.L : 0));\n\n // If this is utcParse, never use the local timezone.\n if (Z && !(\"Z\" in d)) d.Z = 0;\n\n // The am-pm flag is 0 for AM, and 1 for PM.\n if (\"p\" in d) d.H = d.H % 12 + d.p * 12;\n\n // If the month was not specified, inherit from the quarter.\n if (d.m === undefined) d.m = \"q\" in d ? d.q : 0;\n\n // Convert day-of-week and week-of-year to day-of-year.\n if (\"V\" in d) {\n if (d.V < 1 || d.V > 53) return null;\n if (!(\"w\" in d)) d.w = 1;\n if (\"Z\" in d) {\n week = utcDate(newDate(d.y, 0, 1)), day = week.getUTCDay();\n week = day > 4 || day === 0 ? utcMonday.ceil(week) : utcMonday(week);\n week = utcDay.offset(week, (d.V - 1) * 7);\n d.y = week.getUTCFullYear();\n d.m = week.getUTCMonth();\n d.d = week.getUTCDate() + (d.w + 6) % 7;\n } else {\n week = localDate(newDate(d.y, 0, 1)), day = week.getDay();\n week = day > 4 || day === 0 ? timeMonday.ceil(week) : timeMonday(week);\n week = timeDay.offset(week, (d.V - 1) * 7);\n d.y = week.getFullYear();\n d.m = week.getMonth();\n d.d = week.getDate() + (d.w + 6) % 7;\n }\n } else if (\"W\" in d || \"U\" in d) {\n if (!(\"w\" in d)) d.w = \"u\" in d ? d.u % 7 : \"W\" in d ? 1 : 0;\n day = \"Z\" in d ? utcDate(newDate(d.y, 0, 1)).getUTCDay() : localDate(newDate(d.y, 0, 1)).getDay();\n d.m = 0;\n d.d = \"W\" in d ? (d.w + 6) % 7 + d.W * 7 - (day + 5) % 7 : d.w + d.U * 7 - (day + 6) % 7;\n }\n\n // If a time zone is specified, all fields are interpreted as UTC and then\n // offset according to the specified time zone.\n if (\"Z\" in d) {\n d.H += d.Z / 100 | 0;\n d.M += d.Z % 100;\n return utcDate(d);\n }\n\n // Otherwise, all fields are in local time.\n return localDate(d);\n };\n }\n\n function parseSpecifier(d, specifier, string, j) {\n var i = 0,\n n = specifier.length,\n m = string.length,\n c,\n parse;\n\n while (i < n) {\n if (j >= m) return -1;\n c = specifier.charCodeAt(i++);\n if (c === 37) {\n c = specifier.charAt(i++);\n parse = parses[c in pads ? specifier.charAt(i++) : c];\n if (!parse || ((j = parse(d, string, j)) < 0)) return -1;\n } else if (c != string.charCodeAt(j++)) {\n return -1;\n }\n }\n\n return j;\n }\n\n function parsePeriod(d, string, i) {\n var n = periodRe.exec(string.slice(i));\n return n ? (d.p = periodLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;\n }\n\n function parseShortWeekday(d, string, i) {\n var n = shortWeekdayRe.exec(string.slice(i));\n return n ? (d.w = shortWeekdayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;\n }\n\n function parseWeekday(d, string, i) {\n var n = weekdayRe.exec(string.slice(i));\n return n ? (d.w = weekdayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;\n }\n\n function parseShortMonth(d, string, i) {\n var n = shortMonthRe.exec(string.slice(i));\n return n ? (d.m = shortMonthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;\n }\n\n function parseMonth(d, string, i) {\n var n = monthRe.exec(string.slice(i));\n return n ? (d.m = monthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;\n }\n\n function parseLocaleDateTime(d, string, i) {\n return parseSpecifier(d, locale_dateTime, string, i);\n }\n\n function parseLocaleDate(d, string, i) {\n return parseSpecifier(d, locale_date, string, i);\n }\n\n function parseLocaleTime(d, string, i) {\n return parseSpecifier(d, locale_time, string, i);\n }\n\n function formatShortWeekday(d) {\n return locale_shortWeekdays[d.getDay()];\n }\n\n function formatWeekday(d) {\n return locale_weekdays[d.getDay()];\n }\n\n function formatShortMonth(d) {\n return locale_shortMonths[d.getMonth()];\n }\n\n function formatMonth(d) {\n return locale_months[d.getMonth()];\n }\n\n function formatPeriod(d) {\n return locale_periods[+(d.getHours() >= 12)];\n }\n\n function formatQuarter(d) {\n return 1 + ~~(d.getMonth() / 3);\n }\n\n function formatUTCShortWeekday(d) {\n return locale_shortWeekdays[d.getUTCDay()];\n }\n\n function formatUTCWeekday(d) {\n return locale_weekdays[d.getUTCDay()];\n }\n\n function formatUTCShortMonth(d) {\n return locale_shortMonths[d.getUTCMonth()];\n }\n\n function formatUTCMonth(d) {\n return locale_months[d.getUTCMonth()];\n }\n\n function formatUTCPeriod(d) {\n return locale_periods[+(d.getUTCHours() >= 12)];\n }\n\n function formatUTCQuarter(d) {\n return 1 + ~~(d.getUTCMonth() / 3);\n }\n\n return {\n format: function(specifier) {\n var f = newFormat(specifier += \"\", formats);\n f.toString = function() { return specifier; };\n return f;\n },\n parse: function(specifier) {\n var p = newParse(specifier += \"\", false);\n p.toString = function() { return specifier; };\n return p;\n },\n utcFormat: function(specifier) {\n var f = newFormat(specifier += \"\", utcFormats);\n f.toString = function() { return specifier; };\n return f;\n },\n utcParse: function(specifier) {\n var p = newParse(specifier += \"\", true);\n p.toString = function() { return specifier; };\n return p;\n }\n };\n}\n\nvar pads = {\"-\": \"\", \"_\": \" \", \"0\": \"0\"},\n numberRe = /^\\s*\\d+/, // note: ignores next directive\n percentRe = /^%/,\n requoteRe = /[\\\\^$*+?|[\\]().{}]/g;\n\nfunction pad(value, fill, width) {\n var sign = value < 0 ? \"-\" : \"\",\n string = (sign ? -value : value) + \"\",\n length = string.length;\n return sign + (length < width ? new Array(width - length + 1).join(fill) + string : string);\n}\n\nfunction requote(s) {\n return s.replace(requoteRe, \"\\\\$&\");\n}\n\nfunction formatRe(names) {\n return new RegExp(\"^(?:\" + names.map(requote).join(\"|\") + \")\", \"i\");\n}\n\nfunction formatLookup(names) {\n return new Map(names.map((name, i) => [name.toLowerCase(), i]));\n}\n\nfunction parseWeekdayNumberSunday(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 1));\n return n ? (d.w = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseWeekdayNumberMonday(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 1));\n return n ? (d.u = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseWeekNumberSunday(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.U = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseWeekNumberISO(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.V = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseWeekNumberMonday(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.W = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseFullYear(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 4));\n return n ? (d.y = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseYear(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.y = +n[0] + (+n[0] > 68 ? 1900 : 2000), i + n[0].length) : -1;\n}\n\nfunction parseZone(d, string, i) {\n var n = /^(Z)|([+-]\\d\\d)(?::?(\\d\\d))?/.exec(string.slice(i, i + 6));\n return n ? (d.Z = n[1] ? 0 : -(n[2] + (n[3] || \"00\")), i + n[0].length) : -1;\n}\n\nfunction parseQuarter(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 1));\n return n ? (d.q = n[0] * 3 - 3, i + n[0].length) : -1;\n}\n\nfunction parseMonthNumber(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.m = n[0] - 1, i + n[0].length) : -1;\n}\n\nfunction parseDayOfMonth(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.d = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseDayOfYear(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 3));\n return n ? (d.m = 0, d.d = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseHour24(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.H = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseMinutes(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.M = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseSeconds(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.S = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseMilliseconds(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 3));\n return n ? (d.L = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseMicroseconds(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 6));\n return n ? (d.L = Math.floor(n[0] / 1000), i + n[0].length) : -1;\n}\n\nfunction parseLiteralPercent(d, string, i) {\n var n = percentRe.exec(string.slice(i, i + 1));\n return n ? i + n[0].length : -1;\n}\n\nfunction parseUnixTimestamp(d, string, i) {\n var n = numberRe.exec(string.slice(i));\n return n ? (d.Q = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseUnixTimestampSeconds(d, string, i) {\n var n = numberRe.exec(string.slice(i));\n return n ? (d.s = +n[0], i + n[0].length) : -1;\n}\n\nfunction formatDayOfMonth(d, p) {\n return pad(d.getDate(), p, 2);\n}\n\nfunction formatHour24(d, p) {\n return pad(d.getHours(), p, 2);\n}\n\nfunction formatHour12(d, p) {\n return pad(d.getHours() % 12 || 12, p, 2);\n}\n\nfunction formatDayOfYear(d, p) {\n return pad(1 + timeDay.count(timeYear(d), d), p, 3);\n}\n\nfunction formatMilliseconds(d, p) {\n return pad(d.getMilliseconds(), p, 3);\n}\n\nfunction formatMicroseconds(d, p) {\n return formatMilliseconds(d, p) + \"000\";\n}\n\nfunction formatMonthNumber(d, p) {\n return pad(d.getMonth() + 1, p, 2);\n}\n\nfunction formatMinutes(d, p) {\n return pad(d.getMinutes(), p, 2);\n}\n\nfunction formatSeconds(d, p) {\n return pad(d.getSeconds(), p, 2);\n}\n\nfunction formatWeekdayNumberMonday(d) {\n var day = d.getDay();\n return day === 0 ? 7 : day;\n}\n\nfunction formatWeekNumberSunday(d, p) {\n return pad(timeSunday.count(timeYear(d) - 1, d), p, 2);\n}\n\nfunction dISO(d) {\n var day = d.getDay();\n return (day >= 4 || day === 0) ? timeThursday(d) : timeThursday.ceil(d);\n}\n\nfunction formatWeekNumberISO(d, p) {\n d = dISO(d);\n return pad(timeThursday.count(timeYear(d), d) + (timeYear(d).getDay() === 4), p, 2);\n}\n\nfunction formatWeekdayNumberSunday(d) {\n return d.getDay();\n}\n\nfunction formatWeekNumberMonday(d, p) {\n return pad(timeMonday.count(timeYear(d) - 1, d), p, 2);\n}\n\nfunction formatYear(d, p) {\n return pad(d.getFullYear() % 100, p, 2);\n}\n\nfunction formatYearISO(d, p) {\n d = dISO(d);\n return pad(d.getFullYear() % 100, p, 2);\n}\n\nfunction formatFullYear(d, p) {\n return pad(d.getFullYear() % 10000, p, 4);\n}\n\nfunction formatFullYearISO(d, p) {\n var day = d.getDay();\n d = (day >= 4 || day === 0) ? timeThursday(d) : timeThursday.ceil(d);\n return pad(d.getFullYear() % 10000, p, 4);\n}\n\nfunction formatZone(d) {\n var z = d.getTimezoneOffset();\n return (z > 0 ? \"-\" : (z *= -1, \"+\"))\n + pad(z / 60 | 0, \"0\", 2)\n + pad(z % 60, \"0\", 2);\n}\n\nfunction formatUTCDayOfMonth(d, p) {\n return pad(d.getUTCDate(), p, 2);\n}\n\nfunction formatUTCHour24(d, p) {\n return pad(d.getUTCHours(), p, 2);\n}\n\nfunction formatUTCHour12(d, p) {\n return pad(d.getUTCHours() % 12 || 12, p, 2);\n}\n\nfunction formatUTCDayOfYear(d, p) {\n return pad(1 + utcDay.count(utcYear(d), d), p, 3);\n}\n\nfunction formatUTCMilliseconds(d, p) {\n return pad(d.getUTCMilliseconds(), p, 3);\n}\n\nfunction formatUTCMicroseconds(d, p) {\n return formatUTCMilliseconds(d, p) + \"000\";\n}\n\nfunction formatUTCMonthNumber(d, p) {\n return pad(d.getUTCMonth() + 1, p, 2);\n}\n\nfunction formatUTCMinutes(d, p) {\n return pad(d.getUTCMinutes(), p, 2);\n}\n\nfunction formatUTCSeconds(d, p) {\n return pad(d.getUTCSeconds(), p, 2);\n}\n\nfunction formatUTCWeekdayNumberMonday(d) {\n var dow = d.getUTCDay();\n return dow === 0 ? 7 : dow;\n}\n\nfunction formatUTCWeekNumberSunday(d, p) {\n return pad(utcSunday.count(utcYear(d) - 1, d), p, 2);\n}\n\nfunction UTCdISO(d) {\n var day = d.getUTCDay();\n return (day >= 4 || day === 0) ? utcThursday(d) : utcThursday.ceil(d);\n}\n\nfunction formatUTCWeekNumberISO(d, p) {\n d = UTCdISO(d);\n return pad(utcThursday.count(utcYear(d), d) + (utcYear(d).getUTCDay() === 4), p, 2);\n}\n\nfunction formatUTCWeekdayNumberSunday(d) {\n return d.getUTCDay();\n}\n\nfunction formatUTCWeekNumberMonday(d, p) {\n return pad(utcMonday.count(utcYear(d) - 1, d), p, 2);\n}\n\nfunction formatUTCYear(d, p) {\n return pad(d.getUTCFullYear() % 100, p, 2);\n}\n\nfunction formatUTCYearISO(d, p) {\n d = UTCdISO(d);\n return pad(d.getUTCFullYear() % 100, p, 2);\n}\n\nfunction formatUTCFullYear(d, p) {\n return pad(d.getUTCFullYear() % 10000, p, 4);\n}\n\nfunction formatUTCFullYearISO(d, p) {\n var day = d.getUTCDay();\n d = (day >= 4 || day === 0) ? utcThursday(d) : utcThursday.ceil(d);\n return pad(d.getUTCFullYear() % 10000, p, 4);\n}\n\nfunction formatUTCZone() {\n return \"+0000\";\n}\n\nfunction formatLiteralPercent() {\n return \"%\";\n}\n\nfunction formatUnixTimestamp(d) {\n return +d;\n}\n\nfunction formatUnixTimestampSeconds(d) {\n return Math.floor(+d / 1000);\n}\n","import formatLocale from \"./locale.js\";\n\nvar locale;\nexport var timeFormat;\nexport var timeParse;\nexport var utcFormat;\nexport var utcParse;\n\ndefaultLocale({\n dateTime: \"%x, %X\",\n date: \"%-m/%-d/%Y\",\n time: \"%-I:%M:%S %p\",\n periods: [\"AM\", \"PM\"],\n days: [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"],\n shortDays: [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"],\n months: [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"],\n shortMonths: [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"]\n});\n\nexport default function defaultLocale(definition) {\n locale = formatLocale(definition);\n timeFormat = locale.format;\n timeParse = locale.parse;\n utcFormat = locale.utcFormat;\n utcParse = locale.utcParse;\n return locale;\n}\n","import {interpolate, interpolateRound} from \"d3-interpolate\";\nimport {identity} from \"./continuous.js\";\nimport {initInterpolator} from \"./init.js\";\nimport {linearish} from \"./linear.js\";\nimport {loggish} from \"./log.js\";\nimport {symlogish} from \"./symlog.js\";\nimport {powish} from \"./pow.js\";\n\nfunction transformer() {\n var x0 = 0,\n x1 = 1,\n t0,\n t1,\n k10,\n transform,\n interpolator = identity,\n clamp = false,\n unknown;\n\n function scale(x) {\n return x == null || isNaN(x = +x) ? unknown : interpolator(k10 === 0 ? 0.5 : (x = (transform(x) - t0) * k10, clamp ? Math.max(0, Math.min(1, x)) : x));\n }\n\n scale.domain = function(_) {\n return arguments.length ? ([x0, x1] = _, t0 = transform(x0 = +x0), t1 = transform(x1 = +x1), k10 = t0 === t1 ? 0 : 1 / (t1 - t0), scale) : [x0, x1];\n };\n\n scale.clamp = function(_) {\n return arguments.length ? (clamp = !!_, scale) : clamp;\n };\n\n scale.interpolator = function(_) {\n return arguments.length ? (interpolator = _, scale) : interpolator;\n };\n\n function range(interpolate) {\n return function(_) {\n var r0, r1;\n return arguments.length ? ([r0, r1] = _, interpolator = interpolate(r0, r1), scale) : [interpolator(0), interpolator(1)];\n };\n }\n\n scale.range = range(interpolate);\n\n scale.rangeRound = range(interpolateRound);\n\n scale.unknown = function(_) {\n return arguments.length ? (unknown = _, scale) : unknown;\n };\n\n return function(t) {\n transform = t, t0 = t(x0), t1 = t(x1), k10 = t0 === t1 ? 0 : 1 / (t1 - t0);\n return scale;\n };\n}\n\nexport function copy(source, target) {\n return target\n .domain(source.domain())\n .interpolator(source.interpolator())\n .clamp(source.clamp())\n .unknown(source.unknown());\n}\n\nexport default function sequential() {\n var scale = linearish(transformer()(identity));\n\n scale.copy = function() {\n return copy(scale, sequential());\n };\n\n return initInterpolator.apply(scale, arguments);\n}\n\nexport function sequentialLog() {\n var scale = loggish(transformer()).domain([1, 10]);\n\n scale.copy = function() {\n return copy(scale, sequentialLog()).base(scale.base());\n };\n\n return initInterpolator.apply(scale, arguments);\n}\n\nexport function sequentialSymlog() {\n var scale = symlogish(transformer());\n\n scale.copy = function() {\n return copy(scale, sequentialSymlog()).constant(scale.constant());\n };\n\n return initInterpolator.apply(scale, arguments);\n}\n\nexport function sequentialPow() {\n var scale = powish(transformer());\n\n scale.copy = function() {\n return copy(scale, sequentialPow()).exponent(scale.exponent());\n };\n\n return initInterpolator.apply(scale, arguments);\n}\n\nexport function sequentialSqrt() {\n return sequentialPow.apply(null, arguments).exponent(0.5);\n}\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n interpolateCool,\n interpolateInferno,\n interpolateMagma,\n interpolatePlasma,\n interpolateViridis,\n interpolateWarm,\n schemeBlues,\n schemeBuGn,\n schemeBuPu,\n schemeGnBu,\n schemeGreens,\n schemeGreys,\n schemeOranges,\n schemeOrRd,\n schemePuBu,\n schemePuBuGn,\n schemePuRd,\n schemePurples,\n schemeRdPu,\n schemeReds,\n schemeYlGn,\n schemeYlGnBu,\n schemeYlOrBr,\n schemeYlOrRd,\n} from 'd3-scale-chromatic';\nimport {range} from 'd3-array';\nimport {scalePow, scaleSequential, scaleSequentialPow} from 'd3-scale';\nimport {interpolateBasis, interpolateRgbBasis} from 'd3-interpolate';\nimport {color as d3color, hcl, rgb as colorRgb} from 'd3-color';\nimport {SettingsState} from './FlowmapState';\nimport {FlowLinesRenderingMode} from './types';\n\nconst DEFAULT_OUTLINE_COLOR = '#fff';\nconst DEFAULT_DIMMED_OPACITY = 0.4;\nconst DEFAULT_FLOW_MIN_COLOR = 'rgba(240,240,240,0.5)';\nconst DEFAULT_FLOW_COLOR_SCHEME = [DEFAULT_FLOW_MIN_COLOR, '#137CBD'];\nconst DEFAULT_LOCATION_AREA_COLOR = 'rgba(220,220,220,0.5)';\n\nconst DEFAULT_FLOW_COLOR_SCHEME_POSITIVE = [DEFAULT_FLOW_MIN_COLOR, '#f6654e'];\nconst DEFAULT_FLOW_COLOR_SCHEME_NEGATIVE = [DEFAULT_FLOW_MIN_COLOR, '#00a9cc'];\n\nexport type ColorScale = (value: number) => RGBA;\nexport type RGBA = [number, number, number, number];\n\nconst FALLBACK_COLOR_RGBA: RGBA = [255, 255, 255, 255];\n\nexport function opacityFloatToInteger(opacity: number): number {\n return Math.round(opacity * 255);\n}\n\nexport function opacifyHex(hexCode: string, opacity: number): string {\n const c = d3color(hexCode);\n if (!c) {\n console.warn('Invalid color: ', hexCode);\n return `rgba(255, 255, 255, ${opacity})`;\n }\n const col = c.rgb();\n return `rgba(${col.r}, ${col.g}, ${col.b}, ${opacity})`;\n}\n\nexport function colorAsRgba(color: string | number[]): RGBA {\n if (Array.isArray(color)) {\n return color as RGBA;\n }\n const col = d3color(color);\n if (!col) {\n console.warn('Invalid color: ', color);\n return FALLBACK_COLOR_RGBA;\n }\n const rgbColor = col.rgb();\n return [\n Math.floor(rgbColor.r),\n Math.floor(rgbColor.g),\n Math.floor(rgbColor.b),\n opacityFloatToInteger(col.opacity),\n ];\n}\n\nfunction colorAsRgbaOr(\n color: string | undefined,\n defaultColor: RGBA | string,\n): RGBA {\n if (color) {\n return colorAsRgba(color);\n }\n if (typeof defaultColor === 'string') {\n return colorAsRgba(defaultColor);\n }\n return defaultColor;\n}\n\nconst asScheme = (scheme: ReadonlyArray>) =>\n scheme[scheme.length - 1] as string[];\n\nexport enum ColorScheme {\n primary = '#162d3c',\n}\n\nconst SCALE_NUM_STEPS = 20;\nconst getColorSteps = (interpolate: (x: number) => string) =>\n range(0, SCALE_NUM_STEPS + 1)\n .map((i) => interpolate(i / SCALE_NUM_STEPS))\n .reverse();\n\nconst FLOW_MIN_COLOR = 'rgba(240,240,240,0.5)';\nexport const GRAYISH = [FLOW_MIN_COLOR, ColorScheme.primary];\nconst schemeBluYl = [\n '#f7feae',\n '#b7e6a5',\n '#7ccba2',\n '#46aea0',\n '#089099',\n '#00718b',\n '#045275',\n];\n\nconst schemeEmrld = [\n '#d3f2a3',\n '#97e196',\n '#6cc08b',\n '#4c9b82',\n '#217a79',\n '#105965',\n '#074050',\n];\n\nexport const schemeTeal = [\n '#d1eeea',\n '#a8dbd9',\n '#85c4c9',\n '#68abb8',\n '#4f90a6',\n '#3b738f',\n '#2a5674',\n];\n\nexport const DEFAULT_COLOR_SCHEME = schemeTeal;\nexport const COLOR_SCHEMES: {[key: string]: string[]} = {\n Blues: asScheme(schemeBlues),\n BluGrn: [\n '#c4e6c3',\n '#96d2a4',\n '#6dbc90',\n '#4da284',\n '#36877a',\n '#266b6e',\n '#1d4f60',\n ],\n BluYl: schemeBluYl,\n BrwnYl: [\n '#ede5cf',\n '#e0c2a2',\n '#d39c83',\n '#c1766f',\n '#a65461',\n '#813753',\n '#541f3f',\n ],\n BuGn: asScheme(schemeBuGn),\n BuPu: asScheme(schemeBuPu),\n Burg: [\n '#ffc6c4',\n '#f4a3a8',\n '#e38191',\n '#cc607d',\n '#ad466c',\n '#8b3058',\n '#672044',\n ],\n BurgYl: [\n '#fbe6c5',\n '#f5ba98',\n '#ee8a82',\n '#dc7176',\n '#c8586c',\n '#9c3f5d',\n '#70284a',\n ],\n Cool: getColorSteps(interpolateCool),\n DarkMint: [\n '#d2fbd4',\n '#a5dbc2',\n '#7bbcb0',\n '#559c9e',\n '#3a7c89',\n '#235d72',\n '#123f5a',\n ],\n Emrld: schemeEmrld,\n GnBu: asScheme(schemeGnBu),\n Grayish: GRAYISH,\n Greens: asScheme(schemeGreens),\n Greys: asScheme(schemeGreys),\n Inferno: getColorSteps(interpolateInferno),\n Magenta: [\n '#f3cbd3',\n '#eaa9bd',\n '#dd88ac',\n '#ca699d',\n '#b14d8e',\n '#91357d',\n '#6c2167',\n ],\n Magma: getColorSteps(interpolateMagma),\n Mint: [\n '#e4f1e1',\n '#b4d9cc',\n '#89c0b6',\n '#63a6a0',\n '#448c8a',\n '#287274',\n '#0d585f',\n ],\n Oranges: asScheme(schemeOranges),\n OrRd: asScheme(schemeOrRd),\n OrYel: [\n '#ecda9a',\n '#efc47e',\n '#f3ad6a',\n '#f7945d',\n '#f97b57',\n '#f66356',\n '#ee4d5a',\n ],\n Peach: [\n '#fde0c5',\n '#facba6',\n '#f8b58b',\n '#f59e72',\n '#f2855d',\n '#ef6a4c',\n '#eb4a40',\n ],\n Plasma: getColorSteps(interpolatePlasma),\n PinkYl: [\n '#fef6b5',\n '#ffdd9a',\n '#ffc285',\n '#ffa679',\n '#fa8a76',\n '#f16d7a',\n '#e15383',\n ],\n PuBu: asScheme(schemePuBu),\n PuBuGn: asScheme(schemePuBuGn),\n PuRd: asScheme(schemePuRd),\n Purp: [\n '#f3e0f7',\n '#e4c7f1',\n '#d1afe8',\n '#b998dd',\n '#9f82ce',\n '#826dba',\n '#63589f',\n ],\n Purples: asScheme(schemePurples),\n PurpOr: [\n '#f9ddda',\n '#f2b9c4',\n '#e597b9',\n '#ce78b3',\n '#ad5fad',\n '#834ba0',\n '#573b88',\n ],\n RdPu: asScheme(schemeRdPu),\n RedOr: [\n '#f6d2a9',\n '#f5b78e',\n '#f19c7c',\n '#ea8171',\n '#dd686c',\n '#ca5268',\n '#b13f64',\n ],\n Reds: asScheme(schemeReds),\n Sunset: [\n '#f3e79b',\n '#fac484',\n '#f8a07e',\n '#eb7f86',\n '#ce6693',\n '#a059a0',\n '#5c53a5',\n ],\n SunsetDark: [\n '#fcde9c',\n '#faa476',\n '#f0746e',\n '#e34f6f',\n '#dc3977',\n '#b9257a',\n '#7c1d6f',\n ],\n Teal: schemeTeal,\n TealGrn: [\n '#b0f2bc',\n '#89e8ac',\n '#67dba5',\n '#4cc8a3',\n '#38b2a3',\n '#2c98a0',\n '#257d98',\n ],\n Viridis: getColorSteps(interpolateViridis),\n Warm: getColorSteps(interpolateWarm),\n YlGn: asScheme(schemeYlGn),\n YlGnBu: asScheme(schemeYlGnBu),\n YlOrBr: asScheme(schemeYlOrBr),\n YlOrRd: asScheme(schemeYlOrRd),\n};\n\nexport const COLOR_SCHEME_KEYS = Object.keys(COLOR_SCHEMES);\n\nconst complementary = '#f52020';\nconst baseDiffColor = '#17a5be';\n\nconst diffColors: DiffColors = {\n negative: {\n flows: {\n scheme: [FLOW_MIN_COLOR, baseDiffColor],\n },\n },\n positive: {\n flows: {\n scheme: [FLOW_MIN_COLOR, complementary],\n },\n },\n locationAreas: {\n outline: 'rgba(92,112,128,0.5)',\n normal: 'rgba(220,220,220,0.5)',\n },\n outlineColor: 'rgb(230,233,237)',\n};\n\nexport function getFlowmapColors(settings: SettingsState): Colors | DiffColors {\n return getColors(\n false, // TODO: diffMode\n settings.colorScheme,\n settings.darkMode,\n settings.fadeEnabled,\n settings.fadeOpacityEnabled,\n settings.fadeAmount,\n isAnimatedFlowLinesMode(settings.flowLinesRenderingMode),\n );\n}\n\nfunction isAnimatedFlowLinesMode(\n flowLinesRenderingMode: FlowLinesRenderingMode,\n): boolean {\n return flowLinesRenderingMode === 'animated-straight';\n}\n\nexport function getColors(\n diffMode: boolean,\n colorScheme: string | string[] | undefined,\n darkMode: boolean,\n fadeEnabled: boolean,\n fadeOpacityEnabled: boolean,\n fadeAmount: number,\n animate: boolean,\n): Colors | DiffColors {\n if (diffMode) {\n return diffColors;\n }\n\n let scheme;\n\n if (Array.isArray(colorScheme)) {\n scheme = colorScheme;\n } else {\n scheme =\n (colorScheme && COLOR_SCHEMES[colorScheme]) || DEFAULT_COLOR_SCHEME;\n if (darkMode) {\n scheme = scheme.slice().reverse();\n }\n }\n\n // if (animate)\n // if (fadeAmount > 0)\n {\n const indices = range(0, Math.max(10, scheme.length));\n const N = indices.length - 1;\n const colorScale = scaleSequential(interpolateRgbBasis(scheme)).domain([\n 0,\n N,\n ]);\n\n if (!fadeEnabled || fadeAmount === 0) {\n scheme = indices.map((c, i) => colorScale(i));\n } else {\n const amount = scalePow()\n // .exponent(animate ? 1 : 1/2.5)\n // .exponent(animate ? 100 : 50)\n // .exponent(animate ? 20 : 5)\n // .exponent(1/2.5)\n .exponent(1.5)\n .domain([N, 0])\n // .range([fadeAmount/100*(animate?2:1), 0])\n // .range([0, fadeAmount/100*(animate?2:1)])\n // .range(darkMode ? [1-fadeAmount/100, 1] : [1, 1 - fadeAmount/100])\n // .range(darkMode ? [1 - fadeAmount/100, 1] : [fadeAmount/100, 0])\n // .range([1 - fadeAmount/100, 1])\n .range([0, (2 * fadeAmount) / 100]);\n\n scheme = indices.map(\n (c, i) => {\n const color = colorScale(i);\n const a = amount(i);\n if (color == null || a == null) return '#000';\n const col = hcl(color);\n col.l = darkMode ? col.l - col.l * a : col.l + (100 - col.l) * a;\n col.c = col.c - col.c * (a / 4);\n if (fadeOpacityEnabled) {\n col.opacity = col.opacity * (1.0 - a);\n }\n return col.toString();\n },\n // interpolateRgbBasis([colorScale(i), darkMode ? '#000' : '#fff'])(amount(i))\n // interpolateHsl(colorScale(i), darkMode ? '#000' : '#fff')(amount(i)).toString()\n );\n }\n }\n\n return {\n darkMode,\n flows: {\n scheme,\n },\n locationCircles: {\n outgoing: darkMode ? '#000' : '#fff',\n },\n outlineColor: darkMode ? '#000' : 'rgba(255, 255, 255, 0.5)',\n };\n}\n\nfunction interpolateRgbaBasis(colors: string[]) {\n const spline = interpolateBasis;\n const n = colors.length;\n let r: any = new Array(n),\n g: any = new Array(n),\n b: any = new Array(n),\n opacity: any = new Array(n),\n i,\n color: any;\n for (i = 0; i < n; ++i) {\n color = colorRgb(colors[i]);\n r[i] = color.r || 0;\n g[i] = color.g || 0;\n b[i] = color.b || 0;\n opacity[i] = color.opacity || 0;\n }\n r = spline(r);\n g = spline(g);\n b = spline(b);\n opacity = spline(opacity);\n // color.opacity = 1;\n return function (t: number) {\n color.r = r(t);\n color.g = g(t);\n color.b = b(t);\n color.opacity = opacity(t);\n return color + '';\n };\n}\n\nexport function createFlowColorScale(\n domain: [number, number],\n scheme: string[],\n animate: boolean | undefined,\n): ColorScale {\n const scale = scaleSequentialPow(interpolateRgbaBasis(scheme))\n // @ts-ignore\n .exponent(animate ? 1 / 2 : 1 / 3)\n .domain(domain);\n\n return (value: number) => colorAsRgba(scale(value));\n}\n\nexport function getFlowColorScale(\n colors: ColorsRGBA | DiffColorsRGBA,\n magnitudeExtent: [number, number] | undefined,\n animate: boolean | undefined,\n): (magnitude: number) => [number, number, number, number] {\n const minMagnitude = magnitudeExtent ? magnitudeExtent[0] : 0;\n const maxMagnitude = magnitudeExtent ? magnitudeExtent[1] : 0;\n if (isDiffColorsRGBA(colors)) {\n const posScale = createFlowColorScale(\n [0, maxMagnitude],\n colors.positive.flows.scheme,\n animate,\n );\n const negScale = createFlowColorScale(\n [0, minMagnitude],\n colors.negative.flows.scheme,\n animate,\n );\n\n return (magnitude: number) =>\n magnitude >= 0 ? posScale(magnitude) : negScale(magnitude);\n }\n\n const scale = createFlowColorScale(\n [0, maxMagnitude || 0],\n colors.flows.scheme,\n animate,\n );\n return (magnitude: number) => scale(magnitude);\n}\n\nexport function isDiffColors(\n colors: DiffColors | Colors,\n): colors is DiffColors {\n return (colors as DiffColors).positive !== undefined;\n}\n\nexport function isDiffColorsRGBA(\n colors: DiffColorsRGBA | ColorsRGBA,\n): colors is DiffColorsRGBA {\n return (colors as DiffColorsRGBA).positive !== undefined;\n}\n\nfunction getLocationAreaColorsRGBA(\n colors: LocationAreaColors | undefined,\n darkMode: boolean,\n): LocationAreaColorsRGBA {\n const normalColor = (colors && colors.normal) || DEFAULT_LOCATION_AREA_COLOR;\n const normalColorHcl = hcl(normalColor);\n const locationAreasNormal = colorAsRgba(normalColor);\n return {\n normal: locationAreasNormal,\n connected: colorAsRgbaOr(colors && colors.connected, locationAreasNormal),\n highlighted: colorAsRgbaOr(\n colors && colors.highlighted,\n opacifyHex(\n normalColorHcl[darkMode ? 'brighter' : 'darker'](1).toString(),\n 0.5,\n ),\n ),\n selected: colorAsRgbaOr(\n colors && colors.selected,\n opacifyHex(\n normalColorHcl[darkMode ? 'brighter' : 'darker'](2).toString(),\n 0.8,\n ),\n ),\n outline: colorAsRgbaOr(\n colors && colors.outline,\n colorAsRgba(\n normalColorHcl[darkMode ? 'brighter' : 'darker'](4).toString(),\n ),\n ),\n };\n}\n\nexport interface FlowColors {\n scheme?: string[];\n highlighted?: string;\n}\n\nexport interface LocationCircleColors {\n inner?: string;\n outgoing?: string;\n incoming?: string;\n highlighted?: string;\n empty?: string;\n outlineEmptyMix?: number;\n}\n\nexport interface LocationAreaColors {\n outline?: string;\n normal?: string;\n selected?: string;\n highlighted?: string;\n connected?: string;\n}\n\nexport interface BaseColors {\n darkMode?: boolean;\n locationAreas?: LocationAreaColors;\n dimmedOpacity?: number;\n outlineColor?: string;\n}\n\nexport interface Colors extends BaseColors {\n flows?: FlowColors;\n locationCircles?: LocationCircleColors;\n}\n\nexport interface FlowAndCircleColors {\n flows?: FlowColors;\n locationCircles?: LocationCircleColors;\n}\n\nexport interface DiffColors extends BaseColors {\n positive?: FlowAndCircleColors;\n negative?: FlowAndCircleColors;\n}\n\n// The xxxColorsRGBA objects are mirroring the input colors' objects,\n// but converted to RGBA and with all the omitted ones set to defaults\n// or derived.\nexport interface FlowColorsRGBA {\n scheme: string[];\n highlighted: RGBA;\n}\n\nexport interface LocationCircleColorsRGBA {\n inner: RGBA;\n outgoing: RGBA;\n incoming: RGBA;\n highlighted: RGBA;\n empty: RGBA;\n outlineEmptyMix: number;\n}\n\nexport interface LocationAreaColorsRGBA {\n outline: RGBA;\n normal: RGBA;\n selected: RGBA;\n highlighted: RGBA;\n connected: RGBA;\n}\n\nexport interface BaseColorsRGBA {\n darkMode: boolean;\n locationAreas: LocationAreaColorsRGBA;\n dimmedOpacity: number;\n outlineColor: RGBA;\n}\n\nexport interface ColorsRGBA extends BaseColorsRGBA {\n flows: FlowColorsRGBA;\n locationCircles: LocationCircleColorsRGBA;\n}\n\nexport interface FlowAndCircleColorsRGBA {\n flows: FlowColorsRGBA;\n locationCircles: LocationCircleColorsRGBA;\n}\n\nexport interface DiffColorsRGBA extends BaseColorsRGBA {\n positive: FlowAndCircleColorsRGBA;\n negative: FlowAndCircleColorsRGBA;\n}\n\nfunction getFlowAndCircleColors(\n inputColors: FlowAndCircleColors | undefined,\n defaultFlowColorScheme: string[],\n darkMode: boolean,\n): FlowAndCircleColorsRGBA {\n const flowColorScheme =\n (inputColors && inputColors.flows && inputColors.flows.scheme) ||\n defaultFlowColorScheme;\n const maxFlowColorHcl = hcl(flowColorScheme[flowColorScheme.length - 1]);\n const flowColorHighlighted = colorAsRgbaOr(\n inputColors && inputColors.flows && inputColors.flows.highlighted,\n colorAsRgba(\n maxFlowColorHcl[darkMode ? 'brighter' : 'darker'](0.7).toString(),\n ),\n );\n\n const emptyColor = colorAsRgbaOr(\n inputColors?.locationCircles?.empty,\n darkMode ? '#000' : '#fff',\n );\n const innerColor = colorAsRgbaOr(\n inputColors &&\n inputColors.locationCircles &&\n inputColors.locationCircles.inner,\n maxFlowColorHcl.toString(),\n );\n return {\n flows: {\n scheme: flowColorScheme,\n highlighted: flowColorHighlighted,\n },\n locationCircles: {\n inner: innerColor,\n outgoing: colorAsRgbaOr(\n inputColors &&\n inputColors.locationCircles &&\n inputColors.locationCircles.outgoing,\n darkMode ? '#000' : '#fff',\n ),\n incoming: colorAsRgbaOr(\n inputColors &&\n inputColors.locationCircles &&\n inputColors.locationCircles.incoming,\n maxFlowColorHcl[darkMode ? 'brighter' : 'darker'](1.25).toString(),\n ),\n highlighted: colorAsRgbaOr(\n inputColors &&\n inputColors.locationCircles &&\n inputColors.locationCircles.highlighted,\n flowColorHighlighted,\n ),\n empty: emptyColor,\n outlineEmptyMix: inputColors?.locationCircles?.outlineEmptyMix ?? 0.4,\n },\n };\n}\n\nfunction getBaseColorsRGBA(\n colors: Colors | DiffColors | undefined,\n): BaseColorsRGBA {\n const darkMode = colors && colors.darkMode ? true : false;\n return {\n darkMode,\n locationAreas: getLocationAreaColorsRGBA(\n colors && colors.locationAreas,\n darkMode,\n ),\n outlineColor: colorAsRgba(\n (colors && colors.outlineColor) || DEFAULT_OUTLINE_COLOR,\n ),\n dimmedOpacity:\n colors && colors.dimmedOpacity != null\n ? colors.dimmedOpacity\n : DEFAULT_DIMMED_OPACITY,\n };\n}\n\nexport function getColorsRGBA(colors: Colors | undefined): ColorsRGBA {\n const baseColorsRGBA = getBaseColorsRGBA(colors);\n return {\n ...baseColorsRGBA,\n ...getFlowAndCircleColors(\n colors,\n DEFAULT_FLOW_COLOR_SCHEME,\n baseColorsRGBA.darkMode,\n ),\n };\n}\n\nexport function getDiffColorsRGBA(\n colors: DiffColors | undefined,\n): DiffColorsRGBA {\n const baseColorsRGBA = getBaseColorsRGBA(colors);\n return {\n ...baseColorsRGBA,\n positive: getFlowAndCircleColors(\n colors && colors.positive,\n DEFAULT_FLOW_COLOR_SCHEME_POSITIVE,\n baseColorsRGBA.darkMode,\n ),\n negative: getFlowAndCircleColors(\n colors && colors.negative,\n DEFAULT_FLOW_COLOR_SCHEME_NEGATIVE,\n baseColorsRGBA.darkMode,\n ),\n };\n}\n\nexport function rgbaAsString(color: RGBA): string {\n return `rgba(${color.join(',')})`;\n}\n\nexport function midpoint(a: number, b: number, zeroToOne: number): number {\n return a + (b - a) * zeroToOne;\n}\n\nexport function mixColorsRGBA(\n color1: RGBA,\n color2: RGBA,\n zeroToOne: number,\n): RGBA {\n return color1.map((v, i) => midpoint(v, color2[i], zeroToOne)) as RGBA;\n}\n\nexport default getColors;\n","\nconst ARRAY_TYPES = [\n Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array,\n Int32Array, Uint32Array, Float32Array, Float64Array\n];\n\n/** @typedef {Int8ArrayConstructor | Uint8ArrayConstructor | Uint8ClampedArrayConstructor | Int16ArrayConstructor | Uint16ArrayConstructor | Int32ArrayConstructor | Uint32ArrayConstructor | Float32ArrayConstructor | Float64ArrayConstructor} TypedArrayConstructor */\n/** @typedef {Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array} TypedArray */\n\nconst VERSION = 1; // serialized format version\nconst HEADER_SIZE = 8;\n\n// Shared scratch stack for iterative DFS in range/within. Sized for the worst case:\n// 3 ints per frame * (treeHeight + 1), with treeHeight ≤ ceil(log2(2^32 / 3)) ≈ 31.\nconst STACK = new Uint32Array(96);\n\nexport default class KDBush {\n\n /**\n * Creates an index from raw `ArrayBuffer` data.\n * @param {ArrayBufferLike} data\n */\n static from(data) {\n // @ts-expect-error duck typing array buffers\n if (!data || data.byteLength === undefined || data.buffer) {\n throw new Error('Data must be an instance of ArrayBuffer or SharedArrayBuffer.');\n }\n const [magic, versionAndType] = new Uint8Array(data, 0, 2);\n if (magic !== 0xdb) {\n throw new Error('Data does not appear to be in a KDBush format.');\n }\n const version = versionAndType >> 4;\n if (version !== VERSION) {\n throw new Error(`Got v${version} data when expected v${VERSION}.`);\n }\n const ArrayType = ARRAY_TYPES[versionAndType & 0x0f];\n if (!ArrayType) {\n throw new Error('Unrecognized array type.');\n }\n const [nodeSize] = new Uint16Array(data, 2, 1);\n const [numItems] = new Uint32Array(data, 4, 1);\n\n return new KDBush(numItems, nodeSize, ArrayType, undefined, data);\n }\n\n /**\n * Creates an index that will hold a given number of items.\n * @param {number} numItems\n * @param {number} [nodeSize=64] Size of the KD-tree node (64 by default).\n * @param {TypedArrayConstructor} [ArrayType=Float64Array] The array type used for coordinates storage (`Float64Array` by default).\n * @param {ArrayBufferConstructor | SharedArrayBufferConstructor} [ArrayBufferType=ArrayBuffer] The array buffer type used for storage (`ArrayBuffer` by default).\n * @param {ArrayBufferLike} [data] (For internal use only)\n */\n constructor(numItems, nodeSize = 64, ArrayType = Float64Array, ArrayBufferType = ArrayBuffer, data) {\n if (isNaN(numItems) || numItems < 0) throw new Error(`Unexpected numItems value: ${numItems}.`);\n\n this.numItems = +numItems;\n this.nodeSize = Math.min(Math.max(+nodeSize, 2), 65535);\n this.ArrayType = ArrayType;\n this.IndexArrayType = numItems < 65536 ? Uint16Array : Uint32Array;\n\n const arrayTypeIndex = ARRAY_TYPES.indexOf(this.ArrayType);\n const coordsByteSize = numItems * 2 * this.ArrayType.BYTES_PER_ELEMENT;\n const idsByteSize = numItems * this.IndexArrayType.BYTES_PER_ELEMENT;\n const padCoords = (8 - idsByteSize % 8) % 8;\n\n if (arrayTypeIndex < 0) {\n throw new Error(`Unexpected typed array class: ${ArrayType}.`);\n }\n\n if (data) { // reconstruct an index from a buffer\n this.data = data;\n // @ts-expect-error TS can't handle SharedArrayBuffer overloads\n this.ids = new this.IndexArrayType(data, HEADER_SIZE, numItems);\n // @ts-expect-error TS can't handle SharedArrayBuffer overloads\n this.coords = new ArrayType(data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2);\n this._pos = numItems * 2;\n this._finished = true;\n\n } else { // initialize a new index\n const data = this.data = new ArrayBufferType(HEADER_SIZE + coordsByteSize + idsByteSize + padCoords);\n // @ts-expect-error TS can't handle SharedArrayBuffer overloads\n this.ids = new this.IndexArrayType(data, HEADER_SIZE, numItems);\n // @ts-expect-error TS can't handle SharedArrayBuffer overloads\n this.coords = new ArrayType(data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2);\n this._pos = 0;\n this._finished = false;\n\n // set header\n new Uint8Array(data, 0, 2).set([0xdb, (VERSION << 4) + arrayTypeIndex]);\n new Uint16Array(data, 2, 1)[0] = nodeSize;\n new Uint32Array(data, 4, 1)[0] = numItems;\n }\n }\n\n /**\n * Add a point to the index.\n * @param {number} x\n * @param {number} y\n * @returns {number} An incremental index associated with the added item (starting from `0`).\n */\n add(x, y) {\n const index = this._pos >> 1;\n this.ids[index] = index;\n this.coords[this._pos++] = x;\n this.coords[this._pos++] = y;\n return index;\n }\n\n /**\n * Perform indexing of the added points.\n */\n finish() {\n const numAdded = this._pos >> 1;\n if (numAdded !== this.numItems) {\n throw new Error(`Added ${numAdded} items when expected ${this.numItems}.`);\n }\n // kd-sort both arrays for efficient search\n sort(this.ids, this.coords, this.nodeSize, 0, this.numItems - 1, 0);\n\n this._finished = true;\n return this;\n }\n\n /**\n * Search the index for items within a given bounding box.\n * @param {number} minX\n * @param {number} minY\n * @param {number} maxX\n * @param {number} maxY\n * @returns {number[]} An array of indices correponding to the found items.\n */\n range(minX, minY, maxX, maxY) {\n if (!this._finished) throw new Error('Data not yet indexed - call index.finish().');\n\n const {ids, coords, nodeSize} = this;\n STACK[0] = 0;\n STACK[1] = ids.length - 1;\n STACK[2] = 0;\n let sp = 3;\n const result = [];\n\n // recursively search for items in range in the kd-sorted arrays\n while (sp > 0) {\n const axis = STACK[--sp];\n const right = STACK[--sp];\n const left = STACK[--sp];\n\n // if we reached \"tree node\", search linearly\n if (right - left <= nodeSize) {\n for (let i = left; i <= right; i++) {\n const x = coords[2 * i];\n const y = coords[2 * i + 1];\n if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[i]);\n }\n continue;\n }\n\n // otherwise find the middle index\n const m = (left + right) >> 1;\n\n // include the middle item if it's in range\n const x = coords[2 * m];\n const y = coords[2 * m + 1];\n if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[m]);\n\n // queue search in halves that intersect the query\n if (axis === 0 ? minX <= x : minY <= y) {\n STACK[sp++] = left;\n STACK[sp++] = m - 1;\n STACK[sp++] = 1 - axis;\n }\n if (axis === 0 ? maxX >= x : maxY >= y) {\n STACK[sp++] = m + 1;\n STACK[sp++] = right;\n STACK[sp++] = 1 - axis;\n }\n }\n\n return result;\n }\n\n /**\n * Search the index for items within a given radius.\n * @param {number} qx\n * @param {number} qy\n * @param {number} r Query radius.\n * @returns {number[]} An array of indices correponding to the found items.\n */\n within(qx, qy, r) {\n const result = /** @type {number[]} */ ([]);\n this.withinInto(qx, qy, r, result);\n return result;\n }\n\n /**\n * Search the index for items within a given radius, writing matching ids into `out`\n * via indexed assignment (`out[i] = id`). Accepts any indexed-writable container —\n * a typed array sized to the expected upper bound (allocation-free, fast) or a plain\n * `Array` (which will grow as needed). Returns the number of matches written.\n * @param {number} qx\n * @param {number} qy\n * @param {number} r Query radius.\n * @param {number[] | TypedArray} out Container to write matching ids into.\n * @returns {number} The number of matches written to `out`.\n */\n withinInto(qx, qy, r, out) {\n if (!this._finished) throw new Error('Data not yet indexed - call index.finish().');\n\n const {ids, coords, nodeSize} = this;\n STACK[0] = 0;\n STACK[1] = ids.length - 1;\n STACK[2] = 0;\n let sp = 3;\n let count = 0;\n const r2 = r * r;\n\n // recursively search for items within radius in the kd-sorted arrays\n while (sp > 0) {\n const axis = STACK[--sp];\n const right = STACK[--sp];\n const left = STACK[--sp];\n\n // if we reached \"tree node\", search linearly\n if (right - left <= nodeSize) {\n for (let i = left; i <= right; i++) {\n if (sqDist(coords[2 * i], coords[2 * i + 1], qx, qy) <= r2) out[count++] = ids[i];\n }\n continue;\n }\n\n // otherwise find the middle index\n const m = (left + right) >> 1;\n\n // include the middle item if it's in range\n const x = coords[2 * m];\n const y = coords[2 * m + 1];\n if (sqDist(x, y, qx, qy) <= r2) out[count++] = ids[m];\n\n // queue search in halves that intersect the query\n if (axis === 0 ? qx - r <= x : qy - r <= y) {\n STACK[sp++] = left;\n STACK[sp++] = m - 1;\n STACK[sp++] = 1 - axis;\n }\n if (axis === 0 ? qx + r >= x : qy + r >= y) {\n STACK[sp++] = m + 1;\n STACK[sp++] = right;\n STACK[sp++] = 1 - axis;\n }\n }\n\n return count;\n }\n}\n\n/**\n * @param {Uint16Array | Uint32Array} ids\n * @param {TypedArray} coords\n * @param {number} nodeSize\n * @param {number} left\n * @param {number} right\n * @param {number} axis\n */\nfunction sort(ids, coords, nodeSize, left, right, axis) {\n if (right - left <= nodeSize) return;\n\n const m = (left + right) >> 1; // middle index\n\n // sort ids and coords around the middle index so that the halves lie\n // either left/right or top/bottom correspondingly (taking turns)\n select(ids, coords, m, left, right, axis);\n\n // recursively kd-sort first half and second half on the opposite axis\n sort(ids, coords, nodeSize, left, m - 1, 1 - axis);\n sort(ids, coords, nodeSize, m + 1, right, 1 - axis);\n}\n\n/**\n * Custom Floyd-Rivest selection algorithm: sort ids and coords so that\n * [left..k-1] items are smaller than k-th item (on either x or y axis)\n * @param {Uint16Array | Uint32Array} ids\n * @param {TypedArray} coords\n * @param {number} k\n * @param {number} left\n * @param {number} right\n * @param {number} axis\n */\nfunction select(ids, coords, k, left, right, axis) {\n\n while (right > left) {\n if (right - left > 600) {\n const n = right - left + 1;\n const m = k - left + 1;\n const z = Math.log(n);\n const s = 0.5 * Math.exp(2 * z / 3);\n const sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);\n const newLeft = Math.max(left, Math.floor(k - m * s / n + sd));\n const newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));\n select(ids, coords, k, newLeft, newRight, axis);\n }\n\n const t = coords[2 * k + axis];\n let i = left;\n let j = right;\n\n swapItem(ids, coords, left, k);\n if (coords[2 * right + axis] > t) swapItem(ids, coords, left, right);\n\n while (i < j) {\n swapItem(ids, coords, i, j);\n i++;\n j--;\n while (coords[2 * i + axis] < t) i++;\n while (coords[2 * j + axis] > t) j--;\n }\n\n if (coords[2 * left + axis] === t) swapItem(ids, coords, left, j);\n else {\n j++;\n swapItem(ids, coords, j, right);\n }\n\n if (j <= k) left = j + 1;\n if (k <= j) right = j - 1;\n }\n}\n\n/**\n * @param {Uint16Array | Uint32Array} ids\n * @param {TypedArray} coords\n * @param {number} i\n * @param {number} j\n */\nfunction swapItem(ids, coords, i, j) {\n swap(ids, i, j);\n swap(coords, 2 * i, 2 * j);\n swap(coords, 2 * i + 1, 2 * j + 1);\n}\n\n/**\n * @param {TypedArray} arr\n * @param {number} i\n * @param {number} j\n */\nfunction swap(arr, i, j) {\n const tmp = arr[i];\n arr[i] = arr[j];\n arr[j] = tmp;\n}\n\n/**\n * @param {number} ax\n * @param {number} ay\n * @param {number} bx\n * @param {number} by\n */\nfunction sqDist(ax, ay, bx, by) {\n const dx = ax - bx;\n const dy = ay - by;\n return dx * dx + dy * dy;\n}\n","import type { AnyFunction } from '../types'\n\n/**\n * Runs a check to determine if the given result function behaves as an\n * identity function. An identity function is one that returns its\n * input unchanged, for example, `x => x`. This check helps ensure\n * efficient memoization and prevent unnecessary re-renders by encouraging\n * proper use of transformation logic in result functions and\n * extraction logic in input selectors.\n *\n * @param resultFunc - The result function to be checked.\n * @param inputSelectorsResults - The results of the input selectors.\n * @param outputSelectorResult - The result of the output selector.\n *\n * @see {@link https://reselect.js.org/api/development-only-stability-checks#identityfunctioncheck `identityFunctionCheck`}\n *\n * @since 5.0.0\n * @internal\n */\nexport const runIdentityFunctionCheck = (\n resultFunc: AnyFunction,\n inputSelectorsResults: unknown[],\n outputSelectorResult: unknown\n) => {\n if (\n inputSelectorsResults.length === 1 &&\n inputSelectorsResults[0] === outputSelectorResult\n ) {\n let isInputSameAsOutput = false\n try {\n const emptyObject = {}\n if (resultFunc(emptyObject) === emptyObject) isInputSameAsOutput = true\n } catch {\n // Do nothing\n }\n if (isInputSameAsOutput) {\n let stack: string | undefined = undefined\n try {\n throw new Error()\n } catch (e) {\n // eslint-disable-next-line @typescript-eslint/no-extra-semi, no-extra-semi\n ;({ stack } = e as Error)\n }\n console.warn(\n 'The result function returned its own inputs without modification. e.g' +\n '\\n`createSelector([state => state.todos], todos => todos)`' +\n '\\nThis could lead to inefficient memoization and unnecessary re-renders.' +\n '\\nEnsure transformation logic is in the result function, and extraction logic is in the input selectors.',\n { stack }\n )\n }\n }\n}\n","import type { CreateSelectorOptions, UnknownMemoizer } from '../types'\n\n/**\n * Runs a stability check to ensure the input selector results remain stable\n * when provided with the same arguments. This function is designed to detect\n * changes in the output of input selectors, which can impact the performance of memoized selectors.\n *\n * @param inputSelectorResultsObject - An object containing two arrays: `inputSelectorResults` and `inputSelectorResultsCopy`, representing the results of input selectors.\n * @param options - Options object consisting of a `memoize` function and a `memoizeOptions` object.\n * @param inputSelectorArgs - List of arguments being passed to the input selectors.\n *\n * @see {@link https://reselect.js.org/api/development-only-stability-checks/#inputstabilitycheck `inputStabilityCheck`}\n *\n * @since 5.0.0\n * @internal\n */\nexport const runInputStabilityCheck = (\n inputSelectorResultsObject: {\n inputSelectorResults: unknown[]\n inputSelectorResultsCopy: unknown[]\n },\n options: Required<\n Pick<\n CreateSelectorOptions,\n 'memoize' | 'memoizeOptions'\n >\n >,\n inputSelectorArgs: unknown[] | IArguments\n) => {\n const { memoize, memoizeOptions } = options\n const { inputSelectorResults, inputSelectorResultsCopy } =\n inputSelectorResultsObject\n const createAnEmptyObject = memoize(() => ({}), ...memoizeOptions)\n // if the memoize method thinks the parameters are equal, these *should* be the same reference\n const areInputSelectorResultsEqual =\n createAnEmptyObject.apply(null, inputSelectorResults) ===\n createAnEmptyObject.apply(null, inputSelectorResultsCopy)\n if (!areInputSelectorResultsEqual) {\n let stack: string | undefined = undefined\n try {\n throw new Error()\n } catch (e) {\n // eslint-disable-next-line @typescript-eslint/no-extra-semi, no-extra-semi\n ;({ stack } = e as Error)\n }\n console.warn(\n 'An input selector returned a different result when passed same arguments.' +\n '\\nThis means your output selector will likely run more frequently than intended.' +\n '\\nAvoid returning a new reference inside your input selector, e.g.' +\n '\\n`createSelector([state => state.todos.map(todo => todo.id)], todoIds => todoIds.length)`',\n {\n arguments: inputSelectorArgs,\n firstInputs: inputSelectorResults,\n secondInputs: inputSelectorResultsCopy,\n stack\n }\n )\n }\n}\n","import type { DevModeChecks } from '../types'\n\n/**\n * Global configuration for development mode checks. This specifies the default\n * frequency at which each development mode check should be performed.\n *\n * @since 5.0.0\n * @internal\n */\nexport const globalDevModeChecks: DevModeChecks = {\n inputStabilityCheck: 'once',\n identityFunctionCheck: 'once'\n}\n\n/**\n * Overrides the development mode checks settings for all selectors.\n *\n * Reselect performs additional checks in development mode to help identify and\n * warn about potential issues in selector behavior. This function allows you to\n * customize the behavior of these checks across all selectors in your application.\n *\n * **Note**: This setting can still be overridden per selector inside `createSelector`'s `options` object.\n * See {@link https://github.com/reduxjs/reselect#2-per-selector-by-passing-an-identityfunctioncheck-option-directly-to-createselector per-selector-configuration}\n * and {@linkcode CreateSelectorOptions.identityFunctionCheck identityFunctionCheck} for more details.\n *\n * _The development mode checks do not run in production builds._\n *\n * @param devModeChecks - An object specifying the desired settings for development mode checks. You can provide partial overrides. Unspecified settings will retain their current values.\n *\n * @example\n * ```ts\n * import { setGlobalDevModeChecks } from 'reselect'\n * import { DevModeChecks } from '../types'\n *\n * // Run only the first time the selector is called. (default)\n * setGlobalDevModeChecks({ inputStabilityCheck: 'once' })\n *\n * // Run every time the selector is called.\n * setGlobalDevModeChecks({ inputStabilityCheck: 'always' })\n *\n * // Never run the input stability check.\n * setGlobalDevModeChecks({ inputStabilityCheck: 'never' })\n *\n * // Run only the first time the selector is called. (default)\n * setGlobalDevModeChecks({ identityFunctionCheck: 'once' })\n *\n * // Run every time the selector is called.\n * setGlobalDevModeChecks({ identityFunctionCheck: 'always' })\n *\n * // Never run the identity function check.\n * setGlobalDevModeChecks({ identityFunctionCheck: 'never' })\n * ```\n * @see {@link https://reselect.js.org/api/development-only-stability-checks Development-Only Stability Checks}\n * @see {@link https://reselect.js.org/api/development-only-stability-checks#1-globally-through-setglobaldevmodechecks global-configuration}\n *\n * @since 5.0.0\n * @public\n */\nexport const setGlobalDevModeChecks = (\n devModeChecks: Partial\n) => {\n Object.assign(globalDevModeChecks, devModeChecks)\n}\n","import { runIdentityFunctionCheck } from './devModeChecks/identityFunctionCheck'\nimport { runInputStabilityCheck } from './devModeChecks/inputStabilityCheck'\nimport { globalDevModeChecks } from './devModeChecks/setGlobalDevModeChecks'\n// eslint-disable-next-line @typescript-eslint/consistent-type-imports\nimport type {\n DevModeChecks,\n Selector,\n SelectorArray,\n DevModeChecksExecutionInfo\n} from './types'\n\nexport const NOT_FOUND = /* @__PURE__ */ Symbol('NOT_FOUND')\nexport type NOT_FOUND_TYPE = typeof NOT_FOUND\n\n/**\n * Assert that the provided value is a function. If the assertion fails,\n * a `TypeError` is thrown with an optional custom error message.\n *\n * @param func - The value to be checked.\n * @param errorMessage - An optional custom error message to use if the assertion fails.\n * @throws A `TypeError` if the assertion fails.\n */\nexport function assertIsFunction(\n func: unknown,\n errorMessage = `expected a function, instead received ${typeof func}`\n): asserts func is FunctionType {\n if (typeof func !== 'function') {\n throw new TypeError(errorMessage)\n }\n}\n\n/**\n * Assert that the provided value is an object. If the assertion fails,\n * a `TypeError` is thrown with an optional custom error message.\n *\n * @param object - The value to be checked.\n * @param errorMessage - An optional custom error message to use if the assertion fails.\n * @throws A `TypeError` if the assertion fails.\n */\nexport function assertIsObject>(\n object: unknown,\n errorMessage = `expected an object, instead received ${typeof object}`\n): asserts object is ObjectType {\n if (typeof object !== 'object') {\n throw new TypeError(errorMessage)\n }\n}\n\n/**\n * Assert that the provided array is an array of functions. If the assertion fails,\n * a `TypeError` is thrown with an optional custom error message.\n *\n * @param array - The array to be checked.\n * @param errorMessage - An optional custom error message to use if the assertion fails.\n * @throws A `TypeError` if the assertion fails.\n */\nexport function assertIsArrayOfFunctions(\n array: unknown[],\n errorMessage = `expected all items to be functions, instead received the following types: `\n): asserts array is FunctionType[] {\n if (\n !array.every((item): item is FunctionType => typeof item === 'function')\n ) {\n const itemTypes = array\n .map(item =>\n typeof item === 'function'\n ? `function ${item.name || 'unnamed'}()`\n : typeof item\n )\n .join(', ')\n throw new TypeError(`${errorMessage}[${itemTypes}]`)\n }\n}\n\n/**\n * Ensure that the input is an array. If it's already an array, it's returned as is.\n * If it's not an array, it will be wrapped in a new array.\n *\n * @param item - The item to be checked.\n * @returns An array containing the input item. If the input is already an array, it's returned without modification.\n */\nexport const ensureIsArray = (item: unknown) => {\n return Array.isArray(item) ? item : [item]\n}\n\n/**\n * Extracts the \"dependencies\" / \"input selectors\" from the arguments of `createSelector`.\n *\n * @param createSelectorArgs - Arguments passed to `createSelector` as an array.\n * @returns An array of \"input selectors\" / \"dependencies\".\n * @throws A `TypeError` if any of the input selectors is not function.\n */\nexport function getDependencies(createSelectorArgs: unknown[]) {\n const dependencies = Array.isArray(createSelectorArgs[0])\n ? createSelectorArgs[0]\n : createSelectorArgs\n\n assertIsArrayOfFunctions(\n dependencies,\n `createSelector expects all input-selectors to be functions, but received the following types: `\n )\n\n return dependencies as SelectorArray\n}\n\n/**\n * Runs each input selector and returns their collective results as an array.\n *\n * @param dependencies - An array of \"dependencies\" or \"input selectors\".\n * @param inputSelectorArgs - An array of arguments being passed to the input selectors.\n * @returns An array of input selector results.\n */\nexport function collectInputSelectorResults(\n dependencies: SelectorArray,\n inputSelectorArgs: unknown[] | IArguments\n) {\n const inputSelectorResults = []\n const { length } = dependencies\n for (let i = 0; i < length; i++) {\n // @ts-ignore\n // apply arguments instead of spreading and mutate a local list of params for performance.\n inputSelectorResults.push(dependencies[i].apply(null, inputSelectorArgs))\n }\n return inputSelectorResults\n}\n\n/**\n * Retrieves execution information for development mode checks.\n *\n * @param devModeChecks - Custom Settings for development mode checks. These settings will override the global defaults.\n * @param firstRun - Indicates whether it is the first time the selector has run.\n * @returns An object containing the execution information for each development mode check.\n */\nexport const getDevModeChecksExecutionInfo = (\n firstRun: boolean,\n devModeChecks: Partial\n) => {\n const { identityFunctionCheck, inputStabilityCheck } = {\n ...globalDevModeChecks,\n ...devModeChecks\n }\n return {\n identityFunctionCheck: {\n shouldRun:\n identityFunctionCheck === 'always' ||\n (identityFunctionCheck === 'once' && firstRun),\n run: runIdentityFunctionCheck\n },\n inputStabilityCheck: {\n shouldRun:\n inputStabilityCheck === 'always' ||\n (inputStabilityCheck === 'once' && firstRun),\n run: runInputStabilityCheck\n }\n } satisfies DevModeChecksExecutionInfo\n}\n","// Original autotracking implementation source:\n// - https://gist.github.com/pzuraq/79bf862e0f8cd9521b79c4b6eccdc4f9\n// Additional references:\n// - https://www.pzuraq.com/blog/how-autotracking-works\n// - https://v5.chriskrycho.com/journal/autotracking-elegant-dx-via-cutting-edge-cs/\nimport type { EqualityFn } from '../types'\nimport { assertIsFunction } from '../utils'\n\n// The global revision clock. Every time state changes, the clock increments.\nexport let $REVISION = 0\n\n// The current dependency tracker. Whenever we compute a cache, we create a Set\n// to track any dependencies that are used while computing. If no cache is\n// computing, then the tracker is null.\nlet CURRENT_TRACKER: Set | TrackingCache> | null = null\n\n// Storage represents a root value in the system - the actual state of our app.\nexport class Cell {\n revision = $REVISION\n\n _value: T\n _lastValue: T\n _isEqual: EqualityFn = tripleEq\n\n constructor(initialValue: T, isEqual: EqualityFn = tripleEq) {\n this._value = this._lastValue = initialValue\n this._isEqual = isEqual\n }\n\n // Whenever a storage value is read, it'll add itself to the current tracker if\n // one exists, entangling its state with that cache.\n get value() {\n CURRENT_TRACKER?.add(this)\n\n return this._value\n }\n\n // Whenever a storage value is updated, we bump the global revision clock,\n // assign the revision for this storage to the new value, _and_ we schedule a\n // rerender. This is important, and it's what makes autotracking _pull_\n // based. We don't actively tell the caches which depend on the storage that\n // anything has happened. Instead, we recompute the caches when needed.\n set value(newValue) {\n if (this.value === newValue) return\n\n this._value = newValue\n this.revision = ++$REVISION\n }\n}\n\nfunction tripleEq(a: unknown, b: unknown) {\n return a === b\n}\n\n// Caches represent derived state in the system. They are ultimately functions\n// that are memoized based on what state they use to produce their output,\n// meaning they will only rerun IFF a storage value that could affect the output\n// has changed. Otherwise, they'll return the cached value.\nexport class TrackingCache {\n _cachedValue: any\n _cachedRevision = -1\n _deps: any[] = []\n hits = 0\n\n fn: () => any\n\n constructor(fn: () => any) {\n this.fn = fn\n }\n\n clear() {\n this._cachedValue = undefined\n this._cachedRevision = -1\n this._deps = []\n this.hits = 0\n }\n\n get value() {\n // When getting the value for a Cache, first we check all the dependencies of\n // the cache to see what their current revision is. If the current revision is\n // greater than the cached revision, then something has changed.\n if (this.revision > this._cachedRevision) {\n const { fn } = this\n\n // We create a new dependency tracker for this cache. As the cache runs\n // its function, any Storage or Cache instances which are used while\n // computing will be added to this tracker. In the end, it will be the\n // full list of dependencies that this Cache depends on.\n const currentTracker = new Set>()\n const prevTracker = CURRENT_TRACKER\n\n CURRENT_TRACKER = currentTracker\n\n // try {\n this._cachedValue = fn()\n // } finally {\n CURRENT_TRACKER = prevTracker\n this.hits++\n this._deps = Array.from(currentTracker)\n\n // Set the cached revision. This is the current clock count of all the\n // dependencies. If any dependency changes, this number will be less\n // than the new revision.\n this._cachedRevision = this.revision\n // }\n }\n\n // If there is a current tracker, it means another Cache is computing and\n // using this one, so we add this one to the tracker.\n CURRENT_TRACKER?.add(this)\n\n // Always return the cached value.\n return this._cachedValue\n }\n\n get revision() {\n // The current revision is the max of all the dependencies' revisions.\n return Math.max(...this._deps.map(d => d.revision), 0)\n }\n}\n\nexport function getValue(cell: Cell): T {\n if (!(cell instanceof Cell)) {\n console.warn('Not a valid cell! ', cell)\n }\n\n return cell.value\n}\n\ntype CellValue> = T extends Cell ? U : never\n\nexport function setValue>(\n storage: T,\n value: CellValue\n): void {\n if (!(storage instanceof Cell)) {\n throw new TypeError(\n 'setValue must be passed a tracked store created with `createStorage`.'\n )\n }\n\n storage.value = storage._lastValue = value\n}\n\nexport function createCell(\n initialValue: T,\n isEqual: EqualityFn = tripleEq\n): Cell {\n return new Cell(initialValue, isEqual)\n}\n\nexport function createCache(fn: () => T): TrackingCache {\n assertIsFunction(\n fn,\n 'the first parameter to `createCache` must be a function'\n )\n\n return new TrackingCache(fn)\n}\n","import type { Cell } from './autotracking'\nimport {\n getValue as consumeTag,\n createCell as createStorage,\n setValue\n} from './autotracking'\n\nexport type Tag = Cell\n\nconst neverEq = (a: any, b: any): boolean => false\n\nexport function createTag(): Tag {\n return createStorage(null, neverEq)\n}\nexport { consumeTag }\nexport function dirtyTag(tag: Tag, value: any): void {\n setValue(tag, value)\n}\n\nexport interface Node<\n T extends Array | Record =\n | Array\n | Record\n> {\n collectionTag: Tag | null\n tag: Tag | null\n tags: Record\n children: Record\n proxy: T\n value: T\n id: number\n}\n\nexport const consumeCollection = (node: Node): void => {\n let tag = node.collectionTag\n\n if (tag === null) {\n tag = node.collectionTag = createTag()\n }\n\n consumeTag(tag)\n}\n\nexport const dirtyCollection = (node: Node): void => {\n const tag = node.collectionTag\n\n if (tag !== null) {\n dirtyTag(tag, null)\n }\n}\n","// Original source:\n// - https://github.com/simonihmig/tracked-redux/blob/master/packages/tracked-redux/src/-private/proxy.ts\n\nimport type { Node, Tag } from './tracking'\nimport {\n consumeCollection,\n consumeTag,\n createTag,\n dirtyCollection,\n dirtyTag\n} from './tracking'\n\nexport const REDUX_PROXY_LABEL = /* @__PURE__ */ Symbol()\n\nlet nextId = 0\n\nconst proto = /* @__PURE__ */ Object.getPrototypeOf({})\n\nclass ObjectTreeNode> implements Node {\n proxy: T = new Proxy(this, objectProxyHandler) as unknown as T\n tag = createTag()\n tags = {} as Record\n children = {} as Record\n collectionTag = null\n id = nextId++\n\n constructor(public value: T) {\n this.value = value\n this.tag.value = value\n }\n}\n\nconst objectProxyHandler = {\n get(node: Node, key: string | symbol): unknown {\n function calculateResult() {\n const { value } = node\n\n const childValue = Reflect.get(value, key)\n\n if (typeof key === 'symbol') {\n return childValue\n }\n\n if (key in proto) {\n return childValue\n }\n\n if (typeof childValue === 'object' && childValue !== null) {\n let childNode = node.children[key]\n\n if (childNode === undefined) {\n childNode = node.children[key] = createNode(childValue)\n }\n\n if (childNode.tag) {\n consumeTag(childNode.tag)\n }\n\n return childNode.proxy\n } else {\n let tag = node.tags[key]\n\n if (tag === undefined) {\n tag = node.tags[key] = createTag()\n tag.value = childValue\n }\n\n consumeTag(tag)\n\n return childValue\n }\n }\n const res = calculateResult()\n return res\n },\n\n ownKeys(node: Node): ArrayLike {\n consumeCollection(node)\n return Reflect.ownKeys(node.value)\n },\n\n getOwnPropertyDescriptor(\n node: Node,\n prop: string | symbol\n ): PropertyDescriptor | undefined {\n return Reflect.getOwnPropertyDescriptor(node.value, prop)\n },\n\n has(node: Node, prop: string | symbol): boolean {\n return Reflect.has(node.value, prop)\n }\n}\n\nclass ArrayTreeNode> implements Node {\n proxy: T = new Proxy([this], arrayProxyHandler) as unknown as T\n tag = createTag()\n tags = {}\n children = {}\n collectionTag = null\n id = nextId++\n\n constructor(public value: T) {\n this.value = value\n this.tag.value = value\n }\n}\n\nconst arrayProxyHandler = {\n get([node]: [Node], key: string | symbol): unknown {\n if (key === 'length') {\n consumeCollection(node)\n }\n\n return objectProxyHandler.get(node, key)\n },\n\n ownKeys([node]: [Node]): ArrayLike {\n return objectProxyHandler.ownKeys(node)\n },\n\n getOwnPropertyDescriptor(\n [node]: [Node],\n prop: string | symbol\n ): PropertyDescriptor | undefined {\n return objectProxyHandler.getOwnPropertyDescriptor(node, prop)\n },\n\n has([node]: [Node], prop: string | symbol): boolean {\n return objectProxyHandler.has(node, prop)\n }\n}\n\nexport function createNode | Record>(\n value: T\n): Node {\n if (Array.isArray(value)) {\n return new ArrayTreeNode(value)\n }\n\n return new ObjectTreeNode(value) as Node\n}\n\nconst keysMap = new WeakMap<\n Array | Record,\n Set\n>()\n\nexport function updateNode | Record>(\n node: Node,\n newValue: T\n): void {\n const { value, tags, children } = node\n\n node.value = newValue\n\n if (\n Array.isArray(value) &&\n Array.isArray(newValue) &&\n value.length !== newValue.length\n ) {\n dirtyCollection(node)\n } else {\n if (value !== newValue) {\n let oldKeysSize = 0\n let newKeysSize = 0\n let anyKeysAdded = false\n\n for (const _key in value) {\n oldKeysSize++\n }\n\n for (const key in newValue) {\n newKeysSize++\n if (!(key in value)) {\n anyKeysAdded = true\n break\n }\n }\n\n const isDifferent = anyKeysAdded || oldKeysSize !== newKeysSize\n\n if (isDifferent) {\n dirtyCollection(node)\n }\n }\n }\n\n for (const key in tags) {\n const childValue = (value as Record)[key]\n const newChildValue = (newValue as Record)[key]\n\n if (childValue !== newChildValue) {\n dirtyCollection(node)\n dirtyTag(tags[key], newChildValue)\n }\n\n if (typeof newChildValue === 'object' && newChildValue !== null) {\n delete tags[key]\n }\n }\n\n for (const key in children) {\n const childNode = children[key]\n const newChildValue = (newValue as Record)[key]\n\n const childValue = childNode.value\n\n if (childValue === newChildValue) {\n continue\n } else if (typeof newChildValue === 'object' && newChildValue !== null) {\n updateNode(childNode, newChildValue as Record)\n } else {\n deleteNode(childNode)\n delete children[key]\n }\n }\n}\n\nfunction deleteNode(node: Node): void {\n if (node.tag) {\n dirtyTag(node.tag, null)\n }\n dirtyCollection(node)\n for (const key in node.tags) {\n dirtyTag(node.tags[key], null)\n }\n for (const key in node.children) {\n deleteNode(node.children[key])\n }\n}\n","import type {\n AnyFunction,\n DefaultMemoizeFields,\n EqualityFn,\n Simplify\n} from './types'\n\nimport type { NOT_FOUND_TYPE } from './utils'\nimport { NOT_FOUND } from './utils'\n\n// Cache implementation based on Erik Rasmussen's `lru-memoize`:\n// https://github.com/erikras/lru-memoize\n\ninterface Entry {\n key: unknown\n value: unknown\n}\n\ninterface Cache {\n get(key: unknown): unknown | NOT_FOUND_TYPE\n put(key: unknown, value: unknown): void\n getEntries(): Entry[]\n clear(): void\n}\n\nfunction createSingletonCache(equals: EqualityFn): Cache {\n let entry: Entry | undefined\n return {\n get(key: unknown) {\n if (entry && equals(entry.key, key)) {\n return entry.value\n }\n\n return NOT_FOUND\n },\n\n put(key: unknown, value: unknown) {\n entry = { key, value }\n },\n\n getEntries() {\n return entry ? [entry] : []\n },\n\n clear() {\n entry = undefined\n }\n }\n}\n\nfunction createLruCache(maxSize: number, equals: EqualityFn): Cache {\n let entries: Entry[] = []\n\n function get(key: unknown) {\n const cacheIndex = entries.findIndex(entry => equals(key, entry.key))\n\n // We found a cached entry\n if (cacheIndex > -1) {\n const entry = entries[cacheIndex]\n\n // Cached entry not at top of cache, move it to the top\n if (cacheIndex > 0) {\n entries.splice(cacheIndex, 1)\n entries.unshift(entry)\n }\n\n return entry.value\n }\n\n // No entry found in cache, return sentinel\n return NOT_FOUND\n }\n\n function put(key: unknown, value: unknown) {\n if (get(key) === NOT_FOUND) {\n // TODO Is unshift slow?\n entries.unshift({ key, value })\n if (entries.length > maxSize) {\n entries.pop()\n }\n }\n }\n\n function getEntries() {\n return entries\n }\n\n function clear() {\n entries = []\n }\n\n return { get, put, getEntries, clear }\n}\n\n/**\n * Runs a simple reference equality check.\n * What {@linkcode lruMemoize lruMemoize} uses by default.\n *\n * **Note**: This function was previously known as `defaultEqualityCheck`.\n *\n * @public\n */\nexport const referenceEqualityCheck: EqualityFn = (a, b) => a === b\n\nexport function createCacheKeyComparator(equalityCheck: EqualityFn) {\n return function areArgumentsShallowlyEqual(\n prev: unknown[] | IArguments | null,\n next: unknown[] | IArguments | null\n ): boolean {\n if (prev === null || next === null || prev.length !== next.length) {\n return false\n }\n\n // Do this in a for loop (and not a `forEach` or an `every`) so we can determine equality as fast as possible.\n const { length } = prev\n for (let i = 0; i < length; i++) {\n if (!equalityCheck(prev[i], next[i])) {\n return false\n }\n }\n\n return true\n }\n}\n\n/**\n * Options for configuring the behavior of a function memoized with\n * LRU (Least Recently Used) caching.\n *\n * @template Result - The type of the return value of the memoized function.\n *\n * @public\n */\nexport interface LruMemoizeOptions {\n /**\n * Function used to compare the individual arguments of the\n * provided calculation function.\n *\n * @default referenceEqualityCheck\n */\n equalityCheck?: EqualityFn\n\n /**\n * If provided, used to compare a newly generated output value against\n * previous values in the cache. If a match is found,\n * the old value is returned. This addresses the common\n * ```ts\n * todos.map(todo => todo.id)\n * ```\n * use case, where an update to another field in the original data causes\n * a recalculation due to changed references, but the output is still\n * effectively the same.\n *\n * @since 4.1.0\n */\n resultEqualityCheck?: EqualityFn\n\n /**\n * The maximum size of the cache used by the selector.\n * A size greater than 1 means the selector will use an\n * LRU (Least Recently Used) cache, allowing for the caching of multiple\n * results based on different sets of arguments.\n *\n * @default 1\n */\n maxSize?: number\n}\n\n/**\n * Creates a memoized version of a function with an optional\n * LRU (Least Recently Used) cache. The memoized function uses a cache to\n * store computed values. Depending on the `maxSize` option, it will use\n * either a singleton cache (for a single entry) or an\n * LRU cache (for multiple entries).\n *\n * **Note**: This function was previously known as `defaultMemoize`.\n *\n * @param func - The function to be memoized.\n * @param equalityCheckOrOptions - Either an equality check function or an options object.\n * @returns A memoized function with a `.clearCache()` method attached.\n *\n * @template Func - The type of the function that is memoized.\n *\n * @see {@link https://reselect.js.org/api/lruMemoize `lruMemoize`}\n *\n * @public\n */\nexport function lruMemoize(\n func: Func,\n equalityCheckOrOptions?: EqualityFn | LruMemoizeOptions>\n) {\n const providedOptions =\n typeof equalityCheckOrOptions === 'object'\n ? equalityCheckOrOptions\n : { equalityCheck: equalityCheckOrOptions }\n\n const {\n equalityCheck = referenceEqualityCheck,\n maxSize = 1,\n resultEqualityCheck\n } = providedOptions\n\n const comparator = createCacheKeyComparator(equalityCheck)\n\n let resultsCount = 0\n\n const cache =\n maxSize <= 1\n ? createSingletonCache(comparator)\n : createLruCache(maxSize, comparator)\n\n function memoized() {\n let value = cache.get(arguments) as ReturnType\n if (value === NOT_FOUND) {\n // apply arguments instead of spreading for performance.\n // @ts-ignore\n value = func.apply(null, arguments) as ReturnType\n resultsCount++\n\n if (resultEqualityCheck) {\n const entries = cache.getEntries()\n const matchingEntry = entries.find(entry =>\n resultEqualityCheck(entry.value as ReturnType, value)\n )\n\n if (matchingEntry) {\n value = matchingEntry.value as ReturnType\n resultsCount !== 0 && resultsCount--\n }\n }\n\n cache.put(arguments, value)\n }\n return value\n }\n\n memoized.clearCache = () => {\n cache.clear()\n memoized.resetResultsCount()\n }\n\n memoized.resultsCount = () => resultsCount\n\n memoized.resetResultsCount = () => {\n resultsCount = 0\n }\n\n return memoized as Func & Simplify\n}\n","import { createNode, updateNode } from './proxy'\nimport type { Node } from './tracking'\n\nimport { createCacheKeyComparator, referenceEqualityCheck } from '../lruMemoize'\nimport type { AnyFunction, DefaultMemoizeFields, Simplify } from '../types'\nimport { createCache } from './autotracking'\n\n/**\n * Uses an \"auto-tracking\" approach inspired by the work of the Ember Glimmer team.\n * It uses a Proxy to wrap arguments and track accesses to nested fields\n * in your selector on first read. Later, when the selector is called with\n * new arguments, it identifies which accessed fields have changed and\n * only recalculates the result if one or more of those accessed fields have changed.\n * This allows it to be more precise than the shallow equality checks in `lruMemoize`.\n *\n * __Design Tradeoffs for `autotrackMemoize`:__\n * - Pros:\n * - It is likely to avoid excess calculations and recalculate fewer times than `lruMemoize` will,\n * which may also result in fewer component re-renders.\n * - Cons:\n * - It only has a cache size of 1.\n * - It is slower than `lruMemoize`, because it has to do more work. (How much slower is dependent on the number of accessed fields in a selector, number of calls, frequency of input changes, etc)\n * - It can have some unexpected behavior. Because it tracks nested field accesses,\n * cases where you don't access a field will not recalculate properly.\n * For example, a badly-written selector like:\n * ```ts\n * createSelector([state => state.todos], todos => todos)\n * ```\n * that just immediately returns the extracted value will never update, because it doesn't see any field accesses to check.\n *\n * __Use Cases for `autotrackMemoize`:__\n * - It is likely best used for cases where you need to access specific nested fields\n * in data, and avoid recalculating if other fields in the same data objects are immutably updated.\n *\n * @param func - The function to be memoized.\n * @returns A memoized function with a `.clearCache()` method attached.\n *\n * @example\n * Using `createSelector`\n * ```ts\n * import { unstable_autotrackMemoize as autotrackMemoize, createSelector } from 'reselect'\n *\n * const selectTodoIds = createSelector(\n * [(state: RootState) => state.todos],\n * (todos) => todos.map(todo => todo.id),\n * { memoize: autotrackMemoize }\n * )\n * ```\n *\n * @example\n * Using `createSelectorCreator`\n * ```ts\n * import { unstable_autotrackMemoize as autotrackMemoize, createSelectorCreator } from 'reselect'\n *\n * const createSelectorAutotrack = createSelectorCreator({ memoize: autotrackMemoize })\n *\n * const selectTodoIds = createSelectorAutotrack(\n * [(state: RootState) => state.todos],\n * (todos) => todos.map(todo => todo.id)\n * )\n * ```\n *\n * @template Func - The type of the function that is memoized.\n *\n * @see {@link https://reselect.js.org/api/unstable_autotrackMemoize autotrackMemoize}\n *\n * @since 5.0.0\n * @public\n * @experimental\n */\nexport function autotrackMemoize(func: Func) {\n // we reference arguments instead of spreading them for performance reasons\n\n const node: Node> = createNode(\n [] as unknown as Record\n )\n\n let lastArgs: IArguments | null = null\n\n const shallowEqual = createCacheKeyComparator(referenceEqualityCheck)\n\n const cache = createCache(() => {\n const res = func.apply(null, node.proxy as unknown as any[])\n return res\n })\n\n function memoized() {\n if (!shallowEqual(lastArgs, arguments)) {\n updateNode(node, arguments as unknown as Record)\n lastArgs = arguments\n }\n return cache.value\n }\n\n memoized.clearCache = () => {\n return cache.clear()\n }\n\n return memoized as Func & Simplify\n}\n","// Original source:\n// - https://github.com/facebook/react/blob/0b974418c9a56f6c560298560265dcf4b65784bc/packages/react/src/ReactCache.js\n\nimport type {\n AnyFunction,\n DefaultMemoizeFields,\n EqualityFn,\n Simplify\n} from './types'\n\nclass StrongRef {\n constructor(private value: T) {}\n deref() {\n return this.value\n }\n}\n\n/**\n * @returns The {@linkcode StrongRef} if {@linkcode WeakRef} is not available.\n *\n * @since 5.1.2\n * @internal\n */\nconst getWeakRef = () =>\n typeof WeakRef === 'undefined'\n ? (StrongRef as unknown as typeof WeakRef)\n : WeakRef\n\nconst Ref = /* @__PURE__ */ getWeakRef()\n\nconst UNTERMINATED = 0\nconst TERMINATED = 1\n\ninterface UnterminatedCacheNode {\n /**\n * Status, represents whether the cached computation returned a value or threw an error.\n */\n s: 0\n /**\n * Value, either the cached result or an error, depending on status.\n */\n v: void\n /**\n * Object cache, a `WeakMap` where non-primitive arguments are stored.\n */\n o: null | WeakMap>\n /**\n * Primitive cache, a regular Map where primitive arguments are stored.\n */\n p: null | Map>\n}\n\ninterface TerminatedCacheNode {\n /**\n * Status, represents whether the cached computation returned a value or threw an error.\n */\n s: 1\n /**\n * Value, either the cached result or an error, depending on status.\n */\n v: T\n /**\n * Object cache, a `WeakMap` where non-primitive arguments are stored.\n */\n o: null | WeakMap>\n /**\n * Primitive cache, a regular `Map` where primitive arguments are stored.\n */\n p: null | Map>\n}\n\ntype CacheNode = TerminatedCacheNode | UnterminatedCacheNode\n\nfunction createCacheNode(): CacheNode {\n return {\n s: UNTERMINATED,\n v: undefined,\n o: null,\n p: null\n }\n}\n\n/**\n * Configuration options for a memoization function utilizing `WeakMap` for\n * its caching mechanism.\n *\n * @template Result - The type of the return value of the memoized function.\n *\n * @since 5.0.0\n * @public\n */\nexport interface WeakMapMemoizeOptions {\n /**\n * If provided, used to compare a newly generated output value against previous values in the cache.\n * If a match is found, the old value is returned. This addresses the common\n * ```ts\n * todos.map(todo => todo.id)\n * ```\n * use case, where an update to another field in the original data causes a recalculation\n * due to changed references, but the output is still effectively the same.\n *\n * @since 5.0.0\n */\n resultEqualityCheck?: EqualityFn\n}\n\n/**\n * Derefences the argument if it is a Ref. Else if it is a value already, return it.\n *\n * @param r - the object to maybe deref\n * @returns The derefenced value if the argument is a Ref, else the argument value itself.\n */\nfunction maybeDeref(r: any) {\n if (r instanceof Ref) {\n return r.deref()\n }\n\n return r\n}\n\n/**\n * Creates a tree of `WeakMap`-based cache nodes based on the identity of the\n * arguments it's been called with (in this case, the extracted values from your input selectors).\n * This allows `weakMapMemoize` to have an effectively infinite cache size.\n * Cache results will be kept in memory as long as references to the arguments still exist,\n * and then cleared out as the arguments are garbage-collected.\n *\n * __Design Tradeoffs for `weakMapMemoize`:__\n * - Pros:\n * - It has an effectively infinite cache size, but you have no control over\n * how long values are kept in cache as it's based on garbage collection and `WeakMap`s.\n * - Cons:\n * - There's currently no way to alter the argument comparisons.\n * They're based on strict reference equality.\n * - It's roughly the same speed as `lruMemoize`, although likely a fraction slower.\n *\n * __Use Cases for `weakMapMemoize`:__\n * - This memoizer is likely best used for cases where you need to call the\n * same selector instance with many different arguments, such as a single\n * selector instance that is used in a list item component and called with\n * item IDs like:\n * ```ts\n * useSelector(state => selectSomeData(state, props.category))\n * ```\n * @param func - The function to be memoized.\n * @returns A memoized function with a `.clearCache()` method attached.\n *\n * @example\n * Using `createSelector`\n * ```ts\n * import { createSelector, weakMapMemoize } from 'reselect'\n *\n * interface RootState {\n * items: { id: number; category: string; name: string }[]\n * }\n *\n * const selectItemsByCategory = createSelector(\n * [\n * (state: RootState) => state.items,\n * (state: RootState, category: string) => category\n * ],\n * (items, category) => items.filter(item => item.category === category),\n * {\n * memoize: weakMapMemoize,\n * argsMemoize: weakMapMemoize\n * }\n * )\n * ```\n *\n * @example\n * Using `createSelectorCreator`\n * ```ts\n * import { createSelectorCreator, weakMapMemoize } from 'reselect'\n *\n * const createSelectorWeakMap = createSelectorCreator({ memoize: weakMapMemoize, argsMemoize: weakMapMemoize })\n *\n * const selectItemsByCategory = createSelectorWeakMap(\n * [\n * (state: RootState) => state.items,\n * (state: RootState, category: string) => category\n * ],\n * (items, category) => items.filter(item => item.category === category)\n * )\n * ```\n *\n * @template Func - The type of the function that is memoized.\n *\n * @see {@link https://reselect.js.org/api/weakMapMemoize `weakMapMemoize`}\n *\n * @since 5.0.0\n * @public\n * @experimental\n */\nexport function weakMapMemoize(\n func: Func,\n options: WeakMapMemoizeOptions> = {}\n) {\n let fnNode = createCacheNode()\n const { resultEqualityCheck } = options\n\n let lastResult: WeakRef | undefined\n\n let resultsCount = 0\n\n function memoized() {\n let cacheNode = fnNode\n const { length } = arguments\n for (let i = 0, l = length; i < l; i++) {\n const arg = arguments[i]\n if (\n typeof arg === 'function' ||\n (typeof arg === 'object' && arg !== null)\n ) {\n // Objects go into a WeakMap\n let objectCache = cacheNode.o\n if (objectCache === null) {\n cacheNode.o = objectCache = new WeakMap()\n }\n const objectNode = objectCache.get(arg)\n if (objectNode === undefined) {\n cacheNode = createCacheNode()\n objectCache.set(arg, cacheNode)\n } else {\n cacheNode = objectNode\n }\n } else {\n // Primitives go into a regular Map\n let primitiveCache = cacheNode.p\n if (primitiveCache === null) {\n cacheNode.p = primitiveCache = new Map()\n }\n const primitiveNode = primitiveCache.get(arg)\n if (primitiveNode === undefined) {\n cacheNode = createCacheNode()\n primitiveCache.set(arg, cacheNode)\n } else {\n cacheNode = primitiveNode\n }\n }\n }\n\n const terminatedNode = cacheNode as unknown as TerminatedCacheNode\n\n let result\n\n if (cacheNode.s === TERMINATED) {\n result = cacheNode.v\n } else {\n // Allow errors to propagate\n result = func.apply(null, arguments as unknown as any[])\n resultsCount++\n\n if (resultEqualityCheck) {\n // Deref lastResult if it is a Ref\n const lastResultValue = maybeDeref(lastResult)\n\n if (\n lastResultValue != null &&\n resultEqualityCheck(lastResultValue as ReturnType, result)\n ) {\n result = lastResultValue\n\n resultsCount !== 0 && resultsCount--\n }\n\n const needsWeakRef =\n (typeof result === 'object' && result !== null) ||\n typeof result === 'function'\n\n lastResult = needsWeakRef ? /* @__PURE__ */ new Ref(result) : result\n }\n }\n\n terminatedNode.s = TERMINATED\n\n terminatedNode.v = result\n return result\n }\n\n memoized.clearCache = () => {\n fnNode = createCacheNode()\n memoized.resetResultsCount()\n }\n\n memoized.resultsCount = () => resultsCount\n\n memoized.resetResultsCount = () => {\n resultsCount = 0\n }\n\n return memoized as Func & Simplify\n}\n","import { weakMapMemoize } from './weakMapMemoize'\n\nimport type {\n Combiner,\n CreateSelectorOptions,\n DropFirstParameter,\n ExtractMemoizerFields,\n GetParamsFromSelectors,\n GetStateFromSelectors,\n InterruptRecursion,\n OutputSelector,\n Selector,\n SelectorArray,\n SetRequired,\n Simplify,\n UnknownMemoizer\n} from './types'\n\nimport {\n assertIsFunction,\n collectInputSelectorResults,\n ensureIsArray,\n getDependencies,\n getDevModeChecksExecutionInfo\n} from './utils'\n\n/**\n * An instance of `createSelector`, customized with a given memoize implementation.\n *\n * @template MemoizeFunction - The type of the memoize function that is used to memoize the `resultFunc` inside `createSelector` (e.g., `lruMemoize` or `weakMapMemoize`).\n * @template ArgsMemoizeFunction - The type of the optional memoize function that is used to memoize the arguments passed into the output selector generated by `createSelector` (e.g., `lruMemoize` or `weakMapMemoize`). If none is explicitly provided, `weakMapMemoize` will be used.\n * @template StateType - The type of state that the selectors created with this selector creator will operate on.\n *\n * @public\n */\nexport interface CreateSelectorFunction<\n MemoizeFunction extends UnknownMemoizer = typeof weakMapMemoize,\n ArgsMemoizeFunction extends UnknownMemoizer = typeof weakMapMemoize,\n StateType = any\n> {\n /**\n * Creates a memoized selector function.\n *\n * @param createSelectorArgs - An arbitrary number of input selectors as separate inline arguments and a `combiner` function.\n * @returns A memoized output selector.\n *\n * @template InputSelectors - The type of the input selectors as an array.\n * @template Result - The return type of the `combiner` as well as the output selector.\n * @template OverrideMemoizeFunction - The type of the optional `memoize` function that could be passed into the options object to override the original `memoize` function that was initially passed into `createSelectorCreator`.\n * @template OverrideArgsMemoizeFunction - The type of the optional `argsMemoize` function that could be passed into the options object to override the original `argsMemoize` function that was initially passed into `createSelectorCreator`.\n *\n * @see {@link https://reselect.js.org/api/createselector `createSelector`}\n */\n , Result>(\n ...createSelectorArgs: [\n ...inputSelectors: InputSelectors,\n combiner: Combiner\n ]\n ): OutputSelector<\n InputSelectors,\n Result,\n MemoizeFunction,\n ArgsMemoizeFunction\n > &\n InterruptRecursion\n\n /**\n * Creates a memoized selector function.\n *\n * @param createSelectorArgs - An arbitrary number of input selectors as separate inline arguments, a `combiner` function and an `options` object.\n * @returns A memoized output selector.\n *\n * @template InputSelectors - The type of the input selectors as an array.\n * @template Result - The return type of the `combiner` as well as the output selector.\n * @template OverrideMemoizeFunction - The type of the optional `memoize` function that could be passed into the options object to override the original `memoize` function that was initially passed into `createSelectorCreator`.\n * @template OverrideArgsMemoizeFunction - The type of the optional `argsMemoize` function that could be passed into the options object to override the original `argsMemoize` function that was initially passed into `createSelectorCreator`.\n *\n * @see {@link https://reselect.js.org/api/createselector `createSelector`}\n */\n <\n InputSelectors extends SelectorArray,\n Result,\n OverrideMemoizeFunction extends UnknownMemoizer = MemoizeFunction,\n OverrideArgsMemoizeFunction extends UnknownMemoizer = ArgsMemoizeFunction\n >(\n ...createSelectorArgs: [\n ...inputSelectors: InputSelectors,\n combiner: Combiner,\n createSelectorOptions: Simplify<\n CreateSelectorOptions<\n MemoizeFunction,\n ArgsMemoizeFunction,\n OverrideMemoizeFunction,\n OverrideArgsMemoizeFunction\n >\n >\n ]\n ): OutputSelector<\n InputSelectors,\n Result,\n OverrideMemoizeFunction,\n OverrideArgsMemoizeFunction\n > &\n InterruptRecursion\n\n /**\n * Creates a memoized selector function.\n *\n * @param inputSelectors - An array of input selectors.\n * @param combiner - A function that Combines the input selectors and returns an output selector. Otherwise known as the result function.\n * @param createSelectorOptions - An optional options object that allows for further customization per selector.\n * @returns A memoized output selector.\n *\n * @template InputSelectors - The type of the input selectors array.\n * @template Result - The return type of the `combiner` as well as the output selector.\n * @template OverrideMemoizeFunction - The type of the optional `memoize` function that could be passed into the options object to override the original `memoize` function that was initially passed into `createSelectorCreator`.\n * @template OverrideArgsMemoizeFunction - The type of the optional `argsMemoize` function that could be passed into the options object to override the original `argsMemoize` function that was initially passed into `createSelectorCreator`.\n *\n * @see {@link https://reselect.js.org/api/createselector `createSelector`}\n */\n <\n InputSelectors extends SelectorArray,\n Result,\n OverrideMemoizeFunction extends UnknownMemoizer = MemoizeFunction,\n OverrideArgsMemoizeFunction extends UnknownMemoizer = ArgsMemoizeFunction\n >(\n inputSelectors: [...InputSelectors],\n combiner: Combiner,\n createSelectorOptions?: Simplify<\n CreateSelectorOptions<\n MemoizeFunction,\n ArgsMemoizeFunction,\n OverrideMemoizeFunction,\n OverrideArgsMemoizeFunction\n >\n >\n ): OutputSelector<\n InputSelectors,\n Result,\n OverrideMemoizeFunction,\n OverrideArgsMemoizeFunction\n > &\n InterruptRecursion\n\n /**\n * Creates a \"pre-typed\" version of {@linkcode createSelector createSelector}\n * where the `state` type is predefined.\n *\n * This allows you to set the `state` type once, eliminating the need to\n * specify it with every {@linkcode createSelector createSelector} call.\n *\n * @returns A pre-typed `createSelector` with the state type already defined.\n *\n * @example\n * ```ts\n * import { createSelector } from 'reselect'\n *\n * export interface RootState {\n * todos: { id: number; completed: boolean }[]\n * alerts: { id: number; read: boolean }[]\n * }\n *\n * export const createAppSelector = createSelector.withTypes()\n *\n * const selectTodoIds = createAppSelector(\n * [\n * // Type of `state` is set to `RootState`, no need to manually set the type\n * state => state.todos\n * ],\n * todos => todos.map(({ id }) => id)\n * )\n * ```\n * @template OverrideStateType - The specific type of state used by all selectors created with this selector creator.\n *\n * @see {@link https://reselect.js.org/api/createselector#defining-a-pre-typed-createselector `createSelector.withTypes`}\n *\n * @since 5.1.0\n */\n withTypes: () => CreateSelectorFunction<\n MemoizeFunction,\n ArgsMemoizeFunction,\n OverrideStateType\n >\n}\n\n/**\n * Creates a selector creator function with the specified memoization function\n * and options for customizing memoization behavior.\n *\n * @param options - An options object containing the `memoize` function responsible for memoizing the `resultFunc` inside `createSelector` (e.g., `lruMemoize` or `weakMapMemoize`). It also provides additional options for customizing memoization. While the `memoize` property is mandatory, the rest are optional.\n * @returns A customized `createSelector` function.\n *\n * @example\n * ```ts\n * const customCreateSelector = createSelectorCreator({\n * memoize: customMemoize, // Function to be used to memoize `resultFunc`\n * memoizeOptions: [memoizeOption1, memoizeOption2], // Options passed to `customMemoize` as the second argument onwards\n * argsMemoize: customArgsMemoize, // Function to be used to memoize the selector's arguments\n * argsMemoizeOptions: [argsMemoizeOption1, argsMemoizeOption2] // Options passed to `customArgsMemoize` as the second argument onwards\n * })\n *\n * const customSelector = customCreateSelector(\n * [inputSelector1, inputSelector2],\n * resultFunc // `resultFunc` will be passed as the first argument to `customMemoize`\n * )\n *\n * customSelector(\n * ...selectorArgs // Will be memoized by `customArgsMemoize`\n * )\n * ```\n *\n * @template MemoizeFunction - The type of the memoize function that is used to memoize the `resultFunc` inside `createSelector` (e.g., `lruMemoize` or `weakMapMemoize`).\n * @template ArgsMemoizeFunction - The type of the optional memoize function that is used to memoize the arguments passed into the output selector generated by `createSelector` (e.g., `lruMemoize` or `weakMapMemoize`). If none is explicitly provided, `weakMapMemoize` will be used.\n *\n * @see {@link https://reselect.js.org/api/createSelectorCreator#using-options-since-500 `createSelectorCreator`}\n *\n * @since 5.0.0\n * @public\n */\nexport function createSelectorCreator<\n MemoizeFunction extends UnknownMemoizer,\n ArgsMemoizeFunction extends UnknownMemoizer = typeof weakMapMemoize\n>(\n options: Simplify<\n SetRequired<\n CreateSelectorOptions<\n typeof weakMapMemoize,\n typeof weakMapMemoize,\n MemoizeFunction,\n ArgsMemoizeFunction\n >,\n 'memoize'\n >\n >\n): CreateSelectorFunction\n\n/**\n * Creates a selector creator function with the specified memoization function\n * and options for customizing memoization behavior.\n *\n * @param memoize - The `memoize` function responsible for memoizing the `resultFunc` inside `createSelector` (e.g., `lruMemoize` or `weakMapMemoize`).\n * @param memoizeOptionsFromArgs - Optional configuration options for the memoization function. These options are then passed to the memoize function as the second argument onwards.\n * @returns A customized `createSelector` function.\n *\n * @example\n * ```ts\n * const customCreateSelector = createSelectorCreator(customMemoize, // Function to be used to memoize `resultFunc`\n * option1, // Will be passed as second argument to `customMemoize`\n * option2, // Will be passed as third argument to `customMemoize`\n * option3 // Will be passed as fourth argument to `customMemoize`\n * )\n *\n * const customSelector = customCreateSelector(\n * [inputSelector1, inputSelector2],\n * resultFunc // `resultFunc` will be passed as the first argument to `customMemoize`\n * )\n * ```\n *\n * @template MemoizeFunction - The type of the memoize function that is used to memoize the `resultFunc` inside `createSelector` (e.g., `lruMemoize` or `weakMapMemoize`).\n *\n * @see {@link https://reselect.js.org/api/createSelectorCreator#using-memoize-and-memoizeoptions `createSelectorCreator`}\n *\n * @public\n */\nexport function createSelectorCreator(\n memoize: MemoizeFunction,\n ...memoizeOptionsFromArgs: DropFirstParameter\n): CreateSelectorFunction\n\n/**\n * Creates a selector creator function with the specified memoization\n * function and options for customizing memoization behavior.\n *\n * @param memoizeOrOptions - Either A `memoize` function or an `options` object containing the `memoize` function.\n * @param memoizeOptionsFromArgs - Optional configuration options for the memoization function. These options are then passed to the memoize function as the second argument onwards.\n * @returns A customized `createSelector` function.\n *\n * @template MemoizeFunction - The type of the memoize function that is used to memoize the `resultFunc` inside `createSelector` (e.g., `lruMemoize` or `weakMapMemoize`).\n * @template ArgsMemoizeFunction - The type of the optional memoize function that is used to memoize the arguments passed into the output selector generated by `createSelector` (e.g., `lruMemoize` or `weakMapMemoize`). If none is explicitly provided, `weakMapMemoize` will be used.\n * @template MemoizeOrOptions - The type of the first argument. It can either be a `memoize` function or an `options` object containing the `memoize` function.\n */\nexport function createSelectorCreator<\n MemoizeFunction extends UnknownMemoizer,\n ArgsMemoizeFunction extends UnknownMemoizer,\n MemoizeOrOptions extends\n | MemoizeFunction\n | SetRequired<\n CreateSelectorOptions,\n 'memoize'\n >\n>(\n memoizeOrOptions: MemoizeOrOptions,\n ...memoizeOptionsFromArgs: MemoizeOrOptions extends SetRequired<\n CreateSelectorOptions,\n 'memoize'\n >\n ? never\n : DropFirstParameter\n) {\n /** options initially passed into `createSelectorCreator`. */\n const createSelectorCreatorOptions: SetRequired<\n CreateSelectorOptions,\n 'memoize'\n > = typeof memoizeOrOptions === 'function'\n ? {\n memoize: memoizeOrOptions as MemoizeFunction,\n memoizeOptions: memoizeOptionsFromArgs\n }\n : memoizeOrOptions\n\n const createSelector = <\n InputSelectors extends SelectorArray,\n Result,\n OverrideMemoizeFunction extends UnknownMemoizer = MemoizeFunction,\n OverrideArgsMemoizeFunction extends UnknownMemoizer = ArgsMemoizeFunction\n >(\n ...createSelectorArgs: [\n ...inputSelectors: [...InputSelectors],\n combiner: Combiner,\n createSelectorOptions?: CreateSelectorOptions<\n MemoizeFunction,\n ArgsMemoizeFunction,\n OverrideMemoizeFunction,\n OverrideArgsMemoizeFunction\n >\n ]\n ) => {\n let recomputations = 0\n let dependencyRecomputations = 0\n let lastResult: Result\n\n // Due to the intricacies of rest params, we can't do an optional arg after `...createSelectorArgs`.\n // So, start by declaring the default value here.\n // (And yes, the words 'memoize' and 'options' appear too many times in this next sequence.)\n let directlyPassedOptions: CreateSelectorOptions<\n MemoizeFunction,\n ArgsMemoizeFunction,\n OverrideMemoizeFunction,\n OverrideArgsMemoizeFunction\n > = {}\n\n // Normally, the result func or \"combiner\" is the last arg\n let resultFunc = createSelectorArgs.pop() as\n | Combiner\n | CreateSelectorOptions<\n MemoizeFunction,\n ArgsMemoizeFunction,\n OverrideMemoizeFunction,\n OverrideArgsMemoizeFunction\n >\n\n // If the result func is actually an _object_, assume it's our options object\n if (typeof resultFunc === 'object') {\n directlyPassedOptions = resultFunc\n // and pop the real result func off\n resultFunc = createSelectorArgs.pop() as Combiner\n }\n\n assertIsFunction(\n resultFunc,\n `createSelector expects an output function after the inputs, but received: [${typeof resultFunc}]`\n )\n\n // Determine which set of options we're using. Prefer options passed directly,\n // but fall back to options given to `createSelectorCreator`.\n const combinedOptions = {\n ...createSelectorCreatorOptions,\n ...directlyPassedOptions\n }\n\n const {\n memoize,\n memoizeOptions = [],\n argsMemoize = weakMapMemoize,\n argsMemoizeOptions = []\n } = combinedOptions\n\n // Simplifying assumption: it's unlikely that the first options arg of the provided memoizer\n // is an array. In most libs I've looked at, it's an equality function or options object.\n // Based on that, if `memoizeOptions` _is_ an array, we assume it's a full\n // user-provided array of options. Otherwise, it must be just the _first_ arg, and so\n // we wrap it in an array so we can apply it.\n const finalMemoizeOptions = ensureIsArray(memoizeOptions)\n const finalArgsMemoizeOptions = ensureIsArray(argsMemoizeOptions)\n const dependencies = getDependencies(createSelectorArgs) as InputSelectors\n\n const memoizedResultFunc = memoize(function recomputationWrapper() {\n recomputations++\n // apply arguments instead of spreading for performance.\n // @ts-ignore\n return (resultFunc as Combiner).apply(\n null,\n arguments as unknown as Parameters>\n )\n }, ...finalMemoizeOptions) as Combiner &\n ExtractMemoizerFields\n\n let firstRun = true\n\n // If a selector is called with the exact same arguments we don't need to traverse our dependencies again.\n const selector = argsMemoize(function dependenciesChecker() {\n dependencyRecomputations++\n /** Return values of input selectors which the `resultFunc` takes as arguments. */\n const inputSelectorResults = collectInputSelectorResults(\n dependencies,\n arguments\n )\n\n // apply arguments instead of spreading for performance.\n // @ts-ignore\n lastResult = memoizedResultFunc.apply(null, inputSelectorResults)\n\n if (process.env.NODE_ENV !== 'production') {\n const { devModeChecks = {} } = combinedOptions\n const { identityFunctionCheck, inputStabilityCheck } =\n getDevModeChecksExecutionInfo(firstRun, devModeChecks)\n if (identityFunctionCheck.shouldRun) {\n identityFunctionCheck.run(\n resultFunc as Combiner,\n inputSelectorResults,\n lastResult\n )\n }\n\n if (inputStabilityCheck.shouldRun) {\n // make a second copy of the params, to check if we got the same results\n const inputSelectorResultsCopy = collectInputSelectorResults(\n dependencies,\n arguments\n )\n\n inputStabilityCheck.run(\n { inputSelectorResults, inputSelectorResultsCopy },\n { memoize, memoizeOptions: finalMemoizeOptions },\n arguments\n )\n }\n\n if (firstRun) firstRun = false\n }\n\n return lastResult\n }, ...finalArgsMemoizeOptions) as unknown as Selector<\n GetStateFromSelectors,\n Result,\n GetParamsFromSelectors\n > &\n ExtractMemoizerFields\n\n return Object.assign(selector, {\n resultFunc,\n memoizedResultFunc,\n dependencies,\n dependencyRecomputations: () => dependencyRecomputations,\n resetDependencyRecomputations: () => {\n dependencyRecomputations = 0\n },\n lastResult: () => lastResult,\n recomputations: () => recomputations,\n resetRecomputations: () => {\n recomputations = 0\n },\n memoize,\n argsMemoize\n }) as OutputSelector<\n InputSelectors,\n Result,\n OverrideMemoizeFunction,\n OverrideArgsMemoizeFunction\n >\n }\n\n Object.assign(createSelector, {\n withTypes: () => createSelector\n })\n\n return createSelector as CreateSelectorFunction<\n MemoizeFunction,\n ArgsMemoizeFunction\n >\n}\n\n/**\n * Accepts one or more \"input selectors\" (either as separate arguments or a single array),\n * a single \"result function\" / \"combiner\", and an optional options object, and\n * generates a memoized selector function.\n *\n * @see {@link https://reselect.js.org/api/createSelector `createSelector`}\n *\n * @public\n */\nexport const createSelector =\n /* #__PURE__ */ createSelectorCreator(weakMapMemoize)\n","import { createSelector } from './createSelectorCreator'\n\nimport type { CreateSelectorFunction } from './createSelectorCreator'\nimport type {\n InterruptRecursion,\n ObjectValuesToTuple,\n OutputSelector,\n Selector,\n Simplify,\n UnknownMemoizer\n} from './types'\nimport { assertIsObject } from './utils'\nimport type { weakMapMemoize } from './weakMapMemoize'\n\n/**\n * Represents a mapping of selectors to their return types.\n *\n * @template TObject - An object type where each property is a selector function.\n *\n * @public\n */\nexport type SelectorResultsMap = {\n [Key in keyof TObject]: ReturnType\n}\n\n/**\n * Represents a mapping of selectors for each key in a given root state.\n *\n * This type is a utility that takes a root state object type and\n * generates a corresponding set of selectors. Each selector is associated\n * with a key in the root state, allowing for the selection\n * of specific parts of the state.\n *\n * @template RootState - The type of the root state object.\n *\n * @since 5.0.0\n * @public\n */\nexport type RootStateSelectors = {\n [Key in keyof RootState]: Selector\n}\n\n/**\n * @deprecated Please use {@linkcode StructuredSelectorCreator.withTypes createStructuredSelector.withTypes()} instead. This type will be removed in the future.\n * @template RootState - The type of the root state object.\n *\n * @since 5.0.0\n * @public\n */\nexport type TypedStructuredSelectorCreator =\n /**\n * A convenience function that simplifies returning an object\n * made up of selector results.\n *\n * @param inputSelectorsObject - A key value pair consisting of input selectors.\n * @param selectorCreator - A custom selector creator function. It defaults to `createSelector`.\n * @returns A memoized structured selector.\n *\n * @example\n * Modern Use Case\n * ```ts\n * import { createSelector, createStructuredSelector } from 'reselect'\n *\n * interface RootState {\n * todos: {\n * id: number\n * completed: boolean\n * title: string\n * description: string\n * }[]\n * alerts: { id: number; read: boolean }[]\n * }\n *\n * // This:\n * const structuredSelector = createStructuredSelector(\n * {\n * todos: (state: RootState) => state.todos,\n * alerts: (state: RootState) => state.alerts,\n * todoById: (state: RootState, id: number) => state.todos[id]\n * },\n * createSelector\n * )\n *\n * // Is essentially the same as this:\n * const selector = createSelector(\n * [\n * (state: RootState) => state.todos,\n * (state: RootState) => state.alerts,\n * (state: RootState, id: number) => state.todos[id]\n * ],\n * (todos, alerts, todoById) => {\n * return {\n * todos,\n * alerts,\n * todoById\n * }\n * }\n * )\n * ```\n *\n * @example\n * In your component:\n * ```tsx\n * import type { RootState } from 'createStructuredSelector/modernUseCase'\n * import { structuredSelector } from 'createStructuredSelector/modernUseCase'\n * import type { FC } from 'react'\n * import { useSelector } from 'react-redux'\n *\n * interface Props {\n * id: number\n * }\n *\n * const MyComponent: FC = ({ id }) => {\n * const { todos, alerts, todoById } = useSelector((state: RootState) =>\n * structuredSelector(state, id)\n * )\n *\n * return (\n *
\n * Next to do is:\n *

{todoById.title}

\n *

Description: {todoById.description}

\n *
    \n *

    All other to dos:

    \n * {todos.map(todo => (\n *
  • {todo.title}
  • \n * ))}\n *
\n *
\n * )\n * }\n * ```\n *\n * @example\n * Simple Use Case\n * ```ts\n * const selectA = state => state.a\n * const selectB = state => state.b\n *\n * // The result function in the following selector\n * // is simply building an object from the input selectors\n * const structuredSelector = createSelector(selectA, selectB, (a, b) => ({\n * a,\n * b\n * }))\n *\n * const result = structuredSelector({ a: 1, b: 2 }) // will produce { x: 1, y: 2 }\n * ```\n *\n * @template InputSelectorsObject - The shape of the input selectors object.\n * @template MemoizeFunction - The type of the memoize function that is used to create the structured selector. It defaults to `weakMapMemoize`.\n * @template ArgsMemoizeFunction - The type of the of the memoize function that is used to memoize the arguments passed into the generated structured selector. It defaults to `weakMapMemoize`.\n *\n * @see {@link https://reselect.js.org/api/createStructuredSelector `createStructuredSelector`}\n */\n <\n InputSelectorsObject extends RootStateSelectors = RootStateSelectors,\n MemoizeFunction extends UnknownMemoizer = typeof weakMapMemoize,\n ArgsMemoizeFunction extends UnknownMemoizer = typeof weakMapMemoize\n >(\n inputSelectorsObject: InputSelectorsObject,\n selectorCreator?: CreateSelectorFunction<\n MemoizeFunction,\n ArgsMemoizeFunction\n >\n ) => OutputSelector<\n ObjectValuesToTuple,\n Simplify>,\n MemoizeFunction,\n ArgsMemoizeFunction\n > &\n InterruptRecursion\n\n/**\n * Represents an object where each property is a selector function.\n *\n * @template StateType - The type of state that all the selectors operate on.\n *\n * @public\n */\nexport type SelectorsObject = Record<\n string,\n Selector\n>\n\n/**\n * It provides a way to create structured selectors.\n * The structured selector can take multiple input selectors\n * and map their output to an object with specific keys.\n *\n * @template StateType - The type of state that the structured selectors created with this structured selector creator will operate on.\n *\n * @see {@link https://reselect.js.org/api/createStructuredSelector `createStructuredSelector`}\n *\n * @public\n */\nexport interface StructuredSelectorCreator {\n /**\n * A convenience function that simplifies returning an object\n * made up of selector results.\n *\n * @param inputSelectorsObject - A key value pair consisting of input selectors.\n * @param selectorCreator - A custom selector creator function. It defaults to `createSelector`.\n * @returns A memoized structured selector.\n *\n * @example\n * Modern Use Case\n * ```ts\n * import { createSelector, createStructuredSelector } from 'reselect'\n *\n * interface RootState {\n * todos: {\n * id: number\n * completed: boolean\n * title: string\n * description: string\n * }[]\n * alerts: { id: number; read: boolean }[]\n * }\n *\n * // This:\n * const structuredSelector = createStructuredSelector(\n * {\n * todos: (state: RootState) => state.todos,\n * alerts: (state: RootState) => state.alerts,\n * todoById: (state: RootState, id: number) => state.todos[id]\n * },\n * createSelector\n * )\n *\n * // Is essentially the same as this:\n * const selector = createSelector(\n * [\n * (state: RootState) => state.todos,\n * (state: RootState) => state.alerts,\n * (state: RootState, id: number) => state.todos[id]\n * ],\n * (todos, alerts, todoById) => {\n * return {\n * todos,\n * alerts,\n * todoById\n * }\n * }\n * )\n * ```\n *\n * @example\n * In your component:\n * ```tsx\n * import type { RootState } from 'createStructuredSelector/modernUseCase'\n * import { structuredSelector } from 'createStructuredSelector/modernUseCase'\n * import type { FC } from 'react'\n * import { useSelector } from 'react-redux'\n *\n * interface Props {\n * id: number\n * }\n *\n * const MyComponent: FC = ({ id }) => {\n * const { todos, alerts, todoById } = useSelector((state: RootState) =>\n * structuredSelector(state, id)\n * )\n *\n * return (\n *
\n * Next to do is:\n *

{todoById.title}

\n *

Description: {todoById.description}

\n *
    \n *

    All other to dos:

    \n * {todos.map(todo => (\n *
  • {todo.title}
  • \n * ))}\n *
\n *
\n * )\n * }\n * ```\n *\n * @example\n * Simple Use Case\n * ```ts\n * const selectA = state => state.a\n * const selectB = state => state.b\n *\n * // The result function in the following selector\n * // is simply building an object from the input selectors\n * const structuredSelector = createSelector(selectA, selectB, (a, b) => ({\n * a,\n * b\n * }))\n *\n * const result = structuredSelector({ a: 1, b: 2 }) // will produce { x: 1, y: 2 }\n * ```\n *\n * @template InputSelectorsObject - The shape of the input selectors object.\n * @template MemoizeFunction - The type of the memoize function that is used to create the structured selector. It defaults to `weakMapMemoize`.\n * @template ArgsMemoizeFunction - The type of the of the memoize function that is used to memoize the arguments passed into the generated structured selector. It defaults to `weakMapMemoize`.\n *\n * @see {@link https://reselect.js.org/api/createStructuredSelector `createStructuredSelector`}\n */\n <\n InputSelectorsObject extends SelectorsObject,\n MemoizeFunction extends UnknownMemoizer = typeof weakMapMemoize,\n ArgsMemoizeFunction extends UnknownMemoizer = typeof weakMapMemoize\n >(\n inputSelectorsObject: InputSelectorsObject,\n selectorCreator?: CreateSelectorFunction<\n MemoizeFunction,\n ArgsMemoizeFunction\n >\n ): OutputSelector<\n ObjectValuesToTuple,\n Simplify>,\n MemoizeFunction,\n ArgsMemoizeFunction\n > &\n InterruptRecursion\n\n /**\n * Creates a \"pre-typed\" version of\n * {@linkcode createStructuredSelector createStructuredSelector}\n * where the `state` type is predefined.\n *\n * This allows you to set the `state` type once, eliminating the need to\n * specify it with every\n * {@linkcode createStructuredSelector createStructuredSelector} call.\n *\n * @returns A pre-typed `createStructuredSelector` with the state type already defined.\n *\n * @example\n * ```ts\n * import { createStructuredSelector } from 'reselect'\n *\n * export interface RootState {\n * todos: { id: number; completed: boolean }[]\n * alerts: { id: number; read: boolean }[]\n * }\n *\n * export const createStructuredAppSelector =\n * createStructuredSelector.withTypes()\n *\n * const structuredAppSelector = createStructuredAppSelector({\n * // Type of `state` is set to `RootState`, no need to manually set the type\n * todos: state => state.todos,\n * alerts: state => state.alerts,\n * todoById: (state, id: number) => state.todos[id]\n * })\n *\n * ```\n * @template OverrideStateType - The specific type of state used by all structured selectors created with this structured selector creator.\n *\n * @see {@link https://reselect.js.org/api/createstructuredselector#defining-a-pre-typed-createstructuredselector `createSelector.withTypes`}\n *\n * @since 5.1.0\n */\n withTypes: <\n OverrideStateType extends StateType\n >() => StructuredSelectorCreator\n}\n\n/**\n * A convenience function that simplifies returning an object\n * made up of selector results.\n *\n * @param inputSelectorsObject - A key value pair consisting of input selectors.\n * @param selectorCreator - A custom selector creator function. It defaults to `createSelector`.\n * @returns A memoized structured selector.\n *\n * @example\n * Modern Use Case\n * ```ts\n * import { createSelector, createStructuredSelector } from 'reselect'\n *\n * interface RootState {\n * todos: {\n * id: number\n * completed: boolean\n * title: string\n * description: string\n * }[]\n * alerts: { id: number; read: boolean }[]\n * }\n *\n * // This:\n * const structuredSelector = createStructuredSelector(\n * {\n * todos: (state: RootState) => state.todos,\n * alerts: (state: RootState) => state.alerts,\n * todoById: (state: RootState, id: number) => state.todos[id]\n * },\n * createSelector\n * )\n *\n * // Is essentially the same as this:\n * const selector = createSelector(\n * [\n * (state: RootState) => state.todos,\n * (state: RootState) => state.alerts,\n * (state: RootState, id: number) => state.todos[id]\n * ],\n * (todos, alerts, todoById) => {\n * return {\n * todos,\n * alerts,\n * todoById\n * }\n * }\n * )\n * ```\n *\n * @see {@link https://reselect.js.org/api/createStructuredSelector `createStructuredSelector`}\n *\n * @public\n */\nexport const createStructuredSelector: StructuredSelectorCreator =\n /* @__PURE__ */ Object.assign(\n <\n InputSelectorsObject extends SelectorsObject,\n MemoizeFunction extends UnknownMemoizer = typeof weakMapMemoize,\n ArgsMemoizeFunction extends UnknownMemoizer = typeof weakMapMemoize\n >(\n inputSelectorsObject: InputSelectorsObject,\n selectorCreator: CreateSelectorFunction<\n MemoizeFunction,\n ArgsMemoizeFunction\n > = createSelector as CreateSelectorFunction<\n MemoizeFunction,\n ArgsMemoizeFunction\n >\n ) => {\n assertIsObject(\n inputSelectorsObject,\n 'createStructuredSelector expects first argument to be an object ' +\n `where each property is a selector, instead received a ${typeof inputSelectorsObject}`\n )\n const inputSelectorKeys = Object.keys(inputSelectorsObject)\n const dependencies = inputSelectorKeys.map(\n key => inputSelectorsObject[key]\n )\n const structuredSelector = selectorCreator(\n dependencies,\n (...inputSelectorResults: any[]) => {\n return inputSelectorResults.reduce((composition, value, index) => {\n composition[inputSelectorKeys[index]] = value\n return composition\n }, {})\n }\n )\n return structuredSelector\n },\n { withTypes: () => createStructuredSelector }\n ) as StructuredSelectorCreator\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ascending, descending, extent, min, rollup} from 'd3-array';\nimport {ScaleLinear, scaleSqrt} from 'd3-scale';\nimport KDBush from 'kdbush';\nimport {createSelector, createSelectorCreator, lruMemoize} from 'reselect';\nimport {alea} from 'seedrandom';\nimport FlowmapAggregateAccessors from './FlowmapAggregateAccessors';\nimport {FlowmapState} from './FlowmapState';\nimport {\n ClusterIndex,\n LocationWeightGetter,\n buildIndex,\n findAppropriateZoomLevel,\n makeLocationWeightGetter,\n} from './cluster/ClusterIndex';\nimport {clusterLocations} from './cluster/cluster';\nimport getColors, {\n ColorsRGBA,\n DiffColorsRGBA,\n getColorsRGBA,\n getDiffColorsRGBA,\n getFlowColorScale,\n isDiffColors,\n isDiffColorsRGBA,\n} from './colors';\nimport {\n addClusterNames,\n getFlowThicknessScale,\n getViewportBoundingBox,\n} from './selector-functions';\nimport {\n TimeGranularityKey,\n getTimeGranularityByKey,\n getTimeGranularityByOrder,\n getTimeGranularityForDate,\n} from './time';\nimport {\n AggregateFlow,\n Cluster,\n ClusterLevels,\n ClusterNode,\n CountByTime,\n FlowAccessors,\n FlowCirclesLayerAttributes,\n FlowLinesLayerAttributes,\n FlowLinesRenderingMode,\n FlowmapData,\n FlowmapDataAccessors,\n LayersData,\n LocationFilterMode,\n LocationTotals,\n ViewportProps,\n isLocationClusterNode,\n} from './types';\n\nconst MAX_CLUSTER_ZOOM_LEVEL = 20;\ntype KDBushTree = any;\n\nexport type Selector = (\n state: FlowmapState,\n props: FlowmapData,\n) => T;\n\nexport default class FlowmapSelectors<\n L extends Record,\n F extends Record,\n> {\n accessors: FlowmapAggregateAccessors;\n\n constructor(accessors: FlowmapDataAccessors) {\n this.accessors = new FlowmapAggregateAccessors(accessors);\n this.setAccessors(accessors);\n }\n\n setAccessors(accessors: FlowmapDataAccessors) {\n this.accessors = new FlowmapAggregateAccessors(accessors);\n }\n\n getAggregateAccessors(): FlowmapAggregateAccessors {\n return this.accessors;\n }\n\n getFlowsFromProps = (state: FlowmapState, props: FlowmapData) =>\n props.flows;\n getLocationsFromProps = (state: FlowmapState, props: FlowmapData) =>\n props.locations;\n getClusterLevelsFromProps = (\n state: FlowmapState,\n props: FlowmapData,\n ) => {\n return props.clusterLevels;\n };\n getMaxTopFlowsDisplayNum = (state: FlowmapState, props: FlowmapData) =>\n state.settings.maxTopFlowsDisplayNum;\n getFlowEndpointsInViewportMode = (\n state: FlowmapState,\n props: FlowmapData,\n ) => state.settings.flowEndpointsInViewportMode;\n getSelectedLocations = (state: FlowmapState, props: FlowmapData) =>\n state.filter?.selectedLocations;\n getLocationFilterMode = (state: FlowmapState, props: FlowmapData) =>\n state.filter?.locationFilterMode;\n getClusteringEnabled = (state: FlowmapState, props: FlowmapData) =>\n state.settings.clusteringEnabled;\n getLocationTotalsEnabled = (state: FlowmapState, props: FlowmapData) =>\n state.settings.locationTotalsEnabled;\n getLocationLabelsEnabled = (state: FlowmapState, props: FlowmapData) =>\n state.settings.locationLabelsEnabled;\n getZoom = (state: FlowmapState, props: FlowmapData) =>\n state.viewport.zoom;\n getViewport = (state: FlowmapState, props: FlowmapData) =>\n state.viewport;\n getSelectedTimeRange = (state: FlowmapState, props: FlowmapData) =>\n state.filter?.selectedTimeRange;\n\n getColorScheme: Selector = (\n state: FlowmapState,\n props: FlowmapData,\n ) => state.settings.colorScheme;\n\n getDarkMode: Selector = (\n state: FlowmapState,\n props: FlowmapData,\n ) => state.settings.darkMode;\n\n getFadeEnabled: Selector = (\n state: FlowmapState,\n props: FlowmapData,\n ) => state.settings.fadeEnabled;\n\n getFadeOpacityEnabled: Selector = (\n state: FlowmapState,\n props: FlowmapData,\n ) => state.settings.fadeOpacityEnabled;\n\n getFadeAmount: Selector = (\n state: FlowmapState,\n props: FlowmapData,\n ) => state.settings.fadeAmount;\n\n getFlowLinesRenderingMode: Selector = (\n state: FlowmapState,\n props: FlowmapData,\n ) => state.settings.flowLinesRenderingMode;\n\n getAnimate: Selector = createSelector(\n this.getFlowLinesRenderingMode,\n (flowLinesRenderingMode) => flowLinesRenderingMode === 'animated-straight',\n );\n\n getInvalidLocationIds: Selector =\n createSelector(this.getLocationsFromProps, (locations) => {\n if (!locations) return undefined;\n const invalid = [];\n for (const location of locations) {\n const id = this.accessors.getLocationId(location);\n const lon = this.accessors.getLocationLon(location);\n const lat = this.accessors.getLocationLat(location);\n if (!(-90 <= lat && lat <= 90) || !(-180 <= lon && lon <= 180)) {\n invalid.push(id);\n }\n }\n return invalid.length > 0 ? invalid : undefined;\n });\n\n getLocations: Selector | undefined> = createSelector(\n this.getLocationsFromProps,\n this.getInvalidLocationIds,\n (locations, invalidIds) => {\n if (!locations) return undefined;\n if (!invalidIds || invalidIds.length === 0) return locations;\n const invalid = new Set(invalidIds);\n const filtered: L[] = [];\n for (const location of locations) {\n const id = this.accessors.getLocationId(location);\n if (!invalid.has(id)) {\n filtered.push(location);\n }\n }\n return filtered;\n },\n );\n\n getLocationIds: Selector | undefined> =\n createSelector(this.getLocations, (locations) => {\n if (!locations) return undefined;\n const ids = new Set();\n for (const id of locations) {\n ids.add(this.accessors.getLocationId(id));\n }\n return ids;\n });\n\n getSelectedLocationsSet: Selector | undefined> =\n createSelector(this.getSelectedLocations, (ids) =>\n ids && ids.length > 0 ? new Set(ids) : undefined,\n );\n\n getSortedFlowsForKnownLocations: Selector =\n createSelector(\n this.getFlowsFromProps,\n this.getLocationIds,\n (flows, ids) => {\n if (!ids || !flows) return undefined;\n const filtered = [];\n for (const flow of flows) {\n const srcId = this.accessors.getFlowOriginId(flow);\n const dstId = this.accessors.getFlowDestId(flow);\n if (ids.has(srcId) && ids.has(dstId)) {\n filtered.push(flow);\n }\n }\n return filtered.sort((a: F, b: F) =>\n descending(\n Math.abs(this.accessors.getFlowMagnitude(a)),\n Math.abs(this.accessors.getFlowMagnitude(b)),\n ),\n );\n },\n );\n\n getActualTimeExtent: Selector =\n createSelector(this.getSortedFlowsForKnownLocations, (flows) => {\n if (!flows) return undefined;\n let start = null;\n let end = null;\n for (const flow of flows) {\n const time = this.accessors.getFlowTime(flow);\n if (time) {\n if (start == null || start > time) start = time;\n if (end == null || end < time) end = time;\n }\n }\n if (!start || !end) return undefined;\n return [start, end];\n });\n\n getTimeGranularityKey: Selector =\n createSelector(\n this.getSortedFlowsForKnownLocations,\n this.getActualTimeExtent,\n (flows, timeExtent) => {\n if (!flows || !timeExtent) return undefined;\n\n const minOrder = min(flows, (d: F) => {\n const t = this.accessors.getFlowTime(d);\n return t ? getTimeGranularityForDate(t).order : null;\n });\n if (minOrder == null) return undefined;\n const timeGranularity = getTimeGranularityByOrder(minOrder);\n return timeGranularity ? timeGranularity.key : undefined;\n },\n );\n\n getTimeExtent: Selector = createSelector(\n this.getActualTimeExtent,\n this.getTimeGranularityKey,\n (timeExtent, timeGranularityKey) => {\n const timeGranularity = timeGranularityKey\n ? getTimeGranularityByKey(timeGranularityKey)\n : undefined;\n if (!timeExtent || !timeGranularity?.interval) return undefined;\n const {interval} = timeGranularity;\n return [timeExtent[0], interval.offset(interval.floor(timeExtent[1]), 1)];\n },\n );\n\n getSortedFlowsForKnownLocationsFilteredByTime: Selector<\n L,\n F,\n F[] | undefined\n > = createSelector(\n this.getSortedFlowsForKnownLocations,\n this.getTimeExtent,\n this.getSelectedTimeRange,\n (flows, timeExtent, timeRange) => {\n if (!flows) return undefined;\n if (\n !timeExtent ||\n !timeRange ||\n (timeExtent[0] === timeRange[0] && timeExtent[1] === timeRange[1])\n ) {\n return flows;\n }\n return flows.filter((flow: F) => {\n const time = this.accessors.getFlowTime(flow);\n return time && timeRange[0] <= time && time < timeRange[1];\n });\n },\n );\n\n getLocationsHavingFlows: Selector | undefined> =\n createSelector(\n this.getSortedFlowsForKnownLocations,\n this.getLocations,\n (flows, locations) => {\n if (!locations || !flows) return locations;\n const withFlows = new Set();\n for (const flow of flows) {\n withFlows.add(this.accessors.getFlowOriginId(flow));\n withFlows.add(this.accessors.getFlowDestId(flow));\n }\n const filtered = [];\n for (const location of locations) {\n if (withFlows.has(this.accessors.getLocationId(location))) {\n filtered.push(location);\n }\n }\n return filtered;\n },\n );\n\n getLocationsById: Selector | undefined> =\n createSelector(this.getLocationsHavingFlows, (locations) => {\n if (!locations) return undefined;\n const locationsById = new Map();\n for (const location of locations) {\n locationsById.set(this.accessors.getLocationId(location), location);\n }\n return locationsById;\n });\n\n getLocationWeightGetter: Selector =\n createSelector(this.getSortedFlowsForKnownLocations, (flows) => {\n if (!flows) return undefined;\n const getLocationWeight = makeLocationWeightGetter(\n flows,\n this.accessors.getFlowmapDataAccessors(),\n );\n return getLocationWeight;\n });\n\n getClusterLevels: Selector = createSelector(\n this.getClusterLevelsFromProps,\n this.getLocationsHavingFlows,\n this.getLocationWeightGetter,\n (clusterLevelsFromProps, locations, getLocationWeight) => {\n if (clusterLevelsFromProps) return clusterLevelsFromProps;\n if (!locations || !getLocationWeight) return undefined;\n const clusterLevels = clusterLocations(\n locations,\n this.accessors.getFlowmapDataAccessors(),\n getLocationWeight,\n {\n maxZoom: MAX_CLUSTER_ZOOM_LEVEL,\n },\n );\n return clusterLevels;\n },\n );\n\n getClusterIndex: Selector | undefined> = createSelector(\n this.getLocationsById,\n this.getLocationWeightGetter,\n this.getClusterLevels,\n (locationsById, getLocationWeight, clusterLevels) => {\n if (!locationsById || !getLocationWeight || !clusterLevels)\n return undefined;\n\n const clusterIndex = buildIndex(clusterLevels);\n // Adding meaningful names\n addClusterNames(\n clusterIndex,\n clusterLevels,\n locationsById,\n this.accessors.getFlowmapDataAccessors(),\n getLocationWeight,\n );\n return clusterIndex;\n },\n );\n\n getAvailableClusterZoomLevels = createSelector(\n this.getClusterIndex,\n this.getSelectedLocations,\n (clusterIndex, selectedLocations): number[] | undefined => {\n if (!clusterIndex) {\n return undefined;\n }\n\n let maxZoom = Number.POSITIVE_INFINITY;\n let minZoom = Number.NEGATIVE_INFINITY;\n\n const adjust = (zoneId: string | number) => {\n const cluster = clusterIndex.getClusterById(zoneId);\n if (cluster) {\n minZoom = Math.max(minZoom, cluster.zoom);\n maxZoom = Math.min(maxZoom, cluster.zoom);\n } else {\n const zoom = clusterIndex.getMinZoomForLocation(zoneId);\n minZoom = Math.max(minZoom, zoom);\n }\n };\n\n if (selectedLocations) {\n for (const id of selectedLocations) {\n adjust(id);\n }\n }\n\n return clusterIndex.availableZoomLevels.filter(\n (level: number) => minZoom <= level && level <= maxZoom,\n );\n },\n );\n\n _getClusterZoom: Selector = createSelector(\n this.getClusterIndex,\n this.getZoom,\n this.getAvailableClusterZoomLevels,\n (clusterIndex, mapZoom, availableClusterZoomLevels) => {\n if (!clusterIndex) return undefined;\n if (!availableClusterZoomLevels || mapZoom == null) {\n return undefined;\n }\n\n const clusterZoom = findAppropriateZoomLevel(\n availableClusterZoomLevels,\n mapZoom,\n );\n return clusterZoom;\n },\n );\n\n getClusterZoom = (state: FlowmapState, props: FlowmapData) => {\n const {settings} = state;\n if (!settings.clusteringEnabled) return undefined;\n if (settings.clusteringAuto || settings.clusteringLevel == null) {\n return this._getClusterZoom(state, props);\n }\n return settings.clusteringLevel;\n };\n\n getLocationsForSearchBox: Selector =\n createSelector(\n this.getClusteringEnabled,\n this.getLocationsHavingFlows,\n this.getSelectedLocations,\n this.getClusterZoom,\n this.getClusterIndex,\n (\n clusteringEnabled,\n locations,\n selectedLocations,\n clusterZoom,\n clusterIndex,\n ) => {\n if (!locations) return undefined;\n let result: (L | Cluster)[] = Array.from(locations);\n // if (clusteringEnabled) {\n // if (clusterIndex) {\n // const zoomItems = clusterIndex.getClusterNodesFor(clusterZoom);\n // if (zoomItems) {\n // result = result.concat(zoomItems.filter(isCluster));\n // }\n // }\n // }\n\n if (clusterIndex && selectedLocations) {\n const toAppend = [];\n for (const id of selectedLocations) {\n const cluster = clusterIndex.getClusterById(id);\n if (\n cluster &&\n !result.find(\n (d) =>\n (isLocationClusterNode(d)\n ? d.id\n : this.accessors.getLocationId(d)) === id,\n )\n ) {\n toAppend.push(cluster);\n }\n }\n if (toAppend.length > 0) {\n result = result.concat(toAppend);\n }\n }\n return result;\n },\n );\n\n getDiffMode: Selector = createSelector(\n this.getFlowsFromProps,\n (flows) => {\n if (flows) {\n for (const f of flows) {\n if (this.accessors.getFlowMagnitude(f) < 0) {\n return true;\n }\n }\n }\n return false;\n },\n );\n\n _getFlowmapColors = createSelector(\n this.getDiffMode,\n this.getColorScheme,\n this.getDarkMode,\n this.getFadeEnabled,\n this.getFadeOpacityEnabled,\n this.getFadeAmount,\n this.getAnimate,\n getColors,\n );\n\n getFlowmapColorsRGBA = createSelector(\n this._getFlowmapColors,\n (flowmapColors) => {\n return isDiffColors(flowmapColors)\n ? getDiffColorsRGBA(flowmapColors)\n : getColorsRGBA(flowmapColors);\n },\n );\n\n getUnknownLocations: Selector | undefined> =\n createSelector(\n this.getLocationIds,\n this.getFlowsFromProps,\n this.getSortedFlowsForKnownLocations,\n (ids, flows, flowsForKnownLocations) => {\n if (!ids || !flows) return undefined;\n if (\n flowsForKnownLocations\n // && flows.length === flowsForKnownLocations.length\n )\n return undefined;\n const missing = new Set();\n for (const flow of flows) {\n if (!ids.has(this.accessors.getFlowOriginId(flow)))\n missing.add(this.accessors.getFlowOriginId(flow));\n if (!ids.has(this.accessors.getFlowDestId(flow)))\n missing.add(this.accessors.getFlowDestId(flow));\n }\n return missing;\n },\n );\n\n getSortedAggregatedFilteredFlows: Selector<\n L,\n F,\n (F | AggregateFlow)[] | undefined\n > = createSelector(\n this.getClusterIndex,\n this.getClusteringEnabled,\n this.getSortedFlowsForKnownLocationsFilteredByTime,\n this.getClusterZoom,\n this.getTimeExtent,\n (clusterTree, isClusteringEnabled, flows, clusterZoom, timeExtent) => {\n if (!flows) return undefined;\n let aggregated: (F | AggregateFlow)[];\n if (isClusteringEnabled && clusterTree && clusterZoom != null) {\n aggregated = clusterTree.aggregateFlows(\n // TODO: aggregate across time\n // timeExtent != null\n // ? aggregateFlows(flows) // clusterTree.aggregateFlows won't aggregate unclustered across time\n // : flows,\n flows,\n clusterZoom,\n this.accessors.getFlowmapDataAccessors(),\n );\n } else {\n aggregated = aggregateFlows(\n flows,\n this.accessors.getFlowmapDataAccessors(),\n );\n }\n aggregated.sort((a, b) =>\n descending(\n Math.abs(this.accessors.getFlowMagnitude(a)),\n Math.abs(this.accessors.getFlowMagnitude(b)),\n ),\n );\n return aggregated;\n },\n );\n\n getExpandedSelectedLocationsSet: Selector<\n L,\n F,\n Set | undefined\n > = createSelector(\n this.getClusteringEnabled,\n this.getSelectedLocationsSet,\n this.getClusterIndex,\n (clusteringEnabled, selectedLocations, clusterIndex) => {\n if (!selectedLocations || !clusterIndex) {\n return selectedLocations;\n }\n\n const result = new Set();\n for (const locationId of selectedLocations) {\n const cluster = clusterIndex.getClusterById(locationId);\n if (cluster) {\n const expanded = clusterIndex.expandCluster(cluster);\n for (const id of expanded) {\n result.add(id);\n }\n } else {\n result.add(locationId);\n }\n }\n return result;\n },\n );\n\n getTotalCountsByTime: Selector =\n createSelector(\n this.getSortedFlowsForKnownLocations,\n this.getTimeGranularityKey,\n this.getTimeExtent,\n this.getExpandedSelectedLocationsSet,\n this.getLocationFilterMode,\n (\n flows,\n timeGranularityKey,\n timeExtent,\n selectedLocationSet,\n locationFilterMode,\n ) => {\n const timeGranularity = timeGranularityKey\n ? getTimeGranularityByKey(timeGranularityKey)\n : undefined;\n if (!flows || !timeGranularity || !timeExtent) return undefined;\n const byTime = flows.reduce((m: Map, flow: F) => {\n if (\n this.isFlowInSelection(\n flow,\n selectedLocationSet,\n locationFilterMode,\n )\n ) {\n const key = timeGranularity\n .interval(this.accessors.getFlowTime(flow))\n .getTime();\n m.set(\n key,\n (m.get(key) ?? 0) + this.accessors.getFlowMagnitude(flow),\n );\n }\n return m;\n }, new Map());\n\n return Array.from(byTime.entries()).map(\n ([millis, count]: [number, number]) => ({\n time: new Date(millis),\n count,\n }),\n );\n },\n );\n\n getMaxLocationCircleSize: Selector = createSelector(\n this.getLocationTotalsEnabled,\n (locationTotalsEnabled) => (locationTotalsEnabled ? 17 : 1),\n );\n\n getViewportBoundingBox: Selector =\n createSelector(\n this.getViewport,\n this.getMaxLocationCircleSize,\n getViewportBoundingBox,\n );\n\n getLocationsForZoom: Selector | ClusterNode[] | undefined> =\n createSelector(\n this.getClusteringEnabled,\n this.getLocationsHavingFlows,\n this.getClusterIndex,\n this.getClusterZoom,\n (clusteringEnabled, locationsHavingFlows, clusterIndex, clusterZoom) => {\n if (clusteringEnabled && clusterIndex) {\n return clusterIndex.getClusterNodesFor(clusterZoom);\n } else {\n return locationsHavingFlows;\n }\n },\n );\n\n getLocationTotals: Selector<\n L,\n F,\n Map | undefined\n > = createSelector(\n this.getLocationsForZoom,\n this.getSortedAggregatedFilteredFlows,\n this.getSelectedLocationsSet,\n this.getLocationFilterMode,\n (locations, flows, selectedLocationsSet, locationFilterMode) => {\n if (!flows) return undefined;\n const totals = new Map();\n const add = (\n id: string | number,\n d: Partial,\n ): LocationTotals => {\n const rv = totals.get(id) ?? {\n incomingCount: 0,\n outgoingCount: 0,\n internalCount: 0,\n };\n if (d.incomingCount != null) rv.incomingCount += d.incomingCount;\n if (d.outgoingCount != null) rv.outgoingCount += d.outgoingCount;\n if (d.internalCount != null) rv.internalCount += d.internalCount;\n return rv;\n };\n for (const f of flows) {\n if (\n this.isFlowInSelection(f, selectedLocationsSet, locationFilterMode)\n ) {\n const originId = this.accessors.getFlowOriginId(f);\n const destId = this.accessors.getFlowDestId(f);\n const count = this.accessors.getFlowMagnitude(f);\n if (originId === destId) {\n totals.set(originId, add(originId, {internalCount: count}));\n } else {\n totals.set(originId, add(originId, {outgoingCount: count}));\n totals.set(destId, add(destId, {incomingCount: count}));\n }\n }\n }\n return totals;\n },\n );\n\n getLocationsTree: Selector = createSelector(\n this.getLocationsForZoom,\n (locations) => {\n if (!locations) {\n return undefined;\n }\n const nodes = Array.isArray(locations)\n ? locations\n : Array.from(locations);\n const bush = new KDBush(nodes.length, 64, Float32Array);\n for (let i = 0; i < nodes.length; i++) {\n const node = nodes[i];\n bush.add(\n lngX(this.accessors.getLocationLon(node)),\n latY(this.accessors.getLocationLat(node)),\n );\n }\n bush.finish();\n bush.points = nodes;\n return bush;\n },\n );\n\n _getLocationIdsInViewport: Selector | undefined> =\n createSelector(\n this.getLocationsTree,\n this.getViewportBoundingBox,\n (tree: KDBushTree, bbox: [number, number, number, number]) => {\n const ids = this._getLocationsInBboxIndices(tree, bbox);\n if (ids) {\n return new Set(\n ids.map((idx: number) =>\n this.accessors.getLocationId(tree.points[idx]),\n ) as Array,\n );\n }\n return undefined;\n },\n );\n\n getLocationIdsInViewport: Selector | undefined> =\n createSelectorCreator({\n memoize: lruMemoize,\n memoizeOptions: {\n equalityCheck: (\n s1: Set | undefined,\n s2: Set | undefined,\n ) => {\n if (s1 === s2) return true;\n if (s1 == null || s2 == null) return false;\n if (s1.size !== s2.size) return false;\n for (const item of s1) if (!s2.has(item)) return false;\n return true;\n },\n },\n })(\n this._getLocationIdsInViewport,\n (locationIds: Set | undefined) => {\n if (!locationIds) return undefined;\n return locationIds;\n },\n );\n\n getTotalUnfilteredCount: Selector = createSelector(\n this.getSortedFlowsForKnownLocations,\n (flows) => {\n if (!flows) return undefined;\n return flows.reduce(\n (m: number, flow: F) => m + this.accessors.getFlowMagnitude(flow),\n 0,\n );\n },\n );\n\n getTotalFilteredCount: Selector = createSelector(\n this.getSortedAggregatedFilteredFlows,\n this.getSelectedLocationsSet,\n this.getLocationFilterMode,\n (flows, selectedLocationSet, locationFilterMode) => {\n if (!flows) return undefined;\n const count = flows.reduce((m: number, flow: F | AggregateFlow) => {\n if (\n this.isFlowInSelection(flow, selectedLocationSet, locationFilterMode)\n ) {\n return m + this.accessors.getFlowMagnitude(flow);\n }\n return m;\n }, 0);\n return count;\n },\n );\n\n _getLocationTotalsExtent: Selector =\n createSelector(this.getLocationTotals, (locationTotals) =>\n calcLocationTotalsExtent(locationTotals, undefined),\n );\n\n _getLocationTotalsForViewportExtent: Selector<\n L,\n F,\n [number, number] | undefined\n > = createSelector(\n this.getLocationTotals,\n this.getLocationIdsInViewport,\n (locationTotals, locationsInViewport) =>\n calcLocationTotalsExtent(locationTotals, locationsInViewport),\n );\n\n getLocationTotalsExtent = (\n state: FlowmapState,\n props: FlowmapData,\n ): [number, number] | undefined => {\n if (state.settings.adaptiveScalesEnabled) {\n return this._getLocationTotalsForViewportExtent(state, props);\n } else {\n return this._getLocationTotalsExtent(state, props);\n }\n };\n\n getFlowsForFlowmapLayer: Selector =\n createSelector(\n this.getSortedAggregatedFilteredFlows,\n this.getLocationIdsInViewport,\n this.getSelectedLocationsSet,\n this.getLocationFilterMode,\n this.getMaxTopFlowsDisplayNum,\n this.getFlowEndpointsInViewportMode,\n (\n flows,\n locationIdsInViewport,\n selectedLocationsSet,\n locationFilterMode,\n maxTopFlowsDisplayNum,\n flowEndpointsInViewportMode,\n ) => {\n if (!flows || !locationIdsInViewport) return undefined;\n const picked: (F | AggregateFlow)[] = [];\n let pickedCount = 0;\n for (const flow of flows) {\n const origin = this.accessors.getFlowOriginId(flow);\n const dest = this.accessors.getFlowDestId(flow);\n const originInView = locationIdsInViewport.has(origin);\n const destInView = locationIdsInViewport.has(dest);\n const isInViewport =\n flowEndpointsInViewportMode === 'both'\n ? originInView && destInView\n : originInView || destInView;\n if (isInViewport) {\n if (\n this.isFlowInSelection(\n flow,\n selectedLocationsSet,\n locationFilterMode,\n )\n ) {\n if (origin !== dest) {\n // exclude self-loops\n picked.push(flow);\n pickedCount++;\n }\n }\n }\n // Only keep top\n if (pickedCount > maxTopFlowsDisplayNum) break;\n }\n // assuming they are sorted in descending order,\n // we need ascending for rendering\n return picked.reverse();\n },\n );\n\n _getFlowMagnitudeExtent: Selector =\n createSelector(\n this.getSortedAggregatedFilteredFlows,\n this.getSelectedLocationsSet,\n this.getLocationFilterMode,\n (flows, selectedLocationsSet, locationFilterMode) => {\n if (!flows) return undefined;\n let rv: [number, number] | undefined = undefined;\n for (const f of flows) {\n if (\n this.accessors.getFlowOriginId(f) !==\n this.accessors.getFlowDestId(f) &&\n this.isFlowInSelection(f, selectedLocationsSet, locationFilterMode)\n ) {\n const count = this.accessors.getFlowMagnitude(f);\n if (rv == null) {\n rv = [count, count];\n } else {\n if (count < rv[0]) rv[0] = count;\n if (count > rv[1]) rv[1] = count;\n }\n }\n }\n return rv;\n },\n );\n\n _getAdaptiveFlowMagnitudeExtent: Selector<\n L,\n F,\n [number, number] | undefined\n > = createSelector(this.getFlowsForFlowmapLayer, (flows) => {\n if (!flows) return undefined;\n const rv = extent(flows, this.accessors.getFlowMagnitude);\n return rv[0] !== undefined && rv[1] !== undefined ? rv : undefined;\n });\n\n getFlowMagnitudeExtent = (\n state: FlowmapState,\n props: FlowmapData,\n ): [number, number] | undefined => {\n if (state.settings.adaptiveScalesEnabled) {\n return this._getAdaptiveFlowMagnitudeExtent(state, props);\n } else {\n return this._getFlowMagnitudeExtent(state, props);\n }\n };\n\n getLocationMaxAbsTotalGetter = createSelector(\n this.getLocationTotals,\n (locationTotals) => {\n return (locationId: string) => {\n const total = locationTotals?.get(locationId);\n if (!total) return undefined;\n return Math.max(\n Math.abs(total.incomingCount + total.internalCount),\n Math.abs(total.outgoingCount + total.internalCount),\n );\n };\n },\n );\n\n getFlowThicknessScale = createSelector(\n this.getFlowMagnitudeExtent,\n getFlowThicknessScale,\n );\n\n getCircleSizeScale = createSelector(\n this.getMaxLocationCircleSize,\n this.getLocationTotalsEnabled,\n this.getLocationTotalsExtent,\n (maxLocationCircleSize, locationTotalsEnabled, locationTotalsExtent) => {\n if (!locationTotalsEnabled) {\n return () => maxLocationCircleSize;\n }\n if (!locationTotalsExtent) return undefined;\n return scaleSqrt()\n .range([0, maxLocationCircleSize])\n .domain([\n 0,\n // should support diff mode too\n Math.max.apply(\n null,\n locationTotalsExtent.map((x: number | undefined) =>\n Math.abs(x || 0),\n ),\n ),\n ]);\n },\n );\n\n getInCircleSizeGetter = createSelector(\n this.getCircleSizeScale,\n this.getLocationTotals,\n (circleSizeScale, locationTotals) => {\n return (locationId: string | number) => {\n const total = locationTotals?.get(locationId);\n if (total && circleSizeScale) {\n return (\n circleSizeScale(\n Math.abs(total.incomingCount + total.internalCount),\n ) || 0\n );\n }\n return 0;\n };\n },\n );\n\n getOutCircleSizeGetter = createSelector(\n this.getCircleSizeScale,\n this.getLocationTotals,\n (circleSizeScale, locationTotals) => {\n return (locationId: string | number) => {\n const total = locationTotals?.get(locationId);\n if (total && circleSizeScale) {\n return (\n circleSizeScale(\n Math.abs(total.outgoingCount + total.internalCount),\n ) || 0\n );\n }\n return 0;\n };\n },\n );\n\n getSortedLocationsForZoom: Selector =\n createSelector(\n this.getLocationsForZoom,\n this.getInCircleSizeGetter,\n this.getOutCircleSizeGetter,\n (locations, getInCircleSize, getOutCircleSize) => {\n if (!locations) return undefined;\n const nextLocations = [...locations] as L[] | ClusterNode[];\n return nextLocations.sort((a, b) => {\n const idA = this.accessors.getLocationId(a);\n const idB = this.accessors.getLocationId(b);\n return ascending(\n Math.max(getInCircleSize(idA), getOutCircleSize(idA)),\n Math.max(getInCircleSize(idB), getOutCircleSize(idB)),\n );\n });\n },\n );\n\n getLocationsForFlowmapLayer: Selector<\n L,\n F,\n Array | undefined\n > = createSelector(\n this.getSortedLocationsForZoom,\n // this.getLocationIdsInViewport,\n (\n locations,\n // locationIdsInViewport\n ) => {\n // if (!locations) return undefined;\n // if (!locationIdsInViewport) return locations;\n // if (locationIdsInViewport.size === locations.length) return locations;\n // const filtered = [];\n // for (const loc of locations) {\n // if (locationIdsInViewport.has(loc.id)) {\n // filtered.push(loc);\n // }\n // }\n // return filtered;\n // @ts-ignore\n // return locations.filter(\n // (loc: L | ClusterNode) => locationIdsInViewport!.has(loc.id)\n // );\n // TODO: return location in viewport + \"connected\" ones\n return locations;\n },\n );\n\n getLocationsForFlowmapLayerById: Selector<\n L,\n F,\n Map | undefined\n > = createSelector(this.getLocationsForFlowmapLayer, (locations) => {\n if (!locations) return undefined;\n return locations.reduce(\n (m: Map, d: L | ClusterNode) => (\n m.set(this.accessors.getLocationId(d), d),\n m\n ),\n new Map(),\n );\n });\n\n getLocationOrClusterByIdGetter = createSelector(\n this.getClusterIndex,\n this.getLocationsById,\n (clusterIndex, locationsById) => {\n return (id: string | number) =>\n clusterIndex?.getClusterById(id) ?? locationsById?.get(id);\n },\n );\n\n getLayersData: Selector = createSelector(\n this.getLocationsForFlowmapLayer,\n this.getFlowsForFlowmapLayer,\n this.getFlowmapColorsRGBA,\n this.getLocationsForFlowmapLayerById,\n this.getLocationIdsInViewport,\n this.getInCircleSizeGetter,\n this.getOutCircleSizeGetter,\n this.getFlowThicknessScale,\n this.getViewport,\n this.getFlowLinesRenderingMode,\n this.getLocationLabelsEnabled,\n (\n locations,\n flows,\n flowmapColors,\n locationsById,\n locationIdsInViewport,\n getInCircleSize,\n getOutCircleSize,\n flowThicknessScale,\n viewport,\n flowLinesRenderingMode,\n locationLabelsEnabled,\n ) => {\n return this._prepareLayersData(\n locations,\n flows,\n flowmapColors,\n locationsById,\n locationIdsInViewport,\n getInCircleSize,\n getOutCircleSize,\n flowThicknessScale,\n viewport,\n flowLinesRenderingMode,\n locationLabelsEnabled,\n );\n },\n );\n\n prepareLayersData(state: FlowmapState, props: FlowmapData): LayersData {\n const locations = this.getLocationsForFlowmapLayer(state, props) || [];\n const flows = this.getFlowsForFlowmapLayer(state, props) || [];\n const flowmapColors = (\n this.getFlowmapColorsRGBA as Selector\n )(state, props);\n const locationsById = this.getLocationsForFlowmapLayerById(state, props);\n const locationIdsInViewport = this.getLocationIdsInViewport(state, props);\n const getInCircleSize = this.getInCircleSizeGetter(state, props);\n const getOutCircleSize = this.getOutCircleSizeGetter(state, props);\n const flowThicknessScale = this.getFlowThicknessScale(state, props);\n const locationLabelsEnabled = this.getLocationLabelsEnabled(state, props);\n const viewport = this.getViewport(state, props);\n return this._prepareLayersData(\n locations,\n flows,\n flowmapColors,\n locationsById,\n locationIdsInViewport,\n getInCircleSize,\n getOutCircleSize,\n flowThicknessScale,\n viewport,\n state.settings.flowLinesRenderingMode,\n locationLabelsEnabled,\n );\n }\n\n _prepareLayersData(\n locations: (L | ClusterNode)[] | undefined,\n flows: (F | AggregateFlow)[] | undefined,\n flowmapColors: DiffColorsRGBA | ColorsRGBA,\n locationsById: Map | undefined,\n locationIdsInViewport: Set | undefined,\n getInCircleSize: (locationId: string | number) => number,\n getOutCircleSize: (locationId: string | number) => number,\n flowThicknessScale: ScaleLinear | undefined,\n viewport: ViewportProps,\n flowLinesRenderingMode: FlowLinesRenderingMode,\n locationLabelsEnabled: boolean,\n ): LayersData {\n if (!locations) locations = [];\n if (!flows) flows = [];\n const {\n getFlowOriginId,\n getFlowDestId,\n getFlowMagnitude,\n getLocationId,\n getLocationLon,\n getLocationLat,\n getLocationName,\n } = this.accessors;\n\n const flowMagnitudeExtent = extent(flows, (f) => getFlowMagnitude(f)) as [\n number,\n number,\n ];\n const flowColorScale = getFlowColorScale(\n flowmapColors,\n flowMagnitudeExtent,\n flowLinesRenderingMode === 'animated-straight',\n );\n\n // Using a generator here helps to avoid creating intermediary arrays\n const circlePositions = Float64Array.from(\n (function* () {\n for (const location of locations) {\n yield getLocationLon(location);\n yield getLocationLat(location);\n yield 0;\n }\n })(),\n );\n\n // TODO: diff mode\n const circleColor = isDiffColorsRGBA(flowmapColors)\n ? flowmapColors.positive.locationCircles.inner\n : flowmapColors.locationCircles.inner;\n\n const circleColors = Uint8Array.from(\n (function* () {\n for (const location of locations) {\n yield* circleColor;\n }\n })(),\n );\n\n const inCircleRadii = Float32Array.from(\n (function* () {\n for (const location of locations) {\n const id = getLocationId(location);\n yield locationIdsInViewport?.has(id) ? getInCircleSize(id) : 1.0;\n }\n })(),\n );\n const outCircleRadii = Float32Array.from(\n (function* () {\n for (const location of locations) {\n const id = getLocationId(location);\n yield locationIdsInViewport?.has(id) ? getOutCircleSize(id) : 1.0;\n }\n })(),\n );\n\n const sourcePositions = Float64Array.from(\n (function* () {\n for (const flow of flows) {\n const loc = locationsById?.get(getFlowOriginId(flow));\n yield loc ? getLocationLon(loc) : 0;\n yield loc ? getLocationLat(loc) : 0;\n yield 0;\n }\n })(),\n );\n const targetPositions = Float64Array.from(\n (function* () {\n for (const flow of flows) {\n const loc = locationsById?.get(getFlowDestId(flow));\n yield loc ? getLocationLon(loc) : 0;\n yield loc ? getLocationLat(loc) : 0;\n yield 0;\n }\n })(),\n );\n const thicknesses = Float32Array.from(\n (function* () {\n for (const flow of flows) {\n yield flowThicknessScale\n ? flowThicknessScale(getFlowMagnitude(flow)) || 0\n : 0;\n }\n })(),\n );\n const endpointOffsets = Float32Array.from(\n (function* () {\n for (const flow of flows) {\n const originId = getFlowOriginId(flow);\n const destId = getFlowDestId(flow);\n yield Math.max(getInCircleSize(originId), getOutCircleSize(originId));\n yield Math.max(getInCircleSize(destId), getOutCircleSize(destId));\n }\n })(),\n );\n const flowLineColors = Uint8Array.from(\n (function* () {\n for (const flow of flows) {\n yield* flowColorScale(getFlowMagnitude(flow));\n }\n })(),\n );\n\n const staggeringValues =\n flowLinesRenderingMode === 'animated-straight'\n ? Float32Array.from(\n (function* () {\n for (const f of flows) {\n // @ts-ignore\n yield new alea(`${getFlowOriginId(f)}-${getFlowDestId(f)}`)();\n }\n })(),\n )\n : undefined;\n\n const curveOffsets =\n flowLinesRenderingMode === 'curved'\n ? calculateCurveOffsets(\n flows,\n viewport,\n locationsById,\n getFlowOriginId,\n getFlowDestId,\n getLocationLon,\n getLocationLat,\n )\n : undefined;\n\n return {\n circleAttributes: {\n length: locations.length,\n attributes: {\n getPosition: {value: circlePositions, size: 3},\n getColor: {value: circleColors, size: 4},\n getInRadius: {value: inCircleRadii, size: 1},\n getOutRadius: {value: outCircleRadii, size: 1},\n },\n },\n lineAttributes: {\n length: flows.length,\n attributes: {\n getSourcePosition: {value: sourcePositions, size: 3},\n getTargetPosition: {value: targetPositions, size: 3},\n getThickness: {value: thicknesses, size: 1},\n getColor: {value: flowLineColors, size: 4},\n getEndpointOffsets: {value: endpointOffsets, size: 2},\n ...(staggeringValues\n ? {getStaggering: {value: staggeringValues, size: 1}}\n : {}),\n ...(curveOffsets\n ? {getCurveOffset: {value: curveOffsets, size: 1}}\n : {}),\n },\n },\n ...(locationLabelsEnabled\n ? {locationLabels: locations.map(getLocationName)}\n : undefined),\n };\n }\n\n getLocationsInBbox(\n tree: KDBushTree,\n bbox: [number, number, number, number],\n ): Array | undefined {\n if (!tree) return undefined;\n return this._getLocationsInBboxIndices(tree, bbox).map(\n (idx: number) => tree.points[idx],\n ) as Array;\n }\n\n _getLocationsInBboxIndices(\n tree: KDBushTree,\n bbox: [number, number, number, number],\n ) {\n if (!tree) return undefined;\n const [lon1, lat1, lon2, lat2] = bbox;\n const [x1, y1, x2, y2] = [lngX(lon1), latY(lat1), lngX(lon2), latY(lat2)];\n return tree.range(\n Math.min(x1, x2),\n Math.min(y1, y2),\n Math.max(x1, x2),\n Math.max(y1, y2),\n );\n }\n\n isFlowInSelection(\n flow: F | AggregateFlow,\n selectedLocationsSet: Set | undefined,\n locationFilterMode?: LocationFilterMode,\n ) {\n const origin = this.accessors.getFlowOriginId(flow);\n const dest = this.accessors.getFlowDestId(flow);\n if (selectedLocationsSet) {\n switch (locationFilterMode) {\n case LocationFilterMode.ALL:\n return (\n selectedLocationsSet.has(origin) || selectedLocationsSet.has(dest)\n );\n case LocationFilterMode.BETWEEN:\n return (\n selectedLocationsSet.has(origin) && selectedLocationsSet.has(dest)\n );\n case LocationFilterMode.INCOMING:\n return selectedLocationsSet.has(dest);\n case LocationFilterMode.OUTGOING:\n return selectedLocationsSet.has(origin);\n }\n }\n return true;\n }\n\n // calcLocationTotals(\n // locations: (L | ClusterNode)[],\n // flows: F[],\n // ): LocationsTotals {\n // return flows.reduce(\n // (acc: LocationsTotals, curr) => {\n // const originId = this.accessors.getFlowOriginId(curr);\n // const destId = this.accessors.getFlowDestId(curr);\n // const magnitude = this.accessors.getFlowMagnitude(curr);\n // if (originId === destId) {\n // acc.internal[originId] = (acc.internal[originId] || 0) + magnitude;\n // } else {\n // acc.outgoing[originId] = (acc.outgoing[originId] || 0) + magnitude;\n // acc.incoming[destId] = (acc.incoming[destId] || 0) + magnitude;\n // }\n // return acc;\n // },\n // {incoming: {}, outgoing: {}, internal: {}},\n // );\n // }\n}\n\nfunction calcLocationTotalsExtent(\n locationTotals: Map | undefined,\n locationIdsInViewport: Set | undefined,\n) {\n if (!locationTotals) return undefined;\n let rv: [number, number] | undefined = undefined;\n for (const [\n id,\n {incomingCount, outgoingCount, internalCount},\n ] of locationTotals.entries()) {\n if (locationIdsInViewport == null || locationIdsInViewport.has(id)) {\n const lo = Math.min(\n incomingCount + internalCount,\n outgoingCount + internalCount,\n internalCount,\n );\n const hi = Math.max(\n incomingCount + internalCount,\n outgoingCount + internalCount,\n internalCount,\n );\n if (!rv) {\n rv = [lo, hi];\n } else {\n if (lo < rv[0]) rv[0] = lo;\n if (hi > rv[1]) rv[1] = hi;\n }\n }\n }\n return rv;\n}\n\n// longitude/latitude to spherical mercator in [0..1] range\nfunction lngX(lng: number) {\n return lng / 360 + 0.5;\n}\n\nfunction latY(lat: number) {\n const sin = Math.sin((lat * Math.PI) / 180);\n const y = 0.5 - (0.25 * Math.log((1 + sin) / (1 - sin))) / Math.PI;\n return y < 0 ? 0 : y > 1 ? 1 : y;\n}\n\nfunction aggregateFlows(\n flows: F[],\n flowAccessors: FlowAccessors,\n): AggregateFlow[] {\n // Sum up flows with same origin, dest\n const byOriginDest = rollup(\n flows,\n (ff: F[]) => {\n const origin = flowAccessors.getFlowOriginId(ff[0]);\n const dest = flowAccessors.getFlowDestId(ff[0]);\n // const color = ff[0].color;\n const rv: AggregateFlow = {\n aggregate: true,\n origin,\n dest,\n count: ff.reduce((m, f) => {\n const count = flowAccessors.getFlowMagnitude(f);\n if (count) {\n if (!isNaN(count) && isFinite(count)) return m + count;\n }\n return m;\n }, 0),\n // time: undefined,\n };\n // if (color) rv.color = color;\n return rv;\n },\n flowAccessors.getFlowOriginId,\n flowAccessors.getFlowDestId,\n );\n\n const rv: AggregateFlow[] = [];\n for (const values of byOriginDest.values()) {\n for (const value of values.values()) {\n rv.push(value);\n }\n }\n return rv;\n}\n\n/**\n * This is used to augment hover picking info so that we can displace location tooltip\n * @param circleAttributes\n * @param index\n */\nexport function getOuterCircleRadiusByIndex(\n circleAttributes: FlowCirclesLayerAttributes,\n index: number,\n): number {\n const {getInRadius, getOutRadius} = circleAttributes.attributes;\n return Math.max(getInRadius.value[index], getOutRadius.value[index]);\n}\n\nexport function getLocationCoordsByIndex(\n circleAttributes: FlowCirclesLayerAttributes,\n index: number,\n): [number, number] {\n const {getPosition} = circleAttributes.attributes;\n const offset = index * getPosition.size;\n return [getPosition.value[offset], getPosition.value[offset + 1]];\n}\n\nexport function getFlowLineAttributesByIndex(\n lineAttributes: FlowLinesLayerAttributes,\n index: number,\n): FlowLinesLayerAttributes {\n const {\n getColor,\n getCurveOffset,\n getEndpointOffsets,\n getSourcePosition,\n getTargetPosition,\n getThickness,\n getStaggering,\n } = lineAttributes.attributes;\n return {\n length: 1,\n attributes: {\n getColor: {\n value: getColor.value.subarray(index * 4, (index + 1) * 4),\n size: 4,\n },\n getEndpointOffsets: {\n value: getEndpointOffsets.value.subarray(index * 2, (index + 1) * 2),\n size: 2,\n },\n getSourcePosition: {\n value: getSourcePosition.value.subarray(\n index * getSourcePosition.size,\n (index + 1) * getSourcePosition.size,\n ),\n size: getSourcePosition.size,\n },\n getTargetPosition: {\n value: getTargetPosition.value.subarray(\n index * getTargetPosition.size,\n (index + 1) * getTargetPosition.size,\n ),\n size: getTargetPosition.size,\n },\n getThickness: {\n value: getThickness.value.subarray(index, index + 1),\n size: 1,\n },\n ...(getStaggering\n ? {\n getStaggering: {\n value: getStaggering.value.subarray(index, index + 1),\n size: 1,\n },\n }\n : undefined),\n ...(getCurveOffset\n ? {\n getCurveOffset: {\n value: getCurveOffset.value.subarray(index, index + 1),\n size: 1,\n },\n }\n : undefined),\n },\n };\n}\n\ntype FlowLineScreenGeometry = {\n index: number;\n originId: string | number;\n destId: string | number;\n sx: number;\n sy: number;\n tx: number;\n ty: number;\n chordLengthPx: number;\n};\n\nfunction calculateCurveOffsets(\n flows: (F | AggregateFlow)[],\n viewport: ViewportProps,\n locationsById: Map | undefined,\n getFlowOriginId: (flow: F | AggregateFlow) => string | number,\n getFlowDestId: (flow: F | AggregateFlow) => string | number,\n getLocationLon: (location: L | ClusterNode) => number,\n getLocationLat: (location: L | ClusterNode) => number,\n): Float32Array {\n const curveOffsets = new Float32Array(flows.length);\n const corridorBuckets = new Map();\n const worldScale = 512 * Math.pow(2, viewport.zoom ?? 0);\n\n flows.forEach((flow, index) => {\n const originId = getFlowOriginId(flow);\n const destId = getFlowDestId(flow);\n const origin = locationsById?.get(originId);\n const dest = locationsById?.get(destId);\n if (!origin || !dest) {\n return;\n }\n\n const sourceLon = getLocationLon(origin);\n const sourceLat = getLocationLat(origin);\n const targetLon = getLocationLon(dest);\n const targetLat = getLocationLat(dest);\n const sx = lngX(sourceLon) * worldScale;\n const sy = latY(sourceLat) * worldScale;\n const tx = lngX(targetLon) * worldScale;\n const ty = latY(targetLat) * worldScale;\n\n let corridorSourceX = sx;\n let corridorSourceY = sy;\n let corridorTargetX = tx;\n let corridorTargetY = ty;\n if (\n corridorSourceX > corridorTargetX ||\n (corridorSourceX === corridorTargetX && corridorSourceY > corridorTargetY)\n ) {\n [corridorSourceX, corridorTargetX] = [corridorTargetX, corridorSourceX];\n [corridorSourceY, corridorTargetY] = [corridorTargetY, corridorSourceY];\n }\n\n const dx = corridorTargetX - corridorSourceX;\n const dy = corridorTargetY - corridorSourceY;\n const chordLengthPx = Math.hypot(dx, dy);\n if (!isFinite(chordLengthPx) || chordLengthPx < 1) {\n return;\n }\n\n const angle = ((Math.atan2(dy, dx) % Math.PI) + Math.PI) % Math.PI;\n const signedDistance =\n (corridorSourceX * corridorTargetY - corridorSourceY * corridorTargetX) /\n chordLengthPx;\n const key = [\n Math.round(angle / ((6 * Math.PI) / 180)),\n Math.round(signedDistance / 18),\n Math.round(chordLengthPx / 24),\n ].join(':');\n\n const bucket = corridorBuckets.get(key) ?? [];\n bucket.push({index, originId, destId, sx, sy, tx, ty, chordLengthPx});\n corridorBuckets.set(key, bucket);\n });\n\n corridorBuckets.forEach((bucket) => {\n bucket\n .sort((a, b) => {\n const originCompare = compareIds(a.originId, b.originId);\n if (originCompare !== 0) return originCompare;\n const destCompare = compareIds(a.destId, b.destId);\n if (destCompare !== 0) return destCompare;\n return a.index - b.index;\n })\n .forEach((entry, bucketIndex) => {\n const maxOffsetPx = Math.min(72, entry.chordLengthPx * 0.35);\n curveOffsets[entry.index] = Math.min(\n maxOffsetPx,\n (bucketIndex + 1) * 18,\n );\n });\n });\n\n return curveOffsets;\n}\n\nfunction compareIds(a: string | number, b: string | number): number {\n if (typeof a === 'number' && typeof b === 'number') {\n return a - b;\n }\n const aString = String(a);\n const bString = String(b);\n if (aString < bString) return -1;\n if (aString > bString) return 1;\n return 0;\n}\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n AggregateFlow,\n ClusterNode,\n FlowmapDataAccessors,\n isAggregateFlow,\n isCluster,\n isLocationClusterNode,\n} from './types';\n\nexport default class FlowmapAggregateAccessors<\n L extends Record,\n F extends Record,\n> {\n private accessors: FlowmapDataAccessors;\n constructor(accessors: FlowmapDataAccessors) {\n this.accessors = accessors;\n }\n\n setAccessors(accessors: FlowmapDataAccessors) {\n this.accessors = accessors;\n }\n\n getFlowmapDataAccessors() {\n return this.accessors;\n }\n\n getLocationId = (location: L | ClusterNode): string | number =>\n isLocationClusterNode(location)\n ? location.id\n : this.accessors.getLocationId(location);\n\n getLocationName = (location: L | ClusterNode): string => {\n let name;\n if (isLocationClusterNode(location) && isCluster(location)) {\n name = location.name;\n } else if (this.accessors.getLocationName) {\n name = this.accessors.getLocationName(location as L);\n }\n if (!name) name = `${this.getLocationId(location)}`;\n return name;\n };\n\n getLocationLat = (location: L | ClusterNode): number =>\n isLocationClusterNode(location)\n ? location.lat\n : this.accessors.getLocationLat(location);\n\n getLocationLon = (location: L | ClusterNode): number =>\n isLocationClusterNode(location)\n ? location.lon\n : this.accessors.getLocationLon(location);\n\n getFlowOriginId = (f: F | AggregateFlow) => {\n return isAggregateFlow(f) ? f.origin : this.accessors.getFlowOriginId(f);\n };\n\n getFlowDestId = (f: F | AggregateFlow) => {\n return isAggregateFlow(f) ? f.dest : this.accessors.getFlowDestId(f);\n };\n\n getFlowMagnitude = (f: F | AggregateFlow) => {\n return isAggregateFlow(f) ? f.count : this.accessors.getFlowMagnitude(f);\n };\n\n // Note: Aggregate flows have no time\n getFlowTime = (f: F) => {\n const {getFlowTime} = this.accessors;\n return getFlowTime ? getFlowTime(f) : undefined;\n };\n}\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n AggregateFlow,\n Cluster,\n ClusterLevels,\n ClusterNode,\n FlowAccessors,\n FlowCountsMapReduce,\n isCluster,\n} from './../types';\nimport {ascending, bisectLeft, extent} from 'd3-array';\n\nexport type LocationWeightGetter = (id: string | number) => number;\n\n/**\n * A data structure representing the cluster levels for efficient flow aggregation.\n */\nexport interface ClusterIndex {\n availableZoomLevels: number[];\n getClusterById: (clusterId: string | number) => Cluster | undefined;\n /**\n * List the nodes on the given zoom level.\n */\n getClusterNodesFor: (zoom: number | undefined) => ClusterNode[] | undefined;\n /**\n * Get the min zoom level on which the location is not clustered.\n */\n getMinZoomForLocation: (locationId: string | number) => number;\n /**\n * List the IDs of all locations in the cluster (leaves of the subtree starting in the cluster).\n */\n expandCluster: (cluster: Cluster, targetZoom?: number) => string[];\n /**\n * Find the cluster the given location is residing in on the specified zoom level.\n */\n findClusterFor: (\n locationId: string | number,\n zoom: number,\n ) => string | number | undefined;\n /**\n * Aggregate flows for the specified zoom level.\n */\n aggregateFlows: (\n flows: F[],\n zoom: number,\n {getFlowOriginId, getFlowDestId, getFlowMagnitude}: FlowAccessors,\n options?: {\n flowCountsMapReduce?: FlowCountsMapReduce;\n },\n ) => (F | AggregateFlow)[];\n}\n\n/**\n * Build ClusterIndex from the given cluster hierarchy\n */\nexport function buildIndex(clusterLevels: ClusterLevels): ClusterIndex {\n const nodesByZoom = new Map();\n const clustersById = new Map();\n const minZoomByLocationId = new Map();\n for (const {zoom, nodes} of clusterLevels) {\n nodesByZoom.set(zoom, nodes);\n for (const node of nodes) {\n if (isCluster(node)) {\n clustersById.set(node.id, node);\n } else {\n const {id} = node;\n const mz = minZoomByLocationId.get(id);\n if (mz == null || mz > zoom) {\n minZoomByLocationId.set(id, zoom);\n }\n }\n }\n }\n\n const [minZoom, maxZoom] = extent(clusterLevels, (cl) => cl.zoom);\n if (minZoom == null || maxZoom == null) {\n throw new Error('Could not determine minZoom or maxZoom');\n }\n\n const leavesToClustersByZoom = new Map<\n number,\n Map\n >();\n\n for (const cluster of clustersById.values()) {\n const {zoom} = cluster;\n let leavesToClusters = leavesToClustersByZoom.get(zoom);\n if (!leavesToClusters) {\n leavesToClusters = new Map();\n leavesToClustersByZoom.set(zoom, leavesToClusters);\n }\n visitClusterLeaves(cluster, (leafId) => {\n leavesToClusters?.set(leafId, cluster);\n });\n }\n\n function visitClusterLeaves(cluster: Cluster, visit: (id: string) => void) {\n for (const childId of cluster.children) {\n const child = clustersById.get(childId);\n if (child) {\n visitClusterLeaves(child, visit);\n } else {\n visit(childId);\n }\n }\n }\n\n const expandCluster = (cluster: Cluster, targetZoom: number = maxZoom) => {\n const ids: string[] = [];\n const visit = (c: Cluster, expandedIds: (string | number)[]) => {\n if (targetZoom > c.zoom) {\n for (const childId of c.children) {\n const child = clustersById.get(childId);\n if (child) {\n visit(child, expandedIds);\n } else {\n expandedIds.push(childId);\n }\n }\n } else {\n expandedIds.push(c.id);\n }\n };\n visit(cluster, ids);\n return ids;\n };\n\n function findClusterFor(locationId: string | number, zoom: number) {\n const leavesToClusters = leavesToClustersByZoom.get(zoom);\n if (!leavesToClusters) {\n return undefined;\n }\n const cluster = leavesToClusters.get(locationId);\n return cluster ? cluster.id : undefined;\n }\n\n const availableZoomLevels = clusterLevels\n .map((cl) => +cl.zoom)\n .sort((a, b) => ascending(a, b));\n\n return {\n availableZoomLevels,\n\n getClusterNodesFor: (zoom) => {\n if (zoom === undefined) {\n return undefined;\n }\n return nodesByZoom.get(zoom);\n },\n\n getClusterById: (clusterId) => clustersById.get(clusterId),\n\n getMinZoomForLocation: (locationId) =>\n minZoomByLocationId.get(locationId) || minZoom,\n\n expandCluster,\n\n findClusterFor,\n\n aggregateFlows: (\n flows,\n zoom,\n {getFlowOriginId, getFlowDestId, getFlowMagnitude},\n options = {},\n ) => {\n if (zoom > maxZoom) {\n return flows;\n }\n const result: (F | AggregateFlow)[] = [];\n const aggFlowsByKey = new Map();\n const makeKey = (origin: string | number, dest: string | number) =>\n `${origin}:${dest}`;\n const {\n flowCountsMapReduce = {\n map: getFlowMagnitude,\n reduce: (acc: any, count: number) => (acc || 0) + count,\n },\n } = options;\n for (const flow of flows) {\n const origin = getFlowOriginId(flow);\n const dest = getFlowDestId(flow);\n const originCluster = findClusterFor(origin, zoom) || origin;\n const destCluster = findClusterFor(dest, zoom) || dest;\n const key = makeKey(originCluster, destCluster);\n if (originCluster === origin && destCluster === dest) {\n result.push(flow);\n } else {\n let aggregateFlow = aggFlowsByKey.get(key);\n if (!aggregateFlow) {\n aggregateFlow = {\n origin: originCluster,\n dest: destCluster,\n count: flowCountsMapReduce.map(flow),\n aggregate: true,\n };\n result.push(aggregateFlow);\n aggFlowsByKey.set(key, aggregateFlow);\n } else {\n aggregateFlow.count = flowCountsMapReduce.reduce(\n aggregateFlow.count,\n flowCountsMapReduce.map(flow),\n );\n }\n }\n }\n return result;\n },\n };\n}\n\nexport function makeLocationWeightGetter(\n flows: F[],\n {getFlowOriginId, getFlowDestId, getFlowMagnitude}: FlowAccessors,\n): LocationWeightGetter {\n const locationTotals = {\n incoming: new Map(),\n outgoing: new Map(),\n };\n for (const flow of flows) {\n const origin = getFlowOriginId(flow);\n const dest = getFlowDestId(flow);\n const count = getFlowMagnitude(flow);\n locationTotals.incoming.set(\n dest,\n (locationTotals.incoming.get(dest) || 0) + count,\n );\n locationTotals.outgoing.set(\n origin,\n (locationTotals.outgoing.get(origin) || 0) + count,\n );\n }\n return (id: string | number) =>\n Math.max(\n Math.abs(locationTotals.incoming.get(id) || 0),\n Math.abs(locationTotals.outgoing.get(id) || 0),\n );\n}\n\n/**\n * @param availableZoomLevels Must be sorted in ascending order\n * @param targetZoom\n */\nexport function findAppropriateZoomLevel(\n availableZoomLevels: number[],\n targetZoom: number,\n) {\n if (!availableZoomLevels.length) {\n throw new Error('No available zoom levels');\n }\n return availableZoomLevels[\n Math.min(\n bisectLeft(availableZoomLevels, Math.floor(targetZoom)),\n availableZoomLevels.length - 1,\n )\n ];\n}\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {min, rollup} from 'd3-array';\nimport KDBush from 'kdbush';\nimport {LocationWeightGetter} from './ClusterIndex';\nimport {Cluster, ClusterLevel, ClusterNode, LocationAccessors} from '../types';\n\n/**\n * The code in this file is a based on https://github.com/mapbox/supercluster\n *\n * ISC License\n *\n * Copyright (c) 2016, Mapbox\n *\n * Permission to use, copy, modify, and/or distribute this software for any purpose\n * with or without fee is hereby granted, provided that the above copyright notice\n * and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\n * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\n * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\n * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS\n * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER\n * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF\n * THIS SOFTWARE.\n */\n\nexport interface Options {\n minZoom: number; // min zoom to generate clusters on\n maxZoom: number; // max zoom level to cluster the points on\n radius: number; // cluster radius in pixels\n extent: number; // tile extent (radius is calculated relative to it)\n nodeSize: number; // size of the KD-tree leaf node, affects performance\n makeClusterName: (id: number, numPoints: number) => string | undefined;\n makeClusterId: (id: number) => string;\n}\n\nconst defaultOptions: Options = {\n minZoom: 0,\n maxZoom: 16,\n radius: 40,\n extent: 512,\n nodeSize: 64,\n makeClusterName: (id: number, numPoints: number) => undefined,\n makeClusterId: (id: number) => `{[${id}]}`,\n};\n\ninterface BasePoint {\n x: number; // projected point coordinates\n y: number;\n weight: number;\n zoom: number; // the last zoom the point was processed at\n parentId: number; // parent cluster id\n}\n\ninterface LeafPoint extends BasePoint {\n index: number; // index of the source feature in the original input array,\n location: L;\n}\n\ninterface ClusterPoint extends BasePoint {\n id: number;\n numPoints: number;\n}\n\ntype Point = LeafPoint | ClusterPoint;\n\nexport function isLeafPoint(p: Point): p is LeafPoint {\n const {index} = p as LeafPoint;\n return index != null;\n}\n\nexport function isClusterPoint(p: Point): p is ClusterPoint {\n const {id} = p as ClusterPoint;\n return id != null;\n}\n\ntype ZoomLevelKDBush = any;\n\nexport function clusterLocations(\n locations: Iterable,\n locationAccessors: LocationAccessors,\n getLocationWeight: LocationWeightGetter,\n options?: Partial,\n): ClusterLevel[] {\n const {getLocationLon, getLocationLat, getLocationId} = locationAccessors;\n const opts = {\n ...defaultOptions,\n ...options,\n };\n const {minZoom, maxZoom, nodeSize, makeClusterName, makeClusterId} = opts;\n\n const trees = new Array(maxZoom + 1);\n\n // generate a cluster object for each point and index input points into a KD-tree\n let clusters = new Array>();\n let locationsCount = 0;\n for (const location of locations) {\n const x = getLocationLon(location);\n const y = getLocationLat(location);\n clusters.push({\n x: lngX(x), // projected point coordinates\n y: latY(y),\n weight: getLocationWeight(getLocationId(location)),\n zoom: Infinity, // the last zoom the point was processed at\n index: locationsCount, // index of the source feature in the original input array,\n parentId: -1, // parent cluster id\n location,\n });\n locationsCount++;\n }\n\n const makeBush = (points: Point[]) => {\n const bush = new KDBush(points.length, nodeSize, Float32Array);\n for (let i = 0; i < points.length; i++) {\n bush.add(points[i].x, points[i].y);\n }\n bush.finish();\n bush.points = points;\n return bush;\n };\n\n // cluster points on max zoom, then cluster the results on previous zoom, etc.;\n // results in a cluster hierarchy across zoom levels\n trees[maxZoom + 1] = makeBush(clusters);\n let prevZoom = maxZoom + 1;\n\n for (let z = maxZoom; z >= minZoom; z--) {\n // create a new set of clusters for the zoom and index them with a KD-tree\n const _clusters = cluster(clusters, z, trees[prevZoom], opts);\n if (_clusters.length === clusters.length) {\n // same number of clusters => move the higher level clusters up\n // no need to keep the same data on multiple levels\n trees[z] = trees[prevZoom];\n trees[prevZoom] = undefined;\n prevZoom = z;\n clusters = _clusters;\n } else {\n prevZoom = z;\n clusters = _clusters;\n trees[z] = makeBush(clusters);\n }\n }\n\n if (trees.length === 0) {\n return [];\n }\n\n const numbersOfClusters: number[] = trees.map((d) => d?.points.length);\n const minClusters = min(numbersOfClusters.filter((d) => d > 0));\n\n let maxAvailZoom =\n findIndexOfMax(numbersOfClusters) ?? numbersOfClusters.length - 1;\n\n const numUniqueLocations = countUniqueLocations(locations, locationAccessors);\n if (numUniqueLocations < locationsCount) {\n // Duplicate locations would be clustered together at any zoom level which can lead to having too many zooms.\n // To avoid that, we need to find the max zoom level that has less or equal clusters than unique locations\n // and drop all zoom levels beyond that (except the unclustered level).\n const maxClustersZoom = findLastIndex(\n numbersOfClusters,\n (d) => d <= numUniqueLocations,\n );\n if (maxClustersZoom >= 0) {\n // Now, move the unclustered points to the next zoom level to avoid having a gap\n if (maxClustersZoom < maxAvailZoom) {\n trees[maxClustersZoom + 1] = trees[maxAvailZoom];\n trees.splice(maxClustersZoom + 2); // Remove all zoom levels beyond maxClustersZoom\n }\n maxAvailZoom = maxClustersZoom + 1;\n }\n }\n\n const minAvailZoom = Math.min(\n maxAvailZoom,\n minClusters ? numbersOfClusters.lastIndexOf(minClusters) : maxAvailZoom,\n );\n\n const clusterLevels = new Array();\n prevZoom = NaN;\n for (let zoom = maxAvailZoom; zoom >= minAvailZoom; zoom--) {\n let childrenByParent: Map | undefined;\n const tree = trees[zoom];\n if (!tree) continue;\n if (trees[prevZoom] && zoom < maxAvailZoom) {\n childrenByParent = rollup(\n trees[prevZoom].points,\n (points: any[]) =>\n points.map((p: any) =>\n p.id ? makeClusterId(p.id) : getLocationId(p.location),\n ),\n (point: any) => point.parentId,\n );\n }\n\n const nodes: ClusterNode[] = [];\n for (const point of tree.points) {\n const {x, y, numPoints, location} = point;\n if (isLeafPoint(point)) {\n nodes.push({\n id: getLocationId(location),\n zoom,\n lat: getLocationLat(location),\n lon: getLocationLon(location),\n });\n } else if (isClusterPoint(point)) {\n const {id} = point;\n const children = childrenByParent && childrenByParent.get(id);\n if (!children) {\n // Might happen if there are multiple locations with same coordinates\n console.warn(`Omitting cluster with no children, point:`, point);\n continue;\n }\n const cluster = {\n id: makeClusterId(id),\n name: makeClusterName(id, numPoints),\n zoom,\n lat: yLat(y),\n lon: xLng(x),\n children: children ?? [],\n } as Cluster;\n nodes.push(cluster);\n }\n }\n clusterLevels.push({\n zoom,\n nodes,\n });\n prevZoom = zoom;\n }\n return clusterLevels;\n}\n\nfunction createCluster(\n x: number,\n y: number,\n id: number,\n numPoints: number,\n weight: number,\n): ClusterPoint {\n return {\n x, // weighted cluster center\n y,\n zoom: Infinity, // the last zoom the cluster was processed at\n id, // encodes index of the first child of the cluster and its zoom level\n parentId: -1, // parent cluster id\n numPoints,\n weight,\n };\n}\n\nfunction cluster(\n points: Point[],\n zoom: number,\n tree: ZoomLevelKDBush,\n options: Options,\n) {\n const clusters: Point[] = [];\n const {radius, extent} = options;\n const r = radius / (extent * Math.pow(2, zoom));\n\n // loop through each point\n for (let i = 0; i < points.length; i++) {\n const p = points[i];\n // if we've already visited the point at this zoom level, skip it\n if (p.zoom <= zoom) {\n continue;\n }\n p.zoom = zoom;\n\n // find all nearby points\n const neighborIds = tree.within(p.x, p.y, r);\n\n let weight = p.weight || 1;\n let numPoints = isClusterPoint(p) ? p.numPoints : 1;\n let wx = p.x * weight;\n let wy = p.y * weight;\n\n // encode both zoom and point index on which the cluster originated\n const id = (i << 5) + (zoom + 1);\n\n for (const neighborId of neighborIds) {\n const b = tree.points[neighborId];\n // filter out neighbors that are already processed\n if (b.zoom <= zoom) {\n continue;\n }\n b.zoom = zoom; // save the zoom (so it doesn't get processed twice)\n\n const weight2 = b.weight || 1;\n const numPoints2 = b.numPoints || 1;\n wx += b.x * weight2; // accumulate coordinates for calculating weighted center\n wy += b.y * weight2;\n\n weight += weight2;\n numPoints += numPoints2;\n b.parentId = id;\n }\n\n if (numPoints === 1) {\n clusters.push(p);\n } else {\n p.parentId = id;\n clusters.push(\n createCluster(wx / weight, wy / weight, id, numPoints, weight),\n );\n }\n }\n\n return clusters;\n}\n\n// spherical mercator to longitude/latitude\nfunction xLng(x: number) {\n return (x - 0.5) * 360;\n}\n\nfunction yLat(y: number) {\n const y2 = ((180 - y * 360) * Math.PI) / 180;\n return (360 * Math.atan(Math.exp(y2))) / Math.PI - 90;\n}\n\n// longitude/latitude to spherical mercator in [0..1] range\nfunction lngX(lng: number) {\n return lng / 360 + 0.5;\n}\n\nfunction latY(lat: number) {\n const sin = Math.sin((lat * Math.PI) / 180);\n const y = 0.5 - (0.25 * Math.log((1 + sin) / (1 - sin))) / Math.PI;\n return y < 0 ? 0 : y > 1 ? 1 : y;\n}\n\nfunction getX(p: Point) {\n return p.x;\n}\n\nfunction getY(p: Point) {\n return p.y;\n}\n\nfunction countUniqueLocations(\n locations: Iterable,\n locationAccessors: LocationAccessors,\n) {\n const {getLocationLon, getLocationLat} = locationAccessors;\n const countByLatLon = new Map();\n let uniqueCnt = 0;\n for (const loc of locations) {\n const lon = getLocationLon(loc);\n const lat = getLocationLat(loc);\n const key = `${lon},${lat}`;\n const prev = countByLatLon.get(key);\n if (!prev) {\n uniqueCnt++;\n }\n countByLatLon.set(key, prev ? prev + 1 : 1);\n }\n return uniqueCnt;\n}\n\nfunction findIndexOfMax(arr: (number | undefined)[]): number | undefined {\n let max = -Infinity;\n let maxIndex: number | undefined = undefined;\n\n for (let i = 0; i < arr.length; i++) {\n const value = arr[i];\n\n if (typeof value === 'number') {\n if (value > max) {\n max = value;\n maxIndex = i;\n }\n }\n }\n\n return maxIndex;\n}\n\nfunction findLastIndex(\n arr: T[],\n predicate: (value: T, index: number, array: T[]) => boolean,\n): number {\n for (let i = arr.length - 1; i >= 0; i--) {\n if (predicate(arr[i], i, arr)) {\n return i;\n }\n }\n return -1;\n}\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {WebMercatorViewport} from '@math.gl/web-mercator';\nimport {\n ClusterLevel,\n isCluster,\n LocationAccessors,\n ViewportProps,\n} from './types';\nimport {scaleLinear} from 'd3-scale';\nimport {ClusterIndex, LocationWeightGetter} from './cluster/ClusterIndex';\nimport {descending} from 'd3-array';\n\n// TODO: use re-reselect\n\nexport const getViewportBoundingBox = (\n viewport: ViewportProps,\n maxLocationCircleSize = 0,\n): [number, number, number, number] => {\n const pad = maxLocationCircleSize;\n const bounds = new WebMercatorViewport({\n ...viewport,\n width: viewport.width + pad * 2,\n height: viewport.height + pad * 2,\n }).getBounds();\n return [bounds[0][0], bounds[0][1], bounds[1][0], bounds[1][1]];\n};\n\nexport const makeViewportProjector = (viewport: ViewportProps) => {\n const mercatorViewport = new WebMercatorViewport(viewport);\n return (coords: [number, number]): [number, number] => {\n const [x, y] = mercatorViewport.project(coords);\n return [x, y];\n };\n};\n\nexport const getFlowThicknessScale = (\n magnitudeExtent: [number, number] | undefined,\n) => {\n if (!magnitudeExtent) return undefined;\n return scaleLinear()\n .range([0.025, 0.5])\n .domain([\n 0,\n // should support diff mode too\n Math.max.apply(\n null,\n magnitudeExtent.map((x: number | undefined) => Math.abs(x || 0)),\n ),\n ]);\n};\n\n/**\n * Adding meaningful cluster names.\n * NOTE: this will mutate the nodes in clusterIndex\n */\nexport function addClusterNames(\n clusterIndex: ClusterIndex,\n clusterLevels: ClusterLevel[],\n locationsById: Map,\n locationAccessors: LocationAccessors,\n getLocationWeight: LocationWeightGetter,\n): void {\n const {getLocationId, getLocationName, getLocationClusterName} =\n locationAccessors;\n const getName = (id: string | number) => {\n const loc = locationsById.get(id);\n if (loc) {\n return getLocationName ? getLocationName(loc) : getLocationId(loc) || id;\n }\n return `\"${id}\"`;\n };\n for (const level of clusterLevels) {\n for (const node of level.nodes) {\n // Here mutating the nodes (adding names)\n if (isCluster(node)) {\n const leaves = clusterIndex.expandCluster(node);\n\n leaves.sort((a, b) =>\n descending(getLocationWeight(a), getLocationWeight(b)),\n );\n\n if (getLocationClusterName) {\n node.name = getLocationClusterName(leaves);\n } else {\n const topId = leaves[0];\n const otherId = leaves.length === 2 ? leaves[1] : undefined;\n node.name = `\"${getName(topId)}\" and ${\n otherId ? `\"${getName(otherId)}\"` : `${leaves.length - 1} others`\n }`;\n }\n } else {\n (node as any).name = getName(node.id);\n }\n }\n }\n}\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {timeFormat, timeParse} from 'd3-time-format';\nimport {\n timeDay,\n timeHour,\n TimeInterval,\n timeMinute,\n timeMonth,\n timeSecond,\n timeWeek,\n timeYear,\n} from 'd3-time';\n\nconst dateParsers = [\n timeParse('%Y-%m-%d'),\n timeParse('%Y-%m-%d %H:%M'),\n timeParse('%Y-%m-%d %H:%M:%S'),\n timeParse('%Y'),\n timeParse('%Y-%m'),\n];\n\nexport function parseTime(input: string | Date | undefined): Date | undefined {\n if (input != null) {\n if (input instanceof Date) {\n return input;\n }\n for (const parse of dateParsers) {\n const date = parse(input);\n if (date) {\n return date;\n }\n }\n }\n return undefined;\n}\n\nexport enum TimeGranularityKey {\n SECOND = 'SECOND',\n MINUTE = 'MINUTE',\n HOUR = 'HOUR',\n DAY = 'DAY',\n MONTH = 'MONTH',\n YEAR = 'YEAR',\n}\n\nexport interface TimeGranularity {\n key: TimeGranularityKey;\n order: number;\n interval: TimeInterval;\n format: (date: Date) => string;\n formatFull: (date: Date) => string;\n}\n\n// const preferredLocale = navigator.languages ? navigator.languages[0] : 'en';\n\nconst formatMillisecond = timeFormat('.%L'),\n formatSecond = timeFormat(':%S'),\n formatMinute = timeFormat('%I:%M'),\n // formatHour = (d: Date) => d.toLocaleString(preferredLocale, { hour: 'numeric' }),\n formatHour = timeFormat('%I %p'),\n formatDay = timeFormat('%a %d'),\n formatWeek = timeFormat('%b %d'),\n formatMonth = timeFormat('%b'),\n formatYear = timeFormat('%Y');\n\nexport function tickMultiFormat(date: Date) {\n return (\n timeSecond(date) < date\n ? formatMillisecond\n : timeMinute(date) < date\n ? formatSecond\n : timeHour(date) < date\n ? formatMinute\n : timeDay(date) < date\n ? formatHour\n : timeMonth(date) < date\n ? timeWeek(date) < date\n ? formatDay\n : formatWeek\n : timeYear(date) < date\n ? formatMonth\n : formatYear\n )(date);\n}\n\nexport const TIME_GRANULARITIES: TimeGranularity[] = [\n {\n order: 0,\n key: TimeGranularityKey.SECOND,\n interval: timeSecond,\n format: formatSecond,\n formatFull: timeFormat('%Y-%m-%d %H:%M:%S'),\n },\n {\n order: 1,\n key: TimeGranularityKey.MINUTE,\n interval: timeMinute,\n format: formatMinute,\n formatFull: timeFormat('%Y-%m-%d %H:%M'),\n },\n {\n order: 2,\n key: TimeGranularityKey.HOUR,\n interval: timeHour,\n // format: (d: Date) => d.toLocaleString(preferredLocale, { hour: 'numeric', minute: '2-digit' }),\n format: formatHour,\n formatFull: timeFormat('%a %d %b %Y, %I %p'),\n },\n {\n order: 3,\n key: TimeGranularityKey.DAY,\n interval: timeDay,\n format: formatDay,\n formatFull: timeFormat('%a %d %b %Y'),\n },\n {\n order: 4,\n key: TimeGranularityKey.MONTH,\n interval: timeMonth,\n format: formatMonth,\n formatFull: timeFormat('%b %Y'),\n },\n {\n order: 5,\n key: TimeGranularityKey.YEAR,\n interval: timeYear,\n format: formatYear,\n formatFull: timeFormat('%Y'),\n },\n];\n\nexport function getTimeGranularityByKey(key: TimeGranularityKey) {\n return TIME_GRANULARITIES.find((s) => s.key === key);\n}\n\nexport function getTimeGranularityByOrder(order: number) {\n return TIME_GRANULARITIES.find((s) => s.order === order);\n}\n\nexport function getTimeGranularityForDate(date: Date): TimeGranularity {\n let prev = undefined;\n for (const current of TIME_GRANULARITIES) {\n const {interval} = current;\n const floored = interval(date);\n if (floored < date) {\n if (!prev) return current;\n return prev;\n }\n prev = current;\n }\n return TIME_GRANULARITIES[TIME_GRANULARITIES.length - 1];\n}\n\nexport function areRangesEqual(\n a: [Date, Date] | undefined,\n b: [Date, Date] | undefined,\n): boolean {\n if (!a && !b) return true;\n if (!a || !b) return false;\n return a[0] === b[0] && a[1] === b[1];\n}\n","export var epsilon = 1e-6;\nexport var epsilon2 = 1e-12;\nexport var pi = Math.PI;\nexport var halfPi = pi / 2;\nexport var quarterPi = pi / 4;\nexport var tau = pi * 2;\n\nexport var degrees = 180 / pi;\nexport var radians = pi / 180;\n\nexport var abs = Math.abs;\nexport var atan = Math.atan;\nexport var atan2 = Math.atan2;\nexport var cos = Math.cos;\nexport var ceil = Math.ceil;\nexport var exp = Math.exp;\nexport var floor = Math.floor;\nexport var hypot = Math.hypot;\nexport var log = Math.log;\nexport var pow = Math.pow;\nexport var sin = Math.sin;\nexport var sign = Math.sign || function(x) { return x > 0 ? 1 : x < 0 ? -1 : 0; };\nexport var sqrt = Math.sqrt;\nexport var tan = Math.tan;\n\nexport function acos(x) {\n return x > 1 ? 0 : x < -1 ? pi : Math.acos(x);\n}\n\nexport function asin(x) {\n return x > 1 ? halfPi : x < -1 ? -halfPi : Math.asin(x);\n}\n\nexport function haversin(x) {\n return (x = sin(x / 2)) * x;\n}\n","export default function noop() {}\n","function streamGeometry(geometry, stream) {\n if (geometry && streamGeometryType.hasOwnProperty(geometry.type)) {\n streamGeometryType[geometry.type](geometry, stream);\n }\n}\n\nvar streamObjectType = {\n Feature: function(object, stream) {\n streamGeometry(object.geometry, stream);\n },\n FeatureCollection: function(object, stream) {\n var features = object.features, i = -1, n = features.length;\n while (++i < n) streamGeometry(features[i].geometry, stream);\n }\n};\n\nvar streamGeometryType = {\n Sphere: function(object, stream) {\n stream.sphere();\n },\n Point: function(object, stream) {\n object = object.coordinates;\n stream.point(object[0], object[1], object[2]);\n },\n MultiPoint: function(object, stream) {\n var coordinates = object.coordinates, i = -1, n = coordinates.length;\n while (++i < n) object = coordinates[i], stream.point(object[0], object[1], object[2]);\n },\n LineString: function(object, stream) {\n streamLine(object.coordinates, stream, 0);\n },\n MultiLineString: function(object, stream) {\n var coordinates = object.coordinates, i = -1, n = coordinates.length;\n while (++i < n) streamLine(coordinates[i], stream, 0);\n },\n Polygon: function(object, stream) {\n streamPolygon(object.coordinates, stream);\n },\n MultiPolygon: function(object, stream) {\n var coordinates = object.coordinates, i = -1, n = coordinates.length;\n while (++i < n) streamPolygon(coordinates[i], stream);\n },\n GeometryCollection: function(object, stream) {\n var geometries = object.geometries, i = -1, n = geometries.length;\n while (++i < n) streamGeometry(geometries[i], stream);\n }\n};\n\nfunction streamLine(coordinates, stream, closed) {\n var i = -1, n = coordinates.length - closed, coordinate;\n stream.lineStart();\n while (++i < n) coordinate = coordinates[i], stream.point(coordinate[0], coordinate[1], coordinate[2]);\n stream.lineEnd();\n}\n\nfunction streamPolygon(coordinates, stream) {\n var i = -1, n = coordinates.length;\n stream.polygonStart();\n while (++i < n) streamLine(coordinates[i], stream, 1);\n stream.polygonEnd();\n}\n\nexport default function(object, stream) {\n if (object && streamObjectType.hasOwnProperty(object.type)) {\n streamObjectType[object.type](object, stream);\n } else {\n streamGeometry(object, stream);\n }\n}\n","import {Adder} from \"d3-array\";\nimport {atan2, cos, quarterPi, radians, sin, tau} from \"./math.js\";\nimport noop from \"./noop.js\";\nimport stream from \"./stream.js\";\n\nexport var areaRingSum = new Adder();\n\n// hello?\n\nvar areaSum = new Adder(),\n lambda00,\n phi00,\n lambda0,\n cosPhi0,\n sinPhi0;\n\nexport var areaStream = {\n point: noop,\n lineStart: noop,\n lineEnd: noop,\n polygonStart: function() {\n areaRingSum = new Adder();\n areaStream.lineStart = areaRingStart;\n areaStream.lineEnd = areaRingEnd;\n },\n polygonEnd: function() {\n var areaRing = +areaRingSum;\n areaSum.add(areaRing < 0 ? tau + areaRing : areaRing);\n this.lineStart = this.lineEnd = this.point = noop;\n },\n sphere: function() {\n areaSum.add(tau);\n }\n};\n\nfunction areaRingStart() {\n areaStream.point = areaPointFirst;\n}\n\nfunction areaRingEnd() {\n areaPoint(lambda00, phi00);\n}\n\nfunction areaPointFirst(lambda, phi) {\n areaStream.point = areaPoint;\n lambda00 = lambda, phi00 = phi;\n lambda *= radians, phi *= radians;\n lambda0 = lambda, cosPhi0 = cos(phi = phi / 2 + quarterPi), sinPhi0 = sin(phi);\n}\n\nfunction areaPoint(lambda, phi) {\n lambda *= radians, phi *= radians;\n phi = phi / 2 + quarterPi; // half the angular distance from south pole\n\n // Spherical excess E for a spherical triangle with vertices: south pole,\n // previous point, current point. Uses a formula derived from Cagnoli’s\n // theorem. See Todhunter, Spherical Trig. (1871), Sec. 103, Eq. (2).\n var dLambda = lambda - lambda0,\n sdLambda = dLambda >= 0 ? 1 : -1,\n adLambda = sdLambda * dLambda,\n cosPhi = cos(phi),\n sinPhi = sin(phi),\n k = sinPhi0 * sinPhi,\n u = cosPhi0 * cosPhi + k * cos(adLambda),\n v = k * sdLambda * sin(adLambda);\n areaRingSum.add(atan2(v, u));\n\n // Advance the previous points.\n lambda0 = lambda, cosPhi0 = cosPhi, sinPhi0 = sinPhi;\n}\n\nexport default function(object) {\n areaSum = new Adder();\n stream(object, areaStream);\n return areaSum * 2;\n}\n","import {asin, atan2, cos, sin, sqrt} from \"./math.js\";\n\nexport function spherical(cartesian) {\n return [atan2(cartesian[1], cartesian[0]), asin(cartesian[2])];\n}\n\nexport function cartesian(spherical) {\n var lambda = spherical[0], phi = spherical[1], cosPhi = cos(phi);\n return [cosPhi * cos(lambda), cosPhi * sin(lambda), sin(phi)];\n}\n\nexport function cartesianDot(a, b) {\n return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];\n}\n\nexport function cartesianCross(a, b) {\n return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];\n}\n\n// TODO return a\nexport function cartesianAddInPlace(a, b) {\n a[0] += b[0], a[1] += b[1], a[2] += b[2];\n}\n\nexport function cartesianScale(vector, k) {\n return [vector[0] * k, vector[1] * k, vector[2] * k];\n}\n\n// TODO return d\nexport function cartesianNormalizeInPlace(d) {\n var l = sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]);\n d[0] /= l, d[1] /= l, d[2] /= l;\n}\n","import {Adder} from \"d3-array\";\nimport {areaStream, areaRingSum} from \"./area.js\";\nimport {cartesian, cartesianCross, cartesianNormalizeInPlace, spherical} from \"./cartesian.js\";\nimport {abs, degrees, epsilon, radians} from \"./math.js\";\nimport stream from \"./stream.js\";\n\nvar lambda0, phi0, lambda1, phi1, // bounds\n lambda2, // previous lambda-coordinate\n lambda00, phi00, // first point\n p0, // previous 3D point\n deltaSum,\n ranges,\n range;\n\nvar boundsStream = {\n point: boundsPoint,\n lineStart: boundsLineStart,\n lineEnd: boundsLineEnd,\n polygonStart: function() {\n boundsStream.point = boundsRingPoint;\n boundsStream.lineStart = boundsRingStart;\n boundsStream.lineEnd = boundsRingEnd;\n deltaSum = new Adder();\n areaStream.polygonStart();\n },\n polygonEnd: function() {\n areaStream.polygonEnd();\n boundsStream.point = boundsPoint;\n boundsStream.lineStart = boundsLineStart;\n boundsStream.lineEnd = boundsLineEnd;\n if (areaRingSum < 0) lambda0 = -(lambda1 = 180), phi0 = -(phi1 = 90);\n else if (deltaSum > epsilon) phi1 = 90;\n else if (deltaSum < -epsilon) phi0 = -90;\n range[0] = lambda0, range[1] = lambda1;\n },\n sphere: function() {\n lambda0 = -(lambda1 = 180), phi0 = -(phi1 = 90);\n }\n};\n\nfunction boundsPoint(lambda, phi) {\n ranges.push(range = [lambda0 = lambda, lambda1 = lambda]);\n if (phi < phi0) phi0 = phi;\n if (phi > phi1) phi1 = phi;\n}\n\nfunction linePoint(lambda, phi) {\n var p = cartesian([lambda * radians, phi * radians]);\n if (p0) {\n var normal = cartesianCross(p0, p),\n equatorial = [normal[1], -normal[0], 0],\n inflection = cartesianCross(equatorial, normal);\n cartesianNormalizeInPlace(inflection);\n inflection = spherical(inflection);\n var delta = lambda - lambda2,\n sign = delta > 0 ? 1 : -1,\n lambdai = inflection[0] * degrees * sign,\n phii,\n antimeridian = abs(delta) > 180;\n if (antimeridian ^ (sign * lambda2 < lambdai && lambdai < sign * lambda)) {\n phii = inflection[1] * degrees;\n if (phii > phi1) phi1 = phii;\n } else if (lambdai = (lambdai + 360) % 360 - 180, antimeridian ^ (sign * lambda2 < lambdai && lambdai < sign * lambda)) {\n phii = -inflection[1] * degrees;\n if (phii < phi0) phi0 = phii;\n } else {\n if (phi < phi0) phi0 = phi;\n if (phi > phi1) phi1 = phi;\n }\n if (antimeridian) {\n if (lambda < lambda2) {\n if (angle(lambda0, lambda) > angle(lambda0, lambda1)) lambda1 = lambda;\n } else {\n if (angle(lambda, lambda1) > angle(lambda0, lambda1)) lambda0 = lambda;\n }\n } else {\n if (lambda1 >= lambda0) {\n if (lambda < lambda0) lambda0 = lambda;\n if (lambda > lambda1) lambda1 = lambda;\n } else {\n if (lambda > lambda2) {\n if (angle(lambda0, lambda) > angle(lambda0, lambda1)) lambda1 = lambda;\n } else {\n if (angle(lambda, lambda1) > angle(lambda0, lambda1)) lambda0 = lambda;\n }\n }\n }\n } else {\n ranges.push(range = [lambda0 = lambda, lambda1 = lambda]);\n }\n if (phi < phi0) phi0 = phi;\n if (phi > phi1) phi1 = phi;\n p0 = p, lambda2 = lambda;\n}\n\nfunction boundsLineStart() {\n boundsStream.point = linePoint;\n}\n\nfunction boundsLineEnd() {\n range[0] = lambda0, range[1] = lambda1;\n boundsStream.point = boundsPoint;\n p0 = null;\n}\n\nfunction boundsRingPoint(lambda, phi) {\n if (p0) {\n var delta = lambda - lambda2;\n deltaSum.add(abs(delta) > 180 ? delta + (delta > 0 ? 360 : -360) : delta);\n } else {\n lambda00 = lambda, phi00 = phi;\n }\n areaStream.point(lambda, phi);\n linePoint(lambda, phi);\n}\n\nfunction boundsRingStart() {\n areaStream.lineStart();\n}\n\nfunction boundsRingEnd() {\n boundsRingPoint(lambda00, phi00);\n areaStream.lineEnd();\n if (abs(deltaSum) > epsilon) lambda0 = -(lambda1 = 180);\n range[0] = lambda0, range[1] = lambda1;\n p0 = null;\n}\n\n// Finds the left-right distance between two longitudes.\n// This is almost the same as (lambda1 - lambda0 + 360°) % 360°, except that we want\n// the distance between ±180° to be 360°.\nfunction angle(lambda0, lambda1) {\n return (lambda1 -= lambda0) < 0 ? lambda1 + 360 : lambda1;\n}\n\nfunction rangeCompare(a, b) {\n return a[0] - b[0];\n}\n\nfunction rangeContains(range, x) {\n return range[0] <= range[1] ? range[0] <= x && x <= range[1] : x < range[0] || range[1] < x;\n}\n\nexport default function(feature) {\n var i, n, a, b, merged, deltaMax, delta;\n\n phi1 = lambda1 = -(lambda0 = phi0 = Infinity);\n ranges = [];\n stream(feature, boundsStream);\n\n // First, sort ranges by their minimum longitudes.\n if (n = ranges.length) {\n ranges.sort(rangeCompare);\n\n // Then, merge any ranges that overlap.\n for (i = 1, a = ranges[0], merged = [a]; i < n; ++i) {\n b = ranges[i];\n if (rangeContains(a, b[0]) || rangeContains(a, b[1])) {\n if (angle(a[0], b[1]) > angle(a[0], a[1])) a[1] = b[1];\n if (angle(b[0], a[1]) > angle(a[0], a[1])) a[0] = b[0];\n } else {\n merged.push(a = b);\n }\n }\n\n // Finally, find the largest gap between the merged ranges.\n // The final bounding box will be the inverse of this gap.\n for (deltaMax = -Infinity, n = merged.length - 1, i = 0, a = merged[n]; i <= n; a = b, ++i) {\n b = merged[i];\n if ((delta = angle(a[1], b[0])) > deltaMax) deltaMax = delta, lambda0 = b[0], lambda1 = a[1];\n }\n }\n\n ranges = range = null;\n\n return lambda0 === Infinity || phi0 === Infinity\n ? [[NaN, NaN], [NaN, NaN]]\n : [[lambda0, phi0], [lambda1, phi1]];\n}\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {geoBounds} from 'd3-geo';\nimport {fitBounds} from '@math.gl/web-mercator';\nimport type {\n FeatureCollection,\n GeometryCollection,\n GeometryObject,\n} from 'geojson';\nimport type {ViewState} from './types';\n\nexport type LocationProperties = any;\n\nexport type GetViewStateOptions = {\n pad?: number; // size ratio\n padding?: {top: number; bottom: number; left: number; right: number};\n tileSize?: number;\n // minZoom?: number; // not supported by fitBounds\n maxZoom?: number;\n};\n\nexport function getViewStateForFeatures(\n featureCollection:\n | FeatureCollection\n | GeometryCollection,\n size: [number, number],\n opts?: GetViewStateOptions,\n): ViewState & {width: number; height: number} {\n const {pad = 0.05, maxZoom = 100} = opts || {};\n const bounds = geoBounds(featureCollection as any);\n const [[x1, y1], [x2, y2]] = bounds;\n const paddedBounds: [[number, number], [number, number]] = pad\n ? [\n [x1 - pad * (x2 - x1), y1 - pad * (y2 - y1)],\n [x2 + pad * (x2 - x1), y2 + pad * (y2 - y1)],\n ]\n : bounds;\n const [width, height] = size;\n return {\n ...fitBounds({\n width,\n height,\n bounds: paddedBounds,\n padding: opts?.padding,\n // minZoom,\n maxZoom,\n }),\n width,\n height,\n bearing: 0,\n pitch: 0,\n };\n}\n\nexport function getViewStateForLocations(\n locations: Iterable,\n getLocationCoords: (location: L) => [number, number],\n size: [number, number],\n opts?: GetViewStateOptions,\n): ViewState & {width: number; height: number} {\n const asGeometry = (location: L) => ({\n type: 'Point',\n coordinates: getLocationCoords(location),\n });\n let geometries;\n if (Array.isArray(locations)) {\n geometries = locations.map(asGeometry);\n } else {\n geometries = [];\n for (const location of locations) {\n geometries.push(asGeometry(location));\n }\n }\n return getViewStateForFeatures(\n {\n type: 'GeometryCollection',\n geometries,\n } as any,\n size,\n opts,\n );\n}\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {AggregateFlow, Cluster, LocationAccessors, LocationTotals} from '..';\nimport {FlowmapState} from '../FlowmapState';\nimport {\n ClusterNode,\n FlowmapData,\n FlowmapDataAccessors,\n LayersData,\n ViewportProps,\n} from '../types';\n\nexport default interface FlowmapDataProvider {\n setAccessors(accessors: FlowmapDataAccessors): void;\n\n setFlowmapState(flowmapState: FlowmapState): Promise;\n\n // clearData(): void;\n\n getViewportForLocations(\n dims: [number, number],\n ): Promise;\n\n // getFlowTotals(): Promise;\n\n getFlowByIndex(index: number): Promise;\n\n getLocationById(id: string | number): Promise;\n\n getLocationByIndex(idx: number): Promise;\n\n getTotalsForLocation(\n id: string | number,\n ): Promise;\n\n // getLocationsInBbox(\n // bbox: [number, number, number, number],\n // ): Promise | undefined>;\n\n // getLocationsForSearchBox(): Promise<(FlowLocation | ClusterNode)[] | undefined>;\n\n getLayersData(): Promise;\n\n /**\n * This is to give the data provider control over when/how often layersData\n * is updated which leads to the flowmap being redrawn.\n */\n updateLayersData(\n setLayersData: (layersData: LayersData | undefined) => void,\n changeFlags: Record,\n ): Promise;\n}\n\nexport function isFlowmapData(\n data: Record,\n): data is FlowmapData {\n return (\n data && data.locations && data.flows\n // TODO: test that they are iterable\n // Array.isArray(data.locations) &&\n // Array.isArray(data.flows)\n );\n}\n\nexport function isFlowmapDataProvider(\n dataProvider: Record,\n): dataProvider is FlowmapDataProvider {\n return (\n dataProvider &&\n typeof dataProvider.setFlowmapState === 'function' &&\n typeof dataProvider.getViewportForLocations === 'function' &&\n typeof dataProvider.getFlowByIndex === 'function' &&\n typeof dataProvider.getLocationById === 'function' &&\n typeof dataProvider.getLocationByIndex === 'function' &&\n typeof dataProvider.getLayersData === 'function'\n );\n}\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type FlowmapDataProvider from './FlowmapDataProvider';\nimport type {\n Cluster,\n ClusterNode,\n FlowmapData,\n FlowmapDataAccessors,\n LayersData,\n LocationTotals,\n ViewportProps,\n AggregateFlow,\n} from '../types';\nimport {FlowmapState} from '../FlowmapState';\nimport FlowmapSelectors from '../FlowmapSelectors';\nimport {\n GetViewStateOptions,\n getViewStateForLocations,\n} from '../getViewStateForLocations';\nimport {ClusterIndex} from '../cluster/ClusterIndex';\n\nexport default class LocalFlowmapDataProvider<\n L extends Record,\n F extends Record,\n> implements FlowmapDataProvider\n{\n private selectors: FlowmapSelectors;\n private flowmapData: FlowmapData | undefined;\n private flowmapState: FlowmapState | undefined;\n\n constructor(accessors: FlowmapDataAccessors) {\n // scope selectors to the concrete instance of FlowmapDataProvider\n this.selectors = new FlowmapSelectors(accessors);\n this.flowmapData = undefined;\n this.flowmapState = undefined;\n }\n\n setAccessors(accessors: FlowmapDataAccessors) {\n this.selectors.setAccessors(accessors);\n }\n\n setFlowmapData(flowmapData: FlowmapData): void {\n this.flowmapData = flowmapData;\n }\n\n getSelectors(): FlowmapSelectors {\n return this.selectors;\n }\n\n getFlowmapData(): FlowmapData | undefined {\n return this.flowmapData;\n }\n\n async setFlowmapState(flowmapState: FlowmapState): Promise {\n this.flowmapState = flowmapState;\n }\n\n getFlowmapState(): FlowmapState | undefined {\n return this.flowmapState;\n }\n\n async getFlowByIndex(idx: number): Promise {\n if (!this.flowmapState || !this.flowmapData) {\n return undefined;\n }\n const flows = this.selectors.getFlowsForFlowmapLayer(\n this.flowmapState,\n this.flowmapData,\n );\n return flows?.[idx];\n }\n\n // TODO: this is unreliable, should replace by unqiue ID\n async getLocationByIndex(idx: number): Promise {\n if (!this.flowmapState || !this.flowmapData) {\n return undefined;\n }\n const locations = this.selectors.getLocationsForFlowmapLayer(\n this.flowmapState,\n this.flowmapData,\n );\n return locations?.[idx];\n }\n\n async getLayersData(): Promise {\n if (!this.flowmapState || !this.flowmapData) {\n return undefined;\n }\n return this.selectors.getLayersData(this.flowmapState, this.flowmapData);\n }\n\n async getLocationById(id: string | number): Promise {\n if (!this.flowmapState || !this.flowmapData) {\n return undefined;\n }\n const clusterIndex = this.selectors.getClusterIndex(\n this.flowmapState,\n this.flowmapData,\n );\n if (clusterIndex) {\n const cluster = clusterIndex.getClusterById(id);\n if (cluster) {\n return cluster;\n }\n }\n const locationsById = this.selectors.getLocationsById(\n this.flowmapState,\n this.flowmapData,\n );\n return locationsById?.get(id);\n }\n\n async getTotalsForLocation(\n id: string | number,\n ): Promise {\n if (!this.flowmapState || !this.flowmapData) {\n return undefined;\n }\n return this.selectors\n .getLocationTotals(this.flowmapState, this.flowmapData)\n ?.get(id);\n }\n\n async getViewportForLocations(\n dims: [number, number],\n opts?: GetViewStateOptions,\n ): Promise {\n if (!this.flowmapData?.locations) {\n return undefined;\n }\n // @ts-ignore\n return getViewStateForLocations(\n this.flowmapData.locations,\n (loc) => [\n this.selectors.accessors.getLocationLon(loc),\n this.selectors.accessors.getLocationLat(loc),\n ],\n dims,\n opts,\n );\n }\n\n async updateLayersData(\n setLayersData: (layersData: LayersData | undefined) => void,\n ) {\n setLayersData(await this.getLayersData());\n }\n\n getClusterZoom(): number | undefined {\n return this.flowmapState && this.flowmapData\n ? this.selectors.getClusterZoom(this.flowmapState, this.flowmapData)\n : undefined;\n }\n\n getClusterIndex(): ClusterIndex | undefined {\n return this.flowmapState && this.flowmapData\n ? this.selectors.getClusterIndex(this.flowmapState, this.flowmapData)\n : undefined;\n }\n\n getLocationsById(): Map | undefined {\n return this.flowmapState && this.flowmapData\n ? this.selectors.getLocationsById(this.flowmapState, this.flowmapData)\n : undefined;\n }\n\n getLocationTotals(): Map | undefined {\n return this.flowmapState && this.flowmapData\n ? this.selectors.getLocationTotals(this.flowmapState, this.flowmapData)\n : undefined;\n }\n\n getFlowsForFlowmapLayer(): Array | undefined {\n return this.flowmapState && this.flowmapData\n ? this.selectors.getFlowsForFlowmapLayer(\n this.flowmapState,\n this.flowmapData,\n )\n : undefined;\n }\n}\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n AggregateFlow,\n Cluster,\n ClusterNode,\n LocationTotals,\n} from '@flowmap.gl/data';\n\nexport type LayerProps = Record;\n\nexport enum PickingType {\n LOCATION = 'location',\n FLOW = 'flow',\n // LOCATION_AREA = 'location-area',\n}\n\nexport type DeckGLLayer = Record;\n\nexport interface PickingInfo {\n layer: DeckGLLayer;\n index: number;\n picked: boolean;\n object: T | undefined;\n x: number;\n y: number;\n coordinate: [number, number];\n event: MouseEvent | undefined;\n}\n\nexport interface LocationPickingInfoObject {\n id: string | number;\n type: PickingType.LOCATION;\n location: L | ClusterNode;\n name: string;\n totals: LocationTotals;\n circleRadius: number;\n}\n\nexport type LocationPickingInfo = PickingInfo>;\n\nexport interface FlowPickingInfoObject {\n type: PickingType.FLOW;\n flow: F | AggregateFlow;\n origin: L | ClusterNode;\n dest: L | ClusterNode;\n count: number;\n}\n\nexport type FlowPickingInfo = PickingInfo>;\n\n// export interface LocationAreaPickingInfo extends PickingInfo {\n// type: PickingType.LOCATION_AREA;\n// object: FlowLocation;\n// }\n\nexport type FlowmapLayerPickingInfo =\n | LocationPickingInfo\n // | LocationAreaPickingInfo\n | FlowPickingInfo;\n\n// import {FeatureCollection, GeometryObject} from 'geojson';\n// export type LocationProperties = Record;\n\n// export type Locations =\n// | FeatureCollection\n// | FlowLocation[];\n\n// export function isFeatureCollection(\n// locations: Locations,\n// ): locations is FeatureCollection {\n// return (\n// (locations as FeatureCollection)\n// .type === 'FeatureCollection'\n// );\n// }\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {CompositeLayer} from '@deck.gl/core';\nimport {ScatterplotLayer, TextLayer} from '@deck.gl/layers';\nimport {\n FilterState,\n FlowEndpointsInViewportMode,\n FlowLinesLayerAttributes,\n FlowLinesRenderingMode,\n FlowmapAggregateAccessors,\n FlowmapData,\n FlowmapDataAccessors,\n FlowmapDataProvider,\n LayersData,\n LocalFlowmapDataProvider,\n ViewportProps,\n colorAsRgba,\n getFlowLineAttributesByIndex,\n getFlowmapColors,\n getLocationCoordsByIndex,\n getOuterCircleRadiusByIndex,\n isFlowmapData,\n isFlowmapDataProvider,\n} from '@flowmap.gl/data';\nimport AnimatedFlowLinesLayer from './AnimatedFlowLinesLayer';\nimport CurvedFlowLinesLayer from './CurvedFlowLinesLayer';\nimport FlowCirclesLayer from './FlowCirclesLayer';\nimport FlowLinesLayer from './FlowLinesLayer';\nimport {\n FlowmapLayerPickingInfo,\n LayerProps,\n PickingInfo,\n PickingType,\n} from './types';\n\nexport type FlowmapLayerProps<\n L extends Record,\n F extends Record,\n> = {\n data?: FlowmapData;\n dataProvider?: FlowmapDataProvider;\n filter?: FilterState;\n locationsEnabled?: boolean;\n locationTotalsEnabled?: boolean;\n locationLabelsEnabled?: boolean;\n adaptiveScalesEnabled?: boolean;\n flowLineThicknessScale?: number;\n flowLineCurviness?: number;\n flowLinesRenderingMode?: FlowLinesRenderingMode;\n animationEnabled?: boolean;\n clusteringEnabled?: boolean;\n clusteringLevel?: number;\n fadeEnabled?: boolean;\n fadeOpacityEnabled?: boolean;\n clusteringAuto?: boolean;\n darkMode?: boolean;\n fadeAmount?: number;\n colorScheme?: string | string[];\n highlightColor?: string | number[];\n maxTopFlowsDisplayNum?: number;\n flowEndpointsInViewportMode?: FlowEndpointsInViewportMode;\n onHover?: (\n info: FlowmapLayerPickingInfo | undefined,\n event: SourceEvent,\n ) => void;\n onClick?: (info: FlowmapLayerPickingInfo, event: SourceEvent) => void;\n} & Partial> &\n LayerProps;\n\nconst PROPS_TO_CAUSE_LAYER_DATA_UPDATE: string[] = [\n 'filter',\n 'locationsEnabled',\n 'locationTotalsEnabled',\n 'locationLabelsEnabled',\n 'adaptiveScalesEnabled',\n 'flowLinesRenderingMode',\n 'animationEnabled',\n 'clusteringEnabled',\n 'clusteringLevel',\n 'fadeEnabled',\n 'fadeOpacityEnabled',\n 'clusteringAuto',\n 'darkMode',\n 'fadeAmount',\n 'colorScheme',\n 'highlightColor',\n 'maxTopFlowsDisplayNum',\n 'flowEndpointsInViewportMode',\n];\n\nconst DEFAULT_FLOW_LINES_RENDERING_MODE: FlowLinesRenderingMode = 'straight';\n\nenum HighlightType {\n LOCATION = 'location',\n FLOW = 'flow',\n}\n\ntype HighlightedLocationObject = {\n type: HighlightType.LOCATION;\n coords: [number, number];\n radius: number;\n};\n\ntype HighlightedFlowObject = {\n type: HighlightType.FLOW;\n lineAttributes: FlowLinesLayerAttributes;\n};\n\ntype HighlightedObject = HighlightedLocationObject | HighlightedFlowObject;\n\ntype State, F extends Record> = {\n accessors: FlowmapAggregateAccessors;\n dataProvider: FlowmapDataProvider;\n layersData: LayersData | undefined;\n highlightedObject: HighlightedObject | undefined;\n pickingInfo: FlowmapLayerPickingInfo | undefined;\n lastHoverTime: number | undefined;\n lastClickTime: number | undefined;\n};\n\nexport type SourceEvent = {srcEvent: MouseEvent};\n\nexport default class FlowmapLayer<\n L extends Record,\n F extends Record,\n> extends CompositeLayer {\n private _didWarnAboutAnimationEnabledDeprecation = false;\n private _didWarnAboutAnimationEnabledConflict = false;\n\n static defaultProps = {\n darkMode: true,\n fadeAmount: 50,\n locationsEnabled: true,\n locationTotalsEnabled: true,\n locationLabelsEnabled: false,\n clusteringEnabled: true,\n fadeEnabled: true,\n fadeOpacityEnabled: false,\n clusteringAuto: true,\n clusteringLevel: undefined,\n adaptiveScalesEnabled: true,\n flowLineThicknessScale: 1,\n flowLineCurviness: 1,\n colorScheme: 'Teal',\n highlightColor: 'orange',\n maxTopFlowsDisplayNum: 5000,\n flowEndpointsInViewportMode: 'any',\n };\n state!: State;\n\n private get typedProps(): FlowmapLayerProps {\n return this.props as unknown as FlowmapLayerProps;\n }\n\n public constructor(props: FlowmapLayerProps) {\n super({\n ...props,\n onHover: ((info: PickingInfo, event: SourceEvent) => {\n const startTime = Date.now();\n this.setState({\n highlightedObject: this._getHighlightedObject(info),\n lastHoverTime: startTime,\n });\n\n const {onHover} = props;\n if (onHover) {\n this._getFlowmapLayerPickingInfo(info).then((info) => {\n if ((this.state?.lastHoverTime ?? 0) <= startTime) {\n this.setState({pickingInfo: info});\n onHover(info, event);\n } else {\n // Skipping, because this is not the latest hover event\n }\n });\n }\n }) as any,\n onClick: ((info: PickingInfo, event: SourceEvent) => {\n const {onClick} = props;\n const startTime = Date.now();\n this.setState({\n lastClickTime: startTime,\n });\n if (onClick) {\n this._getFlowmapLayerPickingInfo(info).then((info) => {\n if ((this.state?.lastClickTime ?? 0) <= startTime) {\n this.setState({pickingInfo: info});\n if (info) {\n onClick(info, event);\n }\n } else {\n // Skipping, because this is not the latest hover event\n }\n });\n }\n }) as any,\n } as any);\n }\n\n initializeState() {\n this.state = {\n accessors: new FlowmapAggregateAccessors(\n this.typedProps as FlowmapDataAccessors,\n ),\n dataProvider: this._getOrMakeDataProvider(),\n layersData: undefined,\n highlightedObject: undefined,\n pickingInfo: undefined,\n lastHoverTime: undefined,\n lastClickTime: undefined,\n };\n }\n\n getPickingInfo({info}: Record) {\n // This is for onHover event handlers set on the component\n if (!info.object) {\n const object = this.state?.pickingInfo?.object;\n if (object) {\n return {\n ...info,\n object,\n picked: true,\n };\n }\n }\n return info;\n }\n\n // private _updateAccessors() {\n // this.state?.dataProvider?.setAccessors(this.props);\n // this.setState({accessors: new FlowmapAggregateAccessors(this.props)});\n // }\n\n private _getOrMakeDataProvider() {\n const {data, dataProvider} = this.typedProps;\n if (dataProvider && isFlowmapDataProvider(dataProvider as any)) {\n return dataProvider;\n } else if (data && isFlowmapData(data as any)) {\n const dataProvider = new LocalFlowmapDataProvider(\n this.typedProps as FlowmapDataAccessors,\n );\n dataProvider.setFlowmapData(data);\n return dataProvider;\n }\n throw new Error(\n 'FlowmapLayer: data must be a FlowmapDataProvider or FlowmapData',\n );\n }\n\n private _updateDataProvider() {\n this.setState({dataProvider: this._getOrMakeDataProvider()});\n }\n\n shouldUpdateState(params: any): boolean {\n const {changeFlags} = params;\n // if (this._viewportChanged()) {\n // return true;\n // }\n if (changeFlags.viewportChanged) {\n return true;\n }\n return super.shouldUpdateState(params);\n // TODO: be smarter on when to update\n // (e.g. ignore viewport changes when adaptiveScalesEnabled and clustering are false)\n }\n\n updateState(params: any): void {\n super.updateState(params);\n const {oldProps, props, changeFlags} = params;\n if (changeFlags.propsChanged) {\n // this._updateAccessors();\n }\n if (changeFlags.dataChanged) {\n this._updateDataProvider();\n }\n if (changeFlags.viewportChanged || changeFlags.dataChanged) {\n this.setState({highlightedObject: undefined});\n }\n\n if (\n changeFlags.viewportChanged ||\n changeFlags.dataChanged ||\n (changeFlags.propsChanged &&\n PROPS_TO_CAUSE_LAYER_DATA_UPDATE.some(\n (prop) => oldProps[prop] !== props[prop],\n ))\n ) {\n const {dataProvider} = this.state || {};\n if (dataProvider) {\n dataProvider.setFlowmapState(this._getFlowmapState());\n dataProvider.updateLayersData((layersData: LayersData | undefined) => {\n this.setState({layersData, highlightedObject: undefined});\n }, changeFlags);\n }\n }\n }\n\n private _getSettingsState() {\n const props = this.typedProps;\n const defaults = FlowmapLayer.defaultProps;\n const {\n locationsEnabled,\n locationTotalsEnabled,\n locationLabelsEnabled,\n adaptiveScalesEnabled,\n flowLinesRenderingMode,\n clusteringEnabled,\n clusteringLevel,\n fadeEnabled,\n fadeOpacityEnabled,\n clusteringAuto,\n darkMode,\n fadeAmount,\n colorScheme,\n highlightColor,\n maxTopFlowsDisplayNum,\n flowEndpointsInViewportMode,\n } = props;\n return {\n locationsEnabled: locationsEnabled ?? defaults.locationsEnabled,\n locationTotalsEnabled:\n locationTotalsEnabled ?? defaults.locationTotalsEnabled,\n locationLabelsEnabled:\n locationLabelsEnabled ?? defaults.locationLabelsEnabled,\n adaptiveScalesEnabled:\n adaptiveScalesEnabled ?? defaults.adaptiveScalesEnabled,\n flowLinesRenderingMode:\n flowLinesRenderingMode ?? this._getResolvedFlowLinesRenderingMode(),\n clusteringEnabled: clusteringEnabled ?? defaults.clusteringEnabled,\n clusteringLevel,\n fadeEnabled: fadeEnabled ?? defaults.fadeEnabled,\n fadeOpacityEnabled: fadeOpacityEnabled ?? defaults.fadeOpacityEnabled,\n clusteringAuto: clusteringAuto ?? defaults.clusteringAuto,\n darkMode: darkMode ?? defaults.darkMode,\n fadeAmount: fadeAmount ?? defaults.fadeAmount,\n colorScheme,\n highlightColor: highlightColor ?? defaults.highlightColor,\n maxTopFlowsDisplayNum:\n maxTopFlowsDisplayNum ?? defaults.maxTopFlowsDisplayNum,\n flowEndpointsInViewportMode: (flowEndpointsInViewportMode ??\n defaults.flowEndpointsInViewportMode) as FlowEndpointsInViewportMode,\n };\n }\n\n private _getResolvedFlowLinesRenderingMode(): FlowLinesRenderingMode {\n const {animationEnabled, flowLinesRenderingMode} = this.typedProps;\n if (flowLinesRenderingMode !== undefined) {\n if (\n animationEnabled !== undefined &&\n !this._didWarnAboutAnimationEnabledConflict\n ) {\n this._didWarnAboutAnimationEnabledConflict = true;\n console.warn(\n 'FlowmapLayer: `animationEnabled` is deprecated and ignored when `flowLinesRenderingMode` is provided.',\n );\n }\n return flowLinesRenderingMode;\n }\n if (animationEnabled !== undefined) {\n if (!this._didWarnAboutAnimationEnabledDeprecation) {\n this._didWarnAboutAnimationEnabledDeprecation = true;\n console.warn(\n 'FlowmapLayer: `animationEnabled` is deprecated; use `flowLinesRenderingMode` instead.',\n );\n }\n return animationEnabled ? 'animated-straight' : 'straight';\n }\n return DEFAULT_FLOW_LINES_RENDERING_MODE;\n }\n\n private _getFlowmapState() {\n const props = this.typedProps;\n return {\n viewport: pickViewportProps(this.context.viewport),\n filter: props.filter,\n settings: this._getSettingsState(),\n };\n }\n\n private async _getFlowmapLayerPickingInfo(\n info: Record,\n ): Promise | undefined> {\n const {index, sourceLayer} = info;\n const {dataProvider, accessors} = this.state || {};\n if (!dataProvider || !accessors) {\n return undefined;\n }\n const commonInfo = {\n ...info,\n picked: info.picked,\n layer: info.layer,\n index: info.index,\n x: info.x,\n y: info.y,\n coordinate: info.coordinate,\n event: info.event,\n };\n if (\n sourceLayer instanceof FlowLinesLayer ||\n sourceLayer instanceof AnimatedFlowLinesLayer ||\n sourceLayer instanceof CurvedFlowLinesLayer\n ) {\n const flow =\n index === -1 ? undefined : await dataProvider.getFlowByIndex(index);\n if (flow) {\n const origin = await dataProvider.getLocationById(\n accessors.getFlowOriginId(flow),\n );\n const dest = await dataProvider.getLocationById(\n accessors.getFlowDestId(flow),\n );\n if (origin && dest) {\n return {\n ...commonInfo,\n object: {\n type: PickingType.FLOW,\n flow,\n origin: origin,\n dest: dest,\n count: accessors.getFlowMagnitude(flow),\n },\n };\n }\n }\n } else if (sourceLayer instanceof FlowCirclesLayer) {\n const location =\n index === -1 ? undefined : await dataProvider.getLocationByIndex(index);\n\n if (location) {\n const id = accessors.getLocationId(location);\n const name = accessors.getLocationName(location);\n const totals = await dataProvider.getTotalsForLocation(id);\n const {circleAttributes} = this.state?.layersData || {};\n if (totals && circleAttributes) {\n const circleRadius = getOuterCircleRadiusByIndex(\n circleAttributes,\n info.index,\n );\n return {\n ...commonInfo,\n object: {\n type: PickingType.LOCATION,\n location,\n id,\n name,\n totals,\n circleRadius: circleRadius,\n },\n };\n }\n }\n }\n\n return undefined;\n }\n\n private _getHighlightedObject(\n info: Record,\n ): HighlightedObject | undefined {\n const {index, sourceLayer} = info;\n if (index < 0) return undefined;\n if (\n sourceLayer instanceof FlowLinesLayer ||\n sourceLayer instanceof AnimatedFlowLinesLayer ||\n sourceLayer instanceof CurvedFlowLinesLayer\n ) {\n const {lineAttributes} = this.state?.layersData || {};\n if (lineAttributes) {\n let attrs = getFlowLineAttributesByIndex(lineAttributes, index);\n if (this.typedProps.fadeOpacityEnabled) {\n attrs = {\n ...attrs,\n attributes: {\n ...attrs.attributes,\n getColor: {\n ...attrs.attributes.getColor,\n value: new Uint8Array([\n ...attrs.attributes.getColor.value.slice(0, 3),\n 255, // the highlight color should be always opaque\n ]),\n },\n },\n };\n }\n return {\n type: HighlightType.FLOW,\n lineAttributes: attrs,\n };\n }\n } else if (sourceLayer instanceof FlowCirclesLayer) {\n const {circleAttributes} = this.state?.layersData || {};\n if (circleAttributes) {\n return {\n type: HighlightType.LOCATION,\n coords: getLocationCoordsByIndex(circleAttributes, index),\n radius: getOuterCircleRadiusByIndex(circleAttributes, index),\n };\n }\n }\n return undefined;\n }\n\n renderLayers(): Array {\n const props = this.typedProps;\n const flowLinesRenderingMode = this._getResolvedFlowLinesRenderingMode();\n const highlightColor =\n props.highlightColor ?? FlowmapLayer.defaultProps.highlightColor;\n const flowLineThicknessScale =\n props.flowLineThicknessScale ??\n FlowmapLayer.defaultProps.flowLineThicknessScale;\n const flowLineCurviness =\n props.flowLineCurviness ?? FlowmapLayer.defaultProps.flowLineCurviness;\n const layers = [];\n if (this.state?.layersData) {\n const {layersData, highlightedObject} = this.state;\n const {circleAttributes, lineAttributes, locationLabels} =\n layersData || {};\n if (circleAttributes && lineAttributes) {\n const flowmapColors = getFlowmapColors(this._getSettingsState());\n const outlineColor = colorAsRgba(\n flowmapColors.outlineColor || (props.darkMode ? '#000' : '#fff'),\n );\n const commonLineLayerProps = {\n data: lineAttributes,\n parameters: {\n ...((props.parameters as Record | undefined) ??\n {}),\n // prevent z-fighting at non-zero bearing/pitch\n depthTest: false,\n },\n };\n switch (flowLinesRenderingMode) {\n case 'animated-straight':\n layers.push(\n // @ts-ignore\n new AnimatedFlowLinesLayer({\n ...this.getSubLayerProps({\n ...commonLineLayerProps,\n id: 'animated-flow-lines',\n drawOutline: false,\n thicknessUnit: 10 * flowLineThicknessScale,\n }),\n }),\n );\n break;\n case 'curved':\n layers.push(\n new CurvedFlowLinesLayer({\n ...this.getSubLayerProps({\n ...commonLineLayerProps,\n id: 'curved-flow-lines',\n drawOutline: true,\n outlineColor: outlineColor,\n thicknessUnit: 12 * flowLineThicknessScale,\n curviness: flowLineCurviness,\n }),\n }),\n );\n break;\n case 'straight':\n default:\n layers.push(\n new FlowLinesLayer({\n ...this.getSubLayerProps({\n ...commonLineLayerProps,\n id: 'flow-lines',\n drawOutline: true,\n outlineColor: outlineColor,\n thicknessUnit: 12 * flowLineThicknessScale,\n }),\n }),\n );\n break;\n }\n layers.push(\n new FlowCirclesLayer(\n this.getSubLayerProps({\n id: 'circles',\n data: circleAttributes,\n emptyColor: props.darkMode\n ? [0, 0, 0, 255]\n : [255, 255, 255, 255],\n outlineEmptyMix: 0.4,\n }),\n ),\n );\n if (highlightedObject) {\n switch (highlightedObject.type) {\n case HighlightType.LOCATION:\n layers.push(\n new ScatterplotLayer({\n ...this.getSubLayerProps({\n id: 'location-highlight',\n data: [highlightedObject],\n pickable: false,\n antialiasing: true,\n stroked: true,\n filled: false,\n lineWidthUnits: 'pixels',\n getLineWidth: 2,\n radiusUnits: 'pixels',\n getRadius: (d: HighlightedLocationObject) => d.radius,\n getLineColor: colorAsRgba(highlightColor),\n getPosition: (d: HighlightedLocationObject) => d.coords,\n }),\n }),\n );\n break;\n case HighlightType.FLOW:\n if (flowLinesRenderingMode === 'curved') {\n layers.push(\n new CurvedFlowLinesLayer({\n ...this.getSubLayerProps({\n id: 'flow-highlight',\n data: highlightedObject.lineAttributes,\n drawOutline: true,\n pickable: false,\n outlineColor: colorAsRgba(highlightColor),\n outlineThickness: 1.5,\n thicknessUnit: 12 * flowLineThicknessScale,\n curviness: flowLineCurviness,\n parameters: {\n depthTest: false,\n },\n }),\n }),\n );\n } else {\n layers.push(\n new FlowLinesLayer({\n ...this.getSubLayerProps({\n id: 'flow-highlight',\n data: highlightedObject.lineAttributes,\n drawOutline: true,\n pickable: false,\n outlineColor: colorAsRgba(highlightColor),\n outlineThickness: 1.5,\n thicknessUnit: 12 * flowLineThicknessScale,\n parameters: {\n depthTest: false,\n },\n }),\n }),\n );\n }\n break;\n }\n }\n }\n if (locationLabels) {\n layers.push(\n new TextLayer(\n this.getSubLayerProps({\n id: 'location-labels',\n data: locationLabels,\n maxWidth: 1000,\n pickable: false,\n fontFamily: 'Helvetica',\n getPixelOffset: (d: string, {index}: {index: number}) => {\n const r = getOuterCircleRadiusByIndex(circleAttributes, index);\n return [0, r + 5];\n },\n getPosition: (d: string, {index}: {index: number}) => {\n const pos = getLocationCoordsByIndex(circleAttributes, index);\n return pos;\n },\n getText: (d: string) => d,\n getSize: 10,\n getColor: [255, 255, 255, 255],\n getAngle: 0,\n getTextAnchor: 'middle',\n getAlignmentBaseline: 'top',\n }),\n ),\n );\n }\n }\n\n return layers;\n }\n}\n\nfunction pickViewportProps(viewport: Record): ViewportProps {\n const {width, height, longitude, latitude, zoom, pitch, bearing} = viewport;\n return {\n width,\n height,\n longitude,\n latitude,\n zoom,\n pitch,\n bearing,\n };\n}\n","import {Deck} from '@deck.gl/core';\nimport {MapboxOverlay} from '@deck.gl/mapbox';\nimport {FlowmapLayer} from '@flowmap.gl/layers';\n\nwindow.FlowmapGL = {\n Deck,\n FlowmapLayer,\n MapboxOverlay\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,MAEMA,UACAC,YACA,UACA,UACA;AANN;;AAEA,MAAMD,WAAU;A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;MACN;MACA;MACA;MACA;MACA;MACA;MACA;;IAEF,MAAM,SAAS,MAAU;IACzB,MAAM,SAASA,OAAU;IACzB,MAAM;MACJ;MACA;MACA;MACA;MACA;MACA;MACA;;IAEF,QAAQ;MACN;MACA;MACA;MACA;MACA;MACA;MACA;;IAEF,MAAM,cAAc,IAAe;IACnC,UAAU;MACR;MACA;MACA;MACA;MACA;MACA;MACA;;IAEF,OAAO;IACP,MAAM,SAASA,OAAU;IACzB,SAAS;IACT,QAAQ,SAASA,QAAY;IAC7B,OAAO,SAASA,QAAW;IAC3B,SAAS,cAAc,OAAkB;IACzC,SAAS;MACP;MACA;MACA;MACA;MACA;MACA;MACA;;IAEF,OAAO,cAAc,KAAgB;IACrC,MAAM;MACJ;MACA;MACA;MACA;MACA;MACA;MACA;;IAEF,SAAS,SAASA,QAAa;IAC/B,MAAM,SAASA,OAAU;IACzB,OAAO;MACL;MACA;MACA;MACA;MACA;MACA;MACA;;IAEF,OAAO;MACL;MACA;MACA;MACA;MACA;MACA;MACA;;IAEF,QAAQ,cAAc,MAAiB;IACvC,QAAQ;MACN;MACA;MACA;MACA;MACA;MACA;MACA;;IAEF,MAAM,SAASA,OAAU;IACzB,QAAQ,SAASA,OAAY;IAC7B,MAAM,SAASA,OAAU;IACzB,MAAM;MACJ;MACA;MACA;MACA;MACA;MACA;MACA;;IAEF,SAAS,SAASA,QAAa;IAC/B,QAAQ;MACN;MACA;MACA;MACA;MACA;MACA;MACA;;IAEF,MAAM,SAASA,OAAU;IACzB,OAAO;MACL;MACA;MACA;MACA;MACA;MACA;MACA;;IAEF,MAAM,SAASA,QAAU;IACzB,QAAQ;MACN;MACA;MACA;MACA;MACA;MACA;MACA;;IAEF,YAAY;MACV;MACA;MACA;MACA;MACA;MACA;MACA;;IAEF,MAAM;IACN,SAAS;MACP;MACA;MACA;MACA;MACA;MACA;MACA;;IAEF,SAAS,cAAc,eAAkB;IACzC,MAAM,cAAc,IAAe;IACnC,MAAM,SAASA,QAAU;IAC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ACL,EAAA,OAAM,QAAA,WAAA,UAAA,MAAA,OAAA,QAAA,IAAA;WACN;MACA;MACA;MACA;MACA;MACA;MACH;;;;;;ACnrBD,SAAO,YAAY;AAAA,IACjB;AAAA,IACA;AAAA,IACA;AAAA,EACF;","names":["window_","document_","userAgent","isBrowser","isBrowser","userAgent","assert","message","assert","message","message","length","color","isBrowser","COLOR","name","isBrowser","window_","message","isBrowser","assert","init_dist","getHiResTimestamp","init_hi_res_timestamp","init_hi_res_timestamp","name","getHiResTimestamp","name","init_dist","init_hi_res_timestamp","init_dist","name","log","init_dist","count","defaultProps","initializeStats","ORDERED_STATS_CACHE","ORDERED_STAT_NAME_SET_CACHE","name","GPU_TIME_AND_MEMORY_STATS","Buffer","arrayBuffer","count","format","count","format","format","matches","length","message","log","format","source","Buffer","log","webgl2Adapter","map","resolve","isBrowser","resolve","assert","message","init_assert","init_assert","isBrowser","devicePixelRatio","log","format","source","log","message","color","getShaderName","log","attachment","index","format","cache","log","log","log","bindGroups","group","format","name","log","attributeMapping","count","NORMALIZED_TYPE_MAP","name","length","length","isTypedArray","isNumberArray","name","length","isNumberArray","log","index","isNumberArray","uniformBlock","uniformBlock","Buffer","log","init_dist","init_assert","GLEnum","resolve","log","resolve","init_dist","getWebGLContextData","isBrowser","log","message","init_dist","isArray","cache","target","invert","isObjectEmpty","cache","isArray","set","luma","name","version","format","init_dist","init_dist","init_dist","init_dist","init_dist","init_dist","uid","uidCounters","count","init_uid","Buffer","init_dist","arrayBuffer","messageType","message","init_dist","source","log","resolve","isObjectEmpty","map","vertex","log","init_dist","init_dist","isObjectEmpty","init_dist","init_dist","format","log","log","init_dist","name","uniformBlock","uniforms","count","index","name","isArray","format","log","matches","init_dist","init_dist","log","status","isArray","resolve","source","init_dist","init_dist","color","init_dist","fillArray","target","source","count","length","init_dist","enable","length","fillArray","init_dist","log","index","init_dist","resolve","init_dist","resolve","format","source","target","getFramebuffer","init_dist","compareConstantArrayValues","init_dist","init_uid","format","uid","resolve","log","source","number","name","LOG_LEVEL","init_dist","enable","log","WebGLDevice","message","init_dist","global","module","define","copy","global","module","define","copy","global","module","define","copy","global","module","define","me","seed","copy","global","module","define","me","seed","copy","global","module","define","c","copy","global","flatten","prng","seed","copy","count","t","i","j","s","require_seedrandom","alea","message","init_dist","VERSION","log","VERSION","assert","message","globals","self_","window_","global_","document_","isBrowser","isMobile","matches","nodeVersion","resolve","assert","assert","isBrowser","name","source","assert","message","name","onMessage","isBrowser","isMobile","name","source","isBrowser","version","assert","VERSION","assert","isBrowser","name","message","source2","length","copy","filename","toArrayBuffer","copyToArrayBuffer","copy","index","message","matches","matches","message","resolve","init_dist","defaultOptions","message","length","arrayBuffer","DEFAULT_CHUNK_SIZE","arrayBuffer","DEFAULT_CHUNK_SIZE","toArrayBuffer","toArrayBuffer","assert","fetch","VERSION","format","arrayBuffer","arrayBuffer","URL","resolve","message","arrayBuffer","arrayBuffer","parseImageNode","arrayBuffer","VERSION","arrayBuffer","init_dist","log","message","version","VERSION","assert","message","name","source","len","defaultProps","log","name","message","assert","log","index","source","name","source","version","source","index","matches","length","source","group","name","source","vs","fs","log","assert","name","defines","getUniforms","define","group","location","index","source","source","getUniforms","defines","count","len","name","min","max","value","epsilon","target","scale","min","max","length","assert","message","length","dist","assert","equals","forEach","lerp","round","round","round","scale","len","lerp","p0","equals","forEach","count","add","angle","ceil","clone","copy","create","cross","dist","distance","div","divide","dot","equals","exactEquals","floor","forEach","fromValues","inverse","len","length","lerp","max","min","mul","multiply","negate","normalize","random","round","scale","scaleAndAdd","set","sqrDist","sqrLen","squaredDistance","squaredLength","str","sub","subtract","transformMat3","transformMat4","zero","create","clone","length","fromValues","copy","set","add","subtract","multiply","divide","ceil","floor","min","max","round","scale","scaleAndAdd","distance","squaredDistance","squaredLength","negate","inverse","normalize","len","dot","cross","lerp","angle","c","random","transformMat4","transformMat3","zero","str","exactEquals","equals","sub","mul","div","dist","sqrDist","sqrLen","forEach","count","angle","cross","radians","transformMat4","transformMat3","add","clone","copy","create","equals","exactEquals","fromValues","mul","multiply","rotate","rotateX","rotateY","rotateZ","scale","set","str","sub","subtract","create","clone","copy","fromValues","set","multiply","scale","rotate","len","c","rotateX","rotateY","rotateZ","target","str","add","subtract","exactEquals","equals","mul","sub","add","ceil","clone","copy","create","cross","dist","distance","div","divide","dot","equals","exactEquals","floor","forEach","fromValues","inverse","len","length","lerp","max","min","mul","multiply","negate","normalize","random","round","scale","scaleAndAdd","set","sqrDist","sqrLen","squaredDistance","squaredLength","str","sub","subtract","transformMat4","transformQuat","zero","create","clone","fromValues","copy","set","add","subtract","multiply","divide","ceil","floor","min","max","round","scale","scaleAndAdd","distance","squaredDistance","length","squaredLength","negate","inverse","normalize","len","dot","cross","A","B","C","D","E","lerp","random","transformMat4","transformQuat","zero","str","exactEquals","equals","sub","mul","div","dist","sqrDist","sqrLen","forEach","count","INDICES","scale","multiply","radians","rotateX","rotateY","rotateZ","rotate","transformMat4","length","ZERO","index","color","vs","fs","InputEvent","InputDirection","RecognizerState","str","target","getRotation","getRotation","target","index","add","name","index","distance","EVENT_NAMES","Input","window_","Input","Input","enable","Input","Input","MOUSE_EVENTS","scaleX","scaleY","target","name","len","IDENTITY_MATRIX","devicePixelRatio","SHADER_COORDINATE_SYSTEMS","getUniforms","source","vs","clamp","min","max","log2","assert","message","DEGREES_TO_RADIANS","RADIANS_TO_DEGREES","scale","log2","assert","lambda2","unitsPerMeter","unitsPerMeter2","clamp","clamp","assert","scaleX","scaleY","log2","DEGREES_TO_RADIANS","scale","translate","uniformBlock","vs","fs","VECTOR_TO_POINT_MATRIX","color","DEFAULT_LIGHT_COLOR","DEFAULT_LIGHT_INTENSITY","idCount","color","target","c","devicePixelRatio","index","source","target","DEFAULT_SHADOW_COLOR","count","copy","createMat4","mod","c","fp64LowPart","count","DEGREES_TO_RADIANS","IDENTITY","createMat4","ZERO_VECTOR","scale","WebMercatorViewport","scale","translate","DEFAULT_COORDINATE_ORIGIN","init_dist","init_dist","resolve","div","name","init_dist","init_dist","uidCounters","uid","count","uid","Buffer","name","name","source","scale","init_dist","name","index","log","name","init_dist","name","log","name","index","init_dist","init_dist","format","uid","resolve","size","log","Buffer","index","group","format","uid","source","getUniforms","vs","fs","log","set","name","group","Buffer","init_dist","Buffer","uid","index","target","source","count","length","init_dist","Resource","Resource","viewport","deepEqual","deepEqual","Controller","extent","index","target","source","deepEqual","noop","assert","message","assert","DEGREES_TO_RADIANS","RADIANS_TO_DEGREES","getDistanceScales","unitsPerMeter","scale","transformVector","D","DEFAULT_PROPS","deepEqual","scale","lngLatToWorld","y","normalize","assert","scale","mod","e2","index","deepEqual","source","init_dist","Buffer","source","deepEqual","deepEqual","init_dist","init_dist","noop","deepEqual","assert","defaultOptions","VERSION","init_dist","init_dist","name","min","len","max","Buffer","copy","isAsyncIterable","index","target","add","range","len","add","assert","map","source","target","source","target","uniformBlock","vs","getFramebuffer","getTransform","uniformBlock","vs","fs","format","name","init_dist","EPSILON","distance","TRANSITION_TYPES","transition","isObject","target","source","index","init_dist","isArray","deepEqual","getTypeOf","defaultProps","name","defaultProps","name","isAsyncIterable","isAsyncIterable","count","fetch","EMPTY_ARRAY","defaultProps","assert","target","color","index","message","name","Buffer","picking","TRACE_RENDER_LAYERS","fetch","DEGREES_TO_RADIANS","RADIANS_TO_DEGREES","angle","radians","scale","mod","assert","map","map","group","TILE_SIZE","DEGREES_TO_RADIANS","map","group","scale","map","assert","uniformBlock","index","AnimatedFlowLinesLayer_default","uniformBlock","DEFAULT_COLOR","HEAD_START_T","c","index","t0","t1","CurvedFlowLinesLayer_default","DEFAULT_COLOR","FlowLinesLayer_default","uniformBlock","DEFAULT_COLOR","FlowCirclesLayer_default","uniformBlock","noop","number","DEFAULT_COLOR","defaultProps","DEFAULT_COLOR","defaultProps","uniformBlock","glslUniformBlock","DEFAULT_BUFFER","defaultProps","index","DEFAULT_BUFFER","len","pad","scale","length","nextPowOfTwo","number","buildMapping","measureText","target","length","index","index","buildMapping","uniformBlock","defaultProps","DEFAULT_COLOR","defaultProps","index","getPosition","getColor","c","LocationFilterMode","format","min","max","radians","degrees","degrees","c","radians","degrees","radians","t1","t2","t3","color","rgb","c","isNumberArray","c","c","zero","i","c","isNumberArray","cubehelix","hue","scheme","scheme","scheme","scheme","scheme","scheme","scheme","scheme","scheme","scheme","scheme","scheme","scheme","scheme","scheme","scheme","scheme","scheme","range","zero","min","max","index","key","identity","identity","map","values","groups","keyof","index","group","count","ticks","min","index","range","range","number","identity","normalize","range","i","copy","source","target","clamp","scale","number","length","map","locale","group","zero","format","c","length","formatPrefix","value","max","count","scale","count","linear","copy","scale","identity","copy","t0","t1","count","range","locale","formatMonth","formats","c","pad","format","parse","length","name","locale","defaultLocale","transformer","t0","t1","identity","clamp","scale","range","copy","source","target","scale","transformer","copy","c","color","scheme","ColorScheme","scale","colors_default","VERSION","version","data","index","x","y","count","memoize","length","equals","length","cache","length","createSelector","memoize","name","cluster","c","count","defaultOptions","index","min","cluster","extent","sin","max","pad","linear","TimeGranularityKey","formatYear","formatYear","min","range","cluster","colors_default","count","add","lngX","latY","sin","rv","index","getPosition","getColor","angle","degrees","radians","cos","sin","sqrt","asin","noop","noop","radians","cos","sin","cartesian","asin","spherical","cos","sin","sqrt","lambda0","lambda00","phi00","range","radians","degrees","angle","lambda1","pad","cluster","PickingType","HighlightType","info","dataProvider","index","FlowLinesLayer_default","AnimatedFlowLinesLayer_default","CurvedFlowLinesLayer_default","FlowCirclesLayer_default","name"]} diff --git a/inst/htmlwidgets/lib/flowmap-gl/flowmap-gl-bundle.min.js b/inst/htmlwidgets/lib/flowmap-gl/flowmap-gl-bundle.min.js new file mode 100644 index 0000000..a3e74ec --- /dev/null +++ b/inst/htmlwidgets/lib/flowmap-gl/flowmap-gl-bundle.min.js @@ -0,0 +1,3008 @@ +(()=>{var _2=Object.create;var Mu=Object.defineProperty;var y2=Object.getOwnPropertyDescriptor;var x2=Object.getOwnPropertyNames;var b2=Object.getPrototypeOf,T2=Object.prototype.hasOwnProperty;var P=(t,e)=>()=>(t&&(e=t(t=0)),e);var er=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Zi=(t,e)=>{for(var r in e)Mu(t,r,{get:e[r],enumerable:!0})},w2=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of x2(e))!T2.call(t,n)&&n!==r&&Mu(t,n,{get:()=>e[n],enumerable:!(i=y2(e,n))||i.enumerable});return t};var S2=(t,e,r)=>(r=t!=null?_2(b2(t)):{},w2(e||!t||!t.__esModule?Mu(r,"default",{value:t,enumerable:!0}):r,t));var Qa,P2,Ja,M2,e_,Iu=P(()=>{Qa=globalThis,P2=globalThis.document||{},Ja=globalThis.process||{},M2=globalThis.console,e_=globalThis.navigator||{}});function ec(t){if(typeof window<"u"&&window.process?.type==="renderer"||typeof process<"u"&&process.versions?.electron)return!0;let e=typeof navigator<"u"&&navigator.userAgent,r=t||e;return!!(r&&r.indexOf("Electron")>=0)}var Ou=P(()=>{});function De(){return!(typeof process=="object"&&String(process)==="[object process]"&&!process?.browser)||ec()}var Nu=P(()=>{Ou()});function Du(t){return!t&&!De()?"Node":ec(t)?"Electron":(t||e_.userAgent||"").indexOf("Edge")>-1?"Edge":globalThis.chrome?"Chrome":globalThis.safari?"Safari":globalThis.mozInnerScreenX?"Firefox":"Unknown"}var t_=P(()=>{Nu();Ou();Iu()});var Lu,Rr=P(()=>{Iu();Nu();t_();Lu="4.1.1"});function Qi(t,e){if(!t)throw new Error(e||"Assertion failed")}var Fu=P(()=>{});function Bu(t){if(!t)return 0;let e;switch(typeof t){case"number":e=t;break;case"object":e=t.logLevel||t.priority||0;break;default:return 0}return Qi(Number.isFinite(e)&&e>=0),e}function r_(t){let{logLevel:e,message:r}=t;t.logLevel=Bu(e);let i=t.args?Array.from(t.args):[];for(;i.length&&i.shift()!==r;);switch(typeof e){case"string":case"function":r!==void 0&&i.unshift(r),t.message=e;break;case"object":Object.assign(t,e);break;default:}typeof t.message=="function"&&(t.message=t.message());let n=typeof t.message;return Qi(n==="string"||n==="object"),Object.assign(t,{args:i},t.opts)}var i_=P(()=>{Fu()});var oi,tc,n_=P(()=>{i_();oi=()=>{},tc=class{constructor({level:e=0}={}){this.userData={},this._onceCache=new Set,this._level=e}set level(e){this.setLevel(e)}get level(){return this.getLevel()}setLevel(e){return this._level=e,this}getLevel(){return this._level}warn(e,...r){return this._log("warn",0,e,r,{once:!0})}error(e,...r){return this._log("error",0,e,r)}log(e,r,...i){return this._log("log",e,r,i)}info(e,r,...i){return this._log("info",e,r,i)}once(e,r,...i){return this._log("once",e,r,i,{once:!0})}_log(e,r,i,n,o={}){let s=r_({logLevel:r,message:i,args:this._buildArgs(r,i,n),opts:o});return this._createLogFunction(e,s,o)}_buildArgs(e,r,i){return[e,r,...i]}_createLogFunction(e,r,i){if(!this._shouldLog(r.logLevel))return oi;let n=this._getOnceTag(i.tag??r.tag??r.message);if((i.once||r.once)&&n!==void 0){if(this._onceCache.has(n))return oi;this._onceCache.add(n)}return this._emit(e,r)}_shouldLog(e){return this.getLevel()>=Bu(e)}_getOnceTag(e){if(e!==void 0)try{return typeof e=="string"?e:String(e)}catch{return}}}});function O2(t){try{let e=window[t],r="__storage_test__";return e.setItem(r,r),e.removeItem(r),e}catch{return null}}var rc,o_=P(()=>{rc=class{constructor(e,r,i="sessionStorage"){this.storage=O2(i),this.id=e,this.config=r,this._loadConfiguration()}getConfiguration(){return this.config}setConfiguration(e){if(Object.assign(this.config,e),this.storage){let r=JSON.stringify(this.config);this.storage.setItem(this.id,r)}}_loadConfiguration(){let e={};if(this.storage){let r=this.storage.getItem(this.id);e=r?JSON.parse(r):{}}return Object.assign(this.config,e),this}}});function s_(t){let e;return t<10?e=`${t.toFixed(2)}ms`:t<100?e=`${t.toFixed(1)}ms`:t<1e3?e=`${t.toFixed(0)}ms`:e=`${(t/1e3).toFixed(2)}s`,e}function a_(t,e=8){let r=Math.max(e-t.length,0);return`${" ".repeat(r)}${t}`}var c_=P(()=>{});function l_(t){return typeof t!="string"?t:(t=t.toUpperCase(),ic[t]||ic.WHITE)}function f_(t,e,r){return!De&&typeof t=="string"&&(e&&(t=`\x1B[${l_(e)}m${t}\x1B[39m`),r&&(t=`\x1B[${l_(r)+N2}m${t}\x1B[49m`)),t}var ic,N2,u_=P(()=>{Rr();(function(t){t[t.BLACK=30]="BLACK",t[t.RED=31]="RED",t[t.GREEN=32]="GREEN",t[t.YELLOW=33]="YELLOW",t[t.BLUE=34]="BLUE",t[t.MAGENTA=35]="MAGENTA",t[t.CYAN=36]="CYAN",t[t.WHITE=37]="WHITE",t[t.BRIGHT_BLACK=90]="BRIGHT_BLACK",t[t.BRIGHT_RED=91]="BRIGHT_RED",t[t.BRIGHT_GREEN=92]="BRIGHT_GREEN",t[t.BRIGHT_YELLOW=93]="BRIGHT_YELLOW",t[t.BRIGHT_BLUE=94]="BRIGHT_BLUE",t[t.BRIGHT_MAGENTA=95]="BRIGHT_MAGENTA",t[t.BRIGHT_CYAN=96]="BRIGHT_CYAN",t[t.BRIGHT_WHITE=97]="BRIGHT_WHITE"})(ic||(ic={}));N2=10});function d_(t,e=["constructor"]){let r=Object.getPrototypeOf(t),i=Object.getOwnPropertyNames(r),n=t;for(let o of i){let s=n[o];typeof s=="function"&&(e.find(a=>o===a)||(n[o]=s.bind(t)))}}var h_=P(()=>{});function Ji(){let t;if(De()&&Qa.performance)t=Qa?.performance?.now?.();else if("hrtime"in Ja){let e=Ja?.hrtime?.();t=e[0]*1e3+e[1]/1e6}else t=Date.now();return t}var p_=P(()=>{Rr()});function D2(t,e,r){if(typeof e=="string"){let i=r.time?a_(s_(r.total)):"";e=r.time?`${t}: ${i} ${e}`:`${t}: ${e}`,e=f_(e,r.color,r.background)}return e}function L2(t){for(let e in t)for(let r in t[e])return r||"untitled";return"empty"}var en,ku,Le,Uu=P(()=>{Rr();n_();o_();c_();u_();h_();Fu();p_();en={debug:De()&&console.debug||console.log,log:console.log,info:console.info,warn:console.warn,error:console.error},ku={enabled:!0,level:0},Le=class extends tc{constructor({id:e}={id:""}){super({level:0}),this.VERSION=Lu,this._startTs=Ji(),this._deltaTs=Ji(),this.userData={},this.LOG_THROTTLE_TIMEOUT=0,this.id=e,this.userData={},this._storage=new rc(`__probe-${this.id}__`,{[this.id]:ku}),this.timeStamp(`${this.id} started`),d_(this),Object.seal(this)}isEnabled(){return this._getConfiguration().enabled}getLevel(){return this._getConfiguration().level}getTotal(){return Number((Ji()-this._startTs).toPrecision(10))}getDelta(){return Number((Ji()-this._deltaTs).toPrecision(10))}set priority(e){this.level=e}get priority(){return this.level}getPriority(){return this.level}enable(e=!0){return this._updateConfiguration({enabled:e}),this}setLevel(e){return this._updateConfiguration({level:e}),this}get(e){return this._getConfiguration()[e]}set(e,r){this._updateConfiguration({[e]:r})}settings(){console.table?console.table(this._storage.config):console.log(this._storage.config)}assert(e,r){if(!e)throw new Error(r||"Assertion failed")}warn(e,...r){return this._log("warn",0,e,r,{method:en.warn,once:!0})}error(e,...r){return this._log("error",0,e,r,{method:en.error})}deprecated(e,r){return this.warn(`\`${e}\` is deprecated and will be removed in a later version. Use \`${r}\` instead`)}removed(e,r){return this.error(`\`${e}\` has been removed. Use \`${r}\` instead`)}probe(e,r,...i){return this._log("log",e,r,i,{method:en.log,time:!0,once:!0})}log(e,r,...i){return this._log("log",e,r,i,{method:en.debug})}info(e,r,...i){return this._log("info",e,r,i,{method:console.info})}once(e,r,...i){return this._log("once",e,r,i,{method:en.debug||en.info,once:!0})}table(e,r,i){return r?this._log("table",e,r,i&&[i]||[],{method:console.table||oi,tag:L2(r)}):oi}time(e,r){return this._log("time",e,r,[],{method:console.time?console.time:console.info})}timeEnd(e,r){return this._log("time",e,r,[],{method:console.timeEnd?console.timeEnd:console.info})}timeStamp(e,r){return this._log("time",e,r,[],{method:console.timeStamp||oi})}group(e,r,i={collapsed:!1}){let n=(i.collapsed?console.groupCollapsed:console.group)||console.info;return this._log("group",e,r,[],{method:n})}groupCollapsed(e,r,i={}){return this.group(e,r,Object.assign({},i,{collapsed:!0}))}groupEnd(e){return this._log("groupEnd",e,"",[],{method:console.groupEnd||oi})}withGroup(e,r,i){this.group(e,r)();try{i()}finally{this.groupEnd(e)()}}trace(){console.trace&&console.trace()}_shouldLog(e){return this.isEnabled()&&super._shouldLog(e)}_emit(e,r){let i=r.method;Qi(i),r.total=this.getTotal(),r.delta=this.getDelta(),this._deltaTs=Ji();let n=D2(this.id,r.message,r);return i.bind(console,n,...r.args)}_getConfiguration(){return this._storage.config[this.id]||this._updateConfiguration(ku),this._storage.config[this.id]}_updateConfiguration(e){let r=this._storage.config[this.id]||{...ku};this._storage.setConfiguration({[this.id]:{...r,...e}})}};Le.VERSION=Lu});var g_=P(()=>{globalThis.probe={}});var Fk,lo=P(()=>{Uu();Uu();g_();Fk=new Le({id:"@probe.gl/log"})});function po(){let t;if(typeof window<"u"&&window.performance)t=window.performance.now();else if(typeof process<"u"&&process.hrtime){let e=process.hrtime();t=e[0]*1e3+e[1]/1e6}else t=Date.now();return t}var rd=P(()=>{});var ai,id=P(()=>{rd();ai=class{constructor(e,r){this.sampleSize=1,this.time=0,this.count=0,this.samples=0,this.lastTiming=0,this.lastSampleTime=0,this.lastSampleCount=0,this._count=0,this._time=0,this._samples=0,this._startTime=0,this._timerPending=!1,this.name=e,this.type=r,this.reset()}reset(){return this.time=0,this.count=0,this.samples=0,this.lastTiming=0,this.lastSampleTime=0,this.lastSampleCount=0,this._count=0,this._time=0,this._samples=0,this._startTime=0,this._timerPending=!1,this}setSampleSize(e){return this.sampleSize=e,this}incrementCount(){return this.addCount(1),this}decrementCount(){return this.subtractCount(1),this}addCount(e){return this._count+=e,this._samples++,this._checkSampling(),this}subtractCount(e){return this._count-=e,this._samples++,this._checkSampling(),this}addTime(e){return this._time+=e,this.lastTiming=e,this._samples++,this._checkSampling(),this}timeStart(){return this._startTime=po(),this._timerPending=!0,this}timeEnd(){return this._timerPending?(this.addTime(po()-this._startTime),this._timerPending=!1,this._checkSampling(),this):this}getSampleAverageCount(){return this.sampleSize>0?this.lastSampleCount/this.sampleSize:0}getSampleAverageTime(){return this.sampleSize>0?this.lastSampleTime/this.sampleSize:0}getSampleHz(){return this.lastSampleTime>0?this.sampleSize/(this.lastSampleTime/1e3):0}getAverageCount(){return this.samples>0?this.count/this.samples:0}getAverageTime(){return this.samples>0?this.time/this.samples:0}getHz(){return this.time>0?this.samples/(this.time/1e3):0}_checkSampling(){this._samples===this.sampleSize&&(this.lastSampleTime=this._time,this.lastSampleCount=this._count,this.count+=this._count,this.time+=this._time,this.samples+=this._samples,this._time=0,this._count=0,this._samples=0)}}});var it,C_=P(()=>{id();it=class{constructor(e){this.stats={},this.id=e.id,this.stats={},this._initializeStats(e.stats),Object.seal(this)}get(e,r="count"){return this._getOrCreate({name:e,type:r})}get size(){return Object.keys(this.stats).length}reset(){for(let e of Object.values(this.stats))e.reset();return this}forEach(e){for(let r of Object.values(this.stats))e(r)}getTable(){let e={};return this.forEach(r=>{e[r.name]={time:r.time||0,count:r.count||0,average:r.getAverageTime()||0,hz:r.getHz()||0}}),e}_initializeStats(e=[]){e.forEach(r=>this._getOrCreate(r))}_getOrCreate(e){let{name:r,type:i}=e,n=this.stats[r];return n||(e instanceof ai?n=e:n=new ai(r,i),this.stats[r]=n),n}}});var go=P(()=>{C_();id();rd()});function kP(t,e){let r=t.stats,i=!1;for(let c of e)r[c]||(t.get(c),i=!0);let n=Object.keys(r).length,o=Fy.get(t);if(!i&&o?.orderedStatNames===e&&o.statCount===n)return;let s={},a=By.get(e);a||(a=new Set(e),By.set(e,a));for(let c of e)r[c]&&(s[c]=r[c]);for(let[c,l]of Object.entries(r))a.has(c)||(s[c]=l);for(let c of Object.keys(r))delete r[c];Object.assign(r,s),Fy.set(t,{orderedStatNames:e,statCount:n})}var FP,BP,Fy,By,mh,Pc,_h=P(()=>{go();FP="GPU Time and Memory",BP=["Adapter","GPU","GPU Type","GPU Backend","Frame Rate","CPU Time","GPU Time","GPU Memory","Buffer Memory","Texture Memory","Referenced Buffer Memory","Referenced Texture Memory","Swap Chain Texture"],Fy=new WeakMap,By=new WeakMap,mh=class{stats=new Map;getStats(e){return this.get(e)}get(e){this.stats.has(e)||this.stats.set(e,new it({id:e}));let r=this.stats.get(e);return e===FP&&kP(r,BP),r}},Pc=new mh});var v,ot=P(()=>{lo();v=new Le({id:"luma.gl"})});function Dt(t="id"){yh[t]=yh[t]||1;let e=yh[t]++;return`${t}-${e}`}var yh,un=P(()=>{yh={}});function $P(t,e){let r={...e};for(let i in t)t[i]!==void 0&&(r[i]=t[i]);return r}function jy(t,e){let r=t.stats,i=!1;for(let c of e)r[c]||(t.get(c),i=!0);let n=Object.keys(r).length,o=Wy.get(t);if(!i&&o?.orderedStatNames===e&&o.statCount===n)return;let s={},a=Vy.get(e);a||(a=new Set(e),Vy.set(e,a));for(let c of e)r[c]&&(s[c]=r[c]);for(let[c,l]of Object.entries(r))a.has(c)||(s[c]=l);for(let c of Object.keys(r))delete r[c];Object.assign(r,s),Wy.set(t,{orderedStatNames:e,statCount:n})}function $y(t){return t.type==="webgl"?jP:VP}function Po(t){let e=t.userData[UP];return e?.enabled?e:null}function Ir(){return globalThis.performance?.now?.()??Date.now()}function HP(t,e){let r=Po(t);if(!(!r||!r.activeDefaultFramebufferAcquireDepth))switch(r.transientCanvasResourceCreates=(r.transientCanvasResourceCreates||0)+1,e){case"Texture":r.transientCanvasTextureCreates=(r.transientCanvasTextureCreates||0)+1;break;case"TextureView":r.transientCanvasTextureViewCreates=(r.transientCanvasTextureViewCreates||0)+1;break;case"Sampler":r.transientCanvasSamplerCreates=(r.transientCanvasSamplerCreates||0)+1;break;case"Framebuffer":r.transientCanvasFramebufferCreates=(r.transientCanvasFramebufferCreates||0)+1;break;default:break}}function YP(t){let e=Object.getPrototypeOf(t);for(;e;){let r=Object.getPrototypeOf(e);if(!r||r===k.prototype)return XP(e)||t[Symbol.toStringTag]||t.constructor.name;e=r}return t[Symbol.toStringTag]||t.constructor.name}function XP(t){let e=Object.getOwnPropertyDescriptor(t,Symbol.toStringTag);return typeof e?.get=="function"?e.get.call(t):typeof e?.value=="string"?e.value:null}var UP,ky,Uy,zy,zP,WP,VP,jP,Wy,Vy,k,we=P(()=>{un();UP="cpu-hotspot-profiler",ky="GPU Resource Counts",Uy="Resource Counts",zy="GPU Time and Memory",zP=["Resources","Buffers","Textures","Samplers","TextureViews","Framebuffers","QuerySets","Shaders","RenderPipelines","ComputePipelines","PipelineLayouts","VertexArrays","RenderPasss","ComputePasss","CommandEncoders","CommandBuffers"],WP=["Resources","Buffers","Textures","Samplers","TextureViews","Framebuffers","QuerySets","Shaders","RenderPipelines","SharedRenderPipelines","ComputePipelines","PipelineLayouts","VertexArrays","RenderPasss","ComputePasss","CommandEncoders","CommandBuffers"],VP=zP.flatMap(t=>[`${t} Created`,`${t} Active`]),jP=WP.flatMap(t=>[`${t} Created`,`${t} Active`]),Wy=new WeakMap,Vy=new WeakMap,k=class{static defaultProps={id:"undefined",handle:void 0,userData:void 0};toString(){return`${this[Symbol.toStringTag]||this.constructor.name}:"${this.id}"`}id;props;userData={};_device;destroyed=!1;allocatedBytes=0;allocatedBytesName=null;_attachedResources=new Set;constructor(e,r,i){if(!e)throw new Error("no device");this._device=e,this.props=$P(r,i);let n=this.props.id!=="undefined"?this.props.id:Dt(this[Symbol.toStringTag]);this.props.id=n,this.id=n,this.userData=this.props.userData||{},this.addStats()}destroy(){this.destroyed||this.destroyResource()}delete(){return this.destroy(),this}getProps(){return this.props}attachResource(e){this._attachedResources.add(e)}detachResource(e){this._attachedResources.delete(e)}destroyAttachedResource(e){this._attachedResources.delete(e)&&e.destroy()}destroyAttachedResources(){for(let e of this._attachedResources)e.destroy();this._attachedResources=new Set}destroyResource(){this.destroyed||(this.destroyAttachedResources(),this.removeStats(),this.destroyed=!0)}removeStats(){let e=Po(this._device),r=e?Ir():0,i=[this._device.statsManager.getStats(ky),this._device.statsManager.getStats(Uy)],n=$y(this._device);for(let s of i)jy(s,n);let o=this.getStatsName();for(let s of i)s.get("Resources Active").decrementCount(),s.get(`${o}s Active`).decrementCount();e&&(e.statsBookkeepingCalls=(e.statsBookkeepingCalls||0)+1,e.statsBookkeepingTimeMs=(e.statsBookkeepingTimeMs||0)+(Ir()-r))}trackAllocatedMemory(e,r=this.getStatsName()){let i=Po(this._device),n=i?Ir():0,o=this._device.statsManager.getStats(zy);this.allocatedBytes>0&&this.allocatedBytesName&&(o.get("GPU Memory").subtractCount(this.allocatedBytes),o.get(`${this.allocatedBytesName} Memory`).subtractCount(this.allocatedBytes)),o.get("GPU Memory").addCount(e),o.get(`${r} Memory`).addCount(e),i&&(i.statsBookkeepingCalls=(i.statsBookkeepingCalls||0)+1,i.statsBookkeepingTimeMs=(i.statsBookkeepingTimeMs||0)+(Ir()-n)),this.allocatedBytes=e,this.allocatedBytesName=r}trackReferencedMemory(e,r=this.getStatsName()){this.trackAllocatedMemory(e,`Referenced ${r}`)}trackDeallocatedMemory(e=this.getStatsName()){if(this.allocatedBytes===0){this.allocatedBytesName=null;return}let r=Po(this._device),i=r?Ir():0,n=this._device.statsManager.getStats(zy);n.get("GPU Memory").subtractCount(this.allocatedBytes),n.get(`${this.allocatedBytesName||e} Memory`).subtractCount(this.allocatedBytes),r&&(r.statsBookkeepingCalls=(r.statsBookkeepingCalls||0)+1,r.statsBookkeepingTimeMs=(r.statsBookkeepingTimeMs||0)+(Ir()-i)),this.allocatedBytes=0,this.allocatedBytesName=null}trackDeallocatedReferencedMemory(e=this.getStatsName()){this.trackDeallocatedMemory(`Referenced ${e}`)}addStats(){let e=this.getStatsName(),r=Po(this._device),i=r?Ir():0,n=[this._device.statsManager.getStats(ky),this._device.statsManager.getStats(Uy)],o=$y(this._device);for(let s of n)jy(s,o);for(let s of n)s.get("Resources Created").incrementCount(),s.get("Resources Active").incrementCount(),s.get(`${e}s Created`).incrementCount(),s.get(`${e}s Active`).incrementCount();r&&(r.statsBookkeepingCalls=(r.statsBookkeepingCalls||0)+1,r.statsBookkeepingTimeMs=(r.statsBookkeepingTimeMs||0)+(Ir()-i)),HP(this._device,e)}getStatsName(){return YP(this)}}});var j,Mc=P(()=>{we();j=class t extends k{static INDEX=16;static VERTEX=32;static UNIFORM=64;static STORAGE=128;static INDIRECT=256;static QUERY_RESOLVE=512;static MAP_READ=1;static MAP_WRITE=2;static COPY_SRC=4;static COPY_DST=8;get[Symbol.toStringTag](){return"Buffer"}usage;indexType;updateTimestamp;constructor(e,r){let i={...r};(r.usage||0)&t.INDEX&&!r.indexType&&(r.data instanceof Uint32Array?i.indexType="uint32":r.data instanceof Uint16Array?i.indexType="uint16":r.data instanceof Uint8Array&&(i.indexType="uint8")),delete i.data,super(e,i,t.defaultProps),this.usage=i.usage||0,this.indexType=i.indexType,this.updateTimestamp=e.incrementTimestamp()}clone(e){return this.device.createBuffer({...this.props,...e})}static DEBUG_DATA_MAX_LENGTH=32;debugData=new ArrayBuffer(0);_setDebugData(e,r,i){let n=null,o;ArrayBuffer.isView(e)?(n=e,o=e.buffer):o=e;let s=Math.min(e?e.byteLength:i,t.DEBUG_DATA_MAX_LENGTH);if(o===null)this.debugData=new ArrayBuffer(s);else{let a=Math.min(n?.byteOffset||0,o.byteLength),c=Math.max(0,o.byteLength-a),l=Math.min(s,c);this.debugData=new Uint8Array(o,a,l).slice().buffer}}static defaultProps={...k.defaultProps,usage:0,byteLength:0,byteOffset:0,data:null,indexType:"uint16",onMapped:void 0}}});var bh,ke,xh,Ic=P(()=>{bh=class{getDataTypeInfo(e){let[r,i,n]=xh[e],o=e.includes("norm"),s=!o&&!e.startsWith("float"),a=e.startsWith("s");return{signedType:r,primitiveType:i,byteLength:n,normalized:o,integer:s,signed:a}}getNormalizedDataType(e){let r=e;switch(r){case"uint8":return"unorm8";case"sint8":return"snorm8";case"uint16":return"unorm16";case"sint16":return"snorm16";default:return r}}alignTo(e,r){switch(r){case 1:return e;case 2:return e+e%2;default:return e+(4-e%4)%4}}getDataType(e){let r=ArrayBuffer.isView(e)?e.constructor:e;if(r===Uint8ClampedArray)return"uint8";let i=Object.values(xh).find(n=>r===n[4]);if(!i)throw new Error(r.name);return i[0]}getTypedArrayConstructor(e){let[,,,,r]=xh[e];return r}},ke=new bh,xh={uint8:["uint8","u32",1,!1,Uint8Array],sint8:["sint8","i32",1,!1,Int8Array],unorm8:["uint8","f32",1,!0,Uint8Array],snorm8:["sint8","f32",1,!0,Int8Array],uint16:["uint16","u32",2,!1,Uint16Array],sint16:["sint16","i32",2,!1,Int16Array],unorm16:["uint16","u32",2,!0,Uint16Array],snorm16:["sint16","i32",2,!0,Int16Array],float16:["float16","f16",2,!1,Uint16Array],float32:["float32","f32",4,!1,Float32Array],uint32:["uint32","u32",4,!1,Uint32Array],sint32:["sint32","i32",4,!1,Int32Array]}});var Th,or,Oc=P(()=>{Ic();Th=class{getVertexFormatInfo(e){let r;e.endsWith("-webgl")&&(e.replace("-webgl",""),r=!0);let[i,n]=e.split("x"),o=i,s=n?parseInt(n):1,a=ke.getDataTypeInfo(o),c={type:o,components:s,byteLength:a.byteLength*s,integer:a.integer,signed:a.signed,normalized:a.normalized};return r&&(c.webglOnly=!0),c}makeVertexFormat(e,r,i){let n=i?ke.getNormalizedDataType(e):e;switch(n){case"unorm8":return r===1?"unorm8":r===3?"unorm8x3-webgl":`${n}x${r}`;case"snorm8":return r===1?"snorm8":r===3?"snorm8x3-webgl":`${n}x${r}`;case"uint8":case"sint8":if(r===1||r===3)throw new Error(`size: ${r}`);return`${n}x${r}`;case"uint16":return r===1?"uint16":r===3?"uint16x3-webgl":`${n}x${r}`;case"sint16":return r===1?"sint16":r===3?"sint16x3-webgl":`${n}x${r}`;case"unorm16":return r===1?"unorm16":r===3?"unorm16x3-webgl":`${n}x${r}`;case"snorm16":return r===1?"snorm16":r===3?"snorm16x3-webgl":`${n}x${r}`;case"float16":if(r===1||r===3)throw new Error(`size: ${r}`);return`${n}x${r}`;default:return r===1?n:`${n}x${r}`}}getVertexFormatFromAttribute(e,r,i){if(!r||r>4)throw new Error(`size ${r}`);let n=r,o=ke.getDataType(e);return this.makeVertexFormat(o,n,i)}getCompatibleVertexFormat(e){let r;switch(e.primitiveType){case"f32":r="float32";break;case"i32":r="sint32";break;case"u32":r="uint32";break;case"f16":return e.components<=2?"float16x2":"float16x4"}return e.components===1?r:`${r}x${e.components}`}},or=new Th});function Rh(t){let e=Xy[t];if(!e)throw new Error(`Unsupported texture format ${t}`);return e}function Yy(){return Xy}var Ie,te,Lt,GP,Nc,wh,Dc,Sh,qP,Ah,Or,vh,Eh,Lc,Hy,KP,ZP,Xy,Ch=P(()=>{Ie="texture-compression-bc",te="texture-compression-astc",Lt="texture-compression-etc2",GP="texture-compression-etc1-webgl",Nc="texture-compression-pvrtc-webgl",wh="texture-compression-atc-webgl",Dc="float32-renderable-webgl",Sh="float16-renderable-webgl",qP="rgb9e5ufloat-renderable-webgl",Ah="snorm8-renderable-webgl",Or="norm16-webgl",vh="norm16-renderable-webgl",Eh="snorm16-renderable-webgl",Lc="float32-filterable",Hy="float16-filterable-webgl";KP={r8unorm:{},rg8unorm:{},"rgb8unorm-webgl":{},rgba8unorm:{},"rgba8unorm-srgb":{},r8snorm:{render:Ah},rg8snorm:{render:Ah},"rgb8snorm-webgl":{},rgba8snorm:{render:Ah},r8uint:{},rg8uint:{},rgba8uint:{},r8sint:{},rg8sint:{},rgba8sint:{},bgra8unorm:{},"bgra8unorm-srgb":{},r16unorm:{f:Or,render:vh},rg16unorm:{f:Or,render:vh},"rgb16unorm-webgl":{f:Or,render:!1},rgba16unorm:{f:Or,render:vh},r16snorm:{f:Or,render:Eh},rg16snorm:{f:Or,render:Eh},"rgb16snorm-webgl":{f:Or,render:!1},rgba16snorm:{f:Or,render:Eh},r16uint:{},rg16uint:{},rgba16uint:{},r16sint:{},rg16sint:{},rgba16sint:{},r16float:{render:Sh,filter:"float16-filterable-webgl"},rg16float:{render:Sh,filter:Hy},rgba16float:{render:Sh,filter:Hy},r32uint:{},rg32uint:{},rgba32uint:{},r32sint:{},rg32sint:{},rgba32sint:{},r32float:{render:Dc,filter:Lc},rg32float:{render:!1,filter:Lc},"rgb32float-webgl":{render:Dc,filter:Lc},rgba32float:{render:Dc,filter:Lc},"rgba4unorm-webgl":{channels:"rgba",bitsPerChannel:[4,4,4,4],packed:!0},"rgb565unorm-webgl":{channels:"rgb",bitsPerChannel:[5,6,5,0],packed:!0},"rgb5a1unorm-webgl":{channels:"rgba",bitsPerChannel:[5,5,5,1],packed:!0},rgb9e5ufloat:{channels:"rgb",packed:!0,render:qP},rg11b10ufloat:{channels:"rgb",bitsPerChannel:[11,11,10,0],packed:!0,p:1,render:Dc},rgb10a2unorm:{channels:"rgba",bitsPerChannel:[10,10,10,2],packed:!0,p:1},rgb10a2uint:{channels:"rgba",bitsPerChannel:[10,10,10,2],packed:!0,p:1},stencil8:{attachment:"stencil",bitsPerChannel:[8,0,0,0],dataType:"uint8"},depth16unorm:{attachment:"depth",bitsPerChannel:[16,0,0,0],dataType:"uint16"},depth24plus:{attachment:"depth",bitsPerChannel:[24,0,0,0],dataType:"uint32"},depth32float:{attachment:"depth",bitsPerChannel:[32,0,0,0],dataType:"float32"},"depth24plus-stencil8":{attachment:"depth-stencil",bitsPerChannel:[24,8,0,0],packed:!0},"depth32float-stencil8":{attachment:"depth-stencil",bitsPerChannel:[32,8,0,0],packed:!0}},ZP={"bc1-rgb-unorm-webgl":{f:Ie},"bc1-rgb-unorm-srgb-webgl":{f:Ie},"bc1-rgba-unorm":{f:Ie},"bc1-rgba-unorm-srgb":{f:Ie},"bc2-rgba-unorm":{f:Ie},"bc2-rgba-unorm-srgb":{f:Ie},"bc3-rgba-unorm":{f:Ie},"bc3-rgba-unorm-srgb":{f:Ie},"bc4-r-unorm":{f:Ie},"bc4-r-snorm":{f:Ie},"bc5-rg-unorm":{f:Ie},"bc5-rg-snorm":{f:Ie},"bc6h-rgb-ufloat":{f:Ie},"bc6h-rgb-float":{f:Ie},"bc7-rgba-unorm":{f:Ie},"bc7-rgba-unorm-srgb":{f:Ie},"etc2-rgb8unorm":{f:Lt},"etc2-rgb8unorm-srgb":{f:Lt},"etc2-rgb8a1unorm":{f:Lt},"etc2-rgb8a1unorm-srgb":{f:Lt},"etc2-rgba8unorm":{f:Lt},"etc2-rgba8unorm-srgb":{f:Lt},"eac-r11unorm":{f:Lt},"eac-r11snorm":{f:Lt},"eac-rg11unorm":{f:Lt},"eac-rg11snorm":{f:Lt},"astc-4x4-unorm":{f:te},"astc-4x4-unorm-srgb":{f:te},"astc-5x4-unorm":{f:te},"astc-5x4-unorm-srgb":{f:te},"astc-5x5-unorm":{f:te},"astc-5x5-unorm-srgb":{f:te},"astc-6x5-unorm":{f:te},"astc-6x5-unorm-srgb":{f:te},"astc-6x6-unorm":{f:te},"astc-6x6-unorm-srgb":{f:te},"astc-8x5-unorm":{f:te},"astc-8x5-unorm-srgb":{f:te},"astc-8x6-unorm":{f:te},"astc-8x6-unorm-srgb":{f:te},"astc-8x8-unorm":{f:te},"astc-8x8-unorm-srgb":{f:te},"astc-10x5-unorm":{f:te},"astc-10x5-unorm-srgb":{f:te},"astc-10x6-unorm":{f:te},"astc-10x6-unorm-srgb":{f:te},"astc-10x8-unorm":{f:te},"astc-10x8-unorm-srgb":{f:te},"astc-10x10-unorm":{f:te},"astc-10x10-unorm-srgb":{f:te},"astc-12x10-unorm":{f:te},"astc-12x10-unorm-srgb":{f:te},"astc-12x12-unorm":{f:te},"astc-12x12-unorm-srgb":{f:te},"pvrtc-rgb4unorm-webgl":{f:Nc},"pvrtc-rgba4unorm-webgl":{f:Nc},"pvrtc-rgb2unorm-webgl":{f:Nc},"pvrtc-rgba2unorm-webgl":{f:Nc},"etc1-rbg-unorm-webgl":{f:GP},"atc-rgb-unorm-webgl":{f:wh},"atc-rgba-unorm-webgl":{f:wh},"atc-rgbai-unorm-webgl":{f:wh}},Xy={...KP,...ZP}});function rM({format:t,width:e,height:r,depth:i,byteAlignment:n}){let o=Ue.getInfo(t),{bytesPerPixel:s,bytesPerBlock:a=s,blockWidth:c=1,blockHeight:l=1,compressed:f=!1}=o,u=f?Math.ceil(e/c):e,d=f?Math.ceil(r/l):r,h=u*a,p=Math.ceil(h/n)*n,g=d,m=p*g*i;return{bytesPerPixel:s,bytesPerRow:p,rowsPerImage:g,depthOrArrayLayers:i,bytesPerImage:p*g,byteLength:m}}function iM(t){let e=Rh(t),r={format:t,create:e.f??!0,render:e.render??!0,filter:e.filter??!0,blend:e.blend??!0,store:e.store??!0},i=Gy(t),n=t.startsWith("depth")||t.startsWith("stencil"),o=i?.signed,s=i?.integer,a=i?.webgl,c=!!i?.compressed;return r.render&&=!n&&!c,r.filter&&=!n&&!o&&!s&&!a,r}function Gy(t){let e=nM(t);if(Ue.isCompressed(t)){e.channels="rgb",e.components=3,e.bytesPerPixel=1,e.srgb=!1,e.compressed=!0,e.bytesPerBlock=sM(t);let i=oM(t);i&&(e.blockWidth=i.blockWidth,e.blockHeight=i.blockHeight)}let r=e.packed?null:QP.exec(t);if(r){let[,i,n,o,s,a]=r,c=`${o}${n}`,l=ke.getDataTypeInfo(c),f=l.byteLength*8,u=i?.length??1,d=[f,u>=2?f:0,u>=3?f:0,u>=4?f:0];e={format:t,attachment:e.attachment,dataType:l.signedType,components:u,channels:i,integer:l.integer,signed:l.signed,normalized:l.normalized,bitsPerChannel:d,bytesPerPixel:l.byteLength*u,packed:e.packed,srgb:e.srgb},a==="-webgl"&&(e.webgl=!0),s==="-srgb"&&(e.srgb=!0)}return t.endsWith("-webgl")&&(e.webgl=!0),t.endsWith("-srgb")&&(e.srgb=!0),e}function nM(t){let e=Rh(t),r=e.bytesPerPixel||1,i=e.bitsPerChannel||[8,8,8,8];return delete e.bitsPerChannel,delete e.bytesPerPixel,delete e.f,delete e.render,delete e.filter,delete e.blend,delete e.store,{...e,format:t,attachment:e.attachment||"color",channels:e.channels||"r",components:e.components||e.channels?.length||1,bytesPerPixel:r,bitsPerChannel:i,dataType:e.dataType||"uint8",srgb:e.srgb??!1,packed:e.packed??!1,webgl:e.webgl??!1,integer:e.integer??!1,signed:e.signed??!1,normalized:e.normalized??!1,compressed:e.compressed??!1}}function oM(t){let r=/.*-(\d+)x(\d+)-.*/.exec(t);if(r){let[,i,n]=r;return{blockWidth:Number(i),blockHeight:Number(n)}}return t.startsWith("bc")||t.startsWith("etc1")||t.startsWith("etc2")||t.startsWith("eac")||t.startsWith("atc")?{blockWidth:4,blockHeight:4}:t.startsWith("pvrtc-rgb4")||t.startsWith("pvrtc-rgba4")?{blockWidth:4,blockHeight:4}:t.startsWith("pvrtc-rgb2")||t.startsWith("pvrtc-rgba2")?{blockWidth:8,blockHeight:4}:null}function sM(t){return t.startsWith("bc1")||t.startsWith("bc4")||t.startsWith("etc1")||t.startsWith("etc2-rgb8")||t.startsWith("etc2-rgb8a1")||t.startsWith("eac-r11")||t==="atc-rgb-unorm-webgl"?8:t.startsWith("bc2")||t.startsWith("bc3")||t.startsWith("bc5")||t.startsWith("bc6h")||t.startsWith("bc7")||t.startsWith("etc2-rgba8")||t.startsWith("eac-rg11")||t.startsWith("astc")||t==="atc-rgba-unorm-webgl"||t==="atc-rgbai-unorm-webgl"?16:t.startsWith("pvrtc")?8:16}var QP,JP,eM,tM,Ph,Ue,Fc=P(()=>{Ic();Ch();QP=/^(r|rg|rgb|rgba|bgra)([0-9]*)([a-z]*)(-srgb)?(-webgl)?$/,JP=["rgb","rgba","bgra"],eM=["depth","stencil"],tM=["bc1","bc2","bc3","bc4","bc5","bc6","bc7","etc1","etc2","eac","atc","astc","pvrtc"],Ph=class{isColor(e){return JP.some(r=>e.startsWith(r))}isDepthStencil(e){return eM.some(r=>e.startsWith(r))}isCompressed(e){return tM.some(r=>e.startsWith(r))}getInfo(e){return Gy(e)}getCapabilities(e){return iM(e)}computeMemoryLayout(e){return rM(e)}},Ue=new Ph});function dn(t){return typeof ImageData<"u"&&t instanceof ImageData||typeof ImageBitmap<"u"&&t instanceof ImageBitmap||typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement||typeof HTMLVideoElement<"u"&&t instanceof HTMLVideoElement||typeof VideoFrame<"u"&&t instanceof VideoFrame||typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas}function Mo(t){if(typeof ImageData<"u"&&t instanceof ImageData||typeof ImageBitmap<"u"&&t instanceof ImageBitmap||typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas)return{width:t.width,height:t.height};if(typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement)return{width:t.naturalWidth,height:t.naturalHeight};if(typeof HTMLVideoElement<"u"&&t instanceof HTMLVideoElement)return{width:t.videoWidth,height:t.videoHeight};if(typeof VideoFrame<"u"&&t instanceof VideoFrame)return{width:t.displayWidth,height:t.displayHeight};throw new Error("Unknown image type")}var Mh=P(()=>{});function aM(t,e){let r=Ih(t),i=e.map(Ih).filter(n=>n!==void 0);return[r,...i].filter(n=>n!==void 0)}function Ih(t){if(t!==void 0){if(t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;if(t instanceof Error)return t.message;if(Array.isArray(t))return t.map(Ih);if(typeof t=="object"){if(cM(t)){let e=String(t);if(e!=="[object Object]")return e}return lM(t)?fM(t):t.constructor?.name||"Object"}return String(t)}}function cM(t){return"toString"in t&&typeof t.toString=="function"&&t.toString!==Object.prototype.toString}function lM(t){return"message"in t&&"type"in t}function fM(t){let e=typeof t.type=="string"?t.type:"message",r=typeof t.message=="string"?t.message:"",i=typeof t.lineNum=="number"?t.lineNum:null,n=typeof t.linePos=="number"?t.linePos:null,o=i!==null&&n!==null?` @ ${i}:${n}`:i!==null?` @ ${i}`:"";return`${e}${o}: ${r}`.trim()}function uM(t,e){return t!=null?!!t:e!==void 0?e!=="production":!1}function dM(){return uM(v.get("debug"),hM())}function hM(){let t=globalThis.process;if(t?.env)return t.env.NODE_ENV}var Io,Oo,ht,Oh=P(()=>{_h();ot();un();Mc();Oc();Fc();Mh();Ch();Io=class{};Oo=class{features;disabledFeatures;constructor(e=[],r){this.features=new Set(e),this.disabledFeatures=r||{}}*[Symbol.iterator](){yield*this.features}has(e){return!this.disabledFeatures?.[e]&&this.features.has(e)}},ht=class t{static defaultProps={id:null,powerPreference:"high-performance",failIfMajorPerformanceCaveat:!1,createCanvasContext:void 0,webgl:{},onError:(e,r)=>{},onResize:(e,r)=>{let[i,n]=e.getDevicePixelSize();v.log(1,`${e} resized => ${i}x${n}px`)()},onPositionChange:(e,r)=>{let[i,n]=e.getPosition();v.log(1,`${e} repositioned => ${i},${n}`)()},onVisibilityChange:e=>v.log(1,`${e} Visibility changed ${e.isVisible}`)(),onDevicePixelRatioChange:(e,r)=>v.log(1,`${e} DPR changed ${r.oldRatio} => ${e.devicePixelRatio}`)(),debug:dM(),debugGPUTime:!1,debugShaders:v.get("debug-shaders")||void 0,debugFramebuffers:!!v.get("debug-framebuffers"),debugFactories:!!v.get("debug-factories"),debugWebGL:!!v.get("debug-webgl"),debugSpectorJS:void 0,debugSpectorJSUrl:void 0,_reuseDevices:!1,_requestMaxLimits:!0,_cacheShaders:!0,_destroyShaders:!1,_cachePipelines:!0,_sharePipelines:!0,_destroyPipelines:!1,_initializeFeatures:!0,_disabledFeatures:{"compilation-status-async-webgl":!0},_handle:void 0};get[Symbol.toStringTag](){return"Device"}toString(){return`Device(${this.id})`}id;props;userData={};statsManager=Pc;_factories={};timestamp=0;_reused=!1;_moduleData={};_textureCaps={};_debugGPUTimeQuery=null;constructor(e){this.props={...t.defaultProps,...e},this.id=this.props.id||Dt(this[Symbol.toStringTag].toLowerCase())}getVertexFormatInfo(e){return or.getVertexFormatInfo(e)}isVertexFormatSupported(e){return!0}getTextureFormatInfo(e){return Ue.getInfo(e)}getTextureFormatCapabilities(e){let r=this._textureCaps[e];if(!r){let i=this._getDeviceTextureFormatCapabilities(e);r=this._getDeviceSpecificTextureFormatCapabilities(i),this._textureCaps[e]=r}return r}getMipLevelCount(e,r,i=1){let n=Math.max(e,r,i);return 1+Math.floor(Math.log2(n))}isExternalImage(e){return dn(e)}getExternalImageSize(e){return Mo(e)}isTextureFormatSupported(e){return this.getTextureFormatCapabilities(e).create}isTextureFormatFilterable(e){return this.getTextureFormatCapabilities(e).filter}isTextureFormatRenderable(e){return this.getTextureFormatCapabilities(e).render}isTextureFormatCompressed(e){return Ue.isCompressed(e)}getSupportedCompressedTextureFormats(){let e=[];for(let r of Object.keys(Yy()))this.isTextureFormatCompressed(r)&&this.isTextureFormatSupported(r)&&e.push(r);return e}pushDebugGroup(e){this.commandEncoder.pushDebugGroup(e)}popDebugGroup(){this.commandEncoder?.popDebugGroup()}insertDebugMarker(e){this.commandEncoder?.insertDebugMarker(e)}loseDevice(){return!1}incrementTimestamp(){return this.timestamp++}reportError(e,r,...i){if(!this.props.onError(e,r)){let o=aM(r,i);return v.error(this.type==="webgl"?"%cWebGL":"%cWebGPU","color: white; background: red; padding: 2px 6px; border-radius: 3px;",e.message,...o)}return()=>{}}debug(){if(this.props.debug)debugger;else v.once(0,`'Type luma.log.set({debug: true}) in console to enable debug breakpoints', +or create a device with the 'debug: true' prop.`)()}getDefaultCanvasContext(){if(!this.canvasContext)throw new Error("Device has no default CanvasContext. See props.createCanvasContext");return this.canvasContext}createFence(){throw new Error("createFence() not implemented")}beginRenderPass(e){return this.commandEncoder.beginRenderPass(e)}beginComputePass(e){return this.commandEncoder.beginComputePass(e)}generateMipmapsWebGPU(e){throw new Error("not implemented")}_createSharedRenderPipelineWebGL(e){throw new Error("_createSharedRenderPipelineWebGL() not implemented")}_createBindGroupLayoutWebGPU(e,r){throw new Error("_createBindGroupLayoutWebGPU() not implemented")}_createBindGroupWebGPU(e,r,i,n,o){throw new Error("_createBindGroupWebGPU() not implemented")}_supportsDebugGPUTime(){return this.features.has("timestamp-query")&&!!(this.props.debug||this.props.debugGPUTime)}_enableDebugGPUTime(e=256){if(!this._supportsDebugGPUTime())return null;if(this._debugGPUTimeQuery)return this._debugGPUTimeQuery;try{this._debugGPUTimeQuery=this.createQuerySet({type:"timestamp",count:e}),this.commandEncoder=this.createCommandEncoder({id:this.commandEncoder.props.id,timeProfilingQuerySet:this._debugGPUTimeQuery})}catch{this._debugGPUTimeQuery=null}return this._debugGPUTimeQuery}_disableDebugGPUTime(){this._debugGPUTimeQuery&&(this.commandEncoder.getTimeProfilingQuerySet()===this._debugGPUTimeQuery&&(this.commandEncoder=this.createCommandEncoder({id:this.commandEncoder.props.id})),this._debugGPUTimeQuery.destroy(),this._debugGPUTimeQuery=null)}_isDebugGPUTimeEnabled(){return this._debugGPUTimeQuery!==null}getCanvasContext(){return this.getDefaultCanvasContext()}readPixelsToArrayWebGL(e,r){throw new Error("not implemented")}readPixelsToBufferWebGL(e,r){throw new Error("not implemented")}setParametersWebGL(e){throw new Error("not implemented")}getParametersWebGL(e){throw new Error("not implemented")}withParametersWebGL(e,r){throw new Error("not implemented")}clearWebGL(e){throw new Error("not implemented")}resetWebGL(){throw new Error("not implemented")}getModuleData(e){return this._moduleData[e]||={},this._moduleData[e]}static _getCanvasContextProps(e){return e.createCanvasContext===!0?{}:e.createCanvasContext}_getDeviceTextureFormatCapabilities(e){let r=Ue.getCapabilities(e),i=o=>(typeof o=="string"?this.features.has(o):o)??!0,n=i(r.create);return{format:e,create:n,render:n&&i(r.render),filter:n&&i(r.filter),blend:n&&i(r.blend),store:n&&i(r.store)}}_normalizeBufferProps(e){(e instanceof ArrayBuffer||ArrayBuffer.isView(e))&&(e={data:e});let r={...e};if((e.usage||0)&j.INDEX&&(e.indexType||(e.data instanceof Uint32Array?r.indexType="uint32":e.data instanceof Uint16Array?r.indexType="uint16":e.data instanceof Uint8Array&&(r.data=new Uint16Array(e.data),r.indexType="uint16")),!r.indexType))throw new Error("indices buffer content must be of type uint16 or uint32");return r}}});var pM,qy,Nh,hn,Ky=P(()=>{Oh();_h();ot();pM="set luma.log.level=1 (or higher) to trace rendering",qy="No matching device found. Ensure `@luma.gl/webgl` and/or `@luma.gl/webgpu` modules are imported.",Nh=class t{static defaultProps={...ht.defaultProps,type:"best-available",adapters:void 0,waitForPageLoad:!0};stats=Pc;log=v;VERSION="9.3.3";spector;preregisteredAdapters=new Map;constructor(){if(globalThis.luma){if(globalThis.luma.VERSION!==this.VERSION)throw v.error(`Found luma.gl ${globalThis.luma.VERSION} while initialzing ${this.VERSION}`)(),v.error("'yarn why @luma.gl/core' can help identify the source of the conflict")(),new Error("luma.gl - multiple versions detected: see console log");v.error("This version of luma.gl has already been initialized")()}v.log(1,`${this.VERSION} - ${pM}`)(),globalThis.luma=this}async createDevice(e={}){let r={...t.defaultProps,...e},i=this.selectAdapter(r.type,r.adapters);if(!i)throw new Error(qy);return r.waitForPageLoad&&await i.pageLoaded,await i.create(r)}async attachDevice(e,r){let i=this._getTypeFromHandle(e,r.adapters),n=i&&this.selectAdapter(i,r.adapters);if(!n)throw new Error(qy);return await n?.attach?.(e,r)}registerAdapters(e){for(let r of e)this.preregisteredAdapters.set(r.type,r)}getSupportedAdapters(e=[]){let r=this._getAdapterMap(e);return Array.from(r).map(([,i])=>i).filter(i=>i.isSupported?.()).map(i=>i.type)}getBestAvailableAdapterType(e=[]){let r=["webgpu","webgl","null"],i=this._getAdapterMap(e);for(let n of r)if(i.get(n)?.isSupported?.())return n;return null}selectAdapter(e,r=[]){let i=e;e==="best-available"&&(i=this.getBestAvailableAdapterType(r));let n=this._getAdapterMap(r);return i&&n.get(i)||null}enforceWebGL2(e=!0,r=[]){let n=this._getAdapterMap(r).get("webgl");n||v.warn("enforceWebGL2: webgl adapter not found")(),n?.enforceWebGL2?.(e)}setDefaultDeviceProps(e){Object.assign(t.defaultProps,e)}_getAdapterMap(e=[]){let r=new Map(this.preregisteredAdapters);for(let i of e)r.set(i.type,i);return r}_getTypeFromHandle(e,r=[]){return e instanceof WebGL2RenderingContext?"webgl":typeof GPUDevice<"u"&&e instanceof GPUDevice||e?.queue?"webgpu":e===null?"null":(e instanceof WebGLRenderingContext?v.warn("WebGL1 is not supported",e)():v.warn("Unknown handle type",e)(),null)}},hn=new Nh});function _M(){return Bc||(mM()||typeof window>"u"?Bc=Promise.resolve():Bc=new Promise(t=>window.addEventListener("load",()=>t()))),Bc}var No,gM,mM,Bc,Zy=P(()=>{Rr();No=class{get pageLoaded(){return _M()}},gM=De()&&typeof document<"u",mM=()=>gM&&document.readyState==="complete",Bc=null});var kc,Qy=P(()=>{kc=class{props;_resizeObserver;_intersectionObserver;_observeDevicePixelRatioTimeout=null;_observeDevicePixelRatioMediaQuery=null;_handleDevicePixelRatioChange=()=>this._refreshDevicePixelRatio();_trackPositionInterval=null;_started=!1;get started(){return this._started}constructor(e){this.props=e}start(){if(!(this._started||!this.props.canvas)){this._started=!0,this._intersectionObserver||=new IntersectionObserver(e=>this.props.onIntersection(e)),this._resizeObserver||=new ResizeObserver(e=>this.props.onResize(e)),this._intersectionObserver.observe(this.props.canvas);try{this._resizeObserver.observe(this.props.canvas,{box:"device-pixel-content-box"})}catch{this._resizeObserver.observe(this.props.canvas,{box:"content-box"})}this._observeDevicePixelRatioTimeout=setTimeout(()=>this._refreshDevicePixelRatio(),0),this.props.trackPosition&&this._trackPosition()}}stop(){this._started&&(this._started=!1,this._observeDevicePixelRatioTimeout&&(clearTimeout(this._observeDevicePixelRatioTimeout),this._observeDevicePixelRatioTimeout=null),this._observeDevicePixelRatioMediaQuery&&(this._observeDevicePixelRatioMediaQuery.removeEventListener("change",this._handleDevicePixelRatioChange),this._observeDevicePixelRatioMediaQuery=null),this._trackPositionInterval&&(clearInterval(this._trackPositionInterval),this._trackPositionInterval=null),this._resizeObserver?.disconnect(),this._intersectionObserver?.disconnect())}_refreshDevicePixelRatio(){this._started&&(this.props.onDevicePixelRatioChange(),this._observeDevicePixelRatioMediaQuery?.removeEventListener("change",this._handleDevicePixelRatioChange),this._observeDevicePixelRatioMediaQuery=matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`),this._observeDevicePixelRatioMediaQuery.addEventListener("change",this._handleDevicePixelRatioChange,{once:!0}))}_trackPosition(e=100){this._trackPositionInterval||(this._trackPositionInterval=setInterval(()=>{this._started?this.props.onPositionChange():this._trackPositionInterval&&(clearInterval(this._trackPositionInterval),this._trackPositionInterval=null)},e))}}});function Jy(){let t,e;return{promise:new Promise((i,n)=>{t=i,e=n}),resolve:t,reject:e}}var ex=P(()=>{});function Dh(t,e){if(!t){let r=new Error(e??"luma.gl assertion failed.");throw Error.captureStackTrace?.(r,Dh),r}}function hi(t,e){return Dh(t,e),t}var Lh=P(()=>{});function yM(t){if(typeof t=="string"){let e=document.getElementById(t);if(!e)throw new Error(`${t} is not an HTML element`);return e}return t||document.body}function xM(t){let e=document.getElementById(t);if(!Nr.isHTMLCanvas(e))throw new Error("Object is not a canvas element");return e}function bM(t){let{width:e,height:r}=t,i=document.createElement("canvas");i.id=Dt("lumagl-auto-created-canvas"),i.width=e||1,i.height=r||1,i.style.width=Number.isFinite(e)?`${e}px`:"100%",i.style.height=Number.isFinite(r)?`${r}px`:"100%",t?.visible||(i.style.visibility="hidden");let n=yM(t?.container||null);return n.insertBefore(i,n.firstChild),i}function TM(t,e,r,i,n){let o=t,s=tx(o[0],e,r),a=rx(o[1],e,i,n),c=tx(o[0]+1,e,r),l=c===r-1?c:c-1;c=rx(o[1]+1,e,i,n);let f;return n?(c=c===0?c:c+1,f=a,a=c):f=c===i-1?c:c-1,{x:s,y:a,width:Math.max(l-s+1,1),height:Math.max(f-a+1,1)}}function tx(t,e,r){return Math.min(Math.round(t*e),r-1)}function rx(t,e,r,i){return i?Math.max(0,r-1-Math.round(t*e)):Math.min(Math.round(t*e),r-1)}var Nr,Fh=P(()=>{Rr();Qy();un();ex();Lh();Nr=class t{static isHTMLCanvas(e){return typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement}static isOffscreenCanvas(e){return typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas}static defaultProps={id:void 0,canvas:null,width:800,height:600,useDevicePixels:!0,autoResize:!0,container:null,visible:!0,alphaMode:"opaque",colorSpace:"srgb",trackPosition:!1};id;props;canvas;htmlCanvas;offscreenCanvas;type;initialized;isInitialized=!1;isVisible=!0;cssWidth;cssHeight;devicePixelRatio;devicePixelWidth;devicePixelHeight;drawingBufferWidth;drawingBufferHeight;_initializedResolvers=Jy();_canvasObserver;_position=[0,0];destroyed=!1;_needsDrawingBufferResize=!0;toString(){return`${this[Symbol.toStringTag]}(${this.id})`}constructor(e){this.props={...t.defaultProps,...e},e=this.props,this.initialized=this._initializedResolvers.promise,De()?e.canvas?typeof e.canvas=="string"?this.canvas=xM(e.canvas):this.canvas=e.canvas:this.canvas=bM(e):this.canvas={width:e.width||1,height:e.height||1},t.isHTMLCanvas(this.canvas)?(this.id=e.id||this.canvas.id,this.type="html-canvas",this.htmlCanvas=this.canvas):t.isOffscreenCanvas(this.canvas)?(this.id=e.id||"offscreen-canvas",this.type="offscreen-canvas",this.offscreenCanvas=this.canvas):(this.id=e.id||"node-canvas-context",this.type="node"),this.cssWidth=this.htmlCanvas?.clientWidth||this.canvas.width,this.cssHeight=this.htmlCanvas?.clientHeight||this.canvas.height,this.devicePixelWidth=this.canvas.width,this.devicePixelHeight=this.canvas.height,this.drawingBufferWidth=this.canvas.width,this.drawingBufferHeight=this.canvas.height,this.devicePixelRatio=globalThis.devicePixelRatio||1,this._position=[0,0],this._canvasObserver=new kc({canvas:this.htmlCanvas,trackPosition:this.props.trackPosition,onResize:r=>this._handleResize(r),onIntersection:r=>this._handleIntersection(r),onDevicePixelRatioChange:()=>this._observeDevicePixelRatio(),onPositionChange:()=>this.updatePosition()})}destroy(){this.destroyed||(this.destroyed=!0,this._stopObservers(),this.device=null)}setProps(e){return"useDevicePixels"in e&&(this.props.useDevicePixels=e.useDevicePixels||!1,this._updateDrawingBufferSize()),this}getCurrentFramebuffer(e){return this._resizeDrawingBufferIfNeeded(),this._getCurrentFramebuffer(e)}getCSSSize(){return[this.cssWidth,this.cssHeight]}getPosition(){return this._position}getDevicePixelSize(){return[this.devicePixelWidth,this.devicePixelHeight]}getDrawingBufferSize(){return[this.drawingBufferWidth,this.drawingBufferHeight]}getMaxDrawingBufferSize(){let e=this.device.limits.maxTextureDimension2D;return[e,e]}setDrawingBufferSize(e,r){e=Math.floor(e),r=Math.floor(r),!(this.drawingBufferWidth===e&&this.drawingBufferHeight===r)&&(this.drawingBufferWidth=e,this.drawingBufferHeight=r,this._needsDrawingBufferResize=!0)}getDevicePixelRatio(){return typeof window<"u"&&window.devicePixelRatio||1}cssToDevicePixels(e,r=!0){let i=this.cssToDeviceRatio(),[n,o]=this.getDrawingBufferSize();return TM(e,i,n,o,r)}getPixelSize(){return this.getDevicePixelSize()}getAspect(){let[e,r]=this.getDrawingBufferSize();return e>0&&r>0?e/r:1}cssToDeviceRatio(){try{let[e]=this.getDrawingBufferSize(),[r]=this.getCSSSize();return r?e/r:1}catch{return 1}}resize(e){this.setDrawingBufferSize(e.width,e.height)}_setAutoCreatedCanvasId(e){this.htmlCanvas?.id==="lumagl-auto-created-canvas"&&(this.htmlCanvas.id=e)}_startObservers(){this.destroyed||this._canvasObserver.start()}_stopObservers(){this._canvasObserver.stop()}_handleIntersection(e){if(this.destroyed)return;let r=e.find(n=>n.target===this.canvas);if(!r)return;let i=r.isIntersecting;this.isVisible!==i&&(this.isVisible=i,this.device.props.onVisibilityChange(this))}_handleResize(e){if(this.destroyed)return;let r=e.find(l=>l.target===this.canvas);if(!r)return;let i=hi(r.contentBoxSize?.[0]);this.cssWidth=i.inlineSize,this.cssHeight=i.blockSize;let n=this.getDevicePixelSize(),o=r.devicePixelContentBoxSize?.[0]?.inlineSize||i.inlineSize*devicePixelRatio,s=r.devicePixelContentBoxSize?.[0]?.blockSize||i.blockSize*devicePixelRatio,[a,c]=this.getMaxDrawingBufferSize();this.devicePixelWidth=Math.max(1,Math.min(o,a)),this.devicePixelHeight=Math.max(1,Math.min(s,c)),this._updateDrawingBufferSize(),this.device.props.onResize(this,{oldPixelSize:n})}_updateDrawingBufferSize(){if(this.props.autoResize)if(typeof this.props.useDevicePixels=="number"){let e=this.props.useDevicePixels;this.setDrawingBufferSize(this.cssWidth*e,this.cssHeight*e)}else this.props.useDevicePixels?this.setDrawingBufferSize(this.devicePixelWidth,this.devicePixelHeight):this.setDrawingBufferSize(this.cssWidth,this.cssHeight);this._initializedResolvers.resolve(),this.isInitialized=!0,this.updatePosition()}_resizeDrawingBufferIfNeeded(){this._needsDrawingBufferResize&&(this._needsDrawingBufferResize=!1,(this.drawingBufferWidth!==this.canvas.width||this.drawingBufferHeight!==this.canvas.height)&&(this.canvas.width=this.drawingBufferWidth,this.canvas.height=this.drawingBufferHeight,this._configureDevice()))}_observeDevicePixelRatio(){if(this.destroyed||!this._canvasObserver.started)return;let e=this.devicePixelRatio;this.devicePixelRatio=window.devicePixelRatio,this.updatePosition(),this.device.props.onDevicePixelRatioChange?.(this,{oldRatio:e})}updatePosition(){if(this.destroyed)return;let e=this.htmlCanvas?.getBoundingClientRect();if(e){let r=[e.left,e.top];if(this._position??=r,r[0]!==this._position[0]||r[1]!==this._position[1]){let n=this._position;this._position=r,this.device.props.onPositionChange?.(this,{oldPosition:n})}}}}});var Do,ix=P(()=>{Fh();Do=class extends Nr{static defaultProps=Nr.defaultProps}});var Lo,nx=P(()=>{Fh();Lo=class extends Nr{}});var pt,Bh=P(()=>{we();pt=class t extends k{static defaultProps={...k.defaultProps,type:"color-sampler",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge",addressModeW:"clamp-to-edge",magFilter:"nearest",minFilter:"nearest",mipmapFilter:"none",lodMinClamp:0,lodMaxClamp:32,compare:"less-equal",maxAnisotropy:1};get[Symbol.toStringTag](){return"Sampler"}constructor(e,r){r=t.normalizeProps(e,r),super(e,r,t.defaultProps)}static normalizeProps(e,r){return r}}});var wM,$,kh=P(()=>{we();Bh();ot();Fc();wM={"1d":"1d","2d":"2d","2d-array":"2d",cube:"2d","cube-array":"2d","3d":"3d"},$=class t extends k{static SAMPLE=4;static STORAGE=8;static RENDER=16;static COPY_SRC=1;static COPY_DST=2;static TEXTURE=4;static RENDER_ATTACHMENT=16;dimension;baseDimension;format;width;height;depth;mipLevels;samples;byteAlignment;ready=Promise.resolve(this);isReady=!0;updateTimestamp;get[Symbol.toStringTag](){return"Texture"}toString(){return`Texture(${this.id},${this.format},${this.width}x${this.height})`}constructor(e,r,i){if(r=t.normalizeProps(e,r),super(e,r,t.defaultProps),this.dimension=this.props.dimension,this.baseDimension=wM[this.dimension],this.format=this.props.format,this.width=this.props.width,this.height=this.props.height,this.depth=this.props.depth,this.mipLevels=this.props.mipLevels,this.samples=this.props.samples||1,this.dimension==="cube"&&(this.depth=6),this.props.width===void 0||this.props.height===void 0)if(e.isExternalImage(r.data)){let n=e.getExternalImageSize(r.data);this.width=n?.width||1,this.height=n?.height||1}else this.width=1,this.height=1,(this.props.width===void 0||this.props.height===void 0)&&v.warn(`${this} created with undefined width or height. This is deprecated. Use DynamicTexture instead.`)();this.byteAlignment=i?.byteAlignment||1,this.updateTimestamp=e.incrementTimestamp()}clone(e){return this.device.createTexture({...this.props,...e})}setSampler(e){this.sampler=e instanceof pt?e:this.device.createSampler(e)}copyImageData(e){let{data:r,depth:i,...n}=e;this.writeData(r,{...n,depthOrArrayLayers:n.depthOrArrayLayers??i})}computeMemoryLayout(e={}){let r=this._normalizeTextureReadOptions(e),{width:i=this.width,height:n=this.height,depthOrArrayLayers:o=this.depth}=r,{format:s,byteAlignment:a}=this;return Ue.computeMemoryLayout({format:s,width:i,height:n,depth:o,byteAlignment:a})}readBuffer(e,r){throw new Error("readBuffer not implemented")}readDataAsync(e){throw new Error("readBuffer not implemented")}writeBuffer(e,r){throw new Error("readBuffer not implemented")}writeData(e,r){throw new Error("readBuffer not implemented")}readDataSyncWebGL(e){throw new Error("readDataSyncWebGL not available")}generateMipmapsWebGL(){throw new Error("generateMipmapsWebGL not available")}static normalizeProps(e,r){let i={...r},{width:n,height:o}=i;return typeof n=="number"&&(i.width=Math.max(1,Math.ceil(n))),typeof o=="number"&&(i.height=Math.max(1,Math.ceil(o))),i}_initializeData(e){this.device.isExternalImage(e)?this.copyExternalImage({image:e,width:this.width,height:this.height,depth:this.depth,mipLevel:0,x:0,y:0,z:0,aspect:"all",colorSpace:"srgb",premultipliedAlpha:!1,flipY:!1}):e&&this.copyImageData({data:e,mipLevel:0,x:0,y:0,z:0,aspect:"all"})}_normalizeCopyImageDataOptions(e){let{data:r,depth:i,...n}=e,o=this._normalizeTextureWriteOptions({...n,depthOrArrayLayers:n.depthOrArrayLayers??i});return{data:r,depth:o.depthOrArrayLayers,...o}}_normalizeCopyExternalImageOptions(e){let r=t._omitUndefined(e),i=r.mipLevel??0,n=this._getMipLevelSize(i),o=this.device.getExternalImageSize(e.image),s={...t.defaultCopyExternalImageOptions,...n,...o,...r};return s.width=Math.min(s.width,n.width-s.x),s.height=Math.min(s.height,n.height-s.y),s.depth=Math.min(s.depth,n.depthOrArrayLayers-s.z),s}_normalizeTextureReadOptions(e){let r=t._omitUndefined(e),i=r.mipLevel??0,n=this._getMipLevelSize(i),o={...t.defaultTextureReadOptions,...n,...r};return o.width=Math.min(o.width,n.width-o.x),o.height=Math.min(o.height,n.height-o.y),o.depthOrArrayLayers=Math.min(o.depthOrArrayLayers,n.depthOrArrayLayers-o.z),o}_getSupportedColorReadOptions(e){let r=this._normalizeTextureReadOptions(e),i=Ue.getInfo(this.format);switch(this._validateColorReadAspect(r),this._validateColorReadFormat(i),this.dimension){case"2d":case"cube":case"cube-array":case"2d-array":case"3d":return r;default:throw new Error(`${this} color readback does not support ${this.dimension} textures`)}}_validateColorReadAspect(e){if(e.aspect!=="all")throw new Error(`${this} color readback only supports aspect 'all'`)}_validateColorReadFormat(e){if(e.compressed)throw new Error(`${this} color readback does not support compressed formats (${this.format})`);switch(e.attachment){case"color":return;case"depth":throw new Error(`${this} color readback does not support depth formats (${this.format})`);case"stencil":throw new Error(`${this} color readback does not support stencil formats (${this.format})`);case"depth-stencil":throw new Error(`${this} color readback does not support depth-stencil formats (${this.format})`);default:throw new Error(`${this} color readback does not support format ${this.format}`)}}_normalizeTextureWriteOptions(e){let r=t._omitUndefined(e),i=r.mipLevel??0,n=this._getMipLevelSize(i),o={...t.defaultTextureWriteOptions,...n,...r};o.width=Math.min(o.width,n.width-o.x),o.height=Math.min(o.height,n.height-o.y),o.depthOrArrayLayers=Math.min(o.depthOrArrayLayers,n.depthOrArrayLayers-o.z);let s=Ue.computeMemoryLayout({format:this.format,width:o.width,height:o.height,depth:o.depthOrArrayLayers,byteAlignment:this.byteAlignment}),a=s.bytesPerPixel*o.width;if(o.bytesPerRow=r.bytesPerRow??s.bytesPerRow,o.rowsPerImage=r.rowsPerImage??o.height,o.bytesPerRow>e),i=this.baseDimension==="1d"?1:Math.max(1,this.height>>e),n=this.dimension==="3d"?Math.max(1,this.depth>>e):this.depth;return{width:r,height:i,depthOrArrayLayers:n}}getAllocatedByteLength(){let e=0;for(let r=0;rr!==void 0))}static defaultProps={...k.defaultProps,data:null,dimension:"2d",format:"rgba8unorm",usage:t.SAMPLE|t.RENDER|t.COPY_DST,width:void 0,height:void 0,depth:1,mipLevels:1,samples:void 0,sampler:{},view:void 0};static defaultCopyDataOptions={data:void 0,byteOffset:0,bytesPerRow:void 0,rowsPerImage:void 0,width:void 0,height:void 0,depthOrArrayLayers:void 0,depth:1,mipLevel:0,x:0,y:0,z:0,aspect:"all"};static defaultCopyExternalImageOptions={image:void 0,sourceX:0,sourceY:0,width:void 0,height:void 0,depth:1,mipLevel:0,x:0,y:0,z:0,aspect:"all",colorSpace:"srgb",premultipliedAlpha:!1,flipY:!1};static defaultTextureReadOptions={x:0,y:0,z:0,width:void 0,height:void 0,depthOrArrayLayers:1,mipLevel:0,aspect:"all"};static defaultTextureWriteOptions={byteOffset:0,bytesPerRow:void 0,rowsPerImage:void 0,x:0,y:0,z:0,width:void 0,height:void 0,depthOrArrayLayers:1,mipLevel:0,aspect:"all"}}});var pi,ox=P(()=>{we();pi=class t extends k{get[Symbol.toStringTag](){return"TextureView"}constructor(e,r){super(e,r,t.defaultProps)}static defaultProps={...k.defaultProps,format:void 0,dimension:void 0,aspect:"all",baseMipLevel:0,mipLevelCount:void 0,baseArrayLayer:0,arrayLayerCount:void 0}}});function sx(t,e,r){let i="",n=e.split(/\r?\n/),o=t.slice().sort((s,a)=>s.lineNum-a.lineNum);switch(r?.showSourceCode||"no"){case"all":let s=0;for(let a=1;a<=n.length;a++){let c=n[a-1],l=o[s];for(c&&l&&(i+=ax(c,a,r));o.length>s&&l.lineNum===a;){let f=o[s++];f&&(i+=Uh(f,n,f.lineNum,{...r,inlineSource:!1}))}}for(;o.length>s;){let a=o[s++];a&&(i+=Uh(a,[],0,{...r,inlineSource:!1}))}return i;case"issues":case"no":for(let a of t)i+=Uh(a,n,a.lineNum,{inlineSource:r?.showSourceCode!=="no"});return i}}function Uh(t,e,r,i){if(i?.inlineSource){let o=SM(e,r),s=t.linePos>0?`${" ".repeat(t.linePos+5)}^^^ +`:"";return` +${o}${s}${t.type.toUpperCase()}: ${t.message} + +`}let n=t.type==="error"?"red":"orange";return i?.html?`
${t.type.toUpperCase()}: ${t.message}
`:`${t.type.toUpperCase()}: ${t.message}`}function SM(t,e,r){let i="";for(let n=e-2;n<=e;n++){let o=t[n-1];o!==void 0&&(i+=ax(o,e,r))}return i}function ax(t,e,r){let i=r?.html?vM(t):t;return`${AM(String(e),4)}: ${i}${r?.html?"
":` +`}`}function AM(t,e){let r="";for(let i=t.length;i",">").replaceAll('"',""").replaceAll("'","'")}var cx=P(()=>{});function EM(t){return RM(t.source)||t.id||Dt(`unnamed ${t.stage}-shader`)}function RM(t,e="unnamed"){return/#define[\s*]SHADER_NAME[\s*]([A-Za-z0-9_-]+)[\s*]/.exec(t)?.[1]??e}var gi,zh=P(()=>{we();un();cx();gi=class t extends k{get[Symbol.toStringTag](){return"Shader"}stage;source;compilationStatus="pending";constructor(e,r){r={...r,debugShaders:r.debugShaders||e.props.debugShaders||"errors"},super(e,{id:EM(r),...r},t.defaultProps),this.stage=this.props.stage,this.source=this.props.source}getCompilationInfoSync(){return null}getTranslatedSource(){return null}async debugShader(){let e=this.props.debugShaders;switch(e){case"never":return;case"errors":if(this.compilationStatus==="success")return;break;case"warnings":case"always":break}let r=await this.getCompilationInfo();e==="warnings"&&r?.length===0||this._displayShaderLog(r,this.id)}_displayShaderLog(e,r){if(typeof document>"u"||!document?.createElement)return;let i=r,n=`${this.stage} shader "${i}"`,o=sx(e,this.source,{showSourceCode:"all",html:!0}),s=this.getTranslatedSource(),a=document.createElement("div");a.innerHTML=`

Compilation error in ${n}

+
+
+ +
+
${o}
`,s&&(a.innerHTML+=`

Translated Source



${s}
`),a.style.top="0",a.style.left="0",a.style.background="white",a.style.position="fixed",a.style.zIndex="9999",a.style.maxWidth="100vw",a.style.maxHeight="100vh",a.style.overflowY="auto",document.body.appendChild(a),a.querySelector(".luma-compiler-log-error")?.scrollIntoView(),a.querySelector("button#close").onclick=()=>{a.remove()},a.querySelector("button#copy").onclick=()=>{navigator.clipboard.writeText(this.source)}}static defaultProps={...k.defaultProps,language:"auto",stage:void 0,source:"",sourceMap:null,entryPoint:"main",debugShaders:void 0}}});var mi,lx=P(()=>{we();kh();ot();mi=class t extends k{get[Symbol.toStringTag](){return"Framebuffer"}width;height;constructor(e,r={}){super(e,r,t.defaultProps),this.width=this.props.width,this.height=this.props.height}clone(e){let r=this.colorAttachments.map(n=>n.texture.clone(e)),i=this.depthStencilAttachment&&this.depthStencilAttachment.texture.clone(e);return this.device.createFramebuffer({...this.props,...e,colorAttachments:r,depthStencilAttachment:i})}resize(e){let r=!e;if(e){let[i,n]=Array.isArray(e)?e:[e.width,e.height];r=r||n!==this.height||i!==this.width,this.width=i,this.height=n}r&&(v.log(2,`Resizing framebuffer ${this.id} to ${this.width}x${this.height}`)(),this.resizeAttachments(this.width,this.height))}autoCreateAttachmentTextures(){if(this.props.colorAttachments.length===0&&!this.props.depthStencilAttachment)throw new Error("Framebuffer has noattachments");this.colorAttachments=this.props.colorAttachments.map((r,i)=>{if(typeof r=="string"){let n=this.createColorTexture(r,i);return this.attachResource(n),n.view}return r instanceof $?r.view:r});let e=this.props.depthStencilAttachment;if(e)if(typeof e=="string"){let r=this.createDepthStencilTexture(e);this.attachResource(r),this.depthStencilAttachment=r.view}else e instanceof $?this.depthStencilAttachment=e.view:this.depthStencilAttachment=e}createColorTexture(e,r){return this.device.createTexture({id:`${this.id}-color-attachment-${r}`,usage:$.RENDER_ATTACHMENT,format:e,width:this.width,height:this.height,sampler:{magFilter:"linear",minFilter:"linear"}})}createDepthStencilTexture(e){return this.device.createTexture({id:`${this.id}-depth-stencil-attachment`,usage:$.RENDER_ATTACHMENT,format:e,width:this.width,height:this.height})}resizeAttachments(e,r){if(this.colorAttachments.forEach((i,n)=>{let o=i.texture.clone({width:e,height:r});this.destroyAttachedResource(i),this.colorAttachments[n]=o.view,this.attachResource(o.view)}),this.depthStencilAttachment){let i=this.depthStencilAttachment.texture.clone({width:e,height:r});this.destroyAttachedResource(this.depthStencilAttachment),this.depthStencilAttachment=i.view,this.attachResource(i)}this.updateAttachments()}static defaultProps={...k.defaultProps,width:1,height:1,colorAttachments:[],depthStencilAttachment:null}}});var st,Wh=P(()=>{we();st=class t extends k{get[Symbol.toStringTag](){return"RenderPipeline"}shaderLayout;bufferLayout;linkStatus="pending";hash="";sharedRenderPipeline=null;get isPending(){return this.linkStatus==="pending"||this.vs.compilationStatus==="pending"||this.fs?.compilationStatus==="pending"}get isErrored(){return this.linkStatus==="error"||this.vs.compilationStatus==="error"||this.fs?.compilationStatus==="error"}constructor(e,r){super(e,r,t.defaultProps),this.shaderLayout=this.props.shaderLayout,this.bufferLayout=this.props.bufferLayout||[],this.sharedRenderPipeline=this.props._sharedRenderPipeline||null}static defaultProps={...k.defaultProps,vs:null,vertexEntryPoint:"vertexMain",vsConstants:{},fs:null,fragmentEntryPoint:"fragmentMain",fsConstants:{},shaderLayout:null,bufferLayout:[],topology:"triangle-list",colorAttachmentFormats:void 0,depthStencilAttachmentFormat:void 0,parameters:{},varyings:void 0,bufferMode:void 0,disableWarnings:!1,_sharedRenderPipeline:void 0,bindings:void 0,bindGroups:void 0}}});var Fo,fx=P(()=>{we();Fo=class extends k{get[Symbol.toStringTag](){return"SharedRenderPipeline"}constructor(e,r){super(e,r,{...k.defaultProps,handle:void 0,vs:void 0,fs:void 0,varyings:void 0,bufferMode:void 0})}}});var Bo,ux=P(()=>{we();Bo=class t extends k{get[Symbol.toStringTag](){return"ComputePipeline"}hash="";shaderLayout;constructor(e,r){super(e,r,t.defaultProps),this.shaderLayout=r.shaderLayout}static defaultProps={...k.defaultProps,shader:void 0,entryPoint:void 0,constants:{},shaderLayout:void 0}}});var ko,dx=P(()=>{ux();Wh();ot();un();ko=class t{static defaultProps={...st.defaultProps};static getDefaultPipelineFactory(e){let r=e.getModuleData("@luma.gl/core");return r.defaultPipelineFactory||=new t(e),r.defaultPipelineFactory}device;_hashCounter=0;_hashes={};_renderPipelineCache={};_computePipelineCache={};_sharedRenderPipelineCache={};get[Symbol.toStringTag](){return"PipelineFactory"}toString(){return`PipelineFactory(${this.device.id})`}constructor(e){this.device=e}createRenderPipeline(e){if(!this.device.props._cachePipelines)return this.device.createRenderPipeline(e);let r={...st.defaultProps,...e},i=this._renderPipelineCache,n=this._hashRenderPipeline(r),o=i[n]?.resource;if(o)i[n].useCount++,this.device.props.debugFactories&&v.log(3,`${this}: ${i[n].resource} reused, count=${i[n].useCount}, (id=${e.id})`)();else{let s=this.device.type==="webgl"&&this.device.props._sharePipelines?this.createSharedRenderPipeline(r):void 0;o=this.device.createRenderPipeline({...r,id:r.id?`${r.id}-cached`:Dt("unnamed-cached"),_sharedRenderPipeline:s}),o.hash=n,i[n]={resource:o,useCount:1},this.device.props.debugFactories&&v.log(3,`${this}: ${o} created, count=${i[n].useCount}`)()}return o}createComputePipeline(e){if(!this.device.props._cachePipelines)return this.device.createComputePipeline(e);let r={...Bo.defaultProps,...e},i=this._computePipelineCache,n=this._hashComputePipeline(r),o=i[n]?.resource;return o?(i[n].useCount++,this.device.props.debugFactories&&v.log(3,`${this}: ${i[n].resource} reused, count=${i[n].useCount}, (id=${e.id})`)()):(o=this.device.createComputePipeline({...r,id:r.id?`${r.id}-cached`:void 0}),o.hash=n,i[n]={resource:o,useCount:1},this.device.props.debugFactories&&v.log(3,`${this}: ${o} created, count=${i[n].useCount}`)()),o}release(e){if(!this.device.props._cachePipelines){e.destroy();return}let r=this._getCache(e),i=e.hash;r[i].useCount--,r[i].useCount===0?(this._destroyPipeline(e),this.device.props.debugFactories&&v.log(3,`${this}: ${e} released and destroyed`)()):r[i].useCount<0?(v.error(`${this}: ${e} released, useCount < 0, resetting`)(),r[i].useCount=0):this.device.props.debugFactories&&v.log(3,`${this}: ${e} released, count=${r[i].useCount}`)()}createSharedRenderPipeline(e){let r=this._hashSharedRenderPipeline(e),i=this._sharedRenderPipelineCache[r];return i||(i={resource:this.device._createSharedRenderPipelineWebGL(e),useCount:0},this._sharedRenderPipelineCache[r]=i),i.useCount++,i.resource}releaseSharedRenderPipeline(e){if(!e.sharedRenderPipeline)return;let r=this._hashSharedRenderPipeline(e.sharedRenderPipeline.props),i=this._sharedRenderPipelineCache[r];i&&(i.useCount--,i.useCount===0&&(i.resource.destroy(),delete this._sharedRenderPipelineCache[r]))}_destroyPipeline(e){let r=this._getCache(e);return this.device.props._destroyPipelines?(delete r[e.hash],e.destroy(),e instanceof st&&this.releaseSharedRenderPipeline(e),!0):!1}_getCache(e){let r;if(e instanceof Bo&&(r=this._computePipelineCache),e instanceof st&&(r=this._renderPipelineCache),!r)throw new Error(`${this}`);if(!r[e.hash])throw new Error(`${this}: ${e} matched incorrect entry`);return r}_hashComputePipeline(e){let{type:r}=this.device,i=this._getHash(e.shader.source),n=this._getHash(JSON.stringify(e.shaderLayout));return`${r}/C/${i}SL${n}`}_hashRenderPipeline(e){let r=e.vs?this._getHash(e.vs.source):0,i=e.fs?this._getHash(e.fs.source):0,n=this._getWebGLVaryingHash(e),o=this._getHash(JSON.stringify(e.shaderLayout)),s=this._getHash(JSON.stringify(e.bufferLayout)),{type:a}=this.device;if(a==="webgl"){let c=this._getHash(JSON.stringify(e.parameters));return`${a}/R/${r}/${i}V${n}T${e.topology}P${c}SL${o}BL${s}`}else{let l=this._getHash(JSON.stringify({vertexEntryPoint:e.vertexEntryPoint,fragmentEntryPoint:e.fragmentEntryPoint})),f=this._getHash(JSON.stringify(e.parameters)),u=this._getWebGPUAttachmentHash(e);return`${a}/R/${r}/${i}V${n}T${e.topology}EP${l}P${f}SL${o}BL${s}A${u}`}}_hashSharedRenderPipeline(e){let r=e.vs?this._getHash(e.vs.source):0,i=e.fs?this._getHash(e.fs.source):0,n=this._getWebGLVaryingHash(e);return`webgl/S/${r}/${i}V${n}`}_getHash(e){return this._hashes[e]===void 0&&(this._hashes[e]=this._hashCounter++),this._hashes[e]}_getWebGLVaryingHash(e){let{varyings:r=[],bufferMode:i=null}=e;return this._getHash(JSON.stringify({varyings:r,bufferMode:i}))}_getWebGPUAttachmentHash(e){let r=e.colorAttachmentFormats??[this.device.preferredColorFormat],i=e.parameters?.depthWriteEnabled?e.depthStencilAttachmentFormat||this.device.preferredDepthFormat:null;return this._getHash(JSON.stringify({colorAttachmentFormats:r,depthStencilAttachmentFormat:i}))}}});var Uo,hx=P(()=>{zh();ot();Uo=class t{static defaultProps={...gi.defaultProps};static getDefaultShaderFactory(e){let r=e.getModuleData("@luma.gl/core");return r.defaultShaderFactory||=new t(e),r.defaultShaderFactory}device;_cache={};get[Symbol.toStringTag](){return"ShaderFactory"}toString(){return`${this[Symbol.toStringTag]}(${this.device.id})`}constructor(e){this.device=e}createShader(e){if(!this.device.props._cacheShaders)return this.device.createShader(e);let r=this._hashShader(e),i=this._cache[r];if(i)i.useCount++,this.device.props.debugFactories&&v.log(3,`${this}: Reusing shader ${i.resource.id} count=${i.useCount}`)();else{let n=this.device.createShader({...e,id:e.id?`${e.id}-cached`:void 0});this._cache[r]=i={resource:n,useCount:1},this.device.props.debugFactories&&v.log(3,`${this}: Created new shader ${n.id}`)()}return i.resource}release(e){if(!this.device.props._cacheShaders){e.destroy();return}let r=this._hashShader(e),i=this._cache[r];if(i)if(i.useCount--,i.useCount===0)this.device.props._destroyShaders&&(delete this._cache[r],i.resource.destroy(),this.device.props.debugFactories&&v.log(3,`${this}: Releasing shader ${e.id}, destroyed`)());else{if(i.useCount<0)throw new Error(`ShaderFactory: Shader ${e.id} released too many times`);this.device.props.debugFactories&&v.log(3,`${this}: Releasing shader ${e.id} count=${i.useCount}`)()}}_hashShader(e){return`${e.stage}:${e.source}`}}});function px(t,e,r){let i=t.bindings.find(n=>n.name===e||`${n.name.toLocaleLowerCase()}uniforms`===e.toLocaleLowerCase());return!i&&!r?.ignoreWarnings&&v.warn(`Binding ${e} not set: Not found in shader layout.`)(),i||null}function zo(t,e){if(!e)return{};if(CM(e))return Object.fromEntries(Object.entries(e).map(([n,o])=>[Number(n),{...o}]));let r={};for(let[i,n]of Object.entries(e)){let s=px(t,i)?.group??0;r[s]||={},r[s][i]=n}return r}function Uc(t){let e={};for(let r of Object.values(t))Object.assign(e,r);return e}function CM(t){let e=Object.keys(t);return e.length>0&&e.every(r=>/^\d+$/.test(r))}var gx=P(()=>{ot()});var Wo,mx=P(()=>{we();Wo=class t extends k{static defaultClearColor=[0,0,0,1];static defaultClearDepth=1;static defaultClearStencil=0;get[Symbol.toStringTag](){return"RenderPass"}constructor(e,r){r=t.normalizeProps(e,r),super(e,r,t.defaultProps)}static normalizeProps(e,r){return r}static defaultProps={...k.defaultProps,framebuffer:null,parameters:void 0,clearColor:t.defaultClearColor,clearColors:void 0,clearDepth:t.defaultClearDepth,clearStencil:t.defaultClearStencil,depthReadOnly:!1,stencilReadOnly:!1,discard:!1,occlusionQuerySet:void 0,timestampQuerySet:void 0,beginTimestampIndex:void 0,endTimestampIndex:void 0}}});var Vo,_x=P(()=>{we();Vo=class t extends k{get[Symbol.toStringTag](){return"CommandEncoder"}_timeProfilingQuerySet=null;_timeProfilingSlotCount=0;_gpuTimeMs;constructor(e,r){super(e,r,t.defaultProps),this._timeProfilingQuerySet=r.timeProfilingQuerySet??null,this._timeProfilingSlotCount=0,this._gpuTimeMs=void 0}async resolveTimeProfilingQuerySet(){if(this._gpuTimeMs=void 0,!this._timeProfilingQuerySet)return;let e=Math.floor(this._timeProfilingSlotCount/2);if(e<=0)return;let r=e*2,i=await this._timeProfilingQuerySet.readResults({firstQuery:0,queryCount:r}),n=0n;for(let o=0;o=this._timeProfilingQuerySet.props.count?r:(this._timeProfilingSlotCount+=2,{...r,timestampQuerySet:this._timeProfilingQuerySet,beginTimestampIndex:i,endTimestampIndex:i+1})}_supportsTimestampQueries(){return this.device.features.has("timestamp-query")}static defaultProps={...k.defaultProps,measureExecutionTime:void 0,timeProfilingQuerySet:void 0}}});var jo,yx=P(()=>{we();jo=class t extends k{get[Symbol.toStringTag](){return"CommandBuffer"}constructor(e,r){super(e,r,t.defaultProps)}static defaultProps={...k.defaultProps}}});function pn(t){let e=zc(t),r=OM[e];if(!r)throw new Error(`Unsupported variable shader type: ${t}`);return r}function xx(t){let e=bx(t),r=IM[e];if(!r)throw new Error(`Unsupported attribute shader type: ${t}`);let[i,n]=r,o=i==="i32"||i==="u32",s=i!=="u32",a=MM[i]*n;return{primitiveType:i,components:n,byteLength:a,integer:o,signed:s}}function PM(t,e){return e===1?t:`vec${e}<${t}>`}function bx(t){return NM[t]||t}function zc(t){return DM[t]||t}var Vh,jh,MM,IM,OM,NM,DM,Wc=P(()=>{Vh=class{getVariableShaderTypeInfo(e){return pn(e)}getAttributeShaderTypeInfo(e){return xx(e)}makeShaderAttributeType(e,r){return PM(e,r)}resolveAttributeShaderTypeAlias(e){return bx(e)}resolveVariableShaderTypeAlias(e){return zc(e)}};jh=new Vh,MM={f32:4,f16:2,i32:4,u32:4},IM={f32:["f32",1],"vec2":["f32",2],"vec3":["f32",3],"vec4":["f32",4],f16:["f16",1],"vec2":["f16",2],"vec3":["f16",3],"vec4":["f16",4],i32:["i32",1],"vec2":["i32",2],"vec3":["i32",3],"vec4":["i32",4],u32:["u32",1],"vec2":["u32",2],"vec3":["u32",3],"vec4":["u32",4]},OM={f32:{type:"f32",components:1},f16:{type:"f16",components:1},i32:{type:"i32",components:1},u32:{type:"u32",components:1},"vec2":{type:"f32",components:2},"vec3":{type:"f32",components:3},"vec4":{type:"f32",components:4},"vec2":{type:"f16",components:2},"vec3":{type:"f16",components:3},"vec4":{type:"f16",components:4},"vec2":{type:"i32",components:2},"vec3":{type:"i32",components:3},"vec4":{type:"i32",components:4},"vec2":{type:"u32",components:2},"vec3":{type:"u32",components:3},"vec4":{type:"u32",components:4},"mat2x2":{type:"f32",components:4},"mat2x3":{type:"f32",components:6},"mat2x4":{type:"f32",components:8},"mat3x2":{type:"f32",components:6},"mat3x3":{type:"f32",components:9},"mat3x4":{type:"f32",components:12},"mat4x2":{type:"f32",components:8},"mat4x3":{type:"f32",components:12},"mat4x4":{type:"f32",components:16},"mat2x2":{type:"f16",components:4},"mat2x3":{type:"f16",components:6},"mat2x4":{type:"f16",components:8},"mat3x2":{type:"f16",components:6},"mat3x3":{type:"f16",components:9},"mat3x4":{type:"f16",components:12},"mat4x2":{type:"f16",components:8},"mat4x3":{type:"f16",components:12},"mat4x4":{type:"f16",components:16},"mat2x2":{type:"i32",components:4},"mat2x3":{type:"i32",components:6},"mat2x4":{type:"i32",components:8},"mat3x2":{type:"i32",components:6},"mat3x3":{type:"i32",components:9},"mat3x4":{type:"i32",components:12},"mat4x2":{type:"i32",components:8},"mat4x3":{type:"i32",components:12},"mat4x4":{type:"i32",components:16},"mat2x2":{type:"u32",components:4},"mat2x3":{type:"u32",components:6},"mat2x4":{type:"u32",components:8},"mat3x2":{type:"u32",components:6},"mat3x3":{type:"u32",components:9},"mat3x4":{type:"u32",components:12},"mat4x2":{type:"u32",components:8},"mat4x3":{type:"u32",components:12},"mat4x4":{type:"u32",components:16}},NM={vec2i:"vec2",vec3i:"vec3",vec4i:"vec4",vec2u:"vec2",vec3u:"vec3",vec4u:"vec4",vec2f:"vec2",vec3f:"vec3",vec4f:"vec4",vec2h:"vec2",vec3h:"vec3",vec4h:"vec4"},DM={vec2i:"vec2",vec3i:"vec3",vec4i:"vec4",vec2u:"vec2",vec3u:"vec3",vec4u:"vec4",vec2f:"vec2",vec3f:"vec3",vec4f:"vec4",vec2h:"vec2",vec3h:"vec3",vec4h:"vec4",mat2x2f:"mat2x2",mat2x3f:"mat2x3",mat2x4f:"mat2x4",mat3x2f:"mat3x2",mat3x3f:"mat3x3",mat3x4f:"mat3x4",mat4x2f:"mat4x2",mat4x3f:"mat4x3",mat4x4f:"mat4x4",mat2x2i:"mat2x2",mat2x3i:"mat2x3",mat2x4i:"mat2x4",mat3x2i:"mat3x2",mat3x3i:"mat3x3",mat3x4i:"mat3x4",mat4x2i:"mat4x2",mat4x3i:"mat4x3",mat4x4i:"mat4x4",mat2x2u:"mat2x2",mat2x3u:"mat2x3",mat2x4u:"mat2x4",mat3x2u:"mat3x2",mat3x3u:"mat3x3",mat3x4u:"mat3x4",mat4x2u:"mat4x2",mat4x3u:"mat4x3",mat4x4u:"mat4x4",mat2x2h:"mat2x2",mat2x3h:"mat2x3",mat2x4h:"mat2x4",mat3x2h:"mat3x2",mat3x3h:"mat3x3",mat3x4h:"mat3x4",mat4x2h:"mat4x2",mat4x3h:"mat4x3",mat4x4h:"mat4x4"}});function Vc(t,e){let r={};for(let i of t.attributes){let n=LM(t,e,i.name);n&&(r[i.name]=n)}return r}function Tx(t,e,r=16){let i=Vc(t,e),n=new Array(r).fill(null);for(let o of Object.values(i))n[o.location]=o;return n}function LM(t,e,r){let i=FM(t,r),n=BM(e,r);if(!i)return null;let o=jh.getAttributeShaderTypeInfo(i.type),s=or.getCompatibleVertexFormat(o),a=n?.vertexFormat||s,c=or.getVertexFormatInfo(a);return{attributeName:n?.attributeName||i.name,bufferName:n?.bufferName||i.name,location:i.location,shaderType:i.type,primitiveType:o.primitiveType,shaderComponents:o.components,vertexFormat:a,bufferDataType:c.type,bufferComponents:c.components,normalized:c.normalized,integer:o.integer,stepMode:n?.stepMode||i.stepMode||"vertex",byteOffset:n?.byteOffset||0,byteStride:n?.byteStride||0}}function FM(t,e){let r=t.attributes.find(i=>i.name===e);return r||v.warn(`shader layout attribute "${e}" not present in shader`),r||null}function BM(t,e){kM(t);let r=UM(t,e);return r||(r=zM(t,e),r)?r:(v.warn(`layout for attribute "${e}" not present in buffer layout`),null)}function kM(t){for(let e of t)(e.attributes&&e.format||!e.attributes&&!e.format)&&v.warn(`BufferLayout ${name} must have either 'attributes' or 'format' field`)}function UM(t,e){for(let r of t)if(r.format&&r.name===e)return{attributeName:r.name,bufferName:e,stepMode:r.stepMode,vertexFormat:r.format,byteOffset:0,byteStride:r.byteStride||0};return null}function zM(t,e){for(let r of t){let i=r.byteStride;if(typeof r.byteStride!="number")for(let o of r.attributes||[]){let s=or.getVertexFormatInfo(o.format);i+=s.byteLength}let n=r.attributes?.find(o=>o.attribute===e);if(n)return{attributeName:n.attribute,bufferName:r.name,stepMode:r.stepMode,vertexFormat:n.format,byteOffset:n.byteOffset,byteStride:i}}return null}var $h=P(()=>{ot();Wc();Oc()});var $o,wx=P(()=>{$h();we();$o=class t extends k{static defaultProps={...k.defaultProps,shaderLayout:void 0,bufferLayout:[]};get[Symbol.toStringTag](){return"VertexArray"}maxVertexAttributes;attributeInfos;indexBuffer=null;attributes;constructor(e,r){super(e,r,t.defaultProps),this.maxVertexAttributes=e.limits.maxVertexAttributes,this.attributes=new Array(this.maxVertexAttributes).fill(null),this.attributeInfos=Tx(r.shaderLayout,r.bufferLayout,this.maxVertexAttributes)}setConstantWebGL(e,r){this.device.reportError(new Error("constant attributes not supported"),this)()}}});var Ho,Sx=P(()=>{we();Ho=class t extends k{static defaultProps={...k.defaultProps,layout:void 0,buffers:{}};get[Symbol.toStringTag](){return"TransformFeedback"}constructor(e,r){super(e,r,t.defaultProps)}}});var Yo,Ax=P(()=>{we();Yo=class t extends k{get[Symbol.toStringTag](){return"QuerySet"}constructor(e,r){super(e,r,t.defaultProps)}static defaultProps={...k.defaultProps,type:void 0,count:void 0}}});var Xo,vx=P(()=>{we();Xo=class t extends k{static defaultProps={...k.defaultProps};get[Symbol.toStringTag](){return"Fence"}constructor(e,r={}){super(e,r,t.defaultProps)}}});function Ft(t,e){switch(e){case 1:return t;case 2:return t+t%2;default:return t+(4-t%4)%4}}function Go(t){let[,,,,e]=WM[t];return e}var WM,Hh=P(()=>{WM={uint8:["uint8","u32",1,!1,Uint8Array],sint8:["sint8","i32",1,!1,Int8Array],unorm8:["uint8","f32",1,!0,Uint8Array],snorm8:["sint8","f32",1,!0,Int8Array],uint16:["uint16","u32",2,!1,Uint16Array],sint16:["sint16","i32",2,!1,Int16Array],unorm16:["uint16","u32",2,!0,Uint16Array],snorm16:["sint16","i32",2,!0,Int16Array],float16:["float16","f16",2,!1,Uint16Array],float32:["float32","f32",4,!1,Float32Array],uint32:["uint32","u32",4,!1,Uint32Array],sint32:["sint32","i32",4,!1,Int32Array]}});function Rx(t,e={}){let r={...t},i=e.layout??"std140",n={},o=0;for(let[s,a]of Object.entries(r))o=Yh(n,s,a,o,i);return o=Ft(o,Dr(r,i)),{layout:i,byteLength:o*4,uniformTypes:r,fields:n}}function qo(t,e){let r=zc(t),i=pn(r),n=/^mat(\d)x(\d)<.+>$/.exec(r);if(n){let s=Number(n[1]),a=Number(n[2]),c=Ex(a,r,i.type,e),l=jM(c.size,c.alignment,e);return{alignment:c.alignment,size:s*l,components:s*a,columns:s,rows:a,columnStride:l,shaderType:r,type:i.type}}let o=/^vec(\d)<.+>$/.exec(r);return o?Ex(Number(o[1]),r,i.type,e):{alignment:1,size:1,components:1,columns:1,rows:1,columnStride:1,shaderType:r,type:i.type}}function Xh(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function Yh(t,e,r,i,n){if(typeof r=="string"){let o=qo(r,n),s=Ft(i,o.alignment);return t[e]={offset:s,...o},s+o.size}if(Array.isArray(r)){if(Array.isArray(r[0]))throw new Error(`Nested arrays are not supported for ${e}`);let o=r[0],s=r[1],a=Px(o,n),c=Ft(i,Dr(r,n));for(let l=0;l{Hh();Wc()});function qh(t){return(!jc||jc.byteLength{});function HM(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function gn(t){return Array.isArray(t)?t.length===0||typeof t[0]=="number":HM(t)}var Qh=P(()=>{});function YM(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&!ArrayBuffer.isView(t)}function XM(t,e,r){return Array.prototype.slice.call(t,e,r)}var $c,Ix=P(()=>{Zh();Qh();ot();Gh();$c=class{layout;constructor(e){this.layout=e}has(e){return!!this.layout.fields[e]}get(e){let r=this.layout.fields[e];return r?{offset:r.offset,size:r.size}:void 0}getFlatUniformValues(e){let r={};for(let[i,n]of Object.entries(e)){let o=this.layout.uniformTypes[i];o?this._flattenCompositeValue(r,i,o,n):this.layout.fields[i]&&(r[i]=n)}return r}getData(e){let r=qh(this.layout.byteLength);new Uint8Array(r,0,this.layout.byteLength).fill(0);let i={i32:new Int32Array(r),u32:new Uint32Array(r),f32:new Float32Array(r),f16:new Uint16Array(r)},n=this.getFlatUniformValues(e);for(let[o,s]of Object.entries(n))this._writeLeafValue(i,o,s);return new Uint8Array(r,0,this.layout.byteLength)}_flattenCompositeValue(e,r,i,n){if(n!==void 0){if(typeof i=="string"||this.layout.fields[r]){e[r]=n;return}if(Array.isArray(i)){let o=i[0],s=i[1];if(Array.isArray(o))throw new Error(`Nested arrays are not supported for ${r}`);if(typeof o=="string"&&gn(n)){this._flattenPackedArray(e,r,o,s,n);return}if(!Array.isArray(n)){v.warn(`Unsupported uniform array value for ${r}:`,n)();return}for(let a=0;a=s.length)break;c===1?e[`${r}[${l}]`]=Number(s[f]):e[`${r}[${l}]`]=XM(o,f,f+c)}}_writeLeafValue(e,r,i){let n=this.layout.fields[r];if(!n){v.warn(`Uniform ${r} not found in layout`)();return}let{type:o,components:s,columns:a,rows:c,offset:l,columnStride:f}=n,u=e[o];if(s===1){u[l]=Number(i);return}let d=i;if(a===1){for(let p=0;po)return!1;for(let s=0;s{Qh();GM=128});var Hc,Lx=P(()=>{Dx();Hc=class{name;uniforms={};modifiedUniforms={};modified=!0;bindingLayout={};needsRedraw="initialized";constructor(e){if(this.name=e?.name||"unnamed",e?.name&&e?.shaderLayout){let r=e?.shaderLayout.bindings?.find(n=>n.type==="uniform"&&n.name===e?.name);if(!r)throw new Error(e?.name);let i=r;for(let n of i.uniforms||[])this.bindingLayout[n.name]=n}}setUniforms(e){for(let[r,i]of Object.entries(e))this._setUniform(r,i),this.needsRedraw||this.setNeedsRedraw(`${this.name}.${r}=${i}`)}setNeedsRedraw(e){this.needsRedraw=this.needsRedraw||e}getAllUniforms(){return this.modifiedUniforms={},this.needsRedraw=!1,this.uniforms||{}}_setUniform(e,r){Ox(this.uniforms[e],r)||(this.uniforms[e]=Nx(r),this.modifiedUniforms[e]=!0,this.modified=!0)}}});function KM(t){return t.type==="webgpu"?"wgsl-uniform":"std140"}var qM,Ko,Fx=P(()=>{Mc();ot();Gh();Lx();Ix();qM=1024,Ko=class{device;uniformBlocks=new Map;shaderBlockLayouts=new Map;shaderBlockWriters=new Map;uniformBuffers=new Map;constructor(e,r){this.device=e;for(let[i,n]of Object.entries(r)){let o=i,s=Rx(n.uniformTypes??{},{layout:n.layout??KM(e)}),a=new $c(s);this.shaderBlockLayouts.set(o,s),this.shaderBlockWriters.set(o,a);let c=new Hc({name:i});c.setUniforms(a.getFlatUniformValues(n.defaultUniforms||{})),this.uniformBlocks.set(o,c)}}destroy(){for(let e of this.uniformBuffers.values())e.destroy()}setUniforms(e){for(let[r,i]of Object.entries(e)){let n=r,s=this.shaderBlockWriters.get(n)?.getFlatUniformValues(i||{});this.uniformBlocks.get(n)?.setUniforms(s||{})}this.updateUniformBuffers()}getUniformBufferByteLength(e){let r=this.shaderBlockLayouts.get(e)?.byteLength||0;return Math.max(r,qM)}getUniformBufferData(e){let r=this.uniformBlocks.get(e)?.getAllUniforms()||{};return this.shaderBlockWriters.get(e)?.getData(r)||new Uint8Array(0)}createUniformBuffer(e,r){r&&this.setUniforms(r);let i=this.getUniformBufferByteLength(e),n=this.device.createBuffer({usage:j.UNIFORM|j.COPY_DST,byteLength:i}),o=this.getUniformBufferData(e);return n.write(o),n}getManagedUniformBuffer(e){if(!this.uniformBuffers.get(e)){let r=this.getUniformBufferByteLength(e),i=this.device.createBuffer({usage:j.UNIFORM|j.COPY_DST,byteLength:r});this.uniformBuffers.set(e,i)}return this.uniformBuffers.get(e)}updateUniformBuffers(){let e=!1;for(let r of this.uniformBlocks.keys()){let i=this.updateUniformBuffer(r);e||=i}return e&&v.log(3,`UniformStore.updateUniformBuffers(): ${e}`)(),e}updateUniformBuffer(e){let r=this.uniformBlocks.get(e),i=this.uniformBuffers.get(e),n=!1;if(i&&r?.needsRedraw){n||=r.needsRedraw;let o=this.getUniformBufferData(e);i=this.uniformBuffers.get(e),i?.write(o);let s=this.uniformBlocks.get(e)?.getAllUniforms();v.log(4,`Writing to uniform buffer ${String(e)}`,o,s)()}return n}}});var z=P(()=>{Ky();Zy();Oh();ix();nx();Mc();kh();ox();zh();Bh();lx();Wh();fx();dx();hx();mx();_x();yx();wx();Sx();Ax();vx();Fx();Ic();Hh();Wc();Oc();Fc();Mh();ot();gx();Lh();Zh();$h()});var Vr,Jb=P(()=>{(function(t){t[t.DEPTH_BUFFER_BIT=256]="DEPTH_BUFFER_BIT",t[t.STENCIL_BUFFER_BIT=1024]="STENCIL_BUFFER_BIT",t[t.COLOR_BUFFER_BIT=16384]="COLOR_BUFFER_BIT",t[t.POINTS=0]="POINTS",t[t.LINES=1]="LINES",t[t.LINE_LOOP=2]="LINE_LOOP",t[t.LINE_STRIP=3]="LINE_STRIP",t[t.TRIANGLES=4]="TRIANGLES",t[t.TRIANGLE_STRIP=5]="TRIANGLE_STRIP",t[t.TRIANGLE_FAN=6]="TRIANGLE_FAN",t[t.ZERO=0]="ZERO",t[t.ONE=1]="ONE",t[t.SRC_COLOR=768]="SRC_COLOR",t[t.ONE_MINUS_SRC_COLOR=769]="ONE_MINUS_SRC_COLOR",t[t.SRC_ALPHA=770]="SRC_ALPHA",t[t.ONE_MINUS_SRC_ALPHA=771]="ONE_MINUS_SRC_ALPHA",t[t.DST_ALPHA=772]="DST_ALPHA",t[t.ONE_MINUS_DST_ALPHA=773]="ONE_MINUS_DST_ALPHA",t[t.DST_COLOR=774]="DST_COLOR",t[t.ONE_MINUS_DST_COLOR=775]="ONE_MINUS_DST_COLOR",t[t.SRC_ALPHA_SATURATE=776]="SRC_ALPHA_SATURATE",t[t.CONSTANT_COLOR=32769]="CONSTANT_COLOR",t[t.ONE_MINUS_CONSTANT_COLOR=32770]="ONE_MINUS_CONSTANT_COLOR",t[t.CONSTANT_ALPHA=32771]="CONSTANT_ALPHA",t[t.ONE_MINUS_CONSTANT_ALPHA=32772]="ONE_MINUS_CONSTANT_ALPHA",t[t.FUNC_ADD=32774]="FUNC_ADD",t[t.FUNC_SUBTRACT=32778]="FUNC_SUBTRACT",t[t.FUNC_REVERSE_SUBTRACT=32779]="FUNC_REVERSE_SUBTRACT",t[t.BLEND_EQUATION=32777]="BLEND_EQUATION",t[t.BLEND_EQUATION_RGB=32777]="BLEND_EQUATION_RGB",t[t.BLEND_EQUATION_ALPHA=34877]="BLEND_EQUATION_ALPHA",t[t.BLEND_DST_RGB=32968]="BLEND_DST_RGB",t[t.BLEND_SRC_RGB=32969]="BLEND_SRC_RGB",t[t.BLEND_DST_ALPHA=32970]="BLEND_DST_ALPHA",t[t.BLEND_SRC_ALPHA=32971]="BLEND_SRC_ALPHA",t[t.BLEND_COLOR=32773]="BLEND_COLOR",t[t.ARRAY_BUFFER_BINDING=34964]="ARRAY_BUFFER_BINDING",t[t.ELEMENT_ARRAY_BUFFER_BINDING=34965]="ELEMENT_ARRAY_BUFFER_BINDING",t[t.LINE_WIDTH=2849]="LINE_WIDTH",t[t.ALIASED_POINT_SIZE_RANGE=33901]="ALIASED_POINT_SIZE_RANGE",t[t.ALIASED_LINE_WIDTH_RANGE=33902]="ALIASED_LINE_WIDTH_RANGE",t[t.CULL_FACE_MODE=2885]="CULL_FACE_MODE",t[t.FRONT_FACE=2886]="FRONT_FACE",t[t.DEPTH_RANGE=2928]="DEPTH_RANGE",t[t.DEPTH_WRITEMASK=2930]="DEPTH_WRITEMASK",t[t.DEPTH_CLEAR_VALUE=2931]="DEPTH_CLEAR_VALUE",t[t.DEPTH_FUNC=2932]="DEPTH_FUNC",t[t.STENCIL_CLEAR_VALUE=2961]="STENCIL_CLEAR_VALUE",t[t.STENCIL_FUNC=2962]="STENCIL_FUNC",t[t.STENCIL_FAIL=2964]="STENCIL_FAIL",t[t.STENCIL_PASS_DEPTH_FAIL=2965]="STENCIL_PASS_DEPTH_FAIL",t[t.STENCIL_PASS_DEPTH_PASS=2966]="STENCIL_PASS_DEPTH_PASS",t[t.STENCIL_REF=2967]="STENCIL_REF",t[t.STENCIL_VALUE_MASK=2963]="STENCIL_VALUE_MASK",t[t.STENCIL_WRITEMASK=2968]="STENCIL_WRITEMASK",t[t.STENCIL_BACK_FUNC=34816]="STENCIL_BACK_FUNC",t[t.STENCIL_BACK_FAIL=34817]="STENCIL_BACK_FAIL",t[t.STENCIL_BACK_PASS_DEPTH_FAIL=34818]="STENCIL_BACK_PASS_DEPTH_FAIL",t[t.STENCIL_BACK_PASS_DEPTH_PASS=34819]="STENCIL_BACK_PASS_DEPTH_PASS",t[t.STENCIL_BACK_REF=36003]="STENCIL_BACK_REF",t[t.STENCIL_BACK_VALUE_MASK=36004]="STENCIL_BACK_VALUE_MASK",t[t.STENCIL_BACK_WRITEMASK=36005]="STENCIL_BACK_WRITEMASK",t[t.VIEWPORT=2978]="VIEWPORT",t[t.SCISSOR_BOX=3088]="SCISSOR_BOX",t[t.COLOR_CLEAR_VALUE=3106]="COLOR_CLEAR_VALUE",t[t.COLOR_WRITEMASK=3107]="COLOR_WRITEMASK",t[t.UNPACK_ALIGNMENT=3317]="UNPACK_ALIGNMENT",t[t.PACK_ALIGNMENT=3333]="PACK_ALIGNMENT",t[t.MAX_TEXTURE_SIZE=3379]="MAX_TEXTURE_SIZE",t[t.MAX_VIEWPORT_DIMS=3386]="MAX_VIEWPORT_DIMS",t[t.SUBPIXEL_BITS=3408]="SUBPIXEL_BITS",t[t.RED_BITS=3410]="RED_BITS",t[t.GREEN_BITS=3411]="GREEN_BITS",t[t.BLUE_BITS=3412]="BLUE_BITS",t[t.ALPHA_BITS=3413]="ALPHA_BITS",t[t.DEPTH_BITS=3414]="DEPTH_BITS",t[t.STENCIL_BITS=3415]="STENCIL_BITS",t[t.POLYGON_OFFSET_UNITS=10752]="POLYGON_OFFSET_UNITS",t[t.POLYGON_OFFSET_FACTOR=32824]="POLYGON_OFFSET_FACTOR",t[t.TEXTURE_BINDING_2D=32873]="TEXTURE_BINDING_2D",t[t.SAMPLE_BUFFERS=32936]="SAMPLE_BUFFERS",t[t.SAMPLES=32937]="SAMPLES",t[t.SAMPLE_COVERAGE_VALUE=32938]="SAMPLE_COVERAGE_VALUE",t[t.SAMPLE_COVERAGE_INVERT=32939]="SAMPLE_COVERAGE_INVERT",t[t.COMPRESSED_TEXTURE_FORMATS=34467]="COMPRESSED_TEXTURE_FORMATS",t[t.VENDOR=7936]="VENDOR",t[t.RENDERER=7937]="RENDERER",t[t.VERSION=7938]="VERSION",t[t.IMPLEMENTATION_COLOR_READ_TYPE=35738]="IMPLEMENTATION_COLOR_READ_TYPE",t[t.IMPLEMENTATION_COLOR_READ_FORMAT=35739]="IMPLEMENTATION_COLOR_READ_FORMAT",t[t.BROWSER_DEFAULT_WEBGL=37444]="BROWSER_DEFAULT_WEBGL",t[t.STATIC_DRAW=35044]="STATIC_DRAW",t[t.STREAM_DRAW=35040]="STREAM_DRAW",t[t.DYNAMIC_DRAW=35048]="DYNAMIC_DRAW",t[t.ARRAY_BUFFER=34962]="ARRAY_BUFFER",t[t.ELEMENT_ARRAY_BUFFER=34963]="ELEMENT_ARRAY_BUFFER",t[t.BUFFER_SIZE=34660]="BUFFER_SIZE",t[t.BUFFER_USAGE=34661]="BUFFER_USAGE",t[t.CURRENT_VERTEX_ATTRIB=34342]="CURRENT_VERTEX_ATTRIB",t[t.VERTEX_ATTRIB_ARRAY_ENABLED=34338]="VERTEX_ATTRIB_ARRAY_ENABLED",t[t.VERTEX_ATTRIB_ARRAY_SIZE=34339]="VERTEX_ATTRIB_ARRAY_SIZE",t[t.VERTEX_ATTRIB_ARRAY_STRIDE=34340]="VERTEX_ATTRIB_ARRAY_STRIDE",t[t.VERTEX_ATTRIB_ARRAY_TYPE=34341]="VERTEX_ATTRIB_ARRAY_TYPE",t[t.VERTEX_ATTRIB_ARRAY_NORMALIZED=34922]="VERTEX_ATTRIB_ARRAY_NORMALIZED",t[t.VERTEX_ATTRIB_ARRAY_POINTER=34373]="VERTEX_ATTRIB_ARRAY_POINTER",t[t.VERTEX_ATTRIB_ARRAY_BUFFER_BINDING=34975]="VERTEX_ATTRIB_ARRAY_BUFFER_BINDING",t[t.CULL_FACE=2884]="CULL_FACE",t[t.FRONT=1028]="FRONT",t[t.BACK=1029]="BACK",t[t.FRONT_AND_BACK=1032]="FRONT_AND_BACK",t[t.BLEND=3042]="BLEND",t[t.DEPTH_TEST=2929]="DEPTH_TEST",t[t.DITHER=3024]="DITHER",t[t.POLYGON_OFFSET_FILL=32823]="POLYGON_OFFSET_FILL",t[t.SAMPLE_ALPHA_TO_COVERAGE=32926]="SAMPLE_ALPHA_TO_COVERAGE",t[t.SAMPLE_COVERAGE=32928]="SAMPLE_COVERAGE",t[t.SCISSOR_TEST=3089]="SCISSOR_TEST",t[t.STENCIL_TEST=2960]="STENCIL_TEST",t[t.NO_ERROR=0]="NO_ERROR",t[t.INVALID_ENUM=1280]="INVALID_ENUM",t[t.INVALID_VALUE=1281]="INVALID_VALUE",t[t.INVALID_OPERATION=1282]="INVALID_OPERATION",t[t.OUT_OF_MEMORY=1285]="OUT_OF_MEMORY",t[t.CONTEXT_LOST_WEBGL=37442]="CONTEXT_LOST_WEBGL",t[t.CW=2304]="CW",t[t.CCW=2305]="CCW",t[t.DONT_CARE=4352]="DONT_CARE",t[t.FASTEST=4353]="FASTEST",t[t.NICEST=4354]="NICEST",t[t.GENERATE_MIPMAP_HINT=33170]="GENERATE_MIPMAP_HINT",t[t.BYTE=5120]="BYTE",t[t.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",t[t.SHORT=5122]="SHORT",t[t.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",t[t.INT=5124]="INT",t[t.UNSIGNED_INT=5125]="UNSIGNED_INT",t[t.FLOAT=5126]="FLOAT",t[t.DOUBLE=5130]="DOUBLE",t[t.DEPTH_COMPONENT=6402]="DEPTH_COMPONENT",t[t.ALPHA=6406]="ALPHA",t[t.RGB=6407]="RGB",t[t.RGBA=6408]="RGBA",t[t.LUMINANCE=6409]="LUMINANCE",t[t.LUMINANCE_ALPHA=6410]="LUMINANCE_ALPHA",t[t.UNSIGNED_SHORT_4_4_4_4=32819]="UNSIGNED_SHORT_4_4_4_4",t[t.UNSIGNED_SHORT_5_5_5_1=32820]="UNSIGNED_SHORT_5_5_5_1",t[t.UNSIGNED_SHORT_5_6_5=33635]="UNSIGNED_SHORT_5_6_5",t[t.FRAGMENT_SHADER=35632]="FRAGMENT_SHADER",t[t.VERTEX_SHADER=35633]="VERTEX_SHADER",t[t.COMPILE_STATUS=35713]="COMPILE_STATUS",t[t.DELETE_STATUS=35712]="DELETE_STATUS",t[t.LINK_STATUS=35714]="LINK_STATUS",t[t.VALIDATE_STATUS=35715]="VALIDATE_STATUS",t[t.ATTACHED_SHADERS=35717]="ATTACHED_SHADERS",t[t.ACTIVE_ATTRIBUTES=35721]="ACTIVE_ATTRIBUTES",t[t.ACTIVE_UNIFORMS=35718]="ACTIVE_UNIFORMS",t[t.MAX_VERTEX_ATTRIBS=34921]="MAX_VERTEX_ATTRIBS",t[t.MAX_VERTEX_UNIFORM_VECTORS=36347]="MAX_VERTEX_UNIFORM_VECTORS",t[t.MAX_VARYING_VECTORS=36348]="MAX_VARYING_VECTORS",t[t.MAX_COMBINED_TEXTURE_IMAGE_UNITS=35661]="MAX_COMBINED_TEXTURE_IMAGE_UNITS",t[t.MAX_VERTEX_TEXTURE_IMAGE_UNITS=35660]="MAX_VERTEX_TEXTURE_IMAGE_UNITS",t[t.MAX_TEXTURE_IMAGE_UNITS=34930]="MAX_TEXTURE_IMAGE_UNITS",t[t.MAX_FRAGMENT_UNIFORM_VECTORS=36349]="MAX_FRAGMENT_UNIFORM_VECTORS",t[t.SHADER_TYPE=35663]="SHADER_TYPE",t[t.SHADING_LANGUAGE_VERSION=35724]="SHADING_LANGUAGE_VERSION",t[t.CURRENT_PROGRAM=35725]="CURRENT_PROGRAM",t[t.NEVER=512]="NEVER",t[t.LESS=513]="LESS",t[t.EQUAL=514]="EQUAL",t[t.LEQUAL=515]="LEQUAL",t[t.GREATER=516]="GREATER",t[t.NOTEQUAL=517]="NOTEQUAL",t[t.GEQUAL=518]="GEQUAL",t[t.ALWAYS=519]="ALWAYS",t[t.KEEP=7680]="KEEP",t[t.REPLACE=7681]="REPLACE",t[t.INCR=7682]="INCR",t[t.DECR=7683]="DECR",t[t.INVERT=5386]="INVERT",t[t.INCR_WRAP=34055]="INCR_WRAP",t[t.DECR_WRAP=34056]="DECR_WRAP",t[t.NEAREST=9728]="NEAREST",t[t.LINEAR=9729]="LINEAR",t[t.NEAREST_MIPMAP_NEAREST=9984]="NEAREST_MIPMAP_NEAREST",t[t.LINEAR_MIPMAP_NEAREST=9985]="LINEAR_MIPMAP_NEAREST",t[t.NEAREST_MIPMAP_LINEAR=9986]="NEAREST_MIPMAP_LINEAR",t[t.LINEAR_MIPMAP_LINEAR=9987]="LINEAR_MIPMAP_LINEAR",t[t.TEXTURE_MAG_FILTER=10240]="TEXTURE_MAG_FILTER",t[t.TEXTURE_MIN_FILTER=10241]="TEXTURE_MIN_FILTER",t[t.TEXTURE_WRAP_S=10242]="TEXTURE_WRAP_S",t[t.TEXTURE_WRAP_T=10243]="TEXTURE_WRAP_T",t[t.TEXTURE_2D=3553]="TEXTURE_2D",t[t.TEXTURE=5890]="TEXTURE",t[t.TEXTURE_CUBE_MAP=34067]="TEXTURE_CUBE_MAP",t[t.TEXTURE_BINDING_CUBE_MAP=34068]="TEXTURE_BINDING_CUBE_MAP",t[t.TEXTURE_CUBE_MAP_POSITIVE_X=34069]="TEXTURE_CUBE_MAP_POSITIVE_X",t[t.TEXTURE_CUBE_MAP_NEGATIVE_X=34070]="TEXTURE_CUBE_MAP_NEGATIVE_X",t[t.TEXTURE_CUBE_MAP_POSITIVE_Y=34071]="TEXTURE_CUBE_MAP_POSITIVE_Y",t[t.TEXTURE_CUBE_MAP_NEGATIVE_Y=34072]="TEXTURE_CUBE_MAP_NEGATIVE_Y",t[t.TEXTURE_CUBE_MAP_POSITIVE_Z=34073]="TEXTURE_CUBE_MAP_POSITIVE_Z",t[t.TEXTURE_CUBE_MAP_NEGATIVE_Z=34074]="TEXTURE_CUBE_MAP_NEGATIVE_Z",t[t.MAX_CUBE_MAP_TEXTURE_SIZE=34076]="MAX_CUBE_MAP_TEXTURE_SIZE",t[t.TEXTURE0=33984]="TEXTURE0",t[t.ACTIVE_TEXTURE=34016]="ACTIVE_TEXTURE",t[t.REPEAT=10497]="REPEAT",t[t.CLAMP_TO_EDGE=33071]="CLAMP_TO_EDGE",t[t.MIRRORED_REPEAT=33648]="MIRRORED_REPEAT",t[t.TEXTURE_WIDTH=4096]="TEXTURE_WIDTH",t[t.TEXTURE_HEIGHT=4097]="TEXTURE_HEIGHT",t[t.FLOAT_VEC2=35664]="FLOAT_VEC2",t[t.FLOAT_VEC3=35665]="FLOAT_VEC3",t[t.FLOAT_VEC4=35666]="FLOAT_VEC4",t[t.INT_VEC2=35667]="INT_VEC2",t[t.INT_VEC3=35668]="INT_VEC3",t[t.INT_VEC4=35669]="INT_VEC4",t[t.BOOL=35670]="BOOL",t[t.BOOL_VEC2=35671]="BOOL_VEC2",t[t.BOOL_VEC3=35672]="BOOL_VEC3",t[t.BOOL_VEC4=35673]="BOOL_VEC4",t[t.FLOAT_MAT2=35674]="FLOAT_MAT2",t[t.FLOAT_MAT3=35675]="FLOAT_MAT3",t[t.FLOAT_MAT4=35676]="FLOAT_MAT4",t[t.SAMPLER_2D=35678]="SAMPLER_2D",t[t.SAMPLER_CUBE=35680]="SAMPLER_CUBE",t[t.LOW_FLOAT=36336]="LOW_FLOAT",t[t.MEDIUM_FLOAT=36337]="MEDIUM_FLOAT",t[t.HIGH_FLOAT=36338]="HIGH_FLOAT",t[t.LOW_INT=36339]="LOW_INT",t[t.MEDIUM_INT=36340]="MEDIUM_INT",t[t.HIGH_INT=36341]="HIGH_INT",t[t.FRAMEBUFFER=36160]="FRAMEBUFFER",t[t.RENDERBUFFER=36161]="RENDERBUFFER",t[t.RGBA4=32854]="RGBA4",t[t.RGB5_A1=32855]="RGB5_A1",t[t.RGB565=36194]="RGB565",t[t.DEPTH_COMPONENT16=33189]="DEPTH_COMPONENT16",t[t.STENCIL_INDEX=6401]="STENCIL_INDEX",t[t.STENCIL_INDEX8=36168]="STENCIL_INDEX8",t[t.DEPTH_STENCIL=34041]="DEPTH_STENCIL",t[t.RENDERBUFFER_WIDTH=36162]="RENDERBUFFER_WIDTH",t[t.RENDERBUFFER_HEIGHT=36163]="RENDERBUFFER_HEIGHT",t[t.RENDERBUFFER_INTERNAL_FORMAT=36164]="RENDERBUFFER_INTERNAL_FORMAT",t[t.RENDERBUFFER_RED_SIZE=36176]="RENDERBUFFER_RED_SIZE",t[t.RENDERBUFFER_GREEN_SIZE=36177]="RENDERBUFFER_GREEN_SIZE",t[t.RENDERBUFFER_BLUE_SIZE=36178]="RENDERBUFFER_BLUE_SIZE",t[t.RENDERBUFFER_ALPHA_SIZE=36179]="RENDERBUFFER_ALPHA_SIZE",t[t.RENDERBUFFER_DEPTH_SIZE=36180]="RENDERBUFFER_DEPTH_SIZE",t[t.RENDERBUFFER_STENCIL_SIZE=36181]="RENDERBUFFER_STENCIL_SIZE",t[t.FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE=36048]="FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE",t[t.FRAMEBUFFER_ATTACHMENT_OBJECT_NAME=36049]="FRAMEBUFFER_ATTACHMENT_OBJECT_NAME",t[t.FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL=36050]="FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL",t[t.FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE=36051]="FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE",t[t.COLOR_ATTACHMENT0=36064]="COLOR_ATTACHMENT0",t[t.DEPTH_ATTACHMENT=36096]="DEPTH_ATTACHMENT",t[t.STENCIL_ATTACHMENT=36128]="STENCIL_ATTACHMENT",t[t.DEPTH_STENCIL_ATTACHMENT=33306]="DEPTH_STENCIL_ATTACHMENT",t[t.NONE=0]="NONE",t[t.FRAMEBUFFER_COMPLETE=36053]="FRAMEBUFFER_COMPLETE",t[t.FRAMEBUFFER_INCOMPLETE_ATTACHMENT=36054]="FRAMEBUFFER_INCOMPLETE_ATTACHMENT",t[t.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT=36055]="FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT",t[t.FRAMEBUFFER_INCOMPLETE_DIMENSIONS=36057]="FRAMEBUFFER_INCOMPLETE_DIMENSIONS",t[t.FRAMEBUFFER_UNSUPPORTED=36061]="FRAMEBUFFER_UNSUPPORTED",t[t.FRAMEBUFFER_BINDING=36006]="FRAMEBUFFER_BINDING",t[t.RENDERBUFFER_BINDING=36007]="RENDERBUFFER_BINDING",t[t.READ_FRAMEBUFFER=36008]="READ_FRAMEBUFFER",t[t.DRAW_FRAMEBUFFER=36009]="DRAW_FRAMEBUFFER",t[t.MAX_RENDERBUFFER_SIZE=34024]="MAX_RENDERBUFFER_SIZE",t[t.INVALID_FRAMEBUFFER_OPERATION=1286]="INVALID_FRAMEBUFFER_OPERATION",t[t.UNPACK_FLIP_Y_WEBGL=37440]="UNPACK_FLIP_Y_WEBGL",t[t.UNPACK_PREMULTIPLY_ALPHA_WEBGL=37441]="UNPACK_PREMULTIPLY_ALPHA_WEBGL",t[t.UNPACK_COLORSPACE_CONVERSION_WEBGL=37443]="UNPACK_COLORSPACE_CONVERSION_WEBGL",t[t.READ_BUFFER=3074]="READ_BUFFER",t[t.UNPACK_ROW_LENGTH=3314]="UNPACK_ROW_LENGTH",t[t.UNPACK_SKIP_ROWS=3315]="UNPACK_SKIP_ROWS",t[t.UNPACK_SKIP_PIXELS=3316]="UNPACK_SKIP_PIXELS",t[t.PACK_ROW_LENGTH=3330]="PACK_ROW_LENGTH",t[t.PACK_SKIP_ROWS=3331]="PACK_SKIP_ROWS",t[t.PACK_SKIP_PIXELS=3332]="PACK_SKIP_PIXELS",t[t.TEXTURE_BINDING_3D=32874]="TEXTURE_BINDING_3D",t[t.UNPACK_SKIP_IMAGES=32877]="UNPACK_SKIP_IMAGES",t[t.UNPACK_IMAGE_HEIGHT=32878]="UNPACK_IMAGE_HEIGHT",t[t.MAX_3D_TEXTURE_SIZE=32883]="MAX_3D_TEXTURE_SIZE",t[t.MAX_ELEMENTS_VERTICES=33e3]="MAX_ELEMENTS_VERTICES",t[t.MAX_ELEMENTS_INDICES=33001]="MAX_ELEMENTS_INDICES",t[t.MAX_TEXTURE_LOD_BIAS=34045]="MAX_TEXTURE_LOD_BIAS",t[t.MAX_FRAGMENT_UNIFORM_COMPONENTS=35657]="MAX_FRAGMENT_UNIFORM_COMPONENTS",t[t.MAX_VERTEX_UNIFORM_COMPONENTS=35658]="MAX_VERTEX_UNIFORM_COMPONENTS",t[t.MAX_ARRAY_TEXTURE_LAYERS=35071]="MAX_ARRAY_TEXTURE_LAYERS",t[t.MIN_PROGRAM_TEXEL_OFFSET=35076]="MIN_PROGRAM_TEXEL_OFFSET",t[t.MAX_PROGRAM_TEXEL_OFFSET=35077]="MAX_PROGRAM_TEXEL_OFFSET",t[t.MAX_VARYING_COMPONENTS=35659]="MAX_VARYING_COMPONENTS",t[t.FRAGMENT_SHADER_DERIVATIVE_HINT=35723]="FRAGMENT_SHADER_DERIVATIVE_HINT",t[t.RASTERIZER_DISCARD=35977]="RASTERIZER_DISCARD",t[t.VERTEX_ARRAY_BINDING=34229]="VERTEX_ARRAY_BINDING",t[t.MAX_VERTEX_OUTPUT_COMPONENTS=37154]="MAX_VERTEX_OUTPUT_COMPONENTS",t[t.MAX_FRAGMENT_INPUT_COMPONENTS=37157]="MAX_FRAGMENT_INPUT_COMPONENTS",t[t.MAX_SERVER_WAIT_TIMEOUT=37137]="MAX_SERVER_WAIT_TIMEOUT",t[t.MAX_ELEMENT_INDEX=36203]="MAX_ELEMENT_INDEX",t[t.RED=6403]="RED",t[t.RGB8=32849]="RGB8",t[t.RGBA8=32856]="RGBA8",t[t.RGB10_A2=32857]="RGB10_A2",t[t.TEXTURE_3D=32879]="TEXTURE_3D",t[t.TEXTURE_WRAP_R=32882]="TEXTURE_WRAP_R",t[t.TEXTURE_MIN_LOD=33082]="TEXTURE_MIN_LOD",t[t.TEXTURE_MAX_LOD=33083]="TEXTURE_MAX_LOD",t[t.TEXTURE_BASE_LEVEL=33084]="TEXTURE_BASE_LEVEL",t[t.TEXTURE_MAX_LEVEL=33085]="TEXTURE_MAX_LEVEL",t[t.TEXTURE_COMPARE_MODE=34892]="TEXTURE_COMPARE_MODE",t[t.TEXTURE_COMPARE_FUNC=34893]="TEXTURE_COMPARE_FUNC",t[t.SRGB=35904]="SRGB",t[t.SRGB8=35905]="SRGB8",t[t.SRGB8_ALPHA8=35907]="SRGB8_ALPHA8",t[t.COMPARE_REF_TO_TEXTURE=34894]="COMPARE_REF_TO_TEXTURE",t[t.RGBA32F=34836]="RGBA32F",t[t.RGB32F=34837]="RGB32F",t[t.RGBA16F=34842]="RGBA16F",t[t.RGB16F=34843]="RGB16F",t[t.TEXTURE_2D_ARRAY=35866]="TEXTURE_2D_ARRAY",t[t.TEXTURE_BINDING_2D_ARRAY=35869]="TEXTURE_BINDING_2D_ARRAY",t[t.R11F_G11F_B10F=35898]="R11F_G11F_B10F",t[t.RGB9_E5=35901]="RGB9_E5",t[t.RGBA32UI=36208]="RGBA32UI",t[t.RGB32UI=36209]="RGB32UI",t[t.RGBA16UI=36214]="RGBA16UI",t[t.RGB16UI=36215]="RGB16UI",t[t.RGBA8UI=36220]="RGBA8UI",t[t.RGB8UI=36221]="RGB8UI",t[t.RGBA32I=36226]="RGBA32I",t[t.RGB32I=36227]="RGB32I",t[t.RGBA16I=36232]="RGBA16I",t[t.RGB16I=36233]="RGB16I",t[t.RGBA8I=36238]="RGBA8I",t[t.RGB8I=36239]="RGB8I",t[t.RED_INTEGER=36244]="RED_INTEGER",t[t.RGB_INTEGER=36248]="RGB_INTEGER",t[t.RGBA_INTEGER=36249]="RGBA_INTEGER",t[t.R8=33321]="R8",t[t.RG8=33323]="RG8",t[t.R16F=33325]="R16F",t[t.R32F=33326]="R32F",t[t.RG16F=33327]="RG16F",t[t.RG32F=33328]="RG32F",t[t.R8I=33329]="R8I",t[t.R8UI=33330]="R8UI",t[t.R16I=33331]="R16I",t[t.R16UI=33332]="R16UI",t[t.R32I=33333]="R32I",t[t.R32UI=33334]="R32UI",t[t.RG8I=33335]="RG8I",t[t.RG8UI=33336]="RG8UI",t[t.RG16I=33337]="RG16I",t[t.RG16UI=33338]="RG16UI",t[t.RG32I=33339]="RG32I",t[t.RG32UI=33340]="RG32UI",t[t.R8_SNORM=36756]="R8_SNORM",t[t.RG8_SNORM=36757]="RG8_SNORM",t[t.RGB8_SNORM=36758]="RGB8_SNORM",t[t.RGBA8_SNORM=36759]="RGBA8_SNORM",t[t.RGB10_A2UI=36975]="RGB10_A2UI",t[t.TEXTURE_IMMUTABLE_FORMAT=37167]="TEXTURE_IMMUTABLE_FORMAT",t[t.TEXTURE_IMMUTABLE_LEVELS=33503]="TEXTURE_IMMUTABLE_LEVELS",t[t.UNSIGNED_INT_2_10_10_10_REV=33640]="UNSIGNED_INT_2_10_10_10_REV",t[t.UNSIGNED_INT_10F_11F_11F_REV=35899]="UNSIGNED_INT_10F_11F_11F_REV",t[t.UNSIGNED_INT_5_9_9_9_REV=35902]="UNSIGNED_INT_5_9_9_9_REV",t[t.FLOAT_32_UNSIGNED_INT_24_8_REV=36269]="FLOAT_32_UNSIGNED_INT_24_8_REV",t[t.UNSIGNED_INT_24_8=34042]="UNSIGNED_INT_24_8",t[t.HALF_FLOAT=5131]="HALF_FLOAT",t[t.RG=33319]="RG",t[t.RG_INTEGER=33320]="RG_INTEGER",t[t.INT_2_10_10_10_REV=36255]="INT_2_10_10_10_REV",t[t.CURRENT_QUERY=34917]="CURRENT_QUERY",t[t.QUERY_RESULT=34918]="QUERY_RESULT",t[t.QUERY_RESULT_AVAILABLE=34919]="QUERY_RESULT_AVAILABLE",t[t.ANY_SAMPLES_PASSED=35887]="ANY_SAMPLES_PASSED",t[t.ANY_SAMPLES_PASSED_CONSERVATIVE=36202]="ANY_SAMPLES_PASSED_CONSERVATIVE",t[t.MAX_DRAW_BUFFERS=34852]="MAX_DRAW_BUFFERS",t[t.DRAW_BUFFER0=34853]="DRAW_BUFFER0",t[t.DRAW_BUFFER1=34854]="DRAW_BUFFER1",t[t.DRAW_BUFFER2=34855]="DRAW_BUFFER2",t[t.DRAW_BUFFER3=34856]="DRAW_BUFFER3",t[t.DRAW_BUFFER4=34857]="DRAW_BUFFER4",t[t.DRAW_BUFFER5=34858]="DRAW_BUFFER5",t[t.DRAW_BUFFER6=34859]="DRAW_BUFFER6",t[t.DRAW_BUFFER7=34860]="DRAW_BUFFER7",t[t.DRAW_BUFFER8=34861]="DRAW_BUFFER8",t[t.DRAW_BUFFER9=34862]="DRAW_BUFFER9",t[t.DRAW_BUFFER10=34863]="DRAW_BUFFER10",t[t.DRAW_BUFFER11=34864]="DRAW_BUFFER11",t[t.DRAW_BUFFER12=34865]="DRAW_BUFFER12",t[t.DRAW_BUFFER13=34866]="DRAW_BUFFER13",t[t.DRAW_BUFFER14=34867]="DRAW_BUFFER14",t[t.DRAW_BUFFER15=34868]="DRAW_BUFFER15",t[t.MAX_COLOR_ATTACHMENTS=36063]="MAX_COLOR_ATTACHMENTS",t[t.COLOR_ATTACHMENT1=36065]="COLOR_ATTACHMENT1",t[t.COLOR_ATTACHMENT2=36066]="COLOR_ATTACHMENT2",t[t.COLOR_ATTACHMENT3=36067]="COLOR_ATTACHMENT3",t[t.COLOR_ATTACHMENT4=36068]="COLOR_ATTACHMENT4",t[t.COLOR_ATTACHMENT5=36069]="COLOR_ATTACHMENT5",t[t.COLOR_ATTACHMENT6=36070]="COLOR_ATTACHMENT6",t[t.COLOR_ATTACHMENT7=36071]="COLOR_ATTACHMENT7",t[t.COLOR_ATTACHMENT8=36072]="COLOR_ATTACHMENT8",t[t.COLOR_ATTACHMENT9=36073]="COLOR_ATTACHMENT9",t[t.COLOR_ATTACHMENT10=36074]="COLOR_ATTACHMENT10",t[t.COLOR_ATTACHMENT11=36075]="COLOR_ATTACHMENT11",t[t.COLOR_ATTACHMENT12=36076]="COLOR_ATTACHMENT12",t[t.COLOR_ATTACHMENT13=36077]="COLOR_ATTACHMENT13",t[t.COLOR_ATTACHMENT14=36078]="COLOR_ATTACHMENT14",t[t.COLOR_ATTACHMENT15=36079]="COLOR_ATTACHMENT15",t[t.SAMPLER_3D=35679]="SAMPLER_3D",t[t.SAMPLER_2D_SHADOW=35682]="SAMPLER_2D_SHADOW",t[t.SAMPLER_2D_ARRAY=36289]="SAMPLER_2D_ARRAY",t[t.SAMPLER_2D_ARRAY_SHADOW=36292]="SAMPLER_2D_ARRAY_SHADOW",t[t.SAMPLER_CUBE_SHADOW=36293]="SAMPLER_CUBE_SHADOW",t[t.INT_SAMPLER_2D=36298]="INT_SAMPLER_2D",t[t.INT_SAMPLER_3D=36299]="INT_SAMPLER_3D",t[t.INT_SAMPLER_CUBE=36300]="INT_SAMPLER_CUBE",t[t.INT_SAMPLER_2D_ARRAY=36303]="INT_SAMPLER_2D_ARRAY",t[t.UNSIGNED_INT_SAMPLER_2D=36306]="UNSIGNED_INT_SAMPLER_2D",t[t.UNSIGNED_INT_SAMPLER_3D=36307]="UNSIGNED_INT_SAMPLER_3D",t[t.UNSIGNED_INT_SAMPLER_CUBE=36308]="UNSIGNED_INT_SAMPLER_CUBE",t[t.UNSIGNED_INT_SAMPLER_2D_ARRAY=36311]="UNSIGNED_INT_SAMPLER_2D_ARRAY",t[t.MAX_SAMPLES=36183]="MAX_SAMPLES",t[t.SAMPLER_BINDING=35097]="SAMPLER_BINDING",t[t.PIXEL_PACK_BUFFER=35051]="PIXEL_PACK_BUFFER",t[t.PIXEL_UNPACK_BUFFER=35052]="PIXEL_UNPACK_BUFFER",t[t.PIXEL_PACK_BUFFER_BINDING=35053]="PIXEL_PACK_BUFFER_BINDING",t[t.PIXEL_UNPACK_BUFFER_BINDING=35055]="PIXEL_UNPACK_BUFFER_BINDING",t[t.COPY_READ_BUFFER=36662]="COPY_READ_BUFFER",t[t.COPY_WRITE_BUFFER=36663]="COPY_WRITE_BUFFER",t[t.COPY_READ_BUFFER_BINDING=36662]="COPY_READ_BUFFER_BINDING",t[t.COPY_WRITE_BUFFER_BINDING=36663]="COPY_WRITE_BUFFER_BINDING",t[t.FLOAT_MAT2x3=35685]="FLOAT_MAT2x3",t[t.FLOAT_MAT2x4=35686]="FLOAT_MAT2x4",t[t.FLOAT_MAT3x2=35687]="FLOAT_MAT3x2",t[t.FLOAT_MAT3x4=35688]="FLOAT_MAT3x4",t[t.FLOAT_MAT4x2=35689]="FLOAT_MAT4x2",t[t.FLOAT_MAT4x3=35690]="FLOAT_MAT4x3",t[t.UNSIGNED_INT_VEC2=36294]="UNSIGNED_INT_VEC2",t[t.UNSIGNED_INT_VEC3=36295]="UNSIGNED_INT_VEC3",t[t.UNSIGNED_INT_VEC4=36296]="UNSIGNED_INT_VEC4",t[t.UNSIGNED_NORMALIZED=35863]="UNSIGNED_NORMALIZED",t[t.SIGNED_NORMALIZED=36764]="SIGNED_NORMALIZED",t[t.VERTEX_ATTRIB_ARRAY_INTEGER=35069]="VERTEX_ATTRIB_ARRAY_INTEGER",t[t.VERTEX_ATTRIB_ARRAY_DIVISOR=35070]="VERTEX_ATTRIB_ARRAY_DIVISOR",t[t.TRANSFORM_FEEDBACK_BUFFER_MODE=35967]="TRANSFORM_FEEDBACK_BUFFER_MODE",t[t.MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS=35968]="MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS",t[t.TRANSFORM_FEEDBACK_VARYINGS=35971]="TRANSFORM_FEEDBACK_VARYINGS",t[t.TRANSFORM_FEEDBACK_BUFFER_START=35972]="TRANSFORM_FEEDBACK_BUFFER_START",t[t.TRANSFORM_FEEDBACK_BUFFER_SIZE=35973]="TRANSFORM_FEEDBACK_BUFFER_SIZE",t[t.TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN=35976]="TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN",t[t.MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS=35978]="MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS",t[t.MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS=35979]="MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS",t[t.INTERLEAVED_ATTRIBS=35980]="INTERLEAVED_ATTRIBS",t[t.SEPARATE_ATTRIBS=35981]="SEPARATE_ATTRIBS",t[t.TRANSFORM_FEEDBACK_BUFFER=35982]="TRANSFORM_FEEDBACK_BUFFER",t[t.TRANSFORM_FEEDBACK_BUFFER_BINDING=35983]="TRANSFORM_FEEDBACK_BUFFER_BINDING",t[t.TRANSFORM_FEEDBACK=36386]="TRANSFORM_FEEDBACK",t[t.TRANSFORM_FEEDBACK_PAUSED=36387]="TRANSFORM_FEEDBACK_PAUSED",t[t.TRANSFORM_FEEDBACK_ACTIVE=36388]="TRANSFORM_FEEDBACK_ACTIVE",t[t.TRANSFORM_FEEDBACK_BINDING=36389]="TRANSFORM_FEEDBACK_BINDING",t[t.FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING=33296]="FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING",t[t.FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE=33297]="FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE",t[t.FRAMEBUFFER_ATTACHMENT_RED_SIZE=33298]="FRAMEBUFFER_ATTACHMENT_RED_SIZE",t[t.FRAMEBUFFER_ATTACHMENT_GREEN_SIZE=33299]="FRAMEBUFFER_ATTACHMENT_GREEN_SIZE",t[t.FRAMEBUFFER_ATTACHMENT_BLUE_SIZE=33300]="FRAMEBUFFER_ATTACHMENT_BLUE_SIZE",t[t.FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE=33301]="FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE",t[t.FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE=33302]="FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE",t[t.FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE=33303]="FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE",t[t.FRAMEBUFFER_DEFAULT=33304]="FRAMEBUFFER_DEFAULT",t[t.DEPTH24_STENCIL8=35056]="DEPTH24_STENCIL8",t[t.DRAW_FRAMEBUFFER_BINDING=36006]="DRAW_FRAMEBUFFER_BINDING",t[t.READ_FRAMEBUFFER_BINDING=36010]="READ_FRAMEBUFFER_BINDING",t[t.RENDERBUFFER_SAMPLES=36011]="RENDERBUFFER_SAMPLES",t[t.FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER=36052]="FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER",t[t.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE=36182]="FRAMEBUFFER_INCOMPLETE_MULTISAMPLE",t[t.UNIFORM_BUFFER=35345]="UNIFORM_BUFFER",t[t.UNIFORM_BUFFER_BINDING=35368]="UNIFORM_BUFFER_BINDING",t[t.UNIFORM_BUFFER_START=35369]="UNIFORM_BUFFER_START",t[t.UNIFORM_BUFFER_SIZE=35370]="UNIFORM_BUFFER_SIZE",t[t.MAX_VERTEX_UNIFORM_BLOCKS=35371]="MAX_VERTEX_UNIFORM_BLOCKS",t[t.MAX_FRAGMENT_UNIFORM_BLOCKS=35373]="MAX_FRAGMENT_UNIFORM_BLOCKS",t[t.MAX_COMBINED_UNIFORM_BLOCKS=35374]="MAX_COMBINED_UNIFORM_BLOCKS",t[t.MAX_UNIFORM_BUFFER_BINDINGS=35375]="MAX_UNIFORM_BUFFER_BINDINGS",t[t.MAX_UNIFORM_BLOCK_SIZE=35376]="MAX_UNIFORM_BLOCK_SIZE",t[t.MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS=35377]="MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS",t[t.MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS=35379]="MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS",t[t.UNIFORM_BUFFER_OFFSET_ALIGNMENT=35380]="UNIFORM_BUFFER_OFFSET_ALIGNMENT",t[t.ACTIVE_UNIFORM_BLOCKS=35382]="ACTIVE_UNIFORM_BLOCKS",t[t.UNIFORM_TYPE=35383]="UNIFORM_TYPE",t[t.UNIFORM_SIZE=35384]="UNIFORM_SIZE",t[t.UNIFORM_BLOCK_INDEX=35386]="UNIFORM_BLOCK_INDEX",t[t.UNIFORM_OFFSET=35387]="UNIFORM_OFFSET",t[t.UNIFORM_ARRAY_STRIDE=35388]="UNIFORM_ARRAY_STRIDE",t[t.UNIFORM_MATRIX_STRIDE=35389]="UNIFORM_MATRIX_STRIDE",t[t.UNIFORM_IS_ROW_MAJOR=35390]="UNIFORM_IS_ROW_MAJOR",t[t.UNIFORM_BLOCK_BINDING=35391]="UNIFORM_BLOCK_BINDING",t[t.UNIFORM_BLOCK_DATA_SIZE=35392]="UNIFORM_BLOCK_DATA_SIZE",t[t.UNIFORM_BLOCK_ACTIVE_UNIFORMS=35394]="UNIFORM_BLOCK_ACTIVE_UNIFORMS",t[t.UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES=35395]="UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES",t[t.UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER=35396]="UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER",t[t.UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER=35398]="UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER",t[t.OBJECT_TYPE=37138]="OBJECT_TYPE",t[t.SYNC_CONDITION=37139]="SYNC_CONDITION",t[t.SYNC_STATUS=37140]="SYNC_STATUS",t[t.SYNC_FLAGS=37141]="SYNC_FLAGS",t[t.SYNC_FENCE=37142]="SYNC_FENCE",t[t.SYNC_GPU_COMMANDS_COMPLETE=37143]="SYNC_GPU_COMMANDS_COMPLETE",t[t.UNSIGNALED=37144]="UNSIGNALED",t[t.SIGNALED=37145]="SIGNALED",t[t.ALREADY_SIGNALED=37146]="ALREADY_SIGNALED",t[t.TIMEOUT_EXPIRED=37147]="TIMEOUT_EXPIRED",t[t.CONDITION_SATISFIED=37148]="CONDITION_SATISFIED",t[t.WAIT_FAILED=37149]="WAIT_FAILED",t[t.SYNC_FLUSH_COMMANDS_BIT=1]="SYNC_FLUSH_COMMANDS_BIT",t[t.COLOR=6144]="COLOR",t[t.DEPTH=6145]="DEPTH",t[t.STENCIL=6146]="STENCIL",t[t.MIN=32775]="MIN",t[t.MAX=32776]="MAX",t[t.DEPTH_COMPONENT24=33190]="DEPTH_COMPONENT24",t[t.STREAM_READ=35041]="STREAM_READ",t[t.STREAM_COPY=35042]="STREAM_COPY",t[t.STATIC_READ=35045]="STATIC_READ",t[t.STATIC_COPY=35046]="STATIC_COPY",t[t.DYNAMIC_READ=35049]="DYNAMIC_READ",t[t.DYNAMIC_COPY=35050]="DYNAMIC_COPY",t[t.DEPTH_COMPONENT32F=36012]="DEPTH_COMPONENT32F",t[t.DEPTH32F_STENCIL8=36013]="DEPTH32F_STENCIL8",t[t.INVALID_INDEX=4294967295]="INVALID_INDEX",t[t.TIMEOUT_IGNORED=-1]="TIMEOUT_IGNORED",t[t.MAX_CLIENT_WAIT_TIMEOUT_WEBGL=37447]="MAX_CLIENT_WAIT_TIMEOUT_WEBGL",t[t.UNMASKED_VENDOR_WEBGL=37445]="UNMASKED_VENDOR_WEBGL",t[t.UNMASKED_RENDERER_WEBGL=37446]="UNMASKED_RENDERER_WEBGL",t[t.MAX_TEXTURE_MAX_ANISOTROPY_EXT=34047]="MAX_TEXTURE_MAX_ANISOTROPY_EXT",t[t.TEXTURE_MAX_ANISOTROPY_EXT=34046]="TEXTURE_MAX_ANISOTROPY_EXT",t[t.R16_EXT=33322]="R16_EXT",t[t.RG16_EXT=33324]="RG16_EXT",t[t.RGB16_EXT=32852]="RGB16_EXT",t[t.RGBA16_EXT=32859]="RGBA16_EXT",t[t.R16_SNORM_EXT=36760]="R16_SNORM_EXT",t[t.RG16_SNORM_EXT=36761]="RG16_SNORM_EXT",t[t.RGB16_SNORM_EXT=36762]="RGB16_SNORM_EXT",t[t.RGBA16_SNORM_EXT=36763]="RGBA16_SNORM_EXT",t[t.COMPRESSED_RGB_S3TC_DXT1_EXT=33776]="COMPRESSED_RGB_S3TC_DXT1_EXT",t[t.COMPRESSED_RGBA_S3TC_DXT1_EXT=33777]="COMPRESSED_RGBA_S3TC_DXT1_EXT",t[t.COMPRESSED_RGBA_S3TC_DXT3_EXT=33778]="COMPRESSED_RGBA_S3TC_DXT3_EXT",t[t.COMPRESSED_RGBA_S3TC_DXT5_EXT=33779]="COMPRESSED_RGBA_S3TC_DXT5_EXT",t[t.COMPRESSED_SRGB_S3TC_DXT1_EXT=35916]="COMPRESSED_SRGB_S3TC_DXT1_EXT",t[t.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=35917]="COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT",t[t.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT=35918]="COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT",t[t.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=35919]="COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT",t[t.COMPRESSED_RED_RGTC1_EXT=36283]="COMPRESSED_RED_RGTC1_EXT",t[t.COMPRESSED_SIGNED_RED_RGTC1_EXT=36284]="COMPRESSED_SIGNED_RED_RGTC1_EXT",t[t.COMPRESSED_RED_GREEN_RGTC2_EXT=36285]="COMPRESSED_RED_GREEN_RGTC2_EXT",t[t.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT=36286]="COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT",t[t.COMPRESSED_RGBA_BPTC_UNORM_EXT=36492]="COMPRESSED_RGBA_BPTC_UNORM_EXT",t[t.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT=36493]="COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT",t[t.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT=36494]="COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT",t[t.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT=36495]="COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT",t[t.COMPRESSED_R11_EAC=37488]="COMPRESSED_R11_EAC",t[t.COMPRESSED_SIGNED_R11_EAC=37489]="COMPRESSED_SIGNED_R11_EAC",t[t.COMPRESSED_RG11_EAC=37490]="COMPRESSED_RG11_EAC",t[t.COMPRESSED_SIGNED_RG11_EAC=37491]="COMPRESSED_SIGNED_RG11_EAC",t[t.COMPRESSED_RGB8_ETC2=37492]="COMPRESSED_RGB8_ETC2",t[t.COMPRESSED_RGBA8_ETC2_EAC=37493]="COMPRESSED_RGBA8_ETC2_EAC",t[t.COMPRESSED_SRGB8_ETC2=37494]="COMPRESSED_SRGB8_ETC2",t[t.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=37495]="COMPRESSED_SRGB8_ALPHA8_ETC2_EAC",t[t.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2=37496]="COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2",t[t.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2=37497]="COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2",t[t.COMPRESSED_RGB_PVRTC_4BPPV1_IMG=35840]="COMPRESSED_RGB_PVRTC_4BPPV1_IMG",t[t.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=35842]="COMPRESSED_RGBA_PVRTC_4BPPV1_IMG",t[t.COMPRESSED_RGB_PVRTC_2BPPV1_IMG=35841]="COMPRESSED_RGB_PVRTC_2BPPV1_IMG",t[t.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG=35843]="COMPRESSED_RGBA_PVRTC_2BPPV1_IMG",t[t.COMPRESSED_RGB_ETC1_WEBGL=36196]="COMPRESSED_RGB_ETC1_WEBGL",t[t.COMPRESSED_RGB_ATC_WEBGL=35986]="COMPRESSED_RGB_ATC_WEBGL",t[t.COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL=35986]="COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL",t[t.COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL=34798]="COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL",t[t.COMPRESSED_RGBA_ASTC_4x4_KHR=37808]="COMPRESSED_RGBA_ASTC_4x4_KHR",t[t.COMPRESSED_RGBA_ASTC_5x4_KHR=37809]="COMPRESSED_RGBA_ASTC_5x4_KHR",t[t.COMPRESSED_RGBA_ASTC_5x5_KHR=37810]="COMPRESSED_RGBA_ASTC_5x5_KHR",t[t.COMPRESSED_RGBA_ASTC_6x5_KHR=37811]="COMPRESSED_RGBA_ASTC_6x5_KHR",t[t.COMPRESSED_RGBA_ASTC_6x6_KHR=37812]="COMPRESSED_RGBA_ASTC_6x6_KHR",t[t.COMPRESSED_RGBA_ASTC_8x5_KHR=37813]="COMPRESSED_RGBA_ASTC_8x5_KHR",t[t.COMPRESSED_RGBA_ASTC_8x6_KHR=37814]="COMPRESSED_RGBA_ASTC_8x6_KHR",t[t.COMPRESSED_RGBA_ASTC_8x8_KHR=37815]="COMPRESSED_RGBA_ASTC_8x8_KHR",t[t.COMPRESSED_RGBA_ASTC_10x5_KHR=37816]="COMPRESSED_RGBA_ASTC_10x5_KHR",t[t.COMPRESSED_RGBA_ASTC_10x6_KHR=37817]="COMPRESSED_RGBA_ASTC_10x6_KHR",t[t.COMPRESSED_RGBA_ASTC_10x8_KHR=37818]="COMPRESSED_RGBA_ASTC_10x8_KHR",t[t.COMPRESSED_RGBA_ASTC_10x10_KHR=37819]="COMPRESSED_RGBA_ASTC_10x10_KHR",t[t.COMPRESSED_RGBA_ASTC_12x10_KHR=37820]="COMPRESSED_RGBA_ASTC_12x10_KHR",t[t.COMPRESSED_RGBA_ASTC_12x12_KHR=37821]="COMPRESSED_RGBA_ASTC_12x12_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=37840]="COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR=37841]="COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR=37842]="COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR=37843]="COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR=37844]="COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR=37845]="COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR=37846]="COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR=37847]="COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR=37848]="COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR=37849]="COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR=37850]="COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR=37851]="COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR=37852]="COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR=37853]="COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR",t[t.QUERY_COUNTER_BITS_EXT=34916]="QUERY_COUNTER_BITS_EXT",t[t.CURRENT_QUERY_EXT=34917]="CURRENT_QUERY_EXT",t[t.QUERY_RESULT_EXT=34918]="QUERY_RESULT_EXT",t[t.QUERY_RESULT_AVAILABLE_EXT=34919]="QUERY_RESULT_AVAILABLE_EXT",t[t.TIME_ELAPSED_EXT=35007]="TIME_ELAPSED_EXT",t[t.TIMESTAMP_EXT=36392]="TIMESTAMP_EXT",t[t.GPU_DISJOINT_EXT=36795]="GPU_DISJOINT_EXT",t[t.COMPLETION_STATUS_KHR=37297]="COMPLETION_STATUS_KHR",t[t.DEPTH_CLAMP_EXT=34383]="DEPTH_CLAMP_EXT",t[t.FIRST_VERTEX_CONVENTION_WEBGL=36429]="FIRST_VERTEX_CONVENTION_WEBGL",t[t.LAST_VERTEX_CONVENTION_WEBGL=36430]="LAST_VERTEX_CONVENTION_WEBGL",t[t.PROVOKING_VERTEX_WEBL=36431]="PROVOKING_VERTEX_WEBL",t[t.POLYGON_MODE_WEBGL=2880]="POLYGON_MODE_WEBGL",t[t.POLYGON_OFFSET_LINE_WEBGL=10754]="POLYGON_OFFSET_LINE_WEBGL",t[t.LINE_WEBGL=6913]="LINE_WEBGL",t[t.FILL_WEBGL=6914]="FILL_WEBGL",t[t.MAX_CLIP_DISTANCES_WEBGL=3378]="MAX_CLIP_DISTANCES_WEBGL",t[t.MAX_CULL_DISTANCES_WEBGL=33529]="MAX_CULL_DISTANCES_WEBGL",t[t.MAX_COMBINED_CLIP_AND_CULL_DISTANCES_WEBGL=33530]="MAX_COMBINED_CLIP_AND_CULL_DISTANCES_WEBGL",t[t.CLIP_DISTANCE0_WEBGL=12288]="CLIP_DISTANCE0_WEBGL",t[t.CLIP_DISTANCE1_WEBGL=12289]="CLIP_DISTANCE1_WEBGL",t[t.CLIP_DISTANCE2_WEBGL=12290]="CLIP_DISTANCE2_WEBGL",t[t.CLIP_DISTANCE3_WEBGL=12291]="CLIP_DISTANCE3_WEBGL",t[t.CLIP_DISTANCE4_WEBGL=12292]="CLIP_DISTANCE4_WEBGL",t[t.CLIP_DISTANCE5_WEBGL=12293]="CLIP_DISTANCE5_WEBGL",t[t.CLIP_DISTANCE6_WEBGL=12294]="CLIP_DISTANCE6_WEBGL",t[t.CLIP_DISTANCE7_WEBGL=12295]="CLIP_DISTANCE7_WEBGL",t[t.POLYGON_OFFSET_CLAMP_EXT=36379]="POLYGON_OFFSET_CLAMP_EXT",t[t.LOWER_LEFT_EXT=36001]="LOWER_LEFT_EXT",t[t.UPPER_LEFT_EXT=36002]="UPPER_LEFT_EXT",t[t.NEGATIVE_ONE_TO_ONE_EXT=37726]="NEGATIVE_ONE_TO_ONE_EXT",t[t.ZERO_TO_ONE_EXT=37727]="ZERO_TO_ONE_EXT",t[t.CLIP_ORIGIN_EXT=37724]="CLIP_ORIGIN_EXT",t[t.CLIP_DEPTH_MODE_EXT=37725]="CLIP_DEPTH_MODE_EXT",t[t.SRC1_COLOR_WEBGL=35065]="SRC1_COLOR_WEBGL",t[t.SRC1_ALPHA_WEBGL=34185]="SRC1_ALPHA_WEBGL",t[t.ONE_MINUS_SRC1_COLOR_WEBGL=35066]="ONE_MINUS_SRC1_COLOR_WEBGL",t[t.ONE_MINUS_SRC1_ALPHA_WEBGL=35067]="ONE_MINUS_SRC1_ALPHA_WEBGL",t[t.MAX_DUAL_SOURCE_DRAW_BUFFERS_WEBGL=35068]="MAX_DUAL_SOURCE_DRAW_BUFFERS_WEBGL",t[t.MIRROR_CLAMP_TO_EDGE_EXT=34627]="MIRROR_CLAMP_TO_EDGE_EXT"})(Vr||(Vr={}))});var e1=P(()=>{Jb()});function t1(t=!0){let e=HTMLCanvasElement.prototype;if(!t&&e.originalGetContext){e.getContext=e.originalGetContext,e.originalGetContext=void 0;return}e.originalGetContext=e.getContext,e.getContext=function(r,i){if(r==="webgl"||r==="experimental-webgl"){let n=this.originalGetContext("webgl2",i);return n instanceof HTMLElement&&E4(n),n}return this.originalGetContext(r,i)}}function E4(t){t.getExtension("EXT_color_buffer_float");let e={...w4,WEBGL_disjoint_timer_query:t.getExtension("EXT_disjoint_timer_query_webgl2"),WEBGL_draw_buffers:S4(t),OES_vertex_array_object:A4(t),ANGLE_instanced_arrays:v4(t)},r=t.getExtension;t.getExtension=function(n){let o=r.call(t,n);return o||(n in e?e[n]:null)};let i=t.getSupportedExtensions;t.getSupportedExtensions=function(){return(i.apply(t)||[])?.concat(Object.keys(e))}}var w4,S4,A4,v4,r1=P(()=>{w4={WEBGL_depth_texture:{UNSIGNED_INT_24_8_WEBGL:34042},OES_element_index_uint:{},OES_texture_float:{},OES_texture_half_float:{HALF_FLOAT_OES:5131},EXT_color_buffer_float:{},OES_standard_derivatives:{FRAGMENT_SHADER_DERIVATIVE_HINT_OES:35723},EXT_frag_depth:{},EXT_blend_minmax:{MIN_EXT:32775,MAX_EXT:32776},EXT_shader_texture_lod:{}},S4=t=>({drawBuffersWEBGL(e){return t.drawBuffers(e)},COLOR_ATTACHMENT0_WEBGL:36064,COLOR_ATTACHMENT1_WEBGL:36065,COLOR_ATTACHMENT2_WEBGL:36066,COLOR_ATTACHMENT3_WEBGL:36067}),A4=t=>({VERTEX_ARRAY_BINDING_OES:34229,createVertexArrayOES(){return t.createVertexArray()},deleteVertexArrayOES(e){return t.deleteVertexArray(e)},isVertexArrayOES(e){return t.isVertexArray(e)},bindVertexArrayOES(e){return t.bindVertexArray(e)}}),v4=t=>({VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE:35070,drawArraysInstancedANGLE(...e){return t.drawArraysInstanced(...e)},drawElementsInstancedANGLE(...e){return t.drawElementsInstanced(...e)},vertexAttribDivisorANGLE(...e){return t.vertexAttribDivisor(...e)}})});async function Rl(t,e){let r=document.getElementsByTagName("head")[0];if(!r)throw new Error("loadScript");let i=document.createElement("script");return i.setAttribute("type","text/javascript"),i.setAttribute("src",t),e&&(i.id=e),new Promise((n,o)=>{i.onload=n,i.onerror=s=>o(new Error(`Unable to load script '${t}': ${s}`)),r.appendChild(i)})}var zp=P(()=>{});function Ii(t){let e=t.luma||{_polyfilled:!1,extensions:{},softwareRenderer:!1};return e._polyfilled??=!1,e.extensions||={},t.luma=e,e}var Cl=P(()=>{});async function n1(t){if(!globalThis.SPECTOR)try{await Rl(t.debugSpectorJSUrl||Pl.debugSpectorJSUrl)}catch(e){v.warn(String(e))}}function o1(t){if(t={...Pl,...t},!t.debugSpectorJS)return null;if(!Qe&&globalThis.SPECTOR&&!globalThis.luma?.spector){v.probe(R4,"SPECTOR found and initialized. Start with `luma.spector.displayUI()`")();let{Spector:e}=globalThis.SPECTOR;Qe=new e,globalThis.luma&&(globalThis.luma.spector=Qe)}if(!Qe)return null;if(i1||(i1=!0,Qe.spyCanvases(),Qe?.onCaptureStarted.add(e=>v.info("Spector capture started:",e)()),Qe?.onCapture.add(e=>{v.info("Spector capture complete:",e)(),Qe?.getResultUI(),Qe?.resultView.display(),Qe?.resultView.addCapture(e)})),t.gl){let e=t.gl,r=Ii(e),i=r.device;Qe?.startCapture(t.gl,500),r.device=i,new Promise(n=>setTimeout(n,2e3)).then(n=>{v.info("Spector capture stopped after 2 seconds")(),Qe?.stopCapture()})}return Qe}var R4,Qe,i1,Pl,Wp=P(()=>{z();zp();Cl();R4=1,Qe=null,i1=!1,Pl={debugSpectorJS:v.get("debug-spectorjs"),debugSpectorJSUrl:"https://cdn.jsdelivr.net/npm/spectorjs@0.9.30/dist/spector.bundle.js",gl:void 0}});function a1(t){return t.luma=t.luma||{},t.luma}async function c1(){De()&&!globalThis.WebGLDebugUtils&&(globalThis.global=globalThis.global||globalThis,globalThis.global.module={},await Rl(C4))}function l1(t,e={}){return e.debugWebGL||e.traceWebGL?M4(t,e):P4(t)}function P4(t){let e=a1(t);return e.realContext?e.realContext:t}function M4(t,e){if(!globalThis.WebGLDebugUtils)return v.warn("webgl-debug not loaded")(),t;let r=a1(t);if(r.debugContext)return r.debugContext;globalThis.WebGLDebugUtils.init({...Vr,...t});let i=globalThis.WebGLDebugUtils.makeDebugContext(t,I4.bind(null,e),O4.bind(null,e));for(let s in Vr)!(s in i)&&typeof Vr[s]=="number"&&(i[s]=Vr[s]);class n{}Object.setPrototypeOf(i,Object.getPrototypeOf(t)),Object.setPrototypeOf(n,i);let o=Object.create(n);return r.realContext=t,r.debugContext=o,o.luma=r,o.debug=!0,o}function s1(t,e){e=Array.from(e).map(i=>i===void 0?"undefined":i);let r=globalThis.WebGLDebugUtils.glFunctionArgsToString(t,e);return r=`${r.slice(0,100)}${r.length>100?"...":""}`,`gl.${t}(${r})`}function I4(t,e,r,i){i=Array.from(i).map(a=>a===void 0?"undefined":a);let n=globalThis.WebGLDebugUtils.glEnumToString(e),o=globalThis.WebGLDebugUtils.glFunctionArgsToString(r,i),s=`${n} in gl.${r}(${o})`;v.error("%cWebGL","color: white; background: red; padding: 2px 6px; border-radius: 3px;",s)();debugger;throw new Error(s)}function O4(t,e,r){let i="";t.traceWebGL&&v.level>=1&&(i=s1(e,r),v.info(1,"%cWebGL","color: white; background: blue; padding: 2px 6px; border-radius: 3px;",i)());for(let n of r)if(n===void 0){i=i||s1(e,r);debugger}}var C4,Vp=P(()=>{z();e1();Rr();zp();C4="https://unpkg.com/webgl-debug@2.0.1/index.js"});function jp(t){return Array.isArray(t)||ArrayBuffer.isView(t)&&!(t instanceof DataView)}function fe(t,e,r){return e[t]!==void 0?e[t]:r[t]}var Ls,pe,f1,Je,u1,Ds,d1,h1,$p,Vt,Hp,p1,Yp=P(()=>{Ls={3042:!1,32773:new Float32Array([0,0,0,0]),32777:32774,34877:32774,32969:1,32968:0,32971:1,32970:0,3106:new Float32Array([0,0,0,0]),3107:[!0,!0,!0,!0],2884:!1,2885:1029,2929:!1,2931:1,2932:513,2928:new Float32Array([0,1]),2930:!0,3024:!0,35725:null,36006:null,36007:null,34229:null,34964:null,2886:2305,33170:4352,2849:1,32823:!1,32824:0,10752:0,32926:!1,32928:!1,32938:1,32939:!1,3089:!1,3088:new Int32Array([0,0,1024,1024]),2960:!1,2961:0,2968:4294967295,36005:4294967295,2962:519,2967:0,2963:4294967295,34816:519,36003:0,36004:4294967295,2964:7680,2965:7680,2966:7680,34817:7680,34818:7680,34819:7680,2978:[0,0,1024,1024],36389:null,36662:null,36663:null,35053:null,35055:null,35723:4352,36010:null,35977:!1,3333:4,3317:4,37440:!1,37441:!1,37443:37444,3330:0,3332:0,3331:0,3314:0,32878:0,3316:0,3315:0,32877:0},pe=(t,e,r)=>e?t.enable(r):t.disable(r),f1=(t,e,r)=>t.hint(r,e),Je=(t,e,r)=>t.pixelStorei(r,e),u1=(t,e,r)=>{let i=r===36006?36009:36008;return t.bindFramebuffer(i,e)},Ds=(t,e,r)=>{let n={34964:34962,36662:36662,36663:36663,35053:35051,35055:35052}[r];t.bindBuffer(n,e)};d1={3042:pe,32773:(t,e)=>t.blendColor(...e),32777:"blendEquation",34877:"blendEquation",32969:"blendFunc",32968:"blendFunc",32971:"blendFunc",32970:"blendFunc",3106:(t,e)=>t.clearColor(...e),3107:(t,e)=>t.colorMask(...e),2884:pe,2885:(t,e)=>t.cullFace(e),2929:pe,2931:(t,e)=>t.clearDepth(e),2932:(t,e)=>t.depthFunc(e),2928:(t,e)=>t.depthRange(...e),2930:(t,e)=>t.depthMask(e),3024:pe,35723:f1,35725:(t,e)=>t.useProgram(e),36007:(t,e)=>t.bindRenderbuffer(36161,e),36389:(t,e)=>t.bindTransformFeedback?.(36386,e),34229:(t,e)=>t.bindVertexArray(e),36006:u1,36010:u1,34964:Ds,36662:Ds,36663:Ds,35053:Ds,35055:Ds,2886:(t,e)=>t.frontFace(e),33170:f1,2849:(t,e)=>t.lineWidth(e),32823:pe,32824:"polygonOffset",10752:"polygonOffset",35977:pe,32926:pe,32928:pe,32938:"sampleCoverage",32939:"sampleCoverage",3089:pe,3088:(t,e)=>t.scissor(...e),2960:pe,2961:(t,e)=>t.clearStencil(e),2968:(t,e)=>t.stencilMaskSeparate(1028,e),36005:(t,e)=>t.stencilMaskSeparate(1029,e),2962:"stencilFuncFront",2967:"stencilFuncFront",2963:"stencilFuncFront",34816:"stencilFuncBack",36003:"stencilFuncBack",36004:"stencilFuncBack",2964:"stencilOpFront",2965:"stencilOpFront",2966:"stencilOpFront",34817:"stencilOpBack",34818:"stencilOpBack",34819:"stencilOpBack",2978:(t,e)=>t.viewport(...e),34383:pe,10754:pe,12288:pe,12289:pe,12290:pe,12291:pe,12292:pe,12293:pe,12294:pe,12295:pe,3333:Je,3317:Je,37440:Je,37441:Je,37443:Je,3330:Je,3332:Je,3331:Je,3314:Je,32878:Je,3316:Je,3315:Je,32877:Je,framebuffer:(t,e)=>{let r=e&&"handle"in e?e.handle:e;return t.bindFramebuffer(36160,r)},blend:(t,e)=>e?t.enable(3042):t.disable(3042),blendColor:(t,e)=>t.blendColor(...e),blendEquation:(t,e)=>{let r=typeof e=="number"?[e,e]:e;t.blendEquationSeparate(...r)},blendFunc:(t,e)=>{let r=e?.length===2?[...e,...e]:e;t.blendFuncSeparate(...r)},clearColor:(t,e)=>t.clearColor(...e),clearDepth:(t,e)=>t.clearDepth(e),clearStencil:(t,e)=>t.clearStencil(e),colorMask:(t,e)=>t.colorMask(...e),cull:(t,e)=>e?t.enable(2884):t.disable(2884),cullFace:(t,e)=>t.cullFace(e),depthTest:(t,e)=>e?t.enable(2929):t.disable(2929),depthFunc:(t,e)=>t.depthFunc(e),depthMask:(t,e)=>t.depthMask(e),depthRange:(t,e)=>t.depthRange(...e),dither:(t,e)=>e?t.enable(3024):t.disable(3024),derivativeHint:(t,e)=>{t.hint(35723,e)},frontFace:(t,e)=>t.frontFace(e),mipmapHint:(t,e)=>t.hint(33170,e),lineWidth:(t,e)=>t.lineWidth(e),polygonOffsetFill:(t,e)=>e?t.enable(32823):t.disable(32823),polygonOffset:(t,e)=>t.polygonOffset(...e),sampleCoverage:(t,e)=>t.sampleCoverage(e[0],e[1]||!1),scissorTest:(t,e)=>e?t.enable(3089):t.disable(3089),scissor:(t,e)=>t.scissor(...e),stencilTest:(t,e)=>e?t.enable(2960):t.disable(2960),stencilMask:(t,e)=>{e=jp(e)?e:[e,e];let[r,i]=e;t.stencilMaskSeparate(1028,r),t.stencilMaskSeparate(1029,i)},stencilFunc:(t,e)=>{e=jp(e)&&e.length===3?[...e,...e]:e;let[r,i,n,o,s,a]=e;t.stencilFuncSeparate(1028,r,i,n),t.stencilFuncSeparate(1029,o,s,a)},stencilOp:(t,e)=>{e=jp(e)&&e.length===3?[...e,...e]:e;let[r,i,n,o,s,a]=e;t.stencilOpSeparate(1028,r,i,n),t.stencilOpSeparate(1029,o,s,a)},viewport:(t,e)=>t.viewport(...e)};h1={blendEquation:(t,e,r)=>t.blendEquationSeparate(fe(32777,e,r),fe(34877,e,r)),blendFunc:(t,e,r)=>t.blendFuncSeparate(fe(32969,e,r),fe(32968,e,r),fe(32971,e,r),fe(32970,e,r)),polygonOffset:(t,e,r)=>t.polygonOffset(fe(32824,e,r),fe(10752,e,r)),sampleCoverage:(t,e,r)=>t.sampleCoverage(fe(32938,e,r),fe(32939,e,r)),stencilFuncFront:(t,e,r)=>t.stencilFuncSeparate(1028,fe(2962,e,r),fe(2967,e,r),fe(2963,e,r)),stencilFuncBack:(t,e,r)=>t.stencilFuncSeparate(1029,fe(34816,e,r),fe(36003,e,r),fe(36004,e,r)),stencilOpFront:(t,e,r)=>t.stencilOpSeparate(1028,fe(2964,e,r),fe(2965,e,r),fe(2966,e,r)),stencilOpBack:(t,e,r)=>t.stencilOpSeparate(1029,fe(34817,e,r),fe(34818,e,r),fe(34819,e,r))},$p={enable:(t,e)=>t({[e]:!0}),disable:(t,e)=>t({[e]:!1}),pixelStorei:(t,e,r)=>t({[e]:r}),hint:(t,e,r)=>t({[e]:r}),useProgram:(t,e)=>t({35725:e}),bindRenderbuffer:(t,e,r)=>t({36007:r}),bindTransformFeedback:(t,e,r)=>t({36389:r}),bindVertexArray:(t,e)=>t({34229:e}),bindFramebuffer:(t,e,r)=>{switch(e){case 36160:return t({36006:r,36010:r});case 36009:return t({36006:r});case 36008:return t({36010:r});default:return null}},bindBuffer:(t,e,r)=>{let i={34962:[34964],36662:[36662],36663:[36663],35051:[35053],35052:[35055]}[e];return i?t({[i]:r}):{valueChanged:!0}},blendColor:(t,e,r,i,n)=>t({32773:new Float32Array([e,r,i,n])}),blendEquation:(t,e)=>t({32777:e,34877:e}),blendEquationSeparate:(t,e,r)=>t({32777:e,34877:r}),blendFunc:(t,e,r)=>t({32969:e,32968:r,32971:e,32970:r}),blendFuncSeparate:(t,e,r,i,n)=>t({32969:e,32968:r,32971:i,32970:n}),clearColor:(t,e,r,i,n)=>t({3106:new Float32Array([e,r,i,n])}),clearDepth:(t,e)=>t({2931:e}),clearStencil:(t,e)=>t({2961:e}),colorMask:(t,e,r,i,n)=>t({3107:[e,r,i,n]}),cullFace:(t,e)=>t({2885:e}),depthFunc:(t,e)=>t({2932:e}),depthRange:(t,e,r)=>t({2928:new Float32Array([e,r])}),depthMask:(t,e)=>t({2930:e}),frontFace:(t,e)=>t({2886:e}),lineWidth:(t,e)=>t({2849:e}),polygonOffset:(t,e,r)=>t({32824:e,10752:r}),sampleCoverage:(t,e,r)=>t({32938:e,32939:r}),scissor:(t,e,r,i,n)=>t({3088:new Int32Array([e,r,i,n])}),stencilMask:(t,e)=>t({2968:e,36005:e}),stencilMaskSeparate:(t,e,r)=>t({[e===1028?2968:36005]:r}),stencilFunc:(t,e,r,i)=>t({2962:e,2967:r,2963:i,34816:e,36003:r,36004:i}),stencilFuncSeparate:(t,e,r,i,n)=>t({[e===1028?2962:34816]:r,[e===1028?2967:36003]:i,[e===1028?2963:36004]:n}),stencilOp:(t,e,r,i)=>t({2964:e,2965:r,2966:i,34817:e,34818:r,34819:i}),stencilOpSeparate:(t,e,r,i,n)=>t({[e===1028?2964:34817]:r,[e===1028?2965:34818]:i,[e===1028?2966:34819]:n}),viewport:(t,e,r,i,n)=>t({2978:[e,r,i,n]})},Vt=(t,e)=>t.isEnabled(e),Hp={3042:Vt,2884:Vt,2929:Vt,3024:Vt,32823:Vt,32926:Vt,32928:Vt,3089:Vt,2960:Vt,35977:Vt},p1=new Set([34016,36388,36387,35983,35368,34965,35739,35738,3074,34853,34854,34855,34856,34857,34858,34859,34860,34861,34862,34863,34864,34865,34866,34867,34868,35097,32873,35869,32874,34068])});function bt(t,e){if(N4(e))return;let r={};for(let n in e){let o=Number(n),s=d1[n];s&&(typeof s=="string"?r[s]=!0:s(t,e[n],o))}let i=t.lumaState?.cache;if(i)for(let n in r){let o=h1[n];o(t,e,i)}}function Ml(t,e=Ls){if(typeof e=="number"){let n=e,o=Hp[n];return o?o(t,n):t.getParameter(n)}let r=Array.isArray(e)?e:Object.keys(e),i={};for(let n of r){let o=Hp[n];i[n]=o?o(t,Number(n)):t.getParameter(Number(n))}return i}function g1(t){bt(t,Ls)}function N4(t){for(let e in t)return!1;return!0}var Nn=P(()=>{Yp()});function _1(t,e){if(t===e)return!0;if(m1(t)&&m1(e)&&t.length===e.length){for(let r=0;r{});function x1(t,e){let r=t[e].bind(t);t[e]=function(n){if(n===void 0||p1.has(n))return r(n);let o=Tt.get(t);return n in o.cache||(o.cache[n]=r(n)),o.enable?o.cache[n]:r(n)},Object.defineProperty(t[e],"name",{value:`${e}-from-cache`,configurable:!1})}function D4(t,e,r){if(!t[e])return;let i=t[e].bind(t);t[e]=function(...o){let s=Tt.get(t),{valueChanged:a,oldValue:c}=r(s._updateCache,...o);return a&&i(...o),c},Object.defineProperty(t[e],"name",{value:`${e}-to-cache`,configurable:!1})}function L4(t){let e=t.useProgram.bind(t);t.useProgram=function(i){let n=Tt.get(t);n.program!==i&&(e(i),n.program=i)}}var Tt,Xp=P(()=>{Nn();y1();Yp();Tt=class{static get(e){return e.lumaState}gl;program=null;stateStack=[];enable=!0;cache=null;log;initialized=!1;constructor(e,r){this.gl=e,this.log=r?.log||(()=>{}),this._updateCache=this._updateCache.bind(this),Object.seal(this)}push(e={}){this.stateStack.push({})}pop(){let e=this.stateStack[this.stateStack.length-1];bt(this.gl,e),this.stateStack.pop()}trackState(e,r){if(this.cache=r?.copyState?Ml(e):Object.assign({},Ls),this.initialized)throw new Error("WebGLStateTracker");this.initialized=!0,this.gl.lumaState=this,L4(e);for(let i in $p){let n=$p[i];D4(e,i,n)}x1(e,"getParameter"),x1(e,"isEnabled")}_updateCache(e){let r=!1,i,n=this.stateStack.length>0?this.stateStack[this.stateStack.length-1]:null;for(let o in e){let s=e[o],a=this.cache[o];_1(s,a)||(r=!0,i=a,n&&!(o in n)&&(n[o]=a),this.cache[o]=s)}return{valueChanged:r,oldValue:i}}}});function b1(t,e,r){let i="",n=c=>{let l=c.statusMessage;l&&(i||=l)};t.addEventListener("webglcontextcreationerror",n,!1);let o=r.failIfMajorPerformanceCaveat!==!0,s={preserveDrawingBuffer:!0,...r,failIfMajorPerformanceCaveat:!0},a=null;try{a||=t.getContext("webgl2",s),!a&&s.failIfMajorPerformanceCaveat&&(i||="Only software GPU is available. Set `failIfMajorPerformanceCaveat: false` to allow.");let c=!1;if(!a&&o&&(s.failIfMajorPerformanceCaveat=!1,a=t.getContext("webgl2",s),c=!0),a||(a=t.getContext("webgl",{}),a&&(a=null,i||="Your browser only supports WebGL1")),!a)throw i||="Your browser does not support WebGL",new Error(`Failed to create WebGL context: ${i}`);let l=Ii(a);l.softwareRenderer=c;let{onContextLost:f,onContextRestored:u}=e;return t.addEventListener("webglcontextlost",d=>f(d),!1),t.addEventListener("webglcontextrestored",d=>u(d),!1),a}finally{t.removeEventListener("webglcontextcreationerror",n,!1)}}var T1=P(()=>{Cl()});function wt(t,e,r){return r[e]===void 0&&(r[e]=t.getExtension(e)||null),r[e]}var Fs=P(()=>{});function w1(t,e){let r=t.getParameter(7936),i=t.getParameter(7937);wt(t,"WEBGL_debug_renderer_info",e);let n=e.WEBGL_debug_renderer_info,o=t.getParameter(n?n.UNMASKED_VENDOR_WEBGL:7936),s=t.getParameter(n?n.UNMASKED_RENDERER_WEBGL:7937),a=o||r,c=s||i,l=t.getParameter(7938),f=S1(a,c),u=F4(a,c),d=B4(a,c);return{type:"webgl",gpu:f,gpuType:d,gpuBackend:u,vendor:a,renderer:c,version:l,shadingLanguage:"glsl",shadingLanguageVersion:300}}function S1(t,e){return/NVIDIA/i.exec(t)||/NVIDIA/i.exec(e)?"nvidia":/INTEL/i.exec(t)||/INTEL/i.exec(e)?"intel":/Apple/i.exec(t)||/Apple/i.exec(e)?"apple":/AMD/i.exec(t)||/AMD/i.exec(e)||/ATI/i.exec(t)||/ATI/i.exec(e)?"amd":/SwiftShader/i.exec(t)||/SwiftShader/i.exec(e)?"software":"unknown"}function F4(t,e){return/Metal/i.exec(t)||/Metal/i.exec(e)?"metal":/ANGLE/i.exec(t)||/ANGLE/i.exec(e)?"opengl":"unknown"}function B4(t,e){if(/SwiftShader/i.exec(t)||/SwiftShader/i.exec(e))return"cpu";switch(S1(t,e)){case"apple":return k4(t,e)?"integrated":"unknown";case"intel":return"integrated";case"software":return"cpu";case"unknown":return"unknown";default:return"discrete"}}function k4(t,e){return/Apple (M\d|A\d|GPU)/i.test(`${t} ${e}`)}var A1=P(()=>{Fs()});function Il(t){switch(t){case"uint8":return 5121;case"sint8":return 5120;case"unorm8":return 5121;case"snorm8":return 5120;case"uint16":return 5123;case"sint16":return 5122;case"unorm16":return 5123;case"snorm16":return 5122;case"uint32":return 5125;case"sint32":return 5124;case"float16":return 5131;case"float32":return 5126}throw new Error(String(t))}var Gp=P(()=>{});function R1(t){return t in Nl}function Jp(t,e,r){return C1(t,e,r,new Set)}function C1(t,e,r,i){let n=Nl[e];if(!n||i.has(e))return!1;i.add(e);let o=(n.features||[]).every(s=>C1(t,s,r,i));return i.delete(e),o?(n.extensions||[]).every(s=>!!wt(t,s,r)):!1}function P1(t,e,r){let i=e.create,n=Dl[e.format];n?.gl===void 0&&(i=!1),n?.x&&(i=i&&!!wt(t,n.x,r)),e.format==="stencil8"&&(i=!1);let o=n?.r===!1?!1:n?.r===void 0||Jp(t,n.r,r),s=i&&e.render&&o&&Y4(t,e.format,r);return{format:e.format,create:i&&e.create,render:s,filter:i&&e.filter,blend:i&&e.blend,store:i&&e.store}}function Y4(t,e,r){let i=Dl[e],n=i?.gl;if(n===void 0||i?.x&&!wt(t,i.x,r))return!1;let o=t.getParameter(32873),s=t.getParameter(36006),a=t.createTexture(),c=t.createFramebuffer();if(!a||!c)return!1;let l=0,f=Number(t.getError());for(;f!==l;)f=t.getError();let u=!1;try{if(t.bindTexture(3553,a),t.texStorage2D(3553,1,n,1,1),Number(t.getError())!==l)return!1;t.bindFramebuffer(36160,c),t.framebufferTexture2D(36160,36064,3553,a,0),u=Number(t.checkFramebufferStatus(36160))===36053&&Number(t.getError())===l}finally{t.bindFramebuffer(36160,s),t.deleteFramebuffer(c),t.bindTexture(3553,o),t.deleteTexture(a)}return u}function Ll(t){let e=Dl[t],r=G4(t),i=Ue.getInfo(t);return i.compressed&&(e.dataFormat=r),{internalFormat:r,format:e?.dataFormat||X4(i.channels,i.integer,i.normalized,r),type:i.dataType?Il(i.dataType):e?.types?.[0]||5121,compressed:i.compressed||!1}}function M1(t){switch(Ue.getInfo(t).attachment){case"depth":return 36096;case"stencil":return 36128;case"depth-stencil":return 33306;default:throw new Error(`Not a depth stencil format: ${t}`)}}function X4(t,e,r,i){if(i===6408||i===6407)return i;switch(t){case"r":return e&&!r?36244:6403;case"rg":return e&&!r?33320:33319;case"rgb":return e&&!r?36248:6407;case"rgba":return e&&!r?36249:6408;case"bgra":throw new Error("bgra pixels not supported by WebGL");default:return 6408}}function G4(t){let r=Dl[t]?.gl;if(r===void 0)throw new Error(`Unsupported texture format ${t}`);return r}var Bs,ks,Dn,Ln,U4,z4,W4,V4,j4,$4,v1,E1,qp,Kp,Zp,Qp,Ol,H4,Nl,Dl,Fn=P(()=>{z();Fs();Gp();Bs="WEBGL_compressed_texture_s3tc",ks="WEBGL_compressed_texture_s3tc_srgb",Dn="EXT_texture_compression_rgtc",Ln="EXT_texture_compression_bptc",U4="WEBGL_compressed_texture_etc",z4="WEBGL_compressed_texture_astc",W4="WEBGL_compressed_texture_etc1",V4="WEBGL_compressed_texture_pvrtc",j4="WEBGL_compressed_texture_atc",$4="EXT_texture_norm16",v1="EXT_render_snorm",E1="EXT_color_buffer_float",qp="snorm8-renderable-webgl",Kp="norm16-renderable-webgl",Zp="snorm16-renderable-webgl",Qp="float16-renderable-webgl",Ol="float32-renderable-webgl",H4="rgb9e5ufloat-renderable-webgl",Nl={"float32-renderable-webgl":{extensions:[E1]},"float16-renderable-webgl":{extensions:["EXT_color_buffer_half_float"]},"rgb9e5ufloat-renderable-webgl":{extensions:["WEBGL_render_shared_exponent"]},"snorm8-renderable-webgl":{extensions:[v1]},"norm16-webgl":{extensions:[$4]},"norm16-renderable-webgl":{features:["norm16-webgl"]},"snorm16-renderable-webgl":{features:["norm16-webgl"],extensions:[v1]},"float32-filterable":{extensions:["OES_texture_float_linear"]},"float16-filterable-webgl":{extensions:["OES_texture_half_float_linear"]},"texture-filterable-anisotropic-webgl":{extensions:["EXT_texture_filter_anisotropic"]},"texture-blend-float-webgl":{extensions:["EXT_float_blend"]},"texture-compression-bc":{extensions:[Bs,ks,Dn,Ln]},"texture-compression-bc5-webgl":{extensions:[Dn]},"texture-compression-bc7-webgl":{extensions:[Ln]},"texture-compression-etc2":{extensions:[U4]},"texture-compression-astc":{extensions:[z4]},"texture-compression-etc1-webgl":{extensions:[W4]},"texture-compression-pvrtc-webgl":{extensions:[V4]},"texture-compression-atc-webgl":{extensions:[j4]}};Dl={r8unorm:{gl:33321,rb:!0},r8snorm:{gl:36756,r:qp},r8uint:{gl:33330,rb:!0},r8sint:{gl:33329,rb:!0},rg8unorm:{gl:33323,rb:!0},rg8snorm:{gl:36757,r:qp},rg8uint:{gl:33336,rb:!0},rg8sint:{gl:33335,rb:!0},r16uint:{gl:33332,rb:!0},r16sint:{gl:33331,rb:!0},r16float:{gl:33325,rb:!0,r:Qp},r16unorm:{gl:33322,rb:!0,r:Kp},r16snorm:{gl:36760,r:Zp},"rgba4unorm-webgl":{gl:32854,rb:!0},"rgb565unorm-webgl":{gl:36194,rb:!0},"rgb5a1unorm-webgl":{gl:32855,rb:!0},"rgb8unorm-webgl":{gl:32849},"rgb8snorm-webgl":{gl:36758},rgba8unorm:{gl:32856},"rgba8unorm-srgb":{gl:35907},rgba8snorm:{gl:36759,r:qp},rgba8uint:{gl:36220},rgba8sint:{gl:36238},bgra8unorm:{},"bgra8unorm-srgb":{},rg16uint:{gl:33338},rg16sint:{gl:33337},rg16float:{gl:33327,rb:!0,r:Qp},rg16unorm:{gl:33324,r:Kp},rg16snorm:{gl:36761,r:Zp},r32uint:{gl:33334,rb:!0},r32sint:{gl:33333,rb:!0},r32float:{gl:33326,r:Ol},rgb9e5ufloat:{gl:35901,r:H4},rg11b10ufloat:{gl:35898,rb:!0},rgb10a2unorm:{gl:32857,rb:!0},rgb10a2uint:{gl:36975,rb:!0},"rgb16unorm-webgl":{gl:32852,r:!1},"rgb16snorm-webgl":{gl:36762,r:!1},rg32uint:{gl:33340,rb:!0},rg32sint:{gl:33339,rb:!0},rg32float:{gl:33328,rb:!0,r:Ol},rgba16uint:{gl:36214,rb:!0},rgba16sint:{gl:36232,rb:!0},rgba16float:{gl:34842,r:Qp},rgba16unorm:{gl:32859,rb:!0,r:Kp},rgba16snorm:{gl:36763,r:Zp},"rgb32float-webgl":{gl:34837,x:E1,r:Ol,dataFormat:6407,types:[5126]},rgba32uint:{gl:36208,rb:!0},rgba32sint:{gl:36226,rb:!0},rgba32float:{gl:34836,rb:!0,r:Ol},stencil8:{gl:36168,rb:!0},depth16unorm:{gl:33189,dataFormat:6402,types:[5123],rb:!0},depth24plus:{gl:33190,dataFormat:6402,types:[5125]},depth32float:{gl:36012,dataFormat:6402,types:[5126],rb:!0},"depth24plus-stencil8":{gl:35056,rb:!0,depthTexture:!0,dataFormat:34041,types:[34042]},"depth32float-stencil8":{gl:36013,dataFormat:34041,types:[36269],rb:!0},"bc1-rgb-unorm-webgl":{gl:33776,x:Bs},"bc1-rgb-unorm-srgb-webgl":{gl:35916,x:ks},"bc1-rgba-unorm":{gl:33777,x:Bs},"bc1-rgba-unorm-srgb":{gl:35916,x:ks},"bc2-rgba-unorm":{gl:33778,x:Bs},"bc2-rgba-unorm-srgb":{gl:35918,x:ks},"bc3-rgba-unorm":{gl:33779,x:Bs},"bc3-rgba-unorm-srgb":{gl:35919,x:ks},"bc4-r-unorm":{gl:36283,x:Dn},"bc4-r-snorm":{gl:36284,x:Dn},"bc5-rg-unorm":{gl:36285,x:Dn},"bc5-rg-snorm":{gl:36286,x:Dn},"bc6h-rgb-ufloat":{gl:36495,x:Ln},"bc6h-rgb-float":{gl:36494,x:Ln},"bc7-rgba-unorm":{gl:36492,x:Ln},"bc7-rgba-unorm-srgb":{gl:36493,x:Ln},"etc2-rgb8unorm":{gl:37492},"etc2-rgb8unorm-srgb":{gl:37494},"etc2-rgb8a1unorm":{gl:37496},"etc2-rgb8a1unorm-srgb":{gl:37497},"etc2-rgba8unorm":{gl:37493},"etc2-rgba8unorm-srgb":{gl:37495},"eac-r11unorm":{gl:37488},"eac-r11snorm":{gl:37489},"eac-rg11unorm":{gl:37490},"eac-rg11snorm":{gl:37491},"astc-4x4-unorm":{gl:37808},"astc-4x4-unorm-srgb":{gl:37840},"astc-5x4-unorm":{gl:37809},"astc-5x4-unorm-srgb":{gl:37841},"astc-5x5-unorm":{gl:37810},"astc-5x5-unorm-srgb":{gl:37842},"astc-6x5-unorm":{gl:37811},"astc-6x5-unorm-srgb":{gl:37843},"astc-6x6-unorm":{gl:37812},"astc-6x6-unorm-srgb":{gl:37844},"astc-8x5-unorm":{gl:37813},"astc-8x5-unorm-srgb":{gl:37845},"astc-8x6-unorm":{gl:37814},"astc-8x6-unorm-srgb":{gl:37846},"astc-8x8-unorm":{gl:37815},"astc-8x8-unorm-srgb":{gl:37847},"astc-10x5-unorm":{gl:37816},"astc-10x5-unorm-srgb":{gl:37848},"astc-10x6-unorm":{gl:37817},"astc-10x6-unorm-srgb":{gl:37849},"astc-10x8-unorm":{gl:37818},"astc-10x8-unorm-srgb":{gl:37850},"astc-10x10-unorm":{gl:37819},"astc-10x10-unorm-srgb":{gl:37851},"astc-12x10-unorm":{gl:37820},"astc-12x10-unorm-srgb":{gl:37852},"astc-12x12-unorm":{gl:37821},"astc-12x12-unorm-srgb":{gl:37853},"pvrtc-rgb4unorm-webgl":{gl:35840},"pvrtc-rgba4unorm-webgl":{gl:35842},"pvrtc-rgb2unorm-webgl":{gl:35841},"pvrtc-rgba2unorm-webgl":{gl:35843},"etc1-rbg-unorm-webgl":{gl:36196},"atc-rgb-unorm-webgl":{gl:35986},"atc-rgba-unorm-webgl":{gl:35986},"atc-rgbai-unorm-webgl":{gl:34798}}});var I1,Fl,O1=P(()=>{z();Fs();Fn();I1={"depth-clip-control":"EXT_depth_clamp","timestamp-query":"EXT_disjoint_timer_query_webgl2","compilation-status-async-webgl":"KHR_parallel_shader_compile","polygon-mode-webgl":"WEBGL_polygon_mode","provoking-vertex-webgl":"WEBGL_provoking_vertex","shader-clip-cull-distance-webgl":"WEBGL_clip_cull_distance","shader-noperspective-interpolation-webgl":"NV_shader_noperspective_interpolation","shader-conservative-depth-webgl":"EXT_conservative_depth"},Fl=class extends Oo{gl;extensions;testedFeatures=new Set;constructor(e,r,i){super([],i),this.gl=e,this.extensions=r,wt(e,"EXT_color_buffer_float",r)}*[Symbol.iterator](){let e=this.getFeatures();for(let r of e)this.has(r)&&(yield r);return[]}has(e){return this.disabledFeatures?.[e]?!1:(this.testedFeatures.has(e)||(this.testedFeatures.add(e),R1(e)&&Jp(this.gl,e,this.extensions)&&this.features.add(e),this.getWebGLFeature(e)&&this.features.add(e)),this.features.has(e))}initializeFeatures(){let e=this.getFeatures().filter(r=>r!=="polygon-mode-webgl");for(let r of e)this.has(r)}getFeatures(){return[...Object.keys(I1),...Object.keys(Nl)]}getWebGLFeature(e){let r=I1[e];return typeof r=="string"?!!wt(this.gl,r,this.extensions):!!r}}});var Bl,N1=P(()=>{z();Bl=class extends Io{get maxTextureDimension1D(){return 0}get maxTextureDimension2D(){return this.getParameter(3379)}get maxTextureDimension3D(){return this.getParameter(32883)}get maxTextureArrayLayers(){return this.getParameter(35071)}get maxBindGroups(){return 0}get maxDynamicUniformBuffersPerPipelineLayout(){return 0}get maxDynamicStorageBuffersPerPipelineLayout(){return 0}get maxSampledTexturesPerShaderStage(){return this.getParameter(35660)}get maxSamplersPerShaderStage(){return this.getParameter(35661)}get maxStorageBuffersPerShaderStage(){return 0}get maxStorageTexturesPerShaderStage(){return 0}get maxUniformBuffersPerShaderStage(){return this.getParameter(35375)}get maxUniformBufferBindingSize(){return this.getParameter(35376)}get maxStorageBufferBindingSize(){return 0}get minUniformBufferOffsetAlignment(){return this.getParameter(35380)}get minStorageBufferOffsetAlignment(){return 0}get maxVertexBuffers(){return 16}get maxVertexAttributes(){return this.getParameter(34921)}get maxVertexBufferArrayStride(){return 2048}get maxInterStageShaderVariables(){return this.getParameter(35659)}get maxComputeWorkgroupStorageSize(){return 0}get maxComputeInvocationsPerWorkgroup(){return 0}get maxComputeWorkgroupSizeX(){return 0}get maxComputeWorkgroupSizeY(){return 0}get maxComputeWorkgroupSizeZ(){return 0}get maxComputeWorkgroupsPerDimension(){return 0}gl;limits={};constructor(e){super(),this.gl=e}getParameter(e){return this.limits[e]===void 0&&(this.limits[e]=this.gl.getParameter(e)),this.limits[e]||0}}});function q4(t){return t<34069?t+34069:t}function K4(t){switch(t){case 36053:return"success";case 36054:return"Mismatched attachments";case 36055:return"No attachments";case 36057:return"Height/width mismatch";case 36061:return"Unsupported or split attachments";case 36182:return"Samples mismatch";default:return`${t}`}}var jt,kl=P(()=>{z();Fn();jt=class extends mi{device;gl;handle;colorAttachments=[];depthStencilAttachment=null;constructor(e,r){super(e,r);let i=r.handle===null;this.device=e,this.gl=e.gl,this.handle=this.props.handle||i?this.props.handle:this.gl.createFramebuffer(),i||(e._setWebGLDebugMetadata(this.handle,this,{spector:this.props}),r.handle||(this.autoCreateAttachmentTextures(),this.updateAttachments()))}destroy(){super.destroy(),!this.destroyed&&this.handle!==null&&!this.props.handle&&this.gl.deleteFramebuffer(this.handle)}updateAttachments(){let e=this.gl.bindFramebuffer(36160,this.handle);for(let r=0;r{z();kl();Ul=class extends Do{device;handle=null;_framebuffer=null;get[Symbol.toStringTag](){return"WebGLCanvasContext"}constructor(e,r){super(r),this.device=e,this._setAutoCreatedCanvasId(`${this.device.id}-canvas`),this._configureDevice()}_configureDevice(){(this.drawingBufferWidth!==this._framebuffer?.width||this.drawingBufferHeight!==this._framebuffer?.height)&&this._framebuffer?.resize([this.drawingBufferWidth,this.drawingBufferHeight])}_getCurrentFramebuffer(){return this._framebuffer||=new jt(this.device,{id:"canvas-context-framebuffer",handle:null,width:this.drawingBufferWidth,height:this.drawingBufferHeight}),this._framebuffer}}});var zl,L1=P(()=>{z();zl=class extends Lo{device;handle=null;context2d;get[Symbol.toStringTag](){return"WebGLPresentationContext"}constructor(e,r={}){super(r),this.device=e;let i=`${this[Symbol.toStringTag]}(${this.id})`;if(!this.device.getDefaultCanvasContext().offscreenCanvas)throw new Error(`${i}: WebGL PresentationContext requires the default CanvasContext canvas to be an OffscreenCanvas`);let o=this.canvas.getContext("2d");if(!o)throw new Error(`${i}: Failed to create 2d presentation context`);this.context2d=o,this._setAutoCreatedCanvasId(`${this.device.id}-presentation-canvas`),this._configureDevice(),this._startObservers()}present(){this._resizeDrawingBufferIfNeeded(),this.device.submit();let e=this.device.getDefaultCanvasContext(),[r,i]=e.getDrawingBufferSize();if(!(this.drawingBufferWidth===0||this.drawingBufferHeight===0||r===0||i===0||e.canvas.width===0||e.canvas.height===0)){if(r!==this.drawingBufferWidth||i!==this.drawingBufferHeight||e.canvas.width!==this.drawingBufferWidth||e.canvas.height!==this.drawingBufferHeight)throw new Error(`${this[Symbol.toStringTag]}(${this.id}): Default canvas context size ${r}x${i} does not match presentation size ${this.drawingBufferWidth}x${this.drawingBufferHeight}`);this.context2d.clearRect(0,0,this.drawingBufferWidth,this.drawingBufferHeight),this.context2d.drawImage(e.canvas,0,0)}}_configureDevice(){}_getCurrentFramebuffer(e){let r=this.device.getDefaultCanvasContext();return r.setDrawingBufferSize(this.drawingBufferWidth,this.drawingBufferHeight),r.getCurrentFramebuffer(e)}}});function F1(t="id"){eg[t]=eg[t]||1;let e=eg[t]++;return`${t}-${e}`}var eg,B1=P(()=>{eg={}});function Z4(t){return t&j.INDEX?34963:t&j.VERTEX?34962:t&j.UNIFORM?35345:34962}function Q4(t){return t&j.INDEX||t&j.VERTEX?35044:t&j.UNIFORM?35048:35044}var St,Wl=P(()=>{z();St=class extends j{device;gl;handle;glTarget;glUsage;glIndexType=5123;byteLength=0;bytesUsed=0;constructor(e,r={}){super(e,r),this.device=e,this.gl=this.device.gl;let i=typeof r=="object"?r.handle:void 0;this.handle=i||this.gl.createBuffer(),e._setWebGLDebugMetadata(this.handle,this,{spector:{...this.props,data:typeof this.props.data}}),this.glTarget=Z4(this.props.usage),this.glUsage=Q4(this.props.usage),this.glIndexType=this.props.indexType==="uint32"?5125:5123,r.data?this._initWithData(r.data,r.byteOffset,r.byteLength):this._initWithByteLength(r.byteLength||0)}destroy(){!this.destroyed&&this.handle&&(this.removeStats(),this.props.handle?this.trackDeallocatedReferencedMemory("Buffer"):(this.trackDeallocatedMemory(),this.gl.deleteBuffer(this.handle)),this.destroyed=!0,this.handle=null)}_initWithData(e,r=0,i=e.byteLength+r){let n=this.glTarget;this.gl.bindBuffer(n,this.handle),this.gl.bufferData(n,i,this.glUsage),this.gl.bufferSubData(n,r,e),this.gl.bindBuffer(n,null),this.bytesUsed=i,this.byteLength=i,this._setDebugData(e,r,i),this.props.handle?this.trackReferencedMemory(i,"Buffer"):this.trackAllocatedMemory(i)}_initWithByteLength(e){let r=e;e===0&&(r=new Float32Array(0));let i=this.glTarget;return this.gl.bindBuffer(i,this.handle),this.gl.bufferData(i,r,this.glUsage),this.gl.bindBuffer(i,null),this.bytesUsed=e,this.byteLength=e,this._setDebugData(null,0,e),this.props.handle?this.trackReferencedMemory(e,"Buffer"):this.trackAllocatedMemory(e),this}write(e,r=0){let i=ArrayBuffer.isView(e)?e:new Uint8Array(e),n=0,o=void 0,s=36663;this.gl.bindBuffer(s,this.handle),n!==0||o!==void 0?this.gl.bufferSubData(s,r,i,n,o):this.gl.bufferSubData(s,r,i),this.gl.bindBuffer(s,null),this._setDebugData(e,r,e.byteLength)}async mapAndWriteAsync(e,r=0,i=this.byteLength-r){let n=new ArrayBuffer(i);await e(n,"copied"),this.write(n,r)}async readAsync(e=0,r){return this.readSyncWebGL(e,r)}async mapAndReadAsync(e,r=0,i){let n=await this.readAsync(r,i);return await e(n.buffer,"copied")}readSyncWebGL(e=0,r){r=r??this.byteLength-e;let i=new Uint8Array(r),n=0;return this.gl.bindBuffer(36662,this.handle),this.gl.getBufferSubData(36662,e,i,n,r),this.gl.bindBuffer(36662,null),this._setDebugData(i,e,r),i}}});function k1(t){let e=t.split(/\r?\n/),r=[];for(let i of e){if(i.length<=1)continue;let n=i.trim(),o=i.split(":"),s=o[0]?.trim();if(o.length===2){let[h,p]=o;if(!h||!p){r.push({message:n,type:Vl(s||"info"),lineNum:0,linePos:0});continue}r.push({message:p.trim(),type:Vl(h),lineNum:0,linePos:0});continue}let[a,c,l,...f]=o;if(!a||!c||!l){r.push({message:o.slice(1).join(":").trim()||n,type:Vl(s||"info"),lineNum:0,linePos:0});continue}let u=parseInt(l,10);Number.isNaN(u)&&(u=0);let d=parseInt(c,10);Number.isNaN(d)&&(d=0),r.push({message:f.join(":").trim(),type:Vl(a),lineNum:u,linePos:d})}return r}function Vl(t){let e=["warning","error","info"],r=t.toLowerCase();return e.includes(r)?r:"info"}var U1=P(()=>{});var jl,z1=P(()=>{z();U1();jl=class extends gi{device;handle;constructor(e,r){switch(super(e,r),this.device=e,this.props.stage){case"vertex":this.handle=this.props.handle||this.device.gl.createShader(35633);break;case"fragment":this.handle=this.props.handle||this.device.gl.createShader(35632);break;default:throw new Error(this.props.stage)}e._setWebGLDebugMetadata(this.handle,this,{spector:this.props});let i=this._compile(this.source);i&&typeof i.catch=="function"&&i.catch(()=>{this.compilationStatus="error"})}destroy(){this.handle&&(this.removeStats(),this.device.gl.deleteShader(this.handle),this.destroyed=!0,this.handle.destroyed=!0)}get asyncCompilationStatus(){return this._waitForCompilationComplete().then(()=>(this._getCompilationStatus(),this.compilationStatus))}async getCompilationInfo(){return await this._waitForCompilationComplete(),this.getCompilationInfoSync()}getCompilationInfoSync(){let e=this.device.gl.getShaderInfoLog(this.handle);return e?k1(e):[]}getTranslatedSource(){return this.device.getExtension("WEBGL_debug_shaders").WEBGL_debug_shaders?.getTranslatedShaderSource(this.handle)||null}_compile(e){e=e.startsWith("#version ")?e:`#version 300 es +${e}`;let{gl:r}=this.device;if(r.shaderSource(this.handle,e),r.compileShader(this.handle),!this.device.props.debug){this.compilationStatus="pending";return}if(!this.device.features.has("compilation-status-async-webgl")){if(this._getCompilationStatus(),this.debugShader(),this.compilationStatus==="error")throw new Error(`GLSL compilation errors in ${this.props.stage} shader ${this.props.id}`);return}return v.once(1,"Shader compilation is asynchronous")(),this._waitForCompilationComplete().then(()=>{v.info(2,`Shader ${this.id} - async compilation complete: ${this.compilationStatus}`)(),this._getCompilationStatus(),this.debugShader()})}async _waitForCompilationComplete(){let e=async n=>await new Promise(o=>setTimeout(o,n));if(!this.device.features.has("compilation-status-async-webgl")){await e(10);return}let{gl:i}=this.device;for(;;){if(i.getShaderParameter(this.handle,37297))return;await e(10)}}_getCompilationStatus(){this.compilationStatus=this.device.gl.getShaderParameter(this.handle,35713)?"success":"error"}}});function V1(t,e,r,i){if(rN(e))return i(t);let n=t;n.pushState();try{return J4(t,e),bt(n.gl,r),i(t)}finally{n.popState()}}function J4(t,e){let r=t,{gl:i}=r;if(e.cullMode)switch(e.cullMode){case"none":i.disable(2884);break;case"front":i.enable(2884),i.cullFace(1028);break;case"back":i.enable(2884),i.cullFace(1029);break}if(e.frontFace&&i.frontFace(Oi("frontFace",e.frontFace,{ccw:2305,cw:2304})),e.unclippedDepth&&t.features.has("depth-clip-control")&&i.enable(34383),e.depthBias!==void 0&&(i.enable(32823),i.polygonOffset(e.depthBias,e.depthBiasSlopeScale||0)),e.provokingVertex&&t.features.has("provoking-vertex-webgl")){let o=r.getExtension("WEBGL_provoking_vertex").WEBGL_provoking_vertex,s=Oi("provokingVertex",e.provokingVertex,{first:36429,last:36430});o?.provokingVertexWEBGL(s)}if((e.polygonMode||e.polygonOffsetLine)&&t.features.has("polygon-mode-webgl")){if(e.polygonMode){let o=r.getExtension("WEBGL_polygon_mode").WEBGL_polygon_mode,s=Oi("polygonMode",e.polygonMode,{fill:6914,line:6913});o?.polygonModeWEBGL(1028,s),o?.polygonModeWEBGL(1029,s)}e.polygonOffsetLine&&i.enable(10754)}if(t.features.has("shader-clip-cull-distance-webgl")&&(e.clipDistance0&&i.enable(12288),e.clipDistance1&&i.enable(12289),e.clipDistance2&&i.enable(12290),e.clipDistance3&&i.enable(12291),e.clipDistance4&&i.enable(12292),e.clipDistance5&&i.enable(12293),e.clipDistance6&&i.enable(12294),e.clipDistance7&&i.enable(12295)),e.depthWriteEnabled!==void 0&&i.depthMask(tN("depthWriteEnabled",e.depthWriteEnabled)),e.depthCompare&&(e.depthCompare!=="always"?i.enable(2929):i.disable(2929),i.depthFunc(Hl("depthCompare",e.depthCompare))),e.clearDepth!==void 0&&i.clearDepth(e.clearDepth),e.stencilWriteMask){let n=e.stencilWriteMask;i.stencilMaskSeparate(1028,n),i.stencilMaskSeparate(1029,n)}if(e.stencilReadMask&&v.warn("stencilReadMask not supported under WebGL"),e.stencilCompare){let n=e.stencilReadMask||4294967295,o=Hl("depthCompare",e.stencilCompare);e.stencilCompare!=="always"?i.enable(2960):i.disable(2960),i.stencilFuncSeparate(1028,o,0,n),i.stencilFuncSeparate(1029,o,0,n)}if(e.stencilPassOperation&&e.stencilFailOperation&&e.stencilDepthFailOperation){let n=tg("stencilPassOperation",e.stencilPassOperation),o=tg("stencilFailOperation",e.stencilFailOperation),s=tg("stencilDepthFailOperation",e.stencilDepthFailOperation);i.stencilOpSeparate(1028,o,s,n),i.stencilOpSeparate(1029,o,s,n)}switch(e.blend){case!0:i.enable(3042);break;case!1:i.disable(3042);break;default:}if(e.blendColorOperation||e.blendAlphaOperation){let n=W1("blendColorOperation",e.blendColorOperation||"add"),o=W1("blendAlphaOperation",e.blendAlphaOperation||"add");i.blendEquationSeparate(n,o);let s=$l("blendColorSrcFactor",e.blendColorSrcFactor||"one"),a=$l("blendColorDstFactor",e.blendColorDstFactor||"zero"),c=$l("blendAlphaSrcFactor",e.blendAlphaSrcFactor||"one"),l=$l("blendAlphaDstFactor",e.blendAlphaDstFactor||"zero");i.blendFuncSeparate(s,a,c,l)}}function Hl(t,e){return Oi(t,e,{never:512,less:513,equal:514,"less-equal":515,greater:516,"not-equal":517,"greater-equal":518,always:519})}function tg(t,e){return Oi(t,e,{keep:7680,zero:0,replace:7681,invert:5386,"increment-clamp":7682,"decrement-clamp":7683,"increment-wrap":34055,"decrement-wrap":34056})}function W1(t,e){return Oi(t,e,{add:32774,subtract:32778,"reverse-subtract":32779,min:32775,max:32776})}function $l(t,e,r="color"){return Oi(t,e,{one:1,zero:0,src:768,"one-minus-src":769,dst:774,"one-minus-dst":775,"src-alpha":770,"one-minus-src-alpha":771,"dst-alpha":772,"one-minus-dst-alpha":773,"src-alpha-saturated":776,constant:r==="color"?32769:32771,"one-minus-constant":r==="color"?32770:32772,src1:768,"one-minus-src1":769,"src1-alpha":770,"one-minus-src1-alpha":771})}function eN(t,e){return`Illegal parameter ${e} for ${t}`}function Oi(t,e,r){if(!(e in r))throw new Error(eN(t,e));return r[e]}function tN(t,e){return e}function rN(t){let e=!0;for(let r in t){e=!1;break}return e}var rg=P(()=>{z();Nn()});function Yl(t){let e={};return t.addressModeU&&(e[10242]=ig(t.addressModeU)),t.addressModeV&&(e[10243]=ig(t.addressModeV)),t.addressModeW&&(e[32882]=ig(t.addressModeW)),t.magFilter&&(e[10240]=ng(t.magFilter)),(t.minFilter||t.mipmapFilter)&&(e[10241]=iN(t.minFilter||"linear",t.mipmapFilter)),t.lodMinClamp!==void 0&&(e[33082]=t.lodMinClamp),t.lodMaxClamp!==void 0&&(e[33083]=t.lodMaxClamp),t.type==="comparison-sampler"&&(e[34892]=34894),t.compare&&(e[34893]=Hl("compare",t.compare)),t.maxAnisotropy&&(e[34046]=t.maxAnisotropy),e}function ig(t){switch(t){case"clamp-to-edge":return 33071;case"repeat":return 10497;case"mirror-repeat":return 33648}}function ng(t){switch(t){case"nearest":return 9728;case"linear":return 9729}}function iN(t,e="none"){if(!e)return ng(t);switch(e){case"none":return ng(t);case"nearest":switch(t){case"nearest":return 9984;case"linear":return 9985}break;case"linear":switch(t){case"nearest":return 9986;case"linear":return 9987}}}var og=P(()=>{rg()});var Xl,j1=P(()=>{z();og();Xl=class extends pt{device;handle;parameters;constructor(e,r){super(e,r),this.device=e,this.parameters=Yl(r),this.handle=r.handle||this.device.gl.createSampler(),this._setSamplerParameters(this.parameters)}destroy(){this.handle&&(this.device.gl.deleteSampler(this.handle),this.handle=void 0)}toString(){return`Sampler(${this.id},${JSON.stringify(this.props)})`}_setSamplerParameters(e){for(let[r,i]of Object.entries(e)){let n=Number(r);switch(n){case 33082:case 33083:this.device.gl.samplerParameterf(this.handle,n,i);break;default:this.device.gl.samplerParameteri(this.handle,n,i);break}}}}});function $t(t,e,r){if(nN(e))return r(t);let{nocatch:i=!0}=e,n=Tt.get(t);n.push(),bt(t,e);let o;if(i)o=r(t),n.pop();else try{o=r(t)}finally{n.pop()}return o}function nN(t){for(let e in t)return!1;return!0}var Gl=P(()=>{Nn();Xp()});var Ht,sg=P(()=>{z();Ht=class extends pi{device;gl;handle;texture;constructor(e,r){super(e,{...$.defaultProps,...r}),this.device=e,this.gl=this.device.gl,this.handle=null,this.texture=r.texture}}});function ql(t){return oN[t]}var oN,ag=P(()=>{oN={5124:"sint32",5125:"uint32",5122:"sint16",5123:"uint16",5120:"sint8",5121:"uint8",5126:"float32",5131:"float16",33635:"uint16",32819:"uint16",32820:"uint16",33640:"uint32",35899:"uint32",35902:"uint32",34042:"uint32",36269:"uint32"}});function sN(t,e=0){return e?new t.constructor(t.buffer,t.byteOffset+e,(t.byteLength-e)/t.BYTES_PER_ELEMENT):t}function aN(t,e){if(e%t.BYTES_PER_ELEMENT!==0)throw new Error(`Texture byteOffset ${e} must align to typed array element size ${t.BYTES_PER_ELEMENT}`);return e/t.BYTES_PER_ELEMENT}function cN(t){switch(t){case"1d":break;case"2d":return 3553;case"3d":return 32879;case"cube":return 34067;case"2d-array":return 35866;case"cube-array":break}throw new Error(t)}function Kl(t,e,r){return e==="cube"?34069+r:t}var Yt,Zl=P(()=>{z();Fn();og();Gl();sg();ag();Yt=class extends ${device;gl;handle;sampler=void 0;view;glTarget;glFormat;glType;glInternalFormat;compressed;_textureUnit=0;_framebuffer=null;_framebufferAttachmentKey=null;constructor(e,r){super(e,r,{byteAlignment:1}),this.device=e,this.gl=this.device.gl;let i=Ll(this.props.format);this.glTarget=cN(this.props.dimension),this.glInternalFormat=i.internalFormat,this.glFormat=i.format,this.glType=i.type,this.compressed=i.compressed,this.handle=this.props.handle||this.gl.createTexture(),this.device._setWebGLDebugMetadata(this.handle,this,{spector:this.props}),this.gl.bindTexture(this.glTarget,this.handle);let{dimension:n,width:o,height:s,depth:a,mipLevels:c,glTarget:l,glInternalFormat:f}=this;if(!this.compressed)switch(n){case"2d":case"cube":this.gl.texStorage2D(l,c,f,o,s);break;case"2d-array":case"3d":this.gl.texStorage3D(l,c,f,o,s,a);break;default:throw new Error(n)}this.gl.bindTexture(this.glTarget,null),this._initializeData(r.data),this.props.handle?this.trackReferencedMemory(this.getAllocatedByteLength(),"Texture"):this.trackAllocatedMemory(this.getAllocatedByteLength(),"Texture"),this.setSampler(this.props.sampler),this.view=new Ht(this.device,{...this.props,texture:this}),Object.seal(this)}destroy(){this.handle&&(this._framebuffer?.destroy(),this._framebuffer=null,this._framebufferAttachmentKey=null,this.removeStats(),this.props.handle?this.trackDeallocatedReferencedMemory("Texture"):(this.gl.deleteTexture(this.handle),this.trackDeallocatedMemory("Texture")),this.destroyed=!0)}createView(e){return new Ht(this.device,{...e,texture:this})}setSampler(e={}){super.setSampler(e);let r=Yl(this.sampler.props);this._setSamplerParameters(r)}copyExternalImage(e){let r=this._normalizeCopyExternalImageOptions(e);if(r.sourceX||r.sourceY)throw new Error("WebGL does not support sourceX/sourceY)");let{glFormat:i,glType:n}=this,{image:o,depth:s,mipLevel:a,x:c,y:l,z:f,width:u,height:d}=r,h=Kl(this.glTarget,this.dimension,f),p=r.flipY?{37440:!0}:{};return this.gl.bindTexture(this.glTarget,this.handle),$t(this.gl,p,()=>{switch(this.dimension){case"2d":case"cube":this.gl.texSubImage2D(h,a,c,l,u,d,i,n,o);break;case"2d-array":case"3d":this.gl.texSubImage3D(h,a,c,l,f,u,d,s,i,n,o);break;default:}}),this.gl.bindTexture(this.glTarget,null),{width:r.width,height:r.height}}copyImageData(e){super.copyImageData(e)}readBuffer(e={},r){if(!r)throw new Error(`${this} readBuffer requires a destination buffer`);let i=this._getSupportedColorReadOptions(e),n=e.byteOffset??0,o=this.computeMemoryLayout(i);if(r.byteLength{this.gl.readPixels(i.x,i.y,i.width,i.height,this.glFormat,this.glType,n+a)})}finally{this.gl.bindBuffer(35051,null)}return r}async readDataAsync(e={}){throw new Error(`${this} readDataAsync is deprecated; use readBuffer() with an explicit destination buffer or DynamicTexture.readAsync()`)}writeBuffer(e,r={}){let i=this._normalizeTextureWriteOptions(r),{width:n,height:o,depthOrArrayLayers:s,mipLevel:a,byteOffset:c,x:l,y:f,z:u}=i,{glFormat:d,glType:h,compressed:p}=this,g=Kl(this.glTarget,this.dimension,u);if(p)throw new Error("writeBuffer for compressed textures is not implemented in WebGL");let{bytesPerPixel:m}=this.device.getTextureFormatInfo(this.format),_=m?i.bytesPerRow/m:void 0,T={3317:this.byteAlignment,..._!==void 0?{3314:_}:{},32878:i.rowsPerImage};this.gl.bindTexture(this.glTarget,this.handle),this.gl.bindBuffer(35052,e.handle),$t(this.gl,T,()=>{switch(this.dimension){case"2d":case"cube":this.gl.texSubImage2D(g,a,l,f,n,o,d,h,c);break;case"2d-array":case"3d":this.gl.texSubImage3D(g,a,l,f,u,n,o,s,d,h,c);break;default:}}),this.gl.bindBuffer(35052,null),this.gl.bindTexture(this.glTarget,null)}writeData(e,r={}){let i=this._normalizeTextureWriteOptions(r),n=ArrayBuffer.isView(e)?e:new Uint8Array(e),{width:o,height:s,depthOrArrayLayers:a,mipLevel:c,x:l,y:f,z:u,byteOffset:d}=i,{glFormat:h,glType:p,compressed:g}=this,m=Kl(this.glTarget,this.dimension,u),_;if(!g){let{bytesPerPixel:E}=this.device.getTextureFormatInfo(this.format);E&&(_=i.bytesPerRow/E)}let T=this.compressed?{}:{3317:this.byteAlignment,..._!==void 0?{3314:_}:{},32878:i.rowsPerImage},y=aN(n,d),x=g?sN(n,d):n,w=this._getMipLevelSize(c),b=l===0&&f===0&&u===0&&o===w.width&&s===w.height&&a===w.depthOrArrayLayers;this.gl.bindTexture(this.glTarget,this.handle),this.gl.bindBuffer(35052,null),$t(this.gl,T,()=>{switch(this.dimension){case"2d":case"cube":g?b?this.gl.compressedTexImage2D(m,c,h,o,s,0,x):this.gl.compressedTexSubImage2D(m,c,l,f,o,s,h,x):this.gl.texSubImage2D(m,c,l,f,o,s,h,p,n,y);break;case"2d-array":case"3d":g?b?this.gl.compressedTexImage3D(m,c,h,o,s,a,0,x):this.gl.compressedTexSubImage3D(m,c,l,f,u,o,s,a,h,x):this.gl.texSubImage3D(m,c,l,f,u,o,s,a,h,p,n,y);break;default:}}),this.gl.bindTexture(this.glTarget,null)}_getRowByteAlignment(e,r){return 1}_getFramebuffer(){return this._framebuffer||=this.device.createFramebuffer({id:`framebuffer-for-${this.id}`,width:this.width,height:this.height,colorAttachments:[this]}),this._framebuffer}readDataSyncWebGL(e={}){let r=this._getSupportedColorReadOptions(e),i=this.computeMemoryLayout(r),n=ql(this.glType),o=Go(n),s=new o(i.byteLength/o.BYTES_PER_ELEMENT);return this._readColorTextureLayers(r,i,a=>{let c=new o(s.buffer,s.byteOffset+a,i.bytesPerImage/o.BYTES_PER_ELEMENT);this.gl.readPixels(r.x,r.y,r.width,r.height,this.glFormat,this.glType,c)}),s.buffer}_readColorTextureLayers(e,r,i){let n=this._getFramebuffer(),o=r.bytesPerRow/r.bytesPerPixel,s={3333:this.byteAlignment,...o!==e.width?{3330:o}:{}},a=this.gl.getParameter(3074),c=this.gl.bindFramebuffer(36160,n.handle);try{this.gl.readBuffer(36064),$t(this.gl,s,()=>{for(let l=0;l{});function Y1(t){switch(t){case"point-list":return 0;case"line-list":return 1;case"line-strip":return 3;case"triangle-list":return 4;case"triangle-strip":return 5;default:throw new Error(t)}}function X1(t){switch(t){case"point-list":return 0;case"line-list":return 1;case"line-strip":return 1;case"triangle-list":return 4;case"triangle-strip":return 4;default:throw new Error(t)}}var cg=P(()=>{});function lN(t,e){let r={...t,attributes:t.attributes.map(i=>({...i})),bindings:t.bindings.map(i=>({...i}))};for(let i of e?.attributes||[]){let n=r.attributes.find(o=>o.name===i.name);n?(n.type=i.type||n.type,n.stepMode=i.stepMode||n.stepMode):v.warn(`shader layout attribute ${i.name} not present in shader`)}for(let i of e?.bindings||[]){let n=q1(r,i.name);if(!n){v.warn(`shader layout binding ${i.name} not present in shader`);continue}Object.assign(n,i)}return r}function q1(t,e){return t.bindings.find(r=>r.name===e||r.name===`${e}Uniforms`||`${r.name}Uniforms`===e)}function G1(t,e){return t[e]||t[`${e}Uniforms`]||t[e.replace(/Uniforms$/,"")]}var Ql,K1=P(()=>{z();rg();H1();Wl();kl();Zl();sg();cg();Ql=class extends st{device;handle;vs;fs;introspectedLayout;bindings={};uniforms={};varyings=null;_uniformCount=0;_uniformSetters={};get[Symbol.toStringTag](){return"WEBGLRenderPipeline"}constructor(e,r){super(e,r),this.device=e;let i=this.sharedRenderPipeline||this.device._createSharedRenderPipelineWebGL(r);this.sharedRenderPipeline=i,this.handle=i.handle,this.vs=i.vs,this.fs=i.fs,this.linkStatus=i.linkStatus,this.introspectedLayout=i.introspectedLayout,this.device._setWebGLDebugMetadata(this.handle,this,{spector:{id:this.props.id}}),this.shaderLayout=r.shaderLayout?lN(this.introspectedLayout,r.shaderLayout):this.introspectedLayout}destroy(){this.destroyed||(this.sharedRenderPipeline&&!this.props._sharedRenderPipeline&&this.sharedRenderPipeline.destroy(),this.destroyResource())}setBindings(e,r){let i=Uc(zo(this.shaderLayout,e));for(let[n,o]of Object.entries(i)){let s=q1(this.shaderLayout,n);if(s){switch(o||v.warn(`Unsetting binding "${n}" in render pipeline "${this.id}"`)(),s.type){case"uniform":if(!(o instanceof St)&&!(o.buffer instanceof St))throw new Error("buffer value");break;case"texture":if(!(o instanceof Ht||o instanceof Yt||o instanceof jt))throw new Error(`${this} Bad texture binding for ${n}`);break;case"sampler":v.warn(`Ignoring sampler ${n}`)();break;default:throw new Error(s.type)}this.bindings[n]=o}else{let a=this.shaderLayout.bindings.map(c=>`"${c.name}"`).join(", ");r?.disableWarnings||v.warn(`No binding "${n}" in render pipeline "${this.id}", expected one of ${a}`,o)()}}}draw(e){this._syncLinkStatus();let r=e.bindGroups?Uc(e.bindGroups):e.bindings||this.bindings,{renderPass:i,parameters:n=this.props.parameters,topology:o=this.props.topology,vertexArray:s,vertexCount:a,instanceCount:c,isInstanced:l=!1,firstVertex:f=0,transformFeedback:u,uniforms:d=this.uniforms}=e,h=Y1(o),p=!!s.indexBuffer,g=s.indexBuffer?.glIndexType;if(this.linkStatus!=="success")return v.info(2,`RenderPipeline:${this.id}.draw() aborted - waiting for shader linking`)(),!1;if(!this._areTexturesRenderable(r))return v.info(2,`RenderPipeline:${this.id}.draw() aborted - textures not yet loaded`)(),!1;this.device.gl.useProgram(this.handle),s.bindBeforeRender(i),u&&u.begin(this.props.topology),this._applyBindings(r,{disableWarnings:this.props.disableWarnings}),this._applyUniforms(d);let m=i;return V1(this.device,n,m.glParameters,()=>{p&&l?this.device.gl.drawElementsInstanced(h,a||0,g,f,c||0):p?this.device.gl.drawElements(h,a||0,g,f):l?this.device.gl.drawArraysInstanced(h,f,a||0,c||0):this.device.gl.drawArrays(h,f,a||0),u&&u.end()}),s.unbindAfterRender(i),!0}_areTexturesRenderable(e){let r=!0;for(let i of this.shaderLayout.bindings)G1(e,i.name)||(v.warn(`Binding ${i.name} not found in ${this.id}`)(),r=!1);return r}_applyBindings(e,r){if(this._syncLinkStatus(),this.linkStatus!=="success")return;let{gl:i}=this.device;i.useProgram(this.handle);let n=0,o=0;for(let s of this.shaderLayout.bindings){let a=G1(e,s.name);if(!a)throw new Error(`No value for binding ${s.name} in ${this.id}`);switch(s.type){case"uniform":let{name:c}=s,l=i.getUniformBlockIndex(this.handle,c);if(l===4294967295)throw new Error(`Invalid uniform block name ${c}`);if(i.uniformBlockBinding(this.handle,l,o),a instanceof St)i.bindBufferBase(35345,o,a.handle);else{let u=a;i.bindBufferRange(35345,o,u.buffer.handle,u.offset||0,u.size||u.buffer.byteLength-(u.offset||0))}o+=1;break;case"texture":if(!(a instanceof Ht||a instanceof Yt||a instanceof jt))throw new Error("texture");let f;if(a instanceof Ht)f=a.texture;else if(a instanceof Yt)f=a;else if(a instanceof jt&&a.colorAttachments[0]instanceof Ht)v.warn("Passing framebuffer in texture binding may be deprecated. Use fbo.colorAttachments[0] instead")(),f=a.colorAttachments[0].texture;else throw new Error("No texture");i.activeTexture(33984+n),i.bindTexture(f.glTarget,f.handle),n+=1;break;case"sampler":break;case"storage":case"read-only-storage":throw new Error(`binding type '${s.type}' not supported in WebGL`)}}}_applyUniforms(e){for(let r of this.shaderLayout.uniforms||[]){let{name:i,location:n,type:o,textureUnit:s}=r,a=e[i]??s;a!==void 0&&$1(this.device.gl,n,o,a)}}_syncLinkStatus(){this.linkStatus=this.sharedRenderPipeline.linkStatus}}});function Z1(t){return uN[t]}function Jl(t){return fN[t]}function ef(t){return!!J1[t]}function Q1(t){return J1[t]}var fN,J1,uN,tf=P(()=>{fN={5126:"f32",35664:"vec2",35665:"vec3",35666:"vec4",5124:"i32",35667:"vec2",35668:"vec3",35669:"vec4",5125:"u32",36294:"vec2",36295:"vec3",36296:"vec4",35670:"f32",35671:"vec2",35672:"vec3",35673:"vec4",35674:"mat2x2",35685:"mat2x3",35686:"mat2x4",35687:"mat3x2",35675:"mat3x3",35688:"mat3x4",35689:"mat4x2",35690:"mat4x3",35676:"mat4x4"},J1={35678:{viewDimension:"2d",sampleType:"float"},35680:{viewDimension:"cube",sampleType:"float"},35679:{viewDimension:"3d",sampleType:"float"},35682:{viewDimension:"3d",sampleType:"depth"},36289:{viewDimension:"2d-array",sampleType:"float"},36292:{viewDimension:"2d-array",sampleType:"depth"},36293:{viewDimension:"cube",sampleType:"float"},36298:{viewDimension:"2d",sampleType:"sint"},36299:{viewDimension:"3d",sampleType:"sint"},36300:{viewDimension:"cube",sampleType:"sint"},36303:{viewDimension:"2d-array",sampleType:"uint"},36306:{viewDimension:"2d",sampleType:"uint"},36307:{viewDimension:"3d",sampleType:"uint"},36308:{viewDimension:"cube",sampleType:"uint"},36311:{viewDimension:"2d-array",sampleType:"uint"}},uN={uint8:5121,sint8:5120,unorm8:5121,snorm8:5120,uint16:5123,sint16:5122,unorm16:5123,snorm16:5122,uint32:5125,sint32:5124,float16:5131,float32:5126}});function eT(t,e){let r={attributes:[],bindings:[]};r.attributes=dN(t,e);let i=gN(t,e);for(let a of i){let c=a.uniforms.map(l=>({name:l.name,format:l.format,byteOffset:l.byteOffset,byteStride:l.byteStride,arrayLength:l.arrayLength}));r.bindings.push({type:"uniform",name:a.name,group:0,location:a.location,visibility:(a.vertex?1:0)&(a.fragment?2:0),minBindingSize:a.byteLength,uniforms:c})}let n=pN(t,e),o=0;for(let a of n)if(ef(a.type)){let{viewDimension:c,sampleType:l}=Q1(a.type);r.bindings.push({type:"texture",name:a.name,group:0,location:o,viewDimension:c,sampleType:l}),a.textureUnit=o,o+=1}n.length&&(r.uniforms=n);let s=hN(t,e);return s?.length&&(r.varyings=s),r}function dN(t,e){let r=[],i=t.getProgramParameter(e,35721);for(let n=0;n=0){let l=Jl(a),f=/instance/i.test(s)?"instance":"vertex";r.push({name:s,location:c,stepMode:f,type:l})}}return r.sort((n,o)=>n.location-o.location),r}function hN(t,e){let r=[],i=t.getProgramParameter(e,35971);for(let n=0;nn.location-o.location),r}function pN(t,e){let r=[],i=t.getProgramParameter(e,35718);for(let n=0;n1)for(let h=0;ht.getActiveUniformBlockParameter(e,o,s),i=[],n=t.getProgramParameter(e,35382);for(let o=0;op.name.split(".")[0]).filter(p=>!!p)),h=s.name.replace(/Uniforms$/,"");if(d.size===1&&!d.has(s.name)&&!d.has(h)){let[p]=d;v.warn(`Uniform block "${s.name}" uses GLSL instance "${p}". luma.gl binds uniform buffers by block name ("${s.name}") and alias ("${h}"). Prefer matching the instance name to one of those to avoid confusing silent mismatches.`)()}i.push(s)}return i.sort((o,s)=>o.location-s.location),i}function mN(t){if(t[t.length-1]!=="]")return{name:t,length:1,isArray:!1};let r=/([^[]*)(\[[0-9]+\])?/.exec(t);return{name:hi(r?.[1],`Failed to parse GLSL uniform name ${t}`),length:r?.[2]?1:0,isArray:!!r?.[2]}}var tT=P(()=>{z();tf()});var rT,rf,iT=P(()=>{z();tT();tf();rT=4,rf=class extends Fo{device;handle;vs;fs;introspectedLayout={attributes:[],bindings:[],uniforms:[]};linkStatus="pending";constructor(e,r){super(e,r),this.device=e,this.handle=r.handle||this.device.gl.createProgram(),this.vs=r.vs,this.fs=r.fs,r.varyings&&r.varyings.length>0&&this.device.gl.transformFeedbackVaryings(this.handle,r.varyings,r.bufferMode||35981),this._linkShaders(),v.time(3,`RenderPipeline ${this.id} - shaderLayout introspection`)(),this.introspectedLayout=eT(this.device.gl,this.handle),v.timeEnd(3,`RenderPipeline ${this.id} - shaderLayout introspection`)()}destroy(){this.destroyed||(this.device.gl.useProgram(null),this.device.gl.deleteProgram(this.handle),this.handle.destroyed=!0,this.destroyResource())}async _linkShaders(){let{gl:e}=this.device;if(e.attachShader(this.handle,this.vs.handle),e.attachShader(this.handle,this.fs.handle),v.time(rT,`linkProgram for ${this.id}`)(),e.linkProgram(this.handle),v.timeEnd(rT,`linkProgram for ${this.id}`)(),!this.device.features.has("compilation-status-async-webgl")){let i=this._getLinkStatus();this._reportLinkStatus(i);return}v.once(1,"RenderPipeline linking is asynchronous")(),await this._waitForLinkComplete(),v.info(2,`RenderPipeline ${this.id} - async linking complete: ${this.linkStatus}`)();let r=this._getLinkStatus();this._reportLinkStatus(r)}async _reportLinkStatus(e){switch(e){case"success":return;default:let r=e==="link-error"?"Link error":"Validation error";switch(this.vs.compilationStatus){case"error":throw this.vs.debugShader(),new Error(`${this} ${r} during compilation of ${this.vs}`);case"pending":await this.vs.asyncCompilationStatus,this.vs.debugShader();break;case"success":break}switch(this.fs?.compilationStatus){case"error":throw this.fs.debugShader(),new Error(`${this} ${r} during compilation of ${this.fs}`);case"pending":await this.fs.asyncCompilationStatus,this.fs.debugShader();break;case"success":break}let i=this.device.gl.getProgramInfoLog(this.handle);this.device.reportError(new Error(`${r} during ${e}: ${i}`),this)(),this.device.debug()}}_getLinkStatus(){let{gl:e}=this.device;return e.getProgramParameter(this.handle,35714)?(this._initializeSamplerUniforms(),e.validateProgram(this.handle),e.getProgramParameter(this.handle,35715)?(this.linkStatus="success","success"):(this.linkStatus="error","validation-error")):(this.linkStatus="error","link-error")}_initializeSamplerUniforms(){let{gl:e}=this.device;e.useProgram(this.handle);let r=0,i=e.getProgramParameter(this.handle,35718);for(let n=0;n1){let s=Int32Array.from({length:r.size},(a,c)=>n+c);return o.uniform1iv(e,s),n+r.size}return o.uniform1i(e,n),n+1}async _waitForLinkComplete(){let e=async n=>await new Promise(o=>setTimeout(o,n));if(!this.device.features.has("compilation-status-async-webgl")){await e(10);return}let{gl:i}=this.device;for(;;){if(i.getProgramParameter(this.handle,37297))return;await e(10)}}}});function _N(t,e){let r=e.sourceBuffer,i=e.destinationBuffer;t.gl.bindBuffer(36662,r.handle),t.gl.bindBuffer(36663,i.handle),t.gl.copyBufferSubData(36662,36663,e.sourceOffset??0,e.destinationOffset??0,e.size),t.gl.bindBuffer(36662,null),t.gl.bindBuffer(36663,null)}function yN(t,e){throw new Error("copyBufferToTexture is not supported in WebGL")}function xN(t,e){let{sourceTexture:r,mipLevel:i=0,aspect:n="all",width:o=e.sourceTexture.width,height:s=e.sourceTexture.height,depthOrArrayLayers:a,origin:c=[0,0,0],destinationBuffer:l,byteOffset:f=0,bytesPerRow:u,rowsPerImage:d}=e;if(r instanceof $){r.readBuffer({x:c[0]??0,y:c[1]??0,z:c[2]??0,width:o,height:s,depthOrArrayLayers:a,mipLevel:i,aspect:n,byteOffset:f},l);return}if(n!=="all")throw new Error("aspect not supported in WebGL");if(i!==0||a!==void 0||u||d)throw new Error("not implemented");let{framebuffer:h,destroyFramebuffer:p}=nT(r),g;try{let m=l,_=o||h.width,T=s||h.height,y=hi(h.colorAttachments[0]),x=Ll(y.texture.props.format),w=x.format,b=x.type;t.gl.bindBuffer(35051,m.handle),g=t.gl.bindFramebuffer(36160,h.handle),t.gl.readPixels(c[0],c[1],_,T,w,b,f)}finally{t.gl.bindBuffer(35051,null),g!==void 0&&t.gl.bindFramebuffer(36160,g),p&&h.destroy()}}function bN(t,e){let{sourceTexture:r,destinationMipLevel:i=0,origin:n=[0,0],destinationOrigin:o=[0,0,0],destinationTexture:s}=e,{width:a=e.destinationTexture.width,height:c=e.destinationTexture.height}=e,{framebuffer:l,destroyFramebuffer:f}=nT(r),[u=0,d=0]=n,[h,p,g]=o,m=t.gl.bindFramebuffer(36160,l.handle),_,T;if(s instanceof Yt)_=s,a=Number.isFinite(a)?a:_.width,c=Number.isFinite(c)?c:_.height,_._bind(0),T=_.glTarget;else throw new Error("invalid destination");switch(T){case 3553:case 34067:t.gl.copyTexSubImage2D(T,i,h,p,u,d,a,c);break;case 35866:case 32879:t.gl.copyTexSubImage3D(T,i,h,p,g,u,d,a,c);break;default:}_&&_._unbind(),t.gl.bindFramebuffer(36160,m),f&&l.destroy()}function nT(t){if(t instanceof $){let{width:e,height:r,id:i}=t;return{framebuffer:t.device.createFramebuffer({id:`framebuffer-for-${i}`,width:e,height:r,colorAttachments:[t]}),destroyFramebuffer:!0}}return{framebuffer:t,destroyFramebuffer:!1}}var nf,oT=P(()=>{z();Fn();Zl();nf=class extends jo{device;handle=null;commands=[];constructor(e,r={}){super(e,r),this.device=e}_executeCommands(e=this.commands){for(let r of e)switch(r.name){case"copy-buffer-to-buffer":_N(this.device,r.options);break;case"copy-buffer-to-texture":yN(this.device,r.options);break;case"copy-texture-to-buffer":xN(this.device,r.options);break;case"copy-texture-to-texture":bN(this.device,r.options);break;default:throw new Error(r.name)}}}});var TN,of,sT=P(()=>{z();Gl();Nn();TN=[1,2,4,8],of=class extends Wo{device;handle=null;glParameters={};constructor(e,r){super(e,r),this.device=e;let i=this.props.framebuffer,n=!i||i.handle===null;n&&e.getDefaultCanvasContext()._resizeDrawingBufferIfNeeded();let o;if(!r?.parameters?.viewport)if(!n&&i){let{width:s,height:a}=i;o=[0,0,s,a]}else{let[s,a]=e.getDefaultCanvasContext().getDrawingBufferSize();o=[0,0,s,a]}if(this.device.pushState(),this.setParameters({viewport:o,...this.props.parameters}),!n&&i?.colorAttachments.length){let s=i.colorAttachments.map((a,c)=>36064+c);this.device.gl.drawBuffers(s)}else n&&this.device.gl.drawBuffers([1029]);this.clear(),this.props.timestampQuerySet&&this.props.beginTimestampIndex!==void 0&&this.props.timestampQuerySet.writeTimestamp(this.props.beginTimestampIndex)}end(){this.destroyed||(this.props.timestampQuerySet&&this.props.endTimestampIndex!==void 0&&this.props.timestampQuerySet.writeTimestamp(this.props.endTimestampIndex),this.device.popState(),this.destroy())}pushDebugGroup(e){}popDebugGroup(){}insertDebugMarker(e){}setParameters(e={}){let r={...this.glParameters};r.framebuffer=this.props.framebuffer||null,this.props.depthReadOnly&&(r.depthMask=!this.props.depthReadOnly),r.stencilMask=this.props.stencilReadOnly?0:1,r[35977]=this.props.discard,e.viewport&&(e.viewport.length>=6?(r.viewport=e.viewport.slice(0,4),r.depthRange=[e.viewport[4],e.viewport[5]]):r.viewport=e.viewport),e.scissorRect&&(r.scissorTest=!0,r.scissor=e.scissorRect),e.blendConstant&&(r.blendColor=e.blendConstant),e.stencilReference!==void 0&&(r[2967]=e.stencilReference,r[36003]=e.stencilReference),"colorMask"in e&&(r.colorMask=TN.map(i=>!!(i&e.colorMask))),this.glParameters=r,bt(this.device.gl,r)}beginOcclusionQuery(e){this.props.occlusionQuerySet?.beginOcclusionQuery()}endOcclusionQuery(){this.props.occlusionQuerySet?.endOcclusionQuery()}clear(){let e={...this.glParameters},r=0;this.props.clearColors&&this.props.clearColors.forEach((i,n)=>{i&&this.clearColorBuffer(n,i)}),this.props.clearColor!==!1&&this.props.clearColors===void 0&&(r|=16384,e.clearColor=this.props.clearColor),this.props.clearDepth!==!1&&(r|=256,e.clearDepth=this.props.clearDepth),this.props.clearStencil!==!1&&(r|=1024,e.clearStencil=this.props.clearStencil),r!==0&&$t(this.device.gl,e,()=>{this.device.gl.clear(r)})}clearColorBuffer(e=0,r=[0,0,0,0]){$t(this.device.gl,{framebuffer:this.props.framebuffer},()=>{switch(r.constructor){case Int8Array:case Int16Array:case Int32Array:this.device.gl.clearBufferiv(6144,e,r);break;case Uint8Array:case Uint8ClampedArray:case Uint16Array:case Uint32Array:this.device.gl.clearBufferuiv(6144,e,r);break;case Float32Array:this.device.gl.clearBufferfv(6144,e,r);break;default:throw new Error("clearColorBuffer: color must be typed array")}})}}});var Us,aT=P(()=>{z();oT();sT();Us=class extends Vo{device;handle=null;commandBuffer;constructor(e,r){super(e,r),this.device=e,this.commandBuffer=new nf(e,{id:`${this.props.id}-command-buffer`})}destroy(){this.destroyResource()}finish(e){return e?.id&&this.commandBuffer.id!==e.id&&(this.commandBuffer.id=e.id,this.commandBuffer.props.id=e.id),this.destroy(),this.commandBuffer}beginRenderPass(e={}){return new of(this.device,this._applyTimeProfilingToPassProps(e))}beginComputePass(e={}){throw new Error("ComputePass not supported in WebGL")}copyBufferToBuffer(e){this.commandBuffer.commands.push({name:"copy-buffer-to-buffer",options:e})}copyBufferToTexture(e){this.commandBuffer.commands.push({name:"copy-buffer-to-texture",options:e})}copyTextureToBuffer(e){this.commandBuffer.commands.push({name:"copy-texture-to-buffer",options:e})}copyTextureToTexture(e){this.commandBuffer.commands.push({name:"copy-texture-to-texture",options:e})}pushDebugGroup(e){}popDebugGroup(){}insertDebugMarker(e){}resolveQuerySet(e,r,i){throw new Error("resolveQuerySet is not supported in WebGL")}writeTimestamp(e,r){e.writeTimestamp(r)}}});function cT(t){let{target:e,source:r,start:i=0,count:n=1}=t,o=r.length,s=n*o,a=0;for(let c=i;a{});function wN(t){return Array.isArray(t)?new Float32Array(t):t}function SN(t,e){if(!t||!e||t.length!==e.length||t.constructor!==e.constructor)return!1;for(let r=0;r{z();Rr();Gp();lT();sf=class t extends $o{get[Symbol.toStringTag](){return"VertexArray"}device;handle;buffer=null;bufferValue=null;static isConstantAttributeZeroSupported(e){return Du()==="Chrome"}constructor(e,r){super(e,r),this.device=e,this.handle=this.device.gl.createVertexArray()}destroy(){super.destroy(),this.buffer&&this.buffer?.destroy(),this.handle&&(this.device.gl.deleteVertexArray(this.handle),this.handle=void 0)}setIndexBuffer(e){let r=e;if(r&&r.glTarget!==34963)throw new Error("Use .setBuffer()");this.device.gl.bindVertexArray(this.handle),this.device.gl.bindBuffer(34963,r?r.handle:null),this.indexBuffer=r,this.device.gl.bindVertexArray(null)}setBuffer(e,r){let i=r;if(i.glTarget===34963)throw new Error("Use .setIndexBuffer()");let{size:n,type:o,stride:s,offset:a,normalized:c,integer:l,divisor:f}=this._getAccessor(e);this.device.gl.bindVertexArray(this.handle),this.device.gl.bindBuffer(34962,i.handle),l?this.device.gl.vertexAttribIPointer(e,n,o,s,a):this.device.gl.vertexAttribPointer(e,n,o,c,s,a),this.device.gl.bindBuffer(34962,null),this.device.gl.enableVertexAttribArray(e),this.device.gl.vertexAttribDivisor(e,f||0),this.attributes[e]=i,this.device.gl.bindVertexArray(null)}setConstantWebGL(e,r){this._enable(e,!1),this.attributes[e]=r}bindBeforeRender(){this.device.gl.bindVertexArray(this.handle),this._applyConstantAttributes()}unbindAfterRender(){this.device.gl.bindVertexArray(null)}_applyConstantAttributes(){for(let e=0;e{z();cf();cg();af=class extends Ho{device;gl;handle;layout;buffers={};unusedBuffers={};bindOnUse=!0;_bound=!1;constructor(e,r){super(e,r),this.device=e,this.gl=e.gl,this.handle=this.props.handle||this.gl.createTransformFeedback(),this.layout=this.props.layout,r.buffers&&this.setBuffers(r.buffers),Object.seal(this)}destroy(){this.gl.deleteTransformFeedback(this.handle),super.destroy()}begin(e="point-list"){this.gl.bindTransformFeedback(36386,this.handle),this.bindOnUse&&this._bindBuffers(),this.gl.beginTransformFeedback(X1(e))}end(){this.gl.endTransformFeedback(),this.bindOnUse&&this._unbindBuffers(),this.gl.bindTransformFeedback(36386,null)}setBuffers(e){this.buffers={},this.unusedBuffers={},this.bind(()=>{for(let[r,i]of Object.entries(e))this.setBuffer(r,i)})}setBuffer(e,r){let i=this._getVaryingIndex(e),{buffer:n,byteLength:o,byteOffset:s}=this._getBufferRange(r);if(i<0){this.unusedBuffers[e]=n,v.warn(`${this.id} unusedBuffers varying buffer ${e}`)();return}this.buffers[i]={buffer:n,byteLength:o,byteOffset:s},this.bindOnUse||this._bindBuffer(i,n,s,o)}getBuffer(e){if(uT(e))return this.buffers[e]||null;let r=this._getVaryingIndex(e);return this.buffers[r]??null}bind(e=this.handle){if(typeof e!="function")return this.gl.bindTransformFeedback(36386,e),this;let r;return this._bound?r=e():(this.gl.bindTransformFeedback(36386,this.handle),this._bound=!0,r=e(),this._bound=!1,this.gl.bindTransformFeedback(36386,null)),r}unbind(){this.bind(null)}_getBufferRange(e){if(e instanceof St)return{buffer:e,byteOffset:0,byteLength:e.byteLength};let{buffer:r,byteOffset:i=0,byteLength:n=e.buffer.byteLength}=e;return{buffer:r,byteOffset:i,byteLength:n}}_getVaryingIndex(e){if(uT(e))return Number(e);for(let r of this.layout.varyings||[])if(e===r.name)return r.location;return-1}_bindBuffers(){for(let[e,r]of Object.entries(this.buffers)){let{buffer:i,byteLength:n,byteOffset:o}=this._getBufferRange(r);this._bindBuffer(Number(e),i,o,n)}}_unbindBuffers(){for(let e in this.buffers)this.gl.bindBufferBase(35982,Number(e),null)}_bindBuffer(e,r,i=0,n){let o=r&&r.handle;!o||n===void 0?this.gl.bindBufferBase(35982,e,o):this.gl.bindBufferRange(35982,e,o,i,n)}}});var lf,hT=P(()=>{z();lf=class extends Yo{device;handle;_timestampPairs=[];_pendingReads=new Set;_occlusionQuery=null;_occlusionActive=!1;get[Symbol.toStringTag](){return"QuerySet"}constructor(e,r){if(super(e,r),this.device=e,r.type==="timestamp"){if(r.count<2)throw new Error("Timestamp QuerySet requires at least two query slots");this._timestampPairs=new Array(Math.ceil(r.count/2)).fill(null).map(()=>({activeQuery:null,completedQueries:[]})),this.handle=null}else{if(r.count>1)throw new Error("WebGL occlusion QuerySet can only have one value");let i=this.device.gl.createQuery();if(!i)throw new Error("WebGL query not supported");this.handle=i}Object.seal(this)}destroy(){if(!this.destroyed){this.handle&&this.device.gl.deleteQuery(this.handle);for(let e of this._timestampPairs){e.activeQuery&&(this._cancelPendingQuery(e.activeQuery),this.device.gl.deleteQuery(e.activeQuery.handle));for(let r of e.completedQueries)this._cancelPendingQuery(r),this.device.gl.deleteQuery(r.handle)}this._occlusionQuery&&(this._cancelPendingQuery(this._occlusionQuery),this.device.gl.deleteQuery(this._occlusionQuery.handle));for(let e of Array.from(this._pendingReads))this._cancelPendingQuery(e);this.destroyResource()}}isResultAvailable(e){return this.props.type==="timestamp"?e===void 0?this._timestampPairs.some((r,i)=>this._isTimestampPairAvailable(i)):this._isTimestampPairAvailable(this._getTimestampPairIndex(e)):this._occlusionQuery?this._pollQueryAvailability(this._occlusionQuery):!1}async readResults(e){let r=e?.firstQuery||0,i=e?.queryCount||this.props.count-r;if(this._validateRange(r,i),this.props.type==="timestamp"){let n=new Array(i).fill(0n),o=Math.floor(r/2),s=Math.floor((r+i-1)/2);for(let a=o;a<=s;a++){let c=await this._consumeTimestampPairResult(a),l=a*2,f=l+1;l>=r&&l=r&&f=this.props.count||r<=e)throw new Error("Timestamp duration range is out of bounds");if(e%2!==0||r!==e+1)throw new Error("WebGL timestamp durations require adjacent even/odd query indices");let i=await this._consumeTimestampPairResult(this._getTimestampPairIndex(e));return Number(i)/1e6}beginOcclusionQuery(){if(this.props.type!=="occlusion")throw new Error("Occlusion queries require an occlusion QuerySet");if(!this.handle)throw new Error("WebGL occlusion query is not available");if(this._occlusionActive)throw new Error("Occlusion query is already active");this.device.gl.beginQuery(35887,this.handle),this._occlusionQuery={handle:this.handle,promise:null,result:null,disjoint:!1,cancelled:!1,pollRequestId:null,resolve:null,reject:null},this._occlusionActive=!0}endOcclusionQuery(){if(!this._occlusionActive)throw new Error("Occlusion query is not active");this.device.gl.endQuery(35887),this._occlusionActive=!1}writeTimestamp(e){if(this.props.type!=="timestamp")throw new Error("Timestamp writes require a timestamp QuerySet");let r=this._getTimestampPairIndex(e),i=this._timestampPairs[r];if(e%2===0){if(i.activeQuery)throw new Error("Timestamp query pair is already active");let n=this.device.gl.createQuery();if(!n)throw new Error("WebGL query not supported");let o={handle:n,promise:null,result:null,disjoint:!1,cancelled:!1,pollRequestId:null,resolve:null,reject:null};this.device.gl.beginQuery(35007,n),i.activeQuery=o;return}if(!i.activeQuery)throw new Error("Timestamp query pair was ended before it was started");this.device.gl.endQuery(35007),i.completedQueries.push(i.activeQuery),i.activeQuery=null}_validateRange(e,r){if(e<0||r<0||e+r>this.props.count)throw new Error("Query read range is out of bounds")}_getTimestampPairIndex(e){if(e<0||e>=this.props.count)throw new Error("Query index is out of bounds");return Math.floor(e/2)}_isTimestampPairAvailable(e){let r=this._timestampPairs[e];return!r||r.completedQueries.length===0?!1:this._pollQueryAvailability(r.completedQueries[0])}_pollQueryAvailability(e){if(e.cancelled||this.destroyed)return e.result=0n,!0;if(e.result!==null||e.disjoint)return!0;if(!this.device.gl.getQueryParameter(e.handle,34919))return!1;let i=!!this.device.gl.getParameter(36795);return e.disjoint=i,e.result=i?0n:BigInt(this.device.gl.getQueryParameter(e.handle,34918)),!0}async _consumeTimestampPairResult(e){let r=this._timestampPairs[e];if(!r||r.completedQueries.length===0)throw new Error("Timestamp query pair has no completed result");let i=r.completedQueries.shift();try{return await this._consumeQueryResult(i)}finally{this.device.gl.deleteQuery(i.handle)}}_consumeQueryResult(e){return e.promise||(this._pendingReads.add(e),e.promise=new Promise((r,i)=>{e.resolve=r,e.reject=i;let n=()=>{if(e.pollRequestId=null,e.cancelled||this.destroyed){this._pendingReads.delete(e),e.promise=null,e.resolve=null,e.reject=null,r(0n);return}if(!this._pollQueryAvailability(e)){e.pollRequestId=this._requestAnimationFrame(n);return}this._pendingReads.delete(e),e.promise=null,e.resolve=null,e.reject=null,e.disjoint?i(new Error("GPU timestamp query was invalidated by a disjoint event")):r(e.result||0n)};n()})),e.promise}_cancelPendingQuery(e){if(this._pendingReads.delete(e),e.cancelled=!0,e.pollRequestId!==null&&(this._cancelAnimationFrame(e.pollRequestId),e.pollRequestId=null),e.resolve){let r=e.resolve;e.promise=null,e.resolve=null,e.reject=null,r(0n)}}_requestAnimationFrame(e){return requestAnimationFrame(e)}_cancelAnimationFrame(e){cancelAnimationFrame(e)}}});var ff,pT=P(()=>{z();ff=class extends Xo{device;gl;handle;signaled;_signaled=!1;constructor(e,r={}){super(e,{}),this.device=e,this.gl=e.gl;let i=this.props.handle||this.gl.fenceSync(this.gl.SYNC_GPU_COMMANDS_COMPLETE,0);if(!i)throw new Error("Failed to create WebGL fence");this.handle=i,this.signaled=new Promise(n=>{let o=()=>{let s=this.gl.clientWaitSync(this.handle,0,0);s===this.gl.ALREADY_SIGNALED||s===this.gl.CONDITION_SATISFIED?(this._signaled=!0,n()):setTimeout(o,1)};o()})}isSignaled(){if(this._signaled)return!0;let e=this.gl.getSyncParameter(this.handle,this.gl.SYNC_STATUS);return this._signaled=e===this.gl.SIGNALED,this._signaled}destroy(){this.destroyed||this.gl.deleteSync(this.handle)}}});function lg(t){switch(t){case 6406:case 33326:case 6403:case 36244:return 1;case 33339:case 33340:case 33328:case 33320:case 33319:return 2;case 6407:case 36248:case 34837:return 3;case 6408:case 36249:case 34836:return 4;default:return 0}}function gT(t){switch(t){case 5121:return 1;case 33635:case 32819:case 32820:return 2;case 5126:return 4;default:return 0}}var mT=P(()=>{});function _T(t,e){let{sourceX:r=0,sourceY:i=0,sourceAttachment:n=0}=e||{},{target:o=null,sourceWidth:s,sourceHeight:a,sourceDepth:c,sourceFormat:l,sourceType:f}=e||{},{framebuffer:u,deleteFramebuffer:d}=xT(t),{gl:h,handle:p}=u;s||=u.width,a||=u.height;let g=u.colorAttachments[n]?.texture;if(!g)throw new Error(`Invalid framebuffer attachment ${n}`);c=g?.depth||1,l||=g?.glFormat||6408,f||=g?.glType||5121,o=vN(o,f,l,s,a,c);let m=ke.getDataType(o);f=f||Z1(m);let _=h.bindFramebuffer(36160,p);return h.readBuffer(36064+n),h.readPixels(r,i,s,a,l,f,o),h.readBuffer(36064),h.bindFramebuffer(36160,_||null),d&&u.destroy(),o}function yT(t,e){let{target:r,sourceX:i=0,sourceY:n=0,sourceFormat:o=6408,targetByteOffset:s=0}=e||{},{sourceWidth:a,sourceHeight:c,sourceType:l}=e||{},{framebuffer:f,deleteFramebuffer:u}=xT(t);a=a||f.width,c=c||f.height;let d=f;l=l||5121;let h=r;if(!h){let g=lg(o),m=gT(l),_=s+a*c*g*m;h=d.device.createBuffer({byteLength:_})}let p=t.device.createCommandEncoder();return p.copyTextureToBuffer({sourceTexture:t,width:a,height:c,origin:[i,n],destinationBuffer:h,byteOffset:s}),p.destroy(),u&&f.destroy(),h}function xT(t){return t instanceof mi?{framebuffer:t,deleteFramebuffer:!1}:{framebuffer:AN(t),deleteFramebuffer:!0}}function AN(t,e){let{device:r,width:i,height:n,id:o}=t;return r.createFramebuffer({...e,id:`framebuffer-for-${o}`,width:i,height:n,colorAttachments:[t]})}function vN(t,e,r,i,n,o){if(t)return t;e||=5121;let s=ql(e),a=ke.getTypedArrayConstructor(s),c=lg(r);return new a(i*n*c)}var bT=P(()=>{z();tf();mT();ag()});var fg={};Zi(fg,{WebGLDevice:()=>jr});function EN(t,e,r){switch(r.length){case 1:t.gl.vertexAttrib1fv(e,r);break;case 2:t.gl.vertexAttrib2fv(e,r);break;case 3:t.gl.vertexAttrib3fv(e,r);break;case 4:t.gl.vertexAttrib4fv(e,r);break;default:}}function RN(t,e,r){t.gl.vertexAttribI4iv(e,r)}function CN(t,e,r){t.gl.vertexAttribI4uiv(e,r)}function PN(t,e){if(!t||!e||t.length!==e.length||t.constructor!==e.constructor)return!1;for(let r=0;r{z();Xp();T1();Cl();A1();O1();N1();D1();L1();Wp();Vp();Fn();B1();Wl();z1();j1();Zl();kl();K1();iT();aT();fT();dT();hT();pT();bT();Nn();Gl();Fs();jr=class t extends ht{static getDeviceFromContext(e){return e?e.luma?.device??null:null}type="webgl";handle;features;limits;info;canvasContext;preferredColorFormat="rgba8unorm";preferredDepthFormat="depth24plus";commandEncoder;lost;_resolveContextLost;gl;_constants;extensions;_polyfilled=!1;spectorJS;get[Symbol.toStringTag](){return"WebGLDevice"}toString(){return`${this[Symbol.toStringTag]}(${this.id})`}isVertexFormatSupported(e){return e!=="unorm8x4-bgra"}constructor(e){super({...e,id:e.id||F1("webgl-device")});let r=ht._getCanvasContextProps(e);if(!r)throw new Error("WebGLDevice requires props.createCanvasContext to be set");let i=r.canvas?.gl??null,n=t.getDeviceFromContext(i);if(n)throw new Error(`WebGL context already attached to device ${n.id}`);this.canvasContext=new Ul(this,r),this.lost=new Promise(f=>{this._resolveContextLost=f});let o={...e.webgl};r.alphaMode==="premultiplied"&&(o.premultipliedAlpha=!0),e.powerPreference!==void 0&&(o.powerPreference=e.powerPreference),e.failIfMajorPerformanceCaveat!==void 0&&(o.failIfMajorPerformanceCaveat=e.failIfMajorPerformanceCaveat);let a=this.props._handle||b1(this.canvasContext.canvas,{onContextLost:f=>this._resolveContextLost?.({reason:"destroyed",message:"Entered sleep mode, or too many apps or browser tabs are using the GPU."}),onContextRestored:f=>console.log("WebGL context restored")},o);if(!a)throw new Error("WebGL context creation failed");if(n=t.getDeviceFromContext(a),n){if(e._reuseDevices)return v.log(1,`Not creating a new Device, instead returning a reference to Device ${n.id} already attached to WebGL context`,n)(),this.canvasContext.destroy(),n._reused=!0,n;throw new Error(`WebGL context already attached to device ${n.id}`)}this.handle=a,this.gl=a,this.spectorJS=o1({...this.props,gl:this.handle});let c=Ii(this.handle);c.device=this,c.extensions||(c.extensions={}),this.extensions=c.extensions,this.info=w1(this.gl,this.extensions),this.limits=new Bl(this.gl),this.features=new Fl(this.gl,this.extensions,this.props._disabledFeatures),this.props._initializeFeatures&&this.features.initializeFeatures(),new Tt(this.gl,{log:(...f)=>v.log(1,...f)()}).trackState(this.gl,{copyState:!1}),(e.debug||e.debugWebGL)&&(this.gl=l1(this.gl,{debugWebGL:!0,traceWebGL:e.debugWebGL}),v.warn("WebGL debug mode activated. Performance reduced.")()),e.debugWebGL&&(v.level=Math.max(v.level,1)),this.commandEncoder=new Us(this,{id:`${this}-command-encoder`}),this.canvasContext._startObservers()}destroy(){if(this.commandEncoder?.destroy(),!this.props._reuseDevices&&!this._reused){let e=Ii(this.handle);e.device=null}}get isLost(){return this.gl.isContextLost()}createCanvasContext(e){throw new Error("WebGL only supports a single canvas")}createPresentationContext(e){return new zl(this,e||{})}createBuffer(e){let r=this._normalizeBufferProps(e);return new St(this,r)}createTexture(e){return new Yt(this,e)}createExternalTexture(e){throw new Error("createExternalTexture() not implemented")}createSampler(e){return new Xl(this,e)}createShader(e){return new jl(this,e)}createFramebuffer(e){return new jt(this,e)}createVertexArray(e){return new sf(this,e)}createTransformFeedback(e){return new af(this,e)}createQuerySet(e){return new lf(this,e)}createFence(){return new ff(this)}createRenderPipeline(e){return new Ql(this,e)}_createSharedRenderPipelineWebGL(e){return new rf(this,e)}createComputePipeline(e){throw new Error("ComputePipeline not supported in WebGL")}createCommandEncoder(e={}){return new Us(this,e)}submit(e){let r=null;e||({submittedCommandEncoder:r,commandBuffer:e}=this._finalizeDefaultCommandEncoderForSubmit());try{e._executeCommands(),r&&r.resolveTimeProfilingQuerySet().then(()=>{this.commandEncoder._gpuTimeMs=r._gpuTimeMs}).catch(()=>{})}finally{e.destroy()}}_finalizeDefaultCommandEncoderForSubmit(){let e=this.commandEncoder,r=e.finish();return this.commandEncoder.destroy(),this.commandEncoder=this.createCommandEncoder({id:e.props.id,timeProfilingQuerySet:e.getTimeProfilingQuerySet()}),{submittedCommandEncoder:e,commandBuffer:r}}readPixelsToArrayWebGL(e,r){return _T(e,r)}readPixelsToBufferWebGL(e,r){return yT(e,r)}setParametersWebGL(e){bt(this.gl,e)}getParametersWebGL(e){return Ml(this.gl,e)}withParametersWebGL(e,r){return $t(this.gl,e,r)}resetWebGL(){v.warn("WebGLDevice.resetWebGL is deprecated, use only for debugging")(),g1(this.gl)}_getDeviceSpecificTextureFormatCapabilities(e){return P1(this.gl,e,this.extensions)}loseDevice(){let e=!1,i=this.getExtension("WEBGL_lose_context").WEBGL_lose_context;return i&&(e=!0,i.loseContext()),this._resolveContextLost?.({reason:"destroyed",message:"Application triggered context loss"}),e}pushState(){Tt.get(this.gl).push()}popState(){Tt.get(this.gl).pop()}getGLKey(e,r){let i=Number(e);for(let n in this.gl)if(this.gl[n]===i)return`GL.${n}`;return r?.emptyIfUnknown?"":String(e)}getGLKeys(e){let r={emptyIfUnknown:!0};return Object.entries(e).reduce((i,[n,o])=>(i[`${n}:${this.getGLKey(n,r)}`]=`${o}:${this.getGLKey(o,r)}`,i),{})}setConstantAttributeWebGL(e,r){let i=this.limits.maxVertexAttributes;this._constants=this._constants||new Array(i).fill(null);let n=this._constants[e];switch(n&&PN(n,r)&&v.info(1,`setConstantAttributeWebGL(${e}) could have been skipped, value unchanged`)(),this._constants[e]=r,r.constructor){case Float32Array:EN(this,e,r);break;case Int32Array:RN(this,e,r);break;case Uint32Array:CN(this,e,r);break;default:throw new Error("constant")}}getExtension(e){return wt(this.gl,e,this.extensions),this.extensions}_setWebGLDebugMetadata(e,r,i){e.luma=r;let n={props:i.spector,id:i.spector.id};e.__SPECTOR_Metadata=n}}});function MN(t){return typeof WebGL2RenderingContext<"u"&&t instanceof WebGL2RenderingContext?!0:!!(t&&typeof t.createVertexArray=="function")}var zs,ug,Ws,TT=P(()=>{z();r1();Wp();Vp();zs=1,ug=class extends No{type="webgl";constructor(){super(),ht.defaultProps={...ht.defaultProps,...Pl}}enforceWebGL2(e){t1(e)}isSupported(){return typeof WebGL2RenderingContext<"u"}isDeviceHandle(e){return typeof WebGL2RenderingContext<"u"&&e instanceof WebGL2RenderingContext?!0:(typeof WebGLRenderingContext<"u"&&e instanceof WebGLRenderingContext&&v.warn("WebGL1 is not supported",e)(),!1)}async attach(e,r={}){let{WebGLDevice:i}=await Promise.resolve().then(()=>(uf(),fg));if(e instanceof i)return e;let n=i.getDeviceFromContext(e);if(n)return n;if(!MN(e))throw new Error("Invalid WebGL2RenderingContext");let o=r.createCanvasContext===!0?{}:r.createCanvasContext;return new i({...r,_handle:e,createCanvasContext:{canvas:e.canvas,autoResize:!1,...o}})}async create(e={}){let{WebGLDevice:r}=await Promise.resolve().then(()=>(uf(),fg)),i=[];(e.debugWebGL||e.debug)&&i.push(c1()),e.debugSpectorJS&&i.push(n1(e));let n=await Promise.allSettled(i);for(let o of n)o.status==="rejected"&&v.error(`Failed to initialize debug libraries ${o.reason}`)();try{let o=new r(e);v.groupCollapsed(zs,`WebGLDevice ${o.id} created`)();let s=`${o._reused?"Reusing":"Created"} device with WebGL2 ${o.props.debug?"debug ":""}context: ${o.info.vendor}, ${o.info.renderer} for canvas: ${o.canvasContext.id}`;return v.probe(zs,s)(),v.table(zs,o.info)(),o}finally{v.groupEnd(zs)(),v.info(zs,"%cWebGL call tracing: luma.log.set('debug-webgl') ","color: white; background: blue; padding: 2px 6px; border-radius: 3px;")()}}};Ws=new ug});var cf=P(()=>{TT();uf();Wl()});var cv=er((av,Dm)=>{(function(t,e,r){function i(a){var c=this,l=s();c.next=function(){var f=2091639*c.s0+c.c*23283064365386963e-26;return c.s0=c.s1,c.s1=c.s2,c.s2=f-(c.c=f|0)},c.c=1,c.s0=l(" "),c.s1=l(" "),c.s2=l(" "),c.s0-=l(a),c.s0<0&&(c.s0+=1),c.s1-=l(a),c.s1<0&&(c.s1+=1),c.s2-=l(a),c.s2<0&&(c.s2+=1),l=null}function n(a,c){return c.c=a.c,c.s0=a.s0,c.s1=a.s1,c.s2=a.s2,c}function o(a,c){var l=new i(a),f=c&&c.state,u=l.next;return u.int32=function(){return l.next()*4294967296|0},u.double=function(){return u()+(u()*2097152|0)*11102230246251565e-32},u.quick=u,f&&(typeof f=="object"&&n(f,l),u.state=function(){return n(l,{})}),u}function s(){var a=4022871197,c=function(l){l=String(l);for(var f=0;f>>0,u-=a,u*=a,a=u>>>0,u-=a,a+=u*4294967296}return(a>>>0)*23283064365386963e-26};return c}e&&e.exports?e.exports=o:r&&r.amd?r(function(){return o}):this.alea=o})(av,typeof Dm=="object"&&Dm,typeof define=="function"&&define)});var fv=er((lv,Lm)=>{(function(t,e,r){function i(s){var a=this,c="";a.x=0,a.y=0,a.z=0,a.w=0,a.next=function(){var f=a.x^a.x<<11;return a.x=a.y,a.y=a.z,a.z=a.w,a.w^=a.w>>>19^f^f>>>8},s===(s|0)?a.x=s:c+=s;for(var l=0;l>>0)/4294967296};return f.double=function(){do var u=c.next()>>>11,d=(c.next()>>>0)/4294967296,h=(u+d)/(1<<21);while(h===0);return h},f.int32=c.next,f.quick=f,l&&(typeof l=="object"&&n(l,c),f.state=function(){return n(c,{})}),f}e&&e.exports?e.exports=o:r&&r.amd?r(function(){return o}):this.xor128=o})(lv,typeof Lm=="object"&&Lm,typeof define=="function"&&define)});var dv=er((uv,Fm)=>{(function(t,e,r){function i(s){var a=this,c="";a.next=function(){var f=a.x^a.x>>>2;return a.x=a.y,a.y=a.z,a.z=a.w,a.w=a.v,(a.d=a.d+362437|0)+(a.v=a.v^a.v<<4^(f^f<<1))|0},a.x=0,a.y=0,a.z=0,a.w=0,a.v=0,s===(s|0)?a.x=s:c+=s;for(var l=0;l>>4),a.next()}function n(s,a){return a.x=s.x,a.y=s.y,a.z=s.z,a.w=s.w,a.v=s.v,a.d=s.d,a}function o(s,a){var c=new i(s),l=a&&a.state,f=function(){return(c.next()>>>0)/4294967296};return f.double=function(){do var u=c.next()>>>11,d=(c.next()>>>0)/4294967296,h=(u+d)/(1<<21);while(h===0);return h},f.int32=c.next,f.quick=f,l&&(typeof l=="object"&&n(l,c),f.state=function(){return n(c,{})}),f}e&&e.exports?e.exports=o:r&&r.amd?r(function(){return o}):this.xorwow=o})(uv,typeof Fm=="object"&&Fm,typeof define=="function"&&define)});var pv=er((hv,Bm)=>{(function(t,e,r){function i(s){var a=this;a.next=function(){var l=a.x,f=a.i,u,d,h;return u=l[f],u^=u>>>7,d=u^u<<24,u=l[f+1&7],d^=u^u>>>10,u=l[f+3&7],d^=u^u>>>3,u=l[f+4&7],d^=u^u<<7,u=l[f+7&7],u=u^u<<13,d^=u^u<<9,l[f]=d,a.i=f+1&7,d};function c(l,f){var u,d,h=[];if(f===(f|0))d=h[0]=f;else for(f=""+f,u=0;u0;--u)l.next()}c(a,s)}function n(s,a){return a.x=s.x.slice(),a.i=s.i,a}function o(s,a){s==null&&(s=+new Date);var c=new i(s),l=a&&a.state,f=function(){return(c.next()>>>0)/4294967296};return f.double=function(){do var u=c.next()>>>11,d=(c.next()>>>0)/4294967296,h=(u+d)/(1<<21);while(h===0);return h},f.int32=c.next,f.quick=f,l&&(l.x&&n(l,c),f.state=function(){return n(c,{})}),f}e&&e.exports?e.exports=o:r&&r.amd?r(function(){return o}):this.xorshift7=o})(hv,typeof Bm=="object"&&Bm,typeof define=="function"&&define)});var mv=er((gv,km)=>{(function(t,e,r){function i(s){var a=this;a.next=function(){var l=a.w,f=a.X,u=a.i,d,h;return a.w=l=l+1640531527|0,h=f[u+34&127],d=f[u=u+1&127],h^=h<<13,d^=d<<17,h^=h>>>15,d^=d>>>12,h=f[u]=h^d,a.i=u,h+(l^l>>>16)|0};function c(l,f){var u,d,h,p,g,m=[],_=128;for(f===(f|0)?(d=f,f=null):(f=f+"\0",d=0,_=Math.max(_,f.length)),h=0,p=-32;p<_;++p)f&&(d^=f.charCodeAt((p+32)%f.length)),p===0&&(g=d),d^=d<<10,d^=d>>>15,d^=d<<4,d^=d>>>13,p>=0&&(g=g+1640531527|0,u=m[p&127]^=d+g,h=u==0?h+1:0);for(h>=128&&(m[(f&&f.length||0)&127]=-1),h=127,p=512;p>0;--p)d=m[h+34&127],u=m[h=h+1&127],d^=d<<13,u^=u<<17,d^=d>>>15,u^=u>>>12,m[h]=d^u;l.w=g,l.X=m,l.i=h}c(a,s)}function n(s,a){return a.i=s.i,a.w=s.w,a.X=s.X.slice(),a}function o(s,a){s==null&&(s=+new Date);var c=new i(s),l=a&&a.state,f=function(){return(c.next()>>>0)/4294967296};return f.double=function(){do var u=c.next()>>>11,d=(c.next()>>>0)/4294967296,h=(u+d)/(1<<21);while(h===0);return h},f.int32=c.next,f.quick=f,l&&(l.X&&n(l,c),f.state=function(){return n(c,{})}),f}e&&e.exports?e.exports=o:r&&r.amd?r(function(){return o}):this.xor4096=o})(gv,typeof km=="object"&&km,typeof define=="function"&&define)});var yv=er((_v,Um)=>{(function(t,e,r){function i(s){var a=this,c="";a.next=function(){var f=a.b,u=a.c,d=a.d,h=a.a;return f=f<<25^f>>>7^u,u=u-d|0,d=d<<24^d>>>8^h,h=h-f|0,a.b=f=f<<20^f>>>12^u,a.c=u=u-d|0,a.d=d<<16^u>>>16^h,a.a=h-f|0},a.a=0,a.b=0,a.c=-1640531527,a.d=1367130551,s===Math.floor(s)?(a.a=s/4294967296|0,a.b=s|0):c+=s;for(var l=0;l>>0)/4294967296};return f.double=function(){do var u=c.next()>>>11,d=(c.next()>>>0)/4294967296,h=(u+d)/(1<<21);while(h===0);return h},f.int32=c.next,f.quick=f,l&&(typeof l=="object"&&n(l,c),f.state=function(){return n(c,{})}),f}e&&e.exports?e.exports=o:r&&r.amd?r(function(){return o}):this.tychei=o})(_v,typeof Um=="object"&&Um,typeof define=="function"&&define)});var xv=er(()=>{});var Tv=er((bv,wu)=>{(function(t,e,r){var i=256,n=6,o=52,s="random",a=r.pow(i,n),c=r.pow(2,o),l=c*2,f=i-1,u;function d(y,x,w){var b=[];x=x==!0?{entropy:!0}:x||{};var E=m(g(x.entropy?[y,T(e)]:y??_(),3),b),S=new h(b),A=function(){for(var C=S.g(n),I=a,R=0;C=l;)C/=2,I/=2,R>>>=1;return(C+R)/I};return A.int32=function(){return S.g(4)|0},A.quick=function(){return S.g(4)/4294967296},A.double=A,m(T(S.S),e),(x.pass||w||function(C,I,R,N){return N&&(N.S&&p(N,S),C.state=function(){return p(S,{})}),R?(r[s]=C,I):C})(A,E,"global"in x?x.global:this==r,x.state)}function h(y){var x,w=y.length,b=this,E=0,S=b.i=b.j=0,A=b.S=[];for(w||(y=[w++]);E{var _B=cv(),yB=fv(),xB=dv(),bB=pv(),TB=mv(),wB=yv(),Xi=Tv();Xi.alea=_B;Xi.xor128=yB;Xi.xorwow=xB;Xi.xorshift7=bB;Xi.xor4096=TB;Xi.tychei=wB;wv.exports=Xi});function Er(t,e){if(!t)throw new Error(e||"loader assertion failed.")}var Ct={self:typeof self<"u"&&self,window:typeof window<"u"&&window,global:typeof global<"u"&&global,document:typeof document<"u"&&document},A2=Ct.self||Ct.window||Ct.global||{},v2=Ct.window||Ct.self||Ct.global||{},E2=Ct.global||Ct.self||Ct.window||{},R2=Ct.document||{};var ni=!!(typeof process!="object"||String(process)!=="[object process]"||process.browser);var Jm=typeof process<"u"&&process.version&&/v([0-9]*)/.exec(process.version),C2=Jm&&parseFloat(Jm[1])||0;lo();var zu="4.4.2",F2=zu[0]>="0"&&zu[0]<="9"?`v${zu}`:"";function B2(){let t=new Le({id:"loaders.gl"});return globalThis.loaders||={},globalThis.loaders.log=t,globalThis.loaders.version=F2,globalThis.probe||={},globalThis.probe.loaders=t,t}var Wu=B2();var k2=t=>typeof t=="boolean",Pt=t=>typeof t=="function",Mt=t=>t!==null&&typeof t=="object",nc=t=>Mt(t)&&t.constructor==={}.constructor;var Vu=t=>typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer,tn=t=>Mt(t)&&typeof t.byteLength=="number"&&typeof t.slice=="function";var ju=t=>!!t&&Pt(t[Symbol.iterator]),$u=t=>!!t&&Pt(t[Symbol.asyncIterator]);var Ge=t=>typeof Response<"u"&&t instanceof Response||Mt(t)&&Pt(t.arrayBuffer)&&Pt(t.text)&&Pt(t.json);var qe=t=>typeof Blob<"u"&&t instanceof Blob;var m_=t=>typeof ReadableStream<"u"&&t instanceof ReadableStream||Mt(t)&&Pt(t.tee)&&Pt(t.cancel)&&Pt(t.getReader);var __=t=>Mt(t)&&Pt(t.read)&&Pt(t.pipe)&&k2(t.readable),fo=t=>m_(t)||__(t);function Hu(t,e){return y_(t||{},e)}function y_(t,e,r=0){if(r>3)return e;let i={...t};for(let[n,o]of Object.entries(e))o&&typeof o=="object"&&!Array.isArray(o)?i[n]=y_(i[n]||{},e[n],r+1):i[n]=e[n];return i}var x_="latest";function U2(){return globalThis._loadersgl_?.version||(globalThis._loadersgl_=globalThis._loadersgl_||{},globalThis._loadersgl_.version="4.4.2"),globalThis._loadersgl_.version}var b_=U2();function Fe(t,e){if(!t)throw new Error(e||"loaders.gl assertion failed.")}var It={self:typeof self<"u"&&self,window:typeof window<"u"&&window,global:typeof global<"u"&&global,document:typeof document<"u"&&document},Xk=It.self||It.window||It.global||{},Gk=It.window||It.self||It.global||{},qk=It.global||It.self||It.window||{},Kk=It.document||{};var rt=typeof process!="object"||String(process)!=="[object process]"||process.browser;var w_=typeof window<"u"&&typeof window.orientation<"u",T_=typeof process<"u"&&process.version&&/v([0-9]*)/.exec(process.version),Zk=T_&&parseFloat(T_[1])||0;var uo=class{name;workerThread;isRunning=!0;result;_resolve=()=>{};_reject=()=>{};constructor(e,r){this.name=e,this.workerThread=r,this.result=new Promise((i,n)=>{this._resolve=i,this._reject=n})}postMessage(e,r){this.workerThread.postMessage({source:"loaders.gl",type:e,payload:r})}done(e){Fe(this.isRunning),this.isRunning=!1,this._resolve(e)}error(e){Fe(this.isRunning),this.isRunning=!1,this._reject(e)}};var rn=class{terminate(){}};var Yu=new Map;function S_(t){Fe(t.source&&!t.url||!t.source&&t.url);let e=Yu.get(t.source||t.url);return e||(t.url&&(e=z2(t.url),Yu.set(t.url,e)),t.source&&(e=A_(t.source),Yu.set(t.source,e))),Fe(e),e}function z2(t){if(!t.startsWith("http"))return t;let e=W2(t);return A_(e)}function A_(t){let e=new Blob([t],{type:"application/javascript"});return URL.createObjectURL(e)}function W2(t){return`try { + importScripts('${t}'); +} catch (error) { + console.error(error); + throw error; +}`}function Xu(t,e=!0,r){let i=r||new Set;if(t){if(v_(t))i.add(t);else if(v_(t.buffer))i.add(t.buffer);else if(!ArrayBuffer.isView(t)){if(e&&typeof t=="object")for(let n in t)Xu(t[n],e,i)}}return r===void 0?Array.from(i):[]}function v_(t){return t?t instanceof ArrayBuffer||typeof MessagePort<"u"&&t instanceof MessagePort||typeof ImageBitmap<"u"&&t instanceof ImageBitmap||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas:!1}var Gu=()=>{},Cr=class{name;source;url;terminated=!1;worker;onMessage;onError;_loadableURL="";static isSupported(){return typeof Worker<"u"&&rt||typeof rn<"u"&&!rt}constructor(e){let{name:r,source:i,url:n}=e;Fe(i||n),this.name=r,this.source=i,this.url=n,this.onMessage=Gu,this.onError=o=>console.log(o),this.worker=rt?this._createBrowserWorker():this._createNodeWorker()}destroy(){this.onMessage=Gu,this.onError=Gu,this.worker.terminate(),this.terminated=!0}get isRunning(){return!!this.onMessage}postMessage(e,r){r=r||Xu(e),this.worker.postMessage(e,r)}_getErrorFromErrorEvent(e){let r="Failed to load ";return r+=`worker ${this.name} from ${this.url}. `,e.message&&(r+=`${e.message} in `),e.lineno&&(r+=`:${e.lineno}:${e.colno}`),new Error(r)}_createBrowserWorker(){this._loadableURL=S_({source:this.source,url:this.url});let e=new Worker(this._loadableURL,{name:this.name});return e.onmessage=r=>{r.data?this.onMessage(r.data):this.onError(new Error("No data received"))},e.onerror=r=>{this.onError(this._getErrorFromErrorEvent(r)),this.terminated=!0},e.onmessageerror=r=>console.error(r),e}_createNodeWorker(){let e;if(this.url){let i=this.url.includes(":/")||this.url.startsWith("/")?this.url:`./${this.url}`,n=this.url.endsWith(".ts")||this.url.endsWith(".mjs")?"module":"commonjs";e=new rn(i,{eval:!1,type:n})}else if(this.source)e=new rn(this.source,{eval:!0});else throw new Error("no worker");return e.on("message",r=>{this.onMessage(r)}),e.on("error",r=>{this.onError(r)}),e.on("exit",r=>{}),e}};var ho=class{name="unnamed";source;url;maxConcurrency=1;maxMobileConcurrency=1;onDebug=()=>{};reuseWorkers=!0;props={};jobQueue=[];idleQueue=[];count=0;isDestroyed=!1;static isSupported(){return Cr.isSupported()}constructor(e){this.source=e.source,this.url=e.url,this.setProps(e)}destroy(){this.idleQueue.forEach(e=>e.destroy()),this.isDestroyed=!0}setProps(e){this.props={...this.props,...e},e.name!==void 0&&(this.name=e.name),e.maxConcurrency!==void 0&&(this.maxConcurrency=e.maxConcurrency),e.maxMobileConcurrency!==void 0&&(this.maxMobileConcurrency=e.maxMobileConcurrency),e.reuseWorkers!==void 0&&(this.reuseWorkers=e.reuseWorkers),e.onDebug!==void 0&&(this.onDebug=e.onDebug)}async startJob(e,r=(n,o,s)=>n.done(s),i=(n,o)=>n.error(o)){let n=new Promise(o=>(this.jobQueue.push({name:e,onMessage:r,onError:i,onStart:o}),this));return this._startQueuedJob(),await n}async _startQueuedJob(){if(!this.jobQueue.length)return;let e=this._getAvailableWorker();if(!e)return;let r=this.jobQueue.shift();if(r){this.onDebug({message:"Starting job",name:r.name,workerThread:e,backlog:this.jobQueue.length});let i=new uo(r.name,e);e.onMessage=n=>r.onMessage(i,n.type,n.payload),e.onError=n=>r.onError(i,n),r.onStart(i);try{await i.result}catch(n){console.error(`Worker exception: ${n}`)}finally{this.returnWorkerToQueue(e)}}}returnWorkerToQueue(e){!rt||this.isDestroyed||!this.reuseWorkers||this.count>this._getMaxConcurrency()?(e.destroy(),this.count--):this.idleQueue.push(e),this.isDestroyed||this._startQueuedJob()}_getAvailableWorker(){if(this.idleQueue.length>0)return this.idleQueue.shift()||null;if(this.count{}},si=class t{props;workerPools=new Map;static _workerFarm;static isSupported(){return Cr.isSupported()}static getWorkerFarm(e={}){return t._workerFarm=t._workerFarm||new t({}),t._workerFarm.setProps(e),t._workerFarm}constructor(e){this.props={...V2},this.setProps(e),this.workerPools=new Map}destroy(){for(let e of this.workerPools.values())e.destroy();this.workerPools=new Map}setProps(e){this.props={...this.props,...e};for(let r of this.workerPools.values())r.setProps(this._getWorkerPoolProps())}getWorkerPool(e){let{name:r,source:i,url:n}=e,o=this.workerPools.get(r);return o||(o=new ho({name:r,source:i,url:n}),o.setProps(this._getWorkerPoolProps()),this.workerPools.set(r,o)),o}_getWorkerPoolProps(){return{maxConcurrency:this.props.maxConcurrency,maxMobileConcurrency:this.props.maxMobileConcurrency,reuseWorkers:this.props.reuseWorkers,onDebug:this.props.onDebug}}};function qu(t,e={}){let r=e[t.id]||{},i=rt?`${t.id}-worker.js`:`${t.id}-worker-node.js`,n=r.workerUrl;if(!n&&t.id==="compression"&&(n=e.workerUrl),(e._workerType||e?.core?._workerType)==="test"&&(rt?n=`modules/${t.module}/dist/${i}`:n=`modules/${t.module}/src/workers/${t.id}-worker-node.ts`),!n){let s=t.version;s==="latest"&&(s=x_);let a=s?`@${s}`:"";n=`https://unpkg.com/@loaders.gl/${t.module}${a}/dist/${i}`}return Fe(n),n}function Ku(t,e=b_){Fe(t,"no worker provided");let r=t.version;return!(!e||!r)}function Zu(t,e){if(!si.isSupported())return!1;let r=e?._nodeWorkers??e?.core?._nodeWorkers;if(!rt&&!r)return!1;let i=e?.worker??e?.core?.worker;return!!(t.worker&&i)}async function Qu(t,e,r,i,n){let o=t.id,s=qu(t,r),c=si.getWorkerFarm(r?.core).getWorkerPool({name:o,url:s});r=JSON.parse(JSON.stringify(r)),i=JSON.parse(JSON.stringify(i||{}));let l=await c.startJob("process-on-worker",j2.bind(null,n));return l.postMessage("process",{input:e,options:r,context:i}),await(await l.result).result}async function j2(t,e,r,i){switch(r){case"done":e.done(i);break;case"error":e.error(new Error(i.error));break;case"process":let{id:n,input:o,options:s}=i;try{let a=await t(o,s);e.postMessage("done",{id:n,result:a})}catch(a){let c=a instanceof Error?a.message:"unknown error";e.postMessage("error",{id:n,error:c})}break;default:console.warn(`parse-with-worker unknown message ${r}`)}}function Ju(t,e,r){if(r=r||t.byteLength,t.byteLengtho instanceof ArrayBuffer?new Uint8Array(o):o),r=e.reduce((o,s)=>o+s.byteLength,0),i=new Uint8Array(r),n=0;for(let o of e)i.set(o,n),n+=o.byteLength;return i.buffer}async function td(t){let e=[];for await(let r of t)e.push($2(r));return ed(...e)}function $2(t){if(t instanceof ArrayBuffer)return t;if(ArrayBuffer.isView(t)){let{buffer:e,byteOffset:r,byteLength:i}=t;return R_(e,r,i)}return R_(t)}function R_(t,e=0,r=t.byteLength-e){let i=new Uint8Array(t,e,r),n=new Uint8Array(i.length);return n.set(i),n.buffer}var H2="",P_={};function nd(t){for(let e in P_)if(t.startsWith(e)){let r=P_[e];t=t.replace(e,r)}return!t.startsWith("http://")&&!t.startsWith("https://")&&(t=`${H2}${t}`),t}function sc(t){return t&&typeof t=="object"&&t.isBuffer}function nn(t){if(sc(t))return t;if(t instanceof ArrayBuffer)return t;if(Vu(t))return oc(t);if(ArrayBuffer.isView(t)){let e=t.buffer;return t.byteOffset===0&&t.byteLength===t.buffer.byteLength?e:e.slice(t.byteOffset,t.byteOffset+t.byteLength)}if(typeof t=="string"){let e=t;return new TextEncoder().encode(e).buffer}if(t&&typeof t=="object"&&t._toArrayBuffer)return t._toArrayBuffer();throw new Error("toArrayBuffer")}function mo(t){if(t instanceof ArrayBuffer)return t;if(Vu(t))return oc(t);let{buffer:e,byteOffset:r,byteLength:i}=t;return e instanceof ArrayBuffer&&r===0&&i===e.byteLength?e:oc(e,r,i)}function oc(t,e=0,r=t.byteLength-e){let i=new Uint8Array(t,e,r),n=new Uint8Array(i.length);return n.set(i),n.buffer}function od(t){return ArrayBuffer.isView(t)?t:new Uint8Array(t)}var tr={};Zi(tr,{dirname:()=>X2,filename:()=>Y2,join:()=>G2,resolve:()=>q2});function M_(){if(typeof process<"u"&&typeof process.cwd<"u")return process.cwd();let t=window.location?.pathname;return t?.slice(0,t.lastIndexOf("/")+1)||""}function Y2(t){let e=t?t.lastIndexOf("/"):-1;return e>=0?t.substr(e+1):t}function X2(t){let e=t?t.lastIndexOf("/"):-1;return e>=0?t.substr(0,e):""}function G2(...t){return t=t.map((r,i)=>(i&&(r=r.replace(new RegExp("^/"),"")),i!==t.length-1&&(r=r.replace(new RegExp("/$"),"")),r)),t.join("/")}function q2(...t){let e=[];for(let o=0;o=-1&&!i;o--){let s;o>=0?s=e[o]:(n===void 0&&(n=M_()),s=n),s.length!==0&&(r=`${s}/${r}`,i=s.charCodeAt(0)===_o)}return r=K2(r,!i),i?`/${r}`:r.length>0?r:"."}var _o=47,sd=46;function K2(t,e){let r="",i=-1,n=0,o,s=!1;for(let a=0;a<=t.length;++a){if(a2){let c=r.length-1,l=c;for(;l>=0&&r.charCodeAt(l)!==_o;--l);if(l!==c){r=l===-1?"":r.slice(0,l),i=a,n=0,s=!1;continue}}else if(r.length===2||r.length===1){r="",i=a,n=0,s=!1;continue}}e&&(r.length>0?r+="/..":r="..",s=!0)}else{let c=t.slice(i+1,a);r.length>0?r+=`/${c}`:r=c,s=!1}i=a,n=0}else o===sd&&n!==-1?++n:n=-1}return r}var ac=class extends Error{constructor(e,r){super(e),this.reason=r.reason,this.url=r.url,this.response=r.response}reason;url;response};var J2=/^data:([-\w.]+\/[-\w.+]+)(;|,)/,eE=/^([-\w.]+\/[-\w.+]+)/;function ad(t,e){return t.toLowerCase()===e.toLowerCase()}function I_(t){let e=eE.exec(t);return e?e[1]:t}function cd(t){let e=J2.exec(t);return e?e[1]:""}var O_=/\?.*/;function N_(t){let e=t.match(O_);return e&&e[0]}function Pr(t){return t.replace(O_,"")}function D_(t){if(t.length<50)return t;let e=t.slice(t.length-15);return`${t.substr(0,32)}...${e}`}function ci(t){return Ge(t)?t.url:qe(t)?("name"in t?t.name:"")||"":typeof t=="string"?t:""}function on(t){if(Ge(t)){let e=t.headers.get("content-type")||"",r=Pr(t.url);return I_(e)||cd(r)}return qe(t)?t.type||"":typeof t=="string"?cd(t):""}function L_(t){return Ge(t)?t.headers["content-length"]||-1:qe(t)?t.size:typeof t=="string"?t.length:t instanceof ArrayBuffer||ArrayBuffer.isView(t)?t.byteLength:-1}async function cc(t){if(Ge(t))return t;let e={},r=L_(t);r>=0&&(e["content-length"]=String(r));let i=ci(t),n=on(t);n&&(e["content-type"]=n);let o=await rE(t);o&&(e["x-first-bytes"]=o),typeof t=="string"&&(t=new TextEncoder().encode(t));let s=new Response(t,{headers:e});return Object.defineProperty(s,"url",{value:i}),s}async function F_(t){if(!t.ok)throw await tE(t)}async function tE(t){let e=D_(t.url),r=`Failed to fetch resource (${t.status}) ${t.statusText}: ${e}`;r=r.length>100?`${r.slice(0,100)}...`:r;let i={reason:t.statusText,url:t.url,response:t};try{let n=t.headers.get("Content-Type");i.reason=!t.bodyUsed&&n?.includes("application/json")?await t.json():await t.text()}catch{}return new ac(r,i)}async function rE(t){if(typeof t=="string")return`data:,${t.slice(0,5)}`;if(t instanceof Blob){let r=t.slice(0,5);return await new Promise(i=>{let n=new FileReader;n.onload=o=>i(o?.target?.result),n.readAsDataURL(r)})}if(t instanceof ArrayBuffer){let r=t.slice(0,5);return`data:base64,${iE(r)}`}return null}function iE(t){let e="",r=new Uint8Array(t);for(let i=0;i{}}info(){return()=>{}}warn(){return()=>{}}error(){return()=>{}}},fc=class{console;constructor(){this.console=console}log(...e){return this.console.log.bind(this.console,...e)}info(...e){return this.console.info.bind(this.console,...e)}warn(...e){return this.console.warn.bind(this.console,...e)}error(...e){return this.console.error.bind(this.console,...e)}};var uc={core:{baseUrl:void 0,fetch:null,mimeType:void 0,fallbackMimeType:void 0,ignoreRegisteredLoaders:void 0,nothrow:!1,log:new fc,useLocalLibraries:!1,CDN:"https://unpkg.com/@loaders.gl",worker:!0,maxConcurrency:3,maxMobileConcurrency:1,reuseWorkers:ni,_nodeWorkers:!1,_workerType:"",limit:0,_limitMB:0,batchSize:"auto",batchDebounceMs:0,metadata:!1,transforms:[]}},B_={baseUri:"core.baseUrl",fetch:"core.fetch",mimeType:"core.mimeType",fallbackMimeType:"core.fallbackMimeType",ignoreRegisteredLoaders:"core.ignoreRegisteredLoaders",nothrow:"core.nothrow",log:"core.log",useLocalLibraries:"core.useLocalLibraries",CDN:"core.CDN",worker:"core.worker",maxConcurrency:"core.maxConcurrency",maxMobileConcurrency:"core.maxMobileConcurrency",reuseWorkers:"core.reuseWorkers",_nodeWorkers:"core.nodeWorkers",_workerType:"core._workerType",_worker:"core._workerType",limit:"core.limit",_limitMB:"core._limitMB",batchSize:"core.batchSize",batchDebounceMs:"core.batchDebounceMs",metadata:"core.metadata",transforms:"core.transforms",throws:"nothrow",dataType:"(no longer used)",uri:"core.baseUrl",method:"core.fetch.method",headers:"core.fetch.headers",body:"core.fetch.body",mode:"core.fetch.mode",credentials:"core.fetch.credentials",cache:"core.fetch.cache",redirect:"core.fetch.redirect",referrer:"core.fetch.referrer",referrerPolicy:"core.fetch.referrerPolicy",integrity:"core.fetch.integrity",keepalive:"core.fetch.keepalive",signal:"core.fetch.signal"};var fd=["baseUrl","fetch","mimeType","fallbackMimeType","ignoreRegisteredLoaders","nothrow","log","useLocalLibraries","CDN","worker","maxConcurrency","maxMobileConcurrency","reuseWorkers","_nodeWorkers","_workerType","limit","_limitMB","batchSize","batchDebounceMs","metadata","transforms"];function ud(){globalThis.loaders=globalThis.loaders||{};let{loaders:t}=globalThis;return t._state||(t._state={}),t._state}function dd(){let t=ud();return t.globalOptions=t.globalOptions||{...uc,core:{...uc.core}},rr(t.globalOptions)}function z_(t,e,r,i){return r=r||[],r=Array.isArray(r)?r:[r],aE(t,r),rr(lE(e,t,i))}function rr(t){let e=uE(t);W_(e);for(let r of fd)e.core&&e.core[r]!==void 0&&delete e[r];return e.core&&e.core._workerType!==void 0&&delete e._worker,e}function aE(t,e){k_(t,null,uc,B_,e);for(let r of e){let i=t&&t[r.id]||{},n=r.options&&r.options[r.id]||{},o=r.deprecatedOptions&&r.deprecatedOptions[r.id]||{};k_(i,r.id,n,o,e)}}function k_(t,e,r,i,n){let o=e||"Top level",s=e?`${e}.`:"";for(let a in t){let c=!e&&Mt(t[a]),l=a==="baseUri"&&!e,f=a==="workerUrl"&&e;if(!(a in r)&&!l&&!f){if(a in i)yo.level>0&&yo.warn(`${o} loader option '${s}${a}' no longer supported, use '${i[a]}'`)();else if(!c&&yo.level>0){let u=cE(a,n);yo.warn(`${o} loader option '${s}${a}' not recognized. ${u}`)()}}}}function cE(t,e){let r=t.toLowerCase(),i="";for(let n of e)for(let o in n.options){if(t===o)return`Did you mean '${n.id}.${o}'?`;let s=o.toLowerCase();(r.startsWith(s)||s.startsWith(r))&&(i=i||`Did you mean '${n.id}.${o}'?`)}return i}function lE(t,e,r){let i=t.options||{},n={...i};i.core&&(n.core={...i.core}),W_(n),n.core?.log===null&&(n.core={...n.core,log:new lc}),U_(n,rr(dd()));let o=rr(e);return U_(n,o),fE(n,r),dE(n),n}function U_(t,e){for(let r in e)if(r in e){let i=e[r];nc(i)&&nc(t[r])?t[r]={...t[r],...e[r]}:t[r]=e[r]}}function fE(t,e){if(!e)return;t.core?.baseUrl!==void 0||(t.core||={},t.core.baseUrl=tr.dirname(Pr(e)))}function uE(t){let e={...t};return t.core&&(e.core={...t.core}),e}function W_(t){t.baseUri!==void 0&&(t.core||={},t.core.baseUrl===void 0&&(t.core.baseUrl=t.baseUri));for(let r of fd)if(t[r]!==void 0){let n=t.core=t.core||{};n[r]===void 0&&(n[r]=t[r])}let e=t._worker;e!==void 0&&(t.core||={},t.core._workerType===void 0&&(t.core._workerType=e))}function dE(t){let e=t.core;if(e)for(let r of fd)e[r]!==void 0&&(t[r]=e[r])}function xo(t){return t?(Array.isArray(t)&&(t=t[0]),Array.isArray(t?.extensions)):!1}function bo(t){Er(t,"null loader"),Er(xo(t),"invalid loader");let e;return Array.isArray(t)&&(e=t[1],t=t[0],t={...t,options:{...t.options,...e}}),(t?.parseTextSync||t?.parseText)&&(t.text=!0),t.text||(t.binary=!0),t}var V_=()=>{let t=ud();return t.loaderRegistry=t.loaderRegistry||[],t.loaderRegistry};function hd(t){let e=V_();t=Array.isArray(t)?t:[t];for(let r of t){let i=bo(r);e.find(n=>i===n)||e.unshift(i)}}function j_(){return V_()}var hE=/\.([^.]+)$/;async function Y_(t,e=[],r,i){if(!X_(t))return null;let n=rr(r||{});if(n.core||={},t instanceof Response&&$_(t)){let s=await t.clone().text(),a=dc(s,e,{...n,core:{...n.core,nothrow:!0}},i);if(a)return a}let o=dc(t,e,{...n,core:{...n.core,nothrow:!0}},i);if(o)return o;if(qe(t)&&(t=await t.slice(0,10).arrayBuffer(),o=dc(t,e,n,i)),!o&&t instanceof Response&&$_(t)){let s=await t.clone().text();o=dc(s,e,n,i)}if(!o&&!n.core.nothrow)throw new Error(G_(t));return o}function $_(t){let e=on(t);return!!(e&&(e.startsWith("text/")||e==="application/json"||e.endsWith("+json")))}function dc(t,e=[],r,i){if(!X_(t))return null;let n=rr(r||{});if(n.core||={},e&&!Array.isArray(e))return bo(e);let o=[];e&&(o=o.concat(e)),n.core.ignoreRegisteredLoaders||o.push(...j_()),gE(o);let s=pE(t,o,n,i);if(!s&&!n.core.nothrow)throw new Error(G_(t));return s}function pE(t,e,r,i){let n=ci(t),o=on(t),s=Pr(n)||i?.url,a=null,c="";return r?.core?.mimeType&&(a=pd(e,r?.core?.mimeType),c=`match forced by supplied MIME type ${r?.core?.mimeType}`),a=a||mE(e,s),c=c||(a?`matched url ${s}`:""),a=a||pd(e,o),c=c||(a?`matched MIME type ${o}`:""),a=a||yE(e,t),c=c||(a?`matched initial data ${q_(t)}`:""),r?.core?.fallbackMimeType&&(a=a||pd(e,r?.core?.fallbackMimeType),c=c||(a?`matched fallback MIME type ${o}`:"")),c&&Wu.log(1,`selectLoader selected ${a?.name}: ${c}.`),a}function X_(t){return!(t instanceof Response&&t.status===204)}function G_(t){let e=ci(t),r=on(t),i="No valid loader found (";i+=e?`${tr.filename(e)}, `:"no url provided, ",i+=`MIME type: ${r?`"${r}"`:"not provided"}, `;let n=t?q_(t):"";return i+=n?` first bytes: "${n}"`:"first bytes: not available",i+=")",i}function gE(t){for(let e of t)bo(e)}function mE(t,e){let r=e&&hE.exec(e),i=r&&r[1];return i?_E(t,i):null}function _E(t,e){e=e.toLowerCase();for(let r of t)for(let i of r.extensions)if(i.toLowerCase()===e)return r;return null}function pd(t,e){for(let r of t)if(r.mimeTypes?.some(i=>ad(e,i))||ad(e,`application/x.${r.id}`))return r;return null}function yE(t,e){if(!e)return null;for(let r of t)if(typeof e=="string"){if(xE(e,r))return r}else if(ArrayBuffer.isView(e)){if(H_(e.buffer,e.byteOffset,r))return r}else if(e instanceof ArrayBuffer&&H_(e,0,r))return r;return null}function xE(t,e){return e.testText?e.testText(t):(Array.isArray(e.tests)?e.tests:[e.tests]).some(i=>t.startsWith(i))}function H_(t,e,r){return(Array.isArray(r.tests)?r.tests:[r.tests]).some(n=>bE(t,e,r,n))}function bE(t,e,r,i){if(tn(i))return Ju(i,t,i.byteLength);switch(typeof i){case"function":return i(mo(t));case"string":let n=gd(t,e,i.length);return i===n;default:return!1}}function q_(t,e=5){return typeof t=="string"?t.slice(0,e):ArrayBuffer.isView(t)?gd(t.buffer,t.byteOffset,e):t instanceof ArrayBuffer?gd(t,0,e):""}function gd(t,e,r){if(t.byteLengthld(o,n):e?.fetch?e?.fetch:ld}function r0(t,e,r){if(r)return r;let i={fetch:hc(e,t),...t};if(i.url){let n=Pr(i.url);i.baseUrl=n,i.queryString=N_(i.url),i.filename=tr.filename(n),i.baseUrl=tr.dirname(n)}return Array.isArray(i.loaders)||(i.loaders=null),i}function i0(t,e){if(t&&!Array.isArray(t))return t;let r;if(t&&(r=Array.isArray(t)?t:[t]),e&&e.loaders){let i=Array.isArray(e.loaders)?e.loaders:[e.loaders];r=r?[...r,...i]:i}return r&&r.length?r:void 0}async function To(t,e,r,i){e&&!Array.isArray(e)&&!xo(e)&&(i=void 0,r=e,e=void 0),t=await t,r=r||{};let n=ci(t),s=i0(e,i),a=await Y_(t,s,r);if(!a)return null;let c=z_(r,a,s,n);return i=r0({url:n,_parse:To,loaders:s},c,i||null),await vE(a,t,c,i)}async function vE(t,e,r,i){if(Ku(t),r=Hu(t.options,r),Ge(e)){let{ok:o,redirected:s,status:a,statusText:c,type:l,url:f}=e,u=Object.fromEntries(e.headers.entries());i.response={headers:u,ok:o,redirected:s,status:a,statusText:c,type:l,url:f}}e=await t0(e,t,r);let n=t;if(n.parseTextSync&&typeof e=="string")return n.parseTextSync(e,r,i);if(Zu(t,r))return await Qu(t,e,r,i,To);if(n.parseText&&typeof e=="string")return await n.parseText(e,r,i);if(n.parse)return await n.parse(e,r,i);throw Fe(!n.parseSync),new Error(`${t.id} loader - no parser found and worker is disabled`)}function n0(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function o0(t){return Array.isArray(t)?t.length===0||typeof t[0]=="number":!1}function _d(t){return n0(t)||o0(t)}async function Mr(t,e,r,i){let n,o;!Array.isArray(e)&&!xo(e)?(n=[],o=e,i=void 0):(n=e,o=r);let s=hc(o),a=t;return typeof t=="string"&&(a=await s(t)),qe(t)&&(a=await s(t)),typeof t=="string"&&(rr(o||{}).core?.baseUrl||(o={...o,core:{...o?.core,baseUrl:t}})),Array.isArray(n)?await To(a,n,o):await To(a,n,o)}var s0="4.4.2";var EE=globalThis.loaders?.parseImageNode,yd=typeof Image<"u",xd=typeof ImageBitmap<"u",RE=!!EE,bd=ni?!0:RE;function a0(t){switch(t){case"auto":return xd||yd||bd;case"imagebitmap":return xd;case"image":return yd;case"data":return bd;default:throw new Error(`@loaders.gl/images: image ${t} not supported in this environment`)}}function c0(){if(xd)return"imagebitmap";if(yd)return"image";if(bd)return"data";throw new Error("Install '@loaders.gl/polyfills' to parse images under Node.js")}function CE(t){let e=PE(t);if(!e)throw new Error("Not an image");return e}function l0(t){switch(CE(t)){case"data":return t;case"image":case"imagebitmap":let e=document.createElement("canvas"),r=e.getContext("2d");if(!r)throw new Error("getImageData");return e.width=t.width,e.height=t.height,r.drawImage(t,0,0),r.getImageData(0,0,t.width,t.height);default:throw new Error("getImageData")}}function PE(t){return typeof ImageBitmap<"u"&&t instanceof ImageBitmap?"imagebitmap":typeof Image<"u"&&t instanceof Image?"image":t&&typeof t=="object"&&t.data&&t.width&&t.height?"data":null}var ME=/^data:image\/svg\+xml/,IE=/\.svg((\?|#).*)?$/;function pc(t){return t&&(ME.test(t)||IE.test(t))}function f0(t,e){if(pc(e)){let i=new TextDecoder().decode(t);try{typeof unescape=="function"&&typeof encodeURIComponent=="function"&&(i=unescape(encodeURIComponent(i)))}catch(o){throw new Error(o.message)}return`data:image/svg+xml;base64,${btoa(i)}`}return Td(t,e)}function Td(t,e){if(pc(e))throw new Error("SVG cannot be parsed directly to imagebitmap");return new Blob([new Uint8Array(t)])}async function gc(t,e,r){let i=f0(t,r),n=self.URL||self.webkitURL,o=typeof i!="string"&&n.createObjectURL(i);try{return await OE(o||i,e)}finally{o&&n.revokeObjectURL(o)}}async function OE(t,e){let r=new Image;return r.src=t,e.image&&e.image.decode&&r.decode?(await r.decode(),r):await new Promise((i,n)=>{try{r.onload=()=>i(r),r.onerror=o=>{let s=o instanceof Error?o.message:"error";n(new Error(s))}}catch(o){n(o)}})}var u0=!0;async function d0(t,e,r){let i;pc(r)?i=await gc(t,e,r):i=Td(t,r);let n=e&&e.imagebitmap;return await NE(i,n)}async function NE(t,e=null){if((DE(e)||!u0)&&(e=null),e)try{return await createImageBitmap(t,e)}catch(r){console.warn(r),u0=!1}return await createImageBitmap(t)}function DE(t){if(!t)return!0;for(let e in t)if(Object.prototype.hasOwnProperty.call(t,e))return!1;return!0}function h0(t){return!kE(t,"ftyp",4)||(t[8]&96)===0?null:LE(t)}function LE(t){switch(FE(t,8,12).replace("\0"," ").trim()){case"avif":case"avis":return{extension:"avif",mimeType:"image/avif"};default:return null}}function FE(t,e,r){return String.fromCharCode(...t.slice(e,r))}function BE(t){return[...t].map(e=>e.charCodeAt(0))}function kE(t,e,r=0){let i=BE(e);for(let n=0;n=24&&e.getUint32(0,Ot)===2303741511?{mimeType:"image/png",width:e.getUint32(16,Ot),height:e.getUint32(20,Ot)}:null}function WE(t){let e=So(t);return e.byteLength>=10&&e.getUint32(0,Ot)===1195984440?{mimeType:"image/gif",width:e.getUint16(6,wo),height:e.getUint16(8,wo)}:null}function VE(t){let e=So(t);return e.byteLength>=14&&e.getUint16(0,Ot)===16973&&e.getUint32(2,wo)===e.byteLength?{mimeType:"image/bmp",width:e.getUint32(18,wo),height:e.getUint32(22,wo)}:null}function jE(t){let e=So(t);if(!(e.byteLength>=3&&e.getUint16(0,Ot)===65496&&e.getUint8(2)===255))return null;let{tableMarkers:i,sofMarkers:n}=$E(),o=2;for(;o+9!!mc(new DataView(t))],options:GE};lo();var qE=new Le({id:"deck"}),F=qE;var Sd={};function m0(t){Sd=t}function ae(t,e,r,i){F.level>0&&Sd[t]&&Sd[t].call(null,e,r,i)}function KE(t){let e=t[0],r=t[t.length-1];return e==="{"&&r==="}"||e==="["&&r==="]"}var _0={dataType:null,batchType:null,id:"JSON",name:"JSON",module:"",version:"",options:{},extensions:["json","geojson"],mimeTypes:["application/json","application/geo+json"],testText:KE,parseTextSync:JSON.parse};function ZE(){let t="9.3.2",e=globalThis.deck&&globalThis.deck.VERSION;if(e&&e!==t)throw new Error(`deck.gl - multiple versions detected: ${e} vs ${t}`);return e||(F.log(1,`deck.gl ${t}`)(),globalThis.deck={...globalThis.deck,VERSION:t,version:t,log:F,_registerLoggers:m0},hd([_0,[wd,{imagebitmap:{premultiplyAlpha:"none"}}]])),t}var y0=ZE();function li(t,e){if(!t){let r=new Error(e||"shadertools: assertion failed.");throw Error.captureStackTrace?.(r,li),r}}var Ad={number:{type:"number",validate(t,e){return Number.isFinite(t)&&typeof e=="object"&&(e.max===void 0||t<=e.max)&&(e.min===void 0||t>=e.min)}},array:{type:"array",validate(t,e){return Array.isArray(t)||ArrayBuffer.isView(t)}}};function b0(t){let e={};for(let[r,i]of Object.entries(t))e[r]=QE(i);return e}function QE(t){let e=x0(t);if(e!=="object")return{value:t,...Ad[e],type:e};if(typeof t=="object")return t?t.type!==void 0?{...t,...Ad[t.type],type:t.type}:t.value===void 0?{type:"object",value:t}:(e=x0(t.value),{...t,...Ad[e],type:e}):{type:"object",value:null};throw new Error("props")}function x0(t){return Array.isArray(t)||ArrayBuffer.isView(t)?"array":typeof t}var T0=`#ifdef MODULE_LOGDEPTH + logdepth_adjustPosition(gl_Position); +#endif +`,w0=`#ifdef MODULE_MATERIAL + fragColor = material_filterColor(fragColor); +#endif + +#ifdef MODULE_LIGHTING + fragColor = lighting_filterColor(fragColor); +#endif + +#ifdef MODULE_FOG + fragColor = fog_filterColor(fragColor); +#endif + +#ifdef MODULE_PICKING + fragColor = picking_filterHighlightColor(fragColor); + fragColor = picking_filterPickingColor(fragColor); +#endif + +#ifdef MODULE_LOGDEPTH + logdepth_setFragDepth(); +#endif +`;var JE={vertex:T0,fragment:w0},S0=/void\s+main\s*\([^)]*\)\s*\{\n?/,A0=/}\n?[^{}]*$/,vd=[],Ao="__LUMA_INJECT_DECLARATIONS__";function v0(t){let e={vertex:{},fragment:{}};for(let r in t){let i=t[r],n=e3(r);typeof i=="string"&&(i={order:0,injection:i}),e[n][r]=i}return e}function e3(t){let e=t.slice(0,2);switch(e){case"vs":return"vertex";case"fs":return"fragment";default:throw new Error(e)}}function vo(t,e,r,i=!1){let n=e==="vertex";for(let o in r){let s=r[o];s.sort((c,l)=>c.order-l.order),vd.length=s.length;for(let c=0,l=s.length;cc+a));break;case"vs:#main-end":n&&(t=t.replace(A0,c=>a+c));break;case"fs:#decl":n||(t=t.replace(Ao,a));break;case"fs:#main-start":n||(t=t.replace(S0,c=>c+a));break;case"fs:#main-end":n||(t=t.replace(A0,c=>a+c));break;default:t=t.replace(o,c=>c+a)}}return t=t.replace(Ao,""),i&&(t=t.replace(/\}\s*$/,o=>o+JE[e])),t}function sn(t){t.map(e=>t3(e))}function t3(t){if(t.instance)return;sn(t.dependencies||[]);let{propTypes:e={},deprecations:r=[],inject:i={}}=t,n={normalizedInjections:v0(i),parsedDeprecations:r3(r)};e&&(n.propValidators=b0(e)),t.instance=n;let o={};e&&(o=Object.entries(e).reduce((s,[a,c])=>{let l=c?.value;return l&&(s[a]=l),s},{})),t.defaultUniforms={...t.defaultUniforms,...o}}function Ed(t,e,r){t.deprecations?.forEach(i=>{i.regex?.test(e)&&(i.deprecated?r.deprecated(i.old,i.new)():r.removed(i.old,i.new)())})}function r3(t){return t.forEach(e=>{e.type==="function"?e.regex=new RegExp(`\\b${e.old}\\(`):e.regex=new RegExp(`${e.type} ${e.old};`)}),t}function an(t){sn(t);let e={},r={};E0({modules:t,level:0,moduleMap:e,moduleDepth:r});let i=Object.keys(r).sort((n,o)=>r[o]-r[n]).map(n=>e[n]);return sn(i),i}function E0(t){let{modules:e,level:r,moduleMap:i,moduleDepth:n}=t;if(r>=5)throw new Error("Possible loop in shader dependency graph");for(let o of e)i[o.name]=o,(n[o.name]===void 0||n[o.name]]+>)?\s+([A-Za-z0-9_]+)(?:\s*\[[^\]]+\])?\s*;/,n3=/((?:layout\s*\([^)]*\)\s*)*)uniform\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{([\s\S]*?)\}\s*([A-Za-z_][A-Za-z0-9_]*)?\s*;/g;function C0(t){return`${t.name}Uniforms`}function o3(t,e){let r=e==="wgsl"?t.source:e==="vertex"?t.vs:t.fs;if(!r)return null;let i=C0(t);return a3(r,e==="wgsl"?"wgsl":"glsl",i)}function s3(t,e){let r=Object.keys(t.uniformTypes||{});if(!r.length)return null;let i=o3(t,e);return i?{moduleName:t.name,uniformBlockName:C0(t),stage:e,expectedUniformNames:r,actualUniformNames:i,matches:f3(r,i)}:null}function P0(t,e,r={}){let i=s3(t,e);if(!i||i.matches)return i;let n=u3(i);return r.log?.error?.(n,i)(),r.throwOnError!==!1&&li(!1,n),i}function M0(t){let e=[],r=d3(t);for(let i of r.matchAll(n3)){let n=i[1]?.trim()||null;e.push({blockName:i[2],body:i[3],instanceName:i[4]||null,layoutQualifier:n,hasLayoutQualifier:!!n,isStd140:!!(n&&/\blayout\s*\([^)]*\bstd140\b[^)]*\)/.exec(n))})}return e}function I0(t,e,r,i){let n=M0(t).filter(s=>!s.isStd140),o=new Set;for(let s of n){if(o.has(s.blockName))continue;o.add(s.blockName);let a=i?.label?`${i.label} `:"",c=s.hasLayoutQualifier?`declares ${h3(s.layoutQualifier)} instead of layout(std140)`:"does not declare layout(std140)",l=`${a}${e} shader uniform block ${s.blockName} ${c}. luma.gl host-side shader block packing assumes explicit layout(std140) for GLSL uniform blocks. Add \`layout(std140)\` to the block declaration.`;r?.warn?.(l,s)()}return n}function a3(t,e,r){let i=e==="wgsl"?c3(t,r):l3(t,r);if(!i)return null;let n=[];for(let o of i.split(` +`)){let s=o.replace(/\/\/.*$/,"").trim();if(!s||s.startsWith("#"))continue;let a=e==="wgsl"?s.match(/^([A-Za-z0-9_]+)\s*:/):s.match(i3);a&&n.push(a[1])}return n}function c3(t,e){let r=new RegExp(`\\bstruct\\s+${e}\\b`,"m").exec(t);if(!r)return null;let i=t.indexOf("{",r.index);if(i<0)return null;let n=0;for(let o=i;oi.blockName===e)?.body||null}function f3(t,e){if(t.length!==e.length)return!1;for(let r=0;r!r.includes(a)),n=r.filter(a=>!e.includes(a)),o=[`Expected ${e.length} fields, found ${r.length}.`],s=p3(e,r);return s&&o.push(s),i.length&&o.push(`Missing from shader block (${i.length}): ${R0(i)}.`),n.length&&o.push(`Unexpected in shader block (${n.length}): ${R0(n)}.`),e.length<=12&&r.length<=12&&(i.length||n.length)&&(o.push(`Expected: ${e.join(", ")}.`),o.push(`Actual: ${r.join(", ")}.`)),`${t.moduleName}: ${t.stage} shader uniform block ${t.uniformBlockName} does not match module.uniformTypes. ${o.join(" ")}`}function d3(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"")}function h3(t){return t.replace(/\s+/g," ").trim()}function p3(t,e){let r=Math.min(t.length,e.length);for(let i=0;ie.length?`Shader block ends after field ${e.length}; expected next field ${t[e.length]}.`:e.length>t.length?`Shader block has extra field ${e.length}: ${e[t.length]}.`:null}function R0(t,e=8){if(t.length<=e)return t.join(", ");let r=t.length-e;return`${t.slice(0,e).join(", ")}, ... (${r} more)`}function O0(t){switch(t?.gpu.toLowerCase()){case"apple":return`#define APPLE_GPU +// Apple optimizes away the calculation necessary for emulated fp64 +#define LUMA_FP64_CODE_ELIMINATION_WORKAROUND 1 +#define LUMA_FP32_TAN_PRECISION_WORKAROUND 1 +// Intel GPU doesn't have full 32 bits precision in same cases, causes overflow +#define LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND 1 +`;case"nvidia":return`#define NVIDIA_GPU +// Nvidia optimizes away the calculation necessary for emulated fp64 +#define LUMA_FP64_CODE_ELIMINATION_WORKAROUND 1 +`;case"intel":return`#define INTEL_GPU +// Intel optimizes away the calculation necessary for emulated fp64 +#define LUMA_FP64_CODE_ELIMINATION_WORKAROUND 1 +// Intel's built-in 'tan' function doesn't have acceptable precision +#define LUMA_FP32_TAN_PRECISION_WORKAROUND 1 +// Intel GPU doesn't have full 32 bits precision in same cases, causes overflow +#define LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND 1 +`;case"amd":return`#define AMD_GPU +`;default:return`#define DEFAULT_GPU +// Prevent driver from optimizing away the calculation necessary for emulated fp64 +#define LUMA_FP64_CODE_ELIMINATION_WORKAROUND 1 +// Headless Chrome's software shader 'tan' function doesn't have acceptable precision +#define LUMA_FP32_TAN_PRECISION_WORKAROUND 1 +// If the GPU doesn't have full 32 bits precision, will causes overflow +#define LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND 1 +`}}function D0(t,e){if(Number(t.match(/^#version[ \t]+(\d+)/m)?.[1]||100)!==300)throw new Error("luma.gl v9 only supports GLSL 3.00 shader sources");switch(e){case"vertex":return t=N0(t,g3),t;case"fragment":return t=N0(t,m3),t;default:throw new Error(e)}}var L0=[[/^(#version[ \t]+(100|300[ \t]+es))?[ \t]*\n/,`#version 300 es +`],[/\btexture(2D|2DProj|Cube)Lod(EXT)?\(/g,"textureLod("],[/\btexture(2D|2DProj|Cube)(EXT)?\(/g,"texture("]],g3=[...L0,[Rd("attribute"),"in $1"],[Rd("varying"),"out $1"]],m3=[...L0,[Rd("varying"),"in $1"]];function N0(t,e){for(let[r,i]of e)t=t.replace(r,i);return t}function Rd(t){return new RegExp(`\\b${t}[ \\t]+(\\w+[ \\t]+\\w+(\\[\\w+\\])?;)`,"g")}function Cd(t,e){let r="";for(let i in t){let n=t[i];if(r+=`void ${n.signature} { +`,n.header&&(r+=` ${n.header}`),e[i]){let o=e[i];o.sort((s,a)=>s.order-a.order);for(let s of o)r+=` ${s.injection} +`}n.footer&&(r+=` ${n.footer}`),r+=`} +`}return r}function Pd(t){let e={vertex:{},fragment:{}};for(let r of t){let i,n;typeof r!="string"?(i=r,n=i.hook):(i={},n=r),n=n.trim();let[o,s]=n.split(":"),a=n.replace(/\(.+/,""),c=Object.assign(i,{signature:s});switch(o){case"vs":e.vertex[a]=c;break;case"fs":e.fragment[a]=c;break;default:throw new Error(o)}}return e}function F0(t,e){return{name:_3(t,e),language:"glsl",version:y3(t)}}function _3(t,e="unnamed"){let i=/#define[^\S\r\n]*SHADER_NAME[^\S\r\n]*([A-Za-z0-9_-]+)\s*/.exec(t);return i?i[1]:e}function y3(t){let e=100,r=t.match(/[^\s]+/g);if(r&&r.length>=2&&r[0]==="#version"){let i=parseInt(r[1],10);Number.isFinite(i)&&(e=i)}if(e!==100&&e!==300)throw new Error(`Invalid GLSL version ${e}`);return e}var Ke="(?:var<\\s*(uniform|storage(?:\\s*,\\s*[A-Za-z_][A-Za-z0-9_]*)?)\\s*>|var)\\s+([A-Za-z_][A-Za-z0-9_]*)";var cn=[new RegExp(`@binding\\(\\s*(auto|\\d+)\\s*\\)\\s*@group\\(\\s*(\\d+)\\s*\\)\\s*${Ke}`,"g"),new RegExp(`@group\\(\\s*(\\d+)\\s*\\)\\s*@binding\\(\\s*(auto|\\d+)\\s*\\)\\s*${Ke}`,"g")],_c=[new RegExp(`@binding\\(\\s*(auto|\\d+)\\s*\\)\\s*@group\\(\\s*(\\d+)\\s*\\)\\s*${Ke}`,"g"),new RegExp(`@group\\(\\s*(\\d+)\\s*\\)\\s*@binding\\(\\s*(auto|\\d+)\\s*\\)\\s*${Ke}`,"g")],B0=[new RegExp(`@binding\\(\\s*(\\d+)\\s*\\)\\s*@group\\(\\s*(\\d+)\\s*\\)\\s*${Ke}`,"g"),new RegExp(`@group\\(\\s*(\\d+)\\s*\\)\\s*@binding\\(\\s*(\\d+)\\s*\\)\\s*${Ke}`,"g")],x3=[new RegExp(`@binding\\(\\s*(auto)\\s*\\)\\s*@group\\(\\s*(\\d+)\\s*\\)\\s*${Ke}`,"g"),new RegExp(`@group\\(\\s*(\\d+)\\s*\\)\\s*@binding\\(\\s*(auto)\\s*\\)\\s*${Ke}`,"g"),new RegExp(`@binding\\(\\s*(auto)\\s*\\)\\s*@group\\(\\s*(\\d+)\\s*\\)(?:[\\s\\n\\r]*@[A-Za-z_][^\\n\\r]*)*[\\s\\n\\r]*${Ke}`,"g"),new RegExp(`@group\\(\\s*(\\d+)\\s*\\)\\s*@binding\\(\\s*(auto)\\s*\\)(?:[\\s\\n\\r]*@[A-Za-z_][^\\n\\r]*)*[\\s\\n\\r]*${Ke}`,"g")];function yc(t){let e=t.split(""),r=0,i=0,n=!1,o=!1,s=!1;for(;r0){if(a==="/"&&c==="*"){e[r]=" ",e[r+1]=" ",i++,r+=2;continue}if(a==="*"&&c==="/"){e[r]=" ",e[r+1]=" ",i--,r+=2;continue}a!==` +`&&a!=="\r"&&(e[r]=" "),r++;continue}if(a==='"'){o=!0,r++;continue}if(a==="/"&&c==="/"){e[r]=" ",e[r+1]=" ",n=!0,r+=2;continue}if(a==="/"&&c==="*"){e[r]=" ",e[r+1]=" ",i=1,r+=2;continue}r++}return e.join("")}function fi(t,e){let r=yc(t),i=[];for(let n of e){n.lastIndex=0;let o;for(o=n.exec(r);o;){let s=n===e[0],a=o.index,c=o[0].length;i.push({match:t.slice(a,a+c),index:a,length:c,bindingToken:o[s?1:2],groupToken:o[s?2:1],accessDeclaration:o[3]?.trim(),name:o[4]}),o=n.exec(r)}}return i.sort((n,o)=>n.index-o.index)}function Md(t,e,r){let i=fi(t,e);if(!i.length)return t;let n="",o=0;for(let s of i)n+=t.slice(o,s.index),n+=r(s),o=s.index+s.length;return n+=t.slice(o),n}function Id(t){return/@binding\(\s*auto\s*\)/.test(yc(t))}function k0(t,e){return fi(t,e===cn||e===_c?x3:e).find(i=>i.bindingToken==="auto")}var U0=[new RegExp(`@binding\\(\\s*(\\d+)\\s*\\)\\s*@group\\(\\s*(\\d+)\\s*\\)\\s*${Ke}\\s*:\\s*([^;]+);`,"g"),new RegExp(`@group\\(\\s*(\\d+)\\s*\\)\\s*@binding\\(\\s*(\\d+)\\s*\\)\\s*${Ke}\\s*:\\s*([^;]+);`,"g")];function xc(t,e=[]){let r=yc(t),i=new Map;for(let o of e)i.set(z0(o.name,o.group,o.location),o.moduleName);let n=[];for(let o of U0){o.lastIndex=0;let s;for(s=o.exec(r);s;){let a=o===U0[0],c=Number(s[a?1:2]),l=Number(s[a?2:1]),f=s[3]?.trim(),u=s[4],d=s[5].trim(),h=i.get(z0(u,l,c));n.push(b3({name:u,group:l,binding:c,owner:h?"module":"application",moduleName:h,accessDeclaration:f,resourceType:d})),s=o.exec(r)}}return n.sort((o,s)=>o.group!==s.group?o.group-s.group:o.binding!==s.binding?o.binding-s.binding:o.name.localeCompare(s.name))}function b3(t){let e={name:t.name,group:t.group,binding:t.binding,owner:t.owner,kind:"unknown",moduleName:t.moduleName,resourceType:t.resourceType};if(t.accessDeclaration){let r=t.accessDeclaration.split(",").map(i=>i.trim());if(r[0]==="uniform")return{...e,kind:"uniform",access:"uniform"};if(r[0]==="storage"){let i=r[1]||"read_write";return{...e,kind:i==="read"?"read-only-storage":"storage",access:i}}}return t.resourceType==="sampler"||t.resourceType==="sampler_comparison"?{...e,kind:"sampler",samplerKind:t.resourceType==="sampler_comparison"?"comparison":"filtering"}:t.resourceType.startsWith("texture_storage_")?{...e,kind:"storage-texture",access:w3(t.resourceType),viewDimension:W0(t.resourceType)}:t.resourceType.startsWith("texture_")?{...e,kind:"texture",viewDimension:W0(t.resourceType),sampleType:T3(t.resourceType),multisampled:t.resourceType.startsWith("texture_multisampled_")}:e}function z0(t,e,r){return`${e}:${r}:${t}`}function W0(t){if(t.includes("cube_array"))return"cube-array";if(t.includes("2d_array"))return"2d-array";if(t.includes("cube"))return"cube";if(t.includes("3d"))return"3d";if(t.includes("2d"))return"2d";if(t.includes("1d"))return"1d"}function T3(t){if(t.startsWith("texture_depth_"))return"depth";if(t.includes(""))return"sint";if(t.includes(""))return"uint";if(t.includes(""))return"float"}function w3(t){return/,\s*([A-Za-z_][A-Za-z0-9_]*)\s*>$/.exec(t)?.[1]}var Od=` + +${Ao} +`,Eo=100,S3=`precision highp float; +`;function H0(t){let e=an(t.modules||[]),{source:r,bindingAssignments:i}=A3(t.platformInfo,{...t,source:t.source,stage:"vertex",modules:e});return{source:r,getUniforms:X0(e),bindingAssignments:i,bindingTable:xc(r,i)}}function Y0(t){let{vs:e,fs:r}=t,i=an(t.modules||[]);return{vs:V0(t.platformInfo,{...t,source:e,stage:"vertex",modules:i}),fs:V0(t.platformInfo,{...t,source:r,stage:"fragment",modules:i}),getUniforms:X0(i)}}function A3(t,e){let{source:r,stage:i,modules:n,hookFunctions:o=[],inject:s={},log:a}=e;li(typeof r=="string","shader source must be a string");let c=r,l="",f=Pd(o),u={},d={},h={};for(let y in s){let x=typeof s[y]=="string"?{injection:s[y],order:0}:s[y],w=/^(v|f)s:(#)?([\w-]+)$/.exec(y);if(w){let b=w[2],E=w[3];b?E==="decl"?d[y]=[x]:h[y]=[x]:u[y]=[x]}else h[y]=[x]}let p=n,g=R3(c),m=E3(g.source),_=I3(p,e._bindingRegistry,m),T=[];for(let y of p){a&&Ed(y,c,a);let x=C3(G0(y,"wgsl",a),y,{usedBindingsByGroup:m,bindingRegistry:e._bindingRegistry,reservedBindingKeysByGroup:_});T.push(...x.bindingAssignments);let w=x.source;l+=w;let b=y.injections?.[i]||{};for(let E in b){let S=/^(v|f)s:#([\w-]+)$/.exec(E);if(S){let C=S[2]==="decl"?d:h;C[E]=C[E]||[],C[E].push(b[E])}else u[E]=u[E]||[],u[E].push(b[E])}}return l+=Od,l=vo(l,i,d),l+=Cd(f[i],u),l+=F3(T),l+=g.source,l=vo(l,i,h),L3(l),{source:l,bindingAssignments:T}}function V0(t,e){let{source:r,stage:i,language:n="glsl",modules:o,defines:s={},hookFunctions:a=[],inject:c={},prologue:l=!0,log:f}=e;li(typeof r=="string","shader source must be a string");let u=n==="glsl"?F0(r).version:-1,d=t.shaderLanguageVersion,h=u===100?"#version 100":"#version 300 es",g=r.split(` +`).slice(1).join(` +`),m={};o.forEach(b=>{Object.assign(m,b.defines)}),Object.assign(m,s);let _="";switch(n){case"wgsl":break;case"glsl":_=l?`${h} + +// ----- PROLOGUE ------------------------- +${`#define SHADER_TYPE_${i.toUpperCase()}`} + +${O0(t)} +${i==="fragment"?S3:""} + +// ----- APPLICATION DEFINES ------------------------- + +${v3(m)} + +`:`${h} +`;break}let T=Pd(a),y={},x={},w={};for(let b in c){let E=typeof c[b]=="string"?{injection:c[b],order:0}:c[b],S=/^(v|f)s:(#)?([\w-]+)$/.exec(b);if(S){let A=S[2],C=S[3];A?C==="decl"?x[b]=[E]:w[b]=[E]:y[b]=[E]}else w[b]=[E]}for(let b of o){f&&Ed(b,g,f);let E=G0(b,i,f);_+=E;let S=b.instance?.normalizedInjections[i]||{};for(let A in S){let C=/^(v|f)s:#([\w-]+)$/.exec(A);if(C){let R=C[2]==="decl"?x:w;R[A]=R[A]||[],R[A].push(S[A])}else y[A]=y[A]||[],y[A].push(S[A])}}return _+="// ----- MAIN SHADER SOURCE -------------------------",_+=Od,_=vo(_,i,x),_+=Cd(T[i],y),_+=g,_=vo(_,i,w),n==="glsl"&&u!==d&&(_=D0(_,i)),n==="glsl"&&I0(_,i,f),_.trim()}function X0(t){return function(r){let i={};for(let n of t){let o=n.getUniforms?.(r,i);Object.assign(i,o)}return i}}function v3(t={}){let e="";for(let r in t){let i=t[r];(i||Number.isFinite(i))&&(e+=`#define ${r.toUpperCase()} ${t[r]} +`)}return e}function G0(t,e,r){let i;switch(e){case"vertex":i=t.vs||"";break;case"fragment":i=t.fs||"";break;case"wgsl":i=t.source||"";break;default:li(!1)}if(!t.name)throw new Error("Shader module must have a name");P0(t,e,{log:r});let n=t.name.toUpperCase().replace(/[^0-9a-z]/gi,"_"),o=`// ----- MODULE ${t.name} --------------- + +`;return e!=="wgsl"&&(o+=`#define MODULE_${n} +`),o+=`${i} +`,o}function E3(t){let e=new Map;for(let r of fi(t,B0)){let i=Number(r.bindingToken),n=Number(r.groupToken);Nd(n,i,r.name),ln(e,n,i,`application binding "${r.name}"`)}return e}function R3(t){let e=fi(t,_c),r=new Map;for(let o of e){if(o.bindingToken==="auto")continue;let s=Number(o.bindingToken),a=Number(o.groupToken);Nd(a,s,o.name),ln(r,a,s,`application binding "${o.name}"`)}let i={sawSupportedBindingDeclaration:e.length>0},n=Md(t,_c,o=>M3(o,r,i));if(Id(t)&&!i.sawSupportedBindingDeclaration)throw new Error('Unsupported @binding(auto) declaration form in application WGSL. Use adjacent "@group(N)" and "@binding(auto)" decorators followed by a bindable "var" declaration.');return{source:n}}function C3(t,e,r){let i=[],o={sawSupportedBindingDeclaration:fi(t,cn).length>0,nextHintedBindingLocation:typeof e.firstBindingSlot=="number"?e.firstBindingSlot:null},s=Md(t,cn,a=>P3(a,{module:e,context:r,bindingAssignments:i,relocationState:o}));if(Id(t)&&!o.sawSupportedBindingDeclaration)throw new Error(`Unsupported @binding(auto) declaration form in module "${e.name}". Use adjacent "@group(N)" and "@binding(auto)" decorators followed by a bindable "var" declaration.`);return{source:s,bindingAssignments:i}}function P3(t,e){let{module:r,context:i,bindingAssignments:n,relocationState:o}=e,{match:s,bindingToken:a,groupToken:c,name:l}=t,f=Number(c);if(a==="auto"){let d=q0(f,r.name,l),h=i.bindingRegistry?.get(d),p=h!==void 0?h:o.nextHintedBindingLocation===null?$0(f,i.usedBindingsByGroup):$0(f,i.usedBindingsByGroup,o.nextHintedBindingLocation);return j0(r.name,f,p,l),h!==void 0&&O3(i.reservedBindingKeysByGroup,f,p,d)?(n.push({moduleName:r.name,name:l,group:f,location:p}),s.replace(/@binding\(\s*auto\s*\)/,`@binding(${p})`)):(ln(i.usedBindingsByGroup,f,p,`module "${r.name}" binding "${l}"`),i.bindingRegistry?.set(d,p),n.push({moduleName:r.name,name:l,group:f,location:p}),o.nextHintedBindingLocation!==null&&h===void 0&&(o.nextHintedBindingLocation=p+1),s.replace(/@binding\(\s*auto\s*\)/,`@binding(${p})`))}let u=Number(a);return j0(r.name,f,u,l),ln(i.usedBindingsByGroup,f,u,`module "${r.name}" binding "${l}"`),n.push({moduleName:r.name,name:l,group:f,location:u}),s}function M3(t,e,r){let{match:i,bindingToken:n,groupToken:o,name:s}=t,a=Number(o);if(n==="auto"){let c=D3(a,e);return Nd(a,c,s),ln(e,a,c,`application binding "${s}"`),i.replace(/@binding\(\s*auto\s*\)/,`@binding(${c})`)}return r.sawSupportedBindingDeclaration=!0,i}function I3(t,e,r){let i=new Map;if(!e)return i;for(let n of t)for(let o of N3(n)){let s=q0(o.group,n.name,o.name),a=e.get(s);if(a!==void 0){let c=i.get(o.group)||new Map,l=c.get(a);if(l&&l!==s)throw new Error(`Duplicate WGSL binding reservation for modules "${l}" and "${s}": group ${o.group}, binding ${a}.`);ln(r,o.group,a,`registered module binding "${s}"`),c.set(a,s),i.set(o.group,c)}}return i}function O3(t,e,r,i){let n=t.get(e);if(!n)return!1;let o=n.get(r);if(!o)return!1;if(o!==i)throw new Error(`Registered module binding "${i}" collided with "${o}": group ${e}, binding ${r}.`);return!0}function N3(t){let e=[],r=t.source||"";for(let i of fi(r,cn))e.push({name:i.name,group:Number(i.groupToken)});return e}function Nd(t,e,r){if(t===0&&e>=Eo)throw new Error(`Application binding "${r}" in group 0 uses reserved binding ${e}. Application-owned explicit group-0 bindings must stay below ${Eo}.`)}function j0(t,e,r,i){if(e===0&&r0?Math.max(...i)+1:0);for(;i.has(n);)n++;return n}function D3(t,e){let r=e.get(t)||new Set,i=0;for(;r.has(i);)i++;return i}function L3(t){let e=k0(t,cn);if(!e)return;let r=B3(t,e.index);throw r?new Error(`Unresolved @binding(auto) for module "${r}" binding "${e.name}" remained in assembled WGSL source.`):k3(t,e.index)?new Error(`Unresolved @binding(auto) for application binding "${e.name}" remained in assembled WGSL source.`):new Error(`Unresolved @binding(auto) remained in assembled WGSL source near "${U3(e.match)}".`)}function F3(t){if(t.length===0)return"";let e=`// ----- MODULE WGSL BINDING ASSIGNMENTS --------------- +`;for(let r of t)e+=`// ${r.moduleName}.${r.name} -> @group(${r.group}) @binding(${r.location}) +`;return e+=` +`,e}function q0(t,e,r){return`${t}:${e}:${r}`}function B3(t,e){let r=/^\/\/ ----- MODULE ([^\n]+) ---------------$/gm,i,n;for(n=r.exec(t);n&&n.index<=e;)i=n[1],n=r.exec(t);return i}function k3(t,e){let r=t.indexOf(Od);return r>=0?e>r:!0}function U3(t){return t.replace(/\s+/g," ").trim()}var Dd="([a-zA-Z_][a-zA-Z0-9_]*)",z3=new RegExp(`^\\s*\\#\\s*ifdef\\s*${Dd}\\s*$`),W3=new RegExp(`^\\s*\\#\\s*ifndef\\s*${Dd}\\s*(?:\\/\\/.*)?$`),V3=/^\s*\#\s*else\s*(?:\/\/.*)?$/,j3=/^\s*\#\s*endif\s*$/,$3=new RegExp(`^\\s*\\#\\s*ifdef\\s*${Dd}\\s*(?:\\/\\/.*)?$`),H3=/^\s*\#\s*endif\s*(?:\/\/.*)?$/;function K0(t,e){let r=t.split(` +`),i=[],n=[],o=!0;for(let s of r){let a=s.match($3)||s.match(z3),c=s.match(W3),l=s.match(V3),f=s.match(H3)||s.match(j3);if(a||c){let u=(a||c)?.[1],d=!!e?.defines?.[u],h=a?d:!d,p=o&&h;n.push({parentActive:o,branchTaken:h,active:p}),o=p}else if(l){let u=n[n.length-1];if(!u)throw new Error("Encountered #else without matching #ifdef or #ifndef");u.active=u.parentActive&&!u.branchTaken,u.branchTaken=!0,o=u.active}else f?(n.pop(),o=n.length?n[n.length-1].active:!0):o&&i.push(s)}if(n.length>0)throw new Error("Unterminated conditional block in shader source");return i.join(` +`)}var ui=class t{static defaultShaderAssembler;_hookFunctions=[];_defaultModules=[];_wgslBindingRegistry=new Map;static getDefaultShaderAssembler(){return t.defaultShaderAssembler=t.defaultShaderAssembler||new t,t.defaultShaderAssembler}addDefaultModule(e){this._defaultModules.find(r=>r.name===(typeof e=="string"?e:e.name))||this._defaultModules.push(e)}removeDefaultModule(e){let r=typeof e=="string"?e:e.name;this._defaultModules=this._defaultModules.filter(i=>i.name!==r)}addShaderHook(e,r){r&&(e=Object.assign(r,{hook:e})),this._hookFunctions.push(e)}assembleWGSLShader(e){let r=this._getModuleList(e.modules),i=this._hookFunctions,{source:n,getUniforms:o,bindingAssignments:s}=H0({...e,source:e.source,_bindingRegistry:this._wgslBindingRegistry,modules:r,hookFunctions:i}),a={...r.reduce((l,f)=>(Object.assign(l,f.defines),l),{}),...e.defines},c=e.platformInfo.shaderLanguage==="wgsl"?K0(n,{defines:a}):n;return{source:c,getUniforms:o,modules:r,bindingAssignments:s,bindingTable:xc(c,s)}}assembleGLSLShaderPair(e){let r=this._getModuleList(e.modules),i=this._hookFunctions;return{...Y0({...e,vs:e.vs,fs:e.fs,modules:r,hookFunctions:i}),modules:r}}_getModuleList(e=[]){let r=new Array(this._defaultModules.length+e.length),i={},n=0;for(let o=0,s=this._defaultModules.length;oMath.max(e,Math.min(r,i)))}function di(t,e,r){return ir(t)?t.map((i,n)=>di(i,e[n],r)):r*e+(1-r)*t}function nr(t,e,r){let i=ye.EPSILON;r&&(ye.EPSILON=r);try{if(t===e)return!0;if(ir(t)&&ir(e)){if(t.length!==e.length)return!1;for(let n=0;n0?", ":"")+Fd(this[i],e);return`${e.printTypes?this.constructor.name:""}[${r}]`}equals(e){if(!e||this.length!==e.length)return!1;for(let r=0;r=0&&e=0&&enR,angle:()=>SR,ceil:()=>oR,clone:()=>eR,copy:()=>rR,create:()=>Q0,cross:()=>mR,dist:()=>OR,distance:()=>ry,div:()=>IR,divide:()=>ty,dot:()=>gR,equals:()=>RR,exactEquals:()=>ER,floor:()=>sR,forEach:()=>LR,fromValues:()=>tR,inverse:()=>hR,len:()=>CR,length:()=>ny,lerp:()=>_R,max:()=>cR,min:()=>aR,mul:()=>MR,multiply:()=>ey,negate:()=>dR,normalize:()=>pR,random:()=>yR,rotate:()=>wR,round:()=>lR,scale:()=>fR,scaleAndAdd:()=>uR,set:()=>iR,sqrDist:()=>NR,sqrLen:()=>DR,squaredDistance:()=>iy,squaredLength:()=>oy,str:()=>vR,sub:()=>PR,subtract:()=>J0,transformMat2:()=>xR,transformMat2d:()=>bR,transformMat3:()=>TR,transformMat4:()=>kd,zero:()=>AR});var le=typeof Float32Array<"u"?Float32Array:Array,Nt=Math.random;function nt(t){return t>=0?Math.round(t):t%.5===0?Math.floor(t):Math.round(t)}var L9=Math.PI/180;function Q0(){let t=new le(2);return le!=Float32Array&&(t[0]=0,t[1]=0),t}function eR(t){let e=new le(2);return e[0]=t[0],e[1]=t[1],e}function tR(t,e){let r=new le(2);return r[0]=t,r[1]=e,r}function rR(t,e){return t[0]=e[0],t[1]=e[1],t}function iR(t,e,r){return t[0]=e,t[1]=r,t}function nR(t,e,r){return t[0]=e[0]+r[0],t[1]=e[1]+r[1],t}function J0(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t}function ey(t,e,r){return t[0]=e[0]*r[0],t[1]=e[1]*r[1],t}function ty(t,e,r){return t[0]=e[0]/r[0],t[1]=e[1]/r[1],t}function oR(t,e){return t[0]=Math.ceil(e[0]),t[1]=Math.ceil(e[1]),t}function sR(t,e){return t[0]=Math.floor(e[0]),t[1]=Math.floor(e[1]),t}function aR(t,e,r){return t[0]=Math.min(e[0],r[0]),t[1]=Math.min(e[1],r[1]),t}function cR(t,e,r){return t[0]=Math.max(e[0],r[0]),t[1]=Math.max(e[1],r[1]),t}function lR(t,e){return t[0]=nt(e[0]),t[1]=nt(e[1]),t}function fR(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t}function uR(t,e,r,i){return t[0]=e[0]+r[0]*i,t[1]=e[1]+r[1]*i,t}function ry(t,e){let r=e[0]-t[0],i=e[1]-t[1];return Math.sqrt(r*r+i*i)}function iy(t,e){let r=e[0]-t[0],i=e[1]-t[1];return r*r+i*i}function ny(t){let e=t[0],r=t[1];return Math.sqrt(e*e+r*r)}function oy(t){let e=t[0],r=t[1];return e*e+r*r}function dR(t,e){return t[0]=-e[0],t[1]=-e[1],t}function hR(t,e){return t[0]=1/e[0],t[1]=1/e[1],t}function pR(t,e){let r=e[0],i=e[1],n=r*r+i*i;return n>0&&(n=1/Math.sqrt(n)),t[0]=e[0]*n,t[1]=e[1]*n,t}function gR(t,e){return t[0]*e[0]+t[1]*e[1]}function mR(t,e,r){let i=e[0]*r[1]-e[1]*r[0];return t[0]=t[1]=0,t[2]=i,t}function _R(t,e,r,i){let n=e[0],o=e[1];return t[0]=n+i*(r[0]-n),t[1]=o+i*(r[1]-o),t}function yR(t,e){e=e===void 0?1:e;let r=Nt()*2*Math.PI;return t[0]=Math.cos(r)*e,t[1]=Math.sin(r)*e,t}function xR(t,e,r){let i=e[0],n=e[1];return t[0]=r[0]*i+r[2]*n,t[1]=r[1]*i+r[3]*n,t}function bR(t,e,r){let i=e[0],n=e[1];return t[0]=r[0]*i+r[2]*n+r[4],t[1]=r[1]*i+r[3]*n+r[5],t}function TR(t,e,r){let i=e[0],n=e[1];return t[0]=r[0]*i+r[3]*n+r[6],t[1]=r[1]*i+r[4]*n+r[7],t}function kd(t,e,r){let i=e[0],n=e[1];return t[0]=r[0]*i+r[4]*n+r[12],t[1]=r[1]*i+r[5]*n+r[13],t}function wR(t,e,r,i){let n=e[0]-r[0],o=e[1]-r[1],s=Math.sin(i),a=Math.cos(i);return t[0]=n*a-o*s+r[0],t[1]=n*s+o*a+r[1],t}function SR(t,e){let r=t[0],i=t[1],n=e[0],o=e[1],s=Math.sqrt((r*r+i*i)*(n*n+o*o)),a=s&&(r*n+i*o)/s;return Math.acos(Math.min(Math.max(a,-1),1))}function AR(t){return t[0]=0,t[1]=0,t}function vR(t){return`vec2(${t[0]}, ${t[1]})`}function ER(t,e){return t[0]===e[0]&&t[1]===e[1]}function RR(t,e){let r=t[0],i=t[1],n=e[0],o=e[1];return Math.abs(r-n)<=1e-6*Math.max(1,Math.abs(r),Math.abs(n))&&Math.abs(i-o)<=1e-6*Math.max(1,Math.abs(i),Math.abs(o))}var CR=ny,PR=J0,MR=ey,IR=ty,OR=ry,NR=iy,DR=oy,LR=(function(){let t=Q0();return function(e,r,i,n,o,s){let a,c;for(r||(r=2),i||(i=0),n?c=Math.min(n*r+i,e.length):c=e.length,a=i;azR,angle:()=>Yd,bezier:()=>eC,ceil:()=>WR,clone:()=>FR,copy:()=>kR,create:()=>cy,cross:()=>zd,dist:()=>lC,distance:()=>hy,div:()=>cC,divide:()=>dy,dot:()=>Ud,equals:()=>oC,exactEquals:()=>nC,floor:()=>VR,forEach:()=>hC,fromValues:()=>BR,hermite:()=>JR,inverse:()=>qR,len:()=>uC,length:()=>ly,lerp:()=>ZR,max:()=>$R,min:()=>jR,mul:()=>aC,multiply:()=>uy,negate:()=>GR,normalize:()=>KR,random:()=>tC,rotateX:()=>jd,rotateY:()=>$d,rotateZ:()=>Hd,round:()=>HR,scale:()=>YR,scaleAndAdd:()=>XR,set:()=>UR,slerp:()=>QR,sqrDist:()=>fC,sqrLen:()=>dC,squaredDistance:()=>py,squaredLength:()=>gy,str:()=>iC,sub:()=>sC,subtract:()=>fy,transformMat3:()=>Wd,transformMat4:()=>Ro,transformQuat:()=>Vd,zero:()=>rC});function cy(){let t=new le(3);return le!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0),t}function FR(t){let e=new le(3);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e}function ly(t){let e=t[0],r=t[1],i=t[2];return Math.sqrt(e*e+r*r+i*i)}function BR(t,e,r){let i=new le(3);return i[0]=t,i[1]=e,i[2]=r,i}function kR(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t}function UR(t,e,r,i){return t[0]=e,t[1]=r,t[2]=i,t}function zR(t,e,r){return t[0]=e[0]+r[0],t[1]=e[1]+r[1],t[2]=e[2]+r[2],t}function fy(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t}function uy(t,e,r){return t[0]=e[0]*r[0],t[1]=e[1]*r[1],t[2]=e[2]*r[2],t}function dy(t,e,r){return t[0]=e[0]/r[0],t[1]=e[1]/r[1],t[2]=e[2]/r[2],t}function WR(t,e){return t[0]=Math.ceil(e[0]),t[1]=Math.ceil(e[1]),t[2]=Math.ceil(e[2]),t}function VR(t,e){return t[0]=Math.floor(e[0]),t[1]=Math.floor(e[1]),t[2]=Math.floor(e[2]),t}function jR(t,e,r){return t[0]=Math.min(e[0],r[0]),t[1]=Math.min(e[1],r[1]),t[2]=Math.min(e[2],r[2]),t}function $R(t,e,r){return t[0]=Math.max(e[0],r[0]),t[1]=Math.max(e[1],r[1]),t[2]=Math.max(e[2],r[2]),t}function HR(t,e){return t[0]=nt(e[0]),t[1]=nt(e[1]),t[2]=nt(e[2]),t}function YR(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t}function XR(t,e,r,i){return t[0]=e[0]+r[0]*i,t[1]=e[1]+r[1]*i,t[2]=e[2]+r[2]*i,t}function hy(t,e){let r=e[0]-t[0],i=e[1]-t[1],n=e[2]-t[2];return Math.sqrt(r*r+i*i+n*n)}function py(t,e){let r=e[0]-t[0],i=e[1]-t[1],n=e[2]-t[2];return r*r+i*i+n*n}function gy(t){let e=t[0],r=t[1],i=t[2];return e*e+r*r+i*i}function GR(t,e){return t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t}function qR(t,e){return t[0]=1/e[0],t[1]=1/e[1],t[2]=1/e[2],t}function KR(t,e){let r=e[0],i=e[1],n=e[2],o=r*r+i*i+n*n;return o>0&&(o=1/Math.sqrt(o)),t[0]=e[0]*o,t[1]=e[1]*o,t[2]=e[2]*o,t}function Ud(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function zd(t,e,r){let i=e[0],n=e[1],o=e[2],s=r[0],a=r[1],c=r[2];return t[0]=n*c-o*a,t[1]=o*s-i*c,t[2]=i*a-n*s,t}function ZR(t,e,r,i){let n=e[0],o=e[1],s=e[2];return t[0]=n+i*(r[0]-n),t[1]=o+i*(r[1]-o),t[2]=s+i*(r[2]-s),t}function QR(t,e,r,i){let n=Math.acos(Math.min(Math.max(Ud(e,r),-1),1)),o=Math.sin(n),s=Math.sin((1-i)*n)/o,a=Math.sin(i*n)/o;return t[0]=s*e[0]+a*r[0],t[1]=s*e[1]+a*r[1],t[2]=s*e[2]+a*r[2],t}function JR(t,e,r,i,n,o){let s=o*o,a=s*(2*o-3)+1,c=s*(o-2)+o,l=s*(o-1),f=s*(3-2*o);return t[0]=e[0]*a+r[0]*c+i[0]*l+n[0]*f,t[1]=e[1]*a+r[1]*c+i[1]*l+n[1]*f,t[2]=e[2]*a+r[2]*c+i[2]*l+n[2]*f,t}function eC(t,e,r,i,n,o){let s=1-o,a=s*s,c=o*o,l=a*s,f=3*o*a,u=3*c*s,d=c*o;return t[0]=e[0]*l+r[0]*f+i[0]*u+n[0]*d,t[1]=e[1]*l+r[1]*f+i[1]*u+n[1]*d,t[2]=e[2]*l+r[2]*f+i[2]*u+n[2]*d,t}function tC(t,e){e=e===void 0?1:e;let r=Nt()*2*Math.PI,i=Nt()*2-1,n=Math.sqrt(1-i*i)*e;return t[0]=Math.cos(r)*n,t[1]=Math.sin(r)*n,t[2]=i*e,t}function Ro(t,e,r){let i=e[0],n=e[1],o=e[2],s=r[3]*i+r[7]*n+r[11]*o+r[15];return s=s||1,t[0]=(r[0]*i+r[4]*n+r[8]*o+r[12])/s,t[1]=(r[1]*i+r[5]*n+r[9]*o+r[13])/s,t[2]=(r[2]*i+r[6]*n+r[10]*o+r[14])/s,t}function Wd(t,e,r){let i=e[0],n=e[1],o=e[2];return t[0]=i*r[0]+n*r[3]+o*r[6],t[1]=i*r[1]+n*r[4]+o*r[7],t[2]=i*r[2]+n*r[5]+o*r[8],t}function Vd(t,e,r){let i=r[0],n=r[1],o=r[2],s=r[3],a=e[0],c=e[1],l=e[2],f=n*l-o*c,u=o*a-i*l,d=i*c-n*a,h=n*d-o*u,p=o*f-i*d,g=i*u-n*f,m=s*2;return f*=m,u*=m,d*=m,h*=2,p*=2,g*=2,t[0]=a+f+h,t[1]=c+u+p,t[2]=l+d+g,t}function jd(t,e,r,i){let n=[],o=[];return n[0]=e[0]-r[0],n[1]=e[1]-r[1],n[2]=e[2]-r[2],o[0]=n[0],o[1]=n[1]*Math.cos(i)-n[2]*Math.sin(i),o[2]=n[1]*Math.sin(i)+n[2]*Math.cos(i),t[0]=o[0]+r[0],t[1]=o[1]+r[1],t[2]=o[2]+r[2],t}function $d(t,e,r,i){let n=[],o=[];return n[0]=e[0]-r[0],n[1]=e[1]-r[1],n[2]=e[2]-r[2],o[0]=n[2]*Math.sin(i)+n[0]*Math.cos(i),o[1]=n[1],o[2]=n[2]*Math.cos(i)-n[0]*Math.sin(i),t[0]=o[0]+r[0],t[1]=o[1]+r[1],t[2]=o[2]+r[2],t}function Hd(t,e,r,i){let n=[],o=[];return n[0]=e[0]-r[0],n[1]=e[1]-r[1],n[2]=e[2]-r[2],o[0]=n[0]*Math.cos(i)-n[1]*Math.sin(i),o[1]=n[0]*Math.sin(i)+n[1]*Math.cos(i),o[2]=n[2],t[0]=o[0]+r[0],t[1]=o[1]+r[1],t[2]=o[2]+r[2],t}function Yd(t,e){let r=t[0],i=t[1],n=t[2],o=e[0],s=e[1],a=e[2],c=Math.sqrt((r*r+i*i+n*n)*(o*o+s*s+a*a)),l=c&&Ud(t,e)/c;return Math.acos(Math.min(Math.max(l,-1),1))}function rC(t){return t[0]=0,t[1]=0,t[2]=0,t}function iC(t){return`vec3(${t[0]}, ${t[1]}, ${t[2]})`}function nC(t,e){return t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]}function oC(t,e){let r=t[0],i=t[1],n=t[2],o=e[0],s=e[1],a=e[2];return Math.abs(r-o)<=1e-6*Math.max(1,Math.abs(r),Math.abs(o))&&Math.abs(i-s)<=1e-6*Math.max(1,Math.abs(i),Math.abs(s))&&Math.abs(n-a)<=1e-6*Math.max(1,Math.abs(n),Math.abs(a))}var sC=fy,aC=uy,cC=dy,lC=hy,fC=py,uC=ly,dC=gy,hC=(function(){let t=cy();return function(e,r,i,n,o,s){let a,c;for(r||(r=3),i||(i=0),n?c=Math.min(n*r+i,e.length):c=e.length,a=i;akC,adjoint:()=>xC,clone:()=>gC,copy:()=>mC,create:()=>pC,decompose:()=>PC,determinant:()=>Kd,equals:()=>VC,exactEquals:()=>WC,frob:()=>BC,fromQuat:()=>ih,fromQuat2:()=>EC,fromRotation:()=>wC,fromRotationTranslation:()=>_y,fromRotationTranslationScale:()=>MC,fromRotationTranslationScaleOrigin:()=>IC,fromScaling:()=>TC,fromTranslation:()=>bC,fromValues:()=>_C,fromXRotation:()=>SC,fromYRotation:()=>AC,fromZRotation:()=>vC,frustum:()=>nh,getRotation:()=>CC,getScaling:()=>yy,getTranslation:()=>RC,identity:()=>my,invert:()=>qd,lookAt:()=>ah,mul:()=>jC,multiply:()=>Co,multiplyScalar:()=>UC,multiplyScalarAndAdd:()=>zC,ortho:()=>sh,orthoNO:()=>by,orthoZO:()=>DC,perspective:()=>oh,perspectiveFromFieldOfView:()=>NC,perspectiveNO:()=>xy,perspectiveZO:()=>OC,rotate:()=>Jd,rotateX:()=>eh,rotateY:()=>th,rotateZ:()=>rh,scale:()=>Qd,set:()=>yC,str:()=>FC,sub:()=>$C,subtract:()=>Ty,targetTo:()=>LC,translate:()=>Zd,transpose:()=>Gd});function pC(){let t=new le(16);return le!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t}function gC(t){let e=new le(16);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e}function mC(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t}function _C(t,e,r,i,n,o,s,a,c,l,f,u,d,h,p,g){let m=new le(16);return m[0]=t,m[1]=e,m[2]=r,m[3]=i,m[4]=n,m[5]=o,m[6]=s,m[7]=a,m[8]=c,m[9]=l,m[10]=f,m[11]=u,m[12]=d,m[13]=h,m[14]=p,m[15]=g,m}function yC(t,e,r,i,n,o,s,a,c,l,f,u,d,h,p,g,m){return t[0]=e,t[1]=r,t[2]=i,t[3]=n,t[4]=o,t[5]=s,t[6]=a,t[7]=c,t[8]=l,t[9]=f,t[10]=u,t[11]=d,t[12]=h,t[13]=p,t[14]=g,t[15]=m,t}function my(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function Gd(t,e){if(t===e){let r=e[1],i=e[2],n=e[3],o=e[6],s=e[7],a=e[11];t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=r,t[6]=e[9],t[7]=e[13],t[8]=i,t[9]=o,t[11]=e[14],t[12]=n,t[13]=s,t[14]=a}else t[0]=e[0],t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=e[1],t[5]=e[5],t[6]=e[9],t[7]=e[13],t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=e[14],t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15];return t}function qd(t,e){let r=e[0],i=e[1],n=e[2],o=e[3],s=e[4],a=e[5],c=e[6],l=e[7],f=e[8],u=e[9],d=e[10],h=e[11],p=e[12],g=e[13],m=e[14],_=e[15],T=r*a-i*s,y=r*c-n*s,x=r*l-o*s,w=i*c-n*a,b=i*l-o*a,E=n*l-o*c,S=f*g-u*p,A=f*m-d*p,C=f*_-h*p,I=u*m-d*g,R=u*_-h*g,N=d*_-h*m,O=T*N-y*R+x*I+w*C-b*A+E*S;return O?(O=1/O,t[0]=(a*N-c*R+l*I)*O,t[1]=(n*R-i*N-o*I)*O,t[2]=(g*E-m*b+_*w)*O,t[3]=(d*b-u*E-h*w)*O,t[4]=(c*C-s*N-l*A)*O,t[5]=(r*N-n*C+o*A)*O,t[6]=(m*x-p*E-_*y)*O,t[7]=(f*E-d*x+h*y)*O,t[8]=(s*R-a*C+l*S)*O,t[9]=(i*C-r*R-o*S)*O,t[10]=(p*b-g*x+_*T)*O,t[11]=(u*x-f*b-h*T)*O,t[12]=(a*A-s*I-c*S)*O,t[13]=(r*I-i*A+n*S)*O,t[14]=(g*y-p*w-m*T)*O,t[15]=(f*w-u*y+d*T)*O,t):null}function xC(t,e){let r=e[0],i=e[1],n=e[2],o=e[3],s=e[4],a=e[5],c=e[6],l=e[7],f=e[8],u=e[9],d=e[10],h=e[11],p=e[12],g=e[13],m=e[14],_=e[15],T=r*a-i*s,y=r*c-n*s,x=r*l-o*s,w=i*c-n*a,b=i*l-o*a,E=n*l-o*c,S=f*g-u*p,A=f*m-d*p,C=f*_-h*p,I=u*m-d*g,R=u*_-h*g,N=d*_-h*m;return t[0]=a*N-c*R+l*I,t[1]=n*R-i*N-o*I,t[2]=g*E-m*b+_*w,t[3]=d*b-u*E-h*w,t[4]=c*C-s*N-l*A,t[5]=r*N-n*C+o*A,t[6]=m*x-p*E-_*y,t[7]=f*E-d*x+h*y,t[8]=s*R-a*C+l*S,t[9]=i*C-r*R-o*S,t[10]=p*b-g*x+_*T,t[11]=u*x-f*b-h*T,t[12]=a*A-s*I-c*S,t[13]=r*I-i*A+n*S,t[14]=g*y-p*w-m*T,t[15]=f*w-u*y+d*T,t}function Kd(t){let e=t[0],r=t[1],i=t[2],n=t[3],o=t[4],s=t[5],a=t[6],c=t[7],l=t[8],f=t[9],u=t[10],d=t[11],h=t[12],p=t[13],g=t[14],m=t[15],_=e*s-r*o,T=e*a-i*o,y=r*a-i*s,x=l*p-f*h,w=l*g-u*h,b=f*g-u*p,E=e*b-r*w+i*x,S=o*b-s*w+a*x,A=l*y-f*T+u*_,C=h*y-p*T+g*_;return c*E-n*S+m*A-d*C}function Co(t,e,r){let i=e[0],n=e[1],o=e[2],s=e[3],a=e[4],c=e[5],l=e[6],f=e[7],u=e[8],d=e[9],h=e[10],p=e[11],g=e[12],m=e[13],_=e[14],T=e[15],y=r[0],x=r[1],w=r[2],b=r[3];return t[0]=y*i+x*a+w*u+b*g,t[1]=y*n+x*c+w*d+b*m,t[2]=y*o+x*l+w*h+b*_,t[3]=y*s+x*f+w*p+b*T,y=r[4],x=r[5],w=r[6],b=r[7],t[4]=y*i+x*a+w*u+b*g,t[5]=y*n+x*c+w*d+b*m,t[6]=y*o+x*l+w*h+b*_,t[7]=y*s+x*f+w*p+b*T,y=r[8],x=r[9],w=r[10],b=r[11],t[8]=y*i+x*a+w*u+b*g,t[9]=y*n+x*c+w*d+b*m,t[10]=y*o+x*l+w*h+b*_,t[11]=y*s+x*f+w*p+b*T,y=r[12],x=r[13],w=r[14],b=r[15],t[12]=y*i+x*a+w*u+b*g,t[13]=y*n+x*c+w*d+b*m,t[14]=y*o+x*l+w*h+b*_,t[15]=y*s+x*f+w*p+b*T,t}function Zd(t,e,r){let i=r[0],n=r[1],o=r[2],s,a,c,l,f,u,d,h,p,g,m,_;return e===t?(t[12]=e[0]*i+e[4]*n+e[8]*o+e[12],t[13]=e[1]*i+e[5]*n+e[9]*o+e[13],t[14]=e[2]*i+e[6]*n+e[10]*o+e[14],t[15]=e[3]*i+e[7]*n+e[11]*o+e[15]):(s=e[0],a=e[1],c=e[2],l=e[3],f=e[4],u=e[5],d=e[6],h=e[7],p=e[8],g=e[9],m=e[10],_=e[11],t[0]=s,t[1]=a,t[2]=c,t[3]=l,t[4]=f,t[5]=u,t[6]=d,t[7]=h,t[8]=p,t[9]=g,t[10]=m,t[11]=_,t[12]=s*i+f*n+p*o+e[12],t[13]=a*i+u*n+g*o+e[13],t[14]=c*i+d*n+m*o+e[14],t[15]=l*i+h*n+_*o+e[15]),t}function Qd(t,e,r){let i=r[0],n=r[1],o=r[2];return t[0]=e[0]*i,t[1]=e[1]*i,t[2]=e[2]*i,t[3]=e[3]*i,t[4]=e[4]*n,t[5]=e[5]*n,t[6]=e[6]*n,t[7]=e[7]*n,t[8]=e[8]*o,t[9]=e[9]*o,t[10]=e[10]*o,t[11]=e[11]*o,t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t}function Jd(t,e,r,i){let n=i[0],o=i[1],s=i[2],a=Math.sqrt(n*n+o*o+s*s),c,l,f,u,d,h,p,g,m,_,T,y,x,w,b,E,S,A,C,I,R,N,O,W;return a<1e-6?null:(a=1/a,n*=a,o*=a,s*=a,l=Math.sin(r),c=Math.cos(r),f=1-c,u=e[0],d=e[1],h=e[2],p=e[3],g=e[4],m=e[5],_=e[6],T=e[7],y=e[8],x=e[9],w=e[10],b=e[11],E=n*n*f+c,S=o*n*f+s*l,A=s*n*f-o*l,C=n*o*f-s*l,I=o*o*f+c,R=s*o*f+n*l,N=n*s*f+o*l,O=o*s*f-n*l,W=s*s*f+c,t[0]=u*E+g*S+y*A,t[1]=d*E+m*S+x*A,t[2]=h*E+_*S+w*A,t[3]=p*E+T*S+b*A,t[4]=u*C+g*I+y*R,t[5]=d*C+m*I+x*R,t[6]=h*C+_*I+w*R,t[7]=p*C+T*I+b*R,t[8]=u*N+g*O+y*W,t[9]=d*N+m*O+x*W,t[10]=h*N+_*O+w*W,t[11]=p*N+T*O+b*W,e!==t&&(t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t)}function eh(t,e,r){let i=Math.sin(r),n=Math.cos(r),o=e[4],s=e[5],a=e[6],c=e[7],l=e[8],f=e[9],u=e[10],d=e[11];return e!==t&&(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[4]=o*n+l*i,t[5]=s*n+f*i,t[6]=a*n+u*i,t[7]=c*n+d*i,t[8]=l*n-o*i,t[9]=f*n-s*i,t[10]=u*n-a*i,t[11]=d*n-c*i,t}function th(t,e,r){let i=Math.sin(r),n=Math.cos(r),o=e[0],s=e[1],a=e[2],c=e[3],l=e[8],f=e[9],u=e[10],d=e[11];return e!==t&&(t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=o*n-l*i,t[1]=s*n-f*i,t[2]=a*n-u*i,t[3]=c*n-d*i,t[8]=o*i+l*n,t[9]=s*i+f*n,t[10]=a*i+u*n,t[11]=c*i+d*n,t}function rh(t,e,r){let i=Math.sin(r),n=Math.cos(r),o=e[0],s=e[1],a=e[2],c=e[3],l=e[4],f=e[5],u=e[6],d=e[7];return e!==t&&(t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=o*n+l*i,t[1]=s*n+f*i,t[2]=a*n+u*i,t[3]=c*n+d*i,t[4]=l*n-o*i,t[5]=f*n-s*i,t[6]=u*n-a*i,t[7]=d*n-c*i,t}function bC(t,e){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=e[0],t[13]=e[1],t[14]=e[2],t[15]=1,t}function TC(t,e){return t[0]=e[0],t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=e[1],t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=e[2],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function wC(t,e,r){let i=r[0],n=r[1],o=r[2],s=Math.sqrt(i*i+n*n+o*o),a,c,l;return s<1e-6?null:(s=1/s,i*=s,n*=s,o*=s,c=Math.sin(e),a=Math.cos(e),l=1-a,t[0]=i*i*l+a,t[1]=n*i*l+o*c,t[2]=o*i*l-n*c,t[3]=0,t[4]=i*n*l-o*c,t[5]=n*n*l+a,t[6]=o*n*l+i*c,t[7]=0,t[8]=i*o*l+n*c,t[9]=n*o*l-i*c,t[10]=o*o*l+a,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t)}function SC(t,e){let r=Math.sin(e),i=Math.cos(e);return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=i,t[6]=r,t[7]=0,t[8]=0,t[9]=-r,t[10]=i,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function AC(t,e){let r=Math.sin(e),i=Math.cos(e);return t[0]=i,t[1]=0,t[2]=-r,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=r,t[9]=0,t[10]=i,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function vC(t,e){let r=Math.sin(e),i=Math.cos(e);return t[0]=i,t[1]=r,t[2]=0,t[3]=0,t[4]=-r,t[5]=i,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function _y(t,e,r){let i=e[0],n=e[1],o=e[2],s=e[3],a=i+i,c=n+n,l=o+o,f=i*a,u=i*c,d=i*l,h=n*c,p=n*l,g=o*l,m=s*a,_=s*c,T=s*l;return t[0]=1-(h+g),t[1]=u+T,t[2]=d-_,t[3]=0,t[4]=u-T,t[5]=1-(f+g),t[6]=p+m,t[7]=0,t[8]=d+_,t[9]=p-m,t[10]=1-(f+h),t[11]=0,t[12]=r[0],t[13]=r[1],t[14]=r[2],t[15]=1,t}function EC(t,e){let r=new le(3),i=-e[0],n=-e[1],o=-e[2],s=e[3],a=e[4],c=e[5],l=e[6],f=e[7],u=i*i+n*n+o*o+s*s;return u>0?(r[0]=(a*s+f*i+c*o-l*n)*2/u,r[1]=(c*s+f*n+l*i-a*o)*2/u,r[2]=(l*s+f*o+a*n-c*i)*2/u):(r[0]=(a*s+f*i+c*o-l*n)*2,r[1]=(c*s+f*n+l*i-a*o)*2,r[2]=(l*s+f*o+a*n-c*i)*2),_y(t,e,r),t}function RC(t,e){return t[0]=e[12],t[1]=e[13],t[2]=e[14],t}function yy(t,e){let r=e[0],i=e[1],n=e[2],o=e[4],s=e[5],a=e[6],c=e[8],l=e[9],f=e[10];return t[0]=Math.sqrt(r*r+i*i+n*n),t[1]=Math.sqrt(o*o+s*s+a*a),t[2]=Math.sqrt(c*c+l*l+f*f),t}function CC(t,e){let r=new le(3);yy(r,e);let i=1/r[0],n=1/r[1],o=1/r[2],s=e[0]*i,a=e[1]*n,c=e[2]*o,l=e[4]*i,f=e[5]*n,u=e[6]*o,d=e[8]*i,h=e[9]*n,p=e[10]*o,g=s+f+p,m=0;return g>0?(m=Math.sqrt(g+1)*2,t[3]=.25*m,t[0]=(u-h)/m,t[1]=(d-c)/m,t[2]=(a-l)/m):s>f&&s>p?(m=Math.sqrt(1+s-f-p)*2,t[3]=(u-h)/m,t[0]=.25*m,t[1]=(a+l)/m,t[2]=(d+c)/m):f>p?(m=Math.sqrt(1+f-s-p)*2,t[3]=(d-c)/m,t[0]=(a+l)/m,t[1]=.25*m,t[2]=(u+h)/m):(m=Math.sqrt(1+p-s-f)*2,t[3]=(a-l)/m,t[0]=(d+c)/m,t[1]=(u+h)/m,t[2]=.25*m),t}function PC(t,e,r,i){e[0]=i[12],e[1]=i[13],e[2]=i[14];let n=i[0],o=i[1],s=i[2],a=i[4],c=i[5],l=i[6],f=i[8],u=i[9],d=i[10];r[0]=Math.sqrt(n*n+o*o+s*s),r[1]=Math.sqrt(a*a+c*c+l*l),r[2]=Math.sqrt(f*f+u*u+d*d);let h=1/r[0],p=1/r[1],g=1/r[2],m=n*h,_=o*p,T=s*g,y=a*h,x=c*p,w=l*g,b=f*h,E=u*p,S=d*g,A=m+x+S,C=0;return A>0?(C=Math.sqrt(A+1)*2,t[3]=.25*C,t[0]=(w-E)/C,t[1]=(b-T)/C,t[2]=(_-y)/C):m>x&&m>S?(C=Math.sqrt(1+m-x-S)*2,t[3]=(w-E)/C,t[0]=.25*C,t[1]=(_+y)/C,t[2]=(b+T)/C):x>S?(C=Math.sqrt(1+x-m-S)*2,t[3]=(b-T)/C,t[0]=(_+y)/C,t[1]=.25*C,t[2]=(w+E)/C):(C=Math.sqrt(1+S-m-x)*2,t[3]=(_-y)/C,t[0]=(b+T)/C,t[1]=(w+E)/C,t[2]=.25*C),t}function MC(t,e,r,i){let n=e[0],o=e[1],s=e[2],a=e[3],c=n+n,l=o+o,f=s+s,u=n*c,d=n*l,h=n*f,p=o*l,g=o*f,m=s*f,_=a*c,T=a*l,y=a*f,x=i[0],w=i[1],b=i[2];return t[0]=(1-(p+m))*x,t[1]=(d+y)*x,t[2]=(h-T)*x,t[3]=0,t[4]=(d-y)*w,t[5]=(1-(u+m))*w,t[6]=(g+_)*w,t[7]=0,t[8]=(h+T)*b,t[9]=(g-_)*b,t[10]=(1-(u+p))*b,t[11]=0,t[12]=r[0],t[13]=r[1],t[14]=r[2],t[15]=1,t}function IC(t,e,r,i,n){let o=e[0],s=e[1],a=e[2],c=e[3],l=o+o,f=s+s,u=a+a,d=o*l,h=o*f,p=o*u,g=s*f,m=s*u,_=a*u,T=c*l,y=c*f,x=c*u,w=i[0],b=i[1],E=i[2],S=n[0],A=n[1],C=n[2],I=(1-(g+_))*w,R=(h+x)*w,N=(p-y)*w,O=(h-x)*b,W=(1-(d+_))*b,G=(m+T)*b,L=(p+y)*E,H=(m-T)*E,Re=(1-(d+g))*E;return t[0]=I,t[1]=R,t[2]=N,t[3]=0,t[4]=O,t[5]=W,t[6]=G,t[7]=0,t[8]=L,t[9]=H,t[10]=Re,t[11]=0,t[12]=r[0]+S-(I*S+O*A+L*C),t[13]=r[1]+A-(R*S+W*A+H*C),t[14]=r[2]+C-(N*S+G*A+Re*C),t[15]=1,t}function ih(t,e){let r=e[0],i=e[1],n=e[2],o=e[3],s=r+r,a=i+i,c=n+n,l=r*s,f=i*s,u=i*a,d=n*s,h=n*a,p=n*c,g=o*s,m=o*a,_=o*c;return t[0]=1-u-p,t[1]=f+_,t[2]=d-m,t[3]=0,t[4]=f-_,t[5]=1-l-p,t[6]=h+g,t[7]=0,t[8]=d+m,t[9]=h-g,t[10]=1-l-u,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function nh(t,e,r,i,n,o,s){let a=1/(r-e),c=1/(n-i),l=1/(o-s);return t[0]=o*2*a,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=o*2*c,t[6]=0,t[7]=0,t[8]=(r+e)*a,t[9]=(n+i)*c,t[10]=(s+o)*l,t[11]=-1,t[12]=0,t[13]=0,t[14]=s*o*2*l,t[15]=0,t}function xy(t,e,r,i,n){let o=1/Math.tan(e/2);if(t[0]=o/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=o,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,n!=null&&n!==1/0){let s=1/(i-n);t[10]=(n+i)*s,t[14]=2*n*i*s}else t[10]=-1,t[14]=-2*i;return t}var oh=xy;function OC(t,e,r,i,n){let o=1/Math.tan(e/2);if(t[0]=o/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=o,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,n!=null&&n!==1/0){let s=1/(i-n);t[10]=n*s,t[14]=n*i*s}else t[10]=-1,t[14]=-i;return t}function NC(t,e,r,i){let n=Math.tan(e.upDegrees*Math.PI/180),o=Math.tan(e.downDegrees*Math.PI/180),s=Math.tan(e.leftDegrees*Math.PI/180),a=Math.tan(e.rightDegrees*Math.PI/180),c=2/(s+a),l=2/(n+o);return t[0]=c,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=l,t[6]=0,t[7]=0,t[8]=-((s-a)*c*.5),t[9]=(n-o)*l*.5,t[10]=i/(r-i),t[11]=-1,t[12]=0,t[13]=0,t[14]=i*r/(r-i),t[15]=0,t}function by(t,e,r,i,n,o,s){let a=1/(e-r),c=1/(i-n),l=1/(o-s);return t[0]=-2*a,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*c,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=2*l,t[11]=0,t[12]=(e+r)*a,t[13]=(n+i)*c,t[14]=(s+o)*l,t[15]=1,t}var sh=by;function DC(t,e,r,i,n,o,s){let a=1/(e-r),c=1/(i-n),l=1/(o-s);return t[0]=-2*a,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*c,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=l,t[11]=0,t[12]=(e+r)*a,t[13]=(n+i)*c,t[14]=o*l,t[15]=1,t}function ah(t,e,r,i){let n,o,s,a,c,l,f,u,d,h,p=e[0],g=e[1],m=e[2],_=i[0],T=i[1],y=i[2],x=r[0],w=r[1],b=r[2];return Math.abs(p-x)<1e-6&&Math.abs(g-w)<1e-6&&Math.abs(m-b)<1e-6?my(t):(u=p-x,d=g-w,h=m-b,n=1/Math.sqrt(u*u+d*d+h*h),u*=n,d*=n,h*=n,o=T*h-y*d,s=y*u-_*h,a=_*d-T*u,n=Math.sqrt(o*o+s*s+a*a),n?(n=1/n,o*=n,s*=n,a*=n):(o=0,s=0,a=0),c=d*a-h*s,l=h*o-u*a,f=u*s-d*o,n=Math.sqrt(c*c+l*l+f*f),n?(n=1/n,c*=n,l*=n,f*=n):(c=0,l=0,f=0),t[0]=o,t[1]=c,t[2]=u,t[3]=0,t[4]=s,t[5]=l,t[6]=d,t[7]=0,t[8]=a,t[9]=f,t[10]=h,t[11]=0,t[12]=-(o*p+s*g+a*m),t[13]=-(c*p+l*g+f*m),t[14]=-(u*p+d*g+h*m),t[15]=1,t)}function LC(t,e,r,i){let n=e[0],o=e[1],s=e[2],a=i[0],c=i[1],l=i[2],f=n-r[0],u=o-r[1],d=s-r[2],h=f*f+u*u+d*d;h>0&&(h=1/Math.sqrt(h),f*=h,u*=h,d*=h);let p=c*d-l*u,g=l*f-a*d,m=a*u-c*f;return h=p*p+g*g+m*m,h>0&&(h=1/Math.sqrt(h),p*=h,g*=h,m*=h),t[0]=p,t[1]=g,t[2]=m,t[3]=0,t[4]=u*m-d*g,t[5]=d*p-f*m,t[6]=f*g-u*p,t[7]=0,t[8]=f,t[9]=u,t[10]=d,t[11]=0,t[12]=n,t[13]=o,t[14]=s,t[15]=1,t}function FC(t){return`mat4(${t[0]}, ${t[1]}, ${t[2]}, ${t[3]}, ${t[4]}, ${t[5]}, ${t[6]}, ${t[7]}, ${t[8]}, ${t[9]}, ${t[10]}, ${t[11]}, ${t[12]}, ${t[13]}, ${t[14]}, ${t[15]})`}function BC(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]+t[3]*t[3]+t[4]*t[4]+t[5]*t[5]+t[6]*t[6]+t[7]*t[7]+t[8]*t[8]+t[9]*t[9]+t[10]*t[10]+t[11]*t[11]+t[12]*t[12]+t[13]*t[13]+t[14]*t[14]+t[15]*t[15])}function kC(t,e,r){return t[0]=e[0]+r[0],t[1]=e[1]+r[1],t[2]=e[2]+r[2],t[3]=e[3]+r[3],t[4]=e[4]+r[4],t[5]=e[5]+r[5],t[6]=e[6]+r[6],t[7]=e[7]+r[7],t[8]=e[8]+r[8],t[9]=e[9]+r[9],t[10]=e[10]+r[10],t[11]=e[11]+r[11],t[12]=e[12]+r[12],t[13]=e[13]+r[13],t[14]=e[14]+r[14],t[15]=e[15]+r[15],t}function Ty(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t[3]=e[3]-r[3],t[4]=e[4]-r[4],t[5]=e[5]-r[5],t[6]=e[6]-r[6],t[7]=e[7]-r[7],t[8]=e[8]-r[8],t[9]=e[9]-r[9],t[10]=e[10]-r[10],t[11]=e[11]-r[11],t[12]=e[12]-r[12],t[13]=e[13]-r[13],t[14]=e[14]-r[14],t[15]=e[15]-r[15],t}function UC(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t[3]=e[3]*r,t[4]=e[4]*r,t[5]=e[5]*r,t[6]=e[6]*r,t[7]=e[7]*r,t[8]=e[8]*r,t[9]=e[9]*r,t[10]=e[10]*r,t[11]=e[11]*r,t[12]=e[12]*r,t[13]=e[13]*r,t[14]=e[14]*r,t[15]=e[15]*r,t}function zC(t,e,r,i){return t[0]=e[0]+r[0]*i,t[1]=e[1]+r[1]*i,t[2]=e[2]+r[2]*i,t[3]=e[3]+r[3]*i,t[4]=e[4]+r[4]*i,t[5]=e[5]+r[5]*i,t[6]=e[6]+r[6]*i,t[7]=e[7]+r[7]*i,t[8]=e[8]+r[8]*i,t[9]=e[9]+r[9]*i,t[10]=e[10]+r[10]*i,t[11]=e[11]+r[11]*i,t[12]=e[12]+r[12]*i,t[13]=e[13]+r[13]*i,t[14]=e[14]+r[14]*i,t[15]=e[15]+r[15]*i,t}function WC(t,e){return t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]&&t[4]===e[4]&&t[5]===e[5]&&t[6]===e[6]&&t[7]===e[7]&&t[8]===e[8]&&t[9]===e[9]&&t[10]===e[10]&&t[11]===e[11]&&t[12]===e[12]&&t[13]===e[13]&&t[14]===e[14]&&t[15]===e[15]}function VC(t,e){let r=t[0],i=t[1],n=t[2],o=t[3],s=t[4],a=t[5],c=t[6],l=t[7],f=t[8],u=t[9],d=t[10],h=t[11],p=t[12],g=t[13],m=t[14],_=t[15],T=e[0],y=e[1],x=e[2],w=e[3],b=e[4],E=e[5],S=e[6],A=e[7],C=e[8],I=e[9],R=e[10],N=e[11],O=e[12],W=e[13],G=e[14],L=e[15];return Math.abs(r-T)<=1e-6*Math.max(1,Math.abs(r),Math.abs(T))&&Math.abs(i-y)<=1e-6*Math.max(1,Math.abs(i),Math.abs(y))&&Math.abs(n-x)<=1e-6*Math.max(1,Math.abs(n),Math.abs(x))&&Math.abs(o-w)<=1e-6*Math.max(1,Math.abs(o),Math.abs(w))&&Math.abs(s-b)<=1e-6*Math.max(1,Math.abs(s),Math.abs(b))&&Math.abs(a-E)<=1e-6*Math.max(1,Math.abs(a),Math.abs(E))&&Math.abs(c-S)<=1e-6*Math.max(1,Math.abs(c),Math.abs(S))&&Math.abs(l-A)<=1e-6*Math.max(1,Math.abs(l),Math.abs(A))&&Math.abs(f-C)<=1e-6*Math.max(1,Math.abs(f),Math.abs(C))&&Math.abs(u-I)<=1e-6*Math.max(1,Math.abs(u),Math.abs(I))&&Math.abs(d-R)<=1e-6*Math.max(1,Math.abs(d),Math.abs(R))&&Math.abs(h-N)<=1e-6*Math.max(1,Math.abs(h),Math.abs(N))&&Math.abs(p-O)<=1e-6*Math.max(1,Math.abs(p),Math.abs(O))&&Math.abs(g-W)<=1e-6*Math.max(1,Math.abs(g),Math.abs(W))&&Math.abs(m-G)<=1e-6*Math.max(1,Math.abs(m),Math.abs(G))&&Math.abs(_-L)<=1e-6*Math.max(1,Math.abs(_),Math.abs(L))}var jC=Co,$C=Ty;var Ze={};Zi(Ze,{add:()=>qC,ceil:()=>KC,clone:()=>HC,copy:()=>XC,create:()=>wy,cross:()=>aP,dist:()=>yP,distance:()=>Ey,div:()=>_P,divide:()=>vy,dot:()=>sP,equals:()=>pP,exactEquals:()=>hP,floor:()=>ZC,forEach:()=>wP,fromValues:()=>YC,inverse:()=>nP,len:()=>bP,length:()=>Cy,lerp:()=>cP,max:()=>JC,min:()=>QC,mul:()=>mP,multiply:()=>Ay,negate:()=>iP,normalize:()=>oP,random:()=>lP,round:()=>eP,scale:()=>tP,scaleAndAdd:()=>rP,set:()=>GC,sqrDist:()=>xP,sqrLen:()=>TP,squaredDistance:()=>Ry,squaredLength:()=>Py,str:()=>dP,sub:()=>gP,subtract:()=>Sy,transformMat4:()=>ch,transformQuat:()=>fP,zero:()=>uP});function wy(){let t=new le(4);return le!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0,t[3]=0),t}function HC(t){let e=new le(4);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e}function YC(t,e,r,i){let n=new le(4);return n[0]=t,n[1]=e,n[2]=r,n[3]=i,n}function XC(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t}function GC(t,e,r,i,n){return t[0]=e,t[1]=r,t[2]=i,t[3]=n,t}function qC(t,e,r){return t[0]=e[0]+r[0],t[1]=e[1]+r[1],t[2]=e[2]+r[2],t[3]=e[3]+r[3],t}function Sy(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t[3]=e[3]-r[3],t}function Ay(t,e,r){return t[0]=e[0]*r[0],t[1]=e[1]*r[1],t[2]=e[2]*r[2],t[3]=e[3]*r[3],t}function vy(t,e,r){return t[0]=e[0]/r[0],t[1]=e[1]/r[1],t[2]=e[2]/r[2],t[3]=e[3]/r[3],t}function KC(t,e){return t[0]=Math.ceil(e[0]),t[1]=Math.ceil(e[1]),t[2]=Math.ceil(e[2]),t[3]=Math.ceil(e[3]),t}function ZC(t,e){return t[0]=Math.floor(e[0]),t[1]=Math.floor(e[1]),t[2]=Math.floor(e[2]),t[3]=Math.floor(e[3]),t}function QC(t,e,r){return t[0]=Math.min(e[0],r[0]),t[1]=Math.min(e[1],r[1]),t[2]=Math.min(e[2],r[2]),t[3]=Math.min(e[3],r[3]),t}function JC(t,e,r){return t[0]=Math.max(e[0],r[0]),t[1]=Math.max(e[1],r[1]),t[2]=Math.max(e[2],r[2]),t[3]=Math.max(e[3],r[3]),t}function eP(t,e){return t[0]=nt(e[0]),t[1]=nt(e[1]),t[2]=nt(e[2]),t[3]=nt(e[3]),t}function tP(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t[3]=e[3]*r,t}function rP(t,e,r,i){return t[0]=e[0]+r[0]*i,t[1]=e[1]+r[1]*i,t[2]=e[2]+r[2]*i,t[3]=e[3]+r[3]*i,t}function Ey(t,e){let r=e[0]-t[0],i=e[1]-t[1],n=e[2]-t[2],o=e[3]-t[3];return Math.sqrt(r*r+i*i+n*n+o*o)}function Ry(t,e){let r=e[0]-t[0],i=e[1]-t[1],n=e[2]-t[2],o=e[3]-t[3];return r*r+i*i+n*n+o*o}function Cy(t){let e=t[0],r=t[1],i=t[2],n=t[3];return Math.sqrt(e*e+r*r+i*i+n*n)}function Py(t){let e=t[0],r=t[1],i=t[2],n=t[3];return e*e+r*r+i*i+n*n}function iP(t,e){return t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t}function nP(t,e){return t[0]=1/e[0],t[1]=1/e[1],t[2]=1/e[2],t[3]=1/e[3],t}function oP(t,e){let r=e[0],i=e[1],n=e[2],o=e[3],s=r*r+i*i+n*n+o*o;return s>0&&(s=1/Math.sqrt(s)),t[0]=r*s,t[1]=i*s,t[2]=n*s,t[3]=o*s,t}function sP(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]*e[3]}function aP(t,e,r,i){let n=r[0]*i[1]-r[1]*i[0],o=r[0]*i[2]-r[2]*i[0],s=r[0]*i[3]-r[3]*i[0],a=r[1]*i[2]-r[2]*i[1],c=r[1]*i[3]-r[3]*i[1],l=r[2]*i[3]-r[3]*i[2],f=e[0],u=e[1],d=e[2],h=e[3];return t[0]=u*l-d*c+h*a,t[1]=-(f*l)+d*s-h*o,t[2]=f*c-u*s+h*n,t[3]=-(f*a)+u*o-d*n,t}function cP(t,e,r,i){let n=e[0],o=e[1],s=e[2],a=e[3];return t[0]=n+i*(r[0]-n),t[1]=o+i*(r[1]-o),t[2]=s+i*(r[2]-s),t[3]=a+i*(r[3]-a),t}function lP(t,e){e=e===void 0?1:e;let r,i,n,o,s,a;do r=Nt()*2-1,i=Nt()*2-1,s=r*r+i*i;while(s>=1);do n=Nt()*2-1,o=Nt()*2-1,a=n*n+o*o;while(a>=1);let c=Math.sqrt((1-s)/a);return t[0]=e*r,t[1]=e*i,t[2]=e*n*c,t[3]=e*o*c,t}function ch(t,e,r){let i=e[0],n=e[1],o=e[2],s=e[3];return t[0]=r[0]*i+r[4]*n+r[8]*o+r[12]*s,t[1]=r[1]*i+r[5]*n+r[9]*o+r[13]*s,t[2]=r[2]*i+r[6]*n+r[10]*o+r[14]*s,t[3]=r[3]*i+r[7]*n+r[11]*o+r[15]*s,t}function fP(t,e,r){let i=e[0],n=e[1],o=e[2],s=r[0],a=r[1],c=r[2],l=r[3],f=l*i+a*o-c*n,u=l*n+c*i-s*o,d=l*o+s*n-a*i,h=-s*i-a*n-c*o;return t[0]=f*l+h*-s+u*-c-d*-a,t[1]=u*l+h*-a+d*-s-f*-c,t[2]=d*l+h*-c+f*-a-u*-s,t[3]=e[3],t}function uP(t){return t[0]=0,t[1]=0,t[2]=0,t[3]=0,t}function dP(t){return`vec4(${t[0]}, ${t[1]}, ${t[2]}, ${t[3]})`}function hP(t,e){return t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]}function pP(t,e){let r=t[0],i=t[1],n=t[2],o=t[3],s=e[0],a=e[1],c=e[2],l=e[3];return Math.abs(r-s)<=1e-6*Math.max(1,Math.abs(r),Math.abs(s))&&Math.abs(i-a)<=1e-6*Math.max(1,Math.abs(i),Math.abs(a))&&Math.abs(n-c)<=1e-6*Math.max(1,Math.abs(n),Math.abs(c))&&Math.abs(o-l)<=1e-6*Math.max(1,Math.abs(o),Math.abs(l))}var gP=Sy,mP=Ay,_P=vy,yP=Ey,xP=Ry,bP=Cy,TP=Py,wP=(function(){let t=wy();return function(e,r,i,n,o,s){let a,c;for(r||(r=4),i||(i=0),n?c=Math.min(n*r+i,e.length):c=e.length,a=i;aMath.PI*2)throw Error("expected radians")}function CP(t,e,r,i,n,o){let s=2*o/(r-e),a=2*o/(n-i),c=(r+e)/(r-e),l=(n+i)/(n-i),f=-1,u=-1,d=-2*o;return t[0]=s,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=a,t[6]=0,t[7]=0,t[8]=c,t[9]=l,t[10]=f,t[11]=u,t[12]=0,t[13]=0,t[14]=d,t[15]=0,t}function dh(t,e=[],r=0){let i=Math.fround(t),n=t-i;return e[r]=i,e[r+1]=n,e}function Iy(t){return t-Math.fround(t)}function Oy(t){let e=new Float32Array(32);for(let r=0;r<4;++r)for(let i=0;i<4;++i){let n=r*4+i;dh(t[i*4+r],e,n*2)}return e}function Ny(t,e=!0){return t??e}function PP(t=[0,0,0],e=!0){return e?t.map(r=>r/255):[...t]}function Dy(t,e=!0){let r=PP(t.slice(0,3),e),i=Number.isFinite(t[3]),n=i?t[3]:1;return[r[0],r[1],r[2],e&&i?n/255:n]}var MP=`#ifdef LUMA_FP32_TAN_PRECISION_WORKAROUND + +// All these functions are for substituting tan() function from Intel GPU only +const float TWO_PI = 6.2831854820251465; +const float PI_2 = 1.5707963705062866; +const float PI_16 = 0.1963495463132858; + +const float SIN_TABLE_0 = 0.19509032368659973; +const float SIN_TABLE_1 = 0.3826834261417389; +const float SIN_TABLE_2 = 0.5555702447891235; +const float SIN_TABLE_3 = 0.7071067690849304; + +const float COS_TABLE_0 = 0.9807852506637573; +const float COS_TABLE_1 = 0.9238795042037964; +const float COS_TABLE_2 = 0.8314695954322815; +const float COS_TABLE_3 = 0.7071067690849304; + +const float INVERSE_FACTORIAL_3 = 1.666666716337204e-01; // 1/3! +const float INVERSE_FACTORIAL_5 = 8.333333767950535e-03; // 1/5! +const float INVERSE_FACTORIAL_7 = 1.9841270113829523e-04; // 1/7! +const float INVERSE_FACTORIAL_9 = 2.75573188446287533e-06; // 1/9! + +float sin_taylor_fp32(float a) { + float r, s, t, x; + + if (a == 0.0) { + return 0.0; + } + + x = -a * a; + s = a; + r = a; + + r = r * x; + t = r * INVERSE_FACTORIAL_3; + s = s + t; + + r = r * x; + t = r * INVERSE_FACTORIAL_5; + s = s + t; + + r = r * x; + t = r * INVERSE_FACTORIAL_7; + s = s + t; + + r = r * x; + t = r * INVERSE_FACTORIAL_9; + s = s + t; + + return s; +} + +void sincos_taylor_fp32(float a, out float sin_t, out float cos_t) { + if (a == 0.0) { + sin_t = 0.0; + cos_t = 1.0; + } + sin_t = sin_taylor_fp32(a); + cos_t = sqrt(1.0 - sin_t * sin_t); +} + +float tan_taylor_fp32(float a) { + float sin_a; + float cos_a; + + if (a == 0.0) { + return 0.0; + } + + // 2pi range reduction + float z = floor(a / TWO_PI); + float r = a - TWO_PI * z; + + float t; + float q = floor(r / PI_2 + 0.5); + int j = int(q); + + if (j < -2 || j > 2) { + return 1.0 / 0.0; + } + + t = r - PI_2 * q; + + q = floor(t / PI_16 + 0.5); + int k = int(q); + int abs_k = int(abs(float(k))); + + if (abs_k > 4) { + return 1.0 / 0.0; + } else { + t = t - PI_16 * q; + } + + float u = 0.0; + float v = 0.0; + + float sin_t, cos_t; + float s, c; + sincos_taylor_fp32(t, sin_t, cos_t); + + if (k == 0) { + s = sin_t; + c = cos_t; + } else { + if (abs(float(abs_k) - 1.0) < 0.5) { + u = COS_TABLE_0; + v = SIN_TABLE_0; + } else if (abs(float(abs_k) - 2.0) < 0.5) { + u = COS_TABLE_1; + v = SIN_TABLE_1; + } else if (abs(float(abs_k) - 3.0) < 0.5) { + u = COS_TABLE_2; + v = SIN_TABLE_2; + } else if (abs(float(abs_k) - 4.0) < 0.5) { + u = COS_TABLE_3; + v = SIN_TABLE_3; + } + if (k > 0) { + s = u * sin_t + v * cos_t; + c = u * cos_t - v * sin_t; + } else { + s = u * sin_t - v * cos_t; + c = u * cos_t + v * sin_t; + } + } + + if (j == 0) { + sin_a = s; + cos_a = c; + } else if (j == 1) { + sin_a = c; + cos_a = -s; + } else if (j == -1) { + sin_a = -c; + cos_a = s; + } else { + sin_a = -s; + cos_a = -c; + } + return sin_a / cos_a; +} +#endif + +float tan_fp32(float a) { +#ifdef LUMA_FP32_TAN_PRECISION_WORKAROUND + return tan_taylor_fp32(a); +#else + return tan(a); +#endif +} +`,hh={name:"fp32",vs:MP};var ph=` +layout(std140) uniform fp64arithmeticUniforms { + uniform float ONE; + uniform float SPLIT; +} fp64; + +/* +About LUMA_FP64_CODE_ELIMINATION_WORKAROUND + +The purpose of this workaround is to prevent shader compilers from +optimizing away necessary arithmetic operations by swapping their sequences +or transform the equation to some 'equivalent' form. + +These helpers implement Dekker/Veltkamp-style error tracking. If the compiler +folds constants or reassociates the arithmetic, the high/low split can stop +tracking the rounding error correctly. That failure mode tends to look fine in +simple coordinate setup, but then breaks down inside iterative arithmetic such +as fp64 Mandelbrot loops. + +The method is to multiply an artifical variable, ONE, which will be known to +the compiler to be 1 only at runtime. The whole expression is then represented +as a polynomial with respective to ONE. In the coefficients of all terms, only one a +and one b should appear + +err = (a + b) * ONE^6 - a * ONE^5 - (a + b) * ONE^4 + a * ONE^3 - b - (a + b) * ONE^2 + a * ONE +*/ + +float prevent_fp64_optimization(float value) { +#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND) + return value + fp64.ONE * 0.0; +#else + return value; +#endif +} + +// Divide float number to high and low floats to extend fraction bits +vec2 split(float a) { + // Keep SPLIT as a runtime uniform so the compiler cannot fold the Dekker + // split into a constant expression and reassociate the recovery steps. + float split = prevent_fp64_optimization(fp64.SPLIT); + float t = prevent_fp64_optimization(a * split); + float temp = t - a; + float a_hi = t - temp; + float a_lo = a - a_hi; + return vec2(a_hi, a_lo); +} + +// Divide float number again when high float uses too many fraction bits +vec2 split2(vec2 a) { + vec2 b = split(a.x); + b.y += a.y; + return b; +} + +// Special sum operation when a > b +vec2 quickTwoSum(float a, float b) { +#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND) + float sum = (a + b) * fp64.ONE; + float err = b - (sum - a) * fp64.ONE; +#else + float sum = a + b; + float err = b - (sum - a); +#endif + return vec2(sum, err); +} + +// General sum operation +vec2 twoSum(float a, float b) { + float s = (a + b); +#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND) + float v = (s * fp64.ONE - a) * fp64.ONE; + float err = (a - (s - v) * fp64.ONE) * fp64.ONE * fp64.ONE * fp64.ONE + (b - v); +#else + float v = s - a; + float err = (a - (s - v)) + (b - v); +#endif + return vec2(s, err); +} + +vec2 twoSub(float a, float b) { + float s = (a - b); +#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND) + float v = (s * fp64.ONE - a) * fp64.ONE; + float err = (a - (s - v) * fp64.ONE) * fp64.ONE * fp64.ONE * fp64.ONE - (b + v); +#else + float v = s - a; + float err = (a - (s - v)) - (b + v); +#endif + return vec2(s, err); +} + +vec2 twoSqr(float a) { + float prod = a * a; + vec2 a_fp64 = split(a); +#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND) + float err = ((a_fp64.x * a_fp64.x - prod) * fp64.ONE + 2.0 * a_fp64.x * + a_fp64.y * fp64.ONE * fp64.ONE) + a_fp64.y * a_fp64.y * fp64.ONE * fp64.ONE * fp64.ONE; +#else + float err = ((a_fp64.x * a_fp64.x - prod) + 2.0 * a_fp64.x * a_fp64.y) + a_fp64.y * a_fp64.y; +#endif + return vec2(prod, err); +} + +vec2 twoProd(float a, float b) { + float prod = a * b; + vec2 a_fp64 = split(a); + vec2 b_fp64 = split(b); + // twoProd is especially sensitive because mul_fp64 and div_fp64 both depend + // on the split terms and cross terms staying in the original evaluation + // order. If the compiler folds or reassociates them, the low part tends to + // collapse to zero or NaN on some drivers. + float highProduct = prevent_fp64_optimization(a_fp64.x * b_fp64.x); + float crossProduct1 = prevent_fp64_optimization(a_fp64.x * b_fp64.y); + float crossProduct2 = prevent_fp64_optimization(a_fp64.y * b_fp64.x); + float lowProduct = prevent_fp64_optimization(a_fp64.y * b_fp64.y); +#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND) + float err1 = (highProduct - prod) * fp64.ONE; + float err2 = crossProduct1 * fp64.ONE * fp64.ONE; + float err3 = crossProduct2 * fp64.ONE * fp64.ONE * fp64.ONE; + float err4 = lowProduct * fp64.ONE * fp64.ONE * fp64.ONE * fp64.ONE; +#else + float err1 = highProduct - prod; + float err2 = crossProduct1; + float err3 = crossProduct2; + float err4 = lowProduct; +#endif + float err = ((err1 + err2) + err3) + err4; + return vec2(prod, err); +} + +vec2 sum_fp64(vec2 a, vec2 b) { + vec2 s, t; + s = twoSum(a.x, b.x); + t = twoSum(a.y, b.y); + s.y += t.x; + s = quickTwoSum(s.x, s.y); + s.y += t.y; + s = quickTwoSum(s.x, s.y); + return s; +} + +vec2 sub_fp64(vec2 a, vec2 b) { + vec2 s, t; + s = twoSub(a.x, b.x); + t = twoSub(a.y, b.y); + s.y += t.x; + s = quickTwoSum(s.x, s.y); + s.y += t.y; + s = quickTwoSum(s.x, s.y); + return s; +} + +vec2 mul_fp64(vec2 a, vec2 b) { + vec2 prod = twoProd(a.x, b.x); + // y component is for the error + prod.y += a.x * b.y; +#if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND) + prod = split2(prod); +#endif + prod = quickTwoSum(prod.x, prod.y); + prod.y += a.y * b.x; +#if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND) + prod = split2(prod); +#endif + prod = quickTwoSum(prod.x, prod.y); + return prod; +} + +vec2 div_fp64(vec2 a, vec2 b) { + float xn = 1.0 / b.x; +#if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND) + vec2 yn = mul_fp64(a, vec2(xn, 0)); +#else + vec2 yn = a * xn; +#endif + float diff = (sub_fp64(a, mul_fp64(b, yn))).x; + vec2 prod = twoProd(xn, diff); + return sum_fp64(yn, prod); +} + +vec2 sqrt_fp64(vec2 a) { + if (a.x == 0.0 && a.y == 0.0) return vec2(0.0, 0.0); + if (a.x < 0.0) return vec2(0.0 / 0.0, 0.0 / 0.0); + + float x = 1.0 / sqrt(a.x); + float yn = a.x * x; +#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND) + vec2 yn_sqr = twoSqr(yn) * fp64.ONE; +#else + vec2 yn_sqr = twoSqr(yn); +#endif + float diff = sub_fp64(a, yn_sqr).x; + vec2 prod = twoProd(x * 0.5, diff); +#if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND) + return sum_fp64(split(yn), prod); +#else + return sum_fp64(vec2(yn, 0.0), prod); +#endif +} +`;var Ly=`struct Fp64ArithmeticUniforms { + ONE: f32, + SPLIT: f32, +}; + +@group(0) @binding(auto) var fp64arithmetic : Fp64ArithmeticUniforms; + +fn fp64_nan(seed: f32) -> f32 { + let nanBits = 0x7fc00000u | select(0u, 1u, seed < 0.0); + return bitcast(nanBits); +} + +fn fp64_runtime_zero() -> f32 { + return fp64arithmetic.ONE * 0.0; +} + +fn prevent_fp64_optimization(value: f32) -> f32 { +#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND + return value + fp64_runtime_zero(); +#else + return value; +#endif +} + +fn split(a: f32) -> vec2f { + let splitValue = prevent_fp64_optimization(fp64arithmetic.SPLIT + fp64_runtime_zero()); + let t = prevent_fp64_optimization(a * splitValue); + let temp = prevent_fp64_optimization(t - a); + let aHi = prevent_fp64_optimization(t - temp); + let aLo = prevent_fp64_optimization(a - aHi); + return vec2f(aHi, aLo); +} + +fn split2(a: vec2f) -> vec2f { + var b = split(a.x); + b.y = b.y + a.y; + return b; +} + +fn quickTwoSum(a: f32, b: f32) -> vec2f { +#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND + let sum = prevent_fp64_optimization((a + b) * fp64arithmetic.ONE); + let err = prevent_fp64_optimization(b - (sum - a) * fp64arithmetic.ONE); +#else + let sum = prevent_fp64_optimization(a + b); + let err = prevent_fp64_optimization(b - (sum - a)); +#endif + return vec2f(sum, err); +} + +fn twoSum(a: f32, b: f32) -> vec2f { + let s = prevent_fp64_optimization(a + b); +#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND + let v = prevent_fp64_optimization((s * fp64arithmetic.ONE - a) * fp64arithmetic.ONE); + let err = + prevent_fp64_optimization((a - (s - v) * fp64arithmetic.ONE) * + fp64arithmetic.ONE * + fp64arithmetic.ONE * + fp64arithmetic.ONE) + + prevent_fp64_optimization(b - v); +#else + let v = prevent_fp64_optimization(s - a); + let err = prevent_fp64_optimization(a - (s - v)) + prevent_fp64_optimization(b - v); +#endif + return vec2f(s, err); +} + +fn twoSub(a: f32, b: f32) -> vec2f { + let s = prevent_fp64_optimization(a - b); +#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND + let v = prevent_fp64_optimization((s * fp64arithmetic.ONE - a) * fp64arithmetic.ONE); + let err = + prevent_fp64_optimization((a - (s - v) * fp64arithmetic.ONE) * + fp64arithmetic.ONE * + fp64arithmetic.ONE * + fp64arithmetic.ONE) - + prevent_fp64_optimization(b + v); +#else + let v = prevent_fp64_optimization(s - a); + let err = prevent_fp64_optimization(a - (s - v)) - prevent_fp64_optimization(b + v); +#endif + return vec2f(s, err); +} + +fn twoSqr(a: f32) -> vec2f { + let prod = prevent_fp64_optimization(a * a); + let aFp64 = split(a); + let highProduct = prevent_fp64_optimization(aFp64.x * aFp64.x); + let crossProduct = prevent_fp64_optimization(2.0 * aFp64.x * aFp64.y); + let lowProduct = prevent_fp64_optimization(aFp64.y * aFp64.y); +#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND + let err = + (prevent_fp64_optimization(highProduct - prod) * fp64arithmetic.ONE + + crossProduct * fp64arithmetic.ONE * fp64arithmetic.ONE) + + lowProduct * fp64arithmetic.ONE * fp64arithmetic.ONE * fp64arithmetic.ONE; +#else + let err = ((prevent_fp64_optimization(highProduct - prod) + crossProduct) + lowProduct); +#endif + return vec2f(prod, err); +} + +fn twoProd(a: f32, b: f32) -> vec2f { + let prod = prevent_fp64_optimization(a * b); + let aFp64 = split(a); + let bFp64 = split(b); + let highProduct = prevent_fp64_optimization(aFp64.x * bFp64.x); + let crossProduct1 = prevent_fp64_optimization(aFp64.x * bFp64.y); + let crossProduct2 = prevent_fp64_optimization(aFp64.y * bFp64.x); + let lowProduct = prevent_fp64_optimization(aFp64.y * bFp64.y); +#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND + let err1 = (highProduct - prod) * fp64arithmetic.ONE; + let err2 = crossProduct1 * fp64arithmetic.ONE * fp64arithmetic.ONE; + let err3 = crossProduct2 * fp64arithmetic.ONE * fp64arithmetic.ONE * fp64arithmetic.ONE; + let err4 = + lowProduct * + fp64arithmetic.ONE * + fp64arithmetic.ONE * + fp64arithmetic.ONE * + fp64arithmetic.ONE; +#else + let err1 = highProduct - prod; + let err2 = crossProduct1; + let err3 = crossProduct2; + let err4 = lowProduct; +#endif + let err12InputA = prevent_fp64_optimization(err1); + let err12InputB = prevent_fp64_optimization(err2); + let err12 = prevent_fp64_optimization(err12InputA + err12InputB); + let err123InputA = prevent_fp64_optimization(err12); + let err123InputB = prevent_fp64_optimization(err3); + let err123 = prevent_fp64_optimization(err123InputA + err123InputB); + let err1234InputA = prevent_fp64_optimization(err123); + let err1234InputB = prevent_fp64_optimization(err4); + let err = prevent_fp64_optimization(err1234InputA + err1234InputB); + return vec2f(prod, err); +} + +fn sum_fp64(a: vec2f, b: vec2f) -> vec2f { + var s = twoSum(a.x, b.x); + let t = twoSum(a.y, b.y); + s.y = prevent_fp64_optimization(s.y + t.x); + s = quickTwoSum(s.x, s.y); + s.y = prevent_fp64_optimization(s.y + t.y); + s = quickTwoSum(s.x, s.y); + return s; +} + +fn sub_fp64(a: vec2f, b: vec2f) -> vec2f { + var s = twoSub(a.x, b.x); + let t = twoSub(a.y, b.y); + s.y = prevent_fp64_optimization(s.y + t.x); + s = quickTwoSum(s.x, s.y); + s.y = prevent_fp64_optimization(s.y + t.y); + s = quickTwoSum(s.x, s.y); + return s; +} + +fn mul_fp64(a: vec2f, b: vec2f) -> vec2f { + var prod = twoProd(a.x, b.x); + let crossProduct1 = prevent_fp64_optimization(a.x * b.y); + prod.y = prevent_fp64_optimization(prod.y + crossProduct1); +#ifdef LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND + prod = split2(prod); +#endif + prod = quickTwoSum(prod.x, prod.y); + let crossProduct2 = prevent_fp64_optimization(a.y * b.x); + prod.y = prevent_fp64_optimization(prod.y + crossProduct2); +#ifdef LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND + prod = split2(prod); +#endif + prod = quickTwoSum(prod.x, prod.y); + return prod; +} + +fn div_fp64(a: vec2f, b: vec2f) -> vec2f { + let xn = prevent_fp64_optimization(1.0 / b.x); + let yn = mul_fp64(a, vec2f(xn, fp64_runtime_zero())); + let diff = prevent_fp64_optimization(sub_fp64(a, mul_fp64(b, yn)).x); + let prod = twoProd(xn, diff); + return sum_fp64(yn, prod); +} + +fn sqrt_fp64(a: vec2f) -> vec2f { + if (a.x == 0.0 && a.y == 0.0) { + return vec2f(0.0, 0.0); + } + if (a.x < 0.0) { + let nanValue = fp64_nan(a.x); + return vec2f(nanValue, nanValue); + } + + let x = prevent_fp64_optimization(1.0 / sqrt(a.x)); + let yn = prevent_fp64_optimization(a.x * x); +#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND + let ynSqr = twoSqr(yn) * fp64arithmetic.ONE; +#else + let ynSqr = twoSqr(yn); +#endif + let diff = prevent_fp64_optimization(sub_fp64(a, ynSqr).x); + let prod = twoProd(prevent_fp64_optimization(x * 0.5), diff); +#ifdef LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND + return sum_fp64(split(yn), prod); +#else + return sum_fp64(vec2f(yn, 0.0), prod); +#endif +} +`;var IP={ONE:1,SPLIT:4097},gh={name:"fp64arithmetic",source:Ly,fs:ph,vs:ph,defaultUniforms:IP,uniformTypes:{ONE:"f32",SPLIT:"f32"},fp64ify:dh,fp64LowPart:Iy,fp64ifyMatrix4:Oy};var OP=[0,1,1,1],NP=`layout(std140) uniform pickingUniforms { + float isActive; + float isAttribute; + float isHighlightActive; + float useByteColors; + vec3 highlightedObjectColor; + vec4 highlightColor; +} picking; + +out vec4 picking_vRGBcolor_Avalid; + +// Normalize unsigned byte color to 0-1 range +vec3 picking_normalizeColor(vec3 color) { + return picking.useByteColors > 0.5 ? color / 255.0 : color; +} + +// Normalize unsigned byte color to 0-1 range +vec4 picking_normalizeColor(vec4 color) { + return picking.useByteColors > 0.5 ? color / 255.0 : color; +} + +bool picking_isColorZero(vec3 color) { + return dot(color, vec3(1.0)) < 0.00001; +} + +bool picking_isColorValid(vec3 color) { + return dot(color, vec3(1.0)) > 0.00001; +} + +// Check if this vertex is highlighted +bool isVertexHighlighted(vec3 vertexColor) { + vec3 highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor); + return + bool(picking.isHighlightActive) && picking_isColorZero(abs(vertexColor - highlightedObjectColor)); +} + +// Set the current picking color +void picking_setPickingColor(vec3 pickingColor) { + pickingColor = picking_normalizeColor(pickingColor); + + if (bool(picking.isActive)) { + // Use alpha as the validity flag. If pickingColor is [0, 0, 0] fragment is non-pickable + picking_vRGBcolor_Avalid.a = float(picking_isColorValid(pickingColor)); + + if (!bool(picking.isAttribute)) { + // Stores the picking color so that the fragment shader can render it during picking + picking_vRGBcolor_Avalid.rgb = pickingColor; + } + } else { + // Do the comparison with selected item color in vertex shader as it should mean fewer compares + picking_vRGBcolor_Avalid.a = float(isVertexHighlighted(pickingColor)); + } +} + +void picking_setPickingAttribute(float value) { + if (bool(picking.isAttribute)) { + picking_vRGBcolor_Avalid.r = value; + } +} + +void picking_setPickingAttribute(vec2 value) { + if (bool(picking.isAttribute)) { + picking_vRGBcolor_Avalid.rg = value; + } +} + +void picking_setPickingAttribute(vec3 value) { + if (bool(picking.isAttribute)) { + picking_vRGBcolor_Avalid.rgb = value; + } +} +`,DP=`layout(std140) uniform pickingUniforms { + float isActive; + float isAttribute; + float isHighlightActive; + float useByteColors; + vec3 highlightedObjectColor; + vec4 highlightColor; +} picking; + +in vec4 picking_vRGBcolor_Avalid; + +/* + * Returns highlight color if this item is selected. + */ +vec4 picking_filterHighlightColor(vec4 color) { + // If we are still picking, we don't highlight + if (picking.isActive > 0.5) { + return color; + } + + bool selected = bool(picking_vRGBcolor_Avalid.a); + + if (selected) { + // Blend in highlight color based on its alpha value + float highLightAlpha = picking.highlightColor.a; + float blendedAlpha = highLightAlpha + color.a * (1.0 - highLightAlpha); + float highLightRatio = highLightAlpha / blendedAlpha; + + vec3 blendedRGB = mix(color.rgb, picking.highlightColor.rgb, highLightRatio); + return vec4(blendedRGB, blendedAlpha); + } else { + return color; + } +} + +/* + * Returns picking color if picking enabled else unmodified argument. + */ +vec4 picking_filterPickingColor(vec4 color) { + if (bool(picking.isActive)) { + if (picking_vRGBcolor_Avalid.a == 0.0) { + discard; + } + return picking_vRGBcolor_Avalid; + } + return color; +} + +/* + * Returns picking color if picking is enabled if not + * highlight color if this item is selected, otherwise unmodified argument. + */ +vec4 picking_filterColor(vec4 color) { + vec4 highlightColor = picking_filterHighlightColor(color); + return picking_filterPickingColor(highlightColor); +} +`,Cc={props:{},uniforms:{},name:"picking",uniformTypes:{isActive:"f32",isAttribute:"f32",isHighlightActive:"f32",useByteColors:"f32",highlightedObjectColor:"vec3",highlightColor:"vec4"},defaultUniforms:{isActive:!1,isAttribute:!1,isHighlightActive:!1,useByteColors:!0,highlightedObjectColor:[0,0,0],highlightColor:OP},vs:NP,fs:DP,getUniforms:LP};function LP(t={},e){let r={},i=Ny(t.useByteColors,!0);if(t.highlightedObjectColor!==void 0)if(t.highlightedObjectColor===null)r.isHighlightActive=!1;else{r.isHighlightActive=!0;let n=t.highlightedObjectColor.slice(0,3);r.highlightedObjectColor=n}return t.highlightColor&&(r.highlightColor=Dy(t.highlightColor,i)),t.isActive!==void 0&&(r.isActive=!!t.isActive,r.isAttribute=!!t.isAttribute),t.useByteColors!==void 0&&(r.useByteColors=!!t.useByteColors),r}var ZM=`struct LayerUniforms { + opacity: f32, +}; + +@group(0) @binding(auto) +var layer: LayerUniforms; +`,Bx=`layout(std140) uniform layerUniforms { + uniform float opacity; +} layer; +`,Jh={name:"layer",source:ZM,vs:Bx,fs:Bx,getUniforms:t=>({opacity:Math.pow(t.opacity,.45454545454545453)}),uniformTypes:{opacity:"f32"}};var QM=` + +@must_use +fn deckgl_premultiplied_alpha(fragColor: vec4) -> vec4 { + return vec4(fragColor.rgb * fragColor.a, fragColor.a); +}; +`,mn={name:"color",dependencies:[],source:QM,getUniforms:t=>({})};var JM=`const SMOOTH_EDGE_RADIUS: f32 = 0.5; + +struct VertexGeometry { + position: vec4, + worldPosition: vec3, + worldPositionAlt: vec3, + normal: vec3, + uv: vec2, + pickingColor: vec3, +}; + +var geometry_: VertexGeometry = VertexGeometry( + vec4(0.0, 0.0, 1.0, 0.0), + vec3(0.0, 0.0, 0.0), + vec3(0.0, 0.0, 0.0), + vec3(0.0, 0.0, 0.0), + vec2(0.0, 0.0), + vec3(0.0, 0.0, 0.0) +); + +struct FragmentGeometry { + uv: vec2, +}; + +var fragmentGeometry: FragmentGeometry; + +fn smoothedge(edge: f32, x: f32) -> f32 { + return smoothstep(edge - SMOOTH_EDGE_RADIUS, edge + SMOOTH_EDGE_RADIUS, x); +} +`,kx="#define SMOOTH_EDGE_RADIUS 0.5",eI=`${kx} + +struct VertexGeometry { + vec4 position; + vec3 worldPosition; + vec3 worldPositionAlt; + vec3 normal; + vec2 uv; + vec3 pickingColor; +} geometry = VertexGeometry( + vec4(0.0, 0.0, 1.0, 0.0), + vec3(0.0), + vec3(0.0), + vec3(0.0), + vec2(0.0), + vec3(0.0) +); +`,tI=`${kx} + +struct FragmentGeometry { + vec2 uv; +} geometry; + +float smoothedge(float edge, float x) { + return smoothstep(edge - SMOOTH_EDGE_RADIUS, edge + SMOOTH_EDGE_RADIUS, x); +} +`,Yc={name:"geometry",source:JM,vs:eI,fs:tI};var Q;(function(t){t[t.Start=1]="Start",t[t.Move=2]="Move",t[t.End=4]="End",t[t.Cancel=8]="Cancel"})(Q||(Q={}));var ie;(function(t){t[t.None=0]="None",t[t.Left=1]="Left",t[t.Right=2]="Right",t[t.Up=4]="Up",t[t.Down=8]="Down",t[t.Horizontal=3]="Horizontal",t[t.Vertical=12]="Vertical",t[t.All=15]="All"})(ie||(ie={}));var B;(function(t){t[t.Possible=1]="Possible",t[t.Began=2]="Began",t[t.Changed=4]="Changed",t[t.Ended=8]="Ended",t[t.Recognized=8]="Recognized",t[t.Cancelled=16]="Cancelled",t[t.Failed=32]="Failed"})(B||(B={}));var Ux="compute",ep="auto",Zo="manipulation",_i="none",Qo="pan-x",Jo="pan-y";function tp(t){if(t.includes(_i))return _i;let e=t.includes(Qo),r=t.includes(Jo);return e&&r?_i:e||r?e?Qo:Jo:t.includes(Zo)?Zo:ep}var es=class{constructor(e,r){this.actions="",this.manager=e,this.set(r)}set(e){e===Ux&&(e=this.compute()),this.manager.element&&(this.manager.element.style.touchAction=e,this.actions=e)}update(){this.set(this.manager.options.touchAction)}compute(){let e=[];for(let r of this.manager.recognizers)r.options.enable&&(e=e.concat(r.getTouchAction()));return tp(e.join(" "))}};function _n(t){return t.trim().split(/\s+/g)}function Xc(t,e,r){if(t)for(let i of _n(e))t.addEventListener(i,r,!1)}function Gc(t,e,r){if(t)for(let i of _n(e))t.removeEventListener(i,r,!1)}function rp(t){return(t.ownerDocument||t).defaultView}function ip(t,e){let r=t;for(;r;){if(r===e)return!0;r=r.parentNode}return!1}function qc(t){let e=t.length;if(e===1)return{x:Math.round(t[0].clientX),y:Math.round(t[0].clientY)};let r=0,i=0,n=0;for(;n=Math.abs(e)?t<0?ie.Left:ie.Right:e<0?ie.Up:ie.Down}function Wx(t,e){let r=e.center,i=t.offsetDelta,n=t.prevDelta,o=t.prevInput;return(e.eventType===Q.Start||o?.eventType===Q.End)&&(n=t.prevDelta={x:o?.deltaX||0,y:o?.deltaY||0},i=t.offsetDelta={x:r.x,y:r.y}),{deltaX:n.x+(r.x-i.x),deltaY:n.y+(r.y-i.y)}}function Qc(t,e,r){return{x:e/t||0,y:r/t||0}}function Vx(t,e){return op(e[0],e[1])/op(t[0],t[1])}function jx(t,e){return sp(e[1],e[0])-sp(t[1],t[0])}function $x(t,e){let r=t.lastInterval||e,i=e.timeStamp-r.timeStamp,n,o,s,a;if(e.eventType!==Q.Cancel&&(i>25||r.velocity===void 0)){let c=e.deltaX-r.deltaX,l=e.deltaY-r.deltaY,f=Qc(i,c,l);o=f.x,s=f.y,n=Math.abs(f.x)>Math.abs(f.y)?f.x:f.y,a=Zc(c,l),t.lastInterval=e}else n=r.velocity,o=r.velocityX,s=r.velocityY,a=r.direction;e.velocity=n,e.velocityX=o,e.velocityY=s,e.direction=a}function Hx(t,e){let{session:r}=t,{pointers:i}=e,{length:n}=i;r.firstInput||(r.firstInput=np(e)),n>1&&!r.firstMultiple?r.firstMultiple=np(e):n===1&&(r.firstMultiple=!1);let{firstInput:o,firstMultiple:s}=r,a=s?s.center:o.center,c=e.center=qc(i);e.timeStamp=Date.now(),e.deltaTime=e.timeStamp-o.timeStamp,e.angle=zx(a,c),e.distance=Kc(a,c);let{deltaX:l,deltaY:f}=Wx(r,e);e.deltaX=l,e.deltaY=f,e.offsetDirection=Zc(e.deltaX,e.deltaY);let u=Qc(e.deltaTime,e.deltaX,e.deltaY);e.overallVelocityX=u.x,e.overallVelocityY=u.y,e.overallVelocity=Math.abs(u.x)>Math.abs(u.y)?u.x:u.y,e.scale=s?Vx(s.pointers,i):1,e.rotation=s?jx(s.pointers,i):0,e.maxPointers=r.prevInput?e.pointers.length>r.prevInput.maxPointers?e.pointers.length:r.prevInput.maxPointers:e.pointers.length;let d=t.element;return ip(e.srcEvent.target,d)&&(d=e.srcEvent.target),e.target=d,$x(r,e),e}function Yx(t,e,r){let i=r.pointers.length,n=r.changedPointers.length,o=e&Q.Start&&i-n===0,s=e&(Q.End|Q.Cancel)&&i-n===0;r.isFirst=!!o,r.isFinal=!!s,o&&(t.session={}),r.eventType=e;let a=Hx(t,r);t.emit("hammer.input",a),t.recognize(a),t.session.prevInput=a}var ts=class{constructor(e){this.evEl="",this.evWin="",this.evTarget="",this.domHandler=r=>{this.manager.options.enable&&this.handler(r)},this.manager=e,this.element=e.element,this.target=e.options.inputTarget||e.element}callback(e,r){Yx(this.manager,e,r)}init(){Xc(this.element,this.evEl,this.domHandler),Xc(this.target,this.evTarget,this.domHandler),Xc(rp(this.element),this.evWin,this.domHandler)}destroy(){Gc(this.element,this.evEl,this.domHandler),Gc(this.target,this.evTarget,this.domHandler),Gc(rp(this.element),this.evWin,this.domHandler)}};var iI={pointerdown:Q.Start,pointermove:Q.Move,pointerup:Q.End,pointercancel:Q.Cancel,pointerout:Q.Cancel},nI="pointerdown",oI="pointermove pointerup pointercancel",rs=class extends ts{constructor(e){super(e),this.evEl=nI,this.evWin=oI,this.store=this.manager.session.pointerEvents=[],this.init()}handler(e){let{store:r}=this,i=!1,n=iI[e.type],o=e.pointerType,s=o==="touch",a=r.findIndex(c=>c.pointerId===e.pointerId);n&Q.Start&&(e.buttons||s)?a<0&&(r.push(e),a=r.length-1):n&(Q.End|Q.Cancel)&&(i=!0),!(a<0)&&(r[a]=e,this.callback(n,{pointers:r,changedPointers:[e],eventType:n,pointerType:o,srcEvent:e}),i&&r.splice(a,1))}};var sI=["","webkit","Moz","MS","ms","o"];function Xx(t,e){let r=e[0].toUpperCase()+e.slice(1);for(let i of sI){let n=i?i+r:e;if(n in t)return n}}var aI=1,Gx=2,qx={touchAction:"compute",enable:!0,inputTarget:null,cssProps:{userSelect:"none",userDrag:"none",touchCallout:"none",tapHighlightColor:"rgba(0,0,0,0)"}},is=class{constructor(e,r){this.options={...qx,...r,cssProps:{...qx.cssProps,...r.cssProps},inputTarget:r.inputTarget||e},this.handlers={},this.session={},this.recognizers=[],this.oldCssProps={},this.element=e,this.input=new rs(this),this.touchAction=new es(this,this.options.touchAction),this.toggleCssProps(!0)}set(e){return Object.assign(this.options,e),e.touchAction&&this.touchAction.update(),e.inputTarget&&(this.input.destroy(),this.input.target=e.inputTarget,this.input.init()),this}stop(e){this.session.stopped=e?Gx:aI}recognize(e){let{session:r}=this;if(r.stopped)return;this.session.prevented&&e.srcEvent.preventDefault();let i,{recognizers:n}=this,{curRecognizer:o}=r;(!o||o&&o.state&B.Recognized)&&(o=r.curRecognizer=null);let s=0;for(;s-1&&this.requireFail.splice(i,1)}return this}hasRequireFailures(){return!!this.requireFail.find(e=>e.options.enable)}canRecognizeWith(e){return!!this.simultaneous[e.id]}emit(e){if(!e)return;let{state:r}=this;r=B.Ended&&this.manager.emit(this.options.event+ap(r),e)}tryEmit(e){this.canEmit()?this.emit(e):this.state=B.Failed}canEmit(){let e=0;for(;e{this.state=B.Recognized,this.tryEmit(this._input)},r.interval),B.Began):B.Recognized}return B.Failed}failTimeout(){return this._timer=setTimeout(()=>{this.state=B.Failed},this.options.interval),B.Failed}reset(){clearTimeout(this._timer)}emit(e){this.state===B.Recognized&&(e.tapCount=this.count,this.manager.emit(this.options.event,e))}};var lI=["","start","move","end","cancel","up","down","left","right"],Lr=class extends ar{constructor(e={}){super({enable:!0,pointers:1,event:"pan",threshold:10,direction:ie.All,...e}),this.pX=null,this.pY=null}getTouchAction(){let{options:{direction:e}}=this,r=[];return e&ie.Horizontal&&r.push(Jo),e&ie.Vertical&&r.push(Qo),r}getEventNames(){return lI.map(e=>this.options.event+e)}directionTest(e){let{options:r}=this,i=!0,{distance:n}=e,{direction:o}=e,s=e.deltaX,a=e.deltaY;return o&r.direction||(r.direction&ie.Horizontal?(o=s===0?ie.None:s<0?ie.Left:ie.Right,i=s!==this.pX,n=Math.abs(e.deltaX)):(o=a===0?ie.None:a<0?ie.Up:ie.Down,i=a!==this.pY,n=Math.abs(e.deltaY))),e.direction=o,i&&n>r.threshold&&!!(o&r.direction)}attrTest(e){return super.attrTest(e)&&(!!(this.state&B.Began)||!(this.state&B.Began)&&this.directionTest(e))}emit(e){this.pX=e.deltaX,this.pY=e.deltaY;let r=ie[e.direction].toLowerCase();r&&(e.additionalEvent=this.options.event+r),super.emit(e)}};var fI=["","start","move","end","cancel","in","out"],yn=class extends ar{constructor(e={}){super({enable:!0,event:"pinch",threshold:0,pointers:2,...e})}getTouchAction(){return[_i]}getEventNames(){return fI.map(e=>this.options.event+e)}attrTest(e){return super.attrTest(e)&&(Math.abs(e.scale-1)>this.options.threshold||!!(this.state&B.Began))}emit(e){if(e.scale!==1){let r=e.scale<1?"in":"out";e.additionalEvent=this.options.event+r}super.emit(e)}};var Bt=class{constructor(e,r,i){this.element=e,this.callback=r,this.options=i}};var Zx=typeof navigator<"u"&&navigator.userAgent?navigator.userAgent.toLowerCase():"",GH=typeof window<"u"?window:global;var pI=Zx.indexOf("firefox")!==-1,Qx=4.000244140625,gI=40,mI=.25,Jc=class extends Bt{constructor(e,r,i){super(e,r,{enable:!0,...i}),this.handleEvent=n=>{if(!this.options.enable)return;let o=n.deltaY;globalThis.WheelEvent&&(pI&&n.deltaMode===globalThis.WheelEvent.DOM_DELTA_PIXEL&&(o/=globalThis.devicePixelRatio),n.deltaMode===globalThis.WheelEvent.DOM_DELTA_LINE&&(o*=gI)),o!==0&&o%Qx===0&&(o=Math.floor(o/Qx)),n.shiftKey&&o&&(o=o*mI),this.callback({type:"wheel",center:{x:n.clientX,y:n.clientY},delta:-o,srcEvent:n,pointerType:"mouse",target:n.target})},e.addEventListener("wheel",this.handleEvent,{passive:!1})}destroy(){this.element.removeEventListener("wheel",this.handleEvent)}enableEventType(e,r){e==="wheel"&&(this.options.enable=r)}};var Jx=["mousedown","mousemove","mouseup","mouseover","mouseout","mouseleave"],el=class extends Bt{constructor(e,r,i){super(e,r,{enable:!0,...i}),this.handleEvent=o=>{this.handleOverEvent(o),this.handleOutEvent(o),this.handleEnterEvent(o),this.handleLeaveEvent(o),this.handleMoveEvent(o)},this.pressed=!1;let{enable:n}=this.options;this.enableMoveEvent=n,this.enableLeaveEvent=n,this.enableEnterEvent=n,this.enableOutEvent=n,this.enableOverEvent=n,Jx.forEach(o=>e.addEventListener(o,this.handleEvent))}destroy(){Jx.forEach(e=>this.element.removeEventListener(e,this.handleEvent))}enableEventType(e,r){switch(e){case"pointermove":this.enableMoveEvent=r;break;case"pointerover":this.enableOverEvent=r;break;case"pointerout":this.enableOutEvent=r;break;case"pointerenter":this.enableEnterEvent=r;break;case"pointerleave":this.enableLeaveEvent=r;break;default:}}handleOverEvent(e){this.enableOverEvent&&e.type==="mouseover"&&this._emit("pointerover",e)}handleOutEvent(e){this.enableOutEvent&&e.type==="mouseout"&&this._emit("pointerout",e)}handleEnterEvent(e){this.enableEnterEvent&&e.type==="mouseenter"&&this._emit("pointerenter",e)}handleLeaveEvent(e){this.enableLeaveEvent&&e.type==="mouseleave"&&this._emit("pointerleave",e)}handleMoveEvent(e){if(this.enableMoveEvent)switch(e.type){case"mousedown":e.button>=0&&(this.pressed=!0);break;case"mousemove":e.buttons===0&&(this.pressed=!1),this.pressed||this._emit("pointermove",e);break;case"mouseup":this.pressed=!1;break;default:}}_emit(e,r){this.callback({type:e,center:{x:r.clientX,y:r.clientY},srcEvent:r,pointerType:"mouse",target:r.target})}};var eb=["keydown","keyup"],tl=class extends Bt{constructor(e,r,i){super(e,r,{enable:!0,tabIndex:0,...i}),this.handleEvent=n=>{let o=n.target||n.srcElement;o.tagName==="INPUT"&&o.type==="text"||o.tagName==="TEXTAREA"||(this.enableDownEvent&&n.type==="keydown"&&this.callback({type:"keydown",srcEvent:n,key:n.key,target:n.target}),this.enableUpEvent&&n.type==="keyup"&&this.callback({type:"keyup",srcEvent:n,key:n.key,target:n.target}))},this.enableDownEvent=this.options.enable,this.enableUpEvent=this.options.enable,e.tabIndex=this.options.tabIndex,e.style.outline="none",eb.forEach(n=>e.addEventListener(n,this.handleEvent))}destroy(){eb.forEach(e=>this.element.removeEventListener(e,this.handleEvent))}enableEventType(e,r){e==="keydown"&&(this.enableDownEvent=r),e==="keyup"&&(this.enableUpEvent=r)}};var rl=class extends Bt{constructor(e,r,i){super(e,r,i),this.handleEvent=n=>{this.options.enable&&this.callback({type:"contextmenu",center:{x:n.clientX,y:n.clientY},srcEvent:n,pointerType:"mouse",target:n.target})},e.addEventListener("contextmenu",this.handleEvent)}destroy(){this.element.removeEventListener("contextmenu",this.handleEvent)}enableEventType(e,r){e==="contextmenu"&&(this.options.enable=r)}};var _I={pointerdown:1,pointermove:2,pointerup:4,mousedown:1,mousemove:2,mouseup:4},yI=0,xI=1,bI=2,TI=1,wI=2,SI=4;function tb(t){let e=_I[t.srcEvent.type];if(!e)return null;let{buttons:r,button:i}=t.srcEvent,n=!1,o=!1,s=!1;return e===2?(n=!!(r&TI),o=!!(r&SI),s=!!(r&wI)):(n=i===yI,o=i===xI,s=i===bI),{leftButton:n,middleButton:o,rightButton:s}}function rb(t,e){let r=t.center;if(!r)return null;let i=e.getBoundingClientRect(),n=i.width/e.offsetWidth||1,o=i.height/e.offsetHeight||1,s={x:(r.x-i.left-e.clientLeft)/n,y:(r.y-i.top-e.clientTop)/o};return{center:r,offsetCenter:s}}var AI={srcElement:"root",priority:0},il=class{constructor(e,r){this.handleEvent=i=>{if(this.isEmpty())return;let n=this._normalizeEvent(i),o=i.srcEvent.target;for(;o&&o!==n.rootElement;){if(this._emit(n,o),n.handled)return;o=o.parentNode}this._emit(n,"root")},this.eventManager=e,this.recognizerName=r,this.handlers=[],this.handlersByElement=new Map,this._active=!1}isEmpty(){return!this._active}add(e,r,i,n=!1,o=!1){let{handlers:s,handlersByElement:a}=this,c={...AI,...i},l=a.get(c.srcElement);l||(l=[],a.set(c.srcElement,l));let f={type:e,handler:r,srcElement:c.srcElement,priority:c.priority};n&&(f.once=!0),o&&(f.passive=!0),s.push(f),this._active=this._active||!f.passive;let u=l.length-1;for(;u>=0&&!(l[u].priority>=f.priority);)u--;l.splice(u+1,0,f)}remove(e,r){let{handlers:i,handlersByElement:n}=this;for(let o=i.length-1;o>=0;o--){let s=i[o];if(s.type===e&&s.handler===r){i.splice(o,1);let a=n.get(s.srcElement);a.splice(a.indexOf(s),1),a.length===0&&n.delete(s.srcElement)}}this._active=i.some(o=>!o.passive)}_emit(e,r){let i=this.handlersByElement.get(r);if(i){let n=!1,o=()=>{e.handled=!0},s=()=>{e.handled=!0,n=!0},a=[];for(let c=0;c{e.srcEvent.preventDefault()},stopImmediatePropagation:null,stopPropagation:null,handled:!1,rootElement:r}}};function vI(t){if("recognizer"in t)return t;let e,r=Array.isArray(t)?[...t]:[t];if(typeof r[0]=="function"){let i=r.shift(),n=r.shift()||{};e=new i(n)}else e=r.shift();return{recognizer:e,recognizeWith:typeof r[0]=="string"?[r[0]]:r[0],requireFailure:typeof r[1]=="string"?[r[1]]:r[1]}}var ns=class{constructor(e=null,r={}){if(this._onBasicInput=i=>{this.manager.emit(i.srcEvent.type,i)},this._onOtherEvent=i=>{this.manager.emit(i.type,i)},this.options={recognizers:[],events:{},touchAction:"compute",tabIndex:0,cssProps:{},...r},this.events=new Map,this.element=e,!!e){this.manager=new is(e,this.options);for(let i of this.options.recognizers){let{recognizer:n,recognizeWith:o,requireFailure:s}=vI(i);this.manager.add(n),o&&n.recognizeWith(o),s&&n.requireFailure(s)}this.manager.on("hammer.input",this._onBasicInput),this.wheelInput=new Jc(e,this._onOtherEvent,{enable:!1}),this.moveInput=new el(e,this._onOtherEvent,{enable:!1}),this.keyInput=new tl(e,this._onOtherEvent,{enable:!1,tabIndex:r.tabIndex}),this.contextmenuInput=new rl(e,this._onOtherEvent,{enable:!1}),this.on(this.options.events)}}getElement(){return this.element}destroy(){this.element&&(this.wheelInput.destroy(),this.moveInput.destroy(),this.keyInput.destroy(),this.contextmenuInput.destroy(),this.manager.destroy())}on(e,r,i){this._addEventHandler(e,r,i,!1)}once(e,r,i){this._addEventHandler(e,r,i,!0)}watch(e,r,i){this._addEventHandler(e,r,i,!1,!0)}off(e,r){this._removeEventHandler(e,r)}_toggleRecognizer(e,r){let{manager:i}=this;if(!i)return;let n=i.get(e);n&&(n.set({enable:r}),i.touchAction.update()),this.wheelInput?.enableEventType(e,r),this.moveInput?.enableEventType(e,r),this.keyInput?.enableEventType(e,r),this.contextmenuInput?.enableEventType(e,r)}_addEventHandler(e,r,i,n,o){if(typeof e!="string"){i=r;for(let[l,f]of Object.entries(e))this._addEventHandler(l,f,i,n,o);return}let{manager:s,events:a}=this;if(!s)return;let c=a.get(e);if(!c){let l=this._getRecognizerName(e)||e;c=new il(this,l),a.set(e,c),s&&s.on(e,c.handleEvent)}c.add(e,r,i,n,o),c.isEmpty()||this._toggleRecognizer(c.recognizerName,!0)}_removeEventHandler(e,r){if(typeof e!="string"){for(let[o,s]of Object.entries(e))this._removeEventHandler(o,s);return}let{events:i}=this,n=i.get(e);if(n&&(n.remove(e,r),n.isEmpty())){let{recognizerName:o}=n,s=!1;for(let a of i.values())if(a.recognizerName===o&&!a.isEmpty()){s=!0;break}s||this._toggleRecognizer(o,!1)}}_getRecognizerName(e){return this.manager.recognizers.find(r=>r.getEventNames().includes(e))?.options.event}};var cp={DEFAULT:"default",LNGLAT:"lnglat",METER_OFFSETS:"meter-offsets",LNGLAT_OFFSETS:"lnglat-offsets",CARTESIAN:"cartesian"};Object.defineProperty(cp,"IDENTITY",{get:()=>(F.deprecated("COORDINATE_SYSTEM.IDENTITY","COORDINATE_SYSTEM.CARTESIAN")(),cp.CARTESIAN)});var _e={WEB_MERCATOR:1,GLOBE:2,WEB_MERCATOR_AUTO_OFFSET:4,IDENTITY:0},je={common:0,meters:1,pixels:2},xn={click:"onClick",dblclick:"onClick",panstart:"onDragStart",panmove:"onDrag",panend:"onDragEnd"},lp={multipan:[Lr,{threshold:10,direction:ie.Vertical,pointers:2}],pinch:[yn,{},null,["multipan"]],pan:[Lr,{threshold:1},["pinch"],["multipan"]],dblclick:[yi,{event:"dblclick",taps:2}],click:[yi,{event:"click"},null,["dblclick"]]};function EI(t,e){if(t===e)return!0;if(Array.isArray(t)){let r=t.length;if(!e||e.length!==r)return!1;for(let i=0;i{for(let n in i)if(!EI(i[n],e[n])){r=t(i),e=i;break}return r}}var ib=[0,0,0,0],RI=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0],nb=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],CI=[0,0,0],ob=[0,0,0],PI={default:-1,cartesian:0,lnglat:1,"meter-offsets":2,"lnglat-offsets":3};function xi(t){let e=PI[t];if(e===void 0)throw new Error(`Invalid coordinateSystem: ${t}`);return e}var MI=kt(OI);function fp(t,e,r=ob){r.length<3&&(r=[r[0],r[1],0]);let i=r,n,o=!0;switch(e==="lnglat-offsets"||e==="meter-offsets"?n=r:n=t.isGeospatial?[Math.fround(t.longitude),Math.fround(t.latitude),0]:null,t.projectionMode){case _e.WEB_MERCATOR:(e==="lnglat"||e==="cartesian")&&(n=[0,0,0],o=!1);break;case _e.WEB_MERCATOR_AUTO_OFFSET:e==="lnglat"?i=n:e==="cartesian"&&(i=[Math.fround(t.center[0]),Math.fround(t.center[1]),0],n=t.unprojectPosition(i),i[0]-=r[0],i[1]-=r[1],i[2]-=r[2]);break;case _e.IDENTITY:i=t.position.map(Math.fround),i[2]=i[2]||0;break;case _e.GLOBE:o=!1,n=null;break;default:o=!1}return{geospatialOrigin:n,shaderCoordinateOrigin:i,offsetMode:o}}function II(t,e,r){let{viewMatrixUncentered:i,projectionMatrix:n}=t,{viewMatrix:o,viewProjectionMatrix:s}=t,a=ib,c=ib,l=t.cameraPosition,{geospatialOrigin:f,shaderCoordinateOrigin:u,offsetMode:d}=fp(t,e,r);return d&&(c=t.projectPosition(f||u),l=[l[0]-c[0],l[1]-c[1],l[2]-c[2]],c[3]=1,a=Ze.transformMat4([],c,s),o=i||o,s=ee.multiply([],n,o),s=ee.multiply([],s,RI)),{viewMatrix:o,viewProjectionMatrix:s,projectionCenter:a,originCommon:c,cameraPosCommon:l,shaderCoordinateOrigin:u,geospatialOrigin:f}}function sb({viewport:t,devicePixelRatio:e=1,modelMatrix:r=null,coordinateSystem:i="default",coordinateOrigin:n=ob,autoWrapLongitude:o=!1}){i==="default"&&(i=t.isGeospatial?"lnglat":"cartesian");let s=MI({viewport:t,devicePixelRatio:e,coordinateSystem:i,coordinateOrigin:n});return s.wrapLongitude=o,s.modelMatrix=r||nb,s}function OI({viewport:t,devicePixelRatio:e,coordinateSystem:r,coordinateOrigin:i}){let{projectionCenter:n,viewProjectionMatrix:o,originCommon:s,cameraPosCommon:a,shaderCoordinateOrigin:c,geospatialOrigin:l}=II(t,r,i),f=t.getDistanceScales(),u=[t.width*e,t.height*e],d=Ze.transformMat4([],[0,0,-t.focalDistance,1],t.projectionMatrix)[3]||1,h={coordinateSystem:xi(r),projectionMode:t.projectionMode,coordinateOrigin:c,commonOrigin:s.slice(0,3),center:n,pseudoMeters:!!t._pseudoMeters,viewportSize:u,devicePixelRatio:e,focalDistance:d,commonUnitsPerMeter:f.unitsPerMeter,commonUnitsPerWorldUnit:f.unitsPerMeter,commonUnitsPerWorldUnit2:CI,scale:t.scale,wrapLongitude:!1,viewProjectionMatrix:o,modelMatrix:nb,cameraPosition:a};if(l){let p=t.getDistanceScales(l);switch(r){case"meter-offsets":h.commonUnitsPerWorldUnit=p.unitsPerMeter,h.commonUnitsPerWorldUnit2=p.unitsPerMeter2;break;case"lnglat":case"lnglat-offsets":t._pseudoMeters||(h.commonUnitsPerMeter=p.unitsPerMeter),h.commonUnitsPerWorldUnit=p.unitsPerDegree,h.commonUnitsPerWorldUnit2=p.unitsPerDegree2;break;case"cartesian":h.commonUnitsPerWorldUnit=[1,1,p.unitsPerMeter[2]],h.commonUnitsPerWorldUnit2=[0,0,p.unitsPerMeter2[2]];break;default:break}}return h}var NI=["default","lnglat","meter-offsets","lnglat-offsets","cartesian"],DI=NI.map(t=>`const COORDINATE_SYSTEM_${t.toUpperCase().replaceAll("-","_")}: i32 = ${xi(t)};`).join(""),LI=Object.keys(_e).map(t=>`const PROJECTION_MODE_${t}: i32 = ${_e[t]};`).join(""),FI=Object.keys(je).map(t=>`const UNIT_${t.toUpperCase()}: i32 = ${je[t]};`).join(""),BI=`${DI} +${LI} +${FI} + +const TILE_SIZE: f32 = 512.0; +const PI: f32 = 3.1415926536; +const WORLD_SCALE: f32 = TILE_SIZE / (PI * 2.0); +const ZERO_64_LOW: vec3 = vec3(0.0, 0.0, 0.0); +const EARTH_RADIUS: f32 = 6370972.0; // meters +const GLOBE_RADIUS: f32 = 256.0; + +// ----------------------------------------------------------------------------- +// Uniform block (converted from GLSL uniform block) +// ----------------------------------------------------------------------------- +struct ProjectUniforms { + wrapLongitude: i32, + coordinateSystem: i32, + commonUnitsPerMeter: vec3, + projectionMode: i32, + scale: f32, + commonUnitsPerWorldUnit: vec3, + commonUnitsPerWorldUnit2: vec3, + center: vec4, + modelMatrix: mat4x4, + viewProjectionMatrix: mat4x4, + viewportSize: vec2, + devicePixelRatio: f32, + focalDistance: f32, + cameraPosition: vec3, + coordinateOrigin: vec3, + commonOrigin: vec3, + pseudoMeters: i32, +}; + +@group(0) @binding(auto) +var project: ProjectUniforms; + +// ----------------------------------------------------------------------------- +// Geometry data shared across the project helpers. +// The active layer shader is responsible for populating this private module +// state before calling the project functions below. +// ----------------------------------------------------------------------------- + +// Structure to carry additional geometry data used by deck.gl filters. +struct Geometry { + worldPosition: vec3, + worldPositionAlt: vec3, + position: vec4, + normal: vec3, + uv: vec2, + pickingColor: vec3, +}; + +var geometry: Geometry; +`,ab=`${BI} + +// ----------------------------------------------------------------------------- +// Functions +// ----------------------------------------------------------------------------- + +// Returns an adjustment factor for commonUnitsPerMeter +fn _project_size_at_latitude(lat: f32) -> f32 { + let y = clamp(lat, -89.9, 89.9); + return 1.0 / cos(radians(y)); +} + +// Overloaded version: scales a value in meters at a given latitude. +fn _project_size_at_latitude_m(meters: f32, lat: f32) -> f32 { + return meters * project.commonUnitsPerMeter.z * _project_size_at_latitude(lat); +} + +// Computes a non-linear scale factor based on geometry. +// (Note: This function relies on "geometry" being provided.) +fn project_size() -> f32 { + if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR && + project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT && + project.pseudoMeters == 0) { + if (geometry.position.w == 0.0) { + return _project_size_at_latitude(geometry.worldPosition.y); + } + let y: f32 = geometry.position.y / TILE_SIZE * 2.0 - 1.0; + let y2 = y * y; + let y4 = y2 * y2; + let y6 = y4 * y2; + return 1.0 + 4.9348 * y2 + 4.0587 * y4 + 1.5642 * y6; + } + return 1.0; +} + +// Overloads to scale offsets (meters to world units) +fn project_size_float(meters: f32) -> f32 { + return meters * project.commonUnitsPerMeter.z * project_size(); +} + +fn project_size_vec2(meters: vec2) -> vec2 { + return meters * project.commonUnitsPerMeter.xy * project_size(); +} + +fn project_size_vec3(meters: vec3) -> vec3 { + return meters * project.commonUnitsPerMeter * project_size(); +} + +fn project_size_vec4(meters: vec4) -> vec4 { + return vec4(meters.xyz * project.commonUnitsPerMeter, meters.w); +} + +// Returns a rotation matrix aligning the z\u2011axis with the given up vector. +fn project_get_orientation_matrix(up: vec3) -> mat3x3 { + let uz = normalize(up); + let ux = select( + vec3(1.0, 0.0, 0.0), + normalize(vec3(uz.y, -uz.x, 0.0)), + abs(uz.z) == 1.0 + ); + let uy = cross(uz, ux); + return mat3x3(ux, uy, uz); +} + +// Since WGSL does not support "out" parameters, we return a struct. +struct RotationResult { + needsRotation: bool, + transform: mat3x3, +}; + +fn project_needs_rotation(commonPosition: vec3) -> RotationResult { + if (project.projectionMode == PROJECTION_MODE_GLOBE) { + return RotationResult(true, project_get_orientation_matrix(commonPosition)); + } else { + return RotationResult(false, mat3x3()); // identity alternative if needed + }; +} + +// Projects a normal vector from the current coordinate system to world space. +fn project_normal(vector: vec3) -> vec3 { + let normal_modelspace = project.modelMatrix * vec4(vector, 0.0); + var n = normalize(normal_modelspace.xyz * project.commonUnitsPerMeter); + let rotResult = project_needs_rotation(geometry.position.xyz); + if (rotResult.needsRotation) { + n = rotResult.transform * n; + } + return n; +} + +// Applies a scale offset based on y-offset (dy) +fn project_offset_(offset: vec4) -> vec4 { + let dy: f32 = offset.y; + let commonUnitsPerWorldUnit = project.commonUnitsPerWorldUnit + project.commonUnitsPerWorldUnit2 * dy; + return vec4(offset.xyz * commonUnitsPerWorldUnit, offset.w); +} + +// Projects lng/lat coordinates to a unit tile [0,1] +fn project_mercator_(lnglat: vec2) -> vec2 { + var x = lnglat.x; + if (project.wrapLongitude != 0) { + x = ((x + 180.0) % 360.0) - 180.0; + } + let y = clamp(lnglat.y, -89.9, 89.9); + return vec2( + radians(x) + PI, + PI + log(tan(PI * 0.25 + radians(y) * 0.5)) + ) * WORLD_SCALE; +} + +// Projects lng/lat/z coordinates for a globe projection. +fn project_globe_(lnglatz: vec3) -> vec3 { + let lambda = radians(lnglatz.x); + let phi = radians(lnglatz.y); + let cosPhi = cos(phi); + let D = (lnglatz.z / EARTH_RADIUS + 1.0) * GLOBE_RADIUS; + return vec3( + sin(lambda) * cosPhi, + -cos(lambda) * cosPhi, + sin(phi) + ) * D; +} + +// Projects positions (with an optional 64-bit low part) from the input +// coordinate system to the common space. +fn project_position_vec4_f64(position: vec4, position64Low: vec3) -> vec4 { + var position_world = project.modelMatrix * position; + + // Work around for a Mac+NVIDIA bug: + if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR) { + if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) { + return vec4( + project_mercator_(position_world.xy), + _project_size_at_latitude_m(position_world.z, position_world.y), + position_world.w + ); + } + if (project.coordinateSystem == COORDINATE_SYSTEM_CARTESIAN) { + position_world = vec4f(position_world.xyz + project.coordinateOrigin, position_world.w); + } + } + if (project.projectionMode == PROJECTION_MODE_GLOBE) { + if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) { + return vec4( + project_globe_(position_world.xyz), + position_world.w + ); + } + } + if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR_AUTO_OFFSET) { + if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) { + if (abs(position_world.y - project.coordinateOrigin.y) > 0.25) { + return vec4( + project_mercator_(position_world.xy) - project.commonOrigin.xy, + project_size_float(position_world.z), + position_world.w + ); + } + } + } + if (project.projectionMode == PROJECTION_MODE_IDENTITY || + (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR_AUTO_OFFSET && + (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT || + project.coordinateSystem == COORDINATE_SYSTEM_CARTESIAN))) { + position_world = vec4f(position_world.xyz - project.coordinateOrigin, position_world.w); + } + + return project_offset_(position_world) + + project_offset_(project.modelMatrix * vec4(position64Low, 0.0)); +} + +// Overloaded versions for different input types. +fn project_position_vec4_f32(position: vec4) -> vec4 { + return project_position_vec4_f64(position, ZERO_64_LOW); +} + +fn project_position_vec3_f64(position: vec3, position64Low: vec3) -> vec3 { + let projected_position = project_position_vec4_f64(vec4(position, 1.0), position64Low); + return projected_position.xyz; +} + +fn project_position_vec3_f32(position: vec3) -> vec3 { + let projected_position = project_position_vec4_f64(vec4(position, 1.0), ZERO_64_LOW); + return projected_position.xyz; +} + +fn project_position_vec2_f32(position: vec2) -> vec2 { + let projected_position = project_position_vec4_f64(vec4(position, 0.0, 1.0), ZERO_64_LOW); + return projected_position.xy; +} + +// Transforms a common space position to clip space. +fn project_common_position_to_clipspace_with_projection(position: vec4, viewProjectionMatrix: mat4x4, center: vec4) -> vec4 { + return viewProjectionMatrix * position + center; +} + +// Uses the project viewProjectionMatrix and center. +fn project_common_position_to_clipspace(position: vec4) -> vec4 { + return project_common_position_to_clipspace_with_projection(position, project.viewProjectionMatrix, project.center); +} + +// Returns a clip space offset corresponding to a given number of screen pixels. +fn project_pixel_size_to_clipspace(pixels: vec2) -> vec2 { + let offset = pixels / project.viewportSize * project.devicePixelRatio * 2.0; + return offset * project.focalDistance; +} + +fn project_meter_size_to_pixel(meters: f32) -> f32 { + return project_size_float(meters) * project.scale; +} + +fn project_unit_size_to_pixel(size: f32, unit: i32) -> f32 { + if (unit == UNIT_METERS) { + return project_meter_size_to_pixel(size); + } else if (unit == UNIT_COMMON) { + return size * project.scale; + } + // UNIT_PIXELS: no scaling applied. + return size; +} + +fn project_pixel_size_float(pixels: f32) -> f32 { + return pixels / project.scale; +} + +fn project_pixel_size_vec2(pixels: vec2) -> vec2 { + return pixels / project.scale; +} +`;var kI=["default","lnglat","meter-offsets","lnglat-offsets","cartesian"],UI=kI.map(t=>`const int COORDINATE_SYSTEM_${t.toUpperCase().replaceAll("-","_")} = ${xi(t)};`).join(""),zI=Object.keys(_e).map(t=>`const int PROJECTION_MODE_${t} = ${_e[t]};`).join(""),WI=Object.keys(je).map(t=>`const int UNIT_${t.toUpperCase()} = ${je[t]};`).join(""),cb=`${UI} +${zI} +${WI} +layout(std140) uniform projectUniforms { +bool wrapLongitude; +int coordinateSystem; +vec3 commonUnitsPerMeter; +int projectionMode; +float scale; +vec3 commonUnitsPerWorldUnit; +vec3 commonUnitsPerWorldUnit2; +vec4 center; +mat4 modelMatrix; +mat4 viewProjectionMatrix; +vec2 viewportSize; +float devicePixelRatio; +float focalDistance; +vec3 cameraPosition; +vec3 coordinateOrigin; +vec3 commonOrigin; +bool pseudoMeters; +} project; +const float TILE_SIZE = 512.0; +const float PI = 3.1415926536; +const float WORLD_SCALE = TILE_SIZE / (PI * 2.0); +const vec3 ZERO_64_LOW = vec3(0.0); +const float EARTH_RADIUS = 6370972.0; +const float GLOBE_RADIUS = 256.0; +float project_size_at_latitude(float lat) { +float y = clamp(lat, -89.9, 89.9); +return 1.0 / cos(radians(y)); +} +float project_size() { +if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR && +project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT && +project.pseudoMeters == false) { +if (geometry.position.w == 0.0) { +return project_size_at_latitude(geometry.worldPosition.y); +} +float y = geometry.position.y / TILE_SIZE * 2.0 - 1.0; +float y2 = y * y; +float y4 = y2 * y2; +float y6 = y4 * y2; +return 1.0 + 4.9348 * y2 + 4.0587 * y4 + 1.5642 * y6; +} +return 1.0; +} +float project_size_at_latitude(float meters, float lat) { +return meters * project.commonUnitsPerMeter.z * project_size_at_latitude(lat); +} +float project_size(float meters) { +return meters * project.commonUnitsPerMeter.z * project_size(); +} +vec2 project_size(vec2 meters) { +return meters * project.commonUnitsPerMeter.xy * project_size(); +} +vec3 project_size(vec3 meters) { +return meters * project.commonUnitsPerMeter * project_size(); +} +vec4 project_size(vec4 meters) { +return vec4(meters.xyz * project.commonUnitsPerMeter, meters.w); +} +mat3 project_get_orientation_matrix(vec3 up) { +vec3 uz = normalize(up); +vec3 ux = abs(uz.z) == 1.0 ? vec3(1.0, 0.0, 0.0) : normalize(vec3(uz.y, -uz.x, 0)); +vec3 uy = cross(uz, ux); +return mat3(ux, uy, uz); +} +bool project_needs_rotation(vec3 commonPosition, out mat3 transform) { +if (project.projectionMode == PROJECTION_MODE_GLOBE) { +transform = project_get_orientation_matrix(commonPosition); +return true; +} +return false; +} +vec3 project_normal(vec3 vector) { +vec4 normal_modelspace = project.modelMatrix * vec4(vector, 0.0); +vec3 n = normalize(normal_modelspace.xyz * project.commonUnitsPerMeter); +mat3 rotation; +if (project_needs_rotation(geometry.position.xyz, rotation)) { +n = rotation * n; +} +return n; +} +vec4 project_offset_(vec4 offset) { +float dy = offset.y; +vec3 commonUnitsPerWorldUnit = project.commonUnitsPerWorldUnit + project.commonUnitsPerWorldUnit2 * dy; +return vec4(offset.xyz * commonUnitsPerWorldUnit, offset.w); +} +vec2 project_mercator_(vec2 lnglat) { +float x = lnglat.x; +if (project.wrapLongitude) { +x = mod(x + 180., 360.0) - 180.; +} +float y = clamp(lnglat.y, -89.9, 89.9); +return vec2( +radians(x) + PI, +PI + log(tan_fp32(PI * 0.25 + radians(y) * 0.5)) +) * WORLD_SCALE; +} +vec3 project_globe_(vec3 lnglatz) { +float lambda = radians(lnglatz.x); +float phi = radians(lnglatz.y); +float cosPhi = cos(phi); +float D = (lnglatz.z / EARTH_RADIUS + 1.0) * GLOBE_RADIUS; +return vec3( +sin(lambda) * cosPhi, +-cos(lambda) * cosPhi, +sin(phi) +) * D; +} +vec4 project_position(vec4 position, vec3 position64Low) { +vec4 position_world = project.modelMatrix * position; +if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR) { +if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) { +return vec4( +project_mercator_(position_world.xy), +project_size_at_latitude(position_world.z, position_world.y), +position_world.w +); +} +if (project.coordinateSystem == COORDINATE_SYSTEM_CARTESIAN) { +position_world.xyz += project.coordinateOrigin; +} +} +if (project.projectionMode == PROJECTION_MODE_GLOBE) { +if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) { +return vec4( +project_globe_(position_world.xyz), +position_world.w +); +} +} +if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR_AUTO_OFFSET) { +if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) { +if (abs(position_world.y - project.coordinateOrigin.y) > 0.25) { +return vec4( +project_mercator_(position_world.xy) - project.commonOrigin.xy, +project_size(position_world.z), +position_world.w +); +} +} +} +if (project.projectionMode == PROJECTION_MODE_IDENTITY || +(project.projectionMode == PROJECTION_MODE_WEB_MERCATOR_AUTO_OFFSET && +(project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT || +project.coordinateSystem == COORDINATE_SYSTEM_CARTESIAN))) { +position_world.xyz -= project.coordinateOrigin; +} +return project_offset_(position_world) + project_offset_(project.modelMatrix * vec4(position64Low, 0.0)); +} +vec4 project_position(vec4 position) { +return project_position(position, ZERO_64_LOW); +} +vec3 project_position(vec3 position, vec3 position64Low) { +vec4 projected_position = project_position(vec4(position, 1.0), position64Low); +return projected_position.xyz; +} +vec3 project_position(vec3 position) { +vec4 projected_position = project_position(vec4(position, 1.0), ZERO_64_LOW); +return projected_position.xyz; +} +vec2 project_position(vec2 position) { +vec4 projected_position = project_position(vec4(position, 0.0, 1.0), ZERO_64_LOW); +return projected_position.xy; +} +vec4 project_common_position_to_clipspace(vec4 position, mat4 viewProjectionMatrix, vec4 center) { +return viewProjectionMatrix * position + center; +} +vec4 project_common_position_to_clipspace(vec4 position) { +return project_common_position_to_clipspace(position, project.viewProjectionMatrix, project.center); +} +vec2 project_pixel_size_to_clipspace(vec2 pixels) { +vec2 offset = pixels / project.viewportSize * project.devicePixelRatio * 2.0; +return offset * project.focalDistance; +} +float project_size_to_pixel(float meters) { +return project_size(meters) * project.scale; +} +vec2 project_size_to_pixel(vec2 meters) { +return project_size(meters) * project.scale; +} +float project_size_to_pixel(float size, int unit) { +if (unit == UNIT_METERS) return project_size_to_pixel(size); +if (unit == UNIT_COMMON) return size * project.scale; +return size; +} +float project_pixel_size(float pixels) { +return pixels / project.scale; +} +vec2 project_pixel_size(vec2 pixels) { +return pixels / project.scale; +} +`;var VI={};function jI(t=VI){return"viewport"in t?sb(t):{}}var bn={name:"project",dependencies:[hh,Yc],source:ab,vs:cb,getUniforms:jI,uniformTypes:{wrapLongitude:"f32",coordinateSystem:"i32",commonUnitsPerMeter:"vec3",projectionMode:"i32",scale:"f32",commonUnitsPerWorldUnit:"vec3",commonUnitsPerWorldUnit2:"vec3",center:"vec4",modelMatrix:"mat4x4",viewProjectionMatrix:"mat4x4",viewportSize:"vec2",devicePixelRatio:"f32",focalDistance:"f32",cameraPosition:"vec3",coordinateOrigin:"vec3",commonOrigin:"vec3",pseudoMeters:"f32"}};var $I=`// Define a structure to hold both the clip-space position and the common position. +struct ProjectResult { + clipPosition: vec4, + commonPosition: vec4, +}; + +// This function mimics the GLSL version with the 'out' parameter by returning both values. +fn project_position_to_clipspace_and_commonspace( + position: vec3, + position64Low: vec3, + offset: vec3 +) -> ProjectResult { + // Compute the projected position. + let projectedPosition: vec3 = project_position_vec3_f64(position, position64Low); + + // Start with the provided offset. + var finalOffset: vec3 = offset; + + // Get whether a rotation is needed and the rotation matrix. + let rotationResult = project_needs_rotation(projectedPosition); + + // If rotation is needed, update the offset. + if (rotationResult.needsRotation) { + finalOffset = rotationResult.transform * offset; + } + + // Compute the common position. + let commonPosition: vec4 = vec4(projectedPosition + finalOffset, 1.0); + + // Convert to clip-space. + let clipPosition: vec4 = project_common_position_to_clipspace(commonPosition); + + return ProjectResult(clipPosition, commonPosition); +} + +// A convenience overload that returns only the clip-space position. +fn project_position_to_clipspace( + position: vec3, + position64Low: vec3, + offset: vec3 +) -> vec4 { + return project_position_to_clipspace_and_commonspace(position, position64Low, offset).clipPosition; +} +`,HI=`vec4 project_position_to_clipspace( + vec3 position, vec3 position64Low, vec3 offset, out vec4 commonPosition +) { + vec3 projectedPosition = project_position(position, position64Low); + mat3 rotation; + if (project_needs_rotation(projectedPosition, rotation)) { + // offset is specified as ENU + // when in globe projection, rotate offset so that the ground alighs with the surface of the globe + offset = rotation * offset; + } + commonPosition = vec4(projectedPosition + offset, 1.0); + return project_common_position_to_clipspace(commonPosition); +} + +vec4 project_position_to_clipspace( + vec3 position, vec3 position64Low, vec3 offset +) { + vec4 commonPosition; + return project_position_to_clipspace(position, position64Low, offset, commonPosition); +} +`,Oe={name:"project32",dependencies:[bn],source:$I,vs:HI};function Tn(){return[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}function Fr(t,e){let r=Ze.transformMat4([],e,t);return Ze.scale(r,r,1/r[3]),r}function os(t,e,r){return tr?r:t}function YI(t){return Math.log(t)*Math.LOG2E}var ss=Math.log2||YI;function gt(t,e){if(!t)throw new Error(e||"@math.gl/web-mercator: assertion failed.")}var mt=Math.PI,lb=mt/4,at=mt/180,up=180/mt,wn=512,nl=4003e4,ze=85.051129,dp=1.5;function ol(t){return Math.pow(2,t)}function hp(t){return ss(t)}function xe(t){let[e,r]=t;gt(Number.isFinite(e)),gt(Number.isFinite(r)&&r>=-90&&r<=90,"invalid latitude");let i=e*at,n=r*at,o=wn*(i+mt)/(2*mt),s=wn*(mt+Math.log(Math.tan(lb+n*.5)))/(2*mt);return[o,s]}function Se(t){let[e,r]=t,i=e/wn*(2*mt)-mt,n=2*(Math.atan(Math.exp(r/wn*(2*mt)-mt))-lb);return[i*up,n*up]}function pp(t){let{latitude:e}=t;gt(Number.isFinite(e));let r=Math.cos(e*at);return hp(nl*r)-9}function bi(t){let e=Math.cos(t*at);return wn/nl/e}function Ti(t){let{latitude:e,longitude:r,highPrecision:i=!1}=t;gt(Number.isFinite(e)&&Number.isFinite(r));let n=wn,o=Math.cos(e*at),s=n/360,a=s/o,c=n/nl/o,l={unitsPerMeter:[c,c,c],metersPerUnit:[1/c,1/c,1/c],unitsPerDegree:[s,a,c],degreesPerUnit:[1/s,1/a,1/c]};if(i){let f=at*Math.tan(e*at)/o,u=s*f/2,d=n/nl*f,h=d/a*c;l.unitsPerDegree2=[0,u,d],l.unitsPerMeter2=[h,0,h]}return l}function as(t,e){let[r,i,n]=t,[o,s,a]=e,{unitsPerMeter:c,unitsPerMeter2:l}=Ti({longitude:r,latitude:i,highPrecision:!0}),f=xe(t);f[0]+=o*(c[0]+l[0]*s),f[1]+=s*(c[1]+l[1]*s);let u=Se(f),d=(n||0)+(a||0);return Number.isFinite(n)||Number.isFinite(a)?[u[0],u[1],d]:u}function cs(t){let{height:e,pitch:r,bearing:i,altitude:n,scale:o,center:s}=t,a=Tn();ee.translate(a,a,[0,0,-n]),ee.rotateX(a,a,-r*at),ee.rotateZ(a,a,i*at);let c=o/e;return ee.scale(a,a,[c,c,c]),s&&ee.translate(a,a,Pe.negate([],s)),a}function sl(t){let{width:e,height:r,altitude:i,pitch:n=0,offset:o,center:s,scale:a,nearZMultiplier:c=1,farZMultiplier:l=1}=t,{fovy:f=_t(dp)}=t;i!==void 0&&(f=_t(i));let u=f*at,d=n*at,h=Br(f),p=h;s&&(p+=s[2]*a/Math.cos(d)/r);let g=u*(.5+(o?o[1]:0)/r),m=Math.sin(g)*p/Math.sin(os(Math.PI/2-d-g,.01,Math.PI-.01)),_=Math.sin(d)*m+p,T=p*10,y=Math.min(_*l,T);return{fov:u,aspect:e/r,focalDistance:h,near:c,far:y}}function gp(t){let{fov:e,aspect:r,near:i,far:n}=sl(t);return ee.perspective([],e,r,i,n)}function _t(t){return 2*Math.atan(.5/t)*up}function Br(t){return .5/Math.tan(.5*t*at)}function wi(t,e){let[r,i,n=0]=t;return gt(Number.isFinite(r)&&Number.isFinite(i)&&Number.isFinite(n)),Fr(e,[r,i,n,1])}function Ut(t,e,r=0){let[i,n,o]=t;if(gt(Number.isFinite(i)&&Number.isFinite(n),"invalid pixel coordinate"),Number.isFinite(o))return Fr(e,[i,n,o,1]);let s=Fr(e,[i,n,0,1]),a=Fr(e,[i,n,1,1]),c=s[2],l=a[2],f=c===l?0:((r||0)-c)/(l-c);return Be.lerp([],s,a,f)}function Si(t){let{width:e,height:r,bounds:i,minExtent:n=0,maxZoom:o=24,offset:s=[0,0]}=t,[[a,c],[l,f]]=i,u=XI(t.padding),d=xe([a,os(f,-ze,ze)]),h=xe([l,os(c,-ze,ze)]),p=[Math.max(Math.abs(h[0]-d[0]),n),Math.max(Math.abs(h[1]-d[1]),n)],g=[e-u.left-u.right-Math.abs(s[0])*2,r-u.top-u.bottom-Math.abs(s[1])*2];gt(g[0]>0&&g[1]>0);let m=g[0]/p[0],_=g[1]/p[1],T=(u.right-u.left)/2/m,y=(u.top-u.bottom)/2/_,x=[(h[0]+d[0])/2+T,(h[1]+d[1])/2+y],w=Se(x),b=Math.min(o,ss(Math.abs(Math.min(m,_))));return gt(Number.isFinite(b)),{longitude:w[0],latitude:w[1],zoom:b}}function XI(t=0){return typeof t=="number"?{top:t,bottom:t,left:t,right:t}:(gt(Number.isFinite(t.top)&&Number.isFinite(t.bottom)&&Number.isFinite(t.left)&&Number.isFinite(t.right)),t)}var fb=Math.PI/180;function ls(t,e=0){let{width:r,height:i,unproject:n}=t,o={targetZ:e},s=n([0,i],o),a=n([r,i],o),c,l,f=t.fovy?.5*t.fovy*fb:Math.atan(.5/t.altitude),u=(90-t.pitch)*fb;return f>u-.01?(c=ub(t,0,e),l=ub(t,r,e)):(c=n([0,0],o),l=n([r,0],o)),[s,a,l,c]}function ub(t,e,r){let{pixelUnprojectionMatrix:i}=t,n=Fr(i,[e,0,1,1]),o=Fr(i,[e,t.height,1,1]),a=(r*t.distanceScales.unitsPerMeter[2]-n[2])/(o[2]-n[2]),c=Be.lerp([],n,o,a),l=Se(c);return l.push(r),l}var Sn=class t{constructor(e={width:1,height:1}){this.equals=_=>_ instanceof t?_.width===this.width&&_.height===this.height&&ee.equals(_.projectionMatrix,this.projectionMatrix)&&ee.equals(_.viewMatrix,this.viewMatrix):!1,this.project=(_,T={})=>{let{topLeft:y=!0}=T,x=this.projectPosition(_),w=wi(x,this.pixelProjectionMatrix),[b,E]=w,S=y?E:this.height-E;return _.length===2?[b,S]:[b,S,w[2]]},this.unproject=(_,T={})=>{let{topLeft:y=!0,targetZ:x=void 0}=T,[w,b,E]=_,S=y?b:this.height-b,A=x&&x*this.distanceScales.unitsPerMeter[2],C=Ut([w,S,E],this.pixelUnprojectionMatrix,A),[I,R,N]=this.unprojectPosition(C);return Number.isFinite(E)?[I,R,N]:Number.isFinite(x)?[I,R,x]:[I,R]},this.projectPosition=_=>{let[T,y]=xe(_),x=(_[2]||0)*this.distanceScales.unitsPerMeter[2];return[T,y,x]},this.unprojectPosition=_=>{let[T,y]=Se(_),x=(_[2]||0)*this.distanceScales.metersPerUnit[2];return[T,y,x]};let{width:r,height:i,altitude:n=null,fovy:o=null}=e,{latitude:s=0,longitude:a=0,zoom:c=0,pitch:l=0,bearing:f=0,position:u=null,nearZMultiplier:d=.02,farZMultiplier:h=1.01}=e;r=r||1,i=i||1,o===null&&n===null?(n=dp,o=_t(n)):o===null?o=_t(n):n===null&&(n=Br(o));let p=ol(c);n=Math.max(.75,n);let g=Ti({longitude:a,latitude:s}),m=xe([a,s]);m.push(0),u&&Pe.add(m,m,Pe.mul([],u,g.unitsPerMeter)),this.projectionMatrix=gp({width:r,height:i,scale:p,center:m,pitch:l,fovy:o,nearZMultiplier:d,farZMultiplier:h}),this.viewMatrix=cs({height:i,scale:p,center:m,pitch:l,bearing:f,altitude:n}),this.width=r,this.height=i,this.scale=p,this.latitude=s,this.longitude=a,this.zoom=c,this.pitch=l,this.bearing=f,this.altitude=n,this.fovy=o,this.center=m,this.meterOffset=u||[0,0,0],this.distanceScales=g,this._initMatrices(),Object.freeze(this)}_initMatrices(){let{width:e,height:r,projectionMatrix:i,viewMatrix:n}=this,o=Tn();ee.multiply(o,o,i),ee.multiply(o,o,n),this.viewProjectionMatrix=o;let s=Tn();ee.scale(s,s,[e/2,-r/2,1]),ee.translate(s,s,[1,-1,0]),ee.multiply(s,s,o);let a=ee.invert(Tn(),s);if(!a)throw new Error("Pixel project matrix not invertible");this.pixelProjectionMatrix=s,this.pixelUnprojectionMatrix=a}projectFlat(e){return xe(e)}unprojectFlat(e){return Se(e)}getMapCenterByLngLatPosition({lngLat:e,pos:r}){let i=Ut(r,this.pixelUnprojectionMatrix),n=xe(e),o=Be.add([],n,Be.negate([],i)),s=Be.add([],this.center,o);return Se(s)}fitBounds(e,r={}){let{width:i,height:n}=this,{longitude:o,latitude:s,zoom:a}=Si(Object.assign({width:i,height:n,bounds:e},r));return new t({width:i,height:n,longitude:o,latitude:s,zoom:a})}getBounds(e){let r=this.getBoundingRegion(e),i=Math.min(...r.map(a=>a[0])),n=Math.max(...r.map(a=>a[0])),o=Math.min(...r.map(a=>a[1])),s=Math.max(...r.map(a=>a[1]));return[[i,o],[n,s]]}getBoundingRegion(e={}){return ls(this,e.z||0)}getLocationAtPoint({lngLat:e,pos:r}){return this.getMapCenterByLngLatPosition({lngLat:e,pos:r})}};var db=` +layout(std140) uniform shadowUniforms { + bool drawShadowMap; + bool useShadowMap; + vec4 color; + highp int lightId; + float lightCount; + mat4 viewProjectionMatrix0; + mat4 viewProjectionMatrix1; + vec4 projectCenter0; + vec4 projectCenter1; +} shadow; +`,GI=` +const int max_lights = 2; + +out vec3 shadow_vPosition[max_lights]; + +vec4 shadow_setVertexPosition(vec4 position_commonspace) { + mat4 viewProjectionMatrices[max_lights]; + viewProjectionMatrices[0] = shadow.viewProjectionMatrix0; + viewProjectionMatrices[1] = shadow.viewProjectionMatrix1; + vec4 projectCenters[max_lights]; + projectCenters[0] = shadow.projectCenter0; + projectCenters[1] = shadow.projectCenter1; + + if (shadow.drawShadowMap) { + return project_common_position_to_clipspace(position_commonspace, viewProjectionMatrices[shadow.lightId], projectCenters[shadow.lightId]); + } + if (shadow.useShadowMap) { + for (int i = 0; i < max_lights; i++) { + if(i < int(shadow.lightCount)) { + vec4 shadowMap_position = project_common_position_to_clipspace(position_commonspace, viewProjectionMatrices[i], projectCenters[i]); + shadow_vPosition[i] = (shadowMap_position.xyz / shadowMap_position.w + 1.0) / 2.0; + } + } + } + return gl_Position; +} +`,qI=` +${db} +${GI} +`,KI=` +const int max_lights = 2; +uniform sampler2D shadow_uShadowMap0; +uniform sampler2D shadow_uShadowMap1; + +in vec3 shadow_vPosition[max_lights]; + +const vec4 bitPackShift = vec4(1.0, 255.0, 65025.0, 16581375.0); +const vec4 bitUnpackShift = 1.0 / bitPackShift; +const vec4 bitMask = vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0); + +float shadow_getShadowWeight(vec3 position, sampler2D shadowMap) { + vec4 rgbaDepth = texture(shadowMap, position.xy); + + float z = dot(rgbaDepth, bitUnpackShift); + return smoothstep(0.001, 0.01, position.z - z); +} + +vec4 shadow_filterShadowColor(vec4 color) { + if (shadow.drawShadowMap) { + vec4 rgbaDepth = fract(gl_FragCoord.z * bitPackShift); + rgbaDepth -= rgbaDepth.gbaa * bitMask; + return rgbaDepth; + } + if (shadow.useShadowMap) { + float shadowAlpha = 0.0; + shadowAlpha += shadow_getShadowWeight(shadow_vPosition[0], shadow_uShadowMap0); + if(shadow.lightCount > 1.0) { + shadowAlpha += shadow_getShadowWeight(shadow_vPosition[1], shadow_uShadowMap1); + } + shadowAlpha *= shadow.color.a / shadow.lightCount; + float blendedAlpha = shadowAlpha + color.a * (1.0 - shadowAlpha); + + return vec4( + mix(color.rgb, shadow.color.rgb, shadowAlpha / blendedAlpha), + blendedAlpha + ); + } + return color; +} +`,ZI=` +${db} +${KI} +`,QI=kt(iO),JI=kt(nO),eO=[0,0,0,1],tO=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0];function rO(t,e){let[r,i,n]=t,o=Ut([r,i,n],e);return Number.isFinite(n)?o:[o[0],o[1],0]}function iO({viewport:t,center:e}){return new me(t.viewProjectionMatrix).invert().transform(e)}function nO({viewport:t,shadowMatrices:e}){let r=[],i=t.pixelUnprojectionMatrix,n=t.isGeospatial?void 0:1,o=[[0,0,n],[t.width,0,n],[0,t.height,n],[t.width,t.height,n],[0,0,-1],[t.width,0,-1],[0,t.height,-1],[t.width,t.height,-1]].map(s=>rO(s,i));for(let s of e){let a=s.clone().translate(new Me(t.center).negate()),c=o.map(f=>a.transform(f)),l=new me().ortho({left:Math.min(...c.map(f=>f[0])),right:Math.max(...c.map(f=>f[0])),bottom:Math.min(...c.map(f=>f[1])),top:Math.max(...c.map(f=>f[1])),near:Math.min(...c.map(f=>-f[2])),far:Math.max(...c.map(f=>-f[2]))});r.push(l.multiplyRight(s))}return r}function oO(t){let{shadowEnabled:e=!0,project:r}=t;if(!e||!r||!t.shadowMatrices||!t.shadowMatrices.length)return{drawShadowMap:!1,useShadowMap:!1,shadow_uShadowMap0:t.dummyShadowMap,shadow_uShadowMap1:t.dummyShadowMap};let i=bn.getUniforms(r),n=QI({viewport:r.viewport,center:i.center}),o=[],s=JI({shadowMatrices:t.shadowMatrices,viewport:r.viewport}).slice();for(let c=0;c0:!1,color:t.shadowColor||eO,lightId:t.shadowLightId||0,lightCount:t.shadowMatrices.length,shadow_uShadowMap0:t.dummyShadowMap,shadow_uShadowMap1:t.dummyShadowMap};for(let c=0;c",lightId:"i32",lightCount:"f32",viewProjectionMatrix0:"mat4x4",viewProjectionMatrix1:"mat4x4",projectCenter0:"vec4",projectCenter1:"vec4"}};var sO=`struct pickingUniforms { + isActive: f32, + isAttribute: f32, + isHighlightActive: f32, + useByteColors: f32, + highlightedObjectColor: vec3, + highlightColor: vec4, +}; + +@group(0) @binding(auto) var picking: pickingUniforms; + +fn picking_normalizeColor(color: vec3) -> vec3 { + return select(color, color / 255.0, picking.useByteColors > 0.5); +} + +fn picking_normalizeColor4(color: vec4) -> vec4 { + return select(color, color / 255.0, picking.useByteColors > 0.5); +} + +fn picking_isColorZero(color: vec3) -> bool { + return dot(color, vec3(1.0)) < 0.00001; +} + +fn picking_isColorValid(color: vec3) -> bool { + return dot(color, vec3(1.0)) > 0.00001; +} +`,Ne={...Cc,source:sO,defaultUniforms:{...Cc.defaultUniforms,useByteColors:!0},inject:{"vs:DECKGL_FILTER_GL_POSITION":` + // for picking depth values + picking_setPickingAttribute(position.z / position.w); + `,"vs:DECKGL_FILTER_COLOR":` + picking_setPickingColor(geometry.pickingColor); + `,"fs:DECKGL_FILTER_COLOR":{order:99,injection:` + // use highlight color if this fragment belongs to the selected object. + color = picking_filterHighlightColor(color); + + // use picking color if rendering to picking FBO. + color = picking_filterPickingColor(color); + `}}};var lO=[Yc],fO=["vs:DECKGL_FILTER_SIZE(inout vec3 size, VertexGeometry geometry)","vs:DECKGL_FILTER_GL_POSITION(inout vec4 position, VertexGeometry geometry)","vs:DECKGL_FILTER_COLOR(inout vec4 color, VertexGeometry geometry)","fs:DECKGL_FILTER_COLOR(inout vec4 color, FragmentGeometry geometry)"],uO=[];function hb(t){let e=ui.getDefaultShaderAssembler();for(let i of lO)e.addDefaultModule(i);e._hookFunctions.length=0;let r=t==="glsl"?fO:uO;for(let i of r)e.addShaderHook(i);return e}var dO=[255,255,255],hO=1,pO=0,cl=class{constructor(e={}){this.type="ambient";let{color:r=dO}=e,{intensity:i=hO}=e;this.id=e.id||`ambient-${pO++}`,this.color=r,this.intensity=i}};var gO=[255,255,255],mO=1,_O=[0,0,-1],yO=0,fs=class{constructor(e={}){this.type="directional";let{color:r=gO}=e,{intensity:i=mO}=e,{direction:n=_O}=e,{_shadow:o=!1}=e;this.id=e.id||`directional-${yO++}`,this.color=r,this.intensity=i,this.type="directional",this.direction=new Me(n).normalize().toArray(),this.shadow=o}getProjectedLight(e){return this}};var us=class{constructor(e,r={id:"pass"}){let{id:i}=r;this.id=i,this.device=e,this.props={...r}}setProps(e){Object.assign(this.props,e)}render(e){}cleanup(){}};var xO={depthWriteEnabled:!0,depthCompare:"less-equal",blendColorOperation:"add",blendColorSrcFactor:"src-alpha",blendColorDstFactor:"one",blendAlphaOperation:"add",blendAlphaSrcFactor:"one-minus-dst-alpha",blendAlphaDstFactor:"one"},cr=class extends us{constructor(){super(...arguments),this._lastRenderIndex=-1}render(e){this._render(e)}_render(e){let r=this.device.canvasContext,i=e.target??r.getCurrentFramebuffer(),[n,o]=r.getDrawingBufferSize(),s=e.clearCanvas??!0,a=e.clearColor??(s?[0,0,0,0]:!1),c=s?1:!1,l=s?0:!1,f=e.colorMask??15,u={viewport:[0,0,n,o]};e.colorMask&&(u.colorMask=f),e.scissorRect&&(u.scissorRect=e.scissorRect);let d=this.device.beginRenderPass({framebuffer:i,parameters:u,clearColor:a,clearDepth:c,clearStencil:l});try{return this._drawLayers(d,e)}finally{d.end(),this.device.submit()}}_drawLayers(e,r){let{target:i,shaderModuleProps:n,viewports:o,views:s,onViewportActive:a,clearStack:c=!0}=r;r.pass=r.pass||"unknown",c&&(this._lastRenderIndex=-1);let l=[];for(let f of o){let u=s&&s[f.id];a?.(f);let d=this._getDrawLayerParams(f,r),h=f.subViewports||[f];for(let p of h){let g=this._drawLayersInViewport(e,{target:i,shaderModuleProps:n,viewport:p,view:u,pass:r.pass,layers:r.layers},d);l.push(g)}}return l}_getDrawLayerParams(e,{layers:r,pass:i,isPicking:n=!1,layerFilter:o,cullRect:s,effects:a,shaderModuleProps:c},l=!1){let f=[],u=gb(this._lastRenderIndex+1),d={layer:r[0],viewport:e,isPicking:n,renderPass:i,cullRect:s},h={};for(let p=0;py/255):d===!1&&(g=!1),h!==void 0&&(m=h),p!==void 0&&(_=p),this.device.beginRenderPass({framebuffer:o,parameters:{viewport:l,scissorRect:l},clearColor:g,clearDepth:m,clearStencil:_}).end()}}let f={totalCount:r.length,visibleCount:0,compositeCount:0,pickableCount:0};e.setParameters({viewport:l});for(let u=0;u{let s=n.props._offset,a=n.id,c=n.parent&&n.parent.id,l;if(c&&!(c in e)&&i(n.parent,!1),c in r){let f=r[c]=r[c]||gb(e[c],e);l=f(n,o),r[a]=f}else Number.isFinite(s)?(l=s+(e[c]||0),r[a]=null):l=t;return o&&l>=t&&(t=l+1),e[a]=l,l};return i}function bO(t,{shaderModuleProps:e,target:r,viewport:i}){let n=e?.project?.devicePixelRatio??t.canvasContext.cssToDeviceRatio(),[,o]=t.canvasContext.getDrawingBufferSize(),s=r?r.height:o,a=i;return[a.x*n,s-(a.y+a.height)*n,a.width*n,a.height*n]}function pb(t,...e){for(let r of e)if(r)for(let i in r)t[i]?Object.assign(t[i],r[i]):t[i]=r[i];return t}var ds=class extends cr{constructor(e,r){super(e,r);let i=e.createTexture({format:"rgba8unorm",width:1,height:1,sampler:{minFilter:"linear",magFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}}),n=e.createTexture({format:"depth16unorm",width:1,height:1});this.fbo=e.createFramebuffer({id:"shadowmap",width:1,height:1,colorAttachments:[i],depthStencilAttachment:n})}delete(){this.fbo&&(this.fbo.destroy(),this.fbo=null)}getShadowMap(){return this.fbo.colorAttachments[0].texture}render(e){let r=this.fbo,i=this.device.canvasContext.cssToDeviceRatio(),n=e.viewports[0],o=n.width*i,s=n.height*i,a=[1,1,1,1];(o!==r.width||s!==r.height)&&r.resize({width:o,height:s}),super.render({...e,clearColor:a,target:r,pass:"shadow"})}getLayerParameters(e,r,i){return{...e.props.parameters,blend:!1,depthWriteEnabled:!0,depthCompare:"less-equal"}}shouldDrawLayer(e){return e.props.shadowEnabled!==!1}getShaderModuleProps(e,r,i){return{shadow:{project:i.project,drawToShadowMap:!0}}}};var TO={color:[255,255,255],intensity:1},mb=[{color:[255,255,255],intensity:1,direction:[-1,3,-1]},{color:[255,255,255],intensity:.9,direction:[1,-8,-2.5]}],wO=[0,0,0,200/255],An=class{constructor(e={}){this.id="lighting-effect",this.shadowColor=wO,this.shadow=!1,this.directionalLights=[],this.pointLights=[],this.shadowPasses=[],this.dummyShadowMap=null,this.setProps(e)}setup(e){this.context=e;let{device:r,deck:i}=e;this.shadow&&!this.dummyShadowMap&&(this._createShadowPasses(r),i._addDefaultShaderModule(al),this.dummyShadowMap=r.createTexture({width:1,height:1}))}setProps(e){this.ambientLight=void 0,this.directionalLights=[],this.pointLights=[];for(let r in e){let i=e[r];switch(i.type){case"ambient":this.ambientLight=i;break;case"directional":this.directionalLights.push(i);break;case"point":this.pointLights.push(i);break;default:}}this._applyDefaultLights(),this.shadow=this.directionalLights.some(r=>r.shadow),this.context&&this.setup(this.context),this.props=e}preRender({layers:e,layerFilter:r,viewports:i,onViewportActive:n,views:o}){if(this.shadow){this.shadowMatrices=this._calculateMatrices();for(let s=0;ss.getShadowMap()),dummyShadowMap:this.dummyShadowMap,shadowColor:this.shadowColor,shadowMatrices:this.shadowMatrices}:{},n={enabled:!0,lights:this._getLights(e)},o=e.props.material;return{shadow:i,lighting:n,phongMaterial:o,gouraudMaterial:o}}cleanup(e){for(let r of this.shadowPasses)r.delete();this.shadowPasses.length=0,this.dummyShadowMap&&(this.dummyShadowMap.destroy(),this.dummyShadowMap=null,e.deck._removeDefaultShaderModule(al))}_calculateMatrices(){let e=[];for(let r of this.directionalLights){let i=new me().lookAt({eye:new Me(r.direction).negate()});e.push(i)}return e}_createShadowPasses(e){for(let r=0;rn&&(o=n);let s=this._pool,a=e.BYTES_PER_ELEMENT*o,c=s.findIndex(l=>l.byteLength>=a);if(c>=0){let l=new e(s.splice(c,1)[0],0,o);return i&&l.fill(0),l}return new e(o)}_release(e){if(!ArrayBuffer.isView(e))return;let r=this._pool,{buffer:i}=e,{byteLength:n}=i,o=r.findIndex(s=>s.byteLength>=n);o<0?r.push(i):(o>0||r.lengththis.opts.poolSize&&r.shift()}},lr=new mp;function En(){return[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}function ps(t,e){let r=t%e;return r<0?e+r:r}function yb(t){return[t[12],t[13],t[14]]}function xb(t){return{left:vn(t[3]+t[0],t[7]+t[4],t[11]+t[8],t[15]+t[12]),right:vn(t[3]-t[0],t[7]-t[4],t[11]-t[8],t[15]-t[12]),bottom:vn(t[3]+t[1],t[7]+t[5],t[11]+t[9],t[15]+t[13]),top:vn(t[3]-t[1],t[7]-t[5],t[11]-t[9],t[15]-t[13]),near:vn(t[3]+t[2],t[7]+t[6],t[11]+t[10],t[15]+t[14]),far:vn(t[3]-t[2],t[7]-t[6],t[11]-t[10],t[15]-t[14])}}var _b=new Me;function vn(t,e,r,i){_b.set(t,e,r);let n=_b.len();return{distance:i/n,normal:new Me(-t/n,-e/n,-r/n)}}function SO(t){return t-Math.fround(t)}var hs;function ll(t,e){let{size:r=1,startIndex:i=0}=e,n=e.endIndex!==void 0?e.endIndex:t.length,o=(n-i)/r;hs=lr.allocate(hs,o,{type:Float32Array,size:r*2});let s=i,a=0;for(;s=r.delay+r.duration*r.repeat}getTime(e){if(e===void 0)return this.time;let r=this.channels.get(e);return r===void 0?-1:r.time}setTime(e){this.time=Math.max(0,e);let r=this.channels.values();for(let n of r)this._setChannelTime(n,this.time);let i=this.animations.values();for(let n of i){let{animation:o,channel:s}=n;o.setTime(this.getTime(s))}}play(){this.playing=!0}pause(){this.playing=!1,this.lastEngineTime=-1}reset(){this.setTime(0)}attachAnimation(e,r){let i=MO++;return this.animations.set(i,{animation:e,channel:r}),e.setTime(this.getTime(r)),i}detachAnimation(e){this.animations.delete(e)}update(e){this.playing&&(this.lastEngineTime===-1&&(this.lastEngineTime=e),this.setTime(this.time+(e-this.lastEngineTime)),this.lastEngineTime=e)}_setChannelTime(e,r){let i=r-e.delay,n=e.duration*e.repeat;i>=n?e.time=e.duration*e.rate:(e.time=Math.max(0,i)%e.duration,e.time*=e.rate)}};z();function Ab(t){let e=typeof window<"u"?window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame:null;return e?e.call(window,t):setTimeout(()=>t(typeof performance<"u"?performance.now():Date.now()),1e3/60)}function vb(t){let e=typeof window<"u"?window.cancelAnimationFrame||window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame:null;if(e){e.call(window,t);return}clearTimeout(t)}go();var IO=0,OO="Animation Loop",gs=class t{static defaultAnimationLoopProps={device:null,onAddHTML:()=>"",onInitialize:async()=>null,onRender:()=>{},onFinalize:()=>{},onError:e=>console.error(e),stats:void 0,autoResizeViewport:!1};device=null;canvas=null;props;animationProps=null;timeline=null;stats;sharedStats;cpuTime;gpuTime;frameRate;display;_needsRedraw="initialized";_initialized=!1;_running=!1;_animationFrameId=null;_nextFramePromise=null;_resolveNextFrame=null;_cpuStartTime=0;_error=null;_lastFrameTime=0;constructor(e){if(this.props={...t.defaultAnimationLoopProps,...e},e=this.props,!e.device)throw new Error("No device provided");this.stats=e.stats||new it({id:`animation-loop-${IO++}`}),this.sharedStats=hn.stats.get(OO),this.frameRate=this.stats.get("Frame Rate"),this.frameRate.setSampleSize(1),this.cpuTime=this.stats.get("CPU Time"),this.gpuTime=this.stats.get("GPU Time"),this.setProps({autoResizeViewport:e.autoResizeViewport}),this.start=this.start.bind(this),this.stop=this.stop.bind(this),this._onMousemove=this._onMousemove.bind(this),this._onMouseleave=this._onMouseleave.bind(this)}destroy(){this.stop(),this._setDisplay(null),this.device?._disableDebugGPUTime()}delete(){this.destroy()}reportError(e){this.props.onError(e),this._error=e}setNeedsRedraw(e){return this._needsRedraw=this._needsRedraw||e,this}needsRedraw(){let e=this._needsRedraw;return this._needsRedraw=!1,e}setProps(e){return"autoResizeViewport"in e&&(this.props.autoResizeViewport=e.autoResizeViewport||!1),this}async start(){if(this._running)return this;this._running=!0;try{let e;if(!this._initialized){if(this._initialized=!0,await this._initDevice(),this._initialize(),!this._running)return null;await this.props.onInitialize(this._getAnimationProps())}return this._running?(e!==!1&&(this._cancelAnimationFrame(),this._requestAnimationFrame()),this):null}catch(e){let r=e instanceof Error?e:new Error("Unknown error");throw this.props.onError(r),r}}stop(){return this._running&&(this.animationProps&&!this._error&&this.props.onFinalize(this.animationProps),this._cancelAnimationFrame(),this._nextFramePromise=null,this._resolveNextFrame=null,this._running=!1,this._lastFrameTime=0),this}redraw(e){return this.device?.isLost||this._error?this:(this._beginFrameTimers(e),this._setupFrame(),this._updateAnimationProps(),this._renderFrame(this._getAnimationProps()),this._clearNeedsRedraw(),this._resolveNextFrame&&(this._resolveNextFrame(this),this._nextFramePromise=null,this._resolveNextFrame=null),this._endFrameTimers(),this)}attachTimeline(e){return this.timeline=e,this.timeline}detachTimeline(){this.timeline=null}waitForRender(){return this.setNeedsRedraw("waitForRender"),this._nextFramePromise||(this._nextFramePromise=new Promise(e=>{this._resolveNextFrame=e})),this._nextFramePromise}async toDataURL(){if(this.setNeedsRedraw("toDataURL"),await this.waitForRender(),this.canvas instanceof HTMLCanvasElement)return this.canvas.toDataURL();throw new Error("OffscreenCanvas")}_initialize(){this._startEventHandling(),this._initializeAnimationProps(),this._updateAnimationProps(),this._resizeViewport(),this.device?._enableDebugGPUTime()}_setDisplay(e){this.display&&(this.display.destroy(),this.display.animationLoop=null),e&&(e.animationLoop=this),this.display=e}_requestAnimationFrame(){this._running&&(this._animationFrameId=Ab(this._animationFrame.bind(this)))}_cancelAnimationFrame(){this._animationFrameId!==null&&(vb(this._animationFrameId),this._animationFrameId=null)}_animationFrame(e){this._running&&(this.redraw(e),this._requestAnimationFrame())}_renderFrame(e){if(this.display){this.display._renderFrame(e);return}this.props.onRender(this._getAnimationProps()),this.device?.submit()}_clearNeedsRedraw(){this._needsRedraw=!1}_setupFrame(){this._resizeViewport()}_initializeAnimationProps(){let e=this.device?.getDefaultCanvasContext();if(!this.device||!e)throw new Error("loop");let r=e?.canvas,i=e.props.useDevicePixels;this.animationProps={animationLoop:this,device:this.device,canvasContext:e,canvas:r,useDevicePixels:i,timeline:this.timeline,needsRedraw:!1,width:1,height:1,aspect:1,time:0,startTime:Date.now(),engineTime:0,tick:0,tock:0,_mousePosition:null}}_getAnimationProps(){if(!this.animationProps)throw new Error("animationProps");return this.animationProps}_updateAnimationProps(){if(!this.animationProps)return;let{width:e,height:r,aspect:i}=this._getSizeAndAspect();(e!==this.animationProps.width||r!==this.animationProps.height)&&this.setNeedsRedraw("drawing buffer resized"),i!==this.animationProps.aspect&&this.setNeedsRedraw("drawing buffer aspect changed"),this.animationProps.width=e,this.animationProps.height=r,this.animationProps.aspect=i,this.animationProps.needsRedraw=this._needsRedraw,this.animationProps.engineTime=Date.now()-this.animationProps.startTime,this.timeline&&this.timeline.update(this.animationProps.engineTime),this.animationProps.tick=Math.floor(this.animationProps.time/1e3*60),this.animationProps.tock++,this.animationProps.time=this.timeline?this.timeline.getTime():this.animationProps.engineTime}async _initDevice(){if(this.device=await this.props.device,!this.device)throw new Error("No device provided");this.canvas=this.device.getDefaultCanvasContext().canvas||null}_createInfoDiv(){if(this.canvas&&this.props.onAddHTML){let e=document.createElement("div");document.body.appendChild(e),e.style.position="relative";let r=document.createElement("div");r.style.position="absolute",r.style.left="10px",r.style.bottom="10px",r.style.width="300px",r.style.background="white",this.canvas instanceof HTMLCanvasElement&&e.appendChild(this.canvas),e.appendChild(r);let i=this.props.onAddHTML(r);i&&(r.innerHTML=i)}}_getSizeAndAspect(){if(!this.device)return{width:1,height:1,aspect:1};let[e,r]=this.device.getDefaultCanvasContext().getDrawingBufferSize(),i=e>0&&r>0?e/r:1;return{width:e,height:r,aspect:i}}_resizeViewport(){this.props.autoResizeViewport&&this.device.gl&&this.device.gl.viewport(0,0,this.device.gl.drawingBufferWidth,this.device.gl.drawingBufferHeight)}_beginFrameTimers(e){let r=e??(typeof performance<"u"?performance.now():Date.now());if(this._lastFrameTime){let i=r-this._lastFrameTime;i>0&&this.frameRate.addTime(i)}this._lastFrameTime=r,this.device?._isDebugGPUTimeEnabled()&&this._consumeEncodedGpuTime(),this.cpuTime.timeStart()}_endFrameTimers(){this.device?._isDebugGPUTimeEnabled()&&this._consumeEncodedGpuTime(),this.cpuTime.timeEnd(),this._updateSharedStats()}_consumeEncodedGpuTime(){if(!this.device)return;let e=this.device.commandEncoder._gpuTimeMs;e!==void 0&&(this.gpuTime.addTime(e),this.device.commandEncoder._gpuTimeMs=void 0)}_updateSharedStats(){if(this.stats!==this.sharedStats){for(let e of Object.keys(this.sharedStats.stats))this.stats.stats[e]||delete this.sharedStats.stats[e];this.stats.forEach(e=>{let r=this.sharedStats.get(e.name,e.type);r.sampleSize=e.sampleSize,r.time=e.time,r.count=e.count,r.samples=e.samples,r.lastTiming=e.lastTiming,r.lastSampleTime=e.lastSampleTime,r.lastSampleCount=e.lastSampleCount,r._count=e._count,r._time=e._time,r._samples=e._samples,r._startTime=e._startTime,r._timerPending=e._timerPending})}}_startEventHandling(){this.canvas&&(this.canvas.addEventListener("mousemove",this._onMousemove.bind(this)),this.canvas.addEventListener("mouseleave",this._onMouseleave.bind(this)))}_onMousemove(e){e instanceof MouseEvent&&(this._getAnimationProps()._mousePosition=[e.offsetX,e.offsetY])}_onMouseleave(e){this._getAnimationProps()._mousePosition=null}};z();z();var yp={};function kr(t="id"){yp[t]=yp[t]||1;let e=yp[t]++;return`${t}-${e}`}var hl=class{id;userData={};topology;bufferLayout=[];vertexCount;indices;attributes;constructor(e){if(this.id=e.id||kr("geometry"),this.topology=e.topology,this.indices=e.indices||null,this.attributes=e.attributes,this.vertexCount=e.vertexCount,this.bufferLayout=e.bufferLayout||[],this.indices&&!(this.indices.usage&j.INDEX))throw new Error("Index buffer must have INDEX usage")}destroy(){this.indices?.destroy();for(let e of Object.values(this.attributes))e.destroy()}getVertexCount(){return this.vertexCount}getAttributes(){return this.attributes}getIndexes(){return this.indices||null}_calculateVertexCount(e){return e.byteLength/12}};function Eb(t,e){if(e instanceof hl)return e;let r=NO(t,e),{attributes:i,bufferLayout:n}=DO(t,e);return new hl({topology:e.topology||"triangle-list",bufferLayout:n,vertexCount:e.vertexCount,indices:r,attributes:i})}function NO(t,e){if(!e.indices)return;let r=e.indices.value;return t.createBuffer({usage:j.INDEX,data:r})}function DO(t,e){let r=[],i={};for(let[o,s]of Object.entries(e.attributes)){let a=o;switch(o){case"POSITION":a="positions";break;case"NORMAL":a="normals";break;case"TEXCOORD_0":a="texCoords";break;case"TEXCOORD_1":a="texCoords1";break;case"COLOR_0":a="colors";break}if(s){i[a]=t.createBuffer({data:s.value,id:`${o}-buffer`});let{value:c,size:l,normalized:f}=s;if(l===void 0)throw new Error(`Attribute ${o} is missing a size`);r.push({name:a,format:or.getVertexFormatFromAttribute(c,l,f)})}}let n=e._calculateVertexCount(e.attributes,e.indices);return{attributes:i,bufferLayout:r,vertexCount:n}}function Rb(t,e){let r={},i="Values";if(t.attributes.length===0&&!t.varyings?.length)return{"No attributes or varyings":{[i]:"N/A"}};for(let n of t.attributes)if(n){let o=`${n.location} ${n.name}: ${n.type}`;r[`in ${o}`]={[i]:n.stepMode||"vertex"}}for(let n of t.varyings||[]){let o=`${n.location} ${n.name}`;r[`out ${o}`]={[i]:JSON.stringify(n)}}return r}var Cb="__debugFramebufferState";function Mb(t,e,r){if(t.device.type!=="webgl")return;let i=BO(t.device);if(!i.flushing){if(UO(t)){LO(t,r,i);return}e&&kO(e)&&e.handle!==null&&(i.queuedFramebuffers.includes(e)||i.queuedFramebuffers.push(e))}}function LO(t,e,r){if(r.queuedFramebuffers.length===0)return;let i=t.device,{gl:n}=i,o=n.getParameter(36010),s=n.getParameter(36006),[a,c]=t.device.getDefaultCanvasContext().getDrawingBufferSize(),l=Pb(e.top,8),f=Pb(e.left,8);r.flushing=!0;try{for(let u of r.queuedFramebuffers){let[d,h,p,g,m]=FO({framebuffer:u,targetWidth:a,targetHeight:c,topPx:l,leftPx:f,minimap:e.minimap});n.bindFramebuffer(36008,u.handle),n.bindFramebuffer(36009,null),n.blitFramebuffer(0,0,u.width,u.height,d,h,p,g,16384,9728),l+=m+8}}finally{n.bindFramebuffer(36008,o),n.bindFramebuffer(36009,s),r.flushing=!1}}function FO(t){let{framebuffer:e,targetWidth:r,targetHeight:i,topPx:n,leftPx:o,minimap:s}=t,a=s?Math.max(Math.floor(r/4),1):r,c=s?Math.max(Math.floor(i/4),1):i,l=Math.min(a/e.width,c/e.height),f=Math.max(Math.floor(e.width*l),1),u=Math.max(Math.floor(e.height*l),1),d=o,h=Math.max(i-n-u,0),p=d+f,g=h+u;return[d,h,p,g,u]}function BO(t){return t.userData[Cb]||={flushing:!1,queuedFramebuffers:[]},t.userData[Cb]}function kO(t){return"colorAttachments"in t}function UO(t){let e=t.props.framebuffer;return!e||e.handle===null}function Pb(t,e){if(!t)return e;let r=Number.parseInt(t,10);return Number.isFinite(r)?r:e}function pl(t,e,r){if(t===e)return!0;if(!r||!t||!e)return!1;if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(let i=0;ir.name===e)||null}getAttributeNamesForBuffer(e){return e.attributes?e.attributes?.map(r=>r.attribute):[e.name]}mergeBufferLayouts(e,r){let i=[...e];for(let n of r){let o=i.findIndex(s=>s.name===n.name);o<0?i.push(n):i[o]=n}return i}getBufferIndex(e){let r=this.bufferLayouts.findIndex(i=>i.name===e);return r===-1&&v.warn(`BufferLayout: Missing buffer for "${e}".`)(),r}};function Ib(t,e){let r=1/0;for(let i of t){let n=e[i];n!==void 0&&(r=Math.min(r,n))}return r}function Ob(t,e){let r=Object.fromEntries(t.attributes.map(n=>[n.name,n.location])),i=e.slice();return i.sort((n,o)=>{let s=n.attributes?n.attributes.map(f=>f.attribute):[n.name],a=o.attributes?o.attributes.map(f=>f.attribute):[o.name],c=Ib(s,r),l=Ib(a,r);return c-l}),i}function xp(t,e){if(!t||!e.some(i=>i.bindingLayout?.length))return t;let r={...t,bindings:t.bindings.map(i=>({...i}))};"attributes"in(t||{})&&(r.attributes=t?.attributes||[]);for(let i of e)for(let n of i.bindingLayout||[])for(let o of zO(n.name)){let s=r.bindings.find(a=>a.name===o);s?.group===0&&(s.group=n.group)}return r}function Nb(t){return!!(t.uniformTypes&&!WO(t.uniformTypes))}function zO(t){let e=new Set([t,`${t}Uniforms`]);return t.endsWith("Uniforms")||e.add(`${t}Sampler`),[...e]}function WO(t){for(let e in t)return!1;return!0}z();function VO(t){return _d(t)||typeof t=="number"||typeof t=="boolean"}function Db(t,e={}){let r={bindings:{},uniforms:{}};return Object.keys(t).forEach(i=>{let n=t[i];Object.prototype.hasOwnProperty.call(e,i)||VO(n)?r.uniforms[i]=n:r.bindings[i]=n}),r}var gl=class{options={disableWarnings:!1};modules;moduleUniforms;moduleBindings;constructor(e,r){Object.assign(this.options,r);let i=an(Object.values(e).filter(jO));for(let n of i)e[n.name]=n;v.log(1,"Creating ShaderInputs with modules",Object.keys(e))(),this.modules=e,this.moduleUniforms={},this.moduleBindings={};for(let[n,o]of Object.entries(e))o&&(this._addModule(o),o.name&&n!==o.name&&!this.options.disableWarnings&&v.warn(`Module name: ${n} vs ${o.name}`)())}destroy(){}setProps(e){for(let r of Object.keys(e)){let i=r,n=e[i]||{},o=this.modules[i];if(!o)this.options.disableWarnings||v.warn(`Module ${r} not found`)();else{let s=this.moduleUniforms[i],a=this.moduleBindings[i],c=o.getUniforms?.(n,s)||n,{uniforms:l,bindings:f}=Db(c,o.uniformTypes);this.moduleUniforms[i]=Lb(s,l,o.uniformTypes),this.moduleBindings[i]={...a,...f}}}}getModules(){return Object.values(this.modules)}getUniformValues(){return this.moduleUniforms}getBindingValues(){let e={};for(let r of Object.values(this.moduleBindings))Object.assign(e,r);return e}getDebugTable(){let e={};for(let[r,i]of Object.entries(this.moduleUniforms))for(let[n,o]of Object.entries(i))e[`${r}.${n}`]={type:this.modules[r].uniformTypes?.[n],value:String(o)};return e}_addModule(e){let r=e.name;this.moduleUniforms[r]=Lb({},e.defaultUniforms||{},e.uniformTypes),this.moduleBindings[r]={}}};function Lb(t={},e={},r={}){let i={...t};for(let[n,o]of Object.entries(e))o!==void 0&&(i[n]=bp(t[n],o,r[n]));return i}function bp(t,e,r){if(!r||typeof r=="string")return ms(e);if(Array.isArray(r)){if(Tp(e)||!Array.isArray(e))return ms(e);let s=Array.isArray(t)&&!Tp(t)?[...t]:[],a=s.slice();for(let c=0;cr===void 0?void 0:ms(r)):wp(t)?Object.fromEntries(Object.entries(t).map(([e,r])=>[e,r===void 0?void 0:ms(r)])):t}function Tp(t){return ArrayBuffer.isView(t)||Array.isArray(t)&&(t.length===0||typeof t[0]=="number")}function wp(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&!ArrayBuffer.isView(t)}function jO(t){return!!t?.dependencies}z();z();var Sp={"+X":0,"-X":1,"+Y":2,"-Y":3,"+Z":4,"-Z":5};function _s(t){return t?Array.isArray(t)?t[0]??null:t:null}function Fb(t){let{dimension:e,data:r}=t;if(!r)return null;switch(e){case"1d":{let i=_s(r);if(!i)return null;let{width:n}=ys(i);return{width:n,height:1}}case"2d":{let i=_s(r);return i?ys(i):null}case"3d":case"2d-array":{if(!Array.isArray(r)||r.length===0)return null;let i=_s(r[0]);return i?ys(i):null}case"cube":{let i=Object.keys(r)[0]??null;if(!i)return null;let n=r[i],o=_s(n);return o?ys(o):null}case"cube-array":{if(!Array.isArray(r)||r.length===0)return null;let i=r[0],n=Object.keys(i)[0]??null;if(!n)return null;let o=_s(i[n]);return o?ys(o):null}default:return null}}function ys(t){if(dn(t))return Mo(t);if(typeof t=="object"&&"width"in t&&"height"in t)return{width:t.width,height:t.height};throw new Error("Unsupported mip-level data")}function $O(t){return typeof t=="object"&&t!==null&&"data"in t&&"width"in t&&"height"in t}function HO(t){return ArrayBuffer.isView(t)}function Ap(t){let{textureFormat:e,format:r}=t;if(e&&r&&e!==r)throw new Error(`Conflicting texture formats "${e}" and "${r}" provided for the same mip level`);return e??r}function Bb(t){let e=Sp[t];if(e===void 0)throw new Error(`Invalid cube face: ${t}`);return e}function YO(t,e){return 6*t+Bb(e)}function vp(t){throw new Error("setTexture1DData not supported in WebGL.")}function XO(t){return Array.isArray(t)?t:[t]}function vi(t,e,r,i){let n=XO(e),o=t,s=[];for(let a=0;a>a),height:Math.max(1,r.height>>a),...i?{format:i}:{}},textureFormat:i,z:o,mipLevel:a});else throw new Error("Unsupported 2D mip-level payload")}return s}function Ep(t){let e=[];for(let r=0;r{for(let[n,o]of Object.entries(r)){let s=YO(i,n);e.push(...vi(s,o))}}),e}var Ei=class t{device;id;props;_texture=null;_sampler=null;_view=null;ready;isReady=!1;destroyed=!1;resolveReady=()=>{};rejectReady=()=>{};get texture(){if(!this._texture)throw new Error("Texture not initialized yet");return this._texture}get sampler(){if(!this._sampler)throw new Error("Sampler not initialized yet");return this._sampler}get view(){if(!this._view)throw new Error("View not initialized yet");return this._view}get[Symbol.toStringTag](){return"DynamicTexture"}toString(){let e=this._texture?.width??this.props.width??"?",r=this._texture?.height??this.props.height??"?";return`DynamicTexture:"${this.id}":${e}x${r}px:(${this.isReady?"ready":"loading..."})`}constructor(e,r){this.device=e;let i=kr("dynamic-texture"),n=r;this.props={...t.defaultProps,id:i,...r,data:null},this.id=this.props.id,this.ready=new Promise((o,s)=>{this.resolveReady=o,this.rejectReady=s}),this.initAsync(n)}async initAsync(e){try{let r=await this._loadAllData(e);this._checkNotDestroyed();let i=r.data?GO({...r,width:e.width,height:e.height,format:e.format}):[],n="format"in e&&e.format!==void 0,o="usage"in e&&e.usage!==void 0,a=(()=>{if(this.props.width&&this.props.height)return{width:this.props.width,height:this.props.height};let g=Fb(r);return g||{width:this.props.width||1,height:this.props.height||1}})();if(!a||a.width<=0||a.height<=0)throw new Error(`${this} size could not be determined or was zero`);let c=qO(this.device,i,a,{format:n?e.format:void 0}),l=c.format??this.props.format,f={...this.props,...a,format:l,mipLevels:1,data:void 0};this.device.isTextureFormatCompressed(l)&&!o&&(f.usage=$.SAMPLE|$.COPY_DST);let u=this.props.mipmaps&&!c.hasExplicitMipChain&&!this.device.isTextureFormatCompressed(l);if(this.device.type==="webgpu"&&u){let g=this.props.dimension==="3d"?$.SAMPLE|$.STORAGE|$.COPY_DST|$.COPY_SRC:$.SAMPLE|$.RENDER|$.COPY_DST|$.COPY_SRC;f.usage|=g}let d=this.device.getMipLevelCount(f.width,f.height),h=c.hasExplicitMipChain?c.mipLevels:this.props.mipLevels==="auto"?d:Math.max(1,Math.min(d,this.props.mipLevels??1)),p={...f,mipLevels:h};this._texture=this.device.createTexture(p),this._sampler=this.texture.sampler,this._view=this.texture.view,c.subresources.length&&this._setTextureSubresources(c.subresources),this.props.mipmaps&&!c.hasExplicitMipChain&&!u&&v.warn(`${this} skipping auto-generated mipmaps for compressed texture format`)(),u&&this.generateMipmaps(),this.isReady=!0,this.resolveReady(this.texture),v.info(0,`${this} created`)()}catch(r){let i=r instanceof Error?r:new Error(String(r));this.rejectReady(i)}}destroy(){this._texture&&(this._texture.destroy(),this._texture=null,this._sampler=null,this._view=null),this.destroyed=!0}generateMipmaps(){this.device.type==="webgl"?this.texture.generateMipmapsWebGL():this.device.type==="webgpu"?this.device.generateMipmapsWebGPU(this.texture):v.warn(`${this} mipmaps not supported on ${this.device.type}`)}setSampler(e={}){this._checkReady();let r=e instanceof pt?e:this.device.createSampler(e);this.texture.setSampler(r),this._sampler=r}async readBuffer(e={}){this.isReady||await this.ready;let r=e.width??this.texture.width,i=e.height??this.texture.height,n=e.depthOrArrayLayers??this.texture.depth,o=this.texture.computeMemoryLayout({width:r,height:i,depthOrArrayLayers:n}),s=this.device.createBuffer({byteLength:o.byteLength,usage:j.COPY_DST|j.MAP_READ});this.texture.readBuffer({...e,width:r,height:i,depthOrArrayLayers:n},s);let a=this.device.createFence();return await a.signaled,a.destroy(),s}async readAsync(e={}){this.isReady||await this.ready;let r=e.width??this.texture.width,i=e.height??this.texture.height,n=e.depthOrArrayLayers??this.texture.depth,o=this.texture.computeMemoryLayout({width:r,height:i,depthOrArrayLayers:n}),s=await this.readBuffer(e),a=await s.readAsync(0,o.byteLength);return s.destroy(),a.buffer}resize(e){if(this._checkReady(),e.width===this.texture.width&&e.height===this.texture.height)return!1;let r=this.texture;return this._texture=r.clone(e),this._sampler=this.texture.sampler,this._view=this.texture.view,r.destroy(),v.info(`${this} resized`),!0}getCubeFaceIndex(e){let r=Sp[e];if(r===void 0)throw new Error(`Invalid cube face: ${e}`);return r}getCubeArrayFaceIndex(e,r){return 6*e+this.getCubeFaceIndex(r)}setTexture1DData(e){if(this._checkReady(),this.texture.props.dimension!=="1d")throw new Error(`${this} is not 1d`);let r=vp(e);this._setTextureSubresources(r)}setTexture2DData(e,r=0){if(this._checkReady(),this.texture.props.dimension!=="2d")throw new Error(`${this} is not 2d`);let i=vi(r,e);this._setTextureSubresources(i)}setTexture3DData(e){if(this.texture.props.dimension!=="3d")throw new Error(`${this} is not 3d`);let r=Ep(e);this._setTextureSubresources(r)}setTextureArrayData(e){if(this.texture.props.dimension!=="2d-array")throw new Error(`${this} is not 2d-array`);let r=Rp(e);this._setTextureSubresources(r)}setTextureCubeData(e){if(this.texture.props.dimension!=="cube")throw new Error(`${this} is not cube`);let r=Cp(e);this._setTextureSubresources(r)}setTextureCubeArrayData(e){if(this.texture.props.dimension!=="cube-array")throw new Error(`${this} is not cube-array`);let r=Pp(e);this._setTextureSubresources(r)}_setTextureSubresources(e){for(let r of e){let{z:i,mipLevel:n}=r;switch(r.type){case"external-image":let{image:o,flipY:s}=r;this.texture.copyExternalImage({image:o,z:i,mipLevel:n,flipY:s});break;case"texture-data":let{data:a,textureFormat:c}=r;if(c&&c!==this.texture.format)throw new Error(`${this} mip level ${n} uses format "${c}" but texture format is "${this.texture.format}"`);this.texture.writeData(a.data,{x:0,y:0,z:i,width:a.width,height:a.height,depthOrArrayLayers:1,mipLevel:n});break;default:throw new Error("Unsupported 2D mip-level payload")}}}async _loadAllData(e){let r=await Mp(e.data);return{dimension:e.dimension??"2d",data:r??null}}_checkNotDestroyed(){this.destroyed&&v.warn(`${this} already destroyed`)}_checkReady(){this.isReady||v.warn(`${this} Cannot perform this operation before ready`)}static defaultProps={...$.defaultProps,dimension:"2d",data:null,mipmaps:!1}};function GO(t){if(!t.data)return[];let e=t.width&&t.height?{width:t.width,height:t.height}:void 0,r="format"in t?t.format:void 0;switch(t.dimension){case"1d":return vp(t.data);case"2d":return vi(0,t.data,e,r);case"3d":return Ep(t.data);case"2d-array":return Rp(t.data);case"cube":return Cp(t.data);case"cube-array":return Pp(t.data);default:throw new Error(`Unhandled dimension ${t.dimension}`)}}function qO(t,e,r,i){if(e.length===0)return{subresources:e,mipLevels:1,format:i.format,hasExplicitMipChain:!1};let n=new Map;for(let f of e){let u=n.get(f.z)??[];u.push(f),n.set(f.z,u)}let o=e.some(f=>f.mipLevel>0),s=i.format,a=Number.POSITIVE_INFINITY,c=[];for(let[f,u]of n){let d=[...u].sort((T,y)=>T.mipLevel-y.mipLevel),h=d[0];if(!h||h.mipLevel!==0)throw new Error(`DynamicTexture: slice ${f} is missing mip level 0`);let p=Ub(t,h);if(p.width!==r.width||p.height!==r.height)throw new Error(`DynamicTexture: slice ${f} base level dimensions ${p.width}x${p.height} do not match expected ${r.width}x${r.height}`);let g=kb(h);if(g){if(s&&s!==g)throw new Error(`DynamicTexture: slice ${f} base level format "${g}" does not match texture format "${s}"`);s=g}let m=s&&t.isTextureFormatCompressed(s)?KO(t,p.width,p.height,s):t.getMipLevelCount(p.width,p.height),_=0;for(let T=0;T=m)break;let x=Ub(t,y),w=Math.max(1,p.width>>T),b=Math.max(1,p.height>>T);if(x.width!==w||x.height!==b)break;let E=kb(y);if(E&&(s||(s=E),E!==s))break;_++,c.push(y)}a=Math.min(a,_)}let l=Number.isFinite(a)?Math.max(1,a):1;return{subresources:c.filter(f=>f.mipLevel>a),l=Math.max(1,r>>a);if(c[c.name,c])||[]),n=r.shaderInputs||new gl(i,{disableWarnings:this.props.disableWarnings});this.setShaderInputs(n);let o=QO(e),s=(this.props.modules?.length>0?this.props.modules:this.shaderInputs?.getModules())||[];if(this.props.shaderLayout=xp(this.props.shaderLayout,s)||null,this.device.type==="webgpu"&&this.props.source){let{source:c,getUniforms:l,bindingTable:f}=this.props.shaderAssembler.assembleWGSLShader({platformInfo:o,...this.props,modules:s});this.source=c,this._getModuleUniforms=l,this._bindingTable=f;let u=e.getShaderLayout?.(this.source);this.props.shaderLayout=xp(this.props.shaderLayout||u||null,s)||null}else{let{vs:c,fs:l,getUniforms:f}=this.props.shaderAssembler.assembleGLSLShaderPair({platformInfo:o,...this.props,modules:s});this.vs=c,this.fs=l,this._getModuleUniforms=f,this._bindingTable=[]}this.vertexCount=this.props.vertexCount,this.instanceCount=this.props.instanceCount,this.topology=this.props.topology,this.bufferLayout=this.props.bufferLayout,this.parameters=this.props.parameters,r.geometry&&this.setGeometry(r.geometry),this.pipelineFactory=r.pipelineFactory||ko.getDefaultPipelineFactory(this.device),this.shaderFactory=r.shaderFactory||Uo.getDefaultShaderFactory(this.device),this.pipeline=this._updatePipeline(),this.vertexArray=e.createVertexArray({shaderLayout:this.pipeline.shaderLayout,bufferLayout:this.pipeline.bufferLayout}),this._gpuGeometry&&this._setGeometryAttributes(this._gpuGeometry),"isInstanced"in r&&(this.isInstanced=r.isInstanced),r.instanceCount&&this.setInstanceCount(r.instanceCount),r.vertexCount&&this.setVertexCount(r.vertexCount),r.indexBuffer&&this.setIndexBuffer(r.indexBuffer),r.attributes&&this.setAttributes(r.attributes),r.constantAttributes&&this.setConstantAttributes(r.constantAttributes),r.bindings&&this.setBindings(r.bindings),r.transformFeedback&&(this.transformFeedback=r.transformFeedback)}destroy(){this._destroyed||(this.pipelineFactory.release(this.pipeline),this.shaderFactory.release(this.pipeline.vs),this.pipeline.fs&&this.pipeline.fs!==this.pipeline.vs&&this.shaderFactory.release(this.pipeline.fs),this._uniformStore.destroy(),this._gpuGeometry?.destroy(),this._destroyed=!0)}needsRedraw(){this._getBindingsUpdateTimestamp()>this._lastDrawTimestamp&&this.setNeedsRedraw("contents of bound textures or buffers updated");let e=this._needsRedraw;return this._needsRedraw=!1,e}setNeedsRedraw(e){this._needsRedraw||=e}getBindingDebugTable(){return this._bindingTable}predraw(){this.updateShaderInputs(),this.pipeline=this._updatePipeline()}draw(e){let r=this._areBindingsLoading();if(r)return v.info(Ur,`>>> DRAWING ABORTED ${this.id}: ${r} not loaded`)(),!1;try{e.pushDebugGroup(`${this}.predraw(${e})`),this.predraw()}finally{e.popDebugGroup()}let i,n=this.pipeline.isErrored;try{if(e.pushDebugGroup(`${this}.draw(${e})`),this._logDrawCallStart(),this.pipeline=this._updatePipeline(),n=this.pipeline.isErrored,n)v.info(Ur,`>>> DRAWING ABORTED ${this.id}: ${zb}`)(),i=!1;else{let o=this._getBindings(),s=this._getBindGroups(),{indexBuffer:a}=this.vertexArray,c=a?a.byteLength/(a.indexType==="uint32"?4:2):void 0;i=this.pipeline.draw({renderPass:e,vertexArray:this.vertexArray,isInstanced:this.isInstanced,vertexCount:this.vertexCount,instanceCount:this.instanceCount,indexCount:c,transformFeedback:this.transformFeedback||void 0,bindings:o,bindGroups:s,_bindGroupCacheKeys:this._getBindGroupCacheKeys(),uniforms:this.props.uniforms,parameters:this.parameters,topology:this.topology})}}finally{e.popDebugGroup(),this._logDrawCallEnd()}return this._logFramebuffer(e),i?(this._lastDrawTimestamp=this.device.timestamp,this._needsRedraw=!1):n?this._needsRedraw=zb:this._needsRedraw="waiting for resource initialization",i}setGeometry(e){this._gpuGeometry?.destroy();let r=e&&Eb(this.device,e);if(r){this.setTopology(r.topology||"triangle-list");let i=new Pn(this.bufferLayout);this.bufferLayout=i.mergeBufferLayouts(r.bufferLayout,this.bufferLayout),this.vertexArray&&this._setGeometryAttributes(r)}this._gpuGeometry=r}setTopology(e){e!==this.topology&&(this.topology=e,this._setPipelineNeedsUpdate("topology"))}setBufferLayout(e){let r=new Pn(this.bufferLayout);this.bufferLayout=this._gpuGeometry?r.mergeBufferLayouts(e,this._gpuGeometry.bufferLayout):e,this._setPipelineNeedsUpdate("bufferLayout"),this.pipeline=this._updatePipeline(),this.vertexArray=this.device.createVertexArray({shaderLayout:this.pipeline.shaderLayout,bufferLayout:this.pipeline.bufferLayout}),this._gpuGeometry&&this._setGeometryAttributes(this._gpuGeometry)}setParameters(e){pl(e,this.parameters,2)||(this.parameters=e,this._setPipelineNeedsUpdate("parameters"))}setInstanceCount(e){this.instanceCount=e,this.isInstanced===void 0&&e>0&&(this.isInstanced=!0),this.setNeedsRedraw("instanceCount")}setVertexCount(e){this.vertexCount=e,this.setNeedsRedraw("vertexCount")}setShaderInputs(e){this.shaderInputs=e,this._uniformStore=new Ko(this.device,this.shaderInputs.modules);for(let[r,i]of Object.entries(this.shaderInputs.modules))if(Nb(i)&&!this.material?.ownsModule(r)){let n=this._uniformStore.getManagedUniformBuffer(r);this.bindings[`${r}Uniforms`]=n}this.setNeedsRedraw("shaderInputs")}setMaterial(e){this.material=e,this.setNeedsRedraw("material")}updateShaderInputs(){this._uniformStore.setUniforms(this.shaderInputs.getUniformValues()),this.setBindings(this._getNonMaterialBindings(this.shaderInputs.getBindingValues())),this.setNeedsRedraw("shaderInputs")}setBindings(e){Object.assign(this.bindings,e),this.setNeedsRedraw("bindings")}setTransformFeedback(e){this.transformFeedback=e,this.setNeedsRedraw("transformFeedback")}setIndexBuffer(e){this.vertexArray.setIndexBuffer(e),this.setNeedsRedraw("indexBuffer")}setAttributes(e,r){let i=r?.disableWarnings??this.props.disableWarnings;e.indices&&v.warn(`Model:${this.id} setAttributes() - indexBuffer should be set using setIndexBuffer()`)(),this.bufferLayout=Ob(this.pipeline.shaderLayout,this.bufferLayout);let n=new Pn(this.bufferLayout);for(let[o,s]of Object.entries(e)){let a=n.getBufferLayout(o);if(!a){i||v.warn(`Model(${this.id}): Missing layout for buffer "${o}".`)();continue}let c=n.getAttributeNamesForBuffer(a),l=!1;for(let f of c){let u=this._attributeInfos[f];if(u){let d=this.device.type==="webgpu"?n.getBufferIndex(u.bufferName):u.location;this.vertexArray.setBuffer(d,s),l=!0}}!l&&!i&&v.warn(`Model(${this.id}): Ignoring buffer "${s.id}" for unknown attribute "${o}"`)()}this.setNeedsRedraw("attributes")}setConstantAttributes(e,r){for(let[i,n]of Object.entries(e)){let o=this._attributeInfos[i];o?this.vertexArray.setConstantWebGL(o.location,n):(r?.disableWarnings??this.props.disableWarnings)||v.warn(`Model "${this.id}: Ignoring constant supplied for unknown attribute "${i}"`)()}this.setNeedsRedraw("constants")}_areBindingsLoading(){for(let e of Object.values(this.bindings))if(e instanceof Ei&&!e.isReady)return e.id;for(let e of Object.values(this.material?.bindings||{}))if(e instanceof Ei&&!e.isReady)return e.id;return!1}_getBindings(){let e={};for(let[r,i]of Object.entries(this.bindings))i instanceof Ei?i.isReady&&(e[r]=i.texture):e[r]=i;return e}_getBindGroups(){let e=this.pipeline?.shaderLayout||this.props.shaderLayout||{bindings:[]},r=e.bindings.length?zo(e,this._getBindings()):{0:this._getBindings()};if(!this.material)return r;for(let[i,n]of Object.entries(this.material.getBindingsByGroup())){let o=Number(i);r[o]={...r[o]||{},...n}}return r}_getBindGroupCacheKeys(){let e=this.material?.getBindGroupCacheKey(3);return e?{3:e}:{}}_getBindingsUpdateTimestamp(){let e=0;for(let r of Object.values(this.bindings))r instanceof pi?e=Math.max(e,r.texture.updateTimestamp):r instanceof j||r instanceof $?e=Math.max(e,r.updateTimestamp):r instanceof Ei?e=r.texture?Math.max(e,r.texture.updateTimestamp):1/0:r instanceof pt||(e=Math.max(e,r.buffer.updateTimestamp));return Math.max(e,this.material?.getBindingsUpdateTimestamp()||0)}_setGeometryAttributes(e){let r={...e.attributes};for(let[i]of Object.entries(r))!this.pipeline.shaderLayout.attributes.find(n=>n.name===i)&&i!=="positions"&&delete r[i];this.vertexCount=e.vertexCount,this.setIndexBuffer(e.indices||null),this.setAttributes(e.attributes,{disableWarnings:!0}),this.setAttributes(r,{disableWarnings:this.props.disableWarnings}),this.setNeedsRedraw("geometry attributes")}_setPipelineNeedsUpdate(e){this._pipelineNeedsUpdate||=e,this.setNeedsRedraw(e)}_updatePipeline(){if(this._pipelineNeedsUpdate){let e=null,r=null;this.pipeline&&(v.log(1,`Model ${this.id}: Recreating pipeline because "${this._pipelineNeedsUpdate}".`)(),e=this.pipeline.vs,r=this.pipeline.fs),this._pipelineNeedsUpdate=!1;let i=this.shaderFactory.createShader({id:`${this.id}-vertex`,stage:"vertex",source:this.source||this.vs,debugShaders:this.props.debugShaders}),n=null;this.source?n=i:this.fs&&(n=this.shaderFactory.createShader({id:`${this.id}-fragment`,stage:"fragment",source:this.source||this.fs,debugShaders:this.props.debugShaders})),this.pipeline=this.pipelineFactory.createRenderPipeline({...this.props,bindings:void 0,bufferLayout:this.bufferLayout,topology:this.topology,parameters:this.parameters,bindGroups:this._getBindGroups(),vs:i,fs:n}),this._attributeInfos=Vc(this.pipeline.shaderLayout,this.bufferLayout),e&&this.shaderFactory.release(e),r&&r!==e&&this.shaderFactory.release(r)}return this.pipeline}_lastLogTime=0;_logOpen=!1;_logDrawCallStart(){let e=v.level>3?0:ZO;v.level<2||Date.now()-this._lastLogTime>> DRAWING MODEL ${this.id}`,{collapsed:v.level<=2})())}_logDrawCallEnd(){if(this._logOpen){let e=Rb(this.pipeline.shaderLayout,this.id);v.table(Ur,e)();let r=this.shaderInputs.getDebugTable();v.table(Ur,r)();let i=this._getAttributeDebugTable();v.table(Ur,this._attributeInfos)(),v.table(Ur,i)(),v.groupEnd(Ur)(),this._logOpen=!1}}_drawCount=0;_logFramebuffer(e){let r=this.device.props.debugFramebuffers;if(this._drawCount++,!r)return;let i=e.props.framebuffer;Mb(e,i,{id:i?.id||`${this.id}-framebuffer`,minimap:!0})}_getAttributeDebugTable(){let e={};for(let[r,i]of Object.entries(this._attributeInfos)){let n=this.vertexArray.attributes[i.location];e[i.location]={name:r,type:i.shaderType,values:n?this._getBufferOrConstantValues(n,i.bufferDataType):"null"}}if(this.vertexArray.indexBuffer){let{indexBuffer:r}=this.vertexArray,i=r.indexType==="uint32"?new Uint32Array(r.debugData):new Uint16Array(r.debugData);e.indices={name:"indices",type:r.indexType,values:i.toString()}}return e}_getBufferOrConstantValues(e,r){let i=ke.getTypedArrayConstructor(r);return(e instanceof j?new i(e.debugData):e).toString()}_getNonMaterialBindings(e){if(!this.material)return e;let r={};for(let[i,n]of Object.entries(e))this.material.ownsBinding(i)||(r[i]=n);return r}};function QO(t){return{type:t.type,shaderLanguage:t.info.shadingLanguage,shaderLanguageVersion:t.info.shadingLanguageVersion,gpu:t.info.gpu,features:t.features}}z();var zr=class t{device;model;transformFeedback;static defaultProps={...he.defaultProps,outputs:void 0,feedbackBuffers:void 0};static isSupported(e){return e?.info?.type==="webgl"}constructor(e,r=t.defaultProps){if(!t.isSupported(e))throw new Error("BufferTransform not yet implemented on WebGPU");this.device=e,this.model=new he(this.device,{id:r.id||"buffer-transform-model",fs:r.fs||Ld(),topology:r.topology||"point-list",varyings:r.outputs||r.varyings,...r}),this.transformFeedback=this.device.createTransformFeedback({layout:this.model.pipeline.shaderLayout,buffers:r.feedbackBuffers}),this.model.setTransformFeedback(this.transformFeedback),Object.seal(this)}destroy(){this.model&&this.model.destroy()}delete(){this.destroy()}run(e){e?.inputBuffers&&this.model.setAttributes(e.inputBuffers),e?.outputBuffers&&this.transformFeedback.setBuffers(e.outputBuffers);let r=this.device.beginRenderPass(e);this.model.draw(r),r.end()}getBuffer(e){return this.transformFeedback.getBuffer(e)}readAsync(e){let r=this.getBuffer(e);if(!r)throw new Error("BufferTransform#getBuffer");if(r instanceof j)return r.readAsync();let{buffer:i,byteOffset:n=0,byteLength:o=i.byteLength}=r;return i.readAsync(n,o)}};var Ae=class{id;topology;vertexCount;indices;attributes;userData={};constructor(e){let{attributes:r={},indices:i=null,vertexCount:n=null}=e;this.id=e.id||kr("geometry"),this.topology=e.topology,i&&(this.indices=ArrayBuffer.isView(i)?{value:i,size:1}:i),this.attributes={};for(let[o,s]of Object.entries(r)){let a=ArrayBuffer.isView(s)?{value:s}:s;if(!ArrayBuffer.isView(a.value))throw new Error(`${this._print(o)}: must be typed array or object with value as typed array`);if((o==="POSITION"||o==="positions")&&!a.size&&(a.size=3),o==="indices"){if(this.indices)throw new Error("Multiple indices detected");this.indices=a}else this.attributes[o]=a}this.indices&&this.indices.isIndexed!==void 0&&(this.indices=Object.assign({},this.indices),delete this.indices.isIndexed),this.vertexCount=n||this._calculateVertexCount(this.attributes,this.indices)}getVertexCount(){return this.vertexCount}getAttributes(){return this.indices?{indices:this.indices,...this.attributes}:this.attributes}_print(e){return`Geometry ${this.id} attribute ${e}`}_setAttributes(e,r){return this}_calculateVertexCount(e,r){if(r)return r.value.length;let i=1/0;for(let n of Object.values(e)){let{value:o,size:s,constant:a}=n;!a&&o&&s!==void 0&&s>=1&&(i=Math.min(i,o.length/s))}return i}};var JO={blendColorOperation:"add",blendColorSrcFactor:"one",blendColorDstFactor:"zero",blendAlphaOperation:"add",blendAlphaSrcFactor:"constant",blendAlphaDstFactor:"zero"},Ri=class extends cr{constructor(){super(...arguments),this._colorEncoderState=null}render(e){return"pickingFBO"in e?this._drawPickingBuffer(e):{decodePickingColor:null,stats:super._render(e)}}_drawPickingBuffer({layers:e,layerFilter:r,views:i,viewports:n,onViewportActive:o,pickingFBO:s,deviceRect:{x:a,y:c,width:l,height:f},cullRect:u,effects:d,pass:h="picking",pickZ:p,shaderModuleProps:g,clearColor:m}){this.pickZ=p;let _=this._resetColorEncoder(p),T=[a,c,l,f],y=super._render({target:s,layers:e,layerFilter:r,views:i,viewports:n,onViewportActive:o,cullRect:u,effects:d?.filter(w=>w.useInPicking),pass:h,isPicking:!0,shaderModuleProps:g,clearColor:m??[0,0,0,0],colorMask:15,scissorRect:T});return this._colorEncoderState=null,{decodePickingColor:_&&e4.bind(null,_),stats:y}}shouldDrawLayer(e){let{pickable:r,operation:i}=e.props;return r&&i.includes("draw")||i.includes("terrain")||i.includes("mask")}getShaderModuleProps(e,r,i){return{picking:{isActive:1,isAttribute:this.pickZ},lighting:{enabled:!1}}}getLayerParameters(e,r,i){let n={...e.props.parameters},{pickable:o,operation:s}=e.props;return this._colorEncoderState?o&&s.includes("draw")?(Object.assign(n,JO),n.blend=!0,this.device.type==="webgpu"?n.blendConstant=Wb(this._colorEncoderState,e,i):n.blendColor=Wb(this._colorEncoderState,e,i),s.includes("terrain")&&e.state?._hasPickingCover&&(n.blendAlphaSrcFactor="one")):s.includes("terrain")&&(n.blend=!1):n.blend=!1,n}_resetColorEncoder(e){return this._colorEncoderState=e?null:{byLayer:new Map,byAlpha:[]},this._colorEncoderState}};function Wb(t,e,r){let{byLayer:i,byAlpha:n}=t,o,s=i.get(e);return s?(s.viewports.push(r),o=s.a):(o=i.size+1,o<=255?(s={a:o,layer:e,viewports:[r]},i.set(e,s),n[o]=s):(F.warn("Too many pickable layers, only picking the first 255")(),o=0)),[0,0,0,o/255]}function e4(t,e){let r=t.byAlpha[e[3]];return r&&{pickedLayer:r.layer,pickedViewports:r.viewports,pickedObjectIndex:r.layer.decodePickingColor(e)}}var Wr={NO_STATE:"Awaiting state",MATCHED:"Matched. State transferred from previous layer",INITIALIZED:"Initialized",AWAITING_GC:"Discarded. Awaiting garbage collection",AWAITING_FINALIZATION:"No longer matched. Awaiting garbage collection",FINALIZED:"Finalized! Awaiting garbage collection"},Mn=Symbol.for("component"),ct=Symbol.for("propTypes"),ml=Symbol.for("deprecatedProps"),fr=Symbol.for("asyncPropDefaults"),zt=Symbol.for("asyncPropOriginal"),yt=Symbol.for("asyncPropResolved");function lt(t,e=()=>!0){return Array.isArray(t)?Vb(t,e,[]):e(t)?[t]:[]}function Vb(t,e,r){let i=-1;for(;++i0}delete(){}getData(){return this.isLoaded?this._error?Promise.reject(this._error):this._content:this._loader.then(()=>this.getData())}setData(e,r){if(e===this._data&&!r)return;this._data=e;let i=++this._loadCount,n=e;typeof e=="string"&&(n=Mr(e)),n instanceof Promise?(this.isLoaded=!1,this._loader=n.then(o=>{this._loadCount===i&&(this.isLoaded=!0,this._error=void 0,this._content=o)}).catch(o=>{this._loadCount===i&&(this.isLoaded=!0,this._error=o||!0)})):(this.isLoaded=!0,this._error=void 0,this._content=e);for(let o of this._subscribers)o.onChange(this.getData())}};var bs=class{constructor(e){this.protocol=e.protocol||"resource://",this._context={device:e.device,gl:e.device?.gl,resourceManager:this},this._resources={},this._consumers={},this._pruneRequest=null}contains(e){return e.startsWith(this.protocol)?!0:e in this._resources}add({resourceId:e,data:r,forceUpdate:i=!1,persistent:n=!0}){let o=this._resources[e];o?o.setData(r,i):(o=new xs(e,r,this._context),this._resources[e]=o),o.persistent=n}remove(e){let r=this._resources[e];r&&(r.delete(),delete this._resources[e])}unsubscribe({consumerId:e}){let r=this._consumers[e];if(r){for(let i in r){let n=r[i],o=this._resources[n.resourceId];o&&o.unsubscribe(n)}delete this._consumers[e],this.prune()}}subscribe({resourceId:e,onChange:r,consumerId:i,requestId:n="default"}){let{_resources:o,protocol:s}=this;e.startsWith(s)&&(e=e.replace(s,""),o[e]||this.add({resourceId:e,data:null,persistent:!1}));let a=o[e];if(this._track(i,n,a,r),a)return a.getData()}prune(){this._pruneRequest||(this._pruneRequest=setTimeout(()=>this._prune(),0))}finalize(){for(let e in this._resources)this._resources[e].delete()}_track(e,r,i,n){let o=this._consumers,s=o[e]=o[e]||{},a=s[r],c=a&&a.resourceId&&this._resources[a.resourceId];c&&(c.unsubscribe(a),this.prune()),i&&(a?(a.onChange=n,a.resourceId=i.id):a={onChange:n,resourceId:i.id},s[r]=a,i.subscribe(a))}_prune(){this._pruneRequest=null;for(let e of Object.keys(this._resources)){let r=this._resources[e];!r.persistent&&!r.inUse()&&(r.delete(),delete this._resources[e])}}};var t4="layerManager.setLayers",r4="layerManager.activateViewport",Ts=class{constructor(e,r){this._lastRenderedLayers=[],this._needsRedraw=!1,this._needsUpdate=!1,this._nextLayers=null,this._debug=!1,this._defaultShaderModulesChanged=!1,this.activateViewport=a=>{ae(r4,this,a),a&&(this.context.viewport=a)};let{deck:i,stats:n,viewport:o,timeline:s}=r||{};this.layers=[],this.resourceManager=new bs({device:e,protocol:"deck://"}),this.context={mousePosition:null,userData:{},layerManager:this,device:e,gl:e?.gl,deck:i,shaderAssembler:hb(e?.info?.shadingLanguage||"glsl"),defaultShaderModules:[Jh],renderPass:void 0,stats:n||new it({id:"deck.gl"}),viewport:o||new Rn({id:"DEFAULT-INITIAL-VIEWPORT"}),timeline:s||new Ai,resourceManager:this.resourceManager,onError:void 0},Object.seal(this)}finalize(){this.resourceManager.finalize();for(let e of this.layers)this._finalizeLayer(e)}needsRedraw(e={clearRedrawFlags:!1}){let r=this._needsRedraw;e.clearRedrawFlags&&(this._needsRedraw=!1);for(let i of this.layers){let n=i.getNeedsRedraw(e);r=r||n}return r}needsUpdate(){return this._nextLayers&&this._nextLayers!==this._lastRenderedLayers?"layers changed":this._defaultShaderModulesChanged?"shader modules changed":this._needsUpdate}setNeedsRedraw(e){this._needsRedraw=this._needsRedraw||e}setNeedsUpdate(e){this._needsUpdate=this._needsUpdate||e}getLayers({layerIds:e}={}){return e?this.layers.filter(r=>e.find(i=>r.id.indexOf(i)===0)):this.layers}setProps(e){"debug"in e&&(this._debug=e.debug),"userData"in e&&(this.context.userData=e.userData),"layers"in e&&(this._nextLayers=e.layers),"onError"in e&&(this.context.onError=e.onError)}setLayers(e,r){ae(t4,this,r,e),this._lastRenderedLayers=e;let i=lt(e,Boolean);for(let n of i)n.context=this.context;this._updateLayers(this.layers,i)}updateLayers(){let e=this.needsUpdate();e&&(this.setNeedsRedraw(`updating layers: ${e}`),this.setLayers(this._nextLayers||this._lastRenderedLayers,e)),this._nextLayers=null}addDefaultShaderModule(e){let{defaultShaderModules:r}=this.context;r.find(i=>i.name===e.name)||(r.push(e),this._defaultShaderModulesChanged=!0)}removeDefaultShaderModule(e){let{defaultShaderModules:r}=this.context,i=r.findIndex(n=>n.name===e.name);i>=0&&(r.splice(i,1),this._defaultShaderModulesChanged=!0)}_handleError(e,r,i){i.raiseError(r,`${e} of ${i}`)}_updateLayers(e,r){let i={};for(let s of e)i[s.id]?F.warn(`Multiple old layers with same id ${s.id}`)():i[s.id]=s;if(this._defaultShaderModulesChanged){for(let s of e)s.setNeedsUpdate(),s.setChangeFlags({extensionsChanged:!0});this._defaultShaderModulesChanged=!1}let n=[];this._updateSublayersRecursively(r,i,n),this._finalizeOldLayers(i);let o=!1;for(let s of n)if(s.hasUniformTransition()){o=`Uniform transition in ${s}`;break}this._needsUpdate=o,this.layers=n}_updateSublayersRecursively(e,r,i){for(let n of e){n.context=this.context;let o=r[n.id];o===null&&F.warn(`Multiple new layers with same id ${n.id}`)(),r[n.id]=null;let s=null;try{this._debug&&o!==n&&n.validateProps(),o?(this._transferLayerState(o,n),this._updateLayer(n)):this._initializeLayer(n),i.push(n),s=n.isComposite?n.getSubLayers():null}catch(a){this._handleError("matching",a,n)}s&&this._updateSublayersRecursively(s,r,i)}}_finalizeOldLayers(e){for(let r in e){let i=e[r];i&&this._finalizeLayer(i)}}_initializeLayer(e){try{e._initialize(),e.lifecycle=Wr.INITIALIZED}catch(r){this._handleError("initialization",r,e)}}_transferLayerState(e,r){r._transferState(e),r.lifecycle=Wr.MATCHED,r!==e&&(e.lifecycle=Wr.AWAITING_GC)}_updateLayer(e){try{e._update()}catch(r){this._handleError("update",r,e)}}_finalizeLayer(e){this._needsRedraw=this._needsRedraw||`finalized ${e}`,e.lifecycle=Wr.AWAITING_FINALIZATION;try{e._finalize(),e.lifecycle=Wr.FINALIZED}catch(r){this._handleError("finalization",r,e)}}};function de(t,e,r){if(t===e)return!0;if(!r||!t||!e)return!1;if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(let i=0;ir.containsPixel(e)):this._viewports}getViews(){let e={};return this.views.forEach(r=>{e[r.id]=r}),e}getView(e){return this.views.find(r=>r.id===e)}getViewState(e){let r=typeof e=="string"?this.getView(e):e,i=r&&this.viewState[r.getViewStateId()]||this.viewState;return r?r.filterViewState(i):i}getViewport(e){return this._viewportMap[e]}unproject(e,r){let i=this.getViewports(),n={x:e[0],y:e[1]};for(let o=i.length-1;o>=0;--o){let s=i[o];if(s.containsPixel(n)){let a=e.slice();return a[0]-=s.x,a[1]-=s.y,s.unproject(a,r)}}return null}setProps(e){e.views&&this._setViews(e.views),e.viewState&&this._setViewState(e.viewState),("width"in e||"height"in e)&&this._setSize(e.width,e.height),"pickPosition"in e&&(this._pickPosition=e.pickPosition),this._isUpdating||this._update()}_update(){this._isUpdating=!0,this._needsUpdate&&(this._needsUpdate=!1,this._rebuildViewports()),this._needsUpdate&&(this._needsUpdate=!1,this._rebuildViewports()),this._isUpdating=!1}_setSize(e,r){(e!==this.width||r!==this.height)&&(this.width=e,this.height=r,this.setNeedsUpdate("Size changed"))}_setViews(e){e=lt(e,Boolean),this._diffViews(e,this.views)&&this.setNeedsUpdate("views changed"),this.views=e}_setViewState(e){e?(!de(e,this.viewState,3)&&this.setNeedsUpdate("viewState changed"),this.viewState=e):F.warn("missing `viewState` or `initialViewState`")()}_createController(e,r){let i=r.type;return new i({timeline:this.timeline,eventManager:this._eventManager,onViewStateChange:this._eventCallbacks.onViewStateChange,onStateChange:this._eventCallbacks.onInteractionStateChange,makeViewport:o=>this.getView(e.id)?.makeViewport({viewState:o,width:this.width,height:this.height}),pickPosition:this._pickPosition})}_updateController(e,r,i,n){let o=e.controller;if(o&&i){let s={...r,...o,id:e.id,x:i.x,y:i.y,width:i.width,height:i.height};return(!n||n.constructor!==o.type)&&(n=this._createController(e,s)),n&&n.setProps(s),n}return null}_rebuildViewports(){let{views:e}=this,r=this.controllers;this._viewports=[],this.controllers={};let i=!1;for(let n=e.length;n--;){let o=e[n],s=this.getViewState(o),a=o.makeViewport({viewState:s,width:this.width,height:this.height}),c=r[o.id],l=!!o.controller;l&&!c&&(i=!0),(i||!l)&&c&&(c.finalize(),c=null),this.controllers[o.id]=this._updateController(o,s,a,c),a&&this._viewports.unshift(a)}for(let n in r){let o=r[n];o&&!this.controllers[n]&&o.finalize()}this._buildViewportMap()}_buildViewportMap(){this._viewportMap={},this._viewports.forEach(e=>{e.id&&(this._viewportMap[e.id]=this._viewportMap[e.id]||e)})}_diffViews(e,r){return e.length!==r.length?!0:e.some((i,n)=>!e[n].equals(r[n]))}};var i4=/^(?:\d+\.?\d*|\.\d+)$/;function ur(t){switch(typeof t){case"number":if(!Number.isFinite(t))throw new Error(`Could not parse position string ${t}`);return{type:"literal",value:t};case"string":try{let e=n4(t);return new Np(e).parseExpression()}catch(e){let r=e instanceof Error?e.message:String(e);throw new Error(`Could not parse position string ${t}: ${r}`)}default:throw new Error(`Could not parse position string ${t}`)}}function Op(t,e){switch(t.type){case"literal":return t.value;case"percentage":return Math.round(t.value*e);case"binary":let r=Op(t.left,e),i=Op(t.right,e);return t.operator==="+"?r+i:r-i;default:throw new Error("Unknown layout expression type")}}function dr(t,e){return Op(t,e)}function n4(t){let e=[],r=0;for(;r="0"&&t<="9"}function $b(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"}function o4(t){return!!(t&&t.type==="symbol"&&(t.value==="+"||t.value==="-"))}function Hb(t,e){let r={...t};for(let i in e)i!=="id"&&(Array.isArray(r[i])&&Array.isArray(e[i])?r[i]=s4(r[i],e[i]):r[i]=e[i]);return r}function s4(t,e){t=t.slice();for(let r=0;r{},Dp={BREAK:1,SNAP_TO_END:2,IGNORE:3},a4=t=>t,c4=Dp.BREAK,Ss=class{constructor(e){this._onTransitionUpdate=r=>{let{time:i,settings:{interpolator:n,startProps:o,endProps:s,duration:a,easing:c}}=r,l=c(i/a),f=n.interpolateProps(o,s,l);this.propsInTransition=this.getControllerState({...this.props,...f}).getViewportProps(),this.onViewStateChange({viewState:this.propsInTransition,oldViewState:this.props})},this.getControllerState=e.getControllerState,this.propsInTransition=null,this.transition=new xt(e.timeline),this.onViewStateChange=e.onViewStateChange||Yb,this.onStateChange=e.onStateChange||Yb}finalize(){this.transition.cancel()}getViewportInTransition(){return this.propsInTransition}processViewStateChange(e){let r=!1,i=this.props;if(this.props=e,!i||this._shouldIgnoreViewportChange(i,e))return!1;if(this._isTransitionEnabled(e)){let n=i;if(this.transition.inProgress){let{interruption:o,endProps:s}=this.transition.settings;n={...i,...o===Dp.SNAP_TO_END?s:this.propsInTransition||i}}this._triggerTransition(n,e),r=!0}else this.transition.cancel();return r}updateTransition(){this.transition.update()}_isTransitionEnabled(e){let{transitionDuration:r,transitionInterpolator:i}=e;return(r>0||r==="auto")&&!!i}_isUpdateDueToCurrentTransition(e){return this.transition.inProgress&&this.propsInTransition?this.transition.settings.interpolator.arePropsEqual(e,this.propsInTransition):!1}_shouldIgnoreViewportChange(e,r){return this.transition.inProgress?this.transition.settings.interruption===Dp.IGNORE||this._isUpdateDueToCurrentTransition(r):this._isTransitionEnabled(r)?r.transitionInterpolator.arePropsEqual(e,r):!0}_triggerTransition(e,r){let i=this.getControllerState(e),n=this.getControllerState(r).shortestPathFrom(i),o=r.transitionInterpolator,s=o.getDuration?o.getDuration(e,r):r.transitionDuration;if(s===0)return;let a=o.initializeProps(e,n);this.propsInTransition={};let c={duration:s,easing:r.transitionEasing||a4,interpolator:o,interruption:r.transitionInterruption||c4,startProps:a.start,endProps:a.end,onStart:r.onTransitionStart,onUpdate:this._onTransitionUpdate,onInterrupt:this._onTransitionEnd(r.onTransitionInterrupt),onEnd:this._onTransitionEnd(r.onTransitionEnd)};this.transition.start(c),this.onStateChange({inTransition:!0}),this.updateTransition()}_onTransitionEnd(e){return r=>{this.propsInTransition=null,this.onStateChange({inTransition:!1,isZooming:!1,isPanning:!1,isRotating:!1}),e?.(r)}}};function J(t,e){if(!t)throw new Error(e||"deck.gl: assertion failed.")}var As=class{constructor(e){let{compare:r,extract:i,required:n}=e;this._propsToCompare=r,this._propsToExtract=i||r,this._requiredProps=n}arePropsEqual(e,r){for(let i of this._propsToCompare)if(!(i in e)||!(i in r)||!nr(e[i],r[i]))return!1;return!0}initializeProps(e,r){let i={},n={};for(let o of this._propsToExtract)(o in e||o in r)&&(i[o]=e[o],n[o]=r[o]);return this._checkRequiredProps(i),this._checkRequiredProps(n),{start:i,end:n}}getDuration(e,r){return r.transitionDuration}_checkRequiredProps(e){this._requiredProps&&this._requiredProps.forEach(r=>{let i=e[r];J(Number.isFinite(i)||Array.isArray(i),`${r} is required for transition`)})}};var _l=Math.PI/180,Xb=180/Math.PI,yl=6370972,hr=256;function l4(){let t=hr/yl,e=Math.PI/180*hr;return{unitsPerMeter:[t,t,t],unitsPerMeter2:[0,0,0],metersPerUnit:[1/t,1/t,1/t],unitsPerDegree:[e,e,t],unitsPerDegree2:[0,0,0],degreesPerUnit:[1/e,1/e,1/t]}}var xl=class extends Rn{constructor(e={}){let{longitude:r=0,zoom:i=0,nearZMultiplier:n=.5,farZMultiplier:o=1,resolution:s=10}=e,{latitude:a=0,height:c,altitude:l=1.5,fovy:f}=e;a=Math.max(Math.min(a,ze),-ze),c=c||1,f?l=Br(f):f=_t(l);let u=Math.pow(2,i-Wt(a)),d=e.nearZ??n,h=e.farZ??(l+hr*2*u/c)*o,p=new me().lookAt({eye:[0,-l,0],up:[0,0,1]});p.rotateX(a*_l),p.rotateZ(-r*_l),p.scale(u/c),super({...e,height:c,viewMatrix:p,longitude:r,latitude:a,zoom:i,distanceScales:l4(),fovy:f,focalDistance:l,near:d,far:h}),this.scale=u,this.latitude=a,this.longitude=r,this.fovy=f,this.resolution=s}get projectionMode(){return _e.GLOBE}getDistanceScales(){return this.distanceScales}getBounds(e={}){let r={targetZ:e.z||0},i=this.unproject([0,this.height/2],r),n=this.unproject([this.width/2,0],r),o=this.unproject([this.width,this.height/2],r),s=this.unproject([this.width/2,this.height],r);return o[0]this.longitude&&(i[0]-=360),[Math.min(i[0],o[0],n[0],s[0]),Math.min(i[1],o[1],n[1],s[1]),Math.max(i[0],o[0],n[0],s[0]),Math.max(i[1],o[1],n[1],s[1])]}unproject(e,{topLeft:r=!0,targetZ:i}={}){let[n,o,s]=e,a=r?o:this.height-o,{pixelUnprojectionMatrix:c}=this,l;if(Number.isFinite(s))l=Lp(c,[n,a,s,1]);else{let h=Lp(c,[n,a,-1,1]),p=Lp(c,[n,a,1,1]),g=((i||0)/yl+1)*hr,m=Pe.sqrLen(Pe.sub([],h,p)),_=Pe.sqrLen(h),T=Pe.sqrLen(p),x=4*((4*_*T-(m-_-T)**2)/16)/m,w=Math.sqrt(_-x),b=Math.sqrt(Math.max(0,g*g-x)),E=(w-b)/Math.sqrt(m);l=Pe.lerp([],h,p,E)}let[f,u,d]=this.unprojectPosition(l);return Number.isFinite(s)?[f,u,d]:Number.isFinite(i)?[f,u,i]:[f,u]}projectPosition(e){let[r,i,n=0]=e,o=r*_l,s=i*_l,a=Math.cos(s),c=(n/yl+1)*hr;return[Math.sin(o)*a*c,-Math.cos(o)*a*c,Math.sin(s)*c]}unprojectPosition(e){let[r,i,n]=e,o=Pe.len(e),s=Math.asin(n/o),c=Math.atan2(r,-i)*Xb,l=s*Xb,f=(o/hr-1)*yl;return[c,l,f]}projectFlat(e){return e}unprojectFlat(e){return e}panByPosition([e,r,i],n,o){let a=.25/Math.pow(2,this.zoom-Wt(this.latitude)),c=e+a*(o[0]-n[0]),l=r-a*(o[1]-n[1]);l=Math.max(Math.min(l,ze),-ze);let f={longitude:c,latitude:l,zoom:i-Wt(r)};return f.zoom+=Wt(f.latitude),f}};xl.displayName="GlobeViewport";var bl=xl;function Wt(t){let e=Math.PI*Math.cos(t*Math.PI/180);return Math.log2(e)}function Lp(t,e){let r=Ze.transformMat4([],e,t);return Ze.scale(r,r,1/r[3]),r}var f4=["longitude","latitude","zoom","bearing","pitch"],u4=["longitude","latitude","zoom"],pr=class extends As{constructor(e={}){let r=Array.isArray(e)?e:e.transitionProps,i=Array.isArray(e)?{}:e;i.transitionProps=Array.isArray(r)?{compare:r,required:r}:r||{compare:f4,required:u4},super(i.transitionProps),this.opts=i}initializeProps(e,r){let i=super.initializeProps(e,r),{makeViewport:n,around:o}=this.opts;if(n&&o)if(n(e)instanceof bl)F.warn("around not supported in GlobeView")();else{let a=n(e),c=n(r),l=a.unproject(o);i.start.around=o,Object.assign(i.end,{around:c.project(l),aroundPosition:l,width:r.width,height:r.height})}return i}interpolateProps(e,r,i){let n={};for(let o of this._propsToExtract)n[o]=di(e[o]||0,r[o]||0,i);if(r.aroundPosition&&this.opts.makeViewport){let o=this.opts.makeViewport({...r,...n});Object.assign(n,o.panByPosition(r.aroundPosition,di(e.around,r.around,i)))}return n}};var gr={transitionDuration:0},d4=300,Tl=t=>1-(1-t)*(1-t),In={WHEEL:["wheel"],PAN:["panstart","panmove","panend"],PINCH:["pinchstart","pinchmove","pinchend"],MULTI_PAN:["multipanstart","multipanmove","multipanend"],DOUBLE_CLICK:["dblclick"],KEYBOARD:["keydown"]},Pi={},Mi=class{constructor(e){this.state={},this._events={},this._interactionState={isDragging:!1},this._customEvents=[],this._eventStartBlocked=null,this._panMove=!1,this.invertPan=!1,this.dragMode="rotate",this.inertia=0,this.scrollZoom=!0,this.dragPan=!0,this.dragRotate=!0,this.doubleClickZoom=!0,this.touchZoom=!0,this.touchRotate=!1,this.keyboard=!0,this.transitionManager=new Ss({...e,getControllerState:r=>new this.ControllerState(r),onViewStateChange:this._onTransition.bind(this),onStateChange:this._setInteractionState.bind(this)}),this.handleEvent=this.handleEvent.bind(this),this.eventManager=e.eventManager,this.onViewStateChange=e.onViewStateChange||(()=>{}),this.onStateChange=e.onStateChange||(()=>{}),this.makeViewport=e.makeViewport,this.pickPosition=e.pickPosition}set events(e){this.toggleEvents(this._customEvents,!1),this.toggleEvents(e,!0),this._customEvents=e,this.props&&this.setProps(this.props)}finalize(){for(let e in this._events)this._events[e]&&this.eventManager?.off(e,this.handleEvent);this.transitionManager.finalize()}handleEvent(e){this._controllerState=void 0;let r=this._eventStartBlocked;switch(e.type){case"panstart":return r?!1:this._onPanStart(e);case"panmove":return this._onPan(e);case"panend":return this._onPanEnd(e);case"pinchstart":return r?!1:this._onPinchStart(e);case"pinchmove":return this._onPinch(e);case"pinchend":return this._onPinchEnd(e);case"multipanstart":return r?!1:this._onMultiPanStart(e);case"multipanmove":return this._onMultiPan(e);case"multipanend":return this._onMultiPanEnd(e);case"dblclick":return this._onDoubleClick(e);case"wheel":return this._onWheel(e);case"keydown":return this._onKeyDown(e);default:return!1}}get controllerState(){return this._controllerState=this._controllerState||new this.ControllerState({makeViewport:this.makeViewport,...this.props,...this.state}),this._controllerState}getCenter(e){let{x:r,y:i}=this.props,{offsetCenter:n}=e;return[n.x-r,n.y-i]}isPointInBounds(e,r){let{width:i,height:n}=this.props;if(r&&r.handled)return!1;let o=e[0]>=0&&e[0]<=i&&e[1]>=0&&e[1]<=n;return o&&r&&r.stopPropagation(),o}isFunctionKeyPressed(e){let{srcEvent:r}=e;return!!(r.metaKey||r.altKey||r.ctrlKey||r.shiftKey)}isDragging(){return this._interactionState.isDragging||!1}blockEvents(e){let r=setTimeout(()=>{this._eventStartBlocked===r&&(this._eventStartBlocked=null)},e);this._eventStartBlocked=r}setProps(e){e.dragMode&&(this.dragMode=e.dragMode);let r=this.props;this.props=e,"transitionInterpolator"in e||(e.transitionInterpolator=this._getTransitionProps().transitionInterpolator),this.transitionManager.processViewStateChange(e);let{inertia:i}=e;this.inertia=Number.isFinite(i)?i:i===!0?d4:0;let{scrollZoom:n=!0,dragPan:o=!0,dragRotate:s=!0,doubleClickZoom:a=!0,touchZoom:c=!0,touchRotate:l=!1,keyboard:f=!0}=e,u=!!this.onViewStateChange;if(this.toggleEvents(In.WHEEL,u&&n),this.toggleEvents(In.PAN,u),this.toggleEvents(In.PINCH,u&&(c||l)),this.toggleEvents(In.MULTI_PAN,u&&l),this.toggleEvents(In.DOUBLE_CLICK,u&&a),this.toggleEvents(In.KEYBOARD,u&&f),this.scrollZoom=n,this.dragPan=o,this.dragRotate=s,this.doubleClickZoom=a,this.touchZoom=c,this.touchRotate=l,this.keyboard=f,(!r||r.height!==e.height||r.width!==e.width||r.maxBounds!==e.maxBounds)&&e.maxBounds){let h=new this.ControllerState({...e,makeViewport:this.makeViewport}),p=h.getViewportProps();Object.keys(p).some(m=>!de(p[m],e[m],1))&&this.updateViewport(h)}}updateTransition(){this.transitionManager.updateTransition()}toggleEvents(e,r){this.eventManager&&e.forEach(i=>{this._events[i]!==r&&(this._events[i]=r,r?this.eventManager.on(i,this.handleEvent):this.eventManager.off(i,this.handleEvent))})}updateViewport(e,r=null,i={}){let n={...e.getViewportProps(),...r},o=this.controllerState!==e;if(this.state=e.getState(),this._setInteractionState(i),o){let s=this.controllerState&&this.controllerState.getViewportProps();this.onViewStateChange&&this.onViewStateChange({viewState:n,interactionState:this._interactionState,oldViewState:s,viewId:this.props.id})}}_onTransition(e){this.onViewStateChange({...e,interactionState:this._interactionState,viewId:this.props.id})}_setInteractionState(e){Object.assign(this._interactionState,e),this.onStateChange(this._interactionState)}_onPanStart(e){let r=this.getCenter(e);if(!this.isPointInBounds(r,e))return!1;let i=this.isFunctionKeyPressed(e)||e.rightButton||!1;(this.invertPan||this.dragMode==="pan")&&(i=!i);let n=this.controllerState[i?"panStart":"rotateStart"]({pos:r});return this._panMove=i,this.updateViewport(n,gr,{isDragging:!0}),!0}_onPan(e){return this.isDragging()?this._panMove?this._onPanMove(e):this._onPanRotate(e):!1}_onPanEnd(e){return this.isDragging()?this._panMove?this._onPanMoveEnd(e):this._onPanRotateEnd(e):!1}_onPanMove(e){if(!this.dragPan)return!1;let r=this.getCenter(e),i=this.controllerState.pan({pos:r});return this.updateViewport(i,gr,{isDragging:!0,isPanning:!0}),!0}_onPanMoveEnd(e){let{inertia:r}=this;if(this.dragPan&&r&&e.velocity){let i=this.getCenter(e),n=[i[0]+e.velocityX*r/2,i[1]+e.velocityY*r/2],o=this.controllerState.pan({pos:n}).panEnd();this.updateViewport(o,{...this._getTransitionProps(),transitionDuration:r,transitionEasing:Tl},{isDragging:!1,isPanning:!0})}else{let i=this.controllerState.panEnd();this.updateViewport(i,null,{isDragging:!1,isPanning:!1})}return!0}_onPanRotate(e){if(!this.dragRotate)return!1;let r=this.getCenter(e),i=this.controllerState.rotate({pos:r});return this.updateViewport(i,gr,{isDragging:!0,isRotating:!0}),!0}_onPanRotateEnd(e){let{inertia:r}=this;if(this.dragRotate&&r&&e.velocity){let i=this.getCenter(e),n=[i[0]+e.velocityX*r/2,i[1]+e.velocityY*r/2],o=this.controllerState.rotate({pos:n}).rotateEnd();this.updateViewport(o,{...this._getTransitionProps(),transitionDuration:r,transitionEasing:Tl},{isDragging:!1,isRotating:!0})}else{let i=this.controllerState.rotateEnd();this.updateViewport(i,null,{isDragging:!1,isRotating:!1})}return!0}_onWheel(e){if(!this.scrollZoom)return!1;let r=this.getCenter(e);if(!this.isPointInBounds(r,e))return!1;e.srcEvent.preventDefault();let{speed:i=.01,smooth:n=!1}=this.scrollZoom===!0?{}:this.scrollZoom,{delta:o}=e,s=2/(1+Math.exp(-Math.abs(o*i)));o<0&&s!==0&&(s=1/s);let a=n?{...this._getTransitionProps({around:r}),transitionDuration:250}:gr,c=this.controllerState.zoom({pos:r,scale:s});return this.updateViewport(c,a,{isZooming:!0,isPanning:!0}),n||this._setInteractionState({isZooming:!1,isPanning:!1}),!0}_onMultiPanStart(e){let r=this.getCenter(e);if(!this.isPointInBounds(r,e))return!1;let i=this.controllerState.rotateStart({pos:r});return this.updateViewport(i,gr,{isDragging:!0}),!0}_onMultiPan(e){if(!this.touchRotate||!this.isDragging())return!1;let r=this.getCenter(e);r[0]-=e.deltaX;let i=this.controllerState.rotate({pos:r});return this.updateViewport(i,gr,{isDragging:!0,isRotating:!0}),!0}_onMultiPanEnd(e){if(!this.isDragging())return!1;let{inertia:r}=this;if(this.touchRotate&&r&&e.velocityY){let i=this.getCenter(e),n=[i[0],i[1]+=e.velocityY*r/2],o=this.controllerState.rotate({pos:n});this.updateViewport(o,{...this._getTransitionProps(),transitionDuration:r,transitionEasing:Tl},{isDragging:!1,isRotating:!0}),this.blockEvents(r)}else{let i=this.controllerState.rotateEnd();this.updateViewport(i,null,{isDragging:!1,isRotating:!1})}return!0}_onPinchStart(e){let r=this.getCenter(e);if(!this.isPointInBounds(r,e))return!1;let i=this.controllerState.zoomStart({pos:r}).rotateStart({pos:r});return Pi._startPinchRotation=e.rotation,Pi._lastPinchEvent=e,this.updateViewport(i,gr,{isDragging:!0}),!0}_onPinch(e){if(!this.touchZoom&&!this.touchRotate||!this.isDragging())return!1;let r=this.controllerState;if(this.touchZoom){let{scale:i}=e,n=this.getCenter(e);r=r.zoom({pos:n,scale:i})}if(this.touchRotate){let{rotation:i}=e;r=r.rotate({deltaAngleX:Pi._startPinchRotation-i})}return this.updateViewport(r,gr,{isDragging:!0,isPanning:this.touchZoom,isZooming:this.touchZoom,isRotating:this.touchRotate}),Pi._lastPinchEvent=e,!0}_onPinchEnd(e){if(!this.isDragging())return!1;let{inertia:r}=this,{_lastPinchEvent:i}=Pi;if(this.touchZoom&&r&&i&&e.scale!==i.scale){let n=this.getCenter(e),o=this.controllerState.rotateEnd(),s=Math.log2(e.scale),a=(s-Math.log2(i.scale))/(e.deltaTime-i.deltaTime),c=Math.pow(2,s+a*r/2);o=o.zoom({pos:n,scale:c}).zoomEnd(),this.updateViewport(o,{...this._getTransitionProps({around:n}),transitionDuration:r,transitionEasing:Tl},{isDragging:!1,isPanning:this.touchZoom,isZooming:this.touchZoom,isRotating:!1}),this.blockEvents(r)}else{let n=this.controllerState.zoomEnd().rotateEnd();this.updateViewport(n,null,{isDragging:!1,isPanning:!1,isZooming:!1,isRotating:!1})}return Pi._startPinchRotation=null,Pi._lastPinchEvent=null,!0}_onDoubleClick(e){if(!this.doubleClickZoom)return!1;let r=this.getCenter(e);if(!this.isPointInBounds(r,e))return!1;let i=this.isFunctionKeyPressed(e),n=this.controllerState.zoom({pos:r,scale:i?.5:2});return this.updateViewport(n,this._getTransitionProps({around:r}),{isZooming:!0,isPanning:!0}),this.blockEvents(100),!0}_onKeyDown(e){if(!this.keyboard)return!1;let r=this.isFunctionKeyPressed(e),{zoomSpeed:i,moveSpeed:n,rotateSpeedX:o,rotateSpeedY:s}=this.keyboard===!0?{}:this.keyboard,{controllerState:a}=this,c,l={};switch(e.srcEvent.code){case"Minus":c=r?a.zoomOut(i).zoomOut(i):a.zoomOut(i),l.isZooming=!0;break;case"Equal":c=r?a.zoomIn(i).zoomIn(i):a.zoomIn(i),l.isZooming=!0;break;case"ArrowLeft":r?(c=a.rotateLeft(o),l.isRotating=!0):(c=a.moveLeft(n),l.isPanning=!0);break;case"ArrowRight":r?(c=a.rotateRight(o),l.isRotating=!0):(c=a.moveRight(n),l.isPanning=!0);break;case"ArrowUp":r?(c=a.rotateUp(s),l.isRotating=!0):(c=a.moveUp(n),l.isPanning=!0);break;case"ArrowDown":r?(c=a.rotateDown(s),l.isRotating=!0):(c=a.moveDown(n),l.isPanning=!0);break;default:return!1}return this.updateViewport(c,this._getTransitionProps(),l),!0}_getTransitionProps(e){let{transition:r}=this;return!r||!r.transitionInterpolator?gr:e?{...r,transitionInterpolator:new pr({...e,...r.transitionInterpolator.opts,makeViewport:this.controllerState.makeViewport})}:r}};var vs=class{constructor(e,r,i){this.makeViewport=i,this._viewportProps=this.applyConstraints(e),this._state=r}getViewportProps(){return this._viewportProps}getState(){return this._state}};var Gb=5,h4=1.2,qb=512,Kb=[[-1/0,-90],[1/0,90]];function wl([t,e]){if(Math.abs(e)>90&&(e=Math.sign(e)*90),Number.isFinite(t)){let[i,n]=xe([t,e]);return[i,ce(n,0,qb)]}let[,r]=xe([0,e]);return[t,ce(r,0,qb)]}var Es=class extends vs{constructor(e){let{width:r,height:i,latitude:n,longitude:o,zoom:s,bearing:a=0,pitch:c=0,altitude:l=1.5,position:f=[0,0,0],maxZoom:u=20,minZoom:d=0,maxPitch:h=60,minPitch:p=0,startPanLngLat:g,startZoomLngLat:m,startRotatePos:_,startRotateLngLat:T,startBearing:y,startPitch:x,startZoom:w,normalize:b=!0}=e;J(Number.isFinite(o)),J(Number.isFinite(n)),J(Number.isFinite(s));let E=e.maxBounds||(b?Kb:null);super({width:r,height:i,latitude:n,longitude:o,zoom:s,bearing:a,pitch:c,altitude:l,maxZoom:u,minZoom:d,maxPitch:h,minPitch:p,normalize:b,position:f,maxBounds:E},{startPanLngLat:g,startZoomLngLat:m,startRotatePos:_,startRotateLngLat:T,startBearing:y,startPitch:x,startZoom:w},e.makeViewport),this.getAltitude=e.getAltitude}panStart({pos:e}){return this._getUpdatedState({startPanLngLat:this._unproject(e)})}pan({pos:e,startPos:r}){let i=this.getState().startPanLngLat||this._unproject(r);if(!i)return this;let o=this.makeViewport(this.getViewportProps()).panByPosition(i,e);return this._getUpdatedState(o)}panEnd(){return this._getUpdatedState({startPanLngLat:null})}rotateStart({pos:e}){let r=this.getAltitude?.(e);return this._getUpdatedState({startRotatePos:e,startRotateLngLat:r!==void 0?this._unproject3D(e,r):void 0,startBearing:this.getViewportProps().bearing,startPitch:this.getViewportProps().pitch})}rotate({pos:e,deltaAngleX:r=0,deltaAngleY:i=0}){let{startRotatePos:n,startRotateLngLat:o,startBearing:s,startPitch:a}=this.getState();if(!n||s===void 0||a===void 0)return this;let c;if(e?c=this._getNewRotation(e,n,a,s):c={bearing:s+r,pitch:a+i},o){let l=this.makeViewport({...this.getViewportProps(),...c}),f="panByPosition3D"in l?"panByPosition3D":"panByPosition";return this._getUpdatedState({...c,...l[f](o,n)})}return this._getUpdatedState(c)}rotateEnd(){return this._getUpdatedState({startRotatePos:null,startRotateLngLat:null,startBearing:null,startPitch:null})}zoomStart({pos:e}){return this._getUpdatedState({startZoomLngLat:this._unproject(e),startZoom:this.getViewportProps().zoom})}zoom({pos:e,startPos:r,scale:i}){let{startZoom:n,startZoomLngLat:o}=this.getState();if(o||(n=this.getViewportProps().zoom,o=this._unproject(r)||this._unproject(e)),!o)return this;let s=this._constrainZoom(n+Math.log2(i)),a=this.makeViewport({...this.getViewportProps(),zoom:s});return this._getUpdatedState({zoom:s,...a.panByPosition(o,e)})}zoomEnd(){return this._getUpdatedState({startZoomLngLat:null,startZoom:null})}zoomIn(e=2){return this._zoomFromCenter(e)}zoomOut(e=2){return this._zoomFromCenter(1/e)}moveLeft(e=100){return this._panFromCenter([e,0])}moveRight(e=100){return this._panFromCenter([-e,0])}moveUp(e=100){return this._panFromCenter([0,e])}moveDown(e=100){return this._panFromCenter([0,-e])}rotateLeft(e=15){return this._getUpdatedState({bearing:this.getViewportProps().bearing-e})}rotateRight(e=15){return this._getUpdatedState({bearing:this.getViewportProps().bearing+e})}rotateUp(e=10){return this._getUpdatedState({pitch:this.getViewportProps().pitch+e})}rotateDown(e=10){return this._getUpdatedState({pitch:this.getViewportProps().pitch-e})}shortestPathFrom(e){let r=e.getViewportProps(),i={...this.getViewportProps()},{bearing:n,longitude:o}=i;return Math.abs(n-r.bearing)>180&&(i.bearing=n<0?n+360:n-360),Math.abs(o-r.longitude)>180&&(i.longitude=o<0?o+360:o-360),i}applyConstraints(e){let{maxPitch:r,minPitch:i,pitch:n,longitude:o,bearing:s,normalize:a,maxBounds:c}=e;if(a&&((o<-180||o>180)&&(e.longitude=ps(o+180,360)-180),(s<-180||s>180)&&(e.bearing=ps(s+180,360)-180)),e.pitch=ce(n,i,r),e.zoom=this._constrainZoom(e.zoom,e),c){let l=wl(c[0]),f=wl(c[1]),u=2**e.zoom,d=e.width/2/u,h=e.height/2/u,[p,g]=Se([l[0]+d,l[1]+h]),[m,_]=Se([f[0]-d,f[1]-h]);e.longitude=ce(e.longitude,p,m),e.latitude=ce(e.latitude,g,_)}return e}_constrainZoom(e,r){r||(r=this.getViewportProps());let{maxZoom:i,maxBounds:n}=r,o=n!==null&&r.width>0&&r.height>0,{minZoom:s}=r;if(o){let a=wl(n[0]),c=wl(n[1]),l=c[0]-a[0],f=c[1]-a[1];Number.isFinite(l)&&l>0&&(s=Math.max(s,Math.log2(r.width/l))),Number.isFinite(f)&&f>0&&(s=Math.max(s,Math.log2(r.height/f))),s>i&&(s=i)}return ce(e,s,i)}_zoomFromCenter(e){let{width:r,height:i}=this.getViewportProps();return this.zoom({pos:[r/2,i/2],scale:e})}_panFromCenter(e){let{width:r,height:i}=this.getViewportProps();return this.pan({startPos:[r/2,i/2],pos:[r/2+e[0],i/2+e[1]]})}_getUpdatedState(e){return new this.constructor({makeViewport:this.makeViewport,...this.getViewportProps(),...this.getState(),...e})}_unproject(e){let r=this.makeViewport(this.getViewportProps());return e&&r.unproject(e)}_unproject3D(e,r){return this.makeViewport(this.getViewportProps()).unproject(e,{targetZ:r})}_getNewRotation(e,r,i,n){let o=e[0]-r[0],s=e[1]-r[1],a=e[1],c=r[1],{width:l,height:f}=this.getViewportProps(),u=o/l,d=0;s>0?Math.abs(f-c)>Gb&&(d=s/(c-f)*h4):s<0&&c>Gb&&(d=1-a/c),d=ce(d,-1,1);let{minPitch:h,maxPitch:p}=this.getViewportProps(),g=n+180*u,m=i;return d>0?m=i+d*(p-i):d<0&&(m=i-d*(h-i)),{pitch:m,bearing:g}}},Rs=class extends Mi{constructor(){super(...arguments),this.ControllerState=Es,this.transition={transitionDuration:300,transitionInterpolator:new pr({transitionProps:{compare:["longitude","latitude","zoom","bearing","pitch","position"],required:["longitude","latitude","zoom"]}})},this.dragMode="pan",this.rotationPivot="center",this._getAltitude=e=>{if(this.rotationPivot==="2d")return 0;if(this.rotationPivot==="3d"&&this.pickPosition){let{x:r,y:i}=this.props,n=this.pickPosition(r+e[0],i+e[1]);if(n&&n.coordinate&&n.coordinate.length>=3)return n.coordinate[2]}}}setProps(e){"rotationPivot"in e&&(this.rotationPivot=e.rotationPivot||"center"),e.getAltitude=this._getAltitude,e.position=e.position||[0,0,0],e.maxBounds=e.maxBounds||(e.normalize===!1?null:Kb),super.setProps(e)}updateViewport(e,r=null,i={}){let n=e.getState();i.isDragging&&n.startRotateLngLat?i={...i,rotationPivotPosition:n.startRotateLngLat}:i.isDragging===!1&&(i={...i,rotationPivotPosition:void 0}),super.updateViewport(e,r,i)}};var Sl=class extends Ci{constructor(e={}){super(e)}getViewportType(){return Cn}get ControllerType(){return Rs}};Sl.displayName="MapView";var Cs=Sl;var p4=new An;function g4(t,e){let r=t.order??1/0,i=e.order??1/0;return r-i}var Ps=class{constructor(e){this._resolvedEffects=[],this._defaultEffects=[],this.effects=[],this._context=e,this._needsRedraw="Initial render",this._setEffects([])}addDefaultEffect(e){let r=this._defaultEffects;if(!r.find(i=>i.id===e.id)){let i=r.findIndex(n=>g4(n,e)>0);i<0?r.push(e):r.splice(i,0,e),e.setup(this._context),this._setEffects(this.effects)}}setProps(e){"effects"in e&&(de(e.effects,this.effects,1)||this._setEffects(e.effects))}needsRedraw(e={clearRedrawFlags:!1}){let r=this._needsRedraw;return e.clearRedrawFlags&&(this._needsRedraw=!1),r}getEffects(){return this._resolvedEffects}_setEffects(e){let r={};for(let n of this.effects)r[n.id]=n;let i=[];for(let n of e){let o=r[n.id],s=n;o&&o!==n?o.setProps?(o.setProps(n.props),s=o):o.cleanup(this._context):o||n.setup(this._context),i.push(s),delete r[n.id]}for(let n in r)r[n].cleanup(this._context);this.effects=i,this._resolvedEffects=i.concat(this._defaultEffects),e.some(n=>n instanceof An)||this._resolvedEffects.push(p4),this._needsRedraw="effects changed"}finalize(){for(let e of this._resolvedEffects)e.cleanup(this._context);this.effects.length=0,this._resolvedEffects.length=0,this._defaultEffects.length=0}};var Ms=class extends cr{shouldDrawLayer(e){let{operation:r}=e.props;return r.includes("draw")||r.includes("terrain")}render(e){return this._render(e)}};var m4="deckRenderer.renderLayers",Is=class{constructor(e,r={}){this.device=e,this.stats=r.stats,this.layerFilter=null,this.drawPickingColors=!1,this.drawLayersPass=new Ms(e),this.pickLayersPass=new Ri(e),this.renderCount=0,this._needsRedraw="Initial render",this.renderBuffers=[],this.lastPostProcessEffect=null}setProps(e){this.layerFilter!==e.layerFilter&&(this.layerFilter=e.layerFilter,this._needsRedraw="layerFilter changed"),this.drawPickingColors!==e.drawPickingColors&&(this.drawPickingColors=e.drawPickingColors,this._needsRedraw="drawPickingColors changed")}renderLayers(e){if(!e.viewports.length)return;let r=this.drawPickingColors?this.pickLayersPass:this.drawLayersPass,i={layerFilter:this.layerFilter,isPicking:this.drawPickingColors,...e};i.effects&&this._preRender(i.effects,i);let n=this.lastPostProcessEffect?this.renderBuffers[0]:i.target;this.lastPostProcessEffect&&(i.clearColor=[0,0,0,0],i.clearCanvas=!0);let o=r.render({...i,target:n}),s="stats"in o?o.stats:o;i.effects&&(this.lastPostProcessEffect&&(i.clearCanvas=e.clearCanvas===void 0?!0:e.clearCanvas),this._postRender(i.effects,i)),this.renderCount++,ae(m4,this,s,e),this._updateStats(s)}needsRedraw(e={clearRedrawFlags:!1}){let r=this._needsRedraw;return e.clearRedrawFlags&&(this._needsRedraw=!1),r}finalize(){let{renderBuffers:e}=this;for(let r of e)r.delete();e.length=0}_updateStats(e){if(!this.stats)return;let r=0;for(let{visibleCount:i}of e)r+=i;this.stats.get("Layers rendered").addCount(r)}_preRender(e,r){this.lastPostProcessEffect=null,r.preRenderStats=r.preRenderStats||{};for(let i of e)r.preRenderStats[i.id]=i.preRender(r),i.postRender&&(this.lastPostProcessEffect=i.id);this.lastPostProcessEffect&&this._resizeRenderBuffers()}_resizeRenderBuffers(){let{renderBuffers:e}=this,r=this.device.canvasContext.getDrawingBufferSize(),[i,n]=r;e.length===0&&[0,1].map(o=>{let s=this.device.createTexture({sampler:{minFilter:"linear",magFilter:"linear"},width:i,height:n});e.push(this.device.createFramebuffer({id:`deck-renderbuffer-${o}`,colorAttachments:[s]}))});for(let o of e)o.resize(r)}_postRender(e,r){let{renderBuffers:i}=this,n={...r,inputBuffer:i[0],swapBuffer:i[1]};for(let o of e)if(o.postRender){n.target=o.id===this.lastPostProcessEffect?r.target:void 0;let s=o.postRender(n);n.inputBuffer=s,n.swapBuffer=s===i[0]?i[1]:i[0]}}};z();var _4={pickedColor:null,pickedObjectIndex:-1};function Fp({pickedColors:t,decodePickingColor:e,deviceX:r,deviceY:i,deviceRadius:n,deviceRect:o}){let{x:s,y:a,width:c,height:l}=o,f=n*n,u=-1,d=0;for(let h=0;hf)d+=4*c;else for(let m=0;m=0){let T=m+s-r,y=T*T+g;y<=f&&(f=y,u=d)}d+=4}}if(u>=0){let h=t.slice(u,u+4),p=e(h);if(p){let g=Math.floor(u/4/c),m=u/4-g*c;return{...p,pickedColor:h,pickedX:s+m,pickedY:a+g}}F.error("Picked non-existent layer. Is picking buffer corrupt?")()}return _4}function Bp({pickedColors:t,decodePickingColor:e}){let r=new Map;if(t){for(let i=0;i=0){let o=t.slice(i,i+4),s=o.join(",");if(!r.has(s)){let a=e(o);a?r.set(s,{...a,color:o}):F.error("Picked non-existent layer. Is picking buffer corrupt?")()}}}return Array.from(r.values())}function Al({pickInfo:t,viewports:e,pixelRatio:r,x:i,y:n,z:o}){let s=e[0];e.length>1&&(s=y4(t?.pickedViewports||e,{x:i,y:n}));let a;if(s){let c=[i-s.x,n-s.y];o!==void 0&&(c[2]=o),a=s.unproject(c)}return{color:null,layer:null,viewport:s,index:-1,picked:!1,x:i,y:n,pixel:[i,n],coordinate:a,devicePixel:t&&"pickedX"in t?[t.pickedX,t.pickedY]:void 0,pixelRatio:r}}function kp(t){let{pickInfo:e,lastPickedInfo:r,mode:i,layers:n}=t,{pickedColor:o,pickedLayer:s,pickedObjectIndex:a}=e,c=s?[s]:[];if(i==="hover"){let u=r.index,d=r.layerId,h=s?s.props.id:null;if(h!==d||a!==u){if(h!==d){let p=n.find(g=>g.props.id===d);p&&c.unshift(p)}r.layerId=h,r.index=a,r.info=null}}let l=Al(t),f=new Map;return f.set(null,l),c.forEach(u=>{let d={...l};u===s&&(d.color=o,d.index=a,d.picked=!0),d=vl({layer:u,info:d,mode:i});let h=d.layer;u===s&&i==="hover"&&(r.info=d),f.set(h.id,d),i==="hover"&&h.updateAutoHighlight(d)}),f}function vl({layer:t,info:e,mode:r}){for(;t&&e;){let i=e.layer||null;e.sourceLayer=i,e.layer=t,e=t.getPickingInfo({info:e,mode:r,sourceLayer:i}),t=t.parent}return e}function y4(t,e){for(let r=t.length-1;r>=0;r--){let i=t[r];if(i.containsPixel(e))return i}return t[0]}var Os=class{constructor(e,r={}){this._pickable=!0,this.device=e,this.stats=r.stats,this.pickLayersPass=new Ri(e),this.lastPickedInfo={index:-1,layerId:null,info:null}}setProps(e){"layerFilter"in e&&(this.layerFilter=e.layerFilter),"_pickable"in e&&(this._pickable=e._pickable)}finalize(){this.pickingFBO&&this.pickingFBO.destroy(),this.depthFBO&&this.depthFBO.destroy()}pickObjectAsync(e){return this._pickClosestObjectAsync(e)}pickObjectsAsync(e){return this._pickVisibleObjectsAsync(e)}pickObject(e){return this._pickClosestObject(e)}pickObjects(e){return this._pickVisibleObjects(e)}getLastPickedObject({x:e,y:r,layers:i,viewports:n},o=this.lastPickedInfo.info){let s=o&&o.layer&&o.layer.id,a=o&&o.viewport&&o.viewport.id,c=s?i.find(d=>d.id===s):null,l=a&&n.find(d=>d.id===a)||n[0],f=l&&l.unproject([e-l.x,r-l.y]);return{...o,...{x:e,y:r,viewport:l,coordinate:f,layer:c}}}_resizeBuffer(){if(!this.pickingFBO){let r=this.device.createTexture({format:"rgba8unorm",width:1,height:1,usage:$.RENDER_ATTACHMENT|$.COPY_SRC});if(this.pickingFBO=this.device.createFramebuffer({colorAttachments:[r],depthStencilAttachment:"depth16unorm"}),this.device.isTextureFormatRenderable("rgba32float")){let i=this.device.createTexture({format:"rgba32float",width:1,height:1,usage:$.RENDER_ATTACHMENT|$.COPY_SRC}),n=this.device.createFramebuffer({colorAttachments:[i],depthStencilAttachment:"depth16unorm"});this.depthFBO=n}}let{canvas:e}=this.device.getDefaultCanvasContext();this.pickingFBO?.resize({width:e.width,height:e.height}),this.depthFBO?.resize({width:e.width,height:e.height})}_getPickable(e){if(this._pickable===!1)return null;let r=e.filter(i=>this.pickLayersPass.shouldDrawLayer(i)&&!i.isComposite);return r.length?r:null}async _pickClosestObjectAsync({layers:e,views:r,viewports:i,x:n,y:o,radius:s=0,depth:a=1,mode:c="query",unproject3D:l,onViewportActive:f,effects:u}){let d=this.device.canvasContext.cssToDeviceRatio(),h=this._getPickable(e);if(!h||i.length===0)return{result:[],emptyInfo:Al({viewports:i,x:n,y:o,pixelRatio:d})};this._resizeBuffer();let p=this.device.canvasContext.cssToDevicePixels([n,o],!0),g=[p.x+Math.floor(p.width/2),p.y+Math.floor(p.height/2)],m=Math.round(s*d),{width:_,height:T}=this.pickingFBO,y=this._getPickingRect({deviceX:g[0],deviceY:g[1],deviceRadius:m,deviceWidth:_,deviceHeight:T}),x={x:n-s,y:o-s,width:s*2+1,height:s*2+1},w,b=[],E=new Set;for(let S=0;S0){let{pickedColors:R}=await this._drawAndSampleAsync({layers:I,views:r,viewports:i,onViewportActive:f,deviceRect:{x:A.pickedX??g[0],y:A.pickedY??g[1],width:1,height:1},cullRect:x,effects:u,pass:`picking:${c}:z`},!0);R[3]&&(C=R[0])}A.pickedLayer&&S+10){let{pickedColors:R}=this._drawAndSample({layers:I,views:r,viewports:i,onViewportActive:f,deviceRect:{x:A.pickedX??g[0],y:A.pickedY??g[1],width:1,height:1},cullRect:x,effects:u,pass:`picking:${c}:z`},!0);R[3]&&(C=R[0])}A.pickedLayer&&S+1=l);C++){let I=b[C],R={color:I.pickedColor,layer:null,index:I.pickedObjectIndex,picked:!0,x:n,y:o,pixelRatio:h};R=vl({layer:I.pickedLayer,info:R,mode:c});let N=R.layer.id;E.has(N)||E.set(N,new Set);let O=E.get(N),W=R.object??R.index;O.has(W)||(O.add(W),S.push(R))}return S}_pickVisibleObjects({layers:e,views:r,viewports:i,x:n,y:o,width:s=1,height:a=1,mode:c="query",maxObjects:l=null,onViewportActive:f,effects:u}){let d=this._getPickable(e);if(!d||i.length===0)return[];this._resizeBuffer();let h=this.device.canvasContext.cssToDeviceRatio(),p=this.device.canvasContext.cssToDevicePixels([n,o],!0),g=p.x,m=p.y+p.height,_=this.device.canvasContext.cssToDevicePixels([n+s,o+a],!0),T=_.x+_.width,y=_.y,x={x:g,y,width:T-g,height:m-y},w=this._drawAndSample({layers:d,views:r,viewports:i,onViewportActive:f,deviceRect:x,cullRect:{x:n,y:o,width:s,height:a},effects:u,pass:`picking:${c}`}),b=Bp(w),E=new Map,S=[],A=Number.isFinite(l);for(let C=0;C=l);C++){let I=b[C],R={color:I.pickedColor,layer:null,index:I.pickedObjectIndex,picked:!0,x:n,y:o,pixelRatio:h};R=vl({layer:I.pickedLayer,info:R,mode:c});let N=R.layer.id;E.has(N)||E.set(N,new Set);let O=E.get(N),W=R.object??R.index;O.has(W)||(O.add(W),S.push(R))}return S}async _drawAndSampleAsync({layers:e,views:r,viewports:i,onViewportActive:n,deviceRect:o,cullRect:s,effects:a,pass:c},l=!1){let f=l?this.depthFBO:this.pickingFBO,u={layers:e,layerFilter:this.layerFilter,views:r,viewports:i,onViewportActive:n,pickingFBO:f,deviceRect:o,cullRect:s,effects:a,pass:c,pickZ:l,preRenderStats:{},isPicking:!0};for(let x of a)x.useInPicking&&(u.preRenderStats[x.id]=x.preRender(u));let{decodePickingColor:d,stats:h}=this.pickLayersPass.render(u);this._updateStats(h);let{x:p,y:g,width:m,height:_}=o,T=f.colorAttachments[0]?.texture;if(!T)throw new Error("Picking framebuffer color attachment is missing");let y=await this._readTextureDataAsync(T,{x:p,y:g,width:m,height:_},l?Float32Array:Uint8Array);if(!l){let x=!1;for(let w=3;w0&&F.warn("Async pick readback returned only zero alpha values",{deviceRect:o,bytes:Array.from(y.subarray(0,Math.min(y.length,16)))})()}return{pickedColors:y,decodePickingColor:d}}async _readTextureDataAsync(e,r,i){let{width:n,height:o}=r,s=e.computeMemoryLayout(r),a=this.device.createBuffer({byteLength:s.byteLength,usage:j.COPY_DST|j.MAP_READ});try{e.readBuffer(r,a);let c=await a.readAsync(0,s.byteLength),l=i.BYTES_PER_ELEMENT;if(s.bytesPerRow%l!==0)throw new Error(`Texture readback row stride ${s.bytesPerRow} is not aligned to ${l}-byte elements.`);let f=new i(c.buffer,c.byteOffset,s.byteLength/l),u=n*4,d=s.bytesPerRow/l;if(ds.props.operation.includes("terrain"))}_getPickingRect({deviceX:e,deviceY:r,deviceRadius:i,deviceWidth:n,deviceHeight:o}){let s=Math.max(0,e-i),a=Math.max(0,r-i),c=Math.min(n,e+i+1)-s,l=Math.min(o,r+i+1)-a;return c<=0||l<=0?null:{x:s,y:a,width:c,height:l}}};var x4={"top-left":{top:0,left:0},"top-right":{top:0,right:0},"bottom-left":{bottom:0,left:0},"bottom-right":{bottom:0,right:0},fill:{top:0,left:0,bottom:0,right:0}},b4="top-left",Zb="root",El=class{constructor({deck:e,parentElement:r}){this.defaultWidgets=[],this.widgets=[],this.resolvedWidgets=[],this.containers={},this.lastViewports={},this.deck=e,r?.classList.add("deck-widget-container"),this.parentElement=r}getWidgets(){return this.resolvedWidgets}setProps(e){if(e.widgets&&!de(e.widgets,this.widgets,1)){let r=e.widgets.filter(Boolean);this._setWidgets(r)}}finalize(){for(let e of this.getWidgets())this._removeWidget(e);this.defaultWidgets.length=0,this.resolvedWidgets.length=0;for(let e in this.containers)this.containers[e].remove()}addDefault(e){this.defaultWidgets.find(r=>r.id===e.id)||(this._addWidget(e),this.defaultWidgets.push(e),this._setWidgets(this.widgets))}onRedraw({viewports:e,layers:r}){let i=e.reduce((n,o)=>(n[o.id]=o,n),{});for(let n of this.getWidgets()){let{viewId:o}=n;if(o){let s=i[o];s&&(n.onViewportChange&&n.onViewportChange(s),n.onRedraw?.({viewports:[s],layers:r}))}else{if(n.onViewportChange)for(let s of e)n.onViewportChange(s);n.onRedraw?.({viewports:e,layers:r})}}this.lastViewports=i,this._updateContainers()}onHover(e,r){for(let i of this.getWidgets()){let{viewId:n}=i;(!n||n===e.viewport?.id)&&i.onHover?.(e,r)}}onEvent(e,r){let i=xn[r.type];if(i)for(let n of this.getWidgets()){let{viewId:o}=n;(!o||o===e.viewport?.id)&&n[i]?.(e,r)}}_setWidgets(e){let r={};for(let i of this.resolvedWidgets)r[i.id]=i;this.resolvedWidgets.length=0;for(let i of this.defaultWidgets)r[i.id]=null,this.resolvedWidgets.push(i);for(let i of e){let n=r[i.id];n?n.viewId!==i.viewId||n.placement!==i.placement?(this._removeWidget(n),this._addWidget(i)):i!==n&&(n.setProps(i.props),i=n):this._addWidget(i),r[i.id]=null,this.resolvedWidgets.push(i)}for(let i in r){let n=r[i];n&&this._removeWidget(n)}this.widgets=e}_addWidget(e){let{viewId:r=null,placement:i=b4}=e,n=e.props._container??r;e.widgetManager=this,e.deck=this.deck,e.rootElement=e._onAdd({deck:this.deck,viewId:r}),e.rootElement&&this._getContainer(n,i).append(e.rootElement),e.updateHTML()}_removeWidget(e){e.onRemove?.(),e.rootElement&&e.rootElement.remove(),e.rootElement=void 0,e.deck=void 0,e.widgetManager=void 0}_getContainer(e,r){if(e&&typeof e!="string")return e;let i=e||Zb,n=this.containers[i];n||(n=document.createElement("div"),n.style.pointerEvents="none",n.style.position="absolute",n.style.overflow="hidden",this.parentElement?.append(n),this.containers[i]=n);let o=n.querySelector(`.${r}`);return o||(o=globalThis.document.createElement("div"),o.className=r,o.style.position="absolute",o.style.zIndex="2",Object.assign(o.style,x4[r]),n.append(o)),o}_updateContainers(){let e=this.deck.width,r=this.deck.height;for(let i in this.containers){let n=this.lastViewports[i]||null,o=i===Zb||n,s=this.containers[i];o?(s.style.display="block",s.style.left=`${n?n.x:0}px`,s.style.top=`${n?n.y:0}px`,s.style.width=`${n?n.width:e}px`,s.style.height=`${n?n.height:r}px`):s.style.display="none"}}};function Up(t,e){e&&Object.entries(e).map(([r,i])=>{r.startsWith("--")?t.style.setProperty(r,i):t.style[r]=i})}function Qb(t,e){e&&Object.keys(e).map(r=>{r.startsWith("--")?t.style.removeProperty(r):t.style[r]=""})}var On=class{constructor(e){this.viewId=null,this.props={...this.constructor.defaultProps,...e},this.id=this.props.id}setProps(e){let r=this.props,i=this.rootElement;i&&r.className!==e.className&&(r.className&&i.classList.remove(r.className),e.className&&i.classList.add(e.className)),i&&!de(r.style,e.style,1)&&(Qb(i,r.style),Up(i,e.style)),Object.assign(this.props,e),this.updateHTML()}updateHTML(){this.rootElement&&this.onRenderHTML(this.rootElement)}get viewIds(){return this.viewId?[this.viewId]:this.deck?.getViews().map(e=>e.id)??[]}getViewState(e){return this.deck?.viewManager?.getViewState(e)||{}}setViewState(e,r){this.deck?._onViewStateChange({viewId:e,viewState:r,interactionState:{}})}onCreateRootElement(){let e=["deck-widget",this.className,this.props.className],r=document.createElement("div");return e.filter(i=>typeof i=="string"&&i.length>0).forEach(i=>r.classList.add(i)),Up(r,this.props.style),r}_onAdd(e){return this.onAdd(e)??this.onCreateRootElement()}onAdd(e){}onRemove(){}onViewportChange(e){}onRedraw(e){}onHover(e,r){}onClick(e,r){}onDrag(e,r){}onDragStart(e,r){}onDragEnd(e,r){}};On.defaultProps={id:"widget",style:{},_container:null,className:""};var T4={zIndex:"1",position:"absolute",pointerEvents:"none",color:"#a0a7b4",backgroundColor:"#29323c",padding:"10px",top:"0",left:"0",display:"none"},Ns=class extends On{constructor(e={}){super(e),this.id="default-tooltip",this.placement="fill",this.className="deck-tooltip",this.isVisible=!1,this.setProps(e)}onCreateRootElement(){let e=document.createElement("div");return e.className=this.className,Object.assign(e.style,T4),e}onRenderHTML(e){}onViewportChange(e){this.isVisible&&e.id===this.lastViewport?.id&&!e.equals(this.lastViewport)&&this.setTooltip(null),this.lastViewport=e}onHover(e){let{deck:r}=this,i=r&&r.props.getTooltip;if(!i)return;let n=i(e);this.setTooltip(n,e.x,e.y)}setTooltip(e,r,i){let n=this.rootElement;if(n){if(typeof e=="string")n.innerText=e;else if(e)e.text&&(n.innerText=e.text),e.html&&(n.innerHTML=e.html),e.className&&(n.className=e.className);else{this.isVisible=!1,n.style.display="none";return}this.isVisible=!0,n.style.display="block",n.style.transform=`translate(${r}px, ${i}px)`,e&&typeof e=="object"&&"style"in e&&Object.assign(n.style,e.style)}}};Ns.defaultProps={...On.defaultProps};z();cf();go();function $r(){}var IN=({isDragging:t})=>t?"grabbing":"grab",wT={id:"",width:"100%",height:"100%",style:null,viewState:null,initialViewState:null,pickingRadius:0,pickAsync:"auto",layerFilter:null,parameters:{},parent:null,device:null,deviceProps:{},gl:null,canvas:null,layers:[],effects:[],views:null,controller:null,useDevicePixels:!0,touchAction:"none",eventRecognizerOptions:{},_framebuffer:null,_animate:!1,_pickable:!0,_typedArrayManagerProps:{},_customRender:null,widgets:[],onDeviceInitialized:$r,onWebGLInitialized:$r,onResize:$r,onViewStateChange:$r,onInteractionStateChange:$r,onBeforeRender:$r,onAfterRender:$r,onLoad:$r,onError:t=>F.error(t.message,t.cause)(),onHover:null,onClick:null,onDragStart:null,onDrag:null,onDragEnd:null,_onMetrics:null,getCursor:IN,getTooltip:null,debug:!1,drawPickingColors:!1},Vs=class{constructor(e){this.width=0,this.height=0,this.userData={},this.device=null,this.canvas=null,this.viewManager=null,this.layerManager=null,this.effectManager=null,this.deckRenderer=null,this.deckPicker=null,this.eventManager=null,this.widgetManager=null,this.tooltip=null,this.animationLoop=null,this.cursorState={isHovering:!1,isDragging:!1},this.stats=new it({id:"deck.gl"}),this.metrics={fps:0,setPropsTime:0,layersCount:0,drawLayersCount:0,updateLayersCount:0,updateAttributesCount:0,updateAttributesTime:0,framesRedrawn:0,pickTime:0,pickCount:0,pickLayersCount:0,gpuTime:0,gpuTimePerFrame:0,cpuTime:0,cpuTimePerFrame:0,bufferMemory:0,textureMemory:0,renderbufferMemory:0,gpuMemory:0},this._metricsCounter=0,this._hoverPickSequence=0,this._pointerDownPickSequence=0,this._needsRedraw="Initial render",this._pickRequest={mode:"hover",x:-1,y:-1,radius:0,event:null,unproject3D:!1},this._lastPointerDownInfo=null,this._lastPointerDownInfoPromise=null,this._onPointerMove=i=>{let{_pickRequest:n}=this;if(i.type==="pointerleave")n.x=-1,n.y=-1,n.radius=0;else{if(i.leftButton||i.rightButton)return;{let o=i.offsetCenter;if(!o)return;n.x=o.x,n.y=o.y,n.radius=this.props.pickingRadius}}this.layerManager&&(this.layerManager.context.mousePosition={x:n.x,y:n.y}),n.event=i},this._onEvent=i=>{let n=xn[i.type],o=i.offsetCenter;if(!n||!o||!this.layerManager)return;let s=this.layerManager.getLayers(),a=this._getInternalPickingMode();if(!a)return;if(a==="sync"){let l=i.type==="click"&&this._shouldUnproject3D(s)?this._getFirstPickedInfo(this._pickPointSync(this._getPointPickOptions(o.x,o.y,{unproject3D:!0},s))):this._getLastPointerDownPickingInfo(o.x,o.y,s);this._dispatchPickingEvent(l,i);return}(this._lastPointerDownInfoPromise||Promise.resolve(this._getLastPointerDownPickingInfo(o.x,o.y,s))).then(l=>{this._dispatchPickingEvent(l,i)}).catch(l=>this.props.onError?.(l))},this._onPointerDown=i=>{let n=i.offsetCenter;if(!n)return;let o=this._getInternalPickingMode();if(!o)return;let s=this.layerManager?.getLayers()||[],a=++this._pointerDownPickSequence;if(o==="sync"){let l=this._pickPointSync({x:n.x,y:n.y,radius:this.props.pickingRadius}),f=this._getFirstPickedInfo(l);this._lastPointerDownInfo=f,this._lastPointerDownInfoPromise=Promise.resolve(f);return}let c=this._pickPointAsync(this._getPointPickOptions(n.x,n.y,{},s)).then(l=>this._getFirstPickedInfo(l)).then(l=>(a===this._pointerDownPickSequence&&(this._lastPointerDownInfo=l),l)).catch(l=>{this.props.onError?.(l);let f=this.deckPicker&&this.viewManager?this._getLastPointerDownPickingInfo(n.x,n.y,s):{};return a===this._pointerDownPickSequence&&(this._lastPointerDownInfo=f),f});this._lastPointerDownInfo=null,this._lastPointerDownInfoPromise=c},this.props={...wT,...e},e=this.props,e.viewState&&e.initialViewState&&F.warn("View state tracking is disabled. Use either `initialViewState` for auto update or `viewState` for manual update.")(),this.viewState=this.props.initialViewState,e.device&&(this.device=e.device);let r=this.device;if(!r&&e.gl){e.gl instanceof WebGLRenderingContext&&F.error("WebGL1 context not supported.")();let i=this.props.deviceProps?.onResize;r=Ws.attach(e.gl,{_cacheShaders:!0,_cachePipelines:!0,...this.props.deviceProps,onResize:(n,o)=>{let{width:s,height:a}=n.canvas;n.setDrawingBufferSize(s,a),this._needsRedraw="Canvas resized",i?.(n,o)}})}r||(r=this._createDevice(e)),this.animationLoop=this._createAnimationLoop(r,e),this.setProps(e),e._typedArrayManagerProps&&lr.setOptions(e._typedArrayManagerProps),this.animationLoop.start()}finalize(){this.animationLoop?.stop(),this.animationLoop?.destroy(),this.animationLoop=null,this._hoverPickSequence++,this._pointerDownPickSequence++,this._lastPointerDownInfo=null,this._lastPointerDownInfoPromise=null,this.layerManager?.finalize(),this.layerManager=null,this.viewManager?.finalize(),this.viewManager=null,this.effectManager?.finalize(),this.effectManager=null,this.deckRenderer?.finalize(),this.deckRenderer=null,this.deckPicker?.finalize(),this.deckPicker=null,this.eventManager?.destroy(),this.eventManager=null,this.widgetManager?.finalize(),this.widgetManager=null,!this.props.canvas&&!this.props.device&&!this.props.gl&&this.canvas&&(this.canvas.parentElement?.removeChild(this.canvas),this.canvas=null)}setProps(e){this.stats.get("setProps Time").timeStart(),"onLayerHover"in e&&F.removed("onLayerHover","onHover")(),"onLayerClick"in e&&F.removed("onLayerClick","onClick")(),e.initialViewState&&!de(this.props.initialViewState,e.initialViewState,3)&&(this.viewState=e.initialViewState),Object.assign(this.props,e),this._validateInternalPickingMode(),this._setCanvasSize(this.props);let r=Object.create(this.props);Object.assign(r,{views:this._getViews(),width:this.width,height:this.height,viewState:this._getViewState()}),e.device&&e.device.id!==this.device?.id&&(this.animationLoop?.stop(),this.canvas!==e.device.canvasContext?.canvas&&(this.canvas?.remove(),this.eventManager?.destroy(),this.canvas=null),F.log(`recreating animation loop for new device! id=${e.device.id}`)(),this.animationLoop=this._createAnimationLoop(e.device,e),this.animationLoop.start()),this.animationLoop?.setProps(r),e.useDevicePixels!==void 0&&this.device?.canvasContext?.setProps&&this.device.canvasContext.setProps({useDevicePixels:e.useDevicePixels}),this.layerManager&&(this.viewManager.setProps(r),this.layerManager.activateViewport(this.getViewports()[0]),this.layerManager.setProps(r),this.effectManager.setProps(r),this.deckRenderer.setProps(r),this.deckPicker.setProps(r),this.widgetManager.setProps(r)),this.stats.get("setProps Time").timeEnd()}needsRedraw(e={clearRedrawFlags:!1}){if(!this.layerManager)return!1;if(this.props._animate)return"Deck._animate";let r=this._needsRedraw;e.clearRedrawFlags&&(this._needsRedraw=!1);let i=this.viewManager.needsRedraw(e),n=this.layerManager.needsRedraw(e),o=this.effectManager.needsRedraw(e),s=this.deckRenderer.needsRedraw(e);return r=r||i||n||o||s,r}redraw(e){if(!this.layerManager)return;let r=this.needsRedraw({clearRedrawFlags:!0});r=e||r,r&&(this.stats.get("Redraw Count").incrementCount(),this.props._customRender?this.props._customRender(r):this._drawLayers(r))}get isInitialized(){return this.viewManager!==null}getViews(){return J(this.viewManager),this.viewManager.views}getView(e){return J(this.viewManager),this.viewManager.getView(e)}getViewports(e){return J(this.viewManager),this.viewManager.getViewports(e)}getCanvas(){return this.canvas}async pickObjectAsync(e){let r=(await this._pickAsync("pickObjectAsync","pickObject Time",e)).result;return r.length?r[0]:null}async pickObjectsAsync(e){return await this._pickAsync("pickObjectsAsync","pickObjects Time",e)}pickObject(e){let r=this._pick("pickObject","pickObject Time",e).result;return r.length?r[0]:null}pickMultipleObjects(e){return e.depth=e.depth||10,this._pick("pickObject","pickMultipleObjects Time",e).result}pickObjects(e){return this._pick("pickObjects","pickObjects Time",e)}_pickPositionForController(e,r){return this._getInternalPickingMode()!=="sync"?null:this.pickObject({x:e,y:r,radius:0,unproject3D:!0})}_addResources(e,r=!1){for(let i in e)this.layerManager.resourceManager.add({resourceId:i,data:e[i],forceUpdate:r})}_removeResources(e){for(let r of e)this.layerManager.resourceManager.remove(r)}_addDefaultEffect(e){this.effectManager.addDefaultEffect(e)}_addDefaultShaderModule(e){this.layerManager.addDefaultShaderModule(e)}_removeDefaultShaderModule(e){this.layerManager?.removeDefaultShaderModule(e)}_resolveInternalPickingMode(){let{pickAsync:e}=this.props,r=this.device?.type||this.props.deviceProps?.type;if(e==="auto")return r==="webgpu"?"async":"sync";if(e==="sync"&&r==="webgpu")throw new Error('`pickAsync: "sync"` is not supported when Deck is using a WebGPU device.');return e}_getInternalPickingMode(){try{return this._resolveInternalPickingMode()}catch(e){return this.props.onError?.(e),null}}_validateInternalPickingMode(){this._getInternalPickingMode()}_getFirstPickedInfo({result:e,emptyInfo:r}){return e[0]||r}_shouldUnproject3D(e=this.layerManager?.getLayers()||[]){return e.some(r=>r.props.pickable==="3d")}_getPointPickOptions(e,r,i={},n=this.layerManager?.getLayers()||[]){return{x:e,y:r,radius:this.props.pickingRadius,unproject3D:this._shouldUnproject3D(n),...i}}_pickPointSync(e){return this._pick("pickObject","pickObject Time",e)}_pickPointAsync(e){return this._pickAsync("pickObjectAsync","pickObject Time",e)}_getLastPointerDownPickingInfo(e,r,i=this.layerManager?.getLayers()||[]){return this.deckPicker.getLastPickedObject({x:e,y:r,layers:i,viewports:this.getViewports({x:e,y:r})},this._lastPointerDownInfo)}_applyHoverCallbacks({result:e,emptyInfo:r},i){if(!this.widgetManager)return;this.cursorState.isHovering=e.length>0;let n=r,o=!1;for(let s of e)n=s,o=s.layer?.onHover(s,i)||o;o||(this.props.onHover?.(n,i),this.widgetManager.onHover(n,i))}_dispatchPickingEvent(e,r){if(!this.layerManager||!this.widgetManager)return;let i=xn[r.type];if(!i)return;let{layer:n}=e,o=n&&(n[i]||n.props[i]),s=this.props[i],a=!1;o&&(a=o.call(n,e,r)),a||(s?.(e,r),this.widgetManager.onEvent(e,r))}_pickAsync(e,r,i){J(this.deckPicker);let{stats:n}=this;n.get("Pick Count").incrementCount(),n.get(r).timeStart();let o=this.deckPicker[e]({layers:this.layerManager.getLayers(i),views:this.viewManager.getViews(),viewports:this.getViewports(i),onViewportActive:this.layerManager.activateViewport,effects:this.effectManager.getEffects(),...i});return n.get(r).timeEnd(),o}_pick(e,r,i){J(this.deckPicker);let{stats:n}=this;n.get("Pick Count").incrementCount(),n.get(r).timeStart();let o=this.deckPicker[e]({layers:this.layerManager.getLayers(i),views:this.viewManager.getViews(),viewports:this.getViewports(i),onViewportActive:this.layerManager.activateViewport,effects:this.effectManager.getEffects(),...i});return n.get(r).timeEnd(),o}_createCanvas(e){let r=e.canvas;return typeof r=="string"&&(r=document.getElementById(r),J(r)),r||(r=document.createElement("canvas"),r.id=e.id||"deckgl-overlay",e.width&&typeof e.width=="number"&&(r.width=e.width),e.height&&typeof e.height=="number"&&(r.height=e.height),(e.parent||document.body).appendChild(r)),Object.assign(r.style,e.style),r}_setCanvasSize(e){if(!this.canvas)return;let{width:r,height:i}=e;if(r||r===0){let n=Number.isFinite(r)?`${r}px`:r;this.canvas.style.width=n}if(i||i===0){let n=Number.isFinite(i)?`${i}px`:i;this.canvas.style.position=e.style?.position||"absolute",this.canvas.style.height=n}}_updateCanvasSize(){let{canvas:e}=this;if(!e)return;let r=e.clientWidth??e.width,i=e.clientHeight??e.height;(r!==this.width||i!==this.height)&&(this.width=r,this.height=i,this.viewManager?.setProps({width:r,height:i}),this.layerManager?.activateViewport(this.getViewports()[0]),this.props.onResize({width:r,height:i}))}_createAnimationLoop(e,r){let{gl:i,onError:n}=r;return new gs({device:e,autoResizeDrawingBuffer:!i,autoResizeViewport:!1,onInitialize:o=>this._setDevice(o.device),onRender:this._onRenderFrame.bind(this),onError:n})}_createDevice(e){let r=this.props.deviceProps?.createCanvasContext,i=typeof r=="object"?r:void 0,n={adapters:[],_cacheShaders:!0,_cachePipelines:!0,...e.deviceProps};n.adapters.includes(Ws)||n.adapters.push(Ws);let o={alphaMode:this.props.deviceProps?.type==="webgpu"?"premultiplied":void 0},s=this.props.deviceProps?.onResize;return hn.createDevice({_reuseDevices:!0,type:"webgl",...n,createCanvasContext:{...o,...i,canvas:this._createCanvas(e),useDevicePixels:this.props.useDevicePixels,autoResize:!0},onResize:(a,c)=>{this._needsRedraw="Canvas resized",s?.(a,c)}})}_getViewState(){return this.props.viewState||this.viewState}_getViews(){let{views:e}=this.props,r=Array.isArray(e)?e:e?[e]:[new Cs({id:"default-view"})];return r.length&&this.props.controller&&(r[0].props.controller=this.props.controller),r}_onContextLost(){let{onError:e}=this.props;this.animationLoop&&e&&e(new Error("WebGL context is lost"))}_pickAndCallback(){let{_pickRequest:e}=this;if(e.event){let r=e.event,i=this.layerManager?.getLayers()||[],n=this._getPointPickOptions(e.x,e.y,{radius:e.radius,mode:e.mode},i),o=this._getInternalPickingMode(),s=++this._hoverPickSequence;if(e.event=null,!o)return;if(o==="sync"){this._applyHoverCallbacks(this._pickPointSync(n),r);return}this._pickPointAsync(n).then(({result:a,emptyInfo:c})=>{s===this._hoverPickSequence&&this._applyHoverCallbacks({result:a,emptyInfo:c},r)}).catch(a=>this.props.onError?.(a))}}_updateCursor(){let e=this.props.parent||this.canvas;e&&(e.style.cursor=this.props.getCursor(this.cursorState))}_setDevice(e){if(this.device=e,this._validateInternalPickingMode(),!this.animationLoop)return;this.canvas||(this.canvas=this.device.canvasContext?.canvas,!this.canvas.isConnected&&this.props.parent&&this.props.parent.insertBefore(this.canvas,this.props.parent.firstChild)),this.device.type==="webgl"&&this.device.setParametersWebGL({blend:!0,blendFunc:[770,771,1,771],polygonOffsetFill:!0,depthTest:!0,depthFunc:515}),this.props.onDeviceInitialized(this.device),this.device.type==="webgl"&&this.props.onWebGLInitialized(this.device.gl);let r=new Ai;r.play(),this.animationLoop.attachTimeline(r);let i=this.props.parent?.querySelector(".deck-events-root")||this.canvas;this.eventManager=new ns(i,{touchAction:this.props.touchAction,recognizers:Object.keys(lp).map(s=>{let[a,c,l,f]=lp[s],u=this.props.eventRecognizerOptions?.[s],d={...c,...u,event:s};return{recognizer:new a(d),recognizeWith:l,requestFailure:f}}),events:{pointerdown:this._onPointerDown,pointermove:this._onPointerMove,pointerleave:this._onPointerMove}});for(let s in xn)this.eventManager.on(s,this._onEvent);this.viewManager=new ws({timeline:r,eventManager:this.eventManager,onViewStateChange:this._onViewStateChange.bind(this),onInteractionStateChange:this._onInteractionStateChange.bind(this),pickPosition:this._pickPositionForController.bind(this),views:this._getViews(),viewState:this._getViewState(),width:this.width,height:this.height});let n=this.viewManager.getViewports()[0];this.layerManager=new Ts(this.device,{deck:this,stats:this.stats,viewport:n,timeline:r}),this.effectManager=new Ps({deck:this,device:this.device}),this.deckRenderer=new Is(this.device,{stats:this.stats}),this.deckPicker=new Os(this.device,{stats:this.stats});let o=this.props.parent?.querySelector(".deck-widgets-root")||this.canvas?.parentElement;this.widgetManager=new El({deck:this,parentElement:o}),this.widgetManager.addDefault(new Ns),this.setProps(this.props),this._updateCanvasSize(),this.props.onLoad()}_drawLayers(e,r){let{device:i,gl:n}=this.layerManager.context;this.props.onBeforeRender({device:i,gl:n});let o={target:this.props._framebuffer,layers:this.layerManager.getLayers(),viewports:this.viewManager.getViewports(),onViewportActive:this.layerManager.activateViewport,views:this.viewManager.getViews(),pass:"screen",effects:this.effectManager.getEffects(),...r};this.deckRenderer?.renderLayers(o),o.pass==="screen"&&this.widgetManager.onRedraw({viewports:o.viewports,layers:o.layers}),this.props.onAfterRender({device:i,gl:n})}_onRenderFrame(){this._getFrameStats(),this._metricsCounter++%60===0&&(this._getMetrics(),this.stats.reset(),F.table(4,this.metrics)(),this.props._onMetrics&&this.props._onMetrics(this.metrics)),this._updateCanvasSize(),this._updateCursor(),this.layerManager.updateLayers(),this._pickAndCallback(),this.redraw(),this.viewManager&&this.viewManager.updateViewStates()}_onViewStateChange(e){let r=this.props.onViewStateChange(e)||e.viewState;this.viewState&&(this.viewState={...this.viewState,[e.viewId]:r},this.props.viewState||this.viewManager&&this.viewManager.setProps({viewState:this.viewState}))}_onInteractionStateChange(e){this.cursorState.isDragging=e.isDragging||!1,this.props.onInteractionStateChange(e)}_getFrameStats(){let{stats:e}=this;e.get("frameRate").timeEnd(),e.get("frameRate").timeStart();let r=this.animationLoop.stats;e.get("GPU Time").addTime(r.get("GPU Time").lastTiming),e.get("CPU Time").addTime(r.get("CPU Time").lastTiming)}_getMetrics(){let{metrics:e,stats:r}=this;e.fps=r.get("frameRate").getHz(),e.setPropsTime=r.get("setProps Time").time,e.updateAttributesTime=r.get("Update Attributes").time,e.framesRedrawn=r.get("Redraw Count").count,e.pickTime=r.get("pickObject Time").time+r.get("pickMultipleObjects Time").time+r.get("pickObjects Time").time,e.pickCount=r.get("Pick Count").count,e.layersCount=this.layerManager?.layers.length??0,e.drawLayersCount=r.get("Layers rendered").lastSampleCount,e.pickLayersCount=r.get("Layers picked").lastSampleCount,e.updateAttributesCount=r.get("Layers updated").count,e.updateAttributesCount=r.get("Attributes updated").count,e.gpuTime=r.get("GPU Time").time,e.cpuTime=r.get("CPU Time").time,e.gpuTimePerFrame=r.get("GPU Time").getAverageTime(),e.cpuTimePerFrame=r.get("CPU Time").getAverageTime();let i=hn.stats.get("GPU Time and Memory");e.bufferMemory=i.get("Buffer Memory").count,e.textureMemory=i.get("Texture Memory").count,e.renderbufferMemory=i.get("Renderbuffer Memory").count,e.gpuMemory=i.get("GPU Memory").count}};Vs.defaultProps=wT;Vs.VERSION=y0;var Bn=Vs;z();z();function ST(t){switch(t){case"float64":return Float64Array;case"uint8":case"unorm8":return Uint8ClampedArray;default:return Go(t)}}var AT=ke.getDataType.bind(ke);function js(t,e,r){if(e.size>4)return null;let i=r==="webgpu"&&e.type==="uint8"?"unorm8":e.type;return{attribute:t,format:e.size>1?`${i}x${e.size}`:e.type,byteOffset:e.offset||0}}function Hr(t){return t.stride||t.size*t.bytesPerElement}function vT(t,e){return t.type===e.type&&t.size===e.size&&Hr(t)===Hr(e)&&(t.offset||0)===(e.offset||0)}function dg(t,e){e.offset&&F.removed("shaderAttribute.offset","vertexOffset, elementOffset")();let r=Hr(t),i=e.vertexOffset!==void 0?e.vertexOffset:t.vertexOffset||0,n=e.elementOffset||0,o=i*r+n*t.bytesPerElement+(t.offset||0);return{...e,offset:o,stride:r}}function ON(t,e){let r=dg(t,e);return{high:r,low:{...r,offset:r.offset+t.size*4}}}var $s=class{constructor(e,r,i){this._buffer=null,this.device=e,this.id=r.id||"",this.size=r.size||1;let n=r.logicalType||r.type,o=n==="float64",{defaultValue:s}=r;s=Number.isFinite(s)?[s]:s||new Array(this.size).fill(0);let a;o?a="float32":!n&&r.isIndexed?a="uint32":a=n||"float32";let c=ST(n||a);this.doublePrecision=o,o&&r.fp64===!1&&(c=Float32Array),this.value=null,this.settings={...r,defaultType:c,defaultValue:s,logicalType:n,type:a,normalized:a.includes("norm"),size:this.size,bytesPerElement:c.BYTES_PER_ELEMENT},this.state={...i,externalBuffer:null,bufferAccessor:this.settings,allocatedValue:null,numInstances:0,bounds:null,constant:!1}}get isConstant(){return this.state.constant}get buffer(){return this._buffer}get byteOffset(){let e=this.getAccessor();return e.vertexOffset?e.vertexOffset*Hr(e):0}get numInstances(){return this.state.numInstances}set numInstances(e){this.state.numInstances=e}delete(){this._buffer&&(this._buffer.delete(),this._buffer=null),lr.release(this.state.allocatedValue)}getBuffer(){return this.state.constant?null:this.state.externalBuffer||this._buffer}getValue(e=this.id,r=null){let i={};if(this.state.constant){let n=this.value;if(r){let o=dg(this.getAccessor(),r),s=o.offset/n.BYTES_PER_ELEMENT,a=o.size||this.size;i[e]=n.subarray(s,s+a)}else i[e]=n}else i[e]=this.getBuffer();return this.doublePrecision&&(this.value instanceof Float64Array?i[`${e}64Low`]=i[e]:i[`${e}64Low`]=new Float32Array(this.size)),i}_getBufferLayout(e=this.id,r=null){let i=this.getAccessor(),n=[],o={name:this.id,byteStride:Hr(i)};if(this.doublePrecision){let s=ON(i,r||{});n.push(js(e,{...i,...s.high},this.device.type),js(`${e}64Low`,{...i,...s.low},this.device.type))}else if(r){let s=dg(i,r);n.push(js(e,{...i,...s},this.device.type))}else n.push(js(e,i,this.device.type));return o.attributes=n.filter(Boolean),o}setAccessor(e){this.state.bufferAccessor=e}getAccessor(){return this.state.bufferAccessor}getBounds(){if(this.state.bounds)return this.state.bounds;let e=null;if(this.state.constant&&this.value){let r=Array.from(this.value);e=[r,r]}else{let{value:r,numInstances:i,size:n}=this,o=i*n;if(r&&o&&r.length>=o){let s=new Array(n).fill(1/0),a=new Array(n).fill(-1/0);for(let c=0;ca[l]&&(a[l]=f)}e=[s,a]}}return this.state.bounds=e,e}setData(e){let{state:r}=this,i;ArrayBuffer.isView(e)?i={value:e}:e instanceof j?i={buffer:e}:i=e;let n={...this.settings,...i};if(ArrayBuffer.isView(i.value)){if(!i.type)if(this.doublePrecision&&i.value instanceof Float64Array)n.type="float32";else{let s=AT(i.value);n.type=n.normalized?s.replace("int","norm"):s}n.bytesPerElement=i.value.BYTES_PER_ELEMENT,n.stride=Hr(n)}if(r.bounds=null,i.constant){let o=i.value;if(o=this._normalizeValue(o,[],0),this.settings.normalized&&(o=this.normalizeConstant(o)),!(!r.constant||!this._areValuesEqual(o,this.value)))return!1;r.externalBuffer=null,r.constant=!0,this.value=ArrayBuffer.isView(o)?o:new Float32Array(o)}else if(i.buffer){let o=i.buffer;r.externalBuffer=o,r.constant=!1,this.value=i.value||null}else if(i.value){this._checkExternalBuffer(i);let o=i.value;r.externalBuffer=null,r.constant=!1,this.value=o;let{buffer:s}=this,a=Hr(n),c=(n.vertexOffset||0)*a;if(this.doublePrecision&&o instanceof Float64Array&&(o=ll(o,n)),this.settings.isIndexed){let f=this.settings.defaultType;o.constructor!==f&&(o=new f(o))}let l=o.byteLength+c+a*2;(!s||s.byteLength(r+128)/255*2-1);case"snorm16":return new Float32Array(e).map(r=>(r+32768)/65535*2-1);case"unorm8":return new Float32Array(e).map(r=>r/255);case"unorm16":return new Float32Array(e).map(r=>r/65535);default:return e}}_normalizeValue(e,r,i){let{defaultValue:n,size:o}=this.settings;if(Number.isFinite(e))return r[i]=e,r;if(!e){let s=o;for(;--s>=0;)r[i+s]=n[s];return r}switch(o){case 4:r[i+3]=Number.isFinite(e[3])?e[3]:n[3];case 3:r[i+2]=Number.isFinite(e[2])?e[2]:n[2];case 2:r[i+1]=Number.isFinite(e[1])?e[1]:n[1];case 1:r[i+0]=Number.isFinite(e[0])?e[0]:n[0];break;default:let s=o;for(;--s>=0;)r[i+s]=Number.isFinite(e[s])?e[s]:n[s]}return r}_areValuesEqual(e,r){if(!e||!r)return!1;let{size:i}=this;for(let n=0;n0&&(RT.length=t.length,i=RT):i=ET,(e>0||Number.isFinite(r))&&(i=(Array.isArray(i)?i:Array.from(i)).slice(e,r),n.index=e-1),{iterable:i,objectInfo:n}}function df(t){return t&&t[Symbol.asyncIterator]}function CT(t,e){let{size:r,stride:i,offset:n,startIndices:o,nested:s}=e,a=t.BYTES_PER_ELEMENT,c=i?i/a:r,l=n?n/a:0,f=Math.floor((t.length-l)/c);return(u,{index:d,target:h})=>{if(!o){let _=d*c+l;for(let T=0;T=e[1]))return t;let r=[],i=t.length,n=0;for(let o=0;oe[1]?r.push(s):e=[Math.min(s[0],e[0]),Math.max(s[1],e[1])]}return r.splice(n,0,e),r}var DN={interpolation:{duration:0,easing:t=>t},spring:{stiffness:.05,damping:.5}};function hf(t,e){if(!t)return null;Number.isFinite(t)&&(t={type:"interpolation",duration:t});let r=t.type||"interpolation";return{...DN[r],...e,...t,type:r}}var Ni=class extends $s{constructor(e,r){super(e,r,{startIndices:null,lastExternalBuffer:null,binaryValue:null,binaryAccessor:null,needsUpdate:!0,needsRedraw:!1,layoutChanged:!1,updateRanges:Hs}),this.constant=!1,this.settings.update=r.update||(r.accessor?this._autoUpdater:void 0),Object.seal(this.settings),Object.seal(this.state),this._validateAttributeUpdaters()}get startIndices(){return this.state.startIndices}set startIndices(e){this.state.startIndices=e}needsUpdate(){return this.state.needsUpdate}needsRedraw({clearChangedFlags:e=!1}={}){let r=this.state.needsRedraw;return this.state.needsRedraw=r&&!e,r}layoutChanged(){return this.state.layoutChanged}setAccessor(e){var r;(r=this.state).layoutChanged||(r.layoutChanged=!vT(e,this.getAccessor())),super.setAccessor(e)}getUpdateTriggers(){let{accessor:e}=this.settings;return[this.id].concat(typeof e!="function"&&e||[])}supportsTransition(){return!!this.settings.transition}getTransitionSetting(e){if(!e||!this.supportsTransition())return null;let{accessor:r}=this.settings,i=this.settings.transition,n=Array.isArray(r)?e[r.find(o=>e[o])]:e[r];return hf(n,i)}setNeedsUpdate(e=this.id,r){if(this.state.needsUpdate=this.state.needsUpdate||e,this.setNeedsRedraw(e),r){let{startRow:i=0,endRow:n=1/0}=r;this.state.updateRanges=MT(this.state.updateRanges,[i,n])}else this.state.updateRanges=Hs}clearNeedsUpdate(){this.state.needsUpdate=!1,this.state.updateRanges=PT}setNeedsRedraw(e=this.id){this.state.needsRedraw=this.state.needsRedraw||e}allocate(e){let{state:r,settings:i}=this;return i.noAlloc?!1:i.update?(super.allocate(e,r.updateRanges!==Hs),!0):!1}updateBuffer({numInstances:e,data:r,props:i,context:n}){if(!this.needsUpdate())return!1;let{state:{updateRanges:o},settings:{update:s,noAlloc:a}}=this,c=!0;if(s){for(let[l,f]of o)s.call(n,this,{data:r,startRow:l,endRow:f,props:i,numInstances:e});if(this.value)if(this.constant||!this.buffer||this.buffer.byteLengthf?l.set(y,g):(e._normalizeValue(y,_.target,0),Ip({target:l,source:_.target,start:g,count:x}));g+=x*f}else e._normalizeValue(y,l,g),g+=f}}_validateAttributeUpdaters(){let{settings:e}=this;if(!(e.noAlloc||typeof e.update=="function"))throw new Error(`Attribute ${this.id} missing update or accessor`)}_checkAttributeArray(){let{value:e}=this,r=Math.min(4,this.size);if(e&&e.length>=r){let i=!0;switch(r){case 4:i=i&&Number.isFinite(e[3]);case 3:i=i&&Number.isFinite(e[2]);case 2:i=i&&Number.isFinite(e[1]);case 1:i=i&&Number.isFinite(e[0]);break;default:i=!1}if(!i)throw new Error(`Illegal attribute generated for ${this.id}`)}}};function hg(t){let{source:e,target:r,start:i=0,size:n,getData:o}=t,s=t.end||r.length,a=e.length,c=s-i;if(a>c){r.set(e.subarray(0,c),i);return}if(r.set(e,i),!o)return;let l=a;for(;li(f+a,u)),l=Math.min(n.length,o.length);for(let f=1;fa}){let a=r.doublePrecision&&r.value instanceof Float64Array?2:1,c=r.size*a,l=r.byteOffset,f=r.settings.bytesPerElement<4?l/r.settings.bytesPerElement*4:l,u=r.startIndices,d=o&&u,h=r.isConstant;if(!d&&e&&i>=n)return e;let p=r.value instanceof Float64Array?Float32Array:r.value.constructor,g=h?r.value:new p(r.getBuffer().readSyncWebGL(l,n*p.BYTES_PER_ELEMENT).buffer);if(r.settings.normalized&&!h){let y=s;s=(x,w)=>r.normalizeConstant(y(x,w))}let m=h?(y,x)=>s(g,x):(y,x)=>s(g.subarray(y+l,y+l+c),x),_=e?new Float32Array(e.readSyncWebGL(f,i*4).buffer):new Float32Array(0),T=new Float32Array(n);return IT({source:_,target:T,sourceStartIndices:o,targetStartIndices:u,size:c,getData:m}),(!e||e.byteLength0||n.end()}delete(){super.delete(),this.transform.destroy(),this.texture.destroy(),this.framebuffer.destroy()}},UN=`layout(std140) uniform springUniforms { + float damping; + float stiffness; +} spring; +`,zN={name:"spring",vs:UN,uniformTypes:{damping:"f32",stiffness:"f32"}},WN=`#version 300 es +#define SHADER_NAME spring-transition-vertex-shader + +#define EPSILON 0.00001 + +in ATTRIBUTE_TYPE aPrev; +in ATTRIBUTE_TYPE aCur; +in ATTRIBUTE_TYPE aTo; +out ATTRIBUTE_TYPE vNext; +out float vIsTransitioningFlag; + +ATTRIBUTE_TYPE getNextValue(ATTRIBUTE_TYPE cur, ATTRIBUTE_TYPE prev, ATTRIBUTE_TYPE dest) { + ATTRIBUTE_TYPE velocity = cur - prev; + ATTRIBUTE_TYPE delta = dest - cur; + ATTRIBUTE_TYPE force = delta * spring.stiffness; + ATTRIBUTE_TYPE resistance = velocity * spring.damping; + return force - resistance + velocity + cur; +} + +void main(void) { + bool isTransitioning = length(aCur - aPrev) > EPSILON || length(aTo - aCur) > EPSILON; + vIsTransitioningFlag = isTransitioning ? 1.0 : 0.0; + + vNext = getNextValue(aCur, aPrev, aTo); + gl_Position = vec4(0, 0, 0, 1); + gl_PointSize = 100.0; +} +`,VN=`#version 300 es +#define SHADER_NAME spring-transition-is-transitioning-fragment-shader + +in float vIsTransitioningFlag; + +out vec4 fragColor; + +void main(void) { + if (vIsTransitioningFlag == 0.0) { + discard; + } + fragColor = vec4(1.0); +}`;function jN(t,e){let r=pf(e.size),i=gf(e.size);return new zr(t,{vs:WN,fs:VN,bufferLayout:[{name:"aPrev",format:i},{name:"aCur",format:i},{name:"aTo",format:e.getBufferLayout().attributes[0].format}],varyings:["vNext"],modules:[zN],defines:{ATTRIBUTE_TYPE:r},parameters:{depthCompare:"always",blendColorOperation:"max",blendColorSrcFactor:"one",blendColorDstFactor:"one",blendAlphaOperation:"max",blendAlphaSrcFactor:"one",blendAlphaDstFactor:"one"}})}function $N(t){return t.createTexture({data:new Uint8Array(4),format:"rgba8unorm",width:1,height:1})}function HN(t,e){return t.createFramebuffer({id:"spring-transition-is-transitioning-framebuffer",width:1,height:1,colorAttachments:[e]})}var YN={interpolation:Ys,spring:Xs},Gs=class{constructor(e,{id:r,timeline:i}){if(!e)throw new Error("AttributeTransitionManager is constructed without device");this.id=r,this.device=e,this.timeline=i,this.transitions={},this.needsRedraw=!1,this.numInstances=1}finalize(){for(let e in this.transitions)this._removeTransition(e)}update({attributes:e,transitions:r,numInstances:i}){this.numInstances=i||1;for(let n in e){let o=e[n],s=o.getTransitionSetting(r);s&&this._updateAttribute(n,o,s)}for(let n in this.transitions){let o=e[n];(!o||!o.getTransitionSetting(r))&&this._removeTransition(n)}}hasAttribute(e){let r=this.transitions[e];return r&&r.inProgress}getAttributes(){let e={};for(let r in this.transitions){let i=this.transitions[r];i.inProgress&&(e[r]=i.attributeInTransition)}return e}run(){if(this.numInstances===0)return!1;for(let r in this.transitions)this.transitions[r].update()&&(this.needsRedraw=!0);let e=this.needsRedraw;return this.needsRedraw=!1,e}_removeTransition(e){this.transitions[e].delete(),delete this.transitions[e]}_updateAttribute(e,r,i){let n=this.transitions[e],o=!n||n.type!==i.type;if(o){n&&this._removeTransition(e);let s=YN[i.type];s?this.transitions[e]=new s({attribute:r,timeline:this.timeline,device:this.device}):(F.error(`unsupported transition type '${i.type}'`)(),o=!1)}(o||r.needsRedraw())&&(this.needsRedraw=!0,this.transitions[e].start(i,this.numInstances))}};var FT="attributeManager.invalidate",XN="attributeManager.updateStart",GN="attributeManager.updateEnd",qN="attribute.updateStart",KN="attribute.allocate",ZN="attribute.updateEnd",qs=class{constructor(e,{id:r="attribute-manager",stats:i,timeline:n}={}){this.mergeBoundsMemoized=kt(bb),this.id=r,this.device=e,this.attributes={},this.updateTriggers={},this.needsRedraw=!0,this.userData={},this.stats=i,this.attributeTransitionManager=new Gs(e,{id:`${r}-transitions`,timeline:n}),Object.seal(this)}finalize(){for(let e in this.attributes)this.attributes[e].delete();this.attributeTransitionManager.finalize()}getNeedsRedraw(e={clearRedrawFlags:!1}){let r=this.needsRedraw;return this.needsRedraw=this.needsRedraw&&!e.clearRedrawFlags,r&&this.id}setNeedsRedraw(){this.needsRedraw=!0}add(e){this._add(e)}addInstanced(e){this._add(e,{stepMode:"instance"})}remove(e){for(let r of e)this.attributes[r]!==void 0&&(this.attributes[r].delete(),delete this.attributes[r])}invalidate(e,r){let i=this._invalidateTrigger(e,r);ae(FT,this,e,i)}invalidateAll(e){for(let r in this.attributes)this.attributes[r].setNeedsUpdate(r,e);ae(FT,this,"all")}update({data:e,numInstances:r,startIndices:i=null,transitions:n,props:o={},buffers:s={},context:a={}}){let c=!1;ae(XN,this),this.stats&&this.stats.get("Update Attributes").timeStart();for(let l in this.attributes){let f=this.attributes[l],u=f.settings.accessor;f.startIndices=i,f.numInstances=r,o[l]&&F.removed(`props.${l}`,`data.attributes.${l}`)(),f.setExternalBuffer(s[l])||f.setBinaryValue(typeof u=="string"?s[u]:void 0,e.startIndices)||typeof u=="string"&&!s[u]&&f.setConstantValue(a,o[u])||f.needsUpdate()&&(c=!0,this._updateAttribute({attribute:f,numInstances:r,data:e,props:o,context:a})),this.needsRedraw=this.needsRedraw||f.needsRedraw()}c&&ae(GN,this,r),this.stats&&(this.stats.get("Update Attributes").timeEnd(),c&&this.stats.get("Attributes updated").incrementCount()),this.attributeTransitionManager.update({attributes:this.attributes,numInstances:r,transitions:n})}updateTransition(){let{attributeTransitionManager:e}=this,r=e.run();return this.needsRedraw=this.needsRedraw||r,r}getAttributes(){return{...this.attributes,...this.attributeTransitionManager.getAttributes()}}getBounds(e){let r=e.map(i=>this.attributes[i]?.getBounds());return this.mergeBoundsMemoized(r)}getChangedAttributes(e={clearChangedFlags:!1}){let{attributes:r,attributeTransitionManager:i}=this,n={...i.getAttributes()};for(let o in r){let s=r[o];s.needsRedraw(e)&&!i.hasAttribute(o)&&(n[o]=s)}return n}getBufferLayouts(e){return Object.values(this.getAttributes()).map(r=>r.getBufferLayout(e))}_add(e,r){for(let i in e){let n=e[i],o={...n,id:i,size:n.isIndexed&&1||n.size||1,...r};this.attributes[i]=new Ni(this.device,o)}this._mapUpdateTriggersToAttributes()}_mapUpdateTriggersToAttributes(){let e={};for(let r in this.attributes)this.attributes[r].getUpdateTriggers().forEach(n=>{e[n]||(e[n]=[]),e[n].push(r)});this.updateTriggers=e}_invalidateTrigger(e,r){let{attributes:i,updateTriggers:n}=this,o=n[e];return o&&o.forEach(s=>{let a=i[s];a&&a.setNeedsUpdate(a.id,r)}),o}_updateAttribute(e){let{attribute:r,numInstances:i}=e;if(ae(qN,r),r.constant){r.setConstantValue(e.context,r.value);return}r.allocate(i)&&ae(KN,r,i),r.updateBuffer(e)&&(this.needsRedraw=!0,ae(ZN,r,i))}};z();cf();var Ks=class extends xt{get value(){return this._value}_onUpdate(){let{time:e,settings:{fromValue:r,toValue:i,duration:n,easing:o}}=this,s=o(e/n);this._value=di(r,i,s)}};var BT=1e-5;function kT(t,e,r,i,n){let o=e-t,a=(r-e)*n,c=-o*i;return a+c+o+e}function QN(t,e,r,i,n){if(Array.isArray(r)){let o=[];for(let s=0;s0}add(e,r,i,n){let{transitions:o}=this;if(o.has(e)){let c=o.get(e),{value:l=c.settings.fromValue}=c;r=l,this.remove(e)}if(n=hf(n),!n)return;let s=JN[n.type];if(!s){F.error(`unsupported transition type '${n.type}'`)();return}let a=new s(this.timeline);a.start({...n,fromValue:r,toValue:i}),o.set(e,a)}remove(e){let{transitions:r}=this;r.has(e)&&(r.get(e).cancel(),r.delete(e))}update(){let e={};for(let[r,i]of this.transitions)i.update(),e[r]=i.value,i.inProgress||this.remove(r);return e}clear(){for(let e of this.transitions.keys())this.remove(e)}};function WT(t){let e=t[ct];for(let r in e){let i=e[r],{validate:n}=i;if(n&&!n(t[r],i))throw new Error(`Invalid prop ${r}: ${t[r]}`)}}function VT(t,e){let r=jT({newProps:t,oldProps:e,propTypes:t[ct],ignoreProps:{data:null,updateTriggers:null,extensions:null,transitions:null}}),i=tD(t,e),n=!1;return i||(n=rD(t,e)),{dataChanged:i,propsChanged:r,updateTriggersChanged:n,extensionsChanged:iD(t,e),transitionsChanged:eD(t,e)}}function eD(t,e){if(!t.transitions)return!1;let r={},i=t[ct],n=!1;for(let o in t.transitions){let s=i[o],a=s&&s.type;(a==="number"||a==="color"||a==="array")&&pg(t[o],e[o],s)&&(r[o]=!0,n=!0)}return n?r:!1}function jT({newProps:t,oldProps:e,ignoreProps:r={},propTypes:i={},triggerName:n="props"}){if(e===t)return!1;if(typeof t!="object"||t===null)return`${n} changed shallowly`;if(typeof e!="object"||e===null)return`${n} changed shallowly`;for(let o of Object.keys(t))if(!(o in r)){if(!(o in e))return`${n}.${o} added`;let s=pg(t[o],e[o],i[o]);if(s)return`${n}.${o} ${s}`}for(let o of Object.keys(e))if(!(o in r)){if(!(o in t))return`${n}.${o} dropped`;if(!Object.hasOwnProperty.call(t,o)){let s=pg(t[o],e[o],i[o]);if(s)return`${n}.${o} ${s}`}}return!1}function pg(t,e,r){let i=r&&r.equal;return i&&!i(t,e,r)||!i&&(i=t&&e&&t.equals,i&&!i.call(t,e))?"changed deeply":!i&&e!==t?"changed shallowly":null}function tD(t,e){if(e===null)return"oldProps is null, initial diff";let r=!1,{dataComparator:i,_dataDiff:n}=t;return i?i(t.data,e.data)||(r="Data comparator detected a change"):t.data!==e.data&&(r="A new data container was supplied"),r&&n&&(r=n(t.data,e.data)||r),r}function rD(t,e){if(e===null)return{all:!0};if("all"in t.updateTriggers&&zT(t,e,"all"))return{all:!0};let r={},i=!1;for(let n in t.updateTriggers)n!=="all"&&zT(t,e,n)&&(r[n]=!0,i=!0);return i?r:!1}function iD(t,e){if(e===null)return!0;let r=e.extensions,{extensions:i}=t;if(i===r)return!1;if(!r||!i||i.length!==r.length)return!0;for(let n=0;ni.name==="project64"))){let i=r.modules.findIndex(n=>n.name==="project32");i>=0&&r.modules.splice(i,1)}if("inject"in e)if(!t.inject)r.inject=e.inject;else{let i={...t.inject};for(let n in e.inject)i[n]=(i[n]||"")+e.inject[n];r.inject=i}return r}z();var cD={minFilter:"linear",mipmapFilter:"linear",magFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"},mg={};function HT(t,e,r,i){if(r instanceof $)return r;r.constructor&&r.constructor.name!=="Object"&&(r={data:r});let n=null;r.compressed&&(n={minFilter:"linear",mipmapFilter:r.data.length>1?"nearest":"linear"});let{width:o,height:s}=r.data,a=e.createTexture({...r,sampler:{...cD,...n,...i},mipLevels:e.getMipLevelCount(o,s)});return e.type==="webgl"?a.generateMipmapsWebGL():e.type==="webgpu"&&e.generateMipmapsWebGPU(a),mg[a.id]=t,a}function YT(t,e){!e||!(e instanceof $)||mg[e.id]===t&&(e.delete(),delete mg[e.id])}var lD={boolean:{validate(t,e){return!0},equal(t,e,r){return!!t==!!e}},number:{validate(t,e){return Number.isFinite(t)&&(!("max"in e)||t<=e.max)&&(!("min"in e)||t>=e.min)}},color:{validate(t,e){return e.optional&&!t||_g(t)&&(t.length===3||t.length===4)},equal(t,e,r){return de(t,e,1)}},accessor:{validate(t,e){let r=xf(t);return r==="function"||r===xf(e.value)},equal(t,e,r){return typeof e=="function"?!0:de(t,e,1)}},array:{validate(t,e){return e.optional&&!t||_g(t)},equal(t,e,r){let{compare:i}=r,n=Number.isInteger(i)?i:i?1:0;return i?de(t,e,n):t===e}},object:{equal(t,e,r){if(r.ignore)return!0;let{compare:i}=r,n=Number.isInteger(i)?i:i?1:0;return i?de(t,e,n):t===e}},function:{validate(t,e){return e.optional&&!t||typeof t=="function"},equal(t,e,r){return!r.compare&&r.ignore!==!1||t===e}},data:{transform:(t,e,r)=>{if(!t)return t;let{dataTransform:i}=r.props;return i?i(t):typeof t.shape=="string"&&t.shape.endsWith("-table")&&Array.isArray(t.data)?t.data:t}},image:{transform:(t,e,r)=>{let i=r.context;return!i||!i.device?null:HT(r.id,i.device,t,{...e.parameters,...r.props.textureParameters})},release:(t,e,r)=>{YT(r.id,t)}}};function XT(t){let e={},r={},i={};for(let[n,o]of Object.entries(t)){let s=o?.deprecatedFor;if(s)i[n]=Array.isArray(s)?s:[s];else{let a=fD(n,o);e[n]=a,r[n]=a.value}}return{propTypes:e,defaultProps:r,deprecatedProps:i}}function fD(t,e){switch(xf(e)){case"object":return Js(t,e);case"array":return Js(t,{type:"array",value:e,compare:!1});case"boolean":return Js(t,{type:"boolean",value:e});case"number":return Js(t,{type:"number",value:e});case"function":return Js(t,{type:"function",value:e,compare:!0});default:return{name:t,type:"unknown",value:e}}}function Js(t,e){return"type"in e?{name:t,...lD[e.type],...e}:"value"in e?{name:t,type:xf(e.value),...e}:{name:t,type:"object",value:e}}function _g(t){return Array.isArray(t)||ArrayBuffer.isView(t)}function xf(t){return _g(t)?"array":t===null?"null":typeof t}function GT(t,e){let r;for(let o=e.length-1;o>=0;o--){let s=e[o];"extensions"in s&&(r=s.extensions)}let i=yg(t.constructor,r),n=Object.create(i);n[Mn]=t,n[zt]={},n[yt]={};for(let o=0;o{},this.oldProps=null,this.oldAsyncProps=null}finalize(){for(let e in this.asyncProps){let r=this.asyncProps[e];r&&r.type&&r.type.release&&r.type.release(r.resolvedValue,r.type,this.component)}this.asyncProps={},this.component=null,this.resetOldProps()}getOldProps(){return this.oldAsyncProps||this.oldProps||xD}resetOldProps(){this.oldAsyncProps=null,this.oldProps=this.component?this.component.props:null}hasAsyncProp(e){return e in this.asyncProps}getAsyncProp(e){let r=this.asyncProps[e];return r&&r.resolvedValue}isAsyncPropLoading(e){if(e){let r=this.asyncProps[e];return!!(r&&r.pendingLoadCount>0&&r.pendingLoadCount!==r.resolvedLoadCount)}for(let r in this.asyncProps)if(this.isAsyncPropLoading(r))return!0;return!1}reloadAsyncProp(e,r){this._watchPromise(e,Promise.resolve(r))}setAsyncProps(e){this.component=e[Mn]||this.component;let r=e[yt]||{},i=e[zt]||e,n=e[fr]||{};for(let o in r){let s=r[o];this._createAsyncPropData(o,n[o]),this._updateAsyncProp(o,s),r[o]=this.getAsyncProp(o)}for(let o in i){let s=i[o];this._createAsyncPropData(o,n[o]),this._updateAsyncProp(o,s)}}_fetch(e,r){return null}_onResolve(e,r){}_onError(e,r){}_updateAsyncProp(e,r){if(this._didAsyncInputValueChange(e,r)){if(typeof r=="string"&&(r=this._fetch(e,r)),r instanceof Promise){this._watchPromise(e,r);return}if(df(r)){this._resolveAsyncIterable(e,r);return}this._setPropValue(e,r)}}_freezeAsyncOldProps(){if(!this.oldAsyncProps&&this.oldProps){this.oldAsyncProps=Object.create(this.oldProps);for(let e in this.asyncProps)Object.defineProperty(this.oldAsyncProps,e,{enumerable:!0,value:this.oldProps[e]})}}_didAsyncInputValueChange(e,r){let i=this.asyncProps[e];return r===i.resolvedValue||r===i.lastValue?!1:(i.lastValue=r,!0)}_setPropValue(e,r){this._freezeAsyncOldProps();let i=this.asyncProps[e];i&&(r=this._postProcessValue(i,r),i.resolvedValue=r,i.pendingLoadCount++,i.resolvedLoadCount=i.pendingLoadCount)}_setAsyncPropValue(e,r,i){let n=this.asyncProps[e];n&&i>=n.resolvedLoadCount&&r!==void 0&&(this._freezeAsyncOldProps(),n.resolvedValue=r,n.resolvedLoadCount=i,this.onAsyncPropUpdated(e,r))}_watchPromise(e,r){let i=this.asyncProps[e];if(i){i.pendingLoadCount++;let n=i.pendingLoadCount;r.then(o=>{this.component&&(o=this._postProcessValue(i,o),this._setAsyncPropValue(e,o,n),this._onResolve(e,o))}).catch(o=>{this._onError(e,o)})}}async _resolveAsyncIterable(e,r){if(e!=="data"){this._setPropValue(e,r);return}let i=this.asyncProps[e];if(!i)return;i.pendingLoadCount++;let n=i.pendingLoadCount,o=[],s=0;for await(let a of r){if(!this.component)return;let{dataTransform:c}=this.component.props;c?o=c(a,o):o=o.concat(a),Object.defineProperty(o,"__diff",{enumerable:!1,value:[{startRow:s,endRow:o.length}]}),s=o.length,this._setAsyncPropValue(e,o,n)}this._onResolve(e,o)}_postProcessValue(e,r){let i=e.type;return i&&this.component&&(i.release&&i.release(e.resolvedValue,i,this.component),i.transform)?i.transform(r,i,this.component):r}_createAsyncPropData(e,r){if(!this.asyncProps[e]){let n=this.component&&this.component.props[ct];this.asyncProps[e]={type:n&&n[e],lastValue:null,resolvedValue:r,pendingLoadCount:0,resolvedLoadCount:0}}}};var ra=class extends ta{constructor({attributeManager:e,layer:r}){super(r),this.attributeManager=e,this.needsRedraw=!0,this.needsUpdate=!0,this.subLayers=null,this.usesPickingColorCache=!1}get layer(){return this.component}_fetch(e,r){let i=this.layer,n=i?.props.fetch;return n?n(r,{propName:e,layer:i}):super._fetch(e,r)}_onResolve(e,r){let i=this.layer;if(i){let n=i.props.onDataLoad;e==="data"&&n&&n(r,{propName:e,layer:i})}}_onError(e,r){let i=this.layer;i&&i.raiseError(r,`loading ${e} of ${this.layer}`)}};var bD="layer.changeFlag",TD="layer.initialize",wD="layer.update",SD="layer.finalize",AD="layer.matched",KT=2**24-1,vD=Object.freeze([]),ED=kt(({oldViewport:t,viewport:e})=>t.equals(e)),At=new Uint8ClampedArray(0),RD={data:{type:"data",value:vD,async:!0},dataComparator:{type:"function",value:null,optional:!0},_dataDiff:{type:"function",value:t=>t&&t.__diff,optional:!0},dataTransform:{type:"function",value:null,optional:!0},onDataLoad:{type:"function",value:null,optional:!0},onError:{type:"function",value:null,optional:!0},fetch:{type:"function",value:(t,{propName:e,layer:r,loaders:i,loadOptions:n,signal:o})=>{let{resourceManager:s}=r.context;n=n||r.getLoadOptions(),i=i||r.props.loaders,o&&(n={...n,core:{...n?.core,fetch:{...n?.core?.fetch,signal:o}}});let a=s.contains(t);return!a&&!n&&(s.add({resourceId:t,data:Mr(t,i),persistent:!1}),a=!0),a?s.subscribe({resourceId:t,onChange:c=>r.internalState?.reloadAsyncProp(e,c),consumerId:r.id,requestId:e}):Mr(t,i,n)}},updateTriggers:{},visible:!0,pickable:!1,opacity:{type:"number",min:0,max:1,value:1},operation:"draw",onHover:{type:"function",value:null,optional:!0},onClick:{type:"function",value:null,optional:!0},onDragStart:{type:"function",value:null,optional:!0},onDrag:{type:"function",value:null,optional:!0},onDragEnd:{type:"function",value:null,optional:!0},coordinateSystem:"default",coordinateOrigin:{type:"array",value:[0,0,0],compare:!0},modelMatrix:{type:"array",value:null,compare:!0,optional:!0},wrapLongitude:!1,positionFormat:"XYZ",colorFormat:"RGBA",parameters:{type:"object",value:{},optional:!0,compare:2},loadOptions:{type:"object",value:null,optional:!0,ignore:!0},transitions:null,extensions:[],loaders:{type:"array",value:[],optional:!0,ignore:!0},getPolygonOffset:{type:"function",value:({layerIndex:t})=>[0,-t*100]},highlightedObjectIndex:null,autoHighlight:!1,highlightColor:{type:"accessor",value:[0,0,128,128]}},ia=class extends bf{constructor(){super(...arguments),this.internalState=null,this.lifecycle=Wr.NO_STATE,this.parent=null}static get componentName(){return Object.prototype.hasOwnProperty.call(this,"layerName")?this.layerName:""}get root(){let e=this;for(;e.parent;)e=e.parent;return e}toString(){return`${this.constructor.layerName||this.constructor.name}({id: '${this.props.id}'})`}project(e){J(this.internalState);let r=this.internalState.viewport||this.context.viewport,i=dl(e,{viewport:r,modelMatrix:this.props.modelMatrix,coordinateOrigin:this.props.coordinateOrigin,coordinateSystem:this.props.coordinateSystem}),[n,o,s]=wi(i,r.pixelProjectionMatrix);return e.length===2?[n,o]:[n,o,s]}unproject(e){return J(this.internalState),(this.internalState.viewport||this.context.viewport).unproject(e)}projectPosition(e,r){J(this.internalState);let i=this.internalState.viewport||this.context.viewport;return Sb(e,{viewport:i,modelMatrix:this.props.modelMatrix,coordinateOrigin:this.props.coordinateOrigin,coordinateSystem:this.props.coordinateSystem,...r})}get isComposite(){return!1}get isDrawable(){return!0}setState(e){this.setChangeFlags({stateChanged:!0}),Object.assign(this.state,e),this.setNeedsRedraw()}setNeedsRedraw(){this.internalState&&(this.internalState.needsRedraw=!0)}setNeedsUpdate(){this.internalState&&(this.context.layerManager.setNeedsUpdate(String(this)),this.internalState.needsUpdate=!0)}get isLoaded(){return this.internalState?!this.internalState.isAsyncPropLoading():!1}get wrapLongitude(){return this.props.wrapLongitude}isPickable(){return this.props.pickable&&this.props.visible}getModels(){let e=this.state;return e&&(e.models||e.model&&[e.model])||[]}setShaderModuleProps(...e){for(let r of this.getModels())r.shaderInputs.setProps(...e)}getAttributeManager(){return this.internalState&&this.internalState.attributeManager}getCurrentLayer(){return this.internalState&&this.internalState.layer}getLoadOptions(){return this.props.loadOptions}use64bitPositions(){let{coordinateSystem:e}=this.props;return e==="default"||e==="lnglat"||e==="cartesian"}onHover(e,r){return this.props.onHover&&this.props.onHover(e,r)||!1}onClick(e,r){return this.props.onClick&&this.props.onClick(e,r)||!1}nullPickingColor(){return[0,0,0]}encodePickingColor(e,r=[]){return r[0]=e+1&255,r[1]=e+1>>8&255,r[2]=e+1>>8>>8&255,r}decodePickingColor(e){J(e instanceof Uint8Array);let[r,i,n]=e;return r+i*256+n*65536-1}getNumInstances(){return Number.isFinite(this.props.numInstances)?this.props.numInstances:this.state&&this.state.numInstances!==void 0?this.state.numInstances:$T(this.props.data)}getStartIndices(){return this.props.startIndices?this.props.startIndices:this.state&&this.state.startIndices?this.state.startIndices:null}getBounds(){return this.getAttributeManager()?.getBounds(["positions","instancePositions"])}getShaders(e){e=gg(e,{disableWarnings:!0,modules:this.context.defaultShaderModules});for(let r of this.props.extensions)e=gg(e,r.getShaders.call(this,r));return e}shouldUpdateState(e){return e.changeFlags.propsOrDataChanged}updateState(e){let r=this.getAttributeManager(),{dataChanged:i}=e.changeFlags;if(i&&r)if(Array.isArray(i))for(let n of i)r.invalidateAll(n);else r.invalidateAll();if(r){let{props:n}=e,o=this.internalState.hasPickingBuffer,s=Number.isInteger(n.highlightedObjectIndex)||!!n.pickable||n.extensions.some(a=>a.getNeedsPickingBuffer.call(this,a));if(o!==s){this.internalState.hasPickingBuffer=s;let{pickingColors:a,instancePickingColors:c}=r.attributes,l=a||c;l&&(s&&l.constant&&(l.constant=!1,r.invalidate(l.id)),!l.value&&!s&&(l.constant=!0,l.value=[0,0,0]))}}}finalizeState(e){for(let i of this.getModels())i.destroy();let r=this.getAttributeManager();r&&r.finalize(),this.context&&this.context.resourceManager.unsubscribe({consumerId:this.id}),this.internalState&&(this.internalState.uniformTransitions.clear(),this.internalState.finalize())}draw(e){for(let r of this.getModels())r.draw(e.renderPass)}getPickingInfo({info:e,mode:r,sourceLayer:i}){let{index:n}=e;return n>=0&&Array.isArray(this.props.data)&&(e.object=this.props.data[n]),e}raiseError(e,r){r&&(e=new Error(`${r}: ${e.message}`,{cause:e})),this.props.onError?.(e)||this.context?.onError?.(e,this)}getNeedsRedraw(e={clearRedrawFlags:!1}){return this._getNeedsRedraw(e)}needsUpdate(){return this.internalState?this.internalState.needsUpdate||this.hasUniformTransition()||this.shouldUpdateState(this._getUpdateParams()):!1}hasUniformTransition(){return this.internalState?.uniformTransitions.active||!1}activateViewport(e){if(!this.internalState)return;let r=this.internalState.viewport;this.internalState.viewport=e,(!r||!ED({oldViewport:r,viewport:e}))&&(this.setChangeFlags({viewportChanged:!0}),this.isComposite?this.needsUpdate()&&this.setNeedsUpdate():this._update())}invalidateAttribute(e="all"){let r=this.getAttributeManager();r&&(e==="all"?r.invalidateAll():r.invalidate(e))}updateAttributes(e){let r=!1;for(let i in e)e[i].layoutChanged()&&(r=!0);for(let i of this.getModels())this._setModelAttributes(i,e,r)}_updateAttributes(){let e=this.getAttributeManager();if(!e)return;let r=this.props,i=this.getNumInstances(),n=this.getStartIndices();e.update({data:r.data,numInstances:i,startIndices:n,props:r,transitions:r.transitions,buffers:r.data.attributes,context:this});let o=e.getChangedAttributes({clearChangedFlags:!0});this.updateAttributes(o)}_updateAttributeTransition(){let e=this.getAttributeManager();e&&e.updateTransition()}_updateUniformTransition(){let{uniformTransitions:e}=this.internalState;if(e.active){let r=e.update(),i=Object.create(this.props);for(let n in r)Object.defineProperty(i,n,{value:r[n]});return i}return this.props}calculateInstancePickingColors(e,{numInstances:r}){if(e.constant)return;let i=Math.floor(At.length/4);if(this.internalState.usesPickingColorCache=!0,iKT&&F.warn("Layer has too many data objects. Picking might not be able to distinguish all objects.")(),At=lr.allocate(At,r,{size:4,copy:!0,maxCount:Math.max(r,KT)});let n=Math.floor(At.length/4),o=[0,0,0];for(let s=i;s(F.deprecated("layer.state.attributeManager","layer.getAttributeManager()")(),e)}),this.internalState.uniformTransitions=new Qs(this.context.timeline),this.internalState.onAsyncPropUpdated=this._onAsyncPropUpdated.bind(this),this.internalState.setAsyncProps(this.props),this.initializeState(this.context);for(let r of this.props.extensions)r.initializeState.call(this,this.context,r);this.setChangeFlags({dataChanged:"init",propsChanged:"init",viewportChanged:!0,extensionsChanged:!0}),this._update()}_transferState(e){ae(AD,this,this===e);let{state:r,internalState:i}=e;this!==e&&(this.internalState=i,this.state=r,this.internalState.setAsyncProps(this.props),this._diffProps(this.props,this.internalState.getOldProps()))}_update(){let e=this.needsUpdate();if(ae(wD,this,e),!e)return;this.context.stats.get("Layer updates").incrementCount();let r=this.props,i=this.context,n=this.internalState,o=i.viewport,s=this._updateUniformTransition();n.propsInTransition=s,i.viewport=n.viewport||o,this.props=s;try{let a=this._getUpdateParams(),c=this.getModels();if(i.device)this.updateState(a);else try{this.updateState(a)}catch{}for(let f of this.props.extensions)f.updateState.call(this,a,f);this.setNeedsRedraw(),this._updateAttributes();let l=this.getModels()[0]!==c[0];this._postUpdate(a,l)}finally{i.viewport=o,this.props=r,this._clearChangeFlags(),n.needsUpdate=!1,n.resetOldProps()}}_finalize(){ae(SD,this),this.finalizeState(this.context);for(let e of this.props.extensions)e.finalizeState.call(this,this.context,e)}_drawLayer({renderPass:e,shaderModuleProps:r=null,uniforms:i={},parameters:n={}}){this._updateAttributeTransition();let o=this.props,s=this.context;this.props=this.internalState.propsInTransition||o;try{r&&this.setShaderModuleProps(r);let{getPolygonOffset:a}=this.props,c=a&&a(i)||[0,0];s.device instanceof jr&&s.device.setParametersWebGL({polygonOffset:c});let l=s.device instanceof jr?null:CD(n);if(PD(this.getModels(),e,n,l),s.device instanceof jr)s.device.withParametersWebGL(n,()=>{let f={renderPass:e,shaderModuleProps:r,uniforms:i,parameters:n,context:s};for(let u of this.props.extensions)u.draw.call(this,f,u);this.draw(f)});else{l?.renderPassParameters&&e.setParameters(l.renderPassParameters);let f={renderPass:e,shaderModuleProps:r,uniforms:i,parameters:n,context:s};for(let u of this.props.extensions)u.draw.call(this,f,u);this.draw(f)}}finally{this.props=o}}getChangeFlags(){return this.internalState?.changeFlags}setChangeFlags(e){if(!this.internalState)return;let{changeFlags:r}=this.internalState;for(let n in e)if(e[n]){let o=!1;switch(n){case"dataChanged":let s=e[n],a=r[n];s&&Array.isArray(a)&&(r.dataChanged=Array.isArray(s)?a.concat(s):s,o=!0);default:r[n]||(r[n]=e[n],o=!0)}o&&ae(bD,this,n,e)}let i=!!(r.dataChanged||r.updateTriggersChanged||r.propsChanged||r.extensionsChanged);r.propsOrDataChanged=i,r.somethingChanged=i||r.viewportChanged||r.stateChanged}_clearChangeFlags(){this.internalState.changeFlags={dataChanged:!1,propsChanged:!1,updateTriggersChanged:!1,viewportChanged:!1,stateChanged:!1,extensionsChanged:!1,propsOrDataChanged:!1,somethingChanged:!1}}_diffProps(e,r){let i=VT(e,r);if(i.updateTriggersChanged)for(let n in i.updateTriggersChanged)i.updateTriggersChanged[n]&&this.invalidateAttribute(n);if(i.transitionsChanged)for(let n in i.transitionsChanged)this.internalState.uniformTransitions.add(n,r[n],e[n],e.transitions?.[n]);return this.setChangeFlags(i)}validateProps(){WT(this.props)}updateAutoHighlight(e){this.props.autoHighlight&&!Number.isInteger(this.props.highlightedObjectIndex)&&this._updateAutoHighlight(e)}_updateAutoHighlight(e){let r={highlightedObjectColor:e.picked?e.color:null},{highlightColor:i}=this.props;e.picked&&typeof i=="function"&&(r.highlightColor=i(e)),this.setShaderModuleProps({picking:r}),this.setNeedsRedraw()}_getAttributeManager(){let e=this.context;return new qs(e.device,{id:this.props.id,stats:e.stats,timeline:e.timeline})}_postUpdate(e,r){let{props:i,oldProps:n}=e,o=this.state.model;o?.isInstanced&&o.setInstanceCount(this.getNumInstances());let{autoHighlight:s,highlightedObjectIndex:a,highlightColor:c}=i;if(r||n.autoHighlight!==s||n.highlightedObjectIndex!==a||n.highlightColor!==c){let l={};Array.isArray(c)&&(l.highlightColor=c),(r||n.autoHighlight!==s||a!==n.highlightedObjectIndex)&&(l.highlightedObjectColor=Number.isFinite(a)&&a>=0?this.encodePickingColor(a):null),this.setShaderModuleProps({picking:l})}}_getUpdateParams(){return{props:this.props,oldProps:this.internalState.getOldProps(),context:this.context,changeFlags:this.internalState.changeFlags}}_getNeedsRedraw(e){if(!this.internalState)return!1;let r=!1;r=r||this.internalState.needsRedraw&&this.id;let i=this.getAttributeManager(),n=i?i.getNeedsRedraw(e):!1;if(r=r||n,r)for(let o of this.props.extensions)o.onNeedsRedraw.call(this,o);return this.internalState.needsRedraw=this.internalState.needsRedraw&&!e.clearRedrawFlags,r}_onAsyncPropUpdated(){this._diffProps(this.props,this.internalState.getOldProps()),this.setNeedsUpdate()}};ia.defaultProps=RD;ia.layerName="Layer";var ve=ia;function CD(t){let{blendConstant:e,...r}=t;return e?{pipelineParameters:r,renderPassParameters:{blendConstant:e}}:{pipelineParameters:r}}function PD(t,e,r,i){for(let n of t)n.device.type==="webgpu"?(MD(n,e),n.setParameters({...n.parameters,...i?.pipelineParameters})):n.setParameters(r)}function MD(t,e){let r=e.props.framebuffer||(e.framebuffer??null);if(!r)return;let i=r.colorAttachments.map(s=>s?.texture?.format??null),n=r.depthStencilAttachment?.texture?.format,o=t;(!ID(o.props.colorAttachmentFormats,i)||o.props.depthStencilAttachmentFormat!==n)&&(o.props.colorAttachmentFormats=i,o.props.depthStencilAttachmentFormat=n,o._setPipelineNeedsUpdate("attachment formats"))}function ID(t,e){if(t===e)return!0;if(!t||!e||t.length!==e.length)return!1;for(let r=0;re.isLoaded)}getSubLayers(){return this.internalState&&this.internalState.subLayers||[]}initializeState(e){}setState(e){super.setState(e),this.setNeedsUpdate()}getPickingInfo({info:e}){let{object:r}=e;return r&&r.__source&&r.__source.parent&&r.__source.parent.id===this.id&&(e.object=r.__source.object,e.index=r.__source.index),e}filterSubLayer(e){return!0}shouldRenderSubLayer(e,r){return r&&r.length}getSubLayerClass(e,r){let{_subLayerProps:i}=this.props;return i&&i[e]&&i[e].type||r}getSubLayerRow(e,r,i){return e.__source={parent:this,object:r,index:i},e}getSubLayerAccessor(e){if(typeof e=="function"){let r={index:-1,data:this.props.data,target:[]};return(i,n)=>i&&i.__source?(r.index=i.__source.index,e(i.__source.object,r)):e(i,n)}return e}getSubLayerProps(e={}){let{opacity:r,pickable:i,visible:n,parameters:o,getPolygonOffset:s,highlightedObjectIndex:a,autoHighlight:c,highlightColor:l,coordinateSystem:f,coordinateOrigin:u,wrapLongitude:d,positionFormat:h,modelMatrix:p,extensions:g,fetch:m,operation:_,_subLayerProps:T}=this.props,y={id:"",updateTriggers:{},opacity:r,pickable:i,visible:n,parameters:o,getPolygonOffset:s,highlightedObjectIndex:a,autoHighlight:c,highlightColor:l,coordinateSystem:f,coordinateOrigin:u,wrapLongitude:d,positionFormat:h,modelMatrix:p,extensions:g,fetch:m,operation:_},x=T&&e.id&&T[e.id],w=x&&x.updateTriggers,b=e.id||"sublayer";if(x){let E=this.props[ct],S=e.type?e.type._propTypes:{};for(let A in x){let C=S[A]||E[A];C&&C.type==="accessor"&&(x[A]=this.getSubLayerAccessor(x[A]))}}Object.assign(y,e,x),y.id=`${this.props.id}-${b}`,y.updateTriggers={all:this.props.updateTriggers?.all,...e.updateTriggers,...w};for(let E of g){let S=E.getSubLayerProps.call(this,E);S&&Object.assign(y,S,{updateTriggers:Object.assign(y.updateTriggers,S.updateTriggers)})}return y}_updateAutoHighlight(e){for(let r of this.getSubLayers())r.updateAutoHighlight(e)}_getAttributeManager(){return null}_postUpdate(e,r){let i=this.internalState.subLayers,n=!i||this.needsUpdate();if(n){let o=this.renderLayers();i=lt(o,Boolean),this.internalState.subLayers=i}ae(OD,this,n,i);for(let o of i)o.parent=this}};Tf.layerName="CompositeLayer";var na=Tf;var bg=Math.PI/180,ND=180/Math.PI;function ZT(t,e=0){let r=Math.min(180,t)*bg;return hr*2*Math.sin(r/2)*Math.pow(2,e)}function QT(t,e=0){let r=t/Math.pow(2,e);return Math.asin(Math.min(1,r/hr/2))*2*ND}var Tg=class extends Es{constructor(e){let{startPanPos:r,...i}=e;i.normalize=!1,super(i),r!==void 0&&(this._state.startPanPos=r)}panStart({pos:e}){let{latitude:r,longitude:i,zoom:n}=this.getViewportProps();return this._getUpdatedState({startPanLngLat:[i,r],startPanPos:e,startZoom:n})}pan({pos:e,startPos:r}){let i=this.getState(),n=i.startPanLngLat||this._unproject(r);if(!n)return this;let o=i.startZoom??this.getViewportProps().zoom,s=i.startPanPos||r,a=[n[0],n[1],o],l=this.makeViewport(this.getViewportProps()).panByPosition(a,e,s);return this._getUpdatedState(l)}panEnd(){return this._getUpdatedState({startPanLngLat:null,startPanPos:null,startZoom:null})}zoom({scale:e}){let i=(this.getState().startZoom||this.getViewportProps().zoom)+Math.log2(e);return this._getUpdatedState({zoom:i})}applyConstraints(e){let{longitude:r,latitude:i,maxBounds:n}=e;if(e.zoom=this._constrainZoom(e.zoom,e),(r<-180||r>180)&&(e.longitude=ps(r+180,360)-180),e.latitude=ce(i,-ze,ze),n&&(e.longitude=ce(e.longitude,n[0][0],n[1][0]),e.latitude=ce(e.latitude,n[0][1],n[1][1])),n){let o=e.zoom-Wt(i),s=n[1][0]-n[0][0],a=n[1][1]-n[0][1];if(a>0&&a0&&s<360){let c=Math.min(QT(e.width/Math.cos(e.latitude*bg),o),s)/2;e.longitude=ce(e.longitude,n[0][0]+c,n[1][0]-c)}}return e.latitude!==i&&(e.zoom+=Wt(e.latitude)-Wt(i)),e}_constrainZoom(e,r){r||(r=this.getViewportProps());let{latitude:i,maxZoom:n,maxBounds:o}=r,{minZoom:s}=r,a=Wt(0),c=Wt(i)-a;if(o!==null&&r.width>0&&r.height>0){let f=o[0][1],u=o[1][1],d=Math.sign(f)===Math.sign(u)?Math.min(Math.abs(f),Math.abs(u)):0,h=ZT(o[1][0]-o[0][0])*Math.cos(d*bg),p=ZT(o[1][1]-o[0][1]);h>0&&(s=Math.max(s,Math.log2(r.width/h)+a)),p>0&&(s=Math.max(s,Math.log2(r.height/p)+a)),s>n&&(s=n)}return ce(e,s+c,n+c)}},oa=class extends Mi{constructor(){super(...arguments),this.ControllerState=Tg,this.transition={transitionDuration:300,transitionInterpolator:new pr(["longitude","latitude","zoom"])},this.dragMode="pan"}setProps(e){super.setProps(e),this.dragRotate=!1,this.touchRotate=!1}};var wf=class extends Ci{constructor(e={}){super(e)}getViewportType(e){return e.zoom>12?Cn:bl}get ControllerType(){return oa}};wf.displayName="GlobeView";var wg=wf;var sa=class{constructor(e){J(e.id,"id is required"),this.id=e.id,this.type="custom",this.renderingMode=e.renderingMode||"3d",this.slot=e.slot,this.beforeId=e.beforeId,this.map=null}onAdd(e,r){this.map=e}render(e,r){this.map&&JT(this.map.__deck,this.map,this,r)}};var Sg="__UNDEFINED__";function Un(t){return t.props.beforeId?`deck-layer-group-before:${t.props.beforeId}`:t.props.slot?`deck-layer-group-slot:${t.props.slot}`:"deck-layer-group-last"}function ew(t,e,r){if(!t||!t.style||!t.style._loaded)return;let i=lt(r,Boolean);if(e!==r){let s=lt(e,Boolean),a=new Set(s.map(l=>Un(l))),c=new Set(i.map(l=>Un(l)));for(let l of a)c.has(l)||t.getLayer(l)&&t.removeLayer(l)}let n={};for(let s of i){let a=Un(s),c=t.getLayer(a);if(c){let l=c.implementation||c;n[a]=l}else{let l=new sa({id:a,slot:s.props.slot,beforeId:s.props.beforeId});n[a]=l,t.addLayer(l,s.props.beforeId)}}let o=t.style._order;for(let[s,a]of Object.entries(n)){let c=a.beforeId||Sg,l=c===Sg?o.length:o.indexOf(c);if(o.indexOf(s)!==l-1){let u=c===Sg?void 0:c;t.moveLayer(s,u)}}}var Di="mapbox",Ag=512,DD=Math.PI/180;function rw({map:t,deck:e}){if(t.__deck)return t.__deck;let r=e.props._customRender,i=e.props.onLoad,n={...e.props,_customRender:()=>{t.triggerRepaint(),r?.("")}};return n.views||(n.views=aa(t)),Object.assign(n,{width:null,height:null,touchAction:"unset",viewState:zn(t)}),e.isInitialized?tw(e,t):n.onLoad=()=>{i?.(),tw(e,t)},e.setProps(n),t.__deck=e,t.on("render",()=>{e.isInitialized&&FD(e,t)}),e}function tw(t,e){let r=()=>{t.isInitialized?BD(t,e):e.off("move",r)};e.on("move",r)}function iw(t){t.__deck?.finalize(),t.__deck=null}function Sf(t,e){let r=e?{depthWriteEnabled:!0,depthCompare:"less-equal",depthBias:0,blend:!0,blendColorSrcFactor:"src-alpha",blendColorDstFactor:"one-minus-src-alpha",blendAlphaSrcFactor:"one",blendAlphaDstFactor:"one-minus-src-alpha",blendColorOperation:"add",blendAlphaOperation:"add"}:{};return Af(t)==="globe"&&(r.cullMode="back"),r}function JT(t,e,r,i){if(!t.isInitialized)return;let{currentViewport:n}=t.userData,o=!1;n||(n=nw(t,e,i),t.userData.currentViewport=n,o=!0),n&&t._drawLayers("mapbox-repaint",{viewports:[n],layerFilter:s=>{if(t.props.layerFilter&&!t.props.layerFilter(s))return!1;let a=s.layer;return a.props.beforeId===r.beforeId&&a.props.slot===r.slot},clearStack:o,clearCanvas:!1})}function Af(t){let e=t.getProjection?.(),r=e?.type||e?.name;if(r==="globe")return"globe";if(r&&r!=="mercator")throw new Error("Unsupported projection");return"mercator"}function aa(t){return Af(t)==="globe"?new wg({id:Di}):new Cs({id:Di})}function zn(t){let{lng:e,lat:r}=t.getCenter(),i={longitude:(e+540)%360-180,latitude:r,zoom:t.getZoom(),bearing:t.getBearing(),pitch:t.getPitch(),padding:t.getPadding(),repeat:t.getRenderWorldCopies()};return t.getTerrain?.()&&LD(t,i),i}function LD(t,e){if(t.getFreeCameraOptions){let{position:r}=t.getFreeCameraOptions();if(!r||r.z===void 0)return;let i=t.transform.height,{longitude:n,latitude:o,pitch:s}=e,a=r.x*Ag,c=(1-r.y)*Ag,l=r.z*Ag,f=xe([n,o]),u=a-f[0],d=c-f[1],h=Math.sqrt(u*u+d*d),p=s*DD,g=1.5*i,m=p<.001?g*Math.cos(p)/l:g*Math.sin(p)/h;e.zoom=Math.log2(m);let _=g*Math.cos(p)/m,T=l-_;e.position=[0,0,T/bi(o)]}else typeof t.transform.elevation=="number"&&(e.position=[0,0,t.transform.elevation])}function nw(t,e,r){let i=zn(e),n=t.getView(Di)||aa(e);r&&(n.props.nearZMultiplier=.2);let o=r?.nearZ??e.transform._nearZ,s=r?.farZ??e.transform._farZ;return Number.isFinite(o)&&(i.nearZ=o/e.transform.height,i.farZ=s/e.transform.height),n.makeViewport({width:t.width,height:t.height,viewState:i})}function FD(t,e){let i=lt(t.props.layers,Boolean).some(a=>a&&!e.getLayer(Un(a))),n=t.getViewports(),o=n.findIndex(a=>a.id===Di),s=n.length>1||o<0;if(i||s){if(o>=0){n=n.slice();let a=nw(t,e);a?n[o]=a:n.splice(o,1)}t._drawLayers("mapbox-repaint",{viewports:n,layerFilter:a=>(!t.props.layerFilter||t.props.layerFilter(a))&&(a.viewport.id!==Di||!e.getLayer(Un(a.layer))),clearCanvas:!1})}else{let a=t.device,c=a?.gl;t.props.onBeforeRender?.({device:a,gl:c}),t.props.onAfterRender?.({device:a,gl:c})}t.userData.currentViewport=null}function BD(t,e){t.setProps({viewState:zn(e)}),t.needsRedraw({clearRedrawFlags:!0})}var Wn=class{constructor(e){this._handleStyleChange=()=>{if(this._resolveLayers(this._map,this._deck,this._props.layers,this._props.layers),!this._map)return;Af(this._map)&&this._deck?.setProps({views:this._getViews(this._map)})},this._updateContainerSize=()=>{if(this._map&&this._container){let{clientWidth:i,clientHeight:n}=this._map.getContainer();Object.assign(this._container.style,{width:`${i}px`,height:`${n}px`})}},this._updateViewState=()=>{let i=this._deck,n=this._map;i&&n&&(i.setProps({views:this._getViews(n),viewState:zn(n)}),i.isInitialized&&i.redraw())},this._handleMouseEvent=i=>{let n=this._deck;if(!n||!n.isInitialized)return;let o={type:i.type,offsetCenter:i.point,srcEvent:i},s=this._lastMouseDownPoint;switch(!i.point&&s&&(o.deltaX=i.originalEvent.clientX-s.clientX,o.deltaY=i.originalEvent.clientY-s.clientY,o.offsetCenter={x:s.x+o.deltaX,y:s.y+o.deltaY}),o.type){case"mousedown":n._onPointerDown(o),this._lastMouseDownPoint={...i.point,clientX:i.originalEvent.clientX,clientY:i.originalEvent.clientY};break;case"dragstart":o.type="panstart",n._onEvent(o);break;case"drag":o.type="panmove",n._onEvent(o);break;case"dragend":o.type="panend",n._onEvent(o);break;case"click":o.tapCount=1,n._onEvent(o);break;case"dblclick":o.type="click",o.tapCount=2,n._onEvent(o);break;case"mousemove":o.type="pointermove",n._onPointerMove(o);break;case"mouseout":o.type="pointerleave",n._onPointerMove(o);break;default:return}};let{interleaved:r=!1}=e;this._interleaved=r,this._props=this.filterProps(e)}filterProps(e){let{interleaved:r=!1,useDevicePixels:i,...n}=e;return!r&&i!==void 0&&(n.useDevicePixels=i),n}setProps(e){this._interleaved&&e.layers&&this._resolveLayers(this._map,this._deck,this._props.layers,e.layers),Object.assign(this._props,this.filterProps(e)),this._deck&&this._map&&this._deck.setProps({...this._props,views:this._getViews(this._map),parameters:{...Sf(this._map,this._interleaved),...this._props.parameters}})}onAdd(e){return this._map=e,this._interleaved?this._onAddInterleaved(e):this._onAddOverlaid(e)}_onAddOverlaid(e){let r=document.createElement("div");return Object.assign(r.style,{position:"absolute",left:0,top:0,textAlign:"initial",pointerEvents:"none"}),this._container=r,this._deck=new Bn({...this._props,parent:r,parameters:{...Sf(e,!1),...this._props.parameters},views:this._getViews(e),viewState:zn(e)}),e.on("resize",this._updateContainerSize),e.on("render",this._updateViewState),e.on("mousedown",this._handleMouseEvent),e.on("dragstart",this._handleMouseEvent),e.on("drag",this._handleMouseEvent),e.on("dragend",this._handleMouseEvent),e.on("mousemove",this._handleMouseEvent),e.on("mouseout",this._handleMouseEvent),e.on("click",this._handleMouseEvent),e.on("dblclick",this._handleMouseEvent),this._updateContainerSize(),r}_onAddInterleaved(e){let r=e.painter.context.gl;return r instanceof WebGLRenderingContext&&F.warn("Incompatible basemap library. See: https://deck.gl/docs/api-reference/mapbox/overview#compatibility")(),this._deck=rw({map:e,deck:new Bn({...this._props,views:this._getViews(e),gl:r,parameters:{...Sf(e,!0),...this._props.parameters}})}),e.on("styledata",this._handleStyleChange),this._resolveLayers(e,this._deck,[],this._props.layers),document.createElement("div")}_resolveLayers(e,r,i,n){ew(e,i,n)}onRemove(){let e=this._map;e&&(this._interleaved?this._onRemoveInterleaved(e):this._onRemoveOverlaid(e)),this._deck=void 0,this._map=void 0,this._container=void 0}_onRemoveOverlaid(e){e.off("resize",this._updateContainerSize),e.off("render",this._updateViewState),e.off("mousedown",this._handleMouseEvent),e.off("dragstart",this._handleMouseEvent),e.off("drag",this._handleMouseEvent),e.off("dragend",this._handleMouseEvent),e.off("mousemove",this._handleMouseEvent),e.off("mouseout",this._handleMouseEvent),e.off("click",this._handleMouseEvent),e.off("dblclick",this._handleMouseEvent),this._deck?.finalize()}_onRemoveInterleaved(e){e.off("styledata",this._handleStyleChange),this._resolveLayers(e,this._deck,this._props.layers,[]),iw(e)}getDefaultPosition(){return"top-left"}pickObject(e){return J(this._deck),this._deck.pickObject(e)}pickMultipleObjects(e){return J(this._deck),this._deck.pickMultipleObjects(e)}pickObjects(e){return J(this._deck),this._deck.pickObjects(e)}finalize(){this._map&&this._map.removeControl(this)}getCanvas(){return this._map?this._interleaved?this._map.getCanvas():this._deck.getCanvas():null}_getViews(e){if(!this._props.views)return aa(e);let r=Array.isArray(this._props.views)?this._props.views:[this._props.views];return r.some(n=>n.id===Di)?this._props.views:[aa(e),...r]}};var ow=`#version 300 es +#define SHADER_NAME animated-flow-lines-layer-fragment-shader + +precision highp float; + +in vec4 vColor; +in float sourceToTarget; +in vec2 uv; + +out vec4 fragColor; + +void main(void) { + geometry.uv = uv; + + fragColor = vec4(vColor.xyz, vColor.w * smoothstep(1.0 - animatedFlowLines.animationTailLength, 1.0, fract(sourceToTarget))); + + DECKGL_FILTER_COLOR(fragColor, geometry); +} +`;var sw=`#version 300 es +#define SHADER_NAME animated-flow-lines-layer-vertex-shader +#define SPEED 0.015 +#define NUM_PARTS 5.0 + +in vec3 positions; +in vec3 instanceSourcePositions; +in vec3 instanceTargetPositions; +in vec3 instanceSourcePositions64Low; +in vec3 instanceTargetPositions64Low; +in vec4 instanceColors; +in vec3 instancePickingColors; +in float instanceWidths; +in float instancePickable; +in float instanceStaggering; + +out vec4 vColor; +out float sourceToTarget; +out vec2 uv; + +// offset vector by strokeWidth pixels +// offset_direction is -1 (left) or 1 (right) +vec2 getExtrusionOffset(vec2 line_clipspace, float offset_direction, float width) { + // normalized direction of the line + vec2 dir_screenspace = normalize(line_clipspace * project.viewportSize); + // rotate by 90 degrees + dir_screenspace = vec2(-dir_screenspace.y, dir_screenspace.x); + + return dir_screenspace * offset_direction * width / 2.0; +} + +void main(void) { + geometry.worldPosition = instanceSourcePositions; + geometry.worldPositionAlt = instanceTargetPositions; + + // Position + vec4 source_commonspace; + vec4 target_commonspace; + vec4 source = project_position_to_clipspace(instanceSourcePositions, instanceSourcePositions64Low, vec3(0.), source_commonspace); + vec4 target = project_position_to_clipspace(instanceTargetPositions, instanceTargetPositions64Low, vec3(0.), target_commonspace); + + float widthPixels = instanceWidths * animatedFlowLines.thicknessUnit; + + + // linear interpolation of source & target to pick right coord + float segmentIndex = positions.x; + vec4 p = mix(source, target, segmentIndex); + geometry.position = mix(source_commonspace, target_commonspace, segmentIndex); + uv = positions.xy; + geometry.uv = uv; + if (instancePickable > 0.5) { + geometry.pickingColor = instancePickingColors; + } + + // extrude + vec3 offset = vec3( + getExtrusionOffset(target.xy - source.xy, positions.y, widthPixels), + 0.0); + DECKGL_FILTER_SIZE(offset, geometry); + gl_Position = p + vec4(project_pixel_size_to_clipspace(offset.xy), 0.0, 0.0); + DECKGL_FILTER_GL_POSITION(gl_Position, geometry); + + // Color + vColor = vec4(instanceColors.rgb, instanceColors.a * layer.opacity); + DECKGL_FILTER_COLOR(vColor, geometry); + + sourceToTarget = positions.x * length(source - target) * NUM_PARTS - animatedFlowLines.currentTime * SPEED + instanceStaggering; +} +`;var aw=`layout(std140) uniform animatedFlowLinesUniforms { + float thicknessUnit; + float animationTailLength; + float currentTime; +} animatedFlowLines; +`,cw={name:"animatedFlowLines",vs:aw,fs:aw,uniformTypes:{thicknessUnit:"f32",animationTailLength:"f32",currentTime:"f32"}};var kD=[0,132,193,255],fw=1800,UD=20,lw=fw/UD,vf=class extends ve{constructor(e){super(e)}getShaders(){return super.getShaders({vs:sw,fs:ow,modules:[Oe,Ne,cw]})}initializeState(){this.getAttributeManager().addInstanced({instanceSourcePositions:{size:3,type:"float64",transition:!0,accessor:"getSourcePosition"},instanceTargetPositions:{size:3,type:"float64",transition:!0,accessor:"getTargetPosition"},instanceColors:{size:4,type:"unorm8",transition:!0,accessor:"getColor",defaultValue:[0,0,0,255]},instanceWidths:{size:1,transition:!0,accessor:"getThickness",defaultValue:1},instanceStaggering:{accessor:"getStaggering",size:1,transition:!1},instancePickable:{accessor:"getPickable",size:1,transition:!1}}),this.setState({model:this._getModel()})}getNeedsRedraw(){return"animation"}updateState(e){super.updateState(e);let{changeFlags:r}=e;(!this.state.model||r.extensionsChanged)&&(this.state.model?.destroy(),this.setState({model:this._getModel()}),this.getAttributeManager().invalidateAll())}draw(){let{thicknessUnit:e=30,animationTailLength:r=.7}=this.props,n=Date.now()/1e3%lw/lw*fw,o=this.state.model;o&&(o.shaderInputs.setProps({animatedFlowLines:{thicknessUnit:e*4,animationTailLength:r,currentTime:n}}),o.draw(this.context.renderPass))}_getModel(){let{id:e}=this.props,r=[0,-1,0,0,1,0,1,-1,0,1,1,0];return new he(this.context.device,{...this.getShaders(),id:e,bufferLayout:this.getAttributeManager().getBufferLayouts(),geometry:new Ae({topology:"triangle-strip",attributes:{positions:{size:3,value:new Float32Array(r)}}}),isInstanced:!0})}};vf.defaultProps={currentTime:0,animationTailLength:.7,getSourcePosition:{type:"accessor",value:t=>[0,0]},getTargetPosition:{type:"accessor",value:t=>[0,0]},getPickable:{type:"accessor",value:t=>1},getStaggering:{type:"accessor",value:(t,{index:e})=>Math.random()},getColor:{type:"accessor",value:kD},getThickness:{type:"accessor",value:1},thicknessUnit:30,parameters:{depthTest:!1}};var uw=vf;var ca=uw;var dw=`layout(std140) uniform flowLinesUniforms { + vec4 outlineColor; + float thicknessUnit; + float outlineThickness; + float drawOutline; + float gap; + float curviness; +} flowLines; +`,Ef={name:"flowLines",vs:dw,fs:dw,uniformTypes:{outlineColor:"vec4",thicknessUnit:"f32",outlineThickness:"f32",drawOutline:"f32",gap:"f32",curviness:"f32"}};var hw=`#version 300 es +#define SHADER_NAME curved-flow-line-layer-fragment-shader + +precision highp float; + +in vec4 vColor; +in vec2 uv; +in vec3 vBarycentrics; +flat in vec3 vEdgeMask; + +out vec4 fragColor; + +void main(void) { + if (vColor.a == 0.0) { + discard; + } + + geometry.uv = uv; + fragColor = vColor; + + if (flowLines.drawOutline > 0.5 && !bool(picking.isActive)) { + vec3 edgeDistancePx = vBarycentrics / max(fwidth(vBarycentrics), vec3(1e-4)); + vec3 maskedDistancePx = mix(vec3(1e6), edgeDistancePx, step(vec3(0.5), vEdgeMask)); + float minBoundaryDistancePx = min( + maskedDistancePx.x, + min(maskedDistancePx.y, maskedDistancePx.z) + ); + float outlineMix = 1.0 - smoothstep( + max(flowLines.outlineThickness - 1.0, 0.0), + flowLines.outlineThickness, + minBoundaryDistancePx + ); + fragColor = mix( + fragColor, + vec4(flowLines.outlineColor.rgb, flowLines.outlineColor.a * fragColor.a), + outlineMix + ); + } + + DECKGL_FILTER_COLOR(fragColor, geometry); +} +`;var pw=.9583333333333334.toFixed(8),gw=`#version 300 es +#define SHADER_NAME curved-flow-line-layer-vertex-shader + +in vec3 positions; +in vec3 barycentrics; +in vec3 edgeMasks; +in vec4 instanceColors; +in float instanceThickness; +in vec3 instanceSourcePositions; +in vec3 instanceTargetPositions; +in vec3 instanceSourcePositions64Low; +in vec3 instanceTargetPositions64Low; +in vec3 instancePickingColors; +in vec2 instanceEndpointOffsets; +in float instancePickable; +in float instanceCurveOffset; + +out vec4 vColor; +out vec2 uv; +out vec3 vBarycentrics; +flat out vec3 vEdgeMask; + +vec3 quadraticBezier(vec3 p0, vec3 p1, vec3 p2, float t) { + float oneMinusT = 1.0 - t; + return + oneMinusT * oneMinusT * p0 + + 2.0 * oneMinusT * t * p1 + + t * t * p2; +} + +vec3 quadraticBezierTangent(vec3 p0, vec3 p1, vec3 p2, float t) { + return 2.0 * (1.0 - t) * (p1 - p0) + 2.0 * t * (p2 - p1); +} + +void main(void) { + geometry.worldPosition = instanceSourcePositions; + geometry.worldPositionAlt = instanceTargetPositions; + + vec4 source_commonspace; + vec4 target_commonspace; + project_position_to_clipspace( + instanceSourcePositions, + instanceSourcePositions64Low, + vec3(0.0), + source_commonspace + ); + project_position_to_clipspace( + instanceTargetPositions, + instanceTargetPositions64Low, + vec3(0.0), + target_commonspace + ); + + vec2 chord = target_commonspace.xy - source_commonspace.xy; + float chordLengthCommon = max(length(chord), 1e-6); + float startTrim = clamp( + project_pixel_size(instanceEndpointOffsets.x) / chordLengthCommon, + 0.0, + 0.35 + ); + float endTrim = 1.0 - clamp( + project_pixel_size(instanceEndpointOffsets.y) / chordLengthCommon, + 0.0, + 0.35 + ); + endTrim = max(startTrim + 0.05, endTrim); + float baseHeadBacktrackT = project_pixel_size( + instanceThickness * 3.0 * flowLines.thicknessUnit + ) / chordLengthCommon; + float availableSpanT = max(endTrim - startTrim, 0.0); + float headBacktrackT = min(baseHeadBacktrackT, availableSpanT * 0.45); + float headScale = baseHeadBacktrackT > 1e-6 + ? clamp(headBacktrackT / baseHeadBacktrackT, 0.0, 1.0) + : 1.0; + // A soft nonlinear fade of the head deformation avoids tiny heads folding + // into themselves while still allowing them to collapse back toward the strip. + float headDeformation = smoothstep(0.0, 1.0, headScale); + float shaftEndTrim = max(startTrim + 0.02, endTrim - headBacktrackT); + + float curveT = positions.x < 1.0 + ? mix(startTrim, shaftEndTrim, positions.x / ${pw}) + : endTrim; + float headWeight = smoothstep(${pw}, 1.0, positions.x); + float tangentT = mix(curveT, endTrim, headWeight); + vec2 curveNormal = normalize(vec2(chord.y, -chord.x)); + if (length(curveNormal) < 1e-6) { + curveNormal = vec2(0.0, 1.0); + } + vec3 control_commonspace = mix( + source_commonspace.xyz, + target_commonspace.xyz, + 0.5 + ); + control_commonspace.xy += curveNormal * project_pixel_size(abs(instanceCurveOffset)) * flowLines.curviness; + + vec3 curvePoint = quadraticBezier( + source_commonspace.xyz, + control_commonspace, + target_commonspace.xyz, + curveT + ); + vec3 tangent = quadraticBezierTangent( + source_commonspace.xyz, + control_commonspace, + target_commonspace.xyz, + tangentT + ); + if (length(tangent.xy) < 1e-6) { + tangent = target_commonspace.xyz - source_commonspace.xyz; + } + + vec2 flowlineDir = normalize(tangent.xy); + vec2 perpendicularDir = vec2(-flowlineDir.y, flowlineDir.x); + float widthScale = mix(1.0, headScale, headWeight); + float lengthScale = mix(1.0, headScale, headWeight); + float shapeY = mix(min(positions.y, 1.0), positions.y, headDeformation); + float shapeZ = positions.z * headDeformation; + float normalDistanceCommon = clamp( + project_pixel_size( + instanceThickness * shapeY * widthScale * flowLines.thicknessUnit + ), + -chordLengthCommon * 0.8, + chordLengthCommon * 0.8 + ); + float tangentDistanceCommon = clamp( + project_pixel_size( + instanceThickness * shapeZ * lengthScale * flowLines.thicknessUnit + ), + -chordLengthCommon * 0.8, + chordLengthCommon * 0.8 + ); + float gapCommon = project_pixel_size(flowLines.gap); + vec3 offsetCommon = vec3( + flowlineDir * tangentDistanceCommon - + perpendicularDir * (normalDistanceCommon + gapCommon), + 0.0 + ); + + geometry.position = vec4(curvePoint, 1.0); + uv = vec2(curveT, positions.y); + geometry.uv = uv; + vBarycentrics = barycentrics; + vEdgeMask = edgeMasks; + if (instancePickable > 0.5) { + geometry.pickingColor = instancePickingColors; + } + + DECKGL_FILTER_SIZE(offsetCommon, geometry); + vec4 position_commonspace = vec4(curvePoint + offsetCommon, 1.0); + gl_Position = project_common_position_to_clipspace(position_commonspace); + DECKGL_FILTER_GL_POSITION(gl_Position, geometry); + + vec4 fillColor = vec4(instanceColors.rgb, instanceColors.a * layer.opacity); + vColor = fillColor; + DECKGL_FILTER_COLOR(vColor, geometry); +} +`;var zD=[0,132,193,255],Rf=24,vg=1-1/Rf,la=class extends ve{getShaders(){return super.getShaders({vs:gw,fs:hw,modules:[Oe,Ne,Ef]})}initializeState(){this.getAttributeManager().addInstanced({instanceSourcePositions:{accessor:"getSourcePosition",size:3,transition:!1,type:"float64"},instanceTargetPositions:{accessor:"getTargetPosition",size:3,transition:!1,type:"float64"},instanceThickness:{accessor:"getThickness",size:1,transition:!1},instanceEndpointOffsets:{accessor:"getEndpointOffsets",size:2,transition:!1},instanceCurveOffset:{accessor:"getCurveOffset",size:1,transition:!1},instanceColors:{accessor:"getColor",size:4,type:"unorm8",transition:!1},instancePickable:{accessor:"getPickable",size:1,transition:!1}}),this.setState({model:this._getModel()})}updateState(e){super.updateState(e);let{changeFlags:r}=e;(!this.state.model||r.extensionsChanged)&&(this.state.model?.destroy(),this.setState({model:this._getModel()}),this.getAttributeManager().invalidateAll())}draw(){let{drawOutline:e=!0,outlineColor:r=[255,255,255,255],outlineThickness:i=1,thicknessUnit:n=12,curviness:o=1}=this.props,s=this.state.model;s&&(s.shaderInputs.setProps({flowLines:{outlineColor:r.map(a=>a/255),thicknessUnit:n*2,outlineThickness:i,drawOutline:e?1:0,gap:.5,curviness:o}}),s.draw(this.context.renderPass))}_getModel(){let{id:e}=this.props,r=WD();return new he(this.context.device,{id:e,...this.getShaders(),bufferLayout:this.getAttributeManager().getBufferLayouts(),geometry:new Ae({topology:"triangle-list",attributes:{positions:{size:3,value:r.positions},barycentrics:{size:3,value:r.barycentrics},edgeMasks:{size:3,value:r.edgeMasks}}}),isInstanced:!0})}};la.layerName="CurvedFlowLinesLayer";la.defaultProps={getSourcePosition:{type:"accessor",value:t=>[0,0]},getTargetPosition:{type:"accessor",value:t=>[0,0]},getColor:{type:"accessor",value:zD},getThickness:{type:"accessor",value:t=>t.count},getPickable:{type:"accessor",value:()=>1},getCurveOffset:{type:"accessor",value:()=>0},drawOutline:!0,thicknessUnit:12,outlineThickness:1,outlineColor:[255,255,255,255],curviness:1,parameters:{depthTest:!1}};var mw=la;function WD(){let t=[],e=[],r=[],i=(n,o,s,a)=>{t.push(...n,...o,...s),e.push(1,0,0,0,1,0,0,0,1),r.push(...a,...a,...a)};for(let n=0;n 0.5 && !bool(picking.isActive)) { + // For barycentric coordinates, each component trends to 0 on one triangle edge. + // Dividing by fwidth converts that into an approximate edge distance in pixels. + vec3 edgeDistancePx = vBarycentrics / max(fwidth(vBarycentrics), vec3(1e-4)); + // Ignore edges that are only part of the internal triangulation by assigning + // them a large sentinel distance, so only true boundary edges contribute. + vec3 maskedDistancePx = mix(vec3(1e6), edgeDistancePx, step(vec3(0.5), vEdgeMask)); + float minBoundaryDistancePx = min( + maskedDistancePx.x, + min(maskedDistancePx.y, maskedDistancePx.z) + ); + // The outline is inset: fragments within 'outlineThickness' pixels of an + // active boundary edge are mixed toward the outline color. + float outlineMix = 1.0 - smoothstep( + max(flowLines.outlineThickness - 1.0, 0.0), + flowLines.outlineThickness, + minBoundaryDistancePx + ); + fragColor = mix( + fragColor, + vec4(flowLines.outlineColor.rgb, flowLines.outlineColor.a * fragColor.a), + outlineMix + ); + } + + DECKGL_FILTER_COLOR(fragColor, geometry); +} +`;var yw=`#version 300 es +#define SHADER_NAME flow-line-layer-vertex-shader + +in vec3 positions; +in vec2 pixelOffsets; +in vec2 outlineOffsetCoefficients; +in vec2 outlineOffsetConstants; +in vec3 barycentrics; +in vec3 edgeMasks; +in vec4 instanceColors; +in float instanceThickness; // 0..0.5 +in vec3 instanceSourcePositions; +in vec3 instanceTargetPositions; +in vec3 instanceSourcePositions64Low; +in vec3 instanceTargetPositions64Low; +in vec3 instancePickingColors; +in vec2 instanceEndpointOffsets; +in float instancePickable; + +out vec4 vColor; +out vec2 uv; +// Interpolated barycentric coordinates let the fragment shader measure distance +// to triangle edges in screen pixels without extra geometry. +out vec3 vBarycentrics; +// The edge mask is constant per triangle and tells the fragment shader which +// barycentric edges are real outline candidates vs internal triangulation seams. +flat out vec3 vEdgeMask; + +void main(void) { + geometry.worldPosition = instanceSourcePositions; + geometry.worldPositionAlt = instanceTargetPositions; + + // Position + vec4 source_commonspace; + vec4 target_commonspace; + project_position_to_clipspace(instanceSourcePositions, instanceSourcePositions64Low, vec3(0.), source_commonspace); + project_position_to_clipspace(instanceTargetPositions, instanceTargetPositions64Low, vec3(0.), target_commonspace); + + // linear interpolation of source & target to pick right coord + float sourceOrTarget = positions.x; + geometry.position = mix(source_commonspace, target_commonspace, sourceOrTarget); + uv = positions.xy; + geometry.uv = uv; + vBarycentrics = barycentrics; + vEdgeMask = edgeMasks; + if (instancePickable > 0.5) { + geometry.pickingColor = instancePickingColors; + } + + // set the clamp limits in pixel size + float lengthCommon = length(target_commonspace - source_commonspace); + vec2 limitedOffsetDistances = clamp( + project_pixel_size(positions.yz) * flowLines.thicknessUnit, + -lengthCommon*.8, lengthCommon*.8 + ); + float startOffsetCommon = project_pixel_size(instanceEndpointOffsets[0]); + float endOffsetCommon = project_pixel_size(instanceEndpointOffsets[1]); + float endpointOffset = mix( + clamp(startOffsetCommon, 0.0, lengthCommon*.2), + -clamp(endOffsetCommon, 0.0, lengthCommon*.2), + positions.x + ); + + vec2 flowlineDir = normalize(target_commonspace.xy - source_commonspace.xy); + vec2 perpendicularDir = vec2(-flowlineDir.y, flowlineDir.x); + vec2 outlinePixelOffset = ( + outlineOffsetCoefficients * flowLines.outlineThickness + + outlineOffsetConstants + ) * flowLines.drawOutline; + vec2 pixelOffsetCommon = project_pixel_size(pixelOffsets + outlinePixelOffset); + float gapCommon = project_pixel_size(flowLines.gap); + vec3 offsetCommon = vec3( + flowlineDir * (instanceThickness * limitedOffsetDistances[1] + pixelOffsetCommon.y + endpointOffset * 1.05) - + perpendicularDir * (instanceThickness * limitedOffsetDistances[0] + gapCommon + pixelOffsetCommon.x), + 0.0 + ); + + DECKGL_FILTER_SIZE(offsetCommon, geometry); + vec4 position_commonspace = mix(source_commonspace, target_commonspace, sourceOrTarget); + vec4 offset_commonspace = vec4(offsetCommon, 0.0); + gl_Position = project_common_position_to_clipspace(position_commonspace + offset_commonspace); + + DECKGL_FILTER_GL_POSITION(gl_Position, geometry); + + vec4 fillColor = vec4(instanceColors.rgb, instanceColors.a * layer.opacity); + vColor = fillColor; + DECKGL_FILTER_COLOR(vColor, geometry); +} +`;var VD=[0,132,193,255],jD=[1,0,0,1,2,-3,1,1,-3,1,0,0,1,1,-3,0,1,0,1,0,0,0,1,0,0,0,0],Cf=.5,$D=new Float32Array(18),HD=new Float32Array([0,2,2,-1,1,-1,0,2,1,-1,1,-1,0,2,1,-1,0,-1]),YD=new Float32Array([-Cf,0,0,0,0,0,-Cf,0,0,0,0,0,-Cf,0,0,0,-Cf,0]),XD=new Float32Array([1,0,0,0,1,0,0,0,1,1,0,0,0,1,0,0,0,1,1,0,0,0,1,0,0,0,1]),GD=new Float32Array([1,0,1,1,0,1,1,0,1,1,0,0,1,0,0,1,0,0,1,1,0,1,1,0,1,1,0]),fa=class extends ve{constructor(e){super(e)}getShaders(){return super.getShaders({vs:yw,fs:_w,modules:[Oe,Ne,Ef]})}initializeState(){this.getAttributeManager().addInstanced({instanceSourcePositions:{accessor:"getSourcePosition",size:3,transition:!1,type:"float64"},instanceTargetPositions:{accessor:"getTargetPosition",size:3,transition:!1,type:"float64"},instanceThickness:{accessor:"getThickness",size:1,transition:!1},instanceEndpointOffsets:{accessor:"getEndpointOffsets",size:2,transition:!1},instanceColors:{accessor:"getColor",size:4,type:"unorm8",transition:!1},instancePickable:{accessor:"getPickable",size:1,transition:!1}}),this.setState({model:this._getModel()})}updateState(e){super.updateState(e);let{changeFlags:r}=e;(!this.state.model||r.extensionsChanged)&&(this.state.model?.destroy(),this.setState({model:this._getModel()}),this.getAttributeManager().invalidateAll())}draw(){let{drawOutline:e=!0,outlineColor:r=[255,255,255,255],outlineThickness:i=1,thicknessUnit:n=12}=this.props,o=this.state.model;o&&(o.shaderInputs.setProps({flowLines:{outlineColor:r.map(s=>s/255),thicknessUnit:n*2,outlineThickness:i,drawOutline:e?1:0,gap:.5,curviness:1}}),o.draw(this.context.renderPass))}_getModel(){let{id:e}=this.props;return new he(this.context.device,{id:e,...this.getShaders(),bufferLayout:this.getAttributeManager().getBufferLayouts(),geometry:new Ae({topology:"triangle-list",attributes:{positions:{size:3,value:new Float32Array(jD)},pixelOffsets:{size:2,value:$D},outlineOffsetCoefficients:{size:2,value:HD},outlineOffsetConstants:{size:2,value:YD},barycentrics:{size:3,value:XD},edgeMasks:{size:3,value:GD}}}),isInstanced:!0})}};fa.layerName="FlowLinesLayer";fa.defaultProps={getSourcePosition:{type:"accessor",value:t=>[0,0]},getTargetPosition:{type:"accessor",value:t=>[0,0]},getColor:{type:"accessor",value:VD},getThickness:{type:"accessor",value:t=>t.count},getPickable:{type:"accessor",value:t=>1},drawOutline:!0,thicknessUnit:12,outlineThickness:1,outlineColor:[255,255,255,255],parameters:{depthTest:!1}};var xw=fa;var jn=xw;var bw=`#version 300 es +#define SHADER_NAME flow-circles-layer-fragment-shader +#define SOFT_OUTLINE 0.05 +#define EPS 0.05 +precision highp float; + +in vec4 vColor; +in vec2 unitPosition; +in float unitInRadius; +in float unitOutRadius; + +out vec4 fragColor; + +float when_gt(float x, float y) { + return max(sign(x - y), 0.0); +} + +void main(void) { + geometry.uv = unitPosition; + float distToCenter = length(unitPosition); + if (distToCenter > 1.0) { + discard; + } + + // See https://stackoverflow.com/questions/47285778 + vec4 ringColor = mix( + flowCircles.emptyColor, vColor, + when_gt(unitInRadius, unitOutRadius) + ); + vec4 outlineColor = mix( + mix(vColor, flowCircles.emptyColor, flowCircles.outlineEmptyMix), + vColor, + when_gt(unitInRadius, unitOutRadius) + ); + + float innerR = min(unitInRadius, unitOutRadius) * (1.0 - SOFT_OUTLINE); + + // Inner circle + float step2 = innerR - 2.0 * EPS; + float step3 = innerR - EPS; + + // Ring + float step4 = innerR; + // float step5 = 1.0 - SOFT_OUTLINE - EPS; + // float step6 = 1.0 - SOFT_OUTLINE; + float step5 = 1.0 - 5.0 * EPS; + float step6 = 1.0; + + fragColor = vColor; + fragColor = mix(fragColor, flowCircles.emptyColor, smoothstep(step2, step3, distToCenter)); + fragColor = mix(fragColor, ringColor, smoothstep(step3, step4, distToCenter)); + fragColor = mix(fragColor, outlineColor, smoothstep(step5, step6, distToCenter)); + fragColor.a = vColor.a; + fragColor.a *= smoothstep(0.0, SOFT_OUTLINE, 1.0 - distToCenter); + DECKGL_FILTER_COLOR(fragColor, geometry); +} +`;var Tw=`#version 300 es +#define SHADER_NAME flow-circles-layer-vertex-shader +#define radiusScale 100 + +in vec3 positions; + +in vec3 instancePositions; +in vec3 instancePositions64Low; +in float instanceInRadius; +in float instanceOutRadius; +in vec4 instanceColors; +in vec3 instancePickingColors; + +out vec4 vColor; +out vec2 unitPosition; +out float unitInRadius; +out float unitOutRadius; + +void main(void) { + geometry.worldPosition = instancePositions; + + float outerRadiusPixels = max(instanceInRadius, instanceOutRadius); + unitInRadius = instanceInRadius / outerRadiusPixels; + unitOutRadius = instanceOutRadius / outerRadiusPixels; + + // position on the containing square in [-1, 1] space + unitPosition = positions.xy; + geometry.uv = unitPosition; + geometry.pickingColor = instancePickingColors; + + // Find the center of the point and add the current vertex + vec3 offset = positions * project_pixel_size(outerRadiusPixels); + DECKGL_FILTER_SIZE(offset, geometry); + gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset, geometry.position); + DECKGL_FILTER_GL_POSITION(gl_Position, geometry); + + // Apply opacity to instance color, or return instance picking color + vColor = vec4(instanceColors.rgb, instanceColors.a * layer.opacity); + DECKGL_FILTER_COLOR(vColor, geometry); +} +`;var ww=`layout(std140) uniform flowCirclesUniforms { + vec4 emptyColor; + float outlineEmptyMix; +} flowCircles; +`,Sw={name:"flowCircles",vs:ww,fs:ww,uniformTypes:{emptyColor:"vec4",outlineEmptyMix:"f32"}};var Aw=[0,0,0,255],vw=[255,255,255,255],Ew=.4,ua=class extends ve{constructor(e){super(e)}getShaders(){return super.getShaders({vs:Tw,fs:bw,modules:[Oe,Ne,Sw]})}initializeState(){this.getAttributeManager().addInstanced({instancePositions:{size:3,type:"float64",fp64:this.use64bitPositions(),transition:!0,accessor:"getPosition"},instanceInRadius:{size:1,transition:!0,accessor:"getInRadius",defaultValue:1},instanceOutRadius:{size:1,transition:!0,accessor:"getOutRadius",defaultValue:1},instanceColors:{size:4,transition:!0,type:"unorm8",accessor:"getColor",defaultValue:Aw}}),this.setState({model:this._getModel()})}updateState(e){super.updateState(e);let{changeFlags:r}=e;(!this.state.model||r.extensionsChanged)&&(this.state.model?.destroy(),this.setState({model:this._getModel()}),this.getAttributeManager().invalidateAll())}draw(){let{emptyColor:e=vw,outlineEmptyMix:r=Ew}=this.props,i=this.state.model;i&&(i.shaderInputs.setProps({flowCircles:{emptyColor:e.map(n=>n/255),outlineEmptyMix:r}}),i.draw(this.context.renderPass))}_getModel(){let{id:e}=this.props,r=[-1,-1,0,1,-1,0,-1,1,0,1,1,0];return new he(this.context.device,{...this.getShaders(),id:e,bufferLayout:this.getAttributeManager().getBufferLayouts(),geometry:new Ae({topology:"triangle-strip",attributes:{positions:{size:3,value:new Float32Array(r)}}}),isInstanced:!0})}};ua.layerName="FlowCirclesLayer";ua.defaultProps={getColor:{type:"accessor",value:Aw},emptyColor:{type:"accessor",value:vw},outlineEmptyMix:{type:"accessor",value:Ew},getPosition:{type:"accessor",value:t=>t.position},getInRadius:{type:"accessor",value:1},getOutRadius:{type:"accessor",value:1},parameters:{depthTest:!1}};var Rw=ua;var da=Rw;var Cw=`layout(std140) uniform iconUniforms { + float sizeScale; + vec2 iconsTextureDim; + float sizeBasis; + float sizeMinPixels; + float sizeMaxPixels; + bool billboard; + highp int sizeUnits; + float alphaCutoff; +} icon; +`,Pw={name:"icon",vs:Cw,fs:Cw,uniformTypes:{sizeScale:"f32",iconsTextureDim:"vec2",sizeBasis:"f32",sizeMinPixels:"f32",sizeMaxPixels:"f32",billboard:"f32",sizeUnits:"i32",alphaCutoff:"f32"}};var Mw=`#version 300 es +#define SHADER_NAME icon-layer-vertex-shader +in vec2 positions; +in vec3 instancePositions; +in vec3 instancePositions64Low; +in float instanceSizes; +in float instanceAngles; +in vec4 instanceColors; +in vec3 instancePickingColors; +in vec4 instanceIconFrames; +in float instanceColorModes; +in vec2 instanceOffsets; +in vec2 instancePixelOffset; +out float vColorMode; +out vec4 vColor; +out vec2 vTextureCoords; +out vec2 uv; +vec2 rotate_by_angle(vec2 vertex, float angle) { +float angle_radian = angle * PI / 180.0; +float cos_angle = cos(angle_radian); +float sin_angle = sin(angle_radian); +mat2 rotationMatrix = mat2(cos_angle, -sin_angle, sin_angle, cos_angle); +return rotationMatrix * vertex; +} +void main(void) { +geometry.worldPosition = instancePositions; +geometry.uv = positions; +geometry.pickingColor = instancePickingColors; +uv = positions; +vec2 iconSize = instanceIconFrames.zw; +float sizePixels = clamp( +project_size_to_pixel(instanceSizes * icon.sizeScale, icon.sizeUnits), +icon.sizeMinPixels, icon.sizeMaxPixels +); +float iconConstraint = icon.sizeBasis == 0.0 ? iconSize.x : iconSize.y; +float instanceScale = iconConstraint == 0.0 ? 0.0 : sizePixels / iconConstraint; +vec2 pixelOffset = positions / 2.0 * iconSize + instanceOffsets; +pixelOffset = rotate_by_angle(pixelOffset, instanceAngles) * instanceScale; +pixelOffset += instancePixelOffset; +pixelOffset.y *= -1.0; +if (icon.billboard) { +gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0), geometry.position); +DECKGL_FILTER_GL_POSITION(gl_Position, geometry); +vec3 offset = vec3(pixelOffset, 0.0); +DECKGL_FILTER_SIZE(offset, geometry); +gl_Position.xy += project_pixel_size_to_clipspace(offset.xy); +} else { +vec3 offset_common = vec3(project_pixel_size(pixelOffset), 0.0); +DECKGL_FILTER_SIZE(offset_common, geometry); +gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset_common, geometry.position); +DECKGL_FILTER_GL_POSITION(gl_Position, geometry); +} +vTextureCoords = mix( +instanceIconFrames.xy, +instanceIconFrames.xy + iconSize, +(positions.xy + 1.0) / 2.0 +) / icon.iconsTextureDim; +vColor = instanceColors; +DECKGL_FILTER_COLOR(vColor, geometry); +vColorMode = instanceColorModes; +} +`;var Iw=`#version 300 es +#define SHADER_NAME icon-layer-fragment-shader +precision highp float; +uniform sampler2D iconsTexture; +in float vColorMode; +in vec4 vColor; +in vec2 vTextureCoords; +in vec2 uv; +out vec4 fragColor; +void main(void) { +geometry.uv = uv; +vec4 texColor = texture(iconsTexture, vTextureCoords); +vec3 color = mix(texColor.rgb, vColor.rgb, vColorMode); +float a = texColor.a * layer.opacity * vColor.a; +if (a < icon.alphaCutoff) { +discard; +} +fragColor = vec4(color, a); +DECKGL_FILTER_COLOR(fragColor, geometry); +} +`;var Ow=`struct IconUniforms { + sizeScale: f32, + iconsTextureDim: vec2, + sizeBasis: f32, + sizeMinPixels: f32, + sizeMaxPixels: f32, + billboard: i32, + sizeUnits: i32, + alphaCutoff: f32 +}; + +@group(0) @binding(auto) var icon: IconUniforms; +@group(0) @binding(auto) var iconsTexture : texture_2d; +@group(0) @binding(auto) var iconsTextureSampler : sampler; + +fn rotate_by_angle(vertex: vec2, angle_deg: f32) -> vec2 { + let angle_radian = angle_deg * PI / 180.0; + let c = cos(angle_radian); + let s = sin(angle_radian); + let rotation = mat2x2(vec2(c, s), vec2(-s, c)); + return rotation * vertex; +} + +struct Attributes { + @location(0) positions: vec2, + + @location(1) instancePositions: vec3, + @location(2) instancePositions64Low: vec3, + @location(3) instanceSizes: f32, + @location(4) instanceAngles: f32, + @location(5) instanceColors: vec4, + @location(6) instancePickingColors: vec3, + @location(7) instanceIconFrames: vec4, + @location(8) instanceColorModes: f32, + @location(9) instanceOffsets: vec2, + @location(10) instancePixelOffset: vec2, +}; + +struct Varyings { + @builtin(position) position: vec4, + + @location(0) vColorMode: f32, + @location(1) vColor: vec4, + @location(2) vTextureCoords: vec2, + @location(3) uv: vec2, + @location(4) pickingColor: vec3, +}; + +@vertex +fn vertexMain(inp: Attributes) -> Varyings { + // write geometry fields used by filters + FS + geometry.worldPosition = inp.instancePositions; + geometry.uv = inp.positions; + geometry.pickingColor = inp.instancePickingColors; + + var outp: Varyings; + outp.uv = inp.positions; + + let iconSize = inp.instanceIconFrames.zw; + + // convert size in meters to pixels, then clamp + let sizePixels = clamp( + project_unit_size_to_pixel(inp.instanceSizes * icon.sizeScale, icon.sizeUnits), + icon.sizeMinPixels, icon.sizeMaxPixels + ); + + // scale icon height to match instanceSize + let iconConstraint = select(iconSize.y, iconSize.x, icon.sizeBasis == 0.0); + let instanceScale = select(sizePixels / iconConstraint, 0.0, iconConstraint == 0.0); + + // scale and rotate vertex in "pixel" units; then add per-instance pixel offset + var pixelOffset = inp.positions / 2.0 * iconSize + inp.instanceOffsets; + pixelOffset = rotate_by_angle(pixelOffset, inp.instanceAngles) * instanceScale; + pixelOffset = pixelOffset + inp.instancePixelOffset; + pixelOffset.y = pixelOffset.y * -1.0; + + if (icon.billboard != 0) { + var pos = project_position_to_clipspace(inp.instancePositions, inp.instancePositions64Low, vec3(0.0)); // TODO, &geometry.position); + // DECKGL_FILTER_GL_POSITION(pos, geometry); + + var offset = vec3(pixelOffset, 0.0); + // DECKGL_FILTER_SIZE(offset, geometry); + let clipOffset = project_pixel_size_to_clipspace(offset.xy); + pos = vec4(pos.x + clipOffset.x, pos.y + clipOffset.y, pos.z, pos.w); + outp.position = pos; + } else { + var offset_common = vec3(project_pixel_size_vec2(pixelOffset), 0.0); + // DECKGL_FILTER_SIZE(offset_common, geometry); + var pos = project_position_to_clipspace(inp.instancePositions, inp.instancePositions64Low, offset_common); // TODO, &geometry.position); + // DECKGL_FILTER_GL_POSITION(pos, geometry); + outp.position = pos; + } + + let uvMix = (inp.positions.xy + vec2(1.0, 1.0)) * 0.5; + outp.vTextureCoords = mix(inp.instanceIconFrames.xy, inp.instanceIconFrames.xy + iconSize, uvMix) / icon.iconsTextureDim; + + outp.vColor = inp.instanceColors; + // DECKGL_FILTER_COLOR(outp.vColor, geometry); + + outp.vColorMode = inp.instanceColorModes; + outp.pickingColor = inp.instancePickingColors; + + return outp; +} + +@fragment +fn fragmentMain(inp: Varyings) -> @location(0) vec4 { + // expose to deck.gl filter hooks + geometry.uv = inp.uv; + + let texColor = textureSample(iconsTexture, iconsTextureSampler, inp.vTextureCoords); + + // if colorMode == 0, use pixel color from the texture + // if colorMode == 1 (or picking), use texture as transparency mask + let rgb = mix(texColor.rgb, inp.vColor.rgb, inp.vColorMode); + let a = texColor.a * layer.opacity * inp.vColor.a; + + if (a < icon.alphaCutoff) { + discard; + } + + if (picking.isActive > 0.5) { + if (!picking_isColorValid(inp.pickingColor)) { + discard; + } + return vec4(inp.pickingColor, 1.0); + } + + var fragColor = deckgl_premultiplied_alpha(vec4(rgb, a)); + + if (picking.isHighlightActive > 0.5) { + let highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor); + if (picking_isColorZero(abs(inp.pickingColor - highlightedObjectColor))) { + let highLightAlpha = picking.highlightColor.a; + let blendedAlpha = highLightAlpha + fragColor.a * (1.0 - highLightAlpha); + if (blendedAlpha > 0.0) { + let highLightRatio = highLightAlpha / blendedAlpha; + fragColor = vec4( + mix(fragColor.rgb, picking.highlightColor.rgb, highLightRatio), + blendedAlpha + ); + } else { + fragColor = vec4(fragColor.rgb, 0.0); + } + } + } + + return fragColor; +} +`;var qD=1024,KD=4,Nw=()=>{},Dw={minFilter:"linear",mipmapFilter:"linear",magFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"},ZD={x:0,y:0,width:0,height:0};function QD(t){return Math.pow(2,Math.ceil(Math.log2(t)))}function JD(t,e,r,i){let n=Math.min(r/e.width,i/e.height),o=Math.floor(e.width*n),s=Math.floor(e.height*n);return n===1?{image:e,width:o,height:s}:(t.canvas.height=s,t.canvas.width=o,t.clearRect(0,0,o,s),t.drawImage(e,0,0,e.width,e.height,0,0,o,s),{image:t.canvas,width:o,height:s})}function ha(t){return t&&(t.id||t.url)}function Fw(t){let{device:e}=t;e.type==="webgl"?t.generateMipmapsWebGL():e.type==="webgpu"&&e.generateMipmapsWebGPU(t)}function eL(t,e,r,i){let{width:n,height:o,device:s}=t,a=s.createTexture({format:"rgba8unorm",width:e,height:r,sampler:i,mipLevels:s.getMipLevelCount(e,r)}),c=s.createCommandEncoder();c.copyTextureToTexture({sourceTexture:t,destinationTexture:a,width:n,height:o});let l=c.finish();return s.submit(l),Fw(a),t.destroy(),a}function Lw(t,e,r){for(let i=0;is&&(Lw(r,a,n),i=0,n=o+n+e,o=0,a=[]),a.push({icon:l,xOffset:i}),i=i+d+e,o=Math.max(o,u)}}return a.length>0&&Lw(r,a,n),{mapping:r,rowHeight:o,xOffset:i,yOffset:n,canvasWidth:s,canvasHeight:QD(o+n+e)}}function rL(t,e,r){if(!t||!e)return null;r=r||{};let i={},{iterable:n,objectInfo:o}=mr(t);for(let s of n){o.index++;let a=e(s,o),c=ha(a);if(!a)throw new Error("Icon is missing.");if(!a.url)throw new Error("Icon url is missing.");!i[c]&&(!r[c]||a.url!==r[c].url)&&(i[c]={...a,source:s,sourceIndex:o.index})}return i}var pa=class{constructor(e,{onUpdate:r=Nw,onError:i=Nw}){this._loadOptions=null,this._texture=null,this._externalTexture=null,this._mapping={},this._samplerParameters=null,this._pendingCount=0,this._autoPacking=!1,this._xOffset=0,this._yOffset=0,this._rowHeight=0,this._buffer=KD,this._canvasWidth=qD,this._canvasHeight=0,this._canvas=null,this.device=e,this.onUpdate=r,this.onError=i}finalize(){this._texture?.delete()}getTexture(){return this._texture||this._externalTexture}getIconMapping(e){let r=this._autoPacking?ha(e):e;return this._mapping[r]||ZD}setProps({loadOptions:e,autoPacking:r,iconAtlas:i,iconMapping:n,textureParameters:o}){e&&(this._loadOptions=e),r!==void 0&&(this._autoPacking=r),n&&(this._mapping=n),i&&(this._texture?.delete(),this._texture=null,this._externalTexture=i),o&&(this._samplerParameters=o)}get isLoaded(){return this._pendingCount===0}packIcons(e,r){if(!this._autoPacking||typeof document>"u")return;let i=Object.values(rL(e,r,this._mapping)||{});if(i.length>0){let{mapping:n,xOffset:o,yOffset:s,rowHeight:a,canvasHeight:c}=tL({icons:i,buffer:this._buffer,canvasWidth:this._canvasWidth,mapping:this._mapping,rowHeight:this._rowHeight,xOffset:this._xOffset,yOffset:this._yOffset});this._rowHeight=a,this._mapping=n,this._xOffset=o,this._yOffset=s,this._canvasHeight=c,this._texture||(this._texture=this.device.createTexture({format:"rgba8unorm",data:null,width:this._canvasWidth,height:this._canvasHeight,sampler:this._samplerParameters||Dw,mipLevels:this.device.getMipLevelCount(this._canvasWidth,this._canvasHeight)})),this._texture.height!==this._canvasHeight&&(this._texture=eL(this._texture,this._canvasWidth,this._canvasHeight,this._samplerParameters||Dw)),this.onUpdate(!0),this._canvas=this._canvas||document.createElement("canvas"),this._loadIcons(i)}}_loadIcons(e){let r=this._canvas.getContext("2d",{willReadFrequently:!0});for(let i of e)this._pendingCount++,Mr(i.url,this._loadOptions).then(n=>{let o=ha(i),s=this._mapping[o],{x:a,y:c,width:l,height:f}=s,{image:u,width:d,height:h}=JD(r,n,l,f),p=a+(l-d)/2,g=c+(f-h)/2;this._texture?.copyExternalImage({image:u,x:p,y:g,width:d,height:h}),s.x=p,s.y=g,s.width=d,s.height=h,this._texture&&Fw(this._texture),this.onUpdate(d!==l||h!==f)}).catch(n=>{this.onError({url:i.url,source:i.source,sourceIndex:i.sourceIndex,loadOptions:this._loadOptions,error:n})}).finally(()=>{this._pendingCount--})}};var Bw=[0,0,0,255],iL={iconAtlas:{type:"image",value:null,async:!0},iconMapping:{type:"object",value:{},async:!0},sizeScale:{type:"number",value:1,min:0},billboard:!0,sizeUnits:"pixels",sizeBasis:"height",sizeMinPixels:{type:"number",min:0,value:0},sizeMaxPixels:{type:"number",min:0,value:Number.MAX_SAFE_INTEGER},alphaCutoff:{type:"number",value:.05,min:0,max:1},getPosition:{type:"accessor",value:t=>t.position},getIcon:{type:"accessor",value:t=>t.icon},getColor:{type:"accessor",value:Bw},getSize:{type:"accessor",value:1},getAngle:{type:"accessor",value:0},getPixelOffset:{type:"accessor",value:[0,0]},onIconError:{type:"function",value:null,optional:!0},textureParameters:{type:"object",ignore:!0,value:null}},ga=class extends ve{getShaders(){return super.getShaders({vs:Mw,fs:Iw,source:Ow,modules:[Oe,mn,Ne,Pw]})}initializeState(){this.state={iconManager:new pa(this.context.device,{onUpdate:this._onUpdate.bind(this),onError:this._onError.bind(this)})},this.getAttributeManager().addInstanced({instancePositions:{size:3,type:"float64",fp64:this.use64bitPositions(),transition:!0,accessor:"getPosition"},instanceSizes:{size:1,transition:!0,accessor:"getSize",defaultValue:1},instanceIconDefs:{size:7,accessor:"getIcon",transform:this.getInstanceIconDef,shaderAttributes:{instanceOffsets:{size:2,elementOffset:0},instanceIconFrames:{size:4,elementOffset:2},instanceColorModes:{size:1,elementOffset:6}}},instanceColors:{size:this.props.colorFormat.length,type:"unorm8",transition:!0,accessor:"getColor",defaultValue:Bw},instanceAngles:{size:1,transition:!0,accessor:"getAngle"},instancePixelOffset:{size:2,transition:!0,accessor:"getPixelOffset"}})}updateState(e){super.updateState(e);let{props:r,oldProps:i,changeFlags:n}=e,o=this.getAttributeManager(),{iconAtlas:s,iconMapping:a,data:c,getIcon:l,textureParameters:f}=r,{iconManager:u}=this.state;if(typeof s=="string")return;let d=s||this.internalState.isAsyncPropLoading("iconAtlas");u.setProps({loadOptions:r.loadOptions,autoPacking:!d,iconAtlas:s,iconMapping:d?a:null,textureParameters:f}),d?i.iconMapping!==r.iconMapping&&o.invalidate("getIcon"):(n.dataChanged||n.updateTriggersChanged&&(n.updateTriggersChanged.all||n.updateTriggersChanged.getIcon))&&u.packIcons(c,l),n.extensionsChanged&&(this.state.model?.destroy(),this.state.model=this._getModel(),o.invalidateAll())}get isLoaded(){return super.isLoaded&&this.state.iconManager.isLoaded}finalizeState(e){super.finalizeState(e),this.state.iconManager.finalize()}draw({uniforms:e}){let{sizeScale:r,sizeBasis:i,sizeMinPixels:n,sizeMaxPixels:o,sizeUnits:s,billboard:a,alphaCutoff:c}=this.props,{iconManager:l}=this.state,f=l.getTexture();if(f){let u=this.state.model,d={iconsTexture:f,iconsTextureDim:[f.width,f.height],sizeUnits:je[s],sizeScale:r,sizeBasis:i==="height"?1:0,sizeMinPixels:n,sizeMaxPixels:o,billboard:a,alphaCutoff:c};u.shaderInputs.setProps({icon:d}),u.draw(this.context.renderPass)}}_getModel(){let e=[-1,-1,1,-1,-1,1,1,1];return new he(this.context.device,{...this.getShaders(),id:this.props.id,bufferLayout:this.getAttributeManager().getBufferLayouts(),geometry:new Ae({topology:"triangle-strip",attributes:{positions:{size:2,value:new Float32Array(e)}}}),isInstanced:!0})}_onUpdate(e){e?(this.getAttributeManager()?.invalidate("getIcon"),this.setNeedsUpdate()):this.setNeedsRedraw()}_onError(e){let r=this.getCurrentLayer()?.props.onIconError;r?r(e):F.error(e.error.message)()}getInstanceIconDef(e){let{x:r,y:i,width:n,height:o,mask:s,anchorX:a=n/2,anchorY:c=o/2}=this.state.iconManager.getIconMapping(e);return[n/2-a,o/2-c,r,i,n,o,s?1:0]}};ga.defaultProps=iL;ga.layerName="IconLayer";var kw=ga;var Uw=`layout(std140) uniform scatterplotUniforms { + float radiusScale; + float radiusMinPixels; + float radiusMaxPixels; + float lineWidthScale; + float lineWidthMinPixels; + float lineWidthMaxPixels; + float stroked; + float filled; + bool antialiasing; + bool billboard; + highp int radiusUnits; + highp int lineWidthUnits; +} scatterplot; +`,zw={name:"scatterplot",vs:Uw,fs:Uw,source:"",uniformTypes:{radiusScale:"f32",radiusMinPixels:"f32",radiusMaxPixels:"f32",lineWidthScale:"f32",lineWidthMinPixels:"f32",lineWidthMaxPixels:"f32",stroked:"f32",filled:"f32",antialiasing:"f32",billboard:"f32",radiusUnits:"i32",lineWidthUnits:"i32"}};var Ww=`#version 300 es +#define SHADER_NAME scatterplot-layer-vertex-shader +in vec3 positions; +in vec3 instancePositions; +in vec3 instancePositions64Low; +in float instanceRadius; +in float instanceLineWidths; +in vec4 instanceFillColors; +in vec4 instanceLineColors; +in vec3 instancePickingColors; +out vec4 vFillColor; +out vec4 vLineColor; +out vec2 unitPosition; +out float innerUnitRadius; +out float outerRadiusPixels; +void main(void) { +geometry.worldPosition = instancePositions; +outerRadiusPixels = clamp( +project_size_to_pixel(scatterplot.radiusScale * instanceRadius, scatterplot.radiusUnits), +scatterplot.radiusMinPixels, scatterplot.radiusMaxPixels +); +float lineWidthPixels = clamp( +project_size_to_pixel(scatterplot.lineWidthScale * instanceLineWidths, scatterplot.lineWidthUnits), +scatterplot.lineWidthMinPixels, scatterplot.lineWidthMaxPixels +); +outerRadiusPixels += scatterplot.stroked * lineWidthPixels / 2.0; +float edgePadding = scatterplot.antialiasing ? (outerRadiusPixels + SMOOTH_EDGE_RADIUS) / outerRadiusPixels : 1.0; +unitPosition = edgePadding * positions.xy; +geometry.uv = unitPosition; +geometry.pickingColor = instancePickingColors; +innerUnitRadius = 1.0 - scatterplot.stroked * lineWidthPixels / outerRadiusPixels; +if (scatterplot.billboard) { +gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0), geometry.position); +DECKGL_FILTER_GL_POSITION(gl_Position, geometry); +vec3 offset = edgePadding * positions * outerRadiusPixels; +DECKGL_FILTER_SIZE(offset, geometry); +gl_Position.xy += project_pixel_size_to_clipspace(offset.xy); +} else { +vec3 offset = edgePadding * positions * project_pixel_size(outerRadiusPixels); +DECKGL_FILTER_SIZE(offset, geometry); +gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset, geometry.position); +DECKGL_FILTER_GL_POSITION(gl_Position, geometry); +} +vFillColor = vec4(instanceFillColors.rgb, instanceFillColors.a * layer.opacity); +DECKGL_FILTER_COLOR(vFillColor, geometry); +vLineColor = vec4(instanceLineColors.rgb, instanceLineColors.a * layer.opacity); +DECKGL_FILTER_COLOR(vLineColor, geometry); +} +`;var Vw=`#version 300 es +#define SHADER_NAME scatterplot-layer-fragment-shader +precision highp float; +in vec4 vFillColor; +in vec4 vLineColor; +in vec2 unitPosition; +in float innerUnitRadius; +in float outerRadiusPixels; +out vec4 fragColor; +void main(void) { +geometry.uv = unitPosition; +float distToCenter = length(unitPosition) * outerRadiusPixels; +float inCircle = scatterplot.antialiasing ? +smoothedge(distToCenter, outerRadiusPixels) : +step(distToCenter, outerRadiusPixels); +if (inCircle == 0.0) { +discard; +} +if (scatterplot.stroked > 0.5) { +float isLine = scatterplot.antialiasing ? +smoothedge(innerUnitRadius * outerRadiusPixels, distToCenter) : +step(innerUnitRadius * outerRadiusPixels, distToCenter); +if (scatterplot.filled > 0.5) { +fragColor = mix(vFillColor, vLineColor, isLine); +} else { +if (isLine == 0.0) { +discard; +} +fragColor = vec4(vLineColor.rgb, vLineColor.a * isLine); +} +} else if (scatterplot.filled < 0.5) { +discard; +} else { +fragColor = vFillColor; +} +fragColor.a *= inCircle; +DECKGL_FILTER_COLOR(fragColor, geometry); +} +`;var jw=`// Main shaders + +struct ScatterplotUniforms { + radiusScale: f32, + radiusMinPixels: f32, + radiusMaxPixels: f32, + lineWidthScale: f32, + lineWidthMinPixels: f32, + lineWidthMaxPixels: f32, + stroked: f32, + filled: i32, + antialiasing: i32, + billboard: i32, + radiusUnits: i32, + lineWidthUnits: i32, +}; + +struct ConstantAttributeUniforms { + instancePositions: vec3, + instancePositions64Low: vec3, + instanceRadius: f32, + instanceLineWidths: f32, + instanceFillColors: vec4, + instanceLineColors: vec4, + instancePickingColors: vec3, + + instancePositionsConstant: i32, + instancePositions64LowConstant: i32, + instanceRadiusConstant: i32, + instanceLineWidthsConstant: i32, + instanceFillColorsConstant: i32, + instanceLineColorsConstant: i32, + instancePickingColorsConstant: i32 +}; + +@group(0) @binding(0) var scatterplot: ScatterplotUniforms; + +struct ConstantAttributes { + instancePositions: vec3, + instancePositions64Low: vec3, + instanceRadius: f32, + instanceLineWidths: f32, + instanceFillColors: vec4, + instanceLineColors: vec4, + instancePickingColors: vec3 +}; + +const constants = ConstantAttributes( + vec3(0.0), + vec3(0.0), + 0.0, + 0.0, + vec4(0.0, 0.0, 0.0, 1.0), + vec4(0.0, 0.0, 0.0, 1.0), + vec3(0.0) +); + +struct Attributes { + @builtin(instance_index) instanceIndex : u32, + @builtin(vertex_index) vertexIndex : u32, + @location(0) positions: vec3, + @location(1) instancePositions: vec3, + @location(2) instancePositions64Low: vec3, + @location(3) instanceRadius: f32, + @location(4) instanceLineWidths: f32, + @location(5) instanceFillColors: vec4, + @location(6) instanceLineColors: vec4, + @location(7) instancePickingColors: vec3, +}; + +struct Varyings { + @builtin(position) position: vec4, + @location(0) vFillColor: vec4, + @location(1) vLineColor: vec4, + @location(2) unitPosition: vec2, + @location(3) innerUnitRadius: f32, + @location(4) outerRadiusPixels: f32, + @location(5) pickingColor: vec3, +}; + +@vertex +fn vertexMain(attributes: Attributes) -> Varyings { + var varyings: Varyings; + + // Draw an inline geometry constant array clip space triangle to verify that rendering works. + // var positions = array, 3>(vec2(0.0, 0.5), vec2(-0.5, -0.5), vec2(0.5, -0.5)); + // if (attributes.instanceIndex == 0) { + // varyings.position = vec4(positions[attributes.vertexIndex], 0.0, 1.0); + // return varyings; + // } + + geometry.worldPosition = attributes.instancePositions; + + // Multiply out radius and clamp to limits + varyings.outerRadiusPixels = clamp( + project_unit_size_to_pixel(scatterplot.radiusScale * attributes.instanceRadius, scatterplot.radiusUnits), + scatterplot.radiusMinPixels, scatterplot.radiusMaxPixels + ); + + // Multiply out line width and clamp to limits + let lineWidthPixels = clamp( + project_unit_size_to_pixel(scatterplot.lineWidthScale * attributes.instanceLineWidths, scatterplot.lineWidthUnits), + scatterplot.lineWidthMinPixels, scatterplot.lineWidthMaxPixels + ); + + // outer radius needs to offset by half stroke width + varyings.outerRadiusPixels += scatterplot.stroked * lineWidthPixels / 2.0; + // Expand geometry to accommodate edge smoothing + let edgePadding = select( + (varyings.outerRadiusPixels + SMOOTH_EDGE_RADIUS) / varyings.outerRadiusPixels, + 1.0, + scatterplot.antialiasing != 0 + ); + + // position on the containing square in [-1, 1] space + varyings.unitPosition = edgePadding * attributes.positions.xy; + geometry.uv = varyings.unitPosition; + geometry.pickingColor = attributes.instancePickingColors; + + varyings.innerUnitRadius = 1.0 - scatterplot.stroked * lineWidthPixels / varyings.outerRadiusPixels; + + if (scatterplot.billboard != 0) { + varyings.position = project_position_to_clipspace(attributes.instancePositions, attributes.instancePositions64Low, vec3(0.0)); // TODO , geometry.position); + // DECKGL_FILTER_GL_POSITION(varyings.position, geometry); + let offset = attributes.positions; // * edgePadding * varyings.outerRadiusPixels; + // DECKGL_FILTER_SIZE(offset, geometry); + let clipPixels = project_pixel_size_to_clipspace(offset.xy); + varyings.position.x = clipPixels.x; + varyings.position.y = clipPixels.y; + } else { + let offset = edgePadding * attributes.positions * project_pixel_size_float(varyings.outerRadiusPixels); + // DECKGL_FILTER_SIZE(offset, geometry); + varyings.position = project_position_to_clipspace(attributes.instancePositions, attributes.instancePositions64Low, offset); // TODO , geometry.position); + // DECKGL_FILTER_GL_POSITION(varyings.position, geometry); + } + + // Apply opacity to instance color, or return instance picking color + varyings.vFillColor = vec4(attributes.instanceFillColors.rgb, attributes.instanceFillColors.a * layer.opacity); + // DECKGL_FILTER_COLOR(varyings.vFillColor, geometry); + varyings.vLineColor = vec4(attributes.instanceLineColors.rgb, attributes.instanceLineColors.a * layer.opacity); + // DECKGL_FILTER_COLOR(varyings.vLineColor, geometry); + varyings.pickingColor = attributes.instancePickingColors; + + return varyings; +} + +@fragment +fn fragmentMain(varyings: Varyings) -> @location(0) vec4 { + // var geometry: Geometry; + // geometry.uv = unitPosition; + + let distToCenter = length(varyings.unitPosition) * varyings.outerRadiusPixels; + let inCircle = select( + smoothedge(distToCenter, varyings.outerRadiusPixels), + step(distToCenter, varyings.outerRadiusPixels), + scatterplot.antialiasing != 0 + ); + + if (inCircle == 0.0) { + discard; + } + + var fragColor: vec4; + + if (scatterplot.stroked != 0) { + let isLine = select( + smoothedge(varyings.innerUnitRadius * varyings.outerRadiusPixels, distToCenter), + step(varyings.innerUnitRadius * varyings.outerRadiusPixels, distToCenter), + scatterplot.antialiasing != 0 + ); + + if (scatterplot.filled != 0) { + fragColor = mix(varyings.vFillColor, varyings.vLineColor, isLine); + } else { + if (isLine == 0.0) { + discard; + } + fragColor = vec4(varyings.vLineColor.rgb, varyings.vLineColor.a * isLine); + } + } else if (scatterplot.filled == 0) { + discard; + } else { + fragColor = varyings.vFillColor; + } + + fragColor.a *= inCircle; + + if (picking.isActive > 0.5) { + if (!picking_isColorValid(varyings.pickingColor)) { + discard; + } + return vec4(varyings.pickingColor, 1.0); + } + + if (picking.isHighlightActive > 0.5) { + let highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor); + if (picking_isColorZero(abs(varyings.pickingColor - highlightedObjectColor))) { + let highLightAlpha = picking.highlightColor.a; + let blendedAlpha = highLightAlpha + fragColor.a * (1.0 - highLightAlpha); + if (blendedAlpha > 0.0) { + let highLightRatio = highLightAlpha / blendedAlpha; + fragColor = vec4( + mix(fragColor.rgb, picking.highlightColor.rgb, highLightRatio), + blendedAlpha + ); + } else { + fragColor = vec4(fragColor.rgb, 0.0); + } + } + } + + // Apply premultiplied alpha as required by transparent canvas + fragColor = deckgl_premultiplied_alpha(fragColor); + + return fragColor; + // return vec4(0, 0, 1, 1); +} +`;var $w=[0,0,0,255],nL={radiusUnits:"meters",radiusScale:{type:"number",min:0,value:1},radiusMinPixels:{type:"number",min:0,value:0},radiusMaxPixels:{type:"number",min:0,value:Number.MAX_SAFE_INTEGER},lineWidthUnits:"meters",lineWidthScale:{type:"number",min:0,value:1},lineWidthMinPixels:{type:"number",min:0,value:0},lineWidthMaxPixels:{type:"number",min:0,value:Number.MAX_SAFE_INTEGER},stroked:!1,filled:!0,billboard:!1,antialiasing:!0,getPosition:{type:"accessor",value:t=>t.position},getRadius:{type:"accessor",value:1},getFillColor:{type:"accessor",value:$w},getLineColor:{type:"accessor",value:$w},getLineWidth:{type:"accessor",value:1},strokeWidth:{deprecatedFor:"getLineWidth"},outline:{deprecatedFor:"stroked"},getColor:{deprecatedFor:["getFillColor","getLineColor"]}},ma=class extends ve{getShaders(){return super.getShaders({vs:Ww,fs:Vw,source:jw,modules:[Oe,mn,Ne,zw]})}initializeState(){this.getAttributeManager().addInstanced({instancePositions:{size:3,type:"float64",fp64:this.use64bitPositions(),transition:!0,accessor:"getPosition"},instanceRadius:{size:1,transition:!0,accessor:"getRadius",defaultValue:1},instanceFillColors:{size:this.props.colorFormat.length,transition:!0,type:"unorm8",accessor:"getFillColor",defaultValue:[0,0,0,255]},instanceLineColors:{size:this.props.colorFormat.length,transition:!0,type:"unorm8",accessor:"getLineColor",defaultValue:[0,0,0,255]},instanceLineWidths:{size:1,transition:!0,accessor:"getLineWidth",defaultValue:1}})}updateState(e){super.updateState(e),e.changeFlags.extensionsChanged&&(this.state.model?.destroy(),this.state.model=this._getModel(),this.getAttributeManager().invalidateAll())}draw({uniforms:e}){let{radiusUnits:r,radiusScale:i,radiusMinPixels:n,radiusMaxPixels:o,stroked:s,filled:a,billboard:c,antialiasing:l,lineWidthUnits:f,lineWidthScale:u,lineWidthMinPixels:d,lineWidthMaxPixels:h}=this.props,p={stroked:s,filled:a,billboard:c,antialiasing:l,radiusUnits:je[r],radiusScale:i,radiusMinPixels:n,radiusMaxPixels:o,lineWidthUnits:je[f],lineWidthScale:u,lineWidthMinPixels:d,lineWidthMaxPixels:h},g=this.state.model;g.shaderInputs.setProps({scatterplot:p}),g.draw(this.context.renderPass)}_getModel(){let e=[-1,-1,0,1,-1,0,-1,1,0,1,1,0];return new he(this.context.device,{...this.getShaders(),id:this.props.id,bufferLayout:this.getAttributeManager().getBufferLayouts(),geometry:new Ae({topology:"triangle-strip",attributes:{positions:{size:3,value:new Float32Array(e)}}}),isInstanced:!0})}};ma.defaultProps=nL;ma.layerName="ScatterplotLayer";var Eg=ma;var Hw=`layout(std140) uniform sdfUniforms { + float gamma; + bool enabled; + float buffer; + float outlineBuffer; + vec4 outlineColor; +} sdf; +`,Yw={name:"sdf",vs:Hw,fs:Hw,uniformTypes:{gamma:"f32",enabled:"f32",buffer:"f32",outlineBuffer:"f32",outlineColor:"vec4"}};var _a={none:0,start:1,center:2,end:3},oL=`layout(std140) uniform textUniforms { + highp vec2 cutoffPixels; + highp ivec2 align; + highp float fontSize; + bool flipY; +} text; + +#define ALIGN_MODE_START ${_a.start} +#define ALIGN_MODE_CENTER ${_a.center} +#define ALIGN_MODE_END ${_a.end} +`,Pf={name:"text",vs:oL,getUniforms:({contentCutoffPixels:t=[0,0],contentAlignHorizontal:e="none",contentAlignVertical:r="none",fontSize:i,viewport:n})=>({cutoffPixels:t,align:[_a[e],_a[r]],fontSize:i,flipY:n?.flipY??!1}),uniformTypes:{cutoffPixels:"vec2",align:"vec2",fontSize:"f32",flipY:"f32"}};var Xw=`#version 300 es +#define SHADER_NAME multi-icon-layer-vertex-shader +in vec2 positions; +in vec3 instancePositions; +in vec3 instancePositions64Low; +in float instanceSizes; +in float instanceAngles; +in vec4 instanceColors; +in vec3 instancePickingColors; +in vec4 instanceIconFrames; +in float instanceColorModes; +in vec2 instanceOffsets; +in vec2 instancePixelOffset; +in vec4 instanceClipRect; +out float vColorMode; +out vec4 vColor; +out vec2 vTextureCoords; +out vec2 uv; +vec2 rotate_by_angle(vec2 vertex, float angle) { +float angle_radian = angle * PI / 180.0; +float cos_angle = cos(angle_radian); +float sin_angle = sin(angle_radian); +mat2 rotationMatrix = mat2(cos_angle, -sin_angle, sin_angle, cos_angle); +return rotationMatrix * vertex; +} +float getPixelOffsetFromAlignment(float anchor, float extent, float clipStart, float clipEnd, int mode) { +if (clipEnd < clipStart) return 0.0; +if (mode == ALIGN_MODE_START) { +return max(- (anchor + clipStart), 0.0); +} +if (mode == ALIGN_MODE_CENTER) { +float _min = max(0., anchor + clipStart); +float _max = min(extent, anchor + clipEnd); +return _min < _max ? (_min + _max) / 2.0 - anchor : 0.0; +} +if (mode == ALIGN_MODE_END) { +return min(extent - (anchor + clipEnd), 0.); +} +return 0.0; +} +void main(void) { +geometry.worldPosition = instancePositions; +geometry.uv = positions; +geometry.pickingColor = instancePickingColors; +uv = positions; +vec2 iconSize = instanceIconFrames.zw; +float sizePixels = clamp( +project_size_to_pixel(instanceSizes * icon.sizeScale, icon.sizeUnits), +icon.sizeMinPixels, icon.sizeMaxPixels +); +float instanceScale = sizePixels / text.fontSize; +vec2 pixelOffset = positions / 2.0 * iconSize + instanceOffsets; +pixelOffset = rotate_by_angle(pixelOffset, instanceAngles) * instanceScale; +pixelOffset += instancePixelOffset; +pixelOffset.y *= -1.0; +vec2 anchorPosScreen; +if (icon.billboard) { +gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0), geometry.position); +anchorPosScreen = gl_Position.xy / gl_Position.w; +DECKGL_FILTER_GL_POSITION(gl_Position, geometry); +vec3 offset = vec3(pixelOffset, 0.0); +DECKGL_FILTER_SIZE(offset, geometry); +gl_Position.xy += project_pixel_size_to_clipspace(offset.xy); +} else { +vec3 offset_common = vec3(project_pixel_size(pixelOffset), 0.0); +if (text.flipY) { +offset_common.y *= -1.; +} +DECKGL_FILTER_SIZE(offset_common, geometry); +vec4 anchorPos = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0)); +anchorPosScreen = anchorPos.xy / anchorPos.w; +gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset_common, geometry.position); +DECKGL_FILTER_GL_POSITION(gl_Position, geometry); +} +anchorPosScreen = vec2(anchorPosScreen.x + 1.0, 1.0 - anchorPosScreen.y) / 2.0 * project.viewportSize / project.devicePixelRatio; +vec2 xy = project_size_to_pixel(instanceClipRect.xy); +vec2 wh = project_size_to_pixel(instanceClipRect.zw); +if (text.flipY) { +xy.y = -xy.y - wh.y; +} +if (text.align.x > 0 || text.align.y > 0) { +vec2 viewportPixels = project.viewportSize / project.devicePixelRatio; +vec2 scrollPixels = vec2( +getPixelOffsetFromAlignment(anchorPosScreen.x, viewportPixels.x, xy.x, xy.x + wh.x, text.align.x), +-getPixelOffsetFromAlignment(anchorPosScreen.y, viewportPixels.y, -xy.y - wh.y, -xy.y, text.align.y) +); +pixelOffset += scrollPixels; +gl_Position.xy += project_pixel_size_to_clipspace(scrollPixels); +} +if (instanceClipRect.z >= 0.) { +if (pixelOffset.x < xy.x || pixelOffset.x > xy.x + wh.x) { +gl_Position = vec4(0.0); +} +else if (text.cutoffPixels.x > 0.) { +float vpWidth = project.viewportSize.x / project.devicePixelRatio; +float l = max(anchorPosScreen.x + xy.x, 0.0); +float r = min(anchorPosScreen.x + xy.x + wh.x, vpWidth); +if (r - l < text.cutoffPixels.x) { +gl_Position = vec4(0.0); +} +} +} +if (instanceClipRect.w >= 0.) { +if (pixelOffset.y < xy.y || pixelOffset.y > xy.y + wh.y) { +gl_Position = vec4(0.0); +} +else if (text.cutoffPixels.y > 0.) { +float vpHeight = project.viewportSize.y / project.devicePixelRatio; +float t = max(anchorPosScreen.y - xy.y - wh.y, 0.0); +float b = min(anchorPosScreen.y - xy.y, vpHeight); +if (b - t < text.cutoffPixels.y) { +gl_Position = vec4(0.0); +} +} +} +vTextureCoords = mix( +instanceIconFrames.xy, +instanceIconFrames.xy + iconSize, +(positions.xy + 1.0) / 2.0 +) / icon.iconsTextureDim; +vColor = instanceColors; +DECKGL_FILTER_COLOR(vColor, geometry); +vColorMode = instanceColorModes; +} +`;var Gw=`#version 300 es +#define SHADER_NAME multi-icon-layer-fragment-shader +precision highp float; +uniform sampler2D iconsTexture; +in vec4 vColor; +in vec2 vTextureCoords; +in vec2 uv; +out vec4 fragColor; +void main(void) { +geometry.uv = uv; +if (!bool(picking.isActive)) { +float alpha = texture(iconsTexture, vTextureCoords).a; +vec4 color = vColor; +if (sdf.enabled) { +float distance = alpha; +alpha = smoothstep(sdf.buffer - sdf.gamma, sdf.buffer + sdf.gamma, distance); +if (sdf.outlineBuffer > 0.0) { +float inFill = alpha; +float inBorder = smoothstep(sdf.outlineBuffer - sdf.gamma, sdf.outlineBuffer + sdf.gamma, distance); +color = mix(sdf.outlineColor, vColor, inFill); +alpha = inBorder; +} +} +float a = alpha * color.a; +if (a < icon.alphaCutoff) { +discard; +} +fragColor = vec4(color.rgb, a * layer.opacity); +} +DECKGL_FILTER_COLOR(fragColor, geometry); +} +`;var Rg=192/256;var sL={getIconOffsets:{type:"accessor",value:t=>t.offsets},getContentBox:{type:"accessor",value:[0,0,-1,-1]},fontSize:1,alphaCutoff:.001,smoothing:.1,outlineWidth:0,outlineColor:{type:"color",value:[0,0,0,255]},contentCutoffPixels:{type:"array",value:[0,0]},contentAlignHorizontal:"none",contentAlignVertical:"none"},ya=class extends kw{getShaders(){let e=super.getShaders();return{...e,modules:[...e.modules,Pf,Yw],vs:Xw,fs:Gw}}initializeState(){super.initializeState();let e=this.getAttributeManager(),r=e.attributes.instanceIconDefs;r.settings.update=this.calculateInstanceIconDefs,e.addInstanced({instancePickingColors:{type:"uint8",size:4,accessor:(i,{index:n,target:o})=>this.encodePickingColor(n,o)},instanceClipRect:{size:4,accessor:"getContentBox",defaultValue:[0,0,-1,-1]}})}updateState(e){super.updateState(e);let{props:r,oldProps:i,changeFlags:n}=e,{outlineColor:o}=r;if(n.updateTriggersChanged&&(n.updateTriggersChanged.getIcon||n.updateTriggersChanged.getIconOffsets)&&this.getAttributeManager().invalidate("instanceIconDefs"),o!==i.outlineColor){let s=[o[0]/255,o[1]/255,o[2]/255,(o[3]??255)/255];this.setState({outlineColor:s})}!r.sdf&&r.outlineWidth&&F.warn(`${this.id}: fontSettings.sdf is required to render outline`)()}draw(e){let{sdf:r,smoothing:i,fontSize:n,outlineWidth:o,contentCutoffPixels:s,contentAlignHorizontal:a,contentAlignVertical:c}=this.props,{outlineColor:l}=this.state,f=o?Math.max(i,Rg*(1-o)):-1,u=this.state.model,d={buffer:Rg,outlineBuffer:f,gamma:i,enabled:!!r,outlineColor:l},h={contentCutoffPixels:s,contentAlignHorizontal:a,contentAlignVertical:c,fontSize:n,viewport:this.context.viewport};if(u.shaderInputs.setProps({sdf:d,text:h}),super.draw(e),r&&o){let{iconManager:p}=this.state;p.getTexture()&&(u.shaderInputs.setProps({sdf:{...d,outlineBuffer:Rg}}),u.draw(this.context.renderPass))}}calculateInstanceIconDefs(e,{startRow:r,endRow:i}){let{data:n,getIcon:o,getIconOffsets:s}=this.props,a=e.getVertexOffset(r),c=e.value,{iterable:l,objectInfo:f}=mr(n,r,i);for(let u of l){f.index++;let d=o(u,f),h=s(u,f);if(d){let p=0;for(let g of Array.from(d)){let m=super.getInstanceIconDef(g);m[0]=h[p*2],m[1]+=h[p*2+1],m[6]=1,c.set(m,a),a+=e.size,p++}}}}};ya.defaultProps=sL;ya.layerName="MultiIconLayer";var qw=ya;var Cg=new Float64Array(256);for(let t=0;t<256;t++){let e=.5-Math.pow(t/255,.45454545454545453);Cg[t]=e*Math.abs(e)}Cg[255]=-1e20;var xa=class{constructor({fontSize:e=24,buffer:r=3,radius:i=8,cutoff:n=.25,fontFamily:o="sans-serif",fontWeight:s="normal",fontStyle:a="normal",lang:c=null}={}){this.buffer=r,this.radius=i,this.cutoff=n,this.lang=c;let l=this.size=e+r*4,f=this._createCanvas(l),u=this.ctx=f.getContext("2d",{willReadFrequently:!0});u.font=`${a} ${s} ${e}px ${o}`,u.textBaseline="alphabetic",u.textAlign="left",u.fillStyle="black",this.gridOuter=new Float64Array(l*l),this.gridInner=new Float64Array(l*l),this.f=new Float64Array(l),this.z=new Float64Array(l+1),this.v=new Uint16Array(l)}_createCanvas(e){if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(e,e);let r=document.createElement("canvas");return r.width=r.height=e,r}draw(e){let{width:r,actualBoundingBoxAscent:i,actualBoundingBoxDescent:n,actualBoundingBoxLeft:o,actualBoundingBoxRight:s}=this.ctx.measureText(e),a=Math.ceil(i),c=Math.floor(-o),l=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(s)-c)),f=Math.max(0,Math.min(this.size-this.buffer,a+Math.ceil(n))),u=l+2*this.buffer,d=f+2*this.buffer,h=Math.max(u*d,0),p=new Uint8ClampedArray(h),g={data:p,width:u,height:d,glyphWidth:l,glyphHeight:f,glyphTop:a,glyphLeft:c,glyphAdvance:r};if(l===0||f===0)return g;let{ctx:m,buffer:_,gridInner:T,gridOuter:y}=this;this.lang&&(m.lang=this.lang),m.clearRect(_,_,l,f),m.fillText(e,_-c,_+a);let x=m.getImageData(_,_,l,f);y.fill(1e20,0,h),T.fill(0,0,h);let w=3;for(let A=0;A-1);c++,o[c]=a,s[c]=l,s[c+1]=1e20}for(let a=0,c=0;ai&&(l=0,f=u),n[d]={x:l+r,y:f+r,width:p,height:_,advance:h,anchorX:p/2,anchorY:g},l+=p+r*2,u=Math.max(u,f+_+r*2)}return{mapping:n,xOffset:l,yOffsetMin:f,yOffsetMax:u,canvasHeight:lL(u)}}function Jw(t,e,r,i){let n=0;for(let o=e;oi&&(sa){let u=Jw(t,a,c,n);l+u>i&&(si&&(u=eS(t,a,c,i,n,o),s=o[o.length-1])),a=c,l+=u}return l}function uL(t,e,r,i,n=0,o){o===void 0&&(o=t.length);let s=[];return e==="break-all"?eS(t,n,o,r,i,s):fL(t,n,o,r,i,s),s}function dL(t,e,r,i,n,o){let s=0,a=0;for(let c=e;c0,d=[0,0],h=[0,0],p=0,g=e+r/2,m=0,_=0;for(let T=0;T<=a;T++){let y=s[T];if((y===` +`||T===a)&&(_=T),_>m){let x=u?uL(s,i,n,o,m,_):cL;for(let w=0;w<=x.length;w++){let b=w===0?m:x[w-1],E=w1||c>0){let h=t.constructor;d=new h(l);for(let p=0;p=0&&this._order.splice(r,1)}_appendOrder(e){this._order.push(e)}};function hL(){let t=[];for(let e=32;e<128;e++)t.push(String.fromCharCode(e));return t}var Li={fontFamily:"Monaco, monospace",fontWeight:"normal",characterSet:hL(),fontSize:64,buffer:4,sdf:!1,cutoff:.25,radius:12,smoothing:.1},iS=1024,nS=.9,oS=.3,aS=3,Mf=new $n(aS);function pL(t,e){let r;typeof e=="string"?r=new Set(Array.from(e)):r=new Set(e);let i=Mf.get(t);if(!i)return r;for(let n in i.mapping)r.has(n)&&r.delete(n);return r}function gL(t,e){for(let r=0;r=aS,"Invalid cache limit"),Mf=new $n(t)}var ba=class{constructor(){this.props={...Li}}get atlas(){return this._atlas}get mapping(){return this._atlas&&this._atlas.mapping}setProps(e={}){Object.assign(this.props,e),e._getFontRenderer&&(this._getFontRenderer=e._getFontRenderer),this._key=this._getKey();let r=pL(this._key,this.props.characterSet),i=Mf.get(this._key);if(i&&r.size===0){this._atlas!==i&&(this._atlas=i);return}let n=this._generateFontAtlas(r,i);this._atlas=n,Mf.set(this._key,n)}_generateFontAtlas(e,r){let{fontFamily:i,fontWeight:n,fontSize:o,buffer:s,sdf:a,radius:c,cutoff:l}=this.props,f=r&&r.data;f||(f=document.createElement("canvas"),f.width=iS);let u=f.getContext("2d",{willReadFrequently:!0});sS(u,i,o,n);let d=x=>mL(u,o,x),h;this._getFontRenderer?h=this._getFontRenderer(this.props):a&&(h={measure:d,draw:_L(this.props)});let{mapping:p,canvasHeight:g,xOffset:m,yOffsetMin:_,yOffsetMax:T}=Qw({measureText:x=>h?h.measure(x):d(x),buffer:s,characterSet:e,maxCanvasWidth:iS,...r&&{mapping:r.mapping,xOffset:r.xOffset,yOffsetMin:r.yOffsetMin,yOffsetMax:r.yOffsetMax}});if(f.height!==g){let x=f.height>0?u.getImageData(0,0,f.width,f.height):null;f.height=g,x&&u.putImageData(x,0,0)}if(sS(u,i,o,n),h)for(let x of e){let w=p[x],{data:b,left:E=0,top:S=0}=h.draw(x),A=w.x-E,C=w.y-S,I=Math.max(0,Math.round(A)),R=Math.max(0,Math.round(C)),N=Math.min(b.width,f.width-I),O=Math.min(b.height,f.height-R);u.putImageData(b,I,R,0,0,N,O),w.x+=I-A,w.y+=R-C}else for(let x of e){let w=p[x];u.fillText(x,w.x,w.y+w.anchorY)}let y=h?h.measure():d();return{baselineOffset:(y.ascent-y.descent)/2,xOffset:m,yOffsetMin:_,yOffsetMax:T,mapping:p,data:f,width:f.width,height:f.height}}_getKey(){let{fontFamily:e,fontWeight:r,fontSize:i,buffer:n,sdf:o,radius:s,cutoff:a}=this.props;return o?`${e} ${r} ${i} ${n} ${s} ${a}`:`${e} ${r} ${i} ${n}`}};function _L({fontSize:t,buffer:e,radius:r,cutoff:i,fontFamily:n,fontWeight:o}){let s=new xa({fontSize:t,buffer:e,radius:r,cutoff:i,fontFamily:n,fontWeight:`${o}`});return a=>{let{data:c,width:l,height:f}=s.draw(a),u=new ImageData(l,f);return gL(c,u),{data:u,left:e,top:e}}}var lS=`layout(std140) uniform textBackgroundUniforms { + bool billboard; + float sizeScale; + float sizeMinPixels; + float sizeMaxPixels; + vec4 borderRadius; + vec4 padding; + highp int sizeUnits; + bool stroked; +} textBackground; +`,fS={name:"textBackground",vs:lS,fs:lS,uniformTypes:{billboard:"f32",sizeScale:"f32",sizeMinPixels:"f32",sizeMaxPixels:"f32",borderRadius:"vec4",padding:"vec4",sizeUnits:"i32",stroked:"f32"}};var uS=`#version 300 es +#define SHADER_NAME text-background-layer-vertex-shader +in vec2 positions; +in vec3 instancePositions; +in vec3 instancePositions64Low; +in vec4 instanceRects; +in vec4 instanceClipRect; +in float instanceSizes; +in float instanceAngles; +in vec2 instancePixelOffsets; +in float instanceLineWidths; +in vec4 instanceFillColors; +in vec4 instanceLineColors; +in vec3 instancePickingColors; +out vec4 vFillColor; +out vec4 vLineColor; +out float vLineWidth; +out vec2 uv; +out vec2 dimensions; +vec2 rotate_by_angle(vec2 vertex, float angle) { +float angle_radian = radians(angle); +float cos_angle = cos(angle_radian); +float sin_angle = sin(angle_radian); +mat2 rotationMatrix = mat2(cos_angle, -sin_angle, sin_angle, cos_angle); +return rotationMatrix * vertex; +} +void main(void) { +geometry.worldPosition = instancePositions; +geometry.uv = positions; +geometry.pickingColor = instancePickingColors; +uv = positions; +vLineWidth = instanceLineWidths; +float sizePixels = clamp( +project_size_to_pixel(instanceSizes * textBackground.sizeScale, textBackground.sizeUnits), +textBackground.sizeMinPixels, textBackground.sizeMaxPixels +); +float instanceScale = sizePixels / text.fontSize; +dimensions = instanceRects.zw * instanceScale + textBackground.padding.xy + textBackground.padding.zw; +vec2 pixelOffset = (positions * instanceRects.zw + instanceRects.xy) * instanceScale + mix(-textBackground.padding.xy, textBackground.padding.zw, positions); +pixelOffset = rotate_by_angle(pixelOffset, instanceAngles); +pixelOffset += instancePixelOffsets; +pixelOffset.y *= -1.0; +vec2 xy = project_size_to_pixel(instanceClipRect.xy); +vec2 wh = project_size_to_pixel(instanceClipRect.zw); +if (text.flipY) { +xy.y = -xy.y - wh.y; +} +if (instanceClipRect.z >= 0.0) { +dimensions.x = wh.x; +pixelOffset.x = xy.x + uv.x * wh.x + mix(-textBackground.padding.x, textBackground.padding.z, uv.x); +} +if (instanceClipRect.w >= 0.0) { +dimensions.y = wh.y; +pixelOffset.y = xy.y + uv.y * wh.y + mix(-textBackground.padding.y, textBackground.padding.w, uv.y); +} +if (textBackground.billboard) { +gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0), geometry.position); +DECKGL_FILTER_GL_POSITION(gl_Position, geometry); +vec3 offset = vec3(pixelOffset, 0.0); +DECKGL_FILTER_SIZE(offset, geometry); +gl_Position.xy += project_pixel_size_to_clipspace(offset.xy); +} else { +vec3 offset_common = vec3(project_pixel_size(pixelOffset), 0.0); +if (text.flipY) { +offset_common.y *= -1.; +} +DECKGL_FILTER_SIZE(offset_common, geometry); +gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset_common, geometry.position); +DECKGL_FILTER_GL_POSITION(gl_Position, geometry); +} +vFillColor = vec4(instanceFillColors.rgb, instanceFillColors.a * layer.opacity); +DECKGL_FILTER_COLOR(vFillColor, geometry); +vLineColor = vec4(instanceLineColors.rgb, instanceLineColors.a * layer.opacity); +DECKGL_FILTER_COLOR(vLineColor, geometry); +} +`;var dS=`#version 300 es +#define SHADER_NAME text-background-layer-fragment-shader +precision highp float; +in vec4 vFillColor; +in vec4 vLineColor; +in float vLineWidth; +in vec2 uv; +in vec2 dimensions; +out vec4 fragColor; +float round_rect(vec2 p, vec2 size, vec4 radii) { +vec2 pixelPositionCB = (p - 0.5) * size; +vec2 sizeCB = size * 0.5; +float maxBorderRadius = min(size.x, size.y) * 0.5; +vec4 borderRadius = vec4(min(radii, maxBorderRadius)); +borderRadius.xy = +(pixelPositionCB.x > 0.0) ? borderRadius.xy : borderRadius.zw; +borderRadius.x = (pixelPositionCB.y > 0.0) ? borderRadius.x : borderRadius.y; +vec2 q = abs(pixelPositionCB) - sizeCB + borderRadius.x; +return -(min(max(q.x, q.y), 0.0) + length(max(q, 0.0)) - borderRadius.x); +} +float rect(vec2 p, vec2 size) { +vec2 pixelPosition = p * size; +return min(min(pixelPosition.x, size.x - pixelPosition.x), +min(pixelPosition.y, size.y - pixelPosition.y)); +} +vec4 get_stroked_fragColor(float dist) { +float isBorder = smoothedge(dist, vLineWidth); +return mix(vFillColor, vLineColor, isBorder); +} +void main(void) { +geometry.uv = uv; +if (textBackground.borderRadius != vec4(0.0)) { +float distToEdge = round_rect(uv, dimensions, textBackground.borderRadius); +float shapeAlpha = smoothedge(-distToEdge, 0.0); +if (shapeAlpha == 0.0) { +discard; +} +if (textBackground.stroked) { +fragColor = get_stroked_fragColor(distToEdge); +} else { +fragColor = vFillColor; +} +fragColor.a *= shapeAlpha; +} else { +if (textBackground.stroked) { +float distToEdge = rect(uv, dimensions); +fragColor = get_stroked_fragColor(distToEdge); +} else { +fragColor = vFillColor; +} +} +DECKGL_FILTER_COLOR(fragColor, geometry); +} +`;var yL={billboard:!0,sizeScale:1,sizeUnits:"pixels",sizeMinPixels:0,sizeMaxPixels:Number.MAX_SAFE_INTEGER,fontSize:1,borderRadius:{type:"object",value:0},padding:{type:"array",value:[0,0,0,0]},getPosition:{type:"accessor",value:t=>t.position},getSize:{type:"accessor",value:1},getAngle:{type:"accessor",value:0},getPixelOffset:{type:"accessor",value:[0,0]},getBoundingRect:{type:"accessor",value:[0,0,0,0]},getClipRect:{type:"accessor",value:[0,0,-1,-1]},getFillColor:{type:"accessor",value:[0,0,0,255]},getLineColor:{type:"accessor",value:[0,0,0,255]},getLineWidth:{type:"accessor",value:1}},Ta=class extends ve{getShaders(){return super.getShaders({vs:uS,fs:dS,modules:[Oe,Ne,fS,Pf]})}initializeState(){this.getAttributeManager().addInstanced({instancePositions:{size:3,type:"float64",fp64:this.use64bitPositions(),transition:!0,accessor:"getPosition"},instanceSizes:{size:1,transition:!0,accessor:"getSize",defaultValue:1},instanceAngles:{size:1,transition:!0,accessor:"getAngle"},instanceRects:{size:4,accessor:"getBoundingRect"},instanceClipRect:{size:4,accessor:"getClipRect",defaultValue:[0,0,-1,-1]},instancePixelOffsets:{size:2,transition:!0,accessor:"getPixelOffset"},instanceFillColors:{size:4,transition:!0,type:"unorm8",accessor:"getFillColor",defaultValue:[0,0,0,255]},instanceLineColors:{size:4,transition:!0,type:"unorm8",accessor:"getLineColor",defaultValue:[0,0,0,255]},instanceLineWidths:{size:1,transition:!0,accessor:"getLineWidth",defaultValue:1}})}updateState(e){super.updateState(e);let{changeFlags:r}=e;r.extensionsChanged&&(this.state.model?.destroy(),this.state.model=this._getModel(),this.getAttributeManager().invalidateAll())}draw({uniforms:e}){let{billboard:r,sizeScale:i,sizeUnits:n,sizeMinPixels:o,sizeMaxPixels:s,getLineWidth:a,fontSize:c}=this.props,{padding:l,borderRadius:f}=this.props;l.length<4&&(l=[l[0],l[1],l[0],l[1]]),Array.isArray(f)||(f=[f,f,f,f]);let u=this.state.model,d={billboard:r,stroked:!!a,borderRadius:f,padding:l,sizeUnits:je[n],sizeScale:i,sizeMinPixels:o,sizeMaxPixels:s},h={fontSize:c,viewport:this.context.viewport};u.shaderInputs.setProps({textBackground:d,text:h}),u.draw(this.context.renderPass)}_getModel(){let e=[0,0,1,0,0,1,1,1];return new he(this.context.device,{...this.getShaders(),id:this.props.id,bufferLayout:this.getAttributeManager().getBufferLayouts(),geometry:new Ae({topology:"triangle-strip",vertexCount:4,attributes:{positions:{size:2,value:new Float32Array(e)}}}),isInstanced:!0})}};Ta.defaultProps=yL;Ta.layerName="TextBackgroundLayer";var hS=Ta;var pS={start:1,middle:0,end:-1},gS={top:1,center:0,bottom:-1},Pg=[0,0,0,255],xL=1,bL={billboard:!0,sizeScale:1,sizeUnits:"pixels",sizeMinPixels:0,sizeMaxPixels:Number.MAX_SAFE_INTEGER,background:!1,getBackgroundColor:{type:"accessor",value:[255,255,255,255]},getBorderColor:{type:"accessor",value:Pg},getBorderWidth:{type:"accessor",value:0},backgroundBorderRadius:{type:"object",value:0},backgroundPadding:{type:"array",value:[0,0,0,0]},characterSet:{type:"object",value:Li.characterSet},fontFamily:Li.fontFamily,fontWeight:Li.fontWeight,lineHeight:xL,outlineWidth:{type:"number",value:0,min:0},outlineColor:{type:"color",value:Pg},fontSettings:{type:"object",value:{},compare:1},wordBreak:"break-word",maxWidth:{type:"number",value:-1},contentCutoffPixels:{type:"array",value:[0,0]},contentAlignHorizontal:"none",contentAlignVertical:"none",getText:{type:"accessor",value:t=>t.text},getPosition:{type:"accessor",value:t=>t.position},getColor:{type:"accessor",value:Pg},getSize:{type:"accessor",value:32},getAngle:{type:"accessor",value:0},getTextAnchor:{type:"accessor",value:"middle"},getAlignmentBaseline:{type:"accessor",value:"center"},getPixelOffset:{type:"accessor",value:[0,0]},getContentBox:{type:"accessor",value:[0,0,-1,-1]},backgroundColor:{deprecatedFor:["background","getBackgroundColor"]}},wa=class extends na{constructor(){super(...arguments),this.getBoundingRect=(e,r)=>{let{size:[i,n]}=this.transformParagraph(e,r),{getTextAnchor:o,getAlignmentBaseline:s}=this.props,a=pS[typeof o=="function"?o(e,r):o],c=gS[typeof s=="function"?s(e,r):s];return[(a-1)*i/2,(c-1)*n/2,i,n]},this.getIconOffsets=(e,r)=>{let{getTextAnchor:i,getAlignmentBaseline:n}=this.props,{x:o,y:s,rowWidth:a,size:[,c]}=this.transformParagraph(e,r),l=pS[typeof i=="function"?i(e,r):i],f=gS[typeof n=="function"?n(e,r):n],u=o.length,d=new Array(u*2),h=0;for(let p=0;p0&&F.once(1,"v8.9 breaking change: TextLayer maxWidth is now relative to text size")()}updateState(e){let{props:r,oldProps:i,changeFlags:n}=e;(n.dataChanged||n.updateTriggersChanged&&(n.updateTriggersChanged.all||n.updateTriggersChanged.getText))&&this._updateText(),(this._updateFontAtlas()||r.lineHeight!==i.lineHeight||r.wordBreak!==i.wordBreak||r.maxWidth!==i.maxWidth)&&this.setState({styleVersion:this.state.styleVersion+1})}getPickingInfo({info:e}){return e.object=e.index>=0?this.props.data[e.index]:null,e}_updateFontAtlas(){let{fontSettings:e,fontFamily:r,fontWeight:i,_getFontRenderer:n}=this.props,{fontAtlasManager:o,characterSet:s}=this.state,a={...e,characterSet:s,fontFamily:r,fontWeight:i,_getFontRenderer:n};if(!o.mapping)return o.setProps(a),!0;for(let c in a)if(a[c]!==o.props[c])return o.setProps(a),!0;return!1}_updateText(){let{data:e,characterSet:r}=this.props,i=e.attributes?.getText,{getText:n}=this.props,o=e.startIndices,s,a=r==="auto"&&new Set;if(i&&o){let{texts:c,characterCount:l}=rS({...ArrayBuffer.isView(i)?{value:i}:i,length:e.length,startIndices:o,characterSet:a});s=l,n=(f,{index:u})=>c[u]}else{let{iterable:c,objectInfo:l}=mr(e);o=[0],s=0;for(let f of c){l.index++;let u=Array.from(n(f,l)||"");a&&u.forEach(a.add,a),s+=u.length,o.push(s)}}this.setState({getText:n,startIndices:o,numInstances:s,characterSet:a||r})}transformParagraph(e,r){let{fontAtlasManager:i}=this.state,n=i.mapping,{baselineOffset:o}=i.atlas,{fontSize:s}=i.props,a=this.state.getText,{wordBreak:c,lineHeight:l,maxWidth:f}=this.props,u=a(e,r)||"";return tS(u,o,l*s,c,f*s,n)}renderLayers(){let{startIndices:e,numInstances:r,getText:i,fontAtlasManager:{atlas:n,mapping:o},styleVersion:s}=this.state,{data:a,_dataDiff:c,getPosition:l,getColor:f,getSize:u,getAngle:d,getPixelOffset:h,getBackgroundColor:p,getBorderColor:g,getBorderWidth:m,getContentBox:_,backgroundBorderRadius:T,backgroundPadding:y,background:x,billboard:w,fontSettings:b,outlineWidth:E,outlineColor:S,sizeScale:A,sizeUnits:C,sizeMinPixels:I,sizeMaxPixels:R,contentCutoffPixels:N,contentAlignHorizontal:O,contentAlignVertical:W,transitions:G,updateTriggers:L}=this.props,H=this.getSubLayerClass("characters",qw),Re=this.getSubLayerClass("background",hS),{fontSize:We}=this.state.fontAtlasManager.props;return[x&&new Re({getFillColor:p,getLineColor:g,getLineWidth:m,borderRadius:T,padding:y,getPosition:l,getSize:u,getAngle:d,getPixelOffset:h,getClipRect:_,billboard:w,sizeScale:A,sizeUnits:C,sizeMinPixels:I,sizeMaxPixels:R,fontSize:We,transitions:G&&{getPosition:G.getPosition,getAngle:G.getAngle,getSize:G.getSize,getFillColor:G.getBackgroundColor,getLineColor:G.getBorderColor,getLineWidth:G.getBorderWidth,getPixelOffset:G.getPixelOffset}},this.getSubLayerProps({id:"background",updateTriggers:{getPosition:L.getPosition,getAngle:L.getAngle,getSize:L.getSize,getFillColor:L.getBackgroundColor,getLineColor:L.getBorderColor,getLineWidth:L.getBorderWidth,getPixelOffset:L.getPixelOffset,getBoundingRect:{getText:L.getText,getTextAnchor:L.getTextAnchor,getAlignmentBaseline:L.getAlignmentBaseline,styleVersion:s}}}),{data:a.attributes&&a.attributes.background?{length:a.length,attributes:a.attributes.background}:a,_dataDiff:c,autoHighlight:!1,getBoundingRect:this.getBoundingRect}),new H({sdf:b.sdf,smoothing:Number.isFinite(b.smoothing)?b.smoothing:Li.smoothing,outlineWidth:E/(b.radius||Li.radius),outlineColor:S,iconAtlas:n,iconMapping:o,getPosition:l,getColor:f,getSize:u,getAngle:d,getPixelOffset:h,getContentBox:_,billboard:w,sizeScale:A,sizeUnits:C,sizeMinPixels:I,sizeMaxPixels:R,fontSize:We,contentCutoffPixels:N,contentAlignHorizontal:O,contentAlignVertical:W,transitions:G&&{getPosition:G.getPosition,getAngle:G.getAngle,getColor:G.getColor,getSize:G.getSize,getPixelOffset:G.getPixelOffset,getContentBox:G.getContentBox}},this.getSubLayerProps({id:"characters",updateTriggers:{all:L.getText,getPosition:L.getPosition,getAngle:L.getAngle,getColor:L.getColor,getSize:L.getSize,getPixelOffset:L.getPixelOffset,getContentBox:L.getContentBox,getIconOffsets:{getTextAnchor:L.getTextAnchor,getAlignmentBaseline:L.getAlignmentBaseline,styleVersion:s}}}),{data:a,_dataDiff:c,startIndices:e,numInstances:r,getIconOffsets:this.getIconOffsets,getIcon:i})]}static set fontAtlasCacheLimit(e){cS(e)}};wa.defaultProps=bL;wa.layerName="TextLayer";var Mg=wa;function Hn(t){let{children:e}=t;return e&&e.length>0}function Bi(t){let{zoom:e}=t;return e!==void 0}function If(t){return t&&!!t.aggregate}var Fi;(function(t){t.ALL="ALL",t.INCOMING="INCOMING",t.OUTGOING="OUTGOING",t.BETWEEN="BETWEEN"})(Fi||(Fi={}));function V(t){for(var e=t.length/6|0,r=new Array(e),i=0;i>8&15|e>>4&240,e>>4&15|e&240,(e&15)<<4|e&15,1):r===8?Of(e>>24&255,e>>16&255,e>>8&255,(e&255)/255):r===4?Of(e>>12&15|e>>8&240,e>>8&15|e>>4&240,e>>4&15|e&240,((e&15)<<4|e&15)/255):null):(e=wL.exec(t))?new ge(e[1],e[2],e[3],1):(e=SL.exec(t))?new ge(e[1]*255/100,e[2]*255/100,e[3]*255/100,1):(e=AL.exec(t))?Of(e[1],e[2],e[3],e[4]):(e=vL.exec(t))?Of(e[1]*255/100,e[2]*255/100,e[3]*255/100,e[4]):(e=EL.exec(t))?wS(e[1],e[2]/100,e[3]/100,1):(e=RL.exec(t))?wS(e[1],e[2]/100,e[3]/100,e[4]):mS.hasOwnProperty(t)?xS(mS[t]):t==="transparent"?new ge(NaN,NaN,NaN,0):null}function xS(t){return new ge(t>>16&255,t>>8&255,t&255,1)}function Of(t,e,r,i){return i<=0&&(t=e=r=NaN),new ge(t,e,r,i)}function Aa(t){return t instanceof Gt||(t=Et(t)),t?(t=t.rgb(),new ge(t.r,t.g,t.b,t.opacity)):new ge}function Gr(t,e,r,i){return arguments.length===1?Aa(t):new ge(t,e,r,i??1)}function ge(t,e,r,i){this.r=+t,this.g=+e,this.b=+r,this.opacity=+i}_r(ge,Gr,Yr(Gt,{brighter(t){return t=t==null?zi:Math.pow(zi,t),new ge(this.r*t,this.g*t,this.b*t,this.opacity)},darker(t){return t=t==null?Xr:Math.pow(Xr,t),new ge(this.r*t,this.g*t,this.b*t,this.opacity)},rgb(){return this},clamp(){return new ge(Ui(this.r),Ui(this.g),Ui(this.b),Df(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:bS,formatHex:bS,formatHex8:ML,formatRgb:TS,toString:TS}));function bS(){return`#${ki(this.r)}${ki(this.g)}${ki(this.b)}`}function ML(){return`#${ki(this.r)}${ki(this.g)}${ki(this.b)}${ki((isNaN(this.opacity)?1:this.opacity)*255)}`}function TS(){let t=Df(this.opacity);return`${t===1?"rgb(":"rgba("}${Ui(this.r)}, ${Ui(this.g)}, ${Ui(this.b)}${t===1?")":`, ${t})`}`}function Df(t){return isNaN(t)?1:Math.max(0,Math.min(1,t))}function Ui(t){return Math.max(0,Math.min(255,Math.round(t)||0))}function ki(t){return t=Ui(t),(t<16?"0":"")+t.toString(16)}function wS(t,e,r,i){return i<=0?t=e=r=NaN:r<=0||r>=1?t=e=NaN:e<=0&&(t=NaN),new vt(t,e,r,i)}function AS(t){if(t instanceof vt)return new vt(t.h,t.s,t.l,t.opacity);if(t instanceof Gt||(t=Et(t)),!t)return new vt;if(t instanceof vt)return t;t=t.rgb();var e=t.r/255,r=t.g/255,i=t.b/255,n=Math.min(e,r,i),o=Math.max(e,r,i),s=NaN,a=o-n,c=(o+n)/2;return a?(e===o?s=(r-i)/a+(r0&&c<1?0:s,new vt(s,a,c,t.opacity)}function vS(t,e,r,i){return arguments.length===1?AS(t):new vt(t,e,r,i??1)}function vt(t,e,r,i){this.h=+t,this.s=+e,this.l=+r,this.opacity=+i}_r(vt,vS,Yr(Gt,{brighter(t){return t=t==null?zi:Math.pow(zi,t),new vt(this.h,this.s,this.l*t,this.opacity)},darker(t){return t=t==null?Xr:Math.pow(Xr,t),new vt(this.h,this.s,this.l*t,this.opacity)},rgb(){var t=this.h%360+(this.h<0)*360,e=isNaN(t)||isNaN(this.s)?0:this.s,r=this.l,i=r+(r<.5?r:1-r)*e,n=2*r-i;return new ge(Ig(t>=240?t-240:t+120,n,i),Ig(t,n,i),Ig(t<120?t+240:t-120,n,i),this.opacity)},clamp(){return new vt(SS(this.h),Nf(this.s),Nf(this.l),Df(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){let t=Df(this.opacity);return`${t===1?"hsl(":"hsla("}${SS(this.h)}, ${Nf(this.s)*100}%, ${Nf(this.l)*100}%${t===1?")":`, ${t})`}`}}));function SS(t){return t=(t||0)%360,t<0?t+360:t}function Nf(t){return Math.max(0,Math.min(1,t||0))}function Ig(t,e,r){return(t<60?e+(r-e)*t/60:t<180?r:t<240?e+(r-e)*(240-t)/60:e)*255}var Lf=Math.PI/180,Ff=180/Math.PI;var Bf=18,ES=.96422,RS=1,CS=.82521,PS=4/29,Xn=6/29,MS=3*Xn*Xn,IL=Xn*Xn*Xn;function IS(t){if(t instanceof qt)return new qt(t.l,t.a,t.b,t.opacity);if(t instanceof yr)return OS(t);t instanceof ge||(t=Aa(t));var e=Lg(t.r),r=Lg(t.g),i=Lg(t.b),n=Og((.2225045*e+.7168786*r+.0606169*i)/RS),o,s;return e===r&&r===i?o=s=n:(o=Og((.4360747*e+.3850649*r+.1430804*i)/ES),s=Og((.0139322*e+.0971045*r+.7141733*i)/CS)),new qt(116*n-16,500*(o-n),200*(n-s),t.opacity)}function Fg(t,e,r,i){return arguments.length===1?IS(t):new qt(t,e,r,i??1)}function qt(t,e,r,i){this.l=+t,this.a=+e,this.b=+r,this.opacity=+i}_r(qt,Fg,Yr(Gt,{brighter(t){return new qt(this.l+Bf*(t??1),this.a,this.b,this.opacity)},darker(t){return new qt(this.l-Bf*(t??1),this.a,this.b,this.opacity)},rgb(){var t=(this.l+16)/116,e=isNaN(this.a)?t:t+this.a/500,r=isNaN(this.b)?t:t-this.b/200;return e=ES*Ng(e),t=RS*Ng(t),r=CS*Ng(r),new ge(Dg(3.1338561*e-1.6168667*t-.4906146*r),Dg(-.9787684*e+1.9161415*t+.033454*r),Dg(.0719453*e-.2289914*t+1.4052427*r),this.opacity)}}));function Og(t){return t>IL?Math.pow(t,1/3):t/MS+PS}function Ng(t){return t>Xn?t*t*t:MS*(t-PS)}function Dg(t){return 255*(t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055)}function Lg(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function OL(t){if(t instanceof yr)return new yr(t.h,t.c,t.l,t.opacity);if(t instanceof qt||(t=IS(t)),t.a===0&&t.b===0)return new yr(NaN,0=1?(r=1,e-1):Math.floor(r*e),n=t[i],o=t[i+1],s=i>0?t[i-1]:2*n-o,a=i()=>t;function kS(t,e){return function(r){return t+r*e}}function DL(t,e,r){return t=Math.pow(t,r),e=Math.pow(e,r)-t,r=1/r,function(i){return Math.pow(t+i*e,r)}}function US(t,e){var r=e-t;return r?kS(t,r>180||r<-180?r-360*Math.round(r/360):r):qn(isNaN(t)?e:t)}function zS(t){return(t=+t)==1?xr:function(e,r){return r-e?DL(e,r,t):qn(isNaN(e)?r:e)}}function xr(t,e){var r=e-t;return r?kS(t,r):qn(isNaN(t)?e:t)}var Uf=(function t(e){var r=zS(e);function i(n,o){var s=r((n=Gr(n)).r,(o=Gr(o)).r),a=r(n.g,o.g),c=r(n.b,o.b),l=xr(n.opacity,o.opacity);return function(f){return n.r=s(f),n.g=a(f),n.b=c(f),n.opacity=l(f),n+""}}return i.gamma=t,i})(1);function WS(t){return function(e){var r=e.length,i=new Array(r),n=new Array(r),o=new Array(r),s,a;for(s=0;sr&&(o=e.slice(r,o),a[s]?a[s]+=o:a[++s]=o),(i=i[0])===(n=n[0])?a[s]?a[s]+=n:a[++s]=n:(a[++s]=null,c.push({i:s,x:qr(i,n)})),r=zg.lastIndex;return rRa(t[t.length-1]);var Wf=new Array(3).concat("e5f5f999d8c92ca25f","edf8fbb2e2e266c2a4238b45","edf8fbb2e2e266c2a42ca25f006d2c","edf8fbccece699d8c966c2a42ca25f006d2c","edf8fbccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45006d2c00441b").map(V),UL=X(Wf);var Vf=new Array(3).concat("e0ecf49ebcda8856a7","edf8fbb3cde38c96c688419d","edf8fbb3cde38c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d810f7c4d004b").map(V),zL=X(Vf);var jf=new Array(3).concat("e0f3dba8ddb543a2ca","f0f9e8bae4bc7bccc42b8cbe","f0f9e8bae4bc7bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe0868ac084081").map(V),WL=X(jf);var $f=new Array(3).concat("fee8c8fdbb84e34a33","fef0d9fdcc8afc8d59d7301f","fef0d9fdcc8afc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301fb300007f0000").map(V),VL=X($f);var Hf=new Array(3).concat("ece2f0a6bddb1c9099","f6eff7bdc9e167a9cf02818a","f6eff7bdc9e167a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016c59014636").map(V),jL=X(Hf);var Yf=new Array(3).concat("ece7f2a6bddb2b8cbe","f1eef6bdc9e174a9cf0570b0","f1eef6bdc9e174a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0045a8d023858").map(V),$L=X(Yf);var Xf=new Array(3).concat("e7e1efc994c7dd1c77","f1eef6d7b5d8df65b0ce1256","f1eef6d7b5d8df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125698004367001f").map(V),HL=X(Xf);var Gf=new Array(3).concat("fde0ddfa9fb5c51b8a","feebe2fbb4b9f768a1ae017e","feebe2fbb4b9f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a017749006a").map(V),YL=X(Gf);var qf=new Array(3).concat("edf8b17fcdbb2c7fb8","ffffcca1dab441b6c4225ea8","ffffcca1dab441b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea8253494081d58").map(V),XL=X(qf);var Kf=new Array(3).concat("f7fcb9addd8e31a354","ffffccc2e69978c679238443","ffffccc2e69978c67931a354006837","ffffccd9f0a3addd8e78c67931a354006837","ffffccd9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443006837004529").map(V),GL=X(Kf);var Zf=new Array(3).concat("fff7bcfec44fd95f0e","ffffd4fed98efe9929cc4c02","ffffd4fed98efe9929d95f0e993404","ffffd4fee391fec44ffe9929d95f0e993404","ffffd4fee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c02993404662506").map(V),qL=X(Zf);var Qf=new Array(3).concat("ffeda0feb24cf03b20","ffffb2fecc5cfd8d3ce31a1c","ffffb2fecc5cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cbd0026800026").map(V),KL=X(Qf);var Jf=new Array(3).concat("deebf79ecae13182bd","eff3ffbdd7e76baed62171b5","eff3ffbdd7e76baed63182bd08519c","eff3ffc6dbef9ecae16baed63182bd08519c","eff3ffc6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b508519c08306b").map(V),ZL=X(Jf);var eu=new Array(3).concat("e5f5e0a1d99b31a354","edf8e9bae4b374c476238b45","edf8e9bae4b374c47631a354006d2c","edf8e9c7e9c0a1d99b74c47631a354006d2c","edf8e9c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45006d2c00441b").map(V),QL=X(eu);var tu=new Array(3).concat("f0f0f0bdbdbd636363","f7f7f7cccccc969696525252","f7f7f7cccccc969696636363252525","f7f7f7d9d9d9bdbdbd969696636363252525","f7f7f7d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525000000").map(V),JL=X(tu);var ru=new Array(3).concat("efedf5bcbddc756bb1","f2f0f7cbc9e29e9ac86a51a3","f2f0f7cbc9e29e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a354278f3f007d").map(V),e6=X(ru);var iu=new Array(3).concat("fee0d2fc9272de2d26","fee5d9fcae91fb6a4acb181d","fee5d9fcae91fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181da50f1567000d").map(V),t6=X(iu);var nu=new Array(3).concat("fee6cefdae6be6550d","feeddefdbe85fd8d3cd94701","feeddefdbe85fd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d94801a636037f2704").map(V),r6=X(nu);var Vg=zf(ft(-100,.75,.35),ft(80,1.5,.8)),jg=zf(ft(260,.75,.35),ft(80,1.5,.8)),Aae=ft();function ou(t){var e=t.length;return function(r){return t[Math.max(0,Math.min(e-1,Math.floor(r*e)))]}}var $g=ou(V("44015444025645045745055946075a46085c460a5d460b5e470d60470e6147106347116447136548146748166848176948186a481a6c481b6d481c6e481d6f481f70482071482173482374482475482576482677482878482979472a7a472c7a472d7b472e7c472f7d46307e46327e46337f463480453581453781453882443983443a83443b84433d84433e85423f854240864241864142874144874045884046883f47883f48893e49893e4a893e4c8a3d4d8a3d4e8a3c4f8a3c508b3b518b3b528b3a538b3a548c39558c39568c38588c38598c375a8c375b8d365c8d365d8d355e8d355f8d34608d34618d33628d33638d32648e32658e31668e31678e31688e30698e306a8e2f6b8e2f6c8e2e6d8e2e6e8e2e6f8e2d708e2d718e2c718e2c728e2c738e2b748e2b758e2a768e2a778e2a788e29798e297a8e297b8e287c8e287d8e277e8e277f8e27808e26818e26828e26828e25838e25848e25858e24868e24878e23888e23898e238a8d228b8d228c8d228d8d218e8d218f8d21908d21918c20928c20928c20938c1f948c1f958b1f968b1f978b1f988b1f998a1f9a8a1e9b8a1e9c891e9d891f9e891f9f881fa0881fa1881fa1871fa28720a38620a48621a58521a68522a78522a88423a98324aa8325ab8225ac8226ad8127ad8128ae8029af7f2ab07f2cb17e2db27d2eb37c2fb47c31b57b32b67a34b67935b77937b87838b9773aba763bbb753dbc743fbc7340bd7242be7144bf7046c06f48c16e4ac16d4cc26c4ec36b50c46a52c56954c56856c66758c7655ac8645cc8635ec96260ca6063cb5f65cb5e67cc5c69cd5b6ccd5a6ece5870cf5773d05675d05477d1537ad1517cd2507fd34e81d34d84d44b86d54989d5488bd6468ed64590d74393d74195d84098d83e9bd93c9dd93ba0da39a2da37a5db36a8db34aadc32addc30b0dd2fb2dd2db5de2bb8de29bade28bddf26c0df25c2df23c5e021c8e020cae11fcde11dd0e11cd2e21bd5e21ad8e219dae319dde318dfe318e2e418e5e419e7e419eae51aece51befe51cf1e51df4e61ef6e620f8e621fbe723fde725")),Hg=ou(V("00000401000501010601010802010902020b02020d03030f03031204041405041606051806051a07061c08071e0907200a08220b09240c09260d0a290e0b2b100b2d110c2f120d31130d34140e36150e38160f3b180f3d19103f1a10421c10441d11471e114920114b21114e22115024125325125527125829115a2a115c2c115f2d11612f116331116533106734106936106b38106c390f6e3b0f703d0f713f0f72400f74420f75440f764510774710784910784a10794c117a4e117b4f127b51127c52137c54137d56147d57157e59157e5a167e5c167f5d177f5f187f601880621980641a80651a80671b80681c816a1c816b1d816d1d816e1e81701f81721f817320817521817621817822817922827b23827c23827e24828025828125818326818426818627818827818928818b29818c29818e2a81902a81912b81932b80942c80962c80982d80992d809b2e7f9c2e7f9e2f7fa02f7fa1307ea3307ea5317ea6317da8327daa337dab337cad347cae347bb0357bb2357bb3367ab5367ab73779b83779ba3878bc3978bd3977bf3a77c03a76c23b75c43c75c53c74c73d73c83e73ca3e72cc3f71cd4071cf4070d0416fd2426fd3436ed5446dd6456cd8456cd9466bdb476adc4869de4968df4a68e04c67e24d66e34e65e44f64e55064e75263e85362e95462ea5661eb5760ec5860ed5a5fee5b5eef5d5ef05f5ef1605df2625df2645cf3655cf4675cf4695cf56b5cf66c5cf66e5cf7705cf7725cf8745cf8765cf9785df9795df97b5dfa7d5efa7f5efa815ffb835ffb8560fb8761fc8961fc8a62fc8c63fc8e64fc9065fd9266fd9467fd9668fd9869fd9a6afd9b6bfe9d6cfe9f6dfea16efea36ffea571fea772fea973feaa74feac76feae77feb078feb27afeb47bfeb67cfeb77efeb97ffebb81febd82febf84fec185fec287fec488fec68afec88cfeca8dfecc8ffecd90fecf92fed194fed395fed597fed799fed89afdda9cfddc9efddea0fde0a1fde2a3fde3a5fde5a7fde7a9fde9aafdebacfcecaefceeb0fcf0b2fcf2b4fcf4b6fcf6b8fcf7b9fcf9bbfcfbbdfcfdbf")),Yg=ou(V("00000401000501010601010802010a02020c02020e03021004031204031405041706041907051b08051d09061f0a07220b07240c08260d08290e092b10092d110a30120a32140b34150b37160b39180c3c190c3e1b0c411c0c431e0c451f0c48210c4a230c4c240c4f260c51280b53290b552b0b572d0b592f0a5b310a5c320a5e340a5f3609613809623909633b09643d09653e0966400a67420a68440a68450a69470b6a490b6a4a0c6b4c0c6b4d0d6c4f0d6c510e6c520e6d540f6d550f6d57106e59106e5a116e5c126e5d126e5f136e61136e62146e64156e65156e67166e69166e6a176e6c186e6d186e6f196e71196e721a6e741a6e751b6e771c6d781c6d7a1d6d7c1d6d7d1e6d7f1e6c801f6c82206c84206b85216b87216b88226a8a226a8c23698d23698f24699025689225689326679526679727669827669a28659b29649d29649f2a63a02a63a22b62a32c61a52c60a62d60a82e5fa92e5eab2f5ead305dae305cb0315bb1325ab3325ab43359b63458b73557b93556ba3655bc3754bd3853bf3952c03a51c13a50c33b4fc43c4ec63d4dc73e4cc83f4bca404acb4149cc4248ce4347cf4446d04545d24644d34743d44842d54a41d74b3fd84c3ed94d3dda4e3cdb503bdd513ade5238df5337e05536e15635e25734e35933e45a31e55c30e65d2fe75e2ee8602de9612bea632aeb6429eb6628ec6726ed6925ee6a24ef6c23ef6e21f06f20f1711ff1731df2741cf3761bf37819f47918f57b17f57d15f67e14f68013f78212f78410f8850ff8870ef8890cf98b0bf98c0af98e09fa9008fa9207fa9407fb9606fb9706fb9906fb9b06fb9d07fc9f07fca108fca309fca50afca60cfca80dfcaa0ffcac11fcae12fcb014fcb216fcb418fbb61afbb81dfbba1ffbbc21fbbe23fac026fac228fac42afac62df9c72ff9c932f9cb35f8cd37f8cf3af7d13df7d340f6d543f6d746f5d949f5db4cf4dd4ff4df53f4e156f3e35af3e55df2e661f2e865f2ea69f1ec6df1ed71f1ef75f1f179f2f27df2f482f3f586f3f68af4f88ef5f992f6fa96f8fb9af9fc9dfafda1fcffa4")),Xg=ou(V("0d088710078813078916078a19068c1b068d1d068e20068f2206902406912605912805922a05932c05942e05952f059631059733059735049837049938049a3a049a3c049b3e049c3f049c41049d43039e44039e46039f48039f4903a04b03a14c02a14e02a25002a25102a35302a35502a45601a45801a45901a55b01a55c01a65e01a66001a66100a76300a76400a76600a76700a86900a86a00a86c00a86e00a86f00a87100a87201a87401a87501a87701a87801a87a02a87b02a87d03a87e03a88004a88104a78305a78405a78606a68707a68808a68a09a58b0aa58d0ba58e0ca48f0da4910ea3920fa39410a29511a19613a19814a099159f9a169f9c179e9d189d9e199da01a9ca11b9ba21d9aa31e9aa51f99a62098a72197a82296aa2395ab2494ac2694ad2793ae2892b02991b12a90b22b8fb32c8eb42e8db52f8cb6308bb7318ab83289ba3388bb3488bc3587bd3786be3885bf3984c03a83c13b82c23c81c33d80c43e7fc5407ec6417dc7427cc8437bc9447aca457acb4679cc4778cc4977cd4a76ce4b75cf4c74d04d73d14e72d24f71d35171d45270d5536fd5546ed6556dd7566cd8576bd9586ada5a6ada5b69db5c68dc5d67dd5e66de5f65de6164df6263e06363e16462e26561e26660e3685fe4695ee56a5de56b5de66c5ce76e5be76f5ae87059e97158e97257ea7457eb7556eb7655ec7754ed7953ed7a52ee7b51ef7c51ef7e50f07f4ff0804ef1814df1834cf2844bf3854bf3874af48849f48948f58b47f58c46f68d45f68f44f79044f79143f79342f89441f89540f9973ff9983ef99a3efa9b3dfa9c3cfa9e3bfb9f3afba139fba238fca338fca537fca636fca835fca934fdab33fdac33fdae32fdaf31fdb130fdb22ffdb42ffdb52efeb72dfeb82cfeba2cfebb2bfebd2afebe2afec029fdc229fdc328fdc527fdc627fdc827fdca26fdcb26fccd25fcce25fcd025fcd225fbd324fbd524fbd724fad824fada24f9dc24f9dd25f8df25f8e125f7e225f7e425f6e626f6e826f5e926f5eb27f4ed27f3ee27f3f027f2f227f1f426f1f525f0f724f0f921"));function ut(t,e){return t==null||e==null?NaN:te?1:t>=e?0:NaN}function Kt(t,e){return t==null||e==null?NaN:et?1:e>=t?0:NaN}function su(t){let e,r,i;t.length!==2?(e=ut,r=(a,c)=>ut(t(a),c),i=(a,c)=>t(a)-c):(e=t===ut||t===Kt?t:i6,r=t,i=t);function n(a,c,l=0,f=a.length){if(l>>1;r(a[u],c)<0?l=u+1:f=u}while(l>>1;r(a[u],c)<=0?l=u+1:f=u}while(ll&&i(a[u-1],c)>-i(a[u],c)?u-1:u}return{left:n,center:s,right:o}}function i6(){return 0}function Gg(t){return t===null?NaN:+t}var qS=su(ut),KS=qS.right,qg=qS.left,n6=su(Gg).center,Kg=KS;function Kn(t,e){let r,i;if(e===void 0)for(let n of t)n!=null&&(r===void 0?n>=n&&(r=i=n):(r>n&&(r=n),i=o&&(r=i=o):(r>o&&(r=o),i0){for(s=e[--r];r>0&&(i=s,n=e[--r],s=i+n,o=n-(s-i),!o););r>0&&(o<0&&e[r-1]<0||o>0&&e[r-1]>0)&&(n=o*2,i=s+n,n==i-s&&(s=i))}return s}};var au=class extends Map{constructor(e,r=a6){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:r}}),e!=null)for(let[i,n]of e)this.set(i,n)}get(e){return super.get(ZS(this,e))}has(e){return super.has(ZS(this,e))}set(e,r){return super.set(o6(this,e),r)}delete(e){return super.delete(s6(this,e))}};function ZS({_intern:t,_key:e},r){let i=e(r);return t.has(i)?t.get(i):r}function o6({_intern:t,_key:e},r){let i=e(r);return t.has(i)?t.get(i):(t.set(i,r),r)}function s6({_intern:t,_key:e},r){let i=e(r);return t.has(i)&&(r=t.get(i),t.delete(i)),r}function a6(t){return t!==null&&typeof t=="object"?t.valueOf():t}function Zg(t){return t}function Pa(t,e,...r){return c6(t,Zg,e,r)}function c6(t,e,r,i){return(function n(o,s){if(s>=i.length)return r(o);let a=new au,c=i[s++],l=-1;for(let f of o){let u=c(f,++l,o),d=a.get(u);d?d.push(f):a.set(u,[f])}for(let[f,u]of a)a.set(f,n(u,s));return e(a)})(t,0)}var l6=Math.sqrt(50),f6=Math.sqrt(10),u6=Math.sqrt(2);function cu(t,e,r){let i=(e-t)/Math.max(0,r),n=Math.floor(Math.log10(i)),o=i/Math.pow(10,n),s=o>=l6?10:o>=f6?5:o>=u6?2:1,a,c,l;return n<0?(l=Math.pow(10,-n)/s,a=Math.round(t*l),c=Math.round(e*l),a/le&&--c,l=-l):(l=Math.pow(10,n)*s,a=Math.round(t/l),c=Math.round(e/l),a*le&&--c),c0))return[];if(t===e)return[t];let i=e=n))return[];let a=o-n+1,c=new Array(a);if(i)if(s<0)for(let l=0;li||r===void 0&&i>=i)&&(r=i);else{let i=-1;for(let n of t)(n=e(n,++i,t))!=null&&(r>n||r===void 0&&n>=n)&&(r=n)}return r}function Ia(t,e,r){t=+t,e=+e,r=(n=arguments.length)<2?(e=t,t=0,1):n<3?1:+r;for(var i=-1,n=Math.max(0,Math.ceil((e-t)/r))|0,o=new Array(n);++ie&&(r=t,t=e,e=r),function(i){return Math.max(t,Math.min(e,i))}}function h6(t,e,r){var i=t[0],n=t[1],o=e[0],s=e[1];return n2?p6:h6,c=l=null,u}function u(d){return d==null||isNaN(d=+d)?o:(c||(c=a(t.map(i),e,r)))(i(s(d)))}return u.invert=function(d){return s(n((l||(l=a(e,t.map(i),qr)))(d)))},u.domain=function(d){return arguments.length?(t=Array.from(d,tm),f()):t.slice()},u.range=function(d){return arguments.length?(e=Array.from(d),f()):e.slice()},u.rangeRound=function(d){return e=Array.from(d),r=Ca,f()},u.clamp=function(d){return arguments.length?(s=d?!0:$e,f()):s!==$e},u.interpolate=function(d){return arguments.length?(r=d,f()):r},u.unknown=function(d){return arguments.length?(o=d,u):o},function(d,h){return i=d,n=h,f()}}function nm(){return im()($e,$e)}function JS(t){return Math.abs(t=Math.round(t))>=1e21?t.toLocaleString("en").replace(/,/g,""):t.toString(10)}function Vi(t,e){if(!isFinite(t)||t===0)return null;var r=(t=e?t.toExponential(e-1):t.toExponential()).indexOf("e"),i=t.slice(0,r);return[i.length>1?i[0]+i.slice(2):i,+t.slice(r+1)]}function Zt(t){return t=Vi(Math.abs(t)),t?t[1]:NaN}function eA(t,e){return function(r,i){for(var n=r.length,o=[],s=0,a=t[0],c=0;n>0&&a>0&&(c+a+1>i&&(a=Math.max(1,i-c)),o.push(r.substring(n-=a,n+a)),!((c+=a+1)>i));)a=t[s=(s+1)%t.length];return o.reverse().join(e)}}function tA(t){return function(e){return e.replace(/[0-9]/g,function(r){return t[+r]})}}var g6=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function Kr(t){if(!(e=g6.exec(t)))throw new Error("invalid format: "+t);var e;return new du({fill:e[1],align:e[2],sign:e[3],symbol:e[4],zero:e[5],width:e[6],comma:e[7],precision:e[8]&&e[8].slice(1),trim:e[9],type:e[10]})}Kr.prototype=du.prototype;function du(t){this.fill=t.fill===void 0?" ":t.fill+"",this.align=t.align===void 0?">":t.align+"",this.sign=t.sign===void 0?"-":t.sign+"",this.symbol=t.symbol===void 0?"":t.symbol+"",this.zero=!!t.zero,this.width=t.width===void 0?void 0:+t.width,this.comma=!!t.comma,this.precision=t.precision===void 0?void 0:+t.precision,this.trim=!!t.trim,this.type=t.type===void 0?"":t.type+""}du.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(this.width===void 0?"":Math.max(1,this.width|0))+(this.comma?",":"")+(this.precision===void 0?"":"."+Math.max(0,this.precision|0))+(this.trim?"~":"")+this.type};function rA(t){e:for(var e=t.length,r=1,i=-1,n;r0&&(i=0);break}return i>0?t.slice(0,i)+t.slice(n+1):t}var Oa;function iA(t,e){var r=Vi(t,e);if(!r)return Oa=void 0,t.toPrecision(e);var i=r[0],n=r[1],o=n-(Oa=Math.max(-8,Math.min(8,Math.floor(n/3)))*3)+1,s=i.length;return o===s?i:o>s?i+new Array(o-s+1).join("0"):o>0?i.slice(0,o)+"."+i.slice(o):"0."+new Array(1-o).join("0")+Vi(t,Math.max(0,e+o-1))[0]}function om(t,e){var r=Vi(t,e);if(!r)return t+"";var i=r[0],n=r[1];return n<0?"0."+new Array(-n).join("0")+i:i.length>n+1?i.slice(0,n+1)+"."+i.slice(n+1):i+new Array(n-i.length+2).join("0")}var sm={"%":(t,e)=>(t*100).toFixed(e),b:t=>Math.round(t).toString(2),c:t=>t+"",d:JS,e:(t,e)=>t.toExponential(e),f:(t,e)=>t.toFixed(e),g:(t,e)=>t.toPrecision(e),o:t=>Math.round(t).toString(8),p:(t,e)=>om(t*100,e),r:om,s:iA,X:t=>Math.round(t).toString(16).toUpperCase(),x:t=>Math.round(t).toString(16)};function am(t){return t}var nA=Array.prototype.map,oA=["y","z","a","f","p","n","\xB5","m","","k","M","G","T","P","E","Z","Y"];function sA(t){var e=t.grouping===void 0||t.thousands===void 0?am:eA(nA.call(t.grouping,Number),t.thousands+""),r=t.currency===void 0?"":t.currency[0]+"",i=t.currency===void 0?"":t.currency[1]+"",n=t.decimal===void 0?".":t.decimal+"",o=t.numerals===void 0?am:tA(nA.call(t.numerals,String)),s=t.percent===void 0?"%":t.percent+"",a=t.minus===void 0?"\u2212":t.minus+"",c=t.nan===void 0?"NaN":t.nan+"";function l(u,d){u=Kr(u);var h=u.fill,p=u.align,g=u.sign,m=u.symbol,_=u.zero,T=u.width,y=u.comma,x=u.precision,w=u.trim,b=u.type;b==="n"?(y=!0,b="g"):sm[b]||(x===void 0&&(x=12),w=!0,b="g"),(_||h==="0"&&p==="=")&&(_=!0,h="0",p="=");var E=(d&&d.prefix!==void 0?d.prefix:"")+(m==="$"?r:m==="#"&&/[boxX]/.test(b)?"0"+b.toLowerCase():""),S=(m==="$"?i:/[%p]/.test(b)?s:"")+(d&&d.suffix!==void 0?d.suffix:""),A=sm[b],C=/[defgprs%]/.test(b);x=x===void 0?6:/[gprs]/.test(b)?Math.max(1,Math.min(21,x)):Math.max(0,Math.min(20,x));function I(R){var N=E,O=S,W,G,L;if(b==="c")O=A(R)+O,R="";else{R=+R;var H=R<0||1/R<0;if(R=isNaN(R)?c:A(Math.abs(R),x),w&&(R=rA(R)),H&&+R==0&&g!=="+"&&(H=!1),N=(H?g==="("?g:a:g==="-"||g==="("?"":g)+N,O=(b==="s"&&!isNaN(R)&&Oa!==void 0?oA[8+Oa/3]:"")+O+(H&&g==="("?")":""),C){for(W=-1,G=R.length;++WL||L>57){O=(L===46?n+R.slice(W+1):R.slice(W))+O,R=R.slice(0,W);break}}}y&&!_&&(R=e(R,1/0));var Re=N.length+R.length+O.length,We=Re>1)+N+R+O+We.slice(Re);break;default:R=We+N+R+O;break}return o(R)}return I.toString=function(){return u+""},I}function f(u,d){var h=Math.max(-8,Math.min(8,Math.floor(Zt(d)/3)))*3,p=Math.pow(10,-h),g=l((u=Kr(u),u.type="f",u),{suffix:oA[8+h/3]});return function(m){return g(p*m)}}return{format:l,formatPrefix:f}}var hu,pu,gu;cm({thousands:",",grouping:[3],currency:["$",""]});function cm(t){return hu=sA(t),pu=hu.format,gu=hu.formatPrefix,hu}function lm(t){return Math.max(0,-Zt(Math.abs(t)))}function fm(t,e){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(Zt(e)/3)))*3-Zt(Math.abs(t)))}function um(t,e){return t=Math.abs(t),e=Math.abs(e)-t,Math.max(0,Zt(e)-Zt(t))+1}function dm(t,e,r,i){var n=Qg(t,e,r),o;switch(i=Kr(i??",f"),i.type){case"s":{var s=Math.max(Math.abs(t),Math.abs(e));return i.precision==null&&!isNaN(o=fm(n,s))&&(i.precision=o),gu(i,s)}case"":case"e":case"g":case"p":case"r":{i.precision==null&&!isNaN(o=um(n,Math.max(Math.abs(t),Math.abs(e))))&&(i.precision=o-(i.type==="e"));break}case"f":case"%":{i.precision==null&&!isNaN(o=lm(n))&&(i.precision=o-(i.type==="%")*2);break}}return pu(i)}function Na(t){var e=t.domain;return t.ticks=function(r){var i=e();return lu(i[0],i[i.length-1],r??10)},t.tickFormat=function(r,i){var n=e();return dm(n[0],n[n.length-1],r??10,i)},t.nice=function(r){r==null&&(r=10);var i=e(),n=0,o=i.length-1,s=i[n],a=i[o],c,l,f=10;for(a0;){if(l=Ma(s,a,r),l===c)return i[n]=s,i[o]=a,e(i);if(l>0)s=Math.floor(s/l)*l,a=Math.ceil(a/l)*l;else if(l<0)s=Math.ceil(s*l)/l,a=Math.floor(a*l)/l;else break;c=l}return t},t}function Da(){var t=nm();return t.copy=function(){return uu(t,Da())},fu.apply(t,arguments),Na(t)}function aA(t){return function(e){return e<0?-Math.pow(-e,t):Math.pow(e,t)}}function m6(t){return t<0?-Math.sqrt(-t):Math.sqrt(t)}function _6(t){return t<0?-t*t:t*t}function hm(t){var e=t($e,$e),r=1;function i(){return r===1?t($e,$e):r===.5?t(m6,_6):t(aA(r),aA(1/r))}return e.exponent=function(n){return arguments.length?(r=+n,i()):r},Na(e)}function Qn(){var t=hm(im());return t.copy=function(){return uu(t,Qn()).exponent(t.exponent())},fu.apply(t,arguments),t}function pm(){return Qn.apply(null,arguments).exponent(.5)}var gm=new Date,mm=new Date;function ne(t,e,r,i){function n(o){return t(o=arguments.length===0?new Date:new Date(+o)),o}return n.floor=o=>(t(o=new Date(+o)),o),n.ceil=o=>(t(o=new Date(o-1)),e(o,1),t(o),o),n.round=o=>{let s=n(o),a=n.ceil(o);return o-s(e(o=new Date(+o),s==null?1:Math.floor(s)),o),n.range=(o,s,a)=>{let c=[];if(o=n.ceil(o),a=a==null?1:Math.floor(a),!(o0))return c;let l;do c.push(l=new Date(+o)),e(o,a),t(o);while(lne(s=>{if(s>=s)for(;t(s),!o(s);)s.setTime(s-1)},(s,a)=>{if(s>=s)if(a<0)for(;++a<=0;)for(;e(s,-1),!o(s););else for(;--a>=0;)for(;e(s,1),!o(s););}),r&&(n.count=(o,s)=>(gm.setTime(+o),mm.setTime(+s),t(gm),t(mm),Math.floor(r(gm,mm))),n.every=o=>(o=Math.floor(o),!isFinite(o)||!(o>0)?null:o>1?n.filter(i?s=>i(s)%o===0:s=>n.count(0,s)%o===0):n)),n}var La=ne(t=>{t.setTime(t-t.getMilliseconds())},(t,e)=>{t.setTime(+t+e*1e3)},(t,e)=>(e-t)/1e3,t=>t.getUTCSeconds()),cA=La.range;var mu=ne(t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*1e3)},(t,e)=>{t.setTime(+t+e*6e4)},(t,e)=>(e-t)/6e4,t=>t.getMinutes()),y6=mu.range,lA=ne(t=>{t.setUTCSeconds(0,0)},(t,e)=>{t.setTime(+t+e*6e4)},(t,e)=>(e-t)/6e4,t=>t.getUTCMinutes()),x6=lA.range;var _u=ne(t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*1e3-t.getMinutes()*6e4)},(t,e)=>{t.setTime(+t+e*36e5)},(t,e)=>(e-t)/36e5,t=>t.getHours()),b6=_u.range,fA=ne(t=>{t.setUTCMinutes(0,0,0)},(t,e)=>{t.setTime(+t+e*36e5)},(t,e)=>(e-t)/36e5,t=>t.getUTCHours()),T6=fA.range;var ji=ne(t=>t.setHours(0,0,0,0),(t,e)=>t.setDate(t.getDate()+e),(t,e)=>(e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*6e4)/864e5,t=>t.getDate()-1),w6=ji.range,Fa=ne(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/864e5,t=>t.getUTCDate()-1),S6=Fa.range,uA=ne(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/864e5,t=>Math.floor(t/864e5)),A6=uA.range;function $i(t){return ne(e=>{e.setDate(e.getDate()-(e.getDay()+7-t)%7),e.setHours(0,0,0,0)},(e,r)=>{e.setDate(e.getDate()+r*7)},(e,r)=>(r-e-(r.getTimezoneOffset()-e.getTimezoneOffset())*6e4)/6048e5)}var eo=$i(0),to=$i(1),dA=$i(2),hA=$i(3),Zr=$i(4),pA=$i(5),gA=$i(6),mA=eo.range,E6=to.range,R6=dA.range,C6=hA.range,P6=Zr.range,M6=pA.range,I6=gA.range;function Hi(t){return ne(e=>{e.setUTCDate(e.getUTCDate()-(e.getUTCDay()+7-t)%7),e.setUTCHours(0,0,0,0)},(e,r)=>{e.setUTCDate(e.getUTCDate()+r*7)},(e,r)=>(r-e)/6048e5)}var Ba=Hi(0),ro=Hi(1),_A=Hi(2),yA=Hi(3),Qr=Hi(4),xA=Hi(5),bA=Hi(6),TA=Ba.range,O6=ro.range,N6=_A.range,D6=yA.range,L6=Qr.range,F6=xA.range,B6=bA.range;var yu=ne(t=>{t.setDate(1),t.setHours(0,0,0,0)},(t,e)=>{t.setMonth(t.getMonth()+e)},(t,e)=>e.getMonth()-t.getMonth()+(e.getFullYear()-t.getFullYear())*12,t=>t.getMonth()),k6=yu.range,wA=ne(t=>{t.setUTCDate(1),t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCMonth(t.getUTCMonth()+e)},(t,e)=>e.getUTCMonth()-t.getUTCMonth()+(e.getUTCFullYear()-t.getUTCFullYear())*12,t=>t.getUTCMonth()),U6=wA.range;var Rt=ne(t=>{t.setMonth(0,1),t.setHours(0,0,0,0)},(t,e)=>{t.setFullYear(t.getFullYear()+e)},(t,e)=>e.getFullYear()-t.getFullYear(),t=>t.getFullYear());Rt.every=t=>!isFinite(t=Math.floor(t))||!(t>0)?null:ne(e=>{e.setFullYear(Math.floor(e.getFullYear()/t)*t),e.setMonth(0,1),e.setHours(0,0,0,0)},(e,r)=>{e.setFullYear(e.getFullYear()+r*t)});var z6=Rt.range,wr=ne(t=>{t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCFullYear(t.getUTCFullYear()+e)},(t,e)=>e.getUTCFullYear()-t.getUTCFullYear(),t=>t.getUTCFullYear());wr.every=t=>!isFinite(t=Math.floor(t))||!(t>0)?null:ne(e=>{e.setUTCFullYear(Math.floor(e.getUTCFullYear()/t)*t),e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0)},(e,r)=>{e.setUTCFullYear(e.getUTCFullYear()+r*t)});var W6=wr.range;function bm(t){if(0<=t.y&&t.y<100){var e=new Date(-1,t.m,t.d,t.H,t.M,t.S,t.L);return e.setFullYear(t.y),e}return new Date(t.y,t.m,t.d,t.H,t.M,t.S,t.L)}function Tm(t){if(0<=t.y&&t.y<100){var e=new Date(Date.UTC(-1,t.m,t.d,t.H,t.M,t.S,t.L));return e.setUTCFullYear(t.y),e}return new Date(Date.UTC(t.y,t.m,t.d,t.H,t.M,t.S,t.L))}function ka(t,e,r){return{y:t,m:e,d:r,H:0,M:0,S:0,L:0}}function wm(t){var e=t.dateTime,r=t.date,i=t.time,n=t.periods,o=t.days,s=t.shortDays,a=t.months,c=t.shortMonths,l=Ua(n),f=za(n),u=Ua(o),d=za(o),h=Ua(s),p=za(s),g=Ua(a),m=za(a),_=Ua(c),T=za(c),y={a:L,A:H,b:Re,B:We,c:null,d:CA,e:CA,f:fF,g:bF,G:wF,H:aF,I:cF,j:lF,L:NA,m:uF,M:dF,p:l2,q:f2,Q:IA,s:OA,S:hF,u:pF,U:gF,V:mF,w:_F,W:yF,x:null,X:null,y:xF,Y:TF,Z:SF,"%":MA},x={a:u2,A:d2,b:h2,B:p2,c:null,d:PA,e:PA,f:RF,g:BF,G:UF,H:AF,I:vF,j:EF,L:LA,m:CF,M:PF,p:g2,q:m2,Q:IA,s:OA,S:MF,u:IF,U:OF,V:NF,w:DF,W:LF,x:null,X:null,y:FF,Y:kF,Z:zF,"%":MA},w={a:C,A:I,b:R,B:N,c:O,d:EA,e:EA,f:iF,g:vA,G:AA,H:RA,I:RA,j:J6,L:rF,m:Q6,M:eF,p:A,q:Z6,Q:oF,s:sF,S:tF,u:Y6,U:X6,V:G6,w:H6,W:q6,x:W,X:G,y:vA,Y:AA,Z:K6,"%":nF};y.x=b(r,y),y.X=b(i,y),y.c=b(e,y),x.x=b(r,x),x.X=b(i,x),x.c=b(e,x);function b(D,Y){return function(K){var M=[],Ve=-1,re=0,Ye=D.length,Xe,ii,Qm;for(K instanceof Date||(K=new Date(+K));++Ve53)return null;"w"in M||(M.w=1),"Z"in M?(re=Tm(ka(M.y,0,1)),Ye=re.getUTCDay(),re=Ye>4||Ye===0?ro.ceil(re):ro(re),re=Fa.offset(re,(M.V-1)*7),M.y=re.getUTCFullYear(),M.m=re.getUTCMonth(),M.d=re.getUTCDate()+(M.w+6)%7):(re=bm(ka(M.y,0,1)),Ye=re.getDay(),re=Ye>4||Ye===0?to.ceil(re):to(re),re=ji.offset(re,(M.V-1)*7),M.y=re.getFullYear(),M.m=re.getMonth(),M.d=re.getDate()+(M.w+6)%7)}else("W"in M||"U"in M)&&("w"in M||(M.w="u"in M?M.u%7:"W"in M?1:0),Ye="Z"in M?Tm(ka(M.y,0,1)).getUTCDay():bm(ka(M.y,0,1)).getDay(),M.m=0,M.d="W"in M?(M.w+6)%7+M.W*7-(Ye+5)%7:M.w+M.U*7-(Ye+6)%7);return"Z"in M?(M.H+=M.Z/100|0,M.M+=M.Z%100,Tm(M)):bm(M)}}function S(D,Y,K,M){for(var Ve=0,re=Y.length,Ye=K.length,Xe,ii;Ve=Ye)return-1;if(Xe=Y.charCodeAt(Ve++),Xe===37){if(Xe=Y.charAt(Ve++),ii=w[Xe in SA?Y.charAt(Ve++):Xe],!ii||(M=ii(D,K,M))<0)return-1}else if(Xe!=K.charCodeAt(M++))return-1}return M}function A(D,Y,K){var M=l.exec(Y.slice(K));return M?(D.p=f.get(M[0].toLowerCase()),K+M[0].length):-1}function C(D,Y,K){var M=h.exec(Y.slice(K));return M?(D.w=p.get(M[0].toLowerCase()),K+M[0].length):-1}function I(D,Y,K){var M=u.exec(Y.slice(K));return M?(D.w=d.get(M[0].toLowerCase()),K+M[0].length):-1}function R(D,Y,K){var M=_.exec(Y.slice(K));return M?(D.m=T.get(M[0].toLowerCase()),K+M[0].length):-1}function N(D,Y,K){var M=g.exec(Y.slice(K));return M?(D.m=m.get(M[0].toLowerCase()),K+M[0].length):-1}function O(D,Y,K){return S(D,e,Y,K)}function W(D,Y,K){return S(D,r,Y,K)}function G(D,Y,K){return S(D,i,Y,K)}function L(D){return s[D.getDay()]}function H(D){return o[D.getDay()]}function Re(D){return c[D.getMonth()]}function We(D){return a[D.getMonth()]}function l2(D){return n[+(D.getHours()>=12)]}function f2(D){return 1+~~(D.getMonth()/3)}function u2(D){return s[D.getUTCDay()]}function d2(D){return o[D.getUTCDay()]}function h2(D){return c[D.getUTCMonth()]}function p2(D){return a[D.getUTCMonth()]}function g2(D){return n[+(D.getUTCHours()>=12)]}function m2(D){return 1+~~(D.getUTCMonth()/3)}return{format:function(D){var Y=b(D+="",y);return Y.toString=function(){return D},Y},parse:function(D){var Y=E(D+="",!1);return Y.toString=function(){return D},Y},utcFormat:function(D){var Y=b(D+="",x);return Y.toString=function(){return D},Y},utcParse:function(D){var Y=E(D+="",!0);return Y.toString=function(){return D},Y}}}var SA={"-":"",_:" ",0:"0"},be=/^\s*\d+/,V6=/^%/,j6=/[\\^$*+?|[\]().{}]/g;function Z(t,e,r){var i=t<0?"-":"",n=(i?-t:t)+"",o=n.length;return i+(o[e.toLowerCase(),r]))}function H6(t,e,r){var i=be.exec(e.slice(r,r+1));return i?(t.w=+i[0],r+i[0].length):-1}function Y6(t,e,r){var i=be.exec(e.slice(r,r+1));return i?(t.u=+i[0],r+i[0].length):-1}function X6(t,e,r){var i=be.exec(e.slice(r,r+2));return i?(t.U=+i[0],r+i[0].length):-1}function G6(t,e,r){var i=be.exec(e.slice(r,r+2));return i?(t.V=+i[0],r+i[0].length):-1}function q6(t,e,r){var i=be.exec(e.slice(r,r+2));return i?(t.W=+i[0],r+i[0].length):-1}function AA(t,e,r){var i=be.exec(e.slice(r,r+4));return i?(t.y=+i[0],r+i[0].length):-1}function vA(t,e,r){var i=be.exec(e.slice(r,r+2));return i?(t.y=+i[0]+(+i[0]>68?1900:2e3),r+i[0].length):-1}function K6(t,e,r){var i=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(e.slice(r,r+6));return i?(t.Z=i[1]?0:-(i[2]+(i[3]||"00")),r+i[0].length):-1}function Z6(t,e,r){var i=be.exec(e.slice(r,r+1));return i?(t.q=i[0]*3-3,r+i[0].length):-1}function Q6(t,e,r){var i=be.exec(e.slice(r,r+2));return i?(t.m=i[0]-1,r+i[0].length):-1}function EA(t,e,r){var i=be.exec(e.slice(r,r+2));return i?(t.d=+i[0],r+i[0].length):-1}function J6(t,e,r){var i=be.exec(e.slice(r,r+3));return i?(t.m=0,t.d=+i[0],r+i[0].length):-1}function RA(t,e,r){var i=be.exec(e.slice(r,r+2));return i?(t.H=+i[0],r+i[0].length):-1}function eF(t,e,r){var i=be.exec(e.slice(r,r+2));return i?(t.M=+i[0],r+i[0].length):-1}function tF(t,e,r){var i=be.exec(e.slice(r,r+2));return i?(t.S=+i[0],r+i[0].length):-1}function rF(t,e,r){var i=be.exec(e.slice(r,r+3));return i?(t.L=+i[0],r+i[0].length):-1}function iF(t,e,r){var i=be.exec(e.slice(r,r+6));return i?(t.L=Math.floor(i[0]/1e3),r+i[0].length):-1}function nF(t,e,r){var i=V6.exec(e.slice(r,r+1));return i?r+i[0].length:-1}function oF(t,e,r){var i=be.exec(e.slice(r));return i?(t.Q=+i[0],r+i[0].length):-1}function sF(t,e,r){var i=be.exec(e.slice(r));return i?(t.s=+i[0],r+i[0].length):-1}function CA(t,e){return Z(t.getDate(),e,2)}function aF(t,e){return Z(t.getHours(),e,2)}function cF(t,e){return Z(t.getHours()%12||12,e,2)}function lF(t,e){return Z(1+ji.count(Rt(t),t),e,3)}function NA(t,e){return Z(t.getMilliseconds(),e,3)}function fF(t,e){return NA(t,e)+"000"}function uF(t,e){return Z(t.getMonth()+1,e,2)}function dF(t,e){return Z(t.getMinutes(),e,2)}function hF(t,e){return Z(t.getSeconds(),e,2)}function pF(t){var e=t.getDay();return e===0?7:e}function gF(t,e){return Z(eo.count(Rt(t)-1,t),e,2)}function DA(t){var e=t.getDay();return e>=4||e===0?Zr(t):Zr.ceil(t)}function mF(t,e){return t=DA(t),Z(Zr.count(Rt(t),t)+(Rt(t).getDay()===4),e,2)}function _F(t){return t.getDay()}function yF(t,e){return Z(to.count(Rt(t)-1,t),e,2)}function xF(t,e){return Z(t.getFullYear()%100,e,2)}function bF(t,e){return t=DA(t),Z(t.getFullYear()%100,e,2)}function TF(t,e){return Z(t.getFullYear()%1e4,e,4)}function wF(t,e){var r=t.getDay();return t=r>=4||r===0?Zr(t):Zr.ceil(t),Z(t.getFullYear()%1e4,e,4)}function SF(t){var e=t.getTimezoneOffset();return(e>0?"-":(e*=-1,"+"))+Z(e/60|0,"0",2)+Z(e%60,"0",2)}function PA(t,e){return Z(t.getUTCDate(),e,2)}function AF(t,e){return Z(t.getUTCHours(),e,2)}function vF(t,e){return Z(t.getUTCHours()%12||12,e,2)}function EF(t,e){return Z(1+Fa.count(wr(t),t),e,3)}function LA(t,e){return Z(t.getUTCMilliseconds(),e,3)}function RF(t,e){return LA(t,e)+"000"}function CF(t,e){return Z(t.getUTCMonth()+1,e,2)}function PF(t,e){return Z(t.getUTCMinutes(),e,2)}function MF(t,e){return Z(t.getUTCSeconds(),e,2)}function IF(t){var e=t.getUTCDay();return e===0?7:e}function OF(t,e){return Z(Ba.count(wr(t)-1,t),e,2)}function FA(t){var e=t.getUTCDay();return e>=4||e===0?Qr(t):Qr.ceil(t)}function NF(t,e){return t=FA(t),Z(Qr.count(wr(t),t)+(wr(t).getUTCDay()===4),e,2)}function DF(t){return t.getUTCDay()}function LF(t,e){return Z(ro.count(wr(t)-1,t),e,2)}function FF(t,e){return Z(t.getUTCFullYear()%100,e,2)}function BF(t,e){return t=FA(t),Z(t.getUTCFullYear()%100,e,2)}function kF(t,e){return Z(t.getUTCFullYear()%1e4,e,4)}function UF(t,e){var r=t.getUTCDay();return t=r>=4||r===0?Qr(t):Qr.ceil(t),Z(t.getUTCFullYear()%1e4,e,4)}function zF(){return"+0000"}function MA(){return"%"}function IA(t){return+t}function OA(t){return Math.floor(+t/1e3)}var io,Ee,Jr,BA,kA;Sm({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});function Sm(t){return io=wm(t),Ee=io.format,Jr=io.parse,BA=io.utcFormat,kA=io.utcParse,io}function UA(){var t=0,e=1,r,i,n,o,s=$e,a=!1,c;function l(u){return u==null||isNaN(u=+u)?c:s(n===0?.5:(u=(o(u)-r)*n,a?Math.max(0,Math.min(1,u)):u))}l.domain=function(u){return arguments.length?([t,e]=u,r=o(t=+t),i=o(e=+e),n=r===i?0:1/(i-r),l):[t,e]},l.clamp=function(u){return arguments.length?(a=!!u,l):a},l.interpolator=function(u){return arguments.length?(s=u,l):s};function f(u){return function(d){var h,p;return arguments.length?([h,p]=d,s=u(h,p),l):[s(0),s(1)]}}return l.range=f(br),l.rangeRound=f(Ca),l.unknown=function(u){return arguments.length?(c=u,l):c},function(u){return o=u,r=u(t),i=u(e),n=r===i?0:1/(i-r),l}}function zA(t,e){return e.domain(t.domain()).interpolator(t.interpolator()).clamp(t.clamp()).unknown(t.unknown())}function Wa(){var t=Na(UA()($e));return t.copy=function(){return zA(t,Wa())},Jg.apply(t,arguments)}function xu(){var t=hm(UA());return t.copy=function(){return zA(t,xu()).exponent(t.exponent())},Jg.apply(t,arguments)}var WF="#fff",VF=.4,Cm="rgba(240,240,240,0.5)",jF=[Cm,"#137CBD"],$F="rgba(220,220,220,0.5)",HF=[Cm,"#f6654e"],YF=[Cm,"#00a9cc"],XF=[255,255,255,255];function GF(t){return Math.round(t*255)}function WA(t,e){let r=Et(t);if(!r)return console.warn("Invalid color: ",t),`rgba(255, 255, 255, ${e})`;let i=r.rgb();return`rgba(${i.r}, ${i.g}, ${i.b}, ${e})`}function dt(t){if(Array.isArray(t))return t;let e=Et(t);if(!e)return console.warn("Invalid color: ",t),XF;let r=e.rgb();return[Math.floor(r.r),Math.floor(r.g),Math.floor(r.b),GF(e.opacity)]}function Qt(t,e){return t?dt(t):typeof e=="string"?dt(e):e}var Te=t=>t[t.length-1],vm;(function(t){t.primary="#162d3c"})(vm||(vm={}));var VA=20,no=t=>Ia(0,VA+1).map(e=>t(e/VA)).reverse(),Em="rgba(240,240,240,0.5)",qF=[Em,vm.primary],KF=["#f7feae","#b7e6a5","#7ccba2","#46aea0","#089099","#00718b","#045275"],ZF=["#d3f2a3","#97e196","#6cc08b","#4c9b82","#217a79","#105965","#074050"],jA=["#d1eeea","#a8dbd9","#85c4c9","#68abb8","#4f90a6","#3b738f","#2a5674"],QF=jA,$A={Blues:Te(Jf),BluGrn:["#c4e6c3","#96d2a4","#6dbc90","#4da284","#36877a","#266b6e","#1d4f60"],BluYl:KF,BrwnYl:["#ede5cf","#e0c2a2","#d39c83","#c1766f","#a65461","#813753","#541f3f"],BuGn:Te(Wf),BuPu:Te(Vf),Burg:["#ffc6c4","#f4a3a8","#e38191","#cc607d","#ad466c","#8b3058","#672044"],BurgYl:["#fbe6c5","#f5ba98","#ee8a82","#dc7176","#c8586c","#9c3f5d","#70284a"],Cool:no(jg),DarkMint:["#d2fbd4","#a5dbc2","#7bbcb0","#559c9e","#3a7c89","#235d72","#123f5a"],Emrld:ZF,GnBu:Te(jf),Grayish:qF,Greens:Te(eu),Greys:Te(tu),Inferno:no(Yg),Magenta:["#f3cbd3","#eaa9bd","#dd88ac","#ca699d","#b14d8e","#91357d","#6c2167"],Magma:no(Hg),Mint:["#e4f1e1","#b4d9cc","#89c0b6","#63a6a0","#448c8a","#287274","#0d585f"],Oranges:Te(nu),OrRd:Te($f),OrYel:["#ecda9a","#efc47e","#f3ad6a","#f7945d","#f97b57","#f66356","#ee4d5a"],Peach:["#fde0c5","#facba6","#f8b58b","#f59e72","#f2855d","#ef6a4c","#eb4a40"],Plasma:no(Xg),PinkYl:["#fef6b5","#ffdd9a","#ffc285","#ffa679","#fa8a76","#f16d7a","#e15383"],PuBu:Te(Yf),PuBuGn:Te(Hf),PuRd:Te(Xf),Purp:["#f3e0f7","#e4c7f1","#d1afe8","#b998dd","#9f82ce","#826dba","#63589f"],Purples:Te(ru),PurpOr:["#f9ddda","#f2b9c4","#e597b9","#ce78b3","#ad5fad","#834ba0","#573b88"],RdPu:Te(Gf),RedOr:["#f6d2a9","#f5b78e","#f19c7c","#ea8171","#dd686c","#ca5268","#b13f64"],Reds:Te(iu),Sunset:["#f3e79b","#fac484","#f8a07e","#eb7f86","#ce6693","#a059a0","#5c53a5"],SunsetDark:["#fcde9c","#faa476","#f0746e","#e34f6f","#dc3977","#b9257a","#7c1d6f"],Teal:jA,TealGrn:["#b0f2bc","#89e8ac","#67dba5","#4cc8a3","#38b2a3","#2c98a0","#257d98"],Viridis:no($g),Warm:no(Vg),YlGn:Te(Kf),YlGnBu:Te(qf),YlOrBr:Te(Zf),YlOrRd:Te(Qf)},Nfe=Object.keys($A),JF="#f52020",eB="#17a5be",tB={negative:{flows:{scheme:[Em,eB]}},positive:{flows:{scheme:[Em,JF]}},locationAreas:{outline:"rgba(92,112,128,0.5)",normal:"rgba(220,220,220,0.5)"},outlineColor:"rgb(230,233,237)"};function HA(t){return YA(!1,t.colorScheme,t.darkMode,t.fadeEnabled,t.fadeOpacityEnabled,t.fadeAmount,rB(t.flowLinesRenderingMode))}function rB(t){return t==="animated-straight"}function YA(t,e,r,i,n,o,s){if(t)return tB;let a;Array.isArray(e)?a=e:(a=e&&$A[e]||QF,r&&(a=a.slice().reverse()));{let c=Ia(0,Math.max(10,a.length)),l=c.length-1,f=Wa(Ra(a)).domain([0,l]);if(!i||o===0)a=c.map((u,d)=>f(d));else{let u=Qn().exponent(1.5).domain([l,0]).range([0,2*o/100]);a=c.map((d,h)=>{let p=f(h),g=u(h);if(p==null||g==null)return"#000";let m=Gn(p);return m.l=r?m.l-m.l*g:m.l+(100-m.l)*g,m.c=m.c-m.c*(g/4),n&&(m.opacity=m.opacity*(1-g)),m.toString()})}}return{darkMode:r,flows:{scheme:a},locationCircles:{outgoing:r?"#000":"#fff"},outlineColor:r?"#000":"rgba(255, 255, 255, 0.5)"}}function iB(t){let e=Ea,r=t.length,i=new Array(r),n=new Array(r),o=new Array(r),s=new Array(r),a,c;for(a=0;adt(i(n))}function XA(t,e,r){let i=e?e[0]:0,n=e?e[1]:0;if(Pm(t)){let s=Am([0,n],t.positive.flows.scheme,r),a=Am([0,i],t.negative.flows.scheme,r);return c=>c>=0?s(c):a(c)}let o=Am([0,n||0],t.flows.scheme,r);return s=>o(s)}function GA(t){return t.positive!==void 0}function Pm(t){return t.positive!==void 0}function nB(t,e){let r=t&&t.normal||$F,i=Gn(r),n=dt(r);return{normal:n,connected:Qt(t&&t.connected,n),highlighted:Qt(t&&t.highlighted,WA(i[e?"brighter":"darker"](1).toString(),.5)),selected:Qt(t&&t.selected,WA(i[e?"brighter":"darker"](2).toString(),.8)),outline:Qt(t&&t.outline,dt(i[e?"brighter":"darker"](4).toString()))}}function Rm(t,e,r){let i=t&&t.flows&&t.flows.scheme||e,n=Gn(i[i.length-1]),o=Qt(t&&t.flows&&t.flows.highlighted,dt(n[r?"brighter":"darker"](.7).toString())),s=Qt(t?.locationCircles?.empty,r?"#000":"#fff"),a=Qt(t&&t.locationCircles&&t.locationCircles.inner,n.toString());return{flows:{scheme:i,highlighted:o},locationCircles:{inner:a,outgoing:Qt(t&&t.locationCircles&&t.locationCircles.outgoing,r?"#000":"#fff"),incoming:Qt(t&&t.locationCircles&&t.locationCircles.incoming,n[r?"brighter":"darker"](1.25).toString()),highlighted:Qt(t&&t.locationCircles&&t.locationCircles.highlighted,o),empty:s,outlineEmptyMix:t?.locationCircles?.outlineEmptyMix??.4}}}function qA(t){let e=!!(t&&t.darkMode);return{darkMode:e,locationAreas:nB(t&&t.locationAreas,e),outlineColor:dt(t&&t.outlineColor||WF),dimmedOpacity:t&&t.dimmedOpacity!=null?t.dimmedOpacity:VF}}function KA(t){let e=qA(t);return{...e,...Rm(t,jF,e.darkMode)}}function ZA(t){let e=qA(t);return{...e,positive:Rm(t&&t.positive,HF,e.darkMode),negative:Rm(t&&t.negative,YF,e.darkMode)}}var QA=YA;var JA=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],Mm=1,Va=8,oe=new Uint32Array(96),Yi=class t{static from(e){if(!e||e.byteLength===void 0||e.buffer)throw new Error("Data must be an instance of ArrayBuffer or SharedArrayBuffer.");let[r,i]=new Uint8Array(e,0,2);if(r!==219)throw new Error("Data does not appear to be in a KDBush format.");let n=i>>4;if(n!==Mm)throw new Error(`Got v${n} data when expected v${Mm}.`);let o=JA[i&15];if(!o)throw new Error("Unrecognized array type.");let[s]=new Uint16Array(e,2,1),[a]=new Uint32Array(e,4,1);return new t(a,s,o,void 0,e)}constructor(e,r=64,i=Float64Array,n=ArrayBuffer,o){if(isNaN(e)||e<0)throw new Error(`Unexpected numItems value: ${e}.`);this.numItems=+e,this.nodeSize=Math.min(Math.max(+r,2),65535),this.ArrayType=i,this.IndexArrayType=e<65536?Uint16Array:Uint32Array;let s=JA.indexOf(this.ArrayType),a=e*2*this.ArrayType.BYTES_PER_ELEMENT,c=e*this.IndexArrayType.BYTES_PER_ELEMENT,l=(8-c%8)%8;if(s<0)throw new Error(`Unexpected typed array class: ${i}.`);if(o)this.data=o,this.ids=new this.IndexArrayType(o,Va,e),this.coords=new i(o,Va+c+l,e*2),this._pos=e*2,this._finished=!0;else{let f=this.data=new n(Va+a+c+l);this.ids=new this.IndexArrayType(f,Va,e),this.coords=new i(f,Va+c+l,e*2),this._pos=0,this._finished=!1,new Uint8Array(f,0,2).set([219,(Mm<<4)+s]),new Uint16Array(f,2,1)[0]=r,new Uint32Array(f,4,1)[0]=e}}add(e,r){let i=this._pos>>1;return this.ids[i]=i,this.coords[this._pos++]=e,this.coords[this._pos++]=r,i}finish(){let e=this._pos>>1;if(e!==this.numItems)throw new Error(`Added ${e} items when expected ${this.numItems}.`);return Om(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(e,r,i,n){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");let{ids:o,coords:s,nodeSize:a}=this;oe[0]=0,oe[1]=o.length-1,oe[2]=0;let c=3,l=[];for(;c>0;){let f=oe[--c],u=oe[--c],d=oe[--c];if(u-d<=a){for(let m=d;m<=u;m++){let _=s[2*m],T=s[2*m+1];_>=e&&_<=i&&T>=r&&T<=n&&l.push(o[m])}continue}let h=d+u>>1,p=s[2*h],g=s[2*h+1];p>=e&&p<=i&&g>=r&&g<=n&&l.push(o[h]),(f===0?e<=p:r<=g)&&(oe[c++]=d,oe[c++]=h-1,oe[c++]=1-f),(f===0?i>=p:n>=g)&&(oe[c++]=h+1,oe[c++]=u,oe[c++]=1-f)}return l}within(e,r,i){let n=[];return this.withinInto(e,r,i,n),n}withinInto(e,r,i,n){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");let{ids:o,coords:s,nodeSize:a}=this;oe[0]=0,oe[1]=o.length-1,oe[2]=0;let c=3,l=0,f=i*i;for(;c>0;){let u=oe[--c],d=oe[--c],h=oe[--c];if(d-h<=a){for(let _=h;_<=d;_++)ev(s[2*_],s[2*_+1],e,r)<=f&&(n[l++]=o[_]);continue}let p=h+d>>1,g=s[2*p],m=s[2*p+1];ev(g,m,e,r)<=f&&(n[l++]=o[p]),(u===0?e-i<=g:r-i<=m)&&(oe[c++]=h,oe[c++]=p-1,oe[c++]=1-u),(u===0?e+i>=g:r+i>=m)&&(oe[c++]=p+1,oe[c++]=d,oe[c++]=1-u)}return l}};function Om(t,e,r,i,n,o){if(n-i<=r)return;let s=i+n>>1;tv(t,e,s,i,n,o),Om(t,e,r,i,s-1,1-o),Om(t,e,r,s+1,n,1-o)}function tv(t,e,r,i,n,o){for(;n>i;){if(n-i>600){let l=n-i+1,f=r-i+1,u=Math.log(l),d=.5*Math.exp(2*u/3),h=.5*Math.sqrt(u*d*(l-d)/l)*(f-l/2<0?-1:1),p=Math.max(i,Math.floor(r-f*d/l+h)),g=Math.min(n,Math.floor(r+(l-f)*d/l+h));tv(t,e,r,p,g,o)}let s=e[2*r+o],a=i,c=n;for(ja(t,e,i,r),e[2*n+o]>s&&ja(t,e,i,n);as;)c--}e[2*i+o]===s?ja(t,e,i,c):(c++,ja(t,e,c,n)),c<=r&&(i=c+1),r<=c&&(n=c-1)}}function ja(t,e,r,i){Im(t,r,i),Im(e,2*r,2*i),Im(e,2*r+1,2*i+1)}function Im(t,e,r){let i=t[e];t[e]=t[r],t[r]=i}function ev(t,e,r,i){let n=t-r,o=e-i;return n*n+o*o}var Tu=Symbol("NOT_FOUND");function oB(t,e=`expected a function, instead received ${typeof t}`){if(typeof t!="function")throw new TypeError(e)}function sB(t,e="expected all items to be functions, instead received the following types: "){if(!t.every(r=>typeof r=="function")){let r=t.map(i=>typeof i=="function"?`function ${i.name||"unnamed"}()`:typeof i).join(", ");throw new TypeError(`${e}[${r}]`)}}var rv=t=>Array.isArray(t)?t:[t];function aB(t){let e=Array.isArray(t[0])?t[0]:t;return sB(e,"createSelector expects all input-selectors to be functions, but received the following types: "),e}function cB(t,e){let r=[],{length:i}=t;for(let n=0;ne(a,l.key));if(c>-1){let l=r[c];return c>0&&(r.splice(c,1),r.unshift(l)),l.value}return Tu}function n(a,c){i(a)===Tu&&(r.unshift({key:a,value:c}),r.length>t&&r.pop())}function o(){return r}function s(){r=[]}return{get:i,put:n,getEntries:o,clear:s}}var uB=(t,e)=>t===e;function dB(t){return function(r,i){if(r===null||i===null||r.length!==i.length)return!1;let{length:n}=r;for(let o=0;oo(h.value,f));d&&(f=d.value,a!==0&&a--)}c.put(arguments,f)}return f}return l.clearCache=()=>{c.clear(),l.resetResultsCount()},l.resultsCount=()=>a,l.resetResultsCount=()=>{a=0},l}var hB=class{constructor(t){this.value=t}deref(){return this.value}},pB=()=>typeof WeakRef>"u"?hB:WeakRef,ov=pB(),gB=0,iv=1;function bu(){return{s:gB,v:void 0,o:null,p:null}}function mB(t){return t instanceof ov?t.deref():t}function sv(t,e={}){let r=bu(),{resultEqualityCheck:i}=e,n,o=0;function s(){let a=r,{length:c}=arguments;for(let u=0,d=c;u{r=bu(),s.resetResultsCount()},s.resultsCount=()=>o,s.resetResultsCount=()=>{o=0},s}function Nm(t,...e){let r=typeof t=="function"?{memoize:t,memoizeOptions:e}:t,i=(...n)=>{let o=0,s=0,a,c={},l=n.pop();typeof l=="object"&&(c=l,l=n.pop()),oB(l,`createSelector expects an output function after the inputs, but received: [${typeof l}]`);let f={...r,...c},{memoize:u,memoizeOptions:d=[],argsMemoize:h=sv,argsMemoizeOptions:p=[]}=f,g=rv(d),m=rv(p),_=aB(n),T=u(function(){return o++,l.apply(null,arguments)},...g),y=!0,x=h(function(){s++;let b=cB(_,arguments);return a=T.apply(null,b),a},...m);return Object.assign(x,{resultFunc:l,memoizedResultFunc:T,dependencies:_,dependencyRecomputations:()=>s,resetDependencyRecomputations:()=>{s=0},lastResult:()=>a,recomputations:()=>o,resetRecomputations:()=>{o=0},memoize:u,argsMemoize:h})};return Object.assign(i,{withTypes:()=>i}),i}var U=Nm(sv);var Bv=S2(Sv(),1);var Sr=class{constructor(e){this.getLocationId=r=>Bi(r)?r.id:this.accessors.getLocationId(r),this.getLocationName=r=>{let i;return Bi(r)&&Hn(r)?i=r.name:this.accessors.getLocationName&&(i=this.accessors.getLocationName(r)),i||(i=`${this.getLocationId(r)}`),i},this.getLocationLat=r=>Bi(r)?r.lat:this.accessors.getLocationLat(r),this.getLocationLon=r=>Bi(r)?r.lon:this.accessors.getLocationLon(r),this.getFlowOriginId=r=>If(r)?r.origin:this.accessors.getFlowOriginId(r),this.getFlowDestId=r=>If(r)?r.dest:this.accessors.getFlowDestId(r),this.getFlowMagnitude=r=>If(r)?r.count:this.accessors.getFlowMagnitude(r),this.getFlowTime=r=>{let{getFlowTime:i}=this.accessors;return i?i(r):void 0},this.accessors=e}setAccessors(e){this.accessors=e}getFlowmapDataAccessors(){return this.accessors}};function Av(t){let e=new Map,r=new Map,i=new Map;for(let{zoom:u,nodes:d}of t){e.set(u,d);for(let h of d)if(Hn(h))r.set(h.id,h);else{let{id:p}=h,g=i.get(p);(g==null||g>u)&&i.set(p,u)}}let[n,o]=Kn(t,u=>u.zoom);if(n==null||o==null)throw new Error("Could not determine minZoom or maxZoom");let s=new Map;for(let u of r.values()){let{zoom:d}=u,h=s.get(d);h||(h=new Map,s.set(d,h)),a(u,p=>{h?.set(p,u)})}function a(u,d){for(let h of u.children){let p=r.get(h);p?a(p,d):d(h)}}let c=(u,d=o)=>{let h=[],p=(g,m)=>{if(d>g.zoom)for(let _ of g.children){let T=r.get(_);T?p(T,m):m.push(_)}else m.push(g.id)};return p(u,h),h};function l(u,d){let h=s.get(d);if(!h)return;let p=h.get(u);return p?p.id:void 0}return{availableZoomLevels:t.map(u=>+u.zoom).sort((u,d)=>ut(u,d)),getClusterNodesFor:u=>{if(u!==void 0)return e.get(u)},getClusterById:u=>r.get(u),getMinZoomForLocation:u=>i.get(u)||n,expandCluster:c,findClusterFor:l,aggregateFlows:(u,d,{getFlowOriginId:h,getFlowDestId:p,getFlowMagnitude:g},m={})=>{if(d>o)return u;let _=[],T=new Map,y=(w,b)=>`${w}:${b}`,{flowCountsMapReduce:x={map:g,reduce:(w,b)=>(w||0)+b}}=m;for(let w of u){let b=h(w),E=p(w),S=l(b,d)||b,A=l(E,d)||E,C=y(S,A);if(S===b&&A===E)_.push(w);else{let I=T.get(C);I?I.count=x.reduce(I.count,x.map(w)):(I={origin:S,dest:A,count:x.map(w),aggregate:!0},_.push(I),T.set(C,I))}}return _}}}function vv(t,{getFlowOriginId:e,getFlowDestId:r,getFlowMagnitude:i}){let n={incoming:new Map,outgoing:new Map};for(let o of t){let s=e(o),a=r(o),c=i(o);n.incoming.set(a,(n.incoming.get(a)||0)+c),n.outgoing.set(s,(n.outgoing.get(s)||0)+c)}return o=>Math.max(Math.abs(n.incoming.get(o)||0),Math.abs(n.outgoing.get(o)||0))}function Ev(t,e){if(!t.length)throw new Error("No available zoom levels");return t[Math.min(qg(t,Math.floor(e)),t.length-1)]}var SB={minZoom:0,maxZoom:16,radius:40,extent:512,nodeSize:64,makeClusterName:(t,e)=>{},makeClusterId:t=>`{[${t}]}`};function AB(t){let{index:e}=t;return e!=null}function Rv(t){let{id:e}=t;return e!=null}function Cv(t,e,r,i){let{getLocationLon:n,getLocationLat:o,getLocationId:s}=e,a={...SB,...i},{minZoom:c,maxZoom:l,nodeSize:f,makeClusterName:u,makeClusterId:d}=a,h=new Array(l+1),p=new Array,g=0;for(let S of t){let A=n(S),C=o(S);p.push({x:PB(A),y:MB(C),weight:r(s(S)),zoom:1/0,index:g,parentId:-1,location:S}),g++}let m=S=>{let A=new Yi(S.length,f,Float32Array);for(let C=0;C=c;S--){let A=EB(p,S,h[_],a);A.length===p.length?(h[S]=h[_],h[_]=void 0,_=S,p=A):(_=S,p=A,h[S]=m(p))}if(h.length===0)return[];let T=h.map(S=>S?.points.length),y=Zn(T.filter(S=>S>0)),x=OB(T)??T.length-1,w=IB(t,e);if(wA<=w);S>=0&&(S=b;S--){let A,C=h[S];if(!C)continue;h[_]&&SR.map(N=>N.id?d(N.id):s(N.location)),R=>R.parentId));let I=[];for(let R of C.points){let{x:N,y:O,numPoints:W,location:G}=R;if(AB(R))I.push({id:s(G),zoom:S,lat:o(G),lon:n(G)});else if(Rv(R)){let{id:L}=R,H=A&&A.get(L);if(!H){console.warn("Omitting cluster with no children, point:",R);continue}let Re={id:d(L),name:u(L,W),zoom:S,lat:CB(O),lon:RB(N),children:H??[]};I.push(Re)}}E.push({zoom:S,nodes:I}),_=S}return E}function vB(t,e,r,i,n){return{x:t,y:e,zoom:1/0,id:r,parentId:-1,numPoints:i,weight:n}}function EB(t,e,r,i){let n=[],{radius:o,extent:s}=i,a=o/(s*Math.pow(2,e));for(let c=0;c1?1:r}function IB(t,e){let{getLocationLon:r,getLocationLat:i}=e,n=new Map,o=0;for(let s of t){let a=r(s),c=i(s),l=`${a},${c}`,f=n.get(l);f||o++,n.set(l,f?f+1:1)}return o}function OB(t){let e=-1/0,r;for(let i=0;ie&&(e=n,r=i)}return r}function NB(t,e){for(let r=t.length-1;r>=0;r--)if(e(t[r],r,t))return r;return-1}var Pv=(t,e=0)=>{let r=e,i=new Sn({...t,width:t.width+r*2,height:t.height+r*2}).getBounds();return[i[0][0],i[0][1],i[1][0],i[1][1]]};var Mv=t=>{if(t)return Da().range([.025,.5]).domain([0,Math.max.apply(null,t.map(e=>Math.abs(e||0)))])};function Iv(t,e,r,i,n){let{getLocationId:o,getLocationName:s,getLocationClusterName:a}=i,c=l=>{let f=r.get(l);return f?s?s(f):o(f)||l:`"${l}"`};for(let l of e)for(let f of l.nodes)if(Hn(f)){let u=t.expandCluster(f);if(u.sort((d,h)=>Kt(n(d),n(h))),a)f.name=a(u);else{let d=u[0],h=u.length===2?u[1]:void 0;f.name=`"${c(d)}" and ${h?`"${c(h)}"`:`${u.length-1} others`}`}}else f.name=c(f.id)}var rue=[Jr("%Y-%m-%d"),Jr("%Y-%m-%d %H:%M"),Jr("%Y-%m-%d %H:%M:%S"),Jr("%Y"),Jr("%Y-%m")];var ei;(function(t){t.SECOND="SECOND",t.MINUTE="MINUTE",t.HOUR="HOUR",t.DAY="DAY",t.MONTH="MONTH",t.YEAR="YEAR"})(ei||(ei={}));var iue=Ee(".%L"),DB=Ee(":%S"),LB=Ee("%I:%M"),FB=Ee("%I %p"),BB=Ee("%a %d"),nue=Ee("%b %d"),kB=Ee("%b"),UB=Ee("%Y");var $a=[{order:0,key:ei.SECOND,interval:La,format:DB,formatFull:Ee("%Y-%m-%d %H:%M:%S")},{order:1,key:ei.MINUTE,interval:mu,format:LB,formatFull:Ee("%Y-%m-%d %H:%M")},{order:2,key:ei.HOUR,interval:_u,format:FB,formatFull:Ee("%a %d %b %Y, %I %p")},{order:3,key:ei.DAY,interval:ji,format:BB,formatFull:Ee("%a %d %b %Y")},{order:4,key:ei.MONTH,interval:yu,format:kB,formatFull:Ee("%b %Y")},{order:5,key:ei.YEAR,interval:Rt,format:UB,formatFull:Ee("%Y")}];function zm(t){return $a.find(e=>e.key===t)}function Ov(t){return $a.find(e=>e.order===t)}function Nv(t){let e;for(let r of $a){let{interval:i}=r;if(i(t)i.flows,this.getLocationsFromProps=(r,i)=>i.locations,this.getClusterLevelsFromProps=(r,i)=>i.clusterLevels,this.getMaxTopFlowsDisplayNum=(r,i)=>r.settings.maxTopFlowsDisplayNum,this.getFlowEndpointsInViewportMode=(r,i)=>r.settings.flowEndpointsInViewportMode,this.getSelectedLocations=(r,i)=>r.filter?.selectedLocations,this.getLocationFilterMode=(r,i)=>r.filter?.locationFilterMode,this.getClusteringEnabled=(r,i)=>r.settings.clusteringEnabled,this.getLocationTotalsEnabled=(r,i)=>r.settings.locationTotalsEnabled,this.getLocationLabelsEnabled=(r,i)=>r.settings.locationLabelsEnabled,this.getZoom=(r,i)=>r.viewport.zoom,this.getViewport=(r,i)=>r.viewport,this.getSelectedTimeRange=(r,i)=>r.filter?.selectedTimeRange,this.getSelectedTimeRanges=(r,i)=>r.filter?.selectedTimeRanges,this.getTemporalScaleDomain=(r,i)=>r.settings.temporalScaleDomain,this.getColorScheme=(r,i)=>r.settings.colorScheme,this.getDarkMode=(r,i)=>r.settings.darkMode,this.getFadeEnabled=(r,i)=>r.settings.fadeEnabled,this.getFadeOpacityEnabled=(r,i)=>r.settings.fadeOpacityEnabled,this.getFadeAmount=(r,i)=>r.settings.fadeAmount,this.getFlowLinesRenderingMode=(r,i)=>r.settings.flowLinesRenderingMode,this.getAnimate=U(this.getFlowLinesRenderingMode,r=>r==="animated-straight"),this.getInvalidLocationIds=U(this.getLocationsFromProps,r=>{if(!r)return;let i=[];for(let n of r){let o=this.accessors.getLocationId(n),s=this.accessors.getLocationLon(n),a=this.accessors.getLocationLat(n);(!(-90<=a&&a<=90)||!(-180<=s&&s<=180))&&i.push(o)}return i.length>0?i:void 0}),this.getLocations=U(this.getLocationsFromProps,this.getInvalidLocationIds,(r,i)=>{if(!r)return;if(!i||i.length===0)return r;let n=new Set(i),o=[];for(let s of r){let a=this.accessors.getLocationId(s);n.has(a)||o.push(s)}return o}),this.getLocationIds=U(this.getLocations,r=>{if(!r)return;let i=new Set;for(let n of r)i.add(this.accessors.getLocationId(n));return i}),this.getSelectedLocationsSet=U(this.getSelectedLocations,r=>r&&r.length>0?new Set(r):void 0),this.getSortedFlowsForKnownLocations=U(this.getFlowsFromProps,this.getLocationIds,(r,i)=>{if(!i||!r)return;let n=[];for(let o of r){let s=this.accessors.getFlowOriginId(o),a=this.accessors.getFlowDestId(o);i.has(s)&&i.has(a)&&n.push(o)}return n.sort((o,s)=>Kt(Math.abs(this.accessors.getFlowMagnitude(o)),Math.abs(this.accessors.getFlowMagnitude(s))))}),this.getActualTimeExtent=U(this.getSortedFlowsForKnownLocations,r=>{if(!r)return;let i=null,n=null;for(let o of r){let s=this.accessors.getFlowTime(o);s&&((i==null||i>s)&&(i=s),(n==null||n{if(!r||!i)return;let n=Zn(r,s=>{let a=this.accessors.getFlowTime(s);return a?Nv(a).order:null});if(n==null)return;let o=Ov(n);return o?o.key:void 0}),this.getTimeExtent=U(this.getActualTimeExtent,this.getTimeGranularityKey,(r,i)=>{let n=i?zm(i):void 0;if(!r||!n?.interval)return;let{interval:o}=n;return[r[0],o.offset(o.floor(r[1]),1)]}),this.getSortedFlowsForKnownLocationsFilteredByTime=U(this.getSortedFlowsForKnownLocations,this.getTimeExtent,this.getSelectedTimeRange,this.getSelectedTimeRanges,(r,i,n,o)=>{if(!r)return;let s=Array.isArray(o)&&o.length>0?o:n?[n]:null;return!i||!s||s.length===0||s.length===1&&i[0]===s[0][0]&&i[1]===s[0][1]?r:r.filter(a=>{let c=this.accessors.getFlowTime(a);return c&&s.some(l=>l[0]<=c&&c{if(!i||!r)return i;let n=new Set;for(let s of r)n.add(this.accessors.getFlowOriginId(s)),n.add(this.accessors.getFlowDestId(s));let o=[];for(let s of i)n.has(this.accessors.getLocationId(s))&&o.push(s);return o}),this.getLocationsById=U(this.getLocationsHavingFlows,r=>{if(!r)return;let i=new Map;for(let n of r)i.set(this.accessors.getLocationId(n),n);return i}),this.getLocationWeightGetter=U(this.getSortedFlowsForKnownLocations,r=>r?vv(r,this.accessors.getFlowmapDataAccessors()):void 0),this.getClusterLevels=U(this.getClusterLevelsFromProps,this.getLocationsHavingFlows,this.getLocationWeightGetter,(r,i,n)=>r||(!i||!n?void 0:Cv(i,this.accessors.getFlowmapDataAccessors(),n,{maxZoom:zB}))),this.getClusterIndex=U(this.getLocationsById,this.getLocationWeightGetter,this.getClusterLevels,(r,i,n)=>{if(!r||!i||!n)return;let o=Av(n);return Iv(o,n,r,this.accessors.getFlowmapDataAccessors(),i),o}),this.getAvailableClusterZoomLevels=U(this.getClusterIndex,this.getSelectedLocations,(r,i)=>{if(!r)return;let n=Number.POSITIVE_INFINITY,o=Number.NEGATIVE_INFINITY,s=a=>{let c=r.getClusterById(a);if(c)o=Math.max(o,c.zoom),n=Math.min(n,c.zoom);else{let l=r.getMinZoomForLocation(a);o=Math.max(o,l)}};if(i)for(let a of i)s(a);return r.availableZoomLevels.filter(a=>o<=a&&a<=n)}),this._getClusterZoom=U(this.getClusterIndex,this.getZoom,this.getAvailableClusterZoomLevels,(r,i,n)=>!r||!n||i==null?void 0:Ev(n,i)),this.getClusterZoom=(r,i)=>{let{settings:n}=r;if(n.clusteringEnabled)return n.clusteringAuto||n.clusteringLevel==null?this._getClusterZoom(r,i):n.clusteringLevel},this.getLocationsForSearchBox=U(this.getClusteringEnabled,this.getLocationsHavingFlows,this.getSelectedLocations,this.getClusterZoom,this.getClusterIndex,(r,i,n,o,s)=>{if(!i)return;let a=Array.from(i);if(s&&n){let c=[];for(let l of n){let f=s.getClusterById(l);f&&!a.find(u=>(Bi(u)?u.id:this.accessors.getLocationId(u))===l)&&c.push(f)}c.length>0&&(a=a.concat(c))}return a}),this.getDiffMode=U(this.getFlowsFromProps,r=>{if(r){for(let i of r)if(this.accessors.getFlowMagnitude(i)<0)return!0}return!1}),this._getFlowmapColors=U(this.getDiffMode,this.getColorScheme,this.getDarkMode,this.getFadeEnabled,this.getFadeOpacityEnabled,this.getFadeAmount,this.getAnimate,QA),this.getFlowmapColorsRGBA=U(this._getFlowmapColors,r=>GA(r)?ZA(r):KA(r)),this.getUnknownLocations=U(this.getLocationIds,this.getFlowsFromProps,this.getSortedFlowsForKnownLocations,(r,i,n)=>{if(!r||!i||n)return;let o=new Set;for(let s of i)r.has(this.accessors.getFlowOriginId(s))||o.add(this.accessors.getFlowOriginId(s)),r.has(this.accessors.getFlowDestId(s))||o.add(this.accessors.getFlowDestId(s));return o}),this.getSortedAggregatedFlows=U(this.getClusterIndex,this.getClusteringEnabled,this.getSortedFlowsForKnownLocations,this.getClusterZoom,(r,i,n,o)=>{if(!n)return;let s;return i&&r&&o!=null?s=r.aggregateFlows(n,o,this.accessors.getFlowmapDataAccessors()):s=Lv(n,this.accessors.getFlowmapDataAccessors()),s.sort((a,c)=>Kt(Math.abs(this.accessors.getFlowMagnitude(a)),Math.abs(this.accessors.getFlowMagnitude(c)))),s}),this.getSortedAggregatedFilteredFlows=U(this.getClusterIndex,this.getClusteringEnabled,this.getSortedFlowsForKnownLocationsFilteredByTime,this.getClusterZoom,this.getTimeExtent,(r,i,n,o,s)=>{if(!n)return;let a;return i&&r&&o!=null?a=r.aggregateFlows(n,o,this.accessors.getFlowmapDataAccessors()):a=Lv(n,this.accessors.getFlowmapDataAccessors()),a.sort((c,l)=>Kt(Math.abs(this.accessors.getFlowMagnitude(c)),Math.abs(this.accessors.getFlowMagnitude(l)))),a}),this.getFlowsForScaleDomain=U(this.getTemporalScaleDomain,this.getSortedAggregatedFlows,this.getSortedAggregatedFilteredFlows,(r,i,n)=>r==="all"?i:n),this.getExpandedSelectedLocationsSet=U(this.getClusteringEnabled,this.getSelectedLocationsSet,this.getClusterIndex,(r,i,n)=>{if(!i||!n)return i;let o=new Set;for(let s of i){let a=n.getClusterById(s);if(a){let c=n.expandCluster(a);for(let l of c)o.add(l)}else o.add(s)}return o}),this.getTotalCountsByTime=U(this.getSortedFlowsForKnownLocations,this.getTimeGranularityKey,this.getTimeExtent,this.getExpandedSelectedLocationsSet,this.getLocationFilterMode,(r,i,n,o,s)=>{let a=i?zm(i):void 0;if(!r||!a||!n)return;let c=r.reduce((l,f)=>{if(this.isFlowInSelection(f,o,s)){let u=a.interval(this.accessors.getFlowTime(f)).getTime();l.set(u,(l.get(u)??0)+this.accessors.getFlowMagnitude(f))}return l},new Map);return Array.from(c.entries()).map(([l,f])=>({time:new Date(l),count:f}))}),this.getMaxLocationCircleSize=U(this.getLocationTotalsEnabled,r=>r?17:1),this.getViewportBoundingBox=U(this.getViewport,this.getMaxLocationCircleSize,Pv),this.getLocationsForZoom=U(this.getClusteringEnabled,this.getLocationsHavingFlows,this.getClusterIndex,this.getClusterZoom,(r,i,n,o)=>r&&n?n.getClusterNodesFor(o):i),this.getLocationTotals=U(this.getLocationsForZoom,this.getSortedAggregatedFilteredFlows,this.getSelectedLocationsSet,this.getLocationFilterMode,(r,i,n,o)=>{if(!i)return;let s=new Map,a=(c,l)=>{let f=s.get(c)??{incomingCount:0,outgoingCount:0,internalCount:0};return l.incomingCount!=null&&(f.incomingCount+=l.incomingCount),l.outgoingCount!=null&&(f.outgoingCount+=l.outgoingCount),l.internalCount!=null&&(f.internalCount+=l.internalCount),f};for(let c of i)if(this.isFlowInSelection(c,n,o)){let l=this.accessors.getFlowOriginId(c),f=this.accessors.getFlowDestId(c),u=this.accessors.getFlowMagnitude(c);l===f?s.set(l,a(l,{internalCount:u})):(s.set(l,a(l,{outgoingCount:u})),s.set(f,a(f,{incomingCount:u})))}return s}),this.getLocationsTree=U(this.getLocationsForZoom,r=>{if(!r)return;let i=Array.isArray(r)?r:Array.from(r),n=new Yi(i.length,64,Float32Array);for(let o=0;o{let n=this._getLocationsInBboxIndices(r,i);if(n)return new Set(n.map(o=>this.accessors.getLocationId(r.points[o])))}),this.getLocationIdsInViewport=Nm({memoize:nv,memoizeOptions:{equalityCheck:(r,i)=>{if(r===i)return!0;if(r==null||i==null||r.size!==i.size)return!1;for(let n of r)if(!i.has(n))return!1;return!0}}})(this._getLocationIdsInViewport,r=>{if(r)return r}),this.getTotalUnfilteredCount=U(this.getSortedFlowsForKnownLocations,r=>{if(r)return r.reduce((i,n)=>i+this.accessors.getFlowMagnitude(n),0)}),this.getTotalFilteredCount=U(this.getSortedAggregatedFilteredFlows,this.getSelectedLocationsSet,this.getLocationFilterMode,(r,i,n)=>r?r.reduce((s,a)=>this.isFlowInSelection(a,i,n)?s+this.accessors.getFlowMagnitude(a):s,0):void 0),this._getLocationTotalsExtent=U(this.getLocationTotals,r=>Dv(r,void 0)),this._getLocationTotalsForViewportExtent=U(this.getLocationTotals,this.getLocationIdsInViewport,(r,i)=>Dv(r,i)),this.getLocationTotalsExtent=(r,i)=>r.settings.adaptiveScalesEnabled?this._getLocationTotalsForViewportExtent(r,i):this._getLocationTotalsExtent(r,i),this.getFlowsForFlowmapLayer=U(this.getSortedAggregatedFilteredFlows,this.getLocationIdsInViewport,this.getSelectedLocationsSet,this.getLocationFilterMode,this.getMaxTopFlowsDisplayNum,this.getFlowEndpointsInViewportMode,(r,i,n,o,s,a)=>{if(!r||!i)return;let c=[],l=0;for(let f of r){let u=this.accessors.getFlowOriginId(f),d=this.accessors.getFlowDestId(f),h=i.has(u),p=i.has(d);if((a==="both"?h&&p:h||p)&&this.isFlowInSelection(f,n,o)&&u!==d&&(c.push(f),l++),l>s)break}return c.reverse()}),this._getFlowMagnitudeExtent=U(this.getFlowsForScaleDomain,this.getSelectedLocationsSet,this.getLocationFilterMode,(r,i,n)=>{if(!r)return;let o;for(let s of r)if(this.accessors.getFlowOriginId(s)!==this.accessors.getFlowDestId(s)&&this.isFlowInSelection(s,i,n)){let a=this.accessors.getFlowMagnitude(s);o==null?o=[a,a]:(ao[1]&&(o[1]=a))}return o}),this._getAdaptiveFlowMagnitudeExtent=U(this.getFlowsForScaleDomain,this.getLocationIdsInViewport,this.getSelectedLocationsSet,this.getLocationFilterMode,this.getMaxTopFlowsDisplayNum,this.getFlowEndpointsInViewportMode,(r,i,n,o,s,a)=>{if(!r||!i)return;let c=[],l=0;for(let u of r){let d=this.accessors.getFlowOriginId(u),h=this.accessors.getFlowDestId(u),p=i.has(d),g=i.has(h);if((a==="both"?p&&g:p||g)&&this.isFlowInSelection(u,n,o)&&d!==h&&(c.push(u),l++),l>s)break}let f=Kn(c,this.accessors.getFlowMagnitude);return f[0]!==void 0&&f[1]!==void 0?f:void 0}),this.getFlowMagnitudeExtent=(r,i)=>r.settings.adaptiveScalesEnabled?this._getAdaptiveFlowMagnitudeExtent(r,i):this._getFlowMagnitudeExtent(r,i),this.getLocationMaxAbsTotalGetter=U(this.getLocationTotals,r=>i=>{let n=r?.get(i);if(n)return Math.max(Math.abs(n.incomingCount+n.internalCount),Math.abs(n.outgoingCount+n.internalCount))}),this.getFlowThicknessScale=U(this.getFlowMagnitudeExtent,Mv),this.getCircleSizeScale=U(this.getMaxLocationCircleSize,this.getLocationTotalsEnabled,this.getLocationTotalsExtent,(r,i,n)=>{if(!i)return()=>r;if(n)return pm().range([0,r]).domain([0,Math.max.apply(null,n.map(o=>Math.abs(o||0)))])}),this.getInCircleSizeGetter=U(this.getCircleSizeScale,this.getLocationTotals,(r,i)=>n=>{let o=i?.get(n);return o&&r&&r(Math.abs(o.incomingCount+o.internalCount))||0}),this.getOutCircleSizeGetter=U(this.getCircleSizeScale,this.getLocationTotals,(r,i)=>n=>{let o=i?.get(n);return o&&r&&r(Math.abs(o.outgoingCount+o.internalCount))||0}),this.getSortedLocationsForZoom=U(this.getLocationsForZoom,this.getInCircleSizeGetter,this.getOutCircleSizeGetter,(r,i,n)=>r?[...r].sort((s,a)=>{let c=this.accessors.getLocationId(s),l=this.accessors.getLocationId(a);return ut(Math.max(i(c),n(c)),Math.max(i(l),n(l)))}):void 0),this.getLocationsForFlowmapLayer=U(this.getSortedLocationsForZoom,r=>r),this.getLocationsForFlowmapLayerById=U(this.getLocationsForFlowmapLayer,r=>{if(r)return r.reduce((i,n)=>(i.set(this.accessors.getLocationId(n),n),i),new Map)}),this.getLocationOrClusterByIdGetter=U(this.getClusterIndex,this.getLocationsById,(r,i)=>n=>r?.getClusterById(n)??i?.get(n)),this.getLayersData=U(this.getLocationsForFlowmapLayer,this.getFlowsForFlowmapLayer,this.getFlowmapColorsRGBA,this.getLocationsForFlowmapLayerById,this.getLocationIdsInViewport,this.getInCircleSizeGetter,this.getOutCircleSizeGetter,this.getFlowThicknessScale,this.getFlowMagnitudeExtent,this.getViewport,this.getFlowLinesRenderingMode,this.getLocationLabelsEnabled,(r,i,n,o,s,a,c,l,f,u,d,h)=>this._prepareLayersData(r,i,n,o,s,a,c,l,f,u,d,h)),this.accessors=new Sr(e),this.setAccessors(e)}setAccessors(e){this.accessors=new Sr(e)}getAggregateAccessors(){return this.accessors}prepareLayersData(e,r){let i=this.getLocationsForFlowmapLayer(e,r)||[],n=this.getFlowsForFlowmapLayer(e,r)||[],o=this.getFlowmapColorsRGBA(e,r),s=this.getLocationsForFlowmapLayerById(e,r),a=this.getLocationIdsInViewport(e,r),c=this.getInCircleSizeGetter(e,r),l=this.getOutCircleSizeGetter(e,r),f=this.getFlowThicknessScale(e,r),u=this.getFlowMagnitudeExtent(e,r),d=this.getLocationLabelsEnabled(e,r),h=this.getViewport(e,r);return this._prepareLayersData(i,n,o,s,a,c,l,f,u,h,e.settings.flowLinesRenderingMode,d)}_prepareLayersData(e,r,i,n,o,s,a,c,l,f,u,d){e||(e=[]),r||(r=[]);let{getFlowOriginId:h,getFlowDestId:p,getFlowMagnitude:g,getLocationId:m,getLocationLon:_,getLocationLat:T,getLocationName:y}=this.accessors,x=XA(i,l,u==="animated-straight"),w=Float64Array.from((function*(){for(let L of e)yield _(L),yield T(L),yield 0})()),b=Pm(i)?i.positive.locationCircles.inner:i.locationCircles.inner,E=Uint8Array.from((function*(){for(let L of e)yield*b})()),S=Float32Array.from((function*(){for(let L of e){let H=m(L);yield o?.has(H)?s(H):1}})()),A=Float32Array.from((function*(){for(let L of e){let H=m(L);yield o?.has(H)?a(H):1}})()),C=Float64Array.from((function*(){for(let L of r){let H=n?.get(h(L));yield H?_(H):0,yield H?T(H):0,yield 0}})()),I=Float64Array.from((function*(){for(let L of r){let H=n?.get(p(L));yield H?_(H):0,yield H?T(H):0,yield 0}})()),R=Float32Array.from((function*(){for(let L of r)yield c&&c(g(L))||0})()),N=Float32Array.from((function*(){for(let L of r){let H=h(L),Re=p(L);yield Math.max(s(H),a(H)),yield Math.max(s(Re),a(Re))}})()),O=Uint8Array.from((function*(){for(let L of r)yield*x(g(L))})()),W=u==="animated-straight"?Float32Array.from((function*(){for(let L of r)yield new Bv.alea(`${h(L)}-${p(L)}`)()})()):void 0,G=u==="curved"?WB(r,f,n,h,p,_,T):void 0;return{circleAttributes:{length:e.length,attributes:{getPosition:{value:w,size:3},getColor:{value:E,size:4},getInRadius:{value:S,size:1},getOutRadius:{value:A,size:1}}},lineAttributes:{length:r.length,attributes:{getSourcePosition:{value:C,size:3},getTargetPosition:{value:I,size:3},getThickness:{value:R,size:1},getColor:{value:O,size:4},getEndpointOffsets:{value:N,size:2},...W?{getStaggering:{value:W,size:1}}:{},...G?{getCurveOffset:{value:G,size:1}}:{}}},...d?{locationLabels:e.map(y)}:void 0}}getLocationsInBbox(e,r){if(e)return this._getLocationsInBboxIndices(e,r).map(i=>e.points[i])}_getLocationsInBboxIndices(e,r){if(!e)return;let[i,n,o,s]=r,[a,c,l,f]=[Ha(i),Ya(n),Ha(o),Ya(s)];return e.range(Math.min(a,l),Math.min(c,f),Math.max(a,l),Math.max(c,f))}isFlowInSelection(e,r,i){let n=this.accessors.getFlowOriginId(e),o=this.accessors.getFlowDestId(e);if(r)switch(i){case Fi.ALL:return r.has(n)||r.has(o);case Fi.BETWEEN:return r.has(n)&&r.has(o);case Fi.INCOMING:return r.has(o);case Fi.OUTGOING:return r.has(n)}return!0}};function Dv(t,e){if(!t)return;let r;for(let[i,{incomingCount:n,outgoingCount:o,internalCount:s}]of t.entries())if(e==null||e.has(i)){let a=Math.min(n+s,o+s,s),c=Math.max(n+s,o+s,s);r?(ar[1]&&(r[1]=c)):r=[a,c]}return r}function Ha(t){return t/360+.5}function Ya(t){let e=Math.sin(t*Math.PI/180),r=.5-.25*Math.log((1+e)/(1-e))/Math.PI;return r<0?0:r>1?1:r}function Lv(t,e){let r=Pa(t,n=>{let o=e.getFlowOriginId(n[0]),s=e.getFlowDestId(n[0]);return{aggregate:!0,origin:o,dest:s,count:n.reduce((c,l)=>{let f=e.getFlowMagnitude(l);return f&&!isNaN(f)&&isFinite(f)?c+f:c},0)}},e.getFlowOriginId,e.getFlowDestId),i=[];for(let n of r.values())for(let o of n.values())i.push(o);return i}function Su(t,e){let{getInRadius:r,getOutRadius:i}=t.attributes;return Math.max(r.value[e],i.value[e])}function Wm(t,e){let{getPosition:r}=t.attributes,i=e*r.size;return[r.value[i],r.value[i+1]]}function kv(t,e){let{getColor:r,getCurveOffset:i,getEndpointOffsets:n,getSourcePosition:o,getTargetPosition:s,getThickness:a,getStaggering:c}=t.attributes;return{length:1,attributes:{getColor:{value:r.value.subarray(e*4,(e+1)*4),size:4},getEndpointOffsets:{value:n.value.subarray(e*2,(e+1)*2),size:2},getSourcePosition:{value:o.value.subarray(e*o.size,(e+1)*o.size),size:o.size},getTargetPosition:{value:s.value.subarray(e*s.size,(e+1)*s.size),size:s.size},getThickness:{value:a.value.subarray(e,e+1),size:1},...c?{getStaggering:{value:c.value.subarray(e,e+1),size:1}}:void 0,...i?{getCurveOffset:{value:i.value.subarray(e,e+1),size:1}}:void 0}}}function WB(t,e,r,i,n,o,s){let a=new Float32Array(t.length),c=new Map,l=512*Math.pow(2,e.zoom??0);return t.forEach((f,u)=>{let d=i(f),h=n(f),p=r?.get(d),g=r?.get(h);if(!p||!g)return;let m=o(p),_=s(p),T=o(g),y=s(g),x=Ha(m)*l,w=Ya(_)*l,b=Ha(T)*l,E=Ya(y)*l,S=x,A=w,C=b,I=E;(S>C||S===C&&A>I)&&([S,C]=[C,S],[A,I]=[I,A]);let R=C-S,N=I-A,O=Math.hypot(R,N);if(!isFinite(O)||O<1)return;let W=(Math.atan2(N,R)%Math.PI+Math.PI)%Math.PI,G=(S*I-A*C)/O,L=[Math.round(W/(6*Math.PI/180)),Math.round(G/18),Math.round(O/24)].join(":"),H=c.get(L)??[];H.push({index:u,originId:d,destId:h,sx:x,sy:w,tx:b,ty:E,chordLengthPx:O}),c.set(L,H)}),c.forEach(f=>{f.sort((u,d)=>{let h=Fv(u.originId,d.originId);if(h!==0)return h;let p=Fv(u.destId,d.destId);return p!==0?p:u.index-d.index}).forEach((u,d)=>{let h=Math.min(72,u.chordLengthPx*.35);a[u.index]=Math.min(h,(d+1)*18)})}),a}function Fv(t,e){if(typeof t=="number"&&typeof e=="number")return t-e;let r=String(t),i=String(e);return ri?1:0}var Au=1e-6;var Ga=Math.PI,Uv=Ga/2,Vm=Ga/4,jm=Ga*2,vu=180/Ga,ti=Ga/180,Eu=Math.abs;var Ru=Math.atan2,Gi=Math.cos;var qi=Math.sin;var zv=Math.sqrt;function Wv(t){return t>1?Uv:t<-1?-Uv:Math.asin(t)}function oo(){}function Cu(t,e){t&&jv.hasOwnProperty(t.type)&&jv[t.type](t,e)}var Vv={Feature:function(t,e){Cu(t.geometry,e)},FeatureCollection:function(t,e){for(var r=t.features,i=-1,n=r.length;++i=0?1:-1,n=i*r,o=Gi(e),s=qi(e),a=Xm*s,c=Ym*o+a*Gi(n),l=a*i*qi(n);qa.add(Ru(l,c)),Hm=t,Ym=o,Xm=s}function Kv(t){return[Ru(t[1],t[0]),Wv(t[2])]}function Zv(t){var e=t[0],r=t[1],i=Gi(r);return[i*Gi(e),i*qi(e),qi(r)]}function Gm(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function Qv(t){var e=zv(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=e,t[1]/=e,t[2]/=e}var se,He,ue,tt,Ki,r2,i2,so,Ka,ri,vr,Ar={point:qm,lineStart:Jv,lineEnd:e2,polygonStart:function(){Ar.point=o2,Ar.lineStart=HB,Ar.lineEnd=YB,Ka=new Tr,Jt.polygonStart()},polygonEnd:function(){Jt.polygonEnd(),Ar.point=qm,Ar.lineStart=Jv,Ar.lineEnd=e2,qa<0?(se=-(ue=180),He=-(tt=90)):Ka>Au?tt=90:Ka<-Au&&(He=-90),vr[0]=se,vr[1]=ue},sphere:function(){se=-(ue=180),He=-(tt=90)}};function qm(t,e){ri.push(vr=[se=t,ue=t]),ett&&(tt=e)}function n2(t,e){var r=Zv([t*ti,e*ti]);if(so){var i=Gm(so,r),n=[i[1],-i[0],0],o=Gm(n,i);Qv(o),o=Kv(o);var s=t-Ki,a=s>0?1:-1,c=o[0]*vu*a,l,f=Eu(s)>180;f^(a*Kitt&&(tt=l)):(c=(c+360)%360-180,f^(a*Kitt&&(tt=e))),f?tet(se,ue)&&(ue=t):et(t,ue)>et(se,ue)&&(se=t):ue>=se?(tue&&(ue=t)):t>Ki?et(se,t)>et(se,ue)&&(ue=t):et(t,ue)>et(se,ue)&&(se=t)}else ri.push(vr=[se=t,ue=t]);ett&&(tt=e),so=r,Ki=t}function Jv(){Ar.point=n2}function e2(){vr[0]=se,vr[1]=ue,Ar.point=qm,so=null}function o2(t,e){if(so){var r=t-Ki;Ka.add(Eu(r)>180?r+(r>0?360:-360):r)}else r2=t,i2=e;Jt.point(t,e),n2(t,e)}function HB(){Jt.lineStart()}function YB(){o2(r2,i2),Jt.lineEnd(),Eu(Ka)>Au&&(se=-(ue=180)),vr[0]=se,vr[1]=ue,so=null}function et(t,e){return(e-=t)<0?e+360:e}function XB(t,e){return t[0]-e[0]}function t2(t,e){return t[0]<=t[1]?t[0]<=e&&e<=t[1]:eet(i[0],i[1])&&(i[1]=n[1]),et(n[0],i[1])>et(i[0],i[1])&&(i[0]=n[0])):o.push(i=n);for(s=-1/0,r=o.length-1,e=0,i=o[r];e<=r;i=n,++e)n=o[e],(a=et(i[1],n[0]))>s&&(s=a,se=n[0],ue=i[1])}return ri=vr=null,se===1/0||He===1/0?[[NaN,NaN],[NaN,NaN]]:[[se,He],[ue,tt]]}function GB(t,e,r){let{pad:i=.05,maxZoom:n=100}=r||{},o=Km(t),[[s,a],[c,l]]=o,f=i?[[s-i*(c-s),a-i*(l-a)],[c+i*(c-s),l+i*(l-a)]]:o,[u,d]=e;return{...Si({width:u,height:d,bounds:f,padding:r?.padding,maxZoom:n}),width:u,height:d,bearing:0,pitch:0}}function s2(t,e,r,i){let n=s=>({type:"Point",coordinates:e(s)}),o;if(Array.isArray(t))o=t.map(n);else{o=[];for(let s of t)o.push(n(s))}return GB({type:"GeometryCollection",geometries:o},r,i)}function a2(t){return t&&t.locations&&t.flows}function c2(t){return t&&typeof t.setFlowmapState=="function"&&typeof t.getViewportForLocations=="function"&&typeof t.getFlowByIndex=="function"&&typeof t.getLocationById=="function"&&typeof t.getLocationByIndex=="function"&&typeof t.getLayersData=="function"}var ao=class{constructor(e){this.selectors=new Xa(e),this.flowmapData=void 0,this.flowmapState=void 0}setAccessors(e){this.selectors.setAccessors(e)}setFlowmapData(e){this.flowmapData=e}getSelectors(){return this.selectors}getFlowmapData(){return this.flowmapData}async setFlowmapState(e){this.flowmapState=e}getFlowmapState(){return this.flowmapState}async getFlowByIndex(e){return!this.flowmapState||!this.flowmapData?void 0:this.selectors.getFlowsForFlowmapLayer(this.flowmapState,this.flowmapData)?.[e]}async getLocationByIndex(e){return!this.flowmapState||!this.flowmapData?void 0:this.selectors.getLocationsForFlowmapLayer(this.flowmapState,this.flowmapData)?.[e]}async getLayersData(){if(!(!this.flowmapState||!this.flowmapData))return this.selectors.getLayersData(this.flowmapState,this.flowmapData)}async getLocationById(e){if(!this.flowmapState||!this.flowmapData)return;let r=this.selectors.getClusterIndex(this.flowmapState,this.flowmapData);if(r){let n=r.getClusterById(e);if(n)return n}return this.selectors.getLocationsById(this.flowmapState,this.flowmapData)?.get(e)}async getTotalsForLocation(e){if(!(!this.flowmapState||!this.flowmapData))return this.selectors.getLocationTotals(this.flowmapState,this.flowmapData)?.get(e)}async getViewportForLocations(e,r){if(this.flowmapData?.locations)return s2(this.flowmapData.locations,i=>[this.selectors.accessors.getLocationLon(i),this.selectors.accessors.getLocationLat(i)],e,r)}async updateLayersData(e){e(await this.getLayersData())}getClusterZoom(){return this.flowmapState&&this.flowmapData?this.selectors.getClusterZoom(this.flowmapState,this.flowmapData):void 0}getClusterIndex(){return this.flowmapState&&this.flowmapData?this.selectors.getClusterIndex(this.flowmapState,this.flowmapData):void 0}getLocationsById(){return this.flowmapState&&this.flowmapData?this.selectors.getLocationsById(this.flowmapState,this.flowmapData):void 0}getLocationTotals(){return this.flowmapState&&this.flowmapData?this.selectors.getLocationTotals(this.flowmapState,this.flowmapData):void 0}getFlowsForFlowmapLayer(){return this.flowmapState&&this.flowmapData?this.selectors.getFlowsForFlowmapLayer(this.flowmapState,this.flowmapData):void 0}};var Za;(function(t){t.LOCATION="location",t.FLOW="flow"})(Za||(Za={}));var qB=["filter","locationsEnabled","locationTotalsEnabled","locationLabelsEnabled","adaptiveScalesEnabled","flowLinesRenderingMode","animationEnabled","clusteringEnabled","clusteringLevel","fadeEnabled","fadeOpacityEnabled","clusteringAuto","darkMode","fadeAmount","colorScheme","highlightColor","temporalScaleDomain","maxTopFlowsDisplayNum","flowEndpointsInViewportMode"],KB="straight",co;(function(t){t.LOCATION="location",t.FLOW="flow"})(co||(co={}));var Pu=class t extends na{get typedProps(){return this.props}constructor(e){super({...e,onHover:((r,i)=>{let n=Date.now();this.setState({highlightedObject:this._getHighlightedObject(r),lastHoverTime:n});let{onHover:o}=e;o&&this._getFlowmapLayerPickingInfo(r).then(s=>{(this.state?.lastHoverTime??0)<=n&&(this.setState({pickingInfo:s}),o(s,i))})}),onClick:((r,i)=>{let{onClick:n}=e,o=Date.now();this.setState({lastClickTime:o}),n&&this._getFlowmapLayerPickingInfo(r).then(s=>{(this.state?.lastClickTime??0)<=o&&(this.setState({pickingInfo:s}),s&&n(s,i))})})}),this._didWarnAboutAnimationEnabledDeprecation=!1,this._didWarnAboutAnimationEnabledConflict=!1}initializeState(){this.state={accessors:new Sr(this.typedProps),dataProvider:this._getOrMakeDataProvider(),layersData:void 0,highlightedObject:void 0,pickingInfo:void 0,lastHoverTime:void 0,lastClickTime:void 0}}getPickingInfo({info:e}){if(!e.object){let r=this.state?.pickingInfo?.object;if(r)return{...e,object:r,picked:!0}}return e}_getOrMakeDataProvider(){let{data:e,dataProvider:r}=this.typedProps;if(r&&c2(r))return r;if(e&&a2(e)){let i=new ao(this.typedProps);return i.setFlowmapData(e),i}throw new Error("FlowmapLayer: data must be a FlowmapDataProvider or FlowmapData")}_updateDataProvider(){this.setState({dataProvider:this._getOrMakeDataProvider()})}shouldUpdateState(e){let{changeFlags:r}=e;return r.viewportChanged?!0:super.shouldUpdateState(e)}updateState(e){super.updateState(e);let{oldProps:r,props:i,changeFlags:n}=e;if(n.propsChanged,n.dataChanged&&this._updateDataProvider(),(n.viewportChanged||n.dataChanged)&&this.setState({highlightedObject:void 0}),n.viewportChanged||n.dataChanged||n.propsChanged&&qB.some(o=>r[o]!==i[o])){let{dataProvider:o}=this.state||{};o&&(o.setFlowmapState(this._getFlowmapState()),o.updateLayersData(s=>{this.setState({layersData:s,highlightedObject:void 0})},n))}}_getSettingsState(){let e=this.typedProps,r=t.defaultProps,{locationsEnabled:i,locationTotalsEnabled:n,locationLabelsEnabled:o,adaptiveScalesEnabled:s,flowLinesRenderingMode:a,clusteringEnabled:c,clusteringLevel:l,fadeEnabled:f,fadeOpacityEnabled:u,clusteringAuto:d,darkMode:h,fadeAmount:p,colorScheme:g,highlightColor:m,temporalScaleDomain:_,maxTopFlowsDisplayNum:T,flowEndpointsInViewportMode:y}=e;return{locationsEnabled:i??r.locationsEnabled,locationTotalsEnabled:n??r.locationTotalsEnabled,locationLabelsEnabled:o??r.locationLabelsEnabled,adaptiveScalesEnabled:s??r.adaptiveScalesEnabled,flowLinesRenderingMode:a??this._getResolvedFlowLinesRenderingMode(),clusteringEnabled:c??r.clusteringEnabled,clusteringLevel:l,fadeEnabled:f??r.fadeEnabled,fadeOpacityEnabled:u??r.fadeOpacityEnabled,clusteringAuto:d??r.clusteringAuto,darkMode:h??r.darkMode,fadeAmount:p??r.fadeAmount,colorScheme:g,highlightColor:m??r.highlightColor,temporalScaleDomain:_??r.temporalScaleDomain,maxTopFlowsDisplayNum:T??r.maxTopFlowsDisplayNum,flowEndpointsInViewportMode:y??r.flowEndpointsInViewportMode}}_getResolvedFlowLinesRenderingMode(){let{animationEnabled:e,flowLinesRenderingMode:r}=this.typedProps;return r!==void 0?(e!==void 0&&!this._didWarnAboutAnimationEnabledConflict&&(this._didWarnAboutAnimationEnabledConflict=!0,console.warn("FlowmapLayer: `animationEnabled` is deprecated and ignored when `flowLinesRenderingMode` is provided.")),r):e!==void 0?(this._didWarnAboutAnimationEnabledDeprecation||(this._didWarnAboutAnimationEnabledDeprecation=!0,console.warn("FlowmapLayer: `animationEnabled` is deprecated; use `flowLinesRenderingMode` instead.")),e?"animated-straight":"straight"):KB}_getFlowmapState(){let e=this.typedProps;return{viewport:ZB(this.context.viewport),filter:e.filter,settings:this._getSettingsState()}}async _getFlowmapLayerPickingInfo(e){let{index:r,sourceLayer:i}=e,{dataProvider:n,accessors:o}=this.state||{};if(!n||!o)return;let s={...e,picked:e.picked,layer:e.layer,index:e.index,x:e.x,y:e.y,coordinate:e.coordinate,event:e.event};if(i instanceof jn||i instanceof ca||i instanceof Vn){let a=r===-1?void 0:await n.getFlowByIndex(r);if(a){let c=await n.getLocationById(o.getFlowOriginId(a)),l=await n.getLocationById(o.getFlowDestId(a));if(c&&l)return{...s,object:{type:Za.FLOW,flow:a,origin:c,dest:l,count:o.getFlowMagnitude(a)}}}}else if(i instanceof da){let a=r===-1?void 0:await n.getLocationByIndex(r);if(a){let c=o.getLocationId(a),l=o.getLocationName(a),f=await n.getTotalsForLocation(c),{circleAttributes:u}=this.state?.layersData||{};if(f&&u){let d=Su(u,e.index);return{...s,object:{type:Za.LOCATION,location:a,id:c,name:l,totals:f,circleRadius:d}}}}}}_getHighlightedObject(e){let{index:r,sourceLayer:i}=e;if(!(r<0)){if(i instanceof jn||i instanceof ca||i instanceof Vn){let{lineAttributes:n}=this.state?.layersData||{};if(n){let o=kv(n,r);return this.typedProps.fadeOpacityEnabled&&(o={...o,attributes:{...o.attributes,getColor:{...o.attributes.getColor,value:new Uint8Array([...o.attributes.getColor.value.slice(0,3),255])}}}),{type:co.FLOW,lineAttributes:o}}}else if(i instanceof da){let{circleAttributes:n}=this.state?.layersData||{};if(n)return{type:co.LOCATION,coords:Wm(n,r),radius:Su(n,r)}}}}renderLayers(){let e=this.typedProps,r=this._getResolvedFlowLinesRenderingMode(),i=e.highlightColor??t.defaultProps.highlightColor,n=e.flowLineThicknessScale??t.defaultProps.flowLineThicknessScale,o=e.flowLineCurviness??t.defaultProps.flowLineCurviness,s=[];if(this.state?.layersData){let{layersData:a,highlightedObject:c}=this.state,{circleAttributes:l,lineAttributes:f,locationLabels:u}=a||{};if(l&&f){let d=HA(this._getSettingsState()),h=dt(d.outlineColor||(e.darkMode?"#000":"#fff")),p={data:f,parameters:{...e.parameters??{},depthTest:!1}};switch(r){case"animated-straight":s.push(new ca({...this.getSubLayerProps({...p,id:"animated-flow-lines",drawOutline:!1,thicknessUnit:10*n})}));break;case"curved":s.push(new Vn({...this.getSubLayerProps({...p,id:"curved-flow-lines",drawOutline:!0,outlineColor:h,thicknessUnit:12*n,curviness:o})}));break;default:s.push(new jn({...this.getSubLayerProps({...p,id:"flow-lines",drawOutline:!0,outlineColor:h,thicknessUnit:12*n})}));break}if(s.push(new da(this.getSubLayerProps({id:"circles",data:l,emptyColor:e.darkMode?[0,0,0,255]:[255,255,255,255],outlineEmptyMix:.4}))),c)switch(c.type){case co.LOCATION:s.push(new Eg({...this.getSubLayerProps({id:"location-highlight",data:[c],pickable:!1,antialiasing:!0,stroked:!0,filled:!1,lineWidthUnits:"pixels",getLineWidth:2,radiusUnits:"pixels",getRadius:g=>g.radius,getLineColor:dt(i),getPosition:g=>g.coords})}));break;case co.FLOW:r==="curved"?s.push(new Vn({...this.getSubLayerProps({id:"flow-highlight",data:c.lineAttributes,drawOutline:!0,pickable:!1,outlineColor:dt(i),outlineThickness:1.5,thicknessUnit:12*n,curviness:o,parameters:{depthTest:!1}})})):s.push(new jn({...this.getSubLayerProps({id:"flow-highlight",data:c.lineAttributes,drawOutline:!0,pickable:!1,outlineColor:dt(i),outlineThickness:1.5,thicknessUnit:12*n,parameters:{depthTest:!1}})}));break}}u&&s.push(new Mg(this.getSubLayerProps({id:"location-labels",data:u,maxWidth:1e3,pickable:!1,fontFamily:"Helvetica",getPixelOffset:(d,{index:h})=>[0,Su(l,h)+5],getPosition:(d,{index:h})=>Wm(l,h),getText:d=>d,getSize:10,getColor:[255,255,255,255],getAngle:0,getTextAnchor:"middle",getAlignmentBaseline:"top"})))}return s}};Pu.defaultProps={darkMode:!0,fadeAmount:50,locationsEnabled:!0,locationTotalsEnabled:!0,locationLabelsEnabled:!1,clusteringEnabled:!0,fadeEnabled:!0,fadeOpacityEnabled:!1,clusteringAuto:!0,clusteringLevel:void 0,adaptiveScalesEnabled:!0,temporalScaleDomain:"selected",flowLineThicknessScale:1,flowLineCurviness:1,colorScheme:"Teal",highlightColor:"orange",maxTopFlowsDisplayNum:5e3,flowEndpointsInViewportMode:"any"};var Zm=Pu;function ZB(t){let{width:e,height:r,longitude:i,latitude:n,zoom:o,pitch:s,bearing:a}=t;return{width:e,height:r,longitude:i,latitude:n,zoom:o,pitch:s,bearing:a}}window.FlowmapGL={Deck:Bn,FlowmapLayer:Zm,MapboxOverlay:Wn};})(); +//# sourceMappingURL=flowmap-gl-bundle.min.js.map diff --git a/inst/htmlwidgets/lib/flowmap-gl/flowmap-gl-bundle.min.js.map b/inst/htmlwidgets/lib/flowmap-gl/flowmap-gl-bundle.min.js.map new file mode 100644 index 0000000..9240d9b --- /dev/null +++ b/inst/htmlwidgets/lib/flowmap-gl/flowmap-gl-bundle.min.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["node_modules/@probe.gl/env/src/lib/globals.ts","node_modules/@probe.gl/env/src/lib/is-electron.ts","node_modules/@probe.gl/env/src/lib/is-browser.ts","node_modules/@probe.gl/env/src/lib/get-browser.ts","node_modules/@probe.gl/env/src/index.ts","node_modules/@probe.gl/log/src/utils/assert.ts","node_modules/@probe.gl/log/src/loggers/log-utils.ts","node_modules/@probe.gl/log/src/loggers/base-log.ts","node_modules/@probe.gl/log/src/utils/local-storage.ts","node_modules/@probe.gl/log/src/utils/formatters.ts","node_modules/@probe.gl/log/src/utils/color.ts","node_modules/@probe.gl/log/src/utils/autobind.ts","node_modules/@probe.gl/log/src/utils/hi-res-timestamp.ts","node_modules/@probe.gl/log/src/loggers/probe-log.ts","node_modules/@probe.gl/log/src/init.ts","node_modules/@probe.gl/log/src/index.ts","node_modules/@probe.gl/stats/src/utils/hi-res-timestamp.ts","node_modules/@probe.gl/stats/src/lib/stat.ts","node_modules/@probe.gl/stats/src/lib/stats.ts","node_modules/@probe.gl/stats/src/index.ts","node_modules/@luma.gl/core/src/utils/stats-manager.ts","node_modules/@luma.gl/core/src/utils/log.ts","node_modules/@luma.gl/core/src/utils/uid.ts","node_modules/@luma.gl/core/src/adapter/resources/resource.ts","node_modules/@luma.gl/core/src/adapter/resources/buffer.ts","node_modules/@luma.gl/core/src/shadertypes/data-types/data-type-decoder.ts","node_modules/@luma.gl/core/src/shadertypes/vertex-types/vertex-format-decoder.ts","node_modules/@luma.gl/core/src/shadertypes/texture-types/texture-format-table.ts","node_modules/@luma.gl/core/src/shadertypes/texture-types/texture-format-decoder.ts","node_modules/@luma.gl/core/src/shadertypes/image-types/image-types.ts","node_modules/@luma.gl/core/src/adapter/device.ts","node_modules/@luma.gl/core/src/adapter/luma.ts","node_modules/@luma.gl/core/src/adapter/adapter.ts","node_modules/@luma.gl/core/src/adapter/canvas-observer.ts","node_modules/@luma.gl/core/src/utils/promise-utils.ts","node_modules/@luma.gl/core/src/utils/assert.ts","node_modules/@luma.gl/core/src/adapter/canvas-surface.ts","node_modules/@luma.gl/core/src/adapter/canvas-context.ts","node_modules/@luma.gl/core/src/adapter/presentation-context.ts","node_modules/@luma.gl/core/src/adapter/resources/sampler.ts","node_modules/@luma.gl/core/src/adapter/resources/texture.ts","node_modules/@luma.gl/core/src/adapter/resources/texture-view.ts","node_modules/@luma.gl/core/src/adapter-utils/format-compiler-log.ts","node_modules/@luma.gl/core/src/adapter/resources/shader.ts","node_modules/@luma.gl/core/src/adapter/resources/framebuffer.ts","node_modules/@luma.gl/core/src/adapter/resources/render-pipeline.ts","node_modules/@luma.gl/core/src/adapter/resources/shared-render-pipeline.ts","node_modules/@luma.gl/core/src/adapter/resources/compute-pipeline.ts","node_modules/@luma.gl/core/src/factories/pipeline-factory.ts","node_modules/@luma.gl/core/src/factories/shader-factory.ts","node_modules/@luma.gl/core/src/adapter-utils/bind-groups.ts","node_modules/@luma.gl/core/src/adapter/resources/render-pass.ts","node_modules/@luma.gl/core/src/adapter/resources/command-encoder.ts","node_modules/@luma.gl/core/src/adapter/resources/command-buffer.ts","node_modules/@luma.gl/core/src/shadertypes/shader-types/shader-type-decoder.ts","node_modules/@luma.gl/core/src/adapter-utils/get-attribute-from-layouts.ts","node_modules/@luma.gl/core/src/adapter/resources/vertex-array.ts","node_modules/@luma.gl/core/src/adapter/resources/transform-feedback.ts","node_modules/@luma.gl/core/src/adapter/resources/query-set.ts","node_modules/@luma.gl/core/src/adapter/resources/fence.ts","node_modules/@luma.gl/core/src/shadertypes/data-types/decode-data-types.ts","node_modules/@luma.gl/core/src/shadertypes/shader-types/shader-block-layout.ts","node_modules/@luma.gl/core/src/utils/array-utils-flat.ts","node_modules/@luma.gl/core/src/utils/is-array.ts","node_modules/@luma.gl/core/src/portable/shader-block-writer.ts","node_modules/@luma.gl/core/src/utils/array-equal.ts","node_modules/@luma.gl/core/src/portable/uniform-block.ts","node_modules/@luma.gl/core/src/portable/uniform-store.ts","node_modules/@luma.gl/core/src/index.ts","node_modules/@luma.gl/webgl/src/constants/webgl-constants.ts","node_modules/@luma.gl/webgl/src/constants/index.ts","node_modules/@luma.gl/webgl/src/context/polyfills/polyfill-webgl1-extensions.ts","node_modules/@luma.gl/webgl/src/utils/load-script.ts","node_modules/@luma.gl/webgl/src/context/helpers/webgl-context-data.ts","node_modules/@luma.gl/webgl/src/context/debug/spector.ts","node_modules/@luma.gl/webgl/src/context/debug/webgl-developer-tools.ts","node_modules/@luma.gl/webgl/src/context/parameters/webgl-parameter-tables.ts","node_modules/@luma.gl/webgl/src/context/parameters/unified-parameter-api.ts","node_modules/@luma.gl/webgl/src/context/state-tracker/deep-array-equal.ts","node_modules/@luma.gl/webgl/src/context/state-tracker/webgl-state-tracker.ts","node_modules/@luma.gl/webgl/src/context/helpers/create-browser-context.ts","node_modules/@luma.gl/webgl/src/context/helpers/webgl-extensions.ts","node_modules/@luma.gl/webgl/src/adapter/device-helpers/webgl-device-info.ts","node_modules/@luma.gl/webgl/src/adapter/converters/webgl-vertex-formats.ts","node_modules/@luma.gl/webgl/src/adapter/converters/webgl-texture-table.ts","node_modules/@luma.gl/webgl/src/adapter/device-helpers/webgl-device-features.ts","node_modules/@luma.gl/webgl/src/adapter/device-helpers/webgl-device-limits.ts","node_modules/@luma.gl/webgl/src/adapter/resources/webgl-framebuffer.ts","node_modules/@luma.gl/webgl/src/adapter/webgl-canvas-context.ts","node_modules/@luma.gl/webgl/src/adapter/webgl-presentation-context.ts","node_modules/@luma.gl/webgl/src/utils/uid.ts","node_modules/@luma.gl/webgl/src/adapter/resources/webgl-buffer.ts","node_modules/@luma.gl/webgl/src/adapter/helpers/parse-shader-compiler-log.ts","node_modules/@luma.gl/webgl/src/adapter/resources/webgl-shader.ts","node_modules/@luma.gl/webgl/src/adapter/converters/device-parameters.ts","node_modules/@luma.gl/webgl/src/adapter/converters/sampler-parameters.ts","node_modules/@luma.gl/webgl/src/adapter/resources/webgl-sampler.ts","node_modules/@luma.gl/webgl/src/context/state-tracker/with-parameters.ts","node_modules/@luma.gl/webgl/src/adapter/resources/webgl-texture-view.ts","node_modules/@luma.gl/webgl/src/adapter/converters/shader-formats.ts","node_modules/@luma.gl/webgl/src/adapter/resources/webgl-texture.ts","node_modules/@luma.gl/webgl/src/adapter/helpers/set-uniform.ts","node_modules/@luma.gl/webgl/src/adapter/helpers/webgl-topology-utils.ts","node_modules/@luma.gl/webgl/src/adapter/resources/webgl-render-pipeline.ts","node_modules/@luma.gl/webgl/src/adapter/converters/webgl-shadertypes.ts","node_modules/@luma.gl/webgl/src/adapter/helpers/get-shader-layout-from-glsl.ts","node_modules/@luma.gl/webgl/src/adapter/resources/webgl-shared-render-pipeline.ts","node_modules/@luma.gl/webgl/src/adapter/resources/webgl-command-buffer.ts","node_modules/@luma.gl/webgl/src/adapter/resources/webgl-render-pass.ts","node_modules/@luma.gl/webgl/src/adapter/resources/webgl-command-encoder.ts","node_modules/@luma.gl/webgl/src/utils/fill-array.ts","node_modules/@luma.gl/webgl/src/adapter/resources/webgl-vertex-array.ts","node_modules/@luma.gl/webgl/src/adapter/resources/webgl-transform-feedback.ts","node_modules/@luma.gl/webgl/src/adapter/resources/webgl-query-set.ts","node_modules/@luma.gl/webgl/src/adapter/resources/webgl-fence.ts","node_modules/@luma.gl/webgl/src/adapter/helpers/format-utils.ts","node_modules/@luma.gl/webgl/src/adapter/helpers/webgl-texture-utils.ts","node_modules/@luma.gl/webgl/src/adapter/webgl-device.ts","node_modules/@luma.gl/webgl/src/adapter/webgl-adapter.ts","node_modules/@luma.gl/webgl/src/index.ts","node_modules/seedrandom/lib/alea.js","node_modules/seedrandom/lib/xor128.js","node_modules/seedrandom/lib/xorwow.js","node_modules/seedrandom/lib/xorshift7.js","node_modules/seedrandom/lib/xor4096.js","node_modules/seedrandom/lib/tychei.js","node_modules/seedrandom/seedrandom.js","node_modules/seedrandom/index.js","node_modules/@loaders.gl/loader-utils/src/lib/env-utils/assert.ts","node_modules/@loaders.gl/loader-utils/src/lib/env-utils/globals.ts","node_modules/@loaders.gl/loader-utils/src/lib/log-utils/log.ts","node_modules/@loaders.gl/loader-utils/src/lib/javascript-utils/is-type.ts","node_modules/@loaders.gl/loader-utils/src/lib/option-utils/merge-options.ts","node_modules/@loaders.gl/worker-utils/src/lib/npm-tag.ts","node_modules/@loaders.gl/worker-utils/src/lib/env-utils/version.ts","node_modules/@loaders.gl/worker-utils/src/lib/env-utils/assert.ts","node_modules/@loaders.gl/worker-utils/src/lib/env-utils/globals.ts","node_modules/@loaders.gl/worker-utils/src/lib/worker-farm/worker-job.ts","node_modules/@loaders.gl/worker-utils/src/lib/node/worker_threads-browser.ts","node_modules/@loaders.gl/worker-utils/src/lib/worker-utils/get-loadable-worker-url.ts","node_modules/@loaders.gl/worker-utils/src/lib/worker-utils/get-transfer-list.ts","node_modules/@loaders.gl/worker-utils/src/lib/worker-farm/worker-thread.ts","node_modules/@loaders.gl/worker-utils/src/lib/worker-farm/worker-pool.ts","node_modules/@loaders.gl/worker-utils/src/lib/worker-farm/worker-farm.ts","node_modules/@loaders.gl/worker-utils/src/lib/worker-api/get-worker-url.ts","node_modules/@loaders.gl/worker-utils/src/lib/worker-api/validate-worker-version.ts","node_modules/@loaders.gl/loader-utils/src/lib/worker-loader-utils/parse-with-worker.ts","node_modules/@loaders.gl/loader-utils/src/lib/binary-utils/array-buffer-utils.ts","node_modules/@loaders.gl/loader-utils/src/lib/iterators/async-iteration.ts","node_modules/@loaders.gl/loader-utils/src/lib/path-utils/file-aliases.ts","node_modules/@loaders.gl/loader-utils/src/lib/binary-utils/memory-conversion-utils.ts","node_modules/@loaders.gl/loader-utils/src/lib/path-utils/path.ts","node_modules/@loaders.gl/loader-utils/src/lib/path-utils/get-cwd.ts","node_modules/@loaders.gl/core/src/lib/fetch/fetch-error.ts","node_modules/@loaders.gl/core/src/lib/utils/mime-type-utils.ts","node_modules/@loaders.gl/core/src/lib/utils/url-utils.ts","node_modules/@loaders.gl/core/src/lib/utils/resource-utils.ts","node_modules/@loaders.gl/core/src/lib/utils/response-utils.ts","node_modules/@loaders.gl/core/src/lib/fetch/fetch-file.ts","node_modules/@loaders.gl/core/src/lib/loader-utils/loggers.ts","node_modules/@loaders.gl/core/src/lib/loader-utils/option-defaults.ts","node_modules/@loaders.gl/core/src/lib/loader-utils/option-utils.ts","node_modules/@loaders.gl/core/src/lib/loader-utils/normalize-loader.ts","node_modules/@loaders.gl/core/src/lib/api/register-loaders.ts","node_modules/@loaders.gl/core/src/lib/api/select-loader.ts","node_modules/@loaders.gl/core/src/iterators/make-iterator/make-string-iterator.ts","node_modules/@loaders.gl/core/src/iterators/make-iterator/make-array-buffer-iterator.ts","node_modules/@loaders.gl/core/src/iterators/make-iterator/make-blob-iterator.ts","node_modules/@loaders.gl/core/src/iterators/make-iterator/make-stream-iterator.ts","node_modules/@loaders.gl/core/src/iterators/make-iterator/make-iterator.ts","node_modules/@loaders.gl/core/src/lib/loader-utils/get-data.ts","node_modules/@loaders.gl/core/src/lib/loader-utils/get-fetch-function.ts","node_modules/@loaders.gl/core/src/lib/loader-utils/loader-context.ts","node_modules/@loaders.gl/core/src/lib/api/parse.ts","node_modules/@math.gl/types/src/is-array.ts","node_modules/@loaders.gl/core/src/lib/api/load.ts","node_modules/@loaders.gl/images/src/lib/utils/version.ts","node_modules/@loaders.gl/images/src/lib/category-api/image-type.ts","node_modules/@loaders.gl/images/src/lib/category-api/parsed-image-api.ts","node_modules/@loaders.gl/images/src/lib/parsers/svg-utils.ts","node_modules/@loaders.gl/images/src/lib/parsers/parse-to-image.ts","node_modules/@loaders.gl/images/src/lib/parsers/parse-to-image-bitmap.ts","node_modules/@loaders.gl/images/src/lib/category-api/parse-isobmff-binary.ts","node_modules/@loaders.gl/images/src/lib/category-api/binary-image-api.ts","node_modules/@loaders.gl/images/src/lib/parsers/parse-to-node-image.ts","node_modules/@loaders.gl/images/src/lib/parsers/parse-image.ts","node_modules/@loaders.gl/images/src/image-loader.ts","node_modules/@deck.gl/core/src/utils/log.ts","node_modules/@deck.gl/core/src/debug/index.ts","node_modules/@deck.gl/core/src/utils/json-loader.ts","node_modules/@deck.gl/core/src/lib/init.ts","node_modules/@luma.gl/shadertools/src/lib/utils/assert.ts","node_modules/@luma.gl/shadertools/src/lib/filters/prop-types.ts","node_modules/@luma.gl/shadertools/src/module-injectors.ts","node_modules/@luma.gl/shadertools/src/lib/shader-assembly/shader-injections.ts","node_modules/@luma.gl/shadertools/src/lib/shader-module/shader-module.ts","node_modules/@luma.gl/shadertools/src/lib/shader-module/shader-module-dependencies.ts","node_modules/@luma.gl/shadertools/src/lib/shader-module/shader-module-uniform-layout.ts","node_modules/@luma.gl/shadertools/src/lib/shader-assembly/platform-defines.ts","node_modules/@luma.gl/shadertools/src/lib/shader-transpiler/transpile-glsl-shader.ts","node_modules/@luma.gl/shadertools/src/lib/shader-assembly/shader-hooks.ts","node_modules/@luma.gl/shadertools/src/lib/glsl-utils/get-shader-info.ts","node_modules/@luma.gl/shadertools/src/lib/shader-assembly/wgsl-binding-scan.ts","node_modules/@luma.gl/shadertools/src/lib/shader-assembly/wgsl-binding-debug.ts","node_modules/@luma.gl/shadertools/src/lib/shader-assembly/assemble-shaders.ts","node_modules/@luma.gl/shadertools/src/lib/preprocessor/preprocessor.ts","node_modules/@luma.gl/shadertools/src/lib/shader-assembler.ts","node_modules/@luma.gl/shadertools/src/lib/glsl-utils/shader-utils.ts","node_modules/@math.gl/core/src/lib/common.ts","node_modules/@math.gl/core/src/classes/base/math-array.ts","node_modules/@math.gl/core/src/lib/validators.ts","node_modules/@math.gl/core/src/lib/assert.ts","node_modules/@math.gl/core/src/classes/base/vector.ts","node_modules/@math.gl/core/src/gl-matrix/vec2.ts","node_modules/@math.gl/core/src/gl-matrix/common.js","node_modules/@math.gl/core/src/lib/gl-matrix-extras.ts","node_modules/@math.gl/core/src/gl-matrix/vec3.ts","node_modules/@math.gl/core/src/classes/vector3.ts","node_modules/@math.gl/core/src/classes/base/matrix.ts","node_modules/@math.gl/core/src/gl-matrix/mat4.ts","node_modules/@math.gl/core/src/gl-matrix/vec4.ts","node_modules/@math.gl/core/src/classes/matrix4.ts","node_modules/@luma.gl/shadertools/src/modules/math/fp64/fp64-utils.ts","node_modules/@luma.gl/shadertools/src/lib/color/normalize-byte-colors.ts","node_modules/@luma.gl/shadertools/src/modules/math/fp32/fp32.ts","node_modules/@luma.gl/shadertools/src/modules/math/fp64/fp64-arithmetic-glsl.ts","node_modules/@luma.gl/shadertools/src/modules/math/fp64/fp64-arithmetic-wgsl.ts","node_modules/@luma.gl/shadertools/src/modules/math/fp64/fp64.ts","node_modules/@luma.gl/shadertools/src/modules/engine/picking/picking.ts","node_modules/@deck.gl/core/src/shaderlib/misc/layer-uniforms.ts","node_modules/@deck.gl/core/src/shaderlib/color/color.ts","node_modules/@deck.gl/core/src/shaderlib/misc/geometry.ts","node_modules/mjolnir.js/src/hammerjs/input/input-consts.ts","node_modules/mjolnir.js/src/hammerjs/recognizer/recognizer-state.ts","node_modules/mjolnir.js/src/hammerjs/touchaction/touchaction-Consts.ts","node_modules/mjolnir.js/src/hammerjs/touchaction/clean-touch-actions.ts","node_modules/mjolnir.js/src/hammerjs/touchaction/touchaction.ts","node_modules/mjolnir.js/src/hammerjs/utils/split-str.ts","node_modules/mjolnir.js/src/hammerjs/utils/event-listeners.ts","node_modules/mjolnir.js/src/hammerjs/utils/get-window-for-element.ts","node_modules/mjolnir.js/src/hammerjs/utils/has-parent.ts","node_modules/mjolnir.js/src/hammerjs/input/get-center.ts","node_modules/mjolnir.js/src/hammerjs/input/simple-clone-input-data.ts","node_modules/mjolnir.js/src/hammerjs/input/get-distance.ts","node_modules/mjolnir.js/src/hammerjs/input/get-angle.ts","node_modules/mjolnir.js/src/hammerjs/input/get-direction.ts","node_modules/mjolnir.js/src/hammerjs/input/get-delta-xy.ts","node_modules/mjolnir.js/src/hammerjs/input/get-velocity.ts","node_modules/mjolnir.js/src/hammerjs/input/get-scale.ts","node_modules/mjolnir.js/src/hammerjs/input/get-rotation.ts","node_modules/mjolnir.js/src/hammerjs/input/compute-interval-input-data.ts","node_modules/mjolnir.js/src/hammerjs/input/compute-input-data.ts","node_modules/mjolnir.js/src/hammerjs/input/input-handler.ts","node_modules/mjolnir.js/src/hammerjs/input/input.ts","node_modules/mjolnir.js/src/hammerjs/inputs/pointerevent.ts","node_modules/mjolnir.js/src/hammerjs/utils/prefixed.ts","node_modules/mjolnir.js/src/hammerjs/manager.ts","node_modules/mjolnir.js/src/hammerjs/utils/unique-id.ts","node_modules/mjolnir.js/src/hammerjs/recognizer/state-str.ts","node_modules/mjolnir.js/src/hammerjs/recognizer/recognizer.ts","node_modules/mjolnir.js/src/hammerjs/recognizers/attribute.ts","node_modules/mjolnir.js/src/hammerjs/recognizers/tap.ts","node_modules/mjolnir.js/src/hammerjs/recognizers/pan.ts","node_modules/mjolnir.js/src/hammerjs/recognizers/pinch.ts","node_modules/mjolnir.js/src/inputs/input.ts","node_modules/mjolnir.js/src/utils/globals.ts","node_modules/mjolnir.js/src/inputs/wheel-input.ts","node_modules/mjolnir.js/src/inputs/move-input.ts","node_modules/mjolnir.js/src/inputs/key-input.ts","node_modules/mjolnir.js/src/inputs/contextmenu-input.ts","node_modules/mjolnir.js/src/utils/event-utils.ts","node_modules/mjolnir.js/src/utils/event-registrar.ts","node_modules/mjolnir.js/src/event-manager.ts","node_modules/@deck.gl/core/src/lib/constants.ts","node_modules/@deck.gl/core/src/utils/memoize.ts","node_modules/@deck.gl/core/src/shaderlib/project/viewport-uniforms.ts","node_modules/@deck.gl/core/src/shaderlib/project/project.wgsl.ts","node_modules/@deck.gl/core/src/shaderlib/project/project.glsl.ts","node_modules/@deck.gl/core/src/shaderlib/project/project.ts","node_modules/@deck.gl/core/src/shaderlib/project32/project32.ts","node_modules/@math.gl/web-mercator/src/math-utils.ts","node_modules/@math.gl/web-mercator/src/assert.ts","node_modules/@math.gl/web-mercator/src/web-mercator-utils.ts","node_modules/@math.gl/web-mercator/src/fit-bounds.ts","node_modules/@math.gl/web-mercator/src/get-bounds.ts","node_modules/@math.gl/web-mercator/src/web-mercator-viewport.ts","node_modules/@deck.gl/core/src/shaderlib/shadow/shadow.ts","node_modules/@deck.gl/core/src/shaderlib/picking/picking.ts","node_modules/@deck.gl/core/src/shaderlib/index.ts","node_modules/@deck.gl/core/src/effects/lighting/ambient-light.ts","node_modules/@deck.gl/core/src/effects/lighting/directional-light.ts","node_modules/@deck.gl/core/src/passes/pass.ts","node_modules/@deck.gl/core/src/passes/layers-pass.ts","node_modules/@deck.gl/core/src/passes/shadow-pass.ts","node_modules/@deck.gl/core/src/effects/lighting/lighting-effect.ts","node_modules/@deck.gl/core/src/utils/typed-array-manager.ts","node_modules/@deck.gl/core/src/utils/math-utils.ts","node_modules/@deck.gl/core/src/viewports/viewport.ts","node_modules/@deck.gl/core/src/viewports/web-mercator-viewport.ts","node_modules/@deck.gl/core/src/shaderlib/project/project-functions.ts","node_modules/@luma.gl/engine/src/animation/timeline.ts","node_modules/@luma.gl/engine/src/animation-loop/animation-loop.ts","node_modules/@luma.gl/engine/src/animation-loop/request-animation-frame.ts","node_modules/@luma.gl/engine/src/model/model.ts","node_modules/@luma.gl/engine/src/geometry/gpu-geometry.ts","node_modules/@luma.gl/engine/src/utils/uid.ts","node_modules/@luma.gl/engine/src/debug/debug-shader-layout.ts","node_modules/@luma.gl/engine/src/debug/debug-framebuffer.ts","node_modules/@luma.gl/engine/src/utils/deep-equal.ts","node_modules/@luma.gl/engine/src/utils/buffer-layout-helper.ts","node_modules/@luma.gl/engine/src/utils/buffer-layout-order.ts","node_modules/@luma.gl/engine/src/utils/shader-module-utils.ts","node_modules/@luma.gl/engine/src/shader-inputs.ts","node_modules/@luma.gl/engine/src/model/split-uniforms-and-bindings.ts","node_modules/@luma.gl/engine/src/dynamic-texture/dynamic-texture.ts","node_modules/@luma.gl/engine/src/dynamic-texture/texture-data.ts","node_modules/@luma.gl/engine/src/compute/buffer-transform.ts","node_modules/@luma.gl/engine/src/geometry/geometry.ts","node_modules/@deck.gl/core/src/passes/pick-layers-pass.ts","node_modules/@deck.gl/core/src/lifecycle/constants.ts","node_modules/@deck.gl/core/src/utils/flatten.ts","node_modules/@deck.gl/core/src/lib/layer-manager.ts","node_modules/@deck.gl/core/src/lib/resource/resource.ts","node_modules/@deck.gl/core/src/lib/resource/resource-manager.ts","node_modules/@deck.gl/core/src/utils/deep-equal.ts","node_modules/@deck.gl/core/src/lib/view-manager.ts","node_modules/@deck.gl/core/src/utils/positions.ts","node_modules/@deck.gl/core/src/utils/deep-merge.ts","node_modules/@deck.gl/core/src/views/view.ts","node_modules/@deck.gl/core/src/transitions/transition.ts","node_modules/@deck.gl/core/src/controllers/transition-manager.ts","node_modules/@deck.gl/core/src/utils/assert.ts","node_modules/@deck.gl/core/src/transitions/transition-interpolator.ts","node_modules/@deck.gl/core/src/viewports/globe-viewport.ts","node_modules/@deck.gl/core/src/transitions/linear-interpolator.ts","node_modules/@deck.gl/core/src/controllers/controller.ts","node_modules/@deck.gl/core/src/controllers/view-state.ts","node_modules/@deck.gl/core/src/controllers/map-controller.ts","node_modules/@deck.gl/core/src/views/map-view.ts","node_modules/@deck.gl/core/src/lib/effect-manager.ts","node_modules/@deck.gl/core/src/passes/draw-layers-pass.ts","node_modules/@deck.gl/core/src/lib/deck-renderer.ts","node_modules/@deck.gl/core/src/lib/deck-picker.ts","node_modules/@deck.gl/core/src/lib/picking/query-object.ts","node_modules/@deck.gl/core/src/lib/picking/pick-info.ts","node_modules/@deck.gl/core/src/lib/widget-manager.ts","node_modules/@deck.gl/core/src/utils/apply-styles.ts","node_modules/@deck.gl/core/src/lib/widget.ts","node_modules/@deck.gl/core/src/lib/tooltip-widget.ts","node_modules/@deck.gl/core/src/lib/deck.ts","node_modules/@deck.gl/core/src/lib/attribute/data-column.ts","node_modules/@deck.gl/core/src/lib/attribute/gl-utils.ts","node_modules/@deck.gl/core/src/utils/iterable-utils.ts","node_modules/@deck.gl/core/src/utils/range.ts","node_modules/@deck.gl/core/src/lib/attribute/transition-settings.ts","node_modules/@deck.gl/core/src/lib/attribute/attribute.ts","node_modules/@deck.gl/core/src/utils/array-utils.ts","node_modules/@deck.gl/core/src/transitions/gpu-transition-utils.ts","node_modules/@deck.gl/core/src/transitions/gpu-transition.ts","node_modules/@deck.gl/core/src/transitions/gpu-interpolation-transition.ts","node_modules/@deck.gl/core/src/transitions/gpu-spring-transition.ts","node_modules/@deck.gl/core/src/lib/attribute/attribute-transition-manager.ts","node_modules/@deck.gl/core/src/lib/attribute/attribute-manager.ts","node_modules/@deck.gl/core/src/lib/layer.ts","node_modules/@deck.gl/core/src/transitions/cpu-interpolation-transition.ts","node_modules/@deck.gl/core/src/transitions/cpu-spring-transition.ts","node_modules/@deck.gl/core/src/lib/uniform-transition-manager.ts","node_modules/@deck.gl/core/src/lifecycle/props.ts","node_modules/@deck.gl/core/src/utils/count.ts","node_modules/@deck.gl/core/src/utils/shader.ts","node_modules/@deck.gl/core/src/utils/texture.ts","node_modules/@deck.gl/core/src/lifecycle/prop-types.ts","node_modules/@deck.gl/core/src/lifecycle/create-props.ts","node_modules/@deck.gl/core/src/lifecycle/component.ts","node_modules/@deck.gl/core/src/lifecycle/component-state.ts","node_modules/@deck.gl/core/src/lib/layer-state.ts","node_modules/@deck.gl/core/src/lib/composite-layer.ts","node_modules/@deck.gl/core/src/controllers/globe-controller.ts","node_modules/@deck.gl/core/src/views/globe-view.ts","node_modules/@deck.gl/mapbox/src/mapbox-layer-group.ts","node_modules/@deck.gl/mapbox/src/resolve-layer-groups.ts","node_modules/@deck.gl/mapbox/src/deck-utils.ts","node_modules/@deck.gl/mapbox/src/mapbox-overlay.ts","node_modules/@flowmap.gl/layers/src/AnimatedFlowLinesLayer/AnimatedFlowLinesLayerFragment.glsl.ts","node_modules/@flowmap.gl/layers/src/AnimatedFlowLinesLayer/AnimatedFlowLinesLayerVertex.glsl.ts","node_modules/@flowmap.gl/layers/src/AnimatedFlowLinesLayer/AnimatedFlowLinesLayerUniforms.ts","node_modules/@flowmap.gl/layers/src/AnimatedFlowLinesLayer/AnimatedFlowLinesLayer.ts","node_modules/@flowmap.gl/layers/src/AnimatedFlowLinesLayer/index.ts","node_modules/@flowmap.gl/layers/src/FlowLinesLayer/FlowLinesLayerUniforms.ts","node_modules/@flowmap.gl/layers/src/CurvedFlowLinesLayer/CurvedFlowLinesLayerFragment.glsl.ts","node_modules/@flowmap.gl/layers/src/CurvedFlowLinesLayer/CurvedFlowLinesLayerVertex.glsl.ts","node_modules/@flowmap.gl/layers/src/CurvedFlowLinesLayer/CurvedFlowLinesLayer.ts","node_modules/@flowmap.gl/layers/src/CurvedFlowLinesLayer/index.ts","node_modules/@flowmap.gl/layers/src/FlowLinesLayer/FlowLinesLayerFragment.glsl.ts","node_modules/@flowmap.gl/layers/src/FlowLinesLayer/FlowLinesLayerVertex.glsl.ts","node_modules/@flowmap.gl/layers/src/FlowLinesLayer/FlowLinesLayer.ts","node_modules/@flowmap.gl/layers/src/FlowLinesLayer/index.ts","node_modules/@flowmap.gl/layers/src/FlowCirclesLayer/FlowCirclesLayerFragment.glsl.ts","node_modules/@flowmap.gl/layers/src/FlowCirclesLayer/FlowCirclesLayerVertex.glsl.ts","node_modules/@flowmap.gl/layers/src/FlowCirclesLayer/FlowCirclesLayerUniforms.ts","node_modules/@flowmap.gl/layers/src/FlowCirclesLayer/FlowCirclesLayer.ts","node_modules/@flowmap.gl/layers/src/FlowCirclesLayer/index.ts","node_modules/@deck.gl/layers/src/icon-layer/icon-layer-uniforms.ts","node_modules/@deck.gl/layers/src/icon-layer/icon-layer-vertex.glsl.ts","node_modules/@deck.gl/layers/src/icon-layer/icon-layer-fragment.glsl.ts","node_modules/@deck.gl/layers/src/icon-layer/icon-layer.wgsl.ts","node_modules/@deck.gl/layers/src/icon-layer/icon-manager.ts","node_modules/@deck.gl/layers/src/icon-layer/icon-layer.ts","node_modules/@deck.gl/layers/src/scatterplot-layer/scatterplot-layer-uniforms.ts","node_modules/@deck.gl/layers/src/scatterplot-layer/scatterplot-layer-vertex.glsl.ts","node_modules/@deck.gl/layers/src/scatterplot-layer/scatterplot-layer-fragment.glsl.ts","node_modules/@deck.gl/layers/src/scatterplot-layer/scatterplot-layer.wgsl.ts","node_modules/@deck.gl/layers/src/scatterplot-layer/scatterplot-layer.ts","node_modules/@deck.gl/layers/src/text-layer/multi-icon-layer/sdf-uniforms.ts","node_modules/@deck.gl/layers/src/text-layer/text-uniforms.ts","node_modules/@deck.gl/layers/src/text-layer/multi-icon-layer/multi-icon-layer-vertex.glsl.ts","node_modules/@deck.gl/layers/src/text-layer/multi-icon-layer/multi-icon-layer-fragment.glsl.ts","node_modules/@deck.gl/layers/src/text-layer/multi-icon-layer/multi-icon-layer.ts","node_modules/@mapbox/tiny-sdf/index.js","node_modules/@deck.gl/layers/src/text-layer/utils.ts","node_modules/@deck.gl/layers/src/text-layer/lru-cache.ts","node_modules/@deck.gl/layers/src/text-layer/font-atlas-manager.ts","node_modules/@deck.gl/layers/src/text-layer/text-background-layer/text-background-layer-uniforms.ts","node_modules/@deck.gl/layers/src/text-layer/text-background-layer/text-background-layer-vertex.glsl.ts","node_modules/@deck.gl/layers/src/text-layer/text-background-layer/text-background-layer-fragment.glsl.ts","node_modules/@deck.gl/layers/src/text-layer/text-background-layer/text-background-layer.ts","node_modules/@deck.gl/layers/src/text-layer/text-layer.ts","node_modules/@flowmap.gl/data/src/types.ts","node_modules/d3-scale-chromatic/src/colors.js","node_modules/d3-color/src/define.js","node_modules/d3-color/src/color.js","node_modules/d3-color/src/math.js","node_modules/d3-color/src/lab.js","node_modules/d3-color/src/cubehelix.js","node_modules/d3-interpolate/src/basis.js","node_modules/d3-interpolate/src/basisClosed.js","node_modules/d3-interpolate/src/constant.js","node_modules/d3-interpolate/src/color.js","node_modules/d3-interpolate/src/rgb.js","node_modules/d3-interpolate/src/numberArray.js","node_modules/d3-interpolate/src/array.js","node_modules/d3-interpolate/src/date.js","node_modules/d3-interpolate/src/number.js","node_modules/d3-interpolate/src/object.js","node_modules/d3-interpolate/src/string.js","node_modules/d3-interpolate/src/value.js","node_modules/d3-interpolate/src/round.js","node_modules/d3-interpolate/src/cubehelix.js","node_modules/d3-scale-chromatic/src/ramp.js","node_modules/d3-scale-chromatic/src/sequential-multi/BuGn.js","node_modules/d3-scale-chromatic/src/sequential-multi/BuPu.js","node_modules/d3-scale-chromatic/src/sequential-multi/GnBu.js","node_modules/d3-scale-chromatic/src/sequential-multi/OrRd.js","node_modules/d3-scale-chromatic/src/sequential-multi/PuBuGn.js","node_modules/d3-scale-chromatic/src/sequential-multi/PuBu.js","node_modules/d3-scale-chromatic/src/sequential-multi/PuRd.js","node_modules/d3-scale-chromatic/src/sequential-multi/RdPu.js","node_modules/d3-scale-chromatic/src/sequential-multi/YlGnBu.js","node_modules/d3-scale-chromatic/src/sequential-multi/YlGn.js","node_modules/d3-scale-chromatic/src/sequential-multi/YlOrBr.js","node_modules/d3-scale-chromatic/src/sequential-multi/YlOrRd.js","node_modules/d3-scale-chromatic/src/sequential-single/Blues.js","node_modules/d3-scale-chromatic/src/sequential-single/Greens.js","node_modules/d3-scale-chromatic/src/sequential-single/Greys.js","node_modules/d3-scale-chromatic/src/sequential-single/Purples.js","node_modules/d3-scale-chromatic/src/sequential-single/Reds.js","node_modules/d3-scale-chromatic/src/sequential-single/Oranges.js","node_modules/d3-scale-chromatic/src/sequential-multi/rainbow.js","node_modules/d3-scale-chromatic/src/sequential-multi/viridis.js","node_modules/d3-array/src/ascending.js","node_modules/d3-array/src/descending.js","node_modules/d3-array/src/bisector.js","node_modules/d3-array/src/number.js","node_modules/d3-array/src/bisect.js","node_modules/d3-array/src/extent.js","node_modules/d3-array/src/fsum.js","node_modules/internmap/src/index.js","node_modules/d3-array/src/identity.js","node_modules/d3-array/src/group.js","node_modules/d3-array/src/ticks.js","node_modules/d3-array/src/min.js","node_modules/d3-array/src/range.js","node_modules/d3-scale/src/init.js","node_modules/d3-scale/src/constant.js","node_modules/d3-scale/src/number.js","node_modules/d3-scale/src/continuous.js","node_modules/d3-format/src/formatDecimal.js","node_modules/d3-format/src/exponent.js","node_modules/d3-format/src/formatGroup.js","node_modules/d3-format/src/formatNumerals.js","node_modules/d3-format/src/formatSpecifier.js","node_modules/d3-format/src/formatTrim.js","node_modules/d3-format/src/formatPrefixAuto.js","node_modules/d3-format/src/formatRounded.js","node_modules/d3-format/src/formatTypes.js","node_modules/d3-format/src/identity.js","node_modules/d3-format/src/locale.js","node_modules/d3-format/src/defaultLocale.js","node_modules/d3-format/src/precisionFixed.js","node_modules/d3-format/src/precisionPrefix.js","node_modules/d3-format/src/precisionRound.js","node_modules/d3-scale/src/tickFormat.js","node_modules/d3-scale/src/linear.js","node_modules/d3-scale/src/pow.js","node_modules/d3-time/src/interval.js","node_modules/d3-time/src/second.js","node_modules/d3-time/src/minute.js","node_modules/d3-time/src/hour.js","node_modules/d3-time/src/day.js","node_modules/d3-time/src/week.js","node_modules/d3-time/src/month.js","node_modules/d3-time/src/year.js","node_modules/d3-time-format/src/locale.js","node_modules/d3-time-format/src/defaultLocale.js","node_modules/d3-scale/src/sequential.js","node_modules/@flowmap.gl/data/src/colors.ts","node_modules/kdbush/index.js","node_modules/reselect/src/devModeChecks/identityFunctionCheck.ts","node_modules/reselect/src/devModeChecks/inputStabilityCheck.ts","node_modules/reselect/src/devModeChecks/setGlobalDevModeChecks.ts","node_modules/reselect/src/utils.ts","node_modules/reselect/src/autotrackMemoize/autotracking.ts","node_modules/reselect/src/autotrackMemoize/tracking.ts","node_modules/reselect/src/autotrackMemoize/proxy.ts","node_modules/reselect/src/lruMemoize.ts","node_modules/reselect/src/autotrackMemoize/autotrackMemoize.ts","node_modules/reselect/src/weakMapMemoize.ts","node_modules/reselect/src/createSelectorCreator.ts","node_modules/reselect/src/createStructuredSelector.ts","node_modules/@flowmap.gl/data/src/FlowmapSelectors.ts","node_modules/@flowmap.gl/data/src/FlowmapAggregateAccessors.ts","node_modules/@flowmap.gl/data/src/cluster/ClusterIndex.ts","node_modules/@flowmap.gl/data/src/cluster/cluster.ts","node_modules/@flowmap.gl/data/src/selector-functions.ts","node_modules/@flowmap.gl/data/src/time.ts","node_modules/d3-geo/src/math.js","node_modules/d3-geo/src/noop.js","node_modules/d3-geo/src/stream.js","node_modules/d3-geo/src/area.js","node_modules/d3-geo/src/cartesian.js","node_modules/d3-geo/src/bounds.js","node_modules/@flowmap.gl/data/src/getViewStateForLocations.ts","node_modules/@flowmap.gl/data/src/provider/FlowmapDataProvider.ts","node_modules/@flowmap.gl/data/src/provider/LocalFlowmapDataProvider.ts","node_modules/@flowmap.gl/layers/src/types.ts","node_modules/@flowmap.gl/layers/src/FlowmapLayer.ts","entry.js"],"sourcesContent":["// Do not name these variables the same as the global objects - will break bundling\nconst global_ = globalThis;\nconst window_ = globalThis as unknown as Window;\nconst document_ = globalThis.document || ({} as Document);\nconst process_ = globalThis.process || {};\nconst console_ = globalThis.console;\nconst navigator_ = globalThis.navigator || ({} as Navigator);\n\nexport {\n global_ as global,\n global_ as self,\n window_ as window,\n document_ as document,\n process_ as process,\n console_ as console,\n navigator_ as navigator\n};\n","// based on https://github.com/cheton/is-electron\n// https://github.com/electron/electron/issues/2288\n/* eslint-disable complexity */\nexport function isElectron(mockUserAgent?: string): boolean {\n // Renderer process\n // @ts-expect-error\n if (typeof window !== 'undefined' && window.process?.type === 'renderer') {\n return true;\n }\n // Main process\n // eslint-disable-next-line\n if (typeof process !== 'undefined' && Boolean(process.versions?.['electron'])) {\n return true;\n }\n // Detect the user agent when the `nodeIntegration` option is set to true\n const realUserAgent = typeof navigator !== 'undefined' && navigator.userAgent;\n const userAgent = mockUserAgent || realUserAgent;\n return Boolean(userAgent && userAgent.indexOf('Electron') >= 0);\n}\n","// This function is needed in initialization stages,\n// make sure it can be imported in isolation\n\nimport {isElectron} from './is-electron';\n\n/** Check if in browser by duck-typing Node context */\nexport function isBrowser(): boolean {\n const isNode =\n // @ts-expect-error\n typeof process === 'object' && String(process) === '[object process]' && !process?.browser;\n return !isNode || isElectron();\n}\n","// Copyright (c) 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n// This function is needed in initialization stages,\n// make sure it can be imported in isolation\n\nimport {isBrowser} from './is-browser';\nimport {isElectron} from './is-electron';\nimport {navigator} from './globals';\n\ndeclare global {\n var chrome: boolean; // eslint-disable-line no-var\n var safari: boolean; // eslint-disable-line no-var\n var mozInnerScreenX: number; // eslint-disable-line no-var\n}\n\nexport function isMobile(): boolean {\n return typeof globalThis.orientation !== 'undefined';\n}\n\n// Simple browser detection\n// `mockUserAgent` parameter allows user agent to be overridden for testing\n/* eslint-disable complexity */\nexport function getBrowser(\n mockUserAgent?: string\n): 'Node' | 'Electron' | 'Chrome' | 'Firefox' | 'Safari' | 'Edge' | 'Unknown' {\n if (!mockUserAgent && !isBrowser()) {\n return 'Node';\n }\n if (isElectron(mockUserAgent)) {\n return 'Electron';\n }\n\n const userAgent = mockUserAgent || navigator.userAgent || '';\n\n // NOTE: Order of tests matter, as many agents list Chrome etc.\n if (userAgent.indexOf('Edge') > -1) {\n return 'Edge';\n }\n if (globalThis.chrome) {\n return 'Chrome';\n }\n if (globalThis.safari) {\n return 'Safari';\n }\n if (globalThis.mozInnerScreenX) {\n return 'Firefox';\n }\n return 'Unknown';\n}\n","// Extract injected version from package.json (injected by babel plugin)\n// @ts-expect-error\nexport const VERSION = typeof __VERSION__ !== 'undefined' ? __VERSION__ : 'untranspiled source';\n\n// ENVIRONMENT\nexport {self, window, global, document, process, console} from './lib/globals';\nexport {isBrowser} from './lib/is-browser';\nexport {getBrowser, isMobile} from './lib/get-browser';\nexport {isElectron} from './lib/is-electron';\n\n// ENVIRONMENT'S ASSERT IS 5-15KB, SO WE PROVIDE OUR OWN\nexport {assert} from './utils/assert';\n\n// TODO - wish we could just export a constant\n// export const isBrowser = checkIfBrowser();\n","export default function assert(condition: unknown, message?: string): asserts condition {\n if (!condition) {\n throw new Error(message || 'Assertion failed');\n }\n}\n","// probe.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport assert from '../utils/assert';\n\n/**\n * Get logLevel from first argument:\n * - log(logLevel, message, args) => logLevel\n * - log(message, args) => 0\n * - log({logLevel, ...}, message, args) => logLevel\n * - log({logLevel, message, args}) => logLevel\n */\nexport function normalizeLogLevel(logLevel: unknown): number {\n if (!logLevel) {\n return 0;\n }\n let resolvedLevel;\n\n switch (typeof logLevel) {\n case 'number':\n resolvedLevel = logLevel;\n break;\n\n case 'object':\n // Backward compatibility\n // TODO - deprecate `priority`\n // @ts-expect-error\n resolvedLevel = logLevel.logLevel || logLevel.priority || 0;\n break;\n\n default:\n return 0;\n }\n // 'log level must be a number'\n assert(Number.isFinite(resolvedLevel) && resolvedLevel >= 0);\n\n return resolvedLevel;\n}\n\n/**\n * \"Normalizes\" the various argument patterns into an object with known types\n * - log(logLevel, message, args) => {logLevel, message, args}\n * - log(message, args) => {logLevel: 0, message, args}\n * - log({logLevel, ...}, message, args) => {logLevel, message, args}\n * - log({logLevel, message, args}) => {logLevel, message, args}\n */\nexport function normalizeArguments(opts: {\n logLevel;\n message;\n collapsed?: boolean;\n args?: IArguments | any[] | undefined;\n opts?;\n}): NormalizedArguments {\n const {logLevel, message} = opts;\n opts.logLevel = normalizeLogLevel(logLevel);\n\n // We use `arguments` instead of rest parameters (...args) because IE\n // does not support the syntax. Rest parameters is transpiled to code with\n // perf impact. Doing it here instead avoids constructing args when logging is\n // disabled.\n // TODO - remove when/if IE support is dropped\n const args: any[] = opts.args ? Array.from(opts.args) : [];\n // args should only contain arguments that appear after `message`\n // eslint-disable-next-line no-empty\n while (args.length && args.shift() !== message) {}\n\n switch (typeof logLevel) {\n case 'string':\n case 'function':\n if (message !== undefined) {\n args.unshift(message);\n }\n opts.message = logLevel;\n break;\n\n case 'object':\n Object.assign(opts, logLevel);\n break;\n\n default:\n }\n\n // Resolve functions into strings by calling them\n if (typeof opts.message === 'function') {\n opts.message = opts.message();\n }\n const messageType = typeof opts.message;\n // 'log message must be a string' or object\n assert(messageType === 'string' || messageType === 'object');\n\n // original opts + normalized opts + opts arg + fixed up message\n return Object.assign(opts, {args}, opts.opts);\n}\nexport type NormalizedArguments = {\n logLevel: number;\n message: any;\n args: any[];\n tag?: unknown;\n method?: Function;\n once?: boolean;\n total?: number;\n delta?: number;\n [key: string]: any;\n};\n","// probe.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Logger, LogFunction} from './logger';\nimport {NormalizedArguments, normalizeArguments, normalizeLogLevel} from './log-utils';\n\nconst noop = () => {};\n\nexport type NormalizedLogArguments = NormalizedArguments;\ntype LogType = 'log' | 'info' | 'once' | 'warn' | 'error' | 'table' | 'group' | 'groupEnd' | 'time';\n\ntype LogOptions = Partial;\n\n/**\n * Base logger that implements log level handling and once de-duplication.\n * Concrete loggers implement `_emit` to perform actual output.\n */\nexport abstract class BaseLog implements Logger {\n userData: Record = {};\n\n protected _level: number;\n protected _onceCache = new Set();\n\n constructor({level = 0}: {level?: number} = {}) {\n this._level = level;\n }\n\n set level(newLevel: number) {\n this.setLevel(newLevel);\n }\n\n get level(): number {\n return this.getLevel();\n }\n\n setLevel(level: number): this {\n this._level = level;\n return this;\n }\n\n getLevel(): number {\n return this._level;\n }\n\n // Unconditional logging\n\n warn(message: string, ...args: unknown[]): LogFunction {\n return this._log('warn', 0, message, args, {once: true});\n }\n\n error(message: string, ...args: unknown[]): LogFunction {\n return this._log('error', 0, message, args);\n }\n\n // Conditional logging\n\n log(logLevel, message?, ...args: unknown[]): LogFunction {\n return this._log('log', logLevel, message, args);\n }\n\n info(logLevel, message?, ...args: unknown[]): LogFunction {\n return this._log('info', logLevel, message, args);\n }\n\n once(logLevel, message?, ...args: unknown[]): LogFunction {\n return this._log('once', logLevel, message, args, {once: true});\n }\n\n protected _log(\n type: LogType,\n logLevel: unknown,\n message: unknown,\n args: unknown[],\n options: LogOptions = {}\n ): LogFunction {\n const normalized = normalizeArguments({\n logLevel,\n message,\n args: this._buildArgs(logLevel, message, args),\n opts: options\n });\n\n return this._createLogFunction(type, normalized, options);\n }\n\n protected _buildArgs(logLevel: unknown, message: unknown, args: unknown[]): unknown[] {\n return [logLevel, message, ...args];\n }\n\n protected _createLogFunction(\n type: LogType,\n normalized: NormalizedLogArguments,\n options: LogOptions\n ): LogFunction {\n if (!this._shouldLog(normalized.logLevel)) {\n return noop;\n }\n\n const tag = this._getOnceTag(options.tag ?? normalized.tag ?? normalized.message);\n if ((options.once || normalized.once) && tag !== undefined) {\n if (this._onceCache.has(tag)) {\n return noop;\n }\n this._onceCache.add(tag);\n }\n\n return this._emit(type, normalized);\n }\n\n protected _shouldLog(logLevel: unknown): boolean {\n return this.getLevel() >= normalizeLogLevel(logLevel);\n }\n\n protected _getOnceTag(tag: unknown): unknown {\n if (tag === undefined) {\n return undefined;\n }\n try {\n return typeof tag === 'string' ? tag : String(tag);\n } catch {\n return undefined;\n }\n }\n\n /** Create the actual log function for this logger implementation. */\n protected abstract _emit(type: LogType, normalized: NormalizedLogArguments): LogFunction;\n}\n\nexport {noop};\n","// probe.gl, MIT license\n\nexport type StorageType = 'sessionStorage' | 'localStorage';\n\nfunction getStorage(type: StorageType): Storage | null {\n try {\n const storage: Storage = window[type];\n const x = '__storage_test__';\n storage.setItem(x, x);\n storage.removeItem(x);\n return storage;\n } catch (e) {\n return null;\n }\n}\n\n// Store keys in local storage via simple interface\nexport class LocalStorage {\n storage: Storage | null;\n id: string;\n config: Required;\n\n constructor(\n id: string,\n defaultConfig: Required,\n type: StorageType = 'sessionStorage'\n ) {\n this.storage = getStorage(type);\n this.id = id;\n this.config = defaultConfig;\n this._loadConfiguration();\n }\n\n getConfiguration(): Required {\n return this.config;\n }\n\n setConfiguration(configuration: Configuration): void {\n Object.assign(this.config, configuration);\n if (this.storage) {\n const serialized = JSON.stringify(this.config);\n this.storage.setItem(this.id, serialized);\n }\n }\n\n // Get config from persistent store, if available\n _loadConfiguration() {\n let configuration = {};\n if (this.storage) {\n const serializedConfiguration = this.storage.getItem(this.id);\n configuration = serializedConfiguration ? JSON.parse(serializedConfiguration) : {};\n }\n Object.assign(this.config, configuration);\n return this;\n }\n}\n","// probe.gl, MIT license\n\nexport type FormatValueOptions = {\n isInteger?: boolean;\n maxElts?: number;\n size?: number;\n};\n\n/**\n * Format time\n */\nexport function formatTime(ms: number): string {\n let formatted;\n if (ms < 10) {\n formatted = `${ms.toFixed(2)}ms`;\n } else if (ms < 100) {\n formatted = `${ms.toFixed(1)}ms`;\n } else if (ms < 1000) {\n formatted = `${ms.toFixed(0)}ms`;\n } else {\n formatted = `${(ms / 1000).toFixed(2)}s`;\n }\n return formatted;\n}\n\nexport function leftPad(string: string, length: number = 8): string {\n const padLength = Math.max(length - string.length, 0);\n return `${' '.repeat(padLength)}${string}`;\n}\n\nexport function rightPad(string: string, length: number = 8): string {\n const padLength = Math.max(length - string.length, 0);\n return `${string}${' '.repeat(padLength)}`;\n}\n\nexport function formatValue(v: unknown, options: FormatValueOptions = {}): string {\n const EPSILON = 1e-16;\n const {isInteger = false} = options;\n if (Array.isArray(v) || ArrayBuffer.isView(v)) {\n return formatArrayValue(v, options);\n }\n if (!Number.isFinite(v)) {\n return String(v);\n }\n // @ts-expect-error\n if (Math.abs(v) < EPSILON) {\n return isInteger ? '0' : '0.';\n }\n if (isInteger) {\n // @ts-expect-error\n return v.toFixed(0);\n }\n // @ts-expect-error\n if (Math.abs(v) > 100 && Math.abs(v) < 10000) {\n // @ts-expect-error\n return v.toFixed(0);\n }\n // @ts-expect-error\n const string = v.toPrecision(2);\n const decimal = string.indexOf('.0');\n return decimal === string.length - 2 ? string.slice(0, -1) : string;\n}\n\n/** Helper to formatValue */\nfunction formatArrayValue(v: any, options: FormatValueOptions) {\n const {maxElts = 16, size = 1} = options;\n let string = '[';\n for (let i = 0; i < v.length && i < maxElts; ++i) {\n if (i > 0) {\n string += `,${i % size === 0 ? ' ' : ''}`;\n }\n string += formatValue(v[i], options);\n }\n const terminator = v.length > maxElts ? '...' : ']';\n return `${string}${terminator}`;\n}\n","import {isBrowser} from '@probe.gl/env';\n\nexport enum COLOR {\n BLACK = 30,\n RED = 31,\n GREEN = 32,\n YELLOW = 33,\n BLUE = 34,\n MAGENTA = 35,\n CYAN = 36,\n WHITE = 37,\n\n BRIGHT_BLACK = 90,\n BRIGHT_RED = 91,\n BRIGHT_GREEN = 92,\n BRIGHT_YELLOW = 93,\n BRIGHT_BLUE = 94,\n BRIGHT_MAGENTA = 95,\n BRIGHT_CYAN = 96,\n BRIGHT_WHITE = 97\n}\n\nconst BACKGROUND_INCREMENT = 10;\n\nfunction getColor(color: string | COLOR): number {\n if (typeof color !== 'string') {\n return color;\n }\n color = color.toUpperCase();\n return COLOR[color] || COLOR.WHITE;\n}\n\nexport function addColor(\n string: string,\n color: string | COLOR,\n background?: string | COLOR\n): string {\n if (!isBrowser && typeof string === 'string') {\n if (color) {\n const colorCode = getColor(color);\n string = `\\u001b[${colorCode}m${string}\\u001b[39m`;\n }\n if (background) {\n // background colors values are +10\n const colorCode = getColor(background);\n string = `\\u001b[${colorCode + BACKGROUND_INCREMENT}m${string}\\u001b[49m`;\n }\n }\n return string;\n}\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n/**\n * Binds the \"this\" argument of all functions on a class instance to the instance\n * @param obj - class instance (typically a react component)\n */\nexport function autobind(obj: object, predefined = ['constructor']): void {\n const proto = Object.getPrototypeOf(obj);\n const propNames = Object.getOwnPropertyNames(proto);\n\n const object = obj as Record;\n for (const key of propNames) {\n const value = object[key];\n if (typeof value === 'function') {\n if (!predefined.find((name) => key === name)) {\n object[key] = value.bind(obj);\n }\n }\n }\n}\n","// probe.gl, MIT license\n\nimport {window, process, isBrowser} from '@probe.gl/env';\n\n/** Get best timer available. */\nexport function getHiResTimestamp() {\n let timestamp;\n if (isBrowser() && window.performance) {\n timestamp = window?.performance?.now?.();\n } else if ('hrtime' in process) {\n // @ts-ignore\n const timeParts = process?.hrtime?.();\n timestamp = timeParts[0] * 1000 + timeParts[1] / 1e6;\n } else {\n timestamp = Date.now();\n }\n\n return timestamp;\n}\n","// probe.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/* eslint-disable no-console,prefer-rest-params */\nimport {VERSION, isBrowser} from '@probe.gl/env';\nimport {LogFunction} from './logger';\nimport {BaseLog, NormalizedLogArguments, noop} from './base-log';\nimport {LocalStorage} from '../utils/local-storage';\nimport {formatTime, leftPad} from '../utils/formatters';\nimport {addColor} from '../utils/color';\nimport {autobind} from '../utils/autobind';\nimport assert from '../utils/assert';\nimport {getHiResTimestamp} from '../utils/hi-res-timestamp';\n\n/** \"Global\" log configuration settings */\ntype ProbeLogConfiguration = {\n enabled?: boolean;\n level?: number;\n [key: string]: unknown;\n};\n\ntype Table = Record;\n\n// Instrumentation in other packages may override console methods, so preserve them here\nconst originalConsole = {\n debug: isBrowser() ? console.debug || console.log : console.log,\n log: console.log,\n info: console.info,\n warn: console.warn,\n error: console.error\n};\n\nconst DEFAULT_LOG_CONFIGURATION: Required = {\n enabled: true,\n level: 0\n};\n\n/** A console wrapper */\n\nexport class ProbeLog extends BaseLog {\n static VERSION = VERSION;\n\n id: string;\n VERSION: string = VERSION;\n _startTs: number = getHiResTimestamp();\n _deltaTs: number = getHiResTimestamp();\n _storage: LocalStorage>;\n override userData = {};\n\n // TODO - fix support from throttling groups\n LOG_THROTTLE_TIMEOUT: number = 0; // Time before throttled messages are logged again\n\n constructor({id} = {id: ''}) {\n super({level: 0});\n this.id = id;\n this.userData = {};\n this._storage = new LocalStorage>(\n `__probe-${this.id}__`,\n {[this.id]: DEFAULT_LOG_CONFIGURATION}\n );\n\n this.timeStamp(`${this.id} started`);\n\n autobind(this);\n Object.seal(this);\n }\n\n isEnabled(): boolean {\n return this._getConfiguration().enabled;\n }\n\n override getLevel(): number {\n return this._getConfiguration().level;\n }\n\n /** @return milliseconds, with fractions */\n getTotal(): number {\n return Number((getHiResTimestamp() - this._startTs).toPrecision(10));\n }\n\n /** @return milliseconds, with fractions */\n getDelta(): number {\n return Number((getHiResTimestamp() - this._deltaTs).toPrecision(10));\n }\n\n /** @deprecated use logLevel */\n set priority(newPriority: number) {\n this.level = newPriority;\n }\n\n /** @deprecated use logLevel */\n get priority(): number {\n return this.level;\n }\n\n /** @deprecated use logLevel */\n getPriority(): number {\n return this.level;\n }\n\n // Configure\n\n enable(enabled: boolean = true): this {\n this._updateConfiguration({enabled});\n return this;\n }\n\n override setLevel(level: number): this {\n this._updateConfiguration({level});\n return this;\n }\n\n /** return the current status of the setting */\n get(setting: string): any {\n return this._getConfiguration()[setting];\n }\n\n // update the status of the setting\n set(setting: string, value: any): void {\n this._updateConfiguration({[setting]: value});\n }\n\n /** Logs the current settings as a table */\n settings(): void {\n if (console.table) {\n console.table(this._storage.config);\n } else {\n console.log(this._storage.config);\n }\n }\n\n // Unconditional logging\n\n assert(condition: unknown, message?: string): asserts condition {\n if (!condition) {\n throw new Error(message || 'Assertion failed');\n }\n }\n\n /** Warn, but only once, no console flooding */\n override warn(message: string, ...args: unknown[]): LogFunction;\n override warn(message: string, ...args: unknown[]): LogFunction {\n return this._log('warn', 0, message, args, {\n method: originalConsole.warn,\n once: true\n });\n }\n\n /** Print an error */\n override error(message: string, ...args: unknown[]): LogFunction;\n override error(message: string, ...args: unknown[]): LogFunction {\n return this._log('error', 0, message, args, {\n method: originalConsole.error\n });\n }\n\n /** Print a deprecation warning */\n deprecated(oldUsage: string, newUsage: string): LogFunction {\n return this.warn(`\\`${oldUsage}\\` is deprecated and will be removed \\\nin a later version. Use \\`${newUsage}\\` instead`);\n }\n\n /** Print a removal warning */\n removed(oldUsage: string, newUsage: string): LogFunction {\n return this.error(`\\`${oldUsage}\\` has been removed. Use \\`${newUsage}\\` instead`);\n }\n\n // Conditional logging\n\n /** Log to a group */\n probe(logLevel, message?, ...args: unknown[]): LogFunction;\n probe(logLevel, message?, ...args: unknown[]): LogFunction {\n return this._log('log', logLevel, message, args, {\n method: originalConsole.log,\n time: true,\n once: true\n });\n }\n\n /** Log a debug message */\n override log(logLevel, message?, ...args: unknown[]): LogFunction;\n override log(logLevel, message?, ...args: unknown[]): LogFunction {\n return this._log('log', logLevel, message, args, {\n method: originalConsole.debug\n });\n }\n\n /** Log a normal message */\n override info(logLevel, message?, ...args: unknown[]): LogFunction;\n override info(logLevel, message?, ...args: unknown[]): LogFunction {\n return this._log('info', logLevel, message, args, {method: console.info});\n }\n\n /** Log a normal message, but only once, no console flooding */\n override once(logLevel, message?, ...args: unknown[]): LogFunction;\n override once(logLevel, message?, ...args: unknown[]): LogFunction {\n return this._log('once', logLevel, message, args, {\n method: originalConsole.debug || originalConsole.info,\n once: true\n });\n }\n\n /** Logs an object as a table */\n table(logLevel, table?, columns?): LogFunction {\n if (table) {\n return this._log('table', logLevel, table, (columns && [columns]) || [], {\n method: console.table || noop,\n tag: getTableHeader(table)\n });\n }\n return noop;\n }\n\n time(logLevel, message) {\n return this._log('time', logLevel, message, [], {\n method: console.time ? console.time : console.info\n });\n }\n\n timeEnd(logLevel, message) {\n return this._log('time', logLevel, message, [], {\n method: console.timeEnd ? console.timeEnd : console.info\n });\n }\n\n timeStamp(logLevel, message?) {\n return this._log('time', logLevel, message, [], {\n method: console.timeStamp || noop\n });\n }\n\n group(logLevel, message, opts = {collapsed: false}) {\n const method = (opts.collapsed ? console.groupCollapsed : console.group) || console.info;\n return this._log('group', logLevel, message, [], {method});\n }\n\n groupCollapsed(logLevel, message, opts = {}) {\n return this.group(logLevel, message, Object.assign({}, opts, {collapsed: true}));\n }\n\n groupEnd(logLevel) {\n return this._log('groupEnd', logLevel, '', [], {\n method: console.groupEnd || noop\n });\n }\n\n // EXPERIMENTAL\n\n withGroup(logLevel: number, message: string, func: Function): void {\n this.group(logLevel, message)();\n\n try {\n func();\n } finally {\n this.groupEnd(logLevel)();\n }\n }\n\n trace(): void {\n if (console.trace) {\n console.trace();\n }\n }\n\n protected override _shouldLog(logLevel: unknown): boolean {\n return this.isEnabled() && super._shouldLog(logLevel);\n }\n\n protected override _emit(_type: string, normalized: NormalizedLogArguments): LogFunction {\n const method = normalized.method;\n assert(method);\n\n normalized.total = this.getTotal();\n normalized.delta = this.getDelta();\n // reset delta timer\n this._deltaTs = getHiResTimestamp();\n\n const message = decorateMessage(this.id, normalized.message, normalized);\n\n // Bind console function so that it can be called after being returned\n return method.bind(console, message, ...normalized.args);\n }\n\n _getConfiguration(): Required {\n if (!this._storage.config[this.id]) {\n this._updateConfiguration(DEFAULT_LOG_CONFIGURATION);\n }\n\n // @ts-expect-error guaranteed to be defined\n return this._storage.config[this.id];\n }\n\n _updateConfiguration(configuration: ProbeLogConfiguration): void {\n const currentConfiguration = this._storage.config[this.id] || {\n ...DEFAULT_LOG_CONFIGURATION\n };\n this._storage.setConfiguration({\n [this.id]: {...currentConfiguration, ...configuration}\n });\n }\n}\n\nfunction decorateMessage(id, message, opts) {\n if (typeof message === 'string') {\n const time = opts.time ? leftPad(formatTime(opts.total)) : '';\n message = opts.time ? `${id}: ${time} ${message}` : `${id}: ${message}`;\n message = addColor(message, opts.color, opts.background);\n }\n return message;\n}\n\nfunction getTableHeader(table: Table): string {\n for (const key in table) {\n for (const title in table[key]) {\n return title || 'untitled';\n }\n }\n return 'empty';\n}\n\nexport {normalizeArguments} from './log-utils';\nexport {normalizeLogLevel} from './log-utils';\n","// @ts-nocheck\n/* eslint-disable */\nglobalThis.probe = {};\n","import {ProbeLog} from './loggers/probe-log';\n\n// DEFAULT EXPORT IS A LOG INSTANCE\nexport default new ProbeLog({id: '@probe.gl/log'});\n\n// LOGGING\nexport type {Logger} from './loggers/logger';\nexport {ProbeLog, ProbeLog as Log} from './loggers/probe-log';\nexport {ConsoleLog} from './loggers/console-log';\nexport {BaseLog} from './loggers/base-log';\nexport type {MemoryLogMessage} from './loggers/memory-log';\nexport {MemoryLog} from './loggers/memory-log';\n\n// UTILITIES\nexport {COLOR} from './utils/color';\nexport {addColor} from './utils/color';\nexport {leftPad, rightPad} from './utils/formatters';\nexport {autobind} from './utils/autobind';\nexport {LocalStorage} from './utils/local-storage';\nexport {getHiResTimestamp} from './utils/hi-res-timestamp';\n\nimport './init';\n","// Copyright (c) 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nexport default function getHiResTimestamp(): number {\n let timestamp;\n // Get best timer available.\n if (typeof window !== 'undefined' && window.performance) {\n timestamp = window.performance.now();\n } else if (typeof process !== 'undefined' && process.hrtime) {\n const timeParts = process.hrtime();\n timestamp = timeParts[0] * 1000 + timeParts[1] / 1e6;\n } else {\n timestamp = Date.now();\n }\n\n return timestamp;\n}\n","import getHiResTimestamp from '../utils/hi-res-timestamp';\n\nexport default class Stat {\n readonly name: string;\n readonly type: string | undefined;\n sampleSize: number = 1;\n time: number = 0;\n count: number = 0;\n samples: number = 0;\n lastTiming: number = 0;\n lastSampleTime: number = 0;\n lastSampleCount: number = 0;\n\n _count: number = 0;\n _time: number = 0;\n _samples: number = 0;\n _startTime: number = 0;\n _timerPending: boolean = false;\n\n constructor(name: string, type?: string) {\n this.name = name;\n this.type = type;\n this.reset();\n }\n\n reset(): this {\n this.time = 0;\n this.count = 0;\n this.samples = 0;\n this.lastTiming = 0;\n this.lastSampleTime = 0;\n this.lastSampleCount = 0;\n this._count = 0;\n this._time = 0;\n this._samples = 0;\n this._startTime = 0;\n this._timerPending = false;\n\n return this;\n }\n\n setSampleSize(samples: number): this {\n this.sampleSize = samples;\n return this;\n }\n\n /** Call to increment count (+1) */\n incrementCount(): this {\n this.addCount(1);\n\n return this;\n }\n\n /** Call to decrement count (-1) */\n decrementCount(): this {\n this.subtractCount(1);\n\n return this;\n }\n\n /** Increase count */\n addCount(value: number): this {\n this._count += value;\n this._samples++;\n this._checkSampling();\n\n return this;\n }\n\n /** Decrease count */\n subtractCount(value: number): this {\n this._count -= value;\n this._samples++;\n this._checkSampling();\n\n return this;\n }\n\n /** Add an arbitrary timing and bump the count */\n addTime(time: number): this {\n this._time += time;\n this.lastTiming = time;\n this._samples++;\n this._checkSampling();\n\n return this;\n }\n\n /** Start a timer */\n timeStart(): this {\n this._startTime = getHiResTimestamp();\n this._timerPending = true;\n\n return this;\n }\n\n /** End a timer. Adds to time and bumps the timing count. */\n timeEnd(): this {\n if (!this._timerPending) {\n return this;\n }\n this.addTime(getHiResTimestamp() - this._startTime);\n this._timerPending = false;\n this._checkSampling();\n\n return this;\n }\n\n getSampleAverageCount(): number {\n return this.sampleSize > 0 ? this.lastSampleCount / this.sampleSize : 0;\n }\n\n /** Calculate average time / count for the previous window */\n getSampleAverageTime(): number {\n return this.sampleSize > 0 ? this.lastSampleTime / this.sampleSize : 0;\n }\n\n /** Calculate counts per second for the previous window */\n getSampleHz(): number {\n return this.lastSampleTime > 0 ? this.sampleSize / (this.lastSampleTime / 1000) : 0;\n }\n\n getAverageCount(): number {\n return this.samples > 0 ? this.count / this.samples : 0;\n }\n\n /** Calculate average time / count */\n getAverageTime(): number {\n return this.samples > 0 ? this.time / this.samples : 0;\n }\n\n /** Calculate counts per second */\n getHz(): number {\n return this.time > 0 ? this.samples / (this.time / 1000) : 0;\n }\n\n _checkSampling(): void {\n if (this._samples === this.sampleSize) {\n this.lastSampleTime = this._time;\n this.lastSampleCount = this._count;\n this.count += this._count;\n this.time += this._time;\n this.samples += this._samples;\n this._time = 0;\n this._count = 0;\n this._samples = 0;\n }\n }\n}\n","// probe.gl, MIT license\n\nimport Stat from './stat';\n\ntype TableEntry = {\n time: number;\n count: number;\n average: number;\n hz: number;\n};\n\n/** A \"bag\" of `Stat` objects, can be visualized using `StatsWidget` */\nexport default class Stats {\n readonly id: string;\n readonly stats: Record = {};\n\n constructor(options: {id: string; stats?: Stats | Stat[] | {name: string; type?: string}[]}) {\n this.id = options.id;\n this.stats = {};\n\n this._initializeStats(options.stats);\n\n Object.seal(this);\n }\n\n /** Acquire a stat. Create if it doesn't exist. */\n get(name: string, type: string = 'count'): Stat {\n return this._getOrCreate({name, type});\n }\n\n get size(): number {\n return Object.keys(this.stats).length;\n }\n\n /** Reset all stats */\n reset(): this {\n for (const stat of Object.values(this.stats)) {\n stat.reset();\n }\n\n return this;\n }\n\n forEach(fn: (stat: Stat) => void): void {\n for (const stat of Object.values(this.stats)) {\n fn(stat);\n }\n }\n\n getTable(): Record {\n const table: Record = {};\n this.forEach(stat => {\n table[stat.name] = {\n time: stat.time || 0,\n count: stat.count || 0,\n average: stat.getAverageTime() || 0,\n hz: stat.getHz() || 0\n };\n });\n\n return table;\n }\n\n _initializeStats(stats: Stats | Stat[] | {name: string; type?: string}[] = []): void {\n stats.forEach(stat => this._getOrCreate(stat));\n }\n\n _getOrCreate(stat: Stat | {name: string, type?: string}): Stat {\n const {name, type} = stat;\n let result = this.stats[name];\n if (!result) {\n if (stat instanceof Stat) {\n result = stat;\n } else {\n result = new Stat(name, type);\n }\n this.stats[name] = result;\n }\n return result;\n }\n}\n","export {default as Stats} from './lib/stats';\nexport {default as Stat} from './lib/stat';\n\n// UTILITIES\nexport {default as _getHiResTimestamp} from './utils/hi-res-timestamp';\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Stat, Stats} from '@probe.gl/stats';\n\nconst GPU_TIME_AND_MEMORY_STATS = 'GPU Time and Memory';\nconst GPU_TIME_AND_MEMORY_STAT_ORDER = [\n 'Adapter',\n 'GPU',\n 'GPU Type',\n 'GPU Backend',\n 'Frame Rate',\n 'CPU Time',\n 'GPU Time',\n 'GPU Memory',\n 'Buffer Memory',\n 'Texture Memory',\n 'Referenced Buffer Memory',\n 'Referenced Texture Memory',\n 'Swap Chain Texture'\n] as const;\nconst ORDERED_STATS_CACHE = new WeakMap<\n Stats,\n {orderedStatNames: readonly string[]; statCount: number}\n>();\nconst ORDERED_STAT_NAME_SET_CACHE = new WeakMap>();\n\n/**\n * Helper class managing a collection of probe.gl stats objects\n */\nexport class StatsManager {\n stats = new Map();\n\n getStats(name: string): Stats {\n return this.get(name);\n }\n\n get(name: string): Stats {\n if (!this.stats.has(name)) {\n this.stats.set(name, new Stats({id: name}));\n }\n\n const stats = this.stats.get(name);\n if (name === GPU_TIME_AND_MEMORY_STATS) {\n initializeStats(stats, GPU_TIME_AND_MEMORY_STAT_ORDER);\n }\n\n return stats;\n }\n}\n\n/** Global stats for all luma.gl devices */\nexport const lumaStats: StatsManager = new StatsManager();\n\nfunction initializeStats(stats: Stats, orderedStatNames: readonly string[]): void {\n const statsMap = stats.stats;\n let addedOrderedStat = false;\n for (const statName of orderedStatNames) {\n if (!statsMap[statName]) {\n stats.get(statName);\n addedOrderedStat = true;\n }\n }\n\n const statCount = Object.keys(statsMap).length;\n const cachedStats = ORDERED_STATS_CACHE.get(stats);\n if (\n !addedOrderedStat &&\n cachedStats?.orderedStatNames === orderedStatNames &&\n cachedStats.statCount === statCount\n ) {\n return;\n }\n\n const reorderedStats: Record = {};\n let orderedStatNamesSet = ORDERED_STAT_NAME_SET_CACHE.get(orderedStatNames);\n if (!orderedStatNamesSet) {\n orderedStatNamesSet = new Set(orderedStatNames);\n ORDERED_STAT_NAME_SET_CACHE.set(orderedStatNames, orderedStatNamesSet);\n }\n\n for (const statName of orderedStatNames) {\n if (statsMap[statName]) {\n reorderedStats[statName] = statsMap[statName];\n }\n }\n\n for (const [statName, stat] of Object.entries(statsMap)) {\n if (!orderedStatNamesSet.has(statName)) {\n reorderedStats[statName] = stat;\n }\n }\n\n for (const statName of Object.keys(statsMap)) {\n delete statsMap[statName];\n }\n\n Object.assign(statsMap, reorderedStats);\n ORDERED_STATS_CACHE.set(stats, {orderedStatNames, statCount});\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Log} from '@probe.gl/log';\n\n/** Global log instance */\nexport const log: Log = new Log({id: 'luma.gl'});\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nconst uidCounters: Record = {};\n\n/**\n * Returns a UID.\n * @param id= - Identifier base name\n * @return uid\n **/\nexport function uid(id: string = 'id'): string {\n uidCounters[id] = uidCounters[id] || 1;\n const count = uidCounters[id]++;\n return `${id}-${count}`;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport type {Stat, Stats} from '@probe.gl/stats';\nimport {uid} from '../../utils/uid';\n\nconst CPU_HOTSPOT_PROFILER_MODULE = 'cpu-hotspot-profiler';\nconst RESOURCE_COUNTS_STATS = 'GPU Resource Counts';\nconst LEGACY_RESOURCE_COUNTS_STATS = 'Resource Counts';\nconst GPU_TIME_AND_MEMORY_STATS = 'GPU Time and Memory';\nconst BASE_RESOURCE_COUNT_ORDER = [\n 'Resources',\n 'Buffers',\n 'Textures',\n 'Samplers',\n 'TextureViews',\n 'Framebuffers',\n 'QuerySets',\n 'Shaders',\n 'RenderPipelines',\n 'ComputePipelines',\n 'PipelineLayouts',\n 'VertexArrays',\n 'RenderPasss',\n 'ComputePasss',\n 'CommandEncoders',\n 'CommandBuffers'\n] as const;\nconst WEBGL_RESOURCE_COUNT_ORDER = [\n 'Resources',\n 'Buffers',\n 'Textures',\n 'Samplers',\n 'TextureViews',\n 'Framebuffers',\n 'QuerySets',\n 'Shaders',\n 'RenderPipelines',\n 'SharedRenderPipelines',\n 'ComputePipelines',\n 'PipelineLayouts',\n 'VertexArrays',\n 'RenderPasss',\n 'ComputePasss',\n 'CommandEncoders',\n 'CommandBuffers'\n] as const;\nconst BASE_RESOURCE_COUNT_STAT_ORDER = BASE_RESOURCE_COUNT_ORDER.flatMap(resourceType => [\n `${resourceType} Created`,\n `${resourceType} Active`\n]);\nconst WEBGL_RESOURCE_COUNT_STAT_ORDER = WEBGL_RESOURCE_COUNT_ORDER.flatMap(resourceType => [\n `${resourceType} Created`,\n `${resourceType} Active`\n]);\nconst ORDERED_STATS_CACHE = new WeakMap<\n Stats,\n {orderedStatNames: readonly string[]; statCount: number}\n>();\nconst ORDERED_STAT_NAME_SET_CACHE = new WeakMap>();\n\ntype CpuHotspotProfiler = {\n enabled?: boolean;\n activeDefaultFramebufferAcquireDepth?: number;\n statsBookkeepingTimeMs?: number;\n statsBookkeepingCalls?: number;\n transientCanvasResourceCreates?: number;\n transientCanvasTextureCreates?: number;\n transientCanvasTextureViewCreates?: number;\n transientCanvasSamplerCreates?: number;\n transientCanvasFramebufferCreates?: number;\n};\n\nexport type ResourceProps = {\n /** Name of resource, mainly for debugging purposes. A unique name will be assigned if not provided */\n id?: string;\n /** Handle for the underlying resources (WebGL object or WebGPU handle) */\n handle?: any;\n /** User provided data stored on this resource */\n userData?: {[key: string]: any};\n};\n\n/**\n * Base class for GPU (WebGPU/WebGL) Resources\n */\nexport abstract class Resource {\n /** Default properties for resource */\n static defaultProps: Required = {\n id: 'undefined',\n handle: undefined,\n userData: undefined!\n };\n\n abstract get [Symbol.toStringTag](): string;\n\n toString(): string {\n return `${this[Symbol.toStringTag] || this.constructor.name}:\"${this.id}\"`;\n }\n\n /** props.id, for debugging. */\n id: string;\n /** The props that this resource was created with */\n readonly props: Required;\n /** User data object, reserved for the application */\n readonly userData: Record = {};\n /** The device that this resource is associated with */\n abstract readonly device: Device;\n /** The handle for the underlying resource, e.g. WebGL object or WebGPU handle */\n abstract readonly handle: unknown;\n /** The device that this resource is associated with - TODO can we remove this dup? */\n private _device: Device;\n\n /** Whether this resource has been destroyed */\n destroyed: boolean = false;\n /** For resources that allocate GPU memory */\n private allocatedBytes: number = 0;\n /** Stats bucket currently holding the tracked allocation */\n private allocatedBytesName: string | null = null;\n /** Attached resources will be destroyed when this resource is destroyed. Tracks auto-created \"sub\" resources. */\n private _attachedResources = new Set>();\n\n /**\n * Create a new Resource. Called from Subclass\n */\n constructor(device: Device, props: Props, defaultProps: Required) {\n if (!device) {\n throw new Error('no device');\n }\n this._device = device;\n this.props = selectivelyMerge(props, defaultProps);\n\n const id =\n this.props.id !== 'undefined' ? (this.props.id as string) : uid(this[Symbol.toStringTag]);\n this.props.id = id;\n this.id = id;\n this.userData = this.props.userData || {};\n\n this.addStats();\n }\n\n /**\n * destroy can be called on any resource to release it before it is garbage collected.\n */\n destroy(): void {\n if (this.destroyed) {\n return;\n }\n this.destroyResource();\n }\n\n /** @deprecated Use destroy() */\n delete(): this {\n this.destroy();\n return this;\n }\n\n /**\n * Combines a map of user props and default props, only including props from defaultProps\n * @returns returns a map of overridden default props\n */\n getProps(): object {\n return this.props;\n }\n\n // ATTACHED RESOURCES\n\n /**\n * Attaches a resource. Attached resources are auto destroyed when this resource is destroyed\n * Called automatically when sub resources are auto created but can be called by application\n */\n attachResource(resource: Resource): void {\n this._attachedResources.add(resource);\n }\n\n /**\n * Detach an attached resource. The resource will no longer be auto-destroyed when this resource is destroyed.\n */\n detachResource(resource: Resource): void {\n this._attachedResources.delete(resource);\n }\n\n /**\n * Destroys a resource (only if owned), and removes from the owned (auto-destroy) list for this resource.\n */\n destroyAttachedResource(resource: Resource): void {\n if (this._attachedResources.delete(resource)) {\n resource.destroy();\n }\n }\n\n /** Destroy all owned resources. Make sure the resources are no longer needed before calling. */\n destroyAttachedResources(): void {\n for (const resource of this._attachedResources) {\n resource.destroy();\n }\n // don't remove while we are iterating\n this._attachedResources = new Set>();\n }\n\n // PROTECTED METHODS\n\n /** Perform all destroy steps. Can be called by derived resources when overriding destroy() */\n protected destroyResource(): void {\n if (this.destroyed) {\n return;\n }\n this.destroyAttachedResources();\n this.removeStats();\n this.destroyed = true;\n }\n\n /** Called by .destroy() to track object destruction. Subclass must call if overriding destroy() */\n protected removeStats(): void {\n const profiler = getCpuHotspotProfiler(this._device);\n const startTime = profiler ? getTimestamp() : 0;\n const statsObjects = [\n this._device.statsManager.getStats(RESOURCE_COUNTS_STATS),\n this._device.statsManager.getStats(LEGACY_RESOURCE_COUNTS_STATS)\n ];\n const orderedStatNames = getResourceCountStatOrder(this._device);\n for (const stats of statsObjects) {\n initializeStats(stats, orderedStatNames);\n }\n const name = this.getStatsName();\n for (const stats of statsObjects) {\n stats.get('Resources Active').decrementCount();\n stats.get(`${name}s Active`).decrementCount();\n }\n if (profiler) {\n profiler.statsBookkeepingCalls = (profiler.statsBookkeepingCalls || 0) + 1;\n profiler.statsBookkeepingTimeMs =\n (profiler.statsBookkeepingTimeMs || 0) + (getTimestamp() - startTime);\n }\n }\n\n /** Called by subclass to track memory allocations */\n protected trackAllocatedMemory(bytes: number, name = this.getStatsName()): void {\n const profiler = getCpuHotspotProfiler(this._device);\n const startTime = profiler ? getTimestamp() : 0;\n const stats = this._device.statsManager.getStats(GPU_TIME_AND_MEMORY_STATS);\n\n if (this.allocatedBytes > 0 && this.allocatedBytesName) {\n stats.get('GPU Memory').subtractCount(this.allocatedBytes);\n stats.get(`${this.allocatedBytesName} Memory`).subtractCount(this.allocatedBytes);\n }\n\n stats.get('GPU Memory').addCount(bytes);\n stats.get(`${name} Memory`).addCount(bytes);\n if (profiler) {\n profiler.statsBookkeepingCalls = (profiler.statsBookkeepingCalls || 0) + 1;\n profiler.statsBookkeepingTimeMs =\n (profiler.statsBookkeepingTimeMs || 0) + (getTimestamp() - startTime);\n }\n this.allocatedBytes = bytes;\n this.allocatedBytesName = name;\n }\n\n /** Called by subclass to track handle-backed memory allocations separately from owned allocations */\n protected trackReferencedMemory(bytes: number, name = this.getStatsName()): void {\n this.trackAllocatedMemory(bytes, `Referenced ${name}`);\n }\n\n /** Called by subclass to track memory deallocations */\n protected trackDeallocatedMemory(name = this.getStatsName()): void {\n if (this.allocatedBytes === 0) {\n this.allocatedBytesName = null;\n return;\n }\n\n const profiler = getCpuHotspotProfiler(this._device);\n const startTime = profiler ? getTimestamp() : 0;\n const stats = this._device.statsManager.getStats(GPU_TIME_AND_MEMORY_STATS);\n stats.get('GPU Memory').subtractCount(this.allocatedBytes);\n stats.get(`${this.allocatedBytesName || name} Memory`).subtractCount(this.allocatedBytes);\n if (profiler) {\n profiler.statsBookkeepingCalls = (profiler.statsBookkeepingCalls || 0) + 1;\n profiler.statsBookkeepingTimeMs =\n (profiler.statsBookkeepingTimeMs || 0) + (getTimestamp() - startTime);\n }\n this.allocatedBytes = 0;\n this.allocatedBytesName = null;\n }\n\n /** Called by subclass to deallocate handle-backed memory tracked via trackReferencedMemory() */\n protected trackDeallocatedReferencedMemory(name = this.getStatsName()): void {\n this.trackDeallocatedMemory(`Referenced ${name}`);\n }\n\n /** Called by resource constructor to track object creation */\n private addStats(): void {\n const name = this.getStatsName();\n const profiler = getCpuHotspotProfiler(this._device);\n const startTime = profiler ? getTimestamp() : 0;\n const statsObjects = [\n this._device.statsManager.getStats(RESOURCE_COUNTS_STATS),\n this._device.statsManager.getStats(LEGACY_RESOURCE_COUNTS_STATS)\n ];\n const orderedStatNames = getResourceCountStatOrder(this._device);\n for (const stats of statsObjects) {\n initializeStats(stats, orderedStatNames);\n }\n for (const stats of statsObjects) {\n stats.get('Resources Created').incrementCount();\n stats.get('Resources Active').incrementCount();\n stats.get(`${name}s Created`).incrementCount();\n stats.get(`${name}s Active`).incrementCount();\n }\n if (profiler) {\n profiler.statsBookkeepingCalls = (profiler.statsBookkeepingCalls || 0) + 1;\n profiler.statsBookkeepingTimeMs =\n (profiler.statsBookkeepingTimeMs || 0) + (getTimestamp() - startTime);\n }\n recordTransientCanvasResourceCreate(this._device, name);\n }\n\n /** Canonical resource name used for stats buckets. */\n protected getStatsName(): string {\n return getCanonicalResourceName(this);\n }\n}\n\n/**\n * Combines a map of user props and default props, only including props from defaultProps\n * @param props\n * @param defaultProps\n * @returns returns a map of overridden default props\n */\nfunction selectivelyMerge(props: Props, defaultProps: Required): Required {\n const mergedProps = {...defaultProps};\n for (const key in props) {\n if (props[key] !== undefined) {\n mergedProps[key] = props[key];\n }\n }\n return mergedProps;\n}\n\nfunction initializeStats(stats: Stats, orderedStatNames: readonly string[]): void {\n const statsMap = stats.stats;\n let addedOrderedStat = false;\n for (const statName of orderedStatNames) {\n if (!statsMap[statName]) {\n stats.get(statName);\n addedOrderedStat = true;\n }\n }\n\n const statCount = Object.keys(statsMap).length;\n const cachedStats = ORDERED_STATS_CACHE.get(stats);\n if (\n !addedOrderedStat &&\n cachedStats?.orderedStatNames === orderedStatNames &&\n cachedStats.statCount === statCount\n ) {\n return;\n }\n\n const reorderedStats: Record = {};\n let orderedStatNamesSet = ORDERED_STAT_NAME_SET_CACHE.get(orderedStatNames);\n if (!orderedStatNamesSet) {\n orderedStatNamesSet = new Set(orderedStatNames);\n ORDERED_STAT_NAME_SET_CACHE.set(orderedStatNames, orderedStatNamesSet);\n }\n\n for (const statName of orderedStatNames) {\n if (statsMap[statName]) {\n reorderedStats[statName] = statsMap[statName];\n }\n }\n\n for (const [statName, stat] of Object.entries(statsMap)) {\n if (!orderedStatNamesSet.has(statName)) {\n reorderedStats[statName] = stat;\n }\n }\n\n for (const statName of Object.keys(statsMap)) {\n delete statsMap[statName];\n }\n\n Object.assign(statsMap, reorderedStats);\n ORDERED_STATS_CACHE.set(stats, {orderedStatNames, statCount});\n}\n\nfunction getResourceCountStatOrder(device: Device): readonly string[] {\n return device.type === 'webgl' ? WEBGL_RESOURCE_COUNT_STAT_ORDER : BASE_RESOURCE_COUNT_STAT_ORDER;\n}\n\nfunction getCpuHotspotProfiler(device: Device): CpuHotspotProfiler | null {\n const profiler = device.userData[CPU_HOTSPOT_PROFILER_MODULE] as CpuHotspotProfiler | undefined;\n return profiler?.enabled ? profiler : null;\n}\n\nfunction getTimestamp(): number {\n return globalThis.performance?.now?.() ?? Date.now();\n}\n\nfunction recordTransientCanvasResourceCreate(device: Device, name: string): void {\n const profiler = getCpuHotspotProfiler(device);\n if (!profiler || !profiler.activeDefaultFramebufferAcquireDepth) {\n return;\n }\n\n profiler.transientCanvasResourceCreates = (profiler.transientCanvasResourceCreates || 0) + 1;\n\n switch (name) {\n case 'Texture':\n profiler.transientCanvasTextureCreates = (profiler.transientCanvasTextureCreates || 0) + 1;\n break;\n case 'TextureView':\n profiler.transientCanvasTextureViewCreates =\n (profiler.transientCanvasTextureViewCreates || 0) + 1;\n break;\n case 'Sampler':\n profiler.transientCanvasSamplerCreates = (profiler.transientCanvasSamplerCreates || 0) + 1;\n break;\n case 'Framebuffer':\n profiler.transientCanvasFramebufferCreates =\n (profiler.transientCanvasFramebufferCreates || 0) + 1;\n break;\n default:\n break;\n }\n}\n\nfunction getCanonicalResourceName(resource: Resource): string {\n let prototype = Object.getPrototypeOf(resource);\n\n while (prototype) {\n const parentPrototype = Object.getPrototypeOf(prototype);\n if (!parentPrototype || parentPrototype === Resource.prototype) {\n return (\n getPrototypeToStringTag(prototype) ||\n resource[Symbol.toStringTag] ||\n resource.constructor.name\n );\n }\n prototype = parentPrototype;\n }\n\n return resource[Symbol.toStringTag] || resource.constructor.name;\n}\n\nfunction getPrototypeToStringTag(prototype: object): string | null {\n const descriptor = Object.getOwnPropertyDescriptor(prototype, Symbol.toStringTag);\n if (typeof descriptor?.get === 'function') {\n return descriptor.get.call(prototype);\n }\n if (typeof descriptor?.value === 'string') {\n return descriptor.value;\n }\n return null;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport {Resource, ResourceProps} from './resource';\n\n/** Callback for Buffer.mapAndReadAsync */\nexport type BufferMapCallback = (arrayBuffer: ArrayBuffer, lifetime: 'mapped' | 'copied') => T;\n\nexport type BufferProps = ResourceProps & {\n /** Supply a handle to connect to an existing device-specific buffer */\n handle?: WebGLBuffer;\n /** Specifies how this buffer can be used */\n usage?: number;\n /** Length in bytes of memory to be allocated. If not specified, `byteLength` of `props.data` will be used. */\n byteLength?: number;\n /** Byte offset into the newly created Buffer to store data at */\n byteOffset?: number;\n /** If props.usage includes Buffer.INDEX. Note: uint8 indices are automatically converted to uint16 for WebGPU compatibility */\n indexType?: 'uint8' | 'uint16' | 'uint32';\n /** Data to initialize the buffer with. */\n data?: ArrayBuffer | ArrayBufferView | null;\n /** Callback to initialize data without copy */\n onMapped?: BufferMapCallback;\n};\n\n/** Abstract GPU buffer */\nexport abstract class Buffer extends Resource {\n /** Index buffer */\n static INDEX = 0x0010;\n /** Vertex buffer */\n static VERTEX = 0x0020;\n /** Uniform buffer */\n static UNIFORM = 0x0040;\n /** Storage buffer */\n static STORAGE = 0x0080;\n static INDIRECT = 0x0100;\n static QUERY_RESOLVE = 0x0200;\n\n // Usage Flags\n static MAP_READ = 0x01;\n static MAP_WRITE = 0x02;\n static COPY_SRC = 0x0004;\n static COPY_DST = 0x0008;\n\n override get [Symbol.toStringTag](): string {\n return 'Buffer';\n }\n\n /** The usage with which this buffer was created */\n readonly usage: number;\n /** For index buffers, whether indices are 8, 16 or 32 bit. Note: uint8 indices are automatically converted to uint16 for WebGPU compatibility */\n readonly indexType?: 'uint8' | 'uint16' | 'uint32';\n /** Length of buffer in bytes */\n abstract byteLength: number;\n /** \"Time\" of last update, can be used to check if redraw is needed */\n updateTimestamp: number;\n\n constructor(device: Device, props: BufferProps) {\n const deducedProps = {...props};\n\n // Deduce indexType\n if ((props.usage || 0) & Buffer.INDEX && !props.indexType) {\n if (props.data instanceof Uint32Array) {\n deducedProps.indexType = 'uint32';\n } else if (props.data instanceof Uint16Array) {\n deducedProps.indexType = 'uint16';\n } else if (props.data instanceof Uint8Array) {\n deducedProps.indexType = 'uint8';\n }\n }\n\n // Remove data from props before storing, we don't want to hold on to a big chunk of memory\n delete deducedProps.data;\n\n super(device, deducedProps, Buffer.defaultProps);\n\n this.usage = deducedProps.usage || 0;\n this.indexType = deducedProps.indexType;\n\n // TODO - perhaps this should be set on async write completion?\n this.updateTimestamp = device.incrementTimestamp();\n }\n\n /**\n * Create a copy of this Buffer with new byteLength, with same props but of the specified size.\n * @note Does not copy contents of the cloned Buffer.\n */\n clone(props: {byteLength: number}): Buffer {\n return this.device.createBuffer({...this.props, ...props});\n }\n\n /** Write data to buffer */\n abstract write(\n data: ArrayBufferLike | ArrayBufferView | SharedArrayBuffer,\n byteOffset?: number\n ): void;\n\n abstract mapAndWriteAsync(\n onMapped: BufferMapCallback>,\n byteOffset?: number,\n byteLength?: number\n ): Promise;\n\n /** Reads data asynchronously, returns a copy of the buffer data */\n abstract readAsync(byteOffset?: number, byteLength?: number): Promise;\n\n /** Maps buffer data to CPU memory. Mapped memory is only accessible in the callback */\n abstract mapAndReadAsync(\n onMapped: BufferMapCallback,\n byteOffset?: number,\n byteLength?: number\n ): Promise;\n\n /** Read data synchronously. @note WebGL2 only */\n abstract readSyncWebGL(byteOffset?: number, byteLength?: number): Uint8Array;\n\n // PROTECTED METHODS (INTENDED FOR USE BY OTHER FRAMEWORK CODE ONLY)\n\n /** Max amount of debug data saved. Two vec4's */\n static DEBUG_DATA_MAX_LENGTH = 32;\n\n /** A partial CPU-side copy of the data in this buffer, for debugging purposes */\n debugData: ArrayBuffer = new ArrayBuffer(0);\n\n /** This doesn't handle partial non-zero offset updates correctly */\n protected _setDebugData(\n data: ArrayBufferView | ArrayBufferLike | null,\n _byteOffset: number,\n byteLength: number\n ): void {\n let arrayBufferView: ArrayBufferView | null = null;\n let arrayBuffer: ArrayBufferLike | null;\n if (ArrayBuffer.isView(data)) {\n arrayBufferView = data;\n arrayBuffer = data.buffer;\n } else {\n arrayBuffer = data;\n }\n const debugDataLength = Math.min(\n data ? data.byteLength : byteLength,\n Buffer.DEBUG_DATA_MAX_LENGTH\n );\n if (arrayBuffer === null) {\n this.debugData = new ArrayBuffer(debugDataLength);\n } else {\n const sourceByteOffset = Math.min(arrayBufferView?.byteOffset || 0, arrayBuffer.byteLength);\n const availableByteLength = Math.max(0, arrayBuffer.byteLength - sourceByteOffset);\n const copyByteLength = Math.min(debugDataLength, availableByteLength);\n this.debugData = new Uint8Array(arrayBuffer, sourceByteOffset, copyByteLength).slice().buffer;\n }\n }\n\n static override defaultProps: Required = {\n ...Resource.defaultProps,\n usage: 0, // Buffer.COPY_DST | Buffer.COPY_SRC\n byteLength: 0,\n byteOffset: 0,\n data: null,\n indexType: 'uint16',\n onMapped: undefined!\n };\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {TypedArray, TypedArrayConstructor} from '../../types';\nimport {\n PrimitiveDataType,\n SignedDataType,\n NormalizedDataType,\n DataTypeInfo,\n TypedArrayConstructorT\n} from './data-types';\n\nexport class DataTypeDecoder {\n /**\n * Gets info about a data type constant (signed or normalized)\n * @returns underlying primitive / signed types, byte length, normalization, integer, signed flags\n */\n getDataTypeInfo(type: T): DataTypeInfo {\n const [signedType, primitiveType, byteLength] = NORMALIZED_TYPE_MAP[type];\n const normalized: boolean = type.includes('norm');\n const integer: boolean = !normalized && !type.startsWith('float');\n const signed: boolean = type.startsWith('s');\n return {\n signedType: signedType as DataTypeInfo['signedType'],\n primitiveType: primitiveType as DataTypeInfo['primitiveType'],\n byteLength: byteLength as DataTypeInfo['byteLength'],\n normalized: normalized as DataTypeInfo['normalized'],\n integer: integer as DataTypeInfo['integer'],\n signed: signed as DataTypeInfo['signed']\n // TODO - add webglOnly flag\n };\n }\n\n /** Build a vertex format from a signed data type and a component */\n getNormalizedDataType(signedDataType: SignedDataType): NormalizedDataType {\n const dataType: NormalizedDataType = signedDataType;\n // biome-ignore format: preserve layout\n switch (dataType) {\n case 'uint8': return 'unorm8';\n case 'sint8': return 'snorm8';\n case 'uint16': return 'unorm16';\n case 'sint16': return 'snorm16';\n default: return dataType;\n }\n }\n\n /** Align offset to 1, 2 or 4 elements (4, 8 or 16 bytes) */\n alignTo(size: number, count: number): number {\n // biome-ignore format: preserve layout\n switch (count) {\n case 1: return size; // Pad upwards to even multiple of 2\n case 2: return size + (size % 2); // Pad upwards to even multiple of 2\n default: return size + ((4 - (size % 4)) % 4); // Pad upwards to even multiple of 4\n }\n }\n\n /** Returns the VariableShaderType that corresponds to a typed array */\n getDataType(arrayOrType: TypedArray | TypedArrayConstructor): SignedDataType {\n const Constructor = ArrayBuffer.isView(arrayOrType) ? arrayOrType.constructor : arrayOrType;\n if (Constructor === Uint8ClampedArray) {\n return 'uint8';\n }\n const info = Object.values(NORMALIZED_TYPE_MAP).find(entry => Constructor === entry[4]);\n if (!info) {\n throw new Error(Constructor.name);\n }\n return info[0];\n }\n\n /** Returns the TypedArray that corresponds to a shader data type */\n getTypedArrayConstructor(\n type: NormalizedDataType\n ): TypedArrayConstructorT {\n const [, , , , Constructor] = NORMALIZED_TYPE_MAP[type];\n return Constructor as unknown as TypedArrayConstructorT;\n }\n}\n\n/** Entry point for decoding luma.gl data types */\nexport const dataTypeDecoder = new DataTypeDecoder();\n\nconst NORMALIZED_TYPE_MAP = {\n uint8: ['uint8', 'u32', 1, false, Uint8Array],\n sint8: ['sint8', 'i32', 1, false, Int8Array],\n unorm8: ['uint8', 'f32', 1, true, Uint8Array],\n snorm8: ['sint8', 'f32', 1, true, Int8Array],\n uint16: ['uint16', 'u32', 2, false, Uint16Array],\n sint16: ['sint16', 'i32', 2, false, Int16Array],\n unorm16: ['uint16', 'u32', 2, true, Uint16Array],\n snorm16: ['sint16', 'i32', 2, true, Int16Array],\n float16: ['float16', 'f16', 2, false, Uint16Array],\n float32: ['float32', 'f32', 4, false, Float32Array],\n uint32: ['uint32', 'u32', 4, false, Uint32Array],\n sint32: ['sint32', 'i32', 4, false, Int32Array]\n} satisfies Record<\n NormalizedDataType,\n [\n SignedDataType,\n PrimitiveDataType,\n bytes: 1 | 2 | 4,\n normalized: boolean,\n arrayConstructor: TypedArrayConstructor\n ]\n>;\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {TypedArray} from '../../types';\nimport type {NormalizedDataType, PrimitiveDataType, SignedDataType} from '../data-types/data-types';\nimport type {VertexFormat, VertexFormatInfo} from './vertex-formats';\nimport {dataTypeDecoder} from '../data-types/data-type-decoder';\n\nexport class VertexFormatDecoder {\n /**\n * Decodes a vertex format, returning type, components, byte length and flags (integer, signed, normalized)\n */\n getVertexFormatInfo(format: T): VertexFormatInfo {\n // Strip the -webgl ending if present\n let webglOnly: boolean | undefined;\n if (format.endsWith('-webgl')) {\n format.replace('-webgl', '');\n webglOnly = true;\n }\n // split components from type\n const [type_, count] = format.split('x');\n const type = type_ as NormalizedDataType;\n const components = (count ? parseInt(count) : 1) as 1 | 2 | 3 | 4;\n // decode the type\n const decodedType = dataTypeDecoder.getDataTypeInfo(type);\n const result: VertexFormatInfo = {\n type,\n components,\n byteLength: decodedType.byteLength * components,\n integer: decodedType.integer,\n signed: decodedType.signed,\n normalized: decodedType.normalized\n };\n if (webglOnly) {\n result.webglOnly = true;\n }\n return result;\n }\n\n /** Build a vertex format from a signed data type and a component */\n makeVertexFormat(\n signedDataType: SignedDataType,\n components: 1 | 2 | 3 | 4,\n normalized?: boolean\n ): VertexFormat {\n const dataType: NormalizedDataType = normalized\n ? dataTypeDecoder.getNormalizedDataType(signedDataType)\n : signedDataType;\n\n switch (dataType) {\n // Special cases for WebGL-only x3 formats that WebGPU does not support.\n case 'unorm8':\n if (components === 1) {\n return 'unorm8';\n }\n if (components === 3) {\n return 'unorm8x3-webgl';\n }\n return `${dataType}x${components}`;\n\n case 'snorm8':\n if (components === 1) {\n return 'snorm8';\n }\n if (components === 3) {\n return 'snorm8x3-webgl';\n }\n return `${dataType}x${components}`;\n\n case 'uint8':\n case 'sint8':\n // WebGPU 8 bit formats must be aligned to 16 bit boundaries.\n if (components === 1 || components === 3) {\n throw new Error(`size: ${components}`);\n }\n return `${dataType}x${components}`;\n\n case 'uint16':\n if (components === 1) {\n return 'uint16';\n }\n if (components === 3) {\n return 'uint16x3-webgl';\n }\n return `${dataType}x${components}`;\n\n case 'sint16':\n if (components === 1) {\n return 'sint16';\n }\n if (components === 3) {\n return 'sint16x3-webgl';\n }\n return `${dataType}x${components}`;\n\n case 'unorm16':\n if (components === 1) {\n return 'unorm16';\n }\n if (components === 3) {\n return 'unorm16x3-webgl';\n }\n return `${dataType}x${components}`;\n\n case 'snorm16':\n if (components === 1) {\n return 'snorm16';\n }\n if (components === 3) {\n return 'snorm16x3-webgl';\n }\n return `${dataType}x${components}`;\n\n case 'float16':\n // WebGPU 16 bit formats must be aligned to 32 bit boundaries\n if (components === 1 || components === 3) {\n throw new Error(`size: ${components}`);\n }\n return `${dataType}x${components}`;\n\n default:\n return components === 1 ? dataType : `${dataType}x${components}`;\n }\n }\n\n /** Get the vertex format for an attribute with TypedArray and size */\n getVertexFormatFromAttribute(\n typedArray: TypedArray,\n size: number,\n normalized?: boolean\n ): VertexFormat {\n if (!size || size > 4) {\n throw new Error(`size ${size}`);\n }\n\n const components = size as 1 | 2 | 3 | 4;\n const signedDataType = dataTypeDecoder.getDataType(typedArray);\n return this.makeVertexFormat(signedDataType, components, normalized);\n }\n\n /**\n * Return a \"default\" vertex format for a certain shader data type\n * The simplest vertex format that matches the shader attribute's data type\n */\n\n getCompatibleVertexFormat(opts: {\n primitiveType: PrimitiveDataType;\n components: 1 | 2 | 3 | 4;\n }): VertexFormat {\n let vertexType: NormalizedDataType;\n switch (opts.primitiveType) {\n case 'f32':\n vertexType = 'float32';\n break;\n case 'i32':\n vertexType = 'sint32';\n break;\n case 'u32':\n vertexType = 'uint32';\n break;\n case 'f16':\n return opts.components <= 2 ? 'float16x2' : 'float16x4';\n }\n\n // TODO logic does not work for float16\n if (opts.components === 1) {\n return vertexType;\n }\n return `${vertexType}x${opts.components}`;\n }\n}\n\n/** Decoder for luma.gl vertex types */\nexport const vertexFormatDecoder = new VertexFormatDecoder();\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {\n TextureFormat,\n TextureFormatColorUncompressed,\n TextureFormatDepthStencil,\n TextureFeature,\n TextureFormatInfo,\n TextureFormatCompressed\n} from './texture-formats';\n/* eslint-disable camelcase */\n\n// Define local device feature strings to optimize minification\nconst texture_compression_bc: TextureFeature = 'texture-compression-bc';\nconst texture_compression_astc: TextureFeature = 'texture-compression-astc';\nconst texture_compression_etc2: TextureFeature = 'texture-compression-etc2';\nconst texture_compression_etc1_webgl: TextureFeature = 'texture-compression-etc1-webgl';\nconst texture_compression_pvrtc_webgl: TextureFeature = 'texture-compression-pvrtc-webgl';\nconst texture_compression_atc_webgl: TextureFeature = 'texture-compression-atc-webgl';\n\nconst float32_renderable: TextureFeature = 'float32-renderable-webgl';\nconst float16_renderable: TextureFeature = 'float16-renderable-webgl';\nconst rgb9e5ufloat_renderable: TextureFeature = 'rgb9e5ufloat-renderable-webgl';\nconst snorm8_renderable: TextureFeature = 'snorm8-renderable-webgl';\nconst norm16_webgl: TextureFeature = 'norm16-webgl';\nconst norm16_renderable: TextureFeature = 'norm16-renderable-webgl';\nconst snorm16_renderable: TextureFeature = 'snorm16-renderable-webgl';\n\nconst float32_filterable: TextureFeature = 'float32-filterable';\nconst float16_filterable: TextureFeature = 'float16-filterable-webgl';\n\n/** https://www.w3.org/TR/webgpu/#texture-format-caps */\n\n/** Internal type representing texture capabilities */\ntype TextureFormatDefinition = Partial & {\n /** for compressed texture formats */\n f?: TextureFeature;\n /** renderable if feature is present. false means the spec does not support this format */\n render?: TextureFeature | false;\n /** filterable if feature is present. false means the spec does not support this format */\n filter?: TextureFeature | false;\n blend?: TextureFeature | false;\n store?: TextureFeature | false;\n\n /** (bytes per pixel), for memory usage calculations. */\n b?: number;\n /** channels */\n c?: number;\n bpp?: number;\n /** packed */\n p?: number;\n\n /** If not supported on WebGPU */\n wgpu?: false;\n};\n\nexport function getTextureFormatDefinition(format: TextureFormat): TextureFormatDefinition {\n const info = TEXTURE_FORMAT_TABLE[format];\n if (!info) {\n throw new Error(`Unsupported texture format ${format}`);\n }\n return info;\n}\n\nexport function getTextureFormatTable(): Readonly> {\n return TEXTURE_FORMAT_TABLE;\n}\n\n// biome-ignore format: preserve layout\nconst TEXTURE_FORMAT_COLOR_DEPTH_TABLE: Readonly> = {\n // 8-bit formats\n 'r8unorm': {},\n 'rg8unorm': {},\n 'rgb8unorm-webgl': {},\n 'rgba8unorm': {},\n 'rgba8unorm-srgb': {},\n\n 'r8snorm': {render: snorm8_renderable},\n 'rg8snorm': {render: snorm8_renderable},\n 'rgb8snorm-webgl': {},\n 'rgba8snorm': {render: snorm8_renderable},\n\n 'r8uint': {},\n 'rg8uint': {},\n 'rgba8uint': {},\n\n 'r8sint': {},\n 'rg8sint': {},\n 'rgba8sint': {},\n\n 'bgra8unorm': {},\n 'bgra8unorm-srgb': {},\n\n\n 'r16unorm': {f: norm16_webgl, render: norm16_renderable},\n 'rg16unorm': {f: norm16_webgl, render: norm16_renderable},\n 'rgb16unorm-webgl': {f: norm16_webgl, render: false}, // rgb not renderable\n 'rgba16unorm': {f: norm16_webgl, render: norm16_renderable},\n\n 'r16snorm': {f: norm16_webgl, render: snorm16_renderable},\n 'rg16snorm': {f: norm16_webgl, render: snorm16_renderable},\n 'rgb16snorm-webgl': {f: norm16_webgl, render: false}, // rgb not renderable\n 'rgba16snorm': {f: norm16_webgl, render: snorm16_renderable},\n\n 'r16uint': {},\n 'rg16uint': {},\n 'rgba16uint': {},\n\n 'r16sint': {},\n 'rg16sint': {},\n 'rgba16sint': {},\n\n 'r16float': {render: float16_renderable, filter: 'float16-filterable-webgl'},\n 'rg16float': {render: float16_renderable, filter: float16_filterable},\n 'rgba16float': {render: float16_renderable, filter: float16_filterable},\n\n 'r32uint': {},\n 'rg32uint': {},\n 'rgba32uint': {},\n\n 'r32sint': {},\n 'rg32sint': {},\n 'rgba32sint': {},\n\n 'r32float': {render: float32_renderable, filter: float32_filterable},\n 'rg32float': {render: false, filter: float32_filterable},\n 'rgb32float-webgl': {render: float32_renderable, filter: float32_filterable},\n 'rgba32float': {render: float32_renderable, filter: float32_filterable},\n\n // Packed 16-bit formats\n 'rgba4unorm-webgl': {channels: 'rgba', bitsPerChannel: [4, 4, 4, 4], packed: true},\n 'rgb565unorm-webgl': {channels: 'rgb', bitsPerChannel: [5, 6, 5, 0], packed: true},\n 'rgb5a1unorm-webgl': {channels: 'rgba', bitsPerChannel: [5, 5, 5, 1], packed: true},\n\n // Packed 32 bit formats\n 'rgb9e5ufloat': {channels: 'rgb', packed: true, render: rgb9e5ufloat_renderable}, // , filter: true},\n 'rg11b10ufloat': {channels: 'rgb', bitsPerChannel: [11, 11, 10, 0], packed: true, p: 1,render: float32_renderable},\n 'rgb10a2unorm': {channels: 'rgba', bitsPerChannel: [10, 10, 10, 2], packed: true, p: 1},\n 'rgb10a2uint': {channels: 'rgba', bitsPerChannel: [10, 10, 10, 2], packed: true, p: 1},\n\n // Depth/stencil Formats\n \n // Depth and stencil formats\n stencil8: {attachment: 'stencil', bitsPerChannel: [8, 0, 0, 0], dataType: 'uint8'},\n 'depth16unorm': {attachment: 'depth', bitsPerChannel: [16, 0, 0, 0], dataType: 'uint16'},\n 'depth24plus': {attachment: 'depth', bitsPerChannel: [24, 0, 0, 0], dataType: 'uint32'},\n 'depth32float': {attachment: 'depth', bitsPerChannel: [32, 0, 0, 0], dataType: 'float32'},\n // The depth component of the \"depth24plus\" and \"depth24plus-stencil8\" formats may be implemented as either a 24-bit depth value or a \"depth32float\" value.\n 'depth24plus-stencil8': {attachment: 'depth-stencil', bitsPerChannel: [24, 8, 0, 0], packed: true},\n // \"depth32float-stencil8\" feature\n 'depth32float-stencil8': {attachment: 'depth-stencil', bitsPerChannel: [32, 8, 0, 0], packed: true},\n};\n\n// biome-ignore format: preserve layout\nconst TEXTURE_FORMAT_COMPRESSED_TABLE: Readonly> = {\n\n // BC compressed formats: check device.features.has(\"texture-compression-bc\");\n\n 'bc1-rgb-unorm-webgl': {f: texture_compression_bc},\n 'bc1-rgb-unorm-srgb-webgl': {f: texture_compression_bc},\n\n 'bc1-rgba-unorm': {f: texture_compression_bc},\n 'bc1-rgba-unorm-srgb': {f: texture_compression_bc},\n 'bc2-rgba-unorm': {f: texture_compression_bc},\n 'bc2-rgba-unorm-srgb': {f: texture_compression_bc},\n 'bc3-rgba-unorm': {f: texture_compression_bc},\n 'bc3-rgba-unorm-srgb': {f: texture_compression_bc},\n 'bc4-r-unorm': {f: texture_compression_bc},\n 'bc4-r-snorm': {f: texture_compression_bc},\n 'bc5-rg-unorm': {f: texture_compression_bc},\n 'bc5-rg-snorm': {f: texture_compression_bc},\n 'bc6h-rgb-ufloat': {f: texture_compression_bc},\n 'bc6h-rgb-float': {f: texture_compression_bc},\n 'bc7-rgba-unorm': {f: texture_compression_bc},\n 'bc7-rgba-unorm-srgb': {f: texture_compression_bc},\n\n // WEBGL_compressed_texture_etc: device.features.has(\"texture-compression-etc2\")\n // Note: Supposedly guaranteed availability compressed formats in WebGL2, but through CPU decompression\n\n 'etc2-rgb8unorm': {f: texture_compression_etc2},\n 'etc2-rgb8unorm-srgb': {f: texture_compression_etc2},\n 'etc2-rgb8a1unorm': {f: texture_compression_etc2},\n 'etc2-rgb8a1unorm-srgb': {f: texture_compression_etc2},\n 'etc2-rgba8unorm': {f: texture_compression_etc2},\n 'etc2-rgba8unorm-srgb': {f: texture_compression_etc2},\n\n 'eac-r11unorm': {f: texture_compression_etc2},\n 'eac-r11snorm': {f: texture_compression_etc2},\n 'eac-rg11unorm': {f: texture_compression_etc2},\n 'eac-rg11snorm': {f: texture_compression_etc2},\n\n // X_ASTC compressed formats: device.features.has(\"texture-compression-astc\")\n\n 'astc-4x4-unorm': {f: texture_compression_astc},\n 'astc-4x4-unorm-srgb': {f: texture_compression_astc},\n 'astc-5x4-unorm': {f: texture_compression_astc},\n 'astc-5x4-unorm-srgb': {f: texture_compression_astc},\n 'astc-5x5-unorm': {f: texture_compression_astc},\n 'astc-5x5-unorm-srgb': {f: texture_compression_astc},\n 'astc-6x5-unorm': {f: texture_compression_astc},\n 'astc-6x5-unorm-srgb': {f: texture_compression_astc},\n 'astc-6x6-unorm': {f: texture_compression_astc},\n 'astc-6x6-unorm-srgb': {f: texture_compression_astc},\n 'astc-8x5-unorm': {f: texture_compression_astc},\n 'astc-8x5-unorm-srgb': {f: texture_compression_astc},\n 'astc-8x6-unorm': {f: texture_compression_astc},\n 'astc-8x6-unorm-srgb': {f: texture_compression_astc},\n 'astc-8x8-unorm': {f: texture_compression_astc},\n 'astc-8x8-unorm-srgb': {f: texture_compression_astc},\n 'astc-10x5-unorm': {f: texture_compression_astc},\n 'astc-10x5-unorm-srgb': {f: texture_compression_astc},\n 'astc-10x6-unorm': {f: texture_compression_astc},\n 'astc-10x6-unorm-srgb': {f: texture_compression_astc},\n 'astc-10x8-unorm': {f: texture_compression_astc},\n 'astc-10x8-unorm-srgb': {f: texture_compression_astc},\n 'astc-10x10-unorm': {f: texture_compression_astc},\n 'astc-10x10-unorm-srgb': {f: texture_compression_astc},\n 'astc-12x10-unorm': {f: texture_compression_astc},\n 'astc-12x10-unorm-srgb': {f: texture_compression_astc},\n 'astc-12x12-unorm': {f: texture_compression_astc},\n 'astc-12x12-unorm-srgb': {f: texture_compression_astc},\n\n // WEBGL_compressed_texture_pvrtc\n\n 'pvrtc-rgb4unorm-webgl': {f: texture_compression_pvrtc_webgl},\n 'pvrtc-rgba4unorm-webgl': {f: texture_compression_pvrtc_webgl},\n 'pvrtc-rgb2unorm-webgl': {f: texture_compression_pvrtc_webgl},\n 'pvrtc-rgba2unorm-webgl': {f: texture_compression_pvrtc_webgl},\n\n // WEBGL_compressed_texture_etc1\n\n 'etc1-rbg-unorm-webgl': {f: texture_compression_etc1_webgl},\n\n // WEBGL_compressed_texture_atc\n\n 'atc-rgb-unorm-webgl': {f: texture_compression_atc_webgl},\n 'atc-rgba-unorm-webgl': {f: texture_compression_atc_webgl},\n 'atc-rgbai-unorm-webgl': {f: texture_compression_atc_webgl}\n};\n\nexport const TEXTURE_FORMAT_TABLE: Readonly> = {\n ...TEXTURE_FORMAT_COLOR_DEPTH_TABLE,\n ...TEXTURE_FORMAT_COMPRESSED_TABLE\n};\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {NormalizedDataType} from '../data-types/data-types';\nimport {dataTypeDecoder} from '../data-types/data-type-decoder';\nimport type {\n TextureFormat,\n TextureFormatCompressed,\n TextureFormatInfo,\n TextureFormatCapabilities,\n TextureFormatColor,\n TextureMemoryLayout,\n TextureFormatDepthStencil\n} from './texture-formats';\nimport {getTextureFormatDefinition} from './texture-format-table';\n\nconst RGB_FORMAT_REGEX = /^(r|rg|rgb|rgba|bgra)([0-9]*)([a-z]*)(-srgb)?(-webgl)?$/;\nconst COLOR_FORMAT_PREFIXES = ['rgb', 'rgba', 'bgra'];\nconst DEPTH_FORMAT_PREFIXES = ['depth', 'stencil'];\n// biome-ignore format: preserve layout\nconst COMPRESSED_TEXTURE_FORMAT_PREFIXES = [\n 'bc1', 'bc2', 'bc3', 'bc4', 'bc5', 'bc6', 'bc7', 'etc1', 'etc2', 'eac', 'atc', 'astc', 'pvrtc'\n];\n\n// HELPERS - MEMORY LAYOUT\n\n/** Options to calculate a texture layout */\nexport type TextureMemoryLayoutOptions = {\n /** Number of bytes per pixel */\n format: TextureFormat;\n /** Width of the texture in pixels */\n width: number;\n /** Height of the texture in pixels */\n height: number;\n /** Number of images in the texture */\n depth: number;\n /** Alignment of each row */\n byteAlignment: number;\n};\n\n/** Class that helps applications work with texture formats */\nexport class TextureFormatDecoder {\n /** Checks if a texture format is color */\n isColor(format: TextureFormat): format is TextureFormatColor {\n return COLOR_FORMAT_PREFIXES.some(prefix => format.startsWith(prefix));\n }\n\n /** Checks if a texture format is depth or stencil */\n isDepthStencil(format: TextureFormat): format is TextureFormatDepthStencil {\n return DEPTH_FORMAT_PREFIXES.some(prefix => format.startsWith(prefix));\n }\n\n /** Checks if a texture format is compressed */\n isCompressed(format: TextureFormat): format is TextureFormatCompressed {\n return COMPRESSED_TEXTURE_FORMAT_PREFIXES.some(prefix => format.startsWith(prefix));\n }\n\n /** Returns information about a texture format, e.g. attachment type, components, byte length and flags (integer, signed, normalized) */\n getInfo(format: TextureFormat): TextureFormatInfo {\n return getTextureFormatInfo(format);\n }\n\n /** \"static\" capabilities of a texture format. @note Needs to be adjusted against current device */\n getCapabilities(format: TextureFormat): TextureFormatCapabilities {\n return getTextureFormatCapabilities(format);\n }\n\n /** Computes the memory layout for a texture, in particular including row byte alignment */\n computeMemoryLayout(opts: TextureMemoryLayoutOptions): TextureMemoryLayout {\n return computeTextureMemoryLayout(opts);\n }\n}\n\n/** Decoder for luma.gl texture types */\nexport const textureFormatDecoder = new TextureFormatDecoder();\n\n// HELPERS - MEMORY LAYOUT\n\n/** Get the memory layout of a texture */\nfunction computeTextureMemoryLayout({\n format,\n width,\n height,\n depth,\n byteAlignment\n}: TextureMemoryLayoutOptions): TextureMemoryLayout {\n const formatInfo = textureFormatDecoder.getInfo(format);\n const {\n bytesPerPixel,\n bytesPerBlock = bytesPerPixel,\n blockWidth = 1,\n blockHeight = 1,\n compressed = false\n } = formatInfo;\n const blockColumns = compressed ? Math.ceil(width / blockWidth) : width;\n const blockRows = compressed ? Math.ceil(height / blockHeight) : height;\n // byteAlignment comes from the backend/call site. WebGPU buffer copies use 256, queue.writeTexture uses 1.\n const unpaddedBytesPerRow = blockColumns * bytesPerBlock;\n const bytesPerRow = Math.ceil(unpaddedBytesPerRow / byteAlignment) * byteAlignment;\n const rowsPerImage = blockRows;\n const byteLength = bytesPerRow * rowsPerImage * depth;\n\n return {\n bytesPerPixel,\n bytesPerRow,\n rowsPerImage,\n depthOrArrayLayers: depth,\n bytesPerImage: bytesPerRow * rowsPerImage,\n byteLength\n };\n}\n\n// HELPERS - CAPABILITIES\n\nfunction getTextureFormatCapabilities(format: TextureFormat): TextureFormatCapabilities {\n const info = getTextureFormatDefinition(format);\n\n const formatCapabilities: Required = {\n format,\n create: info.f ?? true,\n render: info.render ?? true,\n filter: info.filter ?? true,\n blend: info.blend ?? true,\n store: info.store ?? true\n };\n\n const formatInfo = getTextureFormatInfo(format);\n const isDepthStencil = format.startsWith('depth') || format.startsWith('stencil');\n const isSigned = formatInfo?.signed;\n const isInteger = formatInfo?.integer;\n const isWebGLSpecific = formatInfo?.webgl;\n const isCompressed = Boolean(formatInfo?.compressed);\n\n // Only uncompressed color formats can be used as color-renderable attachments.\n formatCapabilities.render &&= !isDepthStencil && !isCompressed;\n // signed and integer formats are not filterable\n formatCapabilities.filter &&= !isDepthStencil && !isSigned && !isInteger && !isWebGLSpecific;\n\n return formatCapabilities;\n}\n\n// HELPER - FORMAT INFO\n\n/**\n * Decodes a texture format, returning e.g. attatchment type, components, byte length and flags (integer, signed, normalized)\n */\nexport function getTextureFormatInfo(format: TextureFormat): TextureFormatInfo {\n let formatInfo: TextureFormatInfo = getTextureFormatInfoUsingTable(format);\n\n if (textureFormatDecoder.isCompressed(format)) {\n formatInfo.channels = 'rgb';\n formatInfo.components = 3;\n formatInfo.bytesPerPixel = 1;\n formatInfo.srgb = false;\n formatInfo.compressed = true;\n formatInfo.bytesPerBlock = getCompressedTextureBlockByteLength(format);\n\n const blockSize = getCompressedTextureBlockSize(format);\n if (blockSize) {\n formatInfo.blockWidth = blockSize.blockWidth;\n formatInfo.blockHeight = blockSize.blockHeight;\n }\n }\n\n // Fill in missing information that can be derived from the format string\n const matches = !formatInfo.packed ? RGB_FORMAT_REGEX.exec(format as string) : null;\n if (matches) {\n const [, channels, length, type, srgb, suffix] = matches;\n const dataType = `${type}${length}` as NormalizedDataType;\n const decodedType = dataTypeDecoder.getDataTypeInfo(dataType);\n const bits = decodedType.byteLength * 8;\n const components = (channels?.length ?? 1) as 1 | 2 | 3 | 4;\n const bitsPerChannel: [number, number, number, number] = [\n bits,\n components >= 2 ? bits : 0,\n components >= 3 ? bits : 0,\n components >= 4 ? bits : 0\n ];\n\n formatInfo = {\n format,\n attachment: formatInfo.attachment,\n dataType: decodedType.signedType,\n components,\n channels: channels as 'r' | 'rg' | 'rgb' | 'rgba',\n integer: decodedType.integer,\n signed: decodedType.signed,\n normalized: decodedType.normalized,\n bitsPerChannel,\n bytesPerPixel: decodedType.byteLength * components,\n packed: formatInfo.packed,\n srgb: formatInfo.srgb\n };\n\n if (suffix === '-webgl') {\n formatInfo.webgl = true;\n }\n // dataType - overwritten by decodedType\n if (srgb === '-srgb') {\n formatInfo.srgb = true;\n }\n }\n\n if (format.endsWith('-webgl')) {\n formatInfo.webgl = true;\n }\n if (format.endsWith('-srgb')) {\n formatInfo.srgb = true;\n }\n\n return formatInfo;\n}\n\n/** Decode texture format info from the table */\nfunction getTextureFormatInfoUsingTable(format: TextureFormat): TextureFormatInfo {\n const info = getTextureFormatDefinition(format);\n\n const bytesPerPixel = info.bytesPerPixel || 1;\n const bitsPerChannel = info.bitsPerChannel || [8, 8, 8, 8];\n delete info.bitsPerChannel;\n delete info.bytesPerPixel;\n delete info.f;\n delete info.render;\n delete info.filter;\n delete info.blend;\n delete info.store;\n\n const formatInfo: TextureFormatInfo = {\n ...info,\n format,\n attachment: info.attachment || 'color',\n channels: info.channels || 'r',\n components: (info.components || info.channels?.length || 1) as 1 | 2 | 3 | 4,\n bytesPerPixel,\n bitsPerChannel,\n dataType: info.dataType || 'uint8',\n srgb: info.srgb ?? false,\n packed: info.packed ?? false,\n webgl: info.webgl ?? false,\n integer: info.integer ?? false,\n signed: info.signed ?? false,\n normalized: info.normalized ?? false,\n compressed: info.compressed ?? false\n };\n\n return formatInfo;\n}\n\n/** Parses ASTC block widths from format string */\nfunction getCompressedTextureBlockSize(\n format: TextureFormatCompressed\n): {blockWidth: number; blockHeight: number} | null {\n const REGEX = /.*-(\\d+)x(\\d+)-.*/;\n const matches = REGEX.exec(format as string);\n if (matches) {\n const [, blockWidth, blockHeight] = matches;\n return {blockWidth: Number(blockWidth), blockHeight: Number(blockHeight)};\n }\n\n if (\n format.startsWith('bc') ||\n format.startsWith('etc1') ||\n format.startsWith('etc2') ||\n format.startsWith('eac') ||\n format.startsWith('atc')\n ) {\n return {blockWidth: 4, blockHeight: 4};\n }\n\n if (format.startsWith('pvrtc-rgb4') || format.startsWith('pvrtc-rgba4')) {\n return {blockWidth: 4, blockHeight: 4};\n }\n\n if (format.startsWith('pvrtc-rgb2') || format.startsWith('pvrtc-rgba2')) {\n return {blockWidth: 8, blockHeight: 4};\n }\n\n return null;\n}\n\nfunction getCompressedTextureBlockByteLength(format: TextureFormatCompressed): number {\n if (\n format.startsWith('bc1') ||\n format.startsWith('bc4') ||\n format.startsWith('etc1') ||\n format.startsWith('etc2-rgb8') ||\n format.startsWith('etc2-rgb8a1') ||\n format.startsWith('eac-r11') ||\n format === 'atc-rgb-unorm-webgl'\n ) {\n return 8;\n }\n\n if (\n format.startsWith('bc2') ||\n format.startsWith('bc3') ||\n format.startsWith('bc5') ||\n format.startsWith('bc6h') ||\n format.startsWith('bc7') ||\n format.startsWith('etc2-rgba8') ||\n format.startsWith('eac-rg11') ||\n format.startsWith('astc') ||\n format === 'atc-rgba-unorm-webgl' ||\n format === 'atc-rgbai-unorm-webgl'\n ) {\n return 16;\n }\n\n if (format.startsWith('pvrtc')) {\n return 8;\n }\n\n return 16;\n}\n\n/*\n'r8unorm':\t{s: \"float\"}, // \t✓\t✓\t✓\t},\n'r8snorm':\t{s: \"float\"}, // \t\t✓\t\t},\n'r8uint':\t{s: \"uint\"}, // \t✓\t✓\t\t},\n'r8sint':\t{s: \"sint\"}, // \t✓\t✓\t\t},\n'rg8unorm':\t{s: \"float\"}, // \t✓\t✓\t✓\t},\n'rg8snorm':\t{s: \"float\"}, // \t\t✓\t\t},\n'rg8uint':\t{s: \"uint\"}, // \t✓\t✓\t\t},\n'rg8sint':\t{s: \"sint\"}, // \t✓\t✓\t\t},\n'rgba8unorm':\t{s: \"float\"}, // \t✓\t✓\t✓\t✓},\n'rgba8unorm-srgb': {s: \"float\"}, // \t✓\t✓\t✓\t},\n'rgba8snorm':\t{s: \"float\"}, // \t\t✓\t\t✓},\n'rgba8uint':\t{s: \"uint\"}, // \t✓\t✓\t\t✓},\n'rgba8sint':\t{s: \"sint\"}, // \t✓\t✓\t\t✓},\n'bgra8unorm':\t{s: \"float\"}, // \t✓\t✓\t✓\t},\n'bgra8unorm-srgb': {s: \"float\"}, // \t✓\t✓\t✓\t},\n// 16-bit per component\t\t\t\t\t\n'r16uint': {s: \"uint\"}, // \t✓\t✓\t\t},\n'r16sint': {s: \"sint\"}, // \t✓\t✓\t\t},\n'r16float': {s: \"float\"}, // \t✓\t✓\t✓\t},\n'rg16uint': {s: \"uint\"}, // \t✓\t✓\t\t},\n'rg16sint': {s: \"sint\"}, // \t✓\t✓\t\t},\n'rg16float': {s: \"float\"}, // \t✓\t✓\t✓\t},\n'rgba16uint': {s: \"uint\"}, // \t✓\t✓\t\t✓},\n'rgba16sint': {s: \"sint\"}, // \t✓\t✓\t\t✓},\n'rgba16float': {s: \"float\"}, // \t✓\t✓\t✓\t✓},\n// 32-bit per component\t\t\t\t\t\n'r32uint': {s: \"uint\"}, // \t✓\t\t\t✓},\n'r32sint': {s: \"sint\"}, // \t✓\t\t\t✓},\n'r32float': {\"unfilterable-float\"\t✓\t✓\t\t✓},\n'rg32uint': {s: \"uint\"}, // \t✓\t\t\t✓},\n'rg32sint': {s: \"sint\"}, // \t✓\t\t\t✓},\n'rg32float': {\"unfilterable-float\"\t✓\t\t\t✓},\n'rgba32uint': {s: \"uint\"}, // \t✓\t\t\t✓},\n'rgba32sint': {s: \"sint\"}, // \t✓\t\t\t✓},\n'rgba32float': {\"unfilterable-float\"\t✓\t\t\t✓},\n// mixed component width\t\t\t\t\t\n'rgb10a2unorm': {s: \"float\"}, // \t✓\t✓\t✓\t}\n'rg11b10ufloat': {s: \"float\"}, // \t\t✓\t\t}\n// Format\tBytes per texel\tAspect\tGPUTextureSampleType\tValid image copy source\tValid image copy destination\n'stencil8': {1 − 4\tstencil\t\"uint\"\t✓}\n'depth16unorm': {2\tdepth\t\"depth\"\t✓}\n'depth24plus': {4\tdepth\t\"depth\"\t✗}\n'depth24plus': {stencil8\t4 − 8\tdepth\t\"depth\"\t✗}\n'stencil': {s: \"uint\"}, // \t✓}\n'depth32float': {4\tdepth\t\"depth\"\t✓\t✗}\n'depth24unorm': {stencil8\t4\tdepth\t\"depth\"\t✗}\n'stencil': {s: \"uint\"}, // \t✓}\n'depth32float': {stencil8}\n\n// Format\tBytes per block\tGPUTextureSampleType\tBlock Size\tFeature\n'rgb9e5ufloat': {c: 4, s: \"float\",\tbpp: 4/(1*1)},\n\n'bc1-rgba-unorm': {c: 4. s: \"float\", bpp: 8/(4 * 4) f: 'texture-compression-bc'},\n'bc1-rgba-unorm-srgb': {c: 4. s: \"float\", bpp: 8/(4 * 4) f: 'texture-compression-bc'},\n'bc2-rgba-unorm': {c: 4. s: \"float\", bpp: 16/(4 * 4) f: 'texture-compression-bc'},\n'bc2-rgba-unorm-srgb': {c: 4. s: \"float\", bpp: 16/(4 * 4) f: 'texture-compression-bc'},\n'bc3-rgba-unorm': {c: 4. s: \"float\", bpp: 16/(4 * 4) f: 'texture-compression-bc'},\n'bc3-rgba-unorm-srgb': {c: 4. s: \"float\", bpp: 16/(4 * 4) f: 'texture-compression-bc'},\n'bc4-r-unorm': {c: 1. s: \"float\", bpp: 8/(4 * 4) f: 'texture-compression-bc'},\n'bc4-r-snorm': {c: 1. s: \"float\", bpp: 8/(4 * 4) f: 'texture-compression-bc'},\n'bc5-rg-unorm': {c: 2. s: \"float\", bpp: 16/(4 * 4) f: 'texture-compression-bc'},\n'bc5-rg-snorm': { },\n'bc6h-rgb-ufloat': {\t16 },\n'bc6h-rgb-float': { },\n'bc7-rgba-unorm': {\t16 },\n'bc7-rgba-unorm-srgb': { },\n\n'etc2-rgb8unorm': {\t8\t\"float\"\t4 × 4\ttexture-compression-etc2 },\n'etc2-rgb8unorm-srgb': { },\n'etc2-rgb8a1unorm': {\t8 },\n'etc2-rgb8a1unorm-srgb': { },\n'etc2-rgba8unorm': {\t16 },\n'etc2-rgba8unorm-srgb': { },\n\n'eac-r11unorm': {\t8 },\n'eac-r11snorm': { },\n'eac-rg11unorm': {\t16 },\n'eac-rg11snorm': { },\n\n'astc-4x4-unorm': {\t16\t\"float\"\t4 × 4\ttexture-compression-astc },\n'astc-4x4-unorm-srgb': { },\n'astc-5x4-unorm': {\t16\t5 × 4 },\n'astc-5x4-unorm-srgb': { },\n'astc-5x5-unorm': {\t16\t5 × 5 },\n'astc-5x5-unorm-srgb': { },\n'astc-6x5-unorm': {\t16\t6 × 5 },\n'astc-6x5-unorm-srgb': { },\n'astc-6x6-unorm': {\t16\t6 × 6 },\n'astc-6x6-unorm-srgb': { },\n'astc-8x5-unorm': {\t16\t8 × 5 },\n'astc-8x5-unorm-srgb': { },\n'astc-8x6-unorm': {\t16\t8 × 6 },\n'astc-8x6-unorm-srgb': { },\n'astc-8x8-unorm': {\t16\t8 × 8 },\n'astc-8x8-unorm-srgb': { },\n'astc-10x5-unorm': {\t16\t10 × 5 },\n'astc-10x5-unorm-srgb': { },\n'astc-10x6-unorm': {\t16\t10 × 6 },\n'astc-10x6-unorm-srgb': { },\n'astc-10x8-unorm': {\t16\t10 × 8 },\n'astc-10x8-unorm-srgb': { },\n'astc-10x10-unorm': {\t16\t10 × 10 },\n'astc-10x10-unorm-srgb': { },\n'astc-12x10-unorm': {\t16\t12 × 10 },\n'astc-12x10-unorm-srgb': { },\n'astc-12x12-unorm': {\t16 },\n*/\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/**\n * Built-in data types that can be used to initialize textures\n * @note ImageData can be used for contiguous 8 bit data via Uint8ClampedArray\n */\nexport type ExternalImage =\n | ImageBitmap\n | ImageData\n | HTMLImageElement\n | HTMLVideoElement\n | VideoFrame\n | HTMLCanvasElement\n | OffscreenCanvas;\n\n/** Check if data is an external image */\nexport function isExternalImage(data: unknown): data is ExternalImage {\n return (\n (typeof ImageData !== 'undefined' && data instanceof ImageData) ||\n (typeof ImageBitmap !== 'undefined' && data instanceof ImageBitmap) ||\n (typeof HTMLImageElement !== 'undefined' && data instanceof HTMLImageElement) ||\n (typeof HTMLVideoElement !== 'undefined' && data instanceof HTMLVideoElement) ||\n (typeof VideoFrame !== 'undefined' && data instanceof VideoFrame) ||\n (typeof HTMLCanvasElement !== 'undefined' && data instanceof HTMLCanvasElement) ||\n (typeof OffscreenCanvas !== 'undefined' && data instanceof OffscreenCanvas)\n );\n}\n\n/** Determine size (width and height) of provided image data */\nexport function getExternalImageSize(data: ExternalImage): {width: number; height: number} {\n if (\n (typeof ImageData !== 'undefined' && data instanceof ImageData) ||\n (typeof ImageBitmap !== 'undefined' && data instanceof ImageBitmap) ||\n (typeof HTMLCanvasElement !== 'undefined' && data instanceof HTMLCanvasElement) ||\n (typeof OffscreenCanvas !== 'undefined' && data instanceof OffscreenCanvas)\n ) {\n return {width: data.width, height: data.height};\n }\n if (typeof HTMLImageElement !== 'undefined' && data instanceof HTMLImageElement) {\n return {width: data.naturalWidth, height: data.naturalHeight};\n }\n if (typeof HTMLVideoElement !== 'undefined' && data instanceof HTMLVideoElement) {\n return {width: data.videoWidth, height: data.videoHeight};\n }\n if (typeof VideoFrame !== 'undefined' && data instanceof VideoFrame) {\n // TODO: is this the right choice for width and height?\n return {width: data.displayWidth, height: data.displayHeight};\n }\n throw new Error('Unknown image type');\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {StatsManager, lumaStats} from '../utils/stats-manager';\nimport {log} from '../utils/log';\nimport {uid} from '../utils/uid';\nimport type {VertexFormat, VertexFormatInfo} from '../shadertypes/vertex-types/vertex-formats';\nimport type {\n TextureFormat,\n TextureFormatInfo,\n CompressedTextureFormat\n} from '../shadertypes/texture-types/texture-formats';\nimport type {CanvasContext, CanvasContextProps} from './canvas-context';\nimport type {PresentationContext, PresentationContextProps} from './presentation-context';\nimport type {BufferProps} from './resources/buffer';\nimport {Buffer} from './resources/buffer';\nimport type {RenderPipeline, RenderPipelineProps} from './resources/render-pipeline';\nimport type {SharedRenderPipeline} from './resources/shared-render-pipeline';\nimport type {ComputePipeline, ComputePipelineProps} from './resources/compute-pipeline';\nimport type {Sampler, SamplerProps} from './resources/sampler';\nimport type {Shader, ShaderProps} from './resources/shader';\nimport type {Texture, TextureProps} from './resources/texture';\nimport type {ExternalTexture, ExternalTextureProps} from './resources/external-texture';\nimport type {Framebuffer, FramebufferProps} from './resources/framebuffer';\nimport type {RenderPass, RenderPassProps} from './resources/render-pass';\nimport type {ComputePass, ComputePassProps} from './resources/compute-pass';\nimport type {CommandEncoder, CommandEncoderProps} from './resources/command-encoder';\nimport type {CommandBuffer} from './resources/command-buffer';\nimport type {VertexArray, VertexArrayProps} from './resources/vertex-array';\nimport type {TransformFeedback, TransformFeedbackProps} from './resources/transform-feedback';\nimport type {QuerySet, QuerySetProps} from './resources/query-set';\nimport type {Fence} from './resources/fence';\nimport type {Bindings, ComputeShaderLayout, ShaderLayout} from './types/shader-layout';\n\nimport {vertexFormatDecoder} from '../shadertypes/vertex-types/vertex-format-decoder';\nimport {textureFormatDecoder} from '../shadertypes/texture-types/texture-format-decoder';\nimport type {ExternalImage} from '../shadertypes/image-types/image-types';\nimport {isExternalImage, getExternalImageSize} from '../shadertypes/image-types/image-types';\nimport {getTextureFormatTable} from '../shadertypes/texture-types/texture-format-table';\n\n/**\n * Identifies the GPU vendor and driver.\n * @note Chrome WebGPU does not provide much information, though more can be enabled with\n * @see https://developer.chrome.com/blog/new-in-webgpu-120#adapter_information_updates\n * chrome://flags/#enable-webgpu-developer-features\n */\nexport type DeviceInfo = {\n /** Type of device */\n type: 'webgl' | 'webgpu' | 'null' | 'unknown';\n /** Vendor (name of GPU vendor, Apple, nVidia etc */\n vendor: string;\n /** Renderer (usually driver name) */\n renderer: string;\n /** version of driver */\n version: string;\n /** family of GPU */\n gpu: 'nvidia' | 'amd' | 'intel' | 'apple' | 'software' | 'unknown';\n /** Type of GPU () */\n gpuType: 'discrete' | 'integrated' | 'cpu' | 'unknown';\n /** GPU architecture */\n gpuArchitecture?: string; // 'common-3' on Apple\n /** GPU driver backend. Can sometimes be sniffed */\n gpuBackend?: 'opengl' | 'opengles' | 'metal' | 'd3d11' | 'd3d12' | 'vulkan' | 'unknown';\n /** If this is a fallback adapter */\n fallback?: boolean;\n /** Shader language supported by device.createShader() */\n shadingLanguage: 'wgsl' | 'glsl';\n /** Highest supported shader language version: GLSL 3.00 = 300, WGSL 1.00 = 100 */\n shadingLanguageVersion: number;\n};\n\n/** Limits for a device (max supported sizes of resources, max number of bindings etc) */\nexport abstract class DeviceLimits {\n /** max number of TextureDimension1D */\n abstract maxTextureDimension1D: number;\n /** max number of TextureDimension2D */\n abstract maxTextureDimension2D: number;\n /** max number of TextureDimension3D */\n abstract maxTextureDimension3D: number;\n /** max number of TextureArrayLayers */\n abstract maxTextureArrayLayers: number;\n /** max number of BindGroups */\n abstract maxBindGroups: number;\n /** max number of DynamicUniformBuffers per PipelineLayout */\n abstract maxDynamicUniformBuffersPerPipelineLayout: number;\n /** max number of DynamicStorageBuffers per PipelineLayout */\n abstract maxDynamicStorageBuffersPerPipelineLayout: number;\n /** max number of SampledTextures per ShaderStage */\n abstract maxSampledTexturesPerShaderStage: number;\n /** max number of Samplers per ShaderStage */\n abstract maxSamplersPerShaderStage: number;\n /** max number of StorageBuffers per ShaderStage */\n abstract maxStorageBuffersPerShaderStage: number;\n /** max number of StorageTextures per ShaderStage */\n abstract maxStorageTexturesPerShaderStage: number;\n /** max number of UniformBuffers per ShaderStage */\n abstract maxUniformBuffersPerShaderStage: number;\n /** max number of UniformBufferBindingSize */\n abstract maxUniformBufferBindingSize: number;\n /** max number of StorageBufferBindingSize */\n abstract maxStorageBufferBindingSize: number;\n /** min UniformBufferOffsetAlignment */\n abstract minUniformBufferOffsetAlignment: number;\n /** min StorageBufferOffsetAlignment */\n abstract minStorageBufferOffsetAlignment: number;\n /** max number of VertexBuffers */\n abstract maxVertexBuffers: number;\n /** max number of VertexAttributes */\n abstract maxVertexAttributes: number;\n /** max number of VertexBufferArrayStride */\n abstract maxVertexBufferArrayStride: number;\n /** max number of InterStageShaderComponents */\n abstract maxInterStageShaderVariables: number;\n /** max number of ComputeWorkgroupStorageSize */\n abstract maxComputeWorkgroupStorageSize: number;\n /** max number of ComputeInvocations per Workgroup */\n abstract maxComputeInvocationsPerWorkgroup: number;\n /** max ComputeWorkgroupSizeX */\n abstract maxComputeWorkgroupSizeX: number;\n /** max ComputeWorkgroupSizeY */\n abstract maxComputeWorkgroupSizeY: number;\n /** max ComputeWorkgroupSizeZ */\n abstract maxComputeWorkgroupSizeZ: number;\n /** max ComputeWorkgroupsPerDimension */\n abstract maxComputeWorkgroupsPerDimension: number;\n}\n\nfunction formatErrorLogArguments(context: unknown, args: unknown[]): unknown[] {\n const formattedContext = formatErrorLogValue(context);\n const formattedArgs = args.map(formatErrorLogValue).filter(arg => arg !== undefined);\n return [formattedContext, ...formattedArgs].filter(arg => arg !== undefined);\n}\n\nfunction formatErrorLogValue(value: unknown): unknown {\n if (value === undefined) {\n return undefined;\n }\n if (\n value === null ||\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ) {\n return value;\n }\n if (value instanceof Error) {\n return value.message;\n }\n if (Array.isArray(value)) {\n return value.map(formatErrorLogValue);\n }\n if (typeof value === 'object') {\n if (hasCustomToString(value)) {\n const stringValue = String(value);\n if (stringValue !== '[object Object]') {\n return stringValue;\n }\n }\n\n if (looksLikeGPUCompilationMessage(value)) {\n return formatGPUCompilationMessage(value);\n }\n\n return value.constructor?.name || 'Object';\n }\n\n return String(value);\n}\n\nfunction hasCustomToString(value: object): boolean {\n return (\n 'toString' in value &&\n typeof value.toString === 'function' &&\n value.toString !== Object.prototype.toString\n );\n}\n\nfunction looksLikeGPUCompilationMessage(value: object): value is {\n message?: unknown;\n type?: unknown;\n lineNum?: unknown;\n linePos?: unknown;\n} {\n return 'message' in value && 'type' in value;\n}\n\nfunction formatGPUCompilationMessage(value: {\n message?: unknown;\n type?: unknown;\n lineNum?: unknown;\n linePos?: unknown;\n}): string {\n const type = typeof value.type === 'string' ? value.type : 'message';\n const message = typeof value.message === 'string' ? value.message : '';\n const lineNum = typeof value.lineNum === 'number' ? value.lineNum : null;\n const linePos = typeof value.linePos === 'number' ? value.linePos : null;\n const location =\n lineNum !== null && linePos !== null\n ? ` @ ${lineNum}:${linePos}`\n : lineNum !== null\n ? ` @ ${lineNum}`\n : '';\n return `${type}${location}: ${message}`.trim();\n}\n\n/** Set-like class for features (lets apps check for WebGL / WebGPU extensions) */\nexport class DeviceFeatures {\n protected features: Set;\n protected disabledFeatures?: Partial>;\n\n constructor(\n features: DeviceFeature[] = [],\n disabledFeatures: Partial>\n ) {\n this.features = new Set(features);\n this.disabledFeatures = disabledFeatures || {};\n }\n\n *[Symbol.iterator](): IterableIterator {\n yield* this.features;\n }\n\n has(feature: DeviceFeature): boolean {\n return !this.disabledFeatures?.[feature] && this.features.has(feature);\n }\n}\n\n/** Device feature names */\nexport type DeviceFeature =\n | WebGPUDeviceFeature\n | WebGLDeviceFeature\n | WebGLCompressedTextureFeatures;\n// | ChromeExperimentalFeatures\n\n/** Chrome-specific extensions. Expected to eventually become standard features. */\n// export type ChromeExperimentalFeatures = ;\n\nexport type WebGPUDeviceFeature =\n | 'depth-clip-control'\n | 'depth32float-stencil8'\n | 'texture-compression-bc'\n | 'texture-compression-bc-sliced-3d'\n | 'texture-compression-etc2'\n | 'texture-compression-astc'\n | 'texture-compression-astc-sliced-3d'\n | 'timestamp-query'\n | 'indirect-first-instance'\n | 'shader-f16'\n | 'rg11b10ufloat-renderable' // Is the rg11b10ufloat texture format renderable?\n | 'bgra8unorm-storage' // Can the bgra8unorm texture format be used in storage buffers?\n | 'float32-filterable' // Is the float32 format filterable?\n | 'float32-blendable' // Is the float32 format blendable?\n | 'clip-distances'\n | 'dual-source-blending'\n | 'subgroups';\n// | 'depth-clamping' // removed from the WebGPU spec...\n// | 'pipeline-statistics-query' // removed from the WebGPU spec...\n\nexport type WebGLDeviceFeature =\n // webgl extension features\n | 'compilation-status-async-webgl' // Non-blocking shader compile/link status query available\n | 'provoking-vertex-webgl' // parameters.provokingVertex\n | 'polygon-mode-webgl' // parameters.polygonMode and parameters.polygonOffsetLine\n\n // GLSL extension features\n | 'shader-noperspective-interpolation-webgl' // Vertex outputs & fragment inputs can have a `noperspective` interpolation qualifier.\n | 'shader-conservative-depth-webgl' // GLSL `gl_FragDepth` qualifiers `depth_unchanged` etc can enable early depth test\n | 'shader-clip-cull-distance-webgl' // Makes gl_ClipDistance and gl_CullDistance available in shaders\n\n // texture rendering\n | 'float32-renderable-webgl'\n | 'float16-renderable-webgl'\n | 'rgb9e5ufloat-renderable-webgl'\n | 'snorm8-renderable-webgl'\n | 'norm16-webgl'\n | 'norm16-renderable-webgl'\n | 'snorm16-renderable-webgl'\n\n // texture filtering\n | 'float16-filterable-webgl'\n | 'texture-filterable-anisotropic-webgl'\n\n // texture storage bindings\n | 'bgra8unorm-storage'\n\n // texture blending\n | 'texture-blend-float-webgl';\n\ntype WebGLCompressedTextureFeatures =\n | 'texture-compression-bc5-webgl'\n | 'texture-compression-bc7-webgl'\n | 'texture-compression-etc1-webgl'\n | 'texture-compression-pvrtc-webgl'\n | 'texture-compression-atc-webgl';\n\n/** Texture format capabilities that have been checked against a specific device */\nexport type DeviceTextureFormatCapabilities = {\n format: TextureFormat;\n /** Can the format be created and sampled?*/\n create: boolean;\n /** Is the format renderable. */\n render: boolean;\n /** Is the format filterable. */\n filter: boolean;\n /** Is the format blendable. */\n blend: boolean;\n /** Is the format storeable. */\n store: boolean;\n};\n\n/** Device properties */\nexport type DeviceProps = {\n /** string id for debugging. Stored on the object, used in logging and set on underlying GPU objects when feasible. */\n id?: string;\n /** Properties for creating a default canvas context */\n createCanvasContext?: CanvasContextProps | true;\n /** Control which type of GPU is preferred on systems with both integrated and discrete GPU. Defaults to \"high-performance\" / discrete GPU. */\n powerPreference?: 'default' | 'high-performance' | 'low-power';\n /** Hints that device creation should fail if no hardware GPU is available (if the system performance is \"low\"). */\n failIfMajorPerformanceCaveat?: boolean;\n\n /** WebGL specific: Properties passed through to WebGL2RenderingContext creation: `canvas.getContext('webgl2', props.webgl)` */\n webgl?: WebGLContextProps;\n\n // CALLBACKS\n\n /** Error handler. If it returns a probe logger style function, it will be called at the site of the error to optimize console error links. */\n onError?: (error: Error, context?: unknown) => unknown;\n /** Called when the size of a CanvasContext's canvas changes */\n onResize?: (\n ctx: CanvasContext | PresentationContext,\n info: {oldPixelSize: [number, number]}\n ) => unknown;\n /** Called when the absolute position of a CanvasContext's canvas changes. Must set `CanvasContextProps.trackPosition: true` */\n onPositionChange?: (\n ctx: CanvasContext | PresentationContext,\n info: {oldPosition: [number, number]}\n ) => unknown;\n /** Called when the visibility of a CanvasContext's canvas changes */\n onVisibilityChange?: (ctx: CanvasContext | PresentationContext) => unknown;\n /** Called when the device pixel ratio of a CanvasContext's canvas changes */\n onDevicePixelRatioChange?: (\n ctx: CanvasContext | PresentationContext,\n info: {oldRatio: number}\n ) => unknown;\n\n // DEBUG SETTINGS\n\n /** Turn on implementation defined checks that slow down execution but help break where errors occur */\n debug?: boolean;\n /** Enable GPU timestamp collection without enabling all debug validation paths. */\n debugGPUTime?: boolean;\n /** Show shader source in browser? The default is `'error'`, meaning that logs are shown when shader compilation has errors */\n debugShaders?: 'never' | 'errors' | 'warnings' | 'always';\n /** Renders a small version of updated Framebuffers into the primary canvas context. Can be set in console luma.log.set('debug-framebuffers', true) */\n debugFramebuffers?: boolean;\n /** Traces resource caching, reuse, and destroys in the PipelineFactory */\n debugFactories?: boolean;\n /** WebGL specific - Trace WebGL calls (instruments WebGL2RenderingContext at the expense of performance). Can be set in console luma.log.set('debug-webgl', true) */\n debugWebGL?: boolean;\n /** WebGL specific - Initialize the SpectorJS WebGL debugger. Can be set in console luma.log.set('debug-spectorjs', true) */\n debugSpectorJS?: boolean;\n /** WebGL specific - SpectorJS URL. Override if CDN is down or different SpectorJS version is desired. */\n debugSpectorJSUrl?: string;\n\n // EXPERIMENTAL SETTINGS - subject to change\n\n /** adapter.create() returns the existing Device if the provided canvas' WebGL context is already associated with a Device. */\n _reuseDevices?: boolean;\n /** WebGPU specific - Request a Device with the highest limits supported by platform. On WebGPU devices can be created with minimal limits. */\n _requestMaxLimits?: boolean;\n /** Disable specific features */\n _disabledFeatures?: Partial>;\n /** WebGL specific - Initialize all features on startup */\n _initializeFeatures?: boolean;\n /** Enable shader caching (via ShaderFactory) */\n _cacheShaders?: boolean;\n /**\n * Destroy cached shaders when they become unused.\n * Defaults to `false` so repeated create/destroy cycles can still reuse cached shaders.\n * Enable this if the application creates very large numbers of distinct shaders and needs cache eviction.\n */\n _destroyShaders?: boolean;\n /** Enable pipeline caching (via PipelineFactory) */\n _cachePipelines?: boolean;\n /** Enable sharing of backend render-pipeline implementations when caching is enabled. Currently used by WebGL. */\n _sharePipelines?: boolean;\n /**\n * Destroy cached pipelines when they become unused.\n * Defaults to `false` so repeated create/destroy cycles can still reuse cached pipelines.\n * Enable this if the application creates very large numbers of distinct pipelines and needs cache eviction.\n */\n _destroyPipelines?: boolean;\n\n /** @deprecated Internal, Do not use directly! Use `luma.attachDevice()` to attach to pre-created contexts/devices. */\n _handle?: unknown; // WebGL2RenderingContext | GPUDevice | null;\n};\n\ntype DeviceFactories = {\n bindGroupFactory?: unknown;\n};\n\n/** WebGL independent copy of WebGLContextAttributes */\ntype WebGLContextProps = {\n /** indicates if the canvas contains an alpha buffer. */\n alpha?: boolean;\n /** hints the user agent to reduce the latency by desynchronizing the canvas paint cycle from the event loop */\n desynchronized?: boolean;\n /** indicates whether or not to perform anti-aliasing. */\n antialias?: boolean;\n /** indicates that the render target has a stencil buffer of at least `8` bits. */\n stencil?: boolean;\n /** indicates that the drawing buffer has a depth buffer of at least 16 bits. */\n depth?: boolean;\n /** indicates if a context will be created if the system performance is low or if no hardware GPU is available. */\n failIfMajorPerformanceCaveat?: boolean;\n /** Selects GPU */\n powerPreference?: 'default' | 'high-performance' | 'low-power';\n /** page compositor will assume the drawing buffer contains colors with pre-multiplied alpha. */\n premultipliedAlpha?: boolean;\n /** buffers will not be cleared and will preserve their values until cleared or overwritten by the author. */\n preserveDrawingBuffer?: boolean;\n};\n\n/**\n * Create and attach devices for a specific backend. Currently static methods on each device\n */\nexport interface DeviceFactory {\n // new (props: DeviceProps): Device; Constructor isn't used\n type: string;\n isSupported(): boolean;\n create(props: DeviceProps): Promise;\n attach?(handle: unknown): Device;\n}\n\n/**\n * WebGPU Device/WebGL context abstraction\n */\nexport abstract class Device {\n static defaultProps: Required = {\n id: null!,\n powerPreference: 'high-performance',\n failIfMajorPerformanceCaveat: false,\n createCanvasContext: undefined!,\n // WebGL specific\n webgl: {},\n\n // Callbacks\n // eslint-disable-next-line handle-callback-err\n onError: (error: Error, context: unknown) => {},\n onResize: (context: CanvasContext, info: {oldPixelSize: [number, number]}) => {\n const [width, height] = context.getDevicePixelSize();\n log.log(1, `${context} resized => ${width}x${height}px`)();\n },\n onPositionChange: (context: CanvasContext, info: {oldPosition: [number, number]}) => {\n const [left, top] = context.getPosition();\n log.log(1, `${context} repositioned => ${left},${top}`)();\n },\n onVisibilityChange: (context: CanvasContext) =>\n log.log(1, `${context} Visibility changed ${context.isVisible}`)(),\n onDevicePixelRatioChange: (context: CanvasContext, info: {oldRatio: number}) =>\n log.log(1, `${context} DPR changed ${info.oldRatio} => ${context.devicePixelRatio}`)(),\n\n // Debug flags\n debug: getDefaultDebugValue(),\n debugGPUTime: false,\n debugShaders: log.get('debug-shaders') || undefined!,\n debugFramebuffers: Boolean(log.get('debug-framebuffers')),\n debugFactories: Boolean(log.get('debug-factories')),\n debugWebGL: Boolean(log.get('debug-webgl')),\n debugSpectorJS: undefined!, // Note: log setting is queried by the spector.js code\n debugSpectorJSUrl: undefined!,\n\n // Experimental\n _reuseDevices: false,\n _requestMaxLimits: true,\n _cacheShaders: true,\n _destroyShaders: false,\n _cachePipelines: true,\n _sharePipelines: true,\n _destroyPipelines: false,\n // TODO - Change these after confirming things work as expected\n _initializeFeatures: true,\n _disabledFeatures: {\n 'compilation-status-async-webgl': true\n },\n\n // INTERNAL\n _handle: undefined!\n };\n\n get [Symbol.toStringTag](): string {\n return 'Device';\n }\n\n toString(): string {\n return `Device(${this.id})`;\n }\n\n /** id of this device, primarily for debugging */\n readonly id: string;\n /** type of this device */\n abstract readonly type: 'webgl' | 'webgpu' | 'null' | 'unknown';\n abstract readonly handle: unknown;\n abstract commandEncoder: CommandEncoder;\n\n /** A copy of the device props */\n readonly props: Required;\n /** Available for the application to store data on the device */\n userData: {[key: string]: unknown} = {};\n /** stats */\n readonly statsManager: StatsManager = lumaStats;\n /** Internal per-device factory storage */\n _factories: DeviceFactories = {};\n /** An abstract timestamp used for change tracking */\n timestamp: number = 0;\n\n /** True if this device has been reused during device creation (app has multiple references) */\n _reused: boolean = false;\n /** Used by other luma.gl modules to store data on the device */\n private _moduleData: Record> = {};\n\n // Capabilities\n\n /** Information about the device (vendor, versions etc) */\n abstract info: DeviceInfo;\n /** Optional capability discovery */\n abstract features: DeviceFeatures;\n /** WebGPU style device limits */\n abstract get limits(): DeviceLimits;\n\n // Texture helpers\n\n /** Optimal TextureFormat for displaying 8-bit depth, standard dynamic range content on this system. */\n abstract preferredColorFormat: 'rgba8unorm' | 'bgra8unorm';\n /** Default depth format used on this system */\n abstract preferredDepthFormat: 'depth16' | 'depth24plus' | 'depth32float';\n\n protected _textureCaps: Partial> = {};\n /** Internal timestamp query set used when GPU timing collection is enabled for this device. */\n protected _debugGPUTimeQuery: QuerySet | null = null;\n\n constructor(props: DeviceProps) {\n this.props = {...Device.defaultProps, ...props};\n this.id = this.props.id || uid(this[Symbol.toStringTag].toLowerCase());\n }\n\n abstract destroy(): void;\n\n // TODO - just expose the shadertypes decoders?\n\n getVertexFormatInfo(format: VertexFormat): VertexFormatInfo {\n return vertexFormatDecoder.getVertexFormatInfo(format);\n }\n\n isVertexFormatSupported(format: VertexFormat): boolean {\n return true;\n }\n\n /** Returns information about a texture format, such as data type, channels, bits per channel, compression etc */\n getTextureFormatInfo(format: TextureFormat): TextureFormatInfo {\n return textureFormatDecoder.getInfo(format);\n }\n\n /** Determines what operations are supported on a texture format on this particular device (checks against supported device features) */\n getTextureFormatCapabilities(format: TextureFormat): DeviceTextureFormatCapabilities {\n let textureCaps = this._textureCaps[format];\n if (!textureCaps) {\n const capabilities = this._getDeviceTextureFormatCapabilities(format);\n textureCaps = this._getDeviceSpecificTextureFormatCapabilities(capabilities);\n this._textureCaps[format] = textureCaps;\n }\n return textureCaps;\n }\n\n /** Calculates the number of mip levels for a texture of width, height and in case of 3d textures only, depth */\n getMipLevelCount(width: number, height: number, depth3d: number = 1): number {\n const maxSize = Math.max(width, height, depth3d);\n return 1 + Math.floor(Math.log2(maxSize));\n }\n\n /** Check if data is an external image */\n isExternalImage(data: unknown): data is ExternalImage {\n return isExternalImage(data);\n }\n\n /** Get the size of an external image */\n getExternalImageSize(data: ExternalImage): {width: number; height: number} {\n return getExternalImageSize(data);\n }\n\n /** Check if device supports a specific texture format (creation and `nearest` sampling) */\n isTextureFormatSupported(format: TextureFormat): boolean {\n return this.getTextureFormatCapabilities(format).create;\n }\n\n /** Check if linear filtering (sampler interpolation) is supported for a specific texture format */\n isTextureFormatFilterable(format: TextureFormat): boolean {\n return this.getTextureFormatCapabilities(format).filter;\n }\n\n /** Check if device supports rendering to a framebuffer color attachment of a specific texture format */\n isTextureFormatRenderable(format: TextureFormat): boolean {\n return this.getTextureFormatCapabilities(format).render;\n }\n\n /** Check if a specific texture format is GPU compressed */\n isTextureFormatCompressed(format: TextureFormat): boolean {\n return textureFormatDecoder.isCompressed(format);\n }\n\n /** Returns the compressed texture formats that can be created and sampled on this device */\n getSupportedCompressedTextureFormats(): CompressedTextureFormat[] {\n const supportedFormats: CompressedTextureFormat[] = [];\n\n for (const format of Object.keys(getTextureFormatTable()) as TextureFormat[]) {\n if (this.isTextureFormatCompressed(format) && this.isTextureFormatSupported(format)) {\n supportedFormats.push(format as CompressedTextureFormat);\n }\n }\n\n return supportedFormats;\n }\n\n // DEBUG METHODS\n\n pushDebugGroup(groupLabel: string): void {\n this.commandEncoder.pushDebugGroup(groupLabel);\n }\n\n popDebugGroup(): void {\n this.commandEncoder?.popDebugGroup();\n }\n\n insertDebugMarker(markerLabel: string): void {\n this.commandEncoder?.insertDebugMarker(markerLabel);\n }\n\n // Device loss\n\n /** `true` if device is already lost */\n abstract get isLost(): boolean;\n\n /** Promise that resolves when device is lost */\n abstract readonly lost: Promise<{reason: 'destroyed'; message: string}>;\n\n /**\n * Trigger device loss.\n * @returns `true` if context loss could actually be triggered.\n * @note primarily intended for testing how application reacts to device loss\n */\n loseDevice(): boolean {\n return false;\n }\n\n /** A monotonic counter for tracking buffer and texture updates */\n incrementTimestamp(): number {\n return this.timestamp++;\n }\n\n /**\n * Reports Device errors in a way that optimizes for developer experience / debugging.\n * - Logs so that the console error links directly to the source code that generated the error.\n * - Includes the object that reported the error in the log message, even if the error is asynchronous.\n *\n * Conventions when calling reportError():\n * - Always call the returned function - to ensure error is logged, at the error site\n * - Follow with a call to device.debug() - to ensure that the debugger breaks at the error site\n *\n * @param error - the error to report. If needed, just create a new Error object with the appropriate message.\n * @param context - pass `this` as context, otherwise it may not be available in the debugger for async errors.\n * @returns the logger function returned by device.props.onError() so that it can be called from the error site.\n *\n * @example\n * device.reportError(new Error(...), this)();\n * device.debug();\n */\n reportError(error: Error, context: unknown, ...args: unknown[]): () => unknown {\n // Call the error handler\n const isHandled = this.props.onError(error, context);\n if (!isHandled) {\n const logArguments = formatErrorLogArguments(context, args);\n // Note: Returns a function that must be called: `device.reportError(...)()`\n return log.error(\n this.type === 'webgl' ? '%cWebGL' : '%cWebGPU',\n 'color: white; background: red; padding: 2px 6px; border-radius: 3px;',\n error.message,\n ...logArguments\n );\n }\n return () => {};\n }\n\n /** Break in the debugger - if device.props.debug is true */\n debug(): void {\n if (this.props.debug) {\n // @ts-ignore\n // biome-ignore lint/suspicious/noDebugger: explicit debug break when device debugging is enabled.\n debugger;\n } else {\n // TODO(ibgreen): Does not appear to be printed in the console\n const message = `\\\n'Type luma.log.set({debug: true}) in console to enable debug breakpoints',\nor create a device with the 'debug: true' prop.`;\n log.once(0, message)();\n }\n }\n\n // Canvas context\n\n /** Default / primary canvas context. Can be null as WebGPU devices can be created without a CanvasContext */\n abstract canvasContext: CanvasContext | null;\n\n /** Returns the default / primary canvas context. Throws an error if no canvas context is available (a WebGPU compute device) */\n getDefaultCanvasContext(): CanvasContext {\n if (!this.canvasContext) {\n throw new Error('Device has no default CanvasContext. See props.createCanvasContext');\n }\n return this.canvasContext;\n }\n\n /** Creates a new CanvasContext (WebGPU only) */\n abstract createCanvasContext(props?: CanvasContextProps): CanvasContext;\n\n /** Creates a presentation context for a destination canvas. WebGL requires the default canvas context to use an OffscreenCanvas. */\n abstract createPresentationContext(props?: PresentationContextProps): PresentationContext;\n\n /** Call after rendering a frame (necessary e.g. on WebGL OffscreenCanvas) */\n abstract submit(commandBuffer?: CommandBuffer): void;\n\n // Resource creation\n\n /** Create a buffer */\n abstract createBuffer(props: BufferProps | ArrayBuffer | ArrayBufferView): Buffer;\n\n /** Create a texture */\n abstract createTexture(props: TextureProps): Texture;\n\n /** Create a temporary texture view of a video source */\n abstract createExternalTexture(props: ExternalTextureProps): ExternalTexture;\n\n /** Create a sampler */\n abstract createSampler(props: SamplerProps): Sampler;\n\n /** Create a Framebuffer. Must have at least one attachment. */\n abstract createFramebuffer(props: FramebufferProps): Framebuffer;\n\n /** Create a shader */\n abstract createShader(props: ShaderProps): Shader;\n\n /** Create a render pipeline (aka program) */\n abstract createRenderPipeline(props: RenderPipelineProps): RenderPipeline;\n\n /** Create a compute pipeline (aka program). WebGPU only. */\n abstract createComputePipeline(props: ComputePipelineProps): ComputePipeline;\n\n /** Create a vertex array */\n abstract createVertexArray(props: VertexArrayProps): VertexArray;\n\n abstract createCommandEncoder(props?: CommandEncoderProps): CommandEncoder;\n\n /** Create a transform feedback (immutable set of output buffer bindings). WebGL only. */\n abstract createTransformFeedback(props: TransformFeedbackProps): TransformFeedback;\n\n abstract createQuerySet(props: QuerySetProps): QuerySet;\n\n /** Create a fence sync object */\n createFence(): Fence {\n throw new Error('createFence() not implemented');\n }\n\n /** Create a RenderPass using the default CommandEncoder */\n beginRenderPass(props?: RenderPassProps): RenderPass {\n return this.commandEncoder.beginRenderPass(props);\n }\n\n /** Create a ComputePass using the default CommandEncoder*/\n beginComputePass(props?: ComputePassProps): ComputePass {\n return this.commandEncoder.beginComputePass(props);\n }\n\n /**\n * Generate mipmaps for a WebGPU texture.\n * WebGPU textures must be created up front with the required mip count, usage flags, and a format that supports the chosen generation path.\n * WebGL uses `Texture.generateMipmapsWebGL()` directly because the backend manages mip generation on the texture object itself.\n */\n generateMipmapsWebGPU(_texture: Texture): void {\n throw new Error('not implemented');\n }\n\n /** Internal helper for creating a shareable WebGL render-pipeline implementation. */\n _createSharedRenderPipelineWebGL(_props: RenderPipelineProps): SharedRenderPipeline {\n throw new Error('_createSharedRenderPipelineWebGL() not implemented');\n }\n\n /** Internal WebGPU-only helper for retrieving the native bind-group layout for a pipeline group. */\n _createBindGroupLayoutWebGPU(\n _pipeline: RenderPipeline | ComputePipeline,\n _group: number\n ): unknown {\n throw new Error('_createBindGroupLayoutWebGPU() not implemented');\n }\n\n /** Internal WebGPU-only helper for creating a native bind group. */\n _createBindGroupWebGPU(\n _bindGroupLayout: unknown,\n _shaderLayout: ShaderLayout | ComputeShaderLayout,\n _bindings: Bindings,\n _group: number,\n _label?: string\n ): unknown {\n throw new Error('_createBindGroupWebGPU() not implemented');\n }\n\n /**\n * Internal helper that returns `true` when timestamp-query GPU timing should be\n * collected for this device.\n */\n _supportsDebugGPUTime(): boolean {\n return (\n this.features.has('timestamp-query') && Boolean(this.props.debug || this.props.debugGPUTime)\n );\n }\n\n /**\n * Internal helper that enables device-managed GPU timing collection on the\n * default command encoder. Reuses the existing query set if timing is already enabled.\n *\n * @param queryCount - Number of timestamp slots reserved for profiled passes.\n * @returns The device-managed timestamp QuerySet, or `null` when timing is not supported or could not be enabled.\n */\n _enableDebugGPUTime(queryCount: number = 256): QuerySet | null {\n if (!this._supportsDebugGPUTime()) {\n return null;\n }\n\n if (this._debugGPUTimeQuery) {\n return this._debugGPUTimeQuery;\n }\n\n try {\n this._debugGPUTimeQuery = this.createQuerySet({type: 'timestamp', count: queryCount});\n this.commandEncoder = this.createCommandEncoder({\n id: this.commandEncoder.props.id,\n timeProfilingQuerySet: this._debugGPUTimeQuery\n });\n } catch {\n this._debugGPUTimeQuery = null;\n }\n\n return this._debugGPUTimeQuery;\n }\n\n /**\n * Internal helper that disables device-managed GPU timing collection and restores\n * the default command encoder to an unprofiled state.\n */\n _disableDebugGPUTime(): void {\n if (!this._debugGPUTimeQuery) {\n return;\n }\n\n if (this.commandEncoder.getTimeProfilingQuerySet() === this._debugGPUTimeQuery) {\n this.commandEncoder = this.createCommandEncoder({\n id: this.commandEncoder.props.id\n });\n }\n\n this._debugGPUTimeQuery.destroy();\n this._debugGPUTimeQuery = null;\n }\n\n /** Internal helper that returns `true` when device-managed GPU timing is currently active. */\n _isDebugGPUTimeEnabled(): boolean {\n return this._debugGPUTimeQuery !== null;\n }\n\n /**\n * Determines what operations are supported on a texture format, checking against supported device features\n * Subclasses override to apply additional checks\n */\n protected abstract _getDeviceSpecificTextureFormatCapabilities(\n format: DeviceTextureFormatCapabilities\n ): DeviceTextureFormatCapabilities;\n\n // DEPRECATED METHODS\n\n /** @deprecated Use getDefaultCanvasContext() */\n getCanvasContext(): CanvasContext {\n return this.getDefaultCanvasContext();\n }\n\n // WebGL specific HACKS - enables app to remove webgl import\n // Use until we have a better way to handle these\n\n /** @deprecated - will be removed - should use command encoder */\n readPixelsToArrayWebGL(\n source: Framebuffer | Texture,\n options?: {\n sourceX?: number;\n sourceY?: number;\n sourceFormat?: number;\n sourceAttachment?: number;\n target?: Uint8Array | Uint16Array | Float32Array;\n // following parameters are auto deduced if not provided\n sourceWidth?: number;\n sourceHeight?: number;\n sourceType?: number;\n }\n ): Uint8Array | Uint16Array | Float32Array {\n throw new Error('not implemented');\n }\n\n /** @deprecated - will be removed - should use command encoder */\n readPixelsToBufferWebGL(\n source: Framebuffer | Texture,\n options?: {\n sourceX?: number;\n sourceY?: number;\n sourceFormat?: number;\n target?: Buffer; // A new Buffer object is created when not provided.\n targetByteOffset?: number; // byte offset in buffer object\n // following parameters are auto deduced if not provided\n sourceWidth?: number;\n sourceHeight?: number;\n sourceType?: number;\n }\n ): Buffer {\n throw new Error('not implemented');\n }\n\n /** @deprecated - will be removed - should use WebGPU parameters (pipeline) */\n setParametersWebGL(parameters: any): void {\n throw new Error('not implemented');\n }\n\n /** @deprecated - will be removed - should use WebGPU parameters (pipeline) */\n getParametersWebGL(parameters: any): void {\n throw new Error('not implemented');\n }\n\n /** @deprecated - will be removed - should use WebGPU parameters (pipeline) */\n withParametersWebGL(parameters: any, func: any): any {\n throw new Error('not implemented');\n }\n\n /** @deprecated - will be removed - should use clear arguments in RenderPass */\n clearWebGL(options?: {framebuffer?: Framebuffer; color?: any; depth?: any; stencil?: any}): void {\n throw new Error('not implemented');\n }\n\n /** @deprecated - will be removed - should use for debugging only */\n resetWebGL(): void {\n throw new Error('not implemented');\n }\n\n // INTERNAL LUMA.GL METHODS\n\n getModuleData>(moduleName: string): ModuleDataT {\n this._moduleData[moduleName] ||= {};\n return this._moduleData[moduleName] as ModuleDataT;\n }\n\n // INTERNAL HELPERS\n\n // IMPLEMENTATION\n\n /** Helper to get the canvas context props */\n static _getCanvasContextProps(props: DeviceProps): CanvasContextProps | undefined {\n return props.createCanvasContext === true ? {} : props.createCanvasContext;\n }\n\n protected _getDeviceTextureFormatCapabilities(\n format: TextureFormat\n ): DeviceTextureFormatCapabilities {\n const genericCapabilities = textureFormatDecoder.getCapabilities(format);\n\n // Check standard features\n const checkFeature = (feature: DeviceFeature | boolean | undefined) =>\n (typeof feature === 'string' ? this.features.has(feature) : feature) ?? true;\n\n const supported = checkFeature(genericCapabilities.create);\n return {\n format,\n create: supported,\n render: supported && checkFeature(genericCapabilities.render),\n filter: supported && checkFeature(genericCapabilities.filter),\n blend: supported && checkFeature(genericCapabilities.blend),\n store: supported && checkFeature(genericCapabilities.store)\n } as const satisfies DeviceTextureFormatCapabilities;\n }\n\n /** Subclasses use this to support .createBuffer() overloads */\n protected _normalizeBufferProps(props: BufferProps | ArrayBuffer | ArrayBufferView): BufferProps {\n if (props instanceof ArrayBuffer || ArrayBuffer.isView(props)) {\n props = {data: props};\n }\n\n // TODO(ibgreen) - fragile, as this is done before we merge with default options\n // inside the Buffer constructor\n\n const newProps = {...props};\n // Deduce indexType\n const usage = props.usage || 0;\n if (usage & Buffer.INDEX) {\n if (!props.indexType) {\n if (props.data instanceof Uint32Array) {\n newProps.indexType = 'uint32';\n } else if (props.data instanceof Uint16Array) {\n newProps.indexType = 'uint16';\n } else if (props.data instanceof Uint8Array) {\n // Convert uint8 to uint16 for WebGPU compatibility (WebGPU doesn't support uint8 indices)\n newProps.data = new Uint16Array(props.data);\n newProps.indexType = 'uint16';\n }\n }\n if (!newProps.indexType) {\n throw new Error('indices buffer content must be of type uint16 or uint32');\n }\n }\n\n return newProps;\n }\n}\n\n/**\n * Internal helper for resolving the default `debug` prop.\n * Precedence is: explicit log debug value first, then `NODE_ENV`, then `false`.\n */\nexport function _getDefaultDebugValue(logDebugValue: unknown, nodeEnv?: string): boolean {\n if (logDebugValue !== undefined && logDebugValue !== null) {\n return Boolean(logDebugValue);\n }\n\n if (nodeEnv !== undefined) {\n return nodeEnv !== 'production';\n }\n\n return false;\n}\n\nfunction getDefaultDebugValue(): boolean {\n return _getDefaultDebugValue(log.get('debug'), getNodeEnv());\n}\n\nfunction getNodeEnv(): string | undefined {\n const processObject = (\n globalThis as typeof globalThis & {\n process?: {env?: Record};\n }\n ).process;\n if (!processObject?.env) {\n return undefined;\n }\n\n return processObject.env['NODE_ENV'];\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Log} from '@probe.gl/log';\nimport type {DeviceProps} from './device';\nimport {Device} from './device';\nimport {Adapter} from './adapter';\nimport {StatsManager, lumaStats} from '../utils/stats-manager';\nimport {log} from '../utils/log';\n\ndeclare global {\n // eslint-disable-next-line no-var\n var luma: Luma;\n}\n\nconst STARTUP_MESSAGE = 'set luma.log.level=1 (or higher) to trace rendering';\n\nconst ERROR_MESSAGE =\n 'No matching device found. Ensure `@luma.gl/webgl` and/or `@luma.gl/webgpu` modules are imported.';\n\n/** Properties for creating a new device */\nexport type CreateDeviceProps = {\n /** Selects the type of device. `best-available` uses webgpu if available, then webgl. */\n type?: 'webgl' | 'webgpu' | 'null' | 'unknown' | 'best-available';\n /** List of adapters. Will also search any pre-registered adapters */\n adapters?: Adapter[];\n /**\n * Whether to wait for page to be loaded so that CanvasContext's can access the DOM.\n * The browser only supports one 'load' event listener so it may be necessary for the application to set this to false to avoid conflicts.\n */\n waitForPageLoad?: boolean;\n} & DeviceProps;\n\n/** Properties for attaching an existing WebGL context or WebGPU device to a new luma Device */\nexport type AttachDeviceProps = {\n /** List of adapters. Will also search any pre-registered adapters */\n adapters?: Adapter[];\n} & DeviceProps;\n\n/**\n * Entry point to the luma.gl GPU abstraction\n * Register WebGPU and/or WebGL adapters (controls application bundle size)\n * Run-time selection of the first available Device\n */\nexport class Luma {\n static defaultProps: Required = {\n ...Device.defaultProps,\n type: 'best-available',\n adapters: undefined!,\n waitForPageLoad: true\n };\n\n /** Global stats for all devices */\n readonly stats: StatsManager = lumaStats;\n\n /**\n * Global log\n *\n * Assign luma.log.level in console to control logging: \\\n * 0: none, 1: minimal, 2: verbose, 3: attribute/uniforms, 4: gl logs\n * luma.log.break[], set to gl funcs, luma.log.profile[] set to model names`;\n */\n readonly log: Log = log;\n\n /** Version of luma.gl */\n readonly VERSION: string =\n // Version detection using build plugin\n // @ts-expect-error no-undef\n typeof __VERSION__ !== 'undefined' ? __VERSION__ : 'running from source';\n\n spector: unknown;\n\n protected preregisteredAdapters = new Map();\n\n constructor() {\n if (globalThis.luma) {\n if (globalThis.luma.VERSION !== this.VERSION) {\n log.error(`Found luma.gl ${globalThis.luma.VERSION} while initialzing ${this.VERSION}`)();\n log.error(`'yarn why @luma.gl/core' can help identify the source of the conflict`)();\n throw new Error(`luma.gl - multiple versions detected: see console log`);\n }\n\n log.error('This version of luma.gl has already been initialized')();\n }\n\n log.log(1, `${this.VERSION} - ${STARTUP_MESSAGE}`)();\n\n globalThis.luma = this;\n }\n\n /** Creates a device. Asynchronously. */\n async createDevice(props_: CreateDeviceProps = {}): Promise {\n const props: Required = {...Luma.defaultProps, ...props_};\n\n const adapter = this.selectAdapter(props.type, props.adapters);\n if (!adapter) {\n throw new Error(ERROR_MESSAGE);\n }\n\n // Wait for page to load so that CanvasContext's can access the DOM.\n if (props.waitForPageLoad) {\n await adapter.pageLoaded;\n }\n\n return await adapter.create(props);\n }\n\n /**\n * Attach to an existing GPU API handle (WebGL2RenderingContext or GPUDevice).\n * @param handle Externally created WebGL context or WebGPU device\n */\n async attachDevice(handle: unknown, props: AttachDeviceProps): Promise {\n const type = this._getTypeFromHandle(handle, props.adapters);\n\n const adapter = type && this.selectAdapter(type, props.adapters);\n if (!adapter) {\n throw new Error(ERROR_MESSAGE);\n }\n\n return await adapter?.attach?.(handle, props);\n }\n\n /**\n * Global adapter registration.\n * @deprecated Use props.adapters instead\n */\n registerAdapters(adapters: Adapter[]): void {\n for (const deviceClass of adapters) {\n this.preregisteredAdapters.set(deviceClass.type, deviceClass);\n }\n }\n\n /** Get type strings for supported Devices */\n getSupportedAdapters(adapters: Adapter[] = []): string[] {\n const adapterMap = this._getAdapterMap(adapters);\n return Array.from(adapterMap)\n .map(([, adapter]) => adapter)\n .filter(adapter => adapter.isSupported?.())\n .map(adapter => adapter.type);\n }\n\n /** Get type strings for best available Device */\n getBestAvailableAdapterType(adapters: Adapter[] = []): 'webgpu' | 'webgl' | 'null' | null {\n const KNOWN_ADAPTERS: ('webgpu' | 'webgl' | 'null')[] = ['webgpu', 'webgl', 'null'];\n const adapterMap = this._getAdapterMap(adapters);\n for (const type of KNOWN_ADAPTERS) {\n if (adapterMap.get(type)?.isSupported?.()) {\n return type;\n }\n }\n return null;\n }\n\n /** Select adapter of type from registered adapters */\n selectAdapter(type: string, adapters: Adapter[] = []): Adapter | null {\n let selectedType: string | null = type;\n if (type === 'best-available') {\n selectedType = this.getBestAvailableAdapterType(adapters);\n }\n\n const adapterMap = this._getAdapterMap(adapters);\n return (selectedType && adapterMap.get(selectedType)) || null;\n }\n\n /**\n * Override `HTMLCanvasContext.getCanvas()` to always create WebGL2 contexts with additional WebGL1 compatibility.\n * Useful when attaching luma to a context from an external library does not support creating WebGL2 contexts.\n */\n enforceWebGL2(enforce: boolean = true, adapters: Adapter[] = []): void {\n const adapterMap = this._getAdapterMap(adapters);\n const webgl2Adapter = adapterMap.get('webgl');\n if (!webgl2Adapter) {\n log.warn('enforceWebGL2: webgl adapter not found')();\n }\n (webgl2Adapter as any)?.enforceWebGL2?.(enforce);\n }\n\n // DEPRECATED\n\n /** @deprecated */\n setDefaultDeviceProps(props: CreateDeviceProps): void {\n Object.assign(Luma.defaultProps, props);\n }\n\n // HELPERS\n\n /** Convert a list of adapters to a map */\n protected _getAdapterMap(adapters: Adapter[] = []): Map {\n const map = new Map(this.preregisteredAdapters);\n for (const adapter of adapters) {\n map.set(adapter.type, adapter);\n }\n return map;\n }\n\n /** Get type of a handle (for attachDevice) */\n protected _getTypeFromHandle(\n handle: unknown,\n adapters: Adapter[] = []\n ): 'webgpu' | 'webgl' | 'null' | null {\n // TODO - delegate handle identification to adapters\n\n // WebGL\n if (handle instanceof WebGL2RenderingContext) {\n return 'webgl';\n }\n\n if (typeof GPUDevice !== 'undefined' && handle instanceof GPUDevice) {\n return 'webgpu';\n }\n\n // TODO - WebGPU does not yet seem to have a stable in-browser API, so we \"sniff\" for members instead\n if ((handle as any)?.queue) {\n return 'webgpu';\n }\n\n // null\n if (handle === null) {\n return 'null';\n }\n\n if (handle instanceof WebGLRenderingContext) {\n log.warn('WebGL1 is not supported', handle)();\n } else {\n log.warn('Unknown handle type', handle)();\n }\n\n return null;\n }\n}\n\n/**\n * Entry point to the luma.gl GPU abstraction\n * Register WebGPU and/or WebGL adapters (controls application bundle size)\n * Run-time selection of the first available Device\n */\n// biome-ignore lint/suspicious/noRedeclare: the exported singleton intentionally mirrors the global debug handle.\nexport const luma = new Luma();\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {isBrowser} from '@probe.gl/env';\nimport {Device, DeviceProps} from './device';\n\n/**\n * Create and attach devices for a specific backend.\n */\nexport abstract class Adapter {\n // new (props: DeviceProps): Device; Constructor isn't used\n abstract type: string;\n /** Check if this backend is supported */\n abstract isSupported(): boolean;\n /** Check if the given handle is a valid device handle for this backend */\n abstract isDeviceHandle(handle: unknown): boolean;\n /** Create a new device for this backend */\n abstract create(props: DeviceProps): Promise;\n /** Attach a Device to a valid handle for this backend (GPUDevice, WebGL2RenderingContext etc) */\n abstract attach(handle: unknown, props: DeviceProps): Promise;\n\n /**\n * Page load promise\n * Resolves when the DOM is loaded.\n * @note Since are be limitations on number of `load` event listeners,\n * it is recommended avoid calling this accessor until actually needed.\n * I.e. we don't call it unless you know that you will be looking up a string in the DOM.\n */\n get pageLoaded(): Promise {\n return getPageLoadPromise();\n }\n}\n\n// HELPER FUNCTIONS\n\nconst isPage: boolean = isBrowser() && typeof document !== 'undefined';\nconst isPageLoaded: () => boolean = () => isPage && document.readyState === 'complete';\nlet pageLoadPromise: Promise | null = null;\n\n/** Returns a promise that resolves when the page is loaded */\nfunction getPageLoadPromise(): Promise {\n if (!pageLoadPromise) {\n if (isPageLoaded() || typeof window === 'undefined') {\n pageLoadPromise = Promise.resolve();\n } else {\n pageLoadPromise = new Promise(resolve => window.addEventListener('load', () => resolve()));\n }\n }\n return pageLoadPromise;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\ntype CanvasObserverProps = {\n canvas?: HTMLCanvasElement;\n trackPosition: boolean;\n onResize: (entries: ResizeObserverEntry[]) => void;\n onIntersection: (entries: IntersectionObserverEntry[]) => void;\n onDevicePixelRatioChange: () => void;\n onPositionChange: () => void;\n};\n\n/**\n * Internal DOM observer orchestration for HTML canvas surfaces.\n *\n * CanvasSurface owns the tracked state and device callback dispatch. This helper only manages\n * browser observers, timers, and polling loops, then reports events through callbacks.\n */\nexport class CanvasObserver {\n readonly props: CanvasObserverProps;\n\n private _resizeObserver: ResizeObserver | undefined;\n private _intersectionObserver: IntersectionObserver | undefined;\n private _observeDevicePixelRatioTimeout: ReturnType | null = null;\n private _observeDevicePixelRatioMediaQuery: MediaQueryList | null = null;\n private readonly _handleDevicePixelRatioChange = () => this._refreshDevicePixelRatio();\n private _trackPositionInterval: ReturnType | null = null;\n private _started = false;\n\n get started(): boolean {\n return this._started;\n }\n\n constructor(props: CanvasObserverProps) {\n this.props = props;\n }\n\n start(): void {\n if (this._started || !this.props.canvas) {\n return;\n }\n\n this._started = true;\n this._intersectionObserver ||= new IntersectionObserver(entries =>\n this.props.onIntersection(entries)\n );\n this._resizeObserver ||= new ResizeObserver(entries => this.props.onResize(entries));\n\n this._intersectionObserver.observe(this.props.canvas);\n try {\n this._resizeObserver.observe(this.props.canvas, {box: 'device-pixel-content-box'});\n } catch {\n this._resizeObserver.observe(this.props.canvas, {box: 'content-box'});\n }\n\n this._observeDevicePixelRatioTimeout = setTimeout(() => this._refreshDevicePixelRatio(), 0);\n\n if (this.props.trackPosition) {\n this._trackPosition();\n }\n }\n\n stop(): void {\n if (!this._started) {\n return;\n }\n\n this._started = false;\n\n if (this._observeDevicePixelRatioTimeout) {\n clearTimeout(this._observeDevicePixelRatioTimeout);\n this._observeDevicePixelRatioTimeout = null;\n }\n\n if (this._observeDevicePixelRatioMediaQuery) {\n this._observeDevicePixelRatioMediaQuery.removeEventListener(\n 'change',\n this._handleDevicePixelRatioChange\n );\n this._observeDevicePixelRatioMediaQuery = null;\n }\n\n if (this._trackPositionInterval) {\n clearInterval(this._trackPositionInterval);\n this._trackPositionInterval = null;\n }\n\n this._resizeObserver?.disconnect();\n this._intersectionObserver?.disconnect();\n }\n\n private _refreshDevicePixelRatio(): void {\n if (!this._started) {\n return;\n }\n\n this.props.onDevicePixelRatioChange();\n\n this._observeDevicePixelRatioMediaQuery?.removeEventListener(\n 'change',\n this._handleDevicePixelRatioChange\n );\n this._observeDevicePixelRatioMediaQuery = matchMedia(\n `(resolution: ${window.devicePixelRatio}dppx)`\n );\n this._observeDevicePixelRatioMediaQuery.addEventListener(\n 'change',\n this._handleDevicePixelRatioChange,\n {once: true}\n );\n }\n\n private _trackPosition(intervalMs: number = 100): void {\n if (this._trackPositionInterval) {\n return;\n }\n\n this._trackPositionInterval = setInterval(() => {\n if (!this._started) {\n if (this._trackPositionInterval) {\n clearInterval(this._trackPositionInterval);\n this._trackPositionInterval = null;\n }\n } else {\n this.props.onPositionChange();\n }\n }, intervalMs);\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// TODO - replace with Promise.withResolvers once we upgrade TS baseline\nexport function withResolvers(): {\n promise: Promise;\n resolve: (t: T) => void;\n reject: (error: Error) => void;\n} {\n let resolve: (t: T) => void;\n let reject: (error: Error) => void;\n const promise = new Promise((_resolve, _reject) => {\n resolve = _resolve;\n reject = _reject;\n });\n // @ts-expect-error - in fact these are no used before initialized\n return {promise, resolve, reject};\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/** Throws if condition is true and narrows type */\nexport function assert(condition: unknown, message?: string): asserts condition {\n if (!condition) {\n const error = new Error(message ?? 'luma.gl assertion failed.');\n Error.captureStackTrace?.(error, assert);\n throw error;\n }\n}\n\n/** Throws if value is not defined, narrows type */\nexport function assertDefined(value: T | undefined, message?: string): T {\n assert(value, message);\n return value;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {isBrowser} from '@probe.gl/env';\nimport type {Device} from './device';\nimport type {CanvasContext} from './canvas-context';\nimport {CanvasObserver} from './canvas-observer';\nimport type {PresentationContext} from './presentation-context';\nimport type {Framebuffer} from './resources/framebuffer';\nimport type {TextureFormatDepthStencil} from '../shadertypes/texture-types/texture-formats';\nimport {uid} from '../utils/uid';\nimport {withResolvers} from '../utils/promise-utils';\nimport {assertDefined} from '../utils/assert';\n\n/** Properties for a CanvasContext */\nexport type CanvasContextProps = {\n /** Identifier, for debugging */\n id?: string;\n /** If a canvas not supplied, one will be created and added to the DOM. If a string, a canvas with that id will be looked up in the DOM */\n canvas?: HTMLCanvasElement | OffscreenCanvas | string | null;\n /** If new canvas is created, it will be created in the specified container, otherwise is appended as a child of document.body */\n container?: HTMLElement | string | null;\n /** Width in pixels of the canvas - used when creating a new canvas */\n width?: number;\n /** Height in pixels of the canvas - used when creating a new canvas */\n height?: number;\n /** Visibility (only used if new canvas is created). */\n visible?: boolean;\n /** Whether to size the drawing buffer to the pixel size during auto resize. If a number is provided it is used as a static pixel ratio */\n useDevicePixels?: boolean | number;\n /** Whether to track window resizes. */\n autoResize?: boolean;\n /** @see https://developer.mozilla.org/en-US/docs/Web/API/GPUCanvasContext/configure#alphamode */\n alphaMode?: 'opaque' | 'premultiplied';\n /** @see https://developer.mozilla.org/en-US/docs/Web/API/GPUCanvasContext/configure#colorspace */\n colorSpace?: 'srgb'; // GPUPredefinedColorSpace\n /** Whether to track position changes. Calls this.device.onPositionChange */\n trackPosition?: boolean;\n};\n\nexport type MutableCanvasContextProps = {\n /** Whether to size the drawing buffer to the pixel size during auto resize. If a number is provided it is used as a static pixel ratio */\n useDevicePixels?: boolean | number;\n};\n\n/**\n * Shared tracked-canvas lifecycle used by both renderable and presentation contexts.\n * - Creates a new canvas or looks up a canvas from the DOM\n * - Provides check for DOM loaded\n * @todo commit() @see https://github.com/w3ctag/design-reviews/issues/288\n * @todo transferControlToOffscreen: @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/transferControlToOffscreen\n */\nexport abstract class CanvasSurface {\n static isHTMLCanvas(canvas: unknown): canvas is HTMLCanvasElement {\n return typeof HTMLCanvasElement !== 'undefined' && canvas instanceof HTMLCanvasElement;\n }\n\n static isOffscreenCanvas(canvas: unknown): canvas is OffscreenCanvas {\n return typeof OffscreenCanvas !== 'undefined' && canvas instanceof OffscreenCanvas;\n }\n\n static defaultProps: Required = {\n id: undefined!,\n canvas: null,\n width: 800,\n height: 600,\n useDevicePixels: true,\n autoResize: true,\n container: null,\n visible: true,\n alphaMode: 'opaque',\n colorSpace: 'srgb',\n trackPosition: false\n };\n\n abstract readonly device: Device;\n abstract readonly handle: unknown;\n readonly id: string;\n\n readonly props: Required;\n readonly canvas: HTMLCanvasElement | OffscreenCanvas;\n /** Handle to HTML canvas */\n readonly htmlCanvas?: HTMLCanvasElement;\n /** Handle to wrapped OffScreenCanvas */\n readonly offscreenCanvas?: OffscreenCanvas;\n readonly type: 'html-canvas' | 'offscreen-canvas' | 'node';\n\n /** Promise that resolved once the resize observer has updated the pixel size */\n initialized: Promise;\n isInitialized: boolean = false;\n\n /** Visibility is automatically updated (via an IntersectionObserver) */\n isVisible: boolean = true;\n\n /** Width of canvas in CSS units (tracked by a ResizeObserver) */\n cssWidth: number;\n /** Height of canvas in CSS units (tracked by a ResizeObserver) */\n cssHeight: number;\n\n /** Device pixel ratio. Automatically updated via media queries */\n devicePixelRatio: number;\n /** Exact width of canvas in physical pixels (tracked by a ResizeObserver) */\n devicePixelWidth: number;\n /** Exact height of canvas in physical pixels (tracked by a ResizeObserver) */\n devicePixelHeight: number;\n\n /** Width of drawing buffer: automatically tracks this.pixelWidth if props.autoResize is true */\n drawingBufferWidth: number;\n /** Height of drawing buffer: automatically tracks this.pixelHeight if props.autoResize is true */\n drawingBufferHeight: number;\n\n /** Resolves when the canvas is initialized, i.e. when the ResizeObserver has updated the pixel size */\n protected _initializedResolvers = withResolvers();\n protected _canvasObserver: CanvasObserver;\n /** Position of the canvas in the document, updated by a timer */\n protected _position: [number, number] = [0, 0];\n /** Whether this canvas context has been destroyed */\n protected destroyed = false;\n /** Whether the drawing buffer size needs to be resized (deferred resizing to avoid flicker) */\n protected _needsDrawingBufferResize: boolean = true;\n\n abstract get [Symbol.toStringTag](): string;\n\n toString(): string {\n return `${this[Symbol.toStringTag]}(${this.id})`;\n }\n\n constructor(props?: CanvasContextProps) {\n this.props = {...CanvasSurface.defaultProps, ...props};\n props = this.props;\n\n this.initialized = this._initializedResolvers.promise;\n\n if (!isBrowser()) {\n this.canvas = {width: props.width || 1, height: props.height || 1} as OffscreenCanvas;\n } else if (!props.canvas) {\n this.canvas = createCanvasElement(props);\n } else if (typeof props.canvas === 'string') {\n this.canvas = getCanvasFromDOM(props.canvas);\n } else {\n this.canvas = props.canvas;\n }\n\n if (CanvasSurface.isHTMLCanvas(this.canvas)) {\n this.id = props.id || this.canvas.id;\n this.type = 'html-canvas';\n this.htmlCanvas = this.canvas;\n } else if (CanvasSurface.isOffscreenCanvas(this.canvas)) {\n this.id = props.id || 'offscreen-canvas';\n this.type = 'offscreen-canvas';\n this.offscreenCanvas = this.canvas;\n } else {\n this.id = props.id || 'node-canvas-context';\n this.type = 'node';\n }\n\n this.cssWidth = this.htmlCanvas?.clientWidth || this.canvas.width;\n this.cssHeight = this.htmlCanvas?.clientHeight || this.canvas.height;\n this.devicePixelWidth = this.canvas.width;\n this.devicePixelHeight = this.canvas.height;\n this.drawingBufferWidth = this.canvas.width;\n this.drawingBufferHeight = this.canvas.height;\n this.devicePixelRatio = globalThis.devicePixelRatio || 1;\n this._position = [0, 0];\n this._canvasObserver = new CanvasObserver({\n canvas: this.htmlCanvas,\n trackPosition: this.props.trackPosition,\n onResize: entries => this._handleResize(entries),\n onIntersection: entries => this._handleIntersection(entries),\n onDevicePixelRatioChange: () => this._observeDevicePixelRatio(),\n onPositionChange: () => this.updatePosition()\n });\n }\n\n destroy() {\n if (!this.destroyed) {\n this.destroyed = true;\n this._stopObservers();\n // @ts-expect-error Clear the device to make sure we don't access it after destruction.\n this.device = null;\n }\n }\n\n setProps(props: MutableCanvasContextProps): this {\n if ('useDevicePixels' in props) {\n this.props.useDevicePixels = props.useDevicePixels || false;\n this._updateDrawingBufferSize();\n }\n return this;\n }\n\n /** Returns a framebuffer with properly resized current 'swap chain' textures */\n getCurrentFramebuffer(options?: {\n depthStencilFormat?: TextureFormatDepthStencil | false;\n }): Framebuffer {\n this._resizeDrawingBufferIfNeeded();\n return this._getCurrentFramebuffer(options);\n }\n\n getCSSSize(): [number, number] {\n return [this.cssWidth, this.cssHeight];\n }\n\n getPosition() {\n return this._position;\n }\n\n getDevicePixelSize(): [number, number] {\n return [this.devicePixelWidth, this.devicePixelHeight];\n }\n\n getDrawingBufferSize(): [number, number] {\n return [this.drawingBufferWidth, this.drawingBufferHeight];\n }\n\n getMaxDrawingBufferSize(): [number, number] {\n const maxTextureDimension = this.device.limits.maxTextureDimension2D;\n return [maxTextureDimension, maxTextureDimension];\n }\n\n setDrawingBufferSize(width: number, height: number) {\n width = Math.floor(width);\n height = Math.floor(height);\n if (this.drawingBufferWidth === width && this.drawingBufferHeight === height) {\n return;\n }\n this.drawingBufferWidth = width;\n this.drawingBufferHeight = height;\n this._needsDrawingBufferResize = true;\n }\n\n getDevicePixelRatio(): number {\n const devicePixelRatio = typeof window !== 'undefined' && window.devicePixelRatio;\n return devicePixelRatio || 1;\n }\n\n cssToDevicePixels(\n cssPixel: [number, number],\n yInvert: boolean = true\n ): {\n x: number;\n y: number;\n width: number;\n height: number;\n } {\n const ratio = this.cssToDeviceRatio();\n const [width, height] = this.getDrawingBufferSize();\n return scalePixels(cssPixel, ratio, width, height, yInvert);\n }\n\n /** @deprecated - use .getDevicePixelSize() */\n getPixelSize() {\n return this.getDevicePixelSize();\n }\n\n /** @deprecated Use the current drawing buffer size for projection setup. */\n getAspect(): number {\n const [width, height] = this.getDrawingBufferSize();\n return width > 0 && height > 0 ? width / height : 1;\n }\n\n /** @deprecated Returns multiplier need to convert CSS size to Device size */\n cssToDeviceRatio(): number {\n try {\n const [drawingBufferWidth] = this.getDrawingBufferSize();\n const [cssWidth] = this.getCSSSize();\n return cssWidth ? drawingBufferWidth / cssWidth : 1;\n } catch {\n return 1;\n }\n }\n\n /** @deprecated Use canvasContext.setDrawingBufferSize() */\n resize(size: {width: number; height: number}): void {\n this.setDrawingBufferSize(size.width, size.height);\n }\n\n protected abstract _configureDevice(): void;\n\n protected abstract _getCurrentFramebuffer(options?: {\n depthStencilFormat?: TextureFormatDepthStencil | false;\n }): Framebuffer;\n\n protected _setAutoCreatedCanvasId(id: string) {\n if (this.htmlCanvas?.id === 'lumagl-auto-created-canvas') {\n this.htmlCanvas.id = id;\n }\n }\n\n /**\n * Starts DOM observation after the derived context and its device are fully initialized.\n *\n * `CanvasSurface` construction runs before subclasses can assign `this.device`, and the\n * default WebGL canvas context is created before `WebGLDevice` has initialized `limits`,\n * `features`, and the rest of its runtime state. Deferring observer startup avoids early\n * `ResizeObserver` and DPR callbacks running against a partially initialized device.\n */\n _startObservers(): void {\n if (this.destroyed) {\n return;\n }\n this._canvasObserver.start();\n }\n\n /**\n * Stops all DOM observation and timers associated with a canvas surface.\n *\n * This pairs with `_startObservers()` so teardown uses the same lifecycle whether a context is\n * explicitly destroyed, abandoned during device reuse, or temporarily has not started observing\n * yet. Centralizing shutdown here keeps resize/DPR/position watchers from surviving past the\n * lifetime of the owning device.\n */\n _stopObservers(): void {\n this._canvasObserver.stop();\n }\n\n protected _handleIntersection(entries: IntersectionObserverEntry[]) {\n if (this.destroyed) {\n return;\n }\n\n const entry = entries.find(entry_ => entry_.target === this.canvas);\n if (!entry) {\n return;\n }\n const isVisible = entry.isIntersecting;\n if (this.isVisible !== isVisible) {\n this.isVisible = isVisible;\n this.device.props.onVisibilityChange(this as CanvasContext | PresentationContext);\n }\n }\n\n protected _handleResize(entries: ResizeObserverEntry[]) {\n if (this.destroyed) {\n return;\n }\n\n const entry = entries.find(entry_ => entry_.target === this.canvas);\n if (!entry) {\n return;\n }\n\n const contentBoxSize = assertDefined(entry.contentBoxSize?.[0]);\n this.cssWidth = contentBoxSize.inlineSize;\n this.cssHeight = contentBoxSize.blockSize;\n\n const oldPixelSize = this.getDevicePixelSize();\n\n const devicePixelWidth =\n entry.devicePixelContentBoxSize?.[0]?.inlineSize ||\n contentBoxSize.inlineSize * devicePixelRatio;\n\n const devicePixelHeight =\n entry.devicePixelContentBoxSize?.[0]?.blockSize ||\n contentBoxSize.blockSize * devicePixelRatio;\n\n const [maxDevicePixelWidth, maxDevicePixelHeight] = this.getMaxDrawingBufferSize();\n this.devicePixelWidth = Math.max(1, Math.min(devicePixelWidth, maxDevicePixelWidth));\n this.devicePixelHeight = Math.max(1, Math.min(devicePixelHeight, maxDevicePixelHeight));\n\n this._updateDrawingBufferSize();\n\n this.device.props.onResize(this as CanvasContext | PresentationContext, {oldPixelSize});\n }\n\n protected _updateDrawingBufferSize() {\n if (this.props.autoResize) {\n if (typeof this.props.useDevicePixels === 'number') {\n const devicePixelRatio = this.props.useDevicePixels;\n this.setDrawingBufferSize(\n this.cssWidth * devicePixelRatio,\n this.cssHeight * devicePixelRatio\n );\n } else if (this.props.useDevicePixels) {\n this.setDrawingBufferSize(this.devicePixelWidth, this.devicePixelHeight);\n } else {\n this.setDrawingBufferSize(this.cssWidth, this.cssHeight);\n }\n }\n\n this._initializedResolvers.resolve();\n this.isInitialized = true;\n\n this.updatePosition();\n }\n\n _resizeDrawingBufferIfNeeded() {\n if (this._needsDrawingBufferResize) {\n this._needsDrawingBufferResize = false;\n const sizeChanged =\n this.drawingBufferWidth !== this.canvas.width ||\n this.drawingBufferHeight !== this.canvas.height;\n if (sizeChanged) {\n this.canvas.width = this.drawingBufferWidth;\n this.canvas.height = this.drawingBufferHeight;\n this._configureDevice();\n }\n }\n }\n\n _observeDevicePixelRatio() {\n if (this.destroyed || !this._canvasObserver.started) {\n return;\n }\n const oldRatio = this.devicePixelRatio;\n this.devicePixelRatio = window.devicePixelRatio;\n\n this.updatePosition();\n\n this.device.props.onDevicePixelRatioChange?.(this as CanvasContext | PresentationContext, {\n oldRatio\n });\n }\n\n updatePosition() {\n if (this.destroyed) {\n return;\n }\n const newRect = this.htmlCanvas?.getBoundingClientRect();\n if (newRect) {\n const position: [number, number] = [newRect.left, newRect.top];\n this._position ??= position;\n const positionChanged =\n position[0] !== this._position[0] || position[1] !== this._position[1];\n if (positionChanged) {\n const oldPosition = this._position;\n this._position = position;\n this.device.props.onPositionChange?.(this as CanvasContext | PresentationContext, {\n oldPosition\n });\n }\n }\n }\n}\n\nfunction getContainer(container: HTMLElement | string | null): HTMLElement {\n if (typeof container === 'string') {\n const element = document.getElementById(container);\n if (!element) {\n throw new Error(`${container} is not an HTML element`);\n }\n return element;\n }\n if (container) {\n return container;\n }\n return document.body;\n}\n\nfunction getCanvasFromDOM(canvasId: string): HTMLCanvasElement {\n const canvas = document.getElementById(canvasId);\n if (!CanvasSurface.isHTMLCanvas(canvas)) {\n throw new Error('Object is not a canvas element');\n }\n return canvas;\n}\n\nfunction createCanvasElement(props: CanvasContextProps) {\n const {width, height} = props;\n const newCanvas = document.createElement('canvas');\n newCanvas.id = uid('lumagl-auto-created-canvas');\n newCanvas.width = width || 1;\n newCanvas.height = height || 1;\n newCanvas.style.width = Number.isFinite(width) ? `${width}px` : '100%';\n newCanvas.style.height = Number.isFinite(height) ? `${height}px` : '100%';\n if (!props?.visible) {\n newCanvas.style.visibility = 'hidden';\n }\n const container = getContainer(props?.container || null);\n container.insertBefore(newCanvas, container.firstChild);\n\n return newCanvas;\n}\n\nfunction scalePixels(\n pixel: [number, number],\n ratio: number,\n width: number,\n height: number,\n yInvert: boolean\n): {\n x: number;\n y: number;\n width: number;\n height: number;\n} {\n const point = pixel;\n\n const x = scaleX(point[0], ratio, width);\n let y = scaleY(point[1], ratio, height, yInvert);\n\n let temporary = scaleX(point[0] + 1, ratio, width);\n const xHigh = temporary === width - 1 ? temporary : temporary - 1;\n\n temporary = scaleY(point[1] + 1, ratio, height, yInvert);\n let yHigh;\n if (yInvert) {\n temporary = temporary === 0 ? temporary : temporary + 1;\n yHigh = y;\n y = temporary;\n } else {\n yHigh = temporary === height - 1 ? temporary : temporary - 1;\n }\n return {\n x,\n y,\n width: Math.max(xHigh - x + 1, 1),\n height: Math.max(yHigh - y + 1, 1)\n };\n}\n\nfunction scaleX(x: number, ratio: number, width: number): number {\n return Math.min(Math.round(x * ratio), width - 1);\n}\n\nfunction scaleY(y: number, ratio: number, height: number, yInvert: boolean): number {\n return yInvert\n ? Math.max(0, height - 1 - Math.round(y * ratio))\n : Math.min(Math.round(y * ratio), height - 1);\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport type {CanvasContextProps, MutableCanvasContextProps} from './canvas-surface';\nimport {CanvasSurface} from './canvas-surface';\n\n/**\n * Manages a renderable backend canvas. Supports both HTML or offscreen canvas\n * and returns backend framebuffers sourced from the canvas itself.\n */\nexport abstract class CanvasContext extends CanvasSurface {\n static override defaultProps = CanvasSurface.defaultProps;\n\n abstract override readonly handle: unknown;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {CanvasSurface} from './canvas-surface';\n\nexport type {CanvasContextProps as PresentationContextProps} from './canvas-surface';\n\n/**\n * Tracks a destination canvas for presentation.\n * Backend implementations either borrow the default GPU-backed canvas (WebGL)\n * or render directly into the destination canvas (WebGPU).\n */\nexport abstract class PresentationContext extends CanvasSurface {\n abstract present(): void;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport {CompareFunction} from '../types/parameters';\nimport {Resource, ResourceProps} from './resource';\n\n/** Edge values sampling mode */\nexport type SamplerAddressMode = 'clamp-to-edge' | 'repeat' | 'mirror-repeat';\n\n/** Sampler filtering mode */\nexport type SamplerFilterMode = 'nearest' | 'linear';\n\n/**\n * Properties for initializing a sampler\n */\nexport type SamplerProps = ResourceProps & {\n /** Comparison / shadow samplers are used with depth textures. See the `Sampler.compare` field */\n type?: 'color-sampler' | 'comparison-sampler';\n /** Edge value sampling in X direction */\n addressModeU?: 'clamp-to-edge' | 'repeat' | 'mirror-repeat';\n /** Edge value sampling in Y direction */\n addressModeV?: 'clamp-to-edge' | 'repeat' | 'mirror-repeat';\n /** Edge value sampling in Z direction */\n addressModeW?: 'clamp-to-edge' | 'repeat' | 'mirror-repeat';\n\n /** Magnification: the area of the fragment in texture space is smaller than a texel */\n magFilter?: 'nearest' | 'linear';\n /** Minification: the area of the fragment in texture space is larger than a texel */\n minFilter?: 'nearest' | 'linear';\n /** mipmapping: select between multiple mipmaps based on angle and size of the texture relative to the screen. */\n mipmapFilter?: 'none' | 'nearest' | 'linear';\n /** Affects the mipmap image selection */\n lodMinClamp?: number;\n /** Affects the mipmap image selection */\n lodMaxClamp?: number;\n /** Maximum number of samples that can be taken of the texture during any one texture fetch */\n maxAnisotropy?: number;\n /** How to compare reference values provided in shader shadow sampler calls with those pulled from the texture */\n compare?: CompareFunction;\n};\n\nexport type SamplerParameters = Omit;\n\n/** Immutable Sampler object */\nexport abstract class Sampler extends Resource {\n static override defaultProps: Required = {\n ...Resource.defaultProps,\n type: 'color-sampler',\n addressModeU: 'clamp-to-edge',\n addressModeV: 'clamp-to-edge',\n addressModeW: 'clamp-to-edge',\n magFilter: 'nearest',\n minFilter: 'nearest',\n mipmapFilter: 'none',\n lodMinClamp: 0,\n lodMaxClamp: 32, // Per WebGPU spec\n compare: 'less-equal',\n maxAnisotropy: 1\n };\n\n override get [Symbol.toStringTag](): string {\n return 'Sampler';\n }\n\n constructor(device: Device, props: SamplerProps) {\n props = Sampler.normalizeProps(device, props);\n super(device, props, Sampler.defaultProps);\n }\n\n protected static normalizeProps(device: Device, props: SamplerProps): SamplerProps {\n return props;\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {type TypedArray} from '@math.gl/types';\nimport {type Device} from '../device';\nimport {\n type TextureFormat,\n type TextureMemoryLayout,\n type TextureFormatInfo\n} from '../../shadertypes/texture-types/texture-formats';\nimport {type ExternalImage} from '../../shadertypes/image-types/image-types';\nimport {type TextureView, type TextureViewProps} from './texture-view';\nimport {Resource, type ResourceProps} from './resource';\nimport {Sampler, type SamplerProps} from './sampler';\nimport {Buffer} from './buffer';\nimport {log} from '../../utils/log';\nimport {textureFormatDecoder} from '../../shadertypes/texture-types/texture-format-decoder';\n\n/** Options for Texture.copyExternalImage */\nexport type CopyExternalImageOptions = {\n /** Image */\n image: ExternalImage;\n /** Copy from image x offset (default 0) */\n sourceX?: number;\n /** Copy from image y offset (default 0) */\n sourceY?: number;\n /** Copy area width (default 1) */\n width?: number;\n /** Copy area height (default 1) */\n height?: number;\n /** Copy depth, number of layers/depth slices(default 1) */\n depth?: number;\n /** Start copying into offset x (default 0) */\n x?: number;\n /** Start copying into offset y (default 0) */\n y?: number;\n /** Start copying into layer / depth slice z (default 0) */\n z?: number;\n /** Which mip-level to copy into (default 0) */\n mipLevel?: number;\n /** When copying into depth stencil textures (default 'all') */\n aspect?: 'all' | 'stencil-only' | 'depth-only';\n /** Specific color space of image data */\n colorSpace?: 'srgb';\n /** load as premultiplied alpha */\n premultipliedAlpha?: boolean;\n /** Whether to flip the image vertically */\n flipY?: boolean;\n};\n\n/** Options for copyImageData */\nexport type CopyImageDataOptions = {\n /** Data to copy (array of bytes) */\n data: ArrayBuffer | SharedArrayBuffer | ArrayBufferView;\n /** Offset into the data (in addition to any offset built-in to the ArrayBufferView) */\n byteOffset?: number;\n /** The stride, in bytes, between successive texel rows in the CPU source data. Tightly packed uploads can omit this. */\n bytesPerRow?: number;\n /** Number of rows that make up one image when uploading multiple layers or depth slices from CPU memory. */\n rowsPerImage?: number;\n /** Width to copy */\n width?: number;\n /** Height to copy */\n height?: number;\n /** Copy depth or number of layers */\n depthOrArrayLayers?: number;\n /** @deprecated Use `depthOrArrayLayers` */\n depth?: number;\n /** Start copying into offset x (default 0) */\n x?: number;\n /** Start copying into offset y (default 0) */\n y?: number;\n /** Start copying from depth layer z (default 0) */\n z?: number;\n /** Which mip-level to copy into (default 0) */\n mipLevel?: number;\n /** When copying into depth stencil textures (default 'all') */\n aspect?: 'all' | 'stencil-only' | 'depth-only';\n};\n\nexport type TextureReadOptions = {\n /** Start reading from offset x (default 0) */\n x?: number;\n /** Start reading from offset y (default 0) */\n y?: number;\n /** Start reading from layer / depth slice z (default 0) */\n z?: number;\n /** Width of the region to read. Defaults to the mip width. */\n width?: number;\n /** Height of the region to read. Defaults to the mip height. */\n height?: number;\n /** Number of array layers or depth slices to read. Defaults to 1. */\n depthOrArrayLayers?: number;\n /** Which mip-level to read from (default 0) */\n mipLevel?: number;\n /** When reading from depth stencil textures (default 'all') */\n aspect?: 'all' | 'stencil-only' | 'depth-only';\n};\n\nexport type TextureWriteOptions = {\n /** Offset into the source data or buffer, in bytes. */\n byteOffset?: number;\n /** The stride, in bytes, between successive texel rows in the source data or buffer. */\n bytesPerRow?: number;\n /** The number of rows that make up one image when writing multiple layers or slices. */\n rowsPerImage?: number;\n /** Start writing into offset x (default 0) */\n x?: number;\n /** Start writing into offset y (default 0) */\n y?: number;\n /** Start writing into layer / depth slice z (default 0) */\n z?: number;\n /** Width of the region to write. Defaults to the mip width. */\n width?: number;\n /** Height of the region to write. Defaults to the mip height. */\n height?: number;\n /** Number of array layers or depth slices to write. Defaults to 1, or the full mip depth for 3D textures. */\n depthOrArrayLayers?: number;\n /** Which mip-level to write into (default 0) */\n mipLevel?: number;\n /** When writing into depth stencil textures (default 'all') */\n aspect?: 'all' | 'stencil-only' | 'depth-only';\n};\n\nconst BASE_DIMENSIONS = {\n '1d': '1d',\n '2d': '2d',\n '2d-array': '2d',\n cube: '2d',\n 'cube-array': '2d',\n '3d': '3d'\n} as const satisfies Record;\n\n/** Texture properties */\nexport type TextureProps = ResourceProps & {\n /** @deprecated Use DynamicTexture to create textures with data. */\n data?: ExternalImage | TypedArray | null;\n /** Dimension of this texture. Defaults to '2d' */\n dimension?: '1d' | '2d' | '2d-array' | 'cube' | 'cube-array' | '3d';\n /** The format (bit layout) of the textures pixel data */\n format?: TextureFormat;\n /** Width in texels */\n width: number;\n /** Width in texels */\n height: number;\n /** Number of depth layers */\n depth?: number;\n /** How this texture will be used. Defaults to TEXTURE | COPY_DST | RENDER_ATTACHMENT */\n usage?: number;\n /** How many mip levels */\n mipLevels?: number;\n /** Multi sampling */\n samples?: number;\n\n /** Sampler (or SamplerProps) for the default sampler for this texture. Used if no sampler provided. Note that other samplers can still be used. */\n sampler?: Sampler | SamplerProps;\n /** Props for the default TextureView for this texture. Note that other views can still be created and used. */\n view?: TextureViewProps;\n};\n\n/**\n * Abstract Texture interface\n * Texture Object\n * https://gpuweb.github.io/gpuweb/#gputexture\n */\nexport abstract class Texture extends Resource {\n /** The texture can be bound for use as a sampled texture in a shader */\n static SAMPLE = 0x04;\n /** The texture can be bound for use as a storage texture in a shader */\n static STORAGE = 0x08;\n /** The texture can be used as a color or depth/stencil attachment in a render pass */\n static RENDER = 0x10;\n /** The texture can be used as the source of a copy operation */\n static COPY_SRC = 0x01;\n /** he texture can be used as the destination of a copy or write operation */\n static COPY_DST = 0x02;\n\n /** @deprecated Use Texture.SAMPLE */\n static TEXTURE = 0x04;\n /** @deprecated Use Texture.RENDER */\n static RENDER_ATTACHMENT = 0x10;\n\n /** dimension of this texture */\n readonly dimension: '1d' | '2d' | '2d-array' | 'cube' | 'cube-array' | '3d';\n /** base dimension of this texture */\n readonly baseDimension: '1d' | '2d' | '3d';\n /** format of this texture */\n readonly format: TextureFormat;\n /** width in pixels of this texture */\n readonly width: number;\n /** height in pixels of this texture */\n readonly height: number;\n /** depth of this texture */\n readonly depth: number;\n /** mip levels in this texture */\n readonly mipLevels: number;\n /** sample count */\n readonly samples: number;\n /** Rows are multiples of this length, padded with extra bytes if needed */\n readonly byteAlignment: number;\n /** Default sampler for this texture */\n abstract sampler: Sampler;\n /** Default view for this texture */\n abstract view: TextureView;\n\n /** The ready promise is always resolved. It is provided for type compatibility with DynamicTexture. */\n readonly ready: Promise = Promise.resolve(this);\n /** isReady is always true. It is provided for type compatibility with DynamicTexture. */\n readonly isReady: boolean = true;\n\n /** \"Time\" of last update. Monotonically increasing timestamp. TODO move to DynamicTexture? */\n updateTimestamp: number;\n\n override get [Symbol.toStringTag](): string {\n return 'Texture';\n }\n\n override toString(): string {\n return `Texture(${this.id},${this.format},${this.width}x${this.height})`;\n }\n\n /** Do not use directly. Create with device.createTexture() */\n constructor(device: Device, props: TextureProps, backendProps?: {byteAlignment?: number}) {\n props = Texture.normalizeProps(device, props);\n super(device, props, Texture.defaultProps);\n this.dimension = this.props.dimension;\n this.baseDimension = BASE_DIMENSIONS[this.dimension];\n this.format = this.props.format;\n\n // Size\n this.width = this.props.width;\n this.height = this.props.height;\n this.depth = this.props.depth;\n this.mipLevels = this.props.mipLevels;\n this.samples = this.props.samples || 1;\n\n if (this.dimension === 'cube') {\n this.depth = 6;\n }\n\n // Calculate size, if not provided\n if (this.props.width === undefined || this.props.height === undefined) {\n if (device.isExternalImage(props.data)) {\n const size = device.getExternalImageSize(props.data);\n this.width = size?.width || 1;\n this.height = size?.height || 1;\n } else {\n this.width = 1;\n this.height = 1;\n if (this.props.width === undefined || this.props.height === undefined) {\n log.warn(\n `${this} created with undefined width or height. This is deprecated. Use DynamicTexture instead.`\n )();\n }\n }\n }\n\n this.byteAlignment = backendProps?.byteAlignment || 1;\n\n // TODO - perhaps this should be set on async write completion?\n this.updateTimestamp = device.incrementTimestamp();\n }\n\n /**\n * Create a new texture with the same parameters and optionally a different size\n * @note Textures are immutable and cannot be resized after creation, but we can create a similar texture with the same parameters but a new size.\n * @note Does not copy contents of the texture\n */\n clone(size?: {width: number; height: number}): Texture {\n return this.device.createTexture({...this.props, ...size});\n }\n\n /** Set sampler props associated with this texture */\n setSampler(sampler: Sampler | SamplerProps): void {\n this.sampler = sampler instanceof Sampler ? sampler : this.device.createSampler(sampler);\n }\n\n /** Create a texture view for this texture */\n abstract createView(props: TextureViewProps): TextureView;\n\n /** Copy an image (e.g an ImageBitmap) into the texture */\n abstract copyExternalImage(options: CopyExternalImageOptions): {width: number; height: number};\n\n /**\n * Copy raw image data (bytes) into the texture.\n *\n * @note Deprecated compatibility wrapper over {@link writeData}.\n * @note Uses the same layout defaults and alignment rules as {@link writeData}.\n * @note Tightly packed CPU uploads can omit `bytesPerRow` and `rowsPerImage`.\n * @note If the CPU source rows are padded, pass explicit `bytesPerRow` and `rowsPerImage`.\n * @deprecated Use writeData()\n */\n copyImageData(options: CopyImageDataOptions): void {\n const {data, depth, ...writeOptions} = options;\n this.writeData(data, {\n ...writeOptions,\n depthOrArrayLayers: writeOptions.depthOrArrayLayers ?? depth\n });\n }\n\n /**\n * Calculates the memory layout of the texture, required when reading and writing data.\n * @return the backend-aligned linear layout, in particular bytesPerRow which includes any required padding for buffer copy/read paths\n */\n computeMemoryLayout(options_: TextureReadOptions = {}): TextureMemoryLayout {\n const options = this._normalizeTextureReadOptions(options_);\n const {width = this.width, height = this.height, depthOrArrayLayers = this.depth} = options;\n const {format, byteAlignment} = this;\n\n // TODO - does the overriding above make sense?\n // return textureFormatDecoder.computeMemoryLayout(this);\n return textureFormatDecoder.computeMemoryLayout({\n format,\n width,\n height,\n depth: depthOrArrayLayers,\n byteAlignment\n });\n }\n\n /**\n * Read the contents of a texture into a GPU Buffer.\n * @returns A Buffer containing the texture data.\n *\n * @note The memory layout of the texture data is determined by the texture format and dimensions.\n * @note The application can call Texture.computeMemoryLayout() to compute the backend-aligned layout.\n * @note The application can call Buffer.readAsync() to read the returned buffer on the CPU.\n * @note The destination buffer must be supplied by the caller and must be large enough for the requested region.\n * @note On WebGPU this corresponds to a texture-to-buffer copy and uses buffer-copy alignment rules.\n * @note On WebGL, luma.gl emulates the same logical readback behavior.\n */\n readBuffer(options?: TextureReadOptions, buffer?: Buffer): Buffer {\n throw new Error('readBuffer not implemented');\n }\n\n /**\n * Reads data from a texture into an ArrayBuffer.\n * @returns An ArrayBuffer containing the texture data.\n *\n * @note The memory layout of the texture data is determined by the texture format and dimensions.\n * @note The application can call Texture.computeMemoryLayout() to compute the layout.\n * @deprecated Use Texture.readBuffer() with an explicit destination buffer, or DynamicTexture.readAsync() for convenience readback.\n */\n readDataAsync(options?: TextureReadOptions): Promise {\n throw new Error('readBuffer not implemented');\n }\n\n /**\n * Writes a GPU Buffer into a texture.\n *\n * @param buffer - Source GPU buffer.\n * @param options - Destination subresource, extent, and source layout options.\n * @note The memory layout of the texture data is determined by the texture format and dimensions.\n * @note The application can call Texture.computeMemoryLayout() to compute the backend-aligned layout.\n * @note On WebGPU this corresponds to a buffer-to-texture copy and uses buffer-copy alignment rules.\n * @note On WebGL, luma.gl emulates the same destination and layout semantics.\n */\n writeBuffer(buffer: Buffer, options?: TextureWriteOptions): void {\n throw new Error('readBuffer not implemented');\n }\n\n /**\n * Writes an array buffer into a texture.\n *\n * @param data - Source texel data.\n * @param options - Destination subresource, extent, and source layout options.\n * @note If `bytesPerRow` and `rowsPerImage` are omitted, luma.gl computes a tightly packed CPU-memory layout for the requested region.\n * @note On WebGPU this corresponds to `GPUQueue.writeTexture()` and does not implicitly pad rows to 256 bytes.\n * @note On WebGL, padded CPU data is supported via the same `bytesPerRow` and `rowsPerImage` options.\n */\n writeData(\n data: ArrayBuffer | SharedArrayBuffer | ArrayBufferView,\n options?: TextureWriteOptions\n ): void {\n throw new Error('readBuffer not implemented');\n }\n\n // IMPLEMENTATION SPECIFIC\n\n /**\n * WebGL can read data synchronously.\n * @note While it is convenient, the performance penalty is very significant\n */\n readDataSyncWebGL(options?: TextureReadOptions): ArrayBuffer | ArrayBufferView {\n throw new Error('readDataSyncWebGL not available');\n }\n\n /** Generate mipmaps (WebGL only) */\n generateMipmapsWebGL(): void {\n throw new Error('generateMipmapsWebGL not available');\n }\n\n // HELPERS\n\n /** Ensure we have integer coordinates */\n protected static normalizeProps(device: Device, props: TextureProps): TextureProps {\n const newProps = {...props};\n\n // Ensure we have integer coordinates\n const {width, height} = newProps;\n if (typeof width === 'number') {\n newProps.width = Math.max(1, Math.ceil(width));\n }\n if (typeof height === 'number') {\n newProps.height = Math.max(1, Math.ceil(height));\n }\n return newProps;\n }\n\n /** Initialize texture with supplied props */\n // eslint-disable-next-line max-statements\n _initializeData(data: TextureProps['data']): void {\n // Store opts for accessors\n\n if (this.device.isExternalImage(data)) {\n this.copyExternalImage({\n image: data,\n width: this.width,\n height: this.height,\n depth: this.depth,\n mipLevel: 0,\n x: 0,\n y: 0,\n z: 0,\n aspect: 'all',\n colorSpace: 'srgb',\n premultipliedAlpha: false,\n flipY: false\n });\n } else if (data) {\n this.copyImageData({\n data,\n // width: this.width,\n // height: this.height,\n // depth: this.depth,\n mipLevel: 0,\n x: 0,\n y: 0,\n z: 0,\n aspect: 'all'\n });\n }\n }\n\n _normalizeCopyImageDataOptions(options_: CopyImageDataOptions): Required {\n const {data, depth, ...writeOptions} = options_;\n const options = this._normalizeTextureWriteOptions({\n ...writeOptions,\n depthOrArrayLayers: writeOptions.depthOrArrayLayers ?? depth\n });\n return {data, depth: options.depthOrArrayLayers, ...options};\n }\n\n _normalizeCopyExternalImageOptions(\n options_: CopyExternalImageOptions\n ): Required {\n const optionsWithoutUndefined = Texture._omitUndefined(options_);\n const mipLevel = optionsWithoutUndefined.mipLevel ?? 0;\n const mipLevelSize = this._getMipLevelSize(mipLevel);\n const size = this.device.getExternalImageSize(options_.image);\n const options = {\n ...Texture.defaultCopyExternalImageOptions,\n ...mipLevelSize,\n ...size,\n ...optionsWithoutUndefined\n };\n // WebGL will error if we try to copy outside the bounds of the texture\n options.width = Math.min(options.width, mipLevelSize.width - options.x);\n options.height = Math.min(options.height, mipLevelSize.height - options.y);\n options.depth = Math.min(options.depth, mipLevelSize.depthOrArrayLayers - options.z);\n return options;\n }\n\n _normalizeTextureReadOptions(options_: TextureReadOptions): Required {\n const optionsWithoutUndefined = Texture._omitUndefined(options_);\n const mipLevel = optionsWithoutUndefined.mipLevel ?? 0;\n const mipLevelSize = this._getMipLevelSize(mipLevel);\n const options = {\n ...Texture.defaultTextureReadOptions,\n ...mipLevelSize,\n ...optionsWithoutUndefined\n };\n // WebGL will error if we try to copy outside the bounds of the texture\n options.width = Math.min(options.width, mipLevelSize.width - options.x);\n options.height = Math.min(options.height, mipLevelSize.height - options.y);\n options.depthOrArrayLayers = Math.min(\n options.depthOrArrayLayers,\n mipLevelSize.depthOrArrayLayers - options.z\n );\n return options;\n }\n\n /**\n * Normalizes a texture read request and validates the color-only readback contract used by the\n * current texture read APIs. Supported dimensions are `2d`, `cube`, `cube-array`,\n * `2d-array`, and `3d`.\n *\n * @throws if the texture format, aspect, or dimension is not supported by the first-pass\n * color-read implementation.\n */\n protected _getSupportedColorReadOptions(\n options_: TextureReadOptions\n ): Required {\n const options = this._normalizeTextureReadOptions(options_);\n const formatInfo = textureFormatDecoder.getInfo(this.format);\n\n this._validateColorReadAspect(options);\n this._validateColorReadFormat(formatInfo);\n\n switch (this.dimension) {\n case '2d':\n case 'cube':\n case 'cube-array':\n case '2d-array':\n case '3d':\n return options;\n\n default:\n throw new Error(`${this} color readback does not support ${this.dimension} textures`);\n }\n }\n\n /** Validates that a read request targets the full color aspect of the texture. */\n protected _validateColorReadAspect(options: Required): void {\n if (options.aspect !== 'all') {\n throw new Error(`${this} color readback only supports aspect 'all'`);\n }\n }\n\n /** Validates that a read request targets an uncompressed color-renderable texture format. */\n protected _validateColorReadFormat(formatInfo: TextureFormatInfo): void {\n if (formatInfo.compressed) {\n throw new Error(\n `${this} color readback does not support compressed formats (${this.format})`\n );\n }\n\n switch (formatInfo.attachment) {\n case 'color':\n return;\n\n case 'depth':\n throw new Error(`${this} color readback does not support depth formats (${this.format})`);\n\n case 'stencil':\n throw new Error(`${this} color readback does not support stencil formats (${this.format})`);\n\n case 'depth-stencil':\n throw new Error(\n `${this} color readback does not support depth-stencil formats (${this.format})`\n );\n\n default:\n throw new Error(`${this} color readback does not support format ${this.format}`);\n }\n }\n\n _normalizeTextureWriteOptions(options_: TextureWriteOptions): Required {\n const optionsWithoutUndefined = Texture._omitUndefined(options_);\n const mipLevel = optionsWithoutUndefined.mipLevel ?? 0;\n const mipLevelSize = this._getMipLevelSize(mipLevel);\n const options = {\n ...Texture.defaultTextureWriteOptions,\n ...mipLevelSize,\n ...optionsWithoutUndefined\n };\n\n options.width = Math.min(options.width, mipLevelSize.width - options.x);\n options.height = Math.min(options.height, mipLevelSize.height - options.y);\n options.depthOrArrayLayers = Math.min(\n options.depthOrArrayLayers,\n mipLevelSize.depthOrArrayLayers - options.z\n );\n\n const layout = textureFormatDecoder.computeMemoryLayout({\n format: this.format,\n width: options.width,\n height: options.height,\n depth: options.depthOrArrayLayers,\n byteAlignment: this.byteAlignment\n });\n\n const minimumBytesPerRow = layout.bytesPerPixel * options.width;\n options.bytesPerRow = optionsWithoutUndefined.bytesPerRow ?? layout.bytesPerRow;\n options.rowsPerImage = optionsWithoutUndefined.rowsPerImage ?? options.height;\n\n if (options.bytesPerRow < minimumBytesPerRow) {\n throw new Error(\n `bytesPerRow (${options.bytesPerRow}) must be at least ${minimumBytesPerRow} for ${this.format}`\n );\n }\n if (options.rowsPerImage < options.height) {\n throw new Error(\n `rowsPerImage (${options.rowsPerImage}) must be at least ${options.height} for ${this.format}`\n );\n }\n\n const bytesPerPixel = this.device.getTextureFormatInfo(this.format).bytesPerPixel;\n if (bytesPerPixel && options.bytesPerRow % bytesPerPixel !== 0) {\n throw new Error(\n `bytesPerRow (${options.bytesPerRow}) must be a multiple of bytesPerPixel (${bytesPerPixel}) for ${this.format}`\n );\n }\n\n return options;\n }\n\n protected _getMipLevelSize(\n mipLevel: number\n ): Required> {\n const width = Math.max(1, this.width >> mipLevel);\n const height = this.baseDimension === '1d' ? 1 : Math.max(1, this.height >> mipLevel);\n const depthOrArrayLayers =\n this.dimension === '3d' ? Math.max(1, this.depth >> mipLevel) : this.depth;\n\n return {width, height, depthOrArrayLayers};\n }\n\n protected getAllocatedByteLength(): number {\n let allocatedByteLength = 0;\n\n for (let mipLevel = 0; mipLevel < this.mipLevels; mipLevel++) {\n const {width, height, depthOrArrayLayers} = this._getMipLevelSize(mipLevel);\n allocatedByteLength += textureFormatDecoder.computeMemoryLayout({\n format: this.format,\n width,\n height,\n depth: depthOrArrayLayers,\n byteAlignment: 1\n }).byteLength;\n }\n\n return allocatedByteLength * this.samples;\n }\n\n protected static _omitUndefined(options: T): Partial {\n return Object.fromEntries(\n Object.entries(options).filter(([, value]) => value !== undefined)\n ) as Partial;\n }\n\n static override defaultProps: Required = {\n ...Resource.defaultProps,\n data: null,\n dimension: '2d',\n format: 'rgba8unorm',\n usage: Texture.SAMPLE | Texture.RENDER | Texture.COPY_DST,\n width: undefined!,\n height: undefined!,\n depth: 1,\n mipLevels: 1,\n samples: undefined!,\n sampler: {},\n view: undefined!\n };\n\n protected static defaultCopyDataOptions: Required = {\n data: undefined!,\n byteOffset: 0,\n bytesPerRow: undefined!,\n rowsPerImage: undefined!,\n width: undefined!,\n height: undefined!,\n depthOrArrayLayers: undefined!,\n depth: 1,\n mipLevel: 0,\n x: 0,\n y: 0,\n z: 0,\n aspect: 'all'\n };\n\n /** Default options */\n protected static defaultCopyExternalImageOptions: Required = {\n image: undefined!,\n sourceX: 0,\n sourceY: 0,\n width: undefined!,\n height: undefined!,\n depth: 1,\n mipLevel: 0,\n x: 0,\n y: 0,\n z: 0,\n aspect: 'all',\n colorSpace: 'srgb',\n premultipliedAlpha: false,\n flipY: false\n };\n\n protected static defaultTextureReadOptions: Required = {\n x: 0,\n y: 0,\n z: 0,\n width: undefined!,\n height: undefined!,\n depthOrArrayLayers: 1,\n mipLevel: 0,\n aspect: 'all'\n };\n\n protected static defaultTextureWriteOptions: Required = {\n byteOffset: 0,\n bytesPerRow: undefined!,\n rowsPerImage: undefined!,\n x: 0,\n y: 0,\n z: 0,\n width: undefined!,\n height: undefined!,\n depthOrArrayLayers: 1,\n mipLevel: 0,\n aspect: 'all'\n };\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport type {Texture} from './texture';\nimport type {TextureFormat} from '../../shadertypes/texture-types/texture-formats';\nimport {Resource, ResourceProps} from './resource';\n\n/** Properties for initializing a texture view */\nexport type TextureViewProps = ResourceProps & {\n /** The format of the texture view. Must be either the format of the texture or one of the viewFormats specified during its creation. */\n format?: TextureFormat;\n /** The dimension to view the texture as. */\n dimension?: '1d' | '2d' | '2d-array' | 'cube' | 'cube-array' | '3d';\n /** Which aspect(s) of the texture are accessible to the texture view. default \"all\"*/\n aspect?: 'all' | 'stencil-only' | 'depth-only';\n /** The first (most detailed) mipmap level accessible to the texture view. default 0*/\n baseMipLevel?: number;\n /** How many mipmap levels, starting with baseMipLevel, are accessible to the texture view. */\n mipLevelCount: number;\n /** The index of the first array layer accessible to the texture view. default 0 */\n baseArrayLayer?: number;\n /** How many array layers, starting with baseArrayLayer, are accessible to the texture view. */\n arrayLayerCount: number;\n};\n\n/** Immutable TextureView object */\nexport abstract class TextureView extends Resource {\n abstract texture: Texture;\n\n override get [Symbol.toStringTag](): string {\n return 'TextureView';\n }\n\n /** Should not be constructed directly. Use `texture.createView(props)` */\n constructor(device: Device, props: TextureViewProps & {texture: Texture}) {\n super(device, props, TextureView.defaultProps);\n }\n\n static override defaultProps: Required = {\n ...Resource.defaultProps,\n format: undefined!,\n dimension: undefined!,\n aspect: 'all',\n baseMipLevel: 0,\n mipLevelCount: undefined!,\n baseArrayLayer: 0,\n arrayLayerCount: undefined!\n };\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {CompilerMessage} from '../adapter/types/compiler-message';\n\n/** @returns annotated errors or warnings */\nexport function formatCompilerLog(\n shaderLog: readonly CompilerMessage[],\n source: string,\n options?: {\n /** Include source code in the log. Either just the lines before issues or all source code */\n showSourceCode?: 'no' | 'issues' | 'all';\n html?: boolean;\n }\n): string {\n let formattedLog = '';\n const lines = source.split(/\\r?\\n/);\n const log = shaderLog.slice().sort((a, b) => a.lineNum - b.lineNum);\n\n switch (options?.showSourceCode || 'no') {\n case 'all':\n // Parse the error - note: browser and driver dependent\n let currentMessageIndex = 0;\n for (let lineNum = 1; lineNum <= lines.length; lineNum++) {\n const line = lines[lineNum - 1];\n const currentMessage = log[currentMessageIndex];\n if (line && currentMessage) {\n formattedLog += getNumberedLine(line, lineNum, options);\n }\n while (log.length > currentMessageIndex && currentMessage.lineNum === lineNum) {\n const message = log[currentMessageIndex++];\n if (message) {\n formattedLog += formatCompilerMessage(message, lines, message.lineNum, {\n ...options,\n inlineSource: false\n });\n }\n }\n }\n // Print any remaining messages\n while (log.length > currentMessageIndex) {\n const message = log[currentMessageIndex++];\n if (message) {\n formattedLog += formatCompilerMessage(message, [], 0, {\n ...options,\n inlineSource: false\n });\n }\n }\n return formattedLog;\n\n case 'issues':\n case 'no':\n // Parse the error - note: browser and driver dependent\n for (const message of shaderLog) {\n formattedLog += formatCompilerMessage(message, lines, message.lineNum, {\n inlineSource: options?.showSourceCode !== 'no'\n });\n }\n return formattedLog;\n }\n}\n\n// Helpers\n\n/** Format one message */\nfunction formatCompilerMessage(\n message: CompilerMessage,\n lines: readonly string[],\n lineNum: number,\n options: {\n inlineSource?: boolean;\n html?: boolean;\n }\n): string {\n if (options?.inlineSource) {\n const numberedLines = getNumberedLines(lines, lineNum);\n // If we got error position on line add a `^^^` indicator on next line\n const positionIndicator = message.linePos > 0 ? `${' '.repeat(message.linePos + 5)}^^^\\n` : '';\n return `\n${numberedLines}${positionIndicator}${message.type.toUpperCase()}: ${message.message}\n\n`;\n }\n const color = message.type === 'error' ? 'red' : 'orange';\n return options?.html\n ? `
${message.type.toUpperCase()}: ${\n message.message\n }
`\n : `${message.type.toUpperCase()}: ${message.message}`;\n}\n\nfunction getNumberedLines(\n lines: readonly string[],\n lineNum: number,\n options?: {html?: boolean}\n): string {\n let numberedLines = '';\n for (let lineIndex = lineNum - 2; lineIndex <= lineNum; lineIndex++) {\n const sourceLine = lines[lineIndex - 1];\n if (sourceLine !== undefined) {\n numberedLines += getNumberedLine(sourceLine, lineNum, options);\n }\n }\n return numberedLines;\n}\n\nfunction getNumberedLine(line: string, lineNum: number, options?: {html?: boolean}): string {\n const escapedLine = options?.html ? escapeHTML(line) : line;\n return `${padLeft(String(lineNum), 4)}: ${escapedLine}${options?.html ? '
' : '\\n'}`;\n}\n\n/**\n * Pads a string with a number of spaces (space characters) to the left\n * @param {String} string - string to pad\n * @param {Number} digits - number of spaces to add\n * @return {String} string - The padded string\n */\nfunction padLeft(string: string, paddedLength: number): string {\n let result = '';\n for (let i = string.length; i < paddedLength; ++i) {\n result += ' ';\n }\n return result + string;\n}\n\nfunction escapeHTML(unsafe: string): string {\n return unsafe\n .replaceAll('&', '&')\n .replaceAll('<', '<')\n .replaceAll('>', '>')\n .replaceAll('\"', '"')\n .replaceAll(\"'\", ''');\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport {Resource, ResourceProps} from './resource';\n// import { log } from '../../utils/log';\nimport {uid} from '../../utils/uid';\nimport {CompilerMessage} from '../types/compiler-message';\nimport {formatCompilerLog} from '../../adapter-utils/format-compiler-log';\n\n/**\n * Properties for a Shader\n */\nexport type ShaderProps = ResourceProps & {\n /** Shader language (defaults to auto) */\n language?: 'glsl' | 'wgsl' | 'auto';\n /** Which stage are we compiling? Required for GLSL. Ignored for WGSL. */\n stage?: 'vertex' | 'fragment' | 'compute';\n /** Shader source code */\n source: string;\n /** Optional shader source map (WebGPU only) */\n sourceMap?: string | null;\n /** Optional shader entry point (WebGPU only) */\n entryPoint?: string;\n /** Show shader source in browser? Overrides the device.props.debugShaders setting */\n debugShaders?: 'never' | 'errors' | 'warnings' | 'always';\n};\n\n/**\n * Immutable Shader object\n * In WebGPU the handle can be copied between threads\n */\nexport abstract class Shader extends Resource {\n override get [Symbol.toStringTag](): string {\n return 'Shader';\n }\n\n /** The stage of this shader */\n readonly stage: 'vertex' | 'fragment' | 'compute';\n /** The source code of this shader */\n readonly source: string;\n /** The compilation status of the shader. 'pending' if compilation is asynchronous, and on production */\n compilationStatus: 'pending' | 'success' | 'error' = 'pending';\n\n /** Create a new Shader instance */\n constructor(device: Device, props: ShaderProps) {\n props = {...props, debugShaders: props.debugShaders || device.props.debugShaders || 'errors'};\n super(device, {id: getShaderIdFromProps(props), ...props}, Shader.defaultProps);\n this.stage = this.props.stage;\n this.source = this.props.source;\n }\n\n abstract get asyncCompilationStatus(): Promise<'pending' | 'success' | 'error'>;\n\n /** Get compiler log asynchronously */\n abstract getCompilationInfo(): Promise;\n\n /** Get compiler log synchronously (WebGL only) */\n getCompilationInfoSync(): readonly CompilerMessage[] | null {\n return null;\n }\n\n /** Get translated shader source in host platform's native language (HLSL, GLSL, and even GLSL ES), if available */\n getTranslatedSource(): string | null {\n return null;\n }\n\n // PORTABLE HELPERS\n\n /** In browser logging of errors */\n async debugShader(): Promise {\n const trigger = this.props.debugShaders;\n switch (trigger) {\n case 'never':\n return;\n case 'errors':\n // On WebGL - Don't extract the log unless errors\n if (this.compilationStatus === 'success') {\n return;\n }\n break;\n case 'warnings':\n case 'always':\n break;\n }\n\n const messages = await this.getCompilationInfo();\n if (trigger === 'warnings' && messages?.length === 0) {\n return;\n }\n this._displayShaderLog(messages, this.id);\n }\n\n // PRIVATE\n\n /**\n * In-browser UI logging of errors\n * TODO - this HTML formatting code should not be in Device, should be pluggable\n */\n protected _displayShaderLog(messages: readonly CompilerMessage[], shaderId: string): void {\n // Return if under Node.js / incomplete `document` polyfills\n if (typeof document === 'undefined' || !document?.createElement) {\n return;\n }\n\n const shaderName: string = shaderId; // getShaderName(this.source) || ;\n const shaderTitle: string = `${this.stage} shader \"${shaderName}\"`;\n const htmlLog = formatCompilerLog(messages, this.source, {showSourceCode: 'all', html: true});\n // Show translated source if available\n const translatedSource = this.getTranslatedSource();\n\n const container = document.createElement('div');\n container.innerHTML = `\\\n

Compilation error in ${shaderTitle}

\n
\n
\n\n
\n
${htmlLog}
`;\n if (translatedSource) {\n container.innerHTML += `

Translated Source



${translatedSource}
`;\n }\n container.style.top = '0';\n container.style.left = '0';\n container.style.background = 'white';\n container.style.position = 'fixed';\n container.style.zIndex = '9999';\n container.style.maxWidth = '100vw';\n container.style.maxHeight = '100vh';\n container.style.overflowY = 'auto';\n document.body.appendChild(container);\n const error = container.querySelector('.luma-compiler-log-error');\n error?.scrollIntoView();\n (container.querySelector('button#close') as HTMLButtonElement).onclick = () => {\n container.remove();\n };\n (container.querySelector('button#copy') as HTMLButtonElement).onclick = () => {\n navigator.clipboard.writeText(this.source);\n };\n }\n\n static override defaultProps: Required = {\n ...Resource.defaultProps,\n language: 'auto',\n stage: undefined!,\n source: '',\n sourceMap: null,\n entryPoint: 'main',\n debugShaders: undefined!\n };\n}\n\n// HELPERS\n\n/** Deduce an id, from shader source, or supplied id, or shader type */\nfunction getShaderIdFromProps(props: ShaderProps): string {\n return getShaderName(props.source) || props.id || uid(`unnamed ${props.stage}-shader`);\n}\n\n/** Extracts GLSLIFY style naming of shaders: `#define SHADER_NAME ...` */\nfunction getShaderName(shader: string, defaultName: string = 'unnamed'): string {\n const SHADER_NAME_REGEXP = /#define[\\s*]SHADER_NAME[\\s*]([A-Za-z0-9_-]+)[\\s*]/;\n const match = SHADER_NAME_REGEXP.exec(shader);\n return match?.[1] ?? defaultName;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {\n TextureFormatColor,\n TextureFormatDepthStencil,\n TextureFormat\n} from '../../shadertypes/texture-types/texture-formats';\nimport type {Device} from '../device';\nimport {Resource, ResourceProps} from './resource';\nimport {Texture} from './texture';\nimport {TextureView} from './texture-view';\nimport {log} from '../../utils/log';\n\nexport type FramebufferProps = ResourceProps & {\n width?: number;\n height?: number;\n colorAttachments?: (TextureView | Texture | TextureFormatColor)[];\n depthStencilAttachment?: (TextureView | Texture | TextureFormatDepthStencil) | null;\n};\n\n/**\n * Create new textures with correct size for all attachments.\n * @note resize() destroys existing textures (if size has changed).\n */\nexport abstract class Framebuffer extends Resource {\n override get [Symbol.toStringTag](): string {\n return 'Framebuffer';\n }\n\n /** Width of all attachments in this framebuffer */\n width: number;\n /** Height of all attachments in this framebuffer */\n height: number;\n /** Color attachments */\n abstract colorAttachments: TextureView[];\n /** Depth-stencil attachment, if provided */\n abstract depthStencilAttachment: TextureView | null;\n\n constructor(device: Device, props: FramebufferProps = {}) {\n super(device, props, Framebuffer.defaultProps);\n this.width = this.props.width;\n this.height = this.props.height;\n }\n\n /**\n * Create a copy of this framebuffer with new attached textures, with same props but of the specified size.\n * @note Does not copy contents of the attached textures.\n */\n clone(size?: {width: number; height: number}): Framebuffer {\n const colorAttachments = this.colorAttachments.map(colorAttachment =>\n colorAttachment.texture.clone(size)\n );\n\n const depthStencilAttachment =\n this.depthStencilAttachment && this.depthStencilAttachment.texture.clone(size);\n\n return this.device.createFramebuffer({\n ...this.props,\n ...size,\n colorAttachments,\n depthStencilAttachment\n });\n }\n\n /**\n * Resizes all attachments\n * @note resize() destroys existing textures (if size has changed).\n * @deprecated Use framebuffer.clone()\n */\n resize(size: {width: number; height: number}): void;\n resize(size: [width: number, height: number]): void;\n resize(): void;\n resize(size?: {width: number; height: number} | [width: number, height: number]): void {\n let updateSize: boolean = !size;\n if (size) {\n const [width, height] = Array.isArray(size) ? size : [size.width, size.height];\n updateSize = updateSize || height !== this.height || width !== this.width;\n this.width = width;\n this.height = height;\n }\n if (updateSize) {\n log.log(2, `Resizing framebuffer ${this.id} to ${this.width}x${this.height}`)();\n this.resizeAttachments(this.width, this.height);\n }\n }\n\n /** Auto creates any textures */\n protected autoCreateAttachmentTextures(): void {\n if (this.props.colorAttachments.length === 0 && !this.props.depthStencilAttachment) {\n throw new Error('Framebuffer has noattachments');\n }\n\n this.colorAttachments = this.props.colorAttachments.map((attachment, index) => {\n if (typeof attachment === 'string') {\n const texture = this.createColorTexture(attachment, index);\n this.attachResource(texture);\n return texture.view;\n }\n if (attachment instanceof Texture) {\n return attachment.view;\n }\n return attachment;\n });\n\n const attachment = this.props.depthStencilAttachment;\n if (attachment) {\n if (typeof attachment === 'string') {\n const texture = this.createDepthStencilTexture(attachment);\n this.attachResource(texture);\n this.depthStencilAttachment = texture.view;\n } else if (attachment instanceof Texture) {\n this.depthStencilAttachment = attachment.view;\n } else {\n this.depthStencilAttachment = attachment;\n }\n }\n }\n\n /** Create a color texture */\n protected createColorTexture(format: TextureFormat, index: number): Texture {\n return this.device.createTexture({\n id: `${this.id}-color-attachment-${index}`,\n usage: Texture.RENDER_ATTACHMENT,\n format,\n width: this.width,\n height: this.height,\n // TODO deprecated? - luma.gl v8 compatibility\n sampler: {\n magFilter: 'linear',\n minFilter: 'linear'\n }\n });\n }\n\n /** Create depth stencil texture */\n protected createDepthStencilTexture(format: TextureFormat): Texture {\n return this.device.createTexture({\n id: `${this.id}-depth-stencil-attachment`,\n usage: Texture.RENDER_ATTACHMENT,\n format,\n width: this.width,\n height: this.height\n });\n }\n\n /**\n * Default implementation of resize\n * Creates new textures with correct size for all attachments.\n * and destroys existing textures if owned\n */\n protected resizeAttachments(width: number, height: number): void {\n this.colorAttachments.forEach((colorAttachment, i) => {\n const resizedTexture = colorAttachment.texture.clone({\n width,\n height\n });\n this.destroyAttachedResource(colorAttachment);\n this.colorAttachments[i] = resizedTexture.view;\n this.attachResource(resizedTexture.view);\n });\n\n if (this.depthStencilAttachment) {\n const resizedTexture = this.depthStencilAttachment.texture.clone({\n width,\n height\n });\n this.destroyAttachedResource(this.depthStencilAttachment);\n this.depthStencilAttachment = resizedTexture.view;\n this.attachResource(resizedTexture);\n }\n\n this.updateAttachments();\n }\n\n /** Implementation is expected to update any underlying binding (WebGL framebuffer attachment) */\n protected abstract updateAttachments(): void;\n\n static override defaultProps: Required = {\n ...Resource.defaultProps,\n width: 1,\n height: 1,\n colorAttachments: [], // ['rgba8unorm'],\n depthStencilAttachment: null // 'depth24plus-stencil8'\n };\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport type {PrimitiveTopology, RenderPipelineParameters} from '../types/parameters';\nimport type {ShaderLayout, Bindings, BindingsByGroup} from '../types/shader-layout';\nimport type {BufferLayout} from '../types/buffer-layout';\nimport type {\n TextureFormatColor,\n TextureFormatDepthStencil\n} from '@luma.gl/core/shadertypes/texture-types/texture-formats';\nimport type {Shader} from './shader';\nimport type {SharedRenderPipeline} from './shared-render-pipeline';\nimport type {RenderPass} from './render-pass';\nimport {Resource, ResourceProps} from './resource';\nimport {VertexArray} from './vertex-array';\nimport {TransformFeedback} from './transform-feedback';\n\nexport type RenderPipelineProps = ResourceProps & {\n // Shaders and shader layout\n\n /** Compiled vertex shader */\n vs?: Shader | null;\n /** Name of vertex shader stage main function (defaults to 'main'). WGSL only */\n vertexEntryPoint?: string; //\n /** Constant values to apply to compiled vertex shader. Do not require re-compilation. (WGSL only) */\n vsConstants?: Record; // WGSL only\n /** Compiled fragment shader */\n fs?: Shader | null;\n /** Name of fragment shader stage main function (defaults to 'main'). WGSL only */\n fragmentEntryPoint?: string; // WGSL only\n /** Constant values to apply to compiled fragment shader. Do not require re-compilation. (WGSL only) */\n fsConstants?: Record;\n\n /** Describes the attributes and bindings exposed by the pipeline shader(s). */\n shaderLayout?: ShaderLayout | null;\n /** Describes the buffers accepted by this pipeline and how they are mapped to shader attributes. */\n bufferLayout?: BufferLayout[]; // Record\n\n /** Determines how vertices are read from the 'vertex' attributes */\n topology?: PrimitiveTopology;\n\n // color attachment information (needed on WebGPU)\n\n /** Color attachments expected by this pipeline. Defaults to [device.preferredColorFormat]. Array needs not be contiguous. */\n colorAttachmentFormats?: (TextureFormatColor | null)[];\n /** Depth attachment expected by this pipeline. Defaults to device.preferredDepthFormat, if depthWriteEnables parameter is set */\n depthStencilAttachmentFormat?: TextureFormatDepthStencil;\n\n /** Parameters that are controlled by pipeline */\n parameters?: RenderPipelineParameters;\n\n /** Transform feedback varyings captured when linking a WebGL render pipeline. WebGL only. */\n varyings?: string[];\n /** Transform feedback buffer mode used when linking a WebGL render pipeline. WebGL only. */\n bufferMode?: number;\n\n /** Some applications intentionally supply unused attributes and bindings, and want to disable warnings */\n disableWarnings?: boolean;\n\n /** Internal hook for backend-specific shared pipeline implementations. */\n _sharedRenderPipeline?: SharedRenderPipeline;\n\n // Dynamic bindings (TODO - pipelines should be immutable, move to RenderPass)\n /** Buffers, Textures, Samplers for the shader bindings */\n bindings?: Bindings;\n /** Bindings grouped by bind-group index */\n bindGroups?: BindingsByGroup;\n};\n\n/**\n * A compiled and linked shader program\n */\nexport abstract class RenderPipeline extends Resource {\n override get [Symbol.toStringTag](): string {\n return 'RenderPipeline';\n }\n\n abstract readonly vs: Shader;\n abstract readonly fs: Shader | null;\n\n /** The merged layout */\n shaderLayout: ShaderLayout;\n /** Buffer map describing buffer interleaving etc */\n readonly bufferLayout: BufferLayout[];\n /** The linking status of the pipeline. 'pending' if linking is asynchronous, and on production */\n linkStatus: 'pending' | 'success' | 'error' = 'pending';\n /** The hash of the pipeline */\n hash: string = '';\n /** Optional shared backend implementation */\n sharedRenderPipeline: SharedRenderPipeline | null = null;\n\n /** Whether shader or pipeline compilation/linking is still in progress */\n get isPending(): boolean {\n return (\n this.linkStatus === 'pending' ||\n this.vs.compilationStatus === 'pending' ||\n this.fs?.compilationStatus === 'pending'\n );\n }\n\n /** Whether shader or pipeline compilation/linking has failed */\n get isErrored(): boolean {\n return (\n this.linkStatus === 'error' ||\n this.vs.compilationStatus === 'error' ||\n this.fs?.compilationStatus === 'error'\n );\n }\n\n constructor(device: Device, props: RenderPipelineProps) {\n super(device, props, RenderPipeline.defaultProps);\n this.shaderLayout = this.props.shaderLayout!;\n this.bufferLayout = this.props.bufferLayout || [];\n this.sharedRenderPipeline = this.props._sharedRenderPipeline || null;\n }\n\n /** Draw call. Returns false if the draw call was aborted (due to resources still initializing) */\n abstract draw(options: {\n /** Render pass to draw into (targeting screen or framebuffer) */\n renderPass?: RenderPass;\n /** Parameters to be set during draw call. Note that most parameters can only be overridden in WebGL. */\n parameters?: RenderPipelineParameters;\n /** Topology. Note can only be overridden in WebGL. */\n topology?: PrimitiveTopology;\n /** vertex attributes */\n vertexArray: VertexArray;\n /** Use instanced rendering? */\n isInstanced?: boolean;\n /** Number of \"rows\" in 'instance' buffers */\n instanceCount?: number;\n /** Number of \"rows\" in 'vertex' buffers */\n vertexCount?: number;\n /** Number of \"rows\" in index buffer */\n indexCount?: number;\n /** First vertex to draw from */\n firstVertex?: number;\n /** First index to draw from */\n firstIndex?: number;\n /** First instance to draw from */\n firstInstance?: number;\n baseVertex?: number;\n /** Transform feedback. WebGL only. */\n transformFeedback?: TransformFeedback;\n /** Bindings applied for this draw (textures, samplers, uniform buffers) */\n bindings?: Bindings;\n /** Bindings grouped by bind-group index */\n bindGroups?: BindingsByGroup;\n /** Optional stable cache keys for backend bind-group reuse */\n _bindGroupCacheKeys?: Partial>;\n /** WebGL-only uniforms */\n uniforms?: Record;\n }): boolean;\n\n static override defaultProps: Required = {\n ...Resource.defaultProps,\n\n vs: null,\n vertexEntryPoint: 'vertexMain',\n vsConstants: {},\n\n fs: null,\n fragmentEntryPoint: 'fragmentMain',\n fsConstants: {},\n\n shaderLayout: null,\n bufferLayout: [],\n topology: 'triangle-list',\n\n colorAttachmentFormats: undefined!,\n depthStencilAttachmentFormat: undefined!,\n\n parameters: {},\n varyings: undefined!,\n bufferMode: undefined!,\n disableWarnings: false,\n _sharedRenderPipeline: undefined!,\n bindings: undefined!,\n bindGroups: undefined!\n };\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport type {Shader} from './shader';\nimport {Resource, type ResourceProps} from './resource';\n\nexport type SharedRenderPipelineProps = ResourceProps & {\n handle?: unknown;\n vs: Shader;\n fs: Shader;\n varyings?: string[];\n bufferMode?: number;\n};\n\n/**\n * Internal base class for backend-specific shared render-pipeline implementations.\n * Backends may use this to share expensive linked/program state across multiple\n * `RenderPipeline` wrappers.\n */\nexport abstract class SharedRenderPipeline extends Resource {\n override get [Symbol.toStringTag](): string {\n return 'SharedRenderPipeline';\n }\n\n abstract override readonly device: Device;\n abstract override readonly handle: unknown;\n\n constructor(device: Device, props: SharedRenderPipelineProps) {\n super(device, props, {\n ...Resource.defaultProps,\n handle: undefined!,\n vs: undefined!,\n fs: undefined!,\n varyings: undefined!,\n bufferMode: undefined!\n });\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Resource, ResourceProps} from './resource';\nimport type {ComputeShaderLayout, Bindings, BindingsByGroup} from '../types/shader-layout';\nimport type {Device} from '../device';\nimport type {Shader} from './shader';\n\n/**\n * Properties for a compute pipeline\n */\nexport type ComputePipelineProps = ResourceProps & {\n handle?: unknown;\n /** Compiled shader object */\n shader: Shader;\n /** The entry point, defaults to main */\n entryPoint?: string;\n /** These are WGSL constant values - different from GLSL defines in that shader does not need to be recompiled */\n constants?: Record;\n /** Describes the attributes and bindings exposed by the pipeline shader(s). */\n shaderLayout?: ComputeShaderLayout | null;\n};\n\n/**\n * A compiled and linked shader program for compute\n */\nexport abstract class ComputePipeline extends Resource {\n override get [Symbol.toStringTag](): string {\n return 'ComputePipeline';\n }\n\n hash: string = '';\n /** The merged shader layout */\n shaderLayout: ComputeShaderLayout;\n\n constructor(device: Device, props: ComputePipelineProps) {\n super(device, props, ComputePipeline.defaultProps);\n this.shaderLayout = props.shaderLayout!;\n }\n\n /**\n * @todo Use renderpass.setBindings() ?\n * @todo Do we want to expose BindGroups in the API and remove this?\n */\n abstract setBindings(bindings: Bindings | BindingsByGroup): void;\n\n static override defaultProps: Required = {\n ...Resource.defaultProps,\n shader: undefined!,\n entryPoint: undefined!,\n constants: {},\n shaderLayout: undefined!\n };\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Device} from '../adapter/device';\nimport {ComputePipeline, type ComputePipelineProps} from '../adapter/resources/compute-pipeline';\nimport {RenderPipeline, type RenderPipelineProps} from '../adapter/resources/render-pipeline';\nimport {Resource} from '../adapter/resources/resource';\nimport type {SharedRenderPipeline} from '../adapter/resources/shared-render-pipeline';\nimport {log} from '../utils/log';\nimport {uid} from '../utils/uid';\nimport type {CoreModuleState} from './core-module-state';\n\nexport type PipelineFactoryProps = RenderPipelineProps;\n\ntype CacheItem> = {resource: ResourceT; useCount: number};\n\n/**\n * Efficiently creates / caches pipelines\n */\nexport class PipelineFactory {\n static defaultProps: Required = {...RenderPipeline.defaultProps};\n\n /** Get the singleton default pipeline factory for the specified device */\n static getDefaultPipelineFactory(device: Device): PipelineFactory {\n const moduleData = device.getModuleData('@luma.gl/core');\n moduleData.defaultPipelineFactory ||= new PipelineFactory(device);\n return moduleData.defaultPipelineFactory;\n }\n\n readonly device: Device;\n\n private _hashCounter: number = 0;\n private readonly _hashes: Record = {};\n private readonly _renderPipelineCache: Record> = {};\n private readonly _computePipelineCache: Record> = {};\n private readonly _sharedRenderPipelineCache: Record> = {};\n\n get [Symbol.toStringTag](): string {\n return 'PipelineFactory';\n }\n\n toString(): string {\n return `PipelineFactory(${this.device.id})`;\n }\n\n constructor(device: Device) {\n this.device = device;\n }\n\n /**\n * WebGL has two cache layers with different priorities:\n * - `_sharedRenderPipelineCache` owns `WEBGLSharedRenderPipeline` / `WebGLProgram` reuse.\n * - `_renderPipelineCache` owns `RenderPipeline` wrapper reuse.\n *\n * Shared WebGL program reuse is the hard requirement. Wrapper reuse is beneficial,\n * but wrapper cache misses are acceptable if that keeps the cache logic simple and\n * prevents incorrect cache hits.\n *\n * In particular, wrapper hash logic must never force program creation or linked-program\n * introspection just to decide whether a shared WebGL program can be reused.\n */\n /** Return a RenderPipeline matching supplied props. Reuses an equivalent pipeline if already created. */\n createRenderPipeline(props: RenderPipelineProps): RenderPipeline {\n if (!this.device.props._cachePipelines) {\n return this.device.createRenderPipeline(props);\n }\n\n const allProps: Required = {...RenderPipeline.defaultProps, ...props};\n\n const cache = this._renderPipelineCache;\n const hash = this._hashRenderPipeline(allProps);\n\n let pipeline: RenderPipeline = cache[hash]?.resource;\n if (!pipeline) {\n const sharedRenderPipeline =\n this.device.type === 'webgl' && this.device.props._sharePipelines\n ? this.createSharedRenderPipeline(allProps)\n : undefined;\n pipeline = this.device.createRenderPipeline({\n ...allProps,\n id: allProps.id ? `${allProps.id}-cached` : uid('unnamed-cached'),\n _sharedRenderPipeline: sharedRenderPipeline\n });\n pipeline.hash = hash;\n cache[hash] = {resource: pipeline, useCount: 1};\n if (this.device.props.debugFactories) {\n log.log(3, `${this}: ${pipeline} created, count=${cache[hash].useCount}`)();\n }\n } else {\n cache[hash].useCount++;\n if (this.device.props.debugFactories) {\n log.log(\n 3,\n `${this}: ${cache[hash].resource} reused, count=${cache[hash].useCount}, (id=${props.id})`\n )();\n }\n }\n\n return pipeline;\n }\n\n /** Return a ComputePipeline matching supplied props. Reuses an equivalent pipeline if already created. */\n createComputePipeline(props: ComputePipelineProps): ComputePipeline {\n if (!this.device.props._cachePipelines) {\n return this.device.createComputePipeline(props);\n }\n\n const allProps: Required = {...ComputePipeline.defaultProps, ...props};\n\n const cache = this._computePipelineCache;\n const hash = this._hashComputePipeline(allProps);\n\n let pipeline: ComputePipeline = cache[hash]?.resource;\n if (!pipeline) {\n pipeline = this.device.createComputePipeline({\n ...allProps,\n id: allProps.id ? `${allProps.id}-cached` : undefined\n });\n pipeline.hash = hash;\n cache[hash] = {resource: pipeline, useCount: 1};\n if (this.device.props.debugFactories) {\n log.log(3, `${this}: ${pipeline} created, count=${cache[hash].useCount}`)();\n }\n } else {\n cache[hash].useCount++;\n if (this.device.props.debugFactories) {\n log.log(\n 3,\n `${this}: ${cache[hash].resource} reused, count=${cache[hash].useCount}, (id=${props.id})`\n )();\n }\n }\n\n return pipeline;\n }\n\n release(pipeline: RenderPipeline | ComputePipeline): void {\n if (!this.device.props._cachePipelines) {\n pipeline.destroy();\n return;\n }\n\n const cache = this._getCache(pipeline);\n const hash = pipeline.hash;\n\n cache[hash].useCount--;\n if (cache[hash].useCount === 0) {\n this._destroyPipeline(pipeline);\n if (this.device.props.debugFactories) {\n log.log(3, `${this}: ${pipeline} released and destroyed`)();\n }\n } else if (cache[hash].useCount < 0) {\n log.error(`${this}: ${pipeline} released, useCount < 0, resetting`)();\n cache[hash].useCount = 0;\n } else if (this.device.props.debugFactories) {\n log.log(3, `${this}: ${pipeline} released, count=${cache[hash].useCount}`)();\n }\n }\n\n createSharedRenderPipeline(props: RenderPipelineProps): SharedRenderPipeline {\n const sharedPipelineHash = this._hashSharedRenderPipeline(props);\n let sharedCacheItem = this._sharedRenderPipelineCache[sharedPipelineHash];\n if (!sharedCacheItem) {\n const sharedRenderPipeline = this.device._createSharedRenderPipelineWebGL(props);\n sharedCacheItem = {resource: sharedRenderPipeline, useCount: 0};\n this._sharedRenderPipelineCache[sharedPipelineHash] = sharedCacheItem;\n }\n sharedCacheItem.useCount++;\n return sharedCacheItem.resource;\n }\n\n releaseSharedRenderPipeline(pipeline: RenderPipeline): void {\n if (!pipeline.sharedRenderPipeline) {\n return;\n }\n\n const sharedPipelineHash = this._hashSharedRenderPipeline(pipeline.sharedRenderPipeline.props);\n const sharedCacheItem = this._sharedRenderPipelineCache[sharedPipelineHash];\n if (!sharedCacheItem) {\n return;\n }\n\n sharedCacheItem.useCount--;\n if (sharedCacheItem.useCount === 0) {\n sharedCacheItem.resource.destroy();\n delete this._sharedRenderPipelineCache[sharedPipelineHash];\n }\n }\n\n // PRIVATE\n\n /** Destroy a cached pipeline, removing it from the cache if configured to do so. */\n private _destroyPipeline(pipeline: RenderPipeline | ComputePipeline): boolean {\n const cache = this._getCache(pipeline);\n\n if (!this.device.props._destroyPipelines) {\n return false;\n }\n\n delete cache[pipeline.hash];\n pipeline.destroy();\n if (pipeline instanceof RenderPipeline) {\n this.releaseSharedRenderPipeline(pipeline);\n }\n return true;\n }\n\n /** Get the appropriate cache for the type of pipeline */\n private _getCache(\n pipeline: RenderPipeline | ComputePipeline\n ): Record> | Record> {\n let cache:\n | Record>\n | Record>\n | undefined;\n if (pipeline instanceof ComputePipeline) {\n cache = this._computePipelineCache;\n }\n if (pipeline instanceof RenderPipeline) {\n cache = this._renderPipelineCache;\n }\n if (!cache) {\n throw new Error(`${this}`);\n }\n if (!cache[pipeline.hash]) {\n throw new Error(`${this}: ${pipeline} matched incorrect entry`);\n }\n return cache;\n }\n\n /** Calculate a hash based on all the inputs for a compute pipeline */\n private _hashComputePipeline(props: ComputePipelineProps): string {\n const {type} = this.device;\n const shaderHash = this._getHash(props.shader.source);\n const shaderLayoutHash = this._getHash(JSON.stringify(props.shaderLayout));\n return `${type}/C/${shaderHash}SL${shaderLayoutHash}`;\n }\n\n /** Calculate a hash based on all the inputs for a render pipeline */\n private _hashRenderPipeline(props: RenderPipelineProps): string {\n // Backend-specific hashing requirements:\n // - WebGPU hash keys must include every immutable descriptor-shaping input that can\n // change the created `GPURenderPipeline`, including attachment formats.\n // - WebGL hash keys only govern wrapper reuse. They must remain compatible with\n // shared-program reuse and must not depend on linked-program introspection just\n // to decide whether a shared `WebGLProgram` can be reused.\n //\n // General exclusions:\n // - `id`, `handle`: resource identity / caller-supplied handles, not cache shape\n // - `bindings`: mutable per-pipeline compatibility state\n // - `disableWarnings`: logging only, no rendering impact\n // - `vsConstants`, `fsConstants`: currently unused by pipeline creation\n const vsHash = props.vs ? this._getHash(props.vs.source) : 0;\n const fsHash = props.fs ? this._getHash(props.fs.source) : 0;\n const varyingHash = this._getWebGLVaryingHash(props);\n const shaderLayoutHash = this._getHash(JSON.stringify(props.shaderLayout));\n const bufferLayoutHash = this._getHash(JSON.stringify(props.bufferLayout));\n\n const {type} = this.device;\n switch (type) {\n case 'webgl':\n // WebGL wrappers preserve default topology and parameter semantics for direct\n // callers, even though the underlying linked program may be shared separately.\n // Future WebGL-only additions here must not turn wrapper reuse into a prerequisite\n // for shared `WebGLProgram` reuse.\n const webglParameterHash = this._getHash(JSON.stringify(props.parameters));\n return `${type}/R/${vsHash}/${fsHash}V${varyingHash}T${props.topology}P${webglParameterHash}SL${shaderLayoutHash}BL${bufferLayoutHash}`;\n\n case 'webgpu':\n default:\n // On WebGPU we need to rebuild the pipeline if topology, entry points,\n // shader/layout data, parameters, bufferLayout or attachment formats change.\n // Attachment formats must stay in the key so screen and offscreen passes do not\n // accidentally alias the same cached `GPURenderPipeline`.\n const entryPointHash = this._getHash(\n JSON.stringify({\n vertexEntryPoint: props.vertexEntryPoint,\n fragmentEntryPoint: props.fragmentEntryPoint\n })\n );\n const parameterHash = this._getHash(JSON.stringify(props.parameters));\n const attachmentHash = this._getWebGPUAttachmentHash(props);\n // TODO - Can json.stringify() generate different strings for equivalent objects if order of params is different?\n // create a deepHash() to deduplicate?\n return `${type}/R/${vsHash}/${fsHash}V${varyingHash}T${props.topology}EP${entryPointHash}P${parameterHash}SL${shaderLayoutHash}BL${bufferLayoutHash}A${attachmentHash}`;\n }\n }\n\n // This is the only gate for shared `WebGLProgram` reuse.\n // Only include inputs that affect program linking or transform-feedback linkage.\n // Wrapper-only concerns such as topology, parameters, attachment formats and layout\n // overrides must not be added here.\n private _hashSharedRenderPipeline(props: RenderPipelineProps): string {\n const vsHash = props.vs ? this._getHash(props.vs.source) : 0;\n const fsHash = props.fs ? this._getHash(props.fs.source) : 0;\n const varyingHash = this._getWebGLVaryingHash(props);\n return `webgl/S/${vsHash}/${fsHash}V${varyingHash}`;\n }\n\n private _getHash(key: string): number {\n if (this._hashes[key] === undefined) {\n this._hashes[key] = this._hashCounter++;\n }\n return this._hashes[key];\n }\n\n private _getWebGLVaryingHash(props: RenderPipelineProps): number {\n const {varyings = [], bufferMode = null} = props;\n return this._getHash(JSON.stringify({varyings, bufferMode}));\n }\n\n private _getWebGPUAttachmentHash(props: RenderPipelineProps): number {\n const colorAttachmentFormats = props.colorAttachmentFormats ?? [\n this.device.preferredColorFormat\n ];\n const depthStencilAttachmentFormat = props.parameters?.depthWriteEnabled\n ? props.depthStencilAttachmentFormat || this.device.preferredDepthFormat\n : null;\n\n return this._getHash(\n JSON.stringify({\n colorAttachmentFormats,\n depthStencilAttachmentFormat\n })\n );\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Device} from '../adapter/device';\nimport {Shader, type ShaderProps} from '../adapter/resources/shader';\nimport {log} from '../utils/log';\nimport type {CoreModuleState} from './core-module-state';\n\ntype CacheItem = {resource: Shader; useCount: number};\n\n/** Manages a cached pool of Shaders for reuse. */\nexport class ShaderFactory {\n static readonly defaultProps: Required = {...Shader.defaultProps};\n\n /** Returns the default ShaderFactory for the given {@link Device}, creating one if necessary. */\n static getDefaultShaderFactory(device: Device): ShaderFactory {\n const moduleData = device.getModuleData('@luma.gl/core');\n moduleData.defaultShaderFactory ||= new ShaderFactory(device);\n return moduleData.defaultShaderFactory;\n }\n\n public readonly device: Device;\n\n private readonly _cache: Record = {};\n\n get [Symbol.toStringTag](): string {\n return 'ShaderFactory';\n }\n\n toString(): string {\n return `${this[Symbol.toStringTag]}(${this.device.id})`;\n }\n\n /** @internal */\n constructor(device: Device) {\n this.device = device;\n }\n\n /** Requests a {@link Shader} from the cache, creating a new Shader only if necessary. */\n createShader(props: ShaderProps): Shader {\n if (!this.device.props._cacheShaders) {\n return this.device.createShader(props);\n }\n\n const key = this._hashShader(props);\n\n let cacheEntry = this._cache[key];\n if (!cacheEntry) {\n const resource = this.device.createShader({\n ...props,\n id: props.id ? `${props.id}-cached` : undefined\n });\n this._cache[key] = cacheEntry = {resource, useCount: 1};\n if (this.device.props.debugFactories) {\n log.log(3, `${this}: Created new shader ${resource.id}`)();\n }\n } else {\n cacheEntry.useCount++;\n if (this.device.props.debugFactories) {\n log.log(\n 3,\n `${this}: Reusing shader ${cacheEntry.resource.id} count=${cacheEntry.useCount}`\n )();\n }\n }\n\n return cacheEntry.resource;\n }\n\n /** Releases a previously-requested {@link Shader}, destroying it if no users remain. */\n release(shader: Shader): void {\n if (!this.device.props._cacheShaders) {\n shader.destroy();\n return;\n }\n\n const key = this._hashShader(shader);\n const cacheEntry = this._cache[key];\n if (cacheEntry) {\n cacheEntry.useCount--;\n if (cacheEntry.useCount === 0) {\n if (this.device.props._destroyShaders) {\n delete this._cache[key];\n cacheEntry.resource.destroy();\n if (this.device.props.debugFactories) {\n log.log(3, `${this}: Releasing shader ${shader.id}, destroyed`)();\n }\n }\n } else if (cacheEntry.useCount < 0) {\n throw new Error(`ShaderFactory: Shader ${shader.id} released too many times`);\n } else if (this.device.props.debugFactories) {\n log.log(3, `${this}: Releasing shader ${shader.id} count=${cacheEntry.useCount}`)();\n }\n }\n }\n\n // PRIVATE\n\n protected _hashShader(value: Shader | ShaderProps): string {\n return `${value.stage}:${value.source}`;\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {\n BindingDeclaration,\n Bindings,\n BindingsByGroup,\n ComputeShaderLayout,\n ShaderLayout\n} from '../adapter/types/shader-layout';\nimport {log} from '../utils/log';\n\ntype AnyShaderLayout = Pick;\n\nexport function getShaderLayoutBinding(\n shaderLayout: AnyShaderLayout,\n bindingName: string,\n options?: {ignoreWarnings?: boolean}\n): BindingDeclaration | null {\n const bindingLayout = shaderLayout.bindings.find(\n binding =>\n binding.name === bindingName ||\n `${binding.name.toLocaleLowerCase()}uniforms` === bindingName.toLocaleLowerCase()\n );\n\n if (!bindingLayout && !options?.ignoreWarnings) {\n log.warn(`Binding ${bindingName} not set: Not found in shader layout.`)();\n }\n\n return bindingLayout || null;\n}\n\nexport function normalizeBindingsByGroup(\n shaderLayout: AnyShaderLayout,\n bindingsOrBindGroups?: Bindings | BindingsByGroup\n): BindingsByGroup {\n if (!bindingsOrBindGroups) {\n return {};\n }\n\n if (areBindingsGrouped(bindingsOrBindGroups)) {\n const bindGroups = bindingsOrBindGroups as BindingsByGroup;\n return Object.fromEntries(\n Object.entries(bindGroups).map(([group, bindings]) => [Number(group), {...bindings}])\n ) as BindingsByGroup;\n }\n\n const bindGroups: BindingsByGroup = {};\n for (const [bindingName, binding] of Object.entries(bindingsOrBindGroups as Bindings)) {\n const bindingLayout = getShaderLayoutBinding(shaderLayout, bindingName);\n const group = bindingLayout?.group ?? 0;\n bindGroups[group] ||= {};\n bindGroups[group][bindingName] = binding;\n }\n\n return bindGroups;\n}\n\nexport function flattenBindingsByGroup(bindGroups: BindingsByGroup): Bindings {\n const bindings: Bindings = {};\n for (const groupBindings of Object.values(bindGroups)) {\n Object.assign(bindings, groupBindings);\n }\n return bindings;\n}\n\nfunction areBindingsGrouped(bindingsOrBindGroups: Bindings | BindingsByGroup): boolean {\n const keys = Object.keys(bindingsOrBindGroups);\n return keys.length > 0 && keys.every(key => /^\\d+$/.test(key));\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {NumberArray4, TypedArray} from '@math.gl/types';\nimport type {Device} from '../device';\nimport type {RenderPassParameters} from '../types/parameters';\n// import {Binding} from '../types/shader-layout';\nimport {Resource, ResourceProps} from './resource';\nimport {Framebuffer} from './framebuffer';\nimport {QuerySet} from './query-set';\n\n/**\n * Properties for a RenderPass instance is a required parameter to all draw calls.\n */\nexport type RenderPassProps = ResourceProps & {\n /** Framebuffer specifies which textures to render into. Default gets framebuffer from canvas context. */\n framebuffer?: Framebuffer | null;\n /** Control viewport, scissor rect, blend constant and stencil ref */\n parameters?: RenderPassParameters;\n\n // TODO - API needs to be able to control multiple render targets\n\n /** Clear value for color attachment, or false to preserve the previous value */\n clearColor?: NumberArray4 | TypedArray | false;\n /** Experimental: Clear color values for multiple color attachments. Must specify typed arrays. props.clearColor will be ignored. */\n clearColors?: (TypedArray | false)[];\n /** Clear value for depth attachment (true === `1`), or false to preserve the previous value. Must be between 0.0 (near) and 1.0 (far), inclusive. */\n clearDepth?: number | false;\n /** Clear value for stencil attachment (true === `0`), or false to preserve the previous value. Converted to the type and number of LSBs as the number of bits in the stencil aspect */\n clearStencil?: number | false;\n\n /** Indicates that the depth component is read only. */\n depthReadOnly?: boolean;\n /** Indicates that the stencil component is read only. */\n stencilReadOnly?: boolean;\n\n /** Whether to disable / discard the output of the rasterizer */\n discard?: boolean;\n\n /** QuerySet to write begin/end timestamps to */\n occlusionQuerySet?: QuerySet;\n /** QuerySet to write begin/end timestamps to */\n timestampQuerySet?: QuerySet;\n /** QuerySet index to write begin timestamp to. No timestamp is written if not provided. */\n beginTimestampIndex?: number;\n /** QuerySet index to write end timestamp to. No timestamp is written if not provided. */\n endTimestampIndex?: number;\n};\n\n/**\n * A RenderPass instance is a required parameter to all draw calls.\n *\n * It holds a combination of\n * - render targets (specified via a framebuffer)\n * - clear colors, read/write, discard information for the framebuffer attachments\n * - a couple of mutable parameters ()\n */\nexport abstract class RenderPass extends Resource {\n /** TODO - should be [0, 0, 0, 0], update once deck.gl tests run clean */\n static defaultClearColor: [number, number, number, number] = [0, 0, 0, 1];\n /** Depth 1.0 represents the far plance */\n static defaultClearDepth = 1;\n /** Clears all stencil bits */\n static defaultClearStencil = 0;\n\n override get [Symbol.toStringTag](): string {\n return 'RenderPass';\n }\n\n constructor(device: Device, props: RenderPassProps) {\n props = RenderPass.normalizeProps(device, props);\n super(device, props, RenderPass.defaultProps);\n }\n\n /** Call when rendering is done in this pass. */\n abstract end(): void;\n\n /** A few parameters can be changed at any time (viewport, scissorRect, blendColor, stencilReference) */\n abstract setParameters(parameters: RenderPassParameters): void;\n\n // executeBundles(bundles: Iterable): void;\n\n /** Being an occlusion query. Value will be stored in the occlusionQuerySet at the index. Occlusion queries cannot be nested. */\n abstract beginOcclusionQuery(queryIndex: number): void;\n /** End an occlusion query. Stores result in the index specified in beginOcclusionQuery. */\n abstract endOcclusionQuery(): void;\n\n /** Begins a labeled debug group containing subsequent commands */\n abstract pushDebugGroup(groupLabel: string): void;\n /** Ends the labeled debug group most recently started by pushDebugGroup() */\n abstract popDebugGroup(): void;\n /** Marks a point in a stream of commands with a label */\n abstract insertDebugMarker(markerLabel: string): void;\n\n protected static normalizeProps(device: Device, props: RenderPassProps): RenderPassProps {\n return props;\n }\n\n /** Default properties for RenderPass */\n static override defaultProps: Required = {\n ...Resource.defaultProps,\n framebuffer: null,\n parameters: undefined!,\n clearColor: RenderPass.defaultClearColor,\n clearColors: undefined!,\n clearDepth: RenderPass.defaultClearDepth,\n clearStencil: RenderPass.defaultClearStencil,\n depthReadOnly: false,\n stencilReadOnly: false,\n discard: false,\n\n occlusionQuerySet: undefined!,\n timestampQuerySet: undefined!,\n beginTimestampIndex: undefined!,\n endTimestampIndex: undefined!\n };\n}\n\n// TODO - Can we align WebGL implementation with WebGPU API?\n// In WebGPU the following methods are on the renderpass instead of the renderpipeline\n// luma.gl keeps them on the pipeline for now, but that has some issues.\n\n// abstract setPipeline(pipeline: RenderPipeline): void {}\n// abstract setIndexBuffer()\n// abstract setVertexBuffer(slot: number, buffer: Buffer, offset: number): void;\n// abstract setBindings(bindings: Record): void;\n// abstract setParameters(parameters: RenderPassParameters);\n// abstract draw(options: {\n// abstract drawIndirect(indirectBuffer: GPUBuffer, indirectOffset: number): void;\n// abstract drawIndexedIndirect(indirectBuffer: GPUBuffer, indirectOffset: number): void;\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// import type {TypedArray} from '@math.gl/types';\nimport {Device} from '../device';\nimport {Resource, ResourceProps} from './resource';\nimport {QuerySet} from './query-set';\nimport {Buffer} from './buffer';\nimport {Texture} from './texture';\nimport type {RenderPass, RenderPassProps} from './render-pass';\nimport type {ComputePass, ComputePassProps} from './compute-pass';\nimport type {CommandBuffer, CommandBufferProps} from './command-buffer';\n\n// WEBGPU COMMAND ENCODER OPERATIONS\n\nexport type CopyBufferToBufferOptions = {\n sourceBuffer: Buffer;\n sourceOffset?: number;\n destinationBuffer: Buffer;\n destinationOffset?: number;\n size: number;\n};\n\nexport type CopyBufferToTextureOptions = {\n sourceBuffer: Buffer;\n byteOffset?: number;\n destinationTexture: Texture;\n mipLevel?: number; // = 0;\n origin?: [number, number, number];\n aspect?: 'all' | 'stencil-only' | 'depth-only';\n bytesPerRow: number;\n rowsPerImage: number;\n size: [number, number, number];\n};\n\nexport type CopyTextureToBufferOptions = {\n /** Texture to copy to/from. */\n sourceTexture: Texture;\n /** Mip-map level of the texture to copy to/from. (Default 0) */\n mipLevel?: number;\n /** Defines the origin of the copy - the minimum corner of the texture sub-region to copy to/from.\n * Together with `copySize`, defines the full copy sub-region.\n */\n /** Defines which aspects of the texture to copy to/from. */\n aspect?: 'all' | 'stencil-only' | 'depth-only';\n\n /** Width to copy */\n width?: number;\n height?: number;\n depthOrArrayLayers?: number;\n origin?: [number, number, number];\n\n /** Destination buffer */\n destinationBuffer: Buffer;\n /** Offset, in bytes, from the beginning of the buffer to the start of the image data (default 0) */\n byteOffset?: number;\n /**\n * The stride, in bytes, between the beginning of each block row and the subsequent block row.\n * Required if there are multiple block rows (i.e. the copy height or depth is more than one block).\n */\n bytesPerRow?: number;\n /**\n * Number of block rows per single image of the texture.\n * rowsPerImage × bytesPerRow is the stride, in bytes, between the beginning of each image of data and the subsequent image.\n * Required if there are multiple images (i.e. the copy depth is more than one).\n */\n rowsPerImage?: number;\n};\n\nexport type CopyTextureToTextureOptions = {\n /** Texture to copy to/from. */\n sourceTexture: Texture;\n /** Mip-map level of the texture to copy to/from. (Default 0) */\n mipLevel?: number;\n /** Defines the origin of the copy - the minimum corner of the texture sub-region to copy from. */\n origin?: [number, number, number];\n /** Defines which aspects of the {@link GPUImageCopyTexture#texture} to copy to/from. */\n aspect?: 'all' | 'stencil-only' | 'depth-only';\n\n /** Texture to copy to/from. */\n destinationTexture: Texture;\n /** Mip-map level of the texture to copy to/from. (Default 0) */\n destinationMipLevel?: number;\n /** Defines the origin of the copy - the minimum corner of the texture sub-region to copy to. */\n destinationOrigin?: [number, number, number];\n /** Defines which aspects of the {@link GPUImageCopyTexture#texture} to copy to/from. */\n destinationAspect?: 'all' | 'stencil-only' | 'depth-only';\n\n /** Width to copy */\n width?: number;\n height?: number;\n depthOrArrayLayers?: number;\n};\n\n// ADDITIONAL COMMAND ENCODER OPERATIONS DEFINED BY LUMA.GL\n\n/** Options for clearing a texture mip level */\nexport type ClearTextureOptions = {\n /** Texture to Clear. */\n texture: Texture;\n /** Mip-map level of the texture clear. (Default 0) */\n mipLevel?: number;\n /** Defines which aspects of the Texture to clear. */\n aspect?: 'all' | 'stencil-only' | 'depth-only';\n};\n\n// export type WriteBufferOptions = {\n// buffer: Buffer;\n// bufferOffset?: number;\n// data: BufferSource;\n// dataOffset?: number;\n// size?: number;\n// };\n\n// export type TextureWriteOptions = {\n// destination: Texture;\n// mipLevel?: number; // = 0;\n// origin?: [number, number, number] | number[];\n// aspect?: 'all' | 'stencil-only' | 'depth-only';\n// data: BufferSource;\n// // dataLayout;\n// offset: number;\n// bytesPerRow: number;\n// rowsPerImage: number;\n// size: [number, number, number] | number[];\n// };\n\nexport type CommandEncoderProps = ResourceProps & {\n measureExecutionTime?: boolean;\n timeProfilingQuerySet?: QuerySet | null;\n};\n\ntype PassWithTimestamps = {\n timestampQuerySet?: QuerySet;\n beginTimestampIndex?: number;\n endTimestampIndex?: number;\n};\n\n/**\n * Records commands onto a single backend command encoder and can finish them into one command\n * buffer. Resource helpers invoked through a CommandEncoder must record onto that encoder rather\n * than allocating hidden encoders or submitting work eagerly.\n */\nexport abstract class CommandEncoder extends Resource {\n override get [Symbol.toStringTag](): string {\n return 'CommandEncoder';\n }\n\n protected _timeProfilingQuerySet: QuerySet | null = null;\n protected _timeProfilingSlotCount: number = 0;\n _gpuTimeMs?: number;\n\n constructor(device: Device, props: CommandEncoderProps) {\n super(device, props, CommandEncoder.defaultProps);\n this._timeProfilingQuerySet = props.timeProfilingQuerySet ?? null;\n this._timeProfilingSlotCount = 0;\n this._gpuTimeMs = undefined;\n }\n\n /** Completes recording of the commands sequence */\n abstract finish(props?: CommandBufferProps): CommandBuffer;\n\n /** Create a RenderPass using the default CommandEncoder */\n abstract beginRenderPass(props?: RenderPassProps): RenderPass;\n\n /** Create a ComputePass using the default CommandEncoder*/\n abstract beginComputePass(props?: ComputePassProps): ComputePass;\n\n /** Add a command that that copies data from a sub-region of a Buffer to a sub-region of another Buffer. */\n abstract copyBufferToBuffer(options: CopyBufferToBufferOptions): void;\n\n /** Add a command that copies data from a sub-region of a GPUBuffer to a sub-region of one or multiple continuous texture subresources. */\n abstract copyBufferToTexture(options: CopyBufferToTextureOptions): void;\n\n /** Add a command that copies data from a sub-region of one or multiple continuous texture subresources to a sub-region of a Buffer. */\n abstract copyTextureToBuffer(options: CopyTextureToBufferOptions): void;\n\n /** Add a command that copies data from a sub-region of one or multiple contiguous texture subresources to another sub-region of one or multiple continuous texture subresources. */\n abstract copyTextureToTexture(options: CopyTextureToTextureOptions): void;\n\n /** Add a command that clears a texture mip level. */\n // abstract clearTexture(options: ClearTextureOptions): void;\n\n // abstract readTexture(options: TextureReadOptions): Promise;\n\n /** Reads results from a query set into a GPU buffer. Values are 64 bits so byteLength must be querySet.props.count * 8 */\n abstract resolveQuerySet(\n querySet: QuerySet,\n destination: Buffer,\n options?: {\n firstQuery?: number;\n queryCount?: number;\n destinationOffset?: number;\n }\n ): void;\n\n /**\n * Reads all resolved timestamp pairs on the current profiler query set and caches the sum\n * as milliseconds on this encoder.\n */\n async resolveTimeProfilingQuerySet(): Promise {\n this._gpuTimeMs = undefined;\n\n if (!this._timeProfilingQuerySet) {\n return;\n }\n\n const pairCount = Math.floor(this._timeProfilingSlotCount / 2);\n if (pairCount <= 0) {\n return;\n }\n\n const queryCount = pairCount * 2;\n const results = await this._timeProfilingQuerySet.readResults({\n firstQuery: 0,\n queryCount\n });\n\n let totalDurationNanoseconds = 0n;\n for (let queryIndex = 0; queryIndex < queryCount; queryIndex += 2) {\n totalDurationNanoseconds += results[queryIndex + 1] - results[queryIndex];\n }\n\n this._gpuTimeMs = Number(totalDurationNanoseconds) / 1e6;\n }\n\n /** Returns the number of query slots consumed by automatic pass profiling on this encoder. */\n getTimeProfilingSlotCount(): number {\n return this._timeProfilingSlotCount;\n }\n\n getTimeProfilingQuerySet(): QuerySet | null {\n return this._timeProfilingQuerySet;\n }\n\n /** Internal helper for auto-assigning timestamp slots to render/compute passes on this encoder. */\n protected _applyTimeProfilingToPassProps

(props?: P): P {\n const passProps = (props || {}) as P;\n\n if (!this._supportsTimestampQueries() || !this._timeProfilingQuerySet) {\n return passProps;\n }\n\n if (\n passProps.timestampQuerySet !== undefined ||\n passProps.beginTimestampIndex !== undefined ||\n passProps.endTimestampIndex !== undefined\n ) {\n return passProps;\n }\n\n const beginTimestampIndex = this._timeProfilingSlotCount;\n if (beginTimestampIndex + 1 >= this._timeProfilingQuerySet.props.count) {\n return passProps;\n }\n\n this._timeProfilingSlotCount += 2;\n\n return {\n ...passProps,\n timestampQuerySet: this._timeProfilingQuerySet,\n beginTimestampIndex,\n endTimestampIndex: beginTimestampIndex + 1\n };\n }\n\n protected _supportsTimestampQueries(): boolean {\n return this.device.features.has('timestamp-query');\n }\n\n /** Begins a labeled debug group containing subsequent commands */\n abstract pushDebugGroup(groupLabel: string): void;\n /** Ends the labeled debug group most recently started by pushDebugGroup() */\n abstract popDebugGroup(): void;\n /** Marks a point in a stream of commands with a label */\n abstract insertDebugMarker(markerLabel: string): void;\n\n // TODO - luma.gl has these on the device, should we align with WebGPU API?\n // beginRenderPass(GPURenderPassDescriptor descriptor): GPURenderPassEncoder;\n // beginComputePass(optional GPUComputePassDescriptor descriptor = {}): GPUComputePassEncoder;\n\n static override defaultProps: Required = {\n ...Resource.defaultProps,\n measureExecutionTime: undefined!,\n timeProfilingQuerySet: undefined!\n };\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Device} from '../device';\nimport {Resource, ResourceProps} from './resource';\n\n// interface Queue {\n// submit(commandBuffers);\n\n// // onSubmittedWorkDone(): Promise;\n\n// writeBuffer(options: WriteBufferOptions): void;\n// writeTexture(options: TextureWriteOptions): void;\n\n// // copyExternalImageToTexture(\n// // GPUImageCopyExternalImage source,\n// // GPUImageCopyTextureTagged destination,\n// // GPUExtent3D copySize\n// // ): void;\n// }\n\nexport type CommandBufferProps = ResourceProps & {};\n\n/**\n * Represents the finished contents of exactly one CommandEncoder. Backends may store native\n * command buffers or replayable command lists internally, but submission must preserve the same\n * recorded command ordering.\n */\nexport abstract class CommandBuffer extends Resource {\n override get [Symbol.toStringTag](): string {\n return 'CommandBuffer';\n }\n\n constructor(device: Device, props: CommandBufferProps) {\n super(device, props, CommandBuffer.defaultProps);\n }\n\n static override defaultProps: Required = {\n ...Resource.defaultProps\n };\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {type PrimitiveDataType} from '../data-types/data-types';\nimport {\n type VariableShaderType,\n type AttributeShaderType,\n type VariableShaderTypeAlias,\n type AttributeShaderTypeAlias\n} from './shader-types';\n\n/** Information extracted from a VariableShaderType constant */\nexport type VariableShaderTypeInfo = {\n type: PrimitiveDataType;\n components: number;\n};\n\n/** Information extracted from a AttributeShaderType constant */\nexport type AttributeShaderTypeInfo = {\n /** WGSL-style primitive data type, f32, i32, u32 */\n primitiveType: PrimitiveDataType;\n /** Whether this is a normalized integer (that must be used as float) */\n components: 1 | 2 | 3 | 4;\n /** Length in bytes of the data for one vertex */\n byteLength?: number;\n /** Whether this is for integer or float vert */\n integer: boolean;\n /** Whether this data type is signed */\n signed: boolean;\n};\n\n/** Split a uniform type string into type and components */\nexport function getVariableShaderTypeInfo(\n format: VariableShaderType | VariableShaderTypeAlias\n): VariableShaderTypeInfo {\n const resolvedFormat = resolveVariableShaderTypeAlias(format);\n const decoded = UNIFORM_FORMATS[resolvedFormat];\n if (!decoded) {\n throw new Error(`Unsupported variable shader type: ${format}`);\n }\n return decoded;\n}\n\n/** Decodes a vertex type, returning byte length and flags (integer, signed, normalized) */\nexport function getAttributeShaderTypeInfo(\n attributeType: AttributeShaderType | AttributeShaderTypeAlias\n): AttributeShaderTypeInfo {\n const resolvedAttributeType = resolveAttributeShaderTypeAlias(attributeType);\n const decoded = TYPE_INFO[resolvedAttributeType];\n if (!decoded) {\n throw new Error(`Unsupported attribute shader type: ${attributeType}`);\n }\n const [primitiveType, components] = decoded;\n const integer: boolean = primitiveType === 'i32' || primitiveType === 'u32';\n const signed: boolean = primitiveType !== 'u32';\n\n const byteLength = PRIMITIVE_TYPE_SIZES[primitiveType] * components;\n return {\n primitiveType,\n components,\n byteLength,\n integer,\n signed\n };\n}\n\nexport class ShaderTypeDecoder {\n getVariableShaderTypeInfo(\n format: VariableShaderType | VariableShaderTypeAlias\n ): VariableShaderTypeInfo {\n return getVariableShaderTypeInfo(format);\n }\n\n getAttributeShaderTypeInfo(\n attributeType: AttributeShaderType | AttributeShaderTypeAlias\n ): AttributeShaderTypeInfo {\n return getAttributeShaderTypeInfo(attributeType);\n }\n\n makeShaderAttributeType(\n primitiveType: PrimitiveDataType,\n components: 1 | 2 | 3 | 4\n ): AttributeShaderType {\n return makeShaderAttributeType(primitiveType, components);\n }\n\n resolveAttributeShaderTypeAlias(\n alias: AttributeShaderTypeAlias | AttributeShaderType\n ): AttributeShaderType {\n return resolveAttributeShaderTypeAlias(alias);\n }\n\n resolveVariableShaderTypeAlias(\n alias: VariableShaderTypeAlias | VariableShaderType\n ): VariableShaderType {\n return resolveVariableShaderTypeAlias(alias);\n }\n}\n\nexport function makeShaderAttributeType(\n primitiveType: PrimitiveDataType,\n components: 1 | 2 | 3 | 4\n): AttributeShaderType {\n return components === 1 ? primitiveType : `vec${components}<${primitiveType}>`;\n}\n\nexport function resolveAttributeShaderTypeAlias(\n alias: AttributeShaderTypeAlias | AttributeShaderType\n): AttributeShaderType {\n return WGSL_ATTRIBUTE_TYPE_ALIAS_MAP[alias as AttributeShaderTypeAlias] || alias;\n}\n\nexport function resolveVariableShaderTypeAlias(\n alias: VariableShaderTypeAlias | VariableShaderType\n): VariableShaderType {\n return WGSL_VARIABLE_TYPE_ALIAS_MAP[alias as VariableShaderTypeAlias] || alias;\n}\n\n/** Decoder for luma.gl shader types */\nexport const shaderTypeDecoder = new ShaderTypeDecoder();\n\n// TABLES\n\nconst PRIMITIVE_TYPE_SIZES: Record = {\n f32: 4,\n f16: 2,\n i32: 4,\n u32: 4\n // 'bool-webgl': 4,\n};\n\n/** All valid shader attribute types. A table guarantees exhaustive list and fast execution */\nconst TYPE_INFO: Record = {\n f32: ['f32', 1],\n 'vec2': ['f32', 2],\n 'vec3': ['f32', 3],\n 'vec4': ['f32', 4],\n f16: ['f16', 1],\n 'vec2': ['f16', 2],\n 'vec3': ['f16', 3],\n 'vec4': ['f16', 4],\n i32: ['i32', 1],\n 'vec2': ['i32', 2],\n 'vec3': ['i32', 3],\n 'vec4': ['i32', 4],\n u32: ['u32', 1],\n 'vec2': ['u32', 2],\n 'vec3': ['u32', 3],\n 'vec4': ['u32', 4]\n};\n\n/** @todo These tables are quite big, consider parsing type strings instead */\nconst UNIFORM_FORMATS: Record = {\n f32: {type: 'f32', components: 1},\n f16: {type: 'f16', components: 1},\n i32: {type: 'i32', components: 1},\n u32: {type: 'u32', components: 1},\n // 'bool-webgl': {type: 'bool-webgl', components: 1},\n 'vec2': {type: 'f32', components: 2},\n 'vec3': {type: 'f32', components: 3},\n 'vec4': {type: 'f32', components: 4},\n 'vec2': {type: 'f16', components: 2},\n 'vec3': {type: 'f16', components: 3},\n 'vec4': {type: 'f16', components: 4},\n 'vec2': {type: 'i32', components: 2},\n 'vec3': {type: 'i32', components: 3},\n 'vec4': {type: 'i32', components: 4},\n 'vec2': {type: 'u32', components: 2},\n 'vec3': {type: 'u32', components: 3},\n 'vec4': {type: 'u32', components: 4},\n\n 'mat2x2': {type: 'f32', components: 4},\n 'mat2x3': {type: 'f32', components: 6},\n 'mat2x4': {type: 'f32', components: 8},\n 'mat3x2': {type: 'f32', components: 6},\n 'mat3x3': {type: 'f32', components: 9},\n 'mat3x4': {type: 'f32', components: 12},\n 'mat4x2': {type: 'f32', components: 8},\n 'mat4x3': {type: 'f32', components: 12},\n 'mat4x4': {type: 'f32', components: 16},\n\n 'mat2x2': {type: 'f16', components: 4},\n 'mat2x3': {type: 'f16', components: 6},\n 'mat2x4': {type: 'f16', components: 8},\n 'mat3x2': {type: 'f16', components: 6},\n 'mat3x3': {type: 'f16', components: 9},\n 'mat3x4': {type: 'f16', components: 12},\n 'mat4x2': {type: 'f16', components: 8},\n 'mat4x3': {type: 'f16', components: 12},\n 'mat4x4': {type: 'f16', components: 16},\n\n 'mat2x2': {type: 'i32', components: 4},\n 'mat2x3': {type: 'i32', components: 6},\n 'mat2x4': {type: 'i32', components: 8},\n 'mat3x2': {type: 'i32', components: 6},\n 'mat3x3': {type: 'i32', components: 9},\n 'mat3x4': {type: 'i32', components: 12},\n 'mat4x2': {type: 'i32', components: 8},\n 'mat4x3': {type: 'i32', components: 12},\n 'mat4x4': {type: 'i32', components: 16},\n\n 'mat2x2': {type: 'u32', components: 4},\n 'mat2x3': {type: 'u32', components: 6},\n 'mat2x4': {type: 'u32', components: 8},\n 'mat3x2': {type: 'u32', components: 6},\n 'mat3x3': {type: 'u32', components: 9},\n 'mat3x4': {type: 'u32', components: 12},\n 'mat4x2': {type: 'u32', components: 8},\n 'mat4x3': {type: 'u32', components: 12},\n 'mat4x4': {type: 'u32', components: 16}\n};\n\n/** Predeclared aliases @see https://www.w3.org/TR/WGSL/#vector-types */\nexport const WGSL_ATTRIBUTE_TYPE_ALIAS_MAP: Record =\n {\n vec2i: 'vec2',\n vec3i: 'vec3',\n vec4i: 'vec4',\n vec2u: 'vec2',\n vec3u: 'vec3',\n vec4u: 'vec4',\n vec2f: 'vec2',\n vec3f: 'vec3',\n vec4f: 'vec4',\n // Requires the f16 extension.\n vec2h: 'vec2',\n vec3h: 'vec3',\n vec4h: 'vec4'\n };\n\n/** @todo These tables are quite big, consider parsing alias strings instead */\nexport const WGSL_VARIABLE_TYPE_ALIAS_MAP: Record = {\n vec2i: 'vec2',\n vec3i: 'vec3',\n vec4i: 'vec4',\n vec2u: 'vec2',\n vec3u: 'vec3',\n vec4u: 'vec4',\n vec2f: 'vec2',\n vec3f: 'vec3',\n vec4f: 'vec4',\n vec2h: 'vec2',\n vec3h: 'vec3',\n vec4h: 'vec4',\n mat2x2f: 'mat2x2',\n mat2x3f: 'mat2x3',\n mat2x4f: 'mat2x4',\n mat3x2f: 'mat3x2',\n mat3x3f: 'mat3x3',\n mat3x4f: 'mat3x4',\n mat4x2f: 'mat4x2',\n mat4x3f: 'mat4x3',\n mat4x4f: 'mat4x4',\n\n mat2x2i: 'mat2x2',\n mat2x3i: 'mat2x3',\n mat2x4i: 'mat2x4',\n mat3x2i: 'mat3x2',\n mat3x3i: 'mat3x3',\n mat3x4i: 'mat3x4',\n mat4x2i: 'mat4x2',\n mat4x3i: 'mat4x3',\n mat4x4i: 'mat4x4',\n\n mat2x2u: 'mat2x2',\n mat2x3u: 'mat2x3',\n mat2x4u: 'mat2x4',\n mat3x2u: 'mat3x2',\n mat3x3u: 'mat3x3',\n mat3x4u: 'mat3x4',\n mat4x2u: 'mat4x2',\n mat4x3u: 'mat4x3',\n mat4x4u: 'mat4x4',\n\n mat2x2h: 'mat2x2',\n mat2x3h: 'mat2x3',\n mat2x4h: 'mat2x4',\n mat3x2h: 'mat3x2',\n mat3x3h: 'mat3x3',\n mat3x4h: 'mat3x4',\n mat4x2h: 'mat4x2',\n mat4x3h: 'mat4x3',\n mat4x4h: 'mat4x4'\n};\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {log} from '../utils/log';\nimport type {PrimitiveDataType, NormalizedDataType} from '../shadertypes/data-types/data-types';\nimport type {AttributeShaderType} from '../shadertypes/shader-types/shader-types';\nimport type {VertexFormat} from '../shadertypes/vertex-types/vertex-formats';\nimport {shaderTypeDecoder} from '../shadertypes/shader-types/shader-type-decoder';\nimport {vertexFormatDecoder} from '../shadertypes/vertex-types/vertex-format-decoder';\nimport type {ShaderLayout, AttributeDeclaration} from '../adapter/types/shader-layout';\nimport type {BufferLayout} from '../adapter/types/buffer-layout';\n\n/** Resolved info for a buffer / attribute combination to help backend configure it correctly */\nexport type AttributeInfo = {\n /** Attribute name */\n attributeName: string;\n /** Location in shader */\n location: number;\n /** Type / precision used in shader (buffer values may be converted) */\n shaderType: AttributeShaderType;\n /** Calculations are done in this type in the shader's attribute declaration */\n primitiveType: PrimitiveDataType;\n /** Components refer to the number of components in the shader's attribute declaration */\n shaderComponents: 1 | 2 | 3 | 4;\n /** It is the shader attribute declaration that determines whether GPU will process as integer or float */\n integer: boolean;\n\n /** BufferName */\n bufferName: string;\n /** Format of buffer data */\n vertexFormat: VertexFormat;\n /** Memory data type refers to the data type in the buffer */\n bufferDataType: NormalizedDataType;\n /** Components refer to the number of components in the buffer's vertex format */\n bufferComponents: 1 | 2 | 3 | 4;\n /** Normalization is encoded in the buffer layout's vertex format... */\n normalized: boolean;\n\n /** If not specified, the step mode is inferred from the attribute name in the shader (contains string instance) */\n stepMode: 'vertex' | 'instance';\n\n /** The byteOffset is encoded in or calculated from the buffer layout */\n byteOffset: number;\n /** The byteStride is encoded in or calculated from the buffer layout */\n byteStride: number;\n};\n\ntype BufferAttributeInfo = {\n attributeName: string;\n bufferName: string;\n stepMode?: 'vertex' | 'instance';\n vertexFormat: VertexFormat;\n byteOffset: number;\n byteStride: number;\n};\n\n/**\n * Map from \"attribute names\" to \"resolved attribute infos\"\n * containing information about both buffer layouts and shader attribute declarations\n */\nexport function getAttributeInfosFromLayouts(\n shaderLayout: ShaderLayout,\n bufferLayout: BufferLayout[]\n): Record {\n const attributeInfos: Record = {};\n for (const attribute of shaderLayout.attributes) {\n const attributeInfo = getAttributeInfoFromLayouts(shaderLayout, bufferLayout, attribute.name);\n if (attributeInfo) {\n attributeInfos[attribute.name] = attributeInfo;\n }\n }\n return attributeInfos;\n}\n\n/**\n * Array indexed by \"location\" holding \"resolved attribute infos\"\n */\nexport function getAttributeInfosByLocation(\n shaderLayout: ShaderLayout,\n bufferLayout: BufferLayout[],\n maxVertexAttributes: number = 16\n): AttributeInfo[] {\n const attributeInfos = getAttributeInfosFromLayouts(shaderLayout, bufferLayout);\n const locationInfos: AttributeInfo[] = new Array(maxVertexAttributes).fill(null);\n for (const attributeInfo of Object.values(attributeInfos)) {\n locationInfos[attributeInfo.location] = attributeInfo;\n }\n return locationInfos;\n}\n\n/**\n * Get the combined information from a shader layout and a buffer layout for a specific attribute\n */\nfunction getAttributeInfoFromLayouts(\n shaderLayout: ShaderLayout,\n bufferLayout: BufferLayout[],\n name: string\n): AttributeInfo | null {\n const shaderDeclaration = getAttributeFromShaderLayout(shaderLayout, name);\n const bufferMapping: BufferAttributeInfo | null = getAttributeFromBufferLayout(\n bufferLayout,\n name\n );\n\n // TODO should no longer happen\n if (!shaderDeclaration) {\n // || !bufferMapping\n return null;\n }\n\n const attributeTypeInfo = shaderTypeDecoder.getAttributeShaderTypeInfo(shaderDeclaration.type);\n const defaultVertexFormat = vertexFormatDecoder.getCompatibleVertexFormat(attributeTypeInfo);\n const vertexFormat = bufferMapping?.vertexFormat || defaultVertexFormat;\n const vertexFormatInfo = vertexFormatDecoder.getVertexFormatInfo(vertexFormat);\n\n return {\n attributeName: bufferMapping?.attributeName || shaderDeclaration.name,\n bufferName: bufferMapping?.bufferName || shaderDeclaration.name,\n location: shaderDeclaration.location,\n shaderType: shaderDeclaration.type,\n primitiveType: attributeTypeInfo.primitiveType,\n shaderComponents: attributeTypeInfo.components,\n vertexFormat,\n bufferDataType: vertexFormatInfo.type,\n bufferComponents: vertexFormatInfo.components,\n // normalized is a property of the buffer's vertex format\n normalized: vertexFormatInfo.normalized,\n // integer is a property of the shader declaration\n integer: attributeTypeInfo.integer,\n stepMode: bufferMapping?.stepMode || shaderDeclaration.stepMode || 'vertex',\n byteOffset: bufferMapping?.byteOffset || 0,\n byteStride: bufferMapping?.byteStride || 0\n };\n}\n\nfunction getAttributeFromShaderLayout(\n shaderLayout: ShaderLayout,\n name: string\n): AttributeDeclaration | null {\n const attribute = shaderLayout.attributes.find(attr => attr.name === name);\n if (!attribute) {\n log.warn(`shader layout attribute \"${name}\" not present in shader`);\n }\n return attribute || null;\n}\n\nfunction getAttributeFromBufferLayout(\n bufferLayouts: BufferLayout[],\n name: string\n): BufferAttributeInfo | null {\n // Check that bufferLayouts are valid (each either has format or attribute)\n checkBufferLayouts(bufferLayouts);\n\n let bufferLayoutInfo = getAttributeFromShortHand(bufferLayouts, name);\n if (bufferLayoutInfo) {\n return bufferLayoutInfo;\n }\n\n bufferLayoutInfo = getAttributeFromAttributesList(bufferLayouts, name);\n if (bufferLayoutInfo) {\n return bufferLayoutInfo;\n }\n\n // Didn't find...\n log.warn(`layout for attribute \"${name}\" not present in buffer layout`);\n return null;\n}\n\n/** Check that bufferLayouts are valid (each either has format or attribute) */\nfunction checkBufferLayouts(bufferLayouts: BufferLayout[]) {\n for (const bufferLayout of bufferLayouts) {\n if (\n (bufferLayout.attributes && bufferLayout.format) ||\n (!bufferLayout.attributes && !bufferLayout.format)\n ) {\n log.warn(`BufferLayout ${name} must have either 'attributes' or 'format' field`);\n }\n }\n}\n\n/** Get attribute from format shorthand if specified */\nfunction getAttributeFromShortHand(\n bufferLayouts: BufferLayout[],\n name: string\n): BufferAttributeInfo | null {\n for (const bufferLayout of bufferLayouts) {\n if (bufferLayout.format && bufferLayout.name === name) {\n return {\n attributeName: bufferLayout.name,\n bufferName: name,\n stepMode: bufferLayout.stepMode,\n vertexFormat: bufferLayout.format,\n // If offset is needed, use `attributes` field.\n byteOffset: 0,\n byteStride: bufferLayout.byteStride || 0\n };\n }\n }\n return null;\n}\n\n/**\n * Search attribute mappings (e.g. interleaved attributes) for buffer mapping.\n * Not the name of the buffer might be the same as one of the interleaved attributes.\n */\nfunction getAttributeFromAttributesList(\n bufferLayouts: BufferLayout[],\n name: string\n): BufferAttributeInfo | null {\n for (const bufferLayout of bufferLayouts) {\n let byteStride: number | undefined = bufferLayout.byteStride;\n\n // Calculate a default byte stride if not provided\n if (typeof bufferLayout.byteStride !== 'number') {\n for (const attributeMapping of bufferLayout.attributes || []) {\n const info = vertexFormatDecoder.getVertexFormatInfo(attributeMapping.format);\n // @ts-ignore\n byteStride += info.byteLength;\n }\n }\n\n const attributeMapping = bufferLayout.attributes?.find(mapping => mapping.attribute === name);\n if (attributeMapping) {\n return {\n attributeName: attributeMapping.attribute,\n bufferName: bufferLayout.name,\n stepMode: bufferLayout.stepMode,\n vertexFormat: attributeMapping.format,\n byteOffset: attributeMapping.byteOffset,\n // @ts-ignore\n byteStride\n };\n }\n }\n\n return null;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {TypedArray} from '../../types';\nimport {\n AttributeInfo,\n getAttributeInfosByLocation\n} from '../../adapter-utils/get-attribute-from-layouts';\nimport type {Device} from '../device';\nimport type {Buffer} from './buffer';\nimport type {RenderPass} from './render-pass';\nimport {Resource, ResourceProps} from './resource';\nimport {ShaderLayout} from '../types/shader-layout';\nimport {BufferLayout} from '../types/buffer-layout';\n\n/** Properties for initializing a VertexArray */\nexport type VertexArrayProps = ResourceProps & {\n shaderLayout: ShaderLayout;\n bufferLayout: BufferLayout[];\n};\n\n/**\n * Stores attribute bindings.\n * Makes it easy to share a render pipeline and use separate vertex arrays.\n * @note On WebGL, VertexArray allows non-constant bindings to be performed in advance\n * reducing the number of WebGL calls per draw call.\n * @note On WebGPU this is just a convenience class that collects the bindings.\n */\nexport abstract class VertexArray extends Resource {\n static override defaultProps: Required = {\n ...Resource.defaultProps,\n shaderLayout: undefined!,\n bufferLayout: []\n };\n\n override get [Symbol.toStringTag](): string {\n return 'VertexArray';\n }\n\n /** Max number of vertex attributes */\n readonly maxVertexAttributes: number;\n /** Attribute infos indexed by location - TODO only needed by webgl module? */\n protected readonly attributeInfos: AttributeInfo[];\n\n /** Index buffer */\n indexBuffer: Buffer | null = null;\n /** Attributes indexed by buffer slot */\n attributes: (Buffer | TypedArray | null)[];\n\n constructor(device: Device, props: VertexArrayProps) {\n super(device, props, VertexArray.defaultProps);\n this.maxVertexAttributes = device.limits.maxVertexAttributes;\n this.attributes = new Array(this.maxVertexAttributes).fill(null);\n this.attributeInfos = getAttributeInfosByLocation(\n props.shaderLayout,\n props.bufferLayout,\n this.maxVertexAttributes\n );\n }\n\n /** Set attributes (stored on pipeline and set before each call) */\n abstract setIndexBuffer(indices: Buffer | null): void;\n /** Set attributes (stored on pipeline and set before each call) */\n abstract setBuffer(bufferSlot: number, buffer: Buffer | null): void;\n\n abstract bindBeforeRender(renderPass: RenderPass): void;\n abstract unbindAfterRender(renderPass: RenderPass): void;\n\n // DEPRECATED METHODS\n\n /** @deprecated Set constant attributes (WebGL only) */\n setConstantWebGL(location: number, value: TypedArray | null): void {\n this.device.reportError(new Error('constant attributes not supported'), this)();\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport {PrimitiveTopology} from '../types/parameters';\nimport {ShaderLayout} from '../types/shader-layout';\nimport type {Buffer} from './buffer';\nimport {Resource, ResourceProps} from './resource';\n\n/** For bindRange */\nexport type BufferRange = {\n buffer: Buffer;\n byteOffset?: number;\n byteLength?: number;\n};\n\n/** Configures a set of output buffers for pipeline (WebGL only) */\nexport type TransformFeedbackProps = ResourceProps & {\n /** Layout of shader (for varyings) */\n layout: ShaderLayout;\n /** Buffer bindings (for varyings) */\n buffers: Record;\n};\n\n/** Holds a set of output buffers for pipeline (WebGL only) */\nexport abstract class TransformFeedback extends Resource {\n static override defaultProps: Required = {\n ...Resource.defaultProps,\n layout: undefined!,\n buffers: {}\n };\n\n get [Symbol.toStringTag](): string {\n return 'TransformFeedback';\n }\n\n constructor(device: Device, props: TransformFeedbackProps) {\n super(device, props, TransformFeedback.defaultProps);\n }\n\n abstract begin(topology?: PrimitiveTopology): void;\n abstract end(): void;\n\n abstract setBuffers(buffers: Record): void;\n abstract setBuffer(locationOrName: string | number, bufferOrRange: Buffer | BufferRange): void;\n abstract getBuffer(locationOrName: string | number): Buffer | BufferRange | null;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport {Resource, ResourceProps} from './resource';\n\n/**\n * Properties for creating a QuerySet\n * - 'timestamp' - query the GPU timestamp counter at the start and end of render passes\n * timestamp queries are available if the 'timestamp-query' feature is present.\n * - 'occlusion' - query the number of fragment samples that pass all per-fragment tests for a set of drawing commands\n * including scissor, sample mask, alpha to coverage, stencil, and depth tests\n */\nexport type QuerySetProps = ResourceProps & {\n /**\n * The type of query set\n * occlusion - query the number of fragment samples that pass all the per-fragment tests for a set of drawing commands, including scissor, sample mask, alpha to coverage, stencil, and depth tests\n * timestamp - query the GPU timestamp counter. Timestamp queries are available if the\n * `timestamp-query` feature is present.\n */\n type: 'occlusion' | 'timestamp';\n /** The number of queries managed by the query set */\n count: number;\n};\n\n/** Immutable QuerySet object */\nexport abstract class QuerySet extends Resource {\n get [Symbol.toStringTag](): string {\n return 'QuerySet';\n }\n\n constructor(device: Device, props: QuerySetProps) {\n super(device, props, QuerySet.defaultProps);\n }\n\n static override defaultProps: Required = {\n ...Resource.defaultProps,\n type: undefined!,\n count: undefined!\n };\n\n /**\n * Returns true if the requested result has been captured and can be read without blocking.\n * Backends may implement this conservatively.\n */\n abstract isResultAvailable(queryIndex?: number): boolean;\n\n /** Reads query results as 64-bit values. */\n abstract readResults(options?: {firstQuery?: number; queryCount?: number}): Promise;\n\n /**\n * Reads a timestamp duration in milliseconds between a begin and end query index.\n * Portable duration profiling requires adjacent indices that identify one logical pair.\n */\n abstract readTimestampDuration(beginIndex: number, endIndex: number): Promise;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport {Resource, type ResourceProps} from './resource';\n\nexport type FenceProps = ResourceProps;\n\n/** Synchronization primitive that resolves when GPU work is completed */\nexport abstract class Fence extends Resource {\n static override defaultProps: Required = {\n ...Resource.defaultProps\n };\n\n override get [Symbol.toStringTag](): string {\n return 'Fence';\n }\n\n /** Promise that resolves when the fence is signaled */\n abstract readonly signaled: Promise;\n\n constructor(device: Device, props: FenceProps = {}) {\n super(device, props, Fence.defaultProps);\n }\n\n /** Destroy the fence and release any resources */\n abstract override destroy(): void;\n\n /** Check if the fence has been signaled */\n abstract isSignaled(): boolean;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {TypedArray, TypedArrayConstructor} from '../../types';\nimport {PrimitiveDataType, SignedDataType, NormalizedDataType, DataTypeInfo} from './data-types';\n\n/**\n * Gets info about a data type constant (signed or normalized)\n * @returns underlying primitive / signed types, byte length, normalization, integer, signed flags\n */\nexport function getDataTypeInfo(type: NormalizedDataType): DataTypeInfo {\n const normalized: boolean = type.includes('norm');\n const integer: boolean = !normalized && !type.startsWith('float');\n const signed: boolean = type.startsWith('s');\n const typeInfo = NORMALIZED_TYPE_MAP[type];\n const [signedType, primitiveType, byteLength] = typeInfo || ['uint8 ', 'i32', 1];\n return {\n signedType,\n primitiveType,\n byteLength,\n normalized,\n integer,\n signed\n };\n}\n\n/** Build a vertex format from a signed data type and a component */\nexport function getNormalizedDataType(signedDataType: SignedDataType): NormalizedDataType {\n const dataType: NormalizedDataType = signedDataType;\n // biome-ignore format: preserve layout\n switch (dataType) {\n case 'uint8': return 'unorm8';\n case 'sint8': return 'snorm8';\n case 'uint16': return 'unorm16';\n case 'sint16': return 'snorm16';\n default: return dataType;\n }\n}\n\n/** Align offset to 1, 2 or 4 elements (4, 8 or 16 bytes) */\nexport function alignTo(size: number, count: number): number {\n // biome-ignore format: preserve layout\n switch (count) {\n case 1: return size; // Pad upwards to even multiple of 2\n case 2: return size + (size % 2); // Pad upwards to even multiple of 2\n default: return size + ((4 - (size % 4)) % 4); // Pad upwards to even multiple of 4\n }\n}\n\n/** Returns the VariableShaderType that corresponds to a typed array */\nexport function getDataType(arrayOrType: TypedArray | TypedArrayConstructor): SignedDataType {\n const Constructor = ArrayBuffer.isView(arrayOrType) ? arrayOrType.constructor : arrayOrType;\n if (Constructor === Uint8ClampedArray) {\n return 'uint8';\n }\n const info = Object.values(NORMALIZED_TYPE_MAP).find(entry => Constructor === entry[4]);\n if (!info) {\n throw new Error(Constructor.name);\n }\n return info[0];\n}\n\n/** Returns the TypedArray that corresponds to a shader data type */\nexport function getTypedArrayConstructor(type: NormalizedDataType): TypedArrayConstructor {\n const [, , , , Constructor] = NORMALIZED_TYPE_MAP[type];\n return Constructor;\n}\n\nconst NORMALIZED_TYPE_MAP: Record<\n NormalizedDataType,\n [\n SignedDataType,\n PrimitiveDataType,\n bytes: 1 | 2 | 4,\n normalized: boolean,\n arrayConstructor: TypedArrayConstructor\n ]\n> = {\n uint8: ['uint8', 'u32', 1, false, Uint8Array],\n sint8: ['sint8', 'i32', 1, false, Int8Array],\n unorm8: ['uint8', 'f32', 1, true, Uint8Array],\n snorm8: ['sint8', 'f32', 1, true, Int8Array],\n uint16: ['uint16', 'u32', 2, false, Uint16Array],\n sint16: ['sint16', 'i32', 2, false, Int16Array],\n unorm16: ['uint16', 'u32', 2, true, Uint16Array],\n snorm16: ['sint16', 'i32', 2, true, Int16Array],\n float16: ['float16', 'f16', 2, false, Uint16Array],\n float32: ['float32', 'f32', 4, false, Float32Array],\n uint32: ['uint32', 'u32', 4, false, Uint32Array],\n sint32: ['sint32', 'i32', 4, false, Int32Array]\n};\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {PrimitiveDataType} from '../data-types/data-types';\nimport type {CompositeShaderType, VariableShaderType} from './shader-types';\nimport {alignTo} from '../data-types/decode-data-types';\nimport {getVariableShaderTypeInfo, resolveVariableShaderTypeAlias} from './shader-type-decoder';\n\n/**\n * Describes the packing for one flattened field in a shader block.\n *\n * Offsets, sizes, and strides are expressed in 32-bit words so the result can\n * be consumed directly by typed-array writers.\n */\nexport type ShaderBlockLayoutEntry = {\n /** Offset in 32-bit words from the start of the block. */\n offset: number;\n /** Occupied size in 32-bit words, excluding external array stride. */\n size: number;\n /** Number of logical scalar components in the declared value. */\n components: number;\n /** Number of matrix columns, or `1` for scalars and vectors. */\n columns: number;\n /** Number of rows in each column, or vector length for vectors. */\n rows: number;\n /** Distance between matrix columns in 32-bit words. */\n columnStride: number;\n /** Canonical shader type after alias resolution. */\n shaderType: VariableShaderType;\n /** Scalar data type used to write the value. */\n type: PrimitiveDataType;\n};\n\n/**\n * Options for {@link makeShaderBlockLayout}.\n */\nexport type ShaderBlockLayoutOptions = {\n /**\n * Packing rules to apply when building the layout.\n *\n * Defaults to `'std140'`.\n */\n layout?: 'std140' | 'wgsl-uniform' | 'wgsl-storage';\n};\n\n/**\n * Immutable layout metadata for a uniform or storage-style shader block.\n */\nexport type ShaderBlockLayout = {\n /** Packing rules used when this layout was created. */\n layout: 'std140' | 'wgsl-uniform' | 'wgsl-storage';\n /** Exact number of packed bytes required by the block. */\n byteLength: number;\n /** Original composite shader type declarations keyed by top-level field. */\n uniformTypes: Record;\n /** Flattened leaf field layouts keyed by field path. */\n fields: Record;\n};\n\n/**\n * Builds a deterministic shader-block layout from composite shader type declarations.\n *\n * The returned value is pure layout metadata. It records the packed field\n * offsets and exact packed byte length, but it does not allocate buffers or\n * serialize values.\n */\nexport function makeShaderBlockLayout(\n uniformTypes: Readonly>,\n options: ShaderBlockLayoutOptions = {}\n): ShaderBlockLayout {\n const copiedUniformTypes = {...uniformTypes};\n const layout = options.layout ?? 'std140';\n const fields: Record = {};\n\n let size = 0;\n for (const [key, uniformType] of Object.entries(copiedUniformTypes)) {\n size = addToLayout(fields, key, uniformType, size, layout);\n }\n\n size = alignTo(size, getTypeAlignment(copiedUniformTypes, layout));\n\n return {\n layout,\n byteLength: size * 4,\n uniformTypes: copiedUniformTypes,\n fields\n };\n}\n\n/**\n * Returns the layout metadata for a scalar, vector, or matrix leaf type.\n *\n * The result includes both the occupied size in 32-bit words and the alignment\n * requirement that must be applied before placing the value in a shader block.\n */\nexport function getLeafLayoutInfo(\n type: VariableShaderType,\n layout: 'std140' | 'wgsl-uniform' | 'wgsl-storage'\n): Omit & {alignment: 1 | 2 | 4} {\n const resolvedType = resolveVariableShaderTypeAlias(type);\n const decodedType = getVariableShaderTypeInfo(resolvedType);\n const matrixMatch = /^mat(\\d)x(\\d)<.+>$/.exec(resolvedType);\n\n if (matrixMatch) {\n const columns = Number(matrixMatch[1]);\n const rows = Number(matrixMatch[2]);\n const columnInfo = getVectorLayoutInfo(\n rows as 2 | 3 | 4,\n resolvedType,\n decodedType.type,\n layout\n );\n const columnStride = getMatrixColumnStride(columnInfo.size, columnInfo.alignment, layout);\n\n return {\n alignment: columnInfo.alignment,\n size: columns * columnStride,\n components: columns * rows,\n columns,\n rows,\n columnStride,\n shaderType: resolvedType,\n type: decodedType.type\n };\n }\n\n const vectorMatch = /^vec(\\d)<.+>$/.exec(resolvedType);\n if (vectorMatch) {\n return getVectorLayoutInfo(\n Number(vectorMatch[1]) as 2 | 3 | 4,\n resolvedType,\n decodedType.type,\n layout\n );\n }\n\n return {\n alignment: 1,\n size: 1,\n components: 1,\n columns: 1,\n rows: 1,\n columnStride: 1,\n shaderType: resolvedType,\n type: decodedType.type\n };\n}\n\n/**\n * Type guard for composite struct declarations.\n */\nexport function isCompositeShaderTypeStruct(\n value: CompositeShaderType\n): value is Record {\n return Boolean(value) && typeof value === 'object' && !Array.isArray(value);\n}\n\n/**\n * Recursively adds a composite type to the flattened field map.\n *\n * @returns The next free 32-bit-word offset after the inserted type.\n */\nfunction addToLayout(\n fields: Record,\n name: string,\n type: CompositeShaderType,\n offset: number,\n layout: 'std140' | 'wgsl-uniform' | 'wgsl-storage'\n): number {\n if (typeof type === 'string') {\n const info = getLeafLayoutInfo(type, layout);\n const alignedOffset = alignTo(offset, info.alignment);\n fields[name] = {\n offset: alignedOffset,\n ...info\n };\n return alignedOffset + info.size;\n }\n\n if (Array.isArray(type)) {\n if (Array.isArray(type[0])) {\n throw new Error(`Nested arrays are not supported for ${name}`);\n }\n\n const elementType = type[0] as CompositeShaderType;\n const length = type[1] as number;\n const stride = getArrayStride(elementType, layout);\n const arrayOffset = alignTo(offset, getTypeAlignment(type, layout));\n\n for (let i = 0; i < length; i++) {\n addToLayout(fields, `${name}[${i}]`, elementType, arrayOffset + i * stride, layout);\n }\n return arrayOffset + stride * length;\n }\n\n if (isCompositeShaderTypeStruct(type)) {\n const structAlignment = getTypeAlignment(type, layout);\n let structOffset = alignTo(offset, structAlignment);\n for (const [memberName, memberType] of Object.entries(type)) {\n structOffset = addToLayout(fields, `${name}.${memberName}`, memberType, structOffset, layout);\n }\n return alignTo(structOffset, structAlignment);\n }\n\n throw new Error(`Unsupported CompositeShaderType for ${name}`);\n}\n\n/**\n * Returns the occupied size of a composite type in 32-bit words.\n */\nfunction getTypeSize(\n type: CompositeShaderType,\n layout: 'std140' | 'wgsl-uniform' | 'wgsl-storage'\n): number {\n if (typeof type === 'string') {\n return getLeafLayoutInfo(type, layout).size;\n }\n\n if (Array.isArray(type)) {\n const elementType = type[0] as CompositeShaderType;\n const length = type[1] as number;\n\n if (Array.isArray(elementType)) {\n throw new Error('Nested arrays are not supported');\n }\n\n return getArrayStride(elementType, layout) * length;\n }\n\n let size = 0;\n for (const memberType of Object.values(type)) {\n const compositeMemberType = memberType as CompositeShaderType;\n size = alignTo(size, getTypeAlignment(compositeMemberType, layout));\n size += getTypeSize(compositeMemberType, layout);\n }\n\n return alignTo(size, getTypeAlignment(type, layout));\n}\n\n/**\n * Returns the required alignment of a composite type in 32-bit words.\n */\nfunction getTypeAlignment(\n type: CompositeShaderType,\n layout: 'std140' | 'wgsl-uniform' | 'wgsl-storage'\n): 1 | 2 | 4 {\n if (typeof type === 'string') {\n return getLeafLayoutInfo(type, layout).alignment;\n }\n\n if (Array.isArray(type)) {\n const elementType = type[0] as CompositeShaderType;\n const elementAlignment = getTypeAlignment(elementType, layout);\n return uses16ByteArrayAlignment(layout)\n ? (Math.max(elementAlignment, 4) as 1 | 2 | 4)\n : elementAlignment;\n }\n\n let maxAlignment: 1 | 2 | 4 = 1;\n for (const memberType of Object.values(type)) {\n const memberAlignment = getTypeAlignment(memberType as CompositeShaderType, layout);\n maxAlignment = Math.max(maxAlignment, memberAlignment) as 1 | 2 | 4;\n }\n\n return uses16ByteStructAlignment(layout)\n ? (Math.max(maxAlignment, 4) as 1 | 2 | 4)\n : maxAlignment;\n}\n\n/**\n * Returns the layout metadata for a vector leaf type.\n */\nfunction getVectorLayoutInfo(\n components: 2 | 3 | 4,\n shaderType: VariableShaderType,\n type: PrimitiveDataType,\n layout: 'std140' | 'wgsl-uniform' | 'wgsl-storage'\n): Omit & {alignment: 1 | 2 | 4} {\n return {\n alignment: components === 2 ? 2 : 4,\n size: components === 3 ? 3 : components,\n components,\n columns: 1,\n rows: components,\n columnStride: components === 3 ? 3 : components,\n shaderType,\n type\n };\n}\n\n/**\n * Returns the stride of an array element in 32-bit words.\n *\n * This includes any layout-specific padding between adjacent array elements.\n */\nfunction getArrayStride(\n elementType: CompositeShaderType,\n layout: 'std140' | 'wgsl-uniform' | 'wgsl-storage'\n): number {\n const elementSize = getTypeSize(elementType, layout);\n const elementAlignment = getTypeAlignment(elementType, layout);\n return getArrayLikeStride(elementSize, elementAlignment, layout);\n}\n\n/**\n * Returns the common stride rule shared by array-like elements in the target layout.\n */\nfunction getArrayLikeStride(\n size: number,\n alignment: 1 | 2 | 4,\n layout: 'std140' | 'wgsl-uniform' | 'wgsl-storage'\n): number {\n return alignTo(size, uses16ByteArrayAlignment(layout) ? 4 : alignment);\n}\n\n/**\n * Returns the stride of a matrix column in 32-bit words.\n */\nfunction getMatrixColumnStride(\n size: number,\n alignment: 1 | 2 | 4,\n layout: 'std140' | 'wgsl-uniform' | 'wgsl-storage'\n): number {\n return layout === 'std140' ? 4 : alignTo(size, alignment);\n}\n\n/**\n * Returns `true` when arrays must be rounded up to 16-byte boundaries.\n */\nfunction uses16ByteArrayAlignment(layout: 'std140' | 'wgsl-uniform' | 'wgsl-storage'): boolean {\n return layout === 'std140' || layout === 'wgsl-uniform';\n}\n\n/**\n * Returns `true` when structs must be rounded up to 16-byte boundaries.\n */\nfunction uses16ByteStructAlignment(layout: 'std140' | 'wgsl-uniform' | 'wgsl-storage'): boolean {\n return layout === 'std140' || layout === 'wgsl-uniform';\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {TypedArray} from '../types';\n\nlet arrayBuffer: ArrayBuffer;\n\nexport function getScratchArrayBuffer(byteLength: number): ArrayBuffer {\n if (!arrayBuffer || arrayBuffer.byteLength < byteLength) {\n arrayBuffer = new ArrayBuffer(byteLength);\n }\n return arrayBuffer;\n}\n\nexport function getScratchArray(Type: any, length: number): TypedArray {\n const scratchArrayBuffer = getScratchArrayBuffer(Type.BYTES_PER_ELEMENT * length);\n return new Type(scratchArrayBuffer, 0, length); // arrayBuffer, byteOffset, length (in elements)\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {TypedArray, NumberArray} from '../types';\n\n/**\n * Check is an array is a typed array\n * @param value value to be tested\n * @returns input as TypedArray, or null\n * @todo this should be provided by @math.gl/types\n */\nexport function isTypedArray(value: unknown): value is TypedArray {\n return ArrayBuffer.isView(value) && !(value instanceof DataView);\n}\n\n/**\n * Check is an array is a numeric array (typed array or array of numbers)\n * @param value value to be tested\n * @returns input as NumberArray, or null\n * @todo this should be provided by @math.gl/types\n */\nexport function isNumberArray(value: unknown): value is NumberArray {\n if (Array.isArray(value)) {\n return value.length === 0 || typeof value[0] === 'number';\n }\n return isTypedArray(value);\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {CompositeUniformValue, UniformValue} from '../adapter/types/uniforms';\nimport {getScratchArrayBuffer} from '../utils/array-utils-flat';\nimport {isNumberArray} from '../utils/is-array';\nimport {log} from '../utils/log';\nimport type {\n CompositeShaderType,\n VariableShaderType\n} from '../shadertypes/shader-types/shader-types';\nimport {\n getLeafLayoutInfo,\n isCompositeShaderTypeStruct,\n type ShaderBlockLayout\n} from '../shadertypes/shader-types/shader-block-layout';\n\n/**\n * Serializes nested JavaScript uniform values according to a {@link ShaderBlockLayout}.\n */\nexport class ShaderBlockWriter {\n /** Layout metadata used to flatten and serialize values. */\n readonly layout: ShaderBlockLayout;\n\n /**\n * Creates a writer for a precomputed shader-block layout.\n */\n constructor(layout: ShaderBlockLayout) {\n this.layout = layout;\n }\n\n /**\n * Returns `true` if the flattened layout contains the given field.\n */\n has(name: string): boolean {\n return Boolean(this.layout.fields[name]);\n }\n\n /**\n * Returns offset and size metadata for a flattened field.\n */\n get(name: string): {offset: number; size: number} | undefined {\n const entry = this.layout.fields[name];\n return entry ? {offset: entry.offset, size: entry.size} : undefined;\n }\n\n /**\n * Flattens nested composite values into leaf-path values understood by {@link UniformBlock}.\n *\n * Top-level values may be supplied either in nested object form matching the\n * declared composite shader types or as already-flattened leaf-path values.\n */\n getFlatUniformValues(\n uniformValues: Readonly>\n ): Record {\n const flattenedUniformValues: Record = {};\n\n for (const [name, value] of Object.entries(uniformValues)) {\n const uniformType = this.layout.uniformTypes[name];\n if (uniformType) {\n this._flattenCompositeValue(flattenedUniformValues, name, uniformType, value);\n } else if (this.layout.fields[name]) {\n flattenedUniformValues[name] = value as UniformValue;\n }\n }\n\n return flattenedUniformValues;\n }\n\n /**\n * Serializes the supplied values into buffer-backed binary data.\n *\n * The returned view length matches {@link ShaderBlockLayout.byteLength}, which\n * is the exact packed size of the block.\n */\n getData(uniformValues: Readonly>): Uint8Array {\n const buffer = getScratchArrayBuffer(this.layout.byteLength);\n new Uint8Array(buffer, 0, this.layout.byteLength).fill(0);\n const typedArrays = {\n i32: new Int32Array(buffer),\n u32: new Uint32Array(buffer),\n f32: new Float32Array(buffer),\n f16: new Uint16Array(buffer)\n };\n\n const flattenedUniformValues = this.getFlatUniformValues(uniformValues);\n for (const [name, value] of Object.entries(flattenedUniformValues)) {\n this._writeLeafValue(typedArrays, name, value);\n }\n\n return new Uint8Array(buffer, 0, this.layout.byteLength);\n }\n\n /**\n * Recursively flattens nested values using the declared composite shader type.\n */\n private _flattenCompositeValue(\n flattenedUniformValues: Record,\n baseName: string,\n uniformType: CompositeShaderType,\n value: CompositeUniformValue | undefined\n ): void {\n if (value === undefined) {\n return;\n }\n\n if (typeof uniformType === 'string' || this.layout.fields[baseName]) {\n flattenedUniformValues[baseName] = value as UniformValue;\n return;\n }\n\n if (Array.isArray(uniformType)) {\n const elementType = uniformType[0] as CompositeShaderType;\n const length = uniformType[1] as number;\n\n if (Array.isArray(elementType)) {\n throw new Error(`Nested arrays are not supported for ${baseName}`);\n }\n\n if (typeof elementType === 'string' && isNumberArray(value)) {\n this._flattenPackedArray(flattenedUniformValues, baseName, elementType, length, value);\n return;\n }\n\n if (!Array.isArray(value)) {\n log.warn(`Unsupported uniform array value for ${baseName}:`, value)();\n return;\n }\n\n for (let index = 0; index < Math.min(value.length, length); index++) {\n const elementValue = value[index];\n if (elementValue === undefined) {\n continue;\n }\n\n this._flattenCompositeValue(\n flattenedUniformValues,\n `${baseName}[${index}]`,\n elementType,\n elementValue\n );\n }\n return;\n }\n\n if (isCompositeShaderTypeStruct(uniformType) && isCompositeUniformObject(value)) {\n for (const [key, subValue] of Object.entries(value)) {\n if (subValue === undefined) {\n continue;\n }\n\n const nestedName = `${baseName}.${key}`;\n this._flattenCompositeValue(flattenedUniformValues, nestedName, uniformType[key], subValue);\n }\n return;\n }\n\n log.warn(`Unsupported uniform value for ${baseName}:`, value)();\n }\n\n /**\n * Expands tightly packed numeric arrays into per-element leaf fields.\n */\n private _flattenPackedArray(\n flattenedUniformValues: Record,\n baseName: string,\n elementType: VariableShaderType,\n length: number,\n value: UniformValue\n ): void {\n const numericValue = value as Readonly>;\n const elementLayout = getLeafLayoutInfo(elementType, this.layout.layout);\n const packedElementLength = elementLayout.components;\n\n for (let index = 0; index < length; index++) {\n const start = index * packedElementLength;\n if (start >= numericValue.length) {\n break;\n }\n\n if (packedElementLength === 1) {\n flattenedUniformValues[`${baseName}[${index}]`] = Number(numericValue[start]);\n } else {\n flattenedUniformValues[`${baseName}[${index}]`] = sliceNumericArray(\n value,\n start,\n start + packedElementLength\n ) as UniformValue;\n }\n }\n }\n\n /**\n * Writes one flattened leaf value into its typed-array view.\n */\n private _writeLeafValue(\n typedArrays: Record,\n name: string,\n value: UniformValue\n ): void {\n const entry = this.layout.fields[name];\n if (!entry) {\n log.warn(`Uniform ${name} not found in layout`)();\n return;\n }\n\n const {type, components, columns, rows, offset, columnStride} = entry;\n const array = typedArrays[type];\n\n if (components === 1) {\n array[offset] = Number(value);\n return;\n }\n\n const sourceValue = value as Readonly>;\n\n if (columns === 1) {\n for (let componentIndex = 0; componentIndex < components; componentIndex++) {\n array[offset + componentIndex] = Number(sourceValue[componentIndex] ?? 0);\n }\n return;\n }\n\n let sourceIndex = 0;\n for (let columnIndex = 0; columnIndex < columns; columnIndex++) {\n const columnOffset = offset + columnIndex * columnStride;\n for (let rowIndex = 0; rowIndex < rows; rowIndex++) {\n array[columnOffset + rowIndex] = Number(sourceValue[sourceIndex++] ?? 0);\n }\n }\n }\n}\n\n/**\n * Type guard for nested uniform objects.\n */\nfunction isCompositeUniformObject(\n value: CompositeUniformValue\n): value is Record {\n return (\n Boolean(value) &&\n typeof value === 'object' &&\n !Array.isArray(value) &&\n !ArrayBuffer.isView(value)\n );\n}\n\n/**\n * Slices a numeric array-like value without changing its numeric representation.\n */\nfunction sliceNumericArray(value: UniformValue, start: number, end: number): number[] {\n return Array.prototype.slice.call(value, start, end) as number[];\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {isNumberArray} from './is-array';\n\nconst MAX_ELEMENTWISE_ARRAY_COMPARE_LENGTH = 128;\n\n/** Test if two arrays are deep equal, with a small-array length limit that defaults to 16 */\nexport function arrayEqual(a: unknown, b: unknown, limit: number = 16) {\n if (a === b) {\n return true;\n }\n\n const arrayA = a;\n const arrayB = b;\n if (!isNumberArray(arrayA) || !isNumberArray(arrayB)) {\n return false;\n }\n\n if (arrayA.length !== arrayB.length) {\n return false;\n }\n\n const maxCompareLength = Math.min(limit, MAX_ELEMENTWISE_ARRAY_COMPARE_LENGTH);\n if (arrayA.length > maxCompareLength) {\n return false;\n }\n\n for (let i = 0; i < arrayA.length; ++i) {\n if (arrayB[i] !== arrayA[i]) {\n return false;\n }\n }\n\n return true;\n}\n\n/** Copy a value */\nexport function arrayCopy(a: T): T {\n if (isNumberArray(a)) {\n return a.slice() as T;\n }\n return a;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {VariableShaderType} from '../shadertypes/shader-types/shader-types';\nimport type {UniformValue} from '../adapter/types/uniforms';\nimport {\n ShaderLayout,\n UniformInfo,\n UniformBufferBindingLayout\n} from '../adapter/types/shader-layout';\nimport {arrayEqual, arrayCopy} from '../utils/array-equal';\n\n/**\n * A uniform block holds values of the of uniform values for one uniform block / buffer.\n * It also does some book keeping on what has changed, to minimize unnecessary writes to uniform buffers.\n */\nexport class UniformBlock<\n TUniforms extends Record = Record\n> {\n name: string;\n\n uniforms: Record = {} as Record;\n modifiedUniforms: Record = {} as Record;\n modified: boolean = true;\n\n readonly bindingLayout: Record = {};\n needsRedraw: string | false = 'initialized';\n\n constructor(props?: {\n name?: string;\n shaderLayout?: ShaderLayout;\n uniformTypes?: Record>;\n }) {\n this.name = props?.name || 'unnamed';\n\n // TODO - Extract uniform layout from the shaderLayout object\n if (props?.name && props?.shaderLayout) {\n const binding = props?.shaderLayout.bindings?.find(\n binding_ => binding_.type === 'uniform' && binding_.name === props?.name\n );\n if (!binding) {\n throw new Error(props?.name);\n }\n\n const uniformBlock = binding as UniformBufferBindingLayout;\n for (const uniform of uniformBlock.uniforms || []) {\n this.bindingLayout[uniform.name] = uniform;\n }\n }\n }\n\n /** Set a map of uniforms */\n setUniforms(uniforms: Partial): void {\n for (const [key, value] of Object.entries(uniforms)) {\n this._setUniform(key, value);\n if (!this.needsRedraw) {\n this.setNeedsRedraw(`${this.name}.${key}=${value}`);\n }\n }\n }\n\n setNeedsRedraw(reason: string): void {\n this.needsRedraw = this.needsRedraw || reason;\n }\n\n /** Returns all uniforms */\n getAllUniforms(): Record {\n // @ts-expect-error\n this.modifiedUniforms = {};\n this.needsRedraw = false;\n return (this.uniforms || {}) as Record;\n }\n\n /** Set a single uniform */\n private _setUniform(key: keyof TUniforms, value: UniformValue) {\n if (arrayEqual(this.uniforms[key], value)) {\n return;\n }\n this.uniforms[key] = arrayCopy(value);\n this.modifiedUniforms[key] = true;\n this.modified = true;\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {CompositeShaderType} from '../shadertypes/shader-types/shader-types';\nimport type {CompositeUniformValue} from '../adapter/types/uniforms';\nimport type {Device} from '../adapter/device';\nimport {Buffer} from '../adapter/resources/buffer';\nimport {log} from '../utils/log';\nimport {\n makeShaderBlockLayout,\n type ShaderBlockLayout\n} from '../shadertypes/shader-types/shader-block-layout';\nimport {UniformBlock} from './uniform-block';\nimport {ShaderBlockWriter} from './shader-block-writer';\n\n/** Definition of a single managed uniform block. */\nexport type UniformStoreBlockDefinition = {\n /** Declared shader types for the block's uniforms. */\n uniformTypes?: Record;\n /** Reserved for future prop-level defaults. */\n defaultProps?: Record;\n /** Initial uniform values written into the backing block. */\n defaultUniforms?: Record;\n /** Explicit shader-block layout override. */\n layout?: 'std140' | 'wgsl-uniform' | 'wgsl-storage';\n};\n\n/** Uniform block definitions keyed by block name. */\nexport type UniformStoreBlocks>> =\n Record;\n\n/**\n * Smallest buffer size that can be used for uniform buffers.\n *\n * This is an allocation policy rather than part of {@link ShaderBlockLayout}.\n * Layouts report the exact packed size, while the store applies any minimum\n * buffer-size rule when allocating GPU buffers.\n *\n * TODO - does this depend on device?\n */\nconst minUniformBufferSize = 1024;\n\n/**\n * A uniform store holds a uniform values for one or more uniform blocks,\n * - It can generate binary data for any uniform buffer\n * - It can manage a uniform buffer for each block\n * - It can update managed uniform buffers with a single call\n * - It performs some book keeping on what has changed to minimize unnecessary writes to uniform buffers.\n */\nexport class UniformStore<\n TPropGroups extends Record> = Record<\n string,\n Record\n >\n> {\n /** Device used to infer layout and allocate buffers. */\n readonly device: Device;\n /** Stores the uniform values for each uniform block */\n uniformBlocks = new Map();\n /** Flattened layout metadata for each block. */\n shaderBlockLayouts = new Map();\n /** Serializers for block-backed uniform data. */\n shaderBlockWriters = new Map();\n /** Actual buffer for the blocks */\n uniformBuffers = new Map();\n\n /**\n * Creates a new {@link UniformStore} for the supplied device and block definitions.\n */\n constructor(device: Device, blocks: UniformStoreBlocks) {\n this.device = device;\n\n for (const [bufferName, block] of Object.entries(blocks)) {\n const uniformBufferName = bufferName as keyof TPropGroups;\n\n // Create a layout object to help us generate correctly formatted binary uniform buffers\n const shaderBlockLayout = makeShaderBlockLayout(block.uniformTypes ?? {}, {\n layout: block.layout ?? getDefaultUniformBufferLayout(device)\n });\n const shaderBlockWriter = new ShaderBlockWriter(shaderBlockLayout);\n this.shaderBlockLayouts.set(uniformBufferName, shaderBlockLayout);\n this.shaderBlockWriters.set(uniformBufferName, shaderBlockWriter);\n\n // Create a Uniform block to store the uniforms for each buffer.\n const uniformBlock = new UniformBlock({name: bufferName});\n uniformBlock.setUniforms(shaderBlockWriter.getFlatUniformValues(block.defaultUniforms || {}));\n this.uniformBlocks.set(uniformBufferName, uniformBlock);\n }\n }\n\n /** Destroy any managed uniform buffers */\n destroy(): void {\n for (const uniformBuffer of this.uniformBuffers.values()) {\n uniformBuffer.destroy();\n }\n }\n\n /**\n * Set uniforms\n *\n * Makes all group properties partial and eagerly propagates changes to any\n * managed GPU buffers.\n */\n setUniforms(\n uniforms: Partial<{[group in keyof TPropGroups]: Partial}>\n ): void {\n for (const [blockName, uniformValues] of Object.entries(uniforms)) {\n const uniformBufferName = blockName as keyof TPropGroups;\n const shaderBlockWriter = this.shaderBlockWriters.get(uniformBufferName);\n const flattenedUniforms = shaderBlockWriter?.getFlatUniformValues(\n (uniformValues || {}) as Record\n );\n this.uniformBlocks.get(uniformBufferName)?.setUniforms(flattenedUniforms || {});\n // We leverage logging in updateUniformBuffers(), even though slightly less efficient\n // this.updateUniformBuffer(blockName);\n }\n\n this.updateUniformBuffers();\n }\n\n /**\n * Returns the allocation size for the named uniform buffer.\n *\n * This may exceed the packed layout size because minimum buffer-size policy is\n * applied at the store layer.\n */\n getUniformBufferByteLength(uniformBufferName: keyof TPropGroups): number {\n const packedByteLength = this.shaderBlockLayouts.get(uniformBufferName)?.byteLength || 0;\n return Math.max(packedByteLength, minUniformBufferSize);\n }\n\n /**\n * Returns packed binary data that can be uploaded to the named uniform buffer.\n *\n * The returned view length matches the packed block size and is not padded to\n * the store's minimum allocation size.\n */\n getUniformBufferData(uniformBufferName: keyof TPropGroups): Uint8Array {\n const uniformValues = this.uniformBlocks.get(uniformBufferName)?.getAllUniforms() || {};\n const shaderBlockWriter = this.shaderBlockWriters.get(uniformBufferName);\n return shaderBlockWriter?.getData(uniformValues) || new Uint8Array(0);\n }\n\n /**\n * Creates an unmanaged uniform buffer initialized with the current or supplied values.\n */\n createUniformBuffer(\n uniformBufferName: keyof TPropGroups,\n uniforms?: Partial<{[group in keyof TPropGroups]: Partial}>\n ): Buffer {\n if (uniforms) {\n this.setUniforms(uniforms);\n }\n const byteLength = this.getUniformBufferByteLength(uniformBufferName);\n const uniformBuffer = this.device.createBuffer({\n usage: Buffer.UNIFORM | Buffer.COPY_DST,\n byteLength\n });\n // Note that this clears the needs redraw flag\n const uniformBufferData = this.getUniformBufferData(uniformBufferName);\n uniformBuffer.write(uniformBufferData);\n return uniformBuffer;\n }\n\n /** Returns the managed uniform buffer for the named block. */\n getManagedUniformBuffer(uniformBufferName: keyof TPropGroups): Buffer {\n if (!this.uniformBuffers.get(uniformBufferName)) {\n const byteLength = this.getUniformBufferByteLength(uniformBufferName);\n const uniformBuffer = this.device.createBuffer({\n usage: Buffer.UNIFORM | Buffer.COPY_DST,\n byteLength\n });\n this.uniformBuffers.set(uniformBufferName, uniformBuffer);\n }\n // this.updateUniformBuffers();\n // @ts-ignore\n return this.uniformBuffers.get(uniformBufferName);\n }\n\n /**\n * Updates every managed uniform buffer whose source uniforms have changed.\n *\n * @returns The first redraw reason encountered, or `false` if nothing changed.\n */\n updateUniformBuffers(): false | string {\n let reason: false | string = false;\n for (const uniformBufferName of this.uniformBlocks.keys()) {\n const bufferReason = this.updateUniformBuffer(uniformBufferName);\n reason ||= bufferReason;\n }\n if (reason) {\n log.log(3, `UniformStore.updateUniformBuffers(): ${reason}`)();\n }\n return reason;\n }\n\n /**\n * Updates one managed uniform buffer if its corresponding block is dirty.\n *\n * @returns The redraw reason for the update, or `false` if no write occurred.\n */\n updateUniformBuffer(uniformBufferName: keyof TPropGroups): false | string {\n const uniformBlock = this.uniformBlocks.get(uniformBufferName);\n let uniformBuffer = this.uniformBuffers.get(uniformBufferName);\n\n let reason: false | string = false;\n if (uniformBuffer && uniformBlock?.needsRedraw) {\n reason ||= uniformBlock.needsRedraw;\n // This clears the needs redraw flag\n const uniformBufferData = this.getUniformBufferData(uniformBufferName);\n\n uniformBuffer = this.uniformBuffers.get(uniformBufferName);\n uniformBuffer?.write(uniformBufferData);\n\n // logging - TODO - don't query the values unnecessarily\n const uniformValues = this.uniformBlocks.get(uniformBufferName)?.getAllUniforms();\n log.log(\n 4,\n `Writing to uniform buffer ${String(uniformBufferName)}`,\n uniformBufferData,\n uniformValues\n )();\n }\n return reason;\n }\n}\n\n/**\n * Returns the default uniform-buffer layout for the supplied device.\n */\nfunction getDefaultUniformBufferLayout(device: Device): 'std140' | 'wgsl-uniform' | 'wgsl-storage' {\n return device.type === 'webgpu' ? 'wgsl-uniform' : 'std140';\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// MAIN API ACCESS POINT\nexport type {AttachDeviceProps, CreateDeviceProps} from './adapter/luma';\nexport {luma} from './adapter/luma';\n\n// ADAPTER (DEVICE AND GPU RESOURCE INTERFACES)\nexport {Adapter} from './adapter/adapter';\n\nexport type {\n DeviceProps,\n DeviceInfo,\n DeviceFeature,\n DeviceTextureFormatCapabilities\n} from './adapter/device';\nexport {Device, DeviceFeatures, DeviceLimits} from './adapter/device';\n\nexport type {CanvasContextProps} from './adapter/canvas-context';\nexport {CanvasContext} from './adapter/canvas-context';\nexport type {PresentationContextProps} from './adapter/presentation-context';\nexport {PresentationContext} from './adapter/presentation-context';\n\n// GPU RESOURCES\nexport {Resource, type ResourceProps} from './adapter/resources/resource';\n\nexport {Buffer, type BufferProps, type BufferMapCallback} from './adapter/resources/buffer';\n\nexport {Texture, type TextureProps} from './adapter/resources/texture';\n\nexport {TextureView, type TextureViewProps} from './adapter/resources/texture-view';\n\nexport type {ExternalTextureProps} from './adapter/resources/external-texture';\nexport {ExternalTexture} from './adapter/resources/external-texture';\n\nexport type {ShaderProps} from './adapter/resources/shader';\nexport {Shader} from './adapter/resources/shader';\n\nexport type {SamplerProps, SamplerParameters} from './adapter/resources/sampler';\nexport {Sampler} from './adapter/resources/sampler';\n\nexport type {FramebufferProps} from './adapter/resources/framebuffer';\nexport {Framebuffer} from './adapter/resources/framebuffer';\n\nexport type {RenderPipelineProps} from './adapter/resources/render-pipeline';\nexport {RenderPipeline} from './adapter/resources/render-pipeline';\nexport {\n SharedRenderPipeline,\n type SharedRenderPipelineProps\n} from './adapter/resources/shared-render-pipeline';\nexport type {PipelineFactoryProps} from './factories/pipeline-factory';\nexport {PipelineFactory} from './factories/pipeline-factory';\nexport {ShaderFactory} from './factories/shader-factory';\nexport {_getDefaultBindGroupFactory} from './factories/bind-group-factory';\n\nexport type {RenderPassProps} from './adapter/resources/render-pass';\nexport {RenderPass} from './adapter/resources/render-pass';\n\nexport type {ComputePipelineProps} from './adapter/resources/compute-pipeline';\nexport {ComputePipeline} from './adapter/resources/compute-pipeline';\n\nexport type {ComputePassProps} from './adapter/resources/compute-pass';\nexport {ComputePass} from './adapter/resources/compute-pass';\n\nexport type {CommandEncoderProps} from './adapter/resources/command-encoder';\nexport {CommandEncoder} from './adapter/resources/command-encoder';\n\nexport type {CommandBufferProps} from './adapter/resources/command-buffer';\nexport {CommandBuffer} from './adapter/resources/command-buffer';\n\nexport type {VertexArrayProps} from './adapter/resources/vertex-array';\nexport {VertexArray} from './adapter/resources/vertex-array';\n\nexport type {TransformFeedbackProps, BufferRange} from './adapter/resources/transform-feedback';\nexport {TransformFeedback} from './adapter/resources/transform-feedback';\n\nexport type {QuerySetProps} from './adapter/resources/query-set';\nexport {QuerySet} from './adapter/resources/query-set';\n\nexport {Fence, type FenceProps} from './adapter/resources/fence';\n\nexport type {PipelineLayoutProps} from './adapter/resources/pipeline-layout';\nexport {PipelineLayout} from './adapter/resources/pipeline-layout';\n\n// PORTABLE API - UNIFORM BUFFERS\nexport {\n makeShaderBlockLayout,\n type ShaderBlockLayout,\n type ShaderBlockLayoutEntry,\n type ShaderBlockLayoutOptions\n} from './shadertypes/shader-types/shader-block-layout';\nexport {ShaderBlockWriter} from './portable/shader-block-writer';\nexport {UniformBlock} from './portable/uniform-block';\nexport {UniformStore} from './portable/uniform-store';\n// TEXTURE TYPES\n\n// API TYPES\nexport type {CompilerMessage} from './adapter/types/compiler-message';\n\nexport type {ExternalImage} from './shadertypes/image-types/image-types';\n\nexport {\n type CopyExternalImageOptions,\n type CopyImageDataOptions,\n type TextureReadOptions,\n type TextureWriteOptions\n} from './adapter/resources/texture';\n\nexport type {Parameters, PrimitiveTopology, IndexFormat} from './adapter/types/parameters';\n\nexport type {\n CullMode,\n FrontFace,\n RasterizationParameters,\n CompareFunction,\n StencilOperation,\n DepthStencilParameters,\n BlendFactor,\n BlendOperation,\n ColorParameters,\n MultisampleParameters,\n RenderPassParameters,\n RenderPipelineParameters,\n PolygonMode,\n ProvokingVertex\n} from './adapter/types/parameters';\n\nexport type {ColorAttachment, DepthStencilAttachment} from './adapter/types/attachments';\n\nexport type {\n ShaderLayout,\n ComputeShaderLayout,\n AttributeDeclaration,\n BindingDeclaration,\n Binding,\n Bindings,\n BindingsByGroup,\n UniformBufferBindingLayout,\n StorageBufferBindingLayout,\n TextureBindingLayout,\n SamplerBindingLayout,\n StorageTextureBindingLayout\n} from './adapter/types/shader-layout';\nexport type {BufferLayout, BufferAttributeLayout} from './adapter/types/buffer-layout';\nexport type {\n // Deprecated, todo\n AttributeBinding,\n UniformBinding,\n UniformBlockBinding,\n VaryingBinding\n} from './adapter/types/shader-layout';\n\nexport type {UniformValue} from './adapter/types/uniforms';\nexport type {\n CompositeUniformValue,\n CompositeUniformValueArray,\n CompositeUniformValueStruct\n} from './adapter/types/uniforms';\n\n// TYPED ARRAY TYPES\n\nexport type {\n NumberArray,\n TypedArray,\n TypedArrayConstructor,\n BigTypedArray,\n BigTypedArrayConstructor\n} from './types';\n\n// GPU TYPE UTILS - BASIC DATA TYPES\n\nexport {\n type PrimitiveDataType,\n type SignedDataType,\n type NormalizedDataType,\n type DataTypeInfo,\n type PrimitiveDataTypeT,\n type SignedDataTypeT,\n type TypedArrayConstructorT,\n type NormalizedTypedArrayConstructorT\n} from './shadertypes/data-types/data-types';\nexport {dataTypeDecoder} from './shadertypes/data-types/data-type-decoder';\nexport {getTypedArrayConstructor} from './shadertypes/data-types/decode-data-types';\n\nexport {\n type AttributeShaderTypeT,\n type AttributeShaderType,\n type ArrayShaderType,\n type CompositeShaderType,\n type StructShaderType,\n type VariableShaderTypeT,\n type VariableShaderType\n} from './shadertypes/shader-types/shader-types';\nexport {\n shaderTypeDecoder,\n getAttributeShaderTypeInfo,\n getVariableShaderTypeInfo,\n type AttributeShaderTypeInfo\n} from './shadertypes/shader-types/shader-type-decoder';\n\n// GPU TYPE UTILS - VERTEX ARRAYs\n\nexport {\n type VertexFormat,\n type VertexFormatDataTypeT\n} from './shadertypes/vertex-types/vertex-formats';\n\nexport {vertexFormatDecoder} from './shadertypes/vertex-types/vertex-format-decoder';\n\n// GPU TYPE UTILS - Texture Formats\n\nexport {\n type TextureFormat,\n type TextureFormatColor,\n type TextureFormatDepthStencil,\n type CompressedTextureFormat,\n type TextureCompression,\n type TextureFormatInfo,\n type TextureFormatCapabilities,\n type TextureMemoryLayout\n} from './shadertypes/texture-types/texture-formats';\nexport {type TextureFormatDataTypeT} from './shadertypes/texture-types/texture-format-generics';\n\nexport {\n type TextureFormatDecoder,\n textureFormatDecoder\n} from './shadertypes/texture-types/texture-format-decoder';\n\nexport {getTextureImageView, setTextureImageData} from './shadertypes/texture-types/texture-layout';\nexport {type PixelData, readPixel, writePixel} from './shadertypes/texture-types/pixel-utils';\n\nexport {isExternalImage, getExternalImageSize} from './shadertypes/image-types/image-types';\n\n// GENERAL EXPORTS - FOR APPLICATIONS\n\nexport type {StatsManager} from './utils/stats-manager'; // TODO - should this be moved to probe.gl?\n\n// ADAPTER UTILS - for implementing Device adapters (@luma.gl/webgl and @luma.gl/webgpu)\n\nexport type {\n CopyBufferToBufferOptions,\n CopyBufferToTextureOptions,\n CopyTextureToBufferOptions,\n CopyTextureToTextureOptions\n} from './adapter/resources/command-encoder';\n\n// INTERNAL UTILS - for use in other luma.gl modules only\nexport {log} from './utils/log';\nexport {\n getShaderLayoutBinding,\n normalizeBindingsByGroup,\n flattenBindingsByGroup\n} from './adapter-utils/bind-groups';\nexport {assert, assertDefined} from './utils/assert';\nexport {getScratchArray} from './utils/array-utils-flat';\nexport type {AttributeInfo} from './adapter-utils/get-attribute-from-layouts';\nexport {getAttributeInfosFromLayouts} from './adapter-utils/get-attribute-from-layouts';\n\n// TEST EXPORTS\nexport {\n getTextureFormatDefinition as _getTextureFormatDefinition,\n getTextureFormatTable as _getTextureFormatTable\n} from './shadertypes/texture-types/texture-format-table';\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/* eslint-disable key-spacing, max-len, no-inline-comments, camelcase */\n\n/**\n * Standard WebGL, WebGL2 and extension constants (OpenGL constants)\n * @note (Most) of these constants are also defined on the WebGLRenderingContext interface.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Constants\n * @privateRemarks Locally called `GLEnum` instead of `GL`, because `babel-plugin-inline-webl-constants`\n * both depends on and processes this module, but shouldn't replace these declarations.\n */\n// eslint-disable-next-line no-shadow\nenum GLEnum {\n // Clearing buffers\n // Constants passed to clear() to clear buffer masks.\n\n /** Passed to clear to clear the current depth buffer. */\n DEPTH_BUFFER_BIT = 0x00000100,\n /** Passed to clear to clear the current stencil buffer. */\n STENCIL_BUFFER_BIT = 0x00000400,\n /** Passed to clear to clear the current color buffer. */\n COLOR_BUFFER_BIT = 0x00004000,\n\n // Rendering primitives\n // Constants passed to drawElements() or drawArrays() to specify what kind of primitive to render.\n\n /** Passed to drawElements or drawArrays to draw single points. */\n POINTS = 0x0000,\n /** Passed to drawElements or drawArrays to draw lines. Each vertex connects to the one after it. */\n LINES = 0x0001,\n /** Passed to drawElements or drawArrays to draw lines. Each set of two vertices is treated as a separate line segment. */\n LINE_LOOP = 0x0002,\n /** Passed to drawElements or drawArrays to draw a connected group of line segments from the first vertex to the last. */\n LINE_STRIP = 0x0003,\n /** Passed to drawElements or drawArrays to draw triangles. Each set of three vertices creates a separate triangle. */\n TRIANGLES = 0x0004,\n /** Passed to drawElements or drawArrays to draw a connected group of triangles. */\n TRIANGLE_STRIP = 0x0005,\n /** Passed to drawElements or drawArrays to draw a connected group of triangles. Each vertex connects to the previous and the first vertex in the fan. */\n TRIANGLE_FAN = 0x0006,\n\n // Blending modes\n // Constants passed to blendFunc() or blendFuncSeparate() to specify the blending mode (for both, RBG and alpha, or separately).\n /** Passed to blendFunc or blendFuncSeparate to turn off a component. */\n ZERO = 0,\n /** Passed to blendFunc or blendFuncSeparate to turn on a component. */\n ONE = 1,\n /** Passed to blendFunc or blendFuncSeparate to multiply a component by the source elements color. */\n SRC_COLOR = 0x0300,\n /** Passed to blendFunc or blendFuncSeparate to multiply a component by one minus the source elements color. */\n ONE_MINUS_SRC_COLOR = 0x0301,\n /** Passed to blendFunc or blendFuncSeparate to multiply a component by the source's alpha. */\n SRC_ALPHA = 0x0302,\n /** Passed to blendFunc or blendFuncSeparate to multiply a component by one minus the source's alpha. */\n ONE_MINUS_SRC_ALPHA = 0x0303,\n /** Passed to blendFunc or blendFuncSeparate to multiply a component by the destination's alpha. */\n DST_ALPHA = 0x0304,\n /** Passed to blendFunc or blendFuncSeparate to multiply a component by one minus the destination's alpha. */\n ONE_MINUS_DST_ALPHA = 0x0305,\n /** Passed to blendFunc or blendFuncSeparate to multiply a component by the destination's color. */\n DST_COLOR = 0x0306,\n /** Passed to blendFunc or blendFuncSeparate to multiply a component by one minus the destination's color. */\n ONE_MINUS_DST_COLOR = 0x0307,\n /** Passed to blendFunc or blendFuncSeparate to multiply a component by the minimum of source's alpha or one minus the destination's alpha. */\n SRC_ALPHA_SATURATE = 0x0308,\n /** Passed to blendFunc or blendFuncSeparate to specify a constant color blend function. */\n CONSTANT_COLOR = 0x8001,\n /** Passed to blendFunc or blendFuncSeparate to specify one minus a constant color blend function. */\n ONE_MINUS_CONSTANT_COLOR = 0x8002,\n /** Passed to blendFunc or blendFuncSeparate to specify a constant alpha blend function. */\n CONSTANT_ALPHA = 0x8003,\n /** Passed to blendFunc or blendFuncSeparate to specify one minus a constant alpha blend function. */\n ONE_MINUS_CONSTANT_ALPHA = 0x8004,\n\n // Blending equations\n // Constants passed to blendEquation() or blendEquationSeparate() to control\n // how the blending is calculated (for both, RBG and alpha, or separately).\n\n /** Passed to blendEquation or blendEquationSeparate to set an addition blend function. */\n /** Passed to blendEquation or blendEquationSeparate to specify a subtraction blend function (source - destination). */\n /** Passed to blendEquation or blendEquationSeparate to specify a reverse subtraction blend function (destination - source). */\n FUNC_ADD = 0x8006,\n FUNC_SUBTRACT = 0x800a,\n FUNC_REVERSE_SUBTRACT = 0x800b,\n\n // Getting GL parameter information\n // Constants passed to getParameter() to specify what information to return.\n\n /** Passed to getParameter to get the current RGB blend function. */\n BLEND_EQUATION = 0x8009,\n /** Passed to getParameter to get the current RGB blend function. Same as BLEND_EQUATION */\n BLEND_EQUATION_RGB = 0x8009,\n /** Passed to getParameter to get the current alpha blend function. Same as BLEND_EQUATION */\n BLEND_EQUATION_ALPHA = 0x883d,\n /** Passed to getParameter to get the current destination RGB blend function. */\n BLEND_DST_RGB = 0x80c8,\n /** Passed to getParameter to get the current destination RGB blend function. */\n BLEND_SRC_RGB = 0x80c9,\n /** Passed to getParameter to get the current destination alpha blend function. */\n BLEND_DST_ALPHA = 0x80ca,\n /** Passed to getParameter to get the current source alpha blend function. */\n BLEND_SRC_ALPHA = 0x80cb,\n\n /** Passed to getParameter to return a the current blend color. */\n BLEND_COLOR = 0x8005,\n /** Passed to getParameter to get the array buffer binding. */\n ARRAY_BUFFER_BINDING = 0x8894,\n /** Passed to getParameter to get the current element array buffer. */\n ELEMENT_ARRAY_BUFFER_BINDING = 0x8895,\n /** Passed to getParameter to get the current lineWidth (set by the lineWidth method). */\n LINE_WIDTH = 0x0b21,\n /** Passed to getParameter to get the current size of a point drawn with gl.POINTS */\n ALIASED_POINT_SIZE_RANGE = 0x846d,\n /** Passed to getParameter to get the range of available widths for a line. Returns a length-2 array with the lo value at 0, and hight at 1. */\n ALIASED_LINE_WIDTH_RANGE = 0x846e,\n /** Passed to getParameter to get the current value of cullFace. Should return FRONT, BACK, or FRONT_AND_BACK */\n CULL_FACE_MODE = 0x0b45,\n /** Passed to getParameter to determine the current value of frontFace. Should return CW or CCW. */\n FRONT_FACE = 0x0b46,\n /** Passed to getParameter to return a length-2 array of floats giving the current depth range. */\n DEPTH_RANGE = 0x0b70,\n /** Passed to getParameter to determine if the depth write mask is enabled. */\n\n DEPTH_WRITEMASK = 0x0b72,\n /** Passed to getParameter to determine the current depth clear value. */\n DEPTH_CLEAR_VALUE = 0x0b73,\n /** Passed to getParameter to get the current depth function. Returns NEVER, ALWAYS, LESS, EQUAL, LEQUAL, GREATER, GEQUAL, or NOTEQUAL. */\n DEPTH_FUNC = 0x0b74,\n /** Passed to getParameter to get the value the stencil will be cleared to. */\n STENCIL_CLEAR_VALUE = 0x0b91,\n /** Passed to getParameter to get the current stencil function. Returns NEVER, ALWAYS, LESS, EQUAL, LEQUAL, GREATER, GEQUAL, or NOTEQUAL. */\n STENCIL_FUNC = 0x0b92,\n /** Passed to getParameter to get the current stencil fail function. Should return KEEP, REPLACE, INCR, DECR, INVERT, INCR_WRAP, or DECR_WRAP. */\n STENCIL_FAIL = 0x0b94,\n /** Passed to getParameter to get the current stencil fail function should the depth buffer test fail. Should return KEEP, REPLACE, INCR, DECR, INVERT, INCR_WRAP, or DECR_WRAP. */\n STENCIL_PASS_DEPTH_FAIL = 0x0b95,\n /** Passed to getParameter to get the current stencil fail function should the depth buffer test pass. Should return KEEP, REPLACE, INCR, DECR, INVERT, INCR_WRAP, or DECR_WRAP. */\n STENCIL_PASS_DEPTH_PASS = 0x0b96,\n /** Passed to getParameter to get the reference value used for stencil tests. */\n STENCIL_REF = 0x0b97,\n STENCIL_VALUE_MASK = 0x0b93,\n STENCIL_WRITEMASK = 0x0b98,\n STENCIL_BACK_FUNC = 0x8800,\n STENCIL_BACK_FAIL = 0x8801,\n STENCIL_BACK_PASS_DEPTH_FAIL = 0x8802,\n STENCIL_BACK_PASS_DEPTH_PASS = 0x8803,\n STENCIL_BACK_REF = 0x8ca3,\n STENCIL_BACK_VALUE_MASK = 0x8ca4,\n STENCIL_BACK_WRITEMASK = 0x8ca5,\n\n /** An Int32Array with four elements for the current viewport dimensions. */\n VIEWPORT = 0x0ba2,\n /** An Int32Array with four elements for the current scissor box dimensions. */\n SCISSOR_BOX = 0x0c10,\n COLOR_CLEAR_VALUE = 0x0c22,\n COLOR_WRITEMASK = 0x0c23,\n UNPACK_ALIGNMENT = 0x0cf5,\n PACK_ALIGNMENT = 0x0d05,\n MAX_TEXTURE_SIZE = 0x0d33,\n MAX_VIEWPORT_DIMS = 0x0d3a,\n SUBPIXEL_BITS = 0x0d50,\n RED_BITS = 0x0d52,\n GREEN_BITS = 0x0d53,\n BLUE_BITS = 0x0d54,\n ALPHA_BITS = 0x0d55,\n DEPTH_BITS = 0x0d56,\n STENCIL_BITS = 0x0d57,\n POLYGON_OFFSET_UNITS = 0x2a00,\n POLYGON_OFFSET_FACTOR = 0x8038,\n TEXTURE_BINDING_2D = 0x8069,\n SAMPLE_BUFFERS = 0x80a8,\n SAMPLES = 0x80a9,\n SAMPLE_COVERAGE_VALUE = 0x80aa,\n SAMPLE_COVERAGE_INVERT = 0x80ab,\n COMPRESSED_TEXTURE_FORMATS = 0x86a3,\n VENDOR = 0x1f00,\n RENDERER = 0x1f01,\n VERSION = 0x1f02,\n IMPLEMENTATION_COLOR_READ_TYPE = 0x8b9a,\n IMPLEMENTATION_COLOR_READ_FORMAT = 0x8b9b,\n BROWSER_DEFAULT_WEBGL = 0x9244,\n\n // Buffers\n // Constants passed to bufferData(), bufferSubData(), bindBuffer(), or\n // getBufferParameter().\n\n /** Passed to bufferData as a hint about whether the contents of the buffer are likely to be used often and not change often. */\n STATIC_DRAW = 0x88e4,\n /** Passed to bufferData as a hint about whether the contents of the buffer are likely to not be used often. */\n STREAM_DRAW = 0x88e0,\n /** Passed to bufferData as a hint about whether the contents of the buffer are likely to be used often and change often. */\n DYNAMIC_DRAW = 0x88e8,\n /** Passed to bindBuffer or bufferData to specify the type of buffer being used. */\n ARRAY_BUFFER = 0x8892,\n /** Passed to bindBuffer or bufferData to specify the type of buffer being used. */\n ELEMENT_ARRAY_BUFFER = 0x8893,\n /** Passed to getBufferParameter to get a buffer's size. */\n BUFFER_SIZE = 0x8764,\n /** Passed to getBufferParameter to get the hint for the buffer passed in when it was created. */\n BUFFER_USAGE = 0x8765,\n\n // Vertex attributes\n // Constants passed to getVertexAttrib().\n\n /** Passed to getVertexAttrib to read back the current vertex attribute. */\n CURRENT_VERTEX_ATTRIB = 0x8626,\n VERTEX_ATTRIB_ARRAY_ENABLED = 0x8622,\n VERTEX_ATTRIB_ARRAY_SIZE = 0x8623,\n VERTEX_ATTRIB_ARRAY_STRIDE = 0x8624,\n VERTEX_ATTRIB_ARRAY_TYPE = 0x8625,\n VERTEX_ATTRIB_ARRAY_NORMALIZED = 0x886a,\n VERTEX_ATTRIB_ARRAY_POINTER = 0x8645,\n VERTEX_ATTRIB_ARRAY_BUFFER_BINDING = 0x889f,\n\n // Culling\n // Constants passed to cullFace().\n\n /** Passed to enable/disable to turn on/off culling. Can also be used with getParameter to find the current culling method. */\n CULL_FACE = 0x0b44,\n /** Passed to cullFace to specify that only front faces should be culled. */\n FRONT = 0x0404,\n /** Passed to cullFace to specify that only back faces should be culled. */\n BACK = 0x0405,\n /** Passed to cullFace to specify that front and back faces should be culled. */\n FRONT_AND_BACK = 0x0408,\n\n // Enabling and disabling\n // Constants passed to enable() or disable().\n\n /** Passed to enable/disable to turn on/off blending. Can also be used with getParameter to find the current blending method. */\n BLEND = 0x0be2,\n /** Passed to enable/disable to turn on/off the depth test. Can also be used with getParameter to query the depth test. */\n DEPTH_TEST = 0x0b71,\n /** Passed to enable/disable to turn on/off dithering. Can also be used with getParameter to find the current dithering method. */\n DITHER = 0x0bd0,\n /** Passed to enable/disable to turn on/off the polygon offset. Useful for rendering hidden-line images, decals, and or solids with highlighted edges. Can also be used with getParameter to query the scissor test. */\n POLYGON_OFFSET_FILL = 0x8037,\n /** Passed to enable/disable to turn on/off the alpha to coverage. Used in multi-sampling alpha channels. */\n SAMPLE_ALPHA_TO_COVERAGE = 0x809e,\n /** Passed to enable/disable to turn on/off the sample coverage. Used in multi-sampling. */\n SAMPLE_COVERAGE = 0x80a0,\n /** Passed to enable/disable to turn on/off the scissor test. Can also be used with getParameter to query the scissor test. */\n SCISSOR_TEST = 0x0c11,\n /** Passed to enable/disable to turn on/off the stencil test. Can also be used with getParameter to query the stencil test. */\n STENCIL_TEST = 0x0b90,\n\n // Errors\n // Constants returned from getError().\n\n /** Returned from getError(). */\n NO_ERROR = 0,\n /** Returned from getError(). */\n INVALID_ENUM = 0x0500,\n /** Returned from getError(). */\n INVALID_VALUE = 0x0501,\n /** Returned from getError(). */\n INVALID_OPERATION = 0x0502,\n /** Returned from getError(). */\n OUT_OF_MEMORY = 0x0505,\n /** Returned from getError(). */\n CONTEXT_LOST_WEBGL = 0x9242,\n\n // Front face directions\n // Constants passed to frontFace().\n\n /** Passed to frontFace to specify the front face of a polygon is drawn in the clockwise direction */\n CW = 0x0900,\n /** Passed to frontFace to specify the front face of a polygon is drawn in the counter clockwise direction */\n CCW = 0x0901,\n\n // Hints\n // Constants passed to hint()\n\n /** There is no preference for this behavior. */\n DONT_CARE = 0x1100,\n /** The most efficient behavior should be used. */\n FASTEST = 0x1101,\n /** The most correct or the highest quality option should be used. */\n NICEST = 0x1102,\n /** Hint for the quality of filtering when generating mipmap images with WebGLRenderingContext.generateMipmap(). */\n GENERATE_MIPMAP_HINT = 0x8192,\n\n // Data types\n\n BYTE = 0x1400,\n UNSIGNED_BYTE = 0x1401,\n SHORT = 0x1402,\n UNSIGNED_SHORT = 0x1403,\n INT = 0x1404,\n UNSIGNED_INT = 0x1405,\n FLOAT = 0x1406,\n DOUBLE = 0x140a,\n\n // Pixel formats\n\n DEPTH_COMPONENT = 0x1902,\n ALPHA = 0x1906,\n RGB = 0x1907,\n RGBA = 0x1908,\n LUMINANCE = 0x1909,\n LUMINANCE_ALPHA = 0x190a,\n\n // Pixel types\n\n // UNSIGNED_BYTE = 0x1401,\n UNSIGNED_SHORT_4_4_4_4 = 0x8033,\n UNSIGNED_SHORT_5_5_5_1 = 0x8034,\n UNSIGNED_SHORT_5_6_5 = 0x8363,\n\n // Shaders\n // Constants passed to createShader() or getShaderParameter()\n\n /** Passed to createShader to define a fragment shader. */\n FRAGMENT_SHADER = 0x8b30,\n /** Passed to createShader to define a vertex shader */\n VERTEX_SHADER = 0x8b31,\n /** Passed to getShaderParameter to get the status of the compilation. Returns false if the shader was not compiled. You can then query getShaderInfoLog to find the exact error */\n COMPILE_STATUS = 0x8b81,\n /** Passed to getShaderParameter to determine if a shader was deleted via deleteShader. Returns true if it was, false otherwise. */\n DELETE_STATUS = 0x8b80,\n /** Passed to getProgramParameter after calling linkProgram to determine if a program was linked correctly. Returns false if there were errors. Use getProgramInfoLog to find the exact error. */\n LINK_STATUS = 0x8b82,\n /** Passed to getProgramParameter after calling validateProgram to determine if it is valid. Returns false if errors were found. */\n VALIDATE_STATUS = 0x8b83,\n /** Passed to getProgramParameter after calling attachShader to determine if the shader was attached correctly. Returns false if errors occurred. */\n ATTACHED_SHADERS = 0x8b85,\n /** Passed to getProgramParameter to get the number of attributes active in a program. */\n ACTIVE_ATTRIBUTES = 0x8b89,\n /** Passed to getProgramParameter to get the number of uniforms active in a program. */\n ACTIVE_UNIFORMS = 0x8b86,\n /** The maximum number of entries possible in the vertex attribute list. */\n MAX_VERTEX_ATTRIBS = 0x8869,\n MAX_VERTEX_UNIFORM_VECTORS = 0x8dfb,\n MAX_VARYING_VECTORS = 0x8dfc,\n MAX_COMBINED_TEXTURE_IMAGE_UNITS = 0x8b4d,\n MAX_VERTEX_TEXTURE_IMAGE_UNITS = 0x8b4c,\n /** Implementation dependent number of maximum texture units. At least 8. */\n MAX_TEXTURE_IMAGE_UNITS = 0x8872,\n MAX_FRAGMENT_UNIFORM_VECTORS = 0x8dfd,\n SHADER_TYPE = 0x8b4f,\n SHADING_LANGUAGE_VERSION = 0x8b8c,\n CURRENT_PROGRAM = 0x8b8d,\n\n // Depth or stencil tests\n // Constants passed to depthFunc() or stencilFunc().\n\n /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass, i.e., nothing will be drawn. */\n NEVER = 0x0200,\n /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value. */\n LESS = 0x0201,\n /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value. */\n EQUAL = 0x0202,\n /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value. */\n LEQUAL = 0x0203,\n /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value. */\n GREATER = 0x0204,\n /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value. */\n NOTEQUAL = 0x0205,\n /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value. */\n GEQUAL = 0x0206,\n /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass, i.e., pixels will be drawn in the order they are drawn. */\n ALWAYS = 0x0207,\n\n // Stencil actions\n // Constants passed to stencilOp().\n\n KEEP = 0x1e00,\n REPLACE = 0x1e01,\n INCR = 0x1e02,\n DECR = 0x1e03,\n INVERT = 0x150a,\n INCR_WRAP = 0x8507,\n DECR_WRAP = 0x8508,\n\n // Textures\n // Constants passed to texParameteri(),\n // texParameterf(), bindTexture(), texImage2D(), and others.\n\n NEAREST = 0x2600,\n LINEAR = 0x2601,\n NEAREST_MIPMAP_NEAREST = 0x2700,\n LINEAR_MIPMAP_NEAREST = 0x2701,\n NEAREST_MIPMAP_LINEAR = 0x2702,\n LINEAR_MIPMAP_LINEAR = 0x2703,\n /** The texture magnification function is used when the pixel being textured maps to an area less than or equal to one texture element. It sets the texture magnification function to either GL_NEAREST or GL_LINEAR (see below). GL_NEAREST is generally faster than GL_LINEAR, but it can produce textured images with sharper edges because the transition between texture elements is not as smooth. Default: GL_LINEAR. */\n TEXTURE_MAG_FILTER = 0x2800,\n /** The texture minifying function is used whenever the pixel being textured maps to an area greater than one texture element. There are six defined minifying functions. Two of them use the nearest one or nearest four texture elements to compute the texture value. The other four use mipmaps. Default: GL_NEAREST_MIPMAP_LINEAR */\n TEXTURE_MIN_FILTER = 0x2801,\n /** Sets the wrap parameter for texture coordinate to either GL_CLAMP_TO_EDGE, GL_MIRRORED_REPEAT, or GL_REPEAT. G */\n TEXTURE_WRAP_S = 0x2802,\n /** Sets the wrap parameter for texture coordinate to either GL_CLAMP_TO_EDGE, GL_MIRRORED_REPEAT, or GL_REPEAT. G */\n TEXTURE_WRAP_T = 0x2803,\n TEXTURE_2D = 0x0de1,\n TEXTURE = 0x1702,\n TEXTURE_CUBE_MAP = 0x8513,\n TEXTURE_BINDING_CUBE_MAP = 0x8514,\n TEXTURE_CUBE_MAP_POSITIVE_X = 0x8515,\n TEXTURE_CUBE_MAP_NEGATIVE_X = 0x8516,\n TEXTURE_CUBE_MAP_POSITIVE_Y = 0x8517,\n TEXTURE_CUBE_MAP_NEGATIVE_Y = 0x8518,\n TEXTURE_CUBE_MAP_POSITIVE_Z = 0x8519,\n TEXTURE_CUBE_MAP_NEGATIVE_Z = 0x851a,\n MAX_CUBE_MAP_TEXTURE_SIZE = 0x851c,\n // TEXTURE0 - 31 0x84C0 - 0x84DF A texture unit.\n TEXTURE0 = 0x84c0,\n ACTIVE_TEXTURE = 0x84e0,\n REPEAT = 0x2901,\n CLAMP_TO_EDGE = 0x812f,\n MIRRORED_REPEAT = 0x8370,\n\n // Emulation\n TEXTURE_WIDTH = 0x1000,\n TEXTURE_HEIGHT = 0x1001,\n\n // Uniform types\n\n FLOAT_VEC2 = 0x8b50,\n FLOAT_VEC3 = 0x8b51,\n FLOAT_VEC4 = 0x8b52,\n INT_VEC2 = 0x8b53,\n INT_VEC3 = 0x8b54,\n INT_VEC4 = 0x8b55,\n BOOL = 0x8b56,\n BOOL_VEC2 = 0x8b57,\n BOOL_VEC3 = 0x8b58,\n BOOL_VEC4 = 0x8b59,\n FLOAT_MAT2 = 0x8b5a,\n FLOAT_MAT3 = 0x8b5b,\n FLOAT_MAT4 = 0x8b5c,\n SAMPLER_2D = 0x8b5e,\n SAMPLER_CUBE = 0x8b60,\n\n // Shader precision-specified types\n\n LOW_FLOAT = 0x8df0,\n MEDIUM_FLOAT = 0x8df1,\n HIGH_FLOAT = 0x8df2,\n LOW_INT = 0x8df3,\n MEDIUM_INT = 0x8df4,\n HIGH_INT = 0x8df5,\n\n // Framebuffers and renderbuffers\n\n FRAMEBUFFER = 0x8d40,\n RENDERBUFFER = 0x8d41,\n RGBA4 = 0x8056,\n RGB5_A1 = 0x8057,\n RGB565 = 0x8d62,\n DEPTH_COMPONENT16 = 0x81a5,\n STENCIL_INDEX = 0x1901,\n STENCIL_INDEX8 = 0x8d48,\n DEPTH_STENCIL = 0x84f9,\n RENDERBUFFER_WIDTH = 0x8d42,\n RENDERBUFFER_HEIGHT = 0x8d43,\n RENDERBUFFER_INTERNAL_FORMAT = 0x8d44,\n RENDERBUFFER_RED_SIZE = 0x8d50,\n RENDERBUFFER_GREEN_SIZE = 0x8d51,\n RENDERBUFFER_BLUE_SIZE = 0x8d52,\n RENDERBUFFER_ALPHA_SIZE = 0x8d53,\n RENDERBUFFER_DEPTH_SIZE = 0x8d54,\n RENDERBUFFER_STENCIL_SIZE = 0x8d55,\n FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = 0x8cd0,\n FRAMEBUFFER_ATTACHMENT_OBJECT_NAME = 0x8cd1,\n FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL = 0x8cd2,\n FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE = 0x8cd3,\n COLOR_ATTACHMENT0 = 0x8ce0,\n DEPTH_ATTACHMENT = 0x8d00,\n STENCIL_ATTACHMENT = 0x8d20,\n DEPTH_STENCIL_ATTACHMENT = 0x821a,\n NONE = 0,\n FRAMEBUFFER_COMPLETE = 0x8cd5,\n FRAMEBUFFER_INCOMPLETE_ATTACHMENT = 0x8cd6,\n FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = 0x8cd7,\n FRAMEBUFFER_INCOMPLETE_DIMENSIONS = 0x8cd9,\n FRAMEBUFFER_UNSUPPORTED = 0x8cdd,\n FRAMEBUFFER_BINDING = 0x8ca6,\n RENDERBUFFER_BINDING = 0x8ca7,\n READ_FRAMEBUFFER = 0x8ca8,\n DRAW_FRAMEBUFFER = 0x8ca9,\n MAX_RENDERBUFFER_SIZE = 0x84e8,\n INVALID_FRAMEBUFFER_OPERATION = 0x0506,\n\n // Pixel storage modes\n // Constants passed to pixelStorei().\n\n UNPACK_FLIP_Y_WEBGL = 0x9240,\n UNPACK_PREMULTIPLY_ALPHA_WEBGL = 0x9241,\n UNPACK_COLORSPACE_CONVERSION_WEBGL = 0x9243,\n\n // Additional constants defined WebGL 2\n // These constants are defined on the WebGL2RenderingContext interface.\n // All WebGL 1 constants are also available in a WebGL 2 context.\n\n // Getting GL parameter information\n // Constants passed to getParameter()\n // to specify what information to return.\n\n READ_BUFFER = 0x0c02,\n UNPACK_ROW_LENGTH = 0x0cf2,\n UNPACK_SKIP_ROWS = 0x0cf3,\n UNPACK_SKIP_PIXELS = 0x0cf4,\n PACK_ROW_LENGTH = 0x0d02,\n PACK_SKIP_ROWS = 0x0d03,\n PACK_SKIP_PIXELS = 0x0d04,\n TEXTURE_BINDING_3D = 0x806a,\n UNPACK_SKIP_IMAGES = 0x806d,\n UNPACK_IMAGE_HEIGHT = 0x806e,\n MAX_3D_TEXTURE_SIZE = 0x8073,\n MAX_ELEMENTS_VERTICES = 0x80e8,\n MAX_ELEMENTS_INDICES = 0x80e9,\n MAX_TEXTURE_LOD_BIAS = 0x84fd,\n MAX_FRAGMENT_UNIFORM_COMPONENTS = 0x8b49,\n MAX_VERTEX_UNIFORM_COMPONENTS = 0x8b4a,\n MAX_ARRAY_TEXTURE_LAYERS = 0x88ff,\n MIN_PROGRAM_TEXEL_OFFSET = 0x8904,\n MAX_PROGRAM_TEXEL_OFFSET = 0x8905,\n MAX_VARYING_COMPONENTS = 0x8b4b,\n FRAGMENT_SHADER_DERIVATIVE_HINT = 0x8b8b,\n RASTERIZER_DISCARD = 0x8c89,\n VERTEX_ARRAY_BINDING = 0x85b5,\n MAX_VERTEX_OUTPUT_COMPONENTS = 0x9122,\n MAX_FRAGMENT_INPUT_COMPONENTS = 0x9125,\n MAX_SERVER_WAIT_TIMEOUT = 0x9111,\n MAX_ELEMENT_INDEX = 0x8d6b,\n\n // Textures\n // Constants passed to texParameteri(),\n // texParameterf(), bindTexture(), texImage2D(), and others.\n\n RED = 0x1903,\n RGB8 = 0x8051,\n RGBA8 = 0x8058,\n RGB10_A2 = 0x8059,\n TEXTURE_3D = 0x806f,\n /** Sets the wrap parameter for texture coordinate to either GL_CLAMP_TO_EDGE, GL_MIRRORED_REPEAT, or GL_REPEAT. G */\n TEXTURE_WRAP_R = 0x8072,\n TEXTURE_MIN_LOD = 0x813a,\n TEXTURE_MAX_LOD = 0x813b,\n TEXTURE_BASE_LEVEL = 0x813c,\n TEXTURE_MAX_LEVEL = 0x813d,\n TEXTURE_COMPARE_MODE = 0x884c,\n TEXTURE_COMPARE_FUNC = 0x884d,\n SRGB = 0x8c40,\n SRGB8 = 0x8c41,\n SRGB8_ALPHA8 = 0x8c43,\n COMPARE_REF_TO_TEXTURE = 0x884e,\n RGBA32F = 0x8814,\n RGB32F = 0x8815,\n RGBA16F = 0x881a,\n RGB16F = 0x881b,\n TEXTURE_2D_ARRAY = 0x8c1a,\n TEXTURE_BINDING_2D_ARRAY = 0x8c1d,\n R11F_G11F_B10F = 0x8c3a,\n RGB9_E5 = 0x8c3d,\n RGBA32UI = 0x8d70,\n RGB32UI = 0x8d71,\n RGBA16UI = 0x8d76,\n RGB16UI = 0x8d77,\n RGBA8UI = 0x8d7c,\n RGB8UI = 0x8d7d,\n RGBA32I = 0x8d82,\n RGB32I = 0x8d83,\n RGBA16I = 0x8d88,\n RGB16I = 0x8d89,\n RGBA8I = 0x8d8e,\n RGB8I = 0x8d8f,\n RED_INTEGER = 0x8d94,\n RGB_INTEGER = 0x8d98,\n RGBA_INTEGER = 0x8d99,\n R8 = 0x8229,\n RG8 = 0x822b,\n R16F = 0x822d,\n R32F = 0x822e,\n RG16F = 0x822f,\n RG32F = 0x8230,\n R8I = 0x8231,\n R8UI = 0x8232,\n R16I = 0x8233,\n R16UI = 0x8234,\n R32I = 0x8235,\n R32UI = 0x8236,\n RG8I = 0x8237,\n RG8UI = 0x8238,\n RG16I = 0x8239,\n RG16UI = 0x823a,\n RG32I = 0x823b,\n RG32UI = 0x823c,\n R8_SNORM = 0x8f94,\n RG8_SNORM = 0x8f95,\n RGB8_SNORM = 0x8f96,\n RGBA8_SNORM = 0x8f97,\n RGB10_A2UI = 0x906f,\n\n /* covered by extension\n COMPRESSED_R11_EAC = 0x9270,\n COMPRESSED_SIGNED_R11_EAC = 0x9271,\n COMPRESSED_RG11_EAC = 0x9272,\n COMPRESSED_SIGNED_RG11_EAC = 0x9273,\n COMPRESSED_RGB8_ETC2 = 0x9274,\n COMPRESSED_SRGB8_ETC2 = 0x9275,\n COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9276,\n COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC = 0x9277,\n COMPRESSED_RGBA8_ETC2_EAC = 0x9278,\n COMPRESSED_SRGB8_ALPHA8_ETC2_EAC = 0x9279,\n */\n TEXTURE_IMMUTABLE_FORMAT = 0x912f,\n TEXTURE_IMMUTABLE_LEVELS = 0x82df,\n\n // Pixel types\n\n UNSIGNED_INT_2_10_10_10_REV = 0x8368,\n UNSIGNED_INT_10F_11F_11F_REV = 0x8c3b,\n UNSIGNED_INT_5_9_9_9_REV = 0x8c3e,\n FLOAT_32_UNSIGNED_INT_24_8_REV = 0x8dad,\n UNSIGNED_INT_24_8 = 0x84fa,\n HALF_FLOAT = 0x140b,\n RG = 0x8227,\n RG_INTEGER = 0x8228,\n INT_2_10_10_10_REV = 0x8d9f,\n\n // Queries\n\n CURRENT_QUERY = 0x8865,\n /** Returns a GLuint containing the query result. */\n QUERY_RESULT = 0x8866,\n /** Whether query result is available. */\n QUERY_RESULT_AVAILABLE = 0x8867,\n /** Occlusion query (if drawing passed depth test) */\n ANY_SAMPLES_PASSED = 0x8c2f,\n /** Occlusion query less accurate/faster version */\n ANY_SAMPLES_PASSED_CONSERVATIVE = 0x8d6a,\n\n // Draw buffers\n\n MAX_DRAW_BUFFERS = 0x8824,\n DRAW_BUFFER0 = 0x8825,\n DRAW_BUFFER1 = 0x8826,\n DRAW_BUFFER2 = 0x8827,\n DRAW_BUFFER3 = 0x8828,\n DRAW_BUFFER4 = 0x8829,\n DRAW_BUFFER5 = 0x882a,\n DRAW_BUFFER6 = 0x882b,\n DRAW_BUFFER7 = 0x882c,\n DRAW_BUFFER8 = 0x882d,\n DRAW_BUFFER9 = 0x882e,\n DRAW_BUFFER10 = 0x882f,\n DRAW_BUFFER11 = 0x8830,\n DRAW_BUFFER12 = 0x8831,\n DRAW_BUFFER13 = 0x8832,\n DRAW_BUFFER14 = 0x8833,\n DRAW_BUFFER15 = 0x8834,\n MAX_COLOR_ATTACHMENTS = 0x8cdf,\n COLOR_ATTACHMENT1 = 0x8ce1,\n COLOR_ATTACHMENT2 = 0x8ce2,\n COLOR_ATTACHMENT3 = 0x8ce3,\n COLOR_ATTACHMENT4 = 0x8ce4,\n COLOR_ATTACHMENT5 = 0x8ce5,\n COLOR_ATTACHMENT6 = 0x8ce6,\n COLOR_ATTACHMENT7 = 0x8ce7,\n COLOR_ATTACHMENT8 = 0x8ce8,\n COLOR_ATTACHMENT9 = 0x8ce9,\n COLOR_ATTACHMENT10 = 0x8cea,\n COLOR_ATTACHMENT11 = 0x8ceb,\n COLOR_ATTACHMENT12 = 0x8cec,\n COLOR_ATTACHMENT13 = 0x8ced,\n COLOR_ATTACHMENT14 = 0x8cee,\n COLOR_ATTACHMENT15 = 0x8cef,\n\n // Samplers\n\n SAMPLER_3D = 0x8b5f,\n SAMPLER_2D_SHADOW = 0x8b62,\n SAMPLER_2D_ARRAY = 0x8dc1,\n SAMPLER_2D_ARRAY_SHADOW = 0x8dc4,\n SAMPLER_CUBE_SHADOW = 0x8dc5,\n INT_SAMPLER_2D = 0x8dca,\n INT_SAMPLER_3D = 0x8dcb,\n INT_SAMPLER_CUBE = 0x8dcc,\n INT_SAMPLER_2D_ARRAY = 0x8dcf,\n UNSIGNED_INT_SAMPLER_2D = 0x8dd2,\n UNSIGNED_INT_SAMPLER_3D = 0x8dd3,\n UNSIGNED_INT_SAMPLER_CUBE = 0x8dd4,\n UNSIGNED_INT_SAMPLER_2D_ARRAY = 0x8dd7,\n MAX_SAMPLES = 0x8d57,\n SAMPLER_BINDING = 0x8919,\n\n // Buffers\n\n PIXEL_PACK_BUFFER = 0x88eb,\n PIXEL_UNPACK_BUFFER = 0x88ec,\n PIXEL_PACK_BUFFER_BINDING = 0x88ed,\n PIXEL_UNPACK_BUFFER_BINDING = 0x88ef,\n COPY_READ_BUFFER = 0x8f36,\n COPY_WRITE_BUFFER = 0x8f37,\n COPY_READ_BUFFER_BINDING = 0x8f36,\n COPY_WRITE_BUFFER_BINDING = 0x8f37,\n\n // Data types\n\n FLOAT_MAT2x3 = 0x8b65,\n FLOAT_MAT2x4 = 0x8b66,\n FLOAT_MAT3x2 = 0x8b67,\n FLOAT_MAT3x4 = 0x8b68,\n FLOAT_MAT4x2 = 0x8b69,\n FLOAT_MAT4x3 = 0x8b6a,\n UNSIGNED_INT_VEC2 = 0x8dc6,\n UNSIGNED_INT_VEC3 = 0x8dc7,\n UNSIGNED_INT_VEC4 = 0x8dc8,\n UNSIGNED_NORMALIZED = 0x8c17,\n SIGNED_NORMALIZED = 0x8f9c,\n\n // Vertex attributes\n\n VERTEX_ATTRIB_ARRAY_INTEGER = 0x88fd,\n VERTEX_ATTRIB_ARRAY_DIVISOR = 0x88fe,\n\n // Transform feedback\n\n TRANSFORM_FEEDBACK_BUFFER_MODE = 0x8c7f,\n MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS = 0x8c80,\n TRANSFORM_FEEDBACK_VARYINGS = 0x8c83,\n TRANSFORM_FEEDBACK_BUFFER_START = 0x8c84,\n TRANSFORM_FEEDBACK_BUFFER_SIZE = 0x8c85,\n TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN = 0x8c88,\n MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS = 0x8c8a,\n MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS = 0x8c8b,\n INTERLEAVED_ATTRIBS = 0x8c8c,\n SEPARATE_ATTRIBS = 0x8c8d,\n TRANSFORM_FEEDBACK_BUFFER = 0x8c8e,\n TRANSFORM_FEEDBACK_BUFFER_BINDING = 0x8c8f,\n TRANSFORM_FEEDBACK = 0x8e22,\n TRANSFORM_FEEDBACK_PAUSED = 0x8e23,\n TRANSFORM_FEEDBACK_ACTIVE = 0x8e24,\n TRANSFORM_FEEDBACK_BINDING = 0x8e25,\n\n // Framebuffers and renderbuffers\n\n FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING = 0x8210,\n FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE = 0x8211,\n FRAMEBUFFER_ATTACHMENT_RED_SIZE = 0x8212,\n FRAMEBUFFER_ATTACHMENT_GREEN_SIZE = 0x8213,\n FRAMEBUFFER_ATTACHMENT_BLUE_SIZE = 0x8214,\n FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE = 0x8215,\n FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE = 0x8216,\n FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE = 0x8217,\n FRAMEBUFFER_DEFAULT = 0x8218,\n // DEPTH_STENCIL_ATTACHMENT = 0x821A,\n // DEPTH_STENCIL = 0x84F9,\n DEPTH24_STENCIL8 = 0x88f0,\n DRAW_FRAMEBUFFER_BINDING = 0x8ca6,\n READ_FRAMEBUFFER_BINDING = 0x8caa,\n RENDERBUFFER_SAMPLES = 0x8cab,\n FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER = 0x8cd4,\n FRAMEBUFFER_INCOMPLETE_MULTISAMPLE = 0x8d56,\n\n // Uniforms\n\n UNIFORM_BUFFER = 0x8a11,\n UNIFORM_BUFFER_BINDING = 0x8a28,\n UNIFORM_BUFFER_START = 0x8a29,\n UNIFORM_BUFFER_SIZE = 0x8a2a,\n MAX_VERTEX_UNIFORM_BLOCKS = 0x8a2b,\n MAX_FRAGMENT_UNIFORM_BLOCKS = 0x8a2d,\n MAX_COMBINED_UNIFORM_BLOCKS = 0x8a2e,\n MAX_UNIFORM_BUFFER_BINDINGS = 0x8a2f,\n MAX_UNIFORM_BLOCK_SIZE = 0x8a30,\n MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS = 0x8a31,\n MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS = 0x8a33,\n UNIFORM_BUFFER_OFFSET_ALIGNMENT = 0x8a34,\n ACTIVE_UNIFORM_BLOCKS = 0x8a36,\n UNIFORM_TYPE = 0x8a37,\n UNIFORM_SIZE = 0x8a38,\n UNIFORM_BLOCK_INDEX = 0x8a3a,\n UNIFORM_OFFSET = 0x8a3b,\n UNIFORM_ARRAY_STRIDE = 0x8a3c,\n UNIFORM_MATRIX_STRIDE = 0x8a3d,\n UNIFORM_IS_ROW_MAJOR = 0x8a3e,\n UNIFORM_BLOCK_BINDING = 0x8a3f,\n UNIFORM_BLOCK_DATA_SIZE = 0x8a40,\n UNIFORM_BLOCK_ACTIVE_UNIFORMS = 0x8a42,\n UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES = 0x8a43,\n UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER = 0x8a44,\n UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER = 0x8a46,\n\n // Sync objects\n\n OBJECT_TYPE = 0x9112,\n SYNC_CONDITION = 0x9113,\n SYNC_STATUS = 0x9114,\n SYNC_FLAGS = 0x9115,\n SYNC_FENCE = 0x9116,\n SYNC_GPU_COMMANDS_COMPLETE = 0x9117,\n UNSIGNALED = 0x9118,\n SIGNALED = 0x9119,\n ALREADY_SIGNALED = 0x911a,\n TIMEOUT_EXPIRED = 0x911b,\n CONDITION_SATISFIED = 0x911c,\n WAIT_FAILED = 0x911d,\n SYNC_FLUSH_COMMANDS_BIT = 0x00000001,\n\n // Miscellaneous constants\n\n COLOR = 0x1800,\n DEPTH = 0x1801,\n STENCIL = 0x1802,\n MIN = 0x8007,\n MAX = 0x8008,\n DEPTH_COMPONENT24 = 0x81a6,\n STREAM_READ = 0x88e1,\n STREAM_COPY = 0x88e2,\n STATIC_READ = 0x88e5,\n STATIC_COPY = 0x88e6,\n DYNAMIC_READ = 0x88e9,\n DYNAMIC_COPY = 0x88ea,\n DEPTH_COMPONENT32F = 0x8cac,\n DEPTH32F_STENCIL8 = 0x8cad,\n INVALID_INDEX = 0xffffffff,\n TIMEOUT_IGNORED = -1,\n MAX_CLIENT_WAIT_TIMEOUT_WEBGL = 0x9247,\n\n // Constants defined in WebGL extensions\n\n // WEBGL_debug_renderer_info\n\n /** Passed to getParameter to get the vendor string of the graphics driver. */\n UNMASKED_VENDOR_WEBGL = 0x9245,\n /** Passed to getParameter to get the renderer string of the graphics driver. */\n UNMASKED_RENDERER_WEBGL = 0x9246,\n\n // EXT_texture_filter_anisotropic\n\n /** Returns the maximum available anisotropy. */\n MAX_TEXTURE_MAX_ANISOTROPY_EXT = 0x84ff,\n /** Passed to texParameter to set the desired maximum anisotropy for a texture. */\n TEXTURE_MAX_ANISOTROPY_EXT = 0x84fe,\n\n // EXT_texture_norm16 - https://khronos.org/registry/webgl/extensions/EXT_texture_norm16/\n\n R16_EXT = 0x822a,\n RG16_EXT = 0x822c,\n RGB16_EXT = 0x8054,\n RGBA16_EXT = 0x805b,\n R16_SNORM_EXT = 0x8f98,\n RG16_SNORM_EXT = 0x8f99,\n RGB16_SNORM_EXT = 0x8f9a,\n RGBA16_SNORM_EXT = 0x8f9b,\n\n // WEBGL_compressed_texture_s3tc (BC1, BC2, BC3)\n\n /** A DXT1-compressed image in an RGB image format. */\n COMPRESSED_RGB_S3TC_DXT1_EXT = 0x83f0,\n /** A DXT1-compressed image in an RGB image format with a simple on/off alpha value. */\n COMPRESSED_RGBA_S3TC_DXT1_EXT = 0x83f1,\n /** A DXT3-compressed image in an RGBA image format. Compared to a 32-bit RGBA texture, it offers 4:1 compression. */\n COMPRESSED_RGBA_S3TC_DXT3_EXT = 0x83f2,\n /** A DXT5-compressed image in an RGBA image format. It also provides a 4:1 compression, but differs to the DXT3 compression in how the alpha compression is done. */\n COMPRESSED_RGBA_S3TC_DXT5_EXT = 0x83f3,\n\n // WEBGL_compressed_texture_s3tc_srgb (BC1, BC2, BC3 - SRGB)\n\n COMPRESSED_SRGB_S3TC_DXT1_EXT = 0x8c4c,\n COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT = 0x8c4d,\n COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT = 0x8c4e,\n COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT = 0x8c4f,\n\n // WEBGL_compressed_texture_rgtc (BC4, BC5)\n\n COMPRESSED_RED_RGTC1_EXT = 0x8dbb,\n COMPRESSED_SIGNED_RED_RGTC1_EXT = 0x8dbc,\n COMPRESSED_RED_GREEN_RGTC2_EXT = 0x8dbd,\n COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT = 0x8dbe,\n\n // WEBGL_compressed_texture_bptc (BC6, BC7)\n\n COMPRESSED_RGBA_BPTC_UNORM_EXT = 0x8e8c,\n COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT = 0x8e8d,\n COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT = 0x8e8e,\n COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT = 0x8e8f,\n\n // WEBGL_compressed_texture_es3\n\n /** One-channel (red) unsigned format compression. */\n COMPRESSED_R11_EAC = 0x9270,\n /** One-channel (red) signed format compression. */\n COMPRESSED_SIGNED_R11_EAC = 0x9271,\n /** Two-channel (red and green) unsigned format compression. */\n COMPRESSED_RG11_EAC = 0x9272,\n /** Two-channel (red and green) signed format compression. */\n COMPRESSED_SIGNED_RG11_EAC = 0x9273,\n /** Compresses RGB8 data with no alpha channel. */\n COMPRESSED_RGB8_ETC2 = 0x9274,\n /** Compresses RGBA8 data. The RGB part is encoded the same as RGB_ETC2, but the alpha part is encoded separately. */\n COMPRESSED_RGBA8_ETC2_EAC = 0x9275,\n /** Compresses sRGB8 data with no alpha channel. */\n COMPRESSED_SRGB8_ETC2 = 0x9276,\n /** Compresses sRGBA8 data. The sRGB part is encoded the same as SRGB_ETC2, but the alpha part is encoded separately. */\n COMPRESSED_SRGB8_ALPHA8_ETC2_EAC = 0x9277,\n /** Similar to RGB8_ETC, but with ability to punch through the alpha channel, which means to make it completely opaque or transparent. */\n COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9278,\n /** Similar to SRGB8_ETC, but with ability to punch through the alpha channel, which means to make it completely opaque or transparent. */\n COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9279,\n\n // WEBGL_compressed_texture_pvrtc\n\n /** RGB compression in 4-bit mode. One block for each 4×4 pixels. */\n COMPRESSED_RGB_PVRTC_4BPPV1_IMG = 0x8c00,\n /** RGBA compression in 4-bit mode. One block for each 4×4 pixels. */\n COMPRESSED_RGBA_PVRTC_4BPPV1_IMG = 0x8c02,\n /** RGB compression in 2-bit mode. One block for each 8×4 pixels. */\n COMPRESSED_RGB_PVRTC_2BPPV1_IMG = 0x8c01,\n /** RGBA compression in 2-bit mode. One block for each 8×4 pixels. */\n COMPRESSED_RGBA_PVRTC_2BPPV1_IMG = 0x8c03,\n\n // WEBGL_compressed_texture_etc1\n\n /** Compresses 24-bit RGB data with no alpha channel. */\n COMPRESSED_RGB_ETC1_WEBGL = 0x8d64,\n\n // WEBGL_compressed_texture_atc\n\n COMPRESSED_RGB_ATC_WEBGL = 0x8c92,\n COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL = 0x8c92,\n COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL = 0x87ee,\n\n // WEBGL_compressed_texture_astc\n\n COMPRESSED_RGBA_ASTC_4x4_KHR = 0x93b0,\n COMPRESSED_RGBA_ASTC_5x4_KHR = 0x93b1,\n COMPRESSED_RGBA_ASTC_5x5_KHR = 0x93b2,\n COMPRESSED_RGBA_ASTC_6x5_KHR = 0x93b3,\n COMPRESSED_RGBA_ASTC_6x6_KHR = 0x93b4,\n COMPRESSED_RGBA_ASTC_8x5_KHR = 0x93b5,\n COMPRESSED_RGBA_ASTC_8x6_KHR = 0x93b6,\n COMPRESSED_RGBA_ASTC_8x8_KHR = 0x93b7,\n COMPRESSED_RGBA_ASTC_10x5_KHR = 0x93b8,\n COMPRESSED_RGBA_ASTC_10x6_KHR = 0x93b9,\n COMPRESSED_RGBA_ASTC_10x8_KHR = 0x93ba,\n COMPRESSED_RGBA_ASTC_10x10_KHR = 0x93bb,\n COMPRESSED_RGBA_ASTC_12x10_KHR = 0x93bc,\n COMPRESSED_RGBA_ASTC_12x12_KHR = 0x93bd,\n COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR = 0x93d0,\n COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR = 0x93d1,\n COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR = 0x93d2,\n COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR = 0x93d3,\n COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR = 0x93d4,\n COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR = 0x93d5,\n COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR = 0x93d6,\n COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR = 0x93d7,\n COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR = 0x93d8,\n COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR = 0x93d9,\n COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR = 0x93da,\n COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR = 0x93db,\n COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR = 0x93dc,\n COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR = 0x93dd,\n\n // EXT_disjoint_timer_query\n\n /** The number of bits used to hold the query result for the given target. */\n QUERY_COUNTER_BITS_EXT = 0x8864,\n /** The currently active query. */\n CURRENT_QUERY_EXT = 0x8865,\n /** The query result. */\n QUERY_RESULT_EXT = 0x8866,\n /** A Boolean indicating whether or not a query result is available. */\n QUERY_RESULT_AVAILABLE_EXT = 0x8867,\n /** Elapsed time (in nanoseconds). */\n TIME_ELAPSED_EXT = 0x88bf,\n /** The current time. */\n TIMESTAMP_EXT = 0x8e28,\n /** A Boolean indicating whether or not the GPU performed any disjoint operation (lost context) */\n GPU_DISJOINT_EXT = 0x8fbb,\n\n // KHR_parallel_shader_compile https://registry.khronos.org/webgl/extensions/KHR_parallel_shader_compile\n\n /** a non-blocking poll operation, so that compile/link status availability can be queried without potentially incurring stalls */\n COMPLETION_STATUS_KHR = 0x91b1,\n\n // EXT_depth_clamp https://registry.khronos.org/webgl/extensions/EXT_depth_clamp/\n\n /** Disables depth clipping */\n DEPTH_CLAMP_EXT = 0x864f,\n\n // WEBGL_provoking_vertex https://registry.khronos.org/webgl/extensions/WEBGL_provoking_vertex/\n\n /** Values of first vertex in primitive are used for flat shading */\n FIRST_VERTEX_CONVENTION_WEBGL = 0x8e4d,\n /** Values of first vertex in primitive are used for flat shading */\n LAST_VERTEX_CONVENTION_WEBGL = 0x8e4e, // default\n /** Controls which vertex in primitive is used for flat shading */\n PROVOKING_VERTEX_WEBL = 0x8e4f,\n\n // WEBGL_polygon_mode https://registry.khronos.org/webgl/extensions/WEBGL_polygon_mode/\n\n POLYGON_MODE_WEBGL = 0x0b40,\n POLYGON_OFFSET_LINE_WEBGL = 0x2a02,\n LINE_WEBGL = 0x1b01,\n FILL_WEBGL = 0x1b02,\n\n // WEBGL_clip_cull_distance https://registry.khronos.org/webgl/extensions/WEBGL_clip_cull_distance/\n\n /** Max clip distances */\n MAX_CLIP_DISTANCES_WEBGL = 0x0d32,\n /** Max cull distances */\n MAX_CULL_DISTANCES_WEBGL = 0x82f9,\n /** Max clip and cull distances */\n MAX_COMBINED_CLIP_AND_CULL_DISTANCES_WEBGL = 0x82fa,\n\n /** Enable gl_ClipDistance[0] and gl_CullDistance[0] */\n CLIP_DISTANCE0_WEBGL = 0x3000,\n /** Enable gl_ClipDistance[1] and gl_CullDistance[1] */\n CLIP_DISTANCE1_WEBGL = 0x3001,\n /** Enable gl_ClipDistance[2] and gl_CullDistance[2] */\n CLIP_DISTANCE2_WEBGL = 0x3002,\n /** Enable gl_ClipDistance[3] and gl_CullDistance[3] */\n CLIP_DISTANCE3_WEBGL = 0x3003,\n /** Enable gl_ClipDistance[4] and gl_CullDistance[4] */\n CLIP_DISTANCE4_WEBGL = 0x3004,\n /** Enable gl_ClipDistance[5] and gl_CullDistance[5] */\n CLIP_DISTANCE5_WEBGL = 0x3005,\n /** Enable gl_ClipDistance[6] and gl_CullDistance[6] */\n CLIP_DISTANCE6_WEBGL = 0x3006,\n /** Enable gl_ClipDistance[7] and gl_CullDistance[7] */\n CLIP_DISTANCE7_WEBGL = 0x3007,\n\n /** EXT_polygon_offset_clamp https://registry.khronos.org/webgl/extensions/EXT_polygon_offset_clamp/ */\n POLYGON_OFFSET_CLAMP_EXT = 0x8e1b,\n\n /** EXT_clip_control https://registry.khronos.org/webgl/extensions/EXT_clip_control/ */\n LOWER_LEFT_EXT = 0x8ca1,\n UPPER_LEFT_EXT = 0x8ca2,\n\n NEGATIVE_ONE_TO_ONE_EXT = 0x935e,\n ZERO_TO_ONE_EXT = 0x935f,\n\n CLIP_ORIGIN_EXT = 0x935c,\n CLIP_DEPTH_MODE_EXT = 0x935d,\n\n /** WEBGL_blend_func_extended https://registry.khronos.org/webgl/extensions/WEBGL_blend_func_extended/ */\n SRC1_COLOR_WEBGL = 0x88f9,\n SRC1_ALPHA_WEBGL = 0x8589,\n ONE_MINUS_SRC1_COLOR_WEBGL = 0x88fa,\n ONE_MINUS_SRC1_ALPHA_WEBGL = 0x88fb,\n MAX_DUAL_SOURCE_DRAW_BUFFERS_WEBGL = 0x88fc,\n\n /** EXT_texture_mirror_clamp_to_edge https://registry.khronos.org/webgl/extensions/EXT_texture_mirror_clamp_to_edge/ */\n MIRROR_CLAMP_TO_EDGE_EXT = 0x8743\n}\n\nexport {GLEnum as GL};\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport {GL} from './webgl-constants';\n\nexport type {\n GLTextureTarget,\n GLTextureCubeMapTarget,\n GLTexelDataFormat,\n GLPrimitiveTopology,\n GLPrimitive,\n GLDataType,\n GLPixelType,\n GLUniformType,\n GLSamplerType,\n GLFunction,\n GLBlendEquation,\n GLBlendFunction,\n GLStencilOp,\n GLSamplerParameters,\n GLValueParameters,\n GLPackParameters,\n GLUnpackParameters,\n GLFunctionParameters,\n GLParameters,\n GLLimits,\n GLExtensions,\n GLPolygonMode,\n GLProvokingVertex\n} from './webgl-types';\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// Goal is to make WebGL2 contexts look like WebGL1\n// @note Partly inspired by with some older code from the `regl` library\n\n/* eslint-disable camelcase */\n\nimport {GL} from '@luma.gl/webgl/constants';\n\n// webgl1 extensions natively supported by webgl2\nconst WEBGL1_STATIC_EXTENSIONS = {\n WEBGL_depth_texture: {\n UNSIGNED_INT_24_8_WEBGL: GL.UNSIGNED_INT_24_8\n } as const satisfies WEBGL_depth_texture,\n OES_element_index_uint: {} as const satisfies OES_element_index_uint,\n OES_texture_float: {} as const satisfies OES_texture_float,\n OES_texture_half_float: {\n // @ts-expect-error different numbers?\n HALF_FLOAT_OES: GL.HALF_FLOAT\n } as const satisfies OES_texture_half_float,\n EXT_color_buffer_float: {} as const satisfies EXT_color_buffer_float,\n OES_standard_derivatives: {\n FRAGMENT_SHADER_DERIVATIVE_HINT_OES: GL.FRAGMENT_SHADER_DERIVATIVE_HINT\n } as const satisfies OES_standard_derivatives,\n EXT_frag_depth: {} as const satisfies EXT_frag_depth,\n EXT_blend_minmax: {\n MIN_EXT: GL.MIN,\n MAX_EXT: GL.MAX\n } as const satisfies EXT_blend_minmax,\n EXT_shader_texture_lod: {} as const satisfies EXT_shader_texture_lod\n};\n\nconst getWEBGL_draw_buffers = (gl: WebGL2RenderingContext) =>\n ({\n drawBuffersWEBGL(buffers: number[]) {\n return gl.drawBuffers(buffers);\n },\n COLOR_ATTACHMENT0_WEBGL: GL.COLOR_ATTACHMENT0,\n COLOR_ATTACHMENT1_WEBGL: GL.COLOR_ATTACHMENT1,\n COLOR_ATTACHMENT2_WEBGL: GL.COLOR_ATTACHMENT2,\n COLOR_ATTACHMENT3_WEBGL: GL.COLOR_ATTACHMENT3\n }) as const satisfies Partial; // - too many fields\n\nconst getOES_vertex_array_object = (gl: WebGL2RenderingContext) =>\n ({\n VERTEX_ARRAY_BINDING_OES: GL.VERTEX_ARRAY_BINDING,\n createVertexArrayOES() {\n return gl.createVertexArray();\n },\n deleteVertexArrayOES(vertexArray: WebGLVertexArrayObject): void {\n return gl.deleteVertexArray(vertexArray);\n },\n isVertexArrayOES(vertexArray: WebGLVertexArrayObject): boolean {\n return gl.isVertexArray(vertexArray);\n },\n bindVertexArrayOES(vertexArray: WebGLVertexArrayObject): void {\n return gl.bindVertexArray(vertexArray);\n }\n }) as const satisfies OES_vertex_array_object;\n\nconst getANGLE_instanced_arrays = (gl: WebGL2RenderingContext) =>\n ({\n VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: 0x88fe,\n drawArraysInstancedANGLE(...args) {\n return gl.drawArraysInstanced(...args);\n },\n drawElementsInstancedANGLE(...args) {\n return gl.drawElementsInstanced(...args);\n },\n vertexAttribDivisorANGLE(...args) {\n return gl.vertexAttribDivisor(...args);\n }\n }) as const satisfies ANGLE_instanced_arrays;\n\n/**\n * Make browser return WebGL2 contexts even if WebGL1 contexts are requested\n * @param enforce\n * @returns\n */\nexport function enforceWebGL2(enforce: boolean = true): void {\n const prototype = HTMLCanvasElement.prototype as any;\n if (!enforce && prototype.originalGetContext) {\n // Reset the original getContext function\n prototype.getContext = prototype.originalGetContext;\n prototype.originalGetContext = undefined;\n return;\n }\n\n // Store the original getContext function\n prototype.originalGetContext = prototype.getContext;\n\n // Override the getContext function\n prototype.getContext = function (contextId: string, options?: WebGLContextAttributes) {\n // Attempt to force WebGL2 for all WebGL1 contexts\n if (contextId === 'webgl' || contextId === 'experimental-webgl') {\n const context = this.originalGetContext('webgl2', options) as WebGL2RenderingContext;\n // Work around test mocking\n if (context instanceof HTMLElement) {\n polyfillWebGL1Extensions(context);\n }\n return context;\n }\n // For any other type, return the original context\n return this.originalGetContext(contextId, options);\n };\n}\n\n/** Install WebGL1-only extensions on WebGL2 contexts */\nexport function polyfillWebGL1Extensions(gl: WebGL2RenderingContext): void {\n // Enable, to support float and half-float textures\n gl.getExtension('EXT_color_buffer_float');\n\n // WebGL1 extensions implemented using WebGL2 APIs\n const boundExtensions = {\n ...WEBGL1_STATIC_EXTENSIONS,\n WEBGL_disjoint_timer_query: gl.getExtension('EXT_disjoint_timer_query_webgl2'),\n WEBGL_draw_buffers: getWEBGL_draw_buffers(gl),\n OES_vertex_array_object: getOES_vertex_array_object(gl),\n ANGLE_instanced_arrays: getANGLE_instanced_arrays(gl)\n };\n\n // Override gl.getExtension\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalGetExtension = gl.getExtension;\n gl.getExtension = function (extensionName: string) {\n const ext = originalGetExtension.call(gl, extensionName);\n if (ext) {\n return ext;\n }\n\n // Injected extensions\n if (extensionName in boundExtensions) {\n // @ts-ignore TODO string index\n return boundExtensions[extensionName];\n }\n\n return null;\n };\n\n // Override gl.getSupportedExtensions\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalGetSupportedExtensions = gl.getSupportedExtensions;\n gl.getSupportedExtensions = function (): string[] | null {\n const extensions = originalGetSupportedExtensions.apply(gl) || [];\n return extensions?.concat(Object.keys(boundExtensions));\n };\n}\n\n// Update unsized WebGL1 formats to sized WebGL2 formats\n// todo move to texture format file\n// export function getInternalFormat(gl: WebGL2RenderingContext, format: GL, type: GL): GL {\n// // webgl2 texture formats\n// // https://webgl2fundamentals.org/webgl/lessons/webgl-data-textures.html\n// switch (format) {\n// case GL.DEPTH_COMPONENT:\n// return GL.DEPTH_COMPONENT24;\n// case GL.DEPTH_STENCIL:\n// return GL.DEPTH24_STENCIL8;\n// case GL.RGBA:\n// return type === GL.HALF_FLOAT ? GL.RGBA16F : GL.RGBA32F;\n// case GL.RGB:\n// return type === GL.HALF_FLOAT ? GL.RGB16F : GL.RGB32F;\n// default:\n// return format;\n// }\n// }\n\n/*\n// texture type to update on the fly\nexport function getTextureType(gl: WebGL2RenderingContext, type: GL): GL {\n if (type === HALF_FLOAT_OES) {\n return GL.HALF_FLOAT;\n }\n return type;\n}\n\n // And texImage2D to convert the internalFormat to webgl2.\n const webgl2 = this;\n const origTexImage = gl.texImage2D;\n gl.texImage2D = function (target, miplevel, iformat, a, typeFor6, c, d, typeFor9, f) {\n if (arguments.length == 6) {\n var ifmt = webgl2.getInternalFormat(gl, iformat, typeFor6);\n origTexImage.apply(gl, [target, miplevel, ifmt, a, webgl.getTextureType(gl, typeFor6), c]);\n } else {\n // arguments.length == 9\n var ifmt = webgl2.getInternalFormat(gl, iformat, typeFor9);\n origTexImage.apply(gl, [\n target,\n miplevel,\n ifmt,\n a,\n typeFor6,\n c,\n d,\n webgl2.getTextureType(gl, typeFor9),\n f\n ]);\n }\n };\n};\n*/\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/**\n * Load a script (identified by an url). When the url returns, the\n * content of this file is added into a new script element, attached to the DOM (body element)\n * @param scriptUrl defines the url of the script to laod\n * @param scriptId defines the id of the script element\n */\nexport async function loadScript(scriptUrl: string, scriptId?: string): Promise {\n const head = document.getElementsByTagName('head')[0];\n if (!head) {\n throw new Error('loadScript');\n }\n\n const script = document.createElement('script');\n script.setAttribute('type', 'text/javascript');\n script.setAttribute('src', scriptUrl);\n if (scriptId) {\n script.id = scriptId;\n }\n\n return new Promise((resolve, reject) => {\n script.onload = resolve;\n script.onerror = error =>\n reject(new Error(`Unable to load script '${scriptUrl}': ${error as string}`));\n head.appendChild(script);\n });\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {GLExtensions} from '@luma.gl/webgl/constants';\n\n/**\n * Stores luma.gl specific state associated with a context\n */\nexport interface WebGLContextData {\n /** This type is used by lower level code that is not aware of the Device type */\n device?: unknown;\n _polyfilled: boolean;\n extensions: GLExtensions;\n softwareRenderer?: boolean;\n}\n\n/**\n * Gets luma.gl specific state from a context\n * @returns context state\n */\nexport function getWebGLContextData(gl: WebGL2RenderingContext): WebGLContextData {\n // @ts-expect-error\n const contextData = (gl.luma as WebGLContextData | null) || {\n _polyfilled: false,\n extensions: {},\n softwareRenderer: false\n };\n\n contextData._polyfilled ??= false;\n contextData.extensions ||= {};\n\n // @ts-expect-error\n gl.luma = contextData;\n\n return contextData;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {log} from '@luma.gl/core';\nimport {loadScript} from '../../utils/load-script';\nimport {getWebGLContextData} from '../helpers/webgl-context-data';\n\nimport type {Spector} from './spector-types';\n\n/** Spector debug initialization options */\ntype SpectorProps = {\n /** Whether spector.js is enabled */\n debugSpectorJS?: boolean;\n /** URL to load spector script from. Typically a CDN URL */\n debugSpectorJSUrl?: string;\n /** Canvas to monitor */\n gl?: WebGL2RenderingContext;\n};\n\nconst LOG_LEVEL = 1;\n\nlet spector: Spector | null = null;\nlet initialized: boolean = false;\n\ndeclare global {\n // @ts-ignore\n // eslint-disable-next-line no-var\n var SPECTOR: Spector;\n}\n\nexport const DEFAULT_SPECTOR_PROPS: Required = {\n debugSpectorJS: log.get('debug-spectorjs'),\n // https://github.com/BabylonJS/Spector.js#basic-usage\n // https://forum.babylonjs.com/t/spectorcdn-is-temporarily-off/48241\n // spectorUrl: 'https://spectorcdn.babylonjs.com/spector.bundle.js';\n debugSpectorJSUrl: 'https://cdn.jsdelivr.net/npm/spectorjs@0.9.30/dist/spector.bundle.js',\n gl: undefined!\n};\n\n/** Loads spector from CDN if not already installed */\nexport async function loadSpectorJS(props: {debugSpectorJSUrl?: string}): Promise {\n if (!globalThis.SPECTOR) {\n try {\n await loadScript(props.debugSpectorJSUrl || DEFAULT_SPECTOR_PROPS.debugSpectorJSUrl);\n } catch (error) {\n log.warn(String(error));\n }\n }\n}\n\nexport function initializeSpectorJS(props: SpectorProps): Spector | null {\n props = {...DEFAULT_SPECTOR_PROPS, ...props};\n if (!props.debugSpectorJS) {\n return null;\n }\n\n if (!spector && globalThis.SPECTOR && !globalThis.luma?.spector) {\n log.probe(LOG_LEVEL, 'SPECTOR found and initialized. Start with `luma.spector.displayUI()`')();\n const {Spector: SpectorJS} = globalThis.SPECTOR as any;\n spector = new SpectorJS();\n if (globalThis.luma) {\n (globalThis.luma as any).spector = spector;\n }\n }\n\n if (!spector) {\n return null;\n }\n\n if (!initialized) {\n initialized = true;\n\n // enables recording some extra information merged in the capture like texture memory sizes and formats\n spector.spyCanvases();\n // A callback when results are ready\n spector?.onCaptureStarted.add((capture: unknown) =>\n log.info('Spector capture started:', capture)()\n );\n spector?.onCapture.add((capture: unknown) => {\n log.info('Spector capture complete:', capture)();\n // Use undocumented Spector API to open the UI with our capture\n // See https://github.com/BabylonJS/Spector.js/blob/767ad1195a25b85a85c381f400eb50a979239eca/src/spector.ts#L124\n spector?.getResultUI();\n // @ts-expect-error private\n spector?.resultView.display();\n // @ts-expect-error private\n spector?.resultView.addCapture(capture);\n });\n }\n\n if (props.gl) {\n // capture startup\n const gl = props.gl;\n const contextData = getWebGLContextData(gl);\n const device = contextData.device;\n spector?.startCapture(props.gl, 500); // 500 commands\n contextData.device = device;\n\n new Promise(resolve => setTimeout(resolve, 2000)).then(_ => {\n log.info('Spector capture stopped after 2 seconds')();\n spector?.stopCapture();\n // spector?.displayUI();\n });\n }\n\n return spector;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {log} from '@luma.gl/core';\n// Rename constant to prevent inlining. We need the full set of constants for generating debug strings.\nimport {GL as GLEnum} from '@luma.gl/webgl/constants';\nimport {isBrowser} from '@probe.gl/env';\nimport {loadScript} from '../../utils/load-script';\n\nconst WEBGL_DEBUG_CDN_URL = 'https://unpkg.com/webgl-debug@2.0.1/index.js';\n\ntype DebugContextProps = {\n debugWebGL?: boolean;\n traceWebGL?: boolean;\n};\n\ntype ContextData = {\n realContext?: WebGL2RenderingContext;\n debugContext?: WebGL2RenderingContext;\n};\n\n// Helper to get shared context data\nfunction getWebGLContextData(gl: any): ContextData {\n gl.luma = gl.luma || {};\n return gl.luma;\n}\n\ndeclare global {\n // eslint-disable-next-line no-var\n var WebGLDebugUtils: any;\n}\n\n/**\n * Loads Khronos WebGLDeveloperTools from CDN if not already installed\n * const WebGLDebugUtils = require('webgl-debug');\n * @see https://github.com/KhronosGroup/WebGLDeveloperTools\n * @see https://github.com/vorg/webgl-debug\n */\nexport async function loadWebGLDeveloperTools(): Promise {\n if (isBrowser() && !globalThis.WebGLDebugUtils) {\n globalThis.global = globalThis.global || globalThis;\n // @ts-expect-error Developer tools expects global to be set\n globalThis.global.module = {};\n await loadScript(WEBGL_DEBUG_CDN_URL);\n }\n}\n\n// Returns (a potentially new) context with debug instrumentation turned off or on.\n// Note that this actually returns a new context\nexport function makeDebugContext(\n gl: WebGL2RenderingContext,\n props: DebugContextProps = {}\n): WebGL2RenderingContext {\n return props.debugWebGL || props.traceWebGL ? getDebugContext(gl, props) : getRealContext(gl);\n}\n\n// Returns the real context from either of the real/debug contexts\nfunction getRealContext(gl: WebGL2RenderingContext): WebGL2RenderingContext {\n const data = getWebGLContextData(gl);\n // If the context has a realContext member, it is a debug context so return the realContext\n return data.realContext ? data.realContext : gl;\n}\n\n// Returns the debug context from either of the real/debug contexts\nfunction getDebugContext(\n gl: WebGL2RenderingContext,\n props: DebugContextProps\n): WebGL2RenderingContext {\n if (!globalThis.WebGLDebugUtils) {\n log.warn('webgl-debug not loaded')();\n return gl;\n }\n\n const data = getWebGLContextData(gl);\n\n // If this already has a debug context, return it.\n if (data.debugContext) {\n return data.debugContext;\n }\n\n // Create a new debug context\n globalThis.WebGLDebugUtils.init({...GLEnum, ...gl});\n const glDebug = globalThis.WebGLDebugUtils.makeDebugContext(\n gl,\n onGLError.bind(null, props),\n onValidateGLFunc.bind(null, props)\n );\n\n // Make sure we have all WebGL2 and extension constants (todo dynamic import to circumvent minification?)\n for (const key in GLEnum) {\n if (!(key in glDebug) && typeof GLEnum[key] === 'number') {\n glDebug[key] = GLEnum[key];\n }\n }\n\n // Ensure we have a clean prototype on the instrumented object\n // Note: setPrototypeOf does come with perf warnings, but we already take a bigger perf reduction\n // by synchronizing the WebGL errors after each WebGL call.\n class WebGLDebugContext {}\n Object.setPrototypeOf(glDebug, Object.getPrototypeOf(gl));\n Object.setPrototypeOf(WebGLDebugContext, glDebug);\n const debugContext = Object.create(WebGLDebugContext);\n // Store the debug context\n data.realContext = gl;\n data.debugContext = debugContext;\n // Share the context metadata object with the debug context so lookups stay consistent.\n (debugContext as {luma?: unknown}).luma = data;\n debugContext.debug = true;\n\n // Return it\n return debugContext;\n}\n\n// DEBUG TRACING\n\nfunction getFunctionString(functionName: string, functionArgs: unknown[]): string {\n // Cover bug in webgl-debug-tools\n functionArgs = Array.from(functionArgs).map(arg => (arg === undefined ? 'undefined' : arg));\n let args = globalThis.WebGLDebugUtils.glFunctionArgsToString(functionName, functionArgs);\n args = `${args.slice(0, 100)}${args.length > 100 ? '...' : ''}`;\n return `gl.${functionName}(${args})`;\n}\n\nfunction onGLError(\n props: DebugContextProps,\n err: number,\n functionName: string,\n args: unknown[]\n): void {\n // Cover bug in webgl-debug-tools\n args = Array.from(args).map(arg => (arg === undefined ? 'undefined' : arg));\n const errorMessage = globalThis.WebGLDebugUtils.glEnumToString(err);\n const functionArgs = globalThis.WebGLDebugUtils.glFunctionArgsToString(functionName, args);\n const message = `${errorMessage} in gl.${functionName}(${functionArgs})`;\n // TODO - call device.reportError\n log.error(\n '%cWebGL',\n 'color: white; background: red; padding: 2px 6px; border-radius: 3px;',\n message\n )();\n // biome-ignore lint/suspicious/noDebugger: pause immediately on WebGL debug utility errors.\n debugger;\n throw new Error(message);\n}\n\n// Don't generate function string until it is needed\nfunction onValidateGLFunc(\n props: DebugContextProps,\n functionName: string,\n functionArgs: unknown[]\n): void {\n let functionString: string = '';\n if (props.traceWebGL && log.level >= 1) {\n functionString = getFunctionString(functionName, functionArgs);\n log.info(\n 1,\n '%cWebGL',\n 'color: white; background: blue; padding: 2px 6px; border-radius: 3px;',\n functionString\n )();\n }\n\n for (const arg of functionArgs) {\n if (arg === undefined) {\n functionString = functionString || getFunctionString(functionName, functionArgs);\n // biome-ignore lint/suspicious/noDebugger: pause when validating undefined WebGL call arguments.\n debugger;\n // throw new Error(`Undefined argument: ${functionString}`);\n }\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// @ts-nocheck TODO fix\n\n// Tables describing WebGL parameters\nimport {GL, GLParameters} from '@luma.gl/webgl/constants';\n\n// DEFAULT SETTINGS - FOR FAST CACHE INITIALIZATION AND CONTEXT RESETS\n\n/* eslint-disable no-shadow */\n\nexport const GL_PARAMETER_DEFAULTS: GLParameters = {\n [GL.BLEND]: false,\n [GL.BLEND_COLOR]: new Float32Array([0, 0, 0, 0]),\n [GL.BLEND_EQUATION_RGB]: GL.FUNC_ADD,\n [GL.BLEND_EQUATION_ALPHA]: GL.FUNC_ADD,\n [GL.BLEND_SRC_RGB]: GL.ONE,\n [GL.BLEND_DST_RGB]: GL.ZERO,\n [GL.BLEND_SRC_ALPHA]: GL.ONE,\n [GL.BLEND_DST_ALPHA]: GL.ZERO,\n [GL.COLOR_CLEAR_VALUE]: new Float32Array([0, 0, 0, 0]), // TBD\n [GL.COLOR_WRITEMASK]: [true, true, true, true],\n [GL.CULL_FACE]: false,\n [GL.CULL_FACE_MODE]: GL.BACK,\n [GL.DEPTH_TEST]: false,\n [GL.DEPTH_CLEAR_VALUE]: 1,\n [GL.DEPTH_FUNC]: GL.LESS,\n [GL.DEPTH_RANGE]: new Float32Array([0, 1]), // TBD\n [GL.DEPTH_WRITEMASK]: true,\n [GL.DITHER]: true,\n [GL.CURRENT_PROGRAM]: null,\n // FRAMEBUFFER_BINDING and DRAW_FRAMEBUFFER_BINDING(WebGL2) refer same state.\n [GL.FRAMEBUFFER_BINDING]: null,\n [GL.RENDERBUFFER_BINDING]: null,\n [GL.VERTEX_ARRAY_BINDING]: null,\n [GL.ARRAY_BUFFER_BINDING]: null,\n [GL.FRONT_FACE]: GL.CCW,\n [GL.GENERATE_MIPMAP_HINT]: GL.DONT_CARE,\n [GL.LINE_WIDTH]: 1,\n [GL.POLYGON_OFFSET_FILL]: false,\n [GL.POLYGON_OFFSET_FACTOR]: 0,\n [GL.POLYGON_OFFSET_UNITS]: 0,\n [GL.SAMPLE_ALPHA_TO_COVERAGE]: false,\n [GL.SAMPLE_COVERAGE]: false,\n [GL.SAMPLE_COVERAGE_VALUE]: 1.0,\n [GL.SAMPLE_COVERAGE_INVERT]: false,\n [GL.SCISSOR_TEST]: false,\n // Note: Dynamic value. If scissor test enabled we expect users to set correct scissor box\n [GL.SCISSOR_BOX]: new Int32Array([0, 0, 1024, 1024]),\n [GL.STENCIL_TEST]: false,\n [GL.STENCIL_CLEAR_VALUE]: 0,\n [GL.STENCIL_WRITEMASK]: 0xffffffff,\n [GL.STENCIL_BACK_WRITEMASK]: 0xffffffff,\n [GL.STENCIL_FUNC]: GL.ALWAYS,\n [GL.STENCIL_REF]: 0,\n [GL.STENCIL_VALUE_MASK]: 0xffffffff,\n [GL.STENCIL_BACK_FUNC]: GL.ALWAYS,\n [GL.STENCIL_BACK_REF]: 0,\n [GL.STENCIL_BACK_VALUE_MASK]: 0xffffffff,\n [GL.STENCIL_FAIL]: GL.KEEP,\n [GL.STENCIL_PASS_DEPTH_FAIL]: GL.KEEP,\n [GL.STENCIL_PASS_DEPTH_PASS]: GL.KEEP,\n [GL.STENCIL_BACK_FAIL]: GL.KEEP,\n [GL.STENCIL_BACK_PASS_DEPTH_FAIL]: GL.KEEP,\n [GL.STENCIL_BACK_PASS_DEPTH_PASS]: GL.KEEP,\n // Dynamic value: We use [0, 0, 1024, 1024] as default, but usually this is updated in each frame.\n [GL.VIEWPORT]: [0, 0, 1024, 1024],\n\n [GL.TRANSFORM_FEEDBACK_BINDING]: null,\n [GL.COPY_READ_BUFFER_BINDING]: null,\n [GL.COPY_WRITE_BUFFER_BINDING]: null,\n [GL.PIXEL_PACK_BUFFER_BINDING]: null,\n [GL.PIXEL_UNPACK_BUFFER_BINDING]: null,\n [GL.FRAGMENT_SHADER_DERIVATIVE_HINT]: GL.DONT_CARE,\n [GL.READ_FRAMEBUFFER_BINDING]: null,\n [GL.RASTERIZER_DISCARD]: false,\n\n [GL.PACK_ALIGNMENT]: 4,\n [GL.UNPACK_ALIGNMENT]: 4,\n [GL.UNPACK_FLIP_Y_WEBGL]: false,\n [GL.UNPACK_PREMULTIPLY_ALPHA_WEBGL]: false,\n [GL.UNPACK_COLORSPACE_CONVERSION_WEBGL]: GL.BROWSER_DEFAULT_WEBGL,\n [GL.PACK_ROW_LENGTH]: 0,\n [GL.PACK_SKIP_PIXELS]: 0,\n [GL.PACK_SKIP_ROWS]: 0,\n [GL.UNPACK_ROW_LENGTH]: 0,\n [GL.UNPACK_IMAGE_HEIGHT]: 0,\n [GL.UNPACK_SKIP_PIXELS]: 0,\n [GL.UNPACK_SKIP_ROWS]: 0,\n [GL.UNPACK_SKIP_IMAGES]: 0\n};\n\n// SETTER TABLES - ENABLES SETTING ANY PARAMETER WITH A COMMON API\n\nconst enable = (gl: WebGL2RenderingContext, value: unknown, key: GL) =>\n value ? gl.enable(key) : gl.disable(key);\nconst hint = (gl: WebGL2RenderingContext, value: GL, key: GL) => gl.hint(key, value);\nconst pixelStorei = (gl: WebGL2RenderingContext, value: number | boolean, key: GL) =>\n gl.pixelStorei(key, value);\n\nconst bindFramebuffer = (gl: WebGL2RenderingContext, value: unknown, key: GL) => {\n const target = key === GL.FRAMEBUFFER_BINDING ? GL.DRAW_FRAMEBUFFER : GL.READ_FRAMEBUFFER;\n return gl.bindFramebuffer(target, value as WebGLFramebuffer);\n};\n\nconst bindBuffer = (gl: WebGL2RenderingContext, value: unknown, key: GL) => {\n const bindingMap: Partial> = {\n [GL.ARRAY_BUFFER_BINDING]: GL.ARRAY_BUFFER,\n [GL.COPY_READ_BUFFER_BINDING]: GL.COPY_READ_BUFFER,\n [GL.COPY_WRITE_BUFFER_BINDING]: GL.COPY_WRITE_BUFFER,\n [GL.PIXEL_PACK_BUFFER_BINDING]: GL.PIXEL_PACK_BUFFER,\n [GL.PIXEL_UNPACK_BUFFER_BINDING]: GL.PIXEL_UNPACK_BUFFER\n };\n const glTarget = bindingMap[key];\n\n gl.bindBuffer(glTarget as number, value as WebGLBuffer | null);\n};\n\n// Utility\nfunction isArray(array: unknown): boolean {\n return Array.isArray(array) || (ArrayBuffer.isView(array) && !(array instanceof DataView));\n}\n\n// Map from WebGL parameter names to corresponding WebGL setter functions\n// WegGL constants are read by parameter names, but set by function names\n// NOTE: When value type is a string, it will be handled by 'GL_COMPOSITE_PARAMETER_SETTERS'\nexport const GL_PARAMETER_SETTERS = {\n [GL.BLEND]: enable,\n [GL.BLEND_COLOR]: (gl: WebGL2RenderingContext, value: [number, number, number, number]) =>\n gl.blendColor(...value),\n [GL.BLEND_EQUATION_RGB]: 'blendEquation',\n [GL.BLEND_EQUATION_ALPHA]: 'blendEquation',\n [GL.BLEND_SRC_RGB]: 'blendFunc',\n [GL.BLEND_DST_RGB]: 'blendFunc',\n [GL.BLEND_SRC_ALPHA]: 'blendFunc',\n [GL.BLEND_DST_ALPHA]: 'blendFunc',\n [GL.COLOR_CLEAR_VALUE]: (gl: WebGL2RenderingContext, value: [number, number, number, number]) =>\n gl.clearColor(...value),\n [GL.COLOR_WRITEMASK]: (gl: WebGL2RenderingContext, value: [boolean, boolean, boolean, boolean]) =>\n gl.colorMask(...value),\n [GL.CULL_FACE]: enable,\n [GL.CULL_FACE_MODE]: (gl: WebGL2RenderingContext, value) => gl.cullFace(value),\n [GL.DEPTH_TEST]: enable,\n [GL.DEPTH_CLEAR_VALUE]: (gl: WebGL2RenderingContext, value) => gl.clearDepth(value),\n [GL.DEPTH_FUNC]: (gl: WebGL2RenderingContext, value) => gl.depthFunc(value),\n [GL.DEPTH_RANGE]: (gl: WebGL2RenderingContext, value: [number, number]) =>\n gl.depthRange(...value),\n [GL.DEPTH_WRITEMASK]: (gl: WebGL2RenderingContext, value) => gl.depthMask(value),\n [GL.DITHER]: enable,\n [GL.FRAGMENT_SHADER_DERIVATIVE_HINT]: hint,\n\n [GL.CURRENT_PROGRAM]: (gl: WebGL2RenderingContext, value) => gl.useProgram(value),\n [GL.RENDERBUFFER_BINDING]: (gl: WebGL2RenderingContext, value) =>\n gl.bindRenderbuffer(GL.RENDERBUFFER, value),\n [GL.TRANSFORM_FEEDBACK_BINDING]: (gl: WebGL2RenderingContext, value) =>\n gl.bindTransformFeedback?.(GL.TRANSFORM_FEEDBACK, value),\n [GL.VERTEX_ARRAY_BINDING]: (gl: WebGL2RenderingContext, value) => gl.bindVertexArray(value),\n // NOTE: FRAMEBUFFER_BINDING and DRAW_FRAMEBUFFER_BINDING(WebGL2) refer same state.\n [GL.FRAMEBUFFER_BINDING]: bindFramebuffer,\n [GL.READ_FRAMEBUFFER_BINDING]: bindFramebuffer,\n\n // Buffers\n [GL.ARRAY_BUFFER_BINDING]: bindBuffer,\n [GL.COPY_READ_BUFFER_BINDING]: bindBuffer,\n [GL.COPY_WRITE_BUFFER_BINDING]: bindBuffer,\n [GL.PIXEL_PACK_BUFFER_BINDING]: bindBuffer,\n [GL.PIXEL_UNPACK_BUFFER_BINDING]: bindBuffer,\n\n [GL.FRONT_FACE]: (gl: WebGL2RenderingContext, value) => gl.frontFace(value),\n [GL.GENERATE_MIPMAP_HINT]: hint,\n [GL.LINE_WIDTH]: (gl: WebGL2RenderingContext, value) => gl.lineWidth(value),\n [GL.POLYGON_OFFSET_FILL]: enable,\n [GL.POLYGON_OFFSET_FACTOR]: 'polygonOffset',\n [GL.POLYGON_OFFSET_UNITS]: 'polygonOffset',\n [GL.RASTERIZER_DISCARD]: enable,\n [GL.SAMPLE_ALPHA_TO_COVERAGE]: enable,\n [GL.SAMPLE_COVERAGE]: enable,\n [GL.SAMPLE_COVERAGE_VALUE]: 'sampleCoverage',\n [GL.SAMPLE_COVERAGE_INVERT]: 'sampleCoverage',\n [GL.SCISSOR_TEST]: enable,\n [GL.SCISSOR_BOX]: (gl: WebGL2RenderingContext, value: [number, number, number, number]) =>\n gl.scissor(...value),\n [GL.STENCIL_TEST]: enable,\n [GL.STENCIL_CLEAR_VALUE]: (gl: WebGL2RenderingContext, value) => gl.clearStencil(value),\n [GL.STENCIL_WRITEMASK]: (gl: WebGL2RenderingContext, value) =>\n gl.stencilMaskSeparate(GL.FRONT, value),\n [GL.STENCIL_BACK_WRITEMASK]: (gl: WebGL2RenderingContext, value) =>\n gl.stencilMaskSeparate(GL.BACK, value),\n [GL.STENCIL_FUNC]: 'stencilFuncFront',\n [GL.STENCIL_REF]: 'stencilFuncFront',\n [GL.STENCIL_VALUE_MASK]: 'stencilFuncFront',\n [GL.STENCIL_BACK_FUNC]: 'stencilFuncBack',\n [GL.STENCIL_BACK_REF]: 'stencilFuncBack',\n [GL.STENCIL_BACK_VALUE_MASK]: 'stencilFuncBack',\n [GL.STENCIL_FAIL]: 'stencilOpFront',\n [GL.STENCIL_PASS_DEPTH_FAIL]: 'stencilOpFront',\n [GL.STENCIL_PASS_DEPTH_PASS]: 'stencilOpFront',\n [GL.STENCIL_BACK_FAIL]: 'stencilOpBack',\n [GL.STENCIL_BACK_PASS_DEPTH_FAIL]: 'stencilOpBack',\n [GL.STENCIL_BACK_PASS_DEPTH_PASS]: 'stencilOpBack',\n [GL.VIEWPORT]: (gl: WebGL2RenderingContext, value: [number, number, number, number]) =>\n gl.viewport(...value),\n\n // WEBGL2 EXTENSIONS\n\n // EXT_depth_clamp https://registry.khronos.org/webgl/extensions/EXT_depth_clamp/\n\n [GL.DEPTH_CLAMP_EXT]: enable,\n\n // WEBGL_provoking_vertex https://registry.khronos.org/webgl/extensions/WEBGL_provoking_vertex/\n\n // [GL.PROVOKING_VERTEX_WEBL]: TODO - extension function needed\n\n // WEBGL_polygon_mode https://registry.khronos.org/webgl/extensions/WEBGL_polygon_mode/\n\n // POLYGON_MODE_WEBGL TODO - extension function needed\n [GL.POLYGON_OFFSET_LINE_WEBGL]: enable,\n\n // WEBGL_clip_cull_distance https://registry.khronos.org/webgl/extensions/WEBGL_clip_cull_distance/\n\n [GL.CLIP_DISTANCE0_WEBGL]: enable,\n [GL.CLIP_DISTANCE1_WEBGL]: enable,\n [GL.CLIP_DISTANCE2_WEBGL]: enable,\n [GL.CLIP_DISTANCE3_WEBGL]: enable,\n [GL.CLIP_DISTANCE4_WEBGL]: enable,\n [GL.CLIP_DISTANCE5_WEBGL]: enable,\n [GL.CLIP_DISTANCE6_WEBGL]: enable,\n [GL.CLIP_DISTANCE7_WEBGL]: enable,\n\n // PIXEL PACK/UNPACK MODES\n [GL.PACK_ALIGNMENT]: pixelStorei,\n [GL.UNPACK_ALIGNMENT]: pixelStorei,\n [GL.UNPACK_FLIP_Y_WEBGL]: pixelStorei,\n [GL.UNPACK_PREMULTIPLY_ALPHA_WEBGL]: pixelStorei,\n [GL.UNPACK_COLORSPACE_CONVERSION_WEBGL]: pixelStorei,\n [GL.PACK_ROW_LENGTH]: pixelStorei,\n [GL.PACK_SKIP_PIXELS]: pixelStorei,\n [GL.PACK_SKIP_ROWS]: pixelStorei,\n [GL.UNPACK_ROW_LENGTH]: pixelStorei,\n [GL.UNPACK_IMAGE_HEIGHT]: pixelStorei,\n [GL.UNPACK_SKIP_PIXELS]: pixelStorei,\n [GL.UNPACK_SKIP_ROWS]: pixelStorei,\n [GL.UNPACK_SKIP_IMAGES]: pixelStorei,\n\n // Function-style setters\n framebuffer: (gl: WebGL2RenderingContext, framebuffer) => {\n // accepts 1) a WebGLFramebuffer 2) null (default framebuffer), or 3) luma.gl Framebuffer class\n // framebuffer is null when restoring to default framebuffer, otherwise use the WebGL handle.\n const handle = framebuffer && 'handle' in framebuffer ? framebuffer.handle : framebuffer;\n return gl.bindFramebuffer(GL.FRAMEBUFFER, handle);\n },\n blend: (gl: WebGL2RenderingContext, value) =>\n value ? gl.enable(GL.BLEND) : gl.disable(GL.BLEND),\n blendColor: (gl: WebGL2RenderingContext, value: [number, number, number, number]) =>\n gl.blendColor(...value),\n blendEquation: (gl: WebGL2RenderingContext, args: number | [number, number]) => {\n const separateModes = typeof args === 'number' ? ([args, args] as [number, number]) : args;\n gl.blendEquationSeparate(...separateModes);\n },\n blendFunc: (\n gl: WebGL2RenderingContext,\n args: [number, number] | [number, number, number, number]\n ) => {\n const separateFuncs =\n args?.length === 2 ? ([...args, ...args] as [number, number, number, number]) : args;\n gl.blendFuncSeparate(...separateFuncs);\n },\n\n clearColor: (gl: WebGL2RenderingContext, value: [number, number, number, number]) =>\n gl.clearColor(...value),\n clearDepth: (gl: WebGL2RenderingContext, value) => gl.clearDepth(value),\n clearStencil: (gl: WebGL2RenderingContext, value) => gl.clearStencil(value),\n\n colorMask: (gl: WebGL2RenderingContext, value: [boolean, boolean, boolean, boolean]) =>\n gl.colorMask(...value),\n\n cull: (gl: WebGL2RenderingContext, value) =>\n value ? gl.enable(GL.CULL_FACE) : gl.disable(GL.CULL_FACE),\n cullFace: (gl: WebGL2RenderingContext, value) => gl.cullFace(value),\n\n depthTest: (gl: WebGL2RenderingContext, value) =>\n value ? gl.enable(GL.DEPTH_TEST) : gl.disable(GL.DEPTH_TEST),\n depthFunc: (gl: WebGL2RenderingContext, value) => gl.depthFunc(value),\n depthMask: (gl: WebGL2RenderingContext, value) => gl.depthMask(value),\n depthRange: (gl: WebGL2RenderingContext, value: [number, number]) => gl.depthRange(...value),\n\n dither: (gl: WebGL2RenderingContext, value) =>\n value ? gl.enable(GL.DITHER) : gl.disable(GL.DITHER),\n\n derivativeHint: (gl: WebGL2RenderingContext, value) => {\n // gl1: 'OES_standard_derivatives'\n gl.hint(GL.FRAGMENT_SHADER_DERIVATIVE_HINT, value);\n },\n\n frontFace: (gl: WebGL2RenderingContext, value) => gl.frontFace(value),\n\n mipmapHint: (gl: WebGL2RenderingContext, value) => gl.hint(GL.GENERATE_MIPMAP_HINT, value),\n\n lineWidth: (gl: WebGL2RenderingContext, value) => gl.lineWidth(value),\n\n polygonOffsetFill: (gl: WebGL2RenderingContext, value) =>\n value ? gl.enable(GL.POLYGON_OFFSET_FILL) : gl.disable(GL.POLYGON_OFFSET_FILL),\n polygonOffset: (gl: WebGL2RenderingContext, value: [number, number]) =>\n gl.polygonOffset(...value),\n\n sampleCoverage: (gl: WebGL2RenderingContext, value: [number, boolean?]) =>\n gl.sampleCoverage(value[0], value[1] || false),\n\n scissorTest: (gl: WebGL2RenderingContext, value) =>\n value ? gl.enable(GL.SCISSOR_TEST) : gl.disable(GL.SCISSOR_TEST),\n scissor: (gl: WebGL2RenderingContext, value: [number, number, number, number]) =>\n gl.scissor(...value),\n\n stencilTest: (gl: WebGL2RenderingContext, value) =>\n value ? gl.enable(GL.STENCIL_TEST) : gl.disable(GL.STENCIL_TEST),\n stencilMask: (gl: WebGL2RenderingContext, value) => {\n value = isArray(value) ? value : [value, value];\n const [mask, backMask] = value;\n gl.stencilMaskSeparate(GL.FRONT, mask);\n gl.stencilMaskSeparate(GL.BACK, backMask);\n },\n stencilFunc: (gl: WebGL2RenderingContext, args) => {\n args = isArray(args) && args.length === 3 ? [...args, ...args] : args;\n const [func, ref, mask, backFunc, backRef, backMask] = args;\n gl.stencilFuncSeparate(GL.FRONT, func, ref, mask);\n gl.stencilFuncSeparate(GL.BACK, backFunc, backRef, backMask);\n },\n stencilOp: (gl: WebGL2RenderingContext, args) => {\n args = isArray(args) && args.length === 3 ? [...args, ...args] : args;\n const [sfail, dpfail, dppass, backSfail, backDpfail, backDppass] = args;\n gl.stencilOpSeparate(GL.FRONT, sfail, dpfail, dppass);\n gl.stencilOpSeparate(GL.BACK, backSfail, backDpfail, backDppass);\n },\n\n viewport: (gl: WebGL2RenderingContext, value: [number, number, number, number]) =>\n gl.viewport(...value)\n};\n\nfunction getValue(glEnum, values, cache) {\n return values[glEnum] !== undefined ? values[glEnum] : cache[glEnum];\n}\n\n// COMPOSITE_WEBGL_PARAMETER_\nexport const GL_COMPOSITE_PARAMETER_SETTERS = {\n blendEquation: (gl: WebGL2RenderingContext, values, cache) =>\n gl.blendEquationSeparate(\n getValue(GL.BLEND_EQUATION_RGB, values, cache),\n getValue(GL.BLEND_EQUATION_ALPHA, values, cache)\n ),\n blendFunc: (gl: WebGL2RenderingContext, values, cache) =>\n gl.blendFuncSeparate(\n getValue(GL.BLEND_SRC_RGB, values, cache),\n getValue(GL.BLEND_DST_RGB, values, cache),\n getValue(GL.BLEND_SRC_ALPHA, values, cache),\n getValue(GL.BLEND_DST_ALPHA, values, cache)\n ),\n polygonOffset: (gl: WebGL2RenderingContext, values, cache) =>\n gl.polygonOffset(\n getValue(GL.POLYGON_OFFSET_FACTOR, values, cache),\n getValue(GL.POLYGON_OFFSET_UNITS, values, cache)\n ),\n sampleCoverage: (gl: WebGL2RenderingContext, values, cache) =>\n gl.sampleCoverage(\n getValue(GL.SAMPLE_COVERAGE_VALUE, values, cache),\n getValue(GL.SAMPLE_COVERAGE_INVERT, values, cache)\n ),\n stencilFuncFront: (gl: WebGL2RenderingContext, values, cache) =>\n gl.stencilFuncSeparate(\n GL.FRONT,\n getValue(GL.STENCIL_FUNC, values, cache),\n getValue(GL.STENCIL_REF, values, cache),\n getValue(GL.STENCIL_VALUE_MASK, values, cache)\n ),\n stencilFuncBack: (gl: WebGL2RenderingContext, values, cache) =>\n gl.stencilFuncSeparate(\n GL.BACK,\n getValue(GL.STENCIL_BACK_FUNC, values, cache),\n getValue(GL.STENCIL_BACK_REF, values, cache),\n getValue(GL.STENCIL_BACK_VALUE_MASK, values, cache)\n ),\n stencilOpFront: (gl: WebGL2RenderingContext, values, cache) =>\n gl.stencilOpSeparate(\n GL.FRONT,\n getValue(GL.STENCIL_FAIL, values, cache),\n getValue(GL.STENCIL_PASS_DEPTH_FAIL, values, cache),\n getValue(GL.STENCIL_PASS_DEPTH_PASS, values, cache)\n ),\n stencilOpBack: (gl: WebGL2RenderingContext, values, cache) =>\n gl.stencilOpSeparate(\n GL.BACK,\n getValue(GL.STENCIL_BACK_FAIL, values, cache),\n getValue(GL.STENCIL_BACK_PASS_DEPTH_FAIL, values, cache),\n getValue(GL.STENCIL_BACK_PASS_DEPTH_PASS, values, cache)\n )\n};\n\ntype UpdateFunc = (params: Record) => void;\n\n// Setter functions intercepted for cache updates\nexport const GL_HOOKED_SETTERS = {\n // GENERIC SETTERS\n\n enable: (update: UpdateFunc, capability: GL) =>\n update({\n [capability]: true\n }),\n disable: (update: UpdateFunc, capability: GL) =>\n update({\n [capability]: false\n }),\n pixelStorei: (update: UpdateFunc, pname: GL, value) =>\n update({\n [pname]: value\n }),\n hint: (update: UpdateFunc, pname: GL, value: GL) =>\n update({\n [pname]: value\n }),\n\n // SPECIFIC SETTERS\n useProgram: (update: UpdateFunc, value) =>\n update({\n [GL.CURRENT_PROGRAM]: value\n }),\n bindRenderbuffer: (update: UpdateFunc, target, value) =>\n update({\n [GL.RENDERBUFFER_BINDING]: value\n }),\n bindTransformFeedback: (update: UpdateFunc, target, value) =>\n update({\n [GL.TRANSFORM_FEEDBACK_BINDING]: value\n }),\n bindVertexArray: (update: UpdateFunc, value) =>\n update({\n [GL.VERTEX_ARRAY_BINDING]: value\n }),\n\n bindFramebuffer: (update: UpdateFunc, target, framebuffer) => {\n switch (target) {\n case GL.FRAMEBUFFER:\n return update({\n [GL.DRAW_FRAMEBUFFER_BINDING]: framebuffer,\n [GL.READ_FRAMEBUFFER_BINDING]: framebuffer\n });\n case GL.DRAW_FRAMEBUFFER:\n return update({[GL.DRAW_FRAMEBUFFER_BINDING]: framebuffer});\n case GL.READ_FRAMEBUFFER:\n return update({[GL.READ_FRAMEBUFFER_BINDING]: framebuffer});\n default:\n return null;\n }\n },\n bindBuffer: (update: UpdateFunc, target, buffer) => {\n const pname = {\n [GL.ARRAY_BUFFER]: [GL.ARRAY_BUFFER_BINDING],\n [GL.COPY_READ_BUFFER]: [GL.COPY_READ_BUFFER_BINDING],\n [GL.COPY_WRITE_BUFFER]: [GL.COPY_WRITE_BUFFER_BINDING],\n [GL.PIXEL_PACK_BUFFER]: [GL.PIXEL_PACK_BUFFER_BINDING],\n [GL.PIXEL_UNPACK_BUFFER]: [GL.PIXEL_UNPACK_BUFFER_BINDING]\n }[target];\n\n if (pname) {\n return update({[pname]: buffer});\n }\n // targets that should not be cached\n return {valueChanged: true};\n },\n\n blendColor: (update: UpdateFunc, r: number, g: number, b: number, a: number) =>\n update({\n [GL.BLEND_COLOR]: new Float32Array([r, g, b, a])\n }),\n\n blendEquation: (update: UpdateFunc, mode) =>\n update({\n [GL.BLEND_EQUATION_RGB]: mode,\n [GL.BLEND_EQUATION_ALPHA]: mode\n }),\n\n blendEquationSeparate: (update: UpdateFunc, modeRGB, modeAlpha) =>\n update({\n [GL.BLEND_EQUATION_RGB]: modeRGB,\n [GL.BLEND_EQUATION_ALPHA]: modeAlpha\n }),\n\n blendFunc: (update: UpdateFunc, src, dst) =>\n update({\n [GL.BLEND_SRC_RGB]: src,\n [GL.BLEND_DST_RGB]: dst,\n [GL.BLEND_SRC_ALPHA]: src,\n [GL.BLEND_DST_ALPHA]: dst\n }),\n\n blendFuncSeparate: (update: UpdateFunc, srcRGB, dstRGB, srcAlpha, dstAlpha) =>\n update({\n [GL.BLEND_SRC_RGB]: srcRGB,\n [GL.BLEND_DST_RGB]: dstRGB,\n [GL.BLEND_SRC_ALPHA]: srcAlpha,\n [GL.BLEND_DST_ALPHA]: dstAlpha\n }),\n\n clearColor: (update: UpdateFunc, r: number, g: number, b: number, a: number) =>\n update({\n [GL.COLOR_CLEAR_VALUE]: new Float32Array([r, g, b, a])\n }),\n\n clearDepth: (update: UpdateFunc, depth: number) =>\n update({\n [GL.DEPTH_CLEAR_VALUE]: depth\n }),\n\n clearStencil: (update: UpdateFunc, s: number) =>\n update({\n [GL.STENCIL_CLEAR_VALUE]: s\n }),\n\n colorMask: (update: UpdateFunc, r: number, g: number, b: number, a: number) =>\n update({\n [GL.COLOR_WRITEMASK]: [r, g, b, a]\n }),\n\n cullFace: (update: UpdateFunc, mode) =>\n update({\n [GL.CULL_FACE_MODE]: mode\n }),\n\n depthFunc: (update: UpdateFunc, func) =>\n update({\n [GL.DEPTH_FUNC]: func\n }),\n\n depthRange: (update: UpdateFunc, zNear: number, zFar: number) =>\n update({\n [GL.DEPTH_RANGE]: new Float32Array([zNear, zFar])\n }),\n\n depthMask: (update: UpdateFunc, mask: number) =>\n update({\n [GL.DEPTH_WRITEMASK]: mask\n }),\n\n frontFace: (update: UpdateFunc, face) =>\n update({\n [GL.FRONT_FACE]: face\n }),\n\n lineWidth: (update: UpdateFunc, width) =>\n update({\n [GL.LINE_WIDTH]: width\n }),\n\n polygonOffset: (update: UpdateFunc, factor, units) =>\n update({\n [GL.POLYGON_OFFSET_FACTOR]: factor,\n [GL.POLYGON_OFFSET_UNITS]: units\n }),\n\n sampleCoverage: (update: UpdateFunc, value, invert) =>\n update({\n [GL.SAMPLE_COVERAGE_VALUE]: value,\n [GL.SAMPLE_COVERAGE_INVERT]: invert\n }),\n\n scissor: (update: UpdateFunc, x, y, width, height) =>\n update({\n [GL.SCISSOR_BOX]: new Int32Array([x, y, width, height])\n }),\n\n stencilMask: (update: UpdateFunc, mask) =>\n update({\n [GL.STENCIL_WRITEMASK]: mask,\n [GL.STENCIL_BACK_WRITEMASK]: mask\n }),\n\n stencilMaskSeparate: (update: UpdateFunc, face, mask) =>\n update({\n [face === GL.FRONT ? GL.STENCIL_WRITEMASK : GL.STENCIL_BACK_WRITEMASK]: mask\n }),\n\n stencilFunc: (update: UpdateFunc, func, ref, mask) =>\n update({\n [GL.STENCIL_FUNC]: func,\n [GL.STENCIL_REF]: ref,\n [GL.STENCIL_VALUE_MASK]: mask,\n [GL.STENCIL_BACK_FUNC]: func,\n [GL.STENCIL_BACK_REF]: ref,\n [GL.STENCIL_BACK_VALUE_MASK]: mask\n }),\n\n stencilFuncSeparate: (update: UpdateFunc, face, func, ref, mask) =>\n update({\n [face === GL.FRONT ? GL.STENCIL_FUNC : GL.STENCIL_BACK_FUNC]: func,\n [face === GL.FRONT ? GL.STENCIL_REF : GL.STENCIL_BACK_REF]: ref,\n [face === GL.FRONT ? GL.STENCIL_VALUE_MASK : GL.STENCIL_BACK_VALUE_MASK]: mask\n }),\n\n stencilOp: (update: UpdateFunc, fail, zfail, zpass) =>\n update({\n [GL.STENCIL_FAIL]: fail,\n [GL.STENCIL_PASS_DEPTH_FAIL]: zfail,\n [GL.STENCIL_PASS_DEPTH_PASS]: zpass,\n [GL.STENCIL_BACK_FAIL]: fail,\n [GL.STENCIL_BACK_PASS_DEPTH_FAIL]: zfail,\n [GL.STENCIL_BACK_PASS_DEPTH_PASS]: zpass\n }),\n\n stencilOpSeparate: (update: UpdateFunc, face, fail, zfail, zpass) =>\n update({\n [face === GL.FRONT ? GL.STENCIL_FAIL : GL.STENCIL_BACK_FAIL]: fail,\n [face === GL.FRONT ? GL.STENCIL_PASS_DEPTH_FAIL : GL.STENCIL_BACK_PASS_DEPTH_FAIL]: zfail,\n [face === GL.FRONT ? GL.STENCIL_PASS_DEPTH_PASS : GL.STENCIL_BACK_PASS_DEPTH_PASS]: zpass\n }),\n\n viewport: (update: UpdateFunc, x, y, width, height) =>\n update({\n [GL.VIEWPORT]: [x, y, width, height]\n })\n};\n\n// GETTER TABLE - FOR READING OUT AN ENTIRE CONTEXT\n\nconst isEnabled = (gl: WebGL2RenderingContext, key) => gl.isEnabled(key);\n\n// Exceptions for any keys that cannot be queried by gl.getParameters\nexport const GL_PARAMETER_GETTERS = {\n [GL.BLEND]: isEnabled,\n [GL.CULL_FACE]: isEnabled,\n [GL.DEPTH_TEST]: isEnabled,\n [GL.DITHER]: isEnabled,\n [GL.POLYGON_OFFSET_FILL]: isEnabled,\n [GL.SAMPLE_ALPHA_TO_COVERAGE]: isEnabled,\n [GL.SAMPLE_COVERAGE]: isEnabled,\n [GL.SCISSOR_TEST]: isEnabled,\n [GL.STENCIL_TEST]: isEnabled,\n [GL.RASTERIZER_DISCARD]: isEnabled\n};\n\nexport const NON_CACHE_PARAMETERS = new Set([\n // setter not intercepted\n GL.ACTIVE_TEXTURE,\n GL.TRANSFORM_FEEDBACK_ACTIVE,\n GL.TRANSFORM_FEEDBACK_PAUSED,\n\n // setters bindBufferRange/bindBufferBase cannot be pruned based on cache\n GL.TRANSFORM_FEEDBACK_BUFFER_BINDING,\n GL.UNIFORM_BUFFER_BINDING,\n\n // states depending on VERTEX_ARRAY_BINDING\n GL.ELEMENT_ARRAY_BUFFER_BINDING,\n // states depending on READ_FRAMEBUFFER_BINDING\n GL.IMPLEMENTATION_COLOR_READ_FORMAT,\n GL.IMPLEMENTATION_COLOR_READ_TYPE,\n // states depending on FRAMEBUFFER_BINDING\n GL.READ_BUFFER,\n GL.DRAW_BUFFER0,\n GL.DRAW_BUFFER1,\n GL.DRAW_BUFFER2,\n GL.DRAW_BUFFER3,\n GL.DRAW_BUFFER4,\n GL.DRAW_BUFFER5,\n GL.DRAW_BUFFER6,\n GL.DRAW_BUFFER7,\n GL.DRAW_BUFFER8,\n GL.DRAW_BUFFER9,\n GL.DRAW_BUFFER10,\n GL.DRAW_BUFFER11,\n GL.DRAW_BUFFER12,\n GL.DRAW_BUFFER13,\n GL.DRAW_BUFFER14,\n GL.DRAW_BUFFER15,\n // states depending on ACTIVE_TEXTURE\n GL.SAMPLER_BINDING,\n GL.TEXTURE_BINDING_2D,\n GL.TEXTURE_BINDING_2D_ARRAY,\n GL.TEXTURE_BINDING_3D,\n GL.TEXTURE_BINDING_CUBE_MAP\n]);\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// Provides a unified API for getting and setting any WebGL parameter\n// Also knows default values of all parameters, enabling fast cache initialization\n// Provides base functionality for the state caching.\nimport type {GLParameters} from '@luma.gl/webgl/constants';\nimport {\n GL_PARAMETER_DEFAULTS,\n GL_PARAMETER_SETTERS,\n GL_COMPOSITE_PARAMETER_SETTERS,\n GL_PARAMETER_GETTERS\n} from './webgl-parameter-tables';\n\nexport type {GLParameters};\n\n/**\n * Sets any GL parameter regardless of function (gl.blendMode, ...)\n *\n * @note requires a `cache` object to be set on the context (lumaState.cache)\n * This object is used to fill in any missing values for composite setter functions\n */\nexport function setGLParameters(gl: WebGL2RenderingContext, parameters: GLParameters): void {\n if (isObjectEmpty(parameters)) {\n return;\n }\n\n const compositeSetters = {};\n\n // HANDLE PRIMITIVE SETTERS (and make note of any composite setters)\n\n for (const key in parameters) {\n const glConstant = Number(key);\n // @ts-ignore TODO\n const setter = GL_PARAMETER_SETTERS[key];\n if (setter) {\n // Composite setters should only be called once, so save them\n if (typeof setter === 'string') {\n // @ts-ignore TODO\n compositeSetters[setter] = true;\n } else {\n // if (gl[glConstant] !== undefined) {\n // TODO - added above check since this is being called on WebGL2 parameters in WebGL1...\n // TODO - deep equal on values? only call setter if value has changed?\n // NOTE - the setter will automatically update this.state\n // @ts-ignore TODO\n setter(gl, parameters[key], glConstant);\n }\n }\n }\n\n // HANDLE COMPOSITE SETTERS\n\n // NOTE: any non-provided values needed by composite setters are filled in from state cache\n // The cache parameter is automatically retrieved from the context\n // This depends on `trackContextState`, which is technically a \"circular\" dependency.\n // But it is too inconvenient to always require a cache parameter here.\n // This is the ONLY external dependency in this module/\n // @ts-expect-error\n const cache = gl.lumaState?.cache;\n if (cache) {\n for (const key in compositeSetters) {\n // TODO - avoid calling composite setters if values have not changed.\n // @ts-ignore TODO\n const compositeSetter = GL_COMPOSITE_PARAMETER_SETTERS[key];\n // Note - if `trackContextState` has been called,\n // the setter will automatically update this.state.cache\n compositeSetter(gl, parameters, cache);\n }\n }\n\n // Add a log for the else case?\n}\n\n/**\n * Reads the entire WebGL state from a context\n\n // default to querying all parameters\n\n * @returns - a newly created map, with values keyed by GL parameters\n *\n * @note Copies the state from a context (gl.getParameter should not be overriden)\n * Reads the entire WebGL state from a context\n *\n * @note This can generates a huge amount of synchronous driver roundtrips and should be\n * considered a very slow operation, to be used only if/when a context already manipulated\n * by external code needs to be synchronized for the first time\n */\nexport function getGLParameters(\n gl: WebGL2RenderingContext,\n parameters: keyof GLParameters | (keyof GLParameters)[] | GLParameters = GL_PARAMETER_DEFAULTS\n): GLParameters {\n // support both arrays of parameters and objects (keys represent parameters)\n\n if (typeof parameters === 'number') {\n // single GL enum\n const key = parameters;\n // @ts-ignore TODO\n const getter = GL_PARAMETER_GETTERS[key];\n return getter ? getter(gl, key) : gl.getParameter(key);\n }\n\n const parameterKeys = Array.isArray(parameters) ? parameters : Object.keys(parameters);\n\n const state: GLParameters = {};\n for (const key of parameterKeys) {\n // @ts-ignore TODO\n const getter = GL_PARAMETER_GETTERS[key];\n // @ts-ignore TODO\n state[key] = getter ? getter(gl, Number(key)) : gl.getParameter(Number(key));\n }\n return state;\n}\n\n/**\n * Reset all parameters to a (almost) pure context state\n * @note viewport and scissor will be set to the values in GL_PARAMETER_DEFAULTS,\n * NOT the canvas size dimensions, so they will have to be properly set after\n * calling this function.\n */\nexport function resetGLParameters(gl: WebGL2RenderingContext): void {\n setGLParameters(gl, GL_PARAMETER_DEFAULTS);\n}\n\n// Helpers\n\n// Returns true if given object is empty, false otherwise.\nfunction isObjectEmpty(object: Record): boolean {\n // @ts-ignore dummy key variable\n for (const key in object) {\n return false;\n }\n return true;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {TypedArray} from '@luma.gl/core';\n\n/** deeply compare two arrays */\nexport function deepArrayEqual(\n x: unknown | unknown[] | TypedArray,\n y: unknown | unknown[] | TypedArray\n): boolean {\n if (x === y) {\n return true;\n }\n if (isArray(x) && isArray(y) && x.length === y.length) {\n for (let i = 0; i < x.length; ++i) {\n if (x[i] !== y[i]) {\n return false;\n }\n }\n return true;\n }\n return false;\n}\n\nfunction isArray(x: unknown): x is unknown[] {\n return Array.isArray(x) || ArrayBuffer.isView(x);\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// @ts-nocheck TODO - fix\n\nimport {setGLParameters, getGLParameters} from '../parameters/unified-parameter-api';\nimport {deepArrayEqual} from './deep-array-equal';\nimport {\n GL_PARAMETER_DEFAULTS,\n GL_HOOKED_SETTERS,\n NON_CACHE_PARAMETERS\n} from '../parameters/webgl-parameter-tables';\n\n// HELPER CLASS - WebGLStateTracker\n\n/**\n * Support for listening to context state changes and intercepting state queries\n * NOTE: this system does not handle buffer bindings\n */\nexport class WebGLStateTracker {\n static get(gl: WebGL2RenderingContext): WebGLStateTracker {\n // @ts-expect-error\n return gl.lumaState as WebGLStateTracker;\n }\n\n gl: WebGL2RenderingContext;\n program: unknown = null;\n stateStack: object[] = [];\n enable = true;\n cache: Record = null!;\n log;\n\n protected initialized = false;\n\n constructor(\n gl: WebGL2RenderingContext,\n props?: {\n log; // Logging function, called when gl parameter change calls are actually issued\n }\n ) {\n this.gl = gl;\n this.log = props?.log || (() => {});\n\n this._updateCache = this._updateCache.bind(this);\n Object.seal(this);\n }\n\n push(values = {}) {\n this.stateStack.push({});\n }\n\n pop() {\n // assert(this.stateStack.length > 0);\n // Use the saved values in the state stack to restore parameters\n const oldValues = this.stateStack[this.stateStack.length - 1];\n setGLParameters(this.gl, oldValues);\n // Don't pop until we have reset parameters (to make sure other \"stack frames\" are not affected)\n this.stateStack.pop();\n }\n\n /**\n * Initialize WebGL state caching on a context\n * can be called multiple times to enable/disable\n *\n * @note After calling this function, context state will be cached\n * .push() and .pop() will be available for saving,\n * temporarily modifying, and then restoring state.\n */\n trackState(gl: WebGL2RenderingContext, options?: {copyState?: boolean}): void {\n this.cache = options?.copyState\n ? getGLParameters(gl)\n : Object.assign({}, GL_PARAMETER_DEFAULTS);\n\n if (this.initialized) {\n throw new Error('WebGLStateTracker');\n }\n this.initialized = true;\n\n // @ts-expect-error\n this.gl.lumaState = this;\n\n installProgramSpy(gl);\n\n // intercept all setter functions in the table\n for (const key in GL_HOOKED_SETTERS) {\n const setter = GL_HOOKED_SETTERS[key];\n installSetterSpy(gl, key, setter);\n }\n\n // intercept all getter functions in the table\n installGetterOverride(gl, 'getParameter');\n installGetterOverride(gl, 'isEnabled');\n }\n\n /**\n // interceptor for context set functions - update our cache and our stack\n // values (Object) - the key values for this setter\n * @param values\n * @returns\n */\n _updateCache(values: {[key: number | string]: any}) {\n let valueChanged = false;\n let oldValue; // = undefined\n\n const oldValues: {[key: number | string]: any} | null =\n this.stateStack.length > 0 ? this.stateStack[this.stateStack.length - 1] : null;\n\n for (const key in values) {\n // assert(key !== undefined);\n const value = values[key];\n const cached = this.cache[key];\n // Check that value hasn't already been shadowed\n if (!deepArrayEqual(value, cached)) {\n valueChanged = true;\n oldValue = cached;\n\n // First, save current value being shadowed\n // If a state stack frame is active, save the current parameter values for pop\n // but first check that value hasn't already been shadowed and saved\n if (oldValues && !(key in oldValues)) {\n oldValues[key] = cached;\n }\n\n // Save current value being shadowed\n this.cache[key] = value;\n }\n }\n\n return {valueChanged, oldValue};\n }\n}\n\n// HELPER FUNCTIONS - INSTALL GET/SET INTERCEPTORS (SPYS) ON THE CONTEXT\n\n/**\n// Overrides a WebGL2RenderingContext state \"getter\" function\n// to return values directly from cache\n * @param gl\n * @param functionName\n */\nfunction installGetterOverride(gl: WebGL2RenderingContext, functionName: string) {\n // Get the original function from the WebGL2RenderingContext\n const originalGetterFunc = gl[functionName].bind(gl);\n\n // Wrap it with a spy so that we can update our state cache when it gets called\n gl[functionName] = function get(pname) {\n if (pname === undefined || NON_CACHE_PARAMETERS.has(pname)) {\n // Invalid or blacklisted parameter, do not cache\n return originalGetterFunc(pname);\n }\n\n const glState = WebGLStateTracker.get(gl);\n if (!(pname in glState.cache)) {\n // WebGL limits are not prepopulated in the cache, call the original getter when first queried.\n glState.cache[pname] = originalGetterFunc(pname);\n }\n\n // Optionally call the original function to do a \"hard\" query from the WebGL2RenderingContext\n return glState.enable\n ? // Call the getter the params so that it can e.g. serve from a cache\n glState.cache[pname]\n : // Optionally call the original function to do a \"hard\" query from the WebGL2RenderingContext\n originalGetterFunc(pname);\n };\n\n // Set the name of this anonymous function to help in debugging and profiling\n Object.defineProperty(gl[functionName], 'name', {\n value: `${functionName}-from-cache`,\n configurable: false\n });\n}\n\n/**\n// Overrides a WebGL2RenderingContext state \"setter\" function\n// to call a setter spy before the actual setter. Allows us to keep a cache\n// updated with a copy of the WebGL context state.\n * @param gl\n * @param functionName\n * @param setter\n * @returns\n */\nfunction installSetterSpy(gl: WebGL2RenderingContext, functionName: string, setter: Function) {\n // Get the original function from the WebGL2RenderingContext\n if (!gl[functionName]) {\n // TODO - remove?\n // This could happen if we try to intercept WebGL2 method on a WebGL1 context\n return;\n }\n\n const originalSetterFunc = gl[functionName].bind(gl);\n\n // Wrap it with a spy so that we can update our state cache when it gets called\n gl[functionName] = function set(...params) {\n // Update the value\n // Call the setter with the state cache and the params so that it can store the parameters\n const glState = WebGLStateTracker.get(gl);\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const {valueChanged, oldValue} = setter(glState._updateCache, ...params);\n\n // Call the original WebGL2RenderingContext func to make sure the context actually gets updated\n if (valueChanged) {\n originalSetterFunc(...params);\n }\n\n // Note: if the original function fails to set the value, our state cache will be bad\n // No solution for this at the moment, but assuming that this is unlikely to be a real problem\n // We could call the setter after the originalSetterFunc. Concern is that this would\n // cause different behavior in debug mode, where originalSetterFunc can throw exceptions\n\n return oldValue;\n };\n\n // Set the name of this anonymous function to help in debugging and profiling\n Object.defineProperty(gl[functionName], 'name', {\n value: `${functionName}-to-cache`,\n configurable: false\n });\n}\n\nfunction installProgramSpy(gl: WebGL2RenderingContext): void {\n const originalUseProgram = gl.useProgram.bind(gl);\n\n gl.useProgram = function useProgramLuma(handle) {\n const glState = WebGLStateTracker.get(gl);\n if (glState.program !== handle) {\n originalUseProgram(handle);\n glState.program = handle;\n }\n };\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {getWebGLContextData} from './webgl-context-data';\n\n/**\n * ContextProps\n * @param onContextLost\n * @param onContextRestored *\n */\ntype ContextProps = {\n /** Called when a context is lost */\n onContextLost: (event: Event) => void;\n /** Called when a context is restored */\n onContextRestored: (event: Event) => void;\n};\n\n/**\n * Create a WebGL context for a canvas\n * Note calling this multiple time on the same canvas does return the same context\n * @param canvas A canvas element or offscreen canvas\n */\nexport function createBrowserContext(\n canvas: HTMLCanvasElement | OffscreenCanvas,\n props: ContextProps,\n webglContextAttributes: WebGLContextAttributes\n): WebGL2RenderingContext {\n // Try to extract any extra information about why context creation failed\n let errorMessage = '';\n const onCreateError = (event: Event) => {\n const statusMessage = (event as WebGLContextEvent).statusMessage;\n if (statusMessage) {\n errorMessage ||= statusMessage;\n }\n };\n canvas.addEventListener('webglcontextcreationerror', onCreateError, false);\n\n const allowSoftwareRenderer = webglContextAttributes.failIfMajorPerformanceCaveat !== true;\n\n const webglProps: WebGLContextAttributes = {\n preserveDrawingBuffer: true,\n ...webglContextAttributes,\n // Always start by requesting a high-performance context.\n failIfMajorPerformanceCaveat: true\n };\n\n // Create the desired context\n let gl: WebGL2RenderingContext | null = null;\n\n try {\n // Create a webgl2 context\n gl ||= canvas.getContext('webgl2', webglProps);\n if (!gl && webglProps.failIfMajorPerformanceCaveat) {\n errorMessage ||=\n 'Only software GPU is available. Set `failIfMajorPerformanceCaveat: false` to allow.';\n }\n\n // Creation failed with failIfMajorPerformanceCaveat - Try a Software GPU\n let softwareRenderer = false;\n if (!gl && allowSoftwareRenderer) {\n webglProps.failIfMajorPerformanceCaveat = false;\n gl = canvas.getContext('webgl2', webglProps);\n softwareRenderer = true;\n }\n\n if (!gl) {\n gl = canvas.getContext('webgl', {}) as WebGL2RenderingContext;\n if (gl) {\n gl = null;\n errorMessage ||= 'Your browser only supports WebGL1';\n }\n }\n\n if (!gl) {\n errorMessage ||= 'Your browser does not support WebGL';\n throw new Error(`Failed to create WebGL context: ${errorMessage}`);\n }\n\n // Initialize luma.gl specific context data\n const luma = getWebGLContextData(gl);\n luma.softwareRenderer = softwareRenderer;\n\n // Carefully extract and wrap callbacks to prevent addEventListener from rebinding them.\n const {onContextLost, onContextRestored} = props;\n canvas.addEventListener('webglcontextlost', (event: Event) => onContextLost(event), false);\n canvas.addEventListener(\n 'webglcontextrestored',\n (event: Event) => onContextRestored(event),\n false\n );\n\n return gl;\n } finally {\n canvas.removeEventListener('webglcontextcreationerror', onCreateError, false);\n }\n}\n\n/* TODO - can we call this asynchronously to catch the error events?\nexport async function createBrowserContextAsync(canvas: HTMLCanvasElement | OffscreenCanvas, props: ContextProps): Promise {\n props = {...DEFAULT_CONTEXT_PROPS, ...props};\n\n // Try to extract any extra information about why context creation failed\n let errorMessage = null;\n const onCreateError = (error) => (errorMessage = error.statusMessage || errorMessage);\n canvas.addEventListener('webglcontextcreationerror', onCreateError, false);\n\n const gl = createBrowserContext(canvas, props);\n\n // Give the listener a chance to fire\n await new Promise(resolve => setTimeout(resolve, 0));\n\n canvas.removeEventListener('webglcontextcreationerror', onCreateError, false);\n\n return gl;\n}\n*/\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {GLExtensions} from '@luma.gl/webgl/constants';\n\n/** Ensure extensions are only requested once */\nexport function getWebGLExtension(\n gl: WebGL2RenderingContext,\n name: string,\n extensions: GLExtensions\n): unknown {\n // @ts-ignore TODO\n if (extensions[name] === undefined) {\n // @ts-ignore TODO\n extensions[name] = gl.getExtension(name) || null;\n }\n // @ts-ignore TODO\n return extensions[name];\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {DeviceInfo} from '@luma.gl/core';\nimport {GL, GLExtensions} from '@luma.gl/webgl/constants';\nimport {getWebGLExtension} from '../../context/helpers/webgl-extensions';\n\n/** @returns strings identifying the GPU vendor and driver. */\nexport function getDeviceInfo(gl: WebGL2RenderingContext, extensions: GLExtensions): DeviceInfo {\n // \"Masked\" info is always available, but don't contain much useful information\n const vendorMasked = gl.getParameter(GL.VENDOR);\n const rendererMasked = gl.getParameter(GL.RENDERER);\n\n // If we are lucky, unmasked info is available\n // https://www.khronos.org/registry/webgl/extensions/WEBGL_debug_renderer_info/\n getWebGLExtension(gl, 'WEBGL_debug_renderer_info', extensions);\n const ext = extensions.WEBGL_debug_renderer_info;\n const vendorUnmasked = gl.getParameter(ext ? ext.UNMASKED_VENDOR_WEBGL : GL.VENDOR);\n const rendererUnmasked = gl.getParameter(ext ? ext.UNMASKED_RENDERER_WEBGL : GL.RENDERER);\n const vendor = vendorUnmasked || vendorMasked;\n const renderer = rendererUnmasked || rendererMasked;\n\n // Driver version\n const version = gl.getParameter(GL.VERSION) as string;\n\n // \"Sniff\" the GPU type and backend from the info. This works best if unmasked info is available.\n const gpu = identifyGPUVendor(vendor, renderer);\n const gpuBackend = identifyGPUBackend(vendor, renderer);\n const gpuType = identifyGPUType(vendor, renderer);\n\n // Determine GLSL version\n // For now, skip parsing of the long version string, just use context type below to deduce version\n // const version = gl.getParameter(GL.SHADING_LANGUAGE_VERSION) as string;\n // const shadingLanguageVersion = parseGLSLVersion(version);\n const shadingLanguage = 'glsl';\n const shadingLanguageVersion = 300;\n\n return {\n type: 'webgl',\n gpu,\n gpuType,\n gpuBackend,\n vendor,\n renderer,\n version,\n shadingLanguage,\n shadingLanguageVersion\n };\n}\n\n/** \"Sniff\" the GPU type from the info. This works best if unmasked info is available. */\nfunction identifyGPUVendor(\n vendor: string,\n renderer: string\n): 'nvidia' | 'intel' | 'apple' | 'amd' | 'software' | 'unknown' {\n if (/NVIDIA/i.exec(vendor) || /NVIDIA/i.exec(renderer)) {\n return 'nvidia';\n }\n if (/INTEL/i.exec(vendor) || /INTEL/i.exec(renderer)) {\n return 'intel';\n }\n if (/Apple/i.exec(vendor) || /Apple/i.exec(renderer)) {\n return 'apple';\n }\n if (\n /AMD/i.exec(vendor) ||\n /AMD/i.exec(renderer) ||\n /ATI/i.exec(vendor) ||\n /ATI/i.exec(renderer)\n ) {\n return 'amd';\n }\n if (/SwiftShader/i.exec(vendor) || /SwiftShader/i.exec(renderer)) {\n return 'software';\n }\n\n return 'unknown';\n}\n\n/** \"Sniff\" the GPU backend from the info. This works best if unmasked info is available. */\nfunction identifyGPUBackend(vendor: string, renderer: string): 'opengl' | 'metal' | 'unknown' {\n if (/Metal/i.exec(vendor) || /Metal/i.exec(renderer)) {\n return 'metal';\n }\n if (/ANGLE/i.exec(vendor) || /ANGLE/i.exec(renderer)) {\n return 'opengl';\n }\n return 'unknown';\n}\n\nfunction identifyGPUType(\n vendor: string,\n renderer: string\n): 'discrete' | 'integrated' | 'cpu' | 'unknown' {\n if (/SwiftShader/i.exec(vendor) || /SwiftShader/i.exec(renderer)) {\n return 'cpu';\n }\n\n const gpuVendor = identifyGPUVendor(vendor, renderer);\n switch (gpuVendor) {\n case 'apple':\n return isAppleSiliconGPU(vendor, renderer) ? 'integrated' : 'unknown';\n case 'intel':\n return 'integrated';\n case 'software':\n return 'cpu';\n case 'unknown':\n return 'unknown';\n default:\n return 'discrete';\n }\n}\n\nfunction isAppleSiliconGPU(vendor: string, renderer: string): boolean {\n return /Apple (M\\d|A\\d|GPU)/i.test(`${vendor} ${renderer}`);\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {GL} from '@luma.gl/webgl/constants';\nimport {VertexFormat, NormalizedDataType} from '@luma.gl/core';\n\ntype GLDataType =\n | GL.UNSIGNED_BYTE\n | GL.BYTE\n | GL.UNSIGNED_SHORT\n | GL.SHORT\n | GL.UNSIGNED_INT\n | GL.INT\n | GL.HALF_FLOAT\n | GL.FLOAT;\n\n/** Get vertex format from GL constants */\nexport function getVertexFormatFromGL(type: GLDataType, components: 1 | 2 | 3 | 4): VertexFormat {\n const base = getVertexTypeFromGL(type);\n // biome-ignore format: preserve layout\n switch (components) {\n case 1: return base;\n case 2: return `${base}x2`;\n // @ts-expect-error TODO deal with lack of \"unaligned\" formats\n case 3: return `${base}x3`;\n case 4: return `${base}x4`;\n }\n // @ts-ignore unreachable\n throw new Error(String(components));\n}\n\n/** Get data type from GL constants */\nexport function getVertexTypeFromGL(type: GLDataType, normalized = false): NormalizedDataType {\n // biome-ignore format: preserve layout\n switch (type) {\n // WebGPU does not support normalized 32 bit integer attributes\n case GL.INT: return normalized ? 'sint32' : 'sint32';\n case GL.UNSIGNED_INT: return normalized ? 'uint32' : 'uint32';\n case GL.SHORT: return normalized ? 'sint16' : 'unorm16';\n case GL.UNSIGNED_SHORT: return normalized ? 'uint16' : 'unorm16';\n case GL.BYTE: return normalized ? 'sint8' : 'snorm16';\n case GL.UNSIGNED_BYTE: return normalized ? 'uint8' : 'unorm8';\n case GL.FLOAT: return 'float32';\n case GL.HALF_FLOAT: return 'float16';\n }\n // @ts-ignore unreachable\n throw new Error(String(type));\n}\n\nexport function getGLFromVertexType(\n dataType: NormalizedDataType\n):\n | GL.UNSIGNED_BYTE\n | GL.BYTE\n | GL.UNSIGNED_SHORT\n | GL.SHORT\n | GL.UNSIGNED_INT\n | GL.INT\n | GL.HALF_FLOAT\n | GL.FLOAT {\n // biome-ignore format: preserve layout\n switch (dataType) {\n case 'uint8': return GL.UNSIGNED_BYTE;\n case 'sint8': return GL.BYTE;\n case 'unorm8': return GL.UNSIGNED_BYTE;\n case 'snorm8': return GL.BYTE;\n case 'uint16': return GL.UNSIGNED_SHORT;\n case 'sint16': return GL.SHORT;\n case 'unorm16': return GL.UNSIGNED_SHORT;\n case 'snorm16': return GL.SHORT;\n case 'uint32': return GL.UNSIGNED_INT;\n case 'sint32': return GL.INT;\n // WebGPU does not support normalized 32 bit integer attributes\n // case 'unorm32': return GL.UNSIGNED_INT;\n // case 'snorm32': return GL.INT;\n case 'float16': return GL.HALF_FLOAT;\n case 'float32': return GL.FLOAT;\n }\n // @ts-ignore unreachable\n throw new Error(String(dataType));\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {\n DeviceFeature,\n TextureFormat,\n TextureFormatCapabilities,\n DeviceTextureFormatCapabilities\n} from '@luma.gl/core';\nimport {textureFormatDecoder} from '@luma.gl/core';\nimport {GL, GLPixelType, GLExtensions, GLTexelDataFormat} from '@luma.gl/webgl/constants';\nimport {getWebGLExtension} from '../../context/helpers/webgl-extensions';\nimport {getGLFromVertexType} from './webgl-vertex-formats';\n\n/* eslint-disable camelcase */\n\n// TEXTURE FEATURES\n\n// Define local webgl extension strings to optimize minification\nconst X_S3TC = 'WEBGL_compressed_texture_s3tc'; // BC1, BC2, BC3\nconst X_S3TC_SRGB = 'WEBGL_compressed_texture_s3tc_srgb'; // BC1, BC2, BC3\nconst X_RGTC = 'EXT_texture_compression_rgtc'; // BC4, BC5\nconst X_BPTC = 'EXT_texture_compression_bptc'; // BC6, BC7\nconst X_ETC2 = 'WEBGL_compressed_texture_etc'; // Renamed from 'WEBGL_compressed_texture_es3'\nconst X_ASTC = 'WEBGL_compressed_texture_astc';\nconst X_ETC1 = 'WEBGL_compressed_texture_etc1';\nconst X_PVRTC = 'WEBGL_compressed_texture_pvrtc';\nconst X_ATC = 'WEBGL_compressed_texture_atc';\n\n// Define local webgl extension strings to optimize minification\nconst EXT_texture_norm16 = 'EXT_texture_norm16';\nconst EXT_render_snorm = 'EXT_render_snorm';\nconst EXT_color_buffer_float = 'EXT_color_buffer_float';\nconst SNORM8_COLOR_RENDERABLE: DeviceFeature = 'snorm8-renderable-webgl';\nconst NORM16_COLOR_RENDERABLE: DeviceFeature = 'norm16-renderable-webgl';\nconst SNORM16_COLOR_RENDERABLE: DeviceFeature = 'snorm16-renderable-webgl';\nconst FLOAT16_COLOR_RENDERABLE: DeviceFeature = 'float16-renderable-webgl';\nconst FLOAT32_COLOR_RENDERABLE: DeviceFeature = 'float32-renderable-webgl';\nconst RGB9E5UFLOAT_COLOR_RENDERABLE: DeviceFeature = 'rgb9e5ufloat-renderable-webgl';\n\ntype TextureFeatureDefinition = {\n extensions?: string[];\n features?: DeviceFeature[];\n};\n\n// biome-ignore format: preserve layout\nexport const TEXTURE_FEATURES: Partial> = {\n 'float32-renderable-webgl': {extensions: [EXT_color_buffer_float]},\n 'float16-renderable-webgl': {extensions: ['EXT_color_buffer_half_float']},\n 'rgb9e5ufloat-renderable-webgl': {extensions: ['WEBGL_render_shared_exponent']},\n 'snorm8-renderable-webgl': {extensions: [EXT_render_snorm]},\n 'norm16-webgl': {extensions: [EXT_texture_norm16]},\n 'norm16-renderable-webgl': {features: ['norm16-webgl']},\n 'snorm16-renderable-webgl': {features: ['norm16-webgl'], extensions: [EXT_render_snorm]},\n\n 'float32-filterable': {extensions: ['OES_texture_float_linear']},\n 'float16-filterable-webgl': {extensions: ['OES_texture_half_float_linear']},\n 'texture-filterable-anisotropic-webgl': {extensions: ['EXT_texture_filter_anisotropic']},\n\n 'texture-blend-float-webgl': {extensions: ['EXT_float_blend']},\n\n 'texture-compression-bc': {extensions: [X_S3TC, X_S3TC_SRGB, X_RGTC, X_BPTC]},\n // 'texture-compression-bc3-srgb-webgl': [X_S3TC_SRGB],\n // 'texture-compression-bc3-webgl': [X_S3TC],\n 'texture-compression-bc5-webgl': {extensions: [X_RGTC]},\n 'texture-compression-bc7-webgl': {extensions: [X_BPTC]},\n 'texture-compression-etc2': {extensions: [X_ETC2]},\n 'texture-compression-astc': {extensions: [X_ASTC]},\n 'texture-compression-etc1-webgl': {extensions: [X_ETC1]},\n 'texture-compression-pvrtc-webgl': {extensions: [X_PVRTC]},\n 'texture-compression-atc-webgl': {extensions: [X_ATC]}\n};\n\nexport function isTextureFeature(feature: DeviceFeature): boolean {\n return feature in TEXTURE_FEATURES;\n}\n\n/** Checks a texture feature (for Device.features). Mainly compressed texture support */\nexport function checkTextureFeature(\n gl: WebGL2RenderingContext,\n feature: DeviceFeature,\n extensions: GLExtensions\n): boolean {\n return hasTextureFeature(gl, feature, extensions, new Set());\n}\n\nfunction hasTextureFeature(\n gl: WebGL2RenderingContext,\n feature: DeviceFeature,\n extensions: GLExtensions,\n seenFeatures: Set\n): boolean {\n const definition = TEXTURE_FEATURES[feature];\n if (!definition) {\n return false;\n }\n\n if (seenFeatures.has(feature)) {\n return false;\n }\n\n seenFeatures.add(feature);\n const hasDependentFeatures = (definition.features || []).every(dependentFeature =>\n hasTextureFeature(gl, dependentFeature, extensions, seenFeatures)\n );\n seenFeatures.delete(feature);\n if (!hasDependentFeatures) {\n return false;\n }\n\n return (definition.extensions || []).every(extension =>\n Boolean(getWebGLExtension(gl, extension, extensions))\n );\n}\n\n// TEXTURE FORMATS\n\n/** Map a format to webgl and constants */\ntype WebGLFormatInfo = {\n gl?: GL;\n /** compressed */\n x?: string;\n /** color-renderable capability gate. false means never color-renderable on WebGL. */\n r?: DeviceFeature | false;\n types?: GLPixelType[];\n dataFormat?: GLTexelDataFormat;\n /** if depthTexture is set this is a depth/stencil format that can be set to a texture */\n depthTexture?: boolean;\n /** @deprecated can this format be used with renderbuffers */\n rb?: boolean;\n};\n\n// TABLES\n\n/**\n * Texture format data -\n * Exported but can change without notice\n */\n// biome-ignore format: preserve layout\nexport const WEBGL_TEXTURE_FORMATS: Record = {\n // 8-bit formats\n 'r8unorm': {gl: GL.R8, rb: true},\n 'r8snorm': {gl: GL.R8_SNORM, r: SNORM8_COLOR_RENDERABLE},\n 'r8uint': {gl: GL.R8UI, rb: true},\n 'r8sint': {gl: GL.R8I, rb: true},\n\n // 16-bit formats\n 'rg8unorm': {gl: GL.RG8, rb: true},\n 'rg8snorm': {gl: GL.RG8_SNORM, r: SNORM8_COLOR_RENDERABLE},\n 'rg8uint': {gl: GL.RG8UI, rb: true},\n 'rg8sint': {gl: GL.RG8I, rb: true},\n\n 'r16uint': {gl: GL.R16UI, rb: true},\n 'r16sint': {gl: GL.R16I, rb: true},\n 'r16float': {gl: GL.R16F, rb: true, r: FLOAT16_COLOR_RENDERABLE},\n 'r16unorm': {gl: GL.R16_EXT, rb: true, r: NORM16_COLOR_RENDERABLE},\n 'r16snorm': {gl: GL.R16_SNORM_EXT, r: SNORM16_COLOR_RENDERABLE},\n\n // Packed 16-bit formats\n 'rgba4unorm-webgl': {gl: GL.RGBA4, rb: true},\n 'rgb565unorm-webgl': {gl: GL.RGB565, rb: true},\n 'rgb5a1unorm-webgl': {gl: GL.RGB5_A1, rb: true},\n\n // 24-bit formats\n 'rgb8unorm-webgl': {gl: GL.RGB8},\n 'rgb8snorm-webgl': {gl: GL.RGB8_SNORM},\n\n // 32-bit formats\n 'rgba8unorm': {gl: GL.RGBA8},\n 'rgba8unorm-srgb': {gl: GL.SRGB8_ALPHA8},\n 'rgba8snorm': {gl: GL.RGBA8_SNORM, r: SNORM8_COLOR_RENDERABLE},\n 'rgba8uint': {gl: GL.RGBA8UI},\n 'rgba8sint': {gl: GL.RGBA8I},\n // reverse colors, webgpu only\n 'bgra8unorm': {},\n 'bgra8unorm-srgb': {},\n\n 'rg16uint': {gl: GL.RG16UI},\n 'rg16sint': {gl: GL.RG16I},\n 'rg16float': {gl: GL.RG16F, rb: true, r: FLOAT16_COLOR_RENDERABLE},\n 'rg16unorm': {gl: GL.RG16_EXT, r: NORM16_COLOR_RENDERABLE},\n 'rg16snorm': {gl: GL.RG16_SNORM_EXT, r: SNORM16_COLOR_RENDERABLE},\n\n 'r32uint': {gl: GL.R32UI, rb: true},\n 'r32sint': {gl: GL.R32I, rb: true},\n 'r32float': {gl: GL.R32F, r: FLOAT32_COLOR_RENDERABLE},\n\n // Packed 32-bit formats\n 'rgb9e5ufloat': {gl: GL.RGB9_E5, r: RGB9E5UFLOAT_COLOR_RENDERABLE}, // , filter: true},\n 'rg11b10ufloat': {gl: GL.R11F_G11F_B10F, rb: true},\n 'rgb10a2unorm': {gl: GL.RGB10_A2, rb: true},\n 'rgb10a2uint': {gl: GL.RGB10_A2UI, rb: true},\n\n // 48-bit formats\n 'rgb16unorm-webgl': {gl: GL.RGB16_EXT, r: false}, // rgb not renderable\n 'rgb16snorm-webgl': {gl: GL.RGB16_SNORM_EXT, r: false}, // rgb not renderable\n\n // 64-bit formats\n 'rg32uint': {gl: GL.RG32UI, rb: true},\n 'rg32sint': {gl: GL.RG32I, rb: true},\n 'rg32float': {gl: GL.RG32F, rb: true, r: FLOAT32_COLOR_RENDERABLE},\n 'rgba16uint': {gl: GL.RGBA16UI, rb: true},\n 'rgba16sint': {gl: GL.RGBA16I, rb: true},\n 'rgba16float': {gl: GL.RGBA16F, r: FLOAT16_COLOR_RENDERABLE},\n 'rgba16unorm': {gl: GL.RGBA16_EXT, rb: true, r: NORM16_COLOR_RENDERABLE},\n 'rgba16snorm': {gl: GL.RGBA16_SNORM_EXT, r: SNORM16_COLOR_RENDERABLE},\n\n // 96-bit formats (deprecated!)\n 'rgb32float-webgl': {gl: GL.RGB32F, x: EXT_color_buffer_float, r: FLOAT32_COLOR_RENDERABLE, dataFormat: GL.RGB, types: [GL.FLOAT]},\n\n // 128-bit formats\n 'rgba32uint': {gl: GL.RGBA32UI, rb: true},\n 'rgba32sint': {gl: GL.RGBA32I, rb: true},\n 'rgba32float': {gl: GL.RGBA32F, rb: true, r: FLOAT32_COLOR_RENDERABLE},\n\n // Depth and stencil formats\n 'stencil8': {gl: GL.STENCIL_INDEX8, rb: true}, // 8 stencil bits\n\n 'depth16unorm': {gl: GL.DEPTH_COMPONENT16, dataFormat: GL.DEPTH_COMPONENT, types: [GL.UNSIGNED_SHORT], rb: true}, // 16 depth bits\n 'depth24plus': {gl: GL.DEPTH_COMPONENT24, dataFormat: GL.DEPTH_COMPONENT, types: [GL.UNSIGNED_INT]},\n 'depth32float': {gl: GL.DEPTH_COMPONENT32F, dataFormat: GL.DEPTH_COMPONENT, types: [GL.FLOAT], rb: true},\n\n // The depth component of the \"depth24plus\" and \"depth24plus-stencil8\" formats may be implemented as either a 24-bit depth value or a \"depth32float\" value.\n 'depth24plus-stencil8': {gl: GL.DEPTH24_STENCIL8, rb: true, depthTexture: true, dataFormat: GL.DEPTH_STENCIL, types: [GL.UNSIGNED_INT_24_8]},\n // \"depth32float-stencil8\" feature - TODO below is render buffer only?\n 'depth32float-stencil8': {gl: GL.DEPTH32F_STENCIL8, dataFormat: GL.DEPTH_STENCIL, types: [GL.FLOAT_32_UNSIGNED_INT_24_8_REV], rb: true},\n\n // BC compressed formats: check device.features.has(\"texture-compression-bc\");\n\n 'bc1-rgb-unorm-webgl': {gl: GL.COMPRESSED_RGB_S3TC_DXT1_EXT, x: X_S3TC},\n 'bc1-rgb-unorm-srgb-webgl': {gl: GL.COMPRESSED_SRGB_S3TC_DXT1_EXT, x: X_S3TC_SRGB},\n\n 'bc1-rgba-unorm': {gl: GL.COMPRESSED_RGBA_S3TC_DXT1_EXT, x: X_S3TC},\n 'bc1-rgba-unorm-srgb': {gl: GL.COMPRESSED_SRGB_S3TC_DXT1_EXT, x: X_S3TC_SRGB},\n 'bc2-rgba-unorm': {gl: GL.COMPRESSED_RGBA_S3TC_DXT3_EXT, x: X_S3TC},\n 'bc2-rgba-unorm-srgb': {gl: GL.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT, x: X_S3TC_SRGB},\n 'bc3-rgba-unorm': {gl: GL.COMPRESSED_RGBA_S3TC_DXT5_EXT, x: X_S3TC},\n 'bc3-rgba-unorm-srgb': {gl: GL.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT, x: X_S3TC_SRGB},\n 'bc4-r-unorm': {gl: GL.COMPRESSED_RED_RGTC1_EXT, x: X_RGTC},\n 'bc4-r-snorm': {gl: GL.COMPRESSED_SIGNED_RED_RGTC1_EXT, x: X_RGTC},\n 'bc5-rg-unorm': {gl: GL.COMPRESSED_RED_GREEN_RGTC2_EXT, x: X_RGTC},\n 'bc5-rg-snorm': {gl: GL.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT, x: X_RGTC},\n 'bc6h-rgb-ufloat': {gl: GL.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT, x: X_BPTC},\n 'bc6h-rgb-float': {gl: GL.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT, x: X_BPTC},\n 'bc7-rgba-unorm': {gl: GL.COMPRESSED_RGBA_BPTC_UNORM_EXT, x: X_BPTC},\n 'bc7-rgba-unorm-srgb': {gl: GL.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT, x: X_BPTC},\n\n // WEBGL_compressed_texture_etc: device.features.has(\"texture-compression-etc2\")\n // Note: Supposedly guaranteed availability compressed formats in WebGL2, but through CPU decompression\n\n 'etc2-rgb8unorm': {gl: GL.COMPRESSED_RGB8_ETC2},\n 'etc2-rgb8unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ETC2},\n 'etc2-rgb8a1unorm': {gl: GL.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2},\n 'etc2-rgb8a1unorm-srgb': {gl: GL.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2},\n 'etc2-rgba8unorm': {gl: GL.COMPRESSED_RGBA8_ETC2_EAC},\n 'etc2-rgba8unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC},\n\n 'eac-r11unorm': {gl: GL.COMPRESSED_R11_EAC},\n 'eac-r11snorm': {gl: GL.COMPRESSED_SIGNED_R11_EAC},\n 'eac-rg11unorm': {gl: GL.COMPRESSED_RG11_EAC},\n 'eac-rg11snorm': {gl: GL.COMPRESSED_SIGNED_RG11_EAC},\n\n // X_ASTC compressed formats: device.features.has(\"texture-compression-astc\")\n\n 'astc-4x4-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_4x4_KHR},\n 'astc-4x4-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR},\n 'astc-5x4-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_5x4_KHR},\n 'astc-5x4-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR},\n 'astc-5x5-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_5x5_KHR},\n 'astc-5x5-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR},\n 'astc-6x5-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_6x5_KHR},\n 'astc-6x5-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR},\n 'astc-6x6-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_6x6_KHR},\n 'astc-6x6-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR},\n 'astc-8x5-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_8x5_KHR},\n 'astc-8x5-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR},\n 'astc-8x6-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_8x6_KHR},\n 'astc-8x6-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR},\n 'astc-8x8-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_8x8_KHR},\n 'astc-8x8-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR},\n 'astc-10x5-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_10x5_KHR},\n 'astc-10x5-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR},\n 'astc-10x6-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_10x6_KHR},\n 'astc-10x6-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR},\n 'astc-10x8-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_10x8_KHR},\n 'astc-10x8-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR},\n 'astc-10x10-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_10x10_KHR},\n 'astc-10x10-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR},\n 'astc-12x10-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_12x10_KHR},\n 'astc-12x10-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR},\n 'astc-12x12-unorm': {gl: GL.COMPRESSED_RGBA_ASTC_12x12_KHR},\n 'astc-12x12-unorm-srgb': {gl: GL.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR},\n\n // WEBGL_compressed_texture_pvrtc\n\n 'pvrtc-rgb4unorm-webgl': {gl: GL.COMPRESSED_RGB_PVRTC_4BPPV1_IMG},\n 'pvrtc-rgba4unorm-webgl': {gl: GL.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG},\n 'pvrtc-rgb2unorm-webgl': {gl: GL.COMPRESSED_RGB_PVRTC_2BPPV1_IMG},\n 'pvrtc-rgba2unorm-webgl': {gl: GL.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG},\n\n // WEBGL_compressed_texture_etc1\n\n 'etc1-rbg-unorm-webgl': {gl: GL.COMPRESSED_RGB_ETC1_WEBGL},\n\n // WEBGL_compressed_texture_atc\n\n 'atc-rgb-unorm-webgl': {gl: GL.COMPRESSED_RGB_ATC_WEBGL},\n 'atc-rgba-unorm-webgl': {gl: GL.COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL},\n 'atc-rgbai-unorm-webgl': {gl: GL.COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL}\n};\n\n// FUNCTIONS\n\n/** Checks if a texture format is supported, renderable, filterable etc */\nexport function getTextureFormatCapabilitiesWebGL(\n gl: WebGL2RenderingContext,\n formatSupport: TextureFormatCapabilities,\n extensions: GLExtensions\n): DeviceTextureFormatCapabilities {\n let supported = formatSupport.create;\n const webglFormatInfo = WEBGL_TEXTURE_FORMATS[formatSupport.format];\n\n // Support Check that we have a GL constant\n if (webglFormatInfo?.gl === undefined) {\n supported = false;\n }\n\n if (webglFormatInfo?.x) {\n supported = supported && Boolean(getWebGLExtension(gl, webglFormatInfo.x, extensions));\n }\n\n // WebGL2 exposes STENCIL_INDEX8 for renderbuffers, but standalone stencil textures are not\n // valid texture storage targets. Report them as unsupported texture formats to avoid invalid\n // constructor paths and misleading capability checks.\n if (formatSupport.format === 'stencil8') {\n supported = false;\n }\n\n const renderFeatureSupported =\n webglFormatInfo?.r === false\n ? false\n : webglFormatInfo?.r === undefined || checkTextureFeature(gl, webglFormatInfo.r, extensions);\n const renderable =\n supported &&\n formatSupport.render &&\n renderFeatureSupported &&\n isColorRenderableTextureFormat(gl, formatSupport.format, extensions);\n\n return {\n format: formatSupport.format,\n // @ts-ignore\n create: supported && formatSupport.create,\n // @ts-ignore\n render: renderable,\n // @ts-ignore\n filter: supported && formatSupport.filter,\n // @ts-ignore\n blend: supported && formatSupport.blend,\n // @ts-ignore\n store: supported && formatSupport.store\n };\n}\n\nfunction isColorRenderableTextureFormat(\n gl: WebGL2RenderingContext,\n format: TextureFormat,\n extensions: GLExtensions\n): boolean {\n const webglFormatInfo = WEBGL_TEXTURE_FORMATS[format];\n const internalFormat = webglFormatInfo?.gl;\n if (internalFormat === undefined) {\n return false;\n }\n\n if (webglFormatInfo?.x && !getWebGLExtension(gl, webglFormatInfo.x, extensions)) {\n return false;\n }\n\n const previousTexture = gl.getParameter(GL.TEXTURE_BINDING_2D) as WebGLTexture | null;\n const previousFramebuffer = gl.getParameter(GL.FRAMEBUFFER_BINDING) as WebGLFramebuffer | null;\n const texture = gl.createTexture();\n const framebuffer = gl.createFramebuffer();\n if (!texture || !framebuffer) {\n return false;\n }\n\n // Isolate the probe from any prior driver errors so the result reflects only this format.\n const noError = Number(GL.NO_ERROR);\n let error = Number(gl.getError());\n while (error !== noError) {\n error = gl.getError();\n }\n\n let renderable = false;\n try {\n gl.bindTexture(GL.TEXTURE_2D, texture);\n gl.texStorage2D(GL.TEXTURE_2D, 1, internalFormat, 1, 1);\n if (Number(gl.getError()) !== noError) {\n return false;\n }\n\n gl.bindFramebuffer(GL.FRAMEBUFFER, framebuffer);\n gl.framebufferTexture2D(GL.FRAMEBUFFER, GL.COLOR_ATTACHMENT0, GL.TEXTURE_2D, texture, 0);\n renderable =\n Number(gl.checkFramebufferStatus(GL.FRAMEBUFFER)) === Number(GL.FRAMEBUFFER_COMPLETE) &&\n Number(gl.getError()) === noError;\n } finally {\n gl.bindFramebuffer(GL.FRAMEBUFFER, previousFramebuffer);\n gl.deleteFramebuffer(framebuffer);\n gl.bindTexture(GL.TEXTURE_2D, previousTexture);\n gl.deleteTexture(texture);\n }\n\n return renderable;\n}\n\n/** Get parameters necessary to work with format in WebGL: internalFormat, dataFormat, type, compressed, */\nexport function getTextureFormatWebGL(format: TextureFormat): {\n internalFormat: GL;\n format: GLTexelDataFormat;\n type: GLPixelType;\n compressed: boolean;\n} {\n const formatData = WEBGL_TEXTURE_FORMATS[format];\n const webglFormat = convertTextureFormatToGL(format);\n const decoded = textureFormatDecoder.getInfo(format);\n\n if (decoded.compressed) {\n // TODO: Unclear whether this is always valid, this may be why ETC2 RGBA8 fails.\n formatData.dataFormat = webglFormat as GLTexelDataFormat;\n }\n\n return {\n internalFormat: webglFormat,\n format:\n formatData?.dataFormat ||\n getWebGLPixelDataFormat(decoded.channels, decoded.integer, decoded.normalized, webglFormat),\n // depth formats don't have a type\n type: decoded.dataType\n ? getGLFromVertexType(decoded.dataType)\n : formatData?.types?.[0] || GL.UNSIGNED_BYTE,\n compressed: decoded.compressed || false\n };\n}\n\nexport function getDepthStencilAttachmentWebGL(\n format: TextureFormat\n): GL.DEPTH_ATTACHMENT | GL.STENCIL_ATTACHMENT | GL.DEPTH_STENCIL_ATTACHMENT {\n const formatInfo = textureFormatDecoder.getInfo(format);\n switch (formatInfo.attachment) {\n case 'depth':\n return GL.DEPTH_ATTACHMENT;\n case 'stencil':\n return GL.STENCIL_ATTACHMENT;\n case 'depth-stencil':\n return GL.DEPTH_STENCIL_ATTACHMENT;\n default:\n throw new Error(`Not a depth stencil format: ${format}`);\n }\n}\n\n/** TODO - VERY roundabout legacy way of calculating bytes per pixel */\nexport function getTextureFormatBytesPerPixel(format: TextureFormat): number {\n const formatInfo = textureFormatDecoder.getInfo(format);\n return formatInfo.bytesPerPixel;\n}\n\n// DATA TYPE HELPERS\n\nexport function getWebGLPixelDataFormat(\n channels: 'r' | 'rg' | 'rgb' | 'rgba' | 'bgra',\n integer: boolean,\n normalized: boolean,\n format: GL\n): GLTexelDataFormat {\n // WebGL1 formats use same internalFormat\n if (format === GL.RGBA || format === GL.RGB) {\n return format;\n }\n // biome-ignore format: preserve layout\n switch (channels) {\n case 'r': return integer && !normalized ? GL.RED_INTEGER : GL.RED;\n case 'rg': return integer && !normalized ? GL.RG_INTEGER : GL.RG;\n case 'rgb': return integer && !normalized ? GL.RGB_INTEGER : GL.RGB;\n case 'rgba': return integer && !normalized ? GL.RGBA_INTEGER : GL.RGBA;\n case 'bgra': throw new Error('bgra pixels not supported by WebGL');\n default: return GL.RGBA;\n }\n}\n\n/**\n * Map WebGPU style texture format strings to GL constants\n */\nfunction convertTextureFormatToGL(format: TextureFormat): GL {\n const formatInfo = WEBGL_TEXTURE_FORMATS[format];\n const webglFormat = formatInfo?.gl;\n if (webglFormat === undefined) {\n throw new Error(`Unsupported texture format ${format}`);\n }\n return webglFormat;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// Feature detection for WebGL\n// Provides a function that enables simple checking of which WebGL features are\n\nimport {DeviceFeature, DeviceFeatures} from '@luma.gl/core';\nimport {GLExtensions} from '@luma.gl/webgl/constants';\nimport {getWebGLExtension} from '../../context/helpers/webgl-extensions';\nimport {\n isTextureFeature,\n checkTextureFeature,\n TEXTURE_FEATURES\n} from '../converters/webgl-texture-table';\n\n/**\n * Defines luma.gl \"feature\" names and semantics\n * when value is 'string' it is the name of the extension that enables this feature\n */\nconst WEBGL_FEATURES: Partial> = {\n // optional WebGPU features\n 'depth-clip-control': 'EXT_depth_clamp', // TODO these seem subtly different\n 'timestamp-query': 'EXT_disjoint_timer_query_webgl2',\n // \"indirect-first-instance\"\n // Textures are handled by getTextureFeatures()\n // 'depth32float-stencil8' // GPUTextureFormat 'depth32float-stencil8'\n\n // optional WebGL features\n 'compilation-status-async-webgl': 'KHR_parallel_shader_compile',\n 'polygon-mode-webgl': 'WEBGL_polygon_mode',\n 'provoking-vertex-webgl': 'WEBGL_provoking_vertex',\n 'shader-clip-cull-distance-webgl': 'WEBGL_clip_cull_distance',\n 'shader-noperspective-interpolation-webgl': 'NV_shader_noperspective_interpolation',\n 'shader-conservative-depth-webgl': 'EXT_conservative_depth'\n\n // Textures are handled by getTextureFeatures()\n};\n\n/**\n * WebGL extensions exposed as luma.gl features\n * To minimize GL log noise and improve performance, this class ensures that\n * - WebGL extensions are not queried until the corresponding feature is checked.\n * - WebGL extensions are only queried once.\n */\nexport class WebGLDeviceFeatures extends DeviceFeatures {\n protected gl: WebGL2RenderingContext;\n protected extensions: GLExtensions;\n protected testedFeatures = new Set();\n\n constructor(\n gl: WebGL2RenderingContext,\n extensions: GLExtensions,\n disabledFeatures: Partial>\n ) {\n super([], disabledFeatures);\n this.gl = gl;\n this.extensions = extensions;\n // TODO - is this really needed?\n // Enable EXT_float_blend first: https://developer.mozilla.org/en-US/docs/Web/API/EXT_float_blend\n getWebGLExtension(gl, 'EXT_color_buffer_float', extensions);\n }\n\n override *[Symbol.iterator](): IterableIterator {\n const features = this.getFeatures();\n for (const feature of features) {\n if (this.has(feature)) {\n yield feature;\n }\n }\n return [];\n }\n\n override has(feature: DeviceFeature): boolean {\n if (this.disabledFeatures?.[feature]) {\n return false;\n }\n\n // We have already tested this feature\n if (!this.testedFeatures.has(feature)) {\n this.testedFeatures.add(feature);\n\n // Check the feature once\n if (isTextureFeature(feature) && checkTextureFeature(this.gl, feature, this.extensions)) {\n this.features.add(feature);\n }\n\n if (this.getWebGLFeature(feature)) {\n this.features.add(feature);\n }\n }\n return this.features.has(feature);\n }\n\n // FOR DEVICE\n\n initializeFeatures() {\n // Initialize all features by checking them.\n // Except WEBGL_polygon_mode since Chrome logs ugly console warnings\n const features = this.getFeatures().filter(feature => feature !== 'polygon-mode-webgl');\n for (const feature of features) {\n this.has(feature);\n }\n }\n\n // IMPLEMENTATION\n\n getFeatures() {\n return [...Object.keys(WEBGL_FEATURES), ...Object.keys(TEXTURE_FEATURES)] as DeviceFeature[];\n }\n\n /** Extract all WebGL features */\n protected getWebGLFeature(feature: DeviceFeature): boolean {\n const featureInfo = WEBGL_FEATURES[feature];\n // string value requires checking the corresponding WebGL extension\n const isSupported =\n typeof featureInfo === 'string'\n ? Boolean(getWebGLExtension(this.gl, featureInfo, this.extensions))\n : Boolean(featureInfo);\n\n return isSupported;\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {DeviceLimits} from '@luma.gl/core';\nimport {GL} from '@luma.gl/webgl/constants';\n\n// biome-ignore format: preserve layout\nexport class WebGLDeviceLimits extends DeviceLimits {\n get maxTextureDimension1D() { return 0; } // WebGL does not support 1D textures\n get maxTextureDimension2D() { return this.getParameter(GL.MAX_TEXTURE_SIZE); }\n get maxTextureDimension3D() { return this.getParameter(GL.MAX_3D_TEXTURE_SIZE); }\n get maxTextureArrayLayers() { return this.getParameter(GL.MAX_ARRAY_TEXTURE_LAYERS); }\n get maxBindGroups() { return 0; }\n get maxDynamicUniformBuffersPerPipelineLayout() { return 0; } // TBD\n get maxDynamicStorageBuffersPerPipelineLayout() { return 0; } // TBD\n get maxSampledTexturesPerShaderStage() { return this.getParameter(GL.MAX_VERTEX_TEXTURE_IMAGE_UNITS); } // ) TBD\n get maxSamplersPerShaderStage() { return this.getParameter(GL.MAX_COMBINED_TEXTURE_IMAGE_UNITS); }\n get maxStorageBuffersPerShaderStage() { return 0; } // TBD\n get maxStorageTexturesPerShaderStage() { return 0; } // TBD\n get maxUniformBuffersPerShaderStage() { return this.getParameter(GL.MAX_UNIFORM_BUFFER_BINDINGS); }\n get maxUniformBufferBindingSize() { return this.getParameter(GL.MAX_UNIFORM_BLOCK_SIZE); }\n get maxStorageBufferBindingSize() { return 0; }\n get minUniformBufferOffsetAlignment() { return this.getParameter(GL.UNIFORM_BUFFER_OFFSET_ALIGNMENT); }\n get minStorageBufferOffsetAlignment() { return 0; } \n get maxVertexBuffers() { return 16; } // WebGL 2 supports 16 buffers, see https://github.com/gpuweb/gpuweb/issues/4284\n get maxVertexAttributes() { return this.getParameter(GL.MAX_VERTEX_ATTRIBS); }\n get maxVertexBufferArrayStride() { return 2048; } // TBD, this is just the default value from WebGPU\n get maxInterStageShaderVariables() { return this.getParameter(GL.MAX_VARYING_COMPONENTS); }\n get maxComputeWorkgroupStorageSize() { return 0; } // WebGL does not support compute shaders\n get maxComputeInvocationsPerWorkgroup() { return 0; } // WebGL does not support compute shaders\n get maxComputeWorkgroupSizeX() { return 0; } // WebGL does not support compute shaders\n get maxComputeWorkgroupSizeY() { return 0; } // WebGL does not support compute shaders\n get maxComputeWorkgroupSizeZ() { return 0; } // WebGL does not support compute shaders\n get maxComputeWorkgroupsPerDimension() { return 0;} // WebGL does not support compute shaders\n\n // PRIVATE\n\n protected gl: WebGL2RenderingContext;\n protected limits: Partial> = {};\n\n constructor(gl: WebGL2RenderingContext) {\n super();\n this.gl = gl;\n }\n\n protected getParameter(parameter: GL): number {\n if (this.limits[parameter] === undefined) {\n this.limits[parameter] = this.gl.getParameter(parameter);\n }\n return this.limits[parameter] || 0;\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {FramebufferProps} from '@luma.gl/core';\nimport {Framebuffer} from '@luma.gl/core';\nimport {GL} from '@luma.gl/webgl/constants';\nimport {WebGLDevice} from '../webgl-device';\nimport {WEBGLTexture} from './webgl-texture';\nimport {WEBGLTextureView} from './webgl-texture-view';\nimport {getDepthStencilAttachmentWebGL} from '../converters/webgl-texture-table';\n\nexport type Attachment = WEBGLTextureView | WEBGLTexture; // | WEBGLRenderbuffer;\n\n/** luma.gl Framebuffer, WebGL implementation */\nexport class WEBGLFramebuffer extends Framebuffer {\n readonly device: WebGLDevice;\n gl: WebGL2RenderingContext;\n readonly handle: WebGLFramebuffer;\n\n colorAttachments: WEBGLTextureView[] = [];\n depthStencilAttachment: WEBGLTextureView | null = null;\n\n constructor(device: WebGLDevice, props: FramebufferProps) {\n super(device, props);\n\n // WebGL default framebuffer handle is null\n const isDefaultFramebuffer = props.handle === null;\n\n this.device = device;\n this.gl = device.gl;\n this.handle =\n this.props.handle || isDefaultFramebuffer ? this.props.handle : this.gl.createFramebuffer();\n\n if (!isDefaultFramebuffer) {\n // default framebuffer handle is null, so we can't set debug metadata...\n device._setWebGLDebugMetadata(this.handle, this, {spector: this.props});\n\n if (!props.handle) {\n // Auto create textures for attachments if needed\n this.autoCreateAttachmentTextures();\n\n this.updateAttachments();\n }\n }\n }\n\n /** destroys any auto created resources etc. */\n override destroy(): void {\n super.destroy(); // destroys owned resources etc.\n if (!this.destroyed && this.handle !== null && !this.props.handle) {\n this.gl.deleteFramebuffer(this.handle);\n }\n }\n\n protected updateAttachments(): void {\n /** Attach from a map of attachments */\n // @ts-expect-error native bindFramebuffer is overridden by our state tracker\n const prevHandle: WebGLFramebuffer | null = this.gl.bindFramebuffer(\n GL.FRAMEBUFFER,\n this.handle\n );\n\n // Walk the attachments\n for (let i = 0; i < this.colorAttachments.length; ++i) {\n const attachment = this.colorAttachments[i];\n if (attachment) {\n const attachmentPoint = GL.COLOR_ATTACHMENT0 + i;\n this._attachTextureView(attachmentPoint, attachment);\n }\n }\n\n if (this.depthStencilAttachment) {\n const attachmentPoint = getDepthStencilAttachmentWebGL(\n this.depthStencilAttachment.props.format\n );\n this._attachTextureView(attachmentPoint, this.depthStencilAttachment);\n }\n\n /** Check the status */\n if (this.device.props.debug) {\n const status = this.gl.checkFramebufferStatus(GL.FRAMEBUFFER) as GL;\n if (status !== GL.FRAMEBUFFER_COMPLETE) {\n throw new Error(`Framebuffer ${_getFrameBufferStatus(status)}`);\n }\n }\n\n this.gl.bindFramebuffer(GL.FRAMEBUFFER, prevHandle);\n }\n\n // PRIVATE\n\n /** In WebGL we must use renderbuffers for depth/stencil attachments (unless we have extensions) */\n // protected override createDepthStencilTexture(format: TextureFormat): Texture {\n // // return new WEBGLRenderbuffer(this.device, {\n // return new WEBGLTexture(this.device, {\n // id: `${this.id}-depth-stencil`,\n // format,\n // width: this.width,\n // height: this.height,\n // mipmaps: false\n // });\n // }\n\n /**\n * @param attachment\n * @param texture\n * @param layer = 0 - index into WEBGLTextureArray and Texture3D or face for `TextureCubeMap`\n * @param level = 0 - mipmapLevel\n */\n protected _attachTextureView(attachment: GL, textureView: WEBGLTextureView): void {\n const {gl} = this.device;\n const {texture} = textureView;\n const level = textureView.props.baseMipLevel;\n const layer = textureView.props.baseArrayLayer;\n\n gl.bindTexture(texture.glTarget, texture.handle);\n\n switch (texture.glTarget) {\n case GL.TEXTURE_2D_ARRAY:\n case GL.TEXTURE_3D:\n gl.framebufferTextureLayer(GL.FRAMEBUFFER, attachment, texture.handle, level, layer);\n break;\n\n case GL.TEXTURE_CUBE_MAP:\n // layer must be a cubemap face (or if index, converted to cube map face)\n const face = mapIndexToCubeMapFace(layer);\n gl.framebufferTexture2D(GL.FRAMEBUFFER, attachment, face, texture.handle, level);\n break;\n\n case GL.TEXTURE_2D:\n gl.framebufferTexture2D(GL.FRAMEBUFFER, attachment, GL.TEXTURE_2D, texture.handle, level);\n break;\n\n default:\n throw new Error('Illegal texture type');\n }\n\n gl.bindTexture(texture.glTarget, null);\n }\n\n /** Default framebuffer resize is managed by canvas size and should be a no-op. */\n protected override resizeAttachments(width: number, height: number): void {\n if (this.handle === null) {\n this.width = width;\n this.height = height;\n return;\n }\n\n super.resizeAttachments(width, height);\n }\n}\n\n// Helper functions\n\n// Map an index to a cube map face constant\nfunction mapIndexToCubeMapFace(layer: number | GL): GL {\n // TEXTURE_CUBE_MAP_POSITIVE_X is a big value (0x8515)\n // if smaller assume layer is index, otherwise assume it is already a cube map face constant\n return layer < (GL.TEXTURE_CUBE_MAP_POSITIVE_X as number)\n ? layer + GL.TEXTURE_CUBE_MAP_POSITIVE_X\n : layer;\n}\n\n// Helper METHODS\n// Get a string describing the framebuffer error if installed\nfunction _getFrameBufferStatus(status: GL) {\n switch (status) {\n case GL.FRAMEBUFFER_COMPLETE:\n return 'success';\n case GL.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:\n return 'Mismatched attachments';\n case GL.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:\n return 'No attachments';\n case GL.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:\n return 'Height/width mismatch';\n case GL.FRAMEBUFFER_UNSUPPORTED:\n return 'Unsupported or split attachments';\n // WebGL2\n case GL.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:\n return 'Samples mismatch';\n // OVR_multiview2 extension\n // case GL.FRAMEBUFFER_INCOMPLETE_VIEW_TARGETS_OVR: return 'baseViewIndex mismatch';\n default:\n return `${status}`;\n }\n}\n\n/**\n * Attachment resize is expected to be a noop if size is same\n *\nprotected override resizeAttachments(width: number, height: number): this {\n // for default framebuffer, just update the stored size\n if (this.handle === null) {\n // assert(width === undefined && height === undefined);\n this.width = this.gl.drawingBufferWidth;\n this.height = this.gl.drawingBufferHeight;\n return this;\n }\n\n if (width === undefined) {\n width = this.gl.drawingBufferWidth;\n }\n if (height === undefined) {\n height = this.gl.drawingBufferHeight;\n }\n\n // TODO Not clear that this is better than default destroy/create implementation\n\n for (const colorAttachment of this.colorAttachments) {\n colorAttachment.texture.clone({width, height});\n }\n if (this.depthStencilAttachment) {\n this.depthStencilAttachment.texture.resize({width, height});\n }\n return this;\n}\n*/\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {CanvasContextProps} from '@luma.gl/core';\nimport {CanvasContext} from '@luma.gl/core';\nimport {WebGLDevice} from './webgl-device';\nimport {WEBGLFramebuffer} from './resources/webgl-framebuffer';\n\n/**\n * A WebGL Canvas Context which manages the canvas and handles drawing buffer resizing etc\n */\nexport class WebGLCanvasContext extends CanvasContext {\n readonly device: WebGLDevice;\n readonly handle: unknown = null;\n\n private _framebuffer: WEBGLFramebuffer | null = null;\n\n get [Symbol.toStringTag](): string {\n return 'WebGLCanvasContext';\n }\n\n constructor(device: WebGLDevice, props: CanvasContextProps) {\n // Note: Base class creates / looks up the canvas (unless under Node.js)\n super(props);\n this.device = device;\n\n // Base class constructor cannot access derived methods/fields, so we need to call these functions in the subclass constructor\n this._setAutoCreatedCanvasId(`${this.device.id}-canvas`);\n this._configureDevice();\n }\n\n // IMPLEMENTATION OF ABSTRACT METHODS\n\n _configureDevice(): void {\n const shouldResize =\n this.drawingBufferWidth !== this._framebuffer?.width ||\n this.drawingBufferHeight !== this._framebuffer?.height;\n if (shouldResize) {\n this._framebuffer?.resize([this.drawingBufferWidth, this.drawingBufferHeight]);\n }\n }\n\n _getCurrentFramebuffer(): WEBGLFramebuffer {\n this._framebuffer ||= new WEBGLFramebuffer(this.device, {\n id: 'canvas-context-framebuffer',\n handle: null, // Setting handle to null returns a reference to the default WebGL framebuffer\n width: this.drawingBufferWidth,\n height: this.drawingBufferHeight\n });\n return this._framebuffer;\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {PresentationContextProps, TextureFormatDepthStencil, Framebuffer} from '@luma.gl/core';\nimport {PresentationContext} from '@luma.gl/core';\nimport type {WebGLDevice} from './webgl-device';\n\ntype PresentationCanvasRenderingContext2D =\n | CanvasRenderingContext2D\n | OffscreenCanvasRenderingContext2D;\n\n/**\n * Tracks a non-WebGL destination canvas while rendering into the device's default canvas context.\n */\nexport class WebGLPresentationContext extends PresentationContext {\n readonly device: WebGLDevice;\n readonly handle = null;\n readonly context2d: PresentationCanvasRenderingContext2D;\n\n get [Symbol.toStringTag](): string {\n return 'WebGLPresentationContext';\n }\n\n constructor(device: WebGLDevice, props: PresentationContextProps = {}) {\n super(props);\n this.device = device;\n const contextLabel = `${this[Symbol.toStringTag]}(${this.id})`;\n\n const defaultCanvasContext = this.device.getDefaultCanvasContext();\n if (!defaultCanvasContext.offscreenCanvas) {\n throw new Error(\n `${contextLabel}: WebGL PresentationContext requires the default CanvasContext canvas to be an OffscreenCanvas`\n );\n }\n\n const context2d = this.canvas.getContext('2d');\n if (!context2d) {\n throw new Error(`${contextLabel}: Failed to create 2d presentation context`);\n }\n this.context2d = context2d;\n\n this._setAutoCreatedCanvasId(`${this.device.id}-presentation-canvas`);\n this._configureDevice();\n this._startObservers();\n }\n\n present(): void {\n this._resizeDrawingBufferIfNeeded();\n this.device.submit();\n\n const defaultCanvasContext = this.device.getDefaultCanvasContext();\n const [sourceWidth, sourceHeight] = defaultCanvasContext.getDrawingBufferSize();\n\n // Responsive layouts can transiently collapse presentation canvases to 0x0 during reflow.\n // In that case WebGL has nothing meaningful to present, and drawImage() would throw when the\n // offscreen source canvas has zero width or height.\n if (\n this.drawingBufferWidth === 0 ||\n this.drawingBufferHeight === 0 ||\n sourceWidth === 0 ||\n sourceHeight === 0 ||\n defaultCanvasContext.canvas.width === 0 ||\n defaultCanvasContext.canvas.height === 0\n ) {\n return;\n }\n\n if (\n sourceWidth !== this.drawingBufferWidth ||\n sourceHeight !== this.drawingBufferHeight ||\n defaultCanvasContext.canvas.width !== this.drawingBufferWidth ||\n defaultCanvasContext.canvas.height !== this.drawingBufferHeight\n ) {\n throw new Error(\n `${this[Symbol.toStringTag]}(${this.id}): Default canvas context size ${sourceWidth}x${sourceHeight} does not match presentation size ${this.drawingBufferWidth}x${this.drawingBufferHeight}`\n );\n }\n\n this.context2d.clearRect(0, 0, this.drawingBufferWidth, this.drawingBufferHeight);\n this.context2d.drawImage(defaultCanvasContext.canvas, 0, 0);\n }\n\n protected override _configureDevice(): void {}\n\n protected override _getCurrentFramebuffer(options?: {\n depthStencilFormat?: TextureFormatDepthStencil | false;\n }): Framebuffer {\n const defaultCanvasContext = this.device.getDefaultCanvasContext();\n defaultCanvasContext.setDrawingBufferSize(this.drawingBufferWidth, this.drawingBufferHeight);\n return defaultCanvasContext.getCurrentFramebuffer(options);\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nconst uidCounters: Record = {};\n\n/**\n * Returns a UID.\n * @param id= - Identifier base name\n * @return uid\n **/\nexport function uid(id: string = 'id'): string {\n uidCounters[id] = uidCounters[id] || 1;\n const count = uidCounters[id]++;\n return `${id}-${count}`;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {BufferMapCallback, BufferProps} from '@luma.gl/core';\nimport {Buffer} from '@luma.gl/core';\nimport {GL} from '@luma.gl/webgl/constants';\nimport {WebGLDevice} from '../webgl-device';\n\n/** WebGL Buffer interface */\nexport class WEBGLBuffer extends Buffer {\n readonly device: WebGLDevice;\n readonly gl: WebGL2RenderingContext;\n readonly handle: WebGLBuffer;\n\n /** Target in OpenGL defines the type of buffer */\n readonly glTarget: GL.ARRAY_BUFFER | GL.ELEMENT_ARRAY_BUFFER | GL.UNIFORM_BUFFER;\n /** Usage is a hint on how frequently the buffer will be updates */\n readonly glUsage: GL.STATIC_DRAW | GL.DYNAMIC_DRAW;\n /** Index type is needed when issuing draw calls, so we pre-compute it */\n readonly glIndexType: GL.UNSIGNED_SHORT | GL.UNSIGNED_INT = GL.UNSIGNED_SHORT;\n\n /** Number of bytes allocated on the GPU for this buffer */\n byteLength: number = 0;\n /** Number of bytes used */\n bytesUsed: number = 0;\n\n constructor(device: WebGLDevice, props: BufferProps = {}) {\n super(device, props);\n\n this.device = device;\n this.gl = this.device.gl;\n\n const handle = typeof props === 'object' ? props.handle : undefined;\n this.handle = handle || this.gl.createBuffer();\n device._setWebGLDebugMetadata(this.handle, this, {\n spector: {...this.props, data: typeof this.props.data}\n });\n\n // - In WebGL1, need to make sure we use GL.ELEMENT_ARRAY_BUFFER when initializing element buffers\n // otherwise buffer type will lock to generic (non-element) buffer\n // - In WebGL2, we can use GL.COPY_READ_BUFFER which avoids locking the type here\n this.glTarget = getWebGLTarget(this.props.usage);\n this.glUsage = getWebGLUsage(this.props.usage);\n // Note: uint8 indices are converted to uint16 during device normalization for WebGPU compatibility\n this.glIndexType = this.props.indexType === 'uint32' ? GL.UNSIGNED_INT : GL.UNSIGNED_SHORT;\n\n // Set data: (re)initializes the buffer\n if (props.data) {\n this._initWithData(props.data, props.byteOffset, props.byteLength);\n } else {\n this._initWithByteLength(props.byteLength || 0);\n }\n }\n\n override destroy(): void {\n if (!this.destroyed && this.handle) {\n this.removeStats();\n if (!this.props.handle) {\n this.trackDeallocatedMemory();\n this.gl.deleteBuffer(this.handle);\n } else {\n this.trackDeallocatedReferencedMemory('Buffer');\n }\n this.destroyed = true;\n // @ts-expect-error\n this.handle = null;\n }\n }\n\n /** Allocate a new buffer and initialize to contents of typed array */\n _initWithData(\n data: ArrayBuffer | ArrayBufferView,\n byteOffset: number = 0,\n byteLength: number = data.byteLength + byteOffset\n ): void {\n // const glTarget = this.device.isWebGL2 ? GL.COPY_WRITE_BUFFER : this.glTarget;\n const glTarget = this.glTarget;\n this.gl.bindBuffer(glTarget, this.handle);\n this.gl.bufferData(glTarget, byteLength, this.glUsage);\n this.gl.bufferSubData(glTarget, byteOffset, data);\n this.gl.bindBuffer(glTarget, null);\n\n this.bytesUsed = byteLength;\n this.byteLength = byteLength;\n\n this._setDebugData(data, byteOffset, byteLength);\n if (!this.props.handle) {\n this.trackAllocatedMemory(byteLength);\n } else {\n this.trackReferencedMemory(byteLength, 'Buffer');\n }\n }\n\n // Allocate a GPU buffer of specified size.\n _initWithByteLength(byteLength: number): this {\n // assert(byteLength >= 0);\n\n // Workaround needed for Safari (#291):\n // gl.bufferData with size equal to 0 crashes. Instead create zero sized array.\n let data = byteLength;\n if (byteLength === 0) {\n // @ts-expect-error\n data = new Float32Array(0);\n }\n\n // const glTarget = this.device.isWebGL2 ? GL.COPY_WRITE_BUFFER : this.glTarget;\n const glTarget = this.glTarget;\n\n this.gl.bindBuffer(glTarget, this.handle);\n this.gl.bufferData(glTarget, data, this.glUsage);\n this.gl.bindBuffer(glTarget, null);\n\n this.bytesUsed = byteLength;\n this.byteLength = byteLength;\n\n this._setDebugData(null, 0, byteLength);\n if (!this.props.handle) {\n this.trackAllocatedMemory(byteLength);\n } else {\n this.trackReferencedMemory(byteLength, 'Buffer');\n }\n\n return this;\n }\n\n write(data: ArrayBufferLike | ArrayBufferView, byteOffset: number = 0): void {\n const dataView = ArrayBuffer.isView(data) ? data : new Uint8Array(data);\n const srcOffset = 0;\n const byteLength = undefined; // data.byteLength;\n\n // Create the buffer - binding it here for the first time locks the type\n // In WebGL2, use GL.COPY_WRITE_BUFFER to avoid locking the type\n const glTarget = GL.COPY_WRITE_BUFFER;\n this.gl.bindBuffer(glTarget, this.handle);\n // WebGL2: subData supports additional srcOffset and length parameters\n if (srcOffset !== 0 || byteLength !== undefined) {\n this.gl.bufferSubData(glTarget, byteOffset, dataView, srcOffset, byteLength);\n } else {\n this.gl.bufferSubData(glTarget, byteOffset, dataView);\n }\n this.gl.bindBuffer(glTarget, null);\n\n this._setDebugData(data, byteOffset, data.byteLength);\n }\n\n async mapAndWriteAsync(\n callback: BufferMapCallback,\n byteOffset: number = 0,\n byteLength: number = this.byteLength - byteOffset\n ): Promise {\n const arrayBuffer = new ArrayBuffer(byteLength);\n // eslint-disable-next-line @typescript-eslint/await-thenable\n await callback(arrayBuffer, 'copied');\n this.write(arrayBuffer, byteOffset);\n }\n\n async readAsync(byteOffset = 0, byteLength?: number): Promise> {\n return this.readSyncWebGL(byteOffset, byteLength);\n }\n\n async mapAndReadAsync(\n callback: BufferMapCallback,\n byteOffset = 0,\n byteLength?: number\n ): Promise {\n const data = await this.readAsync(byteOffset, byteLength);\n // eslint-disable-next-line @typescript-eslint/await-thenable\n return await callback(data.buffer, 'copied');\n }\n\n readSyncWebGL(byteOffset = 0, byteLength?: number): Uint8Array {\n byteLength = byteLength ?? this.byteLength - byteOffset;\n const data = new Uint8Array(byteLength);\n const dstOffset = 0;\n\n // Use GL.COPY_READ_BUFFER to avoid disturbing other targets and locking type\n this.gl.bindBuffer(GL.COPY_READ_BUFFER, this.handle);\n this.gl.getBufferSubData(GL.COPY_READ_BUFFER, byteOffset, data, dstOffset, byteLength);\n this.gl.bindBuffer(GL.COPY_READ_BUFFER, null);\n\n // Update local `data` if offsets are 0\n this._setDebugData(data, byteOffset, byteLength);\n\n return data;\n }\n}\n\n/**\n * Returns a WebGL buffer target\n *\n * @param usage\n * static MAP_READ = 0x01;\n * static MAP_WRITE = 0x02;\n * static COPY_SRC = 0x0004;\n * static COPY_DST = 0x0008;\n * static INDEX = 0x0010;\n * static VERTEX = 0x0020;\n * static UNIFORM = 0x0040;\n * static STORAGE = 0x0080;\n * static INDIRECT = 0x0100;\n * static QUERY_RESOLVE = 0x0200;\n *\n * @returns WebGL buffer targe\n *\n * Buffer bind points in WebGL2\n * gl.COPY_READ_BUFFER: Buffer for copying from one buffer object to another.\n * gl.COPY_WRITE_BUFFER: Buffer for copying from one buffer object to another.\n * gl.TRANSFORM_FEEDBACK_BUFFER: Buffer for transform feedback operations.\n * gl.PIXEL_PACK_BUFFER: Buffer used for pixel transfer operations.\n * gl.PIXEL_UNPACK_BUFFER: Buffer used for pixel transfer operations.\n */\nfunction getWebGLTarget(\n usage: number\n): GL.ARRAY_BUFFER | GL.ELEMENT_ARRAY_BUFFER | GL.UNIFORM_BUFFER {\n if (usage & Buffer.INDEX) {\n return GL.ELEMENT_ARRAY_BUFFER;\n }\n if (usage & Buffer.VERTEX) {\n return GL.ARRAY_BUFFER;\n }\n if (usage & Buffer.UNIFORM) {\n return GL.UNIFORM_BUFFER;\n }\n\n // Binding a buffer for the first time locks the type\n // In WebGL2, we can use GL.COPY_WRITE_BUFFER to avoid locking the type\n return GL.ARRAY_BUFFER;\n}\n\n/** @todo usage is not passed correctly */\nfunction getWebGLUsage(usage: number): GL.STATIC_DRAW | GL.DYNAMIC_DRAW {\n if (usage & Buffer.INDEX) {\n return GL.STATIC_DRAW;\n }\n if (usage & Buffer.VERTEX) {\n return GL.STATIC_DRAW;\n }\n if (usage & Buffer.UNIFORM) {\n return GL.DYNAMIC_DRAW;\n }\n return GL.STATIC_DRAW;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {type CompilerMessage} from '@luma.gl/core';\n\n/**\n * Parse a WebGL-format GLSL compilation log into an array of WebGPU style message records.\n * This follows documented WebGL conventions for compilation logs.\n * Based on https://github.com/wwwtyro/gl-format-compiler-error (public domain)\n */\nexport function parseShaderCompilerLog(errLog: string): readonly CompilerMessage[] {\n // Parse the error - note: browser and driver dependent\n const lines = errLog.split(/\\r?\\n/);\n\n const messages: CompilerMessage[] = [];\n\n for (const line of lines) {\n if (line.length <= 1) {\n continue; // eslint-disable-line no-continue\n }\n\n const lineWithTrimmedWhitespace = line.trim();\n\n const segments: string[] = line.split(':');\n const trimmedMessageType = segments[0]?.trim();\n\n // Check for messages with no line information `ERROR: unsupported shader version`\n if (segments.length === 2) {\n const [messageType, message] = segments;\n if (!messageType || !message) {\n messages.push({\n message: lineWithTrimmedWhitespace,\n type: getMessageType(trimmedMessageType || 'info'),\n lineNum: 0,\n linePos: 0\n });\n continue; // eslint-disable-line no-continue\n }\n messages.push({\n message: message.trim(),\n type: getMessageType(messageType),\n lineNum: 0,\n linePos: 0\n });\n\n continue; // eslint-disable-line no-continue\n }\n\n const [messageType, linePosition, lineNumber, ...rest] = segments;\n if (!messageType || !linePosition || !lineNumber) {\n messages.push({\n message: segments.slice(1).join(':').trim() || lineWithTrimmedWhitespace,\n type: getMessageType(trimmedMessageType || 'info'),\n lineNum: 0,\n linePos: 0\n });\n continue; // eslint-disable-line no-continue\n }\n\n let lineNum = parseInt(lineNumber, 10);\n if (Number.isNaN(lineNum)) {\n lineNum = 0;\n }\n\n let linePos = parseInt(linePosition, 10);\n if (Number.isNaN(linePos)) {\n linePos = 0;\n }\n\n messages.push({\n message: rest.join(':').trim(),\n type: getMessageType(messageType),\n lineNum,\n linePos // TODO\n });\n }\n\n return messages;\n}\n\n/** Ensure supported type */\nfunction getMessageType(messageType: string): 'warning' | 'error' | 'info' {\n const MESSAGE_TYPES = ['warning', 'error', 'info'];\n const lowerCaseType = messageType.toLowerCase();\n return (MESSAGE_TYPES.includes(lowerCaseType) ? lowerCaseType : 'info') as\n | 'warning'\n | 'error'\n | 'info';\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Shader, ShaderProps, CompilerMessage, log} from '@luma.gl/core';\nimport {GL} from '@luma.gl/webgl/constants';\nimport {parseShaderCompilerLog} from '../helpers/parse-shader-compiler-log';\nimport {WebGLDevice} from '../webgl-device';\n\n/**\n * An immutable compiled shader program that execute portions of the GPU Pipeline\n */\nexport class WEBGLShader extends Shader {\n readonly device: WebGLDevice;\n readonly handle: WebGLShader;\n\n constructor(device: WebGLDevice, props: ShaderProps) {\n super(device, props);\n this.device = device;\n switch (this.props.stage) {\n case 'vertex':\n this.handle = this.props.handle || this.device.gl.createShader(GL.VERTEX_SHADER);\n break;\n case 'fragment':\n this.handle = this.props.handle || this.device.gl.createShader(GL.FRAGMENT_SHADER);\n break;\n default:\n throw new Error(this.props.stage);\n }\n\n // default framebuffer handle is null, so we can't set spector metadata...\n device._setWebGLDebugMetadata(this.handle, this, {spector: this.props});\n\n const compilationStatus = this._compile(this.source);\n if (compilationStatus && typeof compilationStatus.catch === 'function') {\n compilationStatus.catch(() => {\n // Ensure any async compile status errors are consumed.\n this.compilationStatus = 'error';\n });\n }\n }\n\n override destroy(): void {\n if (this.handle) {\n this.removeStats();\n this.device.gl.deleteShader(this.handle);\n this.destroyed = true;\n // @ts-expect-error\n this.handle.destroyed = true;\n // this.handle = null;\n }\n }\n\n get asyncCompilationStatus(): Promise<'pending' | 'success' | 'error'> {\n return this._waitForCompilationComplete().then(() => {\n this._getCompilationStatus();\n return this.compilationStatus;\n });\n }\n\n override async getCompilationInfo(): Promise {\n await this._waitForCompilationComplete();\n return this.getCompilationInfoSync();\n }\n\n override getCompilationInfoSync(): readonly CompilerMessage[] {\n const shaderLog = this.device.gl.getShaderInfoLog(this.handle);\n return shaderLog ? parseShaderCompilerLog(shaderLog) : [];\n }\n\n override getTranslatedSource(): string | null {\n const extensions = this.device.getExtension('WEBGL_debug_shaders');\n const ext = extensions.WEBGL_debug_shaders;\n return ext?.getTranslatedShaderSource(this.handle) || null;\n }\n\n // PRIVATE METHODS\n\n /** Compile a shader and get compilation status */\n protected _compile(source: string): void | Promise {\n source = source.startsWith('#version ') ? source : `#version 300 es\\n${source}`;\n\n const {gl} = this.device;\n gl.shaderSource(this.handle, source);\n gl.compileShader(this.handle);\n\n // For performance reasons, avoid checking shader compilation errors on production\n if (!this.device.props.debug) {\n this.compilationStatus = 'pending';\n return;\n }\n\n // Sync case - slower, but advantage is that it throws in the constructor, making break on error more useful\n if (!this.device.features.has('compilation-status-async-webgl')) {\n this._getCompilationStatus();\n // The `Shader` base class will determine if debug window should be opened based on this.compilationStatus\n this.debugShader();\n if (this.compilationStatus === 'error') {\n throw new Error(`GLSL compilation errors in ${this.props.stage} shader ${this.props.id}`);\n }\n return;\n }\n\n // async case\n log.once(1, 'Shader compilation is asynchronous')();\n return this._waitForCompilationComplete().then(() => {\n log.info(2, `Shader ${this.id} - async compilation complete: ${this.compilationStatus}`)();\n this._getCompilationStatus();\n\n // The `Shader` base class will determine if debug window should be opened based on this.compilationStatus\n this.debugShader();\n });\n }\n\n /** Use KHR_parallel_shader_compile extension if available */\n protected async _waitForCompilationComplete(): Promise {\n const waitMs = async (ms: number) => await new Promise(resolve => setTimeout(resolve, ms));\n const DELAY_MS = 10; // Shader compilation is typically quite fast (with some exceptions)\n\n // If status polling is not available, we can't wait for completion. Just wait a little to minimize blocking\n if (!this.device.features.has('compilation-status-async-webgl')) {\n await waitMs(DELAY_MS);\n return;\n }\n\n const {gl} = this.device;\n for (;;) {\n const complete = gl.getShaderParameter(this.handle, GL.COMPLETION_STATUS_KHR);\n if (complete) {\n return;\n }\n await waitMs(DELAY_MS);\n }\n }\n\n /**\n * Get the shader compilation status\n * TODO - Load log even when no error reported, to catch warnings?\n * https://gamedev.stackexchange.com/questions/30429/how-to-detect-glsl-warnings\n */\n protected _getCompilationStatus() {\n this.compilationStatus = this.device.gl.getShaderParameter(this.handle, GL.COMPILE_STATUS)\n ? 'success'\n : 'error';\n }\n}\n\n// TODO - Original code from luma.gl v8 - keep until new debug functionality has matured\n// if (!compilationSuccess) {\n// const parsedLog = shaderLog ? parseShaderCompilerLog(shaderLog) : [];\n// const messages = parsedLog.filter(message => message.type === 'error');\n// const formattedLog = formatCompilerLog(messages, source, {showSourceCode: 'all', html: true});\n// const shaderDescription = `${this.stage} shader ${shaderName}`;\n// log.error(`GLSL compilation errors in ${shaderDescription}\\n${formattedLog}`)();\n// displayShaderLog(parsedLog, source, shaderName);\n// }\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {CompareFunction, StencilOperation, BlendOperation, BlendFactor} from '@luma.gl/core';\nimport {Device, log, Parameters, PolygonMode, ProvokingVertex} from '@luma.gl/core';\nimport {GL} from '@luma.gl/webgl/constants';\nimport type {\n GLBlendEquation,\n GLBlendFunction,\n GLFunction,\n GLParameters,\n GLPolygonMode,\n GLProvokingVertex,\n GLStencilOp\n} from '@luma.gl/webgl/constants';\nimport {setGLParameters} from '../../context/parameters/unified-parameter-api';\nimport {WebGLDevice} from '../webgl-device';\n\n/* eslint-disable no-unused-expressions */ // For expression ? gl.enable() : gl.disable()\n\n/**\n * Execute a function with a set of temporary WebGL parameter overrides\n * - Saves current \"global\" WebGL context settings\n * - Sets the supplies WebGL context parameters,\n * - Executes supplied function\n * - Restores parameters\n * - Returns the return value of the supplied function\n */\nexport function withDeviceAndGLParameters(\n device: Device,\n parameters: Parameters,\n glParameters: GLParameters,\n func: (_?: Device) => T\n): T {\n if (isObjectEmpty(parameters)) {\n // Avoid setting state if no parameters provided. Just call and return\n return func(device);\n }\n\n // Wrap in a try-catch to ensure that parameters are restored on exceptions\n const webglDevice = device as WebGLDevice;\n webglDevice.pushState();\n try {\n setDeviceParameters(device, parameters);\n setGLParameters(webglDevice.gl, glParameters);\n return func(device);\n } finally {\n webglDevice.popState();\n }\n}\n\n/**\n * Execute a function with a set of temporary WebGL parameter overrides\n * - Saves current \"global\" WebGL context settings\n * - Sets the supplies WebGL context parameters,\n * - Executes supplied function\n * - Restores parameters\n * - Returns the return value of the supplied function\n * @deprecated use withDeviceParameters instead\n */\nexport function withGLParameters(\n device: Device,\n parameters: GLParameters,\n func: (_?: Device) => T\n): T {\n if (isObjectEmpty(parameters)) {\n // Avoid setting state if no parameters provided. Just call and return\n return func(device);\n }\n\n // Wrap in a try-catch to ensure that parameters are restored on exceptions\n const webglDevice = device as WebGLDevice;\n webglDevice.pushState();\n try {\n setGLParameters(webglDevice.gl, parameters);\n return func(device);\n } finally {\n webglDevice.popState();\n }\n}\n\n/**\n * Execute a function with a set of temporary WebGL parameter overrides\n * - Saves current \"global\" WebGL context settings\n * - Sets the supplies WebGL context parameters,\n * - Executes supplied function\n * - Restores parameters\n * - Returns the return value of the supplied function\n */\nexport function withDeviceParameters(\n device: Device,\n parameters: Parameters,\n func: (_?: Device) => T\n): T {\n if (isObjectEmpty(parameters)) {\n // Avoid setting state if no parameters provided. Just call and return\n return func(device);\n }\n\n // Wrap in a try-catch to ensure that parameters are restored on exceptions'\n const webglDevice = device as WebGLDevice;\n webglDevice.pushState();\n try {\n setDeviceParameters(device, parameters);\n return func(device);\n } finally {\n webglDevice.popState();\n }\n}\n\n/** Set WebGPU Style Parameters */\nexport function setDeviceParameters(device: Device, parameters: Parameters) {\n const webglDevice = device as WebGLDevice;\n const {gl} = webglDevice;\n\n // RASTERIZATION SETTINGS\n if (parameters.cullMode) {\n switch (parameters.cullMode) {\n case 'none':\n gl.disable(GL.CULL_FACE);\n break;\n case 'front':\n gl.enable(GL.CULL_FACE);\n gl.cullFace(GL.FRONT);\n break;\n case 'back':\n gl.enable(GL.CULL_FACE);\n gl.cullFace(GL.BACK);\n break;\n }\n }\n\n if (parameters.frontFace) {\n gl.frontFace(\n map('frontFace', parameters.frontFace, {\n ccw: GL.CCW,\n cw: GL.CW\n })\n );\n }\n\n if (parameters.unclippedDepth) {\n if (device.features.has('depth-clip-control')) {\n // EXT_depth_clamp\n gl.enable(GL.DEPTH_CLAMP_EXT);\n }\n }\n\n if (parameters.depthBias !== undefined) {\n gl.enable(GL.POLYGON_OFFSET_FILL);\n gl.polygonOffset(parameters.depthBias, parameters.depthBiasSlopeScale || 0);\n }\n\n // depthBiasSlopeScale: {\n // // Handled by depthBias\n // },\n\n // WEBGL EXTENSIONS\n\n if (parameters.provokingVertex) {\n if (device.features.has('provoking-vertex-webgl')) {\n const extensions = webglDevice.getExtension('WEBGL_provoking_vertex');\n const ext = extensions.WEBGL_provoking_vertex;\n\n const vertex = map(\n 'provokingVertex',\n parameters.provokingVertex,\n {\n first: GL.FIRST_VERTEX_CONVENTION_WEBGL,\n last: GL.LAST_VERTEX_CONVENTION_WEBGL\n }\n );\n ext?.provokingVertexWEBGL(vertex);\n }\n }\n\n if (parameters.polygonMode || parameters.polygonOffsetLine) {\n if (device.features.has('polygon-mode-webgl')) {\n if (parameters.polygonMode) {\n const extensions = webglDevice.getExtension('WEBGL_polygon_mode');\n const ext = extensions.WEBGL_polygon_mode;\n const mode = map('polygonMode', parameters.polygonMode, {\n fill: GL.FILL_WEBGL,\n line: GL.LINE_WEBGL\n });\n ext?.polygonModeWEBGL(GL.FRONT, mode);\n ext?.polygonModeWEBGL(GL.BACK, mode);\n }\n\n if (parameters.polygonOffsetLine) {\n gl.enable(GL.POLYGON_OFFSET_LINE_WEBGL);\n }\n }\n }\n\n if (device.features.has('shader-clip-cull-distance-webgl')) {\n if (parameters.clipDistance0) {\n gl.enable(GL.CLIP_DISTANCE0_WEBGL);\n }\n if (parameters.clipDistance1) {\n gl.enable(GL.CLIP_DISTANCE1_WEBGL);\n }\n if (parameters.clipDistance2) {\n gl.enable(GL.CLIP_DISTANCE2_WEBGL);\n }\n if (parameters.clipDistance3) {\n gl.enable(GL.CLIP_DISTANCE3_WEBGL);\n }\n if (parameters.clipDistance4) {\n gl.enable(GL.CLIP_DISTANCE4_WEBGL);\n }\n if (parameters.clipDistance5) {\n gl.enable(GL.CLIP_DISTANCE5_WEBGL);\n }\n if (parameters.clipDistance6) {\n gl.enable(GL.CLIP_DISTANCE6_WEBGL);\n }\n if (parameters.clipDistance7) {\n gl.enable(GL.CLIP_DISTANCE7_WEBGL);\n }\n }\n\n // DEPTH STENCIL\n\n if (parameters.depthWriteEnabled !== undefined) {\n gl.depthMask(mapBoolean('depthWriteEnabled', parameters.depthWriteEnabled));\n }\n\n if (parameters.depthCompare) {\n parameters.depthCompare !== 'always' ? gl.enable(GL.DEPTH_TEST) : gl.disable(GL.DEPTH_TEST);\n gl.depthFunc(convertCompareFunction('depthCompare', parameters.depthCompare));\n }\n\n if (parameters.clearDepth !== undefined) {\n gl.clearDepth(parameters.clearDepth);\n }\n\n if (parameters.stencilWriteMask) {\n const mask = parameters.stencilWriteMask;\n gl.stencilMaskSeparate(GL.FRONT, mask);\n gl.stencilMaskSeparate(GL.BACK, mask);\n }\n\n if (parameters.stencilReadMask) {\n // stencilReadMask is handle inside stencil***Compare.\n log.warn('stencilReadMask not supported under WebGL');\n }\n\n if (parameters.stencilCompare) {\n const mask = parameters.stencilReadMask || 0xffffffff;\n const glValue = convertCompareFunction('depthCompare', parameters.stencilCompare);\n // TODO - ensure back doesn't overwrite\n parameters.stencilCompare !== 'always'\n ? gl.enable(GL.STENCIL_TEST)\n : gl.disable(GL.STENCIL_TEST);\n gl.stencilFuncSeparate(GL.FRONT, glValue, 0, mask);\n gl.stencilFuncSeparate(GL.BACK, glValue, 0, mask);\n }\n\n if (\n parameters.stencilPassOperation &&\n parameters.stencilFailOperation &&\n parameters.stencilDepthFailOperation\n ) {\n const dppass = convertStencilOperation('stencilPassOperation', parameters.stencilPassOperation);\n const sfail = convertStencilOperation('stencilFailOperation', parameters.stencilFailOperation);\n const dpfail = convertStencilOperation(\n 'stencilDepthFailOperation',\n parameters.stencilDepthFailOperation\n );\n gl.stencilOpSeparate(GL.FRONT, sfail, dpfail, dppass);\n gl.stencilOpSeparate(GL.BACK, sfail, dpfail, dppass);\n }\n\n // stencilDepthFailOperation() {\n // // handled by stencilPassOperation\n // },\n\n // stencilFailOperation() {\n // // handled by stencilPassOperation\n // },\n\n // COLOR STATE\n switch (parameters.blend) {\n case true:\n gl.enable(GL.BLEND);\n break;\n case false:\n gl.disable(GL.BLEND);\n break;\n default:\n // leave WebGL blend state unchanged if `parameters.blend` is not set\n }\n\n if (parameters.blendColorOperation || parameters.blendAlphaOperation) {\n const colorEquation = convertBlendOperationToEquation(\n 'blendColorOperation',\n parameters.blendColorOperation || 'add'\n );\n const alphaEquation = convertBlendOperationToEquation(\n 'blendAlphaOperation',\n parameters.blendAlphaOperation || 'add'\n );\n gl.blendEquationSeparate(colorEquation, alphaEquation);\n\n const colorSrcFactor = convertBlendFactorToFunction(\n 'blendColorSrcFactor',\n parameters.blendColorSrcFactor || 'one'\n );\n const colorDstFactor = convertBlendFactorToFunction(\n 'blendColorDstFactor',\n parameters.blendColorDstFactor || 'zero'\n );\n const alphaSrcFactor = convertBlendFactorToFunction(\n 'blendAlphaSrcFactor',\n parameters.blendAlphaSrcFactor || 'one'\n );\n const alphaDstFactor = convertBlendFactorToFunction(\n 'blendAlphaDstFactor',\n parameters.blendAlphaDstFactor || 'zero'\n );\n gl.blendFuncSeparate(colorSrcFactor, colorDstFactor, alphaSrcFactor, alphaDstFactor);\n }\n}\n\n/*\n rasterizationState: {\n cullMode: \"back\",\n },\n\n depthStencilState: {\n depthWriteEnabled: true,\n depthCompare: \"less\",\n format: \"depth24plus-stencil8\",\n },\n\n colorStates: [\n {\n format: \"bgra8unorm\",\n // colorBlend.srcFactor = wgpu::BlendFactor::SrcAlpha;\n // colorBlend.dstFactor = wgpu::BlendFactor::OneMinusSrcAlpha;\n // alphaBlend.srcFactor = wgpu::BlendFactor::SrcAlpha;\n // alphaBlend.dstFactor = wgpu::BlendFactor::OneMinusSrcAlpha;\n },\n ],\n });\n*/\n\nexport function convertCompareFunction(parameter: string, value: CompareFunction): GLFunction {\n return map(parameter, value, {\n never: GL.NEVER,\n less: GL.LESS,\n equal: GL.EQUAL,\n 'less-equal': GL.LEQUAL,\n greater: GL.GREATER,\n 'not-equal': GL.NOTEQUAL,\n 'greater-equal': GL.GEQUAL,\n always: GL.ALWAYS\n });\n}\n\nexport function convertToCompareFunction(parameter: string, value: GLFunction): CompareFunction {\n return map(parameter, value, {\n [GL.NEVER]: 'never',\n [GL.LESS]: 'less',\n [GL.EQUAL]: 'equal',\n [GL.LEQUAL]: 'less-equal',\n [GL.GREATER]: 'greater',\n [GL.NOTEQUAL]: 'not-equal',\n [GL.GEQUAL]: 'greater-equal',\n [GL.ALWAYS]: 'always'\n });\n}\n\nfunction convertStencilOperation(parameter: string, value: StencilOperation): GL {\n return map(parameter, value, {\n keep: GL.KEEP,\n zero: GL.ZERO,\n replace: GL.REPLACE,\n invert: GL.INVERT,\n 'increment-clamp': GL.INCR,\n 'decrement-clamp': GL.DECR,\n 'increment-wrap': GL.INCR_WRAP,\n 'decrement-wrap': GL.DECR_WRAP\n });\n}\n\nfunction convertBlendOperationToEquation(\n parameter: string,\n value: BlendOperation\n): GLBlendEquation {\n return map(parameter, value, {\n add: GL.FUNC_ADD,\n subtract: GL.FUNC_SUBTRACT,\n 'reverse-subtract': GL.FUNC_REVERSE_SUBTRACT,\n min: GL.MIN,\n max: GL.MAX\n });\n}\n\nfunction convertBlendFactorToFunction(\n parameter: string,\n value: BlendFactor,\n type: 'color' | 'alpha' = 'color'\n): GLBlendFunction {\n return map(parameter, value, {\n one: GL.ONE,\n zero: GL.ZERO,\n src: GL.SRC_COLOR,\n 'one-minus-src': GL.ONE_MINUS_SRC_COLOR,\n dst: GL.DST_COLOR,\n 'one-minus-dst': GL.ONE_MINUS_DST_COLOR,\n 'src-alpha': GL.SRC_ALPHA,\n 'one-minus-src-alpha': GL.ONE_MINUS_SRC_ALPHA,\n 'dst-alpha': GL.DST_ALPHA,\n 'one-minus-dst-alpha': GL.ONE_MINUS_DST_ALPHA,\n 'src-alpha-saturated': GL.SRC_ALPHA_SATURATE,\n constant: type === 'color' ? GL.CONSTANT_COLOR : GL.CONSTANT_ALPHA,\n 'one-minus-constant':\n type === 'color' ? GL.ONE_MINUS_CONSTANT_COLOR : GL.ONE_MINUS_CONSTANT_ALPHA,\n // 'constant-alpha': GL.CONSTANT_ALPHA,\n // 'one-minus-constant-alpha': GL.ONE_MINUS_CONSTANT_ALPHA,\n // TODO not supported in WebGL2\n src1: GL.SRC_COLOR,\n 'one-minus-src1': GL.ONE_MINUS_SRC_COLOR,\n 'src1-alpha': GL.SRC_ALPHA,\n 'one-minus-src1-alpha': GL.ONE_MINUS_SRC_ALPHA\n });\n}\n\nfunction message(parameter: string, value: any): string {\n return `Illegal parameter ${value} for ${parameter}`;\n}\n\nfunction map(parameter: string, value: K, valueMap: Record): V {\n if (!(value in valueMap)) {\n throw new Error(message(parameter, value));\n }\n return valueMap[value];\n}\n\nfunction mapBoolean(parameter: string, value: boolean): boolean {\n return value;\n}\n\n/** Returns true if given object is empty, false otherwise. */\nfunction isObjectEmpty(obj: object): boolean {\n let isEmpty = true;\n // @ts-ignore key is unused\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n for (const key in obj) {\n isEmpty = false;\n break;\n }\n return isEmpty;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// SAMPLER FILTERS\nimport {SamplerProps} from '@luma.gl/core';\nimport {GL, GLSamplerParameters} from '@luma.gl/webgl/constants';\nimport {convertCompareFunction} from './device-parameters';\n\n/**\n * Convert WebGPU-style sampler props to WebGL\n * @param props\n * @returns\n */\nexport function convertSamplerParametersToWebGL(props: SamplerProps): GLSamplerParameters {\n const params: GLSamplerParameters = {};\n if (props.addressModeU) {\n params[GL.TEXTURE_WRAP_S] = convertAddressMode(props.addressModeU);\n }\n if (props.addressModeV) {\n params[GL.TEXTURE_WRAP_T] = convertAddressMode(props.addressModeV);\n }\n if (props.addressModeW) {\n params[GL.TEXTURE_WRAP_R] = convertAddressMode(props.addressModeW);\n }\n if (props.magFilter) {\n params[GL.TEXTURE_MAG_FILTER] = convertMaxFilterMode(props.magFilter);\n }\n if (props.minFilter || props.mipmapFilter) {\n // TODO - arbitrary choice of linear?\n params[GL.TEXTURE_MIN_FILTER] = convertMinFilterMode(\n props.minFilter || 'linear',\n props.mipmapFilter\n );\n }\n if (props.lodMinClamp !== undefined) {\n params[GL.TEXTURE_MIN_LOD] = props.lodMinClamp;\n }\n if (props.lodMaxClamp !== undefined) {\n params[GL.TEXTURE_MAX_LOD] = props.lodMaxClamp;\n }\n if (props.type === 'comparison-sampler') {\n // Setting prop.compare turns this into a comparison sampler\n params[GL.TEXTURE_COMPARE_MODE] = GL.COMPARE_REF_TO_TEXTURE;\n }\n if (props.compare) {\n params[GL.TEXTURE_COMPARE_FUNC] = convertCompareFunction('compare', props.compare);\n }\n // Note depends on WebGL extension\n if (props.maxAnisotropy) {\n params[GL.TEXTURE_MAX_ANISOTROPY_EXT] = props.maxAnisotropy;\n }\n return params;\n}\n\n// HELPERS\n\n/** Convert address more */\nfunction convertAddressMode(\n addressMode: 'clamp-to-edge' | 'repeat' | 'mirror-repeat'\n): GL.CLAMP_TO_EDGE | GL.REPEAT | GL.MIRRORED_REPEAT {\n switch (addressMode) {\n case 'clamp-to-edge':\n return GL.CLAMP_TO_EDGE;\n case 'repeat':\n return GL.REPEAT;\n case 'mirror-repeat':\n return GL.MIRRORED_REPEAT;\n }\n}\n\nfunction convertMaxFilterMode(maxFilter: 'nearest' | 'linear'): GL.NEAREST | GL.LINEAR {\n switch (maxFilter) {\n case 'nearest':\n return GL.NEAREST;\n case 'linear':\n return GL.LINEAR;\n }\n}\n\n/**\n * WebGPU has separate min filter and mipmap filter,\n * WebGL is combined and effectively offers 6 options\n */\nfunction convertMinFilterMode(\n minFilter: 'nearest' | 'linear',\n mipmapFilter: 'none' | 'nearest' | 'linear' = 'none'\n):\n | GL.NEAREST\n | GL.LINEAR\n | GL.NEAREST_MIPMAP_NEAREST\n | GL.LINEAR_MIPMAP_NEAREST\n | GL.NEAREST_MIPMAP_LINEAR\n | GL.LINEAR_MIPMAP_LINEAR {\n if (!mipmapFilter) {\n return convertMaxFilterMode(minFilter);\n }\n switch (mipmapFilter) {\n case 'none':\n return convertMaxFilterMode(minFilter);\n case 'nearest':\n switch (minFilter) {\n case 'nearest':\n return GL.NEAREST_MIPMAP_NEAREST;\n case 'linear':\n return GL.LINEAR_MIPMAP_NEAREST;\n }\n break;\n case 'linear':\n switch (minFilter) {\n case 'nearest':\n return GL.NEAREST_MIPMAP_LINEAR;\n case 'linear':\n return GL.LINEAR_MIPMAP_LINEAR;\n }\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Sampler, SamplerProps} from '@luma.gl/core';\nimport {GL, GLSamplerParameters} from '@luma.gl/webgl/constants';\nimport {convertSamplerParametersToWebGL} from '../converters/sampler-parameters';\nimport type {WebGLDevice} from '../webgl-device';\n\n/**\n * Sampler object -\n * so that they can be set directly on the texture\n * https://github.com/WebGLSamples/WebGL2Samples/blob/master/samples/sampler_object.html\n */\nexport class WEBGLSampler extends Sampler {\n readonly device: WebGLDevice;\n readonly handle: WebGLSampler;\n readonly parameters: GLSamplerParameters;\n\n constructor(device: WebGLDevice, props: SamplerProps) {\n super(device, props);\n this.device = device;\n this.parameters = convertSamplerParametersToWebGL(props);\n this.handle = props.handle || this.device.gl.createSampler();\n this._setSamplerParameters(this.parameters);\n }\n\n override destroy(): void {\n if (this.handle) {\n this.device.gl.deleteSampler(this.handle);\n // @ts-expect-error read-only/undefined\n this.handle = undefined;\n }\n }\n\n override toString(): string {\n return `Sampler(${this.id},${JSON.stringify(this.props)})`;\n }\n\n /** Set sampler parameters on the sampler */\n private _setSamplerParameters(parameters: GLSamplerParameters): void {\n for (const [pname, value] of Object.entries(parameters)) {\n // Apparently there are integer/float conversion issues requires two parameter setting functions in JavaScript.\n // For now, pick the float version for parameters specified as GLfloat.\n const param = Number(pname) as GL.TEXTURE_MIN_LOD | GL.TEXTURE_MAX_LOD;\n switch (param) {\n case GL.TEXTURE_MIN_LOD:\n case GL.TEXTURE_MAX_LOD:\n this.device.gl.samplerParameterf(this.handle, param, value);\n break;\n default:\n this.device.gl.samplerParameteri(this.handle, param, value);\n break;\n }\n }\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {GLParameters, setGLParameters} from '../parameters/unified-parameter-api';\nimport {WebGLStateTracker} from './webgl-state-tracker';\n\n/**\n * Execute a function with a set of temporary WebGL parameter overrides\n * - Saves current \"global\" WebGL context settings\n * - Sets the supplies WebGL context parameters,\n * - Executes supplied function\n * - Restores parameters\n * - Returns the return value of the supplied function\n */\nexport function withGLParameters(\n gl: WebGL2RenderingContext,\n parameters: GLParameters & {nocatch?: boolean},\n func: any\n): any {\n if (isObjectEmpty(parameters)) {\n // Avoid setting state if no parameters provided. Just call and return\n return func(gl);\n }\n\n const {nocatch = true} = parameters;\n\n const webglState = WebGLStateTracker.get(gl);\n webglState.push();\n setGLParameters(gl, parameters);\n\n // Setup is done, call the function\n let value;\n\n if (nocatch) {\n // Avoid try catch to minimize stack size impact for safe execution paths\n value = func(gl);\n webglState.pop();\n } else {\n // Wrap in a try-catch to ensure that parameters are restored on exceptions\n try {\n value = func(gl);\n } finally {\n webglState.pop();\n }\n }\n\n return value;\n}\n\n// Helpers\n\n// Returns true if given object is empty, false otherwise.\nfunction isObjectEmpty(object: unknown): boolean {\n // @ts-ignore - dummy key variable\n for (const key in object) {\n return false;\n }\n return true;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device, TextureViewProps} from '@luma.gl/core';\n// import {getTextureFormatInfo} from '@luma.gl/core';\nimport {TextureView, Texture} from '@luma.gl/core';\n\nimport {WebGLDevice} from '../webgl-device';\nimport {WEBGLTexture} from './webgl-texture';\n\nexport class WEBGLTextureView extends TextureView {\n readonly device: WebGLDevice;\n readonly gl: WebGL2RenderingContext;\n readonly handle: null; // Does not have a WebGL representation\n readonly texture: WEBGLTexture;\n\n constructor(device: Device, props: TextureViewProps & {texture: WEBGLTexture}) {\n super(device, {...Texture.defaultProps, ...props});\n\n this.device = device as WebGLDevice;\n this.gl = this.device.gl;\n this.handle = null;\n this.texture = props.texture;\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {GL, GLDataType, GLPixelType} from '@luma.gl/webgl/constants';\nimport {SignedDataType} from '@luma.gl/core';\n\n/** Get shadertypes data type from GL constants */\nexport function convertGLDataTypeToDataType(type: GLDataType | GLPixelType): SignedDataType {\n return GL_DATA_TYPE_MAP[type];\n}\n\nconst GL_DATA_TYPE_MAP: Record = {\n [GL.INT]: 'sint32',\n [GL.UNSIGNED_INT]: 'uint32',\n [GL.SHORT]: 'sint16',\n [GL.UNSIGNED_SHORT]: 'uint16',\n [GL.BYTE]: 'sint8',\n [GL.UNSIGNED_BYTE]: 'uint8',\n [GL.FLOAT]: 'float32',\n [GL.HALF_FLOAT]: 'float16',\n [GL.UNSIGNED_SHORT_5_6_5]: 'uint16',\n [GL.UNSIGNED_SHORT_4_4_4_4]: 'uint16',\n [GL.UNSIGNED_SHORT_5_5_5_1]: 'uint16',\n [GL.UNSIGNED_INT_2_10_10_10_REV]: 'uint32',\n [GL.UNSIGNED_INT_10F_11F_11F_REV]: 'uint32',\n [GL.UNSIGNED_INT_5_9_9_9_REV]: 'uint32',\n [GL.UNSIGNED_INT_24_8]: 'uint32',\n [GL.FLOAT_32_UNSIGNED_INT_24_8_REV]: 'uint32'\n};\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// @ts-nocheck\n\nimport {\n type Device,\n type TextureProps,\n type TextureViewProps,\n type Sampler,\n type SamplerProps,\n type CopyExternalImageOptions,\n type TextureReadOptions,\n type TextureWriteOptions,\n type TextureFormat,\n Buffer,\n getTypedArrayConstructor,\n Texture,\n log\n} from '@luma.gl/core';\n\nimport {\n GLSamplerParameters,\n GLValueParameters,\n GL,\n GLTextureTarget,\n GLTextureCubeMapTarget,\n GLTexelDataFormat,\n GLPixelType\n} from '@luma.gl/webgl/constants';\n\nimport {getTextureFormatWebGL} from '../converters/webgl-texture-table';\nimport {convertSamplerParametersToWebGL} from '../converters/sampler-parameters';\nimport {withGLParameters} from '../../context/state-tracker/with-parameters';\nimport {WebGLDevice} from '../webgl-device';\nimport {WEBGLBuffer} from './webgl-buffer';\nimport {WEBGLFramebuffer} from './webgl-framebuffer';\nimport {WEBGLSampler} from './webgl-sampler';\nimport {WEBGLTextureView} from './webgl-texture-view';\nimport {convertGLDataTypeToDataType} from '../converters/shader-formats';\n\n/**\n * WebGL... the texture API from hell... hopefully made simpler\n */\nexport class WEBGLTexture extends Texture {\n // readonly MAX_ATTRIBUTES: number;\n readonly device: WebGLDevice;\n readonly gl: WebGL2RenderingContext;\n handle: WebGLTexture;\n\n // @ts-ignore TODO - currently unused in WebGL. Create dummy sampler?\n sampler: WEBGLSampler = undefined;\n view: WEBGLTextureView;\n\n /**\n * The WebGL target corresponding to the texture type\n * @note `target` cannot be modified by bind:\n * textures are special because when you first bind them to a target,\n * When you first bind a texture as a GL_TEXTURE_2D, you are saying that this texture is a 2D texture.\n * And it will always be a 2D texture; this state cannot be changed ever.\n * A texture that was first bound as a GL_TEXTURE_2D, must always be bound as a GL_TEXTURE_2D;\n * attempting to bind it as GL_TEXTURE_3D will give rise to a run-time error\n */\n glTarget: GLTextureTarget;\n /** The WebGL format - essentially channel structure */\n glFormat: GLTexelDataFormat;\n /** The WebGL data format - the type of each channel */\n glType: GLPixelType;\n /** The WebGL constant corresponding to the WebGPU style constant in format */\n glInternalFormat: GL;\n /** Whether the internal format is compressed */\n compressed: boolean;\n\n // state\n /** Texture binding slot - TODO - move to texture view? */\n _textureUnit: number = 0;\n /** Cached framebuffer reused for color texture readback. */\n _framebuffer: WEBGLFramebuffer | null = null;\n /** Cache key for the currently attached readback subresource `${mipLevel}:${layer}`. */\n _framebufferAttachmentKey: string | null = null;\n\n constructor(device: Device, props: TextureProps) {\n // const byteAlignment = this._getRowByteAlignment(props.format, props.width);\n super(device, props, {byteAlignment: 1});\n\n this.device = device as WebGLDevice;\n this.gl = this.device.gl;\n\n const formatInfo = getTextureFormatWebGL(this.props.format);\n\n // Note: In WebGL the texture target defines the type of texture on first bind.\n this.glTarget = getWebGLTextureTarget(this.props.dimension);\n this.glInternalFormat = formatInfo.internalFormat;\n this.glFormat = formatInfo.format;\n this.glType = formatInfo.type;\n this.compressed = formatInfo.compressed;\n\n this.handle = this.props.handle || this.gl.createTexture();\n this.device._setWebGLDebugMetadata(this.handle, this, {spector: this.props});\n\n /**\n * Use WebGL immutable texture storage to allocate and clear texture memory.\n * - texStorage2D should be considered a preferred alternative to texImage2D. It may have lower memory costs than texImage2D in some implementations.\n * - Once texStorage*D has been called, the texture is immutable and can only be updated with texSubImage*(), not texImage()\n * @see https://registry.khronos.org/webgl/specs/latest/2.0/ WebGL 2 spec section 3.7.6\n */\n this.gl.bindTexture(this.glTarget, this.handle);\n const {dimension, width, height, depth, mipLevels, glTarget, glInternalFormat} = this;\n if (!this.compressed) {\n switch (dimension) {\n case '2d':\n case 'cube':\n this.gl.texStorage2D(glTarget, mipLevels, glInternalFormat, width, height);\n break;\n case '2d-array':\n case '3d':\n this.gl.texStorage3D(glTarget, mipLevels, glInternalFormat, width, height, depth);\n break;\n default:\n throw new Error(dimension);\n }\n }\n this.gl.bindTexture(this.glTarget, null);\n\n // Set data\n this._initializeData(props.data);\n\n if (!this.props.handle) {\n this.trackAllocatedMemory(this.getAllocatedByteLength(), 'Texture');\n } else {\n this.trackReferencedMemory(this.getAllocatedByteLength(), 'Texture');\n }\n\n // Set texture sampler parameters\n this.setSampler(this.props.sampler);\n // @ts-ignore TODO - fix types\n this.view = new WEBGLTextureView(this.device, {...this.props, texture: this});\n\n Object.seal(this);\n }\n\n override destroy(): void {\n if (this.handle) {\n // Destroy any cached framebuffer\n this._framebuffer?.destroy();\n this._framebuffer = null;\n this._framebufferAttachmentKey = null;\n\n this.removeStats();\n if (!this.props.handle) {\n this.gl.deleteTexture(this.handle);\n this.trackDeallocatedMemory('Texture');\n } else {\n this.trackDeallocatedReferencedMemory('Texture');\n }\n // this.handle = null;\n this.destroyed = true;\n }\n }\n\n createView(props: TextureViewProps): WEBGLTextureView {\n return new WEBGLTextureView(this.device, {...props, texture: this});\n }\n\n override setSampler(sampler: Sampler | SamplerProps = {}): void {\n super.setSampler(sampler);\n // Apply sampler parameters to texture\n const parameters = convertSamplerParametersToWebGL(this.sampler.props);\n this._setSamplerParameters(parameters);\n }\n\n copyExternalImage(options_: CopyExternalImageOptions): {width: number; height: number} {\n const options = this._normalizeCopyExternalImageOptions(options_);\n\n if (options.sourceX || options.sourceY) {\n // requires copyTexSubImage2D from a framebuffer'\n throw new Error('WebGL does not support sourceX/sourceY)');\n }\n\n const {glFormat, glType} = this;\n const {image, depth, mipLevel, x, y, z, width, height} = options;\n\n // WebGL cube maps specify faces by overriding target instead of using the z parameter\n const glTarget = getWebGLCubeFaceTarget(this.glTarget, this.dimension, z);\n const glParameters: GLValueParameters = options.flipY ? {[GL.UNPACK_FLIP_Y_WEBGL]: true} : {};\n\n this.gl.bindTexture(this.glTarget, this.handle);\n\n withGLParameters(this.gl, glParameters, () => {\n switch (this.dimension) {\n case '2d':\n case 'cube':\n // biome-ignore format: preserve layout\n this.gl.texSubImage2D(glTarget, mipLevel, x, y, width, height, glFormat, glType, image);\n break;\n case '2d-array':\n case '3d':\n // biome-ignore format: preserve layout\n this.gl.texSubImage3D(glTarget, mipLevel, x, y, z, width, height, depth, glFormat, glType, image);\n break;\n default:\n // Can never happen in WebGL\n }\n });\n\n this.gl.bindTexture(this.glTarget, null);\n\n return {width: options.width, height: options.height};\n }\n\n override copyImageData(options_): void {\n super.copyImageData(options_);\n }\n\n /**\n * Reads a color texture subresource into a GPU buffer using `PIXEL_PACK_BUFFER`.\n *\n * @note Only first-pass color readback is supported. Unsupported formats and aspects throw\n * before any WebGL calls are issued.\n */\n readBuffer(options: TextureReadOptions & {byteOffset?: number} = {}, buffer?: Buffer): Buffer {\n if (!buffer) {\n throw new Error(`${this} readBuffer requires a destination buffer`);\n }\n const normalizedOptions = this._getSupportedColorReadOptions(options);\n const byteOffset = options.byteOffset ?? 0;\n const memoryLayout = this.computeMemoryLayout(normalizedOptions);\n\n if (buffer.byteLength < byteOffset + memoryLayout.byteLength) {\n throw new Error(\n `${this} readBuffer target is too small (${buffer.byteLength} < ${byteOffset + memoryLayout.byteLength})`\n );\n }\n\n const webglBuffer = buffer as WEBGLBuffer;\n this.gl.bindBuffer(GL.PIXEL_PACK_BUFFER, webglBuffer.handle);\n try {\n this._readColorTextureLayers(normalizedOptions, memoryLayout, destinationByteOffset => {\n this.gl.readPixels(\n normalizedOptions.x,\n normalizedOptions.y,\n normalizedOptions.width,\n normalizedOptions.height,\n this.glFormat,\n this.glType,\n byteOffset + destinationByteOffset\n );\n });\n } finally {\n this.gl.bindBuffer(GL.PIXEL_PACK_BUFFER, null);\n }\n\n return buffer;\n }\n\n async readDataAsync(options: TextureReadOptions = {}): Promise {\n throw new Error(\n `${this} readDataAsync is deprecated; use readBuffer() with an explicit destination buffer or DynamicTexture.readAsync()`\n );\n }\n\n writeBuffer(buffer: Buffer, options_: TextureWriteOptions = {}) {\n const options = this._normalizeTextureWriteOptions(options_);\n const {width, height, depthOrArrayLayers, mipLevel, byteOffset, x, y, z} = options;\n const {glFormat, glType, compressed} = this;\n const glTarget = getWebGLCubeFaceTarget(this.glTarget, this.dimension, z);\n\n if (compressed) {\n throw new Error('writeBuffer for compressed textures is not implemented in WebGL');\n }\n\n const {bytesPerPixel} = this.device.getTextureFormatInfo(this.format);\n const unpackRowLength = bytesPerPixel ? options.bytesPerRow / bytesPerPixel : undefined;\n const glParameters: GLValueParameters = {\n [GL.UNPACK_ALIGNMENT]: this.byteAlignment,\n ...(unpackRowLength !== undefined ? {[GL.UNPACK_ROW_LENGTH]: unpackRowLength} : {}),\n [GL.UNPACK_IMAGE_HEIGHT]: options.rowsPerImage\n };\n\n this.gl.bindTexture(this.glTarget, this.handle);\n this.gl.bindBuffer(GL.PIXEL_UNPACK_BUFFER, buffer.handle);\n\n withGLParameters(this.gl, glParameters, () => {\n switch (this.dimension) {\n case '2d':\n case 'cube':\n this.gl.texSubImage2D(\n glTarget,\n mipLevel,\n x,\n y,\n width,\n height,\n glFormat,\n glType,\n byteOffset\n );\n break;\n case '2d-array':\n case '3d':\n this.gl.texSubImage3D(\n glTarget,\n mipLevel,\n x,\n y,\n z,\n width,\n height,\n depthOrArrayLayers,\n glFormat,\n glType,\n byteOffset\n );\n break;\n default:\n }\n });\n\n this.gl.bindBuffer(GL.PIXEL_UNPACK_BUFFER, null);\n this.gl.bindTexture(this.glTarget, null);\n }\n\n writeData(\n data: ArrayBuffer | SharedArrayBuffer | ArrayBufferView,\n options_: TextureWriteOptions = {}\n ): void {\n const options = this._normalizeTextureWriteOptions(options_);\n\n const typedArray = ArrayBuffer.isView(data) ? data : new Uint8Array(data);\n const {width, height, depthOrArrayLayers, mipLevel, x, y, z, byteOffset} = options;\n const {glFormat, glType, compressed} = this;\n const glTarget = getWebGLCubeFaceTarget(this.glTarget, this.dimension, z);\n\n let unpackRowLength: number | undefined;\n if (!compressed) {\n const {bytesPerPixel} = this.device.getTextureFormatInfo(this.format);\n if (bytesPerPixel) {\n unpackRowLength = options.bytesPerRow / bytesPerPixel;\n }\n }\n\n const glParameters: GLValueParameters = !this.compressed\n ? {\n [GL.UNPACK_ALIGNMENT]: this.byteAlignment,\n ...(unpackRowLength !== undefined ? {[GL.UNPACK_ROW_LENGTH]: unpackRowLength} : {}),\n [GL.UNPACK_IMAGE_HEIGHT]: options.rowsPerImage\n }\n : {};\n const sourceElementOffset = getWebGLTextureSourceElementOffset(typedArray, byteOffset);\n const compressedData = compressed ? getArrayBufferView(typedArray, byteOffset) : typedArray;\n const mipLevelSize = this._getMipLevelSize(mipLevel);\n const isFullMipUpload =\n x === 0 &&\n y === 0 &&\n z === 0 &&\n width === mipLevelSize.width &&\n height === mipLevelSize.height &&\n depthOrArrayLayers === mipLevelSize.depthOrArrayLayers;\n\n this.gl.bindTexture(this.glTarget, this.handle);\n this.gl.bindBuffer(GL.PIXEL_UNPACK_BUFFER, null);\n\n withGLParameters(this.gl, glParameters, () => {\n switch (this.dimension) {\n case '2d':\n case 'cube':\n if (compressed) {\n if (isFullMipUpload) {\n // biome-ignore format: preserve layout\n this.gl.compressedTexImage2D(glTarget, mipLevel, glFormat, width, height, 0, compressedData);\n } else {\n // biome-ignore format: preserve layout\n this.gl.compressedTexSubImage2D(glTarget, mipLevel, x, y, width, height, glFormat, compressedData);\n }\n } else {\n // biome-ignore format: preserve layout\n this.gl.texSubImage2D(glTarget, mipLevel, x, y, width, height, glFormat, glType, typedArray, sourceElementOffset);\n }\n break;\n case '2d-array':\n case '3d':\n if (compressed) {\n if (isFullMipUpload) {\n // biome-ignore format: preserve layout\n this.gl.compressedTexImage3D(\n glTarget,\n mipLevel,\n glFormat,\n width,\n height,\n depthOrArrayLayers,\n 0,\n compressedData\n );\n } else {\n // biome-ignore format: preserve layout\n this.gl.compressedTexSubImage3D(\n glTarget,\n mipLevel,\n x,\n y,\n z,\n width,\n height,\n depthOrArrayLayers,\n glFormat,\n compressedData\n );\n }\n } else {\n // biome-ignore format: preserve layout\n this.gl.texSubImage3D(glTarget, mipLevel, x, y, z, width, height, depthOrArrayLayers, glFormat, glType, typedArray, sourceElementOffset);\n }\n break;\n default:\n // Can never happen in WebGL\n }\n });\n\n this.gl.bindTexture(this.glTarget, null);\n }\n\n // IMPLEMENTATION SPECIFIC\n\n /** @todo - for now we always use 1 for maximum compatibility, we can fine tune later */\n private _getRowByteAlignment(format: TextureFormat, width: number): 1 | 2 | 4 | 8 {\n // For best texture data read/write performance, calculate the biggest pack/unpack alignment\n // that fits with the provided texture row byte length\n // Note: Any RGBA or 32 bit type will be at least 4 bytes, which should result in good performance.\n // const info = this.device.getTextureFormatInfo(format);\n // const rowByteLength = width * info.bytesPerPixel;\n // if (rowByteLength % 8 === 0) return 8;\n // if (rowByteLength % 4 === 0) return 4;\n // if (rowByteLength % 2 === 0) return 2;\n return 1;\n }\n\n /**\n * Wraps a given texture into a framebuffer object, that can be further used\n * to read data from the texture object.\n */\n _getFramebuffer() {\n this._framebuffer ||= this.device.createFramebuffer({\n id: `framebuffer-for-${this.id}`,\n width: this.width,\n height: this.height,\n colorAttachments: [this]\n });\n return this._framebuffer;\n }\n\n // WEBGL SPECIFIC\n\n override readDataSyncWebGL(options_: TextureReadOptions = {}): ArrayBuffer {\n const options = this._getSupportedColorReadOptions(options_);\n const memoryLayout = this.computeMemoryLayout(options);\n\n // const formatInfo = getTextureFormatInfo(format);\n // Allocate pixel array if not already available, using supplied type\n const shaderType = convertGLDataTypeToDataType(this.glType);\n const ArrayType = getTypedArrayConstructor(shaderType);\n const targetArray = new ArrayType(memoryLayout.byteLength / ArrayType.BYTES_PER_ELEMENT) as\n | Uint8Array\n | Uint16Array\n | Float32Array\n | Int8Array\n | Int16Array\n | Int32Array\n | Uint32Array;\n\n this._readColorTextureLayers(options, memoryLayout, destinationByteOffset => {\n const layerView = new ArrayType(\n targetArray.buffer,\n targetArray.byteOffset + destinationByteOffset,\n memoryLayout.bytesPerImage / ArrayType.BYTES_PER_ELEMENT\n );\n this.gl.readPixels(\n options.x,\n options.y,\n options.width,\n options.height,\n this.glFormat,\n this.glType,\n layerView\n );\n });\n\n return targetArray.buffer as ArrayBuffer;\n }\n\n /**\n * Iterates the requested mip/layer/slice range, reattaching the cached read framebuffer as\n * needed before delegating the actual `readPixels()` call to the supplied callback.\n */\n private _readColorTextureLayers(\n options: Required,\n memoryLayout: ReturnType,\n readLayer: (destinationByteOffset: number) => void\n ): void {\n const framebuffer = this._getFramebuffer();\n const packRowLength = memoryLayout.bytesPerRow / memoryLayout.bytesPerPixel;\n const glParameters: GLValueParameters = {\n [GL.PACK_ALIGNMENT]: this.byteAlignment,\n ...(packRowLength !== options.width ? {[GL.PACK_ROW_LENGTH]: packRowLength} : {})\n };\n\n // Note: luma.gl overrides bindFramebuffer so that we can reliably restore the previous framebuffer.\n const prevReadBuffer = this.gl.getParameter(GL.READ_BUFFER) as GL;\n const prevHandle = this.gl.bindFramebuffer(\n GL.FRAMEBUFFER,\n framebuffer.handle\n ) as unknown as WebGLFramebuffer | null;\n\n try {\n this.gl.readBuffer(GL.COLOR_ATTACHMENT0);\n withGLParameters(this.gl, glParameters, () => {\n for (let layerIndex = 0; layerIndex < options.depthOrArrayLayers; layerIndex++) {\n this._attachReadSubresource(framebuffer, options.mipLevel, options.z + layerIndex);\n readLayer(layerIndex * memoryLayout.bytesPerImage);\n }\n });\n } finally {\n this.gl.bindFramebuffer(GL.FRAMEBUFFER, prevHandle || null);\n this.gl.readBuffer(prevReadBuffer);\n }\n }\n\n /**\n * Attaches a single color subresource to the cached read framebuffer.\n *\n * @note Repeated attachments of the same `(mipLevel, layer)` tuple are skipped.\n */\n private _attachReadSubresource(\n framebuffer: WEBGLFramebuffer,\n mipLevel: number,\n layer: number\n ): void {\n const attachmentKey = `${mipLevel}:${layer}`;\n if (this._framebufferAttachmentKey === attachmentKey) {\n return;\n }\n\n switch (this.dimension) {\n case '2d':\n this.gl.framebufferTexture2D(\n GL.FRAMEBUFFER,\n GL.COLOR_ATTACHMENT0,\n GL.TEXTURE_2D,\n this.handle,\n mipLevel\n );\n break;\n\n case 'cube':\n this.gl.framebufferTexture2D(\n GL.FRAMEBUFFER,\n GL.COLOR_ATTACHMENT0,\n getWebGLCubeFaceTarget(this.glTarget, this.dimension, layer),\n this.handle,\n mipLevel\n );\n break;\n\n case '2d-array':\n case '3d':\n this.gl.framebufferTextureLayer(\n GL.FRAMEBUFFER,\n GL.COLOR_ATTACHMENT0,\n this.handle,\n mipLevel,\n layer\n );\n break;\n\n default:\n throw new Error(`${this} color readback does not support ${this.dimension} textures`);\n }\n\n if (this.device.props.debug) {\n const status = Number(this.gl.checkFramebufferStatus(GL.FRAMEBUFFER));\n if (status !== Number(GL.FRAMEBUFFER_COMPLETE)) {\n throw new Error(`${framebuffer} incomplete for ${this} readback (${status})`);\n }\n }\n\n this._framebufferAttachmentKey = attachmentKey;\n }\n\n /**\n * @note - this is used by the DynamicTexture class to generate mipmaps on WebGL\n */\n override generateMipmapsWebGL(options?: {force?: boolean}): void {\n const isFilterableAndRenderable =\n this.device.isTextureFormatRenderable(this.props.format) &&\n this.device.isTextureFormatFilterable(this.props.format);\n if (!isFilterableAndRenderable) {\n log.warn(`${this} is not renderable or filterable, may not be able to generate mipmaps`)();\n if (!options?.force) {\n return;\n }\n }\n\n try {\n this.gl.bindTexture(this.glTarget, this.handle);\n this.gl.generateMipmap(this.glTarget);\n } catch (error) {\n log.warn(`Error generating mipmap for ${this}: ${(error as Error).message}`)();\n } finally {\n this.gl.bindTexture(this.glTarget, null);\n }\n }\n\n // INTERNAL\n\n /**\n * Sets sampler parameters on texture\n */\n _setSamplerParameters(parameters: GLSamplerParameters): void {\n log.log(2, `${this.id} sampler parameters`, this.device.getGLKeys(parameters))();\n\n this.gl.bindTexture(this.glTarget, this.handle);\n\n for (const [pname, pvalue] of Object.entries(parameters)) {\n const param = Number(pname) as keyof GLSamplerParameters;\n const value = pvalue;\n\n // Apparently integer/float issues require two different texture parameter setting functions in JavaScript.\n // For now, pick the float version for parameters specified as GLfloat.\n switch (param) {\n case GL.TEXTURE_MIN_LOD:\n case GL.TEXTURE_MAX_LOD:\n this.gl.texParameterf(this.glTarget, param, value);\n break;\n\n case GL.TEXTURE_MAG_FILTER:\n case GL.TEXTURE_MIN_FILTER:\n this.gl.texParameteri(this.glTarget, param, value);\n break;\n\n case GL.TEXTURE_WRAP_S:\n case GL.TEXTURE_WRAP_T:\n case GL.TEXTURE_WRAP_R:\n this.gl.texParameteri(this.glTarget, param, value);\n break;\n\n case GL.TEXTURE_MAX_ANISOTROPY_EXT:\n // We have to query feature before using it\n if (this.device.features.has('texture-filterable-anisotropic-webgl')) {\n this.gl.texParameteri(this.glTarget, param, value);\n }\n break;\n\n case GL.TEXTURE_COMPARE_MODE:\n case GL.TEXTURE_COMPARE_FUNC:\n this.gl.texParameteri(this.glTarget, param, value);\n break;\n }\n }\n\n this.gl.bindTexture(this.glTarget, null);\n }\n\n _getActiveUnit(): number {\n return this.gl.getParameter(GL.ACTIVE_TEXTURE) - GL.TEXTURE0;\n }\n\n _bind(_textureUnit?: number): number {\n const {gl} = this;\n\n if (_textureUnit !== undefined) {\n this._textureUnit = _textureUnit;\n gl.activeTexture(gl.TEXTURE0 + _textureUnit);\n }\n\n gl.bindTexture(this.glTarget, this.handle);\n // @ts-ignore TODO fix types\n return _textureUnit;\n }\n\n _unbind(_textureUnit?: number): number | undefined {\n const {gl} = this;\n\n if (_textureUnit !== undefined) {\n this._textureUnit = _textureUnit;\n gl.activeTexture(gl.TEXTURE0 + _textureUnit);\n }\n\n gl.bindTexture(this.glTarget, null);\n return _textureUnit;\n }\n}\n\nfunction getArrayBufferView(typedArray: ArrayBufferView, byteOffset = 0): ArrayBufferView {\n if (!byteOffset) {\n return typedArray;\n }\n\n return new typedArray.constructor(\n typedArray.buffer,\n typedArray.byteOffset + byteOffset,\n (typedArray.byteLength - byteOffset) / typedArray.BYTES_PER_ELEMENT\n ) as ArrayBufferView;\n}\n\nfunction getWebGLTextureSourceElementOffset(\n typedArray: ArrayBufferView,\n byteOffset: number\n): number {\n if (byteOffset % typedArray.BYTES_PER_ELEMENT !== 0) {\n throw new Error(\n `Texture byteOffset ${byteOffset} must align to typed array element size ${typedArray.BYTES_PER_ELEMENT}`\n );\n }\n\n return byteOffset / typedArray.BYTES_PER_ELEMENT;\n}\n\n// INTERNAL HELPERS\n\n/** Convert a WebGPU style texture constant to a WebGL style texture constant */\nexport function getWebGLTextureTarget(\n dimension: '1d' | '2d' | '2d-array' | 'cube' | 'cube-array' | '3d'\n): GLTextureTarget {\n // biome-ignore format: preserve layout\n switch (dimension) {\n case '1d': break; // not supported in any WebGL version\n case '2d': return GL.TEXTURE_2D; // supported in WebGL1\n case '3d': return GL.TEXTURE_3D; // supported in WebGL2\n case 'cube': return GL.TEXTURE_CUBE_MAP; // supported in WebGL1\n case '2d-array': return GL.TEXTURE_2D_ARRAY; // supported in WebGL2\n case 'cube-array': break; // not supported in any WebGL version\n }\n throw new Error(dimension);\n}\n\n/**\n * In WebGL, cube maps specify faces by overriding target instead of using the depth parameter.\n * @note We still bind the texture using GL.TEXTURE_CUBE_MAP, but we need to use the face-specific target when setting mip levels.\n * @returns glTarget unchanged, if dimension !== 'cube'.\n */\nexport function getWebGLCubeFaceTarget(\n glTarget: GLTextureTarget,\n dimension: '1d' | '2d' | '2d-array' | 'cube' | 'cube-array' | '3d',\n level: number\n): GLTextureTarget | GLTextureCubeMapTarget {\n return dimension === 'cube' ? GL.TEXTURE_CUBE_MAP_POSITIVE_X + level : glTarget;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/* eslint-disable */\n\n// Uniforms\nimport type {UniformValue} from '@luma.gl/core';\nimport {GL, GLUniformType, GLSamplerType} from '@luma.gl/webgl/constants';\n\n/** Set a raw uniform (without type conversion and caching) */\n/* eslint-disable max-len */\nexport function setUniform(\n gl: WebGL2RenderingContext,\n location: WebGLUniformLocation,\n type: GLUniformType | GLSamplerType,\n value: UniformValue\n): void {\n const gl2 = gl as WebGL2RenderingContext;\n\n // Prepare the value for WebGL setters\n let uniformValue = value;\n if (uniformValue === true) {\n uniformValue = 1;\n }\n if (uniformValue === false) {\n uniformValue = 0;\n }\n const arrayValue = typeof uniformValue === 'number' ? [uniformValue] : uniformValue;\n\n // biome-ignore format: preserve layout\n switch (type) {\n case GL.SAMPLER_2D:\n case GL.SAMPLER_CUBE:\n case GL.SAMPLER_3D:\n case GL.SAMPLER_2D_SHADOW:\n case GL.SAMPLER_2D_ARRAY:\n case GL.SAMPLER_2D_ARRAY_SHADOW:\n case GL.SAMPLER_CUBE_SHADOW:\n case GL.INT_SAMPLER_2D:\n case GL.INT_SAMPLER_3D:\n case GL.INT_SAMPLER_CUBE:\n case GL.INT_SAMPLER_2D_ARRAY:\n case GL.UNSIGNED_INT_SAMPLER_2D:\n case GL.UNSIGNED_INT_SAMPLER_3D:\n case GL.UNSIGNED_INT_SAMPLER_CUBE:\n case GL.UNSIGNED_INT_SAMPLER_2D_ARRAY:\n if (typeof value !== 'number') {\n throw new Error('samplers must be set to integers');\n }\n return gl.uniform1i(location, value);\n\n case GL.FLOAT: return gl.uniform1fv(location, arrayValue);\n case GL.FLOAT_VEC2: return gl.uniform2fv(location, arrayValue);\n case GL.FLOAT_VEC3: return gl.uniform3fv(location, arrayValue);\n case GL.FLOAT_VEC4: return gl.uniform4fv(location, arrayValue);\n\n case GL.INT: return gl.uniform1iv(location, arrayValue);\n case GL.INT_VEC2: return gl.uniform2iv(location, arrayValue);\n case GL.INT_VEC3: return gl.uniform3iv(location, arrayValue);\n case GL.INT_VEC4: return gl.uniform4iv(location, arrayValue);\n\n case GL.BOOL: return gl.uniform1iv(location, arrayValue);\n case GL.BOOL_VEC2: return gl.uniform2iv(location, arrayValue);\n case GL.BOOL_VEC3: return gl.uniform3iv(location, arrayValue);\n case GL.BOOL_VEC4: return gl.uniform4iv(location, arrayValue);\n\n // WEBGL2 - unsigned integers\n case GL.UNSIGNED_INT: return gl2.uniform1uiv(location, arrayValue, 1);\n case GL.UNSIGNED_INT_VEC2: return gl2.uniform2uiv(location, arrayValue, 2);\n case GL.UNSIGNED_INT_VEC3: return gl2.uniform3uiv(location, arrayValue, 3);\n case GL.UNSIGNED_INT_VEC4: return gl2.uniform4uiv(location, arrayValue, 4);\n\n // WebGL2 - quadratic matrices\n // false: don't transpose the matrix\n case GL.FLOAT_MAT2: return gl.uniformMatrix2fv(location, false, arrayValue);\n case GL.FLOAT_MAT3: return gl.uniformMatrix3fv(location, false, arrayValue);\n case GL.FLOAT_MAT4: return gl.uniformMatrix4fv(location, false, arrayValue);\n\n // WebGL2 - rectangular matrices\n case GL.FLOAT_MAT2x3: return gl2.uniformMatrix2x3fv(location, false, arrayValue);\n case GL.FLOAT_MAT2x4: return gl2.uniformMatrix2x4fv(location, false, arrayValue);\n case GL.FLOAT_MAT3x2: return gl2.uniformMatrix3x2fv(location, false, arrayValue);\n case GL.FLOAT_MAT3x4: return gl2.uniformMatrix3x4fv(location, false, arrayValue);\n case GL.FLOAT_MAT4x2: return gl2.uniformMatrix4x2fv(location, false, arrayValue);\n case GL.FLOAT_MAT4x3: return gl2.uniformMatrix4x3fv(location, false, arrayValue);\n }\n\n throw new Error('Illegal uniform');\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {GL, GLPrimitiveTopology, GLPrimitive} from '@luma.gl/webgl/constants';\nimport {PrimitiveTopology} from '@luma.gl/core';\n\n// Counts the number of complete primitives given a number of vertices and a drawMode\nexport function getPrimitiveDrawMode(drawMode: GLPrimitiveTopology): GLPrimitive {\n switch (drawMode) {\n case GL.POINTS:\n return GL.POINTS;\n case GL.LINES:\n return GL.LINES;\n case GL.LINE_STRIP:\n return GL.LINES;\n case GL.LINE_LOOP:\n return GL.LINES;\n case GL.TRIANGLES:\n return GL.TRIANGLES;\n case GL.TRIANGLE_STRIP:\n return GL.TRIANGLES;\n case GL.TRIANGLE_FAN:\n return GL.TRIANGLES;\n default:\n throw new Error('drawMode');\n }\n}\n\n// Counts the number of complete \"primitives\" given a number of vertices and a drawMode\nexport function getPrimitiveCount(options: {\n drawMode: GLPrimitiveTopology;\n vertexCount: number;\n}): number {\n const {drawMode, vertexCount} = options;\n switch (drawMode) {\n case GL.POINTS:\n case GL.LINE_LOOP:\n return vertexCount;\n case GL.LINES:\n return vertexCount / 2;\n case GL.LINE_STRIP:\n return vertexCount - 1;\n case GL.TRIANGLES:\n return vertexCount / 3;\n case GL.TRIANGLE_STRIP:\n case GL.TRIANGLE_FAN:\n return vertexCount - 2;\n default:\n throw new Error('drawMode');\n }\n}\n\n// Counts the number of vertices after splitting the vertex stream into separate \"primitives\"\nexport function getVertexCount(options: {\n drawMode: GLPrimitiveTopology;\n vertexCount: number;\n}): number {\n const {drawMode, vertexCount} = options;\n const primitiveCount = getPrimitiveCount({drawMode, vertexCount});\n switch (getPrimitiveDrawMode(drawMode)) {\n case GL.POINTS:\n return primitiveCount;\n case GL.LINES:\n return primitiveCount * 2;\n case GL.TRIANGLES:\n return primitiveCount * 3;\n default:\n throw new Error('drawMode');\n }\n}\n\n/** Get the primitive type for draw */\nexport function getGLDrawMode(\n topology: PrimitiveTopology\n):\n | GL.POINTS\n | GL.LINES\n | GL.LINE_STRIP\n | GL.LINE_LOOP\n | GL.TRIANGLES\n | GL.TRIANGLE_STRIP\n | GL.TRIANGLE_FAN {\n // biome-ignore format: preserve layout\n switch (topology) {\n case 'point-list': return GL.POINTS;\n case 'line-list': return GL.LINES;\n case 'line-strip': return GL.LINE_STRIP;\n case 'triangle-list': return GL.TRIANGLES;\n case 'triangle-strip': return GL.TRIANGLE_STRIP;\n default: throw new Error(topology);\n }\n}\n\n/** Get the primitive type for transform feedback */\nexport function getGLPrimitive(topology: PrimitiveTopology): GL.POINTS | GL.LINES | GL.TRIANGLES {\n // biome-ignore format: preserve layout\n switch (topology) {\n case 'point-list': return GL.POINTS;\n case 'line-list': return GL.LINES;\n case 'line-strip': return GL.LINES;\n case 'triangle-list': return GL.TRIANGLES;\n case 'triangle-strip': return GL.TRIANGLES;\n default: throw new Error(topology);\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {\n RenderPipelineProps,\n RenderPipelineParameters,\n PrimitiveTopology,\n ShaderLayout,\n UniformValue,\n Bindings,\n BindingsByGroup,\n RenderPass,\n VertexArray\n} from '@luma.gl/core';\nimport {RenderPipeline, flattenBindingsByGroup, log, normalizeBindingsByGroup} from '@luma.gl/core';\n// import {getAttributeInfosFromLayouts} from '@luma.gl/core';\nimport {GL} from '@luma.gl/webgl/constants';\n\nimport {withDeviceAndGLParameters} from '../converters/device-parameters';\nimport {setUniform} from '../helpers/set-uniform';\n// import {copyUniform, checkUniformValues} from '../../classes/uniforms';\n\nimport {WebGLDevice} from '../webgl-device';\nimport {WEBGLBuffer} from './webgl-buffer';\nimport {WEBGLShader} from './webgl-shader';\nimport {WEBGLFramebuffer} from './webgl-framebuffer';\nimport {WEBGLTexture} from './webgl-texture';\nimport {WEBGLTextureView} from './webgl-texture-view';\nimport {WEBGLRenderPass} from './webgl-render-pass';\nimport {WEBGLTransformFeedback} from './webgl-transform-feedback';\nimport {getGLDrawMode} from '../helpers/webgl-topology-utils';\nimport {WEBGLSharedRenderPipeline} from './webgl-shared-render-pipeline';\n\n/** Creates a new render pipeline */\nexport class WEBGLRenderPipeline extends RenderPipeline {\n /** The WebGL device that created this render pipeline */\n readonly device: WebGLDevice;\n /** Handle to underlying WebGL program */\n readonly handle: WebGLProgram;\n /** vertex shader */\n vs: WEBGLShader;\n /** fragment shader */\n fs: WEBGLShader;\n /** The layout extracted from shader by WebGL introspection APIs */\n introspectedLayout: ShaderLayout;\n\n /** Compatibility path for direct pipeline.setBindings() usage */\n bindings: Bindings = {};\n /** Compatibility path for direct pipeline.uniforms usage */\n uniforms: Record = {};\n /** WebGL varyings */\n varyings: string[] | null = null;\n\n _uniformCount: number = 0;\n _uniformSetters: Record = {}; // TODO are these used?\n\n override get [Symbol.toStringTag]() {\n return 'WEBGLRenderPipeline';\n }\n\n constructor(device: WebGLDevice, props: RenderPipelineProps) {\n super(device, props);\n this.device = device;\n const webglSharedRenderPipeline =\n (this.sharedRenderPipeline as WEBGLSharedRenderPipeline | null) ||\n (this.device._createSharedRenderPipelineWebGL(props) as WEBGLSharedRenderPipeline);\n\n this.sharedRenderPipeline = webglSharedRenderPipeline;\n this.handle = webglSharedRenderPipeline.handle;\n this.vs = webglSharedRenderPipeline.vs;\n this.fs = webglSharedRenderPipeline.fs;\n this.linkStatus = webglSharedRenderPipeline.linkStatus;\n this.introspectedLayout = webglSharedRenderPipeline.introspectedLayout;\n this.device._setWebGLDebugMetadata(this.handle, this, {spector: {id: this.props.id}});\n\n // WebGL only honors shaderLayout overrides for attributes that already exist in the\n // linked program, and only the `type` / `stepMode` fields participate in the merge.\n // Bindings and unknown attributes are ignored. If WebGL cache keys ever depend on\n // `shaderLayout`, they need to match these merge semantics rather than the raw prop.\n this.shaderLayout = props.shaderLayout\n ? mergeShaderLayout(this.introspectedLayout, props.shaderLayout)\n : this.introspectedLayout;\n }\n\n override destroy(): void {\n if (this.destroyed) {\n return;\n }\n if (this.sharedRenderPipeline && !this.props._sharedRenderPipeline) {\n this.sharedRenderPipeline.destroy();\n }\n this.destroyResource();\n }\n\n /**\n * Compatibility shim for code paths that still set bindings on the pipeline.\n * Shared-model draws pass bindings per draw and do not rely on this state.\n */\n setBindings(bindings: Bindings | BindingsByGroup, options?: {disableWarnings?: boolean}): void {\n const flatBindings = flattenBindingsByGroup(\n normalizeBindingsByGroup(this.shaderLayout, bindings)\n );\n for (const [name, value] of Object.entries(flatBindings)) {\n const binding = getShaderLayoutBindingByName(this.shaderLayout, name);\n\n if (!binding) {\n const validBindings = this.shaderLayout.bindings\n .map(binding_ => `\"${binding_.name}\"`)\n .join(', ');\n if (!options?.disableWarnings) {\n log.warn(\n `No binding \"${name}\" in render pipeline \"${this.id}\", expected one of ${validBindings}`,\n value\n )();\n }\n } else {\n if (!value) {\n log.warn(`Unsetting binding \"${name}\" in render pipeline \"${this.id}\"`)();\n }\n switch (binding.type) {\n case 'uniform':\n // @ts-expect-error\n if (!(value instanceof WEBGLBuffer) && !(value.buffer instanceof WEBGLBuffer)) {\n throw new Error('buffer value');\n }\n break;\n case 'texture':\n if (\n !(\n value instanceof WEBGLTextureView ||\n value instanceof WEBGLTexture ||\n value instanceof WEBGLFramebuffer\n )\n ) {\n throw new Error(`${this} Bad texture binding for ${name}`);\n }\n break;\n case 'sampler':\n log.warn(`Ignoring sampler ${name}`)();\n break;\n default:\n throw new Error(binding.type);\n }\n\n this.bindings[name] = value;\n }\n }\n }\n\n /** @todo needed for portable model\n * @note The WebGL API is offers many ways to draw things\n * This function unifies those ways into a single call using common parameters with sane defaults\n */\n draw(options: {\n renderPass: RenderPass;\n parameters?: RenderPipelineParameters;\n topology?: PrimitiveTopology;\n vertexArray: VertexArray;\n isInstanced?: boolean;\n vertexCount?: number;\n indexCount?: number;\n instanceCount?: number;\n firstVertex?: number;\n firstIndex?: number;\n firstInstance?: number;\n baseVertex?: number;\n transformFeedback?: WEBGLTransformFeedback;\n bindings?: Bindings;\n bindGroups?: BindingsByGroup;\n _bindGroupCacheKeys?: Partial>;\n uniforms?: Record;\n }): boolean {\n this._syncLinkStatus();\n const drawBindings = options.bindGroups\n ? flattenBindingsByGroup(options.bindGroups)\n : options.bindings || this.bindings;\n\n const {\n renderPass,\n parameters = this.props.parameters,\n topology = this.props.topology,\n vertexArray,\n vertexCount,\n // indexCount,\n instanceCount,\n isInstanced = false,\n firstVertex = 0,\n // firstIndex,\n // firstInstance,\n // baseVertex,\n transformFeedback,\n uniforms = this.uniforms\n } = options;\n\n const glDrawMode = getGLDrawMode(topology);\n const isIndexed: boolean = Boolean(vertexArray.indexBuffer);\n const glIndexType = (vertexArray.indexBuffer as WEBGLBuffer)?.glIndexType;\n // Note that we sometimes get called with 0 instances\n\n // If we are using async linking, we need to wait until linking completes\n if (this.linkStatus !== 'success') {\n log.info(2, `RenderPipeline:${this.id}.draw() aborted - waiting for shader linking`)();\n return false;\n }\n\n // Avoid WebGL draw call when not rendering any data or values are incomplete\n // Note: async textures set as uniforms might still be loading.\n // Now that all uniforms have been updated, check if any texture\n // in the uniforms is not yet initialized, then we don't draw\n if (!this._areTexturesRenderable(drawBindings)) {\n log.info(2, `RenderPipeline:${this.id}.draw() aborted - textures not yet loaded`)();\n // Note: false means that the app needs to redraw the pipeline again.\n return false;\n }\n\n // (isInstanced && instanceCount === 0)\n // if (vertexCount === 0) {\n // log.info(2, `RenderPipeline:${this.id}.draw() aborted - no vertices to draw`)();\n // Note: false means that the app needs to redraw the pipeline again.\n // return true;\n // }\n\n this.device.gl.useProgram(this.handle);\n\n // Note: Rebinds constant attributes before each draw call\n vertexArray.bindBeforeRender(renderPass);\n\n if (transformFeedback) {\n transformFeedback.begin(this.props.topology);\n }\n\n // We have to apply bindings before every draw call since other draw calls will overwrite\n this._applyBindings(drawBindings, {disableWarnings: this.props.disableWarnings});\n this._applyUniforms(uniforms);\n\n const webglRenderPass = renderPass as WEBGLRenderPass;\n\n withDeviceAndGLParameters(this.device, parameters, webglRenderPass.glParameters, () => {\n if (isIndexed && isInstanced) {\n this.device.gl.drawElementsInstanced(\n glDrawMode,\n vertexCount || 0, // indexCount?\n glIndexType,\n firstVertex,\n instanceCount || 0\n );\n // } else if (isIndexed && this.device.isWebGL2 && !isNaN(start) && !isNaN(end)) {\n // this.device.gldrawRangeElements(glDrawMode, start, end, vertexCount, glIndexType, offset);\n } else if (isIndexed) {\n this.device.gl.drawElements(glDrawMode, vertexCount || 0, glIndexType, firstVertex); // indexCount?\n } else if (isInstanced) {\n this.device.gl.drawArraysInstanced(\n glDrawMode,\n firstVertex,\n vertexCount || 0,\n instanceCount || 0\n );\n } else {\n this.device.gl.drawArrays(glDrawMode, firstVertex, vertexCount || 0);\n }\n\n if (transformFeedback) {\n transformFeedback.end();\n }\n });\n\n vertexArray.unbindAfterRender(renderPass);\n\n return true;\n }\n\n /**\n * Checks if all texture-values uniforms are renderable (i.e. loaded)\n * Update a texture if needed (e.g. from video)\n * Note: This is currently done before every draw call\n */\n _areTexturesRenderable(bindings: Bindings) {\n let texturesRenderable = true;\n\n for (const bindingInfo of this.shaderLayout.bindings) {\n if (!getBindingValueForLayoutBinding(bindings, bindingInfo.name)) {\n log.warn(`Binding ${bindingInfo.name} not found in ${this.id}`)();\n texturesRenderable = false;\n }\n }\n\n // TODO - remove this should be handled by ExternalTexture\n // for (const [, texture] of Object.entries(this.bindings)) {\n // if (texture instanceof WEBGLTexture) {\n // texture.update();\n // }\n // }\n\n return texturesRenderable;\n }\n\n /** Apply any bindings (before each draw call) */\n _applyBindings(bindings: Bindings, _options?: {disableWarnings?: boolean}) {\n this._syncLinkStatus();\n\n // If we are using async linking, we need to wait until linking completes\n if (this.linkStatus !== 'success') {\n return;\n }\n\n const {gl} = this.device;\n gl.useProgram(this.handle);\n\n let textureUnit = 0;\n let uniformBufferIndex = 0;\n for (const binding of this.shaderLayout.bindings) {\n const value = getBindingValueForLayoutBinding(bindings, binding.name);\n if (!value) {\n throw new Error(`No value for binding ${binding.name} in ${this.id}`);\n }\n switch (binding.type) {\n case 'uniform':\n // Set buffer\n const {name} = binding;\n const location = gl.getUniformBlockIndex(this.handle, name);\n if ((location as GL) === GL.INVALID_INDEX) {\n throw new Error(`Invalid uniform block name ${name}`);\n }\n gl.uniformBlockBinding(this.handle, location, uniformBufferIndex);\n if (value instanceof WEBGLBuffer) {\n gl.bindBufferBase(GL.UNIFORM_BUFFER, uniformBufferIndex, value.handle);\n } else {\n const bufferBinding = value as {buffer: WEBGLBuffer; offset?: number; size?: number};\n gl.bindBufferRange(\n GL.UNIFORM_BUFFER,\n uniformBufferIndex,\n bufferBinding.buffer.handle,\n bufferBinding.offset || 0,\n bufferBinding.size || bufferBinding.buffer.byteLength - (bufferBinding.offset || 0)\n );\n }\n uniformBufferIndex += 1;\n break;\n\n case 'texture':\n if (\n !(\n value instanceof WEBGLTextureView ||\n value instanceof WEBGLTexture ||\n value instanceof WEBGLFramebuffer\n )\n ) {\n throw new Error('texture');\n }\n let texture: WEBGLTexture;\n if (value instanceof WEBGLTextureView) {\n texture = value.texture;\n } else if (value instanceof WEBGLTexture) {\n texture = value;\n } else if (\n value instanceof WEBGLFramebuffer &&\n value.colorAttachments[0] instanceof WEBGLTextureView\n ) {\n log.warn(\n 'Passing framebuffer in texture binding may be deprecated. Use fbo.colorAttachments[0] instead'\n )();\n texture = value.colorAttachments[0].texture;\n } else {\n throw new Error('No texture');\n }\n\n gl.activeTexture(GL.TEXTURE0 + textureUnit);\n gl.bindTexture(texture.glTarget, texture.handle);\n // gl.bindSampler(textureUnit, sampler.handle);\n textureUnit += 1;\n break;\n\n case 'sampler':\n // ignore\n break;\n\n case 'storage':\n case 'read-only-storage':\n throw new Error(`binding type '${binding.type}' not supported in WebGL`);\n }\n }\n }\n\n /**\n * Due to program sharing, uniforms need to be reset before every draw call\n * (though caching will avoid redundant WebGL calls)\n */\n _applyUniforms(uniforms: Record) {\n for (const uniformLayout of this.shaderLayout.uniforms || []) {\n const {name, location, type, textureUnit} = uniformLayout;\n const value = uniforms[name] ?? textureUnit;\n if (value !== undefined) {\n setUniform(this.device.gl, location, type, value);\n }\n }\n }\n\n private _syncLinkStatus(): void {\n this.linkStatus = (this.sharedRenderPipeline as WEBGLSharedRenderPipeline).linkStatus;\n }\n}\n\n/**\n * Merges an provided shader layout into a base shader layout\n * In WebGL, this allows the auto generated shader layout to be overridden by the application\n * Typically to change the format of the vertex attributes (from float32x4 to uint8x4 etc).\n * @todo Drop this? Aren't all use cases covered by mergeBufferLayout()?\n */\nfunction mergeShaderLayout(baseLayout: ShaderLayout, overrideLayout: ShaderLayout): ShaderLayout {\n // Deep clone the base layout\n const mergedLayout: ShaderLayout = {\n ...baseLayout,\n attributes: baseLayout.attributes.map(attribute => ({...attribute})),\n bindings: baseLayout.bindings.map(binding => ({...binding}))\n };\n // Merge the attributes\n for (const attribute of overrideLayout?.attributes || []) {\n const baseAttribute = mergedLayout.attributes.find(attr => attr.name === attribute.name);\n if (!baseAttribute) {\n log.warn(`shader layout attribute ${attribute.name} not present in shader`);\n } else {\n baseAttribute.type = attribute.type || baseAttribute.type;\n baseAttribute.stepMode = attribute.stepMode || baseAttribute.stepMode;\n }\n }\n\n for (const binding of overrideLayout?.bindings || []) {\n const baseBinding = getShaderLayoutBindingByName(mergedLayout, binding.name);\n if (!baseBinding) {\n log.warn(`shader layout binding ${binding.name} not present in shader`);\n continue;\n }\n Object.assign(baseBinding, binding);\n }\n return mergedLayout;\n}\n\nfunction getShaderLayoutBindingByName(\n shaderLayout: ShaderLayout,\n bindingName: string\n): ShaderLayout['bindings'][number] | undefined {\n return shaderLayout.bindings.find(\n binding =>\n binding.name === bindingName ||\n binding.name === `${bindingName}Uniforms` ||\n `${binding.name}Uniforms` === bindingName\n );\n}\n\nfunction getBindingValueForLayoutBinding(\n bindings: Bindings,\n bindingName: string\n): Bindings[string] | undefined {\n return (\n bindings[bindingName] ||\n bindings[`${bindingName}Uniforms`] ||\n bindings[bindingName.replace(/Uniforms$/, '')]\n );\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {VariableShaderType, SignedDataType, VertexFormat, NormalizedDataType} from '@luma.gl/core';\nimport {GL, GLUniformType, GLSamplerType, GLDataType} from '@luma.gl/webgl/constants';\n\nexport type TextureBindingInfo = {\n viewDimension: '1d' | '2d' | '2d-array' | 'cube' | 'cube-array' | '3d';\n sampleType: 'float' | 'unfilterable-float' | 'depth' | 'sint' | 'uint';\n};\n\n/** Converts to a luma shadertype to a GL data type (GL.BYTE, GL.FLOAT32 etc) */\nexport function convertDataTypeToGLDataType(normalizedType: NormalizedDataType): GLDataType {\n return NORMALIZED_SHADER_TYPE_TO_WEBGL[normalizedType];\n}\n\n/** Convert a WebGL \"compisite type (e.g. GL.VEC3) into the corresponding luma shader uniform type */\nexport function convertGLUniformTypeToShaderVariableType(\n glUniformType: GLUniformType\n): VariableShaderType {\n return WEBGL_SHADER_TYPES[glUniformType];\n}\n\n/** Check if a WebGL \"uniform:\" is a texture binding */\nexport function isGLSamplerType(type: GLUniformType | GLSamplerType): type is GLSamplerType {\n // @ts-ignore TODO\n return Boolean(WEBGL_SAMPLER_TO_TEXTURE_BINDINGS[type]);\n}\n\n/* Get luma texture binding info (viewDimension and sampleType) from a WebGL \"sampler\" binding */\nexport function getTextureBindingFromGLSamplerType(\n glSamplerType: GLSamplerType\n): TextureBindingInfo {\n return WEBGL_SAMPLER_TO_TEXTURE_BINDINGS[glSamplerType];\n}\n\n/** Get vertex format from GL constants */\nexport function getVertexFormatFromGL(type: GLDataType, components: 1 | 2 | 3 | 4): VertexFormat {\n const base = getVertexTypeFromGL(type);\n // biome-ignore format: preserve layout\n switch (components) {\n case 1: return base;\n case 2: return `${base}x2`;\n // @ts-expect-error - deal with lack of \"unaligned\" formats\n case 3: return `${base}x3`;\n case 4: return `${base}x4`;\n }\n // @ts-ignore unreachable\n throw new Error(String(components));\n}\n\n/** Get data type from GL constants */\nexport function getVertexTypeFromGL(glType: GLDataType, normalized = false): NormalizedDataType {\n const index = normalized ? 1 : 0;\n return WEBGL_TO_NORMALIZED_DATA_TYPE[glType][index];\n}\n\n// Composite types table\n// @ts-ignore TODO - fix the type confusion here\nconst WEBGL_SHADER_TYPES: Record = {\n [GL.FLOAT]: 'f32',\n [GL.FLOAT_VEC2]: 'vec2',\n [GL.FLOAT_VEC3]: 'vec3',\n [GL.FLOAT_VEC4]: 'vec4',\n\n [GL.INT]: 'i32',\n [GL.INT_VEC2]: 'vec2',\n [GL.INT_VEC3]: 'vec3',\n [GL.INT_VEC4]: 'vec4',\n\n [GL.UNSIGNED_INT]: 'u32',\n [GL.UNSIGNED_INT_VEC2]: 'vec2',\n [GL.UNSIGNED_INT_VEC3]: 'vec3',\n [GL.UNSIGNED_INT_VEC4]: 'vec4',\n\n [GL.BOOL]: 'f32',\n [GL.BOOL_VEC2]: 'vec2',\n [GL.BOOL_VEC3]: 'vec3',\n [GL.BOOL_VEC4]: 'vec4',\n\n // TODO - are sizes/components below correct?\n [GL.FLOAT_MAT2]: 'mat2x2',\n [GL.FLOAT_MAT2x3]: 'mat2x3',\n [GL.FLOAT_MAT2x4]: 'mat2x4',\n\n [GL.FLOAT_MAT3x2]: 'mat3x2',\n [GL.FLOAT_MAT3]: 'mat3x3',\n [GL.FLOAT_MAT3x4]: 'mat3x4',\n\n [GL.FLOAT_MAT4x2]: 'mat4x2',\n [GL.FLOAT_MAT4x3]: 'mat4x3',\n [GL.FLOAT_MAT4]: 'mat4x4'\n};\n\nconst WEBGL_SAMPLER_TO_TEXTURE_BINDINGS: Record = {\n [GL.SAMPLER_2D]: {viewDimension: '2d', sampleType: 'float'},\n [GL.SAMPLER_CUBE]: {viewDimension: 'cube', sampleType: 'float'},\n [GL.SAMPLER_3D]: {viewDimension: '3d', sampleType: 'float'},\n [GL.SAMPLER_2D_SHADOW]: {viewDimension: '3d', sampleType: 'depth'},\n [GL.SAMPLER_2D_ARRAY]: {viewDimension: '2d-array', sampleType: 'float'},\n [GL.SAMPLER_2D_ARRAY_SHADOW]: {viewDimension: '2d-array', sampleType: 'depth'},\n [GL.SAMPLER_CUBE_SHADOW]: {viewDimension: 'cube', sampleType: 'float'},\n [GL.INT_SAMPLER_2D]: {viewDimension: '2d', sampleType: 'sint'},\n [GL.INT_SAMPLER_3D]: {viewDimension: '3d', sampleType: 'sint'},\n [GL.INT_SAMPLER_CUBE]: {viewDimension: 'cube', sampleType: 'sint'},\n [GL.INT_SAMPLER_2D_ARRAY]: {viewDimension: '2d-array', sampleType: 'uint'},\n [GL.UNSIGNED_INT_SAMPLER_2D]: {viewDimension: '2d', sampleType: 'uint'},\n [GL.UNSIGNED_INT_SAMPLER_3D]: {viewDimension: '3d', sampleType: 'uint'},\n [GL.UNSIGNED_INT_SAMPLER_CUBE]: {viewDimension: 'cube', sampleType: 'uint'},\n [GL.UNSIGNED_INT_SAMPLER_2D_ARRAY]: {viewDimension: '2d-array', sampleType: 'uint'}\n};\n\n/** Map from WebGL normalized types to WebGL */\nconst NORMALIZED_SHADER_TYPE_TO_WEBGL: Record = {\n uint8: GL.UNSIGNED_BYTE,\n sint8: GL.BYTE,\n unorm8: GL.UNSIGNED_BYTE,\n snorm8: GL.BYTE,\n uint16: GL.UNSIGNED_SHORT,\n sint16: GL.SHORT,\n unorm16: GL.UNSIGNED_SHORT,\n snorm16: GL.SHORT,\n uint32: GL.UNSIGNED_INT,\n sint32: GL.INT,\n // WebGPU does not support normalized 32 bit integer attributes\n // 'unorm32': GL.UNSIGNED_INT,\n // 'snorm32': GL.INT,\n float16: GL.HALF_FLOAT,\n float32: GL.FLOAT\n};\n\n/* Map from WebGL types to webgpu normalized types */\nconst WEBGL_TO_NORMALIZED_DATA_TYPE: Record = {\n [GL.BYTE]: ['sint8', 'snorm16'],\n [GL.UNSIGNED_BYTE]: ['uint8', 'unorm8'],\n [GL.SHORT]: ['sint16', 'unorm16'],\n [GL.UNSIGNED_SHORT]: ['uint16', 'unorm16'],\n [GL.INT]: ['sint32', 'sint32'],\n [GL.UNSIGNED_INT]: ['uint32', 'uint32'],\n [GL.FLOAT]: ['float32', 'float32'],\n [GL.HALF_FLOAT]: ['float16', 'float16']\n};\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {\n ShaderLayout,\n UniformBinding,\n UniformBlockBinding,\n AttributeDeclaration,\n VaryingBinding,\n AttributeShaderType\n} from '@luma.gl/core';\nimport {getVariableShaderTypeInfo, assertDefined, log} from '@luma.gl/core';\n\nimport {GL, GLUniformType} from '@luma.gl/webgl/constants';\nimport {\n isGLSamplerType,\n getTextureBindingFromGLSamplerType,\n convertGLUniformTypeToShaderVariableType\n} from '../converters/webgl-shadertypes';\n\n/**\n * Extract metadata describing binding information for a program's shaders\n * Note: `linkProgram()` needs to have been called\n * (although linking does not need to have been successful).\n */\nexport function getShaderLayoutFromGLSL(\n gl: WebGL2RenderingContext,\n program: WebGLProgram\n): ShaderLayout {\n const shaderLayout: ShaderLayout = {\n attributes: [],\n bindings: []\n };\n\n shaderLayout.attributes = readAttributeDeclarations(gl, program);\n\n // Uniform blocks\n const uniformBlocks: UniformBlockBinding[] = readUniformBlocks(gl, program);\n for (const uniformBlock of uniformBlocks) {\n const uniforms = uniformBlock.uniforms.map(uniform => ({\n name: uniform.name,\n format: uniform.format,\n byteOffset: uniform.byteOffset,\n byteStride: uniform.byteStride,\n arrayLength: uniform.arrayLength\n }));\n shaderLayout.bindings.push({\n type: 'uniform',\n name: uniformBlock.name,\n group: 0,\n location: uniformBlock.location,\n visibility: (uniformBlock.vertex ? 0x1 : 0) & (uniformBlock.fragment ? 0x2 : 0),\n minBindingSize: uniformBlock.byteLength,\n uniforms\n });\n }\n\n const uniforms: UniformBinding[] = readUniformBindings(gl, program);\n let textureUnit = 0;\n for (const uniform of uniforms) {\n if (isGLSamplerType(uniform.type)) {\n const {viewDimension, sampleType} = getTextureBindingFromGLSamplerType(uniform.type);\n shaderLayout.bindings.push({\n type: 'texture',\n name: uniform.name,\n group: 0,\n location: textureUnit,\n viewDimension,\n sampleType\n });\n\n // @ts-expect-error\n uniform.textureUnit = textureUnit;\n textureUnit += 1;\n }\n }\n\n if (uniforms.length) {\n shaderLayout.uniforms = uniforms;\n }\n\n // Varyings\n const varyings: VaryingBinding[] = readVaryings(gl, program);\n // Note - samplers are always in unform bindings, even if uniform blocks are used\n if (varyings?.length) {\n shaderLayout.varyings = varyings;\n }\n\n return shaderLayout;\n}\n\n// HELPERS\n\n/**\n * Extract info about all transform feedback varyings\n *\n * linkProgram needs to have been called, although linking does not need to have been successful\n */\nfunction readAttributeDeclarations(\n gl: WebGL2RenderingContext,\n program: WebGLProgram\n): AttributeDeclaration[] {\n const attributes: AttributeDeclaration[] = [];\n\n const count = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);\n\n for (let index = 0; index < count; index++) {\n const activeInfo = gl.getActiveAttrib(program, index);\n if (!activeInfo) {\n throw new Error('activeInfo');\n }\n const {name, type: compositeType /* , size*/} = activeInfo;\n const location = gl.getAttribLocation(program, name);\n // Add only user provided attributes, for built-in attributes like `gl_InstanceID` location will be < 0\n if (location >= 0) {\n const attributeType = convertGLUniformTypeToShaderVariableType(compositeType);\n\n // Whether an attribute is instanced is essentially fixed by the structure of the shader code,\n // so it is arguably a static property of the shader.\n // There is no hint in the shader declarations\n // Heuristic: Any attribute name containing the word \"instance\" will be assumed to be instanced\n const stepMode = /instance/i.test(name) ? 'instance' : 'vertex';\n\n attributes.push({\n name,\n location,\n stepMode,\n type: attributeType as AttributeShaderType\n // size - for arrays, size is the number of elements in the array\n });\n }\n }\n\n // Sort by declaration order\n attributes.sort((a: AttributeDeclaration, b: AttributeDeclaration) => a.location - b.location);\n return attributes;\n}\n\n/**\n * Extract info about all transform feedback varyings\n *\n * linkProgram needs to have been called, although linking does not need to have been successful\n */\nfunction readVaryings(gl: WebGL2RenderingContext, program: WebGLProgram): VaryingBinding[] {\n const varyings: VaryingBinding[] = [];\n\n const count = gl.getProgramParameter(program, GL.TRANSFORM_FEEDBACK_VARYINGS);\n for (let location = 0; location < count; location++) {\n const activeInfo = gl.getTransformFeedbackVarying(program, location);\n if (!activeInfo) {\n throw new Error('activeInfo');\n }\n const {name, type: glUniformType, size} = activeInfo;\n const uniformType = convertGLUniformTypeToShaderVariableType(glUniformType as GLUniformType);\n const {type, components} = getVariableShaderTypeInfo(uniformType);\n varyings.push({location, name, type, size: size * components});\n }\n\n varyings.sort((a, b) => a.location - b.location);\n return varyings;\n}\n\n/**\n * Extract info about all uniforms\n *\n * Query uniform locations and build name to setter map.\n */\nfunction readUniformBindings(gl: WebGL2RenderingContext, program: WebGLProgram): UniformBinding[] {\n const uniforms: UniformBinding[] = [];\n\n const uniformCount = gl.getProgramParameter(program, GL.ACTIVE_UNIFORMS);\n for (let i = 0; i < uniformCount; i++) {\n const activeInfo = gl.getActiveUniform(program, i);\n if (!activeInfo) {\n throw new Error('activeInfo');\n }\n const {name: rawName, size, type} = activeInfo;\n const {name, isArray} = parseUniformName(rawName);\n let webglLocation = gl.getUniformLocation(program, name);\n const uniformInfo = {\n // WebGL locations are uniquely typed but just numbers\n location: webglLocation as number,\n name,\n size,\n type,\n isArray\n };\n uniforms.push(uniformInfo);\n\n // Array (e.g. matrix) uniforms can occupy several 4x4 byte banks\n if (uniformInfo.size > 1) {\n for (let j = 0; j < uniformInfo.size; j++) {\n const elementName = `${name}[${j}]`;\n\n webglLocation = gl.getUniformLocation(program, elementName);\n\n const arrayElementUniformInfo = {\n ...uniformInfo,\n name: elementName,\n location: webglLocation as number\n };\n\n uniforms.push(arrayElementUniformInfo);\n }\n }\n }\n return uniforms;\n}\n\n/**\n * Extract info about all \"active\" uniform blocks\n * @note In WebGL, \"active\" just means that unused (inactive) blocks may have been optimized away during linking)\n */\nfunction readUniformBlocks(\n gl: WebGL2RenderingContext,\n program: WebGLProgram\n): UniformBlockBinding[] {\n const getBlockParameter = (blockIndex: number, pname: GL): any =>\n gl.getActiveUniformBlockParameter(program, blockIndex, pname);\n\n const uniformBlocks: UniformBlockBinding[] = [];\n\n const blockCount = gl.getProgramParameter(program, GL.ACTIVE_UNIFORM_BLOCKS);\n for (let blockIndex = 0; blockIndex < blockCount; blockIndex++) {\n const blockInfo: UniformBlockBinding = {\n name: gl.getActiveUniformBlockName(program, blockIndex) || '',\n location: getBlockParameter(blockIndex, GL.UNIFORM_BLOCK_BINDING),\n byteLength: getBlockParameter(blockIndex, GL.UNIFORM_BLOCK_DATA_SIZE),\n vertex: getBlockParameter(blockIndex, GL.UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER),\n fragment: getBlockParameter(blockIndex, GL.UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER),\n uniformCount: getBlockParameter(blockIndex, GL.UNIFORM_BLOCK_ACTIVE_UNIFORMS),\n uniforms: [] as any[]\n };\n\n const uniformIndices =\n (getBlockParameter(blockIndex, GL.UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES) as number[]) || [];\n\n const uniformType = gl.getActiveUniforms(program, uniformIndices, GL.UNIFORM_TYPE); // Array of GLenum indicating the types of the uniforms.\n const uniformArrayLength = gl.getActiveUniforms(program, uniformIndices, GL.UNIFORM_SIZE); // Array of GLuint indicating the sizes of the uniforms.\n // const uniformBlockIndex = gl.getActiveUniforms(\n // program,\n // uniformIndices,\n // GL.UNIFORM_BLOCK_INDEX\n // ); // Array of GLint indicating the block indices of the uniforms.\n const uniformOffset = gl.getActiveUniforms(program, uniformIndices, GL.UNIFORM_OFFSET); // Array of GLint indicating the uniform buffer offsets.\n const uniformStride = gl.getActiveUniforms(program, uniformIndices, GL.UNIFORM_ARRAY_STRIDE); // Array of GLint indicating the strides between the elements.\n // const uniformMatrixStride = gl.getActiveUniforms(\n // program,\n // uniformIndices,\n // GL.UNIFORM_MATRIX_STRIDE\n // ); // Array of GLint indicating the strides between columns of a column-major matrix or a row-major matrix.\n // const uniformRowMajor = gl.getActiveUniforms(program, uniformIndices, GL.UNIFORM_IS_ROW_MAJOR);\n for (let i = 0; i < blockInfo.uniformCount; ++i) {\n const uniformIndex = uniformIndices[i];\n if (uniformIndex !== undefined) {\n const activeInfo = gl.getActiveUniform(program, uniformIndex);\n if (!activeInfo) {\n throw new Error('activeInfo');\n }\n\n const format = convertGLUniformTypeToShaderVariableType(uniformType[i]);\n\n blockInfo.uniforms.push({\n name: activeInfo.name,\n format,\n type: uniformType[i],\n arrayLength: uniformArrayLength[i],\n byteOffset: uniformOffset[i],\n byteStride: uniformStride[i]\n // matrixStride: uniformStride[i],\n // rowMajor: uniformRowMajor[i]\n });\n }\n }\n\n const uniformInstancePrefixes = new Set(\n blockInfo.uniforms\n .map(uniform => uniform.name.split('.')[0])\n .filter((instanceName): instanceName is string => Boolean(instanceName))\n );\n const blockAlias = blockInfo.name.replace(/Uniforms$/, '');\n if (\n uniformInstancePrefixes.size === 1 &&\n !uniformInstancePrefixes.has(blockInfo.name) &&\n !uniformInstancePrefixes.has(blockAlias)\n ) {\n const [instanceName] = uniformInstancePrefixes;\n log.warn(\n `Uniform block \"${blockInfo.name}\" uses GLSL instance \"${instanceName}\". ` +\n `luma.gl binds uniform buffers by block name (\"${blockInfo.name}\") and alias (\"${blockAlias}\"). ` +\n 'Prefer matching the instance name to one of those to avoid confusing silent mismatches.'\n )();\n }\n\n uniformBlocks.push(blockInfo);\n }\n\n uniformBlocks.sort((a, b) => a.location - b.location);\n return uniformBlocks;\n}\n\n/**\n * TOOD - compare with a above, confirm copy, then delete\n const bindings: Binding[] = [];\n const count = gl.getProgramParameter(program, gl.ACTIVE_UNIFORM_BLOCKS);\n for (let blockIndex = 0; blockIndex < count; blockIndex++) {\n const vertex = gl.getActiveUniformBlockParameter(program, blockIndex, gl.UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER),\n const fragment = gl.getActiveUniformBlockParameter(program, blockIndex, gl.UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER),\n const visibility = (vertex) + (fragment);\n const binding: BufferBinding = {\n location: gl.getActiveUniformBlockParameter(program, blockIndex, gl.UNIFORM_BLOCK_BINDING),\n // name: gl.getActiveUniformBlockName(program, blockIndex),\n type: 'uniform',\n visibility,\n minBindingSize: gl.getActiveUniformBlockParameter(program, blockIndex, gl.UNIFORM_BLOCK_DATA_SIZE),\n // uniformCount: gl.getActiveUniformBlockParameter(program, blockIndex, gl.UNIFORM_BLOCK_ACTIVE_UNIFORMS),\n // uniformIndices: gl.getActiveUniformBlockParameter(program, blockIndex, gl.UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES),\n }\n bindings.push(binding);\n }\n*/\n\n// HELPERS\n\nfunction parseUniformName(name: string): {name: string; length: number; isArray: boolean} {\n // Shortcut to avoid redundant or bad matches\n if (name[name.length - 1] !== ']') {\n return {\n name,\n length: 1,\n isArray: false\n };\n }\n\n // if array name then clean the array brackets\n const UNIFORM_NAME_REGEXP = /([^[]*)(\\[[0-9]+\\])?/;\n const matches = UNIFORM_NAME_REGEXP.exec(name);\n const uniformName = assertDefined(matches?.[1], `Failed to parse GLSL uniform name ${name}`);\n return {\n name: uniformName,\n // TODO - is this a bug, shouldn't we return the value?\n length: matches?.[2] ? 1 : 0,\n isArray: Boolean(matches?.[2])\n };\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {GL} from '@luma.gl/webgl/constants';\nimport {\n SharedRenderPipeline,\n log,\n type ShaderLayout,\n type SharedRenderPipelineProps\n} from '@luma.gl/core';\n\nimport {getShaderLayoutFromGLSL} from '../helpers/get-shader-layout-from-glsl';\nimport {isGLSamplerType} from '../converters/webgl-shadertypes';\nimport type {WebGLDevice} from '../webgl-device';\nimport type {WEBGLShader} from './webgl-shader';\n\nconst LOG_PROGRAM_PERF_PRIORITY = 4;\n\nexport class WEBGLSharedRenderPipeline extends SharedRenderPipeline {\n readonly device: WebGLDevice;\n readonly handle: WebGLProgram;\n readonly vs: WEBGLShader;\n readonly fs: WEBGLShader;\n introspectedLayout: ShaderLayout = {attributes: [], bindings: [], uniforms: []};\n linkStatus: 'pending' | 'success' | 'error' = 'pending';\n\n constructor(\n device: WebGLDevice,\n props: SharedRenderPipelineProps & {\n handle?: WebGLProgram;\n vs: WEBGLShader;\n fs: WEBGLShader;\n }\n ) {\n super(device, props);\n this.device = device;\n this.handle = props.handle || this.device.gl.createProgram();\n this.vs = props.vs;\n this.fs = props.fs;\n\n if (props.varyings && props.varyings.length > 0) {\n this.device.gl.transformFeedbackVaryings(\n this.handle,\n props.varyings,\n props.bufferMode || GL.SEPARATE_ATTRIBS\n );\n }\n\n this._linkShaders();\n // Introspection happens after linking to build wrapper-facing layout metadata.\n // It is not a prerequisite for deciding whether a shared `WebGLProgram` can be\n // reused; that decision must remain based on the shared-pipeline cache key alone.\n log.time(3, `RenderPipeline ${this.id} - shaderLayout introspection`)();\n this.introspectedLayout = getShaderLayoutFromGLSL(this.device.gl, this.handle);\n log.timeEnd(3, `RenderPipeline ${this.id} - shaderLayout introspection`)();\n }\n\n override destroy(): void {\n if (this.destroyed) {\n return;\n }\n\n this.device.gl.useProgram(null);\n this.device.gl.deleteProgram(this.handle);\n // @ts-expect-error\n this.handle.destroyed = true;\n this.destroyResource();\n }\n\n protected async _linkShaders() {\n const {gl} = this.device;\n gl.attachShader(this.handle, this.vs.handle);\n gl.attachShader(this.handle, this.fs.handle);\n log.time(LOG_PROGRAM_PERF_PRIORITY, `linkProgram for ${this.id}`)();\n gl.linkProgram(this.handle);\n log.timeEnd(LOG_PROGRAM_PERF_PRIORITY, `linkProgram for ${this.id}`)();\n\n if (!this.device.features.has('compilation-status-async-webgl')) {\n const status = this._getLinkStatus();\n this._reportLinkStatus(status);\n return;\n }\n\n log.once(1, 'RenderPipeline linking is asynchronous')();\n await this._waitForLinkComplete();\n log.info(2, `RenderPipeline ${this.id} - async linking complete: ${this.linkStatus}`)();\n const status = this._getLinkStatus();\n this._reportLinkStatus(status);\n }\n\n async _reportLinkStatus(status: 'success' | 'link-error' | 'validation-error'): Promise {\n switch (status) {\n case 'success':\n return;\n\n default:\n const errorType = status === 'link-error' ? 'Link error' : 'Validation error';\n switch (this.vs.compilationStatus) {\n case 'error':\n this.vs.debugShader();\n throw new Error(`${this} ${errorType} during compilation of ${this.vs}`);\n case 'pending':\n await this.vs.asyncCompilationStatus;\n this.vs.debugShader();\n break;\n case 'success':\n break;\n }\n\n switch (this.fs?.compilationStatus) {\n case 'error':\n this.fs.debugShader();\n throw new Error(`${this} ${errorType} during compilation of ${this.fs}`);\n case 'pending':\n await this.fs.asyncCompilationStatus;\n this.fs.debugShader();\n break;\n case 'success':\n break;\n }\n\n const linkErrorLog = this.device.gl.getProgramInfoLog(this.handle);\n this.device.reportError(\n new Error(`${errorType} during ${status}: ${linkErrorLog}`),\n this\n )();\n this.device.debug();\n }\n }\n\n _getLinkStatus(): 'success' | 'link-error' | 'validation-error' {\n const {gl} = this.device;\n const linked = gl.getProgramParameter(this.handle, GL.LINK_STATUS);\n if (!linked) {\n this.linkStatus = 'error';\n return 'link-error';\n }\n\n this._initializeSamplerUniforms();\n gl.validateProgram(this.handle);\n const validated = gl.getProgramParameter(this.handle, GL.VALIDATE_STATUS);\n if (!validated) {\n this.linkStatus = 'error';\n return 'validation-error';\n }\n\n this.linkStatus = 'success';\n return 'success';\n }\n\n _initializeSamplerUniforms(): void {\n const {gl} = this.device;\n gl.useProgram(this.handle);\n\n let textureUnit = 0;\n const uniformCount = gl.getProgramParameter(this.handle, GL.ACTIVE_UNIFORMS);\n for (let uniformIndex = 0; uniformIndex < uniformCount; uniformIndex++) {\n const activeInfo = gl.getActiveUniform(this.handle, uniformIndex);\n if (activeInfo && isGLSamplerType(activeInfo.type)) {\n const isArray = activeInfo.name.endsWith('[0]');\n const uniformName = isArray ? activeInfo.name.slice(0, -3) : activeInfo.name;\n const location = gl.getUniformLocation(this.handle, uniformName);\n\n if (location !== null) {\n textureUnit = this._assignSamplerUniform(location, activeInfo, isArray, textureUnit);\n }\n }\n }\n }\n\n _assignSamplerUniform(\n location: WebGLUniformLocation,\n activeInfo: WebGLActiveInfo,\n isArray: boolean,\n textureUnit: number\n ): number {\n const {gl} = this.device;\n\n if (isArray && activeInfo.size > 1) {\n const textureUnits = Int32Array.from(\n {length: activeInfo.size},\n (_, arrayIndex) => textureUnit + arrayIndex\n );\n gl.uniform1iv(location, textureUnits);\n return textureUnit + activeInfo.size;\n }\n\n gl.uniform1i(location, textureUnit);\n return textureUnit + 1;\n }\n\n async _waitForLinkComplete(): Promise {\n const waitMs = async (ms: number) => await new Promise(resolve => setTimeout(resolve, ms));\n const DELAY_MS = 10;\n\n if (!this.device.features.has('compilation-status-async-webgl')) {\n await waitMs(DELAY_MS);\n return;\n }\n\n const {gl} = this.device;\n for (;;) {\n const complete = gl.getProgramParameter(this.handle, GL.COMPLETION_STATUS_KHR);\n if (complete) {\n return;\n }\n await waitMs(DELAY_MS);\n }\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {\n type CommandBufferProps,\n type CopyBufferToBufferOptions,\n type CopyBufferToTextureOptions,\n type CopyTextureToBufferOptions,\n type CopyTextureToTextureOptions,\n type TextureReadOptions,\n // type ClearTextureOptions,\n CommandBuffer,\n Texture,\n Framebuffer,\n assertDefined\n} from '@luma.gl/core';\nimport {GL, type GLTextureTarget, type GLTextureCubeMapTarget} from '@luma.gl/webgl/constants';\n\nimport {getTextureFormatWebGL} from '../converters/webgl-texture-table';\nimport {WebGLDevice} from '../webgl-device';\nimport {WEBGLBuffer} from './webgl-buffer';\nimport {WEBGLTexture} from './webgl-texture';\nimport {WEBGLFramebuffer} from './webgl-framebuffer';\n\ntype CopyBufferToBufferCommand = {\n name: 'copy-buffer-to-buffer';\n options: CopyBufferToBufferOptions;\n};\n\ntype CopyBufferToTextureCommand = {\n name: 'copy-buffer-to-texture';\n options: CopyBufferToTextureOptions;\n};\n\ntype CopyTextureToBufferCommand = {\n name: 'copy-texture-to-buffer';\n options: CopyTextureToBufferOptions;\n};\n\ntype CopyTextureToTextureCommand = {\n name: 'copy-texture-to-texture';\n options: CopyTextureToTextureOptions;\n};\n\ntype ClearTextureCommand = {\n name: 'clear-texture';\n options: {}; // ClearTextureOptions;\n};\n\ntype ReadTextureCommand = {\n name: 'read-texture';\n options: {}; // TextureReadOptions;\n};\n\ntype Command =\n | CopyBufferToBufferCommand\n | CopyBufferToTextureCommand\n | CopyTextureToBufferCommand\n | CopyTextureToTextureCommand\n | ClearTextureCommand\n | ReadTextureCommand;\n\nexport class WEBGLCommandBuffer extends CommandBuffer {\n readonly device: WebGLDevice;\n readonly handle = null;\n commands: Command[] = [];\n\n constructor(device: WebGLDevice, props: CommandBufferProps = {}) {\n super(device, props);\n this.device = device;\n }\n\n _executeCommands(commands: Command[] = this.commands) {\n for (const command of commands) {\n switch (command.name) {\n case 'copy-buffer-to-buffer':\n _copyBufferToBuffer(this.device, command.options);\n break;\n case 'copy-buffer-to-texture':\n _copyBufferToTexture(this.device, command.options);\n break;\n case 'copy-texture-to-buffer':\n _copyTextureToBuffer(this.device, command.options);\n break;\n case 'copy-texture-to-texture':\n _copyTextureToTexture(this.device, command.options);\n break;\n // case 'clear-texture':\n // _clearTexture(this.device, command.options);\n // break;\n default:\n throw new Error(command.name);\n }\n }\n }\n}\n\nfunction _copyBufferToBuffer(device: WebGLDevice, options: CopyBufferToBufferOptions): void {\n const source = options.sourceBuffer as WEBGLBuffer;\n const destination = options.destinationBuffer as WEBGLBuffer;\n\n // {In WebGL2 we can p}erform the copy on the GPU\n // Use GL.COPY_READ_BUFFER+GL.COPY_WRITE_BUFFER avoid disturbing other targets and locking type\n device.gl.bindBuffer(GL.COPY_READ_BUFFER, source.handle);\n device.gl.bindBuffer(GL.COPY_WRITE_BUFFER, destination.handle);\n device.gl.copyBufferSubData(\n GL.COPY_READ_BUFFER,\n GL.COPY_WRITE_BUFFER,\n options.sourceOffset ?? 0,\n options.destinationOffset ?? 0,\n options.size\n );\n device.gl.bindBuffer(GL.COPY_READ_BUFFER, null);\n device.gl.bindBuffer(GL.COPY_WRITE_BUFFER, null);\n}\n\n/**\n * Copies data from a Buffer object into a Texture object\n * NOTE: doesn't wait for copy to be complete\n */\nfunction _copyBufferToTexture(_device: WebGLDevice, _options: CopyBufferToTextureOptions): void {\n throw new Error('copyBufferToTexture is not supported in WebGL');\n}\n\n/**\n * Copies data from a Texture object into a Buffer object.\n * NOTE: doesn't wait for copy to be complete\n */\nfunction _copyTextureToBuffer(device: WebGLDevice, options: CopyTextureToBufferOptions): void {\n const {\n sourceTexture,\n mipLevel = 0,\n aspect = 'all',\n width = options.sourceTexture.width,\n height = options.sourceTexture.height,\n depthOrArrayLayers,\n origin = [0, 0, 0],\n destinationBuffer,\n byteOffset = 0,\n bytesPerRow,\n rowsPerImage\n } = options;\n\n if (sourceTexture instanceof Texture) {\n sourceTexture.readBuffer(\n {\n x: origin[0] ?? 0,\n y: origin[1] ?? 0,\n z: origin[2] ?? 0,\n width,\n height,\n depthOrArrayLayers,\n mipLevel,\n aspect,\n byteOffset\n } as TextureReadOptions & {byteOffset?: number},\n destinationBuffer\n );\n return;\n }\n\n // TODO - Not possible to read just stencil or depth part in WebGL?\n if (aspect !== 'all') {\n throw new Error('aspect not supported in WebGL');\n }\n\n // TODO - mipLevels are set when attaching texture to framebuffer\n if (mipLevel !== 0 || depthOrArrayLayers !== undefined || bytesPerRow || rowsPerImage) {\n throw new Error('not implemented');\n }\n\n // Asynchronous read (PIXEL_PACK_BUFFER) is WebGL2 only feature\n const {framebuffer, destroyFramebuffer} = getFramebuffer(sourceTexture);\n let prevHandle: WebGLFramebuffer | null | undefined;\n try {\n const webglBuffer = destinationBuffer as WEBGLBuffer;\n const sourceWidth = width || framebuffer.width;\n const sourceHeight = height || framebuffer.height;\n const colorAttachment0 = assertDefined(framebuffer.colorAttachments[0]);\n\n const sourceParams = getTextureFormatWebGL(colorAttachment0.texture.props.format);\n const sourceFormat = sourceParams.format;\n const sourceType = sourceParams.type;\n\n // if (!target) {\n // // Create new buffer with enough size\n // const components = glFormatToComponents(sourceFormat);\n // const byteCount = glTypeToBytes(sourceType);\n // const byteLength = byteOffset + sourceWidth * sourceHeight * components * byteCount;\n // target = device.createBuffer({byteLength});\n // }\n\n device.gl.bindBuffer(GL.PIXEL_PACK_BUFFER, webglBuffer.handle);\n // @ts-expect-error native bindFramebuffer is overridden by our state tracker\n prevHandle = device.gl.bindFramebuffer(GL.FRAMEBUFFER, framebuffer.handle);\n\n device.gl.readPixels(\n origin[0],\n origin[1],\n sourceWidth,\n sourceHeight,\n sourceFormat,\n sourceType,\n byteOffset\n );\n } finally {\n device.gl.bindBuffer(GL.PIXEL_PACK_BUFFER, null);\n // prevHandle may be unassigned if the try block failed before binding\n if (prevHandle !== undefined) {\n device.gl.bindFramebuffer(GL.FRAMEBUFFER, prevHandle);\n }\n\n if (destroyFramebuffer) {\n framebuffer.destroy();\n }\n }\n}\n\n/**\n * Copies data from a Framebuffer or a Texture object into a Buffer object.\n * NOTE: doesn't wait for copy to be complete, it programs GPU to perform a DMA transfer.\nexport function readPixelsToBuffer(\n source: Framebuffer | Texture,\n options?: {\n sourceX?: number;\n sourceY?: number;\n sourceFormat?: number;\n target?: Buffer; // A new Buffer object is created when not provided.\n targetByteOffset?: number; // byte offset in buffer object\n // following parameters are auto deduced if not provided\n sourceWidth?: number;\n sourceHeight?: number;\n sourceType?: number;\n }\n): Buffer\n */\n\n/**\n * Copy a rectangle from a Framebuffer or Texture object into a texture (at an offset)\n */\n// eslint-disable-next-line complexity, max-statements\nfunction _copyTextureToTexture(device: WebGLDevice, options: CopyTextureToTextureOptions): void {\n const {\n /** Texture to copy to/from. */\n sourceTexture,\n /** Mip-map level of the texture to copy to (Default 0) */\n destinationMipLevel = 0,\n /** Defines which aspects of the texture to copy to/from. */\n // aspect = 'all',\n /** Defines the origin of the copy - the minimum corner of the texture sub-region to copy from. */\n origin = [0, 0],\n\n /** Defines the origin of the copy - the minimum corner of the texture sub-region to copy to. */\n destinationOrigin = [0, 0, 0],\n\n /** Texture to copy to/from. */\n destinationTexture\n /** Mip-map level of the texture to copy to/from. (Default 0) */\n // destinationMipLevel = options.mipLevel,\n /** Defines the origin of the copy - the minimum corner of the texture sub-region to copy to/from. */\n // destinationOrigin = [0, 0],\n /** Defines which aspects of the texture to copy to/from. */\n // destinationAspect = options.aspect,\n } = options;\n\n let {\n width = options.destinationTexture.width,\n height = options.destinationTexture.height\n // depthOrArrayLayers = 0\n } = options;\n\n const {framebuffer, destroyFramebuffer} = getFramebuffer(sourceTexture);\n const [sourceX = 0, sourceY = 0] = origin;\n const [destinationX, destinationY, destinationZ] = destinationOrigin;\n\n // @ts-expect-error native bindFramebuffer is overridden by our state tracker\n const prevHandle: WebGLFramebuffer | null = device.gl.bindFramebuffer(\n GL.FRAMEBUFFER,\n framebuffer.handle\n );\n // TODO - support gl.readBuffer (WebGL2 only)\n // const prevBuffer = gl.readBuffer(attachment);\n\n let texture: WEBGLTexture;\n let textureTarget: GL;\n if (destinationTexture instanceof WEBGLTexture) {\n texture = destinationTexture;\n width = Number.isFinite(width) ? width : texture.width;\n height = Number.isFinite(height) ? height : texture.height;\n texture._bind(0);\n textureTarget = texture.glTarget;\n } else {\n throw new Error('invalid destination');\n }\n\n switch (textureTarget) {\n case GL.TEXTURE_2D:\n case GL.TEXTURE_CUBE_MAP:\n device.gl.copyTexSubImage2D(\n textureTarget,\n destinationMipLevel,\n destinationX,\n destinationY,\n sourceX,\n sourceY,\n width,\n height\n );\n break;\n case GL.TEXTURE_2D_ARRAY:\n case GL.TEXTURE_3D:\n device.gl.copyTexSubImage3D(\n textureTarget,\n destinationMipLevel,\n destinationX,\n destinationY,\n destinationZ,\n sourceX,\n sourceY,\n width,\n height\n );\n break;\n default:\n }\n\n if (texture) {\n texture._unbind();\n }\n device.gl.bindFramebuffer(GL.FRAMEBUFFER, prevHandle);\n if (destroyFramebuffer) {\n framebuffer.destroy();\n }\n}\n\n/** Clear one mip level of a texture *\nfunction _clearTexture(device: WebGLDevice, options: ClearTextureOptions) {\n const BORDER = 0;\n const {dimension, width, height, depth = 0, mipLevel = 0} = options;\n const {glInternalFormat, glFormat, glType, compressed} = options;\n const glTarget = getWebGLCubeFaceTarget(options.glTarget, dimension, depth);\n\n switch (dimension) {\n case '2d-array':\n case '3d':\n if (compressed) {\n // biome-ignore format: preserve layout\n device.gl.compressedTexImage3D(glTarget, mipLevel, glInternalFormat, width, height, depth, BORDER, null);\n } else {\n // biome-ignore format: preserve layout\n device.gl.texImage3D( glTarget, mipLevel, glInternalFormat, width, height, depth, BORDER, glFormat, glType, null);\n }\n break;\n\n case '2d':\n case 'cube':\n if (compressed) {\n // biome-ignore format: preserve layout\n device.gl.compressedTexImage2D(glTarget, mipLevel, glInternalFormat, width, height, BORDER, null);\n } else {\n // biome-ignore format: preserve layout\n device.gl.texImage2D(glTarget, mipLevel, glInternalFormat, width, height, BORDER, glFormat, glType, null);\n }\n break;\n\n default:\n throw new Error(dimension);\n }\n}\n */\n\n// function _readTexture(device: WebGLDevice, options: CopyTextureToBufferOptions) {}\n\n// HELPERS\n\n/**\n * In WebGL, cube maps specify faces by overriding target instead of using the depth parameter.\n * @note We still bind the texture using GL.TEXTURE_CUBE_MAP, but we need to use the face-specific target when setting mip levels.\n * @returns glTarget unchanged, if dimension !== 'cube'.\n */\nexport function getWebGLCubeFaceTarget(\n glTarget: GLTextureTarget,\n dimension: '1d' | '2d' | '2d-array' | 'cube' | 'cube-array' | '3d',\n level: number\n): GLTextureTarget | GLTextureCubeMapTarget {\n return dimension === 'cube' ? GL.TEXTURE_CUBE_MAP_POSITIVE_X + level : glTarget;\n}\n\n/** Wrap a texture in a framebuffer so that we can use WebGL APIs that work on framebuffers */\nfunction getFramebuffer(source: Texture | Framebuffer): {\n framebuffer: WEBGLFramebuffer;\n destroyFramebuffer: boolean;\n} {\n if (source instanceof Texture) {\n const {width, height, id} = source;\n const framebuffer = source.device.createFramebuffer({\n id: `framebuffer-for-${id}`,\n width,\n height,\n colorAttachments: [source]\n }) as unknown as WEBGLFramebuffer;\n\n return {framebuffer, destroyFramebuffer: true};\n }\n return {framebuffer: source as unknown as WEBGLFramebuffer, destroyFramebuffer: false};\n}\n\n/**\n * Returns number of components in a specific readPixels WebGL format\n * @todo use shadertypes utils instead?\n */\nexport function glFormatToComponents(format: GL): 1 | 2 | 3 | 4 {\n switch (format) {\n case GL.ALPHA:\n case GL.R32F:\n case GL.RED:\n return 1;\n case GL.RG32F:\n case GL.RG:\n return 2;\n case GL.RGB:\n case GL.RGB32F:\n return 3;\n case GL.RGBA:\n case GL.RGBA32F:\n return 4;\n // TODO: Add support for additional WebGL2 formats\n default:\n throw new Error('GLFormat');\n }\n}\n\n/**\n * Return byte count for given readPixels WebGL type\n * @todo use shadertypes utils instead?\n */\nexport function glTypeToBytes(type: GL): 1 | 2 | 4 {\n switch (type) {\n case GL.UNSIGNED_BYTE:\n return 1;\n case GL.UNSIGNED_SHORT_5_6_5:\n case GL.UNSIGNED_SHORT_4_4_4_4:\n case GL.UNSIGNED_SHORT_5_5_5_1:\n return 2;\n case GL.FLOAT:\n return 4;\n // TODO: Add support for additional WebGL2 types\n default:\n throw new Error('GLType');\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {NumericArray, NumberArray4} from '@math.gl/types';\nimport {RenderPass, RenderPassProps, RenderPassParameters} from '@luma.gl/core';\nimport {WebGLDevice} from '../webgl-device';\nimport {GL, GLParameters} from '@luma.gl/webgl/constants';\nimport {withGLParameters} from '../../context/state-tracker/with-parameters';\nimport {setGLParameters} from '../../context/parameters/unified-parameter-api';\nimport {WEBGLQuerySet} from './webgl-query-set';\nimport {WEBGLFramebuffer} from './webgl-framebuffer';\n\nconst COLOR_CHANNELS: NumberArray4 = [0x1, 0x2, 0x4, 0x8]; // GPUColorWrite RED, GREEN, BLUE, ALPHA\n\nexport class WEBGLRenderPass extends RenderPass {\n readonly device: WebGLDevice;\n readonly handle = null;\n\n /** Parameters that should be applied before each draw call */\n glParameters: GLParameters = {};\n\n constructor(device: WebGLDevice, props: RenderPassProps) {\n super(device, props);\n this.device = device;\n const webglFramebuffer = this.props.framebuffer as WEBGLFramebuffer | null;\n const isDefaultFramebuffer = !webglFramebuffer || webglFramebuffer.handle === null;\n\n if (isDefaultFramebuffer) {\n // Treat an explicit wrapper around the default framebuffer the same as the\n // implicit default path so draw buffer and viewport state stay valid.\n device.getDefaultCanvasContext()._resizeDrawingBufferIfNeeded();\n }\n\n // If no viewport is provided, apply reasonably defaults\n let viewport: NumberArray4 | undefined;\n if (!props?.parameters?.viewport) {\n if (!isDefaultFramebuffer && webglFramebuffer) {\n // Set the viewport to the size of the framebuffer\n const {width, height} = webglFramebuffer;\n viewport = [0, 0, width, height];\n } else {\n // Instead of using our own book-keeping, we can just read the values from the WebGL context\n const [width, height] = device.getDefaultCanvasContext().getDrawingBufferSize();\n viewport = [0, 0, width, height];\n }\n }\n\n // TODO - do parameters (scissorRect) affect the clear operation?\n this.device.pushState();\n this.setParameters({viewport, ...this.props.parameters});\n\n // Specify mapping of draw buffer locations to color attachments\n if (!isDefaultFramebuffer && webglFramebuffer?.colorAttachments.length) {\n const drawBuffers = webglFramebuffer.colorAttachments.map((_, i) => GL.COLOR_ATTACHMENT0 + i);\n this.device.gl.drawBuffers(drawBuffers);\n } else if (isDefaultFramebuffer) {\n // Default framebuffer only supports GL.BACK/GL.NONE draw buffers\n this.device.gl.drawBuffers([GL.BACK]);\n }\n\n // Hack - for now WebGL draws in \"immediate mode\" (instead of queueing the operations)...\n this.clear();\n\n if (this.props.timestampQuerySet && this.props.beginTimestampIndex !== undefined) {\n const webglQuerySet = this.props.timestampQuerySet as WEBGLQuerySet;\n webglQuerySet.writeTimestamp(this.props.beginTimestampIndex);\n }\n }\n\n end(): void {\n if (this.destroyed) {\n return;\n }\n if (this.props.timestampQuerySet && this.props.endTimestampIndex !== undefined) {\n const webglQuerySet = this.props.timestampQuerySet as WEBGLQuerySet;\n webglQuerySet.writeTimestamp(this.props.endTimestampIndex);\n }\n this.device.popState();\n // should add commands to CommandEncoder.\n this.destroy();\n }\n\n pushDebugGroup(groupLabel: string): void {}\n popDebugGroup(): void {}\n insertDebugMarker(markerLabel: string): void {}\n\n // beginOcclusionQuery(queryIndex: number): void;\n // endOcclusionQuery(): void;\n\n // executeBundles(bundles: Iterable): void;\n\n /**\n * Maps RenderPass parameters to GL parameters\n */\n setParameters(parameters: RenderPassParameters = {}): void {\n const glParameters: GLParameters = {...this.glParameters};\n\n // Framebuffers are specified using parameters in WebGL\n glParameters.framebuffer = this.props.framebuffer || null;\n\n if (this.props.depthReadOnly) {\n glParameters.depthMask = !this.props.depthReadOnly;\n }\n\n glParameters.stencilMask = this.props.stencilReadOnly ? 0 : 1;\n\n glParameters[GL.RASTERIZER_DISCARD] = this.props.discard;\n\n // Map the four renderpass parameters to WebGL parameters\n if (parameters.viewport) {\n // WebGPU viewports are 6 coordinates (X, Y, Z)\n if (parameters.viewport.length >= 6) {\n glParameters.viewport = parameters.viewport.slice(0, 4) as NumberArray4;\n glParameters.depthRange = [\n parameters.viewport[4] as number,\n parameters.viewport[5] as number\n ];\n } else {\n // WebGL viewports are 4 coordinates (X, Y)\n glParameters.viewport = parameters.viewport as NumberArray4;\n }\n }\n if (parameters.scissorRect) {\n glParameters.scissorTest = true;\n glParameters.scissor = parameters.scissorRect;\n }\n if (parameters.blendConstant) {\n glParameters.blendColor = parameters.blendConstant;\n }\n if (parameters.stencilReference !== undefined) {\n glParameters[GL.STENCIL_REF] = parameters.stencilReference;\n glParameters[GL.STENCIL_BACK_REF] = parameters.stencilReference;\n }\n\n if ('colorMask' in parameters) {\n glParameters.colorMask = COLOR_CHANNELS.map(channel =>\n Boolean(channel & (parameters.colorMask as number))\n );\n }\n\n this.glParameters = glParameters;\n\n setGLParameters(this.device.gl, glParameters);\n }\n\n beginOcclusionQuery(queryIndex: number): void {\n const webglQuerySet = this.props.occlusionQuerySet as WEBGLQuerySet;\n webglQuerySet?.beginOcclusionQuery();\n }\n\n override endOcclusionQuery(): void {\n const webglQuerySet = this.props.occlusionQuerySet as WEBGLQuerySet;\n webglQuerySet?.endOcclusionQuery();\n }\n\n // PRIVATE\n\n /**\n * Optionally clears depth, color and stencil buffers based on parameters\n */\n protected clear(): void {\n const glParameters: GLParameters = {...this.glParameters};\n\n let clearMask = 0;\n\n if (this.props.clearColors) {\n this.props.clearColors.forEach((color, drawBufferIndex) => {\n if (color) {\n this.clearColorBuffer(drawBufferIndex, color);\n }\n });\n }\n\n if (this.props.clearColor !== false && this.props.clearColors === undefined) {\n clearMask |= GL.COLOR_BUFFER_BIT;\n glParameters.clearColor = this.props.clearColor;\n }\n if (this.props.clearDepth !== false) {\n clearMask |= GL.DEPTH_BUFFER_BIT;\n glParameters.clearDepth = this.props.clearDepth;\n }\n if (this.props.clearStencil !== false) {\n clearMask |= GL.STENCIL_BUFFER_BIT;\n glParameters.clearStencil = this.props.clearStencil;\n }\n\n if (clearMask !== 0) {\n // Temporarily set any clear \"colors\" and call clear\n withGLParameters(this.device.gl, glParameters, () => {\n this.device.gl.clear(clearMask);\n });\n }\n }\n\n /**\n * WebGL2 - clear a specific color buffer\n */\n protected clearColorBuffer(drawBuffer: number = 0, value: NumericArray = [0, 0, 0, 0]) {\n withGLParameters(this.device.gl, {framebuffer: this.props.framebuffer}, () => {\n // Method selection per OpenGL ES 3 docs\n switch (value.constructor) {\n case Int8Array:\n case Int16Array:\n case Int32Array:\n this.device.gl.clearBufferiv(GL.COLOR, drawBuffer, value);\n break;\n case Uint8Array:\n case Uint8ClampedArray:\n case Uint16Array:\n case Uint32Array:\n this.device.gl.clearBufferuiv(GL.COLOR, drawBuffer, value);\n break;\n case Float32Array:\n this.device.gl.clearBufferfv(GL.COLOR, drawBuffer, value);\n break;\n default:\n throw new Error('clearColorBuffer: color must be typed array');\n }\n });\n }\n\n /*\n clearDepthStencil() {\n case GL.DEPTH:\n this.device.gl.clearBufferfv(GL.DEPTH, 0, [value]);\n break;\n\n case GL_STENCIL:\n this.device.gl.clearBufferiv(GL.STENCIL, 0, [value]);\n break;\n\n case GL.DEPTH_STENCIL:\n const [depth, stencil] = value;\n this.device.gl.clearBufferfi(GL.DEPTH_STENCIL, 0, depth, stencil);\n break;\n\n default:\n assert(false, ERR_ARGUMENTS);\n }\n });\n */\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {CommandBufferProps, CommandEncoder, CommandEncoderProps} from '@luma.gl/core';\nimport type {\n RenderPassProps,\n ComputePass,\n ComputePassProps,\n QuerySet,\n Buffer,\n CopyBufferToBufferOptions,\n CopyBufferToTextureOptions,\n CopyTextureToBufferOptions,\n CopyTextureToTextureOptions\n // ClearTextureOptions,\n // TextureReadOptions,\n} from '@luma.gl/core';\n\nimport {WEBGLCommandBuffer} from './webgl-command-buffer';\nimport {WEBGLRenderPass} from './webgl-render-pass';\nimport {WebGLDevice} from '../webgl-device';\nimport {WEBGLQuerySet} from './webgl-query-set';\n\nexport class WEBGLCommandEncoder extends CommandEncoder {\n readonly device: WebGLDevice;\n readonly handle = null;\n\n readonly commandBuffer: WEBGLCommandBuffer;\n\n constructor(device: WebGLDevice, props: CommandEncoderProps) {\n super(device, props);\n this.device = device;\n this.commandBuffer = new WEBGLCommandBuffer(device, {\n id: `${this.props.id}-command-buffer`\n });\n }\n\n override destroy(): void {\n this.destroyResource();\n }\n\n override finish(props?: CommandBufferProps): WEBGLCommandBuffer {\n if (props?.id && this.commandBuffer.id !== props.id) {\n this.commandBuffer.id = props.id;\n this.commandBuffer.props.id = props.id;\n }\n this.destroy();\n return this.commandBuffer;\n }\n\n beginRenderPass(props: RenderPassProps = {}): WEBGLRenderPass {\n return new WEBGLRenderPass(this.device, this._applyTimeProfilingToPassProps(props));\n }\n\n beginComputePass(props: ComputePassProps = {}): ComputePass {\n throw new Error('ComputePass not supported in WebGL');\n }\n\n copyBufferToBuffer(options: CopyBufferToBufferOptions): void {\n this.commandBuffer.commands.push({name: 'copy-buffer-to-buffer', options});\n }\n\n copyBufferToTexture(options: CopyBufferToTextureOptions) {\n this.commandBuffer.commands.push({name: 'copy-buffer-to-texture', options});\n }\n\n copyTextureToBuffer(options: CopyTextureToBufferOptions): void {\n this.commandBuffer.commands.push({name: 'copy-texture-to-buffer', options});\n }\n\n copyTextureToTexture(options: CopyTextureToTextureOptions): void {\n this.commandBuffer.commands.push({name: 'copy-texture-to-texture', options});\n }\n\n // clearTexture(options: ClearTextureOptions): void {\n // this.commandBuffer.commands.push({name: 'copy-texture-to-texture', options});\n // }\n\n override pushDebugGroup(groupLabel: string): void {}\n override popDebugGroup() {}\n\n override insertDebugMarker(markerLabel: string): void {}\n\n override resolveQuerySet(\n _querySet: QuerySet,\n _destination: Buffer,\n _options?: {\n firstQuery?: number;\n queryCount?: number;\n destinationOffset?: number;\n }\n ): void {\n throw new Error('resolveQuerySet is not supported in WebGL');\n }\n\n writeTimestamp(querySet: QuerySet, queryIndex: number): void {\n const webglQuerySet = querySet as WEBGLQuerySet;\n webglQuerySet.writeTimestamp(queryIndex);\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {NumericArray} from '@math.gl/types';\n\n// Uses copyWithin to significantly speed up typed array value filling\nexport function fillArray(options: {\n target: NumericArray;\n source: NumericArray;\n start?: number;\n count?: number;\n}): NumericArray {\n const {target, source, start = 0, count = 1} = options;\n const length = source.length;\n const total = count * length;\n let copied = 0;\n for (let i = start; copied < length; copied++) {\n target[i++] = source[copied] ?? 0;\n }\n\n while (copied < total) {\n // If we have copied less than half, copy everything we got\n // else copy remaining in one operation\n if (copied < total - copied) {\n target.copyWithin(start + copied, start, start + copied);\n copied *= 2;\n } else {\n target.copyWithin(start + copied, start, start + total - copied);\n copied = total;\n }\n }\n\n return options.target;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {TypedArray, NumericArray} from '@math.gl/types';\nimport type {Device, Buffer, VertexArrayProps} from '@luma.gl/core';\nimport {VertexArray, getScratchArray} from '@luma.gl/core';\nimport {GL} from '@luma.gl/webgl/constants';\nimport {getBrowser} from '@probe.gl/env';\n\nimport {WebGLDevice} from '../webgl-device';\nimport {WEBGLBuffer} from '../resources/webgl-buffer';\n\nimport {getGLFromVertexType} from '../converters/webgl-vertex-formats';\nimport {fillArray} from '../../utils/fill-array';\n\n/** VertexArrayObject wrapper */\nexport class WEBGLVertexArray extends VertexArray {\n override get [Symbol.toStringTag](): string {\n return 'VertexArray';\n }\n\n readonly device: WebGLDevice;\n readonly handle: WebGLVertexArrayObject;\n\n /** Attribute 0 buffer constant */\n private buffer: WEBGLBuffer | null = null;\n private bufferValue: TypedArray | null = null;\n\n /** * Attribute 0 can not be disable on most desktop OpenGL based browsers */\n static isConstantAttributeZeroSupported(device: Device): boolean {\n return getBrowser() === 'Chrome';\n }\n\n // Create a VertexArray\n constructor(device: WebGLDevice, props: VertexArrayProps) {\n super(device, props);\n this.device = device;\n this.handle = this.device.gl.createVertexArray()!;\n }\n\n override destroy(): void {\n super.destroy();\n if (this.buffer) {\n this.buffer?.destroy();\n }\n if (this.handle) {\n this.device.gl.deleteVertexArray(this.handle);\n // @ts-expect-error read-only/undefined\n this.handle = undefined!;\n }\n\n // Auto-delete elements?\n // return [this.elements];\n }\n\n /**\n // Set (bind/unbind) an elements buffer, for indexed rendering.\n // Must be a Buffer bound to GL.ELEMENT_ARRAY_BUFFER or null. Constants not supported\n *\n * @param elementBuffer\n */\n setIndexBuffer(indexBuffer: Buffer | null): void {\n const buffer = indexBuffer as WEBGLBuffer;\n // Explicitly allow `null` to support clearing the index buffer\n if (buffer && buffer.glTarget !== GL.ELEMENT_ARRAY_BUFFER) {\n throw new Error('Use .setBuffer()');\n }\n // In WebGL The GL.ELEMENT_ARRAY_BUFFER_BINDING is stored on the VertexArrayObject\n this.device.gl.bindVertexArray(this.handle);\n this.device.gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, buffer ? buffer.handle : null);\n\n this.indexBuffer = buffer;\n\n // Unbind to prevent unintended changes to the VAO.\n this.device.gl.bindVertexArray(null);\n }\n\n /** Set a location in vertex attributes array to a buffer, enables the location, sets divisor */\n setBuffer(location: number, attributeBuffer: Buffer): void {\n const buffer = attributeBuffer as WEBGLBuffer;\n // Sanity check target\n if (buffer.glTarget === GL.ELEMENT_ARRAY_BUFFER) {\n throw new Error('Use .setIndexBuffer()');\n }\n\n const {size, type, stride, offset, normalized, integer, divisor} = this._getAccessor(location);\n\n this.device.gl.bindVertexArray(this.handle);\n // A non-zero buffer object must be bound to the GL_ARRAY_BUFFER target\n this.device.gl.bindBuffer(GL.ARRAY_BUFFER, buffer.handle);\n\n // WebGL2 supports *integer* data formats, i.e. GPU will see integer values\n if (integer) {\n this.device.gl.vertexAttribIPointer(location, size, type, stride, offset);\n } else {\n // Attaches ARRAY_BUFFER with specified buffer format to location\n this.device.gl.vertexAttribPointer(location, size, type, normalized, stride, offset);\n }\n // Clear binding - keeping it may cause [.WebGL-0x12804417100]\n // GL_INVALID_OPERATION: A transform feedback buffer that would be written to is also bound to a non-transform-feedback target\n this.device.gl.bindBuffer(GL.ARRAY_BUFFER, null);\n\n // Mark as non-constant\n this.device.gl.enableVertexAttribArray(location);\n // Set the step mode 0=vertex, 1=instance\n this.device.gl.vertexAttribDivisor(location, divisor || 0);\n\n this.attributes[location] = buffer;\n\n // Unbind to prevent unintended changes to the VAO.\n this.device.gl.bindVertexArray(null);\n }\n\n /** Set a location in vertex attributes array to a constant value, disables the location */\n override setConstantWebGL(location: number, value: TypedArray): void {\n this._enable(location, false);\n this.attributes[location] = value;\n }\n\n override bindBeforeRender(): void {\n this.device.gl.bindVertexArray(this.handle);\n this._applyConstantAttributes();\n }\n\n override unbindAfterRender(): void {\n // Unbind to prevent unintended changes to the VAO.\n this.device.gl.bindVertexArray(null);\n }\n\n // Internal methods\n\n /**\n * Constant attributes need to be reset before every draw call\n * Any attribute that is disabled in the current vertex array object\n * is read from the context's global constant value for that attribute location.\n * @note Constant attributes are only supported in WebGL, not in WebGPU\n */\n protected _applyConstantAttributes(): void {\n for (let location = 0; location < this.maxVertexAttributes; ++location) {\n const constant = this.attributes[location];\n // A typed array means this is a constant\n if (ArrayBuffer.isView(constant)) {\n this.device.setConstantAttributeWebGL(location, constant);\n }\n }\n }\n\n /**\n * Set a location in vertex attributes array to a buffer, enables the location, sets divisor\n * @note requires vertex array to be bound\n */\n // protected _setAttributeLayout(location: number): void {\n // const {size, type, stride, offset, normalized, integer, divisor} = this._getAccessor(location);\n\n // // WebGL2 supports *integer* data formats, i.e. GPU will see integer values\n // if (integer) {\n // this.device.gl.vertexAttribIPointer(location, size, type, stride, offset);\n // } else {\n // // Attaches ARRAY_BUFFER with specified buffer format to location\n // this.device.gl.vertexAttribPointer(location, size, type, normalized, stride, offset);\n // }\n // this.device.gl.vertexAttribDivisor(location, divisor || 0);\n // }\n\n /** Get an accessor from the */\n protected _getAccessor(location: number) {\n const attributeInfo = this.attributeInfos[location];\n if (!attributeInfo) {\n throw new Error(`Unknown attribute location ${location}`);\n }\n const glType = getGLFromVertexType(attributeInfo.bufferDataType);\n return {\n size: attributeInfo.bufferComponents,\n type: glType,\n stride: attributeInfo.byteStride,\n offset: attributeInfo.byteOffset,\n normalized: attributeInfo.normalized,\n // it is the shader attribute declaration, not the vertex memory format,\n // that determines if the data in the buffer will be treated as integers.\n //\n // Also note that WebGL supports assigning non-normalized integer data to floating point attributes,\n // but as far as we can tell, WebGPU does not.\n integer: attributeInfo.integer,\n divisor: attributeInfo.stepMode === 'instance' ? 1 : 0\n };\n }\n\n /**\n * Enabling an attribute location makes it reference the currently bound buffer\n * Disabling an attribute location makes it reference the global constant value\n * TODO - handle single values for size 1 attributes?\n * TODO - convert classic arrays based on known type?\n */\n protected _enable(location: number, enable = true): void {\n // Attribute 0 cannot be disabled in most desktop OpenGL based browsers...\n const canDisableAttributeZero = WEBGLVertexArray.isConstantAttributeZeroSupported(this.device);\n const canDisableAttribute = canDisableAttributeZero || location !== 0;\n\n if (enable || canDisableAttribute) {\n location = Number(location);\n this.device.gl.bindVertexArray(this.handle);\n if (enable) {\n this.device.gl.enableVertexAttribArray(location);\n } else {\n this.device.gl.disableVertexAttribArray(location);\n }\n this.device.gl.bindVertexArray(null);\n }\n }\n\n /**\n * Provide a means to create a buffer that is equivalent to a constant.\n * NOTE: Desktop OpenGL cannot disable attribute 0.\n * https://stackoverflow.com/questions/20305231/webgl-warning-attribute-0-is-disabled-\n * this-has-significant-performance-penalty\n */\n getConstantBuffer(elementCount: number, value: TypedArray): Buffer {\n // Create buffer only when needed, and reuse it (avoids inflating buffer creation statistics)\n\n const constantValue = normalizeConstantArrayValue(value);\n\n const byteLength = constantValue.byteLength * elementCount;\n const length = constantValue.length * elementCount;\n\n if (this.buffer && byteLength !== this.buffer.byteLength) {\n throw new Error(\n `Buffer size is immutable, byte length ${byteLength} !== ${this.buffer.byteLength}.`\n );\n }\n let updateNeeded = !this.buffer;\n\n this.buffer = this.buffer || this.device.createBuffer({byteLength});\n\n // Reallocate and update contents if needed\n // @ts-ignore TODO fix types\n updateNeeded ||= !compareConstantArrayValues(constantValue, this.bufferValue);\n\n if (updateNeeded) {\n // Create a typed array that is big enough, and fill it with the required data\n const typedArray = getScratchArray(value.constructor, length);\n fillArray({target: typedArray, source: constantValue, start: 0, count: length});\n this.buffer.write(typedArray);\n this.bufferValue = value;\n }\n\n return this.buffer;\n }\n}\n\n// HELPER FUNCTIONS\n\n/**\n * TODO - convert Arrays based on known type? (read type from accessor, don't assume Float32Array)\n * TODO - handle single values for size 1 attributes?\n */\nfunction normalizeConstantArrayValue(arrayValue: NumericArray) {\n if (Array.isArray(arrayValue)) {\n return new Float32Array(arrayValue);\n }\n return arrayValue;\n}\n\n/**\n *\n */\nfunction compareConstantArrayValues(v1: NumericArray, v2: NumericArray): boolean {\n if (!v1 || !v2 || v1.length !== v2.length || v1.constructor !== v2.constructor) {\n return false;\n }\n for (let i = 0; i < v1.length; ++i) {\n if (v1[i] !== v2[i]) {\n return false;\n }\n }\n return true;\n}\n","import type {PrimitiveTopology, ShaderLayout, TransformFeedbackProps} from '@luma.gl/core';\nimport {log, TransformFeedback, Buffer, BufferRange} from '@luma.gl/core';\nimport {GL} from '@luma.gl/webgl/constants';\nimport {WebGLDevice} from '../webgl-device';\nimport {WEBGLBuffer} from '../../index';\nimport {getGLPrimitive} from '../helpers/webgl-topology-utils';\n\nexport class WEBGLTransformFeedback extends TransformFeedback {\n readonly device: WebGLDevice;\n readonly gl: WebGL2RenderingContext;\n readonly handle: WebGLTransformFeedback;\n\n /**\n * NOTE: The Model already has this information while drawing, but\n * TransformFeedback currently needs it internally, to look up\n * varying information outside of a draw() call.\n */\n readonly layout: ShaderLayout;\n buffers: Record = {};\n unusedBuffers: Record = {};\n /**\n * Allows us to avoid a Chrome bug where a buffer that is already bound to a\n * different target cannot be bound to 'TRANSFORM_FEEDBACK_BUFFER' target.\n * This a major workaround, see: https://github.com/KhronosGroup/WebGL/issues/2346\n */\n bindOnUse = true;\n private _bound: boolean = false;\n\n constructor(device: WebGLDevice, props: TransformFeedbackProps) {\n super(device, props);\n\n this.device = device;\n this.gl = device.gl;\n this.handle = this.props.handle || this.gl.createTransformFeedback();\n this.layout = this.props.layout;\n\n if (props.buffers) {\n this.setBuffers(props.buffers);\n }\n\n Object.seal(this);\n }\n\n override destroy(): void {\n this.gl.deleteTransformFeedback(this.handle);\n super.destroy();\n }\n\n begin(topology: PrimitiveTopology = 'point-list'): void {\n this.gl.bindTransformFeedback(GL.TRANSFORM_FEEDBACK, this.handle);\n if (this.bindOnUse) {\n this._bindBuffers();\n }\n this.gl.beginTransformFeedback(getGLPrimitive(topology));\n }\n\n end(): void {\n this.gl.endTransformFeedback();\n if (this.bindOnUse) {\n this._unbindBuffers();\n }\n this.gl.bindTransformFeedback(GL.TRANSFORM_FEEDBACK, null);\n }\n\n // SUBCLASS\n\n setBuffers(buffers: Record): void {\n this.buffers = {};\n this.unusedBuffers = {};\n\n this.bind(() => {\n for (const [bufferName, buffer] of Object.entries(buffers)) {\n this.setBuffer(bufferName, buffer);\n }\n });\n }\n\n setBuffer(locationOrName: string | number, bufferOrRange: Buffer | BufferRange): void {\n const location = this._getVaryingIndex(locationOrName);\n const {buffer, byteLength, byteOffset} = this._getBufferRange(bufferOrRange);\n\n if (location < 0) {\n this.unusedBuffers[locationOrName] = buffer;\n log.warn(`${this.id} unusedBuffers varying buffer ${locationOrName}`)();\n return;\n }\n\n this.buffers[location] = {buffer, byteLength, byteOffset};\n\n // Need to avoid chrome bug where buffer that is already bound to a different target\n // cannot be bound to 'TRANSFORM_FEEDBACK_BUFFER' target.\n if (!this.bindOnUse) {\n this._bindBuffer(location, buffer, byteOffset, byteLength);\n }\n }\n\n getBuffer(locationOrName: string | number): Buffer | BufferRange | null {\n if (isIndex(locationOrName)) {\n return this.buffers[locationOrName] || null;\n }\n const location = this._getVaryingIndex(locationOrName);\n return this.buffers[location] ?? null;\n }\n\n bind(funcOrHandle: (() => void) | WebGLTransformFeedback | null = this.handle) {\n if (typeof funcOrHandle !== 'function') {\n this.gl.bindTransformFeedback(GL.TRANSFORM_FEEDBACK, funcOrHandle);\n return this;\n }\n\n let value: unknown;\n\n if (!this._bound) {\n this.gl.bindTransformFeedback(GL.TRANSFORM_FEEDBACK, this.handle);\n this._bound = true;\n value = funcOrHandle();\n this._bound = false;\n this.gl.bindTransformFeedback(GL.TRANSFORM_FEEDBACK, null);\n } else {\n value = funcOrHandle();\n }\n\n return value;\n }\n\n unbind() {\n this.bind(null);\n }\n\n // PRIVATE METHODS\n\n /** Extract offsets for bindBufferRange */\n protected _getBufferRange(\n bufferOrRange: Buffer | {buffer: Buffer; byteOffset?: number; byteLength?: number}\n ): Required {\n if (bufferOrRange instanceof WEBGLBuffer) {\n return {buffer: bufferOrRange, byteOffset: 0, byteLength: bufferOrRange.byteLength};\n }\n\n // To use bindBufferRange either offset or size must be specified.\n // @ts-expect-error Must be a BufferRange.\n const {buffer, byteOffset = 0, byteLength = bufferOrRange.buffer.byteLength} = bufferOrRange;\n return {buffer, byteOffset, byteLength};\n }\n\n protected _getVaryingIndex(locationOrName: string | number): number {\n if (isIndex(locationOrName)) {\n return Number(locationOrName);\n }\n\n for (const varying of this.layout.varyings || []) {\n if (locationOrName === varying.name) {\n return varying.location;\n }\n }\n\n return -1;\n }\n\n /**\n * Need to avoid chrome bug where buffer that is already bound to a different target\n * cannot be bound to 'TRANSFORM_FEEDBACK_BUFFER' target.\n */\n protected _bindBuffers(): void {\n for (const [bufferIndex, bufferEntry] of Object.entries(this.buffers)) {\n const {buffer, byteLength, byteOffset} = this._getBufferRange(bufferEntry);\n this._bindBuffer(Number(bufferIndex), buffer, byteOffset, byteLength);\n }\n }\n\n protected _unbindBuffers(): void {\n for (const bufferIndex in this.buffers) {\n this.gl.bindBufferBase(GL.TRANSFORM_FEEDBACK_BUFFER, Number(bufferIndex), null);\n }\n }\n\n protected _bindBuffer(index: number, buffer: Buffer, byteOffset = 0, byteLength?: number): void {\n const handle = buffer && (buffer as WEBGLBuffer).handle;\n if (!handle || byteLength === undefined) {\n this.gl.bindBufferBase(GL.TRANSFORM_FEEDBACK_BUFFER, index, handle);\n } else {\n this.gl.bindBufferRange(GL.TRANSFORM_FEEDBACK_BUFFER, index, handle, byteOffset, byteLength);\n }\n }\n}\n\n/**\n * Returns true if the given value is an integer, or a string that\n * trivially converts to an integer (only numeric characters).\n */\nfunction isIndex(value: string | number): boolean {\n if (typeof value === 'number') {\n return Number.isInteger(value);\n }\n return /^\\d+$/.test(value);\n}\n","// WebGL2 QuerySet (also handles disjoint timer extensions)\nimport {QuerySet, QuerySetProps} from '@luma.gl/core';\nimport {GL} from '@luma.gl/webgl/constants';\nimport {WebGLDevice} from '../webgl-device';\n\ntype WebGLPendingQuery = {\n handle: WebGLQuery;\n promise: Promise | null;\n result: bigint | null;\n disjoint: boolean;\n cancelled: boolean;\n pollRequestId: number | null;\n resolve: ((value: bigint) => void) | null;\n reject: ((error: Error) => void) | null;\n};\n\ntype WebGLTimestampPair = {\n activeQuery: WebGLPendingQuery | null;\n completedQueries: WebGLPendingQuery[];\n};\n\n/**\n * Asynchronous queries for different kinds of information\n */\nexport class WEBGLQuerySet extends QuerySet {\n readonly device: WebGLDevice;\n readonly handle: WebGLQuery | null;\n\n protected _timestampPairs: WebGLTimestampPair[] = [];\n protected _pendingReads: Set = new Set();\n protected _occlusionQuery: WebGLPendingQuery | null = null;\n protected _occlusionActive = false;\n\n override get [Symbol.toStringTag](): string {\n return 'QuerySet';\n }\n\n constructor(device: WebGLDevice, props: QuerySetProps) {\n super(device, props);\n this.device = device;\n\n if (props.type === 'timestamp') {\n if (props.count < 2) {\n throw new Error('Timestamp QuerySet requires at least two query slots');\n }\n this._timestampPairs = new Array(Math.ceil(props.count / 2))\n .fill(null)\n .map(() => ({activeQuery: null, completedQueries: []}));\n this.handle = null;\n } else {\n if (props.count > 1) {\n throw new Error('WebGL occlusion QuerySet can only have one value');\n }\n const handle = this.device.gl.createQuery();\n if (!handle) {\n throw new Error('WebGL query not supported');\n }\n this.handle = handle;\n }\n\n Object.seal(this);\n }\n\n override destroy(): void {\n if (this.destroyed) {\n return;\n }\n\n if (this.handle) {\n this.device.gl.deleteQuery(this.handle);\n }\n\n for (const pair of this._timestampPairs) {\n if (pair.activeQuery) {\n this._cancelPendingQuery(pair.activeQuery);\n this.device.gl.deleteQuery(pair.activeQuery.handle);\n }\n for (const query of pair.completedQueries) {\n this._cancelPendingQuery(query);\n this.device.gl.deleteQuery(query.handle);\n }\n }\n\n if (this._occlusionQuery) {\n this._cancelPendingQuery(this._occlusionQuery);\n this.device.gl.deleteQuery(this._occlusionQuery.handle);\n }\n\n for (const query of Array.from(this._pendingReads)) {\n this._cancelPendingQuery(query);\n }\n\n this.destroyResource();\n }\n\n isResultAvailable(queryIndex?: number): boolean {\n if (this.props.type === 'timestamp') {\n if (queryIndex === undefined) {\n return this._timestampPairs.some((_, pairIndex) =>\n this._isTimestampPairAvailable(pairIndex)\n );\n }\n return this._isTimestampPairAvailable(this._getTimestampPairIndex(queryIndex));\n }\n\n if (!this._occlusionQuery) {\n return false;\n }\n\n return this._pollQueryAvailability(this._occlusionQuery);\n }\n\n async readResults(options?: {firstQuery?: number; queryCount?: number}): Promise {\n const firstQuery = options?.firstQuery || 0;\n const queryCount = options?.queryCount || this.props.count - firstQuery;\n this._validateRange(firstQuery, queryCount);\n\n if (this.props.type === 'timestamp') {\n const results = new Array(queryCount).fill(0n);\n const startPairIndex = Math.floor(firstQuery / 2);\n const endPairIndex = Math.floor((firstQuery + queryCount - 1) / 2);\n\n for (let pairIndex = startPairIndex; pairIndex <= endPairIndex; pairIndex++) {\n const duration = await this._consumeTimestampPairResult(pairIndex);\n const beginSlot = pairIndex * 2;\n const endSlot = beginSlot + 1;\n\n if (beginSlot >= firstQuery && beginSlot < firstQuery + queryCount) {\n results[beginSlot - firstQuery] = 0n;\n }\n if (endSlot >= firstQuery && endSlot < firstQuery + queryCount) {\n results[endSlot - firstQuery] = duration;\n }\n }\n\n return results;\n }\n\n if (!this._occlusionQuery) {\n throw new Error('Occlusion query has not been started');\n }\n\n return [await this._consumeQueryResult(this._occlusionQuery)];\n }\n\n async readTimestampDuration(beginIndex: number, endIndex: number): Promise {\n if (this.props.type !== 'timestamp') {\n throw new Error('Timestamp durations require a timestamp QuerySet');\n }\n if (beginIndex < 0 || endIndex >= this.props.count || endIndex <= beginIndex) {\n throw new Error('Timestamp duration range is out of bounds');\n }\n if (beginIndex % 2 !== 0 || endIndex !== beginIndex + 1) {\n throw new Error('WebGL timestamp durations require adjacent even/odd query indices');\n }\n\n const result = await this._consumeTimestampPairResult(this._getTimestampPairIndex(beginIndex));\n return Number(result) / 1e6;\n }\n\n beginOcclusionQuery(): void {\n if (this.props.type !== 'occlusion') {\n throw new Error('Occlusion queries require an occlusion QuerySet');\n }\n if (!this.handle) {\n throw new Error('WebGL occlusion query is not available');\n }\n if (this._occlusionActive) {\n throw new Error('Occlusion query is already active');\n }\n\n this.device.gl.beginQuery(GL.ANY_SAMPLES_PASSED, this.handle);\n this._occlusionQuery = {\n handle: this.handle,\n promise: null,\n result: null,\n disjoint: false,\n cancelled: false,\n pollRequestId: null,\n resolve: null,\n reject: null\n };\n this._occlusionActive = true;\n }\n\n endOcclusionQuery(): void {\n if (!this._occlusionActive) {\n throw new Error('Occlusion query is not active');\n }\n\n this.device.gl.endQuery(GL.ANY_SAMPLES_PASSED);\n this._occlusionActive = false;\n }\n\n writeTimestamp(queryIndex: number): void {\n if (this.props.type !== 'timestamp') {\n throw new Error('Timestamp writes require a timestamp QuerySet');\n }\n\n const pairIndex = this._getTimestampPairIndex(queryIndex);\n const pair = this._timestampPairs[pairIndex];\n\n if (queryIndex % 2 === 0) {\n if (pair.activeQuery) {\n throw new Error('Timestamp query pair is already active');\n }\n\n const handle = this.device.gl.createQuery();\n if (!handle) {\n throw new Error('WebGL query not supported');\n }\n\n const query: WebGLPendingQuery = {\n handle,\n promise: null,\n result: null,\n disjoint: false,\n cancelled: false,\n pollRequestId: null,\n resolve: null,\n reject: null\n };\n\n this.device.gl.beginQuery(GL.TIME_ELAPSED_EXT, handle);\n pair.activeQuery = query;\n return;\n }\n\n if (!pair.activeQuery) {\n throw new Error('Timestamp query pair was ended before it was started');\n }\n\n this.device.gl.endQuery(GL.TIME_ELAPSED_EXT);\n pair.completedQueries.push(pair.activeQuery);\n pair.activeQuery = null;\n }\n\n protected _validateRange(firstQuery: number, queryCount: number): void {\n if (firstQuery < 0 || queryCount < 0 || firstQuery + queryCount > this.props.count) {\n throw new Error('Query read range is out of bounds');\n }\n }\n\n protected _getTimestampPairIndex(queryIndex: number): number {\n if (queryIndex < 0 || queryIndex >= this.props.count) {\n throw new Error('Query index is out of bounds');\n }\n\n return Math.floor(queryIndex / 2);\n }\n\n protected _isTimestampPairAvailable(pairIndex: number): boolean {\n const pair = this._timestampPairs[pairIndex];\n if (!pair || pair.completedQueries.length === 0) {\n return false;\n }\n\n return this._pollQueryAvailability(pair.completedQueries[0]);\n }\n\n protected _pollQueryAvailability(query: WebGLPendingQuery): boolean {\n if (query.cancelled || this.destroyed) {\n query.result = 0n;\n return true;\n }\n\n if (query.result !== null || query.disjoint) {\n return true;\n }\n\n const resultAvailable = this.device.gl.getQueryParameter(\n query.handle,\n GL.QUERY_RESULT_AVAILABLE\n );\n if (!resultAvailable) {\n return false;\n }\n\n const isDisjoint = Boolean(this.device.gl.getParameter(GL.GPU_DISJOINT_EXT));\n query.disjoint = isDisjoint;\n query.result = isDisjoint\n ? 0n\n : BigInt(this.device.gl.getQueryParameter(query.handle, GL.QUERY_RESULT));\n return true;\n }\n\n protected async _consumeTimestampPairResult(pairIndex: number): Promise {\n const pair = this._timestampPairs[pairIndex];\n if (!pair || pair.completedQueries.length === 0) {\n throw new Error('Timestamp query pair has no completed result');\n }\n\n const query = pair.completedQueries.shift()!;\n\n try {\n return await this._consumeQueryResult(query);\n } finally {\n this.device.gl.deleteQuery(query.handle);\n }\n }\n\n protected _consumeQueryResult(query: WebGLPendingQuery): Promise {\n if (query.promise) {\n return query.promise;\n }\n\n this._pendingReads.add(query);\n query.promise = new Promise((resolve, reject) => {\n query.resolve = resolve;\n query.reject = reject;\n\n const poll = () => {\n query.pollRequestId = null;\n\n if (query.cancelled || this.destroyed) {\n this._pendingReads.delete(query);\n query.promise = null;\n query.resolve = null;\n query.reject = null;\n resolve(0n);\n return;\n }\n\n if (!this._pollQueryAvailability(query)) {\n query.pollRequestId = this._requestAnimationFrame(poll);\n return;\n }\n\n this._pendingReads.delete(query);\n query.promise = null;\n query.resolve = null;\n query.reject = null;\n if (query.disjoint) {\n reject(new Error('GPU timestamp query was invalidated by a disjoint event'));\n } else {\n resolve(query.result || 0n);\n }\n };\n\n poll();\n });\n\n return query.promise;\n }\n\n protected _cancelPendingQuery(query: WebGLPendingQuery): void {\n this._pendingReads.delete(query);\n query.cancelled = true;\n if (query.pollRequestId !== null) {\n this._cancelAnimationFrame(query.pollRequestId);\n query.pollRequestId = null;\n }\n if (query.resolve) {\n const resolve = query.resolve;\n query.promise = null;\n query.resolve = null;\n query.reject = null;\n resolve(0n);\n }\n }\n\n protected _requestAnimationFrame(callback: FrameRequestCallback): number {\n return requestAnimationFrame(callback);\n }\n\n protected _cancelAnimationFrame(requestId: number): void {\n cancelAnimationFrame(requestId);\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Fence, type FenceProps} from '@luma.gl/core';\nimport {WebGLDevice} from '../webgl-device';\n\n/** WebGL fence implemented with gl.fenceSync */\nexport class WEBGLFence extends Fence {\n readonly device: WebGLDevice;\n readonly gl: WebGL2RenderingContext;\n readonly handle: WebGLSync;\n readonly signaled: Promise;\n private _signaled = false;\n\n constructor(device: WebGLDevice, props: FenceProps = {}) {\n super(device, {});\n this.device = device;\n this.gl = device.gl;\n\n const sync = this.props.handle || this.gl.fenceSync(this.gl.SYNC_GPU_COMMANDS_COMPLETE, 0);\n if (!sync) {\n throw new Error('Failed to create WebGL fence');\n }\n this.handle = sync;\n\n this.signaled = new Promise(resolve => {\n const poll = () => {\n const status = this.gl.clientWaitSync(this.handle, 0, 0);\n if (status === this.gl.ALREADY_SIGNALED || status === this.gl.CONDITION_SATISFIED) {\n this._signaled = true;\n resolve();\n } else {\n setTimeout(poll, 1);\n }\n };\n poll();\n });\n }\n\n isSignaled(): boolean {\n if (this._signaled) {\n return true;\n }\n const status = this.gl.getSyncParameter(this.handle, this.gl.SYNC_STATUS);\n this._signaled = status === this.gl.SIGNALED;\n return this._signaled;\n }\n\n destroy(): void {\n if (!this.destroyed) {\n this.gl.deleteSync(this.handle);\n }\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {GL} from '@luma.gl/webgl/constants';\n\n// Returns number of components in a specific readPixels WebGL format\nexport function glFormatToComponents(format: GL): 0 | 1 | 2 | 3 | 4 {\n switch (format) {\n case GL.ALPHA:\n case GL.R32F:\n case GL.RED:\n case GL.RED_INTEGER:\n return 1;\n case GL.RG32I:\n case GL.RG32UI:\n case GL.RG32F:\n case GL.RG_INTEGER:\n case GL.RG:\n return 2;\n case GL.RGB:\n case GL.RGB_INTEGER:\n case GL.RGB32F:\n return 3;\n case GL.RGBA:\n case GL.RGBA_INTEGER:\n case GL.RGBA32F:\n return 4;\n // TODO: Add support for additional WebGL2 formats\n default:\n return 0;\n }\n}\n\n// Return byte count for given readPixels WebGL type\nexport function glTypeToBytes(type: GL): 0 | 1 | 2 | 4 {\n switch (type) {\n case GL.UNSIGNED_BYTE:\n return 1;\n case GL.UNSIGNED_SHORT_5_6_5:\n case GL.UNSIGNED_SHORT_4_4_4_4:\n case GL.UNSIGNED_SHORT_5_5_5_1:\n return 2;\n case GL.FLOAT:\n return 4;\n // TODO: Add support for additional WebGL2 types\n default:\n return 0;\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// @ts-nocheck This file will be deleted in upcoming refactor\n\nimport type {Buffer, Texture, FramebufferProps} from '@luma.gl/core';\nimport {Framebuffer, dataTypeDecoder} from '@luma.gl/core';\nimport {\n GL,\n GLTextureTarget,\n GLTextureCubeMapTarget,\n GLTexelDataFormat,\n GLPixelType,\n GLDataType\n} from '@luma.gl/webgl/constants';\n\nimport {convertDataTypeToGLDataType} from '../converters/webgl-shadertypes';\nimport {WEBGLFramebuffer} from '../resources/webgl-framebuffer';\nimport {glFormatToComponents, glTypeToBytes} from './format-utils';\nimport {WEBGLBuffer} from '../resources/webgl-buffer';\nimport {WEBGLTexture} from '../resources/webgl-texture';\nimport {convertGLDataTypeToDataType} from '../converters/shader-formats';\n\n/** A \"border\" parameter is required in many WebGL texture APIs, but must always be 0... */\nconst BORDER = 0;\n\n/**\n * Options for setting data into a texture\n */\nexport type WebGLSetTextureOptions = {\n dimension: '1d' | '2d' | '2d-array' | 'cube' | 'cube-array' | '3d';\n height: number;\n width: number;\n depth: number;\n mipLevel?: number;\n glTarget: GLTextureTarget;\n glInternalFormat: GL;\n glFormat: GLTexelDataFormat;\n glType: GLPixelType;\n compressed?: boolean;\n byteOffset?: number;\n byteLength?: number;\n};\n\n/**\n * Options for copying an image or data into a texture\n *\n * @param {GLenum} format - internal format of image data.\n * @param {GLenum} type\n * - format of array (autodetect from type) or\n * - (WEBGL2) format of buffer or ArrayBufferView\n * @param {GLenum} dataFormat - format of image data.\n * @param {Number} offset - (WEBGL2) offset from start of buffer\n * @parameters - temporary settings to be applied, can be used to supply pixel store settings.\n */\nexport type WebGLCopyTextureOptions = {\n dimension: '1d' | '2d' | '2d-array' | 'cube' | 'cube-array' | '3d';\n /** mip level to be updated */\n mipLevel?: number;\n /** width of the sub image to be updated */\n width: number;\n /** height of the sub image to be updated */\n height: number;\n /** depth of texture to be updated */\n depth?: number;\n /** xOffset from where texture to be updated */\n x?: number;\n /** yOffset from where texture to be updated */\n y?: number;\n /** yOffset from where texture to be updated */\n z?: number;\n\n glTarget: GLTextureTarget;\n glInternalFormat: GL;\n glFormat: GL;\n glType: GL;\n compressed?: boolean;\n byteOffset?: number;\n byteLength?: number;\n};\n\n/**\n * Copy a region of compressed data from a GPU memory buffer into this texture.\n */\nexport function copyGPUBufferToMipLevel(\n gl: WebGL2RenderingContext,\n webglBuffer: WebGLBuffer,\n byteLength: number,\n options: WebGLCopyTextureOptions\n): void {\n const {dimension, width, height, depth = 0, mipLevel = 0, byteOffset = 0} = options;\n const {x = 0, y = 0, z = 0} = options;\n const {glFormat, glType, compressed} = options;\n const glTarget = getWebGLCubeFaceTarget(options.glTarget, dimension, depth);\n\n gl.bindBuffer(GL.PIXEL_UNPACK_BUFFER, webglBuffer);\n\n switch (dimension) {\n case '2d-array':\n case '3d':\n // 3 dimensional textures requires 3D texture functions\n if (compressed) {\n // TODO enable extension?\n // biome-ignore format: preserve layout\n gl.compressedTexSubImage3D(glTarget, mipLevel, x, y, z, width, height, depth, glFormat, byteLength, byteOffset);\n } else {\n // biome-ignore format: preserve layout\n gl.texSubImage3D(glTarget, mipLevel, x, y, z, width, height, depth, glFormat, glType, byteOffset);\n }\n break;\n\n case '2d':\n case 'cube':\n if (compressed) {\n // biome-ignore format: preserve layout\n gl.compressedTexSubImage2D(glTarget, mipLevel, x, y, width, height, glFormat, byteLength, byteOffset);\n } else {\n // biome-ignore format: preserve layout\n gl.texSubImage2D(glTarget, mipLevel, x, y, width, height, BORDER, glFormat, byteOffset);\n }\n break;\n\n default:\n throw new Error(dimension);\n }\n}\n\n// INTERNAL HELPERS\n\n/** Convert a WebGPU style texture constant to a WebGL style texture constant */\nexport function getWebGLTextureTarget(\n dimension: '1d' | '2d' | '2d-array' | 'cube' | 'cube-array' | '3d'\n): GLTextureTarget {\n // biome-ignore format: preserve layout\n switch (dimension) {\n case '1d': break; // not supported in any WebGL version\n case '2d': return GL.TEXTURE_2D; // supported in WebGL1\n case '3d': return GL.TEXTURE_3D; // supported in WebGL2\n case 'cube': return GL.TEXTURE_CUBE_MAP; // supported in WebGL1\n case '2d-array': return GL.TEXTURE_2D_ARRAY; // supported in WebGL2\n case 'cube-array': break; // not supported in any WebGL version\n }\n throw new Error(dimension);\n}\n\n/**\n * In WebGL, cube maps specify faces by overriding target instead of using the depth parameter.\n * @note We still bind the texture using GL.TEXTURE_CUBE_MAP, but we need to use the face-specific target when setting mip levels.\n * @returns glTarget unchanged, if dimension !== 'cube'.\n */\nexport function getWebGLCubeFaceTarget(\n glTarget: GLTextureTarget,\n dimension: '1d' | '2d' | '2d-array' | 'cube' | 'cube-array' | '3d',\n level: number\n): GLTextureTarget | GLTextureCubeMapTarget {\n return dimension === 'cube' ? GL.TEXTURE_CUBE_MAP_POSITIVE_X + level : glTarget;\n}\nexport type ReadPixelsToArrayOptions = {\n sourceX?: number;\n sourceY?: number;\n sourceFormat?: number;\n sourceAttachment?: number;\n target?: Uint8Array | Uint16Array | Float32Array;\n // following parameters are auto deduced if not provided\n sourceWidth?: number;\n sourceHeight?: number;\n sourceDepth?: number;\n sourceType?: number;\n};\n\nexport type ReadPixelsToBufferOptions = {\n sourceX?: number;\n sourceY?: number;\n sourceFormat?: number;\n target?: Buffer; // A new Buffer object is created when not provided.\n targetByteOffset?: number; // byte offset in buffer object\n // following parameters are auto deduced if not provided\n sourceWidth?: number;\n sourceHeight?: number;\n sourceType?: number;\n};\n\n/**\n * Copies data from a type or a Texture object into ArrayBuffer object.\n * App can provide targetPixelArray or have it auto allocated by this method\n * newly allocated by this method unless provided by app.\n * @deprecated Use CommandEncoder.copyTextureToBuffer and Buffer.read\n * @note Slow requires roundtrip to GPU\n *\n * @param source\n * @param options\n * @returns pixel array,\n */\nexport function readPixelsToArray(\n source: Framebuffer | Texture,\n options?: ReadPixelsToArrayOptions\n): Uint8Array | Uint16Array | Float32Array {\n const {\n sourceX = 0,\n sourceY = 0,\n sourceAttachment = 0 // TODO - support gl.readBuffer\n } = options || {};\n let {\n target = null,\n // following parameters are auto deduced if not provided\n sourceWidth,\n sourceHeight,\n sourceDepth,\n sourceFormat,\n sourceType\n } = options || {};\n\n const {framebuffer, deleteFramebuffer} = getFramebuffer(source);\n // assert(framebuffer);\n const {gl, handle} = framebuffer;\n\n sourceWidth ||= framebuffer.width;\n sourceHeight ||= framebuffer.height;\n\n const texture = framebuffer.colorAttachments[sourceAttachment]?.texture;\n if (!texture) {\n throw new Error(`Invalid framebuffer attachment ${sourceAttachment}`);\n }\n sourceDepth = texture?.depth || 1;\n\n sourceFormat ||= texture?.glFormat || GL.RGBA;\n // Deduce the type from color attachment if not provided.\n sourceType ||= texture?.glType || GL.UNSIGNED_BYTE;\n\n // Deduce type and allocated pixelArray if needed\n target = getPixelArray(target, sourceType, sourceFormat, sourceWidth, sourceHeight, sourceDepth);\n\n // Pixel array available, if necessary, deduce type from it.\n const signedType = dataTypeDecoder.getDataType(target);\n sourceType = sourceType || convertDataTypeToGLDataType(signedType);\n\n // Note: luma.gl overrides bindFramebuffer so that we can reliably restore the previous framebuffer (this is the only function for which we do that)\n const prevHandle = gl.bindFramebuffer(\n GL.FRAMEBUFFER,\n handle\n ) as unknown as WebGLFramebuffer | null;\n\n // Select the color attachment to read from\n gl.readBuffer(gl.COLOR_ATTACHMENT0 + sourceAttachment);\n\n // There is a lot of hedging in the WebGL2 spec about what formats are guaranteed to be readable\n // (It should always be possible to read RGBA/UNSIGNED_BYTE, but most other combinations are not guaranteed)\n // Querying is possible but expensive:\n // const {device} = framebuffer;\n // texture.glReadFormat ||= gl.getParameter(gl.IMPLEMENTATION_COLOR_READ_FORMAT);\n // texture.glReadType ||= gl.getParameter(gl.IMPLEMENTATION_COLOR_READ_TYPE);\n // console.log('params', device.getGLKey(texture.glReadFormat), device.getGLKey(texture.glReadType));\n\n gl.readPixels(sourceX, sourceY, sourceWidth, sourceHeight, sourceFormat, sourceType, target);\n gl.readBuffer(gl.COLOR_ATTACHMENT0);\n gl.bindFramebuffer(GL.FRAMEBUFFER, prevHandle || null);\n\n if (deleteFramebuffer) {\n framebuffer.destroy();\n }\n\n return target;\n}\n\n/**\n * Copies data from a Framebuffer or a Texture object into a Buffer object.\n * NOTE: doesn't wait for copy to be complete, it programs GPU to perform a DMA transffer.\n * @deprecated Use CommandEncoder\n * @param source\n * @param options\n */\nexport function readPixelsToBuffer(\n source: Framebuffer | Texture,\n options?: ReadPixelsToBufferOptions\n): WEBGLBuffer {\n const {\n target,\n sourceX = 0,\n sourceY = 0,\n sourceFormat = GL.RGBA,\n targetByteOffset = 0\n } = options || {};\n // following parameters are auto deduced if not provided\n let {sourceWidth, sourceHeight, sourceType} = options || {};\n const {framebuffer, deleteFramebuffer} = getFramebuffer(source);\n // assert(framebuffer);\n sourceWidth = sourceWidth || framebuffer.width;\n sourceHeight = sourceHeight || framebuffer.height;\n\n // Asynchronous read (PIXEL_PACK_BUFFER) is WebGL2 only feature\n const webglFramebuffer = framebuffer;\n\n // deduce type if not available.\n sourceType = sourceType || GL.UNSIGNED_BYTE;\n\n let webglBufferTarget = target as unknown as WEBGLBuffer | undefined;\n if (!webglBufferTarget) {\n // Create new buffer with enough size\n const components = glFormatToComponents(sourceFormat);\n const byteCount = glTypeToBytes(sourceType);\n const byteLength = targetByteOffset + sourceWidth * sourceHeight * components * byteCount;\n webglBufferTarget = webglFramebuffer.device.createBuffer({byteLength});\n }\n\n // TODO(donmccurdy): Do we have tests to confirm this is working?\n const commandEncoder = source.device.createCommandEncoder();\n commandEncoder.copyTextureToBuffer({\n sourceTexture: source as Texture,\n width: sourceWidth,\n height: sourceHeight,\n origin: [sourceX, sourceY],\n destinationBuffer: webglBufferTarget,\n byteOffset: targetByteOffset\n });\n commandEncoder.destroy();\n\n if (deleteFramebuffer) {\n framebuffer.destroy();\n }\n\n return webglBufferTarget;\n}\n\n/**\n * Copy a rectangle from a Framebuffer or Texture object into a texture (at an offset)\n * @deprecated Use CommandEncoder\n */\n// eslint-disable-next-line complexity, max-statements\nexport function copyToTexture(\n sourceTexture: Framebuffer | Texture,\n destinationTexture: Texture | GL,\n options?: {\n sourceX?: number;\n sourceY?: number;\n\n targetX?: number;\n targetY?: number;\n targetZ?: number;\n targetMipmaplevel?: number;\n targetInternalFormat?: number;\n\n width?: number; // defaults to target width\n height?: number; // defaults to target height\n }\n): Texture {\n const {\n sourceX = 0,\n sourceY = 0,\n // attachment = GL.COLOR_ATTACHMENT0, // TODO - support gl.readBuffer\n targetMipmaplevel = 0,\n targetInternalFormat = GL.RGBA\n } = options || {};\n let {\n targetX,\n targetY,\n targetZ,\n width, // defaults to target width\n height // defaults to target height\n } = options || {};\n\n const {framebuffer, deleteFramebuffer} = getFramebuffer(sourceTexture);\n // assert(framebuffer);\n const webglFramebuffer = framebuffer;\n const {device, handle} = webglFramebuffer;\n const isSubCopy =\n typeof targetX !== 'undefined' ||\n typeof targetY !== 'undefined' ||\n typeof targetZ !== 'undefined';\n targetX = targetX || 0;\n targetY = targetY || 0;\n targetZ = targetZ || 0;\n const prevHandle = device.gl.bindFramebuffer(GL.FRAMEBUFFER, handle);\n // TODO - support gl.readBuffer (WebGL2 only)\n // const prevBuffer = gl.readBuffer(attachment);\n // assert(target);\n let texture: WEBGLTexture | null = null;\n let textureTarget: GL;\n if (destinationTexture instanceof WEBGLTexture) {\n texture = destinationTexture;\n width = Number.isFinite(width) ? width : texture.width;\n height = Number.isFinite(height) ? height : texture.height;\n texture?._bind(0);\n // @ts-ignore\n textureTarget = texture.target;\n } else {\n // @ts-ignore\n textureTarget = target;\n }\n\n if (!isSubCopy) {\n device.gl.copyTexImage2D(\n textureTarget,\n targetMipmaplevel,\n targetInternalFormat,\n sourceX,\n sourceY,\n width,\n height,\n 0 /* border must be 0 */\n );\n } else {\n switch (textureTarget) {\n case GL.TEXTURE_2D:\n case GL.TEXTURE_CUBE_MAP:\n device.gl.copyTexSubImage2D(\n textureTarget,\n targetMipmaplevel,\n targetX,\n targetY,\n sourceX,\n sourceY,\n width,\n height\n );\n break;\n case GL.TEXTURE_2D_ARRAY:\n case GL.TEXTURE_3D:\n device.gl.copyTexSubImage3D(\n textureTarget,\n targetMipmaplevel,\n targetX,\n targetY,\n targetZ,\n sourceX,\n sourceY,\n width,\n height\n );\n break;\n default:\n }\n }\n if (texture) {\n texture._unbind();\n }\n // @ts-expect-error\n device.gl.bindFramebuffer(GL.FRAMEBUFFER, prevHandle || null);\n if (deleteFramebuffer) {\n framebuffer.destroy();\n }\n return texture;\n}\n\nfunction getFramebuffer(source: Texture | Framebuffer): {\n framebuffer: WEBGLFramebuffer;\n deleteFramebuffer: boolean;\n} {\n if (!(source instanceof Framebuffer)) {\n return {framebuffer: toFramebuffer(source), deleteFramebuffer: true};\n }\n return {framebuffer: source as WEBGLFramebuffer, deleteFramebuffer: false};\n}\n\n/**\n * Wraps a given texture into a framebuffer object, that can be further used\n * to read data from the texture object.\n */\nexport function toFramebuffer(texture: Texture, props?: FramebufferProps): WEBGLFramebuffer {\n const {device, width, height, id} = texture;\n const framebuffer = device.createFramebuffer({\n ...props,\n id: `framebuffer-for-${id}`,\n width,\n height,\n colorAttachments: [texture]\n });\n return framebuffer as WEBGLFramebuffer;\n}\n\n// eslint-disable-next-line max-params\nfunction getPixelArray(\n pixelArray,\n glType: GLDataType | GLPixelType,\n glFormat: GL,\n width: number,\n height: number,\n depth?: number\n): Uint8Array | Uint16Array | Float32Array {\n if (pixelArray) {\n return pixelArray;\n }\n // const formatInfo = getTextureFormatInfo(format);\n // Allocate pixel array if not already available, using supplied type\n glType ||= GL.UNSIGNED_BYTE;\n const shaderType = convertGLDataTypeToDataType(glType);\n const ArrayType = dataTypeDecoder.getTypedArrayConstructor(shaderType);\n const components = glFormatToComponents(glFormat);\n // TODO - check for composite type (components = 1).\n return new ArrayType(width * height * components) as Uint8Array | Uint16Array | Float32Array;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {TypedArray} from '@math.gl/types';\nimport type {\n DeviceProps,\n DeviceInfo,\n DeviceTextureFormatCapabilities,\n CanvasContextProps,\n PresentationContextProps,\n PresentationContext,\n Buffer,\n Texture,\n Framebuffer,\n VertexArray,\n VertexArrayProps,\n BufferProps,\n ShaderProps,\n // Sampler,\n SamplerProps,\n TextureProps,\n ExternalTexture,\n ExternalTextureProps,\n FramebufferProps,\n // RenderPipeline,\n RenderPipelineProps,\n SharedRenderPipeline,\n ComputePipeline,\n ComputePipelineProps,\n // CommandEncoder,\n CommandEncoderProps,\n TransformFeedbackProps,\n QuerySetProps,\n Resource,\n VertexFormat\n} from '@luma.gl/core';\nimport {Device, CanvasContext, log} from '@luma.gl/core';\nimport type {GLExtensions} from '@luma.gl/webgl/constants';\nimport {WebGLStateTracker} from '../context/state-tracker/webgl-state-tracker';\nimport {createBrowserContext} from '../context/helpers/create-browser-context';\nimport {getWebGLContextData} from '../context/helpers/webgl-context-data';\nimport {getDeviceInfo} from './device-helpers/webgl-device-info';\nimport {WebGLDeviceFeatures} from './device-helpers/webgl-device-features';\nimport {WebGLDeviceLimits} from './device-helpers/webgl-device-limits';\nimport {WebGLCanvasContext} from './webgl-canvas-context';\nimport {WebGLPresentationContext} from './webgl-presentation-context';\nimport type {Spector} from '../context/debug/spector-types';\nimport {initializeSpectorJS} from '../context/debug/spector';\nimport {makeDebugContext} from '../context/debug/webgl-developer-tools';\nimport {getTextureFormatCapabilitiesWebGL} from './converters/webgl-texture-table';\nimport {uid} from '../utils/uid';\n\nimport {WEBGLBuffer} from './resources/webgl-buffer';\nimport {WEBGLShader} from './resources/webgl-shader';\nimport {WEBGLSampler} from './resources/webgl-sampler';\nimport {WEBGLTexture} from './resources/webgl-texture';\nimport {WEBGLFramebuffer} from './resources/webgl-framebuffer';\nimport {WEBGLRenderPipeline} from './resources/webgl-render-pipeline';\nimport {WEBGLSharedRenderPipeline} from './resources/webgl-shared-render-pipeline';\nimport {WEBGLCommandEncoder} from './resources/webgl-command-encoder';\nimport {WEBGLCommandBuffer} from './resources/webgl-command-buffer';\nimport {WEBGLVertexArray} from './resources/webgl-vertex-array';\nimport {WEBGLTransformFeedback} from './resources/webgl-transform-feedback';\nimport {WEBGLQuerySet} from './resources/webgl-query-set';\nimport {WEBGLFence} from './resources/webgl-fence';\n\nimport {readPixelsToArray, readPixelsToBuffer} from './helpers/webgl-texture-utils';\nimport {\n setGLParameters,\n getGLParameters,\n resetGLParameters\n} from '../context/parameters/unified-parameter-api';\nimport {withGLParameters} from '../context/state-tracker/with-parameters';\nimport {getWebGLExtension} from '../context/helpers/webgl-extensions';\n\n/** WebGPU style Device API for a WebGL context */\nexport class WebGLDevice extends Device {\n static getDeviceFromContext(gl: WebGL2RenderingContext | null): WebGLDevice | null {\n if (!gl) {\n return null;\n }\n // @ts-expect-error Ingore WebGL2RenderingContext type\n return gl.luma?.device ?? null;\n }\n // Public `Device` API\n\n /** type of this device */\n readonly type = 'webgl';\n\n // Use the ! assertion to handle the case where _reuseDevices causes the constructor to return early\n /** The underlying WebGL context */\n readonly handle!: WebGL2RenderingContext;\n features!: WebGLDeviceFeatures;\n limits!: WebGLDeviceLimits;\n readonly info!: DeviceInfo;\n readonly canvasContext!: WebGLCanvasContext;\n\n readonly preferredColorFormat = 'rgba8unorm';\n readonly preferredDepthFormat = 'depth24plus';\n\n commandEncoder!: WEBGLCommandEncoder;\n\n readonly lost: Promise<{reason: 'destroyed'; message: string}>;\n\n private _resolveContextLost?: (value: {reason: 'destroyed'; message: string}) => void;\n\n /** WebGL2 context. */\n readonly gl!: WebGL2RenderingContext;\n\n /** Store constants */\n // @ts-ignore TODO fix\n _constants: (TypedArray | null)[];\n\n /** State used by luma.gl classes - TODO - not used? */\n readonly extensions!: GLExtensions;\n _polyfilled: boolean = false;\n\n /** Instance of Spector.js (if initialized) */\n spectorJS!: Spector | null;\n\n //\n // Public API\n //\n\n override get [Symbol.toStringTag](): string {\n return 'WebGLDevice';\n }\n\n override toString(): string {\n return `${this[Symbol.toStringTag]}(${this.id})`;\n }\n\n override isVertexFormatSupported(format: VertexFormat): boolean {\n switch (format) {\n case 'unorm8x4-bgra':\n return false;\n default:\n return true;\n }\n }\n\n constructor(props: DeviceProps) {\n super({...props, id: props.id || uid('webgl-device')});\n\n const canvasContextProps = Device._getCanvasContextProps(props)!;\n\n // WebGL requires a canvas to be created before creating the context\n if (!canvasContextProps) {\n throw new Error('WebGLDevice requires props.createCanvasContext to be set');\n }\n\n // Check if the WebGL context is already associated with a device\n // Note that this can be avoided in webgl2adapter.create() if\n // DeviceProps._reuseDevices is set.\n // @ts-expect-error device is attached to context\n const existingContext = canvasContextProps.canvas?.gl ?? null;\n let device: WebGLDevice | null = WebGLDevice.getDeviceFromContext(existingContext);\n if (device) {\n throw new Error(`WebGL context already attached to device ${device.id}`);\n }\n\n // Create and instrument context\n this.canvasContext = new WebGLCanvasContext(this, canvasContextProps);\n\n this.lost = new Promise<{reason: 'destroyed'; message: string}>(resolve => {\n this._resolveContextLost = resolve;\n });\n\n const webglContextAttributes: WebGLContextAttributes = {...props.webgl};\n // Copy props from CanvasContextProps\n if (canvasContextProps.alphaMode === 'premultiplied') {\n webglContextAttributes.premultipliedAlpha = true;\n }\n if (props.powerPreference !== undefined) {\n webglContextAttributes.powerPreference = props.powerPreference;\n }\n if (props.failIfMajorPerformanceCaveat !== undefined) {\n webglContextAttributes.failIfMajorPerformanceCaveat = props.failIfMajorPerformanceCaveat;\n }\n\n // Check if we should attach to an externally created context or create a new context\n const externalGLContext = this.props._handle as WebGL2RenderingContext | null;\n\n const gl =\n externalGLContext ||\n createBrowserContext(\n this.canvasContext.canvas,\n {\n onContextLost: (event: Event) =>\n this._resolveContextLost?.({\n reason: 'destroyed',\n message: 'Entered sleep mode, or too many apps or browser tabs are using the GPU.'\n }),\n // eslint-disable-next-line no-console\n onContextRestored: (event: Event) => console.log('WebGL context restored')\n },\n webglContextAttributes\n );\n\n if (!gl) {\n throw new Error('WebGL context creation failed');\n }\n\n // Note that the browser will only create one WebGL context per canvas.\n // This means that a newly created gl context may already have a device attached to it.\n device = WebGLDevice.getDeviceFromContext(gl);\n if (device) {\n if (props._reuseDevices) {\n log.log(\n 1,\n `Not creating a new Device, instead returning a reference to Device ${device.id} already attached to WebGL context`,\n device\n )();\n // Destroy the orphaned canvas context that was created above (line 149)\n // to prevent its ResizeObserver from firing callbacks with undefined device\n this.canvasContext.destroy();\n device._reused = true;\n return device;\n }\n throw new Error(`WebGL context already attached to device ${device.id}`);\n }\n\n this.handle = gl;\n this.gl = gl;\n\n // Add spector debug instrumentation to context\n // We need to trust spector integration to decide if spector should be initialized\n // We also run spector instrumentation first, otherwise spector can clobber luma instrumentation.\n this.spectorJS = initializeSpectorJS({...this.props, gl: this.handle});\n\n // Instrument context\n const contextData = getWebGLContextData(this.handle);\n contextData.device = this; // Update GL context: Link webgl context back to device\n\n if (!contextData.extensions) {\n contextData.extensions = {};\n }\n this.extensions = contextData.extensions;\n\n // initialize luma Device fields\n this.info = getDeviceInfo(this.gl, this.extensions);\n this.limits = new WebGLDeviceLimits(this.gl);\n this.features = new WebGLDeviceFeatures(this.gl, this.extensions, this.props._disabledFeatures);\n if (this.props._initializeFeatures) {\n this.features.initializeFeatures();\n }\n\n // Install context state tracking\n const glState = new WebGLStateTracker(this.gl, {\n log: (...args: any[]) => log.log(1, ...args)()\n });\n glState.trackState(this.gl, {copyState: false});\n\n // props.debug - instrument the WebGL context with Khronos debug tools\n // props.debugWebGL - activate WebGL context tracing, force log level to at least 1\n if (props.debug || props.debugWebGL) {\n this.gl = makeDebugContext(this.gl, {debugWebGL: true, traceWebGL: props.debugWebGL});\n log.warn('WebGL debug mode activated. Performance reduced.')();\n }\n if (props.debugWebGL) {\n log.level = Math.max(log.level, 1);\n }\n\n this.commandEncoder = new WEBGLCommandEncoder(this, {id: `${this}-command-encoder`});\n this.canvasContext._startObservers();\n }\n\n /**\n * Destroys the device\n *\n * @note \"Detaches\" from the WebGL context unless _reuseDevices is true.\n *\n * @note The underlying WebGL context is not immediately destroyed,\n * but may be destroyed later through normal JavaScript garbage collection.\n * This is a fundamental limitation since WebGL does not offer any\n * browser API for destroying WebGL contexts.\n */\n destroy(): void {\n this.commandEncoder?.destroy();\n // Note that deck.gl (especially in React strict mode) depends on being able\n // to asynchronously create a Device against the same canvas (i.e. WebGL context)\n // multiple times and getting the same device back. Since deck.gl is not aware\n // of this sharing, it might call destroy() multiple times on the same device.\n // Therefore we must do nothing in destroy() if props._reuseDevices is true\n if (!this.props._reuseDevices && !this._reused) {\n // Delete the reference to the device that we store on the WebGL context\n const contextData = getWebGLContextData(this.handle);\n contextData.device = null;\n }\n }\n\n get isLost(): boolean {\n return this.gl.isContextLost();\n }\n\n // IMPLEMENTATION OF ABSTRACT DEVICE\n\n createCanvasContext(props?: CanvasContextProps): CanvasContext {\n throw new Error('WebGL only supports a single canvas');\n }\n\n createPresentationContext(props?: PresentationContextProps): PresentationContext {\n return new WebGLPresentationContext(this, props || {});\n }\n\n createBuffer(props: BufferProps | ArrayBuffer | ArrayBufferView): WEBGLBuffer {\n const newProps = this._normalizeBufferProps(props);\n return new WEBGLBuffer(this, newProps);\n }\n\n createTexture(props: TextureProps): WEBGLTexture {\n return new WEBGLTexture(this, props);\n }\n\n createExternalTexture(props: ExternalTextureProps): ExternalTexture {\n throw new Error('createExternalTexture() not implemented'); // return new Program(props);\n }\n\n createSampler(props: SamplerProps): WEBGLSampler {\n return new WEBGLSampler(this, props);\n }\n\n createShader(props: ShaderProps): WEBGLShader {\n return new WEBGLShader(this, props);\n }\n\n createFramebuffer(props: FramebufferProps): WEBGLFramebuffer {\n return new WEBGLFramebuffer(this, props);\n }\n\n createVertexArray(props: VertexArrayProps): VertexArray {\n return new WEBGLVertexArray(this, props);\n }\n\n createTransformFeedback(props: TransformFeedbackProps): WEBGLTransformFeedback {\n return new WEBGLTransformFeedback(this, props);\n }\n\n createQuerySet(props: QuerySetProps): WEBGLQuerySet {\n return new WEBGLQuerySet(this, props);\n }\n\n override createFence(): WEBGLFence {\n return new WEBGLFence(this);\n }\n\n createRenderPipeline(props: RenderPipelineProps): WEBGLRenderPipeline {\n return new WEBGLRenderPipeline(this, props);\n }\n\n override _createSharedRenderPipelineWebGL(props: RenderPipelineProps): SharedRenderPipeline {\n return new WEBGLSharedRenderPipeline(\n this,\n props as RenderPipelineProps & {vs: WEBGLShader; fs: WEBGLShader}\n );\n }\n\n createComputePipeline(props?: ComputePipelineProps): ComputePipeline {\n throw new Error('ComputePipeline not supported in WebGL');\n }\n\n override createCommandEncoder(props: CommandEncoderProps = {}): WEBGLCommandEncoder {\n return new WEBGLCommandEncoder(this, props);\n }\n\n /**\n * Offscreen Canvas Support: Commit the frame\n * https://developer.mozilla.org/en-US/docs/Web/API/WebGL2RenderingContext/commit\n * Chrome's offscreen canvas does not require gl.commit\n */\n submit(commandBuffer?: WEBGLCommandBuffer): void {\n let submittedCommandEncoder: WEBGLCommandEncoder | null = null;\n if (!commandBuffer) {\n ({submittedCommandEncoder, commandBuffer} = this._finalizeDefaultCommandEncoderForSubmit());\n }\n\n try {\n commandBuffer._executeCommands();\n\n if (submittedCommandEncoder) {\n submittedCommandEncoder\n .resolveTimeProfilingQuerySet()\n .then(() => {\n this.commandEncoder._gpuTimeMs = submittedCommandEncoder._gpuTimeMs;\n })\n .catch(() => {});\n }\n } finally {\n commandBuffer.destroy();\n }\n }\n\n private _finalizeDefaultCommandEncoderForSubmit(): {\n submittedCommandEncoder: WEBGLCommandEncoder;\n commandBuffer: WEBGLCommandBuffer;\n } {\n const submittedCommandEncoder = this.commandEncoder;\n const commandBuffer = submittedCommandEncoder.finish();\n this.commandEncoder.destroy();\n this.commandEncoder = this.createCommandEncoder({\n id: submittedCommandEncoder.props.id,\n timeProfilingQuerySet: submittedCommandEncoder.getTimeProfilingQuerySet()\n });\n return {submittedCommandEncoder, commandBuffer};\n }\n\n //\n // TEMPORARY HACKS - will be removed in v9.1\n //\n\n /** @deprecated - should use command encoder */\n override readPixelsToArrayWebGL(\n source: Framebuffer | Texture,\n options?: {\n sourceX?: number;\n sourceY?: number;\n sourceFormat?: number;\n sourceAttachment?: number;\n target?: Uint8Array | Uint16Array | Float32Array;\n // following parameters are auto deduced if not provided\n sourceWidth?: number;\n sourceHeight?: number;\n sourceType?: number;\n }\n ): Uint8Array | Uint16Array | Float32Array {\n return readPixelsToArray(source, options);\n }\n\n /** @deprecated - should use command encoder */\n override readPixelsToBufferWebGL(\n source: Framebuffer | Texture,\n options?: {\n sourceX?: number;\n sourceY?: number;\n sourceFormat?: number;\n target?: Buffer; // A new Buffer object is created when not provided.\n targetByteOffset?: number; // byte offset in buffer object\n // following parameters are auto deduced if not provided\n sourceWidth?: number;\n sourceHeight?: number;\n sourceType?: number;\n }\n ): Buffer {\n return readPixelsToBuffer(source, options);\n }\n\n override setParametersWebGL(parameters: any): void {\n setGLParameters(this.gl, parameters);\n }\n\n override getParametersWebGL(parameters: any): any {\n return getGLParameters(this.gl, parameters);\n }\n\n override withParametersWebGL(parameters: any, func: any): any {\n return withGLParameters(this.gl, parameters, func);\n }\n\n override resetWebGL(): void {\n log.warn('WebGLDevice.resetWebGL is deprecated, use only for debugging')();\n resetGLParameters(this.gl);\n }\n\n override _getDeviceSpecificTextureFormatCapabilities(\n capabilities: DeviceTextureFormatCapabilities\n ): DeviceTextureFormatCapabilities {\n return getTextureFormatCapabilitiesWebGL(this.gl, capabilities, this.extensions);\n }\n\n //\n // WebGL-only API (not part of `Device` API)\n //\n\n /**\n * Triggers device (or WebGL context) loss.\n * @note primarily intended for testing how application reacts to device loss\n */\n override loseDevice(): boolean {\n let deviceLossTriggered = false;\n const extensions = this.getExtension('WEBGL_lose_context');\n const ext = extensions.WEBGL_lose_context;\n if (ext) {\n deviceLossTriggered = true;\n ext.loseContext();\n // ext.loseContext should trigger context loss callback but the platform may not do this, so do it explicitly\n }\n this._resolveContextLost?.({\n reason: 'destroyed',\n message: 'Application triggered context loss'\n });\n return deviceLossTriggered;\n }\n\n /** Save current WebGL context state onto an internal stack */\n pushState(): void {\n const webglState = WebGLStateTracker.get(this.gl);\n webglState.push();\n }\n\n /** Restores previously saved context state */\n popState(): void {\n const webglState = WebGLStateTracker.get(this.gl);\n webglState.pop();\n }\n\n /**\n * Returns the GL. constant that corresponds to a numeric value of a GL constant\n * Be aware that there are some duplicates especially for constants that are 0,\n * so this isn't guaranteed to return the right key in all cases.\n */\n getGLKey(value: unknown, options?: {emptyIfUnknown?: boolean}): string {\n const number = Number(value);\n for (const key in this.gl) {\n // @ts-ignore expect-error depends on settings\n if (this.gl[key] === number) {\n return `GL.${key}`;\n }\n }\n // No constant found. Stringify the value and return it.\n return options?.emptyIfUnknown ? '' : String(value);\n }\n\n /**\n * Returns a map with any GL. constants mapped to strings, both for keys and values\n */\n getGLKeys(glParameters: Record): Record {\n const opts = {emptyIfUnknown: true};\n return Object.entries(glParameters).reduce>((keys, [key, value]) => {\n // eslint-disable-next-line @typescript-eslint/no-base-to-string\n keys[`${key}:${this.getGLKey(key, opts)}`] = `${value}:${this.getGLKey(value, opts)}`;\n return keys;\n }, {});\n }\n\n /**\n * Set a constant value for a location. Disabled attributes at that location will read from this value\n * @note WebGL constants are stored globally on the WebGL context, not the VertexArray\n * so they need to be updated before every render\n * @todo - remember/cache values to avoid setting them unnecessarily?\n */\n setConstantAttributeWebGL(location: number, constant: TypedArray): void {\n const maxVertexAttributes = this.limits.maxVertexAttributes;\n this._constants = this._constants || new Array(maxVertexAttributes).fill(null);\n const currentConstant = this._constants[location];\n if (currentConstant && compareConstantArrayValues(currentConstant, constant)) {\n log.info(\n 1,\n `setConstantAttributeWebGL(${location}) could have been skipped, value unchanged`\n )();\n }\n this._constants[location] = constant;\n\n switch (constant.constructor) {\n case Float32Array:\n setConstantFloatArray(this, location, constant as Float32Array);\n break;\n case Int32Array:\n setConstantIntArray(this, location, constant as Int32Array);\n break;\n case Uint32Array:\n setConstantUintArray(this, location, constant as Uint32Array);\n break;\n default:\n throw new Error('constant');\n }\n }\n\n /** Ensure extensions are only requested once */\n getExtension(name: keyof GLExtensions): GLExtensions {\n getWebGLExtension(this.gl, name, this.extensions);\n return this.extensions;\n }\n\n // INTERNAL SUPPORT METHODS FOR WEBGL RESOURCES\n\n /**\n * Storing data on a special field on WebGLObjects makes that data visible in SPECTOR chrome debug extension\n * luma.gl ids and props can be inspected\n */\n _setWebGLDebugMetadata(\n handle: unknown,\n resource: Resource,\n options: {spector: Record}\n ): void {\n // @ts-expect-error\n handle.luma = resource;\n\n const spectorMetadata = {props: options.spector, id: options.spector['id']};\n // @ts-expect-error\n // eslint-disable-next-line camelcase\n handle.__SPECTOR_Metadata = spectorMetadata;\n }\n}\n\n/** Set constant float array attribute */\nfunction setConstantFloatArray(device: WebGLDevice, location: number, array: Float32Array): void {\n switch (array.length) {\n case 1:\n device.gl.vertexAttrib1fv(location, array);\n break;\n case 2:\n device.gl.vertexAttrib2fv(location, array);\n break;\n case 3:\n device.gl.vertexAttrib3fv(location, array);\n break;\n case 4:\n device.gl.vertexAttrib4fv(location, array);\n break;\n default:\n // assert(false);\n }\n}\n\n/** Set constant signed int array attribute */\nfunction setConstantIntArray(device: WebGLDevice, location: number, array: Int32Array): void {\n device.gl.vertexAttribI4iv(location, array);\n // TODO - not clear if we need to use the special forms, more testing needed\n // switch (array.length) {\n // case 1:\n // gl.vertexAttribI1iv(location, array);\n // break;\n // case 2:\n // gl.vertexAttribI2iv(location, array);\n // break;\n // case 3:\n // gl.vertexAttribI3iv(location, array);\n // break;\n // case 4:\n // break;\n // default:\n // assert(false);\n // }\n}\n\n/** Set constant unsigned int array attribute */\nfunction setConstantUintArray(device: WebGLDevice, location: number, array: Uint32Array) {\n device.gl.vertexAttribI4uiv(location, array);\n // TODO - not clear if we need to use the special forms, more testing needed\n // switch (array.length) {\n // case 1:\n // gl.vertexAttribI1uiv(location, array);\n // break;\n // case 2:\n // gl.vertexAttribI2uiv(location, array);\n // break;\n // case 3:\n // gl.vertexAttribI3uiv(location, array);\n // break;\n // case 4:\n // gl.vertexAttribI4uiv(location, array);\n // break;\n // default:\n // assert(false);\n // }\n}\n\n/**\n * Compares contents of two typed arrays\n * @todo max length?\n */\nfunction compareConstantArrayValues(v1: TypedArray, v2: TypedArray): boolean {\n if (!v1 || !v2 || v1.length !== v2.length || v1.constructor !== v2.constructor) {\n return false;\n }\n for (let i = 0; i < v1.length; ++i) {\n if (v1[i] !== v2[i]) {\n return false;\n }\n }\n return true;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {WebGLDevice} from './webgl-device';\nimport {Adapter, Device, DeviceProps, log} from '@luma.gl/core';\nimport {enforceWebGL2} from '../context/polyfills/polyfill-webgl1-extensions';\nimport {loadSpectorJS, DEFAULT_SPECTOR_PROPS} from '../context/debug/spector';\nimport {loadWebGLDeveloperTools} from '../context/debug/webgl-developer-tools';\n\nconst LOG_LEVEL = 1;\n\nexport class WebGLAdapter extends Adapter {\n /** type of device's created by this adapter */\n readonly type: Device['type'] = 'webgl';\n\n constructor() {\n super();\n // Add spector default props to device default props, so that runtime settings are observed\n Device.defaultProps = {...Device.defaultProps, ...DEFAULT_SPECTOR_PROPS};\n }\n\n /** Force any created WebGL contexts to be WebGL2 contexts, polyfilled with WebGL1 extensions */\n enforceWebGL2(enable: boolean): void {\n enforceWebGL2(enable);\n }\n\n /** Check if WebGL 2 is available */\n isSupported(): boolean {\n return typeof WebGL2RenderingContext !== 'undefined';\n }\n\n override isDeviceHandle(handle: unknown): boolean {\n // WebGL\n if (typeof WebGL2RenderingContext !== 'undefined' && handle instanceof WebGL2RenderingContext) {\n return true;\n }\n\n if (typeof WebGLRenderingContext !== 'undefined' && handle instanceof WebGLRenderingContext) {\n log.warn('WebGL1 is not supported', handle)();\n }\n\n return false;\n }\n\n /**\n * Get a device instance from a GL context\n * Creates a WebGLCanvasContext against the contexts canvas\n * @note autoResize will be disabled, assuming that whoever created the external context will be handling resizes.\n * @param gl\n * @returns\n */\n async attach(gl: Device | WebGL2RenderingContext, props: DeviceProps = {}): Promise {\n const {WebGLDevice} = await import('./webgl-device');\n if (gl instanceof WebGLDevice) {\n return gl;\n }\n const existingDevice = WebGLDevice.getDeviceFromContext(gl as WebGL2RenderingContext | null);\n if (existingDevice) {\n return existingDevice;\n }\n if (!isWebGL(gl)) {\n throw new Error('Invalid WebGL2RenderingContext');\n }\n\n const createCanvasContext = props.createCanvasContext === true ? {} : props.createCanvasContext;\n\n // We create a new device using the provided WebGL context and its canvas\n // Assume that whoever created the external context will be handling resizes.\n return new WebGLDevice({\n ...props,\n _handle: gl,\n createCanvasContext: {canvas: gl.canvas, autoResize: false, ...createCanvasContext}\n });\n }\n\n async create(props: DeviceProps = {}): Promise {\n const {WebGLDevice} = await import('./webgl-device');\n\n const promises: Promise[] = [];\n\n // Load webgl and spector debug scripts from CDN if requested\n if (props.debugWebGL || props.debug) {\n promises.push(loadWebGLDeveloperTools());\n }\n\n if (props.debugSpectorJS) {\n promises.push(loadSpectorJS(props));\n }\n\n // Wait for all the loads to settle before creating the context.\n // The Device.create() functions are async, so in contrast to the constructor, we can `await` here.\n const results = await Promise.allSettled(promises);\n for (const result of results) {\n if (result.status === 'rejected') {\n log.error(`Failed to initialize debug libraries ${result.reason}`)();\n }\n }\n\n try {\n const device = new WebGLDevice(props);\n\n log.groupCollapsed(LOG_LEVEL, `WebGLDevice ${device.id} created`)();\n // Log some debug info about the newly created context\n const message = `\\\n${device._reused ? 'Reusing' : 'Created'} device with WebGL2 ${device.props.debug ? 'debug ' : ''}context: \\\n${device.info.vendor}, ${device.info.renderer} for canvas: ${device.canvasContext.id}`;\n log.probe(LOG_LEVEL, message)();\n log.table(LOG_LEVEL, device.info)();\n return device;\n } finally {\n log.groupEnd(LOG_LEVEL)();\n log.info(\n LOG_LEVEL,\n `%cWebGL call tracing: luma.log.set('debug-webgl') `,\n 'color: white; background: blue; padding: 2px 6px; border-radius: 3px;'\n )();\n }\n }\n}\n\n/** Check if supplied parameter is a WebGL2RenderingContext */\nfunction isWebGL(gl: any): gl is WebGL2RenderingContext {\n if (typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext) {\n return true;\n }\n return Boolean(gl && typeof gl.createVertexArray === 'function');\n}\n\nexport const webgl2Adapter = new WebGLAdapter();\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// luma.gl Base WebGL wrapper library\n// Provides simple class/function wrappers around the low level webgl objects\n// These classes are intentionally close to the WebGL API\n// but make it easier to use.\n// Higher level abstractions can be built on these classes\n\n// Types\nexport type {WebGLDeviceLimits} from './adapter/device-helpers/webgl-device-limits';\nexport {GL} from './constants/webgl-constants';\nexport type {\n GLTextureTarget,\n GLTextureCubeMapTarget,\n GLTexelDataFormat,\n GLPrimitiveTopology,\n GLPrimitive,\n GLDataType,\n GLPixelType,\n GLUniformType,\n GLSamplerType,\n GLFunction,\n GLBlendEquation,\n GLBlendFunction,\n GLStencilOp,\n GLSamplerParameters,\n GLValueParameters,\n GLPackParameters,\n GLUnpackParameters,\n GLFunctionParameters,\n GLParameters,\n GLLimits,\n GLExtensions,\n GLPolygonMode,\n GLProvokingVertex\n} from './constants/webgl-types';\n\n// WebGL adapter classes\nexport {webgl2Adapter} from './adapter/webgl-adapter';\nexport type {WebGLAdapter} from './adapter/webgl-adapter';\n\n// WebGL Device classes\nexport {WebGLDevice} from './adapter/webgl-device';\nexport {WebGLCanvasContext} from './adapter/webgl-canvas-context';\n\n// WebGL Resource classes\nexport {WEBGLBuffer} from './adapter/resources/webgl-buffer';\nexport {WEBGLTexture} from './adapter/resources/webgl-texture';\n// export {WEBGLExternalTexture} from './adapter/resources/webgl-external-texture';\nexport {WEBGLShader} from './adapter/resources/webgl-shader';\nexport {WEBGLSampler} from './adapter/resources/webgl-sampler';\nexport {WEBGLFramebuffer} from './adapter/resources/webgl-framebuffer';\nexport {WEBGLFence} from './adapter/resources/webgl-fence';\n\nexport {WEBGLRenderPipeline} from './adapter/resources/webgl-render-pipeline';\n// export {WEBGLComputePipeline} from './adapter/resources/webgl-compute-pipeline';\nexport {WEBGLCommandEncoder} from './adapter/resources/webgl-command-encoder';\nexport {WEBGLRenderPass} from './adapter/resources/webgl-render-pass';\n// export {WEBGLComputePass} from './adapter/resources/webgl-compute-pass';\nexport {WEBGLVertexArray} from './adapter/resources/webgl-vertex-array';\n\n// WebGL adapter classes\nexport {WEBGLTransformFeedback} from './adapter/resources/webgl-transform-feedback';\n\n// Unified parameter API\n\nexport {setDeviceParameters, withDeviceParameters} from './adapter/converters/device-parameters';\n\n// HELPERS - EXPERIMENTAL\nexport {getShaderLayoutFromGLSL} from './adapter/helpers/get-shader-layout-from-glsl';\nexport {WebGLStateTracker} from './context/state-tracker/webgl-state-tracker';\n\n// DEPRECATED TEST EXPORTS\nexport {\n resetGLParameters,\n setGLParameters,\n getGLParameters\n} from './context/parameters/unified-parameter-api';\n\nexport {withGLParameters} from './context/state-tracker/with-parameters';\n","// A port of an algorithm by Johannes Baagøe , 2010\n// http://baagoe.com/en/RandomMusings/javascript/\n// https://github.com/nquinlan/better-random-numbers-for-javascript-mirror\n// Original work is under MIT license -\n\n// Copyright (C) 2010 by Johannes Baagøe \n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n\n\n(function(global, module, define) {\n\nfunction Alea(seed) {\n var me = this, mash = Mash();\n\n me.next = function() {\n var t = 2091639 * me.s0 + me.c * 2.3283064365386963e-10; // 2^-32\n me.s0 = me.s1;\n me.s1 = me.s2;\n return me.s2 = t - (me.c = t | 0);\n };\n\n // Apply the seeding algorithm from Baagoe.\n me.c = 1;\n me.s0 = mash(' ');\n me.s1 = mash(' ');\n me.s2 = mash(' ');\n me.s0 -= mash(seed);\n if (me.s0 < 0) { me.s0 += 1; }\n me.s1 -= mash(seed);\n if (me.s1 < 0) { me.s1 += 1; }\n me.s2 -= mash(seed);\n if (me.s2 < 0) { me.s2 += 1; }\n mash = null;\n}\n\nfunction copy(f, t) {\n t.c = f.c;\n t.s0 = f.s0;\n t.s1 = f.s1;\n t.s2 = f.s2;\n return t;\n}\n\nfunction impl(seed, opts) {\n var xg = new Alea(seed),\n state = opts && opts.state,\n prng = xg.next;\n prng.int32 = function() { return (xg.next() * 0x100000000) | 0; }\n prng.double = function() {\n return prng() + (prng() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53\n };\n prng.quick = prng;\n if (state) {\n if (typeof(state) == 'object') copy(state, xg);\n prng.state = function() { return copy(xg, {}); }\n }\n return prng;\n}\n\nfunction Mash() {\n var n = 0xefc8249d;\n\n var mash = function(data) {\n data = String(data);\n for (var i = 0; i < data.length; i++) {\n n += data.charCodeAt(i);\n var h = 0.02519603282416938 * n;\n n = h >>> 0;\n h -= n;\n h *= n;\n n = h >>> 0;\n h -= n;\n n += h * 0x100000000; // 2^32\n }\n return (n >>> 0) * 2.3283064365386963e-10; // 2^-32\n };\n\n return mash;\n}\n\n\nif (module && module.exports) {\n module.exports = impl;\n} else if (define && define.amd) {\n define(function() { return impl; });\n} else {\n this.alea = impl;\n}\n\n})(\n this,\n (typeof module) == 'object' && module, // present in node.js\n (typeof define) == 'function' && define // present with an AMD loader\n);\n\n\n","// A Javascript implementaion of the \"xor128\" prng algorithm by\n// George Marsaglia. See http://www.jstatsoft.org/v08/i14/paper\n\n(function(global, module, define) {\n\nfunction XorGen(seed) {\n var me = this, strseed = '';\n\n me.x = 0;\n me.y = 0;\n me.z = 0;\n me.w = 0;\n\n // Set up generator function.\n me.next = function() {\n var t = me.x ^ (me.x << 11);\n me.x = me.y;\n me.y = me.z;\n me.z = me.w;\n return me.w ^= (me.w >>> 19) ^ t ^ (t >>> 8);\n };\n\n if (seed === (seed | 0)) {\n // Integer seed.\n me.x = seed;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (var k = 0; k < strseed.length + 64; k++) {\n me.x ^= strseed.charCodeAt(k) | 0;\n me.next();\n }\n}\n\nfunction copy(f, t) {\n t.x = f.x;\n t.y = f.y;\n t.z = f.z;\n t.w = f.w;\n return t;\n}\n\nfunction impl(seed, opts) {\n var xg = new XorGen(seed),\n state = opts && opts.state,\n prng = function() { return (xg.next() >>> 0) / 0x100000000; };\n prng.double = function() {\n do {\n var top = xg.next() >>> 11,\n bot = (xg.next() >>> 0) / 0x100000000,\n result = (top + bot) / (1 << 21);\n } while (result === 0);\n return result;\n };\n prng.int32 = xg.next;\n prng.quick = prng;\n if (state) {\n if (typeof(state) == 'object') copy(state, xg);\n prng.state = function() { return copy(xg, {}); }\n }\n return prng;\n}\n\nif (module && module.exports) {\n module.exports = impl;\n} else if (define && define.amd) {\n define(function() { return impl; });\n} else {\n this.xor128 = impl;\n}\n\n})(\n this,\n (typeof module) == 'object' && module, // present in node.js\n (typeof define) == 'function' && define // present with an AMD loader\n);\n\n\n","// A Javascript implementaion of the \"xorwow\" prng algorithm by\n// George Marsaglia. See http://www.jstatsoft.org/v08/i14/paper\n\n(function(global, module, define) {\n\nfunction XorGen(seed) {\n var me = this, strseed = '';\n\n // Set up generator function.\n me.next = function() {\n var t = (me.x ^ (me.x >>> 2));\n me.x = me.y; me.y = me.z; me.z = me.w; me.w = me.v;\n return (me.d = (me.d + 362437 | 0)) +\n (me.v = (me.v ^ (me.v << 4)) ^ (t ^ (t << 1))) | 0;\n };\n\n me.x = 0;\n me.y = 0;\n me.z = 0;\n me.w = 0;\n me.v = 0;\n\n if (seed === (seed | 0)) {\n // Integer seed.\n me.x = seed;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (var k = 0; k < strseed.length + 64; k++) {\n me.x ^= strseed.charCodeAt(k) | 0;\n if (k == strseed.length) {\n me.d = me.x << 10 ^ me.x >>> 4;\n }\n me.next();\n }\n}\n\nfunction copy(f, t) {\n t.x = f.x;\n t.y = f.y;\n t.z = f.z;\n t.w = f.w;\n t.v = f.v;\n t.d = f.d;\n return t;\n}\n\nfunction impl(seed, opts) {\n var xg = new XorGen(seed),\n state = opts && opts.state,\n prng = function() { return (xg.next() >>> 0) / 0x100000000; };\n prng.double = function() {\n do {\n var top = xg.next() >>> 11,\n bot = (xg.next() >>> 0) / 0x100000000,\n result = (top + bot) / (1 << 21);\n } while (result === 0);\n return result;\n };\n prng.int32 = xg.next;\n prng.quick = prng;\n if (state) {\n if (typeof(state) == 'object') copy(state, xg);\n prng.state = function() { return copy(xg, {}); }\n }\n return prng;\n}\n\nif (module && module.exports) {\n module.exports = impl;\n} else if (define && define.amd) {\n define(function() { return impl; });\n} else {\n this.xorwow = impl;\n}\n\n})(\n this,\n (typeof module) == 'object' && module, // present in node.js\n (typeof define) == 'function' && define // present with an AMD loader\n);\n\n\n","// A Javascript implementaion of the \"xorshift7\" algorithm by\n// François Panneton and Pierre L'ecuyer:\n// \"On the Xorgshift Random Number Generators\"\n// http://saluc.engr.uconn.edu/refs/crypto/rng/panneton05onthexorshift.pdf\n\n(function(global, module, define) {\n\nfunction XorGen(seed) {\n var me = this;\n\n // Set up generator function.\n me.next = function() {\n // Update xor generator.\n var X = me.x, i = me.i, t, v, w;\n t = X[i]; t ^= (t >>> 7); v = t ^ (t << 24);\n t = X[(i + 1) & 7]; v ^= t ^ (t >>> 10);\n t = X[(i + 3) & 7]; v ^= t ^ (t >>> 3);\n t = X[(i + 4) & 7]; v ^= t ^ (t << 7);\n t = X[(i + 7) & 7]; t = t ^ (t << 13); v ^= t ^ (t << 9);\n X[i] = v;\n me.i = (i + 1) & 7;\n return v;\n };\n\n function init(me, seed) {\n var j, w, X = [];\n\n if (seed === (seed | 0)) {\n // Seed state array using a 32-bit integer.\n w = X[0] = seed;\n } else {\n // Seed state using a string.\n seed = '' + seed;\n for (j = 0; j < seed.length; ++j) {\n X[j & 7] = (X[j & 7] << 15) ^\n (seed.charCodeAt(j) + X[(j + 1) & 7] << 13);\n }\n }\n // Enforce an array length of 8, not all zeroes.\n while (X.length < 8) X.push(0);\n for (j = 0; j < 8 && X[j] === 0; ++j);\n if (j == 8) w = X[7] = -1; else w = X[j];\n\n me.x = X;\n me.i = 0;\n\n // Discard an initial 256 values.\n for (j = 256; j > 0; --j) {\n me.next();\n }\n }\n\n init(me, seed);\n}\n\nfunction copy(f, t) {\n t.x = f.x.slice();\n t.i = f.i;\n return t;\n}\n\nfunction impl(seed, opts) {\n if (seed == null) seed = +(new Date);\n var xg = new XorGen(seed),\n state = opts && opts.state,\n prng = function() { return (xg.next() >>> 0) / 0x100000000; };\n prng.double = function() {\n do {\n var top = xg.next() >>> 11,\n bot = (xg.next() >>> 0) / 0x100000000,\n result = (top + bot) / (1 << 21);\n } while (result === 0);\n return result;\n };\n prng.int32 = xg.next;\n prng.quick = prng;\n if (state) {\n if (state.x) copy(state, xg);\n prng.state = function() { return copy(xg, {}); }\n }\n return prng;\n}\n\nif (module && module.exports) {\n module.exports = impl;\n} else if (define && define.amd) {\n define(function() { return impl; });\n} else {\n this.xorshift7 = impl;\n}\n\n})(\n this,\n (typeof module) == 'object' && module, // present in node.js\n (typeof define) == 'function' && define // present with an AMD loader\n);\n\n","// A Javascript implementaion of Richard Brent's Xorgens xor4096 algorithm.\n//\n// This fast non-cryptographic random number generator is designed for\n// use in Monte-Carlo algorithms. It combines a long-period xorshift\n// generator with a Weyl generator, and it passes all common batteries\n// of stasticial tests for randomness while consuming only a few nanoseconds\n// for each prng generated. For background on the generator, see Brent's\n// paper: \"Some long-period random number generators using shifts and xors.\"\n// http://arxiv.org/pdf/1004.3115v1.pdf\n//\n// Usage:\n//\n// var xor4096 = require('xor4096');\n// random = xor4096(1); // Seed with int32 or string.\n// assert.equal(random(), 0.1520436450538547); // (0, 1) range, 53 bits.\n// assert.equal(random.int32(), 1806534897); // signed int32, 32 bits.\n//\n// For nonzero numeric keys, this impelementation provides a sequence\n// identical to that by Brent's xorgens 3 implementaion in C. This\n// implementation also provides for initalizing the generator with\n// string seeds, or for saving and restoring the state of the generator.\n//\n// On Chrome, this prng benchmarks about 2.1 times slower than\n// Javascript's built-in Math.random().\n\n(function(global, module, define) {\n\nfunction XorGen(seed) {\n var me = this;\n\n // Set up generator function.\n me.next = function() {\n var w = me.w,\n X = me.X, i = me.i, t, v;\n // Update Weyl generator.\n me.w = w = (w + 0x61c88647) | 0;\n // Update xor generator.\n v = X[(i + 34) & 127];\n t = X[i = ((i + 1) & 127)];\n v ^= v << 13;\n t ^= t << 17;\n v ^= v >>> 15;\n t ^= t >>> 12;\n // Update Xor generator array state.\n v = X[i] = v ^ t;\n me.i = i;\n // Result is the combination.\n return (v + (w ^ (w >>> 16))) | 0;\n };\n\n function init(me, seed) {\n var t, v, i, j, w, X = [], limit = 128;\n if (seed === (seed | 0)) {\n // Numeric seeds initialize v, which is used to generates X.\n v = seed;\n seed = null;\n } else {\n // String seeds are mixed into v and X one character at a time.\n seed = seed + '\\0';\n v = 0;\n limit = Math.max(limit, seed.length);\n }\n // Initialize circular array and weyl value.\n for (i = 0, j = -32; j < limit; ++j) {\n // Put the unicode characters into the array, and shuffle them.\n if (seed) v ^= seed.charCodeAt((j + 32) % seed.length);\n // After 32 shuffles, take v as the starting w value.\n if (j === 0) w = v;\n v ^= v << 10;\n v ^= v >>> 15;\n v ^= v << 4;\n v ^= v >>> 13;\n if (j >= 0) {\n w = (w + 0x61c88647) | 0; // Weyl.\n t = (X[j & 127] ^= (v + w)); // Combine xor and weyl to init array.\n i = (0 == t) ? i + 1 : 0; // Count zeroes.\n }\n }\n // We have detected all zeroes; make the key nonzero.\n if (i >= 128) {\n X[(seed && seed.length || 0) & 127] = -1;\n }\n // Run the generator 512 times to further mix the state before using it.\n // Factoring this as a function slows the main generator, so it is just\n // unrolled here. The weyl generator is not advanced while warming up.\n i = 127;\n for (j = 4 * 128; j > 0; --j) {\n v = X[(i + 34) & 127];\n t = X[i = ((i + 1) & 127)];\n v ^= v << 13;\n t ^= t << 17;\n v ^= v >>> 15;\n t ^= t >>> 12;\n X[i] = v ^ t;\n }\n // Storing state as object members is faster than using closure variables.\n me.w = w;\n me.X = X;\n me.i = i;\n }\n\n init(me, seed);\n}\n\nfunction copy(f, t) {\n t.i = f.i;\n t.w = f.w;\n t.X = f.X.slice();\n return t;\n};\n\nfunction impl(seed, opts) {\n if (seed == null) seed = +(new Date);\n var xg = new XorGen(seed),\n state = opts && opts.state,\n prng = function() { return (xg.next() >>> 0) / 0x100000000; };\n prng.double = function() {\n do {\n var top = xg.next() >>> 11,\n bot = (xg.next() >>> 0) / 0x100000000,\n result = (top + bot) / (1 << 21);\n } while (result === 0);\n return result;\n };\n prng.int32 = xg.next;\n prng.quick = prng;\n if (state) {\n if (state.X) copy(state, xg);\n prng.state = function() { return copy(xg, {}); }\n }\n return prng;\n}\n\nif (module && module.exports) {\n module.exports = impl;\n} else if (define && define.amd) {\n define(function() { return impl; });\n} else {\n this.xor4096 = impl;\n}\n\n})(\n this, // window object or global\n (typeof module) == 'object' && module, // present in node.js\n (typeof define) == 'function' && define // present with an AMD loader\n);\n","// A Javascript implementaion of the \"Tyche-i\" prng algorithm by\n// Samuel Neves and Filipe Araujo.\n// See https://eden.dei.uc.pt/~sneves/pubs/2011-snfa2.pdf\n\n(function(global, module, define) {\n\nfunction XorGen(seed) {\n var me = this, strseed = '';\n\n // Set up generator function.\n me.next = function() {\n var b = me.b, c = me.c, d = me.d, a = me.a;\n b = (b << 25) ^ (b >>> 7) ^ c;\n c = (c - d) | 0;\n d = (d << 24) ^ (d >>> 8) ^ a;\n a = (a - b) | 0;\n me.b = b = (b << 20) ^ (b >>> 12) ^ c;\n me.c = c = (c - d) | 0;\n me.d = (d << 16) ^ (c >>> 16) ^ a;\n return me.a = (a - b) | 0;\n };\n\n /* The following is non-inverted tyche, which has better internal\n * bit diffusion, but which is about 25% slower than tyche-i in JS.\n me.next = function() {\n var a = me.a, b = me.b, c = me.c, d = me.d;\n a = (me.a + me.b | 0) >>> 0;\n d = me.d ^ a; d = d << 16 ^ d >>> 16;\n c = me.c + d | 0;\n b = me.b ^ c; b = b << 12 ^ d >>> 20;\n me.a = a = a + b | 0;\n d = d ^ a; me.d = d = d << 8 ^ d >>> 24;\n me.c = c = c + d | 0;\n b = b ^ c;\n return me.b = (b << 7 ^ b >>> 25);\n }\n */\n\n me.a = 0;\n me.b = 0;\n me.c = 2654435769 | 0;\n me.d = 1367130551;\n\n if (seed === Math.floor(seed)) {\n // Integer seed.\n me.a = (seed / 0x100000000) | 0;\n me.b = seed | 0;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (var k = 0; k < strseed.length + 20; k++) {\n me.b ^= strseed.charCodeAt(k) | 0;\n me.next();\n }\n}\n\nfunction copy(f, t) {\n t.a = f.a;\n t.b = f.b;\n t.c = f.c;\n t.d = f.d;\n return t;\n};\n\nfunction impl(seed, opts) {\n var xg = new XorGen(seed),\n state = opts && opts.state,\n prng = function() { return (xg.next() >>> 0) / 0x100000000; };\n prng.double = function() {\n do {\n var top = xg.next() >>> 11,\n bot = (xg.next() >>> 0) / 0x100000000,\n result = (top + bot) / (1 << 21);\n } while (result === 0);\n return result;\n };\n prng.int32 = xg.next;\n prng.quick = prng;\n if (state) {\n if (typeof(state) == 'object') copy(state, xg);\n prng.state = function() { return copy(xg, {}); }\n }\n return prng;\n}\n\nif (module && module.exports) {\n module.exports = impl;\n} else if (define && define.amd) {\n define(function() { return impl; });\n} else {\n this.tychei = impl;\n}\n\n})(\n this,\n (typeof module) == 'object' && module, // present in node.js\n (typeof define) == 'function' && define // present with an AMD loader\n);\n\n\n","/*\nCopyright 2019 David Bau.\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n*/\n\n(function (global, pool, math) {\n//\n// The following constants are related to IEEE 754 limits.\n//\n\nvar width = 256, // each RC4 output is 0 <= x < 256\n chunks = 6, // at least six RC4 outputs for each double\n digits = 52, // there are 52 significant digits in a double\n rngname = 'random', // rngname: name for Math.random and Math.seedrandom\n startdenom = math.pow(width, chunks),\n significance = math.pow(2, digits),\n overflow = significance * 2,\n mask = width - 1,\n nodecrypto; // node.js crypto module, initialized at the bottom.\n\n//\n// seedrandom()\n// This is the seedrandom function described above.\n//\nfunction seedrandom(seed, options, callback) {\n var key = [];\n options = (options == true) ? { entropy: true } : (options || {});\n\n // Flatten the seed string or build one from local entropy if needed.\n var shortseed = mixkey(flatten(\n options.entropy ? [seed, tostring(pool)] :\n (seed == null) ? autoseed() : seed, 3), key);\n\n // Use the seed to initialize an ARC4 generator.\n var arc4 = new ARC4(key);\n\n // This function returns a random double in [0, 1) that contains\n // randomness in every bit of the mantissa of the IEEE 754 value.\n var prng = function() {\n var n = arc4.g(chunks), // Start with a numerator n < 2 ^ 48\n d = startdenom, // and denominator d = 2 ^ 48.\n x = 0; // and no 'extra last byte'.\n while (n < significance) { // Fill up all significant digits by\n n = (n + x) * width; // shifting numerator and\n d *= width; // denominator and generating a\n x = arc4.g(1); // new least-significant-byte.\n }\n while (n >= overflow) { // To avoid rounding up, before adding\n n /= 2; // last byte, shift everything\n d /= 2; // right using integer math until\n x >>>= 1; // we have exactly the desired bits.\n }\n return (n + x) / d; // Form the number within [0, 1).\n };\n\n prng.int32 = function() { return arc4.g(4) | 0; }\n prng.quick = function() { return arc4.g(4) / 0x100000000; }\n prng.double = prng;\n\n // Mix the randomness into accumulated entropy.\n mixkey(tostring(arc4.S), pool);\n\n // Calling convention: what to return as a function of prng, seed, is_math.\n return (options.pass || callback ||\n function(prng, seed, is_math_call, state) {\n if (state) {\n // Load the arc4 state from the given state if it has an S array.\n if (state.S) { copy(state, arc4); }\n // Only provide the .state method if requested via options.state.\n prng.state = function() { return copy(arc4, {}); }\n }\n\n // If called as a method of Math (Math.seedrandom()), mutate\n // Math.random because that is how seedrandom.js has worked since v1.0.\n if (is_math_call) { math[rngname] = prng; return seed; }\n\n // Otherwise, it is a newer calling convention, so return the\n // prng directly.\n else return prng;\n })(\n prng,\n shortseed,\n 'global' in options ? options.global : (this == math),\n options.state);\n}\n\n//\n// ARC4\n//\n// An ARC4 implementation. The constructor takes a key in the form of\n// an array of at most (width) integers that should be 0 <= x < (width).\n//\n// The g(count) method returns a pseudorandom integer that concatenates\n// the next (count) outputs from ARC4. Its return value is a number x\n// that is in the range 0 <= x < (width ^ count).\n//\nfunction ARC4(key) {\n var t, keylen = key.length,\n me = this, i = 0, j = me.i = me.j = 0, s = me.S = [];\n\n // The empty key [] is treated as [0].\n if (!keylen) { key = [keylen++]; }\n\n // Set up S using the standard key scheduling algorithm.\n while (i < width) {\n s[i] = i++;\n }\n for (i = 0; i < width; i++) {\n s[i] = s[j = mask & (j + key[i % keylen] + (t = s[i]))];\n s[j] = t;\n }\n\n // The \"g\" method returns the next (count) outputs as one number.\n (me.g = function(count) {\n // Using instance members instead of closure state nearly doubles speed.\n var t, r = 0,\n i = me.i, j = me.j, s = me.S;\n while (count--) {\n t = s[i = mask & (i + 1)];\n r = r * width + s[mask & ((s[i] = s[j = mask & (j + t)]) + (s[j] = t))];\n }\n me.i = i; me.j = j;\n return r;\n // For robust unpredictability, the function call below automatically\n // discards an initial batch of values. This is called RC4-drop[256].\n // See http://google.com/search?q=rsa+fluhrer+response&btnI\n })(width);\n}\n\n//\n// copy()\n// Copies internal state of ARC4 to or from a plain object.\n//\nfunction copy(f, t) {\n t.i = f.i;\n t.j = f.j;\n t.S = f.S.slice();\n return t;\n};\n\n//\n// flatten()\n// Converts an object tree to nested arrays of strings.\n//\nfunction flatten(obj, depth) {\n var result = [], typ = (typeof obj), prop;\n if (depth && typ == 'object') {\n for (prop in obj) {\n try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {}\n }\n }\n return (result.length ? result : typ == 'string' ? obj : obj + '\\0');\n}\n\n//\n// mixkey()\n// Mixes a string seed into a key that is an array of integers, and\n// returns a shortened string seed that is equivalent to the result key.\n//\nfunction mixkey(seed, key) {\n var stringseed = seed + '', smear, j = 0;\n while (j < stringseed.length) {\n key[mask & j] =\n mask & ((smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++));\n }\n return tostring(key);\n}\n\n//\n// autoseed()\n// Returns an object for autoseeding, using window.crypto and Node crypto\n// module if available.\n//\nfunction autoseed() {\n try {\n var out;\n if (nodecrypto && (out = nodecrypto.randomBytes)) {\n // The use of 'out' to remember randomBytes makes tight minified code.\n out = out(width);\n } else {\n out = new Uint8Array(width);\n (global.crypto || global.msCrypto).getRandomValues(out);\n }\n return tostring(out);\n } catch (e) {\n var browser = global.navigator,\n plugins = browser && browser.plugins;\n return [+new Date, global, plugins, global.screen, tostring(pool)];\n }\n}\n\n//\n// tostring()\n// Converts an array of charcodes to a string\n//\nfunction tostring(a) {\n return String.fromCharCode.apply(0, a);\n}\n\n//\n// When seedrandom.js is loaded, we immediately mix a few bits\n// from the built-in RNG into the entropy pool. Because we do\n// not want to interfere with deterministic PRNG state later,\n// seedrandom will not call math.random on its own again after\n// initialization.\n//\nmixkey(math.random(), pool);\n\n//\n// Nodejs and AMD support: export the implementation as a module using\n// either convention.\n//\nif ((typeof module) == 'object' && module.exports) {\n module.exports = seedrandom;\n // When in node.js, try using crypto package for autoseeding.\n try {\n nodecrypto = require('crypto');\n } catch (ex) {}\n} else if ((typeof define) == 'function' && define.amd) {\n define(function() { return seedrandom; });\n} else {\n // When included as a plain script, set up Math.seedrandom global.\n math['seed' + rngname] = seedrandom;\n}\n\n\n// End anonymous scope, and pass initial values.\n})(\n // global: `self` in browsers (including strict mode and web workers),\n // otherwise `this` in Node and other environments\n (typeof self !== 'undefined') ? self : this,\n [], // pool: entropy pool starts empty\n Math // math: package containing random, pow, and seedrandom\n);\n","// A library of seedable RNGs implemented in Javascript.\n//\n// Usage:\n//\n// var seedrandom = require('seedrandom');\n// var random = seedrandom(1); // or any seed.\n// var x = random(); // 0 <= x < 1. Every bit is random.\n// var x = random.quick(); // 0 <= x < 1. 32 bits of randomness.\n\n// alea, a 53-bit multiply-with-carry generator by Johannes Baagøe.\n// Period: ~2^116\n// Reported to pass all BigCrush tests.\nvar alea = require('./lib/alea');\n\n// xor128, a pure xor-shift generator by George Marsaglia.\n// Period: 2^128-1.\n// Reported to fail: MatrixRank and LinearComp.\nvar xor128 = require('./lib/xor128');\n\n// xorwow, George Marsaglia's 160-bit xor-shift combined plus weyl.\n// Period: 2^192-2^32\n// Reported to fail: CollisionOver, SimpPoker, and LinearComp.\nvar xorwow = require('./lib/xorwow');\n\n// xorshift7, by François Panneton and Pierre L'ecuyer, takes\n// a different approach: it adds robustness by allowing more shifts\n// than Marsaglia's original three. It is a 7-shift generator\n// with 256 bits, that passes BigCrush with no systmatic failures.\n// Period 2^256-1.\n// No systematic BigCrush failures reported.\nvar xorshift7 = require('./lib/xorshift7');\n\n// xor4096, by Richard Brent, is a 4096-bit xor-shift with a\n// very long period that also adds a Weyl generator. It also passes\n// BigCrush with no systematic failures. Its long period may\n// be useful if you have many generators and need to avoid\n// collisions.\n// Period: 2^4128-2^32.\n// No systematic BigCrush failures reported.\nvar xor4096 = require('./lib/xor4096');\n\n// Tyche-i, by Samuel Neves and Filipe Araujo, is a bit-shifting random\n// number generator derived from ChaCha, a modern stream cipher.\n// https://eden.dei.uc.pt/~sneves/pubs/2011-snfa2.pdf\n// Period: ~2^127\n// No systematic BigCrush failures reported.\nvar tychei = require('./lib/tychei');\n\n// The original ARC4-based prng included in this library.\n// Period: ~2^1600\nvar sr = require('./seedrandom');\n\nsr.alea = alea;\nsr.xor128 = xor128;\nsr.xorwow = xorwow;\nsr.xorshift7 = xorshift7;\nsr.xor4096 = xor4096;\nsr.tychei = tychei;\n\nmodule.exports = sr;\n","/**\n * Throws an `Error` with the optional `message` if `condition` is falsy\n * @note Replacement for the external assert method to reduce bundle size\n */\nexport function assert(condition: any, message?: string): void {\n if (!condition) {\n throw new Error(message || 'loader assertion failed.');\n }\n}\n","// Purpose: include this in your module to avoid\n// dependencies on micro modules like 'global' and 'is-browser';\n\n/* eslint-disable no-restricted-globals */\nconst globals = {\n self: typeof self !== 'undefined' && self,\n window: typeof window !== 'undefined' && window,\n global: typeof global !== 'undefined' && global,\n document: typeof document !== 'undefined' && document\n};\n\ntype obj = {[key: string]: any};\nconst self_: obj = globals.self || globals.window || globals.global || {};\nconst window_: obj = globals.window || globals.self || globals.global || {};\nconst global_: obj = globals.global || globals.self || globals.window || {};\nconst document_: obj = globals.document || {};\n\nexport {self_ as self, window_ as window, global_ as global, document_ as document};\n\n/** true if running in a browser */\nexport const isBrowser: boolean =\n // @ts-ignore process does not exist on browser\n Boolean(typeof process !== 'object' || String(process) !== '[object process]' || process.browser);\n\n/** true if running in a worker thread */\nexport const isWorker: boolean = typeof importScripts === 'function';\n\n// Extract node major version\nconst matches =\n typeof process !== 'undefined' && process.version && /v([0-9]*)/.exec(process.version);\n/** Major Node version (as a number) */\nexport const nodeVersion: number = (matches && parseFloat(matches[1])) || 0;\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Log} from '@probe.gl/log';\n\n// Version constant cannot be imported, it needs to correspond to the build version of **this** module.\n// __VERSION__ is injected by babel-plugin-version-inline\n// @ts-ignore TS2304: Cannot find name '__VERSION__'.\nexport const VERSION = typeof __VERSION__ !== 'undefined' ? __VERSION__ : 'latest';\n\nconst version = VERSION[0] >= '0' && VERSION[0] <= '9' ? `v${VERSION}` : '';\n\n// Make sure we set the global variable\nfunction createLog() {\n const log = new Log({id: 'loaders.gl'});\n\n globalThis.loaders ||= {};\n globalThis.loaders.log = log;\n globalThis.loaders.version = version;\n\n globalThis.probe ||= {};\n globalThis.probe.loaders = log;\n\n return log;\n}\n\nexport const log = createLog();\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/* eslint-disable @typescript-eslint/unbound-method */\n\nimport type {Readable} from 'stream';\n\n/** Minimal shape for Node.js Buffer-like values */\ntype NodeBufferLike = {buffer: ArrayBufferLike; isBuffer: true};\n\n/** Minimal shape for Node.js writable streams */\ntype NodeWritableStream = {\n end: (...args: unknown[]) => unknown;\n write: (...args: unknown[]) => unknown;\n writable: boolean;\n};\n\n/** Minimal shape for WritableStream-like DOM implementations */\ntype WritableDOMStreamLike = WritableStream | {abort: () => unknown; getWriter: () => unknown};\n\n/** A DOM or Node readable stream */\nexport type ReadableStreamType = ReadableStream | Readable;\n\n/** Checks whether a value is a boolean */\nconst isBoolean = (value: unknown): value is boolean => typeof value === 'boolean';\n\n/** Checks whether a value is a function */\nconst isFunction = (value: unknown): value is (...args: unknown[]) => unknown =>\n typeof value === 'function';\n\n/** Checks whether a value is a non-null object */\nexport const isObject = (value: unknown): value is object =>\n value !== null && typeof value === 'object';\n\n/** Checks whether a value is a plain object (created by the Object constructor) */\nexport const isPureObject = (value: unknown): value is Record =>\n isObject(value) && value.constructor === {}.constructor;\n\n/** Checks whether a value is an ArrayBuffer */\nexport const isArrayBuffer = (value: unknown): value is ArrayBuffer =>\n typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer;\n\n/** Checks whether a value is an ArrayBuffer */\nexport const isSharedArrayBuffer = (value: unknown): value is SharedArrayBuffer =>\n typeof SharedArrayBuffer !== 'undefined' && value instanceof SharedArrayBuffer;\n\n/** Checks whether a value is ArrayBuffer-like */\nexport const isArrayBufferLike = (value: unknown): value is ArrayBufferLike =>\n isObject(value) &&\n typeof (value as ArrayBufferLike).byteLength === 'number' &&\n typeof (value as ArrayBufferLike).slice === 'function';\n\n/** Checks whether a value behaves like a promise */\nexport const isPromise = (value: unknown): value is Promise =>\n isObject(value) && 'then' in value && isFunction((value as {then: unknown}).then);\n\n/** Checks whether a value implements the iterable protocol */\nexport const isIterable = (value: unknown): value is Iterable =>\n Boolean(value) && isFunction((value as Iterable)[Symbol.iterator]);\n\n/** Checks whether a value implements the async iterable protocol */\nexport const isAsyncIterable = (value: unknown): value is AsyncIterable =>\n Boolean(value) && isFunction((value as AsyncIterable)[Symbol.asyncIterator]);\n\n/** Checks whether a value is an iterator (has a next function) */\nexport const isIterator = (value: unknown): value is Iterator =>\n Boolean(value) && isFunction((value as Iterator).next);\n\n/** Checks whether a value is a fetch Response or a duck-typed equivalent */\nexport const isResponse = (value: unknown): value is Response =>\n (typeof Response !== 'undefined' && value instanceof Response) ||\n (isObject(value) &&\n isFunction((value as {arrayBuffer?: unknown}).arrayBuffer) &&\n isFunction((value as {text?: unknown}).text) &&\n isFunction((value as {json?: unknown}).json));\n\n/** Checks whether a value is a File */\nexport const isFile = (value: unknown): value is File =>\n typeof File !== 'undefined' && value instanceof File;\n\n/** Checks whether a value is a Blob */\nexport const isBlob = (value: unknown): value is Blob =>\n typeof Blob !== 'undefined' && value instanceof Blob;\n\n/** Checks for Node.js Buffers without triggering bundlers to include the Buffer polyfill */\nexport const isBuffer = (value: unknown): value is NodeBufferLike =>\n Boolean(\n value &&\n typeof value === 'object' &&\n (value as Partial).isBuffer &&\n 'buffer' in (value as NodeBufferLike)\n );\n\n/** Checks whether a value looks like a DOM WritableStream */\nexport const isWritableDOMStream = (value: unknown): value is WritableDOMStreamLike =>\n isObject(value) &&\n isFunction((value as WritableDOMStreamLike).abort) &&\n isFunction((value as WritableDOMStreamLike).getWriter);\n\n/** Checks whether a value looks like a DOM ReadableStream */\nexport const isReadableDOMStream = (value: unknown): value is ReadableStream =>\n (typeof ReadableStream !== 'undefined' && value instanceof ReadableStream) ||\n (isObject(value) &&\n isFunction((value as ReadableStream).tee) &&\n isFunction((value as ReadableStream).cancel) &&\n isFunction((value as ReadableStream).getReader));\n// Not implemented in Firefox: && isFunction(x.pipeTo)\n\n/** Checks whether a value looks like a Node.js writable stream */\nexport const isWritableNodeStream = (value: unknown): value is NodeWritableStream =>\n isObject(value) &&\n isFunction((value as NodeWritableStream).end) &&\n isFunction((value as NodeWritableStream).write) &&\n isBoolean((value as NodeWritableStream).writable);\n\n/** Checks whether a value looks like a Node.js readable stream */\nexport const isReadableNodeStream = (value: unknown): value is Readable =>\n isObject(value) &&\n isFunction((value as Readable).read) &&\n isFunction((value as Readable).pipe) &&\n isBoolean((value as Readable).readable);\n\n/** Checks whether a value is any readable stream (DOM or Node.js) */\nexport const isReadableStream = (value: unknown): value is ReadableStreamType =>\n isReadableDOMStream(value) || isReadableNodeStream(value);\n\n/** Checks whether a value is any writable stream (DOM or Node.js) */\nexport const isWritableStream = (value: unknown): value is WritableStream | NodeWritableStream =>\n isWritableDOMStream(value) || isWritableNodeStream(value);\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport type RequiredOptions = Required<{[K in keyof T]: Required}>;\n\nexport function getRequiredOptions(options: T): RequiredOptions {\n return options as RequiredOptions;\n}\n\n/**\n *\n * @param baseOptions Can be undefined, in which case a fresh options object will be minted\n * @param newOptions\n * @returns\n */\nexport function mergeOptions>(\n baseOptions: OptionsT | undefined,\n newOptions: OptionsT\n): OptionsT {\n return mergeOptionsRecursively(baseOptions || {}, newOptions) as OptionsT;\n}\n\nfunction mergeOptionsRecursively(\n baseOptions: Record,\n newOptions: Record,\n level = 0\n): Record {\n // Sanity check (jest test runner overwrites the console object which can lead to infinite recursion)\n if (level > 3) {\n return newOptions;\n }\n\n const options = {...baseOptions};\n for (const [key, newValue] of Object.entries(newOptions)) {\n if (newValue && typeof newValue === 'object' && !Array.isArray(newValue)) {\n options[key] = mergeOptionsRecursively(\n (options[key] as Record) || {},\n newOptions[key] as Record,\n level + 1\n );\n // Object.assign(options[key] as object, newOptions[key]);\n } else {\n options[key] = newOptions[key];\n }\n }\n return options as Record;\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/**\n * NPM tag to use when loading modules from unpkg.com\n * 'beta' on beta branch, 'latest' on prod branch\n * @note Change between 'beta' and 'latest' depending on whether publishing alpha or prod releases\n * @todo - unpkg.com doesn't seem to have a `latest` specifier for alpha releases...\n */\nexport const NPM_TAG = 'latest';\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {NPM_TAG} from '../npm-tag';\n\n// Version constant cannot be imported, it needs to correspond to the build version of **this** module.\ndeclare let __VERSION__: string;\n\nlet warningIssued = false;\n\nfunction getVersion() {\n if (!globalThis._loadersgl_?.version) {\n globalThis._loadersgl_ = globalThis._loadersgl_ || {};\n // __VERSION__ is injected by babel-plugin-version-inline\n if (typeof __VERSION__ === 'undefined' && !warningIssued) {\n // eslint-disable-next-line\n console.warn(\n 'loaders.gl: The __VERSION__ variable is not injected using babel plugin. Latest unstable workers would be fetched from the CDN.'\n );\n globalThis._loadersgl_.version = NPM_TAG;\n warningIssued = true;\n } else {\n globalThis._loadersgl_.version = __VERSION__;\n }\n }\n\n return globalThis._loadersgl_.version;\n}\n\nexport const VERSION = getVersion();\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// Replacement for the external assert method to reduce bundle size\n// Note: We don't use the second \"message\" argument in calling code,\n// so no need to support it here\n\n/** Throws an `Error` with the optional `message` if `condition` is falsy */\nexport function assert(condition: any, message?: string): void {\n if (!condition) {\n throw new Error(message || 'loaders.gl assertion failed.');\n }\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// Purpose: include this in your module to avoids adding dependencies on\n// micro modules like 'global' and 'is-browser';\n\n/* eslint-disable no-restricted-globals */\nconst globals = {\n self: typeof self !== 'undefined' && self,\n window: typeof window !== 'undefined' && window,\n global: typeof global !== 'undefined' && global,\n document: typeof document !== 'undefined' && document\n};\n\nconst self_: {[key: string]: any} = globals.self || globals.window || globals.global || {};\nconst window_: {[key: string]: any} = globals.window || globals.self || globals.global || {};\nconst global_: {[key: string]: any} = globals.global || globals.self || globals.window || {};\nconst document_: {[key: string]: any} = globals.document || {};\n\nexport {self_ as self, window_ as window, global_ as global, document_ as document};\n\n/** true if running in the browser, false if running in Node.js */\nexport const isBrowser: boolean =\n // @ts-ignore process.browser\n typeof process !== 'object' || String(process) !== '[object process]' || process.browser;\n\n/** true if running on a worker thread */\nexport const isWorker: boolean = typeof importScripts === 'function';\n\n/** true if running on a mobile device */\nexport const isMobile: boolean =\n typeof window !== 'undefined' && typeof window.orientation !== 'undefined';\n\n// Extract node major version\nconst matches =\n typeof process !== 'undefined' && process.version && /v([0-9]*)/.exec(process.version);\n\n/** Version of Node.js if running under Node, otherwise 0 */\nexport const nodeVersion: number = (matches && parseFloat(matches[1])) || 0;\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {WorkerMessageType, WorkerMessagePayload} from '../../types';\nimport WorkerThread from './worker-thread';\nimport {assert} from '../env-utils/assert';\n\n/**\n * Represents one Job handled by a WorkerPool or WorkerFarm\n */\nexport default class WorkerJob {\n readonly name: string;\n readonly workerThread: WorkerThread;\n isRunning: boolean = true;\n /** Promise that resolves when Job is done */\n readonly result: Promise;\n\n private _resolve: (value: any) => void = () => {};\n private _reject: (reason?: any) => void = () => {};\n\n constructor(jobName: string, workerThread: WorkerThread) {\n this.name = jobName;\n this.workerThread = workerThread;\n this.result = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n\n /**\n * Send a message to the job's worker thread\n * @param data any data structure, ideally consisting mostly of transferrable objects\n */\n postMessage(type: WorkerMessageType, payload: WorkerMessagePayload): void {\n this.workerThread.postMessage({\n source: 'loaders.gl', // Lets worker ignore unrelated messages\n type,\n payload\n });\n }\n\n /**\n * Call to resolve the `result` Promise with the supplied value\n */\n done(value: any): void {\n assert(this.isRunning);\n this.isRunning = false;\n this._resolve(value);\n }\n\n /**\n * Call to reject the `result` Promise with the supplied error\n */\n error(error: Error): void {\n assert(this.isRunning);\n this.isRunning = false;\n this._reject(error);\n }\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/** Browser polyfill for Node.js built-in `worker_threads` module.\n * These fills are non-functional, and just intended to ensure that\n * `import 'worker_threads` doesn't break browser builds.\n * The replacement is done in package.json browser field\n */\nexport class NodeWorker {\n terminate() {}\n}\n\nexport type {NodeWorker as NodeWorkerType};\n\nexport const parentPort = null;\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {assert} from '../env-utils/assert';\n\nconst workerURLCache = new Map();\n\n/**\n * Creates a loadable URL from worker source or URL\n * that can be used to create `Worker` instances.\n * Due to CORS issues it may be necessary to wrap a URL in a small importScripts\n * @param props\n * @param props.source Worker source\n * @param props.url Worker URL\n * @returns loadable url\n */\nexport function getLoadableWorkerURL(props: {source?: string; url?: string}) {\n assert((props.source && !props.url) || (!props.source && props.url)); // Either source or url must be defined\n\n let workerURL = workerURLCache.get(props.source || props.url);\n if (!workerURL) {\n // Differentiate worker urls from worker source code\n if (props.url) {\n workerURL = getLoadableWorkerURLFromURL(props.url);\n workerURLCache.set(props.url, workerURL);\n }\n\n if (props.source) {\n workerURL = getLoadableWorkerURLFromSource(props.source);\n workerURLCache.set(props.source, workerURL);\n }\n }\n\n assert(workerURL);\n return workerURL;\n}\n\n/**\n * Build a loadable worker URL from worker URL\n * @param url\n * @returns loadable URL\n */\nfunction getLoadableWorkerURLFromURL(url: string): string {\n // A local script url, we can use it to initialize a Worker directly\n if (!url.startsWith('http')) {\n return url;\n }\n\n // A remote script, we need to use `importScripts` to load from different origin\n const workerSource = buildScriptSource(url);\n return getLoadableWorkerURLFromSource(workerSource);\n}\n\n/**\n * Build a loadable worker URL from worker source\n * @param workerSource\n * @returns loadable url\n */\nfunction getLoadableWorkerURLFromSource(workerSource: string): string {\n const blob = new Blob([workerSource], {type: 'application/javascript'});\n return URL.createObjectURL(blob);\n}\n\n/**\n * Per spec, worker cannot be initialized with a script from a different origin\n * However a local worker script can still import scripts from other origins,\n * so we simply build a wrapper script.\n *\n * @param workerUrl\n * @returns source\n */\nfunction buildScriptSource(workerUrl: string): string {\n return `\\\ntry {\n importScripts('${workerUrl}');\n} catch (error) {\n console.error(error);\n throw error;\n}`;\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// NOTE - there is a copy of this function is both in core and loader-utils\n// core does not need all the utils in loader-utils, just this one.\n\n/**\n * Returns an array of Transferrable objects that can be used with postMessage\n * https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage\n * @param object data to be sent via postMessage\n * @param recursive - not for application use\n * @param transfers - not for application use\n * @returns a transfer list that can be passed to postMessage\n */\nexport function getTransferList(\n object: any,\n recursive: boolean = true,\n transfers?: Set\n): Transferable[] {\n // Make sure that items in the transfer list is unique\n const transfersSet = transfers || new Set();\n\n if (!object) {\n // ignore\n } else if (isTransferable(object)) {\n transfersSet.add(object);\n } else if (isTransferable(object.buffer)) {\n // Typed array\n transfersSet.add(object.buffer);\n } else if (ArrayBuffer.isView(object)) {\n // object is a TypeArray viewing into a SharedArrayBuffer (not transferable)\n // Do not iterate through the content in this case\n } else if (recursive && typeof object === 'object') {\n for (const key in object) {\n // Avoid perf hit - only go one level deep\n getTransferList(object[key], recursive, transfersSet);\n }\n }\n\n // If transfers is defined, is internal recursive call\n // Otherwise it's called by the user\n return transfers === undefined ? Array.from(transfersSet) : [];\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/API/Transferable\nfunction isTransferable(object: unknown) {\n if (!object) {\n return false;\n }\n if (object instanceof ArrayBuffer) {\n return true;\n }\n if (typeof MessagePort !== 'undefined' && object instanceof MessagePort) {\n return true;\n }\n if (typeof ImageBitmap !== 'undefined' && object instanceof ImageBitmap) {\n return true;\n }\n // @ts-ignore\n if (typeof OffscreenCanvas !== 'undefined' && object instanceof OffscreenCanvas) {\n return true;\n }\n return false;\n}\n\n/**\n * Recursively drop non serializable values like functions and regexps.\n * @param object\n */\nexport function getTransferListForWriter(object: object | null): object {\n if (object === null) {\n return {};\n }\n const clone = Object.assign({}, object);\n\n Object.keys(clone).forEach((key) => {\n // Typed Arrays and Arrays are passed with no change\n if (\n typeof object[key] === 'object' &&\n !ArrayBuffer.isView(object[key]) &&\n !(object[key] instanceof Array)\n ) {\n clone[key] = getTransferListForWriter(object[key]);\n } else if (typeof clone[key] === 'function' || clone[key] instanceof RegExp) {\n clone[key] = {};\n } else {\n clone[key] = object[key];\n }\n });\n\n return clone;\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {NodeWorker, NodeWorkerType} from '../node/worker_threads';\nimport {isBrowser} from '../env-utils/globals';\nimport {assert} from '../env-utils/assert';\nimport {getLoadableWorkerURL} from '../worker-utils/get-loadable-worker-url';\nimport {getTransferList} from '../worker-utils/get-transfer-list';\n\nconst NOOP = () => {};\n\nexport type WorkerThreadProps = {\n name: string;\n source?: string;\n url?: string;\n};\n\n/**\n * Represents one worker thread\n */\nexport default class WorkerThread {\n readonly name: string;\n readonly source: string | undefined;\n readonly url: string | undefined;\n terminated: boolean = false;\n worker: Worker | NodeWorkerType;\n onMessage: (message: any) => void;\n onError: (error: Error) => void;\n\n private _loadableURL: string = '';\n\n /** Checks if workers are supported on this platform */\n static isSupported(): boolean {\n return (\n (typeof Worker !== 'undefined' && isBrowser) ||\n (typeof NodeWorker !== 'undefined' && !isBrowser)\n );\n }\n\n constructor(props: WorkerThreadProps) {\n const {name, source, url} = props;\n assert(source || url); // Either source or url must be defined\n this.name = name;\n this.source = source;\n this.url = url;\n this.onMessage = NOOP;\n this.onError = (error) => console.log(error); // eslint-disable-line\n\n this.worker = isBrowser ? this._createBrowserWorker() : this._createNodeWorker();\n }\n\n /**\n * Terminate this worker thread\n * @note Can free up significant memory\n */\n destroy(): void {\n this.onMessage = NOOP;\n this.onError = NOOP;\n this.worker.terminate(); // eslint-disable-line @typescript-eslint/no-floating-promises\n this.terminated = true;\n }\n\n get isRunning() {\n return Boolean(this.onMessage);\n }\n\n /**\n * Send a message to this worker thread\n * @param data any data structure, ideally consisting mostly of transferrable objects\n * @param transferList If not supplied, calculated automatically by traversing data\n */\n postMessage(data: any, transferList?: any[]): void {\n transferList = transferList || getTransferList(data);\n // @ts-ignore\n this.worker.postMessage(data, transferList);\n }\n\n // PRIVATE\n\n /**\n * Generate a standard Error from an ErrorEvent\n * @param event\n */\n _getErrorFromErrorEvent(event: ErrorEvent): Error {\n // Note Error object does not have the expected fields if loading failed completely\n // https://developer.mozilla.org/en-US/docs/Web/API/Worker#Event_handlers\n // https://developer.mozilla.org/en-US/docs/Web/API/ErrorEvent\n let message = 'Failed to load ';\n message += `worker ${this.name} from ${this.url}. `;\n if (event.message) {\n message += `${event.message} in `;\n }\n // const hasFilename = event.filename && !event.filename.startsWith('blob:');\n // message += hasFilename ? event.filename : this.source.slice(0, 100);\n if (event.lineno) {\n message += `:${event.lineno}:${event.colno}`;\n }\n return new Error(message);\n }\n\n /**\n * Creates a worker thread on the browser\n */\n _createBrowserWorker(): Worker {\n this._loadableURL = getLoadableWorkerURL({source: this.source, url: this.url});\n const worker = new Worker(this._loadableURL, {name: this.name});\n\n worker.onmessage = (event) => {\n if (!event.data) {\n this.onError(new Error('No data received'));\n } else {\n this.onMessage(event.data);\n }\n };\n // This callback represents an uncaught exception in the worker thread\n worker.onerror = (error: ErrorEvent): void => {\n this.onError(this._getErrorFromErrorEvent(error));\n this.terminated = true;\n };\n // TODO - not clear when this would be called, for now just log in case it happens\n worker.onmessageerror = (event) => console.error(event); // eslint-disable-line\n\n return worker;\n }\n\n /**\n * Creates a worker thread in node.js\n * @todo https://nodejs.org/api/async_hooks.html#async-resource-worker-pool\n */\n _createNodeWorker(): NodeWorkerType {\n let worker: NodeWorkerType;\n if (this.url) {\n // Make sure relative URLs start with './'\n const absolute = this.url.includes(':/') || this.url.startsWith('/');\n const url = absolute ? this.url : `./${this.url}`;\n const type = this.url.endsWith('.ts') || this.url.endsWith('.mjs') ? 'module' : 'commonjs';\n // console.log('Starting work from', url);\n // @ts-expect-error type is not known\n worker = new NodeWorker(url, {eval: false, type});\n } else if (this.source) {\n worker = new NodeWorker(this.source, {eval: true});\n } else {\n throw new Error('no worker');\n }\n worker.on('message', (data) => {\n // console.error('message', data);\n this.onMessage(data);\n });\n worker.on('error', (error) => {\n this.onError(error as Error);\n });\n worker.on('exit', (code) => {\n // console.error('exit', code);\n });\n return worker;\n }\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {WorkerMessageType, WorkerMessagePayload} from '../../types';\nimport {isMobile, isBrowser} from '../env-utils/globals';\nimport WorkerThread from './worker-thread';\nimport WorkerJob from './worker-job';\n\n/** WorkerPool onDebug Callback Parameters */\ntype OnDebugParameters = {\n message: string;\n worker: string;\n name: string;\n job: string;\n backlog: number;\n workerThread: WorkerThread;\n};\n\n/** WorkerPool Properties */\nexport type WorkerPoolProps = {\n name?: string;\n source?: string; // | Function;\n url?: string;\n maxConcurrency?: number;\n maxMobileConcurrency?: number;\n onDebug?: (options: OnDebugParameters) => any;\n reuseWorkers?: boolean;\n};\n\n/** Private helper types */\ntype OnMessage = (job: WorkerJob, type: WorkerMessageType, payload: WorkerMessagePayload) => void;\ntype OnError = (job: WorkerJob, error: Error) => void;\n\ntype QueuedJob = {\n name: string;\n onMessage: OnMessage;\n onError: OnError;\n onStart: (value: any) => void; // Resolve job start promise\n};\n\n/**\n * Process multiple data messages with small pool of identical workers\n */\nexport default class WorkerPool {\n name: string = 'unnamed';\n source?: string; // | Function;\n url?: string;\n maxConcurrency: number = 1;\n maxMobileConcurrency: number = 1;\n onDebug: (options: OnDebugParameters) => any = () => {};\n reuseWorkers: boolean = true;\n\n private props: WorkerPoolProps = {};\n private jobQueue: QueuedJob[] = [];\n private idleQueue: WorkerThread[] = [];\n private count = 0;\n private isDestroyed = false;\n\n /** Checks if workers are supported on this platform */\n static isSupported(): boolean {\n return WorkerThread.isSupported();\n }\n\n /**\n * @param processor - worker function\n * @param maxConcurrency - max count of workers\n */\n constructor(props: WorkerPoolProps) {\n this.source = props.source;\n this.url = props.url;\n this.setProps(props);\n }\n\n /**\n * Terminates all workers in the pool\n * @note Can free up significant memory\n */\n destroy(): void {\n // Destroy idle workers, active Workers will be destroyed on completion\n this.idleQueue.forEach((worker) => worker.destroy());\n this.isDestroyed = true;\n }\n\n setProps(props: WorkerPoolProps) {\n this.props = {...this.props, ...props};\n\n if (props.name !== undefined) {\n this.name = props.name;\n }\n if (props.maxConcurrency !== undefined) {\n this.maxConcurrency = props.maxConcurrency;\n }\n if (props.maxMobileConcurrency !== undefined) {\n this.maxMobileConcurrency = props.maxMobileConcurrency;\n }\n if (props.reuseWorkers !== undefined) {\n this.reuseWorkers = props.reuseWorkers;\n }\n if (props.onDebug !== undefined) {\n this.onDebug = props.onDebug;\n }\n }\n\n async startJob(\n name: string,\n onMessage: OnMessage = (job, type, data) => job.done(data),\n onError: OnError = (job, error) => job.error(error)\n ): Promise {\n // Promise resolves when thread starts working on this job\n const startPromise = new Promise((onStart) => {\n // Promise resolves when thread completes or fails working on this job\n this.jobQueue.push({name, onMessage, onError, onStart});\n return this;\n });\n this._startQueuedJob(); // eslint-disable-line @typescript-eslint/no-floating-promises\n return await startPromise;\n }\n\n // PRIVATE\n\n /**\n * Starts first queued job if worker is available or can be created\n * Called when job is started and whenever a worker returns to the idleQueue\n */\n async _startQueuedJob(): Promise {\n if (!this.jobQueue.length) {\n return;\n }\n\n const workerThread = this._getAvailableWorker();\n if (!workerThread) {\n return;\n }\n\n // We have a worker, dequeue and start the job\n const queuedJob = this.jobQueue.shift();\n if (queuedJob) {\n // Emit a debug event\n // @ts-ignore\n this.onDebug({\n message: 'Starting job',\n name: queuedJob.name,\n workerThread,\n backlog: this.jobQueue.length\n });\n\n // Create a worker job to let the app access thread and manage job completion\n const job = new WorkerJob(queuedJob.name, workerThread);\n\n // Set the worker thread's message handlers\n workerThread.onMessage = (data) => queuedJob.onMessage(job, data.type, data.payload);\n workerThread.onError = (error) => queuedJob.onError(job, error);\n\n // Resolve the start promise so that the app can start sending messages to worker\n queuedJob.onStart(job);\n\n // Wait for the app to signal that the job is complete, then return worker to queue\n try {\n await job.result;\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error(`Worker exception: ${error}`);\n } finally {\n this.returnWorkerToQueue(workerThread);\n }\n }\n }\n\n /**\n * Returns a worker to the idle queue\n * Destroys the worker if\n * - pool is destroyed\n * - if this pool doesn't reuse workers\n * - if maxConcurrency has been lowered\n * @param worker\n */\n returnWorkerToQueue(worker: WorkerThread) {\n const shouldDestroyWorker =\n // Workers on Node.js prevent the process from exiting.\n // Until we figure out how to close them before exit, we always destroy them\n !isBrowser ||\n // If the pool is destroyed, there is no reason to keep the worker around\n this.isDestroyed ||\n // If the app has disabled worker reuse, any completed workers should be destroyed\n !this.reuseWorkers ||\n // If concurrency has been lowered, this worker might be surplus to requirements\n this.count > this._getMaxConcurrency();\n\n if (shouldDestroyWorker) {\n worker.destroy();\n this.count--;\n } else {\n this.idleQueue.push(worker);\n }\n\n if (!this.isDestroyed) {\n this._startQueuedJob(); // eslint-disable-line @typescript-eslint/no-floating-promises\n }\n }\n\n /**\n * Returns idle worker or creates new worker if maxConcurrency has not been reached\n */\n _getAvailableWorker(): WorkerThread | null {\n // If a worker has completed and returned to the queue, it can be used\n if (this.idleQueue.length > 0) {\n return this.idleQueue.shift() || null;\n }\n\n // Create fresh worker if we haven't yet created the max amount of worker threads for this worker source\n if (this.count < this._getMaxConcurrency()) {\n this.count++;\n const name = `${this.name.toLowerCase()} (#${this.count} of ${this.maxConcurrency})`;\n return new WorkerThread({name, source: this.source, url: this.url});\n }\n\n // No worker available, have to wait\n return null;\n }\n\n _getMaxConcurrency() {\n return isMobile ? this.maxMobileConcurrency : this.maxConcurrency;\n }\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport WorkerPool from './worker-pool';\nimport WorkerThread from './worker-thread';\n\n/**\n * @param maxConcurrency - max count of workers\n * @param maxMobileConcurrency - max count of workers on mobile\n * @param maxConcurrency - max count of workers\n * @param reuseWorkers - if false, destroys workers when task is completed\n * @param onDebug - callback intended to allow application to log worker pool activity\n */\nexport type WorkerFarmProps = {\n maxConcurrency?: number;\n maxMobileConcurrency?: number;\n reuseWorkers?: boolean;\n onDebug?: () => void;\n};\n\nconst DEFAULT_PROPS: Required = {\n maxConcurrency: 3,\n maxMobileConcurrency: 1,\n reuseWorkers: true,\n onDebug: () => {}\n};\n\n/**\n * Process multiple jobs with a \"farm\" of different workers in worker pools.\n */\nexport default class WorkerFarm {\n private props: WorkerFarmProps;\n private workerPools = new Map();\n // singleton\n private static _workerFarm?: WorkerFarm;\n\n /** Checks if workers are supported on this platform */\n static isSupported(): boolean {\n return WorkerThread.isSupported();\n }\n\n /** Get the singleton instance of the global worker farm */\n static getWorkerFarm(props: WorkerFarmProps = {}): WorkerFarm {\n WorkerFarm._workerFarm = WorkerFarm._workerFarm || new WorkerFarm({});\n WorkerFarm._workerFarm.setProps(props);\n return WorkerFarm._workerFarm;\n }\n\n /** get global instance with WorkerFarm.getWorkerFarm() */\n private constructor(props: WorkerFarmProps) {\n this.props = {...DEFAULT_PROPS};\n this.setProps(props);\n /** @type Map} */\n this.workerPools = new Map();\n }\n\n /**\n * Terminate all workers in the farm\n * @note Can free up significant memory\n */\n destroy(): void {\n for (const workerPool of this.workerPools.values()) {\n workerPool.destroy();\n }\n this.workerPools = new Map();\n }\n\n /**\n * Set props used when initializing worker pools\n * @param props\n */\n setProps(props: WorkerFarmProps): void {\n this.props = {...this.props, ...props};\n // Update worker pool props\n for (const workerPool of this.workerPools.values()) {\n workerPool.setProps(this._getWorkerPoolProps());\n }\n }\n\n /**\n * Returns a worker pool for the specified worker\n * @param options - only used first time for a specific worker name\n * @param options.name - the name of the worker - used to identify worker pool\n * @param options.url -\n * @param options.source -\n * @example\n * const job = WorkerFarm.getWorkerFarm().getWorkerPool({name, url}).startJob(...);\n */\n getWorkerPool(options: {name: string; source?: string; url?: string}): WorkerPool {\n const {name, source, url} = options;\n let workerPool = this.workerPools.get(name);\n if (!workerPool) {\n workerPool = new WorkerPool({\n name,\n source,\n url\n });\n workerPool.setProps(this._getWorkerPoolProps());\n this.workerPools.set(name, workerPool);\n }\n return workerPool;\n }\n\n _getWorkerPoolProps() {\n return {\n maxConcurrency: this.props.maxConcurrency,\n maxMobileConcurrency: this.props.maxMobileConcurrency,\n reuseWorkers: this.props.reuseWorkers,\n onDebug: this.props.onDebug\n };\n }\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {WorkerObject, WorkerOptions} from '../../types';\nimport {assert} from '../env-utils/assert';\nimport {isBrowser} from '../env-utils/globals';\nimport {VERSION} from '../env-utils/version';\nimport {NPM_TAG} from '../npm-tag';\n\n/**\n * Gets worker object's name (for debugging in Chrome thread inspector window)\n */\nexport function getWorkerName(worker: WorkerObject): string {\n const warning = worker.version !== VERSION ? ` (worker-utils@${VERSION})` : '';\n return `${worker.name}@${worker.version}${warning}`;\n}\n\n/**\n * Generate a worker URL based on worker object and options\n * @returns A URL to one of the following:\n * - a published worker on unpkg CDN\n * - a local test worker\n * - a URL provided by the user in options\n */\nexport function getWorkerURL(worker: WorkerObject, options: WorkerOptions = {}): string {\n const workerOptions = options[worker.id] || {};\n\n const workerFile = isBrowser ? `${worker.id}-worker.js` : `${worker.id}-worker-node.js`;\n\n let url = workerOptions.workerUrl;\n\n // HACK: Allow for non-nested workerUrl for the CompressionWorker.\n // For the compression worker, workerOptions is currently not nested correctly. For most loaders,\n // you'd have options within an object, i.e. `{mvt: {coordinates: ...}}` but the CompressionWorker\n // puts options at the top level, not within a `compression` key (its `id`). For this reason, the\n // above `workerOptions` will always be a string (i.e. `'gzip'`) for the CompressionWorker. To not\n // break backwards compatibility, we allow the CompressionWorker to have options at the top level.\n if (!url && worker.id === 'compression') {\n url = options.workerUrl;\n }\n\n // If URL is test, generate local loaders.gl url\n // @ts-ignore _workerType\n const workerType = (options as any)._workerType || (options as any)?.core?._workerType;\n if (workerType === 'test') {\n if (isBrowser) {\n url = `modules/${worker.module}/dist/${workerFile}`;\n } else {\n // In the test environment the ts-node loader requires TypeScript code\n url = `modules/${worker.module}/src/workers/${worker.id}-worker-node.ts`;\n }\n }\n\n // If url override is not provided, generate a URL to published version on npm CDN unpkg.com\n if (!url) {\n // GENERATE\n let version = worker.version;\n // On master we need to load npm alpha releases published with the `beta` tag\n if (version === 'latest') {\n // throw new Error('latest worker version specified');\n version = NPM_TAG;\n }\n const versionTag = version ? `@${version}` : '';\n url = `https://unpkg.com/@loaders.gl/${worker.module}${versionTag}/dist/${workerFile}`;\n }\n\n assert(url);\n\n // Allow user to override location\n return url;\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {WorkerObject} from '../../types';\nimport {assert} from '../env-utils/assert';\nimport {VERSION} from '../env-utils/version';\n\n/**\n * Check if worker is compatible with this library version\n * @param worker\n * @param libVersion\n * @returns `true` if the two versions are compatible\n */\nexport function validateWorkerVersion(\n worker: WorkerObject,\n coreVersion: string = VERSION\n): boolean {\n assert(worker, 'no worker provided');\n\n const workerVersion = worker.version;\n if (!coreVersion || !workerVersion) {\n return false;\n }\n\n // TODO enable when fix the __version__ injection\n // const coreVersions = parseVersion(coreVersion);\n // const workerVersions = parseVersion(workerVersion);\n // assert(\n // coreVersion.major === workerVersion.major && coreVersion.minor <= workerVersion.minor,\n // `worker: ${worker.name} is not compatible. ${coreVersion.major}.${\n // coreVersion.minor\n // }+ is required.`\n // );\n\n return true;\n}\n\n// @ts-ignore\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nfunction parseVersion(version) {\n const parts = version.split('.').map(Number);\n return {major: parts[0], minor: parts[1]};\n}\n","import {\n WorkerJob,\n WorkerMessageType,\n WorkerMessagePayload,\n isBrowser,\n WorkerFarm,\n getWorkerURL\n} from '@loaders.gl/worker-utils';\nimport type {Loader, LoaderOptions, LoaderContext} from '../../loader-types';\n\n/**\n * Determines if a loader can parse with worker\n * @param loader\n * @param options\n */\nexport function canParseWithWorker(loader: Loader, options?: LoaderOptions) {\n if (!WorkerFarm.isSupported()) {\n return false;\n }\n\n // Node workers are still experimental\n const nodeWorkers = options?._nodeWorkers ?? options?.core?._nodeWorkers;\n if (!isBrowser && !nodeWorkers) {\n return false;\n }\n\n const useWorkers = options?.worker ?? options?.core?.worker;\n return Boolean(loader.worker && useWorkers);\n}\n\n/**\n * this function expects that the worker function sends certain messages,\n * this can be automated if the worker is wrapper by a call to createLoaderWorker in @loaders.gl/loader-utils.\n */\nexport async function parseWithWorker(\n loader: Loader,\n data: any,\n options?: LoaderOptions,\n context?: LoaderContext,\n parseOnMainThread?: (arrayBuffer: ArrayBuffer, options: {[key: string]: any}) => Promise\n) {\n const name = loader.id; // TODO\n const url = getWorkerURL(loader, options);\n\n const workerFarm = WorkerFarm.getWorkerFarm(options?.core);\n const workerPool = workerFarm.getWorkerPool({name, url});\n\n // options.log object contains functions which cannot be transferred\n // context.fetch & context.parse functions cannot be transferred\n // TODO - decide how to handle logging on workers\n options = JSON.parse(JSON.stringify(options));\n context = JSON.parse(JSON.stringify(context || {}));\n\n const job = await workerPool.startJob(\n 'process-on-worker',\n // @ts-expect-error\n onMessage.bind(null, parseOnMainThread) // eslint-disable-line @typescript-eslint/no-misused-promises\n );\n\n job.postMessage('process', {\n // @ts-ignore\n input: data,\n options,\n context\n });\n\n const result = await job.result;\n // TODO - what is going on here?\n return await result.result;\n}\n\n/**\n * Handle worker's responses to the main thread\n * @param job\n * @param type\n * @param payload\n */\nasync function onMessage(\n parseOnMainThread: (arrayBuffer: ArrayBuffer, options?: {[key: string]: any}) => Promise,\n job: WorkerJob,\n type: WorkerMessageType,\n payload: WorkerMessagePayload\n) {\n switch (type) {\n case 'done':\n job.done(payload);\n break;\n\n case 'error':\n job.error(new Error(payload.error));\n break;\n\n case 'process':\n // Worker is asking for main thread to parseO\n const {id, input, options} = payload;\n try {\n const result = await parseOnMainThread(input, options);\n job.postMessage('done', {id, result});\n } catch (error) {\n const message = error instanceof Error ? error.message : 'unknown error';\n job.postMessage('error', {id, error: message});\n }\n break;\n\n default:\n // eslint-disable-next-line\n console.warn(`parse-with-worker unknown message ${type}`);\n }\n}\n","import {TypedArray} from '../../types';\n\n/**\n * compare two binary arrays for equality\n * @param a\n * @param b\n * @param byteLength\n */\nexport function compareArrayBuffers(\n arrayBuffer1: ArrayBufferLike,\n arrayBuffer2: ArrayBufferLike,\n byteLength?: number\n): boolean {\n byteLength = byteLength || arrayBuffer1.byteLength;\n if (arrayBuffer1.byteLength < byteLength || arrayBuffer2.byteLength < byteLength) {\n return false;\n }\n const array1 = new Uint8Array(arrayBuffer1);\n const array2 = new Uint8Array(arrayBuffer2);\n for (let i = 0; i < array1.length; ++i) {\n if (array1[i] !== array2[i]) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Concatenate a sequence of ArrayBuffers from arguments\n * @return A concatenated ArrayBuffer\n */\nexport function concatenateArrayBuffers(...sources: (ArrayBuffer | Uint8Array)[]): ArrayBuffer {\n return concatenateArrayBuffersFromArray(sources);\n}\n\n/**\n * Concatenate a sequence of ArrayBuffers from array\n * @return A concatenated ArrayBuffer\n */\nexport function concatenateArrayBuffersFromArray(\n sources: (ArrayBuffer | Uint8Array)[]\n): ArrayBuffer {\n // Make sure all inputs are wrapped in typed arrays\n const sourceArrays = sources.map((source2) =>\n source2 instanceof ArrayBuffer ? new Uint8Array(source2) : source2\n );\n\n // Get length of all inputs\n const byteLength = sourceArrays.reduce((length, typedArray) => length + typedArray.byteLength, 0);\n\n // Allocate array with space for all inputs\n const result = new Uint8Array(byteLength);\n\n // Copy the subarrays\n let offset = 0;\n for (const sourceArray of sourceArrays) {\n result.set(sourceArray, offset);\n offset += sourceArray.byteLength;\n }\n\n // We work with ArrayBuffers, discard the typed array wrapper\n return result.buffer;\n}\n\n/**\n * Concatenate arbitrary count of typed arrays\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays\n * @param - list of arrays. All arrays should be the same type\n * @return A concatenated TypedArray\n */\nexport function concatenateTypedArrays(...typedArrays: T[]): T {\n // @ts-ignore\n const arrays = typedArrays as TypedArray[];\n // @ts-ignore\n const TypedArrayConstructor = (arrays && arrays.length > 1 && arrays[0].constructor) || null;\n if (!TypedArrayConstructor) {\n throw new Error(\n '\"concatenateTypedArrays\" - incorrect quantity of arguments or arguments have incompatible data types'\n );\n }\n\n const sumLength = arrays.reduce((acc, value) => acc + value.length, 0);\n // @ts-ignore typescript does not like dynamic constructors\n const result = new TypedArrayConstructor(sumLength);\n let offset = 0;\n for (const array of arrays) {\n result.set(array, offset);\n offset += array.length;\n }\n return result;\n}\n\n/**\n * Copy a view of an ArrayBuffer into new ArrayBuffer with byteOffset = 0\n * @param arrayBuffer\n * @param byteOffset\n * @param byteLength\n */\nexport function sliceArrayBuffer(\n arrayBuffer: ArrayBufferLike,\n byteOffset: number,\n byteLength?: number\n): ArrayBuffer {\n const subArray =\n byteLength !== undefined\n ? new Uint8Array(arrayBuffer).subarray(byteOffset, byteOffset + byteLength)\n : new Uint8Array(arrayBuffer).subarray(byteOffset);\n const arrayCopy = new Uint8Array(subArray);\n return arrayCopy.buffer;\n}\n","import {concatenateArrayBuffers} from '../binary-utils/array-buffer-utils';\n\n// GENERAL UTILITIES\n\n/**\n * Iterates over an {@link AsyncIterable} or {@link Iterable}, invoking `visitor` for each yielded\n * value without rewinding the iterator when exiting early. This enables the caller to continue\n * iterating in another loop after `visitor` signals cancellation.\n */\nexport async function forEach(\n iterable: AsyncIterable | Iterable | AsyncIterator,\n visitor: (value: TValue) => any\n) {\n const iterator = toAsyncIterator(iterable);\n // eslint-disable-next-line\n while (true) {\n const {done, value} = await iterator.next();\n if (done) {\n if (iterator.return) {\n iterator.return();\n }\n return;\n }\n const cancel = visitor(value);\n if (cancel) {\n return;\n }\n }\n}\n\n/**\n * Concatenates all binary chunks yielded by an async or sync iterator.\n * Supports `ArrayBuffer`, typed array views, and `ArrayBufferLike` sources (e.g. `SharedArrayBuffer`).\n * This allows atomic parsers to operate on iterator inputs by materializing them into a single buffer.\n */\nexport async function concatenateArrayBuffersAsync(\n asyncIterator:\n | AsyncIterable\n | Iterable\n): Promise {\n const arrayBuffers: ArrayBuffer[] = [];\n for await (const chunk of asyncIterator) {\n arrayBuffers.push(copyToArrayBuffer(chunk));\n }\n return concatenateArrayBuffers(...arrayBuffers);\n}\n\nexport async function concatenateStringsAsync(\n asyncIterator: AsyncIterable | Iterable\n): Promise {\n const strings: string[] = [];\n for await (const chunk of asyncIterator) {\n strings.push(chunk);\n }\n return strings.join('');\n}\n\n/**\n * Normalizes binary chunk iterators to yield `ArrayBuffer` instances.\n * Accepts `ArrayBuffer`, `ArrayBufferView`, and `ArrayBufferLike` sources\n * (e.g. `SharedArrayBuffer`) and returns a copied `ArrayBuffer` for each chunk.\n */\nexport async function* toArrayBufferIterator(\n asyncIterator:\n | AsyncIterable\n | Iterable\n): AsyncIterable {\n for await (const chunk of asyncIterator) {\n yield copyToArrayBuffer(chunk);\n }\n}\n\nfunction copyToArrayBuffer(chunk: ArrayBufferLike | ArrayBufferView | ArrayBuffer): ArrayBuffer {\n if (chunk instanceof ArrayBuffer) {\n return chunk;\n }\n\n if (ArrayBuffer.isView(chunk)) {\n const {buffer, byteOffset, byteLength} = chunk;\n return copyFromBuffer(buffer, byteOffset, byteLength);\n }\n\n return copyFromBuffer(chunk as ArrayBufferLike);\n}\n\nfunction copyFromBuffer(\n buffer: ArrayBufferLike,\n byteOffset = 0,\n byteLength = buffer.byteLength - byteOffset\n): ArrayBuffer {\n const view = new Uint8Array(buffer, byteOffset, byteLength);\n const copy = new Uint8Array(view.length);\n copy.set(view);\n return copy.buffer;\n}\n\nfunction toAsyncIterator(\n iterable: AsyncIterable | Iterable | AsyncIterator\n): AsyncIterator {\n if (typeof iterable[Symbol.asyncIterator] === 'function') {\n return iterable[Symbol.asyncIterator]();\n }\n\n if (typeof iterable[Symbol.iterator] === 'function') {\n const iterator = iterable[Symbol.iterator]();\n return iteratorToAsyncIterator(iterator);\n }\n\n return iterable as AsyncIterator;\n}\n\nfunction iteratorToAsyncIterator(iterator: Iterator): AsyncIterator {\n return {\n next(value?: any) {\n return Promise.resolve(iterator.next(value));\n },\n\n return(value?: any) {\n if (typeof iterator.return === 'function') {\n return Promise.resolve(iterator.return(value));\n }\n return Promise.resolve({done: true, value});\n },\n\n throw(error?: any) {\n if (typeof iterator.throw === 'function') {\n return Promise.resolve(iterator.throw(error));\n }\n return Promise.reject(error);\n }\n };\n}\n","// Simple file alias mechanisms for tests.\n\nlet pathPrefix = '';\nconst fileAliases: {[aliasPath: string]: string} = {};\n\n/*\n * Set a relative path prefix\n */\nexport function setPathPrefix(prefix: string): void {\n pathPrefix = prefix;\n}\n\n/*\n * Get the relative path prefix\n */\nexport function getPathPrefix(): string {\n return pathPrefix;\n}\n\n/**\n *\n * @param aliases\n *\n * Note: addAliases are an experimental export, they are only for testing of loaders.gl loaders\n * not intended as a generic aliasing mechanism\n */\nexport function addAliases(aliases: {[aliasPath: string]: string}): void {\n Object.assign(fileAliases, aliases);\n}\n\n/**\n * Resolves aliases and adds path-prefix to paths\n */\nexport function resolvePath(filename: string): string {\n for (const alias in fileAliases) {\n if (filename.startsWith(alias)) {\n const replacement = fileAliases[alias];\n filename = filename.replace(alias, replacement);\n }\n }\n if (!filename.startsWith('http://') && !filename.startsWith('https://')) {\n filename = `${pathPrefix}${filename}`;\n }\n return filename;\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {isSharedArrayBuffer} from '../javascript-utils/is-type';\nimport * as node from '../node/buffer';\n\n/**\n * Check for Node.js `Buffer` (without triggering bundler to include Buffer polyfill on browser)\n */\nexport function isBuffer(value: any): value is Buffer {\n return value && typeof value === 'object' && value.isBuffer;\n}\n\n/**\n * Converts to Node.js `Buffer` (without triggering bundler to include Buffer polyfill on browser)\n * @todo better data type\n */\nexport function toBuffer(data: unknown): Buffer {\n return node.toBuffer ? node.toBuffer(data as any) : (data as Buffer);\n}\n\n/**\n * Convert an object to an array buffer. Handles SharedArrayBuffers.\n */\nexport function toArrayBuffer(\n data: Buffer | ArrayBufferLike | ArrayBufferView | string | Blob\n): ArrayBuffer {\n // Note: Should be called first, Buffers can trigger other detections below\n if (isBuffer(data)) {\n return node.toArrayBuffer(data);\n }\n\n if (data instanceof ArrayBuffer) {\n return data;\n }\n\n if (isSharedArrayBuffer(data)) {\n return copyToArrayBuffer(data);\n }\n\n // Node Buffers look like Uint8Arrays (Check isBuffer first)\n if (ArrayBuffer.isView(data)) {\n // TODO - ArrayBufferLike type mess\n const buffer = data.buffer as ArrayBuffer;\n if (data.byteOffset === 0 && data.byteLength === data.buffer.byteLength) {\n return buffer;\n }\n return buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);\n }\n\n if (typeof data === 'string') {\n const text = data;\n const uint8Array = new TextEncoder().encode(text);\n return uint8Array.buffer;\n }\n\n // HACK to support Blob polyfill\n if (data && typeof data === 'object' && (data as any)._toArrayBuffer) {\n return (data as any)._toArrayBuffer();\n }\n\n throw new Error('toArrayBuffer');\n}\n\n/** Ensure that SharedArrayBuffers are copied into ArrayBuffers */\nexport function ensureArrayBuffer(bufferSource: ArrayBufferLike | ArrayBufferView): ArrayBuffer {\n if (bufferSource instanceof ArrayBuffer) {\n return bufferSource;\n }\n\n if (isSharedArrayBuffer(bufferSource)) {\n return copyToArrayBuffer(bufferSource);\n }\n\n const {buffer, byteOffset, byteLength} = bufferSource;\n if (buffer instanceof ArrayBuffer && byteOffset === 0 && byteLength === buffer.byteLength) {\n return buffer;\n }\n return copyToArrayBuffer(buffer, byteOffset, byteLength);\n}\n\n/** Copies an ArrayBuffer or a section of an ArrayBuffer to a new ArrayBuffer, handles SharedArrayBuffers */\nexport function copyToArrayBuffer(\n buffer: ArrayBufferLike,\n byteOffset = 0,\n byteLength = buffer.byteLength - byteOffset\n): ArrayBuffer {\n const view = new Uint8Array(buffer, byteOffset, byteLength);\n const copy = new Uint8Array(view.length);\n copy.set(view);\n return copy.buffer;\n}\n\n/** Convert an object to an ArrayBufferView, handles SharedArrayBuffers */\nexport function toArrayBufferView(\n data: ArrayBufferLike | ArrayBufferView\n): ArrayBuffer | ArrayBufferView {\n if (ArrayBuffer.isView(data)) {\n return data;\n }\n\n // Create a view to support ArrayBufferLike sources such as SharedArrayBuffer\n return new Uint8Array(data);\n}\n","// Beginning of a minimal implementation of the Node.js path API, that doesn't pull in big polyfills.\n\nimport {getCWD} from './get-cwd';\n\n/**\n * Replacement for Node.js path.filename\n * @param url\n */\nexport function filename(url: string): string {\n const slashIndex = url ? url.lastIndexOf('/') : -1;\n return slashIndex >= 0 ? url.substr(slashIndex + 1) : url;\n}\n\n/**\n * Replacement for Node.js path.dirname\n * @param url\n */\nexport function dirname(url: string): string {\n const slashIndex = url ? url.lastIndexOf('/') : -1;\n return slashIndex >= 0 ? url.substr(0, slashIndex) : '';\n}\n\n/**\n * Replacement for Node.js path.join\n * @param parts\n */\nexport function join(...parts: string[]): string {\n const separator = '/';\n parts = parts.map((part, index) => {\n if (index) {\n part = part.replace(new RegExp(`^${separator}`), '');\n }\n if (index !== parts.length - 1) {\n part = part.replace(new RegExp(`${separator}$`), '');\n }\n return part;\n });\n return parts.join(separator);\n}\n\n/* eslint-disable no-continue */\n\n/**\n * https://nodejs.org/api/path.html#path_path_resolve_paths\n * @param paths A sequence of paths or path segments.\n * @return resolved path\n * Forked from BTOdell/path-resolve under MIT license\n * @see https://github.com/BTOdell/path-resolve/blob/master/LICENSE\n */\nexport function resolve(...components: string[]): string {\n const paths: string[] = [];\n for (let _i = 0; _i < components.length; _i++) {\n paths[_i] = components[_i];\n }\n let resolvedPath = '';\n let resolvedAbsolute = false;\n let cwd: string | undefined;\n for (let i = paths.length - 1; i >= -1 && !resolvedAbsolute; i--) {\n let path: string | undefined;\n if (i >= 0) {\n path = paths[i];\n } else {\n if (cwd === undefined) {\n cwd = getCWD();\n }\n path = cwd;\n }\n // Skip empty entries\n if (path.length === 0) {\n continue;\n }\n resolvedPath = `${path}/${resolvedPath}`;\n resolvedAbsolute = path.charCodeAt(0) === SLASH;\n }\n // At this point the path should be resolved to a full absolute path, but\n // handle relative paths to be safe (might happen when process.cwd() fails)\n // Normalize the path (removes leading slash)\n resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute);\n if (resolvedAbsolute) {\n return `/${resolvedPath}`;\n } else if (resolvedPath.length > 0) {\n return resolvedPath;\n }\n return '.';\n}\n\nconst SLASH = 47;\nconst DOT = 46;\n\n/**\n * Resolves . and .. elements in a path with directory names\n * Forked from BTOdell/path-resolve under MIT license\n * @see https://github.com/BTOdell/path-resolve/blob/master/LICENSE\n */\n/* eslint-disable max-depth */\n// eslint-disable-next-line complexity, max-statements\nfunction normalizeStringPosix(path: string, allowAboveRoot: boolean): string {\n let res = '';\n let lastSlash = -1;\n let dots = 0;\n let code: number | undefined;\n let isAboveRoot = false;\n\n for (let i = 0; i <= path.length; ++i) {\n if (i < path.length) {\n code = path.charCodeAt(i);\n } else if (code === SLASH) {\n break;\n } else {\n code = SLASH;\n }\n if (code === SLASH) {\n if (lastSlash === i - 1 || dots === 1) {\n // NOOP\n } else if (lastSlash !== i - 1 && dots === 2) {\n if (\n res.length < 2 ||\n !isAboveRoot ||\n res.charCodeAt(res.length - 1) !== DOT ||\n res.charCodeAt(res.length - 2) !== DOT\n ) {\n if (res.length > 2) {\n const start = res.length - 1;\n let j = start;\n for (; j >= 0; --j) {\n if (res.charCodeAt(j) === SLASH) {\n break;\n }\n }\n if (j !== start) {\n res = j === -1 ? '' : res.slice(0, j);\n lastSlash = i;\n dots = 0;\n isAboveRoot = false;\n continue;\n }\n } else if (res.length === 2 || res.length === 1) {\n res = '';\n lastSlash = i;\n dots = 0;\n isAboveRoot = false;\n continue;\n }\n }\n if (allowAboveRoot) {\n if (res.length > 0) {\n res += '/..';\n } else {\n res = '..';\n }\n isAboveRoot = true;\n }\n } else {\n const slice = path.slice(lastSlash + 1, i);\n if (res.length > 0) {\n res += `/${slice}`;\n } else {\n res = slice;\n }\n isAboveRoot = false;\n }\n lastSlash = i;\n dots = 0;\n } else if (code === DOT && dots !== -1) {\n ++dots;\n } else {\n dots = -1;\n }\n }\n return res;\n}\n","// loaders.gl MIT license\n\nexport function getCWD() {\n if (typeof process !== 'undefined' && typeof process.cwd !== 'undefined') {\n return process.cwd();\n }\n const pathname = window.location?.pathname;\n return pathname?.slice(0, pathname.lastIndexOf('/') + 1) || '';\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport class FetchError extends Error {\n constructor(message: string, info: {url: string; reason: string; response?: Response}) {\n super(message);\n this.reason = info.reason;\n this.url = info.url;\n this.response = info.response;\n }\n /** A best effort reason for why the fetch failed */\n reason: string;\n /** The URL that failed to load. Empty string if not available. */\n url: string;\n /** The Response object, if any. */\n response?: Response;\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// TODO - build/integrate proper MIME type parsing\n// https://mimesniff.spec.whatwg.org/\n\nconst DATA_URL_PATTERN = /^data:([-\\w.]+\\/[-\\w.+]+)(;|,)/;\nconst MIME_TYPE_PATTERN = /^([-\\w.]+\\/[-\\w.+]+)/;\n\n/**\n * Compare two MIME types, case insensitively etc.\n * @param mimeType1\n * @param mimeType2\n * @returns true if the MIME types are equivalent\n * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types#structure_of_a_mime_type\n */\nexport function compareMIMETypes(mimeType1: string, mimeType2: string): boolean {\n if (mimeType1.toLowerCase() === mimeType2.toLowerCase()) {\n return true;\n }\n return false;\n}\n\n/**\n * Remove extra data like `charset` from MIME types\n * @param mimeString\n * @returns A clean MIME type, or an empty string\n *\n * @todo - handle more advanced MIMETYpes, multiple types\n * @todo - extract charset etc\n */\nexport function parseMIMEType(mimeString: string): string {\n // If resource is a data url, extract any embedded mime type\n const matches = MIME_TYPE_PATTERN.exec(mimeString);\n if (matches) {\n return matches[1];\n }\n return mimeString;\n}\n\n/**\n * Extract MIME type from data URL\n *\n * @param mimeString\n * @returns A clean MIME type, or an empty string\n *\n * @todo - handle more advanced MIMETYpes, multiple types\n * @todo - extract charset etc\n */\nexport function parseMIMETypeFromURL(url: string): string {\n // If resource is a data URL, extract any embedded mime type\n const matches = DATA_URL_PATTERN.exec(url);\n if (matches) {\n return matches[1];\n }\n return '';\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nconst QUERY_STRING_PATTERN = /\\?.*/;\n\nexport function extractQueryString(url): string {\n const matches = url.match(QUERY_STRING_PATTERN);\n return matches && matches[0];\n}\n\nexport function stripQueryString(url): string {\n return url.replace(QUERY_STRING_PATTERN, '');\n}\n\nexport function shortenUrlForDisplay(url: string): string {\n if (url.length < 50) {\n return url;\n }\n const urlEnd = url.slice(url.length - 15);\n const urlStart = url.substr(0, 32);\n return `${urlStart}...${urlEnd}`;\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {isResponse, isBlob} from '@loaders.gl/loader-utils';\nimport {parseMIMEType, parseMIMETypeFromURL} from './mime-type-utils';\nimport {stripQueryString} from './url-utils';\n\n/**\n * A loadable resource. Includes:\n * `Response`, `Blob` (`File` is a subclass), string URLs and data URLs\n */\nexport type Resource = Response | Blob | string;\n\n/**\n * Returns the URL associated with this resource.\n * The returned value may include a query string and need further processing.\n * If it cannot determine url, the corresponding value will be an empty string\n *\n * @todo string parameters are assumed to be URLs\n */\nexport function getResourceUrl(resource: unknown): string {\n // If resource is a `Response`, it contains the information directly as a field\n if (isResponse(resource)) {\n return resource.url;\n }\n\n // If the resource is a Blob or a File (subclass of Blob)\n if (isBlob(resource)) {\n // File objects have a \"name\" property. Blob objects don't have any\n // url (name) information\n const fileName = 'name' in resource ? (resource as File).name : '';\n return fileName || '';\n }\n\n if (typeof resource === 'string') {\n return resource;\n }\n\n // Unknown\n return '';\n}\n\n/**\n * Returns the URL associated with this resource.\n * The returned value may include a query string and need further processing.\n * If it cannot determine url, the corresponding value will be an empty string\n *\n * @todo string parameters are assumed to be URLs\n */\nexport function getResourceMIMEType(resource: unknown): string {\n // If resource is a response, it contains the information directly\n if (isResponse(resource)) {\n const contentTypeHeader = resource.headers.get('content-type') || '';\n const noQueryUrl = stripQueryString(resource.url);\n return parseMIMEType(contentTypeHeader) || parseMIMETypeFromURL(noQueryUrl);\n }\n\n // If the resource is a Blob or a File (subclass of Blob)\n if (isBlob(resource)) {\n return resource.type || '';\n }\n\n if (typeof resource === 'string') {\n return parseMIMETypeFromURL(resource);\n }\n\n // Unknown\n return '';\n}\n\n/**\n * Returns (approximate) content length for a resource if it can be determined.\n * Returns -1 if content length cannot be determined.\n * @param resource\n\n * @note string parameters are NOT assumed to be URLs\n */\nexport function getResourceContentLength(resource: unknown): number {\n if (isResponse(resource)) {\n const response = resource;\n return response.headers['content-length'] || -1;\n }\n if (isBlob(resource)) {\n const blob = resource;\n return blob.size;\n }\n if (typeof resource === 'string') {\n // TODO - handle data URL?\n return resource.length;\n }\n if (resource instanceof ArrayBuffer) {\n return resource.byteLength;\n }\n if (ArrayBuffer.isView(resource)) {\n return resource.byteLength;\n }\n return -1;\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {isResponse} from '@loaders.gl/loader-utils';\nimport {FetchError} from '../fetch/fetch-error';\nimport {getResourceContentLength, getResourceUrl, getResourceMIMEType} from './resource-utils';\nimport {shortenUrlForDisplay} from './url-utils';\n\n/**\n * Returns a Response object\n * Adds content-length header when possible\n *\n * @param resource\n */\nexport async function makeResponse(resource: unknown): Promise {\n if (isResponse(resource)) {\n return resource;\n }\n\n // Add content-length header if possible\n const headers: {[header: string]: string} = {};\n\n const contentLength = getResourceContentLength(resource);\n if (contentLength >= 0) {\n headers['content-length'] = String(contentLength);\n }\n\n // `new Response(File)` does not preserve content-type and URL\n // so we add them here\n const url = getResourceUrl(resource);\n const type = getResourceMIMEType(resource);\n if (type) {\n headers['content-type'] = type;\n }\n\n // Add a custom header with initial bytes if available\n const initialDataUrl = await getInitialDataUrl(resource);\n if (initialDataUrl) {\n headers['x-first-bytes'] = initialDataUrl;\n }\n\n // TODO - is this the best way of handling strings?\n // Maybe package as data URL instead?\n if (typeof resource === 'string') {\n // Convert to ArrayBuffer to avoid Response treating it as a URL\n resource = new TextEncoder().encode(resource);\n }\n\n // Attempt to create a Response from the resource, adding headers and setting url\n const response = new Response(resource as any, {headers});\n // We can't control `Response.url` via constructor, use a property override to record URL.\n Object.defineProperty(response, 'url', {value: url});\n return response;\n}\n\n/**\n * Checks response status (async) and throws a helpful error message if status is not OK.\n * @param response\n */\nexport async function checkResponse(response: Response): Promise {\n if (!response.ok) {\n const error = await getResponseError(response);\n throw error;\n }\n}\n\n/**\n * Checks response status (sync) and throws a helpful error message if status is not OK.\n * @param response\n */\nexport function checkResponseSync(response: Response): void {\n if (!response.ok) {\n let message = `${response.status} ${response.statusText}`;\n message = message.length > 60 ? `${message.slice(0, 60)}...` : message;\n throw new Error(message);\n }\n}\n\n// HELPERS\n\nasync function getResponseError(response: Response): Promise {\n const shortUrl = shortenUrlForDisplay(response.url);\n let message = `Failed to fetch resource (${response.status}) ${response.statusText}: ${shortUrl}`;\n message = message.length > 100 ? `${message.slice(0, 100)}...` : message;\n\n const info = {\n reason: response.statusText,\n url: response.url,\n response\n };\n\n // See if we got an error message in the body\n try {\n const contentType = response.headers.get('Content-Type');\n info.reason =\n !response.bodyUsed && contentType?.includes('application/json')\n ? await response.json()\n : await response.text();\n } catch (error) {\n // eslint forbids return in a finally statement, so we just catch here\n }\n return new FetchError(message, info);\n}\n\nasync function getInitialDataUrl(\n resource: string | Blob | ArrayBuffer | unknown\n): Promise {\n const INITIAL_DATA_LENGTH = 5;\n if (typeof resource === 'string') {\n return `data:,${resource.slice(0, INITIAL_DATA_LENGTH)}`;\n }\n if (resource instanceof Blob) {\n const blobSlice = resource.slice(0, 5);\n return await new Promise((resolve) => {\n const reader = new FileReader();\n reader.onload = (event) => resolve(event?.target?.result as string);\n reader.readAsDataURL(blobSlice);\n });\n }\n if (resource instanceof ArrayBuffer) {\n const slice = resource.slice(0, INITIAL_DATA_LENGTH);\n const base64 = arrayBufferToBase64(slice);\n return `data:base64,${base64}`;\n }\n return null;\n}\n\n// https://stackoverflow.com/questions/9267899/arraybuffer-to-base64-encoded-string\nfunction arrayBufferToBase64(buffer: ArrayBuffer): string {\n let binary = '';\n const bytes = new Uint8Array(buffer);\n for (let i = 0; i < bytes.byteLength; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n return btoa(binary);\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {resolvePath} from '@loaders.gl/loader-utils';\nimport {makeResponse} from '../utils/response-utils';\n// import {FetchError} from './fetch-error';\n\nexport function isNodePath(url: string): boolean {\n return !isRequestURL(url) && !isDataURL(url);\n}\n\nexport function isRequestURL(url: string): boolean {\n return url.startsWith('http:') || url.startsWith('https:');\n}\n\nexport function isDataURL(url: string): boolean {\n return url.startsWith('data:');\n}\n\n/**\n * fetch API compatible function\n * - Supports fetching from Node.js local file system paths\n * - Respects pathPrefix and file aliases\n */\nexport async function fetchFile(\n urlOrData: string | Blob,\n fetchOptions?: RequestInit\n): Promise {\n if (typeof urlOrData === 'string') {\n const url = resolvePath(urlOrData);\n\n // Support fetching from local file system\n if (isNodePath(url)) {\n if (globalThis.loaders?.fetchNode) {\n return globalThis.loaders?.fetchNode(url, fetchOptions);\n }\n // throw new Error(\n // 'fetchFile: globalThis.loaders.fetchNode not defined. Install @loaders.gl/polyfills'\n // );\n }\n\n // Call global fetch\n return await fetch(url, fetchOptions);\n }\n\n // TODO - should we still call fetch on non-URL inputs?\n return await makeResponse(urlOrData);\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// probe.gl Log compatible loggers\n\nimport {Log} from '@probe.gl/log';\n\nexport const probeLog = new Log({id: 'loaders.gl'});\n\ntype LogFunction = () => void;\n\n// Logs nothing\nexport class NullLog {\n log(): LogFunction {\n return () => {};\n }\n info(): LogFunction {\n return () => {};\n }\n warn(): LogFunction {\n return () => {};\n }\n error(): LogFunction {\n return () => {};\n }\n}\n\n// Logs to console\nexport class ConsoleLog {\n console;\n\n constructor() {\n this.console = console; // eslint-disable-line\n }\n log(...args: unknown[]): LogFunction {\n return this.console.log.bind(this.console, ...args);\n }\n info(...args: unknown[]): LogFunction {\n return this.console.info.bind(this.console, ...args);\n }\n warn(...args: unknown[]): LogFunction {\n return this.console.warn.bind(this.console, ...args);\n }\n error(...args: unknown[]): LogFunction {\n return this.console.error.bind(this.console, ...args);\n }\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {LoaderOptions} from '@loaders.gl/loader-utils';\nimport {isBrowser} from '@loaders.gl/loader-utils';\nimport {ConsoleLog} from './loggers';\n\nexport const DEFAULT_LOADER_OPTIONS: LoaderOptions = {\n core: {\n baseUrl: undefined,\n // baseUrl\n fetch: null,\n mimeType: undefined,\n fallbackMimeType: undefined,\n ignoreRegisteredLoaders: undefined,\n nothrow: false,\n log: new ConsoleLog(), // A probe.gl compatible (`log.log()()` syntax) that just logs to console\n useLocalLibraries: false,\n\n CDN: 'https://unpkg.com/@loaders.gl',\n worker: true, // By default, use worker if provided by loader.\n maxConcurrency: 3, // How many worker instances should be created for each loader.\n maxMobileConcurrency: 1, // How many worker instances should be created for each loader on mobile devices.\n reuseWorkers: isBrowser, // By default reuse workers in browser (Node.js refuses to terminate if browsers are running)\n _nodeWorkers: false, // By default do not support node workers\n _workerType: '', // 'test' to use locally generated workers\n\n limit: 0,\n _limitMB: 0,\n batchSize: 'auto',\n batchDebounceMs: 0,\n metadata: false, // TODO - currently only implemented for parseInBatches, adds initial metadata batch,\n transforms: []\n }\n};\n\nexport const REMOVED_LOADER_OPTIONS = {\n // deprecated top-level alias\n baseUri: 'core.baseUrl',\n fetch: 'core.fetch',\n mimeType: 'core.mimeType',\n fallbackMimeType: 'core.fallbackMimeType',\n ignoreRegisteredLoaders: 'core.ignoreRegisteredLoaders',\n nothrow: 'core.nothrow',\n log: 'core.log',\n useLocalLibraries: 'core.useLocalLibraries',\n\n CDN: 'core.CDN',\n worker: 'core.worker',\n maxConcurrency: 'core.maxConcurrency',\n maxMobileConcurrency: 'core.maxMobileConcurrency',\n reuseWorkers: 'core.reuseWorkers',\n _nodeWorkers: 'core.nodeWorkers',\n _workerType: 'core._workerType',\n _worker: 'core._workerType',\n\n limit: 'core.limit',\n _limitMB: 'core._limitMB',\n batchSize: 'core.batchSize',\n batchDebounceMs: 'core.batchDebounceMs',\n metadata: 'core.metadata',\n transforms: 'core.transforms',\n\n // Older deprecations\n throws: 'nothrow',\n dataType: '(no longer used)',\n uri: 'core.baseUrl',\n\n // Warn if fetch options are used on toplevel\n method: 'core.fetch.method',\n headers: 'core.fetch.headers',\n body: 'core.fetch.body',\n mode: 'core.fetch.mode',\n credentials: 'core.fetch.credentials',\n cache: 'core.fetch.cache',\n redirect: 'core.fetch.redirect',\n referrer: 'core.fetch.referrer',\n referrerPolicy: 'core.fetch.referrerPolicy',\n integrity: 'core.fetch.integrity',\n keepalive: 'core.fetch.keepalive',\n signal: 'core.fetch.signal'\n};\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {\n Loader,\n LoaderOptions,\n registerJSModules,\n isPureObject,\n isObject,\n StrictLoaderOptions,\n path\n} from '@loaders.gl/loader-utils';\nimport {probeLog, NullLog} from './loggers';\nimport {DEFAULT_LOADER_OPTIONS, REMOVED_LOADER_OPTIONS} from './option-defaults';\nimport {stripQueryString} from '../utils/url-utils';\n\nconst CORE_LOADER_OPTION_KEYS = [\n 'baseUrl',\n 'fetch',\n 'mimeType',\n 'fallbackMimeType',\n 'ignoreRegisteredLoaders',\n 'nothrow',\n 'log',\n 'useLocalLibraries',\n 'CDN',\n 'worker',\n 'maxConcurrency',\n 'maxMobileConcurrency',\n 'reuseWorkers',\n '_nodeWorkers',\n '_workerType',\n 'limit',\n '_limitMB',\n 'batchSize',\n 'batchDebounceMs',\n 'metadata',\n 'transforms'\n] as const;\n\n/**\n * Global state for loaders.gl. Stored on `globalThis.loaders._state`\n */\ntype GlobalLoaderState = {\n loaderRegistry: Loader[];\n globalOptions: LoaderOptions;\n};\n\n/**\n * Helper for safely accessing global loaders.gl variables\n * Wraps initialization of global variable in function to defeat overly aggressive tree-shakers\n */\nexport function getGlobalLoaderState(): GlobalLoaderState {\n // @ts-ignore\n globalThis.loaders = globalThis.loaders || {};\n // @ts-ignore\n const {loaders} = globalThis;\n\n // Add _state object to keep separate from modules added to globalThis.loaders\n if (!loaders._state) {\n loaders._state = {};\n }\n return loaders._state;\n}\n\n/**\n * Store global loader options on the global object to increase chances of cross loaders-version interoperability\n * NOTE: This use case is not reliable but can help when testing new versions of loaders.gl with existing frameworks\n * @returns global loader options merged with default loader options\n */\nexport function getGlobalLoaderOptions(): StrictLoaderOptions {\n const state = getGlobalLoaderState();\n // Ensure all default loader options from this library are mentioned\n state.globalOptions = state.globalOptions || {\n ...DEFAULT_LOADER_OPTIONS,\n core: {...DEFAULT_LOADER_OPTIONS.core}\n };\n return normalizeLoaderOptions(state.globalOptions);\n}\n\n/**\n * Set global loader options\n * @param options\n */\nexport function setGlobalOptions(options: LoaderOptions): void {\n const state = getGlobalLoaderState();\n const globalOptions = getGlobalLoaderOptions();\n // @ts-expect-error First param looks incorrect\n state.globalOptions = normalizeOptionsInternal(globalOptions, options);\n // Make sure any new modules are registered\n registerJSModules(options.modules);\n}\n\n/**\n * Merges options with global opts and loader defaults, also injects baseUrl\n * @param options\n * @param loader\n * @param loaders\n * @param url\n */\nexport function normalizeOptions(\n options: LoaderOptions,\n loader: Loader,\n loaders?: Loader[],\n url?: string\n): StrictLoaderOptions {\n loaders = loaders || [];\n loaders = Array.isArray(loaders) ? loaders : [loaders];\n\n validateOptions(options, loaders);\n return normalizeLoaderOptions(normalizeOptionsInternal(loader, options, url));\n}\n\n/**\n * Returns a copy of the provided options with deprecated top-level core fields moved into `core`\n * and removed from the top level. This keeps global options from leaking deprecated aliases into\n * loader-specific option maps during normalization.\n */\nexport function normalizeLoaderOptions(options: LoaderOptions): StrictLoaderOptions {\n const normalized = cloneLoaderOptions(options);\n moveDeprecatedTopLevelOptionsToCore(normalized);\n for (const key of CORE_LOADER_OPTION_KEYS) {\n if (normalized.core && normalized.core[key] !== undefined) {\n delete (normalized as Record)[key];\n }\n }\n if (normalized.core && normalized.core._workerType !== undefined) {\n delete (normalized as any)._worker;\n }\n return normalized as StrictLoaderOptions;\n}\n\n// VALIDATE OPTIONS\n\n/**\n * Warn for unsupported options\n * @param options\n * @param loaders\n */\nfunction validateOptions(options: LoaderOptions, loaders: Loader[]): void {\n // Check top level options\n validateOptionsObject(options, null, DEFAULT_LOADER_OPTIONS, REMOVED_LOADER_OPTIONS, loaders);\n for (const loader of loaders) {\n // Get the scoped, loader specific options from the user supplied options\n const idOptions: Record =\n ((options && options[loader.id]) as Record) || {};\n\n // Get scoped, loader specific default and deprecated options from the selected loader\n const loaderOptions = (loader.options && loader.options[loader.id]) || {};\n const deprecatedOptions =\n (loader.deprecatedOptions && loader.deprecatedOptions[loader.id]) || {};\n\n // Validate loader specific options\n // @ts-ignore\n validateOptionsObject(idOptions, loader.id, loaderOptions, deprecatedOptions, loaders);\n }\n}\n\n// eslint-disable-next-line max-params, complexity\nfunction validateOptionsObject(\n options: LoaderOptions,\n id: string | null,\n defaultOptions: Record,\n deprecatedOptions: Record,\n loaders: Loader[]\n): void {\n const loaderName = id || 'Top level';\n const prefix = id ? `${id}.` : '';\n\n for (const key in options) {\n // If top level option value is an object it could options for a loader, so ignore\n const isSubOptions = !id && isObject(options[key]);\n const isBaseUriOption = key === 'baseUri' && !id;\n const isWorkerUrlOption = key === 'workerUrl' && id;\n // .workerUrl requires special handling as it is now auto-generated and no longer specified as a default option.\n if (!(key in defaultOptions) && !isBaseUriOption && !isWorkerUrlOption) {\n // Issue deprecation warnings\n if (key in deprecatedOptions) {\n if (probeLog.level > 0) {\n probeLog.warn(\n `${loaderName} loader option \\'${prefix}${key}\\' no longer supported, use \\'${deprecatedOptions[key]}\\'`\n )();\n }\n } else if (!isSubOptions) {\n if (probeLog.level > 0) {\n const suggestion = findSimilarOption(key, loaders);\n probeLog.warn(\n `${loaderName} loader option \\'${prefix}${key}\\' not recognized. ${suggestion}`\n )();\n }\n }\n }\n }\n}\n\nfunction findSimilarOption(optionKey: string, loaders: Loader[]): string {\n const lowerCaseOptionKey = optionKey.toLowerCase();\n let bestSuggestion = '';\n for (const loader of loaders) {\n for (const key in loader.options) {\n if (optionKey === key) {\n return `Did you mean \\'${loader.id}.${key}\\'?`;\n }\n const lowerCaseKey = key.toLowerCase();\n const isPartialMatch =\n lowerCaseOptionKey.startsWith(lowerCaseKey) || lowerCaseKey.startsWith(lowerCaseOptionKey);\n if (isPartialMatch) {\n bestSuggestion = bestSuggestion || `Did you mean \\'${loader.id}.${key}\\'?`;\n }\n }\n }\n return bestSuggestion;\n}\n\nfunction normalizeOptionsInternal(\n loader: Loader,\n options: LoaderOptions,\n url?: string\n): LoaderOptions {\n const loaderDefaultOptions = loader.options || {};\n\n const mergedOptions = {...loaderDefaultOptions};\n if (loaderDefaultOptions.core) {\n mergedOptions.core = {...loaderDefaultOptions.core};\n }\n moveDeprecatedTopLevelOptionsToCore(mergedOptions);\n\n // LOGGING: options.log can be set to `null` to defeat logging\n if (mergedOptions.core?.log === null) {\n mergedOptions.core = {...mergedOptions.core, log: new NullLog()};\n }\n\n mergeNestedFields(mergedOptions, normalizeLoaderOptions(getGlobalLoaderOptions()));\n\n const userOptions = normalizeLoaderOptions(options);\n mergeNestedFields(mergedOptions, userOptions);\n\n addUrlOptions(mergedOptions, url);\n addDeprecatedTopLevelOptions(mergedOptions);\n\n return mergedOptions;\n}\n\n// Merge nested options objects\nfunction mergeNestedFields(mergedOptions: LoaderOptions, options: LoaderOptions): void {\n for (const key in options) {\n // Check for nested options\n // object in options => either no key in defaultOptions or object in defaultOptions\n if (key in options) {\n const value = options[key];\n if (isPureObject(value) && isPureObject(mergedOptions[key])) {\n mergedOptions[key] = {\n ...(mergedOptions[key] as object),\n ...(options[key] as object)\n };\n } else {\n mergedOptions[key] = options[key];\n }\n }\n // else: No need to merge nested opts, and the initial merge already copied over the nested options\n }\n}\n\n/**\n * Harvest information from the url\n * @deprecated This is mainly there to support loaders that still resolve from options\n * TODO - extract extension?\n * TODO - extract query parameters?\n * TODO - should these be injected on context instead of options?\n */\nfunction addUrlOptions(options: LoaderOptions, url?: string): void {\n if (!url) {\n return;\n }\n const hasCoreBaseUrl = options.core?.baseUrl !== undefined;\n if (!hasCoreBaseUrl) {\n options.core ||= {};\n options.core.baseUrl = path.dirname(stripQueryString(url));\n }\n}\n\nfunction cloneLoaderOptions(options: LoaderOptions): LoaderOptions {\n const clonedOptions = {...options};\n if (options.core) {\n clonedOptions.core = {...options.core};\n }\n return clonedOptions;\n}\n\nfunction moveDeprecatedTopLevelOptionsToCore(options: LoaderOptions): void {\n if (options.baseUri !== undefined) {\n options.core ||= {};\n if (options.core.baseUrl === undefined) {\n options.core.baseUrl = options.baseUri;\n }\n }\n\n for (const key of CORE_LOADER_OPTION_KEYS) {\n if ((options as Record)[key] !== undefined) {\n const coreOptions = (options.core = options.core || {});\n const coreRecord = coreOptions as Record;\n // Treat deprecated top-level core options as aliases to `options.core`, but never override an explicitly\n // provided `options.core` value.\n if (coreRecord[key] === undefined) {\n coreRecord[key] = (options as Record)[key];\n }\n }\n }\n\n // Support the older internal `_worker` alias (used by some tests and integrations) for `_workerType`.\n const workerTypeAlias = (options as any)._worker;\n if (workerTypeAlias !== undefined) {\n options.core ||= {};\n if (options.core._workerType === undefined) {\n options.core._workerType = workerTypeAlias;\n }\n }\n}\n\nfunction addDeprecatedTopLevelOptions(options: LoaderOptions): void {\n const coreOptions = options.core as Record | undefined;\n if (!coreOptions) {\n return;\n }\n for (const key of CORE_LOADER_OPTION_KEYS) {\n if (coreOptions[key] !== undefined) {\n (options as Record)[key] = coreOptions[key];\n }\n }\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Loader} from '@loaders.gl/loader-utils';\nimport {assert} from '@loaders.gl/loader-utils';\n\nexport function isLoaderObject(loader?: any): boolean {\n if (!loader) {\n return false;\n }\n\n if (Array.isArray(loader)) {\n loader = loader[0];\n }\n\n const hasExtensions = Array.isArray(loader?.extensions);\n\n /* Now handled by types and worker loaders do not have these\n let hasParser =\n loader.parseTextSync ||\n loader.parseSync ||\n loader.parse ||\n loader.parseStream || // TODO Remove, Replace with parseInBatches\n loader.parseInBatches;\n */\n\n return hasExtensions;\n}\n\nexport function normalizeLoader(loader: Loader): Loader {\n // This error is fairly easy to trigger by mixing up import statements etc\n // So we make an exception and add a developer error message for this case\n // To help new users from getting stuck here\n assert(loader, 'null loader');\n assert(isLoaderObject(loader), 'invalid loader');\n\n // NORMALIZE [LOADER, OPTIONS] => LOADER\n\n // If [loader, options], create a new loaders object with options merged in\n let options;\n if (Array.isArray(loader)) {\n options = loader[1];\n loader = loader[0];\n loader = {\n ...loader,\n options: {...loader.options, ...options}\n };\n }\n\n // NORMALIZE text and binary flags\n // Ensure at least one of text/binary flags are properly set\n\n // @ts-expect-error\n if (loader?.parseTextSync || loader?.parseText) {\n loader.text = true;\n }\n\n if (!loader.text) {\n loader.binary = true;\n }\n\n return loader;\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Loader} from '@loaders.gl/loader-utils';\nimport {normalizeLoader} from '../loader-utils/normalize-loader';\nimport {getGlobalLoaderState} from '../loader-utils/option-utils';\n\n/**\n * Store global registered loaders on the global object to increase chances of cross loaders-version interoperability\n * This use case is not reliable but can help when testing new versions of loaders.gl with existing frameworks\n */\nconst getGlobalLoaderRegistry = () => {\n const state = getGlobalLoaderState();\n state.loaderRegistry = state.loaderRegistry || [];\n return state.loaderRegistry;\n};\n\n/**\n * Register a list of global loaders\n * @note Registration erases loader type information.\n * @deprecated It is recommended that applications manage loader registration. This function will likely be remove in loaders.gl v5\n */\nexport function registerLoaders(loaders: Loader[] | Loader) {\n const loaderRegistry = getGlobalLoaderRegistry();\n\n loaders = Array.isArray(loaders) ? loaders : [loaders];\n\n for (const loader of loaders) {\n const normalizedLoader = normalizeLoader(loader);\n if (!loaderRegistry.find((registeredLoader) => normalizedLoader === registeredLoader)) {\n // add to the beginning of the loaderRegistry, so the last registeredLoader get picked\n loaderRegistry.unshift(normalizedLoader);\n }\n }\n}\n\n/**\n * @deprecated It is recommended that applications manage loader registration. This function will likely be remove in loaders.gl v5\n */\nexport function getRegisteredLoaders(): Loader[] {\n return getGlobalLoaderRegistry();\n}\n\n/** @deprecated For testing only */\nexport function _unregisterLoaders() {\n const state = getGlobalLoaderState();\n state.loaderRegistry = [];\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {LoaderContext, LoaderOptions, Loader, DataType} from '@loaders.gl/loader-utils';\nimport {\n compareArrayBuffers,\n path,\n log,\n isBlob,\n ensureArrayBuffer,\n isArrayBufferLike\n} from '@loaders.gl/loader-utils';\nimport {TypedArray} from '@loaders.gl/schema';\nimport {normalizeLoader} from '../loader-utils/normalize-loader';\nimport {normalizeLoaderOptions} from '../loader-utils/option-utils';\nimport {getResourceUrl, getResourceMIMEType} from '../utils/resource-utils';\nimport {compareMIMETypes} from '../utils/mime-type-utils';\nimport {getRegisteredLoaders} from './register-loaders';\nimport {stripQueryString} from '../utils/url-utils';\n\nconst EXT_PATTERN = /\\.([^.]+)$/;\n\n// TODO - Need a variant that peeks at streams for parseInBatches\n// TODO - Detect multiple matching loaders? Use heuristics to grade matches?\n// TODO - Allow apps to pass context to disambiguate between multiple matches (e.g. multiple .json formats)?\n\n/**\n * Find a loader that matches file extension and/or initial file content\n * Search the loaders array argument for a loader that matches url extension or initial data\n * Returns: a normalized loader\n * @param data data to assist\n * @param loaders\n * @param options\n * @param context used internally, applications should not provide this parameter\n */\nexport async function selectLoader(\n data: DataType,\n loaders: Loader[] | Loader = [],\n options?: LoaderOptions,\n context?: LoaderContext\n): Promise {\n if (!validHTTPResponse(data)) {\n return null;\n }\n\n const normalizedOptions = normalizeLoaderOptions(options || {});\n normalizedOptions.core ||= {};\n\n if (data instanceof Response && mayContainText(data)) {\n const text = await data.clone().text();\n const textLoader = selectLoaderSync(\n text,\n loaders,\n {...normalizedOptions, core: {...normalizedOptions.core, nothrow: true}},\n context\n );\n if (textLoader) {\n return textLoader;\n }\n }\n\n // First make a sync attempt, disabling exceptions\n let loader = selectLoaderSync(\n data,\n loaders,\n {...normalizedOptions, core: {...normalizedOptions.core, nothrow: true}},\n context\n );\n if (loader) {\n return loader;\n }\n\n // For Blobs and Files, try to asynchronously read a small initial slice and test again with that\n // to see if we can detect by initial content\n if (isBlob(data)) {\n data = await data.slice(0, 10).arrayBuffer();\n loader = selectLoaderSync(data, loaders, normalizedOptions, context);\n }\n\n if (!loader && data instanceof Response && mayContainText(data)) {\n const text = await data.clone().text();\n loader = selectLoaderSync(text, loaders, normalizedOptions, context);\n }\n\n // no loader available\n if (!loader && !normalizedOptions.core.nothrow) {\n throw new Error(getNoValidLoaderMessage(data));\n }\n\n return loader;\n}\n\nfunction mayContainText(response: Response): boolean {\n const mimeType = getResourceMIMEType(response);\n return Boolean(\n mimeType &&\n (mimeType.startsWith('text/') || mimeType === 'application/json' || mimeType.endsWith('+json'))\n );\n}\n\n/**\n * Find a loader that matches file extension and/or initial file content\n * Search the loaders array argument for a loader that matches url extension or initial data\n * Returns: a normalized loader\n * @param data data to assist\n * @param loaders\n * @param options\n * @param context used internally, applications should not provide this parameter\n */\nexport function selectLoaderSync(\n data: DataType,\n loaders: Loader[] | Loader = [],\n options?: LoaderOptions,\n context?: LoaderContext\n): Loader | null {\n if (!validHTTPResponse(data)) {\n return null;\n }\n\n const normalizedOptions = normalizeLoaderOptions(options || {});\n normalizedOptions.core ||= {};\n\n // eslint-disable-next-line complexity\n // if only a single loader was provided (not as array), force its use\n // TODO - Should this behavior be kept and documented?\n if (loaders && !Array.isArray(loaders)) {\n // TODO - remove support for legacy loaders\n return normalizeLoader(loaders);\n }\n\n // Build list of candidate loaders that will be searched in order for a match\n let candidateLoaders: Loader[] = [];\n // First search supplied loaders\n if (loaders) {\n candidateLoaders = candidateLoaders.concat(loaders);\n }\n // Then fall back to registered loaders\n if (!normalizedOptions.core.ignoreRegisteredLoaders) {\n candidateLoaders.push(...getRegisteredLoaders());\n }\n\n // TODO - remove support for legacy loaders\n normalizeLoaders(candidateLoaders);\n\n const loader = selectLoaderInternal(data, candidateLoaders, normalizedOptions, context);\n\n // no loader available\n if (!loader && !normalizedOptions.core.nothrow) {\n throw new Error(getNoValidLoaderMessage(data));\n }\n\n return loader;\n}\n\n/** Implements loaders selection logic */\n// eslint-disable-next-line complexity\nfunction selectLoaderInternal(\n data: DataType,\n loaders: Loader[],\n options?: LoaderOptions,\n context?: LoaderContext\n) {\n const url = getResourceUrl(data);\n const type = getResourceMIMEType(data);\n\n const testUrl = stripQueryString(url) || context?.url;\n\n let loader: Loader | null = null;\n let reason: string = '';\n\n // if options.mimeType is supplied, it takes precedence\n if (options?.core?.mimeType) {\n loader = findLoaderByMIMEType(loaders, options?.core?.mimeType);\n reason = `match forced by supplied MIME type ${options?.core?.mimeType}`;\n }\n\n // Look up loader by url\n loader = loader || findLoaderByUrl(loaders, testUrl);\n reason = reason || (loader ? `matched url ${testUrl}` : '');\n\n // Look up loader by mime type\n loader = loader || findLoaderByMIMEType(loaders, type);\n reason = reason || (loader ? `matched MIME type ${type}` : '');\n\n // Look for loader via initial bytes (Note: not always accessible (e.g. Response, stream, async iterator)\n // @ts-ignore Blob | Response\n loader = loader || findLoaderByInitialBytes(loaders, data);\n // @ts-ignore Blob | Response\n reason = reason || (loader ? `matched initial data ${getFirstCharacters(data)}` : '');\n\n // Look up loader by fallback mime type\n if (options?.core?.fallbackMimeType) {\n loader = loader || findLoaderByMIMEType(loaders, options?.core?.fallbackMimeType);\n reason = reason || (loader ? `matched fallback MIME type ${type}` : '');\n }\n\n if (reason) {\n log.log(1, `selectLoader selected ${loader?.name}: ${reason}.`);\n }\n\n return loader;\n}\n\n/** Check HTTP Response */\nfunction validHTTPResponse(data: unknown): boolean {\n // HANDLE HTTP status\n if (data instanceof Response) {\n // 204 - NO CONTENT. This handles cases where e.g. a tile server responds with 204 for a missing tile\n if (data.status === 204) {\n return false;\n }\n }\n return true;\n}\n\n/** Generate a helpful message to help explain why loader selection failed. */\nfunction getNoValidLoaderMessage(data: DataType): string {\n const url = getResourceUrl(data);\n const type = getResourceMIMEType(data);\n\n let message = 'No valid loader found (';\n message += url ? `${path.filename(url)}, ` : 'no url provided, ';\n message += `MIME type: ${type ? `\"${type}\"` : 'not provided'}, `;\n // First characters are only accessible when called on data (string or arrayBuffer).\n // @ts-ignore Blob | Response\n const firstCharacters: string = data ? getFirstCharacters(data) : '';\n message += firstCharacters ? ` first bytes: \"${firstCharacters}\"` : 'first bytes: not available';\n message += ')';\n return message;\n}\n\nfunction normalizeLoaders(loaders: Loader[]): void {\n for (const loader of loaders) {\n normalizeLoader(loader);\n }\n}\n\n// TODO - Would be nice to support http://example.com/file.glb?parameter=1\n// E.g: x = new URL('http://example.com/file.glb?load=1'; x.pathname\nfunction findLoaderByUrl(loaders: Loader[], url?: string): Loader | null {\n // Get extension\n const match = url && EXT_PATTERN.exec(url);\n const extension = match && match[1];\n return extension ? findLoaderByExtension(loaders, extension) : null;\n}\n\nfunction findLoaderByExtension(loaders: Loader[], extension: string): Loader | null {\n extension = extension.toLowerCase();\n\n for (const loader of loaders) {\n for (const loaderExtension of loader.extensions) {\n if (loaderExtension.toLowerCase() === extension) {\n return loader;\n }\n }\n }\n return null;\n}\n\nfunction findLoaderByMIMEType(loaders: Loader[], mimeType: string): Loader | null {\n for (const loader of loaders) {\n if (loader.mimeTypes?.some((mimeType1) => compareMIMETypes(mimeType, mimeType1))) {\n return loader;\n }\n\n // Support referring to loaders using the \"unregistered tree\"\n // https://en.wikipedia.org/wiki/Media_type#Unregistered_tree\n if (compareMIMETypes(mimeType, `application/x.${loader.id}`)) {\n return loader;\n }\n }\n return null;\n}\n\nfunction findLoaderByInitialBytes(loaders: Loader[], data: string | ArrayBuffer): Loader | null {\n if (!data) {\n return null;\n }\n\n for (const loader of loaders) {\n if (typeof data === 'string') {\n if (testDataAgainstText(data, loader)) {\n return loader;\n }\n } else if (ArrayBuffer.isView(data)) {\n // Typed Arrays can have offsets into underlying buffer\n if (testDataAgainstBinary(data.buffer, data.byteOffset, loader)) {\n return loader;\n }\n } else if (data instanceof ArrayBuffer) {\n const byteOffset = 0;\n if (testDataAgainstBinary(data, byteOffset, loader)) {\n return loader;\n }\n }\n // TODO Handle streaming case (requires creating a new AsyncIterator)\n }\n return null;\n}\n\nfunction testDataAgainstText(data: string, loader: Loader): boolean {\n if (loader.testText) {\n return loader.testText(data);\n }\n\n const tests = Array.isArray(loader.tests) ? loader.tests : [loader.tests];\n return tests.some((test) => data.startsWith(test as string));\n}\n\nfunction testDataAgainstBinary(data: ArrayBufferLike, byteOffset: number, loader: Loader): boolean {\n const tests = Array.isArray(loader.tests) ? loader.tests : [loader.tests];\n return tests.some((test) => testBinary(data, byteOffset, loader, test));\n}\n\nfunction testBinary(\n data: ArrayBufferLike,\n byteOffset: number,\n loader: Loader,\n test?: ArrayBuffer | string | ((b: ArrayBuffer) => boolean)\n): boolean {\n if (isArrayBufferLike(test)) {\n return compareArrayBuffers(test, data, test.byteLength);\n }\n switch (typeof test) {\n case 'function':\n return test(ensureArrayBuffer(data));\n\n case 'string':\n // Magic bytes check: If `test` is a string, check if binary data starts with that strings\n const magic = getMagicString(data, byteOffset, test.length);\n return test === magic;\n\n default:\n return false;\n }\n}\n\nfunction getFirstCharacters(data: string | ArrayBuffer | TypedArray, length: number = 5) {\n if (typeof data === 'string') {\n return data.slice(0, length);\n } else if (ArrayBuffer.isView(data)) {\n // Typed Arrays can have offsets into underlying buffer\n return getMagicString(data.buffer, data.byteOffset, length);\n } else if (data instanceof ArrayBuffer) {\n const byteOffset = 0;\n return getMagicString(data, byteOffset, length);\n }\n return '';\n}\n\nfunction getMagicString(arrayBuffer: ArrayBufferLike, byteOffset: number, length: number): string {\n if (arrayBuffer.byteLength < byteOffset + length) {\n return '';\n }\n const dataView = new DataView(arrayBuffer);\n let magic = '';\n for (let i = 0; i < length; i++) {\n magic += String.fromCharCode(dataView.getUint8(byteOffset + i));\n }\n return magic;\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {ensureArrayBuffer} from '@loaders.gl/loader-utils';\nimport type {IteratorOptions} from './make-iterator';\n\nconst DEFAULT_CHUNK_SIZE = 256 * 1024;\n\n/**\n * Returns an iterator that breaks a big string into chunks and yields them one-by-one as ArrayBuffers\n * @param blob string to iterate over\n * @param options\n * @param options.chunkSize\n */\nexport function* makeStringIterator(\n string: string,\n options?: IteratorOptions\n): Iterable {\n const chunkSize = options?.chunkSize || DEFAULT_CHUNK_SIZE;\n\n let offset = 0;\n const textEncoder = new TextEncoder();\n while (offset < string.length) {\n // Create a chunk of the right size\n const chunkLength = Math.min(string.length - offset, chunkSize);\n const chunk = string.slice(offset, offset + chunkLength);\n offset += chunkLength;\n\n // yield an ArrayBuffer chunk\n yield ensureArrayBuffer(textEncoder.encode(chunk));\n }\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {IteratorOptions} from './make-iterator';\n\nconst DEFAULT_CHUNK_SIZE = 256 * 1024;\n\n/**\n * Returns an iterator that breaks a big ArrayBuffer into chunks and yields them one-by-one\n * @param blob ArrayBuffer to iterate over\n * @param options\n * @param options.chunkSize\n */\nexport function* makeArrayBufferIterator(\n arrayBuffer: ArrayBuffer,\n options: IteratorOptions = {}\n): Iterable {\n const {chunkSize = DEFAULT_CHUNK_SIZE} = options;\n\n let byteOffset = 0;\n\n while (byteOffset < arrayBuffer.byteLength) {\n // Create a chunk of the right size\n const chunkByteLength = Math.min(arrayBuffer.byteLength - byteOffset, chunkSize);\n const chunk = new ArrayBuffer(chunkByteLength);\n\n // Copy data from the big chunk\n const sourceArray = new Uint8Array(arrayBuffer, byteOffset, chunkByteLength);\n const chunkArray = new Uint8Array(chunk);\n chunkArray.set(sourceArray);\n\n // yield the chunk\n byteOffset += chunkByteLength;\n yield chunk;\n }\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {IteratorOptions} from './make-iterator';\n\nconst DEFAULT_CHUNK_SIZE = 1024 * 1024; // 1MB — biggest value that keeps UI responsive\n\n/**\n * Returns an iterator that breaks a big Blob into chunks and yields them one-by-one\n * @param blob Blob or File object\n * @param options\n * @param options.chunkSize\n */\nexport async function* makeBlobIterator(\n blob: Blob,\n options?: IteratorOptions\n): AsyncIterable {\n const chunkSize = options?.chunkSize || DEFAULT_CHUNK_SIZE;\n\n let offset = 0;\n while (offset < blob.size) {\n const end = offset + chunkSize;\n\n const chunk = await blob.slice(offset, end).arrayBuffer();\n\n offset = end;\n yield chunk;\n }\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Readable} from 'stream';\nimport {isBrowser, toArrayBuffer} from '@loaders.gl/loader-utils';\n\nexport type StreamIteratorOptions = {\n _streamReadAhead?: boolean;\n};\n\n/**\n * Returns an async iterable that reads from a stream (works in both Node.js and browsers)\n * @param stream stream to iterator over\n */\nexport function makeStreamIterator(\n stream: ReadableStream | Readable,\n options?: StreamIteratorOptions\n): AsyncIterable {\n return isBrowser\n ? makeBrowserStreamIterator(stream as ReadableStream, options)\n : makeNodeStreamIterator(stream as Readable, options);\n}\n\n/**\n * Returns an async iterable that reads from a DOM (browser) stream\n * @param stream stream to iterate from\n * @see https://jakearchibald.com/2017/async-iterators-and-generators/#making-streams-iterate\n */\nasync function* makeBrowserStreamIterator(\n stream: ReadableStream,\n options?: StreamIteratorOptions\n): AsyncIterable {\n // WhatWG: stream is supposed to have a `getIterator` method\n // if (typeof stream.getIterator === 'function') {\n // return stream.getIterator();\n // }\n // if (typeof stream[Symbol.asyncIterator] === 'function') {\n // return makeToArrayBufferIterator(stream);\n // }\n\n // In the browser, we first need to get a lock on the stream\n const reader = stream.getReader();\n\n let nextBatchPromise: Promise<{done?: boolean; value?: Uint8Array}> | undefined;\n\n try {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const currentBatchPromise = nextBatchPromise || reader.read();\n // Issue a read for an additional batch, while we await the next batch\n // Idea is to make fetching happen in parallel with processing / parsing\n if (options?._streamReadAhead) {\n nextBatchPromise = reader.read();\n }\n // Read from the stream\n // value is a Uint8Array\n const {done, value} = await currentBatchPromise;\n // Exit if we're done\n if (done) {\n return;\n }\n // Else yield the chunk\n yield toArrayBuffer(value);\n }\n } catch (error) {\n // TODO - examples makes it look like this should always be called,\n // but that generates exceptions so only call it if we do not reach the end\n reader.releaseLock();\n }\n}\n\n/**\n * Returns an async iterable that reads from a DOM (browser) stream\n * @param stream stream to iterate from\n * @note Requires Node.js >= 10\n */\nasync function* makeNodeStreamIterator(\n stream: Readable,\n options?: StreamIteratorOptions\n): AsyncIterable {\n // Hacky test for node version to ensure we don't call bad polyfills\n // NODE 10+: stream is an asyncIterator\n for await (const chunk of stream) {\n yield toArrayBuffer(chunk); // Coerce each chunk to ArrayBuffer\n }\n}\n/* TODO - remove NODE < 10\n * @see https://github.com/bustle/streaming-iterables, MIT license\n *\n if (typeof stream[Symbol.asyncIterator] === 'function') {\n return;\n }\n\n // TODO - check if is this ever used in Node 10+?\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const data = stream.read();\n if (data !== null) {\n yield toArrayBuffer(data);\n // eslint-disable-next-line no-continue\n continue;\n }\n if (stream._readableState?.ended) {\n return;\n }\n await onceReadable(stream);\n }\n\nasync function onceReadable(stream: Readable): Promise {\n return new Promise((resolve) => {\n stream.once('readable', resolve);\n });\n}\n */\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ReadStream} from 'fs';\n\nimport {makeStringIterator} from './make-string-iterator';\nimport {makeArrayBufferIterator} from './make-array-buffer-iterator';\nimport {makeBlobIterator} from './make-blob-iterator';\nimport type {StreamIteratorOptions} from './make-stream-iterator';\nimport {makeStreamIterator} from './make-stream-iterator';\nimport {isBlob, isReadableStream, isResponse} from '@loaders.gl/loader-utils';\n\n/**\n * @param [options.chunkSize]\n */\nexport type IteratorOptions = StreamIteratorOptions & {\n chunkSize?: number;\n};\n\n/**\n * Returns an iterator that breaks its input into chunks and yields them one-by-one.\n * @param data\n * @param options\n * @returns\n * This function can e.g. be used to enable data sources that can only be read atomically\n * (such as `Blob` and `File` via `FileReader`) to still be parsed in batches.\n */\nexport function makeIterator(\n data: ArrayBuffer | string | Blob | Response | ReadableStream | ReadStream,\n options?: IteratorOptions\n): AsyncIterable | Iterable {\n if (typeof data === 'string') {\n // Note: Converts string chunks to binary\n return makeStringIterator(data, options);\n }\n if (data instanceof ArrayBuffer) {\n return makeArrayBufferIterator(data, options);\n }\n if (isBlob(data)) {\n return makeBlobIterator(data, options);\n }\n if (isReadableStream(data)) {\n return makeStreamIterator(data, options);\n }\n if (isResponse(data)) {\n const responseBody = data.body;\n if (!responseBody) {\n throw new Error('Readable stream not available on Response');\n }\n return makeStreamIterator(responseBody as ReadableStream, options);\n }\n throw new Error('makeIterator');\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {\n DataType,\n SyncDataType,\n BatchableDataType,\n Loader,\n LoaderOptions\n} from '@loaders.gl/loader-utils';\nimport {\n concatenateArrayBuffersAsync,\n isPromise,\n isResponse,\n isReadableStream,\n isAsyncIterable,\n isIterable,\n isIterator,\n isBlob,\n isBuffer,\n isArrayBufferLike,\n toArrayBuffer,\n toArrayBufferView\n} from '@loaders.gl/loader-utils';\nimport {makeIterator} from '../../iterators/make-iterator/make-iterator';\nimport {checkResponse, makeResponse} from '../utils/response-utils';\n\nconst ERR_DATA = 'Cannot convert supplied data type';\n\n/**\n * Returns an {@link ArrayBuffer} or string from the provided data synchronously.\n * Supports `ArrayBuffer`, `ArrayBufferView`, and `ArrayBufferLike` (e.g. `SharedArrayBuffer`)\n * while preserving typed array view offsets.\n */\n// eslint-disable-next-line complexity\nexport function getArrayBufferOrStringFromDataSync(\n data: SyncDataType,\n loader: Loader,\n options: LoaderOptions\n): ArrayBuffer | string {\n if (loader.text && typeof data === 'string') {\n return data;\n }\n\n if (isBuffer(data)) {\n data = data.buffer;\n }\n\n if (isArrayBufferLike(data)) {\n const bufferSource = toArrayBufferView(data);\n if (loader.text && !loader.binary) {\n const textDecoder = new TextDecoder('utf8');\n return textDecoder.decode(bufferSource);\n }\n return toArrayBuffer(bufferSource);\n }\n\n throw new Error(ERR_DATA);\n}\n\n/**\n * Resolves the provided data into an {@link ArrayBuffer} or string asynchronously.\n * Accepts the full {@link DataType} surface including responses and async iterables.\n */\nexport async function getArrayBufferOrStringFromData(\n data: DataType,\n loader: Loader,\n options: LoaderOptions\n): Promise {\n if (typeof data === 'string' || isArrayBufferLike(data)) {\n return getArrayBufferOrStringFromDataSync(data as SyncDataType, loader, options);\n }\n\n // Blobs and files are FileReader compatible\n if (isBlob(data)) {\n data = await makeResponse(data);\n }\n\n if (isResponse(data)) {\n await checkResponse(data);\n return loader.binary ? await data.arrayBuffer() : await data.text();\n }\n\n if (isReadableStream(data)) {\n // @ts-expect-error TS2559 options type\n data = makeIterator(data as ReadableStream, options);\n }\n\n if (isIterable(data) || isAsyncIterable(data)) {\n // Assume arrayBuffer iterator - attempt to concatenate\n return concatenateArrayBuffersAsync(data as AsyncIterable);\n }\n\n throw new Error(ERR_DATA);\n}\n\n/**\n * Normalizes batchable inputs into async iterables for batch parsing flows.\n * Supports synchronous iterables, async iterables, fetch responses, readable streams, and\n * single binary chunks (including typed array views and `ArrayBufferLike` values).\n */\nexport async function getAsyncIterableFromData(\n data: BatchableDataType,\n options: LoaderOptions\n): Promise<\n AsyncIterable | Iterable\n> {\n if (isPromise(data)) {\n data = await data;\n }\n\n if (isIterator(data)) {\n return data as AsyncIterable;\n }\n\n if (isResponse(data)) {\n // Note Since this function is not async, we currently can't load error message, just status\n await checkResponse(data);\n // TODO - bug in polyfill, body can be a Promise under Node.js\n // eslint-disable-next-line @typescript-eslint/await-thenable\n const body = await data.body;\n if (!body) {\n throw new Error(ERR_DATA);\n }\n return makeIterator(body, options as any);\n }\n\n if (isBlob(data) || isReadableStream(data)) {\n return makeIterator(data as Blob | ReadableStream, options as any);\n }\n\n if (isAsyncIterable(data)) {\n return data as AsyncIterable;\n }\n\n if (isIterable(data)) {\n return data as Iterable;\n }\n\n // @ts-expect-error TODO - fix type mess\n return getIterableFromData(data);\n}\n\n/**\n * Returns a readable stream for streaming loader inputs when available.\n */\nexport async function getReadableStream(data: BatchableDataType): Promise {\n if (isReadableStream(data)) {\n return data as ReadableStream;\n }\n if (isResponse(data)) {\n // @ts-ignore\n if (!data.body) {\n throw new Error(ERR_DATA);\n }\n return data.body;\n }\n const response = await makeResponse(data);\n // @ts-ignore\n if (!response.body) {\n throw new Error(ERR_DATA);\n }\n return response.body;\n}\n\n// HELPERS\n\nfunction getIterableFromData(data: string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView) {\n // generate an iterator that emits a single chunk\n if (ArrayBuffer.isView(data)) {\n return (function* oneChunk() {\n yield toArrayBuffer(data);\n })();\n }\n\n if (isArrayBufferLike(data)) {\n return (function* oneChunk() {\n yield toArrayBuffer(data);\n })();\n }\n\n if (isIterator(data)) {\n return data;\n }\n\n if (isIterable(data)) {\n return data[Symbol.iterator]();\n }\n\n throw new Error(ERR_DATA);\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {LoaderContext, LoaderOptions, FetchLike} from '@loaders.gl/loader-utils';\nimport {isObject} from '@loaders.gl/loader-utils';\nimport {fetchFile} from '../fetch/fetch-file';\nimport {getGlobalLoaderOptions} from './option-utils';\n\n/**\n * Gets the current fetch function from options and context\n * @param options\n * @param context\n */\nexport function getFetchFunction(\n options?: LoaderOptions,\n context?: Omit & Partial>\n): FetchLike {\n const globalOptions = getGlobalLoaderOptions();\n\n const loaderOptions = options || globalOptions;\n const fetchOption = loaderOptions.fetch ?? loaderOptions.core?.fetch;\n\n // options.fetch can be a function\n if (typeof fetchOption === 'function') {\n return fetchOption;\n }\n\n // options.fetch can be an options object\n if (isObject(fetchOption)) {\n return (url) => fetchFile(url, fetchOption as RequestInit);\n }\n\n // else refer to context (from parent loader) if available\n if (context?.fetch) {\n return context?.fetch;\n }\n\n // else return the default fetch function\n return fetchFile;\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Loader, LoaderContext, StrictLoaderOptions} from '@loaders.gl/loader-utils';\nimport {getFetchFunction} from './get-fetch-function';\nimport {extractQueryString, stripQueryString} from '../utils/url-utils';\nimport {path} from '@loaders.gl/loader-utils';\n\n/** Properties for creating an updated context */\ntype LoaderContextProps = Omit & Partial>;\n\n/**\n * \"sub\" loaders invoked by other loaders get a \"context\" injected on `this`\n * The context will inject core methods like `parse` and contain information\n * about loaders and options passed in to the top-level `parse` call.\n *\n * @param context\n * @param options\n * @param previousContext\n */\nexport function getLoaderContext(\n context: LoaderContextProps,\n options: StrictLoaderOptions,\n parentContext: LoaderContext | null\n): LoaderContext {\n // For recursive calls, we already have a context\n // TODO - add any additional loaders to context?\n if (parentContext) {\n return parentContext;\n }\n\n const newContext: LoaderContext = {\n fetch: getFetchFunction(options, context),\n ...context\n };\n\n // Parse URLs so that subloaders can easily generate correct strings\n if (newContext.url) {\n const baseUrl = stripQueryString(newContext.url);\n newContext.baseUrl = baseUrl;\n newContext.queryString = extractQueryString(newContext.url);\n newContext.filename = path.filename(baseUrl);\n newContext.baseUrl = path.dirname(baseUrl);\n }\n\n // Recursive loading does not use single loader\n if (!Array.isArray(newContext.loaders)) {\n newContext.loaders = null;\n }\n\n return newContext;\n}\n\n// eslint-disable-next-line complexity\nexport function getLoadersFromContext(\n loaders: Loader[] | Loader | undefined,\n context?: LoaderContext\n): Loader | Loader[] | undefined {\n // A single loader (non-array) indicates no selection desired. Force select.\n if (loaders && !Array.isArray(loaders)) {\n return loaders;\n }\n\n // Create a merged list\n let candidateLoaders;\n if (loaders) {\n candidateLoaders = Array.isArray(loaders) ? loaders : [loaders];\n }\n if (context && context.loaders) {\n const contextLoaders = Array.isArray(context.loaders) ? context.loaders : [context.loaders];\n candidateLoaders = candidateLoaders ? [...candidateLoaders, ...contextLoaders] : contextLoaders;\n }\n // If no loaders, return null to look in globally registered loaders\n return candidateLoaders && candidateLoaders.length ? candidateLoaders : undefined;\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {\n Loader,\n LoaderContext,\n LoaderOptions,\n DataType,\n LoaderWithParser,\n LoaderOptionsType,\n LoaderReturnType,\n LoaderArrayOptionsType,\n LoaderArrayReturnType,\n StrictLoaderOptions\n} from '@loaders.gl/loader-utils';\nimport {\n parseWithWorker,\n canParseWithWorker,\n mergeOptions,\n isResponse\n} from '@loaders.gl/loader-utils';\nimport {assert, validateWorkerVersion} from '@loaders.gl/worker-utils';\nimport {isLoaderObject} from '../loader-utils/normalize-loader';\nimport {normalizeOptions} from '../loader-utils/option-utils';\nimport {getArrayBufferOrStringFromData} from '../loader-utils/get-data';\nimport {getLoaderContext, getLoadersFromContext} from '../loader-utils/loader-context';\nimport {getResourceUrl} from '../utils/resource-utils';\nimport {selectLoader} from './select-loader';\n\n// type LoaderArrayType = T extends (infer Loader)[] ? LoaderOptionsType : T\n\n/**\n * Parses `data` asynchronously using the supplied loader\n */\nexport async function parse<\n LoaderT extends Loader,\n OptionsT extends LoaderOptions = LoaderOptionsType\n>(\n data: DataType | Promise,\n loader: LoaderT,\n options?: OptionsT,\n context?: LoaderContext\n): Promise>;\n\n/**\n * Parses `data` asynchronously by matching one of the supplied loader\n */\nexport async function parse<\n LoaderArrayT extends Loader[],\n OptionsT extends LoaderOptions = LoaderArrayOptionsType\n>(\n data: DataType | Promise,\n loaders: LoaderArrayT,\n options?: OptionsT,\n context?: LoaderContext\n): Promise>;\n\n/**\n * Parses data asynchronously by matching a pre-registered loader\n * @deprecated Loader registration is deprecated, use parse(data, loaders, options) instead\n */\nexport async function parse(\n data: DataType | Promise,\n options?: LoaderOptions\n): Promise;\n\n/**\n * Parses `data` using a specified loader\n * @param data\n * @param loaders\n * @param options\n * @param context\n */\n// implementation signature\nexport async function parse(\n data: DataType | Promise,\n loaders?: Loader | Loader[] | LoaderOptions,\n options?: LoaderOptions,\n context?: LoaderContext\n): Promise {\n // Signature: parse(data, options, context | url)\n // Uses registered loaders\n if (loaders && !Array.isArray(loaders) && !isLoaderObject(loaders)) {\n context = undefined; // context not supported in short signature\n options = loaders as LoaderOptions;\n loaders = undefined;\n }\n\n data = await data; // Resolve any promise\n options = options || ({} as LoaderOptions); // Could be invalid...\n\n // Extract a url for auto detection\n const url = getResourceUrl(data);\n\n // Chooses a loader (and normalizes it)\n // Also use any loaders in the context, new loaders take priority\n const typedLoaders = loaders as Loader | Loader[] | undefined;\n const candidateLoaders = getLoadersFromContext(typedLoaders, context);\n // todo hacky type cast\n const loader = await selectLoader(data as ArrayBuffer, candidateLoaders, options);\n // Note: if no loader was found, if so just return null\n if (!loader) {\n return null;\n }\n\n // Normalize options\n // @ts-expect-error candidateLoaders\n const strictOptions = normalizeOptions(options, loader, candidateLoaders, url); // Could be invalid...\n\n // Get a context (if already present, will be unchanged)\n context = getLoaderContext(\n // @ts-expect-error\n {url, _parse: parse, loaders: candidateLoaders},\n strictOptions,\n context || null\n );\n\n return await parseWithLoader(loader, data, strictOptions, context);\n}\n\n// TODO: support progress and abort\n// TODO - should accept loader.parseAsyncIterator and concatenate.\nasync function parseWithLoader(\n loader: Loader,\n data,\n options: StrictLoaderOptions,\n context: LoaderContext\n): Promise {\n validateWorkerVersion(loader);\n\n options = mergeOptions(loader.options, options);\n\n if (isResponse(data)) {\n // Serialize to support passing the response to web worker\n const {ok, redirected, status, statusText, type, url} = data;\n const headers = Object.fromEntries(data.headers.entries());\n // @ts-expect-error TODO - fix this\n context.response = {headers, ok, redirected, status, statusText, type, url};\n }\n\n data = await getArrayBufferOrStringFromData(data, loader, options);\n\n const loaderWithParser = loader as LoaderWithParser;\n\n // First check for synchronous text parser, wrap results in promises\n if (loaderWithParser.parseTextSync && typeof data === 'string') {\n return loaderWithParser.parseTextSync(data, options, context);\n }\n\n // If we have a workerUrl and the loader can parse the given options efficiently in a worker\n if (canParseWithWorker(loader, options)) {\n return await parseWithWorker(loader, data, options, context, parse);\n }\n\n // Check for asynchronous parser\n if (loaderWithParser.parseText && typeof data === 'string') {\n return await loaderWithParser.parseText(data, options, context);\n }\n\n if (loaderWithParser.parse) {\n return await loaderWithParser.parse(data, options, context);\n }\n\n // This should not happen, all sync loaders should also offer `parse` function\n assert(!loaderWithParser.parseSync);\n\n // TBD - If asynchronous parser not available, return null\n throw new Error(`${loader.id} loader - no parser found and worker is disabled`);\n}\n","// math.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {TypedArray, NumericArray, NumberArray} from './array-types';\n\n/**\n * Check is an array is a typed array\n * @param value value to be tested\n * @returns input with type narrowed to TypedArray, or null\n */\nexport function isTypedArray(value: unknown): value is TypedArray {\n return ArrayBuffer.isView(value) && !(value instanceof DataView);\n}\n\n/**\n * Check is an array is an array of numbers)\n * @param value value to be tested\n * @returns input with type narrowed to NumberArray, or null\n */\nexport function isNumberArray(value: unknown): value is NumberArray {\n if (Array.isArray(value)) {\n return value.length === 0 || typeof value[0] === 'number';\n }\n return false;\n}\n\n/**\n * Check is an array is a numeric array (typed array or array of numbers)\n * @param value value to be tested\n * @returns input with type narrowed to NumericArray, or null\n */\nexport function isNumericArray(value: unknown): value is NumericArray {\n return isTypedArray(value) || isNumberArray(value);\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {\n DataType,\n Loader,\n LoaderContext,\n LoaderOptions,\n LoaderOptionsType,\n LoaderReturnType,\n LoaderArrayOptionsType,\n LoaderArrayReturnType\n} from '@loaders.gl/loader-utils';\nimport {isBlob} from '@loaders.gl/loader-utils';\nimport {isLoaderObject} from '../loader-utils/normalize-loader';\nimport {getFetchFunction} from '../loader-utils/get-fetch-function';\nimport {normalizeLoaderOptions} from '../loader-utils/option-utils';\n\nimport {parse} from './parse';\n\n/**\n * Parses `data` using a specified loader\n * Note: Load does duplicate a lot of parse.\n * it can also call fetchFile on string urls, which `parse` won't do.\n * @param data\n * @param loaders\n * @param options\n * @param context\n */\n\nexport async function load<\n LoaderT extends Loader,\n OptionsT extends LoaderOptions = LoaderOptionsType\n>(\n url: string | DataType,\n loader: LoaderT,\n options?: OptionsT,\n context?: LoaderContext\n): Promise>;\n\nexport async function load<\n LoaderArrayT extends Loader[],\n OptionsT extends LoaderOptions = LoaderArrayOptionsType\n>(\n url: string | DataType,\n loaders: LoaderArrayT,\n options?: OptionsT,\n context?: LoaderContext\n): Promise>;\n\n/**\n * Loads data asynchronously by matching a pre-registered loader\n * @deprecated Loader registration is deprecated, use load(data, loaders, options) instead\n */\nexport async function load(\n url: string | DataType,\n loaders?: LoaderOptions,\n context?: LoaderContext\n): Promise;\n\n// export async function load(url: string | DataType, loaders: LoaderOptions): Promise;\n\n// implementation signature\nexport async function load(\n url: string | DataType,\n loaders?: Loader[] | LoaderOptions,\n options?: LoaderOptions | LoaderContext,\n context?: LoaderContext\n): Promise {\n let resolvedLoaders: Loader | Loader[];\n let resolvedOptions: LoaderOptions | undefined;\n\n // Signature: load(url, options)\n if (!Array.isArray(loaders) && !isLoaderObject(loaders)) {\n resolvedLoaders = [];\n resolvedOptions = loaders as LoaderOptions;\n context = undefined; // context not supported in short signature\n } else {\n resolvedLoaders = loaders as Loader | Loader[];\n resolvedOptions = options as LoaderOptions;\n }\n\n // Select fetch function\n const fetch = getFetchFunction(resolvedOptions);\n\n // at this point, `url` could be already loaded binary data\n let data = url;\n // url is a string, fetch the url\n if (typeof url === 'string') {\n data = await fetch(url);\n // URL is Blob or File, fetchFile handles it (alt: we could generate ObjectURL here)\n }\n\n if (isBlob(url)) {\n // The fetch response object will contain blob.name\n // @ts-expect-error TODO - This may not work for overridden fetch functions\n data = await fetch(url);\n }\n\n if (typeof url === 'string') {\n const normalizedOptions = normalizeLoaderOptions(resolvedOptions || {});\n if (!normalizedOptions.core?.baseUrl) {\n resolvedOptions = {\n ...resolvedOptions,\n core: {\n ...resolvedOptions?.core,\n baseUrl: url\n }\n };\n }\n }\n\n // Data is loaded (at least we have a `Response` object) so time to hand over to `parse`\n // return await parse(data, loaders as Loader[], options);\n return Array.isArray(resolvedLoaders)\n ? await parse(data, resolvedLoaders, resolvedOptions) // loader array overload\n : await parse(data, resolvedLoaders, resolvedOptions); // single loader overload\n}\n","// Version constant cannot be imported, it needs to correspond to the build version of **this** module.\n// __VERSION__ is injected by babel-plugin-version-inline\n// @ts-ignore TS2304: Cannot find name '__VERSION__'.\nexport const VERSION = typeof __VERSION__ !== 'undefined' ? __VERSION__ : 'latest';\n","import {isBrowser} from '@loaders.gl/loader-utils';\nimport type {ImageTypeEnum} from '../../types';\n\n// @ts-ignore TS2339: Property does not exist on type\nconst parseImageNode = globalThis.loaders?.parseImageNode;\n\nconst IMAGE_SUPPORTED = typeof Image !== 'undefined'; // NOTE: \"false\" positives if jsdom is installed\nconst IMAGE_BITMAP_SUPPORTED = typeof ImageBitmap !== 'undefined';\nconst NODE_IMAGE_SUPPORTED = Boolean(parseImageNode);\nconst DATA_SUPPORTED = isBrowser ? true : NODE_IMAGE_SUPPORTED;\n\n/**\n * Checks if a loaders.gl image type is supported\n * @param type image type string\n */\nexport function isImageTypeSupported(type: string): boolean {\n switch (type) {\n case 'auto':\n // Should only ever be false in Node.js, if polyfills have not been installed...\n return IMAGE_BITMAP_SUPPORTED || IMAGE_SUPPORTED || DATA_SUPPORTED;\n\n case 'imagebitmap':\n return IMAGE_BITMAP_SUPPORTED;\n case 'image':\n return IMAGE_SUPPORTED;\n case 'data':\n return DATA_SUPPORTED;\n\n default:\n throw new Error(`@loaders.gl/images: image ${type} not supported in this environment`);\n }\n}\n\n/**\n * Returns the \"most performant\" supported image type on this platform\n * @returns image type string\n */\nexport function getDefaultImageType(): ImageTypeEnum {\n if (IMAGE_BITMAP_SUPPORTED) {\n return 'imagebitmap';\n }\n if (IMAGE_SUPPORTED) {\n return 'image';\n }\n if (DATA_SUPPORTED) {\n return 'data';\n }\n\n // This should only happen in Node.js\n throw new Error('Install \\'@loaders.gl/polyfills\\' to parse images under Node.js');\n}\n","import type {ImageType, ImageTypeEnum, ImageDataType} from '../../types';\n\nexport function isImage(image: ImageType): boolean {\n return Boolean(getImageTypeOrNull(image));\n}\n\nexport function deleteImage(image: ImageType): void {\n switch (getImageType(image)) {\n case 'imagebitmap':\n (image as ImageBitmap).close();\n break;\n default:\n // Nothing to do for images and image data objects\n }\n}\n\nexport function getImageType(image: ImageType): ImageTypeEnum {\n const format = getImageTypeOrNull(image);\n if (!format) {\n throw new Error('Not an image');\n }\n return format;\n}\n\nexport function getImageSize(image: ImageType): {width: number; height: number} {\n return getImageData(image);\n}\n\nexport function getImageData(image: ImageType): ImageDataType | ImageData {\n switch (getImageType(image)) {\n case 'data':\n return image as unknown as ImageData;\n\n case 'image':\n case 'imagebitmap':\n // Extract the image data from the image via a canvas\n const canvas = document.createElement('canvas');\n // TODO - reuse the canvas?\n const context = canvas.getContext('2d');\n if (!context) {\n throw new Error('getImageData');\n }\n // @ts-ignore\n canvas.width = image.width;\n // @ts-ignore\n canvas.height = image.height;\n // @ts-ignore\n context.drawImage(image, 0, 0);\n // @ts-ignore\n return context.getImageData(0, 0, image.width, image.height);\n\n default:\n throw new Error('getImageData');\n }\n}\n\n// PRIVATE\n\n// eslint-disable-next-line complexity\nfunction getImageTypeOrNull(image) {\n if (typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {\n return 'imagebitmap';\n }\n if (typeof Image !== 'undefined' && image instanceof Image) {\n return 'image';\n }\n if (image && typeof image === 'object' && image.data && image.width && image.height) {\n return 'data';\n }\n return null;\n}\n","// SVG parsing has limitations, e.g:\n// https://bugs.chromium.org/p/chromium/issues/detail?id=606319\n\nconst SVG_DATA_URL_PATTERN = /^data:image\\/svg\\+xml/;\nconst SVG_URL_PATTERN = /\\.svg((\\?|#).*)?$/;\n\nexport function isSVG(url) {\n return url && (SVG_DATA_URL_PATTERN.test(url) || SVG_URL_PATTERN.test(url));\n}\n\nexport function getBlobOrSVGDataUrl(arrayBuffer: ArrayBuffer, url?: string): Blob | string {\n if (isSVG(url)) {\n // Prepare a properly tagged data URL, and load using normal mechanism\n const textDecoder = new TextDecoder();\n let xmlText = textDecoder.decode(arrayBuffer);\n // TODO Escape in browser to support e.g. Chinese characters\n try {\n if (typeof unescape === 'function' && typeof encodeURIComponent === 'function') {\n xmlText = unescape(encodeURIComponent(xmlText));\n }\n } catch (error) {\n throw new Error((error as Error).message);\n }\n // base64 encoding is safer. utf-8 fails in some browsers\n const src = `data:image/svg+xml;base64,${btoa(xmlText)}`;\n return src;\n }\n return getBlob(arrayBuffer, url);\n}\n\nexport function getBlob(arrayBuffer: ArrayBuffer, url?: string): Blob {\n if (isSVG(url)) {\n // https://bugs.chromium.org/p/chromium/issues/detail?id=606319\n // return new Blob([new Uint8Array(arrayBuffer)], {type: 'image/svg+xml'});\n throw new Error('SVG cannot be parsed directly to imagebitmap');\n }\n // TODO - how to determine mime type? Param? Sniff here?\n return new Blob([new Uint8Array(arrayBuffer)]); // MIME type not needed?\n}\n","import type {ImageLoaderOptions} from '../../image-loader';\nimport {getBlobOrSVGDataUrl} from './svg-utils';\n\n// Parses html image from array buffer\nexport async function parseToImage(\n arrayBuffer: ArrayBuffer,\n options: ImageLoaderOptions,\n url?: string\n): Promise {\n // Note: image parsing requires conversion to Blob (for createObjectURL).\n // Potentially inefficient for not using `response.blob()` (and for File / Blob inputs)...\n // But presumably not worth adding 'blob' flag to loader objects?\n\n const blobOrDataUrl = getBlobOrSVGDataUrl(arrayBuffer, url);\n const URL = self.URL || self.webkitURL;\n const objectUrl = typeof blobOrDataUrl !== 'string' && URL.createObjectURL(blobOrDataUrl);\n try {\n return await loadToImage(objectUrl || blobOrDataUrl, options);\n } finally {\n if (objectUrl) {\n URL.revokeObjectURL(objectUrl);\n }\n }\n}\n\nexport async function loadToImage(url, options): Promise {\n const image = new Image();\n image.src = url;\n\n // The `image.onload()` callback does not guarantee that the image has been decoded\n // so a main thread \"freeze\" can be incurred when using the image for the first time.\n // `Image.decode()` returns a promise that completes when image is decoded.\n\n // https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/decode\n // Note: When calling `img.decode()`, we do not need to wait for `img.onload()`\n // Note: `HTMLImageElement.decode()` is not available in Edge and IE11\n if (options.image && options.image.decode && image.decode) {\n await image.decode();\n return image;\n }\n\n // Create a promise that tracks onload/onerror callbacks\n return await new Promise((resolve, reject) => {\n try {\n image.onload = () => resolve(image);\n image.onerror = (error) => {\n const message = error instanceof Error ? error.message : 'error';\n reject(new Error(message));\n };\n } catch (error) {\n reject(error);\n }\n });\n}\n","import type {ImageLoaderOptions} from '../../image-loader';\nimport {isSVG, getBlob} from './svg-utils';\nimport {parseToImage} from './parse-to-image';\n\nlet imagebitmapOptionsSupported = true;\n\n/**\n * Asynchronously parses an array buffer into an ImageBitmap - this contains the decoded data\n * ImageBitmaps are supported on worker threads, but not supported on Edge, IE11 and Safari\n * https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap#Browser_compatibility\n *\n * TODO - createImageBitmap supports source rect (5 param overload), pass through?\n */\nexport async function parseToImageBitmap(\n arrayBuffer: ArrayBuffer,\n options: ImageLoaderOptions,\n url?: string\n): Promise {\n let blob;\n\n // Cannot parse SVG directly to ImageBitmap, parse to Image first\n if (isSVG(url)) {\n // Note: this only works on main thread\n const image = await parseToImage(arrayBuffer, options, url);\n blob = image;\n } else {\n // Create blob from the array buffer\n blob = getBlob(arrayBuffer, url);\n }\n\n const imagebitmapOptions = (options && options.imagebitmap) as\n | ImageBitmapOptions\n | null\n | undefined;\n\n return await safeCreateImageBitmap(blob, imagebitmapOptions);\n}\n\n/**\n * Safely creates an imageBitmap with options\n * *\n * Firefox crashes if imagebitmapOptions is supplied\n * Avoid supplying if not provided or supported, remember if not supported\n */\nasync function safeCreateImageBitmap(\n blob: Blob,\n imagebitmapOptions: ImageBitmapOptions | null = null\n): Promise {\n if (isEmptyObject(imagebitmapOptions) || !imagebitmapOptionsSupported) {\n imagebitmapOptions = null;\n }\n\n if (imagebitmapOptions) {\n try {\n // @ts-ignore Options\n return await createImageBitmap(blob, imagebitmapOptions);\n } catch (error) {\n console.warn(error); // eslint-disable-line\n imagebitmapOptionsSupported = false;\n }\n }\n\n return await createImageBitmap(blob);\n}\n\nfunction isEmptyObject(object: object | null | undefined) {\n if (!object) {\n return true;\n }\n\n for (const key in object) {\n if (Object.prototype.hasOwnProperty.call(object, key)) {\n return false;\n }\n }\n\n return true;\n}\n","// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n// code adapted from https://github.com/sindresorhus/file-type under MIT license\n\n/**\n * Box is a container format that can contain a variety of media related files,\n * so we want to return information about which type of file is actually contained inside\n */\nexport type BoxFileType = {extension: string; mimeType: string};\n\n/**\n * Tests if a buffer is in ISO base media file format (ISOBMFF) @see https://en.wikipedia.org/wiki/ISO_base_media_file_format\n * (ISOBMFF is a media container standard based on the Apple QuickTime container format)\n */\nexport function getISOBMFFMediaType(buffer: Uint8Array): BoxFileType | null {\n // Almost all ISO base media files start with `ftyp` box. (It's not required to be first, but it's recommended to be.)\n if (!checkString(buffer, 'ftyp', 4)) {\n return null;\n }\n\n // Extra check: test for 8859-1 printable characters (for simplicity, it's a mask which also catches one non-printable character).\n if ((buffer[8] & 0x60) === 0x00) {\n return null;\n }\n\n // `ftyp` box must contain a brand major identifier, which must consist of ISO 8859-1 printable characters.\n return decodeMajorBrand(buffer);\n}\n\n/**\n * brands explained @see https://github.com/strukturag/libheif/issues/83\n * code adapted from @see https://github.com/sindresorhus/file-type/blob/main/core.js#L489-L492\n */\nexport function decodeMajorBrand(buffer: Uint8Array): BoxFileType | null {\n const brandMajor = getUTF8String(buffer, 8, 12).replace('\\0', ' ').trim();\n\n switch (brandMajor) {\n case 'avif':\n case 'avis':\n return {extension: 'avif', mimeType: 'image/avif'};\n default:\n return null;\n }\n // We don't need these now, but they are easy to add\n // case 'mif1':\n // return {extension: 'heic', mimeType: 'image/heif'};\n // case 'msf1':\n // return {extension: 'heic', mimeType: 'image/heif-sequence'};\n // case 'heic':\n // case 'heix':\n // return {extension: 'heic', mimeType: 'image/heic'};\n // case 'hevc':\n // case 'hevx':\n // return {extension: 'heic', mimeType: 'image/heic-sequence'};\n // case 'qt':\n // return {ext: 'mov', mime: 'video/quicktime'};\n // case 'M4V':\n // case 'M4VH':\n // case 'M4VP':\n // return {ext: 'm4v', mime: 'video/x-m4v'};\n // case 'M4P':\n // return {ext: 'm4p', mime: 'video/mp4'};\n // case 'M4B':\n // return {ext: 'm4b', mime: 'audio/mp4'};\n // case 'M4A':\n // return {ext: 'm4a', mime: 'audio/x-m4a'};\n // case 'F4V':\n // return {ext: 'f4v', mime: 'video/mp4'};\n // case 'F4P':\n // return {ext: 'f4p', mime: 'video/mp4'};\n // case 'F4A':\n // return {ext: 'f4a', mime: 'audio/mp4'};\n // case 'F4B':\n // return {ext: 'f4b', mime: 'audio/mp4'};\n // case 'crx':\n // return {ext: 'cr3', mime: 'image/x-canon-cr3'};\n // default:\n // if (brandMajor.startsWith('3g')) {\n // if (brandMajor.startsWith('3g2')) {\n // return {ext: '3g2', mime: 'video/3gpp2'};\n // }\n // return {ext: '3gp', mime: 'video/3gpp'};\n // }\n // return {ext: 'mp4', mime: 'video/mp4'};\n}\n\n/** Interpret a chunk of bytes as a UTF8 string */\nfunction getUTF8String(array: Uint8Array, start: number, end: number): string {\n return String.fromCharCode(...array.slice(start, end));\n}\n\nfunction stringToBytes(string: string): number[] {\n return [...string].map((character) => character.charCodeAt(0));\n}\n\nfunction checkString(buffer: ArrayLike, header: string, offset: number = 0): boolean {\n const headerBytes = stringToBytes(header);\n\n for (let i = 0; i < headerBytes.length; ++i) {\n if (headerBytes[i] !== buffer[i + offset]) {\n return false;\n }\n }\n\n return true;\n}\n","// Attributions\n// * Based on binary-gltf-utils under MIT license: Copyright (c) 2016-17 Karl Cheng\n\nimport {getISOBMFFMediaType} from './parse-isobmff-binary';\n\n/** MIME type, width and height extracted from binary compressed image data */\nexport type BinaryImageMetadata = {\n mimeType: string;\n width: number;\n height: number;\n};\n\nconst BIG_ENDIAN = false;\nconst LITTLE_ENDIAN = true;\n\n/**\n * Extracts `{mimeType, width and height}` from a memory buffer containing a known image format\n * Currently supports `image/png`, `image/jpeg`, `image/bmp` and `image/gif`.\n * @param binaryData: DataView | ArrayBuffer image file memory to parse\n * @returns metadata or null if memory is not a valid image file format layout.\n */\nexport function getBinaryImageMetadata(\n binaryData: DataView | ArrayBuffer\n): BinaryImageMetadata | null {\n const dataView = toDataView(binaryData);\n return (\n getPngMetadata(dataView) ||\n getJpegMetadata(dataView) ||\n getGifMetadata(dataView) ||\n getBmpMetadata(dataView) ||\n getISOBMFFMetadata(dataView)\n );\n}\n\n// ISOBMFF\n\nfunction getISOBMFFMetadata(binaryData: DataView | ArrayBuffer): BinaryImageMetadata | null {\n const buffer = new Uint8Array(binaryData instanceof DataView ? binaryData.buffer : binaryData);\n const mediaType = getISOBMFFMediaType(buffer);\n if (!mediaType) {\n return null;\n }\n return {\n mimeType: mediaType.mimeType,\n // TODO - decode width and height\n width: 0,\n height: 0\n };\n}\n\n// PNG\n\nfunction getPngMetadata(binaryData: DataView | ArrayBuffer): BinaryImageMetadata | null {\n const dataView = toDataView(binaryData);\n // Check file contains the first 4 bytes of the PNG signature.\n const isPng = dataView.byteLength >= 24 && dataView.getUint32(0, BIG_ENDIAN) === 0x89504e47;\n if (!isPng) {\n return null;\n }\n\n // Extract size from a binary PNG file\n return {\n mimeType: 'image/png',\n width: dataView.getUint32(16, BIG_ENDIAN),\n height: dataView.getUint32(20, BIG_ENDIAN)\n };\n}\n\n// GIF\n\n// Extract size from a binary GIF file\n// TODO: GIF is not this simple\nfunction getGifMetadata(binaryData: DataView | ArrayBuffer): BinaryImageMetadata | null {\n const dataView = toDataView(binaryData);\n // Check first 4 bytes of the GIF signature (\"GIF8\").\n const isGif = dataView.byteLength >= 10 && dataView.getUint32(0, BIG_ENDIAN) === 0x47494638;\n if (!isGif) {\n return null;\n }\n\n // GIF is little endian.\n return {\n mimeType: 'image/gif',\n width: dataView.getUint16(6, LITTLE_ENDIAN),\n height: dataView.getUint16(8, LITTLE_ENDIAN)\n };\n}\n\n// BMP\n\n// TODO: BMP is not this simple\nexport function getBmpMetadata(binaryData: DataView | ArrayBuffer): BinaryImageMetadata | null {\n const dataView = toDataView(binaryData);\n // Check magic number is valid (first 2 characters should be \"BM\").\n // The mandatory bitmap file header is 14 bytes long.\n const isBmp =\n dataView.byteLength >= 14 &&\n dataView.getUint16(0, BIG_ENDIAN) === 0x424d &&\n dataView.getUint32(2, LITTLE_ENDIAN) === dataView.byteLength;\n\n if (!isBmp) {\n return null;\n }\n\n // BMP is little endian.\n return {\n mimeType: 'image/bmp',\n width: dataView.getUint32(18, LITTLE_ENDIAN),\n height: dataView.getUint32(22, LITTLE_ENDIAN)\n };\n}\n\n// JPEG\n\n// Extract width and height from a binary JPEG file\nfunction getJpegMetadata(binaryData: DataView | ArrayBuffer): BinaryImageMetadata | null {\n const dataView = toDataView(binaryData);\n // Check file contains the JPEG \"start of image\" (SOI) marker\n // followed by another marker.\n const isJpeg =\n dataView.byteLength >= 3 &&\n dataView.getUint16(0, BIG_ENDIAN) === 0xffd8 &&\n dataView.getUint8(2) === 0xff;\n\n if (!isJpeg) {\n return null;\n }\n\n const {tableMarkers, sofMarkers} = getJpegMarkers();\n\n // Exclude the two byte SOI marker.\n let i = 2;\n while (i + 9 < dataView.byteLength) {\n const marker = dataView.getUint16(i, BIG_ENDIAN);\n\n // The frame that contains the width and height of the JPEG image.\n if (sofMarkers.has(marker)) {\n return {\n mimeType: 'image/jpeg',\n height: dataView.getUint16(i + 5, BIG_ENDIAN), // Number of lines\n width: dataView.getUint16(i + 7, BIG_ENDIAN) // Number of pixels per line\n };\n }\n\n // Miscellaneous tables/data preceding the frame header.\n if (!tableMarkers.has(marker)) {\n return null;\n }\n\n // Length includes size of length parameter but not the two byte header.\n i += 2;\n i += dataView.getUint16(i, BIG_ENDIAN);\n }\n\n return null;\n}\n\nfunction getJpegMarkers() {\n // Tables/misc header markers.\n // DQT, DHT, DAC, DRI, COM, APP_n\n const tableMarkers = new Set([0xffdb, 0xffc4, 0xffcc, 0xffdd, 0xfffe]);\n for (let i = 0xffe0; i < 0xfff0; ++i) {\n tableMarkers.add(i);\n }\n\n // SOF markers and DHP marker.\n // These markers are after tables/misc data.\n const sofMarkers = new Set([\n 0xffc0, 0xffc1, 0xffc2, 0xffc3, 0xffc5, 0xffc6, 0xffc7, 0xffc9, 0xffca, 0xffcb, 0xffcd, 0xffce,\n 0xffcf, 0xffde\n ]);\n\n return {tableMarkers, sofMarkers};\n}\n\n// TODO - move into image module?\nfunction toDataView(data) {\n if (data instanceof DataView) {\n return data;\n }\n if (ArrayBuffer.isView(data)) {\n return new DataView(data.buffer);\n }\n\n // TODO: make these functions work for Node.js buffers?\n // if (bufferToArrayBuffer) {\n // data = bufferToArrayBuffer(data);\n // }\n\n // Careful - Node Buffers will look like ArrayBuffers (keep after isBuffer)\n if (data instanceof ArrayBuffer) {\n return new DataView(data);\n }\n throw new Error('toDataView');\n}\n","import type {ImageLoaderOptions} from '../../image-loader';\nimport type {ImageDataType} from '../../types';\nimport {assert} from '@loaders.gl/loader-utils';\nimport {getBinaryImageMetadata} from '../category-api/binary-image-api';\n\n// Note: These types should be consistent with loaders.gl/polyfills\n\ntype NDArray = {\n shape: number[];\n data: Uint8Array;\n width: number;\n height: number;\n components: number;\n layers: number[];\n};\n\ntype ParseImageNode = (arrayBuffer: ArrayBuffer, mimeType: string) => Promise;\n\n// Use polyfills if installed to parsed image using get-pixels\nexport async function parseToNodeImage(\n arrayBuffer: ArrayBuffer,\n options: ImageLoaderOptions\n): Promise {\n const {mimeType} = getBinaryImageMetadata(arrayBuffer) || {};\n\n // @ts-ignore\n const parseImageNode: ParseImageNode = globalThis.loaders?.parseImageNode;\n assert(parseImageNode); // '@loaders.gl/polyfills not installed'\n\n // @ts-expect-error TODO should we throw error in this case?\n return await parseImageNode(arrayBuffer, mimeType);\n}\n","import type {LoaderContext} from '@loaders.gl/loader-utils';\nimport {assert} from '@loaders.gl/loader-utils';\nimport type {ImageType} from '../../types';\nimport type {ImageLoaderOptions} from '../../image-loader';\nimport {isImageTypeSupported, getDefaultImageType} from '../category-api/image-type';\nimport {getImageData} from '../category-api/parsed-image-api';\nimport {parseToImage} from './parse-to-image';\nimport {parseToImageBitmap} from './parse-to-image-bitmap';\nimport {parseToNodeImage} from './parse-to-node-image';\n\n// Parse to platform defined image type (data on node, ImageBitmap or HTMLImage on browser)\n// eslint-disable-next-line complexity\nexport async function parseImage(\n arrayBuffer: ArrayBuffer,\n options?: ImageLoaderOptions,\n context?: LoaderContext\n): Promise {\n options = options || {};\n const imageOptions = options.image || {};\n\n // The user can request a specific output format via `options.image.type`\n const imageType = imageOptions.type || 'auto';\n\n const {url} = context || {};\n\n // Note: For options.image.type === `data`, we may still need to load as `image` or `imagebitmap`\n const loadType = getLoadableImageType(imageType);\n\n let image;\n switch (loadType) {\n case 'imagebitmap':\n image = await parseToImageBitmap(arrayBuffer, options, url);\n break;\n case 'image':\n image = await parseToImage(arrayBuffer, options, url);\n break;\n case 'data':\n // Node.js loads imagedata directly\n image = await parseToNodeImage(arrayBuffer, options);\n break;\n default:\n assert(false);\n }\n\n // Browser: if options.image.type === 'data', we can now extract data from the loaded image\n if (imageType === 'data') {\n image = getImageData(image);\n }\n\n return image;\n}\n\n// Get a loadable image type from image type\nfunction getLoadableImageType(type) {\n switch (type) {\n case 'auto':\n case 'data':\n // Browser: For image data we need still need to load using an image format\n // Node: the default image type is `data`.\n return getDefaultImageType();\n default:\n // Throw an error if not supported\n isImageTypeSupported(type);\n return type;\n }\n}\n","import type {LoaderWithParser, StrictLoaderOptions} from '@loaders.gl/loader-utils';\nimport type {ImageType} from './types';\n// import type { ImageType } from '@loaders.gl/schema';\nimport {VERSION} from './lib/utils/version';\nimport {parseImage} from './lib/parsers/parse-image';\nimport {getBinaryImageMetadata} from './lib/category-api/binary-image-api';\n\nconst EXTENSIONS = ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'ico', 'svg', 'avif'];\nconst MIME_TYPES = [\n 'image/png',\n 'image/jpeg',\n 'image/gif',\n 'image/webp',\n 'image/avif',\n 'image/bmp',\n 'image/vnd.microsoft.icon',\n 'image/svg+xml'\n];\n\nexport type ImageLoaderOptions = StrictLoaderOptions & {\n image?: {\n type?: 'auto' | 'data' | 'imagebitmap' | 'image';\n decode?: boolean;\n imagebitmap?: ImageBitmapOptions;\n };\n};\n\nconst DEFAULT_IMAGE_LOADER_OPTIONS: ImageLoaderOptions = {\n image: {\n type: 'auto',\n decode: true // if format is HTML\n }\n // imagebitmap: {} - passes (platform dependent) parameters to ImageBitmap constructor\n};\n\n/**\n * Loads a platform-specific image type\n * Note: This type can be used as input data to WebGL texture creation\n */\nexport const ImageLoader = {\n dataType: null as unknown as ImageType,\n batchType: null as never,\n id: 'image',\n module: 'images',\n name: 'Images',\n version: VERSION,\n mimeTypes: MIME_TYPES,\n extensions: EXTENSIONS,\n parse: parseImage,\n // TODO: byteOffset, byteLength;\n tests: [(arrayBuffer) => Boolean(getBinaryImageMetadata(new DataView(arrayBuffer)))],\n options: DEFAULT_IMAGE_LOADER_OPTIONS\n} as const satisfies LoaderWithParser;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Log} from '@probe.gl/log';\n\nconst defaultLogger: Log = new Log({id: 'deck'});\n\nexport default defaultLogger;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport deckLog from '../utils/log';\nimport {getLoggers} from './loggers';\n\n/* debug utility */\n\nlet loggers: Record = {};\n\n// Conditionally load default loggers in development mode\n// eslint-disable-next-line\nif (process.env.NODE_ENV !== 'production') {\n loggers = getLoggers(deckLog);\n}\n\nexport function register(handlers: Record): void {\n loggers = handlers;\n}\n\nexport default function debug(eventType: string, arg1?: any, arg2?: any, arg3?: any): void {\n if (deckLog.level > 0 && loggers[eventType]) {\n // Not using rest parameters to defeat perf hit from array construction\n loggers[eventType].call(null, arg1, arg2, arg3);\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Loader} from '@loaders.gl/loader-utils';\n\nfunction isJSON(text: string): boolean {\n const firstChar = text[0];\n const lastChar = text[text.length - 1];\n return (firstChar === '{' && lastChar === '}') || (firstChar === '[' && lastChar === ']');\n}\n\n// A light weight version instead of @loaders.gl/json (stream processing etc.)\nexport default {\n dataType: null as any,\n batchType: null as never,\n id: 'JSON',\n name: 'JSON',\n module: '',\n version: '',\n options: {},\n extensions: ['json', 'geojson'],\n mimeTypes: ['application/json', 'application/geo+json'],\n testText: isJSON,\n parseTextSync: JSON.parse\n} as Loader;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {registerLoaders} from '@loaders.gl/core';\nimport {ImageLoader} from '@loaders.gl/images';\n\nimport log from '../utils/log';\nimport {register} from '../debug/index';\nimport jsonLoader from '../utils/json-loader';\n\ndeclare global {\n const __VERSION__: string;\n}\n\nfunction checkVersion() {\n // Version detection using typescript plugin.\n // Fallback for tests and SSR since global variable is defined by esbuild.\n const version =\n typeof __VERSION__ !== 'undefined'\n ? __VERSION__\n : globalThis.DECK_VERSION || 'untranspiled source';\n\n // Note: a `deck` object not created by deck.gl may exist in the global scope\n const existingVersion = globalThis.deck && globalThis.deck.VERSION;\n\n if (existingVersion && existingVersion !== version) {\n throw new Error(`deck.gl - multiple versions detected: ${existingVersion} vs ${version}`);\n }\n\n if (!existingVersion) {\n log.log(1, `deck.gl ${version}`)();\n\n globalThis.deck = {\n ...globalThis.deck,\n VERSION: version,\n version,\n log,\n // experimental\n _registerLoggers: register\n };\n\n registerLoaders([\n jsonLoader,\n // @ts-expect-error non-standard Loader format\n [ImageLoader, {imagebitmap: {premultiplyAlpha: 'none'}}]\n ]);\n }\n\n return version;\n}\n\nexport const VERSION = checkVersion();\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// Recommendation is to ignore message but current test suite checks agains the\n// message so keep it for now.\nexport function assert(condition: unknown, message?: string): void {\n if (!condition) {\n const error = new Error(message || 'shadertools: assertion failed.');\n Error.captureStackTrace?.(error, assert);\n throw error;\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {assert} from '../utils/assert';\n\n/**\n * For use by shader module and shader pass writers to describe the types of the\n * properties they expose (properties ultimately map to uniforms).\n */\nexport type PropType =\n | {\n type?: string;\n value?: unknown;\n max?: number;\n min?: number;\n softMax?: number;\n softMin?: number;\n hint?: string;\n /** @deprecated internal uniform */\n private?: boolean;\n }\n | number;\n\n/**\n * Internal property validators generated by processing the prop types ,\n * The `validate()` method can be used to validate the type of properties passed in to\n * shader module or shader pass\n */\nexport type PropValidator = {\n type: string;\n value?: unknown;\n max?: number;\n min?: number;\n private?: boolean;\n validate?(value: unknown, propDef: PropValidator): boolean;\n};\n\n/** Minimal validators for number and array types */\nconst DEFAULT_PROP_VALIDATORS: Record = {\n number: {\n type: 'number',\n validate(value: unknown, propType: PropType) {\n return (\n Number.isFinite(value) &&\n typeof propType === 'object' &&\n (propType.max === undefined || (value as number) <= propType.max) &&\n (propType.min === undefined || (value as number) >= propType.min)\n );\n }\n },\n array: {\n type: 'array',\n validate(value: unknown, propType: PropType) {\n return Array.isArray(value) || ArrayBuffer.isView(value);\n }\n }\n};\n\n/**\n * Parse a list of property types into property definitions that can be used to validate\n * values passed in by applications.\n * @param propTypes\n * @returns\n */\nexport function makePropValidators(\n propTypes: Record\n): Record {\n const propValidators: Record = {};\n for (const [name, propType] of Object.entries(propTypes)) {\n propValidators[name] = makePropValidator(propType);\n }\n return propValidators;\n}\n\n/**\n * Validate a map of user supplied properties against a map of validators\n * Inject default values when user doesn't supply a property\n * @param properties\n * @param propValidators\n * @returns\n */\nexport function getValidatedProperties(\n properties: Record,\n propValidators: Record,\n errorMessage: string\n): Record {\n const validated: Record = {};\n\n for (const [key, propsValidator] of Object.entries(propValidators)) {\n if (properties && key in properties && !propsValidator.private) {\n if (propsValidator.validate) {\n assert(\n propsValidator.validate(properties[key], propsValidator),\n `${errorMessage}: invalid ${key}`\n );\n }\n validated[key] = properties[key];\n } else {\n // property not supplied - use default value\n validated[key] = propsValidator.value;\n }\n }\n\n // TODO - warn for unused properties that don't match a validator?\n\n return validated;\n}\n\n/**\n * Creates a property validator for a prop type. Either contains:\n * - a valid prop type object ({type, ...})\n * - or just a default value, in which case type and name inference is used\n */\nfunction makePropValidator(propType: PropType): PropValidator {\n let type = getTypeOf(propType);\n\n if (type !== 'object') {\n return {value: propType, ...DEFAULT_PROP_VALIDATORS[type], type};\n }\n\n // Special handling for objects\n if (typeof propType === 'object') {\n if (!propType) {\n return {type: 'object', value: null};\n }\n if (propType.type !== undefined) {\n return {...propType, ...DEFAULT_PROP_VALIDATORS[propType.type], type: propType.type};\n }\n // If no type and value this object is likely the value\n if (propType.value === undefined) {\n return {type: 'object', value: propType};\n }\n\n type = getTypeOf(propType.value);\n return {...propType, ...DEFAULT_PROP_VALIDATORS[type], type};\n }\n\n throw new Error('props');\n}\n\n/**\n * \"improved\" version of javascript typeof that can distinguish arrays and null values\n */\nfunction getTypeOf(value: unknown): string {\n if (Array.isArray(value) || ArrayBuffer.isView(value)) {\n return 'array';\n }\n return typeof value;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport const MODULE_INJECTORS_VS = /* glsl */ `\\\n#ifdef MODULE_LOGDEPTH\n logdepth_adjustPosition(gl_Position);\n#endif\n`;\n\nexport const MODULE_INJECTORS_FS = /* glsl */ `\\\n#ifdef MODULE_MATERIAL\n fragColor = material_filterColor(fragColor);\n#endif\n\n#ifdef MODULE_LIGHTING\n fragColor = lighting_filterColor(fragColor);\n#endif\n\n#ifdef MODULE_FOG\n fragColor = fog_filterColor(fragColor);\n#endif\n\n#ifdef MODULE_PICKING\n fragColor = picking_filterHighlightColor(fragColor);\n fragColor = picking_filterPickingColor(fragColor);\n#endif\n\n#ifdef MODULE_LOGDEPTH\n logdepth_setFragDepth();\n#endif\n`;\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {MODULE_INJECTORS_VS, MODULE_INJECTORS_FS} from '../../module-injectors';\nimport {assert} from '../utils/assert';\n\n// TODO - experimental\nconst MODULE_INJECTORS = {\n vertex: MODULE_INJECTORS_VS,\n fragment: MODULE_INJECTORS_FS\n};\n\nconst REGEX_START_OF_MAIN = /void\\s+main\\s*\\([^)]*\\)\\s*\\{\\n?/; // Beginning of main\nconst REGEX_END_OF_MAIN = /}\\n?[^{}]*$/; // End of main, assumes main is last function\nconst fragments: string[] = [];\n\nexport const DECLARATION_INJECT_MARKER = '__LUMA_INJECT_DECLARATIONS__';\n\n/**\n *\n */\nexport type ShaderInjection = {\n injection: string;\n order: number;\n};\n\n/**\n * ShaderInjections, parsed and split per shader\n */\nexport type ShaderInjections = {\n vertex: Record;\n fragment: Record;\n};\n\n/**\n *\n */\nexport function normalizeInjections(\n injections: Record\n): ShaderInjections {\n const result: ShaderInjections = {vertex: {}, fragment: {}};\n\n for (const hook in injections) {\n let injection = injections[hook];\n const stage = getHookStage(hook);\n if (typeof injection === 'string') {\n injection = {\n order: 0,\n injection\n };\n }\n\n result[stage][hook] = injection;\n }\n\n return result;\n}\n\nfunction getHookStage(hook: string): 'vertex' | 'fragment' {\n const type = hook.slice(0, 2);\n switch (type) {\n case 'vs':\n return 'vertex';\n case 'fs':\n return 'fragment';\n default:\n throw new Error(type);\n }\n}\n\n/**\n// A minimal shader injection/templating system.\n// RFC: https://github.com/visgl/luma.gl/blob/7.0-release/dev-docs/RFCs/v6.0/shader-injection-rfc.md\n * @param source \n * @param type \n * @param inject \n * @param injectStandardStubs \n * @returns \n */\n// eslint-disable-next-line complexity\nexport function injectShader(\n source: string,\n stage: 'vertex' | 'fragment',\n inject: Record,\n injectStandardStubs = false\n): string {\n const isVertex = stage === 'vertex';\n\n for (const key in inject) {\n const fragmentData = inject[key];\n fragmentData.sort((a: ShaderInjection, b: ShaderInjection): number => a.order - b.order);\n fragments.length = fragmentData.length;\n for (let i = 0, len = fragmentData.length; i < len; ++i) {\n fragments[i] = fragmentData[i].injection;\n }\n const fragmentString = `${fragments.join('\\n')}\\n`;\n switch (key) {\n // declarations are injected before the main function\n case 'vs:#decl':\n if (isVertex) {\n source = source.replace(DECLARATION_INJECT_MARKER, fragmentString);\n }\n break;\n // inject code at the beginning of the main function\n case 'vs:#main-start':\n if (isVertex) {\n source = source.replace(REGEX_START_OF_MAIN, (match: string) => match + fragmentString);\n }\n break;\n // inject code at the end of main function\n case 'vs:#main-end':\n if (isVertex) {\n source = source.replace(REGEX_END_OF_MAIN, (match: string) => fragmentString + match);\n }\n break;\n // declarations are injected before the main function\n case 'fs:#decl':\n if (!isVertex) {\n source = source.replace(DECLARATION_INJECT_MARKER, fragmentString);\n }\n break;\n // inject code at the beginning of the main function\n case 'fs:#main-start':\n if (!isVertex) {\n source = source.replace(REGEX_START_OF_MAIN, (match: string) => match + fragmentString);\n }\n break;\n // inject code at the end of main function\n case 'fs:#main-end':\n if (!isVertex) {\n source = source.replace(REGEX_END_OF_MAIN, (match: string) => fragmentString + match);\n }\n break;\n\n default:\n // TODO(Tarek): I think this usage should be deprecated.\n\n // inject code after key, leaving key in place\n source = source.replace(key, (match: string) => match + fragmentString);\n }\n }\n\n // Remove if it hasn't already been replaced\n source = source.replace(DECLARATION_INJECT_MARKER, '');\n\n // Finally, if requested, insert an automatic module injector chunk\n if (injectStandardStubs) {\n source = source.replace(/\\}\\s*$/, (match: string) => match + MODULE_INJECTORS[stage]);\n }\n\n return source;\n}\n\n// Takes an array of inject objects and combines them into one\nexport function combineInjects(injects: any[]): Record {\n const result: Record = {};\n assert(Array.isArray(injects) && injects.length > 1);\n injects.forEach(inject => {\n for (const key in inject) {\n result[key] = result[key] ? `${result[key]}\\n${inject[key]}` : inject[key];\n }\n });\n return result;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {UniformFormat} from '../../types';\nimport {\n PropType,\n PropValidator,\n makePropValidators,\n getValidatedProperties\n} from '../filters/prop-types';\nimport type {ShaderModuleUniformValue, UniformTypes, UniformValue} from '../utils/uniform-types';\nimport {ShaderInjection, normalizeInjections} from '../shader-assembly/shader-injections';\n\n// To avoid dependency on core module, do not import `Binding` type.\n// The ShaderModule is not concerned with the type of `Binding`,\n// it is the repsonsibility of `splitUniformsAndBindings` in\n// ShaderInputs to type the result of `getUniforms()`\ntype Binding = unknown; // import type {Binding} from '@luma.gl/core';\n\nexport type UniformInfo = {\n format?: UniformFormat;\n} & PropType;\n\nexport type ShaderModuleBindingLayout = {\n name: string;\n group: number;\n};\n\n// Helper types\ntype BindingKeys = {[K in keyof T]: T[K] extends UniformValue ? never : K}[keyof T];\ntype UniformKeys = {[K in keyof T]: T[K] extends UniformValue ? K : never}[keyof T];\nexport type PickBindings = {[K in BindingKeys>]: T[K]};\nexport type PickUniforms = {[K in UniformKeys>]: T[K]};\n\n/**\n * A shader module definition object\n *\n * @note Needs to be initialized with `initializeShaderModules`\n * @note `UniformsT` & `BindingsT` are deduced from `PropsT` by default. If\n * a custom type for `UniformsT` is used, `BindingsT` should be also be provided.\n */\nexport type ShaderModule<\n PropsT extends Record = Record,\n UniformsT extends Record = PickUniforms,\n BindingsT extends Record = PickBindings\n> = {\n /** Used for type inference not for values */\n props?: PropsT;\n /** Used for type inference, not currently used for values */\n uniforms?: UniformsT;\n /** Used for type inference, not currently used for values */\n bindings?: BindingsT;\n /** Logical bind-group assignment for bindings declared by this module */\n bindingLayout?: readonly ShaderModuleBindingLayout[];\n /** Preferred starting binding slot for this module's WGSL `@binding(auto)` declarations. */\n firstBindingSlot?: number;\n\n name: string;\n\n /** WGSL code */\n source?: string;\n /** GLSL fragment shader code */\n fs?: string;\n /** GLSL vertex shader code */\n vs?: string;\n\n /** Uniform shader types @note: Both order and types MUST match uniform block declarations in shader */\n uniformTypes?: Required>; // Record;\n /** Uniform JS prop types */\n propTypes?: Record;\n /** Default uniform values */\n defaultUniforms?: Required; // Record;\n\n /** Function that maps props to uniforms & bindings */\n getUniforms?: (\n props: Partial,\n prevUniforms?: UniformsT\n ) => Partial;\n\n defines?: Record;\n /** Injections */\n inject?: Record;\n dependencies?: ShaderModule[];\n /** Information on deprecated properties */\n deprecations?: ShaderModuleDeprecation[];\n\n /** The instance field contains information that is generated at run-time */\n instance?: {\n propValidators?: Record;\n parsedDeprecations: ShaderModuleDeprecation[];\n\n normalizedInjections: {\n vertex: Record;\n fragment: Record;\n };\n };\n};\n\n/** Use to generate deprecations when shader module is used */\nexport type ShaderModuleDeprecation = {\n type: string;\n regex?: RegExp;\n new: string;\n old: string;\n deprecated?: boolean;\n};\n\n// SHNDER MODULE API\n\nexport function initializeShaderModules(modules: ShaderModule[]): void {\n modules.map((module: ShaderModule) => initializeShaderModule(module));\n}\n\nexport function initializeShaderModule(module: ShaderModule): void {\n if (module.instance) {\n return;\n }\n\n initializeShaderModules(module.dependencies || []);\n\n const {\n propTypes = {},\n deprecations = [],\n // defines = {},\n inject = {}\n } = module;\n\n const instance: Required['instance'] = {\n normalizedInjections: normalizeInjections(inject),\n parsedDeprecations: parseDeprecationDefinitions(deprecations)\n };\n\n if (propTypes) {\n instance.propValidators = makePropValidators(propTypes);\n }\n\n module.instance = instance;\n\n // TODO(ib) - we need to apply the original prop types to the default uniforms\n let defaultProps: ShaderModule['props'] = {};\n if (propTypes) {\n defaultProps = Object.entries(propTypes).reduce(\n (obj: ShaderModule['props'], [key, propType]) => {\n // @ts-expect-error\n const value = propType?.value;\n if (value) {\n // @ts-expect-error\n obj[key] = value;\n }\n return obj;\n },\n {} as ShaderModule['props']\n );\n }\n\n module.defaultUniforms = {...module.defaultUniforms, ...defaultProps} as any;\n}\n\n/** Convert module props to uniforms */\nexport function getShaderModuleUniforms<\n ShaderModuleT extends ShaderModule<\n Record,\n Record\n >\n>(\n module: ShaderModuleT,\n props?: ShaderModuleT['props'],\n oldUniforms?: ShaderModuleT['uniforms']\n): Record {\n initializeShaderModule(module);\n\n const uniforms = oldUniforms || {...module.defaultUniforms};\n // If module has a getUniforms function, use it\n if (props && module.getUniforms) {\n return module.getUniforms(props, uniforms);\n }\n\n // Build uniforms from the uniforms array\n // @ts-expect-error\n return getValidatedProperties(props, module.instance?.propValidators, module.name);\n}\n\n/* TODO this looks like it was unused code\n _defaultGetUniforms(opts: Record = {}): Record {\n const uniforms: Record = {};\n const propTypes = this.uniforms;\n\n for (const key in propTypes) {\n const propDef = propTypes[key];\n if (key in opts && !propDef.private) {\n if (propDef.validate) {\n assert(propDef.validate(opts[key], propDef), `${this.name}: invalid ${key}`);\n }\n uniforms[key] = opts[key];\n } else {\n uniforms[key] = propDef.value;\n }\n }\n\n return uniforms;\n }\n}\n*/\n// Warn about deprecated uniforms or functions\nexport function checkShaderModuleDeprecations(\n shaderModule: ShaderModule,\n shaderSource: string,\n log: any\n): void {\n shaderModule.deprecations?.forEach(def => {\n if (def.regex?.test(shaderSource)) {\n if (def.deprecated) {\n log.deprecated(def.old, def.new)();\n } else {\n log.removed(def.old, def.new)();\n }\n }\n });\n}\n\n// HELPERS\n\nfunction parseDeprecationDefinitions(deprecations: ShaderModuleDeprecation[]) {\n deprecations.forEach(def => {\n switch (def.type) {\n case 'function':\n def.regex = new RegExp(`\\\\b${def.old}\\\\(`);\n break;\n default:\n def.regex = new RegExp(`${def.type} ${def.old};`);\n }\n });\n\n return deprecations;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {ShaderModule, initializeShaderModules} from './shader-module';\n\n// import type {ShaderModule} from '../shader-module/shader-module';\n\ntype AbstractModule = {\n name: string;\n dependencies?: AbstractModule[];\n};\n\n/**\n * Takes a list of shader module names and returns a new list of\n * shader module names that includes all dependencies, sorted so\n * that modules that are dependencies of other modules come first.\n *\n * If the shader glsl code from the returned modules is concatenated\n * in the reverse order, it is guaranteed that all functions be resolved and\n * that all function and variable definitions come before use.\n *\n * @param modules - Array of modules (inline modules or module names)\n * @return - Array of modules\n */\nexport function getShaderModuleDependencies(modules: T[]): T[] {\n initializeShaderModules(modules);\n const moduleMap: Record = {};\n const moduleDepth: Record = {};\n getDependencyGraph({modules, level: 0, moduleMap, moduleDepth});\n\n // Return a reverse sort so that dependencies come before the modules that use them\n const dependencies = Object.keys(moduleDepth)\n .sort((a, b) => moduleDepth[b] - moduleDepth[a])\n .map(name => moduleMap[name]);\n initializeShaderModules(dependencies);\n return dependencies;\n}\n\n/**\n * Recursively checks module dependencies to calculate dependency level of each module.\n *\n * @param options.modules - Array of modules\n * @param options.level - Current level\n * @param options.moduleMap -\n * @param options.moduleDepth - Current level\n * @return - Map of module name to its level\n */\n// Adds another level of dependencies to the result map\nexport function getDependencyGraph(options: {\n modules: T[];\n level: number;\n moduleMap: Record;\n moduleDepth: Record;\n}) {\n const {modules, level, moduleMap, moduleDepth} = options;\n if (level >= 5) {\n throw new Error('Possible loop in shader dependency graph');\n }\n\n // Update level on all current modules\n for (const module of modules) {\n moduleMap[module.name] = module;\n if (moduleDepth[module.name] === undefined || moduleDepth[module.name] < level) {\n moduleDepth[module.name] = level;\n }\n }\n\n // Recurse\n for (const module of modules) {\n if (module.dependencies) {\n getDependencyGraph({modules: module.dependencies, level: level + 1, moduleMap, moduleDepth});\n }\n }\n}\n\n/**\n * Takes a list of shader module names and returns a new list of\n * shader module names that includes all dependencies, sorted so\n * that modules that are dependencies of other modules come first.\n *\n * If the shader glsl code from the returned modules is concatenated\n * in the reverse order, it is guaranteed that all functions be resolved and\n * that all function and variable definitions come before use.\n *\n * @param modules - Array of modules (inline modules or module names)\n * @return - Array of modules\n */\nexport function getShaderDependencies(modules: ShaderModule[]): ShaderModule[] {\n initializeShaderModules(modules);\n const moduleMap: Record = {};\n const moduleDepth: Record = {};\n getDependencyGraph({modules, level: 0, moduleMap, moduleDepth});\n\n // Return a reverse sort so that dependencies come before the modules that use them\n modules = Object.keys(moduleDepth)\n .sort((a, b) => moduleDepth[b] - moduleDepth[a])\n .map(name => moduleMap[name]);\n initializeShaderModules(modules);\n return modules;\n}\n\n// DEPRECATED\n\n/**\n * Instantiate shader modules and resolve any dependencies\n * @deprecated Use getShaderDpendencies\n */\nexport function resolveModules(modules: ShaderModule[]): ShaderModule[] {\n return getShaderDependencies(modules);\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ShaderModule} from './shader-module';\nimport {assert} from '../utils/assert';\n\n/**\n * Shader stages supported by shader-module uniform-layout validation helpers.\n */\nexport type ShaderModuleUniformLayoutStage = 'vertex' | 'fragment' | 'wgsl';\n\n/**\n * Describes the result of comparing declared `uniformTypes` with the fields\n * found in a shader uniform block.\n */\nexport type ShaderModuleUniformLayoutValidationResult = {\n /** Name of the shader module being validated. */\n moduleName: string;\n /** Expected block name derived from the shader module name. */\n uniformBlockName: string;\n /** Shader stage that was inspected. */\n stage: ShaderModuleUniformLayoutStage;\n /** Field names declared by the module metadata. */\n expectedUniformNames: string[];\n /** Field names parsed from the shader source. */\n actualUniformNames: string[];\n /** Whether the declared and parsed field lists match exactly. */\n matches: boolean;\n};\n\n/**\n * Parsed information about one GLSL uniform block declaration.\n */\nexport type GLSLUniformBlockInfo = {\n /** Declared block type name. */\n blockName: string;\n /** Optional instance name that follows the block declaration. */\n instanceName: string | null;\n /** Raw layout qualifier text, if present. */\n layoutQualifier: string | null;\n /** Whether any explicit layout qualifier was present. */\n hasLayoutQualifier: boolean;\n /** Whether the block explicitly declares `layout(std140)`. */\n isStd140: boolean;\n /** Raw source text inside the block braces. */\n body: string;\n};\n\n/**\n * Logging surface used by validation and warning helpers.\n */\ntype Logger = {\n /** Error logger compatible with luma's deferred log API. */\n error?: (...args: unknown[]) => () => unknown;\n /** Warning logger compatible with luma's deferred log API. */\n warn?: (...args: unknown[]) => () => unknown;\n};\n\n/**\n * Matches one field declaration inside a GLSL uniform block body.\n */\nconst GLSL_UNIFORM_BLOCK_FIELD_REGEXP =\n /^(?:uniform\\s+)?(?:(?:lowp|mediump|highp)\\s+)?[A-Za-z0-9_]+(?:<[^>]+>)?\\s+([A-Za-z0-9_]+)(?:\\s*\\[[^\\]]+\\])?\\s*;/;\n/**\n * Matches full GLSL uniform block declarations, including optional layout qualifiers.\n */\nconst GLSL_UNIFORM_BLOCK_REGEXP =\n /((?:layout\\s*\\([^)]*\\)\\s*)*)uniform\\s+([A-Za-z_][A-Za-z0-9_]*)\\s*\\{([\\s\\S]*?)\\}\\s*([A-Za-z_][A-Za-z0-9_]*)?\\s*;/g;\n\n/**\n * Returns the uniform block type name expected for the supplied shader module.\n */\nexport function getShaderModuleUniformBlockName(module: ShaderModule): string {\n return `${module.name}Uniforms`;\n}\n\n/**\n * Returns the ordered field names parsed from a shader module's uniform block.\n *\n * @returns `null` when the stage has no source or the expected block is absent.\n */\nexport function getShaderModuleUniformBlockFields(\n module: ShaderModule,\n stage: ShaderModuleUniformLayoutStage\n): string[] | null {\n const shaderSource =\n stage === 'wgsl' ? module.source : stage === 'vertex' ? module.vs : module.fs;\n\n if (!shaderSource) {\n return null;\n }\n\n const uniformBlockName = getShaderModuleUniformBlockName(module);\n return extractShaderUniformBlockFieldNames(\n shaderSource,\n stage === 'wgsl' ? 'wgsl' : 'glsl',\n uniformBlockName\n );\n}\n\n/**\n * Computes the validation result for a shader module's declared and parsed\n * uniform-block field lists.\n *\n * @returns `null` when the module has no declared uniform types or no matching block.\n */\nexport function getShaderModuleUniformLayoutValidationResult(\n module: ShaderModule,\n stage: ShaderModuleUniformLayoutStage\n): ShaderModuleUniformLayoutValidationResult | null {\n const expectedUniformNames = Object.keys(module.uniformTypes || {});\n if (!expectedUniformNames.length) {\n return null;\n }\n\n const actualUniformNames = getShaderModuleUniformBlockFields(module, stage);\n if (!actualUniformNames) {\n return null;\n }\n\n return {\n moduleName: module.name,\n uniformBlockName: getShaderModuleUniformBlockName(module),\n stage,\n expectedUniformNames,\n actualUniformNames,\n matches: areStringArraysEqual(expectedUniformNames, actualUniformNames)\n };\n}\n\n/**\n * Validates that a shader module's parsed uniform block matches `uniformTypes`.\n *\n * When a mismatch is detected, the helper logs a formatted error and optionally\n * throws via {@link assert}.\n */\nexport function validateShaderModuleUniformLayout(\n module: ShaderModule,\n stage: ShaderModuleUniformLayoutStage,\n options: {\n log?: Logger;\n throwOnError?: boolean;\n } = {}\n): ShaderModuleUniformLayoutValidationResult | null {\n const validationResult = getShaderModuleUniformLayoutValidationResult(module, stage);\n if (!validationResult || validationResult.matches) {\n return validationResult;\n }\n\n const message = formatShaderModuleUniformLayoutError(validationResult);\n options.log?.error?.(message, validationResult)();\n\n if (options.throwOnError !== false) {\n assert(false, message);\n }\n\n return validationResult;\n}\n\n/**\n * Parses all GLSL uniform blocks in a shader source string.\n */\nexport function getGLSLUniformBlocks(shaderSource: string): GLSLUniformBlockInfo[] {\n const blocks: GLSLUniformBlockInfo[] = [];\n const uncommentedSource = stripShaderComments(shaderSource);\n\n for (const sourceMatch of uncommentedSource.matchAll(GLSL_UNIFORM_BLOCK_REGEXP)) {\n const layoutQualifier = sourceMatch[1]?.trim() || null;\n blocks.push({\n blockName: sourceMatch[2],\n body: sourceMatch[3],\n instanceName: sourceMatch[4] || null,\n layoutQualifier,\n hasLayoutQualifier: Boolean(layoutQualifier),\n isStd140: Boolean(\n layoutQualifier && /\\blayout\\s*\\([^)]*\\bstd140\\b[^)]*\\)/.exec(layoutQualifier)\n )\n });\n }\n\n return blocks;\n}\n\n/**\n * Emits warnings for GLSL uniform blocks that do not explicitly declare\n * `layout(std140)`.\n *\n * @returns The list of parsed blocks that were considered non-compliant.\n */\nexport function warnIfGLSLUniformBlocksAreNotStd140(\n shaderSource: string,\n stage: Exclude,\n log?: Logger,\n context?: {label?: string}\n): GLSLUniformBlockInfo[] {\n const nonStd140Blocks = getGLSLUniformBlocks(shaderSource).filter(block => !block.isStd140);\n const seenBlockNames = new Set();\n\n for (const block of nonStd140Blocks) {\n if (seenBlockNames.has(block.blockName)) {\n continue;\n }\n seenBlockNames.add(block.blockName);\n\n const shaderLabel = context?.label ? `${context.label} ` : '';\n const actualLayout = block.hasLayoutQualifier\n ? `declares ${normalizeWhitespace(block.layoutQualifier!)} instead of layout(std140)`\n : 'does not declare layout(std140)';\n const message = `${shaderLabel}${stage} shader uniform block ${\n block.blockName\n } ${actualLayout}. luma.gl host-side shader block packing assumes explicit layout(std140) for GLSL uniform blocks. Add \\`layout(std140)\\` to the block declaration.`;\n log?.warn?.(message, block)();\n }\n\n return nonStd140Blocks;\n}\n\n/**\n * Extracts field names from the named GLSL or WGSL uniform block/struct.\n */\nfunction extractShaderUniformBlockFieldNames(\n shaderSource: string,\n language: 'glsl' | 'wgsl',\n uniformBlockName: string\n): string[] | null {\n const sourceBody =\n language === 'wgsl'\n ? extractWGSLStructBody(shaderSource, uniformBlockName)\n : extractGLSLUniformBlockBody(shaderSource, uniformBlockName);\n\n if (!sourceBody) {\n return null;\n }\n\n const fieldNames: string[] = [];\n\n for (const sourceLine of sourceBody.split('\\n')) {\n const line = sourceLine.replace(/\\/\\/.*$/, '').trim();\n if (!line || line.startsWith('#')) {\n continue;\n }\n\n const fieldMatch =\n language === 'wgsl'\n ? line.match(/^([A-Za-z0-9_]+)\\s*:/)\n : line.match(GLSL_UNIFORM_BLOCK_FIELD_REGEXP);\n\n if (fieldMatch) {\n fieldNames.push(fieldMatch[1]);\n }\n }\n\n return fieldNames;\n}\n\n/**\n * Extracts the body of a WGSL struct with the supplied name.\n */\nfunction extractWGSLStructBody(shaderSource: string, uniformBlockName: string): string | null {\n const structMatch = new RegExp(`\\\\bstruct\\\\s+${uniformBlockName}\\\\b`, 'm').exec(shaderSource);\n if (!structMatch) {\n return null;\n }\n\n const openBraceIndex = shaderSource.indexOf('{', structMatch.index);\n if (openBraceIndex < 0) {\n return null;\n }\n\n let braceDepth = 0;\n for (let index = openBraceIndex; index < shaderSource.length; index++) {\n const character = shaderSource[index];\n if (character === '{') {\n braceDepth++;\n continue;\n }\n if (character !== '}') {\n continue;\n }\n\n braceDepth--;\n if (braceDepth === 0) {\n return shaderSource.slice(openBraceIndex + 1, index);\n }\n }\n\n return null;\n}\n\n/**\n * Extracts the body of a named GLSL uniform block from shader source.\n */\nfunction extractGLSLUniformBlockBody(\n shaderSource: string,\n uniformBlockName: string\n): string | null {\n const block = getGLSLUniformBlocks(shaderSource).find(\n candidate => candidate.blockName === uniformBlockName\n );\n return block?.body || null;\n}\n\n/**\n * Returns `true` when the two arrays contain the same strings in the same order.\n */\nfunction areStringArraysEqual(leftValues: string[], rightValues: string[]): boolean {\n if (leftValues.length !== rightValues.length) {\n return false;\n }\n\n for (let valueIndex = 0; valueIndex < leftValues.length; valueIndex++) {\n if (leftValues[valueIndex] !== rightValues[valueIndex]) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Formats the standard validation error message for a shader-module layout mismatch.\n */\nfunction formatShaderModuleUniformLayoutError(\n validationResult: ShaderModuleUniformLayoutValidationResult\n): string {\n const {expectedUniformNames, actualUniformNames} = validationResult;\n const missingUniformNames = expectedUniformNames.filter(\n uniformName => !actualUniformNames.includes(uniformName)\n );\n const unexpectedUniformNames = actualUniformNames.filter(\n uniformName => !expectedUniformNames.includes(uniformName)\n );\n const mismatchDetails = [\n `Expected ${expectedUniformNames.length} fields, found ${actualUniformNames.length}.`\n ];\n const firstMismatchDescription = getFirstUniformMismatchDescription(\n expectedUniformNames,\n actualUniformNames\n );\n if (firstMismatchDescription) {\n mismatchDetails.push(firstMismatchDescription);\n }\n if (missingUniformNames.length) {\n mismatchDetails.push(\n `Missing from shader block (${missingUniformNames.length}): ${formatUniformNameList(\n missingUniformNames\n )}.`\n );\n }\n if (unexpectedUniformNames.length) {\n mismatchDetails.push(\n `Unexpected in shader block (${unexpectedUniformNames.length}): ${formatUniformNameList(\n unexpectedUniformNames\n )}.`\n );\n }\n if (\n expectedUniformNames.length <= 12 &&\n actualUniformNames.length <= 12 &&\n (missingUniformNames.length || unexpectedUniformNames.length)\n ) {\n mismatchDetails.push(`Expected: ${expectedUniformNames.join(', ')}.`);\n mismatchDetails.push(`Actual: ${actualUniformNames.join(', ')}.`);\n }\n\n return `${validationResult.moduleName}: ${validationResult.stage} shader uniform block ${\n validationResult.uniformBlockName\n } does not match module.uniformTypes. ${mismatchDetails.join(' ')}`;\n}\n\n/**\n * Removes line and block comments from shader source before lightweight parsing.\n */\nfunction stripShaderComments(shaderSource: string): string {\n return shaderSource.replace(/\\/\\*[\\s\\S]*?\\*\\//g, '').replace(/\\/\\/.*$/gm, '');\n}\n\n/**\n * Collapses repeated whitespace in a layout qualifier for log-friendly output.\n */\nfunction normalizeWhitespace(value: string): string {\n return value.replace(/\\s+/g, ' ').trim();\n}\n\nfunction getFirstUniformMismatchDescription(\n expectedUniformNames: string[],\n actualUniformNames: string[]\n): string | null {\n const minimumLength = Math.min(expectedUniformNames.length, actualUniformNames.length);\n for (let index = 0; index < minimumLength; index++) {\n if (expectedUniformNames[index] !== actualUniformNames[index]) {\n return `First mismatch at field ${index + 1}: expected ${\n expectedUniformNames[index]\n }, found ${actualUniformNames[index]}.`;\n }\n }\n\n if (expectedUniformNames.length > actualUniformNames.length) {\n return `Shader block ends after field ${actualUniformNames.length}; expected next field ${\n expectedUniformNames[actualUniformNames.length]\n }.`;\n }\n if (actualUniformNames.length > expectedUniformNames.length) {\n return `Shader block has extra field ${actualUniformNames.length}: ${\n actualUniformNames[expectedUniformNames.length]\n }.`;\n }\n\n return null;\n}\n\nfunction formatUniformNameList(uniformNames: string[], maxNames = 8): string {\n if (uniformNames.length <= maxNames) {\n return uniformNames.join(', ');\n }\n\n const remainingCount = uniformNames.length - maxNames;\n return `${uniformNames.slice(0, maxNames).join(', ')}, ... (${remainingCount} more)`;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {PlatformInfo} from './platform-info';\n\n/** Adds defines to help identify GPU architecture / platform */\nexport function getPlatformShaderDefines(platformInfo: PlatformInfo): string {\n switch (platformInfo?.gpu.toLowerCase()) {\n case 'apple':\n return /* glsl */ `\\\n#define APPLE_GPU\n// Apple optimizes away the calculation necessary for emulated fp64\n#define LUMA_FP64_CODE_ELIMINATION_WORKAROUND 1\n#define LUMA_FP32_TAN_PRECISION_WORKAROUND 1\n// Intel GPU doesn't have full 32 bits precision in same cases, causes overflow\n#define LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND 1\n`;\n\n case 'nvidia':\n return /* glsl */ `\\\n#define NVIDIA_GPU\n// Nvidia optimizes away the calculation necessary for emulated fp64\n#define LUMA_FP64_CODE_ELIMINATION_WORKAROUND 1\n`;\n\n case 'intel':\n return /* glsl */ `\\\n#define INTEL_GPU\n// Intel optimizes away the calculation necessary for emulated fp64\n#define LUMA_FP64_CODE_ELIMINATION_WORKAROUND 1\n// Intel's built-in 'tan' function doesn't have acceptable precision\n#define LUMA_FP32_TAN_PRECISION_WORKAROUND 1\n// Intel GPU doesn't have full 32 bits precision in same cases, causes overflow\n#define LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND 1\n`;\n\n case 'amd':\n // AMD Does not eliminate fp64 code\n return /* glsl */ `\\\n#define AMD_GPU\n`;\n\n default:\n // We don't know what GPU it is, could be that the GPU driver or\n // browser is not implementing UNMASKED_RENDERER constant and not\n // reporting a correct name\n return /* glsl */ `\\\n#define DEFAULT_GPU\n// Prevent driver from optimizing away the calculation necessary for emulated fp64\n#define LUMA_FP64_CODE_ELIMINATION_WORKAROUND 1\n// Headless Chrome's software shader 'tan' function doesn't have acceptable precision\n#define LUMA_FP32_TAN_PRECISION_WORKAROUND 1\n// If the GPU doesn't have full 32 bits precision, will causes overflow\n#define LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND 1\n`;\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// TRANSPILATION TABLES\n\n/**\n * Transpiles GLSL 3.00 shader source code to target GLSL version (3.00 or 1.00)\n *\n * @note We always run transpiler even if same version e.g. 3.00 => 3.00\n * @note For texture sampling transpilation, apps need to use non-standard texture* calls in GLSL 3.00 source\n * RFC: https://github.com/visgl/luma.gl/blob/7.0-release/dev-docs/RFCs/v6.0/portable-glsl-300-rfc.md\n */\nexport function transpileGLSLShader(source: string, stage: 'vertex' | 'fragment'): string {\n const sourceGLSLVersion = Number(source.match(/^#version[ \\t]+(\\d+)/m)?.[1] || 100);\n if (sourceGLSLVersion !== 300) {\n // TODO - we splurge on a longer error message to help deck.gl custom layer developers\n throw new Error('luma.gl v9 only supports GLSL 3.00 shader sources');\n }\n\n switch (stage) {\n case 'vertex':\n source = convertShader(source, ES300_VERTEX_REPLACEMENTS);\n return source;\n case 'fragment':\n source = convertShader(source, ES300_FRAGMENT_REPLACEMENTS);\n return source;\n default:\n // Unknown shader stage\n throw new Error(stage);\n }\n}\n\ntype GLSLReplacement = [RegExp, string];\n\n/** Simple regex replacements for GLSL ES 1.00 syntax that has changed in GLSL ES 3.00 */\nconst ES300_REPLACEMENTS: GLSLReplacement[] = [\n // Fix poorly formatted version directive\n [/^(#version[ \\t]+(100|300[ \\t]+es))?[ \\t]*\\n/, '#version 300 es\\n'],\n // The individual `texture...()` functions were replaced with `texture()` overloads\n [/\\btexture(2D|2DProj|Cube)Lod(EXT)?\\(/g, 'textureLod('],\n [/\\btexture(2D|2DProj|Cube)(EXT)?\\(/g, 'texture(']\n];\n\nconst ES300_VERTEX_REPLACEMENTS: GLSLReplacement[] = [\n ...ES300_REPLACEMENTS,\n // `attribute` keyword replaced with `in`\n [makeVariableTextRegExp('attribute'), 'in $1'],\n // `varying` keyword replaced with `out`\n [makeVariableTextRegExp('varying'), 'out $1']\n];\n\n/** Simple regex replacements for GLSL ES 1.00 syntax that has changed in GLSL ES 3.00 */\nconst ES300_FRAGMENT_REPLACEMENTS: GLSLReplacement[] = [\n ...ES300_REPLACEMENTS,\n // `varying` keyword replaced with `in`\n [makeVariableTextRegExp('varying'), 'in $1']\n];\n\nfunction convertShader(source: string, replacements: GLSLReplacement[]) {\n for (const [pattern, replacement] of replacements) {\n source = source.replace(pattern, replacement);\n }\n return source;\n}\n\n/**\n * Creates a regexp that tests for a specific variable type\n * @example\n * should match:\n * in float weight;\n * out vec4 positions[2];\n * should not match:\n * void f(out float a, in float b) {}\n */\nfunction makeVariableTextRegExp(qualifier: 'attribute' | 'varying' | 'in' | 'out'): RegExp {\n return new RegExp(`\\\\b${qualifier}[ \\\\t]+(\\\\w+[ \\\\t]+\\\\w+(\\\\[\\\\w+\\\\])?;)`, 'g');\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {ShaderInjection} from './shader-injections';\n\n// A normalized hook function\n/**\n * The shader hook mechanism allows the application to create shaders\n * that can be automatically extended by the shader modules the application\n * includes.\n *\n * A shader hook function that shader modules can inject code into.\n * Shaders can call these functions, which will be no-ops by default.\n *\n * If a shader module injects code it will be executed upon the hook\n * function call.\n */\nexport type ShaderHook = {\n /** `vs:` or `fs:` followed by the name and arguments of the function, e.g. `vs:MYHOOK_func(inout vec4 value)`. Hook name without arguments\n will also be used as the name of the shader hook */\n hook: string;\n /** Code always included at the beginning of a hook function */\n header: string;\n /** Code always included at the end of a hook function */\n footer: string;\n /** To Be Documented */\n signature?: string;\n};\n\n/** Normalized shader hooks per shader */\nexport type ShaderHooks = {\n /** Normalized shader hooks for vertex shader */\n vertex: Record;\n /** Normalized shader hooks for fragment shader */\n fragment: Record;\n};\n\n/** Generate hook source code */\nexport function getShaderHooks(\n hookFunctions: Record,\n hookInjections: Record\n): string {\n let result = '';\n for (const hookName in hookFunctions) {\n const hookFunction = hookFunctions[hookName];\n result += `void ${hookFunction.signature} {\\n`;\n if (hookFunction.header) {\n result += ` ${hookFunction.header}`;\n }\n if (hookInjections[hookName]) {\n const injections = hookInjections[hookName];\n injections.sort((a: {order: number}, b: {order: number}): number => a.order - b.order);\n for (const injection of injections) {\n result += ` ${injection.injection}\\n`;\n }\n }\n if (hookFunction.footer) {\n result += ` ${hookFunction.footer}`;\n }\n result += '}\\n';\n }\n\n return result;\n}\n\n/**\n * Parse string based hook functions\n * And split per shader\n */\nexport function normalizeShaderHooks(hookFunctions: (string | ShaderHook)[]): ShaderHooks {\n const result: ShaderHooks = {vertex: {}, fragment: {}};\n\n for (const hookFunction of hookFunctions) {\n let opts: ShaderHook;\n let hook: string;\n if (typeof hookFunction !== 'string') {\n opts = hookFunction;\n hook = opts.hook;\n } else {\n opts = {} as ShaderHook;\n hook = hookFunction;\n }\n hook = hook.trim();\n const [shaderStage, signature] = hook.split(':');\n const name = hook.replace(/\\(.+/, '');\n const normalizedHook: ShaderHook = Object.assign(opts, {signature});\n switch (shaderStage) {\n case 'vs':\n result.vertex[name] = normalizedHook;\n break;\n case 'fs':\n result.fragment[name] = normalizedHook;\n break;\n default:\n throw new Error(shaderStage);\n }\n }\n\n return result;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/** Information extracted from shader source code */\nexport type ShaderInfo = {\n name: string;\n language: 'glsl' | 'wgsl';\n version: number;\n};\n\n/** Extracts information from shader source code */\nexport function getShaderInfo(source: string, defaultName?: string): ShaderInfo {\n return {\n name: getShaderName(source, defaultName),\n language: 'glsl',\n version: getShaderVersion(source)\n };\n}\n\n/** Extracts GLSLIFY style naming of shaders: `#define SHADER_NAME ...` */\nfunction getShaderName(shader: string, defaultName: string = 'unnamed'): string {\n const SHADER_NAME_REGEXP = /#define[^\\S\\r\\n]*SHADER_NAME[^\\S\\r\\n]*([A-Za-z0-9_-]+)\\s*/;\n const match = SHADER_NAME_REGEXP.exec(shader);\n return match ? match[1] : defaultName;\n}\n\n/** returns GLSL shader version of given shader string */\nfunction getShaderVersion(source: string): 100 | 300 {\n let version = 100;\n const words = source.match(/[^\\s]+/g);\n if (words && words.length >= 2 && words[0] === '#version') {\n const parsedVersion = parseInt(words[1], 10);\n if (Number.isFinite(parsedVersion)) {\n version = parsedVersion;\n }\n }\n if (version !== 100 && version !== 300) {\n throw new Error(`Invalid GLSL version ${version}`);\n }\n return version;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport const WGSL_BINDABLE_VARIABLE_PATTERN =\n '(?:var<\\\\s*(uniform|storage(?:\\\\s*,\\\\s*[A-Za-z_][A-Za-z0-9_]*)?)\\\\s*>|var)\\\\s+([A-Za-z_][A-Za-z0-9_]*)';\nconst WGSL_BINDING_DECLARATION_SEPARATOR_PATTERN = '\\\\s*';\n\nexport const MODULE_WGSL_BINDING_DECLARATION_REGEXES = [\n new RegExp(\n `@binding\\\\(\\\\s*(auto|\\\\d+)\\\\s*\\\\)${WGSL_BINDING_DECLARATION_SEPARATOR_PATTERN}@group\\\\(\\\\s*(\\\\d+)\\\\s*\\\\)${WGSL_BINDING_DECLARATION_SEPARATOR_PATTERN}${WGSL_BINDABLE_VARIABLE_PATTERN}`,\n 'g'\n ),\n new RegExp(\n `@group\\\\(\\\\s*(\\\\d+)\\\\s*\\\\)${WGSL_BINDING_DECLARATION_SEPARATOR_PATTERN}@binding\\\\(\\\\s*(auto|\\\\d+)\\\\s*\\\\)${WGSL_BINDING_DECLARATION_SEPARATOR_PATTERN}${WGSL_BINDABLE_VARIABLE_PATTERN}`,\n 'g'\n )\n] as const;\n\nexport const WGSL_BINDING_DECLARATION_REGEXES = [\n new RegExp(\n `@binding\\\\(\\\\s*(auto|\\\\d+)\\\\s*\\\\)${WGSL_BINDING_DECLARATION_SEPARATOR_PATTERN}@group\\\\(\\\\s*(\\\\d+)\\\\s*\\\\)${WGSL_BINDING_DECLARATION_SEPARATOR_PATTERN}${WGSL_BINDABLE_VARIABLE_PATTERN}`,\n 'g'\n ),\n new RegExp(\n `@group\\\\(\\\\s*(\\\\d+)\\\\s*\\\\)${WGSL_BINDING_DECLARATION_SEPARATOR_PATTERN}@binding\\\\(\\\\s*(auto|\\\\d+)\\\\s*\\\\)${WGSL_BINDING_DECLARATION_SEPARATOR_PATTERN}${WGSL_BINDABLE_VARIABLE_PATTERN}`,\n 'g'\n )\n] as const;\n\nexport const WGSL_EXPLICIT_BINDING_DECLARATION_REGEXES = [\n new RegExp(\n `@binding\\\\(\\\\s*(\\\\d+)\\\\s*\\\\)${WGSL_BINDING_DECLARATION_SEPARATOR_PATTERN}@group\\\\(\\\\s*(\\\\d+)\\\\s*\\\\)${WGSL_BINDING_DECLARATION_SEPARATOR_PATTERN}${WGSL_BINDABLE_VARIABLE_PATTERN}`,\n 'g'\n ),\n new RegExp(\n `@group\\\\(\\\\s*(\\\\d+)\\\\s*\\\\)${WGSL_BINDING_DECLARATION_SEPARATOR_PATTERN}@binding\\\\(\\\\s*(\\\\d+)\\\\s*\\\\)${WGSL_BINDING_DECLARATION_SEPARATOR_PATTERN}${WGSL_BINDABLE_VARIABLE_PATTERN}`,\n 'g'\n )\n] as const;\n\nconst WGSL_AUTO_BINDING_DECLARATION_REGEXES = [\n new RegExp(\n `@binding\\\\(\\\\s*(auto)\\\\s*\\\\)\\\\s*@group\\\\(\\\\s*(\\\\d+)\\\\s*\\\\)\\\\s*${WGSL_BINDABLE_VARIABLE_PATTERN}`,\n 'g'\n ),\n new RegExp(\n `@group\\\\(\\\\s*(\\\\d+)\\\\s*\\\\)\\\\s*@binding\\\\(\\\\s*(auto)\\\\s*\\\\)\\\\s*${WGSL_BINDABLE_VARIABLE_PATTERN}`,\n 'g'\n ),\n new RegExp(\n `@binding\\\\(\\\\s*(auto)\\\\s*\\\\)\\\\s*@group\\\\(\\\\s*(\\\\d+)\\\\s*\\\\)(?:[\\\\s\\\\n\\\\r]*@[A-Za-z_][^\\\\n\\\\r]*)*[\\\\s\\\\n\\\\r]*${WGSL_BINDABLE_VARIABLE_PATTERN}`,\n 'g'\n ),\n new RegExp(\n `@group\\\\(\\\\s*(\\\\d+)\\\\s*\\\\)\\\\s*@binding\\\\(\\\\s*(auto)\\\\s*\\\\)(?:[\\\\s\\\\n\\\\r]*@[A-Za-z_][^\\\\n\\\\r]*)*[\\\\s\\\\n\\\\r]*${WGSL_BINDABLE_VARIABLE_PATTERN}`,\n 'g'\n )\n] as const;\n\nexport type WGSLBindingDeclarationMatch = {\n match: string;\n index: number;\n length: number;\n bindingToken: string;\n groupToken: string;\n accessDeclaration?: string;\n name: string;\n};\n\nexport function maskWGSLComments(source: string): string {\n const maskedCharacters = source.split('');\n let index = 0;\n let blockCommentDepth = 0;\n let inLineComment = false;\n let inString = false;\n let isEscaped = false;\n\n while (index < source.length) {\n const character = source[index];\n const nextCharacter = source[index + 1];\n\n if (inString) {\n if (isEscaped) {\n isEscaped = false;\n } else if (character === '\\\\') {\n isEscaped = true;\n } else if (character === '\"') {\n inString = false;\n }\n index++;\n continue;\n }\n\n if (inLineComment) {\n if (character === '\\n' || character === '\\r') {\n inLineComment = false;\n } else {\n maskedCharacters[index] = ' ';\n }\n index++;\n continue;\n }\n\n if (blockCommentDepth > 0) {\n if (character === '/' && nextCharacter === '*') {\n maskedCharacters[index] = ' ';\n maskedCharacters[index + 1] = ' ';\n blockCommentDepth++;\n index += 2;\n continue;\n }\n\n if (character === '*' && nextCharacter === '/') {\n maskedCharacters[index] = ' ';\n maskedCharacters[index + 1] = ' ';\n blockCommentDepth--;\n index += 2;\n continue;\n }\n\n if (character !== '\\n' && character !== '\\r') {\n maskedCharacters[index] = ' ';\n }\n index++;\n continue;\n }\n\n if (character === '\"') {\n inString = true;\n index++;\n continue;\n }\n\n if (character === '/' && nextCharacter === '/') {\n maskedCharacters[index] = ' ';\n maskedCharacters[index + 1] = ' ';\n inLineComment = true;\n index += 2;\n continue;\n }\n\n if (character === '/' && nextCharacter === '*') {\n maskedCharacters[index] = ' ';\n maskedCharacters[index + 1] = ' ';\n blockCommentDepth = 1;\n index += 2;\n continue;\n }\n\n index++;\n }\n\n return maskedCharacters.join('');\n}\n\nexport function getWGSLBindingDeclarationMatches(\n source: string,\n regexes: readonly RegExp[]\n): WGSLBindingDeclarationMatch[] {\n const maskedSource = maskWGSLComments(source);\n const matches: WGSLBindingDeclarationMatch[] = [];\n\n for (const regex of regexes) {\n regex.lastIndex = 0;\n let match: RegExpExecArray | null;\n match = regex.exec(maskedSource);\n while (match) {\n const isBindingFirst = regex === regexes[0];\n const index = match.index;\n const length = match[0].length;\n matches.push({\n match: source.slice(index, index + length),\n index,\n length,\n bindingToken: match[isBindingFirst ? 1 : 2],\n groupToken: match[isBindingFirst ? 2 : 1],\n accessDeclaration: match[3]?.trim(),\n name: match[4]\n });\n match = regex.exec(maskedSource);\n }\n }\n\n return matches.sort((left, right) => left.index - right.index);\n}\n\nexport function replaceWGSLBindingDeclarationMatches(\n source: string,\n regexes: readonly RegExp[],\n replacer: (match: WGSLBindingDeclarationMatch) => string\n): string {\n const matches = getWGSLBindingDeclarationMatches(source, regexes);\n if (!matches.length) {\n return source;\n }\n\n let relocatedSource = '';\n let lastIndex = 0;\n\n for (const match of matches) {\n relocatedSource += source.slice(lastIndex, match.index);\n relocatedSource += replacer(match);\n lastIndex = match.index + match.length;\n }\n\n relocatedSource += source.slice(lastIndex);\n return relocatedSource;\n}\n\nexport function hasWGSLAutoBinding(source: string): boolean {\n return /@binding\\(\\s*auto\\s*\\)/.test(maskWGSLComments(source));\n}\n\nexport function getFirstWGSLAutoBindingDeclarationMatch(\n source: string,\n regexes: readonly RegExp[]\n): WGSLBindingDeclarationMatch | undefined {\n const autoBindingRegexes =\n regexes === MODULE_WGSL_BINDING_DECLARATION_REGEXES ||\n regexes === WGSL_BINDING_DECLARATION_REGEXES\n ? WGSL_AUTO_BINDING_DECLARATION_REGEXES\n : regexes;\n\n return getWGSLBindingDeclarationMatches(source, autoBindingRegexes).find(\n declarationMatch => declarationMatch.bindingToken === 'auto'\n );\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {WGSL_BINDABLE_VARIABLE_PATTERN, maskWGSLComments} from './wgsl-binding-scan';\n\ntype ShaderBindingAssignment = {\n moduleName: string;\n name: string;\n group: number;\n location: number;\n};\n\nconst WGSL_BINDING_DEBUG_REGEXES = [\n new RegExp(\n `@binding\\\\(\\\\s*(\\\\d+)\\\\s*\\\\)\\\\s*@group\\\\(\\\\s*(\\\\d+)\\\\s*\\\\)\\\\s*${WGSL_BINDABLE_VARIABLE_PATTERN}\\\\s*:\\\\s*([^;]+);`,\n 'g'\n ),\n new RegExp(\n `@group\\\\(\\\\s*(\\\\d+)\\\\s*\\\\)\\\\s*@binding\\\\(\\\\s*(\\\\d+)\\\\s*\\\\)\\\\s*${WGSL_BINDABLE_VARIABLE_PATTERN}\\\\s*:\\\\s*([^;]+);`,\n 'g'\n )\n] as const;\n\n/** One debug row describing a WGSL binding in the assembled shader source. */\nexport type ShaderBindingDebugRow = {\n /** Binding name as declared in WGSL. */\n name: string;\n /** Bind-group index. */\n group: number;\n /** Binding slot within the bind group. */\n binding: number;\n /** Resource kind inferred from the WGSL declaration. */\n kind:\n | 'uniform'\n | 'storage'\n | 'read-only-storage'\n | 'texture'\n | 'sampler'\n | 'storage-texture'\n | 'unknown';\n /** Whether the binding came from application WGSL or a shader module. */\n owner: 'application' | 'module';\n /** Shader module name when the binding was contributed by a module. */\n moduleName?: string;\n /** Full WGSL resource type text from the declaration. */\n resourceType?: string;\n /** WGSL access mode when cheaply available. */\n access?: string;\n /** Texture view dimension when cheaply available. */\n viewDimension?: string;\n /** Texture sample type when cheaply available. */\n sampleType?: string;\n /** Sampler kind when cheaply available. */\n samplerKind?: string;\n /** Whether the texture is multisampled when cheaply available. */\n multisampled?: boolean;\n};\n\n/** Builds a stable, table-friendly binding summary from assembled WGSL source. */\nexport function getShaderBindingDebugRowsFromWGSL(\n source: string,\n bindingAssignments: ShaderBindingAssignment[] = []\n): ShaderBindingDebugRow[] {\n const maskedSource = maskWGSLComments(source);\n const assignmentMap = new Map();\n for (const bindingAssignment of bindingAssignments) {\n assignmentMap.set(\n getBindingAssignmentKey(\n bindingAssignment.name,\n bindingAssignment.group,\n bindingAssignment.location\n ),\n bindingAssignment.moduleName\n );\n }\n\n const rows: ShaderBindingDebugRow[] = [];\n for (const regex of WGSL_BINDING_DEBUG_REGEXES) {\n regex.lastIndex = 0;\n let match: RegExpExecArray | null;\n match = regex.exec(maskedSource);\n while (match) {\n const isBindingFirst = regex === WGSL_BINDING_DEBUG_REGEXES[0];\n const binding = Number(match[isBindingFirst ? 1 : 2]);\n const group = Number(match[isBindingFirst ? 2 : 1]);\n const accessDeclaration = match[3]?.trim();\n const name = match[4];\n const resourceType = match[5].trim();\n const moduleName = assignmentMap.get(getBindingAssignmentKey(name, group, binding));\n\n rows.push(\n normalizeShaderBindingDebugRow({\n name,\n group,\n binding,\n owner: moduleName ? 'module' : 'application',\n moduleName,\n accessDeclaration,\n resourceType\n })\n );\n match = regex.exec(maskedSource);\n }\n }\n\n return rows.sort((left, right) => {\n if (left.group !== right.group) {\n return left.group - right.group;\n }\n if (left.binding !== right.binding) {\n return left.binding - right.binding;\n }\n return left.name.localeCompare(right.name);\n });\n}\n\nfunction normalizeShaderBindingDebugRow(row: {\n name: string;\n group: number;\n binding: number;\n owner: 'application' | 'module';\n moduleName?: string;\n accessDeclaration?: string;\n resourceType: string;\n}): ShaderBindingDebugRow {\n const baseRow: ShaderBindingDebugRow = {\n name: row.name,\n group: row.group,\n binding: row.binding,\n owner: row.owner,\n kind: 'unknown',\n moduleName: row.moduleName,\n resourceType: row.resourceType\n };\n\n if (row.accessDeclaration) {\n const access = row.accessDeclaration.split(',').map(value => value.trim());\n if (access[0] === 'uniform') {\n return {...baseRow, kind: 'uniform', access: 'uniform'};\n }\n if (access[0] === 'storage') {\n const storageAccess = access[1] || 'read_write';\n return {\n ...baseRow,\n kind: storageAccess === 'read' ? 'read-only-storage' : 'storage',\n access: storageAccess\n };\n }\n }\n\n if (row.resourceType === 'sampler' || row.resourceType === 'sampler_comparison') {\n return {\n ...baseRow,\n kind: 'sampler',\n samplerKind: row.resourceType === 'sampler_comparison' ? 'comparison' : 'filtering'\n };\n }\n\n if (row.resourceType.startsWith('texture_storage_')) {\n return {\n ...baseRow,\n kind: 'storage-texture',\n access: getStorageTextureAccess(row.resourceType),\n viewDimension: getTextureViewDimension(row.resourceType)\n };\n }\n\n if (row.resourceType.startsWith('texture_')) {\n return {\n ...baseRow,\n kind: 'texture',\n viewDimension: getTextureViewDimension(row.resourceType),\n sampleType: getTextureSampleType(row.resourceType),\n multisampled: row.resourceType.startsWith('texture_multisampled_')\n };\n }\n\n return baseRow;\n}\n\nfunction getBindingAssignmentKey(name: string, group: number, binding: number): string {\n return `${group}:${binding}:${name}`;\n}\n\nfunction getTextureViewDimension(resourceType: string): string | undefined {\n if (resourceType.includes('cube_array')) {\n return 'cube-array';\n }\n if (resourceType.includes('2d_array')) {\n return '2d-array';\n }\n if (resourceType.includes('cube')) {\n return 'cube';\n }\n if (resourceType.includes('3d')) {\n return '3d';\n }\n if (resourceType.includes('2d')) {\n return '2d';\n }\n if (resourceType.includes('1d')) {\n return '1d';\n }\n return undefined;\n}\n\nfunction getTextureSampleType(resourceType: string): string | undefined {\n if (resourceType.startsWith('texture_depth_')) {\n return 'depth';\n }\n if (resourceType.includes('')) {\n return 'sint';\n }\n if (resourceType.includes('')) {\n return 'uint';\n }\n if (resourceType.includes('')) {\n return 'float';\n }\n return undefined;\n}\n\nfunction getStorageTextureAccess(resourceType: string): string | undefined {\n const match = /,\\s*([A-Za-z_][A-Za-z0-9_]*)\\s*>$/.exec(resourceType);\n return match?.[1];\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {getShaderModuleDependencies} from '../shader-module/shader-module-dependencies';\nimport {PlatformInfo} from './platform-info';\nimport {getPlatformShaderDefines} from './platform-defines';\nimport {injectShader, DECLARATION_INJECT_MARKER} from './shader-injections';\nimport {transpileGLSLShader} from '../shader-transpiler/transpile-glsl-shader';\nimport {checkShaderModuleDeprecations} from '../shader-module/shader-module';\nimport {\n validateShaderModuleUniformLayout,\n warnIfGLSLUniformBlocksAreNotStd140\n} from '../shader-module/shader-module-uniform-layout';\nimport type {ShaderInjection} from './shader-injections';\nimport type {ShaderModule} from '../shader-module/shader-module';\nimport {ShaderHook, normalizeShaderHooks, getShaderHooks} from './shader-hooks';\nimport {assert} from '../utils/assert';\nimport {getShaderInfo} from '../glsl-utils/get-shader-info';\nimport {getShaderBindingDebugRowsFromWGSL, type ShaderBindingDebugRow} from './wgsl-binding-debug';\nimport {\n MODULE_WGSL_BINDING_DECLARATION_REGEXES,\n WGSL_BINDING_DECLARATION_REGEXES,\n WGSL_EXPLICIT_BINDING_DECLARATION_REGEXES,\n getFirstWGSLAutoBindingDeclarationMatch,\n getWGSLBindingDeclarationMatches,\n hasWGSLAutoBinding,\n replaceWGSLBindingDeclarationMatches,\n type WGSLBindingDeclarationMatch\n} from './wgsl-binding-scan';\n\nconst INJECT_SHADER_DECLARATIONS = `\\n\\n${DECLARATION_INJECT_MARKER}\\n`;\nconst RESERVED_APPLICATION_GROUP_0_BINDING_LIMIT = 100;\n\n/**\n * Precision prologue to inject before functions are injected in shader\n * TODO - extract any existing prologue in the fragment source and move it up...\n */\nconst FRAGMENT_SHADER_PROLOGUE = /* glsl */ `\\\nprecision highp float;\n`;\n\n/**\n * Options for `ShaderAssembler.assembleShaders()`\n */\nexport type AssembleShaderProps = AssembleShaderOptions & {\n platformInfo: PlatformInfo;\n /** WGSL: single shader source. */\n source?: string | null;\n /** GLSL vertex shader source. */\n vs?: string | null;\n /** GLSL fragment shader source. */\n fs?: string | null;\n};\n\nexport type AssembleShaderOptions = {\n /** information about the platform (which shader language & version, extensions etc.) */\n platformInfo: PlatformInfo;\n /** Inject shader id #defines */\n id?: string;\n /** Modules to be injected */\n modules?: ShaderModule[];\n /** Defines to be injected */\n defines?: Record;\n /** GLSL only: Overrides to be injected. In WGSL these are supplied during Pipeline creation time */\n constants?: Record;\n /** Hook functions */\n hookFunctions?: (ShaderHook | string)[];\n /** Code injections */\n inject?: Record;\n /** Whether to inject prologue */\n prologue?: boolean;\n /** logger object */\n log?: any;\n};\n\ntype AssembleStageOptions = {\n /** Inject shader id #defines */\n id?: string;\n /** Vertex shader */\n source: string;\n stage: 'vertex' | 'fragment';\n /** Modules to be injected */\n modules: any[];\n /** Defines to be injected */\n defines?: Record;\n /** GLSL only: Overrides to be injected. In WGSL these are supplied during Pipeline creation time */\n constants?: Record;\n /** Hook functions */\n hookFunctions?: (ShaderHook | string)[];\n /** Code injections */\n inject?: Record;\n /** Whether to inject prologue */\n prologue?: boolean;\n /** logger object */\n log?: any;\n /** @internal Stable per-assembler WGSL binding assignments. */\n _bindingRegistry?: Map;\n};\n\nexport type HookFunction = {hook: string; header: string; footer: string; signature?: string};\n\n/**\n * getUniforms function returned from the shader module system\n */\nexport type GetUniformsFunc = (opts: Record) => Record;\n\n/**\n * Inject a list of shader modules into a single shader source for WGSL\n */\nexport function assembleWGSLShader(\n options: AssembleShaderOptions & {\n /** Single WGSL shader */\n source: string;\n /** @internal Stable per-assembler WGSL binding assignments. */\n _bindingRegistry?: Map;\n }\n): {\n source: string;\n getUniforms: GetUniformsFunc;\n bindingAssignments: {moduleName: string; name: string; group: number; location: number}[];\n bindingTable: ShaderBindingDebugRow[];\n} {\n const modules = getShaderModuleDependencies(options.modules || []);\n const {source, bindingAssignments} = assembleShaderWGSL(options.platformInfo, {\n ...options,\n source: options.source,\n stage: 'vertex',\n modules\n });\n\n return {\n source,\n getUniforms: assembleGetUniforms(modules),\n bindingAssignments,\n bindingTable: getShaderBindingDebugRowsFromWGSL(source, bindingAssignments)\n };\n}\n\n/**\n * Injects dependent shader module sources into pair of main vertex/fragment shader sources for GLSL\n */\nexport function assembleGLSLShaderPair(\n options: AssembleShaderOptions & {\n /** Vertex shader */\n vs: string;\n /** Fragment shader */\n fs?: string;\n }\n): {\n vs: string;\n fs: string;\n getUniforms: GetUniformsFunc;\n} {\n const {vs, fs} = options;\n const modules = getShaderModuleDependencies(options.modules || []);\n\n return {\n vs: assembleShaderGLSL(options.platformInfo, {\n ...options,\n source: vs,\n stage: 'vertex',\n modules\n }),\n fs: assembleShaderGLSL(options.platformInfo, {\n ...options,\n // @ts-expect-error\n source: fs,\n stage: 'fragment',\n modules\n }),\n getUniforms: assembleGetUniforms(modules)\n };\n}\n\n/**\n * Pulls together complete source code for either a vertex or a fragment shader\n * adding prologues, requested module chunks, and any final injections.\n * @param gl\n * @param options\n * @returns\n */\nexport function assembleShaderWGSL(\n platformInfo: PlatformInfo,\n options: AssembleStageOptions\n): {source: string; bindingAssignments: WGSLBindingAssignment[]} {\n const {\n // id,\n source,\n stage,\n modules,\n // defines = {},\n hookFunctions = [],\n inject = {},\n log\n } = options;\n\n assert(typeof source === 'string', 'shader source must be a string');\n\n // const isVertex = type === 'vs';\n // const sourceLines = source.split('\\n');\n\n const coreSource = source;\n\n // Combine Module and Application Defines\n // const allDefines = {};\n // modules.forEach(module => {\n // Object.assign(allDefines, module.getDefines());\n // });\n // Object.assign(allDefines, defines);\n\n // Add platform defines (use these to work around platform-specific bugs and limitations)\n // Add common defines (GLSL version compatibility, feature detection)\n // Add precision declaration for fragment shaders\n let assembledSource = '';\n // prologue\n // ? `\\\n // ${getShaderNameDefine({id, source, type})}\n // ${getShaderType(type)}\n // ${getPlatformShaderDefines(platformInfo)}\n // ${getApplicationDefines(allDefines)}\n // ${isVertex ? '' : FRAGMENT_SHADER_PROLOGUE}\n // `\n // `;\n\n const hookFunctionMap = normalizeShaderHooks(hookFunctions);\n\n // Add source of dependent modules in resolved order\n const hookInjections: Record = {};\n const declInjections: Record = {};\n const mainInjections: Record = {};\n\n for (const key in inject) {\n const injection =\n typeof inject[key] === 'string' ? {injection: inject[key], order: 0} : inject[key];\n const match = /^(v|f)s:(#)?([\\w-]+)$/.exec(key);\n if (match) {\n const hash = match[2];\n const name = match[3];\n if (hash) {\n if (name === 'decl') {\n declInjections[key] = [injection as any];\n } else {\n mainInjections[key] = [injection as any];\n }\n } else {\n hookInjections[key] = [injection as any];\n }\n } else {\n // Regex injection\n mainInjections[key] = [injection as any];\n }\n }\n\n // TODO - hack until shadertool modules support WebGPU\n const modulesToInject = modules;\n const applicationRelocation = relocateWGSLApplicationBindings(coreSource);\n const usedBindingsByGroup = getUsedBindingsByGroupFromApplicationWGSL(\n applicationRelocation.source\n );\n const reservedBindingKeysByGroup = reserveRegisteredModuleBindings(\n modulesToInject,\n options._bindingRegistry,\n usedBindingsByGroup\n );\n const bindingAssignments: WGSLBindingAssignment[] = [];\n\n for (const module of modulesToInject) {\n if (log) {\n checkShaderModuleDeprecations(module, coreSource, log);\n }\n const relocation = relocateWGSLModuleBindings(\n getShaderModuleSource(module, 'wgsl', log),\n module,\n {\n usedBindingsByGroup,\n bindingRegistry: options._bindingRegistry,\n reservedBindingKeysByGroup\n }\n );\n bindingAssignments.push(...relocation.bindingAssignments);\n const moduleSource = relocation.source;\n // Add the module source, and a #define that declares it presence\n assembledSource += moduleSource;\n\n const injections = module.injections?.[stage] || {};\n for (const key in injections) {\n const match = /^(v|f)s:#([\\w-]+)$/.exec(key);\n if (match) {\n const name = match[2];\n const injectionType = name === 'decl' ? declInjections : mainInjections;\n injectionType[key] = injectionType[key] || [];\n injectionType[key].push(injections[key]);\n } else {\n hookInjections[key] = hookInjections[key] || [];\n hookInjections[key].push(injections[key]);\n }\n }\n }\n\n // For injectShader\n assembledSource += INJECT_SHADER_DECLARATIONS;\n\n assembledSource = injectShader(assembledSource, stage, declInjections);\n\n assembledSource += getShaderHooks(hookFunctionMap[stage], hookInjections);\n assembledSource += formatWGSLBindingAssignmentComments(bindingAssignments);\n\n // Add the version directive and actual source of this shader\n assembledSource += applicationRelocation.source;\n\n // Apply any requested shader injections\n assembledSource = injectShader(assembledSource, stage, mainInjections);\n\n assertNoUnresolvedAutoBindings(assembledSource);\n\n return {source: assembledSource, bindingAssignments};\n}\n\n/**\n * Pulls together complete source code for either a vertex or a fragment shader\n * adding prologues, requested module chunks, and any final injections.\n * @param gl\n * @param options\n * @returns\n */\nfunction assembleShaderGLSL(\n platformInfo: PlatformInfo,\n options: {\n id?: string;\n source: string;\n language?: 'glsl' | 'wgsl';\n stage: 'vertex' | 'fragment';\n modules: ShaderModule[];\n defines?: Record;\n hookFunctions?: any[];\n inject?: Record;\n prologue?: boolean;\n log?: any;\n }\n) {\n const {\n source,\n stage,\n language = 'glsl',\n modules,\n defines = {},\n hookFunctions = [],\n inject = {},\n prologue = true,\n log\n } = options;\n\n assert(typeof source === 'string', 'shader source must be a string');\n\n const sourceVersion = language === 'glsl' ? getShaderInfo(source).version : -1;\n const targetVersion = platformInfo.shaderLanguageVersion;\n\n const sourceVersionDirective = sourceVersion === 100 ? '#version 100' : '#version 300 es';\n\n const sourceLines = source.split('\\n');\n // TODO : keep all pre-processor statements at the beginning of the shader.\n const coreSource = sourceLines.slice(1).join('\\n');\n\n // Combine Module and Application Defines\n const allDefines = {};\n modules.forEach(module => {\n Object.assign(allDefines, module.defines);\n });\n Object.assign(allDefines, defines);\n\n // Add platform defines (use these to work around platform-specific bugs and limitations)\n // Add common defines (GLSL version compatibility, feature detection)\n // Add precision declaration for fragment shaders\n let assembledSource = '';\n switch (language) {\n case 'wgsl':\n break;\n case 'glsl':\n assembledSource = prologue\n ? `\\\n${sourceVersionDirective}\n\n// ----- PROLOGUE -------------------------\n${`#define SHADER_TYPE_${stage.toUpperCase()}`}\n\n${getPlatformShaderDefines(platformInfo)}\n${stage === 'fragment' ? FRAGMENT_SHADER_PROLOGUE : ''}\n\n// ----- APPLICATION DEFINES -------------------------\n\n${getApplicationDefines(allDefines)}\n\n`\n : `${sourceVersionDirective}\n`;\n break;\n }\n\n const hookFunctionMap = normalizeShaderHooks(hookFunctions);\n\n // Add source of dependent modules in resolved order\n const hookInjections: Record = {};\n const declInjections: Record = {};\n const mainInjections: Record = {};\n\n for (const key in inject) {\n const injection: ShaderInjection =\n typeof inject[key] === 'string' ? {injection: inject[key], order: 0} : inject[key];\n const match = /^(v|f)s:(#)?([\\w-]+)$/.exec(key);\n if (match) {\n const hash = match[2];\n const name = match[3];\n if (hash) {\n if (name === 'decl') {\n declInjections[key] = [injection];\n } else {\n mainInjections[key] = [injection];\n }\n } else {\n hookInjections[key] = [injection];\n }\n } else {\n // Regex injection\n mainInjections[key] = [injection];\n }\n }\n\n for (const module of modules) {\n if (log) {\n checkShaderModuleDeprecations(module, coreSource, log);\n }\n const moduleSource = getShaderModuleSource(module, stage, log);\n // Add the module source, and a #define that declares it presence\n assembledSource += moduleSource;\n\n const injections = module.instance?.normalizedInjections[stage] || {};\n for (const key in injections) {\n const match = /^(v|f)s:#([\\w-]+)$/.exec(key);\n if (match) {\n const name = match[2];\n const injectionType = name === 'decl' ? declInjections : mainInjections;\n injectionType[key] = injectionType[key] || [];\n injectionType[key].push(injections[key]);\n } else {\n hookInjections[key] = hookInjections[key] || [];\n hookInjections[key].push(injections[key]);\n }\n }\n }\n\n assembledSource += '// ----- MAIN SHADER SOURCE -------------------------';\n\n // For injectShader\n assembledSource += INJECT_SHADER_DECLARATIONS;\n\n assembledSource = injectShader(assembledSource, stage, declInjections);\n\n assembledSource += getShaderHooks(hookFunctionMap[stage], hookInjections);\n\n // Add the version directive and actual source of this shader\n assembledSource += coreSource;\n\n // Apply any requested shader injections\n assembledSource = injectShader(assembledSource, stage, mainInjections);\n\n if (language === 'glsl' && sourceVersion !== targetVersion) {\n assembledSource = transpileGLSLShader(assembledSource, stage);\n }\n\n if (language === 'glsl') {\n warnIfGLSLUniformBlocksAreNotStd140(assembledSource, stage, log);\n }\n\n return assembledSource.trim();\n}\n\n/**\n * Returns a combined `getUniforms` covering the options for all the modules,\n * the created function will pass on options to the inidividual `getUniforms`\n * function of each shader module and combine the results into one object that\n * can be passed to setUniforms.\n * @param modules\n * @returns\n */\nexport function assembleGetUniforms(modules: ShaderModule[]) {\n return function getUniforms(opts: Record): Record {\n const uniforms = {};\n for (const module of modules) {\n // `modules` is already sorted by dependency level. This guarantees that\n // modules have access to the uniforms that are generated by their dependencies.\n const moduleUniforms = module.getUniforms?.(opts, uniforms);\n Object.assign(uniforms, moduleUniforms);\n }\n return uniforms;\n };\n}\n\n/**\n * NOTE: Removed as id injection defeated caching of shaders\n * \n * Generate \"glslify-compatible\" SHADER_NAME defines\n * These are understood by the GLSL error parsing function\n * If id is provided and no SHADER_NAME constant is present in source, create one\n unction getShaderNameDefine(options: {\n id?: string;\n source: string;\n stage: 'vertex' | 'fragment';\n}): string {\n const {id, source, stage} = options;\n const injectShaderName = id && source.indexOf('SHADER_NAME') === -1;\n return injectShaderName\n ? `\n#define SHADER_NAME ${id}_${stage}`\n : '';\n}\n*/\n\n/** Generates application defines from an object of key value pairs */\nfunction getApplicationDefines(defines: Record = {}): string {\n let sourceText = '';\n for (const define in defines) {\n const value = defines[define];\n if (value || Number.isFinite(value)) {\n sourceText += `#define ${define.toUpperCase()} ${defines[define]}\\n`;\n }\n }\n return sourceText;\n}\n\n/** Extracts the source code chunk for the specified shader type from the named shader module */\nexport function getShaderModuleSource(\n module: ShaderModule,\n stage: 'vertex' | 'fragment' | 'wgsl',\n log?: any\n): string {\n let moduleSource;\n switch (stage) {\n case 'vertex':\n moduleSource = module.vs || '';\n break;\n case 'fragment':\n moduleSource = module.fs || '';\n break;\n case 'wgsl':\n moduleSource = module.source || '';\n break;\n default:\n assert(false);\n }\n\n if (!module.name) {\n throw new Error('Shader module must have a name');\n }\n\n validateShaderModuleUniformLayout(module, stage, {log});\n\n const moduleName = module.name.toUpperCase().replace(/[^0-9a-z]/gi, '_');\n let source = `\\\n// ----- MODULE ${module.name} ---------------\n\n`;\n if (stage !== 'wgsl') {\n source += `#define MODULE_${moduleName}\\n`;\n }\n source += `${moduleSource}\\n`;\n return source;\n}\n\ntype BindingRelocationContext = {\n usedBindingsByGroup: Map>;\n bindingRegistry?: Map;\n reservedBindingKeysByGroup: Map>;\n};\n\ntype WGSLBindingAssignment = {\n moduleName: string;\n name: string;\n group: number;\n location: number;\n};\n\ntype WGSLApplicationRelocationState = {\n sawSupportedBindingDeclaration: boolean;\n};\n\ntype WGSLRelocationState = {\n sawSupportedBindingDeclaration: boolean;\n nextHintedBindingLocation: number | null;\n};\n\ntype WGSLRelocationParams = {\n module: ShaderModule;\n context: BindingRelocationContext;\n bindingAssignments: WGSLBindingAssignment[];\n relocationState: WGSLRelocationState;\n};\n\nfunction getUsedBindingsByGroupFromApplicationWGSL(source: string): Map> {\n const usedBindingsByGroup = new Map>();\n\n for (const match of getWGSLBindingDeclarationMatches(\n source,\n WGSL_EXPLICIT_BINDING_DECLARATION_REGEXES\n )) {\n const location = Number(match.bindingToken);\n const group = Number(match.groupToken);\n\n validateApplicationWGSLBinding(group, location, match.name);\n registerUsedBindingLocation(\n usedBindingsByGroup,\n group,\n location,\n `application binding \"${match.name}\"`\n );\n }\n\n return usedBindingsByGroup;\n}\n\nfunction relocateWGSLApplicationBindings(source: string): {source: string} {\n const declarationMatches = getWGSLBindingDeclarationMatches(\n source,\n WGSL_BINDING_DECLARATION_REGEXES\n );\n const usedBindingsByGroup = new Map>();\n\n for (const declarationMatch of declarationMatches) {\n if (declarationMatch.bindingToken === 'auto') {\n continue;\n }\n\n const location = Number(declarationMatch.bindingToken);\n const group = Number(declarationMatch.groupToken);\n\n validateApplicationWGSLBinding(group, location, declarationMatch.name);\n registerUsedBindingLocation(\n usedBindingsByGroup,\n group,\n location,\n `application binding \"${declarationMatch.name}\"`\n );\n }\n\n const relocationState: WGSLApplicationRelocationState = {\n sawSupportedBindingDeclaration: declarationMatches.length > 0\n };\n\n const relocatedSource = replaceWGSLBindingDeclarationMatches(\n source,\n WGSL_BINDING_DECLARATION_REGEXES,\n declarationMatch =>\n relocateWGSLApplicationBindingMatch(declarationMatch, usedBindingsByGroup, relocationState)\n );\n\n if (hasWGSLAutoBinding(source) && !relocationState.sawSupportedBindingDeclaration) {\n throw new Error(\n 'Unsupported @binding(auto) declaration form in application WGSL. ' +\n 'Use adjacent \"@group(N)\" and \"@binding(auto)\" decorators followed by a bindable \"var\" declaration.'\n );\n }\n\n return {source: relocatedSource};\n}\n\nfunction relocateWGSLModuleBindings(\n moduleSource: string,\n module: ShaderModule,\n context: BindingRelocationContext\n): {source: string; bindingAssignments: WGSLBindingAssignment[]} {\n const bindingAssignments: WGSLBindingAssignment[] = [];\n const declarationMatches = getWGSLBindingDeclarationMatches(\n moduleSource,\n MODULE_WGSL_BINDING_DECLARATION_REGEXES\n );\n const relocationState: WGSLRelocationState = {\n sawSupportedBindingDeclaration: declarationMatches.length > 0,\n nextHintedBindingLocation:\n typeof module.firstBindingSlot === 'number' ? module.firstBindingSlot : null\n };\n\n const relocatedSource = replaceWGSLBindingDeclarationMatches(\n moduleSource,\n MODULE_WGSL_BINDING_DECLARATION_REGEXES,\n declarationMatch =>\n relocateWGSLModuleBindingMatch(declarationMatch, {\n module,\n context,\n bindingAssignments,\n relocationState\n })\n );\n\n if (hasWGSLAutoBinding(moduleSource) && !relocationState.sawSupportedBindingDeclaration) {\n throw new Error(\n `Unsupported @binding(auto) declaration form in module \"${module.name}\". ` +\n 'Use adjacent \"@group(N)\" and \"@binding(auto)\" decorators followed by a bindable \"var\" declaration.'\n );\n }\n\n return {source: relocatedSource, bindingAssignments};\n}\n\nfunction relocateWGSLModuleBindingMatch(\n declarationMatch: WGSLBindingDeclarationMatch,\n params: WGSLRelocationParams\n): string {\n const {module, context, bindingAssignments, relocationState} = params;\n\n const {match, bindingToken, groupToken, name} = declarationMatch;\n const group = Number(groupToken);\n\n if (bindingToken === 'auto') {\n const registryKey = getBindingRegistryKey(group, module.name, name);\n const registryLocation = context.bindingRegistry?.get(registryKey);\n const location =\n registryLocation !== undefined\n ? registryLocation\n : relocationState.nextHintedBindingLocation === null\n ? allocateAutoBindingLocation(group, context.usedBindingsByGroup)\n : allocateAutoBindingLocation(\n group,\n context.usedBindingsByGroup,\n relocationState.nextHintedBindingLocation\n );\n validateModuleWGSLBinding(module.name, group, location, name);\n if (\n registryLocation !== undefined &&\n claimReservedBindingLocation(context.reservedBindingKeysByGroup, group, location, registryKey)\n ) {\n bindingAssignments.push({moduleName: module.name, name, group, location});\n return match.replace(/@binding\\(\\s*auto\\s*\\)/, `@binding(${location})`);\n }\n registerUsedBindingLocation(\n context.usedBindingsByGroup,\n group,\n location,\n `module \"${module.name}\" binding \"${name}\"`\n );\n context.bindingRegistry?.set(registryKey, location);\n bindingAssignments.push({moduleName: module.name, name, group, location});\n if (relocationState.nextHintedBindingLocation !== null && registryLocation === undefined) {\n relocationState.nextHintedBindingLocation = location + 1;\n }\n return match.replace(/@binding\\(\\s*auto\\s*\\)/, `@binding(${location})`);\n }\n\n const location = Number(bindingToken);\n validateModuleWGSLBinding(module.name, group, location, name);\n registerUsedBindingLocation(\n context.usedBindingsByGroup,\n group,\n location,\n `module \"${module.name}\" binding \"${name}\"`\n );\n bindingAssignments.push({moduleName: module.name, name, group, location});\n return match;\n}\n\nfunction relocateWGSLApplicationBindingMatch(\n declarationMatch: WGSLBindingDeclarationMatch,\n usedBindingsByGroup: Map>,\n relocationState: WGSLApplicationRelocationState\n): string {\n const {match, bindingToken, groupToken, name} = declarationMatch;\n const group = Number(groupToken);\n\n if (bindingToken === 'auto') {\n const location = allocateApplicationAutoBindingLocation(group, usedBindingsByGroup);\n validateApplicationWGSLBinding(group, location, name);\n registerUsedBindingLocation(\n usedBindingsByGroup,\n group,\n location,\n `application binding \"${name}\"`\n );\n return match.replace(/@binding\\(\\s*auto\\s*\\)/, `@binding(${location})`);\n }\n\n relocationState.sawSupportedBindingDeclaration = true;\n return match;\n}\n\nfunction reserveRegisteredModuleBindings(\n modules: ShaderModule[],\n bindingRegistry: Map | undefined,\n usedBindingsByGroup: Map>\n): Map> {\n const reservedBindingKeysByGroup = new Map>();\n if (!bindingRegistry) {\n return reservedBindingKeysByGroup;\n }\n\n for (const module of modules) {\n for (const binding of getModuleWGSLBindingDeclarations(module)) {\n const registryKey = getBindingRegistryKey(binding.group, module.name, binding.name);\n const location = bindingRegistry.get(registryKey);\n if (location !== undefined) {\n const reservedBindingKeys =\n reservedBindingKeysByGroup.get(binding.group) || new Map();\n const existingReservation = reservedBindingKeys.get(location);\n if (existingReservation && existingReservation !== registryKey) {\n throw new Error(\n `Duplicate WGSL binding reservation for modules \"${existingReservation}\" and \"${registryKey}\": group ${binding.group}, binding ${location}.`\n );\n }\n\n registerUsedBindingLocation(\n usedBindingsByGroup,\n binding.group,\n location,\n `registered module binding \"${registryKey}\"`\n );\n reservedBindingKeys.set(location, registryKey);\n reservedBindingKeysByGroup.set(binding.group, reservedBindingKeys);\n }\n }\n }\n\n return reservedBindingKeysByGroup;\n}\n\nfunction claimReservedBindingLocation(\n reservedBindingKeysByGroup: Map>,\n group: number,\n location: number,\n registryKey: string\n): boolean {\n const reservedBindingKeys = reservedBindingKeysByGroup.get(group);\n if (!reservedBindingKeys) {\n return false;\n }\n\n const reservedKey = reservedBindingKeys.get(location);\n if (!reservedKey) {\n return false;\n }\n if (reservedKey !== registryKey) {\n throw new Error(\n `Registered module binding \"${registryKey}\" collided with \"${reservedKey}\": group ${group}, binding ${location}.`\n );\n }\n return true;\n}\n\nfunction getModuleWGSLBindingDeclarations(module: ShaderModule): {name: string; group: number}[] {\n const declarations: {name: string; group: number}[] = [];\n const moduleSource = module.source || '';\n\n for (const match of getWGSLBindingDeclarationMatches(\n moduleSource,\n MODULE_WGSL_BINDING_DECLARATION_REGEXES\n )) {\n declarations.push({\n name: match.name,\n group: Number(match.groupToken)\n });\n }\n\n return declarations;\n}\n\nfunction validateApplicationWGSLBinding(group: number, location: number, name: string): void {\n if (group === 0 && location >= RESERVED_APPLICATION_GROUP_0_BINDING_LIMIT) {\n throw new Error(\n `Application binding \"${name}\" in group 0 uses reserved binding ${location}. ` +\n `Application-owned explicit group-0 bindings must stay below ${RESERVED_APPLICATION_GROUP_0_BINDING_LIMIT}.`\n );\n }\n}\n\nfunction validateModuleWGSLBinding(\n moduleName: string,\n group: number,\n location: number,\n name: string\n): void {\n if (group === 0 && location < RESERVED_APPLICATION_GROUP_0_BINDING_LIMIT) {\n throw new Error(\n `Module \"${moduleName}\" binding \"${name}\" in group 0 uses reserved application binding ${location}. ` +\n `Module-owned explicit group-0 bindings must be ${RESERVED_APPLICATION_GROUP_0_BINDING_LIMIT} or higher.`\n );\n }\n}\n\nfunction registerUsedBindingLocation(\n usedBindingsByGroup: Map>,\n group: number,\n location: number,\n label: string\n): void {\n const usedBindings = usedBindingsByGroup.get(group) || new Set();\n if (usedBindings.has(location)) {\n throw new Error(\n `Duplicate WGSL binding assignment for ${label}: group ${group}, binding ${location}.`\n );\n }\n usedBindings.add(location);\n usedBindingsByGroup.set(group, usedBindings);\n}\n\nfunction allocateAutoBindingLocation(\n group: number,\n usedBindingsByGroup: Map>,\n preferredBindingLocation?: number\n): number {\n const usedBindings = usedBindingsByGroup.get(group) || new Set();\n let nextBinding =\n preferredBindingLocation ??\n (group === 0\n ? RESERVED_APPLICATION_GROUP_0_BINDING_LIMIT\n : usedBindings.size > 0\n ? Math.max(...usedBindings) + 1\n : 0);\n\n while (usedBindings.has(nextBinding)) {\n nextBinding++;\n }\n\n return nextBinding;\n}\n\nfunction allocateApplicationAutoBindingLocation(\n group: number,\n usedBindingsByGroup: Map>\n): number {\n const usedBindings = usedBindingsByGroup.get(group) || new Set();\n let nextBinding = 0;\n\n while (usedBindings.has(nextBinding)) {\n nextBinding++;\n }\n\n return nextBinding;\n}\n\nfunction assertNoUnresolvedAutoBindings(source: string): void {\n const unresolvedBinding = getFirstWGSLAutoBindingDeclarationMatch(\n source,\n MODULE_WGSL_BINDING_DECLARATION_REGEXES\n );\n if (!unresolvedBinding) {\n return;\n }\n\n const moduleName = getWGSLModuleNameAtIndex(source, unresolvedBinding.index);\n if (moduleName) {\n throw new Error(\n `Unresolved @binding(auto) for module \"${moduleName}\" binding \"${unresolvedBinding.name}\" remained in assembled WGSL source.`\n );\n }\n\n if (isInApplicationWGSLSection(source, unresolvedBinding.index)) {\n throw new Error(\n `Unresolved @binding(auto) for application binding \"${unresolvedBinding.name}\" remained in assembled WGSL source.`\n );\n }\n\n throw new Error(\n `Unresolved @binding(auto) remained in assembled WGSL source near \"${formatWGSLSourceSnippet(unresolvedBinding.match)}\".`\n );\n}\n\nfunction formatWGSLBindingAssignmentComments(bindingAssignments: WGSLBindingAssignment[]): string {\n if (bindingAssignments.length === 0) {\n return '';\n }\n\n let source = '// ----- MODULE WGSL BINDING ASSIGNMENTS ---------------\\n';\n for (const bindingAssignment of bindingAssignments) {\n source += `// ${bindingAssignment.moduleName}.${bindingAssignment.name} -> @group(${bindingAssignment.group}) @binding(${bindingAssignment.location})\\n`;\n }\n source += '\\n';\n return source;\n}\n\nfunction getBindingRegistryKey(group: number, moduleName: string, bindingName: string): string {\n return `${group}:${moduleName}:${bindingName}`;\n}\n\nfunction getWGSLModuleNameAtIndex(source: string, index: number): string | undefined {\n const moduleHeaderRegex = /^\\/\\/ ----- MODULE ([^\\n]+) ---------------$/gm;\n let moduleName: string | undefined;\n let match: RegExpExecArray | null;\n\n match = moduleHeaderRegex.exec(source);\n while (match && match.index <= index) {\n moduleName = match[1];\n match = moduleHeaderRegex.exec(source);\n }\n\n return moduleName;\n}\n\nfunction isInApplicationWGSLSection(source: string, index: number): boolean {\n const injectionMarkerIndex = source.indexOf(INJECT_SHADER_DECLARATIONS);\n return injectionMarkerIndex >= 0 ? index > injectionMarkerIndex : true;\n}\n\nfunction formatWGSLSourceSnippet(source: string): string {\n return source.replace(/\\s+/g, ' ').trim();\n}\n\n/*\nfunction getHookFunctions(\n hookFunctions: Record,\n hookInjections: Record\n): string {\n let result = '';\n for (const hookName in hookFunctions) {\n const hookFunction = hookFunctions[hookName];\n result += `void ${hookFunction.signature} {\\n`;\n if (hookFunction.header) {\n result += ` ${hookFunction.header}`;\n }\n if (hookInjections[hookName]) {\n const injections = hookInjections[hookName];\n injections.sort((a: {order: number}, b: {order: number}): number => a.order - b.order);\n for (const injection of injections) {\n result += ` ${injection.injection}\\n`;\n }\n }\n if (hookFunction.footer) {\n result += ` ${hookFunction.footer}`;\n }\n result += '}\\n';\n }\n\n return result;\n}\n\nfunction normalizeHookFunctions(hookFunctions: (string | HookFunction)[]): {\n vs: Record;\n fs: Record;\n} {\n const result: {vs: Record; fs: Record} = {\n vs: {},\n fs: {}\n };\n\n hookFunctions.forEach((hookFunction: string | HookFunction) => {\n let opts: HookFunction;\n let hook: string;\n if (typeof hookFunction !== 'string') {\n opts = hookFunction;\n hook = opts.hook;\n } else {\n opts = {} as HookFunction;\n hook = hookFunction;\n }\n hook = hook.trim();\n const [stage, signature] = hook.split(':');\n const name = hook.replace(/\\(.+/, '');\n if (stage !== 'vs' && stage !== 'fs') {\n throw new Error(stage);\n }\n result[stage][name] = Object.assign(opts, {signature});\n });\n\n return result;\n}\n*/\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nconst DEFINE_NAME_PATTERN = '([a-zA-Z_][a-zA-Z0-9_]*)';\nconst IFDEF_REGEXP = new RegExp(`^\\\\s*\\\\#\\\\s*ifdef\\\\s*${DEFINE_NAME_PATTERN}\\\\s*$`);\nconst IFNDEF_REGEXP = new RegExp(`^\\\\s*\\\\#\\\\s*ifndef\\\\s*${DEFINE_NAME_PATTERN}\\\\s*(?:\\\\/\\\\/.*)?$`);\nconst ELSE_REGEXP = /^\\s*\\#\\s*else\\s*(?:\\/\\/.*)?$/;\nconst ENDIF_REGEXP = /^\\s*\\#\\s*endif\\s*$/;\nconst IFDEF_WITH_COMMENT_REGEXP = new RegExp(\n `^\\\\s*\\\\#\\\\s*ifdef\\\\s*${DEFINE_NAME_PATTERN}\\\\s*(?:\\\\/\\\\/.*)?$`\n);\nconst ENDIF_WITH_COMMENT_REGEXP = /^\\s*\\#\\s*endif\\s*(?:\\/\\/.*)?$/;\n\nexport type PreprocessorOptions = {\n defines?: Record;\n};\n\nexport function preprocess(source: string, options?: PreprocessorOptions): string {\n const lines = source.split('\\n');\n const output: string[] = [];\n\n const conditionalStack: Array<{\n parentActive: boolean;\n branchTaken: boolean;\n active: boolean;\n }> = [];\n let conditional = true;\n\n for (const line of lines) {\n const matchIf = line.match(IFDEF_WITH_COMMENT_REGEXP) || line.match(IFDEF_REGEXP);\n const matchIfNot = line.match(IFNDEF_REGEXP);\n const matchElse = line.match(ELSE_REGEXP);\n const matchEnd = line.match(ENDIF_WITH_COMMENT_REGEXP) || line.match(ENDIF_REGEXP);\n\n if (matchIf || matchIfNot) {\n const defineName = (matchIf || matchIfNot)?.[1];\n const defineValue: boolean = Boolean(options?.defines?.[defineName!]);\n const branchTaken: boolean = matchIf ? defineValue : !defineValue;\n const active: boolean = conditional && branchTaken;\n conditionalStack.push({parentActive: conditional, branchTaken, active});\n conditional = active;\n } else if (matchElse) {\n const currentConditional = conditionalStack[conditionalStack.length - 1];\n if (!currentConditional) {\n throw new Error('Encountered #else without matching #ifdef or #ifndef');\n }\n currentConditional.active =\n currentConditional.parentActive && !currentConditional.branchTaken;\n currentConditional.branchTaken = true;\n conditional = currentConditional.active;\n } else if (matchEnd) {\n conditionalStack.pop();\n conditional = conditionalStack.length\n ? conditionalStack[conditionalStack.length - 1].active\n : true;\n } else if (conditional) {\n output.push(line);\n }\n }\n\n if (conditionalStack.length > 0) {\n throw new Error('Unterminated conditional block in shader source');\n }\n\n return output.join('\\n');\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ShaderModule} from './shader-module/shader-module';\nimport {initializeShaderModules} from './shader-module/shader-module';\nimport {\n AssembleShaderProps,\n GetUniformsFunc,\n assembleWGSLShader,\n assembleGLSLShaderPair\n} from './shader-assembly/assemble-shaders';\nimport {\n getShaderBindingDebugRowsFromWGSL,\n type ShaderBindingDebugRow\n} from './shader-assembly/wgsl-binding-debug';\nimport {preprocess} from './preprocessor/preprocessor';\n\n/**\n * A stateful version of `assembleShaders` that can be used to assemble shaders.\n * Supports setting of default modules and hooks.\n */\nexport class ShaderAssembler {\n /** Default ShaderAssembler instance */\n static defaultShaderAssembler: ShaderAssembler;\n /** Hook functions */\n private readonly _hookFunctions: any[] = [];\n /** Shader modules */\n private _defaultModules: ShaderModule[] = [];\n /** Stable per-run WGSL auto-binding assignments keyed by group/module/binding. */\n private readonly _wgslBindingRegistry = new Map();\n\n /**\n * A default shader assembler instance - the natural place to register default modules and hooks\n * @returns\n */\n static getDefaultShaderAssembler(): ShaderAssembler {\n ShaderAssembler.defaultShaderAssembler =\n ShaderAssembler.defaultShaderAssembler || new ShaderAssembler();\n return ShaderAssembler.defaultShaderAssembler;\n }\n\n /**\n * Add a default module that does not have to be provided with every call to assembleShaders()\n */\n addDefaultModule(module: ShaderModule): void {\n if (\n !this._defaultModules.find(\n m => m.name === (typeof module === 'string' ? module : module.name)\n )\n ) {\n this._defaultModules.push(module);\n }\n }\n\n /**\n * Remove a default module\n */\n removeDefaultModule(module: ShaderModule): void {\n const moduleName = typeof module === 'string' ? module : module.name;\n this._defaultModules = this._defaultModules.filter(m => m.name !== moduleName);\n }\n\n /**\n * Register a shader hook\n * @param hook\n * @param opts\n */\n addShaderHook(hook: string, opts?: any): void {\n if (opts) {\n hook = Object.assign(opts, {hook});\n }\n this._hookFunctions.push(hook);\n }\n\n /**\n * Assemble a WGSL unified shader\n * @param platformInfo\n * @param props\n * @returns\n */\n assembleWGSLShader(props: AssembleShaderProps): {\n source: string;\n getUniforms: GetUniformsFunc;\n modules: ShaderModule[];\n bindingAssignments: {moduleName: string; name: string; group: number; location: number}[];\n bindingTable: ShaderBindingDebugRow[];\n } {\n const modules = this._getModuleList(props.modules); // Combine with default modules\n const hookFunctions = this._hookFunctions; // TODO - combine with default hook functions\n const {source, getUniforms, bindingAssignments} = assembleWGSLShader({\n ...props,\n // @ts-expect-error\n source: props.source,\n _bindingRegistry: this._wgslBindingRegistry,\n modules,\n hookFunctions\n });\n const defines = {\n ...modules.reduce>((accumulator, module) => {\n Object.assign(accumulator, module.defines);\n return accumulator;\n }, {}),\n ...props.defines\n };\n // WGSL does not have built-in preprocessing support (just compile time constants)\n const preprocessedSource =\n props.platformInfo.shaderLanguage === 'wgsl' ? preprocess(source, {defines}) : source;\n return {\n source: preprocessedSource,\n getUniforms,\n modules,\n bindingAssignments,\n bindingTable: getShaderBindingDebugRowsFromWGSL(preprocessedSource, bindingAssignments)\n };\n }\n\n /**\n * Assemble a pair of shaders into a single shader program\n * @param platformInfo\n * @param props\n * @returns\n */\n assembleGLSLShaderPair(props: AssembleShaderProps): {\n vs: string;\n fs: string;\n getUniforms: GetUniformsFunc;\n modules: ShaderModule[];\n } {\n const modules = this._getModuleList(props.modules); // Combine with default modules\n const hookFunctions = this._hookFunctions; // TODO - combine with default hook functions\n const assembled = assembleGLSLShaderPair({\n ...props,\n // @ts-expect-error\n vs: props.vs,\n // @ts-expect-error\n fs: props.fs,\n modules,\n hookFunctions\n });\n\n return {...assembled, modules};\n }\n\n /**\n * Dedupe and combine with default modules\n */\n _getModuleList(appModules: ShaderModule[] = []): ShaderModule[] {\n const modules = new Array(this._defaultModules.length + appModules.length);\n const seen: Record = {};\n let count = 0;\n\n for (let i = 0, len = this._defaultModules.length; i < len; ++i) {\n const module = this._defaultModules[i];\n const name = module.name;\n modules[count++] = module;\n seen[name] = true;\n }\n\n for (let i = 0, len = appModules.length; i < len; ++i) {\n const module = appModules[i];\n const name = module.name;\n if (!seen[name]) {\n modules[count++] = module;\n seen[name] = true;\n }\n }\n\n modules.length = count;\n\n initializeShaderModules(modules);\n return modules;\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nconst FS_GLES = /* glsl */ `\\\nout vec4 transform_output;\nvoid main() {\n transform_output = vec4(0);\n}`;\nconst FS300 = `#version 300 es\\n${FS_GLES}`;\n\ntype QualifierInfo = {\n qualifier: string;\n type: string;\n name: string;\n};\n\n// Prase given glsl line and return qualifier details or null\nexport function getQualifierDetails(\n line: string,\n qualifiers: string | string[]\n): QualifierInfo | null {\n qualifiers = Array.isArray(qualifiers) ? qualifiers : [qualifiers];\n const words = line.replace(/^\\s+/, '').split(/\\s+/);\n // TODO add support for precession qualifiers (highp, mediump and lowp)\n const [qualifier, type, definition] = words;\n if (!qualifiers.includes(qualifier) || !type || !definition) {\n return null;\n }\n const name = definition.split(';')[0];\n return {qualifier, type, name};\n}\n\n/**\n * Given the shader input and output variable names,\n * builds and return a pass through fragment shader.\n */\nexport function getPassthroughFS(options?: {\n input?: string;\n inputChannels?: 1 | 2 | 3 | 4;\n output?: string;\n}): string {\n const {input, inputChannels, output} = options || {};\n if (!input) {\n // Default shader\n return FS300;\n }\n if (!inputChannels) {\n throw new Error('inputChannels');\n }\n const inputType = channelCountToType(inputChannels);\n const outputValue = convertToVec4(input, inputChannels);\n return `\\\n#version 300 es\nin ${inputType} ${input};\nout vec4 ${output};\nvoid main() {\n ${output} = ${outputValue};\n}`;\n}\n\n/** convert glsl type to suffix */\nexport function typeToChannelSuffix(type: string): 'x' | 'xy' | 'xyz' | 'xyzw' {\n // biome-ignore format: preserve layout\n switch (type) {\n case 'float': return 'x';\n case 'vec2': return 'xy';\n case 'vec3': return 'xyz';\n case 'vec4': return 'xyzw';\n default:\n throw new Error(type);\n }\n}\n\n/** convert glsl type to channel count */\nexport function typeToChannelCount(type: string): 1 | 2 | 3 | 4 {\n // biome-ignore format: preserve layout\n switch (type) {\n case 'float': return 1;\n case 'vec2': return 2;\n case 'vec3': return 3;\n case 'vec4': return 4;\n default:\n throw new Error(type);\n }\n}\nfunction channelCountToType(channels: 1 | 2 | 3 | 4): 'float' | 'vec2' | 'vec3' | 'vec4' {\n // biome-ignore format: preserve layout\n switch (channels) {\n case 1: return 'float';\n case 2: return 'vec2';\n case 3: return 'vec3';\n case 4: return 'vec4';\n default:\n throw new Error(`invalid channels: ${channels}`);\n }\n}\n\n/** Returns glsl instruction for converting to vec4 */\nexport function convertToVec4(variable: string, channels: 1 | 2 | 3 | 4): string {\n // biome-ignore format: preserve layout\n switch (channels) {\n case 1: return `vec4(${variable}, 0.0, 0.0, 1.0)`;\n case 2: return `vec4(${variable}, 0.0, 1.0)`;\n case 3: return `vec4(${variable}, 1.0)`;\n case 4: return variable;\n default:\n throw new Error(`invalid channels: ${channels}`);\n }\n}\n","// math.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/* eslint-disable no-shadow */ // radians and degrees are common variable names\n\nimport type {NumericArray} from '@math.gl/types';\n\nimport type {MathArray} from '../classes/base/math-array';\n\nconst RADIANS_TO_DEGREES = (1 / Math.PI) * 180;\nconst DEGREES_TO_RADIANS = (1 / 180) * Math.PI;\n\nexport type ConfigurationOptions = {\n EPSILON: number;\n debug?: boolean;\n precision: number;\n printTypes?: boolean;\n printDegrees?: boolean;\n printRowMajor?: boolean;\n _cartographicRadians?: boolean;\n};\n\nconst DEFAULT_CONFIG: Required = {\n EPSILON: 1e-12,\n debug: false,\n precision: 4,\n printTypes: false,\n printDegrees: false,\n printRowMajor: true,\n _cartographicRadians: false\n};\n\n// We use a global field to store the config\ndeclare global {\n // eslint-disable-next-line no-var\n var mathgl: {\n config: Required;\n };\n}\n\n// Configuration is truly global as of v3.6 to ensure single config even if multiple copies of math.gl\n// Multiple copies of config can be quite tricky to debug...\nglobalThis.mathgl = globalThis.mathgl || {config: {...DEFAULT_CONFIG}};\n\nexport const config = globalThis.mathgl.config;\n\nexport function configure(options: Partial): ConfigurationOptions {\n // Only copy existing keys\n Object.assign(config, options);\n return config;\n}\n\n/**\n * Formats a value into a string\n * @param value\n * @param param1\n * @returns\n */\nexport function formatValue(\n value: number,\n {precision = config.precision}: {precision?: number} = {}\n): string {\n value = round(value);\n // get rid of trailing zeros\n return `${parseFloat(value.toPrecision(precision))}`;\n}\n\n/**\n * Check if value is an \"array\"\n * Returns `true` if value is either an array or a typed array\n * Note: returns `false` for `ArrayBuffer` and `DataView` instances\n * @note isTypedArray and isNumericArray are often more useful in TypeScript\n */\nexport function isArray(value: unknown): boolean {\n return Array.isArray(value) || (ArrayBuffer.isView(value) && !(value instanceof DataView));\n}\n\nexport function clone(array: NumericArray | MathArray): NumericArray {\n return 'clone' in array ? array.clone() : array.slice();\n}\n\nexport function toRadians(degrees: number): number;\nexport function toRadians(degrees: NumericArray): NumericArray;\n\nexport function toRadians(degrees: number | NumericArray): number | NumericArray {\n return radians(degrees as NumericArray);\n}\n\nexport function toDegrees(degrees: number): number;\nexport function toDegrees(degrees: NumericArray): NumericArray;\n\nexport function toDegrees(radians: number | NumericArray): number | NumericArray {\n return degrees(radians as NumericArray);\n}\n\n// GLSL math function equivalents - Works on both single values and vectors\n\n/**\n * \"GLSL equivalent\" radians: Works on single values and vectors\n */\nexport function radians(degrees: number): number;\nexport function radians(degrees: NumericArray, result?: NumericArray): NumericArray;\n\nexport function radians(\n degrees: number | NumericArray,\n result?: NumericArray\n): number | NumericArray {\n return map(degrees, (degrees) => degrees * DEGREES_TO_RADIANS, result);\n}\n\n/**\n * \"GLSL equivalent\" degrees: Works on single values and vectors\n */\nexport function degrees(radians: number): number;\nexport function degrees(radians: NumericArray, result?: NumericArray): NumericArray;\n\nexport function degrees(\n radians: number | NumericArray,\n result?: NumericArray\n): number | NumericArray {\n return map(radians, (radians) => radians * RADIANS_TO_DEGREES, result);\n}\n\n/**\n * \"GLSL equivalent\" of `Math.sin`: Works on single values and vectors\n * @deprecated\n */\nexport function sin(radians: number | NumericArray, result?: NumericArray): number | NumericArray {\n return map(radians, (angle) => Math.sin(angle), result);\n}\n\n/**\n * \"GLSL equivalent\" of `Math.cos`: Works on single values and vectors\n * @deprecated\n */\nexport function cos(radians: number | NumericArray, result?: NumericArray): number | NumericArray {\n return map(radians, (angle) => Math.cos(angle), result);\n}\n\n/**\n * \"GLSL equivalent\" of `Math.tan`: Works on single values and vectors\n * @deprecated\n */\nexport function tan(radians: number | NumericArray, result?: NumericArray): number | NumericArray {\n return map(radians, (angle) => Math.tan(angle), result);\n}\n\n/**\n * \"GLSL equivalent\" of `Math.asin`: Works on single values and vectors\n * @deprecated\n */\nexport function asin(radians: number | NumericArray, result?: NumericArray): number | NumericArray {\n return map(radians, (angle) => Math.asin(angle), result);\n}\n\n/**\n * \"GLSL equivalent\" of `Math.acos`: Works on single values and vectors\n * @deprecated\n */\nexport function acos(radians: number | NumericArray, result?: NumericArray): number | NumericArray {\n return map(radians, (angle) => Math.acos(angle), result);\n}\n\n/**\n * \"GLSL equivalent\" of `Math.atan`: Works on single values and vectors\n * @deprecated\n */\nexport function atan(radians: number | NumericArray, result?: NumericArray): number | NumericArray {\n return map(radians, (angle) => Math.atan(angle), result);\n}\n\n/**\n * GLSL style value clamping: Works on single values and vectors\n */\nexport function clamp(value: number, min: number, max: number): number;\nexport function clamp(value: NumericArray, min: number, max: number): NumericArray;\n\nexport function clamp(\n value: number | NumericArray,\n min: number,\n max: number\n): number | NumericArray {\n return map(value, (value) => Math.max(min, Math.min(max, value)));\n}\n\n/**\n * Interpolate between two numbers or two arrays\n */\nexport function lerp(a: number, b: number, t: number): number;\nexport function lerp(a: NumericArray, b: NumericArray, t: number): NumericArray;\n\nexport function lerp(\n a: number | NumericArray,\n b: number | NumericArray,\n t: number\n): number | NumericArray {\n if (isArray(a)) {\n return (a as NumericArray).map((ai: number, i: number) => lerp(ai, (b as NumericArray)[i], t));\n }\n return t * (b as number) + (1 - t) * (a as number);\n}\n\n/* eslint-disable */\n\n/**\n * Compares any two math objects, using `equals` method if available.\n * @param a\n * @param b\n * @param epsilon\n * @returns\n */\nexport function equals(a: any, b: any, epsilon?: number): boolean {\n const oldEpsilon = config.EPSILON;\n if (epsilon) {\n config.EPSILON = epsilon;\n }\n try {\n if (a === b) {\n return true;\n }\n if (isArray(a) && isArray(b)) {\n if (a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; ++i) {\n // eslint-disable-next-line max-depth\n if (!equals(a[i], b[i])) {\n return false;\n }\n }\n return true;\n }\n if (a && a.equals) {\n return a.equals(b);\n }\n if (b && b.equals) {\n return b.equals(a);\n }\n if (typeof a === 'number' && typeof b === 'number') {\n return Math.abs(a - b) <= config.EPSILON * Math.max(1, Math.abs(a), Math.abs(b));\n }\n return false;\n } finally {\n config.EPSILON = oldEpsilon;\n }\n}\n\nexport function exactEquals(a: any, b: any): boolean {\n if (a === b) {\n return true;\n }\n if (a && typeof a === 'object' && b && typeof b === 'object') {\n if (a.constructor !== b.constructor) {\n return false;\n }\n if (a.exactEquals) {\n return a.exactEquals(b);\n }\n }\n if (isArray(a) && isArray(b)) {\n if (a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; ++i) {\n if (!exactEquals(a[i], b[i])) {\n return false;\n }\n }\n return true;\n }\n return false;\n}\n\n/* eslint-enable */\n\nexport function withEpsilon(epsilon: number, func: () => T): T {\n const oldPrecision = config.EPSILON;\n config.EPSILON = epsilon;\n let value: T;\n try {\n value = func();\n } finally {\n config.EPSILON = oldPrecision;\n }\n return value;\n}\n\n// HELPERS\n\nfunction round(value: number): number {\n return Math.round(value / config.EPSILON) * config.EPSILON;\n}\n\n// If the array has a clone function, calls it, otherwise returns a copy\nfunction duplicateArray(array: NumericArray): NumericArray {\n // @ts-expect-error We check for math.gl class methods\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n return array.clone ? (array.clone() as NumericArray) : (new Array(array.length) as number[]);\n}\n\n// If the argument value is an array, applies the func element wise,\n// otherwise applies func to the argument value\nfunction map(\n value: number | NumericArray,\n func: (x: number, index?: number, resultArray?: NumericArray) => number,\n result?: NumericArray\n): number | NumericArray {\n if (isArray(value)) {\n const array = value as NumericArray;\n result = result || duplicateArray(array);\n for (let i = 0; i < result.length && i < array.length; ++i) {\n const val = typeof value === 'number' ? value : value[i];\n result[i] = func(val, i, result);\n }\n return result;\n }\n return func(value as number);\n}\n","// math.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {NumericArray} from '@math.gl/types';\nimport {ConfigurationOptions, config, formatValue, equals, isArray} from '../../lib/common';\n\n/** Base class for vectors and matrices */\nexport abstract class MathArray extends Array {\n /** Number of elements (values) in this array */\n abstract get ELEMENTS(): number;\n\n abstract copy(vector: Readonly): this;\n\n abstract fromObject(object: Record): this;\n\n // Common methods\n\n /**\n * Clone the current object\n * @returns a new copy of this object\n */\n clone(): this {\n // @ts-expect-error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature.\n return new this.constructor().copy(this); // eslint-disable-line\n }\n\n fromArray(array: Readonly, offset: number = 0): this {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] = array[i + offset];\n }\n return this.check();\n }\n\n toArray(targetArray: TypedArray, offset?: number): TypedArray;\n toArray(targetArray?: number[], offset?: number): NumericArray;\n\n toArray(targetArray: NumericArray = [], offset: number = 0): NumericArray {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n targetArray[offset + i] = this[i];\n }\n return targetArray;\n }\n\n toObject(targetObject: Record): Record {\n return targetObject;\n }\n\n from(arrayOrObject: Readonly | Record): this {\n return Array.isArray(arrayOrObject)\n ? this.copy(arrayOrObject)\n : // @ts-ignore\n this.fromObject(arrayOrObject);\n }\n\n to>(arrayOrObject: T): T {\n // @ts-ignore\n if (arrayOrObject === this) {\n return this as T;\n }\n // @ts-expect-error TS2339: Property 'toObject' does not exist on type 'MathArray'.\n return isArray(arrayOrObject) ? this.toArray(arrayOrObject) : this.toObject(arrayOrObject);\n }\n\n toTarget(target: this): this {\n return target ? this.to(target) : this;\n }\n\n /** @deprecated */\n toFloat32Array(): Float32Array {\n return new Float32Array(this);\n }\n\n override toString(): string {\n return this.formatString(config);\n }\n\n /** Formats string according to options */\n formatString(opts: ConfigurationOptions): string {\n let string = '';\n for (let i = 0; i < this.ELEMENTS; ++i) {\n string += (i > 0 ? ', ' : '') + formatValue(this[i], opts);\n }\n return `${opts.printTypes ? this.constructor.name : ''}[${string}]`;\n }\n\n equals(array: Readonly): boolean {\n if (!array || this.length !== array.length) {\n return false;\n }\n for (let i = 0; i < this.ELEMENTS; ++i) {\n if (!equals(this[i], array[i])) {\n return false;\n }\n }\n return true;\n }\n\n exactEquals(array: Readonly): boolean {\n if (!array || this.length !== array.length) {\n return false;\n }\n for (let i = 0; i < this.ELEMENTS; ++i) {\n if (this[i] !== array[i]) {\n return false;\n }\n }\n return true;\n }\n\n // Modifiers\n\n /** Negates all values in this object */\n negate(): this {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] = -this[i];\n }\n return this.check();\n }\n\n /** Linearly interpolates between two values */\n lerp(a: Readonly, t: number): this;\n lerp(a: Readonly, b: Readonly, t: number): this;\n\n lerp(a: Readonly, b: Readonly | number, t?: number): this {\n if (t === undefined) {\n return this.lerp(this, a, b as number);\n }\n for (let i = 0; i < this.ELEMENTS; ++i) {\n const ai = a[i];\n const endValue = typeof b === 'number' ? b : b[i];\n this[i] = ai + t * (endValue - ai);\n }\n return this.check();\n }\n\n /** Minimal */\n min(vector: Readonly): this {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] = Math.min(vector[i], this[i]);\n }\n return this.check();\n }\n\n /** Maximal */\n max(vector: Readonly): this {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] = Math.max(vector[i], this[i]);\n }\n return this.check();\n }\n\n clamp(minVector: Readonly, maxVector: Readonly): this {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] = Math.min(Math.max(this[i], minVector[i]), maxVector[i]);\n }\n return this.check();\n }\n\n add(...vectors: Readonly[]): this {\n for (const vector of vectors) {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] += vector[i];\n }\n }\n return this.check();\n }\n\n subtract(...vectors: Readonly[]): this {\n for (const vector of vectors) {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] -= vector[i];\n }\n }\n return this.check();\n }\n\n scale(scale: number | Readonly): this {\n if (typeof scale === 'number') {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] *= scale;\n }\n } else {\n for (let i = 0; i < this.ELEMENTS && i < scale.length; ++i) {\n this[i] *= scale[i];\n }\n }\n return this.check();\n }\n\n /**\n * Multiplies all elements by `scale`\n * Note: `Matrix4.multiplyByScalar` only scales its 3x3 \"minor\"\n */\n multiplyByScalar(scalar: number): this {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] *= scalar;\n }\n return this.check();\n }\n\n // Debug checks\n\n /** Throws an error if array length is incorrect or contains illegal values */\n check(): this {\n if (config.debug && !this.validate()) {\n throw new Error(`math.gl: ${this.constructor.name} some fields set to invalid numbers'`);\n }\n return this;\n }\n\n /** Returns false if the array length is incorrect or contains illegal values */\n validate(): boolean {\n let valid = this.length === this.ELEMENTS;\n for (let i = 0; i < this.ELEMENTS; ++i) {\n valid = valid && Number.isFinite(this[i]);\n }\n return valid;\n }\n\n // three.js compatibility\n\n /** @deprecated */\n sub(a: Readonly): this {\n return this.subtract(a);\n }\n\n /** @deprecated */\n setScalar(a: number): this {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] = a;\n }\n return this.check();\n }\n\n /** @deprecated */\n addScalar(a: number): this {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] += a;\n }\n return this.check();\n }\n\n /** @deprecated */\n subScalar(a: number): this {\n return this.addScalar(-a);\n }\n\n /** @deprecated */\n multiplyScalar(scalar: number): this {\n // Multiplies all elements\n // `Matrix4.scale` only scales its 3x3 \"minor\"\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] *= scalar;\n }\n return this.check();\n }\n\n /** @deprecated */\n divideScalar(a: number): this {\n return this.multiplyByScalar(1 / a);\n }\n\n /** @deprecated */\n clampScalar(min: number, max: number): this {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] = Math.min(Math.max(this[i], min), max);\n }\n return this.check();\n }\n\n /** @deprecated */\n get elements(): NumericArray {\n return this;\n }\n}\n","// math.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {NumericArray} from '@math.gl/types';\nimport {config} from './common';\n\nexport function validateVector(v: NumericArray, length: number): boolean {\n if (v.length !== length) {\n return false;\n }\n // Could be arguments \"array\" (v.every not availasble)\n for (let i = 0; i < v.length; ++i) {\n if (!Number.isFinite(v[i])) {\n return false;\n }\n }\n return true;\n}\n\nexport function checkNumber(value: unknown): number {\n if (!Number.isFinite(value)) {\n throw new Error(`Invalid number ${JSON.stringify(value)}`);\n }\n return value as number;\n}\n\nexport function checkVector(\n v: T,\n length: number,\n callerName: string = ''\n): T {\n if (config.debug && !validateVector(v, length)) {\n throw new Error(`math.gl: ${callerName} some fields set to invalid numbers'`);\n }\n return v;\n}\n\nconst map: Record = {};\n\nexport function deprecated(method: string, version: string): void {\n if (!map[method]) {\n map[method] = true;\n // eslint-disable-next-line\n console.warn(\n `${method} has been removed in version ${version}, see upgrade guide for more information`\n );\n }\n}\n","// math.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport function assert(condition: unknown, message?: string): void {\n if (!condition) {\n throw new Error(`math.gl assertion ${message}`);\n }\n}\n","// math.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n// Copyright (c) 2017 Uber Technologies, Inc.\n\nimport {NumericArray} from '@math.gl/types';\nimport {MathArray} from './math-array';\nimport {checkNumber} from '../../lib/validators';\nimport {assert} from '../../lib/assert';\n\n/** Base class for vectors with at least 2 elements */\nexport abstract class Vector extends MathArray {\n // ACCESSORS\n\n get x(): number {\n return this[0];\n }\n\n set x(value: number) {\n this[0] = checkNumber(value);\n }\n\n get y(): number {\n return this[1];\n }\n\n set y(value: number) {\n this[1] = checkNumber(value);\n }\n\n /**\n * Returns the length of the vector from the origin to the point described by this vector\n *\n * @note `length` is a reserved word for Arrays, so `v.length()` will return number of elements\n * Instead we provide `len` and `magnitude`\n */\n len(): number {\n return Math.sqrt(this.lengthSquared());\n }\n\n /**\n * Returns the length of the vector from the origin to the point described by this vector\n */\n magnitude(): number {\n return this.len();\n }\n\n /**\n * Returns the squared length of the vector from the origin to the point described by this vector\n */\n lengthSquared(): number {\n let length = 0;\n for (let i = 0; i < this.ELEMENTS; ++i) {\n length += this[i] * this[i];\n }\n return length;\n }\n\n /**\n * Returns the squared length of the vector from the origin to the point described by this vector\n */\n magnitudeSquared(): number {\n return this.lengthSquared();\n }\n\n distance(mathArray: Readonly): number {\n return Math.sqrt(this.distanceSquared(mathArray));\n }\n\n distanceSquared(mathArray: Readonly): number {\n let length = 0;\n for (let i = 0; i < this.ELEMENTS; ++i) {\n const dist = this[i] - mathArray[i];\n length += dist * dist;\n }\n return checkNumber(length);\n }\n\n dot(mathArray: Readonly): number {\n let product = 0;\n for (let i = 0; i < this.ELEMENTS; ++i) {\n product += this[i] * mathArray[i];\n }\n return checkNumber(product);\n }\n\n // MODIFIERS\n\n normalize(): this {\n const length = this.magnitude();\n if (length !== 0) {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] /= length;\n }\n }\n return this.check();\n }\n\n multiply(...vectors: Readonly[]): this {\n for (const vector of vectors) {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] *= vector[i];\n }\n }\n return this.check();\n }\n\n divide(...vectors: Readonly[]): this {\n for (const vector of vectors) {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] /= vector[i];\n }\n }\n return this.check();\n }\n\n // THREE.js compatibility\n\n lengthSq(): number {\n return this.lengthSquared();\n }\n distanceTo(vector: Readonly): number {\n return this.distance(vector);\n }\n distanceToSquared(vector: Readonly): number {\n return this.distanceSquared(vector);\n }\n\n getComponent(i: number): number {\n assert(i >= 0 && i < this.ELEMENTS, 'index is out of range');\n return checkNumber(this[i]);\n }\n\n setComponent(i: number, value: number): this {\n assert(i >= 0 && i < this.ELEMENTS, 'index is out of range');\n this[i] = value;\n return this.check();\n }\n\n addVectors(a: Readonly, b: Readonly): this {\n return this.copy(a).add(b);\n }\n\n subVectors(a: Readonly, b: Readonly): this {\n return this.copy(a).subtract(b);\n }\n\n multiplyVectors(a: Readonly, b: Readonly): this {\n return this.copy(a).multiply(b);\n }\n\n addScaledVector(a: Readonly, b: number): this {\n // @ts-expect-error error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature.\n return this.add((new this.constructor(a) as this).multiplyScalar(b));\n }\n}\n","// @eslint-disable\n// @ts-nocheck\n\nimport type {NumericArray} from '@math.gl/types';\nimport * as glMatrix from './common.js';\n\n/**\n * 2 Dimensional Vector\n * @module vec2\n */\n\n/**\n * Creates a new, empty vec2\n *\n * @returns a new 2D vector\n */\nexport function create(): NumericArray {\n const out = new glMatrix.ARRAY_TYPE(2);\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[0] = 0;\n out[1] = 0;\n }\n return out;\n}\n\n/**\n * Creates a new vec2 initialized with values from an existing vector\n *\n * @param a vector to clone\n * @returns a new 2D vector\n */\nexport function clone(a: Readonly): NumericArray {\n const out = new glMatrix.ARRAY_TYPE(2);\n out[0] = a[0];\n out[1] = a[1];\n return out;\n}\n\n/**\n * Creates a new vec2 initialized with the given values\n *\n * @param x X component\n * @param y Y component\n * @returns a new 2D vector\n */\nexport function fromValues(x: number, y: number): NumericArray {\n const out = new glMatrix.ARRAY_TYPE(2);\n out[0] = x;\n out[1] = y;\n return out;\n}\n\n/**\n * Copy the values from one vec2 to another\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a the source vector\n * @returns {NumericArray} out\n */\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n return out;\n}\n\n/**\n * Set the components of a vec2 to the given values\n *\n * @param {NumericArray} out the receiving vector\n * @param {Number} x X component\n * @param {Number} y Y component\n * @returns {NumericArray} out\n */\nexport function set(out, x, y) {\n out[0] = x;\n out[1] = y;\n return out;\n}\n\n/**\n * Adds two vec2's\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a the first operand\n * @param {Readonly} b the second operand\n * @returns {NumericArray} out\n */\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n return out;\n}\n\n/**\n * Subtracts vector b from vector a\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a the first operand\n * @param {Readonly} b the second operand\n * @returns {NumericArray} out\n */\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n return out;\n}\n\n/**\n * Multiplies two vec2's\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a the first operand\n * @param {Readonly} b the second operand\n * @returns {NumericArray} out\n */\nexport function multiply(out, a, b) {\n out[0] = a[0] * b[0];\n out[1] = a[1] * b[1];\n return out;\n}\n\n/**\n * Divides two vec2's\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a the first operand\n * @param {Readonly} b the second operand\n * @returns {NumericArray} out\n */\nexport function divide(out, a, b) {\n out[0] = a[0] / b[0];\n out[1] = a[1] / b[1];\n return out;\n}\n\n/**\n * Math.ceil the components of a vec2\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a vector to ceil\n * @returns {NumericArray} out\n */\nexport function ceil(out, a) {\n out[0] = Math.ceil(a[0]);\n out[1] = Math.ceil(a[1]);\n return out;\n}\n\n/**\n * Math.floor the components of a vec2\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a vector to floor\n * @returns {NumericArray} out\n */\nexport function floor(out, a) {\n out[0] = Math.floor(a[0]);\n out[1] = Math.floor(a[1]);\n return out;\n}\n\n/**\n * Returns the minimum of two vec2's\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a the first operand\n * @param {Readonly} b the second operand\n * @returns {NumericArray} out\n */\nexport function min(out, a, b) {\n out[0] = Math.min(a[0], b[0]);\n out[1] = Math.min(a[1], b[1]);\n return out;\n}\n\n/**\n * Returns the maximum of two vec2's\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a the first operand\n * @param {Readonly} b the second operand\n * @returns {NumericArray} out\n */\nexport function max(out, a, b) {\n out[0] = Math.max(a[0], b[0]);\n out[1] = Math.max(a[1], b[1]);\n return out;\n}\n\n/**\n * symmetric round the components of a vec2\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a vector to round\n * @returns {NumericArray} out\n */\nexport function round(out, a) {\n out[0] = glMatrix.round(a[0]);\n out[1] = glMatrix.round(a[1]);\n return out;\n}\n\n/**\n * Scales a vec2 by a scalar number\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a the vector to scale\n * @param {Number} b amount to scale the vector by\n * @returns {NumericArray} out\n */\nexport function scale(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n return out;\n}\n\n/**\n * Adds two vec2's after scaling the second operand by a scalar value\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a the first operand\n * @param {Readonly} b the second operand\n * @param {Number} scale the amount to scale b by before adding\n * @returns {NumericArray} out\n */\nexport function scaleAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n return out;\n}\n\n/**\n * Calculates the euclidian distance between two vec2's\n *\n * @param {Readonly} a the first operand\n * @param {Readonly} b the second operand\n * @returns {Number} distance between a and b\n */\nexport function distance(a, b) {\n const x = b[0] - a[0];\n const y = b[1] - a[1];\n return Math.sqrt(x * x + y * y);\n}\n\n/**\n * Calculates the squared euclidian distance between two vec2's\n *\n * @param {Readonly} a the first operand\n * @param {Readonly} b the second operand\n * @returns {Number} squared distance between a and b\n */\nexport function squaredDistance(a, b) {\n const x = b[0] - a[0];\n const y = b[1] - a[1];\n return x * x + y * y;\n}\n\n/**\n * Calculates the length of a vec2\n *\n * @param {Readonly} a vector to calculate length of\n * @returns {Number} length of a\n */\nexport function length(a) {\n const x = a[0];\n const y = a[1];\n return Math.sqrt(x * x + y * y);\n}\n\n/**\n * Calculates the squared length of a vec2\n *\n * @param {Readonly} a vector to calculate squared length of\n * @returns {Number} squared length of a\n */\nexport function squaredLength(a) {\n const x = a[0];\n const y = a[1];\n return x * x + y * y;\n}\n\n/**\n * Negates the components of a vec2\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a vector to negate\n * @returns {NumericArray} out\n */\nexport function negate(out, a) {\n out[0] = -a[0];\n out[1] = -a[1];\n return out;\n}\n\n/**\n * Returns the inverse of the components of a vec2\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a vector to invert\n * @returns {NumericArray} out\n */\nexport function inverse(out, a) {\n out[0] = 1.0 / a[0];\n out[1] = 1.0 / a[1];\n return out;\n}\n\n/**\n * Normalize a vec2\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a vector to normalize\n * @returns {NumericArray} out\n */\nexport function normalize(out, a) {\n const x = a[0];\n const y = a[1];\n let len = x * x + y * y;\n if (len > 0) {\n // TODO: evaluate use of glm_invsqrt here?\n len = 1 / Math.sqrt(len);\n }\n out[0] = a[0] * len;\n out[1] = a[1] * len;\n return out;\n}\n\n/**\n * Calculates the dot product of two vec2's\n *\n * @param {Readonly} a the first operand\n * @param {Readonly} b the second operand\n * @returns {Number} dot product of a and b\n */\nexport function dot(a, b) {\n return a[0] * b[0] + a[1] * b[1];\n}\n\n/**\n * Computes the cross product of two vec2's\n * Note that the cross product must by definition produce a 3D vector\n *\n * @param {vec3} out the receiving vector\n * @param {Readonly} a the first operand\n * @param {Readonly} b the second operand\n * @returns {vec3} out\n */\nexport function cross(out, a, b) {\n const z = a[0] * b[1] - a[1] * b[0];\n out[0] = out[1] = 0;\n out[2] = z;\n return out;\n}\n\n/**\n * Performs a linear interpolation between two vec2's\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a the first operand\n * @param {Readonly} b the second operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {NumericArray} out\n */\nexport function lerp(out, a, b, t) {\n const ax = a[0];\n const ay = a[1];\n out[0] = ax + t * (b[0] - ax);\n out[1] = ay + t * (b[1] - ay);\n return out;\n}\n\n/**\n * Generates a random vector with the given scale\n *\n * @param {NumericArray} out the receiving vector\n * @param {Number} [scale] Length of the resulting vector. If omitted, a unit vector will be returned\n * @returns {NumericArray} out\n */\nexport function random(out, scale) {\n scale = scale === undefined ? 1.0 : scale;\n const r = glMatrix.RANDOM() * 2.0 * Math.PI;\n out[0] = Math.cos(r) * scale;\n out[1] = Math.sin(r) * scale;\n return out;\n}\n\n/**\n * Transforms the vec2 with a mat2\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a the vector to transform\n * @param {ReadonlyMat2} m matrix to transform with\n * @returns {NumericArray} out\n */\nexport function transformMat2(out, a, m) {\n const x = a[0];\n const y = a[1];\n out[0] = m[0] * x + m[2] * y;\n out[1] = m[1] * x + m[3] * y;\n return out;\n}\n\n/**\n * Transforms the vec2 with a mat2d\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a the vector to transform\n * @param {ReadonlyMat2d} m matrix to transform with\n * @returns {NumericArray} out\n */\nexport function transformMat2d(out, a, m) {\n const x = a[0];\n const y = a[1];\n out[0] = m[0] * x + m[2] * y + m[4];\n out[1] = m[1] * x + m[3] * y + m[5];\n return out;\n}\n\n/**\n * Transforms the vec2 with a mat3\n * 3rd vector component is implicitly '1'\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a the vector to transform\n * @param {ReadonlyMat3} m matrix to transform with\n * @returns {NumericArray} out\n */\nexport function transformMat3(out, a, m) {\n const x = a[0];\n const y = a[1];\n out[0] = m[0] * x + m[3] * y + m[6];\n out[1] = m[1] * x + m[4] * y + m[7];\n return out;\n}\n\n/**\n * Transforms the vec2 with a mat4\n * 3rd vector component is implicitly '0'\n * 4th vector component is implicitly '1'\n *\n * @param {NumericArray} out the receiving vector\n * @param {Readonly} a the vector to transform\n * @param {ReadonlyMat4} m matrix to transform with\n * @returns {NumericArray} out\n */\nexport function transformMat4(out, a, m) {\n const x = a[0];\n const y = a[1];\n out[0] = m[0] * x + m[4] * y + m[12];\n out[1] = m[1] * x + m[5] * y + m[13];\n return out;\n}\n\n/**\n * Rotate a 2D vector\n * @param {NumericArray} out The receiving vec2\n * @param {Readonly} a The vec2 point to rotate\n * @param {Readonly} b The origin of the rotation\n * @param {Number} rad The angle of rotation in radians\n * @returns {NumericArray} out\n */\nexport function rotate(out, a, b, rad) {\n // Translate point to the origin\n const p0 = a[0] - b[0];\n const p1 = a[1] - b[1];\n const sinC = Math.sin(rad);\n const cosC = Math.cos(rad);\n\n // perform rotation and translate to correct position\n out[0] = p0 * cosC - p1 * sinC + b[0];\n out[1] = p0 * sinC + p1 * cosC + b[1];\n\n return out;\n}\n\n/**\n * Get the angle between two 2D vectors\n * @param {Readonly} a The first operand\n * @param {Readonly} b The second operand\n * @returns {Number} The angle in radians\n */\nexport function angle(a, b) {\n const x1 = a[0];\n const y1 = a[1];\n const x2 = b[0];\n const y2 = b[1];\n // mag is the product of the magnitudes of a and b\n const mag = Math.sqrt((x1 * x1 + y1 * y1) * (x2 * x2 + y2 * y2));\n // mag &&.. short circuits if mag == 0\n const cosine = mag && (x1 * x2 + y1 * y2) / mag;\n // Math.min(Math.max(cosine, -1), 1) clamps the cosine between -1 and 1\n return Math.acos(Math.min(Math.max(cosine, -1), 1));\n}\n\n/**\n * Set the components of a vec2 to zero\n *\n * @param {NumericArray} out the receiving vector\n * @returns {NumericArray} out\n */\nexport function zero(out) {\n out[0] = 0.0;\n out[1] = 0.0;\n return out;\n}\n\n/**\n * Returns a string representation of a vector\n *\n * @param {Readonly} a vector to represent as a string\n * @returns {String} string representation of the vector\n */\nexport function str(a) {\n return `vec2(${a[0]}, ${a[1]})`;\n}\n\n/**\n * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===)\n *\n * @param {Readonly} a The first vector.\n * @param {Readonly} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1];\n}\n\n/**\n * Returns whether or not the vectors have approximately the same elements in the same position.\n *\n * @param {Readonly} a The first vector.\n * @param {Readonly} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\nexport function equals(a, b) {\n const a0 = a[0];\n const a1 = a[1];\n const b0 = b[0];\n const b1 = b[1];\n return (\n Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) &&\n Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1))\n );\n}\n\n/**\n * Alias for {@link vec2.length}\n * @function\n */\nexport const len = length;\n\n/**\n * Alias for {@link vec2.subtract}\n * @function\n */\nexport const sub = subtract;\n\n/**\n * Alias for {@link vec2.multiply}\n * @function\n */\nexport const mul = multiply;\n\n/**\n * Alias for {@link vec2.divide}\n * @function\n */\nexport const div = divide;\n\n/**\n * Alias for {@link vec2.distance}\n * @function\n */\nexport const dist = distance;\n\n/**\n * Alias for {@link vec2.squaredDistance}\n * @function\n */\nexport const sqrDist = squaredDistance;\n\n/**\n * Alias for {@link vec2.squaredLength}\n * @function\n */\nexport const sqrLen = squaredLength;\n\n/**\n * Perform some operation over an array of vec2s.\n *\n * @param {Array} a the array of vectors to iterate over\n * @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed\n * @param {Number} offset Number of elements to skip at the beginning of the array\n * @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array\n * @param {Function} fn Function to call for each vector in the array\n * @param {Object} [arg] additional argument to pass to fn\n * @returns {Array} a\n * @function\n */\nexport const forEach = (function () {\n const vec = create();\n\n return function (a, stride, offset, count, fn, arg) {\n let i;\n let l;\n if (!stride) {\n stride = 2;\n }\n\n if (!offset) {\n offset = 0;\n }\n\n if (count) {\n l = Math.min(count * stride + offset, a.length);\n } else {\n l = a.length;\n }\n\n for (i = offset; i < l; i += stride) {\n vec[0] = a[i];\n vec[1] = a[i + 1];\n fn(vec, vec, arg);\n a[i] = vec[0];\n a[i + 1] = vec[1];\n }\n\n return a;\n };\n})();\n","// @eslint-disable\n// @ts-nocheck\n\n/**\n * Common utilities\n * @module glMatrix\n */\n\n// Configuration Constants\nexport const EPSILON = 0.000001;\nexport let ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array;\nexport const RANDOM = Math.random;\nexport const ANGLE_ORDER = 'zyx';\n\n/**\n * Symmetric round\n * see https://www.npmjs.com/package/round-half-up-symmetric#user-content-detailed-background\n *\n * @param {Number} a value to round\n */\nexport function round(a) {\n if (a >= 0) return Math.round(a);\n\n return a % 0.5 === 0 ? Math.floor(a) : Math.round(a);\n}\n\n/**\n * Sets the type of array used when creating new vectors and matrices\n *\n * @param {Float32ArrayConstructor | ArrayConstructor} type Array type, such as Float32Array or Array\n */\nexport function setMatrixArrayType(type) {\n ARRAY_TYPE = type;\n}\n\nconst degree = Math.PI / 180;\n\n/**\n * Convert Degree To Radian\n *\n * @param {Number} a Angle in Degrees\n */\nexport function toRadian(a) {\n return a * degree;\n}\n\n/**\n * Tests whether or not the arguments have approximately the same value, within an absolute\n * or relative tolerance of glMatrix.EPSILON (an absolute tolerance is used for values less\n * than or equal to 1.0, and a relative tolerance is used for larger values)\n *\n * @param {Number} a The first number to test.\n * @param {Number} b The second number to test.\n * @returns {Boolean} True if the numbers are approximately equal, false otherwise.\n */\nexport function equals(a, b) {\n return Math.abs(a - b) <= EPSILON * Math.max(1.0, Math.abs(a), Math.abs(b));\n}\n","// math.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/* eslint-disable camelcase */\nimport {NumericArray} from '@math.gl/types';\n// vec2 additions\n\nexport function vec2_transformMat4AsVector(\n out: T,\n a: Readonly,\n m: Readonly\n): T {\n const x = a[0];\n const y = a[1];\n const w = m[3] * x + m[7] * y || 1.0;\n out[0] = (m[0] * x + m[4] * y) / w;\n out[1] = (m[1] * x + m[5] * y) / w;\n return out;\n}\n\n// vec3 additions\n\n// Transform as vector, only uses 3x3 minor matrix\nexport function vec3_transformMat4AsVector(\n out: T,\n a: Readonly,\n m: Readonly\n): T {\n const x = a[0];\n const y = a[1];\n const z = a[2];\n const w = m[3] * x + m[7] * y + m[11] * z || 1.0;\n out[0] = (m[0] * x + m[4] * y + m[8] * z) / w;\n out[1] = (m[1] * x + m[5] * y + m[9] * z) / w;\n out[2] = (m[2] * x + m[6] * y + m[10] * z) / w;\n return out;\n}\n\nexport function vec3_transformMat2(\n out: T,\n a: Readonly,\n m: Readonly\n): T {\n const x = a[0];\n const y = a[1];\n out[0] = m[0] * x + m[2] * y;\n out[1] = m[1] * x + m[3] * y;\n out[2] = a[2];\n return out;\n}\n\n// vec4 additions\n\nexport function vec4_transformMat2(\n out: T,\n a: Readonly,\n m: Readonly\n): T {\n const x = a[0];\n const y = a[1];\n out[0] = m[0] * x + m[2] * y;\n out[1] = m[1] * x + m[3] * y;\n out[2] = a[2];\n out[3] = a[3];\n return out;\n}\n\nexport function vec4_transformMat3(\n out: T,\n a: Readonly,\n m: Readonly\n): T {\n const x = a[0];\n const y = a[1];\n const z = a[2];\n out[0] = m[0] * x + m[3] * y + m[6] * z;\n out[1] = m[1] * x + m[4] * y + m[7] * z;\n out[2] = m[2] * x + m[5] * y + m[8] * z;\n out[3] = a[3];\n return out;\n}\n","// @eslint-disable\n// @ts-nocheck\n\nimport * as glMatrix from './common.js';\n\n/**\n * 3 Dimensional Vector\n * @module vec3\n */\n\n/**\n * Creates a new, empty vec3\n *\n * @returns {vec3} a new 3D vector\n */\nexport function create() {\n const out = new glMatrix.ARRAY_TYPE(3);\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[0] = 0;\n out[1] = 0;\n out[2] = 0;\n }\n return out;\n}\n\n/**\n * Creates a new vec3 initialized with values from an existing vector\n *\n * @param {ReadonlyVec3} a vector to clone\n * @returns {vec3} a new 3D vector\n */\nexport function clone(a) {\n const out = new glMatrix.ARRAY_TYPE(3);\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n return out;\n}\n\n/**\n * Calculates the length of a vec3\n *\n * @param {ReadonlyVec3} a vector to calculate length of\n * @returns {Number} length of a\n */\nexport function length(a) {\n const x = a[0];\n const y = a[1];\n const z = a[2];\n return Math.sqrt(x * x + y * y + z * z);\n}\n\n/**\n * Creates a new vec3 initialized with the given values\n *\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @returns {vec3} a new 3D vector\n */\nexport function fromValues(x, y, z) {\n const out = new glMatrix.ARRAY_TYPE(3);\n out[0] = x;\n out[1] = y;\n out[2] = z;\n return out;\n}\n\n/**\n * Copy the values from one vec3 to another\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the source vector\n * @returns {vec3} out\n */\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n return out;\n}\n\n/**\n * Set the components of a vec3 to the given values\n *\n * @param {vec3} out the receiving vector\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @returns {vec3} out\n */\nexport function set(out, x, y, z) {\n out[0] = x;\n out[1] = y;\n out[2] = z;\n return out;\n}\n\n/**\n * Adds two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n out[2] = a[2] + b[2];\n return out;\n}\n\n/**\n * Subtracts vector b from vector a\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n out[2] = a[2] - b[2];\n return out;\n}\n\n/**\n * Multiplies two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\nexport function multiply(out, a, b) {\n out[0] = a[0] * b[0];\n out[1] = a[1] * b[1];\n out[2] = a[2] * b[2];\n return out;\n}\n\n/**\n * Divides two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\nexport function divide(out, a, b) {\n out[0] = a[0] / b[0];\n out[1] = a[1] / b[1];\n out[2] = a[2] / b[2];\n return out;\n}\n\n/**\n * Math.ceil the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to ceil\n * @returns {vec3} out\n */\nexport function ceil(out, a) {\n out[0] = Math.ceil(a[0]);\n out[1] = Math.ceil(a[1]);\n out[2] = Math.ceil(a[2]);\n return out;\n}\n\n/**\n * Math.floor the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to floor\n * @returns {vec3} out\n */\nexport function floor(out, a) {\n out[0] = Math.floor(a[0]);\n out[1] = Math.floor(a[1]);\n out[2] = Math.floor(a[2]);\n return out;\n}\n\n/**\n * Returns the minimum of two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\nexport function min(out, a, b) {\n out[0] = Math.min(a[0], b[0]);\n out[1] = Math.min(a[1], b[1]);\n out[2] = Math.min(a[2], b[2]);\n return out;\n}\n\n/**\n * Returns the maximum of two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\nexport function max(out, a, b) {\n out[0] = Math.max(a[0], b[0]);\n out[1] = Math.max(a[1], b[1]);\n out[2] = Math.max(a[2], b[2]);\n return out;\n}\n\n/**\n * symmetric round the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to round\n * @returns {vec3} out\n */\nexport function round(out, a) {\n out[0] = glMatrix.round(a[0]);\n out[1] = glMatrix.round(a[1]);\n out[2] = glMatrix.round(a[2]);\n return out;\n}\n\n/**\n * Scales a vec3 by a scalar number\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the vector to scale\n * @param {Number} b amount to scale the vector by\n * @returns {vec3} out\n */\nexport function scale(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n out[2] = a[2] * b;\n return out;\n}\n\n/**\n * Adds two vec3's after scaling the second operand by a scalar value\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {Number} scale the amount to scale b by before adding\n * @returns {vec3} out\n */\nexport function scaleAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n out[2] = a[2] + b[2] * scale;\n return out;\n}\n\n/**\n * Calculates the euclidian distance between two vec3's\n *\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {Number} distance between a and b\n */\nexport function distance(a, b) {\n const x = b[0] - a[0];\n const y = b[1] - a[1];\n const z = b[2] - a[2];\n return Math.sqrt(x * x + y * y + z * z);\n}\n\n/**\n * Calculates the squared euclidian distance between two vec3's\n *\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {Number} squared distance between a and b\n */\nexport function squaredDistance(a, b) {\n const x = b[0] - a[0];\n const y = b[1] - a[1];\n const z = b[2] - a[2];\n return x * x + y * y + z * z;\n}\n\n/**\n * Calculates the squared length of a vec3\n *\n * @param {ReadonlyVec3} a vector to calculate squared length of\n * @returns {Number} squared length of a\n */\nexport function squaredLength(a) {\n const x = a[0];\n const y = a[1];\n const z = a[2];\n return x * x + y * y + z * z;\n}\n\n/**\n * Negates the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to negate\n * @returns {vec3} out\n */\nexport function negate(out, a) {\n out[0] = -a[0];\n out[1] = -a[1];\n out[2] = -a[2];\n return out;\n}\n\n/**\n * Returns the inverse of the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to invert\n * @returns {vec3} out\n */\nexport function inverse(out, a) {\n out[0] = 1.0 / a[0];\n out[1] = 1.0 / a[1];\n out[2] = 1.0 / a[2];\n return out;\n}\n\n/**\n * Normalize a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to normalize\n * @returns {vec3} out\n */\nexport function normalize(out, a) {\n const x = a[0];\n const y = a[1];\n const z = a[2];\n let len = x * x + y * y + z * z;\n if (len > 0) {\n // TODO: evaluate use of glm_invsqrt here?\n len = 1 / Math.sqrt(len);\n }\n out[0] = a[0] * len;\n out[1] = a[1] * len;\n out[2] = a[2] * len;\n return out;\n}\n\n/**\n * Calculates the dot product of two vec3's\n *\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {Number} dot product of a and b\n */\nexport function dot(a, b) {\n return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];\n}\n\n/**\n * Computes the cross product of two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\nexport function cross(out, a, b) {\n const ax = a[0];\n const ay = a[1];\n const az = a[2];\n const bx = b[0];\n const by = b[1];\n const bz = b[2];\n\n out[0] = ay * bz - az * by;\n out[1] = az * bx - ax * bz;\n out[2] = ax * by - ay * bx;\n return out;\n}\n\n/**\n * Performs a linear interpolation between two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec3} out\n */\nexport function lerp(out, a, b, t) {\n const ax = a[0];\n const ay = a[1];\n const az = a[2];\n out[0] = ax + t * (b[0] - ax);\n out[1] = ay + t * (b[1] - ay);\n out[2] = az + t * (b[2] - az);\n return out;\n}\n\n/**\n * Performs a spherical linear interpolation between two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec3} out\n */\nexport function slerp(out, a, b, t) {\n const angle = Math.acos(Math.min(Math.max(dot(a, b), -1), 1));\n const sinTotal = Math.sin(angle);\n\n const ratioA = Math.sin((1 - t) * angle) / sinTotal;\n const ratioB = Math.sin(t * angle) / sinTotal;\n out[0] = ratioA * a[0] + ratioB * b[0];\n out[1] = ratioA * a[1] + ratioB * b[1];\n out[2] = ratioA * a[2] + ratioB * b[2];\n\n return out;\n}\n\n/**\n * Performs a hermite interpolation with two control points\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {ReadonlyVec3} c the third operand\n * @param {ReadonlyVec3} d the fourth operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec3} out\n */\nexport function hermite(out, a, b, c, d, t) {\n const factorTimes2 = t * t;\n const factor1 = factorTimes2 * (2 * t - 3) + 1;\n const factor2 = factorTimes2 * (t - 2) + t;\n const factor3 = factorTimes2 * (t - 1);\n const factor4 = factorTimes2 * (3 - 2 * t);\n\n out[0] = a[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4;\n out[1] = a[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4;\n out[2] = a[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4;\n\n return out;\n}\n\n/**\n * Performs a bezier interpolation with two control points\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {ReadonlyVec3} c the third operand\n * @param {ReadonlyVec3} d the fourth operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec3} out\n */\nexport function bezier(out, a, b, c, d, t) {\n const inverseFactor = 1 - t;\n const inverseFactorTimesTwo = inverseFactor * inverseFactor;\n const factorTimes2 = t * t;\n const factor1 = inverseFactorTimesTwo * inverseFactor;\n const factor2 = 3 * t * inverseFactorTimesTwo;\n const factor3 = 3 * factorTimes2 * inverseFactor;\n const factor4 = factorTimes2 * t;\n\n out[0] = a[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4;\n out[1] = a[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4;\n out[2] = a[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4;\n\n return out;\n}\n\n/**\n * Generates a random vector with the given scale\n *\n * @param {vec3} out the receiving vector\n * @param {Number} [scale] Length of the resulting vector. If omitted, a unit vector will be returned\n * @returns {vec3} out\n */\nexport function random(out, scale) {\n scale = scale === undefined ? 1.0 : scale;\n\n const r = glMatrix.RANDOM() * 2.0 * Math.PI;\n const z = glMatrix.RANDOM() * 2.0 - 1.0;\n const zScale = Math.sqrt(1.0 - z * z) * scale;\n\n out[0] = Math.cos(r) * zScale;\n out[1] = Math.sin(r) * zScale;\n out[2] = z * scale;\n return out;\n}\n\n/**\n * Transforms the vec3 with a mat4.\n * 4th vector component is implicitly '1'\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the vector to transform\n * @param {ReadonlyMat4} m matrix to transform with\n * @returns {vec3} out\n */\nexport function transformMat4(out, a, m) {\n const x = a[0];\n const y = a[1];\n const z = a[2];\n let w = m[3] * x + m[7] * y + m[11] * z + m[15];\n w = w || 1.0;\n out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w;\n out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w;\n out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w;\n return out;\n}\n\n/**\n * Transforms the vec3 with a mat3.\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the vector to transform\n * @param {ReadonlyMat3} m the 3x3 matrix to transform with\n * @returns {vec3} out\n */\nexport function transformMat3(out, a, m) {\n const x = a[0];\n const y = a[1];\n const z = a[2];\n out[0] = x * m[0] + y * m[3] + z * m[6];\n out[1] = x * m[1] + y * m[4] + z * m[7];\n out[2] = x * m[2] + y * m[5] + z * m[8];\n return out;\n}\n\n/**\n * Transforms the vec3 with a quat\n * Can also be used for dual quaternions. (Multiply it with the real part)\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the vector to transform\n * @param {ReadonlyQuat} q quaternion to transform with\n * @returns {vec3} out\n */\nexport function transformQuat(out, a, q) {\n // benchmarks: https://jsperf.com/quaternion-transform-vec3-implementations-fixed\n const qx = q[0];\n const qy = q[1];\n const qz = q[2];\n const qw = q[3];\n const x = a[0];\n const y = a[1];\n const z = a[2];\n // var qvec = [qx, qy, qz];\n // var uv = vec3.cross([], qvec, a);\n let uvx = qy * z - qz * y;\n let uvy = qz * x - qx * z;\n let uvz = qx * y - qy * x;\n // var uuv = vec3.cross([], qvec, uv);\n let uuvx = qy * uvz - qz * uvy;\n let uuvy = qz * uvx - qx * uvz;\n let uuvz = qx * uvy - qy * uvx;\n // vec3.scale(uv, uv, 2 * w);\n const w2 = qw * 2;\n uvx *= w2;\n uvy *= w2;\n uvz *= w2;\n // vec3.scale(uuv, uuv, 2);\n uuvx *= 2;\n uuvy *= 2;\n uuvz *= 2;\n // return vec3.add(out, a, vec3.add(out, uv, uuv));\n out[0] = x + uvx + uuvx;\n out[1] = y + uvy + uuvy;\n out[2] = z + uvz + uuvz;\n return out;\n}\n\n/**\n * Rotate a 3D vector around the x-axis\n * @param {vec3} out The receiving vec3\n * @param {ReadonlyVec3} a The vec3 point to rotate\n * @param {ReadonlyVec3} b The origin of the rotation\n * @param {Number} rad The angle of rotation in radians\n * @returns {vec3} out\n */\nexport function rotateX(out, a, b, rad) {\n const p = [];\n const r = [];\n // Translate point to the origin\n p[0] = a[0] - b[0];\n p[1] = a[1] - b[1];\n p[2] = a[2] - b[2];\n\n // perform rotation\n r[0] = p[0];\n r[1] = p[1] * Math.cos(rad) - p[2] * Math.sin(rad);\n r[2] = p[1] * Math.sin(rad) + p[2] * Math.cos(rad);\n\n // translate to correct position\n out[0] = r[0] + b[0];\n out[1] = r[1] + b[1];\n out[2] = r[2] + b[2];\n\n return out;\n}\n\n/**\n * Rotate a 3D vector around the y-axis\n * @param {vec3} out The receiving vec3\n * @param {ReadonlyVec3} a The vec3 point to rotate\n * @param {ReadonlyVec3} b The origin of the rotation\n * @param {Number} rad The angle of rotation in radians\n * @returns {vec3} out\n */\nexport function rotateY(out, a, b, rad) {\n const p = [];\n const r = [];\n // Translate point to the origin\n p[0] = a[0] - b[0];\n p[1] = a[1] - b[1];\n p[2] = a[2] - b[2];\n\n // perform rotation\n r[0] = p[2] * Math.sin(rad) + p[0] * Math.cos(rad);\n r[1] = p[1];\n r[2] = p[2] * Math.cos(rad) - p[0] * Math.sin(rad);\n\n // translate to correct position\n out[0] = r[0] + b[0];\n out[1] = r[1] + b[1];\n out[2] = r[2] + b[2];\n\n return out;\n}\n\n/**\n * Rotate a 3D vector around the z-axis\n * @param {vec3} out The receiving vec3\n * @param {ReadonlyVec3} a The vec3 point to rotate\n * @param {ReadonlyVec3} b The origin of the rotation\n * @param {Number} rad The angle of rotation in radians\n * @returns {vec3} out\n */\nexport function rotateZ(out, a, b, rad) {\n const p = [];\n const r = [];\n // Translate point to the origin\n p[0] = a[0] - b[0];\n p[1] = a[1] - b[1];\n p[2] = a[2] - b[2];\n\n // perform rotation\n r[0] = p[0] * Math.cos(rad) - p[1] * Math.sin(rad);\n r[1] = p[0] * Math.sin(rad) + p[1] * Math.cos(rad);\n r[2] = p[2];\n\n // translate to correct position\n out[0] = r[0] + b[0];\n out[1] = r[1] + b[1];\n out[2] = r[2] + b[2];\n\n return out;\n}\n\n/**\n * Get the angle between two 3D vectors\n * @param {ReadonlyVec3} a The first operand\n * @param {ReadonlyVec3} b The second operand\n * @returns {Number} The angle in radians\n */\nexport function angle(a, b) {\n const ax = a[0];\n const ay = a[1];\n const az = a[2];\n const bx = b[0];\n const by = b[1];\n const bz = b[2];\n const mag = Math.sqrt((ax * ax + ay * ay + az * az) * (bx * bx + by * by + bz * bz));\n const cosine = mag && dot(a, b) / mag;\n return Math.acos(Math.min(Math.max(cosine, -1), 1));\n}\n\n/**\n * Set the components of a vec3 to zero\n *\n * @param {vec3} out the receiving vector\n * @returns {vec3} out\n */\nexport function zero(out) {\n out[0] = 0.0;\n out[1] = 0.0;\n out[2] = 0.0;\n return out;\n}\n\n/**\n * Returns a string representation of a vector\n *\n * @param {ReadonlyVec3} a vector to represent as a string\n * @returns {String} string representation of the vector\n */\nexport function str(a) {\n return `vec3(${a[0]}, ${a[1]}, ${a[2]})`;\n}\n\n/**\n * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyVec3} a The first vector.\n * @param {ReadonlyVec3} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1] && a[2] === b[2];\n}\n\n/**\n * Returns whether or not the vectors have approximately the same elements in the same position.\n *\n * @param {ReadonlyVec3} a The first vector.\n * @param {ReadonlyVec3} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\nexport function equals(a, b) {\n const a0 = a[0];\n const a1 = a[1];\n const a2 = a[2];\n const b0 = b[0];\n const b1 = b[1];\n const b2 = b[2];\n return (\n Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) &&\n Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) &&\n Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2))\n );\n}\n\n/**\n * Alias for {@link vec3.subtract}\n * @function\n */\nexport const sub = subtract;\n\n/**\n * Alias for {@link vec3.multiply}\n * @function\n */\nexport const mul = multiply;\n\n/**\n * Alias for {@link vec3.divide}\n * @function\n */\nexport const div = divide;\n\n/**\n * Alias for {@link vec3.distance}\n * @function\n */\nexport const dist = distance;\n\n/**\n * Alias for {@link vec3.squaredDistance}\n * @function\n */\nexport const sqrDist = squaredDistance;\n\n/**\n * Alias for {@link vec3.length}\n * @function\n */\nexport const len = length;\n\n/**\n * Alias for {@link vec3.squaredLength}\n * @function\n */\nexport const sqrLen = squaredLength;\n\n/**\n * Perform some operation over an array of vec3s.\n *\n * @param {Array} a the array of vectors to iterate over\n * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed\n * @param {Number} offset Number of elements to skip at the beginning of the array\n * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array\n * @param {Function} fn Function to call for each vector in the array\n * @param {Object} [arg] additional argument to pass to fn\n * @returns {Array} a\n * @function\n */\nexport const forEach = (function () {\n const vec = create();\n\n return function (a, stride, offset, count, fn, arg) {\n let i;\n let l;\n if (!stride) {\n stride = 3;\n }\n\n if (!offset) {\n offset = 0;\n }\n\n if (count) {\n l = Math.min(count * stride + offset, a.length);\n } else {\n l = a.length;\n }\n\n for (i = offset; i < l; i += stride) {\n vec[0] = a[i];\n vec[1] = a[i + 1];\n vec[2] = a[i + 2];\n fn(vec, vec, arg);\n a[i] = vec[0];\n a[i + 1] = vec[1];\n a[i + 2] = vec[2];\n }\n\n return a;\n };\n})();\n","// math.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n// Copyright (c) 2017 Uber Technologies, Inc.\n\nimport {NumericArray, NumericArray3} from '@math.gl/types';\nimport {Vector} from './base/vector';\nimport {config, isArray} from '../lib/common';\nimport {checkNumber} from '../lib/validators';\n// @ts-ignore gl-matrix types\nimport {\n angle as vec3_angle,\n cross as vec3_cross,\n rotateX as vec3_rotateX,\n rotateY as vec3_rotateY,\n rotateZ as vec3_rotateZ,\n transformMat4 as vec3_transformMat4,\n transformMat3 as vec3_transformMat3,\n transformQuat as vec3_transformQuat\n} from '../gl-matrix/vec3';\n/* eslint-disable camelcase */\nimport {vec3_transformMat2, vec3_transformMat4AsVector} from '../lib/gl-matrix-extras';\n\nconst ORIGIN = [0, 0, 0];\n\nlet ZERO: Vector3;\n\n/** Helper type that captures array length for a 3 element vector */\nexport type Vector3Like = Vector3 | NumericArray3;\n\n/**\n * Three-element vector class with common linear algebra operations.\n * Subclass of Array meaning that it is highly compatible with other libraries\n */\nexport class Vector3 extends Vector {\n static get ZERO(): Vector3 {\n if (!ZERO) {\n ZERO = new Vector3(0, 0, 0);\n Object.freeze(ZERO);\n }\n return ZERO;\n }\n\n /**\n * @class\n * @param x\n * @param y\n * @param z\n */\n constructor(x: number | Readonly = 0, y: number = 0, z: number = 0) {\n // PERF NOTE: initialize elements as double precision numbers\n super(-0, -0, -0);\n if (arguments.length === 1 && isArray(x)) {\n this.copy(x as NumericArray);\n } else {\n // this.set(x, y, z);\n if (config.debug) {\n checkNumber(x);\n checkNumber(y);\n checkNumber(z);\n }\n // @ts-expect-error TS2412: Property '0' of type 'number | [number, number, number]' is not assignable to numeric index type 'number'\n this[0] = x;\n this[1] = y;\n this[2] = z;\n }\n }\n\n set(x: number, y: number, z: number): this {\n this[0] = x;\n this[1] = y;\n this[2] = z;\n return this.check();\n }\n\n copy(array: Readonly): this {\n this[0] = array[0];\n this[1] = array[1];\n this[2] = array[2];\n return this.check();\n }\n\n fromObject(object: {x: number; y: number; z: number}): this {\n if (config.debug) {\n checkNumber(object.x);\n checkNumber(object.y);\n checkNumber(object.z);\n }\n this[0] = object.x;\n this[1] = object.y;\n this[2] = object.z;\n return this.check();\n }\n\n override toObject(object: {x?: number; y?: number; z?: number}): {\n x: number;\n y: number;\n z: number;\n } {\n object.x = this[0];\n object.y = this[1];\n object.z = this[2];\n return object as {x: number; y: number; z: number};\n }\n\n // Getters/setters\n\n get ELEMENTS(): number {\n return 3;\n }\n get z(): number {\n return this[2];\n }\n set z(value: number) {\n this[2] = checkNumber(value);\n }\n\n // ACCESSORS\n\n angle(vector: Readonly): number {\n return vec3_angle(this, vector);\n }\n\n // MODIFIERS\n\n cross(vector: Readonly): this {\n vec3_cross(this, this, vector);\n return this.check();\n }\n\n rotateX({radians, origin = ORIGIN}: {radians: number; origin?: Readonly}): this {\n vec3_rotateX(this, this, origin, radians);\n return this.check();\n }\n\n rotateY({radians, origin = ORIGIN}: {radians: number; origin?: Readonly}): this {\n vec3_rotateY(this, this, origin, radians);\n return this.check();\n }\n\n rotateZ({radians, origin = ORIGIN}: {radians: number; origin?: Readonly}): this {\n vec3_rotateZ(this, this, origin, radians);\n return this.check();\n }\n\n // Transforms\n\n // transforms as point (4th component is implicitly 1)\n transform(matrix4: Readonly): this {\n return this.transformAsPoint(matrix4);\n }\n\n // transforms as point (4th component is implicitly 1)\n transformAsPoint(matrix4: Readonly): this {\n vec3_transformMat4(this, this, matrix4);\n return this.check();\n }\n\n // transforms as vector (4th component is implicitly 0, ignores translation. slightly faster)\n transformAsVector(matrix4: Readonly): this {\n vec3_transformMat4AsVector(this, this, matrix4);\n return this.check();\n }\n\n transformByMatrix3(matrix3: Readonly): this {\n vec3_transformMat3(this, this, matrix3);\n return this.check();\n }\n\n transformByMatrix2(matrix2: Readonly): this {\n vec3_transformMat2(this, this, matrix2);\n return this.check();\n }\n\n transformByQuaternion(quaternion: Readonly): this {\n vec3_transformQuat(this, this, quaternion);\n return this.check();\n }\n}\n","// math.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n// Copyright (c) 2017 Uber Technologies, Inc.\n\nimport {NumericArray} from '@math.gl/types';\nimport {MathArray} from './math-array';\nimport {checkNumber} from '../../lib/validators';\nimport {config} from '../../lib/common';\n\n/** Base class for matrices */\nexport abstract class Matrix extends MathArray {\n abstract get RANK(): number;\n\n // fromObject(object) {\n // const array = object.elements;\n // return this.fromRowMajor(array);\n // }\n // toObject(object) {\n // const array = object.elements;\n // this.toRowMajor(array);\n // return object;\n // }\n\n // TODO better override formatString?\n override toString(): string {\n let string = '[';\n if (config.printRowMajor) {\n string += 'row-major:';\n for (let row = 0; row < this.RANK; ++row) {\n for (let col = 0; col < this.RANK; ++col) {\n string += ` ${this[col * this.RANK + row]}`;\n }\n }\n } else {\n string += 'column-major:';\n for (let i = 0; i < this.ELEMENTS; ++i) {\n string += ` ${this[i]}`;\n }\n }\n string += ']';\n return string;\n }\n\n getElementIndex(row: number, col: number): number {\n return col * this.RANK + row;\n }\n\n // By default assumes row major indices\n getElement(row: number, col: number): number {\n return this[col * this.RANK + row];\n }\n\n // By default assumes row major indices\n setElement(row: number, col: number, value: number): this {\n this[col * this.RANK + row] = checkNumber(value);\n return this;\n }\n getColumn(columnIndex: number, result: NumArrayT): NumArrayT;\n getColumn(columnIndex: number): number[];\n\n getColumn(\n columnIndex: number,\n result: number[] = new Array(this.RANK).fill(-0)\n ): number[] {\n const firstIndex = columnIndex * this.RANK;\n for (let i = 0; i < this.RANK; ++i) {\n result[i] = this[firstIndex + i];\n }\n return result;\n }\n\n setColumn(columnIndex: number, columnVector: Readonly): this {\n const firstIndex = columnIndex * this.RANK;\n for (let i = 0; i < this.RANK; ++i) {\n this[firstIndex + i] = columnVector[i];\n }\n return this;\n }\n}\n","// @eslint-disable\n// @ts-nocheck\n\nimport * as glMatrix from './common.js';\n\n/**\n * 4x4 Matrix
Format: column-major, when typed out it looks like row-major
The matrices are being post multiplied.\n * @module mat4\n */\n\n/**\n * Creates a new identity mat4\n *\n * @returns a new 4x4 matrix\n */\nexport function create() {\n const out = new glMatrix.ARRAY_TYPE(16);\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n }\n out[0] = 1;\n out[5] = 1;\n out[10] = 1;\n out[15] = 1;\n return out;\n}\n\n/**\n * Creates a new mat4 initialized with values from an existing matrix\n *\n * @param {ReadonlyMat4} a matrix to clone\n * @returns {mat4} a new 4x4 matrix\n */\nexport function clone(a) {\n const out = new glMatrix.ARRAY_TYPE(16);\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n out[9] = a[9];\n out[10] = a[10];\n out[11] = a[11];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n return out;\n}\n\n/**\n * Copy the values from one mat4 to another\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4} out\n */\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n out[9] = a[9];\n out[10] = a[10];\n out[11] = a[11];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n return out;\n}\n\n/**\n * Create a new mat4 with the given values\n *\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\n * @param {Number} m03 Component in column 0, row 3 position (index 3)\n * @param {Number} m10 Component in column 1, row 0 position (index 4)\n * @param {Number} m11 Component in column 1, row 1 position (index 5)\n * @param {Number} m12 Component in column 1, row 2 position (index 6)\n * @param {Number} m13 Component in column 1, row 3 position (index 7)\n * @param {Number} m20 Component in column 2, row 0 position (index 8)\n * @param {Number} m21 Component in column 2, row 1 position (index 9)\n * @param {Number} m22 Component in column 2, row 2 position (index 10)\n * @param {Number} m23 Component in column 2, row 3 position (index 11)\n * @param {Number} m30 Component in column 3, row 0 position (index 12)\n * @param {Number} m31 Component in column 3, row 1 position (index 13)\n * @param {Number} m32 Component in column 3, row 2 position (index 14)\n * @param {Number} m33 Component in column 3, row 3 position (index 15)\n * @returns {mat4} A new mat4\n */\nexport function fromValues(\n m00,\n m01,\n m02,\n m03,\n m10,\n m11,\n m12,\n m13,\n m20,\n m21,\n m22,\n m23,\n m30,\n m31,\n m32,\n m33\n) {\n const out = new glMatrix.ARRAY_TYPE(16);\n out[0] = m00;\n out[1] = m01;\n out[2] = m02;\n out[3] = m03;\n out[4] = m10;\n out[5] = m11;\n out[6] = m12;\n out[7] = m13;\n out[8] = m20;\n out[9] = m21;\n out[10] = m22;\n out[11] = m23;\n out[12] = m30;\n out[13] = m31;\n out[14] = m32;\n out[15] = m33;\n return out;\n}\n\n/**\n * Set the components of a mat4 to the given values\n *\n * @param {mat4} out the receiving matrix\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\n * @param {Number} m03 Component in column 0, row 3 position (index 3)\n * @param {Number} m10 Component in column 1, row 0 position (index 4)\n * @param {Number} m11 Component in column 1, row 1 position (index 5)\n * @param {Number} m12 Component in column 1, row 2 position (index 6)\n * @param {Number} m13 Component in column 1, row 3 position (index 7)\n * @param {Number} m20 Component in column 2, row 0 position (index 8)\n * @param {Number} m21 Component in column 2, row 1 position (index 9)\n * @param {Number} m22 Component in column 2, row 2 position (index 10)\n * @param {Number} m23 Component in column 2, row 3 position (index 11)\n * @param {Number} m30 Component in column 3, row 0 position (index 12)\n * @param {Number} m31 Component in column 3, row 1 position (index 13)\n * @param {Number} m32 Component in column 3, row 2 position (index 14)\n * @param {Number} m33 Component in column 3, row 3 position (index 15)\n * @returns {mat4} out\n */\nexport function set(\n out,\n m00,\n m01,\n m02,\n m03,\n m10,\n m11,\n m12,\n m13,\n m20,\n m21,\n m22,\n m23,\n m30,\n m31,\n m32,\n m33\n) {\n out[0] = m00;\n out[1] = m01;\n out[2] = m02;\n out[3] = m03;\n out[4] = m10;\n out[5] = m11;\n out[6] = m12;\n out[7] = m13;\n out[8] = m20;\n out[9] = m21;\n out[10] = m22;\n out[11] = m23;\n out[12] = m30;\n out[13] = m31;\n out[14] = m32;\n out[15] = m33;\n return out;\n}\n\n/**\n * Set a mat4 to the identity matrix\n *\n * @param {mat4} out the receiving matrix\n * @returns {mat4} out\n */\nexport function identity(out) {\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = 1;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 1;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n\n/**\n * Transpose the values of a mat4\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4} out\n */\nexport function transpose(out, a) {\n // If we are transposing ourselves we can skip a few steps but have to cache some values\n if (out === a) {\n const a01 = a[1];\n const a02 = a[2];\n const a03 = a[3];\n const a12 = a[6];\n const a13 = a[7];\n const a23 = a[11];\n\n out[1] = a[4];\n out[2] = a[8];\n out[3] = a[12];\n out[4] = a01;\n out[6] = a[9];\n out[7] = a[13];\n out[8] = a02;\n out[9] = a12;\n out[11] = a[14];\n out[12] = a03;\n out[13] = a13;\n out[14] = a23;\n } else {\n out[0] = a[0];\n out[1] = a[4];\n out[2] = a[8];\n out[3] = a[12];\n out[4] = a[1];\n out[5] = a[5];\n out[6] = a[9];\n out[7] = a[13];\n out[8] = a[2];\n out[9] = a[6];\n out[10] = a[10];\n out[11] = a[14];\n out[12] = a[3];\n out[13] = a[7];\n out[14] = a[11];\n out[15] = a[15];\n }\n\n return out;\n}\n\n/**\n * Inverts a mat4\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4} out\n */\nexport function invert(out, a) {\n const a00 = a[0];\n const a01 = a[1];\n const a02 = a[2];\n const a03 = a[3];\n const a10 = a[4];\n const a11 = a[5];\n const a12 = a[6];\n const a13 = a[7];\n const a20 = a[8];\n const a21 = a[9];\n const a22 = a[10];\n const a23 = a[11];\n const a30 = a[12];\n const a31 = a[13];\n const a32 = a[14];\n const a33 = a[15];\n\n const b00 = a00 * a11 - a01 * a10;\n const b01 = a00 * a12 - a02 * a10;\n const b02 = a00 * a13 - a03 * a10;\n const b03 = a01 * a12 - a02 * a11;\n const b04 = a01 * a13 - a03 * a11;\n const b05 = a02 * a13 - a03 * a12;\n const b06 = a20 * a31 - a21 * a30;\n const b07 = a20 * a32 - a22 * a30;\n const b08 = a20 * a33 - a23 * a30;\n const b09 = a21 * a32 - a22 * a31;\n const b10 = a21 * a33 - a23 * a31;\n const b11 = a22 * a33 - a23 * a32;\n\n // Calculate the determinant\n let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n if (!det) {\n return null;\n }\n det = 1.0 / det;\n\n out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;\n out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;\n out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;\n out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;\n out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;\n out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;\n out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;\n out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;\n out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;\n out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;\n out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;\n out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;\n out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;\n out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;\n out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;\n out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;\n\n return out;\n}\n\n/**\n * Calculates the adjugate of a mat4\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4} out\n */\nexport function adjoint(out, a) {\n const a00 = a[0];\n const a01 = a[1];\n const a02 = a[2];\n const a03 = a[3];\n const a10 = a[4];\n const a11 = a[5];\n const a12 = a[6];\n const a13 = a[7];\n const a20 = a[8];\n const a21 = a[9];\n const a22 = a[10];\n const a23 = a[11];\n const a30 = a[12];\n const a31 = a[13];\n const a32 = a[14];\n const a33 = a[15];\n\n const b00 = a00 * a11 - a01 * a10;\n const b01 = a00 * a12 - a02 * a10;\n const b02 = a00 * a13 - a03 * a10;\n const b03 = a01 * a12 - a02 * a11;\n const b04 = a01 * a13 - a03 * a11;\n const b05 = a02 * a13 - a03 * a12;\n const b06 = a20 * a31 - a21 * a30;\n const b07 = a20 * a32 - a22 * a30;\n const b08 = a20 * a33 - a23 * a30;\n const b09 = a21 * a32 - a22 * a31;\n const b10 = a21 * a33 - a23 * a31;\n const b11 = a22 * a33 - a23 * a32;\n\n out[0] = a11 * b11 - a12 * b10 + a13 * b09;\n out[1] = a02 * b10 - a01 * b11 - a03 * b09;\n out[2] = a31 * b05 - a32 * b04 + a33 * b03;\n out[3] = a22 * b04 - a21 * b05 - a23 * b03;\n out[4] = a12 * b08 - a10 * b11 - a13 * b07;\n out[5] = a00 * b11 - a02 * b08 + a03 * b07;\n out[6] = a32 * b02 - a30 * b05 - a33 * b01;\n out[7] = a20 * b05 - a22 * b02 + a23 * b01;\n out[8] = a10 * b10 - a11 * b08 + a13 * b06;\n out[9] = a01 * b08 - a00 * b10 - a03 * b06;\n out[10] = a30 * b04 - a31 * b02 + a33 * b00;\n out[11] = a21 * b02 - a20 * b04 - a23 * b00;\n out[12] = a11 * b07 - a10 * b09 - a12 * b06;\n out[13] = a00 * b09 - a01 * b07 + a02 * b06;\n out[14] = a31 * b01 - a30 * b03 - a32 * b00;\n out[15] = a20 * b03 - a21 * b01 + a22 * b00;\n return out;\n}\n\n/**\n * Calculates the determinant of a mat4\n *\n * @param {ReadonlyMat4} a the source matrix\n * @returns {Number} determinant of a\n */\nexport function determinant(a) {\n const a00 = a[0];\n const a01 = a[1];\n const a02 = a[2];\n const a03 = a[3];\n const a10 = a[4];\n const a11 = a[5];\n const a12 = a[6];\n const a13 = a[7];\n const a20 = a[8];\n const a21 = a[9];\n const a22 = a[10];\n const a23 = a[11];\n const a30 = a[12];\n const a31 = a[13];\n const a32 = a[14];\n const a33 = a[15];\n\n const b0 = a00 * a11 - a01 * a10;\n const b1 = a00 * a12 - a02 * a10;\n const b2 = a01 * a12 - a02 * a11;\n const b3 = a20 * a31 - a21 * a30;\n const b4 = a20 * a32 - a22 * a30;\n const b5 = a21 * a32 - a22 * a31;\n const b6 = a00 * b5 - a01 * b4 + a02 * b3;\n const b7 = a10 * b5 - a11 * b4 + a12 * b3;\n const b8 = a20 * b2 - a21 * b1 + a22 * b0;\n const b9 = a30 * b2 - a31 * b1 + a32 * b0;\n\n // Calculate the determinant\n return a13 * b6 - a03 * b7 + a33 * b8 - a23 * b9;\n}\n\n/**\n * Multiplies two mat4s\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @returns {mat4} out\n */\nexport function multiply(out, a, b) {\n const a00 = a[0];\n const a01 = a[1];\n const a02 = a[2];\n const a03 = a[3];\n const a10 = a[4];\n const a11 = a[5];\n const a12 = a[6];\n const a13 = a[7];\n const a20 = a[8];\n const a21 = a[9];\n const a22 = a[10];\n const a23 = a[11];\n const a30 = a[12];\n const a31 = a[13];\n const a32 = a[14];\n const a33 = a[15];\n\n // Cache only the current line of the second matrix\n let b0 = b[0];\n let b1 = b[1];\n let b2 = b[2];\n let b3 = b[3];\n out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n\n b0 = b[4];\n b1 = b[5];\n b2 = b[6];\n b3 = b[7];\n out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n\n b0 = b[8];\n b1 = b[9];\n b2 = b[10];\n b3 = b[11];\n out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n\n b0 = b[12];\n b1 = b[13];\n b2 = b[14];\n b3 = b[15];\n out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n return out;\n}\n\n/**\n * Translate a mat4 by the given vector\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to translate\n * @param {ReadonlyVec3} v vector to translate by\n * @returns {mat4} out\n */\nexport function translate(out, a, v) {\n const x = v[0];\n const y = v[1];\n const z = v[2];\n let a00;\n let a01;\n let a02;\n let a03;\n let a10;\n let a11;\n let a12;\n let a13;\n let a20;\n let a21;\n let a22;\n let a23;\n\n if (a === out) {\n out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];\n out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];\n out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];\n out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];\n } else {\n a00 = a[0];\n a01 = a[1];\n a02 = a[2];\n a03 = a[3];\n a10 = a[4];\n a11 = a[5];\n a12 = a[6];\n a13 = a[7];\n a20 = a[8];\n a21 = a[9];\n a22 = a[10];\n a23 = a[11];\n\n out[0] = a00;\n out[1] = a01;\n out[2] = a02;\n out[3] = a03;\n out[4] = a10;\n out[5] = a11;\n out[6] = a12;\n out[7] = a13;\n out[8] = a20;\n out[9] = a21;\n out[10] = a22;\n out[11] = a23;\n\n out[12] = a00 * x + a10 * y + a20 * z + a[12];\n out[13] = a01 * x + a11 * y + a21 * z + a[13];\n out[14] = a02 * x + a12 * y + a22 * z + a[14];\n out[15] = a03 * x + a13 * y + a23 * z + a[15];\n }\n\n return out;\n}\n\n/**\n * Scales the mat4 by the dimensions in the given vec3 not using vectorization\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to scale\n * @param {ReadonlyVec3} v the vec3 to scale the matrix by\n * @returns {mat4} out\n **/\nexport function scale(out, a, v) {\n const x = v[0];\n const y = v[1];\n const z = v[2];\n\n out[0] = a[0] * x;\n out[1] = a[1] * x;\n out[2] = a[2] * x;\n out[3] = a[3] * x;\n out[4] = a[4] * y;\n out[5] = a[5] * y;\n out[6] = a[6] * y;\n out[7] = a[7] * y;\n out[8] = a[8] * z;\n out[9] = a[9] * z;\n out[10] = a[10] * z;\n out[11] = a[11] * z;\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n return out;\n}\n\n/**\n * Rotates a mat4 by the given angle around the given axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @param {ReadonlyVec3} axis the axis to rotate around\n * @returns {mat4} out\n */\nexport function rotate(out, a, rad, axis) {\n let x = axis[0];\n let y = axis[1];\n let z = axis[2];\n let len = Math.sqrt(x * x + y * y + z * z);\n let c;\n let s;\n let t;\n let a00;\n let a01;\n let a02;\n let a03;\n let a10;\n let a11;\n let a12;\n let a13;\n let a20;\n let a21;\n let a22;\n let a23;\n let b00;\n let b01;\n let b02;\n let b10;\n let b11;\n let b12;\n let b20;\n let b21;\n let b22;\n\n if (len < glMatrix.EPSILON) {\n return null;\n }\n\n len = 1 / len;\n x *= len;\n y *= len;\n z *= len;\n\n s = Math.sin(rad);\n c = Math.cos(rad);\n t = 1 - c;\n\n a00 = a[0];\n a01 = a[1];\n a02 = a[2];\n a03 = a[3];\n a10 = a[4];\n a11 = a[5];\n a12 = a[6];\n a13 = a[7];\n a20 = a[8];\n a21 = a[9];\n a22 = a[10];\n a23 = a[11];\n\n // Construct the elements of the rotation matrix\n b00 = x * x * t + c;\n b01 = y * x * t + z * s;\n b02 = z * x * t - y * s;\n b10 = x * y * t - z * s;\n b11 = y * y * t + c;\n b12 = z * y * t + x * s;\n b20 = x * z * t + y * s;\n b21 = y * z * t - x * s;\n b22 = z * z * t + c;\n\n // Perform rotation-specific matrix multiplication\n out[0] = a00 * b00 + a10 * b01 + a20 * b02;\n out[1] = a01 * b00 + a11 * b01 + a21 * b02;\n out[2] = a02 * b00 + a12 * b01 + a22 * b02;\n out[3] = a03 * b00 + a13 * b01 + a23 * b02;\n out[4] = a00 * b10 + a10 * b11 + a20 * b12;\n out[5] = a01 * b10 + a11 * b11 + a21 * b12;\n out[6] = a02 * b10 + a12 * b11 + a22 * b12;\n out[7] = a03 * b10 + a13 * b11 + a23 * b12;\n out[8] = a00 * b20 + a10 * b21 + a20 * b22;\n out[9] = a01 * b20 + a11 * b21 + a21 * b22;\n out[10] = a02 * b20 + a12 * b21 + a22 * b22;\n out[11] = a03 * b20 + a13 * b21 + a23 * b22;\n\n if (a !== out) {\n // If the source and destination differ, copy the unchanged last row\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n }\n return out;\n}\n\n/**\n * Rotates a matrix by the given angle around the X axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\nexport function rotateX(out, a, rad) {\n const s = Math.sin(rad);\n const c = Math.cos(rad);\n const a10 = a[4];\n const a11 = a[5];\n const a12 = a[6];\n const a13 = a[7];\n const a20 = a[8];\n const a21 = a[9];\n const a22 = a[10];\n const a23 = a[11];\n\n if (a !== out) {\n // If the source and destination differ, copy the unchanged rows\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n }\n\n // Perform axis-specific matrix multiplication\n out[4] = a10 * c + a20 * s;\n out[5] = a11 * c + a21 * s;\n out[6] = a12 * c + a22 * s;\n out[7] = a13 * c + a23 * s;\n out[8] = a20 * c - a10 * s;\n out[9] = a21 * c - a11 * s;\n out[10] = a22 * c - a12 * s;\n out[11] = a23 * c - a13 * s;\n return out;\n}\n\n/**\n * Rotates a matrix by the given angle around the Y axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\nexport function rotateY(out, a, rad) {\n const s = Math.sin(rad);\n const c = Math.cos(rad);\n const a00 = a[0];\n const a01 = a[1];\n const a02 = a[2];\n const a03 = a[3];\n const a20 = a[8];\n const a21 = a[9];\n const a22 = a[10];\n const a23 = a[11];\n\n if (a !== out) {\n // If the source and destination differ, copy the unchanged rows\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n }\n\n // Perform axis-specific matrix multiplication\n out[0] = a00 * c - a20 * s;\n out[1] = a01 * c - a21 * s;\n out[2] = a02 * c - a22 * s;\n out[3] = a03 * c - a23 * s;\n out[8] = a00 * s + a20 * c;\n out[9] = a01 * s + a21 * c;\n out[10] = a02 * s + a22 * c;\n out[11] = a03 * s + a23 * c;\n return out;\n}\n\n/**\n * Rotates a matrix by the given angle around the Z axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\nexport function rotateZ(out, a, rad) {\n const s = Math.sin(rad);\n const c = Math.cos(rad);\n const a00 = a[0];\n const a01 = a[1];\n const a02 = a[2];\n const a03 = a[3];\n const a10 = a[4];\n const a11 = a[5];\n const a12 = a[6];\n const a13 = a[7];\n\n if (a !== out) {\n // If the source and destination differ, copy the unchanged last row\n out[8] = a[8];\n out[9] = a[9];\n out[10] = a[10];\n out[11] = a[11];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n }\n\n // Perform axis-specific matrix multiplication\n out[0] = a00 * c + a10 * s;\n out[1] = a01 * c + a11 * s;\n out[2] = a02 * c + a12 * s;\n out[3] = a03 * c + a13 * s;\n out[4] = a10 * c - a00 * s;\n out[5] = a11 * c - a01 * s;\n out[6] = a12 * c - a02 * s;\n out[7] = a13 * c - a03 * s;\n return out;\n}\n\n/**\n * Creates a matrix from a vector translation\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.translate(dest, dest, vec);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {ReadonlyVec3} v Translation vector\n * @returns {mat4} out\n */\nexport function fromTranslation(out, v) {\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = 1;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 1;\n out[11] = 0;\n out[12] = v[0];\n out[13] = v[1];\n out[14] = v[2];\n out[15] = 1;\n return out;\n}\n\n/**\n * Creates a matrix from a vector scaling\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.scale(dest, dest, vec);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {ReadonlyVec3} v Scaling vector\n * @returns {mat4} out\n */\nexport function fromScaling(out, v) {\n out[0] = v[0];\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = v[1];\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = v[2];\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n\n/**\n * Creates a matrix from a given angle around a given axis\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.rotate(dest, dest, rad, axis);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @param {ReadonlyVec3} axis the axis to rotate around\n * @returns {mat4} out\n */\nexport function fromRotation(out, rad, axis) {\n let x = axis[0];\n let y = axis[1];\n let z = axis[2];\n let len = Math.sqrt(x * x + y * y + z * z);\n let c;\n let s;\n let t;\n\n if (len < glMatrix.EPSILON) {\n return null;\n }\n\n len = 1 / len;\n x *= len;\n y *= len;\n z *= len;\n\n s = Math.sin(rad);\n c = Math.cos(rad);\n t = 1 - c;\n\n // Perform rotation-specific matrix multiplication\n out[0] = x * x * t + c;\n out[1] = y * x * t + z * s;\n out[2] = z * x * t - y * s;\n out[3] = 0;\n out[4] = x * y * t - z * s;\n out[5] = y * y * t + c;\n out[6] = z * y * t + x * s;\n out[7] = 0;\n out[8] = x * z * t + y * s;\n out[9] = y * z * t - x * s;\n out[10] = z * z * t + c;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n\n/**\n * Creates a matrix from the given angle around the X axis\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.rotateX(dest, dest, rad);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\nexport function fromXRotation(out, rad) {\n const s = Math.sin(rad);\n const c = Math.cos(rad);\n\n // Perform axis-specific matrix multiplication\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = c;\n out[6] = s;\n out[7] = 0;\n out[8] = 0;\n out[9] = -s;\n out[10] = c;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n\n/**\n * Creates a matrix from the given angle around the Y axis\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.rotateY(dest, dest, rad);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\nexport function fromYRotation(out, rad) {\n const s = Math.sin(rad);\n const c = Math.cos(rad);\n\n // Perform axis-specific matrix multiplication\n out[0] = c;\n out[1] = 0;\n out[2] = -s;\n out[3] = 0;\n out[4] = 0;\n out[5] = 1;\n out[6] = 0;\n out[7] = 0;\n out[8] = s;\n out[9] = 0;\n out[10] = c;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n\n/**\n * Creates a matrix from the given angle around the Z axis\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.rotateZ(dest, dest, rad);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\nexport function fromZRotation(out, rad) {\n const s = Math.sin(rad);\n const c = Math.cos(rad);\n\n // Perform axis-specific matrix multiplication\n out[0] = c;\n out[1] = s;\n out[2] = 0;\n out[3] = 0;\n out[4] = -s;\n out[5] = c;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 1;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n\n/**\n * Creates a matrix from a quaternion rotation and vector translation\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.translate(dest, vec);\n * let quatMat = mat4.create();\n * quat4.toMat4(quat, quatMat);\n * mat4.multiply(dest, quatMat);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {quat4} q Rotation quaternion\n * @param {ReadonlyVec3} v Translation vector\n * @returns {mat4} out\n */\nexport function fromRotationTranslation(out, q, v) {\n // Quaternion math\n const x = q[0];\n const y = q[1];\n const z = q[2];\n const w = q[3];\n const x2 = x + x;\n const y2 = y + y;\n const z2 = z + z;\n\n const xx = x * x2;\n const xy = x * y2;\n const xz = x * z2;\n const yy = y * y2;\n const yz = y * z2;\n const zz = z * z2;\n const wx = w * x2;\n const wy = w * y2;\n const wz = w * z2;\n\n out[0] = 1 - (yy + zz);\n out[1] = xy + wz;\n out[2] = xz - wy;\n out[3] = 0;\n out[4] = xy - wz;\n out[5] = 1 - (xx + zz);\n out[6] = yz + wx;\n out[7] = 0;\n out[8] = xz + wy;\n out[9] = yz - wx;\n out[10] = 1 - (xx + yy);\n out[11] = 0;\n out[12] = v[0];\n out[13] = v[1];\n out[14] = v[2];\n out[15] = 1;\n\n return out;\n}\n\n/**\n * Creates a new mat4 from a dual quat.\n *\n * @param {mat4} out Matrix\n * @param {ReadonlyQuat2} a Dual Quaternion\n * @returns {mat4} mat4 receiving operation result\n */\nexport function fromQuat2(out, a) {\n const translation = new glMatrix.ARRAY_TYPE(3);\n const bx = -a[0];\n const by = -a[1];\n const bz = -a[2];\n const bw = a[3];\n const ax = a[4];\n const ay = a[5];\n const az = a[6];\n const aw = a[7];\n\n const magnitude = bx * bx + by * by + bz * bz + bw * bw;\n // Only scale if it makes sense\n if (magnitude > 0) {\n translation[0] = ((ax * bw + aw * bx + ay * bz - az * by) * 2) / magnitude;\n translation[1] = ((ay * bw + aw * by + az * bx - ax * bz) * 2) / magnitude;\n translation[2] = ((az * bw + aw * bz + ax * by - ay * bx) * 2) / magnitude;\n } else {\n translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2;\n translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2;\n translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2;\n }\n fromRotationTranslation(out, a, translation);\n return out;\n}\n\n/**\n * Returns the translation vector component of a transformation\n * matrix. If a matrix is built with fromRotationTranslation,\n * the returned vector will be the same as the translation vector\n * originally supplied.\n * @param {vec3} out Vector to receive translation component\n * @param {ReadonlyMat4} mat Matrix to be decomposed (input)\n * @return {vec3} out\n */\nexport function getTranslation(out, mat) {\n out[0] = mat[12];\n out[1] = mat[13];\n out[2] = mat[14];\n\n return out;\n}\n\n/**\n * Returns the scaling factor component of a transformation\n * matrix. If a matrix is built with fromRotationTranslationScale\n * with a normalized Quaternion paramter, the returned vector will be\n * the same as the scaling vector\n * originally supplied.\n * @param {vec3} out Vector to receive scaling factor component\n * @param {ReadonlyMat4} mat Matrix to be decomposed (input)\n * @return {vec3} out\n */\nexport function getScaling(out, mat) {\n const m11 = mat[0];\n const m12 = mat[1];\n const m13 = mat[2];\n const m21 = mat[4];\n const m22 = mat[5];\n const m23 = mat[6];\n const m31 = mat[8];\n const m32 = mat[9];\n const m33 = mat[10];\n\n out[0] = Math.sqrt(m11 * m11 + m12 * m12 + m13 * m13);\n out[1] = Math.sqrt(m21 * m21 + m22 * m22 + m23 * m23);\n out[2] = Math.sqrt(m31 * m31 + m32 * m32 + m33 * m33);\n\n return out;\n}\n\n/**\n * Returns a quaternion representing the rotational component\n * of a transformation matrix. If a matrix is built with\n * fromRotationTranslation, the returned quaternion will be the\n * same as the quaternion originally supplied.\n * @param {quat} out Quaternion to receive the rotation component\n * @param {ReadonlyMat4} mat Matrix to be decomposed (input)\n * @return {quat} out\n */\nexport function getRotation(out, mat) {\n const scaling = new glMatrix.ARRAY_TYPE(3);\n getScaling(scaling, mat);\n\n const is1 = 1 / scaling[0];\n const is2 = 1 / scaling[1];\n const is3 = 1 / scaling[2];\n\n const sm11 = mat[0] * is1;\n const sm12 = mat[1] * is2;\n const sm13 = mat[2] * is3;\n const sm21 = mat[4] * is1;\n const sm22 = mat[5] * is2;\n const sm23 = mat[6] * is3;\n const sm31 = mat[8] * is1;\n const sm32 = mat[9] * is2;\n const sm33 = mat[10] * is3;\n\n const trace = sm11 + sm22 + sm33;\n let S = 0;\n\n if (trace > 0) {\n S = Math.sqrt(trace + 1.0) * 2;\n out[3] = 0.25 * S;\n out[0] = (sm23 - sm32) / S;\n out[1] = (sm31 - sm13) / S;\n out[2] = (sm12 - sm21) / S;\n } else if (sm11 > sm22 && sm11 > sm33) {\n S = Math.sqrt(1.0 + sm11 - sm22 - sm33) * 2;\n out[3] = (sm23 - sm32) / S;\n out[0] = 0.25 * S;\n out[1] = (sm12 + sm21) / S;\n out[2] = (sm31 + sm13) / S;\n } else if (sm22 > sm33) {\n S = Math.sqrt(1.0 + sm22 - sm11 - sm33) * 2;\n out[3] = (sm31 - sm13) / S;\n out[0] = (sm12 + sm21) / S;\n out[1] = 0.25 * S;\n out[2] = (sm23 + sm32) / S;\n } else {\n S = Math.sqrt(1.0 + sm33 - sm11 - sm22) * 2;\n out[3] = (sm12 - sm21) / S;\n out[0] = (sm31 + sm13) / S;\n out[1] = (sm23 + sm32) / S;\n out[2] = 0.25 * S;\n }\n\n return out;\n}\n\n/**\n * Decomposes a transformation matrix into its rotation, translation\n * and scale components. Returns only the rotation component\n * @param {quat} out_r Quaternion to receive the rotation component\n * @param {vec3} out_t Vector to receive the translation vector\n * @param {vec3} out_s Vector to receive the scaling factor\n * @param {ReadonlyMat4} mat Matrix to be decomposed (input)\n * @returns {quat} out_r\n */\nexport function decompose(out_r, out_t, out_s, mat) {\n out_t[0] = mat[12];\n out_t[1] = mat[13];\n out_t[2] = mat[14];\n\n const m11 = mat[0];\n const m12 = mat[1];\n const m13 = mat[2];\n const m21 = mat[4];\n const m22 = mat[5];\n const m23 = mat[6];\n const m31 = mat[8];\n const m32 = mat[9];\n const m33 = mat[10];\n\n out_s[0] = Math.sqrt(m11 * m11 + m12 * m12 + m13 * m13);\n out_s[1] = Math.sqrt(m21 * m21 + m22 * m22 + m23 * m23);\n out_s[2] = Math.sqrt(m31 * m31 + m32 * m32 + m33 * m33);\n\n const is1 = 1 / out_s[0];\n const is2 = 1 / out_s[1];\n const is3 = 1 / out_s[2];\n\n const sm11 = m11 * is1;\n const sm12 = m12 * is2;\n const sm13 = m13 * is3;\n const sm21 = m21 * is1;\n const sm22 = m22 * is2;\n const sm23 = m23 * is3;\n const sm31 = m31 * is1;\n const sm32 = m32 * is2;\n const sm33 = m33 * is3;\n\n const trace = sm11 + sm22 + sm33;\n let S = 0;\n\n if (trace > 0) {\n S = Math.sqrt(trace + 1.0) * 2;\n out_r[3] = 0.25 * S;\n out_r[0] = (sm23 - sm32) / S;\n out_r[1] = (sm31 - sm13) / S;\n out_r[2] = (sm12 - sm21) / S;\n } else if (sm11 > sm22 && sm11 > sm33) {\n S = Math.sqrt(1.0 + sm11 - sm22 - sm33) * 2;\n out_r[3] = (sm23 - sm32) / S;\n out_r[0] = 0.25 * S;\n out_r[1] = (sm12 + sm21) / S;\n out_r[2] = (sm31 + sm13) / S;\n } else if (sm22 > sm33) {\n S = Math.sqrt(1.0 + sm22 - sm11 - sm33) * 2;\n out_r[3] = (sm31 - sm13) / S;\n out_r[0] = (sm12 + sm21) / S;\n out_r[1] = 0.25 * S;\n out_r[2] = (sm23 + sm32) / S;\n } else {\n S = Math.sqrt(1.0 + sm33 - sm11 - sm22) * 2;\n out_r[3] = (sm12 - sm21) / S;\n out_r[0] = (sm31 + sm13) / S;\n out_r[1] = (sm23 + sm32) / S;\n out_r[2] = 0.25 * S;\n }\n\n return out_r;\n}\n\n/**\n * Creates a matrix from a quaternion rotation, vector translation and vector scale\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.translate(dest, vec);\n * let quatMat = mat4.create();\n * quat4.toMat4(quat, quatMat);\n * mat4.multiply(dest, quatMat);\n * mat4.scale(dest, scale)\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {quat4} q Rotation quaternion\n * @param {ReadonlyVec3} v Translation vector\n * @param {ReadonlyVec3} s Scaling vector\n * @returns {mat4} out\n */\nexport function fromRotationTranslationScale(out, q, v, s) {\n // Quaternion math\n const x = q[0];\n const y = q[1];\n const z = q[2];\n const w = q[3];\n const x2 = x + x;\n const y2 = y + y;\n const z2 = z + z;\n\n const xx = x * x2;\n const xy = x * y2;\n const xz = x * z2;\n const yy = y * y2;\n const yz = y * z2;\n const zz = z * z2;\n const wx = w * x2;\n const wy = w * y2;\n const wz = w * z2;\n const sx = s[0];\n const sy = s[1];\n const sz = s[2];\n\n out[0] = (1 - (yy + zz)) * sx;\n out[1] = (xy + wz) * sx;\n out[2] = (xz - wy) * sx;\n out[3] = 0;\n out[4] = (xy - wz) * sy;\n out[5] = (1 - (xx + zz)) * sy;\n out[6] = (yz + wx) * sy;\n out[7] = 0;\n out[8] = (xz + wy) * sz;\n out[9] = (yz - wx) * sz;\n out[10] = (1 - (xx + yy)) * sz;\n out[11] = 0;\n out[12] = v[0];\n out[13] = v[1];\n out[14] = v[2];\n out[15] = 1;\n\n return out;\n}\n\n/**\n * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.translate(dest, vec);\n * mat4.translate(dest, origin);\n * let quatMat = mat4.create();\n * quat4.toMat4(quat, quatMat);\n * mat4.multiply(dest, quatMat);\n * mat4.scale(dest, scale)\n * mat4.translate(dest, negativeOrigin);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {quat4} q Rotation quaternion\n * @param {ReadonlyVec3} v Translation vector\n * @param {ReadonlyVec3} s Scaling vector\n * @param {ReadonlyVec3} o The origin vector around which to scale and rotate\n * @returns {mat4} out\n */\nexport function fromRotationTranslationScaleOrigin(out, q, v, s, o) {\n // Quaternion math\n const x = q[0];\n const y = q[1];\n const z = q[2];\n const w = q[3];\n const x2 = x + x;\n const y2 = y + y;\n const z2 = z + z;\n\n const xx = x * x2;\n const xy = x * y2;\n const xz = x * z2;\n const yy = y * y2;\n const yz = y * z2;\n const zz = z * z2;\n const wx = w * x2;\n const wy = w * y2;\n const wz = w * z2;\n\n const sx = s[0];\n const sy = s[1];\n const sz = s[2];\n\n const ox = o[0];\n const oy = o[1];\n const oz = o[2];\n\n const out0 = (1 - (yy + zz)) * sx;\n const out1 = (xy + wz) * sx;\n const out2 = (xz - wy) * sx;\n const out4 = (xy - wz) * sy;\n const out5 = (1 - (xx + zz)) * sy;\n const out6 = (yz + wx) * sy;\n const out8 = (xz + wy) * sz;\n const out9 = (yz - wx) * sz;\n const out10 = (1 - (xx + yy)) * sz;\n\n out[0] = out0;\n out[1] = out1;\n out[2] = out2;\n out[3] = 0;\n out[4] = out4;\n out[5] = out5;\n out[6] = out6;\n out[7] = 0;\n out[8] = out8;\n out[9] = out9;\n out[10] = out10;\n out[11] = 0;\n out[12] = v[0] + ox - (out0 * ox + out4 * oy + out8 * oz);\n out[13] = v[1] + oy - (out1 * ox + out5 * oy + out9 * oz);\n out[14] = v[2] + oz - (out2 * ox + out6 * oy + out10 * oz);\n out[15] = 1;\n\n return out;\n}\n\n/**\n * Calculates a 4x4 matrix from the given quaternion\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {ReadonlyQuat} q Quaternion to create matrix from\n *\n * @returns {mat4} out\n */\nexport function fromQuat(out, q) {\n const x = q[0];\n const y = q[1];\n const z = q[2];\n const w = q[3];\n const x2 = x + x;\n const y2 = y + y;\n const z2 = z + z;\n\n const xx = x * x2;\n const yx = y * x2;\n const yy = y * y2;\n const zx = z * x2;\n const zy = z * y2;\n const zz = z * z2;\n const wx = w * x2;\n const wy = w * y2;\n const wz = w * z2;\n\n out[0] = 1 - yy - zz;\n out[1] = yx + wz;\n out[2] = zx - wy;\n out[3] = 0;\n\n out[4] = yx - wz;\n out[5] = 1 - xx - zz;\n out[6] = zy + wx;\n out[7] = 0;\n\n out[8] = zx + wy;\n out[9] = zy - wx;\n out[10] = 1 - xx - yy;\n out[11] = 0;\n\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n\n return out;\n}\n\n/**\n * Generates a frustum matrix with the given bounds\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {Number} left Left bound of the frustum\n * @param {Number} right Right bound of the frustum\n * @param {Number} bottom Bottom bound of the frustum\n * @param {Number} top Top bound of the frustum\n * @param {Number} near Near bound of the frustum\n * @param {Number} far Far bound of the frustum\n * @returns {mat4} out\n */\nexport function frustum(out, left, right, bottom, top, near, far) {\n const rl = 1 / (right - left);\n const tb = 1 / (top - bottom);\n const nf = 1 / (near - far);\n out[0] = near * 2 * rl;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = near * 2 * tb;\n out[6] = 0;\n out[7] = 0;\n out[8] = (right + left) * rl;\n out[9] = (top + bottom) * tb;\n out[10] = (far + near) * nf;\n out[11] = -1;\n out[12] = 0;\n out[13] = 0;\n out[14] = far * near * 2 * nf;\n out[15] = 0;\n return out;\n}\n\n/**\n * Generates a perspective projection matrix with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1],\n * which matches WebGL/OpenGL's clip volume.\n * Passing null/undefined/no value for far will generate infinite projection matrix.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} fovy Vertical field of view in radians\n * @param {number} aspect Aspect ratio. typically viewport width/height\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum, can be null or Infinity\n * @returns {mat4} out\n */\nexport function perspectiveNO(out, fovy, aspect, near, far) {\n const f = 1.0 / Math.tan(fovy / 2);\n out[0] = f / aspect;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = f;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[11] = -1;\n out[12] = 0;\n out[13] = 0;\n out[15] = 0;\n if (far != null && far !== Infinity) {\n const nf = 1 / (near - far);\n out[10] = (far + near) * nf;\n out[14] = 2 * far * near * nf;\n } else {\n out[10] = -1;\n out[14] = -2 * near;\n }\n return out;\n}\n\n/**\n * Alias for {@link mat4.perspectiveNO}\n * @function\n */\nexport const perspective = perspectiveNO;\n\n/**\n * Generates a perspective projection matrix suitable for WebGPU with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [0, 1],\n * which matches WebGPU/Vulkan/DirectX/Metal's clip volume.\n * Passing null/undefined/no value for far will generate infinite projection matrix.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} fovy Vertical field of view in radians\n * @param {number} aspect Aspect ratio. typically viewport width/height\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum, can be null or Infinity\n * @returns {mat4} out\n */\nexport function perspectiveZO(out, fovy, aspect, near, far) {\n const f = 1.0 / Math.tan(fovy / 2);\n out[0] = f / aspect;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = f;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[11] = -1;\n out[12] = 0;\n out[13] = 0;\n out[15] = 0;\n if (far != null && far !== Infinity) {\n const nf = 1 / (near - far);\n out[10] = far * nf;\n out[14] = far * near * nf;\n } else {\n out[10] = -1;\n out[14] = -near;\n }\n return out;\n}\n\n/**\n * Generates a perspective projection matrix with the given field of view.\n * This is primarily useful for generating projection matrices to be used\n * with the still experiemental WebVR API.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {Object} fov Object containing the following values: upDegrees, downDegrees, leftDegrees, rightDegrees\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum\n * @returns {mat4} out\n */\nexport function perspectiveFromFieldOfView(out, fov, near, far) {\n const upTan = Math.tan((fov.upDegrees * Math.PI) / 180.0);\n const downTan = Math.tan((fov.downDegrees * Math.PI) / 180.0);\n const leftTan = Math.tan((fov.leftDegrees * Math.PI) / 180.0);\n const rightTan = Math.tan((fov.rightDegrees * Math.PI) / 180.0);\n const xScale = 2.0 / (leftTan + rightTan);\n const yScale = 2.0 / (upTan + downTan);\n\n out[0] = xScale;\n out[1] = 0.0;\n out[2] = 0.0;\n out[3] = 0.0;\n out[4] = 0.0;\n out[5] = yScale;\n out[6] = 0.0;\n out[7] = 0.0;\n out[8] = -((leftTan - rightTan) * xScale * 0.5);\n out[9] = (upTan - downTan) * yScale * 0.5;\n out[10] = far / (near - far);\n out[11] = -1.0;\n out[12] = 0.0;\n out[13] = 0.0;\n out[14] = (far * near) / (near - far);\n out[15] = 0.0;\n return out;\n}\n\n/**\n * Generates a orthogonal projection matrix with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1],\n * which matches WebGL/OpenGL's clip volume.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} left Left bound of the frustum\n * @param {number} right Right bound of the frustum\n * @param {number} bottom Bottom bound of the frustum\n * @param {number} top Top bound of the frustum\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum\n * @returns {mat4} out\n */\nexport function orthoNO(out, left, right, bottom, top, near, far) {\n const lr = 1 / (left - right);\n const bt = 1 / (bottom - top);\n const nf = 1 / (near - far);\n out[0] = -2 * lr;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = -2 * bt;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 2 * nf;\n out[11] = 0;\n out[12] = (left + right) * lr;\n out[13] = (top + bottom) * bt;\n out[14] = (far + near) * nf;\n out[15] = 1;\n return out;\n}\n\n/**\n * Alias for {@link mat4.orthoNO}\n * @function\n */\nexport const ortho = orthoNO;\n\n/**\n * Generates a orthogonal projection matrix with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [0, 1],\n * which matches WebGPU/Vulkan/DirectX/Metal's clip volume.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} left Left bound of the frustum\n * @param {number} right Right bound of the frustum\n * @param {number} bottom Bottom bound of the frustum\n * @param {number} top Top bound of the frustum\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum\n * @returns {mat4} out\n */\nexport function orthoZO(out, left, right, bottom, top, near, far) {\n const lr = 1 / (left - right);\n const bt = 1 / (bottom - top);\n const nf = 1 / (near - far);\n out[0] = -2 * lr;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = -2 * bt;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = nf;\n out[11] = 0;\n out[12] = (left + right) * lr;\n out[13] = (top + bottom) * bt;\n out[14] = near * nf;\n out[15] = 1;\n return out;\n}\n\n/**\n * Generates a look-at matrix with the given eye position, focal point, and up axis.\n * If you want a matrix that actually makes an object look at another object, you should use targetTo instead.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {ReadonlyVec3} eye Position of the viewer\n * @param {ReadonlyVec3} center Point the viewer is looking at\n * @param {ReadonlyVec3} up vec3 pointing up\n * @returns {mat4} out\n */\nexport function lookAt(out, eye, center, up) {\n let len;\n let x0;\n let x1;\n let x2;\n let y0;\n let y1;\n let y2;\n let z0;\n let z1;\n let z2;\n const eyex = eye[0];\n const eyey = eye[1];\n const eyez = eye[2];\n const upx = up[0];\n const upy = up[1];\n const upz = up[2];\n const centerx = center[0];\n const centery = center[1];\n const centerz = center[2];\n\n if (\n Math.abs(eyex - centerx) < glMatrix.EPSILON &&\n Math.abs(eyey - centery) < glMatrix.EPSILON &&\n Math.abs(eyez - centerz) < glMatrix.EPSILON\n ) {\n return identity(out);\n }\n\n z0 = eyex - centerx;\n z1 = eyey - centery;\n z2 = eyez - centerz;\n\n len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2);\n z0 *= len;\n z1 *= len;\n z2 *= len;\n\n x0 = upy * z2 - upz * z1;\n x1 = upz * z0 - upx * z2;\n x2 = upx * z1 - upy * z0;\n len = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2);\n if (!len) {\n x0 = 0;\n x1 = 0;\n x2 = 0;\n } else {\n len = 1 / len;\n x0 *= len;\n x1 *= len;\n x2 *= len;\n }\n\n y0 = z1 * x2 - z2 * x1;\n y1 = z2 * x0 - z0 * x2;\n y2 = z0 * x1 - z1 * x0;\n\n len = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2);\n if (!len) {\n y0 = 0;\n y1 = 0;\n y2 = 0;\n } else {\n len = 1 / len;\n y0 *= len;\n y1 *= len;\n y2 *= len;\n }\n\n out[0] = x0;\n out[1] = y0;\n out[2] = z0;\n out[3] = 0;\n out[4] = x1;\n out[5] = y1;\n out[6] = z1;\n out[7] = 0;\n out[8] = x2;\n out[9] = y2;\n out[10] = z2;\n out[11] = 0;\n out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);\n out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);\n out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);\n out[15] = 1;\n\n return out;\n}\n\n/**\n * Generates a matrix that makes something look at something else.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {ReadonlyVec3} eye Position of the viewer\n * @param {ReadonlyVec3} center Point the viewer is looking at\n * @param {ReadonlyVec3} up vec3 pointing up\n * @returns {mat4} out\n */\nexport function targetTo(out, eye, target, up) {\n const eyex = eye[0];\n const eyey = eye[1];\n const eyez = eye[2];\n const upx = up[0];\n const upy = up[1];\n const upz = up[2];\n\n let z0 = eyex - target[0];\n let z1 = eyey - target[1];\n let z2 = eyez - target[2];\n\n let len = z0 * z0 + z1 * z1 + z2 * z2;\n if (len > 0) {\n len = 1 / Math.sqrt(len);\n z0 *= len;\n z1 *= len;\n z2 *= len;\n }\n\n let x0 = upy * z2 - upz * z1;\n let x1 = upz * z0 - upx * z2;\n let x2 = upx * z1 - upy * z0;\n\n len = x0 * x0 + x1 * x1 + x2 * x2;\n if (len > 0) {\n len = 1 / Math.sqrt(len);\n x0 *= len;\n x1 *= len;\n x2 *= len;\n }\n\n out[0] = x0;\n out[1] = x1;\n out[2] = x2;\n out[3] = 0;\n out[4] = z1 * x2 - z2 * x1;\n out[5] = z2 * x0 - z0 * x2;\n out[6] = z0 * x1 - z1 * x0;\n out[7] = 0;\n out[8] = z0;\n out[9] = z1;\n out[10] = z2;\n out[11] = 0;\n out[12] = eyex;\n out[13] = eyey;\n out[14] = eyez;\n out[15] = 1;\n return out;\n}\n\n/**\n * Returns a string representation of a mat4\n *\n * @param {ReadonlyMat4} a matrix to represent as a string\n * @returns {String} string representation of the matrix\n */\nexport function str(a) {\n return `mat4(${a[0]}, ${a[1]}, ${a[2]}, ${a[3]}, ${a[4]}, ${a[5]}, ${a[6]}, ${a[7]}, ${a[8]}, ${a[9]}, ${a[10]}, ${a[11]}, ${a[12]}, ${a[13]}, ${a[14]}, ${a[15]})`;\n}\n\n/**\n * Returns Frobenius norm of a mat4\n *\n * @param {ReadonlyMat4} a the matrix to calculate Frobenius norm of\n * @returns {Number} Frobenius norm\n */\nexport function frob(a) {\n return Math.sqrt(\n a[0] * a[0] +\n a[1] * a[1] +\n a[2] * a[2] +\n a[3] * a[3] +\n a[4] * a[4] +\n a[5] * a[5] +\n a[6] * a[6] +\n a[7] * a[7] +\n a[8] * a[8] +\n a[9] * a[9] +\n a[10] * a[10] +\n a[11] * a[11] +\n a[12] * a[12] +\n a[13] * a[13] +\n a[14] * a[14] +\n a[15] * a[15]\n );\n}\n\n/**\n * Adds two mat4's\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @returns {mat4} out\n */\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n out[2] = a[2] + b[2];\n out[3] = a[3] + b[3];\n out[4] = a[4] + b[4];\n out[5] = a[5] + b[5];\n out[6] = a[6] + b[6];\n out[7] = a[7] + b[7];\n out[8] = a[8] + b[8];\n out[9] = a[9] + b[9];\n out[10] = a[10] + b[10];\n out[11] = a[11] + b[11];\n out[12] = a[12] + b[12];\n out[13] = a[13] + b[13];\n out[14] = a[14] + b[14];\n out[15] = a[15] + b[15];\n return out;\n}\n\n/**\n * Subtracts matrix b from matrix a\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @returns {mat4} out\n */\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n out[2] = a[2] - b[2];\n out[3] = a[3] - b[3];\n out[4] = a[4] - b[4];\n out[5] = a[5] - b[5];\n out[6] = a[6] - b[6];\n out[7] = a[7] - b[7];\n out[8] = a[8] - b[8];\n out[9] = a[9] - b[9];\n out[10] = a[10] - b[10];\n out[11] = a[11] - b[11];\n out[12] = a[12] - b[12];\n out[13] = a[13] - b[13];\n out[14] = a[14] - b[14];\n out[15] = a[15] - b[15];\n return out;\n}\n\n/**\n * Multiply each element of the matrix by a scalar.\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to scale\n * @param {Number} b amount to scale the matrix's elements by\n * @returns {mat4} out\n */\nexport function multiplyScalar(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n out[2] = a[2] * b;\n out[3] = a[3] * b;\n out[4] = a[4] * b;\n out[5] = a[5] * b;\n out[6] = a[6] * b;\n out[7] = a[7] * b;\n out[8] = a[8] * b;\n out[9] = a[9] * b;\n out[10] = a[10] * b;\n out[11] = a[11] * b;\n out[12] = a[12] * b;\n out[13] = a[13] * b;\n out[14] = a[14] * b;\n out[15] = a[15] * b;\n return out;\n}\n\n/**\n * Adds two mat4's after multiplying each element of the second operand by a scalar value.\n *\n * @param {mat4} out the receiving vector\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @param {Number} scale the amount to scale b's elements by before adding\n * @returns {mat4} out\n */\nexport function multiplyScalarAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n out[2] = a[2] + b[2] * scale;\n out[3] = a[3] + b[3] * scale;\n out[4] = a[4] + b[4] * scale;\n out[5] = a[5] + b[5] * scale;\n out[6] = a[6] + b[6] * scale;\n out[7] = a[7] + b[7] * scale;\n out[8] = a[8] + b[8] * scale;\n out[9] = a[9] + b[9] * scale;\n out[10] = a[10] + b[10] * scale;\n out[11] = a[11] + b[11] * scale;\n out[12] = a[12] + b[12] * scale;\n out[13] = a[13] + b[13] * scale;\n out[14] = a[14] + b[14] * scale;\n out[15] = a[15] + b[15] * scale;\n return out;\n}\n\n/**\n * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyMat4} a The first matrix.\n * @param {ReadonlyMat4} b The second matrix.\n * @returns {Boolean} True if the matrices are equal, false otherwise.\n */\nexport function exactEquals(a, b) {\n return (\n a[0] === b[0] &&\n a[1] === b[1] &&\n a[2] === b[2] &&\n a[3] === b[3] &&\n a[4] === b[4] &&\n a[5] === b[5] &&\n a[6] === b[6] &&\n a[7] === b[7] &&\n a[8] === b[8] &&\n a[9] === b[9] &&\n a[10] === b[10] &&\n a[11] === b[11] &&\n a[12] === b[12] &&\n a[13] === b[13] &&\n a[14] === b[14] &&\n a[15] === b[15]\n );\n}\n\n/**\n * Returns whether or not the matrices have approximately the same elements in the same position.\n *\n * @param {ReadonlyMat4} a The first matrix.\n * @param {ReadonlyMat4} b The second matrix.\n * @returns {Boolean} True if the matrices are equal, false otherwise.\n */\nexport function equals(a, b) {\n const a0 = a[0];\n const a1 = a[1];\n const a2 = a[2];\n const a3 = a[3];\n const a4 = a[4];\n const a5 = a[5];\n const a6 = a[6];\n const a7 = a[7];\n const a8 = a[8];\n const a9 = a[9];\n const a10 = a[10];\n const a11 = a[11];\n const a12 = a[12];\n const a13 = a[13];\n const a14 = a[14];\n const a15 = a[15];\n\n const b0 = b[0];\n const b1 = b[1];\n const b2 = b[2];\n const b3 = b[3];\n const b4 = b[4];\n const b5 = b[5];\n const b6 = b[6];\n const b7 = b[7];\n const b8 = b[8];\n const b9 = b[9];\n const b10 = b[10];\n const b11 = b[11];\n const b12 = b[12];\n const b13 = b[13];\n const b14 = b[14];\n const b15 = b[15];\n\n return (\n Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) &&\n Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) &&\n Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) &&\n Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) &&\n Math.abs(a4 - b4) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) &&\n Math.abs(a5 - b5) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) &&\n Math.abs(a6 - b6) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) &&\n Math.abs(a7 - b7) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) &&\n Math.abs(a8 - b8) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8)) &&\n Math.abs(a9 - b9) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a9), Math.abs(b9)) &&\n Math.abs(a10 - b10) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a10), Math.abs(b10)) &&\n Math.abs(a11 - b11) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a11), Math.abs(b11)) &&\n Math.abs(a12 - b12) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a12), Math.abs(b12)) &&\n Math.abs(a13 - b13) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a13), Math.abs(b13)) &&\n Math.abs(a14 - b14) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a14), Math.abs(b14)) &&\n Math.abs(a15 - b15) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a15), Math.abs(b15))\n );\n}\n\n/**\n * Alias for {@link mat4.multiply}\n * @function\n */\nexport const mul = multiply;\n\n/**\n * Alias for {@link mat4.subtract}\n * @function\n */\nexport const sub = subtract;\n","// @eslint-disable\n// @ts-nocheck\n\nimport * as glMatrix from './common.js';\n\n/**\n * 4 Dimensional Vector\n * @module vec4\n */\n\n/**\n * Creates a new, empty vec4\n *\n * @returns {vec4} a new 4D vector\n */\nexport function create() {\n const out = new glMatrix.ARRAY_TYPE(4);\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[0] = 0;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n }\n return out;\n}\n\n/**\n * Creates a new vec4 initialized with values from an existing vector\n *\n * @param {ReadonlyVec4} a vector to clone\n * @returns {vec4} a new 4D vector\n */\nexport function clone(a) {\n const out = new glMatrix.ARRAY_TYPE(4);\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n return out;\n}\n\n/**\n * Creates a new vec4 initialized with the given values\n *\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @param {Number} w W component\n * @returns {vec4} a new 4D vector\n */\nexport function fromValues(x, y, z, w) {\n const out = new glMatrix.ARRAY_TYPE(4);\n out[0] = x;\n out[1] = y;\n out[2] = z;\n out[3] = w;\n return out;\n}\n\n/**\n * Copy the values from one vec4 to another\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the source vector\n * @returns {vec4} out\n */\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n return out;\n}\n\n/**\n * Set the components of a vec4 to the given values\n *\n * @param {vec4} out the receiving vector\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @param {Number} w W component\n * @returns {vec4} out\n */\nexport function set(out, x, y, z, w) {\n out[0] = x;\n out[1] = y;\n out[2] = z;\n out[3] = w;\n return out;\n}\n\n/**\n * Adds two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n out[2] = a[2] + b[2];\n out[3] = a[3] + b[3];\n return out;\n}\n\n/**\n * Subtracts vector b from vector a\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n out[2] = a[2] - b[2];\n out[3] = a[3] - b[3];\n return out;\n}\n\n/**\n * Multiplies two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\nexport function multiply(out, a, b) {\n out[0] = a[0] * b[0];\n out[1] = a[1] * b[1];\n out[2] = a[2] * b[2];\n out[3] = a[3] * b[3];\n return out;\n}\n\n/**\n * Divides two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\nexport function divide(out, a, b) {\n out[0] = a[0] / b[0];\n out[1] = a[1] / b[1];\n out[2] = a[2] / b[2];\n out[3] = a[3] / b[3];\n return out;\n}\n\n/**\n * Math.ceil the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to ceil\n * @returns {vec4} out\n */\nexport function ceil(out, a) {\n out[0] = Math.ceil(a[0]);\n out[1] = Math.ceil(a[1]);\n out[2] = Math.ceil(a[2]);\n out[3] = Math.ceil(a[3]);\n return out;\n}\n\n/**\n * Math.floor the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to floor\n * @returns {vec4} out\n */\nexport function floor(out, a) {\n out[0] = Math.floor(a[0]);\n out[1] = Math.floor(a[1]);\n out[2] = Math.floor(a[2]);\n out[3] = Math.floor(a[3]);\n return out;\n}\n\n/**\n * Returns the minimum of two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\nexport function min(out, a, b) {\n out[0] = Math.min(a[0], b[0]);\n out[1] = Math.min(a[1], b[1]);\n out[2] = Math.min(a[2], b[2]);\n out[3] = Math.min(a[3], b[3]);\n return out;\n}\n\n/**\n * Returns the maximum of two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\nexport function max(out, a, b) {\n out[0] = Math.max(a[0], b[0]);\n out[1] = Math.max(a[1], b[1]);\n out[2] = Math.max(a[2], b[2]);\n out[3] = Math.max(a[3], b[3]);\n return out;\n}\n\n/**\n * symmetric round the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to round\n * @returns {vec4} out\n */\nexport function round(out, a) {\n out[0] = glMatrix.round(a[0]);\n out[1] = glMatrix.round(a[1]);\n out[2] = glMatrix.round(a[2]);\n out[3] = glMatrix.round(a[3]);\n return out;\n}\n\n/**\n * Scales a vec4 by a scalar number\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the vector to scale\n * @param {Number} b amount to scale the vector by\n * @returns {vec4} out\n */\nexport function scale(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n out[2] = a[2] * b;\n out[3] = a[3] * b;\n return out;\n}\n\n/**\n * Adds two vec4's after scaling the second operand by a scalar value\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @param {Number} scale the amount to scale b by before adding\n * @returns {vec4} out\n */\nexport function scaleAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n out[2] = a[2] + b[2] * scale;\n out[3] = a[3] + b[3] * scale;\n return out;\n}\n\n/**\n * Calculates the euclidian distance between two vec4's\n *\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {Number} distance between a and b\n */\nexport function distance(a, b) {\n const x = b[0] - a[0];\n const y = b[1] - a[1];\n const z = b[2] - a[2];\n const w = b[3] - a[3];\n return Math.sqrt(x * x + y * y + z * z + w * w);\n}\n\n/**\n * Calculates the squared euclidian distance between two vec4's\n *\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {Number} squared distance between a and b\n */\nexport function squaredDistance(a, b) {\n const x = b[0] - a[0];\n const y = b[1] - a[1];\n const z = b[2] - a[2];\n const w = b[3] - a[3];\n return x * x + y * y + z * z + w * w;\n}\n\n/**\n * Calculates the length of a vec4\n *\n * @param {ReadonlyVec4} a vector to calculate length of\n * @returns {Number} length of a\n */\nexport function length(a) {\n const x = a[0];\n const y = a[1];\n const z = a[2];\n const w = a[3];\n return Math.sqrt(x * x + y * y + z * z + w * w);\n}\n\n/**\n * Calculates the squared length of a vec4\n *\n * @param {ReadonlyVec4} a vector to calculate squared length of\n * @returns {Number} squared length of a\n */\nexport function squaredLength(a) {\n const x = a[0];\n const y = a[1];\n const z = a[2];\n const w = a[3];\n return x * x + y * y + z * z + w * w;\n}\n\n/**\n * Negates the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to negate\n * @returns {vec4} out\n */\nexport function negate(out, a) {\n out[0] = -a[0];\n out[1] = -a[1];\n out[2] = -a[2];\n out[3] = -a[3];\n return out;\n}\n\n/**\n * Returns the inverse of the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to invert\n * @returns {vec4} out\n */\nexport function inverse(out, a) {\n out[0] = 1.0 / a[0];\n out[1] = 1.0 / a[1];\n out[2] = 1.0 / a[2];\n out[3] = 1.0 / a[3];\n return out;\n}\n\n/**\n * Normalize a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to normalize\n * @returns {vec4} out\n */\nexport function normalize(out, a) {\n const x = a[0];\n const y = a[1];\n const z = a[2];\n const w = a[3];\n let len = x * x + y * y + z * z + w * w;\n if (len > 0) {\n len = 1 / Math.sqrt(len);\n }\n out[0] = x * len;\n out[1] = y * len;\n out[2] = z * len;\n out[3] = w * len;\n return out;\n}\n\n/**\n * Calculates the dot product of two vec4's\n *\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {Number} dot product of a and b\n */\nexport function dot(a, b) {\n return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];\n}\n\n/**\n * Returns the cross-product of three vectors in a 4-dimensional space\n *\n * @param {ReadonlyVec4} result the receiving vector\n * @param {ReadonlyVec4} U the first vector\n * @param {ReadonlyVec4} V the second vector\n * @param {ReadonlyVec4} W the third vector\n * @returns {vec4} result\n */\nexport function cross(out, u, v, w) {\n const A = v[0] * w[1] - v[1] * w[0];\n const B = v[0] * w[2] - v[2] * w[0];\n const C = v[0] * w[3] - v[3] * w[0];\n const D = v[1] * w[2] - v[2] * w[1];\n const E = v[1] * w[3] - v[3] * w[1];\n const F = v[2] * w[3] - v[3] * w[2];\n const G = u[0];\n const H = u[1];\n const I = u[2];\n const J = u[3];\n\n out[0] = H * F - I * E + J * D;\n out[1] = -(G * F) + I * C - J * B;\n out[2] = G * E - H * C + J * A;\n out[3] = -(G * D) + H * B - I * A;\n\n return out;\n}\n\n/**\n * Performs a linear interpolation between two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec4} out\n */\nexport function lerp(out, a, b, t) {\n const ax = a[0];\n const ay = a[1];\n const az = a[2];\n const aw = a[3];\n out[0] = ax + t * (b[0] - ax);\n out[1] = ay + t * (b[1] - ay);\n out[2] = az + t * (b[2] - az);\n out[3] = aw + t * (b[3] - aw);\n return out;\n}\n\n/**\n * Generates a random vector with the given scale\n *\n * @param {vec4} out the receiving vector\n * @param {Number} [scale] Length of the resulting vector. If omitted, a unit vector will be returned\n * @returns {vec4} out\n */\nexport function random(out, scale) {\n scale = scale === undefined ? 1.0 : scale;\n\n // Marsaglia, George. Choosing a Point from the Surface of a\n // Sphere. Ann. Math. Statist. 43 (1972), no. 2, 645--646.\n // http://projecteuclid.org/euclid.aoms/1177692644;\n let v1;\n let v2;\n let v3;\n let v4;\n let s1;\n let s2;\n do {\n v1 = glMatrix.RANDOM() * 2 - 1;\n v2 = glMatrix.RANDOM() * 2 - 1;\n s1 = v1 * v1 + v2 * v2;\n } while (s1 >= 1);\n do {\n v3 = glMatrix.RANDOM() * 2 - 1;\n v4 = glMatrix.RANDOM() * 2 - 1;\n s2 = v3 * v3 + v4 * v4;\n } while (s2 >= 1);\n\n const d = Math.sqrt((1 - s1) / s2);\n out[0] = scale * v1;\n out[1] = scale * v2;\n out[2] = scale * v3 * d;\n out[3] = scale * v4 * d;\n return out;\n}\n\n/**\n * Transforms the vec4 with a mat4.\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the vector to transform\n * @param {ReadonlyMat4} m matrix to transform with\n * @returns {vec4} out\n */\nexport function transformMat4(out, a, m) {\n const x = a[0];\n const y = a[1];\n const z = a[2];\n const w = a[3];\n out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w;\n out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w;\n out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w;\n out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w;\n return out;\n}\n\n/**\n * Transforms the vec4 with a quat\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the vector to transform\n * @param {ReadonlyQuat} q quaternion to transform with\n * @returns {vec4} out\n */\nexport function transformQuat(out, a, q) {\n const x = a[0];\n const y = a[1];\n const z = a[2];\n const qx = q[0];\n const qy = q[1];\n const qz = q[2];\n const qw = q[3];\n\n // calculate quat * vec\n const ix = qw * x + qy * z - qz * y;\n const iy = qw * y + qz * x - qx * z;\n const iz = qw * z + qx * y - qy * x;\n const iw = -qx * x - qy * y - qz * z;\n\n // calculate result * inverse quat\n out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy;\n out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;\n out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;\n out[3] = a[3];\n return out;\n}\n\n/**\n * Set the components of a vec4 to zero\n *\n * @param {vec4} out the receiving vector\n * @returns {vec4} out\n */\nexport function zero(out) {\n out[0] = 0.0;\n out[1] = 0.0;\n out[2] = 0.0;\n out[3] = 0.0;\n return out;\n}\n\n/**\n * Returns a string representation of a vector\n *\n * @param {ReadonlyVec4} a vector to represent as a string\n * @returns {String} string representation of the vector\n */\nexport function str(a) {\n return `vec4(${a[0]}, ${a[1]}, ${a[2]}, ${a[3]})`;\n}\n\n/**\n * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyVec4} a The first vector.\n * @param {ReadonlyVec4} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3];\n}\n\n/**\n * Returns whether or not the vectors have approximately the same elements in the same position.\n *\n * @param {ReadonlyVec4} a The first vector.\n * @param {ReadonlyVec4} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\nexport function equals(a, b) {\n const a0 = a[0];\n const a1 = a[1];\n const a2 = a[2];\n const a3 = a[3];\n const b0 = b[0];\n const b1 = b[1];\n const b2 = b[2];\n const b3 = b[3];\n return (\n Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) &&\n Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) &&\n Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) &&\n Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3))\n );\n}\n\n/**\n * Alias for {@link vec4.subtract}\n * @function\n */\nexport const sub = subtract;\n\n/**\n * Alias for {@link vec4.multiply}\n * @function\n */\nexport const mul = multiply;\n\n/**\n * Alias for {@link vec4.divide}\n * @function\n */\nexport const div = divide;\n\n/**\n * Alias for {@link vec4.distance}\n * @function\n */\nexport const dist = distance;\n\n/**\n * Alias for {@link vec4.squaredDistance}\n * @function\n */\nexport const sqrDist = squaredDistance;\n\n/**\n * Alias for {@link vec4.length}\n * @function\n */\nexport const len = length;\n\n/**\n * Alias for {@link vec4.squaredLength}\n * @function\n */\nexport const sqrLen = squaredLength;\n\n/**\n * Perform some operation over an array of vec4s.\n *\n * @param {Array} a the array of vectors to iterate over\n * @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed\n * @param {Number} offset Number of elements to skip at the beginning of the array\n * @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array\n * @param {Function} fn Function to call for each vector in the array\n * @param {Object} [arg] additional argument to pass to fn\n * @returns {Array} a\n * @function\n */\nexport const forEach = (function () {\n const vec = create();\n\n return function (a, stride, offset, count, fn, arg) {\n let i;\n let l;\n if (!stride) {\n stride = 4;\n }\n\n if (!offset) {\n offset = 0;\n }\n\n if (count) {\n l = Math.min(count * stride + offset, a.length);\n } else {\n l = a.length;\n }\n\n for (i = offset; i < l; i += stride) {\n vec[0] = a[i];\n vec[1] = a[i + 1];\n vec[2] = a[i + 2];\n vec[3] = a[i + 3];\n fn(vec, vec, arg);\n a[i] = vec[0];\n a[i + 1] = vec[1];\n a[i + 2] = vec[2];\n a[i + 3] = vec[3];\n }\n\n return a;\n };\n})();\n","// math.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n// Copyright (c) 2017 Uber Technologies, Inc.\n\nimport {NumericArray, NumericArray16} from '@math.gl/types';\nimport {Matrix} from './base/matrix';\nimport {checkVector} from '../lib/validators';\n\n/* eslint-disable camelcase */\nimport {vec2_transformMat4AsVector, vec3_transformMat4AsVector} from '../lib/gl-matrix-extras';\n// @ts-ignore gl-matrix types...\nimport {\n fromQuat as mat4_fromQuat,\n frustum as mat4_frustum,\n lookAt as mat4_lookAt,\n ortho as mat4_ortho,\n perspective as mat4_perspective,\n determinant as mat4_determinant,\n transpose as mat4_transpose,\n invert as mat4_invert,\n multiply as mat4_multiply,\n rotateX as mat4_rotateX,\n rotateY as mat4_rotateY,\n rotateZ as mat4_rotateZ,\n rotate as mat4_rotate,\n scale as mat4_scale,\n translate as mat4_translate\n} from '../gl-matrix/mat4';\nimport {transformMat4 as vec2_transformMat4} from '../gl-matrix/vec2';\nimport {transformMat4 as vec3_transformMat4} from '../gl-matrix/vec3';\nimport {transformMat4 as vec4_transformMat4} from '../gl-matrix/vec4';\n\n// eslint-disable-next-line no-shadow\nenum INDICES {\n COL0ROW0 = 0,\n COL0ROW1 = 1,\n COL0ROW2 = 2,\n COL0ROW3 = 3,\n COL1ROW0 = 4,\n COL1ROW1 = 5,\n COL1ROW2 = 6,\n COL1ROW3 = 7,\n COL2ROW0 = 8,\n COL2ROW1 = 9,\n COL2ROW2 = 10,\n COL2ROW3 = 11,\n COL3ROW0 = 12,\n COL3ROW1 = 13,\n COL3ROW2 = 14,\n COL3ROW3 = 15\n}\n\nconst DEFAULT_FOVY = (45 * Math.PI) / 180;\nconst DEFAULT_ASPECT = 1;\nconst DEFAULT_NEAR = 0.1;\nconst DEFAULT_FAR = 500;\n\nconst IDENTITY_MATRIX = Object.freeze([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);\n\n/** Helper type that captures array length for a 4x4 matrix */\nexport type Matrix4Like = Matrix4 | NumericArray16;\n\n/**\n * A 4x4 matrix with common linear algebra operations\n * Subclass of Array meaning that it is highly compatible with other libraries\n */\nexport class Matrix4 extends Matrix {\n static get IDENTITY(): Readonly {\n return getIdentityMatrix();\n }\n\n static get ZERO(): Readonly {\n return getZeroMatrix();\n }\n\n get ELEMENTS(): number {\n return 16;\n }\n\n get RANK(): number {\n return 4;\n }\n\n get INDICES(): typeof INDICES {\n return INDICES;\n }\n\n constructor(array?: Readonly) {\n // PERF NOTE: initialize elements as double precision numbers\n super(-0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0);\n if (arguments.length === 1 && Array.isArray(array)) {\n this.copy(array);\n } else {\n this.identity();\n }\n }\n\n copy(array: Readonly): this {\n this[0] = array[0];\n this[1] = array[1];\n this[2] = array[2];\n this[3] = array[3];\n this[4] = array[4];\n this[5] = array[5];\n this[6] = array[6];\n this[7] = array[7];\n this[8] = array[8];\n this[9] = array[9];\n this[10] = array[10];\n this[11] = array[11];\n this[12] = array[12];\n this[13] = array[13];\n this[14] = array[14];\n this[15] = array[15];\n return this.check();\n }\n\n // eslint-disable-next-line max-params\n set(\n m00: number,\n m10: number,\n m20: number,\n m30: number,\n m01: number,\n m11: number,\n m21: number,\n m31: number,\n m02: number,\n m12: number,\n m22: number,\n m32: number,\n m03: number,\n m13: number,\n m23: number,\n m33: number\n ): this {\n this[0] = m00;\n this[1] = m10;\n this[2] = m20;\n this[3] = m30;\n this[4] = m01;\n this[5] = m11;\n this[6] = m21;\n this[7] = m31;\n this[8] = m02;\n this[9] = m12;\n this[10] = m22;\n this[11] = m32;\n this[12] = m03;\n this[13] = m13;\n this[14] = m23;\n this[15] = m33;\n return this.check();\n }\n\n // accepts row major order, stores as column major\n // eslint-disable-next-line max-params\n setRowMajor(\n m00: number,\n m01: number,\n m02: number,\n m03: number,\n m10: number,\n m11: number,\n m12: number,\n m13: number,\n m20: number,\n m21: number,\n m22: number,\n m23: number,\n m30: number,\n m31: number,\n m32: number,\n m33: number\n ): this {\n this[0] = m00;\n this[1] = m10;\n this[2] = m20;\n this[3] = m30;\n this[4] = m01;\n this[5] = m11;\n this[6] = m21;\n this[7] = m31;\n this[8] = m02;\n this[9] = m12;\n this[10] = m22;\n this[11] = m32;\n this[12] = m03;\n this[13] = m13;\n this[14] = m23;\n this[15] = m33;\n return this.check();\n }\n\n toRowMajor(result: NumericArray): NumericArray {\n result[0] = this[0];\n result[1] = this[4];\n result[2] = this[8];\n result[3] = this[12];\n result[4] = this[1];\n result[5] = this[5];\n result[6] = this[9];\n result[7] = this[13];\n result[8] = this[2];\n result[9] = this[6];\n result[10] = this[10];\n result[11] = this[14];\n result[12] = this[3];\n result[13] = this[7];\n result[14] = this[11];\n result[15] = this[15];\n return result;\n }\n\n // Constructors\n\n /** Set to identity matrix */\n identity(): this {\n return this.copy(IDENTITY_MATRIX);\n }\n\n /**\n *\n * @param object\n * @returns self\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n fromObject(object: {[key: string]: any}): this {\n return this.check();\n }\n\n /**\n * Calculates a 4x4 matrix from the given quaternion\n * @param quaternion Quaternion to create matrix from\n * @returns self\n */\n fromQuaternion(quaternion: Readonly): this {\n mat4_fromQuat(this, quaternion);\n return this.check();\n }\n\n /**\n * Generates a frustum matrix with the given bounds\n * @param view.left - Left bound of the frustum\n * @param view.right - Right bound of the frustum\n * @param view.bottom - Bottom bound of the frustum\n * @param view.top - Top bound of the frustum\n * @param view.near - Near bound of the frustum\n * @param view.far - Far bound of the frustum. Can be set to Infinity.\n * @returns self\n */\n frustum(view: {\n left: number;\n right: number;\n bottom: number;\n top: number;\n near: number;\n far?: number;\n }): this {\n const {left, right, bottom, top, near = DEFAULT_NEAR, far = DEFAULT_FAR} = view;\n if (far === Infinity) {\n computeInfinitePerspectiveOffCenter(this, left, right, bottom, top, near);\n } else {\n mat4_frustum(this, left, right, bottom, top, near, far);\n }\n return this.check();\n }\n\n /**\n * Generates a look-at matrix with the given eye position, focal point,\n * and up axis\n * @param view.eye - (vector) Position of the viewer\n * @param view.center - (vector) Point the viewer is looking at\n * @param view.up - (vector) Up axis\n * @returns self\n */\n lookAt(view: {\n eye: Readonly;\n center?: Readonly;\n up?: Readonly;\n }): this {\n const {eye, center = [0, 0, 0], up = [0, 1, 0]} = view;\n mat4_lookAt(this, eye, center, up);\n return this.check();\n }\n\n /**\n * Generates a orthogonal projection matrix with the given bounds\n * from \"traditional\" view space parameters\n * @param view.left - Left bound of the frustum\n * @param view.right number Right bound of the frustum\n * @param view.bottom - Bottom bound of the frustum\n * @param view.top number Top bound of the frustum\n * @param view.near - Near bound of the frustum\n * @param view.far number Far bound of the frustum\n * @returns self\n */\n ortho(view: {\n left: number;\n right: number;\n bottom: number;\n top: number;\n near?: number;\n far?: number;\n }): this {\n const {left, right, bottom, top, near = DEFAULT_NEAR, far = DEFAULT_FAR} = view;\n mat4_ortho(this, left, right, bottom, top, near, far);\n return this.check();\n }\n\n /**\n * Generates an orthogonal projection matrix with the same parameters\n * as a perspective matrix (plus focalDistance)\n * @param view.fovy Vertical field of view in radians\n * @param view.aspect Aspect ratio. Typically viewport width / viewport height\n * @param view.focalDistance Distance in the view frustum used for extent calculations\n * @param view.near Near bound of the frustum\n * @param view.far Far bound of the frustum\n * @returns self\n */\n orthographic(view: {\n fovy?: number;\n aspect?: number;\n focalDistance?: number;\n near?: number;\n far?: number;\n }): this {\n const {\n fovy = DEFAULT_FOVY,\n aspect = DEFAULT_ASPECT,\n focalDistance = 1,\n near = DEFAULT_NEAR,\n far = DEFAULT_FAR\n } = view;\n\n checkRadians(fovy);\n\n const halfY = fovy / 2;\n const top = focalDistance * Math.tan(halfY); // focus_plane is the distance from the camera\n const right = top * aspect;\n\n return this.ortho({\n left: -right,\n right,\n bottom: -top,\n top,\n near,\n far\n });\n }\n\n /**\n * Generates a perspective projection matrix with the given bounds\n * @param view.fovy Vertical field of view in radians\n * @param view.aspect Aspect ratio. typically viewport width/height\n * @param view.near Near bound of the frustum\n * @param view.far Far bound of the frustum\n * @returns self\n */\n perspective(view: {fovy: number; aspect?: number; near?: number; far?: number}): this {\n const {fovy = (45 * Math.PI) / 180, aspect = 1, near = 0.1, far = 500} = view;\n checkRadians(fovy);\n mat4_perspective(this, fovy, aspect, near, far);\n return this.check();\n }\n\n // Accessors\n\n determinant(): number {\n return mat4_determinant(this);\n }\n\n /**\n * Extracts the non-uniform scale assuming the matrix is an affine transformation.\n * The scales are the \"lengths\" of the column vectors in the upper-left 3x3 matrix.\n * @param result\n * @returns self\n */\n getScale(result: NumericArray = [-0, -0, -0]): NumericArray {\n // explicit is faster than hypot...\n result[0] = Math.sqrt(this[0] * this[0] + this[1] * this[1] + this[2] * this[2]);\n result[1] = Math.sqrt(this[4] * this[4] + this[5] * this[5] + this[6] * this[6]);\n result[2] = Math.sqrt(this[8] * this[8] + this[9] * this[9] + this[10] * this[10]);\n // result[0] = Math.hypot(this[0], this[1], this[2]);\n // result[1] = Math.hypot(this[4], this[5], this[6]);\n // result[2] = Math.hypot(this[8], this[9], this[10]);\n return result;\n }\n\n /**\n * Gets the translation portion, assuming the matrix is a affine transformation matrix.\n * @param result\n * @returns self\n */\n getTranslation(result: NumericArray = [-0, -0, -0]): NumericArray {\n result[0] = this[12];\n result[1] = this[13];\n result[2] = this[14];\n return result;\n }\n\n /**\n * Gets upper left 3x3 pure rotation matrix (non-scaling), assume affine transformation matrix\n * @param result\n * @param scaleResult\n * @returns self\n */\n getRotation(result?: NumericArray, scaleResult?: NumericArray): NumericArray {\n result = result || [-0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0];\n scaleResult = scaleResult || [-0, -0, -0];\n const scale = this.getScale(scaleResult);\n const inverseScale0 = 1 / scale[0];\n const inverseScale1 = 1 / scale[1];\n const inverseScale2 = 1 / scale[2];\n result[0] = this[0] * inverseScale0;\n result[1] = this[1] * inverseScale1;\n result[2] = this[2] * inverseScale2;\n result[3] = 0;\n result[4] = this[4] * inverseScale0;\n result[5] = this[5] * inverseScale1;\n result[6] = this[6] * inverseScale2;\n result[7] = 0;\n result[8] = this[8] * inverseScale0;\n result[9] = this[9] * inverseScale1;\n result[10] = this[10] * inverseScale2;\n result[11] = 0;\n result[12] = 0;\n result[13] = 0;\n result[14] = 0;\n result[15] = 1;\n return result;\n }\n\n /**\n *\n * @param result\n * @param scaleResult\n * @returns self\n */\n getRotationMatrix3(result?: NumericArray, scaleResult?: NumericArray): NumericArray {\n result = result || [-0, -0, -0, -0, -0, -0, -0, -0, -0];\n scaleResult = scaleResult || [-0, -0, -0];\n const scale = this.getScale(scaleResult);\n const inverseScale0 = 1 / scale[0];\n const inverseScale1 = 1 / scale[1];\n const inverseScale2 = 1 / scale[2];\n result[0] = this[0] * inverseScale0;\n result[1] = this[1] * inverseScale1;\n result[2] = this[2] * inverseScale2;\n result[3] = this[4] * inverseScale0;\n result[4] = this[5] * inverseScale1;\n result[5] = this[6] * inverseScale2;\n result[6] = this[8] * inverseScale0;\n result[7] = this[9] * inverseScale1;\n result[8] = this[10] * inverseScale2;\n return result;\n }\n\n // Modifiers\n\n transpose(): this {\n mat4_transpose(this, this);\n return this.check();\n }\n\n invert(): this {\n mat4_invert(this, this);\n return this.check();\n }\n\n // Operations\n\n multiplyLeft(a: Readonly): this {\n mat4_multiply(this, a, this);\n return this.check();\n }\n\n multiplyRight(a: Readonly): this {\n mat4_multiply(this, this, a);\n return this.check();\n }\n\n // Rotates a matrix by the given angle around the X axis\n rotateX(radians: number): this {\n mat4_rotateX(this, this, radians);\n // mat4_rotate(this, this, radians, [1, 0, 0]);\n return this.check();\n }\n\n // Rotates a matrix by the given angle around the Y axis.\n rotateY(radians: number): this {\n mat4_rotateY(this, this, radians);\n // mat4_rotate(this, this, radians, [0, 1, 0]);\n return this.check();\n }\n\n /**\n * Rotates a matrix by the given angle around the Z axis.\n * @param radians\n * @returns self\n */\n rotateZ(radians: number): this {\n mat4_rotateZ(this, this, radians);\n // mat4_rotate(this, this, radians, [0, 0, 1]);\n return this.check();\n }\n\n /**\n *\n * @param param0\n * @returns self\n */\n rotateXYZ(angleXYZ: Readonly): this {\n return this.rotateX(angleXYZ[0]).rotateY(angleXYZ[1]).rotateZ(angleXYZ[2]);\n }\n\n /**\n *\n * @param radians\n * @param axis\n * @returns self\n */\n rotateAxis(radians: number, axis: Readonly): this {\n mat4_rotate(this, this, radians, axis);\n return this.check();\n }\n\n /**\n *\n * @param factor\n * @returns self\n */\n override scale(factor: number | Readonly): this {\n mat4_scale(this, this, Array.isArray(factor) ? factor : [factor, factor, factor]);\n return this.check();\n }\n\n /**\n *\n * @param vec\n * @returns self\n */\n translate(vector: Readonly): this {\n mat4_translate(this, this, vector);\n return this.check();\n }\n\n // Transforms\n\n /**\n * Transforms any 2, 3 or 4 element vector. 2 and 3 elements are treated as points\n * @param vector\n * @param result\n * @returns self\n */\n transform(vector: Readonly, result?: NumericArray): NumericArray {\n if (vector.length === 4) {\n result = vec4_transformMat4(result || [-0, -0, -0, -0], vector, this) as NumericArray;\n checkVector(result, 4);\n return result;\n }\n return this.transformAsPoint(vector, result);\n }\n\n /**\n * Transforms any 2 or 3 element array as point (w implicitly 1)\n * @param vector\n * @param result\n * @returns self\n */\n transformAsPoint(vector: Readonly, result?: NumericArray): NumericArray {\n const {length} = vector;\n let out: NumericArray;\n switch (length) {\n case 2:\n out = vec2_transformMat4(result || [-0, -0], vector, this) as NumericArray;\n break;\n case 3:\n out = vec3_transformMat4(result || [-0, -0, -0], vector, this) as NumericArray;\n break;\n default:\n throw new Error('Illegal vector');\n }\n checkVector(out, vector.length);\n return out;\n }\n\n /**\n * Transforms any 2 or 3 element array as vector (w implicitly 0)\n * @param vector\n * @param result\n * @returns self\n */\n transformAsVector(vector: Readonly, result?: NumericArray): NumericArray {\n let out: NumericArray;\n switch (vector.length) {\n case 2:\n out = vec2_transformMat4AsVector(result || [-0, -0], vector, this);\n break;\n case 3:\n out = vec3_transformMat4AsVector(result || [-0, -0, -0], vector, this);\n break;\n default:\n throw new Error('Illegal vector');\n }\n checkVector(out, vector.length);\n return out;\n }\n\n /** @deprecated */\n transformPoint(vector: Readonly, result?: NumericArray): NumericArray {\n return this.transformAsPoint(vector, result);\n }\n\n /** @deprecated */\n transformVector(vector: Readonly, result?: NumericArray): NumericArray {\n return this.transformAsPoint(vector, result);\n }\n\n /** @deprecated */\n transformDirection(vector: Readonly, result?: NumericArray): NumericArray {\n return this.transformAsVector(vector, result);\n }\n\n // three.js math API compatibility\n\n makeRotationX(radians: number): this {\n return this.identity().rotateX(radians);\n }\n\n makeTranslation(x: number, y: number, z: number): this {\n return this.identity().translate([x, y, z]);\n }\n}\n\n// TODO initializing static members directly is an option, but make sure no tree-shaking issues\nlet ZERO: Matrix4;\nlet IDENTITY: Matrix4;\n\nfunction getZeroMatrix(): Readonly {\n if (!ZERO) {\n ZERO = new Matrix4([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);\n Object.freeze(ZERO);\n }\n return ZERO;\n}\n\nfunction getIdentityMatrix(): Matrix4 {\n if (!IDENTITY) {\n IDENTITY = new Matrix4();\n Object.freeze(IDENTITY);\n }\n return IDENTITY;\n}\n\n// HELPER FUNCTIONS\n\nfunction checkRadians(possiblyDegrees: number) {\n if (possiblyDegrees > Math.PI * 2) {\n throw Error('expected radians');\n }\n}\n\n// eslint-disable-next-line max-params\nfunction computeInfinitePerspectiveOffCenter(\n result: NumericArray,\n left: number,\n right: number,\n bottom: number,\n top: number,\n near: number\n): NumericArray {\n const column0Row0 = (2 * near) / (right - left);\n const column1Row1 = (2 * near) / (top - bottom);\n const column2Row0 = (right + left) / (right - left);\n const column2Row1 = (top + bottom) / (top - bottom);\n const column2Row2 = -1;\n const column2Row3 = -1;\n const column3Row2 = -2 * near;\n result[0] = column0Row0;\n result[1] = 0;\n result[2] = 0;\n result[3] = 0;\n result[4] = 0;\n result[5] = column1Row1;\n result[6] = 0;\n result[7] = 0;\n result[8] = column2Row0;\n result[9] = column2Row1;\n result[10] = column2Row2;\n result[11] = column2Row3;\n result[12] = 0;\n result[13] = 0;\n result[14] = column3Row2;\n result[15] = 0;\n return result;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {NumericArray} from '@math.gl/types';\n\n/**\n * Calculate WebGL 64 bit float\n * @param a - the input float number\n * @param out - the output array. If not supplied, a new array is created.\n * @param startIndex - the index in the output array to fill from. Default 0.\n * @returns - the fp64 representation of the input number\n */\nexport function fp64ify(a: number, out: NumericArray = [], startIndex: number = 0): NumericArray {\n const hiPart = Math.fround(a);\n const loPart = a - hiPart;\n out[startIndex] = hiPart;\n out[startIndex + 1] = loPart;\n return out;\n}\n\n/**\n * Calculate the low part of a WebGL 64 bit float\n * @param a the input float number\n * @returns the lower 32 bit of the number\n */\nexport function fp64LowPart(a: number): number {\n return a - Math.fround(a);\n}\n\n/**\n * Calculate WebGL 64 bit matrix (transposed \"Float64Array\")\n * @param matrix the input matrix\n * @returns the fp64 representation of the input matrix\n */\nexport function fp64ifyMatrix4(matrix: NumericArray): Float32Array {\n // Transpose the projection matrix to column major for GLSL.\n const matrixFP64 = new Float32Array(32);\n for (let i = 0; i < 4; ++i) {\n for (let j = 0; j < 4; ++j) {\n const index = i * 4 + j;\n fp64ify(matrix[j * 4 + i], matrixFP64, index * 2);\n }\n }\n return matrixFP64;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {NumberArray3, NumberArray4} from '@math.gl/types';\n\n/**\n * Resolves whether semantic colors should be interpreted as byte-style `0..255` values.\n * @param useByteColors - Explicit color interpretation flag.\n * @param defaultUseByteColors - Fallback value when `useByteColors` is omitted.\n * @returns `true` when semantic colors should be normalized from bytes, otherwise `false`.\n */\nexport function resolveUseByteColors(\n useByteColors?: boolean,\n defaultUseByteColors: boolean = true\n): boolean {\n return useByteColors ?? defaultUseByteColors;\n}\n\n/**\n * Normalizes an RGB semantic color to float space when byte-style colors are enabled.\n * @param color - Input RGB semantic color.\n * @param useByteColors - When `true`, divide components by `255`.\n * @returns The normalized RGB color.\n */\nexport function normalizeByteColor3(\n color: Readonly = [0, 0, 0],\n useByteColors: boolean = true\n): NumberArray3 {\n if (!useByteColors) {\n return [...color] as NumberArray3;\n }\n\n return color.map(component => component / 255) as NumberArray3;\n}\n\n/**\n * Normalizes an RGBA semantic color to float space when byte-style colors are enabled.\n * @param color - Input RGB or RGBA semantic color.\n * @param useByteColors - When `true`, divide components by `255`.\n * @returns The normalized RGBA color, adding an opaque alpha channel when needed.\n */\nexport function normalizeByteColor4(\n color: Readonly | Readonly,\n useByteColors: boolean = true\n): NumberArray4 {\n const normalizedColor = normalizeByteColor3(color.slice(0, 3) as NumberArray3, useByteColors);\n const hasAlpha = Number.isFinite(color[3]);\n const alpha = hasAlpha ? (color[3] as number) : 1;\n\n return [\n normalizedColor[0],\n normalizedColor[1],\n normalizedColor[2],\n useByteColors && hasAlpha ? alpha / 255 : alpha\n ] as NumberArray4;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// import {ShaderModule} from '../../types';\n\nconst fp32shader = /* glsl */ `\\\n#ifdef LUMA_FP32_TAN_PRECISION_WORKAROUND\n\n// All these functions are for substituting tan() function from Intel GPU only\nconst float TWO_PI = 6.2831854820251465;\nconst float PI_2 = 1.5707963705062866;\nconst float PI_16 = 0.1963495463132858;\n\nconst float SIN_TABLE_0 = 0.19509032368659973;\nconst float SIN_TABLE_1 = 0.3826834261417389;\nconst float SIN_TABLE_2 = 0.5555702447891235;\nconst float SIN_TABLE_3 = 0.7071067690849304;\n\nconst float COS_TABLE_0 = 0.9807852506637573;\nconst float COS_TABLE_1 = 0.9238795042037964;\nconst float COS_TABLE_2 = 0.8314695954322815;\nconst float COS_TABLE_3 = 0.7071067690849304;\n\nconst float INVERSE_FACTORIAL_3 = 1.666666716337204e-01; // 1/3!\nconst float INVERSE_FACTORIAL_5 = 8.333333767950535e-03; // 1/5!\nconst float INVERSE_FACTORIAL_7 = 1.9841270113829523e-04; // 1/7!\nconst float INVERSE_FACTORIAL_9 = 2.75573188446287533e-06; // 1/9!\n\nfloat sin_taylor_fp32(float a) {\n float r, s, t, x;\n\n if (a == 0.0) {\n return 0.0;\n }\n\n x = -a * a;\n s = a;\n r = a;\n\n r = r * x;\n t = r * INVERSE_FACTORIAL_3;\n s = s + t;\n\n r = r * x;\n t = r * INVERSE_FACTORIAL_5;\n s = s + t;\n\n r = r * x;\n t = r * INVERSE_FACTORIAL_7;\n s = s + t;\n\n r = r * x;\n t = r * INVERSE_FACTORIAL_9;\n s = s + t;\n\n return s;\n}\n\nvoid sincos_taylor_fp32(float a, out float sin_t, out float cos_t) {\n if (a == 0.0) {\n sin_t = 0.0;\n cos_t = 1.0;\n }\n sin_t = sin_taylor_fp32(a);\n cos_t = sqrt(1.0 - sin_t * sin_t);\n}\n\nfloat tan_taylor_fp32(float a) {\n float sin_a;\n float cos_a;\n\n if (a == 0.0) {\n return 0.0;\n }\n\n // 2pi range reduction\n float z = floor(a / TWO_PI);\n float r = a - TWO_PI * z;\n\n float t;\n float q = floor(r / PI_2 + 0.5);\n int j = int(q);\n\n if (j < -2 || j > 2) {\n return 1.0 / 0.0;\n }\n\n t = r - PI_2 * q;\n\n q = floor(t / PI_16 + 0.5);\n int k = int(q);\n int abs_k = int(abs(float(k)));\n\n if (abs_k > 4) {\n return 1.0 / 0.0;\n } else {\n t = t - PI_16 * q;\n }\n\n float u = 0.0;\n float v = 0.0;\n\n float sin_t, cos_t;\n float s, c;\n sincos_taylor_fp32(t, sin_t, cos_t);\n\n if (k == 0) {\n s = sin_t;\n c = cos_t;\n } else {\n if (abs(float(abs_k) - 1.0) < 0.5) {\n u = COS_TABLE_0;\n v = SIN_TABLE_0;\n } else if (abs(float(abs_k) - 2.0) < 0.5) {\n u = COS_TABLE_1;\n v = SIN_TABLE_1;\n } else if (abs(float(abs_k) - 3.0) < 0.5) {\n u = COS_TABLE_2;\n v = SIN_TABLE_2;\n } else if (abs(float(abs_k) - 4.0) < 0.5) {\n u = COS_TABLE_3;\n v = SIN_TABLE_3;\n }\n if (k > 0) {\n s = u * sin_t + v * cos_t;\n c = u * cos_t - v * sin_t;\n } else {\n s = u * sin_t - v * cos_t;\n c = u * cos_t + v * sin_t;\n }\n }\n\n if (j == 0) {\n sin_a = s;\n cos_a = c;\n } else if (j == 1) {\n sin_a = c;\n cos_a = -s;\n } else if (j == -1) {\n sin_a = -c;\n cos_a = s;\n } else {\n sin_a = -s;\n cos_a = -c;\n }\n return sin_a / cos_a;\n}\n#endif\n\nfloat tan_fp32(float a) {\n#ifdef LUMA_FP32_TAN_PRECISION_WORKAROUND\n return tan_taylor_fp32(a);\n#else\n return tan(a);\n#endif\n}\n`;\n\n/**\n * 32 bit math library (fixups for GPUs)\n */\nexport const fp32 = {\n name: 'fp32',\n vs: fp32shader\n};\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport const fp64arithmeticShader = /* glsl */ `\\\n\nlayout(std140) uniform fp64arithmeticUniforms {\n uniform float ONE;\n uniform float SPLIT;\n} fp64;\n\n/*\nAbout LUMA_FP64_CODE_ELIMINATION_WORKAROUND\n\nThe purpose of this workaround is to prevent shader compilers from\noptimizing away necessary arithmetic operations by swapping their sequences\nor transform the equation to some 'equivalent' form.\n\nThese helpers implement Dekker/Veltkamp-style error tracking. If the compiler\nfolds constants or reassociates the arithmetic, the high/low split can stop\ntracking the rounding error correctly. That failure mode tends to look fine in\nsimple coordinate setup, but then breaks down inside iterative arithmetic such\nas fp64 Mandelbrot loops.\n\nThe method is to multiply an artifical variable, ONE, which will be known to\nthe compiler to be 1 only at runtime. The whole expression is then represented\nas a polynomial with respective to ONE. In the coefficients of all terms, only one a\nand one b should appear\n\nerr = (a + b) * ONE^6 - a * ONE^5 - (a + b) * ONE^4 + a * ONE^3 - b - (a + b) * ONE^2 + a * ONE\n*/\n\nfloat prevent_fp64_optimization(float value) {\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n return value + fp64.ONE * 0.0;\n#else\n return value;\n#endif\n}\n\n// Divide float number to high and low floats to extend fraction bits\nvec2 split(float a) {\n // Keep SPLIT as a runtime uniform so the compiler cannot fold the Dekker\n // split into a constant expression and reassociate the recovery steps.\n float split = prevent_fp64_optimization(fp64.SPLIT);\n float t = prevent_fp64_optimization(a * split);\n float temp = t - a;\n float a_hi = t - temp;\n float a_lo = a - a_hi;\n return vec2(a_hi, a_lo);\n}\n\n// Divide float number again when high float uses too many fraction bits\nvec2 split2(vec2 a) {\n vec2 b = split(a.x);\n b.y += a.y;\n return b;\n}\n\n// Special sum operation when a > b\nvec2 quickTwoSum(float a, float b) {\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n float sum = (a + b) * fp64.ONE;\n float err = b - (sum - a) * fp64.ONE;\n#else\n float sum = a + b;\n float err = b - (sum - a);\n#endif\n return vec2(sum, err);\n}\n\n// General sum operation\nvec2 twoSum(float a, float b) {\n float s = (a + b);\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n float v = (s * fp64.ONE - a) * fp64.ONE;\n float err = (a - (s - v) * fp64.ONE) * fp64.ONE * fp64.ONE * fp64.ONE + (b - v);\n#else\n float v = s - a;\n float err = (a - (s - v)) + (b - v);\n#endif\n return vec2(s, err);\n}\n\nvec2 twoSub(float a, float b) {\n float s = (a - b);\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n float v = (s * fp64.ONE - a) * fp64.ONE;\n float err = (a - (s - v) * fp64.ONE) * fp64.ONE * fp64.ONE * fp64.ONE - (b + v);\n#else\n float v = s - a;\n float err = (a - (s - v)) - (b + v);\n#endif\n return vec2(s, err);\n}\n\nvec2 twoSqr(float a) {\n float prod = a * a;\n vec2 a_fp64 = split(a);\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n float err = ((a_fp64.x * a_fp64.x - prod) * fp64.ONE + 2.0 * a_fp64.x *\n a_fp64.y * fp64.ONE * fp64.ONE) + a_fp64.y * a_fp64.y * fp64.ONE * fp64.ONE * fp64.ONE;\n#else\n float err = ((a_fp64.x * a_fp64.x - prod) + 2.0 * a_fp64.x * a_fp64.y) + a_fp64.y * a_fp64.y;\n#endif\n return vec2(prod, err);\n}\n\nvec2 twoProd(float a, float b) {\n float prod = a * b;\n vec2 a_fp64 = split(a);\n vec2 b_fp64 = split(b);\n // twoProd is especially sensitive because mul_fp64 and div_fp64 both depend\n // on the split terms and cross terms staying in the original evaluation\n // order. If the compiler folds or reassociates them, the low part tends to\n // collapse to zero or NaN on some drivers.\n float highProduct = prevent_fp64_optimization(a_fp64.x * b_fp64.x);\n float crossProduct1 = prevent_fp64_optimization(a_fp64.x * b_fp64.y);\n float crossProduct2 = prevent_fp64_optimization(a_fp64.y * b_fp64.x);\n float lowProduct = prevent_fp64_optimization(a_fp64.y * b_fp64.y);\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n float err1 = (highProduct - prod) * fp64.ONE;\n float err2 = crossProduct1 * fp64.ONE * fp64.ONE;\n float err3 = crossProduct2 * fp64.ONE * fp64.ONE * fp64.ONE;\n float err4 = lowProduct * fp64.ONE * fp64.ONE * fp64.ONE * fp64.ONE;\n#else\n float err1 = highProduct - prod;\n float err2 = crossProduct1;\n float err3 = crossProduct2;\n float err4 = lowProduct;\n#endif\n float err = ((err1 + err2) + err3) + err4;\n return vec2(prod, err);\n}\n\nvec2 sum_fp64(vec2 a, vec2 b) {\n vec2 s, t;\n s = twoSum(a.x, b.x);\n t = twoSum(a.y, b.y);\n s.y += t.x;\n s = quickTwoSum(s.x, s.y);\n s.y += t.y;\n s = quickTwoSum(s.x, s.y);\n return s;\n}\n\nvec2 sub_fp64(vec2 a, vec2 b) {\n vec2 s, t;\n s = twoSub(a.x, b.x);\n t = twoSub(a.y, b.y);\n s.y += t.x;\n s = quickTwoSum(s.x, s.y);\n s.y += t.y;\n s = quickTwoSum(s.x, s.y);\n return s;\n}\n\nvec2 mul_fp64(vec2 a, vec2 b) {\n vec2 prod = twoProd(a.x, b.x);\n // y component is for the error\n prod.y += a.x * b.y;\n#if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND)\n prod = split2(prod);\n#endif\n prod = quickTwoSum(prod.x, prod.y);\n prod.y += a.y * b.x;\n#if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND)\n prod = split2(prod);\n#endif\n prod = quickTwoSum(prod.x, prod.y);\n return prod;\n}\n\nvec2 div_fp64(vec2 a, vec2 b) {\n float xn = 1.0 / b.x;\n#if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND)\n vec2 yn = mul_fp64(a, vec2(xn, 0));\n#else\n vec2 yn = a * xn;\n#endif\n float diff = (sub_fp64(a, mul_fp64(b, yn))).x;\n vec2 prod = twoProd(xn, diff);\n return sum_fp64(yn, prod);\n}\n\nvec2 sqrt_fp64(vec2 a) {\n if (a.x == 0.0 && a.y == 0.0) return vec2(0.0, 0.0);\n if (a.x < 0.0) return vec2(0.0 / 0.0, 0.0 / 0.0);\n\n float x = 1.0 / sqrt(a.x);\n float yn = a.x * x;\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n vec2 yn_sqr = twoSqr(yn) * fp64.ONE;\n#else\n vec2 yn_sqr = twoSqr(yn);\n#endif\n float diff = sub_fp64(a, yn_sqr).x;\n vec2 prod = twoProd(x * 0.5, diff);\n#if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND)\n return sum_fp64(split(yn), prod);\n#else\n return sum_fp64(vec2(yn, 0.0), prod);\n#endif\n}\n`;\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport const fp64arithmeticWGSL = /* wgsl */ `\\\nstruct Fp64ArithmeticUniforms {\n ONE: f32,\n SPLIT: f32,\n};\n\n@group(0) @binding(auto) var fp64arithmetic : Fp64ArithmeticUniforms;\n\nfn fp64_nan(seed: f32) -> f32 {\n let nanBits = 0x7fc00000u | select(0u, 1u, seed < 0.0);\n return bitcast(nanBits);\n}\n\nfn fp64_runtime_zero() -> f32 {\n return fp64arithmetic.ONE * 0.0;\n}\n\nfn prevent_fp64_optimization(value: f32) -> f32 {\n#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND\n return value + fp64_runtime_zero();\n#else\n return value;\n#endif\n}\n\nfn split(a: f32) -> vec2f {\n let splitValue = prevent_fp64_optimization(fp64arithmetic.SPLIT + fp64_runtime_zero());\n let t = prevent_fp64_optimization(a * splitValue);\n let temp = prevent_fp64_optimization(t - a);\n let aHi = prevent_fp64_optimization(t - temp);\n let aLo = prevent_fp64_optimization(a - aHi);\n return vec2f(aHi, aLo);\n}\n\nfn split2(a: vec2f) -> vec2f {\n var b = split(a.x);\n b.y = b.y + a.y;\n return b;\n}\n\nfn quickTwoSum(a: f32, b: f32) -> vec2f {\n#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND\n let sum = prevent_fp64_optimization((a + b) * fp64arithmetic.ONE);\n let err = prevent_fp64_optimization(b - (sum - a) * fp64arithmetic.ONE);\n#else\n let sum = prevent_fp64_optimization(a + b);\n let err = prevent_fp64_optimization(b - (sum - a));\n#endif\n return vec2f(sum, err);\n}\n\nfn twoSum(a: f32, b: f32) -> vec2f {\n let s = prevent_fp64_optimization(a + b);\n#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND\n let v = prevent_fp64_optimization((s * fp64arithmetic.ONE - a) * fp64arithmetic.ONE);\n let err =\n prevent_fp64_optimization((a - (s - v) * fp64arithmetic.ONE) *\n fp64arithmetic.ONE *\n fp64arithmetic.ONE *\n fp64arithmetic.ONE) +\n prevent_fp64_optimization(b - v);\n#else\n let v = prevent_fp64_optimization(s - a);\n let err = prevent_fp64_optimization(a - (s - v)) + prevent_fp64_optimization(b - v);\n#endif\n return vec2f(s, err);\n}\n\nfn twoSub(a: f32, b: f32) -> vec2f {\n let s = prevent_fp64_optimization(a - b);\n#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND\n let v = prevent_fp64_optimization((s * fp64arithmetic.ONE - a) * fp64arithmetic.ONE);\n let err =\n prevent_fp64_optimization((a - (s - v) * fp64arithmetic.ONE) *\n fp64arithmetic.ONE *\n fp64arithmetic.ONE *\n fp64arithmetic.ONE) -\n prevent_fp64_optimization(b + v);\n#else\n let v = prevent_fp64_optimization(s - a);\n let err = prevent_fp64_optimization(a - (s - v)) - prevent_fp64_optimization(b + v);\n#endif\n return vec2f(s, err);\n}\n\nfn twoSqr(a: f32) -> vec2f {\n let prod = prevent_fp64_optimization(a * a);\n let aFp64 = split(a);\n let highProduct = prevent_fp64_optimization(aFp64.x * aFp64.x);\n let crossProduct = prevent_fp64_optimization(2.0 * aFp64.x * aFp64.y);\n let lowProduct = prevent_fp64_optimization(aFp64.y * aFp64.y);\n#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND\n let err =\n (prevent_fp64_optimization(highProduct - prod) * fp64arithmetic.ONE +\n crossProduct * fp64arithmetic.ONE * fp64arithmetic.ONE) +\n lowProduct * fp64arithmetic.ONE * fp64arithmetic.ONE * fp64arithmetic.ONE;\n#else\n let err = ((prevent_fp64_optimization(highProduct - prod) + crossProduct) + lowProduct);\n#endif\n return vec2f(prod, err);\n}\n\nfn twoProd(a: f32, b: f32) -> vec2f {\n let prod = prevent_fp64_optimization(a * b);\n let aFp64 = split(a);\n let bFp64 = split(b);\n let highProduct = prevent_fp64_optimization(aFp64.x * bFp64.x);\n let crossProduct1 = prevent_fp64_optimization(aFp64.x * bFp64.y);\n let crossProduct2 = prevent_fp64_optimization(aFp64.y * bFp64.x);\n let lowProduct = prevent_fp64_optimization(aFp64.y * bFp64.y);\n#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND\n let err1 = (highProduct - prod) * fp64arithmetic.ONE;\n let err2 = crossProduct1 * fp64arithmetic.ONE * fp64arithmetic.ONE;\n let err3 = crossProduct2 * fp64arithmetic.ONE * fp64arithmetic.ONE * fp64arithmetic.ONE;\n let err4 =\n lowProduct *\n fp64arithmetic.ONE *\n fp64arithmetic.ONE *\n fp64arithmetic.ONE *\n fp64arithmetic.ONE;\n#else\n let err1 = highProduct - prod;\n let err2 = crossProduct1;\n let err3 = crossProduct2;\n let err4 = lowProduct;\n#endif\n let err12InputA = prevent_fp64_optimization(err1);\n let err12InputB = prevent_fp64_optimization(err2);\n let err12 = prevent_fp64_optimization(err12InputA + err12InputB);\n let err123InputA = prevent_fp64_optimization(err12);\n let err123InputB = prevent_fp64_optimization(err3);\n let err123 = prevent_fp64_optimization(err123InputA + err123InputB);\n let err1234InputA = prevent_fp64_optimization(err123);\n let err1234InputB = prevent_fp64_optimization(err4);\n let err = prevent_fp64_optimization(err1234InputA + err1234InputB);\n return vec2f(prod, err);\n}\n\nfn sum_fp64(a: vec2f, b: vec2f) -> vec2f {\n var s = twoSum(a.x, b.x);\n let t = twoSum(a.y, b.y);\n s.y = prevent_fp64_optimization(s.y + t.x);\n s = quickTwoSum(s.x, s.y);\n s.y = prevent_fp64_optimization(s.y + t.y);\n s = quickTwoSum(s.x, s.y);\n return s;\n}\n\nfn sub_fp64(a: vec2f, b: vec2f) -> vec2f {\n var s = twoSub(a.x, b.x);\n let t = twoSub(a.y, b.y);\n s.y = prevent_fp64_optimization(s.y + t.x);\n s = quickTwoSum(s.x, s.y);\n s.y = prevent_fp64_optimization(s.y + t.y);\n s = quickTwoSum(s.x, s.y);\n return s;\n}\n\nfn mul_fp64(a: vec2f, b: vec2f) -> vec2f {\n var prod = twoProd(a.x, b.x);\n let crossProduct1 = prevent_fp64_optimization(a.x * b.y);\n prod.y = prevent_fp64_optimization(prod.y + crossProduct1);\n#ifdef LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND\n prod = split2(prod);\n#endif\n prod = quickTwoSum(prod.x, prod.y);\n let crossProduct2 = prevent_fp64_optimization(a.y * b.x);\n prod.y = prevent_fp64_optimization(prod.y + crossProduct2);\n#ifdef LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND\n prod = split2(prod);\n#endif\n prod = quickTwoSum(prod.x, prod.y);\n return prod;\n}\n\nfn div_fp64(a: vec2f, b: vec2f) -> vec2f {\n let xn = prevent_fp64_optimization(1.0 / b.x);\n let yn = mul_fp64(a, vec2f(xn, fp64_runtime_zero()));\n let diff = prevent_fp64_optimization(sub_fp64(a, mul_fp64(b, yn)).x);\n let prod = twoProd(xn, diff);\n return sum_fp64(yn, prod);\n}\n\nfn sqrt_fp64(a: vec2f) -> vec2f {\n if (a.x == 0.0 && a.y == 0.0) {\n return vec2f(0.0, 0.0);\n }\n if (a.x < 0.0) {\n let nanValue = fp64_nan(a.x);\n return vec2f(nanValue, nanValue);\n }\n\n let x = prevent_fp64_optimization(1.0 / sqrt(a.x));\n let yn = prevent_fp64_optimization(a.x * x);\n#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND\n let ynSqr = twoSqr(yn) * fp64arithmetic.ONE;\n#else\n let ynSqr = twoSqr(yn);\n#endif\n let diff = prevent_fp64_optimization(sub_fp64(a, ynSqr).x);\n let prod = twoProd(prevent_fp64_optimization(x * 0.5), diff);\n#ifdef LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND\n return sum_fp64(split(yn), prod);\n#else\n return sum_fp64(vec2f(yn, 0.0), prod);\n#endif\n}\n`;\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {ShaderModule} from '../../../lib/shader-module/shader-module';\n\nimport {fp64ify, fp64LowPart, fp64ifyMatrix4} from '../../../modules/math/fp64/fp64-utils';\nimport {fp64arithmeticShader} from './fp64-arithmetic-glsl';\nimport {fp64arithmeticWGSL} from './fp64-arithmetic-wgsl';\nimport {fp64functionShader} from './fp64-functions-glsl';\n\ntype FP64Props = {};\ntype FP64Uniforms = {ONE: number; SPLIT: number};\ntype FP64Bindings = {};\n\ntype FP64Utilities = {\n fp64ify: typeof fp64ify;\n fp64LowPart: typeof fp64LowPart;\n fp64ifyMatrix4: typeof fp64ifyMatrix4;\n};\n\nconst defaultUniforms: FP64Uniforms = {\n // Used in LUMA_FP64_CODE_ELIMINATION_WORKAROUND\n ONE: 1.0,\n // Runtime split factor for Dekker splitting. Keeping this as a uniform helps\n // prevent aggressive constant folding in shader compilers.\n SPLIT: 4097.0\n};\n\n/**\n * 64bit arithmetic: add, sub, mul, div (small subset of fp64 module)\n */\nexport const fp64arithmetic: ShaderModule & FP64Utilities = {\n name: 'fp64arithmetic',\n source: fp64arithmeticWGSL,\n fs: fp64arithmeticShader,\n vs: fp64arithmeticShader,\n defaultUniforms,\n uniformTypes: {ONE: 'f32', SPLIT: 'f32'},\n\n // Additional Functions\n fp64ify,\n fp64LowPart,\n fp64ifyMatrix4\n};\n\n/**\n * Full 64 bit math library\n */\nexport const fp64: ShaderModule<{}> & FP64Utilities = {\n name: 'fp64',\n vs: fp64functionShader,\n dependencies: [fp64arithmetic],\n\n // Additional Functions\n fp64ify,\n fp64LowPart,\n fp64ifyMatrix4\n};\n\nexport {fp64ify, fp64LowPart, fp64ifyMatrix4};\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {ShaderModule} from '../../../lib/shader-module/shader-module';\nimport type {NumberArray3, NumberArray4} from '@math.gl/core';\nimport {normalizeByteColor4, resolveUseByteColors} from '../../../lib/color/normalize-byte-colors';\n\n// cyan color\nconst DEFAULT_HIGHLIGHT_COLOR: NumberArray4 = [0, 1, 1, 1];\n\n/**\n * Props for the picking module, which depending on mode renders picking colors or highlighted item.\n * When active, renders picking colors, assumed to be rendered to off-screen \"picking\" buffer.\n * When inactive, renders normal colors, with the exception of selected object which is rendered with highlight\n */\nexport type PickingProps = {\n /** Are we picking? I.e. rendering picking colors? */\n isActive?: boolean;\n /** Set to true when picking an attribute value instead of object index */\n isAttribute?: boolean;\n /** Set to a picking color to visually highlight that item, or `null` to explicitly clear **/\n highlightedObjectColor?: NumberArray3 | null;\n /** Color of visual highlight of \"selected\" item */\n highlightColor?: NumberArray3 | NumberArray4;\n /** Interpret highlight colors as byte-style 0-255 values. */\n useByteColors?: boolean;\n};\n\n/**\n * Uniforms for the picking module, which renders picking colors and highlighted item.\n * When active, renders picking colors, assumed to be rendered to off-screen \"picking\" buffer.\n * When inactive, renders normal colors, with the exception of selected object which is rendered with highlight\n */\nexport type PickingUniforms = {\n /**\n * When true, renders picking colors. Set when rendering to off-screen \"picking\" buffer.\n * When false, renders normal colors, with the exception of selected object which is rendered with highlight\n */\n isActive?: boolean;\n /** Set to true when picking an attribute value instead of object index */\n isAttribute?: boolean;\n /** Interpret highlight colors as byte-style 0-255 values. */\n useByteColors?: boolean;\n /** Do we have a highlighted item? */\n isHighlightActive?: boolean;\n /** Set to a picking color to visually highlight that item */\n highlightedObjectColor?: NumberArray3;\n /** Color of visual highlight of \"selected\" item */\n highlightColor?: NumberArray4;\n};\n\nconst vs = /* glsl */ `\\\nlayout(std140) uniform pickingUniforms {\n float isActive;\n float isAttribute;\n float isHighlightActive;\n float useByteColors;\n vec3 highlightedObjectColor;\n vec4 highlightColor;\n} picking;\n\nout vec4 picking_vRGBcolor_Avalid;\n\n// Normalize unsigned byte color to 0-1 range\nvec3 picking_normalizeColor(vec3 color) {\n return picking.useByteColors > 0.5 ? color / 255.0 : color;\n}\n\n// Normalize unsigned byte color to 0-1 range\nvec4 picking_normalizeColor(vec4 color) {\n return picking.useByteColors > 0.5 ? color / 255.0 : color;\n}\n\nbool picking_isColorZero(vec3 color) {\n return dot(color, vec3(1.0)) < 0.00001;\n}\n\nbool picking_isColorValid(vec3 color) {\n return dot(color, vec3(1.0)) > 0.00001;\n}\n\n// Check if this vertex is highlighted \nbool isVertexHighlighted(vec3 vertexColor) {\n vec3 highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor);\n return\n bool(picking.isHighlightActive) && picking_isColorZero(abs(vertexColor - highlightedObjectColor));\n}\n\n// Set the current picking color\nvoid picking_setPickingColor(vec3 pickingColor) {\n pickingColor = picking_normalizeColor(pickingColor);\n\n if (bool(picking.isActive)) {\n // Use alpha as the validity flag. If pickingColor is [0, 0, 0] fragment is non-pickable\n picking_vRGBcolor_Avalid.a = float(picking_isColorValid(pickingColor));\n\n if (!bool(picking.isAttribute)) {\n // Stores the picking color so that the fragment shader can render it during picking\n picking_vRGBcolor_Avalid.rgb = pickingColor;\n }\n } else {\n // Do the comparison with selected item color in vertex shader as it should mean fewer compares\n picking_vRGBcolor_Avalid.a = float(isVertexHighlighted(pickingColor));\n }\n}\n\nvoid picking_setPickingAttribute(float value) {\n if (bool(picking.isAttribute)) {\n picking_vRGBcolor_Avalid.r = value;\n }\n}\n\nvoid picking_setPickingAttribute(vec2 value) {\n if (bool(picking.isAttribute)) {\n picking_vRGBcolor_Avalid.rg = value;\n }\n}\n\nvoid picking_setPickingAttribute(vec3 value) {\n if (bool(picking.isAttribute)) {\n picking_vRGBcolor_Avalid.rgb = value;\n }\n}\n`;\n\nconst fs = /* glsl */ `\\\nlayout(std140) uniform pickingUniforms {\n float isActive;\n float isAttribute;\n float isHighlightActive;\n float useByteColors;\n vec3 highlightedObjectColor;\n vec4 highlightColor;\n} picking;\n\nin vec4 picking_vRGBcolor_Avalid;\n\n/*\n * Returns highlight color if this item is selected.\n */\nvec4 picking_filterHighlightColor(vec4 color) {\n // If we are still picking, we don't highlight\n if (picking.isActive > 0.5) {\n return color;\n }\n\n bool selected = bool(picking_vRGBcolor_Avalid.a);\n\n if (selected) {\n // Blend in highlight color based on its alpha value\n float highLightAlpha = picking.highlightColor.a;\n float blendedAlpha = highLightAlpha + color.a * (1.0 - highLightAlpha);\n float highLightRatio = highLightAlpha / blendedAlpha;\n\n vec3 blendedRGB = mix(color.rgb, picking.highlightColor.rgb, highLightRatio);\n return vec4(blendedRGB, blendedAlpha);\n } else {\n return color;\n }\n}\n\n/*\n * Returns picking color if picking enabled else unmodified argument.\n */\nvec4 picking_filterPickingColor(vec4 color) {\n if (bool(picking.isActive)) {\n if (picking_vRGBcolor_Avalid.a == 0.0) {\n discard;\n }\n return picking_vRGBcolor_Avalid;\n }\n return color;\n}\n\n/*\n * Returns picking color if picking is enabled if not\n * highlight color if this item is selected, otherwise unmodified argument.\n */\nvec4 picking_filterColor(vec4 color) {\n vec4 highlightColor = picking_filterHighlightColor(color);\n return picking_filterPickingColor(highlightColor);\n}\n`;\n\n/**\n * Deprecated legacy picking module retained for compatibility with existing\n * shadertools users such as deck.gl. Keep the shader contract stable.\n *\n * Provides support for color-coding-based picking and highlighting.\n * In particular, supports picking a specific instance in an instanced\n * draw call and highlighting an instance based on its picking color,\n * and correspondingly, supports picking and highlighting groups of\n * primitives with the same picking color in non-instanced draw-calls\n */\nexport const picking = {\n props: {} as PickingProps,\n uniforms: {} as PickingUniforms,\n\n name: 'picking',\n\n uniformTypes: {\n isActive: 'f32',\n isAttribute: 'f32',\n isHighlightActive: 'f32',\n useByteColors: 'f32',\n highlightedObjectColor: 'vec3',\n highlightColor: 'vec4'\n },\n defaultUniforms: {\n isActive: false,\n isAttribute: false,\n isHighlightActive: false,\n useByteColors: true,\n highlightedObjectColor: [0, 0, 0],\n highlightColor: DEFAULT_HIGHLIGHT_COLOR\n },\n\n vs,\n fs,\n getUniforms\n} as const satisfies ShaderModule;\n\nfunction getUniforms(opts: PickingProps = {}, prevUniforms?: PickingUniforms): PickingUniforms {\n const uniforms = {} as PickingUniforms;\n const useByteColors = resolveUseByteColors(opts.useByteColors, true);\n\n if (opts.highlightedObjectColor === undefined) {\n // Unless highlightedObjectColor explicitly null or set, do not update state\n } else if (opts.highlightedObjectColor === null) {\n uniforms.isHighlightActive = false;\n } else {\n uniforms.isHighlightActive = true;\n const highlightedObjectColor = opts.highlightedObjectColor.slice(0, 3) as NumberArray3;\n uniforms.highlightedObjectColor = highlightedObjectColor;\n }\n\n if (opts.highlightColor) {\n uniforms.highlightColor = normalizeByteColor4(opts.highlightColor, useByteColors);\n }\n\n if (opts.isActive !== undefined) {\n uniforms.isActive = Boolean(opts.isActive);\n uniforms.isAttribute = Boolean(opts.isAttribute);\n }\n\n if (opts.useByteColors !== undefined) {\n uniforms.useByteColors = Boolean(opts.useByteColors);\n }\n\n return uniforms;\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ShaderModule} from '@luma.gl/shadertools';\nimport type {LayerProps} from '../../types/layer-props';\n\nconst uniformBlockWGSL = /* wgsl */ `\\\nstruct LayerUniforms {\n opacity: f32,\n};\n\n@group(0) @binding(auto)\nvar layer: LayerUniforms;\n`;\n\nconst uniformBlock = `\\\nlayout(std140) uniform layerUniforms {\n uniform float opacity;\n} layer;\n`;\n\nexport type LayerUniforms = {\n opacity?: number;\n};\n\nexport const layerUniforms = {\n name: 'layer',\n source: uniformBlockWGSL,\n vs: uniformBlock,\n fs: uniformBlock,\n getUniforms: (props: Partial) => {\n return {\n // apply gamma to opacity to make it visually \"linear\"\n // TODO - v10: use raw opacity?\n opacity: Math.pow(props.opacity!, 1 / 2.2)\n };\n },\n uniformTypes: {\n opacity: 'f32'\n }\n} as const satisfies ShaderModule;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {ShaderModule} from '@luma.gl/shadertools';\nimport {LayerProps} from '../../types/layer-props';\n\nconst colorWGSL = /* WGSL */ `\n\n@must_use\nfn deckgl_premultiplied_alpha(fragColor: vec4) -> vec4 {\n return vec4(fragColor.rgb * fragColor.a, fragColor.a); \n};\n`;\n\nexport type ColorProps = {\n /**\n * Opacity of the layer, between 0 and 1. Default 1.\n */\n opacity?: number;\n};\n\nexport type ColorUniforms = {\n opacity?: number;\n};\n\nexport default {\n name: 'color',\n dependencies: [],\n source: colorWGSL,\n getUniforms: (_props: Partial) => {\n // TODO (kaapp) Handle layer opacity\n // apply gamma to opacity to make it visually \"linear\"\n // TODO - v10: use raw opacity?\n // opacity: Math.pow(props.opacity!, 1 / 2.2)\n return {};\n }\n // @ts-ignore TODO v9.1\n} as const satisfies ShaderModule;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ShaderModule} from '@luma.gl/shadertools';\n\nconst source = /* wgsl */ `\\\nconst SMOOTH_EDGE_RADIUS: f32 = 0.5;\n\nstruct VertexGeometry {\n position: vec4,\n worldPosition: vec3,\n worldPositionAlt: vec3,\n normal: vec3,\n uv: vec2,\n pickingColor: vec3,\n};\n\nvar geometry_: VertexGeometry = VertexGeometry(\n vec4(0.0, 0.0, 1.0, 0.0),\n vec3(0.0, 0.0, 0.0),\n vec3(0.0, 0.0, 0.0),\n vec3(0.0, 0.0, 0.0),\n vec2(0.0, 0.0),\n vec3(0.0, 0.0, 0.0)\n);\n\nstruct FragmentGeometry {\n uv: vec2,\n};\n\nvar fragmentGeometry: FragmentGeometry;\n\nfn smoothedge(edge: f32, x: f32) -> f32 {\n return smoothstep(edge - SMOOTH_EDGE_RADIUS, edge + SMOOTH_EDGE_RADIUS, x);\n}\n`;\n\nconst defines = '#define SMOOTH_EDGE_RADIUS 0.5';\n\nconst vs = /* glsl */ `\\\n${defines}\n\nstruct VertexGeometry {\n vec4 position;\n vec3 worldPosition;\n vec3 worldPositionAlt;\n vec3 normal;\n vec2 uv;\n vec3 pickingColor;\n} geometry = VertexGeometry(\n vec4(0.0, 0.0, 1.0, 0.0),\n vec3(0.0),\n vec3(0.0),\n vec3(0.0),\n vec2(0.0),\n vec3(0.0)\n);\n`;\n\nconst fs = /* glsl */ `\\\n${defines}\n\nstruct FragmentGeometry {\n vec2 uv;\n} geometry;\n\nfloat smoothedge(float edge, float x) {\n return smoothstep(edge - SMOOTH_EDGE_RADIUS, edge + SMOOTH_EDGE_RADIUS, x);\n}\n`;\n\nexport default {\n name: 'geometry',\n source,\n vs,\n fs\n} as const satisfies ShaderModule;\n","export const MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;\n\nexport const COMPUTE_INTERVAL = 25;\n\nexport enum InputEvent {\n Start = 1,\n Move = 2,\n End = 4,\n Cancel = 8\n}\n\nexport enum InputDirection {\n None = 0,\n Left = 1,\n Right = 2,\n Up = 4,\n Down = 8,\n Horizontal = 3,\n Vertical = 12,\n All = 15\n}\n","export enum RecognizerState {\n Possible = 1,\n Began = 2,\n Changed = 4,\n Ended = 8,\n Recognized = 8, // eslint-disable-line\n Cancelled = 16,\n Failed = 32\n}\n","// magical touchAction value\nexport const TOUCH_ACTION_COMPUTE = 'compute';\nexport const TOUCH_ACTION_AUTO = 'auto';\nexport const TOUCH_ACTION_MANIPULATION = 'manipulation'; // not implemented\nexport const TOUCH_ACTION_NONE = 'none';\nexport const TOUCH_ACTION_PAN_X = 'pan-x';\nexport const TOUCH_ACTION_PAN_Y = 'pan-y';\n","import {\n TOUCH_ACTION_NONE,\n TOUCH_ACTION_PAN_X,\n TOUCH_ACTION_PAN_Y,\n TOUCH_ACTION_MANIPULATION,\n TOUCH_ACTION_AUTO\n} from './touchaction-Consts';\n\n/**\n * when the touchActions are collected they are not a valid value, so we need to clean things up. *\n * @returns valid touchAction\n */\nexport default function cleanTouchActions(actions: string): string {\n // none\n if (actions.includes(TOUCH_ACTION_NONE)) {\n return TOUCH_ACTION_NONE;\n }\n\n const hasPanX = actions.includes(TOUCH_ACTION_PAN_X);\n const hasPanY = actions.includes(TOUCH_ACTION_PAN_Y);\n\n // if both pan-x and pan-y are set (different recognizers\n // for different directions, e.g. horizontal pan but vertical swipe?)\n // we need none (as otherwise with pan-x pan-y combined none of these\n // recognizers will work, since the browser would handle all panning\n if (hasPanX && hasPanY) {\n return TOUCH_ACTION_NONE;\n }\n\n // pan-x OR pan-y\n if (hasPanX || hasPanY) {\n return hasPanX ? TOUCH_ACTION_PAN_X : TOUCH_ACTION_PAN_Y;\n }\n\n // manipulation\n if (actions.includes(TOUCH_ACTION_MANIPULATION)) {\n return TOUCH_ACTION_MANIPULATION;\n }\n\n return TOUCH_ACTION_AUTO;\n}\n","import {TOUCH_ACTION_COMPUTE} from './touchaction-Consts';\nimport cleanTouchActions from './clean-touch-actions';\n\nimport type {Manager} from '../manager';\n\n/**\n * Touch Action\n * sets the touchAction property or uses the js alternative\n */\nexport class TouchAction {\n manager: Manager;\n actions: string = '';\n\n constructor(manager: Manager, value: string) {\n this.manager = manager;\n this.set(value);\n }\n\n /**\n * set the touchAction value on the element or enable the polyfill\n */\n set(value: string) {\n // find out the touch-action by the event handlers\n if (value === TOUCH_ACTION_COMPUTE) {\n value = this.compute();\n }\n\n if (this.manager.element) {\n this.manager.element.style.touchAction = value;\n this.actions = value;\n }\n }\n\n /**\n * just re-set the touchAction value\n */\n update() {\n this.set(this.manager.options.touchAction);\n }\n\n /**\n * compute the value for the touchAction property based on the recognizer's settings\n */\n compute(): string {\n let actions: string[] = [];\n for (const recognizer of this.manager.recognizers) {\n if (recognizer.options.enable) {\n actions = actions.concat(recognizer.getTouchAction());\n }\n }\n return cleanTouchActions(actions.join(' '));\n }\n}\n","/**\n * split string on whitespace\n * @returns {Array} words\n */\nexport function splitStr(str: string): string[] {\n return str.trim().split(/\\s+/g);\n}\n","import {splitStr} from './split-str';\n\n/**\n * addEventListener with multiple events at once\n */\nexport function addEventListeners(\n target: EventTarget | null,\n types: string,\n handler: EventListener\n) {\n if (!target) {\n return;\n }\n for (const type of splitStr(types)) {\n target.addEventListener(type, handler, false);\n }\n}\n\n/**\n * removeEventListener with multiple events at once\n */\nexport function removeEventListeners(\n target: EventTarget | null,\n types: string,\n handler: EventListener\n) {\n if (!target) {\n return;\n }\n for (const type of splitStr(types)) {\n target.removeEventListener(type, handler, false);\n }\n}\n","/**\n * get the window object of an element\n */\nexport function getWindowForElement(element: HTMLElement): Window | null {\n const doc = element.ownerDocument || (element as unknown as Document);\n return doc.defaultView;\n}\n","/**\n * find if a node is in the given parent\n */\nexport default function hasParent(node: HTMLElement, parent: HTMLElement): boolean {\n let ancestor: Node | null = node;\n while (ancestor) {\n if (ancestor === parent) {\n return true;\n }\n ancestor = ancestor.parentNode;\n }\n return false;\n}\n","import type {Point, PointerEventLike} from './types';\n\n/**\n * get the center of all the pointers\n */\nexport function getCenter(pointers: PointerEventLike[]): Point {\n const pointersLength = pointers.length;\n\n // no need to loop when only one touch\n if (pointersLength === 1) {\n return {\n x: Math.round(pointers[0].clientX),\n y: Math.round(pointers[0].clientY)\n };\n }\n\n let x = 0;\n let y = 0;\n let i = 0;\n while (i < pointersLength) {\n x += pointers[i].clientX;\n y += pointers[i].clientY;\n i++;\n }\n\n return {\n x: Math.round(x / pointersLength),\n y: Math.round(y / pointersLength)\n };\n}\n","import {getCenter} from './get-center';\nimport type {RawInput, PointerEventLike, SimpleInput} from './types';\n\n/**\n * create a simple clone from the input used for storage of firstInput and firstMultiple\n */\nexport function simpleCloneInputData(input: RawInput): SimpleInput {\n // make a simple copy of the pointers because we will get a reference if we don't\n const pointers: PointerEventLike[] = [];\n let i = 0;\n while (i < input.pointers.length) {\n pointers[i] = {\n clientX: Math.round(input.pointers[i].clientX),\n clientY: Math.round(input.pointers[i].clientY)\n };\n i++;\n }\n\n return {\n timeStamp: Date.now(),\n pointers,\n center: getCenter(pointers),\n deltaX: input.deltaX,\n deltaY: input.deltaY\n };\n}\n","import type {Point, PointerEventLike} from './types';\n\n/**\n * calculate the absolute distance between two points\n * @returns distance\n */\nexport function getPointDistance(p1: Point, p2: Point): number {\n const x = p2.x - p1.x;\n const y = p2.y - p1.y;\n return Math.sqrt(x * x + y * y);\n}\n\n/**\n * calculate the absolute distance between two pointer events\n * @returns distance\n */\nexport function getEventDistance(p1: PointerEventLike, p2: PointerEventLike): number {\n const x = p2.clientX - p1.clientX;\n const y = p2.clientY - p1.clientY;\n return Math.sqrt(x * x + y * y);\n}\n","import {Point, PointerEventLike} from './types';\n\n/**\n * calculate the angle between two coordinates\n * @returns angle in degrees\n */\nexport function getPointAngle(p1: Point, p2: Point) {\n const x: number = p2.x - p1.x;\n const y: number = p2.y - p1.y;\n return (Math.atan2(y, x) * 180) / Math.PI;\n}\n\n/**\n * calculate the angle between two pointer events\n * @returns angle in degrees\n */\nexport function getEventAngle(p1: PointerEventLike, p2: PointerEventLike) {\n const x: number = p2.clientX - p1.clientX;\n const y: number = p2.clientY - p1.clientY;\n return (Math.atan2(y, x) * 180) / Math.PI;\n}\n","import {InputDirection} from './input-consts';\n\n/**\n * get the direction between two points\n * @returns direction\n */\nexport function getDirection(dx: number, dy: number): InputDirection {\n if (dx === dy) {\n return InputDirection.None;\n }\n\n if (Math.abs(dx) >= Math.abs(dy)) {\n return dx < 0 ? InputDirection.Left : InputDirection.Right;\n }\n return dy < 0 ? InputDirection.Up : InputDirection.Down;\n}\n","import {InputEvent} from './input-consts';\nimport type {RawInput, Session} from './types';\n\n/** Populates input.deltaX, input.deltaY */\nexport function computeDeltaXY(\n session: Session,\n input: RawInput\n): {\n deltaX: number;\n deltaY: number;\n} {\n // getCenter is called before computeDeltaXY\n const center = input.center!;\n let offset = session.offsetDelta;\n let prevDelta = session.prevDelta;\n const prevInput = session.prevInput;\n\n if (input.eventType === InputEvent.Start || prevInput?.eventType === InputEvent.End) {\n prevDelta = session.prevDelta = {\n x: prevInput?.deltaX || 0,\n y: prevInput?.deltaY || 0\n };\n\n offset = session.offsetDelta = {\n x: center.x,\n y: center.y\n };\n }\n\n return {\n deltaX: prevDelta!.x + (center.x - offset!.x),\n deltaY: prevDelta!.y + (center.y - offset!.y)\n };\n}\n","import type {Vector} from './types';\n\n/**\n * calculate the velocity between two points. unit is in px per ms.\n */\nexport function getVelocity(deltaTime: number, x: number, y: number): Vector {\n return {\n x: x / deltaTime || 0,\n y: y / deltaTime || 0\n };\n}\n","import {getEventDistance} from './get-distance';\nimport type {PointerEventLike} from './types';\n\n/**\n * calculate the scale factor between two pointersets\n * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out\n */\nexport function getScale(start: PointerEventLike[], end: PointerEventLike[]): number {\n return getEventDistance(end[0], end[1]) / getEventDistance(start[0], start[1]);\n}\n","import {getEventAngle} from './get-angle';\nimport {PointerEventLike} from './types';\n\n/**\n * calculate the rotation degrees between two pointer sets\n * @returns rotation in degrees\n */\nexport function getRotation(start: PointerEventLike[], end: PointerEventLike[]): number {\n return getEventAngle(end[1], end[0]) - getEventAngle(start[1], start[0]);\n}\n","import {InputEvent, COMPUTE_INTERVAL} from './input-consts';\nimport {getVelocity} from './get-velocity';\nimport {getDirection} from './get-direction';\n\nimport type {Session, HammerInput} from './types';\n\n/**\n * velocity is calculated every x ms\n */\nexport function computeIntervalInputData(session: Session, input: HammerInput) {\n const last = session.lastInterval || input;\n const deltaTime = input.timeStamp - last.timeStamp;\n let velocity;\n let velocityX;\n let velocityY;\n let direction;\n\n if (\n input.eventType !== InputEvent.Cancel &&\n (deltaTime > COMPUTE_INTERVAL || last.velocity === undefined)\n ) {\n const deltaX = input.deltaX - last.deltaX;\n const deltaY = input.deltaY - last.deltaY;\n\n const v = getVelocity(deltaTime, deltaX, deltaY);\n velocityX = v.x;\n velocityY = v.y;\n velocity = Math.abs(v.x) > Math.abs(v.y) ? v.x : v.y;\n direction = getDirection(deltaX, deltaY);\n\n session.lastInterval = input;\n } else {\n // use latest velocity info if it doesn't overtake a minimum period\n velocity = last.velocity;\n velocityX = last.velocityX;\n velocityY = last.velocityY;\n direction = last.direction;\n }\n\n input.velocity = velocity;\n input.velocityX = velocityX;\n input.velocityY = velocityY;\n input.direction = direction;\n}\n","import hasParent from '../utils/has-parent';\nimport {simpleCloneInputData} from './simple-clone-input-data';\nimport {getCenter} from './get-center';\nimport {getPointDistance} from './get-distance';\nimport {getPointAngle} from './get-angle';\nimport {getDirection} from './get-direction';\nimport {computeDeltaXY} from './get-delta-xy';\nimport {getVelocity} from './get-velocity';\nimport {getScale} from './get-scale';\nimport {getRotation} from './get-rotation';\nimport {computeIntervalInputData} from './compute-interval-input-data';\n\nimport type {Manager} from '../manager';\nimport type {RawInput, HammerInput} from './types';\n\n/**\n * extend the data with some usable properties like scale, rotate, velocity etc\n */\nexport function computeInputData(manager: Manager, input: RawInput): HammerInput {\n const {session} = manager;\n const {pointers} = input;\n const {length: pointersLength} = pointers;\n\n // store the first input to calculate the distance and direction\n if (!session.firstInput) {\n session.firstInput = simpleCloneInputData(input);\n }\n\n // to compute scale and rotation we need to store the multiple touches\n if (pointersLength > 1 && !session.firstMultiple) {\n session.firstMultiple = simpleCloneInputData(input);\n } else if (pointersLength === 1) {\n session.firstMultiple = false;\n }\n\n const {firstInput, firstMultiple} = session;\n const offsetCenter = firstMultiple ? firstMultiple.center : firstInput.center;\n\n const center = (input.center = getCenter(pointers));\n input.timeStamp = Date.now();\n input.deltaTime = input.timeStamp - firstInput.timeStamp;\n\n input.angle = getPointAngle(offsetCenter, center);\n input.distance = getPointDistance(offsetCenter, center);\n\n const {deltaX, deltaY} = computeDeltaXY(session, input);\n input.deltaX = deltaX;\n input.deltaY = deltaY;\n input.offsetDirection = getDirection(input.deltaX, input.deltaY);\n\n const overallVelocity = getVelocity(input.deltaTime, input.deltaX, input.deltaY);\n input.overallVelocityX = overallVelocity.x;\n input.overallVelocityY = overallVelocity.y;\n input.overallVelocity =\n Math.abs(overallVelocity.x) > Math.abs(overallVelocity.y)\n ? overallVelocity.x\n : overallVelocity.y;\n\n input.scale = firstMultiple ? getScale(firstMultiple.pointers, pointers) : 1;\n input.rotation = firstMultiple ? getRotation(firstMultiple.pointers, pointers) : 0;\n\n input.maxPointers = !session.prevInput\n ? input.pointers.length\n : input.pointers.length > session.prevInput.maxPointers\n ? input.pointers.length\n : session.prevInput.maxPointers;\n\n // find the correct target\n let target = manager.element!;\n if (hasParent(input.srcEvent.target as HTMLElement, target)) {\n target = input.srcEvent.target as HTMLElement;\n }\n input.target = target;\n\n computeIntervalInputData(session, input as HammerInput);\n\n // All the optional fields have been populated\n return input as HammerInput;\n}\n","import {InputEvent} from './input-consts';\nimport {computeInputData} from './compute-input-data';\n\nimport type {Manager} from '../manager';\nimport type {RawInput} from './types';\n\n/**\n * handle input events\n */\nexport function inputHandler(manager: Manager, eventType: InputEvent, input: RawInput) {\n const pointersLen = input.pointers.length;\n const changedPointersLen = input.changedPointers.length;\n const isFirst = eventType & InputEvent.Start && pointersLen - changedPointersLen === 0;\n const isFinal =\n eventType & (InputEvent.End | InputEvent.Cancel) && pointersLen - changedPointersLen === 0;\n\n input.isFirst = Boolean(isFirst);\n input.isFinal = Boolean(isFinal);\n\n if (isFirst) {\n manager.session = {};\n }\n\n // source event is the normalized value of the domEvents\n // like 'touchstart, mouseup, pointerdown'\n input.eventType = eventType;\n\n // compute scale, rotation etc\n const processedInput = computeInputData(manager, input);\n\n // emit secret event\n manager.emit('hammer.input', processedInput);\n\n manager.recognize(processedInput);\n manager.session.prevInput = processedInput;\n}\n","import {addEventListeners, removeEventListeners} from '../utils/event-listeners';\nimport {getWindowForElement} from '../utils/get-window-for-element';\nimport {inputHandler} from './input-handler';\n\nimport {InputEvent} from './input-consts';\nimport type {RawInput} from './types';\nimport type {Manager} from '../manager';\n\n/**\n * create new input type manager\n */\nexport abstract class Input {\n manager: Manager;\n element: HTMLElement;\n target: EventTarget;\n\n evEl: string = '';\n evWin: string = '';\n evTarget: string = '';\n\n constructor(manager: Manager) {\n this.manager = manager;\n this.element = manager.element!;\n this.target = manager.options.inputTarget || manager.element!;\n }\n\n /** smaller wrapper around the handler, for the scope and the enabled state of the manager,\n * so when disabled the input events are completely bypassed.\n */\n protected domHandler = (ev: Event) => {\n if (this.manager.options.enable) {\n this.handler(ev);\n }\n };\n\n protected callback(eventType: InputEvent, input: RawInput) {\n inputHandler(this.manager, eventType, input);\n }\n\n /**\n * should handle the inputEvent data and trigger the callback\n */\n abstract handler(ev: Event): void;\n\n // eslint-disable @typescript-eslint/unbound-method\n /**\n * bind the events\n */\n init() {\n addEventListeners(this.element, this.evEl, this.domHandler);\n addEventListeners(this.target, this.evTarget, this.domHandler);\n addEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);\n }\n\n /**\n * unbind the events\n */\n destroy() {\n removeEventListeners(this.element, this.evEl, this.domHandler);\n removeEventListeners(this.target, this.evTarget, this.domHandler);\n removeEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);\n }\n // eslint-enable @typescript-eslint/unbound-method\n}\n","import {InputEvent} from '../input/input-consts';\nimport {Input} from '../input/input';\nimport type {Manager} from '../manager';\n\nconst POINTER_INPUT_MAP = {\n pointerdown: InputEvent.Start,\n pointermove: InputEvent.Move,\n pointerup: InputEvent.End,\n pointercancel: InputEvent.Cancel,\n pointerout: InputEvent.Cancel\n} as const;\n\nconst POINTER_ELEMENT_EVENTS = 'pointerdown';\nconst POINTER_WINDOW_EVENTS = 'pointermove pointerup pointercancel';\n\n/**\n * Pointer events input\n */\nexport class PointerEventInput extends Input {\n store: PointerEvent[];\n\n constructor(manager: Manager) {\n super(manager);\n this.evEl = POINTER_ELEMENT_EVENTS;\n this.evWin = POINTER_WINDOW_EVENTS;\n\n this.store = this.manager.session.pointerEvents = [];\n this.init();\n }\n\n /**\n * handle mouse events\n */\n handler(ev: PointerEvent) {\n const {store} = this;\n let removePointer = false;\n\n // @ts-ignore\n const eventType = POINTER_INPUT_MAP[ev.type];\n const pointerType = ev.pointerType;\n\n const isTouch = pointerType === 'touch';\n\n // get index of the event in the store\n let storeIndex = store.findIndex((e) => e.pointerId === ev.pointerId);\n\n // start and mouse must be down\n if (eventType & InputEvent.Start && (ev.buttons || isTouch)) {\n if (storeIndex < 0) {\n store.push(ev);\n storeIndex = store.length - 1;\n }\n } else if (eventType & (InputEvent.End | InputEvent.Cancel)) {\n removePointer = true;\n }\n\n // it not found, so the pointer hasn't been down (so it's probably a hover)\n if (storeIndex < 0) {\n return;\n }\n\n // update the event in the store\n store[storeIndex] = ev;\n\n this.callback(eventType, {\n pointers: store,\n changedPointers: [ev],\n eventType,\n pointerType,\n srcEvent: ev\n });\n\n if (removePointer) {\n // remove from the store\n store.splice(storeIndex, 1);\n }\n }\n}\n","const VENDOR_PREFIXES = ['', 'webkit', 'Moz', 'MS', 'ms', 'o'];\n\n/**\n * get the prefixed property\n * @returns prefixed property name\n */\nexport function prefixed(obj: Record, property: string): string | undefined {\n const camelProp = property[0].toUpperCase() + property.slice(1);\n\n for (const prefix of VENDOR_PREFIXES) {\n const prop = prefix ? prefix + camelProp : property;\n\n if (prop in obj) {\n return prop;\n }\n }\n return undefined;\n}\n","import {TouchAction} from './touchaction/touchaction';\nimport {PointerEventInput} from './inputs/pointerevent';\nimport {splitStr} from './utils/split-str';\nimport {prefixed} from './utils/prefixed';\nimport {RecognizerState} from './recognizer/recognizer-state';\n\nimport type {Input} from './input/input';\nimport type {Recognizer} from './recognizer/recognizer';\nimport type {Session, HammerInput} from './input/types';\n\nconst STOP = 1;\nconst FORCED_STOP = 2;\n\nexport type ManagerOptions = {\n /**\n * The value for the touchAction property/fallback.\n * When set to `compute` it will magically set the correct value based on the added recognizers.\n * @default compute\n */\n touchAction?: string;\n\n /**\n * @default true\n */\n enable?: boolean;\n\n /**\n * EXPERIMENTAL FEATURE -- can be removed/changed\n * Change the parent input target element.\n * If Null, then it is being set the to main element.\n * @default null\n */\n inputTarget?: null | EventTarget;\n\n /**\n * Some CSS properties can be used to improve the working of Hammer.\n * Add them to this method and they will be set when creating a new Manager.\n */\n cssProps?: Partial;\n};\n\nexport type HammerEvent = HammerInput & {\n type: string;\n preventDefault: () => void;\n};\nexport type EventHandler = (event: HammerEvent) => void;\n\nconst defaultOptions: Required = {\n touchAction: 'compute',\n enable: true,\n inputTarget: null,\n cssProps: {\n /**\n * Disables text selection to improve the dragging gesture. Mainly for desktop browsers.\n */\n userSelect: 'none',\n /**\n * (Webkit) Disable default dragging behavior\n */\n // @ts-ignore\n userDrag: 'none',\n /**\n * (iOS only) Disables the default callout shown when you touch and hold a touch target.\n * When you touch and hold a touch target such as a link, Safari displays\n * a callout containing information about the link. This property allows you to disable that callout.\n */\n // @ts-ignore\n touchCallout: 'none',\n /**\n * (iOS only) Sets the color of the highlight that appears over a link while it's being tapped.\n */\n // @ts-ignore\n tapHighlightColor: 'rgba(0,0,0,0)'\n }\n};\n\n/**\n * Manager\n */\nexport class Manager {\n options: Required;\n\n element: HTMLElement | null;\n touchAction: TouchAction;\n oldCssProps: {[prop: string]: any};\n session: Session;\n recognizers: Recognizer[];\n input: Input;\n handlers: {[event: string]: EventHandler[]};\n\n constructor(element: HTMLElement, options: ManagerOptions) {\n this.options = {\n ...defaultOptions,\n ...options,\n cssProps: {...defaultOptions.cssProps, ...options.cssProps},\n inputTarget: options.inputTarget || element\n };\n\n this.handlers = {};\n this.session = {};\n this.recognizers = [];\n this.oldCssProps = {};\n\n this.element = element;\n this.input = new PointerEventInput(this);\n this.touchAction = new TouchAction(this, this.options.touchAction);\n\n this.toggleCssProps(true);\n }\n\n /**\n * set options\n */\n set(options: Partial) {\n Object.assign(this.options, options);\n\n // Options that need a little more setup\n if (options.touchAction) {\n this.touchAction.update();\n }\n if (options.inputTarget) {\n // Clean up existing event listeners and reinitialize\n this.input.destroy();\n this.input.target = options.inputTarget;\n this.input.init();\n }\n return this;\n }\n\n /**\n * stop recognizing for this session.\n * This session will be discarded, when a new [input]start event is fired.\n * When forced, the recognizer cycle is stopped immediately.\n */\n stop(force?: boolean) {\n this.session.stopped = force ? FORCED_STOP : STOP;\n }\n\n /**\n * run the recognizers!\n * called by the inputHandler function on every movement of the pointers (touches)\n * it walks through all the recognizers and tries to detect the gesture that is being made\n */\n recognize(inputData: HammerInput) {\n const {session} = this;\n if (session.stopped) {\n return;\n }\n\n // run the touch-action polyfill\n if (this.session.prevented) {\n inputData.srcEvent.preventDefault();\n }\n\n let recognizer;\n const {recognizers} = this;\n\n // this holds the recognizer that is being recognized.\n // so the recognizer's state needs to be BEGAN, CHANGED, ENDED or RECOGNIZED\n // if no recognizer is detecting a thing, it is set to `null`\n let {curRecognizer} = session;\n\n // reset when the last recognizer is recognized\n // or when we're in a new session\n if (!curRecognizer || (curRecognizer && curRecognizer.state & RecognizerState.Recognized)) {\n curRecognizer = session.curRecognizer = null;\n }\n\n let i = 0;\n while (i < recognizers.length) {\n recognizer = recognizers[i];\n\n // find out if we are allowed try to recognize the input for this one.\n // 1. allow if the session is NOT forced stopped (see the .stop() method)\n // 2. allow if we still haven't recognized a gesture in this session, or the this recognizer is the one\n // that is being recognized.\n // 3. allow if the recognizer is allowed to run simultaneous with the current recognized recognizer.\n // this can be setup with the `recognizeWith()` method on the recognizer.\n if (\n session.stopped !== FORCED_STOP && // 1\n (!curRecognizer ||\n recognizer === curRecognizer || // 2\n recognizer.canRecognizeWith(curRecognizer))\n ) {\n // 3\n recognizer.recognize(inputData);\n } else {\n recognizer.reset();\n }\n\n // if the recognizer has been recognizing the input as a valid gesture, we want to store this one as the\n // current active recognizer. but only if we don't already have an active recognizer\n if (\n !curRecognizer &&\n recognizer.state & (RecognizerState.Began | RecognizerState.Changed | RecognizerState.Ended)\n ) {\n curRecognizer = session.curRecognizer = recognizer;\n }\n i++;\n }\n }\n\n /**\n * get a recognizer by its event name.\n */\n get(recognizerName: string): Recognizer | null {\n const {recognizers} = this;\n for (let i = 0; i < recognizers.length; i++) {\n if (recognizers[i].options.event === recognizerName) {\n return recognizers[i];\n }\n }\n return null;\n }\n\n /**\n * add a recognizer to the manager\n * existing recognizers with the same event name will be removed\n */\n add(recognizer: Recognizer | Recognizer[]) {\n if (Array.isArray(recognizer)) {\n for (const item of recognizer) {\n this.add(item);\n }\n return this;\n }\n\n // remove existing\n const existing = this.get(recognizer.options.event);\n if (existing) {\n this.remove(existing);\n }\n\n this.recognizers.push(recognizer);\n recognizer.manager = this;\n\n this.touchAction.update();\n return recognizer;\n }\n\n /**\n * remove a recognizer by name or instance\n */\n remove(recognizerOrName: Recognizer | string | (Recognizer | string)[]) {\n if (Array.isArray(recognizerOrName)) {\n for (const item of recognizerOrName) {\n this.remove(item);\n }\n return this;\n }\n\n const recognizer =\n typeof recognizerOrName === 'string' ? this.get(recognizerOrName) : recognizerOrName;\n\n // let's make sure this recognizer exists\n if (recognizer) {\n const {recognizers} = this;\n const index = recognizers.indexOf(recognizer);\n\n if (index !== -1) {\n recognizers.splice(index, 1);\n this.touchAction.update();\n }\n }\n\n return this;\n }\n\n /**\n * bind event\n */\n on(events: string, handler: EventHandler) {\n if (!events || !handler) {\n return;\n }\n const {handlers} = this;\n for (const event of splitStr(events)) {\n handlers[event] = handlers[event] || [];\n handlers[event].push(handler);\n }\n }\n\n /**\n * unbind event, leave hander blank to remove all handlers\n */\n off(events: string, handler?: EventHandler) {\n if (!events) {\n return;\n }\n\n const {handlers} = this;\n for (const event of splitStr(events)) {\n if (!handler) {\n delete handlers[event];\n } else if (handlers[event]) {\n handlers[event].splice(handlers[event].indexOf(handler), 1);\n }\n }\n }\n\n /**\n * emit event to the listeners\n */\n emit(event: string, data: HammerInput) {\n // no handlers, so skip it all\n const handlers = this.handlers[event] && this.handlers[event].slice();\n if (!handlers || !handlers.length) {\n return;\n }\n\n const evt = data as HammerEvent;\n evt.type = event;\n evt.preventDefault = function () {\n data.srcEvent.preventDefault();\n };\n\n let i = 0;\n while (i < handlers.length) {\n handlers[i](evt);\n i++;\n }\n }\n\n /**\n * destroy the manager and unbinds all events\n * it doesn't unbind dom events, that is the user own responsibility\n */\n destroy() {\n this.toggleCssProps(false);\n\n this.handlers = {};\n this.session = {};\n this.input.destroy();\n this.element = null;\n }\n\n /**\n * add/remove the css properties as defined in manager.options.cssProps\n */\n private toggleCssProps(add: boolean) {\n const {element} = this;\n if (!element) {\n return;\n }\n for (const [name, value] of Object.entries(this.options.cssProps)) {\n const prop = prefixed(element.style, name) as any;\n if (add) {\n this.oldCssProps[prop] = element.style[prop];\n element.style[prop] = value as any;\n } else {\n element.style[prop] = this.oldCssProps[prop] || '';\n }\n }\n if (!add) {\n this.oldCssProps = {};\n }\n }\n}\n","/**\n * get a unique id\n */\nlet _uniqueId = 1;\nexport function uniqueId(): number {\n return _uniqueId++;\n}\n","import {RecognizerState} from './recognizer-state';\n\n/**\n * get a usable string, used as event postfix\n */\nexport function stateStr(state: RecognizerState) {\n if (state & RecognizerState.Cancelled) {\n return 'cancel';\n } else if (state & RecognizerState.Ended) {\n return 'end';\n } else if (state & RecognizerState.Changed) {\n return 'move';\n } else if (state & RecognizerState.Began) {\n return 'start';\n }\n return '';\n}\n","import {RecognizerState} from './recognizer-state';\nimport {uniqueId} from '../utils/unique-id';\nimport {stateStr} from './state-str';\n\nimport type {Manager} from '../manager';\nimport type {HammerInput} from '../input/types';\n\nexport type RecognizerOptions = {\n /** Name of the event */\n event: string;\n /** Enable this recognizer */\n enable: boolean;\n};\n\n/**\n * Recognizer flow explained; *\n * All recognizers have the initial state of POSSIBLE when a input session starts.\n * The definition of a input session is from the first input until the last input, with all it's movement in it. *\n * Example session for mouse-input: mousedown -> mousemove -> mouseup\n *\n * On each recognizing cycle (see Manager.recognize) the .recognize() method is executed\n * which determines with state it should be.\n *\n * If the recognizer has the state FAILED, CANCELLED or RECOGNIZED (equals ENDED), it is reset to\n * POSSIBLE to give it another change on the next cycle.\n *\n * Possible\n * |\n * +-----+---------------+\n * | |\n * +-----+-----+ |\n * | | |\n * Failed Cancelled |\n * +-------+------+\n * | |\n * Recognized Began\n * |\n * Changed\n * |\n * Ended/Recognized\n */\n\n/**\n * Recognizer\n * Every recognizer needs to extend from this class.\n */\nexport abstract class Recognizer {\n id: number;\n state: RecognizerState;\n manager!: Manager;\n\n readonly options: OptionsT;\n\n protected simultaneous: {[id: string]: Recognizer};\n protected requireFail: Recognizer[];\n\n constructor(options: OptionsT) {\n this.options = options;\n\n this.id = uniqueId();\n\n this.state = RecognizerState.Possible;\n this.simultaneous = {};\n this.requireFail = [];\n }\n\n /**\n * set options\n */\n set(options: Partial) {\n Object.assign(this.options, options);\n\n // also update the touchAction, in case something changed about the directions/enabled state\n this.manager.touchAction.update();\n return this;\n }\n\n /**\n * recognize simultaneous with an other recognizer.\n */\n recognizeWith(recognizerOrName: Recognizer | string | (Recognizer | string)[]) {\n if (Array.isArray(recognizerOrName)) {\n for (const item of recognizerOrName) {\n this.recognizeWith(item);\n }\n return this;\n }\n\n let otherRecognizer: Recognizer | null;\n if (typeof recognizerOrName === 'string') {\n otherRecognizer = this.manager.get(recognizerOrName);\n if (!otherRecognizer) {\n throw new Error(`Cannot find recognizer ${recognizerOrName}`);\n }\n } else {\n otherRecognizer = recognizerOrName;\n }\n const {simultaneous} = this;\n if (!simultaneous[otherRecognizer.id]) {\n simultaneous[otherRecognizer.id] = otherRecognizer;\n otherRecognizer.recognizeWith(this);\n }\n return this;\n }\n\n /**\n * drop the simultaneous link. it doesnt remove the link on the other recognizer.\n */\n dropRecognizeWith(recognizerOrName: Recognizer | string | (Recognizer | string)[]) {\n if (Array.isArray(recognizerOrName)) {\n for (const item of recognizerOrName) {\n this.dropRecognizeWith(item);\n }\n return this;\n }\n\n let otherRecognizer: Recognizer | null;\n if (typeof recognizerOrName === 'string') {\n otherRecognizer = this.manager.get(recognizerOrName);\n } else {\n otherRecognizer = recognizerOrName;\n }\n if (otherRecognizer) {\n delete this.simultaneous[otherRecognizer.id];\n }\n return this;\n }\n\n /**\n * recognizer can only run when an other is failing\n */\n requireFailure(recognizerOrName: Recognizer | string | (Recognizer | string)[]) {\n if (Array.isArray(recognizerOrName)) {\n for (const item of recognizerOrName) {\n this.requireFailure(item);\n }\n return this;\n }\n\n let otherRecognizer: Recognizer | null;\n if (typeof recognizerOrName === 'string') {\n otherRecognizer = this.manager.get(recognizerOrName);\n if (!otherRecognizer) {\n throw new Error(`Cannot find recognizer ${recognizerOrName}`);\n }\n } else {\n otherRecognizer = recognizerOrName;\n }\n const {requireFail} = this;\n if (requireFail.indexOf(otherRecognizer) === -1) {\n requireFail.push(otherRecognizer);\n otherRecognizer.requireFailure(this);\n }\n return this;\n }\n\n /**\n * drop the requireFailure link. it does not remove the link on the other recognizer.\n */\n dropRequireFailure(recognizerOrName: Recognizer | string | (Recognizer | string)[]) {\n if (Array.isArray(recognizerOrName)) {\n for (const item of recognizerOrName) {\n this.dropRequireFailure(item);\n }\n return this;\n }\n\n let otherRecognizer: Recognizer | null;\n if (typeof recognizerOrName === 'string') {\n otherRecognizer = this.manager.get(recognizerOrName);\n } else {\n otherRecognizer = recognizerOrName;\n }\n if (otherRecognizer) {\n const index = this.requireFail.indexOf(otherRecognizer);\n if (index > -1) {\n this.requireFail.splice(index, 1);\n }\n }\n return this;\n }\n\n /**\n * has require failures boolean\n */\n hasRequireFailures(): boolean {\n return Boolean(this.requireFail.find((recognier) => recognier.options.enable));\n }\n\n /**\n * if the recognizer can recognize simultaneous with an other recognizer\n */\n canRecognizeWith(otherRecognizer: Recognizer): boolean {\n return Boolean(this.simultaneous[otherRecognizer.id]);\n }\n\n /**\n * You should use `tryEmit` instead of `emit` directly to check\n * that all the needed recognizers has failed before emitting.\n */\n protected emit(input?: HammerInput) {\n // Some recognizers override emit() with their own logic\n if (!input) return;\n\n const {state} = this;\n\n // 'panstart' and 'panmove'\n if (state < RecognizerState.Ended) {\n this.manager.emit(this.options.event + stateStr(state), input);\n }\n\n // simple 'eventName' events\n this.manager.emit(this.options.event, input);\n\n // additional event(panleft, panright, pinchin, pinchout...)\n if (input.additionalEvent) {\n this.manager.emit(input.additionalEvent, input);\n }\n\n // panend and pancancel\n if (state >= RecognizerState.Ended) {\n this.manager.emit(this.options.event + stateStr(state), input);\n }\n }\n\n /**\n * Check that all the require failure recognizers has failed,\n * if true, it emits a gesture event,\n * otherwise, setup the state to FAILED.\n */\n protected tryEmit(input?: HammerInput) {\n if (this.canEmit()) {\n this.emit(input);\n } else {\n // it's failing anyway\n this.state = RecognizerState.Failed;\n }\n }\n\n /**\n * can we emit?\n */\n protected canEmit(): boolean {\n let i = 0;\n while (i < this.requireFail.length) {\n if (!(this.requireFail[i].state & (RecognizerState.Failed | RecognizerState.Possible))) {\n return false;\n }\n i++;\n }\n return true;\n }\n\n /**\n * update the recognizer\n */\n recognize(inputData: HammerInput) {\n // make a new copy of the inputData\n // so we can change the inputData without messing up the other recognizers\n const inputDataClone = {...inputData};\n\n // is is enabled and allow recognizing?\n if (!this.options.enable) {\n this.reset();\n this.state = RecognizerState.Failed;\n return;\n }\n\n // reset when we've reached the end\n if (\n this.state &\n (RecognizerState.Recognized | RecognizerState.Cancelled | RecognizerState.Failed)\n ) {\n this.state = RecognizerState.Possible;\n }\n\n this.state = this.process(inputDataClone);\n\n // the recognizer has recognized a gesture\n // so trigger an event\n if (\n this.state &\n (RecognizerState.Began |\n RecognizerState.Changed |\n RecognizerState.Ended |\n RecognizerState.Cancelled)\n ) {\n this.tryEmit(inputDataClone);\n }\n }\n\n /**\n * return the state of the recognizer\n * the actual recognizing happens in this method\n */\n\n abstract process(inputData: HammerInput): RecognizerState;\n\n /**\n * return the preferred touch-action\n */\n abstract getTouchAction(): string[];\n\n /**\n * return the event names that are emitted by this recognizer\n */\n getEventNames(): string[] {\n return [this.options.event];\n }\n\n /**\n * called when the gesture isn't allowed to recognize\n * like when another is being recognized or it is disabled\n */\n reset(): void {}\n}\n","import {Recognizer, RecognizerOptions} from '../recognizer/recognizer';\nimport {RecognizerState} from '../recognizer/recognizer-state';\nimport {InputEvent} from '../input/input-consts';\nimport type {HammerInput} from '../input/types';\n\ntype AttrRecognizerOptions = RecognizerOptions & {\n pointers: number;\n};\n\n/**\n * This recognizer is just used as a base for the simple attribute recognizers.\n */\nexport abstract class AttrRecognizer<\n OptionsT extends AttrRecognizerOptions\n> extends Recognizer {\n /**\n * Used to check if it the recognizer receives valid input, like input.distance > 10.\n */\n attrTest(input: HammerInput): boolean {\n const optionPointers = this.options.pointers;\n return optionPointers === 0 || input.pointers.length === optionPointers;\n }\n\n /**\n * Process the input and return the state for the recognizer\n */\n process(input: HammerInput) {\n const {state} = this;\n const {eventType} = input;\n\n const isRecognized = state & (RecognizerState.Began | RecognizerState.Changed);\n const isValid = this.attrTest(input);\n\n // on cancel input and we've recognized before, return STATE_CANCELLED\n if (isRecognized && (eventType & InputEvent.Cancel || !isValid)) {\n return state | RecognizerState.Cancelled;\n } else if (isRecognized || isValid) {\n if (eventType & InputEvent.End) {\n return state | RecognizerState.Ended;\n } else if (!(state & RecognizerState.Began)) {\n return RecognizerState.Began;\n }\n return state | RecognizerState.Changed;\n }\n return RecognizerState.Failed;\n }\n}\n","/* global setTimeout, clearTimeout */\nimport {Recognizer} from '../recognizer/recognizer';\nimport {TOUCH_ACTION_MANIPULATION} from '../touchaction/touchaction-Consts';\nimport {InputEvent} from '../input/input-consts';\nimport {RecognizerState} from '../recognizer/recognizer-state';\nimport {getPointDistance} from '../input/get-distance';\nimport type {Point, HammerInput} from '../input/types';\n\nexport type TapRecognizerOptions = {\n /** Name of the event.\n * @default 'tap'\n */\n event?: string;\n /** Enable this event.\n * @default true\n */\n enable?: boolean;\n /** Required pointers.\n * @default 1\n */\n pointers?: number;\n /** Required number of taps in succession.\n * @default 1\n */\n taps?: number;\n /** Maximum time in ms between multiple taps.\n * @default 300\n */\n interval?: number;\n /** Maximum press time in ms.\n * @default 250\n */\n time?: number;\n /** While doing a tap some small movement is allowed.\n * @default 9\n */\n threshold?: number;\n /** The maximum position difference between multiple taps.\n * @default 10\n */\n posThreshold?: number;\n};\n\n/**\n * A tap is recognized when the pointer is doing a small tap/click. Multiple taps are recognized if they occur\n * between the given interval and position. The delay option can be used to recognize multi-taps without firing\n * a single tap.\n *\n * The eventData from the emitted event contains the property `tapCount`, which contains the amount of\n * multi-taps being recognized.\n */\nexport class TapRecognizer extends Recognizer> {\n /** previous time for tap counting */\n private pTime: number | null = null;\n /** previous center for tap counting */\n private pCenter: Point | null = null;\n\n private _timer: any = null;\n private _input: HammerInput | null = null;\n\n private count: number = 0;\n\n constructor(options: TapRecognizerOptions = {}) {\n super({\n enable: true,\n event: 'tap',\n pointers: 1,\n taps: 1,\n interval: 300,\n time: 250,\n threshold: 9,\n posThreshold: 10,\n ...options\n });\n }\n\n getTouchAction() {\n return [TOUCH_ACTION_MANIPULATION];\n }\n\n process(input: HammerInput) {\n const {options} = this;\n\n const validPointers = input.pointers.length === options.pointers;\n const validMovement = input.distance < options.threshold;\n const validTouchTime = input.deltaTime < options.time;\n\n this.reset();\n\n if (input.eventType & InputEvent.Start && this.count === 0) {\n return this.failTimeout();\n }\n\n // we only allow little movement\n // and we've reached an end event, so a tap is possible\n if (validMovement && validTouchTime && validPointers) {\n if (input.eventType !== InputEvent.End) {\n return this.failTimeout();\n }\n\n const validInterval = this.pTime ? input.timeStamp - this.pTime < options.interval : true;\n const validMultiTap =\n !this.pCenter || getPointDistance(this.pCenter, input.center) < options.posThreshold;\n\n this.pTime = input.timeStamp;\n this.pCenter = input.center;\n\n if (!validMultiTap || !validInterval) {\n this.count = 1;\n } else {\n this.count += 1;\n }\n\n this._input = input;\n\n // if tap count matches we have recognized it,\n // else it has began recognizing...\n const tapCount = this.count % options.taps;\n if (tapCount === 0) {\n // no failing requirements, immediately trigger the tap event\n // or wait as long as the multitap interval to trigger\n if (!this.hasRequireFailures()) {\n return RecognizerState.Recognized;\n }\n this._timer = setTimeout(() => {\n this.state = RecognizerState.Recognized;\n this.tryEmit(this._input!);\n }, options.interval);\n return RecognizerState.Began;\n }\n }\n return RecognizerState.Failed;\n }\n\n failTimeout() {\n this._timer = setTimeout(() => {\n this.state = RecognizerState.Failed;\n }, this.options.interval);\n return RecognizerState.Failed;\n }\n\n reset() {\n clearTimeout(this._timer);\n }\n\n emit(input: HammerInput) {\n if (this.state === RecognizerState.Recognized) {\n input.tapCount = this.count;\n this.manager.emit(this.options.event, input);\n }\n }\n}\n","import {AttrRecognizer} from './attribute';\nimport {InputDirection} from '../input/input-consts';\nimport {RecognizerState} from '../recognizer/recognizer-state';\nimport {TOUCH_ACTION_PAN_X, TOUCH_ACTION_PAN_Y} from '../touchaction/touchaction-Consts';\nimport type {HammerInput} from '../input/types';\n\nexport type PanRecognizerOptions = {\n /** Name of the event.\n * @default 'pan'\n */\n event?: string;\n /** Enable this event.\n * @default true\n */\n enable?: boolean;\n /** Required number of pointers. 0 for all pointers.\n * @default 1\n */\n pointers?: number;\n /** Required direction of panning.\n * @default InputDirection.All\n */\n direction?: InputDirection;\n /** Minimal pan distance required before recognizing.\n * @default 10\n */\n threshold?: number;\n};\n\nconst EVENT_NAMES = ['', 'start', 'move', 'end', 'cancel', 'up', 'down', 'left', 'right'] as const;\n\n/**\n * Pan\n * Recognized when the pointer is down and moved in the allowed direction.\n */\nexport class PanRecognizer extends AttrRecognizer> {\n pX: number | null;\n pY: number | null;\n\n constructor(options: PanRecognizerOptions = {}) {\n super({\n enable: true,\n pointers: 1,\n event: 'pan',\n threshold: 10,\n direction: InputDirection.All,\n ...options\n });\n this.pX = null;\n this.pY = null;\n }\n\n getTouchAction(): string[] {\n const {\n options: {direction}\n } = this;\n const actions: string[] = [];\n if (direction & InputDirection.Horizontal) {\n actions.push(TOUCH_ACTION_PAN_Y);\n }\n if (direction & InputDirection.Vertical) {\n actions.push(TOUCH_ACTION_PAN_X);\n }\n return actions;\n }\n\n getEventNames(): string[] {\n return EVENT_NAMES.map((suffix) => this.options.event + suffix);\n }\n\n directionTest(input: HammerInput): boolean {\n const {options} = this;\n let hasMoved = true;\n let {distance} = input;\n let {direction} = input;\n const x = input.deltaX;\n const y = input.deltaY;\n\n // lock to axis?\n if (!(direction & options.direction)) {\n if (options.direction & InputDirection.Horizontal) {\n direction =\n x === 0 ? InputDirection.None : x < 0 ? InputDirection.Left : InputDirection.Right;\n hasMoved = x !== this.pX;\n distance = Math.abs(input.deltaX);\n } else {\n direction = y === 0 ? InputDirection.None : y < 0 ? InputDirection.Up : InputDirection.Down;\n hasMoved = y !== this.pY;\n distance = Math.abs(input.deltaY);\n }\n }\n input.direction = direction;\n return hasMoved && distance > options.threshold && Boolean(direction & options.direction);\n }\n\n attrTest(input: HammerInput): boolean {\n return (\n super.attrTest(input) &&\n (Boolean(this.state & RecognizerState.Began) ||\n (!(this.state & RecognizerState.Began) && this.directionTest(input)))\n );\n }\n\n emit(input: HammerInput) {\n this.pX = input.deltaX;\n this.pY = input.deltaY;\n\n const direction = InputDirection[input.direction].toLowerCase();\n\n if (direction) {\n input.additionalEvent = this.options.event + direction;\n }\n super.emit(input);\n }\n}\n","import {AttrRecognizer} from './attribute';\nimport {TOUCH_ACTION_NONE} from '../touchaction/touchaction-Consts';\nimport {RecognizerState} from '../recognizer/recognizer-state';\nimport type {HammerInput} from '../input/types';\n\nexport type PinchRecognizerOptions = {\n /** Name of the event.\n * @default 'pinch'\n */\n event?: string;\n /** Enable this event.\n * @default true\n */\n enable?: boolean;\n /** Required number of pointers, with a minimum of 2.\n * @default 2\n */\n pointers?: number;\n /** Minimal scale before recognizing.\n * @default 0\n */\n threshold?: number;\n};\n\nconst EVENT_NAMES = ['', 'start', 'move', 'end', 'cancel', 'in', 'out'] as const;\n\n/**\n * Pinch\n * Recognized when two or more pointers are moving toward (zoom-in) or away from each other (zoom-out).\n */\nexport class PinchRecognizer extends AttrRecognizer> {\n constructor(options: PinchRecognizerOptions = {}) {\n super({\n enable: true,\n event: 'pinch',\n threshold: 0,\n pointers: 2,\n ...options\n });\n }\n\n getTouchAction() {\n return [TOUCH_ACTION_NONE];\n }\n\n getEventNames(): string[] {\n return EVENT_NAMES.map((suffix) => this.options.event + suffix);\n }\n\n attrTest(input: HammerInput): boolean {\n return (\n super.attrTest(input) &&\n (Math.abs(input.scale - 1) > this.options.threshold ||\n Boolean(this.state & RecognizerState.Began))\n );\n }\n\n emit(input: HammerInput) {\n if (input.scale !== 1) {\n const inOut = input.scale < 1 ? 'in' : 'out';\n input.additionalEvent = this.options.event + inOut;\n }\n super.emit(input);\n }\n}\n","// mjolnir.js\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {MjolnirEventRaw} from '../types';\n\nexport interface InputOptions {\n enable?: boolean;\n}\n\nexport class Input {\n element: HTMLElement;\n options: Options;\n callback: (e: EventType) => void;\n\n constructor(element: HTMLElement, callback: (e: EventType) => void, options: Options) {\n this.element = element;\n this.callback = callback;\n this.options = options;\n }\n}\n","// mjolnir.js\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// Purpose: include this in your module to avoids adding dependencies on\n// micro modules like 'global'\n\n/* global window, global, document, navigator */\nexport const userAgent =\n typeof navigator !== 'undefined' && navigator.userAgent ? navigator.userAgent.toLowerCase() : '';\n\nconst window_ = typeof window !== 'undefined' ? window : global;\nconst global_ = typeof global !== 'undefined' ? global : window;\nconst document_ = typeof document !== 'undefined' ? document : {};\n\nexport {window_ as window, global_ as global, document_ as document};\n","// mjolnir.js\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {MjolnirWheelEventRaw} from '../types';\nimport {Input, InputOptions} from './input';\n\nimport {userAgent} from '../utils/globals';\n\nconst firefox = userAgent.indexOf('firefox') !== -1;\n\n// Constants for normalizing input delta\nconst WHEEL_DELTA_MAGIC_SCALER = 4.000244140625;\nconst WHEEL_DELTA_PER_LINE = 40;\n// Slow down zoom if shift key is held for more precise zooming\nconst SHIFT_MULTIPLIER = 0.25;\n\nexport class WheelInput extends Input> {\n constructor(\n element: HTMLElement,\n callback: (event: MjolnirWheelEventRaw) => void,\n options: InputOptions\n ) {\n super(element, callback, {enable: true, ...options});\n\n element.addEventListener('wheel', this.handleEvent, {passive: false});\n }\n\n destroy() {\n this.element.removeEventListener('wheel', this.handleEvent);\n }\n\n /**\n * Enable this input (begin processing events)\n * if the specified event type is among those handled by this input.\n */\n enableEventType(eventType: string, enabled: boolean) {\n if (eventType === 'wheel') {\n this.options.enable = enabled;\n }\n }\n\n /* eslint-disable complexity, max-statements */\n handleEvent = (event: WheelEvent) => {\n if (!this.options.enable) {\n return;\n }\n\n let value = event.deltaY;\n if (globalThis.WheelEvent) {\n // Firefox doubles the values on retina screens...\n if (firefox && event.deltaMode === globalThis.WheelEvent.DOM_DELTA_PIXEL) {\n value /= globalThis.devicePixelRatio;\n }\n if (event.deltaMode === globalThis.WheelEvent.DOM_DELTA_LINE) {\n value *= WHEEL_DELTA_PER_LINE;\n }\n }\n\n if (value !== 0 && value % WHEEL_DELTA_MAGIC_SCALER === 0) {\n // This one is definitely a mouse wheel event.\n // Normalize this value to match trackpad.\n value = Math.floor(value / WHEEL_DELTA_MAGIC_SCALER);\n }\n\n if (event.shiftKey && value) {\n value = value * SHIFT_MULTIPLIER;\n }\n\n this.callback({\n type: 'wheel',\n center: {\n x: event.clientX,\n y: event.clientY\n },\n delta: -value,\n srcEvent: event,\n pointerType: 'mouse',\n target: event.target as HTMLElement\n });\n };\n}\n","// mjolnir.js\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {MjolnirPointerEventRaw} from '../types';\nimport {Input, InputOptions} from './input';\n\nconst MOUSE_EVENTS = [\n 'mousedown',\n 'mousemove',\n 'mouseup',\n 'mouseover',\n 'mouseout',\n 'mouseleave'\n] as const;\n\ntype MoveEventType = 'pointermove' | 'pointerover' | 'pointerout' | 'pointerenter' | 'pointerleave';\n\n/**\n * Hammer.js swallows 'move' events (for pointer/touch/mouse)\n * when the pointer is not down. This class sets up a handler\n * specifically for these events to work around this limitation.\n * Note that this could be extended to more intelligently handle\n * move events across input types, e.g. storing multiple simultaneous\n * pointer/touch events, calculating speed/direction, etc.\n */\nexport class MoveInput extends Input> {\n pressed: boolean;\n enableMoveEvent: boolean;\n enableEnterEvent: boolean;\n enableLeaveEvent: boolean;\n enableOutEvent: boolean;\n enableOverEvent: boolean;\n\n constructor(\n element: HTMLElement,\n callback: (event: MjolnirPointerEventRaw) => void,\n options: InputOptions\n ) {\n super(element, callback, {enable: true, ...options});\n\n this.pressed = false;\n const {enable} = this.options;\n\n this.enableMoveEvent = enable;\n this.enableLeaveEvent = enable;\n this.enableEnterEvent = enable;\n this.enableOutEvent = enable;\n this.enableOverEvent = enable;\n\n MOUSE_EVENTS.forEach((event) => element.addEventListener(event, this.handleEvent));\n }\n\n destroy() {\n MOUSE_EVENTS.forEach((event) => this.element.removeEventListener(event, this.handleEvent));\n }\n\n /**\n * Enable this input (begin processing events)\n * if the specified event type is among those handled by this input.\n */\n enableEventType(eventType: string, enabled: boolean) {\n switch (eventType) {\n case 'pointermove':\n this.enableMoveEvent = enabled;\n break;\n case 'pointerover':\n this.enableOverEvent = enabled;\n break;\n case 'pointerout':\n this.enableOutEvent = enabled;\n break;\n case 'pointerenter':\n this.enableEnterEvent = enabled;\n break;\n case 'pointerleave':\n this.enableLeaveEvent = enabled;\n break;\n default:\n // ignore\n }\n }\n\n handleEvent = (event: MouseEvent) => {\n this.handleOverEvent(event);\n this.handleOutEvent(event);\n this.handleEnterEvent(event);\n this.handleLeaveEvent(event);\n this.handleMoveEvent(event);\n };\n\n handleOverEvent(event: MouseEvent) {\n if (this.enableOverEvent && event.type === 'mouseover') {\n this._emit('pointerover', event);\n }\n }\n\n handleOutEvent(event: MouseEvent) {\n if (this.enableOutEvent && event.type === 'mouseout') {\n this._emit('pointerout', event);\n }\n }\n\n handleEnterEvent(event: MouseEvent) {\n if (this.enableEnterEvent && event.type === 'mouseenter') {\n this._emit('pointerenter', event);\n }\n }\n\n handleLeaveEvent(event: MouseEvent) {\n if (this.enableLeaveEvent && event.type === 'mouseleave') {\n this._emit('pointerleave', event);\n }\n }\n\n handleMoveEvent(event: MouseEvent) {\n if (this.enableMoveEvent) {\n switch (event.type) {\n case 'mousedown':\n if (event.button >= 0) {\n // Button is down\n this.pressed = true;\n }\n break;\n case 'mousemove':\n // Move events use `bottons` to track the button being pressed\n if (event.buttons === 0) {\n // Button is not down\n this.pressed = false;\n }\n if (!this.pressed) {\n // Drag events are emitted by hammer already\n // we just need to emit the move event on hover\n this._emit('pointermove', event);\n }\n break;\n case 'mouseup':\n this.pressed = false;\n break;\n default:\n }\n }\n }\n\n _emit(type: MoveEventType, event: MouseEvent) {\n this.callback({\n type,\n center: {\n x: event.clientX,\n y: event.clientY\n },\n srcEvent: event,\n pointerType: 'mouse',\n target: event.target as HTMLElement\n });\n }\n}\n","// mjolnir.js\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {MjolnirKeyEventRaw} from '../types';\nimport {Input, InputOptions} from './input';\n\nconst KEY_EVENTS = ['keydown', 'keyup'] as const;\n\ntype KeyInputOptions = InputOptions & {\n tabIndex?: number;\n};\n\nexport class KeyInput extends Input> {\n enableDownEvent: boolean;\n enableUpEvent: boolean;\n\n constructor(\n element: HTMLElement,\n callback: (event: MjolnirKeyEventRaw) => void,\n options: KeyInputOptions\n ) {\n super(element, callback, {enable: true, tabIndex: 0, ...options});\n\n this.enableDownEvent = this.options.enable;\n this.enableUpEvent = this.options.enable;\n\n element.tabIndex = this.options.tabIndex;\n element.style.outline = 'none';\n KEY_EVENTS.forEach((event) => element.addEventListener(event, this.handleEvent));\n }\n\n destroy() {\n KEY_EVENTS.forEach((event) => this.element.removeEventListener(event, this.handleEvent));\n }\n\n /**\n * Enable this input (begin processing events)\n * if the specified event type is among those handled by this input.\n */\n enableEventType(eventType: string, enabled: boolean) {\n if (eventType === 'keydown') {\n this.enableDownEvent = enabled;\n }\n if (eventType === 'keyup') {\n this.enableUpEvent = enabled;\n }\n }\n\n handleEvent = (event: KeyboardEvent) => {\n // Ignore if focused on text input\n const targetElement = (event.target || event.srcElement) as HTMLElement;\n if (\n (targetElement.tagName === 'INPUT' && (targetElement as HTMLInputElement).type === 'text') ||\n targetElement.tagName === 'TEXTAREA'\n ) {\n return;\n }\n\n if (this.enableDownEvent && event.type === 'keydown') {\n this.callback({\n type: 'keydown',\n srcEvent: event,\n key: event.key,\n target: event.target as HTMLElement\n });\n }\n\n if (this.enableUpEvent && event.type === 'keyup') {\n this.callback({\n type: 'keyup',\n srcEvent: event,\n key: event.key,\n target: event.target as HTMLElement\n });\n }\n };\n}\n","// mjolnir.js\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {MjolnirPointerEventRaw} from '../types';\nimport {Input, InputOptions} from './input';\n\nexport class ContextmenuInput extends Input {\n constructor(\n element: HTMLElement,\n callback: (event: MjolnirPointerEventRaw) => void,\n options: InputOptions\n ) {\n super(element, callback, options);\n\n element.addEventListener('contextmenu', this.handleEvent);\n }\n\n destroy() {\n this.element.removeEventListener('contextmenu', this.handleEvent);\n }\n\n /**\n * Enable this input (begin processing events)\n * if the specified event type is among those handled by this input.\n */\n enableEventType(eventType: string, enabled: boolean) {\n if (eventType === 'contextmenu') {\n this.options.enable = enabled;\n }\n }\n\n handleEvent = (event: MouseEvent) => {\n if (!this.options.enable) {\n return;\n }\n\n this.callback({\n type: 'contextmenu',\n center: {\n x: event.clientX,\n y: event.clientY\n },\n srcEvent: event,\n pointerType: 'mouse',\n target: event.target as HTMLElement\n });\n };\n}\n","// mjolnir.js\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {MjolnirEventRaw, Point} from '../types';\nimport type {HammerEvent} from '../hammerjs/index';\n\n/* Constants */\nconst DOWN_EVENT = 1;\nconst MOVE_EVENT = 2;\nconst UP_EVENT = 4;\nconst MOUSE_EVENTS = {\n pointerdown: DOWN_EVENT,\n pointermove: MOVE_EVENT,\n pointerup: UP_EVENT,\n mousedown: DOWN_EVENT,\n mousemove: MOVE_EVENT,\n mouseup: UP_EVENT\n};\n\n// MouseEvent.button https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button\nconst MOUSE_EVENT_BUTTON_LEFT = 0;\nconst MOUSE_EVENT_BUTTON_MIDDLE = 1;\nconst MOUSE_EVENT_BUTTON_RIGHT = 2;\n// MouseEvent.buttons https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons\nconst MOUSE_EVENT_BUTTONS_LEFT_MASK = 1;\nconst MOUSE_EVENT_BUTTONS_RIGHT_MASK = 2;\nconst MOUSE_EVENT_BUTTONS_MIDDLE_MASK = 4;\n\n/**\n * Extract the involved mouse button\n */\nexport function whichButtons(event: MjolnirEventRaw): {\n leftButton: boolean;\n middleButton: boolean;\n rightButton: boolean;\n} | null {\n const eventType = MOUSE_EVENTS[event.srcEvent.type];\n if (!eventType) {\n // Not a mouse evet\n return null;\n }\n\n const {buttons, button} = event.srcEvent as PointerEvent;\n let leftButton = false;\n let middleButton = false;\n let rightButton = false;\n\n if (eventType === MOVE_EVENT) {\n leftButton = Boolean(buttons & MOUSE_EVENT_BUTTONS_LEFT_MASK);\n middleButton = Boolean(buttons & MOUSE_EVENT_BUTTONS_MIDDLE_MASK);\n rightButton = Boolean(buttons & MOUSE_EVENT_BUTTONS_RIGHT_MASK);\n } else {\n leftButton = button === MOUSE_EVENT_BUTTON_LEFT;\n middleButton = button === MOUSE_EVENT_BUTTON_MIDDLE;\n rightButton = button === MOUSE_EVENT_BUTTON_RIGHT;\n }\n\n return {leftButton, middleButton, rightButton};\n}\n\n/**\n * Calculate event position relative to the root element\n */\nexport function getOffsetPosition(\n event: MjolnirEventRaw,\n rootElement: HTMLElement\n): {\n center: Point;\n offsetCenter: Point;\n} | null {\n const center = (event as HammerEvent).center;\n\n // `center` is a hammer.js event property\n if (!center) {\n // Not a gestural event\n return null;\n }\n\n const rect = rootElement.getBoundingClientRect();\n\n // Fix scale for map affected by a CSS transform.\n // See https://stackoverflow.com/a/26893663/3528533\n const scaleX = rect.width / rootElement.offsetWidth || 1;\n const scaleY = rect.height / rootElement.offsetHeight || 1;\n\n // Calculate center relative to the root element\n const offsetCenter = {\n x: (center.x - rect.left - rootElement.clientLeft) / scaleX,\n y: (center.y - rect.top - rootElement.clientTop) / scaleY\n };\n\n return {center, offsetCenter};\n}\n","// mjolnir.js\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {EventManager} from '../event-manager';\nimport {whichButtons, getOffsetPosition} from './event-utils';\nimport type {\n MjolnirEventRaw,\n MjolnirEventWrapper,\n MjolnirEvent,\n MjolnirEventHandler\n} from '../types';\n\nexport type HandlerOptions = {\n /** Optional element from which the event is originated from.\n * @default 'root'\n */\n srcElement?: 'root' | HTMLElement;\n /** Handler with higher priority will be called first.\n * Handler with the same priority will be called in the order of registration.\n * @default 0\n */\n priority?: number;\n};\n\ntype EventHandler = {\n type: string;\n handler: (event: MjolnirEvent) => void;\n once?: boolean;\n passive?: boolean;\n srcElement: 'root' | HTMLElement;\n priority: number;\n};\n\nconst DEFAULT_OPTIONS: Required = {\n srcElement: 'root',\n priority: 0\n};\n\nexport class EventRegistrar {\n eventManager: EventManager;\n recognizerName: string;\n handlers: EventHandler[];\n handlersByElement: Map<'root' | HTMLElement, EventHandler[]>;\n _active: boolean;\n\n constructor(eventManager: EventManager, recognizerName: string) {\n this.eventManager = eventManager;\n this.recognizerName = recognizerName;\n this.handlers = [];\n // Element -> handler map\n this.handlersByElement = new Map();\n\n this._active = false;\n }\n\n // Returns true if there are no non-passive handlers\n isEmpty(): boolean {\n return !this._active;\n }\n\n add(\n type: string,\n handler: MjolnirEventHandler,\n options?: HandlerOptions,\n once: boolean = false,\n passive: boolean = false\n ) {\n const {handlers, handlersByElement} = this;\n const opts: Required = {...DEFAULT_OPTIONS, ...options};\n\n let entries = handlersByElement.get(opts.srcElement);\n if (!entries) {\n entries = [];\n handlersByElement.set(opts.srcElement, entries);\n }\n const entry: EventHandler = {\n type,\n handler,\n srcElement: opts.srcElement,\n priority: opts.priority\n };\n if (once) {\n entry.once = true;\n }\n if (passive) {\n entry.passive = true;\n }\n handlers.push(entry);\n this._active = this._active || !entry.passive;\n\n // Sort handlers by descending priority\n // Handlers with the same priority are excuted in the order of registration\n let insertPosition = entries.length - 1;\n while (insertPosition >= 0) {\n if (entries[insertPosition].priority >= entry.priority) {\n break;\n }\n insertPosition--;\n }\n entries.splice(insertPosition + 1, 0, entry);\n }\n\n remove(type: string, handler: MjolnirEventHandler) {\n const {handlers, handlersByElement} = this;\n\n for (let i = handlers.length - 1; i >= 0; i--) {\n const entry = handlers[i];\n\n if (entry.type === type && entry.handler === handler) {\n handlers.splice(i, 1);\n const entries = handlersByElement.get(entry.srcElement)!;\n entries.splice(entries.indexOf(entry), 1);\n if (entries.length === 0) {\n handlersByElement.delete(entry.srcElement);\n }\n }\n }\n this._active = handlers.some((entry) => !entry.passive);\n }\n\n /**\n * Handles hammerjs event\n */\n handleEvent = (event: MjolnirEventRaw) => {\n if (this.isEmpty()) {\n return;\n }\n\n const mjolnirEvent = this._normalizeEvent(event);\n let target = event.srcEvent.target as HTMLElement;\n\n while (target && target !== mjolnirEvent.rootElement) {\n this._emit(mjolnirEvent, target);\n if (mjolnirEvent.handled) {\n return;\n }\n target = target.parentNode as HTMLElement;\n }\n this._emit(mjolnirEvent, 'root');\n };\n\n /**\n * Invoke handlers on a particular element\n */\n _emit(\n event: MjolnirEventWrapper,\n srcElement: 'root' | HTMLElement\n ) {\n const entries = this.handlersByElement.get(srcElement);\n\n if (entries) {\n let immediatePropagationStopped = false;\n\n // Prevents the current event from bubbling up\n const stopPropagation = () => {\n event.handled = true;\n };\n // Prevent any remaining listeners from being called\n const stopImmediatePropagation = () => {\n event.handled = true;\n immediatePropagationStopped = true;\n };\n const entriesToRemove: EventHandler[] = [];\n\n for (let i = 0; i < entries.length; i++) {\n const {type, handler, once} = entries[i];\n // @ts-ignore\n handler({\n ...event,\n type,\n stopPropagation,\n stopImmediatePropagation\n });\n if (once) {\n entriesToRemove.push(entries[i]);\n }\n if (immediatePropagationStopped) {\n break;\n }\n }\n\n for (let i = 0; i < entriesToRemove.length; i++) {\n const {type, handler} = entriesToRemove[i];\n this.remove(type, handler);\n }\n }\n }\n\n /**\n * Normalizes hammerjs and custom events to have predictable fields.\n */\n _normalizeEvent(event: T): MjolnirEventWrapper {\n const rootElement = this.eventManager.getElement();\n\n // @ts-ignore\n return {\n ...event,\n ...whichButtons(event),\n ...getOffsetPosition(event, rootElement!),\n preventDefault: () => {\n event.srcEvent.preventDefault();\n },\n stopImmediatePropagation: null,\n stopPropagation: null,\n handled: false,\n rootElement\n };\n }\n}\n","// mjolnir.js\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Manager as HammerManager, Recognizer} from './hammerjs/index';\nimport type {\n MjolnirEventRaw,\n MjolnirEvent,\n MjolnirEventHandler,\n MjolnirEventHandlers\n} from './types';\n\nimport {WheelInput} from './inputs/wheel-input';\nimport {MoveInput} from './inputs/move-input';\nimport {KeyInput} from './inputs/key-input';\nimport {ContextmenuInput} from './inputs/contextmenu-input';\n\nimport {EventRegistrar, HandlerOptions} from './utils/event-registrar';\n\ntype RecognizerConstructor = {new (options: any): Recognizer};\n\ntype RecognizerTupleNormalized = {\n recognizer: Recognizer;\n /** Allow another gesture to be recognized simultaneously with this one.\n * For example an interaction can trigger pinch and rotate at the same time. */\n recognizeWith?: string[];\n /** Another recognizer is mutually exclusive with this one.\n * For example an interaction could be singletap or doubletap; pan-horizontal or pan-vertical; but never both. */\n requireFailure?: string[];\n};\n\nexport type RecognizerTuple =\n | Recognizer\n | RecognizerConstructor\n | RecognizerTupleNormalized\n /** hammer.js/mjolnir.js@2 style */\n | [\n recognizer: RecognizerConstructor,\n options?: any,\n /** Allow another gesture to be recognized simultaneously with this one.\n * For example an interaction can trigger pinch and rotate at the same time. */\n recognizeWith?: string | string[],\n /** Another recognizer is mutually exclusive with this one.\n * For example an interaction could be singletap or doubletap; pan-horizontal or pan-vertical; but never both. */\n requireFailure?: string | string[]\n ];\n\nexport type EventManagerOptions = {\n /** Event listeners */\n events?: MjolnirEventHandlers;\n /** Gesture recognizers */\n recognizers?: RecognizerTuple[];\n /** Touch action to set on the target element.\n * Use 'compute' to automatically set as the least restrictive value to support the recognizers.\n * https://developer.mozilla.org/en-US/docs/Web/CSS/touch-action\n * @default 'compute'\n */\n touchAction?: 'none' | 'compute' | 'manipulation' | 'pan-x' | 'pan-y' | 'pan-x pan-y';\n /** Tab index of the target element */\n tabIndex?: number;\n /**\n * Optional CSS properties to be applied to the target element.\n */\n cssProps?: Partial;\n};\n\nfunction normalizeRecognizer(item: RecognizerTuple): RecognizerTupleNormalized {\n if ('recognizer' in item) {\n return item;\n }\n let recognizer: Recognizer;\n const itemArray = Array.isArray(item) ? [...item] : [item];\n if (typeof itemArray[0] === 'function') {\n // Backward compatibility: v2 / hammerjs style\n const RecognizerType = itemArray.shift();\n const options = itemArray.shift() || {};\n recognizer = new RecognizerType(options);\n } else {\n recognizer = itemArray.shift();\n }\n return {\n recognizer,\n recognizeWith: typeof itemArray[0] === 'string' ? [itemArray[0]] : itemArray[0],\n requireFailure: typeof itemArray[1] === 'string' ? [itemArray[1]] : itemArray[1]\n };\n}\n\n// Unified API for subscribing to events about both\n// basic input events (e.g. 'mousemove', 'touchstart', 'wheel')\n// and gestural input (e.g. 'click', 'tap', 'panstart').\n// Delegates gesture related event registration and handling to Hammer.js.\nexport class EventManager {\n private element: HTMLElement | null;\n private manager: HammerManager;\n private options: Required;\n private events: Map;\n\n // Custom handlers\n private wheelInput: WheelInput;\n private moveInput: MoveInput;\n private contextmenuInput: ContextmenuInput;\n private keyInput: KeyInput;\n\n constructor(element: HTMLElement | null = null, options: EventManagerOptions = {}) {\n this.options = {\n recognizers: [],\n events: {},\n touchAction: 'compute',\n tabIndex: 0,\n cssProps: {},\n ...options\n };\n this.events = new Map();\n this.element = element;\n\n if (!element) return;\n\n this.manager = new HammerManager(element, this.options);\n for (const item of this.options.recognizers) {\n const {recognizer, recognizeWith, requireFailure} = normalizeRecognizer(item);\n this.manager.add(recognizer);\n if (recognizeWith) {\n recognizer.recognizeWith(recognizeWith);\n }\n if (requireFailure) {\n recognizer.requireFailure(requireFailure);\n }\n }\n\n this.manager.on('hammer.input', this._onBasicInput);\n\n // Handle events not handled by Hammer.js:\n // - mouse wheel\n // - pointer/touch/mouse move\n this.wheelInput = new WheelInput(element, this._onOtherEvent, {\n enable: false\n });\n this.moveInput = new MoveInput(element, this._onOtherEvent, {\n enable: false\n });\n this.keyInput = new KeyInput(element, this._onOtherEvent, {\n enable: false,\n tabIndex: options.tabIndex\n });\n this.contextmenuInput = new ContextmenuInput(element, this._onOtherEvent, {\n enable: false\n });\n\n // Register all passed events.\n this.on(this.options.events);\n }\n\n getElement(): HTMLElement | null {\n return this.element;\n }\n\n // Tear down internal event management implementations.\n destroy(): void {\n // manager etc. cannot exist if there is no element\n if (!this.element) return;\n\n this.wheelInput.destroy();\n this.moveInput.destroy();\n this.keyInput.destroy();\n this.contextmenuInput.destroy();\n this.manager.destroy();\n }\n\n /** Register multiple event handlers */\n on(events: MjolnirEventHandlers, opts?: HandlerOptions): void;\n on(\n event: EventT['type'],\n handler: (ev: EventT) => void,\n opts?: HandlerOptions\n ): void;\n\n /** Register an event handler function to be called on `event` */\n on(event: any, handler: any, opts?: any) {\n this._addEventHandler(event, handler, opts, false);\n }\n\n /** Register an event handler function to be called on `event`, then remove it */\n once(events: MjolnirEventHandlers, opts?: HandlerOptions): void;\n once(\n event: EventT['type'],\n handler: (ev: EventT) => void,\n opts?: HandlerOptions\n ): void;\n\n once(event: any, handler: any, opts?: any) {\n this._addEventHandler(event, handler, opts, true);\n }\n\n /** Register an event handler function to be called on `event`\n * This handler does not ask the event to be recognized at all times.\n * Instead, it only \"intercepts\" the event if some other handler is getting it.\n */\n watch(events: MjolnirEventHandlers, opts?: HandlerOptions): void;\n watch(\n event: EventT['type'],\n handler: (ev: EventT) => void,\n opts?: HandlerOptions\n ): void;\n\n watch(event: any, handler: any, opts?: any) {\n this._addEventHandler(event, handler, opts, false, true);\n }\n\n /**\n * Deregister a previously-registered event handler.\n */\n off(events: MjolnirEventHandlers): void;\n off(event: EventT['type'], handler: (ev: EventT) => void): void;\n\n off(event: any, handler?: any) {\n this._removeEventHandler(event, handler);\n }\n\n /*\n * Enable/disable recognizer for the given event\n */\n private _toggleRecognizer(name: string, enabled: boolean): void {\n const {manager} = this;\n if (!manager) {\n return;\n }\n const recognizer = manager.get(name);\n if (recognizer) {\n recognizer.set({enable: enabled});\n manager.touchAction.update();\n }\n this.wheelInput?.enableEventType(name, enabled);\n this.moveInput?.enableEventType(name, enabled);\n this.keyInput?.enableEventType(name, enabled);\n this.contextmenuInput?.enableEventType(name, enabled);\n }\n\n /**\n * Process the event registration for a single event + handler.\n */\n private _addEventHandler(\n event: string | MjolnirEventHandlers,\n handler: MjolnirEventHandler,\n opts?: HandlerOptions,\n once?: boolean,\n passive?: boolean\n ) {\n if (typeof event !== 'string') {\n // @ts-ignore\n opts = handler;\n // If `event` is a map, call `on()` for each entry.\n for (const [eventName, eventHandler] of Object.entries(event)) {\n this._addEventHandler(eventName, eventHandler, opts, once, passive);\n }\n return;\n }\n\n const {manager, events} = this;\n if (!manager) return;\n\n let eventRegistrar = events.get(event);\n if (!eventRegistrar) {\n // Enable recognizer for this event.\n const recognizerName = this._getRecognizerName(event) || event;\n\n eventRegistrar = new EventRegistrar(this, recognizerName);\n events.set(event, eventRegistrar);\n // Listen to the event\n if (manager) {\n manager.on(event, eventRegistrar.handleEvent);\n }\n }\n eventRegistrar.add(event, handler, opts, once, passive);\n if (!eventRegistrar.isEmpty()) {\n this._toggleRecognizer(eventRegistrar.recognizerName, true);\n }\n }\n\n /**\n * Process the event deregistration for a single event + handler.\n */\n private _removeEventHandler(event: string | MjolnirEventHandlers, handler?: MjolnirEventHandler) {\n if (typeof event !== 'string') {\n // If `event` is a map, call `off()` for each entry.\n for (const [eventName, eventHandler] of Object.entries(event)) {\n this._removeEventHandler(eventName, eventHandler);\n }\n return;\n }\n\n const {events} = this;\n\n const eventRegistrar = events.get(event);\n\n if (!eventRegistrar) {\n return;\n }\n\n eventRegistrar.remove(event, handler!);\n\n if (eventRegistrar.isEmpty()) {\n const {recognizerName} = eventRegistrar;\n // Disable recognizer if no more handlers are attached to its events\n let isRecognizerUsed = false;\n for (const eh of events.values()) {\n if (eh.recognizerName === recognizerName && !eh.isEmpty()) {\n isRecognizerUsed = true;\n break;\n }\n }\n if (!isRecognizerUsed) {\n this._toggleRecognizer(recognizerName, false);\n }\n }\n }\n\n private _getRecognizerName(event: string): string | undefined {\n return this.manager.recognizers.find((recognizer) => {\n return recognizer.getEventNames().includes(event);\n })?.options.event;\n }\n\n /**\n * Handle basic events using the 'hammer.input' Hammer.js API:\n * Before running Recognizers, Hammer emits a 'hammer.input' event\n * with the basic event info. This function emits all basic events\n * aliased to the \"class\" of event received.\n * See constants.BASIC_EVENT_CLASSES basic event class definitions.\n */\n private _onBasicInput = (event: MjolnirEventRaw) => {\n this.manager.emit(event.srcEvent.type, event as any);\n };\n\n /**\n * Handle events not supported by Hammer.js,\n * and pipe back out through same (Hammer) channel used by other events.\n */\n private _onOtherEvent = (event: MjolnirEventRaw) => {\n // console.log('onotherevent', event.type, event)\n this.manager.emit(event.type, event as any);\n };\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport log from '../utils/log';\nimport {Pan, InputDirection, Pinch, Tap} from 'mjolnir.js';\nimport type {PanRecognizerOptions, PinchRecognizerOptions, TapRecognizerOptions} from 'mjolnir.js';\n\n/**\n * The coordinate system that positions/dimensions are defined in.\n */\nexport type CoordinateSystem =\n | 'default'\n | 'lnglat'\n | 'meter-offsets'\n | 'lnglat-offsets'\n | 'cartesian';\n\n/**\n * The coordinate system that positions/dimensions are defined in.\n * String constants are the public API.\n * @deprecated Use string constants directly.\n */\nexport const COORDINATE_SYSTEM = {\n /**\n * `LNGLAT` if rendering into a geospatial viewport, `CARTESIAN` otherwise\n */\n DEFAULT: 'default',\n /**\n * Positions are interpreted as [longitude, latitude, elevation]\n * longitude/latitude are in degrees, elevation is in meters.\n * Dimensions are in meters.\n */\n LNGLAT: 'lnglat',\n\n /**\n * Positions are interpreted as [x, y, z] in meter offsets from the coordinate origin.\n * Dimensions are in meters.\n */\n METER_OFFSETS: 'meter-offsets',\n\n /**\n * Positions are interpreted as [deltaLng, deltaLat, elevation] from the coordinate origin.\n * deltaLng/deltaLat are in degrees, elevation is in meters.\n * Dimensions are in meters.\n */\n LNGLAT_OFFSETS: 'lnglat-offsets',\n\n /**\n * Positions and dimensions are in the common units of the viewport.\n */\n CARTESIAN: 'cartesian'\n} as const;\n\n// Deprecated\n/* eslint-disable accessor-pairs */\nObject.defineProperty(COORDINATE_SYSTEM, 'IDENTITY', {\n get: () => {\n log.deprecated('COORDINATE_SYSTEM.IDENTITY', 'COORDINATE_SYSTEM.CARTESIAN')();\n return COORDINATE_SYSTEM.CARTESIAN;\n }\n});\n/* eslint-enable accessor-pairs */\n\n/**\n * How coordinates are transformed from the world space into the common space.\n */\nexport const PROJECTION_MODE = {\n /**\n * Render geospatial data in Web Mercator projection\n */\n WEB_MERCATOR: 1,\n /**\n * Render geospatial data as a 3D globe\n */\n GLOBE: 2,\n\n /**\n * (Internal use only) Web Mercator projection at high zoom\n */\n WEB_MERCATOR_AUTO_OFFSET: 4,\n\n /**\n * No transformation\n */\n IDENTITY: 0\n} as const;\n\nexport const UNIT = {\n common: 0,\n meters: 1,\n pixels: 2\n} as const;\n\nexport const EVENT_HANDLERS = {\n click: 'onClick',\n dblclick: 'onClick',\n panstart: 'onDragStart',\n panmove: 'onDrag',\n panend: 'onDragEnd'\n} as const satisfies {[eventName: string]: string};\n\nexport const RECOGNIZERS = {\n multipan: [Pan, {threshold: 10, direction: InputDirection.Vertical, pointers: 2}],\n pinch: [Pinch, {}, null, ['multipan']],\n pan: [Pan, {threshold: 1}, ['pinch'], ['multipan']],\n dblclick: [Tap, {event: 'dblclick', taps: 2}],\n click: [Tap, {event: 'click'}, null, ['dblclick']]\n} as const;\n\nexport type RecognizerOptions = {\n pinch?: Omit;\n multipan?: Omit;\n pan?: Omit;\n dblclick?: Omit;\n click?: Omit;\n};\n\n/**\n * @deprecated Use string constants directly\n */\nexport const OPERATION = {\n DRAW: 'draw',\n MASK: 'mask',\n TERRAIN: 'terrain'\n} as const;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nfunction isEqual(a, b) {\n if (a === b) {\n return true;\n }\n if (Array.isArray(a)) {\n // Special treatment for arrays: compare 1-level deep\n // This is to support equality of matrix/coordinate props\n const len = a.length;\n if (!b || b.length !== len) {\n return false;\n }\n\n for (let i = 0; i < len; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n }\n return false;\n}\n\n/**\n * Speed up consecutive function calls by caching the result of calls with identical input\n * https://en.wikipedia.org/wiki/Memoization\n * @param {function} compute - the function to be memoized\n */\nexport default function memoize(compute: (args: In) => Out): (args: In) => Out {\n let cachedArgs: any = {};\n let cachedResult: Out;\n\n return (args: In) => {\n for (const key in args) {\n if (!isEqual(args[key], cachedArgs[key])) {\n cachedResult = compute(args);\n cachedArgs = args;\n break;\n }\n }\n return cachedResult;\n };\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/* eslint-disable complexity, camelcase */\n\nimport {mat4, Matrix4Like, vec4} from '@math.gl/core';\n\nimport {PROJECTION_MODE} from '../../lib/constants';\n\nimport memoize from '../../utils/memoize';\n\nimport type Viewport from '../../viewports/viewport';\nimport type {CoordinateSystem} from '../../lib/constants';\n\ntype Vec3 = [number, number, number];\ntype Vec4 = [number, number, number, number];\n\n// To quickly set a vector to zero\nconst ZERO_VECTOR: Vec4 = [0, 0, 0, 0];\n// 4x4 matrix that drops 4th component of vector\nconst VECTOR_TO_POINT_MATRIX: Matrix4Like = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0];\nconst IDENTITY_MATRIX: Matrix4Like = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];\nconst DEFAULT_PIXELS_PER_UNIT2: Vec3 = [0, 0, 0];\nconst DEFAULT_COORDINATE_ORIGIN: Vec3 = [0, 0, 0];\n\n/** Coordinate system constants */\nconst COORDINATE_SYSTEM_NUMBERS = {\n default: -1,\n cartesian: 0,\n lnglat: 1,\n 'meter-offsets': 2,\n 'lnglat-offsets': 3\n} as const satisfies Record;\n\nexport function getShaderCoordinateSystem(coordinateSystem: CoordinateSystem) {\n const shaderCoordinateSystem = COORDINATE_SYSTEM_NUMBERS[coordinateSystem];\n if (shaderCoordinateSystem === undefined) {\n throw new Error(`Invalid coordinateSystem: ${coordinateSystem}`);\n }\n return shaderCoordinateSystem;\n}\n\nconst getMemoizedViewportUniforms = memoize(calculateViewportUniforms);\n\nexport function getOffsetOrigin(\n viewport: Viewport,\n coordinateSystem: CoordinateSystem,\n coordinateOrigin: Vec3 = DEFAULT_COORDINATE_ORIGIN\n): {\n geospatialOrigin: Vec3 | null;\n shaderCoordinateOrigin: Vec3;\n offsetMode: boolean;\n} {\n if (coordinateOrigin.length < 3) {\n coordinateOrigin = [coordinateOrigin[0], coordinateOrigin[1], 0];\n }\n\n let shaderCoordinateOrigin = coordinateOrigin;\n let geospatialOrigin: Vec3 | null;\n let offsetMode = true;\n\n if (coordinateSystem === 'lnglat-offsets' || coordinateSystem === 'meter-offsets') {\n geospatialOrigin = coordinateOrigin;\n } else {\n geospatialOrigin = viewport.isGeospatial\n ? // @ts-expect-error longitude and latitude are not defined on the base Viewport, but is expected on geospatial viewports\n [Math.fround(viewport.longitude), Math.fround(viewport.latitude), 0]\n : null;\n }\n\n switch (viewport.projectionMode) {\n case PROJECTION_MODE.WEB_MERCATOR:\n if (coordinateSystem === 'lnglat' || coordinateSystem === 'cartesian') {\n geospatialOrigin = [0, 0, 0];\n offsetMode = false;\n }\n break;\n\n case PROJECTION_MODE.WEB_MERCATOR_AUTO_OFFSET:\n if (coordinateSystem === 'lnglat') {\n // viewport center in world space\n // @ts-expect-error when using LNGLAT coordinates, we expect the viewport to be geospatial, in which case geospatialOrigin is defined\n shaderCoordinateOrigin = geospatialOrigin;\n } else if (coordinateSystem === 'cartesian') {\n // viewport center in common space\n shaderCoordinateOrigin = [\n Math.fround(viewport.center[0]),\n Math.fround(viewport.center[1]),\n 0\n ];\n // Geospatial origin (wgs84) must match shaderCoordinateOrigin (common)\n geospatialOrigin = viewport.unprojectPosition(shaderCoordinateOrigin);\n shaderCoordinateOrigin[0] -= coordinateOrigin[0];\n shaderCoordinateOrigin[1] -= coordinateOrigin[1];\n shaderCoordinateOrigin[2] -= coordinateOrigin[2];\n }\n break;\n\n case PROJECTION_MODE.IDENTITY:\n shaderCoordinateOrigin = viewport.position.map(Math.fround) as Vec3;\n shaderCoordinateOrigin[2] = shaderCoordinateOrigin[2] || 0;\n break;\n\n case PROJECTION_MODE.GLOBE:\n offsetMode = false;\n geospatialOrigin = null;\n break;\n\n default:\n // Unknown projection mode\n offsetMode = false;\n }\n\n return {geospatialOrigin, shaderCoordinateOrigin, offsetMode};\n}\n\n// The code that utilizes Matrix4 does the same calculation as their mat4 counterparts,\n// has lower performance but provides error checking.\nfunction calculateMatrixAndOffset(\n viewport: Viewport,\n coordinateSystem: CoordinateSystem,\n coordinateOrigin: Vec3\n): {\n viewMatrix: Matrix4Like;\n viewProjectionMatrix: Matrix4Like;\n projectionCenter: Vec4;\n originCommon: Vec4;\n cameraPosCommon: Vec3;\n shaderCoordinateOrigin: Vec3;\n geospatialOrigin: Vec3 | null;\n} {\n const {viewMatrixUncentered, projectionMatrix} = viewport;\n let {viewMatrix, viewProjectionMatrix} = viewport;\n\n let projectionCenter = ZERO_VECTOR;\n let originCommon: Vec4 = ZERO_VECTOR;\n let cameraPosCommon: Vec3 = viewport.cameraPosition as Vec3;\n const {geospatialOrigin, shaderCoordinateOrigin, offsetMode} = getOffsetOrigin(\n viewport,\n coordinateSystem,\n coordinateOrigin\n );\n\n if (offsetMode) {\n // Calculate transformed projectionCenter (using 64 bit precision JS)\n // This is the key to offset mode precision\n // (avoids doing this addition in 32 bit precision in GLSL)\n // @ts-expect-error the 4th component is assigned below\n originCommon = viewport.projectPosition(geospatialOrigin || shaderCoordinateOrigin);\n\n cameraPosCommon = [\n cameraPosCommon[0] - originCommon[0],\n cameraPosCommon[1] - originCommon[1],\n cameraPosCommon[2] - originCommon[2]\n ];\n\n originCommon[3] = 1;\n\n // projectionCenter = new Matrix4(viewProjectionMatrix)\n // .transformVector([positionPixels[0], positionPixels[1], 0.0, 1.0]);\n projectionCenter = vec4.transformMat4([], originCommon, viewProjectionMatrix);\n\n // Always apply uncentered projection matrix if available (shader adds center)\n viewMatrix = viewMatrixUncentered || viewMatrix;\n\n // Zero out 4th coordinate (\"after\" model matrix) - avoids further translations\n // viewMatrix = new Matrix4(viewMatrixUncentered || viewMatrix)\n // .multiplyRight(VECTOR_TO_POINT_MATRIX);\n viewProjectionMatrix = mat4.multiply([], projectionMatrix, viewMatrix);\n viewProjectionMatrix = mat4.multiply([], viewProjectionMatrix, VECTOR_TO_POINT_MATRIX);\n }\n\n return {\n viewMatrix: viewMatrix as Matrix4Like,\n viewProjectionMatrix: viewProjectionMatrix as Matrix4Like,\n projectionCenter,\n originCommon,\n cameraPosCommon,\n shaderCoordinateOrigin,\n geospatialOrigin\n };\n}\n\nexport type ProjectUniforms = {\n coordinateSystem: number;\n projectionMode: number;\n coordinateOrigin: Vec3;\n commonOrigin: Vec3;\n center: Vec4;\n // Backward compatibility\n // TODO: remove in v9\n pseudoMeters: boolean;\n\n // Screen size\n viewportSize: [number, number];\n devicePixelRatio: number;\n\n focalDistance: number;\n commonUnitsPerMeter: Vec3;\n commonUnitsPerWorldUnit: Vec3;\n commonUnitsPerWorldUnit2: Vec3;\n /** 2^zoom */\n scale: number;\n wrapLongitude: boolean;\n\n viewProjectionMatrix: Matrix4Like;\n modelMatrix: Matrix4Like;\n\n // This is for lighting calculations\n cameraPosition: Vec3;\n};\n\nexport type ProjectProps = {\n viewport: Viewport;\n devicePixelRatio?: number;\n modelMatrix?: Matrix4Like | null;\n coordinateSystem?: CoordinateSystem;\n coordinateOrigin?: Vec3;\n autoWrapLongitude?: boolean;\n};\n\n/**\n * Returns uniforms for shaders based on current projection\n * includes: projection matrix suitable for shaders\n *\n * TODO - Ensure this works with any viewport, not just WebMercatorViewports\n *\n * @param {WebMercatorViewport} viewport -\n * @return {Float32Array} - 4x4 projection matrix that can be used in shaders\n */\nexport function getUniformsFromViewport({\n viewport,\n devicePixelRatio = 1,\n modelMatrix = null,\n // Match Layer.defaultProps\n coordinateSystem = 'default',\n coordinateOrigin = DEFAULT_COORDINATE_ORIGIN,\n autoWrapLongitude = false\n}: ProjectProps): ProjectUniforms {\n if (coordinateSystem === 'default') {\n coordinateSystem = viewport.isGeospatial ? 'lnglat' : 'cartesian';\n }\n\n const uniforms = getMemoizedViewportUniforms({\n viewport,\n devicePixelRatio,\n coordinateSystem,\n coordinateOrigin\n });\n\n uniforms.wrapLongitude = autoWrapLongitude;\n uniforms.modelMatrix = modelMatrix || IDENTITY_MATRIX;\n\n return uniforms;\n}\n\nfunction calculateViewportUniforms({\n viewport,\n devicePixelRatio,\n coordinateSystem,\n coordinateOrigin\n}: {\n viewport: Viewport;\n devicePixelRatio: number;\n coordinateSystem: CoordinateSystem;\n coordinateOrigin: Vec3;\n}): ProjectUniforms {\n const {\n projectionCenter,\n viewProjectionMatrix,\n originCommon,\n cameraPosCommon,\n shaderCoordinateOrigin,\n geospatialOrigin\n } = calculateMatrixAndOffset(viewport, coordinateSystem, coordinateOrigin);\n\n // Calculate projection pixels per unit\n const distanceScales = viewport.getDistanceScales();\n\n const viewportSize: [number, number] = [\n viewport.width * devicePixelRatio,\n viewport.height * devicePixelRatio\n ];\n\n // Distance at which screen pixels are projected.\n // Used to scale sizes in clipspace to match screen pixels.\n // When using Viewport class's default projection matrix, this yields 1 for orthographic\n // and `viewport.focalDistance` for perspective views\n const focalDistance =\n vec4.transformMat4([], [0, 0, -viewport.focalDistance, 1], viewport.projectionMatrix)[3] || 1;\n\n const uniforms: ProjectUniforms = {\n // Projection mode values\n coordinateSystem: getShaderCoordinateSystem(coordinateSystem),\n projectionMode: viewport.projectionMode,\n coordinateOrigin: shaderCoordinateOrigin,\n commonOrigin: originCommon.slice(0, 3) as Vec3,\n center: projectionCenter,\n\n // Backward compatibility\n // TODO: remove in v9\n // @ts-expect-error _pseudoMeters is only defined on WebMercator viewport\n pseudoMeters: Boolean(viewport._pseudoMeters),\n\n // Screen size\n viewportSize,\n devicePixelRatio,\n\n focalDistance,\n commonUnitsPerMeter: distanceScales.unitsPerMeter as Vec3,\n commonUnitsPerWorldUnit: distanceScales.unitsPerMeter as Vec3,\n commonUnitsPerWorldUnit2: DEFAULT_PIXELS_PER_UNIT2,\n scale: viewport.scale, // This is the mercator scale (2 ** zoom)\n wrapLongitude: false,\n\n viewProjectionMatrix,\n modelMatrix: IDENTITY_MATRIX,\n\n // This is for lighting calculations\n cameraPosition: cameraPosCommon\n };\n\n if (geospatialOrigin) {\n // Get high-precision DistanceScales from geospatial viewport\n // TODO: stricter types in Viewport classes\n const distanceScalesAtOrigin = viewport.getDistanceScales(geospatialOrigin) as {\n unitsPerMeter: Vec3;\n metersPerUnit: Vec3;\n unitsPerMeter2: Vec3;\n unitsPerDegree: Vec3;\n degreesPerUnit: Vec3;\n unitsPerDegree2: Vec3;\n };\n switch (coordinateSystem) {\n case 'meter-offsets':\n uniforms.commonUnitsPerWorldUnit = distanceScalesAtOrigin.unitsPerMeter;\n uniforms.commonUnitsPerWorldUnit2 = distanceScalesAtOrigin.unitsPerMeter2;\n break;\n\n case 'lnglat':\n case 'lnglat-offsets':\n // @ts-expect-error _pseudoMeters only exists on WebMercatorView\n if (!viewport._pseudoMeters) {\n uniforms.commonUnitsPerMeter = distanceScalesAtOrigin.unitsPerMeter;\n }\n uniforms.commonUnitsPerWorldUnit = distanceScalesAtOrigin.unitsPerDegree;\n uniforms.commonUnitsPerWorldUnit2 = distanceScalesAtOrigin.unitsPerDegree2;\n break;\n\n // a.k.a \"preprojected\" positions\n case 'cartesian':\n uniforms.commonUnitsPerWorldUnit = [1, 1, distanceScalesAtOrigin.unitsPerMeter[2]];\n uniforms.commonUnitsPerWorldUnit2 = [0, 0, distanceScalesAtOrigin.unitsPerMeter2[2]];\n break;\n\n default:\n break;\n }\n }\n\n return uniforms;\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {PROJECTION_MODE, UNIT} from '../../lib/constants';\nimport {getShaderCoordinateSystem} from './viewport-uniforms';\n\nconst SHADER_COORDINATE_SYSTEMS = [\n 'default',\n 'lnglat',\n 'meter-offsets',\n 'lnglat-offsets',\n 'cartesian'\n] as const;\n\nconst COORDINATE_SYSTEM_WGSL_CONSTANTS = SHADER_COORDINATE_SYSTEMS.map(\n coordinateSystem =>\n `const COORDINATE_SYSTEM_${coordinateSystem.toUpperCase().replaceAll('-', '_')}: i32 = ${getShaderCoordinateSystem(coordinateSystem)};`\n).join('');\nconst PROJECTION_MODE_WGSL_CONSTANTS = Object.keys(PROJECTION_MODE)\n .map(key => `const PROJECTION_MODE_${key}: i32 = ${PROJECTION_MODE[key]};`)\n .join('');\nconst UNIT_WGSL_CONSTANTS = Object.keys(UNIT)\n .map(key => `const UNIT_${key.toUpperCase()}: i32 = ${UNIT[key]};`)\n .join('');\n\nexport const projectWGSLHeader = /* wgsl */ `\\\n${COORDINATE_SYSTEM_WGSL_CONSTANTS}\n${PROJECTION_MODE_WGSL_CONSTANTS}\n${UNIT_WGSL_CONSTANTS}\n\nconst TILE_SIZE: f32 = 512.0;\nconst PI: f32 = 3.1415926536;\nconst WORLD_SCALE: f32 = TILE_SIZE / (PI * 2.0);\nconst ZERO_64_LOW: vec3 = vec3(0.0, 0.0, 0.0);\nconst EARTH_RADIUS: f32 = 6370972.0; // meters\nconst GLOBE_RADIUS: f32 = 256.0;\n\n// -----------------------------------------------------------------------------\n// Uniform block (converted from GLSL uniform block)\n// -----------------------------------------------------------------------------\nstruct ProjectUniforms {\n wrapLongitude: i32,\n coordinateSystem: i32,\n commonUnitsPerMeter: vec3,\n projectionMode: i32,\n scale: f32,\n commonUnitsPerWorldUnit: vec3,\n commonUnitsPerWorldUnit2: vec3,\n center: vec4,\n modelMatrix: mat4x4,\n viewProjectionMatrix: mat4x4,\n viewportSize: vec2,\n devicePixelRatio: f32,\n focalDistance: f32,\n cameraPosition: vec3,\n coordinateOrigin: vec3,\n commonOrigin: vec3,\n pseudoMeters: i32,\n};\n\n@group(0) @binding(auto)\nvar project: ProjectUniforms;\n\n// -----------------------------------------------------------------------------\n// Geometry data shared across the project helpers.\n// The active layer shader is responsible for populating this private module\n// state before calling the project functions below.\n// -----------------------------------------------------------------------------\n\n// Structure to carry additional geometry data used by deck.gl filters.\nstruct Geometry {\n worldPosition: vec3,\n worldPositionAlt: vec3,\n position: vec4,\n normal: vec3,\n uv: vec2,\n pickingColor: vec3,\n};\n\nvar geometry: Geometry;\n`;\n\nexport const projectWGSL = /* wgsl */ `\\\n${projectWGSLHeader}\n\n// -----------------------------------------------------------------------------\n// Functions\n// -----------------------------------------------------------------------------\n\n// Returns an adjustment factor for commonUnitsPerMeter\nfn _project_size_at_latitude(lat: f32) -> f32 {\n let y = clamp(lat, -89.9, 89.9);\n return 1.0 / cos(radians(y));\n}\n\n// Overloaded version: scales a value in meters at a given latitude.\nfn _project_size_at_latitude_m(meters: f32, lat: f32) -> f32 {\n return meters * project.commonUnitsPerMeter.z * _project_size_at_latitude(lat);\n}\n\n// Computes a non-linear scale factor based on geometry.\n// (Note: This function relies on \"geometry\" being provided.)\nfn project_size() -> f32 {\n if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR &&\n project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT &&\n project.pseudoMeters == 0) {\n if (geometry.position.w == 0.0) {\n return _project_size_at_latitude(geometry.worldPosition.y);\n }\n let y: f32 = geometry.position.y / TILE_SIZE * 2.0 - 1.0;\n let y2 = y * y;\n let y4 = y2 * y2;\n let y6 = y4 * y2;\n return 1.0 + 4.9348 * y2 + 4.0587 * y4 + 1.5642 * y6;\n }\n return 1.0;\n}\n\n// Overloads to scale offsets (meters to world units)\nfn project_size_float(meters: f32) -> f32 {\n return meters * project.commonUnitsPerMeter.z * project_size();\n}\n\nfn project_size_vec2(meters: vec2) -> vec2 {\n return meters * project.commonUnitsPerMeter.xy * project_size();\n}\n\nfn project_size_vec3(meters: vec3) -> vec3 {\n return meters * project.commonUnitsPerMeter * project_size();\n}\n\nfn project_size_vec4(meters: vec4) -> vec4 {\n return vec4(meters.xyz * project.commonUnitsPerMeter, meters.w);\n}\n\n// Returns a rotation matrix aligning the z‑axis with the given up vector.\nfn project_get_orientation_matrix(up: vec3) -> mat3x3 {\n let uz = normalize(up);\n let ux = select(\n vec3(1.0, 0.0, 0.0),\n normalize(vec3(uz.y, -uz.x, 0.0)),\n abs(uz.z) == 1.0\n );\n let uy = cross(uz, ux);\n return mat3x3(ux, uy, uz);\n}\n\n// Since WGSL does not support \"out\" parameters, we return a struct.\nstruct RotationResult {\n needsRotation: bool,\n transform: mat3x3,\n};\n\nfn project_needs_rotation(commonPosition: vec3) -> RotationResult {\n if (project.projectionMode == PROJECTION_MODE_GLOBE) {\n return RotationResult(true, project_get_orientation_matrix(commonPosition));\n } else {\n return RotationResult(false, mat3x3()); // identity alternative if needed\n };\n}\n\n// Projects a normal vector from the current coordinate system to world space.\nfn project_normal(vector: vec3) -> vec3 {\n let normal_modelspace = project.modelMatrix * vec4(vector, 0.0);\n var n = normalize(normal_modelspace.xyz * project.commonUnitsPerMeter);\n let rotResult = project_needs_rotation(geometry.position.xyz);\n if (rotResult.needsRotation) {\n n = rotResult.transform * n;\n }\n return n;\n}\n\n// Applies a scale offset based on y-offset (dy)\nfn project_offset_(offset: vec4) -> vec4 {\n let dy: f32 = offset.y;\n let commonUnitsPerWorldUnit = project.commonUnitsPerWorldUnit + project.commonUnitsPerWorldUnit2 * dy;\n return vec4(offset.xyz * commonUnitsPerWorldUnit, offset.w);\n}\n\n// Projects lng/lat coordinates to a unit tile [0,1]\nfn project_mercator_(lnglat: vec2) -> vec2 {\n var x = lnglat.x;\n if (project.wrapLongitude != 0) {\n x = ((x + 180.0) % 360.0) - 180.0;\n }\n let y = clamp(lnglat.y, -89.9, 89.9);\n return vec2(\n radians(x) + PI,\n PI + log(tan(PI * 0.25 + radians(y) * 0.5))\n ) * WORLD_SCALE;\n}\n\n// Projects lng/lat/z coordinates for a globe projection.\nfn project_globe_(lnglatz: vec3) -> vec3 {\n let lambda = radians(lnglatz.x);\n let phi = radians(lnglatz.y);\n let cosPhi = cos(phi);\n let D = (lnglatz.z / EARTH_RADIUS + 1.0) * GLOBE_RADIUS;\n return vec3(\n sin(lambda) * cosPhi,\n -cos(lambda) * cosPhi,\n sin(phi)\n ) * D;\n}\n\n// Projects positions (with an optional 64-bit low part) from the input\n// coordinate system to the common space.\nfn project_position_vec4_f64(position: vec4, position64Low: vec3) -> vec4 {\n var position_world = project.modelMatrix * position;\n\n // Work around for a Mac+NVIDIA bug:\n if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR) {\n if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) {\n return vec4(\n project_mercator_(position_world.xy),\n _project_size_at_latitude_m(position_world.z, position_world.y),\n position_world.w\n );\n }\n if (project.coordinateSystem == COORDINATE_SYSTEM_CARTESIAN) {\n position_world = vec4f(position_world.xyz + project.coordinateOrigin, position_world.w);\n }\n }\n if (project.projectionMode == PROJECTION_MODE_GLOBE) {\n if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) {\n return vec4(\n project_globe_(position_world.xyz),\n position_world.w\n );\n }\n }\n if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR_AUTO_OFFSET) {\n if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) {\n if (abs(position_world.y - project.coordinateOrigin.y) > 0.25) {\n return vec4(\n project_mercator_(position_world.xy) - project.commonOrigin.xy,\n project_size_float(position_world.z),\n position_world.w\n );\n }\n }\n }\n if (project.projectionMode == PROJECTION_MODE_IDENTITY ||\n (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR_AUTO_OFFSET &&\n (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT ||\n project.coordinateSystem == COORDINATE_SYSTEM_CARTESIAN))) {\n position_world = vec4f(position_world.xyz - project.coordinateOrigin, position_world.w);\n }\n\n return project_offset_(position_world) +\n project_offset_(project.modelMatrix * vec4(position64Low, 0.0));\n}\n\n// Overloaded versions for different input types.\nfn project_position_vec4_f32(position: vec4) -> vec4 {\n return project_position_vec4_f64(position, ZERO_64_LOW);\n}\n\nfn project_position_vec3_f64(position: vec3, position64Low: vec3) -> vec3 {\n let projected_position = project_position_vec4_f64(vec4(position, 1.0), position64Low);\n return projected_position.xyz;\n}\n\nfn project_position_vec3_f32(position: vec3) -> vec3 {\n let projected_position = project_position_vec4_f64(vec4(position, 1.0), ZERO_64_LOW);\n return projected_position.xyz;\n}\n\nfn project_position_vec2_f32(position: vec2) -> vec2 {\n let projected_position = project_position_vec4_f64(vec4(position, 0.0, 1.0), ZERO_64_LOW);\n return projected_position.xy;\n}\n\n// Transforms a common space position to clip space.\nfn project_common_position_to_clipspace_with_projection(position: vec4, viewProjectionMatrix: mat4x4, center: vec4) -> vec4 {\n return viewProjectionMatrix * position + center;\n}\n\n// Uses the project viewProjectionMatrix and center.\nfn project_common_position_to_clipspace(position: vec4) -> vec4 {\n return project_common_position_to_clipspace_with_projection(position, project.viewProjectionMatrix, project.center);\n}\n\n// Returns a clip space offset corresponding to a given number of screen pixels.\nfn project_pixel_size_to_clipspace(pixels: vec2) -> vec2 {\n let offset = pixels / project.viewportSize * project.devicePixelRatio * 2.0;\n return offset * project.focalDistance;\n}\n\nfn project_meter_size_to_pixel(meters: f32) -> f32 {\n return project_size_float(meters) * project.scale;\n}\n\nfn project_unit_size_to_pixel(size: f32, unit: i32) -> f32 {\n if (unit == UNIT_METERS) {\n return project_meter_size_to_pixel(size);\n } else if (unit == UNIT_COMMON) {\n return size * project.scale;\n }\n // UNIT_PIXELS: no scaling applied.\n return size;\n}\n\nfn project_pixel_size_float(pixels: f32) -> f32 {\n return pixels / project.scale;\n}\n\nfn project_pixel_size_vec2(pixels: vec2) -> vec2 {\n return pixels / project.scale;\n}\n`;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {PROJECTION_MODE, UNIT} from '../../lib/constants';\nimport {getShaderCoordinateSystem} from './viewport-uniforms';\n\nconst SHADER_COORDINATE_SYSTEMS = [\n 'default',\n 'lnglat',\n 'meter-offsets',\n 'lnglat-offsets',\n 'cartesian'\n] as const;\n\nconst COORDINATE_SYSTEM_GLSL_CONSTANTS = SHADER_COORDINATE_SYSTEMS.map(\n coordinateSystem =>\n `const int COORDINATE_SYSTEM_${coordinateSystem.toUpperCase().replaceAll('-', '_')} = ${getShaderCoordinateSystem(coordinateSystem)};`\n).join('');\nconst PROJECTION_MODE_GLSL_CONSTANTS = Object.keys(PROJECTION_MODE)\n .map(key => `const int PROJECTION_MODE_${key} = ${PROJECTION_MODE[key]};`)\n .join('');\nconst UNIT_GLSL_CONSTANTS = Object.keys(UNIT)\n .map(key => `const int UNIT_${key.toUpperCase()} = ${UNIT[key]};`)\n .join('');\n\nexport const projectGLSL = /* glsl */ `\\\n${COORDINATE_SYSTEM_GLSL_CONSTANTS}\n${PROJECTION_MODE_GLSL_CONSTANTS}\n${UNIT_GLSL_CONSTANTS}\n\nlayout(std140) uniform projectUniforms {\n bool wrapLongitude;\n int coordinateSystem;\n vec3 commonUnitsPerMeter;\n int projectionMode;\n float scale;\n vec3 commonUnitsPerWorldUnit;\n vec3 commonUnitsPerWorldUnit2;\n vec4 center;\n mat4 modelMatrix;\n mat4 viewProjectionMatrix;\n vec2 viewportSize;\n float devicePixelRatio;\n float focalDistance;\n vec3 cameraPosition;\n vec3 coordinateOrigin;\n vec3 commonOrigin;\n bool pseudoMeters;\n} project;\n\n\nconst float TILE_SIZE = 512.0;\nconst float PI = 3.1415926536;\nconst float WORLD_SCALE = TILE_SIZE / (PI * 2.0);\nconst vec3 ZERO_64_LOW = vec3(0.0);\nconst float EARTH_RADIUS = 6370972.0; // meters\nconst float GLOBE_RADIUS = 256.0;\n\n// returns an adjustment factor for uCommonUnitsPerMeter\nfloat project_size_at_latitude(float lat) {\n float y = clamp(lat, -89.9, 89.9);\n return 1.0 / cos(radians(y));\n}\n\nfloat project_size() {\n if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR &&\n project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT &&\n project.pseudoMeters == false) {\n\n // uCommonUnitsPerMeter in low-zoom Web Mercator is non-linear\n // Adjust by 1 / cos(latitude)\n // If geometry.position (vertex in common space) is populated, use it\n // Otherwise use geometry.worldPosition (anchor in world space)\n \n if (geometry.position.w == 0.0) {\n return project_size_at_latitude(geometry.worldPosition.y);\n }\n\n // latitude from common y: 2.0 * (atan(exp(y / TILE_SIZE * 2.0 * PI - PI)) - PI / 4.0)\n // Taylor series of 1 / cos(latitude)\n // Max error < 0.003\n \n float y = geometry.position.y / TILE_SIZE * 2.0 - 1.0;\n float y2 = y * y;\n float y4 = y2 * y2;\n float y6 = y4 * y2;\n return 1.0 + 4.9348 * y2 + 4.0587 * y4 + 1.5642 * y6;\n }\n return 1.0;\n}\n\nfloat project_size_at_latitude(float meters, float lat) {\n return meters * project.commonUnitsPerMeter.z * project_size_at_latitude(lat);\n}\n\n//\n// Scaling offsets - scales meters to \"world distance\"\n// Note the scalar version of project_size is for scaling the z component only\n//\nfloat project_size(float meters) {\n // For scatter relevant\n return meters * project.commonUnitsPerMeter.z * project_size();\n}\n\nvec2 project_size(vec2 meters) {\n return meters * project.commonUnitsPerMeter.xy * project_size();\n}\n\nvec3 project_size(vec3 meters) {\n return meters * project.commonUnitsPerMeter * project_size();\n}\n\nvec4 project_size(vec4 meters) {\n return vec4(meters.xyz * project.commonUnitsPerMeter, meters.w);\n}\n\n// Get rotation matrix that aligns the z axis with the given up vector\n// Find 3 unit vectors ux, uy, uz that are perpendicular to each other and uz == up\nmat3 project_get_orientation_matrix(vec3 up) {\n vec3 uz = normalize(up);\n // Tangent on XY plane\n vec3 ux = abs(uz.z) == 1.0 ? vec3(1.0, 0.0, 0.0) : normalize(vec3(uz.y, -uz.x, 0));\n vec3 uy = cross(uz, ux);\n return mat3(ux, uy, uz);\n}\n\nbool project_needs_rotation(vec3 commonPosition, out mat3 transform) {\n if (project.projectionMode == PROJECTION_MODE_GLOBE) {\n transform = project_get_orientation_matrix(commonPosition);\n return true;\n }\n return false;\n}\n\n//\n// Projecting normal - transform deltas from current coordinate system to\n// normals in the worldspace\n//\nvec3 project_normal(vec3 vector) {\n // Apply model matrix\n vec4 normal_modelspace = project.modelMatrix * vec4(vector, 0.0);\n vec3 n = normalize(normal_modelspace.xyz * project.commonUnitsPerMeter);\n mat3 rotation;\n if (project_needs_rotation(geometry.position.xyz, rotation)) {\n n = rotation * n;\n }\n return n;\n}\n\nvec4 project_offset_(vec4 offset) {\n float dy = offset.y;\n vec3 commonUnitsPerWorldUnit = project.commonUnitsPerWorldUnit + project.commonUnitsPerWorldUnit2 * dy;\n return vec4(offset.xyz * commonUnitsPerWorldUnit, offset.w);\n}\n\n//\n// Projecting positions - non-linear projection: lnglats => unit tile [0-1, 0-1]\n//\nvec2 project_mercator_(vec2 lnglat) {\n float x = lnglat.x;\n if (project.wrapLongitude) {\n x = mod(x + 180., 360.0) - 180.;\n }\n float y = clamp(lnglat.y, -89.9, 89.9);\n return vec2(\n radians(x) + PI,\n PI + log(tan_fp32(PI * 0.25 + radians(y) * 0.5))\n ) * WORLD_SCALE;\n}\n\nvec3 project_globe_(vec3 lnglatz) {\n float lambda = radians(lnglatz.x);\n float phi = radians(lnglatz.y);\n float cosPhi = cos(phi);\n float D = (lnglatz.z / EARTH_RADIUS + 1.0) * GLOBE_RADIUS;\n\n return vec3(\n sin(lambda) * cosPhi,\n -cos(lambda) * cosPhi,\n sin(phi)\n ) * D;\n}\n\n//\n// Projects positions (defined by project.coordinateSystem) to common space (defined by project.projectionMode)\n//\nvec4 project_position(vec4 position, vec3 position64Low) {\n vec4 position_world = project.modelMatrix * position;\n\n // Work around for a Mac+NVIDIA bug https://github.com/visgl/deck.gl/issues/4145\n if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR) {\n if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) {\n return vec4(\n project_mercator_(position_world.xy),\n project_size_at_latitude(position_world.z, position_world.y),\n position_world.w\n );\n }\n if (project.coordinateSystem == COORDINATE_SYSTEM_CARTESIAN) {\n position_world.xyz += project.coordinateOrigin;\n }\n }\n if (project.projectionMode == PROJECTION_MODE_GLOBE) {\n if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) {\n return vec4(\n project_globe_(position_world.xyz),\n position_world.w\n );\n }\n }\n if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR_AUTO_OFFSET) {\n if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) {\n if (abs(position_world.y - project.coordinateOrigin.y) > 0.25) {\n // Too far from the projection center for offset mode to be accurate\n // Only use high parts\n return vec4(\n project_mercator_(position_world.xy) - project.commonOrigin.xy,\n project_size(position_world.z),\n position_world.w\n );\n }\n }\n }\n if (project.projectionMode == PROJECTION_MODE_IDENTITY ||\n (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR_AUTO_OFFSET &&\n (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT ||\n project.coordinateSystem == COORDINATE_SYSTEM_CARTESIAN))) {\n // Subtract high part of 64 bit value. Convert remainder to float32, preserving precision.\n position_world.xyz -= project.coordinateOrigin;\n }\n\n // Translation is already added to the high parts\n return project_offset_(position_world) + project_offset_(project.modelMatrix * vec4(position64Low, 0.0));\n}\n\nvec4 project_position(vec4 position) {\n return project_position(position, ZERO_64_LOW);\n}\n\nvec3 project_position(vec3 position, vec3 position64Low) {\n vec4 projected_position = project_position(vec4(position, 1.0), position64Low);\n return projected_position.xyz;\n}\n\nvec3 project_position(vec3 position) {\n vec4 projected_position = project_position(vec4(position, 1.0), ZERO_64_LOW);\n return projected_position.xyz;\n}\n\nvec2 project_position(vec2 position) {\n vec4 projected_position = project_position(vec4(position, 0.0, 1.0), ZERO_64_LOW);\n return projected_position.xy;\n}\n\nvec4 project_common_position_to_clipspace(vec4 position, mat4 viewProjectionMatrix, vec4 center) {\n return viewProjectionMatrix * position + center;\n}\n\n//\n// Projects from common space coordinates to clip space.\n// Uses project.viewProjectionMatrix\n//\nvec4 project_common_position_to_clipspace(vec4 position) {\n return project_common_position_to_clipspace(position, project.viewProjectionMatrix, project.center);\n}\n\n// Returns a clip space offset that corresponds to a given number of screen pixels\nvec2 project_pixel_size_to_clipspace(vec2 pixels) {\n vec2 offset = pixels / project.viewportSize * project.devicePixelRatio * 2.0;\n return offset * project.focalDistance;\n}\n\nfloat project_size_to_pixel(float meters) {\n return project_size(meters) * project.scale;\n}\nvec2 project_size_to_pixel(vec2 meters) {\n return project_size(meters) * project.scale;\n}\nfloat project_size_to_pixel(float size, int unit) {\n if (unit == UNIT_METERS) return project_size_to_pixel(size);\n if (unit == UNIT_COMMON) return size * project.scale;\n // UNIT_PIXELS\n return size;\n}\nfloat project_pixel_size(float pixels) {\n return pixels / project.scale;\n}\nvec2 project_pixel_size(vec2 pixels) {\n return pixels / project.scale;\n}\n`;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {fp32, ShaderModule} from '@luma.gl/shadertools';\nimport geometry from '../misc/geometry';\nimport {getUniformsFromViewport} from './viewport-uniforms';\nimport {projectWGSL} from './project.wgsl';\nimport {projectGLSL} from './project.glsl';\n\nimport type {ProjectProps, ProjectUniforms} from './viewport-uniforms';\n\nconst INITIAL_MODULE_OPTIONS = {};\n\nfunction getUniforms(opts: ProjectProps | {} = INITIAL_MODULE_OPTIONS) {\n if ('viewport' in opts) {\n return getUniformsFromViewport(opts);\n }\n return {};\n}\n\nexport default {\n name: 'project',\n dependencies: [fp32, geometry],\n source: projectWGSL,\n vs: projectGLSL,\n getUniforms,\n uniformTypes: {\n wrapLongitude: 'f32',\n coordinateSystem: 'i32',\n commonUnitsPerMeter: 'vec3',\n projectionMode: 'i32',\n scale: 'f32',\n commonUnitsPerWorldUnit: 'vec3',\n commonUnitsPerWorldUnit2: 'vec3',\n center: 'vec4',\n modelMatrix: 'mat4x4',\n viewProjectionMatrix: 'mat4x4',\n viewportSize: 'vec2',\n devicePixelRatio: 'f32',\n focalDistance: 'f32',\n cameraPosition: 'vec3',\n coordinateOrigin: 'vec3',\n commonOrigin: 'vec3',\n pseudoMeters: 'f32'\n }\n // @ts-ignore TODO v9.1\n} as const satisfies ShaderModule;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ShaderModule} from '@luma.gl/shadertools';\nimport project from '../project/project';\n\nconst source = /* wgsl */ `\\\n// Define a structure to hold both the clip-space position and the common position.\nstruct ProjectResult {\n clipPosition: vec4,\n commonPosition: vec4,\n};\n\n// This function mimics the GLSL version with the 'out' parameter by returning both values.\nfn project_position_to_clipspace_and_commonspace(\n position: vec3,\n position64Low: vec3,\n offset: vec3\n) -> ProjectResult {\n // Compute the projected position.\n let projectedPosition: vec3 = project_position_vec3_f64(position, position64Low);\n\n // Start with the provided offset.\n var finalOffset: vec3 = offset;\n\n // Get whether a rotation is needed and the rotation matrix.\n let rotationResult = project_needs_rotation(projectedPosition);\n\n // If rotation is needed, update the offset.\n if (rotationResult.needsRotation) {\n finalOffset = rotationResult.transform * offset;\n }\n\n // Compute the common position.\n let commonPosition: vec4 = vec4(projectedPosition + finalOffset, 1.0);\n\n // Convert to clip-space.\n let clipPosition: vec4 = project_common_position_to_clipspace(commonPosition);\n\n return ProjectResult(clipPosition, commonPosition);\n}\n\n// A convenience overload that returns only the clip-space position.\nfn project_position_to_clipspace(\n position: vec3,\n position64Low: vec3,\n offset: vec3\n) -> vec4 {\n return project_position_to_clipspace_and_commonspace(position, position64Low, offset).clipPosition;\n}\n`;\n\nconst vs = /* glsl */ `\\\nvec4 project_position_to_clipspace(\n vec3 position, vec3 position64Low, vec3 offset, out vec4 commonPosition\n) {\n vec3 projectedPosition = project_position(position, position64Low);\n mat3 rotation;\n if (project_needs_rotation(projectedPosition, rotation)) {\n // offset is specified as ENU\n // when in globe projection, rotate offset so that the ground alighs with the surface of the globe\n offset = rotation * offset;\n }\n commonPosition = vec4(projectedPosition + offset, 1.0);\n return project_common_position_to_clipspace(commonPosition);\n}\n\nvec4 project_position_to_clipspace(\n vec3 position, vec3 position64Low, vec3 offset\n) {\n vec4 commonPosition;\n return project_position_to_clipspace(position, position64Low, offset, commonPosition);\n}\n`;\n\nexport default {\n name: 'project32',\n dependencies: [project],\n source,\n vs\n} as ShaderModule;\n","import {vec4} from '@math.gl/core';\n\n// Helper, avoids low-precision 32 bit matrices from gl-matrix mat4.create()\nexport function createMat4(): number[] {\n return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];\n}\n\n// Transforms a vec4 with a projection matrix\nexport function transformVector(matrix: number[], vector: number[]): number[] {\n const result = vec4.transformMat4([] as number[], vector, matrix);\n vec4.scale(result, result, 1 / result[3]);\n return result;\n}\n\nexport function mod(value: number, divisor: number): number {\n const modulus = value % divisor;\n return modulus < 0 ? divisor + modulus : modulus;\n}\n\nexport function lerp(start: number, end: number, step: number): number {\n return step * end + (1 - step) * start;\n}\n\nexport function clamp(x: number, min: number, max: number): number {\n return x < min ? min : x > max ? max : x;\n}\n\nfunction ieLog2(x: number): number {\n return Math.log(x) * Math.LOG2E;\n}\n// Handle missing log2 in IE 11\nexport const log2 = Math.log2 || ieLog2;\n","// Replacement for the external assert method to reduce bundle size\n// Note: We don't use the second \"message\" argument in calling code,\n// so no need to support it here\nexport function assert(condition: unknown, message?: string): void {\n if (!condition) {\n throw new Error(message || '@math.gl/web-mercator: assertion failed.');\n }\n}\n","// TODO - THE UTILITIES IN THIS FILE SHOULD BE IMPORTED FROM WEB-MERCATOR-VIEWPORT MODULE\n\nimport {createMat4, transformVector, clamp, log2} from './math-utils';\n\nimport {mat4, vec2, vec3} from '@math.gl/core';\nimport {assert} from './assert';\n\n// CONSTANTS\nconst PI = Math.PI;\nconst PI_4 = PI / 4;\nconst DEGREES_TO_RADIANS = PI / 180;\nconst RADIANS_TO_DEGREES = 180 / PI;\nconst TILE_SIZE = 512;\n// Average circumference (40075 km equatorial, 40007 km meridional)\nconst EARTH_CIRCUMFERENCE = 40.03e6;\n// Latitude that makes a square world, 2 * atan(E ** PI) - PI / 2\nexport const MAX_LATITUDE = 85.051129;\n\n// Mapbox default altitude\nexport const DEFAULT_ALTITUDE = 1.5;\n\nexport type DistanceScales = {\n unitsPerMeter: number[];\n metersPerUnit: number[];\n unitsPerMeter2?: number[];\n unitsPerDegree: number[];\n degreesPerUnit: number[];\n unitsPerDegree2?: number[];\n};\n\n/**\n * PROJECTION MATRIX PARAMETERS\n *\n * TODO how to document mebers\n * @param fov in radians. fov is variable, depends on pitch and altitude\n * @param aspect width/height\n * @param focalDistance distance at which visual scale factor is 1\n * @param near near clipping plane\n * @param far far clipping plane\n */\ntype ProjectionParameters = {\n fov: number;\n aspect: number;\n focalDistance: number;\n near: number;\n far: number;\n};\n\n/** Logarithimic zoom to linear scale **/\nexport function zoomToScale(zoom: number): number {\n return Math.pow(2, zoom);\n}\n\n/** Linear scale to logarithimic zoom **/\nexport function scaleToZoom(scale: number): number {\n return log2(scale);\n}\n\n/**\n * Project [lng,lat] on sphere onto [x,y] on 512*512 Mercator Zoom 0 tile.\n * Performs the nonlinear part of the web mercator projection.\n * Remaining projection is done with 4x4 matrices which also handles\n * perspective.\n *\n * @param lngLat - [lng, lat] coordinates\n * Specifies a point on the sphere to project onto the map.\n * @return [x,y] coordinates.\n */\nexport function lngLatToWorld(lngLat: number[]): [number, number] {\n const [lng, lat] = lngLat;\n assert(Number.isFinite(lng));\n assert(Number.isFinite(lat) && lat >= -90 && lat <= 90, 'invalid latitude');\n\n const lambda2 = lng * DEGREES_TO_RADIANS;\n const phi2 = lat * DEGREES_TO_RADIANS;\n const x = (TILE_SIZE * (lambda2 + PI)) / (2 * PI);\n const y = (TILE_SIZE * (PI + Math.log(Math.tan(PI_4 + phi2 * 0.5)))) / (2 * PI);\n return [x, y];\n}\n\n/**\n * Unproject world point [x,y] on map onto {lat, lon} on sphere\n *\n * @param xy - array with [x,y] members\n * representing point on projected map plane\n * @return - array with [x,y] of point on sphere.\n * Has toArray method if you need a GeoJSON Array.\n * Per cartographic tradition, lat and lon are specified as degrees.\n */\nexport function worldToLngLat(xy: number[]): [number, number] {\n const [x, y] = xy;\n const lambda2 = (x / TILE_SIZE) * (2 * PI) - PI;\n const phi2 = 2 * (Math.atan(Math.exp((y / TILE_SIZE) * (2 * PI) - PI)) - PI_4);\n return [lambda2 * RADIANS_TO_DEGREES, phi2 * RADIANS_TO_DEGREES];\n}\n\n/**\n * Returns the zoom level that gives a 1 meter pixel at a certain latitude\n * 1 = C*cos(y)/2^z/TILE_SIZE = C*cos(y)/2^(z+9)\n */\nexport function getMeterZoom(options: {latitude: number}): number {\n const {latitude} = options;\n assert(Number.isFinite(latitude));\n const latCosine = Math.cos(latitude * DEGREES_TO_RADIANS);\n return scaleToZoom(EARTH_CIRCUMFERENCE * latCosine) - 9;\n}\n\n/**\n * Calculate the conversion from meter to common units at a given latitude\n * This is a cheaper version of `getDistanceScales`\n * @param latitude center latitude in degrees\n * @returns common units per meter\n */\nexport function unitsPerMeter(latitude: number): number {\n const latCosine = Math.cos(latitude * DEGREES_TO_RADIANS);\n return TILE_SIZE / EARTH_CIRCUMFERENCE / latCosine;\n}\n\n/**\n * Calculate distance scales in meters around current lat/lon, both for\n * degrees and pixels.\n * In mercator projection mode, the distance scales vary significantly\n * with latitude.\n */\nexport function getDistanceScales(options: {\n latitude: number;\n longitude: number;\n highPrecision?: boolean;\n}): DistanceScales {\n const {latitude, longitude, highPrecision = false} = options;\n assert(Number.isFinite(latitude) && Number.isFinite(longitude));\n\n const worldSize = TILE_SIZE;\n const latCosine = Math.cos(latitude * DEGREES_TO_RADIANS);\n\n /**\n * Number of pixels occupied by one degree longitude around current lat/lon:\n unitsPerDegreeX = d(lngLatToWorld([lng, lat])[0])/d(lng)\n = scale * TILE_SIZE * DEGREES_TO_RADIANS / (2 * PI)\n unitsPerDegreeY = d(lngLatToWorld([lng, lat])[1])/d(lat)\n = -scale * TILE_SIZE * DEGREES_TO_RADIANS / cos(lat * DEGREES_TO_RADIANS) / (2 * PI)\n */\n const unitsPerDegreeX = worldSize / 360;\n const unitsPerDegreeY = unitsPerDegreeX / latCosine;\n\n /**\n * Number of pixels occupied by one meter around current lat/lon:\n */\n const altUnitsPerMeter = worldSize / EARTH_CIRCUMFERENCE / latCosine;\n\n /**\n * LngLat: longitude -> east and latitude -> north (bottom left)\n * UTM meter offset: x -> east and y -> north (bottom left)\n * World space: x -> east and y -> south (top left)\n *\n * Y needs to be flipped when converting delta degree/meter to delta pixels\n */\n const result: DistanceScales = {\n unitsPerMeter: [altUnitsPerMeter, altUnitsPerMeter, altUnitsPerMeter],\n metersPerUnit: [1 / altUnitsPerMeter, 1 / altUnitsPerMeter, 1 / altUnitsPerMeter],\n\n unitsPerDegree: [unitsPerDegreeX, unitsPerDegreeY, altUnitsPerMeter],\n degreesPerUnit: [1 / unitsPerDegreeX, 1 / unitsPerDegreeY, 1 / altUnitsPerMeter]\n };\n\n /**\n * Taylor series 2nd order for 1/latCosine\n f'(a) * (x - a)\n = d(1/cos(lat * DEGREES_TO_RADIANS))/d(lat) * dLat\n = DEGREES_TO_RADIANS * tan(lat * DEGREES_TO_RADIANS) / cos(lat * DEGREES_TO_RADIANS) * dLat\n */\n if (highPrecision) {\n const latCosine2 = (DEGREES_TO_RADIANS * Math.tan(latitude * DEGREES_TO_RADIANS)) / latCosine;\n const unitsPerDegreeY2 = (unitsPerDegreeX * latCosine2) / 2;\n const altUnitsPerDegree2 = (worldSize / EARTH_CIRCUMFERENCE) * latCosine2;\n const altUnitsPerMeter2 = (altUnitsPerDegree2 / unitsPerDegreeY) * altUnitsPerMeter;\n\n result.unitsPerDegree2 = [0, unitsPerDegreeY2, altUnitsPerDegree2];\n result.unitsPerMeter2 = [altUnitsPerMeter2, 0, altUnitsPerMeter2];\n }\n\n // Main results, used for converting meters to latlng deltas and scaling offsets\n return result;\n}\n\n/**\n * Offset a lng/lat position by meterOffset (northing, easting)\n */\nexport function addMetersToLngLat(lngLatZ: number[], xyz: number[]): number[] {\n const [longitude, latitude, z0] = lngLatZ;\n const [x, y, z] = xyz;\n\n // eslint-disable-next-line no-shadow\n const {unitsPerMeter, unitsPerMeter2} = getDistanceScales({\n longitude,\n latitude,\n highPrecision: true\n });\n\n const worldspace = lngLatToWorld(lngLatZ);\n worldspace[0] += x * (unitsPerMeter[0] + unitsPerMeter2[0] * y);\n worldspace[1] += y * (unitsPerMeter[1] + unitsPerMeter2[1] * y);\n\n const newLngLat = worldToLngLat(worldspace);\n const newZ = (z0 || 0) + (z || 0);\n\n return Number.isFinite(z0) || Number.isFinite(z) ? [newLngLat[0], newLngLat[1], newZ] : newLngLat;\n}\n\n/**\n *\n * view and projection matrix creation is intentionally kept compatible with\n * mapbox-gl's implementation to ensure that seamless interoperation\n * with mapbox and react-map-gl. See: https://github.com/mapbox/mapbox-gl-js\n */\nexport function getViewMatrix(options: {\n // Viewport props\n height: number;\n pitch: number;\n bearing: number;\n altitude: number;\n // Pre-calculated parameters\n scale: number;\n center?: number[];\n}): number[] {\n const {\n // Viewport props\n height,\n pitch,\n bearing,\n altitude,\n // Pre-calculated parameters\n scale,\n center\n } = options;\n // VIEW MATRIX: PROJECTS MERCATOR WORLD COORDINATES\n // Note that mercator world coordinates typically need to be flipped\n //\n // Note: As usual, matrix operation orders should be read in reverse\n // since vectors will be multiplied from the right during transformation\n const vm = createMat4();\n\n // Move camera to altitude (along the pitch & bearing direction)\n mat4.translate(vm, vm, [0, 0, -altitude]);\n\n // Rotate by bearing, and then by pitch (which tilts the view)\n mat4.rotateX(vm, vm, -pitch * DEGREES_TO_RADIANS);\n mat4.rotateZ(vm, vm, bearing * DEGREES_TO_RADIANS);\n\n const relativeScale = scale / height;\n mat4.scale(vm, vm, [relativeScale, relativeScale, relativeScale]);\n\n if (center) {\n mat4.translate(vm, vm, vec3.negate([], center));\n }\n\n return vm;\n}\n\n/**\n * Calculates mapbox compatible projection matrix from parameters\n *\n * @param options.width Width of \"viewport\" or window\n * @param options.height Height of \"viewport\" or window\n * @param options.scale Scale at the current zoom\n * @param options.center Offset of the target, vec3 in world space\n * @param options.offset Offset of the focal point, vec2 in screen space\n * @param options.pitch Camera angle in degrees (0 is straight down)\n * @param options.fovy field of view in degrees\n * @param options.altitude if provided, field of view is calculated using `altitudeToFovy()`\n * @param options.nearZMultiplier control z buffer\n * @param options.farZMultiplier control z buffer\n * @returns project parameters object\n */\nexport function getProjectionParameters(options: {\n width: number;\n height: number;\n scale?: number;\n center?: number[];\n offset?: [number, number];\n fovy?: number;\n altitude?: number;\n pitch?: number;\n nearZMultiplier?: number;\n farZMultiplier?: number;\n}): ProjectionParameters {\n const {\n width,\n height,\n altitude,\n pitch = 0,\n offset,\n center,\n scale,\n nearZMultiplier = 1,\n farZMultiplier = 1\n } = options;\n let {fovy = altitudeToFovy(DEFAULT_ALTITUDE)} = options;\n\n // For back-compatibility allow field of view to be\n // derived from altitude\n if (altitude !== undefined) {\n fovy = altitudeToFovy(altitude);\n }\n\n const fovRadians = fovy * DEGREES_TO_RADIANS;\n const pitchRadians = pitch * DEGREES_TO_RADIANS;\n\n // Distance from camera to the target\n const focalDistance = fovyToAltitude(fovy);\n\n let cameraToSeaLevelDistance = focalDistance;\n\n if (center) {\n cameraToSeaLevelDistance += (center[2] * scale) / Math.cos(pitchRadians) / height;\n }\n\n const fovAboveCenter = fovRadians * (0.5 + (offset ? offset[1] : 0) / height);\n\n // Find the distance from the center point to the center top\n // in focal distance units using law of sines.\n const topHalfSurfaceDistance =\n (Math.sin(fovAboveCenter) * cameraToSeaLevelDistance) /\n Math.sin(clamp(Math.PI / 2 - pitchRadians - fovAboveCenter, 0.01, Math.PI - 0.01));\n\n // Calculate z distance of the farthest fragment that should be rendered.\n const furthestDistance =\n Math.sin(pitchRadians) * topHalfSurfaceDistance + cameraToSeaLevelDistance;\n // Matches mapbox limit\n const horizonDistance = cameraToSeaLevelDistance * 10;\n\n // Calculate z value of the farthest fragment that should be rendered.\n const farZ = Math.min(furthestDistance * farZMultiplier, horizonDistance);\n\n return {\n fov: fovRadians,\n aspect: width / height,\n focalDistance,\n near: nearZMultiplier,\n far: farZ\n };\n}\n\n/**\n * CALCULATE PROJECTION MATRIX: PROJECTS FROM CAMERA (VIEW) SPACE TO CLIPSPACE\n *\n * To match mapbox's z buffer:\n * - \\<= 0.28: nearZMultiplier: 0.1, farZmultiplier: 1\n * - \\>= 0.29: nearZMultiplier: 1 / height, farZMultiplier: 1.01\n *\n * @param options Viewport options\n * @param options.width Width of \"viewport\" or window\n * @param options.height Height of \"viewport\" or window\n * @param options.scale Scale at the current zoom\n * @param options.center Offset of the target, vec3 in world space\n * @param options.offset Offset of the focal point, vec2 in screen space\n * @param options.pitch Camera angle in degrees (0 is straight down)\n * @param options.fovy field of view in degrees\n * @param options.altitude if provided, field of view is calculated using `altitudeToFovy()`\n * @param options.nearZMultiplier control z buffer\n * @param options.farZMultiplier control z buffer\n * @returns 4x4 projection matrix\n */\nexport function getProjectionMatrix(options: {\n width: number;\n height: number;\n pitch: number;\n scale?: number;\n center?: number[];\n offset?: [number, number];\n fovy?: number;\n altitude?: number;\n nearZMultiplier: number;\n farZMultiplier: number;\n}): number[] {\n const {fov, aspect, near, far} = getProjectionParameters(options);\n\n const projectionMatrix = mat4.perspective(\n [] as number[],\n fov, // fov in radians\n aspect, // aspect ratio\n near, // near plane\n far // far plane\n );\n\n return projectionMatrix;\n}\n\n/**\n *\n * Convert an altitude to field of view such that the\n * focal distance is equal to the altitude\n *\n * @param altitude - altitude of camera in screen units\n * @return fovy field of view in degrees\n */\nexport function altitudeToFovy(altitude: number): number {\n return 2 * Math.atan(0.5 / altitude) * RADIANS_TO_DEGREES;\n}\n\n/**\n *\n * Convert an field of view such that the\n * focal distance is equal to the altitude\n *\n * @param fovy - field of view in degrees\n * @return altitude altitude of camera in screen units\n */\nexport function fovyToAltitude(fovy: number): number {\n return 0.5 / Math.tan(0.5 * fovy * DEGREES_TO_RADIANS);\n}\n\n/**\n * Project flat coordinates to pixels on screen.\n *\n * @param xyz - flat coordinate on 512*512 Mercator Zoom 0 tile\n * @param pixelProjectionMatrix - projection matrix 4x4\n * @return [x, y, depth] pixel coordinate on screen.\n */\nexport function worldToPixels(xyz: number[], pixelProjectionMatrix: number[]): number[];\n\n// Project flat coordinates to pixels on screen.\nexport function worldToPixels(xyz: number[], pixelProjectionMatrix: number[]): number[] {\n const [x, y, z = 0] = xyz;\n assert(Number.isFinite(x) && Number.isFinite(y) && Number.isFinite(z));\n\n return transformVector(pixelProjectionMatrix, [x, y, z, 1]);\n}\n\n/**\n * Unproject pixels on screen to flat coordinates.\n *\n * @param xyz - pixel coordinate on screen.\n * @param pixelUnprojectionMatrix - unprojection matrix 4x4\n * @param targetZ - if pixel coordinate does not have a 3rd component (depth),\n * targetZ is used as the elevation plane to unproject onto\n * @return [x, y, Z] flat coordinates on 512*512 Mercator Zoom 0 tile.\n */\nexport function pixelsToWorld(\n xyz: number[],\n pixelUnprojectionMatrix: number[],\n targetZ: number = 0\n): number[] {\n const [x, y, z] = xyz;\n assert(Number.isFinite(x) && Number.isFinite(y), 'invalid pixel coordinate');\n\n if (Number.isFinite(z)) {\n // Has depth component\n const coord = transformVector(pixelUnprojectionMatrix, [x, y, z, 1]);\n return coord;\n }\n\n // since we don't know the correct projected z value for the point,\n // unproject two points to get a line and then find the point on that line with z=0\n const coord0 = transformVector(pixelUnprojectionMatrix, [x, y, 0, 1]);\n const coord1 = transformVector(pixelUnprojectionMatrix, [x, y, 1, 1]);\n\n const z0 = coord0[2];\n const z1 = coord1[2];\n\n const t = z0 === z1 ? 0 : ((targetZ || 0) - z0) / (z1 - z0);\n return vec2.lerp([] as number[], coord0, coord1, t);\n}\n","import {assert} from './assert';\nimport {log2, clamp} from './math-utils';\nimport {MAX_LATITUDE, lngLatToWorld, worldToLngLat} from './web-mercator-utils';\n\n/**\n * Options for fitBounds\n */\nexport type FitBoundsOptions = {\n /** viewport width */\n width: number;\n /** viewport height */\n height: number;\n /** [[lon, lat], [lon, lat]] */\n bounds: [[number, number], [number, number]];\n /** The width/height of the bounded area will never be smaller than this. 0.01 would be about 1000 meters (degree is ~110KM) */\n minExtent?: number;\n /** The maximum zoom level to fit the bounds within. */\n maxZoom?: number; // ~x4,000,000 => About 10 meter extents\n /**\n * padding - The amount of padding in pixels to add to the given bounds.\n * Can also be an object with top, bottom, left and right properties defining the padding.\n */\n padding?: number | Padding;\n /** The center of the given bounds relative to the map's center, */\n offset?: number[];\n};\n\n/**\n * An object describing the padding to add to the bounds.\n */\nexport type Padding = {\n /** Padding from top in pixels to add to the given bounds */\n top: number;\n /** Padding from bottom in pixels to add to the given bounds */\n bottom: number;\n /** Padding from left in pixels to add to the given bounds */\n left: number;\n /** Padding from right in pixels to add to the given bounds */\n right: number;\n};\n\ntype ViewportProps = {\n longitude: number;\n latitude: number;\n zoom: number;\n};\n\n/**\n * Returns map settings {latitude, longitude, zoom}\n * that will contain the provided corners within the provided width.\n *\n * > _Note: Only supports non-perspective mode._\n *\n * @param options fit bounds parameters\n * @returns - latitude, longitude and zoom\n */\nexport function fitBounds(options: FitBoundsOptions): ViewportProps {\n const {\n width,\n height,\n bounds,\n minExtent = 0, // 0.01 would be about 1000 meters (degree is ~110KM)\n maxZoom = 24, // ~x4,000,000 => About 10 meter extents\n offset = [0, 0]\n } = options;\n\n const [[west, south], [east, north]] = bounds;\n const padding = getPaddingObject(options.padding);\n\n const nw = lngLatToWorld([west, clamp(north, -MAX_LATITUDE, MAX_LATITUDE)]);\n const se = lngLatToWorld([east, clamp(south, -MAX_LATITUDE, MAX_LATITUDE)]);\n\n // width/height on the Web Mercator plane\n const size = [\n Math.max(Math.abs(se[0] - nw[0]), minExtent),\n Math.max(Math.abs(se[1] - nw[1]), minExtent)\n ];\n\n const targetSize = [\n width - padding.left - padding.right - Math.abs(offset[0]) * 2,\n height - padding.top - padding.bottom - Math.abs(offset[1]) * 2\n ];\n\n assert(targetSize[0] > 0 && targetSize[1] > 0);\n\n // scale = screen pixels per unit on the Web Mercator plane\n const scaleX = targetSize[0] / size[0];\n const scaleY = targetSize[1] / size[1];\n\n // Find how much we need to shift the center\n const offsetX = (padding.right - padding.left) / 2 / scaleX;\n const offsetY = (padding.top - padding.bottom) / 2 / scaleY;\n\n const center = [(se[0] + nw[0]) / 2 + offsetX, (se[1] + nw[1]) / 2 + offsetY];\n\n const centerLngLat = worldToLngLat(center);\n const zoom = Math.min(maxZoom, log2(Math.abs(Math.min(scaleX, scaleY))));\n\n assert(Number.isFinite(zoom));\n\n return {\n longitude: centerLngLat[0],\n latitude: centerLngLat[1],\n zoom\n };\n}\n\n// Helpers\nfunction getPaddingObject(padding: number | Padding = 0): Padding {\n if (typeof padding === 'number') {\n return {\n top: padding,\n bottom: padding,\n left: padding,\n right: padding\n };\n }\n\n // Make sure all the required properties are set\n assert(\n Number.isFinite(padding.top) &&\n Number.isFinite(padding.bottom) &&\n Number.isFinite(padding.left) &&\n Number.isFinite(padding.right)\n );\n\n return padding;\n}\n","/* eslint-disable camelcase */\nimport {vec2} from '@math.gl/core';\nimport type {WebMercatorViewport} from './web-mercator-viewport';\nimport {worldToLngLat} from './web-mercator-utils';\nimport {transformVector} from './math-utils';\n\nconst DEGREES_TO_RADIANS = Math.PI / 180;\n\n/*\n * Returns the quad at the intersection of the frustum and the given z plane\n * @param {WebMercatorViewport} viewport\n * @param {Number} z - elevation in meters\n */\nexport function getBounds(viewport: WebMercatorViewport, z: number = 0): number[][] {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const {width, height, unproject} = viewport;\n const unprojectOps = {targetZ: z};\n const bottomLeft = unproject([0, height], unprojectOps);\n const bottomRight = unproject([width, height], unprojectOps);\n let topLeft: number[];\n let topRight: number[];\n\n const halfFov = viewport.fovy\n ? 0.5 * viewport.fovy * DEGREES_TO_RADIANS\n : Math.atan(0.5 / viewport.altitude);\n const angleToGround = (90 - viewport.pitch) * DEGREES_TO_RADIANS;\n // The top plane is parallel to the ground if halfFov == angleToGround\n if (halfFov > angleToGround - 0.01) {\n // intersect with the far plane\n topLeft = unprojectOnFarPlane(viewport, 0, z);\n topRight = unprojectOnFarPlane(viewport, width, z);\n } else {\n // intersect with the top plane\n topLeft = unproject([0, 0], unprojectOps);\n topRight = unproject([width, 0], unprojectOps);\n }\n\n return [bottomLeft, bottomRight, topRight, topLeft];\n}\n\n/*\n * Find a point on the far clipping plane of the viewport\n * @param {WebMercatorViewport} viewport\n * @param {Number} x - projected x in screen space\n * @param {Number} targetZ - the elevation of the point in meters\n */\nfunction unprojectOnFarPlane(viewport: WebMercatorViewport, x: number, targetZ: number): number[] {\n const {pixelUnprojectionMatrix} = viewport;\n const coord0 = transformVector(pixelUnprojectionMatrix, [x, 0, 1, 1]);\n const coord1 = transformVector(pixelUnprojectionMatrix, [x, viewport.height, 1, 1]);\n\n const z = targetZ * viewport.distanceScales.unitsPerMeter[2];\n const t = (z - coord0[2]) / (coord1[2] - coord0[2]);\n const coord = vec2.lerp([], coord0, coord1, t);\n\n const result = worldToLngLat(coord);\n result.push(targetZ);\n return result;\n}\n","// View and Projection Matrix calculations for mapbox-js style map view properties\nimport {createMat4} from './math-utils';\n\nimport {\n zoomToScale,\n pixelsToWorld,\n lngLatToWorld,\n worldToLngLat,\n worldToPixels,\n altitudeToFovy,\n fovyToAltitude,\n DEFAULT_ALTITUDE,\n getProjectionMatrix,\n getDistanceScales,\n getViewMatrix,\n DistanceScales\n} from './web-mercator-utils';\nimport {fitBounds} from './fit-bounds';\nimport {getBounds} from './get-bounds';\nimport type {FitBoundsOptions} from './fit-bounds';\n\nimport {mat4, vec2, vec3} from '@math.gl/core';\n\n/**\n * @param width=1 - Width of \"viewport\" or window\n * @param height=1 - Height of \"viewport\" or window\n * @param scale=1 - Either use scale or zoom\n * @param pitch=0 - Camera angle in degrees (0 is straight down)\n * @param bearing=0 - Map rotation in degrees (0 means north is up)\n * @param fovy= - Field of view of camera in degrees\n * @param altitude= - Altitude of camera in screen units \n *\n * Web mercator projection short-hand parameters\n * @param latitude - Center of viewport on map\n * @param longitude - Center of viewport on map\n * @param zoom - Scale = Math.pow(2,zoom) on map\n\n * Notes:\n * - Only one of center or [latitude, longitude] can be specified\n * - [latitude, longitude] can only be specified when \"mercator\" is true\n * - Altitude has a default value that matches assumptions in mapbox-gl\n * - Field of view is independent from altitude, provide `altitudeToFovy(1.5)` (default value) to match assumptions in mapbox-gl\n * - width and height are forced to 1 if supplied as 0, to avoid\n * division by zero. This is intended to reduce the burden of apps to\n * to check values before instantiating a Viewport.\n */\nexport type WebMercatorViewportProps = {\n // Map state\n width: number;\n height: number;\n latitude?: number;\n longitude?: number;\n position?: number[];\n zoom?: number;\n pitch?: number;\n bearing?: number;\n altitude?: number;\n fovy?: number;\n nearZMultiplier?: number;\n farZMultiplier?: number;\n};\n\n/**\n * The WebMercatorViewport class creates\n * - view/projection matrices\n * - \"uniform values\" (for shaders) from mercator params\n *\n * Note: Instances are immutable in the sense that they only have accessors.\n * A new viewport instance should be created if any parameters have changed.\n */\nexport class WebMercatorViewport {\n readonly latitude: number;\n readonly longitude: number;\n readonly zoom: number;\n readonly pitch: number;\n readonly bearing: number;\n readonly altitude: number;\n readonly fovy: number;\n\n readonly meterOffset: number[];\n readonly center: number[];\n\n readonly width: number;\n readonly height: number;\n readonly scale: number;\n readonly distanceScales: DistanceScales;\n\n readonly viewMatrix: number[];\n readonly projectionMatrix: number[];\n\n viewProjectionMatrix: number[];\n pixelProjectionMatrix: number[];\n pixelUnprojectionMatrix: number[];\n\n /**\n * @classdesc\n * Creates view/projection matrices from mercator params\n * Note: The Viewport is immutable in the sense that it only has accessors.\n * A new viewport instance should be created if any parameters have changed.\n */\n // eslint-disable-next-line max-statements\n constructor(props: WebMercatorViewportProps = {width: 1, height: 1}) {\n let {\n // Map state\n width,\n height,\n altitude = null,\n fovy = null\n } = props;\n const {\n latitude = 0,\n longitude = 0,\n zoom = 0,\n pitch = 0,\n bearing = 0,\n position = null,\n nearZMultiplier = 0.02,\n farZMultiplier = 1.01\n } = props;\n\n // Silently allow apps to send in 0,0 to facilitate isomorphic render etc\n width = width || 1;\n height = height || 1;\n\n // `fovy` & `altitude` are independent parameters, one for the\n // projection and the latter for the view matrix. In the past,\n // the `fovy` was always derived from the `altitude`\n if (fovy === null && altitude === null) {\n altitude = DEFAULT_ALTITUDE;\n fovy = altitudeToFovy(altitude);\n } else if (fovy === null) {\n fovy = altitudeToFovy(altitude);\n } else if (altitude === null) {\n altitude = fovyToAltitude(fovy);\n }\n\n const scale = zoomToScale(zoom);\n // Altitude - prevent division by 0\n // TODO - just throw an Error instead?\n altitude = Math.max(0.75, altitude);\n\n const distanceScales = getDistanceScales({longitude, latitude});\n\n const center: number[] = lngLatToWorld([longitude, latitude]);\n center.push(0);\n\n if (position) {\n vec3.add(center, center, vec3.mul([], position, distanceScales.unitsPerMeter));\n }\n\n this.projectionMatrix = getProjectionMatrix({\n width,\n height,\n scale,\n center,\n pitch,\n fovy,\n nearZMultiplier,\n farZMultiplier\n });\n\n this.viewMatrix = getViewMatrix({\n height,\n scale,\n center,\n pitch,\n bearing,\n altitude\n });\n\n // Save parameters\n this.width = width;\n this.height = height;\n this.scale = scale;\n\n this.latitude = latitude;\n this.longitude = longitude;\n this.zoom = zoom;\n this.pitch = pitch;\n this.bearing = bearing;\n this.altitude = altitude;\n this.fovy = fovy;\n this.center = center;\n this.meterOffset = position || [0, 0, 0];\n\n this.distanceScales = distanceScales;\n\n this._initMatrices();\n\n Object.freeze(this);\n }\n\n _initMatrices(): void {\n const {width, height, projectionMatrix, viewMatrix} = this;\n\n // Note: As usual, matrix operations should be applied in \"reverse\" order\n // since vectors will be multiplied in from the right during transformation\n const vpm = createMat4();\n mat4.multiply(vpm, vpm, projectionMatrix);\n mat4.multiply(vpm, vpm, viewMatrix);\n this.viewProjectionMatrix = vpm;\n\n // Calculate matrices and scales needed for projection\n /**\n * Builds matrices that converts preprojected lngLats to screen pixels\n * and vice versa.\n * Note: Currently returns bottom-left coordinates!\n * Note: Starts with the GL projection matrix and adds steps to the\n * scale and translate that matrix onto the window.\n * Note: WebGL controls clip space to screen projection with gl.viewport\n * and does not need this step.\n */\n const m = createMat4();\n\n // matrix for conversion from location to screen coordinates\n mat4.scale(m, m, [width / 2, -height / 2, 1]);\n mat4.translate(m, m, [1, -1, 0]);\n mat4.multiply(m, m, vpm);\n\n const mInverse = mat4.invert(createMat4(), m);\n if (!mInverse) {\n throw new Error('Pixel project matrix not invertible');\n }\n\n this.pixelProjectionMatrix = m;\n this.pixelUnprojectionMatrix = mInverse;\n }\n\n /** Two viewports are equal if width and height are identical, and if\n * their view and projection matrices are (approximately) equal.\n */\n equals = (viewport: WebMercatorViewport | null): boolean => {\n if (!(viewport instanceof WebMercatorViewport)) {\n return false;\n }\n\n return (\n viewport.width === this.width &&\n viewport.height === this.height &&\n mat4.equals(viewport.projectionMatrix, this.projectionMatrix) &&\n mat4.equals(viewport.viewMatrix, this.viewMatrix)\n );\n };\n\n /**\n * Projects xyz (possibly latitude and longitude) to pixel coordinates in window\n * using viewport projection parameters\n * - [longitude, latitude] to [x, y]\n * - [longitude, latitude, Z] => [x, y, z]\n * Note: By default, returns top-left coordinates for canvas/SVG type render\n *\n * @param lngLatZ - [lng, lat] or [lng, lat, Z]\n * @param options - options\n * @param options.topLeft=true - Whether projected coords are top left\n * @return - screen coordinates [x, y] or [x, y, z], z as pixel depth\n */\n project = (lngLatZ: number[], options: {topLeft?: boolean} = {}): number[] => {\n const {topLeft = true} = options;\n const worldPosition = this.projectPosition(lngLatZ);\n const coord = worldToPixels(worldPosition, this.pixelProjectionMatrix);\n\n const [x, y] = coord;\n const y2 = topLeft ? y : this.height - y;\n return lngLatZ.length === 2 ? [x, y2] : [x, y2, coord[2]];\n };\n\n /**\n * Unproject pixel coordinates on screen onto world coordinates, possibly `[lon, lat]` on map.\n *\n * - [x, y] => [lng, lat]\n * - [x, y, z] => [lng, lat, Z]\n *\n * @param xyz - screen coordinates, z as pixel depth\n * @param options - options\n * @param options.topLeft=true - Whether projected coords are top left\n * @param options.targetZ=0 - If pixel depth is unknown, targetZ is used as\n * the elevation plane to unproject onto\n * @return - [lng, lat, Z] or [X, Y, Z]\n */\n unproject = (xyz: number[], options: {topLeft?: boolean; targetZ?: number} = {}): number[] => {\n const {topLeft = true, targetZ = undefined} = options;\n const [x, y, z] = xyz;\n\n const y2 = topLeft ? y : this.height - y;\n const targetZWorld = targetZ && targetZ * this.distanceScales.unitsPerMeter[2];\n const coord = pixelsToWorld([x, y2, z], this.pixelUnprojectionMatrix, targetZWorld);\n const [X, Y, Z] = this.unprojectPosition(coord);\n\n if (Number.isFinite(z)) {\n return [X, Y, Z];\n }\n return Number.isFinite(targetZ) ? [X, Y, targetZ] : [X, Y];\n };\n\n // NON_LINEAR PROJECTION HOOKS\n // Used for web meractor projection\n\n projectPosition = (xyz: number[]): [number, number, number] => {\n const [X, Y] = lngLatToWorld(xyz);\n const Z = (xyz[2] || 0) * this.distanceScales.unitsPerMeter[2];\n return [X, Y, Z];\n };\n\n unprojectPosition = (xyz: number[]): [number, number, number] => {\n const [X, Y] = worldToLngLat(xyz);\n const Z = (xyz[2] || 0) * this.distanceScales.metersPerUnit[2];\n return [X, Y, Z];\n };\n\n /**\n * Project [lng,lat] on sphere onto [x,y] on 512*512 Mercator Zoom 0 tile.\n * Performs the nonlinear part of the web mercator projection.\n * Remaining projection is done with 4x4 matrices which also handles\n * perspective.\n *\n * @param lngLat - [lng, lat] coordinates\n * Specifies a point on the sphere to project onto the map.\n * @return [x,y] coordinates.\n */\n projectFlat(lngLat: number[]): number[] {\n return lngLatToWorld(lngLat);\n }\n\n /**\n * Unproject world point [x,y] on map onto {lat, lon} on sphere\n *\n * @param xy - array with [x,y] members\n * representing point on projected map plane\n * @return - array with [lat,lon] of point on sphere.\n * Has toArray method if you need a GeoJSON Array.\n * Per cartographic tradition, lat and lon are specified as degrees.\n */\n unprojectFlat(xy: number[]): number[] {\n return worldToLngLat(xy);\n }\n\n /**\n * Get the map center that place a given [lng, lat] coordinate at screen point [x, y]\n * @param opt\n * @param opt.lngLat - [lng,lat] coordinates\n * Specifies a point on the sphere.\n * @param opt.pos - [x,y] coordinates\n * Specifies a point on the screen.\n * @return [lng,lat] new map center.\n */\n getMapCenterByLngLatPosition({lngLat, pos}: {lngLat: number[]; pos: number[]}): number[] {\n const fromLocation = pixelsToWorld(pos, this.pixelUnprojectionMatrix);\n const toLocation = lngLatToWorld(lngLat);\n const translate = vec2.add([], toLocation, vec2.negate([], fromLocation));\n const newCenter = vec2.add([], this.center, translate);\n return worldToLngLat(newCenter);\n }\n\n /**\n * Returns a new viewport that fit around the given rectangle.\n * Only supports non-perspective mode.\n * @param bounds - [[lon, lat], [lon, lat]]\n * @param [options]\n * @param [options.padding] - The amount of padding in pixels to add to the given bounds.\n * @param [options.offset] - The center of the given bounds relative to the map's center,\n * [x, y] measured in pixels.\n * @returns {WebMercatorViewport}\n */\n fitBounds(\n bounds: [[number, number], [number, number]],\n options: Omit = {}\n ): WebMercatorViewport {\n const {width, height} = this;\n const {longitude, latitude, zoom} = fitBounds(Object.assign({width, height, bounds}, options));\n return new WebMercatorViewport({width, height, longitude, latitude, zoom});\n }\n\n /**\n * Returns the bounding box of the viewport.\n * @param [options]\n * @param [options.z] - The altitude at which the bounds should be calculated.\n * @returns {Array} bounds - [[lon, lat], [lon, lat]]\n */\n getBounds(options?: {z?: number}): number[][] {\n const corners = this.getBoundingRegion(options);\n\n const west = Math.min(...corners.map((p) => p[0]));\n const east = Math.max(...corners.map((p) => p[0]));\n const south = Math.min(...corners.map((p) => p[1]));\n const north = Math.max(...corners.map((p) => p[1]));\n return [\n [west, south],\n [east, north]\n ];\n }\n\n /**\n * Returns the bounding box of the viewport.\n * @param [options]\n * @param [options.z] - The altitude at which the bounds should be calculated.\n * @returns {Array} an array of 4 points that define the visible region\n */\n getBoundingRegion(options: {z?: number} = {}): number[][] {\n return getBounds(this, options.z || 0);\n }\n\n // DEPRECATED\n\n /** @deprecated Legacy method name */\n getLocationAtPoint({lngLat, pos}: {lngLat: number[]; pos: number[]}): number[] {\n return this.getMapCenterByLngLatPosition({lngLat, pos});\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {COORDINATE_SYSTEM, PROJECTION_MODE} from '../../lib/constants';\nimport project from '../project/project';\nimport {Vector3, Matrix4} from '@math.gl/core';\nimport type {NumericArray} from '@math.gl/core';\nimport memoize from '../../utils/memoize';\nimport {pixelsToWorld} from '@math.gl/web-mercator';\n\nimport type {Texture} from '@luma.gl/core';\nimport {ShaderModule} from '@luma.gl/shadertools';\nimport type Viewport from '../../viewports/viewport';\nimport {\n ProjectProps,\n ProjectUniforms,\n getShaderCoordinateSystem\n} from '../project/viewport-uniforms';\n\nconst uniformBlock = /* glsl */ `\nlayout(std140) uniform shadowUniforms {\n bool drawShadowMap;\n bool useShadowMap;\n vec4 color;\n highp int lightId;\n float lightCount;\n mat4 viewProjectionMatrix0;\n mat4 viewProjectionMatrix1;\n vec4 projectCenter0;\n vec4 projectCenter1;\n} shadow;\n`;\n\nconst vertex = /* glsl */ `\nconst int max_lights = 2;\n\nout vec3 shadow_vPosition[max_lights];\n\nvec4 shadow_setVertexPosition(vec4 position_commonspace) {\n mat4 viewProjectionMatrices[max_lights];\n viewProjectionMatrices[0] = shadow.viewProjectionMatrix0;\n viewProjectionMatrices[1] = shadow.viewProjectionMatrix1;\n vec4 projectCenters[max_lights];\n projectCenters[0] = shadow.projectCenter0;\n projectCenters[1] = shadow.projectCenter1;\n\n if (shadow.drawShadowMap) {\n return project_common_position_to_clipspace(position_commonspace, viewProjectionMatrices[shadow.lightId], projectCenters[shadow.lightId]);\n }\n if (shadow.useShadowMap) {\n for (int i = 0; i < max_lights; i++) {\n if(i < int(shadow.lightCount)) {\n vec4 shadowMap_position = project_common_position_to_clipspace(position_commonspace, viewProjectionMatrices[i], projectCenters[i]);\n shadow_vPosition[i] = (shadowMap_position.xyz / shadowMap_position.w + 1.0) / 2.0;\n }\n }\n }\n return gl_Position;\n}\n`;\n\nconst vs = `\n${uniformBlock}\n${vertex}\n`;\n\nconst fragment = /* glsl */ `\nconst int max_lights = 2;\nuniform sampler2D shadow_uShadowMap0;\nuniform sampler2D shadow_uShadowMap1;\n\nin vec3 shadow_vPosition[max_lights];\n\nconst vec4 bitPackShift = vec4(1.0, 255.0, 65025.0, 16581375.0);\nconst vec4 bitUnpackShift = 1.0 / bitPackShift;\nconst vec4 bitMask = vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0);\n\nfloat shadow_getShadowWeight(vec3 position, sampler2D shadowMap) {\n vec4 rgbaDepth = texture(shadowMap, position.xy);\n\n float z = dot(rgbaDepth, bitUnpackShift);\n return smoothstep(0.001, 0.01, position.z - z);\n}\n\nvec4 shadow_filterShadowColor(vec4 color) {\n if (shadow.drawShadowMap) {\n vec4 rgbaDepth = fract(gl_FragCoord.z * bitPackShift);\n rgbaDepth -= rgbaDepth.gbaa * bitMask;\n return rgbaDepth;\n }\n if (shadow.useShadowMap) {\n float shadowAlpha = 0.0;\n shadowAlpha += shadow_getShadowWeight(shadow_vPosition[0], shadow_uShadowMap0);\n if(shadow.lightCount > 1.0) {\n shadowAlpha += shadow_getShadowWeight(shadow_vPosition[1], shadow_uShadowMap1);\n }\n shadowAlpha *= shadow.color.a / shadow.lightCount;\n float blendedAlpha = shadowAlpha + color.a * (1.0 - shadowAlpha);\n\n return vec4(\n mix(color.rgb, shadow.color.rgb, shadowAlpha / blendedAlpha),\n blendedAlpha\n );\n }\n return color;\n}\n`;\n\nconst fs = `\n${uniformBlock}\n${fragment}\n`;\n\nconst getMemoizedViewportCenterPosition = memoize(getViewportCenterPosition);\nconst getMemoizedViewProjectionMatrices = memoize(getViewProjectionMatrices);\n\nconst DEFAULT_SHADOW_COLOR: NumberArray4 = [0, 0, 0, 1.0];\nconst VECTOR_TO_POINT_MATRIX = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0];\n\nexport type ShadowModuleProps = {\n project: ProjectProps;\n shadowEnabled?: boolean;\n drawToShadowMap?: boolean;\n shadowMaps?: Texture[];\n dummyShadowMap: Texture;\n shadowColor?: NumberArray4;\n shadowMatrices?: Matrix4[];\n shadowLightId?: number;\n};\n\ntype ShadowModuleUniforms = {\n drawShadowMap: boolean;\n useShadowMap: boolean;\n color?: NumberArray4;\n lightId?: number;\n lightCount?: number;\n viewProjectionMatrix0?: NumberArray16;\n viewProjectionMatrix1?: NumberArray16;\n projectCenter0?: NumberArray4;\n projectCenter1?: NumberArray4;\n};\n\ntype ShadowModuleBindings = {\n shadow_uShadowMap0: Texture;\n shadow_uShadowMap1: Texture;\n};\n\nfunction screenToCommonSpace(xyz: number[], pixelUnprojectionMatrix: number[]): number[] {\n const [x, y, z] = xyz;\n const coord = pixelsToWorld([x, y, z], pixelUnprojectionMatrix);\n\n if (Number.isFinite(z)) {\n return coord;\n }\n return [coord[0], coord[1], 0];\n}\n\nfunction getViewportCenterPosition({\n viewport,\n center\n}: {\n viewport: Viewport;\n center: NumericArray;\n}): NumericArray {\n return new Matrix4(viewport.viewProjectionMatrix).invert().transform(center);\n}\n\nfunction getViewProjectionMatrices({\n viewport,\n shadowMatrices\n}: {\n viewport: Viewport;\n shadowMatrices: Matrix4[];\n}): Matrix4[] {\n const projectionMatrices: Matrix4[] = [];\n const pixelUnprojectionMatrix = viewport.pixelUnprojectionMatrix;\n const farZ = viewport.isGeospatial ? undefined : 1;\n const corners = [\n [0, 0, farZ], // top left ground\n [viewport.width, 0, farZ], // top right ground\n [0, viewport.height, farZ], // bottom left ground\n [viewport.width, viewport.height, farZ], // bottom right ground\n [0, 0, -1], // top left near\n [viewport.width, 0, -1], // top right near\n [0, viewport.height, -1], // bottom left near\n [viewport.width, viewport.height, -1] // bottom right near\n ].map(pixel =>\n // @ts-expect-error z may be undefined\n screenToCommonSpace(pixel, pixelUnprojectionMatrix)\n );\n\n for (const shadowMatrix of shadowMatrices) {\n const viewMatrix = shadowMatrix.clone().translate(new Vector3(viewport.center).negate());\n const positions = corners.map(corner => viewMatrix.transform(corner));\n const projectionMatrix = new Matrix4().ortho({\n left: Math.min(...positions.map(position => position[0])),\n right: Math.max(...positions.map(position => position[0])),\n bottom: Math.min(...positions.map(position => position[1])),\n top: Math.max(...positions.map(position => position[1])),\n near: Math.min(...positions.map(position => -position[2])),\n far: Math.max(...positions.map(position => -position[2]))\n });\n projectionMatrices.push(projectionMatrix.multiplyRight(shadowMatrix));\n }\n return projectionMatrices;\n}\n\n/* eslint-disable camelcase */\n\n// eslint-disable-next-line complexity\nfunction createShadowUniforms(\n opts: Partial\n): ShadowModuleBindings & ShadowModuleUniforms {\n const {shadowEnabled = true, project: projectProps} = opts;\n if (!shadowEnabled || !projectProps || !opts.shadowMatrices || !opts.shadowMatrices.length) {\n return {\n drawShadowMap: false,\n useShadowMap: false,\n shadow_uShadowMap0: opts.dummyShadowMap!,\n shadow_uShadowMap1: opts.dummyShadowMap!\n };\n }\n const projectUniforms = project.getUniforms(projectProps) as ProjectUniforms;\n const center = getMemoizedViewportCenterPosition({\n viewport: projectProps.viewport,\n center: projectUniforms.center\n });\n\n const projectCenters: NumericArray[] = [];\n const viewProjectionMatrices = getMemoizedViewProjectionMatrices({\n shadowMatrices: opts.shadowMatrices,\n viewport: projectProps.viewport\n }).slice();\n\n for (let i = 0; i < opts.shadowMatrices.length; i++) {\n const viewProjectionMatrix = viewProjectionMatrices[i];\n const viewProjectionMatrixCentered = viewProjectionMatrix\n .clone()\n .translate(new Vector3(projectProps.viewport.center).negate());\n\n if (\n projectUniforms.coordinateSystem === getShaderCoordinateSystem('lnglat') &&\n projectUniforms.projectionMode === PROJECTION_MODE.WEB_MERCATOR\n ) {\n viewProjectionMatrices[i] = viewProjectionMatrixCentered;\n projectCenters[i] = center;\n } else {\n viewProjectionMatrices[i] = viewProjectionMatrix\n .clone()\n .multiplyRight(VECTOR_TO_POINT_MATRIX);\n projectCenters[i] = viewProjectionMatrixCentered.transform(center);\n }\n }\n\n const uniforms: ShadowModuleUniforms & ShadowModuleBindings = {\n drawShadowMap: Boolean(opts.drawToShadowMap),\n useShadowMap: opts.shadowMaps ? opts.shadowMaps.length > 0 : false,\n color: opts.shadowColor || DEFAULT_SHADOW_COLOR,\n lightId: opts.shadowLightId || 0,\n lightCount: opts.shadowMatrices.length,\n shadow_uShadowMap0: opts.dummyShadowMap!,\n shadow_uShadowMap1: opts.dummyShadowMap!\n };\n\n for (let i = 0; i < viewProjectionMatrices.length; i++) {\n uniforms[`viewProjectionMatrix${i}`] = viewProjectionMatrices[i];\n uniforms[`projectCenter${i}`] = projectCenters[i];\n }\n\n for (let i = 0; i < 2; i++) {\n uniforms[`shadow_uShadowMap${i}`] =\n (opts.shadowMaps && opts.shadowMaps[i]) || opts.dummyShadowMap;\n }\n return uniforms;\n}\n\nexport default {\n name: 'shadow',\n dependencies: [project],\n vs,\n fs,\n inject: {\n 'vs:DECKGL_FILTER_GL_POSITION': `\n position = shadow_setVertexPosition(geometry.position);\n `,\n 'fs:DECKGL_FILTER_COLOR': `\n color = shadow_filterShadowColor(color);\n `\n },\n getUniforms: createShadowUniforms,\n uniformTypes: {\n drawShadowMap: 'f32',\n useShadowMap: 'f32',\n color: 'vec4',\n lightId: 'i32',\n lightCount: 'f32',\n viewProjectionMatrix0: 'mat4x4',\n viewProjectionMatrix1: 'mat4x4',\n projectCenter0: 'vec4',\n projectCenter1: 'vec4'\n }\n} as const satisfies ShaderModule;\n\n// TODO replace with type from math.gl\ntype NumberArray4 = [number, number, number, number];\ntype NumberArray16 = [\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n number,\n number\n];\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {picking} from '@luma.gl/shadertools';\n\nconst sourceWGSL = /* wgsl */ `\\\nstruct pickingUniforms {\n isActive: f32,\n isAttribute: f32,\n isHighlightActive: f32,\n useByteColors: f32,\n highlightedObjectColor: vec3,\n highlightColor: vec4,\n};\n\n@group(0) @binding(auto) var picking: pickingUniforms;\n\nfn picking_normalizeColor(color: vec3) -> vec3 {\n return select(color, color / 255.0, picking.useByteColors > 0.5);\n}\n\nfn picking_normalizeColor4(color: vec4) -> vec4 {\n return select(color, color / 255.0, picking.useByteColors > 0.5);\n}\n\nfn picking_isColorZero(color: vec3) -> bool {\n return dot(color, vec3(1.0)) < 0.00001;\n}\n\nfn picking_isColorValid(color: vec3) -> bool {\n return dot(color, vec3(1.0)) > 0.00001;\n}\n`;\n\nexport default {\n ...picking,\n source: sourceWGSL,\n defaultUniforms: {...picking.defaultUniforms, useByteColors: true},\n inject: {\n 'vs:DECKGL_FILTER_GL_POSITION': `\n // for picking depth values\n picking_setPickingAttribute(position.z / position.w);\n `,\n 'vs:DECKGL_FILTER_COLOR': `\n picking_setPickingColor(geometry.pickingColor);\n `,\n 'fs:DECKGL_FILTER_COLOR': {\n order: 99,\n injection: `\n // use highlight color if this fragment belongs to the selected object.\n color = picking_filterHighlightColor(color);\n\n // use picking color if rendering to picking FBO.\n color = picking_filterPickingColor(color);\n `\n }\n }\n};\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {ShaderAssembler, gouraudMaterial, phongMaterial} from '@luma.gl/shadertools';\nimport {layerUniforms} from './misc/layer-uniforms';\nimport color from './color/color';\nimport geometry from './misc/geometry';\nimport project from './project/project';\nimport project32 from './project32/project32';\nimport shadow from './shadow/shadow';\nimport picking from './picking/picking';\n\nconst DEFAULT_MODULES = [geometry];\n\nconst SHADER_HOOKS_GLSL = [\n 'vs:DECKGL_FILTER_SIZE(inout vec3 size, VertexGeometry geometry)',\n 'vs:DECKGL_FILTER_GL_POSITION(inout vec4 position, VertexGeometry geometry)',\n 'vs:DECKGL_FILTER_COLOR(inout vec4 color, VertexGeometry geometry)',\n 'fs:DECKGL_FILTER_COLOR(inout vec4 color, FragmentGeometry geometry)'\n];\n\nconst SHADER_HOOKS_WGSL = [\n // Not yet supported\n];\n\nexport function getShaderAssembler(language: 'glsl' | 'wgsl'): ShaderAssembler {\n const shaderAssembler = ShaderAssembler.getDefaultShaderAssembler();\n\n for (const shaderModule of DEFAULT_MODULES) {\n shaderAssembler.addDefaultModule(shaderModule);\n }\n\n // if we're recreating the device we may have changed language\n // and must not inject hooks for the wrong language\n // shaderAssembler.resetShaderHooks();\n (shaderAssembler as any)._hookFunctions.length = 0;\n\n // Add shader hooks based on language\n // TODO(ibgreen) - should the luma shader assembler support both sets of hooks?\n const shaderHooks = language === 'glsl' ? SHADER_HOOKS_GLSL : SHADER_HOOKS_WGSL;\n for (const shaderHook of shaderHooks) {\n shaderAssembler.addShaderHook(shaderHook);\n }\n\n return shaderAssembler;\n}\n\nexport {layerUniforms, color, picking, project, project32, gouraudMaterial, phongMaterial, shadow};\n\n// Useful for custom shader modules\nexport type {ProjectProps, ProjectUniforms} from './project/viewport-uniforms';\n\n// TODO - these should be imported from luma.gl\n/* eslint-disable camelcase */\nexport type PickingUniforms = {\n picking_uActive: boolean;\n picking_uAttribute: boolean;\n picking_uSelectedColor: [number, number, number];\n picking_uSelectedColorValid: boolean;\n picking_uHighlightColor: [number, number, number, number];\n};\n\nexport type LightingModuleSettings = {\n material:\n | boolean\n | {\n ambient?: number;\n diffuse?: number;\n shininess?: number;\n specularColor?: [number, number, number];\n };\n};\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nconst DEFAULT_LIGHT_COLOR = [255, 255, 255] as [number, number, number];\nconst DEFAULT_LIGHT_INTENSITY = 1.0;\n\nlet idCount = 0;\n\nexport type AmbientLightOptions = {\n id?: string;\n /** Light color, [r, g, b] in the 0-255 range\n * @default [255, 255, 255]\n */\n color?: [number, number, number];\n /** Light intensity, higher number is brighter\n * @default 1.0\n */\n intensity?: number;\n};\n\nexport class AmbientLight {\n id: string;\n color: [number, number, number];\n intensity: number;\n type = 'ambient' as const;\n\n constructor(props: AmbientLightOptions = {}) {\n const {color = DEFAULT_LIGHT_COLOR} = props;\n const {intensity = DEFAULT_LIGHT_INTENSITY} = props;\n\n this.id = props.id || `ambient-${idCount++}`;\n this.color = color;\n this.intensity = intensity;\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Vector3} from '@math.gl/core';\nimport type Layer from '../../lib/layer';\n\nconst DEFAULT_LIGHT_COLOR = [255, 255, 255] as [number, number, number];\nconst DEFAULT_LIGHT_INTENSITY = 1.0;\nconst DEFAULT_LIGHT_DIRECTION = [0.0, 0.0, -1.0] as [number, number, number];\n\nlet idCount = 0;\n\nexport type DirectionalLightOptions = {\n id?: string;\n /** Light color, [r, g, b] in the 0-255 range\n * @default [255, 255, 255]\n */\n color?: [number, number, number];\n /** Light intensity, higher number is brighter\n * @default 1.0\n */\n intensity?: number;\n /** Light direction in the common space\n * @default [0.0, 0.0, -1.0]\n */\n direction?: [number, number, number];\n /** (Experimental) render shadows cast by this light\n * @default false\n */\n _shadow?: boolean;\n};\n\nexport class DirectionalLight {\n id: string;\n color: [number, number, number];\n intensity: number;\n type = 'directional' as const;\n direction: [number, number, number];\n shadow: boolean;\n\n constructor(props: DirectionalLightOptions = {}) {\n const {color = DEFAULT_LIGHT_COLOR} = props;\n const {intensity = DEFAULT_LIGHT_INTENSITY} = props;\n const {direction = DEFAULT_LIGHT_DIRECTION} = props;\n const {_shadow = false} = props;\n\n this.id = props.id || `directional-${idCount++}`;\n this.color = color;\n this.intensity = intensity;\n this.type = 'directional';\n this.direction = new Vector3(direction).normalize().toArray() as [number, number, number];\n this.shadow = _shadow;\n }\n\n getProjectedLight(opts: {layer: Layer}): DirectionalLight {\n return this;\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '@luma.gl/core';\n\n/**\n * Base class for passes\n * @todo v9 - should the luma.gl RenderPass be owned by this class?\n * Currently owned by subclasses\n */\nexport default class Pass {\n /** string id, mainly for debugging */\n id: string;\n /** The luma.gl Device that this pass is associated with */\n device: Device;\n /** TODO v9 - inject prop types from parent */\n props: any;\n\n /** Create a new Pass instance */\n constructor(device: Device, props: {id: string} = {id: 'pass'}) {\n const {id} = props;\n this.id = id; // id of this pass\n this.device = device;\n this.props = {...props};\n }\n\n setProps(props): void {\n Object.assign(this.props, props);\n }\n\n render(params): void {} // eslint-disable-line @typescript-eslint/no-empty-function\n\n cleanup() {} // eslint-disable-line @typescript-eslint/no-empty-function\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {\n Device,\n Parameters,\n RenderPassParameters,\n RenderPipelineParameters\n} from '@luma.gl/core';\nimport type {Framebuffer, RenderPass} from '@luma.gl/core';\nimport type {NumberArray4} from '@math.gl/core';\n\nimport Pass from './pass';\nimport type Viewport from '../viewports/viewport';\nimport type View from '../views/view';\nimport type Layer from '../lib/layer';\nimport type {Effect} from '../lib/effect';\nimport type {ProjectProps} from '../shaderlib/project/viewport-uniforms';\nimport type {PickingProps} from '@luma.gl/shadertools';\n\nexport type Rect = {x: number; y: number; width: number; height: number};\n\n// WebGPU complication: Matching attachment state of the renderpass requires including a depth buffer\nconst WEBGPU_DEFAULT_DRAW_PARAMETERS: RenderPipelineParameters = {\n depthWriteEnabled: true,\n depthCompare: 'less-equal',\n blendColorOperation: 'add',\n blendColorSrcFactor: 'src-alpha',\n blendColorDstFactor: 'one',\n blendAlphaOperation: 'add',\n blendAlphaSrcFactor: 'one-minus-dst-alpha',\n blendAlphaDstFactor: 'one'\n};\n\nexport type LayersPassRenderOptions = {\n /** @deprecated TODO v9 recommend we rename this to framebuffer to minimize confusion */\n target?: Framebuffer | null;\n isPicking?: boolean;\n pass: string;\n layers: Layer[];\n viewports: Viewport[];\n onViewportActive?: (viewport: Viewport) => void;\n cullRect?: Rect;\n views?: Record;\n effects?: Effect[];\n /** If true, recalculates render index (z) from 0. Set to false if a stack of layers are rendered in multiple passes. */\n clearStack?: boolean;\n clearCanvas?: boolean;\n clearColor?: number[];\n colorMask?: number;\n scissorRect?: number[];\n layerFilter?: ((context: FilterContext) => boolean) | null;\n shaderModuleProps?: any;\n /** Stores returned results from Effect.preRender, for use downstream in the render pipeline */\n preRenderStats?: Record;\n};\n\nexport type DrawLayerParameters = {\n shouldDrawLayer: boolean;\n layerRenderIndex: number;\n shaderModuleProps: any;\n layerParameters: Parameters;\n};\n\nexport type FilterContext = {\n layer: Layer;\n viewport: Viewport;\n isPicking: boolean;\n renderPass: string;\n cullRect?: Rect;\n};\n\nexport type RenderStats = {\n totalCount: number;\n visibleCount: number;\n compositeCount: number;\n pickableCount: number;\n};\n\n/** A Pass that renders all layers */\nexport default class LayersPass extends Pass {\n _lastRenderIndex: number = -1;\n\n render(options: LayersPassRenderOptions): void {\n this._render(options);\n }\n\n protected _render(options: LayersPassRenderOptions): RenderStats[] {\n const canvasContext = this.device.canvasContext!;\n const framebuffer = options.target ?? canvasContext.getCurrentFramebuffer();\n const [width, height] = canvasContext.getDrawingBufferSize();\n\n // Explicitly specify clearColor and clearDepth, overriding render pass defaults.\n const clearCanvas = options.clearCanvas ?? true;\n const clearColor = options.clearColor ?? (clearCanvas ? [0, 0, 0, 0] : false);\n const clearDepth = clearCanvas ? 1 : false;\n const clearStencil = clearCanvas ? 0 : false;\n const colorMask = options.colorMask ?? 0xf;\n\n const parameters: RenderPassParameters = {viewport: [0, 0, width, height]};\n if (options.colorMask) {\n parameters.colorMask = colorMask;\n }\n if (options.scissorRect) {\n parameters.scissorRect = options.scissorRect as NumberArray4;\n }\n\n const renderPass = this.device.beginRenderPass({\n framebuffer,\n parameters,\n clearColor: clearColor as NumberArray4,\n clearDepth,\n clearStencil\n });\n\n try {\n return this._drawLayers(renderPass, options);\n } finally {\n renderPass.end();\n // TODO(ibgreen): WebGPU - submit may not be needed here but initial port had issues with out of render loop rendering\n this.device.submit();\n }\n }\n\n /** Draw a list of layers in a list of viewports */\n private _drawLayers(renderPass: RenderPass, options: LayersPassRenderOptions) {\n const {\n target,\n shaderModuleProps,\n viewports,\n views,\n onViewportActive,\n clearStack = true\n } = options;\n options.pass = options.pass || 'unknown';\n\n if (clearStack) {\n this._lastRenderIndex = -1;\n }\n\n const renderStats: RenderStats[] = [];\n\n for (const viewport of viewports) {\n const view = views && views[viewport.id];\n\n // Update context to point to this viewport\n onViewportActive?.(viewport);\n\n const drawLayerParams = this._getDrawLayerParams(viewport, options);\n\n // render this viewport\n const subViewports = viewport.subViewports || [viewport];\n for (const subViewport of subViewports) {\n const stats = this._drawLayersInViewport(\n renderPass,\n {\n target,\n shaderModuleProps,\n viewport: subViewport,\n view,\n pass: options.pass,\n layers: options.layers\n },\n drawLayerParams\n );\n renderStats.push(stats);\n }\n }\n return renderStats;\n }\n\n // When a viewport contains multiple subviewports (e.g. repeated web mercator map),\n // this is only done once for the parent viewport\n /* Resolve the parameters needed to draw each layer */\n protected _getDrawLayerParams(\n viewport: Viewport,\n {\n layers,\n pass,\n isPicking = false,\n layerFilter,\n cullRect,\n effects,\n shaderModuleProps\n }: LayersPassRenderOptions,\n /** Internal flag, true if only used to determine whether each layer should be drawn */\n evaluateShouldDrawOnly: boolean = false\n ): DrawLayerParameters[] {\n const drawLayerParams: DrawLayerParameters[] = [];\n const indexResolver = layerIndexResolver(this._lastRenderIndex + 1);\n const drawContext: FilterContext = {\n layer: layers[0],\n viewport,\n isPicking,\n renderPass: pass,\n cullRect\n };\n const layerFilterCache = {};\n for (let layerIndex = 0; layerIndex < layers.length; layerIndex++) {\n const layer = layers[layerIndex];\n // Check if we should draw layer\n const shouldDrawLayer = this._shouldDrawLayer(\n layer,\n drawContext,\n layerFilter,\n layerFilterCache\n );\n\n const layerParam = {shouldDrawLayer} as DrawLayerParameters;\n\n if (shouldDrawLayer && !evaluateShouldDrawOnly) {\n layerParam.shouldDrawLayer = true;\n\n // This is the \"logical\" index for ordering this layer in the stack\n // used to calculate polygon offsets\n // It can be the same as another layer\n layerParam.layerRenderIndex = indexResolver(layer, shouldDrawLayer);\n\n layerParam.shaderModuleProps = this._getShaderModuleProps(\n layer,\n effects,\n pass,\n shaderModuleProps\n );\n const defaultParams =\n layer.context.device.type === 'webgpu' ? WEBGPU_DEFAULT_DRAW_PARAMETERS : null;\n layerParam.layerParameters = {\n ...defaultParams,\n ...layer.context.deck?.props.parameters,\n ...this.getLayerParameters(layer, layerIndex, viewport)\n };\n }\n\n drawLayerParams[layerIndex] = layerParam;\n }\n return drawLayerParams;\n }\n\n // Draws a list of layers in one viewport\n // TODO - when picking we could completely skip rendering viewports that dont\n // intersect with the picking rect\n /* eslint-disable max-depth, max-statements, complexity */\n private _drawLayersInViewport(\n renderPass: RenderPass,\n {\n layers,\n shaderModuleProps: globalModuleParameters,\n pass,\n target,\n viewport,\n view\n }: {\n layers: Layer[];\n shaderModuleProps: Record;\n pass: string;\n target?: Framebuffer | null;\n viewport: Viewport;\n view?: View;\n },\n drawLayerParams: DrawLayerParameters[]\n ): RenderStats {\n const glViewport = getGLViewport(this.device, {\n shaderModuleProps: globalModuleParameters,\n target,\n viewport\n });\n\n if (view) {\n const {clear, clearColor, clearDepth, clearStencil} = view.props;\n if (clear) {\n // If clear option is set, clear all buffers by default.\n let colorToUse: NumberArray4 | false = [0, 0, 0, 0];\n let depthToUse: number | false = 1.0;\n let stencilToUse: number | false = 0;\n\n if (Array.isArray(clearColor)) {\n colorToUse = [...clearColor.slice(0, 3), clearColor[3] || 255].map(\n c => c / 255\n ) as NumberArray4;\n } else if (clearColor === false) {\n colorToUse = false;\n }\n\n if (clearDepth !== undefined) {\n depthToUse = clearDepth;\n }\n\n if (clearStencil !== undefined) {\n stencilToUse = clearStencil;\n }\n\n const clearRenderPass = this.device.beginRenderPass({\n framebuffer: target,\n parameters: {\n viewport: glViewport,\n scissorRect: glViewport\n },\n clearColor: colorToUse,\n clearDepth: depthToUse,\n clearStencil: stencilToUse\n });\n clearRenderPass.end();\n }\n }\n\n // render layers in normal colors\n const renderStatus = {\n totalCount: layers.length,\n visibleCount: 0,\n compositeCount: 0,\n pickableCount: 0\n };\n\n renderPass.setParameters({viewport: glViewport});\n\n // render layers in normal colors\n for (let layerIndex = 0; layerIndex < layers.length; layerIndex++) {\n const layer = layers[layerIndex];\n const drawLayerParameters = drawLayerParams[layerIndex];\n const {shouldDrawLayer} = drawLayerParameters;\n\n // Calculate stats\n if (shouldDrawLayer && layer.props.pickable) {\n renderStatus.pickableCount++;\n }\n if (layer.isComposite) {\n renderStatus.compositeCount++;\n }\n if (layer.isDrawable && drawLayerParameters.shouldDrawLayer) {\n const {layerRenderIndex, shaderModuleProps, layerParameters} = drawLayerParameters;\n // Draw the layer\n renderStatus.visibleCount++;\n\n this._lastRenderIndex = Math.max(this._lastRenderIndex, layerRenderIndex);\n\n // overwrite layer.context.viewport with the sub viewport\n if (shaderModuleProps.project) {\n shaderModuleProps.project.viewport = viewport;\n }\n\n // TODO v9 - we are sending renderPass both as a parameter and through the context.\n // Long-term, it is likely better not to have user defined layer methods have to access\n // the \"global\" layer context.\n layer.context.renderPass = renderPass;\n\n try {\n layer._drawLayer({\n renderPass,\n shaderModuleProps,\n uniforms: {layerIndex: layerRenderIndex},\n parameters: layerParameters\n });\n } catch (err) {\n layer.raiseError(err as Error, `drawing ${layer} to ${pass}`);\n }\n }\n }\n\n return renderStatus;\n }\n /* eslint-enable max-depth, max-statements */\n\n /* Methods for subclass overrides */\n shouldDrawLayer(layer: Layer): boolean {\n return true;\n }\n\n protected getShaderModuleProps(\n layer: Layer,\n effects: Effect[] | undefined,\n otherShaderModuleProps: Record\n ): any {\n return null;\n }\n\n protected getLayerParameters(layer: Layer, layerIndex: number, viewport: Viewport): Parameters {\n return layer.props.parameters;\n }\n\n /* Private */\n private _shouldDrawLayer(\n layer: Layer,\n drawContext: FilterContext,\n layerFilter: ((params: FilterContext) => boolean) | undefined | null,\n layerFilterCache: Record\n ) {\n const shouldDrawLayer = layer.props.visible && this.shouldDrawLayer(layer);\n\n if (!shouldDrawLayer) {\n return false;\n }\n\n drawContext.layer = layer;\n\n let parent = layer.parent;\n while (parent) {\n // @ts-ignore\n if (!parent.props.visible || !parent.filterSubLayer(drawContext)) {\n return false;\n }\n drawContext.layer = parent;\n parent = parent.parent;\n }\n\n if (layerFilter) {\n const rootLayerId = drawContext.layer.id;\n if (!(rootLayerId in layerFilterCache)) {\n layerFilterCache[rootLayerId] = layerFilter(drawContext);\n }\n if (!layerFilterCache[rootLayerId]) {\n return false;\n }\n }\n\n // If a layer is drawn, update its viewportChanged flag\n layer.activateViewport(drawContext.viewport);\n\n return true;\n }\n\n private _getShaderModuleProps(\n layer: Layer,\n effects: Effect[] | undefined,\n pass: string,\n overrides: any\n ): any {\n // @ts-expect-error TODO - assuming WebGL context\n const devicePixelRatio = this.device.canvasContext.cssToDeviceRatio();\n const layerProps = layer.internalState?.propsInTransition || layer.props;\n\n const shaderModuleProps = {\n layer: layerProps,\n picking: {\n isActive: false\n } satisfies PickingProps,\n project: {\n viewport: layer.context.viewport,\n devicePixelRatio,\n modelMatrix: layerProps.modelMatrix,\n coordinateSystem: layerProps.coordinateSystem,\n coordinateOrigin: layerProps.coordinateOrigin,\n autoWrapLongitude: layer.wrapLongitude\n } satisfies ProjectProps\n };\n\n if (effects) {\n for (const effect of effects) {\n mergeModuleParameters(\n shaderModuleProps,\n effect.getShaderModuleProps?.(layer, shaderModuleProps)\n );\n }\n }\n\n return mergeModuleParameters(\n shaderModuleProps,\n this.getShaderModuleProps(layer, effects, shaderModuleProps),\n overrides\n );\n }\n}\n\n// If the _index prop is defined, return a layer index that's relative to its parent\n// Otherwise return the index of the layer among all rendered layers\n// This is done recursively, i.e. if the user overrides a layer's default index,\n// all its descendants will be resolved relative to that index.\n// This implementation assumes that parent layers always appear before its children\n// which is true if the layer array comes from the LayerManager\nexport function layerIndexResolver(\n startIndex: number = 0,\n layerIndices: Record = {}\n): (layer: Layer, isDrawn: boolean) => number {\n const resolvers = {};\n\n const resolveLayerIndex = (layer, isDrawn) => {\n const indexOverride = layer.props._offset;\n const layerId = layer.id;\n const parentId = layer.parent && layer.parent.id;\n\n let index;\n\n if (parentId && !(parentId in layerIndices)) {\n // Populate layerIndices with the parent layer's index\n resolveLayerIndex(layer.parent, false);\n }\n\n if (parentId in resolvers) {\n const resolver = (resolvers[parentId] =\n resolvers[parentId] || layerIndexResolver(layerIndices[parentId], layerIndices));\n index = resolver(layer, isDrawn);\n resolvers[layerId] = resolver;\n } else if (Number.isFinite(indexOverride)) {\n index = indexOverride + (layerIndices[parentId] || 0);\n // Mark layer as needing its own resolver\n // We don't actually create it until it's used for the first time\n resolvers[layerId] = null;\n } else {\n index = startIndex;\n }\n\n if (isDrawn && index >= startIndex) {\n startIndex = index + 1;\n }\n\n layerIndices[layerId] = index;\n return index;\n };\n return resolveLayerIndex;\n}\n\n// Convert viewport top-left CSS coordinates to bottom up WebGL coordinates\nfunction getGLViewport(\n device: Device,\n {\n shaderModuleProps,\n target,\n viewport\n }: {\n shaderModuleProps: any;\n target?: Framebuffer | null;\n viewport: Viewport;\n }\n): [number, number, number, number] {\n const pixelRatio =\n shaderModuleProps?.project?.devicePixelRatio ??\n // @ts-expect-error TODO - assuming WebGL context\n device.canvasContext.cssToDeviceRatio();\n\n // Default framebuffer is used when writing to canvas\n // @ts-expect-error TODO - assuming WebGL context\n const [, drawingBufferHeight] = device.canvasContext.getDrawingBufferSize();\n const height = target ? target.height : drawingBufferHeight;\n\n // Convert viewport top-left CSS coordinates to bottom up WebGL coordinates\n const dimensions = viewport;\n return [\n dimensions.x * pixelRatio,\n height - (dimensions.y + dimensions.height) * pixelRatio,\n dimensions.width * pixelRatio,\n dimensions.height * pixelRatio\n ];\n}\n\nfunction mergeModuleParameters(\n target: Record,\n ...sources: Record[]\n): Record {\n for (const source of sources) {\n if (source) {\n for (const key in source) {\n if (target[key]) {\n Object.assign(target[key], source[key]);\n } else {\n target[key] = source[key];\n }\n }\n }\n }\n return target;\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Device, Framebuffer, Parameters, Texture} from '@luma.gl/core';\nimport type Layer from '../lib/layer';\nimport type Viewport from '../viewports/viewport';\nimport LayersPass from './layers-pass';\n\nexport default class ShadowPass extends LayersPass {\n fbo: Framebuffer;\n\n constructor(\n device: Device,\n props?: {\n id;\n }\n ) {\n super(device, props);\n\n // The shadowMap texture\n const shadowMap = device.createTexture({\n format: 'rgba8unorm',\n width: 1,\n height: 1,\n sampler: {\n minFilter: 'linear',\n magFilter: 'linear',\n addressModeU: 'clamp-to-edge',\n addressModeV: 'clamp-to-edge'\n }\n // TODO - texture API change in luma.gl v9.2\n // mipmaps: true\n });\n\n const depthBuffer = device.createTexture({format: 'depth16unorm', width: 1, height: 1});\n\n this.fbo = device.createFramebuffer({\n id: 'shadowmap',\n width: 1,\n height: 1,\n colorAttachments: [shadowMap],\n // Depth attachment has to be specified for depth test to work\n depthStencilAttachment: depthBuffer\n });\n }\n\n delete() {\n if (this.fbo) {\n this.fbo.destroy();\n this.fbo = null!;\n }\n }\n\n getShadowMap(): Texture {\n return this.fbo.colorAttachments[0].texture;\n }\n\n render(params) {\n const target = this.fbo;\n\n // @ts-expect-error TODO - assuming WebGL context\n const pixelRatio = this.device.canvasContext.cssToDeviceRatio();\n\n const viewport = params.viewports[0];\n const width = viewport.width * pixelRatio;\n const height = viewport.height * pixelRatio;\n const clearColor = [1, 1, 1, 1];\n if (width !== target.width || height !== target.height) {\n target.resize({width, height});\n }\n\n super.render({...params, clearColor, target, pass: 'shadow'});\n }\n\n protected getLayerParameters(\n layer: Layer<{}>,\n layerIndex: number,\n viewport: Viewport\n ): Parameters {\n return {\n ...layer.props.parameters,\n blend: false,\n depthWriteEnabled: true,\n depthCompare: 'less-equal'\n };\n }\n\n shouldDrawLayer(layer) {\n return layer.props.shadowEnabled !== false;\n }\n\n getShaderModuleProps(layer: Layer, effects: any, otherShaderModuleProps: Record) {\n return {\n shadow: {\n project: otherShaderModuleProps.project,\n drawToShadowMap: true\n }\n };\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '@luma.gl/core';\nimport {Texture} from '@luma.gl/core';\nimport {AmbientLight} from './ambient-light';\nimport {DirectionalLight} from './directional-light';\nimport {PointLight} from './point-light';\nimport {Matrix4, Vector3} from '@math.gl/core';\nimport ShadowPass from '../../passes/shadow-pass';\nimport shadow from '../../shaderlib/shadow/shadow';\n\nimport type {Light, LightingProps} from '@luma.gl/shadertools';\nimport type {ShadowModuleProps} from '../../shaderlib/shadow/shadow';\nimport type Layer from '../../lib/layer';\nimport type {Effect, EffectContext, PreRenderOptions} from '../../lib/effect';\n\nconst DEFAULT_AMBIENT_LIGHT_PROPS = {\n color: [255, 255, 255] as [number, number, number],\n intensity: 1.0\n};\nconst DEFAULT_DIRECTIONAL_LIGHT_PROPS = [\n {\n color: [255, 255, 255] as [number, number, number],\n intensity: 1.0,\n direction: [-1, 3, -1] as [number, number, number]\n },\n {\n color: [255, 255, 255] as [number, number, number],\n intensity: 0.9,\n direction: [1, -8, -2.5] as [number, number, number]\n }\n];\nconst DEFAULT_SHADOW_COLOR = [0, 0, 0, 200 / 255] as [number, number, number, number];\n\nexport type LightingEffectProps = Record;\n\n// Class to manage ambient, point and directional light sources in deck\nexport default class LightingEffect implements Effect {\n id = 'lighting-effect';\n props!: LightingEffectProps;\n shadowColor: [number, number, number, number] = DEFAULT_SHADOW_COLOR;\n context?: EffectContext;\n\n private shadow: boolean = false;\n private ambientLight?: AmbientLight;\n private directionalLights: DirectionalLight[] = [];\n private pointLights: PointLight[] = [];\n private shadowPasses: ShadowPass[] = [];\n private dummyShadowMap: Texture | null = null;\n private shadowMatrices?: Matrix4[];\n\n constructor(props: LightingEffectProps = {}) {\n this.setProps(props);\n }\n\n setup(context: EffectContext) {\n this.context = context;\n const {device, deck} = context;\n\n if (this.shadow && !this.dummyShadowMap) {\n this._createShadowPasses(device);\n\n deck._addDefaultShaderModule(shadow);\n\n this.dummyShadowMap = device.createTexture({\n width: 1,\n height: 1\n });\n }\n }\n\n setProps(props: LightingEffectProps) {\n this.ambientLight = undefined;\n this.directionalLights = [];\n this.pointLights = [];\n\n for (const key in props) {\n const lightSource = props[key];\n\n switch (lightSource.type) {\n case 'ambient':\n this.ambientLight = lightSource;\n break;\n\n case 'directional':\n this.directionalLights.push(lightSource);\n break;\n\n case 'point':\n this.pointLights.push(lightSource);\n break;\n default:\n }\n }\n this._applyDefaultLights();\n\n this.shadow = this.directionalLights.some(light => light.shadow);\n if (this.context) {\n // Create resources if necessary\n this.setup(this.context);\n }\n this.props = props;\n }\n\n preRender({layers, layerFilter, viewports, onViewportActive, views}: PreRenderOptions) {\n if (!this.shadow) return;\n\n // create light matrix every frame to make sure always updated from light source\n this.shadowMatrices = this._calculateMatrices();\n\n for (let i = 0; i < this.shadowPasses.length; i++) {\n const shadowPass = this.shadowPasses[i];\n shadowPass.render({\n layers,\n layerFilter,\n viewports,\n onViewportActive,\n views,\n shaderModuleProps: {\n shadow: {\n shadowLightId: i,\n dummyShadowMap: this.dummyShadowMap,\n shadowMatrices: this.shadowMatrices\n }\n }\n });\n }\n }\n\n getShaderModuleProps(layer: Layer, otherShaderModuleProps: Record) {\n const shadowProps = this.shadow\n ? ({\n project: otherShaderModuleProps.project,\n shadowMaps: this.shadowPasses.map(shadowPass => shadowPass.getShadowMap()),\n dummyShadowMap: this.dummyShadowMap!,\n shadowColor: this.shadowColor,\n shadowMatrices: this.shadowMatrices\n } satisfies ShadowModuleProps)\n : {};\n\n const lightingProps: LightingProps = {\n enabled: true,\n lights: this._getLights(layer)\n };\n // @ts-expect-error material is not a Layer prop\n const materialProps = layer.props.material;\n\n return {\n shadow: shadowProps,\n lighting: lightingProps,\n phongMaterial: materialProps,\n gouraudMaterial: materialProps\n };\n }\n\n cleanup(context: EffectContext): void {\n for (const shadowPass of this.shadowPasses) {\n shadowPass.delete();\n }\n this.shadowPasses.length = 0;\n\n if (this.dummyShadowMap) {\n this.dummyShadowMap.destroy();\n this.dummyShadowMap = null;\n context.deck._removeDefaultShaderModule(shadow);\n }\n }\n\n private _calculateMatrices(): Matrix4[] {\n const lightMatrices: Matrix4[] = [];\n for (const light of this.directionalLights) {\n const viewMatrix = new Matrix4().lookAt({\n eye: new Vector3(light.direction).negate()\n });\n\n lightMatrices.push(viewMatrix);\n }\n return lightMatrices;\n }\n\n private _createShadowPasses(device: Device): void {\n for (let i = 0; i < this.directionalLights.length; i++) {\n const shadowPass = new ShadowPass(device);\n this.shadowPasses[i] = shadowPass;\n }\n }\n\n private _applyDefaultLights(): void {\n const {ambientLight, pointLights, directionalLights} = this;\n if (!ambientLight && pointLights.length === 0 && directionalLights.length === 0) {\n this.ambientLight = new AmbientLight(DEFAULT_AMBIENT_LIGHT_PROPS);\n this.directionalLights.push(\n new DirectionalLight(DEFAULT_DIRECTIONAL_LIGHT_PROPS[0]),\n new DirectionalLight(DEFAULT_DIRECTIONAL_LIGHT_PROPS[1])\n );\n }\n }\n\n private _getLights(layer: Layer): Light[] {\n const lights: Light[] = [];\n\n if (this.ambientLight) {\n lights.push(this.ambientLight);\n }\n\n for (const pointLight of this.pointLights) {\n lights.push(pointLight.getProjectedLight({layer}));\n }\n\n for (const directionalLight of this.directionalLights) {\n lights.push(directionalLight.getProjectedLight({layer}));\n }\n\n return lights;\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {TypedArray, TypedArrayConstructor} from '../types/types';\n\nexport type TypedArrayManagerOptions = {\n overAlloc?: number;\n poolSize?: number;\n};\n\nexport class TypedArrayManager {\n private _pool: ArrayBuffer[] = [];\n opts: {\n overAlloc: number;\n poolSize: number;\n } = {overAlloc: 2, poolSize: 100};\n\n constructor(options: TypedArrayManagerOptions = {}) {\n this.setOptions(options);\n }\n\n setOptions(options: TypedArrayManagerOptions) {\n Object.assign(this.opts, options);\n }\n\n allocate(\n typedArray: T | null | undefined,\n count: number,\n {\n size = 1,\n type,\n padding = 0,\n copy = false,\n initialize = false,\n maxCount\n }: {\n size?: number;\n type?: TypedArrayConstructor;\n padding?: number;\n copy?: boolean;\n initialize?: boolean;\n maxCount?: number;\n }\n ): T {\n const Type =\n type || (typedArray && (typedArray.constructor as TypedArrayConstructor)) || Float32Array;\n\n const newSize = count * size + padding;\n if (ArrayBuffer.isView(typedArray)) {\n if (newSize <= typedArray.length) {\n return typedArray;\n }\n if (newSize * typedArray.BYTES_PER_ELEMENT <= typedArray.buffer.byteLength) {\n return new Type(typedArray.buffer as ArrayBuffer, 0, newSize) as T;\n }\n }\n\n let maxSize: number = Infinity;\n if (maxCount) {\n maxSize = maxCount * size + padding;\n }\n\n const newArray = this._allocate(Type, newSize, initialize, maxSize);\n\n if (typedArray && copy) {\n newArray.set(typedArray);\n } else if (!initialize) {\n // Hack - always initialize the first 4 elements. NaNs crash the Attribute validation\n newArray.fill(0, 0, 4);\n }\n\n this._release(typedArray);\n return newArray as T;\n }\n\n release(typedArray: TypedArray | null | undefined) {\n this._release(typedArray);\n }\n\n private _allocate(\n Type: TypedArrayConstructor,\n size: number,\n initialize: boolean,\n maxSize: number\n ): TypedArray {\n // Allocate at least one element to ensure a valid buffer\n let sizeToAllocate = Math.max(Math.ceil(size * this.opts.overAlloc), 1);\n // Don't over allocate after certain specified number of elements\n if (sizeToAllocate > maxSize) {\n sizeToAllocate = maxSize;\n }\n\n // Check if available in pool\n const pool = this._pool;\n const byteLength = Type.BYTES_PER_ELEMENT * sizeToAllocate;\n const i = pool.findIndex(b => b.byteLength >= byteLength);\n if (i >= 0) {\n // Create a new array using an existing buffer\n const array = new Type(pool.splice(i, 1)[0], 0, sizeToAllocate);\n if (initialize) {\n // Viewing a buffer with a different type may create NaNs\n array.fill(0);\n }\n return array;\n }\n return new Type(sizeToAllocate);\n }\n\n private _release(typedArray: TypedArray | null | undefined): void {\n if (!ArrayBuffer.isView(typedArray)) {\n return;\n }\n const pool = this._pool;\n const {buffer} = typedArray;\n // Save the buffer of the released array into the pool\n // Sort buffers by size\n // TODO - implement binary search?\n const {byteLength} = buffer;\n const i = pool.findIndex(b => b.byteLength >= byteLength);\n if (i < 0) {\n pool.push(buffer as ArrayBuffer);\n } else if (i > 0 || pool.length < this.opts.poolSize) {\n pool.splice(i, 0, buffer as ArrayBuffer);\n }\n if (pool.length > this.opts.poolSize) {\n // Drop the smallest one\n pool.shift();\n }\n }\n}\n\nexport default new TypedArrayManager();\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// Extensions to math.gl library. Intended to be folded back.\nimport typedArrayManager from './typed-array-manager';\nimport {Vector3, NumericArray} from '@math.gl/core';\n\nimport type {Matrix4} from '@math.gl/core';\n\n// Helper, avoids low-precision 32 bit matrices from gl-matrix mat4.create()\nexport function createMat4(): number[] {\n return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];\n}\n\nexport function mod(value: number, divisor: number): number {\n const modulus = value % divisor;\n return modulus < 0 ? divisor + modulus : modulus;\n}\n\n// Extract camera vectors (move to math library?)\nexport function getCameraPosition(\n viewMatrixInverse: Matrix4 | NumericArray\n): [number, number, number] {\n // Read the translation from the inverse view matrix\n return [viewMatrixInverse[12], viewMatrixInverse[13], viewMatrixInverse[14]];\n}\n\nexport function getProjectionParameters(projectionMatrix: Matrix4 | NumericArray): {\n near: number;\n far: number;\n} {\n const m22 = projectionMatrix[10];\n const m23 = projectionMatrix[14];\n return {\n near: m23 / (m22 - 1),\n far: m23 / (m22 + 1)\n };\n}\n\nexport type FrustumPlane = {\n distance: number;\n normal: Vector3;\n};\n\n// https://www.gamedevs.org/uploads/fast-extraction-viewing-frustum-planes-from-world-view-projection-matrix.pdf\nexport function getFrustumPlanes(viewProjectionMatrix: Matrix4 | NumericArray): {\n left: FrustumPlane;\n right: FrustumPlane;\n top: FrustumPlane;\n bottom: FrustumPlane;\n near: FrustumPlane;\n far: FrustumPlane;\n} {\n return {\n left: getFrustumPlane(\n viewProjectionMatrix[3] + viewProjectionMatrix[0],\n viewProjectionMatrix[7] + viewProjectionMatrix[4],\n viewProjectionMatrix[11] + viewProjectionMatrix[8],\n viewProjectionMatrix[15] + viewProjectionMatrix[12]\n ),\n right: getFrustumPlane(\n viewProjectionMatrix[3] - viewProjectionMatrix[0],\n viewProjectionMatrix[7] - viewProjectionMatrix[4],\n viewProjectionMatrix[11] - viewProjectionMatrix[8],\n viewProjectionMatrix[15] - viewProjectionMatrix[12]\n ),\n bottom: getFrustumPlane(\n viewProjectionMatrix[3] + viewProjectionMatrix[1],\n viewProjectionMatrix[7] + viewProjectionMatrix[5],\n viewProjectionMatrix[11] + viewProjectionMatrix[9],\n viewProjectionMatrix[15] + viewProjectionMatrix[13]\n ),\n top: getFrustumPlane(\n viewProjectionMatrix[3] - viewProjectionMatrix[1],\n viewProjectionMatrix[7] - viewProjectionMatrix[5],\n viewProjectionMatrix[11] - viewProjectionMatrix[9],\n viewProjectionMatrix[15] - viewProjectionMatrix[13]\n ),\n near: getFrustumPlane(\n viewProjectionMatrix[3] + viewProjectionMatrix[2],\n viewProjectionMatrix[7] + viewProjectionMatrix[6],\n viewProjectionMatrix[11] + viewProjectionMatrix[10],\n viewProjectionMatrix[15] + viewProjectionMatrix[14]\n ),\n far: getFrustumPlane(\n viewProjectionMatrix[3] - viewProjectionMatrix[2],\n viewProjectionMatrix[7] - viewProjectionMatrix[6],\n viewProjectionMatrix[11] - viewProjectionMatrix[10],\n viewProjectionMatrix[15] - viewProjectionMatrix[14]\n )\n };\n}\n\nconst scratchVector = new Vector3();\n\nfunction getFrustumPlane(a: number, b: number, c: number, d: number): FrustumPlane {\n scratchVector.set(a, b, c);\n const L = scratchVector.len();\n return {distance: d / L, normal: new Vector3(-a / L, -b / L, -c / L)};\n}\n\n/**\n * Calculate the low part of a WebGL 64 bit float\n * @param x {number} - the input float number\n * @returns {number} - the lower 32 bit of the number\n */\nexport function fp64LowPart(x: number): number {\n return x - Math.fround(x);\n}\n\nlet scratchArray;\n\n/**\n * Split a Float64Array into a double-length Float32Array\n * @param typedArray\n * @param options\n * @param options.size - per attribute size\n * @param options.startIndex - start index in the source array\n * @param options.endIndex - end index in the source array\n * @returns {} - high part, low part for each attribute:\n [1xHi, 1yHi, 1zHi, 1xLow, 1yLow, 1zLow, 2xHi, ...]\n */\nexport function toDoublePrecisionArray(\n typedArray: Float64Array,\n options: {size?: number; startIndex?: number; endIndex?: number}\n): Float32Array {\n const {size = 1, startIndex = 0} = options;\n\n const endIndex = options.endIndex !== undefined ? options.endIndex : typedArray.length;\n\n const count = (endIndex - startIndex) / size;\n scratchArray = typedArrayManager.allocate(scratchArray, count, {\n type: Float32Array,\n size: size * 2\n });\n\n let sourceIndex = startIndex;\n let targetIndex = 0;\n while (sourceIndex < endIndex) {\n for (let j = 0; j < size; j++) {\n const value = typedArray[sourceIndex++];\n scratchArray[targetIndex + j] = value;\n scratchArray[targetIndex + j + size] = fp64LowPart(value);\n }\n targetIndex += size * 2;\n }\n\n return scratchArray.subarray(0, count * size * 2);\n}\n\ntype LayerBounds = [number[], number[]];\nexport function mergeBounds(boundsList: (LayerBounds | null)[]): LayerBounds | null {\n let mergedBounds: LayerBounds | null = null;\n let isMerged = false;\n\n for (const bounds of boundsList) {\n /* eslint-disable-next-line no-continue */\n if (!bounds) continue;\n if (!mergedBounds) {\n mergedBounds = bounds;\n } else {\n if (!isMerged) {\n // Copy to avoid mutating input bounds\n mergedBounds = [\n [mergedBounds[0][0], mergedBounds[0][1]],\n [mergedBounds[1][0], mergedBounds[1][1]]\n ];\n isMerged = true;\n }\n\n mergedBounds[0][0] = Math.min(mergedBounds[0][0], bounds[0][0]);\n mergedBounds[0][1] = Math.min(mergedBounds[0][1], bounds[0][1]);\n mergedBounds[1][0] = Math.max(mergedBounds[1][0], bounds[1][0]);\n mergedBounds[1][1] = Math.max(mergedBounds[1][1], bounds[1][1]);\n }\n }\n\n return mergedBounds;\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport log from '../utils/log';\nimport {createMat4, getCameraPosition, getFrustumPlanes, FrustumPlane} from '../utils/math-utils';\n\nimport {Matrix4, Vector3, equals, clamp, mat4} from '@math.gl/core';\n\nimport {\n getDistanceScales,\n getMeterZoom,\n lngLatToWorld,\n worldToLngLat,\n worldToPixels,\n pixelsToWorld\n} from '@math.gl/web-mercator';\n\nimport {PROJECTION_MODE} from '../lib/constants';\n\nexport type DistanceScales = {\n unitsPerMeter: number[];\n metersPerUnit: number[];\n};\n\nexport type Padding = {\n left?: number;\n right?: number;\n top?: number;\n bottom?: number;\n};\n\nexport type ViewportOptions = {\n /** Name of the viewport */\n id?: string;\n /** Left offset from the canvas edge, in pixels */\n x?: number;\n /** Top offset from the canvas edge, in pixels */\n y?: number;\n /** Viewport width in pixels */\n width?: number;\n /** Viewport height in pixels */\n height?: number;\n /** Longitude in degrees (geospatial only) */\n longitude?: number;\n /** Latitude in degrees (geospatial only) */\n latitude?: number;\n /** Viewport center in world space. If geospatial, refers to meter offsets from lng, lat, elevation */\n position?: number[];\n /** Zoom level */\n zoom?: number;\n /** Padding around the viewport, in pixels. */\n padding?: Padding | null;\n distanceScales?: DistanceScales;\n /** Model matrix of viewport center */\n modelMatrix?: number[] | null;\n /** Custom view matrix */\n viewMatrix?: number[];\n /** Custom projection matrix */\n projectionMatrix?: number[];\n /** Modifier of viewport scale. Corresponds to the number of pixels per common unit at zoom 0. */\n focalDistance?: number;\n /** Use orthographic projection */\n orthographic?: boolean;\n /** fovy in radians. If supplied, overrides fovy */\n fovyRadians?: number;\n /** fovy in degrees. */\n fovy?: number;\n /** Near plane of the projection matrix */\n near?: number;\n /** Far plane of the projection matrix */\n far?: number;\n};\n\nconst DEGREES_TO_RADIANS = Math.PI / 180;\n\nconst IDENTITY = createMat4();\n\nconst ZERO_VECTOR = [0, 0, 0];\n\nconst DEFAULT_DISTANCE_SCALES: DistanceScales = {\n unitsPerMeter: [1, 1, 1],\n metersPerUnit: [1, 1, 1]\n};\n\n// / Helpers\nfunction createProjectionMatrix({\n width,\n height,\n orthographic,\n fovyRadians,\n focalDistance,\n padding,\n near,\n far\n}: {\n width: number;\n height: number;\n orthographic: boolean;\n fovyRadians: number;\n focalDistance: number;\n padding: Padding | null;\n near: number;\n far: number;\n}) {\n const aspect = width / height;\n const matrix = orthographic\n ? new Matrix4().orthographic({fovy: fovyRadians, aspect, focalDistance, near, far})\n : new Matrix4().perspective({fovy: fovyRadians, aspect, near, far});\n if (padding) {\n const {left = 0, right = 0, top = 0, bottom = 0} = padding;\n const offsetX = clamp((left + width - right) / 2, 0, width) - width / 2;\n const offsetY = clamp((top + height - bottom) / 2, 0, height) - height / 2;\n // pixels to clip space\n matrix[8] -= (offsetX * 2) / width;\n matrix[9] += (offsetY * 2) / height;\n }\n return matrix;\n}\n\n/**\n * Manages coordinate system transformations.\n *\n * Note: The Viewport is immutable in the sense that it only has accessors.\n * A new viewport instance should be created if any parameters have changed.\n */\nexport default class Viewport {\n static displayName = 'Viewport';\n\n /** Init parameters */\n\n id: string;\n x: number;\n y: number;\n width: number;\n height: number;\n padding?: Padding | null;\n isGeospatial: boolean;\n zoom: number;\n focalDistance: number;\n position: number[];\n modelMatrix: number[] | null;\n\n /** Derived parameters */\n\n // `!` post-fix expression operator asserts that its operand is non-null and non-undefined in contexts\n // where the type checker is unable to conclude that fact.\n\n distanceScales: DistanceScales; /** scale factors between world space and common space */\n scale!: number; /** scale factor, equals 2^zoom */\n center!: number[]; /** viewport center in common space */\n cameraPosition!: number[]; /** Camera position in common space */\n projectionMatrix!: number[];\n viewMatrix!: number[];\n viewMatrixUncentered!: number[];\n viewMatrixInverse!: number[];\n viewProjectionMatrix!: number[];\n pixelProjectionMatrix!: number[];\n pixelUnprojectionMatrix!: number[];\n resolution?: number;\n\n private _frustumPlanes: {[name: string]: FrustumPlane} = {};\n\n // eslint-disable-next-line complexity\n constructor(opts: ViewportOptions = {}) {\n // @ts-ignore\n this.id = opts.id || this.constructor.displayName || 'viewport';\n\n this.x = opts.x || 0;\n this.y = opts.y || 0;\n // Silently allow apps to send in w,h = 0,0\n this.width = opts.width || 1;\n this.height = opts.height || 1;\n this.zoom = opts.zoom || 0;\n this.padding = opts.padding;\n this.distanceScales = opts.distanceScales || DEFAULT_DISTANCE_SCALES;\n this.focalDistance = opts.focalDistance || 1;\n this.position = opts.position || ZERO_VECTOR;\n this.modelMatrix = opts.modelMatrix || null;\n\n const {longitude, latitude} = opts;\n this.isGeospatial = Number.isFinite(latitude) && Number.isFinite(longitude);\n\n this._initProps(opts);\n this._initMatrices(opts);\n\n // Bind methods for easy access\n this.equals = this.equals.bind(this);\n this.project = this.project.bind(this);\n this.unproject = this.unproject.bind(this);\n this.projectPosition = this.projectPosition.bind(this);\n this.unprojectPosition = this.unprojectPosition.bind(this);\n this.projectFlat = this.projectFlat.bind(this);\n this.unprojectFlat = this.unprojectFlat.bind(this);\n }\n\n get subViewports(): Viewport[] | null {\n return null;\n }\n\n get metersPerPixel(): number {\n return this.distanceScales.metersPerUnit[2] / this.scale;\n }\n\n get projectionMode(): number {\n if (this.isGeospatial) {\n return this.zoom < 12\n ? PROJECTION_MODE.WEB_MERCATOR\n : PROJECTION_MODE.WEB_MERCATOR_AUTO_OFFSET;\n }\n return PROJECTION_MODE.IDENTITY;\n }\n\n // Two viewports are equal if width and height are identical, and if\n // their view and projection matrices are (approximately) equal.\n equals(viewport: Viewport): boolean {\n if (!(viewport instanceof Viewport)) {\n return false;\n }\n if (this === viewport) {\n return true;\n }\n\n return (\n viewport.width === this.width &&\n viewport.height === this.height &&\n viewport.scale === this.scale &&\n equals(viewport.projectionMatrix, this.projectionMatrix) &&\n equals(viewport.viewMatrix, this.viewMatrix)\n );\n // TODO - check distance scales?\n }\n\n /**\n * Projects xyz (possibly latitude and longitude) to pixel coordinates in window\n * using viewport projection parameters\n * - [longitude, latitude] to [x, y]\n * - [longitude, latitude, Z] => [x, y, z]\n * Note: By default, returns top-left coordinates for canvas/SVG type render\n *\n * @param {Array} lngLatZ - [lng, lat] or [lng, lat, Z]\n * @param {Object} opts - options\n * @param {Object} opts.topLeft=true - Whether projected coords are top left\n * @return {Array} - [x, y] or [x, y, z] in top left coords\n */\n project(xyz: number[], {topLeft = true}: {topLeft?: boolean} = {}): number[] {\n const worldPosition = this.projectPosition(xyz);\n const coord = worldToPixels(worldPosition, this.pixelProjectionMatrix);\n\n const [x, y] = coord;\n const y2 = topLeft ? y : this.height - y;\n return xyz.length === 2 ? [x, y2] : [x, y2, coord[2]];\n }\n\n /**\n * Unproject pixel coordinates on screen onto world coordinates,\n * (possibly [lon, lat]) on map.\n * - [x, y] => [lng, lat]\n * - [x, y, z] => [lng, lat, Z]\n * @param {Array} xyz -\n * @param {Object} opts - options\n * @param {Object} opts.topLeft=true - Whether origin is top left\n * @return {Array|null} - [lng, lat, Z] or [X, Y, Z]\n */\n unproject(\n xyz: number[],\n {topLeft = true, targetZ}: {topLeft?: boolean; targetZ?: number} = {}\n ): number[] {\n const [x, y, z] = xyz;\n\n const y2 = topLeft ? y : this.height - y;\n const targetZWorld = targetZ && targetZ * this.distanceScales.unitsPerMeter[2];\n const coord = pixelsToWorld([x, y2, z], this.pixelUnprojectionMatrix, targetZWorld);\n const [X, Y, Z] = this.unprojectPosition(coord);\n\n if (Number.isFinite(z)) {\n return [X, Y, Z];\n }\n return Number.isFinite(targetZ) ? [X, Y, targetZ as number] : [X, Y];\n }\n\n // NON_LINEAR PROJECTION HOOKS\n // Used for web meractor projection\n\n projectPosition(xyz: number[]): [number, number, number] {\n const [X, Y] = this.projectFlat(xyz);\n const Z = (xyz[2] || 0) * this.distanceScales.unitsPerMeter[2];\n return [X, Y, Z];\n }\n\n unprojectPosition(xyz: number[]): [number, number, number] {\n const [X, Y] = this.unprojectFlat(xyz);\n const Z = (xyz[2] || 0) * this.distanceScales.metersPerUnit[2];\n return [X, Y, Z];\n }\n\n /**\n * Project [lng,lat] on sphere onto [x,y] on 512*512 Mercator Zoom 0 tile.\n * Performs the nonlinear part of the web mercator projection.\n * Remaining projection is done with 4x4 matrices which also handles\n * perspective.\n * @param {Array} lngLat - [lng, lat] coordinates\n * Specifies a point on the sphere to project onto the map.\n * @return {Array} [x,y] coordinates.\n */\n projectFlat(xyz: number[]): [number, number] {\n if (this.isGeospatial) {\n // Shader clamps latitude to +-89.9, see /shaderlib/project/project.glsl.js\n // lngLatToWorld([0, -89.9])[1] = -317.9934163758329\n // lngLatToWorld([0, 89.9])[1] = 829.9934163758271\n const result = lngLatToWorld(xyz);\n result[1] = clamp(result[1], -318, 830);\n return result;\n }\n return xyz as [number, number];\n }\n\n /**\n * Unproject world point [x,y] on map onto {lat, lon} on sphere\n * @param {object|Vector} xy - object with {x,y} members\n * representing point on projected map plane\n * @return {GeoCoordinates} - object with {lat,lon} of point on sphere.\n * Has toArray method if you need a GeoJSON Array.\n * Per cartographic tradition, lat and lon are specified as degrees.\n */\n unprojectFlat(xyz: number[]): [number, number] {\n if (this.isGeospatial) {\n return worldToLngLat(xyz);\n }\n return xyz as [number, number];\n }\n\n /**\n * Get bounds of the current viewport\n * @return {Array} - [minX, minY, maxX, maxY]\n */\n getBounds(options: {z?: number} = {}): [number, number, number, number] {\n const unprojectOption = {targetZ: options.z || 0};\n\n const topLeft = this.unproject([0, 0], unprojectOption);\n const topRight = this.unproject([this.width, 0], unprojectOption);\n const bottomLeft = this.unproject([0, this.height], unprojectOption);\n const bottomRight = this.unproject([this.width, this.height], unprojectOption);\n\n return [\n Math.min(topLeft[0], topRight[0], bottomLeft[0], bottomRight[0]),\n Math.min(topLeft[1], topRight[1], bottomLeft[1], bottomRight[1]),\n Math.max(topLeft[0], topRight[0], bottomLeft[0], bottomRight[0]),\n Math.max(topLeft[1], topRight[1], bottomLeft[1], bottomRight[1])\n ];\n }\n\n getDistanceScales(coordinateOrigin?: number[]): DistanceScales {\n if (coordinateOrigin && this.isGeospatial) {\n return getDistanceScales({\n longitude: coordinateOrigin[0],\n latitude: coordinateOrigin[1],\n highPrecision: true\n });\n }\n return this.distanceScales;\n }\n\n containsPixel({\n x,\n y,\n width = 1,\n height = 1\n }: {\n x: number;\n y: number;\n width?: number;\n height?: number;\n }): boolean {\n return (\n x < this.x + this.width &&\n this.x < x + width &&\n y < this.y + this.height &&\n this.y < y + height\n );\n }\n\n // Extract frustum planes in common space\n getFrustumPlanes(): {\n left: FrustumPlane;\n right: FrustumPlane;\n bottom: FrustumPlane;\n top: FrustumPlane;\n near: FrustumPlane;\n far: FrustumPlane;\n } {\n if (this._frustumPlanes.near) {\n // @ts-ignore\n return this._frustumPlanes;\n }\n\n Object.assign(this._frustumPlanes, getFrustumPlanes(this.viewProjectionMatrix));\n\n // @ts-ignore\n return this._frustumPlanes;\n }\n\n // EXPERIMENTAL METHODS\n\n /**\n * Needed by panning and linear transition\n * Pan the viewport to place a given world coordinate at screen point [x, y]\n *\n * @param {Array} coords - world coordinates\n * @param {Array} pixel - [x,y] coordinates on screen\n * @param {Array} startPixel - [x,y] screen position where pan started (optional, for delta-based panning)\n * @return {Object} props of the new viewport\n */\n panByPosition(coords: number[], pixel: number[], startPixel?: number[]): any {\n return null;\n }\n\n // INTERNAL METHODS\n\n /* eslint-disable complexity, max-statements */\n private _initProps(opts: ViewportOptions) {\n const longitude = opts.longitude as number;\n const latitude = opts.latitude as number;\n\n if (this.isGeospatial) {\n if (!Number.isFinite(opts.zoom)) {\n this.zoom = getMeterZoom({latitude}) + Math.log2(this.focalDistance);\n }\n this.distanceScales = opts.distanceScales || getDistanceScales({latitude, longitude});\n }\n const scale = Math.pow(2, this.zoom);\n this.scale = scale;\n\n const {position, modelMatrix} = opts;\n let meterOffset: number[] = ZERO_VECTOR;\n if (position) {\n meterOffset = modelMatrix\n ? (new Matrix4(modelMatrix).transformAsVector(position, []) as number[])\n : position;\n }\n\n if (this.isGeospatial) {\n // Determine camera center in common space\n const center = this.projectPosition([longitude, latitude, 0]);\n\n this.center = new Vector3(meterOffset)\n // Convert to pixels in current zoom\n .scale(this.distanceScales.unitsPerMeter)\n .add(center);\n } else {\n this.center = this.projectPosition(meterOffset);\n }\n }\n /* eslint-enable complexity, max-statements */\n\n private _initMatrices(opts: ViewportOptions) {\n const {\n // View matrix\n viewMatrix = IDENTITY,\n // Projection matrix\n projectionMatrix = null,\n\n // Projection matrix parameters, used if projectionMatrix not supplied\n orthographic = false,\n fovyRadians,\n fovy = 75,\n near = 0.1, // Distance of near clipping plane\n far = 1000, // Distance of far clipping plane\n padding = null, // Center offset in pixels\n focalDistance = 1\n } = opts;\n\n this.viewMatrixUncentered = viewMatrix;\n // Make a centered version of the matrix for projection modes without an offset\n this.viewMatrix = new Matrix4()\n // Apply the uncentered view matrix\n .multiplyRight(viewMatrix)\n // And center it\n .translate(new Vector3(this.center).negate());\n\n this.projectionMatrix =\n projectionMatrix ||\n createProjectionMatrix({\n width: this.width,\n height: this.height,\n orthographic,\n fovyRadians: fovyRadians || fovy * DEGREES_TO_RADIANS,\n focalDistance,\n padding,\n near,\n far\n });\n\n // Note: As usual, matrix operations should be applied in \"reverse\" order\n // since vectors will be multiplied in from the right during transformation\n const vpm = createMat4();\n mat4.multiply(vpm, vpm, this.projectionMatrix);\n mat4.multiply(vpm, vpm, this.viewMatrix);\n this.viewProjectionMatrix = vpm;\n\n // console.log('VPM', this.viewMatrix, this.projectionMatrix, this.viewProjectionMatrix);\n\n // Calculate inverse view matrix\n this.viewMatrixInverse = mat4.invert([], this.viewMatrix) || this.viewMatrix;\n\n // Decompose camera parameters\n this.cameraPosition = getCameraPosition(this.viewMatrixInverse);\n\n /*\n * Builds matrices that converts preprojected lngLats to screen pixels\n * and vice versa.\n * Note: Currently returns bottom-left coordinates!\n * Note: Starts with the GL projection matrix and adds steps to the\n * scale and translate that matrix onto the window.\n * Note: WebGL controls clip space to screen projection with gl.viewport\n * and does not need this step.\n */\n\n // matrix for conversion from world location to screen (pixel) coordinates\n const viewportMatrix = createMat4(); // matrix from NDC to viewport.\n const pixelProjectionMatrix = createMat4(); // matrix from world space to viewport.\n mat4.scale(viewportMatrix, viewportMatrix, [this.width / 2, -this.height / 2, 1]);\n mat4.translate(viewportMatrix, viewportMatrix, [1, -1, 0]);\n mat4.multiply(pixelProjectionMatrix, viewportMatrix, this.viewProjectionMatrix);\n this.pixelProjectionMatrix = pixelProjectionMatrix;\n\n this.pixelUnprojectionMatrix = mat4.invert(createMat4(), this.pixelProjectionMatrix);\n if (!this.pixelUnprojectionMatrix) {\n log.warn('Pixel project matrix not invertible')();\n // throw new Error('Pixel project matrix not invertible');\n }\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// View and Projection Matrix calculations for mapbox-js style\n// map view properties\nimport Viewport from './viewport';\n\nimport {\n pixelsToWorld,\n getViewMatrix,\n addMetersToLngLat,\n unitsPerMeter,\n getProjectionParameters,\n altitudeToFovy,\n fovyToAltitude,\n fitBounds,\n getBounds\n} from '@math.gl/web-mercator';\nimport {Padding} from './viewport';\n\nimport {Matrix4, clamp, vec2} from '@math.gl/core';\n\nexport type WebMercatorViewportOptions = {\n /** Name of the viewport */\n id?: string;\n /** Left offset from the canvas edge, in pixels */\n x?: number;\n /** Top offset from the canvas edge, in pixels */\n y?: number;\n /** Viewport width in pixels */\n width?: number;\n /** Viewport height in pixels */\n height?: number;\n /** Longitude in degrees */\n longitude?: number;\n /** Latitude in degrees */\n latitude?: number;\n /** Tilt of the camera in degrees */\n pitch?: number;\n /** Heading of the camera in degrees */\n bearing?: number;\n /** Camera altitude relative to the viewport height, legacy property used to control the FOV. Default `1.5` */\n altitude?: number;\n /** Camera fovy in degrees. If provided, overrides `altitude` */\n fovy?: number;\n /** Viewport center in world space. If geospatial, refers to meter offsets from lng, lat, elevation */\n position?: number[];\n /** Zoom level */\n zoom?: number;\n /** Padding around the viewport, in pixels. */\n padding?: Padding | null;\n /** Model matrix of viewport center */\n modelMatrix?: number[] | null;\n /** Custom projection matrix */\n projectionMatrix?: number[];\n /** Use orthographic projection */\n orthographic?: boolean;\n /** Scaler for the near plane, 1 unit equals to the height of the viewport. Default `0.1` */\n nearZMultiplier?: number;\n /** Scaler for the far plane, 1 unit equals to the distance from the camera to the edge of the screen. Default `1.01` */\n farZMultiplier?: number;\n /** Optionally override the near plane position. `nearZMultiplier` is ignored if `nearZ` is supplied. */\n nearZ?: number;\n /** Optionally override the far plane position. `farZMultiplier` is ignored if `farZ` is supplied. */\n farZ?: number;\n /** Render multiple copies of the world */\n repeat?: boolean;\n /** Internal use */\n worldOffset?: number;\n /** @deprecated Revert to approximated meter size calculation prior to v8.5 */\n legacyMeterSizes?: boolean;\n};\n\n/**\n * Manages transformations to/from WGS84 coordinates using the Web Mercator Projection.\n */\nexport default class WebMercatorViewport extends Viewport {\n static displayName = 'WebMercatorViewport';\n\n longitude: number;\n latitude: number;\n pitch: number;\n bearing: number;\n altitude: number;\n fovy: number;\n orthographic: boolean;\n\n /** Each sub viewport renders one copy of the world if repeat:true. The list is generated and cached on first request. */\n private _subViewports: WebMercatorViewport[] | null;\n /** @deprecated Revert to approximated meter size calculation prior to v8.5 */\n private _pseudoMeters: boolean;\n\n /* eslint-disable complexity, max-statements */\n constructor(opts: WebMercatorViewportOptions = {}) {\n const {\n latitude = 0,\n longitude = 0,\n zoom = 0,\n pitch = 0,\n bearing = 0,\n nearZMultiplier = 0.1,\n farZMultiplier = 1.01,\n nearZ,\n farZ,\n orthographic = false,\n projectionMatrix,\n\n repeat = false,\n worldOffset = 0,\n position,\n padding,\n\n // backward compatibility\n // TODO: remove in v9\n legacyMeterSizes = false\n } = opts;\n\n let {width, height, altitude = 1.5} = opts;\n const scale = Math.pow(2, zoom);\n\n // Silently allow apps to send in 0,0 to facilitate isomorphic render etc\n width = width || 1;\n height = height || 1;\n\n let fovy;\n let projectionParameters: any = null;\n if (projectionMatrix) {\n altitude = projectionMatrix[5] / 2;\n fovy = altitudeToFovy(altitude);\n } else {\n if (opts.fovy) {\n fovy = opts.fovy;\n altitude = fovyToAltitude(fovy);\n } else {\n fovy = altitudeToFovy(altitude);\n }\n\n let offset: [number, number] | undefined;\n if (padding) {\n const {top = 0, bottom = 0} = padding;\n offset = [0, clamp((top + height - bottom) / 2, 0, height) - height / 2];\n }\n\n projectionParameters = getProjectionParameters({\n width,\n height,\n scale,\n center: position && [0, 0, position[2] * unitsPerMeter(latitude)],\n offset,\n pitch,\n fovy,\n nearZMultiplier,\n farZMultiplier\n });\n\n if (Number.isFinite(nearZ)) {\n projectionParameters.near = nearZ;\n }\n if (Number.isFinite(farZ)) {\n projectionParameters.far = farZ;\n }\n }\n\n // The uncentered matrix allows us two move the center addition to the\n // shader (cheap) which gives a coordinate system that has its center in\n // the layer's center position. This makes rotations and other modelMatrx\n // transforms much more useful.\n let viewMatrixUncentered = getViewMatrix({\n height,\n pitch,\n bearing,\n scale,\n altitude\n });\n\n if (worldOffset) {\n const viewOffset = new Matrix4().translate([512 * worldOffset, 0, 0]);\n viewMatrixUncentered = viewOffset.multiplyLeft(viewMatrixUncentered);\n }\n\n super({\n ...opts,\n // x, y,\n width,\n height,\n\n // view matrix\n viewMatrix: viewMatrixUncentered,\n longitude,\n latitude,\n zoom,\n\n // projection matrix parameters\n ...projectionParameters,\n fovy,\n focalDistance: altitude\n });\n\n // Save parameters\n this.latitude = latitude;\n this.longitude = longitude;\n this.zoom = zoom;\n this.pitch = pitch;\n this.bearing = bearing;\n this.altitude = altitude;\n this.fovy = fovy;\n\n this.orthographic = orthographic;\n\n this._subViewports = repeat ? [] : null;\n this._pseudoMeters = legacyMeterSizes;\n\n Object.freeze(this);\n }\n /* eslint-enable complexity, max-statements */\n\n get subViewports(): WebMercatorViewport[] | null {\n if (this._subViewports && !this._subViewports.length) {\n // Cache sub viewports so that we only calculate them once\n const bounds = this.getBounds();\n\n const minOffset = Math.floor((bounds[0] + 180) / 360);\n const maxOffset = Math.ceil((bounds[2] - 180) / 360);\n\n for (let x = minOffset; x <= maxOffset; x++) {\n const offsetViewport = x\n ? new WebMercatorViewport({\n ...this,\n worldOffset: x\n })\n : this;\n this._subViewports.push(offsetViewport);\n }\n }\n return this._subViewports;\n }\n\n projectPosition(xyz: number[]): [number, number, number] {\n if (this._pseudoMeters) {\n // Backward compatibility\n return super.projectPosition(xyz);\n }\n const [X, Y] = this.projectFlat(xyz);\n const Z = (xyz[2] || 0) * unitsPerMeter(xyz[1]);\n return [X, Y, Z];\n }\n\n unprojectPosition(xyz: number[]): [number, number, number] {\n if (this._pseudoMeters) {\n // Backward compatibility\n return super.unprojectPosition(xyz);\n }\n const [X, Y] = this.unprojectFlat(xyz);\n const Z = (xyz[2] || 0) / unitsPerMeter(Y);\n return [X, Y, Z];\n }\n\n /**\n * Add a meter delta to a base lnglat coordinate, returning a new lnglat array\n *\n * Note: Uses simple linear approximation around the viewport center\n * Error increases with size of offset (roughly 1% per 100km)\n *\n * @param {[Number,Number]|[Number,Number,Number]) lngLatZ - base coordinate\n * @param {[Number,Number]|[Number,Number,Number]) xyz - array of meter deltas\n * @return {[Number,Number]|[Number,Number,Number]) array of [lng,lat,z] deltas\n */\n addMetersToLngLat(lngLatZ: number[], xyz: number[]): number[] {\n return addMetersToLngLat(lngLatZ, xyz);\n }\n\n panByPosition(\n coords: number[],\n pixel: number[],\n startPixel?: number[]\n ): WebMercatorViewportOptions {\n const fromLocation = pixelsToWorld(pixel, this.pixelUnprojectionMatrix);\n const toLocation = this.projectFlat(coords);\n\n const translate = vec2.add([], toLocation, vec2.negate([], fromLocation));\n const newCenter = vec2.add([], this.center, translate);\n\n const [longitude, latitude] = this.unprojectFlat(newCenter);\n return {longitude, latitude};\n }\n\n /**\n * Returns a new longitude and latitude that keeps a 3D world coordinate at a given screen pixel\n * This version handles the z-component (altitude) properly for cameras positioned above ground\n */\n panByPosition3D(coords: number[], pixel: number[]): WebMercatorViewportOptions {\n const targetZ = coords[2] || 0;\n const deltaLngLat = vec2.sub([], coords, this.unproject(pixel, {targetZ}));\n return {longitude: this.longitude + deltaLngLat[0], latitude: this.latitude + deltaLngLat[1]};\n }\n\n getBounds(options: {z?: number} = {}): [number, number, number, number] {\n // @ts-ignore\n const corners = getBounds(this, options.z || 0);\n\n return [\n Math.min(corners[0][0], corners[1][0], corners[2][0], corners[3][0]),\n Math.min(corners[0][1], corners[1][1], corners[2][1], corners[3][1]),\n Math.max(corners[0][0], corners[1][0], corners[2][0], corners[3][0]),\n Math.max(corners[0][1], corners[1][1], corners[2][1], corners[3][1])\n ];\n }\n\n /**\n * Returns a new viewport that fit around the given rectangle.\n * Only supports non-perspective mode.\n */\n fitBounds(\n /** [[lon, lat], [lon, lat]] */\n bounds: [[number, number], [number, number]],\n options: {\n /** If not supplied, will use the current width of the viewport (default `1`) */\n width?: number;\n /** If not supplied, will use the current height of the viewport (default `1`) */\n height?: number;\n /** In degrees, 0.01 would be about 1000 meters */\n minExtent?: number;\n /** Max zoom level */\n maxZoom?: number;\n /** Extra padding in pixels */\n padding?: number | Required;\n /** Center shift in pixels */\n offset?: number[];\n } = {}\n ) {\n const {width, height} = this;\n const {longitude, latitude, zoom} = fitBounds({width, height, bounds, ...options});\n return new WebMercatorViewport({width, height, longitude, latitude, zoom});\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/**\n * Projection utils\n * TODO: move to Viewport class?\n */\nimport {getOffsetOrigin} from './viewport-uniforms';\nimport WebMercatorViewport from '../../viewports/web-mercator-viewport';\n\nimport {vec3, vec4} from '@math.gl/core';\nimport {addMetersToLngLat} from '@math.gl/web-mercator';\n\nimport type {CoordinateSystem} from '../../lib/constants';\nimport type Viewport from '../../viewports/viewport';\nimport type {NumericArray} from '../../types/types';\n\nconst DEFAULT_COORDINATE_ORIGIN = [0, 0, 0];\n\n// In project.glsl, offset modes calculate z differently from LNG_LAT mode.\n// offset modes apply the y adjustment (unitsPerMeter2) when projecting z\n// LNG_LAT mode only use the linear scale.\nfunction lngLatZToWorldPosition(\n lngLatZ: [number, number, number],\n viewport: Viewport,\n offsetMode: boolean = false\n): [number, number, number] {\n const p = viewport.projectPosition(lngLatZ);\n\n // TODO - avoid using instanceof\n if (offsetMode && viewport instanceof WebMercatorViewport) {\n const [longitude, latitude, z = 0] = lngLatZ;\n const distanceScales = viewport.getDistanceScales([longitude, latitude]);\n p[2] = z * distanceScales.unitsPerMeter[2];\n }\n return p;\n}\n\nfunction normalizeParameters(opts: {\n viewport: Viewport;\n coordinateSystem: CoordinateSystem;\n coordinateOrigin: [number, number, number];\n modelMatrix?: NumericArray | null;\n fromCoordinateSystem?: CoordinateSystem;\n fromCoordinateOrigin?: [number, number, number];\n}): {\n viewport: Viewport;\n coordinateSystem: CoordinateSystem;\n coordinateOrigin: [number, number, number];\n modelMatrix?: NumericArray | null;\n fromCoordinateSystem: CoordinateSystem;\n fromCoordinateOrigin: [number, number, number];\n} {\n const {viewport, modelMatrix, coordinateOrigin} = opts;\n let {coordinateSystem, fromCoordinateSystem, fromCoordinateOrigin} = opts;\n\n if (coordinateSystem === 'default') {\n coordinateSystem = viewport.isGeospatial ? 'lnglat' : 'cartesian';\n }\n\n if (fromCoordinateSystem === undefined) {\n fromCoordinateSystem = coordinateSystem;\n } else if (fromCoordinateSystem === 'default') {\n fromCoordinateSystem = viewport.isGeospatial ? 'lnglat' : 'cartesian';\n }\n if (fromCoordinateOrigin === undefined) {\n fromCoordinateOrigin = coordinateOrigin;\n }\n\n return {\n viewport,\n coordinateSystem,\n coordinateOrigin,\n modelMatrix,\n fromCoordinateSystem,\n fromCoordinateOrigin\n };\n}\n\n/** Get the common space position from world coordinates in the given coordinate system */\nexport function getWorldPosition(\n position: number[],\n {\n viewport,\n modelMatrix,\n coordinateSystem,\n coordinateOrigin,\n offsetMode\n }: {\n viewport: Viewport;\n modelMatrix?: NumericArray | null;\n coordinateSystem: CoordinateSystem;\n coordinateOrigin: [number, number, number];\n offsetMode?: boolean;\n }\n): [number, number, number] {\n let [x, y, z = 0] = position;\n\n if (modelMatrix) {\n [x, y, z] = vec4.transformMat4([], [x, y, z, 1.0], modelMatrix);\n }\n\n switch (coordinateSystem) {\n case 'default':\n return getWorldPosition(position, {\n viewport,\n modelMatrix,\n coordinateSystem: viewport.isGeospatial ? 'lnglat' : 'cartesian',\n coordinateOrigin,\n offsetMode\n });\n\n case 'lnglat':\n return lngLatZToWorldPosition([x, y, z], viewport, offsetMode);\n\n case 'lnglat-offsets':\n return lngLatZToWorldPosition(\n [x + coordinateOrigin[0], y + coordinateOrigin[1], z + (coordinateOrigin[2] || 0)],\n viewport,\n offsetMode\n );\n\n case 'meter-offsets':\n return lngLatZToWorldPosition(\n addMetersToLngLat(coordinateOrigin, [x, y, z]) as [number, number, number],\n viewport,\n offsetMode\n );\n\n case 'cartesian':\n return viewport.isGeospatial\n ? [x + coordinateOrigin[0], y + coordinateOrigin[1], z + coordinateOrigin[2]]\n : viewport.projectPosition([x, y, z]);\n\n default:\n throw new Error(`Invalid coordinateSystem: ${coordinateSystem}`);\n }\n}\n\n/**\n * Equivalent to project_position in project.glsl\n * projects a user supplied position to world position directly with or without\n * a reference coordinate system\n */\nexport function projectPosition(\n position: number[],\n params: {\n /** The current viewport */\n viewport: Viewport;\n /** The reference coordinate system used to align world position */\n coordinateSystem: CoordinateSystem;\n /** The reference coordinate origin used to align world position */\n coordinateOrigin: [number, number, number];\n /** The model matrix of the supplied position */\n modelMatrix?: NumericArray | null;\n /** The coordinate system that the supplied position is in. Default to the same as `coordinateSystem`. */\n fromCoordinateSystem?: CoordinateSystem;\n /** The coordinate origin that the supplied position is in. Default to the same as `coordinateOrigin`. */\n fromCoordinateOrigin?: [number, number, number];\n /** Whether to apply offset mode automatically as does the project shader module.\n * Offset mode places the origin of the common space at the given viewport's center. It is used in some use cases\n * to improve precision in the vertex shader due to the fp32 float limitation.\n * Use `autoOffset:false` if the returned position should not be dependent on the current viewport.\n * Default `true` */\n autoOffset?: boolean;\n }\n): [number, number, number] {\n const {\n viewport,\n coordinateSystem,\n coordinateOrigin,\n modelMatrix,\n fromCoordinateSystem,\n fromCoordinateOrigin\n } = normalizeParameters(params);\n const {autoOffset = true} = params;\n\n const {\n geospatialOrigin = DEFAULT_COORDINATE_ORIGIN,\n shaderCoordinateOrigin = DEFAULT_COORDINATE_ORIGIN,\n offsetMode = false\n } = autoOffset ? getOffsetOrigin(viewport, coordinateSystem, coordinateOrigin) : {};\n\n const worldPosition = getWorldPosition(position, {\n viewport,\n modelMatrix,\n coordinateSystem: fromCoordinateSystem,\n coordinateOrigin: fromCoordinateOrigin,\n offsetMode\n });\n\n if (offsetMode) {\n const positionCommonSpace = viewport.projectPosition(\n geospatialOrigin || shaderCoordinateOrigin\n );\n vec3.sub(worldPosition, worldPosition, positionCommonSpace);\n }\n\n return worldPosition;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/**\n * Timeline channel properties\n * @param delay = 0;\n * @param duration = Number.POSITIVE_INFINITY;\n * @param rate = 1\n * @param repeat = 1\n */\nexport type ChannelOptions = {\n delay?: number;\n duration?: number;\n rate?: number;\n repeat?: number;\n};\n\nexport type AnimationOptions = {\n setTime: (time: number) => void;\n};\n\ntype Channel = {\n time: number;\n delay: number;\n duration: number;\n rate: number;\n repeat: number;\n};\n\ntype Animation = {\n channel?: number;\n animation: {\n setTime: (time: number) => void;\n };\n};\n\nlet channelHandles = 1;\nlet animationHandles = 1;\n\nexport class Timeline {\n time: number = 0;\n channels = new Map();\n animations = new Map();\n playing: boolean = false;\n lastEngineTime: number = -1;\n\n constructor() {}\n\n addChannel(props: ChannelOptions): number {\n const {delay = 0, duration = Number.POSITIVE_INFINITY, rate = 1, repeat = 1} = props;\n\n const channelId = channelHandles++;\n const channel: Channel = {\n time: 0,\n delay,\n duration,\n rate,\n repeat\n };\n this._setChannelTime(channel, this.time);\n this.channels.set(channelId, channel);\n\n return channelId;\n }\n\n removeChannel(channelId: number): void {\n this.channels.delete(channelId);\n\n for (const [animationHandle, animation] of this.animations) {\n if (animation.channel === channelId) {\n this.detachAnimation(animationHandle);\n }\n }\n }\n\n isFinished(channelId: number): boolean {\n const channel = this.channels.get(channelId);\n if (channel === undefined) {\n return false;\n }\n\n return this.time >= channel.delay + channel.duration * channel.repeat;\n }\n\n getTime(channelId?: number): number {\n if (channelId === undefined) {\n return this.time;\n }\n\n const channel = this.channels.get(channelId);\n\n if (channel === undefined) {\n return -1;\n }\n\n return channel.time;\n }\n\n setTime(time: number): void {\n this.time = Math.max(0, time);\n\n const channels = this.channels.values();\n for (const channel of channels) {\n this._setChannelTime(channel, this.time);\n }\n\n const animations = this.animations.values();\n for (const animationData of animations) {\n const {animation, channel} = animationData;\n animation.setTime(this.getTime(channel));\n }\n }\n\n play(): void {\n this.playing = true;\n }\n\n pause(): void {\n this.playing = false;\n this.lastEngineTime = -1;\n }\n\n reset(): void {\n this.setTime(0);\n }\n\n attachAnimation(animation: AnimationOptions, channelHandle?: number): number {\n const animationHandle = animationHandles++;\n\n this.animations.set(animationHandle, {\n animation,\n channel: channelHandle\n });\n\n animation.setTime(this.getTime(channelHandle));\n\n return animationHandle;\n }\n\n detachAnimation(channelId: number): void {\n this.animations.delete(channelId);\n }\n\n update(engineTime: number): void {\n if (this.playing) {\n if (this.lastEngineTime === -1) {\n this.lastEngineTime = engineTime;\n }\n this.setTime(this.time + (engineTime - this.lastEngineTime));\n this.lastEngineTime = engineTime;\n }\n }\n\n _setChannelTime(channel: Channel, time: number): void {\n const offsetTime = time - channel.delay;\n const totalDuration = channel.duration * channel.repeat;\n // Note(Tarek): Don't loop on final repeat.\n if (offsetTime >= totalDuration) {\n channel.time = channel.duration * channel.rate;\n } else {\n channel.time = Math.max(0, offsetTime) % channel.duration;\n channel.time *= channel.rate;\n }\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {luma, Device} from '@luma.gl/core';\nimport {\n requestAnimationFramePolyfill,\n cancelAnimationFramePolyfill\n} from './request-animation-frame';\nimport {Timeline} from '../animation/timeline';\nimport {AnimationProps} from './animation-props';\nimport {Stats, Stat} from '@probe.gl/stats';\n\nlet statIdCounter = 0;\nconst ANIMATION_LOOP_STATS = 'Animation Loop';\n\n/** AnimationLoop properties */\nexport type AnimationLoopProps = {\n device: Device | Promise;\n\n onAddHTML?: (div: HTMLDivElement) => string; // innerHTML\n onInitialize?: (animationProps: AnimationProps) => Promise;\n onRender?: (animationProps: AnimationProps) => unknown;\n onFinalize?: (animationProps: AnimationProps) => void;\n onError?: (reason: Error) => void;\n\n stats?: Stats;\n\n // view parameters - TODO move to CanvasContext?\n autoResizeViewport?: boolean;\n};\n\nexport type MutableAnimationLoopProps = {\n // view parameters\n autoResizeViewport?: boolean;\n};\n\n/** Convenient animation loop */\nexport class AnimationLoop {\n static defaultAnimationLoopProps = {\n device: null!,\n\n onAddHTML: () => '',\n onInitialize: async () => null,\n onRender: () => {},\n onFinalize: () => {},\n onError: error => console.error(error), // eslint-disable-line no-console\n\n stats: undefined!,\n\n // view parameters\n autoResizeViewport: false\n } as const satisfies Readonly>;\n\n device: Device | null = null;\n canvas: HTMLCanvasElement | OffscreenCanvas | null = null;\n\n props: Required;\n animationProps: AnimationProps | null = null;\n timeline: Timeline | null = null;\n stats: Stats;\n sharedStats: Stats;\n cpuTime: Stat;\n gpuTime: Stat;\n frameRate: Stat;\n\n display: any;\n\n private _needsRedraw: string | false = 'initialized';\n\n _initialized: boolean = false;\n _running: boolean = false;\n _animationFrameId: any = null;\n _nextFramePromise: Promise | null = null;\n _resolveNextFrame: ((animationLoop: AnimationLoop) => void) | null = null;\n _cpuStartTime: number = 0;\n _error: Error | null = null;\n _lastFrameTime: number = 0;\n\n /*\n * @param {HTMLCanvasElement} canvas - if provided, width and height will be passed to context\n */\n constructor(props: AnimationLoopProps) {\n this.props = {...AnimationLoop.defaultAnimationLoopProps, ...props};\n props = this.props;\n\n if (!props.device) {\n throw new Error('No device provided');\n }\n\n // state\n this.stats = props.stats || new Stats({id: `animation-loop-${statIdCounter++}`});\n this.sharedStats = luma.stats.get(ANIMATION_LOOP_STATS);\n this.frameRate = this.stats.get('Frame Rate');\n this.frameRate.setSampleSize(1);\n this.cpuTime = this.stats.get('CPU Time');\n this.gpuTime = this.stats.get('GPU Time');\n\n this.setProps({autoResizeViewport: props.autoResizeViewport});\n\n // Bind methods\n this.start = this.start.bind(this);\n this.stop = this.stop.bind(this);\n\n this._onMousemove = this._onMousemove.bind(this);\n this._onMouseleave = this._onMouseleave.bind(this);\n }\n\n destroy(): void {\n this.stop();\n this._setDisplay(null);\n this.device?._disableDebugGPUTime();\n }\n\n /** @deprecated Use .destroy() */\n delete(): void {\n this.destroy();\n }\n\n reportError(error: Error): void {\n this.props.onError(error);\n this._error = error;\n }\n\n /** Flags this animation loop as needing redraw */\n setNeedsRedraw(reason: string): this {\n this._needsRedraw = this._needsRedraw || reason;\n return this;\n }\n\n /** Query redraw status. Clears the flag. */\n needsRedraw(): false | string {\n const reason = this._needsRedraw;\n this._needsRedraw = false;\n return reason;\n }\n\n setProps(props: MutableAnimationLoopProps): this {\n if ('autoResizeViewport' in props) {\n this.props.autoResizeViewport = props.autoResizeViewport || false;\n }\n return this;\n }\n\n /** Starts a render loop if not already running */\n async start() {\n if (this._running) {\n return this;\n }\n this._running = true;\n\n try {\n let appContext;\n if (!this._initialized) {\n this._initialized = true;\n // Create the WebGL context\n await this._initDevice();\n this._initialize();\n if (!this._running) {\n return null;\n }\n\n // Note: onIntialize can return a promise (e.g. in case app needs to load resources)\n await this.props.onInitialize(this._getAnimationProps());\n }\n\n // check that we haven't been stopped\n if (!this._running) {\n return null;\n }\n\n // Start the loop\n if (appContext !== false) {\n // cancel any pending renders to ensure only one loop can ever run\n this._cancelAnimationFrame();\n this._requestAnimationFrame();\n }\n\n return this;\n } catch (err: unknown) {\n const error = err instanceof Error ? err : new Error('Unknown error');\n this.props.onError(error);\n // this._running = false; // TODO\n throw error;\n }\n }\n\n /** Stops a render loop if already running, finalizing */\n stop() {\n // console.debug(`Stopping ${this.constructor.name}`);\n if (this._running) {\n // call callback\n // If stop is called immediately, we can end up in a state where props haven't been initialized...\n if (this.animationProps && !this._error) {\n this.props.onFinalize(this.animationProps);\n }\n\n this._cancelAnimationFrame();\n this._nextFramePromise = null;\n this._resolveNextFrame = null;\n this._running = false;\n this._lastFrameTime = 0;\n }\n return this;\n }\n\n /** Explicitly draw a frame */\n redraw(time?: number): this {\n if (this.device?.isLost || this._error) {\n return this;\n }\n\n this._beginFrameTimers(time);\n\n this._setupFrame();\n this._updateAnimationProps();\n\n this._renderFrame(this._getAnimationProps());\n\n // clear needsRedraw flag\n this._clearNeedsRedraw();\n\n if (this._resolveNextFrame) {\n this._resolveNextFrame(this);\n this._nextFramePromise = null;\n this._resolveNextFrame = null;\n }\n\n this._endFrameTimers();\n\n return this;\n }\n\n /** Add a timeline, it will be automatically updated by the animation loop. */\n attachTimeline(timeline: Timeline): Timeline {\n this.timeline = timeline;\n return this.timeline;\n }\n\n /** Remove a timeline */\n detachTimeline(): void {\n this.timeline = null;\n }\n\n /** Wait until a render completes */\n waitForRender(): Promise {\n this.setNeedsRedraw('waitForRender');\n\n if (!this._nextFramePromise) {\n this._nextFramePromise = new Promise(resolve => {\n this._resolveNextFrame = resolve;\n });\n }\n return this._nextFramePromise;\n }\n\n /** TODO - should use device.deviceContext */\n async toDataURL(): Promise {\n this.setNeedsRedraw('toDataURL');\n await this.waitForRender();\n if (this.canvas instanceof HTMLCanvasElement) {\n return this.canvas.toDataURL();\n }\n throw new Error('OffscreenCanvas');\n }\n\n // PRIVATE METHODS\n\n _initialize(): void {\n this._startEventHandling();\n\n // Initialize the callback data\n this._initializeAnimationProps();\n this._updateAnimationProps();\n\n // Default viewport setup, in case onInitialize wants to render\n this._resizeViewport();\n\n this.device?._enableDebugGPUTime();\n }\n\n _setDisplay(display: any): void {\n if (this.display) {\n this.display.destroy();\n this.display.animationLoop = null;\n }\n\n // store animation loop on the display\n if (display) {\n display.animationLoop = this;\n }\n\n this.display = display;\n }\n\n _requestAnimationFrame(): void {\n if (!this._running) {\n return;\n }\n\n // VR display has a separate animation frame to sync with headset\n // TODO WebVR API discontinued, replaced by WebXR: https://immersive-web.github.io/webxr/\n // See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/requestAnimationFrame\n // if (this.display && this.display.requestAnimationFrame) {\n // this._animationFrameId = this.display.requestAnimationFrame(this._animationFrame.bind(this));\n // }\n this._animationFrameId = requestAnimationFramePolyfill(this._animationFrame.bind(this));\n }\n\n _cancelAnimationFrame(): void {\n if (this._animationFrameId === null) {\n return;\n }\n\n // VR display has a separate animation frame to sync with headset\n // TODO WebVR API discontinued, replaced by WebXR: https://immersive-web.github.io/webxr/\n // See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/requestAnimationFrame\n // if (this.display && this.display.cancelAnimationFramePolyfill) {\n // this.display.cancelAnimationFrame(this._animationFrameId);\n // }\n cancelAnimationFramePolyfill(this._animationFrameId);\n this._animationFrameId = null;\n }\n\n _animationFrame(time: number): void {\n if (!this._running) {\n return;\n }\n this.redraw(time);\n this._requestAnimationFrame();\n }\n\n // Called on each frame, can be overridden to call onRender multiple times\n // to support e.g. stereoscopic rendering\n _renderFrame(animationProps: AnimationProps): void {\n // Allow e.g. VR display to render multiple frames.\n if (this.display) {\n this.display._renderFrame(animationProps);\n return;\n }\n\n // call callback\n this.props.onRender(this._getAnimationProps());\n // end callback\n\n // Submit commands (necessary on WebGPU)\n this.device?.submit();\n }\n\n _clearNeedsRedraw(): void {\n this._needsRedraw = false;\n }\n\n _setupFrame(): void {\n this._resizeViewport();\n }\n\n // Initialize the object that will be passed to app callbacks\n _initializeAnimationProps(): void {\n const canvasContext = this.device?.getDefaultCanvasContext();\n if (!this.device || !canvasContext) {\n throw new Error('loop');\n }\n\n const canvas = canvasContext?.canvas;\n const useDevicePixels = canvasContext.props.useDevicePixels;\n\n this.animationProps = {\n animationLoop: this,\n\n device: this.device,\n canvasContext,\n canvas,\n // @ts-expect-error Deprecated\n useDevicePixels,\n\n timeline: this.timeline,\n\n needsRedraw: false,\n\n // Placeholders\n width: 1,\n height: 1,\n aspect: 1,\n\n // Animation props\n time: 0,\n startTime: Date.now(),\n engineTime: 0,\n tick: 0,\n tock: 0,\n\n // Experimental\n _mousePosition: null // Event props\n };\n }\n\n _getAnimationProps(): AnimationProps {\n if (!this.animationProps) {\n throw new Error('animationProps');\n }\n return this.animationProps;\n }\n\n // Update the context object that will be passed to app callbacks\n _updateAnimationProps(): void {\n if (!this.animationProps) {\n return;\n }\n\n // Can this be replaced with canvas context?\n const {width, height, aspect} = this._getSizeAndAspect();\n if (width !== this.animationProps.width || height !== this.animationProps.height) {\n this.setNeedsRedraw('drawing buffer resized');\n }\n if (aspect !== this.animationProps.aspect) {\n this.setNeedsRedraw('drawing buffer aspect changed');\n }\n\n this.animationProps.width = width;\n this.animationProps.height = height;\n this.animationProps.aspect = aspect;\n\n this.animationProps.needsRedraw = this._needsRedraw;\n\n // Update time properties\n this.animationProps.engineTime = Date.now() - this.animationProps.startTime;\n\n if (this.timeline) {\n this.timeline.update(this.animationProps.engineTime);\n }\n\n this.animationProps.tick = Math.floor((this.animationProps.time / 1000) * 60);\n this.animationProps.tock++;\n\n // For back compatibility\n this.animationProps.time = this.timeline\n ? this.timeline.getTime()\n : this.animationProps.engineTime;\n }\n\n /** Wait for supplied device */\n async _initDevice() {\n this.device = await this.props.device;\n if (!this.device) {\n throw new Error('No device provided');\n }\n this.canvas = this.device.getDefaultCanvasContext().canvas || null;\n // this._createInfoDiv();\n }\n\n _createInfoDiv(): void {\n if (this.canvas && this.props.onAddHTML) {\n const wrapperDiv = document.createElement('div');\n document.body.appendChild(wrapperDiv);\n wrapperDiv.style.position = 'relative';\n const div = document.createElement('div');\n div.style.position = 'absolute';\n div.style.left = '10px';\n div.style.bottom = '10px';\n div.style.width = '300px';\n div.style.background = 'white';\n if (this.canvas instanceof HTMLCanvasElement) {\n wrapperDiv.appendChild(this.canvas);\n }\n wrapperDiv.appendChild(div);\n const html = this.props.onAddHTML(div);\n if (html) {\n div.innerHTML = html;\n }\n }\n }\n\n _getSizeAndAspect(): {width: number; height: number; aspect: number} {\n if (!this.device) {\n return {width: 1, height: 1, aspect: 1};\n }\n // Match projection setup to the actual render target dimensions, which may\n // differ from the CSS size when device-pixel scaling or backend clamping applies.\n const [width, height] = this.device.getDefaultCanvasContext().getDrawingBufferSize();\n const aspect = width > 0 && height > 0 ? width / height : 1;\n\n return {width, height, aspect};\n }\n\n /** @deprecated Default viewport setup */\n _resizeViewport(): void {\n // TODO can we use canvas context to code this in a portable way?\n // @ts-expect-error Expose on canvasContext\n if (this.props.autoResizeViewport && this.device.gl) {\n // @ts-expect-error Expose canvasContext\n this.device.gl.viewport(\n 0,\n 0,\n // @ts-expect-error Expose canvasContext\n this.device.gl.drawingBufferWidth,\n // @ts-expect-error Expose canvasContext\n this.device.gl.drawingBufferHeight\n );\n }\n }\n\n _beginFrameTimers(time?: number) {\n const now = time ?? (typeof performance !== 'undefined' ? performance.now() : Date.now());\n if (this._lastFrameTime) {\n const frameTime = now - this._lastFrameTime;\n if (frameTime > 0) {\n this.frameRate.addTime(frameTime);\n }\n }\n this._lastFrameTime = now;\n\n if (this.device?._isDebugGPUTimeEnabled()) {\n this._consumeEncodedGpuTime();\n }\n\n this.cpuTime.timeStart();\n }\n\n _endFrameTimers() {\n if (this.device?._isDebugGPUTimeEnabled()) {\n this._consumeEncodedGpuTime();\n }\n\n this.cpuTime.timeEnd();\n this._updateSharedStats();\n }\n\n _consumeEncodedGpuTime(): void {\n if (!this.device) {\n return;\n }\n\n const gpuTimeMs = this.device.commandEncoder._gpuTimeMs;\n if (gpuTimeMs !== undefined) {\n this.gpuTime.addTime(gpuTimeMs);\n this.device.commandEncoder._gpuTimeMs = undefined;\n }\n }\n\n _updateSharedStats(): void {\n if (this.stats === this.sharedStats) {\n return;\n }\n\n for (const name of Object.keys(this.sharedStats.stats)) {\n if (!this.stats.stats[name]) {\n delete this.sharedStats.stats[name];\n }\n }\n\n this.stats.forEach(sourceStat => {\n const targetStat = this.sharedStats.get(sourceStat.name, sourceStat.type);\n targetStat.sampleSize = sourceStat.sampleSize;\n targetStat.time = sourceStat.time;\n targetStat.count = sourceStat.count;\n targetStat.samples = sourceStat.samples;\n targetStat.lastTiming = sourceStat.lastTiming;\n targetStat.lastSampleTime = sourceStat.lastSampleTime;\n targetStat.lastSampleCount = sourceStat.lastSampleCount;\n targetStat._count = sourceStat._count;\n targetStat._time = sourceStat._time;\n targetStat._samples = sourceStat._samples;\n targetStat._startTime = sourceStat._startTime;\n targetStat._timerPending = sourceStat._timerPending;\n });\n }\n\n // Event handling\n\n _startEventHandling() {\n if (this.canvas) {\n this.canvas.addEventListener('mousemove', this._onMousemove.bind(this));\n this.canvas.addEventListener('mouseleave', this._onMouseleave.bind(this));\n }\n }\n\n _onMousemove(event: Event) {\n if (event instanceof MouseEvent) {\n this._getAnimationProps()._mousePosition = [event.offsetX, event.offsetY];\n }\n }\n\n _onMouseleave(event: Event) {\n this._getAnimationProps()._mousePosition = null;\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/* global window, setTimeout, clearTimeout */\n\n/** Node.js polyfill for requestAnimationFrame */\n// / \nexport function requestAnimationFramePolyfill(callback: (time?: any) => void): any {\n const browserRequestAnimationFrame =\n typeof window !== 'undefined'\n ? window.requestAnimationFrame ||\n (window as Window & {webkitRequestAnimationFrame?: (cb: FrameRequestCallback) => number})\n .webkitRequestAnimationFrame ||\n (window as Window & {mozRequestAnimationFrame?: (cb: FrameRequestCallback) => number})\n .mozRequestAnimationFrame\n : null;\n\n if (browserRequestAnimationFrame) {\n return browserRequestAnimationFrame.call(window, callback);\n }\n\n return setTimeout(\n () => callback(typeof performance !== 'undefined' ? performance.now() : Date.now()),\n 1000 / 60\n );\n}\n\n/** Node.js polyfill for cancelAnimationFrame */\nexport function cancelAnimationFramePolyfill(timerId: any): void {\n const browserCancelAnimationFrame =\n typeof window !== 'undefined'\n ? window.cancelAnimationFrame ||\n (window as Window & {webkitCancelAnimationFrame?: (handle: number) => void})\n .webkitCancelAnimationFrame ||\n (window as Window & {mozCancelAnimationFrame?: (handle: number) => void})\n .mozCancelAnimationFrame\n : null;\n\n if (browserCancelAnimationFrame) {\n browserCancelAnimationFrame.call(window, timerId);\n return;\n }\n\n clearTimeout(timerId);\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// A lot of imports, but then Model is where it all comes together...\nimport {type TypedArray} from '@math.gl/types';\nimport {\n type RenderPipelineProps,\n type RenderPipelineParameters,\n type BufferLayout,\n type Shader,\n type VertexArray,\n type TransformFeedback,\n type AttributeInfo,\n type Binding,\n type BindingsByGroup,\n type PrimitiveTopology,\n Device,\n DeviceFeature,\n Buffer,\n Texture,\n TextureView,\n Sampler,\n RenderPipeline,\n RenderPass,\n PipelineFactory,\n ShaderFactory,\n UniformStore,\n log,\n dataTypeDecoder,\n getAttributeInfosFromLayouts,\n normalizeBindingsByGroup\n} from '@luma.gl/core';\n\nimport type {ShaderBindingDebugRow, ShaderModule, PlatformInfo} from '@luma.gl/shadertools';\nimport {ShaderAssembler} from '@luma.gl/shadertools';\n\nimport type {Geometry} from '../geometry/geometry';\nimport {GPUGeometry, makeGPUGeometry} from '../geometry/gpu-geometry';\nimport {getDebugTableForShaderLayout} from '../debug/debug-shader-layout';\nimport {debugFramebuffer} from '../debug/debug-framebuffer';\nimport {deepEqual} from '../utils/deep-equal';\nimport {BufferLayoutHelper} from '../utils/buffer-layout-helper';\nimport {sortedBufferLayoutByShaderSourceLocations} from '../utils/buffer-layout-order';\nimport {\n mergeShaderModuleBindingsIntoLayout,\n shaderModuleHasUniforms\n} from '../utils/shader-module-utils';\nimport {uid} from '../utils/uid';\nimport {ShaderInputs} from '../shader-inputs';\nimport {DynamicTexture} from '../dynamic-texture/dynamic-texture';\nimport {Material} from '../material/material';\n\nconst LOG_DRAW_PRIORITY = 2;\nconst LOG_DRAW_TIMEOUT = 10000;\nconst PIPELINE_INITIALIZATION_FAILED = 'render pipeline initialization failed';\n\nexport type ModelProps = Omit & {\n source?: string;\n vs?: string | null;\n fs?: string | null;\n\n /** shadertool shader modules (added to shader code) */\n modules?: ShaderModule[];\n /** Shadertool module defines (configures shader code)*/\n defines?: Record;\n // TODO - injections, hooks etc?\n\n /** Shader inputs, used to generated uniform buffers and bindings */\n shaderInputs?: ShaderInputs;\n /** Material-owned group-3 bindings */\n material?: Material;\n /** Bindings */\n bindings?: Record;\n /** WebGL-only uniforms */\n uniforms?: Record;\n /** Parameters that are built into the pipeline */\n parameters?: RenderPipelineParameters;\n\n /** Geometry */\n geometry?: GPUGeometry | Geometry | null;\n\n /** @deprecated Use instanced rendering? Will be auto-detected in 9.1 */\n isInstanced?: boolean;\n /** instance count */\n instanceCount?: number;\n /** Vertex count */\n vertexCount?: number;\n\n indexBuffer?: Buffer | null;\n /** @note this is really a map of buffers, not a map of attributes */\n attributes?: Record;\n /** */\n constantAttributes?: Record;\n\n /** Some applications intentionally supply unused attributes and bindings, and want to disable warnings */\n disableWarnings?: boolean;\n\n /** @internal For use with {@link TransformFeedback}, WebGL only. */\n varyings?: string[];\n\n transformFeedback?: TransformFeedback;\n\n /** Show shader source in browser? */\n debugShaders?: 'never' | 'errors' | 'warnings' | 'always';\n\n /** Factory used to create a {@link RenderPipeline}. Defaults to {@link Device} default factory. */\n pipelineFactory?: PipelineFactory;\n /** Factory used to create a {@link Shader}. Defaults to {@link Device} default factory. */\n shaderFactory?: ShaderFactory;\n /** Shader assembler. Defaults to the ShaderAssembler.getShaderAssembler() */\n shaderAssembler?: ShaderAssembler;\n};\n\n/**\n * High level draw API for luma.gl.\n *\n * A `Model` encapsulates shaders, geometry attributes, bindings and render\n * pipeline state into a single object. It automatically reuses and rebuilds\n * pipelines as render parameters change and exposes convenient hooks for\n * updating uniforms and attributes.\n *\n * Features:\n * - Reuses and lazily recompiles {@link RenderPipeline | pipelines} as needed.\n * - Integrates with `@luma.gl/shadertools` to assemble GLSL or WGSL from shader modules.\n * - Manages geometry attributes and buffer bindings.\n * - Accepts textures, samplers and uniform buffers as bindings, including `DynamicTexture`.\n * - Provides detailed debug logging and optional shader source inspection.\n */\nexport class Model {\n static defaultProps: Required = {\n ...RenderPipeline.defaultProps,\n source: undefined!,\n vs: null,\n fs: null,\n id: 'unnamed',\n handle: undefined,\n userData: {},\n defines: {},\n modules: [],\n geometry: null,\n indexBuffer: null,\n attributes: {},\n constantAttributes: {},\n bindings: {},\n uniforms: {},\n varyings: [],\n\n isInstanced: undefined!,\n instanceCount: 0,\n vertexCount: 0,\n\n shaderInputs: undefined!,\n material: undefined!,\n pipelineFactory: undefined!,\n shaderFactory: undefined!,\n transformFeedback: undefined!,\n shaderAssembler: ShaderAssembler.getDefaultShaderAssembler(),\n\n debugShaders: undefined!,\n disableWarnings: undefined!\n };\n\n /** Device that created this model */\n readonly device: Device;\n /** Application provided identifier */\n readonly id: string;\n /** WGSL shader source when using unified shader */\n // @ts-expect-error assigned in function called from constructor\n readonly source: string;\n /** GLSL vertex shader source */\n // @ts-expect-error assigned in function called from constructor\n readonly vs: string;\n /** GLSL fragment shader source */\n // @ts-expect-error assigned in function called from constructor\n readonly fs: string;\n /** Factory used to create render pipelines */\n readonly pipelineFactory: PipelineFactory;\n /** Factory used to create shaders */\n readonly shaderFactory: ShaderFactory;\n /** User-supplied per-model data */\n userData: {[key: string]: any} = {};\n\n // Fixed properties (change can trigger pipeline rebuild)\n\n /** The render pipeline GPU parameters, depth testing etc */\n parameters: RenderPipelineParameters;\n\n /** The primitive topology */\n topology: PrimitiveTopology;\n /** Buffer layout */\n bufferLayout: BufferLayout[];\n\n // Dynamic properties\n\n /** Use instanced rendering */\n isInstanced: boolean | undefined = undefined;\n /** instance count. `undefined` means not instanced */\n instanceCount: number = 0;\n /** Vertex count */\n vertexCount: number;\n\n /** Index buffer */\n indexBuffer: Buffer | null = null;\n /** Buffer-valued attributes */\n bufferAttributes: Record = {};\n /** Constant-valued attributes */\n constantAttributes: Record = {};\n /** Bindings (textures, samplers, uniform buffers) */\n bindings: Record = {};\n\n /**\n * VertexArray\n * @note not implemented: if bufferLayout is updated, vertex array has to be rebuilt!\n * @todo - allow application to define multiple vertex arrays?\n * */\n vertexArray: VertexArray;\n\n /** TransformFeedback, WebGL 2 only. */\n transformFeedback: TransformFeedback | null = null;\n\n /** The underlying GPU \"program\". @note May be recreated if parameters change */\n pipeline: RenderPipeline;\n\n /** ShaderInputs instance */\n // @ts-expect-error Assigned in function called by constructor\n shaderInputs: ShaderInputs;\n material: Material | null = null;\n // @ts-expect-error Assigned in function called by constructor\n _uniformStore: UniformStore;\n\n _attributeInfos: Record = {};\n _gpuGeometry: GPUGeometry | null = null;\n private props: Required;\n\n _pipelineNeedsUpdate: string | false = 'newly created';\n private _needsRedraw: string | false = 'initializing';\n private _destroyed = false;\n\n /** \"Time\" of last draw. Monotonically increasing timestamp */\n _lastDrawTimestamp: number = -1;\n private _bindingTable: ShaderBindingDebugRow[] = [];\n\n get [Symbol.toStringTag](): string {\n return 'Model';\n }\n\n toString(): string {\n return `Model(${this.id})`;\n }\n\n constructor(device: Device, props: ModelProps) {\n this.props = {...Model.defaultProps, ...props};\n props = this.props;\n this.id = props.id || uid('model');\n this.device = device;\n\n Object.assign(this.userData, props.userData);\n\n this.material = props.material || null;\n\n // Setup shader module inputs\n const moduleMap = Object.fromEntries(\n this.props.modules?.map(module => [module.name, module]) || []\n );\n\n const shaderInputs =\n props.shaderInputs ||\n new ShaderInputs(moduleMap, {disableWarnings: this.props.disableWarnings});\n // @ts-ignore\n this.setShaderInputs(shaderInputs);\n\n // Setup shader assembler\n const platformInfo = getPlatformInfo(device);\n\n // Extract modules from shader inputs if not supplied\n const modules =\n // @ts-ignore shaderInputs is assigned in setShaderInputs above.\n (this.props.modules?.length > 0 ? this.props.modules : this.shaderInputs?.getModules()) || [];\n\n this.props.shaderLayout =\n mergeShaderModuleBindingsIntoLayout(this.props.shaderLayout, modules) || null;\n\n const isWebGPU = this.device.type === 'webgpu';\n\n // WebGPU\n // TODO - hack to support unified WGSL shader\n // TODO - this is wrong, compile a single shader\n if (isWebGPU && this.props.source) {\n // WGSL\n const {source, getUniforms, bindingTable} = this.props.shaderAssembler.assembleWGSLShader({\n platformInfo,\n ...this.props,\n modules\n });\n this.source = source;\n // @ts-expect-error\n this._getModuleUniforms = getUniforms;\n this._bindingTable = bindingTable;\n // Extract shader layout after modules have been added to WGSL source, to include any bindings added by modules\n const inferredShaderLayout = (\n device as Device & {getShaderLayout?: (source: string) => any}\n ).getShaderLayout?.(this.source);\n this.props.shaderLayout =\n mergeShaderModuleBindingsIntoLayout(\n this.props.shaderLayout || inferredShaderLayout || null,\n modules\n ) || null;\n } else {\n // GLSL\n const {vs, fs, getUniforms} = this.props.shaderAssembler.assembleGLSLShaderPair({\n platformInfo,\n ...this.props,\n modules\n });\n\n this.vs = vs;\n this.fs = fs;\n // @ts-expect-error\n this._getModuleUniforms = getUniforms;\n this._bindingTable = [];\n }\n\n this.vertexCount = this.props.vertexCount;\n this.instanceCount = this.props.instanceCount;\n\n this.topology = this.props.topology;\n this.bufferLayout = this.props.bufferLayout;\n this.parameters = this.props.parameters;\n\n // Geometry, if provided, sets topology and vertex cound\n if (props.geometry) {\n this.setGeometry(props.geometry);\n }\n\n this.pipelineFactory =\n props.pipelineFactory || PipelineFactory.getDefaultPipelineFactory(this.device);\n this.shaderFactory = props.shaderFactory || ShaderFactory.getDefaultShaderFactory(this.device);\n\n // Create the pipeline\n // @note order is important\n this.pipeline = this._updatePipeline();\n\n this.vertexArray = device.createVertexArray({\n shaderLayout: this.pipeline.shaderLayout,\n bufferLayout: this.pipeline.bufferLayout\n });\n\n // Now we can apply geometry attributes\n if (this._gpuGeometry) {\n this._setGeometryAttributes(this._gpuGeometry);\n }\n\n // Apply any dynamic settings that will not trigger pipeline change\n if ('isInstanced' in props) {\n this.isInstanced = props.isInstanced;\n }\n\n if (props.instanceCount) {\n this.setInstanceCount(props.instanceCount);\n }\n if (props.vertexCount) {\n this.setVertexCount(props.vertexCount);\n }\n if (props.indexBuffer) {\n this.setIndexBuffer(props.indexBuffer);\n }\n if (props.attributes) {\n this.setAttributes(props.attributes);\n }\n if (props.constantAttributes) {\n this.setConstantAttributes(props.constantAttributes);\n }\n if (props.bindings) {\n this.setBindings(props.bindings);\n }\n if (props.transformFeedback) {\n this.transformFeedback = props.transformFeedback;\n }\n }\n\n destroy(): void {\n if (!this._destroyed) {\n // Release pipeline before we destroy the shaders used by the pipeline\n this.pipelineFactory.release(this.pipeline);\n // Release the shaders\n this.shaderFactory.release(this.pipeline.vs);\n if (this.pipeline.fs && this.pipeline.fs !== this.pipeline.vs) {\n this.shaderFactory.release(this.pipeline.fs);\n }\n this._uniformStore.destroy();\n // TODO - mark resource as managed and destroyIfManaged() ?\n this._gpuGeometry?.destroy();\n this._destroyed = true;\n }\n }\n\n // Draw call\n\n /** Query redraw status. Clears the status. */\n needsRedraw(): false | string {\n // Catch any writes to already bound resources\n if (this._getBindingsUpdateTimestamp() > this._lastDrawTimestamp) {\n this.setNeedsRedraw('contents of bound textures or buffers updated');\n }\n const needsRedraw = this._needsRedraw;\n this._needsRedraw = false;\n return needsRedraw;\n }\n\n /** Mark the model as needing a redraw */\n setNeedsRedraw(reason: string): void {\n this._needsRedraw ||= reason;\n }\n\n /** Returns WGSL binding debug rows for the assembled shader. Returns an empty array for GLSL models. */\n getBindingDebugTable(): readonly ShaderBindingDebugRow[] {\n return this._bindingTable;\n }\n\n /** Update uniforms and pipeline state prior to drawing. */\n predraw(): void {\n // Update uniform buffers if needed\n this.updateShaderInputs();\n // Check if the pipeline is invalidated\n this.pipeline = this._updatePipeline();\n }\n\n /**\n * Issue one draw call.\n * @param renderPass - render pass to draw into\n * @returns `true` if the draw call was executed, `false` if resources were not ready.\n */\n draw(renderPass: RenderPass): boolean {\n const loadingBinding = this._areBindingsLoading();\n if (loadingBinding) {\n log.info(LOG_DRAW_PRIORITY, `>>> DRAWING ABORTED ${this.id}: ${loadingBinding} not loaded`)();\n return false;\n }\n\n try {\n renderPass.pushDebugGroup(`${this}.predraw(${renderPass})`);\n this.predraw();\n } finally {\n renderPass.popDebugGroup();\n }\n\n let drawSuccess: boolean;\n let pipelineErrored = this.pipeline.isErrored;\n try {\n renderPass.pushDebugGroup(`${this}.draw(${renderPass})`);\n this._logDrawCallStart();\n\n // Update the pipeline if invalidated\n // TODO - inside RenderPass is likely the worst place to do this from performance perspective.\n // Application can call Model.predraw() to avoid this.\n this.pipeline = this._updatePipeline();\n pipelineErrored = this.pipeline.isErrored;\n\n if (pipelineErrored) {\n log.info(\n LOG_DRAW_PRIORITY,\n `>>> DRAWING ABORTED ${this.id}: ${PIPELINE_INITIALIZATION_FAILED}`\n )();\n drawSuccess = false;\n } else {\n const syncBindings = this._getBindings();\n const syncBindGroups = this._getBindGroups();\n\n const {indexBuffer} = this.vertexArray;\n const indexCount = indexBuffer\n ? indexBuffer.byteLength / (indexBuffer.indexType === 'uint32' ? 4 : 2)\n : undefined;\n\n drawSuccess = this.pipeline.draw({\n renderPass,\n vertexArray: this.vertexArray,\n isInstanced: this.isInstanced,\n vertexCount: this.vertexCount,\n instanceCount: this.instanceCount,\n indexCount,\n transformFeedback: this.transformFeedback || undefined,\n // Pipelines may be shared across models when caching is enabled, so bindings\n // and WebGL uniforms must be supplied on every draw instead of being stored\n // on the pipeline instance.\n bindings: syncBindings,\n bindGroups: syncBindGroups,\n _bindGroupCacheKeys: this._getBindGroupCacheKeys(),\n uniforms: this.props.uniforms,\n // WebGL shares underlying cached pipelines even for models that have different parameters and topology,\n // so we must provide our unique parameters to each draw\n // (In WebGPU most parameters are encoded in the pipeline and cannot be changed per draw call)\n parameters: this.parameters,\n topology: this.topology\n });\n }\n } finally {\n renderPass.popDebugGroup();\n this._logDrawCallEnd();\n }\n this._logFramebuffer(renderPass);\n\n // Update needsRedraw flag\n if (drawSuccess) {\n this._lastDrawTimestamp = this.device.timestamp;\n this._needsRedraw = false;\n } else if (pipelineErrored) {\n this._needsRedraw = PIPELINE_INITIALIZATION_FAILED;\n } else {\n this._needsRedraw = 'waiting for resource initialization';\n }\n return drawSuccess;\n }\n\n // Update fixed fields (can trigger pipeline rebuild)\n\n /**\n * Updates the optional geometry\n * Geometry, set topology and bufferLayout\n * @note Can trigger a pipeline rebuild / pipeline cache fetch on WebGPU\n */\n setGeometry(geometry: GPUGeometry | Geometry | null): void {\n this._gpuGeometry?.destroy();\n const gpuGeometry = geometry && makeGPUGeometry(this.device, geometry);\n if (gpuGeometry) {\n this.setTopology(gpuGeometry.topology || 'triangle-list');\n const bufferLayoutHelper = new BufferLayoutHelper(this.bufferLayout);\n this.bufferLayout = bufferLayoutHelper.mergeBufferLayouts(\n gpuGeometry.bufferLayout,\n this.bufferLayout\n );\n if (this.vertexArray) {\n this._setGeometryAttributes(gpuGeometry);\n }\n }\n this._gpuGeometry = gpuGeometry;\n }\n\n /**\n * Updates the primitive topology ('triangle-list', 'triangle-strip' etc).\n * @note Triggers a pipeline rebuild / pipeline cache fetch on WebGPU\n */\n setTopology(topology: PrimitiveTopology): void {\n if (topology !== this.topology) {\n this.topology = topology;\n this._setPipelineNeedsUpdate('topology');\n }\n }\n\n /**\n * Updates the buffer layout.\n * @note Triggers a pipeline rebuild / pipeline cache fetch\n */\n setBufferLayout(bufferLayout: BufferLayout[]): void {\n const bufferLayoutHelper = new BufferLayoutHelper(this.bufferLayout);\n this.bufferLayout = this._gpuGeometry\n ? bufferLayoutHelper.mergeBufferLayouts(bufferLayout, this._gpuGeometry.bufferLayout)\n : bufferLayout;\n this._setPipelineNeedsUpdate('bufferLayout');\n\n // Recreate the pipeline\n this.pipeline = this._updatePipeline();\n\n // vertex array needs to be updated if we update buffer layout,\n // but not if we update parameters\n this.vertexArray = this.device.createVertexArray({\n shaderLayout: this.pipeline.shaderLayout,\n bufferLayout: this.pipeline.bufferLayout\n });\n\n // Reapply geometry attributes to the new vertex array\n if (this._gpuGeometry) {\n this._setGeometryAttributes(this._gpuGeometry);\n }\n }\n\n /**\n * Set GPU parameters.\n * @note Can trigger a pipeline rebuild / pipeline cache fetch.\n * @param parameters\n */\n setParameters(parameters: RenderPipelineParameters) {\n if (!deepEqual(parameters, this.parameters, 2)) {\n this.parameters = parameters;\n this._setPipelineNeedsUpdate('parameters');\n }\n }\n\n // Update dynamic fields\n\n /**\n * Updates the instance count (used in draw calls)\n * @note Any attributes with stepMode=instance need to be at least this big\n */\n setInstanceCount(instanceCount: number): void {\n this.instanceCount = instanceCount;\n // luma.gl examples don't set props.isInstanced and rely on auto-detection\n // but deck.gl sets instanceCount even for models that are not instanced.\n if (this.isInstanced === undefined && instanceCount > 0) {\n this.isInstanced = true;\n }\n this.setNeedsRedraw('instanceCount');\n }\n\n /**\n * Updates the vertex count (used in draw calls)\n * @note Any attributes with stepMode=vertex need to be at least this big\n */\n setVertexCount(vertexCount: number): void {\n this.vertexCount = vertexCount;\n this.setNeedsRedraw('vertexCount');\n }\n\n /** Set the shader inputs */\n setShaderInputs(shaderInputs: ShaderInputs): void {\n this.shaderInputs = shaderInputs;\n this._uniformStore = new UniformStore(this.device, this.shaderInputs.modules);\n // Create uniform buffer bindings for all modules that actually have uniforms\n for (const [moduleName, module] of Object.entries(this.shaderInputs.modules)) {\n if (shaderModuleHasUniforms(module) && !this.material?.ownsModule(moduleName)) {\n const uniformBuffer = this._uniformStore.getManagedUniformBuffer(moduleName);\n this.bindings[`${moduleName}Uniforms`] = uniformBuffer;\n }\n }\n this.setNeedsRedraw('shaderInputs');\n }\n\n setMaterial(material: Material | null): void {\n this.material = material;\n this.setNeedsRedraw('material');\n }\n\n /** Update uniform buffers from the model's shader inputs */\n updateShaderInputs(): void {\n this._uniformStore.setUniforms(this.shaderInputs.getUniformValues());\n this.setBindings(this._getNonMaterialBindings(this.shaderInputs.getBindingValues()));\n // TODO - this is already tracked through buffer/texture update times?\n this.setNeedsRedraw('shaderInputs');\n }\n\n /**\n * Sets bindings (textures, samplers, uniform buffers)\n */\n setBindings(bindings: Record): void {\n Object.assign(this.bindings, bindings);\n this.setNeedsRedraw('bindings');\n }\n\n /**\n * Updates optional transform feedback. WebGL only.\n */\n setTransformFeedback(transformFeedback: TransformFeedback | null): void {\n this.transformFeedback = transformFeedback;\n this.setNeedsRedraw('transformFeedback');\n }\n\n /**\n * Sets the index buffer\n * @todo - how to unset it if we change geometry?\n */\n setIndexBuffer(indexBuffer: Buffer | null): void {\n this.vertexArray.setIndexBuffer(indexBuffer);\n this.setNeedsRedraw('indexBuffer');\n }\n\n /**\n * Sets attributes (buffers)\n * @note Overrides any attributes previously set with the same name\n */\n setAttributes(buffers: Record, options?: {disableWarnings?: boolean}): void {\n const disableWarnings = options?.disableWarnings ?? this.props.disableWarnings;\n if (buffers['indices']) {\n log.warn(\n `Model:${this.id} setAttributes() - indexBuffer should be set using setIndexBuffer()`\n )();\n }\n\n // ensure bufferLayout order matches source layout so we bind\n // the correct buffers to the correct indices in webgpu.\n this.bufferLayout = sortedBufferLayoutByShaderSourceLocations(\n this.pipeline.shaderLayout,\n this.bufferLayout\n );\n const bufferLayoutHelper = new BufferLayoutHelper(this.bufferLayout);\n\n // Check if all buffers have a layout\n for (const [bufferName, buffer] of Object.entries(buffers)) {\n const bufferLayout = bufferLayoutHelper.getBufferLayout(bufferName);\n if (!bufferLayout) {\n if (!disableWarnings) {\n log.warn(`Model(${this.id}): Missing layout for buffer \"${bufferName}\".`)();\n }\n continue; // eslint-disable-line no-continue\n }\n\n // In WebGL, for an interleaved attribute we may need to set multiple attributes\n // but in WebGPU, we set it according to the buffer's position in the vertexArray\n const attributeNames = bufferLayoutHelper.getAttributeNamesForBuffer(bufferLayout);\n let set = false;\n for (const attributeName of attributeNames) {\n const attributeInfo = this._attributeInfos[attributeName];\n if (attributeInfo) {\n const location =\n this.device.type === 'webgpu'\n ? bufferLayoutHelper.getBufferIndex(attributeInfo.bufferName)\n : attributeInfo.location;\n\n this.vertexArray.setBuffer(location, buffer);\n set = true;\n }\n }\n if (!set && !disableWarnings) {\n log.warn(\n `Model(${this.id}): Ignoring buffer \"${buffer.id}\" for unknown attribute \"${bufferName}\"`\n )();\n }\n }\n this.setNeedsRedraw('attributes');\n }\n\n /**\n * Sets constant attributes\n * @note Overrides any attributes previously set with the same name\n * Constant attributes are only supported in WebGL, not in WebGPU\n * Any attribute that is disabled in the current vertex array object\n * is read from the context's global constant value for that attribute location.\n * @param constantAttributes\n */\n setConstantAttributes(\n attributes: Record,\n options?: {disableWarnings?: boolean}\n ): void {\n for (const [attributeName, value] of Object.entries(attributes)) {\n const attributeInfo = this._attributeInfos[attributeName];\n if (attributeInfo) {\n this.vertexArray.setConstantWebGL(attributeInfo.location, value);\n } else if (!(options?.disableWarnings ?? this.props.disableWarnings)) {\n log.warn(\n `Model \"${this.id}: Ignoring constant supplied for unknown attribute \"${attributeName}\"`\n )();\n }\n }\n this.setNeedsRedraw('constants');\n }\n\n // INTERNAL METHODS\n\n /** Check that bindings are loaded. Returns id of first binding that is still loading. */\n _areBindingsLoading(): string | false {\n for (const binding of Object.values(this.bindings)) {\n if (binding instanceof DynamicTexture && !binding.isReady) {\n return binding.id;\n }\n }\n for (const binding of Object.values(this.material?.bindings || {})) {\n if (binding instanceof DynamicTexture && !binding.isReady) {\n return binding.id;\n }\n }\n return false;\n }\n\n /** Extracts texture view from loaded async textures. Returns null if any textures have not yet been loaded. */\n _getBindings(): Record {\n const validBindings: Record = {};\n\n for (const [name, binding] of Object.entries(this.bindings)) {\n if (binding instanceof DynamicTexture) {\n // Check that async textures are loaded\n if (binding.isReady) {\n validBindings[name] = binding.texture;\n }\n } else {\n validBindings[name] = binding;\n }\n }\n\n return validBindings;\n }\n\n _getBindGroups(): BindingsByGroup {\n const shaderLayout = this.pipeline?.shaderLayout || this.props.shaderLayout || {bindings: []};\n const bindGroups = shaderLayout.bindings.length\n ? normalizeBindingsByGroup(shaderLayout, this._getBindings())\n : {0: this._getBindings()};\n\n if (!this.material) {\n return bindGroups;\n }\n\n for (const [groupKey, groupBindings] of Object.entries(this.material.getBindingsByGroup())) {\n const group = Number(groupKey);\n bindGroups[group] = {\n ...(bindGroups[group] || {}),\n ...groupBindings\n };\n }\n\n return bindGroups;\n }\n\n _getBindGroupCacheKeys(): Partial> {\n const bindGroupCacheKey = this.material?.getBindGroupCacheKey(3);\n return bindGroupCacheKey ? {3: bindGroupCacheKey} : {};\n }\n\n /** Get the timestamp of the latest updated bound GPU memory resource (buffer/texture). */\n _getBindingsUpdateTimestamp(): number {\n let timestamp = 0;\n for (const binding of Object.values(this.bindings)) {\n if (binding instanceof TextureView) {\n timestamp = Math.max(timestamp, binding.texture.updateTimestamp);\n } else if (binding instanceof Buffer || binding instanceof Texture) {\n timestamp = Math.max(timestamp, binding.updateTimestamp);\n } else if (binding instanceof DynamicTexture) {\n timestamp = binding.texture\n ? Math.max(timestamp, binding.texture.updateTimestamp)\n : // The texture will become available in the future\n Infinity;\n } else if (!(binding instanceof Sampler)) {\n timestamp = Math.max(timestamp, binding.buffer.updateTimestamp);\n }\n }\n return Math.max(timestamp, this.material?.getBindingsUpdateTimestamp() || 0);\n }\n\n /**\n * Updates the optional geometry attributes\n * Geometry, sets several attributes, indexBuffer, and also vertex count\n * @note Can trigger a pipeline rebuild / pipeline cache fetch on WebGPU\n */\n _setGeometryAttributes(gpuGeometry: GPUGeometry): void {\n // Filter geometry attribute so that we don't issue warnings for unused attributes\n const attributes = {...gpuGeometry.attributes};\n for (const [attributeName] of Object.entries(attributes)) {\n if (\n !this.pipeline.shaderLayout.attributes.find(layout => layout.name === attributeName) &&\n attributeName !== 'positions'\n ) {\n delete attributes[attributeName];\n }\n }\n\n // TODO - delete previous geometry?\n this.vertexCount = gpuGeometry.vertexCount;\n this.setIndexBuffer(gpuGeometry.indices || null);\n this.setAttributes(gpuGeometry.attributes, {disableWarnings: true});\n this.setAttributes(attributes, {disableWarnings: this.props.disableWarnings});\n\n this.setNeedsRedraw('geometry attributes');\n }\n\n /** Mark pipeline as needing update */\n _setPipelineNeedsUpdate(reason: string): void {\n this._pipelineNeedsUpdate ||= reason;\n this.setNeedsRedraw(reason);\n }\n\n /** Update pipeline if needed */\n _updatePipeline(): RenderPipeline {\n if (this._pipelineNeedsUpdate) {\n let prevShaderVs: Shader | null = null;\n let prevShaderFs: Shader | null = null;\n if (this.pipeline) {\n log.log(\n 1,\n `Model ${this.id}: Recreating pipeline because \"${this._pipelineNeedsUpdate}\".`\n )();\n prevShaderVs = this.pipeline.vs;\n prevShaderFs = this.pipeline.fs;\n }\n\n this._pipelineNeedsUpdate = false;\n\n const vs = this.shaderFactory.createShader({\n id: `${this.id}-vertex`,\n stage: 'vertex',\n source: this.source || this.vs,\n debugShaders: this.props.debugShaders\n });\n\n let fs: Shader | null = null;\n if (this.source) {\n fs = vs;\n } else if (this.fs) {\n fs = this.shaderFactory.createShader({\n id: `${this.id}-fragment`,\n stage: 'fragment',\n source: this.source || this.fs,\n debugShaders: this.props.debugShaders\n });\n }\n\n this.pipeline = this.pipelineFactory.createRenderPipeline({\n ...this.props,\n bindings: undefined,\n bufferLayout: this.bufferLayout,\n topology: this.topology,\n parameters: this.parameters,\n bindGroups: this._getBindGroups(),\n vs,\n fs\n });\n\n this._attributeInfos = getAttributeInfosFromLayouts(\n this.pipeline.shaderLayout,\n this.bufferLayout\n );\n\n if (prevShaderVs) this.shaderFactory.release(prevShaderVs);\n if (prevShaderFs && prevShaderFs !== prevShaderVs) {\n this.shaderFactory.release(prevShaderFs);\n }\n }\n return this.pipeline;\n }\n\n /** Throttle draw call logging */\n _lastLogTime = 0;\n _logOpen = false;\n\n _logDrawCallStart(): void {\n // IF level is 4 or higher, log every frame.\n const logDrawTimeout = log.level > 3 ? 0 : LOG_DRAW_TIMEOUT;\n if (log.level < 2 || Date.now() - this._lastLogTime < logDrawTimeout) {\n return;\n }\n\n this._lastLogTime = Date.now();\n this._logOpen = true;\n\n log.group(LOG_DRAW_PRIORITY, `>>> DRAWING MODEL ${this.id}`, {collapsed: log.level <= 2})();\n }\n\n _logDrawCallEnd(): void {\n if (this._logOpen) {\n const shaderLayoutTable = getDebugTableForShaderLayout(this.pipeline.shaderLayout, this.id);\n\n // log.table(logLevel, attributeTable)();\n // log.table(logLevel, uniformTable)();\n log.table(LOG_DRAW_PRIORITY, shaderLayoutTable)();\n\n const uniformTable = this.shaderInputs.getDebugTable();\n log.table(LOG_DRAW_PRIORITY, uniformTable)();\n\n const attributeTable = this._getAttributeDebugTable();\n log.table(LOG_DRAW_PRIORITY, this._attributeInfos)();\n log.table(LOG_DRAW_PRIORITY, attributeTable)();\n\n log.groupEnd(LOG_DRAW_PRIORITY)();\n this._logOpen = false;\n }\n }\n\n protected _drawCount = 0;\n _logFramebuffer(renderPass: RenderPass): void {\n const debugFramebuffers = this.device.props.debugFramebuffers;\n this._drawCount++;\n // Update first 3 frames and then every 60 frames\n if (!debugFramebuffers) {\n // } || (this._drawCount++ > 3 && this._drawCount % 60)) {\n return;\n }\n const framebuffer = renderPass.props.framebuffer;\n debugFramebuffer(renderPass, framebuffer, {\n id: framebuffer?.id || `${this.id}-framebuffer`,\n minimap: true\n });\n }\n\n _getAttributeDebugTable(): Record> {\n const table: Record> = {};\n for (const [name, attributeInfo] of Object.entries(this._attributeInfos)) {\n const values = this.vertexArray.attributes[attributeInfo.location];\n table[attributeInfo.location] = {\n name,\n type: attributeInfo.shaderType,\n values: values\n ? this._getBufferOrConstantValues(values, attributeInfo.bufferDataType)\n : 'null'\n };\n }\n if (this.vertexArray.indexBuffer) {\n const {indexBuffer} = this.vertexArray;\n const values =\n indexBuffer.indexType === 'uint32'\n ? new Uint32Array(indexBuffer.debugData)\n : new Uint16Array(indexBuffer.debugData);\n table['indices'] = {\n name: 'indices',\n type: indexBuffer.indexType,\n values: values.toString()\n };\n }\n return table;\n }\n\n // TODO - fix typing of luma data types\n _getBufferOrConstantValues(attribute: Buffer | TypedArray, dataType: any): string {\n const TypedArrayConstructor = dataTypeDecoder.getTypedArrayConstructor(dataType);\n const typedArray =\n attribute instanceof Buffer ? new TypedArrayConstructor(attribute.debugData) : attribute;\n return typedArray.toString();\n }\n\n private _getNonMaterialBindings(\n bindings: Record\n ): Record {\n if (!this.material) {\n return bindings;\n }\n\n const filteredBindings: Record = {};\n for (const [name, binding] of Object.entries(bindings)) {\n if (!this.material.ownsBinding(name)) {\n filteredBindings[name] = binding;\n }\n }\n return filteredBindings;\n }\n}\n\n// HELPERS\n\n/** Create a shadertools platform info from the Device */\nexport function getPlatformInfo(device: Device): PlatformInfo {\n return {\n type: device.type,\n shaderLanguage: device.info.shadingLanguage,\n shaderLanguageVersion: device.info.shadingLanguageVersion as 100 | 300,\n gpu: device.info.gpu,\n // HACK - we pretend that the DeviceFeatures is a Set, it has a similar API\n features: device.features as unknown as Set\n };\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {PrimitiveTopology, BufferLayout} from '@luma.gl/core';\nimport {Device, Buffer, vertexFormatDecoder} from '@luma.gl/core';\nimport type {Geometry} from '../geometry/geometry';\nimport {uid} from '../utils/uid';\n\nexport type GPUGeometryProps = {\n id?: string;\n /** Determines how vertices are read from the 'vertex' attributes */\n topology: 'point-list' | 'line-list' | 'line-strip' | 'triangle-list' | 'triangle-strip';\n /** Auto calculated from attributes if not provided */\n vertexCount: number;\n bufferLayout: BufferLayout[];\n indices?: Buffer | null;\n attributes: Record;\n};\n\nexport class GPUGeometry {\n readonly id: string;\n userData: Record = {};\n\n /** Determines how vertices are read from the 'vertex' attributes */\n readonly topology?: PrimitiveTopology;\n readonly bufferLayout: BufferLayout[] = [];\n\n readonly vertexCount: number;\n readonly indices?: Buffer | null;\n readonly attributes: Record;\n\n constructor(props: GPUGeometryProps) {\n this.id = props.id || uid('geometry');\n this.topology = props.topology;\n this.indices = props.indices || null;\n this.attributes = props.attributes;\n\n this.vertexCount = props.vertexCount;\n\n this.bufferLayout = props.bufferLayout || [];\n\n if (this.indices) {\n if (!(this.indices.usage & Buffer.INDEX)) {\n throw new Error('Index buffer must have INDEX usage');\n }\n }\n }\n\n destroy(): void {\n this.indices?.destroy();\n for (const attribute of Object.values(this.attributes)) {\n attribute.destroy();\n }\n }\n\n getVertexCount(): number {\n return this.vertexCount;\n }\n\n getAttributes(): Record {\n return this.attributes;\n }\n\n getIndexes(): Buffer | null {\n return this.indices || null;\n }\n\n _calculateVertexCount(positions: Buffer): number {\n // Assume that positions is a fully packed float32x3 buffer\n const vertexCount = positions.byteLength / 12;\n return vertexCount;\n }\n}\n\nexport function makeGPUGeometry(device: Device, geometry: Geometry | GPUGeometry): GPUGeometry {\n if (geometry instanceof GPUGeometry) {\n return geometry;\n }\n\n const indices = getIndexBufferFromGeometry(device, geometry);\n const {attributes, bufferLayout} = getAttributeBuffersFromGeometry(device, geometry);\n return new GPUGeometry({\n topology: geometry.topology || 'triangle-list',\n bufferLayout,\n vertexCount: geometry.vertexCount,\n indices,\n attributes\n });\n}\n\nexport function getIndexBufferFromGeometry(device: Device, geometry: Geometry): Buffer | undefined {\n if (!geometry.indices) {\n return undefined;\n }\n const data = geometry.indices.value;\n return device.createBuffer({usage: Buffer.INDEX, data});\n}\n\nexport function getAttributeBuffersFromGeometry(\n device: Device,\n geometry: Geometry\n): {attributes: Record; bufferLayout: BufferLayout[]; vertexCount: number} {\n const bufferLayout: BufferLayout[] = [];\n\n const attributes: Record = {};\n for (const [attributeName, attribute] of Object.entries(geometry.attributes)) {\n let name: string = attributeName;\n // TODO Map some GLTF attribute names (is this still needed?)\n switch (attributeName) {\n case 'POSITION':\n name = 'positions';\n break;\n case 'NORMAL':\n name = 'normals';\n break;\n case 'TEXCOORD_0':\n name = 'texCoords';\n break;\n case 'TEXCOORD_1':\n name = 'texCoords1';\n break;\n case 'COLOR_0':\n name = 'colors';\n break;\n }\n if (attribute) {\n attributes[name] = device.createBuffer({\n data: attribute.value,\n id: `${attributeName}-buffer`\n });\n const {value, size, normalized} = attribute;\n if (size === undefined) {\n throw new Error(`Attribute ${attributeName} is missing a size`);\n }\n bufferLayout.push({\n name,\n format: vertexFormatDecoder.getVertexFormatFromAttribute(value, size, normalized)\n });\n }\n }\n\n const vertexCount = geometry._calculateVertexCount(geometry.attributes, geometry.indices);\n\n return {attributes, bufferLayout, vertexCount};\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nconst uidCounters: Record = {};\n\n/**\n * Returns a UID.\n * @param id= - Identifier base name\n * @return uid\n **/\nexport function uid(id: string = 'id'): string {\n uidCounters[id] = uidCounters[id] || 1;\n const count = uidCounters[id]++;\n return `${id}-${count}`;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ShaderLayout} from '@luma.gl/core';\n\n/**\n * Extracts a table suitable for `console.table()` from a shader layout to assist in debugging.\n * @param layout shader layout\n * @param name app should provide the most meaningful name, usually the model or pipeline name / id.\n * @returns\n */\nexport function getDebugTableForShaderLayout(\n layout: ShaderLayout,\n name: string\n): Record> {\n const table: Record> = {};\n\n const header = 'Values'; // '`Shader Layout for ${name}`;\n\n if (layout.attributes.length === 0 && !layout.varyings?.length) {\n return {'No attributes or varyings': {[header]: 'N/A'}};\n }\n\n for (const attributeDeclaration of layout.attributes) {\n if (attributeDeclaration) {\n const glslDeclaration = `${attributeDeclaration.location} ${attributeDeclaration.name}: ${attributeDeclaration.type}`;\n table[`in ${glslDeclaration}`] = {[header]: attributeDeclaration.stepMode || 'vertex'};\n }\n }\n\n for (const varyingDeclaration of layout.varyings || []) {\n const glslDeclaration = `${varyingDeclaration.location} ${varyingDeclaration.name}`;\n table[`out ${glslDeclaration}`] = {[header]: JSON.stringify(varyingDeclaration)};\n }\n\n return table;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device, Framebuffer, RenderPass, Texture} from '@luma.gl/core';\n\nconst DEBUG_FRAMEBUFFER_STATE_KEY = '__debugFramebufferState';\nconst DEFAULT_MARGIN_PX = 8;\n\ntype DebugFramebufferOptions = {\n id: string;\n minimap?: boolean;\n opaque?: boolean;\n top?: string;\n left?: string;\n rgbaScale?: number;\n};\n\ntype DebugFramebufferState = {\n flushing: boolean;\n queuedFramebuffers: Framebuffer[];\n};\n\n/**\n * Debug utility to blit queued offscreen framebuffers into the default framebuffer\n * without CPU readback. Currently implemented for WebGL only.\n */\nexport function debugFramebuffer(\n renderPass: RenderPass,\n source: Framebuffer | Texture | null,\n options: DebugFramebufferOptions\n): void {\n if (renderPass.device.type !== 'webgl') {\n return;\n }\n\n const state = getDebugFramebufferState(renderPass.device);\n if (state.flushing) {\n return;\n }\n\n if (isDefaultRenderPass(renderPass)) {\n flushDebugFramebuffers(renderPass, options, state);\n return;\n }\n\n if (source && isFramebuffer(source) && source.handle !== null) {\n if (!state.queuedFramebuffers.includes(source)) {\n state.queuedFramebuffers.push(source);\n }\n }\n}\n\nfunction flushDebugFramebuffers(\n renderPass: RenderPass,\n options: DebugFramebufferOptions,\n state: DebugFramebufferState\n): void {\n if (state.queuedFramebuffers.length === 0) {\n return;\n }\n\n const webglDevice = renderPass.device as Device & {gl: WebGL2RenderingContext};\n const {gl} = webglDevice;\n const previousReadFramebuffer = gl.getParameter(gl.READ_FRAMEBUFFER_BINDING);\n const previousDrawFramebuffer = gl.getParameter(gl.DRAW_FRAMEBUFFER_BINDING);\n const [targetWidth, targetHeight] = renderPass.device\n .getDefaultCanvasContext()\n .getDrawingBufferSize();\n\n let topPx = parseCssPixel(options.top, DEFAULT_MARGIN_PX);\n const leftPx = parseCssPixel(options.left, DEFAULT_MARGIN_PX);\n\n state.flushing = true;\n try {\n for (const framebuffer of state.queuedFramebuffers) {\n const [targetX0, targetY0, targetX1, targetY1, previewHeight] = getOverlayRect({\n framebuffer,\n targetWidth,\n targetHeight,\n topPx,\n leftPx,\n minimap: options.minimap\n });\n\n gl.bindFramebuffer(gl.READ_FRAMEBUFFER, framebuffer.handle as WebGLFramebuffer | null);\n gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);\n gl.blitFramebuffer(\n 0,\n 0,\n framebuffer.width,\n framebuffer.height,\n targetX0,\n targetY0,\n targetX1,\n targetY1,\n gl.COLOR_BUFFER_BIT,\n gl.NEAREST\n );\n\n topPx += previewHeight + DEFAULT_MARGIN_PX;\n }\n } finally {\n gl.bindFramebuffer(gl.READ_FRAMEBUFFER, previousReadFramebuffer);\n gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, previousDrawFramebuffer);\n state.flushing = false;\n }\n}\n\nfunction getOverlayRect(options: {\n framebuffer: Framebuffer;\n targetWidth: number;\n targetHeight: number;\n topPx: number;\n leftPx: number;\n minimap?: boolean;\n}): [number, number, number, number, number] {\n const {framebuffer, targetWidth, targetHeight, topPx, leftPx, minimap} = options;\n const maxWidth = minimap ? Math.max(Math.floor(targetWidth / 4), 1) : targetWidth;\n const maxHeight = minimap ? Math.max(Math.floor(targetHeight / 4), 1) : targetHeight;\n const scale = Math.min(maxWidth / framebuffer.width, maxHeight / framebuffer.height);\n const previewWidth = Math.max(Math.floor(framebuffer.width * scale), 1);\n const previewHeight = Math.max(Math.floor(framebuffer.height * scale), 1);\n const targetX0 = leftPx;\n const targetY0 = Math.max(targetHeight - topPx - previewHeight, 0);\n const targetX1 = targetX0 + previewWidth;\n const targetY1 = targetY0 + previewHeight;\n return [targetX0, targetY0, targetX1, targetY1, previewHeight];\n}\n\nfunction getDebugFramebufferState(device: Device): DebugFramebufferState {\n device.userData[DEBUG_FRAMEBUFFER_STATE_KEY] ||= {\n flushing: false,\n queuedFramebuffers: []\n } satisfies DebugFramebufferState;\n return device.userData[DEBUG_FRAMEBUFFER_STATE_KEY] as DebugFramebufferState;\n}\n\nfunction isFramebuffer(value: Framebuffer | Texture): value is Framebuffer {\n return 'colorAttachments' in value;\n}\n\nfunction isDefaultRenderPass(renderPass: RenderPass): boolean {\n const framebuffer = renderPass.props.framebuffer as {handle?: unknown} | null;\n return !framebuffer || framebuffer.handle === null;\n}\n\nfunction parseCssPixel(value: string | undefined, defaultValue: number): number {\n if (!value) {\n return defaultValue;\n }\n const parsedValue = Number.parseInt(value, 10);\n return Number.isFinite(parsedValue) ? parsedValue : defaultValue;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/**\n * Fast partial deep equal for prop.\n *\n * @param a Prop\n * @param b Prop to compare against `a`\n * @param depth Depth to which to recurse in nested Objects/Arrays. Use 0 (default) for shallow comparison, -1 for infinite depth\n */\n/* eslint-disable complexity */\nexport function deepEqual(a: any, b: any, depth: number): boolean {\n if (a === b) {\n return true;\n }\n if (!depth || !a || !b) {\n return false;\n }\n if (Array.isArray(a)) {\n if (!Array.isArray(b) || a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (!deepEqual(a[i], b[i], depth - 1)) {\n return false;\n }\n }\n return true;\n }\n if (Array.isArray(b)) {\n return false;\n }\n if (typeof a === 'object' && typeof b === 'object') {\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n if (aKeys.length !== bKeys.length) {\n return false;\n }\n for (const key of aKeys) {\n if (!b.hasOwnProperty(key)) {\n return false;\n }\n if (!deepEqual(a[key], b[key], depth - 1)) {\n return false;\n }\n }\n return true;\n }\n return false;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {log, type BufferLayout} from '@luma.gl/core';\n\n/** BufferLayoutHelper is a helper class that should not be used directly by applications */\nexport class BufferLayoutHelper {\n bufferLayouts: BufferLayout[];\n\n constructor(bufferLayouts: BufferLayout[]) {\n this.bufferLayouts = bufferLayouts;\n }\n\n getBufferLayout(name: string): BufferLayout | null {\n return this.bufferLayouts.find(layout => layout.name === name) || null;\n }\n\n /** Get attribute names from a BufferLayout */\n getAttributeNamesForBuffer(bufferLayout: BufferLayout): string[] {\n return bufferLayout.attributes\n ? bufferLayout.attributes?.map(layout => layout.attribute)\n : [bufferLayout.name];\n }\n\n mergeBufferLayouts(\n bufferLayouts1: BufferLayout[],\n bufferLayouts2: BufferLayout[]\n ): BufferLayout[] {\n const mergedLayouts = [...bufferLayouts1];\n for (const attribute of bufferLayouts2) {\n const index = mergedLayouts.findIndex(attribute2 => attribute2.name === attribute.name);\n if (index < 0) {\n mergedLayouts.push(attribute);\n } else {\n mergedLayouts[index] = attribute;\n }\n }\n return mergedLayouts;\n }\n\n getBufferIndex(bufferName: string): number {\n const bufferIndex = this.bufferLayouts.findIndex(layout => layout.name === bufferName);\n\n if (bufferIndex === -1) {\n log.warn(`BufferLayout: Missing buffer for \"${bufferName}\".`)();\n }\n\n return bufferIndex;\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {type BufferLayout, type ShaderLayout} from '@luma.gl/core';\n\nfunction getMinLocation(\n attributeNames: string[],\n shaderLayoutMap: Record\n): number {\n let minLocation = Infinity;\n\n for (const name of attributeNames) {\n const location = shaderLayoutMap[name];\n if (location !== undefined) {\n minLocation = Math.min(minLocation, location);\n }\n }\n\n return minLocation;\n}\n\nexport function sortedBufferLayoutByShaderSourceLocations(\n shaderLayout: ShaderLayout,\n bufferLayout: BufferLayout[]\n): BufferLayout[] {\n const shaderLayoutMap = Object.fromEntries(\n shaderLayout.attributes.map(attr => [attr.name, attr.location])\n );\n\n const sortedLayout = bufferLayout.slice();\n sortedLayout.sort((a, b) => {\n const attributeNamesA = a.attributes ? a.attributes.map(attr => attr.attribute) : [a.name];\n const attributeNamesB = b.attributes ? b.attributes.map(attr => attr.attribute) : [b.name];\n const minLocationA = getMinLocation(attributeNamesA, shaderLayoutMap);\n const minLocationB = getMinLocation(attributeNamesB, shaderLayoutMap);\n\n return minLocationA - minLocationB;\n });\n\n return sortedLayout;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ComputeShaderLayout, ShaderLayout} from '@luma.gl/core';\nimport type {ShaderModule} from '@luma.gl/shadertools';\n\ntype AnyShaderLayout = ShaderLayout | ComputeShaderLayout;\n\nexport function mergeShaderModuleBindingsIntoLayout(\n shaderLayout: TShaderLayout | null | undefined,\n modules: ShaderModule[]\n): TShaderLayout | null | undefined {\n if (!shaderLayout || !modules.some(module => module.bindingLayout?.length)) {\n return shaderLayout;\n }\n\n const mergedLayout = {\n ...shaderLayout,\n bindings: shaderLayout.bindings.map(binding => ({...binding}))\n } as TShaderLayout;\n\n if ('attributes' in (shaderLayout || {})) {\n (mergedLayout as ShaderLayout).attributes = (shaderLayout as ShaderLayout)?.attributes || [];\n }\n\n for (const module of modules) {\n for (const bindingLayout of module.bindingLayout || []) {\n for (const relatedBindingName of getRelatedBindingNames(bindingLayout.name)) {\n const binding = mergedLayout.bindings.find(\n candidate => candidate.name === relatedBindingName\n );\n if (binding?.group === 0) {\n binding.group = bindingLayout.group;\n }\n }\n }\n }\n\n return mergedLayout;\n}\n\nexport function shaderModuleHasUniforms(module: ShaderModule): boolean {\n return Boolean(module.uniformTypes && !isObjectEmpty(module.uniformTypes));\n}\n\n/** Returns binding-name aliases that should share the module-declared bind group. */\nfunction getRelatedBindingNames(bindingName: string): string[] {\n const bindingNames = new Set([bindingName, `${bindingName}Uniforms`]);\n\n if (!bindingName.endsWith('Uniforms')) {\n bindingNames.add(`${bindingName}Sampler`);\n }\n\n return [...bindingNames];\n}\n\nfunction isObjectEmpty(obj: object): boolean {\n // @ts-ignore key is intentionally unused\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n for (const key in obj) {\n return false;\n }\n return true;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Binding, CompositeShaderType} from '@luma.gl/core';\nimport {log} from '@luma.gl/core';\n// import type {VariableShaderType, UniformValue, UniformFormat, UniformInfoDevice, Texture, Sampler} from '@luma.gl/core';\nimport {\n getShaderModuleDependencies,\n ShaderModule,\n ShaderModuleUniformValue\n} from '@luma.gl/shadertools';\nimport {splitUniformsAndBindings} from './model/split-uniforms-and-bindings';\n\nexport type ShaderInputsOptions = {\n disableWarnings?: boolean;\n};\n\ntype ShaderInputsModule = Pick<\n ShaderModule,\n 'bindingLayout' | 'defaultUniforms' | 'dependencies' | 'getUniforms' | 'name' | 'uniformTypes'\n>;\n\n/**\n * ShaderInputs holds uniform and binding values for one or more shader modules,\n * - It can generate binary data for any uniform buffer\n * - It can manage a uniform buffer for each block\n * - It can update managed uniform buffers with a single call\n * - It performs some book keeping on what has changed to minimize unnecessary writes to uniform buffers.\n */\nexport class ShaderInputs<\n ShaderPropsT extends Partial>> = Partial<\n Record>\n >\n> {\n options: Required = {\n disableWarnings: false\n };\n\n /**\n * The map of modules\n * @todo should should this include the resolved dependencies?\n */\n // @ts-ignore Fix typings\n modules: Readonly<{[P in keyof ShaderPropsT]: ShaderInputsModule}>;\n\n /** Stores the uniform values for each module */\n moduleUniforms: Record>;\n /** Stores the uniform bindings for each module */\n moduleBindings: Record>;\n /** Tracks if uniforms have changed */\n // moduleUniformsChanged: Record;\n\n /**\n * Create a new UniformStore instance\n * @param modules\n */\n constructor(\n // @ts-ignore Fix typings\n modules: {[P in keyof ShaderPropsT]?: ShaderInputsModule},\n options?: ShaderInputsOptions\n ) {\n Object.assign(this.options, options);\n\n // Extract modules with dependencies\n const resolvedModules = getShaderModuleDependencies(\n Object.values(modules).filter(isShaderInputsModuleWithDependencies)\n );\n for (const resolvedModule of resolvedModules) {\n // @ts-ignore\n modules[resolvedModule.name] = resolvedModule;\n }\n\n log.log(1, 'Creating ShaderInputs with modules', Object.keys(modules))();\n\n // Store the module definitions and create storage for uniform values and binding values, per module\n // @ts-ignore Fix typings\n this.modules = modules as {[P in keyof ShaderPropsT]: ShaderInputsModule};\n this.moduleUniforms = {} as Record<\n keyof ShaderPropsT,\n Record\n >;\n this.moduleBindings = {} as Record>;\n\n // Initialize the modules\n for (const [name, module] of Object.entries(modules)) {\n if (module) {\n this._addModule(module);\n if (module.name && name !== module.name && !this.options.disableWarnings) {\n log.warn(`Module name: ${name} vs ${module.name}`)();\n }\n }\n }\n }\n\n /** Destroy */\n destroy(): void {}\n\n /**\n * Set module props\n */\n setProps(props: Partial<{[P in keyof ShaderPropsT]?: Partial}>): void {\n for (const name of Object.keys(props)) {\n const moduleName = name as keyof ShaderPropsT;\n const moduleProps = props[moduleName] || {};\n const module = this.modules[moduleName];\n if (!module) {\n // Ignore props for unregistered modules\n if (!this.options.disableWarnings) {\n log.warn(`Module ${name} not found`)();\n }\n } else {\n const oldUniforms = this.moduleUniforms[moduleName];\n const oldBindings = this.moduleBindings[moduleName];\n const uniformsAndBindings =\n module.getUniforms?.(moduleProps, oldUniforms) || (moduleProps as any);\n\n const {uniforms, bindings} = splitUniformsAndBindings(\n uniformsAndBindings,\n module.uniformTypes as Readonly>\n );\n this.moduleUniforms[moduleName] = mergeModuleUniforms(\n oldUniforms as Record,\n uniforms,\n module.uniformTypes as Readonly>\n );\n this.moduleBindings[moduleName] = {...oldBindings, ...bindings};\n // this.moduleUniformsChanged ||= moduleName;\n }\n\n // console.log(`setProps(${String(moduleName)}`, moduleName, this.moduleUniforms[moduleName])\n }\n }\n\n /**\n * Return the map of modules\n * @todo should should this include the resolved dependencies?\n */\n getModules(): ShaderModule[] {\n return Object.values(this.modules) as ShaderModule[];\n }\n\n /** Get all uniform values for all modules */\n getUniformValues(): Partial<\n Record>\n > {\n return this.moduleUniforms;\n }\n\n /** Merges all bindings for the shader (from the various modules) */\n getBindingValues(): Record {\n const bindings = {} as Record;\n for (const moduleBindings of Object.values(this.moduleBindings)) {\n Object.assign(bindings, moduleBindings);\n }\n return bindings;\n }\n\n // INTERNAL\n\n /** Return a debug table that can be used for console.table() or log.table() */\n getDebugTable(): Record> {\n const table: Record> = {};\n for (const [moduleName, module] of Object.entries(this.moduleUniforms)) {\n for (const [key, value] of Object.entries(module)) {\n table[`${moduleName}.${key}`] = {\n type: this.modules[moduleName].uniformTypes?.[key as keyof ShaderPropsT],\n value: String(value)\n };\n }\n }\n return table;\n }\n\n _addModule(module: ShaderInputsModule): void {\n const moduleName = module.name as keyof ShaderPropsT;\n // Get default uniforms from module\n this.moduleUniforms[moduleName] = mergeModuleUniforms(\n {},\n (module.defaultUniforms || {}) as Record,\n module.uniformTypes as Readonly>\n );\n this.moduleBindings[moduleName] = {};\n }\n}\n\nfunction mergeModuleUniforms(\n currentUniforms: Record = {},\n nextUniforms: Record = {},\n uniformTypes: Readonly> = {}\n): Record {\n const mergedUniforms = {...currentUniforms};\n for (const [key, value] of Object.entries(nextUniforms)) {\n if (value !== undefined) {\n mergedUniforms[key] = mergeModuleUniformValue(currentUniforms[key], value, uniformTypes[key]);\n }\n }\n return mergedUniforms;\n}\n\nfunction mergeModuleUniformValue(\n currentValue: ShaderModuleUniformValue | undefined,\n nextValue: ShaderModuleUniformValue,\n uniformType: CompositeShaderType | undefined\n): ShaderModuleUniformValue {\n if (!uniformType || typeof uniformType === 'string') {\n return cloneModuleUniformValue(nextValue);\n }\n\n if (Array.isArray(uniformType)) {\n if (isPackedUniformArrayValue(nextValue) || !Array.isArray(nextValue)) {\n return cloneModuleUniformValue(nextValue);\n }\n\n const currentArray: Array =\n Array.isArray(currentValue) && !isPackedUniformArrayValue(currentValue)\n ? [...currentValue]\n : [];\n const mergedArray = currentArray.slice();\n for (let index = 0; index < nextValue.length; index++) {\n const elementValue = nextValue[index];\n if (elementValue !== undefined) {\n mergedArray[index] = mergeModuleUniformValue(\n currentArray[index],\n elementValue,\n uniformType[0] as CompositeShaderType\n );\n }\n }\n return mergedArray;\n }\n\n if (!isPlainUniformObject(nextValue)) {\n return cloneModuleUniformValue(nextValue);\n }\n\n const uniformStruct = uniformType as Record;\n const currentObject = isPlainUniformObject(currentValue) ? currentValue : {};\n const mergedObject: Record = {...currentObject};\n for (const [key, value] of Object.entries(nextValue)) {\n if (value !== undefined) {\n mergedObject[key] = mergeModuleUniformValue(currentObject[key], value, uniformStruct[key]);\n }\n }\n return mergedObject as ShaderModuleUniformValue;\n}\n\nfunction cloneModuleUniformValue(value: ShaderModuleUniformValue): ShaderModuleUniformValue {\n if (ArrayBuffer.isView(value)) {\n return Array.prototype.slice.call(value) as ShaderModuleUniformValue;\n }\n\n if (Array.isArray(value)) {\n if (isPackedUniformArrayValue(value)) {\n return value.slice() as ShaderModuleUniformValue;\n }\n\n const compositeArray = value as ReadonlyArray;\n return compositeArray.map(element =>\n element === undefined ? undefined : cloneModuleUniformValue(element)\n ) as ShaderModuleUniformValue;\n }\n\n if (isPlainUniformObject(value)) {\n return Object.fromEntries(\n Object.entries(value).map(([key, nestedValue]) => [\n key,\n nestedValue === undefined ? undefined : cloneModuleUniformValue(nestedValue)\n ])\n ) as ShaderModuleUniformValue;\n }\n\n return value;\n}\n\nfunction isPackedUniformArrayValue(\n value: unknown\n): value is ReadonlyArray | ArrayBufferView {\n return (\n ArrayBuffer.isView(value) ||\n (Array.isArray(value) && (value.length === 0 || typeof value[0] === 'number'))\n );\n}\n\nfunction isPlainUniformObject(\n value: unknown\n): value is Record {\n return (\n Boolean(value) &&\n typeof value === 'object' &&\n !Array.isArray(value) &&\n !ArrayBuffer.isView(value)\n );\n}\n\nfunction isShaderInputsModuleWithDependencies(\n module: ShaderInputsModule | undefined\n): module is ShaderInputsModule & {dependencies: NonNullable} {\n return Boolean(module?.dependencies);\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Binding, CompositeShaderType, UniformValue} from '@luma.gl/core';\nimport type {ShaderModuleUniformValue} from '@luma.gl/shadertools';\nimport {isNumericArray} from '@math.gl/types';\n\nexport function isUniformValue(value: unknown): value is UniformValue {\n return isNumericArray(value) || typeof value === 'number' || typeof value === 'boolean';\n}\n\ntype UniformsAndBindings = {\n bindings: Record;\n uniforms: Record;\n};\n\nexport function splitUniformsAndBindings(\n uniforms: Record,\n uniformTypes: Readonly> = {}\n): UniformsAndBindings {\n const result: UniformsAndBindings = {bindings: {}, uniforms: {}};\n Object.keys(uniforms).forEach(name => {\n const uniform = uniforms[name];\n if (Object.prototype.hasOwnProperty.call(uniformTypes, name) || isUniformValue(uniform)) {\n result.uniforms[name] = uniform as ShaderModuleUniformValue;\n } else {\n result.bindings[name] = uniform as Binding;\n }\n });\n\n return result;\n}\n","// luma.gl, MIT license\n// Copyright (c) vis.gl contributors\n\nimport type {\n TextureProps,\n SamplerProps,\n TextureView,\n Device,\n TextureFormat,\n TextureReadOptions\n} from '@luma.gl/core';\n\nimport {Buffer, Texture, Sampler, log} from '@luma.gl/core';\n\n// import {loadImageBitmap} from '../application-utils/load-file';\nimport {uid} from '../utils/uid';\nimport {\n // cube constants\n type TextureCubeFace,\n TEXTURE_CUBE_FACE_MAP,\n // texture slice/mip data types\n type TextureSubresource,\n // props (dimension + data)\n type TextureDataProps,\n type TextureDataAsyncProps,\n // combined data for different texture types\n type Texture1DData,\n type Texture2DData,\n type Texture3DData,\n type TextureArrayData,\n type TextureCubeArrayData,\n type TextureCubeData,\n // Helpers\n getTextureSizeFromData,\n resolveTextureImageFormat,\n getTexture1DSubresources,\n getTexture2DSubresources,\n getTexture3DSubresources,\n getTextureCubeSubresources,\n getTextureArraySubresources,\n getTextureCubeArraySubresources\n} from './texture-data';\n\n/**\n * Properties for a dynamic texture\n */\nexport type DynamicTextureProps = Omit &\n TextureDataAsyncProps & {\n /** Generate mipmaps after creating textures and setting data */\n mipmaps?: boolean;\n /** nipLevels can be set to 'auto' to generate max number of mipLevels */\n mipLevels?: number | 'auto';\n /** Width - can be auto-calculated when initializing from ExternalImage */\n width?: number;\n /** Height - can be auto-calculated when initializing from ExternalImage */\n height?: number;\n };\n\n/**\n * Dynamic Textures\n *\n * - Mipmaps - DynamicTexture can generate mipmaps for textures (WebGPU does not provide built-in mipmap generation).\n *\n * - Texture initialization and updates - complex textures (2d array textures, cube textures, 3d textures) need multiple images\n * `DynamicTexture` provides an API that makes it easy to provide the required data.\n *\n * - Texture resizing - Textures are immutable in WebGPU, meaning that they cannot be resized after creation.\n * DynamicTexture provides a `resize()` method that internally creates a new texture with the same parameters\n * but a different size.\n *\n * - Async image data initialization - It is often very convenient to be able to initialize textures with promises\n * returned by image or data loading functions, as it allows a callback-free linear style of programming.\n *\n * @note GPU Textures are quite complex objects, with many subresources and modes of usage.\n * The `DynamicTexture` class allows luma.gl to provide some support for working with textures\n * without accumulating excessive complexity in the core Texture class which is designed as an immutable nature of GPU resource.\n */\nexport class DynamicTexture {\n readonly device: Device;\n readonly id: string;\n\n /** Props with defaults resolved (except `data` which is processed separately) */\n props: Readonly>;\n\n /** Created resources */\n private _texture: Texture | null = null;\n private _sampler: Sampler | null = null;\n private _view: TextureView | null = null;\n\n /** Ready when GPU texture has been created and data (if any) uploaded */\n readonly ready: Promise;\n isReady = false;\n destroyed = false;\n\n private resolveReady: (t: Texture) => void = () => {};\n private rejectReady: (error: Error) => void = () => {};\n\n get texture(): Texture {\n if (!this._texture) throw new Error('Texture not initialized yet');\n return this._texture;\n }\n get sampler(): Sampler {\n if (!this._sampler) throw new Error('Sampler not initialized yet');\n return this._sampler;\n }\n get view(): TextureView {\n if (!this._view) throw new Error('View not initialized yet');\n return this._view;\n }\n\n get [Symbol.toStringTag]() {\n return 'DynamicTexture';\n }\n toString(): string {\n const width = this._texture?.width ?? this.props.width ?? '?';\n const height = this._texture?.height ?? this.props.height ?? '?';\n return `DynamicTexture:\"${this.id}\":${width}x${height}px:(${this.isReady ? 'ready' : 'loading...'})`;\n }\n\n constructor(device: Device, props: DynamicTextureProps) {\n this.device = device;\n\n const id = uid('dynamic-texture');\n // NOTE: We avoid holding on to data to make sure it can be garbage collected.\n const originalPropsWithAsyncData = props;\n this.props = {...DynamicTexture.defaultProps, id, ...props, data: null};\n this.id = this.props.id;\n\n this.ready = new Promise((resolve, reject) => {\n this.resolveReady = resolve;\n this.rejectReady = reject;\n });\n\n this.initAsync(originalPropsWithAsyncData);\n }\n\n /** @note Fire and forget; caller can await `ready` */\n async initAsync(originalPropsWithAsyncData: DynamicTextureProps): Promise {\n try {\n // TODO - Accept URL string for 2D: turn into ExternalImage promise\n // const dataProps =\n // typeof props.data === 'string' && (props.dimension ?? '2d') === '2d'\n // ? ({dimension: '2d', data: loadImageBitmap(props.data)} as const)\n // : {};\n\n const propsWithSyncData = await this._loadAllData(originalPropsWithAsyncData);\n this._checkNotDestroyed();\n const subresources = propsWithSyncData.data\n ? getTextureSubresources({\n ...propsWithSyncData,\n width: originalPropsWithAsyncData.width,\n height: originalPropsWithAsyncData.height,\n format: originalPropsWithAsyncData.format\n })\n : [];\n const userProvidedFormat =\n 'format' in originalPropsWithAsyncData && originalPropsWithAsyncData.format !== undefined;\n const userProvidedUsage =\n 'usage' in originalPropsWithAsyncData && originalPropsWithAsyncData.usage !== undefined;\n\n // Deduce size when not explicitly provided\n // TODO - what about depth?\n const deduceSize = (): {width: number; height: number} => {\n if (this.props.width && this.props.height) {\n return {width: this.props.width, height: this.props.height};\n }\n\n const size = getTextureSizeFromData(propsWithSyncData);\n if (size) {\n return size;\n }\n\n return {width: this.props.width || 1, height: this.props.height || 1};\n };\n\n const size = deduceSize();\n if (!size || size.width <= 0 || size.height <= 0) {\n throw new Error(`${this} size could not be determined or was zero`);\n }\n\n // Normalize caller-provided subresources into one validated mip chain description.\n const textureData = analyzeTextureSubresources(this.device, subresources, size, {\n format: userProvidedFormat ? originalPropsWithAsyncData.format : undefined\n });\n const resolvedFormat = textureData.format ?? this.props.format;\n\n // Create a minimal TextureProps and validate via `satisfies`\n const baseTextureProps = {\n ...this.props,\n ...size,\n format: resolvedFormat,\n mipLevels: 1, // temporary; updated below\n data: undefined\n } satisfies TextureProps;\n\n if (this.device.isTextureFormatCompressed(resolvedFormat) && !userProvidedUsage) {\n baseTextureProps.usage = Texture.SAMPLE | Texture.COPY_DST;\n }\n\n // Explicit mip arrays take ownership of the mip chain; otherwise we may auto-generate it.\n const shouldGenerateMipmaps =\n this.props.mipmaps &&\n !textureData.hasExplicitMipChain &&\n !this.device.isTextureFormatCompressed(resolvedFormat);\n\n if (this.device.type === 'webgpu' && shouldGenerateMipmaps) {\n const requiredUsage =\n this.props.dimension === '3d'\n ? Texture.SAMPLE | Texture.STORAGE | Texture.COPY_DST | Texture.COPY_SRC\n : Texture.SAMPLE | Texture.RENDER | Texture.COPY_DST | Texture.COPY_SRC;\n baseTextureProps.usage |= requiredUsage;\n }\n\n // Compute mip levels (auto clamps to max)\n const maxMips = this.device.getMipLevelCount(baseTextureProps.width, baseTextureProps.height);\n const desired = textureData.hasExplicitMipChain\n ? textureData.mipLevels\n : this.props.mipLevels === 'auto'\n ? maxMips\n : Math.max(1, Math.min(maxMips, this.props.mipLevels ?? 1));\n\n const finalTextureProps: TextureProps = {...baseTextureProps, mipLevels: desired};\n\n this._texture = this.device.createTexture(finalTextureProps);\n this._sampler = this.texture.sampler;\n this._view = this.texture.view;\n\n // Upload data if provided\n if (textureData.subresources.length) {\n this._setTextureSubresources(textureData.subresources);\n }\n\n if (this.props.mipmaps && !textureData.hasExplicitMipChain && !shouldGenerateMipmaps) {\n log.warn(`${this} skipping auto-generated mipmaps for compressed texture format`)();\n }\n\n if (shouldGenerateMipmaps) {\n this.generateMipmaps();\n }\n\n this.isReady = true;\n this.resolveReady(this.texture);\n\n log.info(0, `${this} created`)();\n } catch (e) {\n const err = e instanceof Error ? e : new Error(String(e));\n this.rejectReady(err);\n }\n }\n\n destroy(): void {\n if (this._texture) {\n this._texture.destroy();\n this._texture = null;\n this._sampler = null;\n this._view = null;\n }\n this.destroyed = true;\n }\n\n generateMipmaps(): void {\n if (this.device.type === 'webgl') {\n this.texture.generateMipmapsWebGL();\n } else if (this.device.type === 'webgpu') {\n this.device.generateMipmapsWebGPU(this.texture);\n } else {\n log.warn(`${this} mipmaps not supported on ${this.device.type}`);\n }\n }\n\n /** Set sampler or create one from props */\n setSampler(sampler: Sampler | SamplerProps = {}): void {\n this._checkReady();\n const s = sampler instanceof Sampler ? sampler : this.device.createSampler(sampler);\n this.texture.setSampler(s);\n this._sampler = s;\n }\n\n /**\n * Copies texture contents into a GPU buffer and waits until the copy is complete.\n * The caller owns the returned buffer and must destroy it when finished.\n */\n async readBuffer(options: TextureReadOptions = {}): Promise {\n if (!this.isReady) {\n await this.ready;\n }\n\n const width = options.width ?? this.texture.width;\n const height = options.height ?? this.texture.height;\n const depthOrArrayLayers = options.depthOrArrayLayers ?? this.texture.depth;\n const layout = this.texture.computeMemoryLayout({width, height, depthOrArrayLayers});\n\n const buffer = this.device.createBuffer({\n byteLength: layout.byteLength,\n usage: Buffer.COPY_DST | Buffer.MAP_READ\n });\n\n this.texture.readBuffer(\n {\n ...options,\n width,\n height,\n depthOrArrayLayers\n },\n buffer\n );\n\n const fence = this.device.createFence();\n await fence.signaled;\n fence.destroy();\n\n return buffer;\n }\n\n /** Reads texture contents back to CPU memory. */\n async readAsync(options: TextureReadOptions = {}): Promise {\n if (!this.isReady) {\n await this.ready;\n }\n\n const width = options.width ?? this.texture.width;\n const height = options.height ?? this.texture.height;\n const depthOrArrayLayers = options.depthOrArrayLayers ?? this.texture.depth;\n const layout = this.texture.computeMemoryLayout({width, height, depthOrArrayLayers});\n\n const buffer = await this.readBuffer(options);\n const data = await buffer.readAsync(0, layout.byteLength);\n buffer.destroy();\n return data.buffer;\n }\n\n /**\n * Resize by cloning the underlying immutable texture.\n * Does not copy contents; caller may need to re-upload and/or regenerate mips.\n */\n resize(size: {width: number; height: number}): boolean {\n this._checkReady();\n\n if (size.width === this.texture.width && size.height === this.texture.height) {\n return false;\n }\n const prev = this.texture;\n this._texture = prev.clone(size);\n this._sampler = this.texture.sampler;\n this._view = this.texture.view;\n\n prev.destroy();\n log.info(`${this} resized`);\n return true;\n }\n\n /** Convert cube face label to texture slice index. Index can be used with `setTexture2DData()`. */\n getCubeFaceIndex(face: TextureCubeFace): number {\n const index = TEXTURE_CUBE_FACE_MAP[face];\n if (index === undefined) throw new Error(`Invalid cube face: ${face}`);\n return index;\n }\n\n /** Convert cube face label to texture slice index. Index can be used with `setTexture2DData()`. */\n getCubeArrayFaceIndex(cubeIndex: number, face: TextureCubeFace): number {\n return 6 * cubeIndex + this.getCubeFaceIndex(face);\n }\n\n /** @note experimental: Set multiple mip levels (1D) */\n setTexture1DData(data: Texture1DData): void {\n this._checkReady();\n if (this.texture.props.dimension !== '1d') {\n throw new Error(`${this} is not 1d`);\n }\n const subresources = getTexture1DSubresources(data);\n this._setTextureSubresources(subresources);\n }\n\n /** @note experimental: Set multiple mip levels (2D), optionally at `z`, slice (depth/array level) index */\n setTexture2DData(lodData: Texture2DData, z: number = 0): void {\n this._checkReady();\n if (this.texture.props.dimension !== '2d') {\n throw new Error(`${this} is not 2d`);\n }\n\n const subresources = getTexture2DSubresources(z, lodData);\n this._setTextureSubresources(subresources);\n }\n\n /** 3D: multiple depth slices, each may carry multiple mip levels */\n setTexture3DData(data: Texture3DData): void {\n if (this.texture.props.dimension !== '3d') {\n throw new Error(`${this} is not 3d`);\n }\n const subresources = getTexture3DSubresources(data);\n this._setTextureSubresources(subresources);\n }\n\n /** 2D array: multiple layers, each may carry multiple mip levels */\n setTextureArrayData(data: TextureArrayData): void {\n if (this.texture.props.dimension !== '2d-array') {\n throw new Error(`${this} is not 2d-array`);\n }\n const subresources = getTextureArraySubresources(data);\n this._setTextureSubresources(subresources);\n }\n\n /** Cube: 6 faces, each may carry multiple mip levels */\n setTextureCubeData(data: TextureCubeData): void {\n if (this.texture.props.dimension !== 'cube') {\n throw new Error(`${this} is not cube`);\n }\n const subresources = getTextureCubeSubresources(data);\n this._setTextureSubresources(subresources);\n }\n\n /** Cube array: multiple cubes (faces×layers), each face may carry multiple mips */\n setTextureCubeArrayData(data: TextureCubeArrayData): void {\n if (this.texture.props.dimension !== 'cube-array') {\n throw new Error(`${this} is not cube-array`);\n }\n const subresources = getTextureCubeArraySubresources(data);\n this._setTextureSubresources(subresources);\n }\n\n /** Sets multiple mip levels on different `z` slices (depth/array index) */\n private _setTextureSubresources(subresources: TextureSubresource[]): void {\n // If user supplied multiple mip levels, warn if auto-mips also requested\n // if (lodArray.length > 1 && this.props.mipmaps !== false) {\n // log.warn(\n // `Texture ${this.id}: provided multiple LODs and also requested mipmap generation.`\n // )();\n // }\n\n for (const subresource of subresources) {\n const {z, mipLevel} = subresource;\n switch (subresource.type) {\n case 'external-image':\n const {image, flipY} = subresource;\n this.texture.copyExternalImage({image, z, mipLevel, flipY});\n break;\n case 'texture-data':\n const {data, textureFormat} = subresource;\n if (textureFormat && textureFormat !== this.texture.format) {\n throw new Error(\n `${this} mip level ${mipLevel} uses format \"${textureFormat}\" but texture format is \"${this.texture.format}\"`\n );\n }\n this.texture.writeData(data.data, {\n x: 0,\n y: 0,\n z,\n width: data.width,\n height: data.height,\n depthOrArrayLayers: 1,\n mipLevel\n });\n break;\n default:\n throw new Error('Unsupported 2D mip-level payload');\n }\n }\n }\n\n // ------------------ helpers ------------------\n\n /** Recursively resolve all promises in data structures */\n private async _loadAllData(props: TextureDataAsyncProps): Promise {\n const syncData = await awaitAllPromises(props.data);\n const dimension = (props.dimension ?? '2d') as TextureDataProps['dimension'];\n return {dimension, data: syncData ?? null} as TextureDataProps;\n }\n\n private _checkNotDestroyed() {\n if (this.destroyed) {\n log.warn(`${this} already destroyed`);\n }\n }\n\n private _checkReady() {\n if (!this.isReady) {\n log.warn(`${this} Cannot perform this operation before ready`);\n }\n }\n\n static defaultProps: Required = {\n ...Texture.defaultProps,\n dimension: '2d',\n data: null,\n mipmaps: false\n };\n}\n\ntype TextureSubresourceAnalysis = {\n readonly subresources: TextureSubresource[];\n readonly mipLevels: number;\n readonly format?: TextureFormat;\n readonly hasExplicitMipChain: boolean;\n};\n\n// Flatten dimension-specific texture data into one list of uploadable subresources.\nfunction getTextureSubresources(\n props: TextureDataProps & Partial>\n): TextureSubresource[] {\n if (!props.data) {\n return [];\n }\n\n const baseLevelSize =\n props.width && props.height ? {width: props.width, height: props.height} : undefined;\n const textureFormat = 'format' in props ? props.format : undefined;\n\n switch (props.dimension) {\n case '1d':\n return getTexture1DSubresources(props.data);\n case '2d':\n return getTexture2DSubresources(0, props.data, baseLevelSize, textureFormat);\n case '3d':\n return getTexture3DSubresources(props.data);\n case '2d-array':\n return getTextureArraySubresources(props.data);\n case 'cube':\n return getTextureCubeSubresources(props.data);\n case 'cube-array':\n return getTextureCubeArraySubresources(props.data);\n default:\n throw new Error(`Unhandled dimension ${(props as TextureDataProps).dimension}`);\n }\n}\n\n// Resolve a consistent texture format and the longest mip chain valid across all slices.\nfunction analyzeTextureSubresources(\n device: Device,\n subresources: TextureSubresource[],\n size: {width: number; height: number},\n options: {format?: TextureFormat}\n): TextureSubresourceAnalysis {\n if (subresources.length === 0) {\n return {\n subresources,\n mipLevels: 1,\n format: options.format,\n hasExplicitMipChain: false\n };\n }\n\n const groupedSubresources = new Map();\n for (const subresource of subresources) {\n const group = groupedSubresources.get(subresource.z) ?? [];\n group.push(subresource);\n groupedSubresources.set(subresource.z, group);\n }\n\n const hasExplicitMipChain = subresources.some(subresource => subresource.mipLevel > 0);\n let resolvedFormat = options.format;\n let resolvedMipLevels = Number.POSITIVE_INFINITY;\n const validSubresources: TextureSubresource[] = [];\n\n for (const [z, sliceSubresources] of groupedSubresources) {\n // Validate each slice independently, then keep only the mip levels that are valid everywhere.\n const sortedSubresources = [...sliceSubresources].sort(\n (left, right) => left.mipLevel - right.mipLevel\n );\n const baseLevel = sortedSubresources[0];\n if (!baseLevel || baseLevel.mipLevel !== 0) {\n throw new Error(`DynamicTexture: slice ${z} is missing mip level 0`);\n }\n\n const baseSize = getTextureSubresourceSize(device, baseLevel);\n if (baseSize.width !== size.width || baseSize.height !== size.height) {\n throw new Error(\n `DynamicTexture: slice ${z} base level dimensions ${baseSize.width}x${baseSize.height} do not match expected ${size.width}x${size.height}`\n );\n }\n\n const baseFormat = getTextureSubresourceFormat(baseLevel);\n if (baseFormat) {\n if (resolvedFormat && resolvedFormat !== baseFormat) {\n throw new Error(\n `DynamicTexture: slice ${z} base level format \"${baseFormat}\" does not match texture format \"${resolvedFormat}\"`\n );\n }\n resolvedFormat = baseFormat;\n }\n\n const mipLevelLimit =\n resolvedFormat && device.isTextureFormatCompressed(resolvedFormat)\n ? // Block-compressed formats cannot have mips smaller than a single compression block.\n getMaxCompressedMipLevels(device, baseSize.width, baseSize.height, resolvedFormat)\n : device.getMipLevelCount(baseSize.width, baseSize.height);\n\n let validMipLevelsForSlice = 0;\n for (\n let expectedMipLevel = 0;\n expectedMipLevel < sortedSubresources.length;\n expectedMipLevel++\n ) {\n const subresource = sortedSubresources[expectedMipLevel];\n // Stop at the first gap so callers can provide extra trailing data without breaking creation.\n if (!subresource || subresource.mipLevel !== expectedMipLevel) {\n break;\n }\n if (expectedMipLevel >= mipLevelLimit) {\n break;\n }\n\n const subresourceSize = getTextureSubresourceSize(device, subresource);\n const expectedWidth = Math.max(1, baseSize.width >> expectedMipLevel);\n const expectedHeight = Math.max(1, baseSize.height >> expectedMipLevel);\n if (subresourceSize.width !== expectedWidth || subresourceSize.height !== expectedHeight) {\n break;\n }\n\n const subresourceFormat = getTextureSubresourceFormat(subresource);\n if (subresourceFormat) {\n if (!resolvedFormat) {\n resolvedFormat = subresourceFormat;\n }\n // Later mip levels must stay on the same format as the validated base level.\n if (subresourceFormat !== resolvedFormat) {\n break;\n }\n }\n\n validMipLevelsForSlice++;\n validSubresources.push(subresource);\n }\n\n resolvedMipLevels = Math.min(resolvedMipLevels, validMipLevelsForSlice);\n }\n\n const mipLevels = Number.isFinite(resolvedMipLevels) ? Math.max(1, resolvedMipLevels) : 1;\n\n return {\n // Keep every slice trimmed to the same mip count so the texture shape stays internally consistent.\n subresources: validSubresources.filter(subresource => subresource.mipLevel < mipLevels),\n mipLevels,\n format: resolvedFormat,\n hasExplicitMipChain\n };\n}\n\n// Read the per-level format using the transitional textureFormat -> format fallback rules.\nfunction getTextureSubresourceFormat(subresource: TextureSubresource): TextureFormat | undefined {\n if (subresource.type !== 'texture-data') {\n return undefined;\n }\n return subresource.textureFormat ?? resolveTextureImageFormat(subresource.data);\n}\n\n// Resolve dimensions from either raw bytes or external-image subresources.\nfunction getTextureSubresourceSize(\n device: Device,\n subresource: TextureSubresource\n): {width: number; height: number} {\n switch (subresource.type) {\n case 'external-image':\n return device.getExternalImageSize(subresource.image);\n case 'texture-data':\n return {width: subresource.data.width, height: subresource.data.height};\n default:\n throw new Error('Unsupported texture subresource');\n }\n}\n\n// Count the mip levels that stay at or above one compression block in each dimension.\nfunction getMaxCompressedMipLevels(\n device: Device,\n baseWidth: number,\n baseHeight: number,\n format: TextureFormat\n): number {\n const {blockWidth = 1, blockHeight = 1} = device.getTextureFormatInfo(format);\n let mipLevels = 1;\n for (let mipLevel = 1; ; mipLevel++) {\n const width = Math.max(1, baseWidth >> mipLevel);\n const height = Math.max(1, baseHeight >> mipLevel);\n if (width < blockWidth || height < blockHeight) {\n break;\n }\n mipLevels++;\n }\n return mipLevels;\n}\n\n// HELPERS\n\n/** Resolve all promises in a nested data structure */\nasync function awaitAllPromises(x: any): Promise {\n x = await x;\n if (Array.isArray(x)) {\n return await Promise.all(x.map(awaitAllPromises));\n }\n if (x && typeof x === 'object' && x.constructor === Object) {\n const object: Record = x;\n const values = await Promise.all(Object.values(object).map(awaitAllPromises));\n const keys = Object.keys(object);\n const resolvedObject: Record = {};\n for (let i = 0; i < keys.length; i++) {\n resolvedObject[keys[i]] = values[i];\n }\n return resolvedObject;\n }\n return x;\n}\n\n// /** @note experimental: Set multiple mip levels (2D), optionally at `z`, slice (depth/array level) index */\n// setTexture2DData(lodData: Texture2DData, z: number = 0): void {\n// this._checkReady();\n\n// const lodArray = this._normalizeTexture2DData(lodData);\n\n// // If user supplied multiple mip levels, warn if auto-mips also requested\n// if (lodArray.length > 1 && this.props.mipmaps !== false) {\n// log.warn(\n// `Texture ${this.id}: provided multiple LODs and also requested mipmap generation.`\n// )();\n// }\n\n// for (let mipLevel = 0; mipLevel < lodArray.length; mipLevel++) {\n// const imageData = lodArray[mipLevel];\n// if (this.device.isExternalImage(imageData)) {\n// this.texture.copyExternalImage({image: imageData, z, mipLevel, flipY: true});\n// } else if (this._isTextureImageData(imageData)) {\n// this.texture.copyImageData({data: imageData.data, z, mipLevel});\n// } else {\n// throw new Error('Unsupported 2D mip-level payload');\n// }\n// }\n// }\n\n// /** Normalize 2D layer payload into an array of mip-level items */\n// private _normalizeTexture2DData(data: Texture2DData): (TextureImageData | ExternalImage)[] {\n// return Array.isArray(data) ? data : [data];\n// }\n","import type {TypedArray, TextureFormat, ExternalImage} from '@luma.gl/core';\nimport {isExternalImage, getExternalImageSize} from '@luma.gl/core';\n\nexport type TextureImageSource = ExternalImage;\n\n/**\n * One mip level\n * Basic data structure is similar to `ImageData`\n * additional optional fields can describe compressed texture data.\n */\nexport type TextureImageData = {\n /** Preferred WebGPU style format string. */\n textureFormat?: TextureFormat;\n /** WebGPU style format string. Defaults to 'rgba8unorm' */\n format?: TextureFormat;\n /** Typed Array with the bytes of the image. @note beware row byte alignment requirements */\n data: TypedArray;\n /** Width of the image, in pixels, @note beware row byte alignment requirements */\n width: number;\n /** Height of the image, in rows */\n height: number;\n};\n\n/**\n * A single mip-level can be initialized by data or an ImageBitmap etc\n * @note in the WebGPU spec a mip-level is called a subresource\n */\nexport type TextureMipLevelData = TextureImageData | TextureImageSource;\n\n/**\n * Texture data for one image \"slice\" (which can consist of multiple miplevels)\n * Thus data for one slice be a single mip level or an array of miplevels\n * @note in the WebGPU spec each cross-section image in a 3D texture is called a \"slice\",\n * in a array texture each image in the array is called an array \"layer\"\n * luma.gl calls one image in a GPU texture a \"slice\" regardless of context.\n */\nexport type TextureSliceData = TextureMipLevelData | TextureMipLevelData[];\n\n/** Names of cube texture faces */\nexport type TextureCubeFace = '+X' | '-X' | '+Y' | '-Y' | '+Z' | '-Z';\n\n/** Array of cube texture faces. @note: index in array is the face index */\n// biome-ignore format: preserve layout\nexport const TEXTURE_CUBE_FACES = ['+X', '-X', '+Y', '-Y', '+Z', '-Z'] as const satisfies readonly TextureCubeFace[];\n\n/** Map of cube texture face names to face indexes */\n// biome-ignore format: preserve layout\nexport const TEXTURE_CUBE_FACE_MAP = {'+X': 0, '-X': 1, '+Y': 2, '-Y': 3, '+Z': 4, '-Z': 5} as const satisfies Record;\n\n/** @todo - Define what data type is supported for 1D textures. TextureImageData with height = 1 */\nexport type Texture1DData = TextureSliceData;\n\n/** Texture data can be one or more mip levels */\nexport type Texture2DData = TextureSliceData;\n\n/** 6 face textures */\nexport type TextureCubeData = Record;\n\n/** Array of textures */\nexport type Texture3DData = TextureSliceData[];\n\n/** Array of textures */\nexport type TextureArrayData = TextureSliceData[];\n\n/** Array of 6 face textures */\nexport type TextureCubeArrayData = Record[];\n\ntype TextureData =\n | Texture1DData\n | Texture3DData\n | TextureArrayData\n | TextureCubeArrayData\n | TextureCubeData;\n\n/** Sync data props */\nexport type TextureDataProps =\n | {dimension: '1d'; data: Texture1DData | null}\n | {dimension?: '2d'; data: Texture2DData | null}\n | {dimension: '3d'; data: Texture3DData | null}\n | {dimension: '2d-array'; data: TextureArrayData | null}\n | {dimension: 'cube'; data: TextureCubeData | null}\n | {dimension: 'cube-array'; data: TextureCubeArrayData | null};\n\n/** Async data props */\nexport type TextureDataAsyncProps =\n | {dimension: '1d'; data?: Promise | Texture1DData | null}\n | {dimension?: '2d'; data?: Promise | Texture2DData | null}\n | {dimension: '3d'; data?: Promise | Texture3DData | null}\n | {dimension: '2d-array'; data?: Promise | TextureArrayData | null}\n | {dimension: 'cube'; data?: Promise | TextureCubeData | null}\n | {dimension: 'cube-array'; data?: Promise | TextureCubeArrayData | null};\n\n/** Describes data for one sub resource (one mip level of one slice (depth or array layer)) */\nexport type TextureSubresource = {\n /** slice (depth or array layer)) */\n z: number;\n /** mip level (0 - max mip levels) */\n mipLevel: number;\n} & (\n | {\n type: 'external-image';\n image: ExternalImage;\n /** @deprecated is this an appropriate place for this flag? */\n flipY?: boolean;\n }\n | {\n type: 'texture-data';\n data: TextureImageData;\n textureFormat?: TextureFormat;\n }\n);\n\n/** Check if texture data is a typed array */\nexport function isTextureSliceData(data: TextureData): data is TextureImageData {\n const typedArray = (data as TextureImageData)?.data;\n return ArrayBuffer.isView(typedArray);\n}\n\nexport function getFirstMipLevel(layer: TextureSliceData | null): TextureMipLevelData | null {\n if (!layer) return null;\n return Array.isArray(layer) ? (layer[0] ?? null) : layer;\n}\n\nexport function getTextureSizeFromData(\n props: TextureDataProps\n): {width: number; height: number} | null {\n const {dimension, data} = props;\n if (!data) {\n return null;\n }\n\n switch (dimension) {\n case '1d': {\n const mipLevel = getFirstMipLevel(data);\n if (!mipLevel) return null;\n const {width} = getTextureMipLevelSize(mipLevel);\n return {width, height: 1};\n }\n case '2d': {\n const mipLevel = getFirstMipLevel(data);\n return mipLevel ? getTextureMipLevelSize(mipLevel) : null;\n }\n case '3d':\n case '2d-array': {\n if (!Array.isArray(data) || data.length === 0) return null;\n const mipLevel = getFirstMipLevel(data[0]);\n return mipLevel ? getTextureMipLevelSize(mipLevel) : null;\n }\n case 'cube': {\n const face = (Object.keys(data)[0] as TextureCubeFace) ?? null;\n if (!face) return null;\n const faceData = (data as Record)[face];\n const mipLevel = getFirstMipLevel(faceData);\n return mipLevel ? getTextureMipLevelSize(mipLevel) : null;\n }\n case 'cube-array': {\n if (!Array.isArray(data) || data.length === 0) return null;\n const firstCube = data[0];\n const face = (Object.keys(firstCube)[0] as TextureCubeFace) ?? null;\n if (!face) return null;\n const mipLevel = getFirstMipLevel(firstCube[face]);\n return mipLevel ? getTextureMipLevelSize(mipLevel) : null;\n }\n default:\n return null;\n }\n}\n\nfunction getTextureMipLevelSize(data: TextureMipLevelData): {width: number; height: number} {\n if (isExternalImage(data)) {\n return getExternalImageSize(data);\n }\n if (typeof data === 'object' && 'width' in data && 'height' in data) {\n return {width: data.width, height: data.height};\n }\n throw new Error('Unsupported mip-level data');\n}\n\n/** Type guard: is a mip-level `TextureImageData` (vs ExternalImage or bare typed array) */\nfunction isTextureImageData(data: unknown): data is TextureImageData {\n return (\n typeof data === 'object' &&\n data !== null &&\n 'data' in data &&\n 'width' in data &&\n 'height' in data\n );\n}\n\nfunction isTypedArrayMipLevelData(data: unknown): data is TypedArray {\n return ArrayBuffer.isView(data);\n}\n\nexport function resolveTextureImageFormat(data: TextureImageData): TextureFormat | undefined {\n const {textureFormat, format} = data;\n if (textureFormat && format && textureFormat !== format) {\n throw new Error(\n `Conflicting texture formats \"${textureFormat}\" and \"${format}\" provided for the same mip level`\n );\n }\n return textureFormat ?? format;\n}\n\n/** Resolve size for a single mip-level datum */\n// function getTextureMipLevelSizeFromData(data: TextureMipLevelData): {\n// width: number;\n// height: number;\n// } {\n// if (this.device.isExternalImage(data)) {\n// return this.device.getExternalImageSize(data);\n// }\n// if (this.isTextureImageData(data)) {\n// return {width: data.width, height: data.height};\n// }\n// // Fallback (should not happen with current types)\n// throw new Error('Unsupported mip-level data');\n// }\n\n/** Convert cube face label to depth index */\nexport function getCubeFaceIndex(face: TextureCubeFace): number {\n const idx = TEXTURE_CUBE_FACE_MAP[face];\n if (idx === undefined) throw new Error(`Invalid cube face: ${face}`);\n return idx;\n}\n\n/** Convert cube face label to texture slice index. Index can be used with `setTexture2DData()`. */\nexport function getCubeArrayFaceIndex(cubeIndex: number, face: TextureCubeFace): number {\n return 6 * cubeIndex + getCubeFaceIndex(face);\n}\n\n// ------------------ Upload helpers ------------------\n\n/** Experimental: Set multiple mip levels (1D) */\nexport function getTexture1DSubresources(data: Texture1DData): TextureSubresource[] {\n // Not supported in WebGL; left explicit\n throw new Error('setTexture1DData not supported in WebGL.');\n // const subresources: TextureSubresource[] = [];\n // return subresources;\n}\n\n/** Normalize 2D layer payload into an array of mip-level items */\nfunction _normalizeTexture2DData(\n data: Texture2DData\n): (TextureImageData | ExternalImage | TypedArray)[] {\n return Array.isArray(data) ? data : [data];\n}\n\n/** Experimental: Set multiple mip levels (2D), optionally at `z` (depth/array index) */\nexport function getTexture2DSubresources(\n slice: number,\n lodData: Texture2DData,\n baseLevelSize?: {width: number; height: number},\n textureFormat?: TextureFormat\n): TextureSubresource[] {\n const lodArray = _normalizeTexture2DData(lodData);\n const z = slice;\n\n const subresources: TextureSubresource[] = [];\n\n for (let mipLevel = 0; mipLevel < lodArray.length; mipLevel++) {\n const imageData = lodArray[mipLevel];\n if (isExternalImage(imageData)) {\n subresources.push({\n type: 'external-image',\n image: imageData,\n z,\n mipLevel\n });\n } else if (isTextureImageData(imageData)) {\n subresources.push({\n type: 'texture-data',\n data: imageData,\n textureFormat: resolveTextureImageFormat(imageData),\n z,\n mipLevel\n });\n } else if (isTypedArrayMipLevelData(imageData) && baseLevelSize) {\n subresources.push({\n type: 'texture-data',\n data: {\n data: imageData,\n width: Math.max(1, baseLevelSize.width >> mipLevel),\n height: Math.max(1, baseLevelSize.height >> mipLevel),\n ...(textureFormat ? {format: textureFormat} : {})\n },\n textureFormat,\n z,\n mipLevel\n });\n } else {\n throw new Error('Unsupported 2D mip-level payload');\n }\n }\n\n return subresources;\n}\n\n/** 3D: multiple depth slices, each may carry multiple mip levels */\nexport function getTexture3DSubresources(data: Texture3DData): TextureSubresource[] {\n const subresources: TextureSubresource[] = [];\n for (let depth = 0; depth < data.length; depth++) {\n subresources.push(...getTexture2DSubresources(depth, data[depth]));\n }\n return subresources;\n}\n\n/** 2D array: multiple layers, each may carry multiple mip levels */\nexport function getTextureArraySubresources(data: TextureArrayData): TextureSubresource[] {\n const subresources: TextureSubresource[] = [];\n for (let layer = 0; layer < data.length; layer++) {\n subresources.push(...getTexture2DSubresources(layer, data[layer]));\n }\n return subresources;\n}\n\n/** Cube: 6 faces, each may carry multiple mip levels */\nexport function getTextureCubeSubresources(data: TextureCubeData): TextureSubresource[] {\n const subresources: TextureSubresource[] = [];\n for (const [face, faceData] of Object.entries(data) as [TextureCubeFace, TextureSliceData][]) {\n const faceDepth = getCubeFaceIndex(face);\n subresources.push(...getTexture2DSubresources(faceDepth, faceData));\n }\n return subresources;\n}\n\n/** Cube array: multiple cubes (faces×layers), each face may carry multiple mips */\nexport function getTextureCubeArraySubresources(data: TextureCubeArrayData): TextureSubresource[] {\n const subresources: TextureSubresource[] = [];\n data.forEach((cubeData, cubeIndex) => {\n for (const [face, faceData] of Object.entries(cubeData)) {\n const faceDepth = getCubeArrayFaceIndex(cubeIndex, face as TextureCubeFace);\n subresources.push(...getTexture2DSubresources(faceDepth, faceData));\n }\n });\n return subresources;\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Device, Buffer, BufferRange, TransformFeedback, RenderPassProps} from '@luma.gl/core';\nimport {getPassthroughFS} from '@luma.gl/shadertools';\nimport {Model} from '../model/model';\nimport type {ModelProps} from '../model/model';\n\n/**\n * Properties for creating a {@link BufferTransform}\n * @note Only works under WebGL2.\n */\nexport type BufferTransformProps = Omit & {\n /** Optional fragment shader - normally not used in transforms */\n fs?: ModelProps['fs']; // override as optional\n /** A list of named outputs corresponding to shader declarations (varyings in WebGL) */\n outputs?: string[];\n /** @deprecated Use run({outputBuffers}) instead - Map of output buffers that the shaders will write results of computations to */\n feedbackBuffers?: Record;\n};\n\n/**\n * Manages a WebGL program (pipeline) for buffer→buffer transforms.\n * @note Only works under WebGL2.\n */\nexport class BufferTransform {\n readonly device: Device;\n readonly model: Model;\n readonly transformFeedback: TransformFeedback;\n\n static defaultProps: Required = {\n ...Model.defaultProps,\n outputs: undefined!,\n feedbackBuffers: undefined!\n };\n\n static isSupported(device: Device): boolean {\n return device?.info?.type === 'webgl';\n }\n\n constructor(device: Device, props: BufferTransformProps = BufferTransform.defaultProps) {\n if (!BufferTransform.isSupported(device)) {\n throw new Error('BufferTransform not yet implemented on WebGPU');\n }\n\n this.device = device;\n\n this.model = new Model(this.device, {\n id: props.id || 'buffer-transform-model',\n fs: props.fs || getPassthroughFS(),\n topology: props.topology || 'point-list',\n varyings: props.outputs || props.varyings,\n ...props\n });\n\n this.transformFeedback = this.device.createTransformFeedback({\n layout: this.model.pipeline.shaderLayout,\n // @ts-expect-error TODO\n buffers: props.feedbackBuffers\n });\n\n this.model.setTransformFeedback(this.transformFeedback);\n\n Object.seal(this);\n }\n\n /** Destroy owned resources. */\n destroy(): void {\n if (this.model) {\n this.model.destroy();\n }\n }\n\n /** @deprecated Use {@link destroy}. */\n delete(): void {\n this.destroy();\n }\n\n /** Run one transform loop. */\n run(\n options?: RenderPassProps & {\n inputBuffers?: Record;\n outputBuffers?: Record;\n }\n ): void {\n if (options?.inputBuffers) {\n this.model.setAttributes(options.inputBuffers);\n }\n if (options?.outputBuffers) {\n this.transformFeedback.setBuffers(options.outputBuffers);\n }\n const renderPass = this.device.beginRenderPass(options);\n this.model.draw(renderPass);\n renderPass.end();\n }\n\n // DEPRECATED METHODS\n\n /** @deprecated App knows what buffers it is passing in - Returns the {@link Buffer} or {@link BufferRange} for given varying name. */\n getBuffer(varyingName: string): Buffer | BufferRange | null {\n return this.transformFeedback.getBuffer(varyingName);\n }\n\n /** @deprecated App knows what buffers it is passing in - Reads the {@link Buffer} or {@link BufferRange} for given varying name. */\n readAsync(varyingName: string): Promise {\n const result = this.getBuffer(varyingName);\n if (!result) {\n throw new Error('BufferTransform#getBuffer');\n }\n if (result instanceof Buffer) {\n return result.readAsync();\n }\n const {buffer, byteOffset = 0, byteLength = buffer.byteLength} = result;\n return buffer.readAsync(byteOffset, byteLength);\n }\n}\n","// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {TypedArray} from '@math.gl/core';\nimport type {PrimitiveTopology} from '@luma.gl/core';\nimport {uid} from '../utils/uid';\n\nexport type GeometryProps = {\n id?: string;\n /** Determines how vertices are read from the 'vertex' attributes */\n topology: 'point-list' | 'line-list' | 'line-strip' | 'triangle-list' | 'triangle-strip';\n /** Auto calculated from attributes if not provided */\n vertexCount?: number;\n attributes: Record;\n indices?: GeometryAttribute | TypedArray;\n};\n\nexport type GeometryAttributes = {\n POSITION: GeometryAttribute;\n NORMAL: GeometryAttribute;\n TEXCOORD_0: GeometryAttribute;\n COLOR_0?: GeometryAttribute;\n indices?: GeometryAttribute & {size: 1; value: Uint32Array | Uint16Array};\n};\n\nexport type GeometryAttribute = {\n size?: number;\n value: TypedArray;\n [key: string]: any;\n};\n\nexport class Geometry {\n readonly id: string;\n /** Determines how vertices are read from the 'vertex' attributes */\n readonly topology?: PrimitiveTopology;\n readonly vertexCount: number;\n readonly indices?: GeometryAttribute;\n readonly attributes: {\n POSITION: GeometryAttribute;\n NORMAL: GeometryAttribute;\n TEXCOORD_0: GeometryAttribute;\n COLOR_0?: GeometryAttribute;\n [key: string]: GeometryAttribute | undefined;\n };\n\n userData: Record = {};\n\n constructor(props: GeometryProps) {\n const {attributes = {}, indices = null, vertexCount = null} = props;\n\n this.id = props.id || uid('geometry');\n this.topology = props.topology;\n\n if (indices) {\n this.indices = ArrayBuffer.isView(indices) ? {value: indices, size: 1} : indices;\n }\n\n // @ts-expect-error\n this.attributes = {};\n\n for (const [attributeName, attributeValue] of Object.entries(attributes)) {\n // Wrap \"unwrapped\" arrays and try to autodetect their type\n const attribute: GeometryAttribute = ArrayBuffer.isView(attributeValue)\n ? {value: attributeValue}\n : attributeValue;\n\n if (!ArrayBuffer.isView(attribute.value)) {\n throw new Error(\n `${this._print(attributeName)}: must be typed array or object with value as typed array`\n );\n }\n\n if ((attributeName === 'POSITION' || attributeName === 'positions') && !attribute.size) {\n attribute.size = 3;\n }\n\n // Move indices to separate field\n if (attributeName === 'indices') {\n if (this.indices) {\n throw new Error('Multiple indices detected');\n }\n this.indices = attribute;\n } else {\n this.attributes[attributeName] = attribute;\n }\n }\n\n if (this.indices && this.indices['isIndexed'] !== undefined) {\n this.indices = Object.assign({}, this.indices);\n delete this.indices['isIndexed'];\n }\n\n this.vertexCount = vertexCount || this._calculateVertexCount(this.attributes, this.indices);\n }\n\n getVertexCount(): number {\n return this.vertexCount;\n }\n\n /**\n * Return an object with all attributes plus indices added as a field.\n * TODO Geometry types are a mess\n */\n getAttributes(): GeometryAttributes {\n // @ts-ignore\n return this.indices ? {indices: this.indices, ...this.attributes} : this.attributes;\n }\n\n // PRIVATE\n\n _print(attributeName: string): string {\n return `Geometry ${this.id} attribute ${attributeName}`;\n }\n\n /**\n * GeometryAttribute\n * value: typed array\n * type: indices, vertices, uvs\n * size: elements per vertex\n * target: WebGL buffer type (string or constant)\n *\n * @param attributes\n * @param indices\n * @returns\n */\n _setAttributes(attributes: Record, indices: any): this {\n return this;\n }\n\n _calculateVertexCount(attributes: GeometryAttributes, indices?: GeometryAttribute): number {\n if (indices) {\n return indices.value.length;\n }\n let vertexCount = Infinity;\n for (const attribute of Object.values(attributes)) {\n const {value, size, constant} = attribute;\n if (!constant && value && size !== undefined && size >= 1) {\n vertexCount = Math.min(vertexCount, value.length / size);\n }\n }\n\n // assert(Number.isFinite(vertexCount));\n return vertexCount;\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport LayersPass, {LayersPassRenderOptions, RenderStats, Rect} from './layers-pass';\nimport type {Framebuffer, Parameters, RenderPipelineParameters} from '@luma.gl/core';\nimport log from '../utils/log';\n\nimport type {Effect} from '../lib/effect';\nimport type Viewport from '../viewports/viewport';\nimport type Layer from '../lib/layer';\n\nconst PICKING_BLENDING: RenderPipelineParameters = {\n blendColorOperation: 'add',\n blendColorSrcFactor: 'one',\n blendColorDstFactor: 'zero',\n blendAlphaOperation: 'add',\n blendAlphaSrcFactor: 'constant',\n blendAlphaDstFactor: 'zero'\n};\n\ntype PickLayersPassRenderOptions = LayersPassRenderOptions & {\n pickingFBO: Framebuffer;\n deviceRect: Rect;\n pickZ: boolean;\n};\n\ntype EncodedPickingColors = {\n a: number;\n layer: Layer;\n viewports: Viewport[];\n};\n\nexport type PickingColorDecoder = (pickedColor: number[] | Uint8Array) =>\n | {\n pickedLayer: Layer;\n pickedViewports: Viewport[];\n pickedObjectIndex: number;\n }\n | undefined;\n\nexport default class PickLayersPass extends LayersPass {\n private pickZ?: boolean;\n private _colorEncoderState: {\n byLayer: Map;\n byAlpha: EncodedPickingColors[];\n } | null = null;\n\n render(props: LayersPassRenderOptions | PickLayersPassRenderOptions): {\n decodePickingColor: PickingColorDecoder | null;\n stats: RenderStats[];\n } {\n if ('pickingFBO' in props) {\n // When drawing into an off-screen buffer, use the alpha channel to encode layer index\n return this._drawPickingBuffer(props);\n }\n // When drawing to screen (debug mode), do not use the alpha channel so that result is always visible\n const stats = super._render(props);\n return {decodePickingColor: null, stats};\n }\n\n // Private\n // Draws list of layers and viewports into the picking buffer\n // Note: does not sample the buffer, that has to be done by the caller\n _drawPickingBuffer({\n layers,\n layerFilter,\n views,\n viewports,\n onViewportActive,\n pickingFBO,\n deviceRect: {x, y, width, height},\n cullRect,\n effects,\n pass = 'picking',\n pickZ,\n shaderModuleProps,\n clearColor\n }: PickLayersPassRenderOptions): {\n decodePickingColor: PickingColorDecoder | null;\n stats: RenderStats[];\n } {\n this.pickZ = pickZ;\n const colorEncoderState = this._resetColorEncoder(pickZ);\n const scissorRect = [x, y, width, height];\n\n // Make sure we clear scissor test and fbo bindings in case of exceptions\n // We are only interested in one pixel, no need to render anything else\n // Note that the callback here is called synchronously.\n // Set blend mode for picking\n // always overwrite existing pixel with [r,g,b,layerIndex]\n const renderStatus = super._render({\n target: pickingFBO,\n layers,\n layerFilter,\n views,\n viewports,\n onViewportActive,\n cullRect,\n effects: effects?.filter(e => e.useInPicking),\n pass,\n isPicking: true,\n shaderModuleProps,\n clearColor: clearColor ?? [0, 0, 0, 0],\n colorMask: 0xf,\n scissorRect\n });\n\n // Clear the temp field\n this._colorEncoderState = null;\n const decodePickingColor = colorEncoderState && decodeColor.bind(null, colorEncoderState);\n return {decodePickingColor, stats: renderStatus};\n }\n\n shouldDrawLayer(layer: Layer): boolean {\n const {pickable, operation} = layer.props;\n return (\n (pickable && operation.includes('draw')) ||\n operation.includes('terrain') ||\n operation.includes('mask')\n );\n }\n\n protected getShaderModuleProps(\n layer: Layer,\n effects: Effect[] | undefined,\n otherShaderModuleProps: Record\n ): any {\n return {\n picking: {\n isActive: 1,\n isAttribute: this.pickZ\n },\n lighting: {enabled: false}\n };\n }\n\n protected getLayerParameters(layer: Layer, layerIndex: number, viewport: Viewport): Parameters {\n // TODO use Parameters type\n const pickParameters: any = {\n ...layer.props.parameters\n };\n const {pickable, operation} = layer.props;\n\n if (!this._colorEncoderState) {\n pickParameters.blend = false;\n } else if (pickable && operation.includes('draw')) {\n // Encode pickable layers that include 'draw' operation (including 'terrain+draw')\n Object.assign(pickParameters, PICKING_BLENDING);\n pickParameters.blend = true;\n if (this.device.type === 'webgpu') {\n // WebGPU uses render-pass dynamic state for constant blending.\n pickParameters.blendConstant = encodeColor(this._colorEncoderState, layer, viewport);\n } else {\n pickParameters.blendColor = encodeColor(this._colorEncoderState, layer, viewport);\n }\n if (operation.includes('terrain') && layer.state?._hasPickingCover) {\n // For terrain+draw layers with a valid cover FBO, the terrain shader outputs the\n // cover FBO pixel which already has correctly encoded alpha from the cover encoder.\n // Use srcFactor 'one' to pass through the cover alpha without double-encoding.\n // Without a cover FBO, keep 'constant' so the layer's own picking colors encode correctly.\n pickParameters.blendAlphaSrcFactor = 'one';\n }\n } else if (operation.includes('terrain')) {\n // Pure terrain layers (without 'draw') don't need picking colors\n pickParameters.blend = false;\n }\n\n return pickParameters;\n }\n\n protected _resetColorEncoder(pickZ: boolean) {\n // Track encoded layer indices\n this._colorEncoderState = pickZ\n ? null\n : {\n byLayer: new Map(),\n byAlpha: []\n };\n // Temporarily store it on the instance so that it can be accessed by this.getLayerParameters\n return this._colorEncoderState;\n }\n}\n\n// Assign an unique alpha value for each pickable layer and track the encoding in the cache object\n// Returns normalized blend color\nfunction encodeColor(\n encoded: {\n byLayer: Map;\n byAlpha: EncodedPickingColors[];\n },\n layer: Layer,\n viewport: Viewport\n): number[] {\n const {byLayer, byAlpha} = encoded;\n let a;\n\n // Encode layerIndex in the alpha channel\n // TODO - combine small layers to better utilize the picking color space\n let entry = byLayer.get(layer);\n if (entry) {\n entry.viewports.push(viewport);\n a = entry.a;\n } else {\n a = byLayer.size + 1;\n if (a <= 255) {\n entry = {a, layer, viewports: [viewport]};\n byLayer.set(layer, entry);\n byAlpha[a] = entry;\n } else {\n log.warn('Too many pickable layers, only picking the first 255')();\n a = 0;\n }\n }\n return [0, 0, 0, a / 255];\n}\n\n// Given a picked color, retrieve the corresponding layer and viewports from cache\nfunction decodeColor(\n encoded: {\n byLayer: Map;\n byAlpha: EncodedPickingColors[];\n },\n pickedColor: number[] | Uint8Array\n):\n | {\n pickedLayer: Layer;\n pickedViewports: Viewport[];\n pickedObjectIndex: number;\n }\n | undefined {\n const entry = encoded.byAlpha[pickedColor[3]];\n return (\n entry && {\n pickedLayer: entry.layer,\n pickedViewports: entry.viewports,\n pickedObjectIndex: entry.layer.decodePickingColor(pickedColor)\n }\n );\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport const LIFECYCLE = {\n NO_STATE: 'Awaiting state',\n MATCHED: 'Matched. State transferred from previous layer',\n INITIALIZED: 'Initialized',\n AWAITING_GC: 'Discarded. Awaiting garbage collection',\n AWAITING_FINALIZATION: 'No longer matched. Awaiting garbage collection',\n FINALIZED: 'Finalized! Awaiting garbage collection'\n} as const;\n\nexport type Lifecycle = (typeof LIFECYCLE)[keyof typeof LIFECYCLE];\n\n/* Secret props keys */\n// Symbols are non-enumerable by default, does not show in for...in or Object.keys\n// but are copied with Object.assign ¯\\_(ツ)_/¯\n// Supported everywhere except IE11, can be polyfilled with core-js\nexport const COMPONENT_SYMBOL: unique symbol = Symbol.for('component');\nexport const PROP_TYPES_SYMBOL: unique symbol = Symbol.for('propTypes');\nexport const DEPRECATED_PROPS_SYMBOL: unique symbol = Symbol.for('deprecatedProps');\nexport const ASYNC_DEFAULTS_SYMBOL: unique symbol = Symbol.for('asyncPropDefaults');\nexport const ASYNC_ORIGINAL_SYMBOL: unique symbol = Symbol.for('asyncPropOriginal');\nexport const ASYNC_RESOLVED_SYMBOL: unique symbol = Symbol.for('asyncPropResolved');\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\ntype NestedArray = (T | NestedArray)[];\n\n/**\n * Flattens a nested array into a single level array,\n * or a single value into an array with one value\n * @example flatten([[1, [2]], [3], 4]) => [1, 2, 3, 4]\n * @example flatten(1) => [1]\n * @param array The array to flatten.\n * @param filter= - Optional predicate called on each `value` to\n * determine if it should be included (pushed onto) the resulting array.\n * @return Returns the new flattened array (new array or `result` if provided)\n */\nexport function flatten(\n array: T | NestedArray,\n filter: (element: T) => boolean = () => true\n): T[] {\n // Wrap single object in array\n if (!Array.isArray(array)) {\n return filter(array) ? [array] : [];\n }\n // Deep flatten and filter the array\n return flattenArray(array, filter, []);\n}\n\n/** Deep flattens an array. Helper to `flatten`, see its parameters */\nfunction flattenArray(array: NestedArray, filter: (element: T) => boolean, result: T[]): T[] {\n let index = -1;\n while (++index < array.length) {\n const value = array[index];\n if (Array.isArray(value)) {\n flattenArray(value, filter, result);\n } else if (filter(value)) {\n result.push(value);\n }\n }\n return result;\n}\n\n/** Uses copyWithin to significantly speed up typed array value filling */\nexport function fillArray({target, source, start = 0, count = 1}) {\n const length = source.length;\n const total = count * length;\n let copied = 0;\n for (let i = start; copied < length; copied++) {\n target[i++] = source[copied];\n }\n\n while (copied < total) {\n // If we have copied less than half, copy everything we got\n // else copy remaining in one operation\n if (copied < total - copied) {\n target.copyWithin(start + copied, start, start + copied);\n copied *= 2;\n } else {\n target.copyWithin(start + copied, start, start + total - copied);\n copied = total;\n }\n }\n\n return target;\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device, RenderPass} from '@luma.gl/core';\nimport {Timeline} from '@luma.gl/engine';\nimport type {ShaderAssembler, ShaderModule} from '@luma.gl/shadertools';\nimport {getShaderAssembler, layerUniforms} from '../shaderlib/index';\nimport {LIFECYCLE} from '../lifecycle/constants';\nimport log from '../utils/log';\nimport debug from '../debug/index';\nimport {flatten} from '../utils/flatten';\nimport {Stats} from '@probe.gl/stats';\nimport ResourceManager from './resource/resource-manager';\n\nimport Viewport from '../viewports/viewport';\n\nimport type Layer from './layer';\nimport type CompositeLayer from './composite-layer';\nimport type Deck from './deck';\n\nconst TRACE_SET_LAYERS = 'layerManager.setLayers';\nconst TRACE_ACTIVATE_VIEWPORT = 'layerManager.activateViewport';\n\nexport type LayerContext = {\n layerManager: LayerManager;\n resourceManager: ResourceManager;\n deck?: Deck;\n device: Device;\n shaderAssembler: ShaderAssembler;\n defaultShaderModules: ShaderModule[];\n renderPass: RenderPass;\n stats: Stats;\n viewport: Viewport;\n timeline: Timeline;\n mousePosition: {x: number; y: number} | null;\n userData: any;\n onError?: (error: Error, source: Layer) => void;\n /** @deprecated Use context.device */\n gl: WebGL2RenderingContext;\n};\n\nexport type LayersList = (Layer | undefined | false | null | LayersList)[];\n\nexport type LayerManagerProps = {\n deck?: Deck;\n stats?: Stats;\n viewport?: Viewport;\n timeline?: Timeline;\n};\nexport default class LayerManager {\n layers: Layer[];\n context: LayerContext;\n resourceManager: ResourceManager;\n\n private _lastRenderedLayers: LayersList = [];\n private _needsRedraw: string | false = false;\n private _needsUpdate: string | false = false;\n private _nextLayers: LayersList | null = null;\n private _debug: boolean = false;\n // This flag is separate from _needsUpdate because it can be set during an update and should trigger another full update\n private _defaultShaderModulesChanged: boolean = false;\n\n /**\n * @param device\n * @param param1\n */\n // eslint-disable-next-line\n constructor(device: Device, props: LayerManagerProps) {\n const {deck, stats, viewport, timeline} = props || {};\n\n // Currently deck.gl expects the DeckGL.layers array to be different\n // whenever React rerenders. If the same layers array is used, the\n // LayerManager's diffing algorithm will generate a fatal error and\n // break the rendering.\n\n // `this._lastRenderedLayers` stores the UNFILTERED layers sent\n // down to LayerManager, so that `layers` reference can be compared.\n // If it's the same across two React render calls, the diffing logic\n // will be skipped.\n this.layers = [];\n this.resourceManager = new ResourceManager({device, protocol: 'deck://'});\n\n this.context = {\n mousePosition: null,\n userData: {},\n layerManager: this,\n device,\n // @ts-expect-error\n gl: device?.gl,\n deck,\n shaderAssembler: getShaderAssembler(device?.info?.shadingLanguage || 'glsl'),\n defaultShaderModules: [layerUniforms],\n renderPass: undefined!,\n stats: stats || new Stats({id: 'deck.gl'}),\n // Make sure context.viewport is not empty on the first layer initialization\n viewport: viewport || new Viewport({id: 'DEFAULT-INITIAL-VIEWPORT'}), // Current viewport, exposed to layers for project* function\n timeline: timeline || new Timeline(),\n resourceManager: this.resourceManager,\n onError: undefined\n };\n\n Object.seal(this);\n }\n\n /** Method to call when the layer manager is not needed anymore. */\n finalize() {\n this.resourceManager.finalize();\n // Finalize all layers\n for (const layer of this.layers) {\n this._finalizeLayer(layer);\n }\n }\n\n /** Check if a redraw is needed */\n needsRedraw(\n opts: {\n /** Reset redraw flags to false after the call */\n clearRedrawFlags: boolean;\n } = {clearRedrawFlags: false}\n ): string | false {\n let redraw = this._needsRedraw;\n if (opts.clearRedrawFlags) {\n this._needsRedraw = false;\n }\n\n // This layers list doesn't include sublayers, relying on composite layers\n for (const layer of this.layers) {\n // Call every layer to clear their flags\n const layerNeedsRedraw = layer.getNeedsRedraw(opts);\n redraw = redraw || layerNeedsRedraw;\n }\n\n return redraw;\n }\n\n /** Check if a deep update of all layers is needed */\n needsUpdate(): string | false {\n if (this._nextLayers && this._nextLayers !== this._lastRenderedLayers) {\n // New layers array may be the same as the old one if `setProps` is called by React\n return 'layers changed';\n }\n if (this._defaultShaderModulesChanged) {\n return 'shader modules changed';\n }\n return this._needsUpdate;\n }\n\n /** Layers will be redrawn (in next animation frame) */\n setNeedsRedraw(reason: string): void {\n this._needsRedraw = this._needsRedraw || reason;\n }\n\n /** Layers will be updated deeply (in next animation frame)\n Potentially regenerating attributes and sub layers */\n setNeedsUpdate(reason: string): void {\n this._needsUpdate = this._needsUpdate || reason;\n }\n\n /** Gets a list of currently rendered layers. Optionally filter by id. */\n getLayers({layerIds}: {layerIds?: string[]} = {}): Layer[] {\n // Filtering by layerId compares beginning of strings, so that sublayers will be included\n // Dependes on the convention of adding suffixes to the parent's layer name\n return layerIds\n ? this.layers.filter(layer => layerIds.find(layerId => layer.id.indexOf(layerId) === 0))\n : this.layers;\n }\n\n /** Set props needed for layer rendering and picking. */\n setProps(props: any): void {\n if ('debug' in props) {\n this._debug = props.debug;\n }\n\n // A way for apps to add data to context that can be accessed in layers\n if ('userData' in props) {\n this.context.userData = props.userData;\n }\n\n // New layers will be processed in `updateLayers` in the next update cycle\n if ('layers' in props) {\n this._nextLayers = props.layers;\n }\n\n if ('onError' in props) {\n this.context.onError = props.onError;\n }\n }\n\n /** Supply a new layer list, initiating sublayer generation and layer matching */\n setLayers(newLayers: LayersList, reason?: string): void {\n debug(TRACE_SET_LAYERS, this, reason, newLayers);\n\n this._lastRenderedLayers = newLayers;\n\n const flatLayers = flatten(newLayers, Boolean) as Layer[];\n\n for (const layer of flatLayers) {\n layer.context = this.context;\n }\n\n this._updateLayers(this.layers, flatLayers);\n }\n\n /** Update layers from last cycle if `setNeedsUpdate()` has been called */\n updateLayers(): void {\n // NOTE: For now, even if only some layer has changed, we update all layers\n // to ensure that layer id maps etc remain consistent even if different\n // sublayers are rendered\n const reason = this.needsUpdate();\n if (reason) {\n this.setNeedsRedraw(`updating layers: ${reason}`);\n // Force a full update\n this.setLayers(this._nextLayers || this._lastRenderedLayers, reason);\n }\n // Updated, clear the backlog\n this._nextLayers = null;\n }\n\n //\n // INTERNAL METHODS\n //\n\n /** Make a viewport \"current\" in layer context, updating viewportChanged flags */\n activateViewport = (viewport: Viewport) => {\n debug(TRACE_ACTIVATE_VIEWPORT, this, viewport);\n if (viewport) {\n this.context.viewport = viewport;\n }\n };\n\n /** Register a default shader module */\n addDefaultShaderModule(module: ShaderModule) {\n const {defaultShaderModules} = this.context;\n if (!defaultShaderModules.find(m => m.name === module.name)) {\n defaultShaderModules.push(module);\n this._defaultShaderModulesChanged = true;\n }\n }\n\n /** Deregister a default shader module */\n removeDefaultShaderModule(module: ShaderModule) {\n const {defaultShaderModules} = this.context;\n const i = defaultShaderModules.findIndex(m => m.name === module.name);\n if (i >= 0) {\n defaultShaderModules.splice(i, 1);\n this._defaultShaderModulesChanged = true;\n }\n }\n\n private _handleError(stage: string, error: Error, layer: Layer) {\n layer.raiseError(error, `${stage} of ${layer}`);\n }\n\n // TODO - mark layers with exceptions as bad and remove from rendering cycle?\n /** Match all layers, checking for caught errors\n to avoid having an exception in one layer disrupt other layers */\n private _updateLayers(oldLayers: Layer[], newLayers: Layer[]): void {\n // Create old layer map\n const oldLayerMap: {[layerId: string]: Layer | null} = {};\n for (const oldLayer of oldLayers) {\n if (oldLayerMap[oldLayer.id]) {\n log.warn(`Multiple old layers with same id ${oldLayer.id}`)();\n } else {\n oldLayerMap[oldLayer.id] = oldLayer;\n }\n }\n\n if (this._defaultShaderModulesChanged) {\n for (const layer of oldLayers) {\n layer.setNeedsUpdate();\n layer.setChangeFlags({extensionsChanged: true});\n }\n this._defaultShaderModulesChanged = false;\n }\n\n // Allocate array for generated layers\n const generatedLayers: Layer[] = [];\n\n // Match sublayers\n this._updateSublayersRecursively(newLayers, oldLayerMap, generatedLayers);\n\n // Finalize unmatched layers\n this._finalizeOldLayers(oldLayerMap);\n\n let needsUpdate: string | false = false;\n for (const layer of generatedLayers) {\n if (layer.hasUniformTransition()) {\n needsUpdate = `Uniform transition in ${layer}`;\n break;\n }\n }\n\n this._needsUpdate = needsUpdate;\n this.layers = generatedLayers;\n }\n\n /* eslint-disable complexity,max-statements */\n // Note: adds generated layers to `generatedLayers` array parameter\n private _updateSublayersRecursively(\n newLayers: Layer[],\n oldLayerMap: {[layerId: string]: Layer | null},\n generatedLayers: Layer[]\n ) {\n for (const newLayer of newLayers) {\n newLayer.context = this.context;\n\n // Given a new coming layer, find its matching old layer (if any)\n const oldLayer = oldLayerMap[newLayer.id];\n if (oldLayer === null) {\n // null, rather than undefined, means this id was originally there\n log.warn(`Multiple new layers with same id ${newLayer.id}`)();\n }\n // Remove the old layer from candidates, as it has been matched with this layer\n oldLayerMap[newLayer.id] = null;\n\n let sublayers: Layer[] | null = null;\n\n // We must not generate exceptions until after layer matching is complete\n try {\n if (this._debug && oldLayer !== newLayer) {\n newLayer.validateProps();\n }\n\n if (!oldLayer) {\n this._initializeLayer(newLayer);\n } else {\n this._transferLayerState(oldLayer, newLayer);\n this._updateLayer(newLayer);\n }\n generatedLayers.push(newLayer);\n\n // Call layer lifecycle method: render sublayers\n sublayers = newLayer.isComposite ? (newLayer as CompositeLayer).getSubLayers() : null;\n // End layer lifecycle method: render sublayers\n } catch (err) {\n this._handleError('matching', err as Error, newLayer); // Record first exception\n }\n\n if (sublayers) {\n this._updateSublayersRecursively(sublayers, oldLayerMap, generatedLayers);\n }\n }\n }\n /* eslint-enable complexity,max-statements */\n\n // Finalize any old layers that were not matched\n private _finalizeOldLayers(oldLayerMap: {[layerId: string]: Layer | null}): void {\n for (const layerId in oldLayerMap) {\n const layer = oldLayerMap[layerId];\n if (layer) {\n this._finalizeLayer(layer);\n }\n }\n }\n\n // / EXCEPTION SAFE LAYER ACCESS\n\n /** Safely initializes a single layer, calling layer methods */\n private _initializeLayer(layer: Layer): void {\n try {\n layer._initialize();\n layer.lifecycle = LIFECYCLE.INITIALIZED;\n } catch (err) {\n this._handleError('initialization', err as Error, layer);\n // TODO - what should the lifecycle state be here? LIFECYCLE.INITIALIZATION_FAILED?\n }\n }\n\n /** Transfer state from one layer to a newer version */\n private _transferLayerState(oldLayer: Layer, newLayer: Layer): void {\n newLayer._transferState(oldLayer);\n newLayer.lifecycle = LIFECYCLE.MATCHED;\n\n if (newLayer !== oldLayer) {\n oldLayer.lifecycle = LIFECYCLE.AWAITING_GC;\n }\n }\n\n /** Safely updates a single layer, cleaning all flags */\n private _updateLayer(layer: Layer): void {\n try {\n layer._update();\n } catch (err) {\n this._handleError('update', err as Error, layer);\n }\n }\n\n /** Safely finalizes a single layer, removing all resources */\n private _finalizeLayer(layer: Layer): void {\n this._needsRedraw = this._needsRedraw || `finalized ${layer}`;\n\n layer.lifecycle = LIFECYCLE.AWAITING_FINALIZATION;\n\n try {\n layer._finalize();\n layer.lifecycle = LIFECYCLE.FINALIZED;\n } catch (err) {\n this._handleError('finalization', err as Error, layer);\n }\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {load} from '@loaders.gl/core';\n\nimport type {ResourceManagerContext} from './resource-manager';\n\nexport type ResourceSubscriber = {\n onChange: (data: T | Promise) => void;\n};\n\nexport default class Resource {\n id: string;\n context: ResourceManagerContext;\n isLoaded!: boolean;\n persistent?: boolean;\n\n private _loadCount: number = 0;\n private _subscribers = new Set>();\n private _data!: T | Promise | string;\n private _loader?: Promise;\n private _error?: Error;\n private _content?: T;\n\n constructor(id: string, data: T | Promise | string, context: ResourceManagerContext) {\n this.id = id;\n this.context = context;\n\n this.setData(data);\n }\n\n // consumer: {onChange: Function}\n subscribe(consumer: ResourceSubscriber): void {\n this._subscribers.add(consumer);\n }\n\n unsubscribe(consumer: ResourceSubscriber): void {\n this._subscribers.delete(consumer);\n }\n\n inUse(): boolean {\n return this._subscribers.size > 0;\n }\n\n delete(): void {\n // Remove any resources created\n }\n\n getData(): T | Promise {\n return this.isLoaded\n ? this._error\n ? Promise.reject(this._error)\n : this._content!\n : this._loader!.then(() => this.getData());\n }\n\n setData(data: any, forceUpdate?: boolean) {\n if (data === this._data && !forceUpdate) {\n return;\n }\n this._data = data;\n const loadCount = ++this._loadCount;\n\n let loader = data;\n if (typeof data === 'string') {\n loader = load(data);\n }\n if (loader instanceof Promise) {\n this.isLoaded = false;\n this._loader = loader\n .then(result => {\n // check if source has changed\n if (this._loadCount === loadCount) {\n this.isLoaded = true;\n this._error = undefined;\n this._content = result;\n }\n })\n .catch(error => {\n if (this._loadCount === loadCount) {\n this.isLoaded = true;\n this._error = error || true;\n }\n });\n } else {\n this.isLoaded = true;\n this._error = undefined;\n this._content = data;\n }\n\n for (const subscriber of this._subscribers) {\n subscriber.onChange(this.getData());\n }\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/* global setTimeout */\nimport {Device} from '@luma.gl/core';\nimport Resource from './resource';\nimport type {ResourceSubscriber} from './resource';\n\nexport type ResourceManagerContext = {\n device: Device;\n resourceManager: ResourceManager;\n /** @deprecated */\n gl: WebGL2RenderingContext;\n};\n\ntype Consumer = Record;\n\nexport default class ResourceManager {\n protocol: string;\n\n private _context: ResourceManagerContext;\n private _resources: Record;\n private _consumers: Record;\n private _pruneRequest: number | null;\n\n constructor(props: {device: Device; protocol?: string}) {\n this.protocol = props.protocol || 'resource://';\n\n this._context = {\n device: props.device,\n // @ts-expect-error\n gl: props.device?.gl,\n resourceManager: this\n };\n this._resources = {};\n this._consumers = {};\n\n this._pruneRequest = null;\n }\n\n contains(resourceId: string): boolean {\n if (resourceId.startsWith(this.protocol)) {\n return true;\n }\n return resourceId in this._resources;\n }\n\n add({\n resourceId,\n data,\n forceUpdate = false,\n persistent = true\n }: {\n resourceId: string;\n data: any;\n forceUpdate?: boolean;\n persistent?: boolean;\n }) {\n let res = this._resources[resourceId];\n\n if (res) {\n res.setData(data, forceUpdate);\n } else {\n res = new Resource(resourceId, data, this._context);\n this._resources[resourceId] = res;\n }\n // persistent resources can only be removed by calling `remove`\n // non-persistent resources may be released when there are no more consumers\n res.persistent = persistent;\n }\n\n remove(resourceId: string): void {\n const res = this._resources[resourceId];\n\n if (res) {\n res.delete();\n delete this._resources[resourceId];\n }\n }\n\n unsubscribe({consumerId}: {consumerId: string}): void {\n const consumer = this._consumers[consumerId];\n if (consumer) {\n for (const requestId in consumer) {\n const request = consumer[requestId];\n const resource = this._resources[request.resourceId];\n if (resource) {\n resource.unsubscribe(request);\n }\n }\n delete this._consumers[consumerId];\n this.prune();\n }\n }\n\n subscribe({\n resourceId,\n onChange,\n consumerId,\n requestId = 'default'\n }: {\n resourceId: string;\n onChange: (data: T | Promise) => void;\n consumerId: string;\n requestId: string;\n }): T | Promise | undefined {\n const {_resources: resources, protocol} = this;\n if (resourceId.startsWith(protocol)) {\n resourceId = resourceId.replace(protocol, '');\n if (!resources[resourceId]) {\n // Add placeholder. When this resource becomes available, the consumer will be notified.\n this.add({resourceId, data: null, persistent: false});\n }\n }\n const res: Resource = resources[resourceId];\n this._track(consumerId, requestId, res, onChange);\n if (res) {\n return res.getData();\n }\n\n return undefined;\n }\n\n prune(): void {\n if (!this._pruneRequest) {\n // prune() may be called multiple times in the same animation frame.\n // Batch multiple requests together\n // @ts-ignore setTimeout returns NodeJS.Timeout in node\n this._pruneRequest = setTimeout(() => this._prune(), 0);\n }\n }\n\n finalize(): void {\n for (const key in this._resources) {\n this._resources[key].delete();\n }\n }\n\n private _track(\n consumerId: string,\n requestId: string,\n resource: Resource,\n onChange: (data: any) => void\n ) {\n const consumers = this._consumers;\n const consumer = (consumers[consumerId] = consumers[consumerId] || {});\n let request = consumer[requestId];\n\n const oldResource = request && request.resourceId && this._resources[request.resourceId];\n if (oldResource) {\n oldResource.unsubscribe(request);\n this.prune();\n }\n if (resource) {\n if (request) {\n request.onChange = onChange;\n request.resourceId = resource.id;\n } else {\n request = {\n onChange,\n resourceId: resource.id\n };\n }\n consumer[requestId] = request;\n resource.subscribe(request);\n }\n }\n\n private _prune(): void {\n this._pruneRequest = null;\n\n for (const key of Object.keys(this._resources)) {\n const res = this._resources[key];\n if (!res.persistent && !res.inUse()) {\n res.delete();\n delete this._resources[key];\n }\n }\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/**\n * Fast partial deep equal for prop.\n *\n * @param a Prop\n * @param b Prop to compare against `a`\n * @param depth Depth to which to recurse in nested Objects/Arrays. Use 0 (default) for shallow comparison, -1 for infinite depth\n */\n/* eslint-disable complexity */\nexport function deepEqual(a: any, b: any, depth: number): boolean {\n if (a === b) {\n return true;\n }\n if (!depth || !a || !b) {\n return false;\n }\n if (Array.isArray(a)) {\n if (!Array.isArray(b) || a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (!deepEqual(a[i], b[i], depth - 1)) {\n return false;\n }\n }\n return true;\n }\n if (Array.isArray(b)) {\n return false;\n }\n if (typeof a === 'object' && typeof b === 'object') {\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n if (aKeys.length !== bKeys.length) {\n return false;\n }\n for (const key of aKeys) {\n if (!b.hasOwnProperty(key)) {\n return false;\n }\n if (!deepEqual(a[key], b[key], depth - 1)) {\n return false;\n }\n }\n return true;\n }\n return false;\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {deepEqual} from '../utils/deep-equal';\nimport log from '../utils/log';\nimport {flatten} from '../utils/flatten';\n\nimport type Controller from '../controllers/controller';\nimport type {ViewStateChangeParameters, InteractionState} from '../controllers/controller';\nimport type Viewport from '../viewports/viewport';\nimport type View from '../views/view';\nimport type {Timeline} from '@luma.gl/engine';\nimport type {EventManager} from 'mjolnir.js';\nimport type {ConstructorOf} from '../types/types';\nimport type {default as MapView, MapViewState} from '../views/map-view';\n\nexport type ViewOrViews = View | View[] | null;\ntype ViewStateOf = ViewT extends View ? ViewStateT : never;\ntype OneOfViews = ViewsT extends null\n ? MapView\n : ViewsT extends View[]\n ? ViewsT[number]\n : ViewsT;\nexport type AnyViewStateOf = ViewStateOf>;\nexport type ViewStateMap = ViewsT extends null\n ? MapViewState\n : ViewsT extends View\n ? ViewStateOf\n : {[viewId: string]: AnyViewStateOf};\n\n/** This is a very lose type of all \"acceptable\" viewState\n * It's not good for type hinting but matches what may exist internally\n */\nexport type ViewStateObject =\n | ViewStateMap\n | AnyViewStateOf\n | {[viewId: string]: AnyViewStateOf};\n\n/** ViewManager props directly supplied by the user */\ntype ViewManagerProps = {\n views: ViewsT;\n viewState: ViewStateObject | null;\n onViewStateChange?: (params: ViewStateChangeParameters>) => void;\n onInteractionStateChange?: (state: InteractionState) => void;\n pickPosition?: (x: number, y: number) => {coordinate?: number[]} | null;\n width?: number;\n height?: number;\n};\n\nexport default class ViewManager {\n width: number;\n height: number;\n views: View[];\n viewState: ViewStateObject;\n controllers: {[viewId: string]: Controller | null};\n timeline: Timeline;\n\n private _viewports: Viewport[];\n private _viewportMap: {[viewId: string]: Viewport};\n private _isUpdating: boolean;\n private _needsRedraw: string | false;\n private _needsUpdate: string | false;\n private _eventManager: EventManager;\n private _eventCallbacks: {\n onViewStateChange?: (params: ViewStateChangeParameters) => void;\n onInteractionStateChange?: (state: InteractionState) => void;\n };\n private _pickPosition?: (x: number, y: number) => {coordinate?: number[]} | null;\n\n constructor(\n props: ViewManagerProps & {\n // Initial options\n timeline: Timeline;\n eventManager: EventManager;\n }\n ) {\n // List of view descriptors, gets re-evaluated when width/height changes\n this.views = [];\n this.width = 100;\n this.height = 100;\n this.viewState = {} as any;\n this.controllers = {};\n this.timeline = props.timeline;\n\n this._viewports = []; // Generated viewports\n this._viewportMap = {};\n this._isUpdating = false;\n this._needsRedraw = 'First render';\n this._needsUpdate = 'Initialize';\n\n this._eventManager = props.eventManager;\n this._eventCallbacks = {\n onViewStateChange: props.onViewStateChange,\n onInteractionStateChange: props.onInteractionStateChange\n };\n this._pickPosition = props.pickPosition;\n\n Object.seal(this);\n\n // Init with default map viewport\n this.setProps(props);\n }\n\n /** Remove all resources and event listeners */\n finalize(): void {\n for (const key in this.controllers) {\n const controller = this.controllers[key];\n if (controller) {\n controller.finalize();\n }\n }\n this.controllers = {};\n }\n\n /** Check if a redraw is needed */\n needsRedraw(\n opts: {\n /** Reset redraw flags to false */\n clearRedrawFlags?: boolean;\n } = {clearRedrawFlags: false}\n ): string | false {\n const redraw = this._needsRedraw;\n if (opts.clearRedrawFlags) {\n this._needsRedraw = false;\n }\n return redraw;\n }\n\n /** Mark the manager as dirty. Will rebuild all viewports and update controllers. */\n setNeedsUpdate(reason: string): void {\n this._needsUpdate = this._needsUpdate || reason;\n this._needsRedraw = this._needsRedraw || reason;\n }\n\n /** Checks each viewport for transition updates */\n updateViewStates(): void {\n for (const viewId in this.controllers) {\n const controller = this.controllers[viewId];\n if (controller) {\n controller.updateTransition();\n }\n }\n }\n\n /** Get a set of viewports for a given width and height\n * TODO - Intention is for deck.gl to autodeduce width and height and drop the need for props\n * @param rect (object, optional) - filter the viewports\n * + not provided - return all viewports\n * + {x, y} - only return viewports that contain this pixel\n * + {x, y, width, height} - only return viewports that overlap with this rectangle\n */\n getViewports(rect?: {x: number; y: number; width?: number; height?: number}): Viewport[] {\n if (rect) {\n return this._viewports.filter(viewport => viewport.containsPixel(rect));\n }\n return this._viewports;\n }\n\n /** Get a map of all views */\n getViews(): {[viewId: string]: View} {\n const viewMap = {};\n this.views.forEach(view => {\n viewMap[view.id] = view;\n });\n return viewMap;\n }\n\n /** Resolves a viewId string to a View */\n getView(viewId: string): View | undefined {\n return this.views.find(view => view.id === viewId);\n }\n\n /** Returns the viewState for a specific viewId. Matches the viewState by\n 1. view.viewStateId\n 2. view.id\n 3. root viewState\n then applies the view's filter if any */\n getViewState(viewOrViewId: string | View): AnyViewStateOf {\n const view: View | undefined =\n typeof viewOrViewId === 'string' ? this.getView(viewOrViewId) : viewOrViewId;\n // Backward compatibility: view state for single view\n const viewState = (view && this.viewState[view.getViewStateId()]) || this.viewState;\n return (view ? view.filterViewState(viewState) : viewState) as AnyViewStateOf;\n }\n\n getViewport(viewId: string): Viewport | undefined {\n return this._viewportMap[viewId];\n }\n\n /**\n * Unproject pixel coordinates on screen onto world coordinates,\n * (possibly [lon, lat]) on map.\n * - [x, y] => [lng, lat]\n * - [x, y, z] => [lng, lat, Z]\n * @param {Array} xyz -\n * @param {Object} opts - options\n * @param {Object} opts.topLeft=true - Whether origin is top left\n * @return {Array|null} - [lng, lat, Z] or [X, Y, Z]\n */\n unproject(xyz: number[], opts?: {topLeft?: boolean}): number[] | null {\n const viewports = this.getViewports();\n const pixel = {x: xyz[0], y: xyz[1]};\n for (let i = viewports.length - 1; i >= 0; --i) {\n const viewport = viewports[i];\n if (viewport.containsPixel(pixel)) {\n const p = xyz.slice();\n p[0] -= viewport.x;\n p[1] -= viewport.y;\n return viewport.unproject(p, opts);\n }\n }\n return null;\n }\n\n /** Update the manager with new Deck props */\n setProps(props: Partial>) {\n if (props.views) {\n this._setViews(props.views);\n }\n\n if (props.viewState) {\n this._setViewState(props.viewState);\n }\n\n if ('width' in props || 'height' in props) {\n this._setSize(props.width as number, props.height as number);\n }\n\n if ('pickPosition' in props) {\n this._pickPosition = props.pickPosition;\n }\n\n // Important: avoid invoking _update() inside itself\n // Nested updates result in unexpected side effects inside _rebuildViewports()\n // when using auto control in pure-js\n if (!this._isUpdating) {\n this._update();\n }\n }\n\n //\n // PRIVATE METHODS\n //\n\n private _update(): void {\n this._isUpdating = true;\n\n // Only rebuild viewports if the update flag is set\n if (this._needsUpdate) {\n this._needsUpdate = false;\n this._rebuildViewports();\n }\n\n // If viewport transition(s) are triggered during viewports update, controller(s)\n // will immediately call `onViewStateChange` which calls `viewManager.setProps` again.\n if (this._needsUpdate) {\n this._needsUpdate = false;\n this._rebuildViewports();\n }\n\n this._isUpdating = false;\n }\n\n private _setSize(width: number, height: number): void {\n if (width !== this.width || height !== this.height) {\n this.width = width;\n this.height = height;\n this.setNeedsUpdate('Size changed');\n }\n }\n\n // Update the view descriptor list and set change flag if needed\n // Does not actually rebuild the `Viewport`s until `getViewports` is called\n private _setViews(views: View[]): void {\n views = flatten(views, Boolean);\n\n const viewsChanged = this._diffViews(views, this.views);\n if (viewsChanged) {\n this.setNeedsUpdate('views changed');\n }\n\n this.views = views;\n }\n\n private _setViewState(viewState: ViewStateObject): void {\n if (viewState) {\n // depth = 3 when comparing viewStates: viewId.position.0\n const viewStateChanged = !deepEqual(viewState, this.viewState, 3);\n\n if (viewStateChanged) {\n this.setNeedsUpdate('viewState changed');\n }\n\n this.viewState = viewState;\n } else {\n log.warn('missing `viewState` or `initialViewState`')();\n }\n }\n\n private _createController(\n view: View,\n props: {id: string; type: ConstructorOf>}\n ): Controller {\n const Controller = props.type;\n\n const controller = new Controller({\n timeline: this.timeline,\n eventManager: this._eventManager,\n // Set an internal callback that calls the prop callback if provided\n onViewStateChange: this._eventCallbacks.onViewStateChange,\n onStateChange: this._eventCallbacks.onInteractionStateChange,\n makeViewport: viewState =>\n this.getView(view.id)?.makeViewport({\n viewState,\n width: this.width,\n height: this.height\n }),\n pickPosition: this._pickPosition\n });\n\n return controller;\n }\n\n private _updateController(\n view: View,\n viewState: AnyViewStateOf,\n viewport: Viewport | null,\n controller?: Controller | null\n ): Controller | null {\n const controllerProps = view.controller;\n if (controllerProps && viewport) {\n const resolvedProps = {\n ...viewState,\n ...controllerProps,\n id: view.id,\n x: viewport.x,\n y: viewport.y,\n width: viewport.width,\n height: viewport.height\n };\n\n // Create controller if not already existing or if the type of the\n // controller has changed.\n if (!controller || controller.constructor !== controllerProps.type) {\n controller = this._createController(view, resolvedProps);\n }\n if (controller) {\n controller.setProps(resolvedProps);\n }\n return controller;\n }\n return null;\n }\n\n // Rebuilds viewports from descriptors towards a certain window size\n private _rebuildViewports(): void {\n const {views} = this;\n\n const oldControllers = this.controllers;\n this._viewports = [];\n this.controllers = {};\n\n let invalidateControllers = false;\n // Create controllers in reverse order, so that views on top receive events first\n for (let i = views.length; i--; ) {\n const view = views[i];\n const viewState = this.getViewState(view);\n const viewport = view.makeViewport({viewState, width: this.width, height: this.height});\n\n let oldController = oldControllers[view.id];\n const hasController = Boolean(view.controller);\n if (hasController && !oldController) {\n // When a new controller is added, invalidate all controllers below it so that\n // events are registered in the correct order\n invalidateControllers = true;\n }\n if ((invalidateControllers || !hasController) && oldController) {\n // Remove and reattach invalidated controller\n oldController.finalize();\n oldController = null;\n }\n\n // Update the controller\n this.controllers[view.id] = this._updateController(view, viewState, viewport, oldController);\n\n if (viewport) {\n this._viewports.unshift(viewport);\n }\n }\n\n // Remove unused controllers\n for (const id in oldControllers) {\n const oldController = oldControllers[id];\n if (oldController && !this.controllers[id]) {\n oldController.finalize();\n }\n }\n\n this._buildViewportMap();\n }\n\n _buildViewportMap(): void {\n // Build a view id to view index\n this._viewportMap = {};\n this._viewports.forEach(viewport => {\n if (viewport.id) {\n // TODO - issue warning if multiple viewports use same id\n this._viewportMap[viewport.id] = this._viewportMap[viewport.id] || viewport;\n }\n });\n }\n\n // Check if viewport array has changed, returns true if any change\n // Note that descriptors can be the same\n _diffViews(newViews: View[], oldViews: View[]): boolean {\n if (newViews.length !== oldViews.length) {\n return true;\n }\n\n return newViews.some((_, i) => !newViews[i].equals(oldViews[i]));\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport type LayoutExpression =\n | {type: 'literal'; value: number}\n | {type: 'percentage'; value: number}\n | {type: 'binary'; operator: '+' | '-'; left: LayoutExpression; right: LayoutExpression};\n\ntype Token =\n | {type: 'number'; value: number}\n | {type: 'word'; value: string}\n | {type: 'symbol'; value: string};\n\nconst NUMBER_REGEX = /^(?:\\d+\\.?\\d*|\\.\\d+)$/;\n\n// Takes a number or a string expression that may include numbers, percentages, `px` units or\n// CSS-style `calc()` expressions containing `+`/`-` operations and parentheses.\nexport function parsePosition(value: number | string): LayoutExpression {\n switch (typeof value) {\n case 'number':\n if (!Number.isFinite(value)) {\n throw new Error(`Could not parse position string ${value}`);\n }\n return {type: 'literal', value};\n\n case 'string':\n try {\n const tokens = tokenize(value);\n const parser = new LayoutExpressionParser(tokens);\n return parser.parseExpression();\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n throw new Error(`Could not parse position string ${value}: ${reason}`);\n }\n\n default:\n throw new Error(`Could not parse position string ${value}`);\n }\n}\n\nexport function evaluateLayoutExpression(expression: LayoutExpression, extent: number): number {\n switch (expression.type) {\n case 'literal':\n return expression.value;\n case 'percentage':\n return Math.round(expression.value * extent);\n case 'binary':\n const left = evaluateLayoutExpression(expression.left, extent);\n const right = evaluateLayoutExpression(expression.right, extent);\n return expression.operator === '+' ? left + right : left - right;\n default:\n throw new Error('Unknown layout expression type');\n }\n}\n\nexport function getPosition(expression: LayoutExpression, extent: number): number {\n return evaluateLayoutExpression(expression, extent);\n}\n\nfunction tokenize(input: string): Token[] {\n const tokens: Token[] = [];\n let index = 0;\n while (index < input.length) {\n const char = input[index];\n if (/\\s/.test(char)) {\n index++;\n continue;\n }\n if (char === '+' || char === '-' || char === '(' || char === ')' || char === '%') {\n tokens.push({type: 'symbol', value: char});\n index++;\n continue;\n }\n if (isDigit(char) || char === '.') {\n const start = index;\n let hasDecimal = char === '.';\n index++;\n while (index < input.length) {\n const next = input[index];\n if (isDigit(next)) {\n index++;\n continue;\n }\n if (next === '.' && !hasDecimal) {\n hasDecimal = true;\n index++;\n continue;\n }\n break;\n }\n const numberString = input.slice(start, index);\n if (!NUMBER_REGEX.test(numberString)) {\n throw new Error('Invalid number token');\n }\n tokens.push({type: 'number', value: parseFloat(numberString)});\n continue;\n }\n if (isAlpha(char)) {\n const start = index;\n while (index < input.length && isAlpha(input[index])) {\n index++;\n }\n const word = input.slice(start, index).toLowerCase();\n tokens.push({type: 'word', value: word});\n continue;\n }\n throw new Error('Invalid token in position string');\n }\n return tokens;\n}\n\nclass LayoutExpressionParser {\n private tokens: Token[];\n private index = 0;\n\n constructor(tokens: Token[]) {\n this.tokens = tokens;\n }\n\n parseExpression(): LayoutExpression {\n const expression = this.parseBinaryExpression();\n if (this.index < this.tokens.length) {\n throw new Error('Unexpected token at end of expression');\n }\n return expression;\n }\n\n private parseBinaryExpression(): LayoutExpression {\n let expression = this.parseFactor();\n let token = this.peek();\n while (isAddSubSymbol(token)) {\n this.index++;\n const right = this.parseFactor();\n expression = {type: 'binary', operator: token.value, left: expression, right};\n token = this.peek();\n }\n return expression;\n }\n\n private parseFactor(): LayoutExpression {\n const token = this.peek();\n if (!token) {\n throw new Error('Unexpected end of expression');\n }\n\n if (token.type === 'symbol' && token.value === '+') {\n this.index++;\n return this.parseFactor();\n }\n if (token.type === 'symbol' && token.value === '-') {\n this.index++;\n const factor = this.parseFactor();\n return {type: 'binary', operator: '-', left: {type: 'literal', value: 0}, right: factor};\n }\n if (token.type === 'symbol' && token.value === '(') {\n this.index++;\n const expression = this.parseBinaryExpression();\n if (!this.consumeSymbol(')')) {\n throw new Error('Missing closing parenthesis');\n }\n return expression;\n }\n if (token.type === 'word' && token.value === 'calc') {\n this.index++;\n if (!this.consumeSymbol('(')) {\n throw new Error('Missing opening parenthesis after calc');\n }\n const expression = this.parseBinaryExpression();\n if (!this.consumeSymbol(')')) {\n throw new Error('Missing closing parenthesis');\n }\n return expression;\n }\n if (token.type === 'number') {\n this.index++;\n const numberValue = token.value;\n const nextToken = this.peek();\n if (nextToken && nextToken.type === 'symbol' && nextToken.value === '%') {\n this.index++;\n return {type: 'percentage', value: numberValue / 100};\n }\n if (nextToken && nextToken.type === 'word' && nextToken.value === 'px') {\n this.index++;\n return {type: 'literal', value: numberValue};\n }\n return {type: 'literal', value: numberValue};\n }\n\n throw new Error('Unexpected token in expression');\n }\n\n private consumeSymbol(value: string): boolean {\n const token = this.peek();\n if (token && token.type === 'symbol' && token.value === value) {\n this.index++;\n return true;\n }\n return false;\n }\n\n private peek(): Token | null {\n return this.tokens[this.index] || null;\n }\n}\n\nfunction isDigit(char: string): boolean {\n return char >= '0' && char <= '9';\n}\n\nfunction isAlpha(char: string): boolean {\n return (char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z');\n}\n\nfunction isAddSubSymbol(token: Token | null): token is Token & {type: 'symbol'; value: '+' | '-'} {\n return Boolean(token && token.type === 'symbol' && (token.value === '+' || token.value === '-'));\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/** Merge two viewstates, except `id`\n * For position arrays such as `target`, only override the components that are defined.\n */\nexport function deepMergeViewState>(\n a: ViewStateT,\n b: ViewStateT\n): ViewStateT {\n const result = {...a};\n for (const key in b) {\n if (key === 'id') continue;\n if (Array.isArray(result[key]) && Array.isArray(b[key])) {\n result[key] = mergeNumericArray(result[key], b[key]) as any;\n } else {\n result[key] = b[key];\n }\n }\n return result;\n}\n\nfunction mergeNumericArray(target: number[], source: number[]): number[] {\n target = target.slice();\n for (let i = 0; i < source.length; i++) {\n const v = source[i];\n if (Number.isFinite(v)) {\n target[i] = v;\n }\n }\n return target;\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport Viewport from '../viewports/viewport';\nimport {parsePosition, getPosition, LayoutExpression} from '../utils/positions';\nimport {deepEqual} from '../utils/deep-equal';\nimport {deepMergeViewState} from '../utils/deep-merge';\nimport type Controller from '../controllers/controller';\nimport type {ControllerOptions} from '../controllers/controller';\nimport type {TransitionProps} from '../controllers/transition-manager';\nimport type {Padding} from '../viewports/viewport';\nimport type {ConstructorOf} from '../types/types';\n\nexport type CommonViewState = TransitionProps;\n\nexport type CommonViewProps = {\n /** A unique id of the view. In a multi-view use case, this is important for matching view states and place contents into this view. */\n id?: string;\n /** A relative (e.g. `'50%'`) or absolute position. Default `0`. */\n x?: number | string;\n /** A relative (e.g. `'50%'`) or absolute position. Default `0`. */\n y?: number | string;\n /** A relative (e.g. `'50%'`) or absolute extent. Default `'100%'`. */\n width?: number | string;\n /** A relative (e.g. `'50%'`) or absolute extent. Default `'100%'`. */\n height?: number | string;\n /** Padding around the view, expressed in either relative (e.g. `'50%'`) or absolute pixels. Default `null`. */\n padding?: {\n left?: number | string;\n right?: number | string;\n top?: number | string;\n bottom?: number | string;\n } | null;\n /** When using multiple views, set this flag to wipe the pixels drawn by other overlapping views. Default `false` */\n clear?: boolean;\n /** Color to clear the viewport with, in RGBA format [r, g, b, a?]. Values are 0-255. Default `[0, 0, 0, 0]` (transparent). */\n clearColor?: number[] | false;\n /** Depth buffer value to clear the viewport with, between 0.0 - 1.0. Default `1.0` (far plane). */\n clearDepth?: number | false;\n /** Stencil buffer Value to clear the viewport with, between 0 - 255. Default `0` (clear). */\n clearStencil?: number | false;\n /** State of the view */\n viewState?:\n | string\n | ({\n id?: string;\n } & Partial);\n /** Options for viewport interactivity. */\n controller?:\n | null\n | boolean\n | ConstructorOf>\n | (ControllerOptions & {\n type?: ConstructorOf>;\n });\n};\n\nexport default abstract class View<\n ViewState extends CommonViewState = CommonViewState,\n ViewProps extends CommonViewProps = CommonViewProps\n> {\n id: string;\n abstract getViewportType(viewState: ViewState): ConstructorOf;\n protected abstract get ControllerType(): ConstructorOf>;\n\n private _x: LayoutExpression;\n private _y: LayoutExpression;\n private _width: LayoutExpression;\n private _height: LayoutExpression;\n private _padding: {\n left: LayoutExpression;\n right: LayoutExpression;\n top: LayoutExpression;\n bottom: LayoutExpression;\n } | null;\n\n readonly props: ViewProps;\n\n constructor(props: ViewProps) {\n const {id, x = 0, y = 0, width = '100%', height = '100%', padding = null} = props;\n\n // @ts-ignore\n this.id = id || this.constructor.displayName || 'view';\n\n this.props = {...props, id: this.id};\n\n // Extents\n this._x = parsePosition(x);\n this._y = parsePosition(y);\n this._width = parsePosition(width);\n this._height = parsePosition(height);\n this._padding = padding && {\n left: parsePosition(padding.left || 0),\n right: parsePosition(padding.right || 0),\n top: parsePosition(padding.top || 0),\n bottom: parsePosition(padding.bottom || 0)\n };\n\n // Bind methods for easy access\n this.equals = this.equals.bind(this);\n\n Object.seal(this);\n }\n\n equals(view: this): boolean {\n if (this === view) {\n return true;\n }\n\n // To correctly compare padding use depth=2\n return this.constructor === view.constructor && deepEqual(this.props, view.props, 2);\n }\n\n /** Clone this view with modified props */\n clone(newProps: Partial): this {\n const ViewConstructor = this.constructor as new (props: ViewProps) => this;\n return new ViewConstructor({...this.props, ...newProps});\n }\n\n /** Make viewport from canvas dimensions and view state */\n makeViewport({width, height, viewState}: {width: number; height: number; viewState: ViewState}) {\n viewState = this.filterViewState(viewState);\n\n // Resolve relative viewport dimensions\n const viewportDimensions = this.getDimensions({width, height});\n if (!viewportDimensions.height || !viewportDimensions.width) {\n return null;\n }\n const ViewportType = this.getViewportType(viewState);\n return new ViewportType({...viewState, ...this.props, ...viewportDimensions});\n }\n\n getViewStateId(): string {\n const {viewState} = this.props;\n if (typeof viewState === 'string') {\n // if View.viewState is a string, return it\n return viewState;\n }\n return viewState?.id || this.id;\n }\n\n // Allows view to override (or completely define) viewState\n filterViewState(viewState: ViewState): ViewState {\n if (this.props.viewState && typeof this.props.viewState === 'object') {\n // If we have specified an id, then intent is to override,\n // If not, completely specify the view state\n if (!this.props.viewState.id) {\n return this.props.viewState as ViewState;\n }\n\n return deepMergeViewState(viewState, this.props.viewState as ViewState);\n }\n\n return viewState;\n }\n\n /** Resolve the dimensions of the view from overall canvas dimensions */\n getDimensions({width, height}: {width: number; height: number}): {\n x: number;\n y: number;\n width: number;\n height: number;\n padding?: Padding;\n } {\n const dimensions: {\n x: number;\n y: number;\n width: number;\n height: number;\n padding?: Padding;\n } = {\n x: getPosition(this._x, width),\n y: getPosition(this._y, height),\n width: getPosition(this._width, width),\n height: getPosition(this._height, height)\n };\n\n if (this._padding) {\n dimensions.padding = {\n left: getPosition(this._padding.left, width),\n top: getPosition(this._padding.top, height),\n right: getPosition(this._padding.right, width),\n bottom: getPosition(this._padding.bottom, height)\n };\n }\n return dimensions;\n }\n\n // Used by sub classes to resolve controller props\n get controller(): (ControllerOptions & {type: ConstructorOf>}) | null {\n const opts = this.props.controller;\n\n if (!opts) {\n return null;\n }\n if (opts === true) {\n return {type: this.ControllerType};\n }\n if (typeof opts === 'function') {\n return {type: opts};\n }\n return {type: this.ControllerType, ...opts};\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Timeline} from '@luma.gl/engine';\n\nexport type TransitionSettings = {\n duration: number;\n onStart?: (transition: Transition) => void;\n onUpdate?: (transition: Transition) => void;\n onInterrupt?: (transition: Transition) => void;\n onEnd?: (transition: Transition) => void;\n};\n\nexport default class Transition {\n private _inProgress: boolean = false;\n private _handle: number | null = null;\n private _timeline: Timeline;\n\n time: number = 0;\n // @ts-expect-error\n settings: TransitionSettings & {fromValue; toValue; duration; easing; damping; stiffness} = {\n duration: 0\n };\n\n /**\n * @params timeline {Timeline}\n */\n constructor(timeline: Timeline) {\n this._timeline = timeline;\n }\n\n /* Public API */\n get inProgress(): boolean {\n return this._inProgress;\n }\n\n /**\n * (re)start this transition.\n * @params props {object} - optional overriding props. see constructor\n */\n start(settings: TransitionSettings) {\n this.cancel();\n // @ts-expect-error\n this.settings = settings;\n this._inProgress = true;\n this.settings.onStart?.(this);\n }\n\n /**\n * end this transition if it is in progress.\n */\n end() {\n if (this._inProgress) {\n this._timeline.removeChannel(this._handle as number);\n this._handle = null;\n this._inProgress = false;\n this.settings.onEnd?.(this);\n }\n }\n\n /**\n * cancel this transition if it is in progress.\n */\n cancel() {\n if (this._inProgress) {\n this.settings.onInterrupt?.(this);\n this._timeline.removeChannel(this._handle as number);\n this._handle = null;\n this._inProgress = false;\n }\n }\n\n /**\n * update this transition. Returns `true` if updated.\n */\n update() {\n if (!this._inProgress) {\n return false;\n }\n\n // It is important to initialize the handle during `update` instead of `start`.\n // The CPU time that the `start` frame takes should not be counted towards the duration.\n // On the other hand, `update` always happens during a render cycle. The clock starts when the\n // transition is rendered for the first time.\n if (this._handle === null) {\n const {_timeline: timeline, settings} = this;\n this._handle = timeline.addChannel({\n delay: timeline.getTime(),\n duration: settings.duration\n });\n }\n\n this.time = this._timeline.getTime(this._handle);\n // Call subclass method\n this._onUpdate();\n // Call user callback\n this.settings.onUpdate?.(this);\n\n // This only works if `settings.duration` is set\n // Spring transition must call `end` manually\n if (this._timeline.isFinished(this._handle)) {\n this.end();\n }\n return true;\n }\n\n /* Private API */\n\n protected _onUpdate() {\n // for subclass override\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport Transition, {TransitionSettings as BaseTransitionSettings} from '../transitions/transition';\nimport TransitionInterpolator from '../transitions/transition-interpolator';\nimport type {IViewState} from './view-state';\n\nimport type {Timeline} from '@luma.gl/engine';\nimport type {InteractionState} from './controller';\n\nconst noop = () => {};\n\n// Enums cannot be directly exported as they are not transpiled correctly into ES5, see https://github.com/visgl/deck.gl/issues/7130\nexport const TRANSITION_EVENTS = {\n BREAK: 1,\n SNAP_TO_END: 2,\n IGNORE: 3\n} as const;\n\ntype TransitionEvent = 1 | 2 | 3;\n\nexport type TransitionProps = {\n /** Transition duration in milliseconds, default value 0, implies no transition. When using `FlyToInterpolator`, it can also be set to `'auto'`. */\n transitionDuration?: number | 'auto';\n /** An interpolator object that defines the transition behavior between two viewports. */\n transitionInterpolator?: TransitionInterpolator;\n /** Easing function that can be used to achieve effects like \"Ease-In-Cubic\", \"Ease-Out-Cubic\", etc. Default value performs Linear easing. */\n transitionEasing?: (t: number) => number;\n /** Controls how to process a new view state change that occurs during an existing transition. */\n transitionInterruption?: TransitionEvent;\n /** Callback fired when requested transition starts. */\n onTransitionStart?: (transition: Transition) => void;\n /** Callback fired when requested transition is interrupted. */\n onTransitionInterrupt?: (transition: Transition) => void;\n /** Callback fired when requested transition ends. */\n onTransitionEnd?: (transition: Transition) => void;\n};\n\nconst DEFAULT_EASING = t => t;\nconst DEFAULT_INTERRUPTION = TRANSITION_EVENTS.BREAK;\n\ntype TransitionSettings = BaseTransitionSettings & {\n interpolator: TransitionInterpolator;\n easing: (t: number) => number;\n interruption: TransitionEvent;\n startProps: Record;\n endProps: Record;\n};\n\nexport default class TransitionManager> {\n getControllerState: (props: any) => ControllerState;\n props?: TransitionProps;\n propsInTransition: Record | null;\n transition: Transition;\n onViewStateChange: (params: {\n viewState: Record;\n oldViewState: Record;\n }) => void;\n onStateChange: (state: InteractionState) => void;\n\n constructor(opts: {\n timeline: Timeline;\n getControllerState: (props: any) => ControllerState;\n onViewStateChange?: (params: {\n viewState: Record;\n oldViewState: Record;\n }) => void;\n onStateChange?: (state: InteractionState) => void;\n }) {\n this.getControllerState = opts.getControllerState;\n this.propsInTransition = null;\n this.transition = new Transition(opts.timeline);\n\n this.onViewStateChange = opts.onViewStateChange || noop;\n this.onStateChange = opts.onStateChange || noop;\n }\n\n finalize(): void {\n this.transition.cancel();\n }\n\n // Returns current transitioned viewport.\n getViewportInTransition(): Record | null {\n return this.propsInTransition;\n }\n\n // Process the vewiport change, either ignore or trigger a new transition.\n // Return true if a new transition is triggered, false otherwise.\n processViewStateChange(nextProps: TransitionProps) {\n let transitionTriggered = false;\n const currentProps = this.props;\n // Set this.props here as '_triggerTransition' calls '_updateViewport' that uses this.props.\n this.props = nextProps;\n\n // NOTE: Be cautious re-ordering statements in this function.\n if (!currentProps || this._shouldIgnoreViewportChange(currentProps, nextProps)) {\n return false;\n }\n\n if (this._isTransitionEnabled(nextProps)) {\n let startProps = currentProps;\n if (this.transition.inProgress) {\n // @ts-expect-error\n const {interruption, endProps} = this.transition.settings as TransitionSettings;\n startProps = {\n ...currentProps,\n ...(interruption === TRANSITION_EVENTS.SNAP_TO_END\n ? endProps\n : this.propsInTransition || currentProps)\n };\n }\n\n this._triggerTransition(startProps, nextProps);\n\n transitionTriggered = true;\n } else {\n this.transition.cancel();\n }\n\n return transitionTriggered;\n }\n\n updateTransition() {\n this.transition.update();\n }\n\n // Helper methods\n\n _isTransitionEnabled(props: TransitionProps): boolean {\n const {transitionDuration, transitionInterpolator} = props;\n return (\n ((transitionDuration as number) > 0 || transitionDuration === 'auto') &&\n Boolean(transitionInterpolator)\n );\n }\n\n _isUpdateDueToCurrentTransition(props: TransitionProps): boolean {\n if (this.transition.inProgress && this.propsInTransition) {\n // @ts-expect-error\n return (this.transition.settings as TransitionSettings).interpolator.arePropsEqual(\n props,\n this.propsInTransition\n );\n }\n return false;\n }\n\n _shouldIgnoreViewportChange(currentProps: TransitionProps, nextProps: TransitionProps): boolean {\n if (this.transition.inProgress) {\n // @ts-expect-error\n const transitionSettings = this.transition.settings as TransitionSettings;\n // Ignore update if it is requested to be ignored\n return (\n transitionSettings.interruption === TRANSITION_EVENTS.IGNORE ||\n // Ignore update if it is due to current active transition.\n this._isUpdateDueToCurrentTransition(nextProps)\n );\n }\n if (this._isTransitionEnabled(nextProps)) {\n // Ignore if none of the viewport props changed.\n return (nextProps.transitionInterpolator as TransitionInterpolator).arePropsEqual(\n currentProps,\n nextProps\n );\n }\n return true;\n }\n\n _triggerTransition(startProps: TransitionProps, endProps: TransitionProps): void {\n const startViewstate = this.getControllerState(startProps);\n const endViewStateProps = this.getControllerState(endProps).shortestPathFrom(startViewstate);\n\n // update transitionDuration for 'auto' mode\n const transitionInterpolator = endProps.transitionInterpolator as TransitionInterpolator;\n const duration = transitionInterpolator.getDuration\n ? transitionInterpolator.getDuration(startProps, endProps)\n : (endProps.transitionDuration as number);\n\n if (duration === 0) {\n return;\n }\n\n const initialProps = transitionInterpolator.initializeProps(startProps, endViewStateProps);\n\n this.propsInTransition = {};\n const transitionSettings: TransitionSettings = {\n duration,\n easing: endProps.transitionEasing || DEFAULT_EASING,\n interpolator: transitionInterpolator,\n interruption: endProps.transitionInterruption || DEFAULT_INTERRUPTION,\n\n startProps: initialProps.start,\n endProps: initialProps.end,\n\n onStart: endProps.onTransitionStart,\n onUpdate: this._onTransitionUpdate,\n onInterrupt: this._onTransitionEnd(endProps.onTransitionInterrupt),\n onEnd: this._onTransitionEnd(endProps.onTransitionEnd)\n };\n this.transition.start(transitionSettings);\n\n this.onStateChange({inTransition: true});\n\n this.updateTransition();\n }\n\n _onTransitionEnd(callback?: (transition: Transition) => void) {\n return transition => {\n this.propsInTransition = null;\n\n this.onStateChange({\n inTransition: false,\n isZooming: false,\n isPanning: false,\n isRotating: false\n });\n\n callback?.(transition);\n };\n }\n\n _onTransitionUpdate = transition => {\n // NOTE: Be cautious re-ordering statements in this function.\n const {\n time,\n settings: {interpolator, startProps, endProps, duration, easing}\n } = transition;\n const t = easing(time / duration);\n const viewport = interpolator.interpolateProps(startProps, endProps, t);\n\n // This gurantees all props (e.g. bearing, longitude) are normalized\n // So when viewports are compared they are in same range.\n this.propsInTransition = this.getControllerState({\n ...this.props,\n ...viewport\n }).getViewportProps();\n\n this.onViewStateChange({\n viewState: this.propsInTransition,\n oldViewState: this.props as TransitionProps\n });\n };\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// Replacement for the external assert method to reduce bundle size\n// Note: We don't use the second \"message\" argument in calling code,\n// so no need to support it here\nexport default function assert(condition: any, message?: string): asserts condition {\n if (!condition) {\n throw new Error(message || 'deck.gl: assertion failed.');\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {equals} from '@math.gl/core';\nimport assert from '../utils/assert';\n\nexport default abstract class TransitionInterpolator {\n protected _propsToCompare: string[];\n protected _propsToExtract: string[];\n protected _requiredProps?: string[];\n\n /**\n * @param opts {array|object}\n * @param opts.compare {array} - prop names used in equality check\n * @param opts.extract {array} - prop names needed for interpolation\n * @param opts.required {array} - prop names that must be supplied\n * alternatively, supply one list of prop names as `opts` if all of the above are the same.\n */\n constructor(opts: {compare: string[]; extract?: string[]; required?: string[]}) {\n const {compare, extract, required} = opts;\n\n this._propsToCompare = compare;\n this._propsToExtract = extract || compare;\n this._requiredProps = required;\n }\n\n /**\n * Checks if two sets of props need transition in between\n * @param currentProps {object} - a list of viewport props\n * @param nextProps {object} - a list of viewport props\n * @returns {bool} - true if two props are equivalent\n */\n arePropsEqual(currentProps: Record, nextProps: Record): boolean {\n for (const key of this._propsToCompare) {\n if (\n !(key in currentProps) ||\n !(key in nextProps) ||\n !equals(currentProps[key], nextProps[key])\n ) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Called before transition starts to validate/pre-process start and end props\n * @param startProps {object} - a list of starting viewport props\n * @param endProps {object} - a list of target viewport props\n * @returns {Object} {start, end} - start and end props to be passed\n * to `interpolateProps`\n */\n initializeProps(\n startProps: Record,\n endProps: Record\n ): {\n start: Record;\n end: Record;\n } {\n const startViewStateProps = {};\n const endViewStateProps = {};\n\n for (const key of this._propsToExtract) {\n if (key in startProps || key in endProps) {\n startViewStateProps[key] = startProps[key];\n endViewStateProps[key] = endProps[key];\n }\n }\n\n this._checkRequiredProps(startViewStateProps);\n this._checkRequiredProps(endViewStateProps);\n\n return {start: startViewStateProps, end: endViewStateProps};\n }\n\n /**\n * Returns viewport props in transition\n * @param startProps {object} - a list of starting viewport props\n * @param endProps {object} - a list of target viewport props\n * @param t {number} - a time factor between [0, 1]\n * @returns {object} - a list of interpolated viewport props\n */\n abstract interpolateProps(\n startProps: Record,\n endProps: Record,\n t: number\n ): Record;\n\n /**\n * Returns transition duration\n * @param startProps {object} - a list of starting viewport props\n * @param endProps {object} - a list of target viewport props\n * @returns {Number} - transition duration in milliseconds\n */\n getDuration(startProps: Record, endProps: Record): number {\n return endProps.transitionDuration;\n }\n\n _checkRequiredProps(props) {\n if (!this._requiredProps) {\n return;\n }\n\n this._requiredProps.forEach(propName => {\n const value = props[propName];\n assert(\n Number.isFinite(value) || Array.isArray(value),\n `${propName} is required for transition`\n );\n });\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Matrix4} from '@math.gl/core';\nimport Viewport from './viewport';\nimport {PROJECTION_MODE} from '../lib/constants';\nimport {altitudeToFovy, fovyToAltitude} from '@math.gl/web-mercator';\nimport {MAX_LATITUDE} from '@math.gl/web-mercator';\n\nimport {vec3, vec4} from '@math.gl/core';\n\nconst DEGREES_TO_RADIANS = Math.PI / 180;\nconst RADIANS_TO_DEGREES = 180 / Math.PI;\nconst EARTH_RADIUS = 6370972;\nexport const GLOBE_RADIUS = 256;\n\nfunction getDistanceScales() {\n const unitsPerMeter = GLOBE_RADIUS / EARTH_RADIUS;\n const unitsPerDegree = (Math.PI / 180) * GLOBE_RADIUS;\n\n return {\n unitsPerMeter: [unitsPerMeter, unitsPerMeter, unitsPerMeter],\n unitsPerMeter2: [0, 0, 0],\n metersPerUnit: [1 / unitsPerMeter, 1 / unitsPerMeter, 1 / unitsPerMeter],\n unitsPerDegree: [unitsPerDegree, unitsPerDegree, unitsPerMeter],\n unitsPerDegree2: [0, 0, 0],\n degreesPerUnit: [1 / unitsPerDegree, 1 / unitsPerDegree, 1 / unitsPerMeter]\n };\n}\n\nexport type GlobeViewportOptions = {\n /** Name of the viewport */\n id?: string;\n /** Left offset from the canvas edge, in pixels */\n x?: number;\n /** Top offset from the canvas edge, in pixels */\n y?: number;\n /** Viewport width in pixels */\n width?: number;\n /** Viewport height in pixels */\n height?: number;\n /** Longitude in degrees */\n longitude?: number;\n /** Latitude in degrees */\n latitude?: number;\n /** Camera altitude relative to the viewport height, used to control the FOV. Default `1.5` */\n altitude?: number;\n /* Meter offsets of the viewport center from lng, lat, elevation */\n position?: number[];\n /** Zoom level */\n zoom?: number;\n /** Use orthographic projection */\n orthographic?: boolean;\n /** Camera fovy in degrees. If provided, overrides `altitude` */\n fovy?: number;\n /** Scaler for the near plane, 1 unit equals to the height of the viewport. Default `0.5` */\n nearZMultiplier?: number;\n /** Scaler for the far plane, 1 unit equals to the distance from the camera to the edge of the screen. Default `1` */\n farZMultiplier?: number;\n /** Optionally override the near plane position. `nearZMultiplier` is ignored if `nearZ` is supplied. */\n nearZ?: number;\n /** Optionally override the far plane position. `farZMultiplier` is ignored if `farZ` is supplied. */\n farZ?: number;\n /** The resolution at which to turn flat features into 3D meshes, in degrees. Smaller numbers will generate more detailed mesh. Default `10` */\n resolution?: number;\n};\n\nexport default class GlobeViewport extends Viewport {\n static displayName = 'GlobeViewport';\n\n longitude: number;\n latitude: number;\n fovy: number;\n resolution: number;\n\n constructor(opts: GlobeViewportOptions = {}) {\n const {\n longitude = 0,\n zoom = 0,\n // Matches Maplibre defaults\n // https://github.com/maplibre/maplibre-gl-js/blob/f8ab4b48d59ab8fe7b068b102538793bbdd4c848/src/geo/projection/globe_transform.ts#L632-L633\n nearZMultiplier = 0.5,\n farZMultiplier = 1,\n resolution = 10\n } = opts;\n\n let {latitude = 0, height, altitude = 1.5, fovy} = opts;\n\n // Clamp to web mercator limit to prevent bad inputs\n latitude = Math.max(Math.min(latitude, MAX_LATITUDE), -MAX_LATITUDE);\n\n height = height || 1;\n if (fovy) {\n altitude = fovyToAltitude(fovy);\n } else {\n fovy = altitudeToFovy(altitude);\n }\n // Exagerate distance by latitude to match the Web Mercator distortion\n // The goal is that globe and web mercator projection results converge at high zoom\n // https://github.com/maplibre/maplibre-gl-js/blob/f8ab4b48d59ab8fe7b068b102538793bbdd4c848/src/geo/projection/globe_transform.ts#L575-L577\n const scale = Math.pow(2, zoom - zoomAdjust(latitude));\n const nearZ = opts.nearZ ?? nearZMultiplier;\n const farZ = opts.farZ ?? (altitude + (GLOBE_RADIUS * 2 * scale) / height) * farZMultiplier;\n\n // Calculate view matrix\n const viewMatrix = new Matrix4().lookAt({eye: [0, -altitude, 0], up: [0, 0, 1]});\n viewMatrix.rotateX(latitude * DEGREES_TO_RADIANS);\n viewMatrix.rotateZ(-longitude * DEGREES_TO_RADIANS);\n viewMatrix.scale(scale / height);\n\n super({\n ...opts,\n // x, y, width,\n height,\n\n // view matrix\n viewMatrix,\n longitude,\n latitude,\n zoom,\n\n // projection matrix parameters\n distanceScales: getDistanceScales(),\n fovy,\n focalDistance: altitude,\n near: nearZ,\n far: farZ\n });\n\n this.scale = scale;\n this.latitude = latitude;\n this.longitude = longitude;\n this.fovy = fovy;\n this.resolution = resolution;\n }\n\n get projectionMode() {\n return PROJECTION_MODE.GLOBE;\n }\n\n getDistanceScales() {\n return this.distanceScales;\n }\n\n getBounds(options: {z?: number} = {}): [number, number, number, number] {\n const unprojectOption = {targetZ: options.z || 0};\n\n const left = this.unproject([0, this.height / 2], unprojectOption);\n const top = this.unproject([this.width / 2, 0], unprojectOption);\n const right = this.unproject([this.width, this.height / 2], unprojectOption);\n const bottom = this.unproject([this.width / 2, this.height], unprojectOption);\n\n if (right[0] < this.longitude) right[0] += 360;\n if (left[0] > this.longitude) left[0] -= 360;\n\n return [\n Math.min(left[0], right[0], top[0], bottom[0]),\n Math.min(left[1], right[1], top[1], bottom[1]),\n Math.max(left[0], right[0], top[0], bottom[0]),\n Math.max(left[1], right[1], top[1], bottom[1])\n ];\n }\n\n unproject(\n xyz: number[],\n {topLeft = true, targetZ}: {topLeft?: boolean; targetZ?: number} = {}\n ): number[] {\n const [x, y, z] = xyz;\n\n const y2 = topLeft ? y : this.height - y;\n const {pixelUnprojectionMatrix} = this;\n\n let coord;\n if (Number.isFinite(z)) {\n // Has depth component\n coord = transformVector(pixelUnprojectionMatrix, [x, y2, z, 1]);\n } else {\n // since we don't know the correct projected z value for the point,\n // unproject two points to get a line and then find the point on that line that intersects with the sphere\n const coord0 = transformVector(pixelUnprojectionMatrix, [x, y2, -1, 1]);\n const coord1 = transformVector(pixelUnprojectionMatrix, [x, y2, 1, 1]);\n\n const lt = ((targetZ || 0) / EARTH_RADIUS + 1) * GLOBE_RADIUS;\n const lSqr = vec3.sqrLen(vec3.sub([], coord0, coord1));\n const l0Sqr = vec3.sqrLen(coord0);\n const l1Sqr = vec3.sqrLen(coord1);\n const sSqr = (4 * l0Sqr * l1Sqr - (lSqr - l0Sqr - l1Sqr) ** 2) / 16;\n const dSqr = (4 * sSqr) / lSqr;\n const r0 = Math.sqrt(l0Sqr - dSqr);\n const dr = Math.sqrt(Math.max(0, lt * lt - dSqr));\n const t = (r0 - dr) / Math.sqrt(lSqr);\n\n coord = vec3.lerp([], coord0, coord1, t);\n }\n const [X, Y, Z] = this.unprojectPosition(coord);\n\n if (Number.isFinite(z)) {\n return [X, Y, Z];\n }\n return Number.isFinite(targetZ) ? [X, Y, targetZ as number] : [X, Y];\n }\n\n projectPosition(xyz: number[]): [number, number, number] {\n const [lng, lat, Z = 0] = xyz;\n const lambda = lng * DEGREES_TO_RADIANS;\n const phi = lat * DEGREES_TO_RADIANS;\n const cosPhi = Math.cos(phi);\n const D = (Z / EARTH_RADIUS + 1) * GLOBE_RADIUS;\n\n return [Math.sin(lambda) * cosPhi * D, -Math.cos(lambda) * cosPhi * D, Math.sin(phi) * D];\n }\n\n unprojectPosition(xyz: number[]): [number, number, number] {\n const [x, y, z] = xyz;\n const D = vec3.len(xyz);\n const phi = Math.asin(z / D);\n const lambda = Math.atan2(x, -y);\n\n const lng = lambda * RADIANS_TO_DEGREES;\n const lat = phi * RADIANS_TO_DEGREES;\n const Z = (D / GLOBE_RADIUS - 1) * EARTH_RADIUS;\n return [lng, lat, Z];\n }\n\n projectFlat(xyz: number[]): [number, number] {\n return xyz as [number, number];\n }\n\n unprojectFlat(xyz: number[]): [number, number] {\n return xyz as [number, number];\n }\n\n /**\n * Pan the globe using delta-based movement\n * @param coords - the geographic coordinates where the pan started\n * @param pixel - the current screen position\n * @param startPixel - the screen position where the pan started\n * @returns updated viewport options with new longitude/latitude\n */\n panByPosition(\n [startLng, startLat, startZoom]: number[],\n pixel: number[],\n startPixel: number[]\n ): GlobeViewportOptions {\n // Scale rotation speed inversely with zoom, to approximate constant panning speed\n const scale = Math.pow(2, this.zoom - zoomAdjust(this.latitude));\n const rotationSpeed = 0.25 / scale;\n\n const longitude = startLng + rotationSpeed * (startPixel[0] - pixel[0]);\n let latitude = startLat - rotationSpeed * (startPixel[1] - pixel[1]);\n latitude = Math.max(Math.min(latitude, MAX_LATITUDE), -MAX_LATITUDE);\n const out = {longitude, latitude, zoom: startZoom - zoomAdjust(startLat)};\n out.zoom += zoomAdjust(out.latitude);\n return out;\n }\n}\n\nexport function zoomAdjust(latitude: number): number {\n const scaleAdjust = Math.PI * Math.cos((latitude * Math.PI) / 180);\n return Math.log2(scaleAdjust);\n}\n\nfunction transformVector(matrix: number[], vector: number[]): number[] {\n const result = vec4.transformMat4([], vector, matrix);\n vec4.scale(result, result, 1 / result[3]);\n return result;\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport TransitionInterpolator from './transition-interpolator';\nimport {lerp} from '@math.gl/core';\n\nimport log from '../utils/log';\nimport type Viewport from '../viewports/viewport';\nimport GlobeViewport from '../viewports/globe-viewport';\n\nconst DEFAULT_PROPS = ['longitude', 'latitude', 'zoom', 'bearing', 'pitch'];\nconst DEFAULT_REQUIRED_PROPS = ['longitude', 'latitude', 'zoom'];\n\ntype PropsWithAnchor = {\n around?: number[];\n aroundPosition?: number[];\n [key: string]: any;\n};\n\n/**\n * Performs linear interpolation of two view states.\n */\nexport default class LinearInterpolator extends TransitionInterpolator {\n opts: {\n around?: number[];\n makeViewport?: (props: Record) => Viewport;\n };\n\n /**\n * @param {Object} opts\n * @param {Array} opts.transitionProps - list of props to apply linear transition to.\n * @param {Array} opts.around - a screen point to zoom/rotate around.\n * @param {Function} opts.makeViewport - construct a viewport instance with given props.\n */\n constructor(\n opts:\n | string[]\n | {\n transitionProps?:\n | string[]\n | {\n compare: string[];\n extract?: string[];\n required?: string[];\n };\n around?: number[];\n makeViewport?: (props: Record) => Viewport;\n } = {}\n ) {\n // Backward compatibility\n const transitionProps = Array.isArray(opts) ? opts : opts.transitionProps;\n\n const normalizedOpts = Array.isArray(opts) ? {} : opts;\n normalizedOpts.transitionProps = Array.isArray(transitionProps)\n ? {\n compare: transitionProps,\n required: transitionProps\n }\n : transitionProps || {\n compare: DEFAULT_PROPS,\n required: DEFAULT_REQUIRED_PROPS\n };\n\n super(normalizedOpts.transitionProps);\n this.opts = normalizedOpts;\n }\n\n initializeProps(\n startProps: Record,\n endProps: Record\n ): {\n start: PropsWithAnchor;\n end: PropsWithAnchor;\n } {\n const result = super.initializeProps(startProps, endProps);\n\n const {makeViewport, around} = this.opts;\n\n if (makeViewport && around) {\n const TestViewport = makeViewport(startProps);\n if (TestViewport instanceof GlobeViewport) {\n log.warn('around not supported in GlobeView')();\n } else {\n const startViewport = makeViewport(startProps);\n const endViewport = makeViewport(endProps);\n const aroundPosition = startViewport.unproject(around);\n result.start.around = around;\n Object.assign(result.end, {\n around: endViewport.project(aroundPosition),\n aroundPosition,\n width: endProps.width,\n height: endProps.height\n });\n }\n }\n\n return result;\n }\n\n interpolateProps(\n startProps: PropsWithAnchor,\n endProps: PropsWithAnchor,\n t: number\n ): Record {\n const propsInTransition = {};\n for (const key of this._propsToExtract) {\n propsInTransition[key] = lerp(startProps[key] || 0, endProps[key] || 0, t);\n }\n\n if (endProps.aroundPosition && this.opts.makeViewport) {\n // Linear transition should be performed in common space\n const viewport = this.opts.makeViewport({...endProps, ...propsInTransition});\n Object.assign(\n propsInTransition,\n viewport.panByPosition(\n endProps.aroundPosition,\n // anchor point in current screen coordinates\n lerp(startProps.around as number[], endProps.around as number[], t) as number[]\n )\n );\n }\n return propsInTransition;\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/* eslint-disable max-statements, complexity */\nimport TransitionManager, {TransitionProps} from './transition-manager';\nimport LinearInterpolator from '../transitions/linear-interpolator';\nimport {IViewState} from './view-state';\nimport {ConstructorOf} from '../types/types';\nimport {deepEqual} from '../utils/deep-equal';\n\nimport type Viewport from '../viewports/viewport';\n\nimport type {EventManager, MjolnirEvent, MjolnirGestureEvent, MjolnirWheelEvent, MjolnirKeyEvent} from 'mjolnir.js';\nimport type {Timeline} from '@luma.gl/engine';\n\nconst NO_TRANSITION_PROPS = {\n transitionDuration: 0\n} as const;\n\nconst DEFAULT_INERTIA = 300;\nconst INERTIA_EASING = t => 1 - (1 - t) * (1 - t);\n\nconst EVENT_TYPES = {\n WHEEL: ['wheel'],\n PAN: ['panstart', 'panmove', 'panend'],\n PINCH: ['pinchstart', 'pinchmove', 'pinchend'],\n MULTI_PAN: ['multipanstart', 'multipanmove', 'multipanend'],\n DOUBLE_CLICK: ['dblclick'],\n KEYBOARD: ['keydown']\n} as const;\n\n/** Configuration of how user input is handled */\nexport type ControllerOptions = {\n /** Enable zooming with mouse wheel. Default `true`. */\n scrollZoom?: boolean | {\n /** Scaler that translates wheel delta to the change of viewport scale. Default `0.01`. */\n speed?: number;\n /** Smoothly transition to the new zoom. If enabled, will provide a slightly lagged but smoother experience. Default `false`. */\n smooth?: boolean\n };\n /** Enable panning with pointer drag. Default `true` */\n dragPan?: boolean;\n /** Enable rotating with pointer drag. Default `true` */\n dragRotate?: boolean;\n /** Enable zooming with double click. Default `true` */\n doubleClickZoom?: boolean;\n /** Enable zooming with multi-touch. Default `true` */\n touchZoom?: boolean;\n /** Enable rotating with multi-touch. Use two-finger rotating gesture for horizontal and three-finger swiping gesture for vertical rotation. Default `false` */\n touchRotate?: boolean;\n /** Enable interaction with keyboard. Default `true`. */\n keyboard?:\n | boolean\n | {\n /** Speed of zoom using +/- keys. Default `2` */\n zoomSpeed?: number;\n /** Speed of movement using arrow keys, in pixels. */\n moveSpeed?: number;\n /** Speed of rotation using shift + left/right arrow keys, in degrees. Default 15. */\n rotateSpeedX?: number;\n /** Speed of rotation using shift + up/down arrow keys, in degrees. Default 10. */\n rotateSpeedY?: number;\n };\n /** Drag behavior without pressing function keys, one of `pan` and `rotate`. */\n dragMode?: 'pan' | 'rotate';\n /** Enable inertia after panning/pinching. If a number is provided, indicates the duration of time over which the velocity reduces to zero, in milliseconds. Default `false`. */\n inertia?: boolean | number;\n /** Bounding box of content that the controller is constrained in */\n maxBounds?: [min: [number, number], max: [number, number]] | [min: [number, number, number], max: [number, number, number]] | null;\n};\n\nexport type ControllerProps = {\n /** Identifier of the controller */\n id: string;\n /** Viewport x position */\n x: number;\n /** Viewport y position */\n y: number;\n /** Viewport width */\n width: number;\n /** Viewport height */\n height: number;\n} & ControllerOptions & TransitionProps;\n\n/** The state of a controller */\nexport type InteractionState = {\n /** If the view state is in transition */\n inTransition?: boolean;\n /** If the user is dragging */\n isDragging?: boolean;\n /** If the view is being panned, either from user input or transition */\n isPanning?: boolean;\n /** If the view is being rotated, either from user input or transition */\n isRotating?: boolean;\n /** If the view is being zoomed, either from user input or transition */\n isZooming?: boolean;\n /** World coordinate [lng, lat, altitude] of rotation pivot point when rotating */\n rotationPivotPosition?: [number, number, number];\n}\n\n/** Parameters passed to the onViewStateChange callback */\nexport type ViewStateChangeParameters = {\n viewId: string;\n /** The next view state, either from user input or transition */\n viewState: ViewStateT;\n /** Object describing the nature of the view state change */\n interactionState: InteractionState;\n /** The current view state */\n oldViewState?: ViewStateT;\n}\n\nconst pinchEventWorkaround: any = {};\n\nexport default abstract class Controller> {\n abstract get ControllerState(): ConstructorOf;\n abstract get transition(): TransitionProps;\n\n // @ts-expect-error (2564) - not assigned in the constructor\n protected props: ControllerProps;\n protected state: Record = {};\n\n protected transitionManager: TransitionManager;\n protected eventManager: EventManager;\n protected onViewStateChange: (params: ViewStateChangeParameters) => void;\n protected onStateChange: (state: InteractionState) => void;\n protected makeViewport: (opts: Record) => Viewport;\n protected pickPosition?: (x: number, y: number) => {coordinate?: number[]} | null;\n\n private _controllerState?: ControllerState;\n private _events: Record = {};\n private _interactionState: InteractionState = {\n isDragging: false\n };\n private _customEvents: string[] = [];\n private _eventStartBlocked: any = null;\n private _panMove: boolean = false;\n\n protected invertPan: boolean = false;\n protected dragMode: 'pan' | 'rotate' = 'rotate';\n protected inertia: number = 0;\n protected scrollZoom: boolean | {speed?: number; smooth?: boolean} = true;\n protected dragPan: boolean = true;\n protected dragRotate: boolean = true;\n protected doubleClickZoom: boolean = true;\n protected touchZoom: boolean = true;\n protected touchRotate: boolean = false;\n protected keyboard:\n | boolean\n | {\n zoomSpeed?: number; // speed of zoom using +/- keys. Default 2.\n moveSpeed?: number; // speed of movement using arrow keys, in pixels.\n rotateSpeedX?: number; // speed of rotation using shift + left/right arrow keys, in degrees. Default 15.\n rotateSpeedY?: number; // speed of rotation using shift + up/down arrow keys, in degrees. Default 10.\n } = true;\n\n constructor(opts: {\n timeline: Timeline,\n eventManager: EventManager;\n makeViewport: (opts: Record) => Viewport;\n onViewStateChange: (params: ViewStateChangeParameters) => void;\n onStateChange: (state: InteractionState) => void;\n pickPosition?: (x: number, y: number) => {coordinate?: number[]} | null;\n }) {\n this.transitionManager = new TransitionManager({\n ...opts,\n getControllerState: props => new this.ControllerState(props),\n onViewStateChange: this._onTransition.bind(this),\n onStateChange: this._setInteractionState.bind(this)\n });\n\n this.handleEvent = this.handleEvent.bind(this);\n\n this.eventManager = opts.eventManager;\n this.onViewStateChange = opts.onViewStateChange || (() => {});\n this.onStateChange = opts.onStateChange || (() => {});\n this.makeViewport = opts.makeViewport;\n this.pickPosition = opts.pickPosition;\n }\n\n set events(customEvents) {\n this.toggleEvents(this._customEvents, false);\n this.toggleEvents(customEvents, true);\n this._customEvents = customEvents;\n // Make sure default events are not overwritten\n if (this.props) {\n this.setProps(this.props);\n }\n }\n\n finalize() {\n for (const eventName in this._events) {\n if (this._events[eventName]) {\n // @ts-ignore (2345) event type string cannot be assifned to enum\n // eslint-disable-next-line @typescript-eslint/unbound-method\n this.eventManager?.off(eventName, this.handleEvent);\n }\n }\n this.transitionManager.finalize();\n }\n\n /**\n * Callback for events\n */\n handleEvent(event: MjolnirEvent) {\n // Force recalculate controller state\n this._controllerState = undefined;\n const eventStartBlocked = this._eventStartBlocked;\n\n switch (event.type) {\n case 'panstart':\n return eventStartBlocked ? false : this._onPanStart(event);\n case 'panmove':\n return this._onPan(event);\n case 'panend':\n return this._onPanEnd(event);\n case 'pinchstart':\n return eventStartBlocked ? false : this._onPinchStart(event);\n case 'pinchmove':\n return this._onPinch(event);\n case 'pinchend':\n return this._onPinchEnd(event);\n case 'multipanstart':\n return eventStartBlocked ? false : this._onMultiPanStart(event);\n case 'multipanmove':\n return this._onMultiPan(event);\n case 'multipanend':\n return this._onMultiPanEnd(event);\n case 'dblclick':\n return this._onDoubleClick(event);\n case 'wheel':\n return this._onWheel(event as MjolnirWheelEvent);\n case 'keydown':\n return this._onKeyDown(event as MjolnirKeyEvent);\n default:\n return false;\n }\n }\n\n /* Event utils */\n // Event object: http://hammerjs.github.io/api/#event-object\n get controllerState(): ControllerState {\n this._controllerState = this._controllerState || new this.ControllerState({\n makeViewport: this.makeViewport,\n ...this.props,\n ...this.state\n });\n return this._controllerState;\n }\n\n getCenter(event: MjolnirGestureEvent | MjolnirWheelEvent) : [number, number] {\n const {x, y} = this.props;\n const {offsetCenter} = event;\n return [offsetCenter.x - x, offsetCenter.y - y];\n }\n\n isPointInBounds(pos: [number, number], event: MjolnirEvent): boolean {\n const {width, height} = this.props;\n if (event && event.handled) {\n return false;\n }\n\n const inside = pos[0] >= 0 && pos[0] <= width && pos[1] >= 0 && pos[1] <= height;\n if (inside && event) {\n event.stopPropagation();\n }\n return inside;\n }\n\n isFunctionKeyPressed(event: MjolnirEvent): boolean {\n const {srcEvent} = event;\n return Boolean(srcEvent.metaKey || srcEvent.altKey || srcEvent.ctrlKey || srcEvent.shiftKey);\n }\n\n isDragging(): boolean {\n return this._interactionState.isDragging || false;\n }\n\n // When a multi-touch event ends, e.g. pinch, not all pointers are lifted at the same time.\n // This triggers a brief `pan` event.\n // Calling this method will temporarily disable *start events to avoid conflicting transitions.\n blockEvents(timeout: number): void {\n /* global setTimeout */\n const timer = setTimeout(() => {\n if (this._eventStartBlocked === timer) {\n this._eventStartBlocked = null;\n }\n }, timeout);\n this._eventStartBlocked = timer;\n }\n\n /**\n * Extract interactivity options\n */\n setProps(props: ControllerProps) {\n if (props.dragMode) {\n this.dragMode = props.dragMode;\n }\n const oldProps = this.props;\n this.props = props;\n\n if (!('transitionInterpolator' in props)) {\n // Add default transition interpolator\n props.transitionInterpolator = this._getTransitionProps().transitionInterpolator;\n }\n\n this.transitionManager.processViewStateChange(props);\n\n const {inertia} = props;\n this.inertia = Number.isFinite(inertia) ? (inertia as number) : (inertia === true ? DEFAULT_INERTIA : 0);\n\n // TODO - make sure these are not reset on every setProps\n const {\n scrollZoom = true,\n dragPan = true,\n dragRotate = true,\n doubleClickZoom = true,\n touchZoom = true,\n touchRotate = false,\n keyboard = true\n } = props;\n\n // Register/unregister events\n const isInteractive = Boolean(this.onViewStateChange);\n this.toggleEvents(EVENT_TYPES.WHEEL, isInteractive && scrollZoom);\n // We always need the pan events to set the correct isDragging state, even if dragPan & dragRotate are both false\n this.toggleEvents(EVENT_TYPES.PAN, isInteractive);\n this.toggleEvents(EVENT_TYPES.PINCH, isInteractive && (touchZoom || touchRotate));\n this.toggleEvents(EVENT_TYPES.MULTI_PAN, isInteractive && touchRotate);\n this.toggleEvents(EVENT_TYPES.DOUBLE_CLICK, isInteractive && doubleClickZoom);\n this.toggleEvents(EVENT_TYPES.KEYBOARD, isInteractive && keyboard);\n\n // Interaction toggles\n this.scrollZoom = scrollZoom;\n this.dragPan = dragPan;\n this.dragRotate = dragRotate;\n this.doubleClickZoom = doubleClickZoom;\n this.touchZoom = touchZoom;\n this.touchRotate = touchRotate;\n this.keyboard = keyboard;\n\n // Normalize view state if maxBounds is defined\n const dimensionChanged = !oldProps || oldProps.height !== props.height || oldProps.width !== props.width || oldProps.maxBounds !== props.maxBounds;\n if (dimensionChanged && props.maxBounds) {\n // Dimensions changed, try re-normalize the props\n const controllerState = new this.ControllerState({...props, makeViewport: this.makeViewport});\n const normalizedProps = controllerState.getViewportProps();\n const changed = Object.keys(normalizedProps).some(key => !deepEqual(normalizedProps[key], props[key], 1));\n if (changed) {\n // some props are updated after normalization\n this.updateViewport(controllerState);\n }\n }\n }\n\n updateTransition() {\n this.transitionManager.updateTransition();\n }\n\n toggleEvents(eventNames, enabled) {\n if (this.eventManager) {\n eventNames.forEach(eventName => {\n if (this._events[eventName] !== enabled) {\n this._events[eventName] = enabled;\n if (enabled) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n this.eventManager.on(eventName, this.handleEvent);\n } else {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n this.eventManager.off(eventName, this.handleEvent);\n }\n }\n });\n }\n }\n\n // Private Methods\n\n /* Callback util */\n // formats map state and invokes callback function\n protected updateViewport(newControllerState: ControllerState, extraProps: Record | null = null, interactionState: InteractionState = {}) {\n const viewState = {...newControllerState.getViewportProps(), ...extraProps};\n\n // TODO - to restore diffing, we need to include interactionState\n const changed = this.controllerState !== newControllerState;\n // const oldViewState = this.controllerState.getViewportProps();\n // const changed = Object.keys(viewState).some(key => oldViewState[key] !== viewState[key]);\n\n this.state = newControllerState.getState();\n this._setInteractionState(interactionState);\n\n if (changed) {\n const oldViewState = this.controllerState && this.controllerState.getViewportProps();\n if (this.onViewStateChange) {\n this.onViewStateChange({viewState, interactionState: this._interactionState, oldViewState, viewId: this.props.id});\n }\n }\n }\n\n private _onTransition(params: {viewState: Record, oldViewState: Record}) {\n this.onViewStateChange({...params, interactionState: this._interactionState, viewId: this.props.id});\n }\n\n private _setInteractionState(newStates: InteractionState) {\n Object.assign(this._interactionState, newStates);\n this.onStateChange(this._interactionState);\n }\n\n /* Event handlers */\n // Default handler for the `panstart` event.\n protected _onPanStart(event: MjolnirGestureEvent): boolean {\n const pos = this.getCenter(event);\n if (!this.isPointInBounds(pos, event)) {\n return false;\n }\n let alternateMode = this.isFunctionKeyPressed(event) || event.rightButton || false;\n if (this.invertPan || this.dragMode === 'pan') {\n // invertPan is replaced by props.dragMode, keeping for backward compatibility\n alternateMode = !alternateMode;\n }\n\n const newControllerState = this.controllerState[alternateMode ? 'panStart' : 'rotateStart']({\n pos\n });\n this._panMove = alternateMode;\n this.updateViewport(newControllerState, NO_TRANSITION_PROPS, {isDragging: true});\n return true;\n }\n\n // Default handler for the `panmove` and `panend` event.\n protected _onPan(event: MjolnirGestureEvent): boolean {\n if (!this.isDragging()) {\n return false;\n }\n return this._panMove ? this._onPanMove(event) : this._onPanRotate(event);\n }\n\n protected _onPanEnd(event: MjolnirGestureEvent): boolean {\n if (!this.isDragging()) {\n return false;\n }\n return this._panMove ? this._onPanMoveEnd(event) : this._onPanRotateEnd(event);\n }\n\n // Default handler for panning to move.\n // Called by `_onPan` when panning without function key pressed.\n protected _onPanMove(event: MjolnirGestureEvent): boolean {\n if (!this.dragPan) {\n return false;\n }\n const pos = this.getCenter(event);\n const newControllerState = this.controllerState.pan({pos});\n this.updateViewport(newControllerState, NO_TRANSITION_PROPS, {\n isDragging: true,\n isPanning: true\n });\n return true;\n }\n\n protected _onPanMoveEnd(event: MjolnirGestureEvent): boolean {\n const {inertia} = this;\n if (this.dragPan && inertia && event.velocity) {\n const pos = this.getCenter(event);\n const endPos: [number, number] = [\n pos[0] + (event.velocityX * inertia) / 2,\n pos[1] + (event.velocityY * inertia) / 2\n ];\n const newControllerState = this.controllerState.pan({pos: endPos}).panEnd();\n this.updateViewport(\n newControllerState,\n {\n ...this._getTransitionProps(),\n transitionDuration: inertia,\n transitionEasing: INERTIA_EASING\n },\n {\n isDragging: false,\n isPanning: true\n }\n );\n } else {\n const newControllerState = this.controllerState.panEnd();\n this.updateViewport(newControllerState, null, {\n isDragging: false,\n isPanning: false\n });\n }\n return true;\n }\n\n // Default handler for panning to rotate.\n // Called by `_onPan` when panning with function key pressed.\n protected _onPanRotate(event: MjolnirGestureEvent): boolean {\n if (!this.dragRotate) {\n return false;\n }\n\n const pos = this.getCenter(event);\n const newControllerState = this.controllerState.rotate({pos});\n this.updateViewport(newControllerState, NO_TRANSITION_PROPS, {\n isDragging: true,\n isRotating: true\n });\n return true;\n }\n\n protected _onPanRotateEnd(event): boolean {\n const {inertia} = this;\n if (this.dragRotate && inertia && event.velocity) {\n const pos = this.getCenter(event);\n const endPos: [number, number] = [\n pos[0] + (event.velocityX * inertia) / 2,\n pos[1] + (event.velocityY * inertia) / 2\n ];\n const newControllerState = this.controllerState.rotate({pos: endPos}).rotateEnd();\n this.updateViewport(\n newControllerState,\n {\n ...this._getTransitionProps(),\n transitionDuration: inertia,\n transitionEasing: INERTIA_EASING\n },\n {\n isDragging: false,\n isRotating: true\n }\n );\n } else {\n const newControllerState = this.controllerState.rotateEnd();\n this.updateViewport(newControllerState, null, {\n isDragging: false,\n isRotating: false\n });\n }\n return true;\n }\n\n // Default handler for the `wheel` event.\n protected _onWheel(event: MjolnirWheelEvent): boolean {\n if (!this.scrollZoom) {\n return false;\n }\n\n const pos = this.getCenter(event);\n if (!this.isPointInBounds(pos, event)) {\n return false;\n }\n event.srcEvent.preventDefault();\n\n const {speed = 0.01, smooth = false} = this.scrollZoom === true ? {} : this.scrollZoom;\n const {delta} = event;\n\n // Map wheel delta to relative scale\n let scale = 2 / (1 + Math.exp(-Math.abs(delta * speed)));\n if (delta < 0 && scale !== 0) {\n scale = 1 / scale;\n }\n\n const transitionProps = smooth\n ? {...this._getTransitionProps({around: pos}), transitionDuration: 250}\n : NO_TRANSITION_PROPS;\n\n const newControllerState = this.controllerState.zoom({pos, scale});\n this.updateViewport(\n newControllerState,\n transitionProps,\n {\n isZooming: true,\n isPanning: true\n }\n );\n\n // When there's no transition (duration = 0), immediately reset interaction state\n // since _onTransitionEnd callback won't fire\n if (!smooth) {\n this._setInteractionState({isZooming: false, isPanning: false});\n }\n return true;\n }\n\n protected _onMultiPanStart(event: MjolnirGestureEvent): boolean {\n const pos = this.getCenter(event);\n if (!this.isPointInBounds(pos, event)) {\n return false;\n }\n const newControllerState = this.controllerState.rotateStart({pos});\n this.updateViewport(newControllerState, NO_TRANSITION_PROPS, {isDragging: true});\n return true;\n }\n\n protected _onMultiPan(event: MjolnirGestureEvent): boolean {\n if (!this.touchRotate) {\n return false;\n }\n if (!this.isDragging()) {\n return false;\n }\n\n const pos = this.getCenter(event);\n pos[0] -= event.deltaX;\n\n const newControllerState = this.controllerState.rotate({pos});\n this.updateViewport(newControllerState, NO_TRANSITION_PROPS, {\n isDragging: true,\n isRotating: true\n });\n return true;\n }\n\n protected _onMultiPanEnd(event: MjolnirGestureEvent): boolean {\n if (!this.isDragging()) {\n return false;\n }\n const {inertia} = this;\n if (this.touchRotate && inertia && event.velocityY) {\n const pos = this.getCenter(event);\n const endPos: [number, number] = [pos[0], (pos[1] += (event.velocityY * inertia) / 2)];\n const newControllerState = this.controllerState.rotate({pos: endPos});\n this.updateViewport(\n newControllerState,\n {\n ...this._getTransitionProps(),\n transitionDuration: inertia,\n transitionEasing: INERTIA_EASING\n },\n {\n isDragging: false,\n isRotating: true\n }\n );\n this.blockEvents(inertia);\n } else {\n const newControllerState = this.controllerState.rotateEnd();\n this.updateViewport(newControllerState, null, {\n isDragging: false,\n isRotating: false\n });\n }\n return true;\n }\n\n // Default handler for the `pinchstart` event.\n protected _onPinchStart(event: MjolnirGestureEvent): boolean {\n const pos = this.getCenter(event);\n if (!this.isPointInBounds(pos, event)) {\n return false;\n }\n\n const newControllerState = this.controllerState.zoomStart({pos}).rotateStart({pos});\n // hack - hammer's `rotation` field doesn't seem to produce the correct angle\n pinchEventWorkaround._startPinchRotation = event.rotation;\n pinchEventWorkaround._lastPinchEvent = event;\n this.updateViewport(newControllerState, NO_TRANSITION_PROPS, {isDragging: true});\n return true;\n }\n\n // Default handler for the `pinchmove` and `pinchend` events.\n protected _onPinch(event: MjolnirGestureEvent): boolean {\n if (!this.touchZoom && !this.touchRotate) {\n return false;\n }\n if (!this.isDragging()) {\n return false;\n }\n\n let newControllerState = this.controllerState;\n if (this.touchZoom) {\n const {scale} = event;\n const pos = this.getCenter(event);\n newControllerState = newControllerState.zoom({pos, scale});\n }\n if (this.touchRotate) {\n const {rotation} = event;\n newControllerState = newControllerState.rotate({\n deltaAngleX: pinchEventWorkaround._startPinchRotation - rotation\n });\n }\n\n this.updateViewport(newControllerState, NO_TRANSITION_PROPS, {\n isDragging: true,\n isPanning: this.touchZoom,\n isZooming: this.touchZoom,\n isRotating: this.touchRotate\n });\n pinchEventWorkaround._lastPinchEvent = event;\n return true;\n }\n\n protected _onPinchEnd(event: MjolnirGestureEvent): boolean {\n if (!this.isDragging()) {\n return false;\n }\n const {inertia} = this;\n const {_lastPinchEvent} = pinchEventWorkaround;\n if (this.touchZoom && inertia && _lastPinchEvent && event.scale !== _lastPinchEvent.scale) {\n const pos = this.getCenter(event);\n let newControllerState = this.controllerState.rotateEnd();\n const z = Math.log2(event.scale);\n const velocityZ =\n (z - Math.log2(_lastPinchEvent.scale)) / (event.deltaTime - _lastPinchEvent.deltaTime);\n const endScale = Math.pow(2, z + (velocityZ * inertia) / 2);\n newControllerState = newControllerState.zoom({pos, scale: endScale}).zoomEnd();\n\n this.updateViewport(\n newControllerState,\n {\n ...this._getTransitionProps({around: pos}),\n transitionDuration: inertia,\n transitionEasing: INERTIA_EASING\n },\n {\n isDragging: false,\n isPanning: this.touchZoom,\n isZooming: this.touchZoom,\n isRotating: false\n }\n );\n this.blockEvents(inertia);\n } else {\n const newControllerState = this.controllerState.zoomEnd().rotateEnd();\n this.updateViewport(newControllerState, null, {\n isDragging: false,\n isPanning: false,\n isZooming: false,\n isRotating: false\n });\n }\n pinchEventWorkaround._startPinchRotation = null;\n pinchEventWorkaround._lastPinchEvent = null;\n return true;\n }\n\n // Default handler for the `dblclick` event.\n protected _onDoubleClick(event: MjolnirGestureEvent): boolean {\n if (!this.doubleClickZoom) {\n return false;\n }\n const pos = this.getCenter(event);\n if (!this.isPointInBounds(pos, event)) {\n return false;\n }\n\n const isZoomOut = this.isFunctionKeyPressed(event);\n\n const newControllerState = this.controllerState.zoom({pos, scale: isZoomOut ? 0.5 : 2});\n this.updateViewport(newControllerState, this._getTransitionProps({around: pos}), {\n isZooming: true,\n isPanning: true\n });\n this.blockEvents(100);\n return true;\n }\n\n // Default handler for the `keydown` event\n protected _onKeyDown(event: MjolnirKeyEvent): boolean {\n if (!this.keyboard) {\n return false;\n }\n const funcKey = this.isFunctionKeyPressed(event);\n // @ts-ignore\n const {zoomSpeed, moveSpeed, rotateSpeedX, rotateSpeedY} = this.keyboard === true ? {} : this.keyboard;\n const {controllerState} = this;\n let newControllerState;\n const interactionState: InteractionState = {};\n\n switch (event.srcEvent.code) {\n case 'Minus':\n newControllerState = funcKey\n ? controllerState.zoomOut(zoomSpeed).zoomOut(zoomSpeed)\n : controllerState.zoomOut(zoomSpeed);\n interactionState.isZooming = true;\n break;\n case 'Equal':\n newControllerState = funcKey\n ? controllerState.zoomIn(zoomSpeed).zoomIn(zoomSpeed)\n : controllerState.zoomIn(zoomSpeed);\n interactionState.isZooming = true;\n break;\n case 'ArrowLeft':\n if (funcKey) {\n newControllerState = controllerState.rotateLeft(rotateSpeedX);\n interactionState.isRotating = true;\n } else {\n newControllerState = controllerState.moveLeft(moveSpeed);\n interactionState.isPanning = true;\n }\n break;\n case 'ArrowRight':\n if (funcKey) {\n newControllerState = controllerState.rotateRight(rotateSpeedX);\n interactionState.isRotating = true;\n } else {\n newControllerState = controllerState.moveRight(moveSpeed);\n interactionState.isPanning = true;\n }\n break;\n case 'ArrowUp':\n if (funcKey) {\n newControllerState = controllerState.rotateUp(rotateSpeedY);\n interactionState.isRotating = true;\n } else {\n newControllerState = controllerState.moveUp(moveSpeed);\n interactionState.isPanning = true;\n }\n break;\n case 'ArrowDown':\n if (funcKey) {\n newControllerState = controllerState.rotateDown(rotateSpeedY);\n interactionState.isRotating = true;\n } else {\n newControllerState = controllerState.moveDown(moveSpeed);\n interactionState.isPanning = true;\n }\n break;\n default:\n return false;\n }\n this.updateViewport(newControllerState, this._getTransitionProps(), interactionState);\n return true;\n }\n\n protected _getTransitionProps(opts?: any): TransitionProps {\n const {transition} = this;\n\n if (!transition || !transition.transitionInterpolator) {\n return NO_TRANSITION_PROPS;\n }\n\n // Enables Transitions on double-tap and key-down events.\n return opts\n ? {\n ...transition,\n transitionInterpolator: new LinearInterpolator({\n ...opts,\n ...(transition.transitionInterpolator as LinearInterpolator).opts,\n makeViewport: this.controllerState.makeViewport\n })\n }\n : transition;\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type Viewport from '../viewports/viewport';\n\nexport default abstract class ViewState<\n T,\n Props extends Record,\n State extends Record\n> implements IViewState\n{\n private _viewportProps: Required;\n private _state: State;\n\n makeViewport: (props: Record) => Viewport;\n\n constructor(\n props: Required,\n state: State,\n makeViewport: (props: Record) => Viewport\n ) {\n this.makeViewport = makeViewport;\n this._viewportProps = this.applyConstraints(props);\n this._state = state;\n }\n\n getViewportProps(): Required {\n return this._viewportProps;\n }\n\n getState(): State {\n return this._state;\n }\n\n abstract applyConstraints(props: Required): Required;\n\n abstract shortestPathFrom(viewState: T): Props;\n\n abstract panStart(params: {pos: [number, number]}): T;\n abstract pan({pos, startPos}: {pos: [number, number]; startPos?: [number, number]}): T;\n abstract panEnd(): T;\n\n abstract rotateStart(params: {pos: [number, number]; altitude?: number}): T;\n abstract rotate(params: {pos?: [number, number]; deltaAngleX?: number; deltaAngleY: number}): T;\n abstract rotateEnd(): T;\n\n abstract zoomStart({pos}: {pos: [number, number]}): T;\n abstract zoom({\n pos,\n startPos,\n scale\n }: {\n pos: [number, number];\n startPos?: [number, number];\n scale: number;\n }): T;\n abstract zoomEnd(): T;\n\n abstract zoomIn(speed?: number): T;\n abstract zoomOut(speed?: number): T;\n\n abstract moveLeft(speed?: number): T;\n abstract moveRight(speed?: number): T;\n abstract moveUp(speed?: number): T;\n abstract moveDown(speed?: number): T;\n\n abstract rotateLeft(speed?: number): T;\n abstract rotateRight(speed?: number): T;\n abstract rotateUp(speed?: number): T;\n abstract rotateDown(speed?: number): T;\n}\n\nexport interface IViewState {\n makeViewport?: (props: Record) => Viewport;\n\n getViewportProps(): Record;\n\n getState(): Record;\n\n shortestPathFrom(viewState: T): Record;\n\n panStart(params: {pos: [number, number]}): T;\n pan({pos, startPos}: {pos: [number, number]; startPos?: [number, number]}): T;\n panEnd(): T;\n\n rotateStart(params: {pos: [number, number]; altitude?: number}): T;\n rotate(params: {pos?: [number, number]; deltaAngleX?: number; deltaAngleY?: number}): T;\n rotateEnd(): T;\n\n zoomStart({pos}: {pos: [number, number]}): T;\n zoom({\n pos,\n startPos,\n scale\n }: {\n pos: [number, number];\n startPos?: [number, number];\n scale: number;\n }): T;\n zoomEnd(): T;\n\n zoomIn(speed?: number): T;\n zoomOut(speed?: number): T;\n\n moveLeft(speed?: number): T;\n moveRight(speed?: number): T;\n moveUp(speed?: number): T;\n moveDown(speed?: number): T;\n\n rotateLeft(speed?: number): T;\n rotateRight(speed?: number): T;\n rotateUp(speed?: number): T;\n rotateDown(speed?: number): T;\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {clamp} from '@math.gl/core';\nimport Controller, {ControllerProps, InteractionState} from './controller';\nimport ViewState from './view-state';\nimport {worldToLngLat, lngLatToWorld as _lngLatToWorld} from '@math.gl/web-mercator';\nimport assert from '../utils/assert';\nimport {mod} from '../utils/math-utils';\n\nimport LinearInterpolator from '../transitions/linear-interpolator';\nimport type Viewport from '../viewports/viewport';\n\nconst PITCH_MOUSE_THRESHOLD = 5;\nconst PITCH_ACCEL = 1.2;\nconst WEB_MERCATOR_TILE_SIZE = 512;\nconst WEB_MERCATOR_MAX_BOUNDS = [\n [-Infinity, -90],\n [Infinity, 90]\n] satisfies ControllerProps['maxBounds'];\n\n/** The web mercator utility `lngLatToWorld` throws if invalid coordinates are provided.\n * This wrapper clamps user input to calculate common positions safely. */\nfunction lngLatToWorld([lng, lat]: number[]): number[] {\n if (Math.abs(lat) > 90) {\n lat = Math.sign(lat) * 90;\n }\n if (Number.isFinite(lng)) {\n const [x, y] = _lngLatToWorld([lng, lat]);\n return [x, clamp(y, 0, WEB_MERCATOR_TILE_SIZE)];\n }\n const [, y] = _lngLatToWorld([0, lat]);\n return [lng, clamp(y, 0, WEB_MERCATOR_TILE_SIZE)];\n}\n\nexport type MapStateProps = {\n /** Mapbox viewport properties */\n /** The width of the viewport */\n width: number;\n /** The height of the viewport */\n height: number;\n /** The latitude at the center of the viewport */\n latitude: number;\n /** The longitude at the center of the viewport */\n longitude: number;\n /** The tile zoom level of the map. */\n zoom: number;\n /** The bearing of the viewport in degrees */\n bearing?: number;\n /** The pitch of the viewport in degrees */\n pitch?: number;\n /**\n * Specify the altitude of the viewport camera\n * Unit: map heights, default 1.5\n * Non-public API, see https://github.com/mapbox/mapbox-gl-js/issues/1137\n */\n altitude?: number;\n /** Viewport position */\n position?: [number, number, number];\n\n /** Viewport constraints */\n maxZoom?: number;\n minZoom?: number;\n maxPitch?: number;\n minPitch?: number;\n\n /** Normalize viewport props to fit map height into viewport. Default `true` */\n normalize?: boolean;\n\n maxBounds?: ControllerProps['maxBounds'];\n};\n\nexport type MapStateInternal = {\n /** Interaction states, required to calculate change during transform */\n /* The point on map being grabbed when the operation first started */\n startPanLngLat?: [number, number];\n /* Center of the zoom when the operation first started */\n startZoomLngLat?: [number, number];\n /* Pointer position when rotation started */\n startRotatePos?: [number, number];\n /* The lng/lat/altitude point at the rotation pivot (where rotation started) */\n startRotateLngLat?: [number, number, number];\n /** Bearing when current perspective rotate operation started */\n startBearing?: number;\n /** Pitch when current perspective rotate operation started */\n startPitch?: number;\n /** Zoom when current zoom operation started */\n startZoom?: number;\n};\n\n/* Utils */\n\nexport class MapState extends ViewState {\n /* get optional altitude for rotation pivot\n * - undefined: rotate around viewport center (no pivot point)\n * - 0: rotate around pointer position at ground level\n * - other value: rotate around pointer position at specified altitude\n */\n getAltitude?: (pos: [number, number]) => number | undefined;\n\n constructor(\n options: MapStateProps &\n MapStateInternal & {\n makeViewport: (props: Record) => Viewport;\n getAltitude?: (pos: [number, number]) => number | undefined;\n }\n ) {\n const {\n /** Mapbox viewport properties */\n /** The width of the viewport */\n width,\n /** The height of the viewport */\n height,\n /** The latitude at the center of the viewport */\n latitude,\n /** The longitude at the center of the viewport */\n longitude,\n /** The tile zoom level of the map. */\n zoom,\n /** The bearing of the viewport in degrees */\n bearing = 0,\n /** The pitch of the viewport in degrees */\n pitch = 0,\n /**\n * Specify the altitude of the viewport camera\n * Unit: map heights, default 1.5\n * Non-public API, see https://github.com/mapbox/mapbox-gl-js/issues/1137\n */\n altitude = 1.5,\n /** Viewport position */\n position = [0, 0, 0],\n\n /** Viewport constraints */\n maxZoom = 20,\n minZoom = 0,\n maxPitch = 60,\n minPitch = 0,\n\n /** Interaction states, required to calculate change during transform */\n /* The point on map being grabbed when the operation first started */\n startPanLngLat,\n /* Center of the zoom when the operation first started */\n startZoomLngLat,\n /* Pointer position when rotation started */\n startRotatePos,\n /* The lng/lat point at the rotation pivot (where rotation started) */\n startRotateLngLat,\n /** Bearing when current perspective rotate operation started */\n startBearing,\n /** Pitch when current perspective rotate operation started */\n startPitch,\n /** Zoom when current zoom operation started */\n startZoom,\n\n /** Normalize viewport props to fit map height into viewport */\n normalize = true\n } = options;\n\n assert(Number.isFinite(longitude)); // `longitude` must be supplied\n assert(Number.isFinite(latitude)); // `latitude` must be supplied\n assert(Number.isFinite(zoom)); // `zoom` must be supplied\n\n const maxBounds = options.maxBounds || (normalize ? WEB_MERCATOR_MAX_BOUNDS : null);\n\n super(\n {\n width,\n height,\n latitude,\n longitude,\n zoom,\n bearing,\n pitch,\n altitude,\n maxZoom,\n minZoom,\n maxPitch,\n minPitch,\n normalize,\n position,\n maxBounds\n },\n {\n startPanLngLat,\n startZoomLngLat,\n startRotatePos,\n startRotateLngLat,\n startBearing,\n startPitch,\n startZoom\n },\n options.makeViewport\n );\n\n this.getAltitude = options.getAltitude;\n }\n\n /**\n * Start panning\n * @param {[Number, Number]} pos - position on screen where the pointer grabs\n */\n panStart({pos}: {pos: [number, number]}): MapState {\n return this._getUpdatedState({\n startPanLngLat: this._unproject(pos)\n });\n }\n\n /**\n * Pan\n * @param {[Number, Number]} pos - position on screen where the pointer is\n * @param {[Number, Number], optional} startPos - where the pointer grabbed at\n * the start of the operation. Must be supplied of `panStart()` was not called\n */\n pan({pos, startPos}: {pos: [number, number]; startPos?: [number, number]}): MapState {\n const startPanLngLat = this.getState().startPanLngLat || this._unproject(startPos);\n\n if (!startPanLngLat) {\n return this;\n }\n\n const viewport = this.makeViewport(this.getViewportProps());\n const newProps = viewport.panByPosition(startPanLngLat, pos);\n\n return this._getUpdatedState(newProps);\n }\n\n /**\n * End panning\n * Must call if `panStart()` was called\n */\n panEnd(): MapState {\n return this._getUpdatedState({\n startPanLngLat: null\n });\n }\n\n /**\n * Start rotating\n * @param {[Number, Number]} pos - position on screen where the center is\n */\n rotateStart({pos}: {pos: [number, number]}): MapState {\n const altitude = this.getAltitude?.(pos);\n\n return this._getUpdatedState({\n startRotatePos: pos,\n startRotateLngLat: altitude !== undefined ? this._unproject3D(pos, altitude) : undefined,\n startBearing: this.getViewportProps().bearing,\n startPitch: this.getViewportProps().pitch\n });\n }\n\n /**\n * Rotate\n * @param {[Number, Number]} pos - position on screen where the center is\n */\n rotate({\n pos,\n deltaAngleX = 0,\n deltaAngleY = 0\n }: {\n pos?: [number, number];\n deltaAngleX?: number;\n deltaAngleY?: number;\n }): MapState {\n const {startRotatePos, startRotateLngLat, startBearing, startPitch} = this.getState();\n\n if (!startRotatePos || startBearing === undefined || startPitch === undefined) {\n return this;\n }\n let newRotation;\n if (pos) {\n newRotation = this._getNewRotation(pos, startRotatePos, startPitch, startBearing);\n } else {\n newRotation = {\n bearing: startBearing + deltaAngleX,\n pitch: startPitch + deltaAngleY\n };\n }\n\n // If we have a pivot point, adjust the camera position to keep the pivot point fixed\n if (startRotateLngLat) {\n const rotatedViewport = this.makeViewport({\n ...this.getViewportProps(),\n ...newRotation\n });\n // Use panByPosition3D if available (WebMercatorViewport), otherwise fall back to panByPosition\n const panMethod = 'panByPosition3D' in rotatedViewport ? 'panByPosition3D' : 'panByPosition';\n return this._getUpdatedState({\n ...newRotation,\n ...rotatedViewport[panMethod](startRotateLngLat, startRotatePos)\n });\n }\n\n return this._getUpdatedState(newRotation);\n }\n\n /**\n * End rotating\n * Must call if `rotateStart()` was called\n */\n rotateEnd(): MapState {\n return this._getUpdatedState({\n startRotatePos: null,\n startRotateLngLat: null,\n startBearing: null,\n startPitch: null\n });\n }\n\n /**\n * Start zooming\n * @param {[Number, Number]} pos - position on screen where the center is\n */\n zoomStart({pos}: {pos: [number, number]}): MapState {\n return this._getUpdatedState({\n startZoomLngLat: this._unproject(pos),\n startZoom: this.getViewportProps().zoom\n });\n }\n\n /**\n * Zoom\n * @param {[Number, Number]} pos - position on screen where the current center is\n * @param {[Number, Number]} startPos - the center position at\n * the start of the operation. Must be supplied of `zoomStart()` was not called\n * @param {Number} scale - a number between [0, 1] specifying the accumulated\n * relative scale.\n */\n zoom({\n pos,\n startPos,\n scale\n }: {\n pos: [number, number];\n startPos?: [number, number];\n scale: number;\n }): MapState {\n // Make sure we zoom around the current mouse position rather than map center\n let {startZoom, startZoomLngLat} = this.getState();\n\n if (!startZoomLngLat) {\n // We have two modes of zoom:\n // scroll zoom that are discrete events (transform from the current zoom level),\n // and pinch zoom that are continuous events (transform from the zoom level when\n // pinch started).\n // If startZoom state is defined, then use the startZoom state;\n // otherwise assume discrete zooming\n startZoom = this.getViewportProps().zoom;\n startZoomLngLat = this._unproject(startPos) || this._unproject(pos);\n }\n if (!startZoomLngLat) {\n return this;\n }\n\n const zoom = this._constrainZoom((startZoom as number) + Math.log2(scale));\n const zoomedViewport = this.makeViewport({...this.getViewportProps(), zoom});\n\n return this._getUpdatedState({\n zoom,\n ...zoomedViewport.panByPosition(startZoomLngLat, pos)\n });\n }\n\n /**\n * End zooming\n * Must call if `zoomStart()` was called\n */\n zoomEnd(): MapState {\n return this._getUpdatedState({\n startZoomLngLat: null,\n startZoom: null\n });\n }\n\n zoomIn(speed: number = 2): MapState {\n return this._zoomFromCenter(speed);\n }\n\n zoomOut(speed: number = 2): MapState {\n return this._zoomFromCenter(1 / speed);\n }\n\n moveLeft(speed: number = 100): MapState {\n return this._panFromCenter([speed, 0]);\n }\n\n moveRight(speed: number = 100): MapState {\n return this._panFromCenter([-speed, 0]);\n }\n\n moveUp(speed: number = 100): MapState {\n return this._panFromCenter([0, speed]);\n }\n\n moveDown(speed: number = 100): MapState {\n return this._panFromCenter([0, -speed]);\n }\n\n rotateLeft(speed: number = 15): MapState {\n return this._getUpdatedState({\n bearing: this.getViewportProps().bearing - speed\n });\n }\n\n rotateRight(speed: number = 15): MapState {\n return this._getUpdatedState({\n bearing: this.getViewportProps().bearing + speed\n });\n }\n\n rotateUp(speed: number = 10): MapState {\n return this._getUpdatedState({\n pitch: this.getViewportProps().pitch + speed\n });\n }\n\n rotateDown(speed: number = 10): MapState {\n return this._getUpdatedState({\n pitch: this.getViewportProps().pitch - speed\n });\n }\n\n shortestPathFrom(viewState: MapState): MapStateProps {\n // const endViewStateProps = new this.ControllerState(endProps).shortestPathFrom(startViewstate);\n const fromProps = viewState.getViewportProps();\n const props = {...this.getViewportProps()};\n const {bearing, longitude} = props;\n\n if (Math.abs(bearing - fromProps.bearing) > 180) {\n props.bearing = bearing < 0 ? bearing + 360 : bearing - 360;\n }\n if (Math.abs(longitude - fromProps.longitude) > 180) {\n props.longitude = longitude < 0 ? longitude + 360 : longitude - 360;\n }\n return props;\n }\n\n // Apply any constraints (mathematical or defined by _viewportProps) to map state\n applyConstraints(props: Required): Required {\n // Ensure pitch is within specified range\n const {maxPitch, minPitch, pitch, longitude, bearing, normalize, maxBounds} = props;\n\n if (normalize) {\n if (longitude < -180 || longitude > 180) {\n props.longitude = mod(longitude + 180, 360) - 180;\n }\n if (bearing < -180 || bearing > 180) {\n props.bearing = mod(bearing + 180, 360) - 180;\n }\n }\n props.pitch = clamp(pitch, minPitch, maxPitch);\n\n props.zoom = this._constrainZoom(props.zoom, props);\n\n if (maxBounds) {\n const bl = lngLatToWorld(maxBounds[0]);\n const tr = lngLatToWorld(maxBounds[1]);\n // calculate center and zoom ranges at pitch=0 and bearing=0\n // to maintain visual stability when rotating\n const scale = 2 ** props.zoom;\n const halfWidth = props.width / 2 / scale;\n const halfHeight = props.height / 2 / scale;\n const [minLng, minLat] = worldToLngLat([bl[0] + halfWidth, bl[1] + halfHeight]);\n const [maxLng, maxLat] = worldToLngLat([tr[0] - halfWidth, tr[1] - halfHeight]);\n props.longitude = clamp(props.longitude, minLng, maxLng);\n props.latitude = clamp(props.latitude, minLat, maxLat);\n }\n\n return props;\n }\n\n /* Private methods */\n\n _constrainZoom(zoom: number, props?: Required): number {\n props ||= this.getViewportProps();\n const {maxZoom, maxBounds} = props;\n\n const shouldApplyMaxBounds = maxBounds !== null && props.width > 0 && props.height > 0;\n let {minZoom} = props;\n\n if (shouldApplyMaxBounds) {\n const bl = lngLatToWorld(maxBounds[0]);\n const tr = lngLatToWorld(maxBounds[1]);\n const w = tr[0] - bl[0];\n const h = tr[1] - bl[1];\n // ignore bound size of 0 or Infinity\n if (Number.isFinite(w) && w > 0) {\n minZoom = Math.max(minZoom, Math.log2(props.width / w));\n }\n if (Number.isFinite(h) && h > 0) {\n minZoom = Math.max(minZoom, Math.log2(props.height / h));\n }\n if (minZoom > maxZoom) minZoom = maxZoom;\n }\n return clamp(zoom, minZoom, maxZoom);\n }\n\n _zoomFromCenter(scale) {\n const {width, height} = this.getViewportProps();\n return this.zoom({\n pos: [width / 2, height / 2],\n scale\n });\n }\n\n _panFromCenter(offset) {\n const {width, height} = this.getViewportProps();\n return this.pan({\n startPos: [width / 2, height / 2],\n pos: [width / 2 + offset[0], height / 2 + offset[1]]\n });\n }\n\n _getUpdatedState(newProps): MapState {\n // @ts-ignore\n return new this.constructor({\n makeViewport: this.makeViewport,\n ...this.getViewportProps(),\n ...this.getState(),\n ...newProps\n });\n }\n\n _unproject(pos?: [number, number]): [number, number] | undefined {\n const viewport = this.makeViewport(this.getViewportProps());\n // @ts-ignore\n return pos && viewport.unproject(pos);\n }\n\n _unproject3D(pos: [number, number], altitude: number): [number, number, number] {\n const viewport = this.makeViewport(this.getViewportProps());\n return viewport.unproject(pos, {targetZ: altitude}) as [number, number, number];\n }\n\n _getNewRotation(\n pos: [number, number],\n startPos: [number, number],\n startPitch: number,\n startBearing: number\n ): {\n pitch: number;\n bearing: number;\n } {\n const deltaX = pos[0] - startPos[0];\n const deltaY = pos[1] - startPos[1];\n const centerY = pos[1];\n const startY = startPos[1];\n const {width, height} = this.getViewportProps();\n\n const deltaScaleX = deltaX / width;\n let deltaScaleY = 0;\n\n if (deltaY > 0) {\n if (Math.abs(height - startY) > PITCH_MOUSE_THRESHOLD) {\n // Move from 0 to -1 as we drag upwards\n deltaScaleY = (deltaY / (startY - height)) * PITCH_ACCEL;\n }\n } else if (deltaY < 0) {\n if (startY > PITCH_MOUSE_THRESHOLD) {\n // Move from 0 to 1 as we drag upwards\n deltaScaleY = 1 - centerY / startY;\n }\n }\n // clamp deltaScaleY to [-1, 1] so that rotation is constrained between minPitch and maxPitch.\n // deltaScaleX does not need to be clamped as bearing does not have constraints.\n deltaScaleY = clamp(deltaScaleY, -1, 1);\n\n const {minPitch, maxPitch} = this.getViewportProps();\n\n const bearing = startBearing + 180 * deltaScaleX;\n let pitch = startPitch;\n if (deltaScaleY > 0) {\n // Gradually increase pitch\n pitch = startPitch + deltaScaleY * (maxPitch - startPitch);\n } else if (deltaScaleY < 0) {\n // Gradually decrease pitch\n pitch = startPitch - deltaScaleY * (minPitch - startPitch);\n }\n\n return {\n pitch,\n bearing\n };\n }\n}\n\nexport default class MapController extends Controller {\n ControllerState = MapState;\n\n transition = {\n transitionDuration: 300,\n transitionInterpolator: new LinearInterpolator({\n transitionProps: {\n compare: ['longitude', 'latitude', 'zoom', 'bearing', 'pitch', 'position'],\n required: ['longitude', 'latitude', 'zoom']\n }\n })\n };\n\n dragMode: 'pan' | 'rotate' = 'pan';\n\n /**\n * Rotation pivot behavior:\n * - 'center': Rotate around viewport center (default)\n * - '2d': Rotate around pointer position at ground level (z=0)\n * - '3d': Rotate around 3D picked point (requires pickPosition callback)\n */\n protected rotationPivot: 'center' | '2d' | '3d' = 'center';\n\n setProps(\n props: ControllerProps &\n MapStateProps & {\n rotationPivot?: 'center' | '2d' | '3d';\n getAltitude?: (pos: [number, number]) => number | undefined;\n }\n ) {\n if ('rotationPivot' in props) {\n this.rotationPivot = props.rotationPivot || 'center';\n }\n // this will be passed to MapState constructor\n props.getAltitude = this._getAltitude;\n props.position = props.position || [0, 0, 0];\n props.maxBounds =\n props.maxBounds || (props.normalize === false ? null : WEB_MERCATOR_MAX_BOUNDS);\n\n super.setProps(props);\n }\n\n protected updateViewport(\n newControllerState: MapState,\n extraProps: Record | null = null,\n interactionState: InteractionState = {}\n ): void {\n // Inject rotation pivot position during rotation for visual feedback\n const state = newControllerState.getState();\n if (interactionState.isDragging && state.startRotateLngLat) {\n interactionState = {\n ...interactionState,\n rotationPivotPosition: state.startRotateLngLat\n };\n } else if (interactionState.isDragging === false) {\n // Clear pivot when drag ends\n interactionState = {...interactionState, rotationPivotPosition: undefined};\n }\n\n super.updateViewport(newControllerState, extraProps, interactionState);\n }\n\n /** Add altitude to rotateStart params based on rotationPivot mode */\n protected _getAltitude = (pos: [number, number]): number | undefined => {\n if (this.rotationPivot === '2d') {\n return 0;\n } else if (this.rotationPivot === '3d') {\n if (this.pickPosition) {\n const {x, y} = this.props;\n const pickResult = this.pickPosition(x + pos[0], y + pos[1]);\n if (pickResult && pickResult.coordinate && pickResult.coordinate.length >= 3) {\n return pickResult.coordinate[2];\n }\n }\n }\n return undefined;\n };\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport View, {CommonViewState, CommonViewProps} from './view';\nimport WebMercatorViewport from '../viewports/web-mercator-viewport';\nimport MapController from '../controllers/map-controller';\n\nimport type {NumericArray} from '../types/types';\n\nexport type MapViewState = {\n /** Longitude of the map center */\n longitude: number;\n /** Latitude of the map center */\n latitude: number;\n /** Zoom level */\n zoom: number;\n /** Pitch (tilt) of the map, in degrees. `0` looks top down */\n pitch?: number;\n /** Bearing (rotation) of the map, in degrees. `0` is north up */\n bearing?: number;\n /** Min zoom, default `0` */\n minZoom?: number;\n /** Max zoom, default `20` */\n maxZoom?: number;\n /** Min pitch, default `0` */\n minPitch?: number;\n /** Max pitch, default `60` */\n maxPitch?: number;\n /** Viewport center offsets from lng, lat in meters */\n position?: number[];\n /** The near plane position */\n nearZ?: number;\n /** The far plane position */\n farZ?: number;\n} & CommonViewState;\n\nexport type MapViewProps = {\n /** Whether to render multiple copies of the map at low zoom levels. Default `false`. */\n repeat?: boolean;\n /** Scaler for the near plane, 1 unit equals to the height of the viewport. Default to `0.1`. Overwrites the `near` parameter. */\n nearZMultiplier?: number;\n /** Scaler for the far plane, 1 unit equals to the distance from the camera to the top edge of the screen. Default to `1.01`. Overwrites the `far` parameter. */\n farZMultiplier?: number;\n /** Custom projection matrix */\n projectionMatrix?: NumericArray;\n /** Field of view covered by the camera, in the perspective case. In degrees. If not supplied, will be calculated from `altitude`. */\n fovy?: number;\n /** Distance of the camera relative to viewport height. Default `1.5`. */\n altitude?: number;\n /** Whether to create an orthographic or perspective projection matrix. Default is `false` (perspective projection). */\n orthographic?: boolean;\n} & CommonViewProps;\n\nexport default class MapView extends View {\n static displayName = 'MapView';\n\n constructor(props: MapViewProps = {}) {\n super(props);\n }\n\n getViewportType() {\n return WebMercatorViewport;\n }\n\n get ControllerType() {\n return MapController;\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {deepEqual} from '../utils/deep-equal';\nimport LightingEffect from '../effects/lighting/lighting-effect';\nimport type {Effect, EffectContext} from './effect';\n\nconst DEFAULT_LIGHTING_EFFECT = new LightingEffect();\n\n/** Sort two effects. Returns 0 if equal, negative if e1 < e2, positive if e1 > e2 */\nfunction compareEffects(e1: Effect, e2: Effect): number {\n const o1 = e1.order ?? Infinity;\n const o2 = e2.order ?? Infinity;\n return o1 - o2;\n}\n\nexport default class EffectManager {\n effects: Effect[];\n private _resolvedEffects: Effect[] = [];\n /** Effect instances and order preference pairs, sorted by order */\n private _defaultEffects: Effect[] = [];\n private _needsRedraw: false | string;\n private _context: EffectContext;\n\n constructor(context: EffectContext) {\n this.effects = [];\n this._context = context;\n this._needsRedraw = 'Initial render';\n this._setEffects([]);\n }\n\n /**\n * Register a new default effect, i.e. an effect presents regardless of user supplied props.effects\n */\n addDefaultEffect(effect: Effect) {\n const defaultEffects = this._defaultEffects;\n if (!defaultEffects.find(e => e.id === effect.id)) {\n const index = defaultEffects.findIndex(e => compareEffects(e, effect) > 0);\n if (index < 0) {\n defaultEffects.push(effect);\n } else {\n defaultEffects.splice(index, 0, effect);\n }\n effect.setup(this._context);\n this._setEffects(this.effects);\n }\n }\n\n setProps(props) {\n if ('effects' in props) {\n // Compare effects against each other shallowly\n if (!deepEqual(props.effects, this.effects, 1)) {\n this._setEffects(props.effects);\n }\n }\n }\n\n needsRedraw(opts = {clearRedrawFlags: false}): false | string {\n const redraw = this._needsRedraw;\n if (opts.clearRedrawFlags) {\n this._needsRedraw = false;\n }\n return redraw;\n }\n\n getEffects() {\n return this._resolvedEffects;\n }\n\n private _setEffects(effects: Effect[]) {\n const oldEffectsMap: Record = {};\n for (const effect of this.effects) {\n oldEffectsMap[effect.id] = effect;\n }\n\n const nextEffects: Effect[] = [];\n for (const effect of effects) {\n const oldEffect = oldEffectsMap[effect.id];\n let effectToAdd = effect;\n if (oldEffect && oldEffect !== effect) {\n if (oldEffect.setProps) {\n oldEffect.setProps(effect.props);\n effectToAdd = oldEffect;\n } else {\n oldEffect.cleanup(this._context);\n }\n } else if (!oldEffect) {\n effect.setup(this._context);\n }\n nextEffects.push(effectToAdd);\n delete oldEffectsMap[effect.id];\n }\n for (const removedEffectId in oldEffectsMap) {\n oldEffectsMap[removedEffectId].cleanup(this._context);\n }\n this.effects = nextEffects;\n\n this._resolvedEffects = nextEffects.concat(this._defaultEffects);\n // Special case for lighting: only add default instance if no LightingEffect is specified\n if (!effects.some(effect => effect instanceof LightingEffect)) {\n this._resolvedEffects.push(DEFAULT_LIGHTING_EFFECT);\n }\n this._needsRedraw = 'effects changed';\n }\n\n finalize() {\n for (const effect of this._resolvedEffects) {\n effect.cleanup(this._context);\n }\n\n this.effects.length = 0;\n this._resolvedEffects.length = 0;\n this._defaultEffects.length = 0;\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport LayersPass from './layers-pass';\nimport type {LayersPassRenderOptions, RenderStats} from './layers-pass';\n\nexport default class DrawLayersPass extends LayersPass {\n shouldDrawLayer(layer) {\n const {operation} = layer.props;\n return operation.includes('draw') || operation.includes('terrain');\n }\n\n render(options: LayersPassRenderOptions): RenderStats[] {\n return this._render(options);\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '@luma.gl/core';\nimport {Framebuffer} from '@luma.gl/core';\nimport debug from '../debug/index';\nimport DrawLayersPass from '../passes/draw-layers-pass';\nimport PickLayersPass from '../passes/pick-layers-pass';\nimport type {RenderStats} from '../passes/layers-pass';\nimport type {Stats} from '@probe.gl/stats';\nimport type Layer from './layer';\nimport type Viewport from '../viewports/viewport';\nimport type View from '../views/view';\nimport type {Effect, PostRenderOptions} from './effect';\nimport type {LayersPassRenderOptions, FilterContext} from '../passes/layers-pass';\n\nconst TRACE_RENDER_LAYERS = 'deckRenderer.renderLayers';\n\ntype LayerFilter = ((context: FilterContext) => boolean) | null;\n\nexport default class DeckRenderer {\n device: Device;\n layerFilter: LayerFilter;\n drawPickingColors: boolean;\n drawLayersPass: DrawLayersPass;\n pickLayersPass: PickLayersPass;\n stats?: Stats;\n\n private renderCount: number;\n private _needsRedraw: string | false;\n private renderBuffers: Framebuffer[];\n private lastPostProcessEffect: string | null;\n\n constructor(device: Device, opts: {stats?: Stats} = {}) {\n this.device = device;\n this.stats = opts.stats;\n this.layerFilter = null;\n this.drawPickingColors = false;\n this.drawLayersPass = new DrawLayersPass(device);\n this.pickLayersPass = new PickLayersPass(device);\n this.renderCount = 0;\n this._needsRedraw = 'Initial render';\n this.renderBuffers = [];\n this.lastPostProcessEffect = null;\n }\n\n setProps(props: {layerFilter: LayerFilter; drawPickingColors: boolean}) {\n if (this.layerFilter !== props.layerFilter) {\n this.layerFilter = props.layerFilter;\n this._needsRedraw = 'layerFilter changed';\n }\n\n if (this.drawPickingColors !== props.drawPickingColors) {\n this.drawPickingColors = props.drawPickingColors;\n this._needsRedraw = 'drawPickingColors changed';\n }\n }\n\n renderLayers(opts: {\n pass: string;\n layers: Layer[];\n viewports: Viewport[];\n views: {[viewId: string]: View};\n onViewportActive: (viewport: Viewport) => void;\n effects: Effect[];\n target?: Framebuffer | null;\n layerFilter?: LayerFilter;\n clearStack?: boolean;\n clearCanvas?: boolean;\n }) {\n if (!opts.viewports.length) {\n return;\n }\n\n const layerPass = this.drawPickingColors ? this.pickLayersPass : this.drawLayersPass;\n\n const renderOpts: LayersPassRenderOptions = {\n layerFilter: this.layerFilter,\n isPicking: this.drawPickingColors,\n ...opts\n };\n\n if (renderOpts.effects) {\n this._preRender(renderOpts.effects, renderOpts);\n }\n\n const outputBuffer = this.lastPostProcessEffect ? this.renderBuffers[0] : renderOpts.target;\n\n if (this.lastPostProcessEffect) {\n renderOpts.clearColor = [0, 0, 0, 0];\n renderOpts.clearCanvas = true;\n }\n const renderResult = layerPass.render({...renderOpts, target: outputBuffer});\n const renderStats = 'stats' in renderResult ? renderResult.stats : renderResult;\n\n if (renderOpts.effects) {\n if (this.lastPostProcessEffect) {\n // Interleaved basemap rendering requires clearCanvas to be false\n renderOpts.clearCanvas = opts.clearCanvas === undefined ? true : opts.clearCanvas;\n }\n\n this._postRender(renderOpts.effects, renderOpts);\n }\n\n this.renderCount++;\n\n debug(TRACE_RENDER_LAYERS, this, renderStats, opts);\n this._updateStats(renderStats);\n }\n\n needsRedraw(opts: {clearRedrawFlags: boolean} = {clearRedrawFlags: false}): string | false {\n const redraw = this._needsRedraw;\n if (opts.clearRedrawFlags) {\n this._needsRedraw = false;\n }\n return redraw;\n }\n\n finalize() {\n const {renderBuffers} = this;\n for (const buffer of renderBuffers) {\n buffer.delete();\n }\n renderBuffers.length = 0;\n }\n\n private _updateStats(source: RenderStats[]) {\n if (!this.stats) return;\n let layersCount = 0;\n for (const {visibleCount} of source) {\n layersCount += visibleCount;\n }\n this.stats.get('Layers rendered').addCount(layersCount);\n }\n\n private _preRender(effects: Effect[], opts: LayersPassRenderOptions) {\n this.lastPostProcessEffect = null;\n opts.preRenderStats = opts.preRenderStats || {};\n\n for (const effect of effects) {\n opts.preRenderStats[effect.id] = effect.preRender(opts);\n if (effect.postRender) {\n this.lastPostProcessEffect = effect.id;\n }\n }\n\n if (this.lastPostProcessEffect) {\n this._resizeRenderBuffers();\n }\n }\n\n private _resizeRenderBuffers() {\n const {renderBuffers} = this;\n const size = this.device.canvasContext!.getDrawingBufferSize();\n const [width, height] = size;\n if (renderBuffers.length === 0) {\n [0, 1].map(i => {\n const texture = this.device.createTexture({\n sampler: {minFilter: 'linear', magFilter: 'linear'},\n width,\n height\n });\n renderBuffers.push(\n this.device.createFramebuffer({\n id: `deck-renderbuffer-${i}`,\n colorAttachments: [texture]\n })\n );\n });\n }\n for (const buffer of renderBuffers) {\n buffer.resize(size);\n }\n }\n\n private _postRender(effects: Effect[], opts: LayersPassRenderOptions) {\n const {renderBuffers} = this;\n const params: PostRenderOptions = {\n ...opts,\n inputBuffer: renderBuffers[0],\n swapBuffer: renderBuffers[1]\n };\n for (const effect of effects) {\n if (effect.postRender) {\n // If not the last post processing effect, unset the target so that\n // it only renders between the swap buffers\n params.target = effect.id === this.lastPostProcessEffect ? opts.target : undefined;\n const buffer = effect.postRender(params);\n // Buffer cannot be null if target is unset\n params.inputBuffer = buffer!;\n params.swapBuffer = buffer === renderBuffers[0] ? renderBuffers[1] : renderBuffers[0];\n }\n }\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Buffer, Texture} from '@luma.gl/core';\nimport type {Device} from '@luma.gl/core';\nimport PickLayersPass, {PickingColorDecoder} from '../passes/pick-layers-pass';\nimport log from '../utils/log';\nimport {getClosestObject, getUniqueObjects, PickedPixel} from './picking/query-object';\nimport {\n processPickInfo,\n getLayerPickingInfo,\n getEmptyPickingInfo,\n PickingInfo\n} from './picking/pick-info';\nimport type {RenderStats} from '../passes/layers-pass';\nimport type {Stats} from '@probe.gl/stats';\nimport type {Framebuffer} from '@luma.gl/core';\nimport type {FilterContext, Rect} from '../passes/layers-pass';\nimport type Layer from './layer';\nimport type {Effect} from './effect';\nimport type View from '../views/view';\nimport type Viewport from '../viewports/viewport';\n\nexport type PickByPointOptions = {\n x: number;\n y: number;\n radius?: number;\n depth?: number;\n mode?: string;\n unproject3D?: boolean;\n};\n\nexport type PickByRectOptions = {\n x: number;\n y: number;\n width?: number;\n height?: number;\n mode?: string;\n maxObjects?: number | null;\n};\n\ntype PickOperationContext = {\n layers: Layer[];\n views: Record;\n viewports: Viewport[];\n onViewportActive: (viewport: Viewport) => void;\n effects: Effect[];\n};\n\n/** Manages picking in a Deck context */\nexport default class DeckPicker {\n device: Device;\n pickingFBO?: Framebuffer;\n depthFBO?: Framebuffer;\n pickLayersPass: PickLayersPass;\n layerFilter?: (context: FilterContext) => boolean;\n stats?: Stats;\n\n /** Identifiers of the previously picked object, for callback tracking and auto highlight */\n lastPickedInfo: {\n index: number;\n layerId: string | null;\n info: PickingInfo | null;\n };\n\n _pickable: boolean = true;\n\n constructor(device: Device, opts: {stats?: Stats} = {}) {\n this.device = device;\n this.stats = opts.stats;\n this.pickLayersPass = new PickLayersPass(device);\n this.lastPickedInfo = {\n index: -1,\n layerId: null,\n info: null\n };\n }\n\n setProps(props: any): void {\n if ('layerFilter' in props) {\n this.layerFilter = props.layerFilter;\n }\n\n if ('_pickable' in props) {\n this._pickable = props._pickable;\n }\n }\n\n finalize() {\n if (this.pickingFBO) {\n this.pickingFBO.destroy();\n }\n if (this.depthFBO) {\n this.depthFBO.destroy();\n }\n }\n\n /**\n * Pick the closest info at given coordinate\n * @returns Promise that resolves with picking info\n */\n pickObjectAsync(opts: PickByPointOptions & PickOperationContext): Promise<{\n result: PickingInfo[];\n emptyInfo: PickingInfo;\n }> {\n return this._pickClosestObjectAsync(opts);\n }\n\n /**\n * Picks a list of unique infos within a bounding box\n * @returns Promise that resolves to all unique infos within a bounding box\n */\n pickObjectsAsync(opts: PickByRectOptions & PickOperationContext): Promise {\n return this._pickVisibleObjectsAsync(opts);\n }\n\n /**\n * Pick the closest info at given coordinate\n * @returns picking info\n * @note WebGL only - use pickObjectAsync instead\n */\n pickObject(opts: PickByPointOptions & PickOperationContext) {\n return this._pickClosestObject(opts);\n }\n\n /**\n * Get all unique infos within a bounding box\n * @returns all unique infos within a bounding box\n * @note WebGL only - use pickObjectAsync instead\n */\n pickObjects(opts: PickByRectOptions & PickOperationContext) {\n return this._pickVisibleObjects(opts);\n }\n\n // Returns a new picking info object by assuming the last picked object is still picked\n getLastPickedObject({x, y, layers, viewports}, lastPickedInfo = this.lastPickedInfo.info) {\n const lastPickedLayerId = lastPickedInfo && lastPickedInfo.layer && lastPickedInfo.layer.id;\n const lastPickedViewportId =\n lastPickedInfo && lastPickedInfo.viewport && lastPickedInfo.viewport.id;\n const layer = lastPickedLayerId ? layers.find(l => l.id === lastPickedLayerId) : null;\n const viewport =\n (lastPickedViewportId && viewports.find(v => v.id === lastPickedViewportId)) || viewports[0];\n const coordinate = viewport && viewport.unproject([x - viewport.x, y - viewport.y]);\n\n const info = {\n x,\n y,\n viewport,\n coordinate,\n layer\n };\n\n return {...lastPickedInfo, ...info};\n }\n\n // Private\n\n /** Ensures that picking framebuffer exists and matches the canvas size */\n _resizeBuffer() {\n // Create a frame buffer if not already available\n if (!this.pickingFBO) {\n const pickingColorTexture = this.device.createTexture({\n format: 'rgba8unorm',\n width: 1,\n height: 1,\n usage: Texture.RENDER_ATTACHMENT | Texture.COPY_SRC\n });\n this.pickingFBO = this.device.createFramebuffer({\n colorAttachments: [pickingColorTexture],\n depthStencilAttachment: 'depth16unorm'\n });\n\n if (this.device.isTextureFormatRenderable('rgba32float')) {\n const depthColorTexture = this.device.createTexture({\n format: 'rgba32float',\n width: 1,\n height: 1,\n usage: Texture.RENDER_ATTACHMENT | Texture.COPY_SRC\n });\n const depthFBO = this.device.createFramebuffer({\n colorAttachments: [depthColorTexture],\n depthStencilAttachment: 'depth16unorm'\n });\n this.depthFBO = depthFBO;\n }\n }\n\n // Resize it to current canvas size (this is a noop if size hasn't changed)\n const {canvas} = this.device.getDefaultCanvasContext();\n this.pickingFBO?.resize({width: canvas.width, height: canvas.height});\n this.depthFBO?.resize({width: canvas.width, height: canvas.height});\n }\n\n /** Preliminary filtering of the layers list. Skid picking pass if no layer is pickable. */\n _getPickable(layers: Layer[]): Layer[] | null {\n if (this._pickable === false) {\n return null;\n }\n const pickableLayers = layers.filter(\n layer => this.pickLayersPass.shouldDrawLayer(layer) && !layer.isComposite\n );\n return pickableLayers.length ? pickableLayers : null;\n }\n\n /**\n * Pick the closest object at the given coordinate\n */\n // eslint-disable-next-line max-statements,complexity\n async _pickClosestObjectAsync({\n layers,\n views,\n viewports,\n x,\n y,\n radius = 0,\n depth = 1,\n mode = 'query',\n unproject3D,\n onViewportActive,\n effects\n }: PickByPointOptions & PickOperationContext): Promise<{\n result: PickingInfo[];\n emptyInfo: PickingInfo;\n }> {\n // @ts-expect-error TODO - assuming WebGL context\n const pixelRatio = this.device.canvasContext.cssToDeviceRatio();\n\n const pickableLayers = this._getPickable(layers);\n\n if (!pickableLayers || viewports.length === 0) {\n return {\n result: [],\n emptyInfo: getEmptyPickingInfo({viewports, x, y, pixelRatio})\n };\n }\n\n this._resizeBuffer();\n\n // Convert from canvas top-left to WebGL bottom-left coordinates\n // Top-left coordinates [x, y] to bottom-left coordinates [deviceX, deviceY]\n // And compensate for pixelRatio\n // @ts-expect-error TODO - assuming WebGL context\n const devicePixelRange = this.device.canvasContext.cssToDevicePixels([x, y], true);\n const devicePixel = [\n devicePixelRange.x + Math.floor(devicePixelRange.width / 2),\n devicePixelRange.y + Math.floor(devicePixelRange.height / 2)\n ];\n\n const deviceRadius = Math.round(radius * pixelRatio);\n const {width, height} = this.pickingFBO as Framebuffer;\n const deviceRect = this._getPickingRect({\n deviceX: devicePixel[0],\n deviceY: devicePixel[1],\n deviceRadius,\n deviceWidth: width,\n deviceHeight: height\n });\n\n const cullRect: Rect = {\n x: x - radius,\n y: y - radius,\n width: radius * 2 + 1,\n height: radius * 2 + 1\n };\n\n let infos: Map;\n const result: PickingInfo[] = [];\n const affectedLayers = new Set();\n\n for (let i = 0; i < depth; i++) {\n let pickInfo: PickedPixel;\n\n if (deviceRect) {\n const pickedResult = await this._drawAndSampleAsync({\n layers: pickableLayers,\n views,\n viewports,\n onViewportActive,\n deviceRect,\n cullRect,\n effects,\n pass: `picking:${mode}`\n });\n\n pickInfo = getClosestObject({\n ...pickedResult,\n deviceX: devicePixel[0],\n deviceY: devicePixel[1],\n deviceRadius,\n deviceRect\n });\n } else {\n pickInfo = {\n pickedColor: null,\n pickedObjectIndex: -1\n };\n }\n\n let z;\n const depthLayers = this._getDepthLayers(pickInfo, pickableLayers, unproject3D);\n if (depthLayers.length > 0) {\n const {pickedColors: pickedColors2} = await this._drawAndSampleAsync(\n {\n layers: depthLayers,\n views,\n viewports,\n onViewportActive,\n deviceRect: {\n x: pickInfo.pickedX ?? devicePixel[0],\n y: pickInfo.pickedY ?? devicePixel[1],\n width: 1,\n height: 1\n },\n cullRect,\n effects,\n pass: `picking:${mode}:z`\n },\n true\n );\n // picked value is in common space (pixels) from the camera target (viewport.position)\n // convert it to meters from the ground\n if (pickedColors2[3]) {\n z = pickedColors2[0];\n }\n }\n\n // Only exclude if we need to run picking again.\n // We need to run picking again if an object is detected AND\n // we have not exhausted the requested depth.\n if (pickInfo.pickedLayer && i + 1 < depth) {\n affectedLayers.add(pickInfo.pickedLayer);\n pickInfo.pickedLayer.disablePickingIndex(pickInfo.pickedObjectIndex);\n }\n\n // This logic needs to run even if no object is picked.\n infos = processPickInfo({\n pickInfo,\n lastPickedInfo: this.lastPickedInfo,\n mode,\n layers: pickableLayers,\n viewports,\n x,\n y,\n z,\n pixelRatio\n });\n\n for (const info of infos.values()) {\n if (info.layer) {\n result.push(info);\n }\n }\n\n // If no object is picked stop.\n if (!pickInfo.pickedColor) {\n break;\n }\n }\n\n // reset only affected buffers\n for (const layer of affectedLayers) {\n layer.restorePickingColors();\n }\n\n return {result, emptyInfo: infos!.get(null) as PickingInfo};\n }\n\n /**\n * Pick the closest object at the given coordinate\n * @deprecated WebGL only\n */\n // eslint-disable-next-line max-statements,complexity\n _pickClosestObject({\n layers,\n views,\n viewports,\n x,\n y,\n radius = 0,\n depth = 1,\n mode = 'query',\n unproject3D,\n onViewportActive,\n effects\n }: PickByPointOptions & PickOperationContext): {\n result: PickingInfo[];\n emptyInfo: PickingInfo;\n } {\n // @ts-expect-error TODO - assuming WebGL context\n const pixelRatio = this.device.canvasContext.cssToDeviceRatio();\n\n const pickableLayers = this._getPickable(layers);\n\n if (!pickableLayers || viewports.length === 0) {\n return {\n result: [],\n emptyInfo: getEmptyPickingInfo({viewports, x, y, pixelRatio})\n };\n }\n\n this._resizeBuffer();\n\n // Convert from canvas top-left to WebGL bottom-left coordinates\n // Top-left coordinates [x, y] to bottom-left coordinates [deviceX, deviceY]\n // And compensate for pixelRatio\n // @ts-expect-error TODO - assuming WebGL context\n const devicePixelRange = this.device.canvasContext.cssToDevicePixels([x, y], true);\n const devicePixel = [\n devicePixelRange.x + Math.floor(devicePixelRange.width / 2),\n devicePixelRange.y + Math.floor(devicePixelRange.height / 2)\n ];\n\n const deviceRadius = Math.round(radius * pixelRatio);\n const {width, height} = this.pickingFBO as Framebuffer;\n const deviceRect = this._getPickingRect({\n deviceX: devicePixel[0],\n deviceY: devicePixel[1],\n deviceRadius,\n deviceWidth: width,\n deviceHeight: height\n });\n\n const cullRect: Rect = {\n x: x - radius,\n y: y - radius,\n width: radius * 2 + 1,\n height: radius * 2 + 1\n };\n\n let infos: Map;\n const result: PickingInfo[] = [];\n const affectedLayers = new Set();\n\n for (let i = 0; i < depth; i++) {\n let pickInfo: PickedPixel;\n\n if (deviceRect) {\n const pickedResult = this._drawAndSample({\n layers: pickableLayers,\n views,\n viewports,\n onViewportActive,\n deviceRect,\n cullRect,\n effects,\n pass: `picking:${mode}`\n });\n\n pickInfo = getClosestObject({\n ...pickedResult,\n deviceX: devicePixel[0],\n deviceY: devicePixel[1],\n deviceRadius,\n deviceRect\n });\n } else {\n pickInfo = {\n pickedColor: null,\n pickedObjectIndex: -1\n };\n }\n\n let z;\n const depthLayers = this._getDepthLayers(pickInfo, pickableLayers, unproject3D);\n if (depthLayers.length > 0) {\n const {pickedColors: pickedColors2} = this._drawAndSample(\n {\n layers: depthLayers,\n views,\n viewports,\n onViewportActive,\n deviceRect: {\n x: pickInfo.pickedX ?? devicePixel[0],\n y: pickInfo.pickedY ?? devicePixel[1],\n width: 1,\n height: 1\n },\n cullRect,\n effects,\n pass: `picking:${mode}:z`\n },\n true\n );\n // picked value is in common space (pixels) from the camera target (viewport.position)\n // convert it to meters from the ground\n if (pickedColors2[3]) {\n z = pickedColors2[0];\n }\n }\n\n // Only exclude if we need to run picking again.\n // We need to run picking again if an object is detected AND\n // we have not exhausted the requested depth.\n if (pickInfo.pickedLayer && i + 1 < depth) {\n affectedLayers.add(pickInfo.pickedLayer);\n pickInfo.pickedLayer.disablePickingIndex(pickInfo.pickedObjectIndex);\n }\n\n // This logic needs to run even if no object is picked.\n infos = processPickInfo({\n pickInfo,\n lastPickedInfo: this.lastPickedInfo,\n mode,\n layers: pickableLayers,\n viewports,\n x,\n y,\n z,\n pixelRatio\n });\n\n for (const info of infos.values()) {\n if (info.layer) {\n result.push(info);\n }\n }\n\n // If no object is picked stop.\n if (!pickInfo.pickedColor) {\n break;\n }\n }\n\n // reset only affected buffers\n for (const layer of affectedLayers) {\n layer.restorePickingColors();\n }\n\n return {result, emptyInfo: infos!.get(null) as PickingInfo};\n }\n\n /**\n * Pick all objects within the given bounding box\n */\n // eslint-disable-next-line max-statements\n async _pickVisibleObjectsAsync({\n layers,\n views,\n viewports,\n x,\n y,\n width = 1,\n height = 1,\n mode = 'query',\n maxObjects = null,\n onViewportActive,\n effects\n }: PickByRectOptions & PickOperationContext): Promise {\n const pickableLayers = this._getPickable(layers);\n\n if (!pickableLayers || viewports.length === 0) {\n return [];\n }\n\n this._resizeBuffer();\n\n // Convert from canvas top-left to WebGL bottom-left coordinates\n // And compensate for pixelRatio\n // @ts-expect-error TODO - assuming WebGL context\n const pixelRatio = this.device.canvasContext.cssToDeviceRatio();\n // @ts-expect-error TODO - assuming WebGL context\n const leftTop = this.device.canvasContext.cssToDevicePixels([x, y], true);\n\n // take left and top (y inverted in device pixels) from start location\n const deviceLeft = leftTop.x;\n const deviceTop = leftTop.y + leftTop.height;\n\n // take right and bottom (y inverted in device pixels) from end location\n // @ts-expect-error TODO - assuming WebGL context\n const rightBottom = this.device.canvasContext.cssToDevicePixels([x + width, y + height], true);\n const deviceRight = rightBottom.x + rightBottom.width;\n const deviceBottom = rightBottom.y;\n\n const deviceRect = {\n x: deviceLeft,\n y: deviceBottom,\n // deviceTop and deviceRight represent the first pixel outside the desired rect\n width: deviceRight - deviceLeft,\n height: deviceTop - deviceBottom\n };\n\n const pickedResult = await this._drawAndSampleAsync({\n layers: pickableLayers,\n views,\n viewports,\n onViewportActive,\n deviceRect,\n cullRect: {x, y, width, height},\n effects,\n pass: `picking:${mode}`\n });\n\n const pickInfos = getUniqueObjects(pickedResult);\n\n // `getUniqueObjects` dedup by picked color\n // However different picked color may be linked to the same picked object, e.g. stroke and fill of the same polygon\n // picked from different sub layers of a GeoJsonLayer\n // Here after resolving the picked index with `layer.getPickingInfo`, we need to dedup again by unique picked objects\n const uniquePickedObjects = new Map>();\n const uniqueInfos: PickingInfo[] = [];\n\n const limitMaxObjects = Number.isFinite(maxObjects);\n\n for (let i = 0; i < pickInfos.length; i++) {\n if (limitMaxObjects && uniqueInfos.length >= maxObjects!) {\n break;\n }\n const pickInfo = pickInfos[i];\n let info: PickingInfo = {\n color: pickInfo.pickedColor,\n layer: null,\n index: pickInfo.pickedObjectIndex,\n picked: true,\n x,\n y,\n pixelRatio\n };\n\n info = getLayerPickingInfo({layer: pickInfo.pickedLayer as Layer, info, mode});\n // info.layer is always populated because it's a picked pixel\n const pickedLayerId = info.layer!.id;\n if (!uniquePickedObjects.has(pickedLayerId)) {\n uniquePickedObjects.set(pickedLayerId, new Set());\n }\n const uniqueObjectsInLayer = uniquePickedObjects.get(pickedLayerId) as Set;\n // info.object may be null if the layer is using non-iterable data.\n // Fall back to using index as identifier.\n const pickedObjectKey = info.object ?? info.index;\n if (!uniqueObjectsInLayer.has(pickedObjectKey)) {\n uniqueObjectsInLayer.add(pickedObjectKey);\n uniqueInfos.push(info);\n }\n }\n\n return uniqueInfos;\n }\n\n /**\n * Pick all objects within the given bounding box\n * @deprecated WebGL only\n */\n // eslint-disable-next-line max-statements\n _pickVisibleObjects({\n layers,\n views,\n viewports,\n x,\n y,\n width = 1,\n height = 1,\n mode = 'query',\n maxObjects = null,\n onViewportActive,\n effects\n }: PickByRectOptions & PickOperationContext): PickingInfo[] {\n const pickableLayers = this._getPickable(layers);\n\n if (!pickableLayers || viewports.length === 0) {\n return [];\n }\n\n this._resizeBuffer();\n\n // Convert from canvas top-left to WebGL bottom-left coordinates\n // And compensate for pixelRatio\n // @ts-expect-error TODO - assuming WebGL context\n const pixelRatio = this.device.canvasContext.cssToDeviceRatio();\n // @ts-expect-error TODO - assuming WebGL context\n const leftTop = this.device.canvasContext.cssToDevicePixels([x, y], true);\n\n // take left and top (y inverted in device pixels) from start location\n const deviceLeft = leftTop.x;\n const deviceTop = leftTop.y + leftTop.height;\n\n // take right and bottom (y inverted in device pixels) from end location\n // @ts-expect-error TODO - assuming WebGL context\n const rightBottom = this.device.canvasContext.cssToDevicePixels([x + width, y + height], true);\n const deviceRight = rightBottom.x + rightBottom.width;\n const deviceBottom = rightBottom.y;\n\n const deviceRect = {\n x: deviceLeft,\n y: deviceBottom,\n // deviceTop and deviceRight represent the first pixel outside the desired rect\n width: deviceRight - deviceLeft,\n height: deviceTop - deviceBottom\n };\n\n const pickedResult = this._drawAndSample({\n layers: pickableLayers,\n views,\n viewports,\n onViewportActive,\n deviceRect,\n cullRect: {x, y, width, height},\n effects,\n pass: `picking:${mode}`\n });\n\n const pickInfos = getUniqueObjects(pickedResult);\n\n // `getUniqueObjects` dedup by picked color\n // However different picked color may be linked to the same picked object, e.g. stroke and fill of the same polygon\n // picked from different sub layers of a GeoJsonLayer\n // Here after resolving the picked index with `layer.getPickingInfo`, we need to dedup again by unique picked objects\n const uniquePickedObjects = new Map>();\n const uniqueInfos: PickingInfo[] = [];\n\n const limitMaxObjects = Number.isFinite(maxObjects);\n\n for (let i = 0; i < pickInfos.length; i++) {\n if (limitMaxObjects && uniqueInfos.length >= maxObjects!) {\n break;\n }\n const pickInfo = pickInfos[i];\n let info: PickingInfo = {\n color: pickInfo.pickedColor,\n layer: null,\n index: pickInfo.pickedObjectIndex,\n picked: true,\n x,\n y,\n pixelRatio\n };\n\n info = getLayerPickingInfo({layer: pickInfo.pickedLayer as Layer, info, mode});\n // info.layer is always populated because it's a picked pixel\n const pickedLayerId = info.layer!.id;\n if (!uniquePickedObjects.has(pickedLayerId)) {\n uniquePickedObjects.set(pickedLayerId, new Set());\n }\n const uniqueObjectsInLayer = uniquePickedObjects.get(pickedLayerId) as Set;\n // info.object may be null if the layer is using non-iterable data.\n // Fall back to using index as identifier.\n const pickedObjectKey = info.object ?? info.index;\n if (!uniqueObjectsInLayer.has(pickedObjectKey)) {\n uniqueObjectsInLayer.add(pickedObjectKey);\n uniqueInfos.push(info);\n }\n }\n\n return uniqueInfos;\n }\n\n /** Renders layers into the picking buffer with picking colors and read the pixels. */\n _drawAndSampleAsync(params: {\n deviceRect: Rect;\n pass: string;\n layers: Layer[];\n views: Record;\n viewports: Viewport[];\n onViewportActive: (viewport: Viewport) => void;\n cullRect?: Rect;\n effects: Effect[];\n }): Promise<{\n pickedColors: Uint8Array;\n decodePickingColor: PickingColorDecoder;\n }>;\n\n /** Renders layers into the picking buffer with encoded z values and read the pixels. */\n _drawAndSampleAsync(\n params: {\n deviceRect: Rect;\n pass: string;\n layers: Layer[];\n views: Record;\n viewports: Viewport[];\n onViewportActive: (viewport: Viewport) => void;\n cullRect?: Rect;\n effects: Effect[];\n },\n pickZ: true\n ): Promise<{\n pickedColors: Float32Array;\n decodePickingColor: null;\n }>;\n\n // Note: Implementation of the overloaded signatures above, TSDoc is on the signatures\n async _drawAndSampleAsync(\n {\n layers,\n views,\n viewports,\n onViewportActive,\n deviceRect,\n cullRect,\n effects,\n pass\n }: {\n deviceRect: Rect;\n pass: string;\n layers: Layer[];\n views: Record;\n viewports: Viewport[];\n onViewportActive: (viewport: Viewport) => void;\n cullRect?: Rect;\n effects: Effect[];\n },\n pickZ: boolean = false\n ): Promise<{\n pickedColors: Uint8Array | Float32Array;\n decodePickingColor: PickingColorDecoder | null;\n }> {\n const pickingFBO = pickZ ? this.depthFBO : this.pickingFBO;\n const opts = {\n layers,\n layerFilter: this.layerFilter,\n views,\n viewports,\n onViewportActive,\n pickingFBO,\n deviceRect,\n cullRect,\n effects,\n pass,\n pickZ,\n preRenderStats: {},\n isPicking: true\n };\n\n for (const effect of effects) {\n if (effect.useInPicking) {\n opts.preRenderStats[effect.id] = effect.preRender(opts);\n }\n }\n\n const {decodePickingColor, stats} = this.pickLayersPass.render(opts);\n this._updateStats(stats);\n\n const {x, y, width, height} = deviceRect;\n const texture = (pickingFBO as Framebuffer).colorAttachments[0]?.texture;\n if (!texture) {\n throw new Error('Picking framebuffer color attachment is missing');\n }\n\n const pickedColors = await this._readTextureDataAsync(\n texture,\n {x, y, width, height},\n pickZ ? Float32Array : Uint8Array\n );\n\n if (!pickZ) {\n let hasNonZeroAlpha = false;\n for (let i = 3; i < pickedColors.length; i += 4) {\n if (pickedColors[i] !== 0) {\n hasNonZeroAlpha = true;\n break;\n }\n }\n if (!hasNonZeroAlpha && pickedColors.length > 0) {\n log.warn('Async pick readback returned only zero alpha values', {\n deviceRect,\n bytes: Array.from(pickedColors.subarray(0, Math.min(pickedColors.length, 16)))\n })();\n }\n }\n\n return {pickedColors, decodePickingColor};\n }\n\n private async _readTextureDataAsync(\n texture: Texture,\n options: {x: number; y: number; width: number; height: number},\n ArrayType: Uint8ArrayConstructor | Float32ArrayConstructor\n ): Promise {\n const {width, height} = options;\n const layout = texture.computeMemoryLayout(options);\n const readBuffer = this.device.createBuffer({\n byteLength: layout.byteLength,\n usage: Buffer.COPY_DST | Buffer.MAP_READ\n });\n\n try {\n texture.readBuffer(options, readBuffer);\n const readData = await readBuffer.readAsync(0, layout.byteLength);\n const bytesPerElement = ArrayType.BYTES_PER_ELEMENT;\n if (layout.bytesPerRow % bytesPerElement !== 0) {\n throw new Error(\n `Texture readback row stride ${layout.bytesPerRow} is not aligned to ${bytesPerElement}-byte elements.`\n );\n }\n const source = new ArrayType(\n readData.buffer,\n readData.byteOffset,\n layout.byteLength / bytesPerElement\n );\n // Picking textures are RGBA. WebGPU rows may be padded to satisfy GPU alignment\n // requirements, so repack each row into a tightly packed CPU array before decode.\n const packedRowLength = width * 4;\n const sourceRowLength = layout.bytesPerRow / bytesPerElement;\n if (sourceRowLength < packedRowLength) {\n throw new Error(\n `Texture readback row stride ${sourceRowLength} is smaller than packed row length ${packedRowLength}.`\n );\n }\n const packed = new ArrayType(width * height * 4);\n\n for (let row = 0; row < height; row++) {\n const sourceStart = row * sourceRowLength;\n packed.set(\n source.subarray(sourceStart, sourceStart + packedRowLength),\n row * packedRowLength\n );\n }\n\n return packed as T;\n } finally {\n readBuffer.destroy();\n }\n }\n\n /**\n * Renders layers into the picking buffer with picking colors and read the pixels.\n * @deprecated WebGL only, use _drawAndSampleAsync instead\n */\n _drawAndSample(params: {\n deviceRect: Rect;\n pass: string;\n layers: Layer[];\n views: Record;\n viewports: Viewport[];\n onViewportActive: (viewport: Viewport) => void;\n cullRect?: Rect;\n effects: Effect[];\n }): {\n pickedColors: Uint8Array;\n decodePickingColor: PickingColorDecoder;\n };\n\n /**\n * Renders layers into the picking buffer with encoded z values and read the pixels.\n * @deprecated WebGL only, use _drawAndSampleAsync instead\n */\n _drawAndSample(\n params: {\n deviceRect: Rect;\n pass: string;\n layers: Layer[];\n views: Record;\n viewports: Viewport[];\n onViewportActive: (viewport: Viewport) => void;\n cullRect?: Rect;\n effects: Effect[];\n },\n pickZ: true\n ): {\n pickedColors: Float32Array;\n decodePickingColor: null;\n };\n\n // Note: Implementation of the overloaded signatures above, TSDoc is on the signatures\n _drawAndSample(\n {\n layers,\n views,\n viewports,\n onViewportActive,\n deviceRect,\n cullRect,\n effects,\n pass\n }: {\n deviceRect: Rect;\n pass: string;\n layers: Layer[];\n views: Record;\n viewports: Viewport[];\n onViewportActive: (viewport: Viewport) => void;\n cullRect?: Rect;\n effects: Effect[];\n },\n pickZ: boolean = false\n ): {\n pickedColors: Uint8Array | Float32Array;\n decodePickingColor: PickingColorDecoder | null;\n } {\n const pickingFBO = pickZ ? this.depthFBO : this.pickingFBO;\n const opts = {\n layers,\n layerFilter: this.layerFilter,\n views,\n viewports,\n onViewportActive,\n pickingFBO,\n deviceRect,\n cullRect,\n effects,\n pass,\n pickZ,\n preRenderStats: {},\n isPicking: true\n };\n\n for (const effect of effects) {\n if (effect.useInPicking) {\n opts.preRenderStats[effect.id] = effect.preRender(opts);\n }\n }\n\n const {decodePickingColor, stats} = this.pickLayersPass.render(opts);\n this._updateStats(stats);\n\n // Read from an already rendered picking buffer\n // Returns an Uint8ClampedArray of picked pixels\n const {x, y, width, height} = deviceRect;\n const pickedColors = new (pickZ ? Float32Array : Uint8Array)(width * height * 4);\n this.device.readPixelsToArrayWebGL(pickingFBO as Framebuffer, {\n sourceX: x,\n sourceY: y,\n sourceWidth: width,\n sourceHeight: height,\n target: pickedColors\n });\n\n return {pickedColors, decodePickingColor};\n }\n\n private _updateStats(source: RenderStats[]) {\n if (!this.stats) return;\n let layersCount = 0;\n for (const {visibleCount} of source) {\n layersCount += visibleCount;\n }\n this.stats.get('Layers picked').addCount(layersCount);\n }\n\n /**\n * Determine which layers to use for the depth (pickZ) pass.\n * - If a non-draped layer was picked, use just that layer.\n * - If a draped layer was picked (geometry is at z=0) or no layer was picked\n * (e.g. no-FBO tiles at extreme zoom), fall back to terrain layers.\n */\n _getDepthLayers(pickInfo: PickedPixel, pickableLayers: Layer[], unproject3D?: boolean): Layer[] {\n if (!unproject3D || !this.depthFBO) {\n return [];\n }\n const {pickedLayer} = pickInfo;\n const isDraped = pickedLayer?.state?.terrainDrawMode === 'drape';\n if (pickedLayer && !isDraped) {\n return [pickedLayer];\n }\n // For draped layers or when no layer was picked, use terrain layers for depth\n return pickableLayers.filter(l => l.props.operation.includes('terrain'));\n }\n\n /**\n * Calculate a picking rect centered on deviceX and deviceY and clipped to device\n * @returns null if pixel is outside of device\n */\n _getPickingRect({\n deviceX,\n deviceY,\n deviceRadius,\n deviceWidth,\n deviceHeight\n }: {\n deviceX: number;\n deviceY: number;\n deviceRadius: number;\n deviceWidth: number;\n deviceHeight: number;\n }): Rect | null {\n // Create a box of size `radius * 2 + 1` centered at [deviceX, deviceY]\n const x = Math.max(0, deviceX - deviceRadius);\n const y = Math.max(0, deviceY - deviceRadius);\n const width = Math.min(deviceWidth, deviceX + deviceRadius + 1) - x;\n const height = Math.min(deviceHeight, deviceY + deviceRadius + 1) - y;\n\n // x, y out of bounds.\n if (width <= 0 || height <= 0) {\n return null;\n }\n\n return {x, y, width, height};\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport log from '../../utils/log';\nimport type Layer from '../layer';\nimport type Viewport from '../../viewports/viewport';\nimport type {PickingColorDecoder} from '../../passes/pick-layers-pass';\n\nexport type PickedPixel = {\n pickedColor: Uint8Array | null;\n pickedLayer?: Layer;\n pickedViewports?: Viewport[];\n pickedX?: number;\n pickedY?: number;\n pickedObjectIndex: number;\n};\n\nconst NO_PICKED_OBJECT = {\n pickedColor: null,\n pickedObjectIndex: -1\n};\n\n/* eslint-disable max-depth, max-statements */\n/**\n * Pick at a specified pixel with a tolerance radius\n * Returns the closest object to the pixel in shape `{pickedColor, pickedLayer, pickedObjectIndex}`\n */\nexport function getClosestObject({\n pickedColors,\n decodePickingColor,\n deviceX,\n deviceY,\n deviceRadius,\n deviceRect\n}: {\n pickedColors: Uint8Array;\n decodePickingColor: PickingColorDecoder;\n deviceX: number;\n deviceY: number;\n deviceRadius: number;\n deviceRect: {x: number; y: number; width: number; height: number};\n}): PickedPixel {\n // Traverse all pixels in picking results and find the one closest to the supplied\n // [deviceX, deviceY]\n const {x, y, width, height} = deviceRect;\n let minSquareDistanceToCenter = deviceRadius * deviceRadius;\n let closestPixelIndex = -1;\n let i = 0;\n\n for (let row = 0; row < height; row++) {\n const dy = row + y - deviceY;\n const dy2 = dy * dy;\n\n if (dy2 > minSquareDistanceToCenter) {\n // skip this row\n i += 4 * width;\n } else {\n for (let col = 0; col < width; col++) {\n // Decode picked layer from color\n const pickedLayerIndex = pickedColors[i + 3] - 1;\n\n if (pickedLayerIndex >= 0) {\n const dx = col + x - deviceX;\n const d2 = dx * dx + dy2;\n\n if (d2 <= minSquareDistanceToCenter) {\n minSquareDistanceToCenter = d2;\n closestPixelIndex = i;\n }\n }\n i += 4;\n }\n }\n }\n\n if (closestPixelIndex >= 0) {\n // Decode picked object index from color\n const pickedColor = pickedColors.slice(closestPixelIndex, closestPixelIndex + 4);\n const pickedObject = decodePickingColor(pickedColor);\n if (pickedObject) {\n const dy = Math.floor(closestPixelIndex / 4 / width);\n const dx = closestPixelIndex / 4 - dy * width;\n return {\n ...pickedObject,\n pickedColor,\n pickedX: x + dx,\n pickedY: y + dy\n };\n }\n log.error('Picked non-existent layer. Is picking buffer corrupt?')();\n }\n return NO_PICKED_OBJECT;\n}\n\n/**\n * Examines a picking buffer for unique colors\n * Returns array of unique objects in shape `{x, y, pickedColor, pickedLayer, pickedObjectIndex}`\n */\nexport function getUniqueObjects({\n pickedColors,\n decodePickingColor\n}: {\n pickedColors: Uint8Array;\n decodePickingColor: PickingColorDecoder;\n}): PickedPixel[] {\n const uniqueColors = new Map();\n\n // Traverse all pixels in picking results and get unique colors\n if (pickedColors) {\n for (let i = 0; i < pickedColors.length; i += 4) {\n // Decode picked layer from color\n const pickedLayerIndex = pickedColors[i + 3] - 1;\n\n if (pickedLayerIndex >= 0) {\n const pickedColor = pickedColors.slice(i, i + 4);\n const colorKey = pickedColor.join(',');\n // eslint-disable-next-line\n if (!uniqueColors.has(colorKey)) {\n const pickedObject = decodePickingColor(pickedColor);\n // eslint-disable-next-line\n if (pickedObject) {\n uniqueColors.set(colorKey, {\n ...pickedObject,\n color: pickedColor\n });\n } else {\n log.error('Picked non-existent layer. Is picking buffer corrupt?')();\n }\n }\n }\n }\n }\n\n return Array.from(uniqueColors.values());\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type Layer from '../layer';\nimport type Viewport from '../../viewports/viewport';\nimport type {PickedPixel} from './query-object';\n\nexport type PickingInfo = ExtraInfo & {\n color: Uint8Array | null;\n layer: Layer | null;\n sourceLayer?: Layer | null;\n viewport?: Viewport;\n index: number;\n picked: boolean;\n object?: DataT;\n x: number;\n y: number;\n pixel?: [number, number];\n coordinate?: number[];\n devicePixel?: [number, number];\n pixelRatio: number;\n};\n\nexport interface GetPickingInfoParams {\n info: PickingInfo;\n mode: string;\n sourceLayer: Layer | null;\n}\n\n/** Generates some basic information of the picking action: x, y, coordinates etc.\n * Regardless if anything is picked\n */\nexport function getEmptyPickingInfo({\n pickInfo,\n viewports,\n pixelRatio,\n x,\n y,\n z\n}: {\n pickInfo?: PickedPixel;\n viewports: Viewport[];\n pixelRatio: number;\n x: number;\n y: number;\n z?: number;\n}): PickingInfo {\n // If more than one viewports are used in the picking pass, locate the viewport that\n // drew the picked pixel\n let pickedViewport = viewports[0];\n if (viewports.length > 1) {\n // Find the viewport that contain the picked pixel\n pickedViewport = getViewportFromCoordinates(pickInfo?.pickedViewports || viewports, {x, y});\n }\n let coordinate: number[] | undefined;\n if (pickedViewport) {\n const point = [x - pickedViewport.x, y - pickedViewport.y];\n if (z !== undefined) {\n point[2] = z;\n }\n coordinate = pickedViewport.unproject(point);\n }\n\n return {\n color: null,\n layer: null,\n viewport: pickedViewport,\n index: -1,\n picked: false,\n x,\n y,\n pixel: [x, y],\n coordinate,\n devicePixel:\n pickInfo && 'pickedX' in pickInfo\n ? [pickInfo.pickedX as number, pickInfo.pickedY as number]\n : undefined,\n pixelRatio\n };\n}\n\n/* eslint-disable max-depth */\n/** Generates the picking info of a picking operation */\nexport function processPickInfo(opts: {\n pickInfo: PickedPixel;\n lastPickedInfo: {\n index: number;\n layerId: string | null;\n info: PickingInfo | null;\n };\n mode: string;\n layers: Layer[];\n viewports: Viewport[];\n pixelRatio: number;\n x: number;\n y: number;\n z?: number;\n}): Map {\n const {pickInfo, lastPickedInfo, mode, layers} = opts;\n const {pickedColor, pickedLayer, pickedObjectIndex} = pickInfo;\n\n const affectedLayers = pickedLayer ? [pickedLayer] : [];\n\n if (mode === 'hover') {\n // only invoke onHover events if picked object has changed\n const lastPickedPixelIndex = lastPickedInfo.index;\n const lastPickedLayerId = lastPickedInfo.layerId;\n const pickedLayerId = pickedLayer ? pickedLayer.props.id : null;\n\n // proceed only if picked object changed\n if (pickedLayerId !== lastPickedLayerId || pickedObjectIndex !== lastPickedPixelIndex) {\n if (pickedLayerId !== lastPickedLayerId) {\n // We cannot store a ref to lastPickedLayer in the context because\n // the state of an outdated layer is no longer valid\n // and the props may have changed\n const lastPickedLayer = layers.find(layer => layer.props.id === lastPickedLayerId);\n if (lastPickedLayer) {\n // Let leave event fire before enter event\n affectedLayers.unshift(lastPickedLayer);\n }\n }\n\n // Update layer manager context\n lastPickedInfo.layerId = pickedLayerId;\n lastPickedInfo.index = pickedObjectIndex;\n lastPickedInfo.info = null;\n }\n }\n\n const baseInfo = getEmptyPickingInfo(opts);\n\n // Use a Map to store all picking infos.\n // The following two forEach loops are the result of\n // https://github.com/visgl/deck.gl/issues/443\n // Please be very careful when changing this pattern\n const infos = new Map();\n\n // Make sure infos always contain something even if no layer is affected\n infos.set(null, baseInfo);\n\n affectedLayers.forEach(layer => {\n let info = {...baseInfo};\n\n if (layer === pickedLayer) {\n info.color = pickedColor;\n info.index = pickedObjectIndex;\n info.picked = true;\n }\n\n info = getLayerPickingInfo({layer, info, mode});\n const rootLayer = info.layer as Layer;\n\n if (layer === pickedLayer && mode === 'hover') {\n lastPickedInfo.info = info;\n }\n\n // This guarantees that there will be only one copy of info for\n // one composite layer\n infos.set(rootLayer.id, info);\n\n if (mode === 'hover') {\n rootLayer.updateAutoHighlight(info);\n }\n });\n\n return infos;\n}\n\n/** Walk up the layer composite chain to populate the info object */\nexport function getLayerPickingInfo({\n layer,\n info,\n mode\n}: {\n layer: Layer;\n info: PickingInfo;\n mode: string;\n}): PickingInfo {\n while (layer && info) {\n // For a composite layer, sourceLayer will point to the sublayer\n // where the event originates from.\n // It provides additional context for the composite layer's\n // getPickingInfo() method to populate the info object\n const sourceLayer = info.layer || null;\n info.sourceLayer = sourceLayer;\n info.layer = layer;\n // layer.pickLayer() function requires a non-null ```layer.state```\n // object to function properly. So the layer referenced here\n // must be the \"current\" layer, not an \"out-dated\" / \"invalidated\" layer\n info = layer.getPickingInfo({info, mode, sourceLayer});\n layer = layer.parent as Layer;\n }\n return info;\n}\n\n/** Indentifies which viewport, if any corresponds to x and y\n If multiple viewports contain the target pixel, last viewport drawn is returend\n Returns first viewport if no match */\nfunction getViewportFromCoordinates(\n viewports: Viewport[],\n pixel: {x: number; y: number}\n): Viewport {\n // find the last viewport that contains the pixel\n for (let i = viewports.length - 1; i >= 0; i--) {\n const viewport = viewports[i];\n if (viewport.containsPixel(pixel)) {\n return viewport;\n }\n }\n return viewports[0];\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type Deck from './deck';\nimport type Viewport from '../viewports/viewport';\nimport type {PickingInfo} from './picking/pick-info';\nimport type {MjolnirPointerEvent, MjolnirGestureEvent} from 'mjolnir.js';\nimport type Layer from './layer';\nimport {Widget} from './widget';\n\nimport {EVENT_HANDLERS} from './constants';\nimport {deepEqual} from '../utils/deep-equal';\n\nconst PLACEMENTS = {\n 'top-left': {top: 0, left: 0},\n 'top-right': {top: 0, right: 0},\n 'bottom-left': {bottom: 0, left: 0},\n 'bottom-right': {bottom: 0, right: 0},\n fill: {top: 0, left: 0, bottom: 0, right: 0}\n} as const;\nconst DEFAULT_PLACEMENT = 'top-left';\n\nexport type WidgetPlacement = keyof typeof PLACEMENTS;\n\nconst ROOT_CONTAINER_ID = 'root';\n\nexport type WidgetManagerProps = {\n deck: Deck;\n parentElement?: HTMLElement | null;\n};\nexport class WidgetManager {\n deck: Deck;\n parentElement?: HTMLElement | null;\n\n /** Widgets added via the imperative API */\n private defaultWidgets: Widget[] = [];\n /** Widgets received from the declarative API */\n private widgets: Widget[] = [];\n /** Resolved widgets from both imperative and declarative APIs */\n private resolvedWidgets: Widget[] = [];\n\n /** Mounted HTML containers */\n private containers: {[id: string]: HTMLDivElement} = {};\n /** Viewport provided to widget on redraw */\n private lastViewports: {[id: string]: Viewport} = {};\n\n constructor({deck, parentElement}: WidgetManagerProps) {\n this.deck = deck;\n parentElement?.classList.add('deck-widget-container');\n this.parentElement = parentElement;\n }\n\n getWidgets(): Widget[] {\n return this.resolvedWidgets;\n }\n\n /** Declarative API to configure widgets */\n setProps(props: {widgets?: (Widget | null | undefined)[]}) {\n if (props.widgets && !deepEqual(props.widgets, this.widgets, 1)) {\n // Allow application to supply null widgets\n const nextWidgets = props.widgets.filter(Boolean) as Widget[];\n this._setWidgets(nextWidgets);\n }\n }\n\n finalize() {\n for (const widget of this.getWidgets()) {\n this._removeWidget(widget);\n }\n this.defaultWidgets.length = 0;\n this.resolvedWidgets.length = 0;\n for (const id in this.containers) {\n this.containers[id].remove();\n }\n }\n\n /** Imperative API. Widgets added this way are not affected by the declarative prop. */\n addDefault(widget: Widget) {\n if (!this.defaultWidgets.find(w => w.id === widget.id)) {\n this._addWidget(widget);\n this.defaultWidgets.push(widget);\n // Update widget list\n this._setWidgets(this.widgets);\n }\n }\n\n onRedraw({viewports, layers}: {viewports: Viewport[]; layers: Layer[]}) {\n const viewportsById: {[id: string]: Viewport} = viewports.reduce((acc, v) => {\n acc[v.id] = v;\n return acc;\n }, {});\n\n for (const widget of this.getWidgets()) {\n const {viewId} = widget;\n if (viewId) {\n // Attached to a specific view\n const viewport = viewportsById[viewId];\n if (viewport) {\n if (widget.onViewportChange) {\n widget.onViewportChange(viewport);\n }\n widget.onRedraw?.({viewports: [viewport], layers});\n }\n } else {\n // Not attached to a specific view\n if (widget.onViewportChange) {\n for (const viewport of viewports) {\n widget.onViewportChange(viewport);\n }\n }\n widget.onRedraw?.({viewports, layers});\n }\n }\n this.lastViewports = viewportsById;\n this._updateContainers();\n }\n\n onHover(info: PickingInfo, event: MjolnirPointerEvent) {\n for (const widget of this.getWidgets()) {\n const {viewId} = widget;\n if (!viewId || viewId === info.viewport?.id) {\n widget.onHover?.(info, event);\n }\n }\n }\n\n onEvent(info: PickingInfo, event: MjolnirGestureEvent) {\n const eventHandlerProp = EVENT_HANDLERS[event.type];\n if (!eventHandlerProp) {\n return;\n }\n for (const widget of this.getWidgets()) {\n const {viewId} = widget;\n if (!viewId || viewId === info.viewport?.id) {\n widget[eventHandlerProp]?.(info, event);\n }\n }\n }\n\n // INTERNAL METHODS\n\n /**\n * Resolve widgets from the declarative prop\n * Initialize new widgets and remove old ones\n * Update props of existing widgets\n */\n private _setWidgets(nextWidgets: Widget[]) {\n const oldWidgetMap: Record = {};\n\n for (const widget of this.resolvedWidgets) {\n oldWidgetMap[widget.id] = widget;\n }\n // Clear and rebuild the list\n this.resolvedWidgets.length = 0;\n\n // Add all default widgets\n for (const widget of this.defaultWidgets) {\n oldWidgetMap[widget.id] = null;\n this.resolvedWidgets.push(widget);\n }\n\n for (let widget of nextWidgets) {\n const oldWidget = oldWidgetMap[widget.id];\n if (!oldWidget) {\n // Widget is new\n this._addWidget(widget);\n } else if (\n // Widget placement changed\n oldWidget.viewId !== widget.viewId ||\n oldWidget.placement !== widget.placement\n ) {\n this._removeWidget(oldWidget);\n this._addWidget(widget);\n } else if (widget !== oldWidget) {\n // Widget props changed\n oldWidget.setProps(widget.props);\n widget = oldWidget;\n }\n\n // mark as matched\n oldWidgetMap[widget.id] = null;\n this.resolvedWidgets.push(widget);\n }\n\n for (const id in oldWidgetMap) {\n const oldWidget = oldWidgetMap[id];\n if (oldWidget) {\n // No longer exists\n this._removeWidget(oldWidget);\n }\n }\n this.widgets = nextWidgets;\n }\n\n /** Initialize new widget */\n private _addWidget(widget: Widget) {\n const {viewId = null, placement = DEFAULT_PLACEMENT} = widget;\n const container = widget.props._container ?? viewId;\n\n widget.widgetManager = this;\n widget.deck = this.deck;\n\n // Create an attach the HTML root element\n widget.rootElement = widget._onAdd({deck: this.deck, viewId});\n if (widget.rootElement) {\n this._getContainer(container, placement).append(widget.rootElement);\n }\n\n widget.updateHTML();\n }\n\n /** Destroy an old widget */\n private _removeWidget(widget: Widget) {\n widget.onRemove?.();\n\n if (widget.rootElement) {\n widget.rootElement.remove();\n }\n widget.rootElement = undefined;\n widget.deck = undefined;\n widget.widgetManager = undefined;\n }\n\n /** Get a container element based on view and placement */\n private _getContainer(\n viewIdOrContainer: string | HTMLDivElement | null,\n placement: WidgetPlacement\n ): HTMLDivElement {\n if (viewIdOrContainer && typeof viewIdOrContainer !== 'string') {\n return viewIdOrContainer;\n }\n const containerId = viewIdOrContainer || ROOT_CONTAINER_ID;\n let viewContainer = this.containers[containerId];\n if (!viewContainer) {\n viewContainer = document.createElement('div');\n viewContainer.style.pointerEvents = 'none';\n viewContainer.style.position = 'absolute';\n viewContainer.style.overflow = 'hidden';\n this.parentElement?.append(viewContainer);\n this.containers[containerId] = viewContainer;\n }\n let container = viewContainer.querySelector(`.${placement}`);\n if (!container) {\n container = globalThis.document.createElement('div');\n container.className = placement;\n container.style.position = 'absolute';\n container.style.zIndex = '2';\n Object.assign(container.style, PLACEMENTS[placement]);\n viewContainer.append(container);\n }\n return container;\n }\n\n private _updateContainers() {\n const canvasWidth = this.deck.width;\n const canvasHeight = this.deck.height;\n for (const id in this.containers) {\n const viewport = this.lastViewports[id] || null;\n const visible = id === ROOT_CONTAINER_ID || viewport;\n\n const container = this.containers[id];\n if (visible) {\n container.style.display = 'block';\n // Align the container with the view\n container.style.left = `${viewport ? viewport.x : 0}px`;\n container.style.top = `${viewport ? viewport.y : 0}px`;\n container.style.width = `${viewport ? viewport.width : canvasWidth}px`;\n container.style.height = `${viewport ? viewport.height : canvasHeight}px`;\n } else {\n container.style.display = 'none';\n }\n }\n }\n}\n","export function applyStyles(element: HTMLElement, style?: Partial): void {\n if (style) {\n Object.entries(style).map(([key, value]) => {\n if (key.startsWith('--')) {\n // Assume CSS variable\n element.style.setProperty(key, value as string);\n } else {\n // Assume camelCase\n element.style[key] = value;\n }\n });\n }\n}\n\nexport function removeStyles(element: HTMLElement, style?: Partial): void {\n if (style) {\n Object.keys(style).map(key => {\n if (key.startsWith('--')) {\n // Assume CSS variable\n element.style.removeProperty(key);\n } else {\n // Assume camelCase\n element.style[key] = '';\n }\n });\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type Deck from './deck';\nimport type Viewport from '../viewports/viewport';\nimport type {PickingInfo} from './picking/pick-info';\nimport type {MjolnirPointerEvent, MjolnirGestureEvent} from 'mjolnir.js';\nimport type Layer from './layer';\nimport type {WidgetManager, WidgetPlacement} from './widget-manager';\nimport type {ViewOrViews} from './view-manager';\nimport {deepEqual} from '../utils/deep-equal';\nimport {applyStyles, removeStyles} from '../utils/apply-styles';\n\nexport type WidgetProps = {\n id?: string;\n /** CSS inline style overrides. */\n style?: Partial;\n /** Additional CSS class. */\n className?: string;\n /**\n * The container that this widget is being attached to. Default to `viewId`.\n * If set to `'root'`, the widget is placed relative to the whole deck.gl canvas.\n * If set to a valid view id, the widget is placed relative to that view.\n * If set to a HTMLElement, `placement` is ignored and the widget is appended into the given element.\n */\n _container?: string | HTMLDivElement | null;\n};\n\nexport abstract class Widget<\n PropsT extends WidgetProps = WidgetProps,\n ViewsT extends ViewOrViews = null\n> {\n static defaultProps: Required = {\n id: 'widget',\n style: {},\n _container: null,\n className: ''\n };\n\n /** Unique identifier of the widget. */\n id: string;\n /** Widget props, with defaults applied */\n props: Required;\n /**\n * The view id that this widget controls. Default `null`.\n * If assigned, this widget will only respond to events occurred inside the specific view that matches this id.\n */\n viewId?: string | null = null;\n\n /** Widget positioning within the view. Default 'top-left'. */\n abstract placement: WidgetPlacement;\n /** Class name for this widget */\n abstract className: string;\n\n // Populated by core when mounted\n widgetManager?: WidgetManager;\n deck?: Deck;\n rootElement?: HTMLDivElement | null;\n\n constructor(props: PropsT) {\n this.props = {\n // @ts-expect-error `defaultProps` may not exist on constructor\n ...(this.constructor.defaultProps as Required),\n ...props\n };\n // @ts-expect-error TODO(ib) - why is id considered optional even though we use Required<>\n this.id = this.props.id;\n }\n\n /** Called to update widget options */\n setProps(props: Partial): void {\n const oldProps = this.props;\n const el = this.rootElement;\n\n // Update className and style\n if (el && oldProps.className !== props.className) {\n if (oldProps.className) el.classList.remove(oldProps.className);\n if (props.className) el.classList.add(props.className);\n }\n\n // Update style\n if (el && !deepEqual(oldProps.style, props.style, 1)) {\n removeStyles(el, oldProps.style);\n applyStyles(el, props.style);\n }\n\n Object.assign(this.props, props);\n\n // Update the HTML to match the new props\n this.updateHTML();\n }\n\n /** Update the HTML to reflect latest props and state */\n updateHTML(): void {\n if (this.rootElement) {\n this.onRenderHTML(this.rootElement);\n }\n }\n\n // VIEW STATE HELPERS\n protected get viewIds(): string[] {\n return this.viewId ? [this.viewId] : (this.deck?.getViews().map(v => v.id) ?? []);\n }\n\n /** Returns the current view state for the given view */\n protected getViewState(viewId: string): Record {\n // @ts-ignore viewManager is private\n return this.deck?.viewManager?.getViewState(viewId) || {};\n }\n\n /** Updates the view state for the given view */\n protected setViewState(viewId: string, viewState: Record): void {\n // @ts-ignore Using private method temporary until there's a public one\n this.deck?._onViewStateChange({viewId, viewState, interactionState: {}});\n }\n\n // @note empty method calls have an overhead in V8 but it is very low, ~1ns\n\n /**\n * Common utility to create the root DOM element for this widget\n * Configures the top-level styles and adds basic class names for theming\n * @returns an UI element that should be appended to the Deck container\n */\n protected onCreateRootElement(): HTMLDivElement {\n const CLASS_NAMES = [\n // Add class names for theming\n 'deck-widget',\n this.className,\n // plus any app-supplied class name\n this.props.className\n ];\n\n const element = document.createElement('div');\n CLASS_NAMES.filter((cls): cls is string => typeof cls === 'string' && cls.length > 0).forEach(\n className => element.classList.add(className)\n );\n applyStyles(element, this.props.style);\n return element;\n }\n\n // WIDGET LIFECYCLE\n\n /** Called to render HTML into the root element */\n abstract onRenderHTML(rootElement: HTMLElement): void;\n\n /** Internal API called by Deck when the widget is first added to a Deck instance */\n _onAdd(params: {deck: Deck; viewId: string | null}): HTMLDivElement {\n return this.onAdd(params) ?? this.onCreateRootElement();\n }\n\n /** Overridable by subclass - called when the widget is first added to a Deck instance\n * @returns an optional UI element that should be appended to the Deck container\n */\n onAdd(params: {\n /** The Deck instance that the widget is attached to */\n deck: Deck;\n /** The id of the view that the widget is attached to */\n viewId: string | null;\n }): HTMLDivElement | void {}\n\n /** Called when the widget is removed */\n onRemove(): void {}\n\n // deck integration - Event hooks\n\n /** Called when the containing view is changed */\n onViewportChange(viewport: Viewport): void {}\n /** Called when the containing view is redrawn */\n onRedraw(params: {viewports: Viewport[]; layers: Layer[]}): void {}\n /** Called when a hover event occurs */\n onHover(info: PickingInfo, event: MjolnirPointerEvent): void {}\n /** Called when a click event occurs */\n onClick(info: PickingInfo, event: MjolnirGestureEvent): void {}\n /** Called when a drag event occurs */\n onDrag(info: PickingInfo, event: MjolnirGestureEvent): void {}\n /** Called when a dragstart event occurs */\n onDragStart(info: PickingInfo, event: MjolnirGestureEvent): void {}\n /** Called when a dragend event occurs */\n onDragEnd(info: PickingInfo, event: MjolnirGestureEvent): void {}\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Widget, WidgetProps} from './widget';\nimport type {WidgetPlacement} from './widget-manager';\nimport type {PickingInfo} from './picking/pick-info';\nimport type Viewport from '../viewports/viewport';\n\n/* global document */\nconst defaultStyle: Partial = {\n zIndex: '1',\n position: 'absolute',\n pointerEvents: 'none',\n color: '#a0a7b4',\n backgroundColor: '#29323c',\n padding: '10px',\n top: '0',\n left: '0',\n display: 'none'\n};\n\nexport type TooltipContent =\n | null\n | string\n | {\n text?: string;\n html?: string;\n className?: string;\n style?: Partial;\n };\n\nexport type TooltipWidgetProps = WidgetProps;\n\nexport class TooltipWidget extends Widget {\n static defaultProps: Required = {\n ...Widget.defaultProps\n };\n\n id = 'default-tooltip';\n placement: WidgetPlacement = 'fill';\n className = 'deck-tooltip';\n\n isVisible: boolean = false;\n lastViewport?: Viewport;\n\n constructor(props: TooltipWidgetProps = {}) {\n super(props);\n this.setProps(props);\n }\n\n // TODO(ib) - does this really need to be overridden?\n onCreateRootElement() {\n const el = document.createElement('div');\n el.className = this.className;\n Object.assign(el.style, defaultStyle);\n return el;\n }\n\n onRenderHTML(rootElement: HTMLElement): void {}\n\n onViewportChange(viewport: Viewport) {\n if (\n this.isVisible &&\n viewport.id === this.lastViewport?.id &&\n !viewport.equals(this.lastViewport)\n ) {\n // Camera has moved, clear tooltip\n this.setTooltip(null);\n }\n // Always update lastViewport from the render loop to ensure consistent\n // viewport source for comparisons (avoids mismatches with picking viewports)\n this.lastViewport = viewport;\n }\n\n onHover(info: PickingInfo) {\n const {deck} = this;\n const getTooltip = deck && deck.props.getTooltip;\n if (!getTooltip) {\n return;\n }\n const displayInfo = getTooltip(info);\n this.setTooltip(displayInfo, info.x, info.y);\n }\n\n setTooltip(displayInfo: TooltipContent, x?: number, y?: number): void {\n const el = this.rootElement;\n if (!el) {\n return;\n }\n\n if (typeof displayInfo === 'string') {\n el.innerText = displayInfo;\n } else if (!displayInfo) {\n this.isVisible = false;\n el.style.display = 'none';\n return;\n } else {\n if (displayInfo.text) {\n el.innerText = displayInfo.text;\n }\n if (displayInfo.html) {\n el.innerHTML = displayInfo.html;\n }\n if (displayInfo.className) {\n el.className = displayInfo.className;\n }\n }\n this.isVisible = true;\n el.style.display = 'block';\n el.style.transform = `translate(${x}px, ${y}px)`;\n\n if (displayInfo && typeof displayInfo === 'object' && 'style' in displayInfo) {\n Object.assign(el.style, displayInfo.style);\n }\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport LayerManager from './layer-manager';\nimport ViewManager from './view-manager';\nimport MapView from '../views/map-view';\nimport EffectManager from './effect-manager';\nimport DeckRenderer from './deck-renderer';\nimport DeckPicker from './deck-picker';\nimport {Widget} from './widget';\nimport {WidgetManager} from './widget-manager';\nimport {TooltipWidget} from './tooltip-widget';\nimport log from '../utils/log';\nimport {deepEqual} from '../utils/deep-equal';\nimport typedArrayManager from '../utils/typed-array-manager';\nimport {VERSION} from './init';\n\nimport {luma} from '@luma.gl/core';\nimport {webgl2Adapter} from '@luma.gl/webgl';\nimport {GL} from '@luma.gl/webgl/constants';\nimport {Timeline} from '@luma.gl/engine';\nimport {AnimationLoop} from '@luma.gl/engine';\nimport type {CanvasContextProps, Device, DeviceProps, Framebuffer, Parameters} from '@luma.gl/core';\nimport type {ShaderModule} from '@luma.gl/shadertools';\n\nimport {Stats} from '@probe.gl/stats';\nimport {EventManager} from 'mjolnir.js';\n\nimport assert from '../utils/assert';\nimport {EVENT_HANDLERS, RECOGNIZERS, RecognizerOptions} from './constants';\n\nimport type {Effect} from './effect';\nimport type {FilterContext} from '../passes/layers-pass';\nimport type Layer from './layer';\nimport type View from '../views/view';\nimport type Viewport from '../viewports/viewport';\nimport type {EventManagerOptions, MjolnirGestureEvent, MjolnirPointerEvent} from 'mjolnir.js';\nimport type {TypedArrayManagerOptions} from '../utils/typed-array-manager';\nimport type {ViewStateChangeParameters, InteractionState} from '../controllers/controller';\nimport type {PickingInfo} from './picking/pick-info';\nimport type {PickByPointOptions, PickByRectOptions} from './deck-picker';\nimport type {LayersList} from './layer-manager';\nimport type {TooltipContent} from './tooltip-widget';\nimport type {ViewStateMap, AnyViewStateOf, ViewOrViews, ViewStateObject} from './view-manager';\nimport {CreateDeviceProps} from '@luma.gl/core';\n\n/* global document */\n\n// eslint-disable-next-line @typescript-eslint/no-empty-function\nfunction noop() {}\n\nconst getCursor = ({isDragging}) => (isDragging ? 'grabbing' : 'grab');\n\nexport type DeckMetrics = {\n fps: number;\n setPropsTime: number;\n layersCount: number;\n drawLayersCount: number;\n updateLayersCount: number;\n updateAttributesTime: number;\n updateAttributesCount: number;\n framesRedrawn: number;\n pickTime: number;\n pickCount: number;\n pickLayersCount: number;\n gpuTime: number;\n gpuTimePerFrame: number;\n cpuTime: number;\n cpuTimePerFrame: number;\n bufferMemory: number;\n textureMemory: number;\n renderbufferMemory: number;\n gpuMemory: number;\n};\n\ntype CursorState = {\n /** Whether the cursor is over a pickable object */\n isHovering: boolean;\n /** Whether the cursor is down */\n isDragging: boolean;\n};\n\ntype InternalPickingMode = 'sync' | 'async';\ntype PointPickResult = {\n result: PickingInfo[];\n emptyInfo: PickingInfo;\n};\n\nexport type DeckProps = {\n /** Id of this Deck instance */\n id?: string;\n /** Width of the canvas, a number in pixels or a valid CSS string.\n * @default `'100%'`\n */\n width?: string | number | null;\n /** Height of the canvas, a number in pixels or a valid CSS string.\n * @default `'100%'`\n */\n height?: string | number | null;\n /** Additional CSS styles for the canvas. */\n style?: Partial | null;\n\n /** Controls the resolution of drawing buffer used for rendering.\n * @default `true` (use browser devicePixelRatio)\n */\n useDevicePixels?: boolean | number;\n /** Extra pixels around the pointer to include while picking.\n * @default `0`\n */\n pickingRadius?: number;\n /** Selects the internal picking policy used by deck-managed events and controllers.\n * @default `'auto'`\n */\n pickAsync?: InternalPickingMode | 'auto';\n\n /** WebGL parameters to be set before each frame is rendered. */\n parameters?: Parameters;\n /** If supplied, will be called before a layer is drawn to determine whether it should be rendered. */\n layerFilter?: ((context: FilterContext) => boolean) | null;\n\n /** The container to append the auto-created canvas to.\n * @default `document.body`\n */\n parent?: HTMLDivElement | null;\n\n /** The canvas to render into.\n * Can be either a HTMLCanvasElement or the element id.\n * Will be auto-created if not supplied.\n */\n canvas?: HTMLCanvasElement | string | null;\n\n /** Use an existing luma.gl GPU device. @note If not supplied, a new device will be created using props.deviceProps */\n device?: Device | null;\n\n /** A new device will be created using these props, assuming that an existing device is not supplied using props.device) */\n deviceProps?: CreateDeviceProps;\n\n /** WebGL context @deprecated Use props.deviceProps.webgl. Also note that preserveDrawingBuffers is true by default */\n gl?: WebGL2RenderingContext | null;\n\n /**\n * The array of Layer instances to be rendered.\n * Nested arrays are accepted, as well as falsy values (`null`, `false`, `undefined`)\n */\n layers?: LayersList;\n /** The array of effects to be rendered. A lighting effect will be added if an empty array is supplied. */\n effects?: Effect[];\n /** A single View instance, or an array of `View` instances.\n * @default `new MapView()`\n */\n views?: ViewsT;\n /** Options for viewport interactivity, e.g. pan, rotate and zoom with mouse, touch and keyboard.\n * This is a shorthand for defining interaction with the `views` prop if you are using the default view (i.e. a single `MapView`)\n */\n controller?: View['props']['controller'];\n /**\n * An object that describes the view state for each view in the `views` prop.\n * Use if the camera state should be managed external to the `Deck` instance.\n */\n viewState?: ViewStateMap | null;\n /**\n * If provided, the `Deck` instance will track camera state changes automatically,\n * with `initialViewState` as its initial settings.\n */\n initialViewState?: ViewStateMap | null;\n\n /** Allow browser default touch actions.\n * @default `'none'`\n */\n touchAction?: EventManagerOptions['touchAction'];\n /**\n * Optional mjolnir.js recognizer options\n */\n eventRecognizerOptions?: RecognizerOptions;\n\n /** (Experimental) Render to a custom frame buffer other than to screen. */\n _framebuffer?: Framebuffer | null;\n /** (Experimental) Forces deck.gl to redraw layers every animation frame. */\n _animate?: boolean;\n /** (Experimental) If set to `false`, force disables all picking features, disregarding the `pickable` prop set in any layer. */\n _pickable?: boolean;\n /** (Experimental) Fine-tune attribute memory usage. See documentation for details. */\n _typedArrayManagerProps?: TypedArrayManagerOptions;\n /** An array of Widget instances to be added to the parent element. */\n widgets?: Widget[];\n\n /** Called once the GPU Device has been initiated. */\n onDeviceInitialized?: (device: Device) => void;\n /** @deprecated Called once the WebGL context has been initiated. */\n onWebGLInitialized?: (gl: WebGL2RenderingContext) => void;\n /** Called when the canvas resizes. */\n onResize?: (dimensions: {width: number; height: number}) => void;\n /** Called when the user has interacted with the deck.gl canvas, e.g. using mouse, touch or keyboard. */\n onViewStateChange?: >(\n params: ViewStateChangeParameters\n ) => ViewStateT | null | void;\n /** Called when the user has interacted with the deck.gl canvas, e.g. using mouse, touch or keyboard. */\n onInteractionStateChange?: (state: InteractionState) => void;\n /** Called just before the canvas rerenders. */\n onBeforeRender?: (context: {device: Device; gl: WebGL2RenderingContext}) => void;\n /** Called right after the canvas rerenders. */\n onAfterRender?: (context: {device: Device; gl: WebGL2RenderingContext}) => void;\n /** Called once after gl context and all Deck components are created. */\n onLoad?: () => void;\n /** Called if deck.gl encounters an error.\n * If this callback is set to `null`, errors are silently ignored.\n * @default `console.error`\n */\n onError?: ((error: Error, layer?: Layer) => void) | null;\n /** Called when the pointer moves over the canvas. */\n onHover?: ((info: PickingInfo, event: MjolnirPointerEvent) => void) | null;\n /** Called when clicking on the canvas. */\n onClick?: ((info: PickingInfo, event: MjolnirGestureEvent) => void) | null;\n /** Called when the user starts dragging on the canvas. */\n onDragStart?: ((info: PickingInfo, event: MjolnirGestureEvent) => void) | null;\n /** Called when dragging the canvas. */\n onDrag?: ((info: PickingInfo, event: MjolnirGestureEvent) => void) | null;\n /** Called when the user releases from dragging the canvas. */\n onDragEnd?: ((info: PickingInfo, event: MjolnirGestureEvent) => void) | null;\n\n /** (Experimental) Replace the default redraw procedure */\n _customRender?: ((reason: string) => void) | null;\n /** (Experimental) Called once every second with performance metrics. */\n _onMetrics?: ((metrics: DeckMetrics) => void) | null;\n\n /** A custom callback to retrieve the cursor type. */\n getCursor?: (state: CursorState) => string;\n /** Callback that takes a hovered-over point and renders a tooltip. */\n getTooltip?: ((info: PickingInfo) => TooltipContent) | null;\n\n /** (Debug) Flag to enable WebGL debug mode. Requires importing `@luma.gl/debug`. */\n debug?: boolean;\n /** (Debug) Render the picking buffer to screen. */\n drawPickingColors?: boolean;\n};\n\nconst defaultProps: DeckProps = {\n id: '',\n width: '100%',\n height: '100%',\n style: null,\n viewState: null,\n initialViewState: null,\n pickingRadius: 0,\n pickAsync: 'auto',\n layerFilter: null,\n parameters: {},\n parent: null,\n device: null,\n deviceProps: {} as DeviceProps,\n gl: null,\n canvas: null,\n layers: [],\n effects: [],\n views: null,\n controller: null, // Rely on external controller, e.g. react-map-gl\n useDevicePixels: true,\n touchAction: 'none',\n eventRecognizerOptions: {},\n _framebuffer: null,\n _animate: false,\n _pickable: true,\n _typedArrayManagerProps: {},\n _customRender: null,\n widgets: [],\n\n onDeviceInitialized: noop,\n onWebGLInitialized: noop,\n onResize: noop,\n onViewStateChange: noop,\n onInteractionStateChange: noop,\n onBeforeRender: noop,\n onAfterRender: noop,\n onLoad: noop,\n onError: (error: Error) => log.error(error.message, error.cause)(),\n onHover: null,\n onClick: null,\n onDragStart: null,\n onDrag: null,\n onDragEnd: null,\n _onMetrics: null,\n\n getCursor,\n getTooltip: null,\n\n debug: false,\n drawPickingColors: false\n};\n\n/* eslint-disable max-statements */\nexport default class Deck {\n static defaultProps = defaultProps;\n // This is used to defeat tree shaking of init.js\n // https://github.com/visgl/deck.gl/issues/3213\n static VERSION = VERSION;\n\n readonly props: Required>;\n readonly width: number = 0;\n readonly height: number = 0;\n // Allows attaching arbitrary data to the instance\n readonly userData: Record = {};\n\n protected device: Device | null = null;\n\n protected canvas: HTMLCanvasElement | null = null;\n protected viewManager: ViewManager | null = null;\n protected layerManager: LayerManager | null = null;\n protected effectManager: EffectManager | null = null;\n protected deckRenderer: DeckRenderer | null = null;\n protected deckPicker: DeckPicker | null = null;\n protected eventManager: EventManager | null = null;\n protected widgetManager: WidgetManager | null = null;\n protected tooltip: TooltipWidget | null = null;\n protected animationLoop: AnimationLoop | null = null;\n\n /** Internal view state if no callback is supplied */\n protected viewState: ViewStateObject | null;\n protected cursorState: CursorState = {\n isHovering: false,\n isDragging: false\n };\n\n protected stats = new Stats({id: 'deck.gl'});\n protected metrics: DeckMetrics = {\n fps: 0,\n setPropsTime: 0,\n layersCount: 0,\n drawLayersCount: 0,\n updateLayersCount: 0,\n updateAttributesCount: 0,\n updateAttributesTime: 0,\n framesRedrawn: 0,\n pickTime: 0,\n pickCount: 0,\n pickLayersCount: 0,\n gpuTime: 0,\n gpuTimePerFrame: 0,\n cpuTime: 0,\n cpuTimePerFrame: 0,\n bufferMemory: 0,\n textureMemory: 0,\n renderbufferMemory: 0,\n gpuMemory: 0\n };\n private _metricsCounter: number = 0;\n private _hoverPickSequence: number = 0;\n private _pointerDownPickSequence: number = 0;\n\n private _needsRedraw: false | string = 'Initial render';\n private _pickRequest: {\n mode: string;\n event: MjolnirPointerEvent | null;\n x: number;\n y: number;\n radius: number;\n unproject3D?: boolean;\n } = {\n mode: 'hover',\n x: -1,\n y: -1,\n radius: 0,\n event: null,\n unproject3D: false\n };\n\n /**\n * Pick and store the object under the pointer on `pointerdown`.\n * This object is reused for subsequent `onClick` and `onDrag*` callbacks.\n */\n private _lastPointerDownInfo: PickingInfo | null = null;\n private _lastPointerDownInfoPromise: Promise | null = null;\n\n constructor(props: DeckProps) {\n // @ts-ignore views\n this.props = {...defaultProps, ...props};\n props = this.props;\n\n if (props.viewState && props.initialViewState) {\n log.warn(\n 'View state tracking is disabled. Use either `initialViewState` for auto update or `viewState` for manual update.'\n )();\n }\n this.viewState = this.props.initialViewState;\n\n // See if we already have a device\n if (props.device) {\n this.device = props.device;\n }\n\n let deviceOrPromise: Device | Promise | null = this.device;\n\n // Attach a new luma.gl device to a WebGL2 context if supplied\n if (!deviceOrPromise && props.gl) {\n if (props.gl instanceof WebGLRenderingContext) {\n log.error('WebGL1 context not supported.')();\n }\n // Preserve user's callbacks and add resize handling\n const userOnResize = this.props.deviceProps?.onResize;\n\n deviceOrPromise = webgl2Adapter.attach(props.gl, {\n // Enable shader and pipeline caching for attached devices (matches _createDevice defaults)\n // Without this, interleaved mode (e.g., MapboxOverlay) creates new pipelines every frame\n _cacheShaders: true,\n _cachePipelines: true,\n ...this.props.deviceProps,\n onResize: (canvasContext, info) => {\n // Sync drawing buffer dimensions with externally-managed canvas\n const {width, height} = canvasContext.canvas;\n canvasContext.setDrawingBufferSize(width, height);\n\n this._needsRedraw = 'Canvas resized';\n userOnResize?.(canvasContext, info);\n }\n });\n }\n\n // Create a new device\n if (!deviceOrPromise) {\n deviceOrPromise = this._createDevice(props);\n }\n\n this.animationLoop = this._createAnimationLoop(deviceOrPromise, props);\n\n this.setProps(props);\n\n // UNSAFE/experimental prop: only set at initialization to avoid performance hit\n if (props._typedArrayManagerProps) {\n typedArrayManager.setOptions(props._typedArrayManagerProps);\n }\n\n this.animationLoop.start();\n }\n\n /** Stop rendering and dispose all resources */\n finalize() {\n this.animationLoop?.stop();\n this.animationLoop?.destroy();\n this.animationLoop = null;\n this._hoverPickSequence++;\n this._pointerDownPickSequence++;\n this._lastPointerDownInfo = null;\n this._lastPointerDownInfoPromise = null;\n\n this.layerManager?.finalize();\n this.layerManager = null;\n\n this.viewManager?.finalize();\n this.viewManager = null;\n\n this.effectManager?.finalize();\n this.effectManager = null;\n\n this.deckRenderer?.finalize();\n this.deckRenderer = null;\n\n this.deckPicker?.finalize();\n this.deckPicker = null;\n\n this.eventManager?.destroy();\n this.eventManager = null;\n\n this.widgetManager?.finalize();\n this.widgetManager = null;\n\n if (!this.props.canvas && !this.props.device && !this.props.gl && this.canvas) {\n // remove internally created canvas\n this.canvas.parentElement?.removeChild(this.canvas);\n this.canvas = null;\n }\n }\n\n /** Partially update props */\n setProps(props: DeckProps): void {\n this.stats.get('setProps Time').timeStart();\n\n if ('onLayerHover' in props) {\n log.removed('onLayerHover', 'onHover')();\n }\n if ('onLayerClick' in props) {\n log.removed('onLayerClick', 'onClick')();\n }\n if (\n props.initialViewState &&\n // depth = 3 when comparing viewStates: viewId.position.0\n !deepEqual(this.props.initialViewState, props.initialViewState, 3)\n ) {\n // Overwrite internal view state\n this.viewState = props.initialViewState;\n }\n\n // Merge with existing props\n Object.assign(this.props, props);\n this._validateInternalPickingMode();\n\n // Update CSS size of canvas\n this._setCanvasSize(this.props);\n\n // We need to overwrite CSS style width and height with actual, numeric values\n const resolvedProps: Required & {\n width: number;\n height: number;\n views: View[];\n viewState: ViewStateObject | null;\n } = Object.create(this.props);\n Object.assign(resolvedProps, {\n views: this._getViews(),\n width: this.width,\n height: this.height,\n viewState: this._getViewState()\n });\n\n if (props.device && props.device.id !== this.device?.id) {\n this.animationLoop?.stop();\n if (this.canvas !== props.device.canvasContext?.canvas) {\n // remove old canvas if new one being used and de-register events\n // TODO (ck): We might not own this canvas depending it's source, so removing it from the\n // DOM here might be a bit unexpected but it should be ok for most users.\n this.canvas?.remove();\n this.eventManager?.destroy();\n\n // ensure we will re-attach ourselves after createDevice callbacks\n this.canvas = null;\n }\n\n log.log(`recreating animation loop for new device! id=${props.device.id}`)();\n\n this.animationLoop = this._createAnimationLoop(props.device, props);\n this.animationLoop.start();\n }\n\n // Update the animation loop\n this.animationLoop?.setProps(resolvedProps);\n\n if (props.useDevicePixels !== undefined && this.device?.canvasContext?.setProps) {\n this.device.canvasContext.setProps({useDevicePixels: props.useDevicePixels});\n }\n\n // If initialized, update sub manager props\n if (this.layerManager) {\n this.viewManager!.setProps(resolvedProps);\n // Make sure that any new layer gets initialized with the current viewport\n this.layerManager.activateViewport(this.getViewports()[0]);\n this.layerManager.setProps(resolvedProps);\n this.effectManager!.setProps(resolvedProps);\n this.deckRenderer!.setProps(resolvedProps);\n this.deckPicker!.setProps(resolvedProps);\n this.widgetManager!.setProps(resolvedProps);\n }\n\n this.stats.get('setProps Time').timeEnd();\n }\n\n // Public API\n\n /**\n * Check if a redraw is needed\n * @returns `false` or a string summarizing the redraw reason\n */\n needsRedraw(\n opts: {\n /** Reset the redraw flag afterwards. Default `true` */\n clearRedrawFlags: boolean;\n } = {clearRedrawFlags: false}\n ): false | string {\n if (!this.layerManager) {\n // Not initialized or already finalized\n return false;\n }\n if (this.props._animate) {\n return 'Deck._animate';\n }\n\n let redraw: false | string = this._needsRedraw;\n\n if (opts.clearRedrawFlags) {\n this._needsRedraw = false;\n }\n\n const viewManagerNeedsRedraw = this.viewManager!.needsRedraw(opts);\n const layerManagerNeedsRedraw = this.layerManager.needsRedraw(opts);\n const effectManagerNeedsRedraw = this.effectManager!.needsRedraw(opts);\n const deckRendererNeedsRedraw = this.deckRenderer!.needsRedraw(opts);\n\n redraw =\n redraw ||\n viewManagerNeedsRedraw ||\n layerManagerNeedsRedraw ||\n effectManagerNeedsRedraw ||\n deckRendererNeedsRedraw;\n return redraw;\n }\n\n /**\n * Redraw the GL context\n * @param reason If not provided, only redraw if deemed necessary. Otherwise redraw regardless of internal states.\n * @returns\n */\n redraw(reason?: string): void {\n if (!this.layerManager) {\n // Not yet initialized\n return;\n }\n // Check if we need to redraw\n let redrawReason = this.needsRedraw({clearRedrawFlags: true});\n // User-supplied should take precedent, however the redraw flags get cleared regardless\n redrawReason = reason || redrawReason;\n\n if (!redrawReason) {\n return;\n }\n\n this.stats.get('Redraw Count').incrementCount();\n if (this.props._customRender) {\n this.props._customRender(redrawReason);\n } else {\n this._drawLayers(redrawReason);\n }\n }\n\n /** Flag indicating that the Deck instance has initialized its resources and it's safe to call public methods. */\n get isInitialized(): boolean {\n return this.viewManager !== null;\n }\n\n /** Get a list of views that are currently rendered */\n getViews(): View[] {\n assert(this.viewManager);\n return this.viewManager.views;\n }\n\n /** Get a view by id */\n getView(viewId: string): View | undefined {\n assert(this.viewManager);\n return this.viewManager.getView(viewId);\n }\n\n /** Get a list of viewports that are currently rendered.\n * @param rect If provided, only returns viewports within the given bounding box.\n */\n getViewports(rect?: {x: number; y: number; width?: number; height?: number}): Viewport[] {\n assert(this.viewManager);\n return this.viewManager.getViewports(rect);\n }\n\n /** Get the current canvas element. */\n getCanvas(): HTMLCanvasElement | null {\n return this.canvas;\n }\n\n /** Query the object rendered on top at a given point */\n async pickObjectAsync(opts: {\n /** x position in pixels */\n x: number;\n /** y position in pixels */\n y: number;\n /** Radius of tolerance in pixels. Default `0`. */\n radius?: number;\n /** A list of layer ids to query from. If not specified, then all pickable and visible layers are queried. */\n layerIds?: string[];\n /** If `true`, `info.coordinate` will be a 3D point by unprojecting the `x, y` screen coordinates onto the picked geometry. Default `false`. */\n unproject3D?: boolean;\n }): Promise {\n const infos = (await this._pickAsync('pickObjectAsync', 'pickObject Time', opts)).result;\n return infos.length ? infos[0] : null;\n }\n\n /**\n * Query all objects rendered on top within a bounding box\n * @note Caveat: this method performs multiple async GPU queries, so state could potentially change between calls.\n */\n async pickObjectsAsync(opts: {\n /** Left of the bounding box in pixels */\n x: number;\n /** Top of the bounding box in pixels */\n y: number;\n /** Width of the bounding box in pixels. Default `1` */\n width?: number;\n /** Height of the bounding box in pixels. Default `1` */\n height?: number;\n /** A list of layer ids to query from. If not specified, then all pickable and visible layers are queried. */\n layerIds?: string[];\n /** If specified, limits the number of objects that can be returned. */\n maxObjects?: number | null;\n }): Promise {\n return await this._pickAsync('pickObjectsAsync', 'pickObjects Time', opts);\n }\n\n /**\n * Query the object rendered on top at a given point\n * @deprecated WebGL only. Use `pickObjectsAsync` instead\n */\n pickObject(opts: {\n /** x position in pixels */\n x: number;\n /** y position in pixels */\n y: number;\n /** Radius of tolerance in pixels. Default `0`. */\n radius?: number;\n /** A list of layer ids to query from. If not specified, then all pickable and visible layers are queried. */\n layerIds?: string[];\n /** If `true`, `info.coordinate` will be a 3D point by unprojecting the `x, y` screen coordinates onto the picked geometry. Default `false`. */\n unproject3D?: boolean;\n }): PickingInfo | null {\n const infos = this._pick('pickObject', 'pickObject Time', opts).result;\n return infos.length ? infos[0] : null;\n }\n\n /**\n * Query all rendered objects at a given point\n * @deprecated WebGL only. Use `pickObjectsAsync` instead\n */\n pickMultipleObjects(opts: {\n /** x position in pixels */\n x: number;\n /** y position in pixels */\n y: number;\n /** Radius of tolerance in pixels. Default `0`. */\n radius?: number;\n /** Specifies the max number of objects to return. Default `10`. */\n depth?: number;\n /** A list of layer ids to query from. If not specified, then all pickable and visible layers are queried. */\n layerIds?: string[];\n /** If `true`, `info.coordinate` will be a 3D point by unprojecting the `x, y` screen coordinates onto the picked geometry. Default `false`. */\n unproject3D?: boolean;\n }): PickingInfo[] {\n opts.depth = opts.depth || 10;\n return this._pick('pickObject', 'pickMultipleObjects Time', opts).result;\n }\n\n /**\n * Query all objects rendered on top within a bounding box\n * @deprecated WebGL only. Use `pickObjectsAsync` instead\n */\n pickObjects(opts: {\n /** Left of the bounding box in pixels */\n x: number;\n /** Top of the bounding box in pixels */\n y: number;\n /** Width of the bounding box in pixels. Default `1` */\n width?: number;\n /** Height of the bounding box in pixels. Default `1` */\n height?: number;\n /** A list of layer ids to query from. If not specified, then all pickable and visible layers are queried. */\n layerIds?: string[];\n /** If specified, limits the number of objects that can be returned. */\n maxObjects?: number | null;\n }): PickingInfo[] {\n return this._pick('pickObjects', 'pickObjects Time', opts);\n }\n\n /**\n * Internal method used by controllers to pick 3D position at a screen coordinate\n * @private\n */\n private _pickPositionForController(x: number, y: number): {coordinate?: number[]} | null {\n const internalPickingMode = this._getInternalPickingMode();\n if (internalPickingMode !== 'sync') {\n return null;\n }\n\n return this.pickObject({x, y, radius: 0, unproject3D: true});\n }\n\n /** Experimental\n * Add a global resource for sharing among layers\n */\n _addResources(\n resources: {\n [id: string]: any;\n },\n forceUpdate = false\n ) {\n for (const id in resources) {\n this.layerManager!.resourceManager.add({resourceId: id, data: resources[id], forceUpdate});\n }\n }\n\n /** Experimental\n * Remove a global resource\n */\n _removeResources(resourceIds: string[]) {\n for (const id of resourceIds) {\n this.layerManager!.resourceManager.remove(id);\n }\n }\n\n /** Experimental\n * Register a default effect. Effects will be sorted by order, those with a low order will be rendered first\n */\n _addDefaultEffect(effect: Effect) {\n this.effectManager!.addDefaultEffect(effect);\n }\n\n _addDefaultShaderModule(module: ShaderModule>) {\n this.layerManager!.addDefaultShaderModule(module);\n }\n\n _removeDefaultShaderModule(module: ShaderModule>) {\n this.layerManager?.removeDefaultShaderModule(module);\n }\n\n // Private Methods\n\n private _resolveInternalPickingMode(): InternalPickingMode {\n const {pickAsync} = this.props;\n const deviceType = this.device?.type || this.props.deviceProps?.type;\n\n if (pickAsync === 'auto') {\n return deviceType === 'webgpu' ? 'async' : 'sync';\n }\n if (pickAsync === 'sync' && deviceType === 'webgpu') {\n throw new Error('`pickAsync: \"sync\"` is not supported when Deck is using a WebGPU device.');\n }\n return pickAsync;\n }\n\n private _getInternalPickingMode(): InternalPickingMode | null {\n try {\n return this._resolveInternalPickingMode();\n } catch (error) {\n this.props.onError?.(error as Error);\n return null;\n }\n }\n\n private _validateInternalPickingMode(): void {\n this._getInternalPickingMode();\n }\n\n private _getFirstPickedInfo({result, emptyInfo}: PointPickResult): PickingInfo {\n return result[0] || emptyInfo;\n }\n\n private _shouldUnproject3D(layers = this.layerManager?.getLayers() || []): boolean {\n return layers.some(layer => layer.props.pickable === '3d');\n }\n\n private _getPointPickOptions(\n x: number,\n y: number,\n opts: Partial = {},\n layers = this.layerManager?.getLayers() || []\n ): PickByPointOptions {\n return {\n x,\n y,\n radius: this.props.pickingRadius,\n unproject3D: this._shouldUnproject3D(layers),\n ...opts\n };\n }\n\n private _pickPointSync(opts: PickByPointOptions): PointPickResult {\n return this._pick('pickObject', 'pickObject Time', opts);\n }\n\n private _pickPointAsync(opts: PickByPointOptions): Promise {\n return this._pickAsync('pickObjectAsync', 'pickObject Time', opts);\n }\n\n private _getLastPointerDownPickingInfo(\n x: number,\n y: number,\n layers = this.layerManager?.getLayers() || []\n ): PickingInfo {\n return this.deckPicker!.getLastPickedObject(\n {\n x,\n y,\n layers,\n viewports: this.getViewports({x, y})\n },\n this._lastPointerDownInfo\n ) as PickingInfo;\n }\n\n private _applyHoverCallbacks(\n {result, emptyInfo}: PointPickResult,\n event: MjolnirPointerEvent\n ): void {\n if (!this.widgetManager) {\n return;\n }\n\n this.cursorState.isHovering = result.length > 0;\n\n let pickedInfo = emptyInfo;\n let handled = false;\n for (const info of result) {\n pickedInfo = info;\n handled = info.layer?.onHover(info, event) || handled;\n }\n if (!handled) {\n this.props.onHover?.(pickedInfo, event);\n this.widgetManager.onHover(pickedInfo, event);\n }\n }\n\n private _dispatchPickingEvent(info: PickingInfo, event: MjolnirGestureEvent): void {\n if (!this.layerManager || !this.widgetManager) {\n return;\n }\n\n const eventHandlerProp = EVENT_HANDLERS[event.type];\n if (!eventHandlerProp) {\n return;\n }\n\n const {layer} = info;\n const layerHandler = layer && (layer[eventHandlerProp] || layer.props[eventHandlerProp]);\n const rootHandler = this.props[eventHandlerProp];\n let handled = false;\n\n if (layerHandler) {\n handled = layerHandler.call(layer, info, event);\n }\n if (!handled) {\n rootHandler?.(info, event);\n this.widgetManager.onEvent(info, event);\n }\n }\n\n private _pickAsync(\n method: 'pickObjectAsync',\n statKey: string,\n opts: PickByPointOptions & {layerIds?: string[]}\n ): Promise<{\n result: PickingInfo[];\n emptyInfo: PickingInfo;\n }>;\n private _pickAsync(\n method: 'pickObjectsAsync',\n statKey: string,\n opts: PickByRectOptions & {layerIds?: string[]}\n ): Promise;\n\n private _pickAsync(\n method: 'pickObjectAsync' | 'pickObjectsAsync',\n statKey: string,\n opts: (PickByPointOptions | PickByRectOptions) & {layerIds?: string[]}\n ) {\n assert(this.deckPicker);\n\n const {stats} = this;\n\n stats.get('Pick Count').incrementCount();\n stats.get(statKey).timeStart();\n\n const infos = this.deckPicker[method]({\n // layerManager, viewManager and effectManager are always defined if deckPicker is\n layers: this.layerManager!.getLayers(opts),\n views: this.viewManager!.getViews(),\n viewports: this.getViewports(opts),\n onViewportActive: this.layerManager!.activateViewport,\n effects: this.effectManager!.getEffects(),\n ...opts\n });\n\n stats.get(statKey).timeEnd();\n\n return infos;\n }\n\n private _pick(\n method: 'pickObject',\n statKey: string,\n opts: PickByPointOptions & {layerIds?: string[]}\n ): {\n result: PickingInfo[];\n emptyInfo: PickingInfo;\n };\n private _pick(\n method: 'pickObjects',\n statKey: string,\n opts: PickByRectOptions & {layerIds?: string[]}\n ): PickingInfo[];\n\n private _pick(\n method: 'pickObject' | 'pickObjects',\n statKey: string,\n opts: (PickByPointOptions | PickByRectOptions) & {layerIds?: string[]}\n ) {\n assert(this.deckPicker);\n\n const {stats} = this;\n\n stats.get('Pick Count').incrementCount();\n stats.get(statKey).timeStart();\n\n const infos = this.deckPicker[method]({\n // layerManager, viewManager and effectManager are always defined if deckPicker is\n layers: this.layerManager!.getLayers(opts),\n views: this.viewManager!.getViews(),\n viewports: this.getViewports(opts),\n onViewportActive: this.layerManager!.activateViewport,\n effects: this.effectManager!.getEffects(),\n ...opts\n });\n\n stats.get(statKey).timeEnd();\n\n return infos;\n }\n\n /** Resolve props.canvas to element */\n private _createCanvas(props: DeckProps): HTMLCanvasElement {\n let canvas = props.canvas;\n\n // TODO EventManager should accept element id\n if (typeof canvas === 'string') {\n canvas = document.getElementById(canvas) as HTMLCanvasElement;\n assert(canvas);\n }\n\n if (!canvas) {\n canvas = document.createElement('canvas');\n canvas.id = props.id || 'deckgl-overlay';\n\n // TODO this is a hack, investigate why these are not set for the picking\n // tests\n if (props.width && typeof props.width === 'number') {\n canvas.width = props.width;\n }\n if (props.height && typeof props.height === 'number') {\n canvas.height = props.height;\n }\n const parent = props.parent || document.body;\n parent.appendChild(canvas);\n }\n\n Object.assign(canvas.style, props.style);\n\n return canvas;\n }\n\n /** Updates canvas width and/or height, if provided as props */\n private _setCanvasSize(props: Required>): void {\n if (!this.canvas) {\n return;\n }\n\n const {width, height} = props;\n // Set size ONLY if props are being provided, otherwise let canvas be layouted freely\n if (width || width === 0) {\n const cssWidth = Number.isFinite(width) ? `${width}px` : (width as string);\n this.canvas.style.width = cssWidth;\n }\n if (height || height === 0) {\n const cssHeight = Number.isFinite(height) ? `${height}px` : (height as string);\n // Note: position==='absolute' required for height 100% to work\n this.canvas.style.position = props.style?.position || 'absolute';\n this.canvas.style.height = cssHeight;\n }\n }\n\n /** If canvas size has changed, reads out the new size and update */\n private _updateCanvasSize(): void {\n const {canvas} = this;\n if (!canvas) {\n return;\n }\n // Fallback to width/height when clientWidth/clientHeight are undefined (OffscreenCanvas).\n const newWidth = canvas.clientWidth ?? canvas.width;\n const newHeight = canvas.clientHeight ?? canvas.height;\n if (newWidth !== this.width || newHeight !== this.height) {\n // @ts-expect-error private assign to read-only property\n this.width = newWidth;\n // @ts-expect-error private assign to read-only property\n this.height = newHeight;\n this.viewManager?.setProps({width: newWidth, height: newHeight});\n // Make sure that any new layer gets initialized with the current viewport\n this.layerManager?.activateViewport(this.getViewports()[0]);\n this.props.onResize({width: newWidth, height: newHeight});\n }\n }\n\n private _createAnimationLoop(\n deviceOrPromise: Device | Promise,\n props: DeckProps\n ): AnimationLoop {\n const {\n // width,\n // height,\n gl,\n // debug,\n onError\n // onBeforeRender,\n // onAfterRender,\n } = props;\n\n return new AnimationLoop({\n device: deviceOrPromise,\n // TODO v9\n autoResizeDrawingBuffer: !gl, // do not auto resize external context\n autoResizeViewport: false,\n // @ts-expect-error luma.gl needs to accept Promise return value\n onInitialize: context => this._setDevice(context.device),\n onRender: this._onRenderFrame.bind(this),\n // @ts-expect-error typing mismatch: AnimationLoop does not accept onError:null\n onError\n\n // onBeforeRender,\n // onAfterRender,\n });\n }\n\n // Create a device from the deviceProps, assigning required defaults\n private _createDevice(props: DeckProps): Promise {\n const canvasContextUserProps = this.props.deviceProps?.createCanvasContext;\n const canvasContextProps =\n typeof canvasContextUserProps === 'object' ? canvasContextUserProps : undefined;\n\n // In deck.gl v9, Deck always bundles and adds a webgl2Adapter.\n // This behavior is expected to change in deck.gl v10 to support WebGPU only builds.\n const deviceProps = {\n adapters: [],\n _cacheShaders: true,\n _cachePipelines: true,\n ...props.deviceProps\n };\n if (!deviceProps.adapters.includes(webgl2Adapter)) {\n deviceProps.adapters.push(webgl2Adapter);\n }\n\n const defaultCanvasProps: CanvasContextProps = {\n // we must use 'premultiplied' canvas for webgpu to enable transparency and match shaders\n alphaMode: this.props.deviceProps?.type === 'webgpu' ? 'premultiplied' : undefined\n };\n\n // Preserve user's onResize callback\n const userOnResize = this.props.deviceProps?.onResize;\n\n // Create the \"best\" device supported from the registered adapters\n return luma.createDevice({\n // luma by default throws if a device is already attached\n // asynchronous device creation could happen after finalize() is called\n // TODO - createDevice should support AbortController?\n _reuseDevices: true,\n // tests can't handle WebGPU devices yet so we force WebGL2 unless overridden\n type: 'webgl',\n ...deviceProps,\n // In deck.gl v10 we may emphasize multi canvas support and unwind this prop wrapping\n createCanvasContext: {\n ...defaultCanvasProps,\n ...canvasContextProps,\n canvas: this._createCanvas(props),\n useDevicePixels: this.props.useDevicePixels,\n autoResize: true\n },\n onResize: (canvasContext, info) => {\n // Set redraw flag when luma.gl's CanvasContext detects a resize\n // This restores pre-9.2 behavior where resize automatically triggered redraws\n this._needsRedraw = 'Canvas resized';\n // Call user's onResize if provided\n userOnResize?.(canvasContext, info);\n }\n });\n }\n\n // Get the most relevant view state: props.viewState, if supplied, shadows internal viewState\n // TODO: For backwards compatibility ensure numeric width and height is added to the viewState\n private _getViewState(): ViewStateObject | null {\n return this.props.viewState || this.viewState;\n }\n\n // Get the view descriptor list\n private _getViews(): View[] {\n const {views} = this.props;\n const normalizedViews: View[] = Array.isArray(views)\n ? views\n : // If null, default to a full screen map view port\n views\n ? [views]\n : [new MapView({id: 'default-view'})];\n if (normalizedViews.length && this.props.controller) {\n // Backward compatibility: support controller prop\n normalizedViews[0].props.controller = this.props.controller;\n }\n return normalizedViews;\n }\n\n private _onContextLost() {\n const {onError} = this.props;\n if (this.animationLoop && onError) {\n onError(new Error('WebGL context is lost'));\n }\n }\n\n // The `pointermove` event may fire multiple times in between two animation frames,\n // it's a waste of time to run picking without rerender. Instead we save the last pick\n // request and only do it once on the next animation frame.\n /** Internal use only: event handler for pointerdown */\n _onPointerMove = (event: MjolnirPointerEvent) => {\n const {_pickRequest} = this;\n if (event.type === 'pointerleave') {\n _pickRequest.x = -1;\n _pickRequest.y = -1;\n _pickRequest.radius = 0;\n } else if (event.leftButton || event.rightButton) {\n // Do not trigger onHover callbacks if mouse button is down.\n return;\n } else {\n const pos = event.offsetCenter;\n // Do not trigger callbacks when click/hover position is invalid. Doing so will cause a\n // assertion error when attempting to unproject the position.\n if (!pos) {\n return;\n }\n _pickRequest.x = pos.x;\n _pickRequest.y = pos.y;\n _pickRequest.radius = this.props.pickingRadius;\n }\n\n if (this.layerManager) {\n this.layerManager.context.mousePosition = {x: _pickRequest.x, y: _pickRequest.y};\n }\n\n _pickRequest.event = event;\n };\n\n /** Actually run picking */\n private _pickAndCallback() {\n const {_pickRequest} = this;\n\n if (_pickRequest.event) {\n const event = _pickRequest.event;\n const layers = this.layerManager?.getLayers() || [];\n const pickOptions = this._getPointPickOptions(\n _pickRequest.x,\n _pickRequest.y,\n {\n radius: _pickRequest.radius,\n mode: _pickRequest.mode\n },\n layers\n );\n const internalPickingMode = this._getInternalPickingMode();\n const hoverPickSequence = ++this._hoverPickSequence;\n\n _pickRequest.event = null;\n\n if (!internalPickingMode) {\n return;\n }\n\n if (internalPickingMode === 'sync') {\n this._applyHoverCallbacks(this._pickPointSync(pickOptions), event);\n return;\n }\n\n this._pickPointAsync(pickOptions)\n .then(({result, emptyInfo}) => {\n if (hoverPickSequence === this._hoverPickSequence) {\n this._applyHoverCallbacks({result, emptyInfo}, event);\n }\n })\n .catch(error => this.props.onError?.(error));\n }\n }\n\n private _updateCursor(): void {\n const container = this.props.parent || this.canvas;\n if (container) {\n container.style.cursor = this.props.getCursor(this.cursorState);\n }\n }\n\n private _setDevice(device: Device) {\n this.device = device;\n this._validateInternalPickingMode();\n\n if (!this.animationLoop) {\n // finalize() has been called\n return;\n }\n\n // if external context...\n if (!this.canvas) {\n this.canvas = this.device.canvasContext?.canvas as HTMLCanvasElement;\n\n // external canvas may not be in DOM\n if (!this.canvas.isConnected && this.props.parent) {\n this.props.parent.insertBefore(this.canvas, this.props.parent.firstChild);\n }\n // TODO v9\n // ts-expect-error - Currently luma.gl v9 does not expose these options\n // All WebGLDevice contexts are instrumented, but it seems the device\n // should have a method to start state tracking even if not enabled?\n // instrumentGLContext(this.device.gl, {enable: true, copyState: true});\n }\n\n if (this.device.type === 'webgl') {\n this.device.setParametersWebGL({\n blend: true,\n blendFunc: [GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA, GL.ONE, GL.ONE_MINUS_SRC_ALPHA],\n polygonOffsetFill: true,\n depthTest: true,\n depthFunc: GL.LEQUAL\n });\n }\n\n this.props.onDeviceInitialized(this.device);\n if (this.device.type === 'webgl') {\n // Legacy callback - warn?\n // @ts-expect-error gl is not visible on Device base class\n this.props.onWebGLInitialized(this.device.gl);\n }\n\n // timeline for transitions\n const timeline = new Timeline();\n timeline.play();\n this.animationLoop.attachTimeline(timeline);\n\n const eventRoot =\n this.props.parent?.querySelector('.deck-events-root') || this.canvas;\n this.eventManager = new EventManager(eventRoot, {\n touchAction: this.props.touchAction,\n recognizers: Object.keys(RECOGNIZERS).map((eventName: string) => {\n // Resolve recognizer settings\n const [RecognizerConstructor, defaultOptions, recognizeWith, requestFailure] =\n RECOGNIZERS[eventName];\n const optionsOverride = this.props.eventRecognizerOptions?.[eventName];\n const options = {...defaultOptions, ...optionsOverride, event: eventName};\n return {\n recognizer: new RecognizerConstructor(options),\n recognizeWith,\n requestFailure\n };\n }),\n events: {\n pointerdown: this._onPointerDown,\n pointermove: this._onPointerMove,\n pointerleave: this._onPointerMove\n }\n });\n for (const eventType in EVENT_HANDLERS) {\n this.eventManager.on(eventType, this._onEvent);\n }\n\n this.viewManager = new ViewManager({\n timeline,\n eventManager: this.eventManager,\n onViewStateChange: this._onViewStateChange.bind(this),\n onInteractionStateChange: this._onInteractionStateChange.bind(this),\n pickPosition: this._pickPositionForController.bind(this),\n views: this._getViews(),\n viewState: this._getViewState(),\n width: this.width,\n height: this.height\n });\n\n // viewManager must be initialized before layerManager\n // layerManager depends on viewport created by viewManager.\n const viewport = this.viewManager.getViewports()[0];\n\n // Note: avoid React setState due GL animation loop / setState timing issue\n this.layerManager = new LayerManager(this.device, {\n deck: this,\n stats: this.stats,\n viewport,\n timeline\n });\n\n this.effectManager = new EffectManager({\n deck: this,\n device: this.device\n });\n\n this.deckRenderer = new DeckRenderer(this.device, {stats: this.stats});\n\n this.deckPicker = new DeckPicker(this.device, {stats: this.stats});\n\n const widgetParent =\n this.props.parent?.querySelector('.deck-widgets-root') ||\n this.canvas?.parentElement;\n\n this.widgetManager = new WidgetManager({\n deck: this,\n parentElement: widgetParent\n });\n this.widgetManager.addDefault(new TooltipWidget());\n\n this.setProps(this.props);\n\n this._updateCanvasSize();\n this.props.onLoad();\n }\n\n /** Internal only: default render function (redraw all layers and views) */\n _drawLayers(\n redrawReason: string,\n renderOptions?: {\n target?: Framebuffer;\n layerFilter?: (context: FilterContext) => boolean;\n layers?: Layer[];\n viewports?: Viewport[];\n views?: {[viewId: string]: View};\n pass?: string;\n effects?: Effect[];\n clearStack?: boolean;\n clearCanvas?: boolean;\n }\n ) {\n const {device, gl} = this.layerManager!.context;\n\n this.props.onBeforeRender({device, gl});\n\n const opts = {\n target: this.props._framebuffer,\n layers: this.layerManager!.getLayers(),\n viewports: this.viewManager!.getViewports(),\n onViewportActive: this.layerManager!.activateViewport,\n views: this.viewManager!.getViews(),\n pass: 'screen',\n effects: this.effectManager!.getEffects(),\n ...renderOptions\n };\n this.deckRenderer?.renderLayers(opts);\n\n if (opts.pass === 'screen') {\n // This method could be called when drawing to picking buffer, texture etc.\n // Only when drawing to screen, update all widgets (UI components)\n this.widgetManager!.onRedraw({\n viewports: opts.viewports,\n layers: opts.layers\n });\n }\n\n this.props.onAfterRender({device, gl});\n }\n\n // Callbacks\n\n private _onRenderFrame() {\n this._getFrameStats();\n\n // Log perf stats every second\n if (this._metricsCounter++ % 60 === 0) {\n this._getMetrics();\n this.stats.reset();\n log.table(4, this.metrics)();\n\n // Experimental: report metrics\n if (this.props._onMetrics) {\n this.props._onMetrics(this.metrics);\n }\n }\n\n this._updateCanvasSize();\n\n this._updateCursor();\n\n // Update layers if needed (e.g. some async prop has loaded)\n // Note: This can trigger a redraw\n this.layerManager!.updateLayers();\n\n // Perform picking request if any\n this._pickAndCallback();\n\n // Redraw if necessary\n this.redraw();\n\n // Update viewport transition if needed\n // Note: this can trigger `onViewStateChange`, and affect layers\n // We want to defer these changes to the next frame\n if (this.viewManager) {\n this.viewManager.updateViewStates();\n }\n }\n\n // Callbacks\n\n private _onViewStateChange(params: ViewStateChangeParameters & {viewId: string}) {\n // Let app know that view state is changing, and give it a chance to change it\n const viewState = this.props.onViewStateChange(params) || params.viewState;\n\n // If initialViewState was set on creation, auto track position\n if (this.viewState) {\n this.viewState = {...this.viewState, [params.viewId]: viewState};\n if (!this.props.viewState) {\n // Apply internal view state\n if (this.viewManager) {\n this.viewManager.setProps({viewState: this.viewState});\n }\n }\n }\n }\n\n private _onInteractionStateChange(interactionState: InteractionState) {\n this.cursorState.isDragging = interactionState.isDragging || false;\n this.props.onInteractionStateChange(interactionState);\n }\n\n /** Internal use only: event handler for click & drag */\n _onEvent = (event: MjolnirGestureEvent) => {\n const eventHandlerProp = EVENT_HANDLERS[event.type];\n const pos = event.offsetCenter;\n\n if (!eventHandlerProp || !pos || !this.layerManager) {\n return;\n }\n\n const layers = this.layerManager.getLayers();\n const internalPickingMode = this._getInternalPickingMode();\n\n if (!internalPickingMode) {\n return;\n }\n\n if (internalPickingMode === 'sync') {\n const info =\n event.type === 'click' && this._shouldUnproject3D(layers)\n ? this._getFirstPickedInfo(\n this._pickPointSync(\n this._getPointPickOptions(pos.x, pos.y, {unproject3D: true}, layers)\n )\n )\n : this._getLastPointerDownPickingInfo(pos.x, pos.y, layers);\n\n this._dispatchPickingEvent(info, event);\n return;\n }\n\n const pointerDownInfoPromise =\n this._lastPointerDownInfoPromise ||\n Promise.resolve(this._getLastPointerDownPickingInfo(pos.x, pos.y, layers));\n\n pointerDownInfoPromise\n .then(info => {\n this._dispatchPickingEvent(info, event);\n })\n .catch(error => this.props.onError?.(error));\n };\n\n /** Internal use only: evnet handler for pointerdown */\n _onPointerDown = (event: MjolnirPointerEvent) => {\n const pos = event.offsetCenter;\n if (!pos) {\n return;\n }\n\n const internalPickingMode = this._getInternalPickingMode();\n if (!internalPickingMode) {\n return;\n }\n\n const layers = this.layerManager?.getLayers() || [];\n const pointerDownPickSequence = ++this._pointerDownPickSequence;\n\n if (internalPickingMode === 'sync') {\n const pickedInfo = this._pickPointSync({\n x: pos.x,\n y: pos.y,\n radius: this.props.pickingRadius\n });\n const info = this._getFirstPickedInfo(pickedInfo);\n this._lastPointerDownInfo = info;\n this._lastPointerDownInfoPromise = Promise.resolve(info);\n return;\n }\n\n const pickPromise = this._pickPointAsync(this._getPointPickOptions(pos.x, pos.y, {}, layers))\n .then(pickResult => this._getFirstPickedInfo(pickResult))\n .then(info => {\n if (pointerDownPickSequence === this._pointerDownPickSequence) {\n this._lastPointerDownInfo = info;\n }\n return info;\n })\n .catch(error => {\n this.props.onError?.(error);\n const fallbackInfo =\n this.deckPicker && this.viewManager\n ? this._getLastPointerDownPickingInfo(pos.x, pos.y, layers)\n : ({} as PickingInfo);\n if (pointerDownPickSequence === this._pointerDownPickSequence) {\n this._lastPointerDownInfo = fallbackInfo;\n }\n return fallbackInfo;\n });\n\n this._lastPointerDownInfo = null;\n this._lastPointerDownInfoPromise = pickPromise;\n };\n\n private _getFrameStats(): void {\n const {stats} = this;\n stats.get('frameRate').timeEnd();\n stats.get('frameRate').timeStart();\n\n // Get individual stats from luma.gl so reset works\n const animationLoopStats = this.animationLoop!.stats;\n stats.get('GPU Time').addTime(animationLoopStats.get('GPU Time').lastTiming);\n stats.get('CPU Time').addTime(animationLoopStats.get('CPU Time').lastTiming);\n }\n\n private _getMetrics(): void {\n const {metrics, stats} = this;\n metrics.fps = stats.get('frameRate').getHz();\n metrics.setPropsTime = stats.get('setProps Time').time;\n metrics.updateAttributesTime = stats.get('Update Attributes').time;\n metrics.framesRedrawn = stats.get('Redraw Count').count;\n metrics.pickTime =\n stats.get('pickObject Time').time +\n stats.get('pickMultipleObjects Time').time +\n stats.get('pickObjects Time').time;\n metrics.pickCount = stats.get('Pick Count').count;\n\n metrics.layersCount = this.layerManager?.layers.length ?? 0;\n metrics.drawLayersCount = stats.get('Layers rendered').lastSampleCount;\n metrics.pickLayersCount = stats.get('Layers picked').lastSampleCount;\n metrics.updateAttributesCount = stats.get('Layers updated').count;\n metrics.updateAttributesCount = stats.get('Attributes updated').count;\n\n // Luma stats\n metrics.gpuTime = stats.get('GPU Time').time;\n metrics.cpuTime = stats.get('CPU Time').time;\n metrics.gpuTimePerFrame = stats.get('GPU Time').getAverageTime();\n metrics.cpuTimePerFrame = stats.get('CPU Time').getAverageTime();\n\n const memoryStats = luma.stats.get('GPU Time and Memory');\n metrics.bufferMemory = memoryStats.get('Buffer Memory').count;\n metrics.textureMemory = memoryStats.get('Texture Memory').count;\n metrics.renderbufferMemory = memoryStats.get('Renderbuffer Memory').count;\n metrics.gpuMemory = memoryStats.get('GPU Memory').count;\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/* eslint-disable complexity */\nimport type {Device, NormalizedDataType} from '@luma.gl/core';\nimport {Buffer, BufferLayout, BufferAttributeLayout} from '@luma.gl/core';\n\nimport {\n typedArrayFromDataType,\n getBufferAttributeLayout,\n getStride,\n dataTypeFromTypedArray\n} from './gl-utils';\nimport typedArrayManager from '../../utils/typed-array-manager';\nimport {toDoublePrecisionArray} from '../../utils/math-utils';\nimport log from '../../utils/log';\n\nimport type {TypedArray, NumericArray, TypedArrayConstructor} from '../../types/types';\n\nexport type DataType = Exclude;\nexport type LogicalDataType = DataType | 'float64';\n\nexport type BufferAccessor = {\n /** Vertex data type. */\n type?: DataType;\n /** The number of elements per vertex attribute. */\n size?: number;\n /** Offset of the first vertex attribute into the buffer, in bytes. */\n offset?: number;\n /** The offset between the beginning of consecutive vertex attributes, in bytes. */\n stride?: number;\n};\n\nexport type ShaderAttributeOptions = Partial & {\n offset: number;\n stride: number;\n vertexOffset?: number;\n elementOffset?: number;\n};\n\nfunction resolveShaderAttribute(\n baseAccessor: DataColumnSettings,\n shaderAttributeOptions: Partial\n): ShaderAttributeOptions {\n if (shaderAttributeOptions.offset) {\n log.removed('shaderAttribute.offset', 'vertexOffset, elementOffset')();\n }\n\n // All shader attributes share the parent's stride\n const stride = getStride(baseAccessor);\n // `vertexOffset` is used to access the neighboring vertex's value\n // e.g. `nextPositions` in polygon\n const vertexOffset =\n shaderAttributeOptions.vertexOffset !== undefined\n ? shaderAttributeOptions.vertexOffset\n : baseAccessor.vertexOffset || 0;\n // `elementOffset` is defined when shader attribute's size is smaller than the parent's\n // e.g. `translations` in transform matrix\n const elementOffset = shaderAttributeOptions.elementOffset || 0;\n const offset =\n // offsets defined by the attribute\n vertexOffset * stride +\n elementOffset * baseAccessor.bytesPerElement +\n // offsets defined by external buffers if any\n (baseAccessor.offset || 0);\n\n return {\n ...shaderAttributeOptions,\n offset,\n stride\n };\n}\n\nfunction resolveDoublePrecisionShaderAttributes(\n baseAccessor: DataColumnSettings,\n shaderAttributeOptions: Partial\n): {\n high: ShaderAttributeOptions;\n low: ShaderAttributeOptions;\n} {\n const resolvedOptions = resolveShaderAttribute(baseAccessor, shaderAttributeOptions);\n\n return {\n high: resolvedOptions,\n low: {\n ...resolvedOptions,\n offset: resolvedOptions.offset + baseAccessor.size * 4\n }\n };\n}\n\nexport type DataColumnOptions = Options &\n Omit & {\n id?: string;\n vertexOffset?: number;\n fp64?: boolean;\n /** Vertex data type.\n * @default 'float32'\n */\n type?: LogicalDataType;\n /** Internal API, use `type` instead */\n logicalType?: LogicalDataType;\n isIndexed?: boolean;\n defaultValue?: number | Readonly;\n };\n\nexport type DataColumnSettings = DataColumnOptions & {\n type: DataType;\n size: number;\n logicalType?: LogicalDataType;\n normalized: boolean;\n bytesPerElement: number;\n defaultValue: number[];\n defaultType: TypedArrayConstructor;\n};\n\ntype DataColumnInternalState = State & {\n externalBuffer: Buffer | null;\n bufferAccessor: DataColumnSettings;\n allocatedValue: TypedArray | null;\n numInstances: number;\n bounds: [number[], number[]] | null;\n constant: boolean;\n};\n\nexport default class DataColumn {\n device: Device;\n id: string;\n size: number;\n settings: DataColumnSettings;\n value: NumericArray | null;\n doublePrecision: boolean;\n\n protected _buffer: Buffer | null = null;\n protected state: DataColumnInternalState;\n\n /* eslint-disable max-statements */\n constructor(device: Device, opts: DataColumnOptions, state: State) {\n this.device = device;\n this.id = opts.id || '';\n this.size = opts.size || 1;\n\n const logicalType = opts.logicalType || opts.type;\n const doublePrecision = logicalType === 'float64';\n\n let {defaultValue} = opts;\n defaultValue = Number.isFinite(defaultValue)\n ? [defaultValue]\n : defaultValue || new Array(this.size).fill(0);\n\n let bufferType: DataType;\n if (doublePrecision) {\n bufferType = 'float32';\n } else if (!logicalType && opts.isIndexed) {\n bufferType = 'uint32';\n } else {\n bufferType = logicalType || 'float32';\n }\n\n // This is the attribute type defined by the layer\n // If an external buffer is provided, this.type may be overwritten\n // But we always want to use defaultType for allocation\n let defaultType = typedArrayFromDataType(logicalType || bufferType);\n this.doublePrecision = doublePrecision;\n\n // `fp64: false` tells a double-precision attribute to allocate Float32Arrays\n // by default when using auto-packing. This is more efficient in use cases where\n // high precision is unnecessary, but the `64Low` attribute is still required\n // by the shader.\n if (doublePrecision && opts.fp64 === false) {\n defaultType = Float32Array;\n }\n\n this.value = null;\n this.settings = {\n ...opts,\n defaultType,\n defaultValue: defaultValue as number[],\n logicalType,\n type: bufferType,\n normalized: bufferType.includes('norm'),\n size: this.size,\n bytesPerElement: defaultType.BYTES_PER_ELEMENT\n };\n this.state = {\n ...state,\n externalBuffer: null,\n bufferAccessor: this.settings,\n allocatedValue: null,\n numInstances: 0,\n bounds: null,\n constant: false\n };\n }\n /* eslint-enable max-statements */\n\n get isConstant(): boolean {\n return this.state.constant;\n }\n\n get buffer(): Buffer {\n return this._buffer!;\n }\n\n get byteOffset(): number {\n const accessor = this.getAccessor();\n if (accessor.vertexOffset) {\n return accessor.vertexOffset * getStride(accessor);\n }\n return 0;\n }\n\n get numInstances(): number {\n return this.state.numInstances;\n }\n\n set numInstances(n: number) {\n this.state.numInstances = n;\n }\n\n delete(): void {\n if (this._buffer) {\n this._buffer.delete();\n this._buffer = null;\n }\n typedArrayManager.release(this.state.allocatedValue);\n }\n\n getBuffer(): Buffer | null {\n if (this.state.constant) {\n return null;\n }\n return this.state.externalBuffer || this._buffer;\n }\n\n getValue(\n attributeName: string = this.id,\n options: Partial | null = null\n ): Record {\n const result: Record = {};\n if (this.state.constant) {\n const value = this.value as TypedArray;\n if (options) {\n const shaderAttributeDef = resolveShaderAttribute(this.getAccessor(), options);\n const offset = shaderAttributeDef.offset / value.BYTES_PER_ELEMENT;\n const size = shaderAttributeDef.size || this.size;\n result[attributeName] = value.subarray(offset, offset + size);\n } else {\n result[attributeName] = value;\n }\n } else {\n result[attributeName] = this.getBuffer();\n }\n if (this.doublePrecision) {\n if (this.value instanceof Float64Array) {\n result[`${attributeName}64Low`] = result[attributeName];\n } else {\n // Disable fp64 low part\n result[`${attributeName}64Low`] = new Float32Array(this.size);\n }\n }\n return result;\n }\n\n protected _getBufferLayout(\n attributeName: string = this.id,\n options: Partial | null = null\n ): BufferLayout {\n const accessor = this.getAccessor();\n const attributes: (BufferAttributeLayout | null)[] = [];\n const result: BufferLayout = {\n name: this.id,\n byteStride: getStride(accessor)\n };\n\n if (this.doublePrecision) {\n const doubleShaderAttributeDefs = resolveDoublePrecisionShaderAttributes(\n accessor,\n options || {}\n );\n attributes.push(\n getBufferAttributeLayout(\n attributeName,\n {...accessor, ...doubleShaderAttributeDefs.high},\n this.device.type\n ),\n getBufferAttributeLayout(\n `${attributeName}64Low`,\n {\n ...accessor,\n ...doubleShaderAttributeDefs.low\n },\n this.device.type\n )\n );\n } else if (options) {\n const shaderAttributeDef = resolveShaderAttribute(accessor, options);\n attributes.push(\n getBufferAttributeLayout(\n attributeName,\n {...accessor, ...shaderAttributeDef},\n this.device.type\n )\n );\n } else {\n attributes.push(getBufferAttributeLayout(attributeName, accessor, this.device.type));\n }\n result.attributes = attributes.filter(Boolean) as BufferAttributeLayout[];\n return result;\n }\n\n setAccessor(accessor: DataColumnSettings) {\n this.state.bufferAccessor = accessor;\n }\n\n getAccessor(): DataColumnSettings {\n return this.state.bufferAccessor;\n }\n\n // Returns [min: Array(size), max: Array(size)]\n /* eslint-disable max-depth */\n getBounds(): [number[], number[]] | null {\n if (this.state.bounds) {\n return this.state.bounds;\n }\n let result: [number[], number[]] | null = null;\n if (this.state.constant && this.value) {\n const min = Array.from(this.value);\n result = [min, min];\n } else {\n const {value, numInstances, size} = this;\n const len = numInstances * size;\n if (value && len && value.length >= len) {\n const min = new Array(size).fill(Infinity);\n const max = new Array(size).fill(-Infinity);\n for (let i = 0; i < len; ) {\n for (let j = 0; j < size; j++) {\n const v = value[i++];\n if (v < min[j]) min[j] = v;\n if (v > max[j]) max[j] = v;\n }\n }\n result = [min, max];\n }\n }\n this.state.bounds = result;\n return result;\n }\n\n // returns true if success\n // eslint-disable-next-line max-statements\n setData(\n data:\n | TypedArray\n | Buffer\n | ({\n constant?: boolean;\n value?: NumericArray;\n buffer?: Buffer;\n /** Set to `true` if supplying float values to a unorm attribute */\n normalized?: boolean;\n } & Partial)\n ): boolean {\n const {state} = this;\n\n let opts: {\n constant?: boolean;\n value?: NumericArray;\n buffer?: Buffer;\n } & Partial;\n if (ArrayBuffer.isView(data)) {\n opts = {value: data};\n } else if (data instanceof Buffer) {\n opts = {buffer: data};\n } else {\n opts = data;\n }\n\n const accessor: DataColumnSettings = {...this.settings, ...opts};\n\n if (ArrayBuffer.isView(opts.value)) {\n if (!opts.type) {\n // Deduce data type\n const is64Bit = this.doublePrecision && opts.value instanceof Float64Array;\n if (is64Bit) {\n accessor.type = 'float32';\n } else {\n const type = dataTypeFromTypedArray(opts.value);\n // (lint wants to remove the cast)\n // eslint-disable-next-line\n accessor.type = (accessor.normalized ? type.replace('int', 'norm') : type) as DataType;\n }\n }\n accessor.bytesPerElement = opts.value.BYTES_PER_ELEMENT;\n accessor.stride = getStride(accessor);\n }\n\n state.bounds = null; // clear cached bounds\n\n if (opts.constant) {\n // set constant\n let value = opts.value;\n value = this._normalizeValue(value, [], 0);\n if (this.settings.normalized) {\n value = this.normalizeConstant(value);\n }\n const hasChanged = !state.constant || !this._areValuesEqual(value, this.value);\n\n if (!hasChanged) {\n return false;\n }\n state.externalBuffer = null;\n state.constant = true;\n this.value = ArrayBuffer.isView(value) ? value : new Float32Array(value);\n } else if (opts.buffer) {\n const buffer = opts.buffer;\n state.externalBuffer = buffer;\n state.constant = false;\n this.value = opts.value || null;\n } else if (opts.value) {\n this._checkExternalBuffer(opts);\n\n let value = opts.value as TypedArray;\n state.externalBuffer = null;\n state.constant = false;\n this.value = value;\n\n let {buffer} = this;\n const stride = getStride(accessor);\n const byteOffset = (accessor.vertexOffset || 0) * stride;\n\n if (this.doublePrecision && value instanceof Float64Array) {\n value = toDoublePrecisionArray(value, accessor);\n }\n if (this.settings.isIndexed) {\n const ArrayType = this.settings.defaultType;\n if (value.constructor !== ArrayType) {\n // Cast the index buffer to expected type\n value = new ArrayType(value);\n }\n }\n\n // A small over allocation is used as safety margin\n // Shader attributes may try to access this buffer with bigger offsets\n const requiredBufferSize = value.byteLength + byteOffset + stride * 2;\n if (!buffer || buffer.byteLength < requiredBufferSize) {\n buffer = this._createBuffer(requiredBufferSize);\n }\n\n buffer.write(value, byteOffset);\n }\n\n this.setAccessor(accessor);\n\n return true;\n }\n\n updateSubBuffer(\n opts: {\n startOffset?: number;\n endOffset?: number;\n } = {}\n ): void {\n this.state.bounds = null; // clear cached bounds\n\n const value = this.value as TypedArray;\n const {startOffset = 0, endOffset} = opts;\n this.buffer.write(\n this.doublePrecision && value instanceof Float64Array\n ? toDoublePrecisionArray(value, {\n size: this.size,\n startIndex: startOffset,\n endIndex: endOffset\n })\n : value.subarray(startOffset, endOffset),\n startOffset * value.BYTES_PER_ELEMENT + this.byteOffset\n );\n }\n\n allocate(numInstances: number, copy: boolean = false): boolean {\n const {state} = this;\n const oldValue = state.allocatedValue;\n\n // Allocate at least one element to ensure a valid buffer\n const value = typedArrayManager.allocate(oldValue, numInstances + 1, {\n size: this.size,\n type: this.settings.defaultType,\n copy\n });\n\n this.value = value;\n\n const {byteOffset} = this;\n let {buffer} = this;\n\n if (!buffer || buffer.byteLength < value.byteLength + byteOffset) {\n buffer = this._createBuffer(value.byteLength + byteOffset);\n if (copy && oldValue) {\n // Upload the full existing attribute value to the GPU, so that updateBuffer\n // can choose to only update a partial range.\n // TODO - copy old buffer to new buffer on the GPU\n buffer.write(\n oldValue instanceof Float64Array ? toDoublePrecisionArray(oldValue, this) : oldValue,\n byteOffset\n );\n }\n }\n\n state.allocatedValue = value;\n state.constant = false;\n state.externalBuffer = null;\n this.setAccessor(this.settings);\n return true;\n }\n\n // PRIVATE HELPER METHODS\n protected _checkExternalBuffer(opts: {value?: NumericArray; normalized?: boolean}): void {\n const {value} = opts;\n if (!ArrayBuffer.isView(value)) {\n throw new Error(`Attribute ${this.id} value is not TypedArray`);\n }\n const ArrayType = this.settings.defaultType;\n\n let illegalArrayType = false;\n if (this.doublePrecision) {\n // not 32bit or 64bit\n illegalArrayType = value.BYTES_PER_ELEMENT < 4;\n }\n if (illegalArrayType) {\n throw new Error(`Attribute ${this.id} does not support ${value.constructor.name}`);\n }\n if (!(value instanceof ArrayType) && this.settings.normalized && !('normalized' in opts)) {\n log.warn(`Attribute ${this.id} is normalized`)();\n }\n }\n\n // https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/vertexAttribPointer\n normalizeConstant(value: NumericArray): NumericArray {\n /* eslint-disable complexity */\n switch (this.settings.type) {\n case 'snorm8':\n // normalize [-128, 127] to [-1, 1]\n return new Float32Array(value).map(x => ((x + 128) / 255) * 2 - 1);\n\n case 'snorm16':\n // normalize [-32768, 32767] to [-1, 1]\n return new Float32Array(value).map(x => ((x + 32768) / 65535) * 2 - 1);\n\n case 'unorm8':\n // normalize [0, 255] to [0, 1]\n return new Float32Array(value).map(x => x / 255);\n\n case 'unorm16':\n // normalize [0, 65535] to [0, 1]\n return new Float32Array(value).map(x => x / 65535);\n\n default:\n // No normalization for gl.FLOAT and gl.HALF_FLOAT\n return value;\n }\n }\n\n /* check user supplied values and apply fallback */\n protected _normalizeValue(value: any, out: NumericArray, start: number): NumericArray {\n const {defaultValue, size} = this.settings;\n\n if (Number.isFinite(value)) {\n out[start] = value;\n return out;\n }\n if (!value) {\n let i = size;\n while (--i >= 0) {\n out[start + i] = defaultValue[i];\n }\n return out;\n }\n\n // Important - switch cases are 5x more performant than a for loop!\n /* eslint-disable no-fallthrough, default-case */\n switch (size) {\n case 4:\n out[start + 3] = Number.isFinite(value[3]) ? value[3] : defaultValue[3];\n case 3:\n out[start + 2] = Number.isFinite(value[2]) ? value[2] : defaultValue[2];\n case 2:\n out[start + 1] = Number.isFinite(value[1]) ? value[1] : defaultValue[1];\n case 1:\n out[start + 0] = Number.isFinite(value[0]) ? value[0] : defaultValue[0];\n break;\n\n default:\n // In the rare case where the attribute size > 4, do it the slow way\n // This is used for e.g. transform matrices\n let i = size;\n while (--i >= 0) {\n out[start + i] = Number.isFinite(value[i]) ? value[i] : defaultValue[i];\n }\n }\n\n return out;\n }\n\n protected _areValuesEqual(value1: any, value2: any): boolean {\n if (!value1 || !value2) {\n return false;\n }\n const {size} = this;\n for (let i = 0; i < size; i++) {\n if (value1[i] !== value2[i]) {\n return false;\n }\n }\n return true;\n }\n\n protected _createBuffer(byteLength: number): Buffer {\n if (this._buffer) {\n this._buffer.destroy();\n }\n\n const {isIndexed, type} = this.settings;\n this._buffer = this.device.createBuffer({\n ...this._buffer?.props,\n id: this.id,\n // TODO(ibgreen) - WebGPU requires COPY_DST and COPY_SRC to allow write / read\n usage: (isIndexed ? Buffer.INDEX : Buffer.VERTEX) | Buffer.COPY_DST,\n indexType: isIndexed ? (type as 'uint16' | 'uint32') : undefined,\n byteLength\n });\n\n return this._buffer;\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {dataTypeDecoder, getTypedArrayConstructor} from '@luma.gl/core';\nimport type {BufferAttributeLayout, VertexFormat} from '@luma.gl/core';\nimport type {TypedArrayConstructor} from '../../types/types';\nimport type {BufferAccessor, DataColumnSettings, LogicalDataType} from './data-column';\n\nexport function typedArrayFromDataType(type: LogicalDataType): TypedArrayConstructor {\n // Sorted in some order of likelihood to reduce amount of comparisons\n switch (type) {\n case 'float64':\n return Float64Array;\n case 'uint8':\n case 'unorm8':\n return Uint8ClampedArray;\n default:\n return getTypedArrayConstructor(type);\n }\n}\n\nexport const dataTypeFromTypedArray = dataTypeDecoder.getDataType.bind(dataTypeDecoder);\n\nexport function getBufferAttributeLayout(\n name: string,\n accessor: BufferAccessor,\n deviceType: 'webgpu' | 'wegbgl' | string\n): BufferAttributeLayout | null {\n if ((accessor.size as number) > 4) {\n // Definitely not valid. TODO - stricter validation?\n return null;\n }\n // TODO(ibgreen): WebGPU change. Currently we always use normalized 8 bit integers\n const type = deviceType === 'webgpu' && accessor.type === 'uint8' ? 'unorm8' : accessor.type;\n return {\n attribute: name,\n // @ts-expect-error Not all combinations are valid vertex formats; it's up to DataColumn to ensure\n format:\n (accessor.size as number) > 1 ? (`${type}x${accessor.size}` as VertexFormat) : accessor.type,\n byteOffset: accessor.offset || 0\n // Note stride is set on the top level\n };\n}\n\nexport function getStride(accessor: DataColumnSettings): number {\n return accessor.stride || accessor.size * accessor.bytesPerElement;\n}\n\nexport function bufferLayoutEqual(\n accessor1: DataColumnSettings,\n accessor2: DataColumnSettings\n) {\n return (\n accessor1.type === accessor2.type &&\n accessor1.size === accessor2.size &&\n getStride(accessor1) === getStride(accessor2) &&\n (accessor1.offset || 0) === (accessor2.offset || 0)\n );\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {NumericArray} from '../types/types';\nimport type {AccessorFunction} from '../types/layer-props';\n\nconst EMPTY_ARRAY = [];\nconst placeholderArray = [];\n\n/*\n * Create an Iterable\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols\n * and a \"context\" tracker from the given data\n */\nexport function createIterable(\n data,\n startRow = 0,\n endRow = Infinity\n): {\n iterable: Iterable;\n objectInfo: {\n index: number;\n data: any;\n target: any[];\n };\n} {\n let iterable: Iterable = EMPTY_ARRAY;\n\n const objectInfo = {\n index: -1,\n data,\n // visitor can optionally utilize this to avoid constructing a new array for every object\n target: []\n };\n\n if (!data) {\n iterable = EMPTY_ARRAY;\n } else if (typeof data[Symbol.iterator] === 'function') {\n // data is already an iterable\n iterable = data;\n } else if (data.length > 0) {\n placeholderArray.length = data.length;\n iterable = placeholderArray;\n }\n\n if (startRow > 0 || Number.isFinite(endRow)) {\n iterable = (Array.isArray(iterable) ? iterable : Array.from(iterable)).slice(startRow, endRow);\n objectInfo.index = startRow - 1;\n }\n\n return {iterable, objectInfo};\n}\n\n/*\n * Returns true if data is an async iterable object\n */\nexport function isAsyncIterable(data): boolean {\n return data && data[Symbol.asyncIterator];\n}\n\n/*\n * Create an accessor function from a flat buffer that yields the value at each object index\n */\nexport function getAccessorFromBuffer(\n typedArray,\n options: {\n size: number;\n stride?: number;\n offset?: number;\n startIndices?: NumericArray;\n nested?: boolean;\n }\n): AccessorFunction {\n const {size, stride, offset, startIndices, nested} = options;\n const bytesPerElement = typedArray.BYTES_PER_ELEMENT;\n const elementStride = stride ? stride / bytesPerElement : size;\n const elementOffset = offset ? offset / bytesPerElement : 0;\n const vertexCount = Math.floor((typedArray.length - elementOffset) / elementStride);\n\n return (_, {index, target}) => {\n if (!startIndices) {\n const sourceIndex = index * elementStride + elementOffset;\n for (let j = 0; j < size; j++) {\n target[j] = typedArray[sourceIndex + j];\n }\n return target;\n }\n const startIndex = startIndices[index];\n const endIndex = startIndices[index + 1] || vertexCount;\n let result;\n\n if (nested) {\n result = new Array(endIndex - startIndex);\n for (let i = startIndex; i < endIndex; i++) {\n const sourceIndex = i * elementStride + elementOffset;\n target = new Array(size);\n for (let j = 0; j < size; j++) {\n target[j] = typedArray[sourceIndex + j];\n }\n result[i - startIndex] = target;\n }\n } else if (elementStride === size) {\n result = typedArray.subarray(\n startIndex * size + elementOffset,\n endIndex * size + elementOffset\n );\n } else {\n result = new typedArray.constructor((endIndex - startIndex) * size);\n let targetIndex = 0;\n for (let i = startIndex; i < endIndex; i++) {\n const sourceIndex = i * elementStride + elementOffset;\n for (let j = 0; j < size; j++) {\n result[targetIndex++] = typedArray[sourceIndex + j];\n }\n }\n }\n\n return result;\n };\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/*\n * range (Array)\n * + start (Number) - the start index (incl.)\n * + end (Number) - the end index (excl.)\n * rangeList (Array) - array of sorted, combined ranges\n */\nexport const EMPTY = [];\nexport const FULL = [[0, Infinity]];\n\n// Insert a range into a range collection\nexport function add(rangeList, range) {\n // Noop if range collection already covers all\n if (rangeList === FULL) {\n return rangeList;\n }\n\n // Validate the input range\n if (range[0] < 0) {\n range[0] = 0;\n }\n if (range[0] >= range[1]) {\n return rangeList;\n }\n\n // TODO - split off to tree-shakable Range class\n const newRangeList: number[] = [];\n const len = rangeList.length;\n let insertPosition = 0;\n\n for (let i = 0; i < len; i++) {\n const range0 = rangeList[i];\n\n if (range0[1] < range[0]) {\n // the current range is to the left of the new range\n newRangeList.push(range0);\n insertPosition = i + 1;\n } else if (range0[0] > range[1]) {\n // the current range is to the right of the new range\n newRangeList.push(range0);\n } else {\n range = [Math.min(range0[0], range[0]), Math.max(range0[1], range[1])];\n }\n }\n newRangeList.splice(insertPosition, 0, range);\n return newRangeList;\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {NumericArray} from '../../types/types';\n\nexport interface TransitionSettings {\n type: string;\n /** Callback to get the value that the entering vertices are transitioning from. */\n enter?: (toValue: NumericArray, chunk?: NumericArray) => NumericArray;\n /** Callback when the transition is started */\n onStart?: () => void;\n /** Callback when the transition is done */\n onEnd?: () => void;\n /** Callback when the transition is interrupted */\n onInterrupt?: () => void;\n}\n\nexport type InterpolationTransitionSettings = TransitionSettings & {\n type?: 'interpolation';\n /** Duration of the transition animation, in milliseconds */\n duration: number;\n /** Easing function that maps a value from [0, 1] to [0, 1], see [http://easings.net/](http://easings.net/) */\n easing?: (t: number) => number;\n};\n\nexport type SpringTransitionSettings = TransitionSettings & {\n type: 'spring';\n /** \"Tension\" factor for the spring */\n stiffness: number;\n /** \"Friction\" factor that counteracts the spring's acceleration */\n damping: number;\n};\n\nconst DEFAULT_TRANSITION_SETTINGS = {\n interpolation: {\n duration: 0,\n easing: t => t\n },\n spring: {\n stiffness: 0.05,\n damping: 0.5\n }\n};\n\nexport function normalizeTransitionSettings(\n userSettings: number | InterpolationTransitionSettings | SpringTransitionSettings,\n layerSettings?: boolean | Partial\n): TransitionSettings | null {\n if (!userSettings) {\n return null;\n }\n if (Number.isFinite(userSettings)) {\n userSettings = {type: 'interpolation', duration: userSettings as number};\n }\n const type = (userSettings as TransitionSettings).type || 'interpolation';\n return {\n ...DEFAULT_TRANSITION_SETTINGS[type],\n ...(layerSettings as TransitionSettings),\n ...(userSettings as TransitionSettings),\n type\n };\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/* eslint-disable complexity */\nimport DataColumn, {\n DataColumnOptions,\n ShaderAttributeOptions,\n BufferAccessor,\n DataColumnSettings\n} from './data-column';\nimport assert from '../../utils/assert';\nimport {createIterable, getAccessorFromBuffer} from '../../utils/iterable-utils';\nimport {fillArray} from '../../utils/flatten';\nimport * as range from '../../utils/range';\nimport {bufferLayoutEqual} from './gl-utils';\nimport {normalizeTransitionSettings, TransitionSettings} from './transition-settings';\nimport type {Device, Buffer, BufferLayout} from '@luma.gl/core';\n\nimport type {NumericArray, TypedArray} from '../../types/types';\n\nexport type Accessor = (\n object: DataType,\n context: {\n data: any;\n index: number;\n target: number[];\n }\n) => ReturnType;\n\nexport type Updater = (\n attribute: Attribute,\n {\n data,\n startRow,\n endRow,\n props,\n numInstances\n }: {\n data: any;\n startRow: number;\n endRow: number;\n props: any;\n numInstances: number;\n }\n) => void;\n\nexport type AttributeOptions = DataColumnOptions<{\n transition?: boolean | Partial;\n stepMode?: 'vertex' | 'instance' | 'dynamic';\n noAlloc?: boolean;\n update?: Updater;\n accessor?: Accessor | string | string[];\n transform?: (value: any) => any;\n shaderAttributes?: Record>;\n}>;\n\nexport type BinaryAttribute = Partial & {value?: TypedArray; buffer?: Buffer};\n\ntype AttributeInternalState = {\n startIndices: NumericArray | null;\n /** Legacy: external binary supplied via attribute name */\n lastExternalBuffer: TypedArray | Buffer | BinaryAttribute | null;\n /** External binary supplied via accessor name */\n binaryValue: TypedArray | Buffer | BinaryAttribute | null;\n binaryAccessor: Accessor | null;\n needsUpdate: string | boolean;\n needsRedraw: string | boolean;\n layoutChanged: boolean;\n updateRanges: number[][];\n};\n\nexport default class Attribute extends DataColumn {\n /** Legacy approach to set attribute value - read `isConstant` instead for attribute state */\n constant: boolean = false;\n\n constructor(device: Device, opts: AttributeOptions) {\n super(device, opts, {\n startIndices: null,\n lastExternalBuffer: null,\n binaryValue: null,\n binaryAccessor: null,\n needsUpdate: true,\n needsRedraw: false,\n layoutChanged: false,\n updateRanges: range.FULL\n });\n\n // eslint-disable-next-line\n this.settings.update = opts.update || (opts.accessor ? this._autoUpdater : undefined);\n\n Object.seal(this.settings);\n Object.seal(this.state);\n\n // Check all fields and generate helpful error messages\n this._validateAttributeUpdaters();\n }\n\n get startIndices(): NumericArray | null {\n return this.state.startIndices;\n }\n\n set startIndices(layout: NumericArray | null) {\n this.state.startIndices = layout;\n }\n\n needsUpdate(): string | boolean {\n return this.state.needsUpdate;\n }\n\n needsRedraw({clearChangedFlags = false}: {clearChangedFlags?: boolean} = {}): string | boolean {\n const needsRedraw = this.state.needsRedraw;\n this.state.needsRedraw = needsRedraw && !clearChangedFlags;\n return needsRedraw;\n }\n\n layoutChanged(): boolean {\n return this.state.layoutChanged;\n }\n\n setAccessor(accessor: DataColumnSettings) {\n this.state.layoutChanged ||= !bufferLayoutEqual(accessor, this.getAccessor());\n super.setAccessor(accessor);\n }\n\n getUpdateTriggers(): string[] {\n const {accessor} = this.settings;\n\n // Backards compatibility: allow attribute name to be used as update trigger key\n return [this.id].concat((typeof accessor !== 'function' && accessor) || []);\n }\n\n supportsTransition(): boolean {\n return Boolean(this.settings.transition);\n }\n\n // Resolve transition settings object if transition is enabled, otherwise `null`\n getTransitionSetting(opts: Record): TransitionSettings | null {\n if (!opts || !this.supportsTransition()) {\n return null;\n }\n const {accessor} = this.settings;\n // TODO: have the layer resolve these transition settings itself?\n const layerSettings = this.settings.transition;\n // these are the transition settings passed in by the user\n const userSettings = Array.isArray(accessor)\n ? // @ts-ignore\n opts[accessor.find(a => opts[a])]\n : // @ts-ignore\n opts[accessor];\n\n // Shorthand: use duration instead of parameter object\n return normalizeTransitionSettings(userSettings, layerSettings);\n }\n\n setNeedsUpdate(reason: string = this.id, dataRange?: {startRow?: number; endRow?: number}): void {\n this.state.needsUpdate = this.state.needsUpdate || reason;\n this.setNeedsRedraw(reason);\n if (dataRange) {\n const {startRow = 0, endRow = Infinity} = dataRange;\n this.state.updateRanges = range.add(this.state.updateRanges, [startRow, endRow]);\n } else {\n this.state.updateRanges = range.FULL;\n }\n }\n\n clearNeedsUpdate(): void {\n this.state.needsUpdate = false;\n this.state.updateRanges = range.EMPTY;\n }\n\n setNeedsRedraw(reason: string = this.id): void {\n this.state.needsRedraw = this.state.needsRedraw || reason;\n }\n\n allocate(numInstances: number): boolean {\n const {state, settings} = this;\n\n if (settings.noAlloc) {\n // Data is provided through a Buffer object.\n return false;\n }\n\n if (settings.update) {\n super.allocate(numInstances, state.updateRanges !== range.FULL);\n return true;\n }\n\n return false;\n }\n\n updateBuffer({\n numInstances,\n data,\n props,\n context\n }: {\n numInstances: number;\n data: any;\n props: any;\n context: any;\n }): boolean {\n if (!this.needsUpdate()) {\n return false;\n }\n\n const {\n state: {updateRanges},\n settings: {update, noAlloc}\n } = this;\n\n let updated = true;\n if (update) {\n // Custom updater - typically for non-instanced layers\n for (const [startRow, endRow] of updateRanges) {\n update.call(context, this, {data, startRow, endRow, props, numInstances});\n }\n if (!this.value) {\n // no value was assigned during update\n } else if (\n this.constant ||\n !this.buffer ||\n this.buffer.byteLength < (this.value as TypedArray).byteLength + this.byteOffset\n ) {\n if (this.constant) {\n // Route constant updater output through the same path used by constant accessors\n // so WebGPU can materialize a real buffer while WebGL keeps a constant attribute.\n this.setConstantValue(context, this.value);\n } else {\n this.setData({\n value: this.value,\n constant: this.constant\n });\n }\n // Setting attribute.constant in updater is a legacy approach that interferes with allocation in the next cycle\n // Respect it here but reset after use\n this.constant = false;\n } else {\n for (const [startRow, endRow] of updateRanges) {\n const startOffset = Number.isFinite(startRow) ? this.getVertexOffset(startRow) : 0;\n const endOffset = Number.isFinite(endRow)\n ? this.getVertexOffset(endRow)\n : noAlloc || !Number.isFinite(numInstances)\n ? this.value.length\n : numInstances * this.size;\n\n super.updateSubBuffer({startOffset, endOffset});\n }\n }\n this._checkAttributeArray();\n } else {\n updated = false;\n }\n\n this.clearNeedsUpdate();\n this.setNeedsRedraw();\n\n return updated;\n }\n\n // Use generic value\n // Returns true if successful\n setConstantValue(context: any, value?: any): boolean {\n if (value === undefined || typeof value === 'function') {\n return false;\n }\n\n const transformedValue =\n this.settings.transform && context ? this.settings.transform.call(context, value) : value;\n\n if (this.device.type === 'webgpu') {\n // WebGPU has no equivalent of WebGL constant vertex attributes, so we expand the\n // constant into a full per-instance buffer before passing it to luma.gl.\n return this.setConstantBufferValue(transformedValue, this.numInstances);\n }\n\n // WebGL can bind the normalized/transformed value directly as a constant attribute.\n const hasChanged = this.setData({constant: true, value: transformedValue});\n\n if (hasChanged) {\n this.setNeedsRedraw();\n }\n this.clearNeedsUpdate();\n return true;\n }\n\n setConstantBufferValue(value: any, numInstances: number): boolean {\n const ArrayType = this.settings.defaultType;\n const constantValue = this._normalizeValue(value, new ArrayType(this.size), 0) as TypedArray;\n if (this._hasConstantBufferValue(constantValue, numInstances)) {\n // The emulated buffer already matches this constant, so avoid a redundant upload.\n this.constant = false;\n this.clearNeedsUpdate();\n return false;\n }\n\n const repeatedValue = new ArrayType(Math.max(numInstances, 1) * this.size);\n\n for (let i = 0; i < repeatedValue.length; i += this.size) {\n repeatedValue.set(constantValue, i);\n }\n\n const hasChanged = this.setData({value: repeatedValue});\n this.constant = false;\n this.clearNeedsUpdate();\n\n if (hasChanged) {\n this.setNeedsRedraw();\n }\n\n return hasChanged;\n }\n\n private _hasConstantBufferValue(value: NumericArray, numInstances: number): boolean {\n const currentValue = this.value;\n const expectedLength = Math.max(numInstances, 1) * this.size;\n\n if (\n !ArrayBuffer.isView(currentValue) ||\n currentValue.length !== expectedLength ||\n currentValue.length % this.size !== 0\n ) {\n return false;\n }\n\n for (let i = 0; i < currentValue.length; i += this.size) {\n for (let j = 0; j < this.size; j++) {\n if (currentValue[i + j] !== value[j]) {\n return false;\n }\n }\n }\n\n return true;\n }\n\n // Use external buffer\n // Returns true if successful\n // eslint-disable-next-line max-statements\n setExternalBuffer(buffer?: TypedArray | Buffer | BinaryAttribute): boolean {\n const {state} = this;\n\n if (!buffer) {\n state.lastExternalBuffer = null;\n return false;\n }\n\n this.clearNeedsUpdate();\n\n if (state.lastExternalBuffer === buffer) {\n return true;\n }\n state.lastExternalBuffer = buffer;\n this.setNeedsRedraw();\n this.setData(buffer);\n return true;\n }\n\n // Binary value is a typed array packed from mapping the source data with the accessor\n // If the returned value from the accessor is the same as the attribute value, set it directly\n // Otherwise use the auto updater for transform/normalization\n setBinaryValue(\n buffer?: TypedArray | Buffer | BinaryAttribute,\n startIndices: NumericArray | null = null\n ): boolean {\n const {state, settings} = this;\n\n if (!buffer) {\n state.binaryValue = null;\n state.binaryAccessor = null;\n return false;\n }\n\n if (settings.noAlloc) {\n // Let the layer handle this\n return false;\n }\n\n if (state.binaryValue === buffer) {\n this.clearNeedsUpdate();\n return true;\n }\n state.binaryValue = buffer;\n this.setNeedsRedraw();\n\n const needsUpdate = settings.transform || startIndices !== this.startIndices;\n\n if (needsUpdate) {\n if (ArrayBuffer.isView(buffer)) {\n buffer = {value: buffer};\n }\n const binaryValue = buffer as BinaryAttribute;\n assert(ArrayBuffer.isView(binaryValue.value), `invalid ${settings.accessor}`);\n const needsNormalize = Boolean(binaryValue.size) && binaryValue.size !== this.size;\n\n state.binaryAccessor = getAccessorFromBuffer(binaryValue.value, {\n size: binaryValue.size || this.size,\n stride: binaryValue.stride,\n offset: binaryValue.offset,\n startIndices: startIndices as NumericArray,\n nested: needsNormalize\n });\n // Fall through to auto updater\n return false;\n }\n\n this.clearNeedsUpdate();\n this.setData(buffer);\n return true;\n }\n\n getVertexOffset(row: number): number {\n const {startIndices} = this;\n const vertexIndex = startIndices\n ? row < startIndices.length\n ? startIndices[row]\n : this.numInstances\n : row;\n return vertexIndex * this.size;\n }\n\n getValue(): Record {\n const shaderAttributeDefs = this.settings.shaderAttributes;\n const result = super.getValue();\n if (!shaderAttributeDefs) {\n return result;\n }\n for (const shaderAttributeName in shaderAttributeDefs) {\n Object.assign(\n result,\n super.getValue(shaderAttributeName, shaderAttributeDefs[shaderAttributeName])\n );\n }\n return result;\n }\n\n /** Generate WebGPU-style buffer layout descriptor from this attribute */\n getBufferLayout(\n /** A luma.gl Model-shaped object that supplies additional hint to attribute resolution */\n modelInfo?: {isInstanced?: boolean}\n ): BufferLayout {\n // Clear change flag\n this.state.layoutChanged = false;\n\n const shaderAttributeDefs = this.settings.shaderAttributes;\n const result: BufferLayout = super._getBufferLayout();\n const {stepMode} = this.settings;\n if (stepMode === 'dynamic') {\n // If model info is provided, use isInstanced flag to determine step mode\n // If no model info is provided, assume it's an instanced model (most common use case)\n result.stepMode = modelInfo ? (modelInfo.isInstanced ? 'instance' : 'vertex') : 'instance';\n } else {\n result.stepMode = stepMode ?? 'vertex';\n }\n\n if (!shaderAttributeDefs) {\n return result;\n }\n\n for (const shaderAttributeName in shaderAttributeDefs) {\n const map = super._getBufferLayout(\n shaderAttributeName,\n shaderAttributeDefs[shaderAttributeName]\n );\n // @ts-ignore\n result.attributes.push(...map.attributes);\n }\n return result;\n }\n\n /* eslint-disable max-depth, max-statements */\n private _autoUpdater(\n attribute: Attribute,\n {\n data,\n startRow,\n endRow,\n props,\n numInstances\n }: {\n data: any;\n startRow: number;\n endRow: number;\n props: any;\n numInstances: number;\n }\n ): void {\n const {settings, state, value, size, startIndices} = attribute;\n\n const {accessor, transform} = settings;\n const accessorFunc: Accessor =\n state.binaryAccessor ||\n // @ts-ignore\n (typeof accessor === 'function' ? accessor : props[accessor]);\n assert(typeof accessorFunc === 'function', `accessor \"${accessor}\" is not a function`);\n\n let i = attribute.getVertexOffset(startRow);\n const {iterable, objectInfo} = createIterable(data, startRow, endRow);\n for (const object of iterable) {\n objectInfo.index++;\n\n let objectValue = accessorFunc(object, objectInfo);\n if (transform) {\n // transform callbacks could be bound to a particular layer instance.\n // always point `this` to the current layer.\n objectValue = transform.call(this, objectValue);\n }\n\n if (startIndices) {\n const numVertices =\n (objectInfo.index < startIndices.length - 1\n ? startIndices[objectInfo.index + 1]\n : numInstances) - startIndices[objectInfo.index];\n if (objectValue && Array.isArray(objectValue[0])) {\n let startIndex = i;\n for (const item of objectValue) {\n attribute._normalizeValue(item, value as TypedArray, startIndex);\n startIndex += size;\n }\n } else if (objectValue && objectValue.length > size) {\n (value as TypedArray).set(objectValue, i);\n } else {\n attribute._normalizeValue(objectValue, objectInfo.target, 0);\n fillArray({\n target: value,\n source: objectInfo.target,\n start: i,\n count: numVertices\n });\n }\n i += numVertices * size;\n } else {\n attribute._normalizeValue(objectValue, value as TypedArray, i);\n i += size;\n }\n }\n }\n /* eslint-enable max-depth, max-statements */\n\n // Validate deck.gl level fields\n private _validateAttributeUpdaters() {\n const {settings} = this;\n\n // Check that 'update' is a valid function\n const hasUpdater = settings.noAlloc || typeof settings.update === 'function';\n if (!hasUpdater) {\n throw new Error(`Attribute ${this.id} missing update or accessor`);\n }\n }\n\n // check that the first few elements of the attribute are reasonable\n /* eslint-disable no-fallthrough */\n private _checkAttributeArray() {\n const {value} = this;\n const limit = Math.min(4, this.size);\n if (value && value.length >= limit) {\n let valid = true;\n switch (limit) {\n case 4:\n valid = valid && Number.isFinite(value[3]);\n case 3:\n valid = valid && Number.isFinite(value[2]);\n case 2:\n valid = valid && Number.isFinite(value[1]);\n case 1:\n valid = valid && Number.isFinite(value[0]);\n break;\n default:\n valid = false;\n }\n\n if (!valid) {\n throw new Error(`Illegal attribute generated for ${this.id}`);\n }\n }\n }\n /* eslint-enable no-fallthrough */\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {NumericArray, TypedArray} from '../types/types';\n\n/*\n * Helper function for padArray\n */\nfunction padArrayChunk(options: {\n /** original data */\n source: TypedArray;\n /** output data */\n target: TypedArray;\n /** length per datum */\n size: number;\n /** callback to get new data when source is short */\n getData: (index: number, context: NumericArray) => NumericArray;\n /** start index */\n start?: number;\n /** end index */\n end?: number;\n}): void {\n const {source, target, start = 0, size, getData} = options;\n const end = options.end || target.length;\n\n const sourceLength = source.length;\n const targetLength = end - start;\n\n if (sourceLength > targetLength) {\n target.set(source.subarray(0, targetLength), start);\n return;\n }\n\n target.set(source, start);\n\n if (!getData) {\n return;\n }\n\n // source is not large enough to fill target space, call `getData` to get filler data\n let i = sourceLength;\n while (i < targetLength) {\n const datum = getData(i, source);\n for (let j = 0; j < size; j++) {\n target[start + i] = datum[j] || 0;\n i++;\n }\n }\n}\n\n/*\n * The padArray function stretches a source array to the size of a target array.\n The arrays can have internal structures (like the attributes of PathLayer and\n SolidPolygonLayer), defined by the optional sourceStartIndices and targetStartIndices parameters.\n If the target array is larger, the getData callback is used to fill in the blanks.\n */\nexport function padArray({\n source,\n target,\n size,\n getData,\n sourceStartIndices,\n targetStartIndices\n}: {\n /** original data */\n source: TypedArray;\n /** output data */\n target: TypedArray;\n /** length per datum */\n size: number;\n /** callback to get new data when source is short */\n getData: (index: number, context: NumericArray) => NumericArray;\n /** subdivision of the original data in [object0StartIndex, object1StartIndex, ...] */\n sourceStartIndices?: NumericArray | null;\n /** subdivision of the output data in [object0StartIndex, object1StartIndex, ...] */\n targetStartIndices?: NumericArray | null;\n}): TypedArray {\n if (!sourceStartIndices || !targetStartIndices) {\n // Flat arrays\n padArrayChunk({\n source,\n target,\n size,\n getData\n });\n return target;\n }\n\n // Arrays have internal structure\n let sourceIndex = 0;\n let targetIndex = 0;\n const getChunkData = getData && ((i, chunk) => getData(i + targetIndex, chunk));\n\n const n = Math.min(sourceStartIndices.length, targetStartIndices.length);\n\n for (let i = 1; i < n; i++) {\n const nextSourceIndex = sourceStartIndices[i] * size;\n const nextTargetIndex = targetStartIndices[i] * size;\n\n padArrayChunk({\n source: source.subarray(sourceIndex, nextSourceIndex),\n target,\n start: targetIndex,\n end: nextTargetIndex,\n size,\n getData: getChunkData\n });\n\n sourceIndex = nextSourceIndex;\n targetIndex = nextTargetIndex;\n }\n\n if (targetIndex < target.length) {\n padArrayChunk({\n // @ts-ignore\n source: [],\n target,\n start: targetIndex,\n size,\n getData: getChunkData\n });\n }\n\n return target;\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device, Buffer, VertexFormat} from '@luma.gl/core';\nimport {padArray} from '../utils/array-utils';\nimport {NumericArray, TypedArray, TypedArrayConstructor} from '../types/types';\nimport Attribute from '../lib/attribute/attribute';\nimport {GL} from '@luma.gl/webgl/constants';\n\n/** Create a new empty attribute with the same settings: type, shader layout etc. */\nexport function cloneAttribute(attribute: Attribute): Attribute {\n // `attribute.settings` is the original options passed when constructing the attribute.\n // This ensures that we set the proper `doublePrecision` flag and shader attributes.\n const {device, settings, value} = attribute;\n const newAttribute = new Attribute(device, settings);\n // Placeholder value - necessary for generating the correct buffer layout\n newAttribute.setData({\n value: value instanceof Float64Array ? new Float64Array(0) : new Float32Array(0),\n normalized: settings.normalized\n });\n return newAttribute;\n}\n\n/** Returns the GLSL attribute type for the given number of float32 components. */\nexport function getAttributeTypeFromSize(size: number): string {\n switch (size) {\n case 1:\n return 'float';\n case 2:\n return 'vec2';\n case 3:\n return 'vec3';\n case 4:\n return 'vec4';\n default:\n throw new Error(`No defined attribute type for size \"${size}\"`);\n }\n}\n\n/** Returns the {@link VertexFormat} for the given number of float32 components. */\nexport function getFloat32VertexFormat(size: number): VertexFormat {\n switch (size) {\n case 1:\n return 'float32';\n case 2:\n return 'float32x2';\n case 3:\n return 'float32x3';\n case 4:\n return 'float32x4';\n default:\n throw new Error('invalid type size');\n }\n}\n\nexport function cycleBuffers(buffers: Buffer[]): void {\n buffers.push(buffers.shift() as Buffer);\n}\n\nexport function getAttributeBufferLength(attribute: Attribute, numInstances: number): number {\n const {doublePrecision, settings, value, size} = attribute;\n const multiplier = doublePrecision && value instanceof Float64Array ? 2 : 1;\n let maxVertexOffset = 0;\n const {shaderAttributes} = attribute.settings;\n if (shaderAttributes) {\n for (const shaderAttribute of Object.values(shaderAttributes)) {\n maxVertexOffset = Math.max(maxVertexOffset, shaderAttribute.vertexOffset ?? 0);\n }\n }\n return (\n (settings.noAlloc ? (value as NumericArray).length : (numInstances + maxVertexOffset) * size) *\n multiplier\n );\n}\n\nexport function matchBuffer({\n device,\n source,\n target\n}: {\n device: Device;\n source: Buffer;\n target?: Buffer;\n}): Buffer {\n if (!target || target.byteLength < source.byteLength) {\n target?.destroy();\n target = device.createBuffer({\n byteLength: source.byteLength,\n usage: source.usage\n });\n }\n return target;\n}\n\n/* eslint-disable complexity */\n// This helper is used when transitioning attributes from a set of values in one buffer layout\n// to a set of values in a different buffer layout. (Buffer layouts are used when attribute values\n// within a buffer should be grouped for drawElements, like the Polygon layer.) For example, a\n// buffer layout of [3, 4] might have data [A1, A2, A3, B1, B2, B3, B4]. If it needs to transition\n// to a buffer layout of [4, 2], it should produce a buffer, using the transition setting's `enter`\n// function, that looks like this: [A1, A2, A3, A4 (user `enter` fn), B1, B2, 0]. Note: the final\n// 0 in this buffer is because we never shrink buffers, only grow them, for performance reasons.\n//\n// padBuffer may return either the original buffer, or a new buffer if the size of the original\n// was insufficient. Callers are responsible for disposing of the original buffer if needed.\nexport function padBuffer({\n device,\n buffer,\n attribute,\n fromLength,\n toLength,\n fromStartIndices,\n getData = x => x\n}: {\n device: Device;\n buffer?: Buffer;\n attribute: Attribute;\n fromLength: number;\n toLength: number;\n fromStartIndices?: NumericArray | null;\n getData?: (toValue: NumericArray, chunk?: NumericArray) => NumericArray;\n}): Buffer {\n // TODO: move the precisionMultiplier logic to the attribute when retrieving\n // its `size` and `elementOffset`?\n const precisionMultiplier =\n attribute.doublePrecision && attribute.value instanceof Float64Array ? 2 : 1;\n const size = attribute.size * precisionMultiplier;\n const byteOffset = attribute.byteOffset;\n // Transform feedback can only write to float varyings\n // Attributes of format unorm8/uint8 (1 byte per element) etc will be padded to float32 (4 bytes per element)\n const targetByteOffset =\n attribute.settings.bytesPerElement < 4\n ? (byteOffset / attribute.settings.bytesPerElement) * 4\n : byteOffset;\n const toStartIndices = attribute.startIndices;\n const hasStartIndices = fromStartIndices && toStartIndices;\n const isConstant = attribute.isConstant;\n\n // check if buffer needs to be padded\n if (!hasStartIndices && buffer && fromLength >= toLength) {\n return buffer;\n }\n\n const ArrayType =\n attribute.value instanceof Float64Array\n ? Float32Array\n : ((attribute.value as TypedArray).constructor as TypedArrayConstructor);\n const toData = isConstant\n ? (attribute.value as TypedArray)\n : // TODO(v9.1): Avoid non-portable synchronous reads.\n new ArrayType(\n attribute.getBuffer()!.readSyncWebGL(byteOffset, toLength * ArrayType.BYTES_PER_ELEMENT)\n .buffer as ArrayBuffer\n );\n if (attribute.settings.normalized && !isConstant) {\n const getter = getData;\n getData = (value, chunk) => attribute.normalizeConstant(getter(value, chunk));\n }\n\n const getMissingData = isConstant\n ? (i: number, chunk: NumericArray) => getData(toData, chunk)\n : (i: number, chunk: NumericArray) =>\n getData(toData.subarray(i + byteOffset, i + byteOffset + size), chunk);\n\n // TODO(v9.1): Avoid non-portable synchronous reads.\n const source = buffer\n ? new Float32Array(buffer.readSyncWebGL(targetByteOffset, fromLength * 4).buffer as ArrayBuffer)\n : new Float32Array(0);\n const target = new Float32Array(toLength);\n padArray({\n source,\n target,\n sourceStartIndices: fromStartIndices,\n targetStartIndices: toStartIndices,\n size,\n getData: getMissingData\n });\n\n if (!buffer || buffer.byteLength < target.byteLength + targetByteOffset) {\n buffer?.destroy();\n buffer = device.createBuffer({\n byteLength: target.byteLength + targetByteOffset,\n usage: GL.DYNAMIC_COPY\n });\n }\n buffer.write(target, targetByteOffset);\n return buffer;\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport Transition from './transition';\nimport {cloneAttribute, getAttributeBufferLength} from './gpu-transition-utils';\n\nimport type {Device, Buffer} from '@luma.gl/core';\nimport type {Timeline} from '@luma.gl/engine';\nimport type Attribute from '../lib/attribute/attribute';\nimport type {TransitionSettings} from '../lib/attribute/transition-settings';\nimport type {NumericArray} from '../types/types';\n\nexport interface GPUTransition {\n get type(): string;\n get inProgress(): boolean;\n get attributeInTransition(): Attribute;\n\n /** Called when an attribute's values have changed and we need to start animating towards the new values */\n start(transitionSettings: TransitionSettings, numInstances: number): void;\n /** Called while transition is in progress */\n update(): boolean;\n /** Called when transition is interrupted */\n cancel(): void;\n /** Called when transition is disposed */\n delete(): void;\n}\n\nexport abstract class GPUTransitionBase\n implements GPUTransition\n{\n abstract get type(): string;\n\n device: Device;\n attribute: Attribute;\n transition: Transition;\n settings?: SettingsT;\n /** The attribute that holds the buffer in transition */\n attributeInTransition: Attribute;\n protected buffers: Buffer[] = [];\n /** The vertex count of the last buffer.\n * Buffer may be larger than the actual length we want to use\n * because we only reallocate buffers when they grow, not when they shrink,\n * due to performance costs */\n protected currentLength: number = 0;\n /** The start indices of the last buffer. */\n protected currentStartIndices: NumericArray | null;\n\n constructor({\n device,\n attribute,\n timeline\n }: {\n device: Device;\n attribute: Attribute;\n timeline: Timeline;\n }) {\n this.device = device;\n this.transition = new Transition(timeline);\n this.attribute = attribute;\n this.attributeInTransition = cloneAttribute(attribute);\n this.currentStartIndices = attribute.startIndices;\n }\n\n get inProgress(): boolean {\n return this.transition.inProgress;\n }\n\n start(transitionSettings: SettingsT, numInstances: number, duration: number = Infinity) {\n this.settings = transitionSettings;\n this.currentStartIndices = this.attribute.startIndices;\n this.currentLength = getAttributeBufferLength(this.attribute, numInstances);\n this.transition.start({...transitionSettings, duration});\n }\n\n update(): boolean {\n const updated = this.transition.update();\n if (updated) {\n this.onUpdate();\n }\n return updated;\n }\n\n abstract onUpdate(): void;\n\n protected setBuffer(buffer: Buffer) {\n this.attributeInTransition.setData({\n buffer,\n normalized: this.attribute.settings.normalized,\n // Retain placeholder value to generate correct shader layout\n value: this.attributeInTransition.value as NumericArray\n });\n }\n\n cancel(): void {\n this.transition.cancel();\n }\n\n delete(): void {\n this.cancel();\n for (const buffer of this.buffers) {\n buffer.destroy();\n }\n this.buffers.length = 0;\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '@luma.gl/core';\nimport {Timeline, BufferTransform} from '@luma.gl/engine';\nimport {fp64arithmetic} from '@luma.gl/shadertools';\nimport type {ShaderModule} from '@luma.gl/shadertools';\nimport {GL} from '@luma.gl/webgl/constants';\nimport Attribute from '../lib/attribute/attribute';\nimport {\n getAttributeTypeFromSize,\n cycleBuffers,\n padBuffer,\n matchBuffer,\n getFloat32VertexFormat\n} from './gpu-transition-utils';\nimport {GPUTransitionBase} from './gpu-transition';\n\nimport type {InterpolationTransitionSettings} from '../lib/attribute/transition-settings';\nimport type {TypedArray} from '../types/types';\n\nexport default class GPUInterpolationTransition extends GPUTransitionBase {\n type = 'interpolation';\n\n private transform: BufferTransform;\n\n constructor({\n device,\n attribute,\n timeline\n }: {\n device: Device;\n attribute: Attribute;\n timeline: Timeline;\n }) {\n super({device, attribute, timeline});\n this.transform = getTransform(device, attribute);\n }\n\n override start(transitionSettings: InterpolationTransitionSettings, numInstances: number): void {\n const prevLength = this.currentLength;\n const prevStartIndices = this.currentStartIndices;\n\n super.start(transitionSettings, numInstances, transitionSettings.duration);\n\n if (transitionSettings.duration <= 0) {\n this.transition.cancel();\n return;\n }\n\n const {buffers, attribute} = this;\n // Alternate between two buffers when new transitions start.\n // Last destination buffer is used as an attribute (from state),\n // And the other buffer is now the current buffer.\n cycleBuffers(buffers);\n\n buffers[0] = padBuffer({\n device: this.device,\n buffer: buffers[0],\n attribute,\n fromLength: prevLength,\n toLength: this.currentLength,\n fromStartIndices: prevStartIndices,\n getData: transitionSettings.enter\n });\n buffers[1] = matchBuffer({\n device: this.device,\n source: buffers[0],\n target: buffers[1]\n });\n\n this.setBuffer(buffers[1]);\n\n const {transform} = this;\n const model = transform.model;\n let vertexCount = Math.floor(this.currentLength / attribute.size);\n if (useFp64(attribute)) {\n vertexCount /= 2;\n }\n model.setVertexCount(vertexCount);\n if (attribute.isConstant) {\n model.setAttributes({aFrom: buffers[0]});\n model.setConstantAttributes({aTo: attribute.value as TypedArray});\n } else {\n model.setAttributes({\n aFrom: buffers[0],\n aTo: attribute.getBuffer()!\n });\n }\n transform.transformFeedback.setBuffers({vCurrent: buffers[1]});\n }\n\n onUpdate() {\n const {duration, easing} = this.settings!;\n const {time} = this.transition;\n let t = time / duration;\n if (easing) {\n t = easing(t);\n }\n const {model} = this.transform;\n const interpolationProps: InterpolationProps = {time: t};\n model.shaderInputs.setProps({interpolation: interpolationProps});\n\n this.transform.run({discard: true});\n }\n\n override delete() {\n super.delete();\n this.transform.destroy();\n }\n}\n\nconst uniformBlock = `\\\nlayout(std140) uniform interpolationUniforms {\n float time;\n} interpolation;\n`;\n\ntype InterpolationProps = {time: number};\n\nconst interpolationUniforms = {\n name: 'interpolation',\n vs: uniformBlock,\n uniformTypes: {\n time: 'f32'\n }\n} as const satisfies ShaderModule;\n\nconst vs = `\\\n#version 300 es\n#define SHADER_NAME interpolation-transition-vertex-shader\n\nin ATTRIBUTE_TYPE aFrom;\nin ATTRIBUTE_TYPE aTo;\nout ATTRIBUTE_TYPE vCurrent;\n\nvoid main(void) {\n vCurrent = mix(aFrom, aTo, interpolation.time);\n gl_Position = vec4(0.0);\n}\n`;\nconst vs64 = `\\\n#version 300 es\n#define SHADER_NAME interpolation-transition-vertex-shader\n\nin ATTRIBUTE_TYPE aFrom;\nin ATTRIBUTE_TYPE aFrom64Low;\nin ATTRIBUTE_TYPE aTo;\nin ATTRIBUTE_TYPE aTo64Low;\nout ATTRIBUTE_TYPE vCurrent;\nout ATTRIBUTE_TYPE vCurrent64Low;\n\nvec2 mix_fp64(vec2 a, vec2 b, float x) {\n vec2 range = sub_fp64(b, a);\n return sum_fp64(a, mul_fp64(range, vec2(x, 0.0)));\n}\n\nvoid main(void) {\n for (int i=0; i {\n type = 'spring';\n\n private texture: Texture;\n private framebuffer: Framebuffer;\n private transform: BufferTransform;\n\n constructor({\n device,\n attribute,\n timeline\n }: {\n device: Device;\n attribute: Attribute;\n timeline: Timeline;\n }) {\n super({device, attribute, timeline});\n this.texture = getTexture(device);\n this.framebuffer = getFramebuffer(device, this.texture);\n this.transform = getTransform(device, attribute);\n }\n\n override start(transitionSettings: SpringTransitionSettings, numInstances: number): void {\n const prevLength = this.currentLength;\n const prevStartIndices = this.currentStartIndices;\n super.start(transitionSettings, numInstances);\n\n const {buffers, attribute} = this;\n\n for (let i = 0; i < 2; i++) {\n buffers[i] = padBuffer({\n device: this.device,\n buffer: buffers[i],\n attribute,\n fromLength: prevLength,\n toLength: this.currentLength,\n fromStartIndices: prevStartIndices,\n getData: transitionSettings.enter\n });\n }\n buffers[2] = matchBuffer({\n device: this.device,\n source: buffers[0],\n target: buffers[2]\n });\n\n this.setBuffer(buffers[1]);\n\n const {model} = this.transform;\n model.setVertexCount(Math.floor(this.currentLength / attribute.size));\n if (attribute.isConstant) {\n model.setConstantAttributes({aTo: attribute.value as TypedArray});\n } else {\n model.setAttributes({aTo: attribute.getBuffer()!});\n }\n }\n\n onUpdate() {\n const {buffers, transform, framebuffer, transition} = this;\n\n const settings = this.settings as SpringTransitionSettings;\n\n transform.model.setAttributes({\n aPrev: buffers[0],\n aCur: buffers[1]\n });\n transform.transformFeedback.setBuffers({vNext: buffers[2]});\n const springProps: SpringProps = {\n stiffness: settings.stiffness,\n damping: settings.damping\n };\n transform.model.shaderInputs.setProps({spring: springProps});\n transform.run({\n framebuffer,\n discard: false,\n parameters: {viewport: [0, 0, 1, 1]},\n clearColor: [0, 0, 0, 0]\n });\n\n cycleBuffers(buffers);\n this.setBuffer(buffers[1]);\n\n const isTransitioning = this.device.readPixelsToArrayWebGL(framebuffer)[0] > 0;\n\n if (!isTransitioning) {\n transition.end();\n }\n }\n\n override delete() {\n super.delete();\n this.transform.destroy();\n this.texture.destroy();\n this.framebuffer.destroy();\n }\n}\n\nconst uniformBlock = `\\\nlayout(std140) uniform springUniforms {\n float damping;\n float stiffness;\n} spring;\n`;\n\ntype SpringProps = {\n damping: number;\n stiffness: number;\n};\n\nconst springUniforms = {\n name: 'spring',\n vs: uniformBlock,\n uniformTypes: {\n damping: 'f32',\n stiffness: 'f32'\n }\n} as const satisfies ShaderModule;\n\nconst vs = `\\\n#version 300 es\n#define SHADER_NAME spring-transition-vertex-shader\n\n#define EPSILON 0.00001\n\nin ATTRIBUTE_TYPE aPrev;\nin ATTRIBUTE_TYPE aCur;\nin ATTRIBUTE_TYPE aTo;\nout ATTRIBUTE_TYPE vNext;\nout float vIsTransitioningFlag;\n\nATTRIBUTE_TYPE getNextValue(ATTRIBUTE_TYPE cur, ATTRIBUTE_TYPE prev, ATTRIBUTE_TYPE dest) {\n ATTRIBUTE_TYPE velocity = cur - prev;\n ATTRIBUTE_TYPE delta = dest - cur;\n ATTRIBUTE_TYPE force = delta * spring.stiffness;\n ATTRIBUTE_TYPE resistance = velocity * spring.damping;\n return force - resistance + velocity + cur;\n}\n\nvoid main(void) {\n bool isTransitioning = length(aCur - aPrev) > EPSILON || length(aTo - aCur) > EPSILON;\n vIsTransitioningFlag = isTransitioning ? 1.0 : 0.0;\n\n vNext = getNextValue(aCur, aPrev, aTo);\n gl_Position = vec4(0, 0, 0, 1);\n gl_PointSize = 100.0;\n}\n`;\n\nconst fs = `\\\n#version 300 es\n#define SHADER_NAME spring-transition-is-transitioning-fragment-shader\n\nin float vIsTransitioningFlag;\n\nout vec4 fragColor;\n\nvoid main(void) {\n if (vIsTransitioningFlag == 0.0) {\n discard;\n }\n fragColor = vec4(1.0);\n}`;\n\nfunction getTransform(device: Device, attribute: Attribute): BufferTransform {\n const attributeType = getAttributeTypeFromSize(attribute.size);\n const format = getFloat32VertexFormat(attribute.size);\n return new BufferTransform(device, {\n vs,\n fs,\n bufferLayout: [\n {name: 'aPrev', format},\n {name: 'aCur', format},\n {name: 'aTo', format: attribute.getBufferLayout().attributes![0].format}\n ],\n varyings: ['vNext'],\n modules: [springUniforms],\n // @ts-expect-error TODO fix luma type\n defines: {ATTRIBUTE_TYPE: attributeType},\n parameters: {\n depthCompare: 'always',\n blendColorOperation: 'max',\n blendColorSrcFactor: 'one',\n blendColorDstFactor: 'one',\n blendAlphaOperation: 'max',\n blendAlphaSrcFactor: 'one',\n blendAlphaDstFactor: 'one'\n }\n });\n}\n\nfunction getTexture(device: Device): Texture {\n return device.createTexture({\n data: new Uint8Array(4),\n format: 'rgba8unorm',\n width: 1,\n height: 1\n });\n}\n\nfunction getFramebuffer(device: Device, texture: Texture): Framebuffer {\n return device.createFramebuffer({\n id: 'spring-transition-is-transitioning-framebuffer',\n width: 1,\n height: 1,\n colorAttachments: [texture]\n });\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// deck.gl, MIT license\n\nimport GPUInterpolationTransition from '../../transitions/gpu-interpolation-transition';\nimport GPUSpringTransition from '../../transitions/gpu-spring-transition';\nimport log from '../../utils/log';\n\nimport type {Device} from '@luma.gl/core';\nimport type {Timeline} from '@luma.gl/engine';\nimport type {GPUTransition} from '../../transitions/gpu-transition';\nimport type {ConstructorOf} from '../../types/types';\nimport type Attribute from './attribute';\nimport type {TransitionSettings} from './transition-settings';\n\nconst TRANSITION_TYPES: Record> = {\n interpolation: GPUInterpolationTransition,\n spring: GPUSpringTransition\n};\n\nexport default class AttributeTransitionManager {\n id: string;\n\n private device: Device;\n private timeline?: Timeline;\n\n private transitions: {[id: string]: GPUTransition};\n private needsRedraw: boolean;\n private numInstances: number;\n\n constructor(\n device: Device,\n {\n id,\n timeline\n }: {\n id: string;\n timeline?: Timeline;\n }\n ) {\n if (!device) throw new Error('AttributeTransitionManager is constructed without device');\n this.id = id;\n this.device = device;\n this.timeline = timeline;\n\n this.transitions = {};\n this.needsRedraw = false;\n this.numInstances = 1;\n }\n\n finalize(): void {\n for (const attributeName in this.transitions) {\n this._removeTransition(attributeName);\n }\n }\n\n /* Public methods */\n\n // Called when attribute manager updates\n // Check the latest attributes for updates.\n update({\n attributes,\n transitions,\n numInstances\n }: {\n attributes: {[id: string]: Attribute};\n transitions: any;\n numInstances: number;\n }): void {\n // Transform class will crash if elementCount is 0\n this.numInstances = numInstances || 1;\n\n for (const attributeName in attributes) {\n const attribute = attributes[attributeName];\n const settings = attribute.getTransitionSetting(transitions);\n\n // this attribute might not support transitions?\n if (!settings) continue; // eslint-disable-line no-continue\n this._updateAttribute(attributeName, attribute, settings);\n }\n\n for (const attributeName in this.transitions) {\n const attribute = attributes[attributeName];\n if (!attribute || !attribute.getTransitionSetting(transitions)) {\n // Animated attribute has been removed\n this._removeTransition(attributeName);\n }\n }\n }\n\n // Returns `true` if attribute is transition-enabled\n hasAttribute(attributeName: string): boolean {\n const transition = this.transitions[attributeName];\n return transition && transition.inProgress;\n }\n\n // Get all the animated attributes\n getAttributes(): {[id: string]: Attribute} {\n const animatedAttributes = {};\n\n for (const attributeName in this.transitions) {\n const transition = this.transitions[attributeName];\n if (transition.inProgress) {\n animatedAttributes[attributeName] = transition.attributeInTransition;\n }\n }\n\n return animatedAttributes;\n }\n\n /* eslint-disable max-statements */\n // Called every render cycle, run transform feedback\n // Returns `true` if anything changes\n run(): boolean {\n if (this.numInstances === 0) {\n return false;\n }\n\n for (const attributeName in this.transitions) {\n const updated = this.transitions[attributeName].update();\n if (updated) {\n this.needsRedraw = true;\n }\n }\n\n const needsRedraw = this.needsRedraw;\n this.needsRedraw = false;\n return needsRedraw;\n }\n /* eslint-enable max-statements */\n\n /* Private methods */\n private _removeTransition(attributeName: string): void {\n this.transitions[attributeName].delete();\n delete this.transitions[attributeName];\n }\n\n // Check an attributes for updates\n // Returns a transition object if a new transition is triggered.\n private _updateAttribute(\n attributeName: string,\n attribute: Attribute,\n settings: TransitionSettings\n ): void {\n const transition = this.transitions[attributeName];\n // an attribute can change transition type when it updates\n // let's remove the transition when that happens so we can create the new transition type\n // TODO: when switching transition types, make sure to carry over the attribute's\n // previous buffers, currentLength, startIndices, etc, to be used as the starting point\n // for the next transition\n let isNew = !transition || transition.type !== settings.type;\n\n if (isNew) {\n if (transition) {\n this._removeTransition(attributeName);\n }\n\n const TransitionType = TRANSITION_TYPES[settings.type];\n if (TransitionType) {\n this.transitions[attributeName] = new TransitionType({\n attribute,\n timeline: this.timeline,\n device: this.device\n });\n } else {\n log.error(`unsupported transition type '${settings.type}'`)();\n isNew = false;\n }\n }\n\n if (isNew || attribute.needsRedraw()) {\n this.needsRedraw = true;\n this.transitions[attributeName].start(settings, this.numInstances);\n }\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/* eslint-disable guard-for-in */\nimport Attribute, {AttributeOptions} from './attribute';\nimport log from '../../utils/log';\nimport memoize from '../../utils/memoize';\nimport {mergeBounds} from '../../utils/math-utils';\nimport debug from '../../debug/index';\nimport {NumericArray} from '../../types/types';\n\nimport AttributeTransitionManager from './attribute-transition-manager';\n\nimport type {Device, BufferLayout} from '@luma.gl/core';\nimport type {Stats} from '@probe.gl/stats';\nimport type {Timeline} from '@luma.gl/engine';\n\nconst TRACE_INVALIDATE = 'attributeManager.invalidate';\nconst TRACE_UPDATE_START = 'attributeManager.updateStart';\nconst TRACE_UPDATE_END = 'attributeManager.updateEnd';\nconst TRACE_ATTRIBUTE_UPDATE_START = 'attribute.updateStart';\nconst TRACE_ATTRIBUTE_ALLOCATE = 'attribute.allocate';\nconst TRACE_ATTRIBUTE_UPDATE_END = 'attribute.updateEnd';\n\nexport default class AttributeManager {\n /**\n * @classdesc\n * Automated attribute generation and management. Suitable when a set of\n * vertex shader attributes are generated by iteration over a data array,\n * and updates to these attributes are needed either when the data itself\n * changes, or when other data relevant to the calculations change.\n *\n * - First the application registers descriptions of its dynamic vertex\n * attributes using AttributeManager.add().\n * - Then, when any change that affects attributes is detected by the\n * application, the app will call AttributeManager.invalidate().\n * - Finally before it renders, it calls AttributeManager.update() to\n * ensure that attributes are automatically rebuilt if anything has been\n * invalidated.\n *\n * The application provided update functions describe how attributes\n * should be updated from a data array and are expected to traverse\n * that data array (or iterable) and fill in the attribute's typed array.\n *\n * Note that the attribute manager intentionally does not do advanced\n * change detection, but instead makes it easy to build such detection\n * by offering the ability to \"invalidate\" each attribute separately.\n */\n id: string;\n device: Device;\n attributes: Record;\n updateTriggers: {[name: string]: string[]};\n needsRedraw: string | boolean;\n userData: any;\n\n private stats?: Stats;\n private attributeTransitionManager: AttributeTransitionManager;\n private mergeBoundsMemoized: any = memoize(mergeBounds);\n\n constructor(\n device: Device,\n {\n id = 'attribute-manager',\n stats,\n timeline\n }: {\n id?: string;\n stats?: Stats;\n timeline?: Timeline;\n } = {}\n ) {\n this.id = id;\n this.device = device;\n\n this.attributes = {};\n\n this.updateTriggers = {};\n this.needsRedraw = true;\n\n this.userData = {};\n this.stats = stats;\n\n this.attributeTransitionManager = new AttributeTransitionManager(device, {\n id: `${id}-transitions`,\n timeline\n });\n\n // For debugging sanity, prevent uninitialized members\n Object.seal(this);\n }\n\n finalize() {\n for (const attributeName in this.attributes) {\n this.attributes[attributeName].delete();\n }\n this.attributeTransitionManager.finalize();\n }\n\n // Returns the redraw flag, optionally clearing it.\n // Redraw flag will be set if any attributes attributes changed since\n // flag was last cleared.\n //\n // @param {String} [clearRedrawFlags=false] - whether to clear the flag\n // @return {false|String} - reason a redraw is needed.\n getNeedsRedraw(opts: {clearRedrawFlags?: boolean} = {clearRedrawFlags: false}): string | false {\n const redraw = this.needsRedraw;\n this.needsRedraw = this.needsRedraw && !opts.clearRedrawFlags;\n return redraw && this.id;\n }\n\n // Sets the redraw flag.\n // @param {Boolean} redraw=true\n setNeedsRedraw() {\n this.needsRedraw = true;\n }\n\n // Adds attributes\n add(attributes: {[id: string]: AttributeOptions}) {\n this._add(attributes);\n }\n\n // Adds attributes\n addInstanced(attributes: {[id: string]: AttributeOptions}) {\n this._add(attributes, {stepMode: 'instance'});\n }\n\n /**\n * Removes attributes\n * Takes an array of attribute names and delete them from\n * the attribute map if they exists\n *\n * @example\n * attributeManager.remove(['position']);\n *\n * @param {Object} attributeNameArray - attribute name array (see above)\n */\n remove(attributeNameArray: string[]) {\n for (const name of attributeNameArray) {\n if (this.attributes[name] !== undefined) {\n this.attributes[name].delete();\n delete this.attributes[name];\n }\n }\n }\n\n // Marks an attribute for update\n invalidate(triggerName: string, dataRange?: {startRow?: number; endRow?: number}) {\n const invalidatedAttributes = this._invalidateTrigger(triggerName, dataRange);\n // For performance tuning\n debug(TRACE_INVALIDATE, this, triggerName, invalidatedAttributes);\n }\n\n invalidateAll(dataRange?: {startRow?: number; endRow?: number}) {\n for (const attributeName in this.attributes) {\n this.attributes[attributeName].setNeedsUpdate(attributeName, dataRange);\n }\n // For performance tuning\n debug(TRACE_INVALIDATE, this, 'all');\n }\n\n // Ensure all attribute buffers are updated from props or data.\n // eslint-disable-next-line complexity\n update({\n data,\n numInstances,\n startIndices = null,\n transitions,\n props = {},\n buffers = {},\n context = {}\n }: {\n data: any;\n numInstances: number;\n startIndices?: NumericArray | null;\n transitions: any;\n props: any;\n buffers: any;\n context: any;\n }) {\n // keep track of whether some attributes are updated\n let updated = false;\n\n debug(TRACE_UPDATE_START, this);\n if (this.stats) {\n this.stats.get('Update Attributes').timeStart();\n }\n\n for (const attributeName in this.attributes) {\n const attribute = this.attributes[attributeName];\n const accessorName = attribute.settings.accessor;\n attribute.startIndices = startIndices;\n attribute.numInstances = numInstances;\n\n if (props[attributeName]) {\n log.removed(`props.${attributeName}`, `data.attributes.${attributeName}`)();\n }\n\n if (attribute.setExternalBuffer(buffers[attributeName])) {\n // Step 1: try update attribute directly from external buffers\n } else if (\n attribute.setBinaryValue(\n typeof accessorName === 'string' ? buffers[accessorName] : undefined,\n data.startIndices\n )\n ) {\n // Step 2: try set packed value from external typed array\n } else if (\n typeof accessorName === 'string' &&\n !buffers[accessorName] &&\n attribute.setConstantValue(context, props[accessorName])\n ) {\n // Step 3: try set constant value from props\n // Note: if buffers[accessorName] is supplied, ignore props[accessorName]\n // This may happen when setBinaryValue falls through to use the auto updater\n } else if (attribute.needsUpdate()) {\n // Step 4: update via updater callback\n updated = true;\n this._updateAttribute({\n attribute,\n numInstances,\n data,\n props,\n context\n });\n }\n\n this.needsRedraw = this.needsRedraw || attribute.needsRedraw();\n }\n\n if (updated) {\n // Only initiate alloc/update (and logging) if actually needed\n debug(TRACE_UPDATE_END, this, numInstances);\n }\n\n if (this.stats) {\n this.stats.get('Update Attributes').timeEnd();\n if (updated) this.stats.get('Attributes updated').incrementCount();\n }\n\n this.attributeTransitionManager.update({\n attributes: this.attributes,\n numInstances,\n transitions\n });\n }\n\n // Update attribute transition to the current timestamp\n // Returns `true` if any transition is in progress\n updateTransition() {\n const {attributeTransitionManager} = this;\n const transitionUpdated = attributeTransitionManager.run();\n this.needsRedraw = this.needsRedraw || transitionUpdated;\n return transitionUpdated;\n }\n\n /**\n * Returns all attribute descriptors\n * Note: Format matches luma.gl Model/Program.setAttributes()\n * @return {Object} attributes - descriptors\n */\n getAttributes(): {[id: string]: Attribute} {\n return {...this.attributes, ...this.attributeTransitionManager.getAttributes()};\n }\n\n /**\n * Computes the spatial bounds of a given set of attributes\n */\n getBounds(attributeNames: string[]) {\n const bounds = attributeNames.map(attributeName => this.attributes[attributeName]?.getBounds());\n return this.mergeBoundsMemoized(bounds);\n }\n\n /**\n * Returns changed attribute descriptors\n * This indicates which WebGLBuffers need to be updated\n * @return {Object} attributes - descriptors\n */\n getChangedAttributes(opts: {clearChangedFlags?: boolean} = {clearChangedFlags: false}): {\n [id: string]: Attribute;\n } {\n const {attributes, attributeTransitionManager} = this;\n\n const changedAttributes = {...attributeTransitionManager.getAttributes()};\n\n for (const attributeName in attributes) {\n const attribute = attributes[attributeName];\n if (attribute.needsRedraw(opts) && !attributeTransitionManager.hasAttribute(attributeName)) {\n changedAttributes[attributeName] = attribute;\n }\n }\n\n return changedAttributes;\n }\n\n /** Generate WebGPU-style buffer layout descriptors from all attributes */\n getBufferLayouts(\n /** A luma.gl Model-shaped object that supplies additional hint to attribute resolution */\n modelInfo?: {\n /** Whether the model is instanced */\n isInstanced?: boolean;\n }\n ): BufferLayout[] {\n return Object.values(this.getAttributes()).map(attribute =>\n attribute.getBufferLayout(modelInfo)\n );\n }\n\n // PRIVATE METHODS\n\n /** Register new attributes */\n private _add(\n /** A map from attribute name to attribute descriptors */\n attributes: {[id: string]: AttributeOptions},\n /** Additional attribute settings to pass to all attributes */\n overrideOptions?: Partial\n ) {\n for (const attributeName in attributes) {\n const attribute = attributes[attributeName];\n\n const props: AttributeOptions = {\n ...attribute,\n id: attributeName,\n size: (attribute.isIndexed && 1) || attribute.size || 1,\n ...overrideOptions\n };\n\n // Initialize the attribute descriptor, with WebGL and metadata fields\n this.attributes[attributeName] = new Attribute(this.device, props);\n }\n\n this._mapUpdateTriggersToAttributes();\n }\n\n // build updateTrigger name to attribute name mapping\n private _mapUpdateTriggersToAttributes() {\n const triggers: {[name: string]: string[]} = {};\n\n for (const attributeName in this.attributes) {\n const attribute = this.attributes[attributeName];\n attribute.getUpdateTriggers().forEach(triggerName => {\n if (!triggers[triggerName]) {\n triggers[triggerName] = [];\n }\n triggers[triggerName].push(attributeName);\n });\n }\n\n this.updateTriggers = triggers;\n }\n\n private _invalidateTrigger(\n triggerName: string,\n dataRange?: {startRow?: number; endRow?: number}\n ): string[] {\n const {attributes, updateTriggers} = this;\n const invalidatedAttributes = updateTriggers[triggerName];\n\n if (invalidatedAttributes) {\n invalidatedAttributes.forEach(name => {\n const attribute = attributes[name];\n if (attribute) {\n attribute.setNeedsUpdate(attribute.id, dataRange);\n }\n });\n }\n return invalidatedAttributes;\n }\n\n private _updateAttribute(opts: {\n attribute: Attribute;\n numInstances: number;\n data: any;\n props: any;\n context: any;\n }) {\n const {attribute, numInstances} = opts;\n debug(TRACE_ATTRIBUTE_UPDATE_START, attribute);\n\n if (attribute.constant) {\n // The attribute is flagged as constant outside of an update cycle\n // Skip allocation and updater call\n // @ts-ignore value can be set to an array by user but always cast to typed array during attribute update\n attribute.setConstantValue(opts.context, attribute.value);\n return;\n }\n\n if (attribute.allocate(numInstances)) {\n debug(TRACE_ATTRIBUTE_ALLOCATE, attribute, numInstances);\n }\n\n // Calls update on any buffers that need update\n const updated = attribute.updateBuffer(opts);\n if (updated) {\n this.needsRedraw = true;\n debug(TRACE_ATTRIBUTE_UPDATE_END, attribute, numInstances);\n }\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/* eslint-disable react/no-direct-mutation-state */\nimport {Buffer, Parameters as LumaParameters, TypedArray} from '@luma.gl/core';\nimport {WebGLDevice} from '@luma.gl/webgl';\nimport AttributeManager from './attribute/attribute-manager';\nimport UniformTransitionManager from './uniform-transition-manager';\nimport {diffProps, validateProps} from '../lifecycle/props';\nimport {LIFECYCLE, Lifecycle} from '../lifecycle/constants';\nimport {count} from '../utils/count';\nimport log from '../utils/log';\nimport debug from '../debug/index';\nimport assert from '../utils/assert';\nimport memoize from '../utils/memoize';\nimport {mergeShaders} from '../utils/shader';\nimport {projectPosition, getWorldPosition} from '../shaderlib/project/project-functions';\nimport typedArrayManager from '../utils/typed-array-manager';\n\nimport Component from '../lifecycle/component';\nimport LayerState, {ChangeFlags} from './layer-state';\n\nimport {worldToPixels} from '@math.gl/web-mercator';\n\nimport {load} from '@loaders.gl/core';\n\nimport type {Loader} from '@loaders.gl/loader-utils';\nimport type {CoordinateSystem} from './constants';\nimport type Attribute from './attribute/attribute';\nimport type {Model} from '@luma.gl/engine';\nimport type {PickingInfo, GetPickingInfoParams} from './picking/pick-info';\nimport type Viewport from '../viewports/viewport';\nimport type {NumericArray} from '../types/types';\nimport type {DefaultProps} from '../lifecycle/prop-types';\nimport type {LayerData, LayerProps} from '../types/layer-props';\nimport type {LayerContext} from './layer-manager';\nimport type {BinaryAttribute} from './attribute/attribute';\nimport {RenderPass} from '@luma.gl/core';\nimport {PickingProps} from '@luma.gl/shadertools';\n\nconst TRACE_CHANGE_FLAG = 'layer.changeFlag';\nconst TRACE_INITIALIZE = 'layer.initialize';\nconst TRACE_UPDATE = 'layer.update';\nconst TRACE_FINALIZE = 'layer.finalize';\nconst TRACE_MATCHED = 'layer.matched';\n\nconst MAX_PICKING_COLOR_CACHE_SIZE = 2 ** 24 - 1;\n\nconst EMPTY_ARRAY = Object.freeze([]);\n\n// Only compare the same two viewports once\nconst areViewportsEqual = memoize(\n ({oldViewport, viewport}: {oldViewport: Viewport; viewport: Viewport}): boolean => {\n return oldViewport.equals(viewport);\n }\n);\n\nlet pickingColorCache = new Uint8ClampedArray(0);\n\nconst defaultProps: DefaultProps = {\n // data: Special handling for null, see below\n data: {type: 'data', value: EMPTY_ARRAY, async: true},\n dataComparator: {type: 'function', value: null, optional: true},\n _dataDiff: {\n type: 'function',\n // @ts-ignore __diff is not defined on data\n value: data => data && data.__diff,\n optional: true\n },\n dataTransform: {type: 'function', value: null, optional: true},\n onDataLoad: {type: 'function', value: null, optional: true},\n onError: {type: 'function', value: null, optional: true},\n fetch: {\n type: 'function',\n value: (\n url: string,\n {\n propName,\n layer,\n loaders,\n loadOptions,\n signal\n }: {\n propName: string;\n layer: LayerT;\n loaders?: Loader[];\n loadOptions?: any;\n signal?: AbortSignal;\n }\n ) => {\n const {resourceManager} = layer.context;\n loadOptions = loadOptions || layer.getLoadOptions();\n loaders = loaders || layer.props.loaders;\n if (signal) {\n loadOptions = {\n ...loadOptions,\n core: {\n ...loadOptions?.core,\n fetch: {\n ...loadOptions?.core?.fetch,\n signal\n }\n }\n };\n }\n\n let inResourceManager = resourceManager.contains(url);\n\n if (!inResourceManager && !loadOptions) {\n // If there is no layer-specific load options, then attempt to cache this resource in the data manager\n resourceManager.add({resourceId: url, data: load(url, loaders), persistent: false});\n inResourceManager = true;\n }\n if (inResourceManager) {\n return resourceManager.subscribe({\n resourceId: url,\n onChange: data => layer.internalState?.reloadAsyncProp(propName, data),\n consumerId: layer.id,\n requestId: propName\n });\n }\n\n return load(url, loaders, loadOptions);\n }\n },\n updateTriggers: {}, // Update triggers: a core change detection mechanism in deck.gl\n\n visible: true,\n pickable: false,\n opacity: {type: 'number', min: 0, max: 1, value: 1},\n operation: 'draw',\n\n onHover: {type: 'function', value: null, optional: true},\n onClick: {type: 'function', value: null, optional: true},\n onDragStart: {type: 'function', value: null, optional: true},\n onDrag: {type: 'function', value: null, optional: true},\n onDragEnd: {type: 'function', value: null, optional: true},\n\n coordinateSystem: 'default',\n coordinateOrigin: {type: 'array', value: [0, 0, 0], compare: true},\n modelMatrix: {type: 'array', value: null, compare: true, optional: true},\n wrapLongitude: false,\n positionFormat: 'XYZ',\n colorFormat: 'RGBA',\n\n parameters: {type: 'object', value: {}, optional: true, compare: 2},\n loadOptions: {type: 'object', value: null, optional: true, ignore: true},\n transitions: null,\n extensions: [],\n loaders: {type: 'array', value: [], optional: true, ignore: true},\n\n // Offset depth based on layer index to avoid z-fighting.\n // Negative values pull layer towards the camera\n // https://www.opengl.org/archives/resources/faq/technical/polygonoffset.htm\n getPolygonOffset: {\n type: 'function',\n value: ({layerIndex}) => [0, -layerIndex * 100]\n },\n\n // Selection/Highlighting\n highlightedObjectIndex: null,\n autoHighlight: false,\n highlightColor: {type: 'accessor', value: [0, 0, 128, 128]}\n};\n\nexport type UpdateParameters = {\n props: LayerT['props'];\n oldProps: LayerT['props'];\n context: LayerContext;\n changeFlags: ChangeFlags;\n};\n\ntype DrawOptions = {\n renderPass: RenderPass;\n shaderModuleProps: any;\n uniforms: any;\n parameters: any;\n context: LayerContext;\n};\n\ntype SharedLayerState = {\n [key: string]: unknown;\n};\n\nexport default abstract class Layer extends Component<\n PropsT & Required\n> {\n static defaultProps: DefaultProps = defaultProps;\n static layerName: string = 'Layer';\n\n static override get componentName() {\n return Object.prototype.hasOwnProperty.call(this, 'layerName') ? this.layerName : '';\n }\n\n internalState: LayerState | null = null;\n lifecycle: Lifecycle = LIFECYCLE.NO_STATE; // Helps track and debug the life cycle of the layers\n\n // context and state can technically be null before a layer is initialized/matched.\n // However, they are most extensively accessed in a layer's lifecycle methods, where they are always defined.\n // Checking for null state constantly in layer implementation is unnecessarily verbose.\n context!: LayerContext; // Will reference layer manager's context, contains state shared by layers\n state!: SharedLayerState; // Will be set to the shared layer state object during layer matching\n\n parent: Layer | null = null;\n\n get root(): Layer {\n // eslint-disable-next-line\n let layer: Layer = this;\n while (layer.parent) {\n layer = layer.parent;\n }\n return layer;\n }\n\n toString(): string {\n const className = (this.constructor as typeof Layer).layerName || this.constructor.name;\n return `${className}({id: '${this.props.id}'})`;\n }\n\n // Public API for users\n\n /** Projects a point with current view state from the current layer's coordinate system to screen */\n project(xyz: number[]): number[] {\n assert(this.internalState);\n const viewport = this.internalState.viewport || this.context.viewport;\n\n const worldPosition = getWorldPosition(xyz, {\n viewport,\n modelMatrix: this.props.modelMatrix,\n coordinateOrigin: this.props.coordinateOrigin,\n coordinateSystem: this.props.coordinateSystem\n });\n const [x, y, z] = worldToPixels(worldPosition, viewport.pixelProjectionMatrix);\n return xyz.length === 2 ? [x, y] : [x, y, z];\n }\n\n /** Unprojects a screen pixel to the current view's default coordinate system\n Note: this does not reverse `project`. */\n unproject(xy: number[]): number[] {\n assert(this.internalState);\n const viewport = this.internalState.viewport || this.context.viewport;\n return viewport.unproject(xy);\n }\n\n /** Projects a point with current view state from the current layer's coordinate system to the world space */\n projectPosition(\n xyz: number[],\n params?: {\n /** The viewport to use */\n viewport?: Viewport;\n /** The coordinate system that the supplied position is in. Default to the same as `coordinateSystem`. */\n fromCoordinateSystem?: CoordinateSystem;\n /** The coordinate origin that the supplied position is in. Default to the same as `coordinateOrigin`. */\n fromCoordinateOrigin?: [number, number, number];\n /** Whether to apply offset mode automatically as does the project shader module.\n * Offset mode places the origin of the common space at the given viewport's center. It is used in some use cases\n * to improve precision in the vertex shader due to the fp32 float limitation.\n * Use `autoOffset:false` if the returned position should not be dependent on the current viewport.\n * Default `true` */\n autoOffset?: boolean;\n }\n ): [number, number, number] {\n assert(this.internalState);\n const viewport = this.internalState.viewport || this.context.viewport;\n\n return projectPosition(xyz, {\n viewport,\n modelMatrix: this.props.modelMatrix,\n coordinateOrigin: this.props.coordinateOrigin,\n coordinateSystem: this.props.coordinateSystem,\n ...params\n });\n }\n\n // Public API for custom layer implementation\n\n /** `true` if this layer renders other layers */\n get isComposite(): boolean {\n return false;\n }\n\n /** `true` if the layer renders to screen */\n get isDrawable(): boolean {\n return true;\n }\n\n /** Updates selected state members and marks the layer for redraw */\n setState(partialState: any): void {\n this.setChangeFlags({stateChanged: true});\n Object.assign(this.state, partialState);\n this.setNeedsRedraw();\n }\n\n /** Sets the redraw flag for this layer, will trigger a redraw next animation frame */\n setNeedsRedraw(): void {\n if (this.internalState) {\n this.internalState.needsRedraw = true;\n }\n }\n\n /** Mark this layer as needs a deep update */\n setNeedsUpdate() {\n if (this.internalState) {\n this.context.layerManager.setNeedsUpdate(String(this));\n this.internalState.needsUpdate = true;\n }\n }\n\n /** Returns true if all async resources are loaded */\n get isLoaded(): boolean {\n return this.internalState ? !this.internalState.isAsyncPropLoading() : false;\n }\n\n /** Returns true if using shader-based WGS84 longitude wrapping */\n get wrapLongitude(): boolean {\n return this.props.wrapLongitude;\n }\n\n /** @deprecated Returns true if the layer is visible in the picking pass */\n isPickable(): boolean {\n return this.props.pickable && this.props.visible;\n }\n\n /** Returns an array of models used by this layer, can be overriden by layer subclass */\n getModels(): Model[] {\n const state = this.state as {\n models?: Model[];\n model: Model;\n };\n return (state && (state.models || (state.model && [state.model]))) || [];\n }\n\n /** Update shader input parameters */\n setShaderModuleProps(...props: Parameters): void {\n for (const model of this.getModels()) {\n model.shaderInputs.setProps(...props);\n }\n }\n\n /** Returns the attribute manager of this layer */\n getAttributeManager(): AttributeManager | null {\n return this.internalState && this.internalState.attributeManager;\n }\n\n /** Returns the most recent layer that matched to this state\n (When reacting to an async event, this layer may no longer be the latest) */\n getCurrentLayer(): Layer | null {\n return this.internalState && this.internalState.layer;\n }\n\n /** Returns the default parse options for async props */\n getLoadOptions(): any {\n return this.props.loadOptions;\n }\n\n use64bitPositions(): boolean {\n const {coordinateSystem} = this.props;\n return (\n coordinateSystem === 'default' ||\n coordinateSystem === 'lnglat' ||\n coordinateSystem === 'cartesian'\n );\n }\n\n // Event handling\n onHover(info: PickingInfo, pickingEvent): boolean {\n if (this.props.onHover) {\n return this.props.onHover(info, pickingEvent) || false;\n }\n return false;\n }\n\n onClick(info: PickingInfo, pickingEvent): boolean {\n if (this.props.onClick) {\n return this.props.onClick(info, pickingEvent) || false;\n }\n return false;\n }\n\n // Returns the picking color that doesn't match any subfeature\n // Use if some graphics do not belong to any pickable subfeature\n // @return {Array} - a black color\n nullPickingColor() {\n return [0, 0, 0];\n }\n\n // Returns the picking color that doesn't match any subfeature\n // Use if some graphics do not belong to any pickable subfeature\n encodePickingColor(i, target: number[] = []): [number, number, number] {\n target[0] = (i + 1) & 255;\n target[1] = ((i + 1) >> 8) & 255;\n target[2] = (((i + 1) >> 8) >> 8) & 255;\n return target as [number, number, number];\n }\n\n // Returns the index corresponding to a picking color that doesn't match any subfeature\n // @param {Uint8Array} color - color array to be decoded\n // @return {Array} - the decoded picking color\n decodePickingColor(color) {\n assert(color instanceof Uint8Array);\n const [i1, i2, i3] = color;\n // 1 was added to seperate from no selection\n const index = i1 + i2 * 256 + i3 * 65536 - 1;\n return index;\n }\n\n /** Deduces number of instances. Intention is to support:\n - Explicit setting of numInstances\n - Auto-deduction for ES6 containers that define a size member\n - Auto-deduction for Classic Arrays via the built-in length attribute\n - Auto-deduction via arrays */\n getNumInstances(): number {\n // First Check if app has provided an explicit value\n if (Number.isFinite(this.props.numInstances)) {\n return this.props.numInstances as number;\n }\n\n // Second check if the layer has set its own value\n if (this.state && this.state.numInstances !== undefined) {\n return this.state.numInstances as number;\n }\n\n // Use container library to get a count for any ES6 container or object\n return count(this.props.data);\n }\n\n /** Buffer layout describes how many attribute values are packed for each data object\n The default (null) is one value each object.\n Some data formats (e.g. paths, polygons) have various length. Their buffer layout\n is in the form of [L0, L1, L2, ...] */\n getStartIndices(): NumericArray | null {\n // First Check if startIndices is provided as an explicit value\n if (this.props.startIndices) {\n return this.props.startIndices;\n }\n\n // Second check if the layer has set its own value\n if (this.state && this.state.startIndices) {\n return this.state.startIndices as NumericArray;\n }\n\n return null;\n }\n\n // Default implementation\n getBounds(): [number[], number[]] | null {\n return this.getAttributeManager()?.getBounds(['positions', 'instancePositions']);\n }\n\n // / LIFECYCLE METHODS - overridden by the layer subclasses\n\n /** Called once to set up the initial state. Layers can create WebGL resources here. */\n abstract initializeState(context: LayerContext): void;\n\n getShaders(shaders: any): any {\n shaders = mergeShaders(shaders, {\n disableWarnings: true,\n modules: this.context.defaultShaderModules\n });\n for (const extension of this.props.extensions) {\n shaders = mergeShaders(shaders, extension.getShaders.call(this, extension));\n }\n return shaders;\n }\n\n /** Controls if updateState should be called. By default returns true if any prop has changed */\n shouldUpdateState(params: UpdateParameters>): boolean {\n return params.changeFlags.propsOrDataChanged;\n }\n\n /** Default implementation, all attributes will be invalidated and updated when data changes */\n // eslint-disable-next-line complexity\n updateState(params: UpdateParameters>): void {\n const attributeManager = this.getAttributeManager();\n const {dataChanged} = params.changeFlags;\n if (dataChanged && attributeManager) {\n if (Array.isArray(dataChanged)) {\n // is partial update\n for (const dataRange of dataChanged) {\n attributeManager.invalidateAll(dataRange);\n }\n } else {\n attributeManager.invalidateAll();\n }\n }\n\n // Enable/disable picking buffer\n if (attributeManager) {\n const {props} = params;\n const hasPickingBuffer = this.internalState!.hasPickingBuffer;\n const needsPickingBuffer =\n Number.isInteger(props.highlightedObjectIndex) ||\n Boolean(props.pickable) ||\n props.extensions.some(extension => extension.getNeedsPickingBuffer.call(this, extension));\n\n // Only generate picking buffer if needed\n if (hasPickingBuffer !== needsPickingBuffer) {\n this.internalState!.hasPickingBuffer = needsPickingBuffer;\n const {pickingColors, instancePickingColors} = attributeManager.attributes;\n const pickingColorsAttribute = pickingColors || instancePickingColors;\n if (pickingColorsAttribute) {\n if (needsPickingBuffer && pickingColorsAttribute.constant) {\n pickingColorsAttribute.constant = false;\n attributeManager.invalidate(pickingColorsAttribute.id);\n }\n if (!pickingColorsAttribute.value && !needsPickingBuffer) {\n pickingColorsAttribute.constant = true;\n pickingColorsAttribute.value = [0, 0, 0];\n }\n }\n }\n }\n }\n\n /** Called once when layer is no longer matched and state will be discarded. Layers can destroy WebGL resources here. */\n finalizeState(context: LayerContext): void {\n for (const model of this.getModels()) {\n model.destroy();\n }\n const attributeManager = this.getAttributeManager();\n if (attributeManager) {\n attributeManager.finalize();\n }\n if (this.context) {\n this.context.resourceManager.unsubscribe({consumerId: this.id});\n }\n if (this.internalState) {\n this.internalState.uniformTransitions.clear();\n this.internalState.finalize();\n }\n }\n\n // If state has a model, draw it with supplied uniforms\n draw(opts: DrawOptions) {\n for (const model of this.getModels()) {\n model.draw(opts.renderPass);\n }\n }\n\n // called to populate the info object that is passed to the event handler\n // @return null to cancel event\n getPickingInfo({info, mode, sourceLayer}: GetPickingInfoParams) {\n const {index} = info;\n\n if (index >= 0) {\n // If props.data is an indexable array, get the object\n if (Array.isArray(this.props.data)) {\n info.object = this.props.data[index];\n }\n }\n\n return info;\n }\n\n // END LIFECYCLE METHODS\n\n // / INTERNAL METHODS - called by LayerManager, DeckRenderer and DeckPicker\n\n /** (Internal) Propagate an error event through the system */\n raiseError(error: Error, message: string): void {\n if (message) {\n // Duplicating error message for backward compatibility, see #7986\n // TODO - revisit in v9\n error = new Error(`${message}: ${error.message}`, {cause: error});\n }\n if (!this.props.onError?.(error)) {\n this.context?.onError?.(error, this);\n }\n }\n\n /** (Internal) Checks if this layer needs redraw */\n getNeedsRedraw(\n opts: {\n /** Reset redraw flags to false after the check */\n clearRedrawFlags: boolean;\n } = {clearRedrawFlags: false}\n ): string | false {\n return this._getNeedsRedraw(opts);\n }\n\n /** (Internal) Checks if this layer needs a deep update */\n needsUpdate(): boolean {\n if (!this.internalState) {\n return false;\n }\n\n // Call subclass lifecycle method\n return (\n this.internalState.needsUpdate ||\n this.hasUniformTransition() ||\n this.shouldUpdateState(this._getUpdateParams())\n );\n // End lifecycle method\n }\n\n /** Checks if this layer has ongoing uniform transition */\n hasUniformTransition(): boolean {\n return this.internalState?.uniformTransitions.active || false;\n }\n\n /** Called when this layer is rendered into the given viewport */\n activateViewport(viewport: Viewport): void {\n if (!this.internalState) {\n return;\n }\n\n const oldViewport = this.internalState.viewport;\n this.internalState.viewport = viewport;\n\n if (!oldViewport || !areViewportsEqual({oldViewport, viewport})) {\n this.setChangeFlags({viewportChanged: true});\n\n if (this.isComposite) {\n if (this.needsUpdate()) {\n // Composite layers may add/remove sublayers on viewport change\n // Because we cannot change the layers list during a draw cycle, we don't want to update sublayers right away\n // This will not call update immediately, but mark the layerManager as needs update on the next frame\n this.setNeedsUpdate();\n }\n } else {\n this._update();\n }\n }\n }\n\n /** Default implementation of attribute invalidation, can be redefined */\n protected invalidateAttribute(name = 'all'): void {\n const attributeManager = this.getAttributeManager();\n if (!attributeManager) {\n return;\n }\n\n if (name === 'all') {\n attributeManager.invalidateAll();\n } else {\n attributeManager.invalidate(name);\n }\n }\n\n /** Send updated attributes to the WebGL model */\n protected updateAttributes(changedAttributes: {[id: string]: Attribute}) {\n // If some buffer layout changed\n let bufferLayoutChanged = false;\n for (const id in changedAttributes) {\n if (changedAttributes[id].layoutChanged()) {\n bufferLayoutChanged = true;\n }\n }\n\n for (const model of this.getModels()) {\n this._setModelAttributes(model, changedAttributes, bufferLayoutChanged);\n }\n }\n\n /** Recalculate any attributes if needed */\n protected _updateAttributes(): void {\n const attributeManager = this.getAttributeManager();\n if (!attributeManager) {\n return;\n }\n const props = this.props;\n\n // Figure out data length\n const numInstances = this.getNumInstances();\n const startIndices = this.getStartIndices();\n\n attributeManager.update({\n data: props.data,\n numInstances,\n startIndices,\n props,\n transitions: props.transitions,\n // @ts-ignore (TS2339) property attribute is not present on some acceptable data types\n buffers: props.data.attributes,\n context: this\n });\n\n const changedAttributes = attributeManager.getChangedAttributes({clearChangedFlags: true});\n this.updateAttributes(changedAttributes);\n }\n\n /** Update attribute transitions. This is called in drawLayer, no model updates required. */\n private _updateAttributeTransition() {\n const attributeManager = this.getAttributeManager();\n if (attributeManager) {\n attributeManager.updateTransition();\n }\n }\n\n /** Update uniform (prop) transitions. This is called in updateState, may result in model updates. */\n private _updateUniformTransition(): Layer['props'] {\n // @ts-ignore (TS2339) internalState is alwasy defined when this method is called\n const {uniformTransitions} = this.internalState;\n if (uniformTransitions.active) {\n // clone props\n const propsInTransition = uniformTransitions.update();\n const props = Object.create(this.props);\n for (const key in propsInTransition) {\n Object.defineProperty(props, key, {value: propsInTransition[key]});\n }\n return props;\n }\n return this.props;\n }\n\n /** Updater for the automatically populated instancePickingColors attribute */\n protected calculateInstancePickingColors(\n attribute: Attribute,\n {numInstances}: {numInstances: number}\n ) {\n if (attribute.constant) {\n return;\n }\n\n // calculateInstancePickingColors always generates the same sequence.\n // pickingColorCache saves the largest generated sequence for reuse\n const cacheSize = Math.floor(pickingColorCache.length / 4);\n\n // Record when using the picking buffer cache, so that layers can always point at the most recently allocated cache\n // @ts-ignore (TS2531) internalState is always defined when this method is called\n this.internalState.usesPickingColorCache = true;\n\n if (cacheSize < numInstances) {\n if (numInstances > MAX_PICKING_COLOR_CACHE_SIZE) {\n log.warn(\n 'Layer has too many data objects. Picking might not be able to distinguish all objects.'\n )();\n }\n\n pickingColorCache = typedArrayManager.allocate(pickingColorCache, numInstances, {\n size: 4,\n copy: true,\n maxCount: Math.max(numInstances, MAX_PICKING_COLOR_CACHE_SIZE)\n });\n\n // If the attribute is larger than the cache, resize the cache and populate the missing chunk\n const newCacheSize = Math.floor(pickingColorCache.length / 4);\n const pickingColor: [number, number, number] = [0, 0, 0];\n for (let i = cacheSize; i < newCacheSize; i++) {\n this.encodePickingColor(i, pickingColor);\n pickingColorCache[i * 4 + 0] = pickingColor[0];\n pickingColorCache[i * 4 + 1] = pickingColor[1];\n pickingColorCache[i * 4 + 2] = pickingColor[2];\n pickingColorCache[i * 4 + 3] = 0;\n }\n }\n\n attribute.value = pickingColorCache.subarray(0, numInstances * 4);\n }\n\n /** Apply changed attributes to model */\n protected _setModelAttributes(\n model: Model,\n changedAttributes: {\n [id: string]: Attribute;\n },\n bufferLayoutChanged = false\n ) {\n if (!Object.keys(changedAttributes).length) {\n return;\n }\n\n if (bufferLayoutChanged) {\n // AttributeManager is always defined when this method is called\n const attributeManager = this.getAttributeManager()!;\n model.setBufferLayout(attributeManager.getBufferLayouts(model));\n // All attributes must be reset after buffer layout change\n changedAttributes = attributeManager.getAttributes();\n }\n\n // @ts-ignore luma.gl type issue\n const excludeAttributes = model.userData?.excludeAttributes || {};\n const attributeBuffers: Record = {};\n const constantAttributes: Record = {};\n\n for (const name in changedAttributes) {\n if (excludeAttributes[name]) {\n continue;\n }\n const values = changedAttributes[name].getValue();\n for (const attributeName in values) {\n const value = values[attributeName];\n if (value instanceof Buffer) {\n if (changedAttributes[name].settings.isIndexed) {\n model.setIndexBuffer(value);\n } else {\n attributeBuffers[attributeName] = value;\n }\n } else if (value) {\n constantAttributes[attributeName] = value;\n }\n }\n }\n // TODO - update buffer map?\n model.setAttributes(attributeBuffers);\n model.setConstantAttributes(constantAttributes);\n }\n\n /** (Internal) Sets the picking color at the specified index to null picking color. Used for multi-depth picking.\n This method may be overriden by layer implementations */\n disablePickingIndex(objectIndex: number) {\n const data = this.props.data as LayerData;\n if (!('attributes' in data)) {\n this._disablePickingIndex(objectIndex);\n return;\n }\n\n // @ts-ignore (TS2531) this method is only called internally with attributeManager defined\n const {pickingColors, instancePickingColors} = this.getAttributeManager().attributes;\n const colors = pickingColors || instancePickingColors;\n const externalColorAttribute =\n colors && data.attributes && (data.attributes[colors.id] as BinaryAttribute);\n if (externalColorAttribute && externalColorAttribute.value) {\n const values = externalColorAttribute.value;\n const objectColor = this.encodePickingColor(objectIndex);\n for (let index = 0; index < data.length; index++) {\n const i = colors.getVertexOffset(index);\n if (\n values[i] === objectColor[0] &&\n values[i + 1] === objectColor[1] &&\n values[i + 2] === objectColor[2]\n ) {\n this._disablePickingIndex(index);\n }\n }\n } else {\n this._disablePickingIndex(objectIndex);\n }\n }\n\n // TODO - simplify subclassing interface\n protected _disablePickingIndex(objectIndex: number): void {\n // @ts-ignore (TS2531) this method is only called internally with attributeManager defined\n const {pickingColors, instancePickingColors} = this.getAttributeManager().attributes;\n const colors = pickingColors || instancePickingColors;\n if (!colors) {\n return;\n }\n\n const start = colors.getVertexOffset(objectIndex);\n const end = colors.getVertexOffset(objectIndex + 1);\n\n // Fill the sub buffer with 0s, 1 byte per element\n colors.buffer.write(new Uint8Array(end - start), start);\n }\n\n /** (Internal) Re-enable all picking indices after multi-depth picking */\n restorePickingColors(): void {\n // @ts-ignore (TS2531) this method is only called internally with attributeManager defined\n const {pickingColors, instancePickingColors} = this.getAttributeManager().attributes;\n const colors = pickingColors || instancePickingColors;\n if (!colors) {\n return;\n }\n // The picking color cache may have been freed and then reallocated. This ensures we read from the currently allocated cache.\n if (\n // @ts-ignore (TS2531) this method is only called internally with internalState defined\n this.internalState.usesPickingColorCache &&\n (colors.value as Uint8ClampedArray).buffer !== pickingColorCache.buffer\n ) {\n colors.value = pickingColorCache.subarray(0, (colors.value as Uint8ClampedArray).length);\n }\n colors.updateSubBuffer({startOffset: 0});\n }\n\n /* eslint-disable max-statements */\n /* (Internal) Called by layer manager when a new layer is found */\n _initialize() {\n assert(!this.internalState); // finalized layer cannot be reused\n\n debug(TRACE_INITIALIZE, this);\n\n const attributeManager = this._getAttributeManager();\n\n if (attributeManager) {\n // All instanced layers get instancePickingColors attribute by default\n // Their shaders can use it to render a picking scene\n // TODO - this slightly slows down non instanced layers\n attributeManager.addInstanced({\n instancePickingColors: {\n type: 'uint8',\n size: 4,\n noAlloc: true,\n // Updaters are always called with `this` pointing to the layer\n // eslint-disable-next-line @typescript-eslint/unbound-method\n update: this.calculateInstancePickingColors\n }\n });\n }\n\n this.internalState = new LayerState({\n attributeManager,\n layer: this\n });\n this._clearChangeFlags(); // populate this.internalState.changeFlags\n\n this.state = {};\n // for backwards compatibility with older layers\n // TODO - remove in next release\n /* eslint-disable accessor-pairs */\n Object.defineProperty(this.state, 'attributeManager', {\n get: () => {\n log.deprecated('layer.state.attributeManager', 'layer.getAttributeManager()')();\n return attributeManager;\n }\n });\n /* eslint-enable accessor-pairs */\n\n this.internalState.uniformTransitions = new UniformTransitionManager(this.context.timeline);\n this.internalState.onAsyncPropUpdated = this._onAsyncPropUpdated.bind(this);\n\n // Ensure any async props are updated\n this.internalState.setAsyncProps(this.props);\n\n // Call subclass lifecycle methods\n this.initializeState(this.context);\n\n // Initialize extensions\n for (const extension of this.props.extensions) {\n extension.initializeState.call(this, this.context, extension);\n }\n // End subclass lifecycle methods\n\n // initializeState callback tends to clear state\n this.setChangeFlags({\n dataChanged: 'init',\n propsChanged: 'init',\n viewportChanged: true,\n extensionsChanged: true\n });\n\n this._update();\n }\n\n /** (Internal) Called by layer manager to transfer state from an old layer */\n _transferState(oldLayer: Layer): void {\n debug(TRACE_MATCHED, this, this === oldLayer);\n\n const {state, internalState} = oldLayer;\n\n if (this === oldLayer) {\n return;\n }\n\n // Move internalState\n this.internalState = internalState as LayerState;\n\n // Move state\n this.state = state;\n // We keep the state ref on old layers to support async actions\n // oldLayer.state = null;\n\n // Ensure any async props are updated\n this.internalState.setAsyncProps(this.props);\n\n this._diffProps(this.props, this.internalState.getOldProps() as Layer['props']);\n }\n\n /** (Internal) Called by layer manager when a new layer is added or an existing layer is matched with a new instance */\n _update(): void {\n // Call subclass lifecycle method\n const stateNeedsUpdate = this.needsUpdate();\n // End lifecycle method\n debug(TRACE_UPDATE, this, stateNeedsUpdate);\n\n if (!stateNeedsUpdate) {\n return;\n }\n this.context.stats.get('Layer updates').incrementCount();\n\n const currentProps = this.props;\n const context = this.context;\n const internalState = this.internalState as LayerState;\n\n const currentViewport = context.viewport;\n const propsInTransition = this._updateUniformTransition();\n internalState.propsInTransition = propsInTransition;\n // Overwrite this.context.viewport during update to use the last activated viewport on this layer\n // In multi-view applications, a layer may only be drawn in one of the views\n // Which would make the \"active\" viewport different from the shared context\n context.viewport = internalState.viewport || currentViewport;\n // Overwrite this.props during update to use in-transition prop values\n this.props = propsInTransition;\n\n try {\n const updateParams = this._getUpdateParams();\n const oldModels = this.getModels();\n\n // Safely call subclass lifecycle methods\n if (context.device) {\n this.updateState(updateParams);\n } else {\n try {\n this.updateState(updateParams);\n } catch (error) {\n // ignore error if gl context is missing\n }\n }\n // Execute extension updates\n for (const extension of this.props.extensions) {\n extension.updateState.call(this, updateParams, extension);\n }\n\n this.setNeedsRedraw();\n // Check if attributes need recalculation\n this._updateAttributes();\n\n const modelChanged = this.getModels()[0] !== oldModels[0];\n this._postUpdate(updateParams, modelChanged);\n // End subclass lifecycle methods\n } finally {\n // Restore shared context\n context.viewport = currentViewport;\n this.props = currentProps;\n this._clearChangeFlags();\n internalState.needsUpdate = false;\n internalState.resetOldProps();\n }\n }\n /* eslint-enable max-statements */\n\n /** (Internal) Called by manager when layer is about to be disposed \n Note: not guaranteed to be called on application shutdown */\n _finalize(): void {\n debug(TRACE_FINALIZE, this);\n\n // Call subclass lifecycle method\n this.finalizeState(this.context);\n // Finalize extensions\n for (const extension of this.props.extensions) {\n extension.finalizeState.call(this, this.context, extension);\n }\n }\n\n // Calculates uniforms\n _drawLayer({\n renderPass,\n shaderModuleProps = null,\n uniforms = {},\n parameters = {}\n }: {\n renderPass: RenderPass;\n shaderModuleProps: any;\n uniforms: any;\n parameters: LumaParameters;\n }): void {\n this._updateAttributeTransition();\n\n const currentProps = this.props;\n const context = this.context;\n // Overwrite this.props during redraw to use in-transition prop values\n // `internalState.propsInTransition` could be missing if `updateState` failed\n // @ts-ignore (TS2339) internalState is alwasy defined when this method is called\n this.props = this.internalState.propsInTransition || currentProps;\n\n try {\n // TODO/ib - hack move to luma Model.draw\n if (shaderModuleProps) {\n this.setShaderModuleProps(shaderModuleProps);\n }\n\n // Apply polygon offset to avoid z-fighting\n // TODO - move to draw-layers\n const {getPolygonOffset} = this.props;\n const offsets = (getPolygonOffset && getPolygonOffset(uniforms)) || [0, 0];\n\n if (context.device instanceof WebGLDevice) {\n context.device.setParametersWebGL({polygonOffset: offsets});\n }\n\n const webGPUDrawParameters =\n context.device instanceof WebGLDevice ? null : splitWebGPUDrawParameters(parameters);\n\n applyModelParameters(this.getModels(), renderPass, parameters, webGPUDrawParameters);\n\n // Call subclass lifecycle method\n if (context.device instanceof WebGLDevice) {\n context.device.withParametersWebGL(parameters, () => {\n const opts: DrawOptions = {renderPass, shaderModuleProps, uniforms, parameters, context};\n\n // extensions\n for (const extension of this.props.extensions) {\n extension.draw.call(this, opts, extension);\n }\n\n this.draw(opts);\n });\n } else {\n if (webGPUDrawParameters?.renderPassParameters) {\n renderPass.setParameters(webGPUDrawParameters.renderPassParameters);\n }\n const opts: DrawOptions = {renderPass, shaderModuleProps, uniforms, parameters, context};\n\n // extensions\n for (const extension of this.props.extensions) {\n extension.draw.call(this, opts, extension);\n }\n\n this.draw(opts);\n }\n } finally {\n this.props = currentProps;\n }\n\n // End lifecycle method\n }\n\n // Helper methods\n /** Returns the current change flags */\n getChangeFlags(): ChangeFlags | undefined {\n return this.internalState?.changeFlags;\n }\n\n /* eslint-disable complexity */\n /** Dirty some change flags, will be handled by updateLayer */\n setChangeFlags(flags: Partial): void {\n if (!this.internalState) {\n return;\n }\n const {changeFlags} = this.internalState;\n\n /* eslint-disable no-fallthrough, max-depth */\n for (const key in flags) {\n if (flags[key]) {\n let flagChanged = false;\n switch (key) {\n case 'dataChanged':\n // changeFlags.dataChanged may be `false`, a string (reason) or an array of ranges\n const dataChangedReason = flags[key];\n const prevDataChangedReason = changeFlags[key];\n if (dataChangedReason && Array.isArray(prevDataChangedReason)) {\n // Merge partial updates\n changeFlags.dataChanged = Array.isArray(dataChangedReason)\n ? prevDataChangedReason.concat(dataChangedReason)\n : dataChangedReason;\n flagChanged = true;\n }\n\n default:\n if (!changeFlags[key]) {\n changeFlags[key] = flags[key];\n flagChanged = true;\n }\n }\n if (flagChanged) {\n debug(TRACE_CHANGE_FLAG, this, key, flags);\n }\n }\n }\n /* eslint-enable no-fallthrough, max-depth */\n\n // Update composite flags\n const propsOrDataChanged = Boolean(\n changeFlags.dataChanged ||\n changeFlags.updateTriggersChanged ||\n changeFlags.propsChanged ||\n changeFlags.extensionsChanged\n );\n changeFlags.propsOrDataChanged = propsOrDataChanged;\n changeFlags.somethingChanged =\n propsOrDataChanged || changeFlags.viewportChanged || changeFlags.stateChanged;\n }\n /* eslint-enable complexity */\n\n /** Clear all changeFlags, typically after an update */\n private _clearChangeFlags(): void {\n // @ts-ignore TS2531 this method can only be called internally with internalState assigned\n this.internalState.changeFlags = {\n dataChanged: false,\n propsChanged: false,\n updateTriggersChanged: false,\n viewportChanged: false,\n stateChanged: false,\n extensionsChanged: false,\n propsOrDataChanged: false,\n somethingChanged: false\n };\n }\n\n /** Compares the layers props with old props from a matched older layer\n and extracts change flags that describe what has change so that state\n can be update correctly with minimal effort */\n private _diffProps(newProps: Layer['props'], oldProps: Layer['props']) {\n const changeFlags = diffProps(newProps, oldProps);\n\n // iterate over changedTriggers\n if (changeFlags.updateTriggersChanged) {\n for (const key in changeFlags.updateTriggersChanged) {\n if (changeFlags.updateTriggersChanged[key]) {\n this.invalidateAttribute(key);\n }\n }\n }\n\n // trigger uniform transitions\n if (changeFlags.transitionsChanged) {\n for (const key in changeFlags.transitionsChanged) {\n // prop changed and transition is enabled\n // @ts-ignore (TS2531) internalState is always defined when this method is called\n this.internalState.uniformTransitions.add(\n key,\n oldProps[key],\n newProps[key],\n newProps.transitions?.[key]\n );\n }\n }\n\n return this.setChangeFlags(changeFlags);\n }\n\n /** (Internal) called by layer manager to perform extra props validation (in development only) */\n validateProps(): void {\n validateProps(this.props);\n }\n\n /** (Internal) Called by deck picker when the hovered object changes to update the auto highlight */\n updateAutoHighlight(info: PickingInfo): void {\n if (this.props.autoHighlight && !Number.isInteger(this.props.highlightedObjectIndex)) {\n this._updateAutoHighlight(info);\n }\n }\n\n // May be overriden by subclasses\n\n // TODO - simplify subclassing interface\n /** Update picking module parameters to highlight the hovered object */\n protected _updateAutoHighlight(info: PickingInfo): void {\n const picking: PickingProps = {\n // @ts-ignore\n highlightedObjectColor: info.picked ? info.color : null\n };\n const {highlightColor} = this.props;\n if (info.picked && typeof highlightColor === 'function') {\n // @ts-ignore\n picking.highlightColor = highlightColor(info);\n }\n this.setShaderModuleProps({picking});\n // setShaderModuleProps does not trigger redraw\n this.setNeedsRedraw();\n }\n\n /** Create new attribute manager */\n protected _getAttributeManager(): AttributeManager | null {\n const context = this.context;\n return new AttributeManager(context.device, {\n id: this.props.id,\n stats: context.stats,\n timeline: context.timeline\n });\n }\n\n // Private methods\n\n /** Called after updateState to perform common tasks */\n // eslint-disable-next-line complexity\n protected _postUpdate(updateParams: UpdateParameters>, forceUpdate: boolean) {\n const {props, oldProps} = updateParams;\n\n // Note: Automatic instance count update only works for single layers\n const model = this.state.model as Model | undefined;\n if (model?.isInstanced) {\n model.setInstanceCount(this.getNumInstances());\n }\n\n // Set picking module parameters to match props\n const {autoHighlight, highlightedObjectIndex, highlightColor} = props;\n if (\n forceUpdate ||\n oldProps.autoHighlight !== autoHighlight ||\n oldProps.highlightedObjectIndex !== highlightedObjectIndex ||\n oldProps.highlightColor !== highlightColor\n ) {\n const picking: PickingProps = {};\n\n if (Array.isArray(highlightColor)) {\n picking.highlightColor = highlightColor as [number, number, number];\n }\n\n // highlightedObjectIndex will overwrite any settings from auto highlighting.\n // Do not reset unless the value has changed.\n if (\n forceUpdate ||\n oldProps.autoHighlight !== autoHighlight ||\n highlightedObjectIndex !== oldProps.highlightedObjectIndex\n ) {\n picking.highlightedObjectColor =\n Number.isFinite(highlightedObjectIndex) && (highlightedObjectIndex as number) >= 0\n ? this.encodePickingColor(highlightedObjectIndex)\n : null;\n }\n\n this.setShaderModuleProps({picking});\n }\n }\n\n private _getUpdateParams(): UpdateParameters> {\n return {\n props: this.props,\n // @ts-ignore TS2531 this method can only be called internally with internalState assigned\n oldProps: this.internalState.getOldProps() as PropsT,\n context: this.context,\n // @ts-ignore TS2531 this method can only be called internally with internalState assigned\n changeFlags: this.internalState.changeFlags\n };\n }\n\n /** Checks state of attributes and model */\n private _getNeedsRedraw(opts: {clearRedrawFlags: boolean}): string | false {\n // this method may be called by the render loop as soon a the layer\n // has been created, so guard against uninitialized state\n if (!this.internalState) {\n return false;\n }\n\n let redraw: string | false = false;\n redraw = redraw || (this.internalState.needsRedraw && this.id);\n\n // TODO - is attribute manager needed? - Model should be enough.\n const attributeManager = this.getAttributeManager();\n const attributeManagerNeedsRedraw = attributeManager\n ? attributeManager.getNeedsRedraw(opts)\n : false;\n redraw = redraw || attributeManagerNeedsRedraw;\n\n if (redraw) {\n for (const extension of this.props.extensions) {\n extension.onNeedsRedraw.call(this, extension);\n }\n }\n\n this.internalState.needsRedraw = this.internalState.needsRedraw && !opts.clearRedrawFlags;\n return redraw;\n }\n\n /** Callback when asyn prop is loaded */\n private _onAsyncPropUpdated(): void {\n // @ts-ignore TS2531 this method can only be called internally with internalState assigned\n this._diffProps(this.props, this.internalState.getOldProps());\n this.setNeedsUpdate();\n }\n}\n\nfunction splitWebGPUDrawParameters(parameters: LumaParameters): {\n pipelineParameters: LumaParameters;\n renderPassParameters?: {blendConstant: [number, number, number, number]};\n} {\n const {blendConstant, ...pipelineParameters} = parameters as LumaParameters & {\n blendConstant?: [number, number, number, number];\n };\n\n return blendConstant\n ? {\n pipelineParameters,\n renderPassParameters: {blendConstant}\n }\n : {pipelineParameters};\n}\n\nfunction applyModelParameters(\n models: Model[],\n renderPass: RenderPass,\n parameters: LumaParameters,\n webGPUDrawParameters: ReturnType | null\n): void {\n for (const model of models) {\n if (model.device.type === 'webgpu') {\n syncModelAttachmentFormats(model, renderPass);\n // TODO(ibgreen): model.setParameters currently wipes parameters. Semantics TBD.\n model.setParameters({\n ...model.parameters,\n ...webGPUDrawParameters?.pipelineParameters\n });\n } else {\n model.setParameters(parameters);\n }\n }\n}\n\nfunction syncModelAttachmentFormats(model: Model, renderPass: RenderPass): void {\n const framebuffer =\n renderPass.props.framebuffer ||\n ((\n renderPass as RenderPass & {\n framebuffer?: {\n colorAttachments: Array<{texture: {format: string}}>;\n depthStencilAttachment: {texture: {format: string}} | null;\n };\n }\n ).framebuffer ??\n null);\n\n if (!framebuffer) {\n return;\n }\n\n const colorAttachmentFormats = framebuffer.colorAttachments.map(\n attachment => attachment?.texture?.format ?? null\n );\n const depthStencilAttachmentFormat = framebuffer.depthStencilAttachment?.texture?.format;\n\n const modelWithProps = model as unknown as {\n props: {\n colorAttachmentFormats?: (string | null)[];\n depthStencilAttachmentFormat?: string;\n };\n _setPipelineNeedsUpdate(reason: string): void;\n };\n\n if (\n !equalAttachmentFormats(modelWithProps.props.colorAttachmentFormats, colorAttachmentFormats) ||\n modelWithProps.props.depthStencilAttachmentFormat !== depthStencilAttachmentFormat\n ) {\n modelWithProps.props.colorAttachmentFormats = colorAttachmentFormats;\n modelWithProps.props.depthStencilAttachmentFormat = depthStencilAttachmentFormat;\n modelWithProps._setPipelineNeedsUpdate('attachment formats');\n }\n}\n\nfunction equalAttachmentFormats(left?: (string | null)[], right?: (string | null)[]): boolean {\n if (left === right) {\n return true;\n }\n if (!left || !right || left.length !== right.length) {\n return false;\n }\n for (let i = 0; i < left.length; i++) {\n if (left[i] !== right[i]) {\n return false;\n }\n }\n return true;\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {lerp} from '@math.gl/core';\nimport Transition from './transition';\n\nexport default class CPUInterpolationTransition extends Transition {\n _value;\n\n get value() {\n return this._value;\n }\n\n _onUpdate() {\n const {\n time,\n settings: {fromValue, toValue, duration, easing}\n } = this;\n const t = easing(time / duration);\n this._value = lerp(fromValue, toValue, t);\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport Transition from './transition';\n\nconst EPSILON = 1e-5;\n\n/*\n * Calculate the next value in the spring transition\n * @param prev {Number} - previous value\n * @param cur {Number} - current value\n * @param dest {Number} - destination value\n * @param damping {Number}\n * @param stiffness {Number}\n */\nfunction updateSpringElement(\n prev: number,\n cur: number,\n dest: number,\n damping: number,\n stiffness: number\n): number {\n const velocity = cur - prev;\n const delta = dest - cur;\n const spring = delta * stiffness;\n const damper = -velocity * damping;\n return spring + damper + velocity + cur;\n}\n\n/*\n * Calculate the next value in the spring transition\n * @param prev {Number|Array} - previous value\n * @param cur {Number|Array} - current value\n * @param dest {Number|Array} - destination value\n * @param damping {Number}\n * @param stiffness {Number}\n */\nfunction updateSpring(prev: number, cur: number, dest: number, damping: number, stiffness: number);\nfunction updateSpring(\n prev: number[],\n cur: number[],\n dest: number[],\n damping: number,\n stiffness: number\n): number[];\n\nfunction updateSpring(\n prev: number | number[],\n cur: number | number[],\n dest: number | number[],\n damping: number,\n stiffness: number\n): number | number[] {\n if (Array.isArray(dest)) {\n const next: number[] = [];\n for (let i = 0; i < dest.length; i++) {\n next[i] = updateSpringElement(prev[i], cur[i], dest[i], damping, stiffness);\n }\n return next;\n }\n return updateSpringElement(prev as number, cur as number, dest, damping, stiffness);\n}\n\n/*\n * Calculate the distance between two numbers or two vectors\n */\nfunction distance(value1, value2) {\n if (Array.isArray(value1)) {\n let distanceSquare = 0;\n for (let i = 0; i < value1.length; i++) {\n const d = value1[i] - value2[i];\n distanceSquare += d * d;\n }\n return Math.sqrt(distanceSquare);\n }\n return Math.abs(value1 - value2);\n}\n\nexport default class CPUSpringTransition extends Transition {\n _prevValue;\n _currValue;\n\n get value() {\n return this._currValue;\n }\n\n _onUpdate() {\n // TODO - use timeline\n // const {time} = this;\n\n const {fromValue, toValue, damping, stiffness} = this.settings;\n const {_prevValue = fromValue, _currValue = fromValue} = this;\n let nextValue = updateSpring(_prevValue, _currValue, toValue, damping, stiffness);\n const delta = distance(nextValue, toValue);\n const velocity = distance(nextValue, _currValue);\n\n if (delta < EPSILON && velocity < EPSILON) {\n nextValue = toValue;\n this.end();\n }\n\n this._prevValue = _currValue;\n this._currValue = nextValue;\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {normalizeTransitionSettings} from './attribute/transition-settings';\nimport CPUInterpolationTransition from '../transitions/cpu-interpolation-transition';\nimport CPUSpringTransition from '../transitions/cpu-spring-transition';\nimport log from '../utils/log';\n\nconst TRANSITION_TYPES = {\n interpolation: CPUInterpolationTransition,\n spring: CPUSpringTransition\n};\n\nexport default class UniformTransitionManager {\n transitions = new Map();\n timeline;\n\n constructor(timeline) {\n this.timeline = timeline;\n }\n\n get active() {\n return this.transitions.size > 0;\n }\n\n add(key, fromValue, toValue, settings) {\n const {transitions} = this;\n if (transitions.has(key)) {\n const transition = transitions.get(key);\n // value may not be available if `update()` has not been called. Fallback to `fromValue`\n const {value = transition.settings.fromValue} = transition;\n // start from interrupted position\n fromValue = value;\n this.remove(key);\n }\n\n settings = normalizeTransitionSettings(settings);\n if (!settings) {\n return;\n }\n\n const TransitionType = TRANSITION_TYPES[settings.type];\n if (!TransitionType) {\n log.error(`unsupported transition type '${settings.type}'`)();\n return;\n }\n const transition = new TransitionType(this.timeline);\n transition.start({\n ...settings,\n fromValue,\n toValue\n });\n transitions.set(key, transition);\n }\n\n remove(key) {\n const {transitions} = this;\n if (transitions.has(key)) {\n transitions.get(key).cancel();\n transitions.delete(key);\n }\n }\n\n update() {\n const propsInTransition = {};\n\n for (const [key, transition] of this.transitions) {\n transition.update();\n propsInTransition[key] = transition.value;\n if (!transition.inProgress) {\n // transition ended\n this.remove(key);\n }\n }\n\n return propsInTransition;\n }\n\n clear() {\n for (const key of this.transitions.keys()) {\n this.remove(key);\n }\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {PROP_TYPES_SYMBOL} from './constants';\n\nexport function validateProps(props) {\n const propTypes = props[PROP_TYPES_SYMBOL];\n\n for (const propName in propTypes) {\n const propType = propTypes[propName];\n const {validate} = propType;\n if (validate && !validate(props[propName], propType)) {\n throw new Error(`Invalid prop ${propName}: ${props[propName]}`);\n }\n }\n}\n\n// Returns an object with \"change flags\", either false or strings indicating reason for change\nexport function diffProps(\n props,\n oldProps\n): {\n dataChanged: string | false | {startRow: number; endRow?: number}[];\n propsChanged: string | false;\n updateTriggersChanged: Record | false;\n extensionsChanged: boolean;\n transitionsChanged: Record | false;\n} {\n // First check if any props have changed (ignore props that will be examined separately)\n const propsChangedReason = compareProps({\n newProps: props,\n oldProps,\n propTypes: props[PROP_TYPES_SYMBOL],\n ignoreProps: {data: null, updateTriggers: null, extensions: null, transitions: null}\n });\n\n // Now check if any data related props have changed\n const dataChangedReason = diffDataProps(props, oldProps);\n\n // Check update triggers to determine if any attributes need regeneration\n // Note - if data has changed, all attributes will need regeneration, so skip this step\n let updateTriggersChangedReason: false | string | Record = false;\n if (!dataChangedReason) {\n updateTriggersChangedReason = diffUpdateTriggers(props, oldProps);\n }\n\n return {\n dataChanged: dataChangedReason,\n propsChanged: propsChangedReason,\n updateTriggersChanged: updateTriggersChangedReason,\n extensionsChanged: diffExtensions(props, oldProps),\n transitionsChanged: diffTransitions(props, oldProps)\n };\n}\n\nfunction diffTransitions(props, oldProps): false | Record {\n if (!props.transitions) {\n return false;\n }\n const result: Record = {};\n const propTypes = props[PROP_TYPES_SYMBOL];\n let changed = false;\n\n for (const key in props.transitions) {\n const propType = propTypes[key];\n const type = propType && propType.type;\n const isTransitionable = type === 'number' || type === 'color' || type === 'array';\n if (isTransitionable && comparePropValues(props[key], oldProps[key], propType)) {\n result[key] = true;\n changed = true;\n }\n }\n return changed ? result : false;\n}\n\n/**\n * Performs equality by iterating through keys on an object and returning false\n * when any key has values which are not strictly equal between the arguments.\n * @param {Object} opt.oldProps - object with old key/value pairs\n * @param {Object} opt.newProps - object with new key/value pairs\n * @param {Object} opt.ignoreProps={} - object, keys that should not be compared\n * @returns {null|String} - null when values of all keys are strictly equal.\n * if unequal, returns a string explaining what changed.\n */\n/* eslint-disable max-statements, max-depth, complexity */\n/*\n * Note: for better performance, this function assumes that both oldProps and newProps\n inherit the same prototype (defaultProps). That is, if neither object contains own\n property , assume `oldProps.` and `newProps.` are equal.\n */\nexport function compareProps({\n newProps,\n oldProps,\n ignoreProps = {},\n propTypes = {},\n triggerName = 'props'\n}): string | false {\n // shallow equality => deep equality\n if (oldProps === newProps) {\n return false;\n }\n\n // TODO - do we need these checks? Should never happen...\n if (typeof newProps !== 'object' || newProps === null) {\n return `${triggerName} changed shallowly`;\n }\n\n if (typeof oldProps !== 'object' || oldProps === null) {\n return `${triggerName} changed shallowly`;\n }\n\n // Compare explicitly defined new props against old/default values\n for (const key of Object.keys(newProps)) {\n if (!(key in ignoreProps)) {\n if (!(key in oldProps)) {\n return `${triggerName}.${key} added`;\n }\n const changed = comparePropValues(newProps[key], oldProps[key], propTypes[key]);\n if (changed) {\n return `${triggerName}.${key} ${changed}`;\n }\n }\n }\n\n // Test if any old props have been dropped\n for (const key of Object.keys(oldProps)) {\n if (!(key in ignoreProps)) {\n if (!(key in newProps)) {\n return `${triggerName}.${key} dropped`;\n }\n if (!Object.hasOwnProperty.call(newProps, key)) {\n // Compare dropped old prop against default value\n const changed = comparePropValues(newProps[key], oldProps[key], propTypes[key]);\n if (changed) {\n return `${triggerName}.${key} ${changed}`;\n }\n }\n }\n }\n\n return false;\n}\n/* eslint-enable max-statements, max-depth, complexity */\n\n// HELPERS\nfunction comparePropValues(newProp, oldProp, propType) {\n // If prop type has an equal function, invoke it\n let equal = propType && propType.equal;\n if (equal && !equal(newProp, oldProp, propType)) {\n return 'changed deeply';\n }\n\n if (!equal) {\n // If object has an equals function, invoke it\n equal = newProp && oldProp && newProp.equals;\n if (equal && !equal.call(newProp, oldProp)) {\n return 'changed deeply';\n }\n }\n\n if (!equal && oldProp !== newProp) {\n return 'changed shallowly';\n }\n\n return null;\n}\n\n// The comparison of the data prop requires special handling\n// the dataComparator should be used if supplied\nfunction diffDataProps(props, oldProps): string | false | {startRow: number; endRow?: number}[] {\n if (oldProps === null) {\n return 'oldProps is null, initial diff';\n }\n\n let dataChanged: string | false | {startRow: number; endRow?: number}[] = false;\n // Support optional app defined comparison of data\n const {dataComparator, _dataDiff} = props;\n if (dataComparator) {\n if (!dataComparator(props.data, oldProps.data)) {\n dataChanged = 'Data comparator detected a change';\n }\n // Otherwise, do a shallow equal on props\n } else if (props.data !== oldProps.data) {\n dataChanged = 'A new data container was supplied';\n }\n if (dataChanged && _dataDiff) {\n dataChanged = _dataDiff(props.data, oldProps.data) || dataChanged;\n }\n\n return dataChanged;\n}\n\n// Checks if any update triggers have changed\n// also calls callback to invalidate attributes accordingly.\nfunction diffUpdateTriggers(props, oldProps): Record | false {\n if (oldProps === null) {\n return {all: true};\n }\n\n // If the 'all' updateTrigger fires, ignore testing others\n if ('all' in props.updateTriggers) {\n const diffReason = diffUpdateTrigger(props, oldProps, 'all');\n if (diffReason) {\n return {all: true};\n }\n }\n\n const reason: Record = {};\n let changed = false;\n // If the 'all' updateTrigger didn't fire, need to check all others\n for (const triggerName in props.updateTriggers) {\n if (triggerName !== 'all') {\n const diffReason = diffUpdateTrigger(props, oldProps, triggerName);\n if (diffReason) {\n reason[triggerName] = true;\n changed = true;\n }\n }\n }\n\n return changed ? reason : false;\n}\n\n// Returns true if any extensions have changed\nfunction diffExtensions(props, oldProps): boolean {\n if (oldProps === null) {\n return true;\n }\n\n const oldExtensions = oldProps.extensions;\n const {extensions} = props;\n\n if (extensions === oldExtensions) {\n return false;\n }\n if (!oldExtensions || !extensions) {\n return true;\n }\n if (extensions.length !== oldExtensions.length) {\n return true;\n }\n for (let i = 0; i < extensions.length; i++) {\n if (!extensions[i].equals(oldExtensions[i])) {\n return true;\n }\n }\n return false;\n}\n\nfunction diffUpdateTrigger(props, oldProps, triggerName) {\n let newTriggers = props.updateTriggers[triggerName];\n newTriggers = newTriggers === undefined || newTriggers === null ? {} : newTriggers;\n let oldTriggers = oldProps.updateTriggers[triggerName];\n oldTriggers = oldTriggers === undefined || oldTriggers === null ? {} : oldTriggers;\n const diffReason = compareProps({\n oldProps: oldTriggers,\n newProps: newTriggers,\n triggerName\n });\n return diffReason;\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nconst ERR_NOT_OBJECT = 'count(): argument not an object';\nconst ERR_NOT_CONTAINER = 'count(): argument not a container';\n\n/**\n * Deduces numer of elements in a JavaScript container.\n * - Auto-deduction for ES6 containers that define a count() method\n * - Auto-deduction for ES6 containers that define a size member\n * - Auto-deduction for Classic Arrays via the built-in length attribute\n * - Also handles objects, although note that this an O(N) operation\n */\nexport function count(container: any): number {\n if (!isObject(container)) {\n throw new Error(ERR_NOT_OBJECT);\n }\n\n // Check if ES6 collection \"count\" function is available\n if (typeof container.count === 'function') {\n return container.count();\n }\n\n // Check if ES6 collection \"size\" attribute is set\n if (Number.isFinite(container.size)) {\n return container.size;\n }\n\n // Check if array length attribute is set\n // Note: checking this last since some ES6 collections (Immutable.js)\n // emit profuse warnings when trying to access `length` attribute\n if (Number.isFinite(container.length)) {\n return container.length;\n }\n\n // Note that getting the count of an object is O(N)\n if (isPlainObject(container)) {\n return Object.keys(container).length;\n }\n\n throw new Error(ERR_NOT_CONTAINER);\n}\n\n/**\n * Checks if argument is a plain object (not a class or array etc)\n * @param {*} value - JavaScript value to be tested\n * @return {Boolean} - true if argument is a plain JavaScript object\n */\nfunction isPlainObject(value) {\n return value !== null && typeof value === 'object' && value.constructor === Object;\n}\n\n/**\n * Checks if argument is an indexable object (not a primitive value, nor null)\n * @param {*} value - JavaScript value to be tested\n * @return {Boolean} - true if argument is a JavaScript object\n */\nfunction isObject(value) {\n return value !== null && typeof value === 'object';\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// Merge two luma.gl shader descriptors\nexport function mergeShaders(target, source) {\n if (!source) {\n return target;\n }\n const result = {...target, ...source};\n\n if ('defines' in source) {\n result.defines = {...target.defines, ...source.defines};\n }\n if ('modules' in source) {\n result.modules = (target.modules || []).concat(source.modules);\n\n // Hack: prject32 and project64 cannot co-exist\n if (source.modules.some(module => module.name === 'project64')) {\n const index = result.modules.findIndex(module => module.name === 'project32');\n if (index >= 0) {\n result.modules.splice(index, 1);\n }\n }\n }\n if ('inject' in source) {\n if (!target.inject) {\n result.inject = source.inject;\n } else {\n const mergedInjection = {...target.inject};\n for (const key in source.inject) {\n mergedInjection[key] = (mergedInjection[key] || '') + source.inject[key];\n }\n result.inject = mergedInjection;\n }\n }\n return result;\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Device, Texture, SamplerProps} from '@luma.gl/core';\n\nconst DEFAULT_TEXTURE_PARAMETERS: SamplerProps = {\n minFilter: 'linear',\n mipmapFilter: 'linear',\n magFilter: 'linear',\n addressModeU: 'clamp-to-edge',\n addressModeV: 'clamp-to-edge'\n};\n\n// Track the textures that are created by us. They need to be released when they are no longer used.\nconst internalTextures: Record = {};\n\n/**\n *\n * @param owner\n * @param device\n * @param image could be one of:\n * - Texture\n * - Browser object: Image, ImageData, ImageData, HTMLCanvasElement, HTMLVideoElement, ImageBitmap\n * - Plain object: {width: , height: , data: }\n * @param parameters\n * @returns\n */\nexport function createTexture(\n owner: string,\n device: Device,\n image: any,\n sampler: SamplerProps\n): Texture | null {\n if (image instanceof Texture) {\n return image;\n } else if (image.constructor && image.constructor.name !== 'Object') {\n // Browser object\n image = {data: image};\n }\n\n let samplerParameters: SamplerProps | null = null;\n if (image.compressed) {\n samplerParameters = {\n minFilter: 'linear',\n mipmapFilter: image.data.length > 1 ? 'nearest' : 'linear'\n };\n }\n\n const {width, height} = image.data;\n const texture = device.createTexture({\n ...image,\n sampler: {\n ...DEFAULT_TEXTURE_PARAMETERS,\n ...samplerParameters,\n ...sampler\n },\n mipLevels: device.getMipLevelCount(width, height)\n });\n if (device.type === 'webgl') {\n texture.generateMipmapsWebGL();\n } else if (device.type === 'webgpu') {\n device.generateMipmapsWebGPU(texture);\n }\n\n // Track this texture\n internalTextures[texture.id] = owner;\n return texture;\n}\n\nexport function destroyTexture(owner: string, texture: Texture) {\n if (!texture || !(texture instanceof Texture)) {\n return;\n }\n // Only delete the texture if requested by the same layer that created it\n if (internalTextures[texture.id] === owner) {\n texture.delete();\n delete internalTextures[texture.id];\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {createTexture, destroyTexture} from '../utils/texture';\nimport {deepEqual} from '../utils/deep-equal';\n\nimport type Component from './component';\nimport type {Color, TextureSource} from '../types/layer-props';\nimport type Layer from '../lib/layer';\nimport type {SamplerProps} from '@luma.gl/core';\n\ntype BasePropType = {\n value: ValueT;\n async?: boolean;\n validate?: (value: any, propType: PropType) => boolean;\n equal?: (value1: ValueT, value2: ValueT, propType: PropType) => boolean;\n};\n\n/**\n * Normalized prop type definition\n */\nexport type PropType = BasePropType & {\n type: string;\n name: string;\n transform?: (value: any, propType: PropType, component: Component) => any;\n release?: (value: any, propType: PropType, component: Component) => void;\n};\n\ntype DefaultProp =\n | T\n | DeprecatedProp\n | BooleanPropType\n | NumberPropType\n | ColorPropType\n | ImagePropType\n | DataPropType\n | ArrayPropType\n | ObjectPropType\n | AccessorPropType\n | FunctionPropType;\n\nexport type DefaultProps = {\n [propName in keyof PropsT]?: DefaultProp[propName]>;\n};\n\ntype BooleanPropType = BasePropType & {\n type: 'boolean';\n};\ntype NumberPropType = BasePropType & {\n type: 'number';\n min?: number;\n max?: number;\n};\ntype ColorPropType = BasePropType & {\n type: 'color';\n optional?: boolean;\n};\ntype ArrayPropType = BasePropType & {\n type: 'array';\n optional?: boolean;\n /** Ignore change in the prop value.\n * @default false\n */\n ignore?: boolean;\n /** Deep-compare two prop values. Only used if `ignore: false`.\n * When a number is supplied, used as the depth of deep-comparison. 0 is equivalent to shallow comparison, -1 is infinite depth\n * When a boolean is supplied, `true` is equivalent to `1` (shallow compare all child fields)\n * @default false\n */\n compare?: boolean | number;\n};\ntype AccessorPropType = BasePropType & {\n type: 'accessor';\n};\ntype FunctionPropType = BasePropType & {\n type: 'function';\n optional?: boolean;\n /** @deprecated use `ignore` instead */\n compare?: boolean;\n /** Ignore change in the prop value.\n * @default true\n */\n ignore?: boolean;\n};\ntype DataPropType = BasePropType & {\n type: 'data';\n};\ntype ImagePropType = BasePropType & {\n type: 'image';\n parameters?: SamplerProps;\n};\ntype ObjectPropType = BasePropType & {\n type: 'object';\n optional?: boolean;\n /** Ignore change in the prop value.\n * @default false\n */\n ignore?: boolean;\n /** Deep-compare two prop values. Only used if `ignore: false`.\n * When a number is supplied, used as the depth of deep-comparison. 0 is equivalent to shallow comparison, -1 is infinite depth\n * When a boolean is supplied, `true` is equivalent to `1` (shallow compare all child fields)\n * @default false\n */\n compare?: boolean | number;\n};\ntype DeprecatedProp = {\n deprecatedFor?: string | string[];\n};\ntype PropTypeDef =\n | DeprecatedProp\n | boolean\n | BooleanPropType\n | number\n | NumberPropType\n | string\n | DataPropType\n | number[]\n | ColorPropType\n | ArrayPropType\n | AccessorPropType\n | FunctionPropType\n | ImagePropType\n | ObjectPropType\n | null;\n\nconst TYPE_DEFINITIONS = {\n boolean: {\n validate(value, propType: BooleanPropType) {\n return true;\n },\n equal(value1, value2, propType: BooleanPropType) {\n return Boolean(value1) === Boolean(value2);\n }\n },\n number: {\n validate(value, propType: NumberPropType) {\n return (\n Number.isFinite(value) &&\n (!('max' in propType) || value <= propType.max!) &&\n (!('min' in propType) || value >= propType.min!)\n );\n }\n },\n color: {\n validate(value, propType: ColorPropType) {\n return (\n (propType.optional && !value) ||\n (isArray(value) && (value.length === 3 || value.length === 4))\n );\n },\n equal(value1, value2, propType: ColorPropType) {\n return deepEqual(value1, value2, 1);\n }\n },\n accessor: {\n validate(value, propType: AccessorPropType) {\n const valueType = getTypeOf(value);\n return valueType === 'function' || valueType === getTypeOf(propType.value);\n },\n equal(value1, value2, propType: AccessorPropType) {\n if (typeof value2 === 'function') {\n return true;\n }\n return deepEqual(value1, value2, 1);\n }\n },\n array: {\n validate(value, propType: ArrayPropType) {\n return (propType.optional && !value) || isArray(value);\n },\n equal(value1, value2, propType: ArrayPropType) {\n const {compare} = propType;\n const depth = Number.isInteger(compare as unknown) ? (compare as number) : compare ? 1 : 0;\n return compare ? deepEqual(value1, value2, depth) : value1 === value2;\n }\n },\n object: {\n equal(value1, value2, propType: ObjectPropType) {\n if (propType.ignore) {\n return true;\n }\n const {compare} = propType;\n const depth = Number.isInteger(compare as unknown) ? (compare as number) : compare ? 1 : 0;\n return compare ? deepEqual(value1, value2, depth) : value1 === value2;\n }\n },\n function: {\n validate(value, propType: FunctionPropType) {\n return (propType.optional && !value) || typeof value === 'function';\n },\n equal(value1, value2, propType: FunctionPropType) {\n // Backward compatibility - {compare: true} and {ignore: false} are equivalent\n const shouldIgnore = !propType.compare && propType.ignore !== false;\n return shouldIgnore || value1 === value2;\n }\n },\n data: {\n transform: (value, propType: DataPropType, component) => {\n if (!value) {\n return value;\n }\n const {dataTransform} = component.props;\n if (dataTransform) {\n return dataTransform(value);\n }\n // Detect loaders.gl v4 table format\n if (\n typeof value.shape === 'string' &&\n value.shape.endsWith('-table') &&\n Array.isArray(value.data)\n ) {\n return value.data;\n }\n return value;\n }\n },\n image: {\n transform: (value, propType: ImagePropType, component) => {\n const context = (component as Layer).context;\n if (!context || !context.device) {\n return null;\n }\n return createTexture(component.id, context.device, value, {\n ...propType.parameters,\n ...component.props.textureParameters\n });\n },\n release: (value, propType: ImagePropType, component) => {\n destroyTexture(component.id, value);\n }\n }\n} as const;\n\nexport function parsePropTypes(propDefs: Record): {\n propTypes: Record;\n defaultProps: Record;\n deprecatedProps: Record;\n} {\n const propTypes = {};\n const defaultProps = {};\n const deprecatedProps = {};\n\n for (const [propName, propDef] of Object.entries(propDefs)) {\n const deprecated = (propDef as DeprecatedProp)?.deprecatedFor;\n if (deprecated) {\n deprecatedProps[propName] = Array.isArray(deprecated) ? deprecated : [deprecated];\n } else {\n const propType = parsePropType(propName, propDef);\n propTypes[propName] = propType;\n defaultProps[propName] = propType.value;\n }\n }\n return {propTypes, defaultProps, deprecatedProps};\n}\n\n// Parses one property definition entry. Either contains:\n// * a valid prop type object ({type, ...})\n// * or just a default value, in which case type and name inference is used\nfunction parsePropType(name: string, propDef: PropTypeDef): PropType {\n switch (getTypeOf(propDef)) {\n case 'object':\n return normalizePropDefinition(name, propDef);\n\n case 'array':\n return normalizePropDefinition(name, {type: 'array', value: propDef, compare: false});\n\n case 'boolean':\n return normalizePropDefinition(name, {type: 'boolean', value: propDef});\n\n case 'number':\n return normalizePropDefinition(name, {type: 'number', value: propDef});\n\n case 'function':\n // return guessFunctionType(name, propDef);\n return normalizePropDefinition(name, {type: 'function', value: propDef, compare: true});\n\n default:\n return {name, type: 'unknown', value: propDef};\n }\n}\n\nfunction normalizePropDefinition(name, propDef): PropType {\n if (!('type' in propDef)) {\n if (!('value' in propDef)) {\n // If no type and value this object is likely the value\n return {name, type: 'object', value: propDef};\n }\n return {name, type: getTypeOf(propDef.value), ...propDef};\n }\n return {name, ...TYPE_DEFINITIONS[propDef.type], ...propDef};\n}\n\nfunction isArray(value: any): boolean {\n return Array.isArray(value) || ArrayBuffer.isView(value);\n}\n\n// improved version of javascript typeof that can distinguish arrays and null values\nfunction getTypeOf(value: any): string {\n if (isArray(value)) {\n return 'array';\n }\n if (value === null) {\n return 'null';\n }\n return typeof value;\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport log from '../utils/log';\nimport {isAsyncIterable} from '../utils/iterable-utils';\nimport {parsePropTypes} from './prop-types';\nimport {\n COMPONENT_SYMBOL,\n PROP_TYPES_SYMBOL,\n DEPRECATED_PROPS_SYMBOL,\n ASYNC_ORIGINAL_SYMBOL,\n ASYNC_RESOLVED_SYMBOL,\n ASYNC_DEFAULTS_SYMBOL\n} from './constants';\nimport {StatefulComponentProps} from './component';\nimport Component from './component';\n\n// Create a property object\nexport function createProps(\n component: Component,\n propObjects: Partial[]\n): StatefulComponentProps {\n // Resolve extension value\n let extensions: any[] | undefined;\n for (let i = propObjects.length - 1; i >= 0; i--) {\n const props = propObjects[i];\n if ('extensions' in props) {\n // @ts-expect-error TS(2339) extensions not defined\n extensions = props.extensions;\n }\n }\n\n // Create a new prop object with empty default props object\n const propsPrototype = getPropsPrototype(component.constructor, extensions);\n // The true default props object will be found later\n const propsInstance = Object.create(propsPrototype);\n\n // Props need a back pointer to the owning component\n propsInstance[COMPONENT_SYMBOL] = component;\n // The supplied (original) values for those async props that are set to url strings or Promises.\n // In this case, the actual (i.e. resolved) values are looked up from component.internalState\n propsInstance[ASYNC_ORIGINAL_SYMBOL] = {};\n // Note: the actual (resolved) values for props that are NOT set to urls or Promises.\n // in this case the values are served directly from this map\n propsInstance[ASYNC_RESOLVED_SYMBOL] = {};\n\n // \"Copy\" all sync props\n for (let i = 0; i < propObjects.length; ++i) {\n const props = propObjects[i];\n // Do not use Object.assign here to avoid Symbols in props overwriting our private fields\n // This might happen if one of the arguments is another props instance\n for (const key in props) {\n propsInstance[key] = props[key];\n }\n }\n\n // Props must be immutable\n Object.freeze(propsInstance);\n\n return propsInstance;\n}\n\nconst MergedDefaultPropsCacheKey = '_mergedDefaultProps';\n\n// Return precalculated defaultProps and propType objects if available\n// build them if needed\nfunction getPropsPrototype(componentClass, extensions?: any[]) {\n // Bail out if we're not looking at a component - for two reasons:\n // 1. There's no reason for an ancestor of component to have props\n // 2. If we don't bail out, we'll follow the prototype chain all the way back to the global\n // function prototype and add _mergedDefaultProps to it, which may break other frameworks\n // (e.g. the react-three-fiber reconciler)\n if (!(componentClass instanceof Component.constructor)) return {};\n\n // A string that uniquely identifies the extensions involved\n let cacheKey = MergedDefaultPropsCacheKey;\n if (extensions) {\n for (const extension of extensions) {\n const ExtensionClass = extension.constructor;\n if (ExtensionClass) {\n cacheKey += `:${ExtensionClass.extensionName || ExtensionClass.name}`;\n }\n }\n }\n\n const defaultProps = getOwnProperty(componentClass, cacheKey);\n if (!defaultProps) {\n return (componentClass[cacheKey] = createPropsPrototypeAndTypes(\n componentClass,\n extensions || []\n ));\n }\n return defaultProps;\n}\n\n// Build defaultProps and propType objects by walking component prototype chain\nfunction createPropsPrototypeAndTypes(\n componentClass,\n extensions: any[]\n): Record | null {\n const parent = componentClass.prototype;\n if (!parent) {\n return null;\n }\n\n const parentClass = Object.getPrototypeOf(componentClass);\n const parentDefaultProps = getPropsPrototype(parentClass);\n\n // Parse propTypes from Component.defaultProps\n const componentDefaultProps = getOwnProperty(componentClass, 'defaultProps') || {};\n const componentPropDefs = parsePropTypes(componentDefaultProps);\n\n // Merged default props object. Order: parent, self, extensions\n const defaultProps: any = Object.assign(\n Object.create(null),\n parentDefaultProps,\n componentPropDefs.defaultProps\n );\n // Merged prop type definitions. Order: parent, self, extensions\n const propTypes = Object.assign(\n Object.create(null),\n parentDefaultProps?.[PROP_TYPES_SYMBOL],\n componentPropDefs.propTypes\n );\n // Merged deprecation list. Order: parent, self, extensions\n const deprecatedProps = Object.assign(\n Object.create(null),\n parentDefaultProps?.[DEPRECATED_PROPS_SYMBOL],\n componentPropDefs.deprecatedProps\n );\n\n for (const extension of extensions) {\n const extensionDefaultProps = getPropsPrototype(extension.constructor);\n if (extensionDefaultProps) {\n Object.assign(defaultProps, extensionDefaultProps);\n Object.assign(propTypes, extensionDefaultProps[PROP_TYPES_SYMBOL]);\n Object.assign(deprecatedProps, extensionDefaultProps[DEPRECATED_PROPS_SYMBOL]);\n }\n }\n\n // Create any necessary property descriptors and create the default prop object\n // Assign merged default props\n createPropsPrototype(defaultProps, componentClass);\n\n // Add getters/setters for async props\n addAsyncPropsToPropPrototype(defaultProps, propTypes);\n\n // Add setters for deprecated props\n addDeprecatedPropsToPropPrototype(defaultProps, deprecatedProps);\n\n // Store the precalculated props\n defaultProps[PROP_TYPES_SYMBOL] = propTypes;\n defaultProps[DEPRECATED_PROPS_SYMBOL] = deprecatedProps;\n\n // Backwards compatibility\n // TODO: remove access of hidden property from the rest of the code base\n if (extensions.length === 0 && !hasOwnProperty(componentClass, '_propTypes')) {\n componentClass._propTypes = propTypes;\n }\n return defaultProps;\n}\n\n// Builds a pre-merged default props object that component props can inherit from\nfunction createPropsPrototype(defaultProps, componentClass) {\n // Avoid freezing `id` prop\n const id = getComponentName(componentClass);\n\n Object.defineProperties(defaultProps, {\n // `id` is treated specially because layer might need to override it\n id: {\n writable: true,\n value: id\n }\n });\n}\n\nfunction addDeprecatedPropsToPropPrototype(defaultProps, deprecatedProps) {\n for (const propName in deprecatedProps) {\n /* eslint-disable accessor-pairs */\n Object.defineProperty(defaultProps, propName, {\n enumerable: false,\n set(newValue) {\n const nameStr = `${this.id}: ${propName}`;\n\n for (const newPropName of deprecatedProps[propName]) {\n if (!hasOwnProperty(this, newPropName)) {\n this[newPropName] = newValue;\n }\n }\n\n log.deprecated(nameStr, deprecatedProps[propName].join('/'))();\n }\n });\n /* eslint-enable accessor-pairs */\n }\n}\n\n// Create descriptors for overridable props\nfunction addAsyncPropsToPropPrototype(defaultProps, propTypes) {\n const defaultValues = {};\n\n const descriptors = {};\n\n // Move async props into shadow values\n for (const propName in propTypes) {\n const propType = propTypes[propName];\n const {name, value} = propType;\n\n // Note: async is ES7 keyword, can't destructure\n if (propType.async) {\n defaultValues[name] = value;\n descriptors[name] = getDescriptorForAsyncProp(name);\n }\n }\n\n // Default \"resolved\" values for async props, returned if value not yet resolved/set.\n defaultProps[ASYNC_DEFAULTS_SYMBOL] = defaultValues;\n // Shadowed object, just to make sure \"early indexing\" into the instance does not fail\n defaultProps[ASYNC_ORIGINAL_SYMBOL] = {};\n\n Object.defineProperties(defaultProps, descriptors);\n}\n\n// Helper: Configures getter and setter for one async prop\nfunction getDescriptorForAsyncProp(name) {\n return {\n enumerable: true,\n // Save the provided value for async props in a special map\n set(newValue) {\n if (\n typeof newValue === 'string' ||\n newValue instanceof Promise ||\n isAsyncIterable(newValue)\n ) {\n this[ASYNC_ORIGINAL_SYMBOL][name] = newValue;\n } else {\n this[ASYNC_RESOLVED_SYMBOL][name] = newValue;\n }\n },\n // Only the component's state knows the true value of async prop\n get() {\n if (this[ASYNC_RESOLVED_SYMBOL]) {\n // Prop value isn't async, so just return it\n if (name in this[ASYNC_RESOLVED_SYMBOL]) {\n const value = this[ASYNC_RESOLVED_SYMBOL][name];\n\n return value || this[ASYNC_DEFAULTS_SYMBOL][name];\n }\n\n if (name in this[ASYNC_ORIGINAL_SYMBOL]) {\n // It's an async prop value: look into component state\n const state = this[COMPONENT_SYMBOL] && this[COMPONENT_SYMBOL].internalState;\n if (state && state.hasAsyncProp(name)) {\n return state.getAsyncProp(name) || this[ASYNC_DEFAULTS_SYMBOL][name];\n }\n }\n }\n\n // the prop is not supplied, or\n // component not yet initialized/matched, return the component's default value for the prop\n return this[ASYNC_DEFAULTS_SYMBOL][name];\n }\n };\n}\n\n// HELPER METHODS\n\nfunction hasOwnProperty(object, prop) {\n return Object.prototype.hasOwnProperty.call(object, prop);\n}\n\n// Constructors have their super class constructors as prototypes\nfunction getOwnProperty(object, prop) {\n return hasOwnProperty(object, prop) && object[prop];\n}\n\nfunction getComponentName(componentClass) {\n const componentName = componentClass.componentName;\n if (!componentName) {\n log.warn(`${componentClass.name}.componentName not specified`)();\n }\n return componentName || componentClass.name;\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {\n COMPONENT_SYMBOL,\n PROP_TYPES_SYMBOL,\n ASYNC_ORIGINAL_SYMBOL,\n ASYNC_RESOLVED_SYMBOL,\n ASYNC_DEFAULTS_SYMBOL\n} from './constants';\nimport {PropType} from './prop-types';\nimport {createProps} from './create-props';\n\nlet counter = 0;\n\nexport type StatefulComponentProps = PropsT & {\n id: string;\n [COMPONENT_SYMBOL]: Component;\n [PROP_TYPES_SYMBOL]: Record;\n [ASYNC_DEFAULTS_SYMBOL]: Partial;\n [ASYNC_ORIGINAL_SYMBOL]: Partial;\n [ASYNC_RESOLVED_SYMBOL]: Partial;\n};\n\nexport default class Component {\n static componentName: string = 'Component';\n static defaultProps: Readonly<{}> = {};\n\n id: string;\n props: StatefulComponentProps;\n count: number;\n\n constructor(...propObjects: Partial[]) {\n // Merge supplied props with default props and freeze them.\n /* eslint-disable prefer-spread */\n this.props = createProps(this, propObjects);\n /* eslint-enable prefer-spread */\n\n this.id = this.props.id; // The layer's id, used for matching with layers from last render cycle\n this.count = counter++; // Keep track of how many layer instances you are generating\n }\n\n // clone this layer with modified props\n clone(newProps: Partial) {\n const {props} = this;\n\n // Async props cannot be copied with Object.assign, copy them separately\n const asyncProps: Partial = {};\n\n // See async props definition in create-props.js\n for (const key in props[ASYNC_DEFAULTS_SYMBOL]) {\n if (key in props[ASYNC_RESOLVED_SYMBOL]) {\n asyncProps[key] = props[ASYNC_RESOLVED_SYMBOL][key];\n } else if (key in props[ASYNC_ORIGINAL_SYMBOL]) {\n asyncProps[key] = props[ASYNC_ORIGINAL_SYMBOL][key];\n }\n }\n\n // Some custom layer implementation may not support multiple arguments in the constructor\n // @ts-ignore\n return new this.constructor({...props, ...asyncProps, ...newProps});\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {isAsyncIterable} from '../utils/iterable-utils';\nimport {\n COMPONENT_SYMBOL,\n PROP_TYPES_SYMBOL,\n ASYNC_ORIGINAL_SYMBOL,\n ASYNC_RESOLVED_SYMBOL,\n ASYNC_DEFAULTS_SYMBOL\n} from './constants';\nimport type Component from './component';\nimport {PropType} from './prop-types';\n\nconst EMPTY_PROPS = Object.freeze({});\n\n/** Internal state of an async prop */\ntype AsyncPropState = {\n /** The prop type definition from component.defaultProps, if exists */\n type: PropType | null;\n /** Supplied prop value (can be url/promise, not visible to the component) */\n lastValue: any;\n /** Resolved prop value (valid data, can be \"shown\" to the component) */\n resolvedValue: any;\n /** How many loads have been issued */\n pendingLoadCount: number;\n /** Latest resolved load, (earlier loads will be ignored) */\n resolvedLoadCount: number;\n};\n\nexport default class ComponentState {\n /** The component that this state instance belongs to. `null` if this state has been finalized. */\n component: ComponentT | null;\n onAsyncPropUpdated: (propName: string, value: any) => void;\n\n private asyncProps: Partial>;\n private oldProps: ComponentT['props'] | null;\n private oldAsyncProps: ComponentT['props'] | null;\n\n constructor(component: ComponentT) {\n this.component = component;\n this.asyncProps = {}; // Prop values that the layer sees\n this.onAsyncPropUpdated = () => {};\n this.oldProps = null; // Last props before update\n this.oldAsyncProps = null; // Last props before update, with async values copied.\n }\n\n finalize() {\n for (const propName in this.asyncProps) {\n const asyncProp = this.asyncProps[propName];\n if (asyncProp && asyncProp.type && asyncProp.type.release) {\n // Release any resources created by transforms\n asyncProp.type.release(\n asyncProp.resolvedValue,\n asyncProp.type,\n this.component as Component\n );\n }\n }\n this.asyncProps = {};\n this.component = null;\n this.resetOldProps();\n }\n\n /* Layer-facing props API */\n\n getOldProps(): ComponentT['props'] | typeof EMPTY_PROPS {\n return this.oldAsyncProps || this.oldProps || EMPTY_PROPS;\n }\n\n resetOldProps() {\n this.oldAsyncProps = null;\n this.oldProps = this.component ? this.component.props : null;\n }\n\n // Checks if a prop is overridden\n hasAsyncProp(propName: string): boolean {\n return propName in this.asyncProps;\n }\n\n // Returns value of an overriden prop\n getAsyncProp(propName: string): any {\n const asyncProp = this.asyncProps[propName];\n return asyncProp && asyncProp.resolvedValue;\n }\n\n isAsyncPropLoading(propName?: string): boolean {\n if (propName) {\n const asyncProp = this.asyncProps[propName];\n return Boolean(\n asyncProp &&\n asyncProp.pendingLoadCount > 0 &&\n asyncProp.pendingLoadCount !== asyncProp.resolvedLoadCount\n );\n }\n for (const key in this.asyncProps) {\n if (this.isAsyncPropLoading(key)) {\n return true;\n }\n }\n return false;\n }\n\n // Without changing the original prop value, swap out the data resolution under the hood\n reloadAsyncProp(propName: string, value: any) {\n this._watchPromise(propName, Promise.resolve(value));\n }\n\n // Updates all async/overridden props (when new props come in)\n // Checks if urls have changed, starts loading, or removes override\n setAsyncProps(props: ComponentT['props']) {\n this.component = (props[COMPONENT_SYMBOL] as ComponentT) || this.component;\n\n // NOTE: prop param and default values are only support for testing\n const resolvedValues = props[ASYNC_RESOLVED_SYMBOL] || {};\n const originalValues = props[ASYNC_ORIGINAL_SYMBOL] || props;\n const defaultValues = props[ASYNC_DEFAULTS_SYMBOL] || {};\n\n // TODO - use async props from the layer's prop types\n for (const propName in resolvedValues) {\n const value = resolvedValues[propName];\n this._createAsyncPropData(propName, defaultValues[propName]);\n this._updateAsyncProp(propName, value);\n // Use transformed value\n resolvedValues[propName] = this.getAsyncProp(propName);\n }\n\n for (const propName in originalValues) {\n const value = originalValues[propName];\n // Makes sure a record exists for this prop\n this._createAsyncPropData(propName, defaultValues[propName]);\n this._updateAsyncProp(propName, value);\n }\n }\n\n /* Placeholder methods for subclassing */\n\n protected _fetch(propName: string, url: string): any {\n return null;\n }\n\n protected _onResolve(propName: string, value: any) {} // eslint-disable-line @typescript-eslint/no-empty-function\n\n protected _onError(propName: string, error: Error) {} // eslint-disable-line @typescript-eslint/no-empty-function\n\n // Intercept strings (URLs) and Promises and activates loading and prop rewriting\n private _updateAsyncProp(propName: string, value: any) {\n if (!this._didAsyncInputValueChange(propName, value)) {\n return;\n }\n\n // interpret value string as url and start a new load tracked by a promise\n if (typeof value === 'string') {\n value = this._fetch(propName, value);\n }\n\n // interprets promise and track the \"loading\"\n if (value instanceof Promise) {\n this._watchPromise(propName, value);\n return;\n }\n\n if (isAsyncIterable(value)) {\n this._resolveAsyncIterable(propName, value); // eslint-disable-line @typescript-eslint/no-floating-promises\n return;\n }\n\n // else, normal, non-async value. Just store value for now\n this._setPropValue(propName, value);\n }\n\n // Whenever async props are changing, we need to make a copy of oldProps\n // otherwise the prop rewriting will affect the value both in props and oldProps.\n // While the copy is relatively expensive, this only happens on load completion.\n private _freezeAsyncOldProps() {\n if (!this.oldAsyncProps && this.oldProps) {\n // 1. inherit all synchronous props from oldProps\n // 2. reconfigure the async prop descriptors to fixed values\n this.oldAsyncProps = Object.create(this.oldProps);\n for (const propName in this.asyncProps) {\n Object.defineProperty(this.oldAsyncProps, propName, {\n enumerable: true,\n value: this.oldProps[propName]\n });\n }\n }\n }\n\n // Checks if an input value actually changed (to avoid reloading/rewatching promises/urls)\n private _didAsyncInputValueChange(propName: string, value: any): boolean {\n // @ts-ignore\n const asyncProp: AsyncPropState = this.asyncProps[propName];\n if (value === asyncProp.resolvedValue || value === asyncProp.lastValue) {\n return false;\n }\n asyncProp.lastValue = value;\n return true;\n }\n\n // Set normal, non-async value\n private _setPropValue(propName: string, value: any) {\n // Save the current value before overwriting so that diffProps can access both\n this._freezeAsyncOldProps();\n\n const asyncProp = this.asyncProps[propName];\n if (asyncProp) {\n value = this._postProcessValue(asyncProp, value);\n asyncProp.resolvedValue = value;\n asyncProp.pendingLoadCount++;\n asyncProp.resolvedLoadCount = asyncProp.pendingLoadCount;\n }\n }\n\n // Set a just resolved async value, calling onAsyncPropUpdates if value changes asynchronously\n private _setAsyncPropValue(propName: string, value: any, loadCount: number) {\n // Only update if loadCount is larger or equal to resolvedLoadCount\n // otherwise a more recent load has already completed\n const asyncProp = this.asyncProps[propName];\n if (asyncProp && loadCount >= asyncProp.resolvedLoadCount && value !== undefined) {\n // Save the current value before overwriting so that diffProps can access both\n this._freezeAsyncOldProps();\n\n asyncProp.resolvedValue = value;\n asyncProp.resolvedLoadCount = loadCount;\n\n // Call callback to inform listener\n this.onAsyncPropUpdated(propName, value);\n }\n }\n\n // Tracks a promise, sets the prop when loaded, handles load count\n private _watchPromise(propName: string, promise: Promise) {\n const asyncProp = this.asyncProps[propName];\n if (asyncProp) {\n asyncProp.pendingLoadCount++;\n const loadCount = asyncProp.pendingLoadCount;\n promise\n .then(data => {\n if (!this.component) {\n // This component state has been finalized\n return;\n }\n data = this._postProcessValue(asyncProp, data);\n this._setAsyncPropValue(propName, data, loadCount);\n this._onResolve(propName, data);\n })\n .catch(error => {\n this._onError(propName, error);\n });\n }\n }\n\n private async _resolveAsyncIterable(\n propName: string,\n iterable: AsyncIterable\n ): Promise {\n if (propName !== 'data') {\n // we only support data as async iterable\n this._setPropValue(propName, iterable);\n return;\n }\n\n const asyncProp = this.asyncProps[propName];\n if (!asyncProp) {\n return;\n }\n\n asyncProp.pendingLoadCount++;\n const loadCount = asyncProp.pendingLoadCount;\n let data: any[] = [];\n let count = 0;\n\n for await (const chunk of iterable) {\n if (!this.component) {\n // This component state has been finalized\n return;\n }\n\n // @ts-expect-error (2339) dataTransform is not decared in base component props\n const {dataTransform} = this.component.props;\n if (dataTransform) {\n data = dataTransform(chunk, data) as any[];\n } else {\n data = data.concat(chunk);\n }\n\n // Used by the default _dataDiff function\n Object.defineProperty(data, '__diff', {\n enumerable: false,\n value: [{startRow: count, endRow: data.length}]\n });\n\n count = data.length;\n this._setAsyncPropValue(propName, data, loadCount);\n }\n\n this._onResolve(propName, data);\n }\n\n // Give the app a chance to post process the loaded data\n private _postProcessValue(asyncProp: AsyncPropState, value: any) {\n const propType = asyncProp.type;\n if (propType && this.component) {\n if (propType.release) {\n propType.release(asyncProp.resolvedValue, propType, this.component);\n }\n if (propType.transform) {\n return propType.transform(value, propType, this.component);\n }\n }\n return value;\n }\n\n // Creating an asyncProp record if needed\n private _createAsyncPropData(propName: string, defaultValue: any) {\n const asyncProp = this.asyncProps[propName];\n if (!asyncProp) {\n const propTypes = this.component && this.component.props[PROP_TYPES_SYMBOL];\n // assert(defaultValue !== undefined);\n this.asyncProps[propName] = {\n type: propTypes && propTypes[propName],\n lastValue: null,\n resolvedValue: defaultValue,\n pendingLoadCount: 0,\n resolvedLoadCount: 0\n };\n }\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// deck.gl, MIT license\nimport ComponentState from '../lifecycle/component-state';\n\nimport type Layer from './layer';\nimport type AttributeManager from './attribute/attribute-manager';\nimport type Viewport from '../viewports/viewport';\nimport type UniformTransitionManager from './uniform-transition-manager';\n\nexport type ChangeFlags = {\n // Primary changeFlags, can be strings stating reason for change\n dataChanged: string | false | {startRow: number; endRow?: number}[];\n propsChanged: string | false;\n updateTriggersChanged: Record | false;\n extensionsChanged: boolean;\n viewportChanged: boolean;\n stateChanged: boolean;\n\n // Derived changeFlags\n propsOrDataChanged: boolean;\n somethingChanged: boolean;\n};\n\nexport default class LayerState extends ComponentState {\n attributeManager: AttributeManager | null;\n needsRedraw: boolean;\n needsUpdate: boolean;\n /**\n * Sublayers rendered in a previous cycle\n */\n subLayers: Layer[] | null;\n /**\n * If the layer is using the shared instancedPickingColors buffer\n */\n usesPickingColorCache: boolean;\n /**\n * If the layer has picking buffer (pickingColors or instancePickingColors)\n */\n hasPickingBuffer?: boolean;\n /**\n * Dirty flags of the layer's props and state\n */\n changeFlags!: ChangeFlags;\n\n /** The last viewport rendered by this layer */\n viewport?: Viewport;\n\n uniformTransitions!: UniformTransitionManager;\n /** Populated during uniform transition to replace user-supplied values */\n propsInTransition?: LayerT['props'];\n\n constructor({\n attributeManager,\n layer\n }: {\n attributeManager: AttributeManager | null;\n layer: LayerT;\n }) {\n super(layer);\n this.attributeManager = attributeManager;\n this.needsRedraw = true;\n this.needsUpdate = true;\n this.subLayers = null;\n this.usesPickingColorCache = false;\n }\n\n get layer(): LayerT | null {\n return this.component;\n }\n\n /* Override base Component methods with Layer-specific handling */\n\n protected _fetch(propName, url: string) {\n const layer = this.layer;\n const fetch = layer?.props.fetch;\n if (fetch) {\n return fetch(url, {propName, layer});\n }\n return super._fetch(propName, url);\n }\n\n protected _onResolve(propName: string, value: any) {\n const layer = this.layer;\n if (layer) {\n const onDataLoad = layer.props.onDataLoad;\n if (propName === 'data' && onDataLoad) {\n onDataLoad(value, {propName, layer});\n }\n }\n }\n\n protected _onError(propName: string, error: Error) {\n const layer = this.layer;\n if (layer) {\n layer.raiseError(error, `loading ${propName} of ${this.layer}`);\n }\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport Layer, {UpdateParameters} from './layer';\nimport debug from '../debug/index';\nimport {flatten} from '../utils/flatten';\n\nimport type AttributeManager from './attribute/attribute-manager';\nimport type {PickingInfo, GetPickingInfoParams} from './picking/pick-info';\nimport type {FilterContext} from '../passes/layers-pass';\nimport type {LayersList, LayerContext} from './layer-manager';\nimport type {CompositeLayerProps, Accessor, AccessorContext} from '../types/layer-props';\nimport {ConstructorOf} from '../types/types';\nimport {PROP_TYPES_SYMBOL} from '../lifecycle/constants';\n\nconst TRACE_RENDER_LAYERS = 'compositeLayer.renderLayers';\n\nexport default abstract class CompositeLayer extends Layer<\n PropsT & Required\n> {\n static layerName: string = 'CompositeLayer';\n\n /** `true` if this layer renders other layers */\n get isComposite(): boolean {\n return true;\n }\n\n /** `true` if the layer renders to screen */\n get isDrawable(): boolean {\n return false;\n }\n\n /** Returns true if all async resources are loaded */\n get isLoaded(): boolean {\n return super.isLoaded && this.getSubLayers().every(layer => layer.isLoaded);\n }\n\n /** Return last rendered sub layers */\n getSubLayers(): Layer[] {\n return (this.internalState && this.internalState.subLayers) || [];\n }\n\n // initializeState is usually not needed for composite layers\n // Provide empty definition to disable check for missing definition\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n initializeState(context: LayerContext): void {}\n\n /** Updates selected state members and marks the composite layer to need rerender */\n setState(updateObject: any): void {\n super.setState(updateObject);\n // Trigger a layer update\n // Although conceptually layer.draw and compositeLayer.renderLayers are equivalent,\n // they are executed during different lifecycles.\n // draw can be called without calling updateState (e.g. most viewport changes),\n // while renderLayers can only be called during a recursive layer update.\n this.setNeedsUpdate();\n }\n\n /** called to augment the info object that is bubbled up from a sublayer\n override Layer.getPickingInfo() because decoding / setting uniform do\n not apply to a composite layer. */\n getPickingInfo({info}: GetPickingInfoParams): PickingInfo {\n const {object} = info;\n const isDataWrapped =\n object && object.__source && object.__source.parent && object.__source.parent.id === this.id;\n\n if (!isDataWrapped) {\n return info;\n }\n\n // override object with picked data\n info.object = object.__source.object;\n info.index = object.__source.index;\n\n return info;\n }\n\n // Implement to generate subLayers\n abstract renderLayers(): Layer | null | LayersList;\n\n /**\n * Filters sub layers at draw time. Return true if the sub layer should be drawn.\n */\n filterSubLayer(context: FilterContext): boolean {\n return true;\n }\n\n /** Returns true if sub layer needs to be rendered */\n protected shouldRenderSubLayer(subLayerId: string, data: any): boolean {\n return data && data.length;\n }\n\n /** Returns sub layer class for a specific sublayer */\n protected getSubLayerClass(\n subLayerId: string,\n DefaultLayerClass: ConstructorOf\n ): ConstructorOf {\n const {_subLayerProps: overridingProps} = this.props;\n\n return (\n (overridingProps &&\n overridingProps[subLayerId] &&\n (overridingProps[subLayerId].type as ConstructorOf)) ||\n DefaultLayerClass\n );\n }\n\n /** When casting user data into another format to pass to sublayers,\n add reference to the original object and object index */\n protected getSubLayerRow(row: T, sourceObject: any, sourceObjectIndex: number): T {\n // @ts-ignore (TS2339) adding undefined property\n row.__source = {\n parent: this,\n object: sourceObject,\n index: sourceObjectIndex\n };\n return row;\n }\n\n /** Some composite layers cast user data into another format before passing to sublayers\n We need to unwrap them before calling the accessor so that they see the original data\n objects */\n protected getSubLayerAccessor(accessor: Accessor): Accessor {\n if (typeof accessor === 'function') {\n const objectInfo: AccessorContext = {\n index: -1,\n // @ts-ignore accessing resolved data\n data: this.props.data,\n target: []\n };\n return (x: any, i: AccessorContext) => {\n if (x && x.__source) {\n objectInfo.index = x.__source.index;\n // @ts-ignore (TS2349) Out is never a function\n return accessor(x.__source.object as In, objectInfo);\n }\n // @ts-ignore (TS2349) Out is never a function\n return accessor(x as In, i);\n };\n }\n return accessor;\n }\n\n /** Returns sub layer props for a specific sublayer */\n // eslint-disable-next-line complexity\n protected getSubLayerProps(\n sublayerProps: {\n id?: string;\n updateTriggers?: Record;\n [propName: string]: any;\n } = {}\n ): any {\n const {\n opacity,\n pickable,\n visible,\n parameters,\n getPolygonOffset,\n highlightedObjectIndex,\n autoHighlight,\n highlightColor,\n coordinateSystem,\n coordinateOrigin,\n wrapLongitude,\n positionFormat,\n modelMatrix,\n extensions,\n fetch,\n operation,\n _subLayerProps: overridingProps\n } = this.props;\n const newProps = {\n id: '',\n updateTriggers: {},\n opacity,\n pickable,\n visible,\n parameters,\n getPolygonOffset,\n highlightedObjectIndex,\n autoHighlight,\n highlightColor,\n coordinateSystem,\n coordinateOrigin,\n wrapLongitude,\n positionFormat,\n modelMatrix,\n extensions,\n fetch,\n operation\n };\n\n const overridingSublayerProps =\n overridingProps && sublayerProps.id && overridingProps[sublayerProps.id];\n const overridingSublayerTriggers =\n overridingSublayerProps && overridingSublayerProps.updateTriggers;\n const sublayerId = sublayerProps.id || 'sublayer';\n\n if (overridingSublayerProps) {\n const propTypes = this.props[PROP_TYPES_SYMBOL];\n const subLayerPropTypes = sublayerProps.type ? sublayerProps.type._propTypes : {};\n for (const key in overridingSublayerProps) {\n const propType = subLayerPropTypes[key] || propTypes[key];\n // eslint-disable-next-line\n if (propType && propType.type === 'accessor') {\n overridingSublayerProps[key] = this.getSubLayerAccessor(overridingSublayerProps[key]);\n }\n }\n }\n\n Object.assign(\n newProps,\n sublayerProps,\n // experimental feature that allows users to override sublayer props via parent layer prop\n overridingSublayerProps\n );\n newProps.id = `${this.props.id}-${sublayerId}`;\n newProps.updateTriggers = {\n all: this.props.updateTriggers?.all,\n ...sublayerProps.updateTriggers,\n ...overridingSublayerTriggers\n };\n\n // Pass through extension props\n // @ts-ignore (TS2532) extensions is always defined after merging with default props\n for (const extension of extensions) {\n const passThroughProps = extension.getSubLayerProps.call(this, extension);\n if (passThroughProps) {\n Object.assign(newProps, passThroughProps, {\n updateTriggers: Object.assign(newProps.updateTriggers, passThroughProps.updateTriggers)\n });\n }\n }\n\n return newProps;\n }\n\n /** Update sub layers to highlight the hovered object */\n protected _updateAutoHighlight(info: PickingInfo): void {\n for (const layer of this.getSubLayers()) {\n layer.updateAutoHighlight(info);\n }\n }\n\n /** Override base Layer method */\n protected _getAttributeManager(): AttributeManager | null {\n return null;\n }\n\n /** (Internal) Called after an update to rerender sub layers */\n protected _postUpdate(updateParams: UpdateParameters, forceUpdate: boolean) {\n // @ts-ignore (TS2531) this method is only called internally when internalState is defined\n let subLayers = this.internalState.subLayers as Layer[];\n const shouldUpdate = !subLayers || this.needsUpdate();\n if (shouldUpdate) {\n const subLayersList = this.renderLayers();\n // Flatten the returned array, removing any null, undefined or false\n // this allows layers to render sublayers conditionally\n // (see CompositeLayer.renderLayers docs)\n subLayers = flatten(subLayersList, Boolean) as Layer[];\n // @ts-ignore (TS2531) this method is only called internally when internalState is defined\n this.internalState.subLayers = subLayers;\n }\n debug(TRACE_RENDER_LAYERS, this, shouldUpdate, subLayers);\n\n // populate reference to parent layer (this layer)\n // NOTE: needs to be done even when reusing layers as the parent may have changed\n for (const layer of subLayers) {\n layer.parent = this;\n }\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {clamp} from '@math.gl/core';\nimport Controller, {ControllerProps} from './controller';\n\nimport {MapState, MapStateProps} from './map-controller';\nimport type {MapStateInternal} from './map-controller';\nimport {mod} from '../utils/math-utils';\nimport LinearInterpolator from '../transitions/linear-interpolator';\nimport {zoomAdjust, GLOBE_RADIUS} from '../viewports/globe-viewport';\n\nimport {MAX_LATITUDE} from '@math.gl/web-mercator';\n\nconst DEGREES_TO_RADIANS = Math.PI / 180;\nconst RADIANS_TO_DEGREES = 180 / Math.PI;\n\nfunction degreesToPixels(angle: number, zoom: number = 0): number {\n const radians = Math.min(180, angle) * DEGREES_TO_RADIANS;\n const size = GLOBE_RADIUS * 2 * Math.sin(radians / 2);\n return size * Math.pow(2, zoom);\n}\nfunction pixelsToDegrees(pixels: number, zoom: number = 0): number {\n const size = pixels / Math.pow(2, zoom);\n const radians = Math.asin(Math.min(1, size / GLOBE_RADIUS / 2)) * 2;\n return radians * RADIANS_TO_DEGREES;\n}\n\ntype GlobeStateInternal = MapStateInternal & {\n startPanPos?: [number, number];\n};\n\nclass GlobeState extends MapState {\n constructor(\n options: MapStateProps &\n GlobeStateInternal & {\n makeViewport: (props: Record) => any;\n }\n ) {\n const {startPanPos, ...mapStateOptions} = options;\n mapStateOptions.normalize = false; // disable MapState default normalization\n super(mapStateOptions);\n\n if (startPanPos !== undefined) {\n (this as any)._state.startPanPos = startPanPos;\n }\n }\n\n panStart({pos}: {pos: [number, number]}): GlobeState {\n const {latitude, longitude, zoom} = this.getViewportProps();\n return this._getUpdatedState({\n startPanLngLat: [longitude, latitude],\n startPanPos: pos,\n startZoom: zoom\n }) as GlobeState;\n }\n\n pan({pos, startPos}: {pos: [number, number]; startPos?: [number, number]}): GlobeState {\n const state = this.getState() as GlobeStateInternal;\n const startPanLngLat = state.startPanLngLat || this._unproject(startPos);\n if (!startPanLngLat) return this;\n const startZoom = state.startZoom ?? this.getViewportProps().zoom;\n const startPanPos = state.startPanPos || startPos;\n\n const coords = [startPanLngLat[0], startPanLngLat[1], startZoom];\n const viewport = this.makeViewport(this.getViewportProps());\n const newProps = viewport.panByPosition(coords, pos, startPanPos);\n return this._getUpdatedState(newProps) as GlobeState;\n }\n\n panEnd(): GlobeState {\n return this._getUpdatedState({\n startPanLngLat: null,\n startPanPos: null,\n startZoom: null\n }) as GlobeState;\n }\n\n zoom({scale}: {scale: number}): MapState {\n // In Globe view zoom does not take into account the mouse position\n const startZoom = this.getState().startZoom || this.getViewportProps().zoom;\n const zoom = startZoom + Math.log2(scale);\n return this._getUpdatedState({zoom});\n }\n\n applyConstraints(props: Required): Required {\n // Ensure zoom is within specified range\n const {longitude, latitude, maxBounds} = props;\n\n props.zoom = this._constrainZoom(props.zoom, props);\n\n if (longitude < -180 || longitude > 180) {\n props.longitude = mod(longitude + 180, 360) - 180;\n }\n props.latitude = clamp(latitude, -MAX_LATITUDE, MAX_LATITUDE);\n if (maxBounds) {\n props.longitude = clamp(props.longitude, maxBounds[0][0], maxBounds[1][0]);\n props.latitude = clamp(props.latitude, maxBounds[0][1], maxBounds[1][1]);\n }\n\n if (maxBounds) {\n // calculate center and zoom ranges at pitch=0 and bearing=0\n // to maintain visual stability when rotating\n const effectiveZoom = props.zoom - zoomAdjust(latitude);\n const lngSpan = maxBounds[1][0] - maxBounds[0][0];\n const latSpan = maxBounds[1][1] - maxBounds[0][1];\n if (latSpan > 0 && latSpan < MAX_LATITUDE * 2) {\n const halfHeightDegrees =\n Math.min(pixelsToDegrees(props.height, effectiveZoom), latSpan) / 2;\n props.latitude = clamp(\n props.latitude,\n maxBounds[0][1] + halfHeightDegrees,\n maxBounds[1][1] - halfHeightDegrees\n );\n }\n if (lngSpan > 0 && lngSpan < 360) {\n const halfWidthDegrees =\n Math.min(\n pixelsToDegrees(\n props.width / Math.cos(props.latitude * DEGREES_TO_RADIANS),\n effectiveZoom\n ),\n lngSpan\n ) / 2;\n props.longitude = clamp(\n props.longitude,\n maxBounds[0][0] + halfWidthDegrees,\n maxBounds[1][0] - halfWidthDegrees\n );\n }\n }\n if (props.latitude !== latitude) {\n props.zoom += zoomAdjust(props.latitude) - zoomAdjust(latitude);\n }\n\n return props;\n }\n\n _constrainZoom(zoom: number, props?: Required): number {\n props ||= this.getViewportProps();\n const {latitude, maxZoom, maxBounds} = props;\n let {minZoom} = props;\n const ZOOM0 = zoomAdjust(0);\n const zoomAdjustment = zoomAdjust(latitude) - ZOOM0;\n\n const shouldApplyMaxBounds = maxBounds !== null && props.width > 0 && props.height > 0;\n if (shouldApplyMaxBounds) {\n const minLatitude = maxBounds[0][1];\n const maxLatitude = maxBounds[1][1];\n // latitude at which the bounding box is the widest\n const fitLatitude =\n Math.sign(minLatitude) === Math.sign(maxLatitude)\n ? Math.min(Math.abs(minLatitude), Math.abs(maxLatitude))\n : 0;\n const w =\n degreesToPixels(maxBounds[1][0] - maxBounds[0][0]) *\n Math.cos(fitLatitude * DEGREES_TO_RADIANS);\n const h = degreesToPixels(maxBounds[1][1] - maxBounds[0][1]);\n if (w > 0) {\n minZoom = Math.max(minZoom, Math.log2(props.width / w) + ZOOM0);\n }\n if (h > 0) {\n minZoom = Math.max(minZoom, Math.log2(props.height / h) + ZOOM0);\n }\n if (minZoom > maxZoom) minZoom = maxZoom;\n }\n\n return clamp(zoom, minZoom + zoomAdjustment, maxZoom + zoomAdjustment);\n }\n}\n\nexport default class GlobeController extends Controller {\n ControllerState = GlobeState;\n\n transition = {\n transitionDuration: 300,\n transitionInterpolator: new LinearInterpolator(['longitude', 'latitude', 'zoom'])\n };\n\n dragMode: 'pan' | 'rotate' = 'pan';\n\n setProps(props: ControllerProps) {\n super.setProps(props);\n\n // TODO - support pitching?\n this.dragRotate = false;\n this.touchRotate = false;\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport View, {CommonViewState, CommonViewProps} from './view';\nimport GlobeViewport from '../viewports/globe-viewport';\nimport WebMercatorViewport from '../viewports/web-mercator-viewport';\nimport GlobeController from '../controllers/globe-controller';\n\nexport type GlobeViewState = {\n /** Longitude of the map center */\n longitude: number;\n /** Latitude of the map center */\n latitude: number;\n /** Zoom level */\n zoom: number;\n /** Min zoom, default `0` */\n minZoom?: number;\n /** Max zoom, default `20` */\n maxZoom?: number;\n /** The near plane position */\n nearZ?: number;\n /** The far plane position */\n farZ?: number;\n} & CommonViewState;\n\nexport type GlobeViewProps = {\n /** The resolution at which to turn flat features into 3D meshes, in degrees. Smaller numbers will generate more detailed mesh. Default `10`. */\n resolution?: number;\n /** Scaler for the near plane, 1 unit equals to the height of the viewport. Default to `0.1`. Overwrites the `near` parameter. */\n nearZMultiplier?: number;\n /** Scaler for the far plane, 1 unit equals to the distance from the camera to the top edge of the screen. Default to `1.01`. Overwrites the `far` parameter. */\n farZMultiplier?: number;\n /** Distance of the camera relative to viewport height. Default `1.5`. */\n altitude?: number;\n} & CommonViewProps;\n\nexport default class GlobeView extends View {\n static displayName = 'GlobeView';\n\n constructor(props: GlobeViewProps = {}) {\n super(props);\n }\n\n getViewportType(viewState: GlobeViewState) {\n return viewState.zoom > 12 ? WebMercatorViewport : GlobeViewport;\n }\n\n get ControllerType() {\n return GlobeController;\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {drawLayerGroup} from './deck-utils';\nimport type {Map, CustomLayerInterface} from './types';\nimport {assert, type Deck} from '@deck.gl/core';\n\ntype MapWithDeck = Map & {__deck: Deck};\n\nexport type MapboxLayerGroupProps = {\n id: string;\n renderingMode?: '2d' | '3d';\n /* Mapbox v3 Standard style */\n slot?: 'bottom' | 'middle' | 'top';\n beforeId?: string;\n};\n\nexport default class MapboxLayerGroup implements CustomLayerInterface {\n id: string;\n type: 'custom';\n renderingMode: '2d' | '3d';\n /* Mapbox v3 Standard style */\n slot?: 'bottom' | 'middle' | 'top';\n beforeId?: string;\n map: MapWithDeck | null;\n\n /* eslint-disable no-this-before-super */\n constructor(props: MapboxLayerGroupProps) {\n assert(props.id, 'id is required');\n\n this.id = props.id;\n this.type = 'custom';\n this.renderingMode = props.renderingMode || '3d';\n this.slot = props.slot;\n this.beforeId = props.beforeId;\n this.map = null;\n }\n\n /* Mapbox custom layer methods */\n\n onAdd(map: MapWithDeck, gl: WebGL2RenderingContext): void {\n this.map = map;\n }\n\n render(gl, renderParameters) {\n if (!this.map) return;\n\n drawLayerGroup(this.map.__deck, this.map, this, renderParameters);\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {_flatten as flatten} from '@deck.gl/core';\n\nimport type {Layer, LayersList} from '@deck.gl/core';\nimport type {Map, LayerOverlayProps} from './types';\nimport MapboxLayerGroup from './mapbox-layer-group';\n\nconst UNDEFINED_BEFORE_ID = '__UNDEFINED__';\n\nexport function getLayerGroupId(layer: Layer): string {\n if (layer.props.beforeId) {\n return `deck-layer-group-before:${layer.props.beforeId}`;\n } else if (layer.props.slot) {\n return `deck-layer-group-slot:${layer.props.slot}`;\n }\n return 'deck-layer-group-last';\n}\n\n/** Group Deck layers into buckets (by beforeId or slot) and insert them\n * into the mapbox Map according to the user-defined order\n **/\n// eslint-disable-next-line complexity, max-statements\nexport function resolveLayerGroups(map?: Map, oldLayers?: LayersList, newLayers?: LayersList) {\n // Wait until map style is loaded\n // @ts-ignore non-public map property\n if (!map || !map.style || !map.style._loaded) {\n return;\n }\n\n const layers = flatten(newLayers, Boolean) as Layer[];\n\n if (oldLayers !== newLayers) {\n // Step 1: remove \"group\" layers that no longer exist\n const prevLayers = flatten(oldLayers, Boolean) as Layer[];\n const prevLayerGroupIds = new Set(prevLayers.map(l => getLayerGroupId(l)));\n const newLayerGroupIds = new Set(layers.map(l => getLayerGroupId(l)));\n\n for (const groupId of prevLayerGroupIds) {\n if (!newLayerGroupIds.has(groupId)) {\n if (map.getLayer(groupId)) {\n map.removeLayer(groupId);\n }\n }\n }\n }\n\n // Step 2: add missing \"group\" layers\n const layerGroups: Record = {};\n for (const layer of layers) {\n const groupId = getLayerGroupId(layer);\n const mapboxGroup = map.getLayer(groupId) as MapboxLayerGroup;\n if (mapboxGroup) {\n // Mapbox's map.getLayer() had a breaking change in v3.6.0, see https://github.com/visgl/deck.gl/issues/9086\n // @ts-expect-error not typed\n const groupInstance = mapboxGroup.implementation || mapboxGroup;\n layerGroups[groupId] = groupInstance;\n } else {\n const newGroup = new MapboxLayerGroup({\n id: groupId,\n slot: layer.props.slot,\n beforeId: layer.props.beforeId\n });\n layerGroups[groupId] = newGroup;\n map.addLayer(newGroup, layer.props.beforeId);\n }\n }\n\n // Step 3: check the order of layers\n // If beforeId move \"group\" layers to proper position in the mapbox layer order\n // @ts-ignore non-public map property\n const mapLayers: string[] = map.style._order;\n\n for (const [groupId, group] of Object.entries(layerGroups)) {\n const beforeId = group.beforeId || UNDEFINED_BEFORE_ID;\n\n const expectedGroupIndex =\n beforeId === UNDEFINED_BEFORE_ID ? mapLayers.length : mapLayers.indexOf(beforeId);\n\n const currentGropupIndex = mapLayers.indexOf(groupId);\n if (currentGropupIndex !== expectedGroupIndex - 1) {\n const moveBeforeId = beforeId === UNDEFINED_BEFORE_ID ? undefined : beforeId;\n map.moveLayer(groupId, moveBeforeId);\n }\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Deck, MapView, _GlobeView as GlobeView, _flatten as flatten} from '@deck.gl/core';\nimport type {Viewport, MapViewState, Layer} from '@deck.gl/core';\nimport type {Parameters} from '@luma.gl/core';\nimport type MapboxLayerGroup from './mapbox-layer-group';\nimport type {LayerOverlayProps, Map} from './types';\nimport {getLayerGroupId} from './resolve-layer-groups';\n\nimport {lngLatToWorld, unitsPerMeter} from '@math.gl/web-mercator';\n\nexport const MAPBOX_VIEW_ID = 'mapbox';\n\ntype UserData = {\n currentViewport?: Viewport | null;\n};\n\n// Mercator constants\nconst TILE_SIZE = 512;\nconst DEGREES_TO_RADIANS = Math.PI / 180;\n\n// Create an interleaved deck instance.\nexport function getDeckInstance({\n map,\n deck\n}: {\n map: Map & {__deck?: Deck | null};\n deck: Deck;\n}): Deck {\n // Only create one deck instance per context\n if (map.__deck) {\n return map.__deck;\n }\n\n // Only initialize certain props once per context\n const customRender = deck.props._customRender;\n const onLoad = deck.props.onLoad;\n\n const deckProps = {\n ...deck.props,\n _customRender: () => {\n map.triggerRepaint();\n // customRender may be subscribed by DeckGL React component to update child props\n // make sure it is still called\n // Hack - do not pass a redraw reason here to prevent the React component from clearing the context\n // Rerender will be triggered by MapboxLayerGroup's render()\n customRender?.('');\n }\n };\n deckProps.views ||= getDefaultView(map);\n\n // deck is using the WebGLContext created by mapbox,\n // block deck from setting the canvas size, and use the map's viewState to drive deck.\n Object.assign(deckProps, {\n width: null,\n height: null,\n touchAction: 'unset',\n viewState: getViewState(map)\n });\n if (deck.isInitialized) {\n watchMapMove(deck, map);\n } else {\n deckProps.onLoad = () => {\n onLoad?.();\n watchMapMove(deck, map);\n };\n }\n\n deck.setProps(deckProps);\n\n map.__deck = deck;\n map.on('render', () => {\n if (deck.isInitialized) afterRender(deck, map);\n });\n\n return deck;\n}\n\nfunction watchMapMove(deck: Deck, map: Map & {__deck?: Deck | null}) {\n const _handleMapMove = () => {\n if (deck.isInitialized) {\n // call view state methods\n onMapMove(deck, map);\n } else {\n // deregister itself when deck is finalized\n map.off('move', _handleMapMove);\n }\n };\n map.on('move', _handleMapMove);\n}\n\nexport function removeDeckInstance(map: Map & {__deck?: Deck | null}) {\n map.__deck?.finalize();\n map.__deck = null;\n}\n\nexport function getDefaultParameters(map: Map, interleaved: boolean): Parameters {\n const result: Parameters = interleaved\n ? {\n depthWriteEnabled: true,\n depthCompare: 'less-equal',\n depthBias: 0,\n blend: true,\n blendColorSrcFactor: 'src-alpha',\n blendColorDstFactor: 'one-minus-src-alpha',\n blendAlphaSrcFactor: 'one',\n blendAlphaDstFactor: 'one-minus-src-alpha',\n blendColorOperation: 'add',\n blendAlphaOperation: 'add'\n }\n : {};\n if (getProjection(map) === 'globe') {\n result.cullMode = 'back';\n }\n return result;\n}\n\nexport function drawLayerGroup(\n deck: Deck,\n map: Map,\n group: MapboxLayerGroup,\n renderParameters: any\n): void {\n if (!deck.isInitialized) {\n return;\n }\n\n let {currentViewport} = deck.userData as UserData;\n let clearStack: boolean = false;\n if (!currentViewport) {\n // This is the first layer drawn in this render cycle.\n // Generate viewport from the current map state.\n currentViewport = getViewport(deck, map, renderParameters);\n (deck.userData as UserData).currentViewport = currentViewport;\n clearStack = true;\n }\n\n if (!currentViewport) {\n return;\n }\n\n deck._drawLayers('mapbox-repaint', {\n viewports: [currentViewport],\n layerFilter: params => {\n if (deck.props.layerFilter && !deck.props.layerFilter(params)) {\n return false;\n }\n\n const layer = params.layer as Layer;\n if (layer.props.beforeId === group.beforeId && layer.props.slot === group.slot) {\n return true;\n }\n return false;\n },\n clearStack,\n clearCanvas: false\n });\n}\n\nexport function getProjection(map: Map): 'mercator' | 'globe' {\n const projection = map.getProjection?.();\n const type =\n // maplibre projection spec\n projection?.type ||\n // mapbox projection spec\n projection?.name;\n if (type === 'globe') {\n return 'globe';\n }\n if (type && type !== 'mercator') {\n throw new Error('Unsupported projection');\n }\n return 'mercator';\n}\n\nexport function getDefaultView(map: Map): GlobeView | MapView {\n if (getProjection(map) === 'globe') {\n return new GlobeView({id: MAPBOX_VIEW_ID});\n }\n return new MapView({id: MAPBOX_VIEW_ID});\n}\n\nexport function getViewState(map: Map): MapViewState & {\n repeat: boolean;\n padding: {\n left: number;\n right: number;\n top: number;\n bottom: number;\n };\n} {\n const {lng, lat} = map.getCenter();\n\n const viewState: MapViewState & {\n repeat: boolean;\n padding: {\n left: number;\n right: number;\n top: number;\n bottom: number;\n };\n } = {\n // Longitude returned by getCenter can be outside of [-180, 180] when zooming near the anti meridian\n // https://github.com/visgl/deck.gl/issues/6894\n longitude: ((lng + 540) % 360) - 180,\n latitude: lat,\n zoom: map.getZoom(),\n bearing: map.getBearing(),\n pitch: map.getPitch(),\n padding: map.getPadding(),\n repeat: map.getRenderWorldCopies()\n };\n\n if (map.getTerrain?.()) {\n // When the base map has terrain, we need to target the camera at the terrain surface\n centerCameraOnTerrain(map, viewState);\n }\n\n return viewState;\n}\n\nfunction centerCameraOnTerrain(map: Map, viewState: MapViewState) {\n if (map.getFreeCameraOptions) {\n // mapbox-gl v2\n const {position} = map.getFreeCameraOptions();\n if (!position || position.z === undefined) {\n return;\n }\n\n // @ts-ignore transform is not typed\n const height = map.transform.height;\n const {longitude, latitude, pitch} = viewState;\n\n // Convert mapbox mercator coordinate to deck common space\n const cameraX = position.x * TILE_SIZE;\n const cameraY = (1 - position.y) * TILE_SIZE;\n const cameraZ = position.z * TILE_SIZE;\n\n // Mapbox manipulates zoom in terrain mode, see discussion here: https://github.com/mapbox/mapbox-gl-js/issues/12040\n const center = lngLatToWorld([longitude, latitude]);\n const dx = cameraX - center[0];\n const dy = cameraY - center[1];\n const cameraToCenterDistanceGround = Math.sqrt(dx * dx + dy * dy);\n\n const pitchRadians = pitch! * DEGREES_TO_RADIANS;\n const altitudePixels = 1.5 * height;\n const scale =\n pitchRadians < 0.001\n ? // Pitch angle too small to deduce the look at point, assume elevation is 0\n (altitudePixels * Math.cos(pitchRadians)) / cameraZ\n : (altitudePixels * Math.sin(pitchRadians)) / cameraToCenterDistanceGround;\n viewState.zoom = Math.log2(scale);\n\n const cameraZFromSurface = (altitudePixels * Math.cos(pitchRadians)) / scale;\n const surfaceElevation = cameraZ - cameraZFromSurface;\n viewState.position = [0, 0, surfaceElevation / unitsPerMeter(latitude)];\n }\n // @ts-ignore transform is not typed\n else if (typeof map.transform.elevation === 'number') {\n // maplibre-gl\n // @ts-ignore transform is not typed\n viewState.position = [0, 0, map.transform.elevation];\n }\n}\n\n// Since maplibre-gl@5\n// https://github.com/maplibre/maplibre-gl-js/blob/main/src/style/style_layer/custom_style_layer.ts\ntype MaplibreRenderParameters = {\n farZ: number;\n nearZ: number;\n fov: number;\n modelViewProjectionMatrix: number[];\n projectionMatrix: number[];\n};\n\nfunction getViewport(deck: Deck, map: Map, renderParameters?: unknown): Viewport | null {\n const viewState = getViewState(map);\n // View is always MapView or GlobeView in this context\n const view = (deck.getView(MAPBOX_VIEW_ID) || getDefaultView(map)) as MapView | GlobeView;\n\n if (renderParameters) {\n // Called from MapboxLayerGroup.render\n // Magic number, matches mapbox-gl@>=1.3.0's projection matrix\n view.props.nearZMultiplier = 0.2;\n }\n\n // Get the base map near/far plane\n // renderParameters is maplibre API but not mapbox\n // Transform is not an official API, properties could be undefined for older versions\n const nearZ = (renderParameters as MaplibreRenderParameters)?.nearZ ?? map.transform._nearZ;\n const farZ = (renderParameters as MaplibreRenderParameters)?.farZ ?? map.transform._farZ;\n if (Number.isFinite(nearZ)) {\n viewState.nearZ = nearZ / map.transform.height;\n viewState.farZ = farZ / map.transform.height;\n }\n // Otherwise fallback to default calculation using nearZMultiplier/farZMultiplier\n\n return view.makeViewport({\n width: deck.width,\n height: deck.height,\n viewState\n });\n}\n\nfunction afterRender(deck: Deck, map: Map): void {\n // Draw non-Mapbox layers (layers that don't have a corresponding MapboxLayerGroup on the map)\n const deckLayers = flatten(deck.props.layers, Boolean) as Layer[];\n const hasNonMapboxLayers = deckLayers.some(\n layer => layer && !map.getLayer(getLayerGroupId(layer))\n );\n let viewports = deck.getViewports();\n const mapboxViewportIdx = viewports.findIndex(vp => vp.id === MAPBOX_VIEW_ID);\n const hasNonMapboxViews = viewports.length > 1 || mapboxViewportIdx < 0;\n\n if (hasNonMapboxLayers || hasNonMapboxViews) {\n if (mapboxViewportIdx >= 0) {\n viewports = viewports.slice();\n const mapboxViewport = getViewport(deck, map);\n if (mapboxViewport) {\n viewports[mapboxViewportIdx] = mapboxViewport;\n } else {\n viewports.splice(mapboxViewportIdx, 1);\n }\n }\n\n deck._drawLayers('mapbox-repaint', {\n viewports,\n layerFilter: params =>\n (!deck.props.layerFilter || deck.props.layerFilter(params)) &&\n (params.viewport.id !== MAPBOX_VIEW_ID ||\n !map.getLayer(getLayerGroupId(params.layer as Layer))),\n clearCanvas: false\n });\n } else {\n // Even when there are no non-Mapbox layers to draw, fire lifecycle callbacks\n // so that consumers can still track view state changes via onAfterRender\n const device = (deck as any).device;\n const gl = device?.gl;\n deck.props.onBeforeRender?.({device, gl});\n deck.props.onAfterRender?.({device, gl});\n }\n\n // End of render cycle, clear generated viewport\n (deck.userData as UserData).currentViewport = null;\n}\n\nfunction onMapMove(deck: Deck, map: Map): void {\n deck.setProps({\n viewState: getViewState(map)\n });\n // Camera changed, will trigger a map repaint right after this\n // Clear any change flag triggered by setting viewState so that deck does not request\n // a second repaint\n deck.needsRedraw({clearRedrawFlags: true});\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Deck, assert, log} from '@deck.gl/core';\nimport {\n getViewState,\n getDefaultView,\n getDeckInstance,\n removeDeckInstance,\n getDefaultParameters,\n getProjection,\n MAPBOX_VIEW_ID\n} from './deck-utils';\n\nimport type {Map, IControl, MapMouseEvent, ControlPosition} from './types';\nimport type {MjolnirGestureEvent, MjolnirPointerEvent} from 'mjolnir.js';\nimport type {DeckProps, LayersList} from '@deck.gl/core';\n\nimport {resolveLayerGroups} from './resolve-layer-groups';\n\nexport type MapboxOverlayProps = Omit<\n DeckProps,\n | 'width'\n | 'height'\n | 'gl'\n | 'parent'\n | 'canvas'\n | '_customRender'\n | 'viewState'\n | 'initialViewState'\n | 'controller'\n> & {\n /**\n * deck.gl layers are inserted into mapbox-gl's layer stack, and share the same WebGL2RenderingContext as the base map.\n */\n interleaved?: boolean;\n};\n\n/**\n * Implements Mapbox [IControl](https://docs.mapbox.com/mapbox-gl-js/api/markers/#icontrol) interface\n * Renders deck.gl layers over the base map and automatically synchronizes with the map's camera\n */\nexport default class MapboxOverlay implements IControl {\n private _props: MapboxOverlayProps;\n private _deck?: Deck;\n private _map?: Map;\n private _container?: HTMLDivElement;\n private _interleaved: boolean;\n private _lastMouseDownPoint?: {x: number; y: number; clientX: number; clientY: number};\n\n constructor(props: MapboxOverlayProps) {\n const {interleaved = false} = props;\n this._interleaved = interleaved;\n this._props = this.filterProps(props);\n }\n\n /** Filter out props to pass to Deck **/\n filterProps(props: MapboxOverlayProps): MapboxOverlayProps {\n const {interleaved = false, useDevicePixels, ...deckProps} = props;\n if (!interleaved && useDevicePixels !== undefined) {\n // useDevicePixels cannot be used in interleaved mode\n (deckProps as MapboxOverlayProps).useDevicePixels = useDevicePixels;\n }\n return deckProps;\n }\n\n /** Update (partial) props of the underlying Deck instance. */\n setProps(props: MapboxOverlayProps): void {\n if (this._interleaved && props.layers) {\n this._resolveLayers(this._map, this._deck, this._props.layers, props.layers);\n }\n\n Object.assign(this._props, this.filterProps(props));\n\n if (this._deck && this._map) {\n this._deck.setProps({\n ...this._props,\n views: this._getViews(this._map),\n parameters: {\n ...getDefaultParameters(this._map, this._interleaved),\n ...this._props.parameters\n }\n });\n }\n }\n\n // The local Map type is for internal typecheck only. It does not necesarily satisefy mapbox/maplibre types at runtime.\n // Do not restrict the argument type here to avoid type conflict.\n /** Called when the control is added to a map */\n onAdd(map: unknown): HTMLDivElement {\n this._map = map as Map;\n return this._interleaved ? this._onAddInterleaved(map as Map) : this._onAddOverlaid(map as Map);\n }\n\n private _onAddOverlaid(map: Map): HTMLDivElement {\n /* global document */\n const container = document.createElement('div');\n Object.assign(container.style, {\n position: 'absolute',\n left: 0,\n top: 0,\n textAlign: 'initial',\n pointerEvents: 'none'\n });\n this._container = container;\n\n this._deck = new Deck({\n ...this._props,\n parent: container,\n parameters: {...getDefaultParameters(map, false), ...this._props.parameters},\n views: this._getViews(map),\n viewState: getViewState(map)\n });\n\n map.on('resize', this._updateContainerSize);\n map.on('render', this._updateViewState);\n map.on('mousedown', this._handleMouseEvent);\n map.on('dragstart', this._handleMouseEvent);\n map.on('drag', this._handleMouseEvent);\n map.on('dragend', this._handleMouseEvent);\n map.on('mousemove', this._handleMouseEvent);\n map.on('mouseout', this._handleMouseEvent);\n map.on('click', this._handleMouseEvent);\n map.on('dblclick', this._handleMouseEvent);\n\n this._updateContainerSize();\n return container;\n }\n\n private _onAddInterleaved(map: Map): HTMLDivElement {\n // @ts-ignore non-public map property\n const gl: WebGL2RenderingContext = map.painter.context.gl;\n if (gl instanceof WebGLRenderingContext) {\n log.warn(\n 'Incompatible basemap library. See: https://deck.gl/docs/api-reference/mapbox/overview#compatibility'\n )();\n }\n this._deck = getDeckInstance({\n map,\n deck: new Deck({\n ...this._props,\n views: this._getViews(map),\n gl,\n parameters: {...getDefaultParameters(map, true), ...this._props.parameters}\n })\n });\n\n map.on('styledata', this._handleStyleChange);\n this._resolveLayers(map, this._deck, [], this._props.layers);\n\n return document.createElement('div');\n }\n\n private _resolveLayers(\n map: Map | undefined,\n _deck: Deck | undefined,\n prevLayers: LayersList | undefined,\n newLayers: LayersList | undefined\n ): void {\n resolveLayerGroups(map, prevLayers, newLayers);\n }\n\n /** Called when the control is removed from a map */\n onRemove(): void {\n const map = this._map;\n\n if (map) {\n if (this._interleaved) {\n this._onRemoveInterleaved(map);\n } else {\n this._onRemoveOverlaid(map);\n }\n }\n\n this._deck = undefined;\n this._map = undefined;\n this._container = undefined;\n }\n\n private _onRemoveOverlaid(map: Map): void {\n map.off('resize', this._updateContainerSize);\n map.off('render', this._updateViewState);\n map.off('mousedown', this._handleMouseEvent);\n map.off('dragstart', this._handleMouseEvent);\n map.off('drag', this._handleMouseEvent);\n map.off('dragend', this._handleMouseEvent);\n map.off('mousemove', this._handleMouseEvent);\n map.off('mouseout', this._handleMouseEvent);\n map.off('click', this._handleMouseEvent);\n map.off('dblclick', this._handleMouseEvent);\n this._deck?.finalize();\n }\n\n private _onRemoveInterleaved(map: Map): void {\n map.off('styledata', this._handleStyleChange);\n this._resolveLayers(map, this._deck, this._props.layers, []);\n removeDeckInstance(map);\n }\n\n getDefaultPosition(): ControlPosition {\n return 'top-left';\n }\n\n /** Forwards the Deck.pickObject method */\n pickObject(params: Parameters[0]): ReturnType {\n assert(this._deck);\n return this._deck.pickObject(params);\n }\n\n /** Forwards the Deck.pickMultipleObjects method */\n pickMultipleObjects(\n params: Parameters[0]\n ): ReturnType {\n assert(this._deck);\n return this._deck.pickMultipleObjects(params);\n }\n\n /** Forwards the Deck.pickObjects method */\n pickObjects(params: Parameters[0]): ReturnType {\n assert(this._deck);\n return this._deck.pickObjects(params);\n }\n\n /** Remove from map and releases all resources */\n finalize() {\n if (this._map) {\n this._map.removeControl(this);\n }\n }\n\n /** If interleaved: true, returns base map's canvas, otherwise forwards the Deck.getCanvas method. */\n getCanvas(): HTMLCanvasElement | null {\n if (!this._map) {\n return null;\n }\n return this._interleaved ? this._map.getCanvas() : this._deck!.getCanvas();\n }\n\n private _handleStyleChange = () => {\n this._resolveLayers(this._map, this._deck, this._props.layers, this._props.layers);\n if (!this._map) return;\n\n // getProjection() returns undefined before style is loaded\n const projection = getProjection(this._map);\n if (projection) {\n // Update views to match new projection (MapView vs GlobeView)\n this._deck?.setProps({views: this._getViews(this._map)});\n }\n };\n\n private _updateContainerSize = () => {\n if (this._map && this._container) {\n const {clientWidth, clientHeight} = this._map.getContainer();\n Object.assign(this._container.style, {\n width: `${clientWidth}px`,\n height: `${clientHeight}px`\n });\n }\n };\n\n private _getViews(map: Map) {\n if (!this._props.views) {\n return getDefaultView(map);\n }\n // Check if custom views already include a 'mapbox' view\n const views = Array.isArray(this._props.views) ? this._props.views : [this._props.views];\n const hasMapboxView = views.some((v: any) => v.id === MAPBOX_VIEW_ID);\n if (hasMapboxView) {\n return this._props.views;\n }\n // Add default 'mapbox' view to custom views for consistency with interleaved mode\n return [getDefaultView(map), ...views];\n }\n\n private _updateViewState = () => {\n const deck = this._deck;\n const map = this._map;\n if (deck && map) {\n deck.setProps({\n views: this._getViews(map),\n viewState: getViewState(map)\n });\n // Redraw immediately if view state has changed\n if (deck.isInitialized) {\n deck.redraw();\n }\n }\n };\n\n // eslint-disable-next-line complexity\n private _handleMouseEvent = (event: MapMouseEvent) => {\n const deck = this._deck;\n if (!deck || !deck.isInitialized) {\n return;\n }\n\n const mockEvent: {\n type: string;\n deltaX?: number;\n deltaY?: number;\n offsetCenter: {x: number; y: number};\n srcEvent: MapMouseEvent;\n tapCount?: number;\n } = {\n type: event.type,\n offsetCenter: event.point,\n srcEvent: event\n };\n\n const lastDown = this._lastMouseDownPoint;\n if (!event.point && lastDown) {\n // drag* events do not contain a `point` field\n mockEvent.deltaX = event.originalEvent.clientX - lastDown.clientX;\n mockEvent.deltaY = event.originalEvent.clientY - lastDown.clientY;\n mockEvent.offsetCenter = {\n x: lastDown.x + mockEvent.deltaX,\n y: lastDown.y + mockEvent.deltaY\n };\n }\n\n switch (mockEvent.type) {\n case 'mousedown':\n deck._onPointerDown(mockEvent as unknown as MjolnirPointerEvent);\n this._lastMouseDownPoint = {\n ...event.point,\n clientX: event.originalEvent.clientX,\n clientY: event.originalEvent.clientY\n };\n break;\n\n case 'dragstart':\n mockEvent.type = 'panstart';\n deck._onEvent(mockEvent as unknown as MjolnirGestureEvent);\n break;\n\n case 'drag':\n mockEvent.type = 'panmove';\n deck._onEvent(mockEvent as unknown as MjolnirGestureEvent);\n break;\n\n case 'dragend':\n mockEvent.type = 'panend';\n deck._onEvent(mockEvent as unknown as MjolnirGestureEvent);\n break;\n\n case 'click':\n mockEvent.tapCount = 1;\n deck._onEvent(mockEvent as unknown as MjolnirGestureEvent);\n break;\n\n case 'dblclick':\n mockEvent.type = 'click';\n mockEvent.tapCount = 2;\n deck._onEvent(mockEvent as unknown as MjolnirGestureEvent);\n break;\n\n case 'mousemove':\n mockEvent.type = 'pointermove';\n deck._onPointerMove(mockEvent as unknown as MjolnirPointerEvent);\n break;\n\n case 'mouseout':\n mockEvent.type = 'pointerleave';\n deck._onPointerMove(mockEvent as unknown as MjolnirPointerEvent);\n break;\n\n default:\n return;\n }\n };\n}\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport default `\\\n#version 300 es\n#define SHADER_NAME animated-flow-lines-layer-fragment-shader\n\nprecision highp float;\n\nin vec4 vColor;\nin float sourceToTarget;\nin vec2 uv;\n\nout vec4 fragColor;\n \nvoid main(void) {\n geometry.uv = uv;\n\n fragColor = vec4(vColor.xyz, vColor.w * smoothstep(1.0 - animatedFlowLines.animationTailLength, 1.0, fract(sourceToTarget)));\n\n DECKGL_FILTER_COLOR(fragColor, geometry);\n}\n`;\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\nexport default `\\\n#version 300 es\n#define SHADER_NAME animated-flow-lines-layer-vertex-shader\n#define SPEED 0.015\n#define NUM_PARTS 5.0\n\nin vec3 positions;\nin vec3 instanceSourcePositions;\nin vec3 instanceTargetPositions;\nin vec3 instanceSourcePositions64Low;\nin vec3 instanceTargetPositions64Low;\nin vec4 instanceColors;\nin vec3 instancePickingColors;\nin float instanceWidths;\nin float instancePickable;\nin float instanceStaggering;\n\nout vec4 vColor;\nout float sourceToTarget;\nout vec2 uv;\n\n// offset vector by strokeWidth pixels\n// offset_direction is -1 (left) or 1 (right)\nvec2 getExtrusionOffset(vec2 line_clipspace, float offset_direction, float width) {\n // normalized direction of the line\n vec2 dir_screenspace = normalize(line_clipspace * project.viewportSize);\n // rotate by 90 degrees\n dir_screenspace = vec2(-dir_screenspace.y, dir_screenspace.x);\n\n return dir_screenspace * offset_direction * width / 2.0;\n}\n\nvoid main(void) {\n geometry.worldPosition = instanceSourcePositions;\n geometry.worldPositionAlt = instanceTargetPositions;\n\n // Position\n vec4 source_commonspace;\n vec4 target_commonspace;\n vec4 source = project_position_to_clipspace(instanceSourcePositions, instanceSourcePositions64Low, vec3(0.), source_commonspace);\n vec4 target = project_position_to_clipspace(instanceTargetPositions, instanceTargetPositions64Low, vec3(0.), target_commonspace);\n\n float widthPixels = instanceWidths * animatedFlowLines.thicknessUnit;\n \n \n // linear interpolation of source & target to pick right coord\n float segmentIndex = positions.x;\n vec4 p = mix(source, target, segmentIndex);\n geometry.position = mix(source_commonspace, target_commonspace, segmentIndex);\n uv = positions.xy;\n geometry.uv = uv;\n if (instancePickable > 0.5) {\n geometry.pickingColor = instancePickingColors;\n }\n \n // extrude\n vec3 offset = vec3(\n getExtrusionOffset(target.xy - source.xy, positions.y, widthPixels),\n 0.0);\n DECKGL_FILTER_SIZE(offset, geometry);\n gl_Position = p + vec4(project_pixel_size_to_clipspace(offset.xy), 0.0, 0.0);\n DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n\n // Color\n vColor = vec4(instanceColors.rgb, instanceColors.a * layer.opacity);\n DECKGL_FILTER_COLOR(vColor, geometry);\n\n sourceToTarget = positions.x * length(source - target) * NUM_PARTS - animatedFlowLines.currentTime * SPEED + instanceStaggering; \n}\n`;\n","import type {ShaderModule} from '@luma.gl/shadertools';\n\nconst uniformBlock = `\\\nlayout(std140) uniform animatedFlowLinesUniforms {\n float thicknessUnit;\n float animationTailLength;\n float currentTime;\n} animatedFlowLines;\n`;\n\nexport type AnimatedFlowLinesProps = {\n thicknessUnit: number;\n animationTailLength: number;\n currentTime: number;\n};\n\nexport const animatedFlowLinesUniforms = {\n name: 'animatedFlowLines',\n vs: uniformBlock,\n fs: uniformBlock,\n uniformTypes: {\n thicknessUnit: 'f32',\n animationTailLength: 'f32',\n currentTime: 'f32',\n },\n} as const satisfies ShaderModule;\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {Layer, picking, project32} from '@deck.gl/core';\nimport {Geometry, Model} from '@luma.gl/engine';\nimport FragmentShader from './AnimatedFlowLinesLayerFragment.glsl';\nimport VertexShader from './AnimatedFlowLinesLayerVertex.glsl';\nimport {FlowLinesLayerAttributes, RGBA} from '@flowmap.gl/data';\nimport {LayerProps} from '../types';\nimport {animatedFlowLinesUniforms} from './AnimatedFlowLinesLayerUniforms';\nexport interface Props extends LayerProps {\n id: string;\n opacity?: number;\n pickable?: boolean;\n updateTriggers?: {[key: string]: Record};\n data: F[] | FlowLinesLayerAttributes;\n drawOutline: boolean;\n outlineColor?: RGBA;\n outlineThickness?: number;\n currentTime?: number;\n thicknessUnit?: number;\n animationTailLength?: number;\n getSourcePosition?: (d: F) => [number, number];\n getTargetPosition?: (d: F) => [number, number];\n getStaggering?: (d: F, info: AccessorObjectInfo) => number;\n getPickable?: (d: F, {index}: {index: number}) => number; // >= 1.0 -> true\n getColor?: (d: F) => RGBA;\n getThickness?: (d: F) => number;\n getEndpointOffsets?: (d: F) => [number, number];\n}\n\n// https://deck.gl/#/documentation/developer-guide/using-layers?section=accessors\nexport interface AccessorObjectInfo {\n index: number;\n data: any;\n target: any;\n}\n\nconst DEFAULT_COLOR: RGBA = [0, 132, 193, 255];\nconst loopLength = 1800;\nconst animationSpeed = 20;\nconst loopTime = loopLength / animationSpeed;\n\nexport default class AnimatedFlowLinesLayer extends Layer {\n state!: {\n model?: Model;\n };\n\n static defaultProps = {\n currentTime: 0,\n animationTailLength: 0.7,\n getSourcePosition: {type: 'accessor', value: (d: any) => [0, 0]},\n getTargetPosition: {type: 'accessor', value: (d: any) => [0, 0]},\n getPickable: {type: 'accessor', value: (d: any) => 1.0},\n getStaggering: {\n type: 'accessor',\n value: (d: any, {index}: {index: number}) => Math.random(),\n },\n getColor: {type: 'accessor', value: DEFAULT_COLOR},\n getThickness: {type: 'accessor', value: 1},\n thicknessUnit: 15 * 2,\n parameters: {\n depthTest: false,\n },\n };\n\n constructor(props: Props) {\n super(props);\n }\n\n getShaders(): Record {\n return super.getShaders({\n vs: VertexShader,\n fs: FragmentShader,\n modules: [project32, picking, animatedFlowLinesUniforms],\n });\n }\n\n initializeState(): void {\n this.getAttributeManager()!.addInstanced({\n instanceSourcePositions: {\n size: 3,\n type: 'float64',\n transition: true,\n accessor: 'getSourcePosition',\n },\n instanceTargetPositions: {\n size: 3,\n type: 'float64',\n transition: true,\n accessor: 'getTargetPosition',\n },\n instanceColors: {\n size: 4,\n type: 'unorm8',\n transition: true,\n accessor: 'getColor',\n defaultValue: [0, 0, 0, 255],\n },\n instanceWidths: {\n size: 1,\n transition: true,\n accessor: 'getThickness',\n defaultValue: 1,\n },\n instanceStaggering: {\n accessor: 'getStaggering',\n size: 1,\n transition: false,\n },\n instancePickable: {\n accessor: 'getPickable',\n size: 1,\n transition: false,\n },\n });\n this.setState({model: this._getModel()});\n }\n\n getNeedsRedraw(): string | false {\n return 'animation';\n }\n\n updateState(params: any): void {\n super.updateState(params);\n const {changeFlags} = params;\n\n if (!this.state.model || changeFlags.extensionsChanged) {\n this.state.model?.destroy();\n this.setState({model: this._getModel()});\n this.getAttributeManager()!.invalidateAll();\n }\n }\n\n draw(): void {\n const {thicknessUnit = 15 * 2, animationTailLength = 0.7} = this\n .props as unknown as Props;\n const timestamp = Date.now() / 1000;\n const animationTime = ((timestamp % loopTime) / loopTime) * loopLength;\n\n const model = this.state.model;\n if (!model) {\n return;\n }\n model.shaderInputs.setProps({\n animatedFlowLines: {\n thicknessUnit: thicknessUnit * 4,\n animationTailLength,\n currentTime: animationTime,\n },\n });\n model.draw(this.context.renderPass as any);\n }\n\n _getModel(): Model {\n const {id} = this.props as unknown as Props;\n /*\n * (0, -1)-------------_(1, -1)\n * | _,-\" |\n * o _,-\" o\n * | _,-\" |\n * (0, 1)\"-------------(1, 1)\n */\n const positions = [0, -1, 0, 0, 1, 0, 1, -1, 0, 1, 1, 0];\n\n return new Model(this.context.device as any, {\n ...this.getShaders(),\n id,\n bufferLayout: this.getAttributeManager()!.getBufferLayouts(),\n geometry: new Geometry({\n topology: 'triangle-strip',\n attributes: {\n positions: {size: 3, value: new Float32Array(positions)},\n },\n }),\n isInstanced: true,\n });\n }\n}\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport AnimatedFlowLinesLayer from './AnimatedFlowLinesLayer';\n\nexport default AnimatedFlowLinesLayer;\n","import type {ShaderModule} from '@luma.gl/shadertools';\n\nconst uniformBlock = `\\\nlayout(std140) uniform flowLinesUniforms {\n vec4 outlineColor;\n float thicknessUnit;\n float outlineThickness;\n float drawOutline;\n float gap;\n float curviness;\n} flowLines;\n`;\n\nexport type FlowLinesProps = {\n outlineColor: [number, number, number, number];\n thicknessUnit: number;\n outlineThickness: number;\n drawOutline: number;\n gap: number;\n curviness: number;\n};\n\nexport const flowLinesUniforms = {\n name: 'flowLines',\n vs: uniformBlock,\n fs: uniformBlock,\n uniformTypes: {\n outlineColor: 'vec4',\n thicknessUnit: 'f32',\n outlineThickness: 'f32',\n drawOutline: 'f32',\n gap: 'f32',\n curviness: 'f32',\n },\n} as const satisfies ShaderModule;\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\nexport default `\\\n#version 300 es\n#define SHADER_NAME curved-flow-line-layer-fragment-shader\n\nprecision highp float;\n\nin vec4 vColor;\nin vec2 uv;\nin vec3 vBarycentrics;\nflat in vec3 vEdgeMask;\n\nout vec4 fragColor;\n\nvoid main(void) {\n if (vColor.a == 0.0) {\n discard;\n }\n\n geometry.uv = uv;\n fragColor = vColor;\n\n if (flowLines.drawOutline > 0.5 && !bool(picking.isActive)) {\n vec3 edgeDistancePx = vBarycentrics / max(fwidth(vBarycentrics), vec3(1e-4));\n vec3 maskedDistancePx = mix(vec3(1e6), edgeDistancePx, step(vec3(0.5), vEdgeMask));\n float minBoundaryDistancePx = min(\n maskedDistancePx.x,\n min(maskedDistancePx.y, maskedDistancePx.z)\n );\n float outlineMix = 1.0 - smoothstep(\n max(flowLines.outlineThickness - 1.0, 0.0),\n flowLines.outlineThickness,\n minBoundaryDistancePx\n );\n fragColor = mix(\n fragColor,\n vec4(flowLines.outlineColor.rgb, flowLines.outlineColor.a * fragColor.a),\n outlineMix\n );\n }\n\n DECKGL_FILTER_COLOR(fragColor, geometry);\n}\n`;\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\nconst HEAD_START_T = (1 - 1 / 24).toFixed(8);\n\nexport default `\\\n#version 300 es\n#define SHADER_NAME curved-flow-line-layer-vertex-shader\n\nin vec3 positions;\nin vec3 barycentrics;\nin vec3 edgeMasks;\nin vec4 instanceColors;\nin float instanceThickness;\nin vec3 instanceSourcePositions;\nin vec3 instanceTargetPositions;\nin vec3 instanceSourcePositions64Low;\nin vec3 instanceTargetPositions64Low;\nin vec3 instancePickingColors;\nin vec2 instanceEndpointOffsets;\nin float instancePickable;\nin float instanceCurveOffset;\n\nout vec4 vColor;\nout vec2 uv;\nout vec3 vBarycentrics;\nflat out vec3 vEdgeMask;\n\nvec3 quadraticBezier(vec3 p0, vec3 p1, vec3 p2, float t) {\n float oneMinusT = 1.0 - t;\n return\n oneMinusT * oneMinusT * p0 +\n 2.0 * oneMinusT * t * p1 +\n t * t * p2;\n}\n\nvec3 quadraticBezierTangent(vec3 p0, vec3 p1, vec3 p2, float t) {\n return 2.0 * (1.0 - t) * (p1 - p0) + 2.0 * t * (p2 - p1);\n}\n\nvoid main(void) {\n geometry.worldPosition = instanceSourcePositions;\n geometry.worldPositionAlt = instanceTargetPositions;\n\n vec4 source_commonspace;\n vec4 target_commonspace;\n project_position_to_clipspace(\n instanceSourcePositions,\n instanceSourcePositions64Low,\n vec3(0.0),\n source_commonspace\n );\n project_position_to_clipspace(\n instanceTargetPositions,\n instanceTargetPositions64Low,\n vec3(0.0),\n target_commonspace\n );\n\n vec2 chord = target_commonspace.xy - source_commonspace.xy;\n float chordLengthCommon = max(length(chord), 1e-6);\n float startTrim = clamp(\n project_pixel_size(instanceEndpointOffsets.x) / chordLengthCommon,\n 0.0,\n 0.35\n );\n float endTrim = 1.0 - clamp(\n project_pixel_size(instanceEndpointOffsets.y) / chordLengthCommon,\n 0.0,\n 0.35\n );\n endTrim = max(startTrim + 0.05, endTrim);\n float baseHeadBacktrackT = project_pixel_size(\n instanceThickness * 3.0 * flowLines.thicknessUnit\n ) / chordLengthCommon;\n float availableSpanT = max(endTrim - startTrim, 0.0);\n float headBacktrackT = min(baseHeadBacktrackT, availableSpanT * 0.45);\n float headScale = baseHeadBacktrackT > 1e-6\n ? clamp(headBacktrackT / baseHeadBacktrackT, 0.0, 1.0)\n : 1.0;\n // A soft nonlinear fade of the head deformation avoids tiny heads folding\n // into themselves while still allowing them to collapse back toward the strip.\n float headDeformation = smoothstep(0.0, 1.0, headScale);\n float shaftEndTrim = max(startTrim + 0.02, endTrim - headBacktrackT);\n\n float curveT = positions.x < 1.0\n ? mix(startTrim, shaftEndTrim, positions.x / ${HEAD_START_T})\n : endTrim;\n float headWeight = smoothstep(${HEAD_START_T}, 1.0, positions.x);\n float tangentT = mix(curveT, endTrim, headWeight);\n vec2 curveNormal = normalize(vec2(chord.y, -chord.x));\n if (length(curveNormal) < 1e-6) {\n curveNormal = vec2(0.0, 1.0);\n }\n vec3 control_commonspace = mix(\n source_commonspace.xyz,\n target_commonspace.xyz,\n 0.5\n );\n control_commonspace.xy += curveNormal * project_pixel_size(abs(instanceCurveOffset)) * flowLines.curviness;\n\n vec3 curvePoint = quadraticBezier(\n source_commonspace.xyz,\n control_commonspace,\n target_commonspace.xyz,\n curveT\n );\n vec3 tangent = quadraticBezierTangent(\n source_commonspace.xyz,\n control_commonspace,\n target_commonspace.xyz,\n tangentT\n );\n if (length(tangent.xy) < 1e-6) {\n tangent = target_commonspace.xyz - source_commonspace.xyz;\n }\n\n vec2 flowlineDir = normalize(tangent.xy);\n vec2 perpendicularDir = vec2(-flowlineDir.y, flowlineDir.x);\n float widthScale = mix(1.0, headScale, headWeight);\n float lengthScale = mix(1.0, headScale, headWeight);\n float shapeY = mix(min(positions.y, 1.0), positions.y, headDeformation);\n float shapeZ = positions.z * headDeformation;\n float normalDistanceCommon = clamp(\n project_pixel_size(\n instanceThickness * shapeY * widthScale * flowLines.thicknessUnit\n ),\n -chordLengthCommon * 0.8,\n chordLengthCommon * 0.8\n );\n float tangentDistanceCommon = clamp(\n project_pixel_size(\n instanceThickness * shapeZ * lengthScale * flowLines.thicknessUnit\n ),\n -chordLengthCommon * 0.8,\n chordLengthCommon * 0.8\n );\n float gapCommon = project_pixel_size(flowLines.gap);\n vec3 offsetCommon = vec3(\n flowlineDir * tangentDistanceCommon -\n perpendicularDir * (normalDistanceCommon + gapCommon),\n 0.0\n );\n\n geometry.position = vec4(curvePoint, 1.0);\n uv = vec2(curveT, positions.y);\n geometry.uv = uv;\n vBarycentrics = barycentrics;\n vEdgeMask = edgeMasks;\n if (instancePickable > 0.5) {\n geometry.pickingColor = instancePickingColors;\n }\n\n DECKGL_FILTER_SIZE(offsetCommon, geometry);\n vec4 position_commonspace = vec4(curvePoint + offsetCommon, 1.0);\n gl_Position = project_common_position_to_clipspace(position_commonspace);\n DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n\n vec4 fillColor = vec4(instanceColors.rgb, instanceColors.a * layer.opacity);\n vColor = fillColor;\n DECKGL_FILTER_COLOR(vColor, geometry);\n}\n`;\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {Layer, picking, project32} from '@deck.gl/core';\nimport {FlowLinesLayerAttributes, RGBA} from '@flowmap.gl/data';\nimport {Geometry, Model} from '@luma.gl/engine';\nimport {flowLinesUniforms} from '../FlowLinesLayer/FlowLinesLayerUniforms';\nimport {LayerProps} from '../types';\nimport FragmentShader from './CurvedFlowLinesLayerFragment.glsl';\nimport VertexShader from './CurvedFlowLinesLayerVertex.glsl';\n\nexport interface Props extends LayerProps {\n id: string;\n opacity?: number;\n pickable?: boolean;\n updateTriggers?: {[key: string]: Record};\n data: F[] | FlowLinesLayerAttributes;\n drawOutline: boolean;\n outlineColor?: RGBA;\n outlineThickness?: number;\n thicknessUnit?: number;\n getSourcePosition?: (d: F) => [number, number];\n getTargetPosition?: (d: F) => [number, number];\n getColor?: (d: F) => RGBA;\n getThickness?: (d: F) => number;\n getPickable?: (d: F, {index}: {index: number}) => number;\n getEndpointOffsets?: (d: F) => [number, number];\n getCurveOffset?: (d: F) => number;\n curviness?: number;\n}\n\nconst DEFAULT_COLOR: RGBA = [0, 132, 193, 255];\nconst SHAFT_SEGMENTS = 24;\nconst HEAD_START_T = 1 - 1 / SHAFT_SEGMENTS;\n\ntype GeometryBuffers = {\n positions: Float32Array;\n barycentrics: Float32Array;\n edgeMasks: Float32Array;\n};\n\nexport default class CurvedFlowLinesLayer extends Layer {\n static layerName = 'CurvedFlowLinesLayer';\n\n state!: {\n model?: Model;\n };\n\n static defaultProps = {\n getSourcePosition: {type: 'accessor', value: (d: any) => [0, 0]},\n getTargetPosition: {type: 'accessor', value: (d: any) => [0, 0]},\n getColor: {type: 'accessor', value: DEFAULT_COLOR},\n getThickness: {type: 'accessor', value: (d: any) => d.count},\n getPickable: {type: 'accessor', value: () => 1.0},\n getCurveOffset: {type: 'accessor', value: () => 0},\n drawOutline: true,\n thicknessUnit: 12,\n outlineThickness: 1,\n outlineColor: [255, 255, 255, 255],\n curviness: 1,\n parameters: {\n depthTest: false,\n },\n };\n\n getShaders(): Record {\n return super.getShaders({\n vs: VertexShader,\n fs: FragmentShader,\n modules: [project32, picking, flowLinesUniforms],\n });\n }\n\n initializeState(): void {\n this.getAttributeManager()!.addInstanced({\n instanceSourcePositions: {\n accessor: 'getSourcePosition',\n size: 3,\n transition: false,\n type: 'float64',\n },\n instanceTargetPositions: {\n accessor: 'getTargetPosition',\n size: 3,\n transition: false,\n type: 'float64',\n },\n instanceThickness: {\n accessor: 'getThickness',\n size: 1,\n transition: false,\n },\n instanceEndpointOffsets: {\n accessor: 'getEndpointOffsets',\n size: 2,\n transition: false,\n },\n instanceCurveOffset: {\n accessor: 'getCurveOffset',\n size: 1,\n transition: false,\n },\n instanceColors: {\n accessor: 'getColor',\n size: 4,\n type: 'unorm8',\n transition: false,\n },\n instancePickable: {\n accessor: 'getPickable',\n size: 1,\n transition: false,\n },\n });\n this.setState({model: this._getModel()});\n }\n\n updateState(params: any): void {\n super.updateState(params);\n const {changeFlags} = params;\n\n if (!this.state.model || changeFlags.extensionsChanged) {\n this.state.model?.destroy();\n this.setState({model: this._getModel()});\n this.getAttributeManager()!.invalidateAll();\n }\n }\n\n draw(): void {\n const {\n drawOutline = true,\n outlineColor = [255, 255, 255, 255],\n outlineThickness = 1,\n thicknessUnit = 12,\n curviness = 1,\n } = this.props as unknown as Props;\n const model = this.state.model;\n if (!model) {\n return;\n }\n model.shaderInputs.setProps({\n flowLines: {\n outlineColor: outlineColor.map((x: number) => x / 255) as [\n number,\n number,\n number,\n number,\n ],\n thicknessUnit: thicknessUnit * 2.0,\n outlineThickness,\n drawOutline: drawOutline ? 1 : 0,\n gap: 0.5,\n curviness,\n },\n });\n model.draw(this.context.renderPass as any);\n }\n\n _getModel(): Model {\n const {id} = this.props as unknown as Props;\n const geometry = buildGeometry();\n\n return new Model(this.context.device as any, {\n id,\n ...this.getShaders(),\n bufferLayout: this.getAttributeManager()!.getBufferLayouts(),\n geometry: new Geometry({\n topology: 'triangle-list',\n attributes: {\n positions: {size: 3, value: geometry.positions},\n barycentrics: {size: 3, value: geometry.barycentrics},\n edgeMasks: {size: 3, value: geometry.edgeMasks},\n },\n }),\n isInstanced: true,\n });\n }\n}\n\nfunction buildGeometry(): GeometryBuffers {\n const positions: number[] = [];\n const barycentrics: number[] = [];\n const edgeMasks: number[] = [];\n\n const pushTriangle = (\n a: [number, number, number],\n b: [number, number, number],\n c: [number, number, number],\n mask: [number, number, number],\n ) => {\n positions.push(...a, ...b, ...c);\n barycentrics.push(1, 0, 0, 0, 1, 0, 0, 0, 1);\n edgeMasks.push(...mask, ...mask, ...mask);\n };\n\n for (let index = 0; index < SHAFT_SEGMENTS - 1; index++) {\n const t0 = index / SHAFT_SEGMENTS;\n const t1 = (index + 1) / SHAFT_SEGMENTS;\n pushTriangle(\n [t0, 1, 0],\n [t1, 1, 0],\n [t0, 0, 0],\n [0, index === 0 ? 1 : 0, 1],\n );\n pushTriangle([t0, 0, 0], [t1, 1, 0], [t1, 0, 0], [0, 1, 0]);\n }\n\n pushTriangle(\n [HEAD_START_T, 1, 0],\n [1, 1.7, -4.4],\n [HEAD_START_T, 0, 0],\n [0, 0, 1],\n );\n pushTriangle([HEAD_START_T, 0, 0], [1, 1.7, -4.4], [1, 0, 0], [1, 1, 0]);\n\n return {\n positions: new Float32Array(positions),\n barycentrics: new Float32Array(barycentrics),\n edgeMasks: new Float32Array(edgeMasks),\n };\n}\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport CurvedFlowLinesLayer from './CurvedFlowLinesLayer';\n\nexport default CurvedFlowLinesLayer;\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\nexport default `\\\n#version 300 es\n#define SHADER_NAME flow-line-layer-fragment-shader\n\nprecision highp float;\n\nin vec4 vColor;\nin vec2 uv;\nin vec3 vBarycentrics;\nflat in vec3 vEdgeMask;\n\nout vec4 fragColor;\n\nvoid main(void) {\n if (vColor.a == 0.0) {\n discard;\n }\n\n geometry.uv = uv;\n fragColor = vColor;\n\n if (flowLines.drawOutline > 0.5 && !bool(picking.isActive)) {\n // For barycentric coordinates, each component trends to 0 on one triangle edge.\n // Dividing by fwidth converts that into an approximate edge distance in pixels.\n vec3 edgeDistancePx = vBarycentrics / max(fwidth(vBarycentrics), vec3(1e-4));\n // Ignore edges that are only part of the internal triangulation by assigning\n // them a large sentinel distance, so only true boundary edges contribute.\n vec3 maskedDistancePx = mix(vec3(1e6), edgeDistancePx, step(vec3(0.5), vEdgeMask));\n float minBoundaryDistancePx = min(\n maskedDistancePx.x,\n min(maskedDistancePx.y, maskedDistancePx.z)\n );\n // The outline is inset: fragments within 'outlineThickness' pixels of an\n // active boundary edge are mixed toward the outline color.\n float outlineMix = 1.0 - smoothstep(\n max(flowLines.outlineThickness - 1.0, 0.0),\n flowLines.outlineThickness,\n minBoundaryDistancePx\n );\n fragColor = mix(\n fragColor,\n vec4(flowLines.outlineColor.rgb, flowLines.outlineColor.a * fragColor.a),\n outlineMix\n );\n }\n\n DECKGL_FILTER_COLOR(fragColor, geometry);\n}\n`;\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\nexport default `\\\n#version 300 es\n#define SHADER_NAME flow-line-layer-vertex-shader\n\nin vec3 positions;\nin vec2 pixelOffsets;\nin vec2 outlineOffsetCoefficients;\nin vec2 outlineOffsetConstants;\nin vec3 barycentrics;\nin vec3 edgeMasks;\nin vec4 instanceColors;\nin float instanceThickness; // 0..0.5\nin vec3 instanceSourcePositions;\nin vec3 instanceTargetPositions;\nin vec3 instanceSourcePositions64Low;\nin vec3 instanceTargetPositions64Low;\nin vec3 instancePickingColors;\nin vec2 instanceEndpointOffsets;\nin float instancePickable;\n\nout vec4 vColor;\nout vec2 uv;\n// Interpolated barycentric coordinates let the fragment shader measure distance\n// to triangle edges in screen pixels without extra geometry.\nout vec3 vBarycentrics;\n// The edge mask is constant per triangle and tells the fragment shader which\n// barycentric edges are real outline candidates vs internal triangulation seams.\nflat out vec3 vEdgeMask;\n\nvoid main(void) {\n geometry.worldPosition = instanceSourcePositions;\n geometry.worldPositionAlt = instanceTargetPositions;\n \n // Position\n vec4 source_commonspace; \n vec4 target_commonspace;\n project_position_to_clipspace(instanceSourcePositions, instanceSourcePositions64Low, vec3(0.), source_commonspace);\n project_position_to_clipspace(instanceTargetPositions, instanceTargetPositions64Low, vec3(0.), target_commonspace);\n\n // linear interpolation of source & target to pick right coord\n float sourceOrTarget = positions.x;\n geometry.position = mix(source_commonspace, target_commonspace, sourceOrTarget);\n uv = positions.xy;\n geometry.uv = uv;\n vBarycentrics = barycentrics;\n vEdgeMask = edgeMasks;\n if (instancePickable > 0.5) {\n geometry.pickingColor = instancePickingColors;\n }\n \n // set the clamp limits in pixel size \n float lengthCommon = length(target_commonspace - source_commonspace); \n vec2 limitedOffsetDistances = clamp( \n project_pixel_size(positions.yz) * flowLines.thicknessUnit,\n -lengthCommon*.8, lengthCommon*.8\n );\n float startOffsetCommon = project_pixel_size(instanceEndpointOffsets[0]);\n float endOffsetCommon = project_pixel_size(instanceEndpointOffsets[1]);\n float endpointOffset = mix(\n clamp(startOffsetCommon, 0.0, lengthCommon*.2),\n -clamp(endOffsetCommon, 0.0, lengthCommon*.2),\n positions.x\n );\n\n vec2 flowlineDir = normalize(target_commonspace.xy - source_commonspace.xy);\n vec2 perpendicularDir = vec2(-flowlineDir.y, flowlineDir.x);\n vec2 outlinePixelOffset = (\n outlineOffsetCoefficients * flowLines.outlineThickness +\n outlineOffsetConstants\n ) * flowLines.drawOutline;\n vec2 pixelOffsetCommon = project_pixel_size(pixelOffsets + outlinePixelOffset);\n float gapCommon = project_pixel_size(flowLines.gap);\n vec3 offsetCommon = vec3(\n flowlineDir * (instanceThickness * limitedOffsetDistances[1] + pixelOffsetCommon.y + endpointOffset * 1.05) -\n perpendicularDir * (instanceThickness * limitedOffsetDistances[0] + gapCommon + pixelOffsetCommon.x),\n 0.0\n );\n \n DECKGL_FILTER_SIZE(offsetCommon, geometry);\n vec4 position_commonspace = mix(source_commonspace, target_commonspace, sourceOrTarget);\n vec4 offset_commonspace = vec4(offsetCommon, 0.0);\n gl_Position = project_common_position_to_clipspace(position_commonspace + offset_commonspace);\n \n DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n \n vec4 fillColor = vec4(instanceColors.rgb, instanceColors.a * layer.opacity);\n vColor = fillColor;\n DECKGL_FILTER_COLOR(vColor, geometry);\n}\n`;\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {Layer, picking, project32} from '@deck.gl/core';\nimport {FlowLinesLayerAttributes, RGBA} from '@flowmap.gl/data';\nimport {Geometry, Model} from '@luma.gl/engine';\nimport {LayerProps} from '../types';\nimport FragmentShader from './FlowLinesLayerFragment.glsl';\nimport {flowLinesUniforms} from './FlowLinesLayerUniforms';\nimport VertexShader from './FlowLinesLayerVertex.glsl';\n\nexport interface Props extends LayerProps {\n id: string;\n opacity?: number;\n pickable?: boolean;\n updateTriggers?: {[key: string]: Record};\n data: F[] | FlowLinesLayerAttributes;\n drawOutline: boolean;\n outlineColor?: RGBA;\n outlineThickness?: number;\n thicknessUnit?: number;\n getSourcePosition?: (d: F) => [number, number];\n getTargetPosition?: (d: F) => [number, number];\n getColor?: (d: F) => RGBA;\n getThickness?: (d: F) => number;\n getPickable?: (d: F, {index}: {index: number}) => number; // >= 1.0 -> true\n getEndpointOffsets?: (d: F) => [number, number];\n}\n\nconst DEFAULT_COLOR: RGBA = [0, 132, 193, 255];\n\n// source_target_mix, perpendicular_offset_in_thickness_units, direction_of_travel_offset_in_thickness_units\n// prettier-ignore\nconst POSITIONS = [\n 1, 0, 0, // 0\n 1, 2, -3, // 1\n 1, 1, -3, // 2\n\n\n 1, 0, 0, // 0\n 1, 1, -3, // 2\n 0, 1, 0, // 3\n\n\n 1, 0, 0, // 0\n 0, 1, 0, // 3\n 0, 0, 0, // 4\n];\n/**\n 1\n ··\n · ··\n · ··\n 3 2 · ··\n ······························· ··\n · ······· ···· ··\n · ········ ····· ··\n · ··············· ····· ··\n · ········ ········\n · ················\n 4 ························································ 0\n\n */\nconst INNER_SIDE_OUTLINE_THICKNESS = 0.5;\n\n// Base per-vertex pixel offsets for the fill shape.\nconst PIXEL_OFFSETS = new Float32Array(9 * 2);\n\n// Coefficients for the extra per-vertex expansion when outline rendering is enabled.\n// Multiplied by `outlineThickness` in the vertex shader.\n// prettier-ignore\nconst OUTLINE_OFFSET_COEFFICIENTS = new Float32Array([\n 0, 2,\n 2, -1,\n 1, -1,\n\n 0, 2,\n 1, -1,\n 1, -1,\n\n 0, 2,\n 1, -1,\n 0, -1,\n]);\n\n// Constant pixel tweaks applied regardless of outline thickness to keep the\n// leading arrowhead from visually swallowing the opposite edge.\n// prettier-ignore\nconst OUTLINE_OFFSET_CONSTANTS = new Float32Array([\n -INNER_SIDE_OUTLINE_THICKNESS, 0,\n 0, 0,\n 0, 0,\n\n -INNER_SIDE_OUTLINE_THICKNESS, 0,\n 0, 0,\n 0, 0,\n\n -INNER_SIDE_OUTLINE_THICKNESS, 0,\n 0, 0,\n -INNER_SIDE_OUTLINE_THICKNESS, 0,\n]);\n\n// One barycentric basis per triangle. After interpolation in the fragment shader,\n// each component goes to 0 on the edge opposite its vertex, which lets us compute\n// a stable pixel distance to each triangle edge using `fwidth`.\n// prettier-ignore\nconst BARYCENTRICS = new Float32Array([\n 1, 0, 0,\n 0, 1, 0,\n 0, 0, 1,\n\n 1, 0, 0,\n 0, 1, 0,\n 0, 0, 1,\n\n 1, 0, 0,\n 0, 1, 0,\n 0, 0, 1,\n]);\n\n// Each component maps to the edge opposite the matching barycentric component.\n// A value of 1 means \"this is a real polygon boundary edge that may receive the\n// inset outline\"; 0 means \"ignore this edge\" so the fragment shader does not draw\n// seams along the internal triangle splits used to build the arrow shape.\n// prettier-ignore\nconst EDGE_MASKS = new Float32Array([\n 1, 0, 1,\n 1, 0, 1,\n 1, 0, 1,\n\n 1, 0, 0,\n 1, 0, 0,\n 1, 0, 0,\n\n 1, 1, 0,\n 1, 1, 0,\n 1, 1, 0,\n]);\n\nclass FlowLinesLayer extends Layer {\n static layerName = 'FlowLinesLayer';\n\n state!: {\n model?: Model;\n };\n\n static defaultProps = {\n getSourcePosition: {type: 'accessor', value: (d: any) => [0, 0]},\n getTargetPosition: {type: 'accessor', value: (d: any) => [0, 0]},\n getColor: {type: 'accessor', value: DEFAULT_COLOR},\n getThickness: {type: 'accessor', value: (d: any) => d.count}, // 0..0.5\n getPickable: {type: 'accessor', value: (d: any) => 1.0},\n drawOutline: true,\n thicknessUnit: 12,\n outlineThickness: 1,\n outlineColor: [255, 255, 255, 255],\n parameters: {\n depthTest: false,\n },\n };\n // props!: Props;\n\n constructor(props: Props) {\n super(props);\n }\n\n getShaders(): Record {\n return super.getShaders({\n vs: VertexShader,\n fs: FragmentShader,\n modules: [project32, picking, flowLinesUniforms],\n });\n }\n\n initializeState(): void {\n this.getAttributeManager()!.addInstanced({\n instanceSourcePositions: {\n accessor: 'getSourcePosition',\n size: 3,\n transition: false,\n type: 'float64',\n },\n instanceTargetPositions: {\n accessor: 'getTargetPosition',\n size: 3,\n transition: false,\n type: 'float64',\n },\n instanceThickness: {\n accessor: 'getThickness',\n size: 1,\n transition: false,\n },\n instanceEndpointOffsets: {\n accessor: 'getEndpointOffsets',\n size: 2,\n transition: false,\n },\n instanceColors: {\n accessor: 'getColor',\n size: 4,\n type: 'unorm8',\n transition: false,\n },\n instancePickable: {\n accessor: 'getPickable',\n size: 1,\n transition: false,\n },\n });\n this.setState({model: this._getModel()});\n }\n\n updateState(params: any): void {\n super.updateState(params);\n const {changeFlags} = params;\n\n if (!this.state.model || changeFlags.extensionsChanged) {\n this.state.model?.destroy();\n this.setState({model: this._getModel()});\n this.getAttributeManager()!.invalidateAll();\n }\n }\n\n draw(): void {\n const {\n drawOutline = true,\n outlineColor = [255, 255, 255, 255],\n outlineThickness = 1,\n thicknessUnit = 12,\n } = this.props as unknown as Props;\n const model = this.state.model;\n if (!model) {\n return;\n }\n model.shaderInputs.setProps({\n flowLines: {\n outlineColor: outlineColor.map((x: number) => x / 255) as [\n number,\n number,\n number,\n number,\n ],\n thicknessUnit: thicknessUnit * 2.0,\n outlineThickness,\n drawOutline: drawOutline ? 1 : 0,\n gap: 0.5,\n curviness: 1.0,\n },\n });\n model.draw(this.context.renderPass as any);\n }\n\n _getModel(): Model {\n const {id} = this.props as unknown as Props;\n\n return new Model(this.context.device as any, {\n id,\n ...this.getShaders(),\n bufferLayout: this.getAttributeManager()!.getBufferLayouts(),\n geometry: new Geometry({\n topology: 'triangle-list',\n attributes: {\n positions: {size: 3, value: new Float32Array(POSITIONS)},\n pixelOffsets: {size: 2, value: PIXEL_OFFSETS},\n outlineOffsetCoefficients: {\n size: 2,\n value: OUTLINE_OFFSET_COEFFICIENTS,\n },\n outlineOffsetConstants: {\n size: 2,\n value: OUTLINE_OFFSET_CONSTANTS,\n },\n barycentrics: {size: 3, value: BARYCENTRICS},\n edgeMasks: {size: 3, value: EDGE_MASKS},\n },\n }),\n isInstanced: true,\n });\n }\n}\n\nexport default FlowLinesLayer;\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport FlowLinesLayer from './FlowLinesLayer';\n\nexport default FlowLinesLayer;\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\nexport default `\\\n#version 300 es\n#define SHADER_NAME flow-circles-layer-fragment-shader\n#define SOFT_OUTLINE 0.05\n#define EPS 0.05\nprecision highp float;\n\nin vec4 vColor;\nin vec2 unitPosition;\nin float unitInRadius;\nin float unitOutRadius;\n\nout vec4 fragColor;\n\nfloat when_gt(float x, float y) {\n return max(sign(x - y), 0.0);\n}\n\nvoid main(void) {\n geometry.uv = unitPosition;\n float distToCenter = length(unitPosition);\n if (distToCenter > 1.0) {\n discard;\n }\n\n // See https://stackoverflow.com/questions/47285778\n vec4 ringColor = mix(\n flowCircles.emptyColor, vColor,\n when_gt(unitInRadius, unitOutRadius)\n );\n vec4 outlineColor = mix(\n mix(vColor, flowCircles.emptyColor, flowCircles.outlineEmptyMix),\n vColor,\n when_gt(unitInRadius, unitOutRadius)\n );\n \n float innerR = min(unitInRadius, unitOutRadius) * (1.0 - SOFT_OUTLINE);\n \n // Inner circle\n float step2 = innerR - 2.0 * EPS; \n float step3 = innerR - EPS;\n \n // Ring\n float step4 = innerR;\n // float step5 = 1.0 - SOFT_OUTLINE - EPS;\n // float step6 = 1.0 - SOFT_OUTLINE;\n float step5 = 1.0 - 5.0 * EPS;\n float step6 = 1.0;\n \n fragColor = vColor;\n fragColor = mix(fragColor, flowCircles.emptyColor, smoothstep(step2, step3, distToCenter));\n fragColor = mix(fragColor, ringColor, smoothstep(step3, step4, distToCenter));\n fragColor = mix(fragColor, outlineColor, smoothstep(step5, step6, distToCenter));\n fragColor.a = vColor.a;\n fragColor.a *= smoothstep(0.0, SOFT_OUTLINE, 1.0 - distToCenter);\n DECKGL_FILTER_COLOR(fragColor, geometry);\n}\n`;\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\nexport default `\\\n#version 300 es\n#define SHADER_NAME flow-circles-layer-vertex-shader\n#define radiusScale 100\n\nin vec3 positions;\n\nin vec3 instancePositions;\nin vec3 instancePositions64Low;\nin float instanceInRadius;\nin float instanceOutRadius;\nin vec4 instanceColors;\nin vec3 instancePickingColors;\n\nout vec4 vColor;\nout vec2 unitPosition;\nout float unitInRadius;\nout float unitOutRadius;\n\nvoid main(void) {\n geometry.worldPosition = instancePositions;\n\n float outerRadiusPixels = max(instanceInRadius, instanceOutRadius);\n unitInRadius = instanceInRadius / outerRadiusPixels; \n unitOutRadius = instanceOutRadius / outerRadiusPixels; \n\n // position on the containing square in [-1, 1] space\n unitPosition = positions.xy;\n geometry.uv = unitPosition;\n geometry.pickingColor = instancePickingColors;\n \n // Find the center of the point and add the current vertex\n vec3 offset = positions * project_pixel_size(outerRadiusPixels);\n DECKGL_FILTER_SIZE(offset, geometry);\n gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset, geometry.position);\n DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n \n // Apply opacity to instance color, or return instance picking color\n vColor = vec4(instanceColors.rgb, instanceColors.a * layer.opacity);\n DECKGL_FILTER_COLOR(vColor, geometry);\n}\n`;\n","import type {ShaderModule} from '@luma.gl/shadertools';\n\nconst uniformBlock = `\\\nlayout(std140) uniform flowCirclesUniforms {\n vec4 emptyColor;\n float outlineEmptyMix;\n} flowCircles;\n`;\n\nexport type FlowCirclesProps = {\n emptyColor: [number, number, number, number];\n outlineEmptyMix: number;\n};\n\nexport const flowCirclesUniforms = {\n name: 'flowCircles',\n vs: uniformBlock,\n fs: uniformBlock,\n uniformTypes: {\n emptyColor: 'vec4',\n outlineEmptyMix: 'f32',\n },\n} as const satisfies ShaderModule;\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {Layer, picking, project32} from '@deck.gl/core';\nimport {Geometry, Model} from '@luma.gl/engine';\nimport FragmentShader from './FlowCirclesLayerFragment.glsl';\nimport VertexShader from './FlowCirclesLayerVertex.glsl';\nimport {FlowCirclesLayerAttributes, RGBA} from '@flowmap.gl/data';\nimport {LayerProps} from '../types';\nimport {flowCirclesUniforms} from './FlowCirclesLayerUniforms';\n\nexport type FlowCirclesDatum = Record;\n\nexport interface Props extends LayerProps {\n id: string;\n opacity?: number;\n pickable?: boolean;\n emptyColor?: RGBA;\n outlineEmptyMix?: number;\n getColor?: (d: FlowCirclesDatum) => RGBA;\n getPosition?: (d: FlowCirclesDatum) => [number, number];\n getInRadius?: (d: FlowCirclesDatum) => number;\n getOutRadius?: (d: FlowCirclesDatum) => number;\n data: FlowCirclesDatum[] | FlowCirclesLayerAttributes;\n updateTriggers?: {[key: string]: Record};\n}\n\nconst DEFAULT_COLOR = [0, 0, 0, 255];\nconst DEFAULT_EMPTY_COLOR = [255, 255, 255, 255];\nconst DEFAULT_OUTLINE_EMPTY_MIX = 0.4;\n\nclass FlowCirclesLayer extends Layer {\n static layerName = 'FlowCirclesLayer';\n\n state!: {\n model?: Model;\n };\n\n static defaultProps = {\n getColor: {type: 'accessor', value: DEFAULT_COLOR},\n emptyColor: {type: 'accessor', value: DEFAULT_EMPTY_COLOR},\n outlineEmptyMix: {type: 'accessor', value: DEFAULT_OUTLINE_EMPTY_MIX},\n getPosition: {type: 'accessor', value: (d: FlowCirclesDatum) => d.position},\n getInRadius: {type: 'accessor', value: 1},\n getOutRadius: {type: 'accessor', value: 1},\n parameters: {\n depthTest: false,\n },\n };\n // props!: Props;\n\n constructor(props: Props) {\n super(props);\n }\n\n getShaders() {\n return super.getShaders({\n vs: VertexShader,\n fs: FragmentShader,\n modules: [project32, picking, flowCirclesUniforms],\n });\n }\n\n initializeState() {\n this.getAttributeManager()!.addInstanced({\n instancePositions: {\n size: 3,\n type: 'float64',\n fp64: this.use64bitPositions(),\n transition: true,\n accessor: 'getPosition',\n },\n instanceInRadius: {\n size: 1,\n transition: true,\n accessor: 'getInRadius',\n defaultValue: 1,\n },\n instanceOutRadius: {\n size: 1,\n transition: true,\n accessor: 'getOutRadius',\n defaultValue: 1,\n },\n instanceColors: {\n size: 4,\n transition: true,\n type: 'unorm8',\n accessor: 'getColor',\n defaultValue: DEFAULT_COLOR,\n },\n });\n this.setState({model: this._getModel()});\n }\n\n updateState(params: any) {\n super.updateState(params);\n const {changeFlags} = params;\n if (!this.state.model || changeFlags.extensionsChanged) {\n this.state.model?.destroy();\n this.setState({model: this._getModel()});\n this.getAttributeManager()!.invalidateAll();\n }\n }\n\n draw() {\n const {\n emptyColor = DEFAULT_EMPTY_COLOR,\n outlineEmptyMix = DEFAULT_OUTLINE_EMPTY_MIX,\n } = this.props as unknown as Props;\n const model = this.state.model;\n if (!model) {\n return;\n }\n model.shaderInputs.setProps({\n flowCircles: {\n emptyColor: emptyColor.map((x: number) => x / 255) as [\n number,\n number,\n number,\n number,\n ],\n outlineEmptyMix,\n },\n });\n model.draw(this.context.renderPass as any);\n }\n\n _getModel(): Model {\n const {id} = this.props as unknown as Props;\n // a square that minimally cover the unit circle\n const positions = [-1, -1, 0, 1, -1, 0, -1, 1, 0, 1, 1, 0];\n\n return new Model(this.context.device as any, {\n ...this.getShaders(),\n id,\n bufferLayout: this.getAttributeManager()!.getBufferLayouts(),\n geometry: new Geometry({\n topology: 'triangle-strip',\n attributes: {\n positions: {size: 3, value: new Float32Array(positions)},\n },\n }),\n isInstanced: true,\n });\n }\n}\n\nexport default FlowCirclesLayer;\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport FlowCirclesLayer from './FlowCirclesLayer';\n\nexport default FlowCirclesLayer;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ShaderModule} from '@luma.gl/shadertools';\nimport {Texture} from '@luma.gl/core';\n\nconst uniformBlock = `\\\nlayout(std140) uniform iconUniforms {\n float sizeScale;\n vec2 iconsTextureDim;\n float sizeBasis;\n float sizeMinPixels;\n float sizeMaxPixels;\n bool billboard;\n highp int sizeUnits;\n float alphaCutoff;\n} icon;\n`;\n\ntype IconBindingProps = {\n iconsTexture: Texture;\n};\n\ntype IconUniformProps = {\n sizeScale: number;\n iconsTextureDim: [number, number];\n sizeBasis: number;\n sizeMinPixels: number;\n sizeMaxPixels: number;\n billboard: boolean;\n sizeUnits: number;\n alphaCutoff: number;\n};\n\nexport type IconProps = IconBindingProps & IconUniformProps;\n\nexport const iconUniforms = {\n name: 'icon',\n vs: uniformBlock,\n fs: uniformBlock,\n uniformTypes: {\n sizeScale: 'f32',\n iconsTextureDim: 'vec2',\n sizeBasis: 'f32',\n sizeMinPixels: 'f32',\n sizeMaxPixels: 'f32',\n billboard: 'f32',\n sizeUnits: 'i32',\n alphaCutoff: 'f32'\n }\n} as const satisfies ShaderModule;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport default `\\\n#version 300 es\n#define SHADER_NAME icon-layer-vertex-shader\n\nin vec2 positions;\n\nin vec3 instancePositions;\nin vec3 instancePositions64Low;\nin float instanceSizes;\nin float instanceAngles;\nin vec4 instanceColors;\nin vec3 instancePickingColors;\nin vec4 instanceIconFrames;\nin float instanceColorModes;\nin vec2 instanceOffsets;\nin vec2 instancePixelOffset;\n\nout float vColorMode;\nout vec4 vColor;\nout vec2 vTextureCoords;\nout vec2 uv;\n\nvec2 rotate_by_angle(vec2 vertex, float angle) {\n float angle_radian = angle * PI / 180.0;\n float cos_angle = cos(angle_radian);\n float sin_angle = sin(angle_radian);\n mat2 rotationMatrix = mat2(cos_angle, -sin_angle, sin_angle, cos_angle);\n return rotationMatrix * vertex;\n}\n\nvoid main(void) {\n geometry.worldPosition = instancePositions;\n geometry.uv = positions;\n geometry.pickingColor = instancePickingColors;\n uv = positions;\n\n vec2 iconSize = instanceIconFrames.zw;\n // convert size in meters to pixels, then scaled and clamp\n \n // project meters to pixels and clamp to limits \n float sizePixels = clamp(\n project_size_to_pixel(instanceSizes * icon.sizeScale, icon.sizeUnits),\n icon.sizeMinPixels, icon.sizeMaxPixels\n );\n\n // Choose correct constraint based on the 'sizeBasis' value (0.0 = width, 1.0 = height)\n float iconConstraint = icon.sizeBasis == 0.0 ? iconSize.x : iconSize.y;\n float instanceScale = iconConstraint == 0.0 ? 0.0 : sizePixels / iconConstraint;\n\n // scale and rotate vertex in \"pixel\" value and convert back to fraction in clipspace\n vec2 pixelOffset = positions / 2.0 * iconSize + instanceOffsets;\n pixelOffset = rotate_by_angle(pixelOffset, instanceAngles) * instanceScale;\n pixelOffset += instancePixelOffset;\n pixelOffset.y *= -1.0;\n\n if (icon.billboard) {\n gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0), geometry.position);\n DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n vec3 offset = vec3(pixelOffset, 0.0);\n DECKGL_FILTER_SIZE(offset, geometry);\n gl_Position.xy += project_pixel_size_to_clipspace(offset.xy);\n } else {\n vec3 offset_common = vec3(project_pixel_size(pixelOffset), 0.0);\n DECKGL_FILTER_SIZE(offset_common, geometry);\n gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset_common, geometry.position); \n DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n }\n\n vTextureCoords = mix(\n instanceIconFrames.xy,\n instanceIconFrames.xy + iconSize,\n (positions.xy + 1.0) / 2.0\n ) / icon.iconsTextureDim;\n\n vColor = instanceColors;\n DECKGL_FILTER_COLOR(vColor, geometry);\n\n vColorMode = instanceColorModes;\n}\n`;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport default `\\\n#version 300 es\n#define SHADER_NAME icon-layer-fragment-shader\n\nprecision highp float;\n\nuniform sampler2D iconsTexture;\n\nin float vColorMode;\nin vec4 vColor;\nin vec2 vTextureCoords;\nin vec2 uv;\n\nout vec4 fragColor;\n\nvoid main(void) {\n geometry.uv = uv;\n\n vec4 texColor = texture(iconsTexture, vTextureCoords);\n\n // if colorMode == 0, use pixel color from the texture\n // if colorMode == 1 or rendering picking buffer, use texture as transparency mask\n vec3 color = mix(texColor.rgb, vColor.rgb, vColorMode);\n // Take the global opacity and the alpha from vColor into account for the alpha component\n float a = texColor.a * layer.opacity * vColor.a;\n\n if (a < icon.alphaCutoff) {\n discard;\n }\n\n fragColor = vec4(color, a);\n DECKGL_FILTER_COLOR(fragColor, geometry);\n}\n`;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport const shaderWGSL = /* wgsl */ `\\\nstruct IconUniforms {\n sizeScale: f32,\n iconsTextureDim: vec2,\n sizeBasis: f32,\n sizeMinPixels: f32,\n sizeMaxPixels: f32,\n billboard: i32,\n sizeUnits: i32,\n alphaCutoff: f32\n};\n\n@group(0) @binding(auto) var icon: IconUniforms;\n@group(0) @binding(auto) var iconsTexture : texture_2d;\n@group(0) @binding(auto) var iconsTextureSampler : sampler;\n\nfn rotate_by_angle(vertex: vec2, angle_deg: f32) -> vec2 {\n let angle_radian = angle_deg * PI / 180.0;\n let c = cos(angle_radian);\n let s = sin(angle_radian);\n let rotation = mat2x2(vec2(c, s), vec2(-s, c));\n return rotation * vertex;\n}\n\nstruct Attributes {\n @location(0) positions: vec2,\n\n @location(1) instancePositions: vec3,\n @location(2) instancePositions64Low: vec3,\n @location(3) instanceSizes: f32,\n @location(4) instanceAngles: f32,\n @location(5) instanceColors: vec4,\n @location(6) instancePickingColors: vec3,\n @location(7) instanceIconFrames: vec4,\n @location(8) instanceColorModes: f32,\n @location(9) instanceOffsets: vec2,\n @location(10) instancePixelOffset: vec2,\n};\n\nstruct Varyings {\n @builtin(position) position: vec4,\n\n @location(0) vColorMode: f32,\n @location(1) vColor: vec4,\n @location(2) vTextureCoords: vec2,\n @location(3) uv: vec2,\n @location(4) pickingColor: vec3,\n};\n\n@vertex\nfn vertexMain(inp: Attributes) -> Varyings {\n // write geometry fields used by filters + FS\n geometry.worldPosition = inp.instancePositions;\n geometry.uv = inp.positions;\n geometry.pickingColor = inp.instancePickingColors;\n\n var outp: Varyings;\n outp.uv = inp.positions;\n\n let iconSize = inp.instanceIconFrames.zw;\n\n // convert size in meters to pixels, then clamp\n let sizePixels = clamp(\n project_unit_size_to_pixel(inp.instanceSizes * icon.sizeScale, icon.sizeUnits),\n icon.sizeMinPixels, icon.sizeMaxPixels\n );\n\n // scale icon height to match instanceSize\n let iconConstraint = select(iconSize.y, iconSize.x, icon.sizeBasis == 0.0);\n let instanceScale = select(sizePixels / iconConstraint, 0.0, iconConstraint == 0.0);\n\n // scale and rotate vertex in \"pixel\" units; then add per-instance pixel offset\n var pixelOffset = inp.positions / 2.0 * iconSize + inp.instanceOffsets;\n pixelOffset = rotate_by_angle(pixelOffset, inp.instanceAngles) * instanceScale;\n pixelOffset = pixelOffset + inp.instancePixelOffset;\n pixelOffset.y = pixelOffset.y * -1.0;\n\n if (icon.billboard != 0) {\n var pos = project_position_to_clipspace(inp.instancePositions, inp.instancePositions64Low, vec3(0.0)); // TODO, &geometry.position);\n // DECKGL_FILTER_GL_POSITION(pos, geometry);\n\n var offset = vec3(pixelOffset, 0.0);\n // DECKGL_FILTER_SIZE(offset, geometry);\n let clipOffset = project_pixel_size_to_clipspace(offset.xy);\n pos = vec4(pos.x + clipOffset.x, pos.y + clipOffset.y, pos.z, pos.w);\n outp.position = pos;\n } else {\n var offset_common = vec3(project_pixel_size_vec2(pixelOffset), 0.0);\n // DECKGL_FILTER_SIZE(offset_common, geometry);\n var pos = project_position_to_clipspace(inp.instancePositions, inp.instancePositions64Low, offset_common); // TODO, &geometry.position);\n // DECKGL_FILTER_GL_POSITION(pos, geometry);\n outp.position = pos;\n }\n\n let uvMix = (inp.positions.xy + vec2(1.0, 1.0)) * 0.5;\n outp.vTextureCoords = mix(inp.instanceIconFrames.xy, inp.instanceIconFrames.xy + iconSize, uvMix) / icon.iconsTextureDim;\n\n outp.vColor = inp.instanceColors;\n // DECKGL_FILTER_COLOR(outp.vColor, geometry);\n\n outp.vColorMode = inp.instanceColorModes;\n outp.pickingColor = inp.instancePickingColors;\n\n return outp;\n}\n\n@fragment\nfn fragmentMain(inp: Varyings) -> @location(0) vec4 {\n // expose to deck.gl filter hooks\n geometry.uv = inp.uv;\n\n let texColor = textureSample(iconsTexture, iconsTextureSampler, inp.vTextureCoords);\n\n // if colorMode == 0, use pixel color from the texture\n // if colorMode == 1 (or picking), use texture as transparency mask\n let rgb = mix(texColor.rgb, inp.vColor.rgb, inp.vColorMode);\n let a = texColor.a * layer.opacity * inp.vColor.a;\n\n if (a < icon.alphaCutoff) {\n discard;\n }\n\n if (picking.isActive > 0.5) {\n if (!picking_isColorValid(inp.pickingColor)) {\n discard;\n }\n return vec4(inp.pickingColor, 1.0);\n }\n\n var fragColor = deckgl_premultiplied_alpha(vec4(rgb, a));\n\n if (picking.isHighlightActive > 0.5) {\n let highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor);\n if (picking_isColorZero(abs(inp.pickingColor - highlightedObjectColor))) {\n let highLightAlpha = picking.highlightColor.a;\n let blendedAlpha = highLightAlpha + fragColor.a * (1.0 - highLightAlpha);\n if (blendedAlpha > 0.0) {\n let highLightRatio = highLightAlpha / blendedAlpha;\n fragColor = vec4(\n mix(fragColor.rgb, picking.highlightColor.rgb, highLightRatio),\n blendedAlpha\n );\n } else {\n fragColor = vec4(fragColor.rgb, 0.0);\n }\n }\n }\n\n return fragColor;\n}\n`;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/* global document */\nimport {Device, Texture, SamplerProps} from '@luma.gl/core';\nimport {AsyncTexture} from '@luma.gl/engine';\nimport {load} from '@loaders.gl/core';\nimport {createIterable} from '@deck.gl/core';\n\nimport type {AccessorFunction} from '@deck.gl/core';\n\nconst DEFAULT_CANVAS_WIDTH = 1024;\nconst DEFAULT_BUFFER = 4;\n\nconst noop = () => {};\n\nconst DEFAULT_SAMPLER_PARAMETERS: SamplerProps = {\n minFilter: 'linear',\n mipmapFilter: 'linear',\n // LINEAR is the default value but explicitly set it here\n magFilter: 'linear',\n // minimize texture boundary artifacts\n addressModeU: 'clamp-to-edge',\n addressModeV: 'clamp-to-edge'\n};\n\ntype IconDef = {\n /** Width of the icon */\n width: number;\n /** Height of the icon */\n height: number;\n /** Horizontal position of icon anchor. Default: half width. */\n anchorX?: number;\n /** Vertical position of icon anchor. Default: half height. */\n anchorY?: number;\n /**\n * Whether the icon is treated as a transparency mask.\n * If `true`, color defined by `getColor` is applied.\n * If `false`, pixel color from the icon image is applied.\n * @default false\n */\n mask?: boolean;\n};\n\nexport type UnpackedIcon = {\n /** Url to fetch the icon */\n url: string;\n /** Unique identifier of the icon. Icons of the same id are only fetched once. Fallback to `url` if not specified. */\n id?: string;\n} & IconDef;\n\ntype PrepackedIcon = {\n /** Left position of the icon on the atlas */\n x: number;\n /** Top position of the icon on the atlas */\n y: number;\n} & IconDef;\n\nconst MISSING_ICON: PrepackedIcon = {\n x: 0,\n y: 0,\n width: 0,\n height: 0\n};\n\nexport type IconMapping = Record;\n\nexport type LoadIconErrorContext = {\n error: Error;\n /** The URL that was trying to fetch */\n url: string;\n /** The original data object that requested this icon */\n source: any;\n /** The index of the original data object that requested this icon */\n sourceIndex: number;\n /** The load options used for the fetch */\n loadOptions: any;\n};\n\nfunction nextPowOfTwo(number: number): number {\n return Math.pow(2, Math.ceil(Math.log2(number)));\n}\n\n// update comment to create a new texture and copy original data.\nfunction resizeImage(\n ctx: CanvasRenderingContext2D,\n imageData: HTMLImageElement | ImageBitmap,\n maxWidth: number,\n maxHeight: number\n): {\n image: HTMLImageElement | HTMLCanvasElement | ImageBitmap;\n width: number;\n height: number;\n} {\n const resizeRatio = Math.min(maxWidth / imageData.width, maxHeight / imageData.height);\n const width = Math.floor(imageData.width * resizeRatio);\n const height = Math.floor(imageData.height * resizeRatio);\n\n if (resizeRatio === 1) {\n // No resizing required\n return {image: imageData, width, height};\n }\n\n ctx.canvas.height = height;\n ctx.canvas.width = width;\n\n ctx.clearRect(0, 0, width, height);\n\n // image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight\n ctx.drawImage(imageData, 0, 0, imageData.width, imageData.height, 0, 0, width, height);\n return {image: ctx.canvas, width, height};\n}\n\nfunction getIconId(icon: UnpackedIcon): string {\n return icon && (icon.id || icon.url);\n}\n\nfunction regenerateMipmaps(texture: Texture) {\n const {device} = texture;\n if (device.type === 'webgl') {\n texture.generateMipmapsWebGL();\n } else if (device.type === 'webgpu') {\n device.generateMipmapsWebGPU(texture);\n }\n}\n\n// resize texture without losing original data\nfunction resizeTexture(\n texture: Texture,\n width: number,\n height: number,\n sampler: SamplerProps\n): Texture {\n const {width: oldWidth, height: oldHeight, device} = texture;\n\n const newTexture = device.createTexture({\n format: 'rgba8unorm',\n width,\n height,\n sampler,\n mipLevels: device.getMipLevelCount(width, height)\n });\n\n const commandEncoder = device.createCommandEncoder();\n commandEncoder.copyTextureToTexture({\n sourceTexture: texture,\n destinationTexture: newTexture,\n width: oldWidth,\n height: oldHeight\n });\n const commandBuffer = commandEncoder.finish();\n device.submit(commandBuffer);\n regenerateMipmaps(newTexture);\n\n texture.destroy();\n return newTexture;\n}\n\n// traverse icons in a row of icon atlas\n// extend each icon with left-top coordinates\nfunction buildRowMapping(\n mapping: IconMapping,\n columns: {\n icon: UnpackedIcon;\n xOffset: number;\n }[],\n yOffset: number\n): void {\n for (let i = 0; i < columns.length; i++) {\n const {icon, xOffset} = columns[i];\n const id = getIconId(icon);\n mapping[id] = {\n ...icon,\n x: xOffset,\n y: yOffset\n };\n }\n}\n\n/**\n * Generate coordinate mapping to retrieve icon left-top position from an icon atlas\n */\nexport function buildMapping({\n icons,\n buffer,\n mapping = {},\n xOffset = 0,\n yOffset = 0,\n rowHeight = 0,\n canvasWidth\n}: {\n /** list of icon definitions */\n icons: UnpackedIcon[];\n /** add bleeding buffer to the right and bottom side of the image */\n buffer: number;\n /** right position of last icon in old mapping */\n xOffset: number;\n /** top position in last icon in old mapping */\n yOffset: number;\n /** height of the last icon's row */\n rowHeight: number;\n /** max width of canvas */\n canvasWidth: number;\n mapping: IconMapping;\n}): {\n mapping: IconMapping;\n rowHeight: number;\n xOffset: number;\n yOffset: number;\n canvasWidth: number;\n canvasHeight: number;\n} {\n let columns: {\n icon: UnpackedIcon;\n xOffset: number;\n }[] = [];\n // Strategy to layout all the icons into a texture:\n // traverse the icons sequentially, layout the icons from left to right, top to bottom\n // when the sum of the icons width is equal or larger than canvasWidth,\n // move to next row starting from total height so far plus max height of the icons in previous row\n // row width is equal to canvasWidth\n // row height is decided by the max height of the icons in that row\n // mapping coordinates of each icon is its left-top position in the texture\n for (let i = 0; i < icons.length; i++) {\n const icon = icons[i];\n const id = getIconId(icon);\n\n if (!mapping[id]) {\n const {height, width} = icon;\n\n // fill one row\n if (xOffset + width + buffer > canvasWidth) {\n buildRowMapping(mapping, columns, yOffset);\n\n xOffset = 0;\n yOffset = rowHeight + yOffset + buffer;\n rowHeight = 0;\n columns = [];\n }\n\n columns.push({\n icon,\n xOffset\n });\n\n xOffset = xOffset + width + buffer;\n rowHeight = Math.max(rowHeight, height);\n }\n }\n\n if (columns.length > 0) {\n buildRowMapping(mapping, columns, yOffset);\n }\n\n return {\n mapping,\n rowHeight,\n xOffset,\n yOffset,\n canvasWidth,\n canvasHeight: nextPowOfTwo(rowHeight + yOffset + buffer)\n };\n}\n\n// extract icons from data\n// return icons should be unique, and not cached or cached but url changed\nexport function getDiffIcons(\n data: any,\n getIcon: AccessorFunction | null,\n cachedIcons: Record\n): Record<\n string,\n UnpackedIcon & {\n source: any;\n sourceIndex: number;\n }\n> | null {\n if (!data || !getIcon) {\n return null;\n }\n\n cachedIcons = cachedIcons || {};\n const icons = {};\n const {iterable, objectInfo} = createIterable(data);\n for (const object of iterable) {\n objectInfo.index++;\n const icon = getIcon(object, objectInfo);\n const id = getIconId(icon);\n\n if (!icon) {\n throw new Error('Icon is missing.');\n }\n\n if (!icon.url) {\n throw new Error('Icon url is missing.');\n }\n\n if (!icons[id] && (!cachedIcons[id] || icon.url !== cachedIcons[id].url)) {\n icons[id] = {...icon, source: object, sourceIndex: objectInfo.index};\n }\n }\n return icons;\n}\n\nexport default class IconManager {\n device: Device;\n\n private onUpdate: (didFrameChange: boolean) => void;\n private onError: (context: LoadIconErrorContext) => void;\n private _loadOptions: any = null;\n private _texture: Texture | null = null;\n private _externalTexture: Texture | null = null;\n private _mapping: IconMapping = {};\n private _samplerParameters: SamplerProps | null = null;\n\n /** count of pending requests to fetch icons */\n private _pendingCount: number = 0;\n\n private _autoPacking: boolean = false;\n\n // / internal state used for autoPacking\n\n private _xOffset: number = 0;\n private _yOffset: number = 0;\n private _rowHeight: number = 0;\n private _buffer: number = DEFAULT_BUFFER;\n private _canvasWidth: number = DEFAULT_CANVAS_WIDTH;\n private _canvasHeight: number = 0;\n private _canvas: HTMLCanvasElement | null = null;\n\n constructor(\n device: Device,\n {\n onUpdate = noop,\n onError = noop\n }: {\n /** Callback when the texture updates */\n onUpdate: (didFrameChange: boolean) => void;\n /** Callback when an error is encountered */\n onError: (context: LoadIconErrorContext) => void;\n }\n ) {\n this.device = device;\n this.onUpdate = onUpdate;\n this.onError = onError;\n }\n\n finalize(): void {\n this._texture?.delete();\n }\n\n getTexture(): Texture | null {\n return this._texture || this._externalTexture;\n }\n\n getIconMapping(icon: string | UnpackedIcon): PrepackedIcon {\n const id = this._autoPacking ? getIconId(icon as UnpackedIcon) : (icon as string);\n return this._mapping[id] || MISSING_ICON;\n }\n\n setProps({\n loadOptions,\n autoPacking,\n iconAtlas,\n iconMapping,\n textureParameters\n }: {\n loadOptions?: any;\n autoPacking?: boolean;\n iconAtlas?: Texture | null;\n iconMapping?: IconMapping | null;\n textureParameters?: SamplerProps | null;\n }) {\n if (loadOptions) {\n this._loadOptions = loadOptions;\n }\n\n if (autoPacking !== undefined) {\n this._autoPacking = autoPacking;\n }\n\n if (iconMapping) {\n this._mapping = iconMapping;\n }\n\n if (iconAtlas) {\n this._texture?.delete();\n this._texture = null;\n this._externalTexture = iconAtlas;\n }\n\n if (textureParameters) {\n this._samplerParameters = textureParameters;\n }\n }\n\n get isLoaded(): boolean {\n return this._pendingCount === 0;\n }\n\n packIcons(data: any, getIcon: AccessorFunction): void {\n if (!this._autoPacking || typeof document === 'undefined') {\n return;\n }\n\n const icons = Object.values(getDiffIcons(data, getIcon, this._mapping) || {});\n\n if (icons.length > 0) {\n // generate icon mapping\n const {mapping, xOffset, yOffset, rowHeight, canvasHeight} = buildMapping({\n icons,\n buffer: this._buffer,\n canvasWidth: this._canvasWidth,\n mapping: this._mapping,\n rowHeight: this._rowHeight,\n xOffset: this._xOffset,\n yOffset: this._yOffset\n });\n\n this._rowHeight = rowHeight;\n this._mapping = mapping;\n this._xOffset = xOffset;\n this._yOffset = yOffset;\n this._canvasHeight = canvasHeight;\n\n // create new texture\n if (!this._texture) {\n this._texture = this.device.createTexture({\n format: 'rgba8unorm',\n data: null,\n width: this._canvasWidth,\n height: this._canvasHeight,\n sampler: this._samplerParameters || DEFAULT_SAMPLER_PARAMETERS,\n mipLevels: this.device.getMipLevelCount(this._canvasWidth, this._canvasHeight)\n });\n }\n\n if (this._texture.height !== this._canvasHeight) {\n this._texture = resizeTexture(\n this._texture,\n this._canvasWidth,\n this._canvasHeight,\n this._samplerParameters || DEFAULT_SAMPLER_PARAMETERS\n );\n }\n\n this.onUpdate(true);\n\n // load images\n this._canvas = this._canvas || document.createElement('canvas');\n this._loadIcons(icons);\n }\n }\n\n private _loadIcons(\n icons: (UnpackedIcon & {\n source: any;\n sourceIndex: number;\n })[]\n ): void {\n // This method is only called in the auto packing case, where _canvas is defined\n const ctx = this._canvas!.getContext('2d', {\n willReadFrequently: true\n }) as CanvasRenderingContext2D;\n\n for (const icon of icons) {\n this._pendingCount++;\n load(icon.url, this._loadOptions)\n .then(imageData => {\n const id = getIconId(icon);\n\n const iconDef = this._mapping[id];\n const {x: initialX, y: initialY, width: maxWidth, height: maxHeight} = iconDef;\n\n const {image, width, height} = resizeImage(\n ctx,\n imageData as ImageBitmap,\n maxWidth,\n maxHeight\n );\n\n const x = initialX + (maxWidth - width) / 2;\n const y = initialY + (maxHeight - height) / 2;\n\n this._texture?.copyExternalImage({\n image,\n x,\n y,\n width,\n height\n });\n iconDef.x = x;\n iconDef.y = y;\n iconDef.width = width;\n iconDef.height = height;\n\n // Call to regenerate mipmaps after modifying texture(s)\n if (this._texture) {\n regenerateMipmaps(this._texture);\n }\n\n this.onUpdate(width !== maxWidth || height !== maxHeight);\n })\n .catch(error => {\n this.onError({\n url: icon.url,\n source: icon.source,\n sourceIndex: icon.sourceIndex,\n loadOptions: this._loadOptions,\n error\n });\n })\n .finally(() => {\n this._pendingCount--;\n });\n }\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Layer, color, project32, picking, log, UNIT} from '@deck.gl/core';\nimport {SamplerProps, Texture} from '@luma.gl/core';\nimport {Model, Geometry} from '@luma.gl/engine';\n\nimport {iconUniforms, IconProps} from './icon-layer-uniforms';\nimport vs from './icon-layer-vertex.glsl';\nimport fs from './icon-layer-fragment.glsl';\nimport {shaderWGSL as source} from './icon-layer.wgsl';\nimport IconManager from './icon-manager';\n\nimport type {\n LayerProps,\n LayerDataSource,\n Accessor,\n AccessorFunction,\n Position,\n Color,\n Unit,\n UpdateParameters,\n LayerContext,\n DefaultProps\n} from '@deck.gl/core';\n\nimport type {UnpackedIcon, IconMapping, LoadIconErrorContext} from './icon-manager';\n\ntype _IconLayerProps = {\n data: LayerDataSource;\n /** A prepacked image that contains all icons. */\n iconAtlas?: string | Texture;\n /** Icon names mapped to icon definitions, or a URL to load such mapping from a JSON file. */\n iconMapping?: string | IconMapping;\n\n /** Icon size multiplier.\n * @default 1\n */\n sizeScale?: number;\n /**\n * The units of the icon size, one of `meters`, `common`, and `pixels`.\n *\n * @default 'pixels'\n */\n sizeUnits?: Unit;\n /**\n * The dimension to scale the image\n */\n sizeBasis?: 'height' | 'width';\n /**\n * The minimum size in pixels. When using non-pixel `sizeUnits`, this prop can be used to prevent the icon from getting too small when zoomed out.\n */\n sizeMinPixels?: number;\n /**\n * The maximum size in pixels. When using non-pixel `sizeUnits`, this prop can be used to prevent the icon from getting too big when zoomed in.\n */\n sizeMaxPixels?: number;\n /** If `true`, the icon always faces camera. Otherwise the icon faces up (z)\n * @default true\n */\n billboard?: boolean;\n /**\n * Discard pixels whose opacity is below this threshold.\n * A discarded pixel would create a \"hole\" in the icon that is not considered part of the object.\n * @default 0.05\n */\n alphaCutoff?: number;\n\n /** Anchor position accessor. */\n getPosition?: Accessor;\n /** Icon definition accessor.\n * Should return the icon id if using pre-packed icons (`iconAtlas` + `iconMapping`).\n * Return an object that defines the icon if using auto-packing.\n */\n getIcon?: AccessorFunction | AccessorFunction;\n /** Icon color accessor.\n * @default [0, 0, 0, 255]\n */\n getColor?: Accessor;\n /** Icon size accessor.\n * @default 1\n */\n getSize?: Accessor;\n /** Icon rotation accessor, in degrees.\n * @default 0\n */\n getAngle?: Accessor;\n /**\n * Icon offsest accessor, in pixels.\n * @default [0, 0]\n */\n getPixelOffset?: Accessor>;\n /**\n * Callback called if the attempt to fetch an icon returned by `getIcon` fails.\n */\n onIconError?: ((context: LoadIconErrorContext) => void) | null;\n\n /** Customize the [texture parameters](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/texParameter). */\n textureParameters?: SamplerProps | null;\n};\n\nexport type IconLayerProps = _IconLayerProps & LayerProps;\n\nconst DEFAULT_COLOR = [0, 0, 0, 255] as const;\n\nconst defaultProps: DefaultProps = {\n iconAtlas: {type: 'image', value: null, async: true},\n iconMapping: {type: 'object', value: {}, async: true},\n sizeScale: {type: 'number', value: 1, min: 0},\n billboard: true,\n sizeUnits: 'pixels',\n sizeBasis: 'height',\n sizeMinPixels: {type: 'number', min: 0, value: 0}, // min point radius in pixels\n sizeMaxPixels: {type: 'number', min: 0, value: Number.MAX_SAFE_INTEGER}, // max point radius in pixels\n alphaCutoff: {type: 'number', value: 0.05, min: 0, max: 1},\n\n getPosition: {type: 'accessor', value: (x: any) => x.position},\n getIcon: {type: 'accessor', value: (x: any) => x.icon},\n getColor: {type: 'accessor', value: DEFAULT_COLOR},\n getSize: {type: 'accessor', value: 1},\n getAngle: {type: 'accessor', value: 0},\n getPixelOffset: {type: 'accessor', value: [0, 0]},\n\n onIconError: {type: 'function', value: null, optional: true},\n\n textureParameters: {type: 'object', ignore: true, value: null}\n};\n\n/** Render raster icons at given coordinates. */\nexport default class IconLayer extends Layer<\n ExtraPropsT & Required<_IconLayerProps>\n> {\n static defaultProps = defaultProps;\n static layerName = 'IconLayer';\n\n state!: {\n model?: Model;\n iconManager: IconManager;\n };\n\n getShaders() {\n return super.getShaders({vs, fs, source, modules: [project32, color, picking, iconUniforms]});\n }\n\n initializeState() {\n this.state = {\n iconManager: new IconManager(this.context.device, {\n onUpdate: this._onUpdate.bind(this),\n onError: this._onError.bind(this)\n })\n };\n\n const attributeManager = this.getAttributeManager();\n /* eslint-disable max-len */\n attributeManager!.addInstanced({\n instancePositions: {\n size: 3,\n type: 'float64',\n fp64: this.use64bitPositions(),\n transition: true,\n accessor: 'getPosition'\n },\n instanceSizes: {\n size: 1,\n transition: true,\n accessor: 'getSize',\n defaultValue: 1\n },\n instanceIconDefs: {\n size: 7,\n accessor: 'getIcon',\n // eslint-disable-next-line @typescript-eslint/unbound-method\n transform: this.getInstanceIconDef,\n shaderAttributes: {\n instanceOffsets: {\n size: 2,\n elementOffset: 0\n },\n instanceIconFrames: {\n size: 4,\n elementOffset: 2\n },\n instanceColorModes: {\n size: 1,\n elementOffset: 6\n }\n }\n },\n instanceColors: {\n size: this.props.colorFormat.length,\n type: 'unorm8',\n transition: true,\n accessor: 'getColor',\n defaultValue: DEFAULT_COLOR\n },\n instanceAngles: {\n size: 1,\n transition: true,\n accessor: 'getAngle'\n },\n instancePixelOffset: {\n size: 2,\n transition: true,\n accessor: 'getPixelOffset'\n }\n });\n /* eslint-enable max-len */\n }\n\n /* eslint-disable max-statements, complexity */\n updateState(params: UpdateParameters) {\n super.updateState(params);\n const {props, oldProps, changeFlags} = params;\n\n const attributeManager = this.getAttributeManager();\n const {iconAtlas, iconMapping, data, getIcon, textureParameters} = props;\n const {iconManager} = this.state;\n\n if (typeof iconAtlas === 'string') {\n return;\n }\n\n // internalState is always defined during updateState\n const prePacked = iconAtlas || this.internalState!.isAsyncPropLoading('iconAtlas');\n iconManager.setProps({\n loadOptions: props.loadOptions,\n autoPacking: !prePacked,\n iconAtlas,\n iconMapping: prePacked ? (iconMapping as IconMapping) : null,\n textureParameters\n });\n\n // prepacked iconAtlas from user\n if (prePacked) {\n if (oldProps.iconMapping !== props.iconMapping) {\n attributeManager!.invalidate('getIcon');\n }\n } else if (\n changeFlags.dataChanged ||\n (changeFlags.updateTriggersChanged &&\n (changeFlags.updateTriggersChanged.all || changeFlags.updateTriggersChanged.getIcon))\n ) {\n // Auto packing - getIcon is expected to return an object\n iconManager.packIcons(data, getIcon as AccessorFunction);\n }\n\n if (changeFlags.extensionsChanged) {\n this.state.model?.destroy();\n this.state.model = this._getModel();\n attributeManager!.invalidateAll();\n }\n }\n /* eslint-enable max-statements, complexity */\n\n get isLoaded(): boolean {\n return super.isLoaded && this.state.iconManager.isLoaded;\n }\n\n finalizeState(context: LayerContext): void {\n super.finalizeState(context);\n // Release resources held by the icon manager\n this.state.iconManager.finalize();\n }\n\n draw({uniforms}): void {\n const {sizeScale, sizeBasis, sizeMinPixels, sizeMaxPixels, sizeUnits, billboard, alphaCutoff} =\n this.props;\n const {iconManager} = this.state;\n const iconsTexture = iconManager.getTexture();\n if (iconsTexture) {\n const model = this.state.model!;\n const iconProps: IconProps = {\n iconsTexture,\n iconsTextureDim: [iconsTexture.width, iconsTexture.height],\n sizeUnits: UNIT[sizeUnits],\n sizeScale,\n sizeBasis: sizeBasis === 'height' ? 1.0 : 0.0,\n sizeMinPixels,\n sizeMaxPixels,\n billboard,\n alphaCutoff\n };\n\n model.shaderInputs.setProps({icon: iconProps});\n model.draw(this.context.renderPass);\n }\n }\n\n protected _getModel(): Model {\n // The icon-layer vertex shader uses 2d positions\n // specifed via: in vec2 positions;\n const positions = [-1, -1, 1, -1, -1, 1, 1, 1];\n\n return new Model(this.context.device, {\n ...this.getShaders(),\n id: this.props.id,\n bufferLayout: this.getAttributeManager()!.getBufferLayouts(),\n geometry: new Geometry({\n topology: 'triangle-strip',\n attributes: {\n // The size must be explicitly passed here otherwise luma.gl\n // will default to assuming that positions are 3D (x,y,z)\n positions: {\n size: 2,\n value: new Float32Array(positions)\n }\n }\n }),\n isInstanced: true\n });\n }\n\n private _onUpdate(didFrameChange: boolean): void {\n if (didFrameChange) {\n this.getAttributeManager()?.invalidate('getIcon');\n this.setNeedsUpdate();\n } else {\n this.setNeedsRedraw();\n }\n }\n\n private _onError(evt: LoadIconErrorContext): void {\n const onIconError = this.getCurrentLayer()?.props.onIconError;\n if (onIconError) {\n onIconError(evt);\n } else {\n log.error(evt.error.message)();\n }\n }\n\n protected getInstanceIconDef(icon: string): number[] {\n const {\n x,\n y,\n width,\n height,\n mask,\n anchorX = width / 2,\n anchorY = height / 2\n } = this.state.iconManager.getIconMapping(icon);\n\n return [width / 2 - anchorX, height / 2 - anchorY, x, y, width, height, mask ? 1 : 0];\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ShaderModule} from '@luma.gl/shadertools';\n\nconst glslUniformBlock = `\\\nlayout(std140) uniform scatterplotUniforms {\n float radiusScale;\n float radiusMinPixels;\n float radiusMaxPixels;\n float lineWidthScale;\n float lineWidthMinPixels;\n float lineWidthMaxPixels;\n float stroked;\n float filled;\n bool antialiasing;\n bool billboard;\n highp int radiusUnits;\n highp int lineWidthUnits;\n} scatterplot;\n`;\n\nexport type ScatterplotProps = {\n radiusScale: number;\n radiusMinPixels: number;\n radiusMaxPixels: number;\n lineWidthScale: number;\n lineWidthMinPixels: number;\n lineWidthMaxPixels: number;\n stroked: boolean;\n filled: boolean;\n antialiasing: boolean;\n billboard: boolean;\n radiusUnits: number;\n lineWidthUnits: number;\n};\n\nexport const scatterplotUniforms = {\n name: 'scatterplot',\n vs: glslUniformBlock,\n fs: glslUniformBlock,\n source: '',\n uniformTypes: {\n radiusScale: 'f32',\n radiusMinPixels: 'f32',\n radiusMaxPixels: 'f32',\n lineWidthScale: 'f32',\n lineWidthMinPixels: 'f32',\n lineWidthMaxPixels: 'f32',\n stroked: 'f32',\n filled: 'f32',\n antialiasing: 'f32',\n billboard: 'f32',\n radiusUnits: 'i32',\n lineWidthUnits: 'i32'\n }\n} as const satisfies ShaderModule;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport default /* glsl */ `\\\n#version 300 es\n#define SHADER_NAME scatterplot-layer-vertex-shader\n\nin vec3 positions;\n\nin vec3 instancePositions;\nin vec3 instancePositions64Low;\nin float instanceRadius;\nin float instanceLineWidths;\nin vec4 instanceFillColors;\nin vec4 instanceLineColors;\nin vec3 instancePickingColors;\n\nout vec4 vFillColor;\nout vec4 vLineColor;\nout vec2 unitPosition;\nout float innerUnitRadius;\nout float outerRadiusPixels;\n\n\nvoid main(void) {\n geometry.worldPosition = instancePositions;\n\n // Multiply out radius and clamp to limits\n outerRadiusPixels = clamp(\n project_size_to_pixel(scatterplot.radiusScale * instanceRadius, scatterplot.radiusUnits),\n scatterplot.radiusMinPixels, scatterplot.radiusMaxPixels\n );\n \n // Multiply out line width and clamp to limits\n float lineWidthPixels = clamp(\n project_size_to_pixel(scatterplot.lineWidthScale * instanceLineWidths, scatterplot.lineWidthUnits),\n scatterplot.lineWidthMinPixels, scatterplot.lineWidthMaxPixels\n );\n\n // outer radius needs to offset by half stroke width\n outerRadiusPixels += scatterplot.stroked * lineWidthPixels / 2.0;\n // Expand geometry to accomodate edge smoothing\n float edgePadding = scatterplot.antialiasing ? (outerRadiusPixels + SMOOTH_EDGE_RADIUS) / outerRadiusPixels : 1.0;\n\n // position on the containing square in [-1, 1] space\n unitPosition = edgePadding * positions.xy;\n geometry.uv = unitPosition;\n geometry.pickingColor = instancePickingColors;\n\n innerUnitRadius = 1.0 - scatterplot.stroked * lineWidthPixels / outerRadiusPixels;\n \n if (scatterplot.billboard) {\n gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0), geometry.position);\n DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n vec3 offset = edgePadding * positions * outerRadiusPixels;\n DECKGL_FILTER_SIZE(offset, geometry);\n gl_Position.xy += project_pixel_size_to_clipspace(offset.xy);\n } else {\n vec3 offset = edgePadding * positions * project_pixel_size(outerRadiusPixels);\n DECKGL_FILTER_SIZE(offset, geometry);\n gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset, geometry.position);\n DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n }\n\n // Apply opacity to instance color, or return instance picking color\n vFillColor = vec4(instanceFillColors.rgb, instanceFillColors.a * layer.opacity);\n DECKGL_FILTER_COLOR(vFillColor, geometry);\n vLineColor = vec4(instanceLineColors.rgb, instanceLineColors.a * layer.opacity);\n DECKGL_FILTER_COLOR(vLineColor, geometry);\n}\n`;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport default /* glsl */ `\\\n#version 300 es\n#define SHADER_NAME scatterplot-layer-fragment-shader\n\nprecision highp float;\n\nin vec4 vFillColor;\nin vec4 vLineColor;\nin vec2 unitPosition;\nin float innerUnitRadius;\nin float outerRadiusPixels;\n\nout vec4 fragColor;\n\nvoid main(void) {\n geometry.uv = unitPosition;\n\n float distToCenter = length(unitPosition) * outerRadiusPixels;\n float inCircle = scatterplot.antialiasing ?\n smoothedge(distToCenter, outerRadiusPixels) :\n step(distToCenter, outerRadiusPixels);\n\n if (inCircle == 0.0) {\n discard;\n }\n\n if (scatterplot.stroked > 0.5) {\n float isLine = scatterplot.antialiasing ?\n smoothedge(innerUnitRadius * outerRadiusPixels, distToCenter) :\n step(innerUnitRadius * outerRadiusPixels, distToCenter);\n\n if (scatterplot.filled > 0.5) {\n fragColor = mix(vFillColor, vLineColor, isLine);\n } else {\n if (isLine == 0.0) {\n discard;\n }\n fragColor = vec4(vLineColor.rgb, vLineColor.a * isLine);\n }\n } else if (scatterplot.filled < 0.5) {\n discard;\n } else {\n fragColor = vFillColor;\n }\n\n fragColor.a *= inCircle;\n DECKGL_FILTER_COLOR(fragColor, geometry);\n}\n`;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport default /* wgsl */ `\\\n// Main shaders\n\nstruct ScatterplotUniforms {\n radiusScale: f32,\n radiusMinPixels: f32,\n radiusMaxPixels: f32,\n lineWidthScale: f32,\n lineWidthMinPixels: f32,\n lineWidthMaxPixels: f32,\n stroked: f32,\n filled: i32,\n antialiasing: i32,\n billboard: i32,\n radiusUnits: i32,\n lineWidthUnits: i32,\n};\n\nstruct ConstantAttributeUniforms {\n instancePositions: vec3,\n instancePositions64Low: vec3,\n instanceRadius: f32,\n instanceLineWidths: f32,\n instanceFillColors: vec4,\n instanceLineColors: vec4,\n instancePickingColors: vec3,\n\n instancePositionsConstant: i32,\n instancePositions64LowConstant: i32,\n instanceRadiusConstant: i32,\n instanceLineWidthsConstant: i32,\n instanceFillColorsConstant: i32,\n instanceLineColorsConstant: i32,\n instancePickingColorsConstant: i32\n};\n\n@group(0) @binding(0) var scatterplot: ScatterplotUniforms;\n\nstruct ConstantAttributes {\n instancePositions: vec3,\n instancePositions64Low: vec3,\n instanceRadius: f32,\n instanceLineWidths: f32,\n instanceFillColors: vec4,\n instanceLineColors: vec4,\n instancePickingColors: vec3\n};\n\nconst constants = ConstantAttributes(\n vec3(0.0),\n vec3(0.0),\n 0.0,\n 0.0,\n vec4(0.0, 0.0, 0.0, 1.0),\n vec4(0.0, 0.0, 0.0, 1.0),\n vec3(0.0)\n);\n\nstruct Attributes {\n @builtin(instance_index) instanceIndex : u32,\n @builtin(vertex_index) vertexIndex : u32,\n @location(0) positions: vec3,\n @location(1) instancePositions: vec3,\n @location(2) instancePositions64Low: vec3,\n @location(3) instanceRadius: f32,\n @location(4) instanceLineWidths: f32,\n @location(5) instanceFillColors: vec4,\n @location(6) instanceLineColors: vec4,\n @location(7) instancePickingColors: vec3,\n};\n\nstruct Varyings {\n @builtin(position) position: vec4,\n @location(0) vFillColor: vec4,\n @location(1) vLineColor: vec4,\n @location(2) unitPosition: vec2,\n @location(3) innerUnitRadius: f32,\n @location(4) outerRadiusPixels: f32,\n @location(5) pickingColor: vec3,\n};\n\n@vertex\nfn vertexMain(attributes: Attributes) -> Varyings {\n var varyings: Varyings;\n\n // Draw an inline geometry constant array clip space triangle to verify that rendering works.\n // var positions = array, 3>(vec2(0.0, 0.5), vec2(-0.5, -0.5), vec2(0.5, -0.5));\n // if (attributes.instanceIndex == 0) {\n // varyings.position = vec4(positions[attributes.vertexIndex], 0.0, 1.0);\n // return varyings;\n // }\n\n geometry.worldPosition = attributes.instancePositions;\n\n // Multiply out radius and clamp to limits\n varyings.outerRadiusPixels = clamp(\n project_unit_size_to_pixel(scatterplot.radiusScale * attributes.instanceRadius, scatterplot.radiusUnits),\n scatterplot.radiusMinPixels, scatterplot.radiusMaxPixels\n );\n\n // Multiply out line width and clamp to limits\n let lineWidthPixels = clamp(\n project_unit_size_to_pixel(scatterplot.lineWidthScale * attributes.instanceLineWidths, scatterplot.lineWidthUnits),\n scatterplot.lineWidthMinPixels, scatterplot.lineWidthMaxPixels\n );\n\n // outer radius needs to offset by half stroke width\n varyings.outerRadiusPixels += scatterplot.stroked * lineWidthPixels / 2.0;\n // Expand geometry to accommodate edge smoothing\n let edgePadding = select(\n (varyings.outerRadiusPixels + SMOOTH_EDGE_RADIUS) / varyings.outerRadiusPixels,\n 1.0,\n scatterplot.antialiasing != 0\n );\n\n // position on the containing square in [-1, 1] space\n varyings.unitPosition = edgePadding * attributes.positions.xy;\n geometry.uv = varyings.unitPosition;\n geometry.pickingColor = attributes.instancePickingColors;\n\n varyings.innerUnitRadius = 1.0 - scatterplot.stroked * lineWidthPixels / varyings.outerRadiusPixels;\n\n if (scatterplot.billboard != 0) {\n varyings.position = project_position_to_clipspace(attributes.instancePositions, attributes.instancePositions64Low, vec3(0.0)); // TODO , geometry.position);\n // DECKGL_FILTER_GL_POSITION(varyings.position, geometry);\n let offset = attributes.positions; // * edgePadding * varyings.outerRadiusPixels;\n // DECKGL_FILTER_SIZE(offset, geometry);\n let clipPixels = project_pixel_size_to_clipspace(offset.xy);\n varyings.position.x = clipPixels.x;\n varyings.position.y = clipPixels.y;\n } else {\n let offset = edgePadding * attributes.positions * project_pixel_size_float(varyings.outerRadiusPixels);\n // DECKGL_FILTER_SIZE(offset, geometry);\n varyings.position = project_position_to_clipspace(attributes.instancePositions, attributes.instancePositions64Low, offset); // TODO , geometry.position);\n // DECKGL_FILTER_GL_POSITION(varyings.position, geometry);\n }\n\n // Apply opacity to instance color, or return instance picking color\n varyings.vFillColor = vec4(attributes.instanceFillColors.rgb, attributes.instanceFillColors.a * layer.opacity);\n // DECKGL_FILTER_COLOR(varyings.vFillColor, geometry);\n varyings.vLineColor = vec4(attributes.instanceLineColors.rgb, attributes.instanceLineColors.a * layer.opacity);\n // DECKGL_FILTER_COLOR(varyings.vLineColor, geometry);\n varyings.pickingColor = attributes.instancePickingColors;\n\n return varyings;\n}\n\n@fragment\nfn fragmentMain(varyings: Varyings) -> @location(0) vec4 {\n // var geometry: Geometry;\n // geometry.uv = unitPosition;\n\n let distToCenter = length(varyings.unitPosition) * varyings.outerRadiusPixels;\n let inCircle = select(\n smoothedge(distToCenter, varyings.outerRadiusPixels),\n step(distToCenter, varyings.outerRadiusPixels),\n scatterplot.antialiasing != 0\n );\n\n if (inCircle == 0.0) {\n discard;\n }\n\n var fragColor: vec4;\n\n if (scatterplot.stroked != 0) {\n let isLine = select(\n smoothedge(varyings.innerUnitRadius * varyings.outerRadiusPixels, distToCenter),\n step(varyings.innerUnitRadius * varyings.outerRadiusPixels, distToCenter),\n scatterplot.antialiasing != 0\n );\n\n if (scatterplot.filled != 0) {\n fragColor = mix(varyings.vFillColor, varyings.vLineColor, isLine);\n } else {\n if (isLine == 0.0) {\n discard;\n }\n fragColor = vec4(varyings.vLineColor.rgb, varyings.vLineColor.a * isLine);\n }\n } else if (scatterplot.filled == 0) {\n discard;\n } else {\n fragColor = varyings.vFillColor;\n }\n\n fragColor.a *= inCircle;\n\n if (picking.isActive > 0.5) {\n if (!picking_isColorValid(varyings.pickingColor)) {\n discard;\n }\n return vec4(varyings.pickingColor, 1.0);\n }\n\n if (picking.isHighlightActive > 0.5) {\n let highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor);\n if (picking_isColorZero(abs(varyings.pickingColor - highlightedObjectColor))) {\n let highLightAlpha = picking.highlightColor.a;\n let blendedAlpha = highLightAlpha + fragColor.a * (1.0 - highLightAlpha);\n if (blendedAlpha > 0.0) {\n let highLightRatio = highLightAlpha / blendedAlpha;\n fragColor = vec4(\n mix(fragColor.rgb, picking.highlightColor.rgb, highLightRatio),\n blendedAlpha\n );\n } else {\n fragColor = vec4(fragColor.rgb, 0.0);\n }\n }\n }\n\n // Apply premultiplied alpha as required by transparent canvas\n fragColor = deckgl_premultiplied_alpha(fragColor);\n\n return fragColor;\n // return vec4(0, 0, 1, 1);\n}\n`;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Layer, color, project32, picking, UNIT} from '@deck.gl/core';\nimport {Model, Geometry} from '@luma.gl/engine';\n\nimport {scatterplotUniforms, ScatterplotProps} from './scatterplot-layer-uniforms';\nimport vs from './scatterplot-layer-vertex.glsl';\nimport fs from './scatterplot-layer-fragment.glsl';\nimport source from './scatterplot-layer.wgsl';\n\nimport type {\n LayerProps,\n LayerDataSource,\n UpdateParameters,\n Accessor,\n Unit,\n Position,\n Color,\n DefaultProps\n} from '@deck.gl/core';\n\nconst DEFAULT_COLOR = [0, 0, 0, 255] as const;\n\n/** All props supported by the ScatterplotLayer */\nexport type ScatterplotLayerProps = _ScatterplotLayerProps & LayerProps;\n\n/** Props added by the ScatterplotLayer */\ntype _ScatterplotLayerProps = {\n data: LayerDataSource;\n /**\n * The units of the radius, one of `'meters'`, `'common'`, and `'pixels'`.\n * @default 'meters'\n */\n radiusUnits?: Unit;\n /**\n * Radius multiplier.\n * @default 1\n */\n radiusScale?: number;\n /**\n * The minimum radius in pixels. This prop can be used to prevent the circle from getting too small when zoomed out.\n * @default 0\n */\n radiusMinPixels?: number;\n /**\n * The maximum radius in pixels. This prop can be used to prevent the circle from getting too big when zoomed in.\n * @default Number.MAX_SAFE_INTEGER\n */\n radiusMaxPixels?: number;\n\n /**\n * The units of the stroke width, one of `'meters'`, `'common'`, and `'pixels'`.\n * @default 'meters'\n */\n lineWidthUnits?: Unit;\n /**\n * Stroke width multiplier.\n * @default 1\n */\n lineWidthScale?: number;\n /**\n * The minimum stroke width in pixels. This prop can be used to prevent the line from getting too thin when zoomed out.\n * @default 0\n */\n lineWidthMinPixels?: number;\n /**\n * The maximum stroke width in pixels. This prop can be used to prevent the circle from getting too thick when zoomed in.\n * @default Number.MAX_SAFE_INTEGER\n */\n lineWidthMaxPixels?: number;\n\n /**\n * Draw the outline of points.\n * @default false\n */\n stroked?: boolean;\n /**\n * Draw the filled area of points.\n * @default true\n */\n filled?: boolean;\n /**\n * If `true`, rendered circles always face the camera. If `false` circles face up (i.e. are parallel with the ground plane).\n * @default false\n */\n billboard?: boolean;\n /**\n * If `true`, circles are rendered with smoothed edges. If `false`, circles are rendered with rough edges. Antialiasing can cause artifacts on edges of overlapping circles.\n * @default true\n */\n antialiasing?: boolean;\n\n /**\n * Center position accessor.\n */\n getPosition?: Accessor;\n /**\n * Radius accessor.\n * @default 1\n */\n getRadius?: Accessor;\n /**\n * Fill color accessor.\n * @default [0, 0, 0, 255]\n */\n getFillColor?: Accessor;\n /**\n * Stroke color accessor.\n * @default [0, 0, 0, 255]\n */\n getLineColor?: Accessor;\n /**\n * Stroke width accessor.\n * @default 1\n */\n getLineWidth?: Accessor;\n /**\n * @deprecated Use `getLineWidth` instead\n */\n strokeWidth?: number;\n /**\n * @deprecated Use `stroked` instead\n */\n outline?: boolean;\n /**\n * @deprecated Use `getFillColor` and `getLineColor` instead\n */\n getColor?: Accessor;\n};\n\nconst defaultProps: DefaultProps = {\n radiusUnits: 'meters',\n radiusScale: {type: 'number', min: 0, value: 1},\n radiusMinPixels: {type: 'number', min: 0, value: 0}, // min point radius in pixels\n radiusMaxPixels: {type: 'number', min: 0, value: Number.MAX_SAFE_INTEGER}, // max point radius in pixels\n\n lineWidthUnits: 'meters',\n lineWidthScale: {type: 'number', min: 0, value: 1},\n lineWidthMinPixels: {type: 'number', min: 0, value: 0},\n lineWidthMaxPixels: {type: 'number', min: 0, value: Number.MAX_SAFE_INTEGER},\n\n stroked: false,\n filled: true,\n billboard: false,\n antialiasing: true,\n\n getPosition: {type: 'accessor', value: (x: any) => x.position},\n getRadius: {type: 'accessor', value: 1},\n getFillColor: {type: 'accessor', value: DEFAULT_COLOR},\n getLineColor: {type: 'accessor', value: DEFAULT_COLOR},\n getLineWidth: {type: 'accessor', value: 1},\n\n // deprecated\n strokeWidth: {deprecatedFor: 'getLineWidth'},\n outline: {deprecatedFor: 'stroked'},\n getColor: {deprecatedFor: ['getFillColor', 'getLineColor']}\n};\n\n/** Render circles at given coordinates. */\nexport default class ScatterplotLayer extends Layer<\n ExtraPropsT & Required<_ScatterplotLayerProps>\n> {\n static defaultProps = defaultProps;\n static layerName: string = 'ScatterplotLayer';\n\n state!: {\n model?: Model;\n };\n\n getShaders() {\n return super.getShaders({\n vs,\n fs,\n source,\n modules: [project32, color, picking, scatterplotUniforms]\n });\n }\n\n initializeState() {\n this.getAttributeManager()!.addInstanced({\n instancePositions: {\n size: 3,\n type: 'float64',\n fp64: this.use64bitPositions(),\n transition: true,\n accessor: 'getPosition'\n },\n instanceRadius: {\n size: 1,\n transition: true,\n accessor: 'getRadius',\n defaultValue: 1\n },\n instanceFillColors: {\n size: this.props.colorFormat.length,\n transition: true,\n type: 'unorm8',\n accessor: 'getFillColor',\n defaultValue: [0, 0, 0, 255]\n },\n instanceLineColors: {\n size: this.props.colorFormat.length,\n transition: true,\n type: 'unorm8',\n accessor: 'getLineColor',\n defaultValue: [0, 0, 0, 255]\n },\n instanceLineWidths: {\n size: 1,\n transition: true,\n accessor: 'getLineWidth',\n defaultValue: 1\n }\n });\n }\n\n updateState(params: UpdateParameters) {\n super.updateState(params);\n\n if (params.changeFlags.extensionsChanged) {\n this.state.model?.destroy();\n this.state.model = this._getModel();\n this.getAttributeManager()!.invalidateAll();\n }\n }\n\n draw({uniforms}) {\n const {\n radiusUnits,\n radiusScale,\n radiusMinPixels,\n radiusMaxPixels,\n stroked,\n filled,\n billboard,\n antialiasing,\n lineWidthUnits,\n lineWidthScale,\n lineWidthMinPixels,\n lineWidthMaxPixels\n } = this.props;\n const scatterplotProps: ScatterplotProps = {\n stroked,\n filled,\n billboard,\n antialiasing,\n radiusUnits: UNIT[radiusUnits],\n radiusScale,\n radiusMinPixels,\n radiusMaxPixels,\n lineWidthUnits: UNIT[lineWidthUnits],\n lineWidthScale,\n lineWidthMinPixels,\n lineWidthMaxPixels\n };\n const model = this.state.model!;\n model.shaderInputs.setProps({scatterplot: scatterplotProps});\n model.draw(this.context.renderPass);\n }\n\n protected _getModel() {\n // a square that minimally cover the unit circle\n const positions = [-1, -1, 0, 1, -1, 0, -1, 1, 0, 1, 1, 0];\n return new Model(this.context.device, {\n ...this.getShaders(),\n id: this.props.id,\n bufferLayout: this.getAttributeManager()!.getBufferLayouts(),\n geometry: new Geometry({\n topology: 'triangle-strip',\n attributes: {\n positions: {size: 3, value: new Float32Array(positions)}\n }\n }),\n isInstanced: true\n });\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ShaderModule} from '@luma.gl/shadertools';\n\nconst uniformBlock = `\\\nlayout(std140) uniform sdfUniforms {\n float gamma;\n bool enabled;\n float buffer;\n float outlineBuffer;\n vec4 outlineColor;\n} sdf;\n`;\n\nexport type SdfProps = {\n gamma: number;\n enabled: boolean;\n buffer: number;\n outlineBuffer: number;\n outlineColor: [number, number, number, number];\n};\n\nexport const sdfUniforms = {\n name: 'sdf',\n vs: uniformBlock,\n fs: uniformBlock,\n uniformTypes: {\n gamma: 'f32',\n enabled: 'f32',\n buffer: 'f32',\n outlineBuffer: 'f32',\n outlineColor: 'vec4'\n }\n} as const satisfies ShaderModule;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ShaderModule} from '@luma.gl/shadertools';\nimport type {Viewport, OrthographicViewport} from '@deck.gl/core';\n\nexport type ContentAlignModes = keyof typeof CONTENT_ALIGN;\n\nconst CONTENT_ALIGN = {\n none: 0,\n start: 1,\n center: 2,\n end: 3\n} as const;\n\nconst glslUniformBlock = `\\\nlayout(std140) uniform textUniforms {\n highp vec2 cutoffPixels;\n highp ivec2 align;\n highp float fontSize;\n bool flipY;\n} text;\n\n#define ALIGN_MODE_START ${CONTENT_ALIGN.start}\n#define ALIGN_MODE_CENTER ${CONTENT_ALIGN.center}\n#define ALIGN_MODE_END ${CONTENT_ALIGN.end}\n`;\n\nexport type TextModuleProps = {\n contentCutoffPixels?: [number, number];\n contentAlignHorizontal?: ContentAlignModes;\n contentAlignVertical?: ContentAlignModes;\n fontSize: number;\n viewport: Viewport;\n};\n\ntype TextUniforms = {\n cutoffPixels: [number, number];\n align: [number, number];\n fontSize: number;\n // If true, content's x,y is the top-left corner instead of bottom-left\n flipY: boolean;\n};\n\nexport const textUniforms = {\n name: 'text',\n vs: glslUniformBlock,\n getUniforms: ({\n contentCutoffPixels = [0, 0],\n contentAlignHorizontal = 'none',\n contentAlignVertical = 'none',\n fontSize,\n viewport\n }: Partial) => ({\n cutoffPixels: contentCutoffPixels,\n align: [CONTENT_ALIGN[contentAlignHorizontal], CONTENT_ALIGN[contentAlignVertical]],\n fontSize,\n flipY: (viewport as OrthographicViewport)?.flipY ?? false\n }),\n uniformTypes: {\n cutoffPixels: 'vec2',\n align: 'vec2',\n fontSize: 'f32',\n flipY: 'f32'\n }\n} as const satisfies ShaderModule;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport default /* glsl */ `\\\n#version 300 es\n#define SHADER_NAME multi-icon-layer-vertex-shader\n\nin vec2 positions;\n\nin vec3 instancePositions;\nin vec3 instancePositions64Low;\nin float instanceSizes;\nin float instanceAngles;\nin vec4 instanceColors;\nin vec3 instancePickingColors;\nin vec4 instanceIconFrames;\nin float instanceColorModes;\nin vec2 instanceOffsets;\nin vec2 instancePixelOffset;\nin vec4 instanceClipRect;\n\nout float vColorMode;\nout vec4 vColor;\nout vec2 vTextureCoords;\nout vec2 uv;\n\nvec2 rotate_by_angle(vec2 vertex, float angle) {\n float angle_radian = angle * PI / 180.0;\n float cos_angle = cos(angle_radian);\n float sin_angle = sin(angle_radian);\n mat2 rotationMatrix = mat2(cos_angle, -sin_angle, sin_angle, cos_angle);\n return rotationMatrix * vertex;\n}\n\nfloat getPixelOffsetFromAlignment(float anchor, float extent, float clipStart, float clipEnd, int mode) {\n if (clipEnd < clipStart) return 0.0;\n if (mode == ALIGN_MODE_START) {\n return max(- (anchor + clipStart), 0.0);\n }\n if (mode == ALIGN_MODE_CENTER) {\n float _min = max(0., anchor + clipStart);\n float _max = min(extent, anchor + clipEnd);\n return _min < _max ? (_min + _max) / 2.0 - anchor : 0.0;\n }\n if (mode == ALIGN_MODE_END) {\n return min(extent - (anchor + clipEnd), 0.);\n }\n return 0.0;\n}\n\nvoid main(void) {\n geometry.worldPosition = instancePositions;\n geometry.uv = positions;\n geometry.pickingColor = instancePickingColors;\n uv = positions;\n\n vec2 iconSize = instanceIconFrames.zw;\n // convert size in meters to pixels, then scaled and clamp\n \n // project meters to pixels and clamp to limits \n float sizePixels = clamp(\n project_size_to_pixel(instanceSizes * icon.sizeScale, icon.sizeUnits),\n icon.sizeMinPixels, icon.sizeMaxPixels\n );\n\n float instanceScale = sizePixels / text.fontSize;\n\n // scale and rotate vertex in \"pixel\" value and convert back to fraction in clipspace\n vec2 pixelOffset = positions / 2.0 * iconSize + instanceOffsets;\n pixelOffset = rotate_by_angle(pixelOffset, instanceAngles) * instanceScale;\n pixelOffset += instancePixelOffset;\n pixelOffset.y *= -1.0;\n\n vec2 anchorPosScreen;\n if (icon.billboard) {\n gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0), geometry.position);\n anchorPosScreen = gl_Position.xy / gl_Position.w;\n DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n vec3 offset = vec3(pixelOffset, 0.0);\n DECKGL_FILTER_SIZE(offset, geometry);\n gl_Position.xy += project_pixel_size_to_clipspace(offset.xy);\n } else {\n vec3 offset_common = vec3(project_pixel_size(pixelOffset), 0.0);\n if (text.flipY) {\n offset_common.y *= -1.;\n }\n DECKGL_FILTER_SIZE(offset_common, geometry);\n vec4 anchorPos = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0));\n anchorPosScreen = anchorPos.xy / anchorPos.w;\n gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset_common, geometry.position); \n DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n }\n\n anchorPosScreen = vec2(anchorPosScreen.x + 1.0, 1.0 - anchorPosScreen.y) / 2.0 * project.viewportSize / project.devicePixelRatio;\n vec2 xy = project_size_to_pixel(instanceClipRect.xy);\n vec2 wh = project_size_to_pixel(instanceClipRect.zw);\n if (text.flipY) {\n xy.y = -xy.y - wh.y;\n }\n if (text.align.x > 0 || text.align.y > 0) {\n vec2 viewportPixels = project.viewportSize / project.devicePixelRatio;\n vec2 scrollPixels = vec2(\n getPixelOffsetFromAlignment(anchorPosScreen.x, viewportPixels.x, xy.x, xy.x + wh.x, text.align.x),\n -getPixelOffsetFromAlignment(anchorPosScreen.y, viewportPixels.y, -xy.y - wh.y, -xy.y, text.align.y)\n );\n pixelOffset += scrollPixels;\n gl_Position.xy += project_pixel_size_to_clipspace(scrollPixels);\n }\n\n if (instanceClipRect.z >= 0.) {\n if (pixelOffset.x < xy.x || pixelOffset.x > xy.x + wh.x) {\n gl_Position = vec4(0.0);\n }\n else if (text.cutoffPixels.x > 0.) {\n float vpWidth = project.viewportSize.x / project.devicePixelRatio;\n float l = max(anchorPosScreen.x + xy.x, 0.0);\n float r = min(anchorPosScreen.x + xy.x + wh.x, vpWidth);\n if (r - l < text.cutoffPixels.x) {\n gl_Position = vec4(0.0);\n }\n }\n }\n if (instanceClipRect.w >= 0.) {\n if (pixelOffset.y < xy.y || pixelOffset.y > xy.y + wh.y) {\n gl_Position = vec4(0.0);\n }\n else if (text.cutoffPixels.y > 0.) {\n float vpHeight = project.viewportSize.y / project.devicePixelRatio;\n float t = max(anchorPosScreen.y - xy.y - wh.y, 0.0);\n float b = min(anchorPosScreen.y - xy.y, vpHeight);\n if (b - t < text.cutoffPixels.y) {\n gl_Position = vec4(0.0);\n }\n }\n }\n\n vTextureCoords = mix(\n instanceIconFrames.xy,\n instanceIconFrames.xy + iconSize,\n (positions.xy + 1.0) / 2.0\n ) / icon.iconsTextureDim;\n\n vColor = instanceColors;\n DECKGL_FILTER_COLOR(vColor, geometry);\n\n vColorMode = instanceColorModes;\n}\n`;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport default `\\\n#version 300 es\n#define SHADER_NAME multi-icon-layer-fragment-shader\n\nprecision highp float;\n\nuniform sampler2D iconsTexture;\n\nin vec4 vColor;\nin vec2 vTextureCoords;\nin vec2 uv;\n\nout vec4 fragColor;\n\nvoid main(void) {\n geometry.uv = uv;\n\n if (!bool(picking.isActive)) {\n float alpha = texture(iconsTexture, vTextureCoords).a;\n vec4 color = vColor;\n\n // if enable sdf (signed distance fields)\n if (sdf.enabled) {\n float distance = alpha;\n alpha = smoothstep(sdf.buffer - sdf.gamma, sdf.buffer + sdf.gamma, distance);\n\n if (sdf.outlineBuffer > 0.0) {\n float inFill = alpha;\n float inBorder = smoothstep(sdf.outlineBuffer - sdf.gamma, sdf.outlineBuffer + sdf.gamma, distance);\n color = mix(sdf.outlineColor, vColor, inFill);\n alpha = inBorder;\n }\n }\n\n // Take the global opacity and the alpha from color into account for the alpha component\n float a = alpha * color.a;\n \n if (a < icon.alphaCutoff) {\n discard;\n }\n\n fragColor = vec4(color.rgb, a * layer.opacity);\n }\n\n DECKGL_FILTER_COLOR(fragColor, geometry);\n}\n`;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {log, createIterable} from '@deck.gl/core';\nimport IconLayer from '../../icon-layer/icon-layer';\n\nimport {SdfProps, sdfUniforms} from './sdf-uniforms';\nimport {TextModuleProps, textUniforms, ContentAlignModes} from '../text-uniforms';\n\nimport vs from './multi-icon-layer-vertex.glsl';\nimport fs from './multi-icon-layer-fragment.glsl';\n\nimport type {IconLayerProps} from '../../icon-layer/icon-layer';\nimport type {\n Attribute,\n Accessor,\n AccessorFunction,\n Color,\n UpdateParameters,\n DefaultProps\n} from '@deck.gl/core';\n\n// TODO expose as layer properties\nconst DEFAULT_BUFFER = 192.0 / 256;\nconst EMPTY_ARRAY = [];\n\ntype _MultiIconLayerProps = {\n getIconOffsets?: AccessorFunction;\n getContentBox?: Accessor;\n\n fontSize?: number;\n sdf?: boolean;\n smoothing?: number;\n outlineWidth?: number;\n outlineColor?: Color;\n\n contentCutoffPixels?: [width: number, height: number];\n contentAlignHorizontal?: ContentAlignModes;\n contentAlignVertical?: ContentAlignModes;\n};\n\nexport type MultiIconLayerProps = _MultiIconLayerProps &\n IconLayerProps;\n\nconst defaultProps: DefaultProps = {\n getIconOffsets: {type: 'accessor', value: (x: any) => x.offsets},\n getContentBox: {type: 'accessor', value: [0, 0, -1, -1]},\n fontSize: 1,\n alphaCutoff: 0.001,\n smoothing: 0.1,\n outlineWidth: 0,\n outlineColor: {type: 'color', value: [0, 0, 0, 255]},\n contentCutoffPixels: {type: 'array', value: [0, 0]},\n contentAlignHorizontal: 'none',\n contentAlignVertical: 'none'\n};\n\nexport default class MultiIconLayer extends IconLayer<\n DataT,\n ExtraPropsT & Required<_MultiIconLayerProps>\n> {\n static defaultProps = defaultProps;\n static layerName = 'MultiIconLayer';\n\n state!: IconLayer['state'] & {\n outlineColor: [number, number, number, number];\n };\n\n getShaders() {\n const shaders = super.getShaders();\n return {...shaders, modules: [...shaders.modules, textUniforms, sdfUniforms], vs, fs};\n }\n\n initializeState() {\n super.initializeState();\n\n const attributeManager = this.getAttributeManager();\n const instanceIconDefs = attributeManager!.attributes.instanceIconDefs;\n // eslint-disable-next-line @typescript-eslint/unbound-method\n instanceIconDefs.settings.update = this.calculateInstanceIconDefs;\n attributeManager!.addInstanced({\n instancePickingColors: {\n type: 'uint8',\n size: 4,\n accessor: (object, {index, target: value}) => this.encodePickingColor(index, value)\n },\n instanceClipRect: {\n size: 4,\n accessor: 'getContentBox',\n defaultValue: [0, 0, -1, -1]\n }\n });\n }\n\n updateState(params: UpdateParameters) {\n super.updateState(params);\n const {props, oldProps, changeFlags} = params;\n const {outlineColor} = props;\n\n if (\n changeFlags.updateTriggersChanged &&\n (changeFlags.updateTriggersChanged.getIcon ||\n changeFlags.updateTriggersChanged.getIconOffsets)\n ) {\n this.getAttributeManager()!.invalidate('instanceIconDefs');\n }\n if (outlineColor !== oldProps.outlineColor) {\n const normalizedOutlineColor = [\n outlineColor[0] / 255,\n outlineColor[1] / 255,\n outlineColor[2] / 255,\n (outlineColor[3] ?? 255) / 255\n ];\n\n this.setState({\n outlineColor: normalizedOutlineColor\n });\n }\n if (!props.sdf && props.outlineWidth) {\n log.warn(`${this.id}: fontSettings.sdf is required to render outline`)();\n }\n }\n\n draw(params) {\n const {\n sdf,\n smoothing,\n fontSize,\n outlineWidth,\n contentCutoffPixels,\n contentAlignHorizontal,\n contentAlignVertical\n } = this.props;\n const {outlineColor} = this.state;\n const outlineBuffer = outlineWidth\n ? Math.max(smoothing, DEFAULT_BUFFER * (1 - outlineWidth))\n : -1;\n\n const model = this.state.model!;\n const sdfProps: SdfProps = {\n buffer: DEFAULT_BUFFER,\n outlineBuffer,\n gamma: smoothing,\n enabled: Boolean(sdf),\n outlineColor\n };\n const textProps: TextModuleProps = {\n contentCutoffPixels,\n contentAlignHorizontal,\n contentAlignVertical,\n fontSize,\n viewport: this.context.viewport\n };\n model.shaderInputs.setProps({sdf: sdfProps, text: textProps});\n super.draw(params);\n\n // draw text without outline on top to ensure a thick outline won't occlude other characters\n if (sdf && outlineWidth) {\n const {iconManager} = this.state;\n const iconsTexture = iconManager.getTexture();\n\n if (iconsTexture) {\n model.shaderInputs.setProps({sdf: {...sdfProps, outlineBuffer: DEFAULT_BUFFER}});\n model.draw(this.context.renderPass);\n }\n }\n }\n\n protected calculateInstanceIconDefs(\n attribute: Attribute,\n {startRow, endRow}: {startRow: number; endRow: number}\n ) {\n const {data, getIcon, getIconOffsets} = this.props;\n let i = attribute.getVertexOffset(startRow);\n const output = attribute.value as Float32Array;\n const {iterable, objectInfo} = createIterable(data, startRow, endRow);\n for (const object of iterable) {\n objectInfo.index++;\n const text = getIcon(object, objectInfo) as string; // forwarded getText\n const offsets = getIconOffsets(object, objectInfo); // text length x 2\n if (text) {\n let j = 0;\n for (const char of Array.from(text)) {\n const def = super.getInstanceIconDef(char);\n def[0] = offsets[j * 2];\n def[1] += offsets[j * 2 + 1];\n def[6] = 1; // mask\n output.set(def, i);\n i += attribute.size;\n j++;\n }\n }\n }\n }\n}\n","const INF = 1e20;\n\n// lookup table for gamma-corrected, signed squared alpha distance values\nconst alphaTable = new Float64Array(256);\nfor (let i = 0; i < 256; i++) {\n const d = 0.5 - Math.pow(i / 255, 1 / 2.2);\n alphaTable[i] = d * Math.abs(d);\n}\nalphaTable[255] = -INF;\n\nexport default class TinySDF {\n constructor({\n fontSize = 24,\n buffer = 3,\n radius = 8,\n cutoff = 0.25,\n fontFamily = 'sans-serif',\n fontWeight = 'normal',\n fontStyle = 'normal',\n lang = null\n } = {}) {\n this.buffer = buffer; // padding around a glyph's bounding box\n this.radius = radius; // how many pixels around the glyph edge are encoded as signed distances\n this.cutoff = cutoff; // how much of the SDF byte range represents inside vs outside the edge\n this.lang = lang; // language of the Canvas drawing context\n\n // make the canvas size big enough to both have the specified buffer around the glyph\n // for \"halo\", and account for some glyphs possibly being larger than their font size\n const size = this.size = fontSize + buffer * 4;\n\n const canvas = this._createCanvas(size);\n const ctx = this.ctx = canvas.getContext('2d', {willReadFrequently: true});\n ctx.font = `${fontStyle} ${fontWeight} ${fontSize}px ${fontFamily}`;\n\n ctx.textBaseline = 'alphabetic';\n ctx.textAlign = 'left'; // Necessary so that RTL text doesn't have different alignment\n ctx.fillStyle = 'black';\n\n // two grids of squared distances: one for the outside of the glyph shape, one for the inside;\n // the signed distance is derived as sqrt(outer) - sqrt(inner)\n this.gridOuter = new Float64Array(size * size);\n this.gridInner = new Float64Array(size * size);\n this.f = new Float64Array(size);\n this.z = new Float64Array(size + 1);\n this.v = new Uint16Array(size);\n }\n\n _createCanvas(size) {\n if (typeof OffscreenCanvas !== 'undefined') {\n return new OffscreenCanvas(size, size);\n }\n const canvas = document.createElement('canvas');\n canvas.width = canvas.height = size;\n return canvas;\n }\n\n draw(char) {\n const {\n width: glyphAdvance,\n actualBoundingBoxAscent,\n actualBoundingBoxDescent,\n actualBoundingBoxLeft,\n actualBoundingBoxRight\n } = this.ctx.measureText(char);\n\n // The integer/pixel part of the alignment is encoded in metrics.glyphTop/glyphLeft\n // The remainder is implicitly encoded in the rasterization\n const glyphTop = Math.ceil(actualBoundingBoxAscent);\n // actualBoundingBoxLeft is positive when ink extends LEFT of the origin (per spec),\n // so negate to get the ink's left edge in canvas x-coords (positive = right of origin)\n const glyphLeft = Math.floor(-actualBoundingBoxLeft);\n\n // If the glyph overflows the canvas size, it will be clipped at the bottom/right\n const glyphWidth = Math.max(0, Math.min(this.size - this.buffer, Math.ceil(actualBoundingBoxRight) - glyphLeft));\n const glyphHeight = Math.max(0, Math.min(this.size - this.buffer, glyphTop + Math.ceil(actualBoundingBoxDescent)));\n\n const width = glyphWidth + 2 * this.buffer;\n const height = glyphHeight + 2 * this.buffer;\n\n const len = Math.max(width * height, 0);\n const data = new Uint8ClampedArray(len);\n const glyph = {data, width, height, glyphWidth, glyphHeight, glyphTop, glyphLeft, glyphAdvance};\n if (glyphWidth === 0 || glyphHeight === 0) return glyph;\n\n const {ctx, buffer, gridInner, gridOuter} = this;\n if (this.lang) ctx.lang = this.lang;\n ctx.clearRect(buffer, buffer, glyphWidth, glyphHeight);\n ctx.fillText(char, buffer - glyphLeft, buffer + glyphTop);\n const imgData = ctx.getImageData(buffer, buffer, glyphWidth, glyphHeight);\n\n // default: outside the glyph (INF distance) for outer, inside (0 distance) for inner\n gridOuter.fill(INF, 0, len);\n gridInner.fill(0, 0, len);\n\n // for anti-aliased pixels, treat partial coverage as a distance approximation:\n // a fully covered pixel gets 0 outer / INF inner; a partial pixel gets a small\n // non-zero outer or inner distance based on how far its coverage deviates from 0.5\n let imgIdx = 3; // start at the alpha channel of the first pixel\n for (let y = 0; y < glyphHeight; y++) {\n let j = (y + buffer) * width + buffer;\n for (let x = 0; x < glyphWidth; x++, imgIdx += 4, j++) {\n const a = imgData.data[imgIdx]; // alpha value\n if (a === 0) continue; // empty pixels\n const t = alphaTable[a];\n gridOuter[j] = Math.max(0, t);\n gridInner[j] = Math.max(0, -t);\n }\n }\n\n edt(gridOuter, 0, 0, width, height, width, this.f, this.v, this.z);\n // Pad the inner EDT region by 1 px so ink pixels touching the bbox edge can see the\n // outside-ink seeds in the buffer region; clamp to buffer so we don't underflow when buffer=0\n const pad = Math.min(buffer, 1);\n edt(gridInner, buffer - pad, buffer - pad, glyphWidth + 2 * pad, glyphHeight + 2 * pad, width, this.f, this.v, this.z);\n\n // encode signed distance as a byte: inside the glyph maps to high values, outside to low,\n // with the edge gradient spanning [-radius * cutoff, radius * (1 - cutoff)] pixels around the edge;\n // Uint8ClampedArray clamps beyond that\n const scale = 255 / this.radius;\n const base = 255 * (1 - this.cutoff);\n for (let i = 0; i < len; i++) {\n const d = Math.sqrt(gridOuter[i]) - Math.sqrt(gridInner[i]);\n data[i] = Math.round(base - scale * d);\n }\n\n return glyph;\n }\n}\n\n// 2D Euclidean squared distance transform by Felzenszwalb & Huttenlocher https://cs.brown.edu/~pff/papers/dt-final.pdf\nfunction edt(data, x0, y0, width, height, gridSize, f, v, z) {\n for (let x = x0; x < x0 + width; x++) edt1d(data, y0 * gridSize + x, gridSize, height, f, v, z);\n for (let y = y0; y < y0 + height; y++) edt1d(data, y * gridSize + x0, 1, width, f, v, z);\n}\n\n// 1D squared distance transform\nfunction edt1d(grid, offset, stride, length, f, v, z) {\n v[0] = 0;\n z[0] = -INF;\n z[1] = INF;\n f[0] = grid[offset];\n\n for (let q = 1, k = 0, s = 0; q < length; q++) {\n f[q] = grid[offset + q * stride];\n const q2 = q * q;\n do {\n const r = v[k];\n s = (f[q] - f[r] + q2 - r * r) / (q - r) / 2;\n } while (s <= z[k] && --k > -1);\n\n k++;\n v[k] = q;\n z[k] = s;\n z[k + 1] = INF;\n }\n\n for (let q = 0, k = 0; q < length; q++) {\n while (z[k + 1] < q) k++;\n const r = v[k];\n const qr = q - r;\n grid[offset + q * stride] = f[r] + qr * qr;\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/* eslint-disable max-statements, max-params, complexity, max-depth */\n// TODO merge with icon-layer/icon-manager\nimport {log} from '@deck.gl/core';\nimport type {NumericArray} from '@math.gl/core';\n\nconst MISSING_CHAR_WIDTH = 32;\nconst SINGLE_LINE = [];\n\nexport type Character = {\n x: number;\n y: number;\n width: number;\n height: number;\n anchorX: number;\n anchorY: number;\n advance: number;\n};\n\nexport type CharacterMapping = Record;\n\nexport function nextPowOfTwo(number: number): number {\n return Math.pow(2, Math.ceil(Math.log2(number)));\n}\n\n/**\n * Generate character mapping table or update from an existing mapping table\n */\nexport function buildMapping({\n characterSet,\n measureText,\n buffer,\n maxCanvasWidth,\n mapping = {},\n xOffset = 0,\n yOffsetMin = 0,\n yOffsetMax = 0\n}: {\n /** list of characters */\n characterSet: Set;\n /** function to get width of each character */\n measureText: (char: string) => {advance: number; width: number; ascent: number; descent: number};\n /** bleeding buffer surround each character */\n buffer: number;\n /** max width of font atlas */\n maxCanvasWidth: number;\n /** cached mapping table */\n mapping?: CharacterMapping;\n /** x position of last character in the existing mapping table */\n xOffset?: number;\n /** y position of last character in the existing mapping table */\n yOffsetMin?: number;\n /** bottom position of any character in the existing mapping table */\n yOffsetMax?: number;\n}): {\n /** new mapping table */\n mapping: CharacterMapping;\n /** x position of last character in the new mapping table */\n xOffset: number;\n /** y position of last character in the new mapping table */\n yOffsetMin: number;\n /** bottom position of any character in the new mapping table */\n yOffsetMax: number;\n /** height of the font atlas canvas, power of 2 */\n canvasHeight: number;\n} {\n const row = 0;\n // continue from x position of last character in the old mapping\n let x = xOffset;\n let yMin = yOffsetMin;\n let yMax = yOffsetMax;\n\n for (const char of characterSet) {\n if (!mapping[char]) {\n // measure texts\n const {advance, width, ascent, descent} = measureText(char);\n const height = ascent + descent;\n\n if (x + width + buffer * 2 > maxCanvasWidth) {\n x = 0;\n yMin = yMax;\n }\n mapping[char] = {\n x: x + buffer,\n y: yMin + buffer,\n width,\n height,\n advance,\n anchorX: width / 2,\n anchorY: ascent\n };\n x += width + buffer * 2;\n yMax = Math.max(yMax, yMin + height + buffer * 2);\n }\n }\n\n return {\n mapping,\n xOffset: x,\n yOffsetMin: yMin,\n yOffsetMax: yMax,\n canvasHeight: nextPowOfTwo(yMax)\n };\n}\n\nfunction getTextWidth(\n text: string[],\n startIndex: number,\n endIndex: number,\n mapping: CharacterMapping\n): number {\n let width = 0;\n for (let i = startIndex; i < endIndex; i++) {\n const character = text[i];\n width += mapping[character]?.advance || 0;\n }\n\n return width;\n}\n\nfunction breakAll(\n text: string[],\n startIndex: number,\n endIndex: number,\n maxWidth: number,\n iconMapping: CharacterMapping,\n target: number[]\n): number {\n let rowStartCharIndex = startIndex;\n let rowOffsetLeft = 0;\n\n for (let i = startIndex; i < endIndex; i++) {\n // 2. figure out where to break lines\n const textWidth = getTextWidth(text, i, i + 1, iconMapping);\n if (rowOffsetLeft + textWidth > maxWidth) {\n if (rowStartCharIndex < i) {\n target.push(i);\n }\n rowStartCharIndex = i;\n rowOffsetLeft = 0;\n }\n rowOffsetLeft += textWidth;\n }\n\n return rowOffsetLeft;\n}\n\nfunction breakWord(\n text: string[],\n startIndex: number,\n endIndex: number,\n maxWidth: number,\n iconMapping: CharacterMapping,\n target: number[]\n): number {\n let rowStartCharIndex = startIndex;\n let groupStartCharIndex = startIndex;\n let groupEndCharIndex = startIndex;\n let rowOffsetLeft = 0;\n\n for (let i = startIndex; i < endIndex; i++) {\n // 1. break text into word groups\n // - if current char is white space\n // - else if next char is white space\n // - else if reach last char\n if (text[i] === ' ') {\n groupEndCharIndex = i + 1;\n } else if (text[i + 1] === ' ' || i + 1 === endIndex) {\n groupEndCharIndex = i + 1;\n }\n\n if (groupEndCharIndex > groupStartCharIndex) {\n // 2. break text into next row at maxWidth\n let groupWidth = getTextWidth(text, groupStartCharIndex, groupEndCharIndex, iconMapping);\n if (rowOffsetLeft + groupWidth > maxWidth) {\n if (rowStartCharIndex < groupStartCharIndex) {\n target.push(groupStartCharIndex);\n rowStartCharIndex = groupStartCharIndex;\n rowOffsetLeft = 0;\n }\n\n // if a single text group is bigger than maxWidth, then `break-all`\n if (groupWidth > maxWidth) {\n groupWidth = breakAll(\n text,\n groupStartCharIndex,\n groupEndCharIndex,\n maxWidth,\n iconMapping,\n target\n );\n // move reference to last row\n rowStartCharIndex = target[target.length - 1];\n }\n }\n groupStartCharIndex = groupEndCharIndex;\n rowOffsetLeft += groupWidth;\n }\n }\n\n return rowOffsetLeft;\n}\n\n/**\n * Wrap the given text so that each line does not exceed the given max width.\n * Returns a list of indices where line breaks should be inserted.\n */\nexport function autoWrapping(\n text: string[],\n wordBreak: 'break-all' | 'break-word',\n maxWidth: number,\n iconMapping: CharacterMapping,\n startIndex: number = 0,\n endIndex: number\n): number[] {\n if (endIndex === undefined) {\n endIndex = text.length;\n }\n const result = [];\n if (wordBreak === 'break-all') {\n breakAll(text, startIndex, endIndex, maxWidth, iconMapping, result);\n } else {\n breakWord(text, startIndex, endIndex, maxWidth, iconMapping, result);\n }\n return result;\n}\n\nfunction transformRow(\n line: string[],\n startIndex: number,\n endIndex: number,\n iconMapping: CharacterMapping,\n leftOffsets: number[],\n rowSize: [number, number]\n) {\n let x = 0;\n let rowHeight = 0;\n\n for (let i = startIndex; i < endIndex; i++) {\n const character = line[i];\n const frame = iconMapping[character];\n if (frame) {\n rowHeight = Math.max(rowHeight, frame.height);\n }\n }\n\n for (let i = startIndex; i < endIndex; i++) {\n const character = line[i];\n const frame = iconMapping[character];\n if (frame) {\n leftOffsets[i] = x + frame.anchorX;\n x += frame.advance;\n } else {\n log.warn(`Missing character: ${character} (${character.codePointAt(0)})`)();\n leftOffsets[i] = x;\n x += MISSING_CHAR_WIDTH;\n }\n }\n\n rowSize[0] = x;\n rowSize[1] = rowHeight;\n}\n\n/**\n * Transform a text paragraph to an array of characters, each character contains\n */\nexport function transformParagraph(\n paragraph: string,\n /** font property - distance from baseline to vertical center */\n baselineOffset: number,\n /** line-height in pixels */\n lineHeight: number,\n /** CSS word-break option */\n wordBreak: 'break-word' | 'break-all',\n /** CSS max-width */\n maxWidth: number,\n /** character mapping table for retrieving a character from font atlas */\n iconMapping: CharacterMapping\n): {\n /** x position of each character */\n x: number[];\n /** y position of each character */\n y: number[];\n /** the current row width of each character */\n rowWidth: number[];\n /** the width and height of the paragraph */\n size: [number, number];\n} {\n // Break into an array of characters\n // When dealing with double-length unicode characters, `str.length` or `str[i]` do not work\n const characters = Array.from(paragraph);\n const numCharacters = characters.length;\n const x = new Array(numCharacters) as number[];\n const y = new Array(numCharacters) as number[];\n const rowWidth = new Array(numCharacters) as number[];\n const autoWrappingEnabled =\n (wordBreak === 'break-word' || wordBreak === 'break-all') && isFinite(maxWidth) && maxWidth > 0;\n\n // maxWidth and height of the paragraph\n const size: [number, number] = [0, 0];\n const rowSize: [number, number] = [0, 0];\n let rowCount = 0;\n let rowOffsetTop = baselineOffset + lineHeight / 2; // this places the top of the first row at 0\n let lineStartIndex = 0;\n let lineEndIndex = 0;\n\n for (let i = 0; i <= numCharacters; i++) {\n const char = characters[i];\n if (char === '\\n' || i === numCharacters) {\n lineEndIndex = i;\n }\n\n if (lineEndIndex > lineStartIndex) {\n const rows = autoWrappingEnabled\n ? autoWrapping(characters, wordBreak, maxWidth, iconMapping, lineStartIndex, lineEndIndex)\n : SINGLE_LINE;\n\n for (let rowIndex = 0; rowIndex <= rows.length; rowIndex++) {\n const rowStart = rowIndex === 0 ? lineStartIndex : rows[rowIndex - 1];\n const rowEnd = rowIndex < rows.length ? rows[rowIndex] : lineEndIndex;\n\n transformRow(characters, rowStart, rowEnd, iconMapping, x, rowSize);\n for (let j = rowStart; j < rowEnd; j++) {\n y[j] = rowOffsetTop;\n rowWidth[j] = rowSize[0];\n }\n\n rowCount++;\n rowOffsetTop += lineHeight;\n size[0] = Math.max(size[0], rowSize[0]);\n }\n lineStartIndex = lineEndIndex;\n }\n\n if (char === '\\n') {\n // Make sure result.length matches paragraph.length\n x[lineStartIndex] = 0;\n y[lineStartIndex] = 0;\n rowWidth[lineStartIndex] = 0;\n lineStartIndex++;\n }\n }\n\n // last row\n size[1] = rowCount * lineHeight;\n return {x, y, rowWidth, size};\n}\n\nexport function getTextFromBuffer({\n value,\n length,\n stride,\n offset,\n startIndices,\n characterSet\n}: {\n value: Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array;\n length: number;\n stride?: number;\n offset?: number;\n startIndices: NumericArray;\n characterSet?: Set;\n}): {\n texts: string[];\n characterCount: number;\n} {\n const bytesPerElement = value.BYTES_PER_ELEMENT;\n const elementStride = stride ? stride / bytesPerElement : 1;\n const elementOffset = offset ? offset / bytesPerElement : 0;\n const characterCount =\n startIndices[length] || Math.ceil((value.length - elementOffset) / elementStride);\n const autoCharacterSet = characterSet && new Set();\n\n const texts = new Array(length);\n\n let codes = value;\n if (elementStride > 1 || elementOffset > 0) {\n const ArrayType = value.constructor as\n | Uint8ArrayConstructor\n | Uint8ClampedArrayConstructor\n | Uint16ArrayConstructor\n | Uint32ArrayConstructor;\n codes = new ArrayType(characterCount);\n for (let i = 0; i < characterCount; i++) {\n codes[i] = value[i * elementStride + elementOffset];\n }\n }\n\n for (let index = 0; index < length; index++) {\n const startIndex = startIndices[index];\n const endIndex = startIndices[index + 1] || characterCount;\n const codesAtIndex = codes.subarray(startIndex, endIndex);\n // @ts-ignore TS wants the argument to be number[] but typed array works too\n texts[index] = String.fromCodePoint.apply(null, codesAtIndex);\n if (autoCharacterSet) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n codesAtIndex.forEach(autoCharacterSet.add, autoCharacterSet);\n }\n }\n\n if (autoCharacterSet) {\n for (const charCode of autoCharacterSet) {\n characterSet.add(String.fromCodePoint(charCode));\n }\n }\n\n return {texts, characterCount};\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/**\n * LRU Cache class with limit\n *\n * Update order for each get/set operation\n * Delete oldest when reach given limit\n */\n\nexport default class LRUCache {\n private limit: number;\n private _cache: Record = {};\n /** access/update order, first item is oldest, last item is newest */\n private _order: string[] = [];\n\n constructor(limit: number = 5) {\n this.limit = limit;\n }\n\n get(key: string): ValueT {\n const value = this._cache[key];\n if (value) {\n // update order\n this._deleteOrder(key);\n this._appendOrder(key);\n }\n return value;\n }\n\n set(key: string, value: ValueT): void {\n if (!this._cache[key]) {\n // if reach limit, delete the oldest\n if (Object.keys(this._cache).length === this.limit) {\n this.delete(this._order[0]);\n }\n\n this._cache[key] = value;\n this._appendOrder(key);\n } else {\n // if found in cache, delete the old one, insert new one to the first of list\n this.delete(key);\n\n this._cache[key] = value;\n this._appendOrder(key);\n }\n }\n\n delete(key: string): void {\n const value = this._cache[key];\n if (value) {\n delete this._cache[key];\n this._deleteOrder(key);\n }\n }\n\n private _deleteOrder(key: string): void {\n const index = this._order.indexOf(key);\n if (index >= 0) {\n this._order.splice(index, 1);\n }\n }\n\n private _appendOrder(key: string): void {\n this._order.push(key);\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/* global document */\nimport TinySDF from '@mapbox/tiny-sdf';\n\nimport {log} from '@deck.gl/core';\n\nimport {buildMapping, CharacterMapping} from './utils';\nimport LRUCache from './lru-cache';\n\n// import type {Texture} from '@deck.gl/core';\n\nfunction getDefaultCharacterSet() {\n const charSet: string[] = [];\n for (let i = 32; i < 128; i++) {\n charSet.push(String.fromCharCode(i));\n }\n return charSet;\n}\n\nexport interface FontRenderer {\n /**\n * Measure the dimensions of a given character. If no parameter is passed, returns the bounding metrics of the font.\n *\n * Returned metrics:\n * - `advance`: horizontal distance to move the cursor before placing the next glyph, in pixels.\n * - `width`: width of the visible glyph bounds, in pixels.\n * - `ascent`: distance from the baseline to the top of the glyph, in pixels.\n * - `descent`: distance from the baseline to the bottom of the glyph, in pixels.\n */\n measure(char?: string): {\n advance: number;\n width: number;\n ascent: number;\n descent: number;\n };\n /**\n * Render the given character to an image.\n *\n * Returned image data:\n * - `data`: rasterized glyph pixels.\n * - `left`: x offset from the glyph origin to the left edge of `data`, in pixels. Default `0`.\n * - `top`: y offset from the glyph origin to the top edge of `data`, in pixels. Default `0`.\n */\n draw(char: string): {\n data: ImageData;\n left?: number;\n top?: number;\n };\n}\n\nexport type FontSettings = {\n /** CSS font family\n * @default 'Monaco, monospace'\n */\n fontFamily?: string;\n /** CSS font weight\n * @default 'normal'\n */\n fontWeight?: string | number;\n /** Specifies a list of characters to include in the font.\n * @default (ASCII characters 32-128)\n */\n characterSet?: Set | string[] | string;\n /** Font size in pixels. This option is only applied for generating `fontAtlas`, it does not impact the size of displayed text labels. Larger `fontSize` will give you a sharper look when rendering text labels with very large font sizes. But larger `fontSize` requires more time and space to generate the `fontAtlas`.\n * @default 64\n */\n fontSize?: number;\n /** Whitespace buffer around each side of the character. In general, bigger `fontSize` requires bigger `buffer`. Increase `buffer` will add more space between each character when layout `characterSet` in `fontAtlas`. This option could be tuned to provide sufficient space for drawing each character and avoiding overlapping of neighboring characters.\n * @default 4\n */\n buffer?: number;\n /** Flag to enable / disable `sdf`. [`sdf` (Signed Distance Fields)](http://cs.brown.edu/people/pfelzens/papers/dt-final.pdf) will provide a sharper look when rendering with very large or small font sizes. `TextLayer` integrates with [`TinySDF`](https://github.com/mapbox/tiny-sdf) which implements the `sdf` algorithm.\n * @default false\n */\n sdf?: boolean;\n /** How much of the radius (relative) is used for the inside part the glyph. Bigger `cutoff` makes character thinner. Smaller `cutoff` makes character look thicker. Only applies when `sdf: true`.\n * @default 0.25\n */\n cutoff?: number;\n /** How many pixels around the glyph shape to use for encoding distance. Bigger radius yields higher quality outcome. Only applies when `sdf: true`.\n * @default 12\n */\n radius?: number;\n /** How much smoothing to apply to the text edges. Only applies when `sdf: true`.\n * @default 0.1\n */\n smoothing?: number;\n};\n\nexport const DEFAULT_FONT_SETTINGS: Required = {\n fontFamily: 'Monaco, monospace',\n fontWeight: 'normal',\n characterSet: getDefaultCharacterSet(),\n fontSize: 64,\n buffer: 4,\n sdf: false,\n cutoff: 0.25,\n radius: 12,\n smoothing: 0.1\n};\n\nconst MAX_CANVAS_WIDTH = 1024;\n\nconst DEFAULT_ASCENT = 0.9;\nconst DEFAULT_DESCENT = 0.3;\n\n// only preserve latest three fontAtlas\nconst CACHE_LIMIT = 3;\n\ntype FontAtlas = {\n baselineOffset: number;\n /** x position of last character in mapping */\n xOffset: number;\n /** y position of last character in mapping */\n yOffsetMin: number;\n /** bottom position of any character in mapping */\n yOffsetMax: number;\n /** bounding box of each character in the texture */\n mapping: CharacterMapping;\n /** packed texture */\n data: HTMLCanvasElement;\n /** texture width */\n width: number;\n /** texture height */\n height: number;\n};\n\nlet cache = new LRUCache(CACHE_LIMIT);\n\n/**\n * get all the chars not in cache\n * @returns chars not in cache\n */\nfunction getNewChars(cacheKey: string, characterSet: Set | string[] | string): Set {\n let newCharSet: Set;\n if (typeof characterSet === 'string') {\n newCharSet = new Set(Array.from(characterSet));\n } else {\n newCharSet = new Set(characterSet);\n }\n\n const cachedFontAtlas = cache.get(cacheKey);\n if (!cachedFontAtlas) {\n return newCharSet;\n }\n\n for (const char in cachedFontAtlas.mapping) {\n if (newCharSet.has(char)) {\n newCharSet.delete(char);\n }\n }\n return newCharSet;\n}\n\nfunction populateAlphaChannel(\n alphaChannel: Uint8ClampedArray | Uint8Array,\n imageData: ImageData\n): void {\n // populate distance value from tinySDF to image alpha channel\n for (let i = 0; i < alphaChannel.length; i++) {\n imageData.data[4 * i + 3] = alphaChannel[i];\n }\n}\n\nfunction setTextStyle(\n ctx: CanvasRenderingContext2D,\n fontFamily: string,\n fontSize: number,\n fontWeight: string | number\n): void {\n ctx.font = `${fontWeight} ${fontSize}px ${fontFamily}`;\n ctx.fillStyle = '#000';\n ctx.textBaseline = 'alphabetic';\n ctx.textAlign = 'left';\n}\n\nfunction measureText(\n ctx: CanvasRenderingContext2D,\n fontSize: number,\n char: string | undefined\n): {advance: number; width: number; ascent: number; descent: number} {\n if (char === undefined) {\n const fontMetrics = ctx.measureText('A');\n if (fontMetrics.fontBoundingBoxAscent) {\n return {\n advance: 0,\n width: 0,\n ascent: Math.ceil(fontMetrics.fontBoundingBoxAscent),\n descent: Math.ceil(fontMetrics.fontBoundingBoxDescent)\n };\n }\n return {\n advance: 0,\n width: 0,\n ascent: fontSize * DEFAULT_ASCENT,\n descent: fontSize * DEFAULT_DESCENT\n };\n }\n\n const metrics = ctx.measureText(char);\n if (!metrics.actualBoundingBoxAscent) {\n // TextMetrics not fully supported\n return {\n advance: metrics.width,\n width: metrics.width,\n ascent: fontSize * DEFAULT_ASCENT,\n descent: fontSize * DEFAULT_DESCENT\n };\n }\n return {\n advance: metrics.width,\n width: Math.ceil(metrics.actualBoundingBoxRight - metrics.actualBoundingBoxLeft),\n ascent: Math.ceil(metrics.actualBoundingBoxAscent),\n descent: Math.ceil(metrics.actualBoundingBoxDescent)\n };\n}\n\n/**\n * Sets the Font Atlas LRU Cache Limit\n * @param {number} limit LRU Cache limit\n */\nexport function setFontAtlasCacheLimit(limit: number): void {\n log.assert(Number.isFinite(limit) && limit >= CACHE_LIMIT, 'Invalid cache limit');\n\n cache = new LRUCache(limit);\n}\n\nexport default class FontAtlasManager {\n /** Font settings */\n props: Required = {...DEFAULT_FONT_SETTINGS};\n\n /** Cache key of the current font atlas */\n private _key?: string;\n /** The current font atlas */\n private _atlas?: FontAtlas;\n\n private _getFontRenderer?: (settings: Required) => FontRenderer;\n\n get atlas(): Readonly | undefined {\n return this._atlas;\n }\n\n // TODO - cut during v9 porting as types reveal this is not correct\n // get texture(): Texture | undefined {\n // return this._atlas;\n // }\n\n get mapping(): CharacterMapping | undefined {\n return this._atlas && this._atlas.mapping;\n }\n\n setProps(\n props: FontSettings & {\n _getFontRenderer?: (settings: Required) => FontRenderer;\n } = {}\n ) {\n Object.assign(this.props, props);\n if (props._getFontRenderer) {\n this._getFontRenderer = props._getFontRenderer;\n }\n\n // update cache key\n this._key = this._getKey();\n\n const charSet = getNewChars(this._key, this.props.characterSet);\n const cachedFontAtlas = cache.get(this._key);\n\n // if a fontAtlas associated with the new settings is cached and\n // there are no new chars\n if (cachedFontAtlas && charSet.size === 0) {\n // update texture with cached fontAtlas\n if (this._atlas !== cachedFontAtlas) {\n this._atlas = cachedFontAtlas;\n }\n return;\n }\n\n // update fontAtlas with new settings\n const fontAtlas = this._generateFontAtlas(charSet, cachedFontAtlas);\n this._atlas = fontAtlas;\n\n // update cache\n cache.set(this._key, fontAtlas);\n }\n\n // eslint-disable-next-line max-statements\n private _generateFontAtlas(characterSet: Set, cachedFontAtlas?: FontAtlas): FontAtlas {\n const {fontFamily, fontWeight, fontSize, buffer, sdf, radius, cutoff} = this.props;\n let canvas = cachedFontAtlas && cachedFontAtlas.data;\n if (!canvas) {\n canvas = document.createElement('canvas');\n canvas.width = MAX_CANVAS_WIDTH;\n }\n const ctx = canvas.getContext('2d', {willReadFrequently: true})!;\n setTextStyle(ctx, fontFamily, fontSize, fontWeight);\n const defaultMeasure = (char?: string) => measureText(ctx, fontSize, char);\n\n let renderer: FontRenderer | undefined;\n if (this._getFontRenderer) {\n renderer = this._getFontRenderer(this.props);\n } else if (sdf) {\n renderer = {\n measure: defaultMeasure,\n draw: getSdfFontRenderer(this.props)\n };\n }\n\n // 1. build mapping\n const {mapping, canvasHeight, xOffset, yOffsetMin, yOffsetMax} = buildMapping({\n measureText: char => (renderer ? renderer.measure(char) : defaultMeasure(char)),\n buffer,\n characterSet,\n maxCanvasWidth: MAX_CANVAS_WIDTH,\n ...(cachedFontAtlas && {\n mapping: cachedFontAtlas.mapping,\n xOffset: cachedFontAtlas.xOffset,\n yOffsetMin: cachedFontAtlas.yOffsetMin,\n yOffsetMax: cachedFontAtlas.yOffsetMax\n })\n });\n\n // 2. update canvas\n // copy old canvas data to new canvas only when height changed\n if (canvas.height !== canvasHeight) {\n const imageData =\n canvas.height > 0 ? ctx.getImageData(0, 0, canvas.width, canvas.height) : null;\n canvas.height = canvasHeight;\n if (imageData) {\n ctx.putImageData(imageData, 0, 0);\n }\n }\n setTextStyle(ctx, fontFamily, fontSize, fontWeight);\n\n // 3. layout characters\n if (renderer) {\n for (const char of characterSet) {\n const frame = mapping[char];\n const {data, left = 0, top = 0} = renderer.draw(char);\n const x = frame.x - left;\n const y = frame.y - top;\n // snap origin to the nearest pixel\n const x0 = Math.max(0, Math.round(x));\n const y0 = Math.max(0, Math.round(y));\n const w = Math.min(data.width, canvas.width - x0);\n const h = Math.min(data.height, canvas.height - y0);\n ctx.putImageData(data, x0, y0, 0, 0, w, h);\n\n frame.x += x0 - x;\n frame.y += y0 - y;\n }\n } else {\n for (const char of characterSet) {\n const frame = mapping[char];\n ctx.fillText(char, frame.x, frame.y + frame.anchorY);\n }\n }\n\n const fontMetrics = renderer ? renderer.measure() : defaultMeasure();\n\n return {\n baselineOffset: (fontMetrics.ascent - fontMetrics.descent) / 2,\n xOffset,\n yOffsetMin,\n yOffsetMax,\n mapping,\n data: canvas,\n width: canvas.width,\n height: canvas.height\n };\n }\n\n private _getKey(): string {\n const {fontFamily, fontWeight, fontSize, buffer, sdf, radius, cutoff} = this.props;\n if (sdf) {\n return `${fontFamily} ${fontWeight} ${fontSize} ${buffer} ${radius} ${cutoff}`;\n }\n return `${fontFamily} ${fontWeight} ${fontSize} ${buffer}`;\n }\n}\n\nfunction getSdfFontRenderer({\n fontSize,\n buffer,\n radius,\n cutoff,\n fontFamily,\n fontWeight\n}: Required): FontRenderer['draw'] {\n const tinySDF = new TinySDF({\n fontSize,\n buffer,\n radius,\n cutoff,\n fontFamily,\n fontWeight: `${fontWeight}`\n });\n\n return (char: string) => {\n const {data, width, height} = tinySDF.draw(char);\n const imageData = new ImageData(width, height);\n populateAlphaChannel(data, imageData);\n return {data: imageData, left: buffer, top: buffer};\n };\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ShaderModule} from '@luma.gl/shadertools';\n\nconst uniformBlock = `\\\nlayout(std140) uniform textBackgroundUniforms {\n bool billboard;\n float sizeScale;\n float sizeMinPixels;\n float sizeMaxPixels;\n vec4 borderRadius;\n vec4 padding;\n highp int sizeUnits;\n bool stroked;\n} textBackground;\n`;\n\nexport type TextBackgroundProps = {\n billboard: boolean;\n sizeScale: number;\n sizeMinPixels: number;\n sizeMaxPixels: number;\n borderRadius: Readonly<[number, number, number, number]>;\n padding: Readonly<[number, number, number, number]>;\n sizeUnits: number;\n stroked: boolean;\n};\n\nexport const textBackgroundUniforms = {\n name: 'textBackground',\n vs: uniformBlock,\n fs: uniformBlock,\n uniformTypes: {\n billboard: 'f32',\n sizeScale: 'f32',\n sizeMinPixels: 'f32',\n sizeMaxPixels: 'f32',\n borderRadius: 'vec4',\n padding: 'vec4',\n sizeUnits: 'i32',\n stroked: 'f32'\n }\n} as const satisfies ShaderModule;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport default /* glsl */ `\\\n#version 300 es\n#define SHADER_NAME text-background-layer-vertex-shader\n\nin vec2 positions;\n\nin vec3 instancePositions;\nin vec3 instancePositions64Low;\nin vec4 instanceRects;\nin vec4 instanceClipRect;\nin float instanceSizes;\nin float instanceAngles;\nin vec2 instancePixelOffsets;\nin float instanceLineWidths;\nin vec4 instanceFillColors;\nin vec4 instanceLineColors;\nin vec3 instancePickingColors;\n\nout vec4 vFillColor;\nout vec4 vLineColor;\nout float vLineWidth;\nout vec2 uv;\nout vec2 dimensions;\n\nvec2 rotate_by_angle(vec2 vertex, float angle) {\n float angle_radian = radians(angle);\n float cos_angle = cos(angle_radian);\n float sin_angle = sin(angle_radian);\n mat2 rotationMatrix = mat2(cos_angle, -sin_angle, sin_angle, cos_angle);\n return rotationMatrix * vertex;\n}\n\nvoid main(void) {\n geometry.worldPosition = instancePositions;\n geometry.uv = positions;\n geometry.pickingColor = instancePickingColors;\n uv = positions;\n vLineWidth = instanceLineWidths;\n\n // convert size in meters to pixels, then scaled and clamp\n\n // project meters to pixels and clamp to limits\n float sizePixels = clamp(\n project_size_to_pixel(instanceSizes * textBackground.sizeScale, textBackground.sizeUnits),\n textBackground.sizeMinPixels, textBackground.sizeMaxPixels\n );\n float instanceScale = sizePixels / text.fontSize;\n\n dimensions = instanceRects.zw * instanceScale + textBackground.padding.xy + textBackground.padding.zw;\n\n vec2 pixelOffset = (positions * instanceRects.zw + instanceRects.xy) * instanceScale + mix(-textBackground.padding.xy, textBackground.padding.zw, positions);\n pixelOffset = rotate_by_angle(pixelOffset, instanceAngles);\n pixelOffset += instancePixelOffsets;\n pixelOffset.y *= -1.0;\n\n // apply clipping\n vec2 xy = project_size_to_pixel(instanceClipRect.xy);\n vec2 wh = project_size_to_pixel(instanceClipRect.zw);\n if (text.flipY) {\n xy.y = -xy.y - wh.y;\n }\n if (instanceClipRect.z >= 0.0) {\n dimensions.x = wh.x;\n pixelOffset.x = xy.x + uv.x * wh.x + mix(-textBackground.padding.x, textBackground.padding.z, uv.x);\n }\n if (instanceClipRect.w >= 0.0) {\n dimensions.y = wh.y;\n pixelOffset.y = xy.y + uv.y * wh.y + mix(-textBackground.padding.y, textBackground.padding.w, uv.y);\n }\n\n if (textBackground.billboard) {\n gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0), geometry.position);\n DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n vec3 offset = vec3(pixelOffset, 0.0);\n DECKGL_FILTER_SIZE(offset, geometry);\n gl_Position.xy += project_pixel_size_to_clipspace(offset.xy);\n } else {\n vec3 offset_common = vec3(project_pixel_size(pixelOffset), 0.0);\n if (text.flipY) {\n offset_common.y *= -1.;\n }\n DECKGL_FILTER_SIZE(offset_common, geometry);\n gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset_common, geometry.position);\n DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n }\n\n // Apply opacity to instance color, or return instance picking color\n vFillColor = vec4(instanceFillColors.rgb, instanceFillColors.a * layer.opacity);\n DECKGL_FILTER_COLOR(vFillColor, geometry);\n vLineColor = vec4(instanceLineColors.rgb, instanceLineColors.a * layer.opacity);\n DECKGL_FILTER_COLOR(vLineColor, geometry);\n}\n`;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport default `\\\n#version 300 es\n#define SHADER_NAME text-background-layer-fragment-shader\n\nprecision highp float;\n\nin vec4 vFillColor;\nin vec4 vLineColor;\nin float vLineWidth;\nin vec2 uv;\nin vec2 dimensions;\n\nout vec4 fragColor;\n\nfloat round_rect(vec2 p, vec2 size, vec4 radii) {\n // Convert p and size to center-based coordinates [-0.5, 0.5]\n vec2 pixelPositionCB = (p - 0.5) * size;\n vec2 sizeCB = size * 0.5;\n\n float maxBorderRadius = min(size.x, size.y) * 0.5;\n vec4 borderRadius = vec4(min(radii, maxBorderRadius));\n\n // from https://www.shadertoy.com/view/4llXD7\n borderRadius.xy =\n (pixelPositionCB.x > 0.0) ? borderRadius.xy : borderRadius.zw;\n borderRadius.x = (pixelPositionCB.y > 0.0) ? borderRadius.x : borderRadius.y;\n vec2 q = abs(pixelPositionCB) - sizeCB + borderRadius.x;\n return -(min(max(q.x, q.y), 0.0) + length(max(q, 0.0)) - borderRadius.x);\n}\n\nfloat rect(vec2 p, vec2 size) {\n vec2 pixelPosition = p * size;\n return min(min(pixelPosition.x, size.x - pixelPosition.x),\n min(pixelPosition.y, size.y - pixelPosition.y));\n}\n\nvec4 get_stroked_fragColor(float dist) {\n float isBorder = smoothedge(dist, vLineWidth);\n return mix(vFillColor, vLineColor, isBorder);\n}\n\nvoid main(void) {\n geometry.uv = uv;\n\n if (textBackground.borderRadius != vec4(0.0)) {\n float distToEdge = round_rect(uv, dimensions, textBackground.borderRadius);\n float shapeAlpha = smoothedge(-distToEdge, 0.0);\n if (shapeAlpha == 0.0) {\n discard;\n }\n if (textBackground.stroked) {\n fragColor = get_stroked_fragColor(distToEdge);\n } else {\n fragColor = vFillColor;\n }\n fragColor.a *= shapeAlpha;\n } else {\n if (textBackground.stroked) {\n float distToEdge = rect(uv, dimensions);\n fragColor = get_stroked_fragColor(distToEdge);\n } else {\n fragColor = vFillColor;\n }\n }\n DECKGL_FILTER_COLOR(fragColor, geometry);\n}\n`;\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Layer, project32, picking, UNIT} from '@deck.gl/core';\nimport {Geometry} from '@luma.gl/engine';\nimport {Model} from '@luma.gl/engine';\n\nimport {TextBackgroundProps, textBackgroundUniforms} from './text-background-layer-uniforms';\nimport {TextModuleProps, textUniforms} from '../text-uniforms';\nimport vs from './text-background-layer-vertex.glsl';\nimport fs from './text-background-layer-fragment.glsl';\n\nimport type {\n LayerProps,\n LayerDataSource,\n Accessor,\n Unit,\n Position,\n Color,\n UpdateParameters,\n DefaultProps\n} from '@deck.gl/core';\n\ntype _TextBackgroundLayerProps = {\n data: LayerDataSource;\n billboard?: boolean;\n sizeScale?: number;\n sizeUnits?: Unit;\n sizeMinPixels?: number;\n sizeMaxPixels?: number;\n fontSize?: number;\n\n borderRadius?: number | Readonly<[number, number, number, number]>;\n padding?: Readonly<[number, number]> | Readonly<[number, number, number, number]>;\n\n getPosition?: Accessor;\n getSize?: Accessor;\n getAngle?: Accessor;\n getPixelOffset?: Accessor>;\n getBoundingRect?: Accessor>;\n getClipRect?: Accessor;\n getFillColor?: Accessor;\n getLineColor?: Accessor;\n getLineWidth?: Accessor;\n};\n\nexport type TextBackgroundLayerProps = _TextBackgroundLayerProps &\n LayerProps;\n\nconst defaultProps: DefaultProps = {\n billboard: true,\n sizeScale: 1,\n sizeUnits: 'pixels',\n sizeMinPixels: 0,\n sizeMaxPixels: Number.MAX_SAFE_INTEGER,\n fontSize: 1,\n\n borderRadius: {type: 'object', value: 0},\n padding: {type: 'array', value: [0, 0, 0, 0]},\n\n getPosition: {type: 'accessor', value: (x: any) => x.position},\n getSize: {type: 'accessor', value: 1},\n getAngle: {type: 'accessor', value: 0},\n getPixelOffset: {type: 'accessor', value: [0, 0]},\n getBoundingRect: {type: 'accessor', value: [0, 0, 0, 0]},\n getClipRect: {type: 'accessor', value: [0, 0, -1, -1]},\n getFillColor: {type: 'accessor', value: [0, 0, 0, 255]},\n getLineColor: {type: 'accessor', value: [0, 0, 0, 255]},\n getLineWidth: {type: 'accessor', value: 1}\n};\n\nexport default class TextBackgroundLayer extends Layer<\n ExtraPropsT & Required<_TextBackgroundLayerProps>\n> {\n static defaultProps = defaultProps;\n static layerName = 'TextBackgroundLayer';\n\n state!: {\n model?: Model;\n };\n\n getShaders() {\n return super.getShaders({\n vs,\n fs,\n modules: [project32, picking, textBackgroundUniforms, textUniforms]\n });\n }\n\n initializeState() {\n this.getAttributeManager()!.addInstanced({\n instancePositions: {\n size: 3,\n type: 'float64',\n fp64: this.use64bitPositions(),\n transition: true,\n accessor: 'getPosition'\n },\n instanceSizes: {\n size: 1,\n transition: true,\n accessor: 'getSize',\n defaultValue: 1\n },\n instanceAngles: {\n size: 1,\n transition: true,\n accessor: 'getAngle'\n },\n instanceRects: {\n size: 4,\n accessor: 'getBoundingRect'\n },\n instanceClipRect: {\n size: 4,\n accessor: 'getClipRect',\n defaultValue: [0, 0, -1, -1]\n },\n instancePixelOffsets: {\n size: 2,\n transition: true,\n accessor: 'getPixelOffset'\n },\n instanceFillColors: {\n size: 4,\n transition: true,\n type: 'unorm8',\n accessor: 'getFillColor',\n defaultValue: [0, 0, 0, 255]\n },\n instanceLineColors: {\n size: 4,\n transition: true,\n type: 'unorm8',\n accessor: 'getLineColor',\n defaultValue: [0, 0, 0, 255]\n },\n instanceLineWidths: {\n size: 1,\n transition: true,\n accessor: 'getLineWidth',\n defaultValue: 1\n }\n });\n }\n\n updateState(params: UpdateParameters) {\n super.updateState(params);\n const {changeFlags} = params;\n if (changeFlags.extensionsChanged) {\n this.state.model?.destroy();\n this.state.model = this._getModel();\n this.getAttributeManager()!.invalidateAll();\n }\n }\n\n draw({uniforms}) {\n const {billboard, sizeScale, sizeUnits, sizeMinPixels, sizeMaxPixels, getLineWidth, fontSize} =\n this.props;\n let {padding, borderRadius} = this.props;\n\n if (padding.length < 4) {\n padding = [padding[0], padding[1], padding[0], padding[1]];\n }\n\n if (!Array.isArray(borderRadius)) {\n borderRadius = [\n borderRadius as number,\n borderRadius as number,\n borderRadius as number,\n borderRadius as number\n ];\n }\n\n const model = this.state.model!;\n const textBackgroundProps: TextBackgroundProps = {\n billboard,\n stroked: Boolean(getLineWidth),\n borderRadius: borderRadius as [number, number, number, number],\n padding: padding as [number, number, number, number],\n sizeUnits: UNIT[sizeUnits],\n sizeScale,\n sizeMinPixels,\n sizeMaxPixels\n };\n const textProps: TextModuleProps = {\n fontSize,\n viewport: this.context.viewport\n };\n model.shaderInputs.setProps({textBackground: textBackgroundProps, text: textProps});\n model.draw(this.context.renderPass);\n }\n\n protected _getModel(): Model {\n // a square that minimally cover the unit circle\n const positions = [0, 0, 1, 0, 0, 1, 1, 1];\n\n return new Model(this.context.device, {\n ...this.getShaders(),\n id: this.props.id,\n bufferLayout: this.getAttributeManager()!.getBufferLayouts(),\n geometry: new Geometry({\n topology: 'triangle-strip',\n vertexCount: 4,\n attributes: {\n positions: {size: 2, value: new Float32Array(positions)}\n }\n }),\n isInstanced: true\n });\n }\n}\n","// deck.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {CompositeLayer, createIterable, log} from '@deck.gl/core';\nimport MultiIconLayer from './multi-icon-layer/multi-icon-layer';\nimport FontAtlasManager, {\n DEFAULT_FONT_SETTINGS,\n setFontAtlasCacheLimit\n} from './font-atlas-manager';\nimport {transformParagraph, getTextFromBuffer} from './utils';\n\nimport TextBackgroundLayer from './text-background-layer/text-background-layer';\nimport type {ContentAlignModes} from './text-uniforms';\n\nimport type {FontSettings, FontRenderer} from './font-atlas-manager';\nimport type {\n LayerProps,\n LayerDataSource,\n Accessor,\n AccessorFunction,\n AccessorContext,\n Unit,\n Position,\n Color,\n UpdateParameters,\n GetPickingInfoParams,\n PickingInfo,\n DefaultProps\n} from '@deck.gl/core';\n\nconst TEXT_ANCHOR = {\n start: 1,\n middle: 0,\n end: -1\n} as const;\n\nconst ALIGNMENT_BASELINE = {\n top: 1,\n center: 0,\n bottom: -1\n} as const;\n\nconst DEFAULT_COLOR = [0, 0, 0, 255] as const;\n\nconst DEFAULT_LINE_HEIGHT = 1.0;\n\ntype _TextLayerProps = {\n data: LayerDataSource;\n /** If `true`, the text always faces camera. Otherwise the text faces up (z).\n * @default true\n */\n billboard?: boolean;\n /**\n * Text size multiplier.\n * @default 1\n */\n sizeScale?: number;\n /**\n * The units of the size, one of `'meters'`, `'common'`, and `'pixels'`.\n * @default 'pixels'\n */\n sizeUnits?: Unit;\n /**\n * The minimum size in pixels. When using non-pixel `sizeUnits`, this prop can be used to prevent the icon from getting too small when zoomed out.\n * @default 0\n */\n sizeMinPixels?: number;\n /**\n * The maximum size in pixels. When using non-pixel `sizeUnits`, this prop can be used to prevent the icon from getting too big when zoomed in.\n * @default Number.MAX_SAFE_INTEGER\n */\n sizeMaxPixels?: number;\n\n /** Whether to render background for the text blocks.\n * @default false\n */\n background?: boolean;\n /** Background color accessor.\n * @default [255, 255, 255, 255]\n */\n getBackgroundColor?: Accessor;\n /** Border color accessor.\n * @default [0, 0, 0, 255]\n */\n getBorderColor?: Accessor;\n /** Border width accessor.\n * @default 0\n */\n getBorderWidth?: Accessor;\n /** The border radius of the background.\n * If a number is supplied, it is the same border radius in pixel for all corners.\n * If an array of 4 is supplied, it is interpreted as `[bottom_right_corner, top_right_corner, bottom_left_corner, top_left_corner]` border radius in pixel.\n * @default 0\n */\n backgroundBorderRadius?: number | Readonly<[number, number, number, number]>;\n /**\n * The padding around the text to position the background. Only effective if content box is unset.\n * If an array of 2 is supplied, it is interpreted as `[padding_x, padding_y]` in pixels.\n * If an array of 4 is supplied, it is interpreted as `[padding_left, padding_top, padding_right, padding_bottom]` in pixels.\n * @default [0, 0, 0, 0]\n */\n backgroundPadding?: Readonly<[number, number]> | Readonly<[number, number, number, number]>;\n /**\n * Specifies a list of characters to include in the font. If set to 'auto', will be automatically generated from the data set.\n * @default (ASCII characters 32-128)\n */\n characterSet?: FontSettings['characterSet'] | 'auto';\n /** CSS font family\n * @default 'Monaco, monospace'\n */\n fontFamily?: FontSettings['fontFamily'];\n /** CSS font weight\n * @default 'normal'\n */\n fontWeight?: FontSettings['fontWeight'];\n /** A unitless number that will be multiplied with the current text size to set the line height.\n * @default 'normal'\n */\n lineHeight?: number;\n /**\n * Width of outline around the text, relative to the text size. Only effective if `fontSettings.sdf` is `true`.\n * @default 0\n */\n outlineWidth?: number;\n /**\n * Color of outline around the text, in `[r, g, b, [a]]`. Each channel is a number between 0-255 and `a` is 255 if not supplied.\n * @default [0, 0, 0, 255]\n */\n outlineColor?: Color;\n /**\n * Advance options for fine tuning the appearance and performance of the generated shared `fontAtlas`.\n */\n fontSettings?: FontSettings;\n /**\n * Available options are `break-all` and `break-word`. A valid `maxWidth` has to be provided to use `wordBreak`.\n * @default 'break-word'\n */\n wordBreak?: 'break-word' | 'break-all';\n /**\n * A unitless number that will be multiplied with the current text size to set the width limit of a string.\n * If specified, when the text is longer than the width limit, it will be wrapped into multiple lines using\n * the strategy of `wordBreak`.\n * @default -1\n */\n maxWidth?: number;\n /**\n * Label text accessor\n */\n getText?: AccessorFunction;\n /**\n * Anchor position accessor\n */\n getPosition?: Accessor;\n /**\n * Label color accessor\n * @default [0, 0, 0, 255]\n */\n getColor?: Accessor;\n /**\n * Label size accessor\n * @default 32\n */\n getSize?: Accessor;\n /**\n * Label rotation accessor, in degrees\n * @default 0\n */\n getAngle?: Accessor;\n /**\n * Horizontal alignment accessor\n * @default 'middle'\n */\n getTextAnchor?: Accessor;\n /**\n * Vertical alignment accessor\n * @default 'center'\n */\n getAlignmentBaseline?: Accessor;\n /**\n * Label offset from the anchor position, [x, y] in pixels\n * @default [0, 0]\n */\n getPixelOffset?: Accessor>;\n /**\n * @deprecated Use `background` and `getBackgroundColor` instead\n */\n backgroundColor?: Color;\n\n /** Container limits for each object, as meter offsets from the anchor position.\n * Characters that overflow the area are not displayed.\n * Use negative width/height to disable clipping.\n * @default [0, 0, -1, -1]\n */\n getContentBox?: Accessor;\n\n /**\n * Minimum visible region of the content box in screen pixels. If the visible width or height is smaller than the specified cutoff, the corresponding text is hidden completely.\n * This prop can be used to set the minimum length of clipped texts to improve readability.\n * @default [0, 0]\n */\n contentCutoffPixels?: [width: number, height: number];\n\n /**\n * Align the text horizontally to the visible region of the content box.\n * @default 'none'\n */\n contentAlignHorizontal?: ContentAlignModes;\n\n /**\n * Align the text vertically to the visible region of the content box.\n * @default 'none'\n */\n contentAlignVertical?: ContentAlignModes;\n\n /**\n * Experimental.\n * Custom font rendering methods.\n */\n _getFontRenderer?: (settings: Required) => FontRenderer;\n};\n\nexport type TextLayerProps = _TextLayerProps & LayerProps;\n\nconst defaultProps: DefaultProps = {\n billboard: true,\n sizeScale: 1,\n sizeUnits: 'pixels',\n sizeMinPixels: 0,\n sizeMaxPixels: Number.MAX_SAFE_INTEGER,\n\n background: false,\n getBackgroundColor: {type: 'accessor', value: [255, 255, 255, 255]},\n getBorderColor: {type: 'accessor', value: DEFAULT_COLOR},\n getBorderWidth: {type: 'accessor', value: 0},\n backgroundBorderRadius: {type: 'object', value: 0},\n backgroundPadding: {type: 'array', value: [0, 0, 0, 0]},\n\n characterSet: {type: 'object', value: DEFAULT_FONT_SETTINGS.characterSet},\n fontFamily: DEFAULT_FONT_SETTINGS.fontFamily,\n fontWeight: DEFAULT_FONT_SETTINGS.fontWeight,\n lineHeight: DEFAULT_LINE_HEIGHT,\n outlineWidth: {type: 'number', value: 0, min: 0},\n outlineColor: {type: 'color', value: DEFAULT_COLOR},\n fontSettings: {type: 'object', value: {}, compare: 1},\n\n // auto wrapping options\n wordBreak: 'break-word',\n maxWidth: {type: 'number', value: -1},\n contentCutoffPixels: {type: 'array', value: [0, 0]},\n contentAlignHorizontal: 'none',\n contentAlignVertical: 'none',\n\n getText: {type: 'accessor', value: (x: any) => x.text},\n getPosition: {type: 'accessor', value: (x: any) => x.position},\n getColor: {type: 'accessor', value: DEFAULT_COLOR},\n getSize: {type: 'accessor', value: 32},\n getAngle: {type: 'accessor', value: 0},\n getTextAnchor: {type: 'accessor', value: 'middle'},\n getAlignmentBaseline: {type: 'accessor', value: 'center'},\n getPixelOffset: {type: 'accessor', value: [0, 0]},\n getContentBox: {type: 'accessor', value: [0, 0, -1, -1]},\n\n // deprecated\n backgroundColor: {deprecatedFor: ['background', 'getBackgroundColor']}\n};\n\n/** Render text labels at given coordinates. */\nexport default class TextLayer extends CompositeLayer<\n ExtraPropsT & Required<_TextLayerProps>\n> {\n static defaultProps = defaultProps;\n static layerName = 'TextLayer';\n\n state!: {\n styleVersion: number;\n fontAtlasManager: FontAtlasManager;\n characterSet?: Set;\n startIndices?: number[];\n numInstances?: number;\n getText?: AccessorFunction;\n };\n\n initializeState() {\n this.state = {\n styleVersion: 0,\n fontAtlasManager: new FontAtlasManager()\n };\n\n // Breaking change in v8.9\n if (this.props.maxWidth > 0) {\n log.once(1, 'v8.9 breaking change: TextLayer maxWidth is now relative to text size')();\n }\n }\n\n // eslint-disable-next-line complexity\n updateState(params: UpdateParameters) {\n const {props, oldProps, changeFlags} = params;\n const textChanged =\n changeFlags.dataChanged ||\n (changeFlags.updateTriggersChanged &&\n (changeFlags.updateTriggersChanged.all || changeFlags.updateTriggersChanged.getText));\n\n if (textChanged) {\n this._updateText();\n }\n\n const fontChanged = this._updateFontAtlas();\n\n const styleChanged =\n fontChanged ||\n props.lineHeight !== oldProps.lineHeight ||\n props.wordBreak !== oldProps.wordBreak ||\n props.maxWidth !== oldProps.maxWidth;\n\n if (styleChanged) {\n this.setState({\n styleVersion: this.state.styleVersion + 1\n });\n }\n }\n\n getPickingInfo({info}: GetPickingInfoParams): PickingInfo {\n // because `TextLayer` assign the same pickingInfoIndex for one text label,\n // here info.index refers the index of text label in props.data\n info.object = info.index >= 0 ? (this.props.data as any[])[info.index] : null;\n return info;\n }\n\n /** Returns true if font has changed */\n private _updateFontAtlas(): boolean {\n const {fontSettings, fontFamily, fontWeight, _getFontRenderer} = this.props;\n const {fontAtlasManager, characterSet} = this.state;\n\n const fontProps = {\n ...fontSettings,\n characterSet,\n fontFamily,\n fontWeight,\n _getFontRenderer\n };\n\n if (!fontAtlasManager.mapping) {\n // This is the first update\n fontAtlasManager.setProps(fontProps);\n return true;\n }\n\n for (const key in fontProps) {\n if (fontProps[key] !== fontAtlasManager.props[key]) {\n fontAtlasManager.setProps(fontProps);\n return true;\n }\n }\n\n return false;\n }\n\n // Text strings are variable width objects\n // Count characters and start offsets\n private _updateText() {\n const {data, characterSet} = this.props;\n const textBuffer = (data as any).attributes?.getText;\n let {getText} = this.props;\n let startIndices: number[] = (data as any).startIndices;\n let numInstances: number;\n\n const autoCharacterSet = characterSet === 'auto' && new Set();\n\n if (textBuffer && startIndices) {\n const {texts, characterCount} = getTextFromBuffer({\n ...(ArrayBuffer.isView(textBuffer) ? {value: textBuffer} : textBuffer),\n // @ts-ignore if data.attribute is defined then length is expected\n length: data.length,\n startIndices,\n characterSet: autoCharacterSet\n });\n numInstances = characterCount;\n getText = (_, {index}) => texts[index];\n } else {\n const {iterable, objectInfo} = createIterable(data);\n startIndices = [0];\n numInstances = 0;\n\n for (const object of iterable) {\n objectInfo.index++;\n // Break into an array of characters\n // When dealing with double-length unicode characters, `str.length` or `str[i]` do not work\n const text = Array.from(getText(object, objectInfo) || '');\n if (autoCharacterSet) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n text.forEach(autoCharacterSet.add, autoCharacterSet);\n }\n numInstances += text.length;\n startIndices.push(numInstances);\n }\n }\n\n this.setState({\n getText,\n startIndices,\n numInstances,\n characterSet: autoCharacterSet || characterSet\n });\n }\n\n /** There are two size systems in this layer:\n\n + Pixel size: user-specified text size, via getSize, sizeScale, sizeUnits etc.\n The layer roughly matches the output of the layer to CSS pixels, e.g. getSize: 12, sizeScale: 2\n in layer props is roughly equivalent to font-size: 24px in CSS.\n + Texture size: internally, character positions in a text blob are calculated using the sizes of iconMapping,\n which depends on how large each character is drawn into the font atlas. This is controlled by\n fontSettings.fontSize (default 64) and most users do not set it manually.\n These numbers are intended to be used in the vertex shader and never to be exposed to the end user.\n\n All surfaces exposed to the user should either use the pixel size or a multiplier relative to the pixel size. */\n\n /** Calculate the size and position of each character in a text string.\n * Values are in texture size */\n private transformParagraph(\n object: DataT,\n objectInfo: AccessorContext\n ): ReturnType {\n const {fontAtlasManager} = this.state;\n const iconMapping = fontAtlasManager.mapping!;\n const {baselineOffset} = fontAtlasManager.atlas!;\n const {fontSize} = fontAtlasManager.props;\n const getText = this.state.getText!;\n const {wordBreak, lineHeight, maxWidth} = this.props;\n\n const paragraph = getText(object, objectInfo) || '';\n return transformParagraph(\n paragraph,\n baselineOffset,\n lineHeight * fontSize,\n wordBreak,\n maxWidth * fontSize,\n iconMapping\n );\n }\n\n /** Returns the x, y, width, height of each text string, relative to pixel size.\n * Used to render the background.\n */\n private getBoundingRect: AccessorFunction = (\n object,\n objectInfo\n ) => {\n const {\n size: [width, height]\n } = this.transformParagraph(object, objectInfo);\n\n const {getTextAnchor, getAlignmentBaseline} = this.props;\n const anchorX =\n TEXT_ANCHOR[\n typeof getTextAnchor === 'function' ? getTextAnchor(object, objectInfo) : getTextAnchor\n ];\n const anchorY =\n ALIGNMENT_BASELINE[\n typeof getAlignmentBaseline === 'function'\n ? getAlignmentBaseline(object, objectInfo)\n : getAlignmentBaseline\n ];\n\n return [((anchorX - 1) * width) / 2, ((anchorY - 1) * height) / 2, width, height];\n };\n\n /** Returns the x, y offsets of each character in a text string, in texture size.\n * Used to layout characters in the vertex shader.\n */\n private getIconOffsets: AccessorFunction = (object, objectInfo) => {\n const {getTextAnchor, getAlignmentBaseline} = this.props;\n\n const {\n x,\n y,\n rowWidth,\n size: [, height]\n } = this.transformParagraph(object, objectInfo);\n const anchorX =\n TEXT_ANCHOR[\n typeof getTextAnchor === 'function' ? getTextAnchor(object, objectInfo) : getTextAnchor\n ];\n const anchorY =\n ALIGNMENT_BASELINE[\n typeof getAlignmentBaseline === 'function'\n ? getAlignmentBaseline(object, objectInfo)\n : getAlignmentBaseline\n ];\n\n const numCharacters = x.length;\n const offsets = new Array(numCharacters * 2);\n let index = 0;\n\n for (let i = 0; i < numCharacters; i++) {\n // For a multi-line object, offset in x-direction needs consider\n // the row offset in the paragraph and the object offset in the row\n offsets[index++] = ((anchorX - 1) * rowWidth[i]) / 2 + x[i];\n offsets[index++] = ((anchorY - 1) * height) / 2 + y[i];\n }\n return offsets;\n };\n\n renderLayers() {\n const {\n startIndices,\n numInstances,\n getText,\n fontAtlasManager: {atlas, mapping},\n styleVersion\n } = this.state;\n\n const {\n data,\n _dataDiff,\n getPosition,\n getColor,\n getSize,\n getAngle,\n getPixelOffset,\n getBackgroundColor,\n getBorderColor,\n getBorderWidth,\n getContentBox,\n backgroundBorderRadius,\n backgroundPadding,\n background,\n billboard,\n fontSettings,\n outlineWidth,\n outlineColor,\n sizeScale,\n sizeUnits,\n sizeMinPixels,\n sizeMaxPixels,\n contentCutoffPixels,\n contentAlignHorizontal,\n contentAlignVertical,\n transitions,\n updateTriggers\n } = this.props;\n\n const CharactersLayerClass = this.getSubLayerClass('characters', MultiIconLayer);\n const BackgroundLayerClass = this.getSubLayerClass('background', TextBackgroundLayer);\n const {fontSize} = this.state.fontAtlasManager.props;\n\n return [\n background &&\n new BackgroundLayerClass(\n {\n // background props\n getFillColor: getBackgroundColor,\n getLineColor: getBorderColor,\n getLineWidth: getBorderWidth,\n borderRadius: backgroundBorderRadius,\n padding: backgroundPadding,\n\n // props shared with characters layer\n getPosition,\n getSize,\n getAngle,\n getPixelOffset,\n getClipRect: getContentBox,\n billboard,\n sizeScale,\n sizeUnits,\n sizeMinPixels,\n sizeMaxPixels,\n fontSize,\n\n transitions: transitions && {\n getPosition: transitions.getPosition,\n getAngle: transitions.getAngle,\n getSize: transitions.getSize,\n getFillColor: transitions.getBackgroundColor,\n getLineColor: transitions.getBorderColor,\n getLineWidth: transitions.getBorderWidth,\n getPixelOffset: transitions.getPixelOffset\n }\n },\n this.getSubLayerProps({\n id: 'background',\n updateTriggers: {\n getPosition: updateTriggers.getPosition,\n getAngle: updateTriggers.getAngle,\n getSize: updateTriggers.getSize,\n getFillColor: updateTriggers.getBackgroundColor,\n getLineColor: updateTriggers.getBorderColor,\n getLineWidth: updateTriggers.getBorderWidth,\n getPixelOffset: updateTriggers.getPixelOffset,\n getBoundingRect: {\n getText: updateTriggers.getText,\n getTextAnchor: updateTriggers.getTextAnchor,\n getAlignmentBaseline: updateTriggers.getAlignmentBaseline,\n styleVersion\n }\n }\n }),\n {\n data:\n // @ts-ignore (2339) attribute is not defined on all data types\n data.attributes && data.attributes.background\n ? // @ts-ignore (2339) attribute is not defined on all data types\n {length: data.length, attributes: data.attributes.background}\n : data,\n _dataDiff,\n // Maintain the same background behavior as <=8.3. Remove in v9?\n autoHighlight: false,\n getBoundingRect: this.getBoundingRect\n }\n ),\n new CharactersLayerClass(\n {\n sdf: fontSettings.sdf,\n smoothing: Number.isFinite(fontSettings.smoothing)\n ? fontSettings.smoothing\n : DEFAULT_FONT_SETTINGS.smoothing,\n outlineWidth: outlineWidth / (fontSettings.radius || DEFAULT_FONT_SETTINGS.radius),\n outlineColor,\n iconAtlas: atlas,\n iconMapping: mapping,\n\n getPosition,\n getColor,\n getSize,\n getAngle,\n getPixelOffset,\n getContentBox,\n\n billboard,\n sizeScale,\n sizeUnits,\n sizeMinPixels,\n sizeMaxPixels,\n fontSize,\n contentCutoffPixels,\n contentAlignHorizontal,\n contentAlignVertical,\n\n transitions: transitions && {\n getPosition: transitions.getPosition,\n getAngle: transitions.getAngle,\n getColor: transitions.getColor,\n getSize: transitions.getSize,\n getPixelOffset: transitions.getPixelOffset,\n getContentBox: transitions.getContentBox\n }\n },\n this.getSubLayerProps({\n id: 'characters',\n updateTriggers: {\n all: updateTriggers.getText,\n getPosition: updateTriggers.getPosition,\n getAngle: updateTriggers.getAngle,\n getColor: updateTriggers.getColor,\n getSize: updateTriggers.getSize,\n getPixelOffset: updateTriggers.getPixelOffset,\n getContentBox: updateTriggers.getContentBox,\n getIconOffsets: {\n getTextAnchor: updateTriggers.getTextAnchor,\n getAlignmentBaseline: updateTriggers.getAlignmentBaseline,\n styleVersion\n }\n }\n }),\n {\n data,\n _dataDiff,\n startIndices,\n numInstances,\n getIconOffsets: this.getIconOffsets,\n getIcon: getText\n }\n )\n ];\n }\n\n static set fontAtlasCacheLimit(limit: number) {\n setFontAtlasCacheLimit(limit);\n }\n}\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport type FlowmapData = {\n locations: Iterable | undefined;\n flows: Iterable | undefined;\n clusterLevels?: ClusterLevels;\n};\n\nexport interface ViewState {\n latitude: number;\n longitude: number;\n zoom: number;\n bearing?: number;\n pitch?: number;\n altitude?: number;\n}\n\nexport type FlowAccessor = (flow: F) => T; // objectInfo?: AccessorObjectInfo,\nexport type LocationAccessor = (location: L) => T;\nexport type FlowLinesRenderingMode =\n | 'straight'\n | 'animated-straight'\n | 'curved';\n\nexport interface FlowAccessors {\n getFlowOriginId: FlowAccessor;\n getFlowDestId: FlowAccessor;\n getFlowMagnitude: FlowAccessor;\n getFlowTime?: FlowAccessor; // TODO: use number instead of Date\n // getFlowColor?: FlowAccessor;\n}\n\nexport interface LocationAccessors {\n getLocationId: LocationAccessor;\n getLocationName?: LocationAccessor;\n getLocationLat: LocationAccessor;\n getLocationLon: LocationAccessor;\n getLocationClusterName?: (locationIds: (string | number)[]) => string;\n // getLocationTotalIn?: LocationAccessor;\n // getLocationTotalOut?: LocationAccessor;\n // getLocationTotalInternal?: LocationAccessor;\n}\n\nexport type FlowmapDataAccessors = LocationAccessors &\n FlowAccessors;\n\nexport interface LocationTotals {\n incomingCount: number;\n outgoingCount: number;\n internalCount: number;\n}\n\n// export interface LocationsTotals {\n// incoming: {[id: string]: number};\n// outgoing: {[id: string]: number};\n// internal: {[id: string]: number};\n// }\n\nexport interface CountByTime {\n time: Date;\n count: number;\n}\n\nexport interface ViewportProps {\n width: number;\n height: number;\n latitude: number;\n longitude: number;\n zoom?: number;\n bearing?: number;\n pitch?: number;\n altitude?: number;\n maxZoom?: number;\n minZoom?: number;\n maxPitch?: number;\n minPitch?: number;\n transitionDuration?: number | 'auto';\n transitionInterpolator?: any;\n transitionInterruption?: any;\n transitionEasing?: any;\n}\n\nexport interface ClusterNode {\n id: string | number;\n zoom: number;\n lat: number;\n lon: number;\n}\n\nexport interface ClusterLevel {\n zoom: number;\n nodes: ClusterNode[];\n}\n\nexport type ClusterLevels = ClusterLevel[];\n\n// non-leaf cluster node\nexport interface Cluster extends ClusterNode {\n name?: string;\n children: string[];\n}\n\nexport function isCluster(c: ClusterNode): c is Cluster {\n const {children} = c as Cluster;\n return children && children.length > 0;\n}\n\nexport function isLocationClusterNode(l: L | ClusterNode): l is ClusterNode {\n const {zoom} = l as ClusterNode;\n return zoom !== undefined;\n}\n\nexport interface AggregateFlow {\n origin: string | number;\n dest: string | number;\n count: number;\n aggregate: true;\n}\n\nexport function isAggregateFlow(\n flow: Record,\n): flow is AggregateFlow {\n return (\n flow &&\n // flow.origin !== undefined &&\n // flow.dest !== undefined &&\n // flow.count !== undefined &&\n (flow.aggregate ? true : false)\n );\n}\n\nexport interface FlowCountsMapReduce {\n map: (flow: F) => T;\n reduce: (accumulated: T, val: T) => T;\n}\n\nexport enum LocationFilterMode {\n ALL = 'ALL',\n INCOMING = 'INCOMING',\n OUTGOING = 'OUTGOING',\n BETWEEN = 'BETWEEN',\n}\n\nexport interface FlowCirclesLayerAttributes {\n length: number;\n attributes: {\n getPosition: LayersDataAttrValues;\n getColor: LayersDataAttrValues;\n getInRadius: LayersDataAttrValues;\n getOutRadius: LayersDataAttrValues;\n };\n}\n\nexport interface FlowLinesLayerAttributes {\n length: number;\n attributes: {\n getSourcePosition: LayersDataAttrValues;\n getTargetPosition: LayersDataAttrValues;\n getThickness: LayersDataAttrValues;\n getColor: LayersDataAttrValues;\n getEndpointOffsets: LayersDataAttrValues;\n getStaggering?: LayersDataAttrValues;\n getCurveOffset?: LayersDataAttrValues;\n };\n}\n\nexport interface LayersData {\n circleAttributes: FlowCirclesLayerAttributes;\n lineAttributes: FlowLinesLayerAttributes;\n locationLabels?: string[];\n}\n\nexport type LayersDataAttrValues = {value: T; size: number};\n","export default function(specifier) {\n var n = specifier.length / 6 | 0, colors = new Array(n), i = 0;\n while (i < n) colors[i] = \"#\" + specifier.slice(i * 6, ++i * 6);\n return colors;\n}\n","export default function(constructor, factory, prototype) {\n constructor.prototype = factory.prototype = prototype;\n prototype.constructor = constructor;\n}\n\nexport function extend(parent, definition) {\n var prototype = Object.create(parent.prototype);\n for (var key in definition) prototype[key] = definition[key];\n return prototype;\n}\n","import define, {extend} from \"./define.js\";\n\nexport function Color() {}\n\nexport var darker = 0.7;\nexport var brighter = 1 / darker;\n\nvar reI = \"\\\\s*([+-]?\\\\d+)\\\\s*\",\n reN = \"\\\\s*([+-]?(?:\\\\d*\\\\.)?\\\\d+(?:[eE][+-]?\\\\d+)?)\\\\s*\",\n reP = \"\\\\s*([+-]?(?:\\\\d*\\\\.)?\\\\d+(?:[eE][+-]?\\\\d+)?)%\\\\s*\",\n reHex = /^#([0-9a-f]{3,8})$/,\n reRgbInteger = new RegExp(`^rgb\\\\(${reI},${reI},${reI}\\\\)$`),\n reRgbPercent = new RegExp(`^rgb\\\\(${reP},${reP},${reP}\\\\)$`),\n reRgbaInteger = new RegExp(`^rgba\\\\(${reI},${reI},${reI},${reN}\\\\)$`),\n reRgbaPercent = new RegExp(`^rgba\\\\(${reP},${reP},${reP},${reN}\\\\)$`),\n reHslPercent = new RegExp(`^hsl\\\\(${reN},${reP},${reP}\\\\)$`),\n reHslaPercent = new RegExp(`^hsla\\\\(${reN},${reP},${reP},${reN}\\\\)$`);\n\nvar named = {\n aliceblue: 0xf0f8ff,\n antiquewhite: 0xfaebd7,\n aqua: 0x00ffff,\n aquamarine: 0x7fffd4,\n azure: 0xf0ffff,\n beige: 0xf5f5dc,\n bisque: 0xffe4c4,\n black: 0x000000,\n blanchedalmond: 0xffebcd,\n blue: 0x0000ff,\n blueviolet: 0x8a2be2,\n brown: 0xa52a2a,\n burlywood: 0xdeb887,\n cadetblue: 0x5f9ea0,\n chartreuse: 0x7fff00,\n chocolate: 0xd2691e,\n coral: 0xff7f50,\n cornflowerblue: 0x6495ed,\n cornsilk: 0xfff8dc,\n crimson: 0xdc143c,\n cyan: 0x00ffff,\n darkblue: 0x00008b,\n darkcyan: 0x008b8b,\n darkgoldenrod: 0xb8860b,\n darkgray: 0xa9a9a9,\n darkgreen: 0x006400,\n darkgrey: 0xa9a9a9,\n darkkhaki: 0xbdb76b,\n darkmagenta: 0x8b008b,\n darkolivegreen: 0x556b2f,\n darkorange: 0xff8c00,\n darkorchid: 0x9932cc,\n darkred: 0x8b0000,\n darksalmon: 0xe9967a,\n darkseagreen: 0x8fbc8f,\n darkslateblue: 0x483d8b,\n darkslategray: 0x2f4f4f,\n darkslategrey: 0x2f4f4f,\n darkturquoise: 0x00ced1,\n darkviolet: 0x9400d3,\n deeppink: 0xff1493,\n deepskyblue: 0x00bfff,\n dimgray: 0x696969,\n dimgrey: 0x696969,\n dodgerblue: 0x1e90ff,\n firebrick: 0xb22222,\n floralwhite: 0xfffaf0,\n forestgreen: 0x228b22,\n fuchsia: 0xff00ff,\n gainsboro: 0xdcdcdc,\n ghostwhite: 0xf8f8ff,\n gold: 0xffd700,\n goldenrod: 0xdaa520,\n gray: 0x808080,\n green: 0x008000,\n greenyellow: 0xadff2f,\n grey: 0x808080,\n honeydew: 0xf0fff0,\n hotpink: 0xff69b4,\n indianred: 0xcd5c5c,\n indigo: 0x4b0082,\n ivory: 0xfffff0,\n khaki: 0xf0e68c,\n lavender: 0xe6e6fa,\n lavenderblush: 0xfff0f5,\n lawngreen: 0x7cfc00,\n lemonchiffon: 0xfffacd,\n lightblue: 0xadd8e6,\n lightcoral: 0xf08080,\n lightcyan: 0xe0ffff,\n lightgoldenrodyellow: 0xfafad2,\n lightgray: 0xd3d3d3,\n lightgreen: 0x90ee90,\n lightgrey: 0xd3d3d3,\n lightpink: 0xffb6c1,\n lightsalmon: 0xffa07a,\n lightseagreen: 0x20b2aa,\n lightskyblue: 0x87cefa,\n lightslategray: 0x778899,\n lightslategrey: 0x778899,\n lightsteelblue: 0xb0c4de,\n lightyellow: 0xffffe0,\n lime: 0x00ff00,\n limegreen: 0x32cd32,\n linen: 0xfaf0e6,\n magenta: 0xff00ff,\n maroon: 0x800000,\n mediumaquamarine: 0x66cdaa,\n mediumblue: 0x0000cd,\n mediumorchid: 0xba55d3,\n mediumpurple: 0x9370db,\n mediumseagreen: 0x3cb371,\n mediumslateblue: 0x7b68ee,\n mediumspringgreen: 0x00fa9a,\n mediumturquoise: 0x48d1cc,\n mediumvioletred: 0xc71585,\n midnightblue: 0x191970,\n mintcream: 0xf5fffa,\n mistyrose: 0xffe4e1,\n moccasin: 0xffe4b5,\n navajowhite: 0xffdead,\n navy: 0x000080,\n oldlace: 0xfdf5e6,\n olive: 0x808000,\n olivedrab: 0x6b8e23,\n orange: 0xffa500,\n orangered: 0xff4500,\n orchid: 0xda70d6,\n palegoldenrod: 0xeee8aa,\n palegreen: 0x98fb98,\n paleturquoise: 0xafeeee,\n palevioletred: 0xdb7093,\n papayawhip: 0xffefd5,\n peachpuff: 0xffdab9,\n peru: 0xcd853f,\n pink: 0xffc0cb,\n plum: 0xdda0dd,\n powderblue: 0xb0e0e6,\n purple: 0x800080,\n rebeccapurple: 0x663399,\n red: 0xff0000,\n rosybrown: 0xbc8f8f,\n royalblue: 0x4169e1,\n saddlebrown: 0x8b4513,\n salmon: 0xfa8072,\n sandybrown: 0xf4a460,\n seagreen: 0x2e8b57,\n seashell: 0xfff5ee,\n sienna: 0xa0522d,\n silver: 0xc0c0c0,\n skyblue: 0x87ceeb,\n slateblue: 0x6a5acd,\n slategray: 0x708090,\n slategrey: 0x708090,\n snow: 0xfffafa,\n springgreen: 0x00ff7f,\n steelblue: 0x4682b4,\n tan: 0xd2b48c,\n teal: 0x008080,\n thistle: 0xd8bfd8,\n tomato: 0xff6347,\n turquoise: 0x40e0d0,\n violet: 0xee82ee,\n wheat: 0xf5deb3,\n white: 0xffffff,\n whitesmoke: 0xf5f5f5,\n yellow: 0xffff00,\n yellowgreen: 0x9acd32\n};\n\ndefine(Color, color, {\n copy(channels) {\n return Object.assign(new this.constructor, this, channels);\n },\n displayable() {\n return this.rgb().displayable();\n },\n hex: color_formatHex, // Deprecated! Use color.formatHex.\n formatHex: color_formatHex,\n formatHex8: color_formatHex8,\n formatHsl: color_formatHsl,\n formatRgb: color_formatRgb,\n toString: color_formatRgb\n});\n\nfunction color_formatHex() {\n return this.rgb().formatHex();\n}\n\nfunction color_formatHex8() {\n return this.rgb().formatHex8();\n}\n\nfunction color_formatHsl() {\n return hslConvert(this).formatHsl();\n}\n\nfunction color_formatRgb() {\n return this.rgb().formatRgb();\n}\n\nexport default function color(format) {\n var m, l;\n format = (format + \"\").trim().toLowerCase();\n return (m = reHex.exec(format)) ? (l = m[1].length, m = parseInt(m[1], 16), l === 6 ? rgbn(m) // #ff0000\n : l === 3 ? new Rgb((m >> 8 & 0xf) | (m >> 4 & 0xf0), (m >> 4 & 0xf) | (m & 0xf0), ((m & 0xf) << 4) | (m & 0xf), 1) // #f00\n : l === 8 ? rgba(m >> 24 & 0xff, m >> 16 & 0xff, m >> 8 & 0xff, (m & 0xff) / 0xff) // #ff000000\n : l === 4 ? rgba((m >> 12 & 0xf) | (m >> 8 & 0xf0), (m >> 8 & 0xf) | (m >> 4 & 0xf0), (m >> 4 & 0xf) | (m & 0xf0), (((m & 0xf) << 4) | (m & 0xf)) / 0xff) // #f000\n : null) // invalid hex\n : (m = reRgbInteger.exec(format)) ? new Rgb(m[1], m[2], m[3], 1) // rgb(255, 0, 0)\n : (m = reRgbPercent.exec(format)) ? new Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) // rgb(100%, 0%, 0%)\n : (m = reRgbaInteger.exec(format)) ? rgba(m[1], m[2], m[3], m[4]) // rgba(255, 0, 0, 1)\n : (m = reRgbaPercent.exec(format)) ? rgba(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) // rgb(100%, 0%, 0%, 1)\n : (m = reHslPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, 1) // hsl(120, 50%, 50%)\n : (m = reHslaPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, m[4]) // hsla(120, 50%, 50%, 1)\n : named.hasOwnProperty(format) ? rgbn(named[format]) // eslint-disable-line no-prototype-builtins\n : format === \"transparent\" ? new Rgb(NaN, NaN, NaN, 0)\n : null;\n}\n\nfunction rgbn(n) {\n return new Rgb(n >> 16 & 0xff, n >> 8 & 0xff, n & 0xff, 1);\n}\n\nfunction rgba(r, g, b, a) {\n if (a <= 0) r = g = b = NaN;\n return new Rgb(r, g, b, a);\n}\n\nexport function rgbConvert(o) {\n if (!(o instanceof Color)) o = color(o);\n if (!o) return new Rgb;\n o = o.rgb();\n return new Rgb(o.r, o.g, o.b, o.opacity);\n}\n\nexport function rgb(r, g, b, opacity) {\n return arguments.length === 1 ? rgbConvert(r) : new Rgb(r, g, b, opacity == null ? 1 : opacity);\n}\n\nexport function Rgb(r, g, b, opacity) {\n this.r = +r;\n this.g = +g;\n this.b = +b;\n this.opacity = +opacity;\n}\n\ndefine(Rgb, rgb, extend(Color, {\n brighter(k) {\n k = k == null ? brighter : Math.pow(brighter, k);\n return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);\n },\n darker(k) {\n k = k == null ? darker : Math.pow(darker, k);\n return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);\n },\n rgb() {\n return this;\n },\n clamp() {\n return new Rgb(clampi(this.r), clampi(this.g), clampi(this.b), clampa(this.opacity));\n },\n displayable() {\n return (-0.5 <= this.r && this.r < 255.5)\n && (-0.5 <= this.g && this.g < 255.5)\n && (-0.5 <= this.b && this.b < 255.5)\n && (0 <= this.opacity && this.opacity <= 1);\n },\n hex: rgb_formatHex, // Deprecated! Use color.formatHex.\n formatHex: rgb_formatHex,\n formatHex8: rgb_formatHex8,\n formatRgb: rgb_formatRgb,\n toString: rgb_formatRgb\n}));\n\nfunction rgb_formatHex() {\n return `#${hex(this.r)}${hex(this.g)}${hex(this.b)}`;\n}\n\nfunction rgb_formatHex8() {\n return `#${hex(this.r)}${hex(this.g)}${hex(this.b)}${hex((isNaN(this.opacity) ? 1 : this.opacity) * 255)}`;\n}\n\nfunction rgb_formatRgb() {\n const a = clampa(this.opacity);\n return `${a === 1 ? \"rgb(\" : \"rgba(\"}${clampi(this.r)}, ${clampi(this.g)}, ${clampi(this.b)}${a === 1 ? \")\" : `, ${a})`}`;\n}\n\nfunction clampa(opacity) {\n return isNaN(opacity) ? 1 : Math.max(0, Math.min(1, opacity));\n}\n\nfunction clampi(value) {\n return Math.max(0, Math.min(255, Math.round(value) || 0));\n}\n\nfunction hex(value) {\n value = clampi(value);\n return (value < 16 ? \"0\" : \"\") + value.toString(16);\n}\n\nfunction hsla(h, s, l, a) {\n if (a <= 0) h = s = l = NaN;\n else if (l <= 0 || l >= 1) h = s = NaN;\n else if (s <= 0) h = NaN;\n return new Hsl(h, s, l, a);\n}\n\nexport function hslConvert(o) {\n if (o instanceof Hsl) return new Hsl(o.h, o.s, o.l, o.opacity);\n if (!(o instanceof Color)) o = color(o);\n if (!o) return new Hsl;\n if (o instanceof Hsl) return o;\n o = o.rgb();\n var r = o.r / 255,\n g = o.g / 255,\n b = o.b / 255,\n min = Math.min(r, g, b),\n max = Math.max(r, g, b),\n h = NaN,\n s = max - min,\n l = (max + min) / 2;\n if (s) {\n if (r === max) h = (g - b) / s + (g < b) * 6;\n else if (g === max) h = (b - r) / s + 2;\n else h = (r - g) / s + 4;\n s /= l < 0.5 ? max + min : 2 - max - min;\n h *= 60;\n } else {\n s = l > 0 && l < 1 ? 0 : h;\n }\n return new Hsl(h, s, l, o.opacity);\n}\n\nexport function hsl(h, s, l, opacity) {\n return arguments.length === 1 ? hslConvert(h) : new Hsl(h, s, l, opacity == null ? 1 : opacity);\n}\n\nfunction Hsl(h, s, l, opacity) {\n this.h = +h;\n this.s = +s;\n this.l = +l;\n this.opacity = +opacity;\n}\n\ndefine(Hsl, hsl, extend(Color, {\n brighter(k) {\n k = k == null ? brighter : Math.pow(brighter, k);\n return new Hsl(this.h, this.s, this.l * k, this.opacity);\n },\n darker(k) {\n k = k == null ? darker : Math.pow(darker, k);\n return new Hsl(this.h, this.s, this.l * k, this.opacity);\n },\n rgb() {\n var h = this.h % 360 + (this.h < 0) * 360,\n s = isNaN(h) || isNaN(this.s) ? 0 : this.s,\n l = this.l,\n m2 = l + (l < 0.5 ? l : 1 - l) * s,\n m1 = 2 * l - m2;\n return new Rgb(\n hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2),\n hsl2rgb(h, m1, m2),\n hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2),\n this.opacity\n );\n },\n clamp() {\n return new Hsl(clamph(this.h), clampt(this.s), clampt(this.l), clampa(this.opacity));\n },\n displayable() {\n return (0 <= this.s && this.s <= 1 || isNaN(this.s))\n && (0 <= this.l && this.l <= 1)\n && (0 <= this.opacity && this.opacity <= 1);\n },\n formatHsl() {\n const a = clampa(this.opacity);\n return `${a === 1 ? \"hsl(\" : \"hsla(\"}${clamph(this.h)}, ${clampt(this.s) * 100}%, ${clampt(this.l) * 100}%${a === 1 ? \")\" : `, ${a})`}`;\n }\n}));\n\nfunction clamph(value) {\n value = (value || 0) % 360;\n return value < 0 ? value + 360 : value;\n}\n\nfunction clampt(value) {\n return Math.max(0, Math.min(1, value || 0));\n}\n\n/* From FvD 13.37, CSS Color Module Level 3 */\nfunction hsl2rgb(h, m1, m2) {\n return (h < 60 ? m1 + (m2 - m1) * h / 60\n : h < 180 ? m2\n : h < 240 ? m1 + (m2 - m1) * (240 - h) / 60\n : m1) * 255;\n}\n","export const radians = Math.PI / 180;\nexport const degrees = 180 / Math.PI;\n","import define, {extend} from \"./define.js\";\nimport {Color, rgbConvert, Rgb} from \"./color.js\";\nimport {degrees, radians} from \"./math.js\";\n\n// https://observablehq.com/@mbostock/lab-and-rgb\nconst K = 18,\n Xn = 0.96422,\n Yn = 1,\n Zn = 0.82521,\n t0 = 4 / 29,\n t1 = 6 / 29,\n t2 = 3 * t1 * t1,\n t3 = t1 * t1 * t1;\n\nfunction labConvert(o) {\n if (o instanceof Lab) return new Lab(o.l, o.a, o.b, o.opacity);\n if (o instanceof Hcl) return hcl2lab(o);\n if (!(o instanceof Rgb)) o = rgbConvert(o);\n var r = rgb2lrgb(o.r),\n g = rgb2lrgb(o.g),\n b = rgb2lrgb(o.b),\n y = xyz2lab((0.2225045 * r + 0.7168786 * g + 0.0606169 * b) / Yn), x, z;\n if (r === g && g === b) x = z = y; else {\n x = xyz2lab((0.4360747 * r + 0.3850649 * g + 0.1430804 * b) / Xn);\n z = xyz2lab((0.0139322 * r + 0.0971045 * g + 0.7141733 * b) / Zn);\n }\n return new Lab(116 * y - 16, 500 * (x - y), 200 * (y - z), o.opacity);\n}\n\nexport function gray(l, opacity) {\n return new Lab(l, 0, 0, opacity == null ? 1 : opacity);\n}\n\nexport default function lab(l, a, b, opacity) {\n return arguments.length === 1 ? labConvert(l) : new Lab(l, a, b, opacity == null ? 1 : opacity);\n}\n\nexport function Lab(l, a, b, opacity) {\n this.l = +l;\n this.a = +a;\n this.b = +b;\n this.opacity = +opacity;\n}\n\ndefine(Lab, lab, extend(Color, {\n brighter(k) {\n return new Lab(this.l + K * (k == null ? 1 : k), this.a, this.b, this.opacity);\n },\n darker(k) {\n return new Lab(this.l - K * (k == null ? 1 : k), this.a, this.b, this.opacity);\n },\n rgb() {\n var y = (this.l + 16) / 116,\n x = isNaN(this.a) ? y : y + this.a / 500,\n z = isNaN(this.b) ? y : y - this.b / 200;\n x = Xn * lab2xyz(x);\n y = Yn * lab2xyz(y);\n z = Zn * lab2xyz(z);\n return new Rgb(\n lrgb2rgb( 3.1338561 * x - 1.6168667 * y - 0.4906146 * z),\n lrgb2rgb(-0.9787684 * x + 1.9161415 * y + 0.0334540 * z),\n lrgb2rgb( 0.0719453 * x - 0.2289914 * y + 1.4052427 * z),\n this.opacity\n );\n }\n}));\n\nfunction xyz2lab(t) {\n return t > t3 ? Math.pow(t, 1 / 3) : t / t2 + t0;\n}\n\nfunction lab2xyz(t) {\n return t > t1 ? t * t * t : t2 * (t - t0);\n}\n\nfunction lrgb2rgb(x) {\n return 255 * (x <= 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055);\n}\n\nfunction rgb2lrgb(x) {\n return (x /= 255) <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);\n}\n\nfunction hclConvert(o) {\n if (o instanceof Hcl) return new Hcl(o.h, o.c, o.l, o.opacity);\n if (!(o instanceof Lab)) o = labConvert(o);\n if (o.a === 0 && o.b === 0) return new Hcl(NaN, 0 < o.l && o.l < 100 ? 0 : NaN, o.l, o.opacity);\n var h = Math.atan2(o.b, o.a) * degrees;\n return new Hcl(h < 0 ? h + 360 : h, Math.sqrt(o.a * o.a + o.b * o.b), o.l, o.opacity);\n}\n\nexport function lch(l, c, h, opacity) {\n return arguments.length === 1 ? hclConvert(l) : new Hcl(h, c, l, opacity == null ? 1 : opacity);\n}\n\nexport function hcl(h, c, l, opacity) {\n return arguments.length === 1 ? hclConvert(h) : new Hcl(h, c, l, opacity == null ? 1 : opacity);\n}\n\nexport function Hcl(h, c, l, opacity) {\n this.h = +h;\n this.c = +c;\n this.l = +l;\n this.opacity = +opacity;\n}\n\nfunction hcl2lab(o) {\n if (isNaN(o.h)) return new Lab(o.l, 0, 0, o.opacity);\n var h = o.h * radians;\n return new Lab(o.l, Math.cos(h) * o.c, Math.sin(h) * o.c, o.opacity);\n}\n\ndefine(Hcl, hcl, extend(Color, {\n brighter(k) {\n return new Hcl(this.h, this.c, this.l + K * (k == null ? 1 : k), this.opacity);\n },\n darker(k) {\n return new Hcl(this.h, this.c, this.l - K * (k == null ? 1 : k), this.opacity);\n },\n rgb() {\n return hcl2lab(this).rgb();\n }\n}));\n","import define, {extend} from \"./define.js\";\nimport {Color, rgbConvert, Rgb, darker, brighter} from \"./color.js\";\nimport {degrees, radians} from \"./math.js\";\n\nvar A = -0.14861,\n B = +1.78277,\n C = -0.29227,\n D = -0.90649,\n E = +1.97294,\n ED = E * D,\n EB = E * B,\n BC_DA = B * C - D * A;\n\nfunction cubehelixConvert(o) {\n if (o instanceof Cubehelix) return new Cubehelix(o.h, o.s, o.l, o.opacity);\n if (!(o instanceof Rgb)) o = rgbConvert(o);\n var r = o.r / 255,\n g = o.g / 255,\n b = o.b / 255,\n l = (BC_DA * b + ED * r - EB * g) / (BC_DA + ED - EB),\n bl = b - l,\n k = (E * (g - l) - C * bl) / D,\n s = Math.sqrt(k * k + bl * bl) / (E * l * (1 - l)), // NaN if l=0 or l=1\n h = s ? Math.atan2(k, bl) * degrees - 120 : NaN;\n return new Cubehelix(h < 0 ? h + 360 : h, s, l, o.opacity);\n}\n\nexport default function cubehelix(h, s, l, opacity) {\n return arguments.length === 1 ? cubehelixConvert(h) : new Cubehelix(h, s, l, opacity == null ? 1 : opacity);\n}\n\nexport function Cubehelix(h, s, l, opacity) {\n this.h = +h;\n this.s = +s;\n this.l = +l;\n this.opacity = +opacity;\n}\n\ndefine(Cubehelix, cubehelix, extend(Color, {\n brighter(k) {\n k = k == null ? brighter : Math.pow(brighter, k);\n return new Cubehelix(this.h, this.s, this.l * k, this.opacity);\n },\n darker(k) {\n k = k == null ? darker : Math.pow(darker, k);\n return new Cubehelix(this.h, this.s, this.l * k, this.opacity);\n },\n rgb() {\n var h = isNaN(this.h) ? 0 : (this.h + 120) * radians,\n l = +this.l,\n a = isNaN(this.s) ? 0 : this.s * l * (1 - l),\n cosh = Math.cos(h),\n sinh = Math.sin(h);\n return new Rgb(\n 255 * (l + a * (A * cosh + B * sinh)),\n 255 * (l + a * (C * cosh + D * sinh)),\n 255 * (l + a * (E * cosh)),\n this.opacity\n );\n }\n}));\n","export function basis(t1, v0, v1, v2, v3) {\n var t2 = t1 * t1, t3 = t2 * t1;\n return ((1 - 3 * t1 + 3 * t2 - t3) * v0\n + (4 - 6 * t2 + 3 * t3) * v1\n + (1 + 3 * t1 + 3 * t2 - 3 * t3) * v2\n + t3 * v3) / 6;\n}\n\nexport default function(values) {\n var n = values.length - 1;\n return function(t) {\n var i = t <= 0 ? (t = 0) : t >= 1 ? (t = 1, n - 1) : Math.floor(t * n),\n v1 = values[i],\n v2 = values[i + 1],\n v0 = i > 0 ? values[i - 1] : 2 * v1 - v2,\n v3 = i < n - 1 ? values[i + 2] : 2 * v2 - v1;\n return basis((t - i / n) * n, v0, v1, v2, v3);\n };\n}\n","import {basis} from \"./basis.js\";\n\nexport default function(values) {\n var n = values.length;\n return function(t) {\n var i = Math.floor(((t %= 1) < 0 ? ++t : t) * n),\n v0 = values[(i + n - 1) % n],\n v1 = values[i % n],\n v2 = values[(i + 1) % n],\n v3 = values[(i + 2) % n];\n return basis((t - i / n) * n, v0, v1, v2, v3);\n };\n}\n","export default x => () => x;\n","import constant from \"./constant.js\";\n\nfunction linear(a, d) {\n return function(t) {\n return a + t * d;\n };\n}\n\nfunction exponential(a, b, y) {\n return a = Math.pow(a, y), b = Math.pow(b, y) - a, y = 1 / y, function(t) {\n return Math.pow(a + t * b, y);\n };\n}\n\nexport function hue(a, b) {\n var d = b - a;\n return d ? linear(a, d > 180 || d < -180 ? d - 360 * Math.round(d / 360) : d) : constant(isNaN(a) ? b : a);\n}\n\nexport function gamma(y) {\n return (y = +y) === 1 ? nogamma : function(a, b) {\n return b - a ? exponential(a, b, y) : constant(isNaN(a) ? b : a);\n };\n}\n\nexport default function nogamma(a, b) {\n var d = b - a;\n return d ? linear(a, d) : constant(isNaN(a) ? b : a);\n}\n","import {rgb as colorRgb} from \"d3-color\";\nimport basis from \"./basis.js\";\nimport basisClosed from \"./basisClosed.js\";\nimport nogamma, {gamma} from \"./color.js\";\n\nexport default (function rgbGamma(y) {\n var color = gamma(y);\n\n function rgb(start, end) {\n var r = color((start = colorRgb(start)).r, (end = colorRgb(end)).r),\n g = color(start.g, end.g),\n b = color(start.b, end.b),\n opacity = nogamma(start.opacity, end.opacity);\n return function(t) {\n start.r = r(t);\n start.g = g(t);\n start.b = b(t);\n start.opacity = opacity(t);\n return start + \"\";\n };\n }\n\n rgb.gamma = rgbGamma;\n\n return rgb;\n})(1);\n\nfunction rgbSpline(spline) {\n return function(colors) {\n var n = colors.length,\n r = new Array(n),\n g = new Array(n),\n b = new Array(n),\n i, color;\n for (i = 0; i < n; ++i) {\n color = colorRgb(colors[i]);\n r[i] = color.r || 0;\n g[i] = color.g || 0;\n b[i] = color.b || 0;\n }\n r = spline(r);\n g = spline(g);\n b = spline(b);\n color.opacity = 1;\n return function(t) {\n color.r = r(t);\n color.g = g(t);\n color.b = b(t);\n return color + \"\";\n };\n };\n}\n\nexport var rgbBasis = rgbSpline(basis);\nexport var rgbBasisClosed = rgbSpline(basisClosed);\n","export default function(a, b) {\n if (!b) b = [];\n var n = a ? Math.min(b.length, a.length) : 0,\n c = b.slice(),\n i;\n return function(t) {\n for (i = 0; i < n; ++i) c[i] = a[i] * (1 - t) + b[i] * t;\n return c;\n };\n}\n\nexport function isNumberArray(x) {\n return ArrayBuffer.isView(x) && !(x instanceof DataView);\n}\n","import value from \"./value.js\";\nimport numberArray, {isNumberArray} from \"./numberArray.js\";\n\nexport default function(a, b) {\n return (isNumberArray(b) ? numberArray : genericArray)(a, b);\n}\n\nexport function genericArray(a, b) {\n var nb = b ? b.length : 0,\n na = a ? Math.min(nb, a.length) : 0,\n x = new Array(na),\n c = new Array(nb),\n i;\n\n for (i = 0; i < na; ++i) x[i] = value(a[i], b[i]);\n for (; i < nb; ++i) c[i] = b[i];\n\n return function(t) {\n for (i = 0; i < na; ++i) c[i] = x[i](t);\n return c;\n };\n}\n","export default function(a, b) {\n var d = new Date;\n return a = +a, b = +b, function(t) {\n return d.setTime(a * (1 - t) + b * t), d;\n };\n}\n","export default function(a, b) {\n return a = +a, b = +b, function(t) {\n return a * (1 - t) + b * t;\n };\n}\n","import value from \"./value.js\";\n\nexport default function(a, b) {\n var i = {},\n c = {},\n k;\n\n if (a === null || typeof a !== \"object\") a = {};\n if (b === null || typeof b !== \"object\") b = {};\n\n for (k in b) {\n if (k in a) {\n i[k] = value(a[k], b[k]);\n } else {\n c[k] = b[k];\n }\n }\n\n return function(t) {\n for (k in i) c[k] = i[k](t);\n return c;\n };\n}\n","import number from \"./number.js\";\n\nvar reA = /[-+]?(?:\\d+\\.?\\d*|\\.?\\d+)(?:[eE][-+]?\\d+)?/g,\n reB = new RegExp(reA.source, \"g\");\n\nfunction zero(b) {\n return function() {\n return b;\n };\n}\n\nfunction one(b) {\n return function(t) {\n return b(t) + \"\";\n };\n}\n\nexport default function(a, b) {\n var bi = reA.lastIndex = reB.lastIndex = 0, // scan index for next number in b\n am, // current match in a\n bm, // current match in b\n bs, // string preceding current number in b, if any\n i = -1, // index in s\n s = [], // string constants and placeholders\n q = []; // number interpolators\n\n // Coerce inputs to strings.\n a = a + \"\", b = b + \"\";\n\n // Interpolate pairs of numbers in a & b.\n while ((am = reA.exec(a))\n && (bm = reB.exec(b))) {\n if ((bs = bm.index) > bi) { // a string precedes the next number in b\n bs = b.slice(bi, bs);\n if (s[i]) s[i] += bs; // coalesce with previous string\n else s[++i] = bs;\n }\n if ((am = am[0]) === (bm = bm[0])) { // numbers in a & b match\n if (s[i]) s[i] += bm; // coalesce with previous string\n else s[++i] = bm;\n } else { // interpolate non-matching numbers\n s[++i] = null;\n q.push({i: i, x: number(am, bm)});\n }\n bi = reB.lastIndex;\n }\n\n // Add remains of b.\n if (bi < b.length) {\n bs = b.slice(bi);\n if (s[i]) s[i] += bs; // coalesce with previous string\n else s[++i] = bs;\n }\n\n // Special optimization for only a single match.\n // Otherwise, interpolate each of the numbers and rejoin the string.\n return s.length < 2 ? (q[0]\n ? one(q[0].x)\n : zero(b))\n : (b = q.length, function(t) {\n for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t);\n return s.join(\"\");\n });\n}\n","import {color} from \"d3-color\";\nimport rgb from \"./rgb.js\";\nimport {genericArray} from \"./array.js\";\nimport date from \"./date.js\";\nimport number from \"./number.js\";\nimport object from \"./object.js\";\nimport string from \"./string.js\";\nimport constant from \"./constant.js\";\nimport numberArray, {isNumberArray} from \"./numberArray.js\";\n\nexport default function(a, b) {\n var t = typeof b, c;\n return b == null || t === \"boolean\" ? constant(b)\n : (t === \"number\" ? number\n : t === \"string\" ? ((c = color(b)) ? (b = c, rgb) : string)\n : b instanceof color ? rgb\n : b instanceof Date ? date\n : isNumberArray(b) ? numberArray\n : Array.isArray(b) ? genericArray\n : typeof b.valueOf !== \"function\" && typeof b.toString !== \"function\" || isNaN(b) ? object\n : number)(a, b);\n}\n","export default function(a, b) {\n return a = +a, b = +b, function(t) {\n return Math.round(a * (1 - t) + b * t);\n };\n}\n","import {cubehelix as colorCubehelix} from \"d3-color\";\nimport color, {hue} from \"./color.js\";\n\nfunction cubehelix(hue) {\n return (function cubehelixGamma(y) {\n y = +y;\n\n function cubehelix(start, end) {\n var h = hue((start = colorCubehelix(start)).h, (end = colorCubehelix(end)).h),\n s = color(start.s, end.s),\n l = color(start.l, end.l),\n opacity = color(start.opacity, end.opacity);\n return function(t) {\n start.h = h(t);\n start.s = s(t);\n start.l = l(Math.pow(t, y));\n start.opacity = opacity(t);\n return start + \"\";\n };\n }\n\n cubehelix.gamma = cubehelixGamma;\n\n return cubehelix;\n })(1);\n}\n\nexport default cubehelix(hue);\nexport var cubehelixLong = cubehelix(color);\n","import {interpolateRgbBasis} from \"d3-interpolate\";\n\nexport default scheme => interpolateRgbBasis(scheme[scheme.length - 1]);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"e5f5f999d8c92ca25f\",\n \"edf8fbb2e2e266c2a4238b45\",\n \"edf8fbb2e2e266c2a42ca25f006d2c\",\n \"edf8fbccece699d8c966c2a42ca25f006d2c\",\n \"edf8fbccece699d8c966c2a441ae76238b45005824\",\n \"f7fcfde5f5f9ccece699d8c966c2a441ae76238b45005824\",\n \"f7fcfde5f5f9ccece699d8c966c2a441ae76238b45006d2c00441b\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"e0ecf49ebcda8856a7\",\n \"edf8fbb3cde38c96c688419d\",\n \"edf8fbb3cde38c96c68856a7810f7c\",\n \"edf8fbbfd3e69ebcda8c96c68856a7810f7c\",\n \"edf8fbbfd3e69ebcda8c96c68c6bb188419d6e016b\",\n \"f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d6e016b\",\n \"f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d810f7c4d004b\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"e0f3dba8ddb543a2ca\",\n \"f0f9e8bae4bc7bccc42b8cbe\",\n \"f0f9e8bae4bc7bccc443a2ca0868ac\",\n \"f0f9e8ccebc5a8ddb57bccc443a2ca0868ac\",\n \"f0f9e8ccebc5a8ddb57bccc44eb3d32b8cbe08589e\",\n \"f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe08589e\",\n \"f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe0868ac084081\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"fee8c8fdbb84e34a33\",\n \"fef0d9fdcc8afc8d59d7301f\",\n \"fef0d9fdcc8afc8d59e34a33b30000\",\n \"fef0d9fdd49efdbb84fc8d59e34a33b30000\",\n \"fef0d9fdd49efdbb84fc8d59ef6548d7301f990000\",\n \"fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301f990000\",\n \"fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301fb300007f0000\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"ece2f0a6bddb1c9099\",\n \"f6eff7bdc9e167a9cf02818a\",\n \"f6eff7bdc9e167a9cf1c9099016c59\",\n \"f6eff7d0d1e6a6bddb67a9cf1c9099016c59\",\n \"f6eff7d0d1e6a6bddb67a9cf3690c002818a016450\",\n \"fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016450\",\n \"fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016c59014636\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"ece7f2a6bddb2b8cbe\",\n \"f1eef6bdc9e174a9cf0570b0\",\n \"f1eef6bdc9e174a9cf2b8cbe045a8d\",\n \"f1eef6d0d1e6a6bddb74a9cf2b8cbe045a8d\",\n \"f1eef6d0d1e6a6bddb74a9cf3690c00570b0034e7b\",\n \"fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0034e7b\",\n \"fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0045a8d023858\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"e7e1efc994c7dd1c77\",\n \"f1eef6d7b5d8df65b0ce1256\",\n \"f1eef6d7b5d8df65b0dd1c77980043\",\n \"f1eef6d4b9dac994c7df65b0dd1c77980043\",\n \"f1eef6d4b9dac994c7df65b0e7298ace125691003f\",\n \"f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125691003f\",\n \"f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125698004367001f\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"fde0ddfa9fb5c51b8a\",\n \"feebe2fbb4b9f768a1ae017e\",\n \"feebe2fbb4b9f768a1c51b8a7a0177\",\n \"feebe2fcc5c0fa9fb5f768a1c51b8a7a0177\",\n \"feebe2fcc5c0fa9fb5f768a1dd3497ae017e7a0177\",\n \"fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a0177\",\n \"fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a017749006a\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"edf8b17fcdbb2c7fb8\",\n \"ffffcca1dab441b6c4225ea8\",\n \"ffffcca1dab441b6c42c7fb8253494\",\n \"ffffccc7e9b47fcdbb41b6c42c7fb8253494\",\n \"ffffccc7e9b47fcdbb41b6c41d91c0225ea80c2c84\",\n \"ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea80c2c84\",\n \"ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea8253494081d58\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"f7fcb9addd8e31a354\",\n \"ffffccc2e69978c679238443\",\n \"ffffccc2e69978c67931a354006837\",\n \"ffffccd9f0a3addd8e78c67931a354006837\",\n \"ffffccd9f0a3addd8e78c67941ab5d238443005a32\",\n \"ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443005a32\",\n \"ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443006837004529\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"fff7bcfec44fd95f0e\",\n \"ffffd4fed98efe9929cc4c02\",\n \"ffffd4fed98efe9929d95f0e993404\",\n \"ffffd4fee391fec44ffe9929d95f0e993404\",\n \"ffffd4fee391fec44ffe9929ec7014cc4c028c2d04\",\n \"ffffe5fff7bcfee391fec44ffe9929ec7014cc4c028c2d04\",\n \"ffffe5fff7bcfee391fec44ffe9929ec7014cc4c02993404662506\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"ffeda0feb24cf03b20\",\n \"ffffb2fecc5cfd8d3ce31a1c\",\n \"ffffb2fecc5cfd8d3cf03b20bd0026\",\n \"ffffb2fed976feb24cfd8d3cf03b20bd0026\",\n \"ffffb2fed976feb24cfd8d3cfc4e2ae31a1cb10026\",\n \"ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cb10026\",\n \"ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cbd0026800026\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"deebf79ecae13182bd\",\n \"eff3ffbdd7e76baed62171b5\",\n \"eff3ffbdd7e76baed63182bd08519c\",\n \"eff3ffc6dbef9ecae16baed63182bd08519c\",\n \"eff3ffc6dbef9ecae16baed64292c62171b5084594\",\n \"f7fbffdeebf7c6dbef9ecae16baed64292c62171b5084594\",\n \"f7fbffdeebf7c6dbef9ecae16baed64292c62171b508519c08306b\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"e5f5e0a1d99b31a354\",\n \"edf8e9bae4b374c476238b45\",\n \"edf8e9bae4b374c47631a354006d2c\",\n \"edf8e9c7e9c0a1d99b74c47631a354006d2c\",\n \"edf8e9c7e9c0a1d99b74c47641ab5d238b45005a32\",\n \"f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45005a32\",\n \"f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45006d2c00441b\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"f0f0f0bdbdbd636363\",\n \"f7f7f7cccccc969696525252\",\n \"f7f7f7cccccc969696636363252525\",\n \"f7f7f7d9d9d9bdbdbd969696636363252525\",\n \"f7f7f7d9d9d9bdbdbd969696737373525252252525\",\n \"fffffff0f0f0d9d9d9bdbdbd969696737373525252252525\",\n \"fffffff0f0f0d9d9d9bdbdbd969696737373525252252525000000\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"efedf5bcbddc756bb1\",\n \"f2f0f7cbc9e29e9ac86a51a3\",\n \"f2f0f7cbc9e29e9ac8756bb154278f\",\n \"f2f0f7dadaebbcbddc9e9ac8756bb154278f\",\n \"f2f0f7dadaebbcbddc9e9ac8807dba6a51a34a1486\",\n \"fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a34a1486\",\n \"fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a354278f3f007d\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"fee0d2fc9272de2d26\",\n \"fee5d9fcae91fb6a4acb181d\",\n \"fee5d9fcae91fb6a4ade2d26a50f15\",\n \"fee5d9fcbba1fc9272fb6a4ade2d26a50f15\",\n \"fee5d9fcbba1fc9272fb6a4aef3b2ccb181d99000d\",\n \"fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181d99000d\",\n \"fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181da50f1567000d\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"fee6cefdae6be6550d\",\n \"feeddefdbe85fd8d3cd94701\",\n \"feeddefdbe85fd8d3ce6550da63603\",\n \"feeddefdd0a2fdae6bfd8d3ce6550da63603\",\n \"feeddefdd0a2fdae6bfd8d3cf16913d948018c2d04\",\n \"fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d948018c2d04\",\n \"fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d94801a636037f2704\"\n).map(colors);\n\nexport default ramp(scheme);\n","import {cubehelix} from \"d3-color\";\nimport {interpolateCubehelixLong} from \"d3-interpolate\";\n\nexport var warm = interpolateCubehelixLong(cubehelix(-100, 0.75, 0.35), cubehelix(80, 1.50, 0.8));\n\nexport var cool = interpolateCubehelixLong(cubehelix(260, 0.75, 0.35), cubehelix(80, 1.50, 0.8));\n\nvar c = cubehelix();\n\nexport default function(t) {\n if (t < 0 || t > 1) t -= Math.floor(t);\n var ts = Math.abs(t - 0.5);\n c.h = 360 * t - 100;\n c.s = 1.5 - 1.5 * ts;\n c.l = 0.8 - 0.9 * ts;\n return c + \"\";\n}\n","import colors from \"../colors.js\";\n\nfunction ramp(range) {\n var n = range.length;\n return function(t) {\n return range[Math.max(0, Math.min(n - 1, Math.floor(t * n)))];\n };\n}\n\nexport default ramp(colors(\"44015444025645045745055946075a46085c460a5d460b5e470d60470e6147106347116447136548146748166848176948186a481a6c481b6d481c6e481d6f481f70482071482173482374482475482576482677482878482979472a7a472c7a472d7b472e7c472f7d46307e46327e46337f463480453581453781453882443983443a83443b84433d84433e85423f854240864241864142874144874045884046883f47883f48893e49893e4a893e4c8a3d4d8a3d4e8a3c4f8a3c508b3b518b3b528b3a538b3a548c39558c39568c38588c38598c375a8c375b8d365c8d365d8d355e8d355f8d34608d34618d33628d33638d32648e32658e31668e31678e31688e30698e306a8e2f6b8e2f6c8e2e6d8e2e6e8e2e6f8e2d708e2d718e2c718e2c728e2c738e2b748e2b758e2a768e2a778e2a788e29798e297a8e297b8e287c8e287d8e277e8e277f8e27808e26818e26828e26828e25838e25848e25858e24868e24878e23888e23898e238a8d228b8d228c8d228d8d218e8d218f8d21908d21918c20928c20928c20938c1f948c1f958b1f968b1f978b1f988b1f998a1f9a8a1e9b8a1e9c891e9d891f9e891f9f881fa0881fa1881fa1871fa28720a38620a48621a58521a68522a78522a88423a98324aa8325ab8225ac8226ad8127ad8128ae8029af7f2ab07f2cb17e2db27d2eb37c2fb47c31b57b32b67a34b67935b77937b87838b9773aba763bbb753dbc743fbc7340bd7242be7144bf7046c06f48c16e4ac16d4cc26c4ec36b50c46a52c56954c56856c66758c7655ac8645cc8635ec96260ca6063cb5f65cb5e67cc5c69cd5b6ccd5a6ece5870cf5773d05675d05477d1537ad1517cd2507fd34e81d34d84d44b86d54989d5488bd6468ed64590d74393d74195d84098d83e9bd93c9dd93ba0da39a2da37a5db36a8db34aadc32addc30b0dd2fb2dd2db5de2bb8de29bade28bddf26c0df25c2df23c5e021c8e020cae11fcde11dd0e11cd2e21bd5e21ad8e219dae319dde318dfe318e2e418e5e419e7e419eae51aece51befe51cf1e51df4e61ef6e620f8e621fbe723fde725\"));\n\nexport var magma = ramp(colors(\"00000401000501010601010802010902020b02020d03030f03031204041405041606051806051a07061c08071e0907200a08220b09240c09260d0a290e0b2b100b2d110c2f120d31130d34140e36150e38160f3b180f3d19103f1a10421c10441d11471e114920114b21114e22115024125325125527125829115a2a115c2c115f2d11612f116331116533106734106936106b38106c390f6e3b0f703d0f713f0f72400f74420f75440f764510774710784910784a10794c117a4e117b4f127b51127c52137c54137d56147d57157e59157e5a167e5c167f5d177f5f187f601880621980641a80651a80671b80681c816a1c816b1d816d1d816e1e81701f81721f817320817521817621817822817922827b23827c23827e24828025828125818326818426818627818827818928818b29818c29818e2a81902a81912b81932b80942c80962c80982d80992d809b2e7f9c2e7f9e2f7fa02f7fa1307ea3307ea5317ea6317da8327daa337dab337cad347cae347bb0357bb2357bb3367ab5367ab73779b83779ba3878bc3978bd3977bf3a77c03a76c23b75c43c75c53c74c73d73c83e73ca3e72cc3f71cd4071cf4070d0416fd2426fd3436ed5446dd6456cd8456cd9466bdb476adc4869de4968df4a68e04c67e24d66e34e65e44f64e55064e75263e85362e95462ea5661eb5760ec5860ed5a5fee5b5eef5d5ef05f5ef1605df2625df2645cf3655cf4675cf4695cf56b5cf66c5cf66e5cf7705cf7725cf8745cf8765cf9785df9795df97b5dfa7d5efa7f5efa815ffb835ffb8560fb8761fc8961fc8a62fc8c63fc8e64fc9065fd9266fd9467fd9668fd9869fd9a6afd9b6bfe9d6cfe9f6dfea16efea36ffea571fea772fea973feaa74feac76feae77feb078feb27afeb47bfeb67cfeb77efeb97ffebb81febd82febf84fec185fec287fec488fec68afec88cfeca8dfecc8ffecd90fecf92fed194fed395fed597fed799fed89afdda9cfddc9efddea0fde0a1fde2a3fde3a5fde5a7fde7a9fde9aafdebacfcecaefceeb0fcf0b2fcf2b4fcf4b6fcf6b8fcf7b9fcf9bbfcfbbdfcfdbf\"));\n\nexport var inferno = ramp(colors(\"00000401000501010601010802010a02020c02020e03021004031204031405041706041907051b08051d09061f0a07220b07240c08260d08290e092b10092d110a30120a32140b34150b37160b39180c3c190c3e1b0c411c0c431e0c451f0c48210c4a230c4c240c4f260c51280b53290b552b0b572d0b592f0a5b310a5c320a5e340a5f3609613809623909633b09643d09653e0966400a67420a68440a68450a69470b6a490b6a4a0c6b4c0c6b4d0d6c4f0d6c510e6c520e6d540f6d550f6d57106e59106e5a116e5c126e5d126e5f136e61136e62146e64156e65156e67166e69166e6a176e6c186e6d186e6f196e71196e721a6e741a6e751b6e771c6d781c6d7a1d6d7c1d6d7d1e6d7f1e6c801f6c82206c84206b85216b87216b88226a8a226a8c23698d23698f24699025689225689326679526679727669827669a28659b29649d29649f2a63a02a63a22b62a32c61a52c60a62d60a82e5fa92e5eab2f5ead305dae305cb0315bb1325ab3325ab43359b63458b73557b93556ba3655bc3754bd3853bf3952c03a51c13a50c33b4fc43c4ec63d4dc73e4cc83f4bca404acb4149cc4248ce4347cf4446d04545d24644d34743d44842d54a41d74b3fd84c3ed94d3dda4e3cdb503bdd513ade5238df5337e05536e15635e25734e35933e45a31e55c30e65d2fe75e2ee8602de9612bea632aeb6429eb6628ec6726ed6925ee6a24ef6c23ef6e21f06f20f1711ff1731df2741cf3761bf37819f47918f57b17f57d15f67e14f68013f78212f78410f8850ff8870ef8890cf98b0bf98c0af98e09fa9008fa9207fa9407fb9606fb9706fb9906fb9b06fb9d07fc9f07fca108fca309fca50afca60cfca80dfcaa0ffcac11fcae12fcb014fcb216fcb418fbb61afbb81dfbba1ffbbc21fbbe23fac026fac228fac42afac62df9c72ff9c932f9cb35f8cd37f8cf3af7d13df7d340f6d543f6d746f5d949f5db4cf4dd4ff4df53f4e156f3e35af3e55df2e661f2e865f2ea69f1ec6df1ed71f1ef75f1f179f2f27df2f482f3f586f3f68af4f88ef5f992f6fa96f8fb9af9fc9dfafda1fcffa4\"));\n\nexport var plasma = ramp(colors(\"0d088710078813078916078a19068c1b068d1d068e20068f2206902406912605912805922a05932c05942e05952f059631059733059735049837049938049a3a049a3c049b3e049c3f049c41049d43039e44039e46039f48039f4903a04b03a14c02a14e02a25002a25102a35302a35502a45601a45801a45901a55b01a55c01a65e01a66001a66100a76300a76400a76600a76700a86900a86a00a86c00a86e00a86f00a87100a87201a87401a87501a87701a87801a87a02a87b02a87d03a87e03a88004a88104a78305a78405a78606a68707a68808a68a09a58b0aa58d0ba58e0ca48f0da4910ea3920fa39410a29511a19613a19814a099159f9a169f9c179e9d189d9e199da01a9ca11b9ba21d9aa31e9aa51f99a62098a72197a82296aa2395ab2494ac2694ad2793ae2892b02991b12a90b22b8fb32c8eb42e8db52f8cb6308bb7318ab83289ba3388bb3488bc3587bd3786be3885bf3984c03a83c13b82c23c81c33d80c43e7fc5407ec6417dc7427cc8437bc9447aca457acb4679cc4778cc4977cd4a76ce4b75cf4c74d04d73d14e72d24f71d35171d45270d5536fd5546ed6556dd7566cd8576bd9586ada5a6ada5b69db5c68dc5d67dd5e66de5f65de6164df6263e06363e16462e26561e26660e3685fe4695ee56a5de56b5de66c5ce76e5be76f5ae87059e97158e97257ea7457eb7556eb7655ec7754ed7953ed7a52ee7b51ef7c51ef7e50f07f4ff0804ef1814df1834cf2844bf3854bf3874af48849f48948f58b47f58c46f68d45f68f44f79044f79143f79342f89441f89540f9973ff9983ef99a3efa9b3dfa9c3cfa9e3bfb9f3afba139fba238fca338fca537fca636fca835fca934fdab33fdac33fdae32fdaf31fdb130fdb22ffdb42ffdb52efeb72dfeb82cfeba2cfebb2bfebd2afebe2afec029fdc229fdc328fdc527fdc627fdc827fdca26fdcb26fccd25fcce25fcd025fcd225fbd324fbd524fbd724fad824fada24f9dc24f9dd25f8df25f8e125f7e225f7e425f6e626f6e826f5e926f5eb27f4ed27f3ee27f3f027f2f227f1f426f1f525f0f724f0f921\"));\n","export default function ascending(a, b) {\n return a == null || b == null ? NaN : a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;\n}\n","export default function descending(a, b) {\n return a == null || b == null ? NaN\n : b < a ? -1\n : b > a ? 1\n : b >= a ? 0\n : NaN;\n}\n","import ascending from \"./ascending.js\";\nimport descending from \"./descending.js\";\n\nexport default function bisector(f) {\n let compare1, compare2, delta;\n\n // If an accessor is specified, promote it to a comparator. In this case we\n // can test whether the search value is (self-) comparable. We can’t do this\n // for a comparator (except for specific, known comparators) because we can’t\n // tell if the comparator is symmetric, and an asymmetric comparator can’t be\n // used to test whether a single value is comparable.\n if (f.length !== 2) {\n compare1 = ascending;\n compare2 = (d, x) => ascending(f(d), x);\n delta = (d, x) => f(d) - x;\n } else {\n compare1 = f === ascending || f === descending ? f : zero;\n compare2 = f;\n delta = f;\n }\n\n function left(a, x, lo = 0, hi = a.length) {\n if (lo < hi) {\n if (compare1(x, x) !== 0) return hi;\n do {\n const mid = (lo + hi) >>> 1;\n if (compare2(a[mid], x) < 0) lo = mid + 1;\n else hi = mid;\n } while (lo < hi);\n }\n return lo;\n }\n\n function right(a, x, lo = 0, hi = a.length) {\n if (lo < hi) {\n if (compare1(x, x) !== 0) return hi;\n do {\n const mid = (lo + hi) >>> 1;\n if (compare2(a[mid], x) <= 0) lo = mid + 1;\n else hi = mid;\n } while (lo < hi);\n }\n return lo;\n }\n\n function center(a, x, lo = 0, hi = a.length) {\n const i = left(a, x, lo, hi - 1);\n return i > lo && delta(a[i - 1], x) > -delta(a[i], x) ? i - 1 : i;\n }\n\n return {left, center, right};\n}\n\nfunction zero() {\n return 0;\n}\n","export default function number(x) {\n return x === null ? NaN : +x;\n}\n\nexport function* numbers(values, valueof) {\n if (valueof === undefined) {\n for (let value of values) {\n if (value != null && (value = +value) >= value) {\n yield value;\n }\n }\n } else {\n let index = -1;\n for (let value of values) {\n if ((value = valueof(value, ++index, values)) != null && (value = +value) >= value) {\n yield value;\n }\n }\n }\n}\n","import ascending from \"./ascending.js\";\nimport bisector from \"./bisector.js\";\nimport number from \"./number.js\";\n\nconst ascendingBisect = bisector(ascending);\nexport const bisectRight = ascendingBisect.right;\nexport const bisectLeft = ascendingBisect.left;\nexport const bisectCenter = bisector(number).center;\nexport default bisectRight;\n","export default function extent(values, valueof) {\n let min;\n let max;\n if (valueof === undefined) {\n for (const value of values) {\n if (value != null) {\n if (min === undefined) {\n if (value >= value) min = max = value;\n } else {\n if (min > value) min = value;\n if (max < value) max = value;\n }\n }\n }\n } else {\n let index = -1;\n for (let value of values) {\n if ((value = valueof(value, ++index, values)) != null) {\n if (min === undefined) {\n if (value >= value) min = max = value;\n } else {\n if (min > value) min = value;\n if (max < value) max = value;\n }\n }\n }\n }\n return [min, max];\n}\n","// https://github.com/python/cpython/blob/a74eea238f5baba15797e2e8b570d153bc8690a7/Modules/mathmodule.c#L1423\nexport class Adder {\n constructor() {\n this._partials = new Float64Array(32);\n this._n = 0;\n }\n add(x) {\n const p = this._partials;\n let i = 0;\n for (let j = 0; j < this._n && j < 32; j++) {\n const y = p[j],\n hi = x + y,\n lo = Math.abs(x) < Math.abs(y) ? x - (hi - y) : y - (hi - x);\n if (lo) p[i++] = lo;\n x = hi;\n }\n p[i] = x;\n this._n = i + 1;\n return this;\n }\n valueOf() {\n const p = this._partials;\n let n = this._n, x, y, lo, hi = 0;\n if (n > 0) {\n hi = p[--n];\n while (n > 0) {\n x = hi;\n y = p[--n];\n hi = x + y;\n lo = y - (hi - x);\n if (lo) break;\n }\n if (n > 0 && ((lo < 0 && p[n - 1] < 0) || (lo > 0 && p[n - 1] > 0))) {\n y = lo * 2;\n x = hi + y;\n if (y == x - hi) hi = x;\n }\n }\n return hi;\n }\n}\n\nexport function fsum(values, valueof) {\n const adder = new Adder();\n if (valueof === undefined) {\n for (let value of values) {\n if (value = +value) {\n adder.add(value);\n }\n }\n } else {\n let index = -1;\n for (let value of values) {\n if (value = +valueof(value, ++index, values)) {\n adder.add(value);\n }\n }\n }\n return +adder;\n}\n\nexport function fcumsum(values, valueof) {\n const adder = new Adder();\n let index = -1;\n return Float64Array.from(values, valueof === undefined\n ? v => adder.add(+v || 0)\n : v => adder.add(+valueof(v, ++index, values) || 0)\n );\n}\n","export class InternMap extends Map {\n constructor(entries, key = keyof) {\n super();\n Object.defineProperties(this, {_intern: {value: new Map()}, _key: {value: key}});\n if (entries != null) for (const [key, value] of entries) this.set(key, value);\n }\n get(key) {\n return super.get(intern_get(this, key));\n }\n has(key) {\n return super.has(intern_get(this, key));\n }\n set(key, value) {\n return super.set(intern_set(this, key), value);\n }\n delete(key) {\n return super.delete(intern_delete(this, key));\n }\n}\n\nexport class InternSet extends Set {\n constructor(values, key = keyof) {\n super();\n Object.defineProperties(this, {_intern: {value: new Map()}, _key: {value: key}});\n if (values != null) for (const value of values) this.add(value);\n }\n has(value) {\n return super.has(intern_get(this, value));\n }\n add(value) {\n return super.add(intern_set(this, value));\n }\n delete(value) {\n return super.delete(intern_delete(this, value));\n }\n}\n\nfunction intern_get({_intern, _key}, value) {\n const key = _key(value);\n return _intern.has(key) ? _intern.get(key) : value;\n}\n\nfunction intern_set({_intern, _key}, value) {\n const key = _key(value);\n if (_intern.has(key)) return _intern.get(key);\n _intern.set(key, value);\n return value;\n}\n\nfunction intern_delete({_intern, _key}, value) {\n const key = _key(value);\n if (_intern.has(key)) {\n value = _intern.get(key);\n _intern.delete(key);\n }\n return value;\n}\n\nfunction keyof(value) {\n return value !== null && typeof value === \"object\" ? value.valueOf() : value;\n}\n","export default function identity(x) {\n return x;\n}\n","import {InternMap} from \"internmap\";\nimport identity from \"./identity.js\";\n\nexport default function group(values, ...keys) {\n return nest(values, identity, identity, keys);\n}\n\nexport function groups(values, ...keys) {\n return nest(values, Array.from, identity, keys);\n}\n\nfunction flatten(groups, keys) {\n for (let i = 1, n = keys.length; i < n; ++i) {\n groups = groups.flatMap(g => g.pop().map(([key, value]) => [...g, key, value]));\n }\n return groups;\n}\n\nexport function flatGroup(values, ...keys) {\n return flatten(groups(values, ...keys), keys);\n}\n\nexport function flatRollup(values, reduce, ...keys) {\n return flatten(rollups(values, reduce, ...keys), keys);\n}\n\nexport function rollup(values, reduce, ...keys) {\n return nest(values, identity, reduce, keys);\n}\n\nexport function rollups(values, reduce, ...keys) {\n return nest(values, Array.from, reduce, keys);\n}\n\nexport function index(values, ...keys) {\n return nest(values, identity, unique, keys);\n}\n\nexport function indexes(values, ...keys) {\n return nest(values, Array.from, unique, keys);\n}\n\nfunction unique(values) {\n if (values.length !== 1) throw new Error(\"duplicate key\");\n return values[0];\n}\n\nfunction nest(values, map, reduce, keys) {\n return (function regroup(values, i) {\n if (i >= keys.length) return reduce(values);\n const groups = new InternMap();\n const keyof = keys[i++];\n let index = -1;\n for (const value of values) {\n const key = keyof(value, ++index, values);\n const group = groups.get(key);\n if (group) group.push(value);\n else groups.set(key, [value]);\n }\n for (const [key, values] of groups) {\n groups.set(key, regroup(values, i));\n }\n return map(groups);\n })(values, 0);\n}\n","const e10 = Math.sqrt(50),\n e5 = Math.sqrt(10),\n e2 = Math.sqrt(2);\n\nfunction tickSpec(start, stop, count) {\n const step = (stop - start) / Math.max(0, count),\n power = Math.floor(Math.log10(step)),\n error = step / Math.pow(10, power),\n factor = error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1;\n let i1, i2, inc;\n if (power < 0) {\n inc = Math.pow(10, -power) / factor;\n i1 = Math.round(start * inc);\n i2 = Math.round(stop * inc);\n if (i1 / inc < start) ++i1;\n if (i2 / inc > stop) --i2;\n inc = -inc;\n } else {\n inc = Math.pow(10, power) * factor;\n i1 = Math.round(start / inc);\n i2 = Math.round(stop / inc);\n if (i1 * inc < start) ++i1;\n if (i2 * inc > stop) --i2;\n }\n if (i2 < i1 && 0.5 <= count && count < 2) return tickSpec(start, stop, count * 2);\n return [i1, i2, inc];\n}\n\nexport default function ticks(start, stop, count) {\n stop = +stop, start = +start, count = +count;\n if (!(count > 0)) return [];\n if (start === stop) return [start];\n const reverse = stop < start, [i1, i2, inc] = reverse ? tickSpec(stop, start, count) : tickSpec(start, stop, count);\n if (!(i2 >= i1)) return [];\n const n = i2 - i1 + 1, ticks = new Array(n);\n if (reverse) {\n if (inc < 0) for (let i = 0; i < n; ++i) ticks[i] = (i2 - i) / -inc;\n else for (let i = 0; i < n; ++i) ticks[i] = (i2 - i) * inc;\n } else {\n if (inc < 0) for (let i = 0; i < n; ++i) ticks[i] = (i1 + i) / -inc;\n else for (let i = 0; i < n; ++i) ticks[i] = (i1 + i) * inc;\n }\n return ticks;\n}\n\nexport function tickIncrement(start, stop, count) {\n stop = +stop, start = +start, count = +count;\n return tickSpec(start, stop, count)[2];\n}\n\nexport function tickStep(start, stop, count) {\n stop = +stop, start = +start, count = +count;\n const reverse = stop < start, inc = reverse ? tickIncrement(stop, start, count) : tickIncrement(start, stop, count);\n return (reverse ? -1 : 1) * (inc < 0 ? 1 / -inc : inc);\n}\n","export default function min(values, valueof) {\n let min;\n if (valueof === undefined) {\n for (const value of values) {\n if (value != null\n && (min > value || (min === undefined && value >= value))) {\n min = value;\n }\n }\n } else {\n let index = -1;\n for (let value of values) {\n if ((value = valueof(value, ++index, values)) != null\n && (min > value || (min === undefined && value >= value))) {\n min = value;\n }\n }\n }\n return min;\n}\n","export default function range(start, stop, step) {\n start = +start, stop = +stop, step = (n = arguments.length) < 2 ? (stop = start, start = 0, 1) : n < 3 ? 1 : +step;\n\n var i = -1,\n n = Math.max(0, Math.ceil((stop - start) / step)) | 0,\n range = new Array(n);\n\n while (++i < n) {\n range[i] = start + i * step;\n }\n\n return range;\n}\n","export function initRange(domain, range) {\n switch (arguments.length) {\n case 0: break;\n case 1: this.range(domain); break;\n default: this.range(range).domain(domain); break;\n }\n return this;\n}\n\nexport function initInterpolator(domain, interpolator) {\n switch (arguments.length) {\n case 0: break;\n case 1: {\n if (typeof domain === \"function\") this.interpolator(domain);\n else this.range(domain);\n break;\n }\n default: {\n this.domain(domain);\n if (typeof interpolator === \"function\") this.interpolator(interpolator);\n else this.range(interpolator);\n break;\n }\n }\n return this;\n}\n","export default function constants(x) {\n return function() {\n return x;\n };\n}\n","export default function number(x) {\n return +x;\n}\n","import {bisect} from \"d3-array\";\nimport {interpolate as interpolateValue, interpolateNumber, interpolateRound} from \"d3-interpolate\";\nimport constant from \"./constant.js\";\nimport number from \"./number.js\";\n\nvar unit = [0, 1];\n\nexport function identity(x) {\n return x;\n}\n\nfunction normalize(a, b) {\n return (b -= (a = +a))\n ? function(x) { return (x - a) / b; }\n : constant(isNaN(b) ? NaN : 0.5);\n}\n\nfunction clamper(a, b) {\n var t;\n if (a > b) t = a, a = b, b = t;\n return function(x) { return Math.max(a, Math.min(b, x)); };\n}\n\n// normalize(a, b)(x) takes a domain value x in [a,b] and returns the corresponding parameter t in [0,1].\n// interpolate(a, b)(t) takes a parameter t in [0,1] and returns the corresponding range value x in [a,b].\nfunction bimap(domain, range, interpolate) {\n var d0 = domain[0], d1 = domain[1], r0 = range[0], r1 = range[1];\n if (d1 < d0) d0 = normalize(d1, d0), r0 = interpolate(r1, r0);\n else d0 = normalize(d0, d1), r0 = interpolate(r0, r1);\n return function(x) { return r0(d0(x)); };\n}\n\nfunction polymap(domain, range, interpolate) {\n var j = Math.min(domain.length, range.length) - 1,\n d = new Array(j),\n r = new Array(j),\n i = -1;\n\n // Reverse descending domains.\n if (domain[j] < domain[0]) {\n domain = domain.slice().reverse();\n range = range.slice().reverse();\n }\n\n while (++i < j) {\n d[i] = normalize(domain[i], domain[i + 1]);\n r[i] = interpolate(range[i], range[i + 1]);\n }\n\n return function(x) {\n var i = bisect(domain, x, 1, j) - 1;\n return r[i](d[i](x));\n };\n}\n\nexport function copy(source, target) {\n return target\n .domain(source.domain())\n .range(source.range())\n .interpolate(source.interpolate())\n .clamp(source.clamp())\n .unknown(source.unknown());\n}\n\nexport function transformer() {\n var domain = unit,\n range = unit,\n interpolate = interpolateValue,\n transform,\n untransform,\n unknown,\n clamp = identity,\n piecewise,\n output,\n input;\n\n function rescale() {\n var n = Math.min(domain.length, range.length);\n if (clamp !== identity) clamp = clamper(domain[0], domain[n - 1]);\n piecewise = n > 2 ? polymap : bimap;\n output = input = null;\n return scale;\n }\n\n function scale(x) {\n return x == null || isNaN(x = +x) ? unknown : (output || (output = piecewise(domain.map(transform), range, interpolate)))(transform(clamp(x)));\n }\n\n scale.invert = function(y) {\n return clamp(untransform((input || (input = piecewise(range, domain.map(transform), interpolateNumber)))(y)));\n };\n\n scale.domain = function(_) {\n return arguments.length ? (domain = Array.from(_, number), rescale()) : domain.slice();\n };\n\n scale.range = function(_) {\n return arguments.length ? (range = Array.from(_), rescale()) : range.slice();\n };\n\n scale.rangeRound = function(_) {\n return range = Array.from(_), interpolate = interpolateRound, rescale();\n };\n\n scale.clamp = function(_) {\n return arguments.length ? (clamp = _ ? true : identity, rescale()) : clamp !== identity;\n };\n\n scale.interpolate = function(_) {\n return arguments.length ? (interpolate = _, rescale()) : interpolate;\n };\n\n scale.unknown = function(_) {\n return arguments.length ? (unknown = _, scale) : unknown;\n };\n\n return function(t, u) {\n transform = t, untransform = u;\n return rescale();\n };\n}\n\nexport default function continuous() {\n return transformer()(identity, identity);\n}\n","export default function(x) {\n return Math.abs(x = Math.round(x)) >= 1e21\n ? x.toLocaleString(\"en\").replace(/,/g, \"\")\n : x.toString(10);\n}\n\n// Computes the decimal coefficient and exponent of the specified number x with\n// significant digits p, where x is positive and p is in [1, 21] or undefined.\n// For example, formatDecimalParts(1.23) returns [\"123\", 0].\nexport function formatDecimalParts(x, p) {\n if (!isFinite(x) || x === 0) return null; // NaN, ±Infinity, ±0\n var i = (x = p ? x.toExponential(p - 1) : x.toExponential()).indexOf(\"e\"), coefficient = x.slice(0, i);\n\n // The string returned by toExponential either has the form \\d\\.\\d+e[-+]\\d+\n // (e.g., 1.2e+3) or the form \\de[-+]\\d+ (e.g., 1e+3).\n return [\n coefficient.length > 1 ? coefficient[0] + coefficient.slice(2) : coefficient,\n +x.slice(i + 1)\n ];\n}\n","import {formatDecimalParts} from \"./formatDecimal.js\";\n\nexport default function(x) {\n return x = formatDecimalParts(Math.abs(x)), x ? x[1] : NaN;\n}\n","export default function(grouping, thousands) {\n return function(value, width) {\n var i = value.length,\n t = [],\n j = 0,\n g = grouping[0],\n length = 0;\n\n while (i > 0 && g > 0) {\n if (length + g + 1 > width) g = Math.max(1, width - length);\n t.push(value.substring(i -= g, i + g));\n if ((length += g + 1) > width) break;\n g = grouping[j = (j + 1) % grouping.length];\n }\n\n return t.reverse().join(thousands);\n };\n}\n","export default function(numerals) {\n return function(value) {\n return value.replace(/[0-9]/g, function(i) {\n return numerals[+i];\n });\n };\n}\n","// [[fill]align][sign][symbol][0][width][,][.precision][~][type]\nvar re = /^(?:(.)?([<>=^]))?([+\\-( ])?([$#])?(0)?(\\d+)?(,)?(\\.\\d+)?(~)?([a-z%])?$/i;\n\nexport default function formatSpecifier(specifier) {\n if (!(match = re.exec(specifier))) throw new Error(\"invalid format: \" + specifier);\n var match;\n return new FormatSpecifier({\n fill: match[1],\n align: match[2],\n sign: match[3],\n symbol: match[4],\n zero: match[5],\n width: match[6],\n comma: match[7],\n precision: match[8] && match[8].slice(1),\n trim: match[9],\n type: match[10]\n });\n}\n\nformatSpecifier.prototype = FormatSpecifier.prototype; // instanceof\n\nexport function FormatSpecifier(specifier) {\n this.fill = specifier.fill === undefined ? \" \" : specifier.fill + \"\";\n this.align = specifier.align === undefined ? \">\" : specifier.align + \"\";\n this.sign = specifier.sign === undefined ? \"-\" : specifier.sign + \"\";\n this.symbol = specifier.symbol === undefined ? \"\" : specifier.symbol + \"\";\n this.zero = !!specifier.zero;\n this.width = specifier.width === undefined ? undefined : +specifier.width;\n this.comma = !!specifier.comma;\n this.precision = specifier.precision === undefined ? undefined : +specifier.precision;\n this.trim = !!specifier.trim;\n this.type = specifier.type === undefined ? \"\" : specifier.type + \"\";\n}\n\nFormatSpecifier.prototype.toString = function() {\n return this.fill\n + this.align\n + this.sign\n + this.symbol\n + (this.zero ? \"0\" : \"\")\n + (this.width === undefined ? \"\" : Math.max(1, this.width | 0))\n + (this.comma ? \",\" : \"\")\n + (this.precision === undefined ? \"\" : \".\" + Math.max(0, this.precision | 0))\n + (this.trim ? \"~\" : \"\")\n + this.type;\n};\n","// Trims insignificant zeros, e.g., replaces 1.2000k with 1.2k.\nexport default function(s) {\n out: for (var n = s.length, i = 1, i0 = -1, i1; i < n; ++i) {\n switch (s[i]) {\n case \".\": i0 = i1 = i; break;\n case \"0\": if (i0 === 0) i0 = i; i1 = i; break;\n default: if (!+s[i]) break out; if (i0 > 0) i0 = 0; break;\n }\n }\n return i0 > 0 ? s.slice(0, i0) + s.slice(i1 + 1) : s;\n}\n","import {formatDecimalParts} from \"./formatDecimal.js\";\n\nexport var prefixExponent;\n\nexport default function(x, p) {\n var d = formatDecimalParts(x, p);\n if (!d) return prefixExponent = undefined, x.toPrecision(p);\n var coefficient = d[0],\n exponent = d[1],\n i = exponent - (prefixExponent = Math.max(-8, Math.min(8, Math.floor(exponent / 3))) * 3) + 1,\n n = coefficient.length;\n return i === n ? coefficient\n : i > n ? coefficient + new Array(i - n + 1).join(\"0\")\n : i > 0 ? coefficient.slice(0, i) + \".\" + coefficient.slice(i)\n : \"0.\" + new Array(1 - i).join(\"0\") + formatDecimalParts(x, Math.max(0, p + i - 1))[0]; // less than 1y!\n}\n","import {formatDecimalParts} from \"./formatDecimal.js\";\n\nexport default function(x, p) {\n var d = formatDecimalParts(x, p);\n if (!d) return x + \"\";\n var coefficient = d[0],\n exponent = d[1];\n return exponent < 0 ? \"0.\" + new Array(-exponent).join(\"0\") + coefficient\n : coefficient.length > exponent + 1 ? coefficient.slice(0, exponent + 1) + \".\" + coefficient.slice(exponent + 1)\n : coefficient + new Array(exponent - coefficient.length + 2).join(\"0\");\n}\n","import formatDecimal from \"./formatDecimal.js\";\nimport formatPrefixAuto from \"./formatPrefixAuto.js\";\nimport formatRounded from \"./formatRounded.js\";\n\nexport default {\n \"%\": (x, p) => (x * 100).toFixed(p),\n \"b\": (x) => Math.round(x).toString(2),\n \"c\": (x) => x + \"\",\n \"d\": formatDecimal,\n \"e\": (x, p) => x.toExponential(p),\n \"f\": (x, p) => x.toFixed(p),\n \"g\": (x, p) => x.toPrecision(p),\n \"o\": (x) => Math.round(x).toString(8),\n \"p\": (x, p) => formatRounded(x * 100, p),\n \"r\": formatRounded,\n \"s\": formatPrefixAuto,\n \"X\": (x) => Math.round(x).toString(16).toUpperCase(),\n \"x\": (x) => Math.round(x).toString(16)\n};\n","export default function(x) {\n return x;\n}\n","import exponent from \"./exponent.js\";\nimport formatGroup from \"./formatGroup.js\";\nimport formatNumerals from \"./formatNumerals.js\";\nimport formatSpecifier from \"./formatSpecifier.js\";\nimport formatTrim from \"./formatTrim.js\";\nimport formatTypes from \"./formatTypes.js\";\nimport {prefixExponent} from \"./formatPrefixAuto.js\";\nimport identity from \"./identity.js\";\n\nvar map = Array.prototype.map,\n prefixes = [\"y\",\"z\",\"a\",\"f\",\"p\",\"n\",\"µ\",\"m\",\"\",\"k\",\"M\",\"G\",\"T\",\"P\",\"E\",\"Z\",\"Y\"];\n\nexport default function(locale) {\n var group = locale.grouping === undefined || locale.thousands === undefined ? identity : formatGroup(map.call(locale.grouping, Number), locale.thousands + \"\"),\n currencyPrefix = locale.currency === undefined ? \"\" : locale.currency[0] + \"\",\n currencySuffix = locale.currency === undefined ? \"\" : locale.currency[1] + \"\",\n decimal = locale.decimal === undefined ? \".\" : locale.decimal + \"\",\n numerals = locale.numerals === undefined ? identity : formatNumerals(map.call(locale.numerals, String)),\n percent = locale.percent === undefined ? \"%\" : locale.percent + \"\",\n minus = locale.minus === undefined ? \"−\" : locale.minus + \"\",\n nan = locale.nan === undefined ? \"NaN\" : locale.nan + \"\";\n\n function newFormat(specifier, options) {\n specifier = formatSpecifier(specifier);\n\n var fill = specifier.fill,\n align = specifier.align,\n sign = specifier.sign,\n symbol = specifier.symbol,\n zero = specifier.zero,\n width = specifier.width,\n comma = specifier.comma,\n precision = specifier.precision,\n trim = specifier.trim,\n type = specifier.type;\n\n // The \"n\" type is an alias for \",g\".\n if (type === \"n\") comma = true, type = \"g\";\n\n // The \"\" type, and any invalid type, is an alias for \".12~g\".\n else if (!formatTypes[type]) precision === undefined && (precision = 12), trim = true, type = \"g\";\n\n // If zero fill is specified, padding goes after sign and before digits.\n if (zero || (fill === \"0\" && align === \"=\")) zero = true, fill = \"0\", align = \"=\";\n\n // Compute the prefix and suffix.\n // For SI-prefix, the suffix is lazily computed.\n var prefix = (options && options.prefix !== undefined ? options.prefix : \"\") + (symbol === \"$\" ? currencyPrefix : symbol === \"#\" && /[boxX]/.test(type) ? \"0\" + type.toLowerCase() : \"\"),\n suffix = (symbol === \"$\" ? currencySuffix : /[%p]/.test(type) ? percent : \"\") + (options && options.suffix !== undefined ? options.suffix : \"\");\n\n // What format function should we use?\n // Is this an integer type?\n // Can this type generate exponential notation?\n var formatType = formatTypes[type],\n maybeSuffix = /[defgprs%]/.test(type);\n\n // Set the default precision if not specified,\n // or clamp the specified precision to the supported range.\n // For significant precision, it must be in [1, 21].\n // For fixed precision, it must be in [0, 20].\n precision = precision === undefined ? 6\n : /[gprs]/.test(type) ? Math.max(1, Math.min(21, precision))\n : Math.max(0, Math.min(20, precision));\n\n function format(value) {\n var valuePrefix = prefix,\n valueSuffix = suffix,\n i, n, c;\n\n if (type === \"c\") {\n valueSuffix = formatType(value) + valueSuffix;\n value = \"\";\n } else {\n value = +value;\n\n // Determine the sign. -0 is not less than 0, but 1 / -0 is!\n var valueNegative = value < 0 || 1 / value < 0;\n\n // Perform the initial formatting.\n value = isNaN(value) ? nan : formatType(Math.abs(value), precision);\n\n // Trim insignificant zeros.\n if (trim) value = formatTrim(value);\n\n // If a negative value rounds to zero after formatting, and no explicit positive sign is requested, hide the sign.\n if (valueNegative && +value === 0 && sign !== \"+\") valueNegative = false;\n\n // Compute the prefix and suffix.\n valuePrefix = (valueNegative ? (sign === \"(\" ? sign : minus) : sign === \"-\" || sign === \"(\" ? \"\" : sign) + valuePrefix;\n valueSuffix = (type === \"s\" && !isNaN(value) && prefixExponent !== undefined ? prefixes[8 + prefixExponent / 3] : \"\") + valueSuffix + (valueNegative && sign === \"(\" ? \")\" : \"\");\n\n // Break the formatted value into the integer “value” part that can be\n // grouped, and fractional or exponential “suffix” part that is not.\n if (maybeSuffix) {\n i = -1, n = value.length;\n while (++i < n) {\n if (c = value.charCodeAt(i), 48 > c || c > 57) {\n valueSuffix = (c === 46 ? decimal + value.slice(i + 1) : value.slice(i)) + valueSuffix;\n value = value.slice(0, i);\n break;\n }\n }\n }\n }\n\n // If the fill character is not \"0\", grouping is applied before padding.\n if (comma && !zero) value = group(value, Infinity);\n\n // Compute the padding.\n var length = valuePrefix.length + value.length + valueSuffix.length,\n padding = length < width ? new Array(width - length + 1).join(fill) : \"\";\n\n // If the fill character is \"0\", grouping is applied after padding.\n if (comma && zero) value = group(padding + value, padding.length ? width - valueSuffix.length : Infinity), padding = \"\";\n\n // Reconstruct the final output based on the desired alignment.\n switch (align) {\n case \"<\": value = valuePrefix + value + valueSuffix + padding; break;\n case \"=\": value = valuePrefix + padding + value + valueSuffix; break;\n case \"^\": value = padding.slice(0, length = padding.length >> 1) + valuePrefix + value + valueSuffix + padding.slice(length); break;\n default: value = padding + valuePrefix + value + valueSuffix; break;\n }\n\n return numerals(value);\n }\n\n format.toString = function() {\n return specifier + \"\";\n };\n\n return format;\n }\n\n function formatPrefix(specifier, value) {\n var e = Math.max(-8, Math.min(8, Math.floor(exponent(value) / 3))) * 3,\n k = Math.pow(10, -e),\n f = newFormat((specifier = formatSpecifier(specifier), specifier.type = \"f\", specifier), {suffix: prefixes[8 + e / 3]});\n return function(value) {\n return f(k * value);\n };\n }\n\n return {\n format: newFormat,\n formatPrefix: formatPrefix\n };\n}\n","import formatLocale from \"./locale.js\";\n\nvar locale;\nexport var format;\nexport var formatPrefix;\n\ndefaultLocale({\n thousands: \",\",\n grouping: [3],\n currency: [\"$\", \"\"]\n});\n\nexport default function defaultLocale(definition) {\n locale = formatLocale(definition);\n format = locale.format;\n formatPrefix = locale.formatPrefix;\n return locale;\n}\n","import exponent from \"./exponent.js\";\n\nexport default function(step) {\n return Math.max(0, -exponent(Math.abs(step)));\n}\n","import exponent from \"./exponent.js\";\n\nexport default function(step, value) {\n return Math.max(0, Math.max(-8, Math.min(8, Math.floor(exponent(value) / 3))) * 3 - exponent(Math.abs(step)));\n}\n","import exponent from \"./exponent.js\";\n\nexport default function(step, max) {\n step = Math.abs(step), max = Math.abs(max) - step;\n return Math.max(0, exponent(max) - exponent(step)) + 1;\n}\n","import {tickStep} from \"d3-array\";\nimport {format, formatPrefix, formatSpecifier, precisionFixed, precisionPrefix, precisionRound} from \"d3-format\";\n\nexport default function tickFormat(start, stop, count, specifier) {\n var step = tickStep(start, stop, count),\n precision;\n specifier = formatSpecifier(specifier == null ? \",f\" : specifier);\n switch (specifier.type) {\n case \"s\": {\n var value = Math.max(Math.abs(start), Math.abs(stop));\n if (specifier.precision == null && !isNaN(precision = precisionPrefix(step, value))) specifier.precision = precision;\n return formatPrefix(specifier, value);\n }\n case \"\":\n case \"e\":\n case \"g\":\n case \"p\":\n case \"r\": {\n if (specifier.precision == null && !isNaN(precision = precisionRound(step, Math.max(Math.abs(start), Math.abs(stop))))) specifier.precision = precision - (specifier.type === \"e\");\n break;\n }\n case \"f\":\n case \"%\": {\n if (specifier.precision == null && !isNaN(precision = precisionFixed(step))) specifier.precision = precision - (specifier.type === \"%\") * 2;\n break;\n }\n }\n return format(specifier);\n}\n","import {ticks, tickIncrement} from \"d3-array\";\nimport continuous, {copy} from \"./continuous.js\";\nimport {initRange} from \"./init.js\";\nimport tickFormat from \"./tickFormat.js\";\n\nexport function linearish(scale) {\n var domain = scale.domain;\n\n scale.ticks = function(count) {\n var d = domain();\n return ticks(d[0], d[d.length - 1], count == null ? 10 : count);\n };\n\n scale.tickFormat = function(count, specifier) {\n var d = domain();\n return tickFormat(d[0], d[d.length - 1], count == null ? 10 : count, specifier);\n };\n\n scale.nice = function(count) {\n if (count == null) count = 10;\n\n var d = domain();\n var i0 = 0;\n var i1 = d.length - 1;\n var start = d[i0];\n var stop = d[i1];\n var prestep;\n var step;\n var maxIter = 10;\n\n if (stop < start) {\n step = start, start = stop, stop = step;\n step = i0, i0 = i1, i1 = step;\n }\n \n while (maxIter-- > 0) {\n step = tickIncrement(start, stop, count);\n if (step === prestep) {\n d[i0] = start\n d[i1] = stop\n return domain(d);\n } else if (step > 0) {\n start = Math.floor(start / step) * step;\n stop = Math.ceil(stop / step) * step;\n } else if (step < 0) {\n start = Math.ceil(start * step) / step;\n stop = Math.floor(stop * step) / step;\n } else {\n break;\n }\n prestep = step;\n }\n\n return scale;\n };\n\n return scale;\n}\n\nexport default function linear() {\n var scale = continuous();\n\n scale.copy = function() {\n return copy(scale, linear());\n };\n\n initRange.apply(scale, arguments);\n\n return linearish(scale);\n}\n","import {linearish} from \"./linear.js\";\nimport {copy, identity, transformer} from \"./continuous.js\";\nimport {initRange} from \"./init.js\";\n\nfunction transformPow(exponent) {\n return function(x) {\n return x < 0 ? -Math.pow(-x, exponent) : Math.pow(x, exponent);\n };\n}\n\nfunction transformSqrt(x) {\n return x < 0 ? -Math.sqrt(-x) : Math.sqrt(x);\n}\n\nfunction transformSquare(x) {\n return x < 0 ? -x * x : x * x;\n}\n\nexport function powish(transform) {\n var scale = transform(identity, identity),\n exponent = 1;\n\n function rescale() {\n return exponent === 1 ? transform(identity, identity)\n : exponent === 0.5 ? transform(transformSqrt, transformSquare)\n : transform(transformPow(exponent), transformPow(1 / exponent));\n }\n\n scale.exponent = function(_) {\n return arguments.length ? (exponent = +_, rescale()) : exponent;\n };\n\n return linearish(scale);\n}\n\nexport default function pow() {\n var scale = powish(transformer());\n\n scale.copy = function() {\n return copy(scale, pow()).exponent(scale.exponent());\n };\n\n initRange.apply(scale, arguments);\n\n return scale;\n}\n\nexport function sqrt() {\n return pow.apply(null, arguments).exponent(0.5);\n}\n","const t0 = new Date, t1 = new Date;\n\nexport function timeInterval(floori, offseti, count, field) {\n\n function interval(date) {\n return floori(date = arguments.length === 0 ? new Date : new Date(+date)), date;\n }\n\n interval.floor = (date) => {\n return floori(date = new Date(+date)), date;\n };\n\n interval.ceil = (date) => {\n return floori(date = new Date(date - 1)), offseti(date, 1), floori(date), date;\n };\n\n interval.round = (date) => {\n const d0 = interval(date), d1 = interval.ceil(date);\n return date - d0 < d1 - date ? d0 : d1;\n };\n\n interval.offset = (date, step) => {\n return offseti(date = new Date(+date), step == null ? 1 : Math.floor(step)), date;\n };\n\n interval.range = (start, stop, step) => {\n const range = [];\n start = interval.ceil(start);\n step = step == null ? 1 : Math.floor(step);\n if (!(start < stop) || !(step > 0)) return range; // also handles Invalid Date\n let previous;\n do range.push(previous = new Date(+start)), offseti(start, step), floori(start);\n while (previous < start && start < stop);\n return range;\n };\n\n interval.filter = (test) => {\n return timeInterval((date) => {\n if (date >= date) while (floori(date), !test(date)) date.setTime(date - 1);\n }, (date, step) => {\n if (date >= date) {\n if (step < 0) while (++step <= 0) {\n while (offseti(date, -1), !test(date)) {} // eslint-disable-line no-empty\n } else while (--step >= 0) {\n while (offseti(date, +1), !test(date)) {} // eslint-disable-line no-empty\n }\n }\n });\n };\n\n if (count) {\n interval.count = (start, end) => {\n t0.setTime(+start), t1.setTime(+end);\n floori(t0), floori(t1);\n return Math.floor(count(t0, t1));\n };\n\n interval.every = (step) => {\n step = Math.floor(step);\n return !isFinite(step) || !(step > 0) ? null\n : !(step > 1) ? interval\n : interval.filter(field\n ? (d) => field(d) % step === 0\n : (d) => interval.count(0, d) % step === 0);\n };\n }\n\n return interval;\n}\n","import {timeInterval} from \"./interval.js\";\nimport {durationSecond} from \"./duration.js\";\n\nexport const second = timeInterval((date) => {\n date.setTime(date - date.getMilliseconds());\n}, (date, step) => {\n date.setTime(+date + step * durationSecond);\n}, (start, end) => {\n return (end - start) / durationSecond;\n}, (date) => {\n return date.getUTCSeconds();\n});\n\nexport const seconds = second.range;\n","import {timeInterval} from \"./interval.js\";\nimport {durationMinute, durationSecond} from \"./duration.js\";\n\nexport const timeMinute = timeInterval((date) => {\n date.setTime(date - date.getMilliseconds() - date.getSeconds() * durationSecond);\n}, (date, step) => {\n date.setTime(+date + step * durationMinute);\n}, (start, end) => {\n return (end - start) / durationMinute;\n}, (date) => {\n return date.getMinutes();\n});\n\nexport const timeMinutes = timeMinute.range;\n\nexport const utcMinute = timeInterval((date) => {\n date.setUTCSeconds(0, 0);\n}, (date, step) => {\n date.setTime(+date + step * durationMinute);\n}, (start, end) => {\n return (end - start) / durationMinute;\n}, (date) => {\n return date.getUTCMinutes();\n});\n\nexport const utcMinutes = utcMinute.range;\n","import {timeInterval} from \"./interval.js\";\nimport {durationHour, durationMinute, durationSecond} from \"./duration.js\";\n\nexport const timeHour = timeInterval((date) => {\n date.setTime(date - date.getMilliseconds() - date.getSeconds() * durationSecond - date.getMinutes() * durationMinute);\n}, (date, step) => {\n date.setTime(+date + step * durationHour);\n}, (start, end) => {\n return (end - start) / durationHour;\n}, (date) => {\n return date.getHours();\n});\n\nexport const timeHours = timeHour.range;\n\nexport const utcHour = timeInterval((date) => {\n date.setUTCMinutes(0, 0, 0);\n}, (date, step) => {\n date.setTime(+date + step * durationHour);\n}, (start, end) => {\n return (end - start) / durationHour;\n}, (date) => {\n return date.getUTCHours();\n});\n\nexport const utcHours = utcHour.range;\n","import {timeInterval} from \"./interval.js\";\nimport {durationDay, durationMinute} from \"./duration.js\";\n\nexport const timeDay = timeInterval(\n date => date.setHours(0, 0, 0, 0),\n (date, step) => date.setDate(date.getDate() + step),\n (start, end) => (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationDay,\n date => date.getDate() - 1\n);\n\nexport const timeDays = timeDay.range;\n\nexport const utcDay = timeInterval((date) => {\n date.setUTCHours(0, 0, 0, 0);\n}, (date, step) => {\n date.setUTCDate(date.getUTCDate() + step);\n}, (start, end) => {\n return (end - start) / durationDay;\n}, (date) => {\n return date.getUTCDate() - 1;\n});\n\nexport const utcDays = utcDay.range;\n\nexport const unixDay = timeInterval((date) => {\n date.setUTCHours(0, 0, 0, 0);\n}, (date, step) => {\n date.setUTCDate(date.getUTCDate() + step);\n}, (start, end) => {\n return (end - start) / durationDay;\n}, (date) => {\n return Math.floor(date / durationDay);\n});\n\nexport const unixDays = unixDay.range;\n","import {timeInterval} from \"./interval.js\";\nimport {durationMinute, durationWeek} from \"./duration.js\";\n\nfunction timeWeekday(i) {\n return timeInterval((date) => {\n date.setDate(date.getDate() - (date.getDay() + 7 - i) % 7);\n date.setHours(0, 0, 0, 0);\n }, (date, step) => {\n date.setDate(date.getDate() + step * 7);\n }, (start, end) => {\n return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationWeek;\n });\n}\n\nexport const timeSunday = timeWeekday(0);\nexport const timeMonday = timeWeekday(1);\nexport const timeTuesday = timeWeekday(2);\nexport const timeWednesday = timeWeekday(3);\nexport const timeThursday = timeWeekday(4);\nexport const timeFriday = timeWeekday(5);\nexport const timeSaturday = timeWeekday(6);\n\nexport const timeSundays = timeSunday.range;\nexport const timeMondays = timeMonday.range;\nexport const timeTuesdays = timeTuesday.range;\nexport const timeWednesdays = timeWednesday.range;\nexport const timeThursdays = timeThursday.range;\nexport const timeFridays = timeFriday.range;\nexport const timeSaturdays = timeSaturday.range;\n\nfunction utcWeekday(i) {\n return timeInterval((date) => {\n date.setUTCDate(date.getUTCDate() - (date.getUTCDay() + 7 - i) % 7);\n date.setUTCHours(0, 0, 0, 0);\n }, (date, step) => {\n date.setUTCDate(date.getUTCDate() + step * 7);\n }, (start, end) => {\n return (end - start) / durationWeek;\n });\n}\n\nexport const utcSunday = utcWeekday(0);\nexport const utcMonday = utcWeekday(1);\nexport const utcTuesday = utcWeekday(2);\nexport const utcWednesday = utcWeekday(3);\nexport const utcThursday = utcWeekday(4);\nexport const utcFriday = utcWeekday(5);\nexport const utcSaturday = utcWeekday(6);\n\nexport const utcSundays = utcSunday.range;\nexport const utcMondays = utcMonday.range;\nexport const utcTuesdays = utcTuesday.range;\nexport const utcWednesdays = utcWednesday.range;\nexport const utcThursdays = utcThursday.range;\nexport const utcFridays = utcFriday.range;\nexport const utcSaturdays = utcSaturday.range;\n","import {timeInterval} from \"./interval.js\";\n\nexport const timeMonth = timeInterval((date) => {\n date.setDate(1);\n date.setHours(0, 0, 0, 0);\n}, (date, step) => {\n date.setMonth(date.getMonth() + step);\n}, (start, end) => {\n return end.getMonth() - start.getMonth() + (end.getFullYear() - start.getFullYear()) * 12;\n}, (date) => {\n return date.getMonth();\n});\n\nexport const timeMonths = timeMonth.range;\n\nexport const utcMonth = timeInterval((date) => {\n date.setUTCDate(1);\n date.setUTCHours(0, 0, 0, 0);\n}, (date, step) => {\n date.setUTCMonth(date.getUTCMonth() + step);\n}, (start, end) => {\n return end.getUTCMonth() - start.getUTCMonth() + (end.getUTCFullYear() - start.getUTCFullYear()) * 12;\n}, (date) => {\n return date.getUTCMonth();\n});\n\nexport const utcMonths = utcMonth.range;\n","import {timeInterval} from \"./interval.js\";\n\nexport const timeYear = timeInterval((date) => {\n date.setMonth(0, 1);\n date.setHours(0, 0, 0, 0);\n}, (date, step) => {\n date.setFullYear(date.getFullYear() + step);\n}, (start, end) => {\n return end.getFullYear() - start.getFullYear();\n}, (date) => {\n return date.getFullYear();\n});\n\n// An optimized implementation for this simple case.\ntimeYear.every = (k) => {\n return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : timeInterval((date) => {\n date.setFullYear(Math.floor(date.getFullYear() / k) * k);\n date.setMonth(0, 1);\n date.setHours(0, 0, 0, 0);\n }, (date, step) => {\n date.setFullYear(date.getFullYear() + step * k);\n });\n};\n\nexport const timeYears = timeYear.range;\n\nexport const utcYear = timeInterval((date) => {\n date.setUTCMonth(0, 1);\n date.setUTCHours(0, 0, 0, 0);\n}, (date, step) => {\n date.setUTCFullYear(date.getUTCFullYear() + step);\n}, (start, end) => {\n return end.getUTCFullYear() - start.getUTCFullYear();\n}, (date) => {\n return date.getUTCFullYear();\n});\n\n// An optimized implementation for this simple case.\nutcYear.every = (k) => {\n return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : timeInterval((date) => {\n date.setUTCFullYear(Math.floor(date.getUTCFullYear() / k) * k);\n date.setUTCMonth(0, 1);\n date.setUTCHours(0, 0, 0, 0);\n }, (date, step) => {\n date.setUTCFullYear(date.getUTCFullYear() + step * k);\n });\n};\n\nexport const utcYears = utcYear.range;\n","import {\n timeDay,\n timeSunday,\n timeMonday,\n timeThursday,\n timeYear,\n utcDay,\n utcSunday,\n utcMonday,\n utcThursday,\n utcYear\n} from \"d3-time\";\n\nfunction localDate(d) {\n if (0 <= d.y && d.y < 100) {\n var date = new Date(-1, d.m, d.d, d.H, d.M, d.S, d.L);\n date.setFullYear(d.y);\n return date;\n }\n return new Date(d.y, d.m, d.d, d.H, d.M, d.S, d.L);\n}\n\nfunction utcDate(d) {\n if (0 <= d.y && d.y < 100) {\n var date = new Date(Date.UTC(-1, d.m, d.d, d.H, d.M, d.S, d.L));\n date.setUTCFullYear(d.y);\n return date;\n }\n return new Date(Date.UTC(d.y, d.m, d.d, d.H, d.M, d.S, d.L));\n}\n\nfunction newDate(y, m, d) {\n return {y: y, m: m, d: d, H: 0, M: 0, S: 0, L: 0};\n}\n\nexport default function formatLocale(locale) {\n var locale_dateTime = locale.dateTime,\n locale_date = locale.date,\n locale_time = locale.time,\n locale_periods = locale.periods,\n locale_weekdays = locale.days,\n locale_shortWeekdays = locale.shortDays,\n locale_months = locale.months,\n locale_shortMonths = locale.shortMonths;\n\n var periodRe = formatRe(locale_periods),\n periodLookup = formatLookup(locale_periods),\n weekdayRe = formatRe(locale_weekdays),\n weekdayLookup = formatLookup(locale_weekdays),\n shortWeekdayRe = formatRe(locale_shortWeekdays),\n shortWeekdayLookup = formatLookup(locale_shortWeekdays),\n monthRe = formatRe(locale_months),\n monthLookup = formatLookup(locale_months),\n shortMonthRe = formatRe(locale_shortMonths),\n shortMonthLookup = formatLookup(locale_shortMonths);\n\n var formats = {\n \"a\": formatShortWeekday,\n \"A\": formatWeekday,\n \"b\": formatShortMonth,\n \"B\": formatMonth,\n \"c\": null,\n \"d\": formatDayOfMonth,\n \"e\": formatDayOfMonth,\n \"f\": formatMicroseconds,\n \"g\": formatYearISO,\n \"G\": formatFullYearISO,\n \"H\": formatHour24,\n \"I\": formatHour12,\n \"j\": formatDayOfYear,\n \"L\": formatMilliseconds,\n \"m\": formatMonthNumber,\n \"M\": formatMinutes,\n \"p\": formatPeriod,\n \"q\": formatQuarter,\n \"Q\": formatUnixTimestamp,\n \"s\": formatUnixTimestampSeconds,\n \"S\": formatSeconds,\n \"u\": formatWeekdayNumberMonday,\n \"U\": formatWeekNumberSunday,\n \"V\": formatWeekNumberISO,\n \"w\": formatWeekdayNumberSunday,\n \"W\": formatWeekNumberMonday,\n \"x\": null,\n \"X\": null,\n \"y\": formatYear,\n \"Y\": formatFullYear,\n \"Z\": formatZone,\n \"%\": formatLiteralPercent\n };\n\n var utcFormats = {\n \"a\": formatUTCShortWeekday,\n \"A\": formatUTCWeekday,\n \"b\": formatUTCShortMonth,\n \"B\": formatUTCMonth,\n \"c\": null,\n \"d\": formatUTCDayOfMonth,\n \"e\": formatUTCDayOfMonth,\n \"f\": formatUTCMicroseconds,\n \"g\": formatUTCYearISO,\n \"G\": formatUTCFullYearISO,\n \"H\": formatUTCHour24,\n \"I\": formatUTCHour12,\n \"j\": formatUTCDayOfYear,\n \"L\": formatUTCMilliseconds,\n \"m\": formatUTCMonthNumber,\n \"M\": formatUTCMinutes,\n \"p\": formatUTCPeriod,\n \"q\": formatUTCQuarter,\n \"Q\": formatUnixTimestamp,\n \"s\": formatUnixTimestampSeconds,\n \"S\": formatUTCSeconds,\n \"u\": formatUTCWeekdayNumberMonday,\n \"U\": formatUTCWeekNumberSunday,\n \"V\": formatUTCWeekNumberISO,\n \"w\": formatUTCWeekdayNumberSunday,\n \"W\": formatUTCWeekNumberMonday,\n \"x\": null,\n \"X\": null,\n \"y\": formatUTCYear,\n \"Y\": formatUTCFullYear,\n \"Z\": formatUTCZone,\n \"%\": formatLiteralPercent\n };\n\n var parses = {\n \"a\": parseShortWeekday,\n \"A\": parseWeekday,\n \"b\": parseShortMonth,\n \"B\": parseMonth,\n \"c\": parseLocaleDateTime,\n \"d\": parseDayOfMonth,\n \"e\": parseDayOfMonth,\n \"f\": parseMicroseconds,\n \"g\": parseYear,\n \"G\": parseFullYear,\n \"H\": parseHour24,\n \"I\": parseHour24,\n \"j\": parseDayOfYear,\n \"L\": parseMilliseconds,\n \"m\": parseMonthNumber,\n \"M\": parseMinutes,\n \"p\": parsePeriod,\n \"q\": parseQuarter,\n \"Q\": parseUnixTimestamp,\n \"s\": parseUnixTimestampSeconds,\n \"S\": parseSeconds,\n \"u\": parseWeekdayNumberMonday,\n \"U\": parseWeekNumberSunday,\n \"V\": parseWeekNumberISO,\n \"w\": parseWeekdayNumberSunday,\n \"W\": parseWeekNumberMonday,\n \"x\": parseLocaleDate,\n \"X\": parseLocaleTime,\n \"y\": parseYear,\n \"Y\": parseFullYear,\n \"Z\": parseZone,\n \"%\": parseLiteralPercent\n };\n\n // These recursive directive definitions must be deferred.\n formats.x = newFormat(locale_date, formats);\n formats.X = newFormat(locale_time, formats);\n formats.c = newFormat(locale_dateTime, formats);\n utcFormats.x = newFormat(locale_date, utcFormats);\n utcFormats.X = newFormat(locale_time, utcFormats);\n utcFormats.c = newFormat(locale_dateTime, utcFormats);\n\n function newFormat(specifier, formats) {\n return function(date) {\n var string = [],\n i = -1,\n j = 0,\n n = specifier.length,\n c,\n pad,\n format;\n\n if (!(date instanceof Date)) date = new Date(+date);\n\n while (++i < n) {\n if (specifier.charCodeAt(i) === 37) {\n string.push(specifier.slice(j, i));\n if ((pad = pads[c = specifier.charAt(++i)]) != null) c = specifier.charAt(++i);\n else pad = c === \"e\" ? \" \" : \"0\";\n if (format = formats[c]) c = format(date, pad);\n string.push(c);\n j = i + 1;\n }\n }\n\n string.push(specifier.slice(j, i));\n return string.join(\"\");\n };\n }\n\n function newParse(specifier, Z) {\n return function(string) {\n var d = newDate(1900, undefined, 1),\n i = parseSpecifier(d, specifier, string += \"\", 0),\n week, day;\n if (i != string.length) return null;\n\n // If a UNIX timestamp is specified, return it.\n if (\"Q\" in d) return new Date(d.Q);\n if (\"s\" in d) return new Date(d.s * 1000 + (\"L\" in d ? d.L : 0));\n\n // If this is utcParse, never use the local timezone.\n if (Z && !(\"Z\" in d)) d.Z = 0;\n\n // The am-pm flag is 0 for AM, and 1 for PM.\n if (\"p\" in d) d.H = d.H % 12 + d.p * 12;\n\n // If the month was not specified, inherit from the quarter.\n if (d.m === undefined) d.m = \"q\" in d ? d.q : 0;\n\n // Convert day-of-week and week-of-year to day-of-year.\n if (\"V\" in d) {\n if (d.V < 1 || d.V > 53) return null;\n if (!(\"w\" in d)) d.w = 1;\n if (\"Z\" in d) {\n week = utcDate(newDate(d.y, 0, 1)), day = week.getUTCDay();\n week = day > 4 || day === 0 ? utcMonday.ceil(week) : utcMonday(week);\n week = utcDay.offset(week, (d.V - 1) * 7);\n d.y = week.getUTCFullYear();\n d.m = week.getUTCMonth();\n d.d = week.getUTCDate() + (d.w + 6) % 7;\n } else {\n week = localDate(newDate(d.y, 0, 1)), day = week.getDay();\n week = day > 4 || day === 0 ? timeMonday.ceil(week) : timeMonday(week);\n week = timeDay.offset(week, (d.V - 1) * 7);\n d.y = week.getFullYear();\n d.m = week.getMonth();\n d.d = week.getDate() + (d.w + 6) % 7;\n }\n } else if (\"W\" in d || \"U\" in d) {\n if (!(\"w\" in d)) d.w = \"u\" in d ? d.u % 7 : \"W\" in d ? 1 : 0;\n day = \"Z\" in d ? utcDate(newDate(d.y, 0, 1)).getUTCDay() : localDate(newDate(d.y, 0, 1)).getDay();\n d.m = 0;\n d.d = \"W\" in d ? (d.w + 6) % 7 + d.W * 7 - (day + 5) % 7 : d.w + d.U * 7 - (day + 6) % 7;\n }\n\n // If a time zone is specified, all fields are interpreted as UTC and then\n // offset according to the specified time zone.\n if (\"Z\" in d) {\n d.H += d.Z / 100 | 0;\n d.M += d.Z % 100;\n return utcDate(d);\n }\n\n // Otherwise, all fields are in local time.\n return localDate(d);\n };\n }\n\n function parseSpecifier(d, specifier, string, j) {\n var i = 0,\n n = specifier.length,\n m = string.length,\n c,\n parse;\n\n while (i < n) {\n if (j >= m) return -1;\n c = specifier.charCodeAt(i++);\n if (c === 37) {\n c = specifier.charAt(i++);\n parse = parses[c in pads ? specifier.charAt(i++) : c];\n if (!parse || ((j = parse(d, string, j)) < 0)) return -1;\n } else if (c != string.charCodeAt(j++)) {\n return -1;\n }\n }\n\n return j;\n }\n\n function parsePeriod(d, string, i) {\n var n = periodRe.exec(string.slice(i));\n return n ? (d.p = periodLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;\n }\n\n function parseShortWeekday(d, string, i) {\n var n = shortWeekdayRe.exec(string.slice(i));\n return n ? (d.w = shortWeekdayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;\n }\n\n function parseWeekday(d, string, i) {\n var n = weekdayRe.exec(string.slice(i));\n return n ? (d.w = weekdayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;\n }\n\n function parseShortMonth(d, string, i) {\n var n = shortMonthRe.exec(string.slice(i));\n return n ? (d.m = shortMonthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;\n }\n\n function parseMonth(d, string, i) {\n var n = monthRe.exec(string.slice(i));\n return n ? (d.m = monthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;\n }\n\n function parseLocaleDateTime(d, string, i) {\n return parseSpecifier(d, locale_dateTime, string, i);\n }\n\n function parseLocaleDate(d, string, i) {\n return parseSpecifier(d, locale_date, string, i);\n }\n\n function parseLocaleTime(d, string, i) {\n return parseSpecifier(d, locale_time, string, i);\n }\n\n function formatShortWeekday(d) {\n return locale_shortWeekdays[d.getDay()];\n }\n\n function formatWeekday(d) {\n return locale_weekdays[d.getDay()];\n }\n\n function formatShortMonth(d) {\n return locale_shortMonths[d.getMonth()];\n }\n\n function formatMonth(d) {\n return locale_months[d.getMonth()];\n }\n\n function formatPeriod(d) {\n return locale_periods[+(d.getHours() >= 12)];\n }\n\n function formatQuarter(d) {\n return 1 + ~~(d.getMonth() / 3);\n }\n\n function formatUTCShortWeekday(d) {\n return locale_shortWeekdays[d.getUTCDay()];\n }\n\n function formatUTCWeekday(d) {\n return locale_weekdays[d.getUTCDay()];\n }\n\n function formatUTCShortMonth(d) {\n return locale_shortMonths[d.getUTCMonth()];\n }\n\n function formatUTCMonth(d) {\n return locale_months[d.getUTCMonth()];\n }\n\n function formatUTCPeriod(d) {\n return locale_periods[+(d.getUTCHours() >= 12)];\n }\n\n function formatUTCQuarter(d) {\n return 1 + ~~(d.getUTCMonth() / 3);\n }\n\n return {\n format: function(specifier) {\n var f = newFormat(specifier += \"\", formats);\n f.toString = function() { return specifier; };\n return f;\n },\n parse: function(specifier) {\n var p = newParse(specifier += \"\", false);\n p.toString = function() { return specifier; };\n return p;\n },\n utcFormat: function(specifier) {\n var f = newFormat(specifier += \"\", utcFormats);\n f.toString = function() { return specifier; };\n return f;\n },\n utcParse: function(specifier) {\n var p = newParse(specifier += \"\", true);\n p.toString = function() { return specifier; };\n return p;\n }\n };\n}\n\nvar pads = {\"-\": \"\", \"_\": \" \", \"0\": \"0\"},\n numberRe = /^\\s*\\d+/, // note: ignores next directive\n percentRe = /^%/,\n requoteRe = /[\\\\^$*+?|[\\]().{}]/g;\n\nfunction pad(value, fill, width) {\n var sign = value < 0 ? \"-\" : \"\",\n string = (sign ? -value : value) + \"\",\n length = string.length;\n return sign + (length < width ? new Array(width - length + 1).join(fill) + string : string);\n}\n\nfunction requote(s) {\n return s.replace(requoteRe, \"\\\\$&\");\n}\n\nfunction formatRe(names) {\n return new RegExp(\"^(?:\" + names.map(requote).join(\"|\") + \")\", \"i\");\n}\n\nfunction formatLookup(names) {\n return new Map(names.map((name, i) => [name.toLowerCase(), i]));\n}\n\nfunction parseWeekdayNumberSunday(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 1));\n return n ? (d.w = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseWeekdayNumberMonday(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 1));\n return n ? (d.u = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseWeekNumberSunday(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.U = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseWeekNumberISO(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.V = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseWeekNumberMonday(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.W = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseFullYear(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 4));\n return n ? (d.y = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseYear(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.y = +n[0] + (+n[0] > 68 ? 1900 : 2000), i + n[0].length) : -1;\n}\n\nfunction parseZone(d, string, i) {\n var n = /^(Z)|([+-]\\d\\d)(?::?(\\d\\d))?/.exec(string.slice(i, i + 6));\n return n ? (d.Z = n[1] ? 0 : -(n[2] + (n[3] || \"00\")), i + n[0].length) : -1;\n}\n\nfunction parseQuarter(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 1));\n return n ? (d.q = n[0] * 3 - 3, i + n[0].length) : -1;\n}\n\nfunction parseMonthNumber(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.m = n[0] - 1, i + n[0].length) : -1;\n}\n\nfunction parseDayOfMonth(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.d = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseDayOfYear(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 3));\n return n ? (d.m = 0, d.d = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseHour24(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.H = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseMinutes(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.M = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseSeconds(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.S = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseMilliseconds(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 3));\n return n ? (d.L = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseMicroseconds(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 6));\n return n ? (d.L = Math.floor(n[0] / 1000), i + n[0].length) : -1;\n}\n\nfunction parseLiteralPercent(d, string, i) {\n var n = percentRe.exec(string.slice(i, i + 1));\n return n ? i + n[0].length : -1;\n}\n\nfunction parseUnixTimestamp(d, string, i) {\n var n = numberRe.exec(string.slice(i));\n return n ? (d.Q = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseUnixTimestampSeconds(d, string, i) {\n var n = numberRe.exec(string.slice(i));\n return n ? (d.s = +n[0], i + n[0].length) : -1;\n}\n\nfunction formatDayOfMonth(d, p) {\n return pad(d.getDate(), p, 2);\n}\n\nfunction formatHour24(d, p) {\n return pad(d.getHours(), p, 2);\n}\n\nfunction formatHour12(d, p) {\n return pad(d.getHours() % 12 || 12, p, 2);\n}\n\nfunction formatDayOfYear(d, p) {\n return pad(1 + timeDay.count(timeYear(d), d), p, 3);\n}\n\nfunction formatMilliseconds(d, p) {\n return pad(d.getMilliseconds(), p, 3);\n}\n\nfunction formatMicroseconds(d, p) {\n return formatMilliseconds(d, p) + \"000\";\n}\n\nfunction formatMonthNumber(d, p) {\n return pad(d.getMonth() + 1, p, 2);\n}\n\nfunction formatMinutes(d, p) {\n return pad(d.getMinutes(), p, 2);\n}\n\nfunction formatSeconds(d, p) {\n return pad(d.getSeconds(), p, 2);\n}\n\nfunction formatWeekdayNumberMonday(d) {\n var day = d.getDay();\n return day === 0 ? 7 : day;\n}\n\nfunction formatWeekNumberSunday(d, p) {\n return pad(timeSunday.count(timeYear(d) - 1, d), p, 2);\n}\n\nfunction dISO(d) {\n var day = d.getDay();\n return (day >= 4 || day === 0) ? timeThursday(d) : timeThursday.ceil(d);\n}\n\nfunction formatWeekNumberISO(d, p) {\n d = dISO(d);\n return pad(timeThursday.count(timeYear(d), d) + (timeYear(d).getDay() === 4), p, 2);\n}\n\nfunction formatWeekdayNumberSunday(d) {\n return d.getDay();\n}\n\nfunction formatWeekNumberMonday(d, p) {\n return pad(timeMonday.count(timeYear(d) - 1, d), p, 2);\n}\n\nfunction formatYear(d, p) {\n return pad(d.getFullYear() % 100, p, 2);\n}\n\nfunction formatYearISO(d, p) {\n d = dISO(d);\n return pad(d.getFullYear() % 100, p, 2);\n}\n\nfunction formatFullYear(d, p) {\n return pad(d.getFullYear() % 10000, p, 4);\n}\n\nfunction formatFullYearISO(d, p) {\n var day = d.getDay();\n d = (day >= 4 || day === 0) ? timeThursday(d) : timeThursday.ceil(d);\n return pad(d.getFullYear() % 10000, p, 4);\n}\n\nfunction formatZone(d) {\n var z = d.getTimezoneOffset();\n return (z > 0 ? \"-\" : (z *= -1, \"+\"))\n + pad(z / 60 | 0, \"0\", 2)\n + pad(z % 60, \"0\", 2);\n}\n\nfunction formatUTCDayOfMonth(d, p) {\n return pad(d.getUTCDate(), p, 2);\n}\n\nfunction formatUTCHour24(d, p) {\n return pad(d.getUTCHours(), p, 2);\n}\n\nfunction formatUTCHour12(d, p) {\n return pad(d.getUTCHours() % 12 || 12, p, 2);\n}\n\nfunction formatUTCDayOfYear(d, p) {\n return pad(1 + utcDay.count(utcYear(d), d), p, 3);\n}\n\nfunction formatUTCMilliseconds(d, p) {\n return pad(d.getUTCMilliseconds(), p, 3);\n}\n\nfunction formatUTCMicroseconds(d, p) {\n return formatUTCMilliseconds(d, p) + \"000\";\n}\n\nfunction formatUTCMonthNumber(d, p) {\n return pad(d.getUTCMonth() + 1, p, 2);\n}\n\nfunction formatUTCMinutes(d, p) {\n return pad(d.getUTCMinutes(), p, 2);\n}\n\nfunction formatUTCSeconds(d, p) {\n return pad(d.getUTCSeconds(), p, 2);\n}\n\nfunction formatUTCWeekdayNumberMonday(d) {\n var dow = d.getUTCDay();\n return dow === 0 ? 7 : dow;\n}\n\nfunction formatUTCWeekNumberSunday(d, p) {\n return pad(utcSunday.count(utcYear(d) - 1, d), p, 2);\n}\n\nfunction UTCdISO(d) {\n var day = d.getUTCDay();\n return (day >= 4 || day === 0) ? utcThursday(d) : utcThursday.ceil(d);\n}\n\nfunction formatUTCWeekNumberISO(d, p) {\n d = UTCdISO(d);\n return pad(utcThursday.count(utcYear(d), d) + (utcYear(d).getUTCDay() === 4), p, 2);\n}\n\nfunction formatUTCWeekdayNumberSunday(d) {\n return d.getUTCDay();\n}\n\nfunction formatUTCWeekNumberMonday(d, p) {\n return pad(utcMonday.count(utcYear(d) - 1, d), p, 2);\n}\n\nfunction formatUTCYear(d, p) {\n return pad(d.getUTCFullYear() % 100, p, 2);\n}\n\nfunction formatUTCYearISO(d, p) {\n d = UTCdISO(d);\n return pad(d.getUTCFullYear() % 100, p, 2);\n}\n\nfunction formatUTCFullYear(d, p) {\n return pad(d.getUTCFullYear() % 10000, p, 4);\n}\n\nfunction formatUTCFullYearISO(d, p) {\n var day = d.getUTCDay();\n d = (day >= 4 || day === 0) ? utcThursday(d) : utcThursday.ceil(d);\n return pad(d.getUTCFullYear() % 10000, p, 4);\n}\n\nfunction formatUTCZone() {\n return \"+0000\";\n}\n\nfunction formatLiteralPercent() {\n return \"%\";\n}\n\nfunction formatUnixTimestamp(d) {\n return +d;\n}\n\nfunction formatUnixTimestampSeconds(d) {\n return Math.floor(+d / 1000);\n}\n","import formatLocale from \"./locale.js\";\n\nvar locale;\nexport var timeFormat;\nexport var timeParse;\nexport var utcFormat;\nexport var utcParse;\n\ndefaultLocale({\n dateTime: \"%x, %X\",\n date: \"%-m/%-d/%Y\",\n time: \"%-I:%M:%S %p\",\n periods: [\"AM\", \"PM\"],\n days: [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"],\n shortDays: [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"],\n months: [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"],\n shortMonths: [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"]\n});\n\nexport default function defaultLocale(definition) {\n locale = formatLocale(definition);\n timeFormat = locale.format;\n timeParse = locale.parse;\n utcFormat = locale.utcFormat;\n utcParse = locale.utcParse;\n return locale;\n}\n","import {interpolate, interpolateRound} from \"d3-interpolate\";\nimport {identity} from \"./continuous.js\";\nimport {initInterpolator} from \"./init.js\";\nimport {linearish} from \"./linear.js\";\nimport {loggish} from \"./log.js\";\nimport {symlogish} from \"./symlog.js\";\nimport {powish} from \"./pow.js\";\n\nfunction transformer() {\n var x0 = 0,\n x1 = 1,\n t0,\n t1,\n k10,\n transform,\n interpolator = identity,\n clamp = false,\n unknown;\n\n function scale(x) {\n return x == null || isNaN(x = +x) ? unknown : interpolator(k10 === 0 ? 0.5 : (x = (transform(x) - t0) * k10, clamp ? Math.max(0, Math.min(1, x)) : x));\n }\n\n scale.domain = function(_) {\n return arguments.length ? ([x0, x1] = _, t0 = transform(x0 = +x0), t1 = transform(x1 = +x1), k10 = t0 === t1 ? 0 : 1 / (t1 - t0), scale) : [x0, x1];\n };\n\n scale.clamp = function(_) {\n return arguments.length ? (clamp = !!_, scale) : clamp;\n };\n\n scale.interpolator = function(_) {\n return arguments.length ? (interpolator = _, scale) : interpolator;\n };\n\n function range(interpolate) {\n return function(_) {\n var r0, r1;\n return arguments.length ? ([r0, r1] = _, interpolator = interpolate(r0, r1), scale) : [interpolator(0), interpolator(1)];\n };\n }\n\n scale.range = range(interpolate);\n\n scale.rangeRound = range(interpolateRound);\n\n scale.unknown = function(_) {\n return arguments.length ? (unknown = _, scale) : unknown;\n };\n\n return function(t) {\n transform = t, t0 = t(x0), t1 = t(x1), k10 = t0 === t1 ? 0 : 1 / (t1 - t0);\n return scale;\n };\n}\n\nexport function copy(source, target) {\n return target\n .domain(source.domain())\n .interpolator(source.interpolator())\n .clamp(source.clamp())\n .unknown(source.unknown());\n}\n\nexport default function sequential() {\n var scale = linearish(transformer()(identity));\n\n scale.copy = function() {\n return copy(scale, sequential());\n };\n\n return initInterpolator.apply(scale, arguments);\n}\n\nexport function sequentialLog() {\n var scale = loggish(transformer()).domain([1, 10]);\n\n scale.copy = function() {\n return copy(scale, sequentialLog()).base(scale.base());\n };\n\n return initInterpolator.apply(scale, arguments);\n}\n\nexport function sequentialSymlog() {\n var scale = symlogish(transformer());\n\n scale.copy = function() {\n return copy(scale, sequentialSymlog()).constant(scale.constant());\n };\n\n return initInterpolator.apply(scale, arguments);\n}\n\nexport function sequentialPow() {\n var scale = powish(transformer());\n\n scale.copy = function() {\n return copy(scale, sequentialPow()).exponent(scale.exponent());\n };\n\n return initInterpolator.apply(scale, arguments);\n}\n\nexport function sequentialSqrt() {\n return sequentialPow.apply(null, arguments).exponent(0.5);\n}\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n interpolateCool,\n interpolateInferno,\n interpolateMagma,\n interpolatePlasma,\n interpolateViridis,\n interpolateWarm,\n schemeBlues,\n schemeBuGn,\n schemeBuPu,\n schemeGnBu,\n schemeGreens,\n schemeGreys,\n schemeOranges,\n schemeOrRd,\n schemePuBu,\n schemePuBuGn,\n schemePuRd,\n schemePurples,\n schemeRdPu,\n schemeReds,\n schemeYlGn,\n schemeYlGnBu,\n schemeYlOrBr,\n schemeYlOrRd,\n} from 'd3-scale-chromatic';\nimport {range} from 'd3-array';\nimport {scalePow, scaleSequential, scaleSequentialPow} from 'd3-scale';\nimport {interpolateBasis, interpolateRgbBasis} from 'd3-interpolate';\nimport {color as d3color, hcl, rgb as colorRgb} from 'd3-color';\nimport {SettingsState} from './FlowmapState';\nimport {FlowLinesRenderingMode} from './types';\n\nconst DEFAULT_OUTLINE_COLOR = '#fff';\nconst DEFAULT_DIMMED_OPACITY = 0.4;\nconst DEFAULT_FLOW_MIN_COLOR = 'rgba(240,240,240,0.5)';\nconst DEFAULT_FLOW_COLOR_SCHEME = [DEFAULT_FLOW_MIN_COLOR, '#137CBD'];\nconst DEFAULT_LOCATION_AREA_COLOR = 'rgba(220,220,220,0.5)';\n\nconst DEFAULT_FLOW_COLOR_SCHEME_POSITIVE = [DEFAULT_FLOW_MIN_COLOR, '#f6654e'];\nconst DEFAULT_FLOW_COLOR_SCHEME_NEGATIVE = [DEFAULT_FLOW_MIN_COLOR, '#00a9cc'];\n\nexport type ColorScale = (value: number) => RGBA;\nexport type RGBA = [number, number, number, number];\n\nconst FALLBACK_COLOR_RGBA: RGBA = [255, 255, 255, 255];\n\nexport function opacityFloatToInteger(opacity: number): number {\n return Math.round(opacity * 255);\n}\n\nexport function opacifyHex(hexCode: string, opacity: number): string {\n const c = d3color(hexCode);\n if (!c) {\n console.warn('Invalid color: ', hexCode);\n return `rgba(255, 255, 255, ${opacity})`;\n }\n const col = c.rgb();\n return `rgba(${col.r}, ${col.g}, ${col.b}, ${opacity})`;\n}\n\nexport function colorAsRgba(color: string | number[]): RGBA {\n if (Array.isArray(color)) {\n return color as RGBA;\n }\n const col = d3color(color);\n if (!col) {\n console.warn('Invalid color: ', color);\n return FALLBACK_COLOR_RGBA;\n }\n const rgbColor = col.rgb();\n return [\n Math.floor(rgbColor.r),\n Math.floor(rgbColor.g),\n Math.floor(rgbColor.b),\n opacityFloatToInteger(col.opacity),\n ];\n}\n\nfunction colorAsRgbaOr(\n color: string | undefined,\n defaultColor: RGBA | string,\n): RGBA {\n if (color) {\n return colorAsRgba(color);\n }\n if (typeof defaultColor === 'string') {\n return colorAsRgba(defaultColor);\n }\n return defaultColor;\n}\n\nconst asScheme = (scheme: ReadonlyArray>) =>\n scheme[scheme.length - 1] as string[];\n\nexport enum ColorScheme {\n primary = '#162d3c',\n}\n\nconst SCALE_NUM_STEPS = 20;\nconst getColorSteps = (interpolate: (x: number) => string) =>\n range(0, SCALE_NUM_STEPS + 1)\n .map((i) => interpolate(i / SCALE_NUM_STEPS))\n .reverse();\n\nconst FLOW_MIN_COLOR = 'rgba(240,240,240,0.5)';\nexport const GRAYISH = [FLOW_MIN_COLOR, ColorScheme.primary];\nconst schemeBluYl = [\n '#f7feae',\n '#b7e6a5',\n '#7ccba2',\n '#46aea0',\n '#089099',\n '#00718b',\n '#045275',\n];\n\nconst schemeEmrld = [\n '#d3f2a3',\n '#97e196',\n '#6cc08b',\n '#4c9b82',\n '#217a79',\n '#105965',\n '#074050',\n];\n\nexport const schemeTeal = [\n '#d1eeea',\n '#a8dbd9',\n '#85c4c9',\n '#68abb8',\n '#4f90a6',\n '#3b738f',\n '#2a5674',\n];\n\nexport const DEFAULT_COLOR_SCHEME = schemeTeal;\nexport const COLOR_SCHEMES: {[key: string]: string[]} = {\n Blues: asScheme(schemeBlues),\n BluGrn: [\n '#c4e6c3',\n '#96d2a4',\n '#6dbc90',\n '#4da284',\n '#36877a',\n '#266b6e',\n '#1d4f60',\n ],\n BluYl: schemeBluYl,\n BrwnYl: [\n '#ede5cf',\n '#e0c2a2',\n '#d39c83',\n '#c1766f',\n '#a65461',\n '#813753',\n '#541f3f',\n ],\n BuGn: asScheme(schemeBuGn),\n BuPu: asScheme(schemeBuPu),\n Burg: [\n '#ffc6c4',\n '#f4a3a8',\n '#e38191',\n '#cc607d',\n '#ad466c',\n '#8b3058',\n '#672044',\n ],\n BurgYl: [\n '#fbe6c5',\n '#f5ba98',\n '#ee8a82',\n '#dc7176',\n '#c8586c',\n '#9c3f5d',\n '#70284a',\n ],\n Cool: getColorSteps(interpolateCool),\n DarkMint: [\n '#d2fbd4',\n '#a5dbc2',\n '#7bbcb0',\n '#559c9e',\n '#3a7c89',\n '#235d72',\n '#123f5a',\n ],\n Emrld: schemeEmrld,\n GnBu: asScheme(schemeGnBu),\n Grayish: GRAYISH,\n Greens: asScheme(schemeGreens),\n Greys: asScheme(schemeGreys),\n Inferno: getColorSteps(interpolateInferno),\n Magenta: [\n '#f3cbd3',\n '#eaa9bd',\n '#dd88ac',\n '#ca699d',\n '#b14d8e',\n '#91357d',\n '#6c2167',\n ],\n Magma: getColorSteps(interpolateMagma),\n Mint: [\n '#e4f1e1',\n '#b4d9cc',\n '#89c0b6',\n '#63a6a0',\n '#448c8a',\n '#287274',\n '#0d585f',\n ],\n Oranges: asScheme(schemeOranges),\n OrRd: asScheme(schemeOrRd),\n OrYel: [\n '#ecda9a',\n '#efc47e',\n '#f3ad6a',\n '#f7945d',\n '#f97b57',\n '#f66356',\n '#ee4d5a',\n ],\n Peach: [\n '#fde0c5',\n '#facba6',\n '#f8b58b',\n '#f59e72',\n '#f2855d',\n '#ef6a4c',\n '#eb4a40',\n ],\n Plasma: getColorSteps(interpolatePlasma),\n PinkYl: [\n '#fef6b5',\n '#ffdd9a',\n '#ffc285',\n '#ffa679',\n '#fa8a76',\n '#f16d7a',\n '#e15383',\n ],\n PuBu: asScheme(schemePuBu),\n PuBuGn: asScheme(schemePuBuGn),\n PuRd: asScheme(schemePuRd),\n Purp: [\n '#f3e0f7',\n '#e4c7f1',\n '#d1afe8',\n '#b998dd',\n '#9f82ce',\n '#826dba',\n '#63589f',\n ],\n Purples: asScheme(schemePurples),\n PurpOr: [\n '#f9ddda',\n '#f2b9c4',\n '#e597b9',\n '#ce78b3',\n '#ad5fad',\n '#834ba0',\n '#573b88',\n ],\n RdPu: asScheme(schemeRdPu),\n RedOr: [\n '#f6d2a9',\n '#f5b78e',\n '#f19c7c',\n '#ea8171',\n '#dd686c',\n '#ca5268',\n '#b13f64',\n ],\n Reds: asScheme(schemeReds),\n Sunset: [\n '#f3e79b',\n '#fac484',\n '#f8a07e',\n '#eb7f86',\n '#ce6693',\n '#a059a0',\n '#5c53a5',\n ],\n SunsetDark: [\n '#fcde9c',\n '#faa476',\n '#f0746e',\n '#e34f6f',\n '#dc3977',\n '#b9257a',\n '#7c1d6f',\n ],\n Teal: schemeTeal,\n TealGrn: [\n '#b0f2bc',\n '#89e8ac',\n '#67dba5',\n '#4cc8a3',\n '#38b2a3',\n '#2c98a0',\n '#257d98',\n ],\n Viridis: getColorSteps(interpolateViridis),\n Warm: getColorSteps(interpolateWarm),\n YlGn: asScheme(schemeYlGn),\n YlGnBu: asScheme(schemeYlGnBu),\n YlOrBr: asScheme(schemeYlOrBr),\n YlOrRd: asScheme(schemeYlOrRd),\n};\n\nexport const COLOR_SCHEME_KEYS = Object.keys(COLOR_SCHEMES);\n\nconst complementary = '#f52020';\nconst baseDiffColor = '#17a5be';\n\nconst diffColors: DiffColors = {\n negative: {\n flows: {\n scheme: [FLOW_MIN_COLOR, baseDiffColor],\n },\n },\n positive: {\n flows: {\n scheme: [FLOW_MIN_COLOR, complementary],\n },\n },\n locationAreas: {\n outline: 'rgba(92,112,128,0.5)',\n normal: 'rgba(220,220,220,0.5)',\n },\n outlineColor: 'rgb(230,233,237)',\n};\n\nexport function getFlowmapColors(settings: SettingsState): Colors | DiffColors {\n return getColors(\n false, // TODO: diffMode\n settings.colorScheme,\n settings.darkMode,\n settings.fadeEnabled,\n settings.fadeOpacityEnabled,\n settings.fadeAmount,\n isAnimatedFlowLinesMode(settings.flowLinesRenderingMode),\n );\n}\n\nfunction isAnimatedFlowLinesMode(\n flowLinesRenderingMode: FlowLinesRenderingMode,\n): boolean {\n return flowLinesRenderingMode === 'animated-straight';\n}\n\nexport function getColors(\n diffMode: boolean,\n colorScheme: string | string[] | undefined,\n darkMode: boolean,\n fadeEnabled: boolean,\n fadeOpacityEnabled: boolean,\n fadeAmount: number,\n animate: boolean,\n): Colors | DiffColors {\n if (diffMode) {\n return diffColors;\n }\n\n let scheme;\n\n if (Array.isArray(colorScheme)) {\n scheme = colorScheme;\n } else {\n scheme =\n (colorScheme && COLOR_SCHEMES[colorScheme]) || DEFAULT_COLOR_SCHEME;\n if (darkMode) {\n scheme = scheme.slice().reverse();\n }\n }\n\n // if (animate)\n // if (fadeAmount > 0)\n {\n const indices = range(0, Math.max(10, scheme.length));\n const N = indices.length - 1;\n const colorScale = scaleSequential(interpolateRgbBasis(scheme)).domain([\n 0,\n N,\n ]);\n\n if (!fadeEnabled || fadeAmount === 0) {\n scheme = indices.map((c, i) => colorScale(i));\n } else {\n const amount = scalePow()\n // .exponent(animate ? 1 : 1/2.5)\n // .exponent(animate ? 100 : 50)\n // .exponent(animate ? 20 : 5)\n // .exponent(1/2.5)\n .exponent(1.5)\n .domain([N, 0])\n // .range([fadeAmount/100*(animate?2:1), 0])\n // .range([0, fadeAmount/100*(animate?2:1)])\n // .range(darkMode ? [1-fadeAmount/100, 1] : [1, 1 - fadeAmount/100])\n // .range(darkMode ? [1 - fadeAmount/100, 1] : [fadeAmount/100, 0])\n // .range([1 - fadeAmount/100, 1])\n .range([0, (2 * fadeAmount) / 100]);\n\n scheme = indices.map(\n (c, i) => {\n const color = colorScale(i);\n const a = amount(i);\n if (color == null || a == null) return '#000';\n const col = hcl(color);\n col.l = darkMode ? col.l - col.l * a : col.l + (100 - col.l) * a;\n col.c = col.c - col.c * (a / 4);\n if (fadeOpacityEnabled) {\n col.opacity = col.opacity * (1.0 - a);\n }\n return col.toString();\n },\n // interpolateRgbBasis([colorScale(i), darkMode ? '#000' : '#fff'])(amount(i))\n // interpolateHsl(colorScale(i), darkMode ? '#000' : '#fff')(amount(i)).toString()\n );\n }\n }\n\n return {\n darkMode,\n flows: {\n scheme,\n },\n locationCircles: {\n outgoing: darkMode ? '#000' : '#fff',\n },\n outlineColor: darkMode ? '#000' : 'rgba(255, 255, 255, 0.5)',\n };\n}\n\nfunction interpolateRgbaBasis(colors: string[]) {\n const spline = interpolateBasis;\n const n = colors.length;\n let r: any = new Array(n),\n g: any = new Array(n),\n b: any = new Array(n),\n opacity: any = new Array(n),\n i,\n color: any;\n for (i = 0; i < n; ++i) {\n color = colorRgb(colors[i]);\n r[i] = color.r || 0;\n g[i] = color.g || 0;\n b[i] = color.b || 0;\n opacity[i] = color.opacity || 0;\n }\n r = spline(r);\n g = spline(g);\n b = spline(b);\n opacity = spline(opacity);\n // color.opacity = 1;\n return function (t: number) {\n color.r = r(t);\n color.g = g(t);\n color.b = b(t);\n color.opacity = opacity(t);\n return color + '';\n };\n}\n\nexport function createFlowColorScale(\n domain: [number, number],\n scheme: string[],\n animate: boolean | undefined,\n): ColorScale {\n const scale = scaleSequentialPow(interpolateRgbaBasis(scheme))\n // @ts-ignore\n .exponent(animate ? 1 / 2 : 1 / 3)\n .domain(domain);\n\n return (value: number) => colorAsRgba(scale(value));\n}\n\nexport function getFlowColorScale(\n colors: ColorsRGBA | DiffColorsRGBA,\n magnitudeExtent: [number, number] | undefined,\n animate: boolean | undefined,\n): (magnitude: number) => [number, number, number, number] {\n const minMagnitude = magnitudeExtent ? magnitudeExtent[0] : 0;\n const maxMagnitude = magnitudeExtent ? magnitudeExtent[1] : 0;\n if (isDiffColorsRGBA(colors)) {\n const posScale = createFlowColorScale(\n [0, maxMagnitude],\n colors.positive.flows.scheme,\n animate,\n );\n const negScale = createFlowColorScale(\n [0, minMagnitude],\n colors.negative.flows.scheme,\n animate,\n );\n\n return (magnitude: number) =>\n magnitude >= 0 ? posScale(magnitude) : negScale(magnitude);\n }\n\n const scale = createFlowColorScale(\n [0, maxMagnitude || 0],\n colors.flows.scheme,\n animate,\n );\n return (magnitude: number) => scale(magnitude);\n}\n\nexport function isDiffColors(\n colors: DiffColors | Colors,\n): colors is DiffColors {\n return (colors as DiffColors).positive !== undefined;\n}\n\nexport function isDiffColorsRGBA(\n colors: DiffColorsRGBA | ColorsRGBA,\n): colors is DiffColorsRGBA {\n return (colors as DiffColorsRGBA).positive !== undefined;\n}\n\nfunction getLocationAreaColorsRGBA(\n colors: LocationAreaColors | undefined,\n darkMode: boolean,\n): LocationAreaColorsRGBA {\n const normalColor = (colors && colors.normal) || DEFAULT_LOCATION_AREA_COLOR;\n const normalColorHcl = hcl(normalColor);\n const locationAreasNormal = colorAsRgba(normalColor);\n return {\n normal: locationAreasNormal,\n connected: colorAsRgbaOr(colors && colors.connected, locationAreasNormal),\n highlighted: colorAsRgbaOr(\n colors && colors.highlighted,\n opacifyHex(\n normalColorHcl[darkMode ? 'brighter' : 'darker'](1).toString(),\n 0.5,\n ),\n ),\n selected: colorAsRgbaOr(\n colors && colors.selected,\n opacifyHex(\n normalColorHcl[darkMode ? 'brighter' : 'darker'](2).toString(),\n 0.8,\n ),\n ),\n outline: colorAsRgbaOr(\n colors && colors.outline,\n colorAsRgba(\n normalColorHcl[darkMode ? 'brighter' : 'darker'](4).toString(),\n ),\n ),\n };\n}\n\nexport interface FlowColors {\n scheme?: string[];\n highlighted?: string;\n}\n\nexport interface LocationCircleColors {\n inner?: string;\n outgoing?: string;\n incoming?: string;\n highlighted?: string;\n empty?: string;\n outlineEmptyMix?: number;\n}\n\nexport interface LocationAreaColors {\n outline?: string;\n normal?: string;\n selected?: string;\n highlighted?: string;\n connected?: string;\n}\n\nexport interface BaseColors {\n darkMode?: boolean;\n locationAreas?: LocationAreaColors;\n dimmedOpacity?: number;\n outlineColor?: string;\n}\n\nexport interface Colors extends BaseColors {\n flows?: FlowColors;\n locationCircles?: LocationCircleColors;\n}\n\nexport interface FlowAndCircleColors {\n flows?: FlowColors;\n locationCircles?: LocationCircleColors;\n}\n\nexport interface DiffColors extends BaseColors {\n positive?: FlowAndCircleColors;\n negative?: FlowAndCircleColors;\n}\n\n// The xxxColorsRGBA objects are mirroring the input colors' objects,\n// but converted to RGBA and with all the omitted ones set to defaults\n// or derived.\nexport interface FlowColorsRGBA {\n scheme: string[];\n highlighted: RGBA;\n}\n\nexport interface LocationCircleColorsRGBA {\n inner: RGBA;\n outgoing: RGBA;\n incoming: RGBA;\n highlighted: RGBA;\n empty: RGBA;\n outlineEmptyMix: number;\n}\n\nexport interface LocationAreaColorsRGBA {\n outline: RGBA;\n normal: RGBA;\n selected: RGBA;\n highlighted: RGBA;\n connected: RGBA;\n}\n\nexport interface BaseColorsRGBA {\n darkMode: boolean;\n locationAreas: LocationAreaColorsRGBA;\n dimmedOpacity: number;\n outlineColor: RGBA;\n}\n\nexport interface ColorsRGBA extends BaseColorsRGBA {\n flows: FlowColorsRGBA;\n locationCircles: LocationCircleColorsRGBA;\n}\n\nexport interface FlowAndCircleColorsRGBA {\n flows: FlowColorsRGBA;\n locationCircles: LocationCircleColorsRGBA;\n}\n\nexport interface DiffColorsRGBA extends BaseColorsRGBA {\n positive: FlowAndCircleColorsRGBA;\n negative: FlowAndCircleColorsRGBA;\n}\n\nfunction getFlowAndCircleColors(\n inputColors: FlowAndCircleColors | undefined,\n defaultFlowColorScheme: string[],\n darkMode: boolean,\n): FlowAndCircleColorsRGBA {\n const flowColorScheme =\n (inputColors && inputColors.flows && inputColors.flows.scheme) ||\n defaultFlowColorScheme;\n const maxFlowColorHcl = hcl(flowColorScheme[flowColorScheme.length - 1]);\n const flowColorHighlighted = colorAsRgbaOr(\n inputColors && inputColors.flows && inputColors.flows.highlighted,\n colorAsRgba(\n maxFlowColorHcl[darkMode ? 'brighter' : 'darker'](0.7).toString(),\n ),\n );\n\n const emptyColor = colorAsRgbaOr(\n inputColors?.locationCircles?.empty,\n darkMode ? '#000' : '#fff',\n );\n const innerColor = colorAsRgbaOr(\n inputColors &&\n inputColors.locationCircles &&\n inputColors.locationCircles.inner,\n maxFlowColorHcl.toString(),\n );\n return {\n flows: {\n scheme: flowColorScheme,\n highlighted: flowColorHighlighted,\n },\n locationCircles: {\n inner: innerColor,\n outgoing: colorAsRgbaOr(\n inputColors &&\n inputColors.locationCircles &&\n inputColors.locationCircles.outgoing,\n darkMode ? '#000' : '#fff',\n ),\n incoming: colorAsRgbaOr(\n inputColors &&\n inputColors.locationCircles &&\n inputColors.locationCircles.incoming,\n maxFlowColorHcl[darkMode ? 'brighter' : 'darker'](1.25).toString(),\n ),\n highlighted: colorAsRgbaOr(\n inputColors &&\n inputColors.locationCircles &&\n inputColors.locationCircles.highlighted,\n flowColorHighlighted,\n ),\n empty: emptyColor,\n outlineEmptyMix: inputColors?.locationCircles?.outlineEmptyMix ?? 0.4,\n },\n };\n}\n\nfunction getBaseColorsRGBA(\n colors: Colors | DiffColors | undefined,\n): BaseColorsRGBA {\n const darkMode = colors && colors.darkMode ? true : false;\n return {\n darkMode,\n locationAreas: getLocationAreaColorsRGBA(\n colors && colors.locationAreas,\n darkMode,\n ),\n outlineColor: colorAsRgba(\n (colors && colors.outlineColor) || DEFAULT_OUTLINE_COLOR,\n ),\n dimmedOpacity:\n colors && colors.dimmedOpacity != null\n ? colors.dimmedOpacity\n : DEFAULT_DIMMED_OPACITY,\n };\n}\n\nexport function getColorsRGBA(colors: Colors | undefined): ColorsRGBA {\n const baseColorsRGBA = getBaseColorsRGBA(colors);\n return {\n ...baseColorsRGBA,\n ...getFlowAndCircleColors(\n colors,\n DEFAULT_FLOW_COLOR_SCHEME,\n baseColorsRGBA.darkMode,\n ),\n };\n}\n\nexport function getDiffColorsRGBA(\n colors: DiffColors | undefined,\n): DiffColorsRGBA {\n const baseColorsRGBA = getBaseColorsRGBA(colors);\n return {\n ...baseColorsRGBA,\n positive: getFlowAndCircleColors(\n colors && colors.positive,\n DEFAULT_FLOW_COLOR_SCHEME_POSITIVE,\n baseColorsRGBA.darkMode,\n ),\n negative: getFlowAndCircleColors(\n colors && colors.negative,\n DEFAULT_FLOW_COLOR_SCHEME_NEGATIVE,\n baseColorsRGBA.darkMode,\n ),\n };\n}\n\nexport function rgbaAsString(color: RGBA): string {\n return `rgba(${color.join(',')})`;\n}\n\nexport function midpoint(a: number, b: number, zeroToOne: number): number {\n return a + (b - a) * zeroToOne;\n}\n\nexport function mixColorsRGBA(\n color1: RGBA,\n color2: RGBA,\n zeroToOne: number,\n): RGBA {\n return color1.map((v, i) => midpoint(v, color2[i], zeroToOne)) as RGBA;\n}\n\nexport default getColors;\n","\nconst ARRAY_TYPES = [\n Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array,\n Int32Array, Uint32Array, Float32Array, Float64Array\n];\n\n/** @typedef {Int8ArrayConstructor | Uint8ArrayConstructor | Uint8ClampedArrayConstructor | Int16ArrayConstructor | Uint16ArrayConstructor | Int32ArrayConstructor | Uint32ArrayConstructor | Float32ArrayConstructor | Float64ArrayConstructor} TypedArrayConstructor */\n/** @typedef {Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array} TypedArray */\n\nconst VERSION = 1; // serialized format version\nconst HEADER_SIZE = 8;\n\n// Shared scratch stack for iterative DFS in range/within. Sized for the worst case:\n// 3 ints per frame * (treeHeight + 1), with treeHeight ≤ ceil(log2(2^32 / 3)) ≈ 31.\nconst STACK = new Uint32Array(96);\n\nexport default class KDBush {\n\n /**\n * Creates an index from raw `ArrayBuffer` data.\n * @param {ArrayBufferLike} data\n */\n static from(data) {\n // @ts-expect-error duck typing array buffers\n if (!data || data.byteLength === undefined || data.buffer) {\n throw new Error('Data must be an instance of ArrayBuffer or SharedArrayBuffer.');\n }\n const [magic, versionAndType] = new Uint8Array(data, 0, 2);\n if (magic !== 0xdb) {\n throw new Error('Data does not appear to be in a KDBush format.');\n }\n const version = versionAndType >> 4;\n if (version !== VERSION) {\n throw new Error(`Got v${version} data when expected v${VERSION}.`);\n }\n const ArrayType = ARRAY_TYPES[versionAndType & 0x0f];\n if (!ArrayType) {\n throw new Error('Unrecognized array type.');\n }\n const [nodeSize] = new Uint16Array(data, 2, 1);\n const [numItems] = new Uint32Array(data, 4, 1);\n\n return new KDBush(numItems, nodeSize, ArrayType, undefined, data);\n }\n\n /**\n * Creates an index that will hold a given number of items.\n * @param {number} numItems\n * @param {number} [nodeSize=64] Size of the KD-tree node (64 by default).\n * @param {TypedArrayConstructor} [ArrayType=Float64Array] The array type used for coordinates storage (`Float64Array` by default).\n * @param {ArrayBufferConstructor | SharedArrayBufferConstructor} [ArrayBufferType=ArrayBuffer] The array buffer type used for storage (`ArrayBuffer` by default).\n * @param {ArrayBufferLike} [data] (For internal use only)\n */\n constructor(numItems, nodeSize = 64, ArrayType = Float64Array, ArrayBufferType = ArrayBuffer, data) {\n if (isNaN(numItems) || numItems < 0) throw new Error(`Unexpected numItems value: ${numItems}.`);\n\n this.numItems = +numItems;\n this.nodeSize = Math.min(Math.max(+nodeSize, 2), 65535);\n this.ArrayType = ArrayType;\n this.IndexArrayType = numItems < 65536 ? Uint16Array : Uint32Array;\n\n const arrayTypeIndex = ARRAY_TYPES.indexOf(this.ArrayType);\n const coordsByteSize = numItems * 2 * this.ArrayType.BYTES_PER_ELEMENT;\n const idsByteSize = numItems * this.IndexArrayType.BYTES_PER_ELEMENT;\n const padCoords = (8 - idsByteSize % 8) % 8;\n\n if (arrayTypeIndex < 0) {\n throw new Error(`Unexpected typed array class: ${ArrayType}.`);\n }\n\n if (data) { // reconstruct an index from a buffer\n this.data = data;\n // @ts-expect-error TS can't handle SharedArrayBuffer overloads\n this.ids = new this.IndexArrayType(data, HEADER_SIZE, numItems);\n // @ts-expect-error TS can't handle SharedArrayBuffer overloads\n this.coords = new ArrayType(data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2);\n this._pos = numItems * 2;\n this._finished = true;\n\n } else { // initialize a new index\n const data = this.data = new ArrayBufferType(HEADER_SIZE + coordsByteSize + idsByteSize + padCoords);\n // @ts-expect-error TS can't handle SharedArrayBuffer overloads\n this.ids = new this.IndexArrayType(data, HEADER_SIZE, numItems);\n // @ts-expect-error TS can't handle SharedArrayBuffer overloads\n this.coords = new ArrayType(data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2);\n this._pos = 0;\n this._finished = false;\n\n // set header\n new Uint8Array(data, 0, 2).set([0xdb, (VERSION << 4) + arrayTypeIndex]);\n new Uint16Array(data, 2, 1)[0] = nodeSize;\n new Uint32Array(data, 4, 1)[0] = numItems;\n }\n }\n\n /**\n * Add a point to the index.\n * @param {number} x\n * @param {number} y\n * @returns {number} An incremental index associated with the added item (starting from `0`).\n */\n add(x, y) {\n const index = this._pos >> 1;\n this.ids[index] = index;\n this.coords[this._pos++] = x;\n this.coords[this._pos++] = y;\n return index;\n }\n\n /**\n * Perform indexing of the added points.\n */\n finish() {\n const numAdded = this._pos >> 1;\n if (numAdded !== this.numItems) {\n throw new Error(`Added ${numAdded} items when expected ${this.numItems}.`);\n }\n // kd-sort both arrays for efficient search\n sort(this.ids, this.coords, this.nodeSize, 0, this.numItems - 1, 0);\n\n this._finished = true;\n return this;\n }\n\n /**\n * Search the index for items within a given bounding box.\n * @param {number} minX\n * @param {number} minY\n * @param {number} maxX\n * @param {number} maxY\n * @returns {number[]} An array of indices correponding to the found items.\n */\n range(minX, minY, maxX, maxY) {\n if (!this._finished) throw new Error('Data not yet indexed - call index.finish().');\n\n const {ids, coords, nodeSize} = this;\n STACK[0] = 0;\n STACK[1] = ids.length - 1;\n STACK[2] = 0;\n let sp = 3;\n const result = [];\n\n // recursively search for items in range in the kd-sorted arrays\n while (sp > 0) {\n const axis = STACK[--sp];\n const right = STACK[--sp];\n const left = STACK[--sp];\n\n // if we reached \"tree node\", search linearly\n if (right - left <= nodeSize) {\n for (let i = left; i <= right; i++) {\n const x = coords[2 * i];\n const y = coords[2 * i + 1];\n if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[i]);\n }\n continue;\n }\n\n // otherwise find the middle index\n const m = (left + right) >> 1;\n\n // include the middle item if it's in range\n const x = coords[2 * m];\n const y = coords[2 * m + 1];\n if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[m]);\n\n // queue search in halves that intersect the query\n if (axis === 0 ? minX <= x : minY <= y) {\n STACK[sp++] = left;\n STACK[sp++] = m - 1;\n STACK[sp++] = 1 - axis;\n }\n if (axis === 0 ? maxX >= x : maxY >= y) {\n STACK[sp++] = m + 1;\n STACK[sp++] = right;\n STACK[sp++] = 1 - axis;\n }\n }\n\n return result;\n }\n\n /**\n * Search the index for items within a given radius.\n * @param {number} qx\n * @param {number} qy\n * @param {number} r Query radius.\n * @returns {number[]} An array of indices correponding to the found items.\n */\n within(qx, qy, r) {\n const result = /** @type {number[]} */ ([]);\n this.withinInto(qx, qy, r, result);\n return result;\n }\n\n /**\n * Search the index for items within a given radius, writing matching ids into `out`\n * via indexed assignment (`out[i] = id`). Accepts any indexed-writable container —\n * a typed array sized to the expected upper bound (allocation-free, fast) or a plain\n * `Array` (which will grow as needed). Returns the number of matches written.\n * @param {number} qx\n * @param {number} qy\n * @param {number} r Query radius.\n * @param {number[] | TypedArray} out Container to write matching ids into.\n * @returns {number} The number of matches written to `out`.\n */\n withinInto(qx, qy, r, out) {\n if (!this._finished) throw new Error('Data not yet indexed - call index.finish().');\n\n const {ids, coords, nodeSize} = this;\n STACK[0] = 0;\n STACK[1] = ids.length - 1;\n STACK[2] = 0;\n let sp = 3;\n let count = 0;\n const r2 = r * r;\n\n // recursively search for items within radius in the kd-sorted arrays\n while (sp > 0) {\n const axis = STACK[--sp];\n const right = STACK[--sp];\n const left = STACK[--sp];\n\n // if we reached \"tree node\", search linearly\n if (right - left <= nodeSize) {\n for (let i = left; i <= right; i++) {\n if (sqDist(coords[2 * i], coords[2 * i + 1], qx, qy) <= r2) out[count++] = ids[i];\n }\n continue;\n }\n\n // otherwise find the middle index\n const m = (left + right) >> 1;\n\n // include the middle item if it's in range\n const x = coords[2 * m];\n const y = coords[2 * m + 1];\n if (sqDist(x, y, qx, qy) <= r2) out[count++] = ids[m];\n\n // queue search in halves that intersect the query\n if (axis === 0 ? qx - r <= x : qy - r <= y) {\n STACK[sp++] = left;\n STACK[sp++] = m - 1;\n STACK[sp++] = 1 - axis;\n }\n if (axis === 0 ? qx + r >= x : qy + r >= y) {\n STACK[sp++] = m + 1;\n STACK[sp++] = right;\n STACK[sp++] = 1 - axis;\n }\n }\n\n return count;\n }\n}\n\n/**\n * @param {Uint16Array | Uint32Array} ids\n * @param {TypedArray} coords\n * @param {number} nodeSize\n * @param {number} left\n * @param {number} right\n * @param {number} axis\n */\nfunction sort(ids, coords, nodeSize, left, right, axis) {\n if (right - left <= nodeSize) return;\n\n const m = (left + right) >> 1; // middle index\n\n // sort ids and coords around the middle index so that the halves lie\n // either left/right or top/bottom correspondingly (taking turns)\n select(ids, coords, m, left, right, axis);\n\n // recursively kd-sort first half and second half on the opposite axis\n sort(ids, coords, nodeSize, left, m - 1, 1 - axis);\n sort(ids, coords, nodeSize, m + 1, right, 1 - axis);\n}\n\n/**\n * Custom Floyd-Rivest selection algorithm: sort ids and coords so that\n * [left..k-1] items are smaller than k-th item (on either x or y axis)\n * @param {Uint16Array | Uint32Array} ids\n * @param {TypedArray} coords\n * @param {number} k\n * @param {number} left\n * @param {number} right\n * @param {number} axis\n */\nfunction select(ids, coords, k, left, right, axis) {\n\n while (right > left) {\n if (right - left > 600) {\n const n = right - left + 1;\n const m = k - left + 1;\n const z = Math.log(n);\n const s = 0.5 * Math.exp(2 * z / 3);\n const sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);\n const newLeft = Math.max(left, Math.floor(k - m * s / n + sd));\n const newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));\n select(ids, coords, k, newLeft, newRight, axis);\n }\n\n const t = coords[2 * k + axis];\n let i = left;\n let j = right;\n\n swapItem(ids, coords, left, k);\n if (coords[2 * right + axis] > t) swapItem(ids, coords, left, right);\n\n while (i < j) {\n swapItem(ids, coords, i, j);\n i++;\n j--;\n while (coords[2 * i + axis] < t) i++;\n while (coords[2 * j + axis] > t) j--;\n }\n\n if (coords[2 * left + axis] === t) swapItem(ids, coords, left, j);\n else {\n j++;\n swapItem(ids, coords, j, right);\n }\n\n if (j <= k) left = j + 1;\n if (k <= j) right = j - 1;\n }\n}\n\n/**\n * @param {Uint16Array | Uint32Array} ids\n * @param {TypedArray} coords\n * @param {number} i\n * @param {number} j\n */\nfunction swapItem(ids, coords, i, j) {\n swap(ids, i, j);\n swap(coords, 2 * i, 2 * j);\n swap(coords, 2 * i + 1, 2 * j + 1);\n}\n\n/**\n * @param {TypedArray} arr\n * @param {number} i\n * @param {number} j\n */\nfunction swap(arr, i, j) {\n const tmp = arr[i];\n arr[i] = arr[j];\n arr[j] = tmp;\n}\n\n/**\n * @param {number} ax\n * @param {number} ay\n * @param {number} bx\n * @param {number} by\n */\nfunction sqDist(ax, ay, bx, by) {\n const dx = ax - bx;\n const dy = ay - by;\n return dx * dx + dy * dy;\n}\n","import type { AnyFunction } from '../types'\n\n/**\n * Runs a check to determine if the given result function behaves as an\n * identity function. An identity function is one that returns its\n * input unchanged, for example, `x => x`. This check helps ensure\n * efficient memoization and prevent unnecessary re-renders by encouraging\n * proper use of transformation logic in result functions and\n * extraction logic in input selectors.\n *\n * @param resultFunc - The result function to be checked.\n * @param inputSelectorsResults - The results of the input selectors.\n * @param outputSelectorResult - The result of the output selector.\n *\n * @see {@link https://reselect.js.org/api/development-only-stability-checks#identityfunctioncheck `identityFunctionCheck`}\n *\n * @since 5.0.0\n * @internal\n */\nexport const runIdentityFunctionCheck = (\n resultFunc: AnyFunction,\n inputSelectorsResults: unknown[],\n outputSelectorResult: unknown\n) => {\n if (\n inputSelectorsResults.length === 1 &&\n inputSelectorsResults[0] === outputSelectorResult\n ) {\n let isInputSameAsOutput = false\n try {\n const emptyObject = {}\n if (resultFunc(emptyObject) === emptyObject) isInputSameAsOutput = true\n } catch {\n // Do nothing\n }\n if (isInputSameAsOutput) {\n let stack: string | undefined = undefined\n try {\n throw new Error()\n } catch (e) {\n // eslint-disable-next-line @typescript-eslint/no-extra-semi, no-extra-semi\n ;({ stack } = e as Error)\n }\n console.warn(\n 'The result function returned its own inputs without modification. e.g' +\n '\\n`createSelector([state => state.todos], todos => todos)`' +\n '\\nThis could lead to inefficient memoization and unnecessary re-renders.' +\n '\\nEnsure transformation logic is in the result function, and extraction logic is in the input selectors.',\n { stack }\n )\n }\n }\n}\n","import type { CreateSelectorOptions, UnknownMemoizer } from '../types'\n\n/**\n * Runs a stability check to ensure the input selector results remain stable\n * when provided with the same arguments. This function is designed to detect\n * changes in the output of input selectors, which can impact the performance of memoized selectors.\n *\n * @param inputSelectorResultsObject - An object containing two arrays: `inputSelectorResults` and `inputSelectorResultsCopy`, representing the results of input selectors.\n * @param options - Options object consisting of a `memoize` function and a `memoizeOptions` object.\n * @param inputSelectorArgs - List of arguments being passed to the input selectors.\n *\n * @see {@link https://reselect.js.org/api/development-only-stability-checks/#inputstabilitycheck `inputStabilityCheck`}\n *\n * @since 5.0.0\n * @internal\n */\nexport const runInputStabilityCheck = (\n inputSelectorResultsObject: {\n inputSelectorResults: unknown[]\n inputSelectorResultsCopy: unknown[]\n },\n options: Required<\n Pick<\n CreateSelectorOptions,\n 'memoize' | 'memoizeOptions'\n >\n >,\n inputSelectorArgs: unknown[] | IArguments\n) => {\n const { memoize, memoizeOptions } = options\n const { inputSelectorResults, inputSelectorResultsCopy } =\n inputSelectorResultsObject\n const createAnEmptyObject = memoize(() => ({}), ...memoizeOptions)\n // if the memoize method thinks the parameters are equal, these *should* be the same reference\n const areInputSelectorResultsEqual =\n createAnEmptyObject.apply(null, inputSelectorResults) ===\n createAnEmptyObject.apply(null, inputSelectorResultsCopy)\n if (!areInputSelectorResultsEqual) {\n let stack: string | undefined = undefined\n try {\n throw new Error()\n } catch (e) {\n // eslint-disable-next-line @typescript-eslint/no-extra-semi, no-extra-semi\n ;({ stack } = e as Error)\n }\n console.warn(\n 'An input selector returned a different result when passed same arguments.' +\n '\\nThis means your output selector will likely run more frequently than intended.' +\n '\\nAvoid returning a new reference inside your input selector, e.g.' +\n '\\n`createSelector([state => state.todos.map(todo => todo.id)], todoIds => todoIds.length)`',\n {\n arguments: inputSelectorArgs,\n firstInputs: inputSelectorResults,\n secondInputs: inputSelectorResultsCopy,\n stack\n }\n )\n }\n}\n","import type { DevModeChecks } from '../types'\n\n/**\n * Global configuration for development mode checks. This specifies the default\n * frequency at which each development mode check should be performed.\n *\n * @since 5.0.0\n * @internal\n */\nexport const globalDevModeChecks: DevModeChecks = {\n inputStabilityCheck: 'once',\n identityFunctionCheck: 'once'\n}\n\n/**\n * Overrides the development mode checks settings for all selectors.\n *\n * Reselect performs additional checks in development mode to help identify and\n * warn about potential issues in selector behavior. This function allows you to\n * customize the behavior of these checks across all selectors in your application.\n *\n * **Note**: This setting can still be overridden per selector inside `createSelector`'s `options` object.\n * See {@link https://github.com/reduxjs/reselect#2-per-selector-by-passing-an-identityfunctioncheck-option-directly-to-createselector per-selector-configuration}\n * and {@linkcode CreateSelectorOptions.identityFunctionCheck identityFunctionCheck} for more details.\n *\n * _The development mode checks do not run in production builds._\n *\n * @param devModeChecks - An object specifying the desired settings for development mode checks. You can provide partial overrides. Unspecified settings will retain their current values.\n *\n * @example\n * ```ts\n * import { setGlobalDevModeChecks } from 'reselect'\n * import { DevModeChecks } from '../types'\n *\n * // Run only the first time the selector is called. (default)\n * setGlobalDevModeChecks({ inputStabilityCheck: 'once' })\n *\n * // Run every time the selector is called.\n * setGlobalDevModeChecks({ inputStabilityCheck: 'always' })\n *\n * // Never run the input stability check.\n * setGlobalDevModeChecks({ inputStabilityCheck: 'never' })\n *\n * // Run only the first time the selector is called. (default)\n * setGlobalDevModeChecks({ identityFunctionCheck: 'once' })\n *\n * // Run every time the selector is called.\n * setGlobalDevModeChecks({ identityFunctionCheck: 'always' })\n *\n * // Never run the identity function check.\n * setGlobalDevModeChecks({ identityFunctionCheck: 'never' })\n * ```\n * @see {@link https://reselect.js.org/api/development-only-stability-checks Development-Only Stability Checks}\n * @see {@link https://reselect.js.org/api/development-only-stability-checks#1-globally-through-setglobaldevmodechecks global-configuration}\n *\n * @since 5.0.0\n * @public\n */\nexport const setGlobalDevModeChecks = (\n devModeChecks: Partial\n) => {\n Object.assign(globalDevModeChecks, devModeChecks)\n}\n","import { runIdentityFunctionCheck } from './devModeChecks/identityFunctionCheck'\nimport { runInputStabilityCheck } from './devModeChecks/inputStabilityCheck'\nimport { globalDevModeChecks } from './devModeChecks/setGlobalDevModeChecks'\n// eslint-disable-next-line @typescript-eslint/consistent-type-imports\nimport type {\n DevModeChecks,\n Selector,\n SelectorArray,\n DevModeChecksExecutionInfo\n} from './types'\n\nexport const NOT_FOUND = /* @__PURE__ */ Symbol('NOT_FOUND')\nexport type NOT_FOUND_TYPE = typeof NOT_FOUND\n\n/**\n * Assert that the provided value is a function. If the assertion fails,\n * a `TypeError` is thrown with an optional custom error message.\n *\n * @param func - The value to be checked.\n * @param errorMessage - An optional custom error message to use if the assertion fails.\n * @throws A `TypeError` if the assertion fails.\n */\nexport function assertIsFunction(\n func: unknown,\n errorMessage = `expected a function, instead received ${typeof func}`\n): asserts func is FunctionType {\n if (typeof func !== 'function') {\n throw new TypeError(errorMessage)\n }\n}\n\n/**\n * Assert that the provided value is an object. If the assertion fails,\n * a `TypeError` is thrown with an optional custom error message.\n *\n * @param object - The value to be checked.\n * @param errorMessage - An optional custom error message to use if the assertion fails.\n * @throws A `TypeError` if the assertion fails.\n */\nexport function assertIsObject>(\n object: unknown,\n errorMessage = `expected an object, instead received ${typeof object}`\n): asserts object is ObjectType {\n if (typeof object !== 'object') {\n throw new TypeError(errorMessage)\n }\n}\n\n/**\n * Assert that the provided array is an array of functions. If the assertion fails,\n * a `TypeError` is thrown with an optional custom error message.\n *\n * @param array - The array to be checked.\n * @param errorMessage - An optional custom error message to use if the assertion fails.\n * @throws A `TypeError` if the assertion fails.\n */\nexport function assertIsArrayOfFunctions(\n array: unknown[],\n errorMessage = `expected all items to be functions, instead received the following types: `\n): asserts array is FunctionType[] {\n if (\n !array.every((item): item is FunctionType => typeof item === 'function')\n ) {\n const itemTypes = array\n .map(item =>\n typeof item === 'function'\n ? `function ${item.name || 'unnamed'}()`\n : typeof item\n )\n .join(', ')\n throw new TypeError(`${errorMessage}[${itemTypes}]`)\n }\n}\n\n/**\n * Ensure that the input is an array. If it's already an array, it's returned as is.\n * If it's not an array, it will be wrapped in a new array.\n *\n * @param item - The item to be checked.\n * @returns An array containing the input item. If the input is already an array, it's returned without modification.\n */\nexport const ensureIsArray = (item: unknown) => {\n return Array.isArray(item) ? item : [item]\n}\n\n/**\n * Extracts the \"dependencies\" / \"input selectors\" from the arguments of `createSelector`.\n *\n * @param createSelectorArgs - Arguments passed to `createSelector` as an array.\n * @returns An array of \"input selectors\" / \"dependencies\".\n * @throws A `TypeError` if any of the input selectors is not function.\n */\nexport function getDependencies(createSelectorArgs: unknown[]) {\n const dependencies = Array.isArray(createSelectorArgs[0])\n ? createSelectorArgs[0]\n : createSelectorArgs\n\n assertIsArrayOfFunctions(\n dependencies,\n `createSelector expects all input-selectors to be functions, but received the following types: `\n )\n\n return dependencies as SelectorArray\n}\n\n/**\n * Runs each input selector and returns their collective results as an array.\n *\n * @param dependencies - An array of \"dependencies\" or \"input selectors\".\n * @param inputSelectorArgs - An array of arguments being passed to the input selectors.\n * @returns An array of input selector results.\n */\nexport function collectInputSelectorResults(\n dependencies: SelectorArray,\n inputSelectorArgs: unknown[] | IArguments\n) {\n const inputSelectorResults = []\n const { length } = dependencies\n for (let i = 0; i < length; i++) {\n // @ts-ignore\n // apply arguments instead of spreading and mutate a local list of params for performance.\n inputSelectorResults.push(dependencies[i].apply(null, inputSelectorArgs))\n }\n return inputSelectorResults\n}\n\n/**\n * Retrieves execution information for development mode checks.\n *\n * @param devModeChecks - Custom Settings for development mode checks. These settings will override the global defaults.\n * @param firstRun - Indicates whether it is the first time the selector has run.\n * @returns An object containing the execution information for each development mode check.\n */\nexport const getDevModeChecksExecutionInfo = (\n firstRun: boolean,\n devModeChecks: Partial\n) => {\n const { identityFunctionCheck, inputStabilityCheck } = {\n ...globalDevModeChecks,\n ...devModeChecks\n }\n return {\n identityFunctionCheck: {\n shouldRun:\n identityFunctionCheck === 'always' ||\n (identityFunctionCheck === 'once' && firstRun),\n run: runIdentityFunctionCheck\n },\n inputStabilityCheck: {\n shouldRun:\n inputStabilityCheck === 'always' ||\n (inputStabilityCheck === 'once' && firstRun),\n run: runInputStabilityCheck\n }\n } satisfies DevModeChecksExecutionInfo\n}\n","// Original autotracking implementation source:\n// - https://gist.github.com/pzuraq/79bf862e0f8cd9521b79c4b6eccdc4f9\n// Additional references:\n// - https://www.pzuraq.com/blog/how-autotracking-works\n// - https://v5.chriskrycho.com/journal/autotracking-elegant-dx-via-cutting-edge-cs/\nimport type { EqualityFn } from '../types'\nimport { assertIsFunction } from '../utils'\n\n// The global revision clock. Every time state changes, the clock increments.\nexport let $REVISION = 0\n\n// The current dependency tracker. Whenever we compute a cache, we create a Set\n// to track any dependencies that are used while computing. If no cache is\n// computing, then the tracker is null.\nlet CURRENT_TRACKER: Set | TrackingCache> | null = null\n\n// Storage represents a root value in the system - the actual state of our app.\nexport class Cell {\n revision = $REVISION\n\n _value: T\n _lastValue: T\n _isEqual: EqualityFn = tripleEq\n\n constructor(initialValue: T, isEqual: EqualityFn = tripleEq) {\n this._value = this._lastValue = initialValue\n this._isEqual = isEqual\n }\n\n // Whenever a storage value is read, it'll add itself to the current tracker if\n // one exists, entangling its state with that cache.\n get value() {\n CURRENT_TRACKER?.add(this)\n\n return this._value\n }\n\n // Whenever a storage value is updated, we bump the global revision clock,\n // assign the revision for this storage to the new value, _and_ we schedule a\n // rerender. This is important, and it's what makes autotracking _pull_\n // based. We don't actively tell the caches which depend on the storage that\n // anything has happened. Instead, we recompute the caches when needed.\n set value(newValue) {\n if (this.value === newValue) return\n\n this._value = newValue\n this.revision = ++$REVISION\n }\n}\n\nfunction tripleEq(a: unknown, b: unknown) {\n return a === b\n}\n\n// Caches represent derived state in the system. They are ultimately functions\n// that are memoized based on what state they use to produce their output,\n// meaning they will only rerun IFF a storage value that could affect the output\n// has changed. Otherwise, they'll return the cached value.\nexport class TrackingCache {\n _cachedValue: any\n _cachedRevision = -1\n _deps: any[] = []\n hits = 0\n\n fn: () => any\n\n constructor(fn: () => any) {\n this.fn = fn\n }\n\n clear() {\n this._cachedValue = undefined\n this._cachedRevision = -1\n this._deps = []\n this.hits = 0\n }\n\n get value() {\n // When getting the value for a Cache, first we check all the dependencies of\n // the cache to see what their current revision is. If the current revision is\n // greater than the cached revision, then something has changed.\n if (this.revision > this._cachedRevision) {\n const { fn } = this\n\n // We create a new dependency tracker for this cache. As the cache runs\n // its function, any Storage or Cache instances which are used while\n // computing will be added to this tracker. In the end, it will be the\n // full list of dependencies that this Cache depends on.\n const currentTracker = new Set>()\n const prevTracker = CURRENT_TRACKER\n\n CURRENT_TRACKER = currentTracker\n\n // try {\n this._cachedValue = fn()\n // } finally {\n CURRENT_TRACKER = prevTracker\n this.hits++\n this._deps = Array.from(currentTracker)\n\n // Set the cached revision. This is the current clock count of all the\n // dependencies. If any dependency changes, this number will be less\n // than the new revision.\n this._cachedRevision = this.revision\n // }\n }\n\n // If there is a current tracker, it means another Cache is computing and\n // using this one, so we add this one to the tracker.\n CURRENT_TRACKER?.add(this)\n\n // Always return the cached value.\n return this._cachedValue\n }\n\n get revision() {\n // The current revision is the max of all the dependencies' revisions.\n return Math.max(...this._deps.map(d => d.revision), 0)\n }\n}\n\nexport function getValue(cell: Cell): T {\n if (!(cell instanceof Cell)) {\n console.warn('Not a valid cell! ', cell)\n }\n\n return cell.value\n}\n\ntype CellValue> = T extends Cell ? U : never\n\nexport function setValue>(\n storage: T,\n value: CellValue\n): void {\n if (!(storage instanceof Cell)) {\n throw new TypeError(\n 'setValue must be passed a tracked store created with `createStorage`.'\n )\n }\n\n storage.value = storage._lastValue = value\n}\n\nexport function createCell(\n initialValue: T,\n isEqual: EqualityFn = tripleEq\n): Cell {\n return new Cell(initialValue, isEqual)\n}\n\nexport function createCache(fn: () => T): TrackingCache {\n assertIsFunction(\n fn,\n 'the first parameter to `createCache` must be a function'\n )\n\n return new TrackingCache(fn)\n}\n","import type { Cell } from './autotracking'\nimport {\n getValue as consumeTag,\n createCell as createStorage,\n setValue\n} from './autotracking'\n\nexport type Tag = Cell\n\nconst neverEq = (a: any, b: any): boolean => false\n\nexport function createTag(): Tag {\n return createStorage(null, neverEq)\n}\nexport { consumeTag }\nexport function dirtyTag(tag: Tag, value: any): void {\n setValue(tag, value)\n}\n\nexport interface Node<\n T extends Array | Record =\n | Array\n | Record\n> {\n collectionTag: Tag | null\n tag: Tag | null\n tags: Record\n children: Record\n proxy: T\n value: T\n id: number\n}\n\nexport const consumeCollection = (node: Node): void => {\n let tag = node.collectionTag\n\n if (tag === null) {\n tag = node.collectionTag = createTag()\n }\n\n consumeTag(tag)\n}\n\nexport const dirtyCollection = (node: Node): void => {\n const tag = node.collectionTag\n\n if (tag !== null) {\n dirtyTag(tag, null)\n }\n}\n","// Original source:\n// - https://github.com/simonihmig/tracked-redux/blob/master/packages/tracked-redux/src/-private/proxy.ts\n\nimport type { Node, Tag } from './tracking'\nimport {\n consumeCollection,\n consumeTag,\n createTag,\n dirtyCollection,\n dirtyTag\n} from './tracking'\n\nexport const REDUX_PROXY_LABEL = /* @__PURE__ */ Symbol()\n\nlet nextId = 0\n\nconst proto = /* @__PURE__ */ Object.getPrototypeOf({})\n\nclass ObjectTreeNode> implements Node {\n proxy: T = new Proxy(this, objectProxyHandler) as unknown as T\n tag = createTag()\n tags = {} as Record\n children = {} as Record\n collectionTag = null\n id = nextId++\n\n constructor(public value: T) {\n this.value = value\n this.tag.value = value\n }\n}\n\nconst objectProxyHandler = {\n get(node: Node, key: string | symbol): unknown {\n function calculateResult() {\n const { value } = node\n\n const childValue = Reflect.get(value, key)\n\n if (typeof key === 'symbol') {\n return childValue\n }\n\n if (key in proto) {\n return childValue\n }\n\n if (typeof childValue === 'object' && childValue !== null) {\n let childNode = node.children[key]\n\n if (childNode === undefined) {\n childNode = node.children[key] = createNode(childValue)\n }\n\n if (childNode.tag) {\n consumeTag(childNode.tag)\n }\n\n return childNode.proxy\n } else {\n let tag = node.tags[key]\n\n if (tag === undefined) {\n tag = node.tags[key] = createTag()\n tag.value = childValue\n }\n\n consumeTag(tag)\n\n return childValue\n }\n }\n const res = calculateResult()\n return res\n },\n\n ownKeys(node: Node): ArrayLike {\n consumeCollection(node)\n return Reflect.ownKeys(node.value)\n },\n\n getOwnPropertyDescriptor(\n node: Node,\n prop: string | symbol\n ): PropertyDescriptor | undefined {\n return Reflect.getOwnPropertyDescriptor(node.value, prop)\n },\n\n has(node: Node, prop: string | symbol): boolean {\n return Reflect.has(node.value, prop)\n }\n}\n\nclass ArrayTreeNode> implements Node {\n proxy: T = new Proxy([this], arrayProxyHandler) as unknown as T\n tag = createTag()\n tags = {}\n children = {}\n collectionTag = null\n id = nextId++\n\n constructor(public value: T) {\n this.value = value\n this.tag.value = value\n }\n}\n\nconst arrayProxyHandler = {\n get([node]: [Node], key: string | symbol): unknown {\n if (key === 'length') {\n consumeCollection(node)\n }\n\n return objectProxyHandler.get(node, key)\n },\n\n ownKeys([node]: [Node]): ArrayLike {\n return objectProxyHandler.ownKeys(node)\n },\n\n getOwnPropertyDescriptor(\n [node]: [Node],\n prop: string | symbol\n ): PropertyDescriptor | undefined {\n return objectProxyHandler.getOwnPropertyDescriptor(node, prop)\n },\n\n has([node]: [Node], prop: string | symbol): boolean {\n return objectProxyHandler.has(node, prop)\n }\n}\n\nexport function createNode | Record>(\n value: T\n): Node {\n if (Array.isArray(value)) {\n return new ArrayTreeNode(value)\n }\n\n return new ObjectTreeNode(value) as Node\n}\n\nconst keysMap = new WeakMap<\n Array | Record,\n Set\n>()\n\nexport function updateNode | Record>(\n node: Node,\n newValue: T\n): void {\n const { value, tags, children } = node\n\n node.value = newValue\n\n if (\n Array.isArray(value) &&\n Array.isArray(newValue) &&\n value.length !== newValue.length\n ) {\n dirtyCollection(node)\n } else {\n if (value !== newValue) {\n let oldKeysSize = 0\n let newKeysSize = 0\n let anyKeysAdded = false\n\n for (const _key in value) {\n oldKeysSize++\n }\n\n for (const key in newValue) {\n newKeysSize++\n if (!(key in value)) {\n anyKeysAdded = true\n break\n }\n }\n\n const isDifferent = anyKeysAdded || oldKeysSize !== newKeysSize\n\n if (isDifferent) {\n dirtyCollection(node)\n }\n }\n }\n\n for (const key in tags) {\n const childValue = (value as Record)[key]\n const newChildValue = (newValue as Record)[key]\n\n if (childValue !== newChildValue) {\n dirtyCollection(node)\n dirtyTag(tags[key], newChildValue)\n }\n\n if (typeof newChildValue === 'object' && newChildValue !== null) {\n delete tags[key]\n }\n }\n\n for (const key in children) {\n const childNode = children[key]\n const newChildValue = (newValue as Record)[key]\n\n const childValue = childNode.value\n\n if (childValue === newChildValue) {\n continue\n } else if (typeof newChildValue === 'object' && newChildValue !== null) {\n updateNode(childNode, newChildValue as Record)\n } else {\n deleteNode(childNode)\n delete children[key]\n }\n }\n}\n\nfunction deleteNode(node: Node): void {\n if (node.tag) {\n dirtyTag(node.tag, null)\n }\n dirtyCollection(node)\n for (const key in node.tags) {\n dirtyTag(node.tags[key], null)\n }\n for (const key in node.children) {\n deleteNode(node.children[key])\n }\n}\n","import type {\n AnyFunction,\n DefaultMemoizeFields,\n EqualityFn,\n Simplify\n} from './types'\n\nimport type { NOT_FOUND_TYPE } from './utils'\nimport { NOT_FOUND } from './utils'\n\n// Cache implementation based on Erik Rasmussen's `lru-memoize`:\n// https://github.com/erikras/lru-memoize\n\ninterface Entry {\n key: unknown\n value: unknown\n}\n\ninterface Cache {\n get(key: unknown): unknown | NOT_FOUND_TYPE\n put(key: unknown, value: unknown): void\n getEntries(): Entry[]\n clear(): void\n}\n\nfunction createSingletonCache(equals: EqualityFn): Cache {\n let entry: Entry | undefined\n return {\n get(key: unknown) {\n if (entry && equals(entry.key, key)) {\n return entry.value\n }\n\n return NOT_FOUND\n },\n\n put(key: unknown, value: unknown) {\n entry = { key, value }\n },\n\n getEntries() {\n return entry ? [entry] : []\n },\n\n clear() {\n entry = undefined\n }\n }\n}\n\nfunction createLruCache(maxSize: number, equals: EqualityFn): Cache {\n let entries: Entry[] = []\n\n function get(key: unknown) {\n const cacheIndex = entries.findIndex(entry => equals(key, entry.key))\n\n // We found a cached entry\n if (cacheIndex > -1) {\n const entry = entries[cacheIndex]\n\n // Cached entry not at top of cache, move it to the top\n if (cacheIndex > 0) {\n entries.splice(cacheIndex, 1)\n entries.unshift(entry)\n }\n\n return entry.value\n }\n\n // No entry found in cache, return sentinel\n return NOT_FOUND\n }\n\n function put(key: unknown, value: unknown) {\n if (get(key) === NOT_FOUND) {\n // TODO Is unshift slow?\n entries.unshift({ key, value })\n if (entries.length > maxSize) {\n entries.pop()\n }\n }\n }\n\n function getEntries() {\n return entries\n }\n\n function clear() {\n entries = []\n }\n\n return { get, put, getEntries, clear }\n}\n\n/**\n * Runs a simple reference equality check.\n * What {@linkcode lruMemoize lruMemoize} uses by default.\n *\n * **Note**: This function was previously known as `defaultEqualityCheck`.\n *\n * @public\n */\nexport const referenceEqualityCheck: EqualityFn = (a, b) => a === b\n\nexport function createCacheKeyComparator(equalityCheck: EqualityFn) {\n return function areArgumentsShallowlyEqual(\n prev: unknown[] | IArguments | null,\n next: unknown[] | IArguments | null\n ): boolean {\n if (prev === null || next === null || prev.length !== next.length) {\n return false\n }\n\n // Do this in a for loop (and not a `forEach` or an `every`) so we can determine equality as fast as possible.\n const { length } = prev\n for (let i = 0; i < length; i++) {\n if (!equalityCheck(prev[i], next[i])) {\n return false\n }\n }\n\n return true\n }\n}\n\n/**\n * Options for configuring the behavior of a function memoized with\n * LRU (Least Recently Used) caching.\n *\n * @template Result - The type of the return value of the memoized function.\n *\n * @public\n */\nexport interface LruMemoizeOptions {\n /**\n * Function used to compare the individual arguments of the\n * provided calculation function.\n *\n * @default referenceEqualityCheck\n */\n equalityCheck?: EqualityFn\n\n /**\n * If provided, used to compare a newly generated output value against\n * previous values in the cache. If a match is found,\n * the old value is returned. This addresses the common\n * ```ts\n * todos.map(todo => todo.id)\n * ```\n * use case, where an update to another field in the original data causes\n * a recalculation due to changed references, but the output is still\n * effectively the same.\n *\n * @since 4.1.0\n */\n resultEqualityCheck?: EqualityFn\n\n /**\n * The maximum size of the cache used by the selector.\n * A size greater than 1 means the selector will use an\n * LRU (Least Recently Used) cache, allowing for the caching of multiple\n * results based on different sets of arguments.\n *\n * @default 1\n */\n maxSize?: number\n}\n\n/**\n * Creates a memoized version of a function with an optional\n * LRU (Least Recently Used) cache. The memoized function uses a cache to\n * store computed values. Depending on the `maxSize` option, it will use\n * either a singleton cache (for a single entry) or an\n * LRU cache (for multiple entries).\n *\n * **Note**: This function was previously known as `defaultMemoize`.\n *\n * @param func - The function to be memoized.\n * @param equalityCheckOrOptions - Either an equality check function or an options object.\n * @returns A memoized function with a `.clearCache()` method attached.\n *\n * @template Func - The type of the function that is memoized.\n *\n * @see {@link https://reselect.js.org/api/lruMemoize `lruMemoize`}\n *\n * @public\n */\nexport function lruMemoize(\n func: Func,\n equalityCheckOrOptions?: EqualityFn | LruMemoizeOptions>\n) {\n const providedOptions =\n typeof equalityCheckOrOptions === 'object'\n ? equalityCheckOrOptions\n : { equalityCheck: equalityCheckOrOptions }\n\n const {\n equalityCheck = referenceEqualityCheck,\n maxSize = 1,\n resultEqualityCheck\n } = providedOptions\n\n const comparator = createCacheKeyComparator(equalityCheck)\n\n let resultsCount = 0\n\n const cache =\n maxSize <= 1\n ? createSingletonCache(comparator)\n : createLruCache(maxSize, comparator)\n\n function memoized() {\n let value = cache.get(arguments) as ReturnType\n if (value === NOT_FOUND) {\n // apply arguments instead of spreading for performance.\n // @ts-ignore\n value = func.apply(null, arguments) as ReturnType\n resultsCount++\n\n if (resultEqualityCheck) {\n const entries = cache.getEntries()\n const matchingEntry = entries.find(entry =>\n resultEqualityCheck(entry.value as ReturnType, value)\n )\n\n if (matchingEntry) {\n value = matchingEntry.value as ReturnType\n resultsCount !== 0 && resultsCount--\n }\n }\n\n cache.put(arguments, value)\n }\n return value\n }\n\n memoized.clearCache = () => {\n cache.clear()\n memoized.resetResultsCount()\n }\n\n memoized.resultsCount = () => resultsCount\n\n memoized.resetResultsCount = () => {\n resultsCount = 0\n }\n\n return memoized as Func & Simplify\n}\n","import { createNode, updateNode } from './proxy'\nimport type { Node } from './tracking'\n\nimport { createCacheKeyComparator, referenceEqualityCheck } from '../lruMemoize'\nimport type { AnyFunction, DefaultMemoizeFields, Simplify } from '../types'\nimport { createCache } from './autotracking'\n\n/**\n * Uses an \"auto-tracking\" approach inspired by the work of the Ember Glimmer team.\n * It uses a Proxy to wrap arguments and track accesses to nested fields\n * in your selector on first read. Later, when the selector is called with\n * new arguments, it identifies which accessed fields have changed and\n * only recalculates the result if one or more of those accessed fields have changed.\n * This allows it to be more precise than the shallow equality checks in `lruMemoize`.\n *\n * __Design Tradeoffs for `autotrackMemoize`:__\n * - Pros:\n * - It is likely to avoid excess calculations and recalculate fewer times than `lruMemoize` will,\n * which may also result in fewer component re-renders.\n * - Cons:\n * - It only has a cache size of 1.\n * - It is slower than `lruMemoize`, because it has to do more work. (How much slower is dependent on the number of accessed fields in a selector, number of calls, frequency of input changes, etc)\n * - It can have some unexpected behavior. Because it tracks nested field accesses,\n * cases where you don't access a field will not recalculate properly.\n * For example, a badly-written selector like:\n * ```ts\n * createSelector([state => state.todos], todos => todos)\n * ```\n * that just immediately returns the extracted value will never update, because it doesn't see any field accesses to check.\n *\n * __Use Cases for `autotrackMemoize`:__\n * - It is likely best used for cases where you need to access specific nested fields\n * in data, and avoid recalculating if other fields in the same data objects are immutably updated.\n *\n * @param func - The function to be memoized.\n * @returns A memoized function with a `.clearCache()` method attached.\n *\n * @example\n * Using `createSelector`\n * ```ts\n * import { unstable_autotrackMemoize as autotrackMemoize, createSelector } from 'reselect'\n *\n * const selectTodoIds = createSelector(\n * [(state: RootState) => state.todos],\n * (todos) => todos.map(todo => todo.id),\n * { memoize: autotrackMemoize }\n * )\n * ```\n *\n * @example\n * Using `createSelectorCreator`\n * ```ts\n * import { unstable_autotrackMemoize as autotrackMemoize, createSelectorCreator } from 'reselect'\n *\n * const createSelectorAutotrack = createSelectorCreator({ memoize: autotrackMemoize })\n *\n * const selectTodoIds = createSelectorAutotrack(\n * [(state: RootState) => state.todos],\n * (todos) => todos.map(todo => todo.id)\n * )\n * ```\n *\n * @template Func - The type of the function that is memoized.\n *\n * @see {@link https://reselect.js.org/api/unstable_autotrackMemoize autotrackMemoize}\n *\n * @since 5.0.0\n * @public\n * @experimental\n */\nexport function autotrackMemoize(func: Func) {\n // we reference arguments instead of spreading them for performance reasons\n\n const node: Node> = createNode(\n [] as unknown as Record\n )\n\n let lastArgs: IArguments | null = null\n\n const shallowEqual = createCacheKeyComparator(referenceEqualityCheck)\n\n const cache = createCache(() => {\n const res = func.apply(null, node.proxy as unknown as any[])\n return res\n })\n\n function memoized() {\n if (!shallowEqual(lastArgs, arguments)) {\n updateNode(node, arguments as unknown as Record)\n lastArgs = arguments\n }\n return cache.value\n }\n\n memoized.clearCache = () => {\n return cache.clear()\n }\n\n return memoized as Func & Simplify\n}\n","// Original source:\n// - https://github.com/facebook/react/blob/0b974418c9a56f6c560298560265dcf4b65784bc/packages/react/src/ReactCache.js\n\nimport type {\n AnyFunction,\n DefaultMemoizeFields,\n EqualityFn,\n Simplify\n} from './types'\n\nclass StrongRef {\n constructor(private value: T) {}\n deref() {\n return this.value\n }\n}\n\n/**\n * @returns The {@linkcode StrongRef} if {@linkcode WeakRef} is not available.\n *\n * @since 5.1.2\n * @internal\n */\nconst getWeakRef = () =>\n typeof WeakRef === 'undefined'\n ? (StrongRef as unknown as typeof WeakRef)\n : WeakRef\n\nconst Ref = /* @__PURE__ */ getWeakRef()\n\nconst UNTERMINATED = 0\nconst TERMINATED = 1\n\ninterface UnterminatedCacheNode {\n /**\n * Status, represents whether the cached computation returned a value or threw an error.\n */\n s: 0\n /**\n * Value, either the cached result or an error, depending on status.\n */\n v: void\n /**\n * Object cache, a `WeakMap` where non-primitive arguments are stored.\n */\n o: null | WeakMap>\n /**\n * Primitive cache, a regular Map where primitive arguments are stored.\n */\n p: null | Map>\n}\n\ninterface TerminatedCacheNode {\n /**\n * Status, represents whether the cached computation returned a value or threw an error.\n */\n s: 1\n /**\n * Value, either the cached result or an error, depending on status.\n */\n v: T\n /**\n * Object cache, a `WeakMap` where non-primitive arguments are stored.\n */\n o: null | WeakMap>\n /**\n * Primitive cache, a regular `Map` where primitive arguments are stored.\n */\n p: null | Map>\n}\n\ntype CacheNode = TerminatedCacheNode | UnterminatedCacheNode\n\nfunction createCacheNode(): CacheNode {\n return {\n s: UNTERMINATED,\n v: undefined,\n o: null,\n p: null\n }\n}\n\n/**\n * Configuration options for a memoization function utilizing `WeakMap` for\n * its caching mechanism.\n *\n * @template Result - The type of the return value of the memoized function.\n *\n * @since 5.0.0\n * @public\n */\nexport interface WeakMapMemoizeOptions {\n /**\n * If provided, used to compare a newly generated output value against previous values in the cache.\n * If a match is found, the old value is returned. This addresses the common\n * ```ts\n * todos.map(todo => todo.id)\n * ```\n * use case, where an update to another field in the original data causes a recalculation\n * due to changed references, but the output is still effectively the same.\n *\n * @since 5.0.0\n */\n resultEqualityCheck?: EqualityFn\n}\n\n/**\n * Derefences the argument if it is a Ref. Else if it is a value already, return it.\n *\n * @param r - the object to maybe deref\n * @returns The derefenced value if the argument is a Ref, else the argument value itself.\n */\nfunction maybeDeref(r: any) {\n if (r instanceof Ref) {\n return r.deref()\n }\n\n return r\n}\n\n/**\n * Creates a tree of `WeakMap`-based cache nodes based on the identity of the\n * arguments it's been called with (in this case, the extracted values from your input selectors).\n * This allows `weakMapMemoize` to have an effectively infinite cache size.\n * Cache results will be kept in memory as long as references to the arguments still exist,\n * and then cleared out as the arguments are garbage-collected.\n *\n * __Design Tradeoffs for `weakMapMemoize`:__\n * - Pros:\n * - It has an effectively infinite cache size, but you have no control over\n * how long values are kept in cache as it's based on garbage collection and `WeakMap`s.\n * - Cons:\n * - There's currently no way to alter the argument comparisons.\n * They're based on strict reference equality.\n * - It's roughly the same speed as `lruMemoize`, although likely a fraction slower.\n *\n * __Use Cases for `weakMapMemoize`:__\n * - This memoizer is likely best used for cases where you need to call the\n * same selector instance with many different arguments, such as a single\n * selector instance that is used in a list item component and called with\n * item IDs like:\n * ```ts\n * useSelector(state => selectSomeData(state, props.category))\n * ```\n * @param func - The function to be memoized.\n * @returns A memoized function with a `.clearCache()` method attached.\n *\n * @example\n * Using `createSelector`\n * ```ts\n * import { createSelector, weakMapMemoize } from 'reselect'\n *\n * interface RootState {\n * items: { id: number; category: string; name: string }[]\n * }\n *\n * const selectItemsByCategory = createSelector(\n * [\n * (state: RootState) => state.items,\n * (state: RootState, category: string) => category\n * ],\n * (items, category) => items.filter(item => item.category === category),\n * {\n * memoize: weakMapMemoize,\n * argsMemoize: weakMapMemoize\n * }\n * )\n * ```\n *\n * @example\n * Using `createSelectorCreator`\n * ```ts\n * import { createSelectorCreator, weakMapMemoize } from 'reselect'\n *\n * const createSelectorWeakMap = createSelectorCreator({ memoize: weakMapMemoize, argsMemoize: weakMapMemoize })\n *\n * const selectItemsByCategory = createSelectorWeakMap(\n * [\n * (state: RootState) => state.items,\n * (state: RootState, category: string) => category\n * ],\n * (items, category) => items.filter(item => item.category === category)\n * )\n * ```\n *\n * @template Func - The type of the function that is memoized.\n *\n * @see {@link https://reselect.js.org/api/weakMapMemoize `weakMapMemoize`}\n *\n * @since 5.0.0\n * @public\n * @experimental\n */\nexport function weakMapMemoize(\n func: Func,\n options: WeakMapMemoizeOptions> = {}\n) {\n let fnNode = createCacheNode()\n const { resultEqualityCheck } = options\n\n let lastResult: WeakRef | undefined\n\n let resultsCount = 0\n\n function memoized() {\n let cacheNode = fnNode\n const { length } = arguments\n for (let i = 0, l = length; i < l; i++) {\n const arg = arguments[i]\n if (\n typeof arg === 'function' ||\n (typeof arg === 'object' && arg !== null)\n ) {\n // Objects go into a WeakMap\n let objectCache = cacheNode.o\n if (objectCache === null) {\n cacheNode.o = objectCache = new WeakMap()\n }\n const objectNode = objectCache.get(arg)\n if (objectNode === undefined) {\n cacheNode = createCacheNode()\n objectCache.set(arg, cacheNode)\n } else {\n cacheNode = objectNode\n }\n } else {\n // Primitives go into a regular Map\n let primitiveCache = cacheNode.p\n if (primitiveCache === null) {\n cacheNode.p = primitiveCache = new Map()\n }\n const primitiveNode = primitiveCache.get(arg)\n if (primitiveNode === undefined) {\n cacheNode = createCacheNode()\n primitiveCache.set(arg, cacheNode)\n } else {\n cacheNode = primitiveNode\n }\n }\n }\n\n const terminatedNode = cacheNode as unknown as TerminatedCacheNode\n\n let result\n\n if (cacheNode.s === TERMINATED) {\n result = cacheNode.v\n } else {\n // Allow errors to propagate\n result = func.apply(null, arguments as unknown as any[])\n resultsCount++\n\n if (resultEqualityCheck) {\n // Deref lastResult if it is a Ref\n const lastResultValue = maybeDeref(lastResult)\n\n if (\n lastResultValue != null &&\n resultEqualityCheck(lastResultValue as ReturnType, result)\n ) {\n result = lastResultValue\n\n resultsCount !== 0 && resultsCount--\n }\n\n const needsWeakRef =\n (typeof result === 'object' && result !== null) ||\n typeof result === 'function'\n\n lastResult = needsWeakRef ? /* @__PURE__ */ new Ref(result) : result\n }\n }\n\n terminatedNode.s = TERMINATED\n\n terminatedNode.v = result\n return result\n }\n\n memoized.clearCache = () => {\n fnNode = createCacheNode()\n memoized.resetResultsCount()\n }\n\n memoized.resultsCount = () => resultsCount\n\n memoized.resetResultsCount = () => {\n resultsCount = 0\n }\n\n return memoized as Func & Simplify\n}\n","import { weakMapMemoize } from './weakMapMemoize'\n\nimport type {\n Combiner,\n CreateSelectorOptions,\n DropFirstParameter,\n ExtractMemoizerFields,\n GetParamsFromSelectors,\n GetStateFromSelectors,\n InterruptRecursion,\n OutputSelector,\n Selector,\n SelectorArray,\n SetRequired,\n Simplify,\n UnknownMemoizer\n} from './types'\n\nimport {\n assertIsFunction,\n collectInputSelectorResults,\n ensureIsArray,\n getDependencies,\n getDevModeChecksExecutionInfo\n} from './utils'\n\n/**\n * An instance of `createSelector`, customized with a given memoize implementation.\n *\n * @template MemoizeFunction - The type of the memoize function that is used to memoize the `resultFunc` inside `createSelector` (e.g., `lruMemoize` or `weakMapMemoize`).\n * @template ArgsMemoizeFunction - The type of the optional memoize function that is used to memoize the arguments passed into the output selector generated by `createSelector` (e.g., `lruMemoize` or `weakMapMemoize`). If none is explicitly provided, `weakMapMemoize` will be used.\n * @template StateType - The type of state that the selectors created with this selector creator will operate on.\n *\n * @public\n */\nexport interface CreateSelectorFunction<\n MemoizeFunction extends UnknownMemoizer = typeof weakMapMemoize,\n ArgsMemoizeFunction extends UnknownMemoizer = typeof weakMapMemoize,\n StateType = any\n> {\n /**\n * Creates a memoized selector function.\n *\n * @param createSelectorArgs - An arbitrary number of input selectors as separate inline arguments and a `combiner` function.\n * @returns A memoized output selector.\n *\n * @template InputSelectors - The type of the input selectors as an array.\n * @template Result - The return type of the `combiner` as well as the output selector.\n * @template OverrideMemoizeFunction - The type of the optional `memoize` function that could be passed into the options object to override the original `memoize` function that was initially passed into `createSelectorCreator`.\n * @template OverrideArgsMemoizeFunction - The type of the optional `argsMemoize` function that could be passed into the options object to override the original `argsMemoize` function that was initially passed into `createSelectorCreator`.\n *\n * @see {@link https://reselect.js.org/api/createselector `createSelector`}\n */\n , Result>(\n ...createSelectorArgs: [\n ...inputSelectors: InputSelectors,\n combiner: Combiner\n ]\n ): OutputSelector<\n InputSelectors,\n Result,\n MemoizeFunction,\n ArgsMemoizeFunction\n > &\n InterruptRecursion\n\n /**\n * Creates a memoized selector function.\n *\n * @param createSelectorArgs - An arbitrary number of input selectors as separate inline arguments, a `combiner` function and an `options` object.\n * @returns A memoized output selector.\n *\n * @template InputSelectors - The type of the input selectors as an array.\n * @template Result - The return type of the `combiner` as well as the output selector.\n * @template OverrideMemoizeFunction - The type of the optional `memoize` function that could be passed into the options object to override the original `memoize` function that was initially passed into `createSelectorCreator`.\n * @template OverrideArgsMemoizeFunction - The type of the optional `argsMemoize` function that could be passed into the options object to override the original `argsMemoize` function that was initially passed into `createSelectorCreator`.\n *\n * @see {@link https://reselect.js.org/api/createselector `createSelector`}\n */\n <\n InputSelectors extends SelectorArray,\n Result,\n OverrideMemoizeFunction extends UnknownMemoizer = MemoizeFunction,\n OverrideArgsMemoizeFunction extends UnknownMemoizer = ArgsMemoizeFunction\n >(\n ...createSelectorArgs: [\n ...inputSelectors: InputSelectors,\n combiner: Combiner,\n createSelectorOptions: Simplify<\n CreateSelectorOptions<\n MemoizeFunction,\n ArgsMemoizeFunction,\n OverrideMemoizeFunction,\n OverrideArgsMemoizeFunction\n >\n >\n ]\n ): OutputSelector<\n InputSelectors,\n Result,\n OverrideMemoizeFunction,\n OverrideArgsMemoizeFunction\n > &\n InterruptRecursion\n\n /**\n * Creates a memoized selector function.\n *\n * @param inputSelectors - An array of input selectors.\n * @param combiner - A function that Combines the input selectors and returns an output selector. Otherwise known as the result function.\n * @param createSelectorOptions - An optional options object that allows for further customization per selector.\n * @returns A memoized output selector.\n *\n * @template InputSelectors - The type of the input selectors array.\n * @template Result - The return type of the `combiner` as well as the output selector.\n * @template OverrideMemoizeFunction - The type of the optional `memoize` function that could be passed into the options object to override the original `memoize` function that was initially passed into `createSelectorCreator`.\n * @template OverrideArgsMemoizeFunction - The type of the optional `argsMemoize` function that could be passed into the options object to override the original `argsMemoize` function that was initially passed into `createSelectorCreator`.\n *\n * @see {@link https://reselect.js.org/api/createselector `createSelector`}\n */\n <\n InputSelectors extends SelectorArray,\n Result,\n OverrideMemoizeFunction extends UnknownMemoizer = MemoizeFunction,\n OverrideArgsMemoizeFunction extends UnknownMemoizer = ArgsMemoizeFunction\n >(\n inputSelectors: [...InputSelectors],\n combiner: Combiner,\n createSelectorOptions?: Simplify<\n CreateSelectorOptions<\n MemoizeFunction,\n ArgsMemoizeFunction,\n OverrideMemoizeFunction,\n OverrideArgsMemoizeFunction\n >\n >\n ): OutputSelector<\n InputSelectors,\n Result,\n OverrideMemoizeFunction,\n OverrideArgsMemoizeFunction\n > &\n InterruptRecursion\n\n /**\n * Creates a \"pre-typed\" version of {@linkcode createSelector createSelector}\n * where the `state` type is predefined.\n *\n * This allows you to set the `state` type once, eliminating the need to\n * specify it with every {@linkcode createSelector createSelector} call.\n *\n * @returns A pre-typed `createSelector` with the state type already defined.\n *\n * @example\n * ```ts\n * import { createSelector } from 'reselect'\n *\n * export interface RootState {\n * todos: { id: number; completed: boolean }[]\n * alerts: { id: number; read: boolean }[]\n * }\n *\n * export const createAppSelector = createSelector.withTypes()\n *\n * const selectTodoIds = createAppSelector(\n * [\n * // Type of `state` is set to `RootState`, no need to manually set the type\n * state => state.todos\n * ],\n * todos => todos.map(({ id }) => id)\n * )\n * ```\n * @template OverrideStateType - The specific type of state used by all selectors created with this selector creator.\n *\n * @see {@link https://reselect.js.org/api/createselector#defining-a-pre-typed-createselector `createSelector.withTypes`}\n *\n * @since 5.1.0\n */\n withTypes: () => CreateSelectorFunction<\n MemoizeFunction,\n ArgsMemoizeFunction,\n OverrideStateType\n >\n}\n\n/**\n * Creates a selector creator function with the specified memoization function\n * and options for customizing memoization behavior.\n *\n * @param options - An options object containing the `memoize` function responsible for memoizing the `resultFunc` inside `createSelector` (e.g., `lruMemoize` or `weakMapMemoize`). It also provides additional options for customizing memoization. While the `memoize` property is mandatory, the rest are optional.\n * @returns A customized `createSelector` function.\n *\n * @example\n * ```ts\n * const customCreateSelector = createSelectorCreator({\n * memoize: customMemoize, // Function to be used to memoize `resultFunc`\n * memoizeOptions: [memoizeOption1, memoizeOption2], // Options passed to `customMemoize` as the second argument onwards\n * argsMemoize: customArgsMemoize, // Function to be used to memoize the selector's arguments\n * argsMemoizeOptions: [argsMemoizeOption1, argsMemoizeOption2] // Options passed to `customArgsMemoize` as the second argument onwards\n * })\n *\n * const customSelector = customCreateSelector(\n * [inputSelector1, inputSelector2],\n * resultFunc // `resultFunc` will be passed as the first argument to `customMemoize`\n * )\n *\n * customSelector(\n * ...selectorArgs // Will be memoized by `customArgsMemoize`\n * )\n * ```\n *\n * @template MemoizeFunction - The type of the memoize function that is used to memoize the `resultFunc` inside `createSelector` (e.g., `lruMemoize` or `weakMapMemoize`).\n * @template ArgsMemoizeFunction - The type of the optional memoize function that is used to memoize the arguments passed into the output selector generated by `createSelector` (e.g., `lruMemoize` or `weakMapMemoize`). If none is explicitly provided, `weakMapMemoize` will be used.\n *\n * @see {@link https://reselect.js.org/api/createSelectorCreator#using-options-since-500 `createSelectorCreator`}\n *\n * @since 5.0.0\n * @public\n */\nexport function createSelectorCreator<\n MemoizeFunction extends UnknownMemoizer,\n ArgsMemoizeFunction extends UnknownMemoizer = typeof weakMapMemoize\n>(\n options: Simplify<\n SetRequired<\n CreateSelectorOptions<\n typeof weakMapMemoize,\n typeof weakMapMemoize,\n MemoizeFunction,\n ArgsMemoizeFunction\n >,\n 'memoize'\n >\n >\n): CreateSelectorFunction\n\n/**\n * Creates a selector creator function with the specified memoization function\n * and options for customizing memoization behavior.\n *\n * @param memoize - The `memoize` function responsible for memoizing the `resultFunc` inside `createSelector` (e.g., `lruMemoize` or `weakMapMemoize`).\n * @param memoizeOptionsFromArgs - Optional configuration options for the memoization function. These options are then passed to the memoize function as the second argument onwards.\n * @returns A customized `createSelector` function.\n *\n * @example\n * ```ts\n * const customCreateSelector = createSelectorCreator(customMemoize, // Function to be used to memoize `resultFunc`\n * option1, // Will be passed as second argument to `customMemoize`\n * option2, // Will be passed as third argument to `customMemoize`\n * option3 // Will be passed as fourth argument to `customMemoize`\n * )\n *\n * const customSelector = customCreateSelector(\n * [inputSelector1, inputSelector2],\n * resultFunc // `resultFunc` will be passed as the first argument to `customMemoize`\n * )\n * ```\n *\n * @template MemoizeFunction - The type of the memoize function that is used to memoize the `resultFunc` inside `createSelector` (e.g., `lruMemoize` or `weakMapMemoize`).\n *\n * @see {@link https://reselect.js.org/api/createSelectorCreator#using-memoize-and-memoizeoptions `createSelectorCreator`}\n *\n * @public\n */\nexport function createSelectorCreator(\n memoize: MemoizeFunction,\n ...memoizeOptionsFromArgs: DropFirstParameter\n): CreateSelectorFunction\n\n/**\n * Creates a selector creator function with the specified memoization\n * function and options for customizing memoization behavior.\n *\n * @param memoizeOrOptions - Either A `memoize` function or an `options` object containing the `memoize` function.\n * @param memoizeOptionsFromArgs - Optional configuration options for the memoization function. These options are then passed to the memoize function as the second argument onwards.\n * @returns A customized `createSelector` function.\n *\n * @template MemoizeFunction - The type of the memoize function that is used to memoize the `resultFunc` inside `createSelector` (e.g., `lruMemoize` or `weakMapMemoize`).\n * @template ArgsMemoizeFunction - The type of the optional memoize function that is used to memoize the arguments passed into the output selector generated by `createSelector` (e.g., `lruMemoize` or `weakMapMemoize`). If none is explicitly provided, `weakMapMemoize` will be used.\n * @template MemoizeOrOptions - The type of the first argument. It can either be a `memoize` function or an `options` object containing the `memoize` function.\n */\nexport function createSelectorCreator<\n MemoizeFunction extends UnknownMemoizer,\n ArgsMemoizeFunction extends UnknownMemoizer,\n MemoizeOrOptions extends\n | MemoizeFunction\n | SetRequired<\n CreateSelectorOptions,\n 'memoize'\n >\n>(\n memoizeOrOptions: MemoizeOrOptions,\n ...memoizeOptionsFromArgs: MemoizeOrOptions extends SetRequired<\n CreateSelectorOptions,\n 'memoize'\n >\n ? never\n : DropFirstParameter\n) {\n /** options initially passed into `createSelectorCreator`. */\n const createSelectorCreatorOptions: SetRequired<\n CreateSelectorOptions,\n 'memoize'\n > = typeof memoizeOrOptions === 'function'\n ? {\n memoize: memoizeOrOptions as MemoizeFunction,\n memoizeOptions: memoizeOptionsFromArgs\n }\n : memoizeOrOptions\n\n const createSelector = <\n InputSelectors extends SelectorArray,\n Result,\n OverrideMemoizeFunction extends UnknownMemoizer = MemoizeFunction,\n OverrideArgsMemoizeFunction extends UnknownMemoizer = ArgsMemoizeFunction\n >(\n ...createSelectorArgs: [\n ...inputSelectors: [...InputSelectors],\n combiner: Combiner,\n createSelectorOptions?: CreateSelectorOptions<\n MemoizeFunction,\n ArgsMemoizeFunction,\n OverrideMemoizeFunction,\n OverrideArgsMemoizeFunction\n >\n ]\n ) => {\n let recomputations = 0\n let dependencyRecomputations = 0\n let lastResult: Result\n\n // Due to the intricacies of rest params, we can't do an optional arg after `...createSelectorArgs`.\n // So, start by declaring the default value here.\n // (And yes, the words 'memoize' and 'options' appear too many times in this next sequence.)\n let directlyPassedOptions: CreateSelectorOptions<\n MemoizeFunction,\n ArgsMemoizeFunction,\n OverrideMemoizeFunction,\n OverrideArgsMemoizeFunction\n > = {}\n\n // Normally, the result func or \"combiner\" is the last arg\n let resultFunc = createSelectorArgs.pop() as\n | Combiner\n | CreateSelectorOptions<\n MemoizeFunction,\n ArgsMemoizeFunction,\n OverrideMemoizeFunction,\n OverrideArgsMemoizeFunction\n >\n\n // If the result func is actually an _object_, assume it's our options object\n if (typeof resultFunc === 'object') {\n directlyPassedOptions = resultFunc\n // and pop the real result func off\n resultFunc = createSelectorArgs.pop() as Combiner\n }\n\n assertIsFunction(\n resultFunc,\n `createSelector expects an output function after the inputs, but received: [${typeof resultFunc}]`\n )\n\n // Determine which set of options we're using. Prefer options passed directly,\n // but fall back to options given to `createSelectorCreator`.\n const combinedOptions = {\n ...createSelectorCreatorOptions,\n ...directlyPassedOptions\n }\n\n const {\n memoize,\n memoizeOptions = [],\n argsMemoize = weakMapMemoize,\n argsMemoizeOptions = []\n } = combinedOptions\n\n // Simplifying assumption: it's unlikely that the first options arg of the provided memoizer\n // is an array. In most libs I've looked at, it's an equality function or options object.\n // Based on that, if `memoizeOptions` _is_ an array, we assume it's a full\n // user-provided array of options. Otherwise, it must be just the _first_ arg, and so\n // we wrap it in an array so we can apply it.\n const finalMemoizeOptions = ensureIsArray(memoizeOptions)\n const finalArgsMemoizeOptions = ensureIsArray(argsMemoizeOptions)\n const dependencies = getDependencies(createSelectorArgs) as InputSelectors\n\n const memoizedResultFunc = memoize(function recomputationWrapper() {\n recomputations++\n // apply arguments instead of spreading for performance.\n // @ts-ignore\n return (resultFunc as Combiner).apply(\n null,\n arguments as unknown as Parameters>\n )\n }, ...finalMemoizeOptions) as Combiner &\n ExtractMemoizerFields\n\n let firstRun = true\n\n // If a selector is called with the exact same arguments we don't need to traverse our dependencies again.\n const selector = argsMemoize(function dependenciesChecker() {\n dependencyRecomputations++\n /** Return values of input selectors which the `resultFunc` takes as arguments. */\n const inputSelectorResults = collectInputSelectorResults(\n dependencies,\n arguments\n )\n\n // apply arguments instead of spreading for performance.\n // @ts-ignore\n lastResult = memoizedResultFunc.apply(null, inputSelectorResults)\n\n if (process.env.NODE_ENV !== 'production') {\n const { devModeChecks = {} } = combinedOptions\n const { identityFunctionCheck, inputStabilityCheck } =\n getDevModeChecksExecutionInfo(firstRun, devModeChecks)\n if (identityFunctionCheck.shouldRun) {\n identityFunctionCheck.run(\n resultFunc as Combiner,\n inputSelectorResults,\n lastResult\n )\n }\n\n if (inputStabilityCheck.shouldRun) {\n // make a second copy of the params, to check if we got the same results\n const inputSelectorResultsCopy = collectInputSelectorResults(\n dependencies,\n arguments\n )\n\n inputStabilityCheck.run(\n { inputSelectorResults, inputSelectorResultsCopy },\n { memoize, memoizeOptions: finalMemoizeOptions },\n arguments\n )\n }\n\n if (firstRun) firstRun = false\n }\n\n return lastResult\n }, ...finalArgsMemoizeOptions) as unknown as Selector<\n GetStateFromSelectors,\n Result,\n GetParamsFromSelectors\n > &\n ExtractMemoizerFields\n\n return Object.assign(selector, {\n resultFunc,\n memoizedResultFunc,\n dependencies,\n dependencyRecomputations: () => dependencyRecomputations,\n resetDependencyRecomputations: () => {\n dependencyRecomputations = 0\n },\n lastResult: () => lastResult,\n recomputations: () => recomputations,\n resetRecomputations: () => {\n recomputations = 0\n },\n memoize,\n argsMemoize\n }) as OutputSelector<\n InputSelectors,\n Result,\n OverrideMemoizeFunction,\n OverrideArgsMemoizeFunction\n >\n }\n\n Object.assign(createSelector, {\n withTypes: () => createSelector\n })\n\n return createSelector as CreateSelectorFunction<\n MemoizeFunction,\n ArgsMemoizeFunction\n >\n}\n\n/**\n * Accepts one or more \"input selectors\" (either as separate arguments or a single array),\n * a single \"result function\" / \"combiner\", and an optional options object, and\n * generates a memoized selector function.\n *\n * @see {@link https://reselect.js.org/api/createSelector `createSelector`}\n *\n * @public\n */\nexport const createSelector =\n /* #__PURE__ */ createSelectorCreator(weakMapMemoize)\n","import { createSelector } from './createSelectorCreator'\n\nimport type { CreateSelectorFunction } from './createSelectorCreator'\nimport type {\n InterruptRecursion,\n ObjectValuesToTuple,\n OutputSelector,\n Selector,\n Simplify,\n UnknownMemoizer\n} from './types'\nimport { assertIsObject } from './utils'\nimport type { weakMapMemoize } from './weakMapMemoize'\n\n/**\n * Represents a mapping of selectors to their return types.\n *\n * @template TObject - An object type where each property is a selector function.\n *\n * @public\n */\nexport type SelectorResultsMap = {\n [Key in keyof TObject]: ReturnType\n}\n\n/**\n * Represents a mapping of selectors for each key in a given root state.\n *\n * This type is a utility that takes a root state object type and\n * generates a corresponding set of selectors. Each selector is associated\n * with a key in the root state, allowing for the selection\n * of specific parts of the state.\n *\n * @template RootState - The type of the root state object.\n *\n * @since 5.0.0\n * @public\n */\nexport type RootStateSelectors = {\n [Key in keyof RootState]: Selector\n}\n\n/**\n * @deprecated Please use {@linkcode StructuredSelectorCreator.withTypes createStructuredSelector.withTypes()} instead. This type will be removed in the future.\n * @template RootState - The type of the root state object.\n *\n * @since 5.0.0\n * @public\n */\nexport type TypedStructuredSelectorCreator =\n /**\n * A convenience function that simplifies returning an object\n * made up of selector results.\n *\n * @param inputSelectorsObject - A key value pair consisting of input selectors.\n * @param selectorCreator - A custom selector creator function. It defaults to `createSelector`.\n * @returns A memoized structured selector.\n *\n * @example\n * Modern Use Case\n * ```ts\n * import { createSelector, createStructuredSelector } from 'reselect'\n *\n * interface RootState {\n * todos: {\n * id: number\n * completed: boolean\n * title: string\n * description: string\n * }[]\n * alerts: { id: number; read: boolean }[]\n * }\n *\n * // This:\n * const structuredSelector = createStructuredSelector(\n * {\n * todos: (state: RootState) => state.todos,\n * alerts: (state: RootState) => state.alerts,\n * todoById: (state: RootState, id: number) => state.todos[id]\n * },\n * createSelector\n * )\n *\n * // Is essentially the same as this:\n * const selector = createSelector(\n * [\n * (state: RootState) => state.todos,\n * (state: RootState) => state.alerts,\n * (state: RootState, id: number) => state.todos[id]\n * ],\n * (todos, alerts, todoById) => {\n * return {\n * todos,\n * alerts,\n * todoById\n * }\n * }\n * )\n * ```\n *\n * @example\n * In your component:\n * ```tsx\n * import type { RootState } from 'createStructuredSelector/modernUseCase'\n * import { structuredSelector } from 'createStructuredSelector/modernUseCase'\n * import type { FC } from 'react'\n * import { useSelector } from 'react-redux'\n *\n * interface Props {\n * id: number\n * }\n *\n * const MyComponent: FC = ({ id }) => {\n * const { todos, alerts, todoById } = useSelector((state: RootState) =>\n * structuredSelector(state, id)\n * )\n *\n * return (\n *
\n * Next to do is:\n *

{todoById.title}

\n *

Description: {todoById.description}

\n *
    \n *

    All other to dos:

    \n * {todos.map(todo => (\n *
  • {todo.title}
  • \n * ))}\n *
\n *
\n * )\n * }\n * ```\n *\n * @example\n * Simple Use Case\n * ```ts\n * const selectA = state => state.a\n * const selectB = state => state.b\n *\n * // The result function in the following selector\n * // is simply building an object from the input selectors\n * const structuredSelector = createSelector(selectA, selectB, (a, b) => ({\n * a,\n * b\n * }))\n *\n * const result = structuredSelector({ a: 1, b: 2 }) // will produce { x: 1, y: 2 }\n * ```\n *\n * @template InputSelectorsObject - The shape of the input selectors object.\n * @template MemoizeFunction - The type of the memoize function that is used to create the structured selector. It defaults to `weakMapMemoize`.\n * @template ArgsMemoizeFunction - The type of the of the memoize function that is used to memoize the arguments passed into the generated structured selector. It defaults to `weakMapMemoize`.\n *\n * @see {@link https://reselect.js.org/api/createStructuredSelector `createStructuredSelector`}\n */\n <\n InputSelectorsObject extends RootStateSelectors = RootStateSelectors,\n MemoizeFunction extends UnknownMemoizer = typeof weakMapMemoize,\n ArgsMemoizeFunction extends UnknownMemoizer = typeof weakMapMemoize\n >(\n inputSelectorsObject: InputSelectorsObject,\n selectorCreator?: CreateSelectorFunction<\n MemoizeFunction,\n ArgsMemoizeFunction\n >\n ) => OutputSelector<\n ObjectValuesToTuple,\n Simplify>,\n MemoizeFunction,\n ArgsMemoizeFunction\n > &\n InterruptRecursion\n\n/**\n * Represents an object where each property is a selector function.\n *\n * @template StateType - The type of state that all the selectors operate on.\n *\n * @public\n */\nexport type SelectorsObject = Record<\n string,\n Selector\n>\n\n/**\n * It provides a way to create structured selectors.\n * The structured selector can take multiple input selectors\n * and map their output to an object with specific keys.\n *\n * @template StateType - The type of state that the structured selectors created with this structured selector creator will operate on.\n *\n * @see {@link https://reselect.js.org/api/createStructuredSelector `createStructuredSelector`}\n *\n * @public\n */\nexport interface StructuredSelectorCreator {\n /**\n * A convenience function that simplifies returning an object\n * made up of selector results.\n *\n * @param inputSelectorsObject - A key value pair consisting of input selectors.\n * @param selectorCreator - A custom selector creator function. It defaults to `createSelector`.\n * @returns A memoized structured selector.\n *\n * @example\n * Modern Use Case\n * ```ts\n * import { createSelector, createStructuredSelector } from 'reselect'\n *\n * interface RootState {\n * todos: {\n * id: number\n * completed: boolean\n * title: string\n * description: string\n * }[]\n * alerts: { id: number; read: boolean }[]\n * }\n *\n * // This:\n * const structuredSelector = createStructuredSelector(\n * {\n * todos: (state: RootState) => state.todos,\n * alerts: (state: RootState) => state.alerts,\n * todoById: (state: RootState, id: number) => state.todos[id]\n * },\n * createSelector\n * )\n *\n * // Is essentially the same as this:\n * const selector = createSelector(\n * [\n * (state: RootState) => state.todos,\n * (state: RootState) => state.alerts,\n * (state: RootState, id: number) => state.todos[id]\n * ],\n * (todos, alerts, todoById) => {\n * return {\n * todos,\n * alerts,\n * todoById\n * }\n * }\n * )\n * ```\n *\n * @example\n * In your component:\n * ```tsx\n * import type { RootState } from 'createStructuredSelector/modernUseCase'\n * import { structuredSelector } from 'createStructuredSelector/modernUseCase'\n * import type { FC } from 'react'\n * import { useSelector } from 'react-redux'\n *\n * interface Props {\n * id: number\n * }\n *\n * const MyComponent: FC = ({ id }) => {\n * const { todos, alerts, todoById } = useSelector((state: RootState) =>\n * structuredSelector(state, id)\n * )\n *\n * return (\n *
\n * Next to do is:\n *

{todoById.title}

\n *

Description: {todoById.description}

\n *
    \n *

    All other to dos:

    \n * {todos.map(todo => (\n *
  • {todo.title}
  • \n * ))}\n *
\n *
\n * )\n * }\n * ```\n *\n * @example\n * Simple Use Case\n * ```ts\n * const selectA = state => state.a\n * const selectB = state => state.b\n *\n * // The result function in the following selector\n * // is simply building an object from the input selectors\n * const structuredSelector = createSelector(selectA, selectB, (a, b) => ({\n * a,\n * b\n * }))\n *\n * const result = structuredSelector({ a: 1, b: 2 }) // will produce { x: 1, y: 2 }\n * ```\n *\n * @template InputSelectorsObject - The shape of the input selectors object.\n * @template MemoizeFunction - The type of the memoize function that is used to create the structured selector. It defaults to `weakMapMemoize`.\n * @template ArgsMemoizeFunction - The type of the of the memoize function that is used to memoize the arguments passed into the generated structured selector. It defaults to `weakMapMemoize`.\n *\n * @see {@link https://reselect.js.org/api/createStructuredSelector `createStructuredSelector`}\n */\n <\n InputSelectorsObject extends SelectorsObject,\n MemoizeFunction extends UnknownMemoizer = typeof weakMapMemoize,\n ArgsMemoizeFunction extends UnknownMemoizer = typeof weakMapMemoize\n >(\n inputSelectorsObject: InputSelectorsObject,\n selectorCreator?: CreateSelectorFunction<\n MemoizeFunction,\n ArgsMemoizeFunction\n >\n ): OutputSelector<\n ObjectValuesToTuple,\n Simplify>,\n MemoizeFunction,\n ArgsMemoizeFunction\n > &\n InterruptRecursion\n\n /**\n * Creates a \"pre-typed\" version of\n * {@linkcode createStructuredSelector createStructuredSelector}\n * where the `state` type is predefined.\n *\n * This allows you to set the `state` type once, eliminating the need to\n * specify it with every\n * {@linkcode createStructuredSelector createStructuredSelector} call.\n *\n * @returns A pre-typed `createStructuredSelector` with the state type already defined.\n *\n * @example\n * ```ts\n * import { createStructuredSelector } from 'reselect'\n *\n * export interface RootState {\n * todos: { id: number; completed: boolean }[]\n * alerts: { id: number; read: boolean }[]\n * }\n *\n * export const createStructuredAppSelector =\n * createStructuredSelector.withTypes()\n *\n * const structuredAppSelector = createStructuredAppSelector({\n * // Type of `state` is set to `RootState`, no need to manually set the type\n * todos: state => state.todos,\n * alerts: state => state.alerts,\n * todoById: (state, id: number) => state.todos[id]\n * })\n *\n * ```\n * @template OverrideStateType - The specific type of state used by all structured selectors created with this structured selector creator.\n *\n * @see {@link https://reselect.js.org/api/createstructuredselector#defining-a-pre-typed-createstructuredselector `createSelector.withTypes`}\n *\n * @since 5.1.0\n */\n withTypes: <\n OverrideStateType extends StateType\n >() => StructuredSelectorCreator\n}\n\n/**\n * A convenience function that simplifies returning an object\n * made up of selector results.\n *\n * @param inputSelectorsObject - A key value pair consisting of input selectors.\n * @param selectorCreator - A custom selector creator function. It defaults to `createSelector`.\n * @returns A memoized structured selector.\n *\n * @example\n * Modern Use Case\n * ```ts\n * import { createSelector, createStructuredSelector } from 'reselect'\n *\n * interface RootState {\n * todos: {\n * id: number\n * completed: boolean\n * title: string\n * description: string\n * }[]\n * alerts: { id: number; read: boolean }[]\n * }\n *\n * // This:\n * const structuredSelector = createStructuredSelector(\n * {\n * todos: (state: RootState) => state.todos,\n * alerts: (state: RootState) => state.alerts,\n * todoById: (state: RootState, id: number) => state.todos[id]\n * },\n * createSelector\n * )\n *\n * // Is essentially the same as this:\n * const selector = createSelector(\n * [\n * (state: RootState) => state.todos,\n * (state: RootState) => state.alerts,\n * (state: RootState, id: number) => state.todos[id]\n * ],\n * (todos, alerts, todoById) => {\n * return {\n * todos,\n * alerts,\n * todoById\n * }\n * }\n * )\n * ```\n *\n * @see {@link https://reselect.js.org/api/createStructuredSelector `createStructuredSelector`}\n *\n * @public\n */\nexport const createStructuredSelector: StructuredSelectorCreator =\n /* @__PURE__ */ Object.assign(\n <\n InputSelectorsObject extends SelectorsObject,\n MemoizeFunction extends UnknownMemoizer = typeof weakMapMemoize,\n ArgsMemoizeFunction extends UnknownMemoizer = typeof weakMapMemoize\n >(\n inputSelectorsObject: InputSelectorsObject,\n selectorCreator: CreateSelectorFunction<\n MemoizeFunction,\n ArgsMemoizeFunction\n > = createSelector as CreateSelectorFunction<\n MemoizeFunction,\n ArgsMemoizeFunction\n >\n ) => {\n assertIsObject(\n inputSelectorsObject,\n 'createStructuredSelector expects first argument to be an object ' +\n `where each property is a selector, instead received a ${typeof inputSelectorsObject}`\n )\n const inputSelectorKeys = Object.keys(inputSelectorsObject)\n const dependencies = inputSelectorKeys.map(\n key => inputSelectorsObject[key]\n )\n const structuredSelector = selectorCreator(\n dependencies,\n (...inputSelectorResults: any[]) => {\n return inputSelectorResults.reduce((composition, value, index) => {\n composition[inputSelectorKeys[index]] = value\n return composition\n }, {})\n }\n )\n return structuredSelector\n },\n { withTypes: () => createStructuredSelector }\n ) as StructuredSelectorCreator\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ascending, descending, extent, min, rollup} from 'd3-array';\nimport {ScaleLinear, scaleSqrt} from 'd3-scale';\nimport KDBush from 'kdbush';\nimport {createSelector, createSelectorCreator, lruMemoize} from 'reselect';\nimport {alea} from 'seedrandom';\nimport FlowmapAggregateAccessors from './FlowmapAggregateAccessors';\nimport {FlowmapState} from './FlowmapState';\nimport {\n ClusterIndex,\n LocationWeightGetter,\n buildIndex,\n findAppropriateZoomLevel,\n makeLocationWeightGetter,\n} from './cluster/ClusterIndex';\nimport {clusterLocations} from './cluster/cluster';\nimport getColors, {\n ColorsRGBA,\n DiffColorsRGBA,\n getColorsRGBA,\n getDiffColorsRGBA,\n getFlowColorScale,\n isDiffColors,\n isDiffColorsRGBA,\n} from './colors';\nimport {\n addClusterNames,\n getFlowThicknessScale,\n getViewportBoundingBox,\n} from './selector-functions';\nimport {\n TimeGranularityKey,\n getTimeGranularityByKey,\n getTimeGranularityByOrder,\n getTimeGranularityForDate,\n} from './time';\nimport {\n AggregateFlow,\n Cluster,\n ClusterLevels,\n ClusterNode,\n CountByTime,\n FlowAccessors,\n FlowCirclesLayerAttributes,\n FlowLinesLayerAttributes,\n FlowLinesRenderingMode,\n FlowmapData,\n FlowmapDataAccessors,\n LayersData,\n LocationFilterMode,\n LocationTotals,\n ViewportProps,\n isLocationClusterNode,\n} from './types';\n\nconst MAX_CLUSTER_ZOOM_LEVEL = 20;\ntype KDBushTree = any;\n\nexport type Selector = (\n state: FlowmapState,\n props: FlowmapData,\n) => T;\n\nexport default class FlowmapSelectors<\n L extends Record,\n F extends Record,\n> {\n accessors: FlowmapAggregateAccessors;\n\n constructor(accessors: FlowmapDataAccessors) {\n this.accessors = new FlowmapAggregateAccessors(accessors);\n this.setAccessors(accessors);\n }\n\n setAccessors(accessors: FlowmapDataAccessors) {\n this.accessors = new FlowmapAggregateAccessors(accessors);\n }\n\n getAggregateAccessors(): FlowmapAggregateAccessors {\n return this.accessors;\n }\n\n getFlowsFromProps = (state: FlowmapState, props: FlowmapData) =>\n props.flows;\n getLocationsFromProps = (state: FlowmapState, props: FlowmapData) =>\n props.locations;\n getClusterLevelsFromProps = (\n state: FlowmapState,\n props: FlowmapData,\n ) => {\n return props.clusterLevels;\n };\n getMaxTopFlowsDisplayNum = (state: FlowmapState, props: FlowmapData) =>\n state.settings.maxTopFlowsDisplayNum;\n getFlowEndpointsInViewportMode = (\n state: FlowmapState,\n props: FlowmapData,\n ) => state.settings.flowEndpointsInViewportMode;\n getSelectedLocations = (state: FlowmapState, props: FlowmapData) =>\n state.filter?.selectedLocations;\n getLocationFilterMode = (state: FlowmapState, props: FlowmapData) =>\n state.filter?.locationFilterMode;\n getClusteringEnabled = (state: FlowmapState, props: FlowmapData) =>\n state.settings.clusteringEnabled;\n getLocationTotalsEnabled = (state: FlowmapState, props: FlowmapData) =>\n state.settings.locationTotalsEnabled;\n getLocationLabelsEnabled = (state: FlowmapState, props: FlowmapData) =>\n state.settings.locationLabelsEnabled;\n getZoom = (state: FlowmapState, props: FlowmapData) =>\n state.viewport.zoom;\n getViewport = (state: FlowmapState, props: FlowmapData) =>\n state.viewport;\n getSelectedTimeRange = (state: FlowmapState, props: FlowmapData) =>\n state.filter?.selectedTimeRange;\n\n getColorScheme: Selector = (\n state: FlowmapState,\n props: FlowmapData,\n ) => state.settings.colorScheme;\n\n getDarkMode: Selector = (\n state: FlowmapState,\n props: FlowmapData,\n ) => state.settings.darkMode;\n\n getFadeEnabled: Selector = (\n state: FlowmapState,\n props: FlowmapData,\n ) => state.settings.fadeEnabled;\n\n getFadeOpacityEnabled: Selector = (\n state: FlowmapState,\n props: FlowmapData,\n ) => state.settings.fadeOpacityEnabled;\n\n getFadeAmount: Selector = (\n state: FlowmapState,\n props: FlowmapData,\n ) => state.settings.fadeAmount;\n\n getFlowLinesRenderingMode: Selector = (\n state: FlowmapState,\n props: FlowmapData,\n ) => state.settings.flowLinesRenderingMode;\n\n getAnimate: Selector = createSelector(\n this.getFlowLinesRenderingMode,\n (flowLinesRenderingMode) => flowLinesRenderingMode === 'animated-straight',\n );\n\n getInvalidLocationIds: Selector =\n createSelector(this.getLocationsFromProps, (locations) => {\n if (!locations) return undefined;\n const invalid = [];\n for (const location of locations) {\n const id = this.accessors.getLocationId(location);\n const lon = this.accessors.getLocationLon(location);\n const lat = this.accessors.getLocationLat(location);\n if (!(-90 <= lat && lat <= 90) || !(-180 <= lon && lon <= 180)) {\n invalid.push(id);\n }\n }\n return invalid.length > 0 ? invalid : undefined;\n });\n\n getLocations: Selector | undefined> = createSelector(\n this.getLocationsFromProps,\n this.getInvalidLocationIds,\n (locations, invalidIds) => {\n if (!locations) return undefined;\n if (!invalidIds || invalidIds.length === 0) return locations;\n const invalid = new Set(invalidIds);\n const filtered: L[] = [];\n for (const location of locations) {\n const id = this.accessors.getLocationId(location);\n if (!invalid.has(id)) {\n filtered.push(location);\n }\n }\n return filtered;\n },\n );\n\n getLocationIds: Selector | undefined> =\n createSelector(this.getLocations, (locations) => {\n if (!locations) return undefined;\n const ids = new Set();\n for (const id of locations) {\n ids.add(this.accessors.getLocationId(id));\n }\n return ids;\n });\n\n getSelectedLocationsSet: Selector | undefined> =\n createSelector(this.getSelectedLocations, (ids) =>\n ids && ids.length > 0 ? new Set(ids) : undefined,\n );\n\n getSortedFlowsForKnownLocations: Selector =\n createSelector(\n this.getFlowsFromProps,\n this.getLocationIds,\n (flows, ids) => {\n if (!ids || !flows) return undefined;\n const filtered = [];\n for (const flow of flows) {\n const srcId = this.accessors.getFlowOriginId(flow);\n const dstId = this.accessors.getFlowDestId(flow);\n if (ids.has(srcId) && ids.has(dstId)) {\n filtered.push(flow);\n }\n }\n return filtered.sort((a: F, b: F) =>\n descending(\n Math.abs(this.accessors.getFlowMagnitude(a)),\n Math.abs(this.accessors.getFlowMagnitude(b)),\n ),\n );\n },\n );\n\n getActualTimeExtent: Selector =\n createSelector(this.getSortedFlowsForKnownLocations, (flows) => {\n if (!flows) return undefined;\n let start = null;\n let end = null;\n for (const flow of flows) {\n const time = this.accessors.getFlowTime(flow);\n if (time) {\n if (start == null || start > time) start = time;\n if (end == null || end < time) end = time;\n }\n }\n if (!start || !end) return undefined;\n return [start, end];\n });\n\n getTimeGranularityKey: Selector =\n createSelector(\n this.getSortedFlowsForKnownLocations,\n this.getActualTimeExtent,\n (flows, timeExtent) => {\n if (!flows || !timeExtent) return undefined;\n\n const minOrder = min(flows, (d: F) => {\n const t = this.accessors.getFlowTime(d);\n return t ? getTimeGranularityForDate(t).order : null;\n });\n if (minOrder == null) return undefined;\n const timeGranularity = getTimeGranularityByOrder(minOrder);\n return timeGranularity ? timeGranularity.key : undefined;\n },\n );\n\n getTimeExtent: Selector = createSelector(\n this.getActualTimeExtent,\n this.getTimeGranularityKey,\n (timeExtent, timeGranularityKey) => {\n const timeGranularity = timeGranularityKey\n ? getTimeGranularityByKey(timeGranularityKey)\n : undefined;\n if (!timeExtent || !timeGranularity?.interval) return undefined;\n const {interval} = timeGranularity;\n return [timeExtent[0], interval.offset(interval.floor(timeExtent[1]), 1)];\n },\n );\n\n getSortedFlowsForKnownLocationsFilteredByTime: Selector<\n L,\n F,\n F[] | undefined\n > = createSelector(\n this.getSortedFlowsForKnownLocations,\n this.getTimeExtent,\n this.getSelectedTimeRange,\n (flows, timeExtent, timeRange) => {\n if (!flows) return undefined;\n if (\n !timeExtent ||\n !timeRange ||\n (timeExtent[0] === timeRange[0] && timeExtent[1] === timeRange[1])\n ) {\n return flows;\n }\n return flows.filter((flow: F) => {\n const time = this.accessors.getFlowTime(flow);\n return time && timeRange[0] <= time && time < timeRange[1];\n });\n },\n );\n\n getLocationsHavingFlows: Selector | undefined> =\n createSelector(\n this.getSortedFlowsForKnownLocations,\n this.getLocations,\n (flows, locations) => {\n if (!locations || !flows) return locations;\n const withFlows = new Set();\n for (const flow of flows) {\n withFlows.add(this.accessors.getFlowOriginId(flow));\n withFlows.add(this.accessors.getFlowDestId(flow));\n }\n const filtered = [];\n for (const location of locations) {\n if (withFlows.has(this.accessors.getLocationId(location))) {\n filtered.push(location);\n }\n }\n return filtered;\n },\n );\n\n getLocationsById: Selector | undefined> =\n createSelector(this.getLocationsHavingFlows, (locations) => {\n if (!locations) return undefined;\n const locationsById = new Map();\n for (const location of locations) {\n locationsById.set(this.accessors.getLocationId(location), location);\n }\n return locationsById;\n });\n\n getLocationWeightGetter: Selector =\n createSelector(this.getSortedFlowsForKnownLocations, (flows) => {\n if (!flows) return undefined;\n const getLocationWeight = makeLocationWeightGetter(\n flows,\n this.accessors.getFlowmapDataAccessors(),\n );\n return getLocationWeight;\n });\n\n getClusterLevels: Selector = createSelector(\n this.getClusterLevelsFromProps,\n this.getLocationsHavingFlows,\n this.getLocationWeightGetter,\n (clusterLevelsFromProps, locations, getLocationWeight) => {\n if (clusterLevelsFromProps) return clusterLevelsFromProps;\n if (!locations || !getLocationWeight) return undefined;\n const clusterLevels = clusterLocations(\n locations,\n this.accessors.getFlowmapDataAccessors(),\n getLocationWeight,\n {\n maxZoom: MAX_CLUSTER_ZOOM_LEVEL,\n },\n );\n return clusterLevels;\n },\n );\n\n getClusterIndex: Selector | undefined> = createSelector(\n this.getLocationsById,\n this.getLocationWeightGetter,\n this.getClusterLevels,\n (locationsById, getLocationWeight, clusterLevels) => {\n if (!locationsById || !getLocationWeight || !clusterLevels)\n return undefined;\n\n const clusterIndex = buildIndex(clusterLevels);\n // Adding meaningful names\n addClusterNames(\n clusterIndex,\n clusterLevels,\n locationsById,\n this.accessors.getFlowmapDataAccessors(),\n getLocationWeight,\n );\n return clusterIndex;\n },\n );\n\n getAvailableClusterZoomLevels = createSelector(\n this.getClusterIndex,\n this.getSelectedLocations,\n (clusterIndex, selectedLocations): number[] | undefined => {\n if (!clusterIndex) {\n return undefined;\n }\n\n let maxZoom = Number.POSITIVE_INFINITY;\n let minZoom = Number.NEGATIVE_INFINITY;\n\n const adjust = (zoneId: string | number) => {\n const cluster = clusterIndex.getClusterById(zoneId);\n if (cluster) {\n minZoom = Math.max(minZoom, cluster.zoom);\n maxZoom = Math.min(maxZoom, cluster.zoom);\n } else {\n const zoom = clusterIndex.getMinZoomForLocation(zoneId);\n minZoom = Math.max(minZoom, zoom);\n }\n };\n\n if (selectedLocations) {\n for (const id of selectedLocations) {\n adjust(id);\n }\n }\n\n return clusterIndex.availableZoomLevels.filter(\n (level: number) => minZoom <= level && level <= maxZoom,\n );\n },\n );\n\n _getClusterZoom: Selector = createSelector(\n this.getClusterIndex,\n this.getZoom,\n this.getAvailableClusterZoomLevels,\n (clusterIndex, mapZoom, availableClusterZoomLevels) => {\n if (!clusterIndex) return undefined;\n if (!availableClusterZoomLevels || mapZoom == null) {\n return undefined;\n }\n\n const clusterZoom = findAppropriateZoomLevel(\n availableClusterZoomLevels,\n mapZoom,\n );\n return clusterZoom;\n },\n );\n\n getClusterZoom = (state: FlowmapState, props: FlowmapData) => {\n const {settings} = state;\n if (!settings.clusteringEnabled) return undefined;\n if (settings.clusteringAuto || settings.clusteringLevel == null) {\n return this._getClusterZoom(state, props);\n }\n return settings.clusteringLevel;\n };\n\n getLocationsForSearchBox: Selector =\n createSelector(\n this.getClusteringEnabled,\n this.getLocationsHavingFlows,\n this.getSelectedLocations,\n this.getClusterZoom,\n this.getClusterIndex,\n (\n clusteringEnabled,\n locations,\n selectedLocations,\n clusterZoom,\n clusterIndex,\n ) => {\n if (!locations) return undefined;\n let result: (L | Cluster)[] = Array.from(locations);\n // if (clusteringEnabled) {\n // if (clusterIndex) {\n // const zoomItems = clusterIndex.getClusterNodesFor(clusterZoom);\n // if (zoomItems) {\n // result = result.concat(zoomItems.filter(isCluster));\n // }\n // }\n // }\n\n if (clusterIndex && selectedLocations) {\n const toAppend = [];\n for (const id of selectedLocations) {\n const cluster = clusterIndex.getClusterById(id);\n if (\n cluster &&\n !result.find(\n (d) =>\n (isLocationClusterNode(d)\n ? d.id\n : this.accessors.getLocationId(d)) === id,\n )\n ) {\n toAppend.push(cluster);\n }\n }\n if (toAppend.length > 0) {\n result = result.concat(toAppend);\n }\n }\n return result;\n },\n );\n\n getDiffMode: Selector = createSelector(\n this.getFlowsFromProps,\n (flows) => {\n if (flows) {\n for (const f of flows) {\n if (this.accessors.getFlowMagnitude(f) < 0) {\n return true;\n }\n }\n }\n return false;\n },\n );\n\n _getFlowmapColors = createSelector(\n this.getDiffMode,\n this.getColorScheme,\n this.getDarkMode,\n this.getFadeEnabled,\n this.getFadeOpacityEnabled,\n this.getFadeAmount,\n this.getAnimate,\n getColors,\n );\n\n getFlowmapColorsRGBA = createSelector(\n this._getFlowmapColors,\n (flowmapColors) => {\n return isDiffColors(flowmapColors)\n ? getDiffColorsRGBA(flowmapColors)\n : getColorsRGBA(flowmapColors);\n },\n );\n\n getUnknownLocations: Selector | undefined> =\n createSelector(\n this.getLocationIds,\n this.getFlowsFromProps,\n this.getSortedFlowsForKnownLocations,\n (ids, flows, flowsForKnownLocations) => {\n if (!ids || !flows) return undefined;\n if (\n flowsForKnownLocations\n // && flows.length === flowsForKnownLocations.length\n )\n return undefined;\n const missing = new Set();\n for (const flow of flows) {\n if (!ids.has(this.accessors.getFlowOriginId(flow)))\n missing.add(this.accessors.getFlowOriginId(flow));\n if (!ids.has(this.accessors.getFlowDestId(flow)))\n missing.add(this.accessors.getFlowDestId(flow));\n }\n return missing;\n },\n );\n\n getSortedAggregatedFilteredFlows: Selector<\n L,\n F,\n (F | AggregateFlow)[] | undefined\n > = createSelector(\n this.getClusterIndex,\n this.getClusteringEnabled,\n this.getSortedFlowsForKnownLocationsFilteredByTime,\n this.getClusterZoom,\n this.getTimeExtent,\n (clusterTree, isClusteringEnabled, flows, clusterZoom, timeExtent) => {\n if (!flows) return undefined;\n let aggregated: (F | AggregateFlow)[];\n if (isClusteringEnabled && clusterTree && clusterZoom != null) {\n aggregated = clusterTree.aggregateFlows(\n // TODO: aggregate across time\n // timeExtent != null\n // ? aggregateFlows(flows) // clusterTree.aggregateFlows won't aggregate unclustered across time\n // : flows,\n flows,\n clusterZoom,\n this.accessors.getFlowmapDataAccessors(),\n );\n } else {\n aggregated = aggregateFlows(\n flows,\n this.accessors.getFlowmapDataAccessors(),\n );\n }\n aggregated.sort((a, b) =>\n descending(\n Math.abs(this.accessors.getFlowMagnitude(a)),\n Math.abs(this.accessors.getFlowMagnitude(b)),\n ),\n );\n return aggregated;\n },\n );\n\n getExpandedSelectedLocationsSet: Selector<\n L,\n F,\n Set | undefined\n > = createSelector(\n this.getClusteringEnabled,\n this.getSelectedLocationsSet,\n this.getClusterIndex,\n (clusteringEnabled, selectedLocations, clusterIndex) => {\n if (!selectedLocations || !clusterIndex) {\n return selectedLocations;\n }\n\n const result = new Set();\n for (const locationId of selectedLocations) {\n const cluster = clusterIndex.getClusterById(locationId);\n if (cluster) {\n const expanded = clusterIndex.expandCluster(cluster);\n for (const id of expanded) {\n result.add(id);\n }\n } else {\n result.add(locationId);\n }\n }\n return result;\n },\n );\n\n getTotalCountsByTime: Selector =\n createSelector(\n this.getSortedFlowsForKnownLocations,\n this.getTimeGranularityKey,\n this.getTimeExtent,\n this.getExpandedSelectedLocationsSet,\n this.getLocationFilterMode,\n (\n flows,\n timeGranularityKey,\n timeExtent,\n selectedLocationSet,\n locationFilterMode,\n ) => {\n const timeGranularity = timeGranularityKey\n ? getTimeGranularityByKey(timeGranularityKey)\n : undefined;\n if (!flows || !timeGranularity || !timeExtent) return undefined;\n const byTime = flows.reduce((m: Map, flow: F) => {\n if (\n this.isFlowInSelection(\n flow,\n selectedLocationSet,\n locationFilterMode,\n )\n ) {\n const key = timeGranularity\n .interval(this.accessors.getFlowTime(flow))\n .getTime();\n m.set(\n key,\n (m.get(key) ?? 0) + this.accessors.getFlowMagnitude(flow),\n );\n }\n return m;\n }, new Map());\n\n return Array.from(byTime.entries()).map(\n ([millis, count]: [number, number]) => ({\n time: new Date(millis),\n count,\n }),\n );\n },\n );\n\n getMaxLocationCircleSize: Selector = createSelector(\n this.getLocationTotalsEnabled,\n (locationTotalsEnabled) => (locationTotalsEnabled ? 17 : 1),\n );\n\n getViewportBoundingBox: Selector =\n createSelector(\n this.getViewport,\n this.getMaxLocationCircleSize,\n getViewportBoundingBox,\n );\n\n getLocationsForZoom: Selector | ClusterNode[] | undefined> =\n createSelector(\n this.getClusteringEnabled,\n this.getLocationsHavingFlows,\n this.getClusterIndex,\n this.getClusterZoom,\n (clusteringEnabled, locationsHavingFlows, clusterIndex, clusterZoom) => {\n if (clusteringEnabled && clusterIndex) {\n return clusterIndex.getClusterNodesFor(clusterZoom);\n } else {\n return locationsHavingFlows;\n }\n },\n );\n\n getLocationTotals: Selector<\n L,\n F,\n Map | undefined\n > = createSelector(\n this.getLocationsForZoom,\n this.getSortedAggregatedFilteredFlows,\n this.getSelectedLocationsSet,\n this.getLocationFilterMode,\n (locations, flows, selectedLocationsSet, locationFilterMode) => {\n if (!flows) return undefined;\n const totals = new Map();\n const add = (\n id: string | number,\n d: Partial,\n ): LocationTotals => {\n const rv = totals.get(id) ?? {\n incomingCount: 0,\n outgoingCount: 0,\n internalCount: 0,\n };\n if (d.incomingCount != null) rv.incomingCount += d.incomingCount;\n if (d.outgoingCount != null) rv.outgoingCount += d.outgoingCount;\n if (d.internalCount != null) rv.internalCount += d.internalCount;\n return rv;\n };\n for (const f of flows) {\n if (\n this.isFlowInSelection(f, selectedLocationsSet, locationFilterMode)\n ) {\n const originId = this.accessors.getFlowOriginId(f);\n const destId = this.accessors.getFlowDestId(f);\n const count = this.accessors.getFlowMagnitude(f);\n if (originId === destId) {\n totals.set(originId, add(originId, {internalCount: count}));\n } else {\n totals.set(originId, add(originId, {outgoingCount: count}));\n totals.set(destId, add(destId, {incomingCount: count}));\n }\n }\n }\n return totals;\n },\n );\n\n getLocationsTree: Selector = createSelector(\n this.getLocationsForZoom,\n (locations) => {\n if (!locations) {\n return undefined;\n }\n const nodes = Array.isArray(locations)\n ? locations\n : Array.from(locations);\n const bush = new KDBush(nodes.length, 64, Float32Array);\n for (let i = 0; i < nodes.length; i++) {\n const node = nodes[i];\n bush.add(\n lngX(this.accessors.getLocationLon(node)),\n latY(this.accessors.getLocationLat(node)),\n );\n }\n bush.finish();\n bush.points = nodes;\n return bush;\n },\n );\n\n _getLocationIdsInViewport: Selector | undefined> =\n createSelector(\n this.getLocationsTree,\n this.getViewportBoundingBox,\n (tree: KDBushTree, bbox: [number, number, number, number]) => {\n const ids = this._getLocationsInBboxIndices(tree, bbox);\n if (ids) {\n return new Set(\n ids.map((idx: number) =>\n this.accessors.getLocationId(tree.points[idx]),\n ) as Array,\n );\n }\n return undefined;\n },\n );\n\n getLocationIdsInViewport: Selector | undefined> =\n createSelectorCreator({\n memoize: lruMemoize,\n memoizeOptions: {\n equalityCheck: (\n s1: Set | undefined,\n s2: Set | undefined,\n ) => {\n if (s1 === s2) return true;\n if (s1 == null || s2 == null) return false;\n if (s1.size !== s2.size) return false;\n for (const item of s1) if (!s2.has(item)) return false;\n return true;\n },\n },\n })(\n this._getLocationIdsInViewport,\n (locationIds: Set | undefined) => {\n if (!locationIds) return undefined;\n return locationIds;\n },\n );\n\n getTotalUnfilteredCount: Selector = createSelector(\n this.getSortedFlowsForKnownLocations,\n (flows) => {\n if (!flows) return undefined;\n return flows.reduce(\n (m: number, flow: F) => m + this.accessors.getFlowMagnitude(flow),\n 0,\n );\n },\n );\n\n getTotalFilteredCount: Selector = createSelector(\n this.getSortedAggregatedFilteredFlows,\n this.getSelectedLocationsSet,\n this.getLocationFilterMode,\n (flows, selectedLocationSet, locationFilterMode) => {\n if (!flows) return undefined;\n const count = flows.reduce((m: number, flow: F | AggregateFlow) => {\n if (\n this.isFlowInSelection(flow, selectedLocationSet, locationFilterMode)\n ) {\n return m + this.accessors.getFlowMagnitude(flow);\n }\n return m;\n }, 0);\n return count;\n },\n );\n\n _getLocationTotalsExtent: Selector =\n createSelector(this.getLocationTotals, (locationTotals) =>\n calcLocationTotalsExtent(locationTotals, undefined),\n );\n\n _getLocationTotalsForViewportExtent: Selector<\n L,\n F,\n [number, number] | undefined\n > = createSelector(\n this.getLocationTotals,\n this.getLocationIdsInViewport,\n (locationTotals, locationsInViewport) =>\n calcLocationTotalsExtent(locationTotals, locationsInViewport),\n );\n\n getLocationTotalsExtent = (\n state: FlowmapState,\n props: FlowmapData,\n ): [number, number] | undefined => {\n if (state.settings.adaptiveScalesEnabled) {\n return this._getLocationTotalsForViewportExtent(state, props);\n } else {\n return this._getLocationTotalsExtent(state, props);\n }\n };\n\n getFlowsForFlowmapLayer: Selector =\n createSelector(\n this.getSortedAggregatedFilteredFlows,\n this.getLocationIdsInViewport,\n this.getSelectedLocationsSet,\n this.getLocationFilterMode,\n this.getMaxTopFlowsDisplayNum,\n this.getFlowEndpointsInViewportMode,\n (\n flows,\n locationIdsInViewport,\n selectedLocationsSet,\n locationFilterMode,\n maxTopFlowsDisplayNum,\n flowEndpointsInViewportMode,\n ) => {\n if (!flows || !locationIdsInViewport) return undefined;\n const picked: (F | AggregateFlow)[] = [];\n let pickedCount = 0;\n for (const flow of flows) {\n const origin = this.accessors.getFlowOriginId(flow);\n const dest = this.accessors.getFlowDestId(flow);\n const originInView = locationIdsInViewport.has(origin);\n const destInView = locationIdsInViewport.has(dest);\n const isInViewport =\n flowEndpointsInViewportMode === 'both'\n ? originInView && destInView\n : originInView || destInView;\n if (isInViewport) {\n if (\n this.isFlowInSelection(\n flow,\n selectedLocationsSet,\n locationFilterMode,\n )\n ) {\n if (origin !== dest) {\n // exclude self-loops\n picked.push(flow);\n pickedCount++;\n }\n }\n }\n // Only keep top\n if (pickedCount > maxTopFlowsDisplayNum) break;\n }\n // assuming they are sorted in descending order,\n // we need ascending for rendering\n return picked.reverse();\n },\n );\n\n _getFlowMagnitudeExtent: Selector =\n createSelector(\n this.getSortedAggregatedFilteredFlows,\n this.getSelectedLocationsSet,\n this.getLocationFilterMode,\n (flows, selectedLocationsSet, locationFilterMode) => {\n if (!flows) return undefined;\n let rv: [number, number] | undefined = undefined;\n for (const f of flows) {\n if (\n this.accessors.getFlowOriginId(f) !==\n this.accessors.getFlowDestId(f) &&\n this.isFlowInSelection(f, selectedLocationsSet, locationFilterMode)\n ) {\n const count = this.accessors.getFlowMagnitude(f);\n if (rv == null) {\n rv = [count, count];\n } else {\n if (count < rv[0]) rv[0] = count;\n if (count > rv[1]) rv[1] = count;\n }\n }\n }\n return rv;\n },\n );\n\n _getAdaptiveFlowMagnitudeExtent: Selector<\n L,\n F,\n [number, number] | undefined\n > = createSelector(this.getFlowsForFlowmapLayer, (flows) => {\n if (!flows) return undefined;\n const rv = extent(flows, this.accessors.getFlowMagnitude);\n return rv[0] !== undefined && rv[1] !== undefined ? rv : undefined;\n });\n\n getFlowMagnitudeExtent = (\n state: FlowmapState,\n props: FlowmapData,\n ): [number, number] | undefined => {\n if (state.settings.adaptiveScalesEnabled) {\n return this._getAdaptiveFlowMagnitudeExtent(state, props);\n } else {\n return this._getFlowMagnitudeExtent(state, props);\n }\n };\n\n getLocationMaxAbsTotalGetter = createSelector(\n this.getLocationTotals,\n (locationTotals) => {\n return (locationId: string) => {\n const total = locationTotals?.get(locationId);\n if (!total) return undefined;\n return Math.max(\n Math.abs(total.incomingCount + total.internalCount),\n Math.abs(total.outgoingCount + total.internalCount),\n );\n };\n },\n );\n\n getFlowThicknessScale = createSelector(\n this.getFlowMagnitudeExtent,\n getFlowThicknessScale,\n );\n\n getCircleSizeScale = createSelector(\n this.getMaxLocationCircleSize,\n this.getLocationTotalsEnabled,\n this.getLocationTotalsExtent,\n (maxLocationCircleSize, locationTotalsEnabled, locationTotalsExtent) => {\n if (!locationTotalsEnabled) {\n return () => maxLocationCircleSize;\n }\n if (!locationTotalsExtent) return undefined;\n return scaleSqrt()\n .range([0, maxLocationCircleSize])\n .domain([\n 0,\n // should support diff mode too\n Math.max.apply(\n null,\n locationTotalsExtent.map((x: number | undefined) =>\n Math.abs(x || 0),\n ),\n ),\n ]);\n },\n );\n\n getInCircleSizeGetter = createSelector(\n this.getCircleSizeScale,\n this.getLocationTotals,\n (circleSizeScale, locationTotals) => {\n return (locationId: string | number) => {\n const total = locationTotals?.get(locationId);\n if (total && circleSizeScale) {\n return (\n circleSizeScale(\n Math.abs(total.incomingCount + total.internalCount),\n ) || 0\n );\n }\n return 0;\n };\n },\n );\n\n getOutCircleSizeGetter = createSelector(\n this.getCircleSizeScale,\n this.getLocationTotals,\n (circleSizeScale, locationTotals) => {\n return (locationId: string | number) => {\n const total = locationTotals?.get(locationId);\n if (total && circleSizeScale) {\n return (\n circleSizeScale(\n Math.abs(total.outgoingCount + total.internalCount),\n ) || 0\n );\n }\n return 0;\n };\n },\n );\n\n getSortedLocationsForZoom: Selector =\n createSelector(\n this.getLocationsForZoom,\n this.getInCircleSizeGetter,\n this.getOutCircleSizeGetter,\n (locations, getInCircleSize, getOutCircleSize) => {\n if (!locations) return undefined;\n const nextLocations = [...locations] as L[] | ClusterNode[];\n return nextLocations.sort((a, b) => {\n const idA = this.accessors.getLocationId(a);\n const idB = this.accessors.getLocationId(b);\n return ascending(\n Math.max(getInCircleSize(idA), getOutCircleSize(idA)),\n Math.max(getInCircleSize(idB), getOutCircleSize(idB)),\n );\n });\n },\n );\n\n getLocationsForFlowmapLayer: Selector<\n L,\n F,\n Array | undefined\n > = createSelector(\n this.getSortedLocationsForZoom,\n // this.getLocationIdsInViewport,\n (\n locations,\n // locationIdsInViewport\n ) => {\n // if (!locations) return undefined;\n // if (!locationIdsInViewport) return locations;\n // if (locationIdsInViewport.size === locations.length) return locations;\n // const filtered = [];\n // for (const loc of locations) {\n // if (locationIdsInViewport.has(loc.id)) {\n // filtered.push(loc);\n // }\n // }\n // return filtered;\n // @ts-ignore\n // return locations.filter(\n // (loc: L | ClusterNode) => locationIdsInViewport!.has(loc.id)\n // );\n // TODO: return location in viewport + \"connected\" ones\n return locations;\n },\n );\n\n getLocationsForFlowmapLayerById: Selector<\n L,\n F,\n Map | undefined\n > = createSelector(this.getLocationsForFlowmapLayer, (locations) => {\n if (!locations) return undefined;\n return locations.reduce(\n (m: Map, d: L | ClusterNode) => (\n m.set(this.accessors.getLocationId(d), d),\n m\n ),\n new Map(),\n );\n });\n\n getLocationOrClusterByIdGetter = createSelector(\n this.getClusterIndex,\n this.getLocationsById,\n (clusterIndex, locationsById) => {\n return (id: string | number) =>\n clusterIndex?.getClusterById(id) ?? locationsById?.get(id);\n },\n );\n\n getLayersData: Selector = createSelector(\n this.getLocationsForFlowmapLayer,\n this.getFlowsForFlowmapLayer,\n this.getFlowmapColorsRGBA,\n this.getLocationsForFlowmapLayerById,\n this.getLocationIdsInViewport,\n this.getInCircleSizeGetter,\n this.getOutCircleSizeGetter,\n this.getFlowThicknessScale,\n this.getViewport,\n this.getFlowLinesRenderingMode,\n this.getLocationLabelsEnabled,\n (\n locations,\n flows,\n flowmapColors,\n locationsById,\n locationIdsInViewport,\n getInCircleSize,\n getOutCircleSize,\n flowThicknessScale,\n viewport,\n flowLinesRenderingMode,\n locationLabelsEnabled,\n ) => {\n return this._prepareLayersData(\n locations,\n flows,\n flowmapColors,\n locationsById,\n locationIdsInViewport,\n getInCircleSize,\n getOutCircleSize,\n flowThicknessScale,\n viewport,\n flowLinesRenderingMode,\n locationLabelsEnabled,\n );\n },\n );\n\n prepareLayersData(state: FlowmapState, props: FlowmapData): LayersData {\n const locations = this.getLocationsForFlowmapLayer(state, props) || [];\n const flows = this.getFlowsForFlowmapLayer(state, props) || [];\n const flowmapColors = (\n this.getFlowmapColorsRGBA as Selector\n )(state, props);\n const locationsById = this.getLocationsForFlowmapLayerById(state, props);\n const locationIdsInViewport = this.getLocationIdsInViewport(state, props);\n const getInCircleSize = this.getInCircleSizeGetter(state, props);\n const getOutCircleSize = this.getOutCircleSizeGetter(state, props);\n const flowThicknessScale = this.getFlowThicknessScale(state, props);\n const locationLabelsEnabled = this.getLocationLabelsEnabled(state, props);\n const viewport = this.getViewport(state, props);\n return this._prepareLayersData(\n locations,\n flows,\n flowmapColors,\n locationsById,\n locationIdsInViewport,\n getInCircleSize,\n getOutCircleSize,\n flowThicknessScale,\n viewport,\n state.settings.flowLinesRenderingMode,\n locationLabelsEnabled,\n );\n }\n\n _prepareLayersData(\n locations: (L | ClusterNode)[] | undefined,\n flows: (F | AggregateFlow)[] | undefined,\n flowmapColors: DiffColorsRGBA | ColorsRGBA,\n locationsById: Map | undefined,\n locationIdsInViewport: Set | undefined,\n getInCircleSize: (locationId: string | number) => number,\n getOutCircleSize: (locationId: string | number) => number,\n flowThicknessScale: ScaleLinear | undefined,\n viewport: ViewportProps,\n flowLinesRenderingMode: FlowLinesRenderingMode,\n locationLabelsEnabled: boolean,\n ): LayersData {\n if (!locations) locations = [];\n if (!flows) flows = [];\n const {\n getFlowOriginId,\n getFlowDestId,\n getFlowMagnitude,\n getLocationId,\n getLocationLon,\n getLocationLat,\n getLocationName,\n } = this.accessors;\n\n const flowMagnitudeExtent = extent(flows, (f) => getFlowMagnitude(f)) as [\n number,\n number,\n ];\n const flowColorScale = getFlowColorScale(\n flowmapColors,\n flowMagnitudeExtent,\n flowLinesRenderingMode === 'animated-straight',\n );\n\n // Using a generator here helps to avoid creating intermediary arrays\n const circlePositions = Float64Array.from(\n (function* () {\n for (const location of locations) {\n yield getLocationLon(location);\n yield getLocationLat(location);\n yield 0;\n }\n })(),\n );\n\n // TODO: diff mode\n const circleColor = isDiffColorsRGBA(flowmapColors)\n ? flowmapColors.positive.locationCircles.inner\n : flowmapColors.locationCircles.inner;\n\n const circleColors = Uint8Array.from(\n (function* () {\n for (const location of locations) {\n yield* circleColor;\n }\n })(),\n );\n\n const inCircleRadii = Float32Array.from(\n (function* () {\n for (const location of locations) {\n const id = getLocationId(location);\n yield locationIdsInViewport?.has(id) ? getInCircleSize(id) : 1.0;\n }\n })(),\n );\n const outCircleRadii = Float32Array.from(\n (function* () {\n for (const location of locations) {\n const id = getLocationId(location);\n yield locationIdsInViewport?.has(id) ? getOutCircleSize(id) : 1.0;\n }\n })(),\n );\n\n const sourcePositions = Float64Array.from(\n (function* () {\n for (const flow of flows) {\n const loc = locationsById?.get(getFlowOriginId(flow));\n yield loc ? getLocationLon(loc) : 0;\n yield loc ? getLocationLat(loc) : 0;\n yield 0;\n }\n })(),\n );\n const targetPositions = Float64Array.from(\n (function* () {\n for (const flow of flows) {\n const loc = locationsById?.get(getFlowDestId(flow));\n yield loc ? getLocationLon(loc) : 0;\n yield loc ? getLocationLat(loc) : 0;\n yield 0;\n }\n })(),\n );\n const thicknesses = Float32Array.from(\n (function* () {\n for (const flow of flows) {\n yield flowThicknessScale\n ? flowThicknessScale(getFlowMagnitude(flow)) || 0\n : 0;\n }\n })(),\n );\n const endpointOffsets = Float32Array.from(\n (function* () {\n for (const flow of flows) {\n const originId = getFlowOriginId(flow);\n const destId = getFlowDestId(flow);\n yield Math.max(getInCircleSize(originId), getOutCircleSize(originId));\n yield Math.max(getInCircleSize(destId), getOutCircleSize(destId));\n }\n })(),\n );\n const flowLineColors = Uint8Array.from(\n (function* () {\n for (const flow of flows) {\n yield* flowColorScale(getFlowMagnitude(flow));\n }\n })(),\n );\n\n const staggeringValues =\n flowLinesRenderingMode === 'animated-straight'\n ? Float32Array.from(\n (function* () {\n for (const f of flows) {\n // @ts-ignore\n yield new alea(`${getFlowOriginId(f)}-${getFlowDestId(f)}`)();\n }\n })(),\n )\n : undefined;\n\n const curveOffsets =\n flowLinesRenderingMode === 'curved'\n ? calculateCurveOffsets(\n flows,\n viewport,\n locationsById,\n getFlowOriginId,\n getFlowDestId,\n getLocationLon,\n getLocationLat,\n )\n : undefined;\n\n return {\n circleAttributes: {\n length: locations.length,\n attributes: {\n getPosition: {value: circlePositions, size: 3},\n getColor: {value: circleColors, size: 4},\n getInRadius: {value: inCircleRadii, size: 1},\n getOutRadius: {value: outCircleRadii, size: 1},\n },\n },\n lineAttributes: {\n length: flows.length,\n attributes: {\n getSourcePosition: {value: sourcePositions, size: 3},\n getTargetPosition: {value: targetPositions, size: 3},\n getThickness: {value: thicknesses, size: 1},\n getColor: {value: flowLineColors, size: 4},\n getEndpointOffsets: {value: endpointOffsets, size: 2},\n ...(staggeringValues\n ? {getStaggering: {value: staggeringValues, size: 1}}\n : {}),\n ...(curveOffsets\n ? {getCurveOffset: {value: curveOffsets, size: 1}}\n : {}),\n },\n },\n ...(locationLabelsEnabled\n ? {locationLabels: locations.map(getLocationName)}\n : undefined),\n };\n }\n\n getLocationsInBbox(\n tree: KDBushTree,\n bbox: [number, number, number, number],\n ): Array | undefined {\n if (!tree) return undefined;\n return this._getLocationsInBboxIndices(tree, bbox).map(\n (idx: number) => tree.points[idx],\n ) as Array;\n }\n\n _getLocationsInBboxIndices(\n tree: KDBushTree,\n bbox: [number, number, number, number],\n ) {\n if (!tree) return undefined;\n const [lon1, lat1, lon2, lat2] = bbox;\n const [x1, y1, x2, y2] = [lngX(lon1), latY(lat1), lngX(lon2), latY(lat2)];\n return tree.range(\n Math.min(x1, x2),\n Math.min(y1, y2),\n Math.max(x1, x2),\n Math.max(y1, y2),\n );\n }\n\n isFlowInSelection(\n flow: F | AggregateFlow,\n selectedLocationsSet: Set | undefined,\n locationFilterMode?: LocationFilterMode,\n ) {\n const origin = this.accessors.getFlowOriginId(flow);\n const dest = this.accessors.getFlowDestId(flow);\n if (selectedLocationsSet) {\n switch (locationFilterMode) {\n case LocationFilterMode.ALL:\n return (\n selectedLocationsSet.has(origin) || selectedLocationsSet.has(dest)\n );\n case LocationFilterMode.BETWEEN:\n return (\n selectedLocationsSet.has(origin) && selectedLocationsSet.has(dest)\n );\n case LocationFilterMode.INCOMING:\n return selectedLocationsSet.has(dest);\n case LocationFilterMode.OUTGOING:\n return selectedLocationsSet.has(origin);\n }\n }\n return true;\n }\n\n // calcLocationTotals(\n // locations: (L | ClusterNode)[],\n // flows: F[],\n // ): LocationsTotals {\n // return flows.reduce(\n // (acc: LocationsTotals, curr) => {\n // const originId = this.accessors.getFlowOriginId(curr);\n // const destId = this.accessors.getFlowDestId(curr);\n // const magnitude = this.accessors.getFlowMagnitude(curr);\n // if (originId === destId) {\n // acc.internal[originId] = (acc.internal[originId] || 0) + magnitude;\n // } else {\n // acc.outgoing[originId] = (acc.outgoing[originId] || 0) + magnitude;\n // acc.incoming[destId] = (acc.incoming[destId] || 0) + magnitude;\n // }\n // return acc;\n // },\n // {incoming: {}, outgoing: {}, internal: {}},\n // );\n // }\n}\n\nfunction calcLocationTotalsExtent(\n locationTotals: Map | undefined,\n locationIdsInViewport: Set | undefined,\n) {\n if (!locationTotals) return undefined;\n let rv: [number, number] | undefined = undefined;\n for (const [\n id,\n {incomingCount, outgoingCount, internalCount},\n ] of locationTotals.entries()) {\n if (locationIdsInViewport == null || locationIdsInViewport.has(id)) {\n const lo = Math.min(\n incomingCount + internalCount,\n outgoingCount + internalCount,\n internalCount,\n );\n const hi = Math.max(\n incomingCount + internalCount,\n outgoingCount + internalCount,\n internalCount,\n );\n if (!rv) {\n rv = [lo, hi];\n } else {\n if (lo < rv[0]) rv[0] = lo;\n if (hi > rv[1]) rv[1] = hi;\n }\n }\n }\n return rv;\n}\n\n// longitude/latitude to spherical mercator in [0..1] range\nfunction lngX(lng: number) {\n return lng / 360 + 0.5;\n}\n\nfunction latY(lat: number) {\n const sin = Math.sin((lat * Math.PI) / 180);\n const y = 0.5 - (0.25 * Math.log((1 + sin) / (1 - sin))) / Math.PI;\n return y < 0 ? 0 : y > 1 ? 1 : y;\n}\n\nfunction aggregateFlows(\n flows: F[],\n flowAccessors: FlowAccessors,\n): AggregateFlow[] {\n // Sum up flows with same origin, dest\n const byOriginDest = rollup(\n flows,\n (ff: F[]) => {\n const origin = flowAccessors.getFlowOriginId(ff[0]);\n const dest = flowAccessors.getFlowDestId(ff[0]);\n // const color = ff[0].color;\n const rv: AggregateFlow = {\n aggregate: true,\n origin,\n dest,\n count: ff.reduce((m, f) => {\n const count = flowAccessors.getFlowMagnitude(f);\n if (count) {\n if (!isNaN(count) && isFinite(count)) return m + count;\n }\n return m;\n }, 0),\n // time: undefined,\n };\n // if (color) rv.color = color;\n return rv;\n },\n flowAccessors.getFlowOriginId,\n flowAccessors.getFlowDestId,\n );\n\n const rv: AggregateFlow[] = [];\n for (const values of byOriginDest.values()) {\n for (const value of values.values()) {\n rv.push(value);\n }\n }\n return rv;\n}\n\n/**\n * This is used to augment hover picking info so that we can displace location tooltip\n * @param circleAttributes\n * @param index\n */\nexport function getOuterCircleRadiusByIndex(\n circleAttributes: FlowCirclesLayerAttributes,\n index: number,\n): number {\n const {getInRadius, getOutRadius} = circleAttributes.attributes;\n return Math.max(getInRadius.value[index], getOutRadius.value[index]);\n}\n\nexport function getLocationCoordsByIndex(\n circleAttributes: FlowCirclesLayerAttributes,\n index: number,\n): [number, number] {\n const {getPosition} = circleAttributes.attributes;\n const offset = index * getPosition.size;\n return [getPosition.value[offset], getPosition.value[offset + 1]];\n}\n\nexport function getFlowLineAttributesByIndex(\n lineAttributes: FlowLinesLayerAttributes,\n index: number,\n): FlowLinesLayerAttributes {\n const {\n getColor,\n getCurveOffset,\n getEndpointOffsets,\n getSourcePosition,\n getTargetPosition,\n getThickness,\n getStaggering,\n } = lineAttributes.attributes;\n return {\n length: 1,\n attributes: {\n getColor: {\n value: getColor.value.subarray(index * 4, (index + 1) * 4),\n size: 4,\n },\n getEndpointOffsets: {\n value: getEndpointOffsets.value.subarray(index * 2, (index + 1) * 2),\n size: 2,\n },\n getSourcePosition: {\n value: getSourcePosition.value.subarray(\n index * getSourcePosition.size,\n (index + 1) * getSourcePosition.size,\n ),\n size: getSourcePosition.size,\n },\n getTargetPosition: {\n value: getTargetPosition.value.subarray(\n index * getTargetPosition.size,\n (index + 1) * getTargetPosition.size,\n ),\n size: getTargetPosition.size,\n },\n getThickness: {\n value: getThickness.value.subarray(index, index + 1),\n size: 1,\n },\n ...(getStaggering\n ? {\n getStaggering: {\n value: getStaggering.value.subarray(index, index + 1),\n size: 1,\n },\n }\n : undefined),\n ...(getCurveOffset\n ? {\n getCurveOffset: {\n value: getCurveOffset.value.subarray(index, index + 1),\n size: 1,\n },\n }\n : undefined),\n },\n };\n}\n\ntype FlowLineScreenGeometry = {\n index: number;\n originId: string | number;\n destId: string | number;\n sx: number;\n sy: number;\n tx: number;\n ty: number;\n chordLengthPx: number;\n};\n\nfunction calculateCurveOffsets(\n flows: (F | AggregateFlow)[],\n viewport: ViewportProps,\n locationsById: Map | undefined,\n getFlowOriginId: (flow: F | AggregateFlow) => string | number,\n getFlowDestId: (flow: F | AggregateFlow) => string | number,\n getLocationLon: (location: L | ClusterNode) => number,\n getLocationLat: (location: L | ClusterNode) => number,\n): Float32Array {\n const curveOffsets = new Float32Array(flows.length);\n const corridorBuckets = new Map();\n const worldScale = 512 * Math.pow(2, viewport.zoom ?? 0);\n\n flows.forEach((flow, index) => {\n const originId = getFlowOriginId(flow);\n const destId = getFlowDestId(flow);\n const origin = locationsById?.get(originId);\n const dest = locationsById?.get(destId);\n if (!origin || !dest) {\n return;\n }\n\n const sourceLon = getLocationLon(origin);\n const sourceLat = getLocationLat(origin);\n const targetLon = getLocationLon(dest);\n const targetLat = getLocationLat(dest);\n const sx = lngX(sourceLon) * worldScale;\n const sy = latY(sourceLat) * worldScale;\n const tx = lngX(targetLon) * worldScale;\n const ty = latY(targetLat) * worldScale;\n\n let corridorSourceX = sx;\n let corridorSourceY = sy;\n let corridorTargetX = tx;\n let corridorTargetY = ty;\n if (\n corridorSourceX > corridorTargetX ||\n (corridorSourceX === corridorTargetX && corridorSourceY > corridorTargetY)\n ) {\n [corridorSourceX, corridorTargetX] = [corridorTargetX, corridorSourceX];\n [corridorSourceY, corridorTargetY] = [corridorTargetY, corridorSourceY];\n }\n\n const dx = corridorTargetX - corridorSourceX;\n const dy = corridorTargetY - corridorSourceY;\n const chordLengthPx = Math.hypot(dx, dy);\n if (!isFinite(chordLengthPx) || chordLengthPx < 1) {\n return;\n }\n\n const angle = ((Math.atan2(dy, dx) % Math.PI) + Math.PI) % Math.PI;\n const signedDistance =\n (corridorSourceX * corridorTargetY - corridorSourceY * corridorTargetX) /\n chordLengthPx;\n const key = [\n Math.round(angle / ((6 * Math.PI) / 180)),\n Math.round(signedDistance / 18),\n Math.round(chordLengthPx / 24),\n ].join(':');\n\n const bucket = corridorBuckets.get(key) ?? [];\n bucket.push({index, originId, destId, sx, sy, tx, ty, chordLengthPx});\n corridorBuckets.set(key, bucket);\n });\n\n corridorBuckets.forEach((bucket) => {\n bucket\n .sort((a, b) => {\n const originCompare = compareIds(a.originId, b.originId);\n if (originCompare !== 0) return originCompare;\n const destCompare = compareIds(a.destId, b.destId);\n if (destCompare !== 0) return destCompare;\n return a.index - b.index;\n })\n .forEach((entry, bucketIndex) => {\n const maxOffsetPx = Math.min(72, entry.chordLengthPx * 0.35);\n curveOffsets[entry.index] = Math.min(\n maxOffsetPx,\n (bucketIndex + 1) * 18,\n );\n });\n });\n\n return curveOffsets;\n}\n\nfunction compareIds(a: string | number, b: string | number): number {\n if (typeof a === 'number' && typeof b === 'number') {\n return a - b;\n }\n const aString = String(a);\n const bString = String(b);\n if (aString < bString) return -1;\n if (aString > bString) return 1;\n return 0;\n}\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n AggregateFlow,\n ClusterNode,\n FlowmapDataAccessors,\n isAggregateFlow,\n isCluster,\n isLocationClusterNode,\n} from './types';\n\nexport default class FlowmapAggregateAccessors<\n L extends Record,\n F extends Record,\n> {\n private accessors: FlowmapDataAccessors;\n constructor(accessors: FlowmapDataAccessors) {\n this.accessors = accessors;\n }\n\n setAccessors(accessors: FlowmapDataAccessors) {\n this.accessors = accessors;\n }\n\n getFlowmapDataAccessors() {\n return this.accessors;\n }\n\n getLocationId = (location: L | ClusterNode): string | number =>\n isLocationClusterNode(location)\n ? location.id\n : this.accessors.getLocationId(location);\n\n getLocationName = (location: L | ClusterNode): string => {\n let name;\n if (isLocationClusterNode(location) && isCluster(location)) {\n name = location.name;\n } else if (this.accessors.getLocationName) {\n name = this.accessors.getLocationName(location as L);\n }\n if (!name) name = `${this.getLocationId(location)}`;\n return name;\n };\n\n getLocationLat = (location: L | ClusterNode): number =>\n isLocationClusterNode(location)\n ? location.lat\n : this.accessors.getLocationLat(location);\n\n getLocationLon = (location: L | ClusterNode): number =>\n isLocationClusterNode(location)\n ? location.lon\n : this.accessors.getLocationLon(location);\n\n getFlowOriginId = (f: F | AggregateFlow) => {\n return isAggregateFlow(f) ? f.origin : this.accessors.getFlowOriginId(f);\n };\n\n getFlowDestId = (f: F | AggregateFlow) => {\n return isAggregateFlow(f) ? f.dest : this.accessors.getFlowDestId(f);\n };\n\n getFlowMagnitude = (f: F | AggregateFlow) => {\n return isAggregateFlow(f) ? f.count : this.accessors.getFlowMagnitude(f);\n };\n\n // Note: Aggregate flows have no time\n getFlowTime = (f: F) => {\n const {getFlowTime} = this.accessors;\n return getFlowTime ? getFlowTime(f) : undefined;\n };\n}\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n AggregateFlow,\n Cluster,\n ClusterLevels,\n ClusterNode,\n FlowAccessors,\n FlowCountsMapReduce,\n isCluster,\n} from './../types';\nimport {ascending, bisectLeft, extent} from 'd3-array';\n\nexport type LocationWeightGetter = (id: string | number) => number;\n\n/**\n * A data structure representing the cluster levels for efficient flow aggregation.\n */\nexport interface ClusterIndex {\n availableZoomLevels: number[];\n getClusterById: (clusterId: string | number) => Cluster | undefined;\n /**\n * List the nodes on the given zoom level.\n */\n getClusterNodesFor: (zoom: number | undefined) => ClusterNode[] | undefined;\n /**\n * Get the min zoom level on which the location is not clustered.\n */\n getMinZoomForLocation: (locationId: string | number) => number;\n /**\n * List the IDs of all locations in the cluster (leaves of the subtree starting in the cluster).\n */\n expandCluster: (cluster: Cluster, targetZoom?: number) => string[];\n /**\n * Find the cluster the given location is residing in on the specified zoom level.\n */\n findClusterFor: (\n locationId: string | number,\n zoom: number,\n ) => string | number | undefined;\n /**\n * Aggregate flows for the specified zoom level.\n */\n aggregateFlows: (\n flows: F[],\n zoom: number,\n {getFlowOriginId, getFlowDestId, getFlowMagnitude}: FlowAccessors,\n options?: {\n flowCountsMapReduce?: FlowCountsMapReduce;\n },\n ) => (F | AggregateFlow)[];\n}\n\n/**\n * Build ClusterIndex from the given cluster hierarchy\n */\nexport function buildIndex(clusterLevels: ClusterLevels): ClusterIndex {\n const nodesByZoom = new Map();\n const clustersById = new Map();\n const minZoomByLocationId = new Map();\n for (const {zoom, nodes} of clusterLevels) {\n nodesByZoom.set(zoom, nodes);\n for (const node of nodes) {\n if (isCluster(node)) {\n clustersById.set(node.id, node);\n } else {\n const {id} = node;\n const mz = minZoomByLocationId.get(id);\n if (mz == null || mz > zoom) {\n minZoomByLocationId.set(id, zoom);\n }\n }\n }\n }\n\n const [minZoom, maxZoom] = extent(clusterLevels, (cl) => cl.zoom);\n if (minZoom == null || maxZoom == null) {\n throw new Error('Could not determine minZoom or maxZoom');\n }\n\n const leavesToClustersByZoom = new Map<\n number,\n Map\n >();\n\n for (const cluster of clustersById.values()) {\n const {zoom} = cluster;\n let leavesToClusters = leavesToClustersByZoom.get(zoom);\n if (!leavesToClusters) {\n leavesToClusters = new Map();\n leavesToClustersByZoom.set(zoom, leavesToClusters);\n }\n visitClusterLeaves(cluster, (leafId) => {\n leavesToClusters?.set(leafId, cluster);\n });\n }\n\n function visitClusterLeaves(cluster: Cluster, visit: (id: string) => void) {\n for (const childId of cluster.children) {\n const child = clustersById.get(childId);\n if (child) {\n visitClusterLeaves(child, visit);\n } else {\n visit(childId);\n }\n }\n }\n\n const expandCluster = (cluster: Cluster, targetZoom: number = maxZoom) => {\n const ids: string[] = [];\n const visit = (c: Cluster, expandedIds: (string | number)[]) => {\n if (targetZoom > c.zoom) {\n for (const childId of c.children) {\n const child = clustersById.get(childId);\n if (child) {\n visit(child, expandedIds);\n } else {\n expandedIds.push(childId);\n }\n }\n } else {\n expandedIds.push(c.id);\n }\n };\n visit(cluster, ids);\n return ids;\n };\n\n function findClusterFor(locationId: string | number, zoom: number) {\n const leavesToClusters = leavesToClustersByZoom.get(zoom);\n if (!leavesToClusters) {\n return undefined;\n }\n const cluster = leavesToClusters.get(locationId);\n return cluster ? cluster.id : undefined;\n }\n\n const availableZoomLevels = clusterLevels\n .map((cl) => +cl.zoom)\n .sort((a, b) => ascending(a, b));\n\n return {\n availableZoomLevels,\n\n getClusterNodesFor: (zoom) => {\n if (zoom === undefined) {\n return undefined;\n }\n return nodesByZoom.get(zoom);\n },\n\n getClusterById: (clusterId) => clustersById.get(clusterId),\n\n getMinZoomForLocation: (locationId) =>\n minZoomByLocationId.get(locationId) || minZoom,\n\n expandCluster,\n\n findClusterFor,\n\n aggregateFlows: (\n flows,\n zoom,\n {getFlowOriginId, getFlowDestId, getFlowMagnitude},\n options = {},\n ) => {\n if (zoom > maxZoom) {\n return flows;\n }\n const result: (F | AggregateFlow)[] = [];\n const aggFlowsByKey = new Map();\n const makeKey = (origin: string | number, dest: string | number) =>\n `${origin}:${dest}`;\n const {\n flowCountsMapReduce = {\n map: getFlowMagnitude,\n reduce: (acc: any, count: number) => (acc || 0) + count,\n },\n } = options;\n for (const flow of flows) {\n const origin = getFlowOriginId(flow);\n const dest = getFlowDestId(flow);\n const originCluster = findClusterFor(origin, zoom) || origin;\n const destCluster = findClusterFor(dest, zoom) || dest;\n const key = makeKey(originCluster, destCluster);\n if (originCluster === origin && destCluster === dest) {\n result.push(flow);\n } else {\n let aggregateFlow = aggFlowsByKey.get(key);\n if (!aggregateFlow) {\n aggregateFlow = {\n origin: originCluster,\n dest: destCluster,\n count: flowCountsMapReduce.map(flow),\n aggregate: true,\n };\n result.push(aggregateFlow);\n aggFlowsByKey.set(key, aggregateFlow);\n } else {\n aggregateFlow.count = flowCountsMapReduce.reduce(\n aggregateFlow.count,\n flowCountsMapReduce.map(flow),\n );\n }\n }\n }\n return result;\n },\n };\n}\n\nexport function makeLocationWeightGetter(\n flows: F[],\n {getFlowOriginId, getFlowDestId, getFlowMagnitude}: FlowAccessors,\n): LocationWeightGetter {\n const locationTotals = {\n incoming: new Map(),\n outgoing: new Map(),\n };\n for (const flow of flows) {\n const origin = getFlowOriginId(flow);\n const dest = getFlowDestId(flow);\n const count = getFlowMagnitude(flow);\n locationTotals.incoming.set(\n dest,\n (locationTotals.incoming.get(dest) || 0) + count,\n );\n locationTotals.outgoing.set(\n origin,\n (locationTotals.outgoing.get(origin) || 0) + count,\n );\n }\n return (id: string | number) =>\n Math.max(\n Math.abs(locationTotals.incoming.get(id) || 0),\n Math.abs(locationTotals.outgoing.get(id) || 0),\n );\n}\n\n/**\n * @param availableZoomLevels Must be sorted in ascending order\n * @param targetZoom\n */\nexport function findAppropriateZoomLevel(\n availableZoomLevels: number[],\n targetZoom: number,\n) {\n if (!availableZoomLevels.length) {\n throw new Error('No available zoom levels');\n }\n return availableZoomLevels[\n Math.min(\n bisectLeft(availableZoomLevels, Math.floor(targetZoom)),\n availableZoomLevels.length - 1,\n )\n ];\n}\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {min, rollup} from 'd3-array';\nimport KDBush from 'kdbush';\nimport {LocationWeightGetter} from './ClusterIndex';\nimport {Cluster, ClusterLevel, ClusterNode, LocationAccessors} from '../types';\n\n/**\n * The code in this file is a based on https://github.com/mapbox/supercluster\n *\n * ISC License\n *\n * Copyright (c) 2016, Mapbox\n *\n * Permission to use, copy, modify, and/or distribute this software for any purpose\n * with or without fee is hereby granted, provided that the above copyright notice\n * and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\n * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\n * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\n * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS\n * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER\n * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF\n * THIS SOFTWARE.\n */\n\nexport interface Options {\n minZoom: number; // min zoom to generate clusters on\n maxZoom: number; // max zoom level to cluster the points on\n radius: number; // cluster radius in pixels\n extent: number; // tile extent (radius is calculated relative to it)\n nodeSize: number; // size of the KD-tree leaf node, affects performance\n makeClusterName: (id: number, numPoints: number) => string | undefined;\n makeClusterId: (id: number) => string;\n}\n\nconst defaultOptions: Options = {\n minZoom: 0,\n maxZoom: 16,\n radius: 40,\n extent: 512,\n nodeSize: 64,\n makeClusterName: (id: number, numPoints: number) => undefined,\n makeClusterId: (id: number) => `{[${id}]}`,\n};\n\ninterface BasePoint {\n x: number; // projected point coordinates\n y: number;\n weight: number;\n zoom: number; // the last zoom the point was processed at\n parentId: number; // parent cluster id\n}\n\ninterface LeafPoint extends BasePoint {\n index: number; // index of the source feature in the original input array,\n location: L;\n}\n\ninterface ClusterPoint extends BasePoint {\n id: number;\n numPoints: number;\n}\n\ntype Point = LeafPoint | ClusterPoint;\n\nexport function isLeafPoint(p: Point): p is LeafPoint {\n const {index} = p as LeafPoint;\n return index != null;\n}\n\nexport function isClusterPoint(p: Point): p is ClusterPoint {\n const {id} = p as ClusterPoint;\n return id != null;\n}\n\ntype ZoomLevelKDBush = any;\n\nexport function clusterLocations(\n locations: Iterable,\n locationAccessors: LocationAccessors,\n getLocationWeight: LocationWeightGetter,\n options?: Partial,\n): ClusterLevel[] {\n const {getLocationLon, getLocationLat, getLocationId} = locationAccessors;\n const opts = {\n ...defaultOptions,\n ...options,\n };\n const {minZoom, maxZoom, nodeSize, makeClusterName, makeClusterId} = opts;\n\n const trees = new Array(maxZoom + 1);\n\n // generate a cluster object for each point and index input points into a KD-tree\n let clusters = new Array>();\n let locationsCount = 0;\n for (const location of locations) {\n const x = getLocationLon(location);\n const y = getLocationLat(location);\n clusters.push({\n x: lngX(x), // projected point coordinates\n y: latY(y),\n weight: getLocationWeight(getLocationId(location)),\n zoom: Infinity, // the last zoom the point was processed at\n index: locationsCount, // index of the source feature in the original input array,\n parentId: -1, // parent cluster id\n location,\n });\n locationsCount++;\n }\n\n const makeBush = (points: Point[]) => {\n const bush = new KDBush(points.length, nodeSize, Float32Array);\n for (let i = 0; i < points.length; i++) {\n bush.add(points[i].x, points[i].y);\n }\n bush.finish();\n bush.points = points;\n return bush;\n };\n\n // cluster points on max zoom, then cluster the results on previous zoom, etc.;\n // results in a cluster hierarchy across zoom levels\n trees[maxZoom + 1] = makeBush(clusters);\n let prevZoom = maxZoom + 1;\n\n for (let z = maxZoom; z >= minZoom; z--) {\n // create a new set of clusters for the zoom and index them with a KD-tree\n const _clusters = cluster(clusters, z, trees[prevZoom], opts);\n if (_clusters.length === clusters.length) {\n // same number of clusters => move the higher level clusters up\n // no need to keep the same data on multiple levels\n trees[z] = trees[prevZoom];\n trees[prevZoom] = undefined;\n prevZoom = z;\n clusters = _clusters;\n } else {\n prevZoom = z;\n clusters = _clusters;\n trees[z] = makeBush(clusters);\n }\n }\n\n if (trees.length === 0) {\n return [];\n }\n\n const numbersOfClusters: number[] = trees.map((d) => d?.points.length);\n const minClusters = min(numbersOfClusters.filter((d) => d > 0));\n\n let maxAvailZoom =\n findIndexOfMax(numbersOfClusters) ?? numbersOfClusters.length - 1;\n\n const numUniqueLocations = countUniqueLocations(locations, locationAccessors);\n if (numUniqueLocations < locationsCount) {\n // Duplicate locations would be clustered together at any zoom level which can lead to having too many zooms.\n // To avoid that, we need to find the max zoom level that has less or equal clusters than unique locations\n // and drop all zoom levels beyond that (except the unclustered level).\n const maxClustersZoom = findLastIndex(\n numbersOfClusters,\n (d) => d <= numUniqueLocations,\n );\n if (maxClustersZoom >= 0) {\n // Now, move the unclustered points to the next zoom level to avoid having a gap\n if (maxClustersZoom < maxAvailZoom) {\n trees[maxClustersZoom + 1] = trees[maxAvailZoom];\n trees.splice(maxClustersZoom + 2); // Remove all zoom levels beyond maxClustersZoom\n }\n maxAvailZoom = maxClustersZoom + 1;\n }\n }\n\n const minAvailZoom = Math.min(\n maxAvailZoom,\n minClusters ? numbersOfClusters.lastIndexOf(minClusters) : maxAvailZoom,\n );\n\n const clusterLevels = new Array();\n prevZoom = NaN;\n for (let zoom = maxAvailZoom; zoom >= minAvailZoom; zoom--) {\n let childrenByParent: Map | undefined;\n const tree = trees[zoom];\n if (!tree) continue;\n if (trees[prevZoom] && zoom < maxAvailZoom) {\n childrenByParent = rollup(\n trees[prevZoom].points,\n (points: any[]) =>\n points.map((p: any) =>\n p.id ? makeClusterId(p.id) : getLocationId(p.location),\n ),\n (point: any) => point.parentId,\n );\n }\n\n const nodes: ClusterNode[] = [];\n for (const point of tree.points) {\n const {x, y, numPoints, location} = point;\n if (isLeafPoint(point)) {\n nodes.push({\n id: getLocationId(location),\n zoom,\n lat: getLocationLat(location),\n lon: getLocationLon(location),\n });\n } else if (isClusterPoint(point)) {\n const {id} = point;\n const children = childrenByParent && childrenByParent.get(id);\n if (!children) {\n // Might happen if there are multiple locations with same coordinates\n console.warn(`Omitting cluster with no children, point:`, point);\n continue;\n }\n const cluster = {\n id: makeClusterId(id),\n name: makeClusterName(id, numPoints),\n zoom,\n lat: yLat(y),\n lon: xLng(x),\n children: children ?? [],\n } as Cluster;\n nodes.push(cluster);\n }\n }\n clusterLevels.push({\n zoom,\n nodes,\n });\n prevZoom = zoom;\n }\n return clusterLevels;\n}\n\nfunction createCluster(\n x: number,\n y: number,\n id: number,\n numPoints: number,\n weight: number,\n): ClusterPoint {\n return {\n x, // weighted cluster center\n y,\n zoom: Infinity, // the last zoom the cluster was processed at\n id, // encodes index of the first child of the cluster and its zoom level\n parentId: -1, // parent cluster id\n numPoints,\n weight,\n };\n}\n\nfunction cluster(\n points: Point[],\n zoom: number,\n tree: ZoomLevelKDBush,\n options: Options,\n) {\n const clusters: Point[] = [];\n const {radius, extent} = options;\n const r = radius / (extent * Math.pow(2, zoom));\n\n // loop through each point\n for (let i = 0; i < points.length; i++) {\n const p = points[i];\n // if we've already visited the point at this zoom level, skip it\n if (p.zoom <= zoom) {\n continue;\n }\n p.zoom = zoom;\n\n // find all nearby points\n const neighborIds = tree.within(p.x, p.y, r);\n\n let weight = p.weight || 1;\n let numPoints = isClusterPoint(p) ? p.numPoints : 1;\n let wx = p.x * weight;\n let wy = p.y * weight;\n\n // encode both zoom and point index on which the cluster originated\n const id = (i << 5) + (zoom + 1);\n\n for (const neighborId of neighborIds) {\n const b = tree.points[neighborId];\n // filter out neighbors that are already processed\n if (b.zoom <= zoom) {\n continue;\n }\n b.zoom = zoom; // save the zoom (so it doesn't get processed twice)\n\n const weight2 = b.weight || 1;\n const numPoints2 = b.numPoints || 1;\n wx += b.x * weight2; // accumulate coordinates for calculating weighted center\n wy += b.y * weight2;\n\n weight += weight2;\n numPoints += numPoints2;\n b.parentId = id;\n }\n\n if (numPoints === 1) {\n clusters.push(p);\n } else {\n p.parentId = id;\n clusters.push(\n createCluster(wx / weight, wy / weight, id, numPoints, weight),\n );\n }\n }\n\n return clusters;\n}\n\n// spherical mercator to longitude/latitude\nfunction xLng(x: number) {\n return (x - 0.5) * 360;\n}\n\nfunction yLat(y: number) {\n const y2 = ((180 - y * 360) * Math.PI) / 180;\n return (360 * Math.atan(Math.exp(y2))) / Math.PI - 90;\n}\n\n// longitude/latitude to spherical mercator in [0..1] range\nfunction lngX(lng: number) {\n return lng / 360 + 0.5;\n}\n\nfunction latY(lat: number) {\n const sin = Math.sin((lat * Math.PI) / 180);\n const y = 0.5 - (0.25 * Math.log((1 + sin) / (1 - sin))) / Math.PI;\n return y < 0 ? 0 : y > 1 ? 1 : y;\n}\n\nfunction getX(p: Point) {\n return p.x;\n}\n\nfunction getY(p: Point) {\n return p.y;\n}\n\nfunction countUniqueLocations(\n locations: Iterable,\n locationAccessors: LocationAccessors,\n) {\n const {getLocationLon, getLocationLat} = locationAccessors;\n const countByLatLon = new Map();\n let uniqueCnt = 0;\n for (const loc of locations) {\n const lon = getLocationLon(loc);\n const lat = getLocationLat(loc);\n const key = `${lon},${lat}`;\n const prev = countByLatLon.get(key);\n if (!prev) {\n uniqueCnt++;\n }\n countByLatLon.set(key, prev ? prev + 1 : 1);\n }\n return uniqueCnt;\n}\n\nfunction findIndexOfMax(arr: (number | undefined)[]): number | undefined {\n let max = -Infinity;\n let maxIndex: number | undefined = undefined;\n\n for (let i = 0; i < arr.length; i++) {\n const value = arr[i];\n\n if (typeof value === 'number') {\n if (value > max) {\n max = value;\n maxIndex = i;\n }\n }\n }\n\n return maxIndex;\n}\n\nfunction findLastIndex(\n arr: T[],\n predicate: (value: T, index: number, array: T[]) => boolean,\n): number {\n for (let i = arr.length - 1; i >= 0; i--) {\n if (predicate(arr[i], i, arr)) {\n return i;\n }\n }\n return -1;\n}\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {WebMercatorViewport} from '@math.gl/web-mercator';\nimport {\n ClusterLevel,\n isCluster,\n LocationAccessors,\n ViewportProps,\n} from './types';\nimport {scaleLinear} from 'd3-scale';\nimport {ClusterIndex, LocationWeightGetter} from './cluster/ClusterIndex';\nimport {descending} from 'd3-array';\n\n// TODO: use re-reselect\n\nexport const getViewportBoundingBox = (\n viewport: ViewportProps,\n maxLocationCircleSize = 0,\n): [number, number, number, number] => {\n const pad = maxLocationCircleSize;\n const bounds = new WebMercatorViewport({\n ...viewport,\n width: viewport.width + pad * 2,\n height: viewport.height + pad * 2,\n }).getBounds();\n return [bounds[0][0], bounds[0][1], bounds[1][0], bounds[1][1]];\n};\n\nexport const makeViewportProjector = (viewport: ViewportProps) => {\n const mercatorViewport = new WebMercatorViewport(viewport);\n return (coords: [number, number]): [number, number] => {\n const [x, y] = mercatorViewport.project(coords);\n return [x, y];\n };\n};\n\nexport const getFlowThicknessScale = (\n magnitudeExtent: [number, number] | undefined,\n) => {\n if (!magnitudeExtent) return undefined;\n return scaleLinear()\n .range([0.025, 0.5])\n .domain([\n 0,\n // should support diff mode too\n Math.max.apply(\n null,\n magnitudeExtent.map((x: number | undefined) => Math.abs(x || 0)),\n ),\n ]);\n};\n\n/**\n * Adding meaningful cluster names.\n * NOTE: this will mutate the nodes in clusterIndex\n */\nexport function addClusterNames(\n clusterIndex: ClusterIndex,\n clusterLevels: ClusterLevel[],\n locationsById: Map,\n locationAccessors: LocationAccessors,\n getLocationWeight: LocationWeightGetter,\n): void {\n const {getLocationId, getLocationName, getLocationClusterName} =\n locationAccessors;\n const getName = (id: string | number) => {\n const loc = locationsById.get(id);\n if (loc) {\n return getLocationName ? getLocationName(loc) : getLocationId(loc) || id;\n }\n return `\"${id}\"`;\n };\n for (const level of clusterLevels) {\n for (const node of level.nodes) {\n // Here mutating the nodes (adding names)\n if (isCluster(node)) {\n const leaves = clusterIndex.expandCluster(node);\n\n leaves.sort((a, b) =>\n descending(getLocationWeight(a), getLocationWeight(b)),\n );\n\n if (getLocationClusterName) {\n node.name = getLocationClusterName(leaves);\n } else {\n const topId = leaves[0];\n const otherId = leaves.length === 2 ? leaves[1] : undefined;\n node.name = `\"${getName(topId)}\" and ${\n otherId ? `\"${getName(otherId)}\"` : `${leaves.length - 1} others`\n }`;\n }\n } else {\n (node as any).name = getName(node.id);\n }\n }\n }\n}\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {timeFormat, timeParse} from 'd3-time-format';\nimport {\n timeDay,\n timeHour,\n TimeInterval,\n timeMinute,\n timeMonth,\n timeSecond,\n timeWeek,\n timeYear,\n} from 'd3-time';\n\nconst dateParsers = [\n timeParse('%Y-%m-%d'),\n timeParse('%Y-%m-%d %H:%M'),\n timeParse('%Y-%m-%d %H:%M:%S'),\n timeParse('%Y'),\n timeParse('%Y-%m'),\n];\n\nexport function parseTime(input: string | Date | undefined): Date | undefined {\n if (input != null) {\n if (input instanceof Date) {\n return input;\n }\n for (const parse of dateParsers) {\n const date = parse(input);\n if (date) {\n return date;\n }\n }\n }\n return undefined;\n}\n\nexport enum TimeGranularityKey {\n SECOND = 'SECOND',\n MINUTE = 'MINUTE',\n HOUR = 'HOUR',\n DAY = 'DAY',\n MONTH = 'MONTH',\n YEAR = 'YEAR',\n}\n\nexport interface TimeGranularity {\n key: TimeGranularityKey;\n order: number;\n interval: TimeInterval;\n format: (date: Date) => string;\n formatFull: (date: Date) => string;\n}\n\n// const preferredLocale = navigator.languages ? navigator.languages[0] : 'en';\n\nconst formatMillisecond = timeFormat('.%L'),\n formatSecond = timeFormat(':%S'),\n formatMinute = timeFormat('%I:%M'),\n // formatHour = (d: Date) => d.toLocaleString(preferredLocale, { hour: 'numeric' }),\n formatHour = timeFormat('%I %p'),\n formatDay = timeFormat('%a %d'),\n formatWeek = timeFormat('%b %d'),\n formatMonth = timeFormat('%b'),\n formatYear = timeFormat('%Y');\n\nexport function tickMultiFormat(date: Date) {\n return (\n timeSecond(date) < date\n ? formatMillisecond\n : timeMinute(date) < date\n ? formatSecond\n : timeHour(date) < date\n ? formatMinute\n : timeDay(date) < date\n ? formatHour\n : timeMonth(date) < date\n ? timeWeek(date) < date\n ? formatDay\n : formatWeek\n : timeYear(date) < date\n ? formatMonth\n : formatYear\n )(date);\n}\n\nexport const TIME_GRANULARITIES: TimeGranularity[] = [\n {\n order: 0,\n key: TimeGranularityKey.SECOND,\n interval: timeSecond,\n format: formatSecond,\n formatFull: timeFormat('%Y-%m-%d %H:%M:%S'),\n },\n {\n order: 1,\n key: TimeGranularityKey.MINUTE,\n interval: timeMinute,\n format: formatMinute,\n formatFull: timeFormat('%Y-%m-%d %H:%M'),\n },\n {\n order: 2,\n key: TimeGranularityKey.HOUR,\n interval: timeHour,\n // format: (d: Date) => d.toLocaleString(preferredLocale, { hour: 'numeric', minute: '2-digit' }),\n format: formatHour,\n formatFull: timeFormat('%a %d %b %Y, %I %p'),\n },\n {\n order: 3,\n key: TimeGranularityKey.DAY,\n interval: timeDay,\n format: formatDay,\n formatFull: timeFormat('%a %d %b %Y'),\n },\n {\n order: 4,\n key: TimeGranularityKey.MONTH,\n interval: timeMonth,\n format: formatMonth,\n formatFull: timeFormat('%b %Y'),\n },\n {\n order: 5,\n key: TimeGranularityKey.YEAR,\n interval: timeYear,\n format: formatYear,\n formatFull: timeFormat('%Y'),\n },\n];\n\nexport function getTimeGranularityByKey(key: TimeGranularityKey) {\n return TIME_GRANULARITIES.find((s) => s.key === key);\n}\n\nexport function getTimeGranularityByOrder(order: number) {\n return TIME_GRANULARITIES.find((s) => s.order === order);\n}\n\nexport function getTimeGranularityForDate(date: Date): TimeGranularity {\n let prev = undefined;\n for (const current of TIME_GRANULARITIES) {\n const {interval} = current;\n const floored = interval(date);\n if (floored < date) {\n if (!prev) return current;\n return prev;\n }\n prev = current;\n }\n return TIME_GRANULARITIES[TIME_GRANULARITIES.length - 1];\n}\n\nexport function areRangesEqual(\n a: [Date, Date] | undefined,\n b: [Date, Date] | undefined,\n): boolean {\n if (!a && !b) return true;\n if (!a || !b) return false;\n return a[0] === b[0] && a[1] === b[1];\n}\n","export var epsilon = 1e-6;\nexport var epsilon2 = 1e-12;\nexport var pi = Math.PI;\nexport var halfPi = pi / 2;\nexport var quarterPi = pi / 4;\nexport var tau = pi * 2;\n\nexport var degrees = 180 / pi;\nexport var radians = pi / 180;\n\nexport var abs = Math.abs;\nexport var atan = Math.atan;\nexport var atan2 = Math.atan2;\nexport var cos = Math.cos;\nexport var ceil = Math.ceil;\nexport var exp = Math.exp;\nexport var floor = Math.floor;\nexport var hypot = Math.hypot;\nexport var log = Math.log;\nexport var pow = Math.pow;\nexport var sin = Math.sin;\nexport var sign = Math.sign || function(x) { return x > 0 ? 1 : x < 0 ? -1 : 0; };\nexport var sqrt = Math.sqrt;\nexport var tan = Math.tan;\n\nexport function acos(x) {\n return x > 1 ? 0 : x < -1 ? pi : Math.acos(x);\n}\n\nexport function asin(x) {\n return x > 1 ? halfPi : x < -1 ? -halfPi : Math.asin(x);\n}\n\nexport function haversin(x) {\n return (x = sin(x / 2)) * x;\n}\n","export default function noop() {}\n","function streamGeometry(geometry, stream) {\n if (geometry && streamGeometryType.hasOwnProperty(geometry.type)) {\n streamGeometryType[geometry.type](geometry, stream);\n }\n}\n\nvar streamObjectType = {\n Feature: function(object, stream) {\n streamGeometry(object.geometry, stream);\n },\n FeatureCollection: function(object, stream) {\n var features = object.features, i = -1, n = features.length;\n while (++i < n) streamGeometry(features[i].geometry, stream);\n }\n};\n\nvar streamGeometryType = {\n Sphere: function(object, stream) {\n stream.sphere();\n },\n Point: function(object, stream) {\n object = object.coordinates;\n stream.point(object[0], object[1], object[2]);\n },\n MultiPoint: function(object, stream) {\n var coordinates = object.coordinates, i = -1, n = coordinates.length;\n while (++i < n) object = coordinates[i], stream.point(object[0], object[1], object[2]);\n },\n LineString: function(object, stream) {\n streamLine(object.coordinates, stream, 0);\n },\n MultiLineString: function(object, stream) {\n var coordinates = object.coordinates, i = -1, n = coordinates.length;\n while (++i < n) streamLine(coordinates[i], stream, 0);\n },\n Polygon: function(object, stream) {\n streamPolygon(object.coordinates, stream);\n },\n MultiPolygon: function(object, stream) {\n var coordinates = object.coordinates, i = -1, n = coordinates.length;\n while (++i < n) streamPolygon(coordinates[i], stream);\n },\n GeometryCollection: function(object, stream) {\n var geometries = object.geometries, i = -1, n = geometries.length;\n while (++i < n) streamGeometry(geometries[i], stream);\n }\n};\n\nfunction streamLine(coordinates, stream, closed) {\n var i = -1, n = coordinates.length - closed, coordinate;\n stream.lineStart();\n while (++i < n) coordinate = coordinates[i], stream.point(coordinate[0], coordinate[1], coordinate[2]);\n stream.lineEnd();\n}\n\nfunction streamPolygon(coordinates, stream) {\n var i = -1, n = coordinates.length;\n stream.polygonStart();\n while (++i < n) streamLine(coordinates[i], stream, 1);\n stream.polygonEnd();\n}\n\nexport default function(object, stream) {\n if (object && streamObjectType.hasOwnProperty(object.type)) {\n streamObjectType[object.type](object, stream);\n } else {\n streamGeometry(object, stream);\n }\n}\n","import {Adder} from \"d3-array\";\nimport {atan2, cos, quarterPi, radians, sin, tau} from \"./math.js\";\nimport noop from \"./noop.js\";\nimport stream from \"./stream.js\";\n\nexport var areaRingSum = new Adder();\n\n// hello?\n\nvar areaSum = new Adder(),\n lambda00,\n phi00,\n lambda0,\n cosPhi0,\n sinPhi0;\n\nexport var areaStream = {\n point: noop,\n lineStart: noop,\n lineEnd: noop,\n polygonStart: function() {\n areaRingSum = new Adder();\n areaStream.lineStart = areaRingStart;\n areaStream.lineEnd = areaRingEnd;\n },\n polygonEnd: function() {\n var areaRing = +areaRingSum;\n areaSum.add(areaRing < 0 ? tau + areaRing : areaRing);\n this.lineStart = this.lineEnd = this.point = noop;\n },\n sphere: function() {\n areaSum.add(tau);\n }\n};\n\nfunction areaRingStart() {\n areaStream.point = areaPointFirst;\n}\n\nfunction areaRingEnd() {\n areaPoint(lambda00, phi00);\n}\n\nfunction areaPointFirst(lambda, phi) {\n areaStream.point = areaPoint;\n lambda00 = lambda, phi00 = phi;\n lambda *= radians, phi *= radians;\n lambda0 = lambda, cosPhi0 = cos(phi = phi / 2 + quarterPi), sinPhi0 = sin(phi);\n}\n\nfunction areaPoint(lambda, phi) {\n lambda *= radians, phi *= radians;\n phi = phi / 2 + quarterPi; // half the angular distance from south pole\n\n // Spherical excess E for a spherical triangle with vertices: south pole,\n // previous point, current point. Uses a formula derived from Cagnoli’s\n // theorem. See Todhunter, Spherical Trig. (1871), Sec. 103, Eq. (2).\n var dLambda = lambda - lambda0,\n sdLambda = dLambda >= 0 ? 1 : -1,\n adLambda = sdLambda * dLambda,\n cosPhi = cos(phi),\n sinPhi = sin(phi),\n k = sinPhi0 * sinPhi,\n u = cosPhi0 * cosPhi + k * cos(adLambda),\n v = k * sdLambda * sin(adLambda);\n areaRingSum.add(atan2(v, u));\n\n // Advance the previous points.\n lambda0 = lambda, cosPhi0 = cosPhi, sinPhi0 = sinPhi;\n}\n\nexport default function(object) {\n areaSum = new Adder();\n stream(object, areaStream);\n return areaSum * 2;\n}\n","import {asin, atan2, cos, sin, sqrt} from \"./math.js\";\n\nexport function spherical(cartesian) {\n return [atan2(cartesian[1], cartesian[0]), asin(cartesian[2])];\n}\n\nexport function cartesian(spherical) {\n var lambda = spherical[0], phi = spherical[1], cosPhi = cos(phi);\n return [cosPhi * cos(lambda), cosPhi * sin(lambda), sin(phi)];\n}\n\nexport function cartesianDot(a, b) {\n return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];\n}\n\nexport function cartesianCross(a, b) {\n return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];\n}\n\n// TODO return a\nexport function cartesianAddInPlace(a, b) {\n a[0] += b[0], a[1] += b[1], a[2] += b[2];\n}\n\nexport function cartesianScale(vector, k) {\n return [vector[0] * k, vector[1] * k, vector[2] * k];\n}\n\n// TODO return d\nexport function cartesianNormalizeInPlace(d) {\n var l = sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]);\n d[0] /= l, d[1] /= l, d[2] /= l;\n}\n","import {Adder} from \"d3-array\";\nimport {areaStream, areaRingSum} from \"./area.js\";\nimport {cartesian, cartesianCross, cartesianNormalizeInPlace, spherical} from \"./cartesian.js\";\nimport {abs, degrees, epsilon, radians} from \"./math.js\";\nimport stream from \"./stream.js\";\n\nvar lambda0, phi0, lambda1, phi1, // bounds\n lambda2, // previous lambda-coordinate\n lambda00, phi00, // first point\n p0, // previous 3D point\n deltaSum,\n ranges,\n range;\n\nvar boundsStream = {\n point: boundsPoint,\n lineStart: boundsLineStart,\n lineEnd: boundsLineEnd,\n polygonStart: function() {\n boundsStream.point = boundsRingPoint;\n boundsStream.lineStart = boundsRingStart;\n boundsStream.lineEnd = boundsRingEnd;\n deltaSum = new Adder();\n areaStream.polygonStart();\n },\n polygonEnd: function() {\n areaStream.polygonEnd();\n boundsStream.point = boundsPoint;\n boundsStream.lineStart = boundsLineStart;\n boundsStream.lineEnd = boundsLineEnd;\n if (areaRingSum < 0) lambda0 = -(lambda1 = 180), phi0 = -(phi1 = 90);\n else if (deltaSum > epsilon) phi1 = 90;\n else if (deltaSum < -epsilon) phi0 = -90;\n range[0] = lambda0, range[1] = lambda1;\n },\n sphere: function() {\n lambda0 = -(lambda1 = 180), phi0 = -(phi1 = 90);\n }\n};\n\nfunction boundsPoint(lambda, phi) {\n ranges.push(range = [lambda0 = lambda, lambda1 = lambda]);\n if (phi < phi0) phi0 = phi;\n if (phi > phi1) phi1 = phi;\n}\n\nfunction linePoint(lambda, phi) {\n var p = cartesian([lambda * radians, phi * radians]);\n if (p0) {\n var normal = cartesianCross(p0, p),\n equatorial = [normal[1], -normal[0], 0],\n inflection = cartesianCross(equatorial, normal);\n cartesianNormalizeInPlace(inflection);\n inflection = spherical(inflection);\n var delta = lambda - lambda2,\n sign = delta > 0 ? 1 : -1,\n lambdai = inflection[0] * degrees * sign,\n phii,\n antimeridian = abs(delta) > 180;\n if (antimeridian ^ (sign * lambda2 < lambdai && lambdai < sign * lambda)) {\n phii = inflection[1] * degrees;\n if (phii > phi1) phi1 = phii;\n } else if (lambdai = (lambdai + 360) % 360 - 180, antimeridian ^ (sign * lambda2 < lambdai && lambdai < sign * lambda)) {\n phii = -inflection[1] * degrees;\n if (phii < phi0) phi0 = phii;\n } else {\n if (phi < phi0) phi0 = phi;\n if (phi > phi1) phi1 = phi;\n }\n if (antimeridian) {\n if (lambda < lambda2) {\n if (angle(lambda0, lambda) > angle(lambda0, lambda1)) lambda1 = lambda;\n } else {\n if (angle(lambda, lambda1) > angle(lambda0, lambda1)) lambda0 = lambda;\n }\n } else {\n if (lambda1 >= lambda0) {\n if (lambda < lambda0) lambda0 = lambda;\n if (lambda > lambda1) lambda1 = lambda;\n } else {\n if (lambda > lambda2) {\n if (angle(lambda0, lambda) > angle(lambda0, lambda1)) lambda1 = lambda;\n } else {\n if (angle(lambda, lambda1) > angle(lambda0, lambda1)) lambda0 = lambda;\n }\n }\n }\n } else {\n ranges.push(range = [lambda0 = lambda, lambda1 = lambda]);\n }\n if (phi < phi0) phi0 = phi;\n if (phi > phi1) phi1 = phi;\n p0 = p, lambda2 = lambda;\n}\n\nfunction boundsLineStart() {\n boundsStream.point = linePoint;\n}\n\nfunction boundsLineEnd() {\n range[0] = lambda0, range[1] = lambda1;\n boundsStream.point = boundsPoint;\n p0 = null;\n}\n\nfunction boundsRingPoint(lambda, phi) {\n if (p0) {\n var delta = lambda - lambda2;\n deltaSum.add(abs(delta) > 180 ? delta + (delta > 0 ? 360 : -360) : delta);\n } else {\n lambda00 = lambda, phi00 = phi;\n }\n areaStream.point(lambda, phi);\n linePoint(lambda, phi);\n}\n\nfunction boundsRingStart() {\n areaStream.lineStart();\n}\n\nfunction boundsRingEnd() {\n boundsRingPoint(lambda00, phi00);\n areaStream.lineEnd();\n if (abs(deltaSum) > epsilon) lambda0 = -(lambda1 = 180);\n range[0] = lambda0, range[1] = lambda1;\n p0 = null;\n}\n\n// Finds the left-right distance between two longitudes.\n// This is almost the same as (lambda1 - lambda0 + 360°) % 360°, except that we want\n// the distance between ±180° to be 360°.\nfunction angle(lambda0, lambda1) {\n return (lambda1 -= lambda0) < 0 ? lambda1 + 360 : lambda1;\n}\n\nfunction rangeCompare(a, b) {\n return a[0] - b[0];\n}\n\nfunction rangeContains(range, x) {\n return range[0] <= range[1] ? range[0] <= x && x <= range[1] : x < range[0] || range[1] < x;\n}\n\nexport default function(feature) {\n var i, n, a, b, merged, deltaMax, delta;\n\n phi1 = lambda1 = -(lambda0 = phi0 = Infinity);\n ranges = [];\n stream(feature, boundsStream);\n\n // First, sort ranges by their minimum longitudes.\n if (n = ranges.length) {\n ranges.sort(rangeCompare);\n\n // Then, merge any ranges that overlap.\n for (i = 1, a = ranges[0], merged = [a]; i < n; ++i) {\n b = ranges[i];\n if (rangeContains(a, b[0]) || rangeContains(a, b[1])) {\n if (angle(a[0], b[1]) > angle(a[0], a[1])) a[1] = b[1];\n if (angle(b[0], a[1]) > angle(a[0], a[1])) a[0] = b[0];\n } else {\n merged.push(a = b);\n }\n }\n\n // Finally, find the largest gap between the merged ranges.\n // The final bounding box will be the inverse of this gap.\n for (deltaMax = -Infinity, n = merged.length - 1, i = 0, a = merged[n]; i <= n; a = b, ++i) {\n b = merged[i];\n if ((delta = angle(a[1], b[0])) > deltaMax) deltaMax = delta, lambda0 = b[0], lambda1 = a[1];\n }\n }\n\n ranges = range = null;\n\n return lambda0 === Infinity || phi0 === Infinity\n ? [[NaN, NaN], [NaN, NaN]]\n : [[lambda0, phi0], [lambda1, phi1]];\n}\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {geoBounds} from 'd3-geo';\nimport {fitBounds} from '@math.gl/web-mercator';\nimport type {\n FeatureCollection,\n GeometryCollection,\n GeometryObject,\n} from 'geojson';\nimport type {ViewState} from './types';\n\nexport type LocationProperties = any;\n\nexport type GetViewStateOptions = {\n pad?: number; // size ratio\n padding?: {top: number; bottom: number; left: number; right: number};\n tileSize?: number;\n // minZoom?: number; // not supported by fitBounds\n maxZoom?: number;\n};\n\nexport function getViewStateForFeatures(\n featureCollection:\n | FeatureCollection\n | GeometryCollection,\n size: [number, number],\n opts?: GetViewStateOptions,\n): ViewState & {width: number; height: number} {\n const {pad = 0.05, maxZoom = 100} = opts || {};\n const bounds = geoBounds(featureCollection as any);\n const [[x1, y1], [x2, y2]] = bounds;\n const paddedBounds: [[number, number], [number, number]] = pad\n ? [\n [x1 - pad * (x2 - x1), y1 - pad * (y2 - y1)],\n [x2 + pad * (x2 - x1), y2 + pad * (y2 - y1)],\n ]\n : bounds;\n const [width, height] = size;\n return {\n ...fitBounds({\n width,\n height,\n bounds: paddedBounds,\n padding: opts?.padding,\n // minZoom,\n maxZoom,\n }),\n width,\n height,\n bearing: 0,\n pitch: 0,\n };\n}\n\nexport function getViewStateForLocations(\n locations: Iterable,\n getLocationCoords: (location: L) => [number, number],\n size: [number, number],\n opts?: GetViewStateOptions,\n): ViewState & {width: number; height: number} {\n const asGeometry = (location: L) => ({\n type: 'Point',\n coordinates: getLocationCoords(location),\n });\n let geometries;\n if (Array.isArray(locations)) {\n geometries = locations.map(asGeometry);\n } else {\n geometries = [];\n for (const location of locations) {\n geometries.push(asGeometry(location));\n }\n }\n return getViewStateForFeatures(\n {\n type: 'GeometryCollection',\n geometries,\n } as any,\n size,\n opts,\n );\n}\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {AggregateFlow, Cluster, LocationAccessors, LocationTotals} from '..';\nimport {FlowmapState} from '../FlowmapState';\nimport {\n ClusterNode,\n FlowmapData,\n FlowmapDataAccessors,\n LayersData,\n ViewportProps,\n} from '../types';\n\nexport default interface FlowmapDataProvider {\n setAccessors(accessors: FlowmapDataAccessors): void;\n\n setFlowmapState(flowmapState: FlowmapState): Promise;\n\n // clearData(): void;\n\n getViewportForLocations(\n dims: [number, number],\n ): Promise;\n\n // getFlowTotals(): Promise;\n\n getFlowByIndex(index: number): Promise;\n\n getLocationById(id: string | number): Promise;\n\n getLocationByIndex(idx: number): Promise;\n\n getTotalsForLocation(\n id: string | number,\n ): Promise;\n\n // getLocationsInBbox(\n // bbox: [number, number, number, number],\n // ): Promise | undefined>;\n\n // getLocationsForSearchBox(): Promise<(FlowLocation | ClusterNode)[] | undefined>;\n\n getLayersData(): Promise;\n\n /**\n * This is to give the data provider control over when/how often layersData\n * is updated which leads to the flowmap being redrawn.\n */\n updateLayersData(\n setLayersData: (layersData: LayersData | undefined) => void,\n changeFlags: Record,\n ): Promise;\n}\n\nexport function isFlowmapData(\n data: Record,\n): data is FlowmapData {\n return (\n data && data.locations && data.flows\n // TODO: test that they are iterable\n // Array.isArray(data.locations) &&\n // Array.isArray(data.flows)\n );\n}\n\nexport function isFlowmapDataProvider(\n dataProvider: Record,\n): dataProvider is FlowmapDataProvider {\n return (\n dataProvider &&\n typeof dataProvider.setFlowmapState === 'function' &&\n typeof dataProvider.getViewportForLocations === 'function' &&\n typeof dataProvider.getFlowByIndex === 'function' &&\n typeof dataProvider.getLocationById === 'function' &&\n typeof dataProvider.getLocationByIndex === 'function' &&\n typeof dataProvider.getLayersData === 'function'\n );\n}\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type FlowmapDataProvider from './FlowmapDataProvider';\nimport type {\n Cluster,\n ClusterNode,\n FlowmapData,\n FlowmapDataAccessors,\n LayersData,\n LocationTotals,\n ViewportProps,\n AggregateFlow,\n} from '../types';\nimport {FlowmapState} from '../FlowmapState';\nimport FlowmapSelectors from '../FlowmapSelectors';\nimport {\n GetViewStateOptions,\n getViewStateForLocations,\n} from '../getViewStateForLocations';\nimport {ClusterIndex} from '../cluster/ClusterIndex';\n\nexport default class LocalFlowmapDataProvider<\n L extends Record,\n F extends Record,\n> implements FlowmapDataProvider\n{\n private selectors: FlowmapSelectors;\n private flowmapData: FlowmapData | undefined;\n private flowmapState: FlowmapState | undefined;\n\n constructor(accessors: FlowmapDataAccessors) {\n // scope selectors to the concrete instance of FlowmapDataProvider\n this.selectors = new FlowmapSelectors(accessors);\n this.flowmapData = undefined;\n this.flowmapState = undefined;\n }\n\n setAccessors(accessors: FlowmapDataAccessors) {\n this.selectors.setAccessors(accessors);\n }\n\n setFlowmapData(flowmapData: FlowmapData): void {\n this.flowmapData = flowmapData;\n }\n\n getSelectors(): FlowmapSelectors {\n return this.selectors;\n }\n\n getFlowmapData(): FlowmapData | undefined {\n return this.flowmapData;\n }\n\n async setFlowmapState(flowmapState: FlowmapState): Promise {\n this.flowmapState = flowmapState;\n }\n\n getFlowmapState(): FlowmapState | undefined {\n return this.flowmapState;\n }\n\n async getFlowByIndex(idx: number): Promise {\n if (!this.flowmapState || !this.flowmapData) {\n return undefined;\n }\n const flows = this.selectors.getFlowsForFlowmapLayer(\n this.flowmapState,\n this.flowmapData,\n );\n return flows?.[idx];\n }\n\n // TODO: this is unreliable, should replace by unqiue ID\n async getLocationByIndex(idx: number): Promise {\n if (!this.flowmapState || !this.flowmapData) {\n return undefined;\n }\n const locations = this.selectors.getLocationsForFlowmapLayer(\n this.flowmapState,\n this.flowmapData,\n );\n return locations?.[idx];\n }\n\n async getLayersData(): Promise {\n if (!this.flowmapState || !this.flowmapData) {\n return undefined;\n }\n return this.selectors.getLayersData(this.flowmapState, this.flowmapData);\n }\n\n async getLocationById(id: string | number): Promise {\n if (!this.flowmapState || !this.flowmapData) {\n return undefined;\n }\n const clusterIndex = this.selectors.getClusterIndex(\n this.flowmapState,\n this.flowmapData,\n );\n if (clusterIndex) {\n const cluster = clusterIndex.getClusterById(id);\n if (cluster) {\n return cluster;\n }\n }\n const locationsById = this.selectors.getLocationsById(\n this.flowmapState,\n this.flowmapData,\n );\n return locationsById?.get(id);\n }\n\n async getTotalsForLocation(\n id: string | number,\n ): Promise {\n if (!this.flowmapState || !this.flowmapData) {\n return undefined;\n }\n return this.selectors\n .getLocationTotals(this.flowmapState, this.flowmapData)\n ?.get(id);\n }\n\n async getViewportForLocations(\n dims: [number, number],\n opts?: GetViewStateOptions,\n ): Promise {\n if (!this.flowmapData?.locations) {\n return undefined;\n }\n // @ts-ignore\n return getViewStateForLocations(\n this.flowmapData.locations,\n (loc) => [\n this.selectors.accessors.getLocationLon(loc),\n this.selectors.accessors.getLocationLat(loc),\n ],\n dims,\n opts,\n );\n }\n\n async updateLayersData(\n setLayersData: (layersData: LayersData | undefined) => void,\n ) {\n setLayersData(await this.getLayersData());\n }\n\n getClusterZoom(): number | undefined {\n return this.flowmapState && this.flowmapData\n ? this.selectors.getClusterZoom(this.flowmapState, this.flowmapData)\n : undefined;\n }\n\n getClusterIndex(): ClusterIndex | undefined {\n return this.flowmapState && this.flowmapData\n ? this.selectors.getClusterIndex(this.flowmapState, this.flowmapData)\n : undefined;\n }\n\n getLocationsById(): Map | undefined {\n return this.flowmapState && this.flowmapData\n ? this.selectors.getLocationsById(this.flowmapState, this.flowmapData)\n : undefined;\n }\n\n getLocationTotals(): Map | undefined {\n return this.flowmapState && this.flowmapData\n ? this.selectors.getLocationTotals(this.flowmapState, this.flowmapData)\n : undefined;\n }\n\n getFlowsForFlowmapLayer(): Array | undefined {\n return this.flowmapState && this.flowmapData\n ? this.selectors.getFlowsForFlowmapLayer(\n this.flowmapState,\n this.flowmapData,\n )\n : undefined;\n }\n}\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n AggregateFlow,\n Cluster,\n ClusterNode,\n LocationTotals,\n} from '@flowmap.gl/data';\n\nexport type LayerProps = Record;\n\nexport enum PickingType {\n LOCATION = 'location',\n FLOW = 'flow',\n // LOCATION_AREA = 'location-area',\n}\n\nexport type DeckGLLayer = Record;\n\nexport interface PickingInfo {\n layer: DeckGLLayer;\n index: number;\n picked: boolean;\n object: T | undefined;\n x: number;\n y: number;\n coordinate: [number, number];\n event: MouseEvent | undefined;\n}\n\nexport interface LocationPickingInfoObject {\n id: string | number;\n type: PickingType.LOCATION;\n location: L | ClusterNode;\n name: string;\n totals: LocationTotals;\n circleRadius: number;\n}\n\nexport type LocationPickingInfo = PickingInfo>;\n\nexport interface FlowPickingInfoObject {\n type: PickingType.FLOW;\n flow: F | AggregateFlow;\n origin: L | ClusterNode;\n dest: L | ClusterNode;\n count: number;\n}\n\nexport type FlowPickingInfo = PickingInfo>;\n\n// export interface LocationAreaPickingInfo extends PickingInfo {\n// type: PickingType.LOCATION_AREA;\n// object: FlowLocation;\n// }\n\nexport type FlowmapLayerPickingInfo =\n | LocationPickingInfo\n // | LocationAreaPickingInfo\n | FlowPickingInfo;\n\n// import {FeatureCollection, GeometryObject} from 'geojson';\n// export type LocationProperties = Record;\n\n// export type Locations =\n// | FeatureCollection\n// | FlowLocation[];\n\n// export function isFeatureCollection(\n// locations: Locations,\n// ): locations is FeatureCollection {\n// return (\n// (locations as FeatureCollection)\n// .type === 'FeatureCollection'\n// );\n// }\n","/*\n * Copyright (c) Flowmap.gl contributors\n * Copyright (c) 2018-2020 Teralytics\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {CompositeLayer} from '@deck.gl/core';\nimport {ScatterplotLayer, TextLayer} from '@deck.gl/layers';\nimport {\n FilterState,\n FlowEndpointsInViewportMode,\n FlowLinesLayerAttributes,\n FlowLinesRenderingMode,\n FlowmapAggregateAccessors,\n FlowmapData,\n FlowmapDataAccessors,\n FlowmapDataProvider,\n LayersData,\n LocalFlowmapDataProvider,\n ViewportProps,\n colorAsRgba,\n getFlowLineAttributesByIndex,\n getFlowmapColors,\n getLocationCoordsByIndex,\n getOuterCircleRadiusByIndex,\n isFlowmapData,\n isFlowmapDataProvider,\n} from '@flowmap.gl/data';\nimport AnimatedFlowLinesLayer from './AnimatedFlowLinesLayer';\nimport CurvedFlowLinesLayer from './CurvedFlowLinesLayer';\nimport FlowCirclesLayer from './FlowCirclesLayer';\nimport FlowLinesLayer from './FlowLinesLayer';\nimport {\n FlowmapLayerPickingInfo,\n LayerProps,\n PickingInfo,\n PickingType,\n} from './types';\n\nexport type FlowmapLayerProps<\n L extends Record,\n F extends Record,\n> = {\n data?: FlowmapData;\n dataProvider?: FlowmapDataProvider;\n filter?: FilterState;\n locationsEnabled?: boolean;\n locationTotalsEnabled?: boolean;\n locationLabelsEnabled?: boolean;\n adaptiveScalesEnabled?: boolean;\n flowLineThicknessScale?: number;\n flowLineCurviness?: number;\n flowLinesRenderingMode?: FlowLinesRenderingMode;\n animationEnabled?: boolean;\n clusteringEnabled?: boolean;\n clusteringLevel?: number;\n fadeEnabled?: boolean;\n fadeOpacityEnabled?: boolean;\n clusteringAuto?: boolean;\n darkMode?: boolean;\n fadeAmount?: number;\n colorScheme?: string | string[];\n highlightColor?: string | number[];\n maxTopFlowsDisplayNum?: number;\n flowEndpointsInViewportMode?: FlowEndpointsInViewportMode;\n onHover?: (\n info: FlowmapLayerPickingInfo | undefined,\n event: SourceEvent,\n ) => void;\n onClick?: (info: FlowmapLayerPickingInfo, event: SourceEvent) => void;\n} & Partial> &\n LayerProps;\n\nconst PROPS_TO_CAUSE_LAYER_DATA_UPDATE: string[] = [\n 'filter',\n 'locationsEnabled',\n 'locationTotalsEnabled',\n 'locationLabelsEnabled',\n 'adaptiveScalesEnabled',\n 'flowLinesRenderingMode',\n 'animationEnabled',\n 'clusteringEnabled',\n 'clusteringLevel',\n 'fadeEnabled',\n 'fadeOpacityEnabled',\n 'clusteringAuto',\n 'darkMode',\n 'fadeAmount',\n 'colorScheme',\n 'highlightColor',\n 'maxTopFlowsDisplayNum',\n 'flowEndpointsInViewportMode',\n];\n\nconst DEFAULT_FLOW_LINES_RENDERING_MODE: FlowLinesRenderingMode = 'straight';\n\nenum HighlightType {\n LOCATION = 'location',\n FLOW = 'flow',\n}\n\ntype HighlightedLocationObject = {\n type: HighlightType.LOCATION;\n coords: [number, number];\n radius: number;\n};\n\ntype HighlightedFlowObject = {\n type: HighlightType.FLOW;\n lineAttributes: FlowLinesLayerAttributes;\n};\n\ntype HighlightedObject = HighlightedLocationObject | HighlightedFlowObject;\n\ntype State, F extends Record> = {\n accessors: FlowmapAggregateAccessors;\n dataProvider: FlowmapDataProvider;\n layersData: LayersData | undefined;\n highlightedObject: HighlightedObject | undefined;\n pickingInfo: FlowmapLayerPickingInfo | undefined;\n lastHoverTime: number | undefined;\n lastClickTime: number | undefined;\n};\n\nexport type SourceEvent = {srcEvent: MouseEvent};\n\nexport default class FlowmapLayer<\n L extends Record,\n F extends Record,\n> extends CompositeLayer {\n private _didWarnAboutAnimationEnabledDeprecation = false;\n private _didWarnAboutAnimationEnabledConflict = false;\n\n static defaultProps = {\n darkMode: true,\n fadeAmount: 50,\n locationsEnabled: true,\n locationTotalsEnabled: true,\n locationLabelsEnabled: false,\n clusteringEnabled: true,\n fadeEnabled: true,\n fadeOpacityEnabled: false,\n clusteringAuto: true,\n clusteringLevel: undefined,\n adaptiveScalesEnabled: true,\n flowLineThicknessScale: 1,\n flowLineCurviness: 1,\n colorScheme: 'Teal',\n highlightColor: 'orange',\n maxTopFlowsDisplayNum: 5000,\n flowEndpointsInViewportMode: 'any',\n };\n state!: State;\n\n private get typedProps(): FlowmapLayerProps {\n return this.props as unknown as FlowmapLayerProps;\n }\n\n public constructor(props: FlowmapLayerProps) {\n super({\n ...props,\n onHover: ((info: PickingInfo, event: SourceEvent) => {\n const startTime = Date.now();\n this.setState({\n highlightedObject: this._getHighlightedObject(info),\n lastHoverTime: startTime,\n });\n\n const {onHover} = props;\n if (onHover) {\n this._getFlowmapLayerPickingInfo(info).then((info) => {\n if ((this.state?.lastHoverTime ?? 0) <= startTime) {\n this.setState({pickingInfo: info});\n onHover(info, event);\n } else {\n // Skipping, because this is not the latest hover event\n }\n });\n }\n }) as any,\n onClick: ((info: PickingInfo, event: SourceEvent) => {\n const {onClick} = props;\n const startTime = Date.now();\n this.setState({\n lastClickTime: startTime,\n });\n if (onClick) {\n this._getFlowmapLayerPickingInfo(info).then((info) => {\n if ((this.state?.lastClickTime ?? 0) <= startTime) {\n this.setState({pickingInfo: info});\n if (info) {\n onClick(info, event);\n }\n } else {\n // Skipping, because this is not the latest hover event\n }\n });\n }\n }) as any,\n } as any);\n }\n\n initializeState() {\n this.state = {\n accessors: new FlowmapAggregateAccessors(\n this.typedProps as FlowmapDataAccessors,\n ),\n dataProvider: this._getOrMakeDataProvider(),\n layersData: undefined,\n highlightedObject: undefined,\n pickingInfo: undefined,\n lastHoverTime: undefined,\n lastClickTime: undefined,\n };\n }\n\n getPickingInfo({info}: Record) {\n // This is for onHover event handlers set on the component\n if (!info.object) {\n const object = this.state?.pickingInfo?.object;\n if (object) {\n return {\n ...info,\n object,\n picked: true,\n };\n }\n }\n return info;\n }\n\n // private _updateAccessors() {\n // this.state?.dataProvider?.setAccessors(this.props);\n // this.setState({accessors: new FlowmapAggregateAccessors(this.props)});\n // }\n\n private _getOrMakeDataProvider() {\n const {data, dataProvider} = this.typedProps;\n if (dataProvider && isFlowmapDataProvider(dataProvider as any)) {\n return dataProvider;\n } else if (data && isFlowmapData(data as any)) {\n const dataProvider = new LocalFlowmapDataProvider(\n this.typedProps as FlowmapDataAccessors,\n );\n dataProvider.setFlowmapData(data);\n return dataProvider;\n }\n throw new Error(\n 'FlowmapLayer: data must be a FlowmapDataProvider or FlowmapData',\n );\n }\n\n private _updateDataProvider() {\n this.setState({dataProvider: this._getOrMakeDataProvider()});\n }\n\n shouldUpdateState(params: any): boolean {\n const {changeFlags} = params;\n // if (this._viewportChanged()) {\n // return true;\n // }\n if (changeFlags.viewportChanged) {\n return true;\n }\n return super.shouldUpdateState(params);\n // TODO: be smarter on when to update\n // (e.g. ignore viewport changes when adaptiveScalesEnabled and clustering are false)\n }\n\n updateState(params: any): void {\n super.updateState(params);\n const {oldProps, props, changeFlags} = params;\n if (changeFlags.propsChanged) {\n // this._updateAccessors();\n }\n if (changeFlags.dataChanged) {\n this._updateDataProvider();\n }\n if (changeFlags.viewportChanged || changeFlags.dataChanged) {\n this.setState({highlightedObject: undefined});\n }\n\n if (\n changeFlags.viewportChanged ||\n changeFlags.dataChanged ||\n (changeFlags.propsChanged &&\n PROPS_TO_CAUSE_LAYER_DATA_UPDATE.some(\n (prop) => oldProps[prop] !== props[prop],\n ))\n ) {\n const {dataProvider} = this.state || {};\n if (dataProvider) {\n dataProvider.setFlowmapState(this._getFlowmapState());\n dataProvider.updateLayersData((layersData: LayersData | undefined) => {\n this.setState({layersData, highlightedObject: undefined});\n }, changeFlags);\n }\n }\n }\n\n private _getSettingsState() {\n const props = this.typedProps;\n const defaults = FlowmapLayer.defaultProps;\n const {\n locationsEnabled,\n locationTotalsEnabled,\n locationLabelsEnabled,\n adaptiveScalesEnabled,\n flowLinesRenderingMode,\n clusteringEnabled,\n clusteringLevel,\n fadeEnabled,\n fadeOpacityEnabled,\n clusteringAuto,\n darkMode,\n fadeAmount,\n colorScheme,\n highlightColor,\n maxTopFlowsDisplayNum,\n flowEndpointsInViewportMode,\n } = props;\n return {\n locationsEnabled: locationsEnabled ?? defaults.locationsEnabled,\n locationTotalsEnabled:\n locationTotalsEnabled ?? defaults.locationTotalsEnabled,\n locationLabelsEnabled:\n locationLabelsEnabled ?? defaults.locationLabelsEnabled,\n adaptiveScalesEnabled:\n adaptiveScalesEnabled ?? defaults.adaptiveScalesEnabled,\n flowLinesRenderingMode:\n flowLinesRenderingMode ?? this._getResolvedFlowLinesRenderingMode(),\n clusteringEnabled: clusteringEnabled ?? defaults.clusteringEnabled,\n clusteringLevel,\n fadeEnabled: fadeEnabled ?? defaults.fadeEnabled,\n fadeOpacityEnabled: fadeOpacityEnabled ?? defaults.fadeOpacityEnabled,\n clusteringAuto: clusteringAuto ?? defaults.clusteringAuto,\n darkMode: darkMode ?? defaults.darkMode,\n fadeAmount: fadeAmount ?? defaults.fadeAmount,\n colorScheme,\n highlightColor: highlightColor ?? defaults.highlightColor,\n maxTopFlowsDisplayNum:\n maxTopFlowsDisplayNum ?? defaults.maxTopFlowsDisplayNum,\n flowEndpointsInViewportMode: (flowEndpointsInViewportMode ??\n defaults.flowEndpointsInViewportMode) as FlowEndpointsInViewportMode,\n };\n }\n\n private _getResolvedFlowLinesRenderingMode(): FlowLinesRenderingMode {\n const {animationEnabled, flowLinesRenderingMode} = this.typedProps;\n if (flowLinesRenderingMode !== undefined) {\n if (\n animationEnabled !== undefined &&\n !this._didWarnAboutAnimationEnabledConflict\n ) {\n this._didWarnAboutAnimationEnabledConflict = true;\n console.warn(\n 'FlowmapLayer: `animationEnabled` is deprecated and ignored when `flowLinesRenderingMode` is provided.',\n );\n }\n return flowLinesRenderingMode;\n }\n if (animationEnabled !== undefined) {\n if (!this._didWarnAboutAnimationEnabledDeprecation) {\n this._didWarnAboutAnimationEnabledDeprecation = true;\n console.warn(\n 'FlowmapLayer: `animationEnabled` is deprecated; use `flowLinesRenderingMode` instead.',\n );\n }\n return animationEnabled ? 'animated-straight' : 'straight';\n }\n return DEFAULT_FLOW_LINES_RENDERING_MODE;\n }\n\n private _getFlowmapState() {\n const props = this.typedProps;\n return {\n viewport: pickViewportProps(this.context.viewport),\n filter: props.filter,\n settings: this._getSettingsState(),\n };\n }\n\n private async _getFlowmapLayerPickingInfo(\n info: Record,\n ): Promise | undefined> {\n const {index, sourceLayer} = info;\n const {dataProvider, accessors} = this.state || {};\n if (!dataProvider || !accessors) {\n return undefined;\n }\n const commonInfo = {\n ...info,\n picked: info.picked,\n layer: info.layer,\n index: info.index,\n x: info.x,\n y: info.y,\n coordinate: info.coordinate,\n event: info.event,\n };\n if (\n sourceLayer instanceof FlowLinesLayer ||\n sourceLayer instanceof AnimatedFlowLinesLayer ||\n sourceLayer instanceof CurvedFlowLinesLayer\n ) {\n const flow =\n index === -1 ? undefined : await dataProvider.getFlowByIndex(index);\n if (flow) {\n const origin = await dataProvider.getLocationById(\n accessors.getFlowOriginId(flow),\n );\n const dest = await dataProvider.getLocationById(\n accessors.getFlowDestId(flow),\n );\n if (origin && dest) {\n return {\n ...commonInfo,\n object: {\n type: PickingType.FLOW,\n flow,\n origin: origin,\n dest: dest,\n count: accessors.getFlowMagnitude(flow),\n },\n };\n }\n }\n } else if (sourceLayer instanceof FlowCirclesLayer) {\n const location =\n index === -1 ? undefined : await dataProvider.getLocationByIndex(index);\n\n if (location) {\n const id = accessors.getLocationId(location);\n const name = accessors.getLocationName(location);\n const totals = await dataProvider.getTotalsForLocation(id);\n const {circleAttributes} = this.state?.layersData || {};\n if (totals && circleAttributes) {\n const circleRadius = getOuterCircleRadiusByIndex(\n circleAttributes,\n info.index,\n );\n return {\n ...commonInfo,\n object: {\n type: PickingType.LOCATION,\n location,\n id,\n name,\n totals,\n circleRadius: circleRadius,\n },\n };\n }\n }\n }\n\n return undefined;\n }\n\n private _getHighlightedObject(\n info: Record,\n ): HighlightedObject | undefined {\n const {index, sourceLayer} = info;\n if (index < 0) return undefined;\n if (\n sourceLayer instanceof FlowLinesLayer ||\n sourceLayer instanceof AnimatedFlowLinesLayer ||\n sourceLayer instanceof CurvedFlowLinesLayer\n ) {\n const {lineAttributes} = this.state?.layersData || {};\n if (lineAttributes) {\n let attrs = getFlowLineAttributesByIndex(lineAttributes, index);\n if (this.typedProps.fadeOpacityEnabled) {\n attrs = {\n ...attrs,\n attributes: {\n ...attrs.attributes,\n getColor: {\n ...attrs.attributes.getColor,\n value: new Uint8Array([\n ...attrs.attributes.getColor.value.slice(0, 3),\n 255, // the highlight color should be always opaque\n ]),\n },\n },\n };\n }\n return {\n type: HighlightType.FLOW,\n lineAttributes: attrs,\n };\n }\n } else if (sourceLayer instanceof FlowCirclesLayer) {\n const {circleAttributes} = this.state?.layersData || {};\n if (circleAttributes) {\n return {\n type: HighlightType.LOCATION,\n coords: getLocationCoordsByIndex(circleAttributes, index),\n radius: getOuterCircleRadiusByIndex(circleAttributes, index),\n };\n }\n }\n return undefined;\n }\n\n renderLayers(): Array {\n const props = this.typedProps;\n const flowLinesRenderingMode = this._getResolvedFlowLinesRenderingMode();\n const highlightColor =\n props.highlightColor ?? FlowmapLayer.defaultProps.highlightColor;\n const flowLineThicknessScale =\n props.flowLineThicknessScale ??\n FlowmapLayer.defaultProps.flowLineThicknessScale;\n const flowLineCurviness =\n props.flowLineCurviness ?? FlowmapLayer.defaultProps.flowLineCurviness;\n const layers = [];\n if (this.state?.layersData) {\n const {layersData, highlightedObject} = this.state;\n const {circleAttributes, lineAttributes, locationLabels} =\n layersData || {};\n if (circleAttributes && lineAttributes) {\n const flowmapColors = getFlowmapColors(this._getSettingsState());\n const outlineColor = colorAsRgba(\n flowmapColors.outlineColor || (props.darkMode ? '#000' : '#fff'),\n );\n const commonLineLayerProps = {\n data: lineAttributes,\n parameters: {\n ...((props.parameters as Record | undefined) ??\n {}),\n // prevent z-fighting at non-zero bearing/pitch\n depthTest: false,\n },\n };\n switch (flowLinesRenderingMode) {\n case 'animated-straight':\n layers.push(\n // @ts-ignore\n new AnimatedFlowLinesLayer({\n ...this.getSubLayerProps({\n ...commonLineLayerProps,\n id: 'animated-flow-lines',\n drawOutline: false,\n thicknessUnit: 10 * flowLineThicknessScale,\n }),\n }),\n );\n break;\n case 'curved':\n layers.push(\n new CurvedFlowLinesLayer({\n ...this.getSubLayerProps({\n ...commonLineLayerProps,\n id: 'curved-flow-lines',\n drawOutline: true,\n outlineColor: outlineColor,\n thicknessUnit: 12 * flowLineThicknessScale,\n curviness: flowLineCurviness,\n }),\n }),\n );\n break;\n case 'straight':\n default:\n layers.push(\n new FlowLinesLayer({\n ...this.getSubLayerProps({\n ...commonLineLayerProps,\n id: 'flow-lines',\n drawOutline: true,\n outlineColor: outlineColor,\n thicknessUnit: 12 * flowLineThicknessScale,\n }),\n }),\n );\n break;\n }\n layers.push(\n new FlowCirclesLayer(\n this.getSubLayerProps({\n id: 'circles',\n data: circleAttributes,\n emptyColor: props.darkMode\n ? [0, 0, 0, 255]\n : [255, 255, 255, 255],\n outlineEmptyMix: 0.4,\n }),\n ),\n );\n if (highlightedObject) {\n switch (highlightedObject.type) {\n case HighlightType.LOCATION:\n layers.push(\n new ScatterplotLayer({\n ...this.getSubLayerProps({\n id: 'location-highlight',\n data: [highlightedObject],\n pickable: false,\n antialiasing: true,\n stroked: true,\n filled: false,\n lineWidthUnits: 'pixels',\n getLineWidth: 2,\n radiusUnits: 'pixels',\n getRadius: (d: HighlightedLocationObject) => d.radius,\n getLineColor: colorAsRgba(highlightColor),\n getPosition: (d: HighlightedLocationObject) => d.coords,\n }),\n }),\n );\n break;\n case HighlightType.FLOW:\n if (flowLinesRenderingMode === 'curved') {\n layers.push(\n new CurvedFlowLinesLayer({\n ...this.getSubLayerProps({\n id: 'flow-highlight',\n data: highlightedObject.lineAttributes,\n drawOutline: true,\n pickable: false,\n outlineColor: colorAsRgba(highlightColor),\n outlineThickness: 1.5,\n thicknessUnit: 12 * flowLineThicknessScale,\n curviness: flowLineCurviness,\n parameters: {\n depthTest: false,\n },\n }),\n }),\n );\n } else {\n layers.push(\n new FlowLinesLayer({\n ...this.getSubLayerProps({\n id: 'flow-highlight',\n data: highlightedObject.lineAttributes,\n drawOutline: true,\n pickable: false,\n outlineColor: colorAsRgba(highlightColor),\n outlineThickness: 1.5,\n thicknessUnit: 12 * flowLineThicknessScale,\n parameters: {\n depthTest: false,\n },\n }),\n }),\n );\n }\n break;\n }\n }\n }\n if (locationLabels) {\n layers.push(\n new TextLayer(\n this.getSubLayerProps({\n id: 'location-labels',\n data: locationLabels,\n maxWidth: 1000,\n pickable: false,\n fontFamily: 'Helvetica',\n getPixelOffset: (d: string, {index}: {index: number}) => {\n const r = getOuterCircleRadiusByIndex(circleAttributes, index);\n return [0, r + 5];\n },\n getPosition: (d: string, {index}: {index: number}) => {\n const pos = getLocationCoordsByIndex(circleAttributes, index);\n return pos;\n },\n getText: (d: string) => d,\n getSize: 10,\n getColor: [255, 255, 255, 255],\n getAngle: 0,\n getTextAnchor: 'middle',\n getAlignmentBaseline: 'top',\n }),\n ),\n );\n }\n }\n\n return layers;\n }\n}\n\nfunction pickViewportProps(viewport: Record): ViewportProps {\n const {width, height, longitude, latitude, zoom, pitch, bearing} = viewport;\n return {\n width,\n height,\n longitude,\n latitude,\n zoom,\n pitch,\n bearing,\n };\n}\n","import {Deck} from '@deck.gl/core';\nimport {MapboxOverlay} from '@deck.gl/mapbox';\nimport {FlowmapLayer} from '@flowmap.gl/layers';\n\nwindow.FlowmapGL = {\n Deck,\n FlowmapLayer,\n MapboxOverlay\n};\n"],"mappings":"2nBAAA,IAEMA,GACAC,GACAC,GACAC,GACAC,GANNC,GAAAC,EAAA,KAEMN,GAAU,WACVC,GAAY,WAAW,UAAa,CAAA,EACpCC,GAAW,WAAW,SAAW,CAAA,EACjCC,GAAW,WAAW,QACtBC,GAAa,WAAW,WAAc,CAAA,ICHtC,SAAUG,GAAWC,EAAsB,CAQ/C,GALI,OAAO,OAAW,KAAe,OAAO,SAAS,OAAS,YAK1D,OAAO,QAAY,KAAuB,QAAQ,UAAW,SAC/D,MAAO,GAGT,IAAMC,EAAgB,OAAO,UAAc,KAAe,UAAU,UAC9DC,EAAYF,GAAiBC,EACnC,MAAO,GAAQC,GAAaA,EAAU,QAAQ,UAAU,GAAK,EAC/D,CAlBA,IAAAC,GAAAC,EAAA,QCMM,SAAUC,IAAS,CAIvB,MAAO,EADL,OAAO,SAAY,UAAY,OAAO,OAAO,IAAM,oBAAsB,CAAC,SAAS,UACnEC,GAAU,CAC9B,CAXA,IAAAC,GAAAC,EAAA,KAGAC,OCqCM,SAAUC,GACdC,EAAsB,CAEtB,MAAI,CAACA,GAAiB,CAACC,GAAS,EACvB,OAELC,GAAWF,CAAa,EACnB,YAGSA,GAAiBG,GAAU,WAAa,IAG5C,QAAQ,MAAM,EAAI,GACvB,OAEL,WAAW,OACN,SAEL,WAAW,OACN,SAEL,WAAW,gBACN,UAEF,SACT,CAlEA,IAAAC,GAAAC,EAAA,KAuBAC,KACAC,KACAC,OCzBA,IAEaC,GAFbC,GAAAC,EAAA,KAKAC,KACAC,K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A,UACA,UACA,UACA,UACA,UACA,WAEF,OAAQ,CACN,UACA,UACA,UACA,UACA,UACA,UACA,WAEF,KAAMG,GAAcW,EAAe,EACnC,SAAU,CACR,UACA,UACA,UACA,UACA,UACA,UACA,WAEF,MAAOJ,GACP,KAAMX,GAASC,EAAU,EACzB,QAASQ,GACT,OAAQT,GAASC,EAAY,EAC7B,MAAOD,GAASC,EAAW,EAC3B,QAASG,GAAcY,EAAkB,EACzC,QAAS,CACP,UACA,UACA,UACA,UACA,UACA,UACA,WAEF,MAAOZ,GAAca,EAAgB,EACrC,KAAM,CACJ,UACA,UACA,UACA,UACA,UACA,UACA,WAEF,QAASjB,GAASC,EAAa,EAC/B,KAAMD,GAASC,EAAU,EACzB,MAAO,CACL,UACA,UACA,UACA,UACA,UACA,UACA,WAEF,MAAO,CACL,UACA,UACA,UACA,UACA,UACA,UACA,WAEF,OAAQG,GAAcc,EAAiB,EACvC,OAAQ,CACN,UACA,UACA,UACA,UACA,UACA,UACA,WAEF,KAAMlB,GAASC,EAAU,EACzB,OAAQD,GAASC,EAAY,EAC7B,KAAMD,GAASC,EAAU,EACzB,KAAM,CACJ,UACA,UACA,UACA,UACA,UACA,UACA,WAEF,QAASD,GAASC,EAAa,EAC/B,OAAQ,CACN,UACA,UACA,UACA,UACA,UACA,UACA,WAEF,KAAMD,GAASC,EAAU,EACzB,MAAO,CACL,UACA,UACA,UACA,UACA,UACA,UACA,WAEF,KAAMD,GAASC,EAAU,EACzB,OAAQ,CACN,UACA,UACA,UACA,UACA,UACA,UACA,WAEF,WAAY,CACV,UACA,UACA,UACA,UACA,UACA,UACA,WAEF,KAAMW,GACN,QAAS,CACP,UACA,UACA,UACA,UACA,UACA,UACA,WAEF,QAASR,GAAce,EAAkB,EACzC,KAAMf,GAAcgB,EAAe,EACnC,KAAMpB,GAASC,EAAU,EACzB,OAAQD,GAASC,EAAY,EAC7B,OAAQD,GAASC,EAAY,EAC7B,OAAQD,GAASC,EAAY,GAGlBoB,IAAoB,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W,IACX,cAAY,GAAA6B,YACVC,aACD,CACD,UAAA,EAEJ,CACH,CAAA,EAAM,CAAC,SAII,IAAApB,GAAgB,SAChB,iBAAE,CACN,GAAA,iBACA,KAAAsB,EAAe,eACf,YAAY,GACZ,SAAA,GACA,aAAaK,GAAOrC,CAAA,EACpB,iBAAY,kBACC,GAAK6B,aACjB,CACD,UAAA,EAEJ,CACH,CAAA,CACD,CAAA,CAAM,EAEX,KACF,OAMO,KAAM,IAAAY,GAAc,KAAA,iBAAA,CACpB,GAAA,kBACA,KAAAR,EACA,SAAU,IACV,SAAA,cACS,2BACK,CAAA,EAAI,CAAE,MAAA3B,CAAA,IAET,CAAA,EADVkB,GAAAF,EAAAhB,CAAA,EACyB,CAAA,cAEjB,CAAG,EAAC,CAAA,MAAAA,CAAA,IACZsB,GAAAN,EAAAhB,CAAA,EAGD,QAAU,GAAM,EAChB,QAAQ,GACR,SAAA,CAAA,IAAe,IAAA,IAAQ,GAAA,EACvB,SAAA,EAGL,cAAC,SACH,qBAAA,KACF,CAAA,CAAA,CAAA,CAGF,SAriBM,MAEL,aAAc,CACd,SAAA,GACA,WAAA,GACA,iBAAA,GACA,sBAAuB,GACvB,sBAAiB,GACjB,kBAAkB,GAClB,YAAA,GACA,mBAAiB,GACjB,eAAA,GACA,gBAAA,OACA,sBAAoB,GACpB,oBAAmB,WACnB,uBAAwB,EACxB,kBAAA,EACA,YAAA,OACA,eAAA,+BAzB6B,IA+iBjC,4BAA2B,WAEzBoC,GAAO7E,YACLwC,GAAKsC,EAAA,IACL,CAAA,MAAAC,EAAM,OAAAC,EAAA,UAAAC,EAAA,SAAAC,EAAA,KAAAC,EAAA,MAAAC,EAAA,QAAAC,CAAA,EAAAP,QACN,CACA,MAAAC,EACA,OAAAC,EACA,UAAAC,EACA,SAAAC,EACA,KAAAC,EACH,MAAAC,aCnrBD,OAAO,UAAY,CACjB,KAAAE,GACA,aAAAC,GACA,cAAAC,EACF","names":["window_","document_","process_","console_","navigator_","init_globals","__esmMin","isElectron","mockUserAgent","realUserAgent","userAgent","init_is_electron","__esmMin","isBrowser","isElectron","init_is_browser","__esmMin","init_is_electron","getBrowser","mockUserAgent","isBrowser","isElectron","navigator_","init_get_browser","__esmMin","init_is_browser","init_is_electron","init_globals","VERSION","init_dist","__esmMin","init_globals","init_is_browser","init_get_browser","assert","condition","message","init_assert","__esmMin","normalizeLogLevel","logLevel","resolvedLevel","assert","normalizeArguments","opts","message","args","messageType","init_log_utils","__esmMin","init_assert","noop","BaseLog","init_base_log","__esmMin","init_log_utils","level","newLevel","message","args","logLevel","type","options","normalized","normalizeArguments","tag","normalizeLogLevel","getStorage","type","storage","x","LocalStorage","init_local_storage","__esmMin","id","defaultConfig","configuration","serialized","serializedConfiguration","formatTime","ms","formatted","leftPad","string","length","padLength","init_formatters","__esmMin","getColor","color","COLOR","addColor","string","background","isBrowser","BACKGROUND_INCREMENT","init_color","__esmMin","init_dist","autobind","obj","predefined","proto","propNames","object","key","value","name","init_autobind","__esmMin","getHiResTimestamp","timestamp","isBrowser","window_","process_","timeParts","init_hi_res_timestamp","__esmMin","init_dist","decorateMessage","id","message","opts","time","leftPad","formatTime","addColor","getTableHeader","table","key","title","originalConsole","DEFAULT_LOG_CONFIGURATION","ProbeLog","init_probe_log","__esmMin","init_dist","init_base_log","init_local_storage","init_formatters","init_color","init_autobind","init_assert","init_hi_res_timestamp","isBrowser","BaseLog","VERSION","getHiResTimestamp","LocalStorage","autobind","newPriority","enabled","level","setting","value","condition","args","oldUsage","newUsage","logLevel","columns","noop","method","func","_type","normalized","assert","configuration","currentConfiguration","init_init","__esmMin","dist_default","init_dist","__esmMin","init_probe_log","init_init","ProbeLog","getHiResTimestamp","timestamp","timeParts","init_hi_res_timestamp","__esmMin","Stat","init_stat","__esmMin","init_hi_res_timestamp","name","type","samples","value","time","getHiResTimestamp","Stats","init_stats","__esmMin","init_stat","options","name","type","stat","fn","table","stats","result","Stat","init_dist","__esmMin","init_stats","init_stat","init_hi_res_timestamp","initializeStats","stats","orderedStatNames","statsMap","addedOrderedStat","statName","statCount","cachedStats","ORDERED_STATS_CACHE","reorderedStats","orderedStatNamesSet","ORDERED_STAT_NAME_SET_CACHE","stat","GPU_TIME_AND_MEMORY_STATS","GPU_TIME_AND_MEMORY_STAT_ORDER","StatsManager","lumaStats","init_stats_manager","__esmMin","init_dist","name","Stats","log","init_log","__esmMin","init_dist","ProbeLog","uid","id","uidCounters","count","init_uid","__esmMin","selectivelyMerge","props","defaultProps","mergedProps","key","initializeStats","stats","orderedStatNames","statsMap","addedOrderedStat","statName","statCount","cachedStats","ORDERED_STATS_CACHE","reorderedStats","orderedStatNamesSet","ORDERED_STAT_NAME_SET_CACHE","stat","getResourceCountStatOrder","device","WEBGL_RESOURCE_COUNT_STAT_ORDER","BASE_RESOURCE_COUNT_STAT_ORDER","getCpuHotspotProfiler","profiler","CPU_HOTSPOT_PROFILER_MODULE","getTimestamp","recordTransientCanvasResourceCreate","name","getCanonicalResourceName","resource","prototype","parentPrototype","Resource","getPrototypeToStringTag","descriptor","RESOURCE_COUNTS_STATS","LEGACY_RESOURCE_COUNTS_STATS","GPU_TIME_AND_MEMORY_STATS","BASE_RESOURCE_COUNT_ORDER","WEBGL_RESOURCE_COUNT_ORDER","init_resource","__esmMin","init_uid","resourceType","id","uid","startTime","statsObjects","bytes","Buffer","init_buffer","__esmMin","init_resource","_Buffer","Resource","device","props","deducedProps","data","_byteOffset","byteLength","arrayBufferView","arrayBuffer","debugDataLength","sourceByteOffset","availableByteLength","copyByteLength","DataTypeDecoder","dataTypeDecoder","NORMALIZED_TYPE_MAP","init_data_type_decoder","__esmMin","type","signedType","primitiveType","byteLength","normalized","integer","signed","signedDataType","dataType","size","count","arrayOrType","Constructor","info","entry","VertexFormatDecoder","vertexFormatDecoder","init_vertex_format_decoder","__esmMin","init_data_type_decoder","format","webglOnly","type_","count","type","components","decodedType","dataTypeDecoder","result","signedDataType","normalized","dataType","typedArray","size","opts","vertexType","getTextureFormatDefinition","format","info","TEXTURE_FORMAT_TABLE","getTextureFormatTable","texture_compression_bc","texture_compression_astc","texture_compression_etc2","texture_compression_etc1_webgl","texture_compression_pvrtc_webgl","texture_compression_atc_webgl","float32_renderable","float16_renderable","rgb9e5ufloat_renderable","snorm8_renderable","norm16_webgl","norm16_renderable","snorm16_renderable","float32_filterable","float16_filterable","TEXTURE_FORMAT_COLOR_DEPTH_TABLE","TEXTURE_FORMAT_COMPRESSED_TABLE","init_texture_format_table","__esmMin","computeTextureMemoryLayout","format","width","height","depth","byteAlignment","formatInfo","textureFormatDecoder","bytesPerPixel","bytesPerBlock","blockWidth","blockHeight","compressed","blockColumns","blockRows","unpaddedBytesPerRow","bytesPerRow","rowsPerImage","byteLength","getTextureFormatCapabilities","info","getTextureFormatDefinition","formatCapabilities","getTextureFormatInfo","isDepthStencil","isSigned","isInteger","isWebGLSpecific","isCompressed","getTextureFormatInfoUsingTable","getCompressedTextureBlockByteLength","blockSize","getCompressedTextureBlockSize","matches","RGB_FORMAT_REGEX","channels","length","type","srgb","suffix","dataType","decodedType","dataTypeDecoder","bits","components","bitsPerChannel","COLOR_FORMAT_PREFIXES","DEPTH_FORMAT_PREFIXES","COMPRESSED_TEXTURE_FORMAT_PREFIXES","TextureFormatDecoder","init_texture_format_decoder","__esmMin","init_data_type_decoder","init_texture_format_table","prefix","opts","isExternalImage","data","getExternalImageSize","init_image_types","__esmMin","formatErrorLogArguments","context","args","formattedContext","formatErrorLogValue","formattedArgs","arg","value","hasCustomToString","stringValue","looksLikeGPUCompilationMessage","formatGPUCompilationMessage","type","message","lineNum","linePos","location","_getDefaultDebugValue","logDebugValue","nodeEnv","getDefaultDebugValue","log","getNodeEnv","processObject","DeviceLimits","DeviceFeatures","Device","init_device","__esmMin","init_stats_manager","init_log","init_uid","init_buffer","init_vertex_format_decoder","init_texture_format_decoder","init_image_types","init_texture_format_table","features","disabledFeatures","feature","_Device","error","info","width","height","left","top","lumaStats","props","uid","format","vertexFormatDecoder","textureFormatDecoder","textureCaps","capabilities","depth3d","maxSize","data","isExternalImage","getExternalImageSize","supportedFormats","getTextureFormatTable","groupLabel","markerLabel","logArguments","_texture","_props","_pipeline","_group","_bindGroupLayout","_shaderLayout","_bindings","_label","queryCount","source","options","parameters","func","moduleName","genericCapabilities","checkFeature","supported","newProps","Buffer","STARTUP_MESSAGE","ERROR_MESSAGE","Luma","luma","init_luma","__esmMin","init_device","init_stats_manager","init_log","_Luma","Device","lumaStats","log","props_","props","adapter","handle","type","adapters","deviceClass","adapterMap","KNOWN_ADAPTERS","selectedType","enforce","webgl2Adapter","map","getPageLoadPromise","pageLoadPromise","isPageLoaded","resolve","Adapter","isPage","init_adapter","__esmMin","init_dist","isBrowser","CanvasObserver","init_canvas_observer","__esmMin","props","entries","intervalMs","withResolvers","resolve","reject","_resolve","_reject","init_promise_utils","__esmMin","assert","condition","message","error","assertDefined","value","init_assert","__esmMin","getContainer","container","element","getCanvasFromDOM","canvasId","canvas","CanvasSurface","createCanvasElement","props","width","height","newCanvas","uid","scalePixels","pixel","ratio","yInvert","point","x","scaleX","y","scaleY","temporary","xHigh","yHigh","init_canvas_surface","__esmMin","init_dist","init_canvas_observer","init_uid","init_promise_utils","init_assert","_CanvasSurface","withResolvers","isBrowser","CanvasObserver","entries","options","maxTextureDimension","cssPixel","drawingBufferWidth","cssWidth","size","id","entry","entry_","isVisible","contentBoxSize","assertDefined","oldPixelSize","devicePixelWidth","devicePixelHeight","maxDevicePixelWidth","maxDevicePixelHeight","devicePixelRatio","oldRatio","newRect","position","oldPosition","CanvasContext","init_canvas_context","__esmMin","init_canvas_surface","CanvasSurface","PresentationContext","init_presentation_context","__esmMin","init_canvas_surface","CanvasSurface","Sampler","init_sampler","__esmMin","init_resource","_Sampler","Resource","device","props","BASE_DIMENSIONS","Texture","init_texture","__esmMin","init_resource","init_sampler","init_log","init_texture_format_decoder","_Texture","Resource","device","props","backendProps","size","log","sampler","Sampler","options","data","depth","writeOptions","options_","width","height","depthOrArrayLayers","format","byteAlignment","textureFormatDecoder","buffer","newProps","optionsWithoutUndefined","mipLevel","mipLevelSize","formatInfo","layout","minimumBytesPerRow","bytesPerPixel","allocatedByteLength","value","TextureView","init_texture_view","__esmMin","init_resource","_TextureView","Resource","device","props","formatCompilerLog","shaderLog","source","options","formattedLog","lines","log","a","b","currentMessageIndex","lineNum","line","currentMessage","getNumberedLine","message","formatCompilerMessage","numberedLines","getNumberedLines","positionIndicator","color","lineIndex","sourceLine","escapedLine","escapeHTML","padLeft","string","paddedLength","result","unsafe","init_format_compiler_log","__esmMin","getShaderIdFromProps","props","getShaderName","uid","shader","defaultName","Shader","init_shader","__esmMin","init_resource","init_uid","init_format_compiler_log","_Shader","Resource","device","trigger","messages","shaderId","shaderName","shaderTitle","htmlLog","formatCompilerLog","translatedSource","container","Framebuffer","init_framebuffer","__esmMin","init_resource","init_texture","init_log","_Framebuffer","Resource","device","props","size","colorAttachments","colorAttachment","depthStencilAttachment","updateSize","width","height","log","attachment","index","texture","Texture","format","i","resizedTexture","RenderPipeline","init_render_pipeline","__esmMin","init_resource","_RenderPipeline","Resource","device","props","SharedRenderPipeline","init_shared_render_pipeline","__esmMin","init_resource","Resource","device","props","ComputePipeline","init_compute_pipeline","__esmMin","init_resource","_ComputePipeline","Resource","device","props","PipelineFactory","init_pipeline_factory","__esmMin","init_compute_pipeline","init_render_pipeline","init_log","init_uid","_PipelineFactory","RenderPipeline","device","moduleData","props","allProps","cache","hash","pipeline","log","sharedRenderPipeline","uid","ComputePipeline","sharedPipelineHash","sharedCacheItem","type","shaderHash","shaderLayoutHash","vsHash","fsHash","varyingHash","bufferLayoutHash","webglParameterHash","entryPointHash","parameterHash","attachmentHash","key","varyings","bufferMode","colorAttachmentFormats","depthStencilAttachmentFormat","ShaderFactory","init_shader_factory","__esmMin","init_shader","init_log","_ShaderFactory","Shader","device","moduleData","props","key","cacheEntry","log","resource","shader","value","getShaderLayoutBinding","shaderLayout","bindingName","options","bindingLayout","binding","log","normalizeBindingsByGroup","bindingsOrBindGroups","areBindingsGrouped","group","bindings","bindGroups","flattenBindingsByGroup","groupBindings","keys","key","init_bind_groups","__esmMin","init_log","RenderPass","init_render_pass","__esmMin","init_resource","_RenderPass","Resource","device","props","CommandEncoder","init_command_encoder","__esmMin","init_resource","_CommandEncoder","Resource","device","props","pairCount","queryCount","results","totalDurationNanoseconds","queryIndex","passProps","beginTimestampIndex","CommandBuffer","init_command_buffer","__esmMin","init_resource","_CommandBuffer","Resource","device","props","getVariableShaderTypeInfo","format","resolvedFormat","resolveVariableShaderTypeAlias","decoded","UNIFORM_FORMATS","getAttributeShaderTypeInfo","attributeType","resolvedAttributeType","resolveAttributeShaderTypeAlias","TYPE_INFO","primitiveType","components","integer","signed","byteLength","PRIMITIVE_TYPE_SIZES","makeShaderAttributeType","alias","WGSL_ATTRIBUTE_TYPE_ALIAS_MAP","WGSL_VARIABLE_TYPE_ALIAS_MAP","ShaderTypeDecoder","shaderTypeDecoder","init_shader_type_decoder","__esmMin","getAttributeInfosFromLayouts","shaderLayout","bufferLayout","attributeInfos","attribute","attributeInfo","getAttributeInfoFromLayouts","getAttributeInfosByLocation","maxVertexAttributes","locationInfos","name","shaderDeclaration","getAttributeFromShaderLayout","bufferMapping","getAttributeFromBufferLayout","attributeTypeInfo","shaderTypeDecoder","defaultVertexFormat","vertexFormatDecoder","vertexFormat","vertexFormatInfo","attr","log","bufferLayouts","checkBufferLayouts","bufferLayoutInfo","getAttributeFromShortHand","getAttributeFromAttributesList","byteStride","attributeMapping","info","mapping","init_get_attribute_from_layouts","__esmMin","init_log","init_shader_type_decoder","init_vertex_format_decoder","VertexArray","init_vertex_array","__esmMin","init_get_attribute_from_layouts","init_resource","_VertexArray","Resource","device","props","getAttributeInfosByLocation","location","value","TransformFeedback","init_transform_feedback","__esmMin","init_resource","_TransformFeedback","Resource","device","props","QuerySet","init_query_set","__esmMin","init_resource","_QuerySet","Resource","device","props","Fence","init_fence","__esmMin","init_resource","_Fence","Resource","device","props","alignTo","size","count","getTypedArrayConstructor","type","Constructor","NORMALIZED_TYPE_MAP","init_decode_data_types","__esmMin","makeShaderBlockLayout","uniformTypes","options","copiedUniformTypes","layout","fields","size","key","uniformType","addToLayout","alignTo","getTypeAlignment","getLeafLayoutInfo","type","resolvedType","resolveVariableShaderTypeAlias","decodedType","getVariableShaderTypeInfo","matrixMatch","columns","rows","columnInfo","getVectorLayoutInfo","columnStride","getMatrixColumnStride","vectorMatch","isCompositeShaderTypeStruct","value","name","offset","info","alignedOffset","elementType","length","stride","getArrayStride","arrayOffset","i","structAlignment","structOffset","memberName","memberType","getTypeSize","compositeMemberType","elementAlignment","uses16ByteArrayAlignment","maxAlignment","memberAlignment","uses16ByteStructAlignment","components","shaderType","elementSize","getArrayLikeStride","alignment","init_shader_block_layout","__esmMin","init_decode_data_types","init_shader_type_decoder","getScratchArrayBuffer","byteLength","arrayBuffer","getScratchArray","Type","length","scratchArrayBuffer","init_array_utils_flat","__esmMin","isTypedArray","value","isNumberArray","init_is_array","__esmMin","isCompositeUniformObject","value","sliceNumericArray","start","end","ShaderBlockWriter","init_shader_block_writer","__esmMin","init_array_utils_flat","init_is_array","init_log","init_shader_block_layout","layout","name","entry","uniformValues","flattenedUniformValues","uniformType","buffer","getScratchArrayBuffer","typedArrays","baseName","elementType","length","isNumberArray","log","index","elementValue","isCompositeShaderTypeStruct","key","subValue","nestedName","numericValue","packedElementLength","getLeafLayoutInfo","type","components","columns","rows","offset","columnStride","array","sourceValue","componentIndex","sourceIndex","columnIndex","columnOffset","rowIndex","arrayEqual","a","b","limit","arrayA","arrayB","isNumberArray","maxCompareLength","MAX_ELEMENTWISE_ARRAY_COMPARE_LENGTH","i","arrayCopy","init_array_equal","__esmMin","init_is_array","UniformBlock","init_uniform_block","__esmMin","init_array_equal","props","binding","binding_","uniformBlock","uniform","uniforms","key","value","reason","arrayEqual","arrayCopy","getDefaultUniformBufferLayout","device","minUniformBufferSize","UniformStore","init_uniform_store","__esmMin","init_buffer","init_log","init_shader_block_layout","init_uniform_block","init_shader_block_writer","blocks","bufferName","block","uniformBufferName","shaderBlockLayout","makeShaderBlockLayout","shaderBlockWriter","ShaderBlockWriter","uniformBlock","UniformBlock","uniformBuffer","uniforms","blockName","uniformValues","flattenedUniforms","packedByteLength","byteLength","Buffer","uniformBufferData","reason","bufferReason","log","init_dist","__esmMin","init_luma","init_adapter","init_device","init_canvas_context","init_presentation_context","init_buffer","init_texture","init_texture_view","init_shader","init_sampler","init_framebuffer","init_render_pipeline","init_shared_render_pipeline","init_pipeline_factory","init_shader_factory","init_render_pass","init_command_encoder","init_command_buffer","init_vertex_array","init_transform_feedback","init_query_set","init_fence","init_uniform_store","init_data_type_decoder","init_decode_data_types","init_shader_type_decoder","init_vertex_format_decoder","init_texture_format_decoder","init_image_types","init_log","init_bind_groups","init_assert","init_array_utils_flat","init_get_attribute_from_layouts","GLEnum","init_webgl_constants","__esmMin","init_constants","__esmMin","init_webgl_constants","enforceWebGL2","enforce","prototype","contextId","options","context","polyfillWebGL1Extensions","gl","boundExtensions","WEBGL1_STATIC_EXTENSIONS","getWEBGL_draw_buffers","getOES_vertex_array_object","getANGLE_instanced_arrays","originalGetExtension","extensionName","ext","originalGetSupportedExtensions","init_polyfill_webgl1_extensions","__esmMin","buffers","vertexArray","args","loadScript","scriptUrl","scriptId","head","script","resolve","reject","error","init_load_script","__esmMin","getWebGLContextData","gl","contextData","init_webgl_context_data","__esmMin","loadSpectorJS","props","loadScript","DEFAULT_SPECTOR_PROPS","error","log","initializeSpectorJS","spector","LOG_LEVEL","SpectorJS","initialized","capture","gl","contextData","getWebGLContextData","device","resolve","_","init_spector","__esmMin","init_dist","init_load_script","init_webgl_context_data","getWebGLContextData","gl","loadWebGLDeveloperTools","isBrowser","loadScript","WEBGL_DEBUG_CDN_URL","makeDebugContext","props","getDebugContext","getRealContext","data","log","GLEnum","glDebug","onGLError","onValidateGLFunc","key","WebGLDebugContext","debugContext","getFunctionString","functionName","functionArgs","arg","args","err","errorMessage","message","functionString","init_webgl_developer_tools","__esmMin","init_dist","init_constants","init_load_script","isArray","array","getValue","glEnum","values","cache","GL_PARAMETER_DEFAULTS","enable","hint","pixelStorei","bindFramebuffer","bindBuffer","GL_PARAMETER_SETTERS","GL_COMPOSITE_PARAMETER_SETTERS","GL_HOOKED_SETTERS","isEnabled","GL_PARAMETER_GETTERS","NON_CACHE_PARAMETERS","init_webgl_parameter_tables","__esmMin","gl","value","key","target","glTarget","framebuffer","handle","args","separateModes","separateFuncs","mask","backMask","func","ref","backFunc","backRef","sfail","dpfail","dppass","backSfail","backDpfail","backDppass","update","capability","pname","buffer","r","g","b","a","mode","modeRGB","modeAlpha","src","dst","srcRGB","dstRGB","srcAlpha","dstAlpha","depth","s","zNear","zFar","face","width","factor","units","invert","x","y","height","fail","zfail","zpass","setGLParameters","gl","parameters","isObjectEmpty","compositeSetters","key","glConstant","setter","GL_PARAMETER_SETTERS","cache","compositeSetter","GL_COMPOSITE_PARAMETER_SETTERS","getGLParameters","GL_PARAMETER_DEFAULTS","getter","GL_PARAMETER_GETTERS","parameterKeys","state","resetGLParameters","object","init_unified_parameter_api","__esmMin","init_webgl_parameter_tables","deepArrayEqual","x","y","isArray","i","init_deep_array_equal","__esmMin","installGetterOverride","gl","functionName","originalGetterFunc","pname","NON_CACHE_PARAMETERS","glState","WebGLStateTracker","installSetterSpy","setter","originalSetterFunc","params","valueChanged","oldValue","installProgramSpy","originalUseProgram","handle","init_webgl_state_tracker","__esmMin","init_unified_parameter_api","init_deep_array_equal","init_webgl_parameter_tables","props","values","oldValues","setGLParameters","options","getGLParameters","GL_PARAMETER_DEFAULTS","key","GL_HOOKED_SETTERS","value","cached","deepArrayEqual","createBrowserContext","canvas","props","webglContextAttributes","errorMessage","onCreateError","event","statusMessage","allowSoftwareRenderer","webglProps","gl","softwareRenderer","luma","getWebGLContextData","onContextLost","onContextRestored","init_create_browser_context","__esmMin","init_webgl_context_data","getWebGLExtension","gl","name","extensions","init_webgl_extensions","__esmMin","getDeviceInfo","gl","extensions","vendorMasked","rendererMasked","getWebGLExtension","ext","vendorUnmasked","rendererUnmasked","vendor","renderer","version","gpu","identifyGPUVendor","gpuBackend","identifyGPUBackend","gpuType","identifyGPUType","isAppleSiliconGPU","init_webgl_device_info","__esmMin","init_webgl_extensions","getGLFromVertexType","dataType","init_webgl_vertex_formats","__esmMin","isTextureFeature","feature","TEXTURE_FEATURES","checkTextureFeature","gl","extensions","hasTextureFeature","seenFeatures","definition","hasDependentFeatures","dependentFeature","extension","getWebGLExtension","getTextureFormatCapabilitiesWebGL","formatSupport","supported","webglFormatInfo","WEBGL_TEXTURE_FORMATS","renderFeatureSupported","renderable","isColorRenderableTextureFormat","format","internalFormat","previousTexture","previousFramebuffer","texture","framebuffer","noError","error","getTextureFormatWebGL","formatData","webglFormat","convertTextureFormatToGL","decoded","textureFormatDecoder","getWebGLPixelDataFormat","getGLFromVertexType","getDepthStencilAttachmentWebGL","channels","integer","normalized","X_S3TC","X_S3TC_SRGB","X_RGTC","X_BPTC","X_ETC2","X_ASTC","X_ETC1","X_PVRTC","X_ATC","EXT_texture_norm16","EXT_render_snorm","EXT_color_buffer_float","SNORM8_COLOR_RENDERABLE","NORM16_COLOR_RENDERABLE","SNORM16_COLOR_RENDERABLE","FLOAT16_COLOR_RENDERABLE","FLOAT32_COLOR_RENDERABLE","RGB9E5UFLOAT_COLOR_RENDERABLE","init_webgl_texture_table","__esmMin","init_dist","init_webgl_extensions","init_webgl_vertex_formats","WEBGL_FEATURES","WebGLDeviceFeatures","init_webgl_device_features","__esmMin","init_dist","init_webgl_extensions","init_webgl_texture_table","DeviceFeatures","gl","extensions","disabledFeatures","getWebGLExtension","features","feature","isTextureFeature","checkTextureFeature","TEXTURE_FEATURES","featureInfo","WebGLDeviceLimits","init_webgl_device_limits","__esmMin","init_dist","DeviceLimits","gl","parameter","mapIndexToCubeMapFace","layer","_getFrameBufferStatus","status","WEBGLFramebuffer","init_webgl_framebuffer","__esmMin","init_dist","init_webgl_texture_table","Framebuffer","device","props","isDefaultFramebuffer","prevHandle","i","attachment","attachmentPoint","getDepthStencilAttachmentWebGL","textureView","gl","texture","level","face","width","height","WebGLCanvasContext","init_webgl_canvas_context","__esmMin","init_dist","init_webgl_framebuffer","CanvasContext","device","props","WEBGLFramebuffer","WebGLPresentationContext","init_webgl_presentation_context","__esmMin","init_dist","PresentationContext","device","props","contextLabel","context2d","defaultCanvasContext","sourceWidth","sourceHeight","options","uid","id","uidCounters","count","init_uid","__esmMin","getWebGLTarget","usage","Buffer","getWebGLUsage","WEBGLBuffer","init_webgl_buffer","__esmMin","init_dist","device","props","handle","data","byteOffset","byteLength","glTarget","dataView","srcOffset","callback","arrayBuffer","dstOffset","parseShaderCompilerLog","errLog","lines","messages","line","lineWithTrimmedWhitespace","segments","trimmedMessageType","messageType","message","getMessageType","linePosition","lineNumber","rest","lineNum","linePos","MESSAGE_TYPES","lowerCaseType","init_parse_shader_compiler_log","__esmMin","WEBGLShader","init_webgl_shader","__esmMin","init_dist","init_parse_shader_compiler_log","Shader","device","props","compilationStatus","shaderLog","parseShaderCompilerLog","source","gl","log","waitMs","ms","resolve","withDeviceAndGLParameters","device","parameters","glParameters","func","isObjectEmpty","webglDevice","setDeviceParameters","setGLParameters","gl","map","ext","vertex","mode","mapBoolean","convertCompareFunction","mask","log","glValue","dppass","convertStencilOperation","sfail","dpfail","colorEquation","convertBlendOperationToEquation","alphaEquation","colorSrcFactor","convertBlendFactorToFunction","colorDstFactor","alphaSrcFactor","alphaDstFactor","parameter","value","type","message","valueMap","obj","isEmpty","key","init_device_parameters","__esmMin","init_dist","init_unified_parameter_api","convertSamplerParametersToWebGL","props","params","convertAddressMode","convertMaxFilterMode","convertMinFilterMode","convertCompareFunction","addressMode","maxFilter","minFilter","mipmapFilter","init_sampler_parameters","__esmMin","init_device_parameters","WEBGLSampler","init_webgl_sampler","__esmMin","init_dist","init_sampler_parameters","Sampler","device","props","convertSamplerParametersToWebGL","parameters","pname","value","param","withGLParameters","gl","parameters","func","isObjectEmpty","nocatch","webglState","WebGLStateTracker","setGLParameters","value","object","key","init_with_parameters","__esmMin","init_unified_parameter_api","init_webgl_state_tracker","WEBGLTextureView","init_webgl_texture_view","__esmMin","init_dist","TextureView","device","props","Texture","convertGLDataTypeToDataType","type","GL_DATA_TYPE_MAP","init_shader_formats","__esmMin","getArrayBufferView","typedArray","byteOffset","getWebGLTextureSourceElementOffset","getWebGLTextureTarget","dimension","getWebGLCubeFaceTarget","glTarget","level","WEBGLTexture","init_webgl_texture","__esmMin","init_dist","init_webgl_texture_table","init_sampler_parameters","init_with_parameters","init_webgl_texture_view","init_shader_formats","Texture","device","props","formatInfo","getTextureFormatWebGL","width","height","depth","mipLevels","glInternalFormat","WEBGLTextureView","sampler","parameters","convertSamplerParametersToWebGL","options_","options","glFormat","glType","image","mipLevel","x","y","z","glParameters","withGLParameters","buffer","normalizedOptions","memoryLayout","webglBuffer","destinationByteOffset","depthOrArrayLayers","compressed","bytesPerPixel","unpackRowLength","data","sourceElementOffset","compressedData","mipLevelSize","isFullMipUpload","format","shaderType","convertGLDataTypeToDataType","ArrayType","getTypedArrayConstructor","targetArray","layerView","readLayer","framebuffer","packRowLength","prevReadBuffer","prevHandle","layerIndex","layer","attachmentKey","status","log","error","pname","pvalue","param","value","_textureUnit","gl","setUniform","gl","location","type","value","gl2","uniformValue","arrayValue","init_set_uniform","__esmMin","getGLDrawMode","topology","getGLPrimitive","init_webgl_topology_utils","__esmMin","mergeShaderLayout","baseLayout","overrideLayout","mergedLayout","attribute","binding","baseAttribute","attr","log","baseBinding","getShaderLayoutBindingByName","shaderLayout","bindingName","getBindingValueForLayoutBinding","bindings","WEBGLRenderPipeline","init_webgl_render_pipeline","__esmMin","init_dist","init_device_parameters","init_set_uniform","init_webgl_buffer","init_webgl_framebuffer","init_webgl_texture","init_webgl_texture_view","init_webgl_topology_utils","RenderPipeline","device","props","webglSharedRenderPipeline","options","flatBindings","flattenBindingsByGroup","normalizeBindingsByGroup","name","value","WEBGLBuffer","WEBGLTextureView","WEBGLTexture","WEBGLFramebuffer","validBindings","binding_","drawBindings","renderPass","parameters","topology","vertexArray","vertexCount","instanceCount","isInstanced","firstVertex","transformFeedback","uniforms","glDrawMode","getGLDrawMode","isIndexed","glIndexType","webglRenderPass","withDeviceAndGLParameters","texturesRenderable","bindingInfo","_options","gl","textureUnit","uniformBufferIndex","location","bufferBinding","texture","uniformLayout","type","setUniform","convertDataTypeToGLDataType","normalizedType","NORMALIZED_SHADER_TYPE_TO_WEBGL","convertGLUniformTypeToShaderVariableType","glUniformType","WEBGL_SHADER_TYPES","isGLSamplerType","type","WEBGL_SAMPLER_TO_TEXTURE_BINDINGS","getTextureBindingFromGLSamplerType","glSamplerType","init_webgl_shadertypes","__esmMin","getShaderLayoutFromGLSL","gl","program","shaderLayout","readAttributeDeclarations","uniformBlocks","readUniformBlocks","uniformBlock","uniforms","uniform","readUniformBindings","textureUnit","isGLSamplerType","viewDimension","sampleType","getTextureBindingFromGLSamplerType","varyings","readVaryings","attributes","count","index","activeInfo","name","compositeType","location","attributeType","convertGLUniformTypeToShaderVariableType","stepMode","a","b","glUniformType","size","uniformType","type","components","getVariableShaderTypeInfo","uniformCount","i","rawName","isArray","parseUniformName","webglLocation","uniformInfo","j","elementName","arrayElementUniformInfo","getBlockParameter","blockIndex","pname","blockCount","blockInfo","uniformIndices","uniformArrayLength","uniformOffset","uniformStride","uniformIndex","format","uniformInstancePrefixes","instanceName","blockAlias","log","matches","assertDefined","init_get_shader_layout_from_glsl","__esmMin","init_dist","init_webgl_shadertypes","LOG_PROGRAM_PERF_PRIORITY","WEBGLSharedRenderPipeline","init_webgl_shared_render_pipeline","__esmMin","init_dist","init_get_shader_layout_from_glsl","init_webgl_shadertypes","SharedRenderPipeline","device","props","log","getShaderLayoutFromGLSL","gl","status","errorType","linkErrorLog","textureUnit","uniformCount","uniformIndex","activeInfo","isGLSamplerType","isArray","uniformName","location","textureUnits","_","arrayIndex","waitMs","ms","resolve","_copyBufferToBuffer","device","options","source","destination","_copyBufferToTexture","_device","_options","_copyTextureToBuffer","sourceTexture","mipLevel","aspect","width","height","depthOrArrayLayers","origin","destinationBuffer","byteOffset","bytesPerRow","rowsPerImage","Texture","framebuffer","destroyFramebuffer","getFramebuffer","prevHandle","webglBuffer","sourceWidth","sourceHeight","colorAttachment0","assertDefined","sourceParams","getTextureFormatWebGL","sourceFormat","sourceType","_copyTextureToTexture","destinationMipLevel","destinationOrigin","destinationTexture","sourceX","sourceY","destinationX","destinationY","destinationZ","texture","textureTarget","WEBGLTexture","id","WEBGLCommandBuffer","init_webgl_command_buffer","__esmMin","init_dist","init_webgl_texture_table","init_webgl_texture","CommandBuffer","props","commands","command","COLOR_CHANNELS","WEBGLRenderPass","init_webgl_render_pass","__esmMin","init_dist","init_with_parameters","init_unified_parameter_api","RenderPass","device","props","webglFramebuffer","isDefaultFramebuffer","viewport","width","height","drawBuffers","_","i","groupLabel","markerLabel","parameters","glParameters","channel","setGLParameters","queryIndex","clearMask","color","drawBufferIndex","withGLParameters","drawBuffer","value","WEBGLCommandEncoder","init_webgl_command_encoder","__esmMin","init_dist","init_webgl_command_buffer","init_webgl_render_pass","CommandEncoder","device","props","WEBGLCommandBuffer","WEBGLRenderPass","options","groupLabel","markerLabel","_querySet","_destination","_options","querySet","queryIndex","fillArray","options","target","source","start","count","length","total","copied","i","init_fill_array","__esmMin","normalizeConstantArrayValue","arrayValue","compareConstantArrayValues","v1","v2","i","WEBGLVertexArray","init_webgl_vertex_array","__esmMin","init_dist","init_webgl_vertex_formats","init_fill_array","_WEBGLVertexArray","VertexArray","device","getBrowser","props","indexBuffer","buffer","location","attributeBuffer","size","type","stride","offset","normalized","integer","divisor","value","constant","attributeInfo","glType","getGLFromVertexType","enable","canDisableAttribute","elementCount","constantValue","byteLength","length","updateNeeded","typedArray","getScratchArray","fillArray","isIndex","value","WEBGLTransformFeedback","init_webgl_transform_feedback","__esmMin","init_dist","init_webgl_topology_utils","TransformFeedback","device","props","topology","getGLPrimitive","buffers","bufferName","buffer","locationOrName","bufferOrRange","location","byteLength","byteOffset","log","funcOrHandle","WEBGLBuffer","varying","bufferIndex","bufferEntry","index","handle","WEBGLQuerySet","init_webgl_query_set","__esmMin","init_dist","QuerySet","device","props","handle","pair","query","queryIndex","_","pairIndex","options","firstQuery","queryCount","results","startPairIndex","endPairIndex","duration","beginSlot","endSlot","beginIndex","endIndex","result","isDisjoint","resolve","reject","poll","callback","requestId","WEBGLFence","init_webgl_fence","__esmMin","init_dist","Fence","device","props","sync","resolve","poll","status","glFormatToComponents","format","glTypeToBytes","type","init_format_utils","__esmMin","readPixelsToArray","source","options","sourceX","sourceY","sourceAttachment","target","sourceWidth","sourceHeight","sourceDepth","sourceFormat","sourceType","framebuffer","deleteFramebuffer","getFramebuffer","gl","handle","texture","getPixelArray","signedType","dataTypeDecoder","convertDataTypeToGLDataType","prevHandle","readPixelsToBuffer","targetByteOffset","webglFramebuffer","webglBufferTarget","components","glFormatToComponents","byteCount","glTypeToBytes","byteLength","commandEncoder","Framebuffer","toFramebuffer","props","device","width","height","id","pixelArray","glType","glFormat","depth","shaderType","convertGLDataTypeToDataType","ArrayType","init_webgl_texture_utils","__esmMin","init_dist","init_webgl_shadertypes","init_format_utils","init_shader_formats","webgl_device_exports","__export","WebGLDevice","setConstantFloatArray","device","location","array","setConstantIntArray","setConstantUintArray","compareConstantArrayValues","v1","v2","i","init_webgl_device","__esmMin","init_dist","init_webgl_state_tracker","init_create_browser_context","init_webgl_context_data","init_webgl_device_info","init_webgl_device_features","init_webgl_device_limits","init_webgl_canvas_context","init_webgl_presentation_context","init_spector","init_webgl_developer_tools","init_webgl_texture_table","init_uid","init_webgl_buffer","init_webgl_shader","init_webgl_sampler","init_webgl_texture","init_webgl_framebuffer","init_webgl_render_pipeline","init_webgl_shared_render_pipeline","init_webgl_command_encoder","init_webgl_vertex_array","init_webgl_transform_feedback","init_webgl_query_set","init_webgl_fence","init_webgl_texture_utils","init_unified_parameter_api","init_with_parameters","init_webgl_extensions","_WebGLDevice","Device","gl","format","props","uid","canvasContextProps","existingContext","WebGLCanvasContext","resolve","webglContextAttributes","createBrowserContext","event","log","initializeSpectorJS","contextData","getWebGLContextData","getDeviceInfo","WebGLDeviceLimits","WebGLDeviceFeatures","WebGLStateTracker","args","makeDebugContext","WEBGLCommandEncoder","WebGLPresentationContext","newProps","WEBGLBuffer","WEBGLTexture","WEBGLSampler","WEBGLShader","WEBGLFramebuffer","WEBGLVertexArray","WEBGLTransformFeedback","WEBGLQuerySet","WEBGLFence","WEBGLRenderPipeline","WEBGLSharedRenderPipeline","commandBuffer","submittedCommandEncoder","source","options","readPixelsToArray","readPixelsToBuffer","parameters","setGLParameters","getGLParameters","func","withGLParameters","resetGLParameters","capabilities","getTextureFormatCapabilitiesWebGL","deviceLossTriggered","ext","value","number","key","glParameters","opts","keys","constant","maxVertexAttributes","currentConstant","name","getWebGLExtension","handle","resource","spectorMetadata","isWebGL","gl","LOG_LEVEL","WebGLAdapter","webgl2Adapter","init_webgl_adapter","__esmMin","init_dist","init_polyfill_webgl1_extensions","init_spector","init_webgl_developer_tools","Adapter","Device","DEFAULT_SPECTOR_PROPS","enable","enforceWebGL2","handle","log","props","WebGLDevice","existingDevice","createCanvasContext","promises","loadWebGLDeveloperTools","loadSpectorJS","results","result","device","message","init_dist","__esmMin","init_webgl_adapter","init_webgl_device","init_webgl_buffer","require_alea","__commonJSMin","exports","module","global","define","Alea","seed","me","mash","Mash","t","copy","f","impl","opts","xg","state","prng","n","data","i","h","require_xor128","__commonJSMin","exports","module","global","define","XorGen","seed","me","strseed","t","k","copy","f","impl","opts","xg","state","prng","top","bot","result","require_xorwow","__commonJSMin","exports","module","global","define","XorGen","seed","me","strseed","t","k","copy","f","impl","opts","xg","state","prng","top","bot","result","require_xorshift7","__commonJSMin","exports","module","global","define","XorGen","seed","me","X","i","t","v","w","init","j","copy","f","impl","opts","xg","state","prng","top","bot","result","require_xor4096","__commonJSMin","exports","module","global","define","XorGen","seed","me","w","X","i","t","v","init","j","limit","copy","f","impl","opts","xg","state","prng","top","bot","result","require_tychei","__commonJSMin","exports","module","global","define","XorGen","seed","me","strseed","b","c","a","k","copy","f","t","impl","opts","xg","state","prng","top","bot","result","require_seedrandom","__commonJSMin","exports","module","global","pool","math","width","chunks","digits","rngname","startdenom","significance","overflow","mask","nodecrypto","seedrandom","seed","options","callback","key","shortseed","mixkey","flatten","tostring","autoseed","arc4","ARC4","prng","n","d","x","is_math_call","state","copy","t","keylen","me","i","j","s","count","r","f","obj","depth","result","typ","prop","stringseed","smear","out","browser","plugins","a","require_seedrandom","__commonJSMin","exports","module","alea","xor128","xorwow","xorshift7","xor4096","tychei","sr","assert","condition","message","globals","self_","window_","global_","document_","isBrowser","matches","nodeVersion","init_dist","VERSION","version","createLog","log","ProbeLog","isBoolean","value","isFunction","isObject","isPureObject","isSharedArrayBuffer","value","isArrayBufferLike","isObject","isIterable","value","isFunction","isAsyncIterable","isResponse","value","isObject","isFunction","isBlob","value","isReadableDOMStream","value","isObject","isFunction","isReadableNodeStream","value","isObject","isFunction","isBoolean","isReadableStream","isReadableDOMStream","mergeOptions","baseOptions","newOptions","mergeOptionsRecursively","level","options","key","newValue","NPM_TAG","getVersion","VERSION","assert","condition","message","globals","self_","window_","global_","document_","isBrowser","isMobile","matches","nodeVersion","WorkerJob","jobName","workerThread","resolve","reject","type","payload","value","assert","error","NodeWorker","workerURLCache","getLoadableWorkerURL","props","assert","workerURL","getLoadableWorkerURLFromURL","getLoadableWorkerURLFromSource","url","workerSource","buildScriptSource","blob","workerUrl","getTransferList","object","recursive","transfers","transfersSet","isTransferable","key","NOOP","WorkerThread","isBrowser","NodeWorker","props","name","source","url","assert","error","data","transferList","getTransferList","event","message","getLoadableWorkerURL","worker","type","code","WorkerPool","WorkerThread","props","worker","name","onMessage","job","type","data","onError","error","startPromise","onStart","workerThread","queuedJob","WorkerJob","isBrowser","isMobile","DEFAULT_PROPS","WorkerFarm","_WorkerFarm","WorkerThread","props","workerPool","options","name","source","url","WorkerPool","getWorkerURL","worker","options","workerOptions","workerFile","isBrowser","url","version","NPM_TAG","versionTag","assert","validateWorkerVersion","worker","coreVersion","VERSION","assert","workerVersion","canParseWithWorker","loader","options","WorkerFarm","nodeWorkers","isBrowser","useWorkers","parseWithWorker","data","context","parseOnMainThread","name","url","getWorkerURL","workerPool","job","onMessage","type","payload","id","input","result","error","message","compareArrayBuffers","arrayBuffer1","arrayBuffer2","byteLength","array1","array2","i","concatenateArrayBuffers","sources","concatenateArrayBuffersFromArray","sourceArrays","source2","length","typedArray","result","offset","sourceArray","concatenateArrayBuffersAsync","asyncIterator","arrayBuffers","chunk","copyToArrayBuffer","concatenateArrayBuffers","copyToArrayBuffer","chunk","buffer","byteOffset","byteLength","copyFromBuffer","view","copy","pathPrefix","fileAliases","resolvePath","filename","alias","fileAliases","replacement","pathPrefix","isBuffer","value","toArrayBuffer","data","isBuffer","isSharedArrayBuffer","copyToArrayBuffer","buffer","text","ensureArrayBuffer","bufferSource","byteOffset","byteLength","view","copy","toArrayBufferView","path_exports","__export","dirname","filename","join","resolve","getCWD","pathname","filename","url","slashIndex","dirname","join","parts","part","index","resolve","components","paths","_i","resolvedPath","resolvedAbsolute","cwd","i","path","getCWD","SLASH","normalizeStringPosix","DOT","allowAboveRoot","res","lastSlash","dots","code","isAboveRoot","start","j","slice","FetchError","message","info","DATA_URL_PATTERN","MIME_TYPE_PATTERN","compareMIMETypes","mimeType1","mimeType2","parseMIMEType","mimeString","matches","parseMIMETypeFromURL","url","QUERY_STRING_PATTERN","extractQueryString","url","matches","stripQueryString","shortenUrlForDisplay","urlEnd","getResourceUrl","resource","isResponse","isBlob","getResourceMIMEType","contentTypeHeader","noQueryUrl","stripQueryString","parseMIMEType","parseMIMETypeFromURL","getResourceContentLength","makeResponse","resource","isResponse","headers","contentLength","getResourceContentLength","url","getResourceUrl","type","getResourceMIMEType","initialDataUrl","getInitialDataUrl","response","checkResponse","getResponseError","getResponseError","response","shortUrl","shortenUrlForDisplay","message","info","contentType","FetchError","getInitialDataUrl","resource","blobSlice","resolve","reader","event","slice","arrayBufferToBase64","buffer","binary","bytes","isNodePath","url","isRequestURL","isDataURL","fetchFile","urlOrData","fetchOptions","resolvePath","makeResponse","init_dist","probeLog","ProbeLog","NullLog","ConsoleLog","args","DEFAULT_LOADER_OPTIONS","ConsoleLog","isBrowser","REMOVED_LOADER_OPTIONS","CORE_LOADER_OPTION_KEYS","getGlobalLoaderState","loaders","getGlobalLoaderOptions","state","DEFAULT_LOADER_OPTIONS","normalizeLoaderOptions","normalizeOptions","options","loader","loaders","url","validateOptions","normalizeLoaderOptions","normalizeOptionsInternal","normalized","cloneLoaderOptions","moveDeprecatedTopLevelOptionsToCore","key","CORE_LOADER_OPTION_KEYS","validateOptionsObject","DEFAULT_LOADER_OPTIONS","REMOVED_LOADER_OPTIONS","idOptions","loaderOptions","deprecatedOptions","id","defaultOptions","loaderName","prefix","isSubOptions","isObject","isBaseUriOption","isWorkerUrlOption","probeLog","suggestion","findSimilarOption","optionKey","lowerCaseOptionKey","bestSuggestion","lowerCaseKey","loaderDefaultOptions","mergedOptions","NullLog","mergeNestedFields","getGlobalLoaderOptions","userOptions","addUrlOptions","addDeprecatedTopLevelOptions","value","isPureObject","path_exports","stripQueryString","clonedOptions","coreRecord","workerTypeAlias","coreOptions","isLoaderObject","loader","normalizeLoader","assert","options","getGlobalLoaderRegistry","state","getGlobalLoaderState","registerLoaders","loaders","loaderRegistry","loader","normalizedLoader","normalizeLoader","registeredLoader","getRegisteredLoaders","EXT_PATTERN","selectLoader","data","loaders","options","context","validHTTPResponse","normalizedOptions","normalizeLoaderOptions","mayContainText","text","textLoader","selectLoaderSync","loader","isBlob","getNoValidLoaderMessage","response","mimeType","getResourceMIMEType","normalizeLoader","candidateLoaders","getRegisteredLoaders","normalizeLoaders","selectLoaderInternal","url","getResourceUrl","type","testUrl","stripQueryString","reason","findLoaderByMIMEType","findLoaderByUrl","findLoaderByInitialBytes","getFirstCharacters","log","message","path_exports","firstCharacters","match","extension","findLoaderByExtension","loaderExtension","mimeType1","compareMIMETypes","testDataAgainstText","testDataAgainstBinary","test","byteOffset","testBinary","isArrayBufferLike","compareArrayBuffers","ensureArrayBuffer","magic","getMagicString","length","arrayBuffer","dataView","i","DEFAULT_CHUNK_SIZE","makeStringIterator","string","options","chunkSize","offset","textEncoder","chunkLength","chunk","ensureArrayBuffer","makeArrayBufferIterator","arrayBuffer","options","chunkSize","byteOffset","chunkByteLength","chunk","sourceArray","makeBlobIterator","blob","options","chunkSize","offset","end","chunk","makeStreamIterator","stream","options","isBrowser","makeBrowserStreamIterator","makeNodeStreamIterator","reader","nextBatchPromise","currentBatchPromise","done","value","toArrayBuffer","chunk","makeIterator","data","options","makeStringIterator","makeArrayBufferIterator","isBlob","makeBlobIterator","isReadableStream","makeStreamIterator","isResponse","responseBody","ERR_DATA","getArrayBufferOrStringFromDataSync","data","loader","options","isBuffer","isArrayBufferLike","bufferSource","toArrayBufferView","toArrayBuffer","getArrayBufferOrStringFromData","isBlob","makeResponse","isResponse","checkResponse","isReadableStream","makeIterator","isIterable","isAsyncIterable","concatenateArrayBuffersAsync","getFetchFunction","options","context","globalOptions","getGlobalLoaderOptions","loaderOptions","fetchOption","isObject","url","fetchFile","getLoaderContext","context","options","parentContext","newContext","getFetchFunction","baseUrl","stripQueryString","extractQueryString","path_exports","getLoadersFromContext","loaders","candidateLoaders","contextLoaders","parse","data","loaders","options","context","isLoaderObject","url","getResourceUrl","candidateLoaders","getLoadersFromContext","loader","selectLoader","strictOptions","normalizeOptions","getLoaderContext","parseWithLoader","validateWorkerVersion","mergeOptions","isResponse","ok","redirected","status","statusText","type","headers","getArrayBufferOrStringFromData","loaderWithParser","canParseWithWorker","parseWithWorker","assert","isTypedArray","value","isNumberArray","isNumericArray","load","url","loaders","options","context","resolvedLoaders","resolvedOptions","isLoaderObject","fetch","getFetchFunction","data","isBlob","normalizeLoaderOptions","parse","VERSION","parseImageNode","IMAGE_SUPPORTED","IMAGE_BITMAP_SUPPORTED","NODE_IMAGE_SUPPORTED","DATA_SUPPORTED","isBrowser","isImageTypeSupported","type","getDefaultImageType","getImageType","image","format","getImageTypeOrNull","getImageData","image","getImageType","canvas","context","getImageTypeOrNull","SVG_DATA_URL_PATTERN","SVG_URL_PATTERN","isSVG","url","getBlobOrSVGDataUrl","arrayBuffer","xmlText","error","getBlob","parseToImage","arrayBuffer","options","url","blobOrDataUrl","getBlobOrSVGDataUrl","URL","objectUrl","loadToImage","image","resolve","reject","error","message","imagebitmapOptionsSupported","parseToImageBitmap","arrayBuffer","options","url","blob","isSVG","parseToImage","getBlob","imagebitmapOptions","safeCreateImageBitmap","isEmptyObject","error","object","key","getISOBMFFMediaType","buffer","checkString","decodeMajorBrand","getUTF8String","array","start","end","stringToBytes","string","character","header","offset","headerBytes","i","BIG_ENDIAN","LITTLE_ENDIAN","getBinaryImageMetadata","binaryData","dataView","toDataView","getPngMetadata","getJpegMetadata","getGifMetadata","getBmpMetadata","getISOBMFFMetadata","buffer","mediaType","getISOBMFFMediaType","tableMarkers","sofMarkers","getJpegMarkers","i","marker","data","parseToNodeImage","arrayBuffer","options","mimeType","getBinaryImageMetadata","parseImageNode","assert","parseImage","arrayBuffer","options","context","imageType","url","loadType","getLoadableImageType","image","parseToImageBitmap","parseToImage","parseToNodeImage","assert","getImageData","type","getDefaultImageType","isImageTypeSupported","EXTENSIONS","MIME_TYPES","DEFAULT_IMAGE_LOADER_OPTIONS","ImageLoader","VERSION","parseImage","arrayBuffer","getBinaryImageMetadata","init_dist","defaultLogger","ProbeLog","log_default","loggers","register","handlers","debug","eventType","arg1","arg2","arg3","log_default","isJSON","text","firstChar","lastChar","json_loader_default","checkVersion","version","existingVersion","log_default","register","registerLoaders","json_loader_default","ImageLoader","VERSION","assert","condition","message","error","DEFAULT_PROP_VALIDATORS","value","propType","makePropValidators","propTypes","propValidators","name","makePropValidator","makePropValidator","propType","type","getTypeOf","DEFAULT_PROP_VALIDATORS","value","MODULE_INJECTORS_VS","MODULE_INJECTORS_FS","MODULE_INJECTORS","MODULE_INJECTORS_VS","MODULE_INJECTORS_FS","REGEX_START_OF_MAIN","REGEX_END_OF_MAIN","fragments","DECLARATION_INJECT_MARKER","normalizeInjections","injections","result","hook","injection","stage","getHookStage","type","injectShader","source","inject","injectStandardStubs","isVertex","key","fragmentData","a","b","i","len","fragmentString","match","initializeShaderModules","modules","module","initializeShaderModule","propTypes","deprecations","inject","instance","normalizeInjections","parseDeprecationDefinitions","makePropValidators","defaultProps","obj","key","propType","value","checkShaderModuleDeprecations","shaderModule","shaderSource","log","def","parseDeprecationDefinitions","deprecations","getShaderModuleDependencies","modules","initializeShaderModules","moduleMap","moduleDepth","getDependencyGraph","dependencies","a","b","name","options","level","module","GLSL_UNIFORM_BLOCK_FIELD_REGEXP","GLSL_UNIFORM_BLOCK_REGEXP","getShaderModuleUniformBlockName","module","getShaderModuleUniformBlockFields","stage","shaderSource","uniformBlockName","extractShaderUniformBlockFieldNames","getShaderModuleUniformLayoutValidationResult","expectedUniformNames","actualUniformNames","areStringArraysEqual","validateShaderModuleUniformLayout","options","validationResult","message","formatShaderModuleUniformLayoutError","assert","getGLSLUniformBlocks","blocks","uncommentedSource","stripShaderComments","sourceMatch","layoutQualifier","warnIfGLSLUniformBlocksAreNotStd140","log","context","nonStd140Blocks","block","seenBlockNames","shaderLabel","actualLayout","normalizeWhitespace","language","sourceBody","extractWGSLStructBody","extractGLSLUniformBlockBody","fieldNames","sourceLine","line","fieldMatch","structMatch","openBraceIndex","braceDepth","index","character","candidate","leftValues","rightValues","valueIndex","missingUniformNames","uniformName","unexpectedUniformNames","mismatchDetails","firstMismatchDescription","getFirstUniformMismatchDescription","formatUniformNameList","value","minimumLength","uniformNames","maxNames","remainingCount","getPlatformShaderDefines","platformInfo","transpileGLSLShader","source","stage","convertShader","ES300_VERTEX_REPLACEMENTS","ES300_FRAGMENT_REPLACEMENTS","ES300_REPLACEMENTS","makeVariableTextRegExp","replacements","pattern","replacement","qualifier","getShaderHooks","hookFunctions","hookInjections","result","hookName","hookFunction","injections","a","b","injection","normalizeShaderHooks","opts","hook","shaderStage","signature","name","normalizedHook","getShaderInfo","source","defaultName","getShaderName","getShaderVersion","shader","match","version","words","parsedVersion","WGSL_BINDABLE_VARIABLE_PATTERN","MODULE_WGSL_BINDING_DECLARATION_REGEXES","WGSL_BINDABLE_VARIABLE_PATTERN","WGSL_BINDING_DECLARATION_REGEXES","WGSL_EXPLICIT_BINDING_DECLARATION_REGEXES","WGSL_AUTO_BINDING_DECLARATION_REGEXES","maskWGSLComments","source","maskedCharacters","index","blockCommentDepth","inLineComment","inString","isEscaped","character","nextCharacter","getWGSLBindingDeclarationMatches","regexes","maskedSource","matches","regex","match","isBindingFirst","length","left","right","replaceWGSLBindingDeclarationMatches","replacer","relocatedSource","lastIndex","hasWGSLAutoBinding","getFirstWGSLAutoBindingDeclarationMatch","declarationMatch","WGSL_BINDING_DEBUG_REGEXES","WGSL_BINDABLE_VARIABLE_PATTERN","getShaderBindingDebugRowsFromWGSL","source","bindingAssignments","maskedSource","maskWGSLComments","assignmentMap","bindingAssignment","getBindingAssignmentKey","rows","regex","match","isBindingFirst","binding","group","accessDeclaration","name","resourceType","moduleName","normalizeShaderBindingDebugRow","left","right","row","baseRow","access","value","storageAccess","getStorageTextureAccess","getTextureViewDimension","getTextureSampleType","INJECT_SHADER_DECLARATIONS","DECLARATION_INJECT_MARKER","RESERVED_APPLICATION_GROUP_0_BINDING_LIMIT","FRAGMENT_SHADER_PROLOGUE","assembleWGSLShader","options","modules","getShaderModuleDependencies","source","bindingAssignments","assembleShaderWGSL","assembleGetUniforms","getShaderBindingDebugRowsFromWGSL","assembleGLSLShaderPair","vs","fs","assembleShaderGLSL","platformInfo","stage","hookFunctions","inject","log","assert","coreSource","assembledSource","hookFunctionMap","normalizeShaderHooks","hookInjections","declInjections","mainInjections","key","injection","match","hash","name","modulesToInject","applicationRelocation","relocateWGSLApplicationBindings","usedBindingsByGroup","getUsedBindingsByGroupFromApplicationWGSL","reservedBindingKeysByGroup","reserveRegisteredModuleBindings","module","checkShaderModuleDeprecations","relocation","relocateWGSLModuleBindings","getShaderModuleSource","moduleSource","injections","injectionType","injectShader","getShaderHooks","formatWGSLBindingAssignmentComments","assertNoUnresolvedAutoBindings","language","defines","prologue","sourceVersion","getShaderInfo","targetVersion","sourceVersionDirective","allDefines","getPlatformShaderDefines","getApplicationDefines","transpileGLSLShader","warnIfGLSLUniformBlocksAreNotStd140","opts","uniforms","moduleUniforms","sourceText","define","value","validateShaderModuleUniformLayout","moduleName","getWGSLBindingDeclarationMatches","WGSL_EXPLICIT_BINDING_DECLARATION_REGEXES","location","group","validateApplicationWGSLBinding","registerUsedBindingLocation","declarationMatches","WGSL_BINDING_DECLARATION_REGEXES","declarationMatch","relocationState","relocatedSource","replaceWGSLBindingDeclarationMatches","relocateWGSLApplicationBindingMatch","hasWGSLAutoBinding","context","MODULE_WGSL_BINDING_DECLARATION_REGEXES","relocateWGSLModuleBindingMatch","params","bindingToken","groupToken","registryKey","getBindingRegistryKey","registryLocation","allocateAutoBindingLocation","validateModuleWGSLBinding","claimReservedBindingLocation","allocateApplicationAutoBindingLocation","bindingRegistry","binding","getModuleWGSLBindingDeclarations","reservedBindingKeys","existingReservation","reservedKey","declarations","label","usedBindings","preferredBindingLocation","nextBinding","unresolvedBinding","getFirstWGSLAutoBindingDeclarationMatch","getWGSLModuleNameAtIndex","isInApplicationWGSLSection","formatWGSLSourceSnippet","bindingAssignment","bindingName","index","moduleHeaderRegex","injectionMarkerIndex","DEFINE_NAME_PATTERN","IFDEF_REGEXP","IFNDEF_REGEXP","ELSE_REGEXP","ENDIF_REGEXP","IFDEF_WITH_COMMENT_REGEXP","ENDIF_WITH_COMMENT_REGEXP","preprocess","source","options","lines","output","conditionalStack","conditional","line","matchIf","matchIfNot","matchElse","matchEnd","defineName","defineValue","branchTaken","active","currentConditional","ShaderAssembler","_ShaderAssembler","module","m","moduleName","hook","opts","props","modules","hookFunctions","source","getUniforms","bindingAssignments","assembleWGSLShader","defines","accumulator","preprocessedSource","preprocess","getShaderBindingDebugRowsFromWGSL","assembleGLSLShaderPair","appModules","seen","count","i","len","name","initializeShaderModules","FS_GLES","FS300","getPassthroughFS","options","input","inputChannels","output","FS300","inputType","channelCountToType","outputValue","convertToVec4","channelCountToType","channels","convertToVec4","variable","RADIANS_TO_DEGREES","DEGREES_TO_RADIANS","DEFAULT_CONFIG","config","formatValue","value","precision","config","round","isArray","clamp","value","min","max","map","lerp","a","b","t","isArray","ai","i","equals","epsilon","oldEpsilon","config","round","value","config","duplicateArray","array","map","func","result","isArray","i","val","MathArray","array","offset","targetArray","targetObject","arrayOrObject","isArray","target","config","opts","string","formatValue","i","equals","a","b","t","ai","endValue","vector","minVector","maxVector","vectors","scale","scalar","valid","min","max","validateVector","v","length","i","checkNumber","value","checkVector","callerName","config","assert","condition","message","Vector","MathArray","value","checkNumber","length","i","mathArray","dist","product","vectors","vector","assert","a","b","vec2_exports","__export","add","angle","ceil","clone","copy","create","cross","dist","distance","div","divide","dot","equals","exactEquals","floor","forEach","fromValues","inverse","len","length","lerp","max","min","mul","multiply","negate","normalize","random","rotate","round","scale","scaleAndAdd","set","sqrDist","sqrLen","squaredDistance","squaredLength","str","sub","subtract","transformMat2","transformMat2d","transformMat3","transformMat4","zero","ARRAY_TYPE","RANDOM","round","a","degree","create","out","ARRAY_TYPE","clone","a","fromValues","x","y","copy","set","add","b","subtract","multiply","divide","ceil","floor","min","max","round","scale","scaleAndAdd","distance","squaredDistance","length","squaredLength","negate","inverse","normalize","len","dot","cross","z","lerp","t","ax","ay","random","RANDOM","transformMat2","m","transformMat2d","transformMat3","transformMat4","rotate","rad","p0","p1","sinC","cosC","angle","x1","y1","x2","y2","mag","cosine","zero","str","exactEquals","equals","a0","a1","b0","b1","sub","mul","div","dist","sqrDist","sqrLen","forEach","vec","stride","offset","count","fn","arg","i","l","vec2_transformMat4AsVector","out","a","m","x","y","w","vec3_transformMat4AsVector","z","vec3_transformMat2","vec3_exports","__export","add","angle","bezier","ceil","clone","copy","create","cross","dist","distance","div","divide","dot","equals","exactEquals","floor","forEach","fromValues","hermite","inverse","len","length","lerp","max","min","mul","multiply","negate","normalize","random","rotateX","rotateY","rotateZ","round","scale","scaleAndAdd","set","slerp","sqrDist","sqrLen","squaredDistance","squaredLength","str","sub","subtract","transformMat3","transformMat4","transformQuat","zero","create","out","ARRAY_TYPE","clone","a","length","x","y","z","fromValues","copy","set","add","b","subtract","multiply","divide","ceil","floor","min","max","round","scale","scaleAndAdd","distance","squaredDistance","squaredLength","negate","inverse","normalize","len","dot","cross","ax","ay","az","bx","by","bz","lerp","t","slerp","angle","sinTotal","ratioA","ratioB","hermite","c","d","factorTimes2","factor1","factor2","factor3","factor4","bezier","inverseFactor","inverseFactorTimesTwo","random","RANDOM","zScale","transformMat4","m","w","transformMat3","transformQuat","q","qx","qy","qz","qw","uvx","uvy","uvz","uuvx","uuvy","uuvz","w2","rotateX","rad","p","r","rotateY","rotateZ","mag","cosine","zero","str","exactEquals","equals","a0","a1","a2","b0","b1","b2","sub","mul","div","dist","sqrDist","sqrLen","forEach","vec","stride","offset","count","fn","arg","i","l","ORIGIN","ZERO","Vector3","_Vector3","Vector","x","y","z","isArray","config","checkNumber","array","object","value","vector","angle","cross","radians","origin","rotateX","rotateY","rotateZ","matrix4","transformMat4","vec3_transformMat4AsVector","matrix3","transformMat3","matrix2","vec3_transformMat2","quaternion","transformQuat","Matrix","MathArray","string","config","row","col","i","value","checkNumber","columnIndex","result","firstIndex","columnVector","mat4_exports","__export","add","adjoint","clone","copy","create","decompose","determinant","equals","exactEquals","frob","fromQuat","fromQuat2","fromRotation","fromRotationTranslation","fromRotationTranslationScale","fromRotationTranslationScaleOrigin","fromScaling","fromTranslation","fromValues","fromXRotation","fromYRotation","fromZRotation","frustum","getRotation","getScaling","getTranslation","identity","invert","lookAt","mul","multiply","multiplyScalar","multiplyScalarAndAdd","ortho","orthoNO","orthoZO","perspective","perspectiveFromFieldOfView","perspectiveNO","perspectiveZO","rotate","rotateX","rotateY","rotateZ","scale","set","str","sub","subtract","targetTo","translate","transpose","create","out","ARRAY_TYPE","clone","a","copy","fromValues","m00","m01","m02","m03","m10","m11","m12","m13","m20","m21","m22","m23","m30","m31","m32","m33","set","identity","transpose","a01","a02","a03","a12","a13","a23","invert","a00","a10","a11","a20","a21","a22","a30","a31","a32","a33","b00","b01","b02","b03","b04","b05","b06","b07","b08","b09","b10","b11","det","adjoint","determinant","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","multiply","b","translate","v","x","y","z","scale","rotate","rad","axis","len","s","t","b12","b20","b21","b22","rotateX","c","rotateY","rotateZ","fromTranslation","fromScaling","fromRotation","fromXRotation","fromYRotation","fromZRotation","fromRotationTranslation","q","w","x2","y2","z2","xx","xy","xz","yy","yz","zz","wx","wy","wz","fromQuat2","translation","bx","by","bz","bw","ax","ay","az","aw","magnitude","getTranslation","mat","getScaling","getRotation","scaling","is1","is2","is3","sm11","sm12","sm13","sm21","sm22","sm23","sm31","sm32","sm33","trace","S","decompose","out_r","out_t","out_s","fromRotationTranslationScale","sx","sy","sz","fromRotationTranslationScaleOrigin","o","ox","oy","oz","out0","out1","out2","out4","out5","out6","out8","out9","out10","fromQuat","yx","zx","zy","frustum","left","right","bottom","top","near","far","rl","tb","nf","perspectiveNO","fovy","aspect","f","perspective","perspectiveZO","perspectiveFromFieldOfView","fov","upTan","downTan","leftTan","rightTan","xScale","yScale","orthoNO","lr","bt","ortho","orthoZO","lookAt","eye","center","up","x0","x1","y0","y1","z0","z1","eyex","eyey","eyez","upx","upy","upz","centerx","centery","centerz","targetTo","target","str","frob","add","subtract","multiplyScalar","multiplyScalarAndAdd","exactEquals","equals","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","a14","a15","b13","b14","b15","mul","sub","vec4_exports","__export","add","ceil","clone","copy","create","cross","dist","distance","div","divide","dot","equals","exactEquals","floor","forEach","fromValues","inverse","len","length","lerp","max","min","mul","multiply","negate","normalize","random","round","scale","scaleAndAdd","set","sqrDist","sqrLen","squaredDistance","squaredLength","str","sub","subtract","transformMat4","transformQuat","zero","create","out","ARRAY_TYPE","clone","a","fromValues","x","y","z","w","copy","set","add","b","subtract","multiply","divide","ceil","floor","min","max","round","scale","scaleAndAdd","distance","squaredDistance","length","squaredLength","negate","inverse","normalize","len","dot","cross","u","v","A","B","C","D","E","F","G","H","I","J","lerp","t","ax","ay","az","aw","random","v1","v2","v3","v4","s1","s2","RANDOM","d","transformMat4","m","transformQuat","q","qx","qy","qz","qw","ix","iy","iz","iw","zero","str","exactEquals","equals","a0","a1","a2","a3","b0","b1","b2","b3","sub","mul","div","dist","sqrDist","sqrLen","forEach","vec","stride","offset","count","fn","arg","i","l","INDICES","DEFAULT_FOVY","DEFAULT_ASPECT","DEFAULT_NEAR","DEFAULT_FAR","IDENTITY_MATRIX","Matrix4","Matrix","getIdentityMatrix","getZeroMatrix","array","m00","m10","m20","m30","m01","m11","m21","m31","m02","m12","m22","m32","m03","m13","m23","m33","result","object","quaternion","fromQuat","view","left","right","bottom","top","near","far","computeInfinitePerspectiveOffCenter","frustum","eye","center","up","lookAt","ortho","fovy","aspect","focalDistance","checkRadians","halfY","perspective","determinant","scaleResult","scale","inverseScale0","inverseScale1","inverseScale2","transpose","invert","a","multiply","radians","rotateX","rotateY","rotateZ","angleXYZ","axis","rotate","factor","vector","translate","transformMat4","checkVector","length","out","vec2_transformMat4AsVector","vec3_transformMat4AsVector","x","y","z","ZERO","IDENTITY","possiblyDegrees","column0Row0","column1Row1","column2Row0","column2Row1","column2Row2","column2Row3","column3Row2","fp64ify","a","out","startIndex","hiPart","loPart","fp64LowPart","fp64ifyMatrix4","matrix","matrixFP64","i","j","index","resolveUseByteColors","useByteColors","defaultUseByteColors","normalizeByteColor3","color","component","normalizeByteColor4","normalizedColor","hasAlpha","alpha","fp32shader","fp32","fp64arithmeticShader","fp64arithmeticWGSL","defaultUniforms","fp64arithmetic","fp64arithmeticWGSL","fp64arithmeticShader","fp64ify","fp64LowPart","fp64ifyMatrix4","DEFAULT_HIGHLIGHT_COLOR","vs","fs","picking","getUniforms","opts","prevUniforms","uniforms","useByteColors","resolveUseByteColors","highlightedObjectColor","normalizeByteColor4","uniformBlockWGSL","uniformBlock","layerUniforms","props","colorWGSL","color_default","_props","source","defines","vs","fs","geometry_default","InputEvent","InputDirection","RecognizerState","TOUCH_ACTION_COMPUTE","TOUCH_ACTION_AUTO","TOUCH_ACTION_MANIPULATION","TOUCH_ACTION_NONE","TOUCH_ACTION_PAN_X","TOUCH_ACTION_PAN_Y","cleanTouchActions","actions","TOUCH_ACTION_NONE","hasPanX","TOUCH_ACTION_PAN_X","hasPanY","TOUCH_ACTION_PAN_Y","TOUCH_ACTION_MANIPULATION","TOUCH_ACTION_AUTO","TouchAction","manager","value","TOUCH_ACTION_COMPUTE","actions","recognizer","cleanTouchActions","splitStr","str","addEventListeners","target","types","handler","type","splitStr","removeEventListeners","getWindowForElement","element","hasParent","node","parent","ancestor","getCenter","pointers","pointersLength","x","y","i","simpleCloneInputData","input","pointers","i","getCenter","getPointDistance","p1","p2","x","y","getEventDistance","getPointAngle","p1","p2","x","y","getEventAngle","getDirection","dx","dy","InputDirection","computeDeltaXY","session","input","center","offset","prevDelta","prevInput","InputEvent","getVelocity","deltaTime","x","y","getScale","start","end","getEventDistance","getRotation","start","end","getEventAngle","computeIntervalInputData","session","input","last","deltaTime","velocity","velocityX","velocityY","direction","InputEvent","deltaX","deltaY","v","getVelocity","getDirection","computeInputData","manager","input","session","pointers","pointersLength","simpleCloneInputData","firstInput","firstMultiple","offsetCenter","center","getCenter","getPointAngle","getPointDistance","deltaX","deltaY","computeDeltaXY","getDirection","overallVelocity","getVelocity","getScale","getRotation","target","hasParent","computeIntervalInputData","inputHandler","manager","eventType","input","pointersLen","changedPointersLen","isFirst","InputEvent","isFinal","processedInput","computeInputData","Input","manager","ev","eventType","input","inputHandler","addEventListeners","getWindowForElement","removeEventListeners","POINTER_INPUT_MAP","InputEvent","POINTER_ELEMENT_EVENTS","POINTER_WINDOW_EVENTS","PointerEventInput","Input","manager","ev","store","removePointer","eventType","pointerType","isTouch","storeIndex","e","VENDOR_PREFIXES","prefixed","obj","property","camelProp","prefix","prop","STOP","FORCED_STOP","defaultOptions","Manager","element","options","PointerEventInput","TouchAction","force","inputData","session","recognizer","recognizers","curRecognizer","RecognizerState","i","recognizerName","item","existing","recognizerOrName","index","events","handler","handlers","event","splitStr","data","evt","add","name","value","prop","prefixed","_uniqueId","uniqueId","stateStr","state","RecognizerState","Recognizer","options","uniqueId","RecognizerState","recognizerOrName","item","otherRecognizer","simultaneous","requireFail","index","recognier","input","state","stateStr","i","inputData","inputDataClone","AttrRecognizer","Recognizer","input","optionPointers","state","eventType","isRecognized","RecognizerState","isValid","InputEvent","TapRecognizer","Recognizer","options","TOUCH_ACTION_MANIPULATION","input","validPointers","validMovement","validTouchTime","InputEvent","validInterval","validMultiTap","getPointDistance","RecognizerState","EVENT_NAMES","PanRecognizer","AttrRecognizer","options","InputDirection","direction","actions","TOUCH_ACTION_PAN_Y","TOUCH_ACTION_PAN_X","suffix","input","hasMoved","distance","x","y","RecognizerState","EVENT_NAMES","PinchRecognizer","AttrRecognizer","options","TOUCH_ACTION_NONE","suffix","input","RecognizerState","inOut","Input","element","callback","options","userAgent","window_","firefox","userAgent","WHEEL_DELTA_MAGIC_SCALER","WHEEL_DELTA_PER_LINE","SHIFT_MULTIPLIER","WheelInput","Input","element","callback","options","event","value","eventType","enabled","MOUSE_EVENTS","MoveInput","Input","element","callback","options","event","enable","eventType","enabled","type","KEY_EVENTS","KeyInput","Input","element","callback","options","event","targetElement","eventType","enabled","ContextmenuInput","Input","element","callback","options","event","eventType","enabled","MOUSE_EVENTS","MOUSE_EVENT_BUTTON_LEFT","MOUSE_EVENT_BUTTON_MIDDLE","MOUSE_EVENT_BUTTON_RIGHT","MOUSE_EVENT_BUTTONS_LEFT_MASK","MOUSE_EVENT_BUTTONS_RIGHT_MASK","MOUSE_EVENT_BUTTONS_MIDDLE_MASK","whichButtons","event","eventType","buttons","button","leftButton","middleButton","rightButton","getOffsetPosition","rootElement","center","rect","scaleX","scaleY","offsetCenter","DEFAULT_OPTIONS","EventRegistrar","eventManager","recognizerName","event","mjolnirEvent","target","type","handler","options","once","passive","handlers","handlersByElement","opts","entries","entry","insertPosition","i","srcElement","immediatePropagationStopped","stopPropagation","stopImmediatePropagation","entriesToRemove","rootElement","whichButtons","getOffsetPosition","normalizeRecognizer","item","recognizer","itemArray","RecognizerType","options","EventManager","element","event","Manager","recognizeWith","requireFailure","WheelInput","MoveInput","KeyInput","ContextmenuInput","handler","opts","name","enabled","manager","once","passive","eventName","eventHandler","events","eventRegistrar","recognizerName","EventRegistrar","isRecognizerUsed","eh","COORDINATE_SYSTEM","log_default","PROJECTION_MODE","UNIT","EVENT_HANDLERS","RECOGNIZERS","PanRecognizer","InputDirection","PinchRecognizer","TapRecognizer","isEqual","a","b","len","memoize","compute","cachedArgs","cachedResult","args","key","ZERO_VECTOR","VECTOR_TO_POINT_MATRIX","IDENTITY_MATRIX","DEFAULT_PIXELS_PER_UNIT2","DEFAULT_COORDINATE_ORIGIN","COORDINATE_SYSTEM_NUMBERS","getShaderCoordinateSystem","coordinateSystem","shaderCoordinateSystem","getMemoizedViewportUniforms","memoize","calculateViewportUniforms","getOffsetOrigin","viewport","coordinateOrigin","shaderCoordinateOrigin","geospatialOrigin","offsetMode","PROJECTION_MODE","calculateMatrixAndOffset","viewMatrixUncentered","projectionMatrix","viewMatrix","viewProjectionMatrix","projectionCenter","originCommon","cameraPosCommon","vec4_exports","mat4_exports","getUniformsFromViewport","devicePixelRatio","modelMatrix","autoWrapLongitude","uniforms","distanceScales","viewportSize","focalDistance","distanceScalesAtOrigin","SHADER_COORDINATE_SYSTEMS","COORDINATE_SYSTEM_WGSL_CONSTANTS","coordinateSystem","getShaderCoordinateSystem","PROJECTION_MODE_WGSL_CONSTANTS","PROJECTION_MODE","key","UNIT_WGSL_CONSTANTS","UNIT","projectWGSLHeader","projectWGSL","SHADER_COORDINATE_SYSTEMS","COORDINATE_SYSTEM_GLSL_CONSTANTS","coordinateSystem","getShaderCoordinateSystem","PROJECTION_MODE_GLSL_CONSTANTS","PROJECTION_MODE","key","UNIT_GLSL_CONSTANTS","UNIT","projectGLSL","INITIAL_MODULE_OPTIONS","getUniforms","opts","getUniformsFromViewport","project_default","fp32","geometry_default","projectWGSL","projectGLSL","source","vs","project32_default","project_default","createMat4","transformVector","matrix","vector","result","vec4_exports","clamp","x","min","max","ieLog2","log2","assert","condition","message","PI","PI_4","DEGREES_TO_RADIANS","RADIANS_TO_DEGREES","TILE_SIZE","EARTH_CIRCUMFERENCE","MAX_LATITUDE","DEFAULT_ALTITUDE","zoomToScale","zoom","scaleToZoom","scale","log2","lngLatToWorld","lngLat","lng","lat","assert","lambda2","phi2","x","y","worldToLngLat","xy","getMeterZoom","options","latitude","latCosine","unitsPerMeter","getDistanceScales","longitude","highPrecision","worldSize","unitsPerDegreeX","unitsPerDegreeY","altUnitsPerMeter","result","latCosine2","unitsPerDegreeY2","altUnitsPerDegree2","altUnitsPerMeter2","addMetersToLngLat","lngLatZ","xyz","z0","z","unitsPerMeter2","worldspace","newLngLat","newZ","getViewMatrix","height","pitch","bearing","altitude","center","vm","createMat4","mat4_exports","relativeScale","vec3_exports","getProjectionParameters","width","offset","nearZMultiplier","farZMultiplier","fovy","altitudeToFovy","fovRadians","pitchRadians","focalDistance","fovyToAltitude","cameraToSeaLevelDistance","fovAboveCenter","topHalfSurfaceDistance","clamp","furthestDistance","horizonDistance","farZ","getProjectionMatrix","fov","aspect","near","far","worldToPixels","pixelProjectionMatrix","transformVector","pixelsToWorld","pixelUnprojectionMatrix","targetZ","coord0","coord1","z1","t","vec2_exports","fitBounds","options","width","height","bounds","minExtent","maxZoom","offset","west","south","east","north","padding","getPaddingObject","nw","lngLatToWorld","clamp","MAX_LATITUDE","se","size","targetSize","assert","scaleX","scaleY","offsetX","offsetY","center","centerLngLat","worldToLngLat","zoom","log2","DEGREES_TO_RADIANS","getBounds","viewport","z","width","height","unproject","unprojectOps","bottomLeft","bottomRight","topLeft","topRight","halfFov","angleToGround","unprojectOnFarPlane","x","targetZ","pixelUnprojectionMatrix","coord0","transformVector","coord1","t","coord","vec2_exports","result","worldToLngLat","WebMercatorViewport","_WebMercatorViewport","props","viewport","mat4_exports","lngLatZ","options","topLeft","worldPosition","coord","worldToPixels","x","y","y2","xyz","targetZ","z","targetZWorld","pixelsToWorld","X","Y","Z","lngLatToWorld","worldToLngLat","width","height","altitude","fovy","latitude","longitude","zoom","pitch","bearing","position","nearZMultiplier","farZMultiplier","DEFAULT_ALTITUDE","altitudeToFovy","fovyToAltitude","scale","zoomToScale","distanceScales","getDistanceScales","center","vec3_exports","getProjectionMatrix","getViewMatrix","projectionMatrix","viewMatrix","vpm","createMat4","m","mInverse","lngLat","xy","pos","fromLocation","toLocation","translate","vec2_exports","newCenter","bounds","fitBounds","corners","west","p","east","south","north","getBounds","uniformBlock","vertex","vs","fragment","fs","getMemoizedViewportCenterPosition","memoize","getViewportCenterPosition","getMemoizedViewProjectionMatrices","getViewProjectionMatrices","DEFAULT_SHADOW_COLOR","VECTOR_TO_POINT_MATRIX","screenToCommonSpace","xyz","pixelUnprojectionMatrix","x","y","z","coord","pixelsToWorld","viewport","center","Matrix4","shadowMatrices","projectionMatrices","farZ","corners","pixel","shadowMatrix","viewMatrix","Vector3","positions","corner","projectionMatrix","position","createShadowUniforms","opts","shadowEnabled","projectProps","projectUniforms","project_default","projectCenters","viewProjectionMatrices","i","viewProjectionMatrix","viewProjectionMatrixCentered","getShaderCoordinateSystem","PROJECTION_MODE","uniforms","shadow_default","sourceWGSL","picking_default","picking","DEFAULT_MODULES","geometry_default","SHADER_HOOKS_GLSL","SHADER_HOOKS_WGSL","getShaderAssembler","language","shaderAssembler","ShaderAssembler","shaderModule","shaderHooks","shaderHook","DEFAULT_LIGHT_COLOR","DEFAULT_LIGHT_INTENSITY","idCount","AmbientLight","props","color","intensity","DEFAULT_LIGHT_COLOR","DEFAULT_LIGHT_INTENSITY","DEFAULT_LIGHT_DIRECTION","idCount","DirectionalLight","props","color","intensity","direction","_shadow","Vector3","opts","Pass","device","props","id","params","WEBGPU_DEFAULT_DRAW_PARAMETERS","LayersPass","Pass","options","canvasContext","framebuffer","width","height","clearCanvas","clearColor","clearDepth","clearStencil","colorMask","parameters","renderPass","target","shaderModuleProps","viewports","views","onViewportActive","clearStack","renderStats","viewport","view","drawLayerParams","subViewports","subViewport","stats","layers","pass","isPicking","layerFilter","cullRect","effects","evaluateShouldDrawOnly","indexResolver","layerIndexResolver","drawContext","layerFilterCache","layerIndex","layer","shouldDrawLayer","layerParam","defaultParams","globalModuleParameters","glViewport","getGLViewport","clear","colorToUse","depthToUse","stencilToUse","c","renderStatus","drawLayerParameters","layerRenderIndex","layerParameters","err","otherShaderModuleProps","parent","rootLayerId","overrides","devicePixelRatio","layerProps","effect","mergeModuleParameters","startIndex","layerIndices","resolvers","resolveLayerIndex","isDrawn","indexOverride","layerId","parentId","index","resolver","device","pixelRatio","drawingBufferHeight","dimensions","sources","source","key","ShadowPass","LayersPass","device","props","shadowMap","depthBuffer","params","target","pixelRatio","viewport","width","height","clearColor","layer","layerIndex","effects","otherShaderModuleProps","DEFAULT_AMBIENT_LIGHT_PROPS","DEFAULT_DIRECTIONAL_LIGHT_PROPS","DEFAULT_SHADOW_COLOR","LightingEffect","props","context","device","deck","shadow_default","key","lightSource","light","layers","layerFilter","viewports","onViewportActive","views","i","layer","otherShaderModuleProps","shadowProps","shadowPass","lightingProps","materialProps","lightMatrices","viewMatrix","Matrix4","Vector3","ShadowPass","ambientLight","pointLights","directionalLights","AmbientLight","DirectionalLight","lights","pointLight","directionalLight","TypedArrayManager","options","typedArray","count","size","type","padding","copy","initialize","maxCount","Type","newSize","maxSize","newArray","sizeToAllocate","pool","byteLength","i","b","array","buffer","typed_array_manager_default","createMat4","mod","value","divisor","modulus","getCameraPosition","viewMatrixInverse","getFrustumPlanes","viewProjectionMatrix","getFrustumPlane","scratchVector","Vector3","a","b","c","d","L","fp64LowPart","x","scratchArray","toDoublePrecisionArray","typedArray","options","size","startIndex","endIndex","count","typed_array_manager_default","sourceIndex","targetIndex","j","value","mergeBounds","boundsList","mergedBounds","isMerged","bounds","DEGREES_TO_RADIANS","IDENTITY","createMat4","ZERO_VECTOR","DEFAULT_DISTANCE_SCALES","createProjectionMatrix","width","height","orthographic","fovyRadians","focalDistance","padding","near","far","aspect","matrix","Matrix4","left","right","top","bottom","offsetX","clamp","offsetY","Viewport","_Viewport","opts","longitude","latitude","PROJECTION_MODE","viewport","equals","xyz","topLeft","worldPosition","coord","worldToPixels","x","y","y2","targetZ","z","targetZWorld","pixelsToWorld","X","Y","Z","result","lngLatToWorld","worldToLngLat","options","unprojectOption","topRight","bottomLeft","bottomRight","coordinateOrigin","getDistanceScales","getFrustumPlanes","coords","pixel","startPixel","getMeterZoom","scale","position","modelMatrix","meterOffset","center","Vector3","viewMatrix","projectionMatrix","fovy","vpm","mat4_exports","getCameraPosition","viewportMatrix","pixelProjectionMatrix","log_default","WebMercatorViewport","_WebMercatorViewport","viewport_default","opts","latitude","longitude","zoom","pitch","bearing","nearZMultiplier","farZMultiplier","nearZ","farZ","orthographic","projectionMatrix","repeat","worldOffset","position","padding","legacyMeterSizes","width","height","altitude","scale","fovy","projectionParameters","altitudeToFovy","fovyToAltitude","offset","top","bottom","clamp","getProjectionParameters","unitsPerMeter","viewMatrixUncentered","getViewMatrix","Matrix4","bounds","minOffset","maxOffset","x","offsetViewport","xyz","X","Y","Z","lngLatZ","addMetersToLngLat","coords","pixel","startPixel","fromLocation","pixelsToWorld","toLocation","translate","vec2_exports","newCenter","targetZ","deltaLngLat","options","corners","getBounds","fitBounds","DEFAULT_COORDINATE_ORIGIN","lngLatZToWorldPosition","lngLatZ","viewport","offsetMode","p","web_mercator_viewport_default","longitude","latitude","z","distanceScales","normalizeParameters","opts","modelMatrix","coordinateOrigin","coordinateSystem","fromCoordinateSystem","fromCoordinateOrigin","getWorldPosition","position","x","y","vec4_exports","addMetersToLngLat","projectPosition","params","autoOffset","geospatialOrigin","shaderCoordinateOrigin","getOffsetOrigin","worldPosition","positionCommonSpace","vec3_exports","channelHandles","animationHandles","Timeline","props","delay","duration","rate","repeat","channelId","channel","animationHandle","animation","time","channels","animations","animationData","channelHandle","engineTime","offsetTime","totalDuration","init_dist","requestAnimationFramePolyfill","callback","browserRequestAnimationFrame","cancelAnimationFramePolyfill","timerId","browserCancelAnimationFrame","init_dist","statIdCounter","ANIMATION_LOOP_STATS","AnimationLoop","_AnimationLoop","error","props","Stats","luma","reason","appContext","err","time","timeline","resolve","display","requestAnimationFramePolyfill","cancelAnimationFramePolyfill","animationProps","canvasContext","canvas","useDevicePixels","width","height","aspect","wrapperDiv","div","html","now","frameTime","gpuTimeMs","name","sourceStat","targetStat","event","init_dist","init_dist","uidCounters","uid","id","count","GPUGeometry","props","uid","Buffer","attribute","positions","makeGPUGeometry","device","geometry","indices","getIndexBufferFromGeometry","attributes","bufferLayout","getAttributeBuffersFromGeometry","data","attributeName","name","value","size","normalized","vertexFormatDecoder","vertexCount","getDebugTableForShaderLayout","layout","name","table","header","attributeDeclaration","glslDeclaration","varyingDeclaration","DEBUG_FRAMEBUFFER_STATE_KEY","debugFramebuffer","renderPass","source","options","state","getDebugFramebufferState","isDefaultRenderPass","flushDebugFramebuffers","isFramebuffer","webglDevice","gl","previousReadFramebuffer","previousDrawFramebuffer","targetWidth","targetHeight","topPx","parseCssPixel","leftPx","framebuffer","targetX0","targetY0","targetX1","targetY1","previewHeight","getOverlayRect","minimap","maxWidth","maxHeight","scale","previewWidth","device","DEBUG_FRAMEBUFFER_STATE_KEY","value","defaultValue","parsedValue","deepEqual","a","b","depth","aKeys","bKeys","key","init_dist","BufferLayoutHelper","bufferLayouts","name","layout","bufferLayout","bufferLayouts1","bufferLayouts2","mergedLayouts","attribute","index","attribute2","bufferName","bufferIndex","log","getMinLocation","attributeNames","shaderLayoutMap","minLocation","name","location","sortedBufferLayoutByShaderSourceLocations","shaderLayout","bufferLayout","attr","sortedLayout","a","b","attributeNamesA","attributeNamesB","minLocationA","minLocationB","mergeShaderModuleBindingsIntoLayout","shaderLayout","modules","module","mergedLayout","binding","bindingLayout","relatedBindingName","getRelatedBindingNames","candidate","shaderModuleHasUniforms","isObjectEmpty","bindingName","bindingNames","obj","key","init_dist","isUniformValue","value","isNumericArray","splitUniformsAndBindings","uniforms","uniformTypes","result","name","uniform","ShaderInputs","modules","options","resolvedModules","getShaderModuleDependencies","isShaderInputsModuleWithDependencies","resolvedModule","log","name","module","props","moduleName","moduleProps","oldUniforms","oldBindings","uniformsAndBindings","uniforms","bindings","splitUniformsAndBindings","mergeModuleUniforms","moduleBindings","table","key","value","currentUniforms","nextUniforms","uniformTypes","mergedUniforms","mergeModuleUniformValue","currentValue","nextValue","uniformType","cloneModuleUniformValue","isPackedUniformArrayValue","currentArray","mergedArray","index","elementValue","isPlainUniformObject","uniformStruct","currentObject","mergedObject","element","nestedValue","init_dist","init_dist","TEXTURE_CUBE_FACE_MAP","getFirstMipLevel","layer","getTextureSizeFromData","props","dimension","data","mipLevel","width","getTextureMipLevelSize","face","faceData","firstCube","isExternalImage","getExternalImageSize","isTextureImageData","isTypedArrayMipLevelData","resolveTextureImageFormat","textureFormat","format","getCubeFaceIndex","idx","TEXTURE_CUBE_FACE_MAP","getCubeArrayFaceIndex","cubeIndex","getTexture1DSubresources","_normalizeTexture2DData","getTexture2DSubresources","slice","lodData","baseLevelSize","lodArray","z","subresources","imageData","getTexture3DSubresources","depth","getTextureArraySubresources","getTextureCubeSubresources","faceDepth","getTextureCubeArraySubresources","cubeData","DynamicTexture","_DynamicTexture","width","height","device","props","id","uid","originalPropsWithAsyncData","resolve","reject","propsWithSyncData","subresources","getTextureSubresources","userProvidedFormat","userProvidedUsage","size","getTextureSizeFromData","textureData","analyzeTextureSubresources","resolvedFormat","baseTextureProps","Texture","shouldGenerateMipmaps","requiredUsage","maxMips","desired","finalTextureProps","log","e","err","sampler","s","Sampler","options","depthOrArrayLayers","layout","buffer","Buffer","fence","data","prev","face","index","TEXTURE_CUBE_FACE_MAP","cubeIndex","getTexture1DSubresources","lodData","z","getTexture2DSubresources","getTexture3DSubresources","getTextureArraySubresources","getTextureCubeSubresources","getTextureCubeArraySubresources","subresource","mipLevel","image","flipY","textureFormat","syncData","awaitAllPromises","baseLevelSize","groupedSubresources","group","hasExplicitMipChain","resolvedMipLevels","validSubresources","sliceSubresources","sortedSubresources","left","right","baseLevel","baseSize","getTextureSubresourceSize","baseFormat","getTextureSubresourceFormat","mipLevelLimit","getMaxCompressedMipLevels","validMipLevelsForSlice","expectedMipLevel","subresourceSize","expectedWidth","expectedHeight","subresourceFormat","mipLevels","resolveTextureImageFormat","baseWidth","baseHeight","format","blockWidth","blockHeight","x","object","values","keys","resolvedObject","i","LOG_DRAW_PRIORITY","LOG_DRAW_TIMEOUT","PIPELINE_INITIALIZATION_FAILED","Model","_Model","RenderPipeline","ShaderAssembler","device","props","uid","moduleMap","module","shaderInputs","ShaderInputs","platformInfo","getPlatformInfo","modules","mergeShaderModuleBindingsIntoLayout","source","getUniforms","bindingTable","inferredShaderLayout","vs","fs","PipelineFactory","ShaderFactory","needsRedraw","reason","renderPass","loadingBinding","log","drawSuccess","pipelineErrored","syncBindings","syncBindGroups","indexBuffer","indexCount","geometry","gpuGeometry","makeGPUGeometry","bufferLayoutHelper","BufferLayoutHelper","topology","bufferLayout","parameters","deepEqual","instanceCount","vertexCount","UniformStore","moduleName","shaderModuleHasUniforms","uniformBuffer","material","bindings","transformFeedback","buffers","options","disableWarnings","sortedBufferLayoutByShaderSourceLocations","bufferName","buffer","attributeNames","set","attributeName","attributeInfo","location","attributes","value","binding","DynamicTexture","validBindings","name","shaderLayout","bindGroups","normalizeBindingsByGroup","groupKey","groupBindings","group","bindGroupCacheKey","timestamp","TextureView","Buffer","Texture","Sampler","layout","prevShaderVs","prevShaderFs","getAttributeInfosFromLayouts","logDrawTimeout","shaderLayoutTable","getDebugTableForShaderLayout","uniformTable","attributeTable","debugFramebuffers","framebuffer","debugFramebuffer","table","values","attribute","dataType","TypedArrayConstructor","dataTypeDecoder","filteredBindings","init_dist","BufferTransform","_BufferTransform","Model","device","props","getPassthroughFS","options","renderPass","varyingName","result","Buffer","buffer","byteOffset","byteLength","Geometry","props","attributes","indices","vertexCount","uid","attributeName","attributeValue","attribute","value","size","constant","PICKING_BLENDING","PickLayersPass","LayersPass","props","layers","layerFilter","views","viewports","onViewportActive","pickingFBO","x","y","width","height","cullRect","effects","pass","pickZ","shaderModuleProps","clearColor","colorEncoderState","scissorRect","renderStatus","e","decodeColor","layer","pickable","operation","otherShaderModuleProps","layerIndex","viewport","pickParameters","encodeColor","encoded","byLayer","byAlpha","a","entry","log_default","pickedColor","LIFECYCLE","COMPONENT_SYMBOL","PROP_TYPES_SYMBOL","DEPRECATED_PROPS_SYMBOL","ASYNC_DEFAULTS_SYMBOL","ASYNC_ORIGINAL_SYMBOL","ASYNC_RESOLVED_SYMBOL","flatten","array","filter","flattenArray","result","index","value","fillArray","target","source","start","count","length","total","copied","i","init_dist","Resource","id","data","context","consumer","forceUpdate","loadCount","loader","load","result","error","subscriber","ResourceManager","props","resourceId","data","forceUpdate","persistent","res","Resource","consumerId","consumer","requestId","request","resource","onChange","resources","protocol","key","consumers","oldResource","TRACE_SET_LAYERS","TRACE_ACTIVATE_VIEWPORT","LayerManager","device","props","viewport","debug","deck","stats","timeline","ResourceManager","getShaderAssembler","layerUniforms","Stats","viewport_default","Timeline","layer","opts","redraw","layerNeedsRedraw","reason","layerIds","layerId","newLayers","flatLayers","flatten","module","defaultShaderModules","m","stage","error","oldLayers","oldLayerMap","oldLayer","log_default","generatedLayers","needsUpdate","newLayer","sublayers","err","LIFECYCLE","deepEqual","a","b","depth","aKeys","bKeys","key","ViewManager","props","key","controller","opts","redraw","reason","viewId","rect","viewport","viewMap","view","viewOrViewId","viewState","xyz","viewports","pixel","i","p","width","height","views","flatten","deepEqual","log_default","Controller","controllerProps","resolvedProps","oldControllers","invalidateControllers","oldController","hasController","id","newViews","oldViews","_","NUMBER_REGEX","parsePosition","value","tokens","tokenize","LayoutExpressionParser","error","reason","evaluateLayoutExpression","expression","extent","left","right","getPosition","input","index","char","isDigit","start","hasDecimal","next","numberString","isAlpha","word","token","isAddSubSymbol","factor","numberValue","nextToken","deepMergeViewState","a","b","result","key","mergeNumericArray","target","source","i","v","View","props","id","x","y","width","height","padding","parsePosition","view","deepEqual","newProps","ViewConstructor","viewState","viewportDimensions","ViewportType","deepMergeViewState","dimensions","getPosition","opts","Transition","timeline","settings","noop","TRANSITION_EVENTS","DEFAULT_EASING","DEFAULT_INTERRUPTION","TransitionManager","opts","transition","time","interpolator","startProps","endProps","duration","easing","t","viewport","Transition","nextProps","transitionTriggered","currentProps","interruption","props","transitionDuration","transitionInterpolator","startViewstate","endViewStateProps","initialProps","transitionSettings","callback","assert","condition","message","TransitionInterpolator","opts","compare","extract","required","currentProps","nextProps","key","equals","startProps","endProps","startViewStateProps","endViewStateProps","props","propName","value","assert","DEGREES_TO_RADIANS","RADIANS_TO_DEGREES","EARTH_RADIUS","GLOBE_RADIUS","getDistanceScales","unitsPerMeter","unitsPerDegree","GlobeViewport","viewport_default","opts","longitude","zoom","nearZMultiplier","farZMultiplier","resolution","latitude","height","altitude","fovy","MAX_LATITUDE","fovyToAltitude","altitudeToFovy","scale","zoomAdjust","nearZ","farZ","viewMatrix","Matrix4","PROJECTION_MODE","options","unprojectOption","left","top","right","bottom","xyz","topLeft","targetZ","x","y","z","y2","pixelUnprojectionMatrix","coord","transformVector","coord0","coord1","lt","lSqr","vec3_exports","l0Sqr","l1Sqr","dSqr","r0","dr","t","X","Y","Z","lng","lat","lambda","phi","cosPhi","D","startLng","startLat","startZoom","pixel","startPixel","rotationSpeed","out","scaleAdjust","matrix","vector","result","vec4_exports","DEFAULT_PROPS","DEFAULT_REQUIRED_PROPS","LinearInterpolator","TransitionInterpolator","opts","transitionProps","normalizedOpts","startProps","endProps","result","makeViewport","around","globe_viewport_default","log_default","startViewport","endViewport","aroundPosition","t","propsInTransition","key","lerp","viewport","NO_TRANSITION_PROPS","DEFAULT_INERTIA","INERTIA_EASING","EVENT_TYPES","pinchEventWorkaround","Controller","opts","TransitionManager","props","customEvents","eventName","event","eventStartBlocked","x","y","offsetCenter","pos","width","height","inside","srcEvent","timeout","timer","oldProps","inertia","scrollZoom","dragPan","dragRotate","doubleClickZoom","touchZoom","touchRotate","keyboard","isInteractive","controllerState","normalizedProps","key","deepEqual","eventNames","enabled","newControllerState","extraProps","interactionState","viewState","changed","oldViewState","params","newStates","alternateMode","endPos","speed","smooth","delta","scale","transitionProps","rotation","_lastPinchEvent","z","velocityZ","endScale","isZoomOut","funcKey","zoomSpeed","moveSpeed","rotateSpeedX","rotateSpeedY","transition","LinearInterpolator","ViewState","props","state","makeViewport","PITCH_MOUSE_THRESHOLD","PITCH_ACCEL","WEB_MERCATOR_TILE_SIZE","WEB_MERCATOR_MAX_BOUNDS","lngLatToWorld","lng","lat","x","y","clamp","MapState","ViewState","options","width","height","latitude","longitude","zoom","bearing","pitch","altitude","position","maxZoom","minZoom","maxPitch","minPitch","startPanLngLat","startZoomLngLat","startRotatePos","startRotateLngLat","startBearing","startPitch","startZoom","normalize","assert","maxBounds","pos","startPos","newProps","deltaAngleX","deltaAngleY","newRotation","rotatedViewport","panMethod","scale","zoomedViewport","speed","viewState","fromProps","props","mod","bl","tr","halfWidth","halfHeight","minLng","minLat","worldToLngLat","maxLng","maxLat","shouldApplyMaxBounds","w","h","offset","viewport","deltaX","deltaY","centerY","startY","deltaScaleX","deltaScaleY","MapController","Controller","LinearInterpolator","pickResult","newControllerState","extraProps","interactionState","state","MapView","View","props","web_mercator_viewport_default","MapController","DEFAULT_LIGHTING_EFFECT","LightingEffect","compareEffects","e1","e2","o1","o2","EffectManager","context","effect","defaultEffects","e","index","props","deepEqual","opts","redraw","effects","oldEffectsMap","nextEffects","oldEffect","effectToAdd","removedEffectId","DrawLayersPass","LayersPass","layer","operation","options","TRACE_RENDER_LAYERS","DeckRenderer","device","opts","DrawLayersPass","PickLayersPass","props","layerPass","renderOpts","outputBuffer","renderResult","renderStats","debug","redraw","renderBuffers","buffer","source","layersCount","visibleCount","effects","effect","size","width","height","i","texture","params","init_dist","NO_PICKED_OBJECT","getClosestObject","pickedColors","decodePickingColor","deviceX","deviceY","deviceRadius","deviceRect","x","y","width","height","minSquareDistanceToCenter","closestPixelIndex","i","row","dy","dy2","col","dx","d2","pickedColor","pickedObject","log_default","getUniqueObjects","uniqueColors","colorKey","getEmptyPickingInfo","pickInfo","viewports","pixelRatio","x","y","z","pickedViewport","getViewportFromCoordinates","coordinate","point","processPickInfo","opts","lastPickedInfo","mode","layers","pickedColor","pickedLayer","pickedObjectIndex","affectedLayers","lastPickedPixelIndex","lastPickedLayerId","pickedLayerId","lastPickedLayer","layer","baseInfo","infos","info","getLayerPickingInfo","rootLayer","sourceLayer","pixel","i","viewport","DeckPicker","device","opts","PickLayersPass","props","x","y","layers","viewports","lastPickedInfo","lastPickedLayerId","lastPickedViewportId","layer","l","viewport","v","coordinate","pickingColorTexture","Texture","depthColorTexture","depthFBO","canvas","pickableLayers","views","radius","depth","mode","unproject3D","onViewportActive","effects","pixelRatio","getEmptyPickingInfo","devicePixelRange","devicePixel","deviceRadius","width","height","deviceRect","cullRect","infos","result","affectedLayers","i","pickInfo","pickedResult","getClosestObject","z","depthLayers","pickedColors2","processPickInfo","info","maxObjects","leftTop","deviceLeft","deviceTop","rightBottom","deviceRight","deviceBottom","pickInfos","getUniqueObjects","uniquePickedObjects","uniqueInfos","limitMaxObjects","getLayerPickingInfo","pickedLayerId","uniqueObjectsInLayer","pickedObjectKey","pass","pickZ","pickingFBO","effect","decodePickingColor","stats","texture","pickedColors","hasNonZeroAlpha","log_default","options","ArrayType","layout","readBuffer","Buffer","readData","bytesPerElement","source","packedRowLength","sourceRowLength","packed","row","sourceStart","layersCount","visibleCount","pickedLayer","isDraped","deviceX","deviceY","deviceWidth","deviceHeight","PLACEMENTS","DEFAULT_PLACEMENT","ROOT_CONTAINER_ID","WidgetManager","deck","parentElement","props","deepEqual","nextWidgets","widget","id","w","viewports","layers","viewportsById","acc","v","viewId","viewport","info","event","eventHandlerProp","EVENT_HANDLERS","oldWidgetMap","oldWidget","placement","container","viewIdOrContainer","containerId","viewContainer","canvasWidth","canvasHeight","visible","applyStyles","element","style","key","value","removeStyles","Widget","props","oldProps","el","deepEqual","removeStyles","applyStyles","v","viewId","viewState","CLASS_NAMES","element","cls","className","params","viewport","info","event","defaultStyle","TooltipWidget","Widget","props","el","rootElement","viewport","info","deck","getTooltip","displayInfo","x","y","init_dist","init_dist","noop","getCursor","isDragging","defaultProps","error","log_default","Deck","props","Stats","event","_pickRequest","pos","eventHandlerProp","EVENT_HANDLERS","layers","internalPickingMode","info","pointerDownPickSequence","pickedInfo","pickPromise","pickResult","fallbackInfo","deviceOrPromise","userOnResize","webgl2Adapter","canvasContext","width","height","typed_array_manager_default","deepEqual","resolvedProps","opts","redraw","viewManagerNeedsRedraw","layerManagerNeedsRedraw","effectManagerNeedsRedraw","deckRendererNeedsRedraw","reason","redrawReason","assert","viewId","rect","infos","x","y","resources","forceUpdate","id","resourceIds","effect","module","pickAsync","deviceType","result","emptyInfo","layer","handled","layerHandler","rootHandler","method","statKey","stats","canvas","cssWidth","cssHeight","newWidth","newHeight","gl","onError","AnimationLoop","context","canvasContextUserProps","canvasContextProps","deviceProps","defaultCanvasProps","luma","views","normalizedViews","map_view_default","pickOptions","hoverPickSequence","container","device","timeline","Timeline","eventRoot","EventManager","RECOGNIZERS","eventName","RecognizerConstructor","defaultOptions","recognizeWith","requestFailure","optionsOverride","options","eventType","ViewManager","viewport","LayerManager","EffectManager","DeckRenderer","DeckPicker","widgetParent","WidgetManager","TooltipWidget","renderOptions","params","viewState","interactionState","animationLoopStats","metrics","memoryStats","VERSION","init_dist","init_dist","typedArrayFromDataType","type","getTypedArrayConstructor","dataTypeFromTypedArray","dataTypeDecoder","getBufferAttributeLayout","name","accessor","deviceType","getStride","bufferLayoutEqual","accessor1","accessor2","resolveShaderAttribute","baseAccessor","shaderAttributeOptions","log_default","stride","getStride","vertexOffset","elementOffset","offset","resolveDoublePrecisionShaderAttributes","resolvedOptions","DataColumn","device","opts","state","logicalType","doublePrecision","defaultValue","bufferType","defaultType","typedArrayFromDataType","accessor","n","typed_array_manager_default","attributeName","options","result","value","shaderAttributeDef","size","attributes","doubleShaderAttributeDefs","getBufferAttributeLayout","min","numInstances","len","max","i","j","v","data","Buffer","type","dataTypeFromTypedArray","buffer","byteOffset","toDoublePrecisionArray","ArrayType","requiredBufferSize","startOffset","endOffset","copy","oldValue","illegalArrayType","x","out","start","value1","value2","byteLength","isIndexed","EMPTY_ARRAY","placeholderArray","createIterable","data","startRow","endRow","iterable","objectInfo","isAsyncIterable","getAccessorFromBuffer","typedArray","options","size","stride","offset","startIndices","nested","bytesPerElement","elementStride","elementOffset","vertexCount","_","index","target","sourceIndex","j","startIndex","endIndex","result","i","targetIndex","EMPTY","FULL","add","rangeList","range","newRangeList","len","insertPosition","i","range0","DEFAULT_TRANSITION_SETTINGS","normalizeTransitionSettings","userSettings","layerSettings","type","Attribute","DataColumn","device","opts","FULL","layout","clearChangedFlags","needsRedraw","accessor","_a","bufferLayoutEqual","layerSettings","userSettings","a","normalizeTransitionSettings","reason","dataRange","startRow","endRow","add","EMPTY","numInstances","state","settings","data","props","context","updateRanges","update","noAlloc","updated","startOffset","endOffset","value","transformedValue","ArrayType","constantValue","repeatedValue","i","hasChanged","currentValue","expectedLength","j","buffer","startIndices","binaryValue","assert","needsNormalize","getAccessorFromBuffer","row","shaderAttributeDefs","result","shaderAttributeName","modelInfo","stepMode","map","attribute","size","transform","accessorFunc","iterable","objectInfo","createIterable","object","objectValue","numVertices","startIndex","item","fillArray","limit","valid","padArrayChunk","options","source","target","start","size","getData","end","sourceLength","targetLength","i","datum","j","padArray","sourceStartIndices","targetStartIndices","sourceIndex","targetIndex","getChunkData","chunk","n","nextSourceIndex","nextTargetIndex","cloneAttribute","attribute","device","settings","value","newAttribute","Attribute","getAttributeTypeFromSize","size","getFloat32VertexFormat","cycleBuffers","buffers","getAttributeBufferLength","numInstances","doublePrecision","multiplier","maxVertexOffset","shaderAttributes","shaderAttribute","matchBuffer","source","target","padBuffer","buffer","fromLength","toLength","fromStartIndices","getData","x","precisionMultiplier","byteOffset","targetByteOffset","toStartIndices","hasStartIndices","isConstant","ArrayType","toData","getter","chunk","getMissingData","i","padArray","GPUTransitionBase","device","attribute","timeline","Transition","cloneAttribute","transitionSettings","numInstances","duration","getAttributeBufferLength","updated","buffer","GPUInterpolationTransition","GPUTransitionBase","device","attribute","timeline","getTransform","transitionSettings","numInstances","prevLength","prevStartIndices","buffers","cycleBuffers","padBuffer","matchBuffer","transform","model","vertexCount","useFp64","duration","easing","time","t","interpolationProps","uniformBlock","interpolationUniforms","vs","vs64","attributeSize","attributeType","getAttributeTypeFromSize","inputFormat","getFloat32VertexFormat","bufferLayout","BufferTransform","fp64arithmetic","GPUSpringTransition","GPUTransitionBase","device","attribute","timeline","getTexture","getFramebuffer","getTransform","transitionSettings","numInstances","prevLength","prevStartIndices","buffers","i","padBuffer","matchBuffer","model","transform","framebuffer","transition","settings","springProps","cycleBuffers","uniformBlock","springUniforms","vs","fs","attributeType","getAttributeTypeFromSize","format","getFloat32VertexFormat","BufferTransform","texture","TRANSITION_TYPES","GPUInterpolationTransition","GPUSpringTransition","AttributeTransitionManager","device","id","timeline","attributeName","attributes","transitions","numInstances","attribute","settings","transition","animatedAttributes","needsRedraw","isNew","TransitionType","log_default","TRACE_INVALIDATE","TRACE_UPDATE_START","TRACE_UPDATE_END","TRACE_ATTRIBUTE_UPDATE_START","TRACE_ATTRIBUTE_ALLOCATE","TRACE_ATTRIBUTE_UPDATE_END","AttributeManager","device","id","stats","timeline","memoize","mergeBounds","AttributeTransitionManager","attributeName","opts","redraw","attributes","attributeNameArray","name","triggerName","dataRange","invalidatedAttributes","debug","data","numInstances","startIndices","transitions","props","buffers","context","updated","attribute","accessorName","log_default","attributeTransitionManager","transitionUpdated","attributeNames","bounds","changedAttributes","modelInfo","overrideOptions","Attribute","triggers","updateTriggers","init_dist","CPUInterpolationTransition","Transition","time","fromValue","toValue","duration","easing","t","lerp","EPSILON","updateSpringElement","prev","cur","dest","damping","stiffness","velocity","spring","damper","updateSpring","next","i","distance","value1","value2","distanceSquare","d","CPUSpringTransition","Transition","fromValue","toValue","_prevValue","_currValue","nextValue","delta","TRANSITION_TYPES","CPUInterpolationTransition","CPUSpringTransition","UniformTransitionManager","timeline","key","fromValue","toValue","settings","transitions","transition","value","normalizeTransitionSettings","TransitionType","log_default","propsInTransition","validateProps","props","propTypes","PROP_TYPES_SYMBOL","propName","propType","validate","diffProps","oldProps","propsChangedReason","compareProps","dataChangedReason","diffDataProps","updateTriggersChangedReason","diffUpdateTriggers","diffExtensions","diffTransitions","result","changed","key","type","comparePropValues","newProps","ignoreProps","triggerName","newProp","oldProp","equal","dataChanged","dataComparator","_dataDiff","diffUpdateTrigger","reason","oldExtensions","extensions","i","newTriggers","oldTriggers","ERR_NOT_OBJECT","ERR_NOT_CONTAINER","count","container","isObject","isPlainObject","value","mergeShaders","target","source","result","module","index","mergedInjection","key","init_dist","DEFAULT_TEXTURE_PARAMETERS","internalTextures","createTexture","owner","device","image","sampler","Texture","samplerParameters","width","height","texture","destroyTexture","TYPE_DEFINITIONS","value","propType","value1","value2","isArray","deepEqual","valueType","getTypeOf","compare","depth","component","dataTransform","context","createTexture","destroyTexture","parsePropTypes","propDefs","propTypes","defaultProps","deprecatedProps","propName","propDef","deprecated","parsePropType","name","normalizePropDefinition","createProps","component","propObjects","extensions","i","props","propsPrototype","getPropsPrototype","propsInstance","COMPONENT_SYMBOL","ASYNC_ORIGINAL_SYMBOL","ASYNC_RESOLVED_SYMBOL","key","MergedDefaultPropsCacheKey","componentClass","component_default","cacheKey","extension","ExtensionClass","defaultProps","getOwnProperty","createPropsPrototypeAndTypes","parentClass","parentDefaultProps","componentDefaultProps","componentPropDefs","parsePropTypes","propTypes","PROP_TYPES_SYMBOL","deprecatedProps","DEPRECATED_PROPS_SYMBOL","extensionDefaultProps","createPropsPrototype","addAsyncPropsToPropPrototype","addDeprecatedPropsToPropPrototype","hasOwnProperty","id","getComponentName","propName","newValue","nameStr","newPropName","log_default","defaultValues","descriptors","propType","name","value","getDescriptorForAsyncProp","ASYNC_DEFAULTS_SYMBOL","isAsyncIterable","state","object","prop","componentName","counter","Component","propObjects","createProps","newProps","props","asyncProps","key","ASYNC_DEFAULTS_SYMBOL","ASYNC_RESOLVED_SYMBOL","ASYNC_ORIGINAL_SYMBOL","EMPTY_PROPS","ComponentState","component","propName","asyncProp","key","value","props","COMPONENT_SYMBOL","resolvedValues","ASYNC_RESOLVED_SYMBOL","originalValues","ASYNC_ORIGINAL_SYMBOL","defaultValues","ASYNC_DEFAULTS_SYMBOL","url","error","isAsyncIterable","loadCount","promise","data","iterable","count","chunk","dataTransform","propType","defaultValue","propTypes","PROP_TYPES_SYMBOL","LayerState","ComponentState","attributeManager","layer","propName","url","fetch","value","onDataLoad","error","TRACE_CHANGE_FLAG","TRACE_INITIALIZE","TRACE_UPDATE","TRACE_FINALIZE","TRACE_MATCHED","MAX_PICKING_COLOR_CACHE_SIZE","EMPTY_ARRAY","areViewportsEqual","memoize","oldViewport","viewport","pickingColorCache","defaultProps","data","url","propName","layer","loaders","loadOptions","signal","resourceManager","inResourceManager","load","layerIndex","Layer","component_default","LIFECYCLE","xyz","assert","worldPosition","getWorldPosition","x","y","z","worldToPixels","xy","params","projectPosition","partialState","state","props","model","coordinateSystem","info","pickingEvent","i","target","color","i1","i2","i3","count","shaders","mergeShaders","extension","attributeManager","dataChanged","dataRange","hasPickingBuffer","needsPickingBuffer","pickingColors","instancePickingColors","pickingColorsAttribute","context","opts","mode","sourceLayer","index","error","message","name","changedAttributes","bufferLayoutChanged","id","numInstances","startIndices","uniformTransitions","propsInTransition","key","attribute","cacheSize","log_default","typed_array_manager_default","newCacheSize","pickingColor","excludeAttributes","attributeBuffers","constantAttributes","values","attributeName","value","Buffer","objectIndex","colors","externalColorAttribute","objectColor","start","end","debug","LayerState","UniformTransitionManager","oldLayer","internalState","stateNeedsUpdate","currentProps","currentViewport","updateParams","oldModels","modelChanged","renderPass","shaderModuleProps","uniforms","parameters","getPolygonOffset","offsets","WebGLDevice","webGPUDrawParameters","splitWebGPUDrawParameters","applyModelParameters","flags","changeFlags","flagChanged","dataChangedReason","prevDataChangedReason","propsOrDataChanged","newProps","oldProps","diffProps","validateProps","picking","highlightColor","AttributeManager","forceUpdate","autoHighlight","highlightedObjectIndex","redraw","attributeManagerNeedsRedraw","blendConstant","pipelineParameters","models","syncModelAttachmentFormats","framebuffer","colorAttachmentFormats","attachment","depthStencilAttachmentFormat","modelWithProps","equalAttachmentFormats","left","right","TRACE_RENDER_LAYERS","CompositeLayer","layer_default","layer","context","updateObject","info","object","subLayerId","data","DefaultLayerClass","overridingProps","row","sourceObject","sourceObjectIndex","accessor","objectInfo","x","i","sublayerProps","opacity","pickable","visible","parameters","getPolygonOffset","highlightedObjectIndex","autoHighlight","highlightColor","coordinateSystem","coordinateOrigin","wrapLongitude","positionFormat","modelMatrix","extensions","fetch","operation","newProps","overridingSublayerProps","overridingSublayerTriggers","sublayerId","propTypes","PROP_TYPES_SYMBOL","subLayerPropTypes","key","propType","extension","passThroughProps","updateParams","forceUpdate","subLayers","shouldUpdate","subLayersList","flatten","debug","DEGREES_TO_RADIANS","RADIANS_TO_DEGREES","degreesToPixels","angle","zoom","radians","GLOBE_RADIUS","pixelsToDegrees","pixels","size","GlobeState","MapState","options","startPanPos","mapStateOptions","pos","latitude","longitude","startPos","state","startPanLngLat","startZoom","coords","newProps","scale","props","maxBounds","mod","clamp","MAX_LATITUDE","effectiveZoom","zoomAdjust","lngSpan","latSpan","halfHeightDegrees","halfWidthDegrees","maxZoom","minZoom","ZOOM0","zoomAdjustment","minLatitude","maxLatitude","fitLatitude","w","h","GlobeController","Controller","LinearInterpolator","GlobeView","View","props","viewState","web_mercator_viewport_default","globe_viewport_default","GlobeController","MapboxLayerGroup","props","assert","map","gl","renderParameters","drawLayerGroup","UNDEFINED_BEFORE_ID","getLayerGroupId","layer","resolveLayerGroups","map","oldLayers","newLayers","layers","flatten","prevLayers","prevLayerGroupIds","newLayerGroupIds","groupId","layerGroups","mapboxGroup","groupInstance","newGroup","MapboxLayerGroup","mapLayers","group","beforeId","expectedGroupIndex","moveBeforeId","MAPBOX_VIEW_ID","TILE_SIZE","DEGREES_TO_RADIANS","getDeckInstance","map","deck","customRender","onLoad","deckProps","getDefaultView","getViewState","watchMapMove","afterRender","_handleMapMove","onMapMove","removeDeckInstance","getDefaultParameters","interleaved","result","getProjection","drawLayerGroup","group","renderParameters","currentViewport","clearStack","getViewport","params","layer","projection","type","globe_view_default","map_view_default","lng","lat","viewState","centerCameraOnTerrain","position","height","longitude","latitude","pitch","cameraX","cameraY","cameraZ","center","lngLatToWorld","dx","dy","cameraToCenterDistanceGround","pitchRadians","altitudePixels","scale","cameraZFromSurface","surfaceElevation","unitsPerMeter","view","nearZ","farZ","hasNonMapboxLayers","flatten","getLayerGroupId","viewports","mapboxViewportIdx","vp","hasNonMapboxViews","mapboxViewport","device","gl","MapboxOverlay","props","getProjection","clientWidth","clientHeight","deck","map","getViewState","event","mockEvent","lastDown","interleaved","useDevicePixels","deckProps","getDefaultParameters","container","deck_default","gl","log_default","getDeckInstance","_deck","prevLayers","newLayers","resolveLayerGroups","removeDeckInstance","params","assert","getDefaultView","views","v","MAPBOX_VIEW_ID","AnimatedFlowLinesLayerFragment_glsl_default","AnimatedFlowLinesLayerVertex_glsl_default","uniformBlock","animatedFlowLinesUniforms","DEFAULT_COLOR","loopLength","animationSpeed","loopTime","AnimatedFlowLinesLayer","layer_default","props","AnimatedFlowLinesLayerVertex_glsl_default","AnimatedFlowLinesLayerFragment_glsl_default","project32_default","picking_default","animatedFlowLinesUniforms","params","changeFlags","thicknessUnit","animationTailLength","animationTime","model","id","positions","Model","Geometry","d","index","AnimatedFlowLinesLayer_default","uniformBlock","flowLinesUniforms","CurvedFlowLinesLayerFragment_glsl_default","HEAD_START_T","CurvedFlowLinesLayerVertex_glsl_default","DEFAULT_COLOR","SHAFT_SEGMENTS","HEAD_START_T","CurvedFlowLinesLayer","layer_default","CurvedFlowLinesLayerVertex_glsl_default","CurvedFlowLinesLayerFragment_glsl_default","project32_default","picking_default","flowLinesUniforms","params","changeFlags","drawOutline","outlineColor","outlineThickness","thicknessUnit","curviness","model","x","id","geometry","buildGeometry","Model","Geometry","d","positions","barycentrics","edgeMasks","pushTriangle","a","b","c","mask","index","t0","t1","CurvedFlowLinesLayer_default","FlowLinesLayerFragment_glsl_default","FlowLinesLayerVertex_glsl_default","DEFAULT_COLOR","POSITIONS","INNER_SIDE_OUTLINE_THICKNESS","PIXEL_OFFSETS","OUTLINE_OFFSET_COEFFICIENTS","OUTLINE_OFFSET_CONSTANTS","BARYCENTRICS","EDGE_MASKS","FlowLinesLayer","layer_default","props","FlowLinesLayerVertex_glsl_default","FlowLinesLayerFragment_glsl_default","project32_default","picking_default","flowLinesUniforms","params","changeFlags","drawOutline","outlineColor","outlineThickness","thicknessUnit","model","x","id","Model","Geometry","d","FlowLinesLayer_default","FlowLinesLayer_default","FlowCirclesLayerFragment_glsl_default","FlowCirclesLayerVertex_glsl_default","uniformBlock","flowCirclesUniforms","DEFAULT_COLOR","DEFAULT_EMPTY_COLOR","DEFAULT_OUTLINE_EMPTY_MIX","FlowCirclesLayer","layer_default","props","FlowCirclesLayerVertex_glsl_default","FlowCirclesLayerFragment_glsl_default","project32_default","picking_default","flowCirclesUniforms","params","changeFlags","emptyColor","outlineEmptyMix","model","x","id","positions","Model","Geometry","d","FlowCirclesLayer_default","FlowCirclesLayer_default","uniformBlock","iconUniforms","icon_layer_vertex_glsl_default","icon_layer_fragment_glsl_default","shaderWGSL","DEFAULT_CANVAS_WIDTH","DEFAULT_BUFFER","noop","DEFAULT_SAMPLER_PARAMETERS","MISSING_ICON","nextPowOfTwo","number","resizeImage","ctx","imageData","maxWidth","maxHeight","resizeRatio","width","height","getIconId","icon","regenerateMipmaps","texture","device","resizeTexture","sampler","oldWidth","oldHeight","newTexture","commandEncoder","commandBuffer","buildRowMapping","mapping","columns","yOffset","xOffset","id","buildMapping","icons","buffer","rowHeight","canvasWidth","i","getDiffIcons","data","getIcon","cachedIcons","iterable","objectInfo","createIterable","object","IconManager","onUpdate","onError","loadOptions","autoPacking","iconAtlas","iconMapping","textureParameters","canvasHeight","load","iconDef","initialX","initialY","image","x","y","error","DEFAULT_COLOR","defaultProps","x","IconLayer","layer_default","icon_layer_vertex_glsl_default","icon_layer_fragment_glsl_default","shaderWGSL","project32_default","color_default","picking_default","iconUniforms","IconManager","params","props","oldProps","changeFlags","attributeManager","iconAtlas","iconMapping","data","getIcon","textureParameters","iconManager","prePacked","context","uniforms","sizeScale","sizeBasis","sizeMinPixels","sizeMaxPixels","sizeUnits","billboard","alphaCutoff","iconsTexture","model","iconProps","UNIT","positions","Model","Geometry","didFrameChange","evt","onIconError","log_default","icon","y","width","height","mask","anchorX","anchorY","glslUniformBlock","scatterplotUniforms","scatterplot_layer_vertex_glsl_default","scatterplot_layer_fragment_glsl_default","scatterplot_layer_wgsl_default","DEFAULT_COLOR","defaultProps","x","ScatterplotLayer","layer_default","scatterplot_layer_vertex_glsl_default","scatterplot_layer_fragment_glsl_default","scatterplot_layer_wgsl_default","project32_default","color_default","picking_default","scatterplotUniforms","params","uniforms","radiusUnits","radiusScale","radiusMinPixels","radiusMaxPixels","stroked","filled","billboard","antialiasing","lineWidthUnits","lineWidthScale","lineWidthMinPixels","lineWidthMaxPixels","scatterplotProps","UNIT","model","positions","Model","Geometry","uniformBlock","sdfUniforms","CONTENT_ALIGN","glslUniformBlock","textUniforms","contentCutoffPixels","contentAlignHorizontal","contentAlignVertical","fontSize","viewport","multi_icon_layer_vertex_glsl_default","multi_icon_layer_fragment_glsl_default","DEFAULT_BUFFER","defaultProps","x","MultiIconLayer","icon_layer_default","shaders","textUniforms","sdfUniforms","multi_icon_layer_vertex_glsl_default","multi_icon_layer_fragment_glsl_default","attributeManager","instanceIconDefs","object","index","value","params","props","oldProps","changeFlags","outlineColor","normalizedOutlineColor","log_default","sdf","smoothing","fontSize","outlineWidth","contentCutoffPixels","contentAlignHorizontal","contentAlignVertical","outlineBuffer","DEFAULT_BUFFER","model","sdfProps","textProps","iconManager","attribute","startRow","endRow","data","getIcon","getIconOffsets","i","output","iterable","objectInfo","createIterable","text","offsets","j","char","def","alphaTable","i","d","TinySDF","fontSize","buffer","radius","cutoff","fontFamily","fontWeight","fontStyle","lang","size","canvas","ctx","char","glyphAdvance","actualBoundingBoxAscent","actualBoundingBoxDescent","actualBoundingBoxLeft","actualBoundingBoxRight","glyphTop","glyphLeft","glyphWidth","glyphHeight","width","height","len","data","glyph","gridInner","gridOuter","imgData","imgIdx","y","j","x","a","t","edt","pad","scale","base","x0","y0","gridSize","f","v","z","edt1d","grid","offset","stride","length","q","k","s","q2","r","qr","MISSING_CHAR_WIDTH","SINGLE_LINE","nextPowOfTwo","number","buildMapping","characterSet","measureText","buffer","maxCanvasWidth","mapping","xOffset","yOffsetMin","yOffsetMax","x","yMin","yMax","char","advance","width","ascent","descent","height","getTextWidth","text","startIndex","endIndex","i","character","breakAll","maxWidth","iconMapping","target","rowStartCharIndex","rowOffsetLeft","textWidth","breakWord","groupStartCharIndex","groupEndCharIndex","groupWidth","autoWrapping","wordBreak","result","transformRow","line","leftOffsets","rowSize","rowHeight","frame","log_default","transformParagraph","paragraph","baselineOffset","lineHeight","characters","numCharacters","y","rowWidth","autoWrappingEnabled","size","rowCount","rowOffsetTop","lineStartIndex","lineEndIndex","rows","rowIndex","rowStart","rowEnd","j","getTextFromBuffer","value","length","stride","offset","startIndices","bytesPerElement","elementStride","elementOffset","characterCount","autoCharacterSet","texts","codes","ArrayType","index","codesAtIndex","charCode","LRUCache","limit","key","value","index","getDefaultCharacterSet","charSet","i","DEFAULT_FONT_SETTINGS","MAX_CANVAS_WIDTH","DEFAULT_ASCENT","DEFAULT_DESCENT","CACHE_LIMIT","cache","LRUCache","getNewChars","cacheKey","characterSet","newCharSet","cachedFontAtlas","char","populateAlphaChannel","alphaChannel","imageData","setTextStyle","ctx","fontFamily","fontSize","fontWeight","measureText","fontMetrics","metrics","setFontAtlasCacheLimit","limit","log_default","FontAtlasManager","props","fontAtlas","buffer","sdf","radius","cutoff","canvas","defaultMeasure","renderer","getSdfFontRenderer","mapping","canvasHeight","xOffset","yOffsetMin","yOffsetMax","buildMapping","frame","data","left","top","x","y","x0","y0","w","h","tinySDF","TinySDF","width","height","uniformBlock","textBackgroundUniforms","text_background_layer_vertex_glsl_default","text_background_layer_fragment_glsl_default","defaultProps","x","TextBackgroundLayer","layer_default","text_background_layer_vertex_glsl_default","text_background_layer_fragment_glsl_default","project32_default","picking_default","textBackgroundUniforms","textUniforms","params","changeFlags","uniforms","billboard","sizeScale","sizeUnits","sizeMinPixels","sizeMaxPixels","getLineWidth","fontSize","padding","borderRadius","model","textBackgroundProps","UNIT","textProps","positions","Model","Geometry","TEXT_ANCHOR","ALIGNMENT_BASELINE","DEFAULT_COLOR","DEFAULT_LINE_HEIGHT","defaultProps","DEFAULT_FONT_SETTINGS","x","TextLayer","composite_layer_default","object","objectInfo","width","height","getTextAnchor","getAlignmentBaseline","anchorX","anchorY","y","rowWidth","numCharacters","offsets","index","i","FontAtlasManager","log_default","params","props","oldProps","changeFlags","info","fontSettings","fontFamily","fontWeight","_getFontRenderer","fontAtlasManager","characterSet","fontProps","key","data","textBuffer","getText","startIndices","numInstances","autoCharacterSet","texts","characterCount","getTextFromBuffer","_","iterable","createIterable","text","iconMapping","baselineOffset","fontSize","wordBreak","lineHeight","maxWidth","paragraph","transformParagraph","atlas","mapping","styleVersion","_dataDiff","getPosition","getColor","getSize","getAngle","getPixelOffset","getBackgroundColor","getBorderColor","getBorderWidth","getContentBox","backgroundBorderRadius","backgroundPadding","background","billboard","outlineWidth","outlineColor","sizeScale","sizeUnits","sizeMinPixels","sizeMaxPixels","contentCutoffPixels","contentAlignHorizontal","contentAlignVertical","transitions","updateTriggers","CharactersLayerClass","multi_icon_layer_default","BackgroundLayerClass","text_background_layer_default","limit","setFontAtlasCacheLimit","isCluster","c","children","isLocationClusterNode","l","zoom","isAggregateFlow","flow","LocationFilterMode","colors_default","specifier","n","colors","define_default","constructor","factory","prototype","extend","parent","definition","key","Color","darker","brighter","reI","reN","reP","reHex","reRgbInteger","reRgbPercent","reRgbaInteger","reRgbaPercent","reHslPercent","reHslaPercent","named","define_default","color","channels","color_formatHex","color_formatHex8","color_formatHsl","color_formatRgb","hslConvert","format","m","l","rgbn","Rgb","rgba","hsla","n","r","g","b","a","rgbConvert","o","rgb","opacity","extend","k","clampi","clampa","rgb_formatHex","rgb_formatHex8","rgb_formatRgb","hex","value","h","s","Hsl","min","max","hsl","m2","m1","hsl2rgb","clamph","clampt","radians","degrees","K","Xn","Yn","Zn","t0","t1","t2","t3","labConvert","o","Lab","Hcl","hcl2lab","Rgb","rgbConvert","r","rgb2lrgb","g","b","y","xyz2lab","x","z","lab","l","a","b","opacity","labConvert","Lab","define_default","extend","Color","k","K","y","x","z","Xn","lab2xyz","Yn","Zn","Rgb","lrgb2rgb","xyz2lab","t3","t2","t0","t1","rgb2lrgb","hclConvert","o","Hcl","h","degrees","hcl","h","c","l","opacity","hclConvert","Hcl","hcl2lab","o","Lab","radians","define_default","extend","Color","k","K","A","B","C","D","E","ED","EB","BC_DA","cubehelixConvert","o","Cubehelix","Rgb","rgbConvert","r","g","b","l","bl","k","s","h","degrees","cubehelix","opacity","define_default","extend","Color","brighter","darker","radians","a","cosh","sinh","basis","t1","v0","v1","v2","v3","t2","t3","basis_default","values","n","t","basisClosed_default","values","n","t","v0","v1","v2","v3","basis","constant_default","x","linear","a","d","t","exponential","b","y","hue","constant_default","gamma","nogamma","rgb_default","rgbGamma","y","color","gamma","rgb","start","end","r","g","b","opacity","nogamma","t","rgbSpline","spline","colors","n","i","rgbBasis","basis_default","rgbBasisClosed","basisClosed_default","numberArray_default","a","b","n","c","i","t","isNumberArray","x","genericArray","a","b","nb","na","x","c","i","value_default","t","date_default","a","b","d","t","number_default","a","b","t","object_default","a","b","i","c","k","value_default","t","reA","reB","zero","b","one","t","string_default","a","bi","am","bm","bs","i","s","q","number_default","o","value_default","a","b","t","c","constant_default","number_default","color","rgb_default","string_default","date_default","isNumberArray","numberArray_default","genericArray","object_default","round_default","a","b","t","cubehelix","hue","cubehelixGamma","y","start","end","h","s","nogamma","l","opacity","t","cubehelix_default","cubehelixLong","ramp_default","scheme","rgbBasis","scheme","colors_default","BuGn_default","ramp_default","scheme","colors_default","BuPu_default","ramp_default","scheme","colors_default","GnBu_default","ramp_default","scheme","colors_default","OrRd_default","ramp_default","scheme","colors_default","PuBuGn_default","ramp_default","scheme","colors_default","PuBu_default","ramp_default","scheme","colors_default","PuRd_default","ramp_default","scheme","colors_default","RdPu_default","ramp_default","scheme","colors_default","YlGnBu_default","ramp_default","scheme","colors_default","YlGn_default","ramp_default","scheme","colors_default","YlOrBr_default","ramp_default","scheme","colors_default","YlOrRd_default","ramp_default","scheme","colors_default","Blues_default","ramp_default","scheme","colors_default","Greens_default","ramp_default","scheme","colors_default","Greys_default","ramp_default","scheme","colors_default","Purples_default","ramp_default","scheme","colors_default","Reds_default","ramp_default","scheme","colors_default","Oranges_default","ramp_default","warm","cubehelixLong","cubehelix","cool","c","ramp","range","n","t","viridis_default","colors_default","magma","inferno","plasma","ascending","a","b","descending","a","b","bisector","f","compare1","compare2","delta","ascending","d","x","descending","zero","left","lo","hi","mid","right","center","i","number","x","ascendingBisect","bisector","ascending","bisectRight","bisectLeft","bisectCenter","number","bisect_default","extent","values","valueof","min","max","value","index","Adder","x","p","j","y","hi","lo","n","InternMap","entries","key","keyof","value","intern_get","intern_set","intern_delete","intern_get","_intern","_key","value","key","intern_set","intern_delete","keyof","identity","x","rollup","values","reduce","keys","nest","identity","nest","values","map","reduce","keys","regroup","i","groups","InternMap","keyof","index","value","key","group","e10","e5","e2","tickSpec","start","stop","count","step","power","error","factor","i1","i2","inc","ticks","reverse","n","i","tickIncrement","tickStep","min","values","valueof","value","index","range","start","stop","step","initRange","domain","range","initInterpolator","interpolator","constants","x","number","x","unit","identity","x","normalize","a","b","constants","clamper","t","bimap","domain","range","interpolate","d0","d1","r0","r1","polymap","j","d","r","i","bisect_default","copy","source","target","transformer","value_default","transform","untransform","unknown","clamp","piecewise","output","input","rescale","n","scale","y","number_default","_","number","round_default","u","continuous","formatDecimal_default","x","formatDecimalParts","p","i","coefficient","exponent_default","x","formatDecimalParts","formatGroup_default","grouping","thousands","value","width","i","t","j","g","length","formatNumerals_default","numerals","value","i","re","formatSpecifier","specifier","match","FormatSpecifier","formatTrim_default","s","out","n","i","i0","i1","prefixExponent","formatPrefixAuto_default","x","p","d","formatDecimalParts","coefficient","exponent","i","n","formatRounded_default","x","p","d","formatDecimalParts","coefficient","exponent","formatTypes_default","x","p","formatDecimal_default","formatRounded_default","formatPrefixAuto_default","identity_default","x","map","prefixes","locale_default","locale","group","identity_default","formatGroup_default","currencyPrefix","currencySuffix","decimal","numerals","formatNumerals_default","percent","minus","nan","newFormat","specifier","options","formatSpecifier","fill","align","sign","symbol","zero","width","comma","precision","trim","type","formatTypes_default","prefix","suffix","formatType","maybeSuffix","format","value","valuePrefix","valueSuffix","i","n","c","valueNegative","formatTrim_default","prefixExponent","length","padding","formatPrefix","e","exponent_default","k","f","locale","format","formatPrefix","defaultLocale","definition","locale_default","precisionFixed_default","step","exponent_default","precisionPrefix_default","step","value","exponent_default","precisionRound_default","step","max","exponent_default","tickFormat","start","stop","count","specifier","step","tickStep","precision","formatSpecifier","value","precisionPrefix_default","formatPrefix","precisionRound_default","precisionFixed_default","format","linearish","scale","domain","count","d","ticks","specifier","tickFormat","i0","i1","start","stop","prestep","step","maxIter","tickIncrement","linear","continuous","copy","initRange","transformPow","exponent","x","transformSqrt","transformSquare","powish","transform","scale","identity","rescale","_","linearish","pow","transformer","copy","initRange","sqrt","t0","t1","timeInterval","floori","offseti","count","field","interval","date","d0","d1","step","start","stop","range","previous","test","end","d","second","timeInterval","date","step","start","end","seconds","timeMinute","timeInterval","date","step","start","end","timeMinutes","utcMinute","utcMinutes","timeHour","timeInterval","date","step","start","end","timeHours","utcHour","utcHours","timeDay","timeInterval","date","step","start","end","timeDays","utcDay","utcDays","unixDay","unixDays","timeWeekday","i","timeInterval","date","step","start","end","timeSunday","timeMonday","timeTuesday","timeWednesday","timeThursday","timeFriday","timeSaturday","timeSundays","timeMondays","timeTuesdays","timeWednesdays","timeThursdays","timeFridays","timeSaturdays","utcWeekday","utcSunday","utcMonday","utcTuesday","utcWednesday","utcThursday","utcFriday","utcSaturday","utcSundays","utcMondays","utcTuesdays","utcWednesdays","utcThursdays","utcFridays","utcSaturdays","timeMonth","timeInterval","date","step","start","end","timeMonths","utcMonth","utcMonths","timeYear","timeInterval","date","step","start","end","k","timeYears","utcYear","utcYears","localDate","d","date","utcDate","newDate","y","m","formatLocale","locale","locale_dateTime","locale_date","locale_time","locale_periods","locale_weekdays","locale_shortWeekdays","locale_months","locale_shortMonths","periodRe","formatRe","periodLookup","formatLookup","weekdayRe","weekdayLookup","shortWeekdayRe","shortWeekdayLookup","monthRe","monthLookup","shortMonthRe","shortMonthLookup","formats","formatShortWeekday","formatWeekday","formatShortMonth","formatMonth","formatDayOfMonth","formatMicroseconds","formatYearISO","formatFullYearISO","formatHour24","formatHour12","formatDayOfYear","formatMilliseconds","formatMonthNumber","formatMinutes","formatPeriod","formatQuarter","formatUnixTimestamp","formatUnixTimestampSeconds","formatSeconds","formatWeekdayNumberMonday","formatWeekNumberSunday","formatWeekNumberISO","formatWeekdayNumberSunday","formatWeekNumberMonday","formatYear","formatFullYear","formatZone","formatLiteralPercent","utcFormats","formatUTCShortWeekday","formatUTCWeekday","formatUTCShortMonth","formatUTCMonth","formatUTCDayOfMonth","formatUTCMicroseconds","formatUTCYearISO","formatUTCFullYearISO","formatUTCHour24","formatUTCHour12","formatUTCDayOfYear","formatUTCMilliseconds","formatUTCMonthNumber","formatUTCMinutes","formatUTCPeriod","formatUTCQuarter","formatUTCSeconds","formatUTCWeekdayNumberMonday","formatUTCWeekNumberSunday","formatUTCWeekNumberISO","formatUTCWeekdayNumberSunday","formatUTCWeekNumberMonday","formatUTCYear","formatUTCFullYear","formatUTCZone","parses","parseShortWeekday","parseWeekday","parseShortMonth","parseMonth","parseLocaleDateTime","parseDayOfMonth","parseMicroseconds","parseYear","parseFullYear","parseHour24","parseDayOfYear","parseMilliseconds","parseMonthNumber","parseMinutes","parsePeriod","parseQuarter","parseUnixTimestamp","parseUnixTimestampSeconds","parseSeconds","parseWeekdayNumberMonday","parseWeekNumberSunday","parseWeekNumberISO","parseWeekdayNumberSunday","parseWeekNumberMonday","parseLocaleDate","parseLocaleTime","parseZone","parseLiteralPercent","newFormat","specifier","string","i","j","n","c","pad","format","pads","newParse","Z","parseSpecifier","week","day","utcMonday","utcDay","timeMonday","timeDay","parse","f","p","numberRe","percentRe","requoteRe","value","fill","width","sign","length","requote","s","names","name","timeYear","timeSunday","dISO","timeThursday","z","utcYear","dow","utcSunday","UTCdISO","utcThursday","locale","timeFormat","timeParse","utcFormat","utcParse","defaultLocale","definition","formatLocale","transformer","x0","x1","t0","t1","k10","transform","interpolator","identity","clamp","unknown","scale","x","_","range","interpolate","r0","r1","value_default","round_default","t","copy","source","target","sequential","linearish","initInterpolator","sequentialPow","scale","powish","transformer","copy","initInterpolator","DEFAULT_OUTLINE_COLOR","DEFAULT_DIMMED_OPACITY","DEFAULT_FLOW_MIN_COLOR","DEFAULT_FLOW_COLOR_SCHEME","DEFAULT_LOCATION_AREA_COLOR","DEFAULT_FLOW_COLOR_SCHEME_POSITIVE","DEFAULT_FLOW_COLOR_SCHEME_NEGATIVE","FALLBACK_COLOR_RGBA","opacityFloatToInteger","opacity","opacifyHex","hexCode","c","color","col","colorAsRgba","rgbColor","colorAsRgbaOr","defaultColor","asScheme","scheme","ColorScheme","SCALE_NUM_STEPS","getColorSteps","interpolate","range","i","FLOW_MIN_COLOR","GRAYISH","schemeBluYl","schemeEmrld","schemeTeal","DEFAULT_COLOR_SCHEME","COLOR_SCHEMES","cool","inferno","magma","plasma","viridis_default","warm","COLOR_SCHEME_KEYS","complementary","baseDiffColor","diffColors","getFlowmapColors","settings","getColors","isAnimatedFlowLinesMode","flowLinesRenderingMode","diffMode","colorScheme","darkMode","fadeEnabled","fadeOpacityEnabled","fadeAmount","animate","indices","N","colorScale","sequential","rgbBasis","amount","pow","a","hcl","interpolateRgbaBasis","colors","spline","basis_default","n","r","g","b","rgb","t","createFlowColorScale","domain","scale","sequentialPow","value","getFlowColorScale","magnitudeExtent","minMagnitude","maxMagnitude","isDiffColorsRGBA","posScale","negScale","magnitude","isDiffColors","getLocationAreaColorsRGBA","normalColor","normalColorHcl","locationAreasNormal","getFlowAndCircleColors","inputColors","defaultFlowColorScheme","flowColorScheme","maxFlowColorHcl","flowColorHighlighted","emptyColor","innerColor","getBaseColorsRGBA","getColorsRGBA","baseColorsRGBA","getDiffColorsRGBA","colors_default","getColors","ARRAY_TYPES","VERSION","HEADER_SIZE","STACK","KDBush","_KDBush","data","magic","versionAndType","version","ArrayType","nodeSize","numItems","ArrayBufferType","arrayTypeIndex","coordsByteSize","idsByteSize","padCoords","x","y","index","numAdded","sort","minX","minY","maxX","maxY","ids","coords","sp","result","axis","right","left","i","m","qx","qy","r","out","count","r2","sqDist","select","k","n","z","s","sd","newLeft","newRight","t","j","swapItem","swap","arr","tmp","ax","ay","bx","by","dx","dy","NOT_FOUND","assertIsFunction","func","errorMessage","assertIsArrayOfFunctions","array","errorMessage","item","itemTypes","ensureIsArray","getDependencies","createSelectorArgs","dependencies","collectInputSelectorResults","inputSelectorArgs","inputSelectorResults","length","i","createSingletonCache","equals","entry","key","NOT_FOUND","value","createLruCache","maxSize","entries","get","cacheIndex","put","getEntries","clear","referenceEqualityCheck","a","b","createCacheKeyComparator","equalityCheck","prev","next","length","i","lruMemoize","func","equalityCheckOrOptions","providedOptions","resultEqualityCheck","comparator","resultsCount","cache","memoized","matchingEntry","StrongRef","value","getWeakRef","Ref","UNTERMINATED","TERMINATED","createCacheNode","maybeDeref","r","weakMapMemoize","func","options","fnNode","resultEqualityCheck","lastResult","resultsCount","memoized","cacheNode","length","i","l","arg","objectCache","objectNode","primitiveCache","primitiveNode","terminatedNode","result","lastResultValue","createSelectorCreator","memoizeOrOptions","memoizeOptionsFromArgs","createSelectorCreatorOptions","createSelector","createSelectorArgs","recomputations","dependencyRecomputations","directlyPassedOptions","resultFunc","assertIsFunction","combinedOptions","memoize","memoizeOptions","argsMemoize","argsMemoizeOptions","finalMemoizeOptions","ensureIsArray","finalArgsMemoizeOptions","dependencies","getDependencies","memoizedResultFunc","firstRun","selector","inputSelectorResults","collectInputSelectorResults","import_seedrandom","FlowmapAggregateAccessors","accessors","location","isLocationClusterNode","name","isCluster","f","isAggregateFlow","getFlowTime","buildIndex","clusterLevels","nodesByZoom","clustersById","minZoomByLocationId","zoom","nodes","node","isCluster","id","mz","minZoom","maxZoom","extent","cl","leavesToClustersByZoom","cluster","leavesToClusters","visitClusterLeaves","leafId","visit","childId","child","expandCluster","targetZoom","ids","c","expandedIds","findClusterFor","locationId","a","b","ascending","clusterId","flows","getFlowOriginId","getFlowDestId","getFlowMagnitude","options","result","aggFlowsByKey","makeKey","origin","dest","flowCountsMapReduce","acc","count","flow","originCluster","destCluster","key","aggregateFlow","makeLocationWeightGetter","locationTotals","findAppropriateZoomLevel","availableZoomLevels","bisectLeft","defaultOptions","id","numPoints","isLeafPoint","p","index","isClusterPoint","clusterLocations","locations","locationAccessors","getLocationWeight","options","getLocationLon","getLocationLat","getLocationId","opts","minZoom","maxZoom","nodeSize","makeClusterName","makeClusterId","trees","clusters","locationsCount","location","x","y","lngX","latY","makeBush","points","bush","KDBush","i","prevZoom","z","_clusters","cluster","numbersOfClusters","d","minClusters","min","maxAvailZoom","findIndexOfMax","numUniqueLocations","countUniqueLocations","maxClustersZoom","findLastIndex","minAvailZoom","clusterLevels","zoom","childrenByParent","tree","rollup","point","nodes","children","yLat","xLng","createCluster","weight","radius","extent","r","neighborIds","wx","wy","neighborId","b","weight2","numPoints2","y2","lng","lat","sin","countUniqueLocations","locations","locationAccessors","getLocationLon","getLocationLat","countByLatLon","uniqueCnt","loc","lon","lat","key","prev","findIndexOfMax","arr","max","maxIndex","value","findLastIndex","predicate","i","getViewportBoundingBox","viewport","maxLocationCircleSize","pad","bounds","WebMercatorViewport","getFlowThicknessScale","magnitudeExtent","linear","x","addClusterNames","clusterIndex","clusterLevels","locationsById","locationAccessors","getLocationWeight","getLocationId","getLocationName","getLocationClusterName","getName","id","loc","level","node","isCluster","leaves","a","b","descending","topId","otherId","dateParsers","timeParse","TimeGranularityKey","formatMillisecond","timeFormat","formatSecond","formatMinute","formatHour","formatDay","formatWeek","formatMonth","formatYear","TIME_GRANULARITIES","TimeGranularityKey","second","formatSecond","timeFormat","timeMinute","formatMinute","timeHour","formatHour","timeDay","formatDay","timeMonth","formatMonth","timeYear","formatYear","getTimeGranularityByKey","key","s","getTimeGranularityByOrder","order","getTimeGranularityForDate","date","prev","current","interval","MAX_CLUSTER_ZOOM_LEVEL","FlowmapSelectors","accessors","state","props","createSelector","flowLinesRenderingMode","locations","invalid","location","id","lon","lat","invalidIds","filtered","ids","flows","flow","srcId","dstId","a","b","descending","start","end","time","timeExtent","minOrder","min","d","t","getTimeGranularityForDate","timeGranularity","getTimeGranularityByOrder","timeGranularityKey","getTimeGranularityByKey","interval","timeRange","timeRanges","selectedRanges","range","withFlows","locationsById","makeLocationWeightGetter","clusterLevelsFromProps","getLocationWeight","clusterLocations","clusterLevels","clusterIndex","buildIndex","addClusterNames","selectedLocations","maxZoom","zoneId","cluster","minZoom","zoom","adjust","level","mapZoom","availableClusterZoomLevels","findAppropriateZoomLevel","settings","clusteringEnabled","clusterZoom","result","isLocationClusterNode","toAppend","f","colors_default","flowmapColors","isDiffColors","getDiffColorsRGBA","getColorsRGBA","flowsForKnownLocations","missing","clusterTree","isClusteringEnabled","aggregated","aggregateFlows","temporalScaleDomain","allFlows","selectedFlows","locationId","expanded","selectedLocationSet","locationFilterMode","byTime","m","key","millis","count","locationTotalsEnabled","getViewportBoundingBox","locationsHavingFlows","selectedLocationsSet","rv","totals","originId","destId","add","nodes","KDBush","i","node","lngX","latY","tree","bbox","idx","createSelectorCreator","lruMemoize","s1","s2","item","locationIds","locationTotals","calcLocationTotalsExtent","locationsInViewport","locationIdsInViewport","maxTopFlowsDisplayNum","flowEndpointsInViewportMode","picked","origin","dest","originInView","destInView","pickedCount","extent","total","getFlowThicknessScale","maxLocationCircleSize","locationTotalsExtent","sqrt","x","circleSizeScale","getInCircleSize","getOutCircleSize","idA","idB","ascending","flowThicknessScale","flowMagnitudeExtent","viewport","locationLabelsEnabled","FlowmapAggregateAccessors","getFlowOriginId","getFlowDestId","getFlowMagnitude","getLocationId","getLocationLon","getLocationLat","getLocationName","getFlowColorScale","circleColor","isDiffColorsRGBA","circleColors","inCircleRadii","outCircleRadii","loc","thicknesses","flowLineColors","flowColorScale","staggeringValues","curveOffsets","calculateCurveOffsets","circlePositions","sourcePositions","targetPositions","endpointOffsets","lon1","lat1","lon2","lat2","x1","y1","x2","y2","LocationFilterMode","incomingCount","outgoingCount","internalCount","lo","hi","sin","y","flowAccessors","byOriginDest","rollup","ff","values","value","getOuterCircleRadiusByIndex","circleAttributes","index","getInRadius","getOutRadius","getPosition","offset","getFlowLineAttributesByIndex","lineAttributes","getColor","getCurveOffset","getEndpointOffsets","getSourcePosition","getTargetPosition","getThickness","getStaggering","corridorBuckets","worldScale","sourceLon","sourceLat","targetLat","sx","sy","tx","targetLon","ty","corridorSourceX","corridorSourceY","corridorTargetX","corridorTargetY","dx","dy","chordLengthPx","angle","epsilon","pi","halfPi","quarterPi","tau","degrees","radians","abs","atan2","cos","sin","sqrt","asin","x","halfPi","noop","streamGeometry","geometry","stream","streamGeometryType","streamObjectType","object","features","coordinates","streamLine","streamPolygon","geometries","closed","coordinate","i","n","stream_default","areaRingSum","Adder","areaSum","lambda00","phi00","lambda0","cosPhi0","sinPhi0","areaStream","noop","areaRingStart","areaRingEnd","areaRing","tau","areaPointFirst","areaPoint","lambda","phi","radians","cos","quarterPi","sin","dLambda","sdLambda","adLambda","cosPhi","sinPhi","k","u","v","atan2","spherical","cartesian","atan2","asin","lambda","phi","cosPhi","cos","sin","cartesianCross","a","b","cartesianNormalizeInPlace","d","l","sqrt","lambda0","phi0","lambda1","phi1","lambda2","lambda00","phi00","p0","deltaSum","ranges","range","boundsStream","boundsPoint","boundsLineStart","boundsLineEnd","boundsRingPoint","boundsRingStart","boundsRingEnd","Adder","areaStream","areaRingSum","epsilon","lambda","phi","linePoint","p","cartesian","radians","normal","cartesianCross","equatorial","inflection","cartesianNormalizeInPlace","spherical","delta","sign","lambdai","degrees","phii","antimeridian","abs","angle","rangeCompare","a","b","rangeContains","x","bounds_default","feature","i","n","merged","deltaMax","stream_default","getViewStateForFeatures","featureCollection","size","opts","pad","maxZoom","bounds","bounds_default","x1","y1","x2","y2","paddedBounds","width","height","fitBounds","getViewStateForLocations","locations","getLocationCoords","asGeometry","location","geometries","isFlowmapData","data","isFlowmapDataProvider","dataProvider","LocalFlowmapDataProvider","accessors","FlowmapSelectors","flowmapData","flowmapState","idx","id","clusterIndex","cluster","dims","opts","getViewStateForLocations","loc","setLayersData","PickingType","PROPS_TO_CAUSE_LAYER_DATA_UPDATE","DEFAULT_FLOW_LINES_RENDERING_MODE","HighlightType","FlowmapLayer","_FlowmapLayer","composite_layer_default","props","info","event","startTime","onHover","onClick","FlowmapAggregateAccessors","object","data","dataProvider","isFlowmapDataProvider","isFlowmapData","LocalFlowmapDataProvider","params","changeFlags","oldProps","prop","layersData","defaults","locationsEnabled","locationTotalsEnabled","locationLabelsEnabled","adaptiveScalesEnabled","flowLinesRenderingMode","clusteringEnabled","clusteringLevel","fadeEnabled","fadeOpacityEnabled","clusteringAuto","darkMode","fadeAmount","colorScheme","highlightColor","temporalScaleDomain","maxTopFlowsDisplayNum","flowEndpointsInViewportMode","animationEnabled","pickViewportProps","index","sourceLayer","accessors","commonInfo","FlowLinesLayer_default","AnimatedFlowLinesLayer_default","CurvedFlowLinesLayer_default","flow","origin","dest","PickingType","FlowCirclesLayer_default","location","id","name","totals","circleAttributes","circleRadius","getOuterCircleRadiusByIndex","lineAttributes","attrs","getFlowLineAttributesByIndex","getLocationCoordsByIndex","flowLineThicknessScale","flowLineCurviness","layers","highlightedObject","locationLabels","flowmapColors","getFlowmapColors","outlineColor","colorAsRgba","commonLineLayerProps","scatterplot_layer_default","d","text_layer_default","FlowmapLayer_default","viewport","width","height","longitude","latitude","zoom","pitch","bearing","deck_default","FlowmapLayer_default","MapboxOverlay"]} diff --git a/inst/htmlwidgets/lib/flowmap-gl/flowmap-gl-vendor-manifest.json b/inst/htmlwidgets/lib/flowmap-gl/flowmap-gl-vendor-manifest.json new file mode 100644 index 0000000..5f264b2 --- /dev/null +++ b/inst/htmlwidgets/lib/flowmap-gl/flowmap-gl-vendor-manifest.json @@ -0,0 +1,764 @@ +{ + "schemaVersion": 1, + "source": "npm release packages", + "build": { + "command": "data-raw/flowmap-vendor/build-flowmap.sh build", + "node": "v26.0.0", + "npm": "11.14.1", + "esbuild": "0.28.0" + }, + "bundle": { + "path": "inst/htmlwidgets/lib/flowmap-gl/flowmap-gl-bundle.min.js", + "sha256": "6ee7d9f48276e5ff94a81333b8006590e7a3dba9cdb26c8802a9adf61a380fda", + "bytes": 811231 + }, + "patches": [ + { + "path": "data-raw/flowmap-vendor/patches/flowmap-temporal-scale-domain.patch", + "sha256": "4643c406fdd4c82175f5cbda27d414d5b1e65b08d7270b98eef9b3dc1045b7e7", + "bytes": 19025, + "purpose": "Add temporalScaleDomain so temporal flow width/color domains can use selected-time or all-time flows." + } + ], + "copyrights": { + "path": "LICENSE.note" + }, + "colorSchemes": { + "source": "FlowMapGL 9.3.0 vendored bundle", + "names": [ + "Blues", + "BluGrn", + "BluYl", + "BrwnYl", + "BuGn", + "BuPu", + "Burg", + "BurgYl", + "Cool", + "DarkMint", + "Emrld", + "GnBu", + "Grayish", + "Greens", + "Greys", + "Inferno", + "Magenta", + "Magma", + "Mint", + "Oranges", + "OrRd", + "OrYel", + "Peach", + "Plasma", + "PinkYl", + "PuBu", + "PuBuGn", + "PuRd", + "Purp", + "Purples", + "PurpOr", + "RdPu", + "RedOr", + "Reds", + "Sunset", + "SunsetDark", + "Teal", + "TealGrn", + "Viridis", + "Warm", + "YlGn", + "YlGnBu", + "YlOrBr", + "YlOrRd" + ] + }, + "directDependencies": [ + { + "name": "@deck.gl/core", + "version": "9.3.2", + "license": "MIT", + "integrity": "sha512-32Va3np0Zdlz/LBNtDWCs4EkKqdHmXcbGmVp4+7i1Cpdza8y8CFmJs2VPOmSX1fwHvNCGkAZV/SFZOfDb2INsg==", + "resolved": "https://registry.npmjs.org/@deck.gl/core/-/core-9.3.2.tgz", + "gitHead": "09af8de8d18a9cb9a31d064cae8f9e7239df7f53", + "homepage": null, + "repository": "https://github.com/visgl/deck.gl.git" + }, + { + "name": "@deck.gl/layers", + "version": "9.3.2", + "license": "MIT", + "integrity": "sha512-TeVfhQ/cQU1oTlTn16mCp7268d1uBJ6dwfgmKXThe2TzW9hql3iJaxbYTKg2phDg5YSiGmeEOpXbeBh59jyUcA==", + "resolved": "https://registry.npmjs.org/@deck.gl/layers/-/layers-9.3.2.tgz", + "gitHead": "09af8de8d18a9cb9a31d064cae8f9e7239df7f53", + "homepage": null, + "repository": "https://github.com/visgl/deck.gl.git" + }, + { + "name": "@deck.gl/mapbox", + "version": "9.3.2", + "license": "MIT", + "integrity": "sha512-+T9pJwsOXwjUxyGN6oiBMfIs28VtDIG1V1Rqz4qqn4TjjNEFFw+xO0olJIg8FO5IAqw2OtePdsrMj0tX8tHdGQ==", + "resolved": "https://registry.npmjs.org/@deck.gl/mapbox/-/mapbox-9.3.2.tgz", + "gitHead": "09af8de8d18a9cb9a31d064cae8f9e7239df7f53", + "homepage": null, + "repository": "https://github.com/visgl/deck.gl.git" + }, + { + "name": "@flowmap.gl/data", + "version": "9.3.0", + "license": "Apache-2.0", + "integrity": "sha512-1a4EZJdK13q5Mj3bVurFSpuYVBLSaByJJ9B4LMd7XvuD/ovB6JArDjdJetsA9jVHdA89lZli7f8ALX+oek+WtA==", + "resolved": "https://registry.npmjs.org/@flowmap.gl/data/-/data-9.3.0.tgz", + "gitHead": "ed581e11ca674ed1e17457a9526c864f8def678b", + "homepage": null, + "repository": "git@github.com:visgl/flowmap.gl.git" + }, + { + "name": "@flowmap.gl/layers", + "version": "9.3.0", + "license": "Apache-2.0", + "integrity": "sha512-kARLb28BYK58O4iuiZK0IdNO+W1EX4+MaLbufRU1O0LTMM0Aoe2lET7y4QcrOifQT0dV6cAjzjw4GDnbogOxJg==", + "resolved": "https://registry.npmjs.org/@flowmap.gl/layers/-/layers-9.3.0.tgz", + "gitHead": "ed581e11ca674ed1e17457a9526c864f8def678b", + "homepage": null, + "repository": "git@github.com:visgl/flowmap.gl.git" + }, + { + "name": "@luma.gl/core", + "version": "9.3.3", + "license": "MIT", + "integrity": "sha512-jCFm2htvrVpcXIy85TBTF1ROgMfknKnfw2OH+Vydr41hiCFd6nqr79gM3f2uhaNkal0BghFNqF3qDioKiUWtew==", + "resolved": "https://registry.npmjs.org/@luma.gl/core/-/core-9.3.3.tgz", + "gitHead": "1069000732d3dd5ba6e41f9ad958a7f274125ef4", + "homepage": null, + "repository": "https://github.com/visgl/luma.gl" + }, + { + "name": "@luma.gl/engine", + "version": "9.3.3", + "license": "MIT", + "integrity": "sha512-StmMTzUcUlpKMU3wvWU48A6OQyphptD9zVGBsSkK6iHIBdtBKlOcmqRkyfvRouo8JHtlrnoJDHLVKhxorwhGAg==", + "resolved": "https://registry.npmjs.org/@luma.gl/engine/-/engine-9.3.3.tgz", + "gitHead": "1069000732d3dd5ba6e41f9ad958a7f274125ef4", + "homepage": null, + "repository": "https://github.com/visgl/luma.gl" + }, + { + "name": "@luma.gl/shadertools", + "version": "9.3.3", + "license": "MIT", + "integrity": "sha512-4ZfG4/Utix951vqyiG/JIx+Eg+GMNwOxgr/07/i0gf7bK1gJZIEQ5BxVcDw4MCQfdoVlGPGzl0cQKbdqBvaCAQ==", + "resolved": "https://registry.npmjs.org/@luma.gl/shadertools/-/shadertools-9.3.3.tgz", + "gitHead": "1069000732d3dd5ba6e41f9ad958a7f274125ef4", + "homepage": null, + "repository": "https://github.com/visgl/luma.gl" + }, + { + "name": "esbuild", + "version": "0.28.0", + "license": "MIT", + "integrity": "sha512-sNR9MHpXSUV/XB4zmsFKN+QgVG82Cc7+/aaxJ8Adi8hyOac+EXptIp45QBPaVyX3N70664wRbTcLTOemCAnyqw==", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.0.tgz", + "gitHead": null, + "homepage": null, + "repository": "git+https://github.com/evanw/esbuild.git" + } + ], + "transitiveDependencies": [ + { + "name": "@esbuild/darwin-arm64", + "version": "0.28.0", + "license": "MIT", + "integrity": "sha512-0T+A9WZm+bZ84nZBtk1ckYsOvyA3x7e2Acj1KdVfV4/2tdG4fzUp91YHx+GArWLtwqp77pBXVCPn2We7Letr0Q==", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.0.tgz", + "gitHead": null, + "homepage": null, + "repository": "git+https://github.com/evanw/esbuild.git" + }, + { + "name": "@loaders.gl/core", + "version": "4.4.2", + "license": "MIT", + "integrity": "sha512-DZmsTwxdKh3q+mS1vSOW2EXFgwxZ4nIBte4H5g6e4VyQoQ6jAOkk0M6V+Asgy/eqjGTNjhfBA1HIkyBl0A9hcA==", + "resolved": "https://registry.npmjs.org/@loaders.gl/core/-/core-4.4.2.tgz", + "gitHead": "1c9649781db0403dbf7c3f1224bbeec77bd812eb", + "homepage": null, + "repository": "https://github.com/visgl/loaders.gl" + }, + { + "name": "@loaders.gl/images", + "version": "4.4.2", + "license": "MIT", + "integrity": "sha512-b+1keNvPlyLniWtX4ZaThz2dF2aohi8Q+OEsDF2hJNZYyZJOqP9b/72UhlVk+inxTJfTLRBNARs2TJ2ssBlelg==", + "resolved": "https://registry.npmjs.org/@loaders.gl/images/-/images-4.4.2.tgz", + "gitHead": "1c9649781db0403dbf7c3f1224bbeec77bd812eb", + "homepage": null, + "repository": "https://github.com/visgl/loaders.gl" + }, + { + "name": "@loaders.gl/loader-utils", + "version": "4.4.2", + "license": "MIT", + "integrity": "sha512-kqwBbyRC7rrQVsnJyKeoaig9hxaa5oj91OKqWm27HPuVn4q2dD67SEhiG0ND62eRp0tLY6jTqEcI5kDzHBZ6MA==", + "resolved": "https://registry.npmjs.org/@loaders.gl/loader-utils/-/loader-utils-4.4.2.tgz", + "gitHead": "1c9649781db0403dbf7c3f1224bbeec77bd812eb", + "homepage": null, + "repository": "https://github.com/visgl/loaders.gl" + }, + { + "name": "@loaders.gl/schema", + "version": "4.4.2", + "license": "MIT", + "integrity": "sha512-mJTZehTHIFl8ed+03nebuPAMnLP8Yp00DKTzCnKT2HNy/uV4+Sw+GrGIuhPHGU8tdQmtBXRURGM2ZxUAxMfGKg==", + "resolved": "https://registry.npmjs.org/@loaders.gl/schema/-/schema-4.4.2.tgz", + "gitHead": "1c9649781db0403dbf7c3f1224bbeec77bd812eb", + "homepage": null, + "repository": "https://github.com/visgl/loaders.gl" + }, + { + "name": "@loaders.gl/schema-utils", + "version": "4.4.2", + "license": "MIT", + "integrity": "sha512-yYYRD/POBEO72rhIyLASrqKUUhfIOQuFk/fgInN6Td2qvFgsHbo5UaCM4sTqVUWwNxNvXDQi8ezpbnCa/yi+OQ==", + "resolved": "https://registry.npmjs.org/@loaders.gl/schema-utils/-/schema-utils-4.4.2.tgz", + "gitHead": "1c9649781db0403dbf7c3f1224bbeec77bd812eb", + "homepage": null, + "repository": "https://github.com/visgl/loaders.gl" + }, + { + "name": "@loaders.gl/worker-utils", + "version": "4.4.2", + "license": "MIT", + "integrity": "sha512-oiZ0SoC1QKrOkhYPlVZ6Q06CtmuFRyZw2rwzmT08ZyaGtOArIJHDjlhxzwWiv+6fdws47Ub5uIGsdI1Ab1xYsA==", + "resolved": "https://registry.npmjs.org/@loaders.gl/worker-utils/-/worker-utils-4.4.2.tgz", + "gitHead": "1c9649781db0403dbf7c3f1224bbeec77bd812eb", + "homepage": null, + "repository": "https://github.com/visgl/loaders.gl" + }, + { + "name": "@luma.gl/webgl", + "version": "9.3.3", + "license": "MIT", + "integrity": "sha512-X+aavdP5o6VFHSA0es9gKZTT145jfcFbhKJt/gwJrptnKNoIW4+Y37ZEpCo1AzAnr+FQCxjgcM2kOCpoWMfSVA==", + "resolved": "https://registry.npmjs.org/@luma.gl/webgl/-/webgl-9.3.3.tgz", + "gitHead": "1069000732d3dd5ba6e41f9ad958a7f274125ef4", + "homepage": null, + "repository": "https://github.com/visgl/luma.gl" + }, + { + "name": "@mapbox/tiny-sdf", + "version": "2.2.0", + "license": "BSD-2-Clause", + "integrity": "sha512-LVL4wgI9YAum5V+LNVQO6QgFBPw7/MIIY4XJPNsPDMrjEwcE+JfKk1LuIl8GnF197ejVdC9QdPaxrx5gfgdGXg==", + "resolved": "https://registry.npmjs.org/@mapbox/tiny-sdf/-/tiny-sdf-2.2.0.tgz", + "gitHead": null, + "homepage": "https://github.com/mapbox/tiny-sdf#readme", + "repository": "git+https://github.com/mapbox/tiny-sdf.git" + }, + { + "name": "@math.gl/core", + "version": "4.1.0", + "license": "MIT", + "integrity": "sha512-FrdHBCVG3QdrworwrUSzXIaK+/9OCRLscxI2OUy6sLOHyHgBMyfnEGs99/m3KNvs+95BsnQLWklVfpKfQzfwKA==", + "resolved": "https://registry.npmjs.org/@math.gl/core/-/core-4.1.0.tgz", + "gitHead": "76820f54e2a9034b42bd24ffeb381cc4e01ad46e", + "homepage": null, + "repository": "https://github.com/visgl/math.gl.git" + }, + { + "name": "@math.gl/polygon", + "version": "4.1.0", + "license": "MIT", + "integrity": "sha512-YA/9PzaCRHbIP5/0E9uTYrqe+jsYTQoqoDWhf6/b0Ixz8bPZBaGDEafLg3z7ffBomZLacUty9U3TlPjqMtzPjA==", + "resolved": "https://registry.npmjs.org/@math.gl/polygon/-/polygon-4.1.0.tgz", + "gitHead": "76820f54e2a9034b42bd24ffeb381cc4e01ad46e", + "homepage": null, + "repository": "https://github.com/visgl/math.gl.git" + }, + { + "name": "@math.gl/sun", + "version": "4.1.0", + "license": "MIT", + "integrity": "sha512-i3q6OCBLSZ5wgZVhXg+X7gsjY/TUtuFW/2KBiq/U1ypLso3S4sEykoU/MGjxUv1xiiGtr+v8TeMbO1OBIh/HmA==", + "resolved": "https://registry.npmjs.org/@math.gl/sun/-/sun-4.1.0.tgz", + "gitHead": "76820f54e2a9034b42bd24ffeb381cc4e01ad46e", + "homepage": null, + "repository": "https://github.com/visgl/math.gl.git" + }, + { + "name": "@math.gl/types", + "version": "4.1.0", + "license": "MIT", + "integrity": "sha512-clYZdHcmRvMzVK5fjeDkQlHUzXQSNdZ7s4xOqC3nJPgz4C/TZkUecTo9YS4PruZqtDda/ag4erndP0MIn40dGA==", + "resolved": "https://registry.npmjs.org/@math.gl/types/-/types-4.1.0.tgz", + "gitHead": "76820f54e2a9034b42bd24ffeb381cc4e01ad46e", + "homepage": null, + "repository": "https://github.com/visgl/math.gl.git" + }, + { + "name": "@math.gl/web-mercator", + "version": "4.1.0", + "license": "MIT", + "integrity": "sha512-HZo3vO5GCMkXJThxRJ5/QYUYRr3XumfT8CzNNCwoJfinxy5NtKUd7dusNTXn7yJ40UoB8FMIwkVwNlqaiRZZAw==", + "resolved": "https://registry.npmjs.org/@math.gl/web-mercator/-/web-mercator-4.1.0.tgz", + "gitHead": "76820f54e2a9034b42bd24ffeb381cc4e01ad46e", + "homepage": null, + "repository": "https://github.com/visgl/math.gl.git" + }, + { + "name": "@probe.gl/env", + "version": "4.1.1", + "license": "MIT", + "integrity": "sha512-+68seNDMVsEegRB47pFA/Ws1Fjy8agcFYXxzorKToyPcD6zd+gZ5uhwoLd7TzsSw6Ydns//2KEszWn+EnNHTbA==", + "resolved": "https://registry.npmjs.org/@probe.gl/env/-/env-4.1.1.tgz", + "gitHead": "bd33a0cf48fe0bcc56941272e3a760d13df65b4e", + "homepage": null, + "repository": "https://github.com/visgl/probe.gl.git" + }, + { + "name": "@probe.gl/log", + "version": "4.1.1", + "license": "MIT", + "integrity": "sha512-kcZs9BT44pL7hS1OkRGKYRXI/SN9KejUlPD+BY40DguRLzdC5tLG/28WGMyfKdn/51GT4a0p+0P8xvDn1Ez+Kg==", + "resolved": "https://registry.npmjs.org/@probe.gl/log/-/log-4.1.1.tgz", + "gitHead": "bd33a0cf48fe0bcc56941272e3a760d13df65b4e", + "homepage": null, + "repository": "https://github.com/visgl/probe.gl.git" + }, + { + "name": "@probe.gl/stats", + "version": "4.1.1", + "license": "MIT", + "integrity": "sha512-4VpAyMHOqydSvPlEyHwXaE+AkIdR03nX+Qhlxsk2D/IW4OVmDZgIsvJB1cDzyEEtcfKcnaEbfXeiPgejBceT6g==", + "resolved": "https://registry.npmjs.org/@probe.gl/stats/-/stats-4.1.1.tgz", + "gitHead": "bd33a0cf48fe0bcc56941272e3a760d13df65b4e", + "homepage": null, + "repository": "https://github.com/visgl/probe.gl.git" + }, + { + "name": "@swc/helpers", + "version": "0.5.23", + "license": "Apache-2.0", + "integrity": "sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw==", + "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.23.tgz", + "gitHead": null, + "homepage": "https://swc.rs", + "repository": "git+https://github.com/swc-project/swc.git" + }, + { + "name": "@types/command-line-args", + "version": "5.2.3", + "license": "MIT", + "integrity": "sha512-uv0aG6R0Y8WHZLTamZwtfsDLVRnOa+n+n5rEvFWL5Na5gZ8V2Teab/duDPFzIIIhs9qizDpcavCusCLJZu62Kw==", + "resolved": "https://registry.npmjs.org/@types/command-line-args/-/command-line-args-5.2.3.tgz", + "gitHead": null, + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/command-line-args", + "repository": "https://github.com/DefinitelyTyped/DefinitelyTyped.git" + }, + { + "name": "@types/command-line-usage", + "version": "5.0.4", + "license": "MIT", + "integrity": "sha512-BwR5KP3Es/CSht0xqBcUXS3qCAUVXwpRKsV2+arxeb65atasuXG9LykC9Ab10Cw3s2raH92ZqOeILaQbsB2ACg==", + "resolved": "https://registry.npmjs.org/@types/command-line-usage/-/command-line-usage-5.0.4.tgz", + "gitHead": null, + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/command-line-usage", + "repository": "https://github.com/DefinitelyTyped/DefinitelyTyped.git" + }, + { + "name": "@types/geojson", + "version": "7946.0.16", + "license": "MIT", + "integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==", + "resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz", + "gitHead": null, + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/geojson", + "repository": "https://github.com/DefinitelyTyped/DefinitelyTyped.git" + }, + { + "name": "@types/node", + "version": "24.12.4", + "license": "MIT", + "integrity": "sha512-GUUEShf+PBCGW2KaXwcIt3Yk+e3pkKwWKb9GSyM9WQVE+ep2jzmHdGsHzu4wgcZy5fN9FBdVzjpBQsYlpfpgLA==", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.12.4.tgz", + "gitHead": null, + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node", + "repository": "https://github.com/DefinitelyTyped/DefinitelyTyped.git" + }, + { + "name": "@types/offscreencanvas", + "version": "2019.7.3", + "license": "MIT", + "integrity": "sha512-ieXiYmgSRXUDeOntE1InxjWyvEelZGP63M+cGuquuRLuIKKT1osnkXjxev9B7d1nXSug5vpunx+gNlbVxMlC9A==", + "resolved": "https://registry.npmjs.org/@types/offscreencanvas/-/offscreencanvas-2019.7.3.tgz", + "gitHead": null, + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/offscreencanvas", + "repository": "https://github.com/DefinitelyTyped/DefinitelyTyped.git" + }, + { + "name": "ansi-styles", + "version": "4.3.0", + "license": "MIT", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "gitHead": null, + "homepage": null, + "repository": "chalk/ansi-styles" + }, + { + "name": "apache-arrow", + "version": "21.1.0", + "license": "Apache-2.0", + "integrity": "sha512-kQrYLxhC+NTVVZ4CCzGF6L/uPVOzJmD1T3XgbiUnP7oTeVFOFgEUu6IKNwCDkpFoBVqDKQivlX4RUFqqnWFlEA==", + "resolved": "https://registry.npmjs.org/apache-arrow/-/apache-arrow-21.1.0.tgz", + "gitHead": null, + "homepage": "https://arrow.apache.org/js/", + "repository": "git+https://github.com/apache/arrow-js.git" + }, + { + "name": "array-back", + "version": "6.2.3", + "license": "MIT", + "integrity": "sha512-SGDvmg6QTYiTxCBkYVmThcoa67uLl35pyzRHdpCGBOcqFy6BtwnphoFPk7LhJshD+Yk1Kt35WGWeZPTgwR4Fhw==", + "resolved": "https://registry.npmjs.org/array-back/-/array-back-6.2.3.tgz", + "gitHead": null, + "homepage": null, + "repository": "git+https://github.com/75lb/array-back.git" + }, + { + "name": "chalk", + "version": "4.1.2", + "license": "MIT", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "gitHead": null, + "homepage": null, + "repository": "chalk/chalk" + }, + { + "name": "chalk-template", + "version": "0.4.0", + "license": "MIT", + "integrity": "sha512-/ghrgmhfY8RaSdeo43hNXxpoHAtxdbskUHjPpfqUWGttFgycUhYPGx3YZBCnUCvOa7Doivn1IZec3DEGFoMgLg==", + "resolved": "https://registry.npmjs.org/chalk-template/-/chalk-template-0.4.0.tgz", + "gitHead": null, + "homepage": null, + "repository": "chalk/chalk-template" + }, + { + "name": "color-convert", + "version": "2.0.1", + "license": "MIT", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "gitHead": null, + "homepage": null, + "repository": "Qix-/color-convert" + }, + { + "name": "color-name", + "version": "1.1.4", + "license": "MIT", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "gitHead": null, + "homepage": "https://github.com/colorjs/color-name", + "repository": "git@github.com:colorjs/color-name.git" + }, + { + "name": "command-line-args", + "version": "6.0.2", + "license": "MIT", + "integrity": "sha512-AIjYVxrV9X752LmPDLbVYv8aMCuHPSLZJXEo2qo/xJfv+NYhaZ4sMSF01rM+gHPaMgvPM0l5D/F+Qx+i2WfSmQ==", + "resolved": "https://registry.npmjs.org/command-line-args/-/command-line-args-6.0.2.tgz", + "gitHead": null, + "homepage": "https://github.com/75lb/command-line-args#readme", + "repository": "git+https://github.com/75lb/command-line-args.git" + }, + { + "name": "command-line-usage", + "version": "7.0.4", + "license": "MIT", + "integrity": "sha512-85UdvzTNx/+s5CkSgBm/0hzP80RFHAa7PsfeADE5ezZF3uHz3/Tqj9gIKGT9PTtpycc3Ua64T0oVulGfKxzfqg==", + "resolved": "https://registry.npmjs.org/command-line-usage/-/command-line-usage-7.0.4.tgz", + "gitHead": null, + "homepage": null, + "repository": "https://github.com/75lb/command-line-usage" + }, + { + "name": "d3-array", + "version": "3.2.4", + "license": "ISC", + "integrity": "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==", + "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz", + "gitHead": null, + "homepage": "https://d3js.org/d3-array/", + "repository": "https://github.com/d3/d3-array.git" + }, + { + "name": "d3-color", + "version": "3.1.0", + "license": "ISC", + "integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==", + "resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz", + "gitHead": null, + "homepage": "https://d3js.org/d3-color/", + "repository": "https://github.com/d3/d3-color.git" + }, + { + "name": "d3-format", + "version": "3.1.2", + "license": "ISC", + "integrity": "sha512-AJDdYOdnyRDV5b6ArilzCPPwc1ejkHcoyFarqlPqT7zRYjhavcT3uSrqcMvsgh2CgoPbK3RCwyHaVyxYcP2Arg==", + "resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.2.tgz", + "gitHead": null, + "homepage": "https://d3js.org/d3-format/", + "repository": "https://github.com/d3/d3-format.git" + }, + { + "name": "d3-geo", + "version": "3.1.1", + "license": "ISC", + "integrity": "sha512-637ln3gXKXOwhalDzinUgY83KzNWZRKbYubaG+fGVuc/dxO64RRljtCTnf5ecMyE1RIdtqpkVcq0IbtU2S8j2Q==", + "resolved": "https://registry.npmjs.org/d3-geo/-/d3-geo-3.1.1.tgz", + "gitHead": null, + "homepage": "https://d3js.org/d3-geo/", + "repository": "https://github.com/d3/d3-geo.git" + }, + { + "name": "d3-interpolate", + "version": "3.0.1", + "license": "ISC", + "integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==", + "resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz", + "gitHead": null, + "homepage": "https://d3js.org/d3-interpolate/", + "repository": "https://github.com/d3/d3-interpolate.git" + }, + { + "name": "d3-scale", + "version": "4.0.2", + "license": "ISC", + "integrity": "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==", + "resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.2.tgz", + "gitHead": null, + "homepage": "https://d3js.org/d3-scale/", + "repository": "https://github.com/d3/d3-scale.git" + }, + { + "name": "d3-scale-chromatic", + "version": "3.1.0", + "license": "ISC", + "integrity": "sha512-A3s5PWiZ9YCXFye1o246KoscMWqf8BsD9eRiJ3He7C9OBaxKhAd5TFCdEx/7VbKtxxTsu//1mMJFrEt572cEyQ==", + "resolved": "https://registry.npmjs.org/d3-scale-chromatic/-/d3-scale-chromatic-3.1.0.tgz", + "gitHead": null, + "homepage": "https://d3js.org/d3-scale-chromatic/", + "repository": "https://github.com/d3/d3-scale-chromatic.git" + }, + { + "name": "d3-time", + "version": "3.1.0", + "license": "ISC", + "integrity": "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==", + "resolved": "https://registry.npmjs.org/d3-time/-/d3-time-3.1.0.tgz", + "gitHead": null, + "homepage": "https://d3js.org/d3-time/", + "repository": "https://github.com/d3/d3-time.git" + }, + { + "name": "d3-time-format", + "version": "4.1.0", + "license": "ISC", + "integrity": "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==", + "resolved": "https://registry.npmjs.org/d3-time-format/-/d3-time-format-4.1.0.tgz", + "gitHead": null, + "homepage": "https://d3js.org/d3-time-format/", + "repository": "https://github.com/d3/d3-time-format.git" + }, + { + "name": "earcut", + "version": "2.2.4", + "license": "ISC", + "integrity": "sha512-/pjZsA1b4RPHbeWZQn66SWS8nZZWLQQ23oE3Eam7aroEFGEvwKAsJfZ9ytiEMycfzXWpca4FA9QIOehf7PocBQ==", + "resolved": "https://registry.npmjs.org/earcut/-/earcut-2.2.4.tgz", + "gitHead": null, + "homepage": null, + "repository": "git://github.com/mapbox/earcut.git" + }, + { + "name": "find-replace", + "version": "5.0.2", + "license": "MIT", + "integrity": "sha512-Y45BAiE3mz2QsrN2fb5QEtO4qb44NcS7en/0y9PEVsg351HsLeVclP8QPMH79Le9sH3rs5RSwJu99W0WPZO43Q==", + "resolved": "https://registry.npmjs.org/find-replace/-/find-replace-5.0.2.tgz", + "gitHead": null, + "homepage": null, + "repository": "git+https://github.com/75lb/find-replace.git" + }, + { + "name": "flatbuffers", + "version": "25.9.23", + "license": "Apache-2.0", + "integrity": "sha512-MI1qs7Lo4Syw0EOzUl0xjs2lsoeqFku44KpngfIduHBYvzm8h2+7K8YMQh1JtVVVrUvhLpNwqVi4DERegUJhPQ==", + "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-25.9.23.tgz", + "gitHead": null, + "homepage": "https://google.github.io/flatbuffers/", + "repository": "git+https://github.com/google/flatbuffers.git" + }, + { + "name": "gl-matrix", + "version": "3.4.4", + "license": "MIT", + "integrity": "sha512-latSnyDNt/8zYUB6VIJ6PCh2jBjJX6gnDsoCZ7LyW7GkqrD51EWwa9qCoGixj8YqBtETQK/xY7OmpTF8xz1DdQ==", + "resolved": "https://registry.npmjs.org/gl-matrix/-/gl-matrix-3.4.4.tgz", + "gitHead": null, + "homepage": "http://glmatrix.net", + "repository": "https://github.com/toji/gl-matrix.git" + }, + { + "name": "has-flag", + "version": "4.0.0", + "license": "MIT", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "gitHead": null, + "homepage": null, + "repository": "sindresorhus/has-flag" + }, + { + "name": "internmap", + "version": "2.0.3", + "license": "ISC", + "integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==", + "resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz", + "gitHead": null, + "homepage": "https://github.com/mbostock/internmap/", + "repository": "https://github.com/mbostock/internmap.git" + }, + { + "name": "json-bignum", + "version": "0.0.3", + "license": [ + { + "type": "MIT", + "url": "https://github.com/datalanche/json-bignum/raw/master/LICENSE" + } + ], + "integrity": "sha512-2WHyXj3OfHSgNyuzDbSxI1w2jgw5gkWSWhS7Qg4bWXx1nLk3jnbwfUeS0PSba3IzpTUWdHxBieELUzXRjQB2zg==", + "resolved": "https://registry.npmjs.org/json-bignum/-/json-bignum-0.0.3.tgz", + "gitHead": null, + "homepage": "https://github.com/datalanche/json-bignum", + "repository": "https://github.com/datalanche/json-bignum.git" + }, + { + "name": "kdbush", + "version": "4.1.0", + "license": "ISC", + "integrity": "sha512-e9vurzrXJQrFX6ckpHP3bvj5l+9CnYzkxDNnNQ1h2QTqdWsUAJgXiKdGNcOa1EY85dU8KbQ+z/FdQdB7P+9yfQ==", + "resolved": "https://registry.npmjs.org/kdbush/-/kdbush-4.1.0.tgz", + "gitHead": null, + "homepage": null, + "repository": "git://github.com/mourner/kdbush.git" + }, + { + "name": "lodash.camelcase", + "version": "4.3.0", + "license": "MIT", + "integrity": "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==", + "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", + "gitHead": null, + "homepage": "https://lodash.com/", + "repository": "lodash/lodash" + }, + { + "name": "mjolnir.js", + "version": "3.0.0", + "license": "MIT", + "integrity": "sha512-siX3YCG7N2HnmN1xMH3cK4JkUZJhbkhRFJL+G5N1vH0mh1t5088rJknIoqDFWDIU6NPGvRRgLnYW3ZHjSMEBLA==", + "resolved": "https://registry.npmjs.org/mjolnir.js/-/mjolnir.js-3.0.0.tgz", + "gitHead": null, + "homepage": null, + "repository": "https://github.com/visgl/mjolnir.js" + }, + { + "name": "reselect", + "version": "5.2.0", + "license": "MIT", + "integrity": "sha512-AgZ3UOZm3YndfrJ4OYjgrT7bmCm/1iqkjvEfH/oYjzh6PD2qw4QuT3jjnXIrpdt4MTpMXclMT3lXbmRY+XRakw==", + "resolved": "https://registry.npmjs.org/reselect/-/reselect-5.2.0.tgz", + "gitHead": null, + "homepage": null, + "repository": "https://github.com/reduxjs/reselect.git" + }, + { + "name": "seedrandom", + "version": "3.0.5", + "license": "MIT", + "integrity": "sha512-8OwmbklUNzwezjGInmZ+2clQmExQPvomqjL7LFqOYqtmuxRgQYqOD3mHaU+MvZn5FLUeVxVfQjwLZW/n/JFuqg==", + "resolved": "https://registry.npmjs.org/seedrandom/-/seedrandom-3.0.5.tgz", + "gitHead": null, + "homepage": "http://davidbau.com/archives/2010/01/30/random_seeds_coded_hints_and_quintillions.html", + "repository": "git://github.com/davidbau/seedrandom.git" + }, + { + "name": "supports-color", + "version": "7.2.0", + "license": "MIT", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "gitHead": null, + "homepage": null, + "repository": "chalk/supports-color" + }, + { + "name": "table-layout", + "version": "4.1.1", + "license": "MIT", + "integrity": "sha512-iK5/YhZxq5GO5z8wb0bY1317uDF3Zjpha0QFFLA8/trAoiLbQD0HUbMesEaxyzUgDxi2QlcbM8IvqOlEjgoXBA==", + "resolved": "https://registry.npmjs.org/table-layout/-/table-layout-4.1.1.tgz", + "gitHead": null, + "homepage": null, + "repository": "https://github.com/75lb/table-layout" + }, + { + "name": "tslib", + "version": "2.8.1", + "license": "0BSD", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "gitHead": null, + "homepage": "https://www.typescriptlang.org/", + "repository": "https://github.com/Microsoft/tslib.git" + }, + { + "name": "typical", + "version": "7.3.0", + "license": "MIT", + "integrity": "sha512-ya4mg/30vm+DOWfBg4YK3j2WD6TWtRkCbasOJr40CseYENzCUby/7rIvXA99JGsQHeNxLbnXdyLLxKSv3tauFw==", + "resolved": "https://registry.npmjs.org/typical/-/typical-7.3.0.tgz", + "gitHead": null, + "homepage": null, + "repository": "git+https://github.com/75lb/typical.git" + }, + { + "name": "undici-types", + "version": "7.16.0", + "license": "MIT", + "integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz", + "gitHead": null, + "homepage": "https://undici.nodejs.org", + "repository": "git+https://github.com/nodejs/undici.git" + }, + { + "name": "wordwrapjs", + "version": "5.1.1", + "license": "MIT", + "integrity": "sha512-0yweIbkINJodk27gX9LBGMzyQdBDan3s/dEAiwBOj+Mf0PPyWL6/rikalkv8EeD0E8jm4o5RXEOrFTP3NXbhJg==", + "resolved": "https://registry.npmjs.org/wordwrapjs/-/wordwrapjs-5.1.1.tgz", + "gitHead": null, + "homepage": null, + "repository": "https://github.com/75lb/wordwrapjs" + } + ] +} diff --git a/inst/htmlwidgets/lib/layer-tuner/layer-tuner.js b/inst/htmlwidgets/lib/layer-tuner/layer-tuner.js new file mode 100644 index 0000000..146e366 --- /dev/null +++ b/inst/htmlwidgets/lib/layer-tuner/layer-tuner.js @@ -0,0 +1,1018 @@ +(function() { + window.MapGLLayerTuner = { + init: function(map, x, el, HTMLWidgets) { + if (typeof lil === 'undefined') { + console.warn('lil-gui is not loaded. Layer tuner cannot be initialized.'); + return; + } + + if (map._layerTunerInitialized) return; + map._layerTunerInitialized = true; + + const config = x.layer_tuner || x || {}; + + const cssLength = function(value, fallback) { + if (value === null || value === undefined || value === '') return fallback; + if (typeof value === 'number') return `${value}px`; + return String(value); + }; + + const formatRValue = function(val) { + if (val === undefined || val === null) return 'NULL'; + if (typeof val === 'string') return `"${val}"`; + if (typeof val === 'boolean') return val ? 'TRUE' : 'FALSE'; + if (typeof val === 'number') return val; + if (Array.isArray(val)) return `c(${val.map(formatRValue).join(', ')})`; + return JSON.stringify(val); + }; + + const copyToClipboardFallback = function(text) { + return new Promise(function(resolve, reject) { + if (navigator.clipboard && window.isSecureContext) { + navigator.clipboard.writeText(text).then(resolve).catch(reject); + } else { + const textArea = document.createElement('textarea'); + textArea.value = text; + textArea.style.position = 'fixed'; textArea.style.top = '0'; textArea.style.left = '0'; textArea.style.opacity = '0'; + document.body.appendChild(textArea); + textArea.focus(); textArea.select(); + try { if (document.execCommand('copy')) resolve(); else reject(); } catch (err) { reject(err); } + document.body.removeChild(textArea); + } + }); + }; + + const getRName = function(type, prop) { + if (type === 'flowmap') { + if (prop === 'colorScheme') return 'flow_color_scheme'; + if (prop === 'darkMode') return 'flow_dark_mode'; + if (prop === 'opacity') return 'flow_opacity'; + if (prop === 'blendMode') return 'flow_blend'; + return 'flow_' + prop.replace(/([A-Z])/g, "_$1").toLowerCase(); + } + return prop.replace(/-/g, '_'); + }; + + const NAMED_COLORS = { + black: '#000000', + blue: '#0000ff', + cyan: '#00ffff', + gray: '#808080', + green: '#008000', + grey: '#808080', + orange: '#ffa500', + purple: '#800080', + red: '#ff0000', + transparent: '#000000', + white: '#ffffff', + yellow: '#ffff00' + }; + + const toTwoDigitHex = function(value) { + const numeric = Math.max(0, Math.min(255, Number(value))); + return Math.round(numeric).toString(16).padStart(2, '0'); + }; + + const normalizeColorValue = function(value, fallback) { + if (Array.isArray(value)) { + if (value.length >= 3) { + return '#' + value.slice(0, 3).map(toTwoDigitHex).join(''); + } + return fallback; + } + if (typeof value !== 'string') return fallback; + let trimmed = value.trim(); + const lower = trimmed.toLowerCase(); + + if (/^#[0-9a-f]{6}$/i.test(trimmed)) return trimmed; + if (/^#[0-9a-f]{3}$/i.test(trimmed)) { + return '#' + trimmed.slice(1).split('').map(function(ch) { + return ch + ch; + }).join(''); + } + if (/^[0-9a-f]{6}$/i.test(trimmed)) return '#' + trimmed; + if (/^[0-9a-f]{3}$/i.test(trimmed)) { + return '#' + trimmed.split('').map(function(ch) { + return ch + ch; + }).join(''); + } + + const rgbMatch = lower.match(/^rgba?\(([^)]+)\)$/); + if (rgbMatch) { + const parts = rgbMatch[1].split(',').map(function(part) { + return parseFloat(part.trim()); + }); + if (parts.length >= 3 && parts.slice(0, 3).every(Number.isFinite)) { + return '#' + parts.slice(0, 3).map(toTwoDigitHex).join(''); + } + } + + if (NAMED_COLORS[lower]) return NAMED_COLORS[lower]; + + try { + const ctx = document.createElement('canvas').getContext('2d'); + if (ctx) { + ctx.fillStyle = '#000000'; + ctx.fillStyle = trimmed; + const normalized = ctx.fillStyle; + if (/^#[0-9a-f]{6}$/i.test(normalized)) return normalized; + } + } catch (e) {} + + return fallback; + }; + + const getExpandedSliderBounds = function(spec, value) { + let min = spec.min; + let max = spec.max; + if (!Number.isFinite(value)) return { min: min, max: max }; + + const range = Math.max(Math.abs(max - min), spec.step || 1); + const padding = Math.max(range * 0.25, spec.step || 1); + if (value < min) min = value - padding; + if (value > max) max = value + padding; + + return { min: min, max: max }; + }; + + const expandSliderToValue = function(controller, value, spec) { + if (!controller || !Number.isFinite(value)) return; + const currentMin = controller._min; + const currentMax = controller._max; + if (!Number.isFinite(currentMin) || !Number.isFinite(currentMax)) return; + + const expanded = getExpandedSliderBounds( + { min: currentMin, max: currentMax, step: spec.step }, + value + ); + + if (expanded.min !== currentMin && typeof controller.min === 'function') { + controller.min(expanded.min); + } + if (expanded.max !== currentMax && typeof controller.max === 'function') { + controller.max(expanded.max); + } + }; + + const attachSliderAutoExpansion = function(controller, spec) { + if (!controller || spec.type !== 'slider') return; + const input = controller.domElement && + controller.domElement.querySelector && + controller.domElement.querySelector('input'); + if (!input) return; + + input.addEventListener('input', function() { + const value = parseFloat(input.value); + if (!Number.isFinite(value)) return; + expandSliderToValue(controller, value, spec); + if (controller.getValue && controller.getValue() !== value) { + controller.setValue(value); + } + }); + }; + + const TUNER_SCHEMA = { + 'fill': { + 'fill-antialias': { type: 'boolean', default: true, method: 'paint' }, + 'fill-color': { type: 'color', default: '#000000', method: 'paint' }, + 'fill-opacity': { type: 'slider', min: 0, max: 1, step: 0.05, default: 1, method: 'paint' }, + 'fill-outline-color': { type: 'color', default: '#000000', method: 'paint' }, + 'fill-emissive-strength': { type: 'slider', min: 0, max: 1, step: 0.05, default: 0, method: 'paint' }, + 'fill-sort-key': { type: 'slider', min: 0, max: 100, step: 1, default: 0, method: 'layout' } + }, + 'line': { + 'line-blur': { type: 'slider', min: 0, max: 20, step: 0.5, default: 0, method: 'paint' }, + 'line-cap': { type: 'select', options: ['butt', 'round', 'square'], default: 'butt', method: 'layout' }, + 'line-color': { type: 'color', default: '#000000', method: 'paint' }, + 'line-emissive-strength': { type: 'slider', min: 0, max: 1, step: 0.05, default: 0, method: 'paint' }, + 'line-gap-width': { type: 'slider', min: 0, max: 30, step: 0.5, default: 0, method: 'paint' }, + 'line-join': { type: 'select', options: ['bevel', 'miter', 'round'], default: 'miter', method: 'layout' }, + 'line-miter-limit': { type: 'slider', min: 0, max: 20, step: 0.5, default: 2, method: 'layout' }, + 'line-offset': { type: 'slider', min: -20, max: 20, step: 0.5, default: 0, method: 'paint' }, + 'line-opacity': { type: 'slider', min: 0, max: 1, step: 0.05, default: 1, method: 'paint' }, + 'line-round-limit': { type: 'slider', min: 0, max: 20, step: 0.5, default: 1, method: 'layout' }, + 'line-sort-key': { type: 'slider', min: 0, max: 100, step: 1, default: 0, method: 'layout' }, + 'line-width': { type: 'slider', min: 0, max: 20, step: 0.5, default: 1, method: 'paint' } + }, + 'circle': { + 'circle-blur': { type: 'slider', min: 0, max: 1, step: 0.05, default: 0, method: 'paint' }, + 'circle-color': { type: 'color', default: '#000000', method: 'paint' }, + 'circle-emissive-strength': { type: 'slider', min: 0, max: 1, step: 0.05, default: 0, method: 'paint' }, + 'circle-opacity': { type: 'slider', min: 0, max: 1, step: 0.05, default: 1, method: 'paint' }, + 'circle-pitch-alignment': { type: 'select', options: ['map', 'viewport'], default: 'viewport', method: 'paint' }, + 'circle-pitch-scale': { type: 'select', options: ['map', 'viewport'], default: 'map', method: 'paint' }, + 'circle-radius': { type: 'slider', min: 0, max: 50, step: 0.5, default: 5, method: 'paint' }, + 'circle-sort-key': { type: 'slider', min: 0, max: 100, step: 1, default: 0, method: 'layout' }, + 'circle-stroke-color': { type: 'color', default: '#000000', method: 'paint' }, + 'circle-stroke-opacity': { type: 'slider', min: 0, max: 1, step: 0.05, default: 1, method: 'paint' }, + 'circle-stroke-width': { type: 'slider', min: 0, max: 10, step: 0.5, default: 0, method: 'paint' }, + 'circle-translate': { type: 'text', default: '0,0', method: 'paint' } + }, + 'symbol': { + 'icon-allow-overlap': { type: 'boolean', default: false, method: 'layout' }, + 'icon-anchor': { type: 'select', options: ['center', 'left', 'right', 'top', 'bottom', 'top-left', 'top-right', 'bottom-left', 'bottom-right'], default: 'center', method: 'layout' }, + 'icon-color': { type: 'color', default: '#ffffff', method: 'paint' }, + 'icon-emissive-strength': { type: 'slider', min: 0, max: 1, step: 0.05, default: 0, method: 'paint' }, + 'icon-halo-blur': { type: 'slider', min: 0, max: 10, step: 0.5, default: 0, method: 'paint' }, + 'icon-halo-color': { type: 'color', default: '#000000', method: 'paint' }, + 'icon-halo-width': { type: 'slider', min: 0, max: 10, step: 0.5, default: 0, method: 'paint' }, + 'icon-ignore-placement': { type: 'boolean', default: false, method: 'layout' }, + 'icon-image': { type: 'text', default: '', method: 'layout' }, + 'icon-keep-upright': { type: 'boolean', default: false, method: 'layout' }, + 'icon-opacity': { type: 'slider', min: 0, max: 1, step: 0.05, default: 1, method: 'paint' }, + 'icon-optional': { type: 'boolean', default: false, method: 'layout' }, + 'icon-padding': { type: 'slider', min: 0, max: 50, step: 1, default: 2, method: 'layout' }, + 'icon-pitch-alignment': { type: 'select', options: ['map', 'viewport', 'auto'], default: 'auto', method: 'layout' }, + 'icon-rotate': { type: 'slider', min: 0, max: 360, step: 1, default: 0, method: 'layout' }, + 'icon-rotation-alignment': { type: 'select', options: ['map', 'viewport', 'auto'], default: 'auto', method: 'layout' }, + 'icon-size': { type: 'slider', min: 0.1, max: 5, step: 0.05, default: 1, method: 'layout' }, + 'text-allow-overlap': { type: 'boolean', default: false, method: 'layout' }, + 'text-anchor': { type: 'select', options: ['center', 'left', 'right', 'top', 'bottom', 'top-left', 'top-right', 'bottom-left', 'bottom-right'], default: 'center', method: 'layout' }, + 'text-color': { type: 'color', default: '#000000', method: 'paint' }, + 'text-emissive-strength': { type: 'slider', min: 0, max: 1, step: 0.05, default: 0, method: 'paint' }, + 'text-field': { type: 'text', default: '', method: 'layout' }, + 'text-halo-blur': { type: 'slider', min: 0, max: 10, step: 0.5, default: 0, method: 'paint' }, + 'text-halo-color': { type: 'color', default: '#000000', method: 'paint' }, + 'text-halo-width': { type: 'slider', min: 0, max: 10, step: 0.5, default: 0, method: 'paint' }, + 'text-ignore-placement': { type: 'boolean', default: false, method: 'layout' }, + 'text-justify': { type: 'select', options: ['auto', 'left', 'center', 'right'], default: 'auto', method: 'layout' }, + 'text-keep-upright': { type: 'boolean', default: true, method: 'layout' }, + 'text-letter-spacing': { type: 'slider', min: 0, max: 2, step: 0.05, default: 0, method: 'layout' }, + 'text-line-height': { type: 'slider', min: 0.5, max: 3, step: 0.1, default: 1.2, method: 'layout' }, + 'text-max-angle': { type: 'slider', min: 0, max: 360, step: 5, default: 45, method: 'layout' }, + 'text-max-width': { type: 'slider', min: 0, max: 50, step: 0.5, default: 10, method: 'layout' }, + 'text-opacity': { type: 'slider', min: 0, max: 1, step: 0.05, default: 1, method: 'paint' }, + 'text-padding': { type: 'slider', min: 0, max: 50, step: 1, default: 2, method: 'layout' }, + 'text-pitch-alignment': { type: 'select', options: ['map', 'viewport', 'auto'], default: 'auto', method: 'layout' }, + 'text-rotate': { type: 'slider', min: 0, max: 360, step: 1, default: 0, method: 'layout' }, + 'text-rotation-alignment': { type: 'select', options: ['map', 'viewport', 'auto'], default: 'auto', method: 'layout' }, + 'text-size': { type: 'slider', min: 4, max: 72, step: 1, default: 16, method: 'layout' }, + 'text-transform': { type: 'select', options: ['none', 'uppercase', 'lowercase'], default: 'none', method: 'layout' } + }, + 'heatmap': { + 'heatmap-weight': { type: 'slider', min: 0, max: 10, step: 0.1, default: 1, method: 'paint' }, + 'heatmap-intensity': { type: 'slider', min: 0, max: 10, step: 0.1, default: 1, method: 'paint' }, + 'heatmap-radius': { type: 'slider', min: 0, max: 100, step: 1, default: 30, method: 'paint' }, + 'heatmap-opacity': { type: 'slider', min: 0, max: 1, step: 0.05, default: 1, method: 'paint' } + }, + 'fill-extrusion': { + 'fill-extrusion-opacity': { type: 'slider', min: 0, max: 1, step: 0.05, default: 1, method: 'paint' }, + 'fill-extrusion-color': { type: 'color', default: '#000000', method: 'paint' }, + 'fill-extrusion-height': { type: 'slider', min: 0, max: 5000, step: 10, default: 0, method: 'paint' }, + 'fill-extrusion-base': { type: 'slider', min: 0, max: 5000, step: 10, default: 0, method: 'paint' }, + 'fill-extrusion-vertical-gradient': { type: 'boolean', default: true, method: 'paint' }, + 'fill-extrusion-emissive-strength': { type: 'slider', min: 0, max: 1, step: 0.05, default: 0, method: 'paint' } + }, + 'raster': { + 'raster-opacity': { type: 'slider', min: 0, max: 1, step: 0.05, default: 1, method: 'paint' }, + 'raster-hue-rotate': { type: 'slider', min: 0, max: 360, step: 1, default: 0, method: 'paint' }, + 'raster-brightness-min': { type: 'slider', min: 0, max: 1, step: 0.05, default: 0, method: 'paint' }, + 'raster-brightness-max': { type: 'slider', min: 0, max: 1, step: 0.05, default: 1, method: 'paint' }, + 'raster-saturation': { type: 'slider', min: -1, max: 1, step: 0.1, default: 0, method: 'paint' }, + 'raster-contrast': { type: 'slider', min: -1, max: 1, step: 0.1, default: 0, method: 'paint' }, + 'raster-resampling': { type: 'select', options: ['linear', 'nearest'], default: 'linear', method: 'paint' }, + 'raster-fade-duration': { type: 'slider', min: 0, max: 1000, step: 10, default: 300, method: 'paint' }, + 'raster-emissive-strength': { type: 'slider', min: 0, max: 1, step: 0.05, default: 0, method: 'paint' } + } + }; + + const gui = new lil.GUI({ title: config.title || 'Layer Tuner 🎨', container: el }); + map._layerTunerGui = gui; + + // 1. Initial styles + const dom = gui.domElement; + const initialWidth = cssLength(config.width, '245px'); + const initialHeight = cssLength(config.height, 'auto'); + const initialMaxHeight = config.height ? 'none' : 'calc(100% - 20px)'; + const initialPosition = config.position || 'top-left'; + const applyInitialLayout = function() { + dom.style.top = 'auto'; + dom.style.right = 'auto'; + dom.style.bottom = 'auto'; + dom.style.left = 'auto'; + if (initialPosition.includes('bottom')) dom.style.bottom = '10px'; + else dom.style.top = '10px'; + if (initialPosition.includes('right')) dom.style.right = '10px'; + else dom.style.left = '10px'; + dom.style.width = initialWidth; + dom.style.height = initialHeight; + dom.style.maxHeight = initialMaxHeight; + }; + dom.style.position = 'absolute'; dom.style.zIndex = '9999'; dom.style.display = 'flex'; dom.style.flexDirection = 'column'; + applyInitialLayout(); + + const children = dom.querySelector('.children'); + if (children) { children.style.flex = '1 1 auto'; children.style.overflowY = 'auto'; } + + // Resize handles + const corners = ['tl', 'tr', 'bl', 'br']; + let isResizing = false, hasBeenManuallyResized = false, manualWidth = initialWidth, manualHeight = initialHeight; + corners.forEach(c => { + const handle = document.createElement('div'); + handle.style.position = 'absolute'; handle.style.width = '12px'; handle.style.height = '12px'; handle.style.zIndex = '10001'; handle.style.background = 'transparent'; + if (c==='tl') { handle.style.top='-4px'; handle.style.left='-4px'; handle.style.cursor='nw-resize'; } + else if (c==='tr') { handle.style.top='-4px'; handle.style.right='-4px'; handle.style.cursor='ne-resize'; } + else if (c==='bl') { handle.style.bottom='-4px'; handle.style.left='-4px'; handle.style.cursor='sw-resize'; } + else if (c==='br') { + handle.style.bottom='-4px'; handle.style.right='-4px'; handle.style.cursor='se-resize'; + handle.innerHTML = '
'; + } + dom.appendChild(handle); + handle.onmousedown = (e) => { + isResizing = true; hasBeenManuallyResized = true; + dom.style.left = dom.offsetLeft + 'px'; dom.style.top = dom.offsetTop + 'px'; dom.style.right = 'auto'; dom.style.bottom = 'auto'; + const sw = dom.offsetWidth, sh = dom.offsetHeight, sx = e.clientX, sy = e.clientY, st = dom.offsetTop, sl = dom.offsetLeft; + const onMove = (me) => { + if (!isResizing) return; + const dx = me.clientX - sx, dy = me.clientY - sy; + if (c.includes('r')) dom.style.width = Math.max(180, sw + dx) + 'px'; + if (c.includes('l')) { const nw = Math.max(180, sw - dx); dom.style.width = nw + 'px'; dom.style.left = (sl + (sw - nw)) + 'px'; } + if (c.includes('b')) dom.style.height = Math.max(100, sh + dy) + 'px'; + if (c.includes('t')) { const nh = Math.max(100, sh - dy); dom.style.height = nh + 'px'; dom.style.top = (st + (sh - nh)) + 'px'; } + manualWidth = dom.style.width; manualHeight = dom.style.height; dom.style.maxHeight = 'none'; + }; + const onUp = () => { isResizing = false; window.removeEventListener('mousemove', onMove); window.removeEventListener('mouseup', onUp); }; + window.addEventListener('mousemove', onMove); window.addEventListener('mouseup', onUp); + e.preventDefault(); e.stopPropagation(); + }; + }); + + gui.onOpenClose(g => { + if (g === gui) { + if (gui._closed) { dom.style.height = 'auto'; dom.querySelectorAll('div').forEach(d => { if(d.style.cursor.includes('resize')) d.style.display='none'; }); } + else { + if (hasBeenManuallyResized) { dom.style.width = manualWidth; dom.style.height = manualHeight; dom.style.maxHeight = 'none'; } + else applyInitialLayout(); + dom.querySelectorAll('div').forEach(d => { if(d.style.cursor.includes('resize')) d.style.display='block'; }); + } + } + }); + + map._layerTunerChanges = {}; + const tunerState = { showMode: config.show_all_args ? 'All Options' : 'Customized', searchQuery: '', propSearchQuery: '' }; + const allLayerControllers = []; + const layerFolders = []; + const layerMeta = {}; // To store initial values for reset + const HISTORY_LIMIT = 1000; + const undoStack = []; + const redoStack = []; + let currentSnapshot = null; + let isApplyingHistory = false; + let undoButton = null; + let redoButton = null; + + const cloneHistoryValue = function(value) { + if (value === undefined || value === null) return value; + if (Array.isArray(value)) return value.map(cloneHistoryValue); + if (typeof value === 'object') { + const copy = {}; + Object.keys(value).forEach(function(key) { + copy[key] = cloneHistoryValue(value[key]); + }); + return copy; + } + return value; + }; + + const captureHistorySnapshot = function() { + const snapshot = { + layers: {}, + changes: cloneHistoryValue(map._layerTunerChanges || {}) + }; + + Object.keys(layerMeta).forEach(function(lid) { + const meta = layerMeta[lid]; + if (meta.type === 'flowmap') { + snapshot.layers[lid] = { + type: 'flowmap', + state: cloneHistoryValue(meta.state) + }; + return; + } + + const raw = {}; + Object.keys(TUNER_SCHEMA[meta.type]).forEach(function(p) { + const spec = TUNER_SCHEMA[meta.type][p]; + try { + raw[p] = spec.method === 'paint' ? + map.getPaintProperty(lid, p) : + map.getLayoutProperty(lid, p); + } catch (e) { + raw[p] = undefined; + } + }); + + snapshot.layers[lid] = { + type: meta.type, + state: cloneHistoryValue(meta.state), + raw: cloneHistoryValue(raw) + }; + }); + + return snapshot; + }; + + const updateHistoryButtons = function() { + if (undoButton) { + undoButton.disabled = undoStack.length === 0; + undoButton.style.opacity = undoButton.disabled ? '0.45' : '1'; + undoButton.style.cursor = undoButton.disabled ? 'default' : 'pointer'; + } + if (redoButton) { + redoButton.disabled = redoStack.length === 0; + redoButton.style.opacity = redoButton.disabled ? '0.45' : '1'; + redoButton.style.cursor = redoButton.disabled ? 'default' : 'pointer'; + } + }; + + const refreshCurrentSnapshot = function() { + currentSnapshot = captureHistorySnapshot(); + updateHistoryButtons(); + }; + + const recordHistory = function() { + if (isApplyingHistory || !currentSnapshot) return; + undoStack.push(cloneHistoryValue(currentSnapshot)); + if (undoStack.length > HISTORY_LIMIT) undoStack.shift(); + redoStack.length = 0; + updateHistoryButtons(); + }; + + const applyHistorySnapshot = function(snapshot) { + if (!snapshot) return; + isApplyingHistory = true; + try { + Object.keys(snapshot.layers).forEach(function(lid) { + const meta = layerMeta[lid]; + const layerSnapshot = snapshot.layers[lid]; + if (!meta || !layerSnapshot) return; + + if (meta.type === 'flowmap') { + Object.assign(meta.state, cloneHistoryValue(layerSnapshot.state)); + const current = map._mapglFlowmapLayers; + if (current && current[meta.idx]) { + const updated = current[meta.idx].clone({ + colorScheme: meta.state.colorScheme, + darkMode: meta.state.darkMode, + opacity: meta.state.opacity, + fadeAmount: meta.state.fadeAmount, + highlightColor: meta.state.highlightColor, + locationsEnabled: meta.state.locationsEnabled, + locationTotalsEnabled: meta.state.locationTotalsEnabled, + locationLabelsEnabled: meta.state.locationLabelsEnabled, + flowLinesRenderingMode: meta.state.flowLinesRenderingMode, + clusteringEnabled: meta.state.clusteringEnabled, + clusteringAuto: meta.state.clusteringAuto, + clusteringLevel: meta.state.clusteringAuto ? undefined : meta.state.clusteringLevel, + fadeEnabled: meta.state.fadeEnabled, + fadeOpacityEnabled: meta.state.fadeOpacityEnabled, + adaptiveScalesEnabled: meta.state.adaptiveScalesEnabled, + temporalScaleDomain: meta.state.temporalScaleDomain, + animationEnabled: meta.state.animationEnabled, + maxTopFlowsDisplayNum: meta.state.maxTopFlowsDisplayNum, + flowEndpointsInViewportMode: meta.state.flowEndpointsInViewportMode + }); + const newLayers = [...current]; + newLayers[meta.idx] = updated; + map._mapglFlowmapLayers = newLayers; + if (map._mapglFlowmapOverlay || map._deckgl) { + (map._mapglFlowmapOverlay || map._deckgl).setProps({ + layers: map._mapglFlowmapLayers + }); + } + } + if (map._deckCanvas) { + map._deckCanvas.style.mixBlendMode = meta.state.blendMode; + } + return; + } + + Object.keys(layerSnapshot.raw || {}).forEach(function(p) { + const spec = TUNER_SCHEMA[meta.type][p]; + const rawVal = layerSnapshot.raw[p] === undefined ? + null : + cloneHistoryValue(layerSnapshot.raw[p]); + try { + if (spec.method === 'paint') map.setPaintProperty(lid, p, rawVal); + else map.setLayoutProperty(lid, p, rawVal); + } catch (e) { + console.warn(`Layer Tuner: Failed applying history for ${lid}.${p}`, e); + } + }); + Object.assign(meta.state, cloneHistoryValue(layerSnapshot.state)); + }); + + map._layerTunerChanges = cloneHistoryValue(snapshot.changes || {}); + if (map.triggerRepaint) map.triggerRepaint(); + try { + gui.controllersRecursive().forEach(c => { + if (c && typeof c.updateDisplay === 'function') c.updateDisplay(); + }); + updateControllerVisibilities(); + } catch (e) { + console.error('Layer Tuner: Failed updating UI after history change', e); + } + } finally { + isApplyingHistory = false; + } + }; + + const undoHistory = function() { + if (undoStack.length === 0 || !currentSnapshot) return; + redoStack.push(cloneHistoryValue(currentSnapshot)); + const previous = undoStack.pop(); + applyHistorySnapshot(previous); + currentSnapshot = cloneHistoryValue(previous); + updateHistoryButtons(); + }; + + const redoHistory = function() { + if (redoStack.length === 0 || !currentSnapshot) return; + undoStack.push(cloneHistoryValue(currentSnapshot)); + if (undoStack.length > HISTORY_LIMIT) undoStack.shift(); + const next = redoStack.pop(); + applyHistorySnapshot(next); + currentSnapshot = cloneHistoryValue(next); + updateHistoryButtons(); + }; + + const updateControllerVisibilities = function() { + const showAll = tunerState.showMode === 'All Options'; + const propQuery = (tunerState.propSearchQuery || '').toLowerCase(); + allLayerControllers.forEach(function(meta) { + const rName = (meta.controller._name || '').toLowerCase(); + const propMatches = !propQuery || rName.includes(propQuery); + const isTuned = map._layerTunerChanges[meta.layerId] && map._layerTunerChanges[meta.layerId].props[meta.prop] !== undefined; + const logicVisible = showAll || meta.originallyPresent || meta.hasInStyle || isTuned; + if (propMatches && logicVisible) meta.controller.show(); else meta.controller.hide(); + }); + }; + + const updateFolderVisibilities = function() { + const query = (tunerState.searchQuery || '').toLowerCase(); + layerFolders.forEach(f => { const title = (f._title || '').toLowerCase(); if (!query || title.includes(query)) f.show(); else f.hide(); }); + }; + + const applyLayerControllerValue = function(layerId, layerType, prop, spec, value, options) { + const shouldRecord = !options || options.record !== false; + const shouldRefresh = !options || options.refresh !== false; + try { + if (shouldRecord) recordHistory(); + if (spec.method === 'paint') map.setPaintProperty(layerId, prop, value); + else map.setLayoutProperty(layerId, prop, value); + if (!map._layerTunerChanges[layerId]) { + map._layerTunerChanges[layerId] = { type: layerType, props: {} }; + } + map._layerTunerChanges[layerId].props[prop] = { + method: spec.method, + value: value + }; + updateControllerVisibilities(); + if (shouldRefresh) refreshCurrentSnapshot(); + } catch (e) {} + }; + + // 2. Export & Layout Reset + const exportCodeCtrl = gui.add({ exportCode: function() { + try { + const changes = map._layerTunerChanges; + const showAllArgs = tunerState.showMode === 'All Options'; + let codeStr = '# Copy-paste this complete pipeline to recreate your styled map:\n\n'; + const parts = []; const originalCalls = config.original_calls; const processedLayerIds = new Set(); + if (originalCalls && Array.isArray(originalCalls) && originalCalls.length > 0) { + originalCalls.forEach(function(call) { + const fun = call.fun; const args = call.args.map(a => ({ name: a.name, value: a.value })); + let layerId = null; const idArg = args.find(a => a.name === 'id'); + if (idArg) { layerId = idArg.value.replace(/^["']|["']$/g, ''); processedLayerIds.add(layerId); } + if (layerId) { + const layerChanges = changes[layerId]; + if (fun === 'add_flowmap' && layerMeta[layerId] && layerMeta[layerId].type === 'flowmap') { + const flowState = layerMeta[layerId].state; + Object.keys(flowState).forEach(function(propName) { + const rName = getRName('flowmap', propName); + const propVal = flowState[propName]; + const isTuned = layerChanges && layerChanges.props && layerChanges.props[propName] !== undefined; + const wasPresent = args.some(a => a.name === rName); + if (wasPresent || isTuned || showAllArgs) { + if (propVal === null || (propVal !== undefined && typeof propVal !== 'object')) { + const formattedVal = formatRValue(propVal); + const existing = args.find(a => a.name === rName); + if (existing) existing.value = formattedVal; + else args.push({ name: rName, value: formattedVal }); + } + } + }); + } + const type = fun.startsWith('add_') && fun.endsWith('_layer') ? { 'add_circle_layer': 'circle', 'add_fill_layer': 'fill', 'add_line_layer': 'line', 'add_symbol_layer': 'symbol', 'add_heatmap_layer': 'heatmap', 'add_fill_extrusion_layer': 'fill-extrusion', 'add_raster_layer': 'raster' }[fun] : null; + if (type && TUNER_SCHEMA[type]) { + const schema = TUNER_SCHEMA[type]; + Object.keys(schema).forEach(function(propName) { + const rName = getRName(type, propName); let propVal = undefined; + if (layerChanges && layerChanges.props[propName] !== undefined) propVal = layerChanges.props[propName].value; + else if (args.some(a => a.name === rName) || showAllArgs) { + try { propVal = schema[propName].method === 'paint' ? map.getPaintProperty(layerId, propName) : map.getLayoutProperty(layerId, propName); } catch (e) {} + if (propVal === undefined || typeof propVal === 'object') propVal = schema[propName].default; + } + if (propVal === null || (propVal !== undefined && typeof propVal !== 'object')) { + const formattedVal = formatRValue(propVal); const existing = args.find(a => a.name === rName); + if (existing) existing.value = formattedVal; else args.push({ name: rName, value: formattedVal }); + } + }); + } + } + if (['maplibre', 'mapboxgl', 'maplibre_compare', 'mapboxgl_compare'].includes(fun)) { + const sArg = args.find(a => a.name === 'style'); + if (sArg && sArg.value.includes('basemaps.cartocdn.com')) { + const valStr = sArg.value.replace(/^["']|["']$/g, ''); const name = (valStr.split('/').slice(-2, -1)[0] || '').replace('-gl-style', '').replace('nolabels', 'no-labels'); + sArg.value = `carto_style("${name || 'dark-matter'}")`; + } + parts.push(`${fun}(\n${args.map(a => ` ${a.name} = ${a.value}`).join(',\n')}\n)`); + } else parts.push(` ${fun}(\n${args.map(a => a.name ? ` ${a.name} = ${a.value}` : ` ${a.value}`).join(',\n')}\n )`); + }); + } else { + const mt = config.map_type === 'mapboxgl' ? 'mapboxgl' : 'maplibre'; + let s = x.style || ''; + if (s.includes('basemaps.cartocdn.com')) { const n = (s.split('/').slice(-2, -1)[0] || '').replace('-gl-style', '').replace('nolabels', 'no-labels'); s = `carto_style("${n || 'dark-matter'}")`; } else s = `"${s}"`; + parts.push(`${mt}(\n style = ${s}${x.center ? `,\n center = c(${x.center[0]}, ${x.center[1]})` : ''}${x.zoom ? `,\n zoom = ${x.zoom}` : ''}\n)`); + } + const styleObj = map.getStyle(); + if (styleObj && styleObj.layers) { + styleObj.layers.forEach(l => { + if (processedLayerIds.has(l.id) || (map._basemapLayerIds && map._basemapLayerIds.has(l.id))) return; + const typeMap = { 'circle': 'add_circle_layer', 'fill': 'add_fill_layer', 'line': 'add_line_layer', 'symbol': 'add_symbol_layer', 'heatmap': 'add_heatmap_layer', 'fill-extrusion': 'add_fill_extrusion_layer', 'raster': 'add_raster_layer' }; + if (!typeMap[l.type] || !TUNER_SCHEMA[l.type]) return; + const rf = typeMap[l.type]; + let lc = ` ${rf}(\n id = "${l.id}",\n source = "${l.source}"`; + const sch = TUNER_SCHEMA[l.type]; const lCh = (changes[l.id] && changes[l.id].props) || {}; + Object.keys(sch).forEach(p => { + let v = lCh[p] ? lCh[p].value : (showAllArgs ? (function(){ try { return sch[p].method === 'paint' ? map.getPaintProperty(l.id, p) : map.getLayoutProperty(l.id, p); } catch(e){} })() : undefined); + if (v === undefined && showAllArgs) v = sch[p].default; + if (v === null || (v !== undefined && typeof v !== 'object')) lc += `,\n ${getRName(l.type, p)} = ${formatRValue(v)}`; + }); + parts.push(lc + '\n )'); + }); + } + if (map._mapglFlowmapLayers) { + map._mapglFlowmapLayers.forEach(l => { + if (processedLayerIds.has(l.id)) return; + let lc = ` add_flowmap(\n id = "${l.id}",\n locations = locations_data,\n flows = flows_data`; + const meta = layerMeta[l.id]; + if (meta && meta.state) { + Object.keys(meta.state).forEach(p => { + const rName = getRName('flowmap', p); + const v = meta.state[p]; + if (v !== undefined && typeof v !== 'object') lc += `,\n ${rName} = ${formatRValue(v)}`; + }); + } + parts.push(lc + '\n )'); + }); + } + codeStr += parts.join(' |>\n') + ' |>\n add_layer_tuner()'; + const overlay = document.createElement('div'); + overlay.style = 'position:fixed;top:0;left:0;width:100vw;height:100vh;background:rgba(0,0,0,0.6);z-index:100000;display:flex;align-items:center;justify-content:center;'; + overlay.innerHTML = `

Exported R Code 🚀

Copy and paste into your R script.

${codeStr}
`; + document.body.appendChild(overlay); document.getElementById('tuner-close-btn').onclick = () => document.body.removeChild(overlay); + document.getElementById('tuner-copy-btn').onclick = function() { + copyToClipboardFallback(codeStr).then(() => { + this.textContent = 'Copied! ✓'; this.style.background = '#4caf50'; this.style.color = '#fff'; + setTimeout(() => { this.textContent = 'Copy Code'; this.style.background = '#00bcd4'; this.style.color = '#121212'; }, 2000); + }); + }; + } catch (err) { console.error('Export Error:', err); alert('Export failed. Check console.'); } + } }, 'exportCode').name('Export R Code 🚀'); + + const resetAllLayers = function() { + console.log('Layer Tuner: Global reset triggered'); + recordHistory(); + Object.keys(layerMeta).forEach(lid => { + try { + const meta = layerMeta[lid]; + if (meta.type === 'flowmap') { + const current = map._mapglFlowmapLayers; + if (current && current[meta.idx]) { + const updated = current[meta.idx].clone({ ...meta.initial }); + const newArr = [...current]; newArr[meta.idx] = updated; map._mapglFlowmapLayers = newArr; + if (map._mapglFlowmapOverlay || map._deckgl) (map._mapglFlowmapOverlay || map._deckgl).setProps({ layers: map._mapglFlowmapLayers }); + Object.assign(meta.state, meta.initial); + } + } else { + Object.keys(meta.rawInitial).forEach(p => { + const spec = TUNER_SCHEMA[meta.type][p]; + const rawVal = meta.rawInitial[p]; + try { + // If rawVal was undefined originally, some map properties cannot be unset to undefined. + // Try to apply it, or gracefully fail. + if (rawVal !== undefined) { + if (spec.method === 'paint') map.setPaintProperty(lid, p, rawVal); + else map.setLayoutProperty(lid, p, rawVal); + } + } catch (e) { console.warn(`Layer Tuner: Reset property ${p} failed on ${lid}`, e); } + meta.state[p] = meta.initial[p]; // Update UI state + }); + } + delete map._layerTunerChanges[lid]; + } catch (e) { console.error(`Layer Tuner: Failed resetting layer ${lid}`, e); } + }); + + try { + gui.controllersRecursive().forEach(c => { if(c && typeof c.updateDisplay === 'function') c.updateDisplay(); }); + updateControllerVisibilities(); + refreshCurrentSnapshot(); + } catch (e) { console.error('Layer Tuner: Failed updating UI post-reset', e); } + }; + + gui.add({ resetAll: resetAllLayers }, 'resetAll').name('♻️ Reset All Layers'); + gui.add({ resetLayout: function() { hasBeenManuallyResized = false; manualWidth = initialWidth; manualHeight = initialHeight; applyInitialLayout(); } }, 'resetLayout').name('🔄 Reset UI Layout'); + + // 3. Toggles & Filters + const modeRow = document.createElement('div'); + modeRow.style.display = 'flex'; modeRow.style.gap = '2px'; modeRow.style.padding = '0 4px'; modeRow.style.margin = '4px 0'; + const bCust = document.createElement('button'); bCust.textContent = '🎯 Customized'; bCust.style.flex = '1'; bCust.style.fontSize = '10px'; bCust.style.padding = '6px 0'; bCust.style.background = tunerState.showMode === 'Customized' ? '#00bcd4' : '#424242'; bCust.style.color = tunerState.showMode === 'Customized' ? '#121212' : '#fff'; bCust.style.border = 'none'; bCust.style.borderRadius = '2px'; bCust.style.cursor = 'pointer'; bCust.style.fontWeight = '600'; + const bAll = document.createElement('button'); bAll.textContent = '🌐 All Options'; bAll.style.flex = '1'; bAll.style.fontSize = '10px'; bAll.style.padding = '6px 0'; bAll.style.background = tunerState.showMode === 'All Options' ? '#00bcd4' : '#424242'; bAll.style.color = tunerState.showMode === 'All Options' ? '#121212' : '#fff'; bAll.style.border = 'none'; bAll.style.borderRadius = '2px'; bAll.style.cursor = 'pointer'; bAll.style.fontWeight = '600'; + const setMode = (m) => { tunerState.showMode = m; bCust.style.background = m === 'Customized' ? '#00bcd4' : '#424242'; bCust.style.color = m === 'Customized' ? '#121212' : '#fff'; bAll.style.background = m === 'All Options' ? '#00bcd4' : '#424242'; bAll.style.color = m === 'All Options' ? '#121212' : '#fff'; updateControllerVisibilities(); }; + bCust.onclick = () => setMode('Customized'); bAll.onclick = () => setMode('All Options'); modeRow.appendChild(bCust); modeRow.appendChild(bAll); dom.querySelector('.children').prepend(modeRow); + + const historyRow = document.createElement('div'); + historyRow.style.display = 'flex'; historyRow.style.gap = '2px'; historyRow.style.padding = '0 4px'; historyRow.style.margin = '4px 0'; + undoButton = document.createElement('button'); undoButton.innerHTML = '↶ Undo'; undoButton.title = `Undo previous tuning change (keeps up to ${HISTORY_LIMIT} states)`; undoButton.style.flex = '1'; undoButton.style.fontSize = '10px'; undoButton.style.padding = '5px 0'; undoButton.style.background = '#424242'; undoButton.style.color = '#fff'; undoButton.style.border = 'none'; undoButton.style.borderRadius = '2px'; undoButton.style.fontWeight = '600'; + redoButton = document.createElement('button'); redoButton.innerHTML = '↷ Redo'; redoButton.title = `Redo tuning change (history keeps up to ${HISTORY_LIMIT} undo states)`; redoButton.style.flex = '1'; redoButton.style.fontSize = '10px'; redoButton.style.padding = '5px 0'; redoButton.style.background = '#424242'; redoButton.style.color = '#fff'; redoButton.style.border = 'none'; redoButton.style.borderRadius = '2px'; redoButton.style.fontWeight = '600'; + undoButton.onclick = undoHistory; redoButton.onclick = redoHistory; + historyRow.appendChild(undoButton); historyRow.appendChild(redoButton); + dom.querySelector('.children').insertBefore(historyRow, modeRow.nextSibling); + updateHistoryButtons(); + + const searchCtrl = gui.add(tunerState, 'searchQuery').name('🔍 Filter Layers').onChange(updateFolderVisibilities); + try { const input = searchCtrl.domElement.querySelector('input'); if (input) input.addEventListener('input', function() { tunerState.searchQuery = this.value; updateFolderVisibilities(); }); } catch (e) {} + const propSearchCtrl = gui.add(tunerState, 'propSearchQuery').name('🔍 Filter Arguments').onChange(updateControllerVisibilities); + try { const input = propSearchCtrl.domElement.querySelector('input'); if (input) input.addEventListener('input', function() { tunerState.propSearchQuery = this.value; updateControllerVisibilities(); }); } catch (e) {} + + const btnRow = document.createElement('div'); + btnRow.style.display = 'flex'; btnRow.style.gap = '2px'; btnRow.style.padding = '0 4px'; btnRow.style.margin = '4px 0'; + const bExpand = document.createElement('button'); bExpand.textContent = '📂 Expand All'; bExpand.style.flex = '1'; bExpand.style.fontSize = '10px'; bExpand.style.padding = '4px 0'; bExpand.style.background = '#424242'; bExpand.style.color = '#fff'; bExpand.style.border = 'none'; bExpand.style.borderRadius = '2px'; bExpand.style.cursor = 'pointer'; bExpand.onclick = () => layerFolders.forEach(f => f.open()); + const bCollapse = document.createElement('button'); bCollapse.textContent = '📁 Collapse All'; bCollapse.style.flex = '1'; bCollapse.style.fontSize = '10px'; bCollapse.style.padding = '4px 0'; bCollapse.style.background = '#424242'; bCollapse.style.color = '#fff'; bCollapse.style.border = 'none'; bCollapse.style.borderRadius = '2px'; bCollapse.style.cursor = 'pointer'; bCollapse.onclick = () => layerFolders.forEach(f => f.close()); + btnRow.appendChild(bExpand); btnRow.appendChild(bCollapse); dom.querySelector('.children').insertBefore(btnRow, searchCtrl.domElement); + dom.querySelector('.children').prepend(exportCodeCtrl.domElement); + + // 4. Robust Draggability + const titleEl = dom.querySelector('.title'); + if (titleEl) { + titleEl.style.cursor = 'move'; let dragging = false, moved = false, sx, sy, ex, ey; + titleEl.addEventListener('mousedown', (e) => { + if (e.button !== 0 || isResizing) return; + dragging = true; moved = false; sx = e.clientX; sy = e.clientY; + const r = dom.getBoundingClientRect(); const pr = el.getBoundingClientRect(); ex = r.left - pr.left; ey = r.top - pr.top; + dom.style.left = ex + 'px'; dom.style.top = ey + 'px'; dom.style.right = 'auto'; dom.style.bottom = 'auto'; + dom.style.height = r.height + 'px'; dom.style.width = r.width + 'px'; dom.style.maxHeight = 'none'; + }); + window.addEventListener('mousemove', (e) => { + if (!dragging) return; const dx = e.clientX - sx, dy = e.clientY - sy; if (Math.hypot(dx, dy) > 5) moved = true; + if (moved) { const pr = el.getBoundingClientRect(); let nx = ex + dx, ny = ey + dy; nx = Math.max(0, Math.min(nx, pr.width - 50)); ny = Math.max(0, Math.min(ny, pr.height - 30)); dom.style.left = nx + 'px'; dom.style.top = ny + 'px'; } + }); + window.addEventListener('mouseup', () => { dragging = false; if (!hasBeenManuallyResized && !gui._closed) { dom.style.height = 'auto'; dom.style.maxHeight = 'calc(100% - 20px)'; } }); + titleEl.addEventListener('click', (e) => { if (moved) { e.stopImmediatePropagation(); e.preventDefault(); moved = false; } }, { capture: true }); + } + + // 5. Process Layers + const style = map.getStyle(); + if (style && style.layers) { + style.layers.forEach(function(l) { + if ((map._basemapLayerIds && map._basemapLayerIds.has(l.id)) || !TUNER_SCHEMA[l.type]) return; + if (config.layers && config.layers !== 'all' && !config.layers.includes(l.id)) return; + const folder = gui.addFolder(`${l.type.toUpperCase()}: ${l.id}`); + folder.close(); layerFolders.push(folder); + const s = {}, initial = {}, rawInitial = {}; + layerMeta[l.id] = { type: l.type, state: s, initial: initial, rawInitial: rawInitial }; + Object.keys(TUNER_SCHEMA[l.type]).forEach(p => { + const spec = TUNER_SCHEMA[l.type][p]; let v = undefined; + try { v = spec.method === 'paint' ? map.getPaintProperty(l.id, p) : map.getLayoutProperty(l.id, p); } catch (e) {} + rawInitial[p] = v; // Store original format (could be an object/expression) + if (v === undefined || typeof v === 'object') v = spec.default; + if (spec.type === 'color') v = normalizeColorValue(v, spec.default); + s[p] = v; initial[p] = v; + let orig = false; + if (config.original_calls) { + const rn = getRName(l.type, p); const mc = config.original_calls.find(c => { const ia = c.args.find(a => a.name === 'id'); return ia && ia.value.replace(/^["']|["']$/g, '') === l.id; }); + if (mc) orig = mc.args.some(a => a.name === rn); + } + const hasS = (spec.method === 'paint' && l.paint && l.paint[p] !== undefined) || (spec.method === 'layout' && l.layout && l.layout[p] !== undefined); + let ctrl; + if (spec.type === 'color') { + ctrl = folder.addColor(s, p); + } else if (spec.type === 'slider') { + const bounds = getExpandedSliderBounds(spec, s[p]); + ctrl = folder.add(s, p, bounds.min, bounds.max, spec.step); + attachSliderAutoExpansion(ctrl, spec); + } else { + ctrl = folder.add(s, p); + } + if (ctrl) { + ctrl.name(getRName(l.type, p)); allLayerControllers.push({ controller: ctrl, type: l.type, prop: p, layerId: l.id, originallyPresent: orig, hasInStyle: hasS }); + if (spec.type === 'slider' && typeof ctrl.onFinishChange === 'function') { + ctrl.onChange(nv => { + applyLayerControllerValue(l.id, l.type, p, spec, nv, { + record: false, + refresh: false + }); + }); + ctrl.onFinishChange(nv => { + applyLayerControllerValue(l.id, l.type, p, spec, nv); + }); + } else { + ctrl.onChange(nv => { + applyLayerControllerValue(l.id, l.type, p, spec, nv); + }); + } + } + }); + folder.add({ reset: function() { + console.log(`Layer Tuner: Resetting layer ${l.id}`); + try { + recordHistory(); + Object.keys(rawInitial).forEach(p => { + const sp = TUNER_SCHEMA[l.type][p]; + const rawVal = rawInitial[p]; + try { + if (rawVal !== undefined) { + if (sp.method === 'paint') map.setPaintProperty(l.id, p, rawVal); + else map.setLayoutProperty(l.id, p, rawVal); + } + } catch(e) {} + s[p] = initial[p]; + }); + delete map._layerTunerChanges[l.id]; + try { + folder.controllersRecursive().forEach(c => { if(c && typeof c.updateDisplay === 'function') c.updateDisplay(); }); + updateControllerVisibilities(); + refreshCurrentSnapshot(); + } catch(e){} + } catch(e) { console.error(`Failed to reset layer ${l.id}`, e); } + }}, 'reset').name('♻️ Reset Layer'); + }); + } + + // 6. Flowmaps + if (map._mapglFlowmapLayers) { + map._mapglFlowmapLayers.forEach((l, i) => { + const lid = l.id || `flowmap-${i}`; if (config.layers && config.layers !== 'all' && !config.layers.includes(lid)) return; + const folder = gui.addFolder(`FLOWMAP: ${lid}`); folder.close(); layerFolders.push(folder); + const initial = { + colorScheme: l.props.colorScheme || 'Teal', + darkMode: l.props.darkMode !== undefined ? l.props.darkMode : true, + opacity: l.props.opacity !== undefined ? l.props.opacity : 1, + blendMode: map._deckCanvas && map._deckCanvas.style.mixBlendMode ? map._deckCanvas.style.mixBlendMode : 'screen', + fadeAmount: l.props.fadeAmount !== undefined ? l.props.fadeAmount : 50, + highlightColor: normalizeColorValue(l.props.highlightColor, '#ff9b29'), + locationsEnabled: l.props.locationsEnabled !== undefined ? l.props.locationsEnabled : true, + locationTotalsEnabled: l.props.locationTotalsEnabled !== undefined ? l.props.locationTotalsEnabled : true, + locationLabelsEnabled: l.props.locationLabelsEnabled !== undefined ? l.props.locationLabelsEnabled : false, + flowLinesRenderingMode: l.props.flowLinesRenderingMode || 'straight', + clusteringEnabled: l.props.clusteringEnabled !== undefined ? l.props.clusteringEnabled : true, + clusteringAuto: l.props.clusteringAuto !== undefined ? l.props.clusteringAuto : true, + clusteringLevel: l.props.clusteringLevel !== undefined ? l.props.clusteringLevel : 5, + fadeEnabled: l.props.fadeEnabled !== undefined ? l.props.fadeEnabled : true, + fadeOpacityEnabled: l.props.fadeOpacityEnabled !== undefined ? l.props.fadeOpacityEnabled : false, + adaptiveScalesEnabled: l.props.adaptiveScalesEnabled !== undefined ? l.props.adaptiveScalesEnabled : true, + temporalScaleDomain: l.props.temporalScaleDomain || 'selected', + animationEnabled: l.props.animationEnabled !== undefined ? l.props.animationEnabled : false, + maxTopFlowsDisplayNum: l.props.maxTopFlowsDisplayNum || 5000, + flowEndpointsInViewportMode: l.props.flowEndpointsInViewportMode || 'any' + }; + const fs = { ...initial }; + layerMeta[lid] = { type: 'flowmap', state: fs, initial: initial, idx: i }; + const up = (options) => { + try { + const shouldRecord = !options || options.record !== false; + const shouldRefresh = !options || options.refresh !== false; + if (shouldRecord) recordHistory(); + const cur = map._mapglFlowmapLayers; + + // Handle animation toggle syncing + if (options && options.prop === 'animationEnabled') { + if (fs.animationEnabled) { + fs.flowLinesRenderingMode = 'animated-straight'; + } else if (fs.flowLinesRenderingMode === 'animated-straight') { + fs.flowLinesRenderingMode = 'straight'; + } + // Update display of rendering mode controller + try { + const rmc = folder.controllersRecursive().find(c => c._name === 'flow_lines_rendering_mode'); + if (rmc) rmc.updateDisplay(); + } catch(e) {} + } else if (options && options.prop === 'flowLinesRenderingMode') { + fs.animationEnabled = (fs.flowLinesRenderingMode === 'animated-straight'); + try { + const anc = folder.controllersRecursive().find(c => c._name === 'flow_animation_enabled'); + if (anc) anc.updateDisplay(); + } catch(e) {} + } + + const nL = cur[i].clone({ + colorScheme: fs.colorScheme, + darkMode: fs.darkMode, + opacity: fs.opacity, + fadeAmount: fs.fadeAmount, + highlightColor: fs.highlightColor, + locationsEnabled: fs.locationsEnabled, + locationTotalsEnabled: fs.locationTotalsEnabled, + locationLabelsEnabled: fs.locationLabelsEnabled, + flowLinesRenderingMode: fs.flowLinesRenderingMode, + clusteringEnabled: fs.clusteringEnabled, + clusteringAuto: fs.clusteringAuto, + clusteringLevel: fs.clusteringAuto ? undefined : fs.clusteringLevel, + fadeEnabled: fs.fadeEnabled, + fadeOpacityEnabled: fs.fadeOpacityEnabled, + adaptiveScalesEnabled: fs.adaptiveScalesEnabled, + temporalScaleDomain: fs.temporalScaleDomain, + maxTopFlowsDisplayNum: fs.maxTopFlowsDisplayNum, + flowEndpointsInViewportMode: fs.flowEndpointsInViewportMode + }); + const nArr = [...cur]; nArr[i] = nL; map._mapglFlowmapLayers = nArr; + (map._mapglFlowmapOverlay || map._deckgl).setProps({ layers: map._mapglFlowmapLayers }); if (map._deckCanvas) map._deckCanvas.style.mixBlendMode = fs.blendMode; + map._layerTunerChanges[lid] = { type: 'flowmap', props: { ...fs } }; if (map.triggerRepaint) map.triggerRepaint(); + if (shouldRefresh) refreshCurrentSnapshot(); + } catch (e) {} + }; + const registerFlowmapController = function(controller, prop) { + controller.name(getRName('flowmap', prop)); + let originallyPresent = false; + if (config.original_calls) { + const rn = getRName('flowmap', prop); + const mc = config.original_calls.find(c => { + const ia = c.args.find(a => a.name === 'id'); + return ia && ia.value.replace(/^["']|["']$/g, '') === lid; + }); + if (mc) originallyPresent = mc.args.some(a => a.name === rn); + } + if ((prop === 'opacity' || prop === 'fadeAmount') && typeof controller.onFinishChange === 'function') { + controller.onChange(function() { + up({ record: false, refresh: false, prop: prop }); + }); + controller.onFinishChange(function() { + up({ prop: prop }); + }); + } else { + controller.onChange(function() { + up({ prop: prop }); + }); + } + allLayerControllers.push({ + controller: controller, + type: 'flowmap', + prop: prop, + layerId: lid, + originallyPresent: originallyPresent, + hasInStyle: false + }); + }; + registerFlowmapController( + folder.add(fs, 'colorScheme', config.flowmap_color_schemes || ['Teal', 'Blues', 'Burg', 'Sunset', 'Greens', 'Oranges', 'Purples', 'Reds']), + 'colorScheme' + ); + registerFlowmapController(folder.add(fs, 'darkMode'), 'darkMode'); + registerFlowmapController(folder.add(fs, 'opacity', 0, 1, 0.05), 'opacity'); + registerFlowmapController( + folder.add(fs, 'blendMode', ['normal', 'multiply', 'screen', 'overlay', 'darken', 'lighten', 'color-dodge', 'color-burn', 'hard-light', 'soft-light', 'difference', 'exclusion', 'hue', 'saturation', 'color', 'luminosity']), + 'blendMode' + ); + registerFlowmapController(folder.add(fs, 'fadeAmount', 0, 100, 1), 'fadeAmount'); + registerFlowmapController(folder.addColor(fs, 'highlightColor'), 'highlightColor'); + registerFlowmapController(folder.add(fs, 'locationsEnabled'), 'locationsEnabled'); + registerFlowmapController(folder.add(fs, 'locationTotalsEnabled'), 'locationTotalsEnabled'); + registerFlowmapController(folder.add(fs, 'locationLabelsEnabled'), 'locationLabelsEnabled'); + registerFlowmapController(folder.add(fs, 'flowLinesRenderingMode', ['straight', 'animated-straight', 'curved']), 'flowLinesRenderingMode'); + registerFlowmapController(folder.add(fs, 'clusteringEnabled'), 'clusteringEnabled'); + registerFlowmapController(folder.add(fs, 'clusteringAuto'), 'clusteringAuto'); + registerFlowmapController(folder.add(fs, 'clusteringLevel', 0, 20, 1), 'clusteringLevel'); + registerFlowmapController(folder.add(fs, 'fadeEnabled'), 'fadeEnabled'); + registerFlowmapController(folder.add(fs, 'fadeOpacityEnabled'), 'fadeOpacityEnabled'); + registerFlowmapController(folder.add(fs, 'adaptiveScalesEnabled'), 'adaptiveScalesEnabled'); + registerFlowmapController(folder.add(fs, 'temporalScaleDomain', ['selected', 'all']), 'temporalScaleDomain'); + registerFlowmapController(folder.add(fs, 'maxTopFlowsDisplayNum', 100, 50000, 100), 'maxTopFlowsDisplayNum'); + registerFlowmapController(folder.add(fs, 'flowEndpointsInViewportMode', ['any', 'both']), 'flowEndpointsInViewportMode'); + + folder.add({ reset: function() { + console.log(`Layer Tuner: Resetting flowmap ${lid}`); + try { + recordHistory(); + Object.assign(fs, initial); + up({ record: false }); + delete map._layerTunerChanges[lid]; + try { + folder.controllersRecursive().forEach(c => { if(c && typeof c.updateDisplay === 'function') c.updateDisplay(); }); + updateControllerVisibilities(); + refreshCurrentSnapshot(); + } catch(e){} + } catch(e) { console.error(`Failed to reset flowmap ${lid}`, e); } + }}, 'reset').name('♻️ Reset Layer'); + }); + } + + if (config.collapsed) { + gui.close(); + } else if (layerFolders.length <= 2) { + layerFolders.forEach(folder => folder.open()); + } + refreshCurrentSnapshot(); updateControllerVisibilities(); updateFolderVisibilities(); + } + }; +})(); diff --git a/inst/htmlwidgets/lib/lil-gui/lil-gui.umd.min.js b/inst/htmlwidgets/lib/lil-gui/lil-gui.umd.min.js new file mode 100644 index 0000000..aa63ce3 --- /dev/null +++ b/inst/htmlwidgets/lib/lil-gui/lil-gui.umd.min.js @@ -0,0 +1,8 @@ +/** + * lil-gui + * https://lil-gui.georgealways.com + * @version 0.19.2 + * @author George Michael Brower + * @license MIT + */ +!function(t,i){"object"==typeof exports&&"undefined"!=typeof module?i(exports):"function"==typeof define&&define.amd?define(["exports"],i):i((t=t||self).lil={})}(this,(function(t){"use strict";class i{constructor(t,e,s,n,l="div"){this.parent=t,this.object=e,this.property=s,this._disabled=!1,this._hidden=!1,this.initialValue=this.getValue(),this.domElement=document.createElement(l),this.domElement.classList.add("controller"),this.domElement.classList.add(n),this.$name=document.createElement("div"),this.$name.classList.add("name"),i.nextNameID=i.nextNameID||0,this.$name.id="lil-gui-name-"+ ++i.nextNameID,this.$widget=document.createElement("div"),this.$widget.classList.add("widget"),this.$disable=this.$widget,this.domElement.appendChild(this.$name),this.domElement.appendChild(this.$widget),this.domElement.addEventListener("keydown",t=>t.stopPropagation()),this.domElement.addEventListener("keyup",t=>t.stopPropagation()),this.parent.children.push(this),this.parent.controllers.push(this),this.parent.$children.appendChild(this.domElement),this._listenCallback=this._listenCallback.bind(this),this.name(s)}name(t){return this._name=t,this.$name.textContent=t,this}onChange(t){return this._onChange=t,this}_callOnChange(){this.parent._callOnChange(this),void 0!==this._onChange&&this._onChange.call(this,this.getValue()),this._changed=!0}onFinishChange(t){return this._onFinishChange=t,this}_callOnFinishChange(){this._changed&&(this.parent._callOnFinishChange(this),void 0!==this._onFinishChange&&this._onFinishChange.call(this,this.getValue())),this._changed=!1}reset(){return this.setValue(this.initialValue),this._callOnFinishChange(),this}enable(t=!0){return this.disable(!t)}disable(t=!0){return t===this._disabled||(this._disabled=t,this.domElement.classList.toggle("disabled",t),this.$disable.toggleAttribute("disabled",t)),this}show(t=!0){return this._hidden=!t,this.domElement.style.display=this._hidden?"none":"",this}hide(){return this.show(!1)}options(t){const i=this.parent.add(this.object,this.property,t);return i.name(this._name),this.destroy(),i}min(t){return this}max(t){return this}step(t){return this}decimals(t){return this}listen(t=!0){return this._listening=t,void 0!==this._listenCallbackID&&(cancelAnimationFrame(this._listenCallbackID),this._listenCallbackID=void 0),this._listening&&this._listenCallback(),this}_listenCallback(){this._listenCallbackID=requestAnimationFrame(this._listenCallback);const t=this.save();t!==this._listenPrevValue&&this.updateDisplay(),this._listenPrevValue=t}getValue(){return this.object[this.property]}setValue(t){return this.getValue()!==t&&(this.object[this.property]=t,this._callOnChange(),this.updateDisplay()),this}updateDisplay(){return this}load(t){return this.setValue(t),this._callOnFinishChange(),this}save(){return this.getValue()}destroy(){this.listen(!1),this.parent.children.splice(this.parent.children.indexOf(this),1),this.parent.controllers.splice(this.parent.controllers.indexOf(this),1),this.parent.$children.removeChild(this.domElement)}}class e extends i{constructor(t,i,e){super(t,i,e,"boolean","label"),this.$input=document.createElement("input"),this.$input.setAttribute("type","checkbox"),this.$input.setAttribute("aria-labelledby",this.$name.id),this.$widget.appendChild(this.$input),this.$input.addEventListener("change",()=>{this.setValue(this.$input.checked),this._callOnFinishChange()}),this.$disable=this.$input,this.updateDisplay()}updateDisplay(){return this.$input.checked=this.getValue(),this}}function s(t){let i,e;return(i=t.match(/(#|0x)?([a-f0-9]{6})/i))?e=i[2]:(i=t.match(/rgb\(\s*(\d*)\s*,\s*(\d*)\s*,\s*(\d*)\s*\)/))?e=parseInt(i[1]).toString(16).padStart(2,0)+parseInt(i[2]).toString(16).padStart(2,0)+parseInt(i[3]).toString(16).padStart(2,0):(i=t.match(/^#?([a-f0-9])([a-f0-9])([a-f0-9])$/i))&&(e=i[1]+i[1]+i[2]+i[2]+i[3]+i[3]),!!e&&"#"+e}const n={isPrimitive:!0,match:t=>"number"==typeof t,fromHexString:t=>parseInt(t.substring(1),16),toHexString:t=>"#"+t.toString(16).padStart(6,0)},l={isPrimitive:!1,match:t=>Array.isArray(t),fromHexString(t,i,e=1){const s=n.fromHexString(t);i[0]=(s>>16&255)/255*e,i[1]=(s>>8&255)/255*e,i[2]=(255&s)/255*e},toHexString:([t,i,e],s=1)=>n.toHexString(t*(s=255/s)<<16^i*s<<8^e*s<<0)},r={isPrimitive:!1,match:t=>Object(t)===t,fromHexString(t,i,e=1){const s=n.fromHexString(t);i.r=(s>>16&255)/255*e,i.g=(s>>8&255)/255*e,i.b=(255&s)/255*e},toHexString:({r:t,g:i,b:e},s=1)=>n.toHexString(t*(s=255/s)<<16^i*s<<8^e*s<<0)},o=[{isPrimitive:!0,match:t=>"string"==typeof t,fromHexString:s,toHexString:s},n,l,r];class a extends i{constructor(t,i,e,n){var l;super(t,i,e,"color"),this.$input=document.createElement("input"),this.$input.setAttribute("type","color"),this.$input.setAttribute("tabindex",-1),this.$input.setAttribute("aria-labelledby",this.$name.id),this.$text=document.createElement("input"),this.$text.setAttribute("type","text"),this.$text.setAttribute("spellcheck","false"),this.$text.setAttribute("aria-labelledby",this.$name.id),this.$display=document.createElement("div"),this.$display.classList.add("display"),this.$display.appendChild(this.$input),this.$widget.appendChild(this.$display),this.$widget.appendChild(this.$text),this._format=(l=this.initialValue,o.find(t=>t.match(l))),this._rgbScale=n,this._initialValueHexString=this.save(),this._textFocused=!1,this.$input.addEventListener("input",()=>{this._setValueFromHexString(this.$input.value)}),this.$input.addEventListener("blur",()=>{this._callOnFinishChange()}),this.$text.addEventListener("input",()=>{const t=s(this.$text.value);t&&this._setValueFromHexString(t)}),this.$text.addEventListener("focus",()=>{this._textFocused=!0,this.$text.select()}),this.$text.addEventListener("blur",()=>{this._textFocused=!1,this.updateDisplay(),this._callOnFinishChange()}),this.$disable=this.$text,this.updateDisplay()}reset(){return this._setValueFromHexString(this._initialValueHexString),this}_setValueFromHexString(t){if(this._format.isPrimitive){const i=this._format.fromHexString(t);this.setValue(i)}else this._format.fromHexString(t,this.getValue(),this._rgbScale),this._callOnChange(),this.updateDisplay()}save(){return this._format.toHexString(this.getValue(),this._rgbScale)}load(t){return this._setValueFromHexString(t),this._callOnFinishChange(),this}updateDisplay(){return this.$input.value=this._format.toHexString(this.getValue(),this._rgbScale),this._textFocused||(this.$text.value=this.$input.value.substring(1)),this.$display.style.backgroundColor=this.$input.value,this}}class h extends i{constructor(t,i,e){super(t,i,e,"function"),this.$button=document.createElement("button"),this.$button.appendChild(this.$name),this.$widget.appendChild(this.$button),this.$button.addEventListener("click",t=>{t.preventDefault(),this.getValue().call(this.object),this._callOnChange()}),this.$button.addEventListener("touchstart",()=>{},{passive:!0}),this.$disable=this.$button}}class d extends i{constructor(t,i,e,s,n,l){super(t,i,e,"number"),this._initInput(),this.min(s),this.max(n);const r=void 0!==l;this.step(r?l:this._getImplicitStep(),r),this.updateDisplay()}decimals(t){return this._decimals=t,this.updateDisplay(),this}min(t){return this._min=t,this._onUpdateMinMax(),this}max(t){return this._max=t,this._onUpdateMinMax(),this}step(t,i=!0){return this._step=t,this._stepExplicit=i,this}updateDisplay(){const t=this.getValue();if(this._hasSlider){let i=(t-this._min)/(this._max-this._min);i=Math.max(0,Math.min(i,1)),this.$fill.style.width=100*i+"%"}return this._inputFocused||(this.$input.value=void 0===this._decimals?t:t.toFixed(this._decimals)),this}_initInput(){this.$input=document.createElement("input"),this.$input.setAttribute("type","text"),this.$input.setAttribute("aria-labelledby",this.$name.id);window.matchMedia("(pointer: coarse)").matches&&(this.$input.setAttribute("type","number"),this.$input.setAttribute("step","any")),this.$widget.appendChild(this.$input),this.$disable=this.$input;const t=t=>{const i=parseFloat(this.$input.value);isNaN(i)||(this._snapClampSetValue(i+t),this.$input.value=this.getValue())};let i,e,s,n,l,r=!1;const o=t=>{if(r){const s=t.clientX-i,n=t.clientY-e;Math.abs(n)>5?(t.preventDefault(),this.$input.blur(),r=!1,this._setDraggingStyle(!0,"vertical")):Math.abs(s)>5&&a()}if(!r){const i=t.clientY-s;l-=i*this._step*this._arrowKeyMultiplier(t),n+l>this._max?l=this._max-n:n+l{this._setDraggingStyle(!1,"vertical"),this._callOnFinishChange(),window.removeEventListener("mousemove",o),window.removeEventListener("mouseup",a)};this.$input.addEventListener("input",()=>{let t=parseFloat(this.$input.value);isNaN(t)||(this._stepExplicit&&(t=this._snap(t)),this.setValue(this._clamp(t)))}),this.$input.addEventListener("keydown",i=>{"Enter"===i.key&&this.$input.blur(),"ArrowUp"===i.code&&(i.preventDefault(),t(this._step*this._arrowKeyMultiplier(i))),"ArrowDown"===i.code&&(i.preventDefault(),t(this._step*this._arrowKeyMultiplier(i)*-1))}),this.$input.addEventListener("wheel",i=>{this._inputFocused&&(i.preventDefault(),t(this._step*this._normalizeMouseWheel(i)))},{passive:!1}),this.$input.addEventListener("mousedown",t=>{i=t.clientX,e=s=t.clientY,r=!0,n=this.getValue(),l=0,window.addEventListener("mousemove",o),window.addEventListener("mouseup",a)}),this.$input.addEventListener("focus",()=>{this._inputFocused=!0}),this.$input.addEventListener("blur",()=>{this._inputFocused=!1,this.updateDisplay(),this._callOnFinishChange()})}_initSlider(){this._hasSlider=!0,this.$slider=document.createElement("div"),this.$slider.classList.add("slider"),this.$fill=document.createElement("div"),this.$fill.classList.add("fill"),this.$slider.appendChild(this.$fill),this.$widget.insertBefore(this.$slider,this.$input),this.domElement.classList.add("hasSlider");const t=t=>{const i=this.$slider.getBoundingClientRect();let e=(s=t,n=i.left,l=i.right,r=this._min,o=this._max,(s-n)/(l-n)*(o-r)+r);var s,n,l,r,o;this._snapClampSetValue(e)},i=i=>{t(i.clientX)},e=()=>{this._callOnFinishChange(),this._setDraggingStyle(!1),window.removeEventListener("mousemove",i),window.removeEventListener("mouseup",e)};let s,n,l=!1;const r=i=>{i.preventDefault(),this._setDraggingStyle(!0),t(i.touches[0].clientX),l=!1},o=i=>{if(l){const t=i.touches[0].clientX-s,e=i.touches[0].clientY-n;Math.abs(t)>Math.abs(e)?r(i):(window.removeEventListener("touchmove",o),window.removeEventListener("touchend",a))}else i.preventDefault(),t(i.touches[0].clientX)},a=()=>{this._callOnFinishChange(),this._setDraggingStyle(!1),window.removeEventListener("touchmove",o),window.removeEventListener("touchend",a)},h=this._callOnFinishChange.bind(this);let d;this.$slider.addEventListener("mousedown",s=>{this._setDraggingStyle(!0),t(s.clientX),window.addEventListener("mousemove",i),window.addEventListener("mouseup",e)}),this.$slider.addEventListener("touchstart",t=>{t.touches.length>1||(this._hasScrollBar?(s=t.touches[0].clientX,n=t.touches[0].clientY,l=!0):r(t),window.addEventListener("touchmove",o,{passive:!1}),window.addEventListener("touchend",a))},{passive:!1}),this.$slider.addEventListener("wheel",t=>{if(Math.abs(t.deltaX)this._max&&(t=this._max),t}_snapClampSetValue(t){this.setValue(this._clamp(this._snap(t)))}get _hasScrollBar(){const t=this.parent.root.$children;return t.scrollHeight>t.clientHeight}get _hasMin(){return void 0!==this._min}get _hasMax(){return void 0!==this._max}}class c extends i{constructor(t,i,e,s){super(t,i,e,"option"),this.$select=document.createElement("select"),this.$select.setAttribute("aria-labelledby",this.$name.id),this.$display=document.createElement("div"),this.$display.classList.add("display"),this.$select.addEventListener("change",()=>{this.setValue(this._values[this.$select.selectedIndex]),this._callOnFinishChange()}),this.$select.addEventListener("focus",()=>{this.$display.classList.add("focus")}),this.$select.addEventListener("blur",()=>{this.$display.classList.remove("focus")}),this.$widget.appendChild(this.$select),this.$widget.appendChild(this.$display),this.$disable=this.$select,this.options(s)}options(t){return this._values=Array.isArray(t)?t:Object.values(t),this._names=Array.isArray(t)?t:Object.keys(t),this.$select.replaceChildren(),this._names.forEach(t=>{const i=document.createElement("option");i.textContent=t,this.$select.appendChild(i)}),this.updateDisplay(),this}updateDisplay(){const t=this.getValue(),i=this._values.indexOf(t);return this.$select.selectedIndex=i,this.$display.textContent=-1===i?t:this._names[i],this}}class u extends i{constructor(t,i,e){super(t,i,e,"string"),this.$input=document.createElement("input"),this.$input.setAttribute("type","text"),this.$input.setAttribute("spellcheck","false"),this.$input.setAttribute("aria-labelledby",this.$name.id),this.$input.addEventListener("input",()=>{this.setValue(this.$input.value)}),this.$input.addEventListener("keydown",t=>{"Enter"===t.code&&this.$input.blur()}),this.$input.addEventListener("blur",()=>{this._callOnFinishChange()}),this.$widget.appendChild(this.$input),this.$disable=this.$input,this.updateDisplay()}updateDisplay(){return this.$input.value=this.getValue(),this}}let p=!1;class g{constructor({parent:t,autoPlace:i=void 0===t,container:e,width:s,title:n="Controls",closeFolders:l=!1,injectStyles:r=!0,touchStyles:o=!0}={}){if(this.parent=t,this.root=t?t.root:this,this.children=[],this.controllers=[],this.folders=[],this._closed=!1,this._hidden=!1,this.domElement=document.createElement("div"),this.domElement.classList.add("lil-gui"),this.$title=document.createElement("div"),this.$title.classList.add("title"),this.$title.setAttribute("role","button"),this.$title.setAttribute("aria-expanded",!0),this.$title.setAttribute("tabindex",0),this.$title.addEventListener("click",()=>this.openAnimated(this._closed)),this.$title.addEventListener("keydown",t=>{"Enter"!==t.code&&"Space"!==t.code||(t.preventDefault(),this.$title.click())}),this.$title.addEventListener("touchstart",()=>{},{passive:!0}),this.$children=document.createElement("div"),this.$children.classList.add("children"),this.domElement.appendChild(this.$title),this.domElement.appendChild(this.$children),this.title(n),this.parent)return this.parent.children.push(this),this.parent.folders.push(this),void this.parent.$children.appendChild(this.domElement);this.domElement.classList.add("root"),o&&this.domElement.classList.add("allow-touch-styles"),!p&&r&&(!function(t){const i=document.createElement("style");i.innerHTML=t;const e=document.querySelector("head link[rel=stylesheet], head style");e?document.head.insertBefore(i,e):document.head.appendChild(i)}('.lil-gui{--background-color:#1f1f1f;--text-color:#ebebeb;--title-background-color:#111;--title-text-color:#ebebeb;--widget-color:#424242;--hover-color:#4f4f4f;--focus-color:#595959;--number-color:#2cc9ff;--string-color:#a2db3c;--font-size:11px;--input-font-size:11px;--font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Arial,sans-serif;--font-family-mono:Menlo,Monaco,Consolas,"Droid Sans Mono",monospace;--padding:4px;--spacing:4px;--widget-height:20px;--title-height:calc(var(--widget-height) + var(--spacing)*1.25);--name-width:45%;--slider-knob-width:2px;--slider-input-width:27%;--color-input-width:27%;--slider-input-min-width:45px;--color-input-min-width:45px;--folder-indent:7px;--widget-padding:0 0 0 3px;--widget-border-radius:2px;--checkbox-size:calc(var(--widget-height)*0.75);--scrollbar-width:5px;color:var(--text-color);font-family:var(--font-family);font-size:var(--font-size);font-style:normal;font-weight:400;line-height:1;text-align:left;touch-action:manipulation;user-select:none;-webkit-user-select:none}.lil-gui,.lil-gui *{box-sizing:border-box;margin:0;padding:0}.lil-gui.root{background:var(--background-color);display:flex;flex-direction:column;width:var(--width,245px)}.lil-gui.root>.title{background:var(--title-background-color);color:var(--title-text-color)}.lil-gui.root>.children{overflow-x:hidden;overflow-y:auto}.lil-gui.root>.children::-webkit-scrollbar{background:var(--background-color);height:var(--scrollbar-width);width:var(--scrollbar-width)}.lil-gui.root>.children::-webkit-scrollbar-thumb{background:var(--focus-color);border-radius:var(--scrollbar-width)}.lil-gui.force-touch-styles,.lil-gui.force-touch-styles .lil-gui{--widget-height:28px;--padding:6px;--spacing:6px;--font-size:13px;--input-font-size:16px;--folder-indent:10px;--scrollbar-width:7px;--slider-input-min-width:50px;--color-input-min-width:65px}.lil-gui.autoPlace{max-height:100%;position:fixed;right:15px;top:0;z-index:1001}.lil-gui .controller{align-items:center;display:flex;margin:var(--spacing) 0;padding:0 var(--padding)}.lil-gui .controller.disabled{opacity:.5}.lil-gui .controller.disabled,.lil-gui .controller.disabled *{pointer-events:none!important}.lil-gui .controller>.name{flex-shrink:0;line-height:var(--widget-height);min-width:var(--name-width);padding-right:var(--spacing);white-space:pre}.lil-gui .controller .widget{align-items:center;display:flex;min-height:var(--widget-height);position:relative;width:100%}.lil-gui .controller.string input{color:var(--string-color)}.lil-gui .controller.boolean{cursor:pointer}.lil-gui .controller.color .display{border-radius:var(--widget-border-radius);height:var(--widget-height);position:relative;width:100%}.lil-gui .controller.color input[type=color]{cursor:pointer;height:100%;opacity:0;width:100%}.lil-gui .controller.color input[type=text]{flex-shrink:0;font-family:var(--font-family-mono);margin-left:var(--spacing);min-width:var(--color-input-min-width);width:var(--color-input-width)}.lil-gui .controller.option select{max-width:100%;opacity:0;position:absolute;width:100%}.lil-gui .controller.option .display{background:var(--widget-color);border-radius:var(--widget-border-radius);height:var(--widget-height);line-height:var(--widget-height);max-width:100%;overflow:hidden;padding-left:.55em;padding-right:1.75em;pointer-events:none;position:relative;word-break:break-all}.lil-gui .controller.option .display.active{background:var(--focus-color)}.lil-gui .controller.option .display:after{bottom:0;content:"↕";font-family:lil-gui;padding-right:.375em;position:absolute;right:0;top:0}.lil-gui .controller.option .widget,.lil-gui .controller.option select{cursor:pointer}.lil-gui .controller.number input{color:var(--number-color)}.lil-gui .controller.number.hasSlider input{flex-shrink:0;margin-left:var(--spacing);min-width:var(--slider-input-min-width);width:var(--slider-input-width)}.lil-gui .controller.number .slider{background:var(--widget-color);border-radius:var(--widget-border-radius);cursor:ew-resize;height:var(--widget-height);overflow:hidden;padding-right:var(--slider-knob-width);touch-action:pan-y;width:100%}.lil-gui .controller.number .slider.active{background:var(--focus-color)}.lil-gui .controller.number .slider.active .fill{opacity:.95}.lil-gui .controller.number .fill{border-right:var(--slider-knob-width) solid var(--number-color);box-sizing:content-box;height:100%}.lil-gui-dragging .lil-gui{--hover-color:var(--widget-color)}.lil-gui-dragging *{cursor:ew-resize!important}.lil-gui-dragging.lil-gui-vertical *{cursor:ns-resize!important}.lil-gui .title{-webkit-tap-highlight-color:transparent;text-decoration-skip:objects;cursor:pointer;font-weight:600;height:var(--title-height);line-height:calc(var(--title-height) - 4px);outline:none;padding:0 var(--padding)}.lil-gui .title:before{content:"▾";display:inline-block;font-family:lil-gui;padding-right:2px}.lil-gui .title:active{background:var(--title-background-color);opacity:.75}.lil-gui.root>.title:focus{text-decoration:none!important}.lil-gui.closed>.title:before{content:"▸"}.lil-gui.closed>.children{opacity:0;transform:translateY(-7px)}.lil-gui.closed:not(.transition)>.children{display:none}.lil-gui.transition>.children{overflow:hidden;pointer-events:none;transition-duration:.3s;transition-property:height,opacity,transform;transition-timing-function:cubic-bezier(.2,.6,.35,1)}.lil-gui .children:empty:before{content:"Empty";display:block;font-style:italic;height:var(--widget-height);line-height:var(--widget-height);margin:var(--spacing) 0;opacity:.5;padding:0 var(--padding)}.lil-gui.root>.children>.lil-gui>.title{border-width:0;border-bottom:1px solid var(--widget-color);border-left:0 solid var(--widget-color);border-right:0 solid var(--widget-color);border-top:1px solid var(--widget-color);transition:border-color .3s}.lil-gui.root>.children>.lil-gui.closed>.title{border-bottom-color:transparent}.lil-gui+.controller{border-top:1px solid var(--widget-color);margin-top:0;padding-top:var(--spacing)}.lil-gui .lil-gui .lil-gui>.title{border:none}.lil-gui .lil-gui .lil-gui>.children{border:none;border-left:2px solid var(--widget-color);margin-left:var(--folder-indent)}.lil-gui .lil-gui .controller{border:none}.lil-gui button,.lil-gui input,.lil-gui label{-webkit-tap-highlight-color:transparent}.lil-gui input{background:var(--widget-color);border:0;border-radius:var(--widget-border-radius);color:var(--text-color);font-family:var(--font-family);font-size:var(--input-font-size);height:var(--widget-height);outline:none;width:100%}.lil-gui input:disabled{opacity:1}.lil-gui input[type=number],.lil-gui input[type=text]{-moz-appearance:textfield;padding:var(--widget-padding)}.lil-gui input[type=number]:focus,.lil-gui input[type=text]:focus{background:var(--focus-color)}.lil-gui input[type=checkbox]{appearance:none;border-radius:var(--widget-border-radius);cursor:pointer;height:var(--checkbox-size);text-align:center;width:var(--checkbox-size)}.lil-gui input[type=checkbox]:checked:before{content:"✓";font-family:lil-gui;font-size:var(--checkbox-size);line-height:var(--checkbox-size)}.lil-gui button{background:var(--widget-color);border:none;border-radius:var(--widget-border-radius);color:var(--text-color);cursor:pointer;font-family:var(--font-family);font-size:var(--font-size);height:var(--widget-height);outline:none;text-transform:none;width:100%}.lil-gui button:active{background:var(--focus-color)}@font-face{font-family:lil-gui;src:url("data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAAAUsAAsAAAAACJwAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABHU1VCAAABCAAAAH4AAADAImwmYE9TLzIAAAGIAAAAPwAAAGBKqH5SY21hcAAAAcgAAAD0AAACrukyyJBnbHlmAAACvAAAAF8AAACEIZpWH2hlYWQAAAMcAAAAJwAAADZfcj2zaGhlYQAAA0QAAAAYAAAAJAC5AHhobXR4AAADXAAAABAAAABMAZAAAGxvY2EAAANsAAAAFAAAACgCEgIybWF4cAAAA4AAAAAeAAAAIAEfABJuYW1lAAADoAAAASIAAAIK9SUU/XBvc3QAAATEAAAAZgAAAJCTcMc2eJxVjbEOgjAURU+hFRBK1dGRL+ALnAiToyMLEzFpnPz/eAshwSa97517c/MwwJmeB9kwPl+0cf5+uGPZXsqPu4nvZabcSZldZ6kfyWnomFY/eScKqZNWupKJO6kXN3K9uCVoL7iInPr1X5baXs3tjuMqCtzEuagm/AAlzQgPAAB4nGNgYRBlnMDAysDAYM/gBiT5oLQBAwuDJAMDEwMrMwNWEJDmmsJwgCFeXZghBcjlZMgFCzOiKOIFAB71Bb8AeJy1kjFuwkAQRZ+DwRAwBtNQRUGKQ8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z+p762aNaeYXom2n3m2dLTVgsrCgFJ7OTmIkYbwIbC6vIB7WmFfAAAA==") format("woff")}@media (pointer:coarse){.lil-gui.allow-touch-styles,.lil-gui.allow-touch-styles .lil-gui{--widget-height:28px;--padding:6px;--spacing:6px;--font-size:13px;--input-font-size:16px;--folder-indent:10px;--scrollbar-width:7px;--slider-input-min-width:50px;--color-input-min-width:65px}}@media (hover:hover){.lil-gui .controller.color .display:hover:before{border:1px solid #fff9;border-radius:var(--widget-border-radius);bottom:0;content:" ";display:block;left:0;position:absolute;right:0;top:0}.lil-gui .controller.option .display.focus{background:var(--focus-color)}.lil-gui .controller.number .slider:hover,.lil-gui .controller.option .widget:hover .display{background:var(--hover-color)}body:not(.lil-gui-dragging) .lil-gui .title:hover{background:var(--title-background-color);opacity:.85}.lil-gui .title:focus{text-decoration:underline var(--focus-color)}.lil-gui input:hover{background:var(--hover-color)}.lil-gui input:active{background:var(--focus-color)}.lil-gui input[type=checkbox]:focus{box-shadow:inset 0 0 0 1px var(--focus-color)}.lil-gui button:hover{background:var(--hover-color)}.lil-gui button:focus{box-shadow:inset 0 0 0 1px var(--focus-color)}}'),p=!0),e?e.appendChild(this.domElement):i&&(this.domElement.classList.add("autoPlace"),document.body.appendChild(this.domElement)),s&&this.domElement.style.setProperty("--width",s+"px"),this._closeFolders=l}add(t,i,s,n,l){if(Object(s)===s)return new c(this,t,i,s);const r=t[i];switch(typeof r){case"number":return new d(this,t,i,s,n,l);case"boolean":return new e(this,t,i);case"string":return new u(this,t,i);case"function":return new h(this,t,i)}console.error("gui.add failed\n\tproperty:",i,"\n\tobject:",t,"\n\tvalue:",r)}addColor(t,i,e=1){return new a(this,t,i,e)}addFolder(t){const i=new g({parent:this,title:t});return this.root._closeFolders&&i.close(),i}load(t,i=!0){return t.controllers&&this.controllers.forEach(i=>{i instanceof h||i._name in t.controllers&&i.load(t.controllers[i._name])}),i&&t.folders&&this.folders.forEach(i=>{i._title in t.folders&&i.load(t.folders[i._title])}),this}save(t=!0){const i={controllers:{},folders:{}};return this.controllers.forEach(t=>{if(!(t instanceof h)){if(t._name in i.controllers)throw new Error(`Cannot save GUI with duplicate property "${t._name}"`);i.controllers[t._name]=t.save()}}),t&&this.folders.forEach(t=>{if(t._title in i.folders)throw new Error(`Cannot save GUI with duplicate folder "${t._title}"`);i.folders[t._title]=t.save()}),i}open(t=!0){return this._setClosed(!t),this.$title.setAttribute("aria-expanded",!this._closed),this.domElement.classList.toggle("closed",this._closed),this}close(){return this.open(!1)}_setClosed(t){this._closed!==t&&(this._closed=t,this._callOnOpenClose(this))}show(t=!0){return this._hidden=!t,this.domElement.style.display=this._hidden?"none":"",this}hide(){return this.show(!1)}openAnimated(t=!0){return this._setClosed(!t),this.$title.setAttribute("aria-expanded",!this._closed),requestAnimationFrame(()=>{const i=this.$children.clientHeight;this.$children.style.height=i+"px",this.domElement.classList.add("transition");const e=t=>{t.target===this.$children&&(this.$children.style.height="",this.domElement.classList.remove("transition"),this.$children.removeEventListener("transitionend",e))};this.$children.addEventListener("transitionend",e);const s=t?this.$children.scrollHeight:0;this.domElement.classList.toggle("closed",!t),requestAnimationFrame(()=>{this.$children.style.height=s+"px"})}),this}title(t){return this._title=t,this.$title.textContent=t,this}reset(t=!0){return(t?this.controllersRecursive():this.controllers).forEach(t=>t.reset()),this}onChange(t){return this._onChange=t,this}_callOnChange(t){this.parent&&this.parent._callOnChange(t),void 0!==this._onChange&&this._onChange.call(this,{object:t.object,property:t.property,value:t.getValue(),controller:t})}onFinishChange(t){return this._onFinishChange=t,this}_callOnFinishChange(t){this.parent&&this.parent._callOnFinishChange(t),void 0!==this._onFinishChange&&this._onFinishChange.call(this,{object:t.object,property:t.property,value:t.getValue(),controller:t})}onOpenClose(t){return this._onOpenClose=t,this}_callOnOpenClose(t){this.parent&&this.parent._callOnOpenClose(t),void 0!==this._onOpenClose&&this._onOpenClose.call(this,t)}destroy(){this.parent&&(this.parent.children.splice(this.parent.children.indexOf(this),1),this.parent.folders.splice(this.parent.folders.indexOf(this),1)),this.domElement.parentElement&&this.domElement.parentElement.removeChild(this.domElement),Array.from(this.children).forEach(t=>t.destroy())}controllersRecursive(){let t=Array.from(this.controllers);return this.folders.forEach(i=>{t=t.concat(i.controllersRecursive())}),t}foldersRecursive(){let t=Array.from(this.folders);return this.folders.forEach(i=>{t=t.concat(i.foldersRecursive())}),t}}t.BooleanController=e,t.ColorController=a,t.Controller=i,t.FunctionController=h,t.GUI=g,t.NumberController=d,t.OptionController=c,t.StringController=u,t.default=g,Object.defineProperty(t,"__esModule",{value:!0})})); diff --git a/inst/htmlwidgets/lib/time-control/time-control.css b/inst/htmlwidgets/lib/time-control/time-control.css new file mode 100644 index 0000000..73d37ca --- /dev/null +++ b/inst/htmlwidgets/lib/time-control/time-control.css @@ -0,0 +1,325 @@ +.mapgl-time-control-container { + background: #f7f8fa; + color: #222; + border-radius: 14px; + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, + Arial, sans-serif; + font-size: 12px; + box-shadow: 0 6px 24px rgba(0, 0, 0, 0.15); + width: 560px; + max-width: calc(100vw - 24px); + pointer-events: auto; + border: 1px solid rgba(0, 0, 0, 0.08); + margin: 10px; + padding: 8px 12px 6px 12px; + display: flex; + flex-direction: column; + gap: 4px; + box-sizing: border-box; +} + +.mapgl-time-control-container.dark-mode { + background: rgba(40, 48, 60, 0.92); + color: #e5e9f0; + border: 1px solid rgba(255, 255, 255, 0.08); + box-shadow: 0 10px 32px rgba(0, 0, 0, 0.45); + backdrop-filter: blur(8px); + -webkit-backdrop-filter: blur(8px); +} + +.mapgl-time-control-container.mapgl-pos-bottom-center { + position: absolute; + left: 50%; + transform: translateX(-50%); + bottom: 20px; + margin: 0 !important; + z-index: 10; +} + +.mapgl-time-control-container.mapgl-floating { + z-index: 10; + margin: 0; +} + +.mapgl-time-header { + display: flex; + align-items: center; + min-height: 24px; + gap: 6px; + user-select: none; +} + +.is-draggable .mapgl-time-header { + cursor: move; +} + +.mapgl-time-icon-btn { + width: 26px; + height: 26px; + border: none; + border-radius: 999px; + background: transparent; + color: inherit; + cursor: pointer; + display: inline-flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + padding: 0; + opacity: 0.78; + transition: opacity 0.15s, background 0.15s; +} + +.mapgl-time-icon-btn:hover { + opacity: 1; + background: rgba(127, 127, 127, 0.12); +} + +.mapgl-time-control-container:not(.is-collapsible) .mapgl-time-icon-btn { + display: none; +} + +.mapgl-time-icon-glyph { + font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, + "Segoe UI", sans-serif; + font-size: 17px; + line-height: 1; +} + +.mapgl-time-title { + flex: 0 1 auto; + font-weight: 600; + font-size: 11px; + opacity: 0.7; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +/* Body */ +.mapgl-time-body { + display: flex; + align-items: center; + gap: 12px; +} + +.is-collapsed .mapgl-time-body { + display: none; +} + +.mapgl-time-control-container.is-collapsed { + width: 38px; + height: 38px; + min-width: 38px; + max-width: 38px; + padding: 0; + border-radius: 999px; + gap: 0; +} + +.is-collapsed .mapgl-time-header { + width: 100%; + min-height: 100%; + justify-content: center; + gap: 0; +} + +.is-collapsed .mapgl-time-title, +.is-collapsed .mapgl-current-range-label, +.is-collapsed .mapgl-time-play-btn { + display: none; +} + +.is-collapsed .mapgl-time-icon-btn { + width: 100%; + height: 100%; + opacity: 0.9; +} + +.is-draggable.is-collapsed .mapgl-time-icon-btn { + cursor: move; +} + +.mapgl-time-play-btn { + background: transparent; + border: none; + cursor: pointer; + padding: 0; + width: 26px; + height: 26px; + border-radius: 999px; + display: inline-flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + color: inherit; + opacity: 0.78; + transition: opacity 0.15s, background 0.15s; +} + +.mapgl-time-play-btn:hover { + opacity: 1; + background: rgba(127, 127, 127, 0.12); +} + +.mapgl-time-play-btn svg { + fill: currentColor; + width: 14px; + height: 14px; +} + +.mapgl-timeline-wrapper { + flex-grow: 1; + height: 158px; + position: relative; +} + +.mapgl-current-range-label { + flex: 1 1 auto; + font-size: 11px; + font-weight: 600; + color: inherit; + opacity: 0.9; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + text-align: right; +} + +.dark-mode .mapgl-current-range-label { + color: #e5e9f0; +} + +.mapgl-time-hint { + color: #6b7280; + font-size: 10px; + line-height: 1.2; + margin-top: 2px; + text-align: center; + opacity: 0.72; + pointer-events: none; +} + +.dark-mode .mapgl-time-hint { + color: #c2c8d2; + opacity: 0.58; +} + +/* Axis */ +.mapgl-axis text { + fill: #555; + font-size: 10px; +} + +.mapgl-axis line, +.mapgl-axis path { + stroke: rgba(0, 0, 0, 0.15); + fill: none; +} + +.dark-mode .mapgl-axis text { + fill: #c2c8d2; +} + +.dark-mode .mapgl-axis line, +.dark-mode .mapgl-axis path { + stroke: rgba(255, 255, 255, 0.18); + fill: none; +} + +/* Bars */ +.mapgl-bar { + opacity: 0.55; + transition: opacity 0.15s; +} + +.dark-mode .mapgl-bar { + opacity: 0.65; +} + +.mapgl-bar:hover { + opacity: 1; +} + +/* Brush */ +.mapgl-brush .selection { + fill: currentColor; + fill-opacity: 0.22; + stroke: currentColor; + stroke-opacity: 0.7; + stroke-width: 1px; + shape-rendering: crispEdges; +} + +.dark-mode .mapgl-brush .selection { + fill-opacity: 0.28; +} + +.mapgl-selected-ranges { + pointer-events: none; +} + +.mapgl-selected-range { + fill: currentColor; + fill-opacity: 0.12; + stroke: currentColor; + stroke-opacity: 0.45; + stroke-width: 1px; + shape-rendering: crispEdges; + pointer-events: auto; + cursor: grab; +} + +.mapgl-selected-range:active { + cursor: grabbing; +} + +.dark-mode .mapgl-selected-range { + fill-opacity: 0.16; +} + +.mapgl-brush .handle { + fill: currentColor; + fill-opacity: 0.95; + stroke: none; + cursor: ew-resize; +} + +.mapgl-brush .handle--w, +.mapgl-brush .handle--e { + width: 4px !important; +} + +.mapgl-range-label { + font-size: 10px; + font-weight: 600; + fill: #222; + stroke: #f7f8fa; + stroke-width: 3px; + stroke-linejoin: round; + paint-order: stroke fill; + pointer-events: none; + user-select: none; +} + +.dark-mode .mapgl-range-label { + fill: #e5e9f0; + stroke: rgba(40, 48, 60, 0.92); +} + +.mapgl-range-handle { + fill: transparent; + cursor: ew-resize; + pointer-events: auto; + transition: fill 0.15s, fill-opacity 0.15s; +} + +.mapgl-range-handle:hover { + fill: currentColor; + fill-opacity: 0.35; +} + +.mapgl-y-axis .domain, +.mapgl-y-axis line { + display: none; +} diff --git a/inst/htmlwidgets/lib/time-control/time-control.js b/inst/htmlwidgets/lib/time-control/time-control.js new file mode 100644 index 0000000..0b0a01d --- /dev/null +++ b/inst/htmlwidgets/lib/time-control/time-control.js @@ -0,0 +1,926 @@ +(function () { + /** + * TimeControl: temporal scrubbing histogram with optional drag and collapse. + * Drives one or several layers (flowmap or ordinary Mapbox/MapLibre). + */ + class TimeControl { + constructor(options = {}) { + this.options = Object.assign( + { + id: "mapgl-time-control", + bins: [], + interval: "hour", + speed: 500, + loop: true, + initialRange: null, + targetLayerIds: null, + featureTimeProperty: "time", + featureTimeFormat: "iso", + accentColor: "#00bcd4", + darkMode: true, + position: "bottom-left", + draggable: false, + collapsible: false, + collapsed: false, + title: null, + }, + options, + ); + + this._isPlaying = false; + this._listeners = {}; + this._currentRange = null; + this._ranges = []; + this._isCollapsed = !!this.options.collapsed; + this._canCollapse = !!(this.options.collapsible || this.options.draggable); + } + + onAdd(map) { + this._map = map; + const opts = this.options; + + this._container = document.createElement("div"); + this._container.className = + "mapgl-time-control-container maplibregl-ctrl mapboxgl-ctrl"; + + if (opts.darkMode) this._container.classList.add("dark-mode"); + if (opts.draggable) this._container.classList.add("is-draggable"); + if (this._canCollapse) this._container.classList.add("is-collapsible"); + + this._header = document.createElement("div"); + this._header.className = "mapgl-time-header"; + + this._collapseBtn = document.createElement("button"); + this._collapseBtn.className = "mapgl-time-icon-btn"; + this._collapseBtn.type = "button"; + this._collapseBtn.innerHTML = this._clockIcon(); + this._collapseBtn.setAttribute( + "aria-label", + this._isCollapsed ? "Expand time control" : "Collapse time control", + ); + if (this._canCollapse) { + this._collapseBtn.onclick = (e) => { + if (this._dragged) { + this._dragged = false; + return; + } + this.toggleCollapse(); + }; + } else { + this._collapseBtn.tabIndex = -1; + this._collapseBtn.setAttribute("aria-hidden", "true"); + } + + this._playBtn = document.createElement("button"); + this._playBtn.type = "button"; + this._playBtn.className = "mapgl-time-play-btn"; + this._playBtn.innerHTML = this._getPlayIcon(); + this._playBtn.onclick = () => this.toggle(); + + const titleEl = document.createElement("span"); + titleEl.className = "mapgl-time-title"; + titleEl.textContent = opts.title || ""; + + this._label = document.createElement("div"); + this._label.className = "mapgl-current-range-label"; + + this._header.appendChild(this._collapseBtn); + this._header.appendChild(this._playBtn); + this._header.appendChild(titleEl); + this._header.appendChild(this._label); + this._container.appendChild(this._header); + + // Body (holds chart wrapper) + this._body = document.createElement("div"); + this._body.className = "mapgl-time-body"; + + const wrapper = document.createElement("div"); + wrapper.className = "mapgl-timeline-wrapper"; + + this._svgNode = document.createElementNS( + "http://www.w3.org/2000/svg", + "svg", + ); + wrapper.appendChild(this._svgNode); + + const hint = document.createElement("div"); + hint.className = "mapgl-time-hint"; + hint.textContent = "Shift + drag = select multiple | Double click = select all"; + wrapper.appendChild(hint); + + this._body.appendChild(wrapper); + this._container.appendChild(this._body); + + // Draggable: detach from corner and position absolutely on map container + if (opts.draggable || opts.position === "bottom-center") { + if (opts.position === "bottom-center") { + this._container.classList.add("mapgl-pos-bottom-center"); + } + if (opts.draggable) { + this._container.classList.add("mapgl-floating"); + // Default initial placement: bottom-left of map container + this._container.style.position = "absolute"; + this._container.style.left = "12px"; + this._container.style.bottom = "12px"; + this._container.style.right = "auto"; + this._container.style.top = "auto"; + this._setupDrag(); + } + map.getContainer().appendChild(this._container); + } + + if (this._isCollapsed) { + this._container.classList.add("is-collapsed"); + } + + this._retryCount = 0; + this._checkReadyAndInit(); + + return this._container; + } + + _clockIcon() { + return ''; + } + + toggleCollapse() { + if (!this._canCollapse) return; + this._isCollapsed = !this._isCollapsed; + this._container.classList.toggle("is-collapsed", this._isCollapsed); + if (this._collapseBtn) { + this._collapseBtn.setAttribute( + "aria-label", + this._isCollapsed ? "Expand time control" : "Collapse time control", + ); + } + } + + _setupDrag() { + const handle = this._header || this._container; + handle.style.cursor = "move"; + let startX, startY, originLeft, originTop, moved; + const onDown = (e) => { + const button = e.target.closest("button"); + if (button && button !== this._collapseBtn) return; + + if (!button) { + e.preventDefault(); + } + + this._dragged = false; + const rect = this._container.getBoundingClientRect(); + const parentRect = this._map.getContainer().getBoundingClientRect(); + originLeft = rect.left - parentRect.left; + originTop = rect.top - parentRect.top; + startX = e.clientX; + startY = e.clientY; + moved = false; + document.addEventListener("mousemove", onMove); + document.addEventListener("mouseup", onUp); + }; + const onMove = (e) => { + const dx = e.clientX - startX; + const dy = e.clientY - startY; + if (!moved && Math.abs(dx) + Math.abs(dy) < 3) return; + + e.preventDefault(); + e.stopPropagation(); + + if (!moved) { + moved = true; + this._dragged = true; + this._container.style.bottom = "auto"; + this._container.style.right = "auto"; + this._container.style.left = originLeft + "px"; + this._container.style.top = originTop + "px"; + } + this._container.style.left = originLeft + dx + "px"; + this._container.style.top = originTop + dy + "px"; + }; + const onUp = () => { + document.removeEventListener("mousemove", onMove); + document.removeEventListener("mouseup", onUp); + }; + handle.addEventListener("mousedown", onDown); + } + + _checkReadyAndInit() { + const width = this._svgNode.parentElement.clientWidth; + if (window.d3 && width > 50) { + this._initChart(); + } else if (this._retryCount < 100) { + this._retryCount++; + setTimeout(() => this._checkReadyAndInit(), 50); + } else { + if (!window.d3) console.error("D3.js missing for time-control."); + if (width <= 50) console.error("TimeControl container has 0 width."); + } + } + + onRemove() { + this.pause(); + if (this._container && this._container.parentNode) { + this._container.parentNode.removeChild(this._container); + } + this._map = undefined; + } + + _initChart() { + const d3 = window.d3; + const width = this._svgNode.parentElement.clientWidth; + const height = 140; + const margin = { top: 28, right: 10, bottom: 44, left: 46 }; + const innerWidth = width - margin.left - margin.right; + const innerHeight = height - margin.top - margin.bottom; + if (innerWidth <= 0) return; + + const svg = d3 + .select(this._svgNode) + .attr("width", width) + .attr("height", height); + + // Clear any existing elements inside the SVG to prevent duplicate overlapping charts + svg.selectAll("*").remove(); + + const g = svg + .append("g") + .attr("transform", `translate(${margin.left},${margin.top})`); + + let binsData = this.options.bins; + if (binsData && !Array.isArray(binsData) && typeof binsData === "object") { + const keys = Object.keys(binsData); + const rowCount = binsData[keys[0]].length; + binsData = Array.from({ length: rowCount }, (_, i) => { + const row = {}; + keys.forEach((k) => (row[k] = binsData[k][i])); + return row; + }); + } + const bins = binsData.map((d) => ({ + time: new Date(d.time), + count: +d.count, + })); + + const intervalMs = this._getIntervalMs(); + const domainEnd = new Date( + bins[bins.length - 1].time.getTime() + intervalMs, + ); + const x = d3 + .scaleTime() + .domain([bins[0].time, domainEnd]) + .range([0, innerWidth]); + const y = d3 + .scaleLinear() + .domain([0, d3.max(bins, (d) => d.count) || 1]) + .range([innerHeight, 0]); + + const barWidth = innerWidth / bins.length; + g.selectAll(".mapgl-bar") + .data(bins) + .enter() + .append("rect") + .attr("class", "mapgl-bar") + .attr("x", (d) => x(d.time) + 1) + .attr("y", (d) => y(d.count)) + .attr("width", Math.max(0.5, barWidth - 2)) + .attr("height", (d) => Math.max(0, innerHeight - y(d.count))) + .attr("rx", 1.5) + .attr("fill", this.options.accentColor); + + const timeFormat = + this.options.interval === "day" + ? d3.timeFormat("%b %d") + : d3.timeFormat("%H:%M"); + + // X-Axis + g.append("g") + .attr("class", "mapgl-axis") + .attr("transform", `translate(0,${innerHeight})`) + .call(d3.axisBottom(x).ticks(6).tickFormat(timeFormat)); + + // Y-Axis + const yMax = d3.max(bins, (d) => d.count) || 1; + const yTicks = Array.from(new Set([0, Math.round(yMax / 2), yMax])).sort((a, b) => a - b); + g.append("g") + .attr("class", "mapgl-axis mapgl-y-axis") + .call( + d3.axisLeft(y) + .tickValues(yTicks) + .tickFormat(d3.format(",")) + ); + + this._xScale = x; + this._innerWidth = innerWidth; + this._innerHeight = innerHeight; + + this._brush = d3 + .brushX() + .extent([ + [0, 0], + [innerWidth, innerHeight], + ]) + .on("brush end", (event) => this._handleBrush(event)); + this._brushGroup = g + .append("g") + .attr("class", "mapgl-brush") + .call(this._brush); + + svg.on("dblclick", (event) => { + event.preventDefault(); + event.stopPropagation(); + this._brushGroup.call(this._brush.move, [0, innerWidth]); + }); + + this._rangeOverlay = g + .append("g") + .attr("class", "mapgl-selected-ranges"); + + let initialSelection; + if (this.options.initialRange) { + initialSelection = [ + x(new Date(this.options.initialRange[0])), + x(new Date(this.options.initialRange[1])), + ]; + } else { + const start = bins[0].time; + const binsToSelect = Math.max(1, Math.round(bins.length * 0.2)); + const end = new Date( + start.getTime() + binsToSelect * intervalMs, + ); + initialSelection = [x(start), x(end)]; + } + this._brushGroup.call(this._brush.move, initialSelection); + this._renderRanges(); + } + + _handleBrush(event) { + if (event.type === "start") { + const append = + event && + event.sourceEvent && + event.sourceEvent.shiftKey && + this._ranges.length > 0; + + if (!append) { + this._ranges = []; + this._renderRanges(); + } + } + + if (!event.selection) { + if (this._activeLabel) this._activeLabel.style("display", "none"); + return; + } + + const range = this._selectionToRange(event.selection); + const ranges = this._rangesForBrush(range, event); + + this._currentRange = range; + this._updateLabel(ranges); + this._emit("change", ranges); + this._applyFilter(ranges); + + // Show active label hovering above the active brush rectangle + if (!this._activeLabel) { + this._activeLabel = this._brushGroup + .append("text") + .attr("class", "mapgl-range-label") + .attr("text-anchor", "middle"); + } + + const [s0, s1] = event.selection; + this._activeLabel + .attr("x", s0 + (s1 - s0) / 2) + .attr("y", -10) + .text(this._formatRange(range)) + .style("display", null); + + if (event.type === "end" && !this._isPlaying) { + this._ranges = ranges; + this._renderRanges(); + if (this._activeLabel) this._activeLabel.style("display", "none"); + this._brushGroup.call(this._brush.move, null); + } else if (event.type === "end") { + this._ranges = ranges; + this._renderRanges(); + } + } + + _selectionToRange(selection) { + return selection.map((value) => this._xScale.invert(value)); + } + + _rangesForBrush(range, event) { + const append = + event && + event.sourceEvent && + event.sourceEvent.shiftKey && + this._ranges.length > 0; + + return this._normalizeRanges( + append ? this._ranges.concat([range]) : [range], + ); + } + + _normalizeRanges(ranges) { + if ( + Array.isArray(ranges) && + ranges.length === 2 && + !Array.isArray(ranges[0]) + ) { + ranges = [ranges]; + } + + const normalized = ranges + .filter((range) => Array.isArray(range) && range.length === 2) + .map((range) => { + const start = new Date(range[0]); + const end = new Date(range[1]); + return start <= end ? [start, end] : [end, start]; + }) + .filter((range) => range[0].getTime() !== range[1].getTime()) + .sort((a, b) => a[0] - b[0]); + + return normalized.reduce((merged, range) => { + const previous = merged[merged.length - 1]; + if (previous && range[0] <= previous[1]) { + if (range[1] > previous[1]) previous[1] = range[1]; + } else { + merged.push(range); + } + return merged; + }, []); + } + + _renderRanges() { + if (!this._rangeOverlay || !this._xScale) return; + + // 1. Render selection rectangles + const rects = this._rangeOverlay + .selectAll(".mapgl-selected-range") + .data(this._ranges); + + rects + .enter() + .append("rect") + .attr("class", "mapgl-selected-range") + .merge(rects) + .attr("x", (d) => this._xScale(d[0])) + .attr("y", 0) + .attr("width", (d) => + Math.max(1, this._xScale(d[1]) - this._xScale(d[0])), + ) + .attr("height", this._innerHeight); + + rects.exit().remove(); + + // 2. Render left resize handles (west) + const handlesW = this._rangeOverlay + .selectAll(".mapgl-range-handle-w") + .data(this._ranges); + + handlesW + .enter() + .append("rect") + .attr("class", "mapgl-range-handle mapgl-range-handle-w") + .merge(handlesW) + .attr("x", (d) => this._xScale(d[0]) - 3) + .attr("y", 0) + .attr("width", 6) + .attr("height", this._innerHeight); + + handlesW.exit().remove(); + + // 3. Render right resize handles (east) + const handlesE = this._rangeOverlay + .selectAll(".mapgl-range-handle-e") + .data(this._ranges); + + handlesE + .enter() + .append("rect") + .attr("class", "mapgl-range-handle mapgl-range-handle-e") + .merge(handlesE) + .attr("x", (d) => this._xScale(d[1]) - 3) + .attr("y", 0) + .attr("width", 6) + .attr("height", this._innerHeight); + + handlesE.exit().remove(); + + // 4. Compute vertical positions (above/below) dynamically based on overlaps + const positions = []; + let lastAboveRight = -Infinity; + const padding = 12; // safety margin between labels + + for (let i = 0; i < this._ranges.length; i++) { + const d = this._ranges[i]; + const text = this._formatRange(d); + const textWidth = text.length * 6; // approximate text width + const cx = this._xScale(d[0]) + (this._xScale(d[1]) - this._xScale(d[0])) / 2; + const left = cx - textWidth / 2; + const right = cx + textWidth / 2; + + if (left < lastAboveRight + padding) { + positions.push("below"); + } else { + positions.push("above"); + lastAboveRight = right; + } + } + + // 5. Render text labels hovering above/below + const labels = this._rangeOverlay + .selectAll(".mapgl-range-label") + .data(this._ranges); + + labels + .enter() + .append("text") + .attr("class", "mapgl-range-label") + .attr("text-anchor", "middle") + .merge(labels) + .attr("x", (d) => { + const x0 = this._xScale(d[0]); + const x1 = this._xScale(d[1]); + return x0 + (x1 - x0) / 2; + }) + .attr("y", (d, i) => { + const pos = positions[i] || "above"; + return pos === "above" ? -10 : this._innerHeight + 32; + }) + .text((d) => this._formatRange(d)); + + labels.exit().remove(); + + this._setupRangeDrag(); + } + + _formatRange(range) { + const d3 = window.d3; + if (!d3) return ""; + const fmt = d3.timeFormat("%H:%M"); + const dateFmt = d3.timeFormat("%b %d"); + const fullFmt = d3.timeFormat("%Y-%m-%d %H:%M"); + if (this.options.interval === "day") { + return `${dateFmt(range[0])} — ${dateFmt(range[1])}`; + } else if (range[0].toDateString() === range[1].toDateString()) { + // When it's only one day, omit the date before time to save space! + return `${fmt(range[0])} — ${fmt(range[1])}`; + } else { + return `${fullFmt(range[0])} — ${fullFmt(range[1])}`; + } + } + + _setupRangeDrag() { + const d3 = window.d3; + if (!d3 || !this._rangeOverlay) return; + + const rects = this._rangeOverlay.selectAll(".mapgl-selected-range"); + const handlesW = this._rangeOverlay.selectAll(".mapgl-range-handle-w"); + const handlesE = this._rangeOverlay.selectAll(".mapgl-range-handle-e"); + + // 1. Drag main selection to move + const dragRect = d3.drag() + .on("start", (event, d) => { + if (event.sourceEvent) { + event.sourceEvent.preventDefault(); + event.sourceEvent.stopPropagation(); + } + event.subject.originalRange = [new Date(d[0]), new Date(d[1])]; + event.subject.startX = event.x; + }) + .on("drag", (event, d) => { + if (event.sourceEvent) { + event.sourceEvent.preventDefault(); + event.sourceEvent.stopPropagation(); + } + const dx = event.x - event.subject.startX; + + // Convert dx (pixels) to time offset (ms) using scale + const startX = this._xScale(event.subject.originalRange[0]) + dx; + + // Constrain within scale limits [0, innerWidth] + const minX = 0; + const maxX = this._innerWidth; + const widthPx = this._xScale(event.subject.originalRange[1]) - this._xScale(event.subject.originalRange[0]); + + let newStartX = startX; + if (newStartX < minX) { + newStartX = minX; + } else if (newStartX + widthPx > maxX) { + newStartX = maxX - widthPx; + } + + const newStart = this._xScale.invert(newStartX); + const newEnd = this._xScale.invert(newStartX + widthPx); + + // Mutate the range bounds in place so references remain valid + d[0] = newStart; + d[1] = newEnd; + + // Re-render immediately during drag to update positions and text + this._renderRanges(); + this._updateLabel(this._ranges); + this._applyFilter(this._ranges); + this._emit("change", this._ranges); + }) + .on("end", (event, d) => { + if (event.sourceEvent) { + event.sourceEvent.preventDefault(); + event.sourceEvent.stopPropagation(); + } + // Normalize (and merge overlapping ranges) on mouseup/end + this._ranges = this._normalizeRanges(this._ranges); + this._renderRanges(); + this._updateLabel(this._ranges); + this._applyFilter(this._ranges); + this._emit("change", this._ranges); + }); + + rects.call(dragRect); + + // 2. Drag left handle to resize start boundary + const dragLeft = d3.drag() + .on("start", (event, d) => { + if (event.sourceEvent) { + event.sourceEvent.preventDefault(); + event.sourceEvent.stopPropagation(); + } + event.subject.originalEnd = new Date(d[1]); + }) + .on("drag", (event, d) => { + if (event.sourceEvent) { + event.sourceEvent.preventDefault(); + event.sourceEvent.stopPropagation(); + } + let newX = event.x; + // Constrain: must be between 0 and the right boundary (leaving min 5px width) + const minX = 0; + const maxX = this._xScale(event.subject.originalEnd) - 5; + if (newX < minX) newX = minX; + if (newX > maxX) newX = maxX; + + const newStart = this._xScale.invert(newX); + + d[0] = newStart; + d[1] = event.subject.originalEnd; + + this._renderRanges(); + this._updateLabel(this._ranges); + this._applyFilter(this._ranges); + this._emit("change", this._ranges); + }) + .on("end", (event, d) => { + if (event.sourceEvent) { + event.sourceEvent.preventDefault(); + event.sourceEvent.stopPropagation(); + } + this._ranges = this._normalizeRanges(this._ranges); + this._renderRanges(); + this._updateLabel(this._ranges); + this._applyFilter(this._ranges); + this._emit("change", this._ranges); + }); + + handlesW.call(dragLeft); + + // 3. Drag right handle to resize end boundary + const dragRight = d3.drag() + .on("start", (event, d) => { + if (event.sourceEvent) { + event.sourceEvent.preventDefault(); + event.sourceEvent.stopPropagation(); + } + event.subject.originalStart = new Date(d[0]); + }) + .on("drag", (event, d) => { + if (event.sourceEvent) { + event.sourceEvent.preventDefault(); + event.sourceEvent.stopPropagation(); + } + let newX = event.x; + // Constrain: must be between left boundary (leaving min 5px width) and full width + const minX = this._xScale(event.subject.originalStart) + 5; + const maxX = this._innerWidth; + if (newX < minX) newX = minX; + if (newX > maxX) newX = maxX; + + const newEnd = this._xScale.invert(newX); + + d[0] = event.subject.originalStart; + d[1] = newEnd; + + this._renderRanges(); + this._updateLabel(this._ranges); + this._applyFilter(this._ranges); + this._emit("change", this._ranges); + }) + .on("end", (event, d) => { + if (event.sourceEvent) { + event.sourceEvent.preventDefault(); + event.sourceEvent.stopPropagation(); + } + this._ranges = this._normalizeRanges(this._ranges); + this._renderRanges(); + this._updateLabel(this._ranges); + this._applyFilter(this._ranges); + this._emit("change", this._ranges); + }); + + handlesE.call(dragRight); + } + + _getIntervalMs() { + switch (this.options.interval) { + case "hour": return 3600000; + case "day": return 86400000; + default: return 3600000; + } + } + + _applyFilter(ranges) { + if (!this._map) return; + const ids = this._resolveTargetIds(); + ids.forEach((id) => this._applyToLayer(id, ranges)); + } + + _resolveTargetIds() { + const explicit = this.options.targetLayerIds; + if (Array.isArray(explicit) && explicit.length > 0) { + return explicit.filter((s) => typeof s === "string"); + } + // Default: all flowmap layers + const map = this._map; + if (map && map._mapglFlowmapLayers) { + return map._mapglFlowmapLayers.map((l) => l.id); + } + return []; + } + + _applyToLayer(id, ranges) { + const map = this._map; + const normalizedRanges = this._normalizeRanges(ranges); + if (normalizedRanges.length === 0) return; + + // Flowmap layer? + if ( + window.MapGLFlowmapPlugin && + typeof window.MapGLFlowmapPlugin.hasLayer === "function" && + window.MapGLFlowmapPlugin.hasLayer(map, id) + ) { + const selectedTimeRanges = normalizedRanges.map((range) => [ + range[0].toISOString(), + range[1].toISOString(), + ]); + const filter = + selectedTimeRanges.length === 1 + ? { + selectedTimeRange: selectedTimeRanges[0], + selectedTimeRanges: null, + } + : { + selectedTimeRange: null, + selectedTimeRanges: selectedTimeRanges, + }; + window.MapGLFlowmapPlugin.setFilter(map, id, filter); + return; + } + + // Native map layer + if (typeof map.getLayer !== "function" || !map.getLayer(id)) return; + const clauses = normalizedRanges.map((range) => + this._nativeRangeFilter(range), + ); + const filter = clauses.length === 1 ? clauses[0] : ["any", ...clauses]; + try { + map.setFilter(id, filter); + } catch (e) { + console.warn("time-control: failed to setFilter on", id, e); + } + } + + _nativeRangeFilter(range) { + const prop = this.options.featureTimeProperty; + const fmt = this.options.featureTimeFormat; + let lo, hi; + if (fmt === "epoch_ms") { + lo = range[0].getTime(); + hi = range[1].getTime(); + } else if (fmt === "epoch_s") { + lo = Math.floor(range[0].getTime() / 1000); + hi = Math.floor(range[1].getTime() / 1000); + } else { + lo = range[0].toISOString(); + hi = range[1].toISOString(); + } + const numericGet = + fmt === "epoch_ms" || fmt === "epoch_s" + ? ["to-number", ["get", prop]] + : ["get", prop]; + return [ + "all", + [">=", numericGet, lo], + ["<", numericGet, hi], + ]; + } + + _updateLabel(ranges) { + const d3 = window.d3; + if (!d3) return; + const normalizedRanges = this._normalizeRanges(ranges); + if (normalizedRanges.length === 0) return; + + if (normalizedRanges.length > 1) { + this._label.innerText = `${normalizedRanges.length} selected ranges`; + return; + } + + const range = normalizedRanges[0]; + const fmt = d3.timeFormat("%H:%M"); + const dateFmt = d3.timeFormat("%b %d"); + const fullFmt = d3.timeFormat("%Y-%m-%d %H:%M"); + if (this.options.interval === "day") { + this._label.innerText = `${dateFmt(range[0])} — ${dateFmt(range[1])}`; + } else if (range[0].toDateString() === range[1].toDateString()) { + this._label.innerText = `${dateFmt(range[0])} ${fmt(range[0])} — ${fmt(range[1])}`; + } else { + this._label.innerText = `${fullFmt(range[0])} — ${fullFmt(range[1])}`; + } + } + + toggle() { if (this._isPlaying) this.pause(); else this.play(); } + play() { + if (this._isPlaying) return; + this._isPlaying = true; + this._playBtn.innerHTML = this._getPauseIcon(); + const d3 = window.d3; + if (d3) { + const selection = d3.brushSelection(this._brushGroup.node()); + if (!selection && this._ranges && this._ranges.length > 0) { + const r = this._ranges[0]; + this._brushGroup.call(this._brush.move, [this._xScale(r[0]), this._xScale(r[1])]); + } + } + this._animate(); + this._emit("play"); + } + pause() { + if (!this._isPlaying) return; + this._isPlaying = false; + this._playBtn.innerHTML = this._getPlayIcon(); + if (this._animationFrame) cancelAnimationFrame(this._animationFrame); + this._brushGroup.call(this._brush.move, null); + this._emit("pause"); + } + _animate() { + if (!this._isPlaying) return; + const d3 = window.d3; + if (!d3) return; + const selection = d3.brushSelection(this._brushGroup.node()); + if (!selection) return; + const width = selection[1] - selection[0]; + let nextStart = selection[0] + 1.5; + if (nextStart + width > this._innerWidth) { + if (this.options.loop) nextStart = 0; + else { this.pause(); return; } + } + this._brushGroup.call(this._brush.move, [nextStart, nextStart + width]); + this._animationFrame = requestAnimationFrame(() => this._animate()); + } + _getPlayIcon() { return ``; } + _getPauseIcon() { return ``; } + on(event, cb) { (this._listeners[event] ||= []).push(cb); } + _emit(event, data) { (this._listeners[event] || []).forEach((cb) => cb(data)); } + } + + function addControl(map, config) { + const tc = new TimeControl(config); + const floating = config.draggable || config.position === "bottom-center"; + if (floating) { + tc.onAdd(map); + } else { + map.addControl(tc, config.position); + } + if (!map.controls) map.controls = []; + map.controls.push({ type: "timeControl", control: tc }); + if (config.autoplay) setTimeout(() => tc.play(), 2000); + return tc; + } + + window.MapGLTimeControlPlugin = { + init: function (map, x) { + if (x.time_controls && x.time_controls.length > 0) { + x.time_controls.forEach((config) => addControl(map, config)); + } + }, + handleMessage: function (map, message) { + if (message.type === "add_time_control") { + addControl(map, message); + return true; + } + return false; + }, + }; + window.MapGLTimeControl = TimeControl; +})(); diff --git a/inst/htmlwidgets/mapboxgl.js b/inst/htmlwidgets/mapboxgl.js index d856649..9c1df35 100644 --- a/inst/htmlwidgets/mapboxgl.js +++ b/inst/htmlwidgets/mapboxgl.js @@ -2102,6 +2102,14 @@ HTMLWidgets.widget({ }); } + if (window.MapGLFlowmapPlugin) { + window.MapGLFlowmapPlugin.init(map, x, el, HTMLWidgets); + } + + if (window.MapGLLayerTuner && x.layer_tuner && x.layer_tuner.enabled) { + window.MapGLLayerTuner.init(map, x, el, HTMLWidgets); + } + // Apply setFilter if provided if (x.setFilter) { x.setFilter.forEach(function (filter) { @@ -2663,6 +2671,11 @@ HTMLWidgets.widget({ map.controls.push(fullscreen); } + // Add time controls if enabled + if (window.MapGLTimeControlPlugin) { + window.MapGLTimeControlPlugin.init(map, x); + } + // Add geolocate control if enabled if (x.geolocate_control) { const geolocate = new mapboxgl.GeolocateControl({ @@ -2919,6 +2932,26 @@ HTMLWidgets.widget({ x.layers_control.layers || map.getStyle().layers.map((layer) => layer.id); let layersConfig = x.layers_control.layers_config; + const getLayerControlVisibility = (layerId) => { + if ( + window.MapGLFlowmapPlugin && + window.MapGLFlowmapPlugin.hasLayer(map, layerId) + ) { + return window.MapGLFlowmapPlugin.getVisibility(map, layerId); + } + return map.getLayoutProperty(layerId, "visibility") || "visible"; + }; + const setLayerControlVisibility = (layerId, visibility) => { + if ( + window.MapGLFlowmapPlugin && + window.MapGLFlowmapPlugin.setVisibility(map, layerId, visibility) + ) { + return; + } + if (map.getLayer(layerId)) { + map.setLayoutProperty(layerId, "visibility", visibility); + } + }; // If we have a layers_config, use that; otherwise fall back to original behavior if (layersConfig && Array.isArray(layersConfig)) { @@ -2936,10 +2969,8 @@ HTMLWidgets.widget({ // Check if the first layer's visibility is set to "none" initially const firstLayerId = layerIds[0]; - const initialVisibility = map.getLayoutProperty( - firstLayerId, - "visibility", - ); + const initialVisibility = + getLayerControlVisibility(firstLayerId); link.className = initialVisibility === "none" ? "" : "active"; // Also hide any associated legends if the layer is initially hidden @@ -2963,15 +2994,12 @@ HTMLWidgets.widget({ this.getAttribute("data-layer-ids"), ); const firstLayerId = layerIds[0]; - const visibility = map.getLayoutProperty( - firstLayerId, - "visibility", - ); + const visibility = getLayerControlVisibility(firstLayerId); // Toggle visibility for all layer IDs in the group if (visibility === "visible") { layerIds.forEach((layerId) => { - map.setLayoutProperty(layerId, "visibility", "none"); + setLayerControlVisibility(layerId, "none"); // Hide associated legends const associatedLegends = document.querySelectorAll( `.mapboxgl-legend[data-layer-id="${layerId}"]`, @@ -2983,7 +3011,7 @@ HTMLWidgets.widget({ this.className = ""; } else { layerIds.forEach((layerId) => { - map.setLayoutProperty(layerId, "visibility", "visible"); + setLayerControlVisibility(layerId, "visible"); // Show associated legends const associatedLegends = document.querySelectorAll( `.mapboxgl-legend[data-layer-id="${layerId}"]`, @@ -3012,10 +3040,7 @@ HTMLWidgets.widget({ link.textContent = layerId; // Check if the layer visibility is set to "none" initially - const initialVisibility = map.getLayoutProperty( - layerId, - "visibility", - ); + const initialVisibility = getLayerControlVisibility(layerId); link.className = initialVisibility === "none" ? "" : "active"; // Also hide any associated legends if the layer is initially hidden @@ -3034,14 +3059,11 @@ HTMLWidgets.widget({ e.preventDefault(); e.stopPropagation(); - const visibility = map.getLayoutProperty( - clickedLayer, - "visibility", - ); + const visibility = getLayerControlVisibility(clickedLayer); // Toggle layer visibility by changing the layout object's visibility property if (visibility === "visible") { - map.setLayoutProperty(clickedLayer, "visibility", "none"); + setLayerControlVisibility(clickedLayer, "none"); this.className = ""; // Hide associated legends @@ -3053,11 +3075,7 @@ HTMLWidgets.widget({ }); } else { this.className = "active"; - map.setLayoutProperty( - clickedLayer, - "visibility", - "visible", - ); + setLayerControlVisibility(clickedLayer, "visible"); // Show associated legends const associatedLegends = document.querySelectorAll( @@ -3691,6 +3709,18 @@ if (HTMLWidgets.shinyMode) { } layerState.layoutProperties[message.layer][message.name] = message.value; + } else if (message.type === "set_flowmap_filter") { + if (window.MapGLFlowmapPlugin) { + window.MapGLFlowmapPlugin.setFilter(map, message.id, message.filter); + } + } else if (message.type === "set_flowmap_settings") { + if (window.MapGLFlowmapPlugin) { + window.MapGLFlowmapPlugin.setSettings( + map, + message.id, + message.settings, + ); + } } else if (message.type === "set_paint_property") { const layerId = message.layer; const propertyName = message.name; @@ -4673,6 +4703,11 @@ if (HTMLWidgets.shinyMode) { const fullscreen = new mapboxgl.FullscreenControl(); map.addControl(fullscreen, position); map.controls.push({ type: "fullscreen", control: fullscreen }); + } else if ( + window.MapGLTimeControlPlugin && + window.MapGLTimeControlPlugin.handleMessage(map, message) + ) { + // Handled by plugin } else if (message.type === "add_scale_control") { const scaleControl = new mapboxgl.ScaleControl({ maxWidth: message.options.maxWidth, @@ -5319,6 +5354,15 @@ if (HTMLWidgets.shinyMode) { const globeMinimap = new GlobeMinimap(globeMinimapOptions); map.addControl(globeMinimap, message.position || "bottom-left"); map.controls.push({ type: "globe_minimap", control: globeMinimap }); + } else if (message.type === "add_layer_tuner") { + if (window.MapGLLayerTuner) { + window.MapGLLayerTuner.init( + map, + { layer_tuner: message.layer_tuner || { enabled: true, layers: message.layers } }, + el, + HTMLWidgets + ); + } } } }); diff --git a/inst/htmlwidgets/mapboxgl.yaml b/inst/htmlwidgets/mapboxgl.yaml index 6964fa1..02aef7f 100644 --- a/inst/htmlwidgets/mapboxgl.yaml +++ b/inst/htmlwidgets/mapboxgl.yaml @@ -85,3 +85,33 @@ dependencies: - "legend-interactivity.js" stylesheet: - "legend-interactivity.css" + - name: flowmap-gl + version: "9.3.0" + src: "htmlwidgets/lib/flowmap-gl" + script: + - "flowmap-gl-bundle.min.js" + - name: flowmap-plugin + version: "1.0.0" + src: "htmlwidgets" + script: + - "flowmap.js" + stylesheet: + - "flowmap.css" + - name: lil-gui + version: "0.19.0" + src: "htmlwidgets/lib/lil-gui" + script: + - "lil-gui.umd.min.js" + - name: d3 + version: "7.9.0" + src: "htmlwidgets/lib/d3" + script: + - "d3.min.js" + + - name: time-control + version: "1.0.0" + src: "htmlwidgets/lib/time-control" + script: + - "time-control.js" + stylesheet: + - "time-control.css" diff --git a/inst/htmlwidgets/mapboxgl_compare.js b/inst/htmlwidgets/mapboxgl_compare.js index b9a4e46..a6e1207 100644 --- a/inst/htmlwidgets/mapboxgl_compare.js +++ b/inst/htmlwidgets/mapboxgl_compare.js @@ -506,6 +506,22 @@ HTMLWidgets.widget({ // Set the global access token mapboxgl.accessToken = x.map1.access_token; + beforeMap.on("style.load", function () { + if (!beforeMap._basemapLayerIds) { + beforeMap._basemapLayerIds = new Set( + beforeMap.getStyle().layers.map((layer) => layer.id), + ); + } + }); + + afterMap.on("style.load", function () { + if (!afterMap._basemapLayerIds) { + afterMap._basemapLayerIds = new Set( + afterMap.getStyle().layers.map((layer) => layer.id), + ); + } + }); + if (x.mode === "swipe") { // Only create the swiper in swipe mode compareControl = new mapboxgl.Compare( @@ -1104,6 +1120,22 @@ HTMLWidgets.widget({ } layerState.layoutProperties[message.layer][message.name] = message.value; + } else if (message.type === "set_flowmap_filter") { + if (window.MapGLFlowmapPlugin) { + window.MapGLFlowmapPlugin.setFilter( + map, + message.id, + message.filter, + ); + } + } else if (message.type === "set_flowmap_settings") { + if (window.MapGLFlowmapPlugin) { + window.MapGLFlowmapPlugin.setSettings( + map, + message.id, + message.settings, + ); + } } else if (message.type === "set_paint_property") { const layerId = message.layer; const propertyName = message.name; @@ -2425,6 +2457,46 @@ HTMLWidgets.widget({ } } + function ensureCompareLayerTunerHost(map) { + const side = map === beforeMap ? "before" : "after"; + const hostId = `${el.id}-${side}-layer-tuner-host`; + let host = document.getElementById(hostId); + if (host) { + return host; + } + + host = document.createElement("div"); + host.id = hostId; + host.className = "mapgl-compare-layer-tuner-host"; + host.style.position = "absolute"; + host.style.zIndex = "10000"; + host.style.pointerEvents = "none"; + host.style.overflow = "visible"; + + if (x.orientation === "horizontal") { + host.style.left = "0"; + host.style.width = "100%"; + host.style.height = "50%"; + if (side === "before") { + host.style.top = "0"; + } else { + host.style.top = "50%"; + } + } else { + host.style.top = "0"; + host.style.width = "50%"; + host.style.height = "100%"; + if (side === "before") { + host.style.left = "0"; + } else { + host.style.left = "50%"; + } + } + + el.appendChild(host); + return host; + } + function applyMapModifications(map, mapData) { // Initialize controls array if it doesn't exist if (!map.controls) { @@ -2732,6 +2804,38 @@ HTMLWidgets.widget({ }); } + if (mapData.flowmaps) { + if (window.MapGLFlowmapPlugin) { + const flowmapEl = { + id: `${el.id}-${map === beforeMap ? "before" : "after"}`, + }; + window.MapGLFlowmapPlugin.init( + map, + mapData, + flowmapEl, + HTMLWidgets, + ); + } else { + console.error("Flowmap plugin is not loaded. Cannot add flowmap layers."); + } + } + + if ( + window.MapGLLayerTuner && + mapData.layer_tuner && + mapData.layer_tuner.enabled + ) { + window.MapGLLayerTuner.init( + map, + mapData, + ensureCompareLayerTunerHost(map), + HTMLWidgets, + ); + if (map._layerTunerGui && map._layerTunerGui.domElement) { + map._layerTunerGui.domElement.style.pointerEvents = "auto"; + } + } + // Set terrain if provided if (mapData.terrain) { map.setTerrain({ @@ -3496,6 +3600,43 @@ HTMLWidgets.widget({ mapData.layers_control.layers || map.getStyle().layers.map((layer) => layer.id); let layersConfig = mapData.layers_control.layers_config; + const getLayerControlVisibility = (targetMap, layerId) => { + if ( + window.MapGLFlowmapPlugin && + window.MapGLFlowmapPlugin.hasLayer(targetMap, layerId) + ) { + return window.MapGLFlowmapPlugin.getVisibility( + targetMap, + layerId, + ); + } + if (targetMap.getLayer(layerId)) { + return ( + targetMap.getLayoutProperty(layerId, "visibility") || + "visible" + ); + } + return "visible"; + }; + const setLayerControlVisibility = ( + targetMap, + layerId, + visibility, + ) => { + if ( + window.MapGLFlowmapPlugin && + window.MapGLFlowmapPlugin.setVisibility( + targetMap, + layerId, + visibility, + ) + ) { + return; + } + if (targetMap.getLayer(layerId)) { + targetMap.setLayoutProperty(layerId, "visibility", visibility); + } + }; // If we have a layers_config, use that; otherwise fall back to original behavior if (layersConfig && Array.isArray(layersConfig)) { @@ -3513,9 +3654,9 @@ HTMLWidgets.widget({ // Check if the first layer's visibility is set to "none" initially const firstLayerId = layerIds[0]; - const initialVisibility = map.getLayoutProperty( + const initialVisibility = getLayerControlVisibility( + map, firstLayerId, - "visibility", ); link.className = initialVisibility === "none" ? "" : "active"; @@ -3528,20 +3669,20 @@ HTMLWidgets.widget({ this.getAttribute("data-layer-ids"), ); const firstLayerId = layerIds[0]; - const visibility = map.getLayoutProperty( + const visibility = getLayerControlVisibility( + map, firstLayerId, - "visibility", ); // Toggle visibility for all layer IDs in the group if (visibility === "visible") { layerIds.forEach((layerId) => { - map.setLayoutProperty(layerId, "visibility", "none"); + setLayerControlVisibility(map, layerId, "none"); }); this.className = ""; } else { layerIds.forEach((layerId) => { - map.setLayoutProperty(layerId, "visibility", "visible"); + setLayerControlVisibility(map, layerId, "visible"); }); this.className = "active"; } @@ -3564,22 +3705,18 @@ HTMLWidgets.widget({ e.preventDefault(); e.stopPropagation(); - const visibility = map.getLayoutProperty( + const visibility = getLayerControlVisibility( + map, clickedLayer, - "visibility", ); // Toggle layer visibility by changing the layout object's visibility property if (visibility === "visible") { - map.setLayoutProperty(clickedLayer, "visibility", "none"); + setLayerControlVisibility(map, clickedLayer, "none"); this.className = ""; } else { this.className = "active"; - map.setLayoutProperty( - clickedLayer, - "visibility", - "visible", - ); + setLayerControlVisibility(map, clickedLayer, "visible"); } }; diff --git a/inst/htmlwidgets/mapboxgl_compare.yaml b/inst/htmlwidgets/mapboxgl_compare.yaml index 9cc6e38..3d15417 100644 --- a/inst/htmlwidgets/mapboxgl_compare.yaml +++ b/inst/htmlwidgets/mapboxgl_compare.yaml @@ -62,3 +62,15 @@ dependencies: - "legend-interactivity.js" stylesheet: - "legend-interactivity.css" + - name: flowmap-gl + version: "9.3.0" + src: "htmlwidgets/lib/flowmap-gl" + script: + - "flowmap-gl-bundle.min.js" + - name: flowmap-plugin + version: "1.0.0" + src: "htmlwidgets" + script: + - "flowmap.js" + stylesheet: + - "flowmap.css" diff --git a/inst/htmlwidgets/maplibregl.js b/inst/htmlwidgets/maplibregl.js index 1771769..b3b7cb9 100644 --- a/inst/htmlwidgets/maplibregl.js +++ b/inst/htmlwidgets/maplibregl.js @@ -2157,6 +2157,14 @@ HTMLWidgets.widget({ x.layers.forEach((layer) => add_my_layers(layer)); } + if (window.MapGLFlowmapPlugin) { + window.MapGLFlowmapPlugin.init(map, x, el, HTMLWidgets); + } + + if (window.MapGLLayerTuner && x.layer_tuner && x.layer_tuner.enabled) { + window.MapGLLayerTuner.init(map, x, el, HTMLWidgets); + } + // Apply setFilter if provided if (x.setFilter) { x.setFilter.forEach(function (filter) { @@ -2825,6 +2833,11 @@ HTMLWidgets.widget({ map.controls.push({ type: "fullscreen", control: fullscreen }); } + // Add time controls if enabled + if (window.MapGLTimeControlPlugin) { + window.MapGLTimeControlPlugin.init(map, x); + } + // Add geolocate control if enabled if (x.geolocate_control) { const geolocate = new maplibregl.GeolocateControl({ @@ -3061,6 +3074,26 @@ HTMLWidgets.widget({ x.layers_control.layers || map.getStyle().layers.map((layer) => layer.id); let layersConfig = x.layers_control.layers_config; + const getLayerControlVisibility = (layerId) => { + if ( + window.MapGLFlowmapPlugin && + window.MapGLFlowmapPlugin.hasLayer(map, layerId) + ) { + return window.MapGLFlowmapPlugin.getVisibility(map, layerId); + } + return map.getLayoutProperty(layerId, "visibility") || "visible"; + }; + const setLayerControlVisibility = (layerId, visibility) => { + if ( + window.MapGLFlowmapPlugin && + window.MapGLFlowmapPlugin.setVisibility(map, layerId, visibility) + ) { + return; + } + if (map.getLayer(layerId)) { + map.setLayoutProperty(layerId, "visibility", visibility); + } + }; // If we have a layers_config, use that; otherwise fall back to original behavior if (layersConfig && Array.isArray(layersConfig)) { @@ -3078,10 +3111,8 @@ HTMLWidgets.widget({ // Check if the first layer's visibility is set to "none" initially const firstLayerId = layerIds[0]; - const initialVisibility = map.getLayoutProperty( - firstLayerId, - "visibility", - ); + const initialVisibility = + getLayerControlVisibility(firstLayerId); link.className = initialVisibility === "none" ? "" : "active"; // Also hide any associated legends if the layer is initially hidden @@ -3105,15 +3136,12 @@ HTMLWidgets.widget({ this.getAttribute("data-layer-ids"), ); const firstLayerId = layerIds[0]; - const visibility = map.getLayoutProperty( - firstLayerId, - "visibility", - ); + const visibility = getLayerControlVisibility(firstLayerId); // Toggle visibility for all layer IDs in the group if (visibility === "visible") { layerIds.forEach((layerId) => { - map.setLayoutProperty(layerId, "visibility", "none"); + setLayerControlVisibility(layerId, "none"); // Hide associated legends const associatedLegends = document.querySelectorAll( `.mapboxgl-legend[data-layer-id="${layerId}"]`, @@ -3125,7 +3153,7 @@ HTMLWidgets.widget({ this.className = ""; } else { layerIds.forEach((layerId) => { - map.setLayoutProperty(layerId, "visibility", "visible"); + setLayerControlVisibility(layerId, "visible"); // Show associated legends const associatedLegends = document.querySelectorAll( `.mapboxgl-legend[data-layer-id="${layerId}"]`, @@ -3154,10 +3182,7 @@ HTMLWidgets.widget({ link.textContent = layerId; // Check if the layer visibility is set to "none" initially - const initialVisibility = map.getLayoutProperty( - layerId, - "visibility", - ); + const initialVisibility = getLayerControlVisibility(layerId); link.className = initialVisibility === "none" ? "" : "active"; // Also hide any associated legends if the layer is initially hidden @@ -3176,14 +3201,11 @@ HTMLWidgets.widget({ e.preventDefault(); e.stopPropagation(); - const visibility = map.getLayoutProperty( - clickedLayer, - "visibility", - ); + const visibility = getLayerControlVisibility(clickedLayer); // Toggle layer visibility by changing the layout object's visibility property if (visibility === "visible") { - map.setLayoutProperty(clickedLayer, "visibility", "none"); + setLayerControlVisibility(clickedLayer, "none"); this.className = ""; // Hide associated legends @@ -3195,11 +3217,7 @@ HTMLWidgets.widget({ }); } else { this.className = "active"; - map.setLayoutProperty( - clickedLayer, - "visibility", - "visible", - ); + setLayerControlVisibility(clickedLayer, "visible"); // Show associated legends const associatedLegends = document.querySelectorAll( @@ -3781,6 +3799,18 @@ if (HTMLWidgets.shinyMode) { } layerState.layoutProperties[message.layer][message.name] = message.value; + } else if (message.type === "set_flowmap_filter") { + if (window.MapGLFlowmapPlugin) { + window.MapGLFlowmapPlugin.setFilter(map, message.id, message.filter); + } + } else if (message.type === "set_flowmap_settings") { + if (window.MapGLFlowmapPlugin) { + window.MapGLFlowmapPlugin.setSettings( + map, + message.id, + message.settings, + ); + } } else if (message.type === "set_paint_property") { const layerId = message.layer; const propertyName = message.name; @@ -5794,6 +5824,11 @@ if (HTMLWidgets.shinyMode) { const fullscreen = new maplibregl.FullscreenControl(); map.addControl(fullscreen, position); map.controls.push({ type: "fullscreen", control: fullscreen }); + } else if ( + window.MapGLTimeControlPlugin && + window.MapGLTimeControlPlugin.handleMessage(map, message) + ) { + // Handled by plugin } else if (message.type === "add_scale_control") { const scaleControl = new maplibregl.ScaleControl({ maxWidth: message.options.maxWidth, @@ -6528,6 +6563,15 @@ if (HTMLWidgets.shinyMode) { const globeMinimap = new GlobeMinimap(globeMinimapOptions); map.addControl(globeMinimap, message.position || "bottom-left"); map.controls.push({ type: "globe_minimap", control: globeMinimap }); + } else if (message.type === "add_layer_tuner") { + if (window.MapGLLayerTuner) { + window.MapGLLayerTuner.init( + map, + { layer_tuner: message.layer_tuner || { enabled: true, layers: message.layers } }, + el, + HTMLWidgets + ); + } } else if (message.type === "add_globe_control") { const globeControl = new maplibregl.GlobeControl(); map.addControl(globeControl, message.position); diff --git a/inst/htmlwidgets/maplibregl.yaml b/inst/htmlwidgets/maplibregl.yaml index 9aa0f07..2245af9 100644 --- a/inst/htmlwidgets/maplibregl.yaml +++ b/inst/htmlwidgets/maplibregl.yaml @@ -89,3 +89,33 @@ dependencies: - "legend-interactivity.js" stylesheet: - "legend-interactivity.css" + - name: flowmap-gl + version: "9.3.0" + src: "htmlwidgets/lib/flowmap-gl" + script: + - "flowmap-gl-bundle.min.js" + - name: flowmap-plugin + version: "1.0.0" + src: "htmlwidgets" + script: + - "flowmap.js" + stylesheet: + - "flowmap.css" + - name: lil-gui + version: "0.19.0" + src: "htmlwidgets/lib/lil-gui" + script: + - "lil-gui.umd.min.js" + - name: d3 + version: "7.9.0" + src: "htmlwidgets/lib/d3" + script: + - "d3.min.js" + + - name: time-control + version: "1.0.0" + src: "htmlwidgets/lib/time-control" + script: + - "time-control.js" + stylesheet: + - "time-control.css" diff --git a/inst/htmlwidgets/maplibregl_compare.js b/inst/htmlwidgets/maplibregl_compare.js index c522d88..b911e60 100644 --- a/inst/htmlwidgets/maplibregl_compare.js +++ b/inst/htmlwidgets/maplibregl_compare.js @@ -485,6 +485,12 @@ HTMLWidgets.widget({ // Set projection on style load (MapLibre doesn't support projection in constructor) beforeMap.on("style.load", function () { + if (!beforeMap._basemapLayerIds) { + beforeMap._basemapLayerIds = new Set( + beforeMap.getStyle().layers.map((layer) => layer.id), + ); + } + if (x.map1.projection) { beforeMap.setProjection({ type: x.map1.projection }); } @@ -506,6 +512,12 @@ HTMLWidgets.widget({ // Set projection on style load (MapLibre doesn't support projection in constructor) afterMap.on("style.load", function () { + if (!afterMap._basemapLayerIds) { + afterMap._basemapLayerIds = new Set( + afterMap.getStyle().layers.map((layer) => layer.id), + ); + } + if (x.map2.projection) { afterMap.setProjection({ type: x.map2.projection }); } @@ -1157,6 +1169,22 @@ HTMLWidgets.widget({ } layerState.layoutProperties[message.layer][message.name] = message.value; + } else if (message.type === "set_flowmap_filter") { + if (window.MapGLFlowmapPlugin) { + window.MapGLFlowmapPlugin.setFilter( + map, + message.id, + message.filter, + ); + } + } else if (message.type === "set_flowmap_settings") { + if (window.MapGLFlowmapPlugin) { + window.MapGLFlowmapPlugin.setSettings( + map, + message.id, + message.settings, + ); + } } else if (message.type === "set_paint_property") { const layerId = message.layer; const propertyName = message.name; @@ -3098,6 +3126,46 @@ HTMLWidgets.widget({ } } + function ensureCompareLayerTunerHost(map) { + const side = map === beforeMap ? "before" : "after"; + const hostId = `${el.id}-${side}-layer-tuner-host`; + let host = document.getElementById(hostId); + if (host) { + return host; + } + + host = document.createElement("div"); + host.id = hostId; + host.className = "mapgl-compare-layer-tuner-host"; + host.style.position = "absolute"; + host.style.zIndex = "10000"; + host.style.pointerEvents = "none"; + host.style.overflow = "visible"; + + if (x.orientation === "horizontal") { + host.style.left = "0"; + host.style.width = "100%"; + host.style.height = "50%"; + if (side === "before") { + host.style.top = "0"; + } else { + host.style.top = "50%"; + } + } else { + host.style.top = "0"; + host.style.width = "50%"; + host.style.height = "100%"; + if (side === "before") { + host.style.left = "0"; + } else { + host.style.left = "50%"; + } + } + + el.appendChild(host); + return host; + } + async function applyMapModifications(map, mapData) { // Initialize controls array if it doesn't exist if (!map.controls) { @@ -3617,6 +3685,38 @@ HTMLWidgets.widget({ }); } + if (mapData.flowmaps) { + if (window.MapGLFlowmapPlugin) { + const flowmapEl = { + id: `${el.id}-${map === beforeMap ? "before" : "after"}`, + }; + window.MapGLFlowmapPlugin.init( + map, + mapData, + flowmapEl, + HTMLWidgets, + ); + } else { + console.error("Flowmap plugin is not loaded. Cannot add flowmap layers."); + } + } + + if ( + window.MapGLLayerTuner && + mapData.layer_tuner && + mapData.layer_tuner.enabled + ) { + window.MapGLLayerTuner.init( + map, + mapData, + ensureCompareLayerTunerHost(map), + HTMLWidgets, + ); + if (map._layerTunerGui && map._layerTunerGui.domElement) { + map._layerTunerGui.domElement.style.pointerEvents = "auto"; + } + } + // Set terrain if provided if (mapData.terrain) { map.setTerrain({ @@ -4487,6 +4587,43 @@ HTMLWidgets.widget({ mapData.layers_control.layers || map.getStyle().layers.map((layer) => layer.id); let layersConfig = mapData.layers_control.layers_config; + const getLayerControlVisibility = (targetMap, layerId) => { + if ( + window.MapGLFlowmapPlugin && + window.MapGLFlowmapPlugin.hasLayer(targetMap, layerId) + ) { + return window.MapGLFlowmapPlugin.getVisibility( + targetMap, + layerId, + ); + } + if (targetMap.getLayer(layerId)) { + return ( + targetMap.getLayoutProperty(layerId, "visibility") || + "visible" + ); + } + return "visible"; + }; + const setLayerControlVisibility = ( + targetMap, + layerId, + visibility, + ) => { + if ( + window.MapGLFlowmapPlugin && + window.MapGLFlowmapPlugin.setVisibility( + targetMap, + layerId, + visibility, + ) + ) { + return; + } + if (targetMap.getLayer(layerId)) { + targetMap.setLayoutProperty(layerId, "visibility", visibility); + } + }; // If we have a layers_config, use that; otherwise fall back to original behavior if (layersConfig && Array.isArray(layersConfig)) { @@ -4504,9 +4641,9 @@ HTMLWidgets.widget({ // Check if the first layer's visibility is set to "none" initially const firstLayerId = layerIds[0]; - const initialVisibility = map.getLayoutProperty( + const initialVisibility = getLayerControlVisibility( + map, firstLayerId, - "visibility", ); link.className = initialVisibility === "none" ? "" : "active"; @@ -4520,16 +4657,16 @@ HTMLWidgets.widget({ this.getAttribute("data-layer-ids"), ); const firstLayerId = layerIds[0]; - const visibility = map.getLayoutProperty( + const visibility = getLayerControlVisibility( + map, firstLayerId, - "visibility", ); const newVis = visibility === "visible" ? "none" : "visible"; const allMaps = [beforeMap, afterMap]; layerIds.forEach((layerId) => { allMaps.forEach((m) => { - try { m.setLayoutProperty(layerId, "visibility", newVis); } catch(err) {} + setLayerControlVisibility(m, layerId, newVis); }); }); this.className = newVis === "visible" ? "active" : ""; @@ -4553,15 +4690,15 @@ HTMLWidgets.widget({ e.preventDefault(); e.stopPropagation(); - const visibility = map.getLayoutProperty( + const visibility = getLayerControlVisibility( + map, clickedLayer, - "visibility", ); // toggle on BOTH maps in the compare widget const newVis = visibility === "visible" ? "none" : "visible"; [beforeMap, afterMap].forEach((m) => { - try { m.setLayoutProperty(clickedLayer, "visibility", newVis); } catch(err) {} + setLayerControlVisibility(m, clickedLayer, newVis); }); this.className = newVis === "visible" ? "active" : ""; }; diff --git a/inst/htmlwidgets/maplibregl_compare.yaml b/inst/htmlwidgets/maplibregl_compare.yaml index cde719e..7784774 100644 --- a/inst/htmlwidgets/maplibregl_compare.yaml +++ b/inst/htmlwidgets/maplibregl_compare.yaml @@ -72,3 +72,15 @@ dependencies: - "legend-interactivity.js" stylesheet: - "legend-interactivity.css" + - name: flowmap-gl + version: "9.3.0" + src: "htmlwidgets/lib/flowmap-gl" + script: + - "flowmap-gl-bundle.min.js" + - name: flowmap-plugin + version: "1.0.0" + src: "htmlwidgets" + script: + - "flowmap.js" + stylesheet: + - "flowmap.css" diff --git a/inst/htmlwidgets/screenshot.js b/inst/htmlwidgets/screenshot.js index 3513708..1f663f3 100644 --- a/inst/htmlwidgets/screenshot.js +++ b/inst/htmlwidgets/screenshot.js @@ -84,7 +84,7 @@ function applyMapScreenshotOptions(map, options) { el.style.display = 'none'; }); // Also hide layers control, measurement box, and geocoder controls - container.querySelectorAll('.layers-control, .mapgl-measurement-box, .mapgl-coordinates-control, .maplibregl-ctrl-geocoder, .mapboxgl-ctrl-geocoder, .maptiler-ctrl').forEach(el => { + container.querySelectorAll('.layers-control, .mapgl-measurement-box, .mapgl-coordinates-control, .maplibregl-ctrl-geocoder, .mapboxgl-ctrl-geocoder, .maptiler-ctrl, .lil-gui').forEach(el => { hiddenElements.push({ element: el, display: el.style.display }); el.style.display = 'none'; }); @@ -190,6 +190,171 @@ async function prepareMapForScreenshot(map, options) { } } +function findClonedCanvas( + originalRoot, + clonedDoc, + clonedElement, + originalCanvas, + selector +) { + if (!originalCanvas) { + return null; + } + + if (originalCanvas.id) { + const clonedById = clonedDoc.getElementById(originalCanvas.id); + if (clonedById) { + return clonedById; + } + } + + const originalCanvases = Array.from(originalRoot.querySelectorAll(selector)); + const clonedCanvases = Array.from(clonedElement.querySelectorAll(selector)); + const canvasIndex = originalCanvases.indexOf(originalCanvas); + + return canvasIndex >= 0 ? clonedCanvases[canvasIndex] : null; +} + +function copyCanvasContents(originalCanvas, clonedCanvas) { + if (!originalCanvas || !clonedCanvas) { + return false; + } + + const ctx = clonedCanvas.getContext('2d'); + if (!ctx) { + return false; + } + + ctx.drawImage(originalCanvas, 0, 0); + return true; +} + +function canvasHasVisiblePixels(canvas) { + if (!canvas) { + return false; + } + + const ctx = canvas.getContext('2d'); + if (!ctx) { + return false; + } + + try { + const width = canvas.width; + const height = canvas.height; + const sampleCount = 5; + + for (let yStep = 0; yStep < sampleCount; yStep++) { + for (let xStep = 0; xStep < sampleCount; xStep++) { + const x = Math.min( + width - 1, + Math.floor((xStep / (sampleCount - 1)) * (width - 1)) + ); + const y = Math.min( + height - 1, + Math.floor((yStep / (sampleCount - 1)) * (height - 1)) + ); + const pixel = ctx.getImageData(x, y, 1, 1).data; + if (pixel[3] !== 0) { + return true; + } + } + } + } catch (e) { + return true; + } + + return false; +} + +function getFlowmapBlendMode(deckCanvas) { + if (!deckCanvas) { + return null; + } + + const computedStyle = window.getComputedStyle(deckCanvas); + const blendMode = + deckCanvas.style.mixBlendMode || + (computedStyle && computedStyle.mixBlendMode) || + ''; + + if (!blendMode || blendMode === 'normal') { + return null; + } + + return blendMode; +} + +function compositeFlowmapCanvasForScreenshot(map, state, clonedDoc, clonedElement) { + const mapCanvasSelector = 'canvas.maplibregl-canvas, canvas.mapboxgl-canvas'; + const originalMapCanvas = state.container.querySelector(mapCanvasSelector); + const clonedMapCanvas = findClonedCanvas( + state.container, + clonedDoc, + clonedElement, + originalMapCanvas, + mapCanvasSelector + ); + + const mapCanvasCopied = copyCanvasContents(originalMapCanvas, clonedMapCanvas); + const mapCanvasHasContent = + mapCanvasCopied && canvasHasVisiblePixels(clonedMapCanvas); + + const originalDeckCanvas = map._deckCanvas && + state.container.contains(map._deckCanvas) ? + map._deckCanvas : + state.container.querySelector('canvas[id^="deck-canvas-"]'); + + if (!originalDeckCanvas) { + return; + } + + const deckCanvasSelector = 'canvas[id^="deck-canvas-"]'; + const clonedDeckCanvas = findClonedCanvas( + state.container, + clonedDoc, + clonedElement, + originalDeckCanvas, + deckCanvasSelector + ); + const blendMode = getFlowmapBlendMode(originalDeckCanvas); + + copyCanvasContents(originalDeckCanvas, clonedDeckCanvas); + + if (!blendMode || !clonedMapCanvas || !mapCanvasHasContent) { + copyCanvasContents(originalDeckCanvas, clonedDeckCanvas); + return; + } + + const mapCtx = clonedMapCanvas.getContext('2d'); + if (!mapCtx) { + copyCanvasContents(originalDeckCanvas, clonedDeckCanvas); + return; + } + + const previousCompositeOperation = mapCtx.globalCompositeOperation; + mapCtx.globalCompositeOperation = blendMode; + + if (mapCtx.globalCompositeOperation !== blendMode) { + mapCtx.globalCompositeOperation = previousCompositeOperation; + copyCanvasContents(originalDeckCanvas, clonedDeckCanvas); + return; + } + + mapCtx.drawImage( + originalDeckCanvas, + 0, + 0 + ); + mapCtx.globalCompositeOperation = previousCompositeOperation; + + // The flowmap is already blended into the cloned map canvas. Hide the cloned + // Deck canvas so html2canvas does not draw it a second time in normal mode. + if (clonedDeckCanvas) { + clonedDeckCanvas.style.display = 'none'; + } +} + async function captureMapScreenshot(map, options) { const state = await prepareMapForScreenshot(map, options); @@ -201,15 +366,7 @@ async function captureMapScreenshot(map, options) { logging: false, scale: options.image_scale || 1, onclone: function(clonedDoc, clonedElement) { - // Copy WebGL canvas content to cloned canvas - const originalCanvas = state.container.querySelector('canvas.maplibregl-canvas, canvas.mapboxgl-canvas'); - const clonedCanvas = clonedElement.querySelector('canvas.maplibregl-canvas, canvas.mapboxgl-canvas'); - if (originalCanvas && clonedCanvas) { - const ctx = clonedCanvas.getContext('2d'); - if (ctx) { - ctx.drawImage(originalCanvas, 0, 0); - } - } + compositeFlowmapCanvasForScreenshot(map, state, clonedDoc, clonedElement); } }); diff --git a/man/add_flowmap.Rd b/man/add_flowmap.Rd new file mode 100644 index 0000000..121f594 --- /dev/null +++ b/man/add_flowmap.Rd @@ -0,0 +1,212 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/flowmap.R +\name{add_flowmap} +\alias{add_flowmap} +\title{Adds a FlowmapGL layer for visualizing origin-destination flows between +point locations.} +\usage{ +add_flowmap( + map, + id, + locations, + flows, + flow_color_scheme = "Teal", + flow_opacity = 1, + flow_dark_mode = "auto", + flow_blend = "auto", + flow_fade_amount = 50, + flow_highlight_color = "#ff9b29", + flow_locations_enabled = TRUE, + flow_location_totals_enabled = TRUE, + flow_location_labels_enabled = FALSE, + flow_lines_rendering_mode = c("straight", "animated-straight", "curved"), + flow_line_thickness_scale = 1, + flow_line_curviness = 1, + flow_clustering_enabled = TRUE, + flow_clustering_auto = TRUE, + flow_clustering_level = NULL, + flow_fade_enabled = TRUE, + flow_fade_opacity_enabled = FALSE, + flow_adaptive_scales_enabled = TRUE, + flow_temporal_scale_domain = c("selected", "all"), + flow_max_top_flows_display_num = 5000, + flow_endpoints_in_viewport_mode = c("any", "both"), + flow_time_column = NULL, + flow_selected_time_range = NULL, + flow_selected_locations = NULL, + flow_location_filter_mode = c("ALL", "INCOMING", "OUTGOING", "BETWEEN"), + tooltip = TRUE, + popup = FALSE, + tooltip_style = c("floating", "anchored"), + popup_style = c("floating", "anchored"), + tooltip_theme = c("auto", "light", "dark"), + popup_theme = c("auto", "light", "dark"), + tooltip_options = list(), + popup_options = list(), + visibility = c("visible", "none"), + before_id = NULL, + slot = NULL +) +} +\arguments{ +\item{map}{A map object created by \code{\link[=mapboxgl]{mapboxgl()}} or \code{\link[=maplibre]{maplibre()}}.} + +\item{id}{A unique layer ID.} + +\item{locations}{A data frame or \code{sf} point object with location data. +Data frames must include \code{id}, \code{lat}, and \code{lon} columns. \code{sf} point +objects must include \code{id}; coordinates are transformed to EPSG:4326 and +serialized as \code{lon}/\code{lat}.} + +\item{flows}{A data frame with \code{origin}, \code{dest}, and \code{count} columns.} + +\item{flow_color_scheme}{FlowMapGL preset color scheme name, a character +vector of at least two CSS colors, or a \code{mapgl_continuous_scale} object +created by \code{\link[=interpolate_palette]{interpolate_palette()}}. Preset names are case-sensitive; use +\code{\link[=flowmap_color_schemes]{flowmap_color_schemes()}} to list them.} + +\item{flow_opacity}{Layer opacity between 0 and 1.} + +\item{flow_dark_mode}{Logical (\code{TRUE} or \code{FALSE}), or \code{"auto"}; whether to use FlowMapGL dark-mode +colors. If \code{"auto"}, the mode is dynamically detected based on the map style.} + +\item{flow_blend}{Logical (\code{TRUE} or \code{FALSE}), \code{"auto"}, or a character string specifying a CSS +mix-blend-mode. + +Valid modes are: \code{"normal"}, \code{"multiply"}, \code{"screen"}, \code{"overlay"}, \code{"darken"}, +\code{"lighten"}, \code{"color-dodge"}, \code{"color-burn"}, \code{"hard-light"}, \code{"soft-light"}, +\code{"difference"}, \code{"exclusion"}, \code{"hue"}, \code{"saturation"}, \code{"color"}, and \code{"luminosity"}. + +\strong{Recommendations}: +\itemize{ +\item On \strong{dark basemaps}: \code{"screen"} looks best, creating a glowing additive effect where flows overlap. +\item On \strong{light basemaps}: \code{"multiply"} or \code{"darken"} looks best, increasing contrast against the light background. +} + +If \code{"auto"}, automatically chooses \code{"screen"} for dark styles and \code{"multiply"} for light styles. +If \code{before_id} or \code{slot} is specified (interleaved mode), \code{"auto"} quietly disables blending (\code{FALSE}) +without throwing a warning. If \code{TRUE}, defaults to \code{"screen"} when \code{flow_dark_mode} is \code{TRUE}, +and \code{"multiply"} when \code{FALSE}. If \code{FALSE}, no blending is applied. Note: CSS blending requires +a standalone canvas overlay and is ignored when \code{before_id} or \code{slot} is specified.} + +\item{flow_fade_amount}{Controls how much lower-magnitude flows fade compared to higher ones. Range: 0-100.} + +\item{flow_highlight_color}{Color used for highlighting hovered elements.} + +\item{flow_locations_enabled}{Whether to show location circles.} + +\item{flow_location_totals_enabled}{Whether to show incoming/outgoing totals as concentric circles at each location.} + +\item{flow_location_labels_enabled}{Whether to show text labels at locations.} + +\item{flow_lines_rendering_mode}{Controls how flow lines are rendered: \code{"straight"}, \code{"animated-straight"}, or \code{"curved"}.} + +\item{flow_line_thickness_scale}{Multiplier for flow line thickness.} + +\item{flow_line_curviness}{Multiplier for flow line curviness (only used when \code{flow_lines_rendering_mode} is \code{"curved"}).} + +\item{flow_clustering_enabled}{Whether to cluster nearby locations when zoomed out.} + +\item{flow_clustering_auto}{Whether to automatically adjust clustering level based on zoom.} + +\item{flow_clustering_level}{Fixed clustering zoom level. Only used when \code{flow_clustering_auto} is \code{FALSE}.} + +\item{flow_fade_enabled}{Whether to apply color fading to lower-magnitude flows.} + +\item{flow_fade_opacity_enabled}{Whether to also fade opacity for lower-magnitude flows.} + +\item{flow_adaptive_scales_enabled}{Whether to adapt flow thickness and +color scales to the current viewport. This controls the spatial scale +domain while panning and zooming.} + +\item{flow_temporal_scale_domain}{For temporal flowmaps, whether flow +thickness and color scales use only the currently selected time range +(\code{"selected"}) or all flow data across the full time extent (\code{"all"}).} + +\item{flow_max_top_flows_display_num}{Maximum number of flows to display.} + +\item{flow_endpoints_in_viewport_mode}{Controls when a flow is considered visible based on endpoint locations: \code{"any"} or \code{"both"}.} + +\item{flow_time_column}{Optional column name in \code{flows} for time data.} + +\item{flow_selected_time_range}{Optional vector of two dates (or strings) for initial time filtering.} + +\item{flow_selected_locations}{Optional vector of location IDs to select.} + +\item{flow_location_filter_mode}{Optional location filter mode: \code{"ALL"}, \code{"INCOMING"}, \code{"OUTGOING"}, or \code{"BETWEEN"}.} + +\item{tooltip}{Tooltip configuration. Use \code{FALSE} or \code{NULL} to disable +tooltips, \code{TRUE} for default tooltips, a single template string, +a named list, or a \code{\link[=tooltip_options]{tooltip_options()}} object.} + +\item{popup}{Popup configuration. Use \code{FALSE} or \code{NULL} to disable +popups, \code{TRUE} for default popups, a single template string, +a named list, or a \code{\link[=popup_options]{popup_options()}} object.} + +\item{tooltip_style}{Tooltip rendering style: \code{"floating"} (cursor-following) +or \code{"anchored"} (fixed to feature).} + +\item{popup_style}{Popup rendering style: \code{"floating"} (at click position) +or \code{"anchored"} (fixed to feature).} + +\item{tooltip_theme}{Tooltip theme. \code{"auto"} follows \code{flow_dark_mode}; +\code{"light"} and \code{"dark"} force a theme.} + +\item{popup_theme}{Popup theme. \code{"auto"} follows \code{flow_dark_mode}; +\code{"light"} and \code{"dark"} force a theme.} + +\item{tooltip_options}{A named list of renderer-specific tooltip options.} + +\item{popup_options}{A named list of renderer-specific popup options.} + +\item{visibility}{Whether the layer is initially \code{"visible"} or \code{"none"}.} + +\item{before_id}{Optional map layer ID to render before.} + +\item{slot}{Optional Mapbox Standard slot.} +} +\value{ +The modified map object with the flowmap layer added. +} +\description{ +Adds a FlowmapGL layer for visualizing origin-destination flows between +point locations. +} +\details{ +Mapbox and MapLibre layer paint arguments such as \code{fill_color}, +\code{circle_color}, and \code{line_color} require a scalar CSS color or a style +expression. Use \code{interpolate_palette(...)$expression} for data-driven layer +color ramps. FlowMapGL's \code{flow_color_scheme} accepts a preset name such as +\code{"Teal"}, a plain color ramp such as \code{c("red", "white", "blue")}, or an +\code{interpolate_palette(...)} scale object. + +Flow scale domains have separate spatial and temporal controls. +\code{flow_adaptive_scales_enabled = TRUE} rescales flow thickness and color for +the current viewport; \code{FALSE} keeps the scale tied to the broader map extent. +For temporal flowmaps, \code{flow_temporal_scale_domain = "selected"} rescales +within the selected time-control interval, while \code{"all"} keeps the scale +comparable across the full time extent. +} +\examples{ +# Create a flowmap centered on Montréal using the bundled datasets +maplibre( + style = carto_style("dark-matter"), + center = c(-73.58, 45.50), + zoom = 11, + projection = "mercator" +) |> + add_flowmap( + id = "bixi-rides", + locations = bixi_locations, + flows = bixi_flows, + flow_time_column = "time", + flow_color_scheme = "Teal", + flow_dark_mode = TRUE + ) |> + add_time_control( + data = bixi_flows, + time_column = "time", + time_interval = "hour", + title = "BIXI Montréal Rides" + ) +} diff --git a/man/add_layer_tuner.Rd b/man/add_layer_tuner.Rd new file mode 100644 index 0000000..9123acd --- /dev/null +++ b/man/add_layer_tuner.Rd @@ -0,0 +1,70 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/layer_tuner.R +\name{add_layer_tuner} +\alias{add_layer_tuner} +\title{Add a Layer Tuner to a map} +\usage{ +add_layer_tuner( + map, + layers = "all", + show_all_args = FALSE, + title = NULL, + position = "top-left", + width = 245, + height = NULL, + collapsed = FALSE +) +} +\arguments{ +\item{map}{A \code{mapboxgl} or \code{maplibre} object.} + +\item{layers}{A character vector of layer IDs to include in the tuner, or \code{"all"} (default) +to include all compatible layers.} + +\item{show_all_args}{A logical value. If \code{TRUE}, the exported R code will include all +whitelisted arguments for each layer (using current map values or defaults) even if they +were not explicitly customized in your original R code or during tuning. Default is \code{FALSE}.} + +\item{title}{Optional title for the tuner panel. Defaults to the built-in +layer tuner title.} + +\item{position}{Initial position of the tuner panel. One of \code{"top-left"}, +\code{"top-right"}, \code{"bottom-left"}, or \code{"bottom-right"}. Defaults to +\code{"top-left"}.} + +\item{width}{Initial tuner panel width. Numeric values are interpreted as +pixels; character values are passed through as CSS lengths. Defaults to +\code{245}.} + +\item{height}{Optional initial tuner panel height. Numeric values are +interpreted as pixels; character values are passed through as CSS lengths. +Defaults to \code{NULL}, which lets the panel size itself automatically.} + +\item{collapsed}{Logical value indicating whether the tuner panel should be +collapsed initially. Defaults to \code{FALSE}.} +} +\value{ +The modified map object with the layer tuner added. +} +\description{ +This function adds an interactive live customization widget (using lil-gui) to the map. +It allows users to customize paint and layout properties of map layers in real-time. +} +\examples{ +# Create a flowmap centered on Montréal using the bundled datasets and add a layer tuner +maplibre( + style = carto_style("dark-matter"), + center = c(-73.58, 45.50), + zoom = 11, + projection = "mercator" +) |> + add_flowmap( + id = "bixi-rides", + locations = bixi_locations, + flows = bixi_flows, + flow_time_column = "time", + flow_color_scheme = "Teal", + flow_dark_mode = TRUE + ) |> + add_layer_tuner(position = "top-right", width = 320) +} diff --git a/man/add_time_control.Rd b/man/add_time_control.Rd new file mode 100644 index 0000000..957d433 --- /dev/null +++ b/man/add_time_control.Rd @@ -0,0 +1,129 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/time_control.R +\name{add_time_control} +\alias{add_time_control} +\title{Add a time control with a histogram} +\usage{ +add_time_control( + map, + data, + time_column, + layer_id = NULL, + feature_time_property = NULL, + feature_time_format = c("iso", "epoch_ms", "epoch_s"), + time_interval = c("hour", "day"), + position = "bottom-left", + initial_range = NULL, + loop = TRUE, + speed = 500, + autoplay = FALSE, + accent_color = "#00bcd4", + dark_mode = TRUE, + draggable = TRUE, + collapsible = FALSE, + collapsed = FALSE, + title = NULL +) +} +\arguments{ +\item{map}{A map object created by \code{\link[=mapboxgl]{mapboxgl()}} or \code{\link[=maplibre]{maplibre()}}.} + +\item{data}{A data frame containing the temporal data used to build the +histogram (bin counts and extent).} + +\item{time_column}{The name of the column in \code{data} containing timestamps +(POSIXct or Date).} + +\item{layer_id}{Target layer ID(s) to filter. Either a character vector of +layer IDs (flowmap and/or ordinary layers), or \code{NULL} to filter every +flowmap layer in the map. To filter ordinary (non-flowmap) layers, list +them explicitly.} + +\item{feature_time_property}{For ordinary (non-flowmap) target layers, the +name of the feature property holding the timestamp. Defaults to +\code{time_column}.} + +\item{feature_time_format}{How the timestamp is stored on ordinary target +layers' source features: \code{"iso"} (ISO 8601 string, default), +\code{"epoch_ms"}, or \code{"epoch_s"}.} + +\item{time_interval}{The aggregation interval for the histogram: \code{"hour"} +or \code{"day"}.} + +\item{position}{The position of the control: \code{"top-right"}, \code{"top-left"}, +\code{"bottom-right"}, \code{"bottom-left"}, or \code{"bottom-center"}.} + +\item{initial_range}{Optional vector of two dates/timestamps for the initial +time filter range.} + +\item{loop}{Logical; whether to loop the playback.} + +\item{speed}{Playback speed in milliseconds per step (default 500).} + +\item{autoplay}{Logical; if \code{TRUE}, start playing the scrubber animation +immediately after the control mounts. Defaults to \code{FALSE}.} + +\item{accent_color}{Color for the bars and selection handles.} + +\item{dark_mode}{Logical; whether to use a dark theme for the widget.} + +\item{draggable}{Logical; if \code{TRUE} (default) the widget is detached from +the map corner container and can be repositioned by dragging its header.} + +\item{collapsible}{Logical; if \code{TRUE} the histogram body can be collapsed +to a compact bar.} + +\item{collapsed}{Logical; whether to start in the collapsed state. Implies +\code{collapsible = TRUE}.} + +\item{title}{Optional short title shown in the header (useful when the +control is draggable or collapsible).} +} +\value{ +The modified map object. +} +\description{ +Adds an interactive time scrubber with a histogram to the map. The control +filters temporal data by dragging a range across a bar chart. It can drive +one or several layers at once — both flowmap layers and ordinary +Mapbox/MapLibre layers (circle, fill, line, symbol, etc.) whose source +features carry a time property. +} +\details{ +For ordinary layers, the control sets a Mapbox filter expression of the +form \verb{[">=", ["get", feature_time_property], start] && ["<", ..., end]}. +The property is assumed to be an ISO 8601 timestamp string by default; pass +\code{feature_time_format = "epoch_ms"} (or \code{"epoch_s"}) if your source data +encodes time as numeric epoch milliseconds (or seconds). + +For flowmap layers the control updates the \code{selectedTimeRange} of the +flowmap filter via the flowmap.gl plugin. + +Hold Shift while dragging on the histogram to add another selected time +range. Multiple ranges are combined with OR semantics when filtering target +layers. +} +\examples{ +# Create a flowmap centered on Montréal using the bundled datasets +maplibre( + style = carto_style("dark-matter"), + center = c(-73.58, 45.50), + zoom = 11, + projection = "mercator" +) |> + add_flowmap( + id = "bixi-rides", + locations = bixi_locations, + flows = bixi_flows, + flow_time_column = "time", + flow_color_scheme = "Teal", + flow_dark_mode = TRUE + ) |> + add_time_control( + data = bixi_flows, + time_column = "time", + time_interval = "hour", + title = "BIXI Montréal Rides" + ) + +} diff --git a/man/bixi_flows.Rd b/man/bixi_flows.Rd new file mode 100644 index 0000000..07da9ce --- /dev/null +++ b/man/bixi_flows.Rd @@ -0,0 +1,42 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/data.R +\docType{data} +\name{bixi_flows} +\alias{bixi_flows} +\title{BIXI Montréal Hourly Bike Sharing Flows (July 1-7, 2019)} +\format{ +A data frame with 6,092 rows and 4 variables: +\describe{ +\item{time}{Hourly timestamp (POSIXct, UTC)} +\item{origin}{Origin station ID (factor, matching \code{bixi_locations$id})} +\item{dest}{Destination station ID (factor, matching \code{bixi_locations$id})} +\item{count}{Aggregated number of bike sharing trips in that hour (integer)} +} +} +\source{ +BIXI Montréal Open Data (\url{https://bixi.com/fr/donnees-ouvertes}). +Prepared for \url{https://github.com/FlowmapBlue/FlowmapBlue} by Ilya Boyandin (\url{https://twitter.com/ilyabo}). +Original interactive visualization on Flowmap.blue: +\url{https://www.flowmap.blue/1qTVOzkPB7U1ySI4g4uPtVBzzEDCI8n1WXAmQeZL15fE} +} +\usage{ +bixi_flows +} +\description{ +A dataset containing hourly aggregated bike sharing trips between BIXI +stations in Montréal during the week of July 1 to July 7, 2019. +} +\details{ +To minimize the package footprint, the dataset has been truncated to a +\strong{minimum of three trips} (retaining only flows where \code{count > 2}), +which reduces the rows from 213,227 to 6,092, and compresses the final size +to just \strong{~22 KB}. +} +\examples{ +# Check first few records +print(head(bixi_flows)) +} +\seealso{ +\code{\link{bixi_locations}} +} +\keyword{datasets} diff --git a/man/bixi_locations.Rd b/man/bixi_locations.Rd new file mode 100644 index 0000000..88b38bf --- /dev/null +++ b/man/bixi_locations.Rd @@ -0,0 +1,37 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/data.R +\docType{data} +\name{bixi_locations} +\alias{bixi_locations} +\title{BIXI Montréal Bike Share Stations (2019)} +\format{ +A data frame with 618 rows and 4 variables: +\describe{ +\item{id}{Unique station ID (character, e.g., \code{"4000"}, \code{"MTL-ECO5.1-01"})} +\item{name}{Station name (character, e.g., \code{"Jeanne-d'Arc / Ontario"})} +\item{lat}{Latitude coordinate (numeric)} +\item{lon}{Longitude coordinate (numeric)} +} +} +\source{ +BIXI Montréal Open Data (\url{https://bixi.com/fr/donnees-ouvertes}). +Prepared for \url{https://github.com/FlowmapBlue/FlowmapBlue} by Ilya Boyandin (\url{https://twitter.com/ilyabo}). +} +\usage{ +bixi_locations +} +\description{ +A dataset containing the names and coordinates of BIXI bicycle sharing +stations in Montréal, Quebec, Canada. +} +\examples{ +# Convert to sf object to view on a map +if (requireNamespace("sf", quietly = TRUE)) { + bixi_sf <- sf::st_as_sf(bixi_locations, coords = c("lon", "lat"), crs = 4326) + print(head(bixi_sf)) +} +} +\seealso{ +\code{\link{bixi_flows}} +} +\keyword{datasets} diff --git a/man/flowmap_color_schemes.Rd b/man/flowmap_color_schemes.Rd new file mode 100644 index 0000000..513895a --- /dev/null +++ b/man/flowmap_color_schemes.Rd @@ -0,0 +1,22 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/flowmap.R +\name{flowmap_color_schemes} +\alias{flowmap_color_schemes} +\title{FlowMapGL color scheme names} +\usage{ +flowmap_color_schemes() +} +\value{ +A character vector of FlowMapGL preset names. +} +\description{ +Returns the FlowMapGL 9.3.0 preset color scheme names supported by +\code{\link[=add_flowmap]{add_flowmap()}}. These names are case-sensitive. +} +\details{ +The bundled FlowMapGL presets are: +\code{Blues}, \code{BluGrn}, \code{BluYl}, \code{BrwnYl}, \code{BuGn}, \code{BuPu}, \code{Burg}, \code{BurgYl}, \code{Cool}, \code{DarkMint}, \code{Emrld}, \code{GnBu}, \code{Grayish}, \code{Greens}, \code{Greys}, \code{Inferno}, \code{Magenta}, \code{Magma}, \code{Mint}, \code{Oranges}, \code{OrRd}, \code{OrYel}, \code{Peach}, \code{Plasma}, \code{PinkYl}, \code{PuBu}, \code{PuBuGn}, \code{PuRd}, \code{Purp}, \code{Purples}, \code{PurpOr}, \code{RdPu}, \code{RedOr}, \code{Reds}, \code{Sunset}, \code{SunsetDark}, \code{Teal}, \code{TealGrn}, \code{Viridis}, \code{Warm}, \code{YlGn}, \code{YlGnBu}, \code{YlOrBr}, and \code{YlOrRd}. +} +\examples{ +flowmap_color_schemes() +} diff --git a/man/mapgl-package.Rd b/man/mapgl-package.Rd index 2a548c4..d7cd104 100644 --- a/man/mapgl-package.Rd +++ b/man/mapgl-package.Rd @@ -21,5 +21,10 @@ Useful links: \author{ \strong{Maintainer}: Kyle Walker \email{kyle@walker-data.com} +Authors: +\itemize{ + \item Egor Kotov \email{kotov.egor@gmail.com} (\href{https://orcid.org/0000-0001-6690-5345}{ORCID}) (added Flowmap.gl, layer tuner, time control) [contributor] +} + } \keyword{internal} diff --git a/man/popup_options.Rd b/man/popup_options.Rd new file mode 100644 index 0000000..a8c2d61 --- /dev/null +++ b/man/popup_options.Rd @@ -0,0 +1,18 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/tooltips_popups.R +\name{popup_options} +\alias{popup_options} +\title{Configure popup options} +\usage{ +popup_options(template = NULL, theme = "auto", ...) +} +\arguments{ +\item{template}{Template string or a named list with \code{location} and/or \code{flow} keys.} + +\item{theme}{Visual theme: \code{"auto"}, \code{"light"}, or \code{"dark"}.} + +\item{...}{Additional properties passed to the Mapbox/MapLibre popup, such as \code{className}, \code{css}, \code{maxWidth}, etc.} +} +\description{ +Configure popup options +} diff --git a/man/set_flowmap_filter.Rd b/man/set_flowmap_filter.Rd new file mode 100644 index 0000000..3ecf374 --- /dev/null +++ b/man/set_flowmap_filter.Rd @@ -0,0 +1,32 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/flowmap.R +\name{set_flowmap_filter} +\alias{set_flowmap_filter} +\title{Update flowmap filter} +\usage{ +set_flowmap_filter( + proxy, + id, + selected_locations = NULL, + location_filter_mode = NULL, + selected_time_range = NULL +) +} +\arguments{ +\item{proxy}{A map proxy object.} + +\item{id}{The ID of the flowmap layer to update.} + +\item{selected_locations}{Optional vector of location IDs to select.} + +\item{location_filter_mode}{Optional location filter mode: \code{"ALL"}, \code{"INCOMING"}, \code{"OUTGOING"}, or \code{"BETWEEN"}.} + +\item{selected_time_range}{Optional vector of two dates for time filtering.} +} +\value{ +The modified map proxy. +} +\description{ +Updates the filter state of a flowmap layer, including selected locations +and time range. +} diff --git a/man/set_flowmap_settings.Rd b/man/set_flowmap_settings.Rd new file mode 100644 index 0000000..e128d78 --- /dev/null +++ b/man/set_flowmap_settings.Rd @@ -0,0 +1,47 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/flowmap.R +\name{set_flowmap_settings} +\alias{set_flowmap_settings} +\title{Update a flowmap setting} +\usage{ +set_flowmap_settings(map, id, name, value) +} +\arguments{ +\item{map}{A map object created by \code{\link[=mapboxgl]{mapboxgl()}} or \code{\link[=maplibre]{maplibre()}}, or a proxy +object created by \code{\link[=mapboxgl_proxy]{mapboxgl_proxy()}} or \code{\link[=maplibre_proxy]{maplibre_proxy()}}.} + +\item{id}{The ID of the flowmap layer to update.} + +\item{name}{The setting name to update. Supported canonical FlowMapGL +setting names are \code{opacity}, \code{colorScheme}, \code{darkMode}, \code{fadeAmount}, +\code{highlightColor}, \code{locationsEnabled}, \code{locationTotalsEnabled}, +\code{locationLabelsEnabled}, \code{flowLinesRenderingMode}, +\code{flowLineThicknessScale}, \code{flowLineCurviness}, \code{clusteringEnabled}, +\code{clusteringAuto}, \code{clusteringLevel}, \code{fadeEnabled}, +\code{fadeOpacityEnabled}, \code{adaptiveScalesEnabled}, \code{temporalScaleDomain}, +\code{maxTopFlowsDisplayNum}, and \code{flowEndpointsInViewportMode}. +Snake-case aliases such as \code{color_scheme}, \code{temporal_scale_domain}, and +\code{max_top_flows_display_num} are accepted and normalized internally. +Filter state (\code{selectedTimeRange}, \code{selectedLocations}, and +\code{locationFilterMode}) must be updated with \code{\link[=set_flowmap_filter]{set_flowmap_filter()}}.} + +\item{value}{The setting value.} +} +\value{ +The modified map object. +} +\description{ +Updates one setting of a flowmap layer. +} +\details{ +\code{colorScheme} accepts the same values as \code{flow_color_scheme} in +\code{\link[=add_flowmap]{add_flowmap()}}: a FlowMapGL preset name, a character vector of at least two +CSS colors, or a \code{mapgl_continuous_scale} object from +\code{\link[=interpolate_palette]{interpolate_palette()}}. \code{opacity} must be between 0 and 1. \code{fadeAmount} +must be between 0 and 100. \code{maxTopFlowsDisplayNum} must be positive. +\code{clusteringLevel} must be numeric or \code{NULL}. \code{flowLinesRenderingMode} must +be \code{"straight"}, \code{"animated-straight"}, or \code{"curved"}. +\code{temporalScaleDomain} must be \code{"selected"} or \code{"all"}. +\code{flowEndpointsInViewportMode} must be \code{"any"} or \code{"both"}. Boolean +settings must be scalar \code{TRUE} or \code{FALSE}. +} diff --git a/man/tooltip_options.Rd b/man/tooltip_options.Rd new file mode 100644 index 0000000..c7a57c8 --- /dev/null +++ b/man/tooltip_options.Rd @@ -0,0 +1,18 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/tooltips_popups.R +\name{tooltip_options} +\alias{tooltip_options} +\title{Configure tooltip options} +\usage{ +tooltip_options(template = NULL, theme = "auto", ...) +} +\arguments{ +\item{template}{Template string or a named list with \code{location} and/or \code{flow} keys.} + +\item{theme}{Visual theme: \code{"auto"}, \code{"light"}, or \code{"dark"}.} + +\item{...}{Additional properties passed to the Mapbox/MapLibre popup, such as \code{className}, \code{css}, \code{maxWidth}, etc.} +} +\description{ +Configure tooltip options +} diff --git a/tests/testthat/test-dynamic-legends.R b/tests/testthat/test-dynamic-legends.R index 8681a78..e46a2ad 100644 --- a/tests/testthat/test-dynamic-legends.R +++ b/tests/testthat/test-dynamic-legends.R @@ -53,7 +53,11 @@ test_that("color ramp labels are optional", { config <- map$x$legend_interactivity[[1]] expect_equal(config$selectedRamp, "Ramp 2") expect_match(map$x$legend_html, "mapgl-ramp-picker-no-labels") - expect_false(grepl("mapgl-ramp-picker-label", map$x$legend_html, fixed = TRUE)) + expect_false(grepl( + "mapgl-ramp-picker-label", + map$x$legend_html, + fixed = TRUE + )) }) test_that("continuous legends can use scale metadata for ramp picker config", { @@ -75,7 +79,12 @@ test_that("continuous legends can use scale metadata for ramp picker config", { ), fill_color = scale$expression ) |> - add_legend("Values", colors = scale, layer_id = "values", ramp_picker = TRUE) + add_legend( + "Values", + colors = scale, + layer_id = "values", + ramp_picker = TRUE + ) config <- map$x$legend_interactivity[[1]] expect_true(config$rampPicker) @@ -112,7 +121,11 @@ test_that("bottom-positioned ramp pickers open upward", { ramp_picker = TRUE ) - expect_match(map$x$legend_css, ".bottom-left .mapgl-ramp-picker-menu", fixed = TRUE) + expect_match( + map$x$legend_css, + ".bottom-left .mapgl-ramp-picker-menu", + fixed = TRUE + ) expect_match(map$x$legend_css, "bottom: 4px", fixed = TRUE) }) @@ -186,7 +199,10 @@ test_that("bivariate_scale accepts custom breaks", { test_that("bivariate built-in palettes are inspectable", { palettes <- bivariate_palettes() - expect_true(all(c("blue_pink", "blue_red", "green_blue", "purple_orange") %in% names(palettes))) + expect_true(all( + c("blue_pink", "blue_red", "green_blue", "purple_orange") %in% + names(palettes) + )) expect_equal(dim(bivariate_palettes("blue_red")), c(3, 3)) expect_error(bivariate_palettes("not-a-palette"), "Unknown bivariate palette") }) diff --git a/tests/testthat/test-flowmap-customization.R b/tests/testthat/test-flowmap-customization.R new file mode 100644 index 0000000..ffda0c9 --- /dev/null +++ b/tests/testthat/test-flowmap-customization.R @@ -0,0 +1,108 @@ +test_that("add_flowmap serializes all new customization settings", { + locations <- data.frame( + id = c("a", "b"), + lat = c(40, 41), + lon = c(-74, -75) + ) + flows <- data.frame(origin = "a", dest = "b", count = 10) + + map <- maplibre() |> + add_flowmap( + id = "flows", + locations = locations, + flows = flows, + flow_fade_amount = 75, + flow_highlight_color = "red", + flow_locations_enabled = FALSE, + flow_location_totals_enabled = FALSE, + flow_location_labels_enabled = TRUE, + flow_lines_rendering_mode = "animated-straight", + flow_clustering_enabled = FALSE, + flow_clustering_auto = FALSE, + flow_clustering_level = 5, + flow_fade_enabled = FALSE, + flow_fade_opacity_enabled = TRUE, + flow_adaptive_scales_enabled = FALSE, + flow_temporal_scale_domain = "all", + flow_max_top_flows_display_num = 1000, + flow_endpoints_in_viewport_mode = "both" + ) + + expect_length(map$x$flowmaps, 1) + settings <- map$x$flowmaps[[1]]$settings + + expect_equal(settings$fadeAmount, 75) + expect_equal(settings$highlightColor, "red") + expect_false(settings$locationsEnabled) + expect_false(settings$locationTotalsEnabled) + expect_true(settings$locationLabelsEnabled) + expect_equal(settings$flowLinesRenderingMode, "animated-straight") + expect_false(settings$clusteringEnabled) + expect_false(settings$clusteringAuto) + expect_equal(settings$clusteringLevel, 5) + expect_false(settings$fadeEnabled) + expect_true(settings$fadeOpacityEnabled) + expect_false(settings$adaptiveScalesEnabled) + expect_equal(settings$temporalScaleDomain, "all") + expect_equal(settings$flowLinesRenderingMode, "animated-straight") + expect_equal(settings$maxTopFlowsDisplayNum, 1000) + expect_equal(settings$flowEndpointsInViewportMode, "both") +}) + +test_that("add_flowmap validates new parameters", { + locations <- data.frame(id = c("a", "b"), lat = c(40, 41), lon = c(-74, -75)) + flows <- data.frame(origin = "a", dest = "b", count = 10) + + expect_error( + add_flowmap(maplibre(), "id", locations, flows, flow_fade_amount = -1), + "between 0 and 100" + ) + expect_error( + add_flowmap(maplibre(), "id", locations, flows, flow_fade_amount = 101), + "between 0 and 100" + ) + expect_error( + add_flowmap( + maplibre(), + "id", + locations, + flows, + flow_max_top_flows_display_num = 0 + ), + "positive number" + ) + expect_error( + add_flowmap( + maplibre(), + "id", + locations, + flows, + flow_clustering_level = "a" + ), + "number or NULL" + ) + expect_error( + add_flowmap( + maplibre(), + "id", + locations, + flows, + flow_locations_enabled = "TRUE" + ), + "TRUE or FALSE" + ) + expect_error( + add_flowmap(maplibre(), "id", locations, flows, flow_highlight_color = 123), + "single string" + ) + expect_error( + add_flowmap( + maplibre(), + "id", + locations, + flows, + flow_temporal_scale_domain = "hour" + ), + "'arg' should be one of" + ) +}) diff --git a/tests/testthat/test-flowmap.R b/tests/testthat/test-flowmap.R new file mode 100644 index 0000000..3c8b501 --- /dev/null +++ b/tests/testthat/test-flowmap.R @@ -0,0 +1,948 @@ +flowmap_test_locations <- function() { + data.frame( + id = c("a", "b"), + lat = c(40, 41), + lon = c(-74, -75) + ) +} + +flowmap_test_flows <- function() { + data.frame(origin = "a", dest = "b", count = 10) +} + +flowmap_test_map <- function(flow_blend = FALSE, ...) { + maplibre() |> + add_flowmap( + id = "flows", + locations = flowmap_test_locations(), + flows = flowmap_test_flows(), + flow_blend = flow_blend, + ... + ) +} + +test_that("add_flowmap serializes minimal flowmap config", { + locations <- data.frame( + id = c("a", "b"), + lat = c(40, 41), + lon = c(-74, -75) + ) + flows <- data.frame(origin = "a", dest = "b", count = 10) + + map <- maplibre() |> + add_flowmap( + id = "flows", + locations = locations, + flows = flows, + flow_color_scheme = "Teal", + flow_dark_mode = FALSE, + flow_opacity = 0.7, + flow_blend = FALSE, + visibility = "none", + before_id = "labels", + slot = "top" + ) + + expect_length(map$x$flowmaps, 1) + flowmap <- map$x$flowmaps[[1]] + expect_equal(flowmap$id, "flows") + expect_equal(flowmap$data$locations$id, c("a", "b")) + expect_equal(flowmap$data$locations$name, c("a", "b")) + expect_equal(flowmap$data$flows$count, 10) + expect_equal(flowmap$settings$colorScheme, "Teal") + expect_false(flowmap$settings$darkMode) + expect_equal(flowmap$settings$opacity, 0.7) + expect_false(flowmap$settings$flowBlend) + expect_equal(flowmap$visibility, "none") + expect_equal(flowmap$beforeId, "labels") + expect_equal(flowmap$slot, "top") + + mapbox_map <- mapboxgl(access_token = "test-token") |> + add_flowmap("flows", locations, flows, flow_blend = FALSE) + + expect_length(mapbox_map$x$flowmaps, 1) + expect_equal(mapbox_map$x$flowmaps[[1]]$id, "flows") +}) + +test_that("add_flowmap serializes flowmap tooltip options", { + no_tooltip <- flowmap_test_map(tooltip = FALSE) + expect_null(no_tooltip$x$flowmaps[[1]]$tooltip) + + default_tooltip <- flowmap_test_map(tooltip = TRUE) + tooltip <- default_tooltip$x$flowmaps[[1]]$tooltip + expect_true(tooltip$enabled) + expect_equal(tooltip$style, "floating") + expect_equal(tooltip$theme, "light") + expect_equal(tooltip$location, list(kind = "template", value = TRUE)) + expect_equal(tooltip$flow, list(kind = "template", value = TRUE)) + + dark_tooltip <- mapboxgl( + style = mapbox_style("dark"), + access_token = "token" + ) |> + add_flowmap( + id = "flows", + locations = flowmap_test_locations(), + flows = flowmap_test_flows(), + flow_blend = FALSE, + tooltip = TRUE + ) + expect_equal(dark_tooltip$x$flowmaps[[1]]$tooltip$theme, "dark") + + custom <- flowmap_test_map( + tooltip = tooltip_options( + template = list( + location = "{name}", + flow = "{origin.id} -> {dest.id}: {count}" + ), + theme = "dark", + offset = c(12, 14) + ) + ) + tooltip <- custom$x$flowmaps[[1]]$tooltip + expect_equal(tooltip$style, "floating") + expect_equal(tooltip$theme, "dark") + expect_equal(tooltip$location, list(kind = "template", value = "{name}")) + expect_equal(tooltip$flow, list(kind = "template", value = "{origin.id} -> {dest.id}: {count}")) + expect_equal(tooltip$popup_props$offset, c(12, 14)) + + same_template <- flowmap_test_map(tooltip = "{count}") + expect_equal(same_template$x$flowmaps[[1]]$tooltip$location, list(kind = "template", value = "{count}")) + expect_equal(same_template$x$flowmaps[[1]]$tooltip$flow, list(kind = "template", value = "{count}")) + + flow_only <- flowmap_test_map( + tooltip = list(location = FALSE, flow = "{count}") + ) + expect_false(flow_only$x$flowmaps[[1]]$tooltip$location) + expect_equal(flow_only$x$flowmaps[[1]]$tooltip$flow, list(kind = "template", value = "{count}")) +}) + +test_that("add_flowmap validates flowmap tooltip options", { + expect_error( + flowmap_test_map(tooltip = 1), + "must be TRUE, FALSE, NULL, a template string" + ) + expect_error( + flowmap_test_map(tooltip_style = "native", tooltip = TRUE), + "should be one of" + ) + expect_error( + flowmap_test_map(tooltip_theme = "sepia", tooltip = TRUE), + "should be one of" + ) + expect_error( + flowmap_test_map(tooltip = list(location = c("a", "b"))), + "templates for `location`" + ) + expect_error( + flowmap_test_map(tooltip = TRUE, tooltip_options = c(offset = 1)), + "`tooltip_options` must be a named list" + ) + expect_error( + tooltip_options(template = TRUE, theme = "auto", render_mode = "floating", list(1)), + "Additional popup properties must be named" + ) + expect_error( + flowmap_test_map(tooltip = tooltip_options(template = list(location = c("a", "b")))), + "Interaction templates for `location` must be TRUE, FALSE, or a string" + ) +}) + +test_that("flowmap_color_schemes returns FlowMapGL 9.3.0 presets", { + expected <- c( + "Blues", + "BluGrn", + "BluYl", + "BrwnYl", + "BuGn", + "BuPu", + "Burg", + "BurgYl", + "Cool", + "DarkMint", + "Emrld", + "GnBu", + "Grayish", + "Greens", + "Greys", + "Inferno", + "Magenta", + "Magma", + "Mint", + "Oranges", + "OrRd", + "OrYel", + "Peach", + "Plasma", + "PinkYl", + "PuBu", + "PuBuGn", + "PuRd", + "Purp", + "Purples", + "PurpOr", + "RdPu", + "RedOr", + "Reds", + "Sunset", + "SunsetDark", + "Teal", + "TealGrn", + "Viridis", + "Warm", + "YlGn", + "YlGnBu", + "YlOrBr", + "YlOrRd" + ) + + expect_equal(flowmap_color_schemes(), expected) + expect_true(all( + c("Teal", "Blues", "Viridis", "Grayish", "YlOrRd") %in% + flowmap_color_schemes() + )) +}) + +test_that("add_flowmap validates valid flow_color_scheme shapes", { + preset <- flowmap_test_map(flow_color_scheme = "Viridis") + expect_equal(preset$x$flowmaps[[1]]$settings$colorScheme, "Viridis") + + colors <- c("red", "#12345678", "rgb(1, 2, 3)", "rgba(4, 5, 6, 0.7)") + custom <- flowmap_test_map(flow_color_scheme = colors) + expect_equal(custom$x$flowmaps[[1]]$settings$colorScheme, colors) + + scale <- interpolate_palette( + data = data.frame(value = c(1, 2)), + column = "value", + n = 2, + colors = c("#111111", "#eeeeee") + ) + scale_map <- flowmap_test_map(flow_color_scheme = scale) + expect_equal(scale_map$x$flowmaps[[1]]$settings$colorScheme, scale$colors) +}) + +test_that("add_flowmap rejects invalid flow_color_scheme values", { + expect_error( + flowmap_test_map(flow_color_scheme = "Unknown"), + "FlowMapGL preset" + ) + expect_error( + flowmap_test_map(flow_color_scheme = "teal"), + "FlowMapGL preset" + ) + expect_error( + flowmap_test_map(flow_color_scheme = "red"), + "Scalar color strings" + ) + expect_error( + flowmap_test_map(flow_color_scheme = character()), + "at least two" + ) + expect_error( + flowmap_test_map(flow_color_scheme = c("red")), + "Scalar color strings" + ) + expect_error( + flowmap_test_map(flow_color_scheme = NA_character_), + "missing or empty" + ) + expect_error( + flowmap_test_map(flow_color_scheme = c("red", NA_character_)), + "missing or empty" + ) + expect_error( + flowmap_test_map(flow_color_scheme = 1:2), + "must be a FlowMapGL preset name" + ) + expect_error( + flowmap_test_map(flow_color_scheme = c("red", "not-a-color")), + "invalid CSS color" + ) + expect_error( + flowmap_test_map( + flow_color_scheme = structure( + list(colors = c("red")), + class = "mapgl_continuous_scale" + ) + ), + "at least two" + ) + expect_error( + flowmap_test_map( + flow_color_scheme = structure( + list(expression = list()), + class = "mapgl_continuous_scale" + ) + ), + "must contain a `colors` vector" + ) +}) + +test_that("add_flowmap strictly validates flow_dark_mode", { + expect_true( + flowmap_test_map(flow_dark_mode = TRUE)$x$flowmaps[[1]]$settings$darkMode + ) + expect_false( + flowmap_test_map(flow_dark_mode = FALSE)$x$flowmaps[[1]]$settings$darkMode + ) + + expect_error(flowmap_test_map(flow_dark_mode = NA), "TRUE` or `FALSE") + expect_error(flowmap_test_map(flow_dark_mode = "TRUE"), "TRUE` or `FALSE") + expect_error(flowmap_test_map(flow_dark_mode = 1), "TRUE` or `FALSE") + expect_error( + flowmap_test_map(flow_dark_mode = c(TRUE, FALSE)), + "TRUE` or `FALSE" + ) +}) + +test_that("add_flowmap validates placement strings", { + expect_null(flowmap_test_map(before_id = NULL)$x$flowmaps[[1]]$beforeId) + expect_null(flowmap_test_map(slot = NULL)$x$flowmaps[[1]]$slot) + expect_equal( + flowmap_test_map(before_id = "labels")$x$flowmaps[[1]]$beforeId, + "labels" + ) + expect_equal(flowmap_test_map(slot = "top")$x$flowmaps[[1]]$slot, "top") + + expect_error(flowmap_test_map(before_id = ""), "`before_id`") + expect_error(flowmap_test_map(before_id = c("a", "b")), "`before_id`") + expect_error(flowmap_test_map(before_id = NA_character_), "`before_id`") + expect_error(flowmap_test_map(before_id = 1), "`before_id`") + expect_error(flowmap_test_map(slot = ""), "`slot`") + expect_error(flowmap_test_map(slot = c("top", "bottom")), "`slot`") + expect_error(flowmap_test_map(slot = NA_character_), "`slot`") + expect_error(flowmap_test_map(slot = 1), "`slot`") +}) + +test_that("add_flowmap validates flow_opacity boundaries", { + expect_equal( + flowmap_test_map(flow_opacity = 0)$x$flowmaps[[1]]$settings$opacity, + 0 + ) + expect_equal( + flowmap_test_map(flow_opacity = 1)$x$flowmaps[[1]]$settings$opacity, + 1 + ) + + expect_error(flowmap_test_map(flow_opacity = -0.1), "between 0 and 1") + expect_error(flowmap_test_map(flow_opacity = 1.1), "between 0 and 1") + expect_error(flowmap_test_map(flow_opacity = NA_real_), "between 0 and 1") + expect_error(flowmap_test_map(flow_opacity = NaN), "between 0 and 1") + expect_error(flowmap_test_map(flow_opacity = "1"), "between 0 and 1") +}) + +test_that("set_flowmap_settings updates one setting on a regular map", { + map <- flowmap_test_map() |> + set_flowmap_settings("flows", "opacity", 0.25) + + expect_equal(map$x$flowmaps[[1]]$settings$opacity, 0.25) +}) + +test_that("set_flowmap_settings normalizes snake_case aliases", { + map <- flowmap_test_map() |> + set_flowmap_settings("flows", "color_scheme", "Viridis") |> + set_flowmap_settings("flows", "temporal_scale_domain", "all") |> + set_flowmap_settings("flows", "max_top_flows_display_num", 100) + + settings <- map$x$flowmaps[[1]]$settings + expect_equal(settings$colorScheme, "Viridis") + expect_equal(settings$temporalScaleDomain, "all") + expect_equal(settings$maxTopFlowsDisplayNum, 100) +}) + +test_that("set_flowmap_settings sends unchanged proxy message shape", { + messages <- list() + session <- list( + sendCustomMessage = function(type, message) { + messages[[length(messages) + 1]] <<- list(type = type, message = message) + } + ) + proxy <- structure( + list(id = "map", session = session), + class = "maplibre_proxy" + ) + + result <- set_flowmap_settings(proxy, "flows", "color_scheme", "Viridis") + + expect_identical(result, proxy) + expect_length(messages, 1) + expect_equal(messages[[1]]$type, "maplibre-proxy") + expect_equal(messages[[1]]$message$id, "map") + expect_equal(messages[[1]]$message$message$type, "set_flowmap_settings") + expect_equal(messages[[1]]$message$message$id, "flows") + expect_equal( + messages[[1]]$message$message$settings, + list(colorScheme = "Viridis") + ) +}) + +test_that("set_flowmap_settings preserves NULL setting values", { + map <- flowmap_test_map(flow_clustering_level = 5) |> + set_flowmap_settings("flows", "clusteringLevel", NULL) + + settings <- map$x$flowmaps[[1]]$settings + expect_true("clusteringLevel" %in% names(settings)) + expect_null(settings$clusteringLevel) +}) + +test_that("set_flowmap_settings rejects unknown and filter settings", { + expect_error( + set_flowmap_settings(flowmap_test_map(), "flows", "unknownSetting", 1), + "Supported names" + ) + expect_error( + set_flowmap_settings(flowmap_test_map(), "flows", "selectedTimeRange", 1), + "set_flowmap_filter" + ) + expect_error( + set_flowmap_settings(flowmap_test_map(), "flows", "selected_time_range", 1), + "set_flowmap_filter" + ) +}) + +test_that("set_flowmap_settings validates setting values", { + expect_error( + set_flowmap_settings(flowmap_test_map(), "flows", "opacity", -0.1), + "between 0 and 1" + ) + expect_error( + set_flowmap_settings(flowmap_test_map(), "flows", "fadeAmount", 101), + "between 0 and 100" + ) + expect_error( + set_flowmap_settings(flowmap_test_map(), "flows", "darkMode", "TRUE"), + "TRUE or FALSE" + ) + expect_error( + set_flowmap_settings( + flowmap_test_map(), + "flows", + "temporalScaleDomain", + "hour" + ), + "selected" + ) + expect_error( + set_flowmap_settings(flowmap_test_map(), "flows", "colorScheme", "red"), + "FlowMapGL preset" + ) + expect_error( + set_flowmap_settings( + flowmap_test_map(), + "flows", + "flowLinesRenderingMode", + "arc" + ), + "animated-straight" + ) + expect_error( + set_flowmap_settings( + flowmap_test_map(), + "flows", + "flowEndpointsInViewportMode", + "none" + ), + "both" + ) + expect_error( + set_flowmap_settings( + flowmap_test_map(), + "flows", + "maxTopFlowsDisplayNum", + 0 + ), + "positive number" + ) +}) + +test_that("flowmap can be included in explicit layers control config", { + locations <- data.frame( + id = c("a", "b"), + lat = c(40, 41), + lon = c(-74, -75) + ) + flows <- data.frame(origin = "a", dest = "b", count = 10) + + map <- maplibre() |> + add_flowmap("flows", locations, flows) |> + add_layers_control( + layers = list( + "Migration flowmap" = "flows" + ) + ) + + expect_equal( + map$x$layers_control$layers_config[[1]]$label, + "Migration flowmap" + ) + expect_equal(map$x$layers_control$layers_config[[1]]$ids, "flows") +}) + +test_that("flowmap added before a regular layer gets inferred beforeId", { + locations <- data.frame( + id = c("a", "b"), + lat = c(40, 41), + lon = c(-74, -75) + ) + flows <- data.frame(origin = "a", dest = "b", count = 10) + + map <- maplibre() |> + add_flowmap("flows", locations, flows, flow_blend = FALSE) |> + add_layer( + id = "points", + type = "circle", + source = list( + type = "geojson", + data = list(type = "FeatureCollection", features = list()) + ) + ) + + expect_equal(map$x$flowmaps[[1]]$beforeId, "points") +}) + +test_that("flowmap added after the final regular layer keeps beforeId NULL", { + locations <- data.frame( + id = c("a", "b"), + lat = c(40, 41), + lon = c(-74, -75) + ) + flows <- data.frame(origin = "a", dest = "b", count = 10) + + map <- maplibre() |> + add_layer( + id = "points", + type = "circle", + source = list( + type = "geojson", + data = list(type = "FeatureCollection", features = list()) + ) + ) |> + add_flowmap("flows", locations, flows) + + expect_null(map$x$flowmaps[[1]]$beforeId) +}) + +test_that("explicit flowmap before_id is not overwritten by later layers", { + locations <- data.frame( + id = c("a", "b"), + lat = c(40, 41), + lon = c(-74, -75) + ) + flows <- data.frame(origin = "a", dest = "b", count = 10) + + map <- maplibre() |> + add_flowmap( + "flows", + locations, + flows, + before_id = "labels", + flow_blend = FALSE + ) |> + add_layer( + id = "points", + type = "circle", + source = list( + type = "geojson", + data = list(type = "FeatureCollection", features = list()) + ) + ) + + expect_equal(map$x$flowmaps[[1]]$beforeId, "labels") +}) + +test_that("multiple pending flowmaps resolve to the same later regular layer", { + locations <- data.frame( + id = c("a", "b"), + lat = c(40, 41), + lon = c(-74, -75) + ) + flows <- data.frame(origin = "a", dest = "b", count = 10) + + map <- maplibre() |> + add_flowmap("flows-a", locations, flows, flow_blend = FALSE) |> + add_flowmap("flows-b", locations, flows, flow_blend = FALSE) |> + add_layer( + id = "points", + type = "circle", + source = list( + type = "geojson", + data = list(type = "FeatureCollection", features = list()) + ) + ) + + expect_equal( + vapply(map$x$flowmaps, `[[`, character(1), "beforeId"), + c("points", "points") + ) +}) + +test_that("add_flowmap validates required columns and IDs", { + locations <- data.frame(id = c("a", "b"), lat = c(40, 41), lon = c(-74, -75)) + + expect_error( + maplibre() |> + add_flowmap( + "flows", + locations[-1], + data.frame(origin = "a", dest = "b", count = 1) + ), + "missing required column" + ) + + expect_error( + maplibre() |> + add_flowmap( + "flows", + locations, + data.frame(origin = "a", dest = "z", count = 1) + ), + "unknown ID" + ) + + expect_error( + maplibre() |> + add_flowmap( + "flows", + locations, + data.frame(origin = "a", dest = "b", count = NA_real_) + ), + "must not contain missing values" + ) +}) + +test_that("add_flowmap converts sf points to EPSG 4326 lon lat columns", { + locations <- sf::st_as_sf( + data.frame(id = c("a", "b"), x = c(0, 1000), y = c(0, 1000)), + coords = c("x", "y"), + crs = 3857 + ) + flows <- data.frame(origin = "a", dest = "b", count = 10) + + map <- maplibre() |> add_flowmap("flows", locations, flows) + serialized_locations <- map$x$flowmaps[[1]]$data$locations + + expect_equal(names(serialized_locations)[1:4], c("id", "lat", "lon", "name")) + expect_equal(serialized_locations$id, c("a", "b")) + expect_equal(serialized_locations$lon[1], 0) + expect_equal(serialized_locations$lat[1], 0) + expect_gt(serialized_locations$lon[2], 0) + expect_gt(serialized_locations$lat[2], 0) +}) + +test_that("Mapbox and MapLibre YAML files include the same flowmap dependencies", { + mapbox <- readLines(system.file( + "htmlwidgets/mapboxgl.yaml", + package = "mapgl" + )) + maplibre <- readLines(system.file( + "htmlwidgets/maplibregl.yaml", + package = "mapgl" + )) + + flowmap_entries <- c( + " - name: flowmap-gl", + " version: \"9.3.0\"", + " src: \"htmlwidgets/lib/flowmap-gl\"", + " - \"flowmap-gl-bundle.min.js\"", + " - name: flowmap-plugin", + " version: \"1.0.0\"", + " src: \"htmlwidgets\"", + " - \"flowmap.js\"" + ) + + for (entry in flowmap_entries) { + expect_true(any(mapbox == entry), info = entry) + expect_true(any(maplibre == entry), info = entry) + } + + yaml_dependency_names <- function(lines) { + name_lines <- grep("^ - name:", lines, value = TRUE) + sub("^ - name: ", "", name_lines) + } + + expect_equal( + yaml_dependency_names(mapbox)[ + match("flowmap-gl", yaml_dependency_names(mapbox)):match( + "flowmap-plugin", + yaml_dependency_names(mapbox) + ) + ], + c("flowmap-gl", "flowmap-plugin") + ) + expect_equal( + yaml_dependency_names(maplibre)[ + match("flowmap-gl", yaml_dependency_names(maplibre)):match( + "flowmap-plugin", + yaml_dependency_names(maplibre) + ) + ], + c("flowmap-gl", "flowmap-plugin") + ) +}) + +test_that("compare widgets include and initialize flowmap support", { + yaml_dependency_names <- function(lines) { + name_lines <- grep("^ - name:", lines, value = TRUE) + sub("^ - name: ", "", name_lines) + } + + compare_yaml_paths <- c( + "htmlwidgets/mapboxgl_compare.yaml", + "htmlwidgets/maplibregl_compare.yaml" + ) + + for (path in compare_yaml_paths) { + lines <- readLines(system.file(path, package = "mapgl")) + expect_true("flowmap-gl" %in% yaml_dependency_names(lines), info = path) + expect_true("flowmap-plugin" %in% yaml_dependency_names(lines), info = path) + } + + compare_js_paths <- c( + "htmlwidgets/mapboxgl_compare.js", + "htmlwidgets/maplibregl_compare.js" + ) + + for (path in compare_js_paths) { + js <- paste( + readLines(system.file(path, package = "mapgl")), + collapse = "\n" + ) + expect_match(js, "MapGLFlowmapPlugin\\.init", fixed = FALSE) + expect_match(js, "MapGLFlowmapPlugin\\.getVisibility", fixed = FALSE) + expect_match(js, "MapGLFlowmapPlugin\\.setVisibility", fixed = FALSE) + } +}) + +test_that("flowmap plugin prepends Flowmap.gl to native attribution", { + js <- paste( + readLines(system.file("htmlwidgets/flowmap.js", package = "mapgl")), + collapse = "\n" + ) + + expect_match( + js, + ".mapboxgl-ctrl-attrib-inner, .maplibregl-ctrl-attrib-inner", + fixed = TRUE + ) + expect_match(js, "https://flowmap.gl/", fixed = TRUE) + expect_match(js, 'data-mapgl-flowmap-attribution", "true"', fixed = TRUE) + expect_match( + js, + "data-mapgl-flowmap-attribution-separator", + fixed = TRUE + ) + expect_match( + js, + "insertBefore(link, attributionInner.firstChild)", + fixed = TRUE + ) + expect_match(js, 'map.on("styledata", refresh)', fixed = TRUE) + expect_match(js, 'map.on("sourcedata", refresh)', fixed = TRUE) + expect_match(js, 'map.on("idle", refresh)', fixed = TRUE) +}) + +test_that("flowmap plugin includes tooltip renderers", { + js <- paste( + readLines(system.file("htmlwidgets/flowmap.js", package = "mapgl")), + collapse = "\n" + ) + + expect_match(js, "DEFAULT_LOCATION_TOOLTIP", fixed = TRUE) + expect_match(js, "showInteractiveUI", fixed = TRUE) + expect_match(js, "getTooltipStore(map)", fixed = TRUE) + expect_match(js, "hideOtherFlowmapTooltips", fixed = TRUE) + expect_match(js, "layerProps.onHover", fixed = TRUE) + expect_match(js, "info.layer.onHover(info, event)", fixed = TRUE) + expect_match(js, "hideAllFlowmapTooltips(map)", fixed = TRUE) + expect_match(js, "cloneFlowmapLayer", fixed = TRUE) + expect_match(js, "cloneProps.onHover = layer._mapglOnHover", fixed = TRUE) + expect_match(js, "cloneFlowmapLayer(layer, {", fixed = TRUE) +}) + +test_that("flowmap vendoring manifest matches committed bundle", { + manifest_path <- system.file( + "htmlwidgets/lib/flowmap-gl/flowmap-gl-vendor-manifest.json", + package = "mapgl" + ) + bundle_path <- system.file( + "htmlwidgets/lib/flowmap-gl/flowmap-gl-bundle.min.js", + package = "mapgl" + ) + + manifest <- jsonlite::read_json(manifest_path) + + expect_equal( + unname(tools::sha256sum(bundle_path)), + manifest$bundle$sha256 + ) + expect_equal( + manifest$bundle$path, + "inst/htmlwidgets/lib/flowmap-gl/flowmap-gl-bundle.min.js" + ) + expect_equal(manifest$copyrights$path, "LICENSE.note") +}) + +test_that("flowmap vendoring manifest records temporal-scale patch", { + manifest_path <- system.file( + "htmlwidgets/lib/flowmap-gl/flowmap-gl-vendor-manifest.json", + package = "mapgl" + ) + manifest <- jsonlite::read_json(manifest_path) + patch_paths <- vapply(manifest$patches, `[[`, character(1), "path") + patch_path <- "data-raw/flowmap-vendor/patches/flowmap-temporal-scale-domain.patch" + + expect_equal(intersect(patch_paths, patch_path), patch_path) + + source_patch_path <- patch_path + if (!file.exists(source_patch_path)) { + source_patch_path <- file.path("..", "..", patch_path) + } + if (!file.exists(source_patch_path)) { + skip("flowmap vendor patch source is not available in installed package") + } + + patch <- manifest$patches[[match(patch_path, patch_paths)]] + expect_equal(unname(tools::sha256sum(source_patch_path)), patch$sha256) + expect_equal(file.info(source_patch_path)$size, patch$bytes) + expect_match(patch$purpose, "temporalScaleDomain", fixed = TRUE) +}) + +test_that("flowmap loaded bundle includes temporalScaleDomain", { + bundle_path <- system.file( + "htmlwidgets/lib/flowmap-gl/flowmap-gl-bundle.min.js", + package = "mapgl" + ) + bundle <- paste(readLines(bundle_path, warn = FALSE), collapse = "\n") + + expect_match(bundle, "temporalScaleDomain", fixed = TRUE) +}) + +test_that("is_dark_style utility classifies basemaps correctly", { + # Dark styles + expect_true(is_dark_style("mapbox://styles/mapbox/dark-v11")) + expect_true(is_dark_style("mapbox://styles/mapbox/navigation-night-v1")) + expect_true(is_dark_style("mapbox://styles/mapbox/satellite-v9")) + expect_true(is_dark_style( + "https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json" + )) + expect_true(is_dark_style( + "https://api.maptiler.com/maps/basic-dark/style.json" + )) + expect_true(is_dark_style( + "https://basemapstyles-api.arcgis.com/arcgis/rest/services/styles/v2/styles/arcgis/imagery" + )) + + # Light styles + expect_false(is_dark_style("mapbox://styles/mapbox/light-v11")) + expect_false(is_dark_style("mapbox://styles/mapbox/streets-v12")) + expect_false(is_dark_style( + "https://basemaps.cartocdn.com/gl/voyager-gl-style/style.json" + )) + expect_false(is_dark_style( + "https://basemaps.cartocdn.com/gl/positron-gl-style/style.json" + )) + expect_false(is_dark_style( + "https://api.maptiler.com/maps/streets-v2/style.json" + )) + expect_false(is_dark_style( + "https://basemapstyles-api.arcgis.com/arcgis/rest/services/styles/v2/styles/arcgis/streets" + )) + + # Custom basemap_style list object + dark_custom <- list( + layers = list(list( + type = "background", + paint = list(`background-color` = "black") + )) + ) + light_custom <- list( + layers = list(list( + type = "background", + paint = list(`background-color` = "white") + )) + ) + expect_true(is_dark_style(dark_custom)) + expect_false(is_dark_style(light_custom)) + + # Fallbacks + expect_true(is_dark_style(NULL)) + expect_true(is_dark_style(list())) + expect_true(is_dark_style("random-style")) +}) + +test_that("add_flowmap validates flow_blend and handles auto-resolution", { + # Standalone map with flow_blend = "auto" (default) on default light basemap (voyager) + map_default <- maplibre() |> + add_flowmap( + id = "flows", + locations = flowmap_test_locations(), + flows = flowmap_test_flows() + ) + expect_false(map_default$x$flowmaps[[1]]$settings$darkMode) # Inferred to FALSE + expect_equal(map_default$x$flowmaps[[1]]$settings$flowBlend, "multiply") # Inferred to "multiply" + + # Standalone map with flow_blend = "auto" on dark style + map_dark <- mapboxgl(style = mapbox_style("dark"), access_token = "token") |> + add_flowmap( + id = "flows", + locations = flowmap_test_locations(), + flows = flowmap_test_flows() + ) + expect_true(map_dark$x$flowmaps[[1]]$settings$darkMode) # Inferred to TRUE + expect_equal(map_dark$x$flowmaps[[1]]$settings$flowBlend, "screen") # Inferred to "screen" + + # Interleaved map with flow_blend = "auto" (default) quietly resolves to FALSE (no warning) + expect_no_warning( + map_interleaved <- maplibre() |> + add_flowmap( + id = "flows", + locations = flowmap_test_locations(), + flows = flowmap_test_flows(), + before_id = "labels" + ) + ) + expect_false(map_interleaved$x$flowmaps[[1]]$settings$flowBlend) + + # Check validation + expect_error(flowmap_test_map(flow_blend = NA), "must be `TRUE` or `FALSE`") + expect_error( + flowmap_test_map(flow_blend = "invalid-mode"), + "must be one of the valid CSS mix-blend-mode" + ) + expect_error(flowmap_test_map(flow_blend = 123), "must be a logical") + + # Valid string blend mode + map_string <- maplibre() |> + add_flowmap( + id = "flows", + locations = flowmap_test_locations(), + flows = flowmap_test_flows(), + flow_blend = "screen" + ) + expect_equal(map_string$x$flowmaps[[1]]$settings$flowBlend, "screen") + + # Check warning when interleaved (before_id is set) and flow_blend is explicitly non-FALSE + expect_warning( + maplibre() |> + add_flowmap( + id = "flows", + locations = flowmap_test_locations(), + flows = flowmap_test_flows(), + flow_blend = TRUE, + before_id = "labels" + ), + "ignored when `before_id` or `slot` is specified" + ) + + expect_warning( + maplibre() |> + add_flowmap( + id = "flows", + locations = flowmap_test_locations(), + flows = flowmap_test_flows(), + flow_blend = "screen", + before_id = "labels" + ), + "ignored when `before_id` or `slot` is specified" + ) +}) diff --git a/tests/testthat/test-layer-tuner.R b/tests/testthat/test-layer-tuner.R new file mode 100644 index 0000000..9ddc22b --- /dev/null +++ b/tests/testthat/test-layer-tuner.R @@ -0,0 +1,91 @@ +test_that("add_layer_tuner serializes initial UI options", { + map <- maplibre() |> + add_layer_tuner( + layers = c("counties", "roads"), + show_all_args = TRUE, + title = "Style editor", + position = "bottom-right", + width = 320, + height = "40vh", + collapsed = TRUE + ) + + tuner <- map$x$layer_tuner + expect_true(tuner$enabled) + expect_equal(tuner$layers, c("counties", "roads")) + expect_true(tuner$show_all_args) + expect_equal(tuner$title, "Style editor") + expect_equal(tuner$position, "bottom-right") + expect_equal(tuner$width, "320px") + expect_equal(tuner$height, "40vh") + expect_true(tuner$collapsed) +}) + +test_that("add_layer_tuner keeps default UI options compatible", { + tuner <- maplibre() |> + add_layer_tuner() |> + getElement("x") |> + getElement("layer_tuner") + + expect_null(tuner$title) + expect_equal(tuner$position, "top-left") + expect_equal(tuner$width, "245px") + expect_null(tuner$height) + expect_false(tuner$collapsed) +}) + +test_that("add_layer_tuner validates initial UI options", { + expect_error(add_layer_tuner(maplibre(), title = ""), "`title`") + expect_error(add_layer_tuner(maplibre(), position = "middle"), "`position`") + expect_error(add_layer_tuner(maplibre(), width = 0), "`width`") + expect_error(add_layer_tuner(maplibre(), width = c(200, 300)), "`width`") + expect_error(add_layer_tuner(maplibre(), height = NA), "`height`") + expect_error(add_layer_tuner(maplibre(), collapsed = NA), "`collapsed`") +}) + +test_that("compare widgets preserve child layer tuner dependencies", { + widget <- compare( + maplibre() |> add_layer_tuner(), + maplibre() + ) + + dependency_names <- vapply( + widget$dependencies, + `[[`, + character(1), + "name" + ) + + expect_true("lil-gui" %in% dependency_names) + expect_true("layer-tuner" %in% dependency_names) + expect_true(widget$x$map1$layer_tuner$enabled) + expect_null(widget$x$map2$layer_tuner) +}) + +test_that("add_layer_tuner configures both maps in compare widgets", { + widget <- compare(maplibre(), maplibre()) |> + add_layer_tuner(position = "top-right") + + expect_true(widget$x$map1$layer_tuner$enabled) + expect_true(widget$x$map2$layer_tuner$enabled) + expect_equal(widget$x$map1$layer_tuner$position, "top-right") + expect_equal(widget$x$map2$layer_tuner$position, "top-right") +}) + +test_that("compare widget bindings initialize the layer tuner", { + compare_js_paths <- c( + "htmlwidgets/mapboxgl_compare.js", + "htmlwidgets/maplibregl_compare.js" + ) + + for (path in compare_js_paths) { + js <- paste( + readLines(system.file(path, package = "mapgl")), + collapse = "\n" + ) + expect_match(js, "MapGLLayerTuner\\.init", fixed = FALSE) + expect_match(js, "mapData\\.layer_tuner", fixed = FALSE) + expect_match(js, "_basemapLayerIds", fixed = TRUE) + expect_match(js, "mapgl-compare-layer-tuner-host", fixed = TRUE) + } +}) diff --git a/tests/testthat/test-time-control.R b/tests/testthat/test-time-control.R new file mode 100644 index 0000000..664a0df --- /dev/null +++ b/tests/testthat/test-time-control.R @@ -0,0 +1,62 @@ +test_that("add_time_control serializes initial range", { + timestamps <- as.POSIXct( + c("2026-01-01 00:15:00", "2026-01-01 01:30:00"), + tz = "UTC" + ) + map <- maplibre() |> + add_time_control( + data = data.frame(time = timestamps), + time_column = "time", + layer_id = "points", + initial_range = as.POSIXct( + c("2026-01-01 00:00:00", "2026-01-01 01:00:00"), + tz = "UTC" + ) + ) + + control <- map$x$time_controls[[1]] + expect_equal(control$targetLayerIds, list("points")) + expect_equal( + control$initialRange, + c("2026-01-01T00:00:00Z", "2026-01-01T01:00:00Z") + ) +}) + +test_that("time control JavaScript supports shift-selected ranges", { + js <- paste( + readLines(system.file( + "htmlwidgets/lib/time-control/time-control.js", + package = "mapgl" + )), + collapse = "\n" + ) + + expect_match(js, "sourceEvent\\.shiftKey", fixed = FALSE) + expect_match(js, "selectedTimeRanges", fixed = TRUE) + expect_match(js, "\\[\"any\", \\.\\.\\.clauses\\]", fixed = FALSE) + expect_match(js, "Shift \\+ drag = select multiple", fixed = FALSE) + expect_match(js, "mapgl-time-icon-btn", fixed = TRUE) + expect_match( + js, + "Math\\.abs\\(dx\\) \\+ Math\\.abs\\(dy\\) < 3", + fixed = FALSE + ) +}) + +test_that("flowmap assets support multiple selected time ranges", { + flowmap_js <- paste( + readLines(system.file("htmlwidgets/flowmap.js", package = "mapgl")), + collapse = "\n" + ) + bundle_js <- paste( + readLines(system.file( + "htmlwidgets/lib/flowmap-gl/flowmap-gl-bundle.min.js", + package = "mapgl" + )), + collapse = "\n" + ) + + expect_match(flowmap_js, "normalizeTimeRanges", fixed = TRUE) + expect_match(flowmap_js, "selectedTimeRanges", fixed = TRUE) + expect_match(bundle_js, "getSelectedTimeRanges", fixed = TRUE) +})