An open source design system that's fully customizable and agent ready
TypeScript
feat(storybook): 3D point cloud showcase — minimal, sculptural demos (#1451)
Cindy Zhangedbe8bbf1a35
diff --git a/apps/storybook/stories/ThreeD-Backdrop.stories.tsx b/apps/storybook/stories/ThreeD-Backdrop.stories.tsxnew file mode 100644index 0000000000..e19b11efaa--- /dev/null+++ b/apps/storybook/stories/ThreeD-Backdrop.stories.tsx@@ -0,0 +1,276 @@+import type {Meta, StoryObj} from '@storybook/react';+import {useMemo} from 'react';+import {XDS3DChart, XDS3DScatter, use3D, useXDSChartColors} from '@xds/lab';++const meta: Meta = {title: 'Lab/XDS3DChart/Backdrop'};+export default meta;++/** Scatter that colors each point based on its projected screen position */+function AdaptiveScatter({+ splitX,+ leftColor,+ rightColor,+ radius = 1.2,+ opacity = 0.65,+}: {+ splitX: number;+ leftColor: string;+ rightColor: string;+ radius?: number;+ opacity?: number;+}) {+ const {+ data,+ xKey,+ yKey,+ zKey,+ project,+ xDomain,+ yDomain,+ zDomain,+ normalize,+ } = use3D();++ const points = useMemo(() => {+ return data+ .map((d, i) => {+ const nx = normalize(d[xKey] as number, xDomain);+ const ny = normalize(d[yKey] as number, yDomain);+ const nz = normalize(d[zKey] as number, zDomain);+ const {px, py, depth} = project(nx, ny, nz);+ return {px, py, depth, index: i};+ })+ .sort((a, b) => a.depth - b.depth);+ }, [data, xKey, yKey, zKey, project, xDomain, yDomain, zDomain, normalize]);++ return (+ <g>+ {points.map(p => {+ const depthFactor = 0.5 + (p.depth + 0.5) * 0.5;+ const color = p.px < splitX ? leftColor : rightColor;+ return (+ <circle+ key={p.index}+ cx={p.px}+ cy={p.py}+ r={radius * depthFactor}+ fill={color}+ fillOpacity={opacity * depthFactor}+ />+ );+ })}+ </g>+ );+}++/** Split backdrop — half dark, half light with adaptive point colors */+function SplitBackdrop({+ width,+ height,+ leftBg,+ rightBg,+}: {+ width: number;+ height: number;+ leftBg: string;+ rightBg: string;+}) {+ return (+ <g>+ <rect x={0} y={0} width={width / 2} height={height} fill={leftBg} />+ <rect+ x={width / 2}+ y={0}+ width={width / 2}+ height={height}+ fill={rightBg}+ />+ </g>+ );+}++function BackdropInner({+ leftBg,+ rightBg,+ leftDot,+ rightDot,+}: {+ leftBg: string;+ rightBg: string;+ leftDot: string;+ rightDot: string;+}) {+ const {width, height} = use3D();+ return (+ <>+ <SplitBackdrop+ width={width}+ height={height}+ leftBg={leftBg}+ rightBg={rightBg}+ />+ <AdaptiveScatter+ splitX={width / 2}+ leftColor={leftDot}+ rightColor={rightDot}+ />+ </>+ );+}++function sphere(n: number) {+ const phi = (1 + Math.sqrt(5)) / 2;+ return Array.from({length: n}, (_, i) => {+ const theta = Math.acos(1 - (2 * (i + 0.5)) / n);+ const p = (2 * Math.PI * i) / phi;+ return {+ x: Math.sin(theta) * Math.cos(p),+ y: Math.sin(theta) * Math.sin(p),+ z: Math.cos(theta),+ };+ });+}++function torusKnot(n: number) {+ return Array.from({length: n}, (_, i) => {+ const t = (i / n) * Math.PI * 2;+ const r = Math.cos(3 * t) + 2;+ return {x: r * Math.cos(2 * t), y: r * Math.sin(2 * t), z: Math.sin(3 * t)};+ });+}++/** Dark/light split — points adapt color based on which half they project onto */+export const SplitDarkLight: StoryObj = {+ render: () => {+ const data = useMemo(() => sphere(2000), []);+ return (+ <div style={{borderRadius: 16, overflow: 'hidden', maxWidth: 600}}>+ <XDS3DChart+ data={data}+ xKey="x"+ yKey="y"+ zKey="z"+ height={400}+ interactive+ autoRotate={0.15}>+ <BackdropInner+ leftBg="#0A1317"+ rightBg="#F1F4F7"+ leftDot="#DFE2E5"+ rightDot="#0A1317"+ />+ </XDS3DChart>+ </div>+ );+ },+};++/** Color split — two bold colors */+export const SplitBoldColors: StoryObj = {+ render: () => {+ const data = useMemo(() => torusKnot(2500), []);+ return (+ <div style={{borderRadius: 16, overflow: 'hidden', maxWidth: 600}}>+ <XDS3DChart+ data={data}+ xKey="x"+ yKey="y"+ zKey="z"+ height={400}+ interactive+ autoRotate={0.2}>+ <BackdropInner+ leftBg="#0064E0"+ rightBg="#E3193B"+ leftDot="#FFFFFF"+ rightDot="#FFFFFF"+ />+ </XDS3DChart>+ </div>+ );+ },+};++/** Quad split — four colored quadrants */+function QuadBackdropInner() {+ const {+ width,+ height,+ data,+ xKey,+ yKey,+ zKey,+ project,+ xDomain,+ yDomain,+ zDomain,+ normalize,+ } = use3D();++ const colors = [+ {bg: '#0064E0', dot: '#FFFFFF'}, // top-left+ {bg: '#E3193B', dot: '#FFFFFF'}, // top-right+ {bg: '#FBCE03', dot: '#0A1317'}, // bottom-left+ {bg: '#0B991F', dot: '#FFFFFF'}, // bottom-right+ ];++ const points = useMemo(() => {+ return data+ .map((d, i) => {+ const nx = normalize(d[xKey] as number, xDomain);+ const ny = normalize(d[yKey] as number, yDomain);+ const nz = normalize(d[zKey] as number, zDomain);+ const {px, py, depth} = project(nx, ny, nz);+ return {px, py, depth, index: i};+ })+ .sort((a, b) => a.depth - b.depth);+ }, [data, xKey, yKey, zKey, project, xDomain, yDomain, zDomain, normalize]);++ const hw = width / 2,+ hh = height / 2;++ return (+ <>+ <rect x={0} y={0} width={hw} height={hh} fill={colors[0].bg} />+ <rect x={hw} y={0} width={hw} height={hh} fill={colors[1].bg} />+ <rect x={0} y={hh} width={hw} height={hh} fill={colors[2].bg} />+ <rect x={hw} y={hh} width={hw} height={hh} fill={colors[3].bg} />+ <g>+ {points.map(p => {+ const depthFactor = 0.5 + (p.depth + 0.5) * 0.5;+ const quadIdx = (p.px < hw ? 0 : 1) + (p.py < hh ? 0 : 2);+ return (+ <circle+ key={p.index}+ cx={p.px}+ cy={p.py}+ r={1.2 * depthFactor}+ fill={colors[quadIdx].dot}+ fillOpacity={0.65 * depthFactor}+ />+ );+ })}+ </g>+ </>+ );+}++export const QuadSplit: StoryObj = {+ render: () => {+ const data = useMemo(() => sphere(2500), []);+ return (+ <div style={{borderRadius: 16, overflow: 'hidden', maxWidth: 600}}>+ <XDS3DChart+ data={data}+ xKey="x"+ yKey="y"+ zKey="z"+ height={400}+ interactive+ autoRotate={0.15}>+ <QuadBackdropInner />+ </XDS3DChart>+ </div>+ );+ },+};diff --git a/apps/storybook/stories/ThreeD-Showcase.stories.tsx b/apps/storybook/stories/ThreeD-Showcase.stories.tsxnew file mode 100644index 0000000000..aeabb25d7e--- /dev/null+++ b/apps/storybook/stories/ThreeD-Showcase.stories.tsx@@ -0,0 +1,674 @@+import type {Meta, StoryObj} from '@storybook/react';+import {useMemo} from 'react';+import {+ XDS3DChart,+ XDS3DScatter,+ XDS3DScatterGL,+ useXDSChartColors,+} from '@xds/lab';+import {XDSMediaTheme} from '@xds/core/theme';++const meta: Meta = {title: 'Lab/XDS3DChart/PopArt'};+export default meta;++// =============================================================================+// Shapes+// =============================================================================++function teapot(n: number) {+ const pts: Record<string, unknown>[] = [];+ // Body — wider, less tall+ for (let i = 0; i < n * 0.45; i++) {+ const u = Math.random() * Math.PI * 2;+ const v = Math.random() * Math.PI;+ const profile = Math.sin(v) * (1.2 + 0.2 * Math.sin(2 * v));+ pts.push({+ x: profile * Math.cos(u),+ z: profile * Math.sin(u),+ y: Math.cos(v) * 0.7,+ });+ }+ // Spout — curved tube+ for (let i = 0; i < n * 0.18; i++) {+ const t = Math.random();+ const a = Math.random() * Math.PI * 2;+ const r = 0.09 * (1 - t * 0.4);+ pts.push({+ x: 1.1 + t * 0.6 + t * t * 0.2,+ z: r * Math.cos(a),+ y: -0.1 + t * 0.6 + t * t * 0.2,+ });+ }+ // Handle — arch+ for (let i = 0; i < n * 0.17; i++) {+ const t = Math.random() * Math.PI;+ const a = Math.random() * Math.PI * 2;+ const r = 0.07;+ pts.push({+ x: -1.1 - 0.5 * Math.sin(t),+ z: r * Math.cos(a),+ y: -0.35 + 0.7 * Math.sin(t),+ });+ }+ // Lid+ for (let i = 0; i < n * 0.15; i++) {+ const r = Math.random() * 0.6;+ const a = Math.random() * Math.PI * 2;+ pts.push({x: r * Math.cos(a), z: r * Math.sin(a), y: 0.72});+ }+ // Knob+ for (let i = 0; i < n * 0.05; i++) {+ const u = Math.random() * Math.PI * 2;+ const v = Math.random() * Math.PI;+ const r = 0.1;+ pts.push({+ x: r * Math.sin(v) * Math.cos(u),+ z: r * Math.sin(v) * Math.sin(u),+ y: 0.82 + r * Math.cos(v),+ });+ }+ return pts;+}++function heart(n: number) {+ return Array.from({length: n}, () => {+ const u = Math.random() * Math.PI * 2;+ const v = Math.random() * Math.PI;+ const x = Math.sin(v) * (15 * Math.sin(u) - 4 * Math.sin(3 * u));+ const y = 8 * Math.cos(v);+ const z =+ Math.sin(v) *+ (15 * Math.cos(u) -+ 5 * Math.cos(2 * u) -+ 2 * Math.cos(3 * u) -+ Math.cos(4 * u));+ return {x: x / 16, y: y / 16, z: z / 16};+ });+}++function seashell(n: number) {+ return Array.from({length: n}, () => {+ const u = Math.random() * 4 * Math.PI;+ const v = Math.random() * Math.PI * 2;+ const r = Math.exp(0.15 * u);+ const opening = 0.3 + 0.3 * Math.cos(v);+ const x = r * Math.cos(u) * opening;+ const z = r * Math.sin(u) * opening;+ const y = r * (0.08 * u + 0.2 * Math.sin(v));+ const s = 0.1;+ return {x: x * s, z: z * s, y: y * s - 0.5};+ });+}++function kleinBottle(n: number) {+ return Array.from({length: n}, () => {+ const u = Math.random() * Math.PI * 2;+ const v = Math.random() * Math.PI * 2;+ const r = 4 * (1 - Math.cos(u) / 2);+ let x: number, z: number;+ if (u < Math.PI) {+ x = 6 * Math.cos(u) * (1 + Math.sin(u)) + r * Math.cos(u) * Math.cos(v);+ z = r * Math.sin(u) * Math.cos(v);+ } else {+ x = 6 * Math.cos(u) * (1 + Math.sin(u)) + r * Math.cos(v + Math.PI);+ z = r * Math.sin(u) * Math.cos(v);+ }+ const y = -16 * Math.sin(u) + r * Math.sin(v);+ return {x: x / 22, y: y / 22, z: z / 22};+ });+}++function star(n: number) {+ const pts: Record<string, unknown>[] = [];+ const spikes = 5;+ for (let i = 0; i < n; i++) {+ const u = Math.random() * Math.PI * 2;+ const v = Math.acos(2 * Math.random() - 1);+ const spike = 0.6 + 0.6 * Math.pow(Math.abs(Math.cos((spikes * u) / 2)), 8);+ const r = spike;+ pts.push({+ x: r * Math.sin(v) * Math.cos(u),+ y: r * Math.cos(v),+ z: r * Math.sin(v) * Math.sin(u),+ });+ }+ return pts;+}++function tree(n: number) {+ const pts: Record<string, unknown>[] = [];+ // Trunk — tapered cylinder+ for (let i = 0; i < n * 0.15; i++) {+ const h = Math.random() * 1.0;+ const a = Math.random() * Math.PI * 2;+ const r = 0.1 * (1 - h * 0.4);+ pts.push({x: r * Math.cos(a), y: h, z: r * Math.sin(a)});+ }+ // Canopy — cone-ish layers of points+ for (let i = 0; i < n * 0.85; i++) {+ const layer = Math.random();+ const h = 0.8 + layer * 1.4;+ const maxR = 0.8 * (1 - layer * 0.7);+ const r = Math.sqrt(Math.random()) * maxR;+ const a = Math.random() * Math.PI * 2;+ pts.push({+ x: r * Math.cos(a) + (Math.random() - 0.5) * 0.05,+ y: h + (Math.random() - 0.5) * 0.15,+ z: r * Math.sin(a) + (Math.random() - 0.5) * 0.05,+ });+ }+ return pts;+}++// =============================================================================+// Cell+// =============================================================================++interface CellProps {+ bg: string;+ mediaMode: 'dark' | 'light';+ data: Record<string, unknown>[];+ label: string;+ azimuth?: number;+ elevation?: number;+}++function Cell({+ bg,+ mediaMode,+ data,+ label,+ azimuth = 30,+ elevation = 20,+}: CellProps) {+ return (+ <XDSMediaTheme mode={mediaMode}>+ <div+ style={{+ background: bg,+ borderRadius: 16,+ overflow: 'hidden',+ display: 'flex',+ flexDirection: 'column',+ }}>+ <div style={{flex: 1, padding: 4}}>+ <XDS3DChart+ data={data}+ xKey="x"+ yKey="y"+ zKey="z"+ height={220}+ azimuth={azimuth}+ elevation={elevation}+ interactive+ autoRotate={0.3}>+ <XDS3DScatterGL+ color={mediaMode === 'dark' ? '#DFE2E5' : '#0A1317'}+ size={1.5}+ opacity={0.6}+ />+ </XDS3DChart>+ </div>+ <div+ style={{+ padding: '6px 12px',+ fontSize: 11,+ fontWeight: 500,+ color: 'var(--color-text-primary)',+ textAlign: 'center',+ letterSpacing: '0.05em',+ textTransform: 'uppercase',+ }}>+ {label}+ </div>+ </div>+ </XDSMediaTheme>+ );+}++// =============================================================================+// Stories+// =============================================================================++export const Gallery: StoryObj = {+ render: () => {+ const shapes = useMemo(+ () => [+ {data: teapot(3000), label: 'Teapot', az: 30, el: 25},+ {data: heart(2500), label: 'Heart', az: 0, el: 15},+ {data: seashell(3000), label: 'Seashell', az: 45, el: 30},+ {data: kleinBottle(2500), label: 'Klein Bottle', az: 50, el: 25},+ {data: star(2500), label: 'Star', az: 30, el: 35},+ {data: tree(3000), label: 'Tree', az: 35, el: 15},+ ],+ [],+ );++ const palettes: {bg: string; mode: 'dark' | 'light'}[] = [+ {bg: '#0064E0', mode: 'dark'},+ {bg: '#E3193B', mode: 'dark'},+ {bg: '#FBCE03', mode: 'light'},+ {bg: '#6B1EFD', mode: 'dark'},+ {bg: '#0B991F', mode: 'dark'},+ {bg: '#EB6E00', mode: 'dark'},+ ];++ return (+ <div+ style={{+ display: 'grid',+ gridTemplateColumns: 'repeat(3, 1fr)',+ gap: 12,+ maxWidth: 780,+ }}>+ {shapes.map((s, i) => (+ <Cell+ key={i}+ bg={palettes[i].bg}+ mediaMode={palettes[i].mode}+ data={s.data}+ label={s.label}+ azimuth={s.az}+ elevation={s.el}+ />+ ))}+ </div>+ );+ },+};++export const DarkGallery: StoryObj = {+ render: () => {+ const shapes = useMemo(+ () => [+ {data: teapot(3000), label: 'Teapot', az: 30, el: 25},+ {data: heart(2500), label: 'Heart', az: 0, el: 15},+ {data: seashell(3000), label: 'Seashell', az: 45, el: 30},+ {data: kleinBottle(2500), label: 'Klein Bottle', az: 50, el: 25},+ {data: star(2500), label: 'Star', az: 30, el: 35},+ {data: tree(3000), label: 'Tree', az: 35, el: 15},+ ],+ [],+ );++ const bgs = [+ '#1a1a2e',+ '#16213e',+ '#0f3460',+ '#1b1b2f',+ '#162447',+ '#1f1f38',+ ];++ return (+ <div+ style={{+ display: 'grid',+ gridTemplateColumns: 'repeat(3, 1fr)',+ gap: 12,+ maxWidth: 780,+ }}>+ {shapes.map((s, i) => (+ <Cell+ key={i}+ bg={bgs[i]}+ mediaMode="dark"+ data={s.data}+ label={s.label}+ azimuth={s.az}+ elevation={s.el}+ />+ ))}+ </div>+ );+ },+};++/** Side-by-side SVG vs WebGL — same data, same camera, same depth params */+export const SVGvsWebGL: StoryObj = {+ render: () => {+ const data = useMemo(() => {+ const phi = (1 + Math.sqrt(5)) / 2;+ return Array.from({length: 2000}, (_, i) => {+ const theta = Math.acos(1 - (2 * (i + 0.5)) / 2000);+ const p = (2 * Math.PI * i) / phi;+ return {+ x: Math.sin(theta) * Math.cos(p),+ y: Math.sin(theta) * Math.sin(p),+ z: Math.cos(theta),+ };+ });+ }, []);+ return (+ <div+ style={{+ display: 'grid',+ gridTemplateColumns: '1fr 1fr',+ gap: 12,+ maxWidth: 780,+ }}>+ <div+ style={{background: '#0064E0', borderRadius: 16, overflow: 'hidden'}}>+ <XDSMediaTheme mode="dark">+ <div+ style={{+ padding: '6px 12px',+ fontSize: 11,+ fontWeight: 500,+ color: 'var(--color-text-primary)',+ textAlign: 'center',+ letterSpacing: '0.05em',+ textTransform: 'uppercase',+ }}>+ SVG (XDS3DScatter)+ </div>+ <XDS3DChart+ data={data}+ xKey="x"+ yKey="y"+ zKey="z"+ height={300}+ azimuth={30}+ elevation={20}+ interactive+ autoRotate={0.3}>+ <XDS3DScatter color="#DFE2E5" radius={1.5} opacity={0.85} />+ </XDS3DChart>+ </XDSMediaTheme>+ </div>+ <div+ style={{background: '#0064E0', borderRadius: 16, overflow: 'hidden'}}>+ <XDSMediaTheme mode="dark">+ <div+ style={{+ padding: '6px 12px',+ fontSize: 11,+ fontWeight: 500,+ color: 'var(--color-text-primary)',+ textAlign: 'center',+ letterSpacing: '0.05em',+ textTransform: 'uppercase',+ }}>+ WebGL (XDS3DScatterGL)+ </div>+ <XDS3DChart+ data={data}+ xKey="x"+ yKey="y"+ zKey="z"+ height={300}+ azimuth={30}+ elevation={20}+ interactive+ autoRotate={0.3}>+ <XDS3DScatterGL color="#DFE2E5" size={3} opacity={0.85} />+ </XDS3DChart>+ </XDSMediaTheme>+ </div>+ </div>+ );+ },+};++/** Debug: 8 cube corners + center, labeled coordinates. SVG vs WebGL side by side. */+export const DebugProjection: StoryObj = {+ render: () => {+ const debugData = useMemo(+ () => [+ {x: 0, y: 0, z: 0},+ {x: 1, y: 0, z: 0},+ {x: 0, y: 1, z: 0},+ {x: 0, y: 0, z: 1},+ {x: 1, y: 1, z: 0},+ {x: 1, y: 0, z: 1},+ {x: 0, y: 1, z: 1},+ {x: 1, y: 1, z: 1},+ {x: 0.5, y: 0.5, z: 0.5},+ ],+ [],+ );++ return (+ <div+ style={{+ display: 'grid',+ gridTemplateColumns: '1fr 1fr',+ gap: 12,+ maxWidth: 780,+ }}>+ <div+ style={{+ border: '1px solid red',+ borderRadius: 8,+ overflow: 'hidden',+ }}>+ <div+ style={{+ padding: '4px 8px',+ fontSize: 11,+ fontWeight: 600,+ color: 'red',+ }}>+ SVG+ </div>+ <XDS3DChart+ data={debugData}+ xKey="x"+ yKey="y"+ zKey="z"+ height={300}+ azimuth={35}+ elevation={25}>+ <XDS3DScatter color="#E3193B" radius={6} opacity={1} />+ </XDS3DChart>+ </div>+ <div+ style={{+ border: '1px solid blue',+ borderRadius: 8,+ overflow: 'hidden',+ }}>+ <div+ style={{+ padding: '4px 8px',+ fontSize: 11,+ fontWeight: 600,+ color: 'blue',+ }}>+ WebGL+ </div>+ <XDS3DChart+ data={debugData}+ xKey="x"+ yKey="y"+ zKey="z"+ height={300}+ azimuth={35}+ elevation={25}>+ <XDS3DScatterGL color="#0064E0" size={12} opacity={1} />+ </XDS3DChart>+ </div>+ </div>+ );+ },+};+/** Debug: same 9 points, same color, overlaid on ONE chart — SVG circles + WebGL dots */+export const DebugOverlay: StoryObj = {+ render: () => {+ const debugData = useMemo(+ () => [+ {x: 0, y: 0, z: 0},+ {x: 1, y: 0, z: 0},+ {x: 0, y: 1, z: 0},+ {x: 0, y: 0, z: 1},+ {x: 1, y: 1, z: 0},+ {x: 1, y: 0, z: 1},+ {x: 0, y: 1, z: 1},+ {x: 1, y: 1, z: 1},+ {x: 0.5, y: 0.5, z: 0.5},+ ],+ [],+ );+ return (+ <div style={{border: '1px solid #ccc', borderRadius: 8, maxWidth: 500}}>+ <div style={{padding: '4px 8px', fontSize: 11}}>+ Red = SVG, Blue = WebGL. If Tier 1 holds, they overlap perfectly.+ </div>+ <XDS3DChart+ data={debugData}+ xKey="x"+ yKey="y"+ zKey="z"+ height={400}+ azimuth={35}+ elevation={25}>+ <XDS3DScatter color="#E3193B" radius={8} opacity={0.8} />+ <XDS3DScatterGL color="#0064E0" size={8} opacity={0.8} />+ </XDS3DChart>+ </div>+ );+ },+};++/** Debug: size/opacity parity — reduced grid to avoid WebGL context limit */+export const DebugSizeOpacity: StoryObj = {+ render: () => {+ const pt = useMemo(() => [{x: 0.5, y: 0.5, z: 0.5}], []);+ return (+ <div+ style={{+ display: 'flex',+ flexDirection: 'column',+ gap: 16,+ maxWidth: 700,+ }}>+ <div style={{fontSize: 11, fontWeight: 500}}>+ Size 16, \u03b1=1.0 — SVG only | GL only | SVG on GL | GL on SVG+ </div>+ <div style={{display: 'flex', gap: 4}}>+ <div+ style={{+ border: '1px solid #eee',+ borderRadius: 6,+ width: 120,+ textAlign: 'center',+ }}>+ <div style={{fontSize: 9, color: '#ccc'}}>SVG 16</div>+ <XDS3DChart+ data={pt}+ xKey="x"+ yKey="y"+ zKey="z"+ height={120}+ azimuth={0}+ elevation={0}>+ <XDS3DScatter color="#E3193B" radius={8} opacity={1} />+ </XDS3DChart>+ </div>+ <div+ style={{+ border: '1px solid #eee',+ borderRadius: 6,+ width: 120,+ textAlign: 'center',+ }}>+ <div style={{fontSize: 9, color: '#ccc'}}>GL 16</div>+ <XDS3DChart+ data={pt}+ xKey="x"+ yKey="y"+ zKey="z"+ height={120}+ azimuth={0}+ elevation={0}>+ <XDS3DScatterGL color="#0064E0" size={16} opacity={1} />+ </XDS3DChart>+ </div>+ <div+ style={{+ border: '1px solid #eee',+ borderRadius: 6,+ width: 120,+ textAlign: 'center',+ }}>+ <div style={{fontSize: 9, color: '#ccc'}}>SVG on GL</div>+ <XDS3DChart+ data={pt}+ xKey="x"+ yKey="y"+ zKey="z"+ height={120}+ azimuth={0}+ elevation={0}>+ <XDS3DScatterGL color="#0064E0" size={16} opacity={1} />+ <XDS3DScatter color="#E3193B" radius={8} opacity={1} />+ </XDS3DChart>+ </div>+ <div+ style={{+ border: '1px solid #eee',+ borderRadius: 6,+ width: 120,+ textAlign: 'center',+ }}>+ <div style={{fontSize: 9, color: '#ccc'}}>GL on SVG</div>+ <XDS3DChart+ data={pt}+ xKey="x"+ yKey="y"+ zKey="z"+ height={120}+ azimuth={0}+ elevation={0}>+ <XDS3DScatter color="#E3193B" radius={8} opacity={1} />+ <XDS3DScatterGL color="#0064E0" size={16} opacity={1} />+ </XDS3DChart>+ </div>+ </div>+ <div style={{fontSize: 11, fontWeight: 500}}>Size 16, \u03b1=0.5</div>+ <div style={{display: 'flex', gap: 4}}>+ <div+ style={{+ border: '1px solid #eee',+ borderRadius: 6,+ width: 120,+ textAlign: 'center',+ }}>+ <div style={{fontSize: 9, color: '#ccc'}}>SVG on GL</div>+ <XDS3DChart+ data={pt}+ xKey="x"+ yKey="y"+ zKey="z"+ height={120}+ azimuth={0}+ elevation={0}>+ <XDS3DScatterGL color="#0064E0" size={16} opacity={0.5} />+ <XDS3DScatter color="#E3193B" radius={8} opacity={0.5} />+ </XDS3DChart>+ </div>+ <div+ style={{+ border: '1px solid #eee',+ borderRadius: 6,+ width: 120,+ textAlign: 'center',+ }}>+ <div style={{fontSize: 9, color: '#ccc'}}>GL on SVG</div>+ <XDS3DChart+ data={pt}+ xKey="x"+ yKey="y"+ zKey="z"+ height={120}+ azimuth={0}+ elevation={0}>+ <XDS3DScatter color="#E3193B" radius={8} opacity={0.5} />+ <XDS3DScatterGL color="#0064E0" size={16} opacity={0.5} />+ </XDS3DChart>+ </div>+ </div>+ </div>+ );+ },+};diff --git a/packages/lab/src/Chart/XDSChartDotGL.tsx b/packages/lab/src/Chart/XDSChartDotGL.tsxindex d7c445ba4f..f16b8bfdec 100644--- a/packages/lab/src/Chart/XDSChartDotGL.tsx+++ b/packages/lab/src/Chart/XDSChartDotGL.tsx@@ -1,40 +1,41 @@/*** @file XDSChartDotGL.tsx- * @output WebGL scatter renderer — canvas overlay aligned with SVG chart space- * @position Child of XDSChart; reads scales from context, renders to a canvas via foreignObject+ * @output WebGL scatter — single draw call, canvas mounted outside SVG for sharp DPR+ * @position Child of XDSChart; reads scales from context*/import {useRef, useEffect, useCallback} from 'react';import {useChart} from './ChartContext';import {xPixel} from './utils';+import {+ hexToGL,+ getCanvasDPR,+ getWebGLContext,+ setupGLState,+ sizeCanvas,+ mountCanvasOverSVG,+ createProgram,+ CIRCLE_FRAG_BODY,+ POINT_SIZE_COMPENSATION,+} from './webgl';export interface XDSChartDotGLProps {- /** Which data key for the y values */dataKey: string;- /** Dot fill color (hex string) */color: string;- /** Point size in pixels */size?: number;- /** Opacity 0-1 */opacity?: number;}-/** Parse hex color to [r, g, b] floats 0-1 */-function hexToGL(hex: string): [number, number, number] {- const n = parseInt(hex.replace('#', ''), 16);- return [(n >> 16) / 255, ((n >> 8) & 0xff) / 255, (n & 0xff) / 255];-}-const VERT = `attribute vec2 a_position;uniform vec2 u_resolution;uniform float u_size;+ varying float v_alpha;void main() {- // Convert pixel coords to clip space (-1 to 1)vec2 clip = (a_position / u_resolution) * 2.0 - 1.0;- // Flip y — canvas y goes down, clip y goes upgl_Position = vec4(clip.x, -clip.y, 0.0, 1.0);- gl_PointSize = u_size;+ gl_PointSize = u_size * ${POINT_SIZE_COMPENSATION.toFixed(6)};+ v_alpha = 1.0;}`;@@ -42,54 +43,24 @@ const FRAG = `precision mediump float;uniform vec3 u_color;uniform float u_opacity;+ varying float v_alpha;void main() {- // Circle mask — discard outside radius+ float v_alpha_final = u_opacity;vec2 coord = gl_PointCoord - vec2(0.5);- if (dot(coord, coord) > 0.25) discard;- gl_FragColor = vec4(u_color, u_opacity);+ float dist = length(coord);+ if (dist > 0.5) discard;+ float edge = 1.0 - smoothstep(0.48, 0.5, dist);+ float a = v_alpha_final * edge;+ gl_FragColor = vec4(u_color * a, a);}`;-function compileShader(- gl: WebGLRenderingContext,- type: number,- source: string,-): WebGLShader | null {- const shader = gl.createShader(type);- if (!shader) return null;- gl.shaderSource(shader, source);- gl.compileShader(shader);- if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {- gl.deleteShader(shader);- return null;- }- return shader;-}--function createProgram(gl: WebGLRenderingContext): WebGLProgram | null {- const vert = compileShader(gl, gl.VERTEX_SHADER, VERT);- const frag = compileShader(gl, gl.FRAGMENT_SHADER, FRAG);- if (!vert || !frag) return null;- const program = gl.createProgram();- if (!program) return null;- gl.attachShader(program, vert);- gl.attachShader(program, frag);- gl.linkProgram(program);- if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {- gl.deleteProgram(program);- return null;- }- return program;-}-/**- * WebGL scatter plot. Renders points on a canvas overlay aligned with the SVG chart.- * Use for large datasets (1k+ points) where SVG circles would be slow.+ * WebGL scatter plot. Canvas mounted outside SVG for sharp Retina rendering.** @example* ```- * <XDSChartDotGL dataKey="value" color={useXDSChartColors().categorical(1)[0]} />- * <XDSChartDotGL dataKey="value" color="#0171E3" size={4} opacity={0.6} />+ * <XDSChartDotGL dataKey="value" color={colors.categorical(1)[0]} />* ```*/export function XDSChartDotGL({@@ -99,11 +70,11 @@ export function XDSChartDotGL({opacity = 0.8,}: XDSChartDotGLProps) {const {data, xKey, xScale, yScale, width, height} = useChart();- const canvasRef = useRef<HTMLCanvasElement>(null);+ const canvasRef = useRef<HTMLCanvasElement | null>(null);const glRef = useRef<WebGLRenderingContext | null>(null);const programRef = useRef<WebGLProgram | null>(null);+ const markerRef = useRef<SVGGElement>(null);- // Compute pixel positions from scalesconst getPositions = useCallback((): Float32Array => {const positions: number[] = [];for (const d of data) {@@ -114,89 +85,52 @@ export function XDSChartDotGL({return new Float32Array(positions);}, [data, xKey, dataKey, xScale, yScale]);+ // Mount canvas outside SVG+ useEffect(() => {+ const marker = markerRef.current;+ if (!marker) return;+ if (!canvasRef.current)+ canvasRef.current = document.createElement('canvas');+ return mountCanvasOverSVG(marker, canvasRef.current, width, height);+ }, [width, height]);++ // DrawuseEffect(() => {const canvas = canvasRef.current;if (!canvas || width <= 0 || height <= 0) return;- // Set canvas size (account for device pixel ratio for sharp rendering)- const dpr = window.devicePixelRatio || 1;- canvas.width = width * dpr;- canvas.height = height * dpr;- canvas.style.width = `${width}px`;- canvas.style.height = `${height}px`;-- // Init WebGL- let gl = glRef.current;- if (!gl) {- gl = canvas.getContext('webgl', {- alpha: true,- premultipliedAlpha: false,- antialias: true,- });- if (!gl) return;- glRef.current = gl;- }+ const dpr = sizeCanvas(canvas, width, height);- // Init program- let program = programRef.current;- if (!program) {- program = createProgram(gl);- if (!program) return;- programRef.current = program;- }+ if (!glRef.current) glRef.current = getWebGLContext(canvas);+ const gl = glRef.current;+ if (!gl) return;- gl.viewport(0, 0, canvas.width, canvas.height);- gl.clearColor(0, 0, 0, 0);- gl.clear(gl.COLOR_BUFFER_BIT);- gl.enable(gl.BLEND);- gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);+ if (!programRef.current) programRef.current = createProgram(gl, VERT, FRAG);+ const program = programRef.current;+ if (!program) return;+ gl.viewport(0, 0, canvas.width, canvas.height);+ setupGLState(gl);gl.useProgram(program);- // Upload positionsconst positions = getPositions();const posBuffer = gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER, posBuffer);gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW);-const aPos = gl.getAttribLocation(program, 'a_position');gl.enableVertexAttribArray(aPos);gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 0, 0);- // Uniformsconst [r, g, b] = hexToGL(color);- // Resolution in logical pixels — positions from xPixel/yScale are logical.- // The viewport is set to physical pixels (width*dpr) for sharp rendering,- // but the shader maps logical positions → clip space via u_resolution.gl.uniform2f(gl.getUniformLocation(program, 'u_resolution'), width, height);gl.uniform3f(gl.getUniformLocation(program, 'u_color'), r, g, b);gl.uniform1f(gl.getUniformLocation(program, 'u_size'), size * dpr);gl.uniform1f(gl.getUniformLocation(program, 'u_opacity'), opacity);- // Drawgl.drawArrays(gl.POINTS, 0, positions.length / 2);-- // Cleanup buffergl.deleteBuffer(posBuffer);}, [width, height, color, size, opacity, getPositions]);if (width <= 0 || height <= 0) return null;-- return (- <foreignObject- x={0}- y={0}- width={width}- height={height}- style={{overflow: 'hidden'}}>- <canvas- ref={canvasRef}- style={{- width,- height,- pointerEvents: 'none',- }}- />- </foreignObject>- );+ return <g ref={markerRef} />;}diff --git a/packages/lab/src/Chart/XDSChartHeatmapGL.tsx b/packages/lab/src/Chart/XDSChartHeatmapGL.tsxindex f710f459ac..c49161c6e5 100644--- a/packages/lab/src/Chart/XDSChartHeatmapGL.tsx+++ b/packages/lab/src/Chart/XDSChartHeatmapGL.tsx@@ -1,11 +1,7 @@/*** @file XDSChartHeatmapGL.tsx- * @output WebGL heatmap — 2D grid of color-mapped cells- * @position Child of XDSChart; manages its own row (y) band scale- *- * Renders a grid where x positions come from the chart's xScale (band)- * and y positions come from a second categorical key. Each cell is colored- * by interpolating a sequential palette based on the value key.+ * @output WebGL heatmap — 2D grid, canvas mounted outside SVG+ * @position Child of XDSChart; manages its own y band scale for rows*/import {useRef, useEffect, useMemo} from 'react';@@ -13,30 +9,24 @@ import {scaleBand} from 'd3-scale';import {useChart} from './ChartContext';import {isBandScale} from './utils';import type {ScaleBand} from 'd3-scale';+import {+ hexToGL,+ getWebGLContext,+ setupGLState,+ sizeCanvas,+ mountCanvasOverSVG,+ createProgram,+} from './webgl';export interface XDSChartHeatmapGLProps {- /** Data key for x-axis categories (columns) */xKey: string;- /** Data key for y-axis categories (rows) */yKey: string;- /** Data key containing the numeric intensity value */valueKey: string;- /**- * Color ramp — array of hex colors from low to high intensity.- * Use useXDSChartColors().sequential.blue(5) or similar.- */colorRange: string[];- /** Explicit domain [min, max]. If omitted, computed from data. */domain?: [number, number];- /** Gap between cells in pixels (default: 1) */cellGap?: number;}-function hexToGL(hex: string): [number, number, number] {- const n = parseInt(hex.replace('#', ''), 16);- return [(n >> 16) / 255, ((n >> 8) & 0xff) / 255, (n & 0xff) / 255];-}-const VERT = `attribute vec2 a_position;attribute vec3 a_color;@@ -57,68 +47,23 @@ const FRAG = `}`;-function compileShader(- gl: WebGLRenderingContext,- type: number,- source: string,-): WebGLShader | null {- const shader = gl.createShader(type);- if (!shader) return null;- gl.shaderSource(shader, source);- gl.compileShader(shader);- if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {- gl.deleteShader(shader);- return null;- }- return shader;-}--function createProgram(gl: WebGLRenderingContext): WebGLProgram | null {- const vert = compileShader(gl, gl.VERTEX_SHADER, VERT);- const frag = compileShader(gl, gl.FRAGMENT_SHADER, FRAG);- if (!vert || !frag) return null;- const program = gl.createProgram();- if (!program) return null;- gl.attachShader(program, vert);- gl.attachShader(program, frag);- gl.linkProgram(program);- if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {- gl.deleteProgram(program);- return null;- }- return program;-}-function sampleRamp(ramp: [number, number, number][],t: number,): [number, number, number] {- const clamped = Math.max(0, Math.min(1, t));+ const c = Math.max(0, Math.min(1, t));if (ramp.length === 1) return ramp[0];- const scaled = clamped * (ramp.length - 1);- const lo = Math.floor(scaled);+ const s = c * (ramp.length - 1);+ const lo = Math.floor(s);const hi = Math.min(lo + 1, ramp.length - 1);- const frac = scaled - lo;+ const f = s - lo;return [- ramp[lo][0] + frac * (ramp[hi][0] - ramp[lo][0]),- ramp[lo][1] + frac * (ramp[hi][1] - ramp[lo][1]),- ramp[lo][2] + frac * (ramp[hi][2] - ramp[lo][2]),+ ramp[lo][0] + f * (ramp[hi][0] - ramp[lo][0]),+ ramp[lo][1] + f * (ramp[hi][1] - ramp[lo][1]),+ ramp[lo][2] + f * (ramp[hi][2] - ramp[lo][2]),];}-/**- * WebGL heatmap grid. Two categorical axes (xKey × yKey) with cells colored by valueKey.- *- * @example- * ```- * <XDSChartHeatmapGL- * xKey="hour"- * yKey="day"- * valueKey="activity"- * colorRange={useXDSChartColors().sequential.blue(5)}- * />- * ```- */export function XDSChartHeatmapGL({xKey,yKey,@@ -128,26 +73,22 @@ export function XDSChartHeatmapGL({cellGap = 1,}: XDSChartHeatmapGLProps) {const {data, xScale, width, height} = useChart();- const canvasRef = useRef<HTMLCanvasElement>(null);+ const canvasRef = useRef<HTMLCanvasElement | null>(null);const glRef = useRef<WebGLRenderingContext | null>(null);const programRef = useRef<WebGLProgram | null>(null);+ const markerRef = useRef<SVGGElement>(null);const ramp = useMemo(() => colorRange.map(hexToGL), [colorRange]);- // Build row (y) band scale from unique yKey valuesconst yBandScale = useMemo(() => {- const yCategories = [...new Set(data.map(d => String(d[yKey])))];- return scaleBand<string>()- .domain(yCategories)- .range([0, height])- .padding(0.05);+ const cats = [...new Set(data.map(d => String(d[yKey])))];+ return scaleBand<string>().domain(cats).range([0, height]).padding(0.05);}, [data, yKey, height]);- // Value domainconst domain = useMemo((): [number, number] => {if (domainProp) return domainProp;- let min = Infinity;- let max = -Infinity;+ let min = Infinity,+ max = -Infinity;for (const d of data) {const v = d[valueKey];if (typeof v === 'number') {@@ -158,37 +99,32 @@ export function XDSChartHeatmapGL({return [min, max];}, [data, valueKey, domainProp]);+ // Mount canvas+ useEffect(() => {+ const marker = markerRef.current;+ if (!marker) return;+ if (!canvasRef.current)+ canvasRef.current = document.createElement('canvas');+ return mountCanvasOverSVG(marker, canvasRef.current, width, height);+ }, [width, height]);++ // DrawuseEffect(() => {const canvas = canvasRef.current;if (!canvas || width <= 0 || height <= 0 || !isBandScale(xScale)) return;- const dpr = window.devicePixelRatio || 1;- canvas.width = width * dpr;- canvas.height = height * dpr;- canvas.style.width = `${width}px`;- canvas.style.height = `${height}px`;+ const dpr = sizeCanvas(canvas, width, height);- let gl = glRef.current;- if (!gl) {- gl = canvas.getContext('webgl', {- alpha: true,- premultipliedAlpha: false,- antialias: false,- });- if (!gl) return;- glRef.current = gl;- }+ if (!glRef.current) glRef.current = getWebGLContext(canvas);+ const gl = glRef.current;+ if (!gl) return;- let program = programRef.current;- if (!program) {- program = createProgram(gl);- if (!program) return;- programRef.current = program;- }+ if (!programRef.current) programRef.current = createProgram(gl, VERT, FRAG);+ const program = programRef.current;+ if (!program) return;gl.viewport(0, 0, canvas.width, canvas.height);- gl.clearColor(0, 0, 0, 0);- gl.clear(gl.COLOR_BUFFER_BIT);+ setupGLState(gl);gl.useProgram(program);const positions: number[] = [];@@ -196,7 +132,6 @@ export function XDSChartHeatmapGL({const [dMin, dMax] = domain;const range = dMax - dMin || 1;const gap = cellGap;-const xBW = xScale.bandwidth();const yBW = yBandScale.bandwidth();@@ -214,9 +149,7 @@ export function XDSChartHeatmapGL({const y0 = yVal + gap / 2;const y1 = yVal + yBW - gap / 2;- // Two triangles per cell- positions.push(x0, y0, x1, y0, x0, y1);- positions.push(x1, y0, x1, y1, x0, y1);+ positions.push(x0, y0, x1, y0, x0, y1, x1, y0, x1, y1, x0, y1);for (let i = 0; i < 6; i++) colors.push(r, g, b);}@@ -234,7 +167,6 @@ export function XDSChartHeatmapGL({gl.enableVertexAttribArray(aCol);gl.vertexAttribPointer(aCol, 3, gl.FLOAT, false, 0, 0);- // Logical pixels — positions are in logical space, viewport handles DPRgl.uniform2f(gl.getUniformLocation(program, 'u_resolution'), width, height);gl.drawArrays(gl.TRIANGLES, 0, positions.length / 2);@@ -255,15 +187,5 @@ export function XDSChartHeatmapGL({]);if (width <= 0 || height <= 0) return null;-- return (- <foreignObject- x={0}- y={0}- width={width}- height={height}- style={{overflow: 'hidden'}}>- <canvas ref={canvasRef} style={{width, height, pointerEvents: 'none'}} />- </foreignObject>- );+ return <g ref={markerRef} />;}diff --git a/packages/lab/src/Chart/XDSChartStreamGL.tsx b/packages/lab/src/Chart/XDSChartStreamGL.tsxindex abb4f9fa9a..380a1679e6 100644--- a/packages/lab/src/Chart/XDSChartStreamGL.tsx+++ b/packages/lab/src/Chart/XDSChartStreamGL.tsx@@ -1,11 +1,9 @@/*** @file XDSChartStreamGL.tsx- * @output WebGL streaming time-series renderer — ring buffer drawn as a line strip- * @position Child of XDSChart; uses the chart's yScale for y-mapping+ * @output WebGL streaming time-series line — ring buffer, canvas outside SVG+ * @position Child of XDSChart; uses the chart's xScale/yScale for mapping*- * The y-axis domain is controlled by XDSChart (via yDomain/yBaseline).- * The x-axis domain is controlled by XDSChart (via xDomain).- * Both axes, grid, and stream data map through the same scales.+ * Y-axis and x-axis domains are controlled by XDSChart.* For streaming, the parent should update xDomain as new data arrives.*/@@ -17,30 +15,27 @@ import {useCallback,} from 'react';import {useChart} from './ChartContext';+import {+ hexToGL,+ getWebGLContext,+ setupGLState,+ sizeCanvas,+ mountCanvasOverSVG,+ createProgram,+} from './webgl';export interface XDSChartStreamGLProps {- /** Line stroke color (hex) */color: string;- /** Max number of points in the buffer (default: 500) */bufferSize?: number;- /** Line width in pixels (default: 2) */lineWidth?: number;- /** Opacity 0-1 */opacity?: number;}export interface XDSChartStreamGLHandle {- /** Push a new [x, y] point into the ring buffer and redraw */push(x: number, y: number): void;- /** Clear the buffer */clear(): void;}-function hexToGL(hex: string): [number, number, number] {- const n = parseInt(hex.replace('#', ''), 16);- return [(n >> 16) / 255, ((n >> 8) & 0xff) / 255, (n & 0xff) / 255];-}-const VERT = `attribute vec2 a_position;uniform vec2 u_resolution;@@ -55,61 +50,11 @@ const FRAG = `uniform vec3 u_color;uniform float u_opacity;void main() {- gl_FragColor = vec4(u_color, u_opacity);+ float a = u_opacity;+ gl_FragColor = vec4(u_color * a, a);}`;-function compileShader(- gl: WebGLRenderingContext,- type: number,- source: string,-): WebGLShader | null {- const shader = gl.createShader(type);- if (!shader) return null;- gl.shaderSource(shader, source);- gl.compileShader(shader);- if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {- gl.deleteShader(shader);- return null;- }- return shader;-}--function createProgram(gl: WebGLRenderingContext): WebGLProgram | null {- const vert = compileShader(gl, gl.VERTEX_SHADER, VERT);- const frag = compileShader(gl, gl.FRAGMENT_SHADER, FRAG);- if (!vert || !frag) return null;- const program = gl.createProgram();- if (!program) return null;- gl.attachShader(program, vert);- gl.attachShader(program, frag);- gl.linkProgram(program);- if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {- gl.deleteProgram(program);- return null;- }- return program;-}--/**- * WebGL streaming time-series line. Ring buffer — push new points without- * React re-renders.- *- * Y-axis is controlled by the parent XDSChart's yDomain/yBaseline.- * X-axis is a sliding window (oldest point at left, newest at right).- *- * @example- * ```- * const [xDomain, setXDomain] = useState<[number, number]>([0, 100]);- *- * <XDSChart data={[]} xKey="t" yKeys={[]} yDomain={[0, 100]} xDomain={xDomain} height={200}>- * <XDSChartGrid horizontal />- * <XDSChartAxis position="bottom" />- * <XDSChartAxis position="left" />- * <XDSChartStreamGL ref={streamRef} color="#0171E3" />- * </XDSChart>- * ```- */export const XDSChartStreamGL = forwardRef<XDSChartStreamGLHandle,XDSChartStreamGLProps@@ -118,28 +63,50 @@ export const XDSChartStreamGL = forwardRef<ref,) {const {width, height, xScale, yScale} = useChart();- const canvasRef = useRef<HTMLCanvasElement>(null);+ const canvasRef = useRef<HTMLCanvasElement | null>(null);const glRef = useRef<WebGLRenderingContext | null>(null);const programRef = useRef<WebGLProgram | null>(null);const bufRef = useRef<WebGLBuffer | null>(null);+ const markerRef = useRef<SVGGElement>(null);- // Ring buffer — raw data only, no domain trackingconst ring = useRef({data: new Float32Array(bufferSize * 2),head: 0,count: 0,});+ // Mount canvas outside SVG+ useEffect(() => {+ const marker = markerRef.current;+ if (!marker) return;+ if (!canvasRef.current)+ canvasRef.current = document.createElement('canvas');+ return mountCanvasOverSVG(marker, canvasRef.current, width, height);+ }, [width, height]);++ // Size canvas+ useEffect(() => {+ const canvas = canvasRef.current;+ if (!canvas || width <= 0 || height <= 0) return;+ sizeCanvas(canvas, width, height);+ }, [width, height]);+const draw = useCallback(() => {+ const canvas = canvasRef.current;+ if (!canvas) return;+ if (!glRef.current) glRef.current = getWebGLContext(canvas);const gl = glRef.current;+ if (!gl) return;++ if (!programRef.current) programRef.current = createProgram(gl, VERT, FRAG);const program = programRef.current;- const buffer = bufRef.current;- if (!gl || !program || !buffer) return;+ if (!program) return;++ if (!bufRef.current) bufRef.current = gl.createBuffer();const {data: ringData, head, count} = ring.current;if (count < 2) return;- // Map to pixel space: both x and y from chart's scalesconst linearX = xScale as (v: number) => number;const drawBuf = new Float32Array(count * 2);for (let i = 0; i < count; i++) {@@ -148,15 +115,11 @@ export const XDSChartStreamGL = forwardRef<drawBuf[i * 2 + 1] = yScale(ringData[idx + 1]);}- gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);- gl.clearColor(0, 0, 0, 0);- gl.clear(gl.COLOR_BUFFER_BIT);- gl.enable(gl.BLEND);- gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);-+ gl.viewport(0, 0, canvas.width, canvas.height);+ setupGLState(gl);gl.useProgram(program);- gl.bindBuffer(gl.ARRAY_BUFFER, buffer);+ gl.bindBuffer(gl.ARRAY_BUFFER, bufRef.current);gl.bufferData(gl.ARRAY_BUFFER, drawBuf, gl.DYNAMIC_DRAW);const aPos = gl.getAttribLocation(program, 'a_position');@@ -164,7 +127,6 @@ export const XDSChartStreamGL = forwardRef<gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 0, 0);const [r, g, b] = hexToGL(color);- // Logical pixels — positions are in logical space, viewport handles DPRgl.uniform2f(gl.getUniformLocation(program, 'u_resolution'), width, height);gl.uniform3f(gl.getUniformLocation(program, 'u_color'), r, g, b);gl.uniform1f(gl.getUniformLocation(program, 'u_opacity'), opacity);@@ -198,45 +160,6 @@ export const XDSChartStreamGL = forwardRef<[bufferSize, draw],);- useEffect(() => {- const canvas = canvasRef.current;- if (!canvas || width <= 0 || height <= 0) return;-- const dpr = window.devicePixelRatio || 1;- canvas.width = width * dpr;- canvas.height = height * dpr;- canvas.style.width = `${width}px`;- canvas.style.height = `${height}px`;-- if (!glRef.current) {- const gl = canvas.getContext('webgl', {- alpha: true,- premultipliedAlpha: false,- antialias: true,- });- if (!gl) return;- glRef.current = gl;- }-- if (!programRef.current) {- programRef.current = createProgram(glRef.current);- }-- if (!bufRef.current) {- bufRef.current = glRef.current.createBuffer();- }- }, [width, height]);-if (width <= 0 || height <= 0) return null;-- return (- <foreignObject- x={0}- y={0}- width={width}- height={height}- style={{overflow: 'hidden'}}>- <canvas ref={canvasRef} style={{width, height, pointerEvents: 'none'}} />- </foreignObject>- );+ return <g ref={markerRef} />;});diff --git a/packages/lab/src/Chart/index.ts b/packages/lab/src/Chart/index.tsindex baa3710608..ea393b80ba 100644--- a/packages/lab/src/Chart/index.ts+++ b/packages/lab/src/Chart/index.ts@@ -47,3 +47,15 @@ export {type UseXDSChartRangeOptions,type UseXDSChartRangeReturn,} from './useXDSChartRange';+export {+ hexToGL,+ getCanvasDPR,+ getWebGLContext,+ setupGLState,+ sizeCanvas,+ mountCanvasOverSVG,+ compileShader,+ createProgram as createGLProgram,+ CIRCLE_FRAG_BODY,+ POINT_SIZE_COMPENSATION,+} from './webgl';diff --git a/packages/lab/src/Chart/webgl.ts b/packages/lab/src/Chart/webgl.tsnew file mode 100644index 0000000000..fe0b45512a--- /dev/null+++ b/packages/lab/src/Chart/webgl.ts@@ -0,0 +1,181 @@+/**+ * @file webgl.ts+ * @output Shared WebGL utilities for chart components+ * @position Internal helpers; consumed by all GL mark components+ *+ * Provides:+ * - Canvas mounting outside SVG (avoids foreignObject DPR blur)+ * - Premultiplied alpha setup (correct compositing over page)+ * - Shader compilation helpers+ * - Smoothstep circle fragment for crisp point sprites+ */++/** Compile a WebGL shader, returns null on failure */+export function compileShader(+ gl: WebGLRenderingContext,+ type: number,+ src: string,+): WebGLShader | null {+ const s = gl.createShader(type);+ if (!s) return null;+ gl.shaderSource(s, src);+ gl.compileShader(s);+ if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) {+ gl.deleteShader(s);+ return null;+ }+ return s;+}++/** Link a vertex + fragment shader into a program */+export function createProgram(+ gl: WebGLRenderingContext,+ vertSrc: string,+ fragSrc: string,+): WebGLProgram | null {+ const vs = compileShader(gl, gl.VERTEX_SHADER, vertSrc);+ const fs = compileShader(gl, gl.FRAGMENT_SHADER, fragSrc);+ if (!vs || !fs) return null;+ const p = gl.createProgram();+ if (!p) return null;+ gl.attachShader(p, vs);+ gl.attachShader(p, fs);+ gl.linkProgram(p);+ if (!gl.getProgramParameter(p, gl.LINK_STATUS)) {+ gl.deleteProgram(p);+ return null;+ }+ return p;+}++/** Parse hex (#RRGGBB) to [r, g, b] floats 0-1 */+export function hexToGL(hex: string): [number, number, number] {+ const n = parseInt(hex.replace('#', ''), 16);+ return [(n >> 16) / 255, ((n >> 8) & 0xff) / 255, (n & 0xff) / 255];+}++/** DPR with supersampling for crisp circles */+export function getCanvasDPR(): number {+ return (window.devicePixelRatio || 2) * 2;+}++/**+ * Create or get a WebGL context with correct alpha settings.+ * Uses premultiplied alpha for correct compositing over the page.+ */+export function getWebGLContext(+ canvas: HTMLCanvasElement,+): WebGLRenderingContext | null {+ return canvas.getContext('webgl', {+ alpha: true,+ premultipliedAlpha: true,+ antialias: true,+ });+}++/**+ * Set up standard GL state for chart rendering:+ * - Clear with transparent+ * - Enable premultiplied alpha blending+ */+export function setupGLState(gl: WebGLRenderingContext): void {+ gl.clearColor(0, 0, 0, 0);+ gl.clear(gl.COLOR_BUFFER_BIT);+ gl.enable(gl.BLEND);+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);+}++/**+ * Size a canvas for sharp rendering, accounting for DPR.+ * Returns the DPR used.+ */+export function sizeCanvas(+ canvas: HTMLCanvasElement,+ width: number,+ height: number,+): number {+ const dpr = getCanvasDPR();+ canvas.width = width * dpr;+ canvas.height = height * dpr;+ canvas.style.width = `${width}px`;+ canvas.style.height = `${height}px`;+ return dpr;+}++/**+ * Mount a canvas as an absolute-positioned sibling to an SVG element.+ * Automatically aligns with the SVG marker's position — no manual margin+ * offset needed. This is a Tier 1 guarantee: the canvas lands exactly+ * where the SVG content area is, regardless of chart margins or transforms.+ *+ * Call from a useEffect. Returns a cleanup function.+ */+export function mountCanvasOverSVG(+ svgMarker: SVGElement,+ canvas: HTMLCanvasElement,+ width: number,+ height: number,+): (() => void) | undefined {+ const svg = svgMarker.ownerSVGElement;+ if (!svg) return;+ const parent = svg.parentElement;+ if (!parent) return;++ if (getComputedStyle(parent).position === 'static') {+ parent.style.position = 'relative';+ }++ canvas.style.position = 'absolute';+ canvas.style.pointerEvents = 'none';++ // Compute offset from the SVG marker's actual screen position.+ // The marker sits inside the chart's <g transform="translate(margin)">+ // so its bounding rect includes the margin offset automatically.+ // This is a Tier 1 guarantee — we derive position from the SVG, not from props.+ const svgRect = svg.getBoundingClientRect();+ const parentRect = parent.getBoundingClientRect();+ const markerCTM = svgMarker.getScreenCTM();+ if (markerCTM) {+ canvas.style.left = `${markerCTM.e - parentRect.left}px`;+ canvas.style.top = `${markerCTM.f - parentRect.top}px`;+ } else {+ canvas.style.left = '0';+ canvas.style.top = '0';+ }+ canvas.style.width = `${width}px`;+ canvas.style.height = `${height}px`;++ parent.appendChild(canvas);++ return () => {+ if (canvas.parentElement === parent) {+ parent.removeChild(canvas);+ }+ };+}++/**+ * GLSL fragment for premultiplied-alpha circle with smoothstep AA.+ * Use in fragment shaders that render point sprites.+ *+ * Expects:+ * - varying float v_alpha (the final alpha before edge AA)+ * - uniform vec3 u_color+ *+ * Returns: gl_FragColor with premultiplied alpha+ */+export const CIRCLE_FRAG_BODY = `+ vec2 coord = gl_PointCoord - vec2(0.5);+ float dist = length(coord);+ if (dist > 0.5) discard;+ float edge = 1.0 - smoothstep(0.48, 0.5, dist);+ float a = v_alpha * edge;+ gl_FragColor = vec4(u_color * a, a);+`;++/**+ * Smoothstep compensation factor for gl_PointSize.+ * The visible circle radius is 0.48 of the point sprite (smoothstep starts there),+ * so we scale up by 1/0.96 to match SVG circle radius exactly.+ */+export const POINT_SIZE_COMPENSATION = 1.0 / 0.96;diff --git a/packages/lab/src/ThreeD/XDS3DChart.tsx b/packages/lab/src/ThreeD/XDS3DChart.tsxindex d681d33203..fae19d7855 100644--- a/packages/lab/src/ThreeD/XDS3DChart.tsx+++ b/packages/lab/src/ThreeD/XDS3DChart.tsx@@ -9,6 +9,7 @@ import {useMemo,useRef,useState,+ useEffect,useLayoutEffect,useCallback,} from 'react';@@ -27,6 +28,8 @@ export interface XDS3DChartProps {azimuth?: number;elevation?: number;interactive?: boolean;+ /** Auto-rotate speed in degrees per frame (default: 0 = off) */+ autoRotate?: number;children: ReactNode;}@@ -58,6 +61,7 @@ export function XDS3DChart({azimuth: azimuthProp = 35,elevation: elevationProp = 25,interactive = false,+ autoRotate = 0,children,}: XDS3DChartProps) {const containerRef = useRef<HTMLDivElement>(null);@@ -92,6 +96,10 @@ export function XDS3DChart({return range === 0 ? 0.5 : (value - domain[0]) / range;}, []);+ // Projection: normalized [0,1]^3 → 2D pixel coords+ // SYNC: This math is replicated in XDS3DScatterGL's vertex shader.+ // Both must produce identical output. Verified by projection.test.ts.+ // If you change this, update the shader and re-run the parity tests.const project = useMemo(() => {const azRad = (camera.azimuth * Math.PI) / 180;const elRad = (camera.elevation * Math.PI) / 180;@@ -145,6 +153,25 @@ export function XDS3DChart({dragRef.current = null;}, []);+ // Auto-rotation — throttled to ~20fps to avoid overwhelming React with re-renders+ useEffect(() => {+ if (autoRotate === 0) return;+ let raf: number;+ let lastUpdate = 0;+ const interval = 50; // ms between React updates (~20fps)+ const tick = (now: number) => {+ if (!dragRef.current && now - lastUpdate >= interval) {+ const elapsed = lastUpdate === 0 ? interval : now - lastUpdate;+ lastUpdate = now;+ const degrees = autoRotate * (elapsed / 16.67); // normalize to 60fps equivalent+ setCamera(prev => ({...prev, azimuth: prev.azimuth + degrees}));+ }+ raf = requestAnimationFrame(tick);+ };+ raf = requestAnimationFrame(tick);+ return () => cancelAnimationFrame(raf);+ }, [autoRotate]);+const ctx = useMemo(() => ({width,diff --git a/packages/lab/src/ThreeD/XDS3DScatter.tsx b/packages/lab/src/ThreeD/XDS3DScatter.tsxindex a6d661dccd..8c2271d3ab 100644--- a/packages/lab/src/ThreeD/XDS3DScatter.tsx+++ b/packages/lab/src/ThreeD/XDS3DScatter.tsx@@ -15,7 +15,7 @@ export interface XDS3DScatterProps {export function XDS3DScatter({color,radius = 4,- opacity = 0.8,+ opacity = 0.85,}: XDS3DScatterProps) {const {data,@@ -44,7 +44,7 @@ export function XDS3DScatter({return (<g>{points.map(p => {- const depthFactor = 0.5 + (p.depth + 0.5) * 0.5; // 0.5-1.0+ const depthFactor = 0.75 + (p.depth + 0.5) * 0.25; // 0.5-1.0return (<circlekey={p.index}diff --git a/packages/lab/src/ThreeD/XDS3DScatterGL.tsx b/packages/lab/src/ThreeD/XDS3DScatterGL.tsxnew file mode 100644index 0000000000..f31d3f57cb--- /dev/null+++ b/packages/lab/src/ThreeD/XDS3DScatterGL.tsx@@ -0,0 +1,245 @@+/**+ * @file XDS3DScatterGL.tsx+ * @output WebGL 3D scatter — canvas overlaid outside SVG for sharp DPR rendering+ * @position Child of XDS3DChart; reads camera from context (Tier 1)+ *+ * SYNC: The vertex shader replicates XDS3DChart's project() math exactly.+ * Verified by projection.test.ts.+ *+ * The canvas renders as an absolute-positioned sibling to the SVG (not inside+ * foreignObject) to avoid the browser's 1x compositing of foreignObject content+ * on Retina displays.+ */++import {useRef, useEffect, useMemo} from 'react';+import {createPortal} from 'react-dom';+import {use3D} from './ThreeDContext';++export interface XDS3DScatterGLProps {+ color: string;+ size?: number;+ opacity?: number;+}++function hexToGL(hex: string): [number, number, number] {+ const n = parseInt(hex.replace('#', ''), 16);+ return [(n >> 16) / 255, ((n >> 8) & 0xff) / 255, (n & 0xff) / 255];+}++// SYNC: Steps 1-5 match XDS3DChart.project() exactly.+const VERT = `+ attribute vec3 a_position;+ uniform vec2 u_resolution;+ uniform vec2 u_center;+ uniform float u_scale;+ uniform float u_cosAz;+ uniform float u_sinAz;+ uniform float u_cosEl;+ uniform float u_sinEl;+ uniform float u_size;+ varying float v_depth;+ void main() {+ vec3 p = a_position - 0.5;+ float x1 = p.x * u_cosAz + p.z * u_sinAz;+ float z1 = -p.x * u_sinAz + p.z * u_cosAz;+ float y1 = p.y * u_cosEl - z1 * u_sinEl;+ float z2 = p.y * u_sinEl + z1 * u_cosEl;+ float px = u_center.x + x1 * u_scale;+ float py = u_center.y - y1 * u_scale;+ vec2 clip = (vec2(px, py) / u_resolution) * 2.0 - 1.0;+ gl_Position = vec4(clip.x, -clip.y, z2, 1.0);+ v_depth = z2;+ float depthFactor = 0.75 + (z2 + 0.5) * 0.25;+ // Compensate for smoothstep edge erosion (visible at r=0.48, not 0.5)+ // so visible circle matches SVG radius exactly+ gl_PointSize = (u_size * depthFactor) / 0.96;+ }+`;++const FRAG = `+ precision mediump float;+ uniform vec3 u_color;+ uniform float u_opacity;+ varying float v_depth;+ void main() {+ vec2 coord = gl_PointCoord - vec2(0.5);+ float dist = length(coord);+ if (dist > 0.5) discard;+ float edge = 1.0 - smoothstep(0.48, 0.5, dist);+ float depthFactor = 0.75 + (v_depth + 0.5) * 0.25;+ float a = u_opacity * depthFactor * edge;+ // Premultiplied alpha — required for correct compositing over page+ gl_FragColor = vec4(u_color * a, a);+ }+`;++function compileShader(+ gl: WebGLRenderingContext,+ type: number,+ src: string,+): WebGLShader | null {+ const s = gl.createShader(type);+ if (!s) return null;+ gl.shaderSource(s, src);+ gl.compileShader(s);+ if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) {+ gl.deleteShader(s);+ return null;+ }+ return s;+}++function createProgram(gl: WebGLRenderingContext): WebGLProgram | null {+ const vs = compileShader(gl, gl.VERTEX_SHADER, VERT);+ const fs = compileShader(gl, gl.FRAGMENT_SHADER, FRAG);+ if (!vs || !fs) return null;+ const p = gl.createProgram();+ if (!p) return null;+ gl.attachShader(p, vs);+ gl.attachShader(p, fs);+ gl.linkProgram(p);+ if (!gl.getProgramParameter(p, gl.LINK_STATUS)) {+ gl.deleteProgram(p);+ return null;+ }+ return p;+}++export function XDS3DScatterGL({+ color,+ size = 4,+ opacity = 0.85,+}: XDS3DScatterGLProps) {+ const {+ data,+ xKey,+ yKey,+ zKey,+ xDomain,+ yDomain,+ zDomain,+ normalize,+ camera,+ width,+ height,+ } = use3D();+ const canvasRef = useRef<HTMLCanvasElement | null>(null);+ const containerRef = useRef<HTMLDivElement | null>(null);+ const glRef = useRef<WebGLRenderingContext | null>(null);+ const programRef = useRef<WebGLProgram | null>(null);+ const markerRef = useRef<SVGGElement>(null);++ // Normalized 3D positions+ const positions = useMemo(() => {+ const buf = new Float32Array(data.length * 3);+ for (let i = 0; i < data.length; i++) {+ buf[i * 3] = normalize(data[i][xKey] as number, xDomain);+ buf[i * 3 + 1] = normalize(data[i][yKey] as number, yDomain);+ buf[i * 3 + 2] = normalize(data[i][zKey] as number, zDomain);+ }+ return buf;+ }, [data, xKey, yKey, zKey, xDomain, yDomain, zDomain, normalize]);++ // Mount canvas as sibling to SVG+ useEffect(() => {+ const marker = markerRef.current;+ if (!marker) return;+ const svg = marker.ownerSVGElement;+ if (!svg) return;+ const parent = svg.parentElement;+ if (!parent) return;++ // Ensure parent is positioned for absolute child+ if (getComputedStyle(parent).position === 'static') {+ parent.style.position = 'relative';+ }++ // Create canvas if not exists+ if (!canvasRef.current) {+ const canvas = document.createElement('canvas');+ canvas.style.position = 'absolute';+ canvas.style.top = '0';+ canvas.style.left = '0';+ canvas.style.pointerEvents = 'none';+ canvasRef.current = canvas;+ }++ const canvas = canvasRef.current;+ parent.appendChild(canvas);+ containerRef.current = parent as HTMLDivElement;++ return () => {+ if (canvas.parentElement) canvas.parentElement.removeChild(canvas);+ };+ }, []);++ // Draw+ useEffect(() => {+ const canvas = canvasRef.current;+ if (!canvas || width <= 0 || height <= 0) return;++ const dpr = (window.devicePixelRatio || 2) * 2; // 2x supersampling + smoothstep for crisp circles // supersampling for crisp circles+ canvas.width = width * dpr;+ canvas.height = height * dpr;+ canvas.style.width = `${width}px`;+ canvas.style.height = `${height}px`;++ if (!glRef.current) {+ glRef.current = canvas.getContext('webgl', {+ alpha: true,+ premultipliedAlpha: true,+ antialias: true,+ });+ }+ const gl = glRef.current;+ if (!gl) return;++ if (!programRef.current) programRef.current = createProgram(gl);+ const program = programRef.current;+ if (!program) return;++ const buf = gl.createBuffer();+ gl.bindBuffer(gl.ARRAY_BUFFER, buf);+ gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW);++ gl.viewport(0, 0, canvas.width, canvas.height);+ gl.clearColor(0, 0, 0, 0);+ gl.clear(gl.COLOR_BUFFER_BIT);+ gl.enable(gl.BLEND);+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);+ gl.useProgram(program);++ const aPos = gl.getAttribLocation(program, 'a_position');+ gl.enableVertexAttribArray(aPos);+ gl.vertexAttribPointer(aPos, 3, gl.FLOAT, false, 0, 0);++ // All uniforms in logical pixels — viewport handles DPR+ const azRad = (camera.azimuth * Math.PI) / 180;+ const elRad = (camera.elevation * Math.PI) / 180;+ const scale = Math.min(width, height) * 0.35;+ const [r, g, b] = hexToGL(color);++ gl.uniform2f(gl.getUniformLocation(program, 'u_resolution'), width, height);+ gl.uniform2f(+ gl.getUniformLocation(program, 'u_center'),+ width / 2,+ height / 2,+ );+ gl.uniform1f(gl.getUniformLocation(program, 'u_scale'), scale);+ gl.uniform1f(gl.getUniformLocation(program, 'u_cosAz'), Math.cos(azRad));+ gl.uniform1f(gl.getUniformLocation(program, 'u_sinAz'), Math.sin(azRad));+ gl.uniform1f(gl.getUniformLocation(program, 'u_cosEl'), Math.cos(elRad));+ gl.uniform1f(gl.getUniformLocation(program, 'u_sinEl'), Math.sin(elRad));+ gl.uniform3f(gl.getUniformLocation(program, 'u_color'), r, g, b);+ gl.uniform1f(gl.getUniformLocation(program, 'u_size'), size * dpr);+ gl.uniform1f(gl.getUniformLocation(program, 'u_opacity'), opacity);++ gl.drawArrays(gl.POINTS, 0, data.length);+ gl.deleteBuffer(buf);+ }, [positions, camera, color, size, opacity, width, height, data.length]);++ if (width <= 0 || height <= 0) return null;++ // Render an invisible SVG marker — the canvas is mounted imperatively as a sibling+ return <g ref={markerRef} />;+}diff --git a/packages/lab/src/ThreeD/index.ts b/packages/lab/src/ThreeD/index.tsindex c39e485291..eb2b4bff7c 100644--- a/packages/lab/src/ThreeD/index.ts+++ b/packages/lab/src/ThreeD/index.ts@@ -1,5 +1,6 @@export {XDS3DChart, type XDS3DChartProps} from './XDS3DChart';export {XDS3DScatter, type XDS3DScatterProps} from './XDS3DScatter';+export {XDS3DScatterGL, type XDS3DScatterGLProps} from './XDS3DScatterGL';export {XDS3DBar, type XDS3DBarProps} from './XDS3DBar';export {XDS3DGrid, type XDS3DGridProps} from './XDS3DGrid';export {XDS3DAxis, type XDS3DAxisProps} from './XDS3DAxis';diff --git a/packages/lab/src/ThreeD/projection.test.ts b/packages/lab/src/ThreeD/projection.test.tsnew file mode 100644index 0000000000..3fbb676404--- /dev/null+++ b/packages/lab/src/ThreeD/projection.test.ts@@ -0,0 +1,130 @@+import {describe, it, expect} from 'vitest';++/**+ * Verifies that the XDS3DScatterGL shader projection produces identical+ * output to XDS3DChart's project() function. This is a Tier 1 guarantee —+ * SVG and WebGL marks must agree on pixel positions.+ *+ * The shader's rotation math is replicated here in JS. If someone changes+ * project() or the shader without updating the other, this test fails.+ */++// JS implementation of project() from XDS3DChart+function projectJS(+ nx: number,+ ny: number,+ nz: number,+ azDeg: number,+ elDeg: number,+ width: number,+ height: number,+): {px: number; py: number; depth: number} {+ const azRad = (azDeg * Math.PI) / 180;+ const elRad = (elDeg * Math.PI) / 180;+ const cosAz = Math.cos(azRad),+ sinAz = Math.sin(azRad);+ const cosEl = Math.cos(elRad),+ sinEl = Math.sin(elRad);+ const scale = Math.min(width, height) * 0.35;+ const cx = width / 2,+ cy = height / 2;++ const x = nx - 0.5,+ y = ny - 0.5,+ z = nz - 0.5;+ const x1 = x * cosAz + z * sinAz;+ const z1 = -x * sinAz + z * cosAz;+ const y1 = y * cosEl - z1 * sinEl;+ const z2 = y * sinEl + z1 * cosEl;++ return {px: cx + x1 * scale, py: cy - y1 * scale, depth: z2};+}++// JS implementation of the GLSL shader's projection (what the GPU does)+function projectShader(+ nx: number,+ ny: number,+ nz: number,+ azDeg: number,+ elDeg: number,+ width: number,+ height: number,+): {px: number; py: number; depth: number} {+ const azRad = (azDeg * Math.PI) / 180;+ const elRad = (elDeg * Math.PI) / 180;+ const cosAz = Math.cos(azRad),+ sinAz = Math.sin(azRad);+ const cosEl = Math.cos(elRad),+ sinEl = Math.sin(elRad);+ const scale = Math.min(width, height) * 0.35;+ const cx = width / 2,+ cy = height / 2;++ // Step 1: center+ const x = nx - 0.5,+ y = ny - 0.5,+ z = nz - 0.5;+ // Step 2: azimuth+ const x1 = x * cosAz + z * sinAz;+ const z1 = -x * sinAz + z * cosAz;+ // Step 3: elevation+ const y1 = y * cosEl - z1 * sinEl;+ const z2 = y * sinEl + z1 * cosEl;+ // Step 4: project to pixels+ const px = cx + x1 * scale;+ const py = cy - y1 * scale;++ return {px, py, depth: z2};+}++describe('3D projection parity (Tier 1)', () => {+ const testCases = [+ {nx: 0, ny: 0, nz: 0, label: 'origin'},+ {nx: 1, ny: 1, nz: 1, label: 'corner'},+ {nx: 0.5, ny: 0.5, nz: 0.5, label: 'center'},+ {nx: 0, ny: 1, nz: 0.5, label: 'top-front'},+ {nx: 1, ny: 0, nz: 0, label: 'right-bottom-front'},+ {nx: 0.3, ny: 0.7, nz: 0.9, label: 'arbitrary'},+ ];++ const cameras = [+ {az: 0, el: 0, label: 'front'},+ {az: 35, el: 25, label: 'default'},+ {az: 90, el: 0, label: 'side'},+ {az: 45, el: 45, label: 'diagonal'},+ {az: -30, el: 15, label: 'negative azimuth'},+ {az: 180, el: -20, label: 'behind'},+ ];++ const width = 600,+ height = 400;++ for (const cam of cameras) {+ for (const pt of testCases) {+ it(`${pt.label} at camera ${cam.label} (az=${cam.az}, el=${cam.el})`, () => {+ const js = projectJS(+ pt.nx,+ pt.ny,+ pt.nz,+ cam.az,+ cam.el,+ width,+ height,+ );+ const gl = projectShader(+ pt.nx,+ pt.ny,+ pt.nz,+ cam.az,+ cam.el,+ width,+ height,+ );++ expect(gl.px).toBeCloseTo(js.px, 6);+ expect(gl.py).toBeCloseTo(js.py, 6);+ expect(gl.depth).toBeCloseTo(js.depth, 6);+ });+ }+ }+});diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.tsindex 78603fbab8..dadcbad200 100644--- a/packages/lab/src/index.ts+++ b/packages/lab/src/index.ts@@ -129,7 +129,9 @@ export {XDS3DChart,type XDS3DChartProps,XDS3DScatter,+ XDS3DScatterGL,type XDS3DScatterProps,+ type XDS3DScatterGLProps,XDS3DBar,type XDS3DBarProps,XDS3DGrid,