Skip to content

Visualize Your Ideas With Code

feat: webgl shaders (#920)

Jacob849216ed34c4
diff --git a/package-lock.json b/package-lock.json
index 836024a6..62380648 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -22769,7 +22769,8 @@
},
"node_modules/source-map": {
"version": "0.6.1",
- "license": "BSD-3-Clause",
+ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
+ "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",
"engines": {
"node": ">=0.10.0"
}
@@ -25944,7 +25945,8 @@
"dependencies": {
"fast-glob": "^3.3.1",
"follow-redirects": "^1.15.2",
- "mime-types": "^2.1.35"
+ "mime-types": "^2.1.35",
+ "source-map": "^0.6.1"
},
"devDependencies": {
"@motion-canvas/internal": "0.0.0",
@@ -29685,7 +29687,8 @@
"@types/node": "^18.14.0",
"fast-glob": "^3.3.1",
"follow-redirects": "^1.15.2",
- "mime-types": "^2.1.35"
+ "mime-types": "^2.1.35",
+ "source-map": "^0.6.1"
}
},
"@nodelib/fs.scandir": {
@@ -41881,7 +41884,9 @@
}
},
"source-map": {
- "version": "0.6.1"
+ "version": "0.6.1",
+ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
+ "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="
},
"source-map-js": {
"version": "1.0.2",
diff --git a/packages/2d/src/lib/components/Node.ts b/packages/2d/src/lib/components/Node.ts
index d37841c5..5b00588d 100644
--- a/packages/2d/src/lib/components/Node.ts
+++ b/packages/2d/src/lib/components/Node.ts
@@ -3,6 +3,7 @@ import {
ColorSignal,
DependencyContext,
PossibleColor,
+ PossibleSpacing,
PossibleVector2,
Promisable,
ReferenceReceiver,
@@ -10,8 +11,12 @@ import {
SignalValue,
SimpleSignal,
SimpleVector2Signal,
+ SpacingSignal,
ThreadGenerator,
TimingFunction,
+ UNIFORM_DESTINATION_MATRIX,
+ UNIFORM_SOURCE_MATRIX,
+ UNIFORM_TIME,
Vector2,
Vector2Signal,
all,
@@ -42,7 +47,13 @@ import {
wrapper,
} from '../decorators';
import {FiltersSignal, filtersSignal} from '../decorators/filtersSignal';
+import {spacingSignal} from '../decorators/spacingSignal';
import {Filter} from '../partials';
+import {
+ PossibleShaderConfig,
+ ShaderConfig,
+ parseShader,
+} from '../partials/ShaderConfig';
import {useScene2D} from '../scenes/useScene2D';
import {drawLine} from '../utils';
import type {View2D} from './View2D';
@@ -73,14 +84,41 @@ export interface NodeProps {
opacity?: SignalValue<number>;
filters?: SignalValue<Filter[]>;
+
shadowColor?: SignalValue<PossibleColor>;
shadowBlur?: SignalValue<number>;
shadowOffsetX?: SignalValue<number>;
shadowOffsetY?: SignalValue<number>;
shadowOffset?: SignalValue<PossibleVector2>;
+
cache?: SignalValue<boolean>;
+ /**
+ * {@inheritDoc Node.cachePadding}
+ */
+ cachePaddingTop?: SignalValue<number>;
+ /**
+ * {@inheritDoc Node.cachePadding}
+ */
+ cachePaddingBottom?: SignalValue<number>;
+ /**
+ * {@inheritDoc Node.cachePadding}
+ */
+ cachePaddingLeft?: SignalValue<number>;
+ /**
+ * {@inheritDoc Node.cachePadding}
+ */
+ cachePaddingRight?: SignalValue<number>;
+ /**
+ * {@inheritDoc Node.cachePadding}
+ */
+ cachePadding?: SignalValue<PossibleSpacing>;
+
composite?: SignalValue<boolean>;
compositeOperation?: SignalValue<GlobalCompositeOperation>;
+ /**
+ * @experimental
+ */
+ shaders?: PossibleShaderConfig;
}
@nodeName('Node')
@@ -314,6 +352,18 @@ export class Node implements Promisable<Node> {
@signal()
public declare readonly cache: SimpleSignal<boolean, this>;
+ /**
+ * Controls the padding of the cached canvas used by this node.
+ *
+ * @remarks
+ * By default, the size of the cache is determined based on the bounding box
+ * of the node and its children. That includes effects such as stroke or
+ * shadow. This property can be used to expand the cache area further.
+ * Usually used to account for custom effects created by {@link shaders}.
+ */
+ @spacingSignal('cachePadding')
+ public declare readonly cachePadding: SpacingSignal<this>;
+
@initial(false)
@signal()
public declare readonly composite: SimpleSignal<boolean, this>;
@@ -375,6 +425,18 @@ export class Node implements Promisable<Node> {
@vector2Signal('shadowOffset')
public declare readonly shadowOffset: Vector2Signal<this>;
+ /**
+ * @experimental
+ */
+ @initial([])
+ @parser(parseShader)
+ @signal()
+ public declare readonly shaders: Signal<
+ PossibleShaderConfig,
+ ShaderConfig[],
+ this
+ >;
+
@computed()
protected hasFilters(): boolean {
return !!this.filters().find(filter => filter.isActive());
@@ -563,7 +625,7 @@ export class Node implements Promisable<Node> {
* @remarks
* Certain effects such as blur and shadows ignore the current transformation.
* This matrix can be used to transform their parameters so that the effect
- * appears relative to the closes composite root.
+ * appears relative to the closest composite root.
*/
@computed()
public compositeToWorld(): DOMMatrix {
@@ -1261,7 +1323,8 @@ export class Node implements Promisable<Node> {
this.opacity() < 1 ||
this.compositeOperation() !== 'source-over' ||
this.hasFilters() ||
- this.hasShadow()
+ this.hasShadow() ||
+ this.shaders().length > 0
);
}
@@ -1318,8 +1381,9 @@ export class Node implements Promisable<Node> {
public cacheBBox(): BBox {
const cache = this.getCacheBBox();
const children = this.children();
+ const padding = this.cachePadding();
if (children.length === 0) {
- return cache;
+ return cache.addSpacing(padding);
}
const points: Vector2[] = cache.corners;
@@ -1331,7 +1395,8 @@ export class Node implements Promisable<Node> {
);
}
- return BBox.fromPoints(...points);
+ const bbox = BBox.fromPoints(...points);
+ return bbox.addSpacing(padding);
}
/**
@@ -1384,8 +1449,17 @@ export class Node implements Promisable<Node> {
);
const cacheBBox = BBox.fromPoints(
...this.cacheBBox().transformCorners(this.localToWorld()),
+ ).pixelPerfect.expand(2);
+
+ return canvasBBox.intersection(cacheBBox);
+ }
+
+ @computed()
+ protected parentWorldSpaceCacheBBox(): BBox {
+ return (
+ this.findAncestor(node => node.requiresCache())?.worldSpaceCacheBBox() ??
+ new BBox(Vector2.zero, useScene2D().getSize())
);
- return canvasBBox.intersection(cacheBBox).pixelPerfect;
}
/**
@@ -1417,6 +1491,122 @@ export class Node implements Promisable<Node> {
context.shadowOffsetX = offset.x;
context.shadowOffsetY = offset.y;
}
+
+ const matrix = this.worldToLocal();
+ context.transform(
+ matrix.a,
+ matrix.b,
+ matrix.c,
+ matrix.d,
+ matrix.e,
+ matrix.f,
+ );
+ }
+
+ protected renderFromSource(
+ context: CanvasRenderingContext2D,
+ source: CanvasImageSource,
+ x: number,
+ y: number,
+ ) {
+ this.setupDrawFromCache(context);
+
+ const compositeOverride = this.compositeOverride();
+ context.drawImage(source, x, y);
+ if (compositeOverride > 0) {
+ context.save();
+ context.globalAlpha *= compositeOverride;
+ context.globalCompositeOperation = 'source-over';
+ context.drawImage(source, x, y);
+ context.restore();
+ }
+ }
+
+ private shaderCanvas(destination: TexImageSource, source: TexImageSource) {
+ const shaders = this.shaders();
+ if (shaders.length === 0) {
+ return null;
+ }
+
+ const scene = useScene2D();
+ const size = scene.getRealSize();
+ const parentCacheRect = this.parentWorldSpaceCacheBBox();
+ const cameraToWorld = new DOMMatrix()
+ .scaleSelf(
+ size.width / parentCacheRect.width,
+ size.height / -parentCacheRect.height,
+ )
+ .translateSelf(
+ parentCacheRect.x / -size.width,
+ parentCacheRect.y / size.height - 1,
+ );
+
+ const cacheRect = this.worldSpaceCacheBBox();
+ const cameraToCache = new DOMMatrix()
+ .scaleSelf(size.width / cacheRect.width, size.height / -cacheRect.height)
+ .translateSelf(cacheRect.x / -size.width, cacheRect.y / size.height - 1)
+ .invertSelf();
+
+ const gl = scene.shaders.getGL();
+ scene.shaders.copyTextures(destination, source);
+ scene.shaders.clear();
+
+ for (const shader of shaders) {
+ const program = scene.shaders.getProgram(shader.fragment);
+ if (!program) {
+ continue;
+ }
+
+ if (shader.uniforms) {
+ for (const [name, uniform] of Object.entries(shader.uniforms)) {
+ const location = gl.getUniformLocation(program, name);
+ if (location === null) {
+ continue;
+ }
+
+ const value = unwrap(uniform);
+ if (typeof value === 'number') {
+ gl.uniform1f(location, value);
+ } else if (value.length === 1) {
+ gl.uniform1f(location, value[0]);
+ } else if (value.length === 2) {
+ gl.uniform2f(location, value[0], value[1]);
+ } else if (value.length === 3) {
+ gl.uniform3f(location, value[0], value[1], value[2]);
+ } else if (value.length === 4) {
+ gl.uniform4f(location, value[0], value[1], value[2], value[3]);
+ }
+ }
+ }
+
+ gl.uniform1f(
+ gl.getUniformLocation(program, UNIFORM_TIME),
+ this.view2D.globalTime(),
+ );
+
+ gl.uniform1i(
+ gl.getUniformLocation(program, UNIFORM_TIME),
+ scene.playback.frame,
+ );
+
+ gl.uniformMatrix4fv(
+ gl.getUniformLocation(program, UNIFORM_SOURCE_MATRIX),
+ false,
+ cameraToCache.toFloat32Array(),
+ );
+
+ gl.uniformMatrix4fv(
+ gl.getUniformLocation(program, UNIFORM_DESTINATION_MATRIX),
+ false,
+ cameraToWorld.toFloat32Array(),
+ );
+
+ shader.setup?.(gl, program);
+ scene.shaders.render();
+ shader.teardown?.(gl, program);
+ }
+
+ return gl.canvas;
}
/**
@@ -1435,33 +1625,17 @@ export class Node implements Promisable<Node> {
if (this.requiresCache()) {
const cacheRect = this.worldSpaceCacheBBox();
if (cacheRect.width !== 0 && cacheRect.height !== 0) {
- this.setupDrawFromCache(context);
- const cacheContext = this.cachedCanvas();
- const compositeOverride = this.compositeOverride();
- const matrix = this.worldToLocal();
- context.transform(
- matrix.a,
- matrix.b,
- matrix.c,
- matrix.d,
- matrix.e,
- matrix.f,
- );
- context.drawImage(
- cacheContext.canvas,
- cacheRect.position.x,
- cacheRect.position.y,
- );
- if (compositeOverride > 0) {
- context.save();
- context.globalAlpha *= compositeOverride;
- context.globalCompositeOperation = 'source-over';
- context.drawImage(
- cacheContext.canvas,
+ const cache = this.cachedCanvas().canvas;
+ const source = this.shaderCanvas(context.canvas, cache);
+ if (source) {
+ this.renderFromSource(context, source, 0, 0);
+ } else {
+ this.renderFromSource(
+ context,
+ cache,
cacheRect.position.x,
cacheRect.position.y,
);
- context.restore();
}
}
} else {
diff --git a/packages/2d/src/lib/components/View2D.ts b/packages/2d/src/lib/components/View2D.ts
index 7372a3fb..46a9de1e 100644
--- a/packages/2d/src/lib/components/View2D.ts
+++ b/packages/2d/src/lib/components/View2D.ts
@@ -33,6 +33,10 @@ export class View2D extends Rect {
@signal()
public declare readonly playbackState: SimpleSignal<PlaybackState, this>;
+ @initial(0)
+ @signal()
+ public declare readonly globalTime: SimpleSignal<number, this>;
+
@signal()
public declare readonly assetHash: SimpleSignal<string, this>;
diff --git a/packages/2d/src/lib/partials/ShaderConfig.ts b/packages/2d/src/lib/partials/ShaderConfig.ts
new file mode 100644
index 00000000..191876b9
--- /dev/null
+++ b/packages/2d/src/lib/partials/ShaderConfig.ts
@@ -0,0 +1,121 @@
+import {
+ experimentalLog,
+ SignalValue,
+ useLogger,
+ useScene,
+} from '@motion-canvas/core';
+import {Node} from '../components';
+
+/**
+ * Describes a shader program used to apply effects to nodes.
+ *
+ * @experimental
+ */
+export interface ShaderConfig {
+ /**
+ * The source code of the fragment shader.
+ *
+ * @example
+ * ```glsl
+ * #version 300 es
+ * precision highp float;
+ *
+ * #include "@motion-canvas/core/shaders/common.glsl"
+ *
+ * void main() {
+ * out_color = texture(core_source_tx, source_uv);
+ * }
+ * ```
+ */
+ fragment: string;
+
+ /**
+ * Custom uniforms to be passed to the shader.
+ *
+ * @remarks
+ * The keys of this object will be used as the uniform names.
+ * The values can be either a number or an array of numbers.
+ * The following table shows how the values will be mapped to GLSL types.
+ *
+ * | TypeScript | GLSL |
+ * | ---------------------------------- | ------- |
+ * | `number` | `float` |
+ * | `[number, number]` | `vec2` |
+ * | `[number, number, number]` | `vec3` |
+ * | `[number, number, number, number]` | `vec4` |
+ *
+ * @example
+ * ```ts
+ * const shader = {
+ * // ...
+ * uniforms: {
+ * my_value: () => 1,
+ * my_vector: [1, 2, 3],
+ * },
+ * };
+ * ```
+ *
+ * ```glsl
+ * uniform float my_value;
+ * uniform vec3 my_vector;
+ * ```
+ */
+ uniforms?: Record<string, SignalValue<number | number[]>>;
+
+ /**
+ * A custom hook run before the shader is used.
+ *
+ * @remarks
+ * Gives you low-level access to the WebGL context and the shader program.
+ *
+ * @param gl - WebGL context.
+ * @param program - The shader program.
+ */
+ setup?: (gl: WebGL2RenderingContext, program: WebGLProgram) => void;
+
+ /**
+ * A custom hook run after the shader is used.
+ *
+ * @remarks
+ * Gives you low-level access to the WebGL context and the shader program.
+ * Can be used to clean up resources created in the {@link setup} hook.
+ *
+ * @param gl - WebGL context.
+ * @param program - The shader program.
+ */
+ teardown?: (gl: WebGL2RenderingContext, program: WebGLProgram) => void;
+}
+
+export type PossibleShaderConfig =
+ | (ShaderConfig | string)[]
+ | ShaderConfig
+ | string
+ | null;
+
+export function parseShader(
+ this: Node,
+ value: PossibleShaderConfig,
+): ShaderConfig[] {
+ let result: ShaderConfig[];
+ if (!value) {
+ result = [];
+ } else if (typeof value === 'string') {
+ result = [{fragment: value}];
+ } else if (Array.isArray(value)) {
+ result = value.map(item =>
+ typeof item === 'string' ? {fragment: item} : item,
+ );
+ } else {
+ result = [value];
+ }
+
+ if (!useScene().experimentalFeatures && result.length > 0) {
+ result = [];
+ useLogger().log({
+ ...experimentalLog(`Node uses experimental shaders.`),
+ inspect: this.key,
+ });
+ }
+
+ return result;
+}
diff --git a/packages/2d/src/lib/scenes/Scene2D.ts b/packages/2d/src/lib/scenes/Scene2D.ts
index d8182667..b13e18aa 100644
--- a/packages/2d/src/lib/scenes/Scene2D.ts
+++ b/packages/2d/src/lib/scenes/Scene2D.ts
@@ -36,7 +36,9 @@ export class Scene2D extends GeneratorScene<View2D> implements Inspectable {
}
public override next(): Promise<void> {
- this.getView()?.playbackState(this.playback.state);
+ this.getView()
+ ?.playbackState(this.playback.state)
+ .globalTime(this.playback.time);
return super.next();
}
@@ -45,7 +47,9 @@ export class Scene2D extends GeneratorScene<View2D> implements Inspectable {
this.renderLifecycle.dispatch([SceneRenderEvent.BeforeRender, context]);
context.save();
this.renderLifecycle.dispatch([SceneRenderEvent.BeginRender, context]);
- this.getView().playbackState(this.playback.state);
+ this.getView()
+ .playbackState(this.playback.state)
+ .globalTime(this.playback.time);
this.getView().render(context);
this.renderLifecycle.dispatch([SceneRenderEvent.FinishRender, context]);
context.restore();
diff --git a/packages/core/package.json b/packages/core/package.json
index 6baf82e2..7d385a40 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -21,7 +21,8 @@
"files": [
"lib",
"tsconfig.project.json",
- "project.d.ts"
+ "project.d.ts",
+ "shaders"
],
"dependencies": {
"@types/chroma-js": "^2.1.4",
diff --git a/packages/core/shaders/common.glsl b/packages/core/shaders/common.glsl
new file mode 100644
index 00000000..88ea7b85
--- /dev/null
+++ b/packages/core/shaders/common.glsl
@@ -0,0 +1,15 @@
+in vec2 screenUV;
+in vec2 sourceUV;
+in vec2 destinationUV;
+
+out vec4 outColor;
+
+uniform float time;
+uniform float deltaTime;
+uniform float framerate;
+uniform int frame;
+uniform vec2 resolution;
+uniform sampler2D sourceTexture;
+uniform sampler2D destinationTexture;
+uniform mat4 sourceMatrix;
+uniform mat4 destinationMatrix;
\ No newline at end of file
diff --git a/packages/core/shaders/fragment.glsl b/packages/core/shaders/fragment.glsl
new file mode 100644
index 00000000..99c1962e
--- /dev/null
+++ b/packages/core/shaders/fragment.glsl
@@ -0,0 +1,8 @@
+#version 300 es
+precision highp float;
+
+#include "./common.glsl"
+
+void main() {
+ outColor = textureLod(sourceTexture, sourceUV, 0.0);
+}
\ No newline at end of file
diff --git a/packages/core/src/app/PlaybackStatus.ts b/packages/core/src/app/PlaybackStatus.ts
index 299c5551..1605eca8 100644
--- a/packages/core/src/app/PlaybackStatus.ts
+++ b/packages/core/src/app/PlaybackStatus.ts
@@ -43,4 +43,11 @@ export class PlaybackStatus {
public get state(): PlaybackState {
return this.playback.state;
}
+
+ /**
+ * The time passed since the last frame in seconds.
+ */
+ public get deltaTime(): number {
+ return this.framesToSeconds(1) * this.speed;
+ }
}
diff --git a/packages/core/src/app/Player.ts b/packages/core/src/app/Player.ts
index caff71a7..94dbd8bc 100644
--- a/packages/core/src/app/Player.ts
+++ b/packages/core/src/app/Player.ts
@@ -13,6 +13,7 @@ import {Logger} from './Logger';
import {PlaybackManager, PlaybackState} from './PlaybackManager';
import {PlaybackStatus} from './PlaybackStatus';
import {Project} from './Project';
+import {SharedWebGLContext} from './SharedWebGLContext';
export interface PlayerState extends Record<string, unknown> {
paused: boolean;
@@ -89,6 +90,7 @@ export class Player {
public readonly status: PlaybackStatus;
public readonly audio: AudioManager;
public readonly logger: Logger;
+ private readonly sharedWebGLContext: SharedWebGLContext;
private readonly lock = new Semaphore();
private startTime = 0;
@@ -135,6 +137,7 @@ export class Player {
paused: true,
});
+ this.sharedWebGLContext = new SharedWebGLContext(this.project.logger);
this.requestedSeek = initialFrame;
this.logger = this.project.logger;
this.playback = new PlaybackManager();
@@ -160,6 +163,8 @@ export class Player {
size: this.size,
resolutionScale: this.resolutionScale,
timeEventsClass: EditableTimeEvents,
+ sharedWebGLContext: this.sharedWebGLContext,
+ experimentalFeatures: project.experimentalFeatures,
});
description.onReplaced?.subscribe(description => {
scene.reload(description);
@@ -341,6 +346,7 @@ export class Player {
*/
public deactivate() {
this.active = false;
+ this.sharedWebGLContext.dispose();
if (this.requestId !== null) {
cancelAnimationFrame(this.requestId);
this.requestId = null;
diff --git a/packages/core/src/app/Presenter.ts b/packages/core/src/app/Presenter.ts
index 6dc2dbb5..0a601f87 100644
--- a/packages/core/src/app/Presenter.ts
+++ b/packages/core/src/app/Presenter.ts
@@ -7,6 +7,7 @@ import type {Logger} from './Logger';
import {PlaybackManager, PlaybackState} from './PlaybackManager';
import {PlaybackStatus} from './PlaybackStatus';
import type {Project} from './Project';
+import {SharedWebGLContext} from './SharedWebGLContext';
import {Stage, StageSettings} from './Stage';
export interface PresenterSettings extends StageSettings {
@@ -64,6 +65,7 @@ export class Presenter {
public readonly playback: PlaybackManager;
private readonly status: PlaybackStatus;
private readonly logger: Logger;
+ private readonly sharedWebGLContext: SharedWebGLContext;
private abortController: AbortController | null = null;
private renderTime = 0;
private requestId: number | null = null;
@@ -78,6 +80,7 @@ export class Presenter {
this.logger = project.logger;
this.playback = new PlaybackManager();
this.status = new PlaybackStatus(this.playback);
+ this.sharedWebGLContext = new SharedWebGLContext(this.logger);
const scenes: Scene[] = [];
for (const description of project.scenes) {
const scene = new description.klass({
@@ -88,6 +91,8 @@ export class Presenter {
size: new Vector2(1920, 1080),
resolutionScale: 1,
timeEventsClass: ReadOnlyTimeEvents,
+ sharedWebGLContext: this.sharedWebGLContext,
+ experimentalFeatures: project.experimentalFeatures,
});
scenes.push(scene);
}
@@ -110,6 +115,7 @@ export class Presenter {
this.project.logger.error(e);
}
+ this.sharedWebGLContext.dispose();
this.state.current = PresenterState.Initial;
this.lock.release();
}
diff --git a/packages/core/src/app/Renderer.ts b/packages/core/src/app/Renderer.ts
index 9a14e649..79cf25f4 100644
--- a/packages/core/src/app/Renderer.ts
+++ b/packages/core/src/app/Renderer.ts
@@ -8,6 +8,7 @@ import type {Exporter} from './Exporter';
import {PlaybackManager, PlaybackState} from './PlaybackManager';
import {PlaybackStatus} from './PlaybackStatus';
import type {Project} from './Project';
+import {SharedWebGLContext} from './SharedWebGLContext';
import {Stage, StageSettings} from './Stage';
import {TimeEstimator} from './TimeEstimator';
@@ -65,12 +66,14 @@ export class Renderer {
private readonly lock = new Semaphore();
private readonly playback: PlaybackManager;
private readonly status: PlaybackStatus;
+ private readonly sharedWebGLContext: SharedWebGLContext;
private exporter: Exporter | null = null;
private abortController: AbortController | null = null;
public constructor(private project: Project) {
this.playback = new PlaybackManager();
this.status = new PlaybackStatus(this.playback);
+ this.sharedWebGLContext = new SharedWebGLContext(this.project.logger);
const scenes: Scene[] = [];
for (const description of project.scenes) {
const scene = new description.klass({
@@ -81,6 +84,8 @@ export class Renderer {
size: new Vector2(1920, 1080),
resolutionScale: 1,
timeEventsClass: ReadOnlyTimeEvents,
+ sharedWebGLContext: this.sharedWebGLContext,
+ experimentalFeatures: project.experimentalFeatures,
});
scenes.push(scene);
}
@@ -117,6 +122,7 @@ export class Renderer {
this.estimator.update(1);
this.state.current = RendererState.Initial;
this.finished.dispatch(result);
+ this.sharedWebGLContext.dispose();
this.lock.release();
}
diff --git a/packages/core/src/app/SharedWebGLContext.ts b/packages/core/src/app/SharedWebGLContext.ts
new file mode 100644
index 00000000..b290fef2
--- /dev/null
+++ b/packages/core/src/app/SharedWebGLContext.ts
@@ -0,0 +1,222 @@
+import {Logger} from './Logger';
+import includeWithoutPreprocessor from './__logs__/include-without-preprocessor.md';
+
+const SOURCE_URL_REGEX = /^\/\/# sourceURL=(.*)$/gm;
+const INFO_LOG_REGEX = /ERROR: \d+:(\d+): (.*)/g;
+const INFO_TOKEN_REGEX = /^'([^']+)'/;
+
+/**
+ * @internal
+ */
+export interface WebGLContextOwner {
+ setup(gl: WebGL2RenderingContext): void;
+ teardown(gl: WebGL2RenderingContext): void;
+}
+
+interface WebGLProgramData {
+ program: WebGLProgram;
+ fragment: WebGLShader;
+ vertex: WebGLShader;
+}
+
+export class SharedWebGLContext {
+ private gl: WebGL2RenderingContext | null = null;
+ private currentOwner: WebGLContextOwner | null = null;
+ private readonly programLookup = new Map<string, WebGLProgramData>();
+
+ public constructor(private readonly logger: Logger) {}
+
+ public borrow(owner: WebGLContextOwner): WebGL2RenderingContext {
+ if (this.currentOwner === owner) {
+ return this.gl!;
+ }
+
+ this.currentOwner?.teardown(this.gl!);
+ this.currentOwner = owner;
+ this.currentOwner.setup(this.getGL());
+ return this.gl!;
+ }
+
+ /**
+ * Dispose the WebGL context to free up resources.
+ */
+ public dispose() {
+ if (!this.gl) {
+ return;
+ }
+
+ this.currentOwner?.teardown(this.gl);
+ this.currentOwner = null;
+
+ this.gl.useProgram(null);
+ for (const {program, fragment, vertex} of this.programLookup.values()) {
+ this.gl.deleteProgram(program);
+ this.gl.deleteShader(fragment);
+ this.gl.deleteShader(vertex);
+ }
+
+ this.programLookup.clear();
+ this.gl.getExtension('WEBGL_lose_context')?.loseContext();
+ (this.gl.canvas as HTMLCanvasElement).remove();
+ this.gl = null;
+ }
+
+ public getProgram(fragment: string, vertex: string): WebGLProgram | null {
+ const key = `${fragment}#${vertex}`;
+ if (this.programLookup.has(key)) {
+ return this.programLookup.get(key)!.program;
+ }
+
+ const gl = this.getGL();
+ const fragmentShader = this.getShader(gl.FRAGMENT_SHADER, fragment);
+ const vertexShader = this.getShader(gl.VERTEX_SHADER, vertex);
+ if (!fragmentShader || !vertexShader) {
+ return null;
+ }
+
+ const program = gl.createProgram()!;
+ gl.attachShader(program, fragmentShader);
+ gl.attachShader(program, vertexShader);
+ gl.linkProgram(program);
+
+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
+ this.logger.error({
+ message: 'Failed to initialize the shader program.',
+ remarks: gl.getProgramInfoLog(program) ?? undefined,
+ stack: new Error().stack,
+ });
+ gl.deleteProgram(program);
+ return null;
+ }
+
+ this.programLookup.set(key, {
+ program,
+ fragment: fragmentShader,
+ vertex: vertexShader,
+ });
+
+ return program;
+ }
+
+ private getShader(type: GLenum, source: string): WebGLShader | null {
+ const gl = this.getGL();
+ const shader = gl.createShader(type)!;
+ gl.shaderSource(shader, source);
+ gl.compileShader(shader);
+ if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
+ const log = gl.getShaderInfoLog(shader);
+ logGlslError(this.logger, log, source);
+ gl.deleteShader(shader);
+ return null;
+ }
+
+ return shader;
+ }
+
+ private getGL(): WebGL2RenderingContext {
+ if (this.gl) {
+ return this.gl;
+ }
+
+ this.gl = document.createElement('canvas').getContext('webgl2', {
+ depth: false,
+ premultipliedAlpha: false,
+ stencil: false,
+ powerPreference: 'high-performance',
+ });
+ if (!this.gl) {
+ throw new Error('Failed to initialize WebGL.');
+ }
+
+ /* NOTE: Temporary debugging code
+ const canvas = this.gl.canvas as HTMLCanvasElement;
+ document.body.append(canvas);
+ canvas.style.position = 'absolute';
+ canvas.style.top = '16px';
+ canvas.style.right = '16px';
+ canvas.style.width = '300px';
+ canvas.style.borderRadius = '4px';
+ canvas.style.border = '1px solid #ccc';
+ canvas.style.backgroundColor = '#141414';
+ canvas.style.zIndex = '1000';
+ */
+
+ return this.gl;
+ }
+}
+
+function logGlslError(logger: Logger, log: string | null, source: string) {
+ let sourceUrl: string | null = null;
+
+ SOURCE_URL_REGEX.lastIndex = 0;
+ const sourceMatch = SOURCE_URL_REGEX.exec(source);
+ if (sourceMatch) {
+ const url = new URL(sourceMatch[1], window.location.origin);
+ url.searchParams.set('t', Date.now().toString());
+ sourceUrl = url.toString();
+ }
+
+ if (!log) {
+ logger.error({
+ message: `Unknown shader compilation error.`,
+ stack: fakeStackTrace(sourceUrl, 1, 0),
+ });
+ return null;
+ }
+
+ let logged = false;
+ let result;
+ while ((result = INFO_LOG_REGEX.exec(log))) {
+ const [, line, message] = result;
+ let column = 0;
+ const match = message.match(INFO_TOKEN_REGEX);
+ if (match) {
+ const tokenLine = source.split('\n')[parseInt(line)! - 1];
+ const index = tokenLine.indexOf(match[1]!);
+ if (index !== -1) {
+ column = index;
+ }
+
+ if (match[1] === 'include') {
+ const line = source
+ .split('\n')
+ .find(line => line.startsWith('#include'));
+ if (line) {
+ logged = true;
+ logger.error({
+ message: `Shader compilation error: ${message}`,
+ remarks: includeWithoutPreprocessor,
+ });
+ break;
+ }
+ }
+ }
+
+ logged = true;
+ logger.error({
+ message: `Shader compilation error: ${message}`,
+ stack: fakeStackTrace(sourceUrl, line, column),
+ });
+ }
+
+ if (!logged) {
+ logger.error({
+ message: `Shader compilation error: ${log}`,
+ stack: fakeStackTrace(sourceUrl, 1, 0),
+ });
+ }
+}
+
+function fakeStackTrace(
+ file: string | null,
+ line: string | number,
+ column: string | number,
+): string | undefined {
+ if (!file) {
+ return undefined;
+ }
+
+ return navigator.userAgent.toLowerCase().includes('chrome')
+ ? ` at (${file}:${line}:${column})`
+ : `@${file}:${line}:${column}`;
+}
diff --git a/packages/core/src/app/__logs__/include-without-preprocessor.md b/packages/core/src/app/__logs__/include-without-preprocessor.md
new file mode 100644
index 00000000..6f651201
--- /dev/null
+++ b/packages/core/src/app/__logs__/include-without-preprocessor.md
@@ -0,0 +1,23 @@
+The `#include` directive requires the use of a preprocessor.
+
+Make sure to import the shader from a file:
+
+```ts
+import shader from './shader.glsl';
+```
+
+Do **NOT** use the raw loader:
+
+```ts
+import shader from './shader.glsl?raw';
+```
+
+Do **NOT** use `#include` in an inline string:
+
+```ts
+const shader = `\
+#include "example.glsl"
+`;
+```
+
+[Learn more](https://motioncanvas.io/docs/shaders) about working with shaders.
diff --git a/packages/core/src/app/index.ts b/packages/core/src/app/index.ts
index 0c07775b..aa062c1d 100644
--- a/packages/core/src/app/index.ts
+++ b/packages/core/src/app/index.ts
@@ -15,5 +15,6 @@ export * from './Project';
export * from './ProjectMetadata';
export * from './Renderer';
export * from './SettingsMetadata';
+export * from './SharedWebGLContext';
export * from './Stage';
export * from './bootstrap';
diff --git a/packages/core/src/scenes/GeneratorScene.ts b/packages/core/src/scenes/GeneratorScene.ts
index 38d28124..2af9ddb2 100644
--- a/packages/core/src/scenes/GeneratorScene.ts
+++ b/packages/core/src/scenes/GeneratorScene.ts
@@ -3,10 +3,10 @@ import {decorate, threadable} from '../decorators';
import {EventDispatcher, ValueDispatcher} from '../events';
import {DependencyContext, SignalValue} from '../signals';
import {
- isPromisable,
- isPromise,
Thread,
ThreadGenerator,
+ isPromisable,
+ isPromise,
threads,
} from '../threading';
import {Vector2} from '../types';
@@ -22,10 +22,11 @@ import {
} from './Scene';
import {SceneMetadata} from './SceneMetadata';
import {SceneState} from './SceneState';
+import {Shaders} from './Shaders';
import {Slides} from './Slides';
import {Threadable} from './Threadable';
-import {TimeEvents} from './timeEvents';
import {Variables} from './Variables';
+import {TimeEvents} from './timeEvents';
export interface ThreadGeneratorFactory<T> {
(view: T): ThreadGenerator;
@@ -44,6 +45,7 @@ export abstract class GeneratorScene<T>
public readonly logger: Logger;
public readonly meta: SceneMetadata;
public readonly timeEvents: TimeEvents;
+ public readonly shaders: Shaders;
public readonly slides: Slides;
public readonly variables: Variables;
public random: Random;
@@ -135,6 +137,7 @@ export abstract class GeneratorScene<T>
decorate(this.runnerFactory, threadable(this.name));
this.timeEvents = new description.timeEventsClass(this);
this.variables = new Variables(this);
+ this.shaders = new Shaders(this, description.sharedWebGLContext);
this.slides = new Slides(this);
this.random = new Random(this.meta.seed.get());
diff --git a/packages/core/src/scenes/Scene.ts b/packages/core/src/scenes/Scene.ts
index 4e3970dc..3135306e 100644
--- a/packages/core/src/scenes/Scene.ts
+++ b/packages/core/src/scenes/Scene.ts
@@ -1,4 +1,4 @@
-import type {Logger, PlaybackStatus} from '../app';
+import type {Logger, PlaybackStatus, SharedWebGLContext} from '../app';
import type {
SubscribableEvent,
SubscribableValueEvent,
@@ -10,6 +10,7 @@ import type {Vector2} from '../types';
import type {LifecycleEvents} from './LifecycleEvents';
import type {Random} from './Random';
import type {SceneMetadata} from './SceneMetadata';
+import type {Shaders} from './Shaders';
import type {Slides} from './Slides';
import type {Variables} from './Variables';
import type {TimeEvents} from './timeEvents';
@@ -68,6 +69,7 @@ export interface FullSceneDescription<T = unknown> extends SceneDescription<T> {
logger: Logger;
onReplaced: ValueDispatcher<FullSceneDescription<T>>;
timeEventsClass: new (scene: Scene) => TimeEvents;
+ sharedWebGLContext: SharedWebGLContext;
experimentalFeatures?: boolean;
}
@@ -143,6 +145,10 @@ export interface Scene<T = unknown> {
*/
readonly playback: PlaybackStatus;
readonly timeEvents: TimeEvents;
+ /**
+ * @experimental
+ */
+ readonly shaders: Shaders;
readonly slides: Slides;
readonly logger: Logger;
readonly variables: Variables;
diff --git a/packages/core/src/scenes/Shaders.ts b/packages/core/src/scenes/Shaders.ts
new file mode 100644
index 00000000..b3d63347
--- /dev/null
+++ b/packages/core/src/scenes/Shaders.ts
@@ -0,0 +1,191 @@
+import {SharedWebGLContext, WebGLContextOwner} from '../app/SharedWebGLContext';
+import {Scene} from './Scene';
+
+/**
+ * @internal
+ */
+export const UNIFORM_RESOLUTION = 'resolution';
+/**
+ * @internal
+ */
+export const UNIFORM_DESTINATION_TEXTURE = 'destinationTexture';
+/**
+ * @internal
+ */
+export const UNIFORM_SOURCE_TEXTURE = 'sourceTexture';
+/**
+ * @internal
+ */
+export const UNIFORM_TIME = 'time';
+/**
+ * @internal
+ */
+export const UNIFORM_DELTA_TIME = 'deltaTime';
+/**
+ * @internal
+ */
+export const UNIFORM_FRAMERATE = 'framerate';
+/**
+ * @internal
+ */
+export const UNIFORM_FRAME = 'frame';
+/**
+ * @internal
+ */
+export const UNIFORM_SOURCE_MATRIX = 'sourceMatrix';
+/**
+ * @internal
+ */
+export const UNIFORM_DESTINATION_MATRIX = 'destinationMatrix';
+
+// language=glsl
+const FragmentShader = `\
+#version 300 es
+
+in vec2 position;
+
+out vec2 screenUV;
+out vec2 sourceUV;
+out vec2 destinationUV;
+
+uniform mat4 sourceMatrix;
+uniform mat4 destinationMatrix;
+
+void main() {
+ vec2 position_source = position * 0.5 + 0.5;
+ vec4 position_screen = sourceMatrix * vec4(position_source, 0, 1);
+
+ screenUV = position_screen.xy;
+ sourceUV = position_source;
+ destinationUV = (destinationMatrix * position_screen).xy;
+
+ gl_Position = (position_screen - 0.5) * 2.0;
+}
+`;
+
+/**
+ * @internal
+ */
+export class Shaders implements WebGLContextOwner {
+ private gl: WebGL2RenderingContext | null = null;
+ private positionBuffer: WebGLBuffer | null = null;
+ private sourceTexture: WebGLTexture | null = null;
+ private destinationTexture: WebGLTexture | null = null;
+ private positionLocation = 0;
+ private readonly quadPositions = new Float32Array([
+ -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0, -1.0,
+ ]);
+
+ public constructor(
+ private readonly scene: Scene,
+ private readonly sharedContext: SharedWebGLContext,
+ ) {
+ scene.onReloaded.subscribe(this.handleReload);
+ }
+
+ public setup(gl: WebGL2RenderingContext): void {
+ this.gl = gl;
+ this.updateViewport();
+ this.positionBuffer = gl.createBuffer();
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.positionBuffer);
+ gl.bufferData(gl.ARRAY_BUFFER, this.quadPositions, gl.STATIC_DRAW);
+ gl.vertexAttribPointer(this.positionLocation, 2, gl.FLOAT, false, 0, 0);
+ gl.enableVertexAttribArray(this.positionLocation);
+
+ this.sourceTexture = gl.createTexture();
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, this.sourceTexture);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+
+ this.destinationTexture = gl.createTexture();
+ gl.activeTexture(gl.TEXTURE1);
+ gl.bindTexture(gl.TEXTURE_2D, this.destinationTexture);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ }
+
+ public teardown(gl: WebGL2RenderingContext): void {
+ gl.deleteBuffer(this.positionBuffer);
+ gl.disableVertexAttribArray(this.positionLocation);
+ gl.deleteTexture(this.sourceTexture);
+ gl.deleteTexture(this.destinationTexture);
+ this.positionBuffer = null;
+ this.sourceTexture = null;
+ this.destinationTexture = null;
+ this.gl = null;
+ }
+
+ private handleReload = () => {
+ if (this.gl) {
+ this.updateViewport();
+ }
+ };
+
+ private updateViewport() {
+ if (this.gl) {
+ const size = this.scene.getRealSize();
+ this.gl.canvas.width = size.width;
+ this.gl.canvas.height = size.height;
+ this.gl.viewport(0, 0, size.width, size.height);
+ }
+ }
+
+ public getGL() {
+ return this.gl ?? this.sharedContext.borrow(this);
+ }
+
+ public getProgram(fragment: string) {
+ const program = this.sharedContext.getProgram(fragment, FragmentShader);
+ if (!program) {
+ return null;
+ }
+
+ const size = this.scene.getRealSize();
+ const gl = this.getGL();
+ gl.useProgram(program);
+ gl.uniform1i(gl.getUniformLocation(program, UNIFORM_SOURCE_TEXTURE), 0);
+ gl.uniform1i(
+ gl.getUniformLocation(program, UNIFORM_DESTINATION_TEXTURE),
+ 1,
+ );
+ gl.uniform2f(
+ gl.getUniformLocation(program, UNIFORM_RESOLUTION),
+ size.x,
+ size.y,
+ );
+ gl.uniform1f(
+ gl.getUniformLocation(program, UNIFORM_DELTA_TIME),
+ this.scene.playback.deltaTime,
+ );
+ gl.uniform1f(
+ gl.getUniformLocation(program, UNIFORM_FRAMERATE),
+ this.scene.playback.fps,
+ );
+
+ return program;
+ }
+
+ public copyTextures(destination: TexImageSource, source: TexImageSource) {
+ this.copyTexture(source, this.sourceTexture!);
+ this.copyTexture(destination, this.destinationTexture!);
+ }
+
+ public clear() {
+ const gl = this.getGL();
+ gl.clearColor(0, 0, 0, 0);
+ gl.clear(gl.COLOR_BUFFER_BIT);
+ }
+
+ public render() {
+ const gl = this.getGL();
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
+ }
+
+ private copyTexture(source: TexImageSource, texture: WebGLTexture) {
+ const gl = this.getGL();
+ gl.bindTexture(gl.TEXTURE_2D, texture);
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source);
+ gl.generateMipmap(gl.TEXTURE_2D);
+ }
+}
diff --git a/packages/core/src/scenes/index.ts b/packages/core/src/scenes/index.ts
index d66618b4..4ceceb80 100644
--- a/packages/core/src/scenes/index.ts
+++ b/packages/core/src/scenes/index.ts
@@ -11,6 +11,7 @@ export * from './Random';
export * from './Scene';
export * from './SceneMetadata';
export * from './SceneState';
+export * from './Shaders';
export * from './Slides';
export * from './Threadable';
export * from './Variables';
diff --git a/packages/core/src/threading/threads.ts b/packages/core/src/threading/threads.ts
index 90daadf0..06420471 100644
--- a/packages/core/src/threading/threads.ts
+++ b/packages/core/src/threading/threads.ts
@@ -66,7 +66,7 @@ export function* threads(
while (threads.length > 0) {
const newThreads = [];
const queue = [...threads];
- const dt = playback.framesToSeconds(1) * playback.speed;
+ const dt = playback.deltaTime;
while (queue.length > 0) {
const thread = queue.pop();
diff --git a/packages/ui/src/utils/sourceMaps.ts b/packages/ui/src/utils/sourceMaps.ts
index f7545188..cd9aca6e 100644
--- a/packages/ui/src/utils/sourceMaps.ts
+++ b/packages/ui/src/utils/sourceMaps.ts
@@ -2,6 +2,12 @@ import highlight from 'highlight.js';
import {SourceMapConsumer} from 'source-map-js';
import {withLoader} from './withLoader';
+declare module 'source-map-js' {
+ interface SourceMapConsumer {
+ raw: any;
+ }
+}
+
const ExternalFileRegex = /^\/(@fs|@id|node_modules)\//;
const StackTraceRegex = navigator.userAgent.toLowerCase().includes('chrome')
? /^ +at(.*) \(?(.*):([0-9]+):([0-9]+)/
@@ -18,7 +24,9 @@ async function getSourceMap(
}
const response = await fetch(`${file}.map${search}`);
- const consumer = new SourceMapConsumer(await response.json());
+ const json = await response.json();
+ const consumer = new SourceMapConsumer(json);
+ consumer.raw = json;
Cache.set(key, consumer);
return consumer;
}
@@ -52,6 +60,7 @@ export async function resolveStackTrace(
const [, functionName, uri, line, column] = match;
const parsed = new URL(uri);
const file = parsed.pathname;
+ const directory = file.split('/').slice(0, -1).join('/') + '/';
const entry: StackTraceEntry = {
file,
uri,
@@ -61,13 +70,19 @@ export async function resolveStackTrace(
functionName: functionName?.trim(),
};
- if (!ExternalFileRegex.test(file)) {
+ if (!entry.isExternal) {
try {
const sourceMap = await getSourceMap(file, parsed.search);
const position = sourceMap.originalPositionFor(entry);
if (position.line === null || position.column === null) {
entry.isExternal = true;
} else {
+ const source =
+ position.source[0] === '/'
+ ? position.source
+ : directory + position.source;
+
+ entry.file = source;
entry.line = position.line;
entry.column = position.column;
entry.source = position.source;
@@ -81,7 +96,28 @@ export async function resolveStackTrace(
entry.isExternal = true;
}
}
+
result.push(entry);
+
+ if (entry.sourceMap?.raw?.includeMap) {
+ const includeMap: Record<string, [string, number]> =
+ entry.sourceMap.raw.includeMap;
+ let current = entry;
+ while (current.source in includeMap) {
+ const [path, line] = includeMap[current.source];
+ const file = directory + path;
+ current = {
+ file,
+ uri: file,
+ line,
+ column: 9,
+ isExternal: false,
+ source: path,
+ sourceMap: entry.sourceMap,
+ };
+ result.push(current);
+ }
+ }
}
if (firstOnly) {
@@ -117,11 +153,12 @@ export function getSourceCodeFrame(entry: StackTraceEntry): string | null {
const {line, column} = entry;
const lastLine = line + 2;
const spacing = lastLine.toString().length;
- const sourceLines = source.split('\n').slice(line - 1, lastLine);
+ const language = getExtension(entry.source) ?? 'ts';
const code = highlight
- .highlight('typescript', sourceLines.join('\n'))
- .value.split('\n');
+ .highlight(source, {language})
+ .value.split('\n')
+ .slice(line - 1, lastLine);
const formatted = code.map(
(text, index) =>
@@ -137,3 +174,8 @@ export async function findAndOpenFirstUserFile(stack: string) {
await openFileInEditor(entry);
}
}
+
+function getExtension(file: string): string | null {
+ const parts = file.split('.');
+ return parts.length > 1 ? parts.pop() : null;
+}
diff --git a/packages/vite-plugin/package.json b/packages/vite-plugin/package.json
index e1a501ba..fbf80c1b 100644
--- a/packages/vite-plugin/package.json
+++ b/packages/vite-plugin/package.json
@@ -30,6 +30,7 @@
"dependencies": {
"fast-glob": "^3.3.1",
"follow-redirects": "^1.15.2",
- "mime-types": "^2.1.35"
+ "mime-types": "^2.1.35",
+ "source-map": "^0.6.1"
}
}
diff --git a/packages/vite-plugin/src/main.ts b/packages/vite-plugin/src/main.ts
index c0735a8c..45e9c88a 100644
--- a/packages/vite-plugin/src/main.ts
+++ b/packages/vite-plugin/src/main.ts
@@ -10,6 +10,7 @@ import {
projectsPlugin,
scenesPlugin,
settingsPlugin,
+ webglPlugin,
} from './partials';
import {PLUGIN_OPTIONS, PluginOptions, isPlugin} from './plugins';
import {getProjects} from './utils';
@@ -133,6 +134,7 @@ export default ({
editorPlugin({editor, projects}),
projectsPlugin({projects, plugins, buildForEditor}),
assetsPlugin({bufferedAssets}),
+ webglPlugin(),
corsProxyPlugin(proxy),
];
};
diff --git a/packages/vite-plugin/src/partials/index.ts b/packages/vite-plugin/src/partials/index.ts
index 0facf4da..2c5f0792 100644
--- a/packages/vite-plugin/src/partials/index.ts
+++ b/packages/vite-plugin/src/partials/index.ts
@@ -6,3 +6,4 @@ export * from './meta';
export * from './projects';
export * from './scenes';
export * from './settings';
+export * from './webgl';
diff --git a/packages/vite-plugin/src/partials/webgl.ts b/packages/vite-plugin/src/partials/webgl.ts
new file mode 100644
index 00000000..2abb0f72
--- /dev/null
+++ b/packages/vite-plugin/src/partials/webgl.ts
@@ -0,0 +1,120 @@
+import fs from 'fs';
+import path from 'path';
+import {SourceNode} from 'source-map';
+import {normalizePath, Plugin, ResolvedConfig} from 'vite';
+
+declare module 'source-map' {
+ interface SourceNode {
+ add(value: string | SourceNode): void;
+ }
+
+ interface SourceMapGenerator {
+ toJSON(): any;
+ }
+}
+
+const GLSL_EXTENSION_REGEX = /\.glsl(?:$|\?)/;
+const INCLUDE_REGEX = /^#include "([^"]+)"/;
+
+export function webglPlugin(): Plugin {
+ let config: ResolvedConfig;
+ return {
+ name: 'motion-canvas:webgl',
+
+ configResolved(resolvedConfig) {
+ config = resolvedConfig;
+ },
+
+ async transform(code, id) {
+ if (!GLSL_EXTENSION_REGEX.test(id)) {
+ return;
+ }
+
+ const [base, query] = id.split('?');
+ const {dir} = path.posix.parse(base);
+ const params = new URLSearchParams(query);
+ if (params.has('raw')) {
+ return;
+ }
+
+ const context: ResolutionContext = {
+ rootDir: dir,
+ fileStack: [],
+ includeMap: new Map(),
+ watchFile: file => this.addWatchFile(file),
+ resolve: async (source, importer) => {
+ const resolved = await this.resolve(source, importer);
+ return resolved?.id;
+ },
+ };
+
+ const glslSource = await resolveGlsl(context, id, code);
+ const sourceUrl = normalizePath(path.relative(config.root, base));
+
+ const result = glslSource.toStringWithSourceMap();
+ const map = result.map.toJSON();
+ map.includeMap = Object.fromEntries(context.includeMap);
+
+ return {
+ map,
+ code: `export default \`${result.code}\n//# sourceURL=${sourceUrl}\`;`,
+ };
+ },
+ };
+}
+
+interface ResolutionContext {
+ watchFile: (file: string) => void;
+ resolve: (source: string, importer: string) => Promise<string | undefined>;
+ rootDir: string;
+ includeMap: Map<string, [string, number]>;
+ fileStack: string[];
+}
+
+async function resolveGlsl(
+ context: ResolutionContext,
+ id: string,
+ code: string,
+): Promise<SourceNode> {
+ const lines = code.split(/\r?\n/);
+ const source = new SourceNode(1, 0, '', '');
+
+ if (context.fileStack.includes(id)) {
+ throw new Error(
+ `Circular dependency detected: ${context.fileStack.join(' -> ')}`,
+ );
+ }
+
+ context.fileStack.push(id);
+
+ const sourceMapId = path.posix.relative(context.rootDir, id);
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i];
+ const match = line.match(INCLUDE_REGEX);
+ if (match) {
+ const childId = await context.resolve(match[1], id);
+ if (!childId) {
+ continue;
+ }
+
+ const childSourceMapId = path.posix.relative(context.rootDir, childId);
+ if (context.includeMap.has(childSourceMapId)) {
+ continue;
+ }
+
+ context.includeMap.set(childSourceMapId, [sourceMapId, i + 1]);
+ context.watchFile(childId);
+ const childCode = await fs.promises.readFile(childId, 'utf-8');
+ source.add(await resolveGlsl(context, childId, childCode));
+ } else {
+ let j = 0;
+ for (; j < line.length; j++) {
+ source.add(new SourceNode(i + 1, j, sourceMapId, line[j]));
+ }
+ source.add(new SourceNode(i + 1, j, sourceMapId, '\n'));
+ }
+ }
+ context.fileStack.pop();
+
+ return source;
+}