Architecting Fluid CPPN Shaders in Three.js and React 19
“How Compositional Pattern Producing Networks (CPPN) can be executed natively in GLSL fragment shaders for hypnotic, generative portfolio heroes.”
Introduction
Generative art in modern web browsers requires a delicate balance between computational intensity and thermal efficiency. Compositional Pattern Producing Networks (CPPN) represent a class of neural networks that produce complex, organic visual patterns through mathematical compositions of activation functions. Unlike traditional CNNs, CPPNs take spatial coordinates as input and output color or intensity values, making them naturally suited for GPU execution via fragment shaders.
In this article, we walk through the full architecture of implementing CPPN-based generative visuals inside a production React 19 application using Three.js, covering everything from the mathematical foundations to performance optimization on mobile devices.
What Are CPPNs and Why Use Them?
A Compositional Pattern Producing Network is a type of artificial neural network introduced by Kenneth Stanley in 2007. Instead of learning from data, CPPNs are evolved or hand-tuned to produce aesthetic patterns. Each node in the network applies a mathematical activation function — such as sin, cos, tanh, or gaussian — to weighted combinations of its inputs.
The key insight is that when you feed pixel coordinates (x, y) into such a network, the output naturally produces smooth, continuous, and often strikingly organic visuals. This makes CPPNs perfect for:
- Hero section backgrounds that feel alive and unique
- Generative art installations running in real-time
- Loading screens and ambient visual textures
- Interactive mouse-reactive shader surfaces
CPPN vs Traditional Noise Functions
Perlin noise and simplex noise are the go-to choices for procedural generation. However, they produce relatively predictable, cloud-like patterns. CPPNs offer significantly more visual diversity because the composition of activation functions creates interference patterns, moire effects, and fractal-like structures that noise functions cannot replicate.
The tradeoff is computational cost. A deep CPPN with 8+ layers can be expensive per pixel. This is where GLSL fragment shaders become essential — they execute the network in parallel across millions of pixels simultaneously on the GPU.
Setting Up the Three.js Pipeline in React 19
React 19 introduces several improvements that make integrating imperative WebGL code cleaner. Server Components allow us to keep the Three.js canvas as a pure client component while the surrounding page layout remains server-rendered.
Project Structure
We organize the shader system into three layers:
- ShaderCanvas — A React component wrapping the Three.js
WebGLRenderer, handling resize observers and cleanup - CPPNMaterial — A custom
ShaderMaterialcontaining the GLSL vertex and fragment shaders - AnimationLoop — A
requestAnimationFrameloop synchronized with React's lifecycle viauseEffect
The Canvas Component
The canvas component mounts a full-viewport Three.js scene with an orthographic camera. We use a simple fullscreen quad (two triangles) as the geometry, since the entire visual is computed in the fragment shader:
// ShaderCanvas.tsx
'use client';
import { useEffect, useRef } from 'react';
import * as THREE from 'three';
import { createCPPNMaterial } from './cppn-material';
export function ShaderCanvas() {
const containerRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const container = containerRef.current;
if (!container) return;
const renderer = new THREE.WebGLRenderer({
antialias: false,
alpha: true,
powerPreference: 'high-performance',
});
const scene = new THREE.Scene();
const camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
const geometry = new THREE.PlaneGeometry(2, 2);
const material = createCPPNMaterial();
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
container.appendChild(renderer.domElement);
let frameId: number;
const animate = () => {
material.uniforms.u_time.value = performance.now() * 0.001;
renderer.render(scene, camera);
frameId = requestAnimationFrame(animate);
};
animate();
return () => {
cancelAnimationFrame(frameId);
renderer.dispose();
geometry.dispose();
material.dispose();
container.removeChild(renderer.domElement);
};
}, []);
return <div ref={containerRef} className="absolute inset-0" />;
}
Writing the GLSL Fragment Shader
The fragment shader is where the CPPN network executes. Each pixel independently computes its color by running the network forward with its normalized screen coordinates as input.
Network Architecture in GLSL
We implement a 4-layer CPPN with the following structure:
- Input layer:
(x, y, r, time)wherer = sqrt(x² + y²)is the radial distance from center - Hidden layer 1: 6 neurons with
sinactivation - Hidden layer 2: 4 neurons with
tanhactivation - Output layer: 3 neurons (RGB) with
sigmoidactivation
The weight matrices are passed as uniforms, allowing real-time parameter tweaking or even evolutionary mutation of the network topology.
// Fragment shader (GLSL)
precision highp float;
uniform float u_time;
uniform vec2 u_resolution;
uniform vec2 u_mouse;
float sigmoid(float x) {
return 1.0 / (1.0 + exp(-x));
}
void main() {
vec2 uv = (gl_FragCoord.xy - 0.5 * u_resolution) / min(u_resolution.x, u_resolution.y);
float r = length(uv);
float t = u_time * 0.3;
// Layer 1: input expansion
float h1 = sin(uv.x * 3.0 + t);
float h2 = cos(uv.y * 2.7 - t * 0.8);
float h3 = sin(r * 5.0 + t * 1.2);
float h4 = tanh(uv.x * uv.y * 4.0);
float h5 = sin(uv.x * 1.5 + uv.y * 2.0 + t);
float h6 = cos(r * 3.0 - uv.x * 2.0);
// Layer 2: feature mixing
float m1 = tanh(h1 * 0.8 + h3 * 0.6 - h5 * 0.4);
float m2 = tanh(h2 * 0.7 - h4 * 0.5 + h6 * 0.9);
float m3 = tanh(h1 * 0.3 + h2 * 0.3 + h6 * 0.4);
float m4 = tanh(h3 * 0.5 - h5 * 0.7 + h4 * 0.2);
// Output: RGB channels
float red = sigmoid(m1 * 1.5 + m3 * 0.8);
float green = sigmoid(m2 * 1.2 - m4 * 0.6);
float blue = sigmoid(m3 * 1.8 + m1 * 0.4 - m2 * 0.3);
gl_FragColor = vec4(red, green, blue, 1.0);
}
Uniform Management
Three.js ShaderMaterial accepts a uniforms object that maps directly to GLSL uniform declarations. We update u_time every frame and u_mouse on pointer move events. The resolution uniform updates on window resize via a ResizeObserver.
Performance Optimization
Running a per-pixel neural network at 60fps across millions of fragments demands careful optimization. Here are the techniques we apply:
1. Resolution Scaling
On mobile devices, rendering at native retina resolution (3x DPR) is unnecessary for a background effect. We cap the pixel ratio at 1.5 and use CSS to scale the canvas up. This reduces fragment count by ~4x on high-DPI phones with negligible visual difference.
2. Reduced Precision
Using mediump instead of highp floats on mobile GPUs (Adreno, Mali) can yield 20-40% performance improvements. The visual output of CPPNs is tolerant of reduced precision because the activation functions naturally clamp values into bounded ranges.
3. Frame Throttling
When the canvas is not visible (scrolled off-screen), we pause the animation loop entirely using an IntersectionObserver. This prevents wasted GPU cycles and reduces thermal throttling on mobile devices.
4. Layer Depth Budget
Each additional CPPN layer roughly doubles the ALU instruction count. We profile the shader using EXT_disjoint_timer_query and maintain a strict budget of 4ms per frame on a baseline GPU (Intel UHD 630). If the budget is exceeded, we dynamically reduce the network depth.
Integrating Mouse Reactivity
Adding mouse interaction transforms the shader from a passive background into an engaging experience. We pass normalized mouse coordinates as a uniform and use them to distort the CPPN input space:
// In the fragment shader
vec2 mouseInfluence = (u_mouse - uv) * 0.3;
float distortion = exp(-length(mouseInfluence) * 5.0);
uv += mouseInfluence * distortion;
This creates a gentle gravitational pull effect around the cursor position. The exponential falloff ensures the distortion is localized and smooth, avoiding harsh visual artifacts at the boundary.
Color Palette Control
Raw CPPN outputs tend toward full RGB chaos. For a cohesive portfolio aesthetic, we remap the output through a curated color palette. The technique involves defining 3-4 key colors and interpolating between them based on the CPPN output luminance:
vec3 palette(float t) {
vec3 a = vec3(0.05, 0.05, 0.15); // deep navy
vec3 b = vec3(0.15, 0.35, 0.65); // ocean blue
vec3 c = vec3(0.35, 0.55, 0.85); // sky blue
vec3 d = vec3(0.85, 0.90, 0.95); // near-white
t = clamp(t, 0.0, 1.0);
if (t < 0.33) return mix(a, b, t / 0.33);
if (t < 0.66) return mix(b, c, (t - 0.33) / 0.33);
return mix(c, d, (t - 0.66) / 0.34);
}
This constrains the visual output to a monochromatic blue spectrum that aligns with the portfolio's design language while preserving the organic CPPN structure.
React 19 Lifecycle Considerations
React 19's strict mode double-invokes effects in development, which causes the Three.js renderer to initialize twice. The cleanup function in useEffect must fully dispose of all GPU resources:
- Call
renderer.dispose()to release the WebGL context - Dispose geometry and material individually to free GPU buffer memory
- Remove the canvas DOM node to prevent ghost elements
- Cancel the animation frame to stop orphaned render loops
With React 19's use hook and Server Components, we can also lazy-load the entire shader module only when the component enters the viewport, further reducing initial bundle size.
Thermal Management on Mobile
Continuous GPU workloads cause mobile devices to thermal-throttle, reducing frame rates and draining battery. We implement a thermal budget system:
- Monitor frame time variance over a 60-frame rolling window
- If average frame time exceeds 18ms (below 55fps), reduce resolution by 25%
- If frame time drops below 8ms consistently, restore resolution
- After 30 seconds of continuous animation, reduce to 30fps target
This adaptive approach ensures the shader remains smooth on flagship phones while gracefully degrading on older hardware without crashing or freezing the browser.
Deployment and Bundle Size
Three.js is a substantial dependency (~600KB minified). For a portfolio where the shader is the only 3D element, we apply aggressive tree-shaking:
- Import only
WebGLRenderer,Scene,OrthographicCamera,PlaneGeometry,ShaderMaterial, andMesh - Use
next/dynamicwith SSR disabled to code-split the entire canvas component - GLSL source is inlined as template literals, avoiding separate file loaders
After tree-shaking, the Three.js portion of the bundle drops to approximately 85KB gzipped — acceptable for a hero visual that runs on every page load.
Conclusion
CPPN shaders offer a distinctive alternative to stock gradient backgrounds and generic particle systems. By porting the network computation to GLSL and managing GPU resources carefully within React 19's component lifecycle, we achieve a generative hero section that is visually unique, performant on mobile, and architecturally clean.
The complete source code for this implementation is available in the portfolio repository. For questions or collaboration on generative web art, reach out via the guestbook or social links.