@pairdraw/vue 0.20.0 → 0.21.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/canvas/CanvasRoot.vue.js +3 -0
- package/dist/canvas/CanvasRoot.vue.js.map +1 -1
- package/dist/canvas/surface/color-space.d.ts +1 -0
- package/dist/canvas/surface/color-space.d.ts.map +1 -1
- package/dist/canvas/surface/gl-surface.js +16 -2
- package/dist/canvas/surface/gl-surface.js.map +1 -1
- package/dist/canvas/surface/lifecycle.js +4 -2
- package/dist/canvas/surface/lifecycle.js.map +1 -1
- package/dist/canvas/surface/origin.js +14 -0
- package/dist/canvas/surface/origin.js.map +1 -0
- package/dist/canvas/surface/shader/plan.js +40 -0
- package/dist/canvas/surface/shader/plan.js.map +1 -0
- package/dist/canvas/surface/shader/playback.js +132 -36
- package/dist/canvas/surface/shader/playback.js.map +1 -1
- package/dist/canvas/surface/shader/stage.d.ts.map +1 -1
- package/dist/canvas/surface/shader/stage.js +42 -5
- package/dist/canvas/surface/shader/stage.js.map +1 -1
- package/dist/canvas/surface/types.d.ts +16 -0
- package/dist/canvas/surface/types.d.ts.map +1 -1
- package/dist/canvas/surface/use.js +3 -1
- package/dist/canvas/surface/use.js.map +1 -1
- package/dist/canvas/useCanvasInput.d.ts +8 -8
- package/dist/controls/binding-provider/pairdraw.js +1 -1
- package/dist/controls/binding-provider/pairdraw.js.map +1 -1
- package/dist/controls/color-model/types.d.ts +6 -0
- package/dist/controls/color-model/types.d.ts.map +1 -1
- package/dist/controls/color-model/use.d.ts.map +1 -1
- package/dist/controls/color-model/use.js +5 -3
- package/dist/controls/color-model/use.js.map +1 -1
- package/dist/controls/document-colors/index.d.ts +2 -2
- package/dist/controls/document-colors/index.js +2 -2
- package/dist/controls/document-colors/use.d.ts +7 -1
- package/dist/controls/document-colors/use.d.ts.map +1 -1
- package/dist/controls/document-colors/use.js +9 -1
- package/dist/controls/document-colors/use.js.map +1 -1
- package/dist/controls/node-props/use.d.ts +3 -3
- package/dist/controls/okhcl/use.d.ts +2 -2
- package/dist/controls/shader/catalog.d.ts +11 -0
- package/dist/controls/shader/catalog.d.ts.map +1 -1
- package/dist/controls/shader/catalog.js +35 -6
- package/dist/controls/shader/catalog.js.map +1 -1
- package/dist/controls/shader/gallery.d.ts +1 -1
- package/dist/controls/shader/gallery.d.ts.map +1 -1
- package/dist/controls/shader/gallery.js +292 -0
- package/dist/controls/shader/gallery.js.map +1 -1
- package/dist/controls/shader/index.d.ts +3 -1
- package/dist/controls/shader/index.js +3 -1
- package/dist/controls/shader/shapes.d.ts +18 -0
- package/dist/controls/shader/shapes.d.ts.map +1 -0
- package/dist/controls/shader/shapes.js +227 -0
- package/dist/controls/shader/shapes.js.map +1 -0
- package/dist/controls/shader/stops.d.ts +22 -0
- package/dist/controls/shader/stops.d.ts.map +1 -0
- package/dist/controls/shader/stops.js +73 -0
- package/dist/controls/shader/stops.js.map +1 -0
- package/dist/controls/variable-modes/helpers.d.ts.map +1 -1
- package/dist/controls/variable-modes/helpers.js +4 -2
- package/dist/controls/variable-modes/helpers.js.map +1 -1
- package/dist/editor/commands/shortcut.d.ts.map +1 -1
- package/dist/editor/commands/shortcut.js +9 -1
- package/dist/editor/commands/shortcut.js.map +1 -1
- package/dist/i18n/create.d.ts +1 -1
- package/dist/i18n/create.d.ts.map +1 -1
- package/dist/i18n/create.js +1 -0
- package/dist/i18n/create.js.map +1 -1
- package/dist/i18n/locale.d.ts +5 -4
- package/dist/i18n/locale.d.ts.map +1 -1
- package/dist/i18n/locale.js +4 -0
- package/dist/i18n/locale.js.map +1 -1
- package/dist/i18n/locales/de/ai.json.js +15 -0
- package/dist/i18n/locales/de/code.json.js +2 -0
- package/dist/i18n/locales/de/comments.json.js +1 -1
- package/dist/i18n/locales/de/panels.json.js +16 -1
- package/dist/i18n/locales/es/ai.json.js +15 -0
- package/dist/i18n/locales/es/code.json.js +2 -0
- package/dist/i18n/locales/es/comments.json.js +1 -1
- package/dist/i18n/locales/es/panels.json.js +16 -1
- package/dist/i18n/locales/fr/ai.json.js +15 -0
- package/dist/i18n/locales/fr/code.json.js +2 -0
- package/dist/i18n/locales/fr/comments.json.js +1 -1
- package/dist/i18n/locales/fr/panels.json.js +16 -1
- package/dist/i18n/locales/id/agents.json.js +31 -0
- package/dist/i18n/locales/id/agents.json.js.map +1 -0
- package/dist/i18n/locales/id/ai.json.js +608 -0
- package/dist/i18n/locales/id/ai.json.js.map +1 -0
- package/dist/i18n/locales/id/automation.json.js +150 -0
- package/dist/i18n/locales/id/automation.json.js.map +1 -0
- package/dist/i18n/locales/id/browser.json.js +50 -0
- package/dist/i18n/locales/id/browser.json.js.map +1 -0
- package/dist/i18n/locales/id/chat-context.json.js +62 -0
- package/dist/i18n/locales/id/chat-context.json.js.map +1 -0
- package/dist/i18n/locales/id/cloud/editor.json.js +337 -0
- package/dist/i18n/locales/id/cloud/editor.json.js.map +1 -0
- package/dist/i18n/locales/id/cloud/portal.json.js +435 -0
- package/dist/i18n/locales/id/cloud/portal.json.js.map +1 -0
- package/dist/i18n/locales/id/code.json.js +45 -0
- package/dist/i18n/locales/id/code.json.js.map +1 -0
- package/dist/i18n/locales/id/collaboration.json.js +84 -0
- package/dist/i18n/locales/id/collaboration.json.js.map +1 -0
- package/dist/i18n/locales/id/commands.json.js +111 -0
- package/dist/i18n/locales/id/commands.json.js.map +1 -0
- package/dist/i18n/locales/id/comments.json.js +37 -0
- package/dist/i18n/locales/id/comments.json.js.map +1 -0
- package/dist/i18n/locales/id/common.json.js +51 -0
- package/dist/i18n/locales/id/common.json.js.map +1 -0
- package/dist/i18n/locales/id/credentials.json.js +21 -0
- package/dist/i18n/locales/id/credentials.json.js.map +1 -0
- package/dist/i18n/locales/id/design-check.json.js +101 -0
- package/dist/i18n/locales/id/design-check.json.js.map +1 -0
- package/dist/i18n/locales/id/design-memory.json.js +61 -0
- package/dist/i18n/locales/id/design-memory.json.js.map +1 -0
- package/dist/i18n/locales/id/diagnostics.json.js +78 -0
- package/dist/i18n/locales/id/diagnostics.json.js.map +1 -0
- package/dist/i18n/locales/id/editor.json.js +62 -0
- package/dist/i18n/locales/id/editor.json.js.map +1 -0
- package/dist/i18n/locales/id/explore.json.js +30 -0
- package/dist/i18n/locales/id/explore.json.js.map +1 -0
- package/dist/i18n/locales/id/figjam.json.js +39 -0
- package/dist/i18n/locales/id/figjam.json.js.map +1 -0
- package/dist/i18n/locales/id/files.json.js +86 -0
- package/dist/i18n/locales/id/files.json.js.map +1 -0
- package/dist/i18n/locales/id/fonts.json.js +54 -0
- package/dist/i18n/locales/id/fonts.json.js.map +1 -0
- package/dist/i18n/locales/id/index.js +85 -0
- package/dist/i18n/locales/id/index.js.map +1 -0
- package/dist/i18n/locales/id/media.json.js +52 -0
- package/dist/i18n/locales/id/media.json.js.map +1 -0
- package/dist/i18n/locales/id/menu.json.js +118 -0
- package/dist/i18n/locales/id/menu.json.js.map +1 -0
- package/dist/i18n/locales/id/pages.json.js +16 -0
- package/dist/i18n/locales/id/pages.json.js.map +1 -0
- package/dist/i18n/locales/id/panels.json.js +838 -0
- package/dist/i18n/locales/id/panels.json.js.map +1 -0
- package/dist/i18n/locales/id/recovery.json.js +36 -0
- package/dist/i18n/locales/id/recovery.json.js.map +1 -0
- package/dist/i18n/locales/id/rename.json.js +19 -0
- package/dist/i18n/locales/id/rename.json.js.map +1 -0
- package/dist/i18n/locales/id/rendering.json.js +18 -0
- package/dist/i18n/locales/id/rendering.json.js.map +1 -0
- package/dist/i18n/locales/id/settings.json.js +169 -0
- package/dist/i18n/locales/id/settings.json.js.map +1 -0
- package/dist/i18n/locales/id/shaders.json.js +24 -0
- package/dist/i18n/locales/id/shaders.json.js.map +1 -0
- package/dist/i18n/locales/id/shapes.json.js +48 -0
- package/dist/i18n/locales/id/shapes.json.js.map +1 -0
- package/dist/i18n/locales/id/slides.json.js +27 -0
- package/dist/i18n/locales/id/slides.json.js.map +1 -0
- package/dist/i18n/locales/id/statuses.json.js +38 -0
- package/dist/i18n/locales/id/statuses.json.js.map +1 -0
- package/dist/i18n/locales/id/storage.json.js +21 -0
- package/dist/i18n/locales/id/storage.json.js.map +1 -0
- package/dist/i18n/locales/id/tools.json.js +27 -0
- package/dist/i18n/locales/id/tools.json.js.map +1 -0
- package/dist/i18n/locales/id/updates.json.js +31 -0
- package/dist/i18n/locales/id/updates.json.js.map +1 -0
- package/dist/i18n/locales/id/variables/panel.json.js +175 -0
- package/dist/i18n/locales/id/variables/panel.json.js.map +1 -0
- package/dist/i18n/locales/id/variables/types.json.js +15 -0
- package/dist/i18n/locales/id/variables/types.json.js.map +1 -0
- package/dist/i18n/locales/id/variations.json.js +23 -0
- package/dist/i18n/locales/id/variations.json.js.map +1 -0
- package/dist/i18n/locales/it/ai.json.js +15 -0
- package/dist/i18n/locales/it/code.json.js +2 -0
- package/dist/i18n/locales/it/comments.json.js +1 -1
- package/dist/i18n/locales/it/panels.json.js +16 -1
- package/dist/i18n/locales/ja/ai.json.js +15 -0
- package/dist/i18n/locales/ja/code.json.js +2 -0
- package/dist/i18n/locales/ja/comments.json.js +1 -1
- package/dist/i18n/locales/ja/panels.json.js +16 -1
- package/dist/i18n/locales/pl/ai.json.js +15 -0
- package/dist/i18n/locales/pl/code.json.js +2 -0
- package/dist/i18n/locales/pl/comments.json.js +1 -1
- package/dist/i18n/locales/pl/panels.json.js +16 -1
- package/dist/i18n/locales/ru/ai.json.js +15 -0
- package/dist/i18n/locales/ru/code.json.js +2 -0
- package/dist/i18n/locales/ru/comments.json.js +1 -1
- package/dist/i18n/locales/ru/panels.json.js +16 -1
- package/dist/i18n/locales/zh-cn/ai.json.js +15 -0
- package/dist/i18n/locales/zh-cn/code.json.js +2 -0
- package/dist/i18n/locales/zh-cn/comments.json.js +1 -1
- package/dist/i18n/locales/zh-cn/panels.json.js +16 -1
- package/dist/i18n/messages/ai.d.ts +33 -0
- package/dist/i18n/messages/ai.d.ts.map +1 -1
- package/dist/i18n/messages/ai.js +17 -0
- package/dist/i18n/messages/ai.js.map +1 -1
- package/dist/i18n/messages/code.d.ts +4 -0
- package/dist/i18n/messages/code.d.ts.map +1 -1
- package/dist/i18n/messages/code.js +3 -1
- package/dist/i18n/messages/code.js.map +1 -1
- package/dist/i18n/messages/comments.d.ts +2 -2
- package/dist/i18n/messages/comments.js +2 -2
- package/dist/i18n/messages/comments.js.map +1 -1
- package/dist/i18n/messages/panels.d.ts +17 -0
- package/dist/i18n/messages/panels.d.ts.map +1 -1
- package/dist/i18n/messages/panels.js +15 -0
- package/dist/i18n/messages/panels.js.map +1 -1
- package/dist/i18n/messages.d.ts +53 -1
- package/dist/i18n/useI18n.d.ts +212 -4
- package/dist/i18n/useI18n.d.ts.map +1 -1
- package/dist/primitives/ColorPicker/ColorInputRoot.vue.d.ts +6 -0
- package/dist/primitives/ColorPicker/ColorInputRoot.vue.d.ts.map +1 -1
- package/dist/primitives/ColorPicker/ColorInputRoot.vue.js +3 -1
- package/dist/primitives/ColorPicker/ColorInputRoot.vue.js.map +1 -1
- package/dist/primitives/ColorPicker/ColorPickerRoot.vue.d.ts +6 -0
- package/dist/primitives/ColorPicker/ColorPickerRoot.vue.d.ts.map +1 -1
- package/dist/primitives/ColorPicker/ColorPickerRoot.vue.js +3 -2
- package/dist/primitives/ColorPicker/ColorPickerRoot.vue.js.map +1 -1
- package/dist/primitives/Fill/FillRoot.vue.d.ts +2 -1
- package/dist/primitives/Fill/FillRoot.vue.d.ts.map +1 -1
- package/dist/primitives/Fill/FillRoot.vue.js +5 -2
- package/dist/primitives/Fill/FillRoot.vue.js.map +1 -1
- package/dist/primitives/Fill/FillSwatch.vue.d.ts.map +1 -1
- package/dist/primitives/Fill/FillSwatch.vue.js +2 -1
- package/dist/primitives/Fill/FillSwatch.vue.js.map +1 -1
- package/dist/primitives/Fill/types.d.ts +6 -1
- package/dist/primitives/Fill/types.d.ts.map +1 -1
- package/dist/primitives/Fill/useFill.d.ts +10 -4
- package/dist/primitives/Fill/useFill.d.ts.map +1 -1
- package/dist/primitives/Fill/useFill.js +14 -10
- package/dist/primitives/Fill/useFill.js.map +1 -1
- package/dist/primitives/GradientEditor/GradientEditorRoot.vue.d.ts +2 -1
- package/dist/primitives/GradientEditor/GradientEditorRoot.vue.d.ts.map +1 -1
- package/dist/primitives/GradientEditor/GradientEditorRoot.vue.js +5 -2
- package/dist/primitives/GradientEditor/GradientEditorRoot.vue.js.map +1 -1
- package/dist/primitives/GradientEditor/GradientEditorStop.vue.d.ts.map +1 -1
- package/dist/primitives/GradientEditor/GradientEditorStop.vue.js +4 -3
- package/dist/primitives/GradientEditor/GradientEditorStop.vue.js.map +1 -1
- package/dist/primitives/GradientEditor/types.d.ts +3 -1
- package/dist/primitives/GradientEditor/types.d.ts.map +1 -1
- package/dist/primitives/GradientEditor/useGradientStops.d.ts +5 -3
- package/dist/primitives/GradientEditor/useGradientStops.d.ts.map +1 -1
- package/dist/primitives/GradientEditor/useGradientStops.js +9 -4
- package/dist/primitives/GradientEditor/useGradientStops.js.map +1 -1
- package/dist/primitives/LayerTree/LayerTreeRoot.vue.d.ts +6 -1
- package/dist/primitives/LayerTree/LayerTreeRoot.vue.d.ts.map +1 -1
- package/dist/primitives/LayerTree/LayerTreeRoot.vue.js +16 -1
- package/dist/primitives/LayerTree/LayerTreeRoot.vue.js.map +1 -1
- package/package.json +4 -4
|
@@ -12,6 +12,8 @@ const _sfc_main = /*@__PURE__*/ defineComponent({
|
|
|
12
12
|
sceneRenderer: {},
|
|
13
13
|
maxPixelRatio: {},
|
|
14
14
|
reducedEffects: { type: Boolean },
|
|
15
|
+
animations: { type: Function },
|
|
16
|
+
warnShaderLimit: { type: Function },
|
|
15
17
|
showRulers: { type: Boolean },
|
|
16
18
|
preserveDrawingBuffer: { type: Boolean },
|
|
17
19
|
onReady: { type: Function },
|
|
@@ -23,6 +25,7 @@ const _sfc_main = /*@__PURE__*/ defineComponent({
|
|
|
23
25
|
getPlayScroll: { type: Function },
|
|
24
26
|
onFrame: { type: Function },
|
|
25
27
|
onViewportResize: { type: Function },
|
|
28
|
+
onViewportMove: { type: Function },
|
|
26
29
|
onContextLost: { type: Function },
|
|
27
30
|
onNodeDrawFailure: { type: Function }
|
|
28
31
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CanvasRoot.vue.js","names":[],"sources":["../../src/canvas/CanvasRoot.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport { ref } from 'vue'\n\nimport { provideCanvas } from '#vue/canvas/context'\nimport { useCanvas, type UseCanvasOptions } from '#vue/canvas/surface/use'\nimport { useEditor } from '#vue/editor/context'\n\nconst { showRulers, preserveDrawingBuffer } = defineProps<UseCanvasOptions>()\n\nconst editor = useEditor()\nconst canvasRef = ref<HTMLCanvasElement | null>(null)\nconst ready = ref(false)\n\nconst { renderNow, hitTestSectionTitle, hitTestComponentLabel, hitTestFrameTitle } = useCanvas(\n canvasRef,\n editor,\n {\n showRulers,\n preserveDrawingBuffer,\n onReady: () => {\n ready.value = true\n }\n }\n)\n\nprovideCanvas({\n canvasRef,\n ready,\n renderNow,\n hitTestSectionTitle,\n hitTestComponentLabel,\n hitTestFrameTitle\n})\n</script>\n\n<template>\n <slot :canvas-ref=\"canvasRef\" :ready=\"ready\" :render-now=\"renderNow\" />\n</template>\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"CanvasRoot.vue.js","names":[],"sources":["../../src/canvas/CanvasRoot.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport { ref } from 'vue'\n\nimport { provideCanvas } from '#vue/canvas/context'\nimport { useCanvas, type UseCanvasOptions } from '#vue/canvas/surface/use'\nimport { useEditor } from '#vue/editor/context'\n\nconst { showRulers, preserveDrawingBuffer } = defineProps<UseCanvasOptions>()\n\nconst editor = useEditor()\nconst canvasRef = ref<HTMLCanvasElement | null>(null)\nconst ready = ref(false)\n\nconst { renderNow, hitTestSectionTitle, hitTestComponentLabel, hitTestFrameTitle } = useCanvas(\n canvasRef,\n editor,\n {\n showRulers,\n preserveDrawingBuffer,\n onReady: () => {\n ready.value = true\n }\n }\n)\n\nprovideCanvas({\n canvasRef,\n ready,\n renderNow,\n hitTestSectionTitle,\n hitTestComponentLabel,\n hitTestFrameTitle\n})\n</script>\n\n<template>\n <slot :canvas-ref=\"canvasRef\" :ready=\"ready\" :render-now=\"renderNow\" />\n</template>\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EASA,MAAM,SAAS,UAAU;EACzB,MAAM,YAAY,IAA8B,IAAI;EACpD,MAAM,QAAQ,IAAI,KAAK;EAEvB,MAAM,EAAE,WAAW,qBAAqB,uBAAuB,sBAAsB,UACnF,WACA,QACA;GACE,YAAS,QAAA;GACT,uBAAoB,QAAA;GACpB,eAAe;IACb,MAAM,QAAQ;GAChB;EACF,CACF;EAEA,cAAc;GACZ;GACA;GACA;GACA;GACA;GACA;EACF,CAAC;;GAIC,OAAA,WAAuE,KAAA,QAAA,WAAA;IAAhE,WAAY,UAAA;IAAY,OAAO,MAAA;IAAQ,WAAY,MAAA,SAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"color-space.d.ts","names":[],"sources":["../../../src/canvas/surface/color-space.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"color-space.d.ts","names":[],"sources":["../../../src/canvas/surface/color-space.ts"],"mappings":";;KAGY;;;;;;iBAuJI"}
|
|
@@ -2,6 +2,15 @@ import { configurePresentation, supportsWideGamutPresentation } from "./color-sp
|
|
|
2
2
|
import { IS_BROWSER } from "@pairdraw/core/constants";
|
|
3
3
|
//#region src/canvas/surface/gl-surface.ts
|
|
4
4
|
const parkingHandles = /* @__PURE__ */ new WeakMap();
|
|
5
|
+
/**
|
|
6
|
+
* Applies a resource-cache limit to one canvas context and nothing when no limit is chosen. Reading
|
|
7
|
+
* first keeps it idempotent: a context that already holds the value is left as it is.
|
|
8
|
+
*/
|
|
9
|
+
function applyResourceCacheLimit(context, bytes) {
|
|
10
|
+
if (bytes === void 0) return;
|
|
11
|
+
if (context.getResourceCacheLimitBytes() === bytes) return;
|
|
12
|
+
context.setResourceCacheLimitBytes(bytes);
|
|
13
|
+
}
|
|
5
14
|
/** A 1×1 offscreen WebGL context that stays registered, so another context can become current. */
|
|
6
15
|
function parkingHandle(ck) {
|
|
7
16
|
const existing = parkingHandles.get(ck);
|
|
@@ -94,7 +103,7 @@ function rememberWrittenStyle(canvas) {
|
|
|
94
103
|
* one through its margins; pointers map from its box, so they follow. Under a transform, where no
|
|
95
104
|
* snap holds, the canvas takes its layout size rounded and stays where it is. A flex container
|
|
96
105
|
* that centres the canvas moves it by half a margin change, so there the snap can stay a quarter
|
|
97
|
-
* pixel off.
|
|
106
|
+
* pixel off. Returns where the content box now starts on screen.
|
|
98
107
|
*/
|
|
99
108
|
function sizeCanvas(canvas, editor, onViewportResize, maxPixelRatio = Number.POSITIVE_INFINITY) {
|
|
100
109
|
const dpr = canvasPixelRatio(maxPixelRatio);
|
|
@@ -129,6 +138,10 @@ function sizeCanvas(canvas, editor, onViewportResize, maxPixelRatio = Number.POS
|
|
|
129
138
|
rememberWrittenStyle(canvas);
|
|
130
139
|
if (onViewportResize) onViewportResize(width, height);
|
|
131
140
|
else if ("setViewportSize" in editor && typeof editor.setViewportSize === "function") editor.setViewportSize(width, height);
|
|
141
|
+
return {
|
|
142
|
+
x: left,
|
|
143
|
+
y: top
|
|
144
|
+
};
|
|
132
145
|
}
|
|
133
146
|
function makeGLSurface(ck, canvas, options, glContext, documentColorSpace) {
|
|
134
147
|
let context = glContext;
|
|
@@ -166,6 +179,7 @@ function makeGLSurface(ck, canvas, options, glContext, documentColorSpace) {
|
|
|
166
179
|
presentation: null
|
|
167
180
|
};
|
|
168
181
|
}
|
|
182
|
+
applyResourceCacheLimit(context, void 0);
|
|
169
183
|
return {
|
|
170
184
|
surface: ck.MakeOnScreenGLSurface(context, canvas.width, canvas.height, presentation === "display-p3" ? ck.ColorSpace.DISPLAY_P3 : ck.ColorSpace.SRGB),
|
|
171
185
|
glContext: context,
|
|
@@ -174,6 +188,6 @@ function makeGLSurface(ck, canvas, options, glContext, documentColorSpace) {
|
|
|
174
188
|
};
|
|
175
189
|
}
|
|
176
190
|
//#endregion
|
|
177
|
-
export { canvasPixelRatio, makeGLSurface, releaseWebGLContext, sizeCanvas };
|
|
191
|
+
export { applyResourceCacheLimit, canvasPixelRatio, makeGLSurface, releaseWebGLContext, sizeCanvas };
|
|
178
192
|
|
|
179
193
|
//# sourceMappingURL=gl-surface.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gl-surface.js","names":[],"sources":["../../../src/canvas/surface/gl-surface.ts"],"sourcesContent":["import type { CanvasKit, Surface } from 'canvaskit-wasm'\n\nimport type { Editor } from '@pairdraw/core'\nimport { IS_BROWSER } from '@pairdraw/core/constants'\nimport type { DocumentColorSpace } from '@pairdraw/scene-graph'\n\nimport type { UseCanvasOptions } from '#vue/canvas/surface/types'\n\nimport {\n configurePresentation,\n supportsWideGamutPresentation,\n type PresentationColorSpace\n} from './color-space'\n\ntype GLContext = ReturnType<CanvasKit['MakeGrContext']>\ntype GLHandle = ReturnType<CanvasKit['GetWebGLContext']>\n\nexport type CanvasGLContext = GLContext\nexport type CanvasGLHandle = GLHandle\n\nconst parkingHandles = new WeakMap<CanvasKit, GLHandle>()\n\n/** A 1×1 offscreen WebGL context that stays registered, so another context can become current. */\nfunction parkingHandle(ck: CanvasKit): GLHandle | null {\n const existing = parkingHandles.get(ck)\n if (existing !== undefined) return existing\n if (typeof document === 'undefined') return null\n const canvas = document.createElement('canvas')\n canvas.width = 1\n canvas.height = 1\n const handle = ck.GetWebGLContext(canvas)\n if (!handle) return null\n parkingHandles.set(ck, handle)\n return handle\n}\n\n/** Makes the parking context current, so CanvasKit lets go of the one it held. */\nfunction park(ck: CanvasKit): void {\n const parking = parkingHandle(ck)\n if (!parking) return\n try {\n ck.MakeGrContext(parking)?.delete()\n } catch {\n // A browser drops a page's oldest WebGL contexts once it holds too many, as WebKit does after\n // a few tabs, and reports it only later; the parking context is the oldest, so it is the one\n // gone, and CanvasKit fails on it. A new parking context takes its place.\n ck.deleteContext(parking)\n parkingHandles.delete(ck)\n const replacement = parkingHandle(ck)\n if (replacement) ck.MakeGrContext(replacement)?.delete()\n }\n}\n\n/**\n * Unregisters a canvas's WebGL context from CanvasKit. `deleteContext` leaves CanvasKit holding\n * the last current context, which keeps the canvas, and every component its element reaches,\n * alive; when this context was current, a parking context takes its place.\n */\nexport function releaseWebGLContext(\n ck: CanvasKit,\n handle: GLHandle,\n canvas: HTMLCanvasElement | null\n): void {\n const context = canvas ? (canvas.getContext('webgl2') ?? canvas.getContext('webgl')) : null\n const wasCurrent = context !== null && Reflect.get(ck, 'ctx') === context\n ck.deleteContext(handle)\n if (wasCurrent) park(ck)\n}\n\n/** The device pixels a canvas draws per CSS pixel: the display's, at most `maxPixelRatio`. */\nexport function canvasPixelRatio(maxPixelRatio = Number.POSITIVE_INFINITY): number {\n return Math.min(IS_BROWSER ? window.devicePixelRatio || 1 : 1, maxPixelRatio)\n}\n\n/** A canvas's inline size and margins. */\ntype PinnedStyle = Pick<CSSStyleDeclaration, 'width' | 'height' | 'marginLeft' | 'marginTop'>\nconst PINNED_PROPERTIES = ['width', 'height', 'marginLeft', 'marginTop'] as const\n/** Per canvas: the inline style its owner set, and the style sizeCanvas last wrote over it. */\nconst pinnedStyles = new WeakMap<HTMLCanvasElement, { own: PinnedStyle; written: PinnedStyle }>()\n\nfunction inlineStyle(canvas: HTMLCanvasElement): PinnedStyle {\n const { width, height, marginLeft, marginTop } = canvas.style\n return { width, height, marginLeft, marginTop }\n}\n\n/**\n * Puts back the inline style the canvas's owner set, so the page's own sizing is measured. A\n * property that differs from what sizeCanvas last wrote was set by the owner since, and becomes\n * theirs; the others keep the owner's earlier value.\n */\nfunction restoreOwnStyle(canvas: HTMLCanvasElement): void {\n const current = inlineStyle(canvas)\n const pinned = pinnedStyles.get(canvas)\n const own = { ...current }\n if (pinned) {\n for (const property of PINNED_PROPERTIES) {\n if (current[property] === pinned.written[property]) own[property] = pinned.own[property]\n }\n }\n pinnedStyles.set(canvas, { own, written: current })\n Object.assign(canvas.style, own)\n}\n\n/** Records the style sizeCanvas wrote, so a later change by the owner can be told apart. */\nfunction rememberWrittenStyle(canvas: HTMLCanvasElement): void {\n const pinned = pinnedStyles.get(canvas)\n if (pinned) pinnedStyles.set(canvas, { own: pinned.own, written: inlineStyle(canvas) })\n}\n\n/**\n * Sizes the canvas bitmap to the content box the page's CSS gives it, pinned to whole CSS pixels\n * as Figma pins its canvas. A panel sized in percent leaves the box at a fraction of a pixel, and\n * the browser shows a canvas at whole pixels, so its bitmap was stretched by one device pixel\n * across the width, softening every line. The canvas moves under a pixel to the nearest whole\n * one through its margins; pointers map from its box, so they follow. Under a transform, where no\n * snap holds, the canvas takes its layout size rounded and stays where it is. A flex container\n * that centres the canvas moves it by half a margin change, so there the snap can stay a quarter\n * pixel off.\n */\nexport function sizeCanvas(\n canvas: HTMLCanvasElement,\n editor: Editor,\n onViewportResize?: (width: number, height: number) => void,\n maxPixelRatio = Number.POSITIVE_INFINITY\n) {\n const dpr = canvasPixelRatio(maxPixelRatio)\n restoreOwnStyle(canvas)\n const box = canvas.getBoundingClientRect()\n const layout = getComputedStyle(canvas)\n const px = (value: string) => Number.parseFloat(value) || 0\n // Border and padding sit outside the bitmap, which fills the content box.\n const inset = {\n left: px(layout.borderLeftWidth) + px(layout.paddingLeft),\n right: px(layout.borderRightWidth) + px(layout.paddingRight),\n top: px(layout.borderTopWidth) + px(layout.paddingTop),\n bottom: px(layout.borderBottomWidth) + px(layout.paddingBottom)\n }\n const borderBox = layout.boxSizing === 'border-box'\n const outerWidth = (px(layout.width) || box.width) + (borderBox ? 0 : inset.left + inset.right)\n const outerHeight = (px(layout.height) || box.height) + (borderBox ? 0 : inset.top + inset.bottom)\n const transformed =\n Math.abs(outerWidth - box.width) > 0.01 || Math.abs(outerHeight - box.height) > 0.01\n const contentLeft = box.left + inset.left\n const contentTop = box.top + inset.top\n const left = transformed ? contentLeft : Math.round(contentLeft)\n const top = transformed ? contentTop : Math.round(contentTop)\n const width = Math.max(\n 1,\n transformed\n ? Math.round(outerWidth - inset.left - inset.right)\n : Math.round(box.right - inset.right) - left\n )\n const height = Math.max(\n 1,\n transformed\n ? Math.round(outerHeight - inset.top - inset.bottom)\n : Math.round(box.bottom - inset.bottom) - top\n )\n canvas.width = Math.round(width * dpr)\n canvas.height = Math.round(height * dpr)\n canvas.style.width = `${borderBox ? width + inset.left + inset.right : width}px`\n canvas.style.height = `${borderBox ? height + inset.top + inset.bottom : height}px`\n // The margins the page resolves, such as auto for a centred canvas, plus the snap. A translate\n // would leave the bitmap a fraction of a pixel off, which the browser smooths over.\n if (!transformed) {\n canvas.style.marginLeft = `${px(layout.marginLeft) + left - contentLeft}px`\n canvas.style.marginTop = `${px(layout.marginTop) + top - contentTop}px`\n }\n rememberWrittenStyle(canvas)\n if (onViewportResize) {\n onViewportResize(width, height)\n } else if ('setViewportSize' in editor && typeof editor.setViewportSize === 'function') {\n editor.setViewportSize(width, height)\n }\n}\n\nexport function makeGLSurface(\n ck: CanvasKit,\n canvas: HTMLCanvasElement,\n options: UseCanvasOptions | undefined,\n glContext: GLContext | null,\n documentColorSpace: DocumentColorSpace\n): {\n surface: Surface | null\n glContext: GLContext | null\n /**\n * The WebGL context this call registered with CanvasKit, which the caller must release with\n * `deleteContext`: CanvasKit's context table otherwise keeps the canvas, and everything its\n * element reaches, alive. Null when the existing context was reused.\n */\n glHandle: GLHandle | null\n presentation: PresentationColorSpace | null\n} {\n let context = glContext\n const glAttrs = options?.preserveDrawingBuffer ? { preserveDrawingBuffer: 1 } : undefined\n const handle = context ? null : ck.GetWebGLContext(canvas, glAttrs)\n if (!context && !handle) {\n return { surface: null, glContext: context, glHandle: null, presentation: null }\n }\n\n const buffer = canvas.getContext('webgl2') ?? canvas.getContext('webgl')\n const presentation = configurePresentation(buffer, {\n documentColorSpace,\n wideGamutDisplay: IS_BROWSER && supportsWideGamutPresentation(),\n width: canvas.width,\n height: canvas.height\n })\n if (!presentation) {\n if (handle) ck.deleteContext(handle)\n return { surface: null, glContext: context, glHandle: null, presentation: null }\n }\n if (!context && handle) context = ck.MakeGrContext(handle)\n if (!context) {\n if (handle) ck.deleteContext(handle)\n return { surface: null, glContext: context, glHandle: null, presentation: null }\n }\n\n return {\n surface: ck.MakeOnScreenGLSurface(\n context,\n canvas.width,\n canvas.height,\n presentation === 'display-p3' ? ck.ColorSpace.DISPLAY_P3 : ck.ColorSpace.SRGB\n ),\n glContext: context,\n glHandle: handle,\n presentation\n }\n}\n"],"mappings":";;;AAoBA,MAAM,iCAAiB,IAAI,QAA6B;;AAGxD,SAAS,cAAc,IAAgC;CACrD,MAAM,WAAW,eAAe,IAAI,EAAE;CACtC,IAAI,aAAa,KAAA,GAAW,OAAO;CACnC,IAAI,OAAO,aAAa,aAAa,OAAO;CAC5C,MAAM,SAAS,SAAS,cAAc,QAAQ;CAC9C,OAAO,QAAQ;CACf,OAAO,SAAS;CAChB,MAAM,SAAS,GAAG,gBAAgB,MAAM;CACxC,IAAI,CAAC,QAAQ,OAAO;CACpB,eAAe,IAAI,IAAI,MAAM;CAC7B,OAAO;AACT;;AAGA,SAAS,KAAK,IAAqB;CACjC,MAAM,UAAU,cAAc,EAAE;CAChC,IAAI,CAAC,SAAS;CACd,IAAI;EACF,GAAG,cAAc,OAAO,CAAC,EAAE,OAAO;CACpC,QAAQ;EAIN,GAAG,cAAc,OAAO;EACxB,eAAe,OAAO,EAAE;EACxB,MAAM,cAAc,cAAc,EAAE;EACpC,IAAI,aAAa,GAAG,cAAc,WAAW,CAAC,EAAE,OAAO;CACzD;AACF;;;;;;AAOA,SAAgB,oBACd,IACA,QACA,QACM;CACN,MAAM,UAAU,SAAU,OAAO,WAAW,QAAQ,KAAK,OAAO,WAAW,OAAO,IAAK;CACvF,MAAM,aAAa,YAAY,QAAQ,QAAQ,IAAI,IAAI,KAAK,MAAM;CAClE,GAAG,cAAc,MAAM;CACvB,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,SAAS,IAAI,MAAM,WAAW;CACtE;CACA,qBAAqB,MAAM;CAC3B,IAAI,kBACF,iBAAiB,OAAO,MAAM;MACzB,IAAI,qBAAqB,UAAU,OAAO,OAAO,oBAAoB,YAC1E,OAAO,gBAAgB,OAAO,MAAM;AAExC;AAEA,SAAgB,cACd,IACA,QACA,SACA,WACA,oBAWA;CACA,IAAI,UAAU;CACd,MAAM,UAAU,SAAS,wBAAwB,EAAE,uBAAuB,EAAE,IAAI,KAAA;CAChF,MAAM,SAAS,UAAU,OAAO,GAAG,gBAAgB,QAAQ,OAAO;CAClE,IAAI,CAAC,WAAW,CAAC,QACf,OAAO;EAAE,SAAS;EAAM,WAAW;EAAS,UAAU;EAAM,cAAc;CAAK;CAGjF,MAAM,SAAS,OAAO,WAAW,QAAQ,KAAK,OAAO,WAAW,OAAO;CACvE,MAAM,eAAe,sBAAsB,QAAQ;EACjD;EACA,kBAAkB,cAAc,8BAA8B;EAC9D,OAAO,OAAO;EACd,QAAQ,OAAO;CACjB,CAAC;CACD,IAAI,CAAC,cAAc;EACjB,IAAI,QAAQ,GAAG,cAAc,MAAM;EACnC,OAAO;GAAE,SAAS;GAAM,WAAW;GAAS,UAAU;GAAM,cAAc;EAAK;CACjF;CACA,IAAI,CAAC,WAAW,QAAQ,UAAU,GAAG,cAAc,MAAM;CACzD,IAAI,CAAC,SAAS;EACZ,IAAI,QAAQ,GAAG,cAAc,MAAM;EACnC,OAAO;GAAE,SAAS;GAAM,WAAW;GAAS,UAAU;GAAM,cAAc;EAAK;CACjF;CAEA,OAAO;EACL,SAAS,GAAG,sBACV,SACA,OAAO,OACP,OAAO,QACP,iBAAiB,eAAe,GAAG,WAAW,aAAa,GAAG,WAAW,IAC3E;EACA,WAAW;EACX,UAAU;EACV;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"gl-surface.js","names":[],"sources":["../../../src/canvas/surface/gl-surface.ts"],"sourcesContent":["import type { CanvasKit, Surface } from 'canvaskit-wasm'\n\nimport type { Editor } from '@pairdraw/core'\nimport { IS_BROWSER } from '@pairdraw/core/constants'\nimport type { DocumentColorSpace } from '@pairdraw/scene-graph'\nimport type { Vector } from '@pairdraw/scene-graph/primitives'\n\nimport type { UseCanvasOptions } from '#vue/canvas/surface/types'\n\nimport {\n configurePresentation,\n supportsWideGamutPresentation,\n type PresentationColorSpace\n} from './color-space'\n\ntype GLContext = ReturnType<CanvasKit['MakeGrContext']>\ntype GLHandle = ReturnType<CanvasKit['GetWebGLContext']>\n\nexport type CanvasGLContext = GLContext\nexport type CanvasGLHandle = GLHandle\n\nconst parkingHandles = new WeakMap<CanvasKit, GLHandle>()\n\n/**\n * Skia's GPU resource-cache limit per canvas context, in bytes. `undefined` keeps the context's own\n * default: the post-tag measurement (peak `[anon]` vs pan/zoom frame time, see\n * `spec-release-render-caches.md`) picks the number.\n */\nexport const RESOURCE_CACHE_LIMIT_BYTES: number | undefined = undefined\n\n/** The part of `GrDirectContext` the limit needs, so a fake context can stand in for a test. */\ntype ResourceCacheContext = {\n getResourceCacheLimitBytes(): number\n setResourceCacheLimitBytes(bytes: number): void\n}\n\n/**\n * Applies a resource-cache limit to one canvas context and nothing when no limit is chosen. Reading\n * first keeps it idempotent: a context that already holds the value is left as it is.\n */\nexport function applyResourceCacheLimit(\n context: ResourceCacheContext,\n bytes: number | undefined\n): void {\n if (bytes === undefined) return\n if (context.getResourceCacheLimitBytes() === bytes) return\n context.setResourceCacheLimitBytes(bytes)\n}\n\n/** A 1×1 offscreen WebGL context that stays registered, so another context can become current. */\nfunction parkingHandle(ck: CanvasKit): GLHandle | null {\n const existing = parkingHandles.get(ck)\n if (existing !== undefined) return existing\n if (typeof document === 'undefined') return null\n const canvas = document.createElement('canvas')\n canvas.width = 1\n canvas.height = 1\n const handle = ck.GetWebGLContext(canvas)\n if (!handle) return null\n parkingHandles.set(ck, handle)\n return handle\n}\n\n/** Makes the parking context current, so CanvasKit lets go of the one it held. */\nfunction park(ck: CanvasKit): void {\n const parking = parkingHandle(ck)\n if (!parking) return\n try {\n ck.MakeGrContext(parking)?.delete()\n } catch {\n // A browser drops a page's oldest WebGL contexts once it holds too many, as WebKit does after\n // a few tabs, and reports it only later; the parking context is the oldest, so it is the one\n // gone, and CanvasKit fails on it. A new parking context takes its place.\n ck.deleteContext(parking)\n parkingHandles.delete(ck)\n const replacement = parkingHandle(ck)\n if (replacement) ck.MakeGrContext(replacement)?.delete()\n }\n}\n\n/**\n * Unregisters a canvas's WebGL context from CanvasKit. `deleteContext` leaves CanvasKit holding\n * the last current context, which keeps the canvas, and every component its element reaches,\n * alive; when this context was current, a parking context takes its place.\n */\nexport function releaseWebGLContext(\n ck: CanvasKit,\n handle: GLHandle,\n canvas: HTMLCanvasElement | null\n): void {\n const context = canvas ? (canvas.getContext('webgl2') ?? canvas.getContext('webgl')) : null\n const wasCurrent = context !== null && Reflect.get(ck, 'ctx') === context\n ck.deleteContext(handle)\n if (wasCurrent) park(ck)\n}\n\n/** The device pixels a canvas draws per CSS pixel: the display's, at most `maxPixelRatio`. */\nexport function canvasPixelRatio(maxPixelRatio = Number.POSITIVE_INFINITY): number {\n return Math.min(IS_BROWSER ? window.devicePixelRatio || 1 : 1, maxPixelRatio)\n}\n\n/** A canvas's inline size and margins. */\ntype PinnedStyle = Pick<CSSStyleDeclaration, 'width' | 'height' | 'marginLeft' | 'marginTop'>\nconst PINNED_PROPERTIES = ['width', 'height', 'marginLeft', 'marginTop'] as const\n/** Per canvas: the inline style its owner set, and the style sizeCanvas last wrote over it. */\nconst pinnedStyles = new WeakMap<HTMLCanvasElement, { own: PinnedStyle; written: PinnedStyle }>()\n\nfunction inlineStyle(canvas: HTMLCanvasElement): PinnedStyle {\n const { width, height, marginLeft, marginTop } = canvas.style\n return { width, height, marginLeft, marginTop }\n}\n\n/**\n * Puts back the inline style the canvas's owner set, so the page's own sizing is measured. A\n * property that differs from what sizeCanvas last wrote was set by the owner since, and becomes\n * theirs; the others keep the owner's earlier value.\n */\nfunction restoreOwnStyle(canvas: HTMLCanvasElement): void {\n const current = inlineStyle(canvas)\n const pinned = pinnedStyles.get(canvas)\n const own = { ...current }\n if (pinned) {\n for (const property of PINNED_PROPERTIES) {\n if (current[property] === pinned.written[property]) own[property] = pinned.own[property]\n }\n }\n pinnedStyles.set(canvas, { own, written: current })\n Object.assign(canvas.style, own)\n}\n\n/** Records the style sizeCanvas wrote, so a later change by the owner can be told apart. */\nfunction rememberWrittenStyle(canvas: HTMLCanvasElement): void {\n const pinned = pinnedStyles.get(canvas)\n if (pinned) pinnedStyles.set(canvas, { own: pinned.own, written: inlineStyle(canvas) })\n}\n\n/**\n * Sizes the canvas bitmap to the content box the page's CSS gives it, pinned to whole CSS pixels\n * as Figma pins its canvas. A panel sized in percent leaves the box at a fraction of a pixel, and\n * the browser shows a canvas at whole pixels, so its bitmap was stretched by one device pixel\n * across the width, softening every line. The canvas moves under a pixel to the nearest whole\n * one through its margins; pointers map from its box, so they follow. Under a transform, where no\n * snap holds, the canvas takes its layout size rounded and stays where it is. A flex container\n * that centres the canvas moves it by half a margin change, so there the snap can stay a quarter\n * pixel off. Returns where the content box now starts on screen.\n */\nexport function sizeCanvas(\n canvas: HTMLCanvasElement,\n editor: Editor,\n onViewportResize?: (width: number, height: number) => void,\n maxPixelRatio = Number.POSITIVE_INFINITY\n): Vector {\n const dpr = canvasPixelRatio(maxPixelRatio)\n restoreOwnStyle(canvas)\n const box = canvas.getBoundingClientRect()\n const layout = getComputedStyle(canvas)\n const px = (value: string) => Number.parseFloat(value) || 0\n // Border and padding sit outside the bitmap, which fills the content box.\n const inset = {\n left: px(layout.borderLeftWidth) + px(layout.paddingLeft),\n right: px(layout.borderRightWidth) + px(layout.paddingRight),\n top: px(layout.borderTopWidth) + px(layout.paddingTop),\n bottom: px(layout.borderBottomWidth) + px(layout.paddingBottom)\n }\n const borderBox = layout.boxSizing === 'border-box'\n const outerWidth = (px(layout.width) || box.width) + (borderBox ? 0 : inset.left + inset.right)\n const outerHeight = (px(layout.height) || box.height) + (borderBox ? 0 : inset.top + inset.bottom)\n const transformed =\n Math.abs(outerWidth - box.width) > 0.01 || Math.abs(outerHeight - box.height) > 0.01\n const contentLeft = box.left + inset.left\n const contentTop = box.top + inset.top\n const left = transformed ? contentLeft : Math.round(contentLeft)\n const top = transformed ? contentTop : Math.round(contentTop)\n const width = Math.max(\n 1,\n transformed\n ? Math.round(outerWidth - inset.left - inset.right)\n : Math.round(box.right - inset.right) - left\n )\n const height = Math.max(\n 1,\n transformed\n ? Math.round(outerHeight - inset.top - inset.bottom)\n : Math.round(box.bottom - inset.bottom) - top\n )\n canvas.width = Math.round(width * dpr)\n canvas.height = Math.round(height * dpr)\n canvas.style.width = `${borderBox ? width + inset.left + inset.right : width}px`\n canvas.style.height = `${borderBox ? height + inset.top + inset.bottom : height}px`\n // The margins the page resolves, such as auto for a centred canvas, plus the snap. A translate\n // would leave the bitmap a fraction of a pixel off, which the browser smooths over.\n if (!transformed) {\n canvas.style.marginLeft = `${px(layout.marginLeft) + left - contentLeft}px`\n canvas.style.marginTop = `${px(layout.marginTop) + top - contentTop}px`\n }\n rememberWrittenStyle(canvas)\n if (onViewportResize) {\n onViewportResize(width, height)\n } else if ('setViewportSize' in editor && typeof editor.setViewportSize === 'function') {\n editor.setViewportSize(width, height)\n }\n return { x: left, y: top }\n}\n\nexport function makeGLSurface(\n ck: CanvasKit,\n canvas: HTMLCanvasElement,\n options: UseCanvasOptions | undefined,\n glContext: GLContext | null,\n documentColorSpace: DocumentColorSpace\n): {\n surface: Surface | null\n glContext: GLContext | null\n /**\n * The WebGL context this call registered with CanvasKit, which the caller must release with\n * `deleteContext`: CanvasKit's context table otherwise keeps the canvas, and everything its\n * element reaches, alive. Null when the existing context was reused.\n */\n glHandle: GLHandle | null\n presentation: PresentationColorSpace | null\n} {\n let context = glContext\n const glAttrs = options?.preserveDrawingBuffer ? { preserveDrawingBuffer: 1 } : undefined\n const handle = context ? null : ck.GetWebGLContext(canvas, glAttrs)\n if (!context && !handle) {\n return { surface: null, glContext: context, glHandle: null, presentation: null }\n }\n\n const buffer = canvas.getContext('webgl2') ?? canvas.getContext('webgl')\n const presentation = configurePresentation(buffer, {\n documentColorSpace,\n wideGamutDisplay: IS_BROWSER && supportsWideGamutPresentation(),\n width: canvas.width,\n height: canvas.height\n })\n if (!presentation) {\n if (handle) ck.deleteContext(handle)\n return { surface: null, glContext: context, glHandle: null, presentation: null }\n }\n if (!context && handle) context = ck.MakeGrContext(handle)\n if (!context) {\n if (handle) ck.deleteContext(handle)\n return { surface: null, glContext: context, glHandle: null, presentation: null }\n }\n // First creation, resize and the fallback recreation all pass through here; replaceSurface does\n // not make a context.\n applyResourceCacheLimit(context, RESOURCE_CACHE_LIMIT_BYTES)\n\n return {\n surface: ck.MakeOnScreenGLSurface(\n context,\n canvas.width,\n canvas.height,\n presentation === 'display-p3' ? ck.ColorSpace.DISPLAY_P3 : ck.ColorSpace.SRGB\n ),\n glContext: context,\n glHandle: handle,\n presentation\n }\n}\n"],"mappings":";;;AAqBA,MAAM,iCAAiB,IAAI,QAA6B;;;;;AAmBxD,SAAgB,wBACd,SACA,OACM;CACN,IAAI,UAAU,KAAA,GAAW;CACzB,IAAI,QAAQ,2BAA2B,MAAM,OAAO;CACpD,QAAQ,2BAA2B,KAAK;AAC1C;;AAGA,SAAS,cAAc,IAAgC;CACrD,MAAM,WAAW,eAAe,IAAI,EAAE;CACtC,IAAI,aAAa,KAAA,GAAW,OAAO;CACnC,IAAI,OAAO,aAAa,aAAa,OAAO;CAC5C,MAAM,SAAS,SAAS,cAAc,QAAQ;CAC9C,OAAO,QAAQ;CACf,OAAO,SAAS;CAChB,MAAM,SAAS,GAAG,gBAAgB,MAAM;CACxC,IAAI,CAAC,QAAQ,OAAO;CACpB,eAAe,IAAI,IAAI,MAAM;CAC7B,OAAO;AACT;;AAGA,SAAS,KAAK,IAAqB;CACjC,MAAM,UAAU,cAAc,EAAE;CAChC,IAAI,CAAC,SAAS;CACd,IAAI;EACF,GAAG,cAAc,OAAO,CAAC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MAAM;CACzD,IAAI,CAAC,SAAS;EACZ,IAAI,QAAQ,GAAG,cAAc,MAAM;EACnC,OAAO;GAAE,SAAS;GAAM,WAAW;GAAS,UAAU;GAAM,cAAc;EAAK;CACjF;CAGA,wBAAwB,SAAA,KAAA,CAAmC;CAE3D,OAAO;EACL,SAAS,GAAG,sBACV,SACA,OAAO,OACP,OAAO,QACP,iBAAiB,eAAe,GAAG,WAAW,aAAa,GAAG,WAAW,IAC3E;EACA,WAAW;EACX,UAAU;EACV;CACF;AACF"}
|
|
@@ -2,6 +2,7 @@ import { supportsWideGamutPresentation } from "./color-space.js";
|
|
|
2
2
|
import { makeGLSurface, releaseWebGLContext, sizeCanvas } from "./gl-surface.js";
|
|
3
3
|
import { createImagePreviewDecoder } from "./image-preview.js";
|
|
4
4
|
import { useCanvasKitLoader } from "./kit-loader.js";
|
|
5
|
+
import { createCanvasOriginTracker } from "./origin.js";
|
|
5
6
|
import { createCanvasRenderLoop } from "./render-loop.js";
|
|
6
7
|
import { useCanvasResizeObserver } from "./resize-observer.js";
|
|
7
8
|
import { createShaderRasterizer } from "./shader/rasterizer.js";
|
|
@@ -38,6 +39,7 @@ function applySceneScope(renderer, options) {
|
|
|
38
39
|
renderer.playScroll = options?.getPlayScroll?.() ?? null;
|
|
39
40
|
}
|
|
40
41
|
function createCanvasSurfaceManager({ editor, canvasRef, options, getCanvasKit, isDestroyed, shouldShowRulers }) {
|
|
42
|
+
const origin = createCanvasOriginTracker(options?.onViewportMove);
|
|
41
43
|
const state = {
|
|
42
44
|
renderer: null,
|
|
43
45
|
glContext: null,
|
|
@@ -91,7 +93,7 @@ function createCanvasSurfaceManager({ editor, canvasRef, options, getCanvasKit,
|
|
|
91
93
|
state.renderer?.destroy();
|
|
92
94
|
state.renderer = null;
|
|
93
95
|
releaseGLContext();
|
|
94
|
-
sizeCanvas(canvas, editor, options?.onViewportResize, options?.maxPixelRatio);
|
|
96
|
+
origin.place(sizeCanvas(canvas, editor, options?.onViewportResize, options?.maxPixelRatio));
|
|
95
97
|
const result = makeGLSurface(ck, canvas, options, state.glContext, editor.graph.documentColorSpace);
|
|
96
98
|
state.glContext = result.glContext;
|
|
97
99
|
state.glHandle = result.glHandle;
|
|
@@ -156,7 +158,7 @@ function createCanvasSurfaceManager({ editor, canvasRef, options, getCanvasKit,
|
|
|
156
158
|
createSurface(canvas);
|
|
157
159
|
return;
|
|
158
160
|
}
|
|
159
|
-
sizeCanvas(canvas, editor, options?.onViewportResize, options?.maxPixelRatio);
|
|
161
|
+
origin.place(sizeCanvas(canvas, editor, options?.onViewportResize, options?.maxPixelRatio));
|
|
160
162
|
const result = makeGLSurface(ck, canvas, options, state.glContext, editor.graph.documentColorSpace);
|
|
161
163
|
state.glContext = result.glContext;
|
|
162
164
|
state.presentation = result.presentation;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lifecycle.js","names":[],"sources":["../../../src/canvas/surface/lifecycle.ts"],"sourcesContent":["import { useDocumentVisibility } from '@vueuse/core'\nimport type { CanvasKit } from 'canvaskit-wasm'\nimport { onScopeDispose, watch } from 'vue'\nimport type { Ref } from 'vue'\n\nimport type { Editor } from '@pairdraw/core'\nimport { SkiaRenderer } from '@pairdraw/core/canvas'\n\nimport {\n supportsWideGamutPresentation,\n type PresentationColorSpace\n} from '#vue/canvas/surface/color-space'\nimport {\n makeGLSurface,\n releaseWebGLContext,\n sizeCanvas,\n type CanvasGLContext,\n type CanvasGLHandle\n} from '#vue/canvas/surface/gl-surface'\nimport { createImagePreviewDecoder } from '#vue/canvas/surface/image-preview'\nimport { useCanvasKitLoader } from '#vue/canvas/surface/kit-loader'\nimport { createCanvasRenderLoop } from '#vue/canvas/surface/render-loop'\nimport { useCanvasResizeObserver } from '#vue/canvas/surface/resize-observer'\nimport { createShaderRasterizer } from '#vue/canvas/surface/shader/rasterizer'\nimport type { UseCanvasOptions } from '#vue/canvas/surface/types'\nimport { editorMessages } from '#vue/i18n/messages/editor'\n\n/**\n * The device's memory in bytes where the browser reports it. Browsers round it and stop at 8 GB,\n * which means at least that much, so a device at the cap is treated as unknown.\n */\nfunction reportedDeviceMemory(): number | undefined {\n // Chromium's Device Memory API; WebKit and Firefox leave it out.\n const gigabytes: unknown = Reflect.get(navigator, 'deviceMemory')\n if (typeof gigabytes !== 'number' || gigabytes >= 8) return undefined\n return gigabytes * 1024 ** 3\n}\n\ntype SurfaceManagerState = {\n renderer: SkiaRenderer | null\n glContext: CanvasGLContext | null\n glHandle: CanvasGLHandle | null\n /** The canvas the WebGL context belongs to, kept until the context is released. */\n glCanvas: HTMLCanvasElement | null\n presentation: PresentationColorSpace | null\n}\n\n/** What a canvas asks of its renderer: its layer, renderer mode, pixel density, and effects. */\nfunction applyRenderOptions(renderer: SkiaRenderer, options: UseCanvasOptions | undefined) {\n renderer.tracksSceneSettlement = options?.layer !== 'overlays'\n renderer.tiledSceneEnabled = options?.sceneRenderer === 'tiled'\n // The canvas buffer is sized for this ratio, so the renderer must draw at the same one.\n renderer.maxPixelRatio = options?.maxPixelRatio ?? Number.POSITIVE_INFINITY\n renderer.reducedEffects = options?.reducedEffects ?? false\n renderer.onNodeDrawFailure = options?.onNodeDrawFailure ?? null\n}\n\n/**\n * Shows only the scope layer the canvas asks for, or the whole page when it asks for none, with\n * the frames a playing prototype changed drawn from their play scenes, scrolled as play scrolled\n * them.\n */\nfunction applySceneScope(renderer: SkiaRenderer, options: UseCanvasOptions | undefined) {\n renderer.sceneScopeId = options?.getSceneScope?.() ?? null\n renderer.playScenes = options?.getPlayScenes?.() ?? null\n renderer.playScroll = options?.getPlayScroll?.() ?? null\n}\n\nexport function createCanvasSurfaceManager({\n editor,\n canvasRef,\n options,\n getCanvasKit,\n isDestroyed,\n shouldShowRulers\n}: {\n editor: Editor\n canvasRef: { value: HTMLCanvasElement | null }\n options: UseCanvasOptions | undefined\n getCanvasKit: () => CanvasKit | null\n isDestroyed: () => boolean\n shouldShowRulers: () => boolean\n}) {\n const state: SurfaceManagerState = {\n renderer: null,\n glContext: null,\n glHandle: null,\n glCanvas: null,\n presentation: null\n }\n let sceneBackingRenderTimer: ReturnType<typeof setTimeout> | null = null\n\n // The scene of an editing canvas shows an empty sticky note's placeholder, and every layer an\n // empty connector label's while it is typed into, as the overlays draw the text being edited,\n // in the interface language, and draws them again when the language changes.\n const showsStickyPlaceholder = options?.layer !== 'overlays'\n let stickyPlaceholder: string = editorMessages.get().stickyPlaceholder\n let connectorLabelPlaceholder: string = editorMessages.get().connectorLabelPlaceholder\n const stopPlaceholders = editorMessages.subscribe((messages) => {\n if (\n messages.stickyPlaceholder === stickyPlaceholder &&\n messages.connectorLabelPlaceholder === connectorLabelPlaceholder\n ) {\n return\n }\n ;({ stickyPlaceholder, connectorLabelPlaceholder } = messages)\n if (!state.renderer) return\n showPlaceholders(state.renderer)\n editor.requestRender()\n })\n\n function showPlaceholders(renderer: SkiaRenderer) {\n renderer.connectorLabelPlaceholder = connectorLabelPlaceholder\n if (showsStickyPlaceholder) renderer.stickyPlaceholder = stickyPlaceholder\n }\n\n /**\n * Tells the renderer's tiles what memory they share: a share of the device's where the browser\n * reports it, and only what the canvas showed last while the page is hidden.\n */\n function applyTileMemory() {\n state.renderer?.tiledScene.setMemory({\n deviceBytes: reportedDeviceMemory(),\n hidden: document.visibilityState === 'hidden'\n })\n }\n\n function clearSceneBackingRenderTimer() {\n if (sceneBackingRenderTimer === null) return\n clearTimeout(sceneBackingRenderTimer)\n sceneBackingRenderTimer = null\n }\n\n /** Releases the Skia context and the WebGL context CanvasKit registered for this canvas. */\n function releaseGLContext() {\n state.glContext?.delete()\n state.glContext = null\n const ck = getCanvasKit()\n if (ck && state.glHandle !== null) releaseWebGLContext(ck, state.glHandle, state.glCanvas)\n state.glHandle = null\n state.glCanvas = null\n }\n\n function createSurface(\n canvas: HTMLCanvasElement,\n { reloadFonts = false }: { reloadFonts?: boolean } = {}\n ): boolean {\n const ck = getCanvasKit()\n if (!ck) return false\n\n if (state.renderer) editor.removeCanvasRenderer(state.renderer)\n state.renderer?.destroy()\n state.renderer = null\n releaseGLContext()\n\n sizeCanvas(canvas, editor, options?.onViewportResize, options?.maxPixelRatio)\n\n const result = makeGLSurface(\n ck,\n canvas,\n options,\n state.glContext,\n editor.graph.documentColorSpace\n )\n state.glContext = result.glContext\n state.glHandle = result.glHandle\n state.glCanvas = result.glHandle === null ? null : canvas\n state.presentation = result.presentation\n options?.onPresentation?.(result.presentation)\n const surface = result.surface\n if (!surface) {\n canvas.dataset.surfaceError = 'webgl'\n return false\n }\n\n const glCtx = canvas.getContext('webgl2') ?? null\n state.renderer = new SkiaRenderer(ck, surface, glCtx)\n state.renderer.onImagePreviewReady = () => renderLoop.markDirty()\n state.renderer.imagePreviews.setDecoder(createImagePreviewDecoder())\n state.renderer.presentationColorSpace = result.presentation ?? 'srgb'\n applyRenderOptions(state.renderer, options)\n showPlaceholders(state.renderer)\n applyTileMemory()\n editor.setCanvasKit(ck, state.renderer)\n // The scene surface draws shader frames; an overlay surface has none to draw.\n if (options?.layer !== 'overlays' && !editor.hasShaderRasterizer())\n editor.setShaderRasterizer(createShaderRasterizer())\n canvas.dataset.ready = '1'\n\n // When the surface is recreated after a resize fallback, destroyRenderer\n // has cleared the module-level fontProvider — the new renderer must reload.\n // On initial mount, kit-loader.init() handles loadFonts, so skip here.\n if (reloadFonts && !isDestroyed()) {\n void state.renderer.loadFonts(renderNow).then(() => {\n if (!isDestroyed()) renderNow()\n return undefined\n })\n }\n return true\n }\n\n function acknowledgePresentation() {\n const renderedState = options?.getRenderState?.() ?? editor.state\n options?.onPresented?.({\n renderVersion: renderedState.renderVersion,\n sceneVersion: renderedState.sceneVersion\n })\n }\n\n function renderNow() {\n if (!state.renderer || isDestroyed()) return\n const view = options?.getRenderState?.() ?? editor.state\n applySceneScope(state.renderer, options)\n state.renderer.renderFromEditorState(\n view,\n editor.graph,\n editor.textEditor,\n canvasRef.value?.clientWidth ?? 0,\n canvasRef.value?.clientHeight ?? 0,\n shouldShowRulers(),\n options?.layer ?? 'full',\n editor.isInteractiveEditing()\n )\n renderLoop.markRendered()\n options?.onFrame?.({ panX: view.panX, panY: view.panY, zoom: view.zoom })\n acknowledgePresentation()\n clearSceneBackingRenderTimer()\n if (options?.layer === 'scene' && state.renderer.tiledScenePending) {\n renderLoop.markDirty()\n }\n if (options?.layer === 'scene' && state.renderer.sceneBackingNeedsCrispRender) {\n const delay = Math.max(0, state.renderer.sceneBackingPreviewUntil - performance.now())\n sceneBackingRenderTimer = setTimeout(() => renderLoop.markDirty(), delay)\n }\n }\n\n const renderLoop = createCanvasRenderLoop(editor, renderNow, {\n layer: options?.layer,\n getRenderState: options?.getRenderState,\n shouldSuspendRender: options?.shouldSuspendRender\n })\n\n function resizeCanvas(canvas: HTMLCanvasElement) {\n const ck = getCanvasKit()\n if (!ck || !state.renderer) {\n createSurface(canvas)\n return\n }\n\n sizeCanvas(canvas, editor, options?.onViewportResize, options?.maxPixelRatio)\n\n const result = makeGLSurface(\n ck,\n canvas,\n options,\n state.glContext,\n editor.graph.documentColorSpace\n )\n state.glContext = result.glContext\n state.presentation = result.presentation\n options?.onPresentation?.(result.presentation)\n const surface = result.surface\n if (!surface) {\n console.warn('Falling back to full surface recreation after resize')\n createSurface(canvas, { reloadFonts: true })\n return\n }\n state.renderer.presentationColorSpace = result.presentation ?? 'srgb'\n state.renderer.replaceSurface(surface)\n renderNow()\n }\n\n const wantsWideGamut = () =>\n editor.graph.documentColorSpace === 'display-p3' && supportsWideGamutPresentation()\n\n /** A P3 document needs the P3 surface, and vice versa; documents arrive after mount. */\n function refreshPresentation() {\n if (isDestroyed()) return\n const canvas = canvasRef.value\n if (!canvas) return\n if (wantsWideGamut() === (state.presentation === 'display-p3')) return\n createSurface(canvas, { reloadFonts: true })\n }\n\n const stopPresentationRefresh = editor.onEditorEvent('graph:replaced', refreshPresentation)\n const stopColorSpaceRefresh = editor.onEditorEvent(\n 'document:color-space-changed',\n refreshPresentation\n )\n\n function destroy() {\n stopPlaceholders()\n stopPresentationRefresh()\n stopColorSpaceRefresh()\n clearSceneBackingRenderTimer()\n renderLoop.pause()\n if (state.renderer) editor.removeCanvasRenderer(state.renderer)\n state.renderer?.destroy()\n releaseGLContext()\n }\n\n return {\n createSurface,\n resizeCanvas,\n renderNow,\n destroy,\n markDirty: () => renderLoop.markDirty(),\n applyTileMemory,\n getRenderer: () => state.renderer,\n getPresentation: () => state.presentation\n }\n}\n\n/**\n * A browser takes a canvas's WebGL context away on a GPU reset, a driver update, or a tab that\n * comes back from sleep. Ignoring the events leaves the canvas blank for good: the loss is\n * prevented so the context can be given back. The app replaces the element, which starts again.\n * An SDK canvas keeps its element, so the surface is made again on that same element once the\n * browser gives the context back.\n */\nfunction connectContextRecovery(\n canvasRef: Ref<HTMLCanvasElement | null>,\n lifecycle: { destroyed: boolean },\n onContextLost: (() => void) | undefined,\n recreateSurface: (canvas: HTMLCanvasElement) => void\n): void {\n watch(\n canvasRef,\n (canvas, _previous, onCleanup) => {\n if (!canvas) return\n const onLost = (event: Event) => {\n // The host may replace the canvas, because a context the browser keeps lost can never be\n // drawn into again; a fresh element gets a fresh context.\n event.preventDefault()\n if (lifecycle.destroyed) return\n onContextLost?.()\n }\n const onRestored = () => {\n if (lifecycle.destroyed) return\n // A host that already swapped in a new element must not have the old one's restore\n // rebuild a surface for a canvas that is no longer shown.\n if (canvasRef.value !== canvas) return\n recreateSurface(canvas)\n }\n canvas.addEventListener('webglcontextlost', onLost)\n canvas.addEventListener('webglcontextrestored', onRestored)\n onCleanup(() => {\n canvas.removeEventListener('webglcontextlost', onLost)\n canvas.removeEventListener('webglcontextrestored', onRestored)\n })\n },\n { flush: 'post' }\n )\n}\n\nexport function useCanvasSurfaceLifecycle({\n canvasRef,\n surface,\n setCanvasKit,\n getCanvasKitValue,\n lifecycle,\n onReady,\n onFailed,\n onContextLost,\n loadCanvasKit\n}: {\n canvasRef: Ref<HTMLCanvasElement | null>\n surface: ReturnType<typeof createCanvasSurfaceManager>\n setCanvasKit: (ck: CanvasKit | null) => void\n getCanvasKitValue: () => CanvasKit | null\n lifecycle: { destroyed: boolean }\n onReady?: () => void\n onFailed?: (error: unknown) => void\n onContextLost?: () => void\n /** Loads CanvasKit. The canvas uses the shared loader; a test can pass a stand-in. */\n loadCanvasKit?: () => Promise<CanvasKit>\n}) {\n useCanvasKitLoader({\n canvasRef,\n lifecycle,\n setCanvasKit,\n createSurface: surface.createSurface,\n loadFonts: () => surface.getRenderer()?.loadFonts(surface.renderNow),\n renderNow: surface.renderNow,\n onReady,\n onFailed,\n loadCanvasKit\n })\n\n connectContextRecovery(canvasRef, lifecycle, onContextLost, (canvas) => {\n surface.createSurface(canvas, { reloadFonts: true })\n })\n\n const { cancelResize } = useCanvasResizeObserver({\n canvasRef,\n getCanvasKitValue,\n resizeCanvas: surface.resizeCanvas\n })\n\n // A hidden page draws nothing, so its tiles shrink to what it showed last until it is back.\n watch(useDocumentVisibility(), () => surface.applyTileMemory())\n\n onScopeDispose(() => {\n lifecycle.destroyed = true\n cancelResize()\n surface.destroy()\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA+BA,SAAS,uBAA2C;CAElD,MAAM,YAAqB,QAAQ,IAAI,WAAW,cAAc;CAChE,IAAI,OAAO,cAAc,YAAY,aAAa,GAAG,OAAO,KAAA;CAC5D,OAAO,YAAY,QAAQ;AAC7B;;AAYA,SAAS,mBAAmB,UAAwB,SAAuC;CACzF,SAAS,wBAAwB,SAAS,UAAU;CACpD,SAAS,oBAAoB,SAAS,kBAAkB;CAExD,SAAS,gBAAgB,SAAS,iBAAiB,OAAO;CAC1D,SAAS,iBAAiB,SAAS,kBAAkB;CACrD,SAAS,oBAAoB,SAAS,qBAAqB;AAC7D;;;;;;AAOA,SAAS,gBAAgB,UAAwB,SAAuC;CACtF,SAAS,eAAe,SAAS,gBAAgB,KAAK;CACtD,SAAS,aAAa,SAAS,gBAAgB,KAAK;CACpD,SAAS,aAAa,SAAS,gBAAgB,KAAK;AACtD;AAEA,SAAgB,2BAA2B,EACzC,QACA,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E,UAAU,QAAQ,SAAS;EACnE,WAAW,QAAQ;EACnB;EACA;EACA;CACF,CAAC;CAED,uBAAuB,WAAW,WAAW,gBAAgB,WAAW;EACtE,QAAQ,cAAc,QAAQ,EAAE,aAAa,KAAK,CAAC;CACrD,CAAC;CAED,MAAM,EAAE,iBAAiB,wBAAwB;EAC/C;EACA;EACA,cAAc,QAAQ;CACxB,CAAC;CAGD,MAAM,sBAAsB,SAAS,QAAQ,gBAAgB,CAAC;CAE9D,qBAAqB;EACnB,UAAU,YAAY;EACtB,aAAa;EACb,QAAQ,QAAQ;CAClB,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"lifecycle.js","names":[],"sources":["../../../src/canvas/surface/lifecycle.ts"],"sourcesContent":["import { useDocumentVisibility } from '@vueuse/core'\nimport type { CanvasKit } from 'canvaskit-wasm'\nimport { onScopeDispose, watch } from 'vue'\nimport type { Ref } from 'vue'\n\nimport type { Editor } from '@pairdraw/core'\nimport { SkiaRenderer } from '@pairdraw/core/canvas'\n\nimport {\n supportsWideGamutPresentation,\n type PresentationColorSpace\n} from '#vue/canvas/surface/color-space'\nimport {\n makeGLSurface,\n releaseWebGLContext,\n sizeCanvas,\n type CanvasGLContext,\n type CanvasGLHandle\n} from '#vue/canvas/surface/gl-surface'\nimport { createImagePreviewDecoder } from '#vue/canvas/surface/image-preview'\nimport { useCanvasKitLoader } from '#vue/canvas/surface/kit-loader'\nimport { createCanvasOriginTracker } from '#vue/canvas/surface/origin'\nimport { createCanvasRenderLoop } from '#vue/canvas/surface/render-loop'\nimport { useCanvasResizeObserver } from '#vue/canvas/surface/resize-observer'\nimport { createShaderRasterizer } from '#vue/canvas/surface/shader/rasterizer'\nimport type { UseCanvasOptions } from '#vue/canvas/surface/types'\nimport { editorMessages } from '#vue/i18n/messages/editor'\n\n/**\n * The device's memory in bytes where the browser reports it. Browsers round it and stop at 8 GB,\n * which means at least that much, so a device at the cap is treated as unknown.\n */\nfunction reportedDeviceMemory(): number | undefined {\n // Chromium's Device Memory API; WebKit and Firefox leave it out.\n const gigabytes: unknown = Reflect.get(navigator, 'deviceMemory')\n if (typeof gigabytes !== 'number' || gigabytes >= 8) return undefined\n return gigabytes * 1024 ** 3\n}\n\ntype SurfaceManagerState = {\n renderer: SkiaRenderer | null\n glContext: CanvasGLContext | null\n glHandle: CanvasGLHandle | null\n /** The canvas the WebGL context belongs to, kept until the context is released. */\n glCanvas: HTMLCanvasElement | null\n presentation: PresentationColorSpace | null\n}\n\n/** What a canvas asks of its renderer: its layer, renderer mode, pixel density, and effects. */\nfunction applyRenderOptions(renderer: SkiaRenderer, options: UseCanvasOptions | undefined) {\n renderer.tracksSceneSettlement = options?.layer !== 'overlays'\n renderer.tiledSceneEnabled = options?.sceneRenderer === 'tiled'\n // The canvas buffer is sized for this ratio, so the renderer must draw at the same one.\n renderer.maxPixelRatio = options?.maxPixelRatio ?? Number.POSITIVE_INFINITY\n renderer.reducedEffects = options?.reducedEffects ?? false\n renderer.onNodeDrawFailure = options?.onNodeDrawFailure ?? null\n}\n\n/**\n * Shows only the scope layer the canvas asks for, or the whole page when it asks for none, with\n * the frames a playing prototype changed drawn from their play scenes, scrolled as play scrolled\n * them.\n */\nfunction applySceneScope(renderer: SkiaRenderer, options: UseCanvasOptions | undefined) {\n renderer.sceneScopeId = options?.getSceneScope?.() ?? null\n renderer.playScenes = options?.getPlayScenes?.() ?? null\n renderer.playScroll = options?.getPlayScroll?.() ?? null\n}\n\nexport function createCanvasSurfaceManager({\n editor,\n canvasRef,\n options,\n getCanvasKit,\n isDestroyed,\n shouldShowRulers\n}: {\n editor: Editor\n canvasRef: { value: HTMLCanvasElement | null }\n options: UseCanvasOptions | undefined\n getCanvasKit: () => CanvasKit | null\n isDestroyed: () => boolean\n shouldShowRulers: () => boolean\n}) {\n const origin = createCanvasOriginTracker(options?.onViewportMove)\n const state: SurfaceManagerState = {\n renderer: null,\n glContext: null,\n glHandle: null,\n glCanvas: null,\n presentation: null\n }\n let sceneBackingRenderTimer: ReturnType<typeof setTimeout> | null = null\n\n // The scene of an editing canvas shows an empty sticky note's placeholder, and every layer an\n // empty connector label's while it is typed into, as the overlays draw the text being edited,\n // in the interface language, and draws them again when the language changes.\n const showsStickyPlaceholder = options?.layer !== 'overlays'\n let stickyPlaceholder: string = editorMessages.get().stickyPlaceholder\n let connectorLabelPlaceholder: string = editorMessages.get().connectorLabelPlaceholder\n const stopPlaceholders = editorMessages.subscribe((messages) => {\n if (\n messages.stickyPlaceholder === stickyPlaceholder &&\n messages.connectorLabelPlaceholder === connectorLabelPlaceholder\n ) {\n return\n }\n ;({ stickyPlaceholder, connectorLabelPlaceholder } = messages)\n if (!state.renderer) return\n showPlaceholders(state.renderer)\n editor.requestRender()\n })\n\n function showPlaceholders(renderer: SkiaRenderer) {\n renderer.connectorLabelPlaceholder = connectorLabelPlaceholder\n if (showsStickyPlaceholder) renderer.stickyPlaceholder = stickyPlaceholder\n }\n\n /**\n * Tells the renderer's tiles what memory they share: a share of the device's where the browser\n * reports it, and only what the canvas showed last while the page is hidden.\n */\n function applyTileMemory() {\n state.renderer?.tiledScene.setMemory({\n deviceBytes: reportedDeviceMemory(),\n hidden: document.visibilityState === 'hidden'\n })\n }\n\n function clearSceneBackingRenderTimer() {\n if (sceneBackingRenderTimer === null) return\n clearTimeout(sceneBackingRenderTimer)\n sceneBackingRenderTimer = null\n }\n\n /** Releases the Skia context and the WebGL context CanvasKit registered for this canvas. */\n function releaseGLContext() {\n state.glContext?.delete()\n state.glContext = null\n const ck = getCanvasKit()\n if (ck && state.glHandle !== null) releaseWebGLContext(ck, state.glHandle, state.glCanvas)\n state.glHandle = null\n state.glCanvas = null\n }\n\n function createSurface(\n canvas: HTMLCanvasElement,\n { reloadFonts = false }: { reloadFonts?: boolean } = {}\n ): boolean {\n const ck = getCanvasKit()\n if (!ck) return false\n\n if (state.renderer) editor.removeCanvasRenderer(state.renderer)\n state.renderer?.destroy()\n state.renderer = null\n releaseGLContext()\n\n origin.place(sizeCanvas(canvas, editor, options?.onViewportResize, options?.maxPixelRatio))\n\n const result = makeGLSurface(\n ck,\n canvas,\n options,\n state.glContext,\n editor.graph.documentColorSpace\n )\n state.glContext = result.glContext\n state.glHandle = result.glHandle\n state.glCanvas = result.glHandle === null ? null : canvas\n state.presentation = result.presentation\n options?.onPresentation?.(result.presentation)\n const surface = result.surface\n if (!surface) {\n canvas.dataset.surfaceError = 'webgl'\n return false\n }\n\n const glCtx = canvas.getContext('webgl2') ?? null\n state.renderer = new SkiaRenderer(ck, surface, glCtx)\n state.renderer.onImagePreviewReady = () => renderLoop.markDirty()\n state.renderer.imagePreviews.setDecoder(createImagePreviewDecoder())\n state.renderer.presentationColorSpace = result.presentation ?? 'srgb'\n applyRenderOptions(state.renderer, options)\n showPlaceholders(state.renderer)\n applyTileMemory()\n editor.setCanvasKit(ck, state.renderer)\n // The scene surface draws shader frames; an overlay surface has none to draw.\n if (options?.layer !== 'overlays' && !editor.hasShaderRasterizer())\n editor.setShaderRasterizer(createShaderRasterizer())\n canvas.dataset.ready = '1'\n\n // When the surface is recreated after a resize fallback, destroyRenderer\n // has cleared the module-level fontProvider — the new renderer must reload.\n // On initial mount, kit-loader.init() handles loadFonts, so skip here.\n if (reloadFonts && !isDestroyed()) {\n void state.renderer.loadFonts(renderNow).then(() => {\n if (!isDestroyed()) renderNow()\n return undefined\n })\n }\n return true\n }\n\n function acknowledgePresentation() {\n const renderedState = options?.getRenderState?.() ?? editor.state\n options?.onPresented?.({\n renderVersion: renderedState.renderVersion,\n sceneVersion: renderedState.sceneVersion\n })\n }\n\n function renderNow() {\n if (!state.renderer || isDestroyed()) return\n const view = options?.getRenderState?.() ?? editor.state\n applySceneScope(state.renderer, options)\n state.renderer.renderFromEditorState(\n view,\n editor.graph,\n editor.textEditor,\n canvasRef.value?.clientWidth ?? 0,\n canvasRef.value?.clientHeight ?? 0,\n shouldShowRulers(),\n options?.layer ?? 'full',\n editor.isInteractiveEditing()\n )\n renderLoop.markRendered()\n options?.onFrame?.({ panX: view.panX, panY: view.panY, zoom: view.zoom })\n acknowledgePresentation()\n clearSceneBackingRenderTimer()\n if (options?.layer === 'scene' && state.renderer.tiledScenePending) {\n renderLoop.markDirty()\n }\n if (options?.layer === 'scene' && state.renderer.sceneBackingNeedsCrispRender) {\n const delay = Math.max(0, state.renderer.sceneBackingPreviewUntil - performance.now())\n sceneBackingRenderTimer = setTimeout(() => renderLoop.markDirty(), delay)\n }\n }\n\n const renderLoop = createCanvasRenderLoop(editor, renderNow, {\n layer: options?.layer,\n getRenderState: options?.getRenderState,\n shouldSuspendRender: options?.shouldSuspendRender\n })\n\n function resizeCanvas(canvas: HTMLCanvasElement) {\n const ck = getCanvasKit()\n if (!ck || !state.renderer) {\n createSurface(canvas)\n return\n }\n\n origin.place(sizeCanvas(canvas, editor, options?.onViewportResize, options?.maxPixelRatio))\n\n const result = makeGLSurface(\n ck,\n canvas,\n options,\n state.glContext,\n editor.graph.documentColorSpace\n )\n state.glContext = result.glContext\n state.presentation = result.presentation\n options?.onPresentation?.(result.presentation)\n const surface = result.surface\n if (!surface) {\n console.warn('Falling back to full surface recreation after resize')\n createSurface(canvas, { reloadFonts: true })\n return\n }\n state.renderer.presentationColorSpace = result.presentation ?? 'srgb'\n state.renderer.replaceSurface(surface)\n renderNow()\n }\n\n const wantsWideGamut = () =>\n editor.graph.documentColorSpace === 'display-p3' && supportsWideGamutPresentation()\n\n /** A P3 document needs the P3 surface, and vice versa; documents arrive after mount. */\n function refreshPresentation() {\n if (isDestroyed()) return\n const canvas = canvasRef.value\n if (!canvas) return\n if (wantsWideGamut() === (state.presentation === 'display-p3')) return\n createSurface(canvas, { reloadFonts: true })\n }\n\n const stopPresentationRefresh = editor.onEditorEvent('graph:replaced', refreshPresentation)\n const stopColorSpaceRefresh = editor.onEditorEvent(\n 'document:color-space-changed',\n refreshPresentation\n )\n\n function destroy() {\n stopPlaceholders()\n stopPresentationRefresh()\n stopColorSpaceRefresh()\n clearSceneBackingRenderTimer()\n renderLoop.pause()\n if (state.renderer) editor.removeCanvasRenderer(state.renderer)\n state.renderer?.destroy()\n releaseGLContext()\n }\n\n return {\n createSurface,\n resizeCanvas,\n renderNow,\n destroy,\n markDirty: () => renderLoop.markDirty(),\n applyTileMemory,\n getRenderer: () => state.renderer,\n getPresentation: () => state.presentation\n }\n}\n\n/**\n * A browser takes a canvas's WebGL context away on a GPU reset, a driver update, or a tab that\n * comes back from sleep. Ignoring the events leaves the canvas blank for good: the loss is\n * prevented so the context can be given back. The app replaces the element, which starts again.\n * An SDK canvas keeps its element, so the surface is made again on that same element once the\n * browser gives the context back.\n */\nfunction connectContextRecovery(\n canvasRef: Ref<HTMLCanvasElement | null>,\n lifecycle: { destroyed: boolean },\n onContextLost: (() => void) | undefined,\n recreateSurface: (canvas: HTMLCanvasElement) => void\n): void {\n watch(\n canvasRef,\n (canvas, _previous, onCleanup) => {\n if (!canvas) return\n const onLost = (event: Event) => {\n // The host may replace the canvas, because a context the browser keeps lost can never be\n // drawn into again; a fresh element gets a fresh context.\n event.preventDefault()\n if (lifecycle.destroyed) return\n onContextLost?.()\n }\n const onRestored = () => {\n if (lifecycle.destroyed) return\n // A host that already swapped in a new element must not have the old one's restore\n // rebuild a surface for a canvas that is no longer shown.\n if (canvasRef.value !== canvas) return\n recreateSurface(canvas)\n }\n canvas.addEventListener('webglcontextlost', onLost)\n canvas.addEventListener('webglcontextrestored', onRestored)\n onCleanup(() => {\n canvas.removeEventListener('webglcontextlost', onLost)\n canvas.removeEventListener('webglcontextrestored', onRestored)\n })\n },\n { flush: 'post' }\n )\n}\n\nexport function useCanvasSurfaceLifecycle({\n canvasRef,\n surface,\n setCanvasKit,\n getCanvasKitValue,\n lifecycle,\n onReady,\n onFailed,\n onContextLost,\n loadCanvasKit\n}: {\n canvasRef: Ref<HTMLCanvasElement | null>\n surface: ReturnType<typeof createCanvasSurfaceManager>\n setCanvasKit: (ck: CanvasKit | null) => void\n getCanvasKitValue: () => CanvasKit | null\n lifecycle: { destroyed: boolean }\n onReady?: () => void\n onFailed?: (error: unknown) => void\n onContextLost?: () => void\n /** Loads CanvasKit. The canvas uses the shared loader; a test can pass a stand-in. */\n loadCanvasKit?: () => Promise<CanvasKit>\n}) {\n useCanvasKitLoader({\n canvasRef,\n lifecycle,\n setCanvasKit,\n createSurface: surface.createSurface,\n loadFonts: () => surface.getRenderer()?.loadFonts(surface.renderNow),\n renderNow: surface.renderNow,\n onReady,\n onFailed,\n loadCanvasKit\n })\n\n connectContextRecovery(canvasRef, lifecycle, onContextLost, (canvas) => {\n surface.createSurface(canvas, { reloadFonts: true })\n })\n\n const { cancelResize } = useCanvasResizeObserver({\n canvasRef,\n getCanvasKitValue,\n resizeCanvas: surface.resizeCanvas\n })\n\n // A hidden page draws nothing, so its tiles shrink to what it showed last until it is back.\n watch(useDocumentVisibility(), () => surface.applyTileMemory())\n\n onScopeDispose(() => {\n lifecycle.destroyed = true\n cancelResize()\n surface.destroy()\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAgCA,SAAS,uBAA2C;CAElD,MAAM,YAAqB,QAAQ,IAAI,WAAW,cAAc;CAChE,IAAI,OAAO,cAAc,YAAY,aAAa,GAAG,OAAO,KAAA;CAC5D,OAAO,YAAY,QAAQ;AAC7B;;AAYA,SAAS,mBAAmB,UAAwB,SAAuC;CACzF,SAAS,wBAAwB,SAAS,UAAU;CACpD,SAAS,oBAAoB,SAAS,kBAAkB;CAExD,SAAS,gBAAgB,SAAS,iBAAiB,OAAO;CAC1D,SAAS,iBAAiB,SAAS,kBAAkB;CACrD,SAAS,oBAAoB,SAAS,qBAAqB;AAC7D;;;;;;AAOA,SAAS,gBAAgB,UAAwB,SAAuC;CACtF,SAAS,eAAe,SAAS,gBAAgB,KAAK;CACtD,SAAS,aAAa,SAAS,gBAAgB,KAAK;CACpD,SAAS,aAAa,SAAS,gBAAgB,KAAK;AACtD;AAEA,SAAgB,2BAA2B,EACzC,QACA,WACA,SACA,cACA,aACA,oBAQC;CACD,MAAM,SAAS,0BAA0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B,QAAQ,YAAY,CAAC,EAAE,UAAU,QAAQ,SAAS;EACnE,WAAW,QAAQ;EACnB;EACA;EACA;CACF,CAAC;CAED,uBAAuB,WAAW,WAAW,gBAAgB,WAAW;EACtE,QAAQ,cAAc,QAAQ,EAAE,aAAa,KAAK,CAAC;CACrD,CAAC;CAED,MAAM,EAAE,iBAAiB,wBAAwB;EAC/C;EACA;EACA,cAAc,QAAQ;CACxB,CAAC;CAGD,MAAM,sBAAsB,SAAS,QAAQ,gBAAgB,CAAC;CAE9D,qBAAqB;EACnB,UAAU,YAAY;EACtB,aAAa;EACb,QAAQ,QAAQ;CAClB,CAAC;AACH"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
//#region src/canvas/surface/origin.ts
|
|
2
|
+
function createCanvasOriginTracker(onMove) {
|
|
3
|
+
let origin = null;
|
|
4
|
+
return { place(next) {
|
|
5
|
+
const previous = origin;
|
|
6
|
+
origin = next;
|
|
7
|
+
if (!onMove || !previous || previous.x === next.x && previous.y === next.y) return;
|
|
8
|
+
onMove(next.x - previous.x, next.y - previous.y);
|
|
9
|
+
} };
|
|
10
|
+
}
|
|
11
|
+
//#endregion
|
|
12
|
+
export { createCanvasOriginTracker };
|
|
13
|
+
|
|
14
|
+
//# sourceMappingURL=origin.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"origin.js","names":[],"sources":["../../../src/canvas/surface/origin.ts"],"sourcesContent":["import type { Vector } from '@pairdraw/scene-graph/primitives'\n\nimport type { UseCanvasOptions } from '#vue/canvas/surface/types'\n\nexport function createCanvasOriginTracker(onMove: UseCanvasOptions['onViewportMove']) {\n let origin: Vector | null = null\n\n return {\n place(next: Vector) {\n const previous = origin\n origin = next\n if (!onMove || !previous || (previous.x === next.x && previous.y === next.y)) {\n return\n }\n onMove(next.x - previous.x, next.y - previous.y)\n }\n }\n}\n"],"mappings":";AAIA,SAAgB,0BAA0B,QAA4C;CACpF,IAAI,SAAwB;CAE5B,OAAO,EACL,MAAM,MAAc;EAClB,MAAM,WAAW;EACjB,SAAS;EACT,IAAI,CAAC,UAAU,CAAC,YAAa,SAAS,MAAM,KAAK,KAAK,SAAS,MAAM,KAAK,GACxE;EAEF,OAAO,KAAK,IAAI,SAAS,GAAG,KAAK,IAAI,SAAS,CAAC;CACjD,EACF;AACF"}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { isShaderPresetPaint, readShaderPaints, shaderOfPaint } from "@pairdraw/scene-graph/shaders";
|
|
2
|
+
//#region src/canvas/surface/shader/plan.ts
|
|
3
|
+
/** Whether `node` and every layer above it are visible, so the canvas draws it. */
|
|
4
|
+
function isShown(node, graph) {
|
|
5
|
+
return graph.closest(node.id, (current) => !current.visible) === void 0;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Each image a preset shader on `pageId` shows, with its preset and the layers painting it, as
|
|
9
|
+
* far as a player may draw it: a hidden layer, a hidden ancestor, a hidden paint, or code the
|
|
10
|
+
* user wrote (which the canvas compiles itself) is left out.
|
|
11
|
+
*/
|
|
12
|
+
function shadersOnPage(graph, pageId) {
|
|
13
|
+
const found = /* @__PURE__ */ new Map();
|
|
14
|
+
for (const node of graph.getAllNodes()) {
|
|
15
|
+
if (readShaderPaints(node).length === 0 || !graph.isDescendant(node.id, pageId)) continue;
|
|
16
|
+
if (!isShown(node, graph)) continue;
|
|
17
|
+
for (const paint of [...node.fills, ...node.strokes]) {
|
|
18
|
+
if (!paint.visible) continue;
|
|
19
|
+
const shader = shaderOfPaint(node, paint);
|
|
20
|
+
if (!shader || !isShaderPresetPaint(shader)) continue;
|
|
21
|
+
const entry = found.get(shader.image) ?? {
|
|
22
|
+
preset: shader.preset,
|
|
23
|
+
nodeIds: /* @__PURE__ */ new Set(),
|
|
24
|
+
bounds: []
|
|
25
|
+
};
|
|
26
|
+
entry.nodeIds.add(node.id);
|
|
27
|
+
entry.bounds.push(graph.getAbsoluteBounds(node.id));
|
|
28
|
+
found.set(shader.image, entry);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return found;
|
|
32
|
+
}
|
|
33
|
+
/** Whether any part of `bounds` is inside the view, at its pan and zoom. */
|
|
34
|
+
function onScreen(bounds, view, viewport) {
|
|
35
|
+
return bounds.some((rect) => rect.x * view.zoom + view.panX < viewport.width && (rect.x + rect.width) * view.zoom + view.panX > 0 && rect.y * view.zoom + view.panY < viewport.height && (rect.y + rect.height) * view.zoom + view.panY > 0);
|
|
36
|
+
}
|
|
37
|
+
//#endregion
|
|
38
|
+
export { onScreen, shadersOnPage };
|
|
39
|
+
|
|
40
|
+
//# sourceMappingURL=plan.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"plan.js","names":[],"sources":["../../../../src/canvas/surface/shader/plan.ts"],"sourcesContent":["import type { ViewportTransform } from '@pairdraw/core/geometry'\nimport type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'\nimport type { Rect } from '@pairdraw/scene-graph/primitives'\nimport {\n isShaderPresetPaint,\n readShaderPaints,\n shaderOfPaint,\n type ShaderPreset\n} from '@pairdraw/scene-graph/shaders'\n\n/** A shader preset a page draws, and the layers that paint it. */\nexport interface PageShader {\n preset: ShaderPreset\n nodeIds: Set<string>\n /** Where the layers that paint it are, on the page. */\n bounds: Rect[]\n}\n\n/** Whether `node` and every layer above it are visible, so the canvas draws it. */\nfunction isShown(node: SceneNode, graph: SceneGraph): boolean {\n return graph.closest(node.id, (current) => !current.visible) === undefined\n}\n\n/**\n * Each image a preset shader on `pageId` shows, with its preset and the layers painting it, as\n * far as a player may draw it: a hidden layer, a hidden ancestor, a hidden paint, or code the\n * user wrote (which the canvas compiles itself) is left out.\n */\nexport function shadersOnPage(graph: SceneGraph, pageId: string): Map<string, PageShader> {\n const found = new Map<string, PageShader>()\n for (const node of graph.getAllNodes()) {\n if (readShaderPaints(node).length === 0 || !graph.isDescendant(node.id, pageId)) continue\n if (!isShown(node, graph)) continue\n for (const paint of [...node.fills, ...node.strokes]) {\n if (!paint.visible) continue\n const shader = shaderOfPaint(node, paint)\n if (!shader || !isShaderPresetPaint(shader)) continue\n const entry = found.get(shader.image) ?? {\n preset: shader.preset,\n nodeIds: new Set<string>(),\n bounds: []\n }\n entry.nodeIds.add(node.id)\n entry.bounds.push(graph.getAbsoluteBounds(node.id))\n found.set(shader.image, entry)\n }\n }\n return found\n}\n\n/** Whether any part of `bounds` is inside the view, at its pan and zoom. */\nexport function onScreen(\n bounds: readonly Rect[],\n view: ViewportTransform,\n viewport: { width: number; height: number }\n): boolean {\n return bounds.some(\n (rect) =>\n rect.x * view.zoom + view.panX < viewport.width &&\n (rect.x + rect.width) * view.zoom + view.panX > 0 &&\n rect.y * view.zoom + view.panY < viewport.height &&\n (rect.y + rect.height) * view.zoom + view.panY > 0\n )\n}\n"],"mappings":";;;AAmBA,SAAS,QAAQ,MAAiB,OAA4B;CAC5D,OAAO,MAAM,QAAQ,KAAK,KAAK,YAAY,CAAC,QAAQ,OAAO,MAAM,KAAA;AACnE;;;;;;AAOA,SAAgB,cAAc,OAAmB,QAAyC;CACxF,MAAM,wBAAQ,IAAI,IAAwB;CAC1C,KAAK,MAAM,QAAQ,MAAM,YAAY,GAAG;EACtC,IAAI,iBAAiB,IAAI,CAAC,CAAC,WAAW,KAAK,CAAC,MAAM,aAAa,KAAK,IAAI,MAAM,GAAG;EACjF,IAAI,CAAC,QAAQ,MAAM,KAAK,GAAG;EAC3B,KAAK,MAAM,SAAS,CAAC,GAAG,KAAK,OAAO,GAAG,KAAK,OAAO,GAAG;GACpD,IAAI,CAAC,MAAM,SAAS;GACpB,MAAM,SAAS,cAAc,MAAM,KAAK;GACxC,IAAI,CAAC,UAAU,CAAC,oBAAoB,MAAM,GAAG;GAC7C,MAAM,QAAQ,MAAM,IAAI,OAAO,KAAK,KAAK;IACvC,QAAQ,OAAO;IACf,yBAAS,IAAI,IAAY;IACzB,QAAQ,CAAC;GACX;GACA,MAAM,QAAQ,IAAI,KAAK,EAAE;GACzB,MAAM,OAAO,KAAK,MAAM,kBAAkB,KAAK,EAAE,CAAC;GAClD,MAAM,IAAI,OAAO,OAAO,KAAK;EAC/B;CACF;CACA,OAAO;AACT;;AAGA,SAAgB,SACd,QACA,MACA,UACS;CACT,OAAO,OAAO,MACX,SACC,KAAK,IAAI,KAAK,OAAO,KAAK,OAAO,SAAS,UACzC,KAAK,IAAI,KAAK,SAAS,KAAK,OAAO,KAAK,OAAO,KAChD,KAAK,IAAI,KAAK,OAAO,KAAK,OAAO,SAAS,WACzC,KAAK,IAAI,KAAK,UAAU,KAAK,OAAO,KAAK,OAAO,CACrD;AACF"}
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { canDrawShaders } from "./rasterizer.js";
|
|
2
2
|
import { shaderFrames } from "./frames.js";
|
|
3
|
+
import { onScreen, shadersOnPage } from "./plan.js";
|
|
3
4
|
import { onScopeDispose, watch } from "vue";
|
|
4
5
|
import { useRafFn, watchThrottled } from "@vueuse/core";
|
|
5
|
-
import {
|
|
6
|
+
import { presetAnimates } from "@pairdraw/scene-graph/shaders";
|
|
6
7
|
import { resolveEditorProfile } from "@pairdraw/core";
|
|
7
8
|
//#region src/canvas/surface/shader/playback.ts
|
|
8
9
|
/** The longest side a playing shader is drawn at, however large it is on screen. */
|
|
@@ -19,25 +20,32 @@ const COPY_FRAME_MS = 1e3 / 30;
|
|
|
19
20
|
const VIEW_CHECK_MS = 200;
|
|
20
21
|
/** How much a shader's size on screen may change before it is drawn at the new size. */
|
|
21
22
|
const RESIZE_FACTOR = 1.5;
|
|
22
|
-
/**
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
}
|
|
23
|
+
/**
|
|
24
|
+
* The most shaders a page plays at once. Each player is a WebGPU canvas, so a document of
|
|
25
|
+
* hundreds of shader layers plays the ones on screen and stays within what a GPU can hold.
|
|
26
|
+
*/
|
|
27
|
+
const MAX_PLAYERS = 16;
|
|
28
|
+
const playbackStats = /* @__PURE__ */ new WeakMap();
|
|
29
|
+
/** The library's motion metadata, by effect name, read from its registry. */
|
|
30
|
+
async function libraryMotions() {
|
|
31
|
+
const { getAllShaders } = await import("shaders/registry");
|
|
32
|
+
const known = /* @__PURE__ */ new Map();
|
|
33
|
+
for (const entry of getAllShaders()) {
|
|
34
|
+
const { name, definition } = entry;
|
|
35
|
+
if (typeof name !== "string") continue;
|
|
36
|
+
known.set(name, {
|
|
37
|
+
animates: definition?.animatedTime !== void 0,
|
|
38
|
+
speed: definition?.props?.speed !== void 0
|
|
39
|
+
});
|
|
39
40
|
}
|
|
40
|
-
return
|
|
41
|
+
return known;
|
|
42
|
+
}
|
|
43
|
+
/** Starts the library's renderer for `preset` on `canvas`, ready to draw frames. */
|
|
44
|
+
async function libraryPlayer(preset, canvas) {
|
|
45
|
+
const { createRendererFromJSON } = await import("shaders/core");
|
|
46
|
+
const renderer = createRendererFromJSON(structuredClone(preset));
|
|
47
|
+
await renderer.initialize(canvas);
|
|
48
|
+
return renderer;
|
|
41
49
|
}
|
|
42
50
|
/**
|
|
43
51
|
* Plays the shader paints on screen while the editor previews a page: each runs on a WebGPU
|
|
@@ -63,12 +71,54 @@ function useShaderPlayback(options) {
|
|
|
63
71
|
const failed = /* @__PURE__ */ new Map();
|
|
64
72
|
/** Renderers to let go of once the frame being drawn is done with them. */
|
|
65
73
|
const retired = [];
|
|
74
|
+
/**
|
|
75
|
+
* What the library says of each effect's motion, by name. Loading it is deferred until a page
|
|
76
|
+
* draws a shader; until then a preset is played, as it always was.
|
|
77
|
+
*/
|
|
78
|
+
let motions = null;
|
|
66
79
|
let last = 0;
|
|
67
80
|
let stepping = false;
|
|
68
81
|
/** Where the next frame starts drawing, when the last one ran out of time. */
|
|
69
82
|
let turn = 0;
|
|
70
83
|
/** Whether this browser needs each frame copied before the canvas can show it. */
|
|
71
84
|
let copyFrames = false;
|
|
85
|
+
/** Shader frames drawn since the canvas started, which the stats report. */
|
|
86
|
+
let framesDrawn = 0;
|
|
87
|
+
/** Players the last sync left on screen. */
|
|
88
|
+
let shownPlayers = 0;
|
|
89
|
+
/** Whether the page was told once that it plays the most shaders it may. */
|
|
90
|
+
let warnedFull = false;
|
|
91
|
+
/** Records what this canvas is playing, which tests and diagnostics read from the page. */
|
|
92
|
+
function report() {
|
|
93
|
+
playbackStats.set(editor, {
|
|
94
|
+
players: players.size,
|
|
95
|
+
visible: shownPlayers,
|
|
96
|
+
running: shownPlayers > 0,
|
|
97
|
+
frames: framesDrawn
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
let loadingMotions = false;
|
|
101
|
+
/**
|
|
102
|
+
* Reads the library's motion metadata, once, the first time a page draws a preset shader: a
|
|
103
|
+
* document with no shaders never downloads it.
|
|
104
|
+
*/
|
|
105
|
+
function loadMotions() {
|
|
106
|
+
if (motions !== null || loadingMotions) return;
|
|
107
|
+
loadingMotions = true;
|
|
108
|
+
(options.loadMotionMap ?? libraryMotions)().then((known) => {
|
|
109
|
+
motions = known;
|
|
110
|
+
sync();
|
|
111
|
+
}).catch(() => {
|
|
112
|
+
loadingMotions = false;
|
|
113
|
+
motions = /* @__PURE__ */ new Map();
|
|
114
|
+
sync();
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
/** Whether `preset` draws a new picture from one frame to the next. */
|
|
118
|
+
function animates(preset) {
|
|
119
|
+
if (motions === null) return true;
|
|
120
|
+
return presetAnimates(preset, (type) => motions?.get(type));
|
|
121
|
+
}
|
|
72
122
|
function release() {
|
|
73
123
|
for (const player of retired.splice(0)) {
|
|
74
124
|
player.renderer?.dispose();
|
|
@@ -101,10 +151,25 @@ function useShaderPlayback(options) {
|
|
|
101
151
|
height: Math.max(1, Math.round(height * fit))
|
|
102
152
|
};
|
|
103
153
|
}
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
154
|
+
/** Whether any layer painting a shader is in view, so it is worth drawing. */
|
|
155
|
+
function shown(bounds) {
|
|
156
|
+
return onScreen(bounds, getView(), getViewport());
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Makes room for one more player, by letting go of one that is off screen. False when the page
|
|
160
|
+
* already plays the most it may.
|
|
161
|
+
*/
|
|
162
|
+
function makeRoom() {
|
|
163
|
+
if (players.size < MAX_PLAYERS) return true;
|
|
164
|
+
for (const [hash, player] of players) if (!player.visible) {
|
|
165
|
+
stop(hash);
|
|
166
|
+
return true;
|
|
167
|
+
}
|
|
168
|
+
if (!warnedFull) {
|
|
169
|
+
warnedFull = true;
|
|
170
|
+
options.warn?.(`A page plays at most ${MAX_PLAYERS} shaders; the rest keep their still frames.`);
|
|
171
|
+
}
|
|
172
|
+
return false;
|
|
108
173
|
}
|
|
109
174
|
/**
|
|
110
175
|
* Starts playing `hash`'s shader at `size`. A player that `replaces` one already playing, at
|
|
@@ -133,10 +198,7 @@ function useShaderPlayback(options) {
|
|
|
133
198
|
const stopped = () => player.disposed;
|
|
134
199
|
let renderer = null;
|
|
135
200
|
try {
|
|
136
|
-
|
|
137
|
-
if (stopped()) return;
|
|
138
|
-
renderer = shaders.createRendererFromJSON(structuredClone(preset));
|
|
139
|
-
await renderer.initialize(canvas);
|
|
201
|
+
renderer = await (options.createPlayer ?? libraryPlayer)(preset, canvas);
|
|
140
202
|
} catch (error) {
|
|
141
203
|
console.warn("Could not play a shader", error);
|
|
142
204
|
renderer?.dispose();
|
|
@@ -191,32 +253,49 @@ function useShaderPlayback(options) {
|
|
|
191
253
|
failedSizes.delete(hash);
|
|
192
254
|
return false;
|
|
193
255
|
}
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
256
|
+
/** The shaders a page should play: the ones in preview that draw a new picture each frame. */
|
|
257
|
+
function wantedShaders(playing, pageId) {
|
|
258
|
+
if (!playing) return /* @__PURE__ */ new Map();
|
|
259
|
+
const wanted = shadersOnPage(editor.graph, pageId);
|
|
260
|
+
if (wanted.size === 0) return wanted;
|
|
261
|
+
if (motions === null) {
|
|
262
|
+
loadMotions();
|
|
263
|
+
return /* @__PURE__ */ new Map();
|
|
264
|
+
}
|
|
265
|
+
for (const [hash, shader] of wanted) if (!animates(shader.preset)) wanted.delete(hash);
|
|
266
|
+
return wanted;
|
|
267
|
+
}
|
|
268
|
+
/** Starts, resizes, or retires the players that draw `wanted`, and marks the ones on screen. */
|
|
269
|
+
function placePlayers(wanted) {
|
|
197
270
|
for (const [hash, player] of players) {
|
|
198
271
|
const shader = wanted.get(hash);
|
|
199
272
|
if (!shader || JSON.stringify(shader.preset) !== player.preset) stop(hash);
|
|
200
273
|
}
|
|
201
274
|
for (const [hash, shader] of wanted) {
|
|
202
275
|
if (failed.get(hash) !== JSON.stringify(shader.preset)) failed.delete(hash);
|
|
203
|
-
const visible =
|
|
276
|
+
const visible = shown(shader.bounds);
|
|
204
277
|
const size = screenSize(shader.bounds);
|
|
205
278
|
const existing = players.get(hash);
|
|
206
279
|
if (existing && visible && !replacing.has(hash) && resized(existing.canvas, size) && !failedNear(hash, existing.preset, size)) start(hash, shader.preset, size, existing);
|
|
207
|
-
if (!players.has(hash) && visible && !failed.has(hash)) start(hash, shader.preset, size);
|
|
280
|
+
if (!players.has(hash) && visible && !failed.has(hash) && makeRoom()) start(hash, shader.preset, size);
|
|
208
281
|
const player = players.get(hash);
|
|
209
282
|
if (!player) continue;
|
|
210
283
|
player.nodeIds = shader.nodeIds;
|
|
211
284
|
player.visible = visible;
|
|
212
285
|
}
|
|
213
|
-
|
|
286
|
+
}
|
|
287
|
+
function sync() {
|
|
288
|
+
const view = getView();
|
|
289
|
+
placePlayers(wantedShaders((options.getAnimations?.() ?? true) && resolveEditorProfile(view).live !== null && canDrawShaders(), view.currentPageId));
|
|
290
|
+
shownPlayers = [...players.values()].filter((player) => player.visible).length;
|
|
291
|
+
if (shownPlayers > 0) resume();
|
|
214
292
|
else {
|
|
215
293
|
pause();
|
|
216
294
|
last = 0;
|
|
217
295
|
}
|
|
296
|
+
report();
|
|
218
297
|
}
|
|
219
|
-
const { pause, resume } = useRafFn(({ timestamp }) => {
|
|
298
|
+
const { pause, resume } = (options.frames ?? ((draw) => useRafFn(({ timestamp }) => draw(timestamp), { immediate: false })))((timestamp) => {
|
|
220
299
|
if (stepping || copyFrames && last !== 0 && timestamp - last < COPY_FRAME_MS) return;
|
|
221
300
|
last = timestamp;
|
|
222
301
|
stepping = true;
|
|
@@ -224,7 +303,7 @@ function useShaderPlayback(options) {
|
|
|
224
303
|
stepping = false;
|
|
225
304
|
release();
|
|
226
305
|
});
|
|
227
|
-
}
|
|
306
|
+
});
|
|
228
307
|
/**
|
|
229
308
|
* Draws every visible shader and shows its frame. The WebGPU canvas itself is uploaded right
|
|
230
309
|
* after drawing, in the same task, since it keeps its frame only until that task ends. A
|
|
@@ -248,6 +327,8 @@ function useShaderPlayback(options) {
|
|
|
248
327
|
waitForGpu: false
|
|
249
328
|
});
|
|
250
329
|
if (player.disposed) continue;
|
|
330
|
+
framesDrawn += 1;
|
|
331
|
+
report();
|
|
251
332
|
frames.publish(hash, player.canvas);
|
|
252
333
|
if (!copyFrames && uploads(renderer, hash, player)) drew = true;
|
|
253
334
|
else {
|
|
@@ -286,7 +367,8 @@ function useShaderPlayback(options) {
|
|
|
286
367
|
watch(() => [
|
|
287
368
|
resolveEditorProfile(getView()).live !== null,
|
|
288
369
|
getView().currentPageId,
|
|
289
|
-
editor.state.sceneVersion
|
|
370
|
+
editor.state.sceneVersion,
|
|
371
|
+
options.getAnimations?.() ?? true
|
|
290
372
|
], sync, { immediate: true });
|
|
291
373
|
watchThrottled(() => [
|
|
292
374
|
getView().panX,
|
|
@@ -295,7 +377,21 @@ function useShaderPlayback(options) {
|
|
|
295
377
|
getViewport().width,
|
|
296
378
|
getViewport().height
|
|
297
379
|
], sync, { throttle: VIEW_CHECK_MS });
|
|
380
|
+
/**
|
|
381
|
+
* A hidden tab draws nothing, so its players are let go of rather than left running; coming
|
|
382
|
+
* back starts them again. A browser already stops animation frames for a hidden tab; stopping
|
|
383
|
+
* the players too gives the GPU and their memory back.
|
|
384
|
+
*/
|
|
385
|
+
function onVisibilityChange() {
|
|
386
|
+
if (document.visibilityState === "hidden") {
|
|
387
|
+
for (const hash of Array.from(players.keys())) stop(hash);
|
|
388
|
+
shownPlayers = 0;
|
|
389
|
+
report();
|
|
390
|
+
} else sync();
|
|
391
|
+
}
|
|
392
|
+
if (typeof document !== "undefined") document.addEventListener("visibilitychange", onVisibilityChange);
|
|
298
393
|
onScopeDispose(() => {
|
|
394
|
+
if (typeof document !== "undefined") document.removeEventListener("visibilitychange", onVisibilityChange);
|
|
299
395
|
pause();
|
|
300
396
|
for (const hash of Array.from(players.keys())) stop(hash);
|
|
301
397
|
release();
|