7 minute read

Final Result - Video

Watch the video

WCCChallenge Blurb

Biz Biz Biz
Author Project Somedays
Title WCCChallenge 2026 Week 47 - Waveform
📅 Started 2026-11-22
📅 Completed 2026-11-22
🕒 Taken ~1.5hrs + 1.5hrs render time
🤯 Concept Wave bots doing their thing generating the superposition of waveforms in 3 dimensions 🥰
🔎 Focus First foray into scripting in Blender using the python API
🤖 AI-use Vibe-coded multi/moving source waves and anchoring empties to the source of the waves

Made for Sableraph’s weekly creative coding challenges, reviewed weekly on https://www.twitch.tv/sableraph

See other submissions here: https://openprocessing.org/curation/78544

Join The Birb’s Nest Discord community! https://discord.gg/g5J6Ajx9Am

Birb’s Nesters! It’s been a hot minute. This is my year of thick butter (not spreading myself too thin) and I’ve spent a lot of it doing a deep dive into Blender. This prompt is a great opportunity to at least briefly visit the land of creative coding again and try out Blender’s python API. I’ve done wave superposition in p5.js, in straight webgl, using p5.strands, and now Blender/python! Enjoy.

📃THE ALGORITHM📃

  1. Establish a grid of vertices and 3 source points with various phase offsets and positions. Position empties at those source points.
  2. Move the source points around with perlin noise AND with repulsion to each other so our syringes
  3. Each timestep and vertice, calculate z by the superposition of waves based on the source point positions
  4. Set the position of the empty at each source point to the z height of the contributing wave

Set the syringe platform to the xy (xz in three.js and p5.js) and the plunger to the z position (y in three.js / p5.js) of the wave generator.

🎓Lessons Learned🎓

  • So. Happy to report that the python API is pretty intuitive to work with! Genuinely didn’t know python had perlin noise built right in!
  • Mixing creative coding and the things I’ve learned about Blender over the last year is a dangerous mix!
  • Coming to Blender from creative coding sets you up to give REALLY good, detailed prompts about implementation

Resources

  • BlendKit:
    • Bot model, rigged and animated by me. Any by animated, I mean I parented the IK hands to the plunger 🥰
    • Syringes
    • HDRI lighting
    • Stylized ocean material for the wave pool
    • Tile material for the sides of the pool
  • 🔊

The Code

import math
import bmesh
import bpy
import numpy as np
from mathutils import Vector, noise

# --- Grid & Wave Parameters ---
GRID_SIZE = 15.0
DIVISIONS = 300
AMPLITUDE = 0.5
WAVELENGTH = 1.6
FREQUENCY = 0.5
FPS = 24.0
DECAY = 0.08

# Perlin drift controls
DRIFT_SPEED = 0.05
DRIFT_RADIUS = 0.78
EDGE_PADDING = 0.5

MIN_SEPARATION = 6.0       # Minimum desired distance between any two sources (meters)
REPULSION_STRENGTH = 1.0    # 1.0 = full constraint resolution per iteration; <1.0 = softer
RELAXATION_ITERS = 32

# Empty tracking controls
EMPTY_PREFIX = "Source_Empty_"
EMPTY_TRACK_WAVE_Z = True   # True: follow surface Z at source; False: stay at EMPTY_Z_OFFSET
EMPTY_Z_OFFSET = 0.0        # Added to wave Z (or used directly if EMPTY_TRACK_WAVE_Z is False)
EMPTY_DISPLAY_SIZE = 0.35

# Empty rotation controls (around Z axis)
EMPTY_SPIN_SPEED = 0.25      # Base angular speed in radians/sec (negative reverses direction)
EMPTY_WOBBLE_AMP = 0.35      # Extra Perlin yaw sway in radians (~20 deg)
EMPTY_WOBBLE_SPEED = 0.30    # How fast the yaw sway drifts

# Source tuple: (anchor_x, anchor_y, weight, phase_offset, noise_seed)
SOURCES = [
    (-3, -1.0, 1.0, 0.0, 10.1),
    (3, -1.0, 1.0, math.pi/3.0, 37.4),
    (3.0, 5.5, 1.0, 2.0*math.pi/3.0, 83.9),
]

OBJECT_NAME = "Interference_Grid"
ATTR_NAME = "interference"

_axis = np.linspace(-GRID_SIZE * 0.5, GRID_SIZE * 0.5, DIVISIONS + 1, dtype=np.float32)
_GX, _GY = np.meshgrid(_axis, _axis)
_X = _GX.ravel()
_Y = _GY.ravel()
_NORM = max(1.0, sum(abs(s[2]) for s in SOURCES))


def perlin_source_xy(anchor_x: float, anchor_y: float, seed: float, t: float) -> tuple[float, float]:
    """Smoothly wander inside [-GRID_SIZE/2, GRID_SIZE/2] using Blender's Perlin noise."""
    max_bound = max(0.0, GRID_SIZE * 0.5 - EDGE_PADDING) * DRIFT_RADIUS
    u = t * DRIFT_SPEED

    nx = noise.noise(Vector((u, seed, 1.7)))
    ny = noise.noise(Vector((u + 19.3, seed + 41.2, -5.4)))

    nx = max(-1.0, min(1.0, nx * 1.35))
    ny = max(-1.0, min(1.0, ny * 1.35))

    x = max(-max_bound, min(max_bound, anchor_x + nx * max_bound))
    y = max(-max_bound, min(max_bound, anchor_y + ny * max_bound))
    return x, y

def source_oscillation_z(weight: float, src_phase: float, t: float, match_field_scale: bool = True) -> float:
    """Return the Z stroke of a single source's own oscillator (at dist = 0) at time `t`."""
    omega = 2.0 * math.pi * FREQUENCY
    stroke = weight * math.sin(-omega * t + src_phase)
    if match_field_scale:
        stroke /= _NORM
    return stroke * AMPLITUDE


def source_yaw_z(seed: float, t: float) -> float:
    """Smooth Z-axis rotation combining steady drift with gentle Perlin yaw sway."""
    wobble_sample = noise.noise(Vector((t * EMPTY_WOBBLE_SPEED, seed + 101.5, 7.3)))
    wobble_sample = max(-1.0, min(1.0, wobble_sample * 1.35))
    return EMPTY_SPIN_SPEED * t + wobble_sample * EMPTY_WOBBLE_AMP


def update_source_empties(t: float, empties: list[bpy.types.Object]) -> None:
    """Move each Empty to its source's (x, y) and Z stroke, and rotate around Z."""
    for idx, (ax, ay, weight, src_phase, seed) in enumerate(SOURCES):
        if idx >= len(empties):
            break
        sx, sy = perlin_source_xy(ax, ay, seed, t)
        if EMPTY_TRACK_WAVE_Z:
            sz = source_oscillation_z(weight, src_phase, t, match_field_scale=True) + EMPTY_Z_OFFSET
        else:
            sz = EMPTY_Z_OFFSET

        empty = empties[idx]
        empty.location = (sx, sy, sz)
        empty.rotation_mode = "XYZ"
        empty.rotation_euler = (0.0, 0.0, source_yaw_z(seed, t))


def compute_wave_field(t: float) -> np.ndarray:
    """Return normalized wave values for all grid vertices at time `t` (seconds)."""
    total = np.zeros_like(_X, dtype=np.float32)
    k = (2.0 * math.pi) / WAVELENGTH
    omega = 2.0 * math.pi * FREQUENCY

    for ax, ay, weight, src_phase, seed in SOURCES:
        sx, sy = perlin_source_xy(ax, ay, seed, t)
        dist = np.hypot(_X - sx, _Y - sy)
        attenuation = np.exp(-DECAY * dist) if DECAY > 0.0 else 1.0
        phase = k * dist - omega * t + src_phase
        total += weight * attenuation * np.sin(phase)

    return total / _NORM


def ensure_source_empties() -> list[bpy.types.Object]:
    """Create or reuse one Empty object per source in `SOURCES`."""
    empties = []
    scene_collection = bpy.context.scene.collection

    for idx in range(len(SOURCES)):
        name = f"{EMPTY_PREFIX}{idx}"
        empty = bpy.data.objects.get(name)
        if empty is None:
            empty = bpy.data.objects.new(name, None)
            scene_collection.objects.link(empty)
        empty.empty_display_type = "PLAIN_AXES"
        empty.empty_display_size = EMPTY_DISPLAY_SIZE
        empties.append(empty)

    return empties


def ensure_base_grid_object() -> bpy.types.Object:
    """Create the quad grid topology once, or return the existing object."""
    obj = bpy.data.objects.get(OBJECT_NAME)
    if obj and obj.type == "MESH" and len(obj.data.vertices) == len(_X):
        return obj

    bm = bmesh.new()
    n_cols = DIVISIONS + 1
    verts = [bm.verts.new((float(x), float(y), 0.0)) for x, y in zip(_X, _Y)]

    for iy in range(DIVISIONS):
        row0 = iy * n_cols
        row1 = (iy + 1) * n_cols
        for ix in range(DIVISIONS):
            v00 = verts[row0 + ix]
            v10 = verts[row0 + ix + 1]
            v11 = verts[row1 + ix + 1]
            v01 = verts[row1 + ix]
            bm.faces.new((v00, v10, v11, v01))

    bm.normal_update()

    if obj and obj.type == "MESH":
        mesh = obj.data
        bm.to_mesh(mesh)
    else:
        mesh = bpy.data.meshes.new(f"{OBJECT_NAME}_Mesh")
        bm.to_mesh(mesh)
        obj = bpy.data.objects.new(OBJECT_NAME, mesh)
        bpy.context.scene.collection.objects.link(obj)

    bm.free()

    mesh.polygons.foreach_set("use_smooth", [True] * len(mesh.polygons))
    mesh.attributes.new(name=ATTR_NAME, type="FLOAT", domain="POINT")
    mesh.update()
    return obj

def apply_minimum_separation(
    positions: list[tuple[float, float]],
    min_dist: float = MIN_SEPARATION,
    strength: float = REPULSION_STRENGTH,
    iters: int = RELAXATION_ITERS,
) -> list[tuple[float, float]]:
    """Iteratively enforce minimum pairwise distance while keeping motion smooth."""
    pts = [[float(x), float(y)] for x, y in positions]
    n = len(pts)
    if n < 2 or min_dist <= 0.0:
        return positions

    wall_bound = max(0.0, GRID_SIZE * 0.5 - EDGE_PADDING)

    for _ in range(max(1, iters)):
        moved = False
        for i in range(n):
            for j in range(i + 1, n):
                dx = pts[j][0] - pts[i][0]
                dy = pts[j][1] - pts[i][1]
                dist = math.hypot(dx, dy)

                if dist < min_dist:
                    moved = True
                    if dist > 1e-6:
                        nx, ny = dx / dist, dy / dist
                    else:
                        angle = i * 2.094395 + j * 0.7
                        nx, ny = math.cos(angle), math.sin(angle)

                    # Full overlap correction split evenly between the two sources
                    overlap = (min_dist - dist) * strength
                    half_push = 0.5 * overlap

                    pts[i][0] -= nx * half_push
                    pts[i][1] -= ny * half_push
                    pts[j][0] += nx * half_push
                    pts[j][1] += ny * half_push

        # Clamp inside the playable grid boundary after each pass
        for pt in pts:
            pt[0] = max(-wall_bound, min(wall_bound, pt[0]))
            pt[1] = max(-wall_bound, min(wall_bound, pt[1]))

        if not moved:
            break

    return [(x, y) for x, y in pts]


def update_grid_for_frame(scene: bpy.types.Scene) -> None:
    """Update vertex Z heights, `interference` attribute, and tracking Empties."""
    obj = bpy.data.objects.get(OBJECT_NAME)
    if obj is None or obj.type != "MESH":
        return

    fps = scene.render.fps if scene.render.fps > 0 else FPS
    t = scene.frame_current / fps

    values = compute_wave_field(t)
    z_coords = values * AMPLITUDE

    coords = np.column_stack((_X, _Y, z_coords)).ravel()

    mesh = obj.data
    mesh.vertices.foreach_set("co", coords)

    attr = mesh.attributes.get(ATTR_NAME)
    if attr is None or attr.domain != "POINT" or attr.data_type != "FLOAT":
        if attr is not None:
            mesh.attributes.remove(attr)
        attr = mesh.attributes.new(name=ATTR_NAME, type="FLOAT", domain="POINT")

    attr.data.foreach_set("value", values)
    mesh.update()

    empties = ensure_source_empties()
    update_source_empties(t, empties)


def register_interference_handler() -> None:
    """Replace any previous handler from this script so re-running doesn't duplicate."""
    handlers = bpy.app.handlers.frame_change_pre
    to_remove = [h for h in handlers if getattr(h, "_is_interference_handler", False)]
    for h in to_remove:
        handlers.remove(h)

    def _on_frame_change(scene, depsgraph=None):
        update_grid_for_frame(scene)

    _on_frame_change._is_interference_handler = True
    handlers.append(_on_frame_change)


if __name__ == "__main__":
    ensure_base_grid_object()
    ensure_source_empties()
    register_interference_handler()
    update_grid_for_frame(bpy.context.scene)
    print("Interference handler + source Empties active.")