Skip to content

🎥 Make videos programmatically with React

`@remotion/effects`: Add paper effect (#8770)

Jonny Burger11df594fd820
diff --git a/packages/docs/components/effects-demos/registry.ts b/packages/docs/components/effects-demos/registry.ts
index f2a01b4207..bab91f9979 100644
--- a/packages/docs/components/effects-demos/registry.ts
+++ b/packages/docs/components/effects-demos/registry.ts
@@ -22,13 +22,14 @@ import {halftoneLinearGradient} from '@remotion/effects/halftone-linear-gradient
import {hue} from '@remotion/effects/hue';
import {invert} from '@remotion/effects/invert';
import {lightTrail} from '@remotion/effects/light-trail';
-import {linearGradientTint} from '@remotion/effects/linear-gradient-tint';
import {linearGradient} from '@remotion/effects/linear-gradient';
+import {linearGradientTint} from '@remotion/effects/linear-gradient-tint';
import {linearProgressiveBlur} from '@remotion/effects/linear-progressive-blur';
import {lines} from '@remotion/effects/lines';
import {mirror} from '@remotion/effects/mirror';
import {noise} from '@remotion/effects/noise';
import {noiseDisplacement} from '@remotion/effects/noise-displacement';
+import {paper} from '@remotion/effects/paper';
import {pattern} from '@remotion/effects/pattern';
import {pixelDissolve} from '@remotion/effects/pixel-dissolve';
import {pixelate} from '@remotion/effects/pixelate';
@@ -81,8 +82,8 @@ import {
EffectsLightTrailPreview,
LIGHT_TRAIL_PREVIEW_PARAMS,
} from '../effects/effects-light-trail-preview';
-import {EffectsLinearGradientTintPreview} from '../effects/effects-linear-gradient-tint-preview';
import {EffectsLinearGradientPreview} from '../effects/effects-linear-gradient-preview';
+import {EffectsLinearGradientTintPreview} from '../effects/effects-linear-gradient-tint-preview';
import {EffectsLinearProgressiveBlurPreview} from '../effects/effects-linear-progressive-blur-preview';
import {EffectsLinesPreview} from '../effects/effects-lines-preview';
import {EffectsMirrorPreview} from '../effects/effects-mirror-preview';
@@ -95,6 +96,10 @@ import {
EffectsPaletteMapPreview,
paletteMap,
} from '../effects/effects-palette-map-preview';
+import {
+ EffectsPaperPreview,
+ PAPER_PREVIEW_PARAMS,
+} from '../effects/effects-paper-preview';
import {EffectsPatternPreview} from '../effects/effects-pattern-preview';
import {EffectsPixelDissolvePreview} from '../effects/effects-pixel-dissolve-preview';
import {EffectsPixelatePreview} from '../effects/effects-pixelate-preview';
@@ -352,6 +357,15 @@ export const effectsDemos: EffectsDemoType[] = [
.schema,
initialValues: NOISE_DISPLACEMENT_PREVIEW_PARAMS,
},
+ {
+ ...defaults,
+ id: 'effects-paper',
+ effectName: 'paper',
+ effectImportPath: '@remotion/effects/paper',
+ comp: EffectsPaperPreview,
+ schema: paper().definition.schema,
+ initialValues: PAPER_PREVIEW_PARAMS,
+ },
{
...defaults,
id: 'effects-white-noise',
diff --git a/packages/docs/components/effects/effects-paper-preview.tsx b/packages/docs/components/effects/effects-paper-preview.tsx
new file mode 100644
index 0000000000..4824e4fb9a
--- /dev/null
+++ b/packages/docs/components/effects/effects-paper-preview.tsx
@@ -0,0 +1,84 @@
+import {paper} from '@remotion/effects/paper';
+import React from 'react';
+import {CanvasImage} from 'remotion';
+import {EFFECTS_PREVIEW_IMAGE_SRC} from './effects-preview-image';
+
+export const PAPER_PREVIEW_PARAMS = {
+ amount: 1,
+ colorFront: '#9fadbc',
+ colorBack: '#ffffff',
+ contrast: 0.3,
+ roughness: 0.4,
+ fiber: 0.3,
+ fiberSize: 0.2,
+ crumples: 0.3,
+ crumpleSize: 0.35,
+ folds: 0.65,
+ foldCount: 5,
+ drops: 0.2,
+ fade: 0,
+ seed: 6,
+ scale: 0.6,
+} as const;
+
+export const EffectsPaperPreview: React.FC<{
+ readonly amount: number;
+ readonly colorFront: string;
+ readonly colorBack: string;
+ readonly contrast: number;
+ readonly roughness: number;
+ readonly fiber: number;
+ readonly fiberSize: number;
+ readonly crumples: number;
+ readonly crumpleSize: number;
+ readonly folds: number;
+ readonly foldCount: number;
+ readonly drops: number;
+ readonly fade: number;
+ readonly seed: number;
+ readonly scale: number;
+}> = ({
+ amount,
+ colorFront,
+ colorBack,
+ contrast,
+ roughness,
+ fiber,
+ fiberSize,
+ crumples,
+ crumpleSize,
+ folds,
+ foldCount,
+ drops,
+ fade,
+ seed,
+ scale,
+}) => {
+ return (
+ <CanvasImage
+ src={EFFECTS_PREVIEW_IMAGE_SRC}
+ width={1280}
+ height={720}
+ fit="cover"
+ effects={[
+ paper({
+ amount,
+ colorFront,
+ colorBack,
+ contrast,
+ roughness,
+ fiber,
+ fiberSize,
+ crumples,
+ crumpleSize,
+ folds,
+ foldCount,
+ drops,
+ fade,
+ seed,
+ scale,
+ }),
+ ]}
+ />
+ );
+};
diff --git a/packages/docs/docs/effects/paper.mdx b/packages/docs/docs/effects/paper.mdx
new file mode 100644
index 0000000000..1308c8e5cd
--- /dev/null
+++ b/packages/docs/docs/effects/paper.mdx
@@ -0,0 +1,164 @@
+---
+image: /generated/articles-docs-effects-paper.png
+slug: /effects/paper
+title: paper()
+sidebar_label: paper()
+crumb: '@remotion/effects'
+---
+
+# paper()<AvailableFrom v="4.0.486" />
+
+_Part of the [`@remotion/effects`](/docs/effects/api) package._
+
+Adds a procedural paper texture 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 adds paper grain, fibers, crumples, folds and speckles while preserving the source alpha mask.
+
+Based on the open-source [Paper Shaders paper texture](https://shaders.paper.design/paper-texture), created by [uuuulala](https://github.com/uuuulala) for Paper Design.
+
+## Preview
+
+<EffectsDemo type="effects-paper" />
+
+## Example
+
+```tsx twoslash title="MyComp.tsx"
+import {paper} from '@remotion/effects/paper';
+import {AbsoluteFill, Solid} from 'remotion';
+
+export const MyComp: React.FC = () => {
+ return (
+ <AbsoluteFill>
+ <Solid
+ width={1280}
+ height={720}
+ color="#fff4d0"
+ effects={[
+ paper({
+ roughness: 0.4,
+ fiber: 0.3,
+ fiberSize: 0.2,
+ crumples: 0.3,
+ crumpleSize: 0.35,
+ folds: 0.65,
+ foldCount: 5,
+ drops: 0.2,
+ scale: 0.6,
+ seed: 6,
+ }),
+ ]}
+ />
+ </AbsoluteFill>
+ );
+};
+```
+
+## API
+
+Pass an object with the following properties. You can also call `paper()` without arguments.
+
+### `amount?`
+
+Strength of the paper texture from `0` to `1`. Defaults to `1`.
+
+Use `0` to leave the source unchanged.
+
+### `colorFront?`
+
+Light-facing paper color. Defaults to `#9fadbc`.
+
+Alpha in the color controls how strongly this color tints the paper highlights.
+
+### `colorBack?`
+
+Shadow-facing paper color. Defaults to `#ffffff`.
+
+Alpha in the color controls how strongly this color tints the paper shadows.
+
+### `contrast?`
+
+Sharpness of light and color transitions from `0` to `1`. Defaults to `0.3`.
+
+Higher values make folds and crumples more pronounced.
+
+### `roughness?`
+
+Fine pixel noise from `0` to `1`. Defaults to `0.4`.
+
+Use `0` for a smoother texture.
+
+### `fiber?`
+
+Curly fiber intensity from `0` to `1`. Defaults to `0.3`.
+
+Higher values add more visible paper strands.
+
+### `fiberSize?`
+
+Curly fiber scale from `0.01` to `1`. Defaults to `0.2`.
+
+Smaller values create finer fibers. Must be greater than `0`.
+
+### `crumples?`
+
+Cell-based crumple intensity from `0` to `1`. Defaults to `0.3`.
+
+Higher values add stronger small-scale crumple marks.
+
+### `crumpleSize?`
+
+Cell-based crumple scale from `0.01` to `1`. Defaults to `0.35`.
+
+Smaller values create tighter crumple cells. Must be greater than `0`.
+
+### `folds?`
+
+Fold lighting intensity from `0` to `1`. Defaults to `0.65`.
+
+Use `0` to remove the broader fold pattern.
+
+### `foldCount?`
+
+Number of generated folds from `0` to `15`. Defaults to `5`.
+
+Higher values create more fold lines.
+
+### `drops?`
+
+Speckle visibility from `0` to `1`. Defaults to `0.2`.
+
+Use `0` to remove the speckle pattern.
+
+### `fade?`
+
+Large-scale mask applied to the paper pattern from `0` to `1`. Defaults to `0`.
+
+Higher values make the paper details less uniform across the frame.
+
+### `seed?`
+
+Seed for the generated paper pattern from `0` to `1000`. Defaults to `6`.
+
+Change it to get a different static paper pattern.
+
+### `scale?`
+
+Scale of the generated paper texture from `0.01` to `4`. Defaults to `0.6`.
+
+Smaller values create denser paper detail. Larger values make the texture broader.
+
+### `disabled?`
+
+When `true`, the effect is skipped. Defaults to `false`.
+
+## Requirements
+
+`paper()` 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)
+- [`burlap()`](/docs/effects/burlap)
+- [`noise()`](/docs/effects/noise)
+- [Paper Shaders](https://shaders.paper.design)
+- [Source code for this effect](https://github.com/remotion-dev/remotion/blob/main/packages/effects/src/paper.ts)
diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.ts
index 80f2316519..e56c7171f7 100644
--- a/packages/docs/sidebars.ts
+++ b/packages/docs/sidebars.ts
@@ -304,6 +304,7 @@ const sidebars: SidebarsConfig = {
'effects/mirror',
'effects/noise',
'effects/noise-displacement',
+ 'effects/paper',
'effects/pattern',
'effects/pixel-dissolve',
'effects/pixelate',
diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.ts
index 496a0a8ed3..542511b79a 100644
--- a/packages/docs/src/data/articles.ts
+++ b/packages/docs/src/data/articles.ts
@@ -2024,6 +2024,15 @@ export const articles = [
noAi: false,
slug: 'effects/noise',
},
+ {
+ id: 'effects/paper',
+ title: 'paper()',
+ relativePath: 'docs/effects/paper.mdx',
+ compId: 'articles-docs-effects-paper',
+ crumb: '@remotion/effects',
+ noAi: false,
+ slug: 'effects/paper',
+ },
{
id: 'effects/pattern',
title: 'pattern()',
diff --git a/packages/docs/src/remotion/Root.tsx b/packages/docs/src/remotion/Root.tsx
index 8e8d00ea94..77b932b7c3 100644
--- a/packages/docs/src/remotion/Root.tsx
+++ b/packages/docs/src/remotion/Root.tsx
@@ -42,6 +42,10 @@ import {
NoiseDisplacementTextSource,
} from '../../components/effects/effects-noise-displacement-preview';
import {EffectsNoisePreview} from '../../components/effects/effects-noise-preview';
+import {
+ EffectsPaperPreview,
+ PAPER_PREVIEW_PARAMS,
+} from '../../components/effects/effects-paper-preview';
import {EffectsPatternPreview} from '../../components/effects/effects-pattern-preview';
import {EffectsPixelDissolvePreview} from '../../components/effects/effects-pixel-dissolve-preview';
import {EffectsPixelatePreview} from '../../components/effects/effects-pixelate-preview';
@@ -593,6 +597,13 @@ export const RemotionRoot: React.FC = () => {
height={720}
defaultProps={NOISE_DISPLACEMENT_PREVIEW_PARAMS}
/>
+ <Still
+ id="effects-paper-preview"
+ component={EffectsPaperPreview}
+ width={1280}
+ height={720}
+ defaultProps={PAPER_PREVIEW_PARAMS}
+ />
<Still
id="effects-white-noise-preview"
component={EffectsWhiteNoisePreview}
diff --git a/packages/docs/static/generated/articles-docs-effects-paper.png b/packages/docs/static/generated/articles-docs-effects-paper.png
new file mode 100644
index 0000000000..0b9ba8aa0b
Binary files /dev/null and b/packages/docs/static/generated/articles-docs-effects-paper.png differ
diff --git a/packages/docs/static/img/effects-paper-preview.png b/packages/docs/static/img/effects-paper-preview.png
new file mode 100644
index 0000000000..65eed04b64
Binary files /dev/null and b/packages/docs/static/img/effects-paper-preview.png differ
diff --git a/packages/effects/bundle.ts b/packages/effects/bundle.ts
index ff029d655b..ae3163974a 100644
--- a/packages/effects/bundle.ts
+++ b/packages/effects/bundle.ts
@@ -40,6 +40,7 @@ const effectEntrypoints = [
'src/mirror.ts',
'src/noise.ts',
'src/noise-displacement.ts',
+ 'src/paper.ts',
'src/pattern.ts',
'src/radial-progressive-blur.ts',
'src/rings.ts',
diff --git a/packages/effects/package.json b/packages/effects/package.json
index 4fa9f429e0..0a4500b5bd 100644
--- a/packages/effects/package.json
+++ b/packages/effects/package.json
@@ -199,6 +199,11 @@
"module": "./dist/esm/noise-displacement.mjs",
"import": "./dist/esm/noise-displacement.mjs"
},
+ "./paper": {
+ "types": "./dist/paper.d.ts",
+ "module": "./dist/esm/paper.mjs",
+ "import": "./dist/esm/paper.mjs"
+ },
"./pattern": {
"types": "./dist/pattern.d.ts",
"module": "./dist/esm/pattern.mjs",
@@ -402,6 +407,9 @@
"noise-displacement": [
"dist/noise-displacement.d.ts"
],
+ "paper": [
+ "dist/paper.d.ts"
+ ],
"pattern": [
"dist/pattern.d.ts"
],
diff --git a/packages/effects/src/paper.ts b/packages/effects/src/paper.ts
new file mode 100644
index 0000000000..fa313b12cd
--- /dev/null
+++ b/packages/effects/src/paper.ts
@@ -0,0 +1,975 @@
+import type {InteractivitySchema} from 'remotion';
+import {Internals} from 'remotion';
+import {
+ assertOptionalFiniteNumber,
+ parseColorRgba,
+ type ParsedColorRgba,
+ validateNonNegative,
+ validateUnitInterval,
+} from './color-utils.js';
+import {
+ assertEffectParamsObject,
+ assertOptionalColor,
+} from './validate-effect-param.js';
+
+const {createEffect, createWebGL2ContextError} = Internals;
+
+const DEFAULT_AMOUNT = 1 as const;
+const DEFAULT_COLOR_FRONT = '#9fadbc' as const;
+const DEFAULT_COLOR_BACK = '#ffffff' as const;
+const DEFAULT_CONTRAST = 0.3 as const;
+const DEFAULT_ROUGHNESS = 0.4 as const;
+const DEFAULT_FIBER = 0.3 as const;
+const DEFAULT_FIBER_SIZE = 0.2 as const;
+const DEFAULT_CRUMPLES = 0.3 as const;
+const DEFAULT_CRUMPLE_SIZE = 0.35 as const;
+const DEFAULT_FOLDS = 0.65 as const;
+const DEFAULT_FOLD_COUNT = 5 as const;
+const DEFAULT_DROPS = 0.2 as const;
+const DEFAULT_FADE = 0 as const;
+const DEFAULT_SEED = 6 as const;
+const DEFAULT_SCALE = 0.6 as const;
+const MAX_FOLD_COUNT = 15 as const;
+const MAX_SEED = 1000 as const;
+const NOISE_TEXTURE_SIZE = 256;
+
+const paperSchema = {
+ amount: {
+ type: 'number',
+ min: 0,
+ max: 1,
+ step: 0.01,
+ default: DEFAULT_AMOUNT,
+ description: 'Amount',
+ hiddenFromList: false,
+ },
+ colorFront: {
+ type: 'color',
+ default: DEFAULT_COLOR_FRONT,
+ description: 'Front color',
+ },
+ colorBack: {
+ type: 'color',
+ default: DEFAULT_COLOR_BACK,
+ description: 'Back color',
+ },
+ contrast: {
+ type: 'number',
+ min: 0,
+ max: 1,
+ step: 0.01,
+ default: DEFAULT_CONTRAST,
+ description: 'Contrast',
+ hiddenFromList: false,
+ },
+ roughness: {
+ type: 'number',
+ min: 0,
+ max: 1,
+ step: 0.01,
+ default: DEFAULT_ROUGHNESS,
+ description: 'Roughness',
+ hiddenFromList: false,
+ },
+ fiber: {
+ type: 'number',
+ min: 0,
+ max: 1,
+ step: 0.01,
+ default: DEFAULT_FIBER,
+ description: 'Fiber',
+ hiddenFromList: false,
+ },
+ fiberSize: {
+ type: 'number',
+ min: 0.01,
+ max: 1,
+ step: 0.01,
+ default: DEFAULT_FIBER_SIZE,
+ description: 'Fiber size',
+ hiddenFromList: false,
+ },
+ crumples: {
+ type: 'number',
+ min: 0,
+ max: 1,
+ step: 0.01,
+ default: DEFAULT_CRUMPLES,
+ description: 'Crumples',
+ hiddenFromList: false,
+ },
+ crumpleSize: {
+ type: 'number',
+ min: 0.01,
+ max: 1,
+ step: 0.01,
+ default: DEFAULT_CRUMPLE_SIZE,
+ description: 'Crumple size',
+ hiddenFromList: false,
+ },
+ folds: {
+ type: 'number',
+ min: 0,
+ max: 1,
+ step: 0.01,
+ default: DEFAULT_FOLDS,
+ description: 'Folds',
+ hiddenFromList: false,
+ },
+ foldCount: {
+ type: 'number',
+ min: 0,
+ max: MAX_FOLD_COUNT,
+ step: 1,
+ default: DEFAULT_FOLD_COUNT,
+ description: 'Fold count',
+ hiddenFromList: false,
+ },
+ drops: {
+ type: 'number',
+ min: 0,
+ max: 1,
+ step: 0.01,
+ default: DEFAULT_DROPS,
+ description: 'Drops',
+ hiddenFromList: false,
+ },
+ fade: {
+ type: 'number',
+ min: 0,
+ max: 1,
+ step: 0.01,
+ default: DEFAULT_FADE,
+ description: 'Fade',
+ hiddenFromList: false,
+ },
+ seed: {
+ type: 'number',
+ min: 0,
+ max: MAX_SEED,
+ step: 0.01,
+ default: DEFAULT_SEED,
+ description: 'Seed',
+ hiddenFromList: false,
+ },
+ scale: {
+ type: 'number',
+ min: 0.01,
+ max: 4,
+ step: 0.01,
+ default: DEFAULT_SCALE,
+ description: 'Scale',
+ hiddenFromList: false,
+ },
+} as const satisfies InteractivitySchema;
+
+export type PaperParams = {
+ /** Strength of the paper texture from `0` to `1`. Defaults to `1`. */
+ readonly amount?: number;
+ /** Light-facing paper color. Defaults to `#9fadbc`. */
+ readonly colorFront?: string;
+ /** Shadow-facing paper color. Defaults to `#ffffff`. */
+ readonly colorBack?: string;
+ /** Sharpness of light and color transitions from `0` to `1`. Defaults to `0.3`. */
+ readonly contrast?: number;
+ /** Fine pixel noise from `0` to `1`. Defaults to `0.4`. */
+ readonly roughness?: number;
+ /** Curly fiber intensity from `0` to `1`. Defaults to `0.3`. */
+ readonly fiber?: number;
+ /** Curly fiber scale from `0.01` to `1`. Defaults to `0.2`. */
+ readonly fiberSize?: number;
+ /** Cell-based crumple intensity from `0` to `1`. Defaults to `0.3`. */
+ readonly crumples?: number;
+ /** Cell-based crumple scale from `0.01` to `1`. Defaults to `0.35`. */
+ readonly crumpleSize?: number;
+ /** Fold lighting intensity from `0` to `1`. Defaults to `0.65`. */
+ readonly folds?: number;
+ /** Number of generated folds from `0` to `15`. Defaults to `5`. */
+ readonly foldCount?: number;
+ /** Speckle visibility from `0` to `1`. Defaults to `0.2`. */
+ readonly drops?: number;
+ /** Large-scale mask applied to the paper pattern from `0` to `1`. Defaults to `0`. */
+ readonly fade?: number;
+ /** Seed for the generated paper pattern from `0` to `1000`. Defaults to `6`. */
+ readonly seed?: number;
+ /** Scale of the generated paper texture from `0.01` to `4`. Defaults to `0.6`. */
+ readonly scale?: number;
+};
+
+type PaperResolved = {
+ amount: number;
+ colorFront: string;
+ colorBack: string;
+ contrast: number;
+ roughness: number;
+ fiber: number;
+ fiberSize: number;
+ crumples: number;
+ crumpleSize: number;
+ folds: number;
+ foldCount: number;
+ drops: number;
+ fade: number;
+ seed: number;
+ scale: number;
+};
+
+type PaperState = {
+ readonly gl: WebGL2RenderingContext;
+ readonly program: WebGLProgram;
+ readonly vao: WebGLVertexArrayObject;
+ readonly vbo: WebGLBuffer;
+ readonly sourceTexture: WebGLTexture;
+ readonly noiseTexture: WebGLTexture;
+ readonly uSource: WebGLUniformLocation | null;
+ readonly uResolution: WebGLUniformLocation | null;
+ readonly uImageAspectRatio: WebGLUniformLocation | null;
+ readonly uColorFront: WebGLUniformLocation | null;
+ readonly uColorBack: WebGLUniformLocation | null;
+ readonly uAmount: WebGLUniformLocation | null;
+ readonly uContrast: WebGLUniformLocation | null;
+ readonly uRoughness: WebGLUniformLocation | null;
+ readonly uFiber: WebGLUniformLocation | null;
+ readonly uFiberSize: WebGLUniformLocation | null;
+ readonly uCrumples: WebGLUniformLocation | null;
+ readonly uCrumpleSize: WebGLUniformLocation | null;
+ readonly uFolds: WebGLUniformLocation | null;
+ readonly uFoldCount: WebGLUniformLocation | null;
+ readonly uDrops: WebGLUniformLocation | null;
+ readonly uFade: WebGLUniformLocation | null;
+ readonly uSeed: WebGLUniformLocation | null;
+ readonly uScale: WebGLUniformLocation | null;
+ readonly uNoiseTexture: WebGLUniformLocation | null;
+ readonly colorCtx: CanvasRenderingContext2D;
+ cachedColorFront: string;
+ cachedColorFrontRgba: ParsedColorRgba;
+ cachedColorBack: string;
+ cachedColorBackRgba: ParsedColorRgba;
+ cachedNoiseSeed: number;
+};
+
+const resolve = (p: PaperParams): PaperResolved => ({
+ amount: p.amount ?? DEFAULT_AMOUNT,
+ colorFront: p.colorFront ?? DEFAULT_COLOR_FRONT,
+ colorBack: p.colorBack ?? DEFAULT_COLOR_BACK,
+ contrast: p.contrast ?? DEFAULT_CONTRAST,
+ roughness: p.roughness ?? DEFAULT_ROUGHNESS,
+ fiber: p.fiber ?? DEFAULT_FIBER,
+ fiberSize: p.fiberSize ?? DEFAULT_FIBER_SIZE,
+ crumples: p.crumples ?? DEFAULT_CRUMPLES,
+ crumpleSize: p.crumpleSize ?? DEFAULT_CRUMPLE_SIZE,
+ folds: p.folds ?? DEFAULT_FOLDS,
+ foldCount: p.foldCount ?? DEFAULT_FOLD_COUNT,
+ drops: p.drops ?? DEFAULT_DROPS,
+ fade: p.fade ?? DEFAULT_FADE,
+ seed: p.seed ?? DEFAULT_SEED,
+ scale: p.scale ?? DEFAULT_SCALE,
+});
+
+const validateAtMost = (value: number, max: number, name: string): void => {
+ if (value > max) {
+ throw new TypeError(
+ `"${name}" must be <= ${max}, but got ${JSON.stringify(value)}`,
+ );
+ }
+};
+
+const validatePositiveUnitInterval = (value: number, name: string): void => {
+ if (value <= 0) {
+ throw new TypeError(
+ `"${name}" must be greater than 0, but got ${JSON.stringify(value)}`,
+ );
+ }
+
+ validateAtMost(value, 1, name);
+};
+
+const validatePaperParams = (params: PaperParams): void => {
+ assertEffectParamsObject(params, 'Paper');
+ assertOptionalFiniteNumber(params.amount, 'amount');
+ assertOptionalColor(params.colorFront, 'colorFront');
+ assertOptionalColor(params.colorBack, 'colorBack');
+ assertOptionalFiniteNumber(params.contrast, 'contrast');
+ assertOptionalFiniteNumber(params.roughness, 'roughness');
+ assertOptionalFiniteNumber(params.fiber, 'fiber');
+ assertOptionalFiniteNumber(params.fiberSize, 'fiberSize');
+ assertOptionalFiniteNumber(params.crumples, 'crumples');
+ assertOptionalFiniteNumber(params.crumpleSize, 'crumpleSize');
+ assertOptionalFiniteNumber(params.folds, 'folds');
+ assertOptionalFiniteNumber(params.foldCount, 'foldCount');
+ assertOptionalFiniteNumber(params.drops, 'drops');
+ assertOptionalFiniteNumber(params.fade, 'fade');
+ assertOptionalFiniteNumber(params.seed, 'seed');
+ assertOptionalFiniteNumber(params.scale, 'scale');
+
+ const r = resolve(params);
+ validateUnitInterval(r.amount, 'amount');
+ validateUnitInterval(r.contrast, 'contrast');
+ validateUnitInterval(r.roughness, 'roughness');
+ validateUnitInterval(r.fiber, 'fiber');
+ validatePositiveUnitInterval(r.fiberSize, 'fiberSize');
+ validateUnitInterval(r.crumples, 'crumples');
+ validatePositiveUnitInterval(r.crumpleSize, 'crumpleSize');
+ validateUnitInterval(r.folds, 'folds');
+ validateNonNegative(r.foldCount, 'foldCount');
+ validateAtMost(r.foldCount, MAX_FOLD_COUNT, 'foldCount');
+ validateUnitInterval(r.drops, 'drops');
+ validateUnitInterval(r.fade, 'fade');
+ validateNonNegative(r.seed, 'seed');
+ validateAtMost(r.seed, MAX_SEED, 'seed');
+ if (r.scale <= 0) {
+ throw new TypeError(
+ `"scale" must be greater than 0, but got ${JSON.stringify(r.scale)}`,
+ );
+ }
+
+ validateAtMost(r.scale, 4, 'scale');
+};
+
+const PAPER_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);
+}
+`;
+
+// Adapted from @paper-design/shaders, Apache-2.0.
+// Paper Shaders, Copyright 2026 Paper.
+// Powered by Paper Shaders: https://shaders.paper.design
+const PAPER_FS = /* glsl */ `#version 300 es
+precision highp float;
+
+in vec2 vUv;
+out vec4 fragColor;
+
+uniform sampler2D uSource;
+uniform vec2 uResolution;
+uniform float uImageAspectRatio;
+
+uniform vec4 uColorFront;
+uniform vec4 uColorBack;
+uniform float uAmount;
+uniform float uContrast;
+uniform float uRoughness;
+uniform float uFiber;
+uniform float uFiberSize;
+uniform float uCrumples;
+uniform float uCrumpleSize;
+uniform float uFolds;
+uniform float uFoldCount;
+uniform float uDrops;
+uniform float uFade;
+uniform float uSeed;
+uniform float uScale;
+uniform sampler2D uNoiseTexture;
+
+#define TWO_PI 6.28318530718
+#define PI 3.14159265358979323846
+
+float getUvFrame(vec2 uv) {
+ float aax = 2.0 * fwidth(uv.x);
+ float aay = 2.0 * fwidth(uv.y);
+
+ float left = smoothstep(0.0, aax, uv.x);
+ float right = 1.0 - smoothstep(1.0 - aax, 1.0, uv.x);
+ float bottom = smoothstep(0.0, aay, uv.y);
+ float top = 1.0 - smoothstep(1.0 - aay, 1.0, uv.y);
+
+ return left * right * bottom * top;
+}
+
+vec2 rotate(vec2 uv, float th) {
+ return mat2(cos(th), sin(th), -sin(th), cos(th)) * uv;
+}
+
+vec2 seedOffset(float salt) {
+ float seeded = uSeed + salt;
+ return fract(
+ sin(
+ vec2(
+ seeded * 12.9898 + 78.233,
+ seeded * 39.3468 + 11.135
+ )
+ ) * 43758.5453
+ );
+}
+
+float randomR(vec2 p) {
+ vec2 uv = floor(p) / 100.0 + 0.5;
+ return texture(uNoiseTexture, fract(uv)).r;
+}
+
+float valueNoise(vec2 st) {
+ vec2 i = floor(st);
+ vec2 f = fract(st);
+ float a = randomR(i);
+ float b = randomR(i + vec2(1.0, 0.0));
+ float c = randomR(i + vec2(0.0, 1.0));
+ float d = randomR(i + vec2(1.0, 1.0));
+ vec2 u = f * f * (3.0 - 2.0 * f);
+ float x1 = mix(a, b, u.x);
+ float x2 = mix(c, d, u.x);
+ return mix(x1, x2, u.y);
+}
+
+float fbm(vec2 n) {
+ float total = 0.0;
+ float amplitude = 0.4;
+ for (int i = 0; i < 3; i++) {
+ total += valueNoise(n) * amplitude;
+ n *= 1.99;
+ amplitude *= 0.65;
+ }
+ return total;
+}
+
+float randomG(vec2 p) {
+ vec2 uv = floor(p) / 50.0 + 0.5;
+ return texture(uNoiseTexture, fract(uv)).g;
+}
+
+float roughnessNoise(vec2 p) {
+ p *= 0.1;
+ float o = 0.0;
+ for (float i = 0.0; ++i < 4.0; p *= 2.1) {
+ vec4 w = vec4(floor(p), ceil(p));
+ vec2 f = fract(p);
+ o += mix(
+ mix(randomG(w.xy), randomG(w.xw), f.y),
+ mix(randomG(w.zy), randomG(w.zw), f.y),
+ f.x
+ );
+ o += 0.2 / exp(2.0 * abs(sin(0.2 * p.x + 0.5 * p.y)));
+ }
+ return o / 3.0;
+}
+
+float fiberRandom(vec2 p) {
+ vec2 uv = floor(p) / 100.0;
+ return texture(uNoiseTexture, fract(uv)).b;
+}
+
+float fiberValueNoise(vec2 st) {
+ vec2 i = floor(st);
+ vec2 f = fract(st);
+ float a = fiberRandom(i);
+ float b = fiberRandom(i + vec2(1.0, 0.0));
+ float c = fiberRandom(i + vec2(0.0, 1.0));
+ float d = fiberRandom(i + vec2(1.0, 1.0));
+ vec2 u = f * f * (3.0 - 2.0 * f);
+ float x1 = mix(a, b, u.x);
+ float x2 = mix(c, d, u.x);
+ return mix(x1, x2, u.y);
+}
+
+float fiberNoiseFbm(in vec2 n, vec2 seedOffset) {
+ float total = 0.0;
+ float amplitude = 1.0;
+ for (int i = 0; i < 4; i++) {
+ n = rotate(n, 0.7);
+ total += fiberValueNoise(n + seedOffset) * amplitude;
+ n *= 2.0;
+ amplitude *= 0.6;
+ }
+ return total;
+}
+
+float fiberNoise(vec2 uv, vec2 seedOffset) {
+ float epsilon = 0.001;
+ float n1 = fiberNoiseFbm(uv + vec2(epsilon, 0.0), seedOffset);
+ float n2 = fiberNoiseFbm(uv - vec2(epsilon, 0.0), seedOffset);
+ float n3 = fiberNoiseFbm(uv + vec2(0.0, epsilon), seedOffset);
+ float n4 = fiberNoiseFbm(uv - vec2(0.0, epsilon), seedOffset);
+ return length(vec2(n1 - n2, n3 - n4)) / (2.0 * epsilon);
+}
+
+vec2 randomGB(vec2 p) {
+ vec2 uv = floor(p) / 50.0 + 0.5;
+ return texture(uNoiseTexture, fract(uv)).gb;
+}
+
+float crumpledNoise(vec2 t, float pw) {
+ vec2 p = floor(t);
+ float wsum = 0.0;
+ float cl = 0.0;
+ for (int y = -1; y < 2; y += 1) {
+ for (int x = -1; x < 2; x += 1) {
+ vec2 b = vec2(float(x), float(y));
+ vec2 q = b + p;
+ vec2 q2 = q - floor(q / 8.0) * 8.0;
+ vec2 c = q + randomGB(q2);
+ vec2 r = c - t;
+ float w =
+ pow(smoothstep(0.0, 1.0, 1.0 - abs(r.x)), pw) *
+ pow(smoothstep(0.0, 1.0, 1.0 - abs(r.y)), pw);
+ cl += (0.5 + 0.5 * sin((q2.x + q2.y * 5.0) * 8.0)) * w;
+ wsum += w;
+ }
+ }
+ return pow(wsum != 0.0 ? cl / wsum : 0.0, 0.5) * 2.0;
+}
+
+float crumplesShape(vec2 uv) {
+ return crumpledNoise(uv * 0.25, 16.0) * crumpledNoise(uv * 0.5, 2.0);
+}
+
+vec2 folds(vec2 uv) {
+ vec3 pp = vec3(0.0);
+ float l = 9.0;
+ for (float i = 0.0; i < 15.0; i++) {
+ if (i >= uFoldCount) {
+ break;
+ }
+ vec2 rand = randomGB(vec2(i, i * uSeed));
+ float an = rand.x * TWO_PI;
+ vec2 p = vec2(cos(an), sin(an)) * rand.y;
+ float dist = distance(uv, p);
+ l = min(l, dist);
+
+ if (l == dist) {
+ pp.xy = uv - p.xy;
+ pp.z = dist;
+ }
+ }
+ return mix(pp.xy, vec2(0.0), pow(pp.z, 0.25));
+}
+
+float drops(vec2 uv) {
+ vec2 iDropsUV = floor(uv);
+ vec2 fDropsUV = fract(uv);
+ float dropsMinDist = 1.0;
+ for (int j = -1; j <= 1; j++) {
+ for (int i = -1; i <= 1; i++) {
+ vec2 neighbor = vec2(float(i), float(j));
+ vec2 offset = randomGB(iDropsUV + neighbor);
+ offset = 0.5 + 0.5 * sin(10.0 * uSeed + TWO_PI * offset);
+ vec2 pos = neighbor + offset - fDropsUV;
+ float dist = length(pos);
+ dropsMinDist = min(dropsMinDist, dropsMinDist * dist);
+ }
+ }
+ return 1.0 - smoothstep(0.05, 0.09, pow(dropsMinDist, 0.5));
+}
+
+void main() {
+ vec4 source = texture(uSource, vUv);
+ float sourceAlpha = source.a;
+
+ if (sourceAlpha <= 0.001 || uAmount <= 0.0) {
+ fragColor = source;
+ return;
+ }
+
+ vec3 sourceRgb = source.rgb / sourceAlpha;
+ vec2 imageUV = vUv;
+ vec2 patternUV = vUv - 0.5;
+ patternUV /= max(uScale, 0.001);
+ patternUV = 5.0 * (patternUV * vec2(uImageAspectRatio, 1.0));
+
+ vec2 roughnessUv =
+ 1.5 * (gl_FragCoord.xy - 0.5 * uResolution) +
+ 128.0 * seedOffset(1.0);
+ float roughness =
+ roughnessNoise(roughnessUv + vec2(1.0, 0.0)) -
+ roughnessNoise(roughnessUv - vec2(1.0, 0.0));
+
+ vec2 crumplesUV =
+ fract(patternUV * 0.02 / max(uCrumpleSize, 0.001) - uSeed) * 32.0;
+ float crumples =
+ uCrumples *
+ (crumplesShape(crumplesUV + vec2(0.05, 0.0)) -
+ crumplesShape(crumplesUV));
+
+ vec2 fiberUV = 2.0 / max(uFiberSize, 0.001) * patternUV;
+ float fiber = fiberNoise(fiberUV, 64.0 * seedOffset(2.0));
+ fiber = 0.5 * uFiber * (fiber - 1.0);
+
+ vec2 normal = vec2(0.0);
+ vec2 normalImage = vec2(0.0);
+
+ vec2 foldsUV = patternUV * 0.12;
+ foldsUV = rotate(foldsUV, 4.0 * uSeed);
+ vec2 w = folds(foldsUV);
+ foldsUV = rotate(foldsUV + 0.007 * cos(uSeed), 0.01 * sin(uSeed));
+ vec2 w2 = folds(foldsUV);
+
+ float dropPattern = uDrops * drops(patternUV * 2.0);
+
+ float fade = uFade * fbm(0.17 * patternUV + 10.0 * uSeed);
+ fade = clamp(8.0 * fade * fade * fade, 0.0, 1.0);
+
+ w = mix(w, vec2(0.0), fade);
+ w2 = mix(w2, vec2(0.0), fade);
+ crumples = mix(crumples, 0.0, fade);
+ dropPattern = mix(dropPattern, 0.0, fade);
+ fiber *= mix(1.0, 0.5, fade);
+ roughness *= mix(1.0, 0.5, fade);
+
+ normal.xy += uFolds * min(5.0 * uContrast, 1.0) * 4.0 * max(vec2(0.0), w + w2);
+ normalImage.xy += uFolds * 2.0 * w;
+ normal.xy += crumples;
+ normalImage.xy += 1.5 * crumples;
+ normal.xy += 3.0 * dropPattern;
+ normalImage.xy += 0.2 * dropPattern;
+ normal.xy += uRoughness * 1.5 * roughness;
+ normal.xy += fiber;
+ normalImage += uRoughness * 0.75 * roughness;
+ normalImage += 0.2 * fiber;
+
+ vec3 lightPos = vec3(1.0, 2.0, 1.0);
+ float res = dot(
+ normalize(vec3(normal, 9.5 - 9.0 * pow(uContrast, 0.1))),
+ normalize(lightPos)
+ );
+
+ imageUV += 0.02 * normalImage;
+ float frame = getUvFrame(imageUV);
+ vec4 displacedSource = texture(uSource, clamp(imageUV, vec2(0.0), vec2(1.0)));
+ vec3 displacedRgb = displacedSource.a > 0.001
+ ? displacedSource.rgb / displacedSource.a
+ : sourceRgb;
+ displacedRgb += 0.6 * pow(uContrast, 0.4) * (res - 0.7);
+
+ vec3 frontRgb = mix(vec3(1.0), uColorFront.rgb, uColorFront.a);
+ vec3 backRgb = mix(vec3(1.0), uColorBack.rgb, uColorBack.a);
+ vec3 paperTone = mix(backRgb, frontRgb, clamp(res, 0.0, 1.0));
+ vec3 texturedRgb = displacedRgb * (0.72 + 0.42 * res);
+ texturedRgb = mix(texturedRgb, texturedRgb * paperTone, 0.65);
+ texturedRgb -= 0.007 * dropPattern;
+ texturedRgb = mix(sourceRgb, texturedRgb, frame);
+
+ vec3 finalRgb = mix(sourceRgb, clamp(texturedRgb, 0.0, 1.0), uAmount);
+ fragColor = vec4(finalRgb * sourceAlpha, sourceAlpha);
+}
+`;
+
+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(`Paper 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(`Paper program link failed: ${log ?? '(no log)'}`);
+ }
+
+ return program;
+};
+
+const createSourceTexture = (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 initialNoiseState = (seed: number): number => {
+ const scaledSeed = Math.round(seed * 1000);
+ const mixedState = (0x9e3779b9 ^ Math.imul(scaledSeed, 0x85ebca6b)) >>> 0;
+ return mixedState === 0 ? 0x9e3779b9 : mixedState;
+};
+
+const nextNoiseState = (state: number): number => {
+ let next = state;
+ next ^= next << 13;
+ next ^= next >>> 17;
+ next ^= next << 5;
+ return next >>> 0;
+};
+
+const createNoiseData = (seed: number): Uint8Array => {
+ const data = new Uint8Array(NOISE_TEXTURE_SIZE * NOISE_TEXTURE_SIZE * 4);
+ let state = initialNoiseState(seed);
+ for (let i = 0; i < data.length; i += 4) {
+ state = nextNoiseState(state);
+ data[i] = state & 0xff;
+ state = nextNoiseState(state);
+ data[i + 1] = state & 0xff;
+ state = nextNoiseState(state);
+ data[i + 2] = state & 0xff;
+ data[i + 3] = 255;
+ }
+
+ return data;
+};
+
+const uploadNoiseTexture = (
+ gl: WebGL2RenderingContext,
+ texture: WebGLTexture,
+ seed: number,
+): void => {
+ const data = createNoiseData(seed);
+ gl.bindTexture(gl.TEXTURE_2D, texture);
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
+ gl.texImage2D(
+ gl.TEXTURE_2D,
+ 0,
+ gl.RGBA,
+ NOISE_TEXTURE_SIZE,
+ NOISE_TEXTURE_SIZE,
+ 0,
+ gl.RGBA,
+ gl.UNSIGNED_BYTE,
+ data,
+ );
+};
+
+const createNoiseTexture = (gl: WebGL2RenderingContext): WebGLTexture => {
+ const texture = gl.createTexture();
+ if (!texture) {
+ throw new Error('Failed to create WebGL noise texture');
+ }
+
+ uploadNoiseTexture(gl, texture, DEFAULT_SEED);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
+ gl.bindTexture(gl.TEXTURE_2D, null);
+ return texture;
+};
+
+const setupPaper = (target: HTMLCanvasElement): PaperState => {
+ const gl = target.getContext('webgl2', {
+ premultipliedAlpha: true,
+ alpha: true,
+ preserveDrawingBuffer: true,
+ });
+ if (!gl) {
+ throw createWebGL2ContextError('paper effect');
+ }
+
+ const vs = compileShader(gl, gl.VERTEX_SHADER, PAPER_VS);
+ const fs = compileShader(gl, gl.FRAGMENT_SHADER, PAPER_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 sourceTexture = createSourceTexture(gl);
+ const noiseTexture = createNoiseTexture(gl);
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
+
+ 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,
+ noiseTexture,
+ uSource: gl.getUniformLocation(program, 'uSource'),
+ uResolution: gl.getUniformLocation(program, 'uResolution'),
+ uImageAspectRatio: gl.getUniformLocation(program, 'uImageAspectRatio'),
+ uColorFront: gl.getUniformLocation(program, 'uColorFront'),
+ uColorBack: gl.getUniformLocation(program, 'uColorBack'),
+ uAmount: gl.getUniformLocation(program, 'uAmount'),
+ uContrast: gl.getUniformLocation(program, 'uContrast'),
+ uRoughness: gl.getUniformLocation(program, 'uRoughness'),
+ uFiber: gl.getUniformLocation(program, 'uFiber'),
+ uFiberSize: gl.getUniformLocation(program, 'uFiberSize'),
+ uCrumples: gl.getUniformLocation(program, 'uCrumples'),
+ uCrumpleSize: gl.getUniformLocation(program, 'uCrumpleSize'),
+ uFolds: gl.getUniformLocation(program, 'uFolds'),
+ uFoldCount: gl.getUniformLocation(program, 'uFoldCount'),
+ uDrops: gl.getUniformLocation(program, 'uDrops'),
+ uFade: gl.getUniformLocation(program, 'uFade'),
+ uSeed: gl.getUniformLocation(program, 'uSeed'),
+ uScale: gl.getUniformLocation(program, 'uScale'),
+ uNoiseTexture: gl.getUniformLocation(program, 'uNoiseTexture'),
+ colorCtx,
+ cachedColorFront: '',
+ cachedColorFrontRgba: [159, 173, 188, 255],
+ cachedColorBack: '',
+ cachedColorBackRgba: [255, 255, 255, 255],
+ cachedNoiseSeed: DEFAULT_SEED,
+ };
+};
+
+const normalizedRgba = (
+ color: ParsedColorRgba,
+): readonly [number, number, number, number] => {
+ return [color[0] / 255, color[1] / 255, color[2] / 255, color[3] / 255];
+};
+
+export const paper = createEffect<PaperParams, PaperState>({
+ type: 'dev.remotion.effects.paper',
+ label: 'paper()',
+ documentationLink: 'https://www.remotion.dev/docs/effects/paper',
+ backend: 'webgl2',
+ calculateKey: (params) => {
+ const r = resolve(params);
+ return `paper-${r.amount}-${r.colorFront}-${r.colorBack}-${r.contrast}-${r.roughness}-${r.fiber}-${r.fiberSize}-${r.crumples}-${r.crumpleSize}-${r.folds}-${r.foldCount}-${r.drops}-${r.fade}-${r.seed}-${r.scale}`;
+ },
+ setup: (target) => setupPaper(target),
+ apply: ({source, width, height, params, state, flipSourceY}) => {
+ const r = resolve(params);
+ const {gl, program, vao, sourceTexture, noiseTexture} = state;
+ if (state.cachedColorFront !== r.colorFront) {
+ state.cachedColorFront = r.colorFront;
+ state.cachedColorFrontRgba = parseColorRgba(state.colorCtx, r.colorFront);
+ }
+
+ if (state.cachedColorBack !== r.colorBack) {
+ state.cachedColorBack = r.colorBack;
+ state.cachedColorBackRgba = parseColorRgba(state.colorCtx, r.colorBack);
+ }
+
+ const [frontRed, frontGreen, frontBlue, frontAlpha] = normalizedRgba(
+ state.cachedColorFrontRgba,
+ );
+ const [backRed, backGreen, backBlue, backAlpha] = normalizedRgba(
+ state.cachedColorBackRgba,
+ );
+
+ 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, 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.activeTexture(gl.TEXTURE1);
+ gl.bindTexture(gl.TEXTURE_2D, noiseTexture);
+ if (state.cachedNoiseSeed !== r.seed) {
+ uploadNoiseTexture(gl, noiseTexture, r.seed);
+ state.cachedNoiseSeed = r.seed;
+ }
+
+ if (state.uSource) gl.uniform1i(state.uSource, 0);
+ if (state.uResolution) gl.uniform2f(state.uResolution, width, height);
+ if (state.uImageAspectRatio)
+ gl.uniform1f(state.uImageAspectRatio, width / height);
+ if (state.uColorFront)
+ gl.uniform4f(
+ state.uColorFront,
+ frontRed,
+ frontGreen,
+ frontBlue,
+ frontAlpha,
+ );
+ if (state.uColorBack)
+ gl.uniform4f(state.uColorBack, backRed, backGreen, backBlue, backAlpha);
+ if (state.uAmount) gl.uniform1f(state.uAmount, r.amount);
+ if (state.uContrast) gl.uniform1f(state.uContrast, r.contrast);
+ if (state.uRoughness) gl.uniform1f(state.uRoughness, r.roughness);
+ if (state.uFiber) gl.uniform1f(state.uFiber, r.fiber);
+ if (state.uFiberSize) gl.uniform1f(state.uFiberSize, r.fiberSize);
+ if (state.uCrumples) gl.uniform1f(state.uCrumples, r.crumples);
+ if (state.uCrumpleSize) gl.uniform1f(state.uCrumpleSize, r.crumpleSize);
+ if (state.uFolds) gl.uniform1f(state.uFolds, r.folds);
+ if (state.uFoldCount) gl.uniform1f(state.uFoldCount, r.foldCount);
+ if (state.uDrops) gl.uniform1f(state.uDrops, r.drops);
+ if (state.uFade) gl.uniform1f(state.uFade, r.fade);
+ if (state.uSeed) gl.uniform1f(state.uSeed, r.seed);
+ if (state.uScale) gl.uniform1f(state.uScale, r.scale);
+ if (state.uNoiseTexture) gl.uniform1i(state.uNoiseTexture, 1);
+
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
+ gl.bindVertexArray(null);
+ gl.activeTexture(gl.TEXTURE1);
+ gl.bindTexture(gl.TEXTURE_2D, null);
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, null);
+ gl.useProgram(null);
+ },
+ cleanup: ({gl, program, vao, vbo, sourceTexture, noiseTexture}) => {
+ gl.deleteTexture(sourceTexture);
+ gl.deleteTexture(noiseTexture);
+ gl.deleteBuffer(vbo);
+ gl.deleteProgram(program);
+ gl.deleteVertexArray(vao);
+ },
+ schema: paperSchema,
+ validateParams: validatePaperParams,
+});
diff --git a/packages/effects/src/test/effect-params.test.ts b/packages/effects/src/test/effect-params.test.ts
index 36bb4575e4..197431f932 100644
--- a/packages/effects/src/test/effect-params.test.ts
+++ b/packages/effects/src/test/effect-params.test.ts
@@ -33,6 +33,7 @@ import {
type NoiseDisplacementParams,
} from '../noise-displacement.js';
import {noise} from '../noise.js';
+import {paper} from '../paper.js';
import {pattern} from '../pattern.js';
import {pixelDissolve} from '../pixel-dissolve.js';
import {pixelate} from '../pixelate.js';
@@ -176,6 +177,9 @@ test('@remotion/effects expose documentation links', () => {
noiseDisplacement({center: [0.5, 0.5], radius: 0.25}).definition
.documentationLink,
).toBe('https://www.remotion.dev/docs/effects/noise-displacement');
+ expect(paper().definition.documentationLink).toBe(
+ 'https://www.remotion.dev/docs/effects/paper',
+ );
expect(pattern().definition.documentationLink).toBe(
'https://www.remotion.dev/docs/effects/pattern',
);
@@ -280,6 +284,7 @@ test('@remotion/effects expose API names as Studio labels', () => {
expect(
noiseDisplacement({center: [0.5, 0.5], radius: 0.25}).definition.label,
).toBe('noiseDisplacement()');
+ expect(paper().definition.label).toBe('paper()');
expect(pattern().definition.label).toBe('pattern()');
expect(radialProgressiveBlur().definition.label).toBe(
'radialProgressiveBlur()',
@@ -2406,6 +2411,96 @@ test('noiseDisplacement() parameters produce distinct effect keys', () => {
).toBe(10);
});
+test('paper() accepts default params', () => {
+ expect(() => paper()).not.toThrow();
+});
+
+test('paper() accepts valid params', () => {
+ expect(() =>
+ paper({
+ amount: 0.8,
+ colorFront: '#fff4d0',
+ colorBack: '#94774d',
+ contrast: 0.6,
+ roughness: 0.5,
+ fiber: 0.4,
+ fiberSize: 0.6,
+ crumples: 0.35,
+ crumpleSize: 0.45,
+ folds: 0.25,
+ foldCount: 8,
+ drops: 0.1,
+ fade: 0.2,
+ seed: 12.34,
+ scale: 0.8,
+ }),
+ ).not.toThrow();
+});
+
+test('paper() rejects non-finite amount', () => {
+ expect(() => paper({amount: Number.NaN})).toThrow(
+ '"amount" must be a finite number',
+ );
+});
+
+test('paper() rejects amount above range', () => {
+ expect(() => paper({amount: 1.1})).toThrow('"amount" must be <= 1');
+});
+
+test('paper() rejects empty color strings', () => {
+ expect(() => paper({colorFront: ''})).toThrow(
+ '"colorFront" must be a non-empty string, but got ""',
+ );
+ expect(() => paper({colorBack: ''})).toThrow(
+ '"colorBack" must be a non-empty string, but got ""',
+ );
+});
+
+test('paper() rejects invalid paper texture params', () => {
+ expect(() => paper({fiberSize: 0})).toThrow(
+ '"fiberSize" must be greater than 0',
+ );
+ expect(() => paper({crumpleSize: 0})).toThrow(
+ '"crumpleSize" must be greater than 0',
+ );
+ expect(() => paper({foldCount: 16})).toThrow('"foldCount" must be <= 15');
+ expect(() => paper({seed: -1})).toThrow('"seed" must be >= 0');
+ expect(() => paper({scale: 0})).toThrow('"scale" must be greater than 0');
+ expect(() => paper({scale: 4.1})).toThrow('"scale" must be <= 4');
+});
+
+test('paper() parameters produce distinct effect keys', () => {
+ const defaults = paper();
+ const subtle = paper({amount: 0.6});
+ const frontColored = paper({colorFront: '#fff4d0'});
+ const backColored = paper({colorBack: '#94774d'});
+ const rough = paper({roughness: 0.8});
+ const fibrous = paper({fiber: 0.7, fiberSize: 0.35});
+ const crumpled = paper({crumples: 0.75, crumpleSize: 0.3});
+ const folded = paper({folds: 0.55, foldCount: 10});
+ const dotted = paper({drops: 0.3});
+ const faded = paper({fade: 0.6});
+ const seeded = paper({seed: 12});
+ const scaled = paper({scale: 1.2});
+
+ expect(
+ new Set([
+ defaults.effectKey,
+ subtle.effectKey,
+ frontColored.effectKey,
+ backColored.effectKey,
+ rough.effectKey,
+ fibrous.effectKey,
+ crumpled.effectKey,
+ folded.effectKey,
+ dotted.effectKey,
+ faded.effectKey,
+ seeded.effectKey,
+ scaled.effectKey,
+ ]).size,
+ ).toBe(12);
+});
+
test('pattern() accepts default params', () => {
expect(() => pattern()).not.toThrow();
});
diff --git a/packages/skills/skills/remotion/SKILL.md b/packages/skills/skills/remotion/SKILL.md
index a8aef4aec9..6827c18578 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: `brightness()`, `contrast()`, `colorKey()`, `duotone()`, `grayscale()`, `hue()`, `invert()`, `saturation()`, `tint()`, `linearGradient()`, `linearGradientTint()`, `thermalVision()`, `blur()`, `linearProgressiveBlur()`, `radialProgressiveBlur()`, `zoomBlur()`, `dropShadow()`, `glow()`, `lightTrail()`, `evolve()`, `venetianBlinds()`, `mirror()`, `scale()`, `uvTranslate()`, `xyTranslate()`, `barrelDistortion()`, `chromaticAberration()`, `fisheye()`, `cornerPin()`, `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()`.
+Available effects: `brightness()`, `contrast()`, `colorKey()`, `duotone()`, `grayscale()`, `hue()`, `invert()`, `saturation()`, `tint()`, `linearGradient()`, `linearGradientTint()`, `thermalVision()`, `blur()`, `linearProgressiveBlur()`, `radialProgressiveBlur()`, `zoomBlur()`, `dropShadow()`, `glow()`, `lightTrail()`, `evolve()`, `venetianBlinds()`, `mirror()`, `scale()`, `uvTranslate()`, `xyTranslate()`, `barrelDistortion()`, `chromaticAberration()`, `fisheye()`, `cornerPin()`, `wave()`, `burlap()`, `emboss()`, `dotGrid()`, `halftone()`, `noise()`, `noiseDisplacement()`, `paper()`, `pattern()`, `pixelate()`, `pixelDissolve()`, `scanlines()`, `speckle()`, `shine()`, `shrinkwrap()`, `vignette()`, `contourLines()`, `checkerboard()`, `halftoneLinearGradient()`, `gridlines()`, `whiteNoise()`, `tvSignalOff()`, `lines()`, `rings()`, `waves()`, `zigzag()`, `lightLeak()`, `starburst()`.
## 3D content
diff --git a/packages/studio-shared/src/effect-catalog.ts b/packages/studio-shared/src/effect-catalog.ts
index c6625dfefc..2d9e2cb1c5 100644
--- a/packages/studio-shared/src/effect-catalog.ts
+++ b/packages/studio-shared/src/effect-catalog.ts
@@ -499,6 +499,17 @@ export const EFFECT_CATALOG: readonly EffectCatalogItem[] = [
},
},
},
+ {
+ id: 'effects-paper',
+ category: 'Stylize',
+ label: 'paper()',
+ description: 'Procedural paper texture effect',
+ effect: {
+ name: 'paper',
+ importPath: '@remotion/effects/paper',
+ config: {},
+ },
+ },
{
id: 'effects-pattern',
category: 'Stylize',