🎥 Make videos programmatically with React
`@remotion/effects`: Add gridlines effect (#8564)
Jonny Burger56fbb7f28dc3
diff --git a/packages/docs/components/effects-demos/registry.ts b/packages/docs/components/effects-demos/registry.tsindex 201de69001..ee9781c5bf 100644--- a/packages/docs/components/effects-demos/registry.ts+++ b/packages/docs/components/effects-demos/registry.ts@@ -15,6 +15,7 @@ import {evolve} from '@remotion/effects/evolve';import {fisheye} from '@remotion/effects/fisheye';import {glow} from '@remotion/effects/glow';import {grayscale} from '@remotion/effects/grayscale';+import {gridlines} from '@remotion/effects/gridlines';import {halftone} from '@remotion/effects/halftone';import {halftoneLinearGradient} from '@remotion/effects/halftone-linear-gradient';import {hue} from '@remotion/effects/hue';@@ -63,6 +64,7 @@ import {EffectsEvolvePreview} from '../effects/effects-evolve-preview';import {EffectsFisheyePreview} from '../effects/effects-fisheye-preview';import {EffectsGlowPreview} from '../effects/effects-glow-preview';import {EffectsGrayscalePreview} from '../effects/effects-grayscale-preview';+import {EffectsGridlinesPreview} from '../effects/effects-gridlines-preview';import {EffectsHalftoneLinearGradientPreview} from '../effects/effects-halftone-linear-gradient-preview';import {EffectsHalftonePreview} from '../effects/effects-halftone-preview';import {EffectsHuePreview} from '../effects/effects-hue-preview';@@ -519,6 +521,14 @@ export const effectsDemos: EffectsDemoType[] = [comp: EffectsHalftoneLinearGradientPreview,schema: halftoneLinearGradient().definition.schema,},+ {+ ...defaults,+ id: 'effects-gridlines',+ effectName: 'gridlines',+ effectImportPath: '@remotion/effects/gridlines',+ comp: EffectsGridlinesPreview,+ schema: gridlines().definition.schema,+ },{...defaults,id: 'effects-dot-grid',diff --git a/packages/docs/components/effects/effects-gridlines-preview.tsx b/packages/docs/components/effects/effects-gridlines-preview.tsxnew file mode 100644index 0000000000..b74577451e--- /dev/null+++ b/packages/docs/components/effects/effects-gridlines-preview.tsx@@ -0,0 +1,51 @@+import {gridlines} from '@remotion/effects/gridlines';+import React from 'react';+import {Solid, useVideoConfig} from 'remotion';++export const EffectsGridlinesPreview: React.FC<{+ readonly gridSize: number;+ readonly lineWidth: number;+ readonly lineColor: string;+ readonly backgroundColor: string;+ readonly rotation: number;+ readonly rotationX: number;+ readonly rotationY: number;+ readonly perspective: number;+ readonly offsetX: number;+ readonly offsetY: number;+}> = ({+ gridSize,+ lineWidth,+ lineColor,+ backgroundColor,+ rotation,+ rotationX,+ rotationY,+ perspective,+ offsetX,+ offsetY,+}) => {+ const {width, height} = useVideoConfig();++ return (+ <Solid+ width={width}+ height={height}+ color="#101828"+ effects={[+ gridlines({+ gridSize,+ lineWidth,+ lineColor,+ backgroundColor,+ rotation,+ rotationX,+ rotationY,+ perspective,+ offsetX,+ offsetY,+ }),+ ]}+ />+ );+};diff --git a/packages/docs/docs/effects/checkerboard.mdx b/packages/docs/docs/effects/checkerboard.mdxindex 19ad3e0f14..666e07a7a3 100644--- a/packages/docs/docs/effects/checkerboard.mdx+++ b/packages/docs/docs/effects/checkerboard.mdx@@ -66,7 +66,7 @@ Size of each square cell in pixels. Defaults to `80`.Transparent gap in pixels between cells. Defaults to `0`.-With `gap: 0` (the default), cells are packed solid with no gap between them.+With `gap: 0` (the default), cells are packed solid with no gap between them.With `gap > 0`, the source content shows through between cells.### `angle?`diff --git a/packages/docs/docs/effects/gridlines.mdx b/packages/docs/docs/effects/gridlines.mdxnew file mode 100644index 0000000000..a15310a3e0--- /dev/null+++ b/packages/docs/docs/effects/gridlines.mdx@@ -0,0 +1,179 @@+---+image: /generated/articles-docs-effects-gridlines.png+slug: /effects/gridlines+title: gridlines()+sidebar_label: gridlines()+crumb: '@remotion/effects'+---++# gridlines()<AvailableFrom v="4.0.476" />++_Part of the [`@remotion/effects`](/docs/effects/api) package._++Draws a configurable rectangular grid over a canvas-based component.++Use it for overlays, guide patterns, and generated backgrounds on canvas-based components such as [`<Video>`](/docs/media/video), [`<HtmlInCanvas>`](/docs/remotion/html-in-canvas) and [`<Solid>`](/docs/solid).++## Preview++<EffectsDemo type="effects-gridlines" />++## Example++```tsx twoslash title="MyComp.tsx"+import {AbsoluteFill, Solid} from 'remotion';+import {gridlines} from '@remotion/effects/gridlines';++export const MyComp: React.FC = () => {+ return (+ <AbsoluteFill>+ <Solid+ width={1280}+ height={720}+ color="#101828"+ effects={[+ gridlines({+ gridSize: 72,+ lineWidth: 3,+ lineColor: '#7cc6ff',+ }),+ ]}+ />+ </AbsoluteFill>+ );+};+```++To generate a complete grid tile, set `backgroundColor`:++```tsx twoslash title="MyComp.tsx"+import {AbsoluteFill, Solid} from 'remotion';+import {gridlines} from '@remotion/effects/gridlines';++export const MyComp: React.FC = () => {+ return (+ <AbsoluteFill>+ <Solid+ width={1280}+ height={720}+ effects={[+ gridlines({+ gridSize: 64,+ lineWidth: 2,+ lineColor: '#ffffff',+ backgroundColor: '#0f172a',+ rotation: 15,+ }),+ ]}+ />+ </AbsoluteFill>+ );+};+```++To create a retro perspective floor, combine `rotationX` and `perspective`:++```tsx twoslash title="MyComp.tsx"+import {AbsoluteFill, Solid} from 'remotion';+import {gridlines} from '@remotion/effects/gridlines';++export const MyComp: React.FC = () => {+ return (+ <AbsoluteFill>+ <Solid+ width={1280}+ height={720}+ color="#101828"+ effects={[+ gridlines({+ gridSize: 72,+ lineWidth: 3,+ lineColor: '#ff4fd8',+ rotationX: -68,+ perspective: 900,+ offsetY: 180,+ }),+ ]}+ />+ </AbsoluteFill>+ );+};+```++## API++Pass an object with the following properties. You can also call `gridlines()` without arguments.++### `gridSize?`++Distance between adjacent grid lines in pixels. Defaults to `64`. Must be greater than `0`.++### `lineWidth?`++Width of each grid line in screen pixels. Defaults to `2`. Must be at least `0`.++Set this to `0` to render no grid lines.++### `lineColor?`++Color of the grid lines. Defaults to `'#ffffff'`.++### `backgroundColor?`++Color behind the grid lines. Defaults to `'transparent'`.++Keep this transparent to draw the grid over the previous effect in the chain.++### `rotation?`++Rotates the grid in degrees. Defaults to `0`.++### `rotationX?`++Rotates the grid plane around the X axis in degrees. Defaults to `0`.++Use this with `perspective` to tilt the grid into the screen.++### `rotationY?`++Rotates the grid plane around the Y axis in degrees. Defaults to `0`.++### `perspective?`++Perspective distance in pixels. Defaults to `0`, which renders an orthographic grid.++Set this to a positive value to project the grid as a 3D plane. Larger values make the perspective milder.++### `offsetX?`++Horizontal grid offset in pixels. Defaults to `0`.++Animate this value to move the grid horizontally.++### `offsetY?`++Vertical grid offset in pixels. Defaults to `0`.++Animate this value to move the grid vertically.++### `maskToSourceAlpha?`++Masks the generated grid to the source alpha channel. Defaults to `false`.++Set this to `true` to prevent grid lines and background color from appearing in fully transparent source pixels.++### `disabled?`++When `true`, the effect is skipped. Defaults to `false`.++## Requirements++`gridlines()` uses a WebGL2 backend. During renders, enable WebGL via [`Config.setChromiumOpenGlRenderer('angle')`](/docs/config#setchromiumopenglrenderer). See [Using WebGL during renders](/docs/remotion/html-in-canvas#using-webgl-during-renders).++## See also++- [`@remotion/effects`](/docs/effects/api)+- [`lines()`](/docs/effects/lines)+- [`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/gridlines.ts)diff --git a/packages/docs/docs/investors.mdx b/packages/docs/docs/investors.mdxindex a0110bd828..b574707e4e 100644--- a/packages/docs/docs/investors.mdx+++ b/packages/docs/docs/investors.mdx@@ -42,13 +42,13 @@ See also: [Why we are not building Lovable for Motion Graphics](/docs/lovable-fo## Customers-Remotion has over 200 active customers, making us very diversified.+Remotion has over 200 active customers, making us very diversified.Our goal is to make Remotion a framework that works for everyone, not favoring any specific customer.## Shark Tank appearance-In 2024, we [appeared on the Swiss version of Shark Tank](https://www.youtube.com/watch?v=XzY1ukohYdA).+In 2024, we [appeared on the Swiss version of Shark Tank](https://www.youtube.com/watch?v=XzY1ukohYdA).We filled in as a last-minute replacement for a startup which already got funded in the meanwhile.-We were not actively looking for a new financing round, but saw this as a great opportunity for exposing and challenging ourselves.+We were not actively looking for a new financing round, but saw this as a great opportunity for exposing and challenging ourselves.Keep this in mind while watching this, nonetheless this is a great watch to learn more about our company!diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.tsindex 599663cbe6..7a4a716380 100644--- a/packages/docs/sidebars.ts+++ b/packages/docs/sidebars.ts@@ -290,6 +290,7 @@ const sidebars: SidebarsConfig = {'effects/fisheye','effects/glow','effects/grayscale',+ 'effects/gridlines','effects/halftone','effects/halftone-linear-gradient','effects/hue',diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.tsindex 23fb3d807e..2ef6710640 100644--- a/packages/docs/src/data/articles.ts+++ b/packages/docs/src/data/articles.ts@@ -1889,6 +1889,15 @@ export const articles = [noAi: false,slug: 'effects/grayscale',},+ {+ id: 'effects/gridlines',+ title: 'gridlines()',+ relativePath: 'docs/effects/gridlines.mdx',+ compId: 'articles-docs-effects-gridlines',+ crumb: '@remotion/effects',+ noAi: false,+ slug: 'effects/gridlines',+ },{id: 'effects/halftone-linear-gradient',title: 'halftoneLinearGradient()',diff --git a/packages/docs/src/remotion/Root.tsx b/packages/docs/src/remotion/Root.tsxindex 96cbe86f25..afe25782a9 100644--- a/packages/docs/src/remotion/Root.tsx+++ b/packages/docs/src/remotion/Root.tsx@@ -19,6 +19,7 @@ import {EffectsEvolvePreview} from '../../components/effects/effects-evolve-previmport {EffectsFisheyePreview} from '../../components/effects/effects-fisheye-preview';import {EffectsGlowPreview} from '../../components/effects/effects-glow-preview';import {EffectsGrayscalePreview} from '../../components/effects/effects-grayscale-preview';+import {EffectsGridlinesPreview} from '../../components/effects/effects-gridlines-preview';import {EffectsHalftoneLinearGradientPreview} from '../../components/effects/effects-halftone-linear-gradient-preview';import {EffectsHalftonePreview} from '../../components/effects/effects-halftone-preview';import {EffectsHuePreview} from '../../components/effects/effects-hue-preview';@@ -458,6 +459,24 @@ export const RemotionRoot: React.FC = () => {dotColor: '#0b84f3',}}/>+ <Still+ id="effects-gridlines-preview"+ component={EffectsGridlinesPreview}+ width={1280}+ height={720}+ defaultProps={{+ gridSize: 72,+ lineWidth: 3,+ lineColor: '#ffffff',+ backgroundColor: 'transparent',+ rotation: 0,+ rotationX: 0,+ rotationY: 0,+ perspective: 0,+ offsetX: 0,+ offsetY: 0,+ }}+ /><Stillid="effects-dot-grid-preview"component={EffectsDotGridPreview}diff --git a/packages/docs/static/generated/articles-docs-effects-gridlines.png b/packages/docs/static/generated/articles-docs-effects-gridlines.pngnew file mode 100644index 0000000000..8f472c9546Binary files /dev/null and b/packages/docs/static/generated/articles-docs-effects-gridlines.png differdiff --git a/packages/docs/static/img/effects-gridlines-preview.png b/packages/docs/static/img/effects-gridlines-preview.pngnew file mode 100644index 0000000000..67b8e0e9efBinary files /dev/null and b/packages/docs/static/img/effects-gridlines-preview.png differdiff --git a/packages/effects/bundle.ts b/packages/effects/bundle.tsindex 06a5de5bdb..41a843ca15 100644--- a/packages/effects/bundle.ts+++ b/packages/effects/bundle.ts@@ -1,5 +1,5 @@-import {build} from 'bun';import path from 'path';+import {build} from 'bun';if (process.env.NODE_ENV !== 'production') {throw new Error('This script must be run using NODE_ENV=production');@@ -23,6 +23,7 @@ const effectEntrypoints = ['src/fisheye.ts','src/glow.ts','src/grayscale.ts',+ 'src/gridlines.ts','src/halftone-linear-gradient.ts','src/halftone.ts','src/hue.ts',diff --git a/packages/effects/package.json b/packages/effects/package.jsonindex 29d6d71346..50208212c2 100644--- a/packages/effects/package.json+++ b/packages/effects/package.json@@ -109,6 +109,11 @@"module": "./dist/esm/glow.mjs","import": "./dist/esm/glow.mjs"},+ "./gridlines": {+ "types": "./dist/gridlines.d.ts",+ "module": "./dist/esm/gridlines.mjs",+ "import": "./dist/esm/gridlines.mjs"+ },"./halftone": {"types": "./dist/halftone.d.ts","module": "./dist/esm/halftone.mjs",@@ -313,6 +318,9 @@"glow": ["dist/glow.d.ts"],+ "gridlines": [+ "dist/gridlines.d.ts"+ ],"halftone": ["dist/halftone.d.ts"],diff --git a/packages/effects/src/gridlines.ts b/packages/effects/src/gridlines.tsnew file mode 100644index 0000000000..60438a6994--- /dev/null+++ b/packages/effects/src/gridlines.ts@@ -0,0 +1,591 @@+import type {InteractivitySchema} from 'remotion';+import {Internals} from 'remotion';+import {+ assertOptionalFiniteNumber,+ parseColorRgba,+ type ParsedColorRgba,+} from './color-utils.js';+import {+ assertEffectParamsObject,+ assertOptionalBoolean,+ assertOptionalColor,+} from './validate-effect-param.js';++const {createEffect, createWebGL2ContextError} = Internals;++const DEFAULT_GRID_SIZE = 64 as const;+const DEFAULT_LINE_WIDTH = 2 as const;+const DEFAULT_LINE_COLOR = '#ffffff' as const;+const DEFAULT_BACKGROUND_COLOR = 'transparent' as const;+const DEFAULT_ROTATION = 0 as const;+const DEFAULT_ROTATION_X = 0 as const;+const DEFAULT_ROTATION_Y = 0 as const;+const DEFAULT_PERSPECTIVE = 0 as const;+const DEFAULT_OFFSET_X = 0 as const;+const DEFAULT_OFFSET_Y = 0 as const;+const DEFAULT_MASK_TO_SOURCE_ALPHA = false as const;++export const gridlinesSchema = {+ gridSize: {+ type: 'number',+ min: 1,+ max: 400,+ step: 1,+ default: DEFAULT_GRID_SIZE,+ description: 'Grid size',+ hiddenFromList: false,+ },+ lineWidth: {+ type: 'number',+ min: 0,+ max: 100,+ step: 0.1,+ default: DEFAULT_LINE_WIDTH,+ description: 'Line width',+ hiddenFromList: false,+ },+ lineColor: {+ type: 'color',+ default: DEFAULT_LINE_COLOR,+ description: 'Line color',+ },+ backgroundColor: {+ type: 'color',+ default: DEFAULT_BACKGROUND_COLOR,+ description: 'Background color',+ },+ rotation: {+ type: 'rotation-degrees',+ min: -180,+ max: 180,+ step: 1,+ default: DEFAULT_ROTATION,+ description: 'Rotation',+ },+ rotationX: {+ type: 'rotation-degrees',+ min: -180,+ max: 180,+ step: 1,+ default: DEFAULT_ROTATION_X,+ description: 'Rotation X',+ },+ rotationY: {+ type: 'rotation-degrees',+ min: -180,+ max: 180,+ step: 1,+ default: DEFAULT_ROTATION_Y,+ description: 'Rotation Y',+ },+ perspective: {+ type: 'number',+ min: 0,+ max: 4000,+ step: 1,+ default: DEFAULT_PERSPECTIVE,+ description: 'Perspective',+ hiddenFromList: false,+ },+ offsetX: {+ type: 'number',+ min: -400,+ max: 400,+ step: 0.1,+ default: DEFAULT_OFFSET_X,+ description: 'Offset X',+ hiddenFromList: false,+ },+ offsetY: {+ type: 'number',+ min: -400,+ max: 400,+ step: 0.1,+ default: DEFAULT_OFFSET_Y,+ description: 'Offset Y',+ hiddenFromList: false,+ },+ maskToSourceAlpha: {+ type: 'boolean',+ default: DEFAULT_MASK_TO_SOURCE_ALPHA,+ description: 'Mask to source alpha',+ },+} as const satisfies InteractivitySchema;++export type GridlinesParams = {+ /** Distance between adjacent grid lines in pixels. Defaults to `64`. */+ readonly gridSize?: number;+ /** Width of each grid line in pixels. Defaults to `2`. */+ readonly lineWidth?: number;+ /** Color of the grid lines. Defaults to white. */+ readonly lineColor?: string;+ /** Color behind the grid lines. Defaults to transparent. */+ readonly backgroundColor?: string;+ /** Rotates the grid in degrees. Defaults to `0`. */+ readonly rotation?: number;+ /** Rotates the grid plane around the X axis in degrees. Defaults to `0`. */+ readonly rotationX?: number;+ /** Rotates the grid plane around the Y axis in degrees. Defaults to `0`. */+ readonly rotationY?: number;+ /** Perspective distance in pixels. Defaults to `0` for an orthographic grid. */+ readonly perspective?: number;+ /** Horizontal grid offset in pixels. Defaults to `0`. */+ readonly offsetX?: number;+ /** Vertical grid offset in pixels. Defaults to `0`. */+ readonly offsetY?: number;+ /** Masks the generated grid to the source alpha channel. Defaults to `false`. */+ readonly maskToSourceAlpha?: boolean;+};++type GridlinesResolved = {+ gridSize: number;+ lineWidth: number;+ lineColor: string;+ backgroundColor: string;+ rotation: number;+ rotationX: number;+ rotationY: number;+ perspective: number;+ offsetX: number;+ offsetY: number;+ maskToSourceAlpha: boolean;+};++type GridlinesState = {+ readonly gl: WebGL2RenderingContext;+ readonly program: WebGLProgram;+ readonly vao: WebGLVertexArrayObject;+ readonly vbo: WebGLBuffer;+ readonly texture: WebGLTexture;+ readonly uniforms: {+ readonly uSource: WebGLUniformLocation | null;+ readonly uResolution: WebGLUniformLocation | null;+ readonly uGridSize: WebGLUniformLocation | null;+ readonly uLineWidth: WebGLUniformLocation | null;+ readonly uLineColor: WebGLUniformLocation | null;+ readonly uBackgroundColor: WebGLUniformLocation | null;+ readonly uRotation: WebGLUniformLocation | null;+ readonly uRotationX: WebGLUniformLocation | null;+ readonly uRotationY: WebGLUniformLocation | null;+ readonly uPerspective: WebGLUniformLocation | null;+ readonly uOffset: WebGLUniformLocation | null;+ readonly uMaskToSourceAlpha: WebGLUniformLocation | null;+ };+ readonly colorCtx: CanvasRenderingContext2D;+ cachedLineColorStr: string;+ cachedLineColorRgba: ParsedColorRgba;+ cachedBackgroundColorStr: string;+ cachedBackgroundColorRgba: ParsedColorRgba;+};++const resolve = (p: GridlinesParams): GridlinesResolved => ({+ gridSize: p.gridSize ?? DEFAULT_GRID_SIZE,+ lineWidth: p.lineWidth ?? DEFAULT_LINE_WIDTH,+ lineColor: p.lineColor ?? DEFAULT_LINE_COLOR,+ backgroundColor: p.backgroundColor ?? DEFAULT_BACKGROUND_COLOR,+ rotation: p.rotation ?? DEFAULT_ROTATION,+ rotationX: p.rotationX ?? DEFAULT_ROTATION_X,+ rotationY: p.rotationY ?? DEFAULT_ROTATION_Y,+ perspective: p.perspective ?? DEFAULT_PERSPECTIVE,+ offsetX: p.offsetX ?? DEFAULT_OFFSET_X,+ offsetY: p.offsetY ?? DEFAULT_OFFSET_Y,+ maskToSourceAlpha: p.maskToSourceAlpha ?? DEFAULT_MASK_TO_SOURCE_ALPHA,+});++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 validateNonNegative = (value: number, name: string): void => {+ if (value < 0) {+ throw new TypeError(+ `"${name}" must be greater than or equal to 0, but got ${JSON.stringify(value)}`,+ );+ }+};++const validateGridlinesParams = (params: GridlinesParams): void => {+ assertEffectParamsObject(params, 'Gridlines');+ assertOptionalFiniteNumber(params.gridSize, 'gridSize');+ assertOptionalFiniteNumber(params.lineWidth, 'lineWidth');+ assertOptionalFiniteNumber(params.rotation, 'rotation');+ assertOptionalFiniteNumber(params.rotationX, 'rotationX');+ assertOptionalFiniteNumber(params.rotationY, 'rotationY');+ assertOptionalFiniteNumber(params.perspective, 'perspective');+ assertOptionalFiniteNumber(params.offsetX, 'offsetX');+ assertOptionalFiniteNumber(params.offsetY, 'offsetY');+ assertOptionalColor(params.lineColor, 'lineColor');+ assertOptionalColor(params.backgroundColor, 'backgroundColor');+ assertOptionalBoolean(params.maskToSourceAlpha, 'maskToSourceAlpha');++ validatePositive(params.gridSize ?? DEFAULT_GRID_SIZE, 'gridSize');+ validateNonNegative(params.lineWidth ?? DEFAULT_LINE_WIDTH, 'lineWidth');+ validateNonNegative(params.perspective ?? DEFAULT_PERSPECTIVE, 'perspective');+};++const GRIDLINES_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 GRIDLINES_FS = /* glsl */ `#version 300 es+precision highp float;++in vec2 vUv;+out vec4 fragColor;++uniform sampler2D uSource;+uniform vec2 uResolution;+uniform float uGridSize;+uniform float uLineWidth;+uniform vec4 uLineColor;+uniform vec4 uBackgroundColor;+uniform float uRotation;+uniform float uRotationX;+uniform float uRotationY;+uniform float uPerspective;+uniform vec2 uOffset;+uniform bool uMaskToSourceAlpha;++vec4 sourceOver(vec4 backdrop, vec4 overlay) {+ return overlay + backdrop * (1.0 - overlay.a);+}++vec4 sourceAtop(vec4 backdrop, vec4 overlay) {+ return vec4(+ overlay.rgb * backdrop.a + backdrop.rgb * (1.0 - overlay.a),+ backdrop.a+ );+}++mat3 rotationMatrix(float rotationX, float rotationY, float rotationZ) {+ float sx = sin(rotationX);+ float cx = cos(rotationX);+ float sy = sin(rotationY);+ float cy = cos(rotationY);+ float sz = sin(rotationZ);+ float cz = cos(rotationZ);++ mat3 rx = mat3(+ 1.0, 0.0, 0.0,+ 0.0, cx, sx,+ 0.0, -sx, cx+ );+ mat3 ry = mat3(+ cy, 0.0, -sy,+ 0.0, 1.0, 0.0,+ sy, 0.0, cy+ );+ mat3 rz = mat3(+ cz, sz, 0.0,+ -sz, cz, 0.0,+ 0.0, 0.0, 1.0+ );++ return rz * ry * rx;+}++void main() {+ vec4 texColor = texture(uSource, vUv);+ vec2 centered = vUv * uResolution - uResolution * 0.5;+ mat3 rotation = rotationMatrix(uRotationX, uRotationY, uRotation);+ vec2 gridCoord;++ if (uPerspective <= 0.0) {+ vec3 rotated = rotation * vec3(centered, 0.0);+ gridCoord = rotated.xy + uOffset;+ } else {+ vec3 camera = vec3(0.0, 0.0, uPerspective);+ vec3 ray = normalize(vec3(centered, -uPerspective));+ vec3 normal = rotation * vec3(0.0, 0.0, 1.0);+ float denominator = dot(ray, normal);+ float t = -dot(camera, normal) / denominator;++ if (abs(denominator) < 0.0001 || t <= 0.0) {+ fragColor = sourceOver(texColor, uBackgroundColor);+ return;+ }++ vec3 worldPosition = camera + ray * t;+ vec3 localPosition = transpose(rotation) * worldPosition;+ gridCoord = localPosition.xy + uOffset;+ }++ float gridSize = max(uGridSize, 0.001);+ vec2 cell = abs(fract(gridCoord / gridSize + 0.5) - 0.5) * gridSize;+ float halfLineWidth = uLineWidth * 0.5;+ vec2 gridUnitsPerPixel = max(fwidth(gridCoord), vec2(0.001));+ vec2 halfWidthInGridUnits = halfLineWidth * gridUnitsPerPixel;+ vec2 antialiasInGridUnits = gridUnitsPerPixel;+ vec2 projectedCellSize = gridSize / gridUnitsPerPixel;+ vec2 densityFade = smoothstep(+ vec2(max(uLineWidth * 1.5, 1.0)),+ vec2(max(uLineWidth * 4.0, 2.0)),+ projectedCellSize+ );+ vec2 lineCoverage = halfLineWidth <= 0.001+ ? vec2(0.0)+ : 1.0 - smoothstep(+ halfWidthInGridUnits - antialiasInGridUnits,+ halfWidthInGridUnits + antialiasInGridUnits,+ cell+ );+ lineCoverage *= densityFade;+ float coverage = max(lineCoverage.x, lineCoverage.y);++ vec4 background = uBackgroundColor;+ vec4 line = uLineColor * coverage;++ if (uMaskToSourceAlpha) {+ fragColor = sourceAtop(sourceAtop(texColor, background), line);+ return;+ }++ fragColor = sourceOver(sourceOver(texColor, background), line);+}+`;++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(`Gridlines 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(`Gridlines program link failed: ${log ?? '(no log)'}`);+ }++ return program;+};++const rgbaToUniform = (+ rgba: ParsedColorRgba,+): readonly [number, number, number, number] => {+ const [r, g, b, a] = rgba;+ const alpha = a / 255;+ return [(r / 255) * alpha, (g / 255) * alpha, (b / 255) * alpha, alpha];+};++export const gridlines = createEffect<GridlinesParams, GridlinesState>({+ type: 'remotion/gridlines',+ label: 'gridlines()',+ documentationLink: 'https://www.remotion.dev/docs/effects/gridlines',+ backend: 'webgl2',+ calculateKey: (params) => {+ const r = resolve(params);+ const maskSuffix = r.maskToSourceAlpha ? '-mask-to-source-alpha' : '';+ return `gridlines-${r.gridSize}-${r.lineWidth}-${r.lineColor}-${r.backgroundColor}-${r.rotation}-${r.rotationX}-${r.rotationY}-${r.perspective}-${r.offsetX}-${r.offsetY}${maskSuffix}`;+ },+ setup: (target) => {+ const gl = target.getContext('webgl2', {+ premultipliedAlpha: true,+ alpha: true,+ preserveDrawingBuffer: true,+ });+ if (!gl) {+ throw createWebGL2ContextError('gridlines effect');+ }++ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);++ const vs = compileShader(gl, gl.VERTEX_SHADER, GRIDLINES_VS);+ const fs = compileShader(gl, gl.FRAGMENT_SHADER, GRIDLINES_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);++ const colorCanvas = document.createElement('canvas');+ colorCanvas.width = 1;+ colorCanvas.height = 1;+ const colorCtx = colorCanvas.getContext('2d', {willReadFrequently: true});+ if (!colorCtx) {+ throw new Error('Failed to acquire 2D context for color parsing');+ }++ return {+ gl,+ program,+ vao,+ vbo,+ texture,+ uniforms: {+ uSource: gl.getUniformLocation(program, 'uSource'),+ uResolution: gl.getUniformLocation(program, 'uResolution'),+ uGridSize: gl.getUniformLocation(program, 'uGridSize'),+ uLineWidth: gl.getUniformLocation(program, 'uLineWidth'),+ uLineColor: gl.getUniformLocation(program, 'uLineColor'),+ uBackgroundColor: gl.getUniformLocation(program, 'uBackgroundColor'),+ uRotation: gl.getUniformLocation(program, 'uRotation'),+ uRotationX: gl.getUniformLocation(program, 'uRotationX'),+ uRotationY: gl.getUniformLocation(program, 'uRotationY'),+ uPerspective: gl.getUniformLocation(program, 'uPerspective'),+ uOffset: gl.getUniformLocation(program, 'uOffset'),+ uMaskToSourceAlpha: gl.getUniformLocation(+ program,+ 'uMaskToSourceAlpha',+ ),+ },+ colorCtx,+ cachedLineColorStr: '',+ cachedLineColorRgba: [255, 255, 255, 255],+ cachedBackgroundColorStr: '',+ cachedBackgroundColorRgba: [0, 0, 0, 0],+ };+ },+ apply: ({source, width, height, params, state, flipSourceY}) => {+ const r = resolve(params);+ const {gl, program, vao, texture, uniforms} = state;++ if (state.cachedLineColorStr !== r.lineColor) {+ state.cachedLineColorStr = r.lineColor;+ state.cachedLineColorRgba = parseColorRgba(state.colorCtx, r.lineColor);+ }++ if (state.cachedBackgroundColorStr !== r.backgroundColor) {+ state.cachedBackgroundColorStr = r.backgroundColor;+ state.cachedBackgroundColorRgba = parseColorRgba(+ state.colorCtx,+ r.backgroundColor,+ );+ }++ const [lineR, lineG, lineB, lineA] = rgbaToUniform(+ state.cachedLineColorRgba,+ );+ const [bgR, bgG, bgB, bgA] = rgbaToUniform(state.cachedBackgroundColorRgba);++ gl.viewport(0, 0, width, height);+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);+ 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 (uniforms.uSource) gl.uniform1i(uniforms.uSource, 0);+ if (uniforms.uResolution) gl.uniform2f(uniforms.uResolution, width, height);+ if (uniforms.uGridSize) gl.uniform1f(uniforms.uGridSize, r.gridSize);+ if (uniforms.uLineWidth) gl.uniform1f(uniforms.uLineWidth, r.lineWidth);+ if (uniforms.uLineColor)+ gl.uniform4f(uniforms.uLineColor, lineR, lineG, lineB, lineA);+ if (uniforms.uBackgroundColor)+ gl.uniform4f(uniforms.uBackgroundColor, bgR, bgG, bgB, bgA);+ if (uniforms.uRotation)+ gl.uniform1f(uniforms.uRotation, (r.rotation * Math.PI) / 180);+ if (uniforms.uRotationX)+ gl.uniform1f(uniforms.uRotationX, (r.rotationX * Math.PI) / 180);+ if (uniforms.uRotationY)+ gl.uniform1f(uniforms.uRotationY, (r.rotationY * Math.PI) / 180);+ if (uniforms.uPerspective)+ gl.uniform1f(uniforms.uPerspective, r.perspective);+ if (uniforms.uOffset) gl.uniform2f(uniforms.uOffset, r.offsetX, r.offsetY);+ if (uniforms.uMaskToSourceAlpha)+ gl.uniform1i(uniforms.uMaskToSourceAlpha, r.maskToSourceAlpha ? 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: gridlinesSchema,+ validateParams: validateGridlinesParams,+});diff --git a/packages/effects/src/index.ts b/packages/effects/src/index.tsindex 1724310856..6e691b2c35 100644--- a/packages/effects/src/index.ts+++ b/packages/effects/src/index.ts@@ -1,4 +1,5 @@export {checkerboard, type CheckerboardParams} from './checkerboard.js';export {pattern, type PatternOrigin, type PatternParams} from './pattern.js';export {rings, type RingsCenter, type RingsParams} from './rings.js';+export {gridlines, type GridlinesParams} from './gridlines.js';export {zigzag, type ZigzagDirection, type ZigzagParams} from './zigzag.js';diff --git a/packages/effects/src/pixelate.ts b/packages/effects/src/pixelate.tsindex 01ca91bce1..01e238f9b4 100644--- a/packages/effects/src/pixelate.ts+++ b/packages/effects/src/pixelate.ts@@ -51,9 +51,9 @@ type PixelateState = {const VERTEX_SHADER = /* glsl */ `#version 300 es-in vec2 aPos;-in vec2 aUv;-out vec2 vUv;+in vec2 aPos;+in vec2 aUv;+out vec2 vUv;void main() {vUv = aUv;diff --git a/packages/effects/src/test/effect-params.test.ts b/packages/effects/src/test/effect-params.test.tsindex f552885374..598bf80d98 100644--- a/packages/effects/src/test/effect-params.test.ts+++ b/packages/effects/src/test/effect-params.test.ts@@ -16,6 +16,7 @@ import {evolve} from '../evolve.js';import {fisheye} from '../fisheye/index.js';import {glow} from '../glow/index.js';import {grayscale} from '../grayscale.js';+import {gridlines} from '../gridlines.js';import {halftoneLinearGradient} from '../halftone-linear-gradient.js';import {halftone} from '../halftone.js';import {hue} from '../hue.js';@@ -120,6 +121,9 @@ test('@remotion/effects expose documentation links', () => {expect(grayscale().definition.documentationLink).toBe('https://www.remotion.dev/docs/effects/grayscale',);+ expect(gridlines().definition.documentationLink).toBe(+ 'https://www.remotion.dev/docs/effects/gridlines',+ );expect(halftone().definition.documentationLink).toBe('https://www.remotion.dev/docs/effects/halftone',);@@ -230,6 +234,7 @@ test('@remotion/effects expose API names as Studio labels', () => {expect(fisheye().definition.label).toBe('fisheye()');expect(glow().definition.label).toBe('glow()');expect(grayscale().definition.label).toBe('grayscale()');+ expect(gridlines().definition.label).toBe('gridlines()');expect(halftone().definition.label).toBe('halftone()');expect(halftoneLinearGradient().definition.label).toBe('halftoneLinearGradient()',@@ -1571,6 +1576,99 @@ test('contourLines() parameters produce distinct effect keys', () => {).toBe(12);});+test('gridlines() accepts default params', () => {+ expect(() => gridlines()).not.toThrow();+});++test('gridlines() rejects non-finite grid size', () => {+ expect(() => gridlines({gridSize: Number.NaN})).toThrow(+ '"gridSize" must be a finite number',+ );+});++test('gridlines() rejects non-positive grid size', () => {+ expect(() => gridlines({gridSize: 0})).toThrow(+ '"gridSize" must be greater than 0',+ );+});++test('gridlines() rejects negative line width', () => {+ expect(() => gridlines({lineWidth: -1})).toThrow(+ '"lineWidth" must be greater than or equal to 0',+ );+});++test('gridlines() rejects invalid colors', () => {+ expect(() => gridlines({lineColor: ''})).toThrow(+ '"lineColor" must be a non-empty string',+ );+ expect(() => gridlines({backgroundColor: ''})).toThrow(+ '"backgroundColor" must be a non-empty string',+ );+});++test('gridlines() rejects non-finite transform params', () => {+ expect(() => gridlines({rotation: Number.NaN})).toThrow(+ '"rotation" must be a finite number',+ );+ expect(() => gridlines({rotationX: Number.NaN})).toThrow(+ '"rotationX" must be a finite number',+ );+ expect(() => gridlines({rotationY: Number.NaN})).toThrow(+ '"rotationY" must be a finite number',+ );+ expect(() => gridlines({perspective: Number.NaN})).toThrow(+ '"perspective" must be a finite number',+ );+ expect(() => gridlines({perspective: -1})).toThrow(+ '"perspective" must be greater than or equal to 0',+ );+ expect(() => gridlines({offsetX: Number.NaN})).toThrow(+ '"offsetX" must be a finite number',+ );+ expect(() => gridlines({offsetY: Number.NaN})).toThrow(+ '"offsetY" must be a finite number',+ );+});++test('gridlines() rejects non-boolean maskToSourceAlpha', () => {+ expect(() =>+ gridlines({maskToSourceAlpha: 'yes' as unknown as boolean}),+ ).toThrow('"maskToSourceAlpha" must be a boolean');+});++test('gridlines() parameters produce distinct effect keys', () => {+ const defaultGrid = gridlines();+ const widerGrid = gridlines({gridSize: 80});+ const thicker = gridlines({lineWidth: 6});+ const colored = gridlines({lineColor: '#0b84f3'});+ const background = gridlines({backgroundColor: '#101828'});+ const rotated = gridlines({rotation: 30});+ const rotatedX = gridlines({rotationX: 68});+ const rotatedY = gridlines({rotationY: 20});+ const perspective = gridlines({perspective: 900});+ const shiftedX = gridlines({offsetX: 12});+ const shiftedY = gridlines({offsetY: 12});+ const masked = gridlines({maskToSourceAlpha: true});++ expect(+ new Set([+ defaultGrid.effectKey,+ widerGrid.effectKey,+ thicker.effectKey,+ colored.effectKey,+ background.effectKey,+ rotated.effectKey,+ rotatedX.effectKey,+ rotatedY.effectKey,+ perspective.effectKey,+ shiftedX.effectKey,+ shiftedY.effectKey,+ masked.effectKey,+ ]).size,+ ).toBe(12);+});+test('invert() accepts default params', () => {expect(() => invert()).not.toThrow();});diff --git a/packages/skills/skills/remotion/SKILL.md b/packages/skills/skills/remotion/SKILL.mdindex d189abff6f..98c44d26ae 100644--- a/packages/skills/skills/remotion/SKILL.md+++ b/packages/skills/skills/remotion/SKILL.md@@ -260,7 +260,7 @@ When creating a visual effect, prefer: 1. normal Remotion/HTML/CSS/SVG/filter/blFor light leak overlays, see [rules/light-leaks.md](rules/light-leaks.md). Docs: https://www.remotion.dev/docs/effects-Available effects: `brightness()`, `contrast()`, `colorKey()`, `duotone()`, `grayscale()`, `hue()`, `invert()`, `saturation()`, `tint()`, `thermalVision()`, `blur()`, `linearProgressiveBlur()`, `zoomBlur()`, `dropShadow()`, `glow()`, `evolve()`, `mirror()`, `scale()`, `uvTranslate()`, `xyTranslate()`, `barrelDistortion()`, `chromaticAberration()`, `fisheye()`, `wave()`, `burlap()`, `emboss()`, `dotGrid()`, `halftone()`, `noise()`, `noiseDisplacement()`, `pattern()`, `pixelate()`, `pixelDissolve()`, `scanlines()`, `speckle()`, `shine()`, `shrinkwrap()`, `vignette()`, `contourLines()`, `checkerboard()`, `halftoneLinearGradient()`, `whiteNoise()`, `tvSignalOff()`, `lines()`, `rings()`, `waves()`, `zigzag()`, `lightLeak()`, `starburst()`.+Available effects: `brightness()`, `contrast()`, `colorKey()`, `duotone()`, `grayscale()`, `hue()`, `invert()`, `saturation()`, `tint()`, `thermalVision()`, `blur()`, `linearProgressiveBlur()`, `zoomBlur()`, `dropShadow()`, `glow()`, `evolve()`, `mirror()`, `scale()`, `uvTranslate()`, `xyTranslate()`, `barrelDistortion()`, `chromaticAberration()`, `fisheye()`, `wave()`, `burlap()`, `emboss()`, `dotGrid()`, `halftone()`, `noise()`, `noiseDisplacement()`, `pattern()`, `pixelate()`, `pixelDissolve()`, `scanlines()`, `speckle()`, `shine()`, `shrinkwrap()`, `vignette()`, `contourLines()`, `checkerboard()`, `halftoneLinearGradient()`, `gridlines()`, `whiteNoise()`, `tvSignalOff()`, `lines()`, `rings()`, `waves()`, `zigzag()`, `lightLeak()`, `starburst()`.## 3D contentdiff --git a/packages/studio-shared/src/effect-catalog.ts b/packages/studio-shared/src/effect-catalog.tsindex 0f009e4fb9..87cdc2b7cf 100644--- a/packages/studio-shared/src/effect-catalog.ts+++ b/packages/studio-shared/src/effect-catalog.ts@@ -559,6 +559,17 @@ export const EFFECT_CATALOG: readonly EffectCatalogItem[] = [config: {},},},+ {+ id: 'effects-gridlines',+ category: 'Generate',+ label: 'gridlines()',+ description: 'Procedural grid pattern effect',+ effect: {+ name: 'gridlines',+ importPath: '@remotion/effects/gridlines',+ config: {},+ },+ },{id: 'effects-white-noise',category: 'Generate',