To create a high-definition, progressively zooming Mandelbrot video on an RTX 3090 GPU, we can use CuPy, which compiles CUDA kernels on the fly.
To achieve the best visual quality, this script renders each frame at 8K resolution (7680x4320) and then down samples it to 4K (3840x2160). This technique, known as Super-Sample Anti-Aliasing (SSAA), removes jagged edges and creates incredibly crisp, cinematic fractal filaments. It also employs a continuous smooth-coloring algorithm to eliminate color banding as you zoom.
a)
Prerequisites
You will need the CUDA toolkit installed on your system, along with a few Python libraries:
Bash
pip install cupy-cuda12x numpy opencv-python
The Python Program
import cupy as cp
import numpy as np
import cv2
import time
# --- CONFIGURATION ---
# Target 4K Output, Rendered at 8K for Super-Sample Anti-Aliasing (SSAA)
WIDTH_8K, HEIGHT_8K = 7680, 4320
WIDTH_4K, HEIGHT_4K = 3840, 2160
# Video Settings
FPS = 60
TOTAL_FRAMES = 600 # 10 seconds at 60fps
ZOOM_FACTOR = 0.97 # Scale multiplier per frame (closer to 1.0 = slower zoom)
# Target coordinates (A visually interesting mini-mandelbrot in Seahorse Valley)
CENTER_X = -0.743643887037151
CENTER_Y = 0.131825904205330
INITIAL_SCALE = 3.0 / WIDTH_8K
# --- CUDA KERNEL ---
# This calculates the Mandelbrot set with continuous smooth coloring
mandelbrot_kernel = cp.ElementwiseKernel(
'float64 x, float64 y, int32 max_iter',
'float32 smooth_iter',
'''
double c_real = x;
double c_imag = y;
double z_real = 0.0;
double z_imag = 0.0;
int i = 0;
double r2 = 0.0, i2 = 0.0;
// Using an escape radius of 256.0 for better smooth coloring
for(; i < max_iter; ++i) {
r2 = z_real * z_real;
i2 = z_imag * z_imag;
if(r2 + i2 > 256.0) break;
z_imag = 2.0 * z_real * z_imag + c_imag;
z_real = r2 - i2 + c_real;
}
if (i < max_iter) {
// Continuous smooth iteration calculation
double log_zn = log(r2 + i2) / 2.0;
double nu = log(log_zn / 0.6931471805599453) / 0.6931471805599453; // ln(2)
smooth_iter = (float)(i + 1 - nu);
} else {
smooth_iter = (float)max_iter;
}
''',
'smooth_mandelbrot'
)
def get_color_palette(iters, max_iter):
"""Applies a smooth sinusoidal color palette to the iteration counts."""
# Mask out the inside of the set (which reaches max_iter)
inside_mask = (iters >= max_iter)
# Calculate colors using phase-shifted sine waves
r = cp.sin(0.15 * iters + 0.0) * 127.5 + 127.5
g = cp.sin(0.15 * iters + 2.094) * 127.5 + 127.5 # 2.094 is approx 2pi/3
b = cp.sin(0.15 * iters + 4.188) * 127.5 + 127.5 # 4.188 is approx 4pi/3
# Stack channels (OpenCV uses BGR by default)
img = cp.stack((b, g, r), axis=-1).astype(cp.uint8)
# Set the interior of the fractal to black
img[inside_mask] = 0
return img
def main():
print(f"Starting 8K SSAA Render Pipeline on {cp.cuda.runtime.getDeviceProperties(0)['name'].decode()}")
# Setup OpenCV Video Writer
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter('mandelbrot_4k_zoom.mp4', fourcc, FPS, (WIDTH_4K, HEIGHT_4K))
current_scale = INITIAL_SCALE
for frame in range(TOTAL_FRAMES):
start_time = time.time()
# Increase max iterations as we zoom deeper to preserve detail
max_iter = int(250 + (-cp.log10(current_scale * WIDTH_8K).get()) * 150)
# Calculate the real and imaginary boundaries
x_min = CENTER_X - (WIDTH_8K / 2) * current_scale
x_max = CENTER_X + (WIDTH_8K / 2) * current_scale
y_min = CENTER_Y - (HEIGHT_8K / 2) * current_scale
y_max = CENTER_Y + (HEIGHT_8K / 2) * current_scale
# Generate the coordinate grid directly on the GPU
x_coords = cp.linspace(x_min, x_max, WIDTH_8K, dtype=cp.float64)
y_coords = cp.linspace(y_min, y_max, HEIGHT_8K, dtype=cp.float64)
X, Y = cp.meshgrid(x_coords, y_coords)
# Run the CUDA Mandelbrot kernel
iters = mandelbrot_kernel(X, Y, max_iter)
# Apply the color palette
img_8k_gpu = get_color_palette(iters, max_iter)
# Transfer the image from GPU to CPU RAM
img_8k_cpu = cp.asnumpy(img_8k_gpu)
# Downsample to 4K using Area Interpolation (Best for downscaling)
img_4k = cv2.resize(img_8k_cpu, (WIDTH_4K, HEIGHT_4K), interpolation=cv2.INTER_AREA)
# Write frame to video
out.write(img_4k)
current_scale *= ZOOM_FACTOR
fps_current = 1.0 / (time.time() - start_time)
if frame % 10 == 0:
print(f"Frame {frame}/{TOTAL_FRAMES} | Max Iter: {max_iter} | Render Speed: {fps_current:.2f} fps")
out.release()
print("Video rendering complete! Saved as mandelbrot_4k_zoom.mp4")
if __name__ == "__main__":
main()
How the Hardware Optimization Works
Memory Bandwidth: The RTX 3090's massive 24GB of GDDR6X VRAM is utilized heavily here. Standard processors would choke allocating grids for 33.1 million pixels (8K) per frame, but the 3090 handles
cp.meshgridwithout stuttering.Elementwise Compiling: Rather than looping in Python, CuPy compiles the
mandelbrot_kernelinto C++ CUDA code behind the scenes and executes it simultaneously across all 10,496 CUDA cores on the RTX 3090.Dynamic Iterations: As the
current_scalegets smaller, the program calculates that you are zooming deeper and automatically steps upmax_iterdynamically.
The Perturbation Python Program
2) Multi-Reference Python Implementation
Here is the upgraded framework. It encapsulates the references into a manager and updates the CuPy kernel to support dynamically switching reference centers.
import cupy as cp
import numpy as np
import cv2
import time
import mpmath
# --- CONFIGURATION ---
WIDTH_8K, HEIGHT_8K = 7680, 4320
WIDTH_4K, HEIGHT_4K = 3840, 2160
FPS = 60
TOTAL_FRAMES = 600
ZOOM_FACTOR = 0.85
INITIAL_SCALE = 4.0 / WIDTH_8K
MAX_ITER = 5000
SKIP_SIZE = 16
MAX_REFS = 16 # Maximum number of reference orbits to hold in VRAM
mpmath.mp.dps = 120
CENTER_X = mpmath.mpf("-1.749957683706093503602214506070699707271105797262520779302428378202860080829728048872186727844317008311005")
CENTER_Y = mpmath.mpf("0.000000000000000002787937065633794021782042378912524398563297050280644026364072225906323670977239016467362")
# --- MULTI-REFERENCE CUDA KERNEL ---
multi_ref_kernel = cp.RawKernel(r'''
extern "C" __global__
void mandelbrot_multi_ref(
const double* Ref_r, const double* Ref_i,
const double* A_r, const double* A_i,
const double* B_r, const double* B_i,
const double* R_valid,
const double* Ref_dc_r, const double* Ref_dc_i,
int num_refs, double scale, int width, int height,
int max_iter, int skip_size,
float* smooth_iters, unsigned char* glitch_mask)
{
int x = blockDim.x * blockIdx.x + threadIdx.x;
int y = blockDim.y * blockIdx.y + threadIdx.y;
if (x >= width || y >= height) return;
// Pixel's delta relative to the absolute center (Reference 0)
double absolute_dc_r = (x - width / 2.0) * scale;
double absolute_dc_i = (y - height / 2.0) * scale;
// Find the closest valid reference orbit
int best_ref = 0;
double min_dist = 1e300;
for (int k = 0; k < num_refs; k++) {
double dx = absolute_dc_r - Ref_dc_r[k];
double dy = absolute_dc_i - Ref_dc_i[k];
double dist = dx*dx + dy*dy;
if (dist < min_dist) {
min_dist = dist;
best_ref = k;
}
}
// Calculate delta relative to the chosen auxiliary reference
double dc_r = absolute_dc_r - Ref_dc_r[best_ref];
double dc_i = absolute_dc_i - Ref_dc_i[best_ref];
// Offset array pointers to the chosen reference's tables
int offset = best_ref * max_iter;
double dz_r = 0.0, dz_i = 0.0;
double r2 = 0.0, i2 = 0.0;
int i = 0;
bool glitched = false;
while (i < max_iter) {
double dz_mag2 = dz_r * dz_r + dz_i * dz_i;
// BLA Jump
if (i + skip_size < max_iter && dz_mag2 < R_valid[offset + i]) {
double next_dz_r = A_r[offset + i] * dz_r - A_i[offset + i] * dz_i + B_r[offset + i] * dc_r - B_i[offset + i] * dc_i;
double next_dz_i = A_r[offset + i] * dz_i + A_i[offset + i] * dz_r + B_r[offset + i] * dc_i + B_i[offset + i] * dc_r;
dz_r = next_dz_r;
dz_i = next_dz_i;
i += skip_size;
}
// Standard Perturbation Step
else {
double zr = Ref_r[offset + i];
double zi = Ref_i[offset + i];
double zdz_r = zr * dz_r - zi * dz_i;
double zdz_i = zr * dz_i + zi * dz_r;
dz_r = 2.0 * zdz_r + (dz_r * dz_r - dz_i * dz_i) + dc_r;
dz_i = 2.0 * zdz_i + (2.0 * dz_r * dz_i) + dc_i;
i++;
}
double z_total_r = Ref_r[offset + i] + dz_r;
double z_total_i = Ref_i[offset + i] + dz_i;
r2 = z_total_r * z_total_r;
i2 = z_total_i * z_total_i;
if (r2 + i2 > 256.0) break;
// Glitch Detection: Delta magnitude vs Reference magnitude
if (dz_mag2 > 0.5 * (r2 + i2) && (r2 + i2) < 0.1) {
glitched = true;
break;
}
}
int idx = y * width + x;
glitch_mask[idx] = glitched ? 1 : 0;
if (!glitched && i < max_iter) {
double log_zn = log(r2 + i2) / 2.0;
double nu = log(log_zn / 0.6931471805599453) / 0.6931471805599453;
smooth_iters[idx] = (float)(i + 1 - nu);
} else {
smooth_iters[idx] = (float)max_iter; // Keep glitch regions dark or mark for rebasing
}
}
''', 'mandelbrot_multi_ref')
class ReferenceManager:
def __init__(self, c_base, max_iter, skip_size):
self.c_base = c_base
self.max_iter = max_iter
self.skip_size = skip_size
# Flattened buffers for GPU
self.ref_r = np.zeros(MAX_REFS * max_iter, dtype=np.float64)
self.ref_i = np.zeros(MAX_REFS * max_iter, dtype=np.float64)
self.A_r = np.zeros(MAX_REFS * max_iter, dtype=np.float64)
self.A_i = np.zeros(MAX_REFS * max_iter, dtype=np.float64)
self.B_r = np.zeros(MAX_REFS * max_iter, dtype=np.float64)
self.B_i = np.zeros(MAX_REFS * max_iter, dtype=np.float64)
self.R_valid = np.zeros(MAX_REFS * max_iter, dtype=np.float64)
# Track offsets relative to the main center (float64 is fine for deltas)
self.ref_dc_r = np.zeros(MAX_REFS, dtype=np.float64)
self.ref_dc_i = np.zeros(MAX_REFS, dtype=np.float64)
self.active_refs = 0
# Create primary reference (Index 0)
self.add_reference(mpmath.mpc(0, 0), 0.0, 0.0)
def add_reference(self, offset_c_high, dc_r_float, dc_i_float):
if self.active_refs >= MAX_REFS: return False
idx = self.active_refs
offset = idx * self.max_iter
c_val = self.c_base + offset_c_high
z = mpmath.mpc(0, 0)
print(f"Spawning Reference {idx} at delta ({dc_r_float:.2e}, {dc_i_float:.2e})")
# Calculate Orbit and BLA Tables for this new center
temp_r = np.zeros(self.max_iter + self.skip_size, dtype=np.float64)
temp_i = np.zeros(self.max_iter + self.skip_size, dtype=np.float64)
for i in range(self.max_iter + self.skip_size):
temp_r[i] = float(z.real)
temp_i[i] = float(z.imag)
z = z*z + c_val
for i in range(self.max_iter):
curr_A = complex(1.0, 0.0)
curr_B = complex(0.0, 0.0)
for s in range(self.skip_size):
Z = complex(temp_r[i + s], temp_i[i + s])
curr_B = 2.0 * Z * curr_B + 1.0
curr_A = 2.0 * Z * curr_A
self.ref_r[offset + i] = temp_r[i]
self.ref_i[offset + i] = temp_i[i]
self.A_r[offset + i] = curr_A.real
self.A_i[offset + i] = curr_A.imag
self.B_r[offset + i] = curr_B.real
self.B_i[offset + i] = curr_B.imag
self.R_valid[offset + i] = (1e-5 / (abs(curr_A) + 1e-12)) ** 2
self.ref_dc_r[idx] = dc_r_float
self.ref_dc_i[idx] = dc_i_float
self.active_refs += 1
return True
def to_gpu(self):
return (cp.asarray(self.ref_r), cp.asarray(self.ref_i),
cp.asarray(self.A_r), cp.asarray(self.A_i),
cp.asarray(self.B_r), cp.asarray(self.B_i),
cp.asarray(self.R_valid),
cp.asarray(self.ref_dc_r), cp.asarray(self.ref_dc_i))
3. Rendering Pipeline with Probing
In your main() render loop, run a small probe frame first. If glitches are flagged, calculate the centroid of the glitched mask, convert that position into high-precision mpmath coordinates relative to your root center, and feed it into add_reference().
When you create a cinematic fractal video, the camera doesn't just zoom straight in—it pans across the complex plane following a curved spline through waypoints.
As you pan, the screen center drifts away from your root c_base. Eventually, the offset distance (e.g., $10^{-3}) becomes so much larger than the width of your viewport (e.g., $10^{-20}) that adding the tiny pixel coordinates to the camera offset causes standard 64-bit floats to truncate the tiny digits. This is known as loss of significance, and it immediately pixelates the frame.
To fix this, you must periodically move the arbitrary-precision root coordinate to match the exact center of your camera, and mathematically shift all active auxiliary references backwards to compensate.
1. The Root Re-basing Method
Add this method to your Reference Manager class. It safely uproots Index 0 and adjusts the dc (delta C) of all other active references so the GPU kernel doesn't notice the shift.
To smoothly pan the camera while zooming, you cannot use standard linear interpolation. Linear panning creates jarring, robotic direction changes at every waypoint, and linear zooming feels like the camera is abruptly decelerating as it gets deeper.
A professional deep zoom engine uses two separate interpolation curves:
Exponential Interpolation for Zoom: The scale must multiply by a constant fraction over time so the perceived speed of diving into the fractal remains constant.
Catmull-Rom Splines for Panning: This generates a smooth, curved path through arbitrary-precision coordinates in the complex plane, ensuring the camera's velocity and direction never instantly snap.
Arbitrary-Precision Spline Interpolator
This implementation uses mpmath to calculate a Catmull-Rom spline. It requires 4 control points to calculate the curve between the middle two, ensuring smooth entry and exit vectors.
import mpmath
class Keyframe:
def __init__(self, frame: int, center_c: mpmath.mpc, scale: mpmath.mpf):
self.frame = frame
self.center = center_c
self.scale = scale
class CameraAnimator:
def __init__(self, keyframes):
"""
keyframes: A list of Keyframe objects sorted by frame number.
Must have at least 4 keyframes for a proper Catmull-Rom spline.
"""
self.keyframes = sorted(keyframes, key=lambda k: k.frame)
def get_state(self, current_frame: int):
# 1. Handle edge cases (before first frame or after last frame)
if current_frame <= self.keyframes[0].frame:
return self.keyframes[0].center, self.keyframes[0].scale
if current_frame >= self.keyframes[-1].frame:
return self.keyframes[-1].center, self.keyframes[-1].scale
# 2. Find the relevant keyframe segment
idx = 0
for i in range(len(self.keyframes) - 1):
if self.keyframes[i].frame <= current_frame < self.keyframes[i+1].frame:
idx = i
break
# 3. Get the 4 control points for the Catmull-Rom spline
# If we are at the boundaries, we duplicate the end points to flatten the curve
p0 = self.keyframes[max(0, idx - 1)]
p1 = self.keyframes[idx]
p2 = self.keyframes[idx + 1]
p3 = self.keyframes[min(len(self.keyframes) - 1, idx + 2)]
# 4. Calculate normalized time 't' (0.0 to 1.0) between p1 and p2
frame_range = p2.frame - p1.frame
t = mpmath.mpf(current_frame - p1.frame) / mpmath.mpf(frame_range)
# 5. Exponential Interpolation for Scale
# S(t) = S1 * (S2 / S1)^t
scale = p1.scale * mpmath.power(p2.scale / p1.scale, t)
# 6. Catmull-Rom Spline Interpolation for Position (Arbitrary Precision)
# P(t) = 0.5 * ( (2*P1) + (-P0 + P2)*t + (2*P0 - 5*P1 + 4*P2 - P3)*t^2 + (-P0 + 3*P1 - 3*P2 + P3)*t^3 )
t2 = t * t
t3 = t2 * t
c0 = p0.center
c1 = p1.center
c2 = p2.center
c3 = p3.center
term1 = 2.0 * c1
term2 = (-c0 + c2) * t
term3 = (2.0*c0 - 5.0*c1 + 4.0*c2 - c3) * t2
term4 = (-c0 + 3.0*c1 - 3.0*c2 + c3) * t3
center = 0.5 * (term1 + term2 + term3 + term4)
return center, scale
Integrating the Animator into the Main Loop
To use this, define your cinematic path using exact mpmath coordinates and frame numbers before starting the render loop. Then, query the animator for the exact camera position on each frame.
# 1. Define your arbitrary-precision waypoints
mpmath.mp.dps = 120
waypoints = [
Keyframe(0, mpmath.mpc("-0.5", "0.0"), mpmath.mpf("3.0")), # Zoomed out
Keyframe(300, mpmath.mpc("-0.7436", "0.1318"), mpmath.mpf("0.05")), # Seahorse valley
Keyframe(900, mpmath.mpc("-0.74364388", "0.13182590"), mpmath.mpf("1e-6")), # Deeper
Keyframe(1800, mpmath.mpc(CENTER_X, CENTER_Y), mpmath.mpf("1e-25")), # Target deep dive
Keyframe(2400, mpmath.mpc(CENTER_X, CENTER_Y), mpmath.mpf("1e-45")) # Final hold/zoom
]
animator = CameraAnimator(waypoints)
# 2. Main Render Loop
for frame in range(TOTAL_FRAMES):
start_time = time.time()
# Get exact camera state for this specific frame
exact_camera_center, current_scale = animator.get_state(frame)
# Calculate drift from root for re-basing (from previous multi-reference logic)
camera_offset_exact = exact_camera_center - ref_mgr.c_base
dist_from_root = float(abs(camera_offset_exact))
if dist_from_root > 10000.0 * float(WIDTH_8K * current_scale):
ref_mgr.rebase_root(exact_camera_center)
ref_mgr.prune_offscreen_references(current_scale, WIDTH_8K, HEIGHT_8K)
# Recalculate offset after rebasing (should now be 0.0)
camera_offset_exact = exact_camera_center - ref_mgr.c_base
# 3. Update Kernel with the exact floating point offsets relative to root
dc_r_float = float(camera_offset_exact.real)
dc_i_float = float(camera_offset_exact.imag)
# (Execute multi-ref kernel using dc_r_float and dc_i_float as the camera position)
Watching how these smooth curves look in motion will help you tune the timing between your keyframes so the camera glides naturally into the spirals
How to implement temporal accumulation to add cinematic motion blur to the 8K fractal frames.
To create realistic, cinematic motion blur, you must simulate how a physical camera sensor captures light over time. Instead of rendering a single instant in time for each video frame, you render multiple sub-frames across the duration the "shutter" is open, and mathematically average their RGB values together.
This process, known as Temporal Accumulation, completely eliminates the "strobe effect" during fast camera pans or aggressive zooms, resulting in buttery smooth motion.
The Mathematics of Shutter Angles
In cinema, motion blur is controlled by the Shutter Angle.
A 360-degree shutter is open for the entire duration of a frame (maximum blur).
A 180-degree shutter (the Hollywood standard) is open for half the frame's duration (e.g., at 60 FPS, the shutter is open for $1/120^{\text{th}}$ of a second).
A 90-degree shutter is open for a quarter of the frame (sharp, staccato action, like in Saving Private Ryan).
To implement this, you slice the shutter-open duration into $N$ temporal samples. The RTX 3090's massive 24GB VRAM makes this highly efficient, as you can hold a 32-bit floating-point accumulation buffer for the entire 8K canvas directly on the GPU without swapping memory.
Upgrading the Main Render Loop
Replace your main() render loop with this temporal accumulation setup. It heavily utilizes the Camera Animator from the previous step to fetch fractional, sub-frame coordinates.
# --- CINEMATIC MOTION BLUR SETTINGS ---
SUB_SAMPLES = 8 # Number of sub-frames to render per final frame (higher = smoother but slower)
SHUTTER_ANGLE = 180.0 # 180 is cinematic standard. 360 is maximum blur.
def main():
# Precompute Reference Orbit and BLA tables
d_ref_r, d_ref_i, d_A_r, d_A_i, d_B_r, d_B_i, d_R_valid = compute_reference_and_bla(MAX_POSSIBLE_ITER, SKIP_SIZE)
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter('mandelbrot_4k_cinematic.mp4', fourcc, FPS, (WIDTH_4K, HEIGHT_4K))
block_size = (16, 16)
grid_size = (int(np.ceil(WIDTH_8K / 16)), int(np.ceil(HEIGHT_8K / 16)))
# 1. Allocate GPU Buffers
d_smooth_iters = cp.zeros((HEIGHT_8K, WIDTH_8K), dtype=cp.float32)
# 32-bit float accumulation buffer is REQUIRED.
# Adding 8 sub-frames of 8-bit RGB values will immediately overflow 255.
d_accum_buffer = cp.zeros((HEIGHT_8K, WIDTH_8K, 3), dtype=cp.float32)
# Calculate what fraction of the frame time the shutter is open
shutter_fraction = SHUTTER_ANGLE / 360.0
for frame in range(TOTAL_FRAMES):
start_time = time.time()
# Clear the accumulation buffer for the new frame
d_accum_buffer.fill(0.0)
# Determine base iterations for this frame depth
_, base_scale = animator.get_state(frame)
current_max_iter = min(MAX_POSSIBLE_ITER, int(500 + (-np.log10(float(base_scale))) * 100))
# --- TEMPORAL ACCUMULATION LOOP ---
for sub in range(SUB_SAMPLES):
# Calculate exact fractional time for this sub-frame
# E.g., for frame 10 and 180-deg shutter, time goes from 10.0 to 10.5
temporal_offset = (sub / max(1, SUB_SAMPLES - 1)) * shutter_fraction
exact_time = frame + temporal_offset
# Query the Spline Animator for the precise sub-frame camera state
exact_camera_center, current_scale = animator.get_state(exact_time)
# Rebase check (Standard multi-reference logic)
camera_offset_exact = exact_camera_center - ref_mgr.c_base
dist_from_root = float(abs(camera_offset_exact))
if dist_from_root > 10000.0 * float(WIDTH_8K * current_scale):
ref_mgr.rebase_root(exact_camera_center)
ref_mgr.prune_offscreen_references(current_scale, WIDTH_8K, HEIGHT_8K)
camera_offset_exact = exact_camera_center - ref_mgr.c_base
dc_r_float = float(camera_offset_exact.real)
dc_i_float = float(camera_offset_exact.imag)
# Execute BLA Perturbation Kernel for this sub-frame
multi_ref_kernel(
grid_size, block_size,
(*ref_mgr.to_gpu(),
ref_mgr.active_refs, np.float64(current_scale),
WIDTH_8K, HEIGHT_8K, current_max_iter, SKIP_SIZE,
dc_r_float, dc_i_float,
d_smooth_iters)
)
# Generate uint8 RGB image for the sub-frame, cast to float32, and add to accumulator
img_8k_gpu = get_color_palette(d_smooth_iters, current_max_iter)
d_accum_buffer += img_8k_gpu.astype(cp.float32)
# --- FINALIZE FRAME ---
# 1. Average the sub-frames
d_accum_buffer /= SUB_SAMPLES
# 2. Cast back to 8-bit RGB and transfer to CPU
final_img_8k_cpu = cp.asnumpy(d_accum_buffer.astype(cp.uint8))
# 3. Apply SSAA Downscale to 4K
final_4k_cpu = cv2.resize(final_img_8k_cpu, (WIDTH_4K, HEIGHT_4K), interpolation=cv2.INTER_AREA)
# Write to video file
out.write(final_4k_cpu)
fps_current = 1.0 / (time.time() - start_time)
if frame % 10 == 0:
print(f"Frame {frame}/{TOTAL_FRAMES} | Sub-frames: {SUB_SAMPLES} | {fps_current:.2f} final fps")
out.release()
print("Video rendering complete! Saved as mandelbrot_4k_cinematic.mp4")
Performance Considerations
Rendering 8 sub-frames means the GPU is doing exactly 8 times the mathematical workload per final frame. However, by accumulating purely in VRAM (d_accum_buffer += img_8k_gpu), you avoid the catastrophic PCIe bottleneck that would occur if you tried to transfer all 8 sub-frames to the CPU to average them in numpy.
The video below demonstrates how motion blur combined with deep zooming creates a tangible sense of speed and scale that raw, sharp frames lack.
How to add a GPU-accelerated post-processing bloom and glow effect to the fractal filaments before exporting
To add a cinematic bloom (glow) effect, you extract the brightest pixels in your image, blur them to simulate light scattering across a camera lens, and add them back to the original frame.
Since your pipeline is already operating on the RTX 3090 via CuPy, doing this entirely in VRAM on the accumulated float32 buffer ensures it takes only milliseconds per frame without any PCIe transfer bottlenecks.
The CuPy Bloom Implementation
You will need to import CuPy's GPU-accelerated SciPy equivalent for the Gaussian filter:
import cupyx.scipy.ndimage as ndimage
Add this apply_bloom function above your main() loop. It operates directly on the 32-bit floating-point accumulation buffer before it is converted to an 8-bit image.
def apply_bloom(d_float_img, threshold=180.0, sigma=15.0, intensity=1.2):
"""
Applies a GPU-accelerated bloom effect to a float32 CuPy image buffer.
threshold: Minimum brightness (0-255) for a pixel to emit glow.
sigma: The spread/radius of the blur.
intensity: How bright the blended glow should be.
"""
# 1. Calculate Perceived Luminance (Rec. 709 Standard)
# OpenCV stores as BGR, so index 0=Blue, 1=Green, 2=Red
luminance = (0.0722 * d_float_img[:, :, 0] +
0.7152 * d_float_img[:, :, 1] +
0.2126 * d_float_img[:, :, 2])
# 2. Thresholding: Isolate only the brightest pixels
# Create a 3D mask by expanding the dimensions to match (H, W, 3)
bloom_mask = (luminance > threshold)[:, :, cp.newaxis]
d_highlights = d_float_img * bloom_mask
# 3. GPU Gaussian Blur
# Applying it per-channel prevents color channels from bleeding into one another incorrectly
d_blurred_highlights = cp.empty_like(d_highlights)
for channel in range(3):
d_blurred_highlights[:, :, channel] = ndimage.gaussian_filter(
d_highlights[:, :, channel],
sigma=sigma
)
# 4. Additive Blending: Screen the glow over the original image
d_final = d_float_img + (d_blurred_highlights * intensity)
# 5. Clip overflow values back to the 0-255 visible range
return cp.clip(d_final, 0, 255.0)
Performance Optimization Note
If you increase the sigma to a very large number (e.g., 50+) for a massive, screen-wide glow, the gaussian_filter will start to slow down the 8K render. To optimize large sigmas, you can slice the d_highlights array to process the blur at a lower resolution (e.g., 1080p), and then upscale it back to 8K before blending. Because glow is inherently blurry, the lost resolution during the downscale is entirely unnoticeable.
To tie your color palette to the zoom depth, you must convert the camera's current scale into a linear depth metric using a base-10 logarithm. For example, a scale of $10^{-5}$ becomes a depth of $5$, and a scale of $10^{-100}$ becomes a depth of $100$.
You can then use this depth value to dynamically drive the frequencies and phase shifts of the sine waves generating your colors directly on the GPU.
Method 1: Procedural Phase Shifting
The easiest way to evolve the colors is to push the sine wave phases forward or backward based on the depth. This causes the color gradient to slowly morph through different hues as the camera dives.
Replace your static get_color_palette function with this depth-aware version:
def get_dynamic_color_palette(iters, max_iter, current_scale):
"""
Generates a color palette that organically shifts hues based on zoom depth.
"""
# 1. Calculate logarithmic depth (e.g., scale 10^-50 -> depth 50.0)
# cp.log10 returns a 0D CuPy array, so we use .get() to extract the float
depth = float(-cp.log10(current_scale).get())
# 2. Define how fast the colors change
# A phase shift of 2*pi means a full color wheel rotation.
# Here, the colors complete one full cycle every 20 orders of magnitude.
color_cycle_speed = 20.0
phase_shift = (depth / color_cycle_speed) * 2.0 * np.pi
inside_mask = (iters >= max_iter)
# 3. Dynamic Sine Waves
# Base frequency for how tightly packed the color bands are
freq = 0.15
# Red: Shifts forward as we zoom
r = cp.sin(freq * iters + 0.0 + phase_shift) * 127.5 + 127.5
# Green: Shifts backward at half speed
g = cp.sin(freq * iters + 2.094 - (phase_shift * 0.5)) * 127.5 + 127.5
# Blue: Shifts forward rapidly, and the frequency increases slightly at extreme depths
dynamic_freq_b = freq + (depth * 0.0005)
b = cp.sin(dynamic_freq_b * iters + 4.188 + (phase_shift * 1.5)) * 127.5 + 127.5
img = cp.stack((b, g, r), axis=-1).astype(cp.uint8)
img[inside_mask] = 0
return img
Method 2: Keyframed Palette Blending (Cinematic Control)
If you want precise control—for example, starting with an "Electric Blue" theme and smoothly fading into a "Molten Gold" theme exactly at $10^{-30}$ depth—you can interpolate between predefined arrays of phase vectors.
def get_keyframed_palette(iters, max_iter, current_scale):
"""
Smoothly interpolates between exact color themes based on depth milestones.
"""
depth = float(-cp.log10(current_scale).get())
# Define color themes as (Red Phase, Green Phase, Blue Phase)
THEME_ELECTRIC_BLUE = np.array([3.14, 1.0, 0.0])
THEME_MOLTEN_GOLD = np.array([0.0, 1.0, 3.14])
THEME_NEON_PURPLE = np.array([0.0, 3.14, 0.5])
# Determine the blend factor based on current depth
if depth < 30.0:
# Depth 0 to 30: Blend Electric Blue -> Molten Gold
t = depth / 30.0
current_phases = (1.0 - t) * THEME_ELECTRIC_BLUE + t * THEME_MOLTEN_GOLD
else:
# Depth 30 to 60: Blend Molten Gold -> Neon Purple
# (Clamp 't' to 1.0 so it stays purple past depth 60)
t = min(1.0, (depth - 30.0) / 30.0)
current_phases = (1.0 - t) * THEME_MOLTEN_GOLD + t * THEME_NEON_PURPLE
inside_mask = (iters >= max_iter)
freq = 0.15
# Apply the interpolated phases
r = cp.sin(freq * iters + current_phases[0]) * 127.5 + 127.5
g = cp.sin(freq * iters + current_phases[1]) * 127.5 + 127.5
b = cp.sin(freq * iters + current_phases[2]) * 127.5 + 127.5
img = cp.stack((b, g, r), axis=-1).astype(cp.uint8)
img[inside_mask] = 0
return img
Updating the Render Loop
Whether you use the procedural or keyframed method, update the color palette call inside your sub-frame temporal accumulation loop to pass the current fractional scale:

