Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
121 changes: 117 additions & 4 deletions src/Flowfield.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as d3 from "d3";
import { useEffect, useRef } from "react";
import { useCallback, useEffect, useRef } from "react";
import { createNoise2D, createNoise3D } from "simplex-noise";

export interface Peak {
Expand Down Expand Up @@ -92,6 +92,9 @@ export function Flowfield({
timeSpeed = 0.0025,
driftAmplitude = 150,
smoothing = 0,
cursorRadius = 200,
cursorStrength = 50,
cursorTrail = 0.95,
}: {
/** SVG viewBox width. */
width?: number;
Expand All @@ -113,11 +116,51 @@ export function Flowfield({
driftAmplitude?: number;
/** Number of blur passes applied to the grid before contouring (0 = no smoothing). */
smoothing?: number;
/** Influence radius of cursor interactions in viewBox units. */
cursorRadius?: number;
/** Maximum displacement strength applied at the cursor position. */
cursorStrength?: number;
/** Dissipation factor per frame for the cursor trail (0 = no trail / instant, 0.99 = long trail). When `0`, the displacement grid is skipped entirely for zero overhead. */
cursorTrail?: number;
}) {
const svgRef = useRef<SVGSVGElement>(null);
const noise2DRef = useRef<ReturnType<typeof createNoise2D>>(null);
const noise3DRef = useRef<ReturnType<typeof createNoise3D>>(null);
const timeRef = useRef(0);
const pointersRef = useRef<
Map<number, { x: number; y: number; vx: number; vy: number }>
>(new Map());

const toViewBox = useCallback((clientX: number, clientY: number) => {
const svg = svgRef.current;
if (!svg) return null;
const pt = svg.createSVGPoint();
pt.x = clientX;
pt.y = clientY;
const ctm = svg.getScreenCTM();
if (!ctm) return null;
const svgPt = pt.matrixTransform(ctm.inverse());
return { x: svgPt.x, y: svgPt.y };
}, []);

const handlePointerMove = useCallback(
(e: React.PointerEvent<SVGSVGElement>) => {
const pos = toViewBox(e.clientX, e.clientY);
if (!pos) return;
const prev = pointersRef.current.get(e.pointerId);
const vx = prev ? pos.x - prev.x : 0;
const vy = prev ? pos.y - prev.y : 0;
pointersRef.current.set(e.pointerId, { ...pos, vx, vy });
},
[toViewBox],
);

const handlePointerLeave = useCallback(
(e: React.PointerEvent<SVGSVGElement>) => {
pointersRef.current.delete(e.pointerId);
},
[],
);

useEffect(() => {
const svgEl = svgRef.current;
Expand Down Expand Up @@ -179,6 +222,10 @@ export function Flowfield({
new Array<number>(gridW * gridH).fill(0),
);
const rawElev = new Array<number>(runtimePeaks.length).fill(0);
const displaceX =
cursorTrail > 0 ? new Array<number>(gridW * gridH).fill(0) : null;
const displaceY =
cursorTrail > 0 ? new Array<number>(gridW * gridH).fill(0) : null;
const baseThresholds = Object.keys(baseColors)
.map(Number)
.sort((a, b) => a - b);
Expand All @@ -190,6 +237,54 @@ export function Flowfield({
isPeakBase: boolean;
}

function applyPointerDisplacement(
pos: { x: number; y: number; vx: number; vy: number },
dx: number[],
dy: number[],
) {
const speed = Math.sqrt(pos.vx * pos.vx + pos.vy * pos.vy);
if (speed < 0.01) return;
const nx = pos.vx / speed;
const ny = pos.vy / speed;
const minI = Math.max(0, Math.floor((pos.x - cursorRadius) / gridScale));
const maxI = Math.min(
gridW - 1,
Math.ceil((pos.x + cursorRadius) / gridScale),
);
const minJ = Math.max(0, Math.floor((pos.y - cursorRadius) / gridScale));
const maxJ = Math.min(
gridH - 1,
Math.ceil((pos.y + cursorRadius) / gridScale),
);
for (let j = minJ; j <= maxJ; ++j) {
for (let i = minI; i <= maxI; ++i) {
const cx = i * gridScale - pos.x;
const cy = j * gridScale - pos.y;
const dist = Math.sqrt(cx * cx + cy * cy);
if (dist < cursorRadius) {
const factor = 1 - dist / cursorRadius;
const strength = cursorStrength * factor * factor;
const idx = j * gridW + i;
dx[idx] = (dx[idx] ?? 0) + nx * strength;
dy[idx] = (dy[idx] ?? 0) + ny * strength;
}
}
}
pos.vx = 0;
pos.vy = 0;
}

function updateCursorHeat() {
if (!displaceX || !displaceY) return;
for (let i = 0; i < displaceX.length; i++) {
displaceX[i] = (displaceX[i] ?? 0) * cursorTrail;
displaceY[i] = (displaceY[i] ?? 0) * cursorTrail;
}
for (const pos of pointersRef.current.values()) {
applyPointerDisplacement(pos, displaceX, displaceY);
}
}

function computeGrid() {
for (const p of runtimePeaks) {
p.x = p.baseX + noise2D(p.seed, timeRef.current * 0.3) * driftAmplitude;
Expand All @@ -198,6 +293,8 @@ export function Flowfield({
noise2D(p.seed + 100, timeRef.current * 0.3) * driftAmplitude;
}

updateCursorHeat();

for (let j = 0; j < gridH; ++j) {
for (let i = 0; i < gridW; ++i) {
computeCell(i * gridScale, j * gridScale, j * gridW + i);
Expand All @@ -206,13 +303,18 @@ export function Flowfield({
}

function computeCell(realX: number, realY: number, idx: number) {
// Apply cursor displacement to sampling coordinates
const sampleX = displaceX ? realX - (displaceX[idx] as number) : realX;
const sampleY = displaceY ? realY - (displaceY[idx] as number) : realY;

let maxElev = 0;
for (let k = 0; k < runtimePeaks.length; k++) {
const peak = runtimePeaks[k] as RuntimePeak;
const elev = getRawElevation(peak, realX, realY, timeRef.current);
const elev = getRawElevation(peak, sampleX, sampleY, timeRef.current);
rawElev[k] = elev;
if (elev > maxElev) maxElev = elev;
}

baseValues[idx] = maxElev;

const pow = 8;
Expand Down Expand Up @@ -287,7 +389,7 @@ export function Flowfield({
paths
.enter()
.append("path")
// .style("pointer-events", "none")
.style("pointer-events", "none")
.style("stroke-linejoin", "round")
.merge(paths)
.attr("d", (d) =>
Expand Down Expand Up @@ -319,14 +421,25 @@ export function Flowfield({
timeSpeed,
driftAmplitude,
smoothing,
cursorRadius,
cursorStrength,
cursorTrail,
]);

return (
<svg
ref={svgRef}
viewBox={`0 0 ${width} ${height}`}
preserveAspectRatio="xMidYMid slice"
style={{ width: "100%", height: "100%", display: "block" }}
style={{
width: "100%",
height: "100%",
display: "block",
touchAction: "none",
}}
onPointerDown={handlePointerMove}
onPointerMove={handlePointerMove}
onPointerLeave={handlePointerLeave}
/>
);
}
Loading