Skip to content

🎥 Make videos programmatically with React

`@remotion/effects`: Add contourLines effect (#8411)

Jonny Burger180c309b0c34
diff --git a/packages/docs/components/effects-demos/registry.ts b/packages/docs/components/effects-demos/registry.ts
index fda2e14ccc..c69c645a91 100644
--- a/packages/docs/components/effects-demos/registry.ts
+++ b/packages/docs/components/effects-demos/registry.ts
@@ -4,6 +4,7 @@ import {brightness} from '@remotion/effects/brightness';
import {chromaticAberration} from '@remotion/effects/chromatic-aberration';
import {colorKey} from '@remotion/effects/color-key';
import {contrast} from '@remotion/effects/contrast';
+import {contourLines} from '@remotion/effects/contour-lines';
import {dotGrid} from '@remotion/effects/dot-grid';
import {dropShadow} from '@remotion/effects/drop-shadow';
import {duotone} from '@remotion/effects/duotone';
@@ -44,6 +45,7 @@ import {EffectsBrightnessPreview} from '../effects/effects-brightness-preview';
import {EffectsChromaticAberrationPreview} from '../effects/effects-chromatic-aberration-preview';
import {EffectsColorKeyPreview} from '../effects/effects-color-key-preview';
import {EffectsContrastPreview} from '../effects/effects-contrast-preview';
+import {EffectsContourLinesPreview} from '../effects/effects-contour-lines-preview';
import {EffectsDotGridPreview} from '../effects/effects-dot-grid-preview';
import {EffectsDropShadowPreview} from '../effects/effects-drop-shadow-preview';
import {EffectsDuotonePreview} from '../effects/effects-duotone-preview';
@@ -275,6 +277,14 @@ export const effectsDemos: EffectsDemoType[] = [
comp: EffectsLinesPreview,
schema: lines().definition.schema,
},
+ {
+ ...defaults,
+ id: 'effects-contour-lines',
+ effectName: 'contourLines',
+ effectImportPath: '@remotion/effects/contour-lines',
+ comp: EffectsContourLinesPreview,
+ schema: contourLines().definition.schema,
+ },
{
...defaults,
id: 'effects-rings',
diff --git a/packages/docs/components/effects/effects-contour-lines-preview.tsx b/packages/docs/components/effects/effects-contour-lines-preview.tsx
new file mode 100644
index 0000000000..3eafd81363
--- /dev/null
+++ b/packages/docs/components/effects/effects-contour-lines-preview.tsx
@@ -0,0 +1,63 @@
+import {contourLines} from '@remotion/effects/contour-lines';
+import React from 'react';
+import {AbsoluteFill, CanvasImage, Solid} from 'remotion';
+import {EFFECTS_PREVIEW_IMAGE_SRC} from './effects-preview-image';
+
+export const EffectsContourLinesPreview: React.FC<{
+ readonly lineColor: string;
+ readonly lineWidth: number;
+ readonly spacing: number;
+ readonly scale: number;
+ readonly complexity: number;
+ readonly smoothness: number;
+ readonly seed: number;
+ readonly offsetX: number;
+ readonly offsetY: number;
+ readonly opacity: number;
+ readonly maskToSourceAlpha: boolean;
+}> = ({
+ lineColor,
+ lineWidth,
+ spacing,
+ scale,
+ complexity,
+ smoothness,
+ seed,
+ offsetX,
+ offsetY,
+ opacity,
+ maskToSourceAlpha,
+}) => {
+ return (
+ <AbsoluteFill>
+ <CanvasImage
+ src={EFFECTS_PREVIEW_IMAGE_SRC}
+ width={1280}
+ height={720}
+ fit="cover"
+ style={{position: 'absolute', zIndex: 0}}
+ />
+ <Solid
+ color="transparent"
+ width={1280}
+ height={720}
+ style={{position: 'absolute', zIndex: 1}}
+ effects={[
+ contourLines({
+ lineColor,
+ lineWidth,
+ spacing,
+ scale,
+ complexity,
+ smoothness,
+ seed,
+ offsetX,
+ offsetY,
+ opacity,
+ maskToSourceAlpha,
+ }),
+ ]}
+ />
+ </AbsoluteFill>
+ );
+};
diff --git a/packages/docs/docs/effects/contour-lines.mdx b/packages/docs/docs/effects/contour-lines.mdx
new file mode 100644
index 0000000000..891a99e7b6
--- /dev/null
+++ b/packages/docs/docs/effects/contour-lines.mdx
@@ -0,0 +1,145 @@
+---
+image: /generated/articles-docs-effects-contour-lines.png
+slug: /effects/contour-lines
+title: contourLines()
+sidebar_label: contourLines()
+crumb: '@remotion/effects'
+---
+
+# contourLines()<AvailableFrom v="4.0.476" />
+
+_Part of the [`@remotion/effects`](/docs/effects/api) package._
+
+Adds a deterministic topographic contour-line overlay to canvas-based components such as [`<Video>`](/docs/media/video), [`<HtmlInCanvas>`](/docs/remotion/html-in-canvas), [`<CanvasImage>`](/docs/canvasimage) and [`<Solid>`](/docs/solid).
+
+The effect renders static procedural linework. Animate its parameters, such as `offsetX`, `offsetY` or `scale`, to move or morph the pattern.
+
+## Preview
+
+<EffectsDemo type="effects-contour-lines" />
+
+## Example
+
+```tsx twoslash title="MyComp.tsx"
+import {contourLines} from '@remotion/effects/contour-lines';
+import {
+ AbsoluteFill,
+ CanvasImage,
+ staticFile,
+ useCurrentFrame,
+} from 'remotion';
+
+export const MyComp: React.FC = () => {
+ const frame = useCurrentFrame();
+
+ return (
+ <AbsoluteFill>
+ <CanvasImage
+ src={staticFile('image.png')}
+ width={1280}
+ height={720}
+ fit="cover"
+ effects={[
+ contourLines({
+ lineColor: 'rgba(255, 255, 255, 0.75)',
+ lineWidth: 1.4,
+ spacing: 36,
+ scale: 220,
+ complexity: 0.7,
+ smoothness: 0.75,
+ seed: 2,
+ offsetX: frame * 0.4,
+ offsetY: frame * 0.2,
+ }),
+ ]}
+ />
+ </AbsoluteFill>
+ );
+};
+```
+
+## API
+
+Pass an object with the following properties. You can also call `contourLines()` without arguments.
+
+### `lineColor?`
+
+Color of the contour lines. Defaults to `'#ffffff'`.
+
+Use an alpha channel in the color string, or use [`opacity`](#opacity), to make the overlay more subtle.
+
+### `lineWidth?`
+
+Width of each contour line in pixels. Defaults to `1.5`. Must be greater than `0`.
+
+### `spacing?`
+
+Distance between contour height levels in pixels. Defaults to `36`. Must be greater than `0`.
+
+Lower values create denser contour lines.
+
+### `scale?`
+
+Size of the generated terrain features in pixels. Defaults to `220`. Must be greater than `0`.
+
+Higher values create larger hills and wider contour shapes.
+
+### `complexity?`
+
+Amount of terrain detail from `0` to `1`. Defaults to `0.65`.
+
+Lower values create smoother contours. Higher values add more irregular detail.
+
+### `smoothness?`
+
+Smooths the contour curves from `0` to `1`. Defaults to `0.55`.
+
+Higher values reduce small wiggles while preserving the larger terrain shapes.
+
+### `seed?`
+
+Seed for the deterministic contour field. Defaults to `0`.
+
+Change it to get a different static pattern.
+
+### `offsetX?`
+
+Horizontal offset in pixels. Defaults to `0`.
+
+Use this to align the contour field with other layers, or pass a frame-based value to move the linework.
+
+### `offsetY?`
+
+Vertical offset in pixels. Defaults to `0`.
+
+Use this to align the contour field with other layers, or pass a frame-based value to move the linework.
+
+### `opacity?`
+
+Multiplies the alpha channel of [`lineColor`](#linecolor). Defaults to `1`.
+
+Must be between `0` and `1`.
+
+### `maskToSourceAlpha?`
+
+Masks the generated contour lines to the source alpha channel. Defaults to `false`.
+
+Set this to `true` to prevent the line pattern from appearing in fully transparent source pixels.
+
+This has no visible effect on fully opaque sources.
+
+### `disabled?`
+
+When `true`, the effect is skipped. Defaults to `false`.
+
+## Requirements
+
+`contourLines()` 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)
+- [`rings()`](/docs/effects/rings)
+- [`noise()`](/docs/effects/noise)
+- [Source code for this effect](https://github.com/remotion-dev/remotion/blob/main/packages/effects/src/contour-lines.ts)
diff --git a/packages/docs/docs/effects/table-of-contents.tsx b/packages/docs/docs/effects/table-of-contents.tsx
index 5d116040ee..78fadd7f61 100644
--- a/packages/docs/docs/effects/table-of-contents.tsx
+++ b/packages/docs/docs/effects/table-of-contents.tsx
@@ -277,6 +277,13 @@ const categories: {
{
title: 'Generate',
effects: [
+ {
+ link: '/docs/effects/contour-lines',
+ preview: '/img/effects-contour-lines-preview.png',
+ alt: 'contour lines effect preview',
+ name: 'contourLines()',
+ description: 'Topographic line overlay effect',
+ },
{
link: '/docs/effects/halftone-linear-gradient',
preview: '/img/effects-halftone-linear-gradient-preview.png',
diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.ts
index 9c9779e126..37f23ca5eb 100644
--- a/packages/docs/sidebars.ts
+++ b/packages/docs/sidebars.ts
@@ -276,6 +276,7 @@ const sidebars: SidebarsConfig = {
'effects/chromatic-aberration',
'effects/color-key',
'effects/contrast',
+ 'effects/contour-lines',
'effects/dot-grid',
'effects/drop-shadow',
'effects/duotone',
diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.ts
index f9072d2f4d..721322b8d8 100644
--- a/packages/docs/src/data/articles.ts
+++ b/packages/docs/src/data/articles.ts
@@ -1772,6 +1772,15 @@ export const articles = [
noAi: false,
slug: 'effects/color-key',
},
+ {
+ id: 'effects/contour-lines',
+ title: 'contourLines()',
+ relativePath: 'docs/effects/contour-lines.mdx',
+ compId: 'articles-docs-effects-contour-lines',
+ crumb: '@remotion/effects',
+ noAi: false,
+ slug: 'effects/contour-lines',
+ },
{
id: 'effects/contrast',
title: 'contrast()',
diff --git a/packages/docs/src/remotion/Root.tsx b/packages/docs/src/remotion/Root.tsx
index b839e91c06..892556ec62 100644
--- a/packages/docs/src/remotion/Root.tsx
+++ b/packages/docs/src/remotion/Root.tsx
@@ -7,6 +7,7 @@ import {EffectsBlurPreview} from '../../components/effects/effects-blur-preview'
import {EffectsBrightnessPreview} from '../../components/effects/effects-brightness-preview';
import {EffectsChromaticAberrationPreview} from '../../components/effects/effects-chromatic-aberration-preview';
import {EffectsColorKeyPreview} from '../../components/effects/effects-color-key-preview';
+import {EffectsContourLinesPreview} from '../../components/effects/effects-contour-lines-preview';
import {EffectsContrastPreview} from '../../components/effects/effects-contrast-preview';
import {EffectsDotGridPreview} from '../../components/effects/effects-dot-grid-preview';
import {EffectsDropShadowPreview} from '../../components/effects/effects-drop-shadow-preview';
@@ -464,6 +465,25 @@ export const RemotionRoot: React.FC = () => {
offset: 0,
}}
/>
+ <Still
+ id="effects-contour-lines-preview"
+ component={EffectsContourLinesPreview}
+ width={1280}
+ height={720}
+ defaultProps={{
+ lineColor: '#ffffff',
+ lineWidth: 1.1,
+ spacing: 36,
+ scale: 220,
+ complexity: 0.7,
+ smoothness: 0.75,
+ seed: 2,
+ offsetX: 0,
+ offsetY: 0,
+ opacity: 0.65,
+ maskToSourceAlpha: false,
+ }}
+ />
<Still
id="effects-rings-preview"
component={EffectsRingsPreview}
diff --git a/packages/docs/static/generated/articles-docs-effects-contour-lines.png b/packages/docs/static/generated/articles-docs-effects-contour-lines.png
new file mode 100644
index 0000000000..8001fa3a9c
Binary files /dev/null and b/packages/docs/static/generated/articles-docs-effects-contour-lines.png differ
diff --git a/packages/docs/static/img/effects-contour-lines-preview.png b/packages/docs/static/img/effects-contour-lines-preview.png
new file mode 100644
index 0000000000..a6efdf596d
Binary files /dev/null and b/packages/docs/static/img/effects-contour-lines-preview.png differ
diff --git a/packages/effects/bundle.ts b/packages/effects/bundle.ts
index f167c89087..2b7c64fbdc 100644
--- a/packages/effects/bundle.ts
+++ b/packages/effects/bundle.ts
@@ -13,6 +13,7 @@ const effectEntrypoints = [
'src/color-key.ts',
'src/brightness.ts',
'src/contrast.ts',
+ 'src/contour-lines.ts',
'src/drop-shadow.ts',
'src/duotone.ts',
'src/evolve.ts',
diff --git a/packages/effects/package.json b/packages/effects/package.json
index 1d7f5b2407..d7c17488b1 100644
--- a/packages/effects/package.json
+++ b/packages/effects/package.json
@@ -64,6 +64,11 @@
"module": "./dist/esm/contrast.mjs",
"import": "./dist/esm/contrast.mjs"
},
+ "./contour-lines": {
+ "types": "./dist/contour-lines.d.ts",
+ "module": "./dist/esm/contour-lines.mjs",
+ "import": "./dist/esm/contour-lines.mjs"
+ },
"./drop-shadow": {
"types": "./dist/drop-shadow.d.ts",
"module": "./dist/esm/drop-shadow.mjs",
@@ -246,6 +251,9 @@
"contrast": [
"dist/contrast.d.ts"
],
+ "contour-lines": [
+ "dist/contour-lines.d.ts"
+ ],
"drop-shadow": [
"dist/drop-shadow.d.ts"
],
diff --git a/packages/effects/src/contour-lines.ts b/packages/effects/src/contour-lines.ts
new file mode 100644
index 0000000000..5929ce3ac5
--- /dev/null
+++ b/packages/effects/src/contour-lines.ts
@@ -0,0 +1,579 @@
+import type {SequenceSchema} from 'remotion';
+import {Internals} from 'remotion';
+import {
+ assertOptionalFiniteNumber,
+ parseColorRgba,
+ validateUnitInterval,
+ type ParsedColorRgba,
+} from './color-utils.js';
+import {
+ assertEffectParamsObject,
+ assertOptionalBoolean,
+ assertOptionalColor,
+} from './validate-effect-param.js';
+
+const {createEffect, createWebGL2ContextError} = Internals;
+
+const DEFAULT_LINE_COLOR = '#ffffff' as const;
+const DEFAULT_LINE_WIDTH = 1.5 as const;
+const DEFAULT_SPACING = 36 as const;
+const DEFAULT_SCALE = 220 as const;
+const DEFAULT_COMPLEXITY = 0.65 as const;
+const DEFAULT_SMOOTHNESS = 0.55 as const;
+const DEFAULT_SEED = 0 as const;
+const DEFAULT_OFFSET_X = 0 as const;
+const DEFAULT_OFFSET_Y = 0 as const;
+const DEFAULT_OPACITY = 1 as const;
+const DEFAULT_MASK_TO_SOURCE_ALPHA = false as const;
+
+export const contourLinesSchema = {
+ lineColor: {
+ type: 'color',
+ default: DEFAULT_LINE_COLOR,
+ description: 'Line color',
+ },
+ lineWidth: {
+ type: 'number',
+ min: 0.1,
+ max: 20,
+ step: 0.1,
+ default: DEFAULT_LINE_WIDTH,
+ description: 'Line width',
+ hiddenFromList: false,
+ },
+ spacing: {
+ type: 'number',
+ min: 1,
+ max: 200,
+ step: 1,
+ default: DEFAULT_SPACING,
+ description: 'Spacing',
+ hiddenFromList: false,
+ },
+ scale: {
+ type: 'number',
+ min: 20,
+ max: 1000,
+ step: 1,
+ default: DEFAULT_SCALE,
+ description: 'Scale',
+ hiddenFromList: false,
+ },
+ complexity: {
+ type: 'number',
+ min: 0,
+ max: 1,
+ step: 0.01,
+ default: DEFAULT_COMPLEXITY,
+ description: 'Complexity',
+ hiddenFromList: false,
+ },
+ smoothness: {
+ type: 'number',
+ min: 0,
+ max: 1,
+ step: 0.01,
+ default: DEFAULT_SMOOTHNESS,
+ description: 'Smoothness',
+ hiddenFromList: false,
+ },
+ seed: {
+ type: 'number',
+ step: 1,
+ default: DEFAULT_SEED,
+ description: 'Seed',
+ hiddenFromList: false,
+ },
+ offsetX: {
+ type: 'number',
+ step: 0.1,
+ default: DEFAULT_OFFSET_X,
+ description: 'Offset X',
+ hiddenFromList: false,
+ },
+ offsetY: {
+ type: 'number',
+ step: 0.1,
+ default: DEFAULT_OFFSET_Y,
+ description: 'Offset Y',
+ hiddenFromList: false,
+ },
+ opacity: {
+ type: 'number',
+ min: 0,
+ max: 1,
+ step: 0.01,
+ default: DEFAULT_OPACITY,
+ description: 'Opacity',
+ hiddenFromList: false,
+ },
+ maskToSourceAlpha: {
+ type: 'boolean',
+ default: DEFAULT_MASK_TO_SOURCE_ALPHA,
+ description: 'Mask to source alpha',
+ },
+} as const satisfies SequenceSchema;
+
+export type ContourLinesParams = {
+ /** Color of the contour lines. Defaults to `#ffffff`. */
+ readonly lineColor?: string;
+ /** Width of each contour line in pixels. Defaults to `1.5`. */
+ readonly lineWidth?: number;
+ /** Distance between contour height levels in pixels. Defaults to `36`. */
+ readonly spacing?: number;
+ /** Size of the generated terrain features in pixels. Defaults to `220`. */
+ readonly scale?: number;
+ /** Amount of terrain detail from `0` to `1`. Defaults to `0.65`. */
+ readonly complexity?: number;
+ /** Smooths the contour curves from `0` to `1`. Defaults to `0.55`. */
+ readonly smoothness?: number;
+ /** Deterministic seed for the contour field. Defaults to `0`. */
+ readonly seed?: number;
+ /** Horizontal offset in pixels. Defaults to `0`. */
+ readonly offsetX?: number;
+ /** Vertical offset in pixels. Defaults to `0`. */
+ readonly offsetY?: number;
+ /** Multiplies the alpha channel of `lineColor`. Defaults to `1`. */
+ readonly opacity?: number;
+ /** Masks the generated contour lines to the source alpha channel. Defaults to `false`. */
+ readonly maskToSourceAlpha?: boolean;
+};
+
+type ContourLinesResolved = {
+ lineColor: string;
+ lineWidth: number;
+ spacing: number;
+ scale: number;
+ complexity: number;
+ smoothness: number;
+ seed: number;
+ offsetX: number;
+ offsetY: number;
+ opacity: number;
+ maskToSourceAlpha: boolean;
+};
+
+type ContourLinesState = {
+ readonly gl: WebGL2RenderingContext;
+ readonly program: WebGLProgram;
+ readonly vao: WebGLVertexArrayObject;
+ readonly vbo: WebGLBuffer;
+ readonly sourceTexture: WebGLTexture;
+ readonly colorCtx: CanvasRenderingContext2D;
+ readonly uniforms: {
+ readonly uSource: WebGLUniformLocation | null;
+ readonly uResolution: WebGLUniformLocation | null;
+ readonly uLineColor: WebGLUniformLocation | null;
+ readonly uLineWidth: WebGLUniformLocation | null;
+ readonly uSpacing: WebGLUniformLocation | null;
+ readonly uScale: WebGLUniformLocation | null;
+ readonly uComplexity: WebGLUniformLocation | null;
+ readonly uSmoothness: WebGLUniformLocation | null;
+ readonly uSeed: WebGLUniformLocation | null;
+ readonly uOffset: WebGLUniformLocation | null;
+ readonly uOpacity: WebGLUniformLocation | null;
+ readonly uMaskToSourceAlpha: WebGLUniformLocation | null;
+ };
+ cachedLineColor: string;
+ cachedLineColorRgba: ParsedColorRgba;
+};
+
+const resolve = (p: ContourLinesParams): ContourLinesResolved => ({
+ lineColor: p.lineColor ?? DEFAULT_LINE_COLOR,
+ lineWidth: p.lineWidth ?? DEFAULT_LINE_WIDTH,
+ spacing: p.spacing ?? DEFAULT_SPACING,
+ scale: p.scale ?? DEFAULT_SCALE,
+ complexity: p.complexity ?? DEFAULT_COMPLEXITY,
+ smoothness: p.smoothness ?? DEFAULT_SMOOTHNESS,
+ seed: p.seed ?? DEFAULT_SEED,
+ offsetX: p.offsetX ?? DEFAULT_OFFSET_X,
+ offsetY: p.offsetY ?? DEFAULT_OFFSET_Y,
+ opacity: p.opacity ?? DEFAULT_OPACITY,
+ 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 validateContourLinesParams = (params: ContourLinesParams): void => {
+ assertEffectParamsObject(params, 'Contour lines');
+ assertOptionalColor(params.lineColor, 'lineColor');
+ assertOptionalFiniteNumber(params.lineWidth, 'lineWidth');
+ assertOptionalFiniteNumber(params.spacing, 'spacing');
+ assertOptionalFiniteNumber(params.scale, 'scale');
+ assertOptionalFiniteNumber(params.complexity, 'complexity');
+ assertOptionalFiniteNumber(params.smoothness, 'smoothness');
+ assertOptionalFiniteNumber(params.seed, 'seed');
+ assertOptionalFiniteNumber(params.offsetX, 'offsetX');
+ assertOptionalFiniteNumber(params.offsetY, 'offsetY');
+ assertOptionalFiniteNumber(params.opacity, 'opacity');
+ assertOptionalBoolean(params.maskToSourceAlpha, 'maskToSourceAlpha');
+
+ const r = resolve(params);
+ validatePositive(r.lineWidth, 'lineWidth');
+ validatePositive(r.spacing, 'spacing');
+ validatePositive(r.scale, 'scale');
+ validateUnitInterval(r.complexity, 'complexity');
+ validateUnitInterval(r.smoothness, 'smoothness');
+ validateUnitInterval(r.opacity, 'opacity');
+};
+
+const CONTOUR_LINES_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 CONTOUR_LINES_FS = /* glsl */ `#version 300 es
+precision highp float;
+
+in vec2 vUv;
+out vec4 fragColor;
+
+uniform sampler2D uSource;
+uniform vec2 uResolution;
+uniform vec4 uLineColor;
+uniform float uLineWidth;
+uniform float uSpacing;
+uniform float uScale;
+uniform float uComplexity;
+uniform float uSmoothness;
+uniform float uSeed;
+uniform vec2 uOffset;
+uniform float uOpacity;
+uniform bool uMaskToSourceAlpha;
+
+float hash(vec2 p) {
+ vec3 p3 = fract(vec3(p.xyx) * 0.1031);
+ p3 += dot(p3, p3.yzx + 33.33 + uSeed * 0.013);
+ return fract((p3.x + p3.y) * p3.z);
+}
+
+float valueNoise(vec2 p) {
+ vec2 i = floor(p);
+ vec2 f = fract(p);
+ vec2 u = f * f * f * (f * (f * 6.0 - 15.0) + 10.0);
+
+ float a = hash(i);
+ float b = hash(i + vec2(1.0, 0.0));
+ float c = hash(i + vec2(0.0, 1.0));
+ float d = hash(i + vec2(1.0, 1.0));
+
+ return mix(mix(a, b, u.x), mix(c, d, u.x), u.y);
+}
+
+float fbm(vec2 p) {
+ float value = 0.0;
+ float amplitude = 0.5;
+ float totalAmplitude = 0.0;
+ float persistence = mix(0.18, 0.58, clamp(uComplexity, 0.0, 1.0));
+ float smoothness = clamp(uSmoothness, 0.0, 1.0);
+ mat2 rotate = mat2(0.80, 0.60, -0.60, 0.80);
+
+ for (int i = 0; i < 5; i++) {
+ float octave = float(i) / 4.0;
+ float detailWeight = mix(
+ 1.0,
+ 1.0 - smoothstep(0.15, 1.0, octave),
+ smoothness
+ );
+ value += amplitude * detailWeight * valueNoise(p);
+ totalAmplitude += amplitude * detailWeight;
+ p = rotate * p * 2.04 + vec2(13.17, 7.31);
+ amplitude *= persistence;
+ }
+
+ return value / totalAmplitude;
+}
+
+void main() {
+ vec4 texColor = texture(uSource, vUv);
+ vec2 pixelPosition = vUv * uResolution + uOffset;
+ float scale = max(uScale, 0.001);
+ vec2 p = pixelPosition / scale + vec2(uSeed * 0.137, uSeed * 0.193);
+
+ float complexity = clamp(uComplexity, 0.0, 1.0);
+ float smoothness = clamp(uSmoothness, 0.0, 1.0);
+ vec2 warp = vec2(
+ fbm(p + vec2(5.2, 1.3)),
+ fbm(p + vec2(1.7, 9.2))
+ ) - 0.5;
+ float terrain = fbm(p + warp * complexity * mix(2.8, 1.2, smoothness));
+
+ float levels = max(
+ max(uResolution.x, uResolution.y) / (max(uSpacing, 0.001) * 2.0),
+ 1.0
+ );
+ float contourPosition = terrain * levels;
+ float contourFraction = fract(contourPosition);
+ float distanceToContour = min(contourFraction, 1.0 - contourFraction);
+ float derivative = max(fwidth(contourPosition), 0.0001);
+ float halfLineWidth = max(uLineWidth, 0.001) * 0.5 * derivative;
+ float coverage = 1.0 - smoothstep(
+ halfLineWidth,
+ halfLineWidth + derivative,
+ distanceToContour
+ );
+
+ float lineAlpha = uLineColor.a * uOpacity * coverage;
+ vec3 premultipliedLine = uLineColor.rgb * lineAlpha;
+
+ if (uMaskToSourceAlpha) {
+ fragColor = vec4(
+ premultipliedLine * texColor.a + texColor.rgb * (1.0 - lineAlpha),
+ texColor.a
+ );
+ return;
+ }
+
+ fragColor = vec4(
+ premultipliedLine + texColor.rgb * (1.0 - lineAlpha),
+ lineAlpha + texColor.a * (1.0 - lineAlpha)
+ );
+}
+`;
+
+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(
+ `Contour lines 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(`Contour lines program link failed: ${log ?? '(no log)'}`);
+ }
+
+ return program;
+};
+
+const createProgram = (
+ gl: WebGL2RenderingContext,
+ vertexSource: string,
+ fragmentSource: string,
+): WebGLProgram => {
+ const vs = compileShader(gl, gl.VERTEX_SHADER, vertexSource);
+ const fs = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSource);
+ const program = linkProgram(gl, vs, fs);
+ gl.deleteShader(vs);
+ gl.deleteShader(fs);
+ return program;
+};
+
+const createTexture = (gl: WebGL2RenderingContext): WebGLTexture => {
+ 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_MIN_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+ 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.bindTexture(gl.TEXTURE_2D, null);
+ return texture;
+};
+
+const setupContourLines = (target: HTMLCanvasElement): ContourLinesState => {
+ const gl = target.getContext('webgl2', {
+ premultipliedAlpha: true,
+ alpha: true,
+ preserveDrawingBuffer: true,
+ });
+ if (!gl) {
+ throw createWebGL2ContextError('contour lines effect');
+ }
+
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
+
+ const program = createProgram(gl, CONTOUR_LINES_VS, CONTOUR_LINES_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 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,
+ sourceTexture: createTexture(gl),
+ colorCtx,
+ uniforms: {
+ uSource: gl.getUniformLocation(program, 'uSource'),
+ uResolution: gl.getUniformLocation(program, 'uResolution'),
+ uLineColor: gl.getUniformLocation(program, 'uLineColor'),
+ uLineWidth: gl.getUniformLocation(program, 'uLineWidth'),
+ uSpacing: gl.getUniformLocation(program, 'uSpacing'),
+ uScale: gl.getUniformLocation(program, 'uScale'),
+ uComplexity: gl.getUniformLocation(program, 'uComplexity'),
+ uSmoothness: gl.getUniformLocation(program, 'uSmoothness'),
+ uSeed: gl.getUniformLocation(program, 'uSeed'),
+ uOffset: gl.getUniformLocation(program, 'uOffset'),
+ uOpacity: gl.getUniformLocation(program, 'uOpacity'),
+ uMaskToSourceAlpha: gl.getUniformLocation(program, 'uMaskToSourceAlpha'),
+ },
+ cachedLineColor: '',
+ cachedLineColorRgba: [255, 255, 255, 255],
+ };
+};
+
+export const contourLines = createEffect<ContourLinesParams, ContourLinesState>(
+ {
+ type: 'remotion/contour-lines',
+ label: 'contourLines()',
+ documentationLink: 'https://www.remotion.dev/docs/effects/contour-lines',
+ backend: 'webgl2',
+ calculateKey: (params) => {
+ const r = resolve(params);
+ const maskSuffix = r.maskToSourceAlpha ? '-mask-to-source-alpha' : '';
+ return `contour-lines-${r.lineColor}-${r.lineWidth}-${r.spacing}-${r.scale}-${r.complexity}-${r.smoothness}-${r.seed}-${r.offsetX}-${r.offsetY}-${r.opacity}${maskSuffix}`;
+ },
+ setup: (target) => setupContourLines(target),
+ apply: ({source, width, height, params, state, flipSourceY}) => {
+ const r = resolve(params);
+ const {gl, program, sourceTexture, uniforms, vao} = state;
+
+ if (state.cachedLineColor !== r.lineColor) {
+ state.cachedLineColor = r.lineColor;
+ state.cachedLineColorRgba = parseColorRgba(state.colorCtx, r.lineColor);
+ }
+
+ const [cr, cg, cb, ca] = state.cachedLineColorRgba;
+
+ gl.viewport(0, 0, width, height);
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+ gl.clearColor(0, 0, 0, 0);
+ gl.clear(gl.COLOR_BUFFER_BIT);
+
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, sourceTexture);
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipSourceY);
+ gl.texImage2D(
+ gl.TEXTURE_2D,
+ 0,
+ gl.RGBA,
+ gl.RGBA,
+ gl.UNSIGNED_BYTE,
+ source as TexImageSource,
+ );
+
+ gl.useProgram(program);
+ if (uniforms.uSource) gl.uniform1i(uniforms.uSource, 0);
+ if (uniforms.uResolution)
+ gl.uniform2f(uniforms.uResolution, width, height);
+ if (uniforms.uLineColor) {
+ gl.uniform4f(
+ uniforms.uLineColor,
+ cr / 255,
+ cg / 255,
+ cb / 255,
+ ca / 255,
+ );
+ }
+
+ if (uniforms.uLineWidth) gl.uniform1f(uniforms.uLineWidth, r.lineWidth);
+ if (uniforms.uSpacing) gl.uniform1f(uniforms.uSpacing, r.spacing);
+ if (uniforms.uScale) gl.uniform1f(uniforms.uScale, r.scale);
+ if (uniforms.uComplexity)
+ gl.uniform1f(uniforms.uComplexity, r.complexity);
+ if (uniforms.uSmoothness)
+ gl.uniform1f(uniforms.uSmoothness, r.smoothness);
+ if (uniforms.uSeed) gl.uniform1f(uniforms.uSeed, r.seed);
+ if (uniforms.uOffset)
+ gl.uniform2f(uniforms.uOffset, r.offsetX, r.offsetY);
+ if (uniforms.uOpacity) gl.uniform1f(uniforms.uOpacity, r.opacity);
+ if (uniforms.uMaskToSourceAlpha)
+ gl.uniform1i(uniforms.uMaskToSourceAlpha, r.maskToSourceAlpha ? 1 : 0);
+
+ gl.bindVertexArray(vao);
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
+ gl.bindVertexArray(null);
+ gl.bindTexture(gl.TEXTURE_2D, null);
+ gl.useProgram(null);
+ },
+ cleanup: ({gl, program, vao, vbo, sourceTexture}) => {
+ gl.deleteTexture(sourceTexture);
+ gl.deleteBuffer(vbo);
+ gl.deleteProgram(program);
+ gl.deleteVertexArray(vao);
+ },
+ schema: contourLinesSchema,
+ validateParams: validateContourLinesParams,
+ },
+);
diff --git a/packages/effects/src/test/effect-params.test.ts b/packages/effects/src/test/effect-params.test.ts
index cfd862522f..cd09c06b1c 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 {colorKey} from '../color-key.js';
+import {contourLines} from '../contour-lines.js';
import {contrast} from '../contrast.js';
import {dotGrid} from '../dot-grid.js';
import {dropShadow} from '../drop-shadow/index.js';
@@ -82,6 +83,9 @@ test('@remotion/effects expose documentation links', () => {
expect(contrast().definition.documentationLink).toBe(
'https://www.remotion.dev/docs/effects/contrast',
);
+ expect(contourLines().definition.documentationLink).toBe(
+ 'https://www.remotion.dev/docs/effects/contour-lines',
+ );
expect(duotone().definition.documentationLink).toBe(
'https://www.remotion.dev/docs/effects/duotone',
);
@@ -191,6 +195,7 @@ test('@remotion/effects expose API names as Studio labels', () => {
expect(colorKey().definition.label).toBe('colorKey()');
expect(brightness().definition.label).toBe('brightness()');
expect(contrast().definition.label).toBe('contrast()');
+ expect(contourLines().definition.label).toBe('contourLines()');
expect(duotone().definition.label).toBe('duotone()');
expect(evolve().definition.label).toBe('evolve()');
expect(dropShadow().definition.label).toBe('dropShadow()');
@@ -1363,6 +1368,110 @@ test('dotGrid() parameters produce distinct effect keys', () => {
).toBe(4);
});
+test('contourLines() accepts default params', () => {
+ expect(() => contourLines()).not.toThrow();
+});
+
+test('contourLines() rejects empty lineColor strings', () => {
+ expect(() => contourLines({lineColor: ''})).toThrow(
+ '"lineColor" must be a non-empty string, but got ""',
+ );
+});
+
+test('contourLines() rejects non-finite lineWidth', () => {
+ expect(() => contourLines({lineWidth: Number.NaN})).toThrow(
+ '"lineWidth" must be a finite number',
+ );
+});
+
+test('contourLines() rejects non-positive lineWidth', () => {
+ expect(() => contourLines({lineWidth: 0})).toThrow(
+ '"lineWidth" must be greater than 0',
+ );
+});
+
+test('contourLines() rejects non-positive spacing', () => {
+ expect(() => contourLines({spacing: 0})).toThrow(
+ '"spacing" must be greater than 0',
+ );
+});
+
+test('contourLines() rejects non-positive scale', () => {
+ expect(() => contourLines({scale: 0})).toThrow(
+ '"scale" must be greater than 0',
+ );
+});
+
+test('contourLines() rejects complexity outside unit range', () => {
+ expect(() => contourLines({complexity: -0.1})).toThrow(
+ '"complexity" must be >= 0',
+ );
+ expect(() => contourLines({complexity: 1.1})).toThrow(
+ '"complexity" must be <= 1',
+ );
+});
+
+test('contourLines() rejects smoothness outside unit range', () => {
+ expect(() => contourLines({smoothness: -0.1})).toThrow(
+ '"smoothness" must be >= 0',
+ );
+ expect(() => contourLines({smoothness: 1.1})).toThrow(
+ '"smoothness" must be <= 1',
+ );
+});
+
+test('contourLines() rejects non-finite offsets', () => {
+ expect(() => contourLines({offsetX: Number.NaN})).toThrow(
+ '"offsetX" must be a finite number',
+ );
+ expect(() => contourLines({offsetY: Number.NaN})).toThrow(
+ '"offsetY" must be a finite number',
+ );
+});
+
+test('contourLines() rejects opacity outside unit range', () => {
+ expect(() => contourLines({opacity: -0.1})).toThrow('"opacity" must be >= 0');
+ expect(() => contourLines({opacity: 1.1})).toThrow('"opacity" must be <= 1');
+});
+
+test('contourLines() rejects non-boolean maskToSourceAlpha', () => {
+ expect(() =>
+ contourLines({maskToSourceAlpha: 'yes' as unknown as boolean}),
+ ).toThrow('"maskToSourceAlpha" must be a boolean');
+});
+
+test('contourLines() parameters produce distinct effect keys', () => {
+ const defaults = contourLines();
+ const colored = contourLines({lineColor: '#0b84f3'});
+ const thicker = contourLines({lineWidth: 3});
+ const denser = contourLines({spacing: 12});
+ const larger = contourLines({scale: 240});
+ const simpler = contourLines({complexity: 0.2});
+ const smoother = contourLines({smoothness: 0.9});
+ const seeded = contourLines({seed: 3});
+ const shiftedX = contourLines({offsetX: 12});
+ const shiftedY = contourLines({offsetY: 12});
+ const transparent = contourLines({opacity: 0.5});
+ const masked = contourLines({maskToSourceAlpha: true});
+
+ expect(
+ new Set([
+ defaults.effectKey,
+ colored.effectKey,
+ thicker.effectKey,
+ denser.effectKey,
+ larger.effectKey,
+ simpler.effectKey,
+ smoother.effectKey,
+ seeded.effectKey,
+ shiftedX.effectKey,
+ shiftedY.effectKey,
+ transparent.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.md
index bf9b5c89cc..41033547ac 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/bl
For light leak overlays, see [rules/light-leaks.md](rules/light-leaks.md). Docs: https://www.remotion.dev/docs/effects
-Available effects: `barrelDistortion()`, `blur()`, `brightness()`, `chromaticAberration()`, `colorKey()`, `contrast()`, `dotGrid()`, `dropShadow()`, `duotone()`, `evolve()`, `fisheye()`, `glow()`, `grayscale()`, `halftone()`, `halftoneLinearGradient()`, `hue()`, `invert()`, `lightLeak()`, `linearProgressiveBlur()`, `lines()`, `mirror()`, `noise()`, `noiseDisplacement()`, `pattern()`, `pixelDissolve()`, `rings()`, `saturation()`, `scale()`, `scanlines()`, `tvSignalOff()`, `speckle()`, `shine()`, `starburst()`, `tint()`, `uvTranslate()`, `vignette()`, `wave()`, `waves()`, `whiteNoise()`, `xyTranslate()`, `zigzag()`.
+Available effects: `barrelDistortion()`, `blur()`, `brightness()`, `chromaticAberration()`, `colorKey()`, `contourLines()`, `contrast()`, `dotGrid()`, `dropShadow()`, `duotone()`, `evolve()`, `fisheye()`, `glow()`, `grayscale()`, `halftone()`, `halftoneLinearGradient()`, `hue()`, `invert()`, `lightLeak()`, `linearProgressiveBlur()`, `lines()`, `mirror()`, `noise()`, `noiseDisplacement()`, `pattern()`, `pixelDissolve()`, `rings()`, `saturation()`, `scale()`, `scanlines()`, `tvSignalOff()`, `speckle()`, `shine()`, `starburst()`, `tint()`, `uvTranslate()`, `vignette()`, `wave()`, `waves()`, `whiteNoise()`, `xyTranslate()`, `zigzag()`.
## 3D content