From 8de1f27eb3111ad5cbf978abf8108fe0b9690f85 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 00:25:45 -0800 Subject: [PATCH 1/6] Pin regl-scatter2d to a fork commit with typed positions The next commits pass Float32Array data to regl-scatter2d without a copy. The pinned commit holds the changes that regl-scatter2d needs for that, and a built bundle.js. regl-scatter2d builds bundle.js at publish time, so a plain git commit holds no entry file. A regl-scatter2d release replaces this pin. --- package-lock.json | 6 +++--- package.json | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/package-lock.json b/package-lock.json index 41ff510cdf1..684d2505d3e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -44,7 +44,7 @@ "probe-image-size": "^7.5.0", "regl-error2d": "^2.0.12", "regl-line2d": "^3.1.4", - "regl-scatter2d": "^3.4.0", + "regl-scatter2d": "github:settylab/regl-scatter2d#e2db766d5f8032210289a86a3bbef883e9f6ef10", "regl-splom": "^1.0.14", "strongly-connected-components": "^1.0.1", "svg-path-sdf": "^2.0.0", @@ -6231,8 +6231,8 @@ }, "node_modules/regl-scatter2d": { "version": "3.4.0", - "resolved": "https://registry.npmjs.org/regl-scatter2d/-/regl-scatter2d-3.4.0.tgz", - "integrity": "sha512-DavKQlHsI+iHZuLgOL+yGkg+sPd94CS+7FCBWkcQ6s/TbaNfUsF9eN591fjjSWIoKrGNfb/SEGhsXR5lXjqZ2w==", + "resolved": "git+ssh://git@github.com/settylab/regl-scatter2d.git#e2db766d5f8032210289a86a3bbef883e9f6ef10", + "integrity": "sha512-UuCLyCo03l/d0TxnXvlg+iYwad/IrtCk5cin9oIZXEM1xilGQHXLFz2InrGNyUryafwo2bSnTKShNbX/fEQE1A==", "license": "MIT", "dependencies": { "@plotly/point-cluster": "^3.1.9", diff --git a/package.json b/package.json index 8db841d331a..a0169cef81d 100644 --- a/package.json +++ b/package.json @@ -118,7 +118,7 @@ "probe-image-size": "^7.5.0", "regl-error2d": "^2.0.12", "regl-line2d": "^3.1.4", - "regl-scatter2d": "^3.4.0", + "regl-scatter2d": "github:settylab/regl-scatter2d#e2db766d5f8032210289a86a3bbef883e9f6ef10", "regl-splom": "^1.0.14", "strongly-connected-components": "^1.0.1", "svg-path-sdf": "^2.0.0", From 0811d513137b541bd23f5ee4f81a65502a36ed66 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 00:25:46 -0800 Subject: [PATCH 2/6] Pass Float32Array x and y of scattergl traces to regl-scatter2d calc wrote x and y of each trace to a plain Array of doubles and built an Array of point ids. regl-scatter2d then copied the positions and uploaded 16 bytes for each point. Each restyle or moveTraces repeated the copies and the upload. For a markers-only trace on linear axes with Float32Array data, calc now passes {x, y, count, rev} to regl-scatter2d. regl-scatter2d uploads 8 bytes for each point one time. The same buffer range with the same layout.datarevision is the same data. calc reads the axis extremes from a cache and builds the point ids at the first read. If you refill a typed array in place, set a new layout.datarevision. --- src/traces/scattergl/calc.js | 148 ++++++++++-- test/jasmine/tests/scattergl_test.js | 329 ++++++++++++++++++++++++++- 2 files changed, 455 insertions(+), 22 deletions(-) diff --git a/src/traces/scattergl/calc.js b/src/traces/scattergl/calc.js index 240418b07af..f9de62a22ba 100644 --- a/src/traces/scattergl/calc.js +++ b/src/traces/scattergl/calc.js @@ -16,6 +16,7 @@ var convert = require('./convert'); var sceneUpdate = require('./scene_update'); var BADNUM = require('../../constants/numerical').BADNUM; +const FP_SAFE = require('../../constants/numerical').FP_SAFE; var TOO_MANY_POINTS = require('./constants').TOO_MANY_POINTS; module.exports = function calc(gd, trace) { @@ -50,25 +51,31 @@ module.exports = function calc(gd, trace) { trace._yEnds = yObj.ends; } - // we need hi-precision for scatter2d, - // regl-scatter2d uses NaNs for bad/missing values - var positions = new Array(len2); - var _ids = new Array(len); - for(i = 0; i < len; i++) { - positions[i * 2] = x[i] === BADNUM ? NaN : x[i]; - positions[i * 2 + 1] = y[i] === BADNUM ? NaN : y[i]; - // Pre-compute ids. - _ids[i] = i; - } + // regl-scatter2d uploads Float32Array x and y without a copy, so calc builds no positions for them + const xy = xyPositions(gd, trace, xa, ya, x, y, len); + let positions = xy; + let _ids; + if (!xy) { + // we need hi-precision for scatter2d, + // regl-scatter2d uses NaNs for bad/missing values + positions = new Array(len2); + _ids = new Array(len); + for(i = 0; i < len; i++) { + positions[i * 2] = x[i] === BADNUM ? NaN : x[i]; + positions[i * 2 + 1] = y[i] === BADNUM ? NaN : y[i]; + // Pre-compute ids. + _ids[i] = i; + } - if(xa.type === 'log') { - for(i = 0; i < len2; i += 2) { - positions[i] = xa.c2l(positions[i]); + if(xa.type === 'log') { + for(i = 0; i < len2; i += 2) { + positions[i] = xa.c2l(positions[i]); + } } - } - if(ya.type === 'log') { - for(i = 1; i < len2; i += 2) { - positions[i] = ya.c2l(positions[i]); + if(ya.type === 'log') { + for(i = 1; i < len2; i += 2) { + positions[i] = ya.c2l(positions[i]); + } } } @@ -76,7 +83,13 @@ module.exports = function calc(gd, trace) { // and it is also if(hasTooManyPoints && (xa.type !== 'log' && ya.type !== 'log')) { // FIXME: delegate this to webworker - stash.tree = cluster(positions); + stash.tree = cluster(xy ? interleaved(x, y, len) : positions); + } else if (xy) { + lazyProp(stash, 'ids', () => { + const ids = new Uint32Array(len); + for (let k = 0; k < len; k++) ids[k] = k; + return ids; + }); } else { stash.ids = _ids; } @@ -96,7 +109,12 @@ module.exports = function calc(gd, trace) { } else if(opts.marker) { ppad = opts.marker.sizeAvg || Math.max(opts.marker.size, 3); } - calcAxisExpansion(gd, trace, xa, ya, x, y, ppad); + // A restyle recalculates every trace, so the extremes of Float32Array data come from a cache + if (xy && !Array.isArray(ppad)) { + calcAxisExpansion(gd, trace, xa, ya, extremesOf(x, len, xy.rev), extremesOf(y, len, xy.rev), ppad); + } else { + calcAxisExpansion(gd, trace, xa, ya, x, y, ppad); + } if(opts.errorX) expandForErrorBars(trace, xa, opts.errorX); if(opts.errorY) expandForErrorBars(trace, ya, opts.errorY); @@ -125,12 +143,102 @@ module.exports = function calc(gd, trace) { stash.index = scene.count; stash.x = x; stash.y = y; - stash.positions = positions; + if (!xy) stash.positions = positions; scene.count++; return [{x: false, y: false, t: stash, trace: trace}]; }; +/** + * Get the positions of a trace that regl-scatter2d can upload without a copy. + * + * @param gd - the graph div + * @param trace - the full trace + * @param xa - the full x axis + * @param ya - the full y axis + * @param x - the calc x values + * @param y - the calc y values + * @param len - the number of points + * @returns `{x, y, count, rev}` for a markers-only trace on linear axes with Float32Array x and y, else null. + * `rev` is `layout.datarevision`. The same buffer range with the same `rev` is the same data. + */ +function xyPositions(gd, trace, xa, ya, x, y, len) { + if (!isFloat32Array(x) || !isFloat32Array(y)) return null; + if (xa.type !== 'linear' || ya.type !== 'linear') return null; + if (trace.xperiodalignment || trace.yperiodalignment) return null; + if (trace.mode !== 'markers') return null; + if (trace.fill && trace.fill !== 'none') return null; + if (trace.error_x?.visible || trace.error_y?.visible) return null; + if (x.length < len || y.length < len) return null; + return { x, y, count: len, rev: gd.layout?.datarevision }; +} + +const extremesCache = new WeakMap(); + +/** + * Get the finite extremes of a Float32Array. The function scans the array one time per buffer range and `rev`. + * + * @param v - the Float32Array + * @param len - the number of values to read + * @param rev - the revision of the data (`layout.datarevision`) + * @returns `[min, max]`, with the limits that `findExtremes` applies + */ +function extremesOf(v, len, rev) { + let byBuffer = extremesCache.get(v.buffer); + if (!byBuffer || byBuffer.rev !== rev) { + byBuffer = { rev, extremes: {} }; + extremesCache.set(v.buffer, byBuffer); + } + const key = `${v.byteOffset}:${len}`; + let extremes = byBuffer.extremes[key]; + if (extremes) return extremes; + let min = Infinity; + let max = -Infinity; + for (let i = 0; i < len; i++) { + const vi = v[i]; + if (vi < min && vi > -FP_SAFE) min = vi; + if (vi > max && vi < FP_SAFE) max = vi; + } + extremes = byBuffer.extremes[key] = [min, max]; + return extremes; +} + +// `instanceof` fails for an array from another window +function isFloat32Array(v) { + return Object.prototype.toString.call(v) === '[object Float32Array]'; +} + +function interleaved(x, y, len) { + const positions = new Float64Array(len * 2); + for (let i = 0; i < len; i++) { + positions[i * 2] = x[i]; + positions[i * 2 + 1] = y[i]; + } + return positions; +} + +/** + * Define a property that computes its value at the first read. + * + * @param stash - the object that gets the property + * @param key - the property name + * @param make - the function that returns the value + */ +function lazyProp(stash, key, make) { + let value; + Object.defineProperty(stash, key, { + configurable: true, + enumerable: true, + get: () => { + if (value === undefined) value = make(); + return value; + }, + set: (newValue) => { + value = newValue; + } + }); +} + function expandForErrorBars(trace, ax, opts) { var extremes = trace._extremes[ax._id]; var errExt = findExtremes(ax, opts._bnds, {padded: true}); diff --git a/test/jasmine/tests/scattergl_test.js b/test/jasmine/tests/scattergl_test.js index 1e8b904ed28..ea57ad0a281 100644 --- a/test/jasmine/tests/scattergl_test.js +++ b/test/jasmine/tests/scattergl_test.js @@ -567,8 +567,10 @@ describe('end-to-end scattergl tests', function() { [1, 0, 0, 1] ]); - expect(opts.positions) - .toBeCloseToArray([1, 1, 2, 2, 3, 1]); + // calc passes Float32Array x and y of a markers-only trace without a copy + expect(opts.positions.x).toBe(gd._fullData[0].x); + expect(opts.positions.y).toBe(gd._fullData[0].y); + expect(opts.positions.count).toBe(3); }) .then(done, done.fail); }); @@ -974,3 +976,326 @@ describe('Test texttemplate for scattergl', function() { ['%{x} is %{y}', ['*0* is $1000.00 !', '*1* is $1200.00 !']] ]); }); + +function f32(n, seed) { + let a = new Float32Array(n); + let s = seed; + for (let i = 0; i < n; i++) { + s = (s * 1664525 + 1013904223) >>> 0; + a[i] = s / 4294967296; + } + return a; +} + +describe('scattergl Float32Array positions', () => { + let gd; + + beforeEach(() => { gd = createGraphDiv(); }); + afterEach(() => { + Plotly.purge(gd); + destroyGraphDiv(); + }); + + function trace(x, y, extra) { + let t = {type: 'scattergl', mode: 'markers', x: x, y: y}; + for (let k in extra) t[k] = extra[k]; + return t; + } + function stash(i) { return gd.calcdata[i][0].t; } + function groups() { return gd._fullLayout._plots.xy._scene.scatter2d.groups; } + + function options(i) { return gd._fullLayout._plots.xy._scene.markerOptions[i]; } + // Record the byte length of each Float32Array that goes to the GPU + function countUploads() { + let uploads = []; + ['bufferData', 'bufferSubData'].forEach((name) => { + let orig = WebGLRenderingContext.prototype[name]; + spyOn(WebGLRenderingContext.prototype, name).and.callFake(function () { + let d = arguments[name === 'bufferData' ? 1 : 2]; + if (d instanceof Float32Array && d.byteLength) uploads.push(d.byteLength); + return orig.apply(this, arguments); + }); + }); + return uploads; + } + function pixels() { + let canvas = gd.querySelector('.gl-canvas-context'); + let gl = canvas.getContext('webgl'); + let px = new Uint8Array(canvas.width * canvas.height * 4); + gl.readPixels(0, 0, canvas.width, canvas.height, gl.RGBA, gl.UNSIGNED_BYTE, px); + return px; + } + + it('@gl gives Float32 x and y of a markers-only trace to regl-scatter2d as they are: no calc positions, lazy ids', (done) => { + let x = f32(1000, 1); + let y = f32(1000, 2); + Plotly.newPlot(gd, [trace(x, y)]) + .then(() => { + let t = stash(0); + expect(t.positions).toBeUndefined(); + expect(options(0).positions.x).toBe(x); + expect(options(0).positions.y).toBe(y); + expect(options(0).positions.count).toBe(1000); + expect(t.ids instanceof Uint32Array).toBe(true); + expect(t.ids[999]).toBe(999); + // The group reads x and y from GPU segments + expect(groups()[0].xy.x).toBe(x); + expect(groups()[0].xAttr.stride).toBe(4); + expect(groups()[0].count).toBe(1000); + }) + .then(done, done.fail); + }); + + it('@gl keeps plain positions for plain arrays, lines, and log axes', (done) => { + let x = f32(100, 3); + let y = f32(100, 4); + Plotly.newPlot(gd, [ + trace(Array.from(x), Array.from(y)), + trace(x, y, {mode: 'lines+markers'}), + trace(x, y, {xaxis: 'x2'}) + ], {xaxis2: {type: 'log', overlaying: 'x'}}) + .then(() => { + expect(Array.isArray(stash(0).positions)).toBe(true); + expect(Array.isArray(stash(1).positions)).toBe(true); + expect(Array.isArray(stash(2).positions)).toBe(true); + }) + .then(done, done.fail); + }); + + it('@gl uploads chunks of one buffer once per axis, and nothing on a reorder, a restyle or new views of the same data', (done) => { + let X = f32(1500, 5); + let Y = f32(1500, 6); + function chunks() { + return [0, 500, 1000].map((a) => { return trace(X.subarray(a, a + 500), Y.subarray(a, a + 500)); }); + } + let uploads = countUploads(); + Plotly.newPlot(gd, chunks()) + .then(() => { + // 1,500 points of 4 bytes, for x and for y + expect(uploads).toEqual([6000, 6000]); + uploads.length = 0; + return Plotly.moveTraces(gd, [0], [2]); + }) + .then(() => { + return Plotly.restyle(gd, {'marker.color': 'red'}, [1]); + }) + .then(() => { + return Plotly.restyle(gd, {visible: 'legendonly'}, [0]); + }) + .then(() => { + return Plotly.restyle(gd, {visible: true}, [0]); + }) + .then(() => { + // New views of the same bytes are the same data + return Plotly.react(gd, chunks(), gd.layout); + }) + .then(() => { + return Plotly.relayout(gd, {'xaxis.range': [0, 0.5]}); + }) + .then(() => { + expect(uploads).toEqual([]); + // New data uploads only its own bytes + return Plotly.restyle(gd, {x: [f32(500, 9)]}, [1]); + }) + .then(() => { + expect(uploads).toEqual([2000]); + }) + .then(done, done.fail); + }); + + it('@gl a new datarevision uploads the same arrays again', (done) => { + let x = f32(100, 10); + let y = f32(100, 11); + let uploads = countUploads(); + Plotly.newPlot(gd, [trace(x, y)], {datarevision: 1}) + .then(() => { + uploads.length = 0; + x[0] = 0.5; + // Without a new datarevision, the same bytes are the same data + return Plotly.react(gd, [trace(x.subarray(0), y)], {datarevision: 1}); + }) + .then(() => { + expect(uploads).toEqual([]); + return Plotly.react(gd, [trace(x, y)], {datarevision: 2}); + }) + .then(() => { + expect(uploads).toEqual([400, 400]); + expect(groups()[0].xy.rev).toBe(2); + }) + .then(done, done.fail); + }); + + it('@gl draws a trace across segments in pieces with the same pixels, selection included', (done) => { + let createScatter = require('regl-scatter2d'); + let segment = createScatter.xySegment; + let x = f32(3000, 12); + let y = f32(3000, 13); + let sel = []; + for (let i = 0; i < 3000; i += 7) sel.push(i); + let layout = {width: 400, height: 300, xaxis: {range: [0, 1]}, yaxis: {range: [0, 1]}}; + let whole, wholeSel; + Plotly.newPlot(gd, [trace(x, y)], layout) + .then(() => { + expect(groups()[0].pieces).toBe(null); + whole = pixels(); + return Plotly.restyle(gd, {selectedpoints: [sel]}); + }) + .then(() => { + wholeSel = pixels(); + Plotly.purge(gd); + // A segment holds 1,024 points + createScatter.xySegment = 4096; + return Plotly.newPlot(gd, [trace(x, y)], layout); + }) + .then(() => { + expect(groups()[0].pieces.length).toBe(3); + expect(pixels()).toEqual(whole); + return Plotly.restyle(gd, {selectedpoints: [sel]}); + }) + .then(() => { + expect(pixels()).toEqual(wholeSel); + }) + .then(() => { createScatter.xySegment = segment; }, (e) => { createScatter.xySegment = segment; throw e; }) + .then(done, done.fail); + }); + + it('@gl autoranges as plain arrays do, and scans an array for its extremes once', (done) => { + let x = f32(2000, 14); + let y = f32(2000, 15); + x[3] = NaN; + let range; + Plotly.newPlot(gd, [trace(Array.from(x), Array.from(y))]) + .then(() => { + range = [gd._fullLayout.xaxis.range.slice(), gd._fullLayout.yaxis.range.slice()]; + return Plotly.react(gd, [trace(x, y)]); + }) + .then(() => { + expect([gd._fullLayout.xaxis.range, gd._fullLayout.yaxis.range]).toEqual(range); + // A new datarevision makes calc read the changed value + x[0] = 5; + return Plotly.restyle(gd, {'marker.color': 'red'}); + }) + .then(() => { + expect(gd._fullLayout.xaxis.range).toEqual(range[0]); + return Plotly.react(gd, [trace(x, y)], {datarevision: 1}); + }) + .then(() => { + expect(gd._fullLayout.xaxis.range[1]).toBeGreaterThan(5); + }) + .then(done, done.fail); + }); + + it('@gl keeps the fract32 half for doubles a float32 cannot hold', (done) => { + Plotly.newPlot(gd, [trace([1000.0000001, 1000.0000002], [1, 2])]) + .then(() => { + expect(groups()[0].fractZero).toBe(false); + return Plotly.restyle(gd, {x: [[1, 2]]}); + }) + .then(() => { + expect(groups()[0].fractZero).toBe(true); + }) + .then(done, done.fail); + }); +}); + +describe('regl-scatter2d positions as regl buffers (splom)', () => { + let gd; + + beforeEach(() => { gd = createGraphDiv(); }); + afterEach(() => { + Plotly.purge(gd); + destroyGraphDiv(); + }); + + it('@gl still draws a splom, whose positions are {x, y} with a regl buffer, offset and count', (done) => { + Plotly.newPlot(gd, [{ + type: 'splom', + dimensions: [{values: Array.from(f32(300, 31))}, {values: Array.from(f32(300, 32))}, {values: Array.from(f32(300, 33))}], + marker: {color: 'rgb(255, 0, 0)', size: 6} + }], {width: 400, height: 400}) + .then(() => { + let canvas = gd.querySelector('.gl-canvas-context'); + let gl = canvas.getContext('webgl'); + let px = new Uint8Array(canvas.width * canvas.height * 4); + gl.readPixels(0, 0, canvas.width, canvas.height, gl.RGBA, gl.UNSIGNED_BYTE, px); + let red = 0; + for (let i = 0; i < px.length; i += 4) if (px[i] > 200 && px[i + 1] < 60 && px[i + 3] > 200) red++; + expect(red).toBeGreaterThan(1000); + }) + .then(done, done.fail); + }); +}); + +describe('regl-scatter2d {x, y} positions', () => { + let createScatter = require('regl-scatter2d'); + let gd, regl, sc, uploads, segment; + + beforeEach((done) => { + gd = createGraphDiv(); + segment = createScatter.xySegment; + uploads = []; + Plotly.newPlot(gd, [{type: 'scattergl', mode: 'markers', x: [0, 1], y: [0, 1]}]).then(() => { + regl = gd._fullLayout._glcanvas.data()[0].regl; + sc = createScatter(regl); + ['bufferData', 'bufferSubData'].forEach((name) => { + let orig = WebGLRenderingContext.prototype[name]; + spyOn(WebGLRenderingContext.prototype, name).and.callFake(function () { + let d = arguments[name === 'bufferData' ? 1 : 2]; + if (d instanceof Float32Array && d.byteLength) uploads.push(d.byteLength); + return orig.apply(this, arguments); + }); + }); + }).then(done, done.fail); + }); + afterEach(() => { + createScatter.xySegment = segment; + sc.destroy(); + Plotly.purge(gd); + destroyGraphDiv(); + }); + + function opts(x, y, a, b, rev) { + return {positions: {x: x.subarray(a, b), y: y.subarray(a, b), count: b - a, rev: rev}, size: 5, color: 'red'}; + } + function sum() { return uploads.reduce((a, b) => { return a + b; }, 0); } + + it('@gl uploads the views of one buffer once per axis, and the same bytes never again', () => { + let X = f32(1500, 21); + let Y = f32(1500, 22); + sc.update([opts(X, Y, 0, 500), opts(X, Y, 500, 1000)]); + expect(uploads).toEqual([4000, 4000]); + + // New views of the same bytes, then the two groups in the other order + uploads = []; + sc.update([opts(X, Y, 0, 500), opts(X, Y, 500, 1000)]); + sc.update([opts(X, Y, 500, 1000), opts(X, Y, 0, 500)]); + sc.update([{color: 'blue'}, {size: 3}]); + expect(uploads).toEqual([]); + + // A view of new bytes uploads the segment again + sc.update([opts(X, Y, 500, 1000), opts(X, Y, 1000, 1500)]); + expect(uploads).toEqual([6000, 6000]); + + // A new revision uploads the same arrays + uploads = []; + sc.update([opts(X, Y, 500, 1000, 2), opts(X, Y, 1000, 1500, 2)]); + expect(sum()).toBe(8000); + }); + + it('@gl uploads by segment, never more than the segment size at once', () => { + createScatter.xySegment = 1024; + let X = f32(1000, 23); + let Y = f32(1000, 24); + sc.update([opts(X, Y, 0, 1000)]); + // Each axis holds 4,000 bytes in segments of 1,024 + expect(uploads.length).toBe(8); + expect(Math.max.apply(null, uploads)).toBe(1024); + expect(sum()).toBe(8000); + + // A view inside the uploaded bytes uploads nothing, and the unused segments go away + uploads = []; + sc.update([opts(X, Y, 100, 300)]); + sc.update([opts(X, Y, 0, 1000)]); + expect(sum()).toBe(2 * (1024 + 928)); + }); +}); From b34d913c4389b28d34e0315f77cbf2755c551063 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 00:25:46 -0800 Subject: [PATCH 3/6] Build the hover tree of a large scattergl trace at the first read calc built a point-cluster tree for each trace of 100,000 points or more, at every calc. Only hoverPoints reads the tree. If layout.hovermode is false, or the trace has hoverinfo 'skip', the first read now builds the tree. With hover, calc builds the tree as before. --- src/traces/scattergl/calc.js | 8 +++++- test/jasmine/tests/scattergl_test.js | 40 ++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/src/traces/scattergl/calc.js b/src/traces/scattergl/calc.js index f9de62a22ba..922f379a0f1 100644 --- a/src/traces/scattergl/calc.js +++ b/src/traces/scattergl/calc.js @@ -83,7 +83,13 @@ module.exports = function calc(gd, trace) { // and it is also if(hasTooManyPoints && (xa.type !== 'log' && ya.type !== 'log')) { // FIXME: delegate this to webworker - stash.tree = cluster(xy ? interleaved(x, y, len) : positions); + // Only hover reads the tree. Without hover, the first read builds the tree. + const makeTree = () => cluster(xy ? interleaved(x, y, len) : positions); + if (fullLayout.hovermode === false || trace.hoverinfo === 'skip') { + lazyProp(stash, 'tree', makeTree); + } else { + stash.tree = makeTree(); + } } else if (xy) { lazyProp(stash, 'ids', () => { const ids = new Uint32Array(len); diff --git a/test/jasmine/tests/scattergl_test.js b/test/jasmine/tests/scattergl_test.js index ea57ad0a281..d10a94c22bf 100644 --- a/test/jasmine/tests/scattergl_test.js +++ b/test/jasmine/tests/scattergl_test.js @@ -1185,6 +1185,46 @@ describe('scattergl Float32Array positions', () => { .then(done, done.fail); }); + it('@gl builds the hover tree of a big trace in calc only when there is hover, else on first read', (done) => { + let n = 150000; + let x = f32(n, 16); + let y = f32(n, 17); + function lazy(i) { return typeof Object.getOwnPropertyDescriptor(stash(i), 'tree').get === 'function'; } + function hoverAt() { + Plotly.Fx.hover(gd, {xval: x[777], yval: y[777]}); + return gd._hoverdata && gd._hoverdata[0].pointNumber; + } + let found; + Plotly.newPlot(gd, [trace(x, y), trace(Array.from(x.subarray(0, 100000)), Array.from(y.subarray(0, 100000)))], {hovermode: 'closest'}) + .then(() => { + // With hover, calc builds the tree + expect(lazy(0)).toBe(false); + expect(lazy(1)).toBe(false); + expect(typeof stash(0).tree.range).toBe('function'); + found = hoverAt(); + expect(found).toBe(777); + return Plotly.react(gd, [trace(x, y, {hoverinfo: 'skip'}), trace(x, y)], {hovermode: 'closest'}); + }) + .then(() => { + expect(lazy(0)).toBe(true); + expect(lazy(1)).toBe(false); + Plotly.purge(gd); + return Plotly.newPlot(gd, [trace(x, y), trace(Array.from(x.subarray(0, 100000)), Array.from(y.subarray(0, 100000)))], {hovermode: false}); + }) + .then(() => { + expect(lazy(0)).toBe(true); + expect(lazy(1)).toBe(true); + // A relayout does not recalculate, so the first hover builds the tree + return Plotly.relayout(gd, {hovermode: 'closest'}); + }) + .then(() => { + expect(lazy(0)).toBe(true); + expect(hoverAt()).toBe(found); + expect(typeof stash(0).tree.range).toBe('function'); + }) + .then(done, done.fail); + }); + it('@gl keeps the fract32 half for doubles a float32 cannot hold', (done) => { Plotly.newPlot(gd, [trace([1000.0000001, 1000.0000002], [1, 2])]) .then(() => { From a019f2282179e9d975384a24e7310b65ed5bd075 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 00:25:46 -0800 Subject: [PATCH 4/6] Add the draftlog for the scattergl Float32Array changes --- draftlogs/XXXX_change.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 draftlogs/XXXX_change.md diff --git a/draftlogs/XXXX_change.md b/draftlogs/XXXX_change.md new file mode 100644 index 00000000000..239500711b8 --- /dev/null +++ b/draftlogs/XXXX_change.md @@ -0,0 +1 @@ +- Upload `Float32Array` `x` and `y` of markers-only `scattergl` traces without a copy, and build the hover index of large traces only when the graph has hover [[#XXXX](https://github.com/plotly/plotly.js/pull/XXXX)] From 244133200f301e77326846a29176e97b633e06a4 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 4 Dec 2026 12:17:44 -0800 Subject: [PATCH 5/6] Move the regl-scatter2d pin to a commit without build scripts npm prepares a git dependency that has a build script. It installs the devDependencies of regl-scatter2d, which include the native gl package, and a plain npm ci fails where gl has no binary. The new pinned commit holds the same bundle.js and no build script, so npm ci needs no build. --- package-lock.json | 6 +++--- package.json | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/package-lock.json b/package-lock.json index 684d2505d3e..26db59660a9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -44,7 +44,7 @@ "probe-image-size": "^7.5.0", "regl-error2d": "^2.0.12", "regl-line2d": "^3.1.4", - "regl-scatter2d": "github:settylab/regl-scatter2d#e2db766d5f8032210289a86a3bbef883e9f6ef10", + "regl-scatter2d": "github:settylab/regl-scatter2d#dd2fb74d0c2f964025a3054953723f2e533cbdd3", "regl-splom": "^1.0.14", "strongly-connected-components": "^1.0.1", "svg-path-sdf": "^2.0.0", @@ -6231,8 +6231,8 @@ }, "node_modules/regl-scatter2d": { "version": "3.4.0", - "resolved": "git+ssh://git@github.com/settylab/regl-scatter2d.git#e2db766d5f8032210289a86a3bbef883e9f6ef10", - "integrity": "sha512-UuCLyCo03l/d0TxnXvlg+iYwad/IrtCk5cin9oIZXEM1xilGQHXLFz2InrGNyUryafwo2bSnTKShNbX/fEQE1A==", + "resolved": "git+ssh://git@github.com/settylab/regl-scatter2d.git#dd2fb74d0c2f964025a3054953723f2e533cbdd3", + "integrity": "sha512-2sQKxt3aSJiPCPbsSNKn32ExgLNp8VMOpiguaysC7A+4NwNh7rvm+YRS5ZmTzo8jJF63F+avkFAuyLl/v01Elw==", "license": "MIT", "dependencies": { "@plotly/point-cluster": "^3.1.9", diff --git a/package.json b/package.json index a0169cef81d..3c3f130e823 100644 --- a/package.json +++ b/package.json @@ -118,7 +118,7 @@ "probe-image-size": "^7.5.0", "regl-error2d": "^2.0.12", "regl-line2d": "^3.1.4", - "regl-scatter2d": "github:settylab/regl-scatter2d#e2db766d5f8032210289a86a3bbef883e9f6ef10", + "regl-scatter2d": "github:settylab/regl-scatter2d#dd2fb74d0c2f964025a3054953723f2e533cbdd3", "regl-splom": "^1.0.14", "strongly-connected-components": "^1.0.1", "svg-path-sdf": "^2.0.0", From dae4331851fb444920ba41c00057a1531b5982e1 Mon Sep 17 00:00:00 2001 From: Dominik Date: Sat, 5 Dec 2026 01:03:19 -0800 Subject: [PATCH 6/6] Count the uploads on the context that regl uses With virtual-webgl, regl gets a virtual context. That context calls functions that virtual-webgl copied from WebGLRenderingContext.prototype at load, so a later spy on that prototype records nothing, and four upload specs failed in the virtual-webgl job. The specs now spy on the prototype of the context itself. Without virtual-webgl, that prototype is WebGLRenderingContext.prototype as before. --- test/jasmine/tests/scattergl_test.js | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/test/jasmine/tests/scattergl_test.js b/test/jasmine/tests/scattergl_test.js index d10a94c22bf..d1e1b415610 100644 --- a/test/jasmine/tests/scattergl_test.js +++ b/test/jasmine/tests/scattergl_test.js @@ -1005,12 +1005,19 @@ describe('scattergl Float32Array positions', () => { function groups() { return gd._fullLayout._plots.xy._scene.scatter2d.groups; } function options(i) { return gd._fullLayout._plots.xy._scene.markerOptions[i]; } + // The prototype of the contexts that regl gets. With virtual-webgl, it is not WebGLRenderingContext.prototype. + let glProto; + function contextPrototype() { + if (!glProto) glProto = Object.getPrototypeOf(document.createElement('canvas').getContext('webgl')); + return glProto; + } // Record the byte length of each Float32Array that goes to the GPU function countUploads() { let uploads = []; + let proto = contextPrototype(); ['bufferData', 'bufferSubData'].forEach((name) => { - let orig = WebGLRenderingContext.prototype[name]; - spyOn(WebGLRenderingContext.prototype, name).and.callFake(function () { + let orig = proto[name]; + spyOn(proto, name).and.callFake(function () { let d = arguments[name === 'bufferData' ? 1 : 2]; if (d instanceof Float32Array && d.byteLength) uploads.push(d.byteLength); return orig.apply(this, arguments); @@ -1277,9 +1284,11 @@ describe('regl-scatter2d {x, y} positions', () => { Plotly.newPlot(gd, [{type: 'scattergl', mode: 'markers', x: [0, 1], y: [0, 1]}]).then(() => { regl = gd._fullLayout._glcanvas.data()[0].regl; sc = createScatter(regl); + // With virtual-webgl, the context of regl does not use WebGLRenderingContext.prototype + let proto = Object.getPrototypeOf(regl._gl); ['bufferData', 'bufferSubData'].forEach((name) => { - let orig = WebGLRenderingContext.prototype[name]; - spyOn(WebGLRenderingContext.prototype, name).and.callFake(function () { + let orig = proto[name]; + spyOn(proto, name).and.callFake(function () { let d = arguments[name === 'bufferData' ? 1 : 2]; if (d instanceof Float32Array && d.byteLength) uploads.push(d.byteLength); return orig.apply(this, arguments);