Matrix
import {
Shader,
type ShaderComponentProps,
type ShaderMotionParams,
type ShaderPreset,
} from "@/components/Shader";
import {
colorPropsAreEqual,
defaultObjectSizing,
ShaderFitOptions,
type ShaderSizingParams,
type ShaderSizingUniforms,
sizingVariablesDeclaration,
} from "@/lib/shader-utils";
import { cn } from "@/lib/utils";
import { memo } from "react";
const fragmentShader = `#version 300 es
precision highp float;
uniform float u_time;
out vec4 fragColor;
${sizingVariablesDeclaration}
#define r(s) fract(43. * sin(s.x * 13. + s.y * 78.))
void main() {
vec2 r = v_responsiveBoxGivenSize;
float t = u_time;
vec2 i = gl_FragCoord.xy;
vec2 j = fract(i *= 50. / r.x);
vec2 p = i - j + vec2(2, floor(t * 20. * fract(sin(i - j).x)));
i = abs(j - 0.5);
float brightness = r(floor(p * 23. + 5. * j)) > 0.5 && i.x < 0.3 && i.y < 0.45
? 1. - r(p) * (2. - dot(i, i) * 6.)
: 0.0;
fragColor = vec4(0.0, brightness, 0.0, 1.0);
}
`;
type MatrixUniforms = ShaderSizingUniforms & {};
export interface MatrixParams extends ShaderSizingParams, ShaderMotionParams {}
const defaultPreset: ShaderPreset<MatrixParams> = {
name: "Default",
params: {
speed: 1,
frame: 0,
...defaultObjectSizing,
},
};
export const matrixPresets: ShaderPreset<MatrixParams>[] = [defaultPreset];
export interface MatrixProps extends ShaderComponentProps, MatrixParams {}
export const Matrix: React.FC<MatrixProps> = memo(function MatrixImpl({
// Own props
speed = defaultPreset.params.speed,
frame = defaultPreset.params.frame,
// Sizing props
fit = defaultPreset.params.fit,
rotation = defaultPreset.params.rotation,
scale = defaultPreset.params.scale,
originX = defaultPreset.params.originX,
originY = defaultPreset.params.originY,
offsetX = defaultPreset.params.offsetX,
offsetY = defaultPreset.params.offsetY,
worldWidth = defaultPreset.params.worldWidth,
worldHeight = defaultPreset.params.worldHeight,
...props
}: MatrixProps) {
const uniforms = {
// Sizing uniforms
u_fit: ShaderFitOptions[fit],
u_rotation: rotation,
u_scale: scale,
u_offsetX: offsetX,
u_offsetY: offsetY,
u_originX: originX,
u_originY: originY,
u_worldWidth: worldWidth,
u_worldHeight: worldHeight,
} satisfies MatrixUniforms;
return (
<Shader
{...props}
className={cn("w-full h-full", props.className)}
speed={speed}
frame={frame}
fragmentShader={fragmentShader}
uniforms={uniforms}
/>
);
}, colorPropsAreEqual);
Usage
import { Matrix } from "@/components/matrix";
export default function Component() {
return <Matrix />;
}
Credit
Last updated on