🎥 Make videos programmatically with React
`@remotion/effects`: Add dot grid effect (#7736)
Jonny Burgerd90c1c50ffe8
diff --git a/packages/docs/components/demos/index.tsx b/packages/docs/components/demos/index.tsxindex 87b994ae74..242e24ecd9 100644--- a/packages/docs/components/demos/index.tsx+++ b/packages/docs/components/demos/index.tsx@@ -28,6 +28,7 @@ import {effectsHalftoneDemo,effectsHalftoneLinearGradientDemo,effectsHueDemo,+ effectsDotGridDemo,effectsInvertDemo,effectsLightLeakDemo,effectsMirrorDemo,@@ -119,6 +120,7 @@ const demos: DemoType[] = [effectsWaveDemo,effectsHalftoneDemo,effectsHalftoneLinearGradientDemo,+ effectsDotGridDemo,effectsStarburstDemo,effectsLightLeakDemo,arrowDemo,diff --git a/packages/docs/components/demos/types.ts b/packages/docs/components/demos/types.tsindex 23b8f7a735..8213918b28 100644--- a/packages/docs/components/demos/types.ts+++ b/packages/docs/components/demos/types.ts@@ -10,6 +10,7 @@ import {EffectsGrayscalePreview} from '../effects/effects-grayscale-preview';import {EffectsHalftoneLinearGradientPreview} from '../effects/effects-halftone-linear-gradient-preview';import {EffectsHalftonePreview} from '../effects/effects-halftone-preview';import {EffectsHuePreview} from '../effects/effects-hue-preview';+import {EffectsDotGridPreview} from '../effects/effects-dot-grid-preview';import {EffectsInvertPreview} from '../effects/effects-invert-preview';import {EffectsLightLeakPreview} from '../effects/effects-light-leak-preview';import {EffectsMirrorPreview} from '../effects/effects-mirror-preview';@@ -2329,6 +2330,44 @@ export const effectsHalftoneLinearGradientDemo: DemoType = {],};+export const effectsDotGridDemo: DemoType = {+ comp: EffectsDotGridPreview,+ compHeight: 720,+ compWidth: 1280,+ durationInFrames: 1,+ fps: 30,+ id: 'effects-dot-grid',+ autoPlay: false,+ controls: false,+ logLevel: 'info',+ options: [+ {+ name: 'dotSize',+ type: 'numeric',+ min: 0,+ max: 80,+ step: 1,+ default: 16,+ optional: 'no',+ },+ {+ name: 'gridSize',+ type: 'numeric',+ min: 1,+ max: 80,+ step: 1,+ default: 20,+ optional: 'no',+ },+ {+ name: 'invert',+ type: 'boolean',+ default: false,+ optional: 'no',+ },+ ],+};+export const effectsStarburstDemo: DemoType = {comp: EffectsStarburstPreview,compHeight: 720,diff --git a/packages/docs/components/effects/effects-dot-grid-preview.tsx b/packages/docs/components/effects/effects-dot-grid-preview.tsxnew file mode 100644index 0000000000..b5a4a1ed3e--- /dev/null+++ b/packages/docs/components/effects/effects-dot-grid-preview.tsx@@ -0,0 +1,32 @@+import {dotGrid} from '@remotion/effects/dot-grid';+import React from 'react';+import {CanvasImage} from 'remotion';+import {EFFECTS_PREVIEW_IMAGE_SRC} from './effects-preview-image';++const fullSize: React.CSSProperties = {+ width: '100%',+ height: '100%',+};++export const EffectsDotGridPreview: React.FC<{+ readonly dotSize: number;+ readonly gridSize: number;+ readonly invert: boolean;+}> = ({dotSize, gridSize, invert}) => {+ return (+ <CanvasImage+ src={EFFECTS_PREVIEW_IMAGE_SRC}+ width={1280}+ height={720}+ fit="cover"+ style={fullSize}+ effects={[+ dotGrid({+ dotSize,+ gridSize,+ invert,+ }),+ ]}+ />+ );+};diff --git a/packages/docs/docs/effects/dot-grid.mdx b/packages/docs/docs/effects/dot-grid.mdxnew file mode 100644index 0000000000..700257559c--- /dev/null+++ b/packages/docs/docs/effects/dot-grid.mdx@@ -0,0 +1,100 @@+---+image: /generated/articles-docs-effects-dot-grid.png+slug: /effects/dot-grid+title: dotGrid()+sidebar_label: dotGrid()+crumb: '@remotion/effects'+---++# dotGrid()<AvailableFrom v="4.0.469" />++_Part of the [`@remotion/effects`](/docs/effects/api) package._++An effect that turns a canvas-based component into evenly sized source-color dots.++Use it for dotted masks on [`<Video>`](/docs/media/video), [`<HtmlInCanvas>`](/docs/remotion/html-in-canvas) and [`<Solid>`](/docs/solid).++## Preview++<Demo type="effects-dot-grid" />++## Example++```tsx twoslash title="MyComp.tsx"+import {AbsoluteFill} from 'remotion';+import {Video} from '@remotion/media';+import {dotGrid} from '@remotion/effects/dot-grid';++export const MyComp: React.FC = () => {+ return (+ <AbsoluteFill>+ <Video+ src="https://remotion.media/video.mp4"+ effects={[+ dotGrid({+ dotSize: 16,+ gridSize: 20,+ }),+ ]}+ />+ </AbsoluteFill>+ );+};+```++To cut transparent dots out of the source instead, set `invert` to `true`:++```tsx twoslash title="MyComp.tsx"+import {AbsoluteFill} from 'remotion';+import {Video} from '@remotion/media';+import {dotGrid} from '@remotion/effects/dot-grid';++export const MyComp: React.FC = () => {+ return (+ <AbsoluteFill>+ <Video+ src="https://remotion.media/video.mp4"+ effects={[+ dotGrid({+ dotSize: 10,+ gridSize: 24,+ invert: true,+ }),+ ]}+ />+ </AbsoluteFill>+ );+};+```++## API++Pass an object with the following properties. You can also call `dotGrid()` without arguments.++### `dotSize?`++Diameter of each circular dot in pixels. Defaults to `16`. Must be at least `0`.++### `gridSize?`++Distance between adjacent dot centers in pixels. Defaults to `20`. Must be greater than `0`.++### `invert?`++When `false`, only the circular dots reveal the source. When `true`, the source is kept and circular dot cutouts are removed. Defaults to `false`.++### `disabled?`++When `true`, the effect is skipped. Defaults to `false`.++## Requirements++`dotGrid()` uses a WebGL2 backend. During renders, enable WebGL via [`Config.setChromiumOpenGlRenderer()`](/docs/config#setchromiumopenglrenderer) (for example `'angle'`). See [Using WebGL during renders](/docs/remotion/html-in-canvas#using-webgl-during-renders).++## See also++- [`@remotion/effects`](/docs/effects/api)+- [`halftone()`](/docs/effects/halftone)+- [`halftoneLinearGradient()`](/docs/effects/halftone-linear-gradient)+- [HTML-in-canvas guide](/docs/html-in-canvas)+- [Source code for this effect](https://github.com/remotion-dev/remotion/blob/main/packages/effects/src/dot-grid.ts)diff --git a/packages/docs/docs/effects/table-of-contents.tsx b/packages/docs/docs/effects/table-of-contents.tsxindex 3d3fb21373..53ffdbebce 100644--- a/packages/docs/docs/effects/table-of-contents.tsx+++ b/packages/docs/docs/effects/table-of-contents.tsx@@ -172,6 +172,13 @@ const categories: {name: 'halftoneLinearGradient()',description: 'Linear dot size gradient',},+ {+ link: '/docs/effects/dot-grid',+ preview: '/img/effects-dot-grid-preview.png',+ alt: 'dot grid effect preview',+ name: 'dotGrid()',+ description: 'Source-color dot mask effect',+ },{link: '/docs/effects/noise',preview: '/img/effects-noise-preview.jpg',diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.tsindex 136cddab2a..829babb06a 100644--- a/packages/docs/sidebars.ts+++ b/packages/docs/sidebars.ts@@ -279,6 +279,7 @@ const sidebars: SidebarsConfig = {'effects/halftone','effects/halftone-linear-gradient','effects/hue',+ 'effects/dot-grid','effects/invert','effects/mirror','effects/noise',diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.tsindex 7a784ceb3b..e44167223e 100644--- a/packages/docs/src/data/articles.ts+++ b/packages/docs/src/data/articles.ts@@ -1763,6 +1763,15 @@ export const articles = [noAi: false,slug: 'effects/contrast',},+ {+ id: 'effects/dot-grid',+ title: 'dotGrid()',+ relativePath: 'docs/effects/dot-grid.mdx',+ compId: 'articles-docs-effects-dot-grid',+ crumb: '@remotion/effects',+ noAi: false,+ slug: 'effects/dot-grid',+ },{id: 'effects/duotone',title: 'duotone()',diff --git a/packages/docs/static/generated/articles-docs-effects-dot-grid.png b/packages/docs/static/generated/articles-docs-effects-dot-grid.pngnew file mode 100644index 0000000000..5f4a3d2754Binary files /dev/null and b/packages/docs/static/generated/articles-docs-effects-dot-grid.png differdiff --git a/packages/docs/static/img/effects-dot-grid-preview.png b/packages/docs/static/img/effects-dot-grid-preview.pngnew file mode 100644index 0000000000..5581304e9eBinary files /dev/null and b/packages/docs/static/img/effects-dot-grid-preview.png differdiff --git a/packages/effects/bundle.ts b/packages/effects/bundle.tsindex bcb62d541f..4bac94815d 100644--- a/packages/effects/bundle.ts+++ b/packages/effects/bundle.ts@@ -18,6 +18,7 @@ const effectEntrypoints = ['src/halftone-linear-gradient.ts','src/halftone.ts','src/hue.ts',+ 'src/dot-grid.ts','src/invert.ts','src/mirror.ts','src/noise.ts',diff --git a/packages/effects/package.json b/packages/effects/package.jsonindex 0fe7587865..82017bf0df 100644--- a/packages/effects/package.json+++ b/packages/effects/package.json@@ -92,6 +92,11 @@"module": "./dist/esm/invert.mjs","import": "./dist/esm/invert.mjs"},+ "./dot-grid": {+ "types": "./dist/dot-grid.d.ts",+ "module": "./dist/esm/dot-grid.mjs",+ "import": "./dist/esm/dot-grid.mjs"+ },"./mirror": {"types": "./dist/mirror.d.ts","module": "./dist/esm/mirror.mjs",@@ -182,6 +187,9 @@"invert": ["dist/invert.d.ts"],+ "dot-grid": [+ "dist/dot-grid.d.ts"+ ],"mirror": ["dist/mirror.d.ts"],diff --git a/packages/effects/src/dot-grid.ts b/packages/effects/src/dot-grid.tsnew file mode 100644index 0000000000..28ace0c168--- /dev/null+++ b/packages/effects/src/dot-grid.ts@@ -0,0 +1,315 @@+import type {SequenceSchema} from 'remotion';+import {Internals} from 'remotion';+import {+ assertOptionalFiniteNumber,+ validateNonNegative,+} from './color-utils.js';+import {assertEffectParamsObject} from './validate-effect-param.js';++const {createEffect, createWebGL2ContextError} = Internals;++const DEFAULT_DOT_SIZE = 16 as const;+const DEFAULT_GRID_SIZE = 20 as const;+const DEFAULT_INVERT = false as const;++export const dotGridSchema = {+ dotSize: {+ type: 'number',+ min: 0,+ max: 400,+ step: 1,+ default: DEFAULT_DOT_SIZE,+ description: 'Dot size',+ },+ gridSize: {+ type: 'number',+ min: 1,+ max: 400,+ step: 1,+ default: DEFAULT_GRID_SIZE,+ description: 'Grid size',+ },+ invert: {+ type: 'boolean',+ default: DEFAULT_INVERT,+ description: 'Invert',+ },+} as const satisfies SequenceSchema;++export type DotGridParams = {+ readonly dotSize?: number;+ readonly gridSize?: number;+ readonly invert?: boolean;+};++type DotGridResolved = {+ dotSize: number;+ gridSize: number;+ invert: boolean;+};++const resolve = (p: DotGridParams): DotGridResolved => ({+ dotSize: p.dotSize ?? DEFAULT_DOT_SIZE,+ gridSize: p.gridSize ?? DEFAULT_GRID_SIZE,+ invert: p.invert ?? DEFAULT_INVERT,+});++const assertOptionalBoolean = (value: unknown, name: string): void => {+ if (value === undefined) {+ return;+ }++ if (typeof value !== 'boolean') {+ throw new TypeError(+ `"${name}" must be a boolean, but got ${JSON.stringify(value)}`,+ );+ }+};++const validatePositive = (value: number, name: string): void => {+ if (value <= 0) {+ throw new TypeError(+ `"${name}" must be greater than 0, but got ${JSON.stringify(value)}`,+ );+ }+};++const validateDotGridParams = (params: DotGridParams): void => {+ assertEffectParamsObject(params, 'Dot grid');+ assertOptionalFiniteNumber(params.dotSize, 'dotSize');+ assertOptionalFiniteNumber(params.gridSize, 'gridSize');+ assertOptionalBoolean(params.invert, 'invert');++ if (params.dotSize !== undefined) {+ validateNonNegative(params.dotSize, 'dotSize');+ }++ if (params.gridSize !== undefined) {+ validatePositive(params.gridSize, 'gridSize');+ }+};++const DOT_GRID_VS = /* glsl */ `#version 300 es+in vec2 aPos;+in vec2 aUv;+out vec2 vUv;++void main() {+ vUv = aUv;+ gl_Position = vec4(aPos, 0.0, 1.0);+}+`;++const DOT_GRID_FS = /* glsl */ `#version 300 es+precision highp float;++in vec2 vUv;+out vec4 fragColor;++uniform sampler2D uSource;+uniform vec2 uResolution;+uniform float uDotSize;+uniform float uGridSize;+uniform bool uInvert;++void main() {+ vec2 fragPos = vUv * uResolution;+ vec2 center = uResolution * 0.5;+ vec2 gridPos = fragPos - center;++ float gridSize = max(uGridSize, 0.001);+ vec2 cellIndex = floor(gridPos / gridSize + 0.5);+ vec2 gridCenter = cellIndex * gridSize;+ vec2 diff = gridPos - gridCenter;++ float radius = uDotSize * 0.5;+ float dotCoverage = radius <= 0.005+ ? 0.0+ : 1.0 - smoothstep(radius - 0.75, radius + 0.75, length(diff));+ float coverage = uInvert ? 1.0 - dotCoverage : dotCoverage;++ vec4 texColor = texture(uSource, vUv);+ fragColor = texColor * coverage;+}+`;++type DotGridState = {+ gl: WebGL2RenderingContext;+ program: WebGLProgram;+ vao: WebGLVertexArrayObject;+ vbo: WebGLBuffer;+ texture: WebGLTexture;+ uSource: WebGLUniformLocation | null;+ uResolution: WebGLUniformLocation | null;+ uDotSize: WebGLUniformLocation | null;+ uGridSize: WebGLUniformLocation | null;+ uInvert: WebGLUniformLocation | null;+};++const compileShader = (+ gl: WebGL2RenderingContext,+ type: number,+ source: string,+): WebGLShader => {+ const shader = gl.createShader(type);+ if (!shader) {+ throw new Error('Failed to create WebGL shader');+ }++ gl.shaderSource(shader, source);+ gl.compileShader(shader);+ if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {+ const log = gl.getShaderInfoLog(shader);+ gl.deleteShader(shader);+ throw new Error(`Dot grid shader compile failed: ${log ?? '(no log)'}`);+ }++ return shader;+};++const linkProgram = (+ gl: WebGL2RenderingContext,+ vs: WebGLShader,+ fs: WebGLShader,+): WebGLProgram => {+ const program = gl.createProgram();+ if (!program) {+ throw new Error('Failed to create WebGL program');+ }++ gl.attachShader(program, vs);+ gl.attachShader(program, fs);+ gl.linkProgram(program);+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {+ const log = gl.getProgramInfoLog(program);+ gl.deleteProgram(program);+ throw new Error(`Dot grid program link failed: ${log ?? '(no log)'}`);+ }++ return program;+};++export const dotGrid = createEffect<DotGridParams, DotGridState>({+ type: 'remotion/dot-grid',+ label: 'dotGrid()',+ documentationLink: 'https://www.remotion.dev/docs/effects/dot-grid',+ backend: 'webgl2',+ calculateKey: (params) => {+ const r = resolve(params);+ return `dot-grid-${r.dotSize}-${r.gridSize}-${r.invert ? 1 : 0}`;+ },+ setup: (target) => {+ const gl = target.getContext('webgl2', {+ premultipliedAlpha: true,+ alpha: true,+ preserveDrawingBuffer: true,+ });+ if (!gl) {+ throw createWebGL2ContextError('dot grid effect');+ }++ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);++ const vs = compileShader(gl, gl.VERTEX_SHADER, DOT_GRID_VS);+ const fs = compileShader(gl, gl.FRAGMENT_SHADER, DOT_GRID_FS);+ const program = linkProgram(gl, vs, fs);+ gl.deleteShader(vs);+ gl.deleteShader(fs);++ const vao = gl.createVertexArray();+ if (!vao) {+ throw new Error('Failed to create WebGL vertex array');+ }++ gl.bindVertexArray(vao);++ const data = new Float32Array([+ -1, -1, 0, 0, 1, -1, 1, 0, -1, 1, 0, 1, 1, 1, 1, 1,+ ]);++ const vbo = gl.createBuffer();+ if (!vbo) {+ throw new Error('Failed to create WebGL buffer');+ }++ gl.bindBuffer(gl.ARRAY_BUFFER, vbo);+ gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);++ const aPos = gl.getAttribLocation(program, 'aPos');+ const aUv = gl.getAttribLocation(program, 'aUv');+ gl.enableVertexAttribArray(aPos);+ gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 16, 0);+ gl.enableVertexAttribArray(aUv);+ gl.vertexAttribPointer(aUv, 2, gl.FLOAT, false, 16, 8);++ gl.bindVertexArray(null);++ const texture = gl.createTexture();+ if (!texture) {+ throw new Error('Failed to create WebGL texture');+ }++ gl.bindTexture(gl.TEXTURE_2D, texture);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);+ gl.bindTexture(gl.TEXTURE_2D, null);++ return {+ gl,+ program,+ vao,+ vbo,+ texture,+ uSource: gl.getUniformLocation(program, 'uSource'),+ uResolution: gl.getUniformLocation(program, 'uResolution'),+ uDotSize: gl.getUniformLocation(program, 'uDotSize'),+ uGridSize: gl.getUniformLocation(program, 'uGridSize'),+ uInvert: gl.getUniformLocation(program, 'uInvert'),+ };+ },+ apply: ({source, width, height, params, state, flipSourceY}) => {+ const r = resolve(params);+ const {gl, program, vao, texture} = state;++ gl.viewport(0, 0, width, height);+ gl.clearColor(0, 0, 0, 0);+ gl.clear(gl.COLOR_BUFFER_BIT);++ gl.useProgram(program);+ gl.bindVertexArray(vao);++ gl.activeTexture(gl.TEXTURE0);+ gl.bindTexture(gl.TEXTURE_2D, texture);+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipSourceY);+ gl.texImage2D(+ gl.TEXTURE_2D,+ 0,+ gl.RGBA,+ gl.RGBA,+ gl.UNSIGNED_BYTE,+ source as TexImageSource,+ );++ if (state.uSource) gl.uniform1i(state.uSource, 0);+ if (state.uResolution) gl.uniform2f(state.uResolution, width, height);+ if (state.uDotSize) gl.uniform1f(state.uDotSize, r.dotSize);+ if (state.uGridSize) gl.uniform1f(state.uGridSize, r.gridSize);+ if (state.uInvert) gl.uniform1i(state.uInvert, r.invert ? 1 : 0);++ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);++ gl.bindVertexArray(null);+ gl.bindTexture(gl.TEXTURE_2D, null);+ gl.useProgram(null);+ },+ cleanup: ({gl, program, vao, vbo, texture}) => {+ gl.deleteBuffer(vbo);+ gl.deleteProgram(program);+ gl.deleteVertexArray(vao);+ gl.deleteTexture(texture);+ },+ schema: dotGridSchema,+ validateParams: validateDotGridParams,+});diff --git a/packages/effects/src/test/effect-params.test.ts b/packages/effects/src/test/effect-params.test.tsindex 109914c62d..f2e6d22dc9 100644--- a/packages/effects/src/test/effect-params.test.ts+++ b/packages/effects/src/test/effect-params.test.ts@@ -4,6 +4,7 @@ import {blur} from '../blur/index.js';import {brightness} from '../brightness.js';import {chromaticAberration} from '../chromatic-aberration/index.js';import {contrast} from '../contrast.js';+import {dotGrid} from '../dot-grid.js';import {duotone} from '../duotone.js';import {glow} from '../glow/index.js';import {grayscale} from '../grayscale.js';@@ -59,6 +60,9 @@ test('@remotion/effects expose documentation links', () => {expect(invert().definition.documentationLink).toBe('https://www.remotion.dev/docs/effects/invert',);+ expect(dotGrid().definition.documentationLink).toBe(+ 'https://www.remotion.dev/docs/effects/dot-grid',+ );expect(mirror().definition.documentationLink).toBe('https://www.remotion.dev/docs/effects/mirror',);@@ -108,6 +112,7 @@ test('@remotion/effects expose API names as Studio labels', () => {);expect(hue().definition.label).toBe('hue()');expect(invert().definition.label).toBe('invert()');+ expect(dotGrid().definition.label).toBe('dotGrid()');expect(mirror().definition.label).toBe('mirror()');expect(noise().definition.label).toBe('noise()');expect(saturation().definition.label).toBe('saturation()');@@ -717,6 +722,48 @@ test('halftoneLinearGradient() parameters produce distinct effect keys', () => {).toBe(5);});+test('dotGrid() accepts default params', () => {+ expect(() => dotGrid()).not.toThrow();+});++test('dotGrid() rejects non-finite dot size', () => {+ expect(() => dotGrid({dotSize: Number.NaN})).toThrow(+ '"dotSize" must be a finite number',+ );+});++test('dotGrid() rejects dot size below range', () => {+ expect(() => dotGrid({dotSize: -1})).toThrow('"dotSize" must be >= 0');+});++test('dotGrid() rejects non-positive grid size', () => {+ expect(() => dotGrid({gridSize: 0})).toThrow(+ '"gridSize" must be greater than 0',+ );+});++test('dotGrid() rejects non-boolean invert', () => {+ expect(() => dotGrid({invert: 'yes' as unknown as boolean})).toThrow(+ '"invert" must be a boolean',+ );+});++test('dotGrid() parameters produce distinct effect keys', () => {+ const defaultGrid = dotGrid();+ const largerDots = dotGrid({dotSize: 24});+ const widerGrid = dotGrid({gridSize: 32});+ const inverted = dotGrid({invert: true});++ expect(+ new Set([+ defaultGrid.effectKey,+ largerDots.effectKey,+ widerGrid.effectKey,+ inverted.effectKey,+ ]).size,+ ).toBe(4);+});+test('invert() accepts default params', () => {expect(() => invert()).not.toThrow();});