Published
Edited
Nov 21, 2020
65 stars
WebGPU ShaderHydraulic Erosion SimulationHow Does Mapbox Raster Colorization Work?Arc Length of a Quadratic Bézier SplineMagnetic PendulumTracing Lamb Modes in the Complex PlaneMissing Fundamental IllusionSliced Optimal TransportLine Integral ConvolutionShanks TransformationUeda's AttractorCubic basis vs. Hermite interpolationBicubic Texture Interpolation using Linear FilteringFactor-of-Two Lanczos Image ResamplingAperiodic Monotileeqn [WIP]SDF Points with reglKnocking Down the Gates with our Friend JacobiFast Generalized Winding Numbers in 2DHTML+CSS Periodic Three-Body OrbitsClifford and de Jong AttractorsStrange Attractors on the GPU, Part 1: ImplementationStrange Attractors on the GPU, Part 2: Fun!Lawson's Klein BottleInteractive Multi-scale Turing PatternsComputing π with the Bailey-Borwein-Plouffe FormulaThe Double Pendulum MapMalkus WaterwheelRegister Allocation and the k-Coloring ProblemMultiscale Turing Patterns in WebGLSelecting the Right Opacity for 2D Point CloudsKuramoto-Sivashinsky Equation in 2DAdaptive Contouring in Fragment ShadersComplex function plotterGPU Voronoi Diagrams using the Jump Flooding AlgorithmBaker's MapHello, g9Dispersion in Water Surface WavesFake Transparency for 3D SurfacesUniformly Distributed Points on a SphereGPU BoidsGrouping Points with Principal Component AnalysisDomain Coloring for Complex FunctionsDrawing indexed mesh data as screen-space normals without duplicating dataFinding Roots in the Complex PlanePeriodic Planar Three-Body Orbits2D (Non-physical) N-body Gravity with Poisson's EquationHalf-Precision Floating-Point, VisualizedIntegers in Single-Precision Floating-PointDomain Coloring with Adaptive ContouringInstanced WebGL Circles
Double Compound Pendulums
3D Reaction-DiffusionMathematical Easter Egg ColoringToiletpaperfullerenes and Charmin Nanotubes
Also listed in…
Math
WebGL
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
simulationLoop = {
restart;
let gif;
if (saveGIF) {
gif = new GIF({
width: regl._gl.canvas.width,
height: regl._gl.canvas.height
});
}
var gifTick = 0;
var gifDone = false;

let frame = regl.frame(() => {
if (!simulate || (saveGIF && gifDone)) return;

// The screen is only uint8, which isn't enough precision to draw so many pendulums
// with such low opacity. Instead we use a screen-sized framebuffer to accumulate
// in higher precision, then copy that to the screen with gamma correction at the
// end.
// This command just makes sure it's the right size. If there's no change, it's a no-op.
offscreenFBO.resize(regl._gl.canvas.width, regl._gl.canvas.height);

if (simulate) {
// Read FBO #0 as the state and write to FBO #1.
stateFBO[1].use(() =>
iterate({
src: stateFBO[0],
dt: dt * 0.1 // (To compensate for coarse control in the slider widget)
})
);

// Swap references so #0 is once again the current state.
swap(stateFBO);
}

offscreenFBO.use(() => {
// Clear the offscreen FBO
regl.clear({ color: [0, 0, 0, 1] });

// Draw the pendulums as GL_LINES. To accomplish this we use instanced rendering. Each
// pixel in the positions FBO represent the state (theta1, theta2, p_theta1, p_theta2).
// So we use instanced rendering to draw two line primitives for each pixel of the state
// texture.
var drawCmd =
draw === 'Physical space' ? drawPendulums : drawPendulumStates;
drawCmd({ src: stateFBO[0], ɑ, count: n });
});

// Once we've drawn all the lines, copy the offscreen framebuffer to the screen.
copy({ src: offscreenFBO, γ });

if (saveGIF) {
regl.poll();
gif.addFrame(regl._gl.canvas, { copy: true, delay: 16 });
if (gifTick++ === gifFrames) {
console.log('GIF capture complete. Beginning conversion…');
gif.render();
frame.cancel();
frame = null;
}
}
});
invalidation.then(() => {
frame && frame.cancel();
if (saveGIF) gif.abort();
});

if (saveGIF) {
gif.on("finished", blob => {
console.log('GIF conversion complete');
saveFile(blob, 'pendulum.gif');
});
}
}
Insert cell
onRestart = {
// Restart when you toggle saving or when you click restart.
saveGIF;
restart;
// Necessary whenever you do something outside of regl.frame
regl.poll();
// Write positions to state framebuffer #0
stateFBO[0].use(() =>
initialize({
θ: (θ * Math.PI) / 180,
spread: (spread * Math.PI) / 180,
count: textureSize * textureSize
})
);
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
copy = {
let copy = regl({
frag: `
precision highp float;
varying vec2 uv;
uniform sampler2D src;
uniform float gamma;
void main () {
vec3 color = max(1.0 - texture2D(src, uv).rgb, 0.0);
gl_FragColor = vec4(
vec3(pow(color.r, gamma)),
//pow(color.g, gamma), // Save some 'pow' calls since only grayscale right now
//pow(color.b, gamma),
1.0);
}`,
uniforms: {
src: regl.prop('src'),
gamma: (ctx, props) => 1 / props.γ
}
});
return props => blit(() => copy(props));
}
Insert cell
initialize = regl({
vert: `
precision highp float;
attribute vec3 aUV;
varying vec2 uv;
varying float t;
void main () {
// The location of this state in the state texture:
uv = aUV.xy;

// A paramater that varies from 0 to 1 across the state texture
t = aUV.z;

gl_Position = vec4(uv * 2.0 - 1.0, 0, 1);
gl_PointSize = 1.0;
}`,
frag: `
precision highp float;
varying float t;
varying vec2 uv;
uniform float theta, spread;
#define TWOPI ${Math.PI * 2}
#define PI ${Math.PI}
void main () {
vec2 intl;
// State is:
// theta_1 (angle of inside and outside, respectively)
// theta_2
// p_theta_1 (momentum)
// p_theta_2

${
initialConditions === "θ1 = θ2"
? `
intl = vec2(mix((theta - spread * 0.5), (theta + spread * 0.5), t));
gl_FragColor = vec4(intl, vec2(0));`
: initialConditions === "uniformly distributed in θ phase space"
? `
intl = (uv - 0.5) * spread;
gl_FragColor = vec4(intl, vec2(0));`
: initialConditions ===
"uniformly distributed in momentum phase space"
? `
intl = (uv - 0.5) * spread * vec2(1, 0.5);
gl_FragColor = vec4(vec2(0), intl);`
: `
gl_FragColor = (
(uv.x - 0.5) * vec4(0.776140490509798, 0.3700898833514918, 0.4427594582202827, 0.6333677919749464) +
(uv.y - 0.5) * vec4(0.776140490509798, 0.3700898833514918, -0.4427594582202827, -0.6333677919749464)
) * spread;`
}
}`,
count: regl.prop('count'),
primitive: 'points',
attributes: { aUV: lookupBuffer },
uniforms: {
theta: regl.prop('θ'),
spread: regl.prop('spread')
}
})
Insert cell
iterate = {
let iterate = regl({
frag: `
precision highp float;
varying vec2 uv;
uniform sampler2D src;
uniform float dt;
${
linearized
? `
vec4 derivative (vec4 state) {
return vec4(
(12.0 * state.z - 18.0 * state.w) / 7.0,
(-18.0 * state.z + 48.0 * state.w) / 7.0,
-1.5 * state.x,
-0.5 * state.y
);
}`
: `
// From: https://en.wikipedia.org/wiki/Double_pendulum#Lagrangian
vec4 derivative (vec4 state) {
vec2 theta = state.xy;
vec2 pTheta = state.zw;
float threeCosTheta12 = 3.0 * cos(theta.x - theta.y);
vec2 thetaDot = 6.0 * (
vec2(
2.0 * pTheta.x - threeCosTheta12 * pTheta.y,
8.0 * pTheta.y - threeCosTheta12 * pTheta.x
) / (16.0 - threeCosTheta12 * threeCosTheta12)
);
float thetaDot12sinTheta12 = thetaDot.x * thetaDot.y * sin(theta.x - theta.y);
vec2 pThetaDot = -0.5 * vec2(
thetaDot12sinTheta12 + 3.0 * sin(theta.x),
-thetaDot12sinTheta12 + sin(theta.y)
);
return vec4(thetaDot, pThetaDot);
}`
}

void main () {
vec4 yn = texture2D(src, uv);

// RK4 integration
vec4 k1 = dt * derivative(yn);
vec4 k2 = dt * derivative(yn + 0.5 * k1);
vec4 k3 = dt * derivative(yn + 0.5 * k2);
vec4 k4 = dt * derivative(yn + k3);
gl_FragColor = yn + (k1 + k4 + 2.0 * (k2 + k3)) / 6.0;
}`,
uniforms: {
src: regl.prop('src'),
dt: regl.prop('dt')
}
});
return props => blit(() => iterate(props));
}
Insert cell
drawPendulumStates = regl({
vert: `
precision highp float;
attribute vec3 uv;
uniform sampler2D positions;
varying float r;
varying vec2 shade;
#define TWOPI_INV ${0.5 / Math.PI}
void main () {
${
draw === 'θ phase space, (θ1 vs. θ2)'
? `
vec2 state = texture2D(positions, uv.xy).xy;
state = fract(state.xy * TWOPI_INV + 0.5);`
: draw === 'Similarity-transformed'
? `
vec4 statevector = texture2D(positions, uv.xy);
vec2 state;
state.x = dot(vec4(0.776140490509798, 0.3700898833514918, 0.4427594582202827, 0.6333677919749464), statevector);
state.y = dot(vec4(0.776140490509798, 0.3700898833514918, -0.4427594582202827, -0.6333677919749464), statevector);
state = state.xy * TWOPI_INV * 1.25 + 0.5;
`
: `
vec2 state = texture2D(positions, uv.xy).zw;
state *= vec2(1, 2);
state = state.xy * TWOPI_INV + 0.5;
`
}
gl_Position = vec4(state * 2.0 - 1.0, 0, 1);
gl_PointSize = 1.0;
}
`,
frag: `
precision highp float;
uniform float alpha;
varying float r;
varying vec2 shade;
void main () {
gl_FragColor = vec4(vec3(1.0), alpha);
}
`,
count: regl.prop('count'),
primitive: 'points',

depth: { enable: false },
uniforms: {
alpha: (ctx, props) =>
((20000 * props.ɑ) / Math.pow(textureSize, 2)) * (width / 600),
positions: regl.prop('src')
},
attributes: {
uv: { buffer: lookupBuffer }
},
blend: {
enable: true,
func: {
srcRGB: 'src alpha',
srcAlpha: 1,
dstRGB: 1,
dstAlpha: 1
},
equation: {
rgb: 'add',
alpha: 'add'
}
}
})
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more