import { Color, SRGBColorSpace } from "three"; import { extent } from "./utils"; import { paintColor, type ColorStops } from "@tedius-npm/vandelay"; /** * Linear min/max scale for a column: the bridge between its real-world * units and the normalized [-1, 1] space the 3D scene lives in. */ export interface Scale { min: number; max: number; range: number; // Function properties, not methods: they use no `this`, so they can be passed around on their own /** real value to normalized [-1, 1] space */ toNormalized: (value: number) => number; /** normalized [-1, 1] space to real value */ toReal: (normalized: number) => number; } /** Spans the plotted values, so an axis follows the filters as they narrow or widen it. */ export function createScale(values: ArrayLike): Scale { const [min, max] = extent(values) ?? [0, 0]; const range = max - min; return { min, max, range, toNormalized: (value) => (Number.isFinite(value) && range !== 0 ? ((value - min) / range) * 2 - 1 : 0), toReal: (normalized) => ((normalized + 1) / 2) * range + min, }; } /** The three columns already normalized to [-1, 1], ready for a BufferGeometry. */ export interface Points3D { xs: Float32Array; ys: Float32Array; zs: Float32Array; } export function normalizePoints( xValues: Float64Array, yValues: Float64Array, zValues: Float64Array, xScale: Scale, yScale: Scale, zScale: Scale, ): Points3D { return { xs: normalized(xValues, xScale), ys: normalized(yValues, yScale), zs: normalized(zValues, zScale), }; } // A loop, since Float32Array.from with a map function is many times slower on a large column function normalized(values: Float64Array, scale: Scale): Float32Array { const out = new Float32Array(values.length); for (let i = 0; i < values.length; i++) out[i] = scale.toNormalized(values[i]); return out; } // The linear value a vertex color holds for each 0 to 255 channel of a paint color, which is what // Color.set gives a hex string, made once instead of once per point const LINEAR = Float32Array.from( { length: 256 }, (_, v) => new Color().setRGB(v / 255, v / 255, v / 255, SRGBColorSpace).r, ); /** * Three channels per point for a BufferGeometry: each value through paintColor, the gradient every * plot draws with, or black where the value is not finite. */ export function vertexColors(values: Float64Array, stops: readonly ColorStops[]): Float32Array { const colors = new Float32Array(values.length * 3); for (let i = 0; i < values.length; i++) { if (!Number.isFinite(values[i])) continue; const [r, g, b] = paintColor(values[i], stops); colors[i * 3] = LINEAR[r]; colors[i * 3 + 1] = LINEAR[g]; colors[i * 3 + 2] = LINEAR[b]; } return colors; }