diff --git a/draftlogs/XXXX-alwaysontop_add.md b/draftlogs/XXXX-alwaysontop_add.md new file mode 100644 index 00000000000..5aee154ea17 --- /dev/null +++ b/draftlogs/XXXX-alwaysontop_add.md @@ -0,0 +1 @@ +- Add `alwaysontop` to `scatter3d` traces to draw their markers last, over everything else [[#XXXX](https://github.com/plotly/plotly.js/pull/XXXX)] diff --git a/draftlogs/XXXX-datascale_add.md b/draftlogs/XXXX-datascale_add.md new file mode 100644 index 00000000000..29380df1f73 --- /dev/null +++ b/draftlogs/XXXX-datascale_add.md @@ -0,0 +1 @@ +- Add `scene.datascale` to let traces hidden in the legend keep the scale of a 3D scene, so that the positions of the other traces stay on the GPU [[#XXXX](https://github.com/plotly/plotly.js/pull/XXXX)] diff --git a/draftlogs/XXXX-focus-context_change.md b/draftlogs/XXXX-focus-context_change.md new file mode 100644 index 00000000000..8e469f2cf8f --- /dev/null +++ b/draftlogs/XXXX-focus-context_change.md @@ -0,0 +1 @@ +- Create the WebGL context of the `scattergl` and `splom` focus layer only when a selection starts (a selection drag mode or selected points) [[#XXXX](https://github.com/plotly/plotly.js/pull/XXXX)] diff --git a/draftlogs/XXXX-glyph-outline_fix.md b/draftlogs/XXXX-glyph-outline_fix.md new file mode 100644 index 00000000000..2dad55d224c --- /dev/null +++ b/draftlogs/XXXX-glyph-outline_fix.md @@ -0,0 +1 @@ +- Fix `scatter3d` allocating glyph outline vertices for markers without an outline, which cuts the vertex count of a circle marker from 104 to 60 [[#XXXX](https://github.com/plotly/plotly.js/pull/XXXX)] diff --git a/draftlogs/XXXX-lod_add.md b/draftlogs/XXXX-lod_add.md new file mode 100644 index 00000000000..3f237ec4876 --- /dev/null +++ b/draftlogs/XXXX-lod_add.md @@ -0,0 +1 @@ +- Add `layout.lod` and `layout.scene.lod` to draw a preview of every k-th point first in `scattergl` plots and while the camera moves in `scatter3d` plots of many points, with the full picture drawn when the plot is at rest, the `plotly_lod` event, and `scene.hidden` / `scene.setHidden` to hide `scattergl` traces without a recalculation [[#XXXX](https://github.com/plotly/plotly.js/pull/XXXX)] diff --git a/draftlogs/XXXX-markerrender_add.md b/draftlogs/XXXX-markerrender_add.md new file mode 100644 index 00000000000..a4056f1fa90 --- /dev/null +++ b/draftlogs/XXXX-markerrender_add.md @@ -0,0 +1 @@ +- Add `scene.markerrender` to draw `scatter3d` circle markers as one-vertex discs instead of glyph meshes, which cuts the memory of a marker from 4,160 bytes to 36 bytes [[#XXXX](https://github.com/plotly/plotly.js/pull/XXXX)] diff --git a/draftlogs/XXXX-oit_add.md b/draftlogs/XXXX-oit_add.md new file mode 100644 index 00000000000..943d469f43e --- /dev/null +++ b/draftlogs/XXXX-oit_add.md @@ -0,0 +1 @@ +- Add `scene.oit` to blend translucent `scatter3d` markers by depth in place of draw order [[#XXXX](https://github.com/plotly/plotly.js/pull/XXXX)] diff --git a/draftlogs/XXXX-pick_change.md b/draftlogs/XXXX-pick_change.md new file mode 100644 index 00000000000..675efb90412 --- /dev/null +++ b/draftlogs/XXXX-pick_change.md @@ -0,0 +1 @@ +- Draw the gl3d pick pass when a pointer event needs it instead of in every frame that moves the camera, skip it when no trace of the scene can be picked, draw no frame for a hover that changes nothing in the picture, and make `scene.hovermode: false` pick only on a button press without emitting hover events [[#XXXX](https://github.com/plotly/plotly.js/pull/XXXX)] diff --git a/draftlogs/XXXX-pick_fix.md b/draftlogs/XXXX-pick_fix.md new file mode 100644 index 00000000000..24e45e3c675 --- /dev/null +++ b/draftlogs/XXXX-pick_fix.md @@ -0,0 +1 @@ +- Fix hover and click on `scatter3d` traces with more than 16,777,215 points naming other points: such a trace is drawn but not picked, with a console warning [[#XXXX](https://github.com/plotly/plotly.js/pull/XXXX)] diff --git a/draftlogs/XXXX-scaleanchor_change.md b/draftlogs/XXXX-scaleanchor_change.md new file mode 100644 index 00000000000..83d0f64addf --- /dev/null +++ b/draftlogs/XXXX-scaleanchor_change.md @@ -0,0 +1 @@ +- Skip the recalculation after a range change of axes with `scaleanchor`, if every trace is a regl trace and the ranges of the constrained axes are fixed [[#XXXX](https://github.com/plotly/plotly.js/pull/XXXX)] diff --git a/draftlogs/XXXX-scattergl-typed_change.md b/draftlogs/XXXX-scattergl-typed_change.md new file mode 100644 index 00000000000..239500711b8 --- /dev/null +++ b/draftlogs/XXXX-scattergl-typed_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)] diff --git a/draftlogs/XXXX-typed3d_change.md b/draftlogs/XXXX-typed3d_change.md new file mode 100644 index 00000000000..d2e25d00eb3 --- /dev/null +++ b/draftlogs/XXXX-typed3d_change.md @@ -0,0 +1 @@ +- Convert typed `x`, `y`, and `z` of a `scatter3d` trace with markers only to one `Float32Array`, scan the data one time for the bounds, and keep the positions on the GPU when a later plot call gives the same data [[#XXXX](https://github.com/plotly/plotly.js/pull/XXXX)] diff --git a/package-lock.json b/package-lock.json index 41ff510cdf1..86fb3986b5e 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#37e65835d22ff96b1b4e759cf857549143f18ad8", "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#37e65835d22ff96b1b4e759cf857549143f18ad8", + "integrity": "sha512-FUoOWDV5xmYe4OaEje1K6LvDJLq5ZHgwh6cUicxa84p13tDvD/IGe7lFPJtj6PEC1FnecUX2yGjY9LycD71R3A==", "license": "MIT", "dependencies": { "@plotly/point-cluster": "^3.1.9", diff --git a/package.json b/package.json index 8db841d331a..cd1a33344e1 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#37e65835d22ff96b1b4e759cf857549143f18ad8", "regl-splom": "^1.0.14", "strongly-connected-components": "^1.0.1", "svg-path-sdf": "^2.0.0", diff --git a/src/lib/clear_gl_canvases.js b/src/lib/clear_gl_canvases.js index 234ed82a9f7..5298db9f73e 100644 --- a/src/lib/clear_gl_canvases.js +++ b/src/lib/clear_gl_canvases.js @@ -11,6 +11,12 @@ module.exports = function clearGlCanvases(gd) { var fullLayout = gd._fullLayout; if(fullLayout._glcanvas && fullLayout._glcanvas.size()) { + // A scattergl scene with a level of detail can keep a copy of the full picture on screen. + for(const id in fullLayout._plots) { + const scene = fullLayout._plots[id]._scene; + if(scene?.lod?.beforeClear) scene.lod.beforeClear(); + } + fullLayout._glcanvas.each(function(d) { if(d.regl) d.regl.clear({color: true, depth: true}); }); diff --git a/src/lib/prepare_regl.js b/src/lib/prepare_regl.js index d81c7f83a3a..c66c9add1bc 100644 --- a/src/lib/prepare_regl.js +++ b/src/lib/prepare_regl.js @@ -15,10 +15,13 @@ var createRegl = require('@plotly/regl'); * * @param {DOM node or object} gd : graph div object * @param {array} extensions : list of extension to pass to createRegl + * @param {object} reglPrecompiled : precompiled regl code for strict bundles + * @param {boolean} needsFocusLayer : if true, also create the regl instance of the focus layer. + * A graph with parcoords always gets that instance. * * @return {boolean} true if all createRegl calls succeeded, false otherwise */ -module.exports = function prepareRegl(gd, extensions, reglPrecompiled) { +module.exports = function prepareRegl(gd, extensions, reglPrecompiled, needsFocusLayer) { var fullLayout = gd._fullLayout; var success = true; @@ -29,6 +32,8 @@ module.exports = function prepareRegl(gd, extensions, reglPrecompiled) { } // only parcoords needs pick layer if(d.pick && !fullLayout._has('parcoords')) return; + // Browsers limit the WebGL contexts of a page, so the focus layer gets a context only on request + if (d.key === 'focusLayer' && !needsFocusLayer && !fullLayout._has('parcoords')) return; try { d.regl = createRegl({ diff --git a/src/plot_api/plot_api.js b/src/plot_api/plot_api.js index 5eea5fc4806..ddaa2eab7aa 100644 --- a/src/plot_api/plot_api.js +++ b/src/plot_api/plot_api.js @@ -2205,7 +2205,8 @@ function _relayout(gd, aobj) { // specifying arbitrary ranges for all axes in the group. // this way some ranges may expand beyond what's specified, // as they do at first draw, to satisfy the constraints. - flags.calc = true; + // The replot applies the constraints from the axes. A recalc uploads every regl trace again. + flags[constraintsNeedCalc(gd, group) ? 'calc' : 'plot'] = true; for (var groupAxId in group) { if (!rangesAltered[groupAxId]) { Axes.getFromId(gd, groupAxId)._constraintShrinkable = true; @@ -2245,6 +2246,35 @@ function _relayout(gd, aobj) { }; } +/** + * Decide if a relayout that alters the ranges of a constraint group needs a recalc. + * + * @param gd - the graph div + * @param group - the constraint group, keyed by axis id + * @returns false if every trace is a regl trace and every axis of the group has a fixed range, else true + */ +function constraintsNeedCalc(gd, group) { + const fullData = gd._fullData || []; + for (let i = 0; i < fullData.length; i++) { + if (!Registry.traceIs(fullData[i], 'regl')) return true; + } + for (const axId in group) { + const axIn = Axes.getFromId(gd, axId)?._input; + if (!axIn) return true; + const range = axIn.range; + const fixed = + axIn.autorange === false || + (axIn.autorange === undefined && + Array.isArray(range) && + range.length === 2 && + range[0] !== null && + range[1] !== null); + // An autorange needs the extremes of a new calc + if (!fixed) return true; + } + return false; +} + /* * updateAutosize: we made a change, does it change the autosize result? * puts the new size into fullLayout diff --git a/src/plots/gl3d/layout/defaults.js b/src/plots/gl3d/layout/defaults.js index 311ad2fe919..7ea6f2bcd2b 100644 --- a/src/plots/gl3d/layout/defaults.js +++ b/src/plots/gl3d/layout/defaults.js @@ -51,6 +51,13 @@ function handleGl3dDefaults(sceneLayoutIn, sceneLayoutOut, coerce, opts) { */ var bgcolor = coerce('bgcolor'); + coerce('oit'); + // A scene without `lod` gets no `lod` container. + if(Lib.isPlainObject(sceneLayoutIn.lod) && coerce('lod.minpoints')) { + coerce('lod.budget'); + coerce('lod.maxstride'); + coerce('lod.settle'); + } var bgColorCombined = Color.combine(bgcolor, opts.paper_bgcolor); var cameraKeys = ['up', 'center', 'eye']; @@ -62,6 +69,8 @@ function handleGl3dDefaults(sceneLayoutIn, sceneLayoutOut, coerce, opts) { } coerce('camera.projection.type'); + coerce('markerrender'); + coerce('datascale'); /* * coerce to positive number (min 0) but also do not accept 0 (>0 not >=0) diff --git a/src/plots/gl3d/layout/layout_attributes.js b/src/plots/gl3d/layout/layout_attributes.js index 3666d33e741..50d857dbe35 100644 --- a/src/plots/gl3d/layout/layout_attributes.js +++ b/src/plots/gl3d/layout/layout_attributes.js @@ -133,6 +133,34 @@ module.exports = { yaxis: gl3dAxisAttrs, zaxis: gl3dAxisAttrs, + markerrender: { + valType: 'enumerated', + values: ['glyph', 'disc', 'auto'], + dflt: 'glyph', + editType: 'plot', + description: [ + 'Sets how circle markers of *scatter3d* traces are drawn.', + 'The symbols *circle* and *circle-open* have two forms.', + '*glyph* draws each marker as a mesh of 60 to 104 vertices. This is the default.', + '*disc* draws each marker as one round point sprite. It needs far less memory and draws faster.', + 'The edge of a disc differs from the edge of a glyph by about one pixel.', + 'A marker with another symbol, a projection on the axes, or a size above the point size limit of the GPU is drawn as a glyph.', + '*auto* is currently the same as *disc*.' + ].join(' ') + }, + datascale: { + valType: 'enumerated', + values: ['visible', 'all'], + dflt: 'visible', + editType: 'plot', + description: [ + 'Determines which traces set the scale that the data of this scene is drawn at.', + 'With *visible*, hiding or showing a trace that changes the extent of the data', + 'changes the scale, and the positions of every trace are converted and uploaded again.', + 'With *all*, traces that are hidden with `visible: *legendonly*` count as well,', + 'so hiding and showing them leaves the positions of the other traces as they are.' + ].join(' ') + }, dragmode: { valType: 'enumerated', values: ['orbit', 'turntable', 'zoom', 'pan', false], @@ -150,6 +178,63 @@ module.exports = { 'Determines the mode of hover interactions for this scene.' ].join(' ') }, + oit: { + valType: 'enumerated', + values: ['off', 'auto'], + dflt: 'off', + editType: 'plot', + description: [ + 'Determines how translucent `scatter3d` markers blend.', + 'With *off*, the markers blend in draw order.', + 'The picture then depends on the order of the traces and of the points.', + 'With *auto*, the markers blend by depth and the draw order has no effect.', + 'This uses extra render passes and float render targets.', + 'The targets need memory in proportion to the size of the plot.', + 'If the graphics hardware lacks a feature, plotly.js falls back to *off*.', + 'The scene reports the result in `getOITStatus()` and in the `plotly_oitstatus` event.' + ].join(' ') + }, + lod: { + minpoints: { + valType: 'number', + min: 0, + dflt: 0, + editType: 'plot', + description: [ + 'Sets the number of `scatter3d` disc markers from which a camera move shows a preview.', + 'A preview draws every k-th marker of every trace and no pick pass.', + 'The scene draws every marker again `settle` milliseconds after the last camera move.', + '0 turns the preview off.', + 'The graph emits `plotly_lod` when the state changes.' + ].join(' ') + }, + budget: { + valType: 'number', + min: 1, + dflt: 2500000, + editType: 'plot', + description: [ + 'Sets the largest number of markers in a preview.', + 'The stride k is the smallest power of two, from 2 to `maxstride`,', + 'that brings the markers within this number.' + ].join(' ') + }, + maxstride: { + valType: 'integer', + min: 2, + dflt: 64, + editType: 'plot', + description: 'Sets the largest stride of a preview.' + }, + settle: { + valType: 'number', + min: 0, + dflt: 150, + editType: 'plot', + description: 'Sets the time in milliseconds between the last camera move and the full picture.' + }, + editType: 'plot' + }, uirevision: { valType: 'any', editType: 'none', diff --git a/src/plots/gl3d/scene.js b/src/plots/gl3d/scene.js index e320fe9e780..427e79382e5 100644 --- a/src/plots/gl3d/scene.js +++ b/src/plots/gl3d/scene.js @@ -99,6 +99,8 @@ proto.prepareOptions = function() { axes: scene.axesOptions, spikes: scene.spikeOptions, pickRadius: 10, + // Nothing queries a static scene, so no pick pass runs before a query + pickIdleDelay: scene.staticMode ? 0 : 120, snapToData: true, autoScale: true, autoBounds: false, @@ -293,9 +295,38 @@ proto.initializeGLPlot = function() { scene.render(); }; + scene.glplot.onoitstatus = function(status) { + var gd = scene.graphDiv; + if(gd && gd.emit) gd.emit('plotly_oitstatus', Lib.extendFlat({scene: scene.id}, status)); + }; + scene.oitMode = scene.fullSceneLayout.oit; + scene.glplot.setOIT(scene.oitMode); + + // A static scene gets no level of detail, because an image must show every point. + scene.glplot.onlod = (state) => { + const gd = scene.graphDiv; + if(gd?.emit) gd.emit('plotly_lod', { subplot: scene.id, ...state }); + }; + scene.glplot.lod = scene.staticMode ? null : scene.fullSceneLayout.lod; + return true; }; +// order independent transparency status: {mode, tier, reason, format, mrt, nodes, passes, ...} +proto.getOITStatus = function() { + return this.glplot && this.glplot.getOITStatus ? this.glplot.getOITStatus() : null; +}; + +/** + * Get the level of detail of the scene. + * + * @returns `{state, stride, shown, total, settle}`. `state` is 'off', 'preview' or 'full'. `settle()` draws every point now. + */ +proto.getLOD = function() { + const { lodState, lodSettle } = this.glplot; + return { ...lodState, settle: lodSettle }; +}; + proto.render = function() { var scene = this; var gd = scene.graphDiv; @@ -456,13 +487,14 @@ proto.render = function() { pointData.bbox = bbox[0]; } + const hoverOn = !!scene.fullSceneLayout.hovermode; if(selection.distance < 5 && (selection.buttons || tabletmode)) { gd.emit('plotly_click', eventData); - } else { + } else if(hoverOn) { gd.emit('plotly_hover', eventData); } - this.oldEventData = eventData; + this.oldEventData = hoverOn ? eventData : undefined; } else { Fx.loneUnhover(svgContainer); if(this.oldEventData) gd.emit('plotly_unhover', this.oldEventData); @@ -494,9 +526,75 @@ proto.recoverContext = function() { var axisProperties = [ 'xaxis', 'yaxis', 'zaxis' ]; +const rangeOf = (a) => ({ buffer: a.buffer, offset: a.byteOffset, length: a.length }); +const sameRange = (r, a) => r.buffer === a.buffer && r.offset === a.byteOffset && r.length === a.length; + +/** + * Add the bounds of a scatter3d trace with typed x, y, and z on linear axes. + * + * One loop reads the three arrays. The scene keeps the result for the next plot call + * with the same buffer ranges and `layout.datarevision`. If every point is finite, + * `trace._typedBounds` gives the bounds to the conversion of the trace. + * + * @param scene - the scene + * @param trace - the full trace + * @param bounds - the bounds of the scene data, which this function extends + * @returns false if the trace needs the conversion of one value at a time + */ +function typedTraceBounds(scene, trace, bounds) { + const { x, y, z } = trace; + const layout = scene.fullSceneLayout; + if (trace.type !== 'scatter3d') return false; + if (!Lib.isTypedArray(x) || !Lib.isTypedArray(y) || !Lib.isTypedArray(z)) return false; + if (layout.xaxis.type !== 'linear' || layout.yaxis.type !== 'linear' || layout.zaxis.type !== 'linear') return false; + const n = x.length; + if ((trace._xlength || n) !== n || (trace._ylength || n) !== n || (trace._zlength || n) !== n) return false; + if (y.length !== n || z.length !== n) return false; + + const rev = scene.fullLayout.datarevision; + let b = scene._typedBounds?.[trace.uid]; + if (!(b && b.n === n && b.rev === rev && sameRange(b.x, x) && sameRange(b.y, y) && sameRange(b.z, z))) { + let x0 = Infinity; + let x1 = -Infinity; + let y0 = Infinity; + let y1 = -Infinity; + let z0 = Infinity; + let z1 = -Infinity; + let finite = true; + for (let i = 0; i < n; i++) { + const u = x[i]; + const v = y[i]; + const w = z[i]; + if (u - u === 0) { + if (u < x0) x0 = u; + if (u > x1) x1 = u; + } else finite = false; + if (v - v === 0) { + if (v < y0) y0 = v; + if (v > y1) y1 = v; + } else finite = false; + if (w - w === 0) { + if (w < z0) z0 = w; + if (w > z1) z1 = w; + } else finite = false; + } + b = { x: rangeOf(x), y: rangeOf(y), z: rangeOf(z), n, rev, lo: [x0, y0, z0], hi: [x1, y1, z1], finite }; + } + if (scene._typedBoundsNext) scene._typedBoundsNext[trace.uid] = b; + + for (let d = 0; d < 3; d++) { + if (b.lo[d] < bounds[0][d]) bounds[0][d] = b.lo[d]; + if (b.hi[d] > bounds[1][d]) bounds[1][d] = b.hi[d]; + } + trace._typedBounds = b.finite ? { x, y, z, lo: b.lo, hi: b.hi } : null; + return true; +} + function computeTraceBounds(scene, trace, bounds) { var fullSceneLayout = scene.fullSceneLayout; + if (typedTraceBounds(scene, trace, bounds)) return; + for(var d = 0; d < 3; d++) { var axisName = axisProperties[d]; var axLetter = axisName.charAt(0); @@ -580,9 +678,17 @@ proto.plot = function(sceneData, fullLayout, layout) { scene.updateFx(fullSceneLayout.dragmode, fullSceneLayout.hovermode); scene.camera.enableWheel = scene.graphDiv._context._scrollZoom.gl3d; + scene.glplot.lod = scene.staticMode ? null : fullSceneLayout.lod; + // Update scene background scene.glplot.setClearColor(str2RGBAarray(fullSceneLayout.bgcolor)); + // Update order independent transparency mode + if(scene.oitMode !== fullSceneLayout.oit) { + scene.oitMode = fullSceneLayout.oit; + scene.glplot.setOIT(scene.oitMode); + } + // Update axes functions BEFORE updating traces scene.setConvert(axis); @@ -596,12 +702,17 @@ proto.plot = function(sceneData, fullLayout, layout) { [-Infinity, -Infinity, -Infinity] ]; + scene._typedBoundsNext = {}; + const legendOnly = fullSceneLayout.datascale === 'all'; for(i = 0; i < sceneData.length; ++i) { data = sceneData[i]; - if(data.visible !== true || data._length === 0) continue; + const counts = data.visible === true || (legendOnly && data.visible === 'legendonly'); + if(!counts || data._length === 0) continue; computeTraceBounds(this, data, dataBounds); } + scene._typedBounds = scene._typedBoundsNext; + scene._typedBoundsNext = null; computeAnnotationBounds(this, dataBounds); var dataScale = [1, 1, 1]; @@ -1054,6 +1165,9 @@ proto.updateFx = function(dragmode, hovermode) { // to put dragmode and hovermode on the same grounds from relayout scene.fullSceneLayout.hovermode = hovermode; + + // Without hover, only a button press queries the pick buffer, for plotly_click + if (scene.glplot) scene.glplot.pickOnPress = !hovermode; }; function flipPixels(pixels, w, h) { @@ -1093,8 +1207,11 @@ proto.toImage = function(format) { if(!format) format = 'png'; if(scene.staticMode) scene.container.appendChild(STATIC_CANVAS); - // Force redraw + // Force redraw. Disc markers take a slower, smoother edge path on targets without multisampling. + var exportObjs = scene.glplot.objects; + for(var oi = 0; oi < exportObjs.length; oi++) exportObjs[oi].discExport = true; scene.glplot.redraw(); + for(var oj = 0; oj < exportObjs.length; oj++) exportObjs[oj].discExport = false; // Grab context and yank out pixels var gl = scene.glplot.gl; diff --git a/src/traces/scatter3d/attributes.js b/src/traces/scatter3d/attributes.js index 7191d73c1b6..70dd21209a8 100644 --- a/src/traces/scatter3d/attributes.js +++ b/src/traces/scatter3d/attributes.js @@ -172,6 +172,18 @@ var attrs = (module.exports = overrideAll( opacity: baseAttrs.opacity, + alwaysontop: { + valType: 'boolean', + dflt: false, + editType: 'calc', + description: [ + 'If *true*, the markers of this trace are drawn last, on top of everything else', + 'in the scene, without depth testing, in trace order.', + 'Use it for a highlight that must never be hidden by other points.', + 'The markers stay pickable.' + ].join(' ') + }, + hoverinfo: extendFlat({}, baseAttrs.hoverinfo) }, 'calc', diff --git a/src/traces/scatter3d/convert.js b/src/traces/scatter3d/convert.js index 019d362e5fe..3da266e9444 100644 --- a/src/traces/scatter3d/convert.js +++ b/src/traces/scatter3d/convert.js @@ -186,7 +186,88 @@ function formatParam(paramIn, len, calculate, dflt, extraFn) { return paramOut; } -function convertPlotlyOptions(scene, data) { +// Typed x, y, and z of a trace with markers only, on linear axes, convert to +// one Float32Array (x, y, z for each point) and not to one array for each point. +function isFlat(data, sceneLayout, x, y, z, len) { + if (!Lib.isTypedArray(x) || !Lib.isTypedArray(y) || !Lib.isTypedArray(z)) return false; + if (sceneLayout.xaxis.type !== 'linear' || sceneLayout.yaxis.type !== 'linear' || sceneLayout.zaxis.type !== 'linear') { + return false; + } + if (data.mode !== 'markers' || data.surfaceaxis >= 0) return false; + if (['error_x', 'error_y', 'error_z'].some((e) => data[e]?.visible)) return false; + const p = data.projection; + if (p && (p.x?.show || p.y?.show || p.z?.show)) return false; + return y.length >= len && z.length >= len; +} + +function flatPositions(data, scaleFactor, x, y, z, len) { + const [sx, sy, sz] = scaleFactor; + const out = new Float32Array(3 * len); + // The scene scanned these arrays for its bounds, and every point is finite. + // The scale is positive, so the bounds of the products are the products of the bounds. + const tb = data._typedBounds; + if (tb && tb.x === x && tb.y === y && tb.z === z && x.length === len && sx > 0 && sy > 0 && sz > 0) { + for (let i = 0, o = 0; i < len; i++, o += 3) { + out[o] = x[i] * sx; + out[o + 1] = y[i] * sy; + out[o + 2] = z[i] * sz; + } + out.bounds = [ + [tb.lo[0] * sx, tb.lo[1] * sy, tb.lo[2] * sz], + [tb.hi[0] * sx, tb.hi[1] * sy, tb.hi[2] * sz] + ]; + out.finite = true; + return out; + } + // Bounds of the finite points, from the same doubles as the conversion of one point at a time + const lo = [Infinity, Infinity, Infinity]; + const hi = [-Infinity, -Infinity, -Infinity]; + for (let i = 0, o = 0; i < len; i++, o += 3) { + const a = x[i] * sx; + const b = y[i] * sy; + const c = z[i] * sz; + out[o] = a; + out[o + 1] = b; + out[o + 2] = c; + if (a - a === 0 && b - b === 0 && c - c === 0) { + if (a < lo[0]) lo[0] = a; + if (a > hi[0]) hi[0] = a; + if (b < lo[1]) lo[1] = b; + if (b > hi[1]) hi[1] = b; + if (c < lo[2]) lo[2] = c; + if (c > hi[2]) hi[2] = c; + } + } + out.bounds = [lo, hi]; + return out; +} + +// The same range of the same buffer holds the same data, also in a new view object. +const rangeOf = (a) => ({ buffer: a.buffer, offset: a.byteOffset, length: a.length }); +const sameRange = (r, a) => r.buffer === a.buffer && r.offset === a.byteOffset && r.length === a.length; + +/** + * Tell if hover and click can never select a point of the trace. + * + * The pick buffer holds 24 bits of the point index. The ids of a longer trace + * name other points, so such a trace gets no hover and no click. The function logs a warning for it. + * + * @param data - the full trace + * @param len - the number of points + * @returns true for `hoverinfo: 'skip'` and for a trace above `maxPickPoints` + */ +function neverPicked(data, len) { + if (data.hoverinfo === 'skip') return true; + const max = createLineWithMarkers.maxPickPoints; + if (len <= max) return false; + Lib.warn( + `scatter3d trace ${data.index} has ${len} points. Hover and click cannot tell more than ${max} apart, ` + + 'so the trace gets neither. Split the trace, or set hoverinfo to *skip*.' + ); + return true; +} + +function convertPlotlyOptions(scene, data, self, sendPositions) { var points = []; var sceneLayout = scene.fullSceneLayout; var scaleFactor = scene.dataScale; @@ -206,18 +287,52 @@ function convertPlotlyOptions(scene, data) { var params, i; var text; - // Convert points - for (i = 0; i < len; i++) { - // sanitize numbers and apply transforms based on axes.type - xc = xaxis.d2l(x[i], 0, xcalendar) * scaleFactor[0]; - yc = yaxis.d2l(y[i], 0, ycalendar) * scaleFactor[1]; - zc = zaxis.d2l(z[i], 0, zcalendar) * scaleFactor[2]; + // gl-scatter3d keeps the positions of the last update when the same data + // comes again at the same scale: the same buffer ranges and `layout.datarevision`. + const flat = isFlat(data, sceneLayout, x, y, z, len); + const skip = neverPicked(data, len); + const rev = scene.fullLayout.datarevision; + const key = self?._flatKey; + const kept = + flat && + !sendPositions && + !!key && + !!self.scatterPlot?.flatState && + key.n === len && + key.rev === rev && + key.skip === skip && + key.scale.every((s, j) => s === scaleFactor[j]) && + sameRange(key.x, x) && + sameRange(key.y, y) && + sameRange(key.z, z); + if (self && !kept) { + self._flatKey = flat + ? { x: rangeOf(x), y: rangeOf(y), z: rangeOf(z), n: len, rev, skip, scale: scaleFactor.slice() } + : null; + } - points[i] = [xc, yc, zc]; + if (kept) { + // A trace with hover keeps the flat positions for the hover label + points = skip ? null : self.dataPoints; + } else if (flat) { + points = flatPositions(data, scaleFactor, x, y, z, len); + } else { + // Convert points + for (i = 0; i < len; i++) { + // sanitize numbers and apply transforms based on axes.type + xc = xaxis.d2l(x[i], 0, xcalendar) * scaleFactor[0]; + yc = yaxis.d2l(y[i], 0, ycalendar) * scaleFactor[1]; + zc = zaxis.d2l(z[i], 0, zcalendar) * scaleFactor[2]; + + points[i] = [xc, yc, zc]; + } } // convert text - if (Array.isArray(data.text)) { + if (flat && !Lib.isArrayOrTypedArray(data.text)) { + // One text for all the points of a trace with markers only needs no array + text = data.text; + } else if (Array.isArray(data.text)) { text = data.text; } else if (Lib.isTypedArray(data.text)) { text = Array.from(data.text); @@ -270,6 +385,9 @@ function convertPlotlyOptions(scene, data) { // Build object parameters params = { position: points, + positionsKept: kept, + skip: flat && skip, + neverPicked: skip, mode: data.mode, text: text }; @@ -369,7 +487,7 @@ proto.update = function (data) { this.data = data; // Run data conversion - var options = convertPlotlyOptions(this.scene, data); + var options = convertPlotlyOptions(this.scene, data, this); if ('mode' in options) { this.mode = options.mode; @@ -382,8 +500,8 @@ proto.update = function (data) { this.color = arrayToColor(options.scatterColor) || arrayToColor(options.lineColor); - // Save data points - this.dataPoints = options.position; + // Save data points. A flat trace without hover keeps none. + if (!options.positionsKept) this.dataPoints = options.skip ? [] : options.position; lineOptions = { gl: this.scene.glplot.gl, @@ -421,6 +539,9 @@ proto.update = function (data) { glyph: options.scatterMarker, opacity: scatterOpacity, orthographic: true, + markerRender: this.scene.fullSceneLayout.markerrender, + positionsKept: options.positionsKept, + pick: !options.neverPicked, lineWidth: options.scatterLineWidth, lineColor: options.scatterLineColor, project: options.project, @@ -429,13 +550,23 @@ proto.update = function (data) { }; if (this.mode.indexOf('markers') !== -1) { - if (this.scatterPlot) this.scatterPlot.update(scatterOptions); - else { + if (this.scatterPlot) { + this.scatterPlot.update(scatterOptions); + if (this.scatterPlot.positionsMissing) { + // gl-scatter3d draws this update on another marker path, which needs the positions + options = convertPlotlyOptions(this.scene, data, this, true); + this.dataPoints = options.skip ? [] : options.position; + scatterOptions.position = options.position; + scatterOptions.positionsKept = false; + this.scatterPlot.update(scatterOptions); + } + } else { this.scatterPlot = createScatterPlot(scatterOptions); this.scatterPlot._trace = this; this.scatterPlot.highlightScale = 1; this.scene.glplot.add(this.scatterPlot); } + this.scatterPlot.alwaysOnTop = !!data.alwaysontop; } else if (this.scatterPlot) { this.scene.glplot.remove(this.scatterPlot); this.scatterPlot.dispose(); @@ -547,4 +678,7 @@ function createLineWithMarkers(scene, data) { return plot; } +// The pick ids of one trace: 0 to 2^24 - 2. The last value means no point. +createLineWithMarkers.maxPickPoints = 16777215; + module.exports = createLineWithMarkers; diff --git a/src/traces/scatter3d/defaults.js b/src/traces/scatter3d/defaults.js index eb366090612..73e10033819 100644 --- a/src/traces/scatter3d/defaults.js +++ b/src/traces/scatter3d/defaults.js @@ -30,6 +30,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout coerce('zhoverformat'); coerce('mode'); + coerce('alwaysontop'); if (subTypes.hasMarkers(traceOut)) { handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, { diff --git a/src/traces/scattergl/base_index.js b/src/traces/scattergl/base_index.js index 2339e07acb7..32a0339fc6e 100644 --- a/src/traces/scattergl/base_index.js +++ b/src/traces/scattergl/base_index.js @@ -9,7 +9,9 @@ module.exports = { categories: ['gl', 'regl', 'cartesian', 'symbols', 'errorBarsOK', 'showLegend', 'scatter-like'], attributes: require('./attributes'), + layoutAttributes: require('./layout_attributes').default, supplyDefaults: require('./defaults'), + supplyLayoutDefaults: require('./layout_defaults').default, crossTraceDefaults: require('../scatter/cross_trace_defaults'), colorbar: require('../scatter/marker_colorbar'), formatLabels: require('./format_labels'), diff --git a/src/traces/scattergl/calc.js b/src/traces/scattergl/calc.js index 240418b07af..922f379a0f1 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,19 @@ 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); + // 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); + for (let k = 0; k < len; k++) ids[k] = k; + return ids; + }); } else { stash.ids = _ids; } @@ -96,7 +115,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 +149,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/src/traces/scattergl/layout_attributes.ts b/src/traces/scattergl/layout_attributes.ts new file mode 100644 index 00000000000..ae206726a34 --- /dev/null +++ b/src/traces/scattergl/layout_attributes.ts @@ -0,0 +1,77 @@ +import type { AttributeMap } from '../../types/lib/attributes'; + +/** + * Layout attributes of the scattergl level of detail. + * Consumer-facing types are generated from the schema by generate_schema_types.mjs. + */ +const attributes = { + lod: { + minpoints: { + valType: 'number', + min: 0, + dflt: 0, + editType: 'none', + description: [ + 'Sets the number of visible scattergl points from which a draw shows a preview first.', + 'A preview draws every k-th point of every trace.', + 'The full picture follows when no draw request came for `settle` milliseconds.', + '0 turns the preview off.', + 'Applies to a graph where the scattergl markers of one subplot are the only WebGL traces.', + 'The graph emits `plotly_lod` when the state changes.' + ].join(' ') + }, + budget: { + valType: 'number', + min: 1, + dflt: 2500000, + editType: 'none', + description: [ + 'Sets the largest number of points in a preview.', + 'The stride k is the smallest power of two, from 2 to `maxstride`,', + 'that brings the visible points within this number.' + ].join(' ') + }, + maxstride: { + valType: 'integer', + min: 2, + dflt: 64, + editType: 'none', + description: 'Sets the largest stride of a preview.' + }, + settle: { + valType: 'number', + min: 0, + dflt: 150, + editType: 'none', + description: 'Sets the time in milliseconds between the last draw request and the full picture.' + }, + slice: { + valType: 'number', + min: 0, + dflt: 5000000, + editType: 'none', + description: [ + 'Sets the number of points in one part of the full picture.', + 'The plot draws the next part when the GPU finished the part before.', + 'Thus a draw request between two parts does not wait for the full picture.', + '0 draws the full picture in one part.' + ].join(' ') + }, + edits: { + valType: 'enumerated', + values: ['hold', 'preview'] as const, + dflt: 'hold', + editType: 'none', + description: [ + 'Determines the picture during an edit of a fully drawn plot', + 'that keeps the axis ranges, the plot area and the size.', + '*hold* keeps the previous full picture until the new full picture is ready.', + '*preview* shows a preview first, as a pan does.', + 'Use *preview* for edits in quick succession, for example from a slider.' + ].join(' ') + }, + editType: 'none' + } +} as const satisfies AttributeMap; + +export default attributes; diff --git a/src/traces/scattergl/layout_defaults.ts b/src/traces/scattergl/layout_defaults.ts new file mode 100644 index 00000000000..7805bef03e9 --- /dev/null +++ b/src/traces/scattergl/layout_defaults.ts @@ -0,0 +1,23 @@ +import Lib from '../../lib'; +import layoutAttributes from './layout_attributes'; + +/** + * Supply the `lod` container of the layout. + * A layout without `lod` gets no `lod` container. + * + * @param layoutIn - the user-supplied layout + * @param layoutOut - the full layout to write into + */ +export default function supplyLayoutDefaults(layoutIn: any, layoutOut: any) { + if (!Lib.isPlainObject(layoutIn.lod)) return; + + const coerce = (attr: string) => Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr); + + if (coerce('lod.minpoints')) { + coerce('lod.budget'); + coerce('lod.maxstride'); + coerce('lod.settle'); + coerce('lod.slice'); + coerce('lod.edits'); + } +} diff --git a/src/traces/scattergl/lod.ts b/src/traces/scattergl/lod.ts new file mode 100644 index 00000000000..fd3d2470562 --- /dev/null +++ b/src/traces/scattergl/lod.ts @@ -0,0 +1,362 @@ +/** The `layout.lod` container after defaults. */ +interface LodOptions { + minpoints: number; + budget: number; + maxstride: number; + settle: number; + slice: number; + edits: 'hold' | 'preview'; +} + +type LodState = 'off' | 'preview' | 'stale' | 'full'; +type LodReason = 'plot' | 'range' | 'settle'; + +/** The work that waits for the GPU: the parts of a full picture, or the one draw of a held edit. */ +interface LodRun { + /** Index of the next group for `drawRange`. */ + g: number; + /** Offset of the next point in that group. */ + off: number; + slice: number; + gl: WebGLRenderingContext; + /** `EXT_disjoint_timer_query`, or null. */ + ext: any; + query: unknown; + /** Time of the last query, from `Date.now()`. */ + asked: number; +} + +const TIMER_QUERY = 'EXT_disjoint_timer_query'; +// A timer query that never returns must not stop the plot. +const PART_TIMEOUT = 2000; +const HOLD_TIMEOUT = 5000; + +/** + * Attach the level of detail to the scene of a scattergl subplot. + * + * With `layout.lod.minpoints` set, `scene.draw` draws a preview of every k-th point. + * The full picture follows `layout.lod.settle` ms after the last draw request, in parts. + * The function replaces `scene.draw` and `scene.update` and adds `scene.lod`: + * `{state, stride, shown, total, settle(), beforeClear(), cancel()}`. + * The graph emits `plotly_lod` when `state`, `stride` or `total` changes. + * Without `layout.lod`, `scene.draw` draws as before. + * + * @param gd - the graph div + * @param subplot - the cartesian subplot (`plotinfo`) that owns the scene + * @param scene - the scattergl scene of the subplot + */ +export function attachLod(gd: any, subplot: any, scene: any) { + const fullDraw = scene.draw; + const update = scene.update; + const S = (scene.lod = { state: 'off' as LodState, stride: 0, shown: 0, total: 0 } as any); + let timer: ReturnType | null = null; + let frame: number | null = null; + let run: LodRun | null = null; + let cover: HTMLCanvasElement | null = null; + let covered: HTMLCanvasElement | null = null; + // A drag or a wheel changed the range since the last draw. + let ranged = false; + // The view of the full picture that the cover shows, between a clear and the next draw. + let held: string | null = null; + let heldTimer: ReturnType | null = null; + let view = ''; + + const strideFor = (n: number, opts: LodOptions) => { + if (n < opts.minpoints) return 0; + let k = 2; + while (k < opts.maxstride && n / k > opts.budget) k *= 2; + return k; + }; + + /** The visible points of the scene, or 0 if the scene cannot show a preview. */ + const points = (opts: LodOptions | undefined) => { + const fullLayout = gd._fullLayout; + const scatter = scene.scatter2d; + if (!opts || !(opts.minpoints > 0) || gd._context.staticPlot || !scatter || !scatter.lodCount) return 0; + // The regl components stay after their traces go, so the options of this calc tell what the scene draws. + for (let i = 0; i < scene.count; i++) { + if ( + scene.lineOptions[i] || + scene.fillOptions[i] || + scene.errorXOptions[i] || + scene.errorYOptions[i] || + scene.textOptions[i] || + scene.selectBatch[i].length || + scene.unselectBatch[i].length + ) + return 0; + } + // All regl scenes share one canvas, and the full picture needs a clear of that canvas. + if (fullLayout._has('splom') || fullLayout._has('polar')) return 0; + for (const id in fullLayout._plots) { + const other = fullLayout._plots[id]._scene; + if (other && other !== scene) return 0; + } + const n = scatter.lodCount(scene.hidden, scene.visibleCount); + return n > 0 ? n : 0; + }; + + const clearCanvases = () => { + gd._fullLayout._glcanvas.each((d: any) => { + if (d.regl) d.regl.clear({ color: true, depth: true }); + }); + }; + + /** The ranges and the geometry that fix the position of each point on the canvas. */ + const viewOf = () => { + const { width, height } = gd._fullLayout; + const xa = subplot.xaxis; + const ya = subplot.yaxis; + return [...xa.range, ...ya.range, xa._offset, xa._length, ya._offset, ya._length, width, height].join(); + }; + + const set = (state: LodState, stride: number, total: number, reason: LodReason) => { + if (S.state === state && S.stride === stride && S.total === total) return; + const shown = state === 'preview' ? Math.round(total / stride) : total; + S.state = state; + S.stride = stride; + S.total = total; + S.shown = shown; + if (gd.emit) gd.emit('plotly_lod', { subplot: subplot.id, state, stride, shown, total, reason }); + }; + + const glCanvas = (): HTMLCanvasElement => gd._fullLayout._glcanvas.node(); + + /** Show a copy of the canvas in place of the canvas, so that the scene can draw on the canvas in parts. */ + const coverCanvas = () => { + const canvas = glCanvas(); + if (!cover) { + cover = document.createElement('canvas'); + cover.className = 'gl-lod-cover'; + cover.style.cssText = 'position:absolute;top:0;left:0;pointer-events:none'; + } + if (cover.parentNode !== canvas.parentNode) canvas.parentNode!.appendChild(cover); + cover.width = canvas.width; + cover.height = canvas.height; + cover.style.width = canvas.style.width; + cover.style.height = canvas.style.height; + cover.style.display = ''; + cover.getContext('2d')!.drawImage(canvas, 0, 0); + canvas.style.visibility = 'hidden'; + covered = canvas; + }; + + const uncover = () => { + if (!covered || !cover) return; + covered.style.visibility = ''; + covered = null; + cover.style.display = 'none'; + // Release the pixels of the copy. + cover.width = cover.height = 0; + }; + + /** Stop all work that waits. The cover stays. */ + const stop = () => { + if (timer !== null) { + clearTimeout(timer); + timer = null; + } + if (heldTimer !== null) { + clearTimeout(heldTimer); + heldTimer = null; + } + held = null; + if (frame !== null) { + window.cancelAnimationFrame(frame); + frame = null; + } + if (run) { + if (run.query) run.ext.deleteQueryEXT(run.query); + run = null; + } + }; + + const cancel = () => { + stop(); + uncover(); + }; + + /** Tell if the GPU still works on the draws of the last query of `me`, for `ms` at most. */ + const pending = (me: LodRun, ms: number) => { + if (!me.query) return false; + const available = me.ext.getQueryObjectEXT(me.query, me.ext.QUERY_RESULT_AVAILABLE_EXT); + if (!available && Date.now() - me.asked < ms) return true; + me.ext.deleteQueryEXT(me.query); + me.query = null; + return false; + }; + + /** Do `draw` and start a timer query on `me` for the draw. Without the extension, wait for the GPU. */ + const timed = (me: LodRun, draw: () => boolean, wait: (done: boolean) => boolean) => { + const { gl, ext } = me; + if (ext) { + me.query = ext.createQueryEXT(); + ext.beginQueryEXT(ext.TIME_ELAPSED_EXT, me.query); + } + const done = draw(); + if (ext) { + ext.endQueryEXT(ext.TIME_ELAPSED_EXT); + gl.flush(); + me.asked = Date.now(); + } else if (wait(done)) { + gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(4)); + } + return done; + }; + + const newRun = (slice: number): LodRun => { + const gl = scene.scatter2d.gl; + // A context wrapper can return an object without functions for an extension that the wrapper does not + // know, as virtual-webgl does. Such an extension counts as missing. + let ext = gl.getExtension(TIMER_QUERY); + if (!ext || typeof ext.createQueryEXT !== 'function' || typeof ext.getQueryObjectEXT !== 'function') ext = null; + return { g: 0, off: 0, slice, gl, ext, query: null, asked: 0 }; + }; + + /** Draw one part of the full picture. Draw the next part when the GPU finished this part. */ + const step = () => { + const me = run!; + frame = null; + if (pending(me, PART_TIMEOUT)) { + frame = window.requestAnimationFrame(step); + return; + } + const done = timed( + me, + () => scene.scatter2d.drawRange(me, me.slice, scene.hidden), + (last) => !last + ); + if (done) { + cancel(); + scene.dirty = false; + set('full', S.stride, S.total, 'settle'); + } else { + frame = window.requestAnimationFrame(step); + } + }; + + const refine = () => { + const opts: LodOptions = gd._fullLayout.lod; + timer = null; + if (!scene.scatter2d) return; + if (!(opts.slice > 0)) { + clearCanvases(); + fullDraw.call(scene); + set('full', S.stride, S.total, 'settle'); + return; + } + run = newRun(opts.slice); + coverCanvas(); + clearCanvases(); + step(); + }; + + /** + * Draw the new full picture of an edit in one draw, below the copy of the old full picture. + * A settle time or parts only delay the new picture, because the old picture stays on screen. + */ + const holdDraw = (stride: number, total: number, reason: LodReason) => { + const me = (run = newRun(0)); + timed( + me, + () => { + fullDraw.call(scene); + return true; + }, + () => true + ); + set('stale', stride, total, reason); + const wait = () => { + frame = null; + if (pending(me, HOLD_TIMEOUT)) { + frame = window.requestAnimationFrame(wait); + return; + } + cancel(); + set('full', stride, total, 'settle'); + }; + wait(); + }; + + // The browser reports the loss of a released canvas one task later, on the same graph div. + // A new plot can then own the graph div, so only a canvas of this plot counts. + const contextLost = (d: any) => { + const target = d?.event?.target; + const glcanvas = gd._fullLayout?._glcanvas; + if (!target || !glcanvas) return; + let own = false; + glcanvas.each(function (this: Element) { + if (this === target) own = true; + }); + if (own) cancel(); + }; + if (gd.on) gd.on('plotly_webglcontextlost', contextLost); + + scene.update = function (opt: any) { + if (opt && opt.range) ranged = true; + return update.apply(scene, arguments); + }; + + scene.draw = () => { + const opts: LodOptions | undefined = gd._fullLayout.lod; + const reason: LodReason = ranged ? 'range' : 'plot'; + const was = held; + const now = viewOf(); + ranged = false; + stop(); + const total = points(opts); + const stride = total ? strideFor(total, opts!) : 0; + view = now; + if (stride && was === now && reason === 'plot') { + holdDraw(stride, total, reason); + return; + } + uncover(); + if (!stride) { + fullDraw.call(scene); + set('off', 0, total, reason); + return; + } + scene.scatter2d.drawStride(stride, scene.hidden); + scene.dirty = false; + set('preview', stride, total, reason); + timer = setTimeout(refine, opts!.settle); + }; + + /** + * Prepare for a clear of the canvas. `clearGlCanvases` calls this function. + * If the canvas shows the full picture, a copy takes the place of the canvas. + * The next `scene.draw` keeps the copy for an edit and removes the copy for a new view. + */ + S.beforeClear = () => { + const opts: LodOptions | undefined = gd._fullLayout.lod; + if (ranged || !opts || opts.edits === 'preview' || !glCanvas()) return; + if (S.state === 'full' && !covered) coverCanvas(); + else if (S.state !== 'stale' || !covered) return; + held = view; + if (heldTimer !== null) return; + // If no draw follows the clear, remove the copy. + heldTimer = setTimeout(() => { + heldTimer = null; + if (held === null) return; + held = null; + if (!run) uncover(); + }, 0); + }; + + /** Draw the full picture now, in one draw. */ + S.settle = () => { + if (S.state !== 'preview' && S.state !== 'stale') return; + cancel(); + clearCanvases(); + fullDraw.call(scene); + set('full', S.stride, S.total, 'settle'); + }; + + /** Stop all work and remove the cover. `scene.destroy` calls this function. */ + S.cancel = () => { + cancel(); + if (cover && cover.parentNode) cover.parentNode.removeChild(cover); + if (gd.removeListener) gd.removeListener('plotly_webglcontextlost', contextLost); + }; +} diff --git a/src/traces/scattergl/plot.js b/src/traces/scattergl/plot.js index d271f8dda8a..7c0e259284f 100644 --- a/src/traces/scattergl/plot.js +++ b/src/traces/scattergl/plot.js @@ -319,6 +319,11 @@ var exports = module.exports = function plot(gd, subplot, cdata) { if(isSelectMode) { // create scatter instance by cloning scatter2d if(!scene.select2d) { + // The focus layer shows the selected points and gets its WebGL context here + if (!prepareRegl(gd, ['ANGLE_instanced_arrays', 'OES_element_index_uint'], reglPrecompiled, true)) { + scene.init(); + return; + } scene.select2d = createScatter(fullLayout._glcanvas.data()[1].regl); } diff --git a/src/traces/scattergl/scene_update.js b/src/traces/scattergl/scene_update.js index 080c524525c..d6542c05ce7 100644 --- a/src/traces/scattergl/scene_update.js +++ b/src/traces/scattergl/scene_update.js @@ -1,6 +1,8 @@ 'use strict'; var Lib = require('../../lib'); +const clearGlCanvases = require('../../lib/clear_gl_canvases'); +const { attachLod } = require('./lod'); // make sure scene exists on subplot, return it module.exports = function sceneUpdate(gd, subplot) { @@ -24,7 +26,11 @@ module.exports = function sceneUpdate(gd, subplot) { textUnselectedOptions: [], // selection batches selectBatch: [], - unselectBatch: [] + unselectBatch: [], + // Sparse arrays by scene index. If hidden[i] is true, no draw shows the markers of trace i. + // visibleCount[i] replaces the point count of trace i for the level of detail. + hidden: [], + visibleCount: [] }; // regl- component stubs, initialized in dirty plot call @@ -85,7 +91,7 @@ module.exports = function sceneUpdate(gd, subplot) { if(scene.errorXOptions[i]) error2d.draw(i); if(scene.errorYOptions[i]) error2d.draw(i + count); } - if(scatter2d && scene.markerOptions[i]) { + if(scatter2d && scene.markerOptions[i] && !scene.hidden[i]) { if(unselectBatch[i].length) { var arg = Lib.repeat([], scene.count); arg[i] = unselectBatch[i]; @@ -106,8 +112,20 @@ module.exports = function sceneUpdate(gd, subplot) { scene.dirty = false; }; + // Hide or show the markers of traces by scene index, then draw again. + // A restyle of `visible` does a calc and an upload. setHidden does not. + scene.setHidden = (map) => { + for(const index in map) scene.hidden[index] = !!map[index]; + clearGlCanvases(gd); + // A require at the top makes a cycle, because plot_api/subroutines loads the trace modules. + require('../../plot_api/subroutines').redrawReglTraces(gd); + }; + + attachLod(gd, subplot, scene); + // remove scene resources scene.destroy = function destroy() { + scene.lod.cancel(); if(scene.fill2d && scene.fill2d.destroy) scene.fill2d.destroy(); if(scene.scatter2d && scene.scatter2d.destroy) scene.scatter2d.destroy(); if(scene.error2d && scene.error2d.destroy) scene.error2d.destroy(); @@ -132,6 +150,8 @@ module.exports = function sceneUpdate(gd, subplot) { scene.selectBatch = null; scene.unselectBatch = null; + scene.hidden = null; + scene.visibleCount = null; // we can't just delete _scene, because `destroy` is called in the // middle of supplyDefaults, before relinkPrivateKeys which will put it back. diff --git a/src/types/core/events.d.ts b/src/types/core/events.d.ts index fb42ba475ad..c96b2942d67 100644 --- a/src/types/core/events.d.ts +++ b/src/types/core/events.d.ts @@ -321,6 +321,26 @@ export interface SliderEndEvent { step: SliderStep; } +// --------------------------------------------------------------------------- +// Level of detail events +// --------------------------------------------------------------------------- + +/** Payload for `plotly_lod`, emitted when the level of detail of a subplot changes. */ +export interface LodEvent { + /** The id of the cartesian subplot or of the gl3d scene, for example 'xy' or 'scene'. */ + subplot: string; + /** 'preview': a part of the points is on screen. 'stale': the picture before an edit is on screen. */ + state: 'off' | 'preview' | 'stale' | 'full'; + /** The preview draws every `stride`-th point. 0 in state 'off'. */ + stride: number; + /** The number of points on screen. */ + shown: number; + /** The number of visible points. */ + total: number; + /** The cause of the change. */ + reason: 'plot' | 'range' | 'camera' | 'settle'; +} + // --------------------------------------------------------------------------- // WebGL context events // --------------------------------------------------------------------------- @@ -428,6 +448,8 @@ export interface PlotlyHTMLElement extends HTMLElement { on(event: 'plotly_relayout' | 'plotly_relayouting', callback: (event: PlotRelayoutEvent) => void): void; /** Subscribe to update events (`Plotly.update` calls). */ on(event: 'plotly_update', callback: (event: PlotUpdateEvent) => void): void; + /** Subscribe to level of detail events (`layout.lod`, `scene.lod`). */ + on(event: 'plotly_lod', callback: (event: LodEvent) => void): void; /** Subscribe to WebGL context loss events. */ on(event: 'plotly_webglcontextlost', callback: (event: WebGLContextLostEvent) => void): void; /** Subscribe to annotation click events. */ @@ -523,6 +545,7 @@ export type PlotlyEventName = | 'plotly_legenddoubleclick' | 'plotly_legendtitleclick' | 'plotly_legendtitledoubleclick' + | 'plotly_lod' | 'plotly_react' | 'plotly_redraw' | 'plotly_relayout' diff --git a/src/types/generated/schema.d.ts b/src/types/generated/schema.d.ts index 853b8c815f9..f68a5ea16be 100644 --- a/src/types/generated/schema.d.ts +++ b/src/types/generated/schema.d.ts @@ -7447,6 +7447,11 @@ export interface ScatterData { } export interface Scatter3dData { + /** + * If *true*, the markers of this trace are drawn last, on top of everything else in the scene, without depth testing, in trace order. Use it for a highlight that must never be hidden by other points. The markers stay pickable. + * @default false + */ + alwaysontop?: boolean; /** * Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected. * @default false @@ -13734,6 +13739,11 @@ export interface Scene { z?: number; }; }; + /** + * Determines which traces set the scale that the data of this scene is drawn at. With *visible*, hiding or showing a trace that changes the extent of the data changes the scale, and the positions of every trace are converted and uploaded again. With *all*, traces that are hidden with `visible: *legendonly*` count as well, so hiding and showing them leaves the positions of the other traces as they are. + * @default 'visible' + */ + datascale?: 'visible' | 'all'; domain?: Domain; /** Determines the mode of drag interactions for this scene. */ dragmode?: 'orbit' | 'turntable' | 'zoom' | 'pan' | false; @@ -13742,6 +13752,42 @@ export interface Scene { * @default 'closest' */ hovermode?: 'closest' | false; + lod?: { + /** + * Sets the largest number of markers in a preview. The stride k is the smallest power of two, from 2 to `maxstride`, that brings the markers within this number. + * @default 2500000 + * Minimum: 1 + */ + budget?: number; + /** + * Sets the largest stride of a preview. + * @default 64 + * Minimum: 2 + */ + maxstride?: number; + /** + * Sets the number of `scatter3d` disc markers from which a camera move shows a preview. A preview draws every k-th marker of every trace and no pick pass. The scene draws every marker again `settle` milliseconds after the last camera move. 0 turns the preview off. The graph emits `plotly_lod` when the state changes. + * @default 0 + * Minimum: 0 + */ + minpoints?: number; + /** + * Sets the time in milliseconds between the last camera move and the full picture. + * @default 150 + * Minimum: 0 + */ + settle?: number; + }; + /** + * Sets how circle markers of *scatter3d* traces are drawn. The symbols *circle* and *circle-open* have two forms. *glyph* draws each marker as a mesh of 60 to 104 vertices. This is the default. *disc* draws each marker as one round point sprite. It needs far less memory and draws faster. The edge of a disc differs from the edge of a glyph by about one pixel. A marker with another symbol, a projection on the axes, or a size above the point size limit of the GPU is drawn as a glyph. *auto* is currently the same as *disc*. + * @default 'glyph' + */ + markerrender?: 'glyph' | 'disc' | 'auto'; + /** + * Determines how translucent `scatter3d` markers blend. With *off*, the markers blend in draw order. The picture then depends on the order of the traces and of the points. With *auto*, the markers blend by depth and the draw order has no effect. This uses extra render passes and float render targets. The targets need memory in proportion to the size of the plot. If the graphics hardware lacks a feature, plotly.js falls back to *off*. The scene reports the result in `getOITStatus()` and in the `plotly_oitstatus` event. + * @default 'off' + */ + oit?: 'off' | 'auto'; /** Controls persistence of user-driven changes in camera attributes. Defaults to `layout.uirevision`. */ uirevision?: any; xaxis?: { @@ -16333,6 +16379,43 @@ export interface Layout { iciclecolorway?: Color[]; images?: LayoutImage[]; legend?: Legend; + lod?: { + /** + * Sets the largest number of points in a preview. The stride k is the smallest power of two, from 2 to `maxstride`, that brings the visible points within this number. + * @default 2500000 + * Minimum: 1 + */ + budget?: number; + /** + * Determines the picture during an edit of a fully drawn plot that keeps the axis ranges, the plot area and the size. *hold* keeps the previous full picture until the new full picture is ready. *preview* shows a preview first, as a pan does. Use *preview* for edits in quick succession, for example from a slider. + * @default 'hold' + */ + edits?: 'hold' | 'preview'; + /** + * Sets the largest stride of a preview. + * @default 64 + * Minimum: 2 + */ + maxstride?: number; + /** + * Sets the number of visible scattergl points from which a draw shows a preview first. A preview draws every k-th point of every trace. The full picture follows when no draw request came for `settle` milliseconds. 0 turns the preview off. Applies to a graph where the scattergl markers of one subplot are the only WebGL traces. The graph emits `plotly_lod` when the state changes. + * @default 0 + * Minimum: 0 + */ + minpoints?: number; + /** + * Sets the time in milliseconds between the last draw request and the full picture. + * @default 150 + * Minimum: 0 + */ + settle?: number; + /** + * Sets the number of points in one part of the full picture. The plot draws the next part when the GPU finished the part before. Thus a draw request between two parts does not wait for the full picture. 0 draws the full picture in one part. + * @default 5000000 + * Minimum: 0 + */ + slice?: number; + }; map?: MapLayout; margin?: { /** diff --git a/stackgl_modules/index.js b/stackgl_modules/index.js index b812d41f949..68d7423b205 100644 --- a/stackgl_modules/index.js +++ b/stackgl_modules/index.js @@ -18665,6 +18665,488 @@ function createCamera(element, options) { } +/***/ }, + +/***/ 2971 +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; + + +// Order independent transparency for gl-plot3d: probe, render targets, composite shader and depth extent. +// The render loop (scene.js) drives the passes; objects draw themselves through obj.drawOIT. + +var createGLShader = __webpack_require__(9405) +var drawTriangle = __webpack_require__(7169) + +// ---- Order independent transparency: per-pixel transmittance binning ---- +// D: anchor pass (nearest transparent depth) + optical-depth pass + colour pass + composite. +// D2: the same without the anchor (global nodes over the depth extent of the transparent data). +// Everything is additive (or MIN for the anchor), so draw order does not matter. +var OIT_VARIANTS = { + 'D8': {K: 8, anchored: true}, + 'D16': {K: 16, anchored: true}, + 'D2-8': {K: 8, anchored: false}, + 'D2-16': {K: 16, anchored: false} +} + +// TEST HOOKS ONLY. window.__plotlyOITTestHooks = {disableExt: ['WEBGL_draw_buffers', ...] (pretend these extensions +// are missing), failAlloc: true (make the render target allocation fail), anchorF32: true (32 bit anchor instead of +// 16 bit), noReuse: true (own colour and depth targets instead of sharing the accumBuffer's), timerLog: [] (record +// per-pass EXT_disjoint_timer_query timers; costs nothing when unset)}. The object is read when a scene is created +// and again on scene.setOIT() / scene.resetOIT(), never per frame. variant: 'D8' | 'D2-8' | 'D2-16' selects another +// node count or the variant without the anchor pass (default 'D16'). Nothing here is a supported API. +var OIT_HOOKS = {} + +function oitLoadHooks() { + OIT_HOOKS = (typeof window !== 'undefined' && window.__plotlyOITTestHooks) || {} +} + +function oitDisabledExt() { + return OIT_HOOKS.disableExt || [] +} + +// getExtension that honours the test hook disableExt +function oitExt(gl, name) { + if(oitDisabledExt().indexOf(name) >= 0) return null + return gl.getExtension(name) +} + +var OIT_VERT = 'precision mediump float;\nattribute vec2 position;\nvoid main() {\n gl_Position = vec4(position, 0, 1);\n}' + +function oitMakeTex(gl, w, h, type) { + var t = gl.createTexture() + gl.bindTexture(gl.TEXTURE_2D, t) + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST) + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST) + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE) + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE) + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, w, h, 0, gl.RGBA, type, null) + return t +} + +function oitProbeShader(gl, body, withMRT) { + var frag = (withMRT ? '#extension GL_EXT_draw_buffers : require\n' : '') + + 'precision highp float;\nuniform float v;\nvoid main() {\n' + body + '\n}' + return createGLShader(gl, OIT_VERT, frag, null, [{name: 'position', type: 'vec2'}]) +} + +// reads the 2x2 float texture `tex` through a decoding pass into an RGBA8 target +function oitReadTex(gl, decode, rgba8Fbo, tex, scale) { + gl.bindFramebuffer(gl.FRAMEBUFFER, rgba8Fbo) + gl.viewport(0, 0, 2, 2) + gl.disable(gl.BLEND) + gl.activeTexture(gl.TEXTURE0) + gl.bindTexture(gl.TEXTURE_2D, tex) + decode.bind() + decode.uniforms.tex = 0 + decode.uniforms.scale = scale + drawTriangle(gl) + var px = new Uint8Array(4) + gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, px) + return px +} + +function oitClose(px, want, tol) { + for(var i = 0; i < 4; ++i) { + if(Math.abs(px[i] - want[i]) > tol) return false + } + return true +} + +// Functional 2x2 render-and-blend test of one float format. Returns what actually works. +function oitTestFormat(gl, type, mm, db) { + var out = {complete: false, add: false, clear: false, minmax: false, mrt: false} + var tmp = [] + var fbo = gl.createFramebuffer() + var fbo2 = gl.createFramebuffer() + var dfbo = gl.createFramebuffer() + var texA = oitMakeTex(gl, 2, 2, type) + var texB = oitMakeTex(gl, 2, 2, type) + var texD = oitMakeTex(gl, 2, 2, gl.UNSIGNED_BYTE) + var decode = null, draw = null, drawMRT = null + try { + while(gl.getError() !== gl.NO_ERROR) { /* flush */ } + gl.bindFramebuffer(gl.FRAMEBUFFER, dfbo) + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texD, 0) + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo) + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texA, 0) + if(gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) return out + out.complete = true + + decode = createGLShader(gl, OIT_VERT, + 'precision highp float;\nuniform sampler2D tex;\nuniform vec4 scale;\nvoid main() {\n gl_FragColor = texture2D(tex, vec2(0.5)) * scale;\n}', + null, [{name: 'position', type: 'vec2'}]) + draw = oitProbeShader(gl, 'gl_FragColor = vec4(v, 2.0 * v, v / 3.0, 1.0);') + + gl.disable(gl.DEPTH_TEST) + gl.disable(gl.CULL_FACE) + gl.colorMask(true, true, true, true) + gl.depthMask(false) + + // 1. additive blending keeps values above 1 and sums three draws + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo) + gl.viewport(0, 0, 2, 2) + gl.clearColor(0, 0, 0, 0) + gl.clear(gl.COLOR_BUFFER_BIT) + gl.enable(gl.BLEND) + gl.blendEquation(gl.FUNC_ADD) + gl.blendFunc(gl.ONE, gl.ONE) + draw.bind() + draw.uniforms.v = 0.75 + for(var i = 0; i < 3; ++i) drawTriangle(gl) + var px = oitReadTex(gl, decode, dfbo, texA, [0.25, 0.125, 0.5, 0.25]) + out.add = oitClose(px, [143, 143, 96, 191], 4) && gl.getError() === gl.NO_ERROR + + // 2. clear values above 1 are kept (the anchor is cleared to a large depth) + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo) + gl.viewport(0, 0, 2, 2) + gl.clearColor(5, 5, 5, 5) + gl.clear(gl.COLOR_BUFFER_BIT) + px = oitReadTex(gl, decode, dfbo, texA, [0.125, 0.125, 0.125, 0.125]) + out.clear = oitClose(px, [159, 159, 159, 159], 4) + + // 3. MIN blending (the anchor) on this format + if(mm) { + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo) + gl.viewport(0, 0, 2, 2) + gl.enable(gl.BLEND) + gl.blendEquation(mm.MIN_EXT) + gl.blendFunc(gl.ONE, gl.ONE) + draw.bind() + draw.uniforms.v = 0.7 + drawTriangle(gl) + draw.uniforms.v = 0.3 + drawTriangle(gl) + draw.uniforms.v = 0.9 + drawTriangle(gl) + gl.blendEquation(gl.FUNC_ADD) + px = oitReadTex(gl, decode, dfbo, texA, [1, 0.5, 1, 1]) + out.minmax = oitClose(px, [77, 77, 26, 255], 4) && gl.getError() === gl.NO_ERROR + } + + // 4. two colour attachments written by one draw (WEBGL_draw_buffers) + if(db && gl.getParameter(db.MAX_DRAW_BUFFERS_WEBGL) >= 2) { + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo2) + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texA, 0) + gl.framebufferTexture2D(gl.FRAMEBUFFER, db.COLOR_ATTACHMENT1_WEBGL, gl.TEXTURE_2D, texB, 0) + if(gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE) { + drawMRT = oitProbeShader(gl, 'gl_FragData[0] = vec4(0.5);\n gl_FragData[1] = vec4(0.25);', true) + db.drawBuffersWEBGL([db.COLOR_ATTACHMENT0_WEBGL, db.COLOR_ATTACHMENT1_WEBGL]) + gl.viewport(0, 0, 2, 2) + gl.clearColor(0, 0, 0, 0) + gl.clear(gl.COLOR_BUFFER_BIT) + gl.enable(gl.BLEND) + gl.blendFunc(gl.ONE, gl.ONE) + drawMRT.bind() + drawTriangle(gl) + drawTriangle(gl) + var pa = oitReadTex(gl, decode, dfbo, texA, [0.5, 0.5, 0.5, 0.5]) + var pb = oitReadTex(gl, decode, dfbo, texB, [0.5, 0.5, 0.5, 0.5]) + out.mrt = oitClose(pa, [128, 128, 128, 128], 4) && oitClose(pb, [64, 64, 64, 64], 4) && + gl.getError() === gl.NO_ERROR + } + } + } catch(e) { + out.error = String(e && e.message || e) + } finally { + gl.bindFramebuffer(gl.FRAMEBUFFER, null) + gl.bindTexture(gl.TEXTURE_2D, null) + gl.disable(gl.BLEND) + gl.blendEquation(gl.FUNC_ADD) + gl.deleteFramebuffer(fbo) + gl.deleteFramebuffer(fbo2) + gl.deleteFramebuffer(dfbo) + gl.deleteTexture(texA) + gl.deleteTexture(texB) + gl.deleteTexture(texD) + if(decode) decode.dispose() + if(draw) draw.dispose() + if(drawMRT) drawMRT.dispose() + while(gl.getError() !== gl.NO_ERROR) { /* flush */ } + } + return out +} + +var oitProbeCache = [] + +// Capability probe: functional, per context, cached. Never throws. +function oitProbe(gl) { + var key = oitDisabledExt().join(',') + for(var i = oitProbeCache.length - 1; i >= 0; --i) { + var e = oitProbeCache[i] + if(e.gl.isContextLost()) oitProbeCache.splice(i, 1) + else if(e.gl === gl && e.key === key) return e.result + } + var res + try { + res = oitRunProbe(gl) + } catch(err) { + res = {ok: false, reason: 'probe-failed', error: String(err && err.message || err)} + } + oitProbeCache.push({gl: gl, key: key, result: res}) + return res +} + +function oitRunProbe(gl) { + var res = {ok: false, reason: null, accFmt: null, tauFmt: null, anchorOK: {}, mrtOK: false, maxDraw: 1, tests: {}} + if(typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext) { + res.reason = 'webgl2-context' + return res + } + var hp = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT) + if(!hp || !hp.precision) { + res.reason = 'no-highp-fragment' + return res + } + if(gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS) < 6) { + res.reason = 'few-texture-units' + return res + } + var mm = oitExt(gl, 'EXT_blend_minmax') + var db = oitExt(gl, 'WEBGL_draw_buffers') + if(db) res.maxDraw = Math.min(gl.getParameter(db.MAX_DRAW_BUFFERS_WEBGL), gl.getParameter(db.MAX_COLOR_ATTACHMENTS_WEBGL)) + + var hTex = oitExt(gl, 'OES_texture_half_float') + var hCb = oitExt(gl, 'EXT_color_buffer_half_float') + var fTex = oitExt(gl, 'OES_texture_float') + var fCb = oitExt(gl, 'WEBGL_color_buffer_float') + oitExt(gl, 'EXT_float_blend') + var t16 = (hTex && hCb) ? oitTestFormat(gl, hTex.HALF_FLOAT_OES, mm, db) : null + var t32 = (fTex && fCb) ? oitTestFormat(gl, gl.FLOAT, mm, db) : null + res.tests = {f16: t16, f32: t32} + var ok16 = !!(t16 && t16.complete && t16.add) + var ok32 = !!(t32 && t32.complete && t32.add && t32.clear) + if(ok16) res.hType = hTex.HALF_FLOAT_OES + if(ok32) res.fType = gl.FLOAT + if(!ok16 && !ok32) { + res.reason = (!hTex || !hCb) && (!fTex || !fCb) ? 'no-float-target' : + ((t32 && t32.complete && !t32.add) || (t16 && t16.complete && !t16.add)) ? 'no-float-blend' : 'probe-failed' + return res + } + // accumulation (and anchor) in 32 bit floats when they blend, else 16 bit + res.accFmt = ok32 ? 'f32' : 'f16' + // optical depth is safe in 16 bit floats: use them whenever they work + res.tauFmt = ok16 ? 'f16' : 'f32' + res.anchorOK.f32 = !!(ok32 && mm && t32.minmax) + res.anchorOK.f16 = !!(ok16 && mm && t16.minmax && t16.clear) + res.mrtOK = !!(db && ((res.tauFmt === 'f16' ? t16 : t32).mrt)) + res.ok = true + return res +} + +// Optional per-pass GPU timers for measurements (test hook timerLog). +function oitTimerEnd(gl) { + var log = OIT_HOOKS.timerLog + if(!log || !log._open) return + log._open.ext.endQueryEXT(log._open.ext.TIME_ELAPSED_EXT) + log.push(log._open) + log._open = null +} + +function oitTimerBegin(gl, label) { + var log = OIT_HOOKS.timerLog + if(!log) return + var ext = gl.getExtension('EXT_disjoint_timer_query') + if(!ext) return + oitTimerEnd(gl) + var q = ext.createQueryEXT() + ext.beginQueryEXT(ext.TIME_ELAPSED_EXT, q) + log._open = {label: label, q: q, ext: ext} +} + +function oitBytesPerPixel(fmt) { + return fmt === 'f32' ? 16 : 8 +} + +function oitFreeTargets(gl, T) { + if(!T) return + var i + if(T.anchorFbo) gl.deleteFramebuffer(T.anchorFbo) + if(T.anchorTex) gl.deleteTexture(T.anchorTex) + for(i = 0; i < T.tauFbo.length; ++i) gl.deleteFramebuffer(T.tauFbo[i]) + for(i = 0; i < T.tauTex.length; ++i) gl.deleteTexture(T.tauTex[i]) + gl.deleteFramebuffer(T.accFbo) + if(!T.accShared) gl.deleteTexture(T.accTex) + if(T.depthRB) gl.deleteRenderbuffer(T.depthRB) +} + +// Allocates the render targets for one configuration; throws on failure. +function oitAllocTargets(gl, caps, cfg, w, h, accum) { + var T = {accShared: false, w: w, h: h, reusedBytes: 0, anchorFbo: null, anchorTex: null, tauFbo: [], tauTex: [], accFbo: null, accTex: null, depthRB: null, bytes: 0} + var nT = cfg.K / 4 + var db = cfg.db + var typeOf = function(f) { return f === 'f32' ? caps.fType : caps.hType } + try { + if(OIT_HOOKS.failAlloc) throw new Error('forced allocation failure (test hook)') + while(gl.getError() !== gl.NO_ERROR) { /* flush */ } + // memory diet: share the depth buffer (and the float colour buffer) of the legacy accumulation FBO, + // which exists at full size anyway. Its depth is 16 bit, as in today's pass (only used for occlusion). + var sharedDepth = !!(cfg.reuse && accum && (accum.depth || accum._depth_rb)) + var sharedColour = !!(sharedDepth && accum._colorType === gl.FLOAT && cfg.accFmt === 'f32' && accum.color[0]) + if(sharedDepth) accum.shape = [w, h] + var attachDepth + if(sharedDepth) { + attachDepth = function() { + if(accum.depth) gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, accum.depth.handle, 0) + else gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, accum._depth_rb) + } + T.reusedBytes += w * h * 2 + (sharedColour ? w * h * 16 : 0) + } else { + T.depthRB = gl.createRenderbuffer() + gl.bindRenderbuffer(gl.RENDERBUFFER, T.depthRB) + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, w, h) + attachDepth = function() { + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, T.depthRB) + } + T.bytes += w * h * 4 + } + var check = function(what) { + if(gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) throw new Error('incomplete ' + what) + } + if(cfg.anchored) { + T.anchorTex = oitMakeTex(gl, w, h, typeOf(cfg.anchorFmt)) + T.anchorFbo = gl.createFramebuffer() + gl.bindFramebuffer(gl.FRAMEBUFFER, T.anchorFbo) + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, T.anchorTex, 0) + attachDepth() + check('anchor') + T.bytes += w * h * oitBytesPerPixel(cfg.anchorFmt) + } + for(var t = 0; t < nT; ++t) { + T.tauTex.push(oitMakeTex(gl, w, h, typeOf(cfg.tauFmt))) + T.bytes += w * h * oitBytesPerPixel(cfg.tauFmt) + } + if(cfg.mrt) { + var f = gl.createFramebuffer() + T.tauFbo.push(f) + gl.bindFramebuffer(gl.FRAMEBUFFER, f) + for(t = 0; t < nT; ++t) { + gl.framebufferTexture2D(gl.FRAMEBUFFER, db.COLOR_ATTACHMENT0_WEBGL + t, gl.TEXTURE_2D, T.tauTex[t], 0) + } + attachDepth() + check('tau (mrt)') + } else { + for(t = 0; t < nT; ++t) { + var f2 = gl.createFramebuffer() + T.tauFbo.push(f2) + gl.bindFramebuffer(gl.FRAMEBUFFER, f2) + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, T.tauTex[t], 0) + attachDepth() + check('tau') + } + } + if(sharedColour) { + T.accTex = accum.color[0].handle + T.accShared = true + } else { + T.accTex = oitMakeTex(gl, w, h, typeOf(cfg.accFmt)) + T.bytes += w * h * oitBytesPerPixel(cfg.accFmt) + } + T.accFbo = gl.createFramebuffer() + gl.bindFramebuffer(gl.FRAMEBUFFER, T.accFbo) + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, T.accTex, 0) + attachDepth() + check('accumulation') + if(sharedDepth) { + // the accumulation FBO may reallocate its attachments: re-attach when the handles change + var handles = function() { return [accum.depth ? accum.depth.handle : accum._depth_rb, accum.color[0].handle] } + var seen = handles() + T.resync = function() { + accum.shape = [w, h] + var now = handles() + if(now[0] === seen[0] && now[1] === seen[1]) return + seen = now + var fbos = T.tauFbo.concat([T.accFbo]) + if(T.anchorFbo) fbos.push(T.anchorFbo) + for(var i = 0; i < fbos.length; ++i) { + gl.bindFramebuffer(gl.FRAMEBUFFER, fbos[i]) + attachDepth() + } + if(sharedColour) { + T.accTex = now[1] + gl.bindFramebuffer(gl.FRAMEBUFFER, T.accFbo) + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, now[1], 0) + } + } + } + if(gl.getError() !== gl.NO_ERROR) throw new Error('gl error while allocating') + } catch(e) { + oitFreeTargets(gl, T) + gl.bindFramebuffer(gl.FRAMEBUFFER, null) + gl.bindRenderbuffer(gl.RENDERBUFFER, null) + gl.bindTexture(gl.TEXTURE_2D, null) + throw e + } + gl.bindFramebuffer(gl.FRAMEBUFFER, null) + gl.bindRenderbuffer(gl.RENDERBUFFER, null) + gl.bindTexture(gl.TEXTURE_2D, null) + return T +} + +function oitCompositeSrc(K) { + var s = 'precision highp float;\nuniform sampler2D oitAcc;\nuniform vec2 oitInvSize;\n' + var i, nT = K / 4 + for(i = 0; i < nT; ++i) s += 'uniform sampler2D oitTau' + i + ';\n' + s += 'void main() {\n vec2 uv = gl_FragCoord.xy * oitInvSize;\n float S = 0.0;\n' + for(i = 0; i < nT; ++i) { + s += ' vec4 t' + i + ' = texture2D(oitTau' + i + ', uv);\n S += t' + i + '.x + t' + i + '.y + t' + i + '.z + t' + i + '.w;\n' + } + s += ' if(S <= 0.0) discard;\n float A = 1.0 - exp(-S);\n vec4 acc = texture2D(oitAcc, uv);\n' + s += ' gl_FragColor = vec4(acc.rgb / max(acc.a, 1e-30) * A, A);\n}\n' + return s +} + +// Depth (distance along the view direction) range of the transparent data's bounding boxes. +function oitDepthExtent(objs, cp, sceneBounds) { + var m = cp.model, v = cp.view + var mn = Infinity, mx = -Infinity + for(var i = 0; i < objs.length; ++i) { + var b = objs[i].bounds + if(!b) continue + var lo = [0, 0, 0], hi = [0, 0, 0] + var useScene = objs[i].projectHasAlpha + for(var j = 0; j < 3; ++j) { + lo[j] = useScene ? sceneBounds[0][j] : Math.max(b[0][j], sceneBounds[0][j]) + hi[j] = useScene ? sceneBounds[1][j] : Math.min(b[1][j], sceneBounds[1][j]) + } + if(lo[0] > hi[0] || lo[1] > hi[1] || lo[2] > hi[2]) continue + for(var c = 0; c < 8; ++c) { + var x = (c & 1) ? hi[0] : lo[0] + var y = (c & 2) ? hi[1] : lo[1] + var z = (c & 4) ? hi[2] : lo[2] + var wx = m[0] * x + m[4] * y + m[8] * z + m[12] + var wy = m[1] * x + m[5] * y + m[9] * z + m[13] + var wz = m[2] * x + m[6] * y + m[10] * z + m[14] + var ww = m[3] * x + m[7] * y + m[11] * z + m[15] + var d = -(v[2] * wx + v[6] * wy + v[10] * wz + v[14] * ww) + if(d < mn) mn = d + if(d > mx) mx = d + } + } + if(!(mn <= mx)) { mn = 0; mx = 1 } + var range = Math.max(mx - mn, 1e-6) + return {min: mn, inv: 1 / range} +} + +module.exports = { + OIT_VARIANTS: OIT_VARIANTS, + loadHooks: oitLoadHooks, + hooks: function() { return OIT_HOOKS }, + ext: oitExt, + probe: oitProbe, + probeCache: oitProbeCache, + freeTargets: oitFreeTargets, + allocTargets: oitAllocTargets, + compositeSrc: oitCompositeSrc, + depthExtent: oitDepthExtent, + timerBegin: oitTimerBegin, + timerEnd: oitTimerEnd, + VERT: OIT_VERT, + createGLShader: createGLShader +} + + /***/ }, /***/ 799 @@ -18700,6 +19182,7 @@ var mouseChange = __webpack_require__(351) var perspective = __webpack_require__(4772) var ortho = __webpack_require__(4040) var createShader = __webpack_require__(799) +var oit = __webpack_require__(2971) var isMobile = __webpack_require__(2431)({ tablet: true, featureDetect: true }) module.exports = { @@ -18751,6 +19234,7 @@ function defaultBool(x) { } function createScene(options) { + oit.loadHooks() options = options || {} options.camera = options.camera || {} @@ -18881,6 +19365,24 @@ function createScene(options) { mouseListener: null, _stopped: false, + // The pick pass. 'lazy': drawn when a pointer event queries it, or pickIdleDelay ms after the last + // frame that changed it (0: never ahead of the query). 'eager': drawn in every frame that changed it (upstream). + pickMode: options.pickMode || 'lazy', + pickIdleDelay: options.pickIdleDelay === undefined ? 120 : options.pickIdleDelay, + // Query the pick buffers only when the main button goes down (hover is off): pointer moves draw nothing + pickOnPress: false, + pickStats: {draws: 0}, + + // Level of detail while the camera moves. lod = {minpoints, budget, maxstride, settle} (or null): + // with at least minpoints thinnable points in the scene (objects with lodPoints()), a frame in which + // the view changed draws every k-th point of every such object (k: the smallest power of two, at + // least 2 and at most maxstride, that brings them within budget) and no pick pass, and the first + // frame settle ms after the view last changed draws them all. + // lodState = {state: 'off', 'preview' or 'full', stride, shown, total}; onlod(state and reason) on a change. + lod: options.lod || null, + lodState: {state: 'off', stride: 0, shown: 0, total: 0}, + onlod: options.onlod || null, + getAspectratio: function() { return { x: this.aspect[0], @@ -18982,6 +19484,7 @@ function createScene(options) { } //Create new pick buffer var nbuffer = createSelect(gl, viewShape) + pickDrawn = false pickBufferIds[i] = numPick pickBuffers.push(nbuffer) pickBufferCount.push(pickCount) @@ -19013,6 +19516,7 @@ function createScene(options) { pickBufferIds.push(-1) dirty = true pickDirty = true + pickNew = true reallocPickIds() } @@ -19028,6 +19532,7 @@ function createScene(options) { pickBufferIds.pop() dirty = true pickDirty = true + pickNew = true reallocPickIds() } @@ -19037,6 +19542,14 @@ function createScene(options) { } scene._stopped = true + if(pickTimer) { + clearTimeout(pickTimer) + pickTimer = null + } + if(pickWait) { + clearTimeout(pickWait) + pickWait = null + } window.removeEventListener('resize', resizeListener) canvas.removeEventListener('webglcontextlost', checkContextLoss) @@ -19054,6 +19567,8 @@ function createScene(options) { } //Clean up buffers + oitRelease() + if(oitState.composite) oitState.composite.shader.dispose() accumBuffer.dispose() for(var i=0; i selection.distance) { @@ -19129,17 +19650,27 @@ function createScene(options) { } } + // A hover that changes nothing in the picture needs no frame: the axis spikes are off and the + // hovered cloud is not drawn larger (highlightScale 1, as plotly sets it). The render callback alone + // then gives the hover label and events, as it does from the frame. + var e = spikes.enabled + var still = !e[0] && !e[1] && !e[2] && !!scene.onrender && pickFrameSeen && + (!prevObj || prevObj.highlightScale === 1) && + (!selection.object || selection.object.highlightScale === 1) if(prevObj && prevObj !== selection.object) { if(prevObj.highlight) { prevObj.highlight(null) } - dirty = true + dirty = dirty || !still } if(selection.object) { if(selection.object.highlight) { selection.object.highlight(selection.data) } - dirty = true + dirty = dirty || !still + } + if(still && !dirty && (prevObj || selection.object)) { + scene.onrender() } change = change || (selection.object !== prevObj) @@ -19170,12 +19701,89 @@ function createScene(options) { canvas.addEventListener('webglcontextlost', checkContextLoss) + var pickTimer = null + var pickFrameSeen = false + var pickEmpty = false + // False until a pick pass has drawn every pick buffer. A new buffer holds memory from the pool, not a picture, + // so no query reads the buffers before that. + var pickDrawn = false + // The pick pass of a frame was read back 1 ms after the frame, so a pointer event right after a frame saw the + // picture of the frame before. A pass on demand waits as long: pickWait is set for 1 ms after a frame that changed it. + var pickWait = null + // True from a change of the objects (add, remove) to the next frame. Only that frame starts the wait: after a frame + // that moves the camera, the pass on demand answers at once, where the frame pass gave the picture of the frame before. + var pickNew = true + + // True if some object that is drawn into a pick buffer can be picked + function anyPickable() { + for(var i=0; i= 0 && objects[i].drawPick && !objects[i].noPick) { + return true + } + } + return false + } + + // Draw the pick buffers and read them back now, if they are out of date. + // Not while a change waits for its frame (an object added, removed or updated, a new size): a pass on demand + // shows what the last frame drew, as the pass in the frame did. That frame starts the idle timer again. + function ensurePick() { + if(pickTimer) { + clearTimeout(pickTimer) + pickTimer = null + } + if(!pickDirty || !pickFrameSeen || dirty || pickWait || lodOn || scene._stopped || scene.contextLost) { + return + } + pickDirty = false + renderPick() + // the pick pass draws at pixel ratio 1; objects read their own ratio when a query follows (mesh pick) + for(var i=0; i 0) || scene.pickOnPress) { + return + } + pickTimer = setTimeout(function() { + pickTimer = null + if(scene._prevButtons) { + // nothing is queried while a button is held: look again later + schedulePick() + } else { + ensurePick() + } + }, scene.pickIdleDelay) + } + //Render the scene for mouse picking function renderPick() { if(checkContextLoss()) { return } + // Nothing can be picked (every trace has hoverinfo 'skip'): no pass, and no query reads the buffers + pickEmpty = !anyPickable() + if(pickEmpty) { + return + } + + scene.pickStats.draws++ + gl.colorMask(true, true, true, true) gl.depthMask(true) gl.disable(gl.BLEND) @@ -19200,6 +19808,7 @@ function createScene(options) { } buf.end() } + pickDrawn = true } var nBounds = [ @@ -19208,6 +19817,370 @@ function createScene(options) { var prevBounds = [nBounds[0].slice(), nBounds[1].slice()] + // ---- order independent transparency: state, status and rendering (see oitProbe and friends above) ---- + var oitState = { + mode: 'off', // requested: 'off' | 'auto' + cfg: null, // chosen configuration, or null (legacy) + reason: null, + targets: null, + composite: null, + statusKey: '' + } + + var OIT_NONE = {mode: 'none', variant: null, tier: 4, reason: 'no-transparent', format: null, mrt: false, nodes: 0, passes: 1, mixed: false, targetBytes: 0} + scene.oit = OIT_NONE + scene.onoitstatus = null + + scene.getOITStatus = function() { + return scene.oit + } + + function oitSetStatus(st) { + var key = JSON.stringify(st) + scene.oit = st + if(key !== oitState.statusKey) { + oitState.statusKey = key + if(typeof scene.onoitstatus === 'function') { + try { scene.onoitstatus(st) } catch(e) { /* a listener must not break rendering */ } + } + } + } + + function oitRelease() { + if(oitState.targets) { + if(!scene.contextLost) oit.freeTargets(gl, oitState.targets) + oitState.targets = null + } + } + + // mode: 'off' | 'auto' + scene.setOIT = function(mode) { + oit.loadHooks() + oitRelease() + oitState.cfg = null + oitState.reason = null + oitState.mode = mode || 'off' + oitState.failedSize = null + dirty = true + } + + // forget the cached probe and configuration (used after changing the test hooks) + scene.resetOIT = function() { + oit.loadHooks() + oitRelease() + for(var i = oit.probeCache.length - 1; i >= 0; --i) { + if(oit.probeCache[i].gl === gl) oit.probeCache.splice(i, 1) + } + oitState.cfg = null + oitState.failedSize = null + dirty = true + } + + // Decide the configuration for the requested mode and the probed capabilities. + function oitConfigure() { + var caps = oit.probe(gl) + if(!caps.ok) return {cfg: null, reason: caps.reason} + var name = oit.hooks().variant || 'D16' + var v = oit.OIT_VARIANTS[name] || oit.OIT_VARIANTS.D16 + var cfg = {variant: name, K: v.K, anchored: v.anchored, accFmt: caps.accFmt, tauFmt: caps.tauFmt, caps: caps, notes: []} + cfg.mm = oit.ext(gl, 'EXT_blend_minmax') + cfg.db = oit.ext(gl, 'WEBGL_draw_buffers') + // anchor in 16 bit floats unless asked otherwise (memory); test hook anchorF32 + cfg.anchorFmt = oit.hooks().anchorF32 ? cfg.accFmt : (caps.anchorOK.f16 ? 'f16' : cfg.accFmt) + cfg.reuse = !oit.hooks().noReuse + if(cfg.anchored && !caps.anchorOK[cfg.anchorFmt]) { + cfg.anchored = false + cfg.notes.push('no-minmax-anchor') + cfg.variant = 'D2-' + cfg.K + } + cfg.mrt = !!(caps.mrtOK && cfg.db && caps.maxDraw >= cfg.K / 4) + cfg.tier = !cfg.mrt ? 3 : (cfg.accFmt === 'f32' ? 1 : 2) + var nT = cfg.K / 4 + cfg.passes = (cfg.anchored ? 1 : 0) + (cfg.mrt ? 1 : nT) + 1 + return {cfg: cfg, reason: cfg.notes.length ? cfg.notes.join(',') : null} + } + + var OIT_LEGACY = function(reason, mixed) { + return {mode: 'legacy', variant: null, tier: 4, reason: reason, format: null, mrt: false, nodes: 0, passes: 1, mixed: !!mixed, targetBytes: 0} + } + + // Returns true if this frame's transparent OIT objects should use the OIT passes. + function oitPrepare(width, height) { + if(oitState.mode === 'off') { + oitSetStatus(OIT_LEGACY('off')) + return false + } + if(!oitState.cfg && !oitState.reason) { + var c = oitConfigure() + oitState.cfg = c.cfg + oitState.reason = c.reason + // the probe leaves GL state behind; put the opaque pass state back + oitRestoreState(width, height) + } + var cfg = oitState.cfg + if(!cfg) { + oitSetStatus(OIT_LEGACY(oitState.reason)) + return false + } + var T = oitState.targets + var sizeKey = width + 'x' + height + if(!T && oitState.failedSize === sizeKey) { + oitSetStatus(OIT_LEGACY('alloc-failed')) + return false + } + if(!T || T.w !== width || T.h !== height) { + oitRelease() + try { + oitState.targets = oit.allocTargets(gl, cfg.caps, cfg, width, height, accumBuffer) + } catch(e) { + // no MRT, then give up for this size + if(cfg.mrt) { + cfg.mrt = false + cfg.tier = 3 + cfg.passes = (cfg.anchored ? 1 : 0) + cfg.K / 4 + 1 + cfg.notes.push('mrt-alloc-failed') + try { + oitState.targets = oit.allocTargets(gl, cfg.caps, cfg, width, height, accumBuffer) + } catch(e2) { + oitState.targets = null + } + } + if(!oitState.targets) { + oitRestoreState(width, height) + oitState.failedSize = sizeKey + oitSetStatus(OIT_LEGACY('alloc-failed')) + return false + } + } + oitRestoreState(width, height) + if(cfg.accFmt && !cfg.formatStr) { + cfg.formatStr = 'acc=' + cfg.accFmt + ',tau=' + cfg.tauFmt + (cfg.anchored ? ',anchor=' + cfg.anchorFmt : '') + (cfg.reuse ? ',shared=accumBuffer' : '') + } + } + oitSetStatus({ + mode: cfg.anchored ? 'D' : 'D2', + variant: cfg.variant, + tier: cfg.tier, + reason: cfg.notes.length ? cfg.notes.join(',') : null, + format: cfg.formatStr, + mrt: cfg.mrt, + nodes: cfg.K, + passes: cfg.passes, + mixed: !!oitState.mixed, + targetBytes: oitState.targets.bytes, + reusedBytes: oitState.targets.reusedBytes + }) + return true + } + + function oitRestoreState(width, height) { + gl.bindFramebuffer(gl.FRAMEBUFFER, null) + gl.viewport(0, 0, width, height) + gl.disable(gl.BLEND) + gl.blendEquation(gl.FUNC_ADD) + gl.colorMask(true, true, true, true) + gl.depthMask(true) + gl.enable(gl.DEPTH_TEST) + gl.depthFunc(gl.LEQUAL) + gl.disable(gl.CULL_FACE) + gl.activeTexture(gl.TEXTURE0) + gl.bindTexture(gl.TEXTURE_2D, null) + } + + function oitDrawObjs(objs, ctx) { + for(var i = 0; i < objs.length; ++i) { + objs[i].drawOIT(cameraParams, ctx) + } + } + + function renderOIT(objs, width, height) { + var cfg = oitState.cfg + var T = oitState.targets + var db = cfg.db + var nT = cfg.K / 4 + var t + var ext = oit.depthExtent(objs, cameraParams, scene.bounds) + var ctx = { + pass: 0, K: cfg.K, anchored: cfg.anchored, mrt: cfg.mrt, group: 0, + map: [ext.min, ext.inv], invSize: [1 / width, 1 / height], + anchorUnit: 0, tauUnit: 1 + } + var depthFbo = cfg.anchored ? T.anchorFbo : T.tauFbo[0] + if(T.resync) T.resync() + + gl.viewport(0, 0, width, height) + + oit.timerBegin(gl, 'depth') + //1. depth of the opaque objects (as the legacy pre-pass does), into the shared depth buffer + gl.bindFramebuffer(gl.FRAMEBUFFER, depthFbo) + gl.enable(gl.DEPTH_TEST) + gl.disable(gl.BLEND) + gl.colorMask(false, false, false, false) + gl.depthMask(true) + gl.depthFunc(gl.LESS) + gl.clear(gl.DEPTH_BUFFER_BIT) + if(axes.enable && axes.isTransparent()) { + axes.drawTransparent(cameraParams) + } + for(var i = 0; i < numObjsNow(); ++i) { + var o = objects[i] + if(o.isOpaque && o.isOpaque() && !o.alwaysOnTop) o.draw(cameraParams) + } + + gl.colorMask(true, true, true, true) + gl.depthMask(false) + gl.enable(gl.BLEND) + + //2. anchor: nearest transparent depth per pixel (MIN blending) + oit.timerBegin(gl, 'anchor') + if(cfg.anchored) { + gl.bindFramebuffer(gl.FRAMEBUFFER, T.anchorFbo) + gl.clearColor(1000, 1000, 1000, 1000) + gl.clear(gl.COLOR_BUFFER_BIT) + gl.blendEquation(cfg.mm.MIN_EXT) + gl.blendFunc(gl.ONE, gl.ONE) + ctx.pass = 0 + oitDrawObjs(objs, ctx) + gl.blendEquation(gl.FUNC_ADD) + } + + //3. optical depth tau = -ln(1-alpha), tent-splatted into K nodes + oit.timerBegin(gl, 'tau') + gl.blendFunc(gl.ONE, gl.ONE) + gl.clearColor(0, 0, 0, 0) + if(cfg.anchored) { + gl.activeTexture(gl.TEXTURE0) + gl.bindTexture(gl.TEXTURE_2D, T.anchorTex) + } + ctx.pass = 1 + if(cfg.mrt) { + var list = [] + for(t = 0; t < nT; ++t) list.push(db.COLOR_ATTACHMENT0_WEBGL + t) + gl.bindFramebuffer(gl.FRAMEBUFFER, T.tauFbo[0]) + db.drawBuffersWEBGL(list) + gl.clear(gl.COLOR_BUFFER_BIT) + oitDrawObjs(objs, ctx) + } else { + for(t = 0; t < nT; ++t) { + gl.bindFramebuffer(gl.FRAMEBUFFER, T.tauFbo[t]) + gl.clear(gl.COLOR_BUFFER_BIT) + ctx.group = t + oitDrawObjs(objs, ctx) + } + ctx.group = 0 + } + + //4. colour weighted by the transmittance in front of each fragment, accumulated + oit.timerBegin(gl, 'colour') + for(t = 0; t < nT; ++t) { + gl.activeTexture(gl.TEXTURE1 + t) + gl.bindTexture(gl.TEXTURE_2D, T.tauTex[t]) + } + gl.bindFramebuffer(gl.FRAMEBUFFER, T.accFbo) + gl.clear(gl.COLOR_BUFFER_BIT) + ctx.pass = 2 + oitDrawObjs(objs, ctx) + + //5. composite over the screen: normalise, apply the exact coverage 1 - exp(-sum tau) + oit.timerBegin(gl, 'composite') + gl.bindFramebuffer(gl.FRAMEBUFFER, null) + gl.disable(gl.DEPTH_TEST) + gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA) + if(!oitState.composite || oitState.composite.K !== cfg.K) { + if(oitState.composite) oitState.composite.shader.dispose() + oitState.composite = { + K: cfg.K, + shader: oit.createGLShader(gl, oit.VERT, oit.compositeSrc(cfg.K), null, [{name: 'position', type: 'vec2'}]) + } + } + var cs = oitState.composite.shader + cs.bind() + gl.activeTexture(gl.TEXTURE0) + gl.bindTexture(gl.TEXTURE_2D, T.accTex) + cs.uniforms.oitAcc = 0 + cs.uniforms.oitInvSize = ctx.invSize + for(t = 0; t < nT; ++t) cs.uniforms['oitTau' + t] = 1 + t + drawTriangle(gl) + + for(t = nT; t >= 0; --t) { + gl.activeTexture(gl.TEXTURE0 + t) + gl.bindTexture(gl.TEXTURE_2D, null) + } + gl.activeTexture(gl.TEXTURE0) + gl.disable(gl.BLEND) + oit.timerEnd(gl) + } + + function numObjsNow() { + return objects.length + } + + // Level of detail while the camera moves (scene.lod) + var lodMoved = 0 // when the camera last moved in a preview, ms + var lodOn = false // the frames are previews + var lodView = new Float64Array(16) // the view matrix of the last frame + var lodForce = false // lodSettle: this frame draws every disc + + function lodFrame(cameraMoved) { + var o = scene.lod + var n = 0 + var k = 0 + var i + // the camera can report a move after it has reached its place: only a view that changed is a move here. + // (After a plot the camera glides to its place for about 0.4 s: those frames are previews too.) + var view = scene.camera.matrix + var moved = false + for(i=0; i<16; ++i) { + if(lodView[i] !== view[i]) { + moved = true + lodView[i] = view[i] + } + } + cameraMoved = cameraMoved && moved + if(o && o.minpoints > 0) { + for(i=0; i= o.minpoints) { + k = 2 + while(k < o.maxstride && n / k > o.budget) k *= 2 + } + } + var now = Date.now() + if(k && cameraMoved) lodMoved = now + var preview = k > 0 && !lodForce && lodMoved > 0 && now - lodMoved < o.settle + lodForce = false + if(!preview) lodMoved = 0 + var toggled = preview !== lodOn + lodOn = preview + // the frame that draws every disc again + if(toggled && !preview) dirty = true + if(preview || toggled) { + for(i=0; i 0) { + oitUse = oitPrepare(width, height) + } else { + oitSetStatus(OIT_LEGACY(oitState.mode === 'off' ? 'off' : 'no-oit-objects')) + } + + if(!oitUse || legacyObjs || axes.isTransparent()) { //Render transparent pass accumBuffer.shape = viewShape accumBuffer.bind() @@ -19412,7 +20424,7 @@ function createScene(options) { } for(var i=0; i 0 && o.anchored) s += 'uniform sampler2D oitAnchor;\n' + if(o.pass === 2) { + for(i = 0; i < T; ++i) s += 'uniform sampler2D oitTau' + i + ';\n' + } + s += 'varying vec4 interpColor;\n' + (o.disc ? '' : 'varying vec3 dataCoordinate;\n') + 'varying float oitZ;\n' + + if(o.pass > 0) { + // node coordinate in [0, K-1]: log-plus-linear warp of the distance to the anchor (D), + // or linear in the depth extent of the transparent data (D2) + s += 'float oitX(float f) {\n' + if(o.anchored) { + var Klog = K === 8 ? 4 : 8 + var delta = K === 8 ? 1 / 1024 : 1 / 8192 + s += ' float u = max(f - texture2D(oitAnchor, gl_FragCoord.xy * oitInvSize).r, 0.0);\n' + s += ' float x = ' + f1(Klog) + ' * log(1.0 + u * ' + f1(1 / delta) + ') / ' + f1(Math.log(1 + 1 / delta)) + ' + ' + f1(K - 1 - Klog) + ' * u;\n' + } else { + s += ' float x = clamp(f, 0.0, 1.0) * ' + f1(K - 1) + ';\n' + } + s += ' return clamp(x, 0.0, ' + f1(K - 1) + ');\n}\n' + } + if(o.pass === 2) { + s += 'float oitPhi(float N) {\n return N < 0.01 ? 1.0 - N * (0.5 - N * (0.16666667 - N * 0.041666668)) : (1.0 - exp(-N)) / N;\n}\n' + } + + s += 'void main() {\n' + if(o.disc) { + // the coverage of the transparent disc pass (smooth 1 px edge), the same in all three passes + s += ' float d = length((gl_PointCoord - 0.5) * 2.0 * vHalf);\n' + s += ' float cf = clamp(vB - d + 0.5, 0.0, 1.0) * clamp(d - vA + 0.5, 0.0, 1.0);\n' + s += ' if (interpColor.a * opacity == 0.) cf = 0.;\n' + s += ' vec3 col = interpColor.rgb;\n float araw = interpColor.a * opacity * cf;\n' + s += '#ifdef OUTLINE\n' + s += ' float e = min(abs(d - vB), vA < 0.0 ? 1e6 : abs(d - vA));\n' + s += ' float cl = clamp(lineHalf - e + 0.5, 0.0, 1.0);\n' + s += ' float wf = cf * (1.0 - cl);\n' + s += ' araw = (interpColor.a * wf + interpLine.a * cl) * opacity;\n' + s += ' col = (interpColor.rgb * wf + interpLine.rgb * cl) / max(wf + cl, 1e-6);\n' + s += '#endif\n' + s += ' if (araw <= 0.0) discard;\n' + } else { + s += ' if (outOfRange(fragClipBounds[0], fragClipBounds[1], dataCoordinate) || interpColor.a * opacity == 0.) discard;\n' + } + s += ' float f = (-oitZ - oitMap.x) * oitMap.y;\n' + if(o.pass === 0) { + // the faint edge fragments of a disc must not set the anchor depth + if(o.disc) s += ' if (araw < 0.5 * interpColor.a * opacity) discard;\n' + s += ' gl_FragColor = vec4(f, f, f, f);\n}\n' + return s + } + s += ' float a = min(' + araw + ', 0.99609375);\n' + s += ' float tau = -log(1.0 - a);\n' + s += ' float x = oitX(f);\n' + s += ' float k = min(floor(x), ' + f1(K - 2) + ');\n' + s += ' float fr = x - k;\n' + if(o.pass === 1) { + var tent = function(nv) { + return 'tau * ((1.0 - fr) * (1.0 - step(0.5, abs(' + nv + ' - k))) + fr * (1.0 - step(0.5, abs(' + nv + ' - k - 1.0))))' + } + if(o.mrt) { + for(i = 0; i < T; ++i) { + s += ' gl_FragData[' + i + '] = ' + tent('(vec4(0.0, 1.0, 2.0, 3.0) + ' + f1(4 * i) + ')') + ';\n' + } + } else { + s += ' gl_FragColor = ' + tent('(vec4(0.0, 1.0, 2.0, 3.0) + 4.0 * oitGroup)') + ';\n' + } + s += '}\n' + return s + } + // colour pass: telescoping weights from the optical-depth nodes + s += ' vec2 uv = gl_FragCoord.xy * oitInvSize;\n' + s += ' float Tb = 1.0, Wk = 0.0, Wk1 = 0.0, N, W;\n' + for(i = 0; i < T; ++i) { + s += ' vec4 t' + i + ' = texture2D(oitTau' + i + ', uv);\n' + for(c = 0; c < 4; ++c) { + j = 4 * i + c + s += ' N = t' + i + '.' + 'xyzw'.charAt(c) + '; W = Tb * oitPhi(N);\n' + s += ' if(abs(k - ' + f1(j) + ') < 0.5) Wk = W;\n' + s += ' if(abs(k + 1.0 - ' + f1(j) + ') < 0.5) Wk1 = W;\n' + s += ' Tb *= exp(-N);\n' + } + } + s += ' float w = tau * ((1.0 - fr) * Wk + fr * Wk1);\n' + s += ' gl_FragColor = vec4(' + col + ' * w, w);\n}\n' + return s +} + +var oitShaderCache = [] + +// the OIT shaders of one WebGL context +function oitCacheEntry(gl) { + var entry = null + for(var i = oitShaderCache.length - 1; i >= 0; --i) { + if(oitShaderCache[i].gl === gl) entry = oitShaderCache[i] + else if(oitShaderCache[i].gl.isContextLost()) oitShaderCache.splice(i, 1) + } + if(!entry) { + entry = {gl: gl, map: {}} + oitShaderCache.push(entry) + } + return entry +} + +// o: {pass: 0|1|2, K, anchored, mrt} +function getOITShaders(gl, o) { + var entry = oitCacheEntry(gl) + var key = o.pass === 0 ? '0' : [o.pass, o.K, o.anchored ? 1 : 0, o.mrt ? 1 : 0].join('-') + if(!entry.map[key]) { + var frag = oitFragSrc(o) + var mk = function(vert) { + return createShader(gl, {vertex: vert, fragment: frag, attributes: ATTRIBUTES}) + } + entry.map[key] = { + perspective: mk(oitPatchVertex(perspectiveVertSrc, 'dataCoordinate = position;', 'viewPosition.z')), + ortho: mk(oitPatchVertex(orthographicVertSrc, 'dataCoordinate = position;', 'viewPosition.z')), + project: mk(oitPatchVertex(projectionVertSrc, 'dataCoordinate = dataPosition;', '(view * (model * vec4(dataPosition, 1))).z')) + } + } + return entry.map[key] +} + + +exports.getOITShaders = getOITShaders +exports.oitFragSrc = oitFragSrc +exports.oitCacheEntry = oitCacheEntry + /***/ }, @@ -19794,6 +20995,7 @@ var createVAO = __webpack_require__(8116) var pool = __webpack_require__(1888) var mat4mult = __webpack_require__(6760) var shaders = __webpack_require__(1283) +var createShaderWrapper = __webpack_require__(9405) var getGlyph = __webpack_require__(9366) var getSimpleString = __webpack_require__(5964) @@ -19874,6 +21076,19 @@ function PointCloud( this.vertexCount = 0 this.lineVertexCount = 0 + // disc markers (see _updateDisc): 'glyph' keeps the vectorised glyph meshes + this.markerRender = 'glyph' + this.discActive = false + this.discBlocker = '' + this.discHardEdge = false + this.discSet = null + this.discCur = null + this.lodStride = 0 // > 1 draws every lodStride-th disc (a preview; never the pick pass) + this.discOutline = false + this.lineColorBuffer = null + this.sizeBuffer = null + this.pointSizeRange = null + this.opacity = 1 this.hasAlpha = false @@ -19980,7 +21195,7 @@ function getClipBounds(bounds) { return result } -function drawProject(shader, points, camera, pixelRatio) { +function drawProject(shader, points, camera, pixelRatio, oit) { var axesProject = points.axesProject var gl = points.gl @@ -20002,6 +21217,7 @@ function drawProject(shader, points, camera, pixelRatio) { VIEW_SHAPE[1] = 2.0/gl.drawingBufferHeight shader.bind() + if(oit) setOITUniforms(shader, oit) uniforms.view = view uniforms.projection = projection uniforms.screenSize = VIEW_SHAPE @@ -20099,17 +21315,659 @@ var NEG_INFINITY3 = [-1e8, -1e8, -1e8] var POS_INFINITY3 = [1e8, 1e8, 1e8] var CLIP_GROUP = [NEG_INFINITY3, POS_INFINITY3] -function drawFull(shader, pshader, points, camera, pixelRatio, transparent, forceDraw) { +// --------------------------------------------------------------------------- +// Disc markers: a circle marker drawn as one gl.POINTS vertex (round cutout in the fragment shader) +// instead of a vectorised "●" glyph mesh of 60 to 104 vertices. The disc has the same screen-aligned constant +// pixel size as the glyph. +// '●' circle: filled disc, with an outline ring when marker.line.width is above 0 (lineColor attribute) +// '○' circle-open: hollow ring in the marker colour +// The edge of the disc in the opaque pass is chosen at draw time, see drawDisc. +// --------------------------------------------------------------------------- +var DISC_FILL = '●' +var DISC_OPEN = '○' + +var DISC_OUT_OF_RANGE = [ + 'bool outOfRange(float a, float b, float p) {', + ' return ((p > max(a, b)) || (p < min(a, b)));', + '}', + 'bool outOfRange(vec3 a, vec3 b, vec3 p) {', + ' return (outOfRange(a.x, b.x, p.x) || outOfRange(a.y, b.y, p.y) || outOfRange(a.z, b.z, p.z));', + '}' +].join('\n') + +function discVert(outline) { + return [ + outline ? '#define OUTLINE' : '', + 'precision highp float;', + DISC_OUT_OF_RANGE, + 'attribute vec3 position;', + 'attribute vec4 color;', + 'attribute float size;', + 'attribute vec4 id;', + '#ifdef OUTLINE', + 'attribute vec4 lineColor;', + 'varying vec4 interpLine;', + '#endif', + 'uniform mat4 model, view, projection;', + 'uniform vec2 screenSize;', + 'uniform vec3 clipBounds[2];', + 'uniform float highlightScale, pixelRatio, unitA, unitB, lineHalf;', + 'uniform float opacity, lodK;', + 'uniform vec2 unitCenter;', + 'uniform vec4 highlightId;', + 'varying vec4 interpColor;', + 'varying vec4 pickId;', + 'varying float vA;', + 'varying float vB;', + 'varying float vHalf;', + 'varying vec2 vDense;', + // A preview draws every lodK-th disc. A translucent disc then stands for lodK discs: its alpha a becomes + // 1 - (1 - a)^lodK, the cover of lodK discs on one pixel. The factor is 1 for a disc of alpha 1 and for a full draw. + 'float lodDense(float alpha) {', + ' float a = alpha * opacity;', + ' if (lodK > 1.0 && a > 0.0 && a < 1.0) {', + ' return (1.0 - pow(1.0 - a, lodK)) / a;', + ' }', + ' return 1.0;', + '}', + 'void main() {', + ' if (outOfRange(clipBounds[0], clipBounds[1], position)) {', + ' gl_Position = vec4(0, 0, 0, 0);', + ' gl_PointSize = 1.0;', + ' vA = -1.0; vB = 0.0; vHalf = 1.0;', + ' vDense = vec2(1.0);', + ' } else {', + ' float scale = pixelRatio;', + ' if (distance(highlightId.bgr, id.bgr) < 0.001) {', + ' scale *= highlightScale;', + ' }', + ' vec4 clipPosition = projection * (view * (model * vec4(position, 1.0)));', + ' clipPosition /= clipPosition.w;', + ' gl_Position = clipPosition + vec4(screenSize * scale * size * vec2(unitCenter.x, -unitCenter.y), 0.0, 0.0);', + ' vB = scale * size * unitB;', + ' vA = unitA < 0.0 ? -1.0 : scale * size * unitA;', + ' vHalf = vB + lineHalf + 1.0;', + ' gl_PointSize = 2.0 * vHalf;', + ' interpColor = color;', + ' vDense = vec2(lodDense(color.a), 1.0);', + ' interpColor.a *= vDense.x;', + ' pickId = id;', + '#ifdef OUTLINE', + ' interpLine = lineColor;', + ' vDense.y = lodDense(lineColor.a);', + ' interpLine.a *= vDense.y;', + '#endif', + ' }', + '}' + ].join('\n') +} + +function discFrag(outline) { + return [ + outline ? '#define OUTLINE' : '', + 'precision highp float;', + 'uniform float opacity, hardEdge, lineHalf, a2c, rim;', + 'varying vec4 interpColor;', + 'varying float vA;', + 'varying float vB;', + 'varying float vHalf;', + 'varying vec2 vDense;', + '#ifdef OUTLINE', + 'varying vec4 interpLine;', + '#endif', + 'void main() {', + ' float d = length((gl_PointCoord - 0.5) * 2.0 * vHalf);', + ' float cf = hardEdge > 0.5 ? step(d, vB) * step(vA, d)', + ' : clamp(vB - d + 0.5, 0.0, 1.0) * clamp(d - vA + 0.5, 0.0, 1.0);', + ' if (interpColor.a * opacity == 0.) cf = 0.;', + // (the vertex shader made the alpha of a thinned translucent disc denser; the color takes the same factor) + ' vec4 c = vec4(interpColor.rgb * vDense.x, interpColor.a) * (opacity * cf);', + '#ifdef OUTLINE', + ' float e = min(abs(d - vB), vA < 0.0 ? 1e6 : abs(d - vA));', // outer edge, plus the inner edge of a ring + ' float cl = hardEdge > 0.5 ? step(e, lineHalf) : clamp(lineHalf - e + 0.5, 0.0, 1.0);', + ' c = c * (1.0 - cl) + vec4(interpLine.rgb * vDense.y, interpLine.a) * (opacity * cl);', + ' if (cf + cl <= 0.0) discard;', + '#else', + ' if (cf <= 0.0) discard;', + '#endif', + ' if (rim > -0.5) {', + ' if (rim < 0.5 && c.a < 0.999) discard;', // pass 0: fully covered pixels only (opaque cores, depth written) + ' if (rim > 0.5 && (c.a >= 0.999 || c.a <= 0.0)) discard;', // pass 1: partial-coverage rim pixels, blended over + ' }', + ' gl_FragColor = a2c > 0.5 ? vec4(c.rgb / max(c.a, 1e-4), c.a) : c;', // pure a2c: full colour, alpha = coverage (alpha channel is masked) + '}' + ].join('\n') +} + +var DISC_PICK_FRAG = [ + 'precision highp float;', + 'uniform float pickGroup, lineHalf;', + 'varying vec4 pickId;', + 'varying float vA;', + 'varying float vB;', + 'varying float vHalf;', + 'void main() {', + ' float d = length((gl_PointCoord - 0.5) * 2.0 * vHalf);', + ' if (d > vB + lineHalf || d < (vA < 0.0 ? vA : vA - lineHalf)) discard;', + ' gl_FragColor = vec4(pickGroup, pickId.bgr);', + '}' +].join('\n') + +function createDiscShader(gl, outline, pick) { + var shader = createShaderWrapper(gl, {vertex: discVert(outline), fragment: pick ? DISC_PICK_FRAG : discFrag(outline)}) + var attr = shader.attributes + attr.position.location = 0 + attr.color.location = 1 + attr.size.location = 2 + attr.id.location = 3 + if(outline && attr.lineColor) attr.lineColor.location = 4 + return shader +} + +// 'fill', 'open', or '' when the symbols are anything else +function discKind(glyphs, n) { + var first + if(isArrayOrTypedArray(glyphs)) { + if(glyphs.length < n || n === 0) return '' + first = glyphs[0] + for(var i = 0; i < n; ++i) if(glyphs[i] !== first) return '' + } else { + first = glyphs + } + return first === DISC_FILL ? 'fill' : first === DISC_OPEN ? 'open' : '' +} + +// Returns '' when the disc path can draw this update, otherwise the reason it cannot +proto._discBlocker = function(options) { + var mode = this.markerRender + if(mode !== 'disc' && mode !== 'auto') return 'markerRender is ' + mode + if(!options.position && !options.positionsKept) return 'no positions' + if(!this.useOrtho) return 'perspective sizing' + for(var i = 0; i < 3; ++i) if(this.axesProject[i]) return 'axes projection' + var angles = options.angle + if(angles && (!isArrayOrTypedArray(angles) || angles.length)) return 'marker angle' + var al = options.alignment + if(al && (al.length !== 2 || al[0] || al[1])) return 'alignment' + var kind = discKind(options.glyph, this._count(options)) + if(!kind) return 'symbol is not circle or circle-open' + return '' +} + +proto._discSetup = function(kind, outline) { + var gl = this.gl + if(!this.sizeBuffer) this.sizeBuffer = createBuffer(gl) + if(outline && !this.lineColorBuffer) this.lineColorBuffer = createBuffer(gl) + var key = outline ? 'outline' : 'plain' + if(!this.discSet) this.discSet = {} + if(!this.discSet[key]) { + var attrs = [ + { buffer: this.pointBuffer, size: 3, type: gl.FLOAT }, + { buffer: this.colorBuffer, size: 4, type: gl.FLOAT }, + { buffer: this.sizeBuffer, size: 1, type: gl.FLOAT }, + { buffer: this.idBuffer, size: 4, type: gl.UNSIGNED_BYTE, normalized: true } + ] + if(outline) attrs.push({ buffer: this.lineColorBuffer, size: 4, type: gl.FLOAT }) + this.discSet[key] = { + shader: createDiscShader(gl, outline, false), + pickShader: createDiscShader(gl, outline, true), + vao: createVAO(gl, attrs), + attrs: attrs, + lod: null + } + } + this.discCur = this.discSet[key] + this.discOutline = outline + // Radii of the glyph, in the units the glyph shaders use (already divided by the pixelRatio the glyph was cached with). + // The disc is centred on the point: the glyph's own centre sits a little off (font bearings, up to ~0.012 * size px) + // and differs between glyph cache entries, so it is not reproduced. + var font = {family: 'normal', style: 'normal', weight: 'normal', variant: 'normal'} + var g = get_glyphData(kind === 'open' ? DISC_OPEN : DISC_FILL, font, this.pixelRatio) + var b = g.bounds + var cx = 0.5 * (b[0][0] + b[1][0]) + var cy = 0.5 * (b[0][1] + b[1][1]) + var lp = g.lines.positions + var rs = [] + var i + if(kind === 'fill') { + var s = 0 + for(i = 0; i < lp.length; ++i) s += Math.hypot(lp[i][0] - cx, lp[i][1] - cy) + this.discUnit = {cx: 0, cy: 0, a: -1, b: s / lp.length} + } else { + // ring: outer and inner polygon radii + var mp = g.mesh.positions + var rmin = Infinity, rmax = -Infinity + for(i = 0; i < mp.length; ++i) { + var r = Math.hypot(mp[i][0] - cx, mp[i][1] - cy) + rs.push(r); rmin = Math.min(rmin, r); rmax = Math.max(rmax, r) + } + var mid = 0.5 * (rmin + rmax), so = 0, no = 0, si = 0, ni = 0 + for(i = 0; i < rs.length; ++i) { + if(rs[i] > mid) { so += rs[i]; no++ } else { si += rs[i]; ni++ } + } + this.discUnit = {cx: 0, cy: 0, a: si / ni, b: so / no} + } +} + +// Whether a sprite of this marker size (device pixels, +2 for the antialiasing margin) fits the driver's point size cap +proto._discSizeFits = function(maxSize) { + var gl = this.gl + var range = gl.getParameter(gl.ALIASED_POINT_SIZE_RANGE) + this.pointSizeRange = [range[0], range[1]] + var maxPx = 2 * (maxSize * this.discUnit.b * this.pixelRatio * Math.max(1, this.highlightScale || 1) + + this._discLineHalf(this.pixelRatio) + 1) + if(maxPx > range[1]) { + this.discBlocker = 'marker size ' + maxPx.toFixed(0) + ' px exceeds point size cap ' + range[1] + return false + } + return true +} + +// Positions given as one flat Float32Array (x, y, z per point) +function isFlatPositions(points) { + return !!points && ArrayBuffer.isView(points) +} +function positionCount(points) { + return isFlatPositions(points) ? Math.floor(points.length / 3) : points.length +} +function unflattenPositions(flat) { + var n = positionCount(flat) + var out = new Array(n) + for(var i = 0; i < n; ++i) out[i] = [flat[3 * i], flat[3 * i + 1], flat[3 * i + 2]] + out.bounds = flat.bounds + return out +} + +// One colour, one size or no pick ids for every point of a trace are +// drawn from constant vertex attributes instead of per-point buffers (16, 4 +// and 4 bytes a point); the values are the same floats the buffers held +proto._discConstAttrs = function(gl) { + var c = this.discConst + if(c && c.color) { + gl.disableVertexAttribArray(1) + gl.vertexAttrib4f(1, c.color[0], c.color[1], c.color[2], c.color[3]) + } else gl.enableVertexAttribArray(1) + if(c && c.size !== null) { + gl.disableVertexAttribArray(2) + gl.vertexAttrib1f(2, c.size) + } else gl.enableVertexAttribArray(2) + if(c && c.noPick) { + // the "no highlight" id: hover is off for this trace, so it is never picked + gl.disableVertexAttribArray(3) + gl.vertexAttrib4f(3, 1, 1, 1, 1) + } else gl.enableVertexAttribArray(3) +} + +// The disc path for flat positions with one colour and one size: +// the positions are uploaded as given when every point is finite +proto._updateDiscFlat = function(options, points, n, outline) { + var colors = options.color + var sizes = options.size + var color = [0, 0, 0, 1] + if(isArrayOrTypedArray(colors)) { + if(colors.length === 3) { color[0] = colors[0]; color[1] = colors[1]; color[2] = colors[2] } + else if(colors.length === 4) { + color[0] = colors[0]; color[1] = colors[1]; color[2] = colors[2]; color[3] = colors[3] + if(!this.hasAlpha && colors[3] < 1) this.hasAlpha = true + } + } + var size = sizes ? +sizes : 12 + var pick = options.pick !== false + + // The same positions as at the last update (positionsKept): the position and id buffers stay, and so does + // the pick buffer when the size is the same (the pick pass reads neither colour nor opacity) + if(options.positionsKept) { + var fs = this.flatState + if(fs.n !== n || fs.pick !== pick || outline || fs.outline) return false + fs.size = size + fs.kind = this._kind + fs.kept++ + this.discConst = {color: color, size: size, noPick: !pick} + return true + } + + var lowerBound = [ Infinity, Infinity, Infinity] + var upperBound = [-Infinity,-Infinity,-Infinity] + var finite = true + // The caller has scanned the points (every point finite, bounds given) + var scanned = points.finite === true && !!points.bounds + for(var i = 0; i < n && !scanned; ++i) { + var x0 = points[3 * i], x1 = points[3 * i + 1], x2 = points[3 * i + 2] + if(x0 - x0 !== 0 || x1 - x1 !== 0 || x2 - x2 !== 0) { finite = false; continue } // NaN or infinite + if(x0 < lowerBound[0]) lowerBound[0] = x0 + if(x0 > upperBound[0]) upperBound[0] = x0 + if(x1 < lowerBound[1]) lowerBound[1] = x1 + if(x1 > upperBound[1]) upperBound[1] = x1 + if(x2 < lowerBound[2]) lowerBound[2] = x2 + if(x2 > upperBound[2]) upperBound[2] = x2 + } + + var m = n + var positionArray = null + var idArray = null + if(!finite) { + // drop the points that are not finite, as the per-point path does; ids keep the original index + positionArray = pool.mallocFloat(3 * n) + if(pick) idArray = pool.mallocUint32(n) + m = 0 + for(var i = 0; i < n; ++i) { + var x0 = points[3 * i], x1 = points[3 * i + 1], x2 = points[3 * i + 2] + if(x0 - x0 !== 0 || x1 - x1 !== 0 || x2 - x2 !== 0) continue + positionArray[3 * m] = x0; positionArray[3 * m + 1] = x1; positionArray[3 * m + 2] = x2 + if(idArray) idArray[m] = i + m += 1 + } + } else if(pick) { + idArray = pool.mallocUint32(n) + for(var i = 0; i < n; ++i) idArray[i] = i + } + + // bounds from the doubles the positions were rounded from, when the caller kept them (scatter3d convert) + this.bounds = points.bounds || [lowerBound, upperBound] + this.points = pick ? points : null // a trace that is never picked does not keep its positions + this.pointCount = n + this.vertexCount = m + this.lineVertexCount = 0 + this.discConst = {color: color, size: size, noPick: !pick} + + this.pointBuffer.update(positionArray ? positionArray.subarray(0, 3 * m) : points) + this.colorBuffer.update(1) + this.sizeBuffer.update(1) + if(idArray) this.idBuffer.update(idArray.subarray(0, m)) + else this.idBuffer.update(1) + if(outline) { + var lc = options.lineColor, lca = new Float32Array(4 * m), l = [0, 0, 0, 1] + if(isArrayOrTypedArray(lc) && (lc.length === 3 || lc.length === 4)) { + l[0] = lc[0]; l[1] = lc[1]; l[2] = lc[2]; l[3] = lc.length === 4 ? lc[3] : 1 + if(!this.hasAlpha && l[3] < 1) this.hasAlpha = true + } + for(var i = 0; i < m; ++i) { lca[4 * i] = l[0]; lca[4 * i + 1] = l[1]; lca[4 * i + 2] = l[2]; lca[4 * i + 3] = l[3] } + this.lineColorBuffer.update(lca) + } else if(this.lineColorBuffer) this.lineColorBuffer.update(1) + this.glyphBuffer.update(1) + + if(positionArray) pool.free(positionArray) + if(idArray) pool.free(idArray) + this.flatState = {n: n, pick: pick, outline: !!outline, size: size, kind: this._kind, kept: 0} + return true +} + +// Fill the disc buffers, 1 vertex per point. Returns false if the disc path cannot be used. +// The number of points of an update; with positionsKept, that of the buffers kept from the last one +proto._count = function(options) { + return options.positionsKept ? this.flatState.n : positionCount(options.position) +} + +proto._updateDisc = function(options) { + var gl = this.gl + var points = options.position + var n = this._count(options) + var kind = discKind(options.glyph, n) + this._kind = kind + var outline = this.lineWidth > 0 + try { + this._discSetup(kind, outline) + } catch(e) { + this.discBlocker = 'disc shader failed: ' + e + return false + } + + if(isFlatPositions(points) || options.positionsKept) { + var fc = options.color + var flc = options.lineColor + var perPoint = (isArrayOrTypedArray(fc) && isArrayOrTypedArray(fc[0])) || isArrayOrTypedArray(options.size) || + (outline && isArrayOrTypedArray(flc) && isArrayOrTypedArray(flc[0])) + if(!perPoint) { + if(!this._discSizeFits(options.size ? +options.size : 12)) return false + return this._updateDiscFlat(options, points, n, outline) + } + if(options.positionsKept) return false + points = unflattenPositions(points) + } + + var colors = options.color + var lineColors = options.lineColor + var sizes = options.size + + var positionArray = pool.mallocFloat(3 * n) + var colorArray = pool.mallocFloat(4 * n) + var sizeArray = pool.mallocFloat(n) + var idArray = pool.mallocUint32(n) + var lineArray = outline ? pool.mallocFloat(4 * n) : null + + var lowerBound = [ Infinity, Infinity, Infinity] + var upperBound = [-Infinity,-Infinity,-Infinity] + var color = [0, 0, 0, 1] + var lineColor = [0, 0, 0, 1] + var isColorArray = isArrayOrTypedArray(colors) && isArrayOrTypedArray(colors[0]) + var isLineColorArray = isArrayOrTypedArray(lineColors) && isArrayOrTypedArray(lineColors[0]) + var sizeIsArray = isArrayOrTypedArray(sizes) + var sizeScalar = sizeIsArray ? 0 : sizes ? +sizes : 12 + var maxSize = 0 + var m = 0 + + fill_loop: + for(var i = 0; i < n; ++i) { + var x = points[i] + for(var j = 0; j < 3; ++j) { + if(isNaN(x[j]) || !isFinite(x[j])) continue fill_loop + } + + if(isArrayOrTypedArray(colors)) { + var c + if(isColorArray) c = i < colors.length ? colors[i] : [0, 0, 0, 0] + else c = colors + if(c.length === 3) { + color[0] = c[0]; color[1] = c[1]; color[2] = c[2]; color[3] = 1 + } else if(c.length === 4) { + color[0] = c[0]; color[1] = c[1]; color[2] = c[2]; color[3] = c[3] + // a fully transparent fill under an outline draws nothing: the outline ring stays opaque + if(!this.hasAlpha && c[3] < 1 && !(c[3] === 0 && outline)) this.hasAlpha = true + } + } else { + color[0] = color[1] = color[2] = 0 + color[3] = 1 + } + + if(outline) { + if(isArrayOrTypedArray(lineColors)) { + var lc + if(isLineColorArray) lc = i < lineColors.length ? lineColors[i] : [0, 0, 0, 0] + else lc = lineColors + if(lc.length === 3) { + lineColor[0] = lc[0]; lineColor[1] = lc[1]; lineColor[2] = lc[2]; lineColor[3] = 1 + } else if(lc.length === 4) { + lineColor[0] = lc[0]; lineColor[1] = lc[1]; lineColor[2] = lc[2]; lineColor[3] = lc[3] + if(!this.hasAlpha && lc[3] < 1) this.hasAlpha = true + } + } else { + lineColor[0] = lineColor[1] = lineColor[2] = 0 + lineColor[3] = 1 + } + lineArray[4 * m] = lineColor[0] + lineArray[4 * m + 1] = lineColor[1] + lineArray[4 * m + 2] = lineColor[2] + lineArray[4 * m + 3] = lineColor[3] + } + + var size = sizeIsArray ? (i < sizes.length ? +sizes[i] : 12) : sizeScalar + if(size > maxSize) maxSize = size + + for(var j = 0; j < 3; ++j) { + positionArray[3 * m + j] = x[j] + if(x[j] > upperBound[j]) upperBound[j] = x[j] + if(x[j] < lowerBound[j]) lowerBound[j] = x[j] + } + colorArray[4 * m] = color[0] + colorArray[4 * m + 1] = color[1] + colorArray[4 * m + 2] = color[2] + colorArray[4 * m + 3] = color[3] + sizeArray[m] = size + idArray[m] = i + m += 1 + } + + // Largest sprite in device pixels (+2 for the antialiasing margin) against the driver's point size cap + if(!this._discSizeFits(maxSize)) { + pool.free(positionArray) + pool.free(colorArray) + pool.free(sizeArray) + pool.free(idArray) + if(lineArray) pool.free(lineArray) + return false + } + + this.bounds = points.bounds || [lowerBound, upperBound] + this.points = points + this.pointCount = n + this.vertexCount = m + this.lineVertexCount = 0 + this.discConst = null + + this.pointBuffer.update(positionArray.subarray(0, 3 * m)) + this.colorBuffer.update(colorArray.subarray(0, 4 * m)) + this.sizeBuffer.update(sizeArray.subarray(0, m)) + this.idBuffer.update(idArray.subarray(0, m)) + if(outline) this.lineColorBuffer.update(lineArray.subarray(0, 4 * m)) + else if(this.lineColorBuffer) this.lineColorBuffer.update(1) + this.glyphBuffer.update(1) // release the glyph buffer, it is not used by discs + + pool.free(positionArray) + pool.free(colorArray) + pool.free(sizeArray) + pool.free(idArray) + if(lineArray) pool.free(lineArray) + return true +} + +// Half width in device pixels of the outline ring. The ring is drawn in the fragment shader, not with GL lines, so +// marker.line.width applies as requested: ALIASED_LINE_WIDTH_RANGE only limits the glyph path. +proto._discLineHalf = function(pixelRatio) { + if(!this.discOutline) return 0 + return 0.5 * this.lineWidth * pixelRatio +} + +// the discs a preview can thin out (0 when the markers are not discs) +proto.lodPoints = function() { + return this.discActive ? this.vertexCount : 0 +} + +// A second vertex array of the same buffers with the element indices 0, k, 2k, ... for a preview of every +// k-th disc; kept until k or the number of discs changes. Null when 32-bit element indices are missing. +proto._discLod = function(set, k) { + var gl = this.gl + var count = Math.ceil(this.vertexCount / k) + var lod = set.lod + if(lod && lod.k === k && lod.count === count) return lod + if(this.lodIndex32 === undefined) { + this.lodIndex32 = !!((typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext) || + gl.getExtension('OES_element_index_uint')) + } + if(!this.lodIndex32 || !count) return null + var index = new Uint32Array(count) + for(var i = 0; i < count; ++i) index[i] = i * k + if(lod) { + lod.elements.update(index) + } else { + lod = set.lod = {elements: createBuffer(gl, index, gl.ELEMENT_ARRAY_BUFFER)} + lod.vao = createVAO(gl, set.attrs, lod.elements, gl.UNSIGNED_INT) + } + lod.k = k + lod.count = count + return lod +} + +function drawDisc(points, camera, pixelRatio, pick, hard, oitShader, oit) { + var gl = points.gl + var set = points.discCur + var shader = oitShader || (pick ? set.pickShader : set.shader) + var uniforms = shader.uniforms + shader.bind() + if(oit) setOITUniforms(shader, oit) + uniforms.model = camera.model || IDENTITY + uniforms.view = camera.view || IDENTITY + uniforms.projection = camera.projection || IDENTITY + VIEW_SHAPE[0] = 2.0/gl.drawingBufferWidth + VIEW_SHAPE[1] = 2.0/gl.drawingBufferHeight + uniforms.screenSize = VIEW_SHAPE + uniforms.highlightId = points.highlightId + uniforms.highlightScale = points.highlightScale + uniforms.clipBounds = points.axes.bounds + uniforms.opacity = points.opacity + uniforms.pickGroup = points.pickId / 255.0 + uniforms.pixelRatio = pixelRatio + uniforms.unitA = points.discUnit.a + uniforms.unitB = points.discUnit.b + uniforms.unitCenter = [points.discUnit.cx, points.discUnit.cy] + uniforms.lineHalf = points._discLineHalf(pixelRatio) + // Opaque pass, soft edges, in order of preference: + // 1. Multisampled target and an opaque clear alpha: pure alpha-to-coverage. Full colour, blending off, alpha written as + // coverage only (the alpha channel is masked off, it stays 1). Every sample is either fully this disc (with depth) or + // untouched, so the result does not depend on draw order, exactly like MSAA of the glyph meshes. + // 2. Transparent canvas (the plotly default scene background) or an export: hard cores with depth write, then the + // antialiased rim blended over (premultiplied) with the depth test and no depth write. This doubles the draw cost, so + // interactive draws only use it when points.discRimScreen is set; otherwise they keep the hard alpha-1 edge. + var samples = hard && !pick ? gl.getParameter(gl.SAMPLES) : 0 + var clearAlpha = hard && !pick ? gl.getParameter(gl.COLOR_CLEAR_VALUE)[3] : 0 + var a2c = !!(hard && !pick && points.discA2C !== false && samples > 0 && clearAlpha >= 0.999) + var rimPass = !!(hard && !pick && !a2c && !points.discHardEdge && + (points.discExport || (points.discRimScreen === true && samples > 0))) + uniforms.hardEdge = (hard && !a2c && !rimPass || points.discHardEdge) ? 1 : 0 + points.discPath = pick ? 'pick' : a2c ? 'a2c' : rimPass ? 'rim' : (hard || points.discHardEdge) ? 'hard' : 'smooth' // last draw path, for diagnostics + uniforms.a2c = a2c ? 1 : 0 + uniforms.rim = rimPass ? 0 : -1 + if(a2c) { + gl.enable(gl.SAMPLE_ALPHA_TO_COVERAGE) + gl.disable(gl.BLEND) + gl.colorMask(true, true, true, false) + } + + // a preview draws every lodStride-th disc through an index buffer; the pick pass draws them all + var vao = set.vao + var count = points.vertexCount + var lod = !pick && points.lodStride > 1 ? points._discLod(set, points.lodStride) : null + if(lod) { + vao = lod.vao + count = lod.count + } + // the thinned discs are drawn denser, see lodDense in the vertex shader + uniforms.lodK = lod ? points.lodStride : 1 + vao.bind() + points._discConstAttrs(gl) + vao.draw(gl.POINTS, count) + if(rimPass) { + uniforms.rim = 1 + gl.enable(gl.BLEND) + gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA) + gl.depthMask(false) + vao.draw(gl.POINTS, count) + gl.depthMask(true) + gl.disable(gl.BLEND) + } + vao.unbind() + if(a2c) { + gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE) + gl.colorMask(true, true, true, true) + } +} + +function drawFull(shader, pshader, points, camera, pixelRatio, transparent, forceDraw, oit) { var gl = points.gl if(transparent === points.projectHasAlpha || forceDraw) { - drawProject(pshader, points, camera, pixelRatio) + drawProject(pshader, points, camera, pixelRatio, oit) } if(transparent === points.hasAlpha || forceDraw) { + if(points.discActive) { + var isPick = pshader === points.pickProjectShader + drawDisc(points, camera, pixelRatio, isPick, isPick || !transparent) + return + } + shader.bind() var uniforms = shader.uniforms + if(oit) setOITUniforms(shader, oit) uniforms.model = camera.model || IDENTITY uniforms.view = camera.view || IDENTITY @@ -20157,6 +22015,53 @@ proto.drawTransparent = function(camera) { drawFull(shader, this.projectShader, this, camera, this.pixelRatio, true, false) } +// ---- draw this object into one of the order independent passes ---- +proto.isOIT = true + +function setOITUniforms(shader, oit) { + var u = shader.uniforms + u.oitMap = oit.map + u.oitInvSize = oit.invSize + u.oitGroup = oit.group + if(oit.pass > 0 && oit.anchored) u.oitAnchor = oit.anchorUnit + if(oit.pass === 2) { + for(var i = 0; i < oit.K / 4; ++i) u['oitTau' + i] = oit.tauUnit + i + } +} + +// The disc shaders for the OIT passes: the disc vertex shader plus the view depth, and the OIT fragment shader +function getOITDiscShader(gl, o, outline) { + var entry = shaders.oitCacheEntry(gl) + var key = 'disc-' + (outline ? 'o-' : 'p-') + (o.pass === 0 ? '0' : [o.pass, o.K, o.anchored ? 1 : 0, o.mrt ? 1 : 0].join('-')) + if(!entry.map[key]) { + var vert = discVert(outline) + var anchor = ' interpColor = color;' + if(vert.indexOf(anchor) < 0 || vert.indexOf('varying float vA;') < 0) throw new Error('oit: cannot patch disc vertex shader') + vert = vert.replace('varying float vA;', 'varying float vA;\nvarying float oitZ;') + .replace(anchor, anchor + '\n oitZ = (view * (model * vec4(position, 1.0))).z;') + var frag = shaders.oitFragSrc({pass: o.pass, K: o.K, anchored: o.anchored, mrt: o.mrt, disc: true, outline: outline}) + var shader = createShaderWrapper(gl, {vertex: vert, fragment: frag}) + var attr = shader.attributes + attr.position.location = 0 + attr.color.location = 1 + attr.size.location = 2 + attr.id.location = 3 + if(outline && attr.lineColor) attr.lineColor.location = 4 + entry.map[key] = shader + } + return entry.map[key] +} + +proto.drawOIT = function(camera, oit) { + if(this.discActive) { + if(this.hasAlpha) drawDisc(this, camera, this.pixelRatio, false, false, getOITDiscShader(this.gl, oit, this.discOutline), oit) + return + } + var sh = shaders.getOITShaders(this.gl, oit) + var shader = this.useOrtho ? sh.ortho : sh.perspective + drawFull(shader, sh.project, this, camera, this.pixelRatio, true, false, oit) +} + proto.drawPick = function(camera) { var shader = this.useOrtho ? this.pickOrthoShader : this.pickPerspectiveShader drawFull(shader, this.pickProjectShader, this, camera, 1, true, true) @@ -20169,15 +22074,28 @@ proto.pick = function(selected) { if(selected.id !== this.pickId) { return null } + // A cloud that is never picked gives no hit. Nor does one with more points than the 24 bits of the point index + // in the pick buffer can tell apart (the last value means none): its ids would name other points + if(this.noPick || this.pointCount > 16777215) { + return null + } var x = selected.value[2] + (selected.value[1]<<8) + (selected.value[0]<<16) if(x >= this.pointCount || x < 0) { return null } + if(!this.points) return null + //Unpack result - var coord = this.points[x] var result = this._selectResult result.index = x + if(isFlatPositions(this.points)) { + for(var i=0; i<3; ++i) { + result.position[i] = result.dataCoordinate[i] = this.points[3 * x + i] + } + return result + } + var coord = this.points[x] for(var i=0; i<3; ++i) { result.position[i] = result.dataCoordinate[i] = coord[i] } @@ -20311,9 +22229,40 @@ proto.update = function(options) { //Set dirty flag this.dirty = true + // A cloud that is never picked (hoverinfo 'skip'). The scene draws no pick pass when no object can be picked. + if('pick' in options) this.noPick = options.pick === false + //Create new buffers var points = options.position + //Circle markers as 1 vertex discs + if('markerRender' in options) this.markerRender = options.markerRender + if('discHardEdge' in options) this.discHardEdge = !!options.discHardEdge + // With positionsKept the caller sends no positions; if the buffers of the last update cannot serve + // this one, positionsMissing asks for them + var kept = !!options.positionsKept + this.positionsMissing = false + if(!kept) this.flatState = null + else if(!this.flatState) { + this.positionsMissing = true + return + } + this.discBlocker = this._discBlocker(options) + this.discActive = false + if(!this.discBlocker && this._updateDisc(options)) { + this.discActive = true + return + } + if(kept) { + this.flatState = null + this.positionsMissing = true + return + } + if(this.sizeBuffer) this.sizeBuffer.update(1) // release the disc buffers while glyphs are in use + if(this.lineColorBuffer) this.lineColorBuffer.update(1) + this.discConst = null + if(isFlatPositions(points)) points = unflattenPositions(points) + //Text font var font = { family: options.font || 'normal', @@ -20379,7 +22328,7 @@ proto.update = function(options) { var glyphBounds = glyphData.bounds triVertexCount += glyphMesh.cells.length * 3 - lineVertexCount += glyphLines.edges.length * 2 + if(this.lineWidth > 0) lineVertexCount += glyphLines.edges.length * 2 } } @@ -20575,7 +22524,7 @@ proto.update = function(options) { } } - var cells = glyphLines.edges + var cells = this.lineWidth > 0 ? glyphLines.edges : [] var verts = glyphLines.positions for(var j=0; j { + let centerX; + let centerY; + let calcdata; + + function assertScale(msg) { + let xa = gd._fullLayout.xaxis; + let ya = gd._fullLayout.yaxis; + // With scaleratio 2, y has two times the pixels per unit of x + expect(-ya._m).toBeCloseTo(2 * xa._m, 6, msg); + expect(gd.calcdata).toBe(calcdata, 'no recalc - ' + msg); + } + + Plotly.newPlot(gd, [{ + type: 'scattergl', x: [1, 15], y: [1, 15] + }], { + width: 400, + height: 400, + margin: {t: 100, b: 100, l: 100, r: 100}, + xaxis: {range: [-8, 24]}, + yaxis: {range: [0, 16], scaleanchor: 'x', scaleratio: 2} + }) + .then(() => { + let bBox = gd.getBoundingClientRect(); + centerX = bBox.left + 200; + centerY = bBox.top + 200; + calcdata = gd.calcdata; + + return mouseTo([centerX, centerY], [centerX - 1, centerY - 50]); + }) + .then(() => { + expect(gd.layout.xaxis.range).toBeCloseToArray([0, 8], 3); + expect(gd.layout.yaxis.range).toBeCloseToArray([8, 12], 3); + assertScale('zoom'); + + return Plotly.relayout(gd, 'dragmode', 'pan'); + }) + .then(() => { + return mouseTo([centerX, centerY], [centerX + 50, centerY]); + }) + .then(() => { + expect(gd.layout.xaxis.range).toBeCloseToArray([-2, 6], 3); + expect(gd.layout.yaxis.range).toBeCloseToArray([8, 12], 3); + assertScale('pan'); + + return Plotly.relayout(gd, 'xaxis.range', [0, 4]); + }) + .then(() => { + // The y range changes to keep the ratio, about the same center + expect(gd.layout.xaxis.range).toBeCloseToArray([0, 4], 3); + expect(gd.layout.yaxis.range).toBeCloseToArray([9, 11], 3); + assertScale('relayout of one axis'); + }) + .then(done, done.fail); + }); + it('@gl data-referenced annotations should update on drag', function(done) { function assertAnnotation(xy) { var ann = d3Select('g.annotation-text-g').select('g'); diff --git a/test/jasmine/tests/gl3d_hover_click_test.js b/test/jasmine/tests/gl3d_hover_click_test.js index 1499eebbf5d..2675f63f046 100644 --- a/test/jasmine/tests/gl3d_hover_click_test.js +++ b/test/jasmine/tests/gl3d_hover_click_test.js @@ -1503,3 +1503,415 @@ describe('hover on traces with (x|y|z|u|v|w)hoverformat and valuehoverformat', f }); }); }); + +function f32(n, seed) { + var a = new Float32Array(n); + var s = seed; + for(var i = 0; i < n; i++) { + s = (s * 1664525 + 1013904223) >>> 0; + a[i] = s / 4294967296; + } + return a; +} + +function cloud(n, extra, seed) { + seed = seed || 0; + var t = {type: 'scatter3d', mode: 'markers', x: f32(n, 1 + seed), y: f32(n, 2 + seed), z: f32(n, 3 + seed), + marker: {size: 10, color: 'blue', line: {width: 0}}}; + for(var k in extra) t[k] = extra[k]; + return t; +} + +var PICK_LAYOUT = {width: 600, height: 400, margin: {l: 0, r: 0, t: 0, b: 0}, showlegend: false, + scene: {camera: {eye: {x: 1.4, y: 1.2, z: 0.9}, projection: {type: 'orthographic'}}}}; +var EYE2 = {x: 0.9, y: 1.6, z: 0.8}; + +describe('Test gl3d pick pass:', function() { + var gd; + + beforeEach(function() { gd = createGraphDiv(); }); + afterEach(function() { + Plotly.purge(gd); + destroyGraphDiv(); + }); + + function glplot() { return gd._fullLayout.scene._scene.glplot; } + function draws() { return glplot().pickStats.draws; } + function layout() { return JSON.parse(JSON.stringify(PICK_LAYOUT)); } + // the points of the hover events of pointer moves over the cloud + function hoverTrail() { + var out = []; + gd.on('plotly_hover', function(e) { + // every frame with a hovered point emits the event again: keep the changes + var p = e.points[0].curveNumber + ':' + e.points[0].pointNumber; + if(out[out.length - 1] !== p) out.push(p); + }); + return out; + } + // Wait for the frame of the scene that follows a pointer event. With the pick pass in each frame, or with + // the axis spikes on, the hover events come from that frame, and a frame can take longer than a fixed delay. + const frame = () => + new Promise((resolve) => { + requestAnimationFrame(() => requestAnimationFrame(() => setTimeout(resolve, 0))); + }); + function moves(list) { + var p = Promise.resolve(); + list.forEach(function(xy) { + p = p + .then(() => { + mouseEvent('mousemove', xy[0], xy[1]); + }) + .then(delay(60)) + .then(frame); + }); + return p; + } + var PATH = [[300, 200], [280, 190], [320, 215], [305, 230]]; + + it('@gl draws no pick pass in the frames of a camera change; the first pointer query draws one', function(done) { + var n0; + Plotly.newPlot(gd, [cloud(3000)], layout()) + .then(delay(100)) + .then(function() { + glplot().pickIdleDelay = 0; + mouseEvent('mousemove', 300, 200); + n0 = draws(); + return Plotly.relayout(gd, 'scene.camera.eye', EYE2); + }) + .then(delay(150)) + .then(function() { + expect(draws()).toBe(n0, 'no pass in the frames after the camera change'); + mouseEvent('mousemove', 310, 205); + expect(draws()).toBe(n0 + 1, 'the pointer query draws it'); + mouseEvent('mousemove', 320, 210); + mouseEvent('mousemove', 290, 190); + expect(draws()).toBe(n0 + 1, 'later queries read the same buffer'); + }) + .then(done, done.fail); + }); + + it('@gl draws the pick pass once the scene has been at rest for pickIdleDelay', function(done) { + var n0; + Plotly.newPlot(gd, [cloud(3000)], layout()) + .then(delay(900)) + .then(function() { + expect(glplot().pickIdleDelay).toBe(120); + n0 = draws(); + expect(n0).toBeGreaterThan(0); + return Plotly.relayout(gd, 'scene.camera.eye', EYE2); + }) + .then(delay(900)) + .then(function() { + expect(draws()).toBe(n0 + 1); + mouseEvent('mousemove', 310, 205); + expect(draws()).toBe(n0 + 1); + }) + .then(done, done.fail); + }); + + it('@gl draws no pick pass during a drag', function(done) { + var n0; + Plotly.newPlot(gd, [cloud(3000)], layout()) + .then(delay(300)) + .then(function() { + mouseEvent('mousemove', 300, 200); + n0 = draws(); + mouseEvent('mousedown', 300, 200, {buttons: 1}); + }) + .then(delay(30)) + .then(function() { mouseEvent('mousemove', 320, 205, {buttons: 1}); }) + .then(delay(200)) + .then(function() { mouseEvent('mousemove', 340, 210, {buttons: 1}); }) + .then(delay(200)) + .then(function() { + expect(draws()).toBe(n0, 'none while the button is held, also past the idle delay'); + mouseEvent('mouseup', 340, 210); + expect(draws()).toBe(n0 + 1, 'the release queries the buffer'); + }) + .then(done, done.fail); + }); + + it('@gl gives the hover points of the eager pick pass after a camera change', function(done) { + var lazy, eager; + Plotly.newPlot(gd, [cloud(3000), cloud(3000, {marker: {size: 10, color: 'red', line: {width: 0}}}, 7)], layout()) + .then(delay(700)) + .then(function() { + glplot().pickIdleDelay = 0; + lazy = hoverTrail(); + return Plotly.relayout(gd, 'scene.camera.eye', EYE2); + }) + .then(delay(700)) + .then(function() { return moves(PATH); }) + .then(function() { + return Plotly.newPlot(gd, [cloud(3000), cloud(3000, {marker: {size: 10, color: 'red', line: {width: 0}}}, 7)], layout()); + }) + .then(delay(700)) + .then(function() { + glplot().pickMode = 'eager'; + eager = hoverTrail(); + return Plotly.relayout(gd, 'scene.camera.eye', EYE2); + }) + .then(delay(700)) + .then(function() { return moves(PATH); }) + .then(function() { + expect(lazy.length).toBeGreaterThan(1); + expect(lazy).toEqual(eager); + }) + .then(done, done.fail); + }); + + it('@gl draws no pick pass when every trace has hoverinfo skip', function(done) { + var trail; + Plotly.newPlot(gd, [cloud(3000, {hoverinfo: 'skip'}), cloud(3000, {hoverinfo: 'skip'}, 7)], layout()) + .then(delay(900)) + .then(function() { + trail = hoverTrail(); + expect(draws()).toBe(0); + return Plotly.relayout(gd, 'scene.camera.eye', EYE2); + }) + .then(delay(700)) + .then(function() { return moves(PATH); }) + .then(function() { + expect(draws()).toBe(0); + expect(trail.length).toBe(0); + // a pickable trace brings the pass back + return Plotly.restyle(gd, {hoverinfo: 'all'}, [1]); + }) + .then(delay(300)) + .then(function() { return moves(PATH); }) + .then(function() { + expect(draws()).toBeGreaterThan(0); + expect(trail.length).toBeGreaterThan(0); + trail.forEach(function(p) { expect(p.charAt(0)).toBe('1'); }); + }) + .then(done, done.fail); + }); + + it('@gl a skip trace in a mixed scene is still drawn into the pick buffer and hides the points behind it', function(done) { + // a wall of skip points in front of a pickable wall, seen along x + function wall(xv, extra) { + var t = cloud(4000, extra); + for(var i = 0; i < 4000; i++) t.x[i] = xv; + t.marker.size = 14; + return t; + } + var L = layout(); + L.scene.camera.eye = {x: 2, y: 0, z: 0}; + var trail; + Plotly.newPlot(gd, [wall(0), wall(1, {hoverinfo: 'skip'})], L) + .then(delay(900)) + .then(function() { + trail = hoverTrail(); + return moves(PATH); + }) + .then(function() { + expect(draws()).toBe(1); + expect(trail.length).toBe(0); + }) + .then(done, done.fail); + }); + + it('@gl hovermode false picks only when the button goes down: no hover events, plotly_click works', function(done) { + var ev = []; + var L = layout(); + L.scene.hovermode = false; + Plotly.newPlot(gd, [cloud(3000)], L) + .then(delay(900)) + .then(function() { + ['plotly_hover', 'plotly_unhover', 'plotly_click'].forEach(function(n) { + gd.on(n, function(e) { ev.push(n.slice(7) + (e && e.points ? ':' + e.points[0].pointNumber : '')); }); + }); + expect(glplot().pickOnPress).toBe(true); + expect(draws()).toBe(0, 'no pass ahead of a query'); + return moves(PATH); + }) + .then(function() { + expect(draws()).toBe(0, 'pointer moves query nothing'); + expect(ev).toEqual([]); + mouseEvent('mousedown', 300, 200, {buttons: 1}); + }) + .then(delay(100)) + .then(function() { + expect(draws()).toBe(1); + expect(ev.length).toBeGreaterThan(0); + ev.forEach(function(e) { expect(e.slice(0, 6)).toBe('click:'); }); + mouseEvent('mouseup', 300, 200); + }) + .then(delay(100)) + .then(function() { + ev.length = 0; + return Plotly.relayout(gd, 'scene.hovermode', 'closest'); + }) + .then(function() { + expect(glplot().pickOnPress).toBe(false); + return moves(PATH); + }) + .then(function() { + expect(ev.filter(function(e) { return e.slice(0, 6) === 'hover:'; }).length).toBeGreaterThan(0); + }) + .then(done, done.fail); + }); + + it('@gl gives no hover for a pointer event right after the first frame of a scene', function(done) { + // A pointer that rests on a scene sends an event when the canvas appears, right after the first frame. + // The pick pass in the frame was read back 1 ms later, so that event found nothing, and the pointer got no label + // until it moved. The pick pass on demand must answer the same way. + const labels = () => document.querySelectorAll('g.hovertext').length; + Plotly.newPlot(gd, Lib.extendDeep({}, mesh3dcoloringMock)) + .then(() => { + mouseEvent('mousemove', 600, 200); + }) + .then(frame) + .then(() => { + expect(labels()).toBe(0, 'no label for the event right after the first frame'); + }) + .then(delay(300)) + .then(() => { + expect(labels()).toBe(0, 'and none later without a pointer event'); + mouseEvent('mousemove', 601, 201); + }) + .then(delay(20)) + .then(frame) + .then(() => { + expect(labels()).toBe(1, 'the mesh is under that pointer: a move at rest finds it'); + }) + .then(done, done.fail); + }); + + it('@gl a hover move draws no frame when the axis spikes are off, and gives the same events', function(done) { + function run(spikes) { + var L = layout(); + ['xaxis', 'yaxis', 'zaxis'].forEach(function(a) { L.scene[a] = {showspikes: spikes}; }); + var ev = []; + var frames = 0; + return Plotly.newPlot(gd, [cloud(3000)], L) + .then(delay(900)) + .then(function() { + var o = glplot().objects[0]; + var draw = o.draw; + o.draw = function() { + frames++; + return draw.apply(this, arguments); + }; + gd.on('plotly_hover', function(e) { ev.push('hover:' + e.points[0].pointNumber); }); + gd.on('plotly_unhover', function() { ev.push('unhover'); }); + gd.on('plotly_click', function(e) { ev.push('click:' + e.points[0].pointNumber); }); + return moves(PATH); + }) + .then(function() { mouseEvent('mousedown', 305, 230, {buttons: 1}); }) + .then(delay(60)) + .then(frame) + .then(function() { mouseEvent('mouseup', 305, 230); }) + .then(delay(60)) + .then(frame) + .then(function() { return moves([[5, 5]]); }) + .then(function() { + expect(document.querySelectorAll('g.hovertext').length).toBe(0); + return {ev: ev, frames: frames}; + }); + } + var off; + run(false) + .then(function(r) { + off = r; + expect(r.frames).toBe(0, 'no frame for the hover moves, the click and the unhover'); + expect(r.ev.length).toBeGreaterThan(PATH.length); + expect(r.ev[r.ev.length - 1]).toBe('unhover'); + return run(true); + }) + .then(function(on) { + expect(on.frames).toBeGreaterThan(PATH.length - 1, 'with spikes every hover move draws a frame'); + expect(off.ev).toEqual(on.ev); + }) + .then(done, done.fail); + }); + + it('@gl a trace with more points than a pick id can tell apart is drawn but never picked, and says so', function(done) { + var convert = require('../../../src/traces/scatter3d/convert'); + var max = convert.maxPickPoints; + expect(max).toBe(16777215); + convert.maxPickPoints = 2000; + spyOn(Lib, 'warn'); + var trail; + Plotly.newPlot(gd, [cloud(3000)], layout()) + .then(delay(900)) + .then(function() { + var o = glplot().objects[0]; + expect(Lib.warn).toHaveBeenCalled(); + expect(Lib.warn.calls.argsFor(0)[0]).toMatch(/3000 points/); + expect(o.pointCount).toBe(3000); + expect(o.noPick).toBe(true); + trail = hoverTrail(); + return moves(PATH); + }) + .then(function() { + expect(trail.length).toBe(0); + expect(draws()).toBe(0); + Lib.warn.calls.reset(); + return Plotly.newPlot(gd, [cloud(2000)], layout()); + }) + .then(delay(900)) + .then(function() { + expect(Lib.warn).not.toHaveBeenCalled(); + trail = hoverTrail(); + return moves(PATH); + }) + .then(function() { + expect(trail.length).toBeGreaterThan(0); + // gl-scatter3d itself gives no hit for a cloud above 2^24 - 1 points + var o = glplot().objects[0]; + var n = o.pointCount; + expect(o.pick({id: o.pickId, value: [0, 0, 7]})).not.toBe(null); + o.pointCount = 16777216; + expect(o.pick({id: o.pickId, value: [0, 0, 7]})).toBe(null); + o.pointCount = n; + }) + .then(function() { convert.maxPickPoints = max; }, function(e) { + convert.maxPickPoints = max; + throw e; + }) + .then(done, done.fail); + }); + + it('@gl a disc trace of typed positions above the pick id range keeps no hover positions', function(done) { + var convert = require('../../../src/traces/scatter3d/convert'); + var max = convert.maxPickPoints; + convert.maxPickPoints = 2000; + spyOn(Lib, 'warn'); + var trail; + var fig = layout(); + fig.scene.markerrender = 'disc'; + Plotly.newPlot(gd, [cloud(3000)], fig) + .then(delay(900)) + .then(function() { + var trace = gd._fullLayout.scene._scene.traces[gd._fullData[0].uid]; + var o = trace.scatterPlot; + expect(Lib.warn).toHaveBeenCalled(); + expect(o.discActive).toBe(true); + expect(o.vertexCount).toBe(3000, 'the cloud is drawn'); + expect(o.noPick).toBe(true); + expect(trace.dataPoints.length).toBe(0); + trail = hoverTrail(); + return moves(PATH); + }) + .then(function() { + expect(trail.length).toBe(0); + expect(draws()).toBe(0); + }) + .then(function() { convert.maxPickPoints = max; }, function(e) { + convert.maxPickPoints = max; + throw e; + }) + .then(done, done.fail); + }); + + it('@gl a purge with a pending idle timer does not throw', function(done) { + Plotly.newPlot(gd, [cloud(3000)], layout()) + .then(delay(50)) + .then(function() { return Plotly.relayout(gd, 'scene.camera.eye', EYE2); }) + .then(delay(30)) + .then(function() { Plotly.purge(gd); }) + .then(delay(300)) + .then(done, done.fail); + }); +}); diff --git a/test/jasmine/tests/gl3d_lod_test.js b/test/jasmine/tests/gl3d_lod_test.js new file mode 100644 index 00000000000..912bdfff141 --- /dev/null +++ b/test/jasmine/tests/gl3d_lod_test.js @@ -0,0 +1,522 @@ +const Plotly = require('../../../lib/index'); +const createGraphDiv = require('../assets/create_graph_div'); +const destroyGraphDiv = require('../assets/destroy_graph_div'); +const mouseEvent = require('../assets/mouse_event'); + +// level of detail while the camera moves: scene.lod + +function f32(n, seed) { + const 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('gl-scatter3d strided discs', () => { + let gd; + + beforeEach(() => { + gd = createGraphDiv(); + }); + afterEach(() => { + Plotly.purge(gd); + destroyGraphDiv(); + }); + + function trace3d(n, seed, extra) { + let t = { + type: 'scatter3d', + mode: 'markers', + x: f32(n, seed), + y: f32(n, seed + 1), + z: f32(n, seed + 2), + marker: { size: 4, color: 'red', line: { width: 0 } } + }; + for (let k in extra) t[k] = extra[k]; + return t; + } + function glplot() { + return gd._fullLayout.scene._scene.glplot; + } + function watch3d() { + let gl = glplot().gl; + let log = { elements: [], arrays: [] }; + let de = gl.drawElements; + let da = gl.drawArrays; + gl.drawElements = function (mode, count, type) { + if (mode === gl.POINTS) log.elements.push([count, type]); + return de.apply(gl, arguments); + }; + gl.drawArrays = function (mode, first, count) { + if (mode === gl.POINTS) log.arrays.push(count); + return da.apply(gl, arguments); + }; + log.reset = () => { + log.elements = []; + log.arrays = []; + }; + log.restore = () => { + gl.drawElements = de; + gl.drawArrays = da; + }; + return log; + } + function frame() { + glplot().dirty = true; + glplot().redraw(); + } + function differ3(a, b) { + let n = 0; + for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) n++; + return n; + } + function pixels() { + let gl = glplot().gl; + const px = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4); + gl.readPixels(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight, gl.RGBA, gl.UNSIGNED_BYTE, px); + return px; + } + + it('@gl draws every k-th disc of a trace when asked, opaque and translucent, and all of them again after', (done) => { + let log, full, plain, objs; + Plotly.newPlot( + gd, + [ + trace3d(1000, 1), + trace3d(501, 4, { marker: { size: 4, color: 'blue', opacity: 0.5, line: { width: 0 } } }) + ], + { width: 400, height: 300, scene: { bgcolor: '#ffffff', markerrender: 'auto' } } + ) + .then(() => { + objs = glplot().objects; + expect( + objs.map((o) => { + return o.lodPoints(); + }) + ).toEqual([1000, 501]); + // no alpha to coverage: the thinned frame is compared with a full one + objs.forEach((o) => { + o.discA2C = false; + }); + log = watch3d(); + frame(); + plain = log.arrays.slice(); + expect(log.elements.length).toBe(0); + full = pixels(); + log.reset(); + objs.forEach((o) => { + o.lodStride = 8; + }); + frame(); + let gl = glplot().gl; + // every draw of the two traces for the picture is thinned (the pick pass, drawArrays, is not) + const counts = log.elements.map((e) => { + return e[0]; + }); + expect(counts.indexOf(125)).not.toBe(-1); + expect(counts.indexOf(63)).not.toBe(-1); + expect( + counts.filter((c) => { + return c !== 125 && c !== 63; + }) + ).toEqual([]); + expect(counts.length).toBeGreaterThan(2); + log.elements.forEach((e) => { + expect(e[1]).toBe(gl.UNSIGNED_INT); + }); + const thin = pixels(); + expect(differ3(full, thin)).toBeGreaterThan(1000); + + // the same stride again: no new index buffer + let uploads = 0; + const bd = gl.bufferData; + gl.bufferData = function (target) { + if (target === gl.ELEMENT_ARRAY_BUFFER) uploads++; + return bd.apply(gl, arguments); + }; + frame(); + expect(uploads).toBe(0); + gl.bufferData = bd; + + log.reset(); + objs.forEach((o) => { + o.lodStride = 0; + }); + frame(); + // the draws of before + expect(log.elements.length).toBe(0); + expect(log.arrays).toEqual(plain); + log.restore(); + }) + .then(done, done.fail); + }); + + it('@gl draws thinned translucent discs as dense as all of them, and thinned opaque discs as before', (done) => { + // no axes: only the discs are compared + const axis = { range: [0, 1], autorange: false, visible: false }; + const layout = { + width: 400, + height: 300, + scene: { bgcolor: '#ffffff', markerrender: 'auto', xaxis: axis, yaxis: axis, zaxis: axis } + }; + // 64 discs of opacity 0.1 on one place: 8 of them with the opacity of 8 discs each cover the same + const pile = { + type: 'scatter3d', + mode: 'markers', + x: new Float32Array(64).fill(0.5), + y: new Float32Array(64).fill(0.5), + z: new Float32Array(64).fill(0.5), + marker: { size: 30, color: 'red', opacity: 0.1, line: { width: 0 } } + }; + const opaque = trace3d(1000, 1); + let at, full, thin; + // the camera glides to its place after a plot: wait until it rests + const rest = () => new Promise((r) => setTimeout(r, 700)); + Plotly.newPlot(gd, [pile], layout) + .then(rest) + .then(() => { + expect(glplot().objects[0].lodPoints()).toBe(64); + frame(); + full = pixels(); + // the pixel with the most red over the white ground: the lowest green + at = 1; + for (let i = 1; i < full.length; i += 4) if (full[i] < full[at]) at = i; + expect(full[at]).toBeLessThan(40); + + glplot().objects[0].lodStride = 8; + frame(); + thin = pixels(); + expect(Math.abs(thin[at] - full[at])).toBeLessThan(17); + // (without the denser alpha, 8 discs of opacity 0.1 leave the green at about 110) + + return Plotly.react(gd, [opaque], layout); + }) + .then(rest) + .then(() => { + const gl = glplot().gl; + glplot().objects.forEach((o) => { + o.discA2C = false; + o.lodStride = 16; + }); + frame(); + thin = pixels(); + // the same thinned draw with the stride of the shader set to 1, which turns the denser alpha off: + // opaque discs have the same pixels + const u1f = gl.uniform1f; + let replaced = 0; + gl.uniform1f = function (loc, v) { + if (v === 16) { + replaced++; + v = 1; + } + return u1f.call(gl, loc, v); + }; + frame(); + gl.uniform1f = u1f; + expect(replaced).toBeGreaterThan(0); + expect(differ3(pixels(), thin)).toBe(0); + }) + .then(done, done.fail); + }); + + it('@gl draws a thinned translucent cloud about as dense as the full one with scene.oit auto', (done) => { + const mean = (px) => { + let sum = 0; + for (let i = 0; i < px.length; i += 4) sum += px[i + 1]; + return sum / (px.length / 4); + }; + Plotly.newPlot( + gd, + [trace3d(40000, 1, { marker: { size: 6, color: 'red', opacity: 0.2, line: { width: 0 } } })], + { width: 400, height: 300, scene: { bgcolor: '#ffffff', markerrender: 'disc', oit: 'auto' } } + ) + .then(() => { + const objs = glplot().objects; + expect(gd._fullLayout.scene._scene.getOITStatus().mode).toBe('D'); + expect(objs[0].lodPoints()).toBe(40000); + frame(); + // green is 255 on the background and 0 under an opaque red cover + const full = mean(pixels()); + objs[0].lodStride = 8; + frame(); + const thin = mean(pixels()); + // an eighth of the discs at the same alpha would leave most of the cover out + expect(full).toBeLessThan(235); + expect(Math.abs(thin - full)).toBeLessThan(6); + }) + .then(done, done.fail); + }); + + it('@gl never thins the pick pass, and has no discs to thin for glyph markers', (done) => { + let log; + Plotly.newPlot(gd, [trace3d(1000, 1), trace3d(300, 4, { marker: { size: 4, symbol: 'square' } })], { + width: 400, + height: 300, + scene: { markerrender: 'auto' } + }) + .then(() => { + const objs = glplot().objects; + expect( + objs.map((o) => { + return o.lodPoints(); + }) + ).toEqual([1000, 0]); + objs.forEach((o) => { + o.lodStride = 8; + }); + log = watch3d(); + objs[0].drawPick({ + model: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], + view: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], + projection: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] + }); + expect(log.elements.length).toBe(0); + expect(log.arrays).toEqual([1000]); + log.restore(); + }) + .then(done, done.fail); + }); +}); + +describe('gl3d scene.lod', () => { + let gd; + let events; + + beforeEach(() => { + gd = createGraphDiv(); + events = []; + }); + afterEach(() => { + Plotly.purge(gd); + destroyGraphDiv(); + }); + + function trace3d(n, seed, extra) { + const t = { + type: 'scatter3d', + mode: 'markers', + x: f32(n, seed), + y: f32(n, seed + 1), + z: f32(n, seed + 2), + marker: { size: 4, color: 'red', line: { width: 0 } } + }; + for (let k in extra) t[k] = extra[k]; + return t; + } + function data() { + return [ + trace3d(1000, 1), + trace3d(501, 4, { marker: { size: 4, color: 'blue', opacity: 0.5, line: { width: 0 } } }) + ]; + } + function layout(lod) { + const scene = { bgcolor: '#ffffff', markerrender: 'auto', camera: { eye: { x: 1.5, y: 1.5, z: 1.5 } } }; + if (lod) scene.lod = JSON.parse(JSON.stringify(lod)); + return { width: 400, height: 300, scene: scene }; + } + const LOD = { minpoints: 1000, budget: 200, maxstride: 64, settle: 80 }; + function scene() { + return gd._fullLayout.scene._scene; + } + function glplot() { + return scene().glplot; + } + function wait(ms) { + return new Promise((r) => { + setTimeout(r, ms); + }); + } + function when(state) { + return new Promise((resolve, reject) => { + const t0 = Date.now(); + (function poll() { + if (scene().getLOD().state === state) resolve(); + else if (Date.now() - t0 > 3000) + reject(new Error('never ' + state + ', still ' + scene().getLOD().state)); + else setTimeout(poll, 5); + })(); + }); + } + function watch3d() { + const gl = glplot().gl; + let log = { elements: [], arrays: [] }; + const de = gl.drawElements; + const da = gl.drawArrays; + gl.drawElements = function (mode, count) { + if (mode === gl.POINTS) log.elements.push(count); + return de.apply(gl, arguments); + }; + gl.drawArrays = function (mode, first, count) { + if (mode === gl.POINTS) log.arrays.push(count); + return da.apply(gl, arguments); + }; + log.reset = () => { + log.elements = []; + log.arrays = []; + }; + log.restore = () => { + gl.drawElements = de; + gl.drawArrays = da; + }; + return log; + } + function moveCamera(x) { + return Plotly.relayout(gd, { 'scene.camera.eye': { x: x, y: 1.5, z: 1.5 } }); + } + function plot(lod, config) { + return Plotly.newPlot(gd, data(), layout(lod), config).then(() => { + gd.on('plotly_lod', (e) => { + events.push(e); + }); + }); + } + + it('@gl thins the discs while the camera moves, with no pick pass, and draws them all at rest', (done) => { + let log; + let picks; + const pickDraws = () => glplot().pickStats.draws; + plot(LOD) + .then(() => { + return wait(800); + }) + .then(() => { + // at rest after the open every disc is drawn: 1501 discs, budget 200, stride 8 + expect(gd._fullLayout.scene.lod).toEqual(LOD); + expect(scene().getLOD().state).toBe('full'); + expect(scene().getLOD().stride).toBe(8); + expect(scene().getLOD().total).toBe(1501); + // The pick pass is drawn only for a pointer query. + glplot().pickIdleDelay = 0; + mouseEvent('mousemove', 200, 150); + picks = pickDraws(); + events.length = 0; + log = watch3d(); + return moveCamera(1.7); + }) + .then(() => { + return when('preview'); + }) + .then(() => { + return wait(30); + }) + .then(() => { + expect(log.elements.length).toBeGreaterThan(1); + expect( + log.elements.filter((c) => { + return c !== 125 && c !== 63; + }) + ).toEqual([]); + expect(log.arrays.length).toBe(0); + expect(events[0]).toEqual({ + subplot: 'scene', + state: 'preview', + stride: 8, + shown: 188, + total: 1501, + reason: 'camera' + }); + // a second move restarts the wait + return moveCamera(1.9); + }) + .then(() => { + return wait(40); + }) + .then(() => { + expect(scene().getLOD().state).toBe('preview'); + // no pick pass in a preview, also for a pointer query: it would draw every disc with drawArrays + mouseEvent('mousemove', 210, 150); + expect(log.arrays.length).toBe(0); + expect(pickDraws()).toBe(picks); + log.reset(); + return when('full'); + }) + .then(() => { + return wait(30); + }) + .then(() => { + expect(log.arrays.indexOf(1000)).not.toBe(-1); + expect(log.arrays.indexOf(501)).not.toBe(-1); + expect( + events.map((e) => { + return e.state + ':' + e.reason; + }) + ).toEqual(['preview:camera', 'full:settle']); + // the full frame draws no pick pass, and the next pointer query draws one: every disc once more + expect(pickDraws()).toBe(picks); + const before = log.arrays.filter((c) => c === 501).length; + mouseEvent('mousemove', 220, 155); + expect(pickDraws()).toBe(picks + 1); + expect(log.arrays.filter((c) => c === 501).length).toBe(before + 1); + log.restore(); + }) + .then(done, done.fail); + }); + + it('@gl draws every disc at once on settle()', (done) => { + let log; + plot({ minpoints: 1000, budget: 200, settle: 100000 }) + .then(() => { + return wait(800); + }) + .then(() => { + return moveCamera(1.7); + }) + .then(() => { + return when('preview'); + }) + .then(() => { + log = watch3d(); + scene().getLOD().settle(); + expect(scene().getLOD().state).toBe('full'); + expect(log.arrays.indexOf(1000)).not.toBe(-1); + expect(log.elements.length).toBe(0); + log.restore(); + }) + .then(done, done.fail); + }); + + it('@gl is off without scene.lod, below minpoints and in a static plot', (done) => { + let log; + plot(null) + .then(() => { + return wait(800); + }) + .then(() => { + expect(gd._fullLayout.scene.lod).toBeUndefined(); + expect(scene().getLOD().state).toBe('off'); + log = watch3d(); + return moveCamera(1.7); + }) + .then(() => { + return wait(150); + }) + .then(() => { + expect(log.elements.length).toBe(0); + expect(log.arrays.indexOf(1000)).not.toBe(-1); + expect(events.length).toBe(0); + log.restore(); + return plot({ minpoints: 5000, budget: 200 }); + }) + .then(() => { + return wait(800); + }) + .then(() => { + return moveCamera(1.7); + }) + .then(() => { + return wait(150); + }) + .then(() => { + expect(scene().getLOD().state).toBe('off'); + expect(scene().getLOD().total).toBe(1501); + return plot(LOD, { staticPlot: true }); + }) + .then(() => { + expect(glplot().lod).toBe(null); + }) + .then(done, done.fail); + }); +}); diff --git a/test/jasmine/tests/gl3dlayout_test.js b/test/jasmine/tests/gl3dlayout_test.js index 75d271f7b6c..69812bfda4e 100644 --- a/test/jasmine/tests/gl3dlayout_test.js +++ b/test/jasmine/tests/gl3dlayout_test.js @@ -341,6 +341,36 @@ describe('Test Gl3d layout defaults', function() { .toBe('closest', 'to default if not valid'); }); + it('should coerce oit', function() { + layoutIn = { scene: {} }; + supplyLayoutDefaults(layoutIn, layoutOut, fullData); + expect(layoutOut.scene.oit).toBe('off', 'to off by default'); + + layoutIn = { scene: { oit: 'auto' } }; + supplyLayoutDefaults(layoutIn, layoutOut, fullData); + expect(layoutOut.scene.oit).toBe('auto', 'to user val if valid'); + + layoutIn = { scene: { oit: 'sorted' } }; + supplyLayoutDefaults(layoutIn, layoutOut, fullData); + expect(layoutOut.scene.oit).toBe('off', 'to off if invalid'); + }); + + it('should coerce markerrender', function() { + layoutIn = { scene: {} }; + supplyLayoutDefaults(layoutIn, layoutOut, fullData); + expect(layoutOut.scene.markerrender).toBe('glyph', 'to glyph by default'); + + ['auto', 'disc', 'glyph'].forEach(function(v) { + layoutIn = { scene: { markerrender: v } }; + supplyLayoutDefaults(layoutIn, layoutOut, fullData); + expect(layoutOut.scene.markerrender).toBe(v, 'to user val if valid'); + }); + + layoutIn = { scene: { markerrender: 'sphere' } }; + supplyLayoutDefaults(layoutIn, layoutOut, fullData); + expect(layoutOut.scene.markerrender).toBe('glyph', 'to glyph if invalid'); + }); + it('should add data-only scenes into layoutIn', function() { layoutIn = {}; fullData = [{ type: 'scatter3d', scene: 'scene' }]; diff --git a/test/jasmine/tests/plot_api_test.js b/test/jasmine/tests/plot_api_test.js index 40c75212cda..8b2431109b4 100644 --- a/test/jasmine/tests/plot_api_test.js +++ b/test/jasmine/tests/plot_api_test.js @@ -754,6 +754,55 @@ describe('Test plot api', function () { }) .then(done, done.fail); }); + + it('should trigger replot (but not recalc) on constrained axis range updates when every trace is regl', (done) => { + function regl(layout) { + return mock({ + data: [{type: 'scattergl', x: [1, 2, 3], y: [1, 2, 1]}], + layout: layout + }); + } + function fixed() { + return {xaxis: {range: [0, 4]}, yaxis: {range: [0, 3], scaleanchor: 'x'}}; + } + + gd = regl(fixed()); + Plotly.relayout(gd, 'xaxis.range', [1, 3]) + .then(() => { + expectReplot('range'); + + gd = regl(fixed()); + return Plotly.relayout(gd, {'xaxis.range': [1, 3], 'yaxis.range': [0, 2]}); + }) + .then(() => { + expectReplot('both ranges'); + + gd = regl({xaxis: {}, yaxis: {range: [0, 3], scaleanchor: 'x'}}); + return Plotly.relayout(gd, 'yaxis.range', [0, 2]); + }) + .then(() => { + expect(gd.calcdata).toBeUndefined('an axis of the group autoranges'); + + gd = regl(fixed()); + return Plotly.relayout(gd, 'xaxis.autorange', true); + }) + .then(() => { + expect(gd.calcdata).toBeUndefined('autorange'); + + gd = mock({ + data: [ + {type: 'scattergl', x: [1, 2, 3], y: [1, 2, 1]}, + {x: [1, 2, 3], y: [2, 1, 2]} + ], + layout: fixed() + }); + return Plotly.relayout(gd, 'xaxis.range', [1, 3]); + }) + .then(() => { + expect(gd.calcdata).toBeUndefined('a trace that is not regl'); + }) + .then(done, done.fail); + }); }); describe('Plotly.restyle subroutines switchboard', function () { diff --git a/test/jasmine/tests/scatter3d_test.js b/test/jasmine/tests/scatter3d_test.js index a5f1a7f8b4d..ebd53bbbbdc 100644 --- a/test/jasmine/tests/scatter3d_test.js +++ b/test/jasmine/tests/scatter3d_test.js @@ -9,6 +9,7 @@ var createGraphDiv = require('../assets/create_graph_div'); var destroyGraphDiv = require('../assets/destroy_graph_div'); var delay = require('../assets/delay'); +var mouseEvent = require('../assets/mouse_event'); function countCanvases() { return d3SelectAll('canvas').size(); @@ -77,6 +78,11 @@ describe('Scatter3D defaults', function() { expect(out.marker.line.color).toBe(Color.defaultLine); }); + it('should default alwaysontop to false', function() { + expect(_supply(Lib.extendFlat({}, base)).alwaysontop).toBe(false); + expect(_supply(Lib.extendFlat({ alwaysontop: true }, base)).alwaysontop).toBe(true); + }); + it('should inherit layout.calendar', function() { var out = _supply(base, {calendar: 'islamic'}); @@ -285,6 +291,40 @@ describe('Test scatter3d interactions:', function() { .then(done, done.fail); }); + it('@gl should allocate glyph outline vertices only when marker.line.width is above 0', function(done) { + var obj; + var fillCount; + + Plotly.newPlot(gd, [{ + type: 'scatter3d', + mode: 'markers', + x: [1, 2, 3], + y: [2, 3, 1], + z: [3, 1, 2], + marker: {symbol: 'square', size: 10} + }]) + .then(function() { + obj = gd._fullLayout.scene._scene.glplot.objects[0]; + + fillCount = obj.vertexCount; + + expect(fillCount).toBeGreaterThan(0, '# of fill vertices'); + expect(obj.lineVertexCount).toBe(0, '# of outline vertices, no outline'); + + return Plotly.restyle(gd, 'marker.line.width', 2); + }) + .then(function() { + expect(obj.vertexCount).toBe(fillCount, '# of fill vertices'); + expect(obj.lineVertexCount).toBeGreaterThan(0, '# of outline vertices, with outline'); + + return Plotly.restyle(gd, 'marker.line.width', 0); + }) + .then(function() { + expect(obj.lineVertexCount).toBe(0, '# of outline vertices, outline removed'); + }) + .then(done, done.fail); + }); + it('@gl should only accept texts for textposition otherwise textposition is set to middle center before passing to webgl', function(done) { Plotly.newPlot(gd, [{ type: 'scatter3d', @@ -345,4 +385,972 @@ describe('Test scatter3d interactions:', function() { }) .then(done, done.fail); }); + + describe('order independent transparency', function() { + // a red marker at z=+0.5 and a blue marker at z=-0.5 on the line of sight + function plot(eyez, opacity, oit, markerrender) { + const scene = { + xaxis: { range: [-1, 1], visible: false }, + yaxis: { range: [-1, 1], visible: false }, + zaxis: { range: [-1, 1], visible: false }, + bgcolor: 'white', + aspectmode: 'cube', + camera: { + eye: { x: 0, y: 0, z: eyez }, + up: { x: 0, y: 1, z: 0 }, + projection: { type: 'orthographic' } + } + }; + if (oit) scene.oit = oit; + if (markerrender) scene.markerrender = markerrender; + return Plotly.react( + gd, + [ + { + type: 'scatter3d', + mode: 'markers', + x: [0, 0], + y: [0, 0], + z: [0.5, -0.5], + marker: { size: 60, opacity: opacity, color: ['red', 'blue'], line: { width: 0 } } + } + ], + { + width: 400, + height: 400, + margin: { l: 0, r: 0, t: 0, b: 0 }, + paper_bgcolor: 'white', + uirevision: Math.random(), + scene: scene + } + ).then(delay(400)); + } + + const glplot = () => gd._fullLayout.scene._scene.glplot; + const status = () => gd._fullLayout.scene._scene.getOITStatus(); + + function readPixels() { + const gl = glplot().gl; + glplot().redraw(); + const px = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4); + gl.readPixels(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight, gl.RGBA, gl.UNSIGNED_BYTE, px); + return px; + } + + // mean colour of the 11 by 11 pixels at the centre + function centre() { + const gl = glplot().gl; + glplot().redraw(); + const px = new Uint8Array(11 * 11 * 4); + gl.readPixels((gl.drawingBufferWidth / 2 | 0) - 5, (gl.drawingBufferHeight / 2 | 0) - 5, 11, 11, gl.RGBA, gl.UNSIGNED_BYTE, px); + const mean = [0, 0, 0]; + for (let i = 0; i < 121; i++) for (let c = 0; c < 3; c++) mean[c] += px[4 * i + c] / 121; + return mean; + } + + function expectNear(got, want) { + for (let i = 0; i < 3; i++) expect(got[i]).toBeCloseTo(want[i], -0.8, 'channel ' + i + ': ' + got + ' vs ' + want); + } + + afterEach(function() { + window.__plotlyOITTestHooks = null; + }); + + it('@gl scene.oit auto orders red over blue from either side', function(done) { + plot(2.5, 0.5, 'auto') + .then(function() { + expect(status().mode).toBe('D'); + expectNear(centre(), [192, 64, 128]); + return plot(-2.5, 0.5, 'auto'); + }) + .then(function() { + expectNear(centre(), [128, 64, 192]); + }) + .then(done, done.fail); + }); + + it('@gl scene.oit auto orders red over blue from either side for disc markers', function(done) { + const disc = () => gd._fullLayout.scene._scene.traces[gd._fullData[0].uid].scatterPlot.discActive; + plot(2.5, 0.5, 'auto', 'disc') + .then(function() { + expect(disc()).toBe(true); + expect(status().mode).toBe('D'); + expectNear(centre(), [192, 64, 128]); + return plot(-2.5, 0.5, 'auto', 'disc'); + }) + .then(function() { + expect(disc()).toBe(true); + expectNear(centre(), [128, 64, 192]); + }) + .then(done, done.fail); + }); + + it('@gl scene.oit auto gives the exact over operator at opacity 0.3 and 0.8', function(done) { + plot(2.5, 0.3, 'auto') + .then(function() { + expectNear(centre(), [201, 125, 179]); + return plot(2.5, 0.8, 'auto'); + }) + .then(function() { + expectNear(centre(), [214, 10, 51]); + }) + .then(done, done.fail); + }); + + it('@gl scene.oit off blends in draw order and opaque scenes skip the new passes', function(done) { + plot(2.5, 0.5) + .then(function() { + expect(status().mode).toBe('legacy'); + expect(status().reason).toBe('off'); + expectNear(centre(), [128, 64, 192]); + return plot(2.5, 1, 'auto'); + }) + .then(function() { + expect(status().mode).toBe('none'); + }) + .then(done, done.fail); + }); + + it('@gl scene.oit auto falls back to the draw order pass without float render targets', function(done) { + let off; + const events = []; + plot(2.5, 0.5, 'off') + .then(function() { + off = readPixels(); + window.__plotlyOITTestHooks = { disableExt: ['WEBGL_color_buffer_float', 'EXT_color_buffer_half_float'] }; + gd.on('plotly_oitstatus', (s) => events.push(s)); + glplot().resetOIT(); + glplot().setOIT('auto'); + }) + .then(delay(200)) + .then(function() { + expect(status().mode).toBe('legacy'); + expect(status().tier).toBe(4); + expect(status().reason).toBe('no-float-target'); + expect(events.length).toBeGreaterThan(0); + const px = readPixels(); + let diff = 0; + for (let i = 0; i < px.length; i++) if (px[i] !== off[i]) diff++; + expect(diff).toBe(0, 'the last tier must equal the draw order pixels'); + }) + .then(done, done.fail); + }); + + it('@gl scene.oit auto falls back when the render targets cannot be allocated', function(done) { + plot(2.5, 0.5, 'off') + .then(function() { + window.__plotlyOITTestHooks = { failAlloc: true }; + glplot().resetOIT(); + glplot().setOIT('auto'); + }) + .then(delay(200)) + .then(function() { + expect(status().mode).toBe('legacy'); + expect(status().reason).toBe('alloc-failed'); + }) + .then(done, done.fail); + }); + + it('@gl scene.oit auto uses global depth nodes without MIN blending', function(done) { + window.__plotlyOITTestHooks = { disableExt: ['EXT_blend_minmax'] }; + plot(2.5, 0.5, 'auto') + .then(function() { + expect(status().mode).toBe('D2'); + expect(status().reason).toBe('no-minmax-anchor'); + expectNear(centre(), [192, 64, 128]); + }) + .then(done, done.fail); + }); + + it('@gl scene.oit auto without multiple render targets takes extra passes for the same picture', function(done) { + let ref; + plot(2.5, 0.5, 'auto') + .then(function() { + ref = readPixels(); + window.__plotlyOITTestHooks = { disableExt: ['WEBGL_draw_buffers'] }; + glplot().resetOIT(); + glplot().setOIT('auto'); + }) + .then(delay(200)) + .then(function() { + expect(status().mrt).toBe(false); + expect(status().passes).toBeGreaterThan(3); + const px = readPixels(); + let worst = 0; + for (let i = 0; i < px.length; i++) worst = Math.max(worst, Math.abs(px[i] - ref[i])); + expect(worst).not.toBeGreaterThan(1); + }) + .then(done, done.fail); + }); + + it('@gl scene.oit switches at run time and emits plotly_oitstatus', function(done) { + const modes = []; + plot(2.5, 0.5, 'off') + .then(function() { + gd.on('plotly_oitstatus', (s) => modes.push(s.mode)); + return Plotly.relayout(gd, 'scene.oit', 'auto'); + }) + .then(delay(300)) + .then(function() { + expect(status().mode).toBe('D'); + expect(modes).toContain('D'); + expectNear(centre(), [192, 64, 128]); + }) + .then(done, done.fail); + }); + }); + + describe('alwaysontop', function() { + const W = 300; + const H = 300; + + // 3000 translucent red markers around the origin and one opaque black marker behind most of them + function traces(top, onlyMarker) { + const x = []; + const y = []; + const z = []; + let seed = 7; + const rnd = () => { + seed = (seed * 16807) % 2147483647; + return seed / 2147483647 - 0.5; + }; + for (let i = 0; i < 3000; i++) { + x.push(rnd() * 1.6); + y.push(rnd() * 1.6); + z.push(rnd() * 1.6); + } + const cloud = { + type: 'scatter3d', + mode: 'markers', + x: x, + y: y, + z: z, + hoverinfo: 'skip', + marker: { size: 8, color: 'rgb(220,40,40)', opacity: 0.6, line: { width: 0 } } + }; + const focus = { + type: 'scatter3d', + mode: 'markers', + x: [0], + y: [0], + z: [-0.3], + alwaysontop: top, + marker: { size: 30, color: 'black', line: { width: 0 } } + }; + return onlyMarker ? [focus] : [cloud, focus]; + } + + function plot(data, oit) { + return Plotly.react(gd, data, { + width: W, + height: H, + margin: { l: 0, r: 0, t: 0, b: 0 }, + paper_bgcolor: 'white', + showlegend: false, + uirevision: Math.random(), + scene: { + oit: oit, + bgcolor: 'white', + xaxis: { range: [-1, 1], visible: false }, + yaxis: { range: [-1, 1], visible: false }, + zaxis: { range: [-1, 1], visible: false }, + aspectmode: 'cube', + camera: { + eye: { x: 0, y: 0, z: 2.5 }, + up: { x: 0, y: 1, z: 0 }, + projection: { type: 'orthographic' } + } + } + }).then(delay(400)); + } + + function pixels() { + const glplot = gd._fullLayout.scene._scene.glplot; + const gl = glplot.gl; + glplot.redraw(); + const px = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4); + gl.readPixels(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight, gl.RGBA, gl.UNSIGNED_BYTE, px); + return { w: gl.drawingBufferWidth, h: gl.drawingBufferHeight, px: px }; + } + + const isBlack = (p, i) => p.px[4 * i] === 0 && p.px[4 * i + 1] === 0 && p.px[4 * i + 2] === 0; + + ['off', 'auto'].forEach(function(oit) { + it('@gl draws the marker on top of the translucent cloud with scene.oit ' + oit, function(done) { + let without; + let footprint; + plot(traces(false), oit) + .then(function() { + without = pixels(); + return plot(traces(false, true), oit); + }) + .then(function() { + const p = pixels(); + footprint = []; + for (let i = 0; i < p.w * p.h; i++) footprint.push(isBlack(p, i)); + const covered = footprint.filter(Boolean).length; + expect(covered).toBeGreaterThan(400); + const hidden = footprint.filter((f, i) => f && !isBlack(without, i)).length; + expect(hidden).toBeGreaterThan(covered * 0.5); + return plot(traces(true), oit); + }) + .then(function() { + const withTop = pixels(); + const notBlack = footprint.filter((f, i) => f && !isBlack(withTop, i)).length; + expect(notBlack).toBe(0, 'every pixel of the marker shows its own color'); + + // outside the marker, dilated by 2 px for the soft edge, nothing changes + let changed = 0; + for (let i = 0; i < withTop.w * withTop.h; i++) { + const cx = i % withTop.w; + const cy = (i / withTop.w) | 0; + let near = false; + for (let dy = -2; dy <= 2 && !near; dy++) { + for (let dx = -2; dx <= 2; dx++) { + if (footprint[(cy + dy) * withTop.w + cx + dx]) { + near = true; + break; + } + } + } + if (near) continue; + for (let c = 0; c < 3; c++) { + if (withTop.px[4 * i + c] !== without.px[4 * i + c]) { + changed++; + break; + } + } + } + expect(changed).toBe(0, 'pixels outside the marker are unchanged'); + }) + .then(done, done.fail); + }); + }); + + it('@gl a marker with alwaysontop stays pickable', function(done) { + const hovered = []; + plot(traces(true, true), 'off') + .then(function() { + gd.on('plotly_hover', (e) => hovered.push(e.points[0].curveNumber)); + }) + .then(delay(20)) + .then(function() { + mouseEvent('mouseover', 0, 0); + mouseEvent('mouseover', W / 2, H / 2); + }) + .then(delay(100)) + .then(function() { + expect(hovered.length).toBeGreaterThan(0); + }) + .then(done, done.fail); + }); + }); + + describe('circle markers as discs:', function() { + function point(marker, extra) { + return Lib.extendFlat({ + type: 'scatter3d', + mode: 'markers', + x: [1, 2, 3], + y: [2, 3, 1], + z: [3, 1, 2], + marker: marker + }, extra || {}); + } + + function scatterPlot() { + return gd._fullLayout.scene._scene.traces[gd._fullData[0].uid].scatterPlot; + } + + function plot(marker, markerrender, extra) { + return Plotly.newPlot(gd, [point(marker, extra)], {scene: {markerrender: markerrender}}); + } + + it('@gl should draw glyph meshes by default', function(done) { + Plotly.newPlot(gd, [point({size: 10})]) + .then(function() { + expect(scatterPlot().discActive).toBe(false); + expect(scatterPlot().vertexCount).toBeGreaterThan(3, '# of vertices'); + }) + .then(done, done.fail); + }); + + it('@gl should draw one vertex per circle with markerrender auto and disc, and a glyph mesh with glyph', function(done) { + plot({size: 10}, 'auto') + .then(function() { + var o = scatterPlot(); + expect(o.discActive).toBe(true, 'auto'); + expect(o.vertexCount).toBe(3, 'auto, # of vertices'); + expect(o.lineVertexCount).toBe(0, 'auto, # of outline vertices'); + return plot({size: 10}, 'disc'); + }) + .then(function() { + expect(scatterPlot().discActive).toBe(true, 'disc'); + expect(scatterPlot().vertexCount).toBe(3, 'disc, # of vertices'); + return plot({size: 10}, 'glyph'); + }) + .then(function() { + var o = scatterPlot(); + expect(o.discActive).toBe(false, 'glyph'); + expect(o.vertexCount).toBeGreaterThan(3, 'glyph, # of vertices'); + }) + .then(done, done.fail); + }); + + it('@gl should switch between disc and glyph on relayout', function(done) { + plot({size: 10}, 'disc') + .then(function() { + expect(scatterPlot().discActive).toBe(true); + return Plotly.relayout(gd, 'scene.markerrender', 'glyph'); + }) + .then(function() { + expect(scatterPlot().discActive).toBe(false); + return Plotly.relayout(gd, 'scene.markerrender', 'auto'); + }) + .then(function() { + expect(scatterPlot().discActive).toBe(true); + }) + .then(done, done.fail); + }); + + it('@gl should fall back to glyphs, with a reason, where a disc cannot draw the marker', function(done) { + plot({size: 10, symbol: 'square'}, 'disc') + .then(function() { + expect(scatterPlot().discActive).toBe(false, 'square'); + expect(scatterPlot().discBlocker).toBe('symbol is not circle or circle-open', 'square'); + return plot({size: 10}, 'disc', {projection: {z: {show: true}}}); + }) + .then(function() { + expect(scatterPlot().discActive).toBe(false, 'projection'); + expect(scatterPlot().discBlocker).toBe('axes projection', 'projection'); + return plot({size: 5000}, 'disc'); + }) + .then(function() { + expect(scatterPlot().discActive).toBe(false, 'oversize'); + expect(scatterPlot().discBlocker).toMatch(/exceeds point size cap/, 'oversize'); + }) + .then(done, done.fail); + }); + + it('@gl should draw circle-open and marker.line as discs', function(done) { + plot({size: 10, symbol: 'circle-open'}, 'disc') + .then(function() { + expect(scatterPlot().discActive).toBe(true, 'circle-open'); + return plot({size: 10, line: {width: 2, color: 'black'}}, 'disc'); + }) + .then(function() { + expect(scatterPlot().discActive).toBe(true, 'marker.line'); + expect(scatterPlot().vertexCount).toBe(3, 'marker.line, # of vertices'); + }) + .then(done, done.fail); + }); + + it('@gl should draw marker.line.width as requested, not clamped to the GL line width range', function(done) { + plot({size: 40, color: 'red', line: {color: 'cyan', width: 6}}, 'disc') + .then(function() { + var o = scatterPlot(); + expect(o.discActive).toBe(true); + expect(o._discLineHalf(2)).toBe(6); + expect(o._discLineHalf(1)).toBe(3); + return Plotly.restyle(gd, 'marker.line.width', 0); + }) + .then(function() { + expect(scatterPlot()._discLineHalf(2)).toBe(0); + }) + .then(done, done.fail); + }); + + it('@gl should keep a transparent fill with an opaque outline in the opaque pass', function(done) { + plot({size: 40, color: 'rgba(0,0,0,0)', line: {color: 'cyan', width: 2}}, 'disc') + .then(function() { + expect(scatterPlot().discActive).toBe(true); + expect(scatterPlot().hasAlpha).toBe(false, 'ring'); + return Plotly.restyle(gd, 'marker.line.width', 0); + }) + .then(function() { + expect(scatterPlot().hasAlpha).toBe(true, 'no outline'); + return Plotly.restyle(gd, {'marker.color': 'rgba(255,0,0,0.5)', 'marker.line.width': 2}); + }) + .then(function() { + expect(scatterPlot().hasAlpha).toBe(true, 'half transparent fill'); + }) + .then(done, done.fail); + }); + + ['disc', 'glyph'].forEach(function(markerrender) { + it('@gl should pick the original point number past a missing point with markerrender ' + markerrender, function(done) { + var hover; + + Plotly.newPlot(gd, [{ + type: 'scatter3d', + mode: 'markers', + x: [null, 0], + y: [0, 0], + z: [0, 0], + marker: {size: 20} + }], { + width: 400, + height: 400, + margin: {l: 0, r: 0, t: 0, b: 0}, + scene: { + markerrender: markerrender, + xaxis: {range: [-1, 1]}, + yaxis: {range: [-1, 1]}, + zaxis: {range: [-1, 1]}, + camera: {projection: {type: 'orthographic'}} + } + }) + .then(delay(20)) + .then(function() { + gd.on('plotly_hover', function(eventData) { hover = eventData.points[0]; }); + mouseEvent('mouseover', 0, 0); + mouseEvent('mouseover', 200, 200); + }) + .then(delay(100)) + .then(function() { + expect(hover).toBeDefined('hover fired'); + expect(hover.pointNumber).toBe(1, 'point number'); + }) + .then(done, done.fail); + }); + }); + }); +}); + +describe('Test scatter3d typed positions:', function() { + var DISC = {scene: {markerrender: 'disc'}}; + + function f32(n, seed) { + var a = new Float32Array(n); + var s = seed; + for(var i = 0; i < n; i++) { + s = (s * 1664525 + 1013904223) >>> 0; + a[i] = s / 4294967296; + } + return a; + } + + function cloud10(n, extra, seed) { + seed = seed || 0; + var t = {type: 'scatter3d', mode: 'markers', x: f32(n, 1 + seed), y: f32(n, 2 + seed), z: f32(n, 3 + seed), + marker: {size: 10, color: 'blue', line: {width: 0}}}; + for(var k in extra) t[k] = extra[k]; + return t; + } + + describe('scatter3d flat typed positions', function() { + var gd; + + beforeEach(function() { gd = createGraphDiv(); }); + afterEach(function() { + Plotly.purge(gd); + destroyGraphDiv(); + }); + + function cloud(n, extra) { + var t = {type: 'scatter3d', mode: 'markers', x: f32(n, 1), y: f32(n, 2), z: f32(n, 3), + marker: {size: 4, color: 'blue', line: {width: 0}}}; + for(var k in extra) t[k] = extra[k]; + return t; + } + function obj(i) { return gd._fullLayout.scene._scene.traces[gd._fullData[i].uid].scatterPlot; } + + it('@gl draws typed x, y and z from one Float32Array with constant colour and size', function(done) { + Plotly.newPlot(gd, [cloud(1000)], DISC) + .then(function() { + var o = obj(0); + expect(o.discActive).toBe(true); + expect(o.points instanceof Float32Array).toBe(true); + expect(o.points.length).toBe(3000); + expect(o.discConst).toBeTruthy(); + expect(o.discConst.noPick).toBe(false); + expect(o.vertexCount).toBe(1000); + }) + .then(done, done.fail); + }); + + it('@gl drops NaN points and keeps the original index for picking', function(done) { + var t = cloud(10); + t.x[3] = NaN; + Plotly.newPlot(gd, [t], DISC) + .then(function() { + var o = obj(0); + expect(o.pointCount).toBe(10); + expect(o.vertexCount).toBe(9); + var sel = {id: o.pickId, value: [0, 0, 7]}; + var r = o.pick(sel); + expect(r.index).toBe(7); + expect(r.position[1]).toBe(o.points[22]); + }) + .then(done, done.fail); + }); + + it('@gl keeps neither pick ids nor positions for hoverinfo skip', function(done) { + Plotly.newPlot(gd, [cloud(1000, {hoverinfo: 'skip'})], DISC) + .then(function() { + var o = obj(0); + expect(o.discConst.noPick).toBe(true); + expect(o.points).toBe(null); + expect(o.pick({id: o.pickId, value: [0, 0, 1]})).toBe(null); + }) + .then(done, done.fail); + }); + + it('@gl falls back to per-point arrays for per-point colours and other symbols', function(done) { + var c = []; + for(var i = 0; i < 100; i++) c.push(i % 2 ? 'red' : 'blue'); + Plotly.newPlot(gd, [ + cloud(100, {marker: {color: c, size: 4, line: {width: 0}}}), + cloud(100, {marker: {symbol: 'square', size: 4, color: 'red', line: {width: 0}}}) + ], DISC) + .then(function() { + expect(obj(0).discActive).toBe(true); + expect(obj(0).discConst).toBe(null); + expect(Array.isArray(obj(0).points)).toBe(true); + expect(obj(1).discActive).toBe(false); + expect(Array.isArray(obj(1).points)).toBe(true); + }) + .then(done, done.fail); + }); + + it('@gl draws typed arrays as glyphs with the default markerrender', function(done) { + Plotly.newPlot(gd, [cloud(100)]) + .then(function() { + expect(gd._fullLayout.scene.markerrender).toBe('glyph'); + expect(obj(0).discActive).toBe(false); + expect(obj(0).flatState).toBe(null); + expect(Array.isArray(obj(0).points)).toBe(true); + expect(obj(0).points.length).toBe(100); + return Plotly.restyle(gd, 'marker.color', 'red'); + }) + .then(function() { + expect(obj(0).positionsMissing).toBe(false); + expect(obj(0).points.length).toBe(100); + }) + .then(done, done.fail); + }); + + it('@gl takes the per-point path for plain arrays', function(done) { + var t = cloud(100); + t.x = Array.from(t.x); + Plotly.newPlot(gd, [t], DISC) + .then(function() { + expect(Array.isArray(obj(0).points)).toBe(true); + expect(obj(0).discConst).toBe(null); + }) + .then(done, done.fail); + }); + }); + + describe('scatter3d typed bounds, one scan', function() { + var gd; + + beforeEach(function() { gd = createGraphDiv(); }); + afterEach(function() { + Plotly.purge(gd); + destroyGraphDiv(); + }); + + function cloud(n, seed) { + return {type: 'scatter3d', mode: 'markers', x: f32(n, seed), y: f32(n, seed + 1), z: f32(n, seed + 2), + marker: {size: 4, color: 'blue', line: {width: 0}}}; + } + function scene() { return gd._fullLayout.scene._scene; } + function obj(i) { return scene().traces[gd._fullData[i].uid].scatterPlot; } + // the bounds the per-point path gives: the finite points, scaled as doubles + function expected(t, len) { + var s = scene().dataScale; + var lo = [Infinity, Infinity, Infinity]; + var hi = [-Infinity, -Infinity, -Infinity]; + for(var i = 0; i < len; i++) { + var p = [t.x[i] * s[0], t.y[i] * s[1], t.z[i] * s[2]]; + if(isFinite(p[0]) && isFinite(p[1]) && isFinite(p[2])) { + for(var d = 0; d < 3; d++) { + if(p[d] < lo[d]) lo[d] = p[d]; + if(p[d] > hi[d]) hi[d] = p[d]; + } + } + } + return [lo, hi]; + } + + it('@gl gives the bounds of the per-point path for finite data, NaN data and arrays of unequal length', function(done) { + var a = cloud(500, 1); + var b = cloud(500, 11); + b.y[7] = NaN; + b.x[499] = 50; + b.z[499] = NaN; + var c = cloud(300, 21); + c.x = f32(400, 31); + Plotly.newPlot(gd, [a, b, c], DISC) + .then(function() { + expect(gd._fullData[0]._typedBounds).toBeTruthy(); + expect(gd._fullData[1]._typedBounds).toBe(null, 'a trace with a NaN keeps its own scan'); + expect(gd._fullData[2]._typedBounds).toBeUndefined('unequal lengths keep the scan per axis'); + expect(obj(0).bounds).toEqual(expected(a, 500)); + expect(obj(1).bounds).toEqual(expected(b, 500)); + expect(obj(2).bounds).toEqual(expected(c, 300)); + // the scene's scale counts every finite coordinate, as before: x = 50 of the point whose z is NaN + expect(scene().dataScale[0]).toBeCloseTo(1 / 50, 3); + expect(obj(0).vertexCount).toBe(500); + expect(obj(1).vertexCount).toBe(498); + }) + .then(done, done.fail); + }); + + it('@gl keeps the scan while the same buffer ranges and datarevision come again', function(done) { + var a = cloud(500, 1); + var first; + function scan() { return scene()._typedBounds[gd._fullData[0].uid]; } + Plotly.newPlot(gd, [a], {datarevision: 1, scene: {markerrender: 'disc'}}) + .then(function() { + first = scan(); + return Plotly.restyle(gd, 'marker.color', 'red'); + }) + .then(function() { + expect(scan()).toBe(first); + // new view objects of the same range are the same data + return Plotly.restyle(gd, {x: [a.x.subarray(0)], y: [a.y.subarray(0)], z: [a.z.subarray(0)]}); + }) + .then(function() { + expect(scan()).toBe(first); + a.x[3] = 9; + return Plotly.relayout(gd, 'datarevision', 2); + }) + .then(function() { + expect(scan()).not.toBe(first); + expect(scan().hi[0]).toBe(9); + first = scan(); + return Plotly.restyle(gd, {x: [f32(500, 77)]}); + }) + .then(function() { + expect(scan()).not.toBe(first); + expect(scan().hi[0]).toBeLessThan(1); + }) + .then(done, done.fail); + }); + }); + + describe('scatter3d positions kept across edits', function() { + var gd; + var N = 2000; + + beforeEach(function() { gd = createGraphDiv(); }); + afterEach(function() { + Plotly.purge(gd); + destroyGraphDiv(); + }); + + function scene() { return gd._fullLayout.scene._scene; } + function obj(i) { return scene().traces[gd._fullData[i].uid].scatterPlot; } + function layout() { + return {width: 600, height: 400, margin: {l: 0, r: 0, t: 0, b: 0}, showlegend: false, scene: {markerrender: 'disc'}}; + } + // bytes given to the GPU by a step + function uploaded(step) { + var gl = scene().glplot.gl; + var bytes = 0; + var bd = gl.bufferData; + var bsd = gl.bufferSubData; + gl.bufferData = function(t, d) { + if(d && d.byteLength) bytes += d.byteLength; + return bd.apply(this, arguments); + }; + gl.bufferSubData = function(t, o, d) { + if(d && d.byteLength) bytes += d.byteLength; + return bsd.apply(this, arguments); + }; + return Promise.resolve(step()).then(function() { + gl.bufferData = bd; + gl.bufferSubData = bsd; + return bytes; + }); + } + function expectKept(step, msg) { + var before = obj(0).flatState.kept; + var buffer = obj(0).pointBuffer.handle; + return uploaded(step).then(function(bytes) { + // nothing per point (the first translucent frame makes the 24 bytes of a full-screen triangle) + expect(bytes).toBeLessThan(100, msg); + expect(obj(0).flatState.kept).toBe(before + 1, msg); + expect(obj(0).pointBuffer.handle).toBe(buffer, msg); + expect(obj(0).discActive).toBe(true, msg); + }); + } + function expectSent(step, atLeast, msg) { + return uploaded(step).then(function(bytes) { + expect(bytes).not.toBeLessThan(atLeast, msg); + expect(obj(0).positionsMissing).toBe(false, msg); + }); + } + + [false, true].forEach(function(skip) { + var extra = skip ? {hoverinfo: 'skip'} : {}; + var name = skip ? ' (hoverinfo skip)' : ''; + + it('@gl colour, size, opacity and layout edits upload nothing' + name, function(done) { + var a = cloud10(N, extra); + Plotly.newPlot(gd, [a, cloud10(N, extra, 7)], layout()) + .then(function() { + return expectKept(function() { return Plotly.restyle(gd, 'marker.color', 'red', [0]); }, 'colour'); + }) + .then(function() { + expect(obj(0).discConst.color.slice(0, 3)).toEqual([1, 0, 0]); + return expectKept(function() { return Plotly.restyle(gd, 'marker.size', 6); }, 'size'); + }) + .then(function() { + expect(obj(0).discConst.size).not.toBe(10); + return expectKept(function() { return Plotly.restyle(gd, 'marker.opacity', 0.5); }, 'opacity'); + }) + .then(function() { + expect(obj(0).hasAlpha).toBe(true); + return expectKept(function() { return Plotly.relayout(gd, 'scene.bgcolor', '#eee'); }, 'background'); + }) + .then(function() { + // new view objects of the same buffer ranges are the same data + return expectKept(function() { + return Plotly.restyle(gd, {x: [a.x.subarray(0)], y: [a.y.subarray(0)], z: [a.z.subarray(0)]}, [0]); + }, 'new views'); + }) + .then(function() { + expect(obj(0).vertexCount).toBe(N); + expect(obj(0).points === null).toBe(skip); + }) + .then(done, done.fail); + }); + + it('@gl new data, a new scale, datarevision and other marker paths send the positions' + name, function(done) { + var a = cloud10(N, extra); + var P = 12 * N; + Plotly.newPlot(gd, [a], layout()) + .then(function() { + return expectSent(function() { return Plotly.restyle(gd, {x: [f32(N, 99)]}, [0]); }, P, 'new array'); + }) + .then(function() { + expect(obj(0).flatState.kept).toBe(0); + var x2 = f32(N, 99); + x2[0] = 3; + return expectSent(function() { return Plotly.restyle(gd, {x: [x2]}, [0]); }, P, 'new scale'); + }) + .then(function() { + gd.data[0].y[5] = 0.123; + return expectSent(function() { return Plotly.relayout(gd, 'datarevision', 5); }, P, 'datarevision'); + }) + .then(function() { + expect(obj(0).flatState.kept).toBe(0); + return expectSent(function() { return Plotly.restyle(gd, 'marker.line.width', 2); }, P, 'outline'); + }) + .then(function() { + expect(obj(0).discOutline).toBe(true); + // an outlined cloud keeps nothing + return expectSent(function() { return Plotly.restyle(gd, 'marker.color', 'green'); }, P, 'colour with outline'); + }) + .then(function() { + return expectSent(function() { return Plotly.restyle(gd, 'marker.line.width', 0); }, P, 'outline off'); + }) + .then(function() { + var colours = []; + for(var i = 0; i < N; i++) colours.push(i % 2 ? 'red' : 'blue'); + return expectSent(function() { return Plotly.restyle(gd, {'marker.color': [colours]}); }, P, 'colour array'); + }) + .then(function() { + expect(obj(0).discConst).toBe(null); + expect(obj(0).flatState).toBe(null); + return expectSent(function() { return Plotly.restyle(gd, 'marker.color', 'blue'); }, P, 'back to one colour'); + }) + .then(function() { + expect(obj(0).flatState.kept).toBe(0); + return expectSent(function() { return Plotly.restyle(gd, 'marker.symbol', 'square'); }, P, 'glyph symbol'); + }) + .then(function() { + expect(obj(0).discActive).toBe(false); + return expectSent(function() { return Plotly.restyle(gd, 'marker.symbol', 'circle'); }, P, 'back to discs'); + }) + .then(function() { + expect(obj(0).discActive).toBe(true); + return expectSent(function() { + return Plotly.restyle(gd, 'hoverinfo', skip ? 'all' : 'skip'); + }, skip ? 4 * N : 0, 'pick ids come and go with hoverinfo skip'); + }) + .then(function() { + expect(obj(0).discConst.noPick).toBe(!skip); + expect(obj(0).flatState.kept).toBe(0); + }) + .then(done, done.fail); + }); + }); + + it('@gl scene.datascale all: hiding a trace in the legend keeps the scale and the other positions', function(done) { + function wide() { + var t = cloud10(N, {}, 7); + t.x[0] = 4; + return t; + } + var scale; + var L = layout(); + L.scene.datascale = 'all'; + // the axes upload new ticks when the range changes, so this looks at the cloud's own buffers + function expectCloudKept(step, msg) { + var before = obj(0).flatState.kept; + var buffer = obj(0).pointBuffer.handle; + var update = obj(0).pointBuffer.update; + var uploads = 0; + obj(0).pointBuffer.update = function() { + uploads++; + return update.apply(this, arguments); + }; + return Promise.resolve(step()).then(function() { + expect(uploads).toBe(0, msg); + expect(obj(0).flatState.kept).toBe(before + 1, msg); + expect(obj(0).pointBuffer.handle).toBe(buffer, msg); + obj(0).pointBuffer.update = update; + }); + } + Plotly.newPlot(gd, [cloud10(N), wide()], L) + .then(function() { + scale = scene().dataScale.slice(); + expect(scale[0]).toBeCloseTo(0.25, 2); + return expectCloudKept(function() { return Plotly.restyle(gd, 'visible', 'legendonly', [1]); }, 'hide'); + }) + .then(function() { + expect(scene().dataScale).toEqual(scale); + expect(scene().glplot.objects.length).toBe(1); + return expectCloudKept(function() { return Plotly.restyle(gd, 'visible', true, [1]); }, 'show'); + }) + .then(function() { + expect(scene().dataScale).toEqual(scale); + expect(scene().glplot.objects.length).toBe(2); + // the default: the visible traces set the scale + return Plotly.newPlot(gd, [cloud10(N), wide()], layout()); + }) + .then(function() { + expect(gd._fullLayout.scene.datascale).toBe('visible'); + return expectSent(function() { return Plotly.restyle(gd, 'visible', 'legendonly', [1]); }, 12 * N, 'hide, default'); + }) + .then(function() { + expect(scene().dataScale[0]).toBeCloseTo(1, 1); + }) + .then(done, done.fail); + }); + + it('@gl scene.datascale all keeps the scale for legendonly traces, and not for removed traces', function(done) { + function scale() { return scene().dataScale.slice(); } + Plotly.newPlot(gd, [ + {type: 'scatter3d', mode: 'markers', x: [0, 1], y: [0, 1], z: [0, 1]}, + {type: 'scatter3d', mode: 'markers', x: [0, 4], y: [0, 2], z: [0, 1]} + ], {scene: {datascale: 'all'}}) + .then(function() { + expect(scale()).toEqual([1 / 4, 1 / 2, 1]); + return Plotly.restyle(gd, 'visible', 'legendonly', [1]); + }) + .then(function() { + expect(scale()).toEqual([1 / 4, 1 / 2, 1]); + return Plotly.restyle(gd, 'visible', false, [1]); + }) + .then(function() { + expect(scale()).toEqual([1, 1, 1]); + }) + .then(done, done.fail); + }); + }); }); diff --git a/test/jasmine/tests/scattergl_lod_test.js b/test/jasmine/tests/scattergl_lod_test.js new file mode 100644 index 00000000000..92fcc7525e3 --- /dev/null +++ b/test/jasmine/tests/scattergl_lod_test.js @@ -0,0 +1,1185 @@ +const Plotly = require('../../../lib/index'); +const createGraphDiv = require('../assets/create_graph_div'); +const destroyGraphDiv = require('../assets/destroy_graph_div'); + +// level of detail at draw time: layout.lod, scene.lod, scene.hidden + +function f32(n, seed) { + const 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; +} + +function trace(n, seed, extra) { + const t = { type: 'scattergl', mode: 'markers', x: f32(n, seed), y: f32(n, seed + 1), marker: { size: 6 } }; + for (let k in extra) t[k] = extra[k]; + return t; +} + +// what the regl context of the graph is asked to draw +function watch(gd) { + let gl = gd._fullLayout._glcanvas.data()[0].regl._gl; + let log = { elements: [], arrays: [], indexUploads: 0 }; + const de = gl.drawElements; + const da = gl.drawArrays; + let bd = gl.bufferData; + gl.drawElements = function (mode, count, type) { + log.elements.push([mode, count, type]); + return de.apply(gl, arguments); + }; + gl.drawArrays = function (mode, first, count) { + log.arrays.push([mode, first, count]); + return da.apply(gl, arguments); + }; + gl.bufferData = function (target) { + if (target === gl.ELEMENT_ARRAY_BUFFER) log.indexUploads++; + return bd.apply(gl, arguments); + }; + log.gl = gl; + log.reset = () => { + log.elements = []; + log.arrays = []; + log.indexUploads = 0; + }; + log.restore = () => { + gl.drawElements = de; + gl.drawArrays = da; + gl.bufferData = bd; + }; + return log; +} + +describe('regl-scatter2d level of detail draws', () => { + let gd; + + beforeEach(() => { + gd = createGraphDiv(); + }); + afterEach(() => { + Plotly.purge(gd); + destroyGraphDiv(); + }); + + function scatter() { + return gd._fullLayout._plots.xy._scene.scatter2d; + } + + it('@gl counts the points of the groups, with groups left out and counts replaced', (done) => { + Plotly.newPlot(gd, [trace(1000, 1), trace(501, 3), trace(250, 5)]) + .then(() => { + let sc = scatter(); + expect(sc.lodCount()).toBe(1751); + expect(sc.lodCount([false, true])).toBe(1250); + expect(sc.lodCount(null, [100])).toBe(851); + expect(sc.lodCount([true], [100, 1])).toBe(251); + }) + .then(done, done.fail); + }); + + it('@gl draws every k-th point of every group through one shared index buffer', (done) => { + let log; + Plotly.newPlot(gd, [trace(1000, 1), trace(501, 3), trace(250, 5)]) + .then(() => { + let sc = scatter(); + log = watch(gd); + sc.drawStride(4); + expect(log.elements).toEqual([ + [log.gl.POINTS, 250, log.gl.UNSIGNED_INT], + [log.gl.POINTS, 126, log.gl.UNSIGNED_INT], + [log.gl.POINTS, 63, log.gl.UNSIGNED_INT] + ]); + expect(log.arrays.length).toBe(0); + expect(log.indexUploads).toBe(1); + + // the same stride again: the index buffer is kept; a group left out is not drawn + log.reset(); + sc.drawStride(4, [false, true]); + expect( + log.elements.map((e) => { + return e[1]; + }) + ).toEqual([250, 63]); + expect(log.indexUploads).toBe(0); + + // another stride: a new index buffer + log.reset(); + sc.drawStride(8); + expect( + log.elements.map((e) => { + return e[1]; + }) + ).toEqual([125, 63, 32]); + expect(log.indexUploads).toBe(1); + log.restore(); + }) + .then(done, done.fail); + }); + + it('@gl draws the full picture in parts, in order, cutting inside a group', (done) => { + let log; + Plotly.newPlot(gd, [trace(1000, 1), trace(501, 3), trace(250, 5)]) + .then(() => { + let sc = scatter(); + log = watch(gd); + let at = { g: 0, off: 0 }; + expect(sc.drawRange(at, 700)).toBe(false); + expect(at).toEqual({ g: 0, off: 700 }); + expect(sc.drawRange(at, 700)).toBe(false); + expect(at).toEqual({ g: 1, off: 400 }); + expect(sc.drawRange(at, 700)).toBe(true); + expect(log.arrays).toEqual([ + [log.gl.POINTS, 0, 700], + [log.gl.POINTS, 700, 300], + [log.gl.POINTS, 0, 400], + [log.gl.POINTS, 400, 101], + [log.gl.POINTS, 0, 250] + ]); + expect(log.elements.length).toBe(0); + + // a group left out, and the whole picture in one part + log.reset(); + expect(sc.drawRange({ g: 0, off: 0 }, Infinity, [false, true])).toBe(true); + expect(log.arrays).toEqual([ + [log.gl.POINTS, 0, 1000], + [log.gl.POINTS, 0, 250] + ]); + log.restore(); + }) + .then(done, done.fail); + }); + + it('@gl draws a group that lies in several GPU segments piece by piece, with the pixels of the plain draws', (done) => { + const createScatter = require('regl-scatter2d'); + const segment = createScatter.xySegment; + let gl, sc, plain, strided, log; + function read() { + let px = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4); + gl.readPixels(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight, gl.RGBA, gl.UNSIGNED_BYTE, px); + return px; + } + function clear() { + gd._fullLayout._glcanvas.each((d) => { + if (d.regl) d.regl.clear({ color: true, depth: true }); + }); + } + function every(n, k) { + const out = []; + for (let i = 0; i < n; i += k) out.push(i); + return out; + } + // 1,024 points per segment: 3 pieces and 2 pieces + createScatter.xySegment = 4096; + Plotly.newPlot( + gd, + [ + trace(3000, 1, { marker: { size: 9, opacity: 0.6, color: 'red' } }), + trace(1500, 3, { marker: { size: 9, opacity: 0.6, color: 'blue' } }) + ], + { width: 400, height: 300, xaxis: { range: [0, 1] }, yaxis: { range: [0, 1] } } + ) + .then(() => { + sc = scatter(); + gl = gd._fullLayout._glcanvas.data()[0].regl._gl; + plain = read(); + + // in parts of 700 points + clear(); + log = watch(gd); + let at = { g: 0, off: 0 }; + while (!sc.drawRange(at, 700)); + expect( + log.arrays.map((a) => { + return [a[1], a[2]]; + }) + ).toEqual([ + [0, 700], + [700, 324], + [0, 376], + [376, 648], + [0, 52], + [52, 700], + [752, 200], + [0, 500], + [500, 524], + [0, 176], + [176, 300] + ]); + log.restore(); + expect(read()).toEqual(plain); + + // every 5th point: the plain draw of those elements, and drawStride + clear(); + sc.draw(every(3000, 5), every(1500, 5)); + strided = read(); + clear(); + log = watch(gd); + // (plain: the opacity of the every 5th point as it is, to compare with the plain draw) + sc.drawStride(5, null, true); + // pieces of 1024, 1024, 952 and 1024, 476 points; the second starts at its point 1 (1025 in the group) + expect( + log.elements.map((e) => { + return e[1]; + }) + ).toEqual([205, 205, 190, 205, 95]); + expect(log.indexUploads).toBe(1); + log.restore(); + expect(read()).toEqual(strided); + }) + .then( + () => { + createScatter.xySegment = segment; + }, + (e) => { + createScatter.xySegment = segment; + throw e; + } + ) + .then(done, done.fail); + }); + + it('@gl draws a thinned translucent group as dense as the full one, and a thinned opaque group as it is', (done) => { + let gl, sc; + function read() { + let px = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4); + gl.readPixels(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight, gl.RGBA, gl.UNSIGNED_BYTE, px); + return px; + } + function clear() { + gd._fullLayout._glcanvas.each((d) => { + if (d.regl) d.regl.clear({ color: true, depth: true }); + }); + } + function every(n, k) { + const out = []; + for (let i = 0; i < n; i += k) out.push(i); + return out; + } + const layout = { width: 400, height: 300, xaxis: { range: [0, 1] }, yaxis: { range: [0, 1] } }; + // 16 markers of opacity 0.05 on one place: 4 of them with the opacity of 4 markers each cover the same + const pile = { + type: 'scattergl', + mode: 'markers', + x: new Float32Array(16).fill(0.5), + y: new Float32Array(16).fill(0.5), + marker: { size: 40, color: 'red', opacity: 0.05 } + }; + Plotly.newPlot(gd, [pile], layout) + .then(() => { + sc = scatter(); + gl = gd._fullLayout._glcanvas.data()[0].regl._gl; + const full = read(); + // the pixel with the most cover + let at = 3; + for (let i = 3; i < full.length; i += 4) if (full[i] > full[at]) at = i; + expect(full[at]).toBeGreaterThan(100); + + clear(); + sc.drawStride(4); + const dense = read()[at]; + expect(Math.abs(dense - full[at])).toBeLessThan(9); + + clear(); + sc.drawStride(4, null, true); + expect(read()[at]).toBeLessThan(full[at] / 2); + + return Plotly.react(gd, [trace(1000, 1, { marker: { size: 9, color: 'blue' } })], layout); + }) + .then(() => { + sc = scatter(); + clear(); + sc.draw(every(1000, 4)); + const plain = read(); + clear(); + sc.drawStride(4); + expect(read()).toEqual(plain); + }) + .then(done, done.fail); + }); + + it('@gl draws the same pixels in parts as the plain draw does', (done) => { + let gl, full, parts; + function read() { + let px = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4); + gl.readPixels(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight, gl.RGBA, gl.UNSIGNED_BYTE, px); + return px; + } + function clear() { + gd._fullLayout._glcanvas.each((d) => { + if (d.regl) d.regl.clear({ color: true, depth: true }); + }); + } + Plotly.newPlot( + gd, + [ + trace(3000, 1, { marker: { size: 9, opacity: 0.6, color: 'red' } }), + trace(3000, 3, { marker: { size: 9, opacity: 0.6, color: 'blue' } }), + trace(3000, 5, { marker: { size: 12, symbol: 'square', color: 'green' } }) + ], + { width: 400, height: 300 } + ) + .then(() => { + const sc = scatter(); + gl = gd._fullLayout._glcanvas.data()[0].regl._gl; + full = read(); + clear(); + const at = { g: 0, off: 0 }; + let n = 0; + while (!sc.drawRange(at, 1234)) n++; + expect(n).toBe(7); + parts = read(); + let diff = 0; + let drawn = 0; + for (let i = 0; i < full.length; i++) { + if (full[i] !== parts[i]) diff++; + if (full[i]) drawn++; + } + expect(drawn).toBeGreaterThan(10000); + expect(diff).toBe(0); + }) + .then(done, done.fail); + }); +}); + +describe('scattergl scene.hidden', () => { + let gd; + + beforeEach(() => { + gd = createGraphDiv(); + }); + afterEach(() => { + Plotly.purge(gd); + destroyGraphDiv(); + }); + + function scene() { + return gd._fullLayout._plots.xy._scene; + } + function counts(log) { + return log.arrays.map((a) => { + return a[2]; + }); + } + + it('@gl leaves hidden traces out of the draw, in place, until the next calc', (done) => { + let log; + let uploads = 0; + Plotly.newPlot(gd, [trace(1000, 1), trace(501, 3), trace(250, 5)]) + .then(() => { + log = watch(gd); + const bd = log.gl.bufferData; + log.gl.bufferData = function (target) { + if (target === log.gl.ARRAY_BUFFER) uploads++; + return bd.apply(log.gl, arguments); + }; + expect(scene().hidden).toEqual([]); + expect(scene().visibleCount).toEqual([]); + + scene().setHidden({ 1: true }); + expect(counts(log)).toEqual([1000, 250]); + expect(uploads).toBe(0); + expect(scene().hidden[1]).toBe(true); + expect(gd.calcdata.length).toBe(3); + + // a pan draws the same two + log.reset(); + return Plotly.relayout(gd, { 'xaxis.range': [0, 0.5] }); + }) + .then(() => { + expect(counts(log)).toEqual([1000, 250]); + + log.reset(); + uploads = 0; + scene().setHidden({ 1: false, 2: true }); + expect(counts(log)).toEqual([1000, 501]); + expect(uploads).toBe(0); + + // a calc starts again with nothing hidden + log.reset(); + return Plotly.restyle(gd, 'marker.size', 7); + }) + .then(() => { + expect(scene().hidden).toEqual([]); + expect(counts(log)).toEqual([1000, 501, 250]); + log.restore(); + }) + .then(done, done.fail); + }); +}); + +describe('scattergl layout.lod', () => { + let gd; + let events; + + beforeEach(() => { + gd = createGraphDiv(); + events = []; + }); + afterEach(() => { + Plotly.purge(gd); + destroyGraphDiv(); + }); + + const LOD = { minpoints: 1000, budget: 500, maxstride: 64, settle: 30 }; + function data() { + return [trace(1000, 1), trace(501, 3), trace(250, 5)]; + } + function layout(lod, extra) { + const l = { width: 400, height: 300, lod: JSON.parse(JSON.stringify(lod)) }; + for (let k in extra) l[k] = extra[k]; + return l; + } + function scene() { + return gd._fullLayout._plots.xy._scene; + } + function listen() { + gd.on('plotly_lod', (e) => { + events.push(e); + }); + } + function plot(d, l, config) { + return Plotly.newPlot(gd, d, l, config).then(listen); + } + function states() { + return events.map((e) => { + return e.state + ':' + e.reason; + }); + } + // resolves when the scene reaches `state` + function when(state) { + return new Promise((resolve, reject) => { + const t0 = Date.now(); + (function poll() { + if (scene().lod.state === state) resolve(); + else if (Date.now() - t0 > 3000) reject(new Error('never ' + state + ', still ' + scene().lod.state)); + else setTimeout(poll, 5); + })(); + }); + } + function clear() { + gd._fullLayout._glcanvas.each((d) => { + if (d.regl) d.regl.clear({ color: true, depth: true }); + }); + } + function pixels() { + let gl = gd._fullLayout._glcanvas.data()[0].regl._gl; + const px = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4); + gl.readPixels(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight, gl.RGBA, gl.UNSIGNED_BYTE, px); + return px; + } + function differ(a, b) { + let n = 0; + for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) n++; + return n; + } + + it('@gl is off without layout.lod: the draws of before, no event, no layout key', (done) => { + let log; + Plotly.newPlot(gd, data(), { width: 400, height: 300 }) + .then(() => { + listen(); + expect(gd._fullLayout.lod).toBeUndefined(); + expect(scene().lod.state).toBe('off'); + log = watch(gd); + return Plotly.relayout(gd, { 'xaxis.range': [0, 0.5] }); + }) + .then(() => { + expect( + log.arrays.map((a) => { + return a[2]; + }) + ).toEqual([1000, 501, 250]); + expect(log.elements.length).toBe(0); + expect(events.length).toBe(0); + log.restore(); + }) + .then(done, done.fail); + }); + + it('@gl previews every k-th point, then draws the full picture, and says so', (done) => { + let log, full; + plot(data(), layout(LOD)) + .then(() => { + // 1751 points, budget 500: every 4th + expect(gd._fullLayout.lod).toEqual({ + minpoints: 1000, + budget: 500, + maxstride: 64, + settle: 30, + slice: 5000000, + edits: 'hold' + }); + expect(scene().lod.state).toBe('preview'); + expect(scene().lod.stride).toBe(4); + expect(scene().lod.total).toBe(1751); + expect(scene().lod.shown).toBe(438); + log = watch(gd); + return when('full'); + }) + .then(() => { + expect( + log.arrays.map((a) => { + return a[2]; + }) + ).toEqual([1000, 501, 250]); + expect(states()).toEqual(['full:settle']); + expect(events[0]).toEqual({ + subplot: 'xy', + state: 'full', + stride: 4, + shown: 1751, + total: 1751, + reason: 'settle' + }); + full = pixels(); + + // an edit: a preview through the index buffer, then the same full picture + log.reset(); + return Plotly.relayout(gd, { 'xaxis.range': [0, 0.5] }); + }) + .then(() => { + expect( + log.elements.map((e) => { + return e[1]; + }) + ).toEqual([250, 126, 63]); + expect(log.arrays.length).toBe(0); + expect(events[1]).toEqual({ + subplot: 'xy', + state: 'preview', + stride: 4, + shown: 438, + total: 1751, + reason: 'plot' + }); + return when('full'); + }) + .then(() => { + expect(states()).toEqual(['full:settle', 'preview:plot', 'full:settle']); + log.restore(); + full = pixels(); + // the picture without the level of detail + return Plotly.relayout(gd, { 'lod.minpoints': 0 }); + }) + .then(() => { + expect(scene().lod.state).toBe('full'); + return Plotly.relayout(gd, { 'xaxis.range': [0, 0.5] }); + }) + .then(() => { + expect(scene().lod.state).toBe('off'); + expect(differ(full, pixels())).toBe(0); + }) + .then(done, done.fail); + }); + + it('@gl restarts the wait with each draw request and settles once; a drag gives reason range', (done) => { + function drag(i) { + scene().update({ range: [0.01 * i, 0.01 * i, 0.5, 0.5] }); + clear(); + scene().draw(); + } + plot(data(), layout(LOD)) + .then(() => { + return when('full'); + }) + .then(() => { + events.length = 0; + drag(1); + drag(2); + return new Promise((r) => { + setTimeout(r, 15); + }); + }) + .then(() => { + drag(3); + expect(scene().lod.state).toBe('preview'); + return when('full'); + }) + .then(() => { + expect(states()).toEqual(['preview:range', 'full:settle']); + }) + .then(done, done.fail); + }); + + it('@gl draws in full at once on settle()', (done) => { + let log; + plot(data(), layout({ minpoints: 1000, budget: 500, settle: 100000 })) + .then(() => { + expect(scene().lod.state).toBe('preview'); + log = watch(gd); + scene().lod.settle(); + expect(scene().lod.state).toBe('full'); + expect( + log.arrays.map((a) => { + return a[2]; + }) + ).toEqual([1000, 501, 250]); + expect(states()).toEqual(['full:settle']); + log.restore(); + }) + .then(done, done.fail); + }); + + it('@gl counts visible points only: hidden traces and visibleCount', (done) => { + plot(data(), layout({ minpoints: 800, budget: 500, settle: 100000 })) + .then(() => { + expect(scene().lod.total).toBe(1751); + scene().visibleCount[0] = 100; + clear(); + scene().draw(); + // 851 visible points: every 2nd + expect(scene().lod.total).toBe(851); + expect(scene().lod.stride).toBe(2); + expect(events[events.length - 1]).toEqual({ + subplot: 'xy', + state: 'preview', + stride: 2, + shown: 426, + total: 851, + reason: 'plot' + }); + scene().setHidden({ 1: true }); + // 350 visible points: under minpoints, every point is drawn + expect(scene().lod.total).toBe(350); + expect(scene().lod.state).toBe('off'); + }) + .then(done, done.fail); + }); + + it('@gl stays off below minpoints, in a static plot, with lines, a selection or a second subplot', (done) => { + plot(data(), layout({ minpoints: 5000, budget: 500 })) + .then(() => { + expect(scene().lod.state).toBe('off'); + let d = data(); + d[1].mode = 'lines+markers'; + return plot(d, layout(LOD)); + }) + .then(() => { + expect(scene().lod.state).toBe('off'); + let d = data(); + d[0].selectedpoints = [1, 2, 3]; + return plot(d, layout(LOD)); + }) + .then(() => { + expect(scene().lod.state).toBe('off'); + const d = data(); + d[2].xaxis = 'x2'; + d[2].yaxis = 'y2'; + return plot(d, layout(LOD, { grid: { rows: 1, columns: 2, pattern: 'independent' } })); + }) + .then(() => { + expect(scene().lod.state).toBe('off'); + expect(gd._fullLayout._plots.x2y2._scene.lod.state).toBe('off'); + expect(events.length).toBe(0); + // a big single trace is drawn in a preview like any other + return plot([trace(120000, 7)], layout({ minpoints: 1000, budget: 50000, settle: 100000 })); + }) + .then(() => { + expect(scene().lod.state).toBe('preview'); + expect(scene().lod.stride).toBe(4); + return plot(data(), layout(LOD), { staticPlot: true }); + }) + .then(() => { + expect(scene().lod.state).toBe('off'); + }) + .then(done, done.fail); + }); + + it('@gl leaves nothing pending after a purge during a preview', (done) => { + plot(data(), layout(LOD)) + .then(() => { + expect(scene().lod.state).toBe('preview'); + Plotly.purge(gd); + return new Promise((r) => { + setTimeout(r, 80); + }); + }) + .then(() => { + expect(events.length).toBe(0); + }) + .then(done, done.fail); + }); + + it('@gl ignores the late context loss of a released canvas, and settles the new plot', (done) => { + let old; + plot(data(), layout(LOD)) + .then(() => { + old = gd.querySelector('.gl-canvas-context'); + Plotly.purge(gd); + return plot(data(), layout(LOD)); + }) + .then(() => { + expect(gd.querySelector('.gl-canvas-context')).not.toBe(old); + expect(scene().lod.state).toBe('preview'); + // the browser reports the loss of the old context a task later, through Plotly's listener on that canvas + old.dispatchEvent(new Event('webglcontextlost')); + return when('full'); + }) + .then(() => { + expect(states()).toEqual(['full:settle']); + }) + .then(done, done.fail); + }); + + // the full picture in parts + const PARTS = { minpoints: 1000, budget: 500, maxstride: 64, settle: 40, slice: 400 }; + function glOf() { + return gd._fullLayout._glcanvas.data()[0].regl._gl; + } + function canvas() { + return gd.querySelector('.gl-canvas-context'); + } + function cover() { + return gd.querySelector('.gl-lod-cover'); + } + function wait(ms) { + return new Promise((r) => { + setTimeout(r, ms); + }); + } + // a timer query whose result comes when the spec says so (null: the extension is missing) + function fakeTimer(missing) { + let gl = glOf(); + const orig = gl.getExtension; + const f = { + available: false, + begun: 0, + deleted: 0, + QUERY_RESULT_AVAILABLE_EXT: 1, + TIME_ELAPSED_EXT: 2, + createQueryEXT: () => { + return {}; + }, + deleteQueryEXT: () => { + f.deleted++; + }, + beginQueryEXT: () => { + f.begun++; + }, + endQueryEXT: () => {}, + getQueryObjectEXT: () => { + return f.available; + } + }; + // 'hollow': an object with the constants and no functions, as virtual-webgl gives for this extension + const hollow = { QUERY_RESULT_AVAILABLE_EXT: 1, TIME_ELAPSED_EXT: 2, createQueryEXT: undefined }; + gl.getExtension = (name) => { + if (name !== 'EXT_disjoint_timer_query') return orig.call(gl, name); + return missing === 'hollow' ? hollow : missing ? null : f; + }; + f.restore = () => { + gl.getExtension = orig; + }; + return f; + } + + it('@gl draws the full picture in parts under a copy of the preview, each part when the GPU has finished the last', (done) => { + let log, timer, full; + plot(data(), layout(PARTS)) + .then(() => { + timer = fakeTimer(); + log = watch(gd); + return wait(200); + }) + .then(() => { + // the first part is out and its query is pending: nothing more is issued + expect(timer.begun).toBe(1); + expect(log.arrays).toEqual([[log.gl.POINTS, 0, 400]]); + expect(scene().lod.state).toBe('preview'); + // the canvas is not shown while it holds a part; the copy of the preview is + expect(canvas().style.visibility).toBe('hidden'); + expect(cover().style.display).toBe(''); + expect(cover().width).toBe(canvas().width); + expect(cover().height).toBe(canvas().height); + expect(cover().style.width).toBe(canvas().style.width); + timer.available = true; + return when('full'); + }) + .then(() => { + expect(log.arrays).toEqual([ + [log.gl.POINTS, 0, 400], + [log.gl.POINTS, 400, 400], + [log.gl.POINTS, 800, 200], + [log.gl.POINTS, 0, 200], + [log.gl.POINTS, 200, 301], + [log.gl.POINTS, 0, 99], + [log.gl.POINTS, 99, 151] + ]); + expect(timer.begun).toBe(5); + expect(canvas().style.visibility).toBe(''); + expect(cover().style.display).toBe('none'); + expect(cover().width).toBe(0); + expect(states()).toEqual(['full:settle']); + timer.restore(); + log.restore(); + full = pixels(); + return Plotly.relayout(gd, { 'lod.minpoints': 0 }); + }) + .then(() => { + clear(); + scene().draw(); + expect(scene().lod.state).toBe('off'); + expect(differ(full, pixels())).toBe(0); + }) + .then(done, done.fail); + }); + + it('@gl waits for the GPU with readPixels when there is no timer query', (done) => { + let gl, rp; + let reads = 0; + plot(data(), layout(PARTS)) + .then(() => { + fakeTimer(true); + gl = glOf(); + rp = gl.readPixels; + gl.readPixels = function (x, y, w, h) { + if (w === 1 && h === 1) reads++; + return rp.apply(gl, arguments); + }; + return when('full'); + }) + .then(() => { + // five parts, a wait after each but the last + expect(reads).toBe(4); + expect(canvas().style.visibility).toBe(''); + gl.readPixels = rp; + }) + .then(done, done.fail); + }); + + it('@gl waits with readPixels when the timer query extension has no functions', (done) => { + let gl, rp; + let reads = 0; + plot(data(), layout(PARTS)) + .then(() => { + fakeTimer('hollow'); + gl = glOf(); + rp = gl.readPixels; + gl.readPixels = function (x, y, w, h) { + if (w === 1 && h === 1) reads++; + return rp.apply(gl, arguments); + }; + return when('full'); + }) + .then(() => { + expect(reads).toBe(4); + expect(canvas().style.visibility).toBe(''); + gl.readPixels = rp; + }) + .then(done, done.fail); + }); + + it('@gl drops the parts that are left when a draw is asked for, and previews again', (done) => { + let log, timer; + plot(data(), layout(PARTS)) + .then(() => { + timer = fakeTimer(); + return wait(200); + }) + .then(() => { + expect(timer.begun).toBe(1); + log = watch(gd); + return Plotly.relayout(gd, { 'xaxis.range': [0, 0.5] }); + }) + .then(() => { + // the preview is on the canvas, shown; the pending query is let go + expect( + log.elements.map((e) => { + return e[1]; + }) + ).toEqual([250, 126, 63]); + expect(log.arrays.length).toBe(0); + expect(canvas().style.visibility).toBe(''); + expect(cover().style.display).toBe('none'); + expect(timer.deleted).toBe(1); + expect(scene().lod.state).toBe('preview'); + timer.available = true; + return when('full'); + }) + .then(() => { + // one full picture, from its start + expect(log.arrays.length).toBe(7); + expect(log.arrays[0]).toEqual([log.gl.POINTS, 0, 400]); + expect(states()).toEqual(['full:settle']); + timer.restore(); + log.restore(); + }) + .then(done, done.fail); + }); + + it('@gl settles, loses its context or is purged in the middle of the parts with nothing left pending', (done) => { + let log, timer; + plot(data(), layout(PARTS)) + .then(() => { + timer = fakeTimer(); + return wait(200); + }) + .then(() => { + log = watch(gd); + scene().lod.settle(); + expect(scene().lod.state).toBe('full'); + expect( + log.arrays.map((a) => { + return a[2]; + }) + ).toEqual([1000, 501, 250]); + expect(canvas().style.visibility).toBe(''); + timer.available = true; + return wait(100); + }) + .then(() => { + expect(log.arrays.length).toBe(3); + expect(timer.begun).toBe(1); + + // a context loss during the parts + timer.available = false; + return Plotly.relayout(gd, { 'xaxis.range': [0, 0.6] }); + }) + .then(() => { + return wait(200); + }) + .then(function () { + expect(timer.begun).toBe(2); + expect(canvas().style.visibility).toBe('hidden'); + // the loss of a canvas that is not this plot's (a released one) changes nothing + gd.emit('plotly_webglcontextlost', { + event: { target: document.createElement('canvas') }, + layer: 'contextLayer' + }); + gd.emit('plotly_webglcontextlost', {}); + expect(canvas().style.visibility).toBe('hidden'); + gd.emit('plotly_webglcontextlost', { event: { target: canvas() }, layer: 'contextLayer' }); + expect(canvas().style.visibility).toBe(''); + timer.available = true; + return wait(100); + }) + .then(() => { + expect(timer.begun).toBe(2); + + // a purge during the parts + timer.available = false; + return Plotly.relayout(gd, { 'xaxis.range': [0, 0.7] }); + }) + .then(() => { + return wait(200); + }) + .then(() => { + expect(timer.begun).toBe(3); + expect(cover().parentNode).not.toBe(null); + timer.restore(); + log.restore(); + Plotly.purge(gd); + expect(gd.querySelector('.gl-lod-cover')).toBe(null); + return wait(100); + }) + .then(() => { + expect(timer.begun).toBe(3); + }) + .then(done, done.fail); + }); + + // an edit of a fully drawn plot + it('@gl holds the full picture through an edit: stale, then full, never a preview', (done) => { + let log, timer, full; + plot(data(), layout(PARTS)) + .then(() => { + return when('full'); + }) + .then(() => { + events.length = 0; + timer = fakeTimer(); + log = watch(gd); + return Plotly.restyle(gd, { 'marker.color': 'black' }, [0]); + }) + .then(() => { + // the new full picture is drawn at once, in one draw, on the hidden canvas + expect(scene().lod.state).toBe('stale'); + expect( + log.arrays.map((a) => { + return a[2]; + }) + ).toEqual([1000, 501, 250]); + expect(log.elements.length).toBe(0); + expect(canvas().style.visibility).toBe('hidden'); + expect(cover().style.display).toBe(''); + expect(events[0]).toEqual({ + subplot: 'xy', + state: 'stale', + stride: 4, + shown: 1751, + total: 1751, + reason: 'plot' + }); + return wait(100); + }) + .then(() => { + expect(scene().lod.state).toBe('stale'); + // a second edit during the hold: still held, drawn again, no event + log.reset(); + return Plotly.moveTraces(gd, 2, 0); + }) + .then(() => { + expect(scene().lod.state).toBe('stale'); + expect( + log.arrays.map((a) => { + return a[2]; + }) + ).toEqual([250, 1000, 501]); + expect(canvas().style.visibility).toBe('hidden'); + expect(timer.deleted).toBe(1); + timer.available = true; + return when('full'); + }) + .then(() => { + expect(states()).toEqual(['stale:plot', 'full:settle']); + expect(canvas().style.visibility).toBe(''); + expect(cover().style.display).toBe('none'); + timer.restore(); + log.restore(); + full = pixels(); + return Plotly.relayout(gd, { 'lod.minpoints': 0 }); + }) + .then(() => { + clear(); + scene().draw(); + expect(differ(full, pixels())).toBe(0); + }) + .then(done, done.fail); + }); + + it('@gl holds for setHidden, previews for another view, and a view change ends a hold', (done) => { + let log, timer; + plot(data(), layout(PARTS)) + .then(() => { + return when('full'); + }) + .then(() => { + events.length = 0; + timer = fakeTimer(); + log = watch(gd); + // 1250 visible points: every 4th + scene().setHidden({ 1: true }); + expect(scene().lod.state).toBe('stale'); + expect( + log.arrays.map((a) => { + return a[2]; + }) + ).toEqual([1000, 250]); + expect(canvas().style.visibility).toBe('hidden'); + + // a zoom during the hold: the copy goes, a preview is drawn + log.reset(); + return Plotly.relayout(gd, { 'xaxis.range': [0, 0.5] }); + }) + .then(() => { + expect(scene().lod.state).toBe('preview'); + expect( + log.elements.map((e) => { + return e[1]; + }) + ).toEqual([250, 63]); + expect(canvas().style.visibility).toBe(''); + expect(cover().style.display).toBe('none'); + timer.available = true; + return when('full'); + }) + .then(() => { + expect(states()).toEqual(['stale:plot', 'preview:plot', 'full:settle']); + // a drag of a fully drawn plot previews + events.length = 0; + scene().update({ range: [0.1, 0.1, 0.5, 0.5] }); + require('../../../src/lib/clear_gl_canvases')(gd); + scene().draw(); + expect(scene().lod.state).toBe('preview'); + expect(canvas().style.visibility).toBe(''); + expect(events[0].reason).toBe('range'); + return when('full'); + }) + .then(() => { + // a clear that no draw follows: the copy does not stay + require('../../../src/lib/clear_gl_canvases')(gd); + expect(canvas().style.visibility).toBe('hidden'); + return wait(30); + }) + .then(() => { + expect(canvas().style.visibility).toBe(''); + expect(cover().style.display).toBe('none'); + timer.restore(); + log.restore(); + }) + .then(done, done.fail); + }); + + it('@gl previews an edit with edits: preview, and holds again with edits: hold', (done) => { + let log; + const lod = { minpoints: 1000, budget: 500, settle: 40, slice: 400, edits: 'preview' }; + plot(data(), layout(lod)) + .then(() => { + return when('full'); + }) + .then(() => { + events.length = 0; + log = watch(gd); + return Plotly.restyle(gd, { 'marker.color': 'black' }, [0]); + }) + .then(() => { + expect(scene().lod.state).toBe('preview'); + expect(log.elements.length).toBe(3); + expect(canvas().style.visibility).toBe(''); + return when('full'); + }) + .then(() => { + log.reset(); + return Plotly.relayout(gd, { 'lod.edits': 'hold' }); + }) + .then(() => { + // setting it draws nothing + expect(log.arrays.length + log.elements.length).toBe(0); + expect(gd._fullLayout.lod.edits).toBe('hold'); + return Plotly.restyle(gd, { 'marker.color': 'red' }, [0]); + }) + .then(() => { + expect(log.elements.length).toBe(0); + expect(log.arrays.length).toBe(3); + return when('full'); + }) + .then(() => { + expect(states()).toEqual(['preview:plot', 'full:settle', 'stale:plot', 'full:settle']); + log.restore(); + }) + .then(done, done.fail); + }); + + it('@gl waits with readPixels for a held edit when there is no timer query', (done) => { + plot(data(), layout(PARTS)) + .then(() => { + return when('full'); + }) + .then(() => { + events.length = 0; + fakeTimer(true); + return Plotly.restyle(gd, { 'marker.color': 'black' }, [0]); + }) + .then(() => { + expect(scene().lod.state).toBe('full'); + expect(states()).toEqual(['stale:plot', 'full:settle']); + expect(canvas().style.visibility).toBe(''); + }) + .then(done, done.fail); + }); + + it('@gl draws every point for an image', (done) => { + plot(data(), layout({ minpoints: 1000, budget: 500, settle: 100000 })) + .then(() => { + return Plotly.toImage(gd, { format: 'png', width: 400, height: 300 }); + }) + .then((url) => { + expect(url.length).toBeGreaterThan(1000); + expect(scene().lod.state).toBe('preview'); + }) + .then(done, done.fail); + }); +}); diff --git a/test/jasmine/tests/scattergl_test.js b/test/jasmine/tests/scattergl_test.js index 1e8b904ed28..d1e1b415610 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,375 @@ 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]; } + // 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 = 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); + }); + }); + 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 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(() => { + 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); + // With virtual-webgl, the context of regl does not use WebGLRenderingContext.prototype + let proto = Object.getPrototypeOf(regl._gl); + ['bufferData', 'bufferSubData'].forEach((name) => { + 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); + }); + }); + }).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)); + }); +}); diff --git a/test/plot-schema.json b/test/plot-schema.json index 7ab1ae48d50..cbb74f15efd 100644 --- a/test/plot-schema.json +++ b/test/plot-schema.json @@ -6621,6 +6621,16 @@ } } }, + "datascale": { + "description": "Determines which traces set the scale that the data of this scene is drawn at. With *visible*, hiding or showing a trace that changes the extent of the data changes the scale, and the positions of every trace are converted and uploaded again. With *all*, traces that are hidden with `visible: *legendonly*` count as well, so hiding and showing them leaves the positions of the other traces as they are.", + "dflt": "visible", + "editType": "plot", + "valType": "enumerated", + "values": [ + "visible", + "all" + ] + }, "domain": { "column": { "description": "If there is a layout grid, use the domain for this column in the grid for this scene subplot.", @@ -6708,6 +6718,59 @@ false ] }, + "lod": { + "budget": { + "description": "Sets the largest number of markers in a preview. The stride k is the smallest power of two, from 2 to `maxstride`, that brings the markers within this number.", + "dflt": 2500000, + "editType": "plot", + "min": 1, + "valType": "number" + }, + "editType": "plot", + "maxstride": { + "description": "Sets the largest stride of a preview.", + "dflt": 64, + "editType": "plot", + "min": 2, + "valType": "integer" + }, + "minpoints": { + "description": "Sets the number of `scatter3d` disc markers from which a camera move shows a preview. A preview draws every k-th marker of every trace and no pick pass. The scene draws every marker again `settle` milliseconds after the last camera move. 0 turns the preview off. The graph emits `plotly_lod` when the state changes.", + "dflt": 0, + "editType": "plot", + "min": 0, + "valType": "number" + }, + "role": "object", + "settle": { + "description": "Sets the time in milliseconds between the last camera move and the full picture.", + "dflt": 150, + "editType": "plot", + "min": 0, + "valType": "number" + } + }, + "markerrender": { + "description": "Sets how circle markers of *scatter3d* traces are drawn. The symbols *circle* and *circle-open* have two forms. *glyph* draws each marker as a mesh of 60 to 104 vertices. This is the default. *disc* draws each marker as one round point sprite. It needs far less memory and draws faster. The edge of a disc differs from the edge of a glyph by about one pixel. A marker with another symbol, a projection on the axes, or a size above the point size limit of the GPU is drawn as a glyph. *auto* is currently the same as *disc*.", + "dflt": "glyph", + "editType": "plot", + "valType": "enumerated", + "values": [ + "glyph", + "disc", + "auto" + ] + }, + "oit": { + "description": "Determines how translucent `scatter3d` markers blend. With *off*, the markers blend in draw order. The picture then depends on the order of the traces and of the points. With *auto*, the markers blend by depth and the draw order has no effect. This uses extra render passes and float render targets. The targets need memory in proportion to the size of the plot. If the graphics hardware lacks a feature, plotly.js falls back to *off*. The scene reports the result in `getOITStatus()` and in the `plotly_oitstatus` event.", + "dflt": "off", + "editType": "plot", + "valType": "enumerated", + "values": [ + "off", + "auto" + ] + }, "role": "object", "uirevision": { "description": "Controls persistence of user-driven changes in camera attributes. Defaults to `layout.uirevision`.", @@ -55194,6 +55257,12 @@ "scatter3d": { "animatable": false, "attributes": { + "alwaysontop": { + "description": "If *true*, the markers of this trace are drawn last, on top of everything else in the scene, without depth testing, in trace order. Use it for a highlight that must never be hidden by other points. The markers stay pickable.", + "dflt": false, + "editType": "calc", + "valType": "boolean" + }, "connectgaps": { "description": "Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected.", "dflt": false, @@ -63992,6 +64061,57 @@ "showLegend", "scatter-like" ], + "layoutAttributes": { + "lod": { + "budget": { + "description": "Sets the largest number of points in a preview. The stride k is the smallest power of two, from 2 to `maxstride`, that brings the visible points within this number.", + "dflt": 2500000, + "editType": "none", + "min": 1, + "valType": "number" + }, + "edits": { + "description": "Determines the picture during an edit of a fully drawn plot that keeps the axis ranges, the plot area and the size. *hold* keeps the previous full picture until the new full picture is ready. *preview* shows a preview first, as a pan does. Use *preview* for edits in quick succession, for example from a slider.", + "dflt": "hold", + "editType": "none", + "valType": "enumerated", + "values": [ + "hold", + "preview" + ] + }, + "editType": "none", + "maxstride": { + "description": "Sets the largest stride of a preview.", + "dflt": 64, + "editType": "none", + "min": 2, + "valType": "integer" + }, + "minpoints": { + "description": "Sets the number of visible scattergl points from which a draw shows a preview first. A preview draws every k-th point of every trace. The full picture follows when no draw request came for `settle` milliseconds. 0 turns the preview off. Applies to a graph where the scattergl markers of one subplot are the only WebGL traces. The graph emits `plotly_lod` when the state changes.", + "dflt": 0, + "editType": "none", + "min": 0, + "valType": "number" + }, + "role": "object", + "settle": { + "description": "Sets the time in milliseconds between the last draw request and the full picture.", + "dflt": 150, + "editType": "none", + "min": 0, + "valType": "number" + }, + "slice": { + "description": "Sets the number of points in one part of the full picture. The plot draws the next part when the GPU finished the part before. Thus a draw request between two parts does not wait for the full picture. 0 draws the full picture in one part.", + "dflt": 5000000, + "editType": "none", + "min": 0, + "valType": "number" + } + } + }, "meta": { "description": "The data visualized as scatter point or lines is set in `x` and `y` using the WebGL plotting engine. Bubble charts are achieved by setting `marker.size` and/or `marker.color` to a numerical arrays.", "hrName": "scatter_gl"