Repository navigation
Expand file tree
/
Copy pathbenchmark.py
More file actions
244 lines (190 loc) · 8.39 KB
/
Copy pathbenchmark.py
File metadata and controls
244 lines (190 loc) · 8.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
#!/usr/bin/env python
"""
Benchmark: vectorized NumPy renderer vs. a naive pure-Python ray-by-ray tracer.
Both tracers render the *same* scene with the *same* maths — the only difference
is that one processes the whole image as NumPy arrays while the other loops over
every pixel in pure Python. The script renders both at a range of resolutions,
plots wall-clock time vs. pixel count, and reports the speed-up.
python benchmark.py --out docs/benchmark.png
"""
from __future__ import annotations
import argparse
import math
import random
import time
import numpy as np
from raytracer.materials import Dielectric, Lambertian, Metal
from raytracer.renderer import render
from raytracer.scenes import showcase_camera, showcase_scene
# --------------------------------------------------------------------------- #
# Naive, pure-Python reference implementation (no NumPy in the hot path).
# This is intentionally the "obvious" way to write a ray tracer, one ray at a
# time, so the benchmark shows what vectorization buys us.
# --------------------------------------------------------------------------- #
Vec = tuple[float, float, float]
def _sub(a: Vec, b: Vec) -> Vec:
return (a[0] - b[0], a[1] - b[1], a[2] - b[2])
def _add(a: Vec, b: Vec) -> Vec:
return (a[0] + b[0], a[1] + b[1], a[2] + b[2])
def _scale(a: Vec, s: float) -> Vec:
return (a[0] * s, a[1] * s, a[2] * s)
def _dot(a: Vec, b: Vec) -> float:
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
def _norm(a: Vec) -> Vec:
inv = 1.0 / math.sqrt(_dot(a, a))
return (a[0] * inv, a[1] * inv, a[2] * inv)
def _reflect(v: Vec, n: Vec) -> Vec:
d = 2.0 * _dot(v, n)
return (v[0] - d * n[0], v[1] - d * n[1], v[2] - d * n[2])
def _random_unit(rng: random.Random) -> Vec:
while True:
x, y, z = rng.gauss(0, 1), rng.gauss(0, 1), rng.gauss(0, 1)
d2 = x * x + y * y + z * z
if d2 > 1e-12:
inv = 1.0 / math.sqrt(d2)
return (x * inv, y * inv, z * inv)
def _extract_spheres(scene) -> list[dict]:
"""Flatten the OO scene into plain dicts the naive tracer can consume."""
spheres = []
for obj in scene.objects:
mat = obj.material
if isinstance(mat, Lambertian):
m = {"kind": "lambertian", "albedo": tuple(mat.albedo)}
elif isinstance(mat, Metal):
m = {"kind": "metal", "albedo": tuple(mat.albedo), "fuzz": mat.fuzz}
elif isinstance(mat, Dielectric):
m = {"kind": "dielectric", "ir": mat.ir}
else: # pragma: no cover
m = {"kind": "lambertian", "albedo": (0.5, 0.5, 0.5)}
spheres.append({"center": tuple(obj.center), "radius": float(obj.radius), "mat": m})
return spheres
def _background(d: Vec) -> Vec:
u = _norm(d)
t = 0.5 * (u[1] + 1.0)
return (1.0 - t + t * 0.5, 1.0 - t + t * 0.7, 1.0 - t + t * 1.0)
def _hit_scene(o: Vec, d: Vec, spheres, t_min: float, t_max: float):
best_t, best = t_max, None
for sph in spheres:
oc = _sub(o, sph["center"])
a = _dot(d, d)
half_b = _dot(oc, d)
c = _dot(oc, oc) - sph["radius"] ** 2
disc = half_b * half_b - a * c
if disc <= 0:
continue
sq = math.sqrt(disc)
for root in ((-half_b - sq) / a, (-half_b + sq) / a):
if t_min < root < best_t:
best_t, best = root, sph
break
return best_t, best
def _naive_trace(o: Vec, d: Vec, spheres, depth: int, rng: random.Random) -> Vec:
if depth <= 0:
return (0.0, 0.0, 0.0)
t, sph = _hit_scene(o, d, spheres, 1e-3, math.inf)
if sph is None:
return _background(d)
p = _add(o, _scale(d, t))
outward = _scale(_sub(p, sph["center"]), 1.0 / sph["radius"])
front = _dot(d, outward) < 0
n = outward if front else _scale(outward, -1.0)
mat = sph["mat"]
if mat["kind"] == "lambertian":
direction = _add(n, _random_unit(rng))
col = _naive_trace(p, direction, spheres, depth - 1, rng)
a = mat["albedo"]
return (a[0] * col[0], a[1] * col[1], a[2] * col[2])
if mat["kind"] == "metal":
refl = _reflect(_norm(d), n)
fz = mat["fuzz"]
if fz:
ru = _random_unit(rng)
refl = (refl[0] + fz * ru[0], refl[1] + fz * ru[1], refl[2] + fz * ru[2])
if _dot(refl, n) <= 0:
return (0.0, 0.0, 0.0)
col = _naive_trace(p, refl, spheres, depth - 1, rng)
a = mat["albedo"]
return (a[0] * col[0], a[1] * col[1], a[2] * col[2])
# dielectric
ir = mat["ir"]
ratio = (1.0 / ir) if front else ir
ud = _norm(d)
cos_theta = min(_dot(_scale(ud, -1.0), n), 1.0)
sin_theta = math.sqrt(max(0.0, 1.0 - cos_theta * cos_theta))
r0 = ((1 - ratio) / (1 + ratio)) ** 2
reflectance = r0 + (1 - r0) * (1 - cos_theta) ** 5
if ratio * sin_theta > 1.0 or reflectance > rng.random():
direction = _reflect(ud, n)
else:
r_perp = _scale(_add(ud, _scale(n, cos_theta)), ratio)
k = -math.sqrt(abs(1.0 - _dot(r_perp, r_perp)))
direction = _add(r_perp, _scale(n, k))
return _naive_trace(p, direction, spheres, depth - 1, rng)
def naive_render(scene, camera, width: int, height: int, depth: int, seed: int = 0):
spheres = _extract_spheres(scene)
rng = random.Random(seed)
for y in range(height):
t = (height - 1 - y + 0.5) / height
for x in range(width):
s = (x + 0.5) / width
o = tuple(camera.origin)
d = (
camera.lower_left_corner[0] + s * camera.horizontal[0] + t * camera.vertical[0] - o[0],
camera.lower_left_corner[1] + s * camera.horizontal[1] + t * camera.vertical[1] - o[1],
camera.lower_left_corner[2] + s * camera.horizontal[2] + t * camera.vertical[2] - o[2],
)
_naive_trace(o, d, spheres, depth, rng) # result discarded; we time the work
# --------------------------------------------------------------------------- #
# Benchmark driver
# --------------------------------------------------------------------------- #
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--widths", type=int, nargs="+", default=[24, 32, 48, 64, 96],
help="image widths (16:9) to benchmark")
parser.add_argument("--depth", type=int, default=8, help="max bounces per ray")
parser.add_argument("--out", type=str, default="docs/benchmark.png", help="output chart path")
args = parser.parse_args()
scene = showcase_scene()
print(f"{'pixels':>9} {'naive (s)':>11} {'vector (s)':>11} {'speedup':>9}")
print("-" * 44)
pixels, naive_times, vec_times = [], [], []
for width in args.widths:
height = int(round(width / (16 / 9)))
camera = showcase_camera(aspect=width / height, angle_deg=25.0)
n_px = width * height
t0 = time.perf_counter()
naive_render(scene, camera, width, height, depth=args.depth, seed=0)
t_naive = time.perf_counter() - t0
t0 = time.perf_counter()
render(scene, camera, width=width, height=height, samples=1,
max_depth=args.depth, seed=0, progress=False)
t_vec = time.perf_counter() - t0
pixels.append(n_px)
naive_times.append(t_naive)
vec_times.append(t_vec)
print(f"{n_px:>9} {t_naive:>11.3f} {t_vec:>11.3f} {t_naive / t_vec:>8.1f}x")
_plot(pixels, naive_times, vec_times, args.out)
def _plot(pixels, naive_times, vec_times, out: str) -> None:
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from pathlib import Path
speedup = naive_times[-1] / vec_times[-1]
fig, ax = plt.subplots(figsize=(8, 5))
ax.plot(pixels, naive_times, "o-", color="#d1495b", label="Pure Python (ray-by-ray)")
ax.plot(pixels, vec_times, "o-", color="#2e7d32", label="Vectorized (NumPy)")
ax.set_xscale("log")
ax.set_yscale("log")
ax.set_xlabel("Pixels (rays at 1 sample/pixel)")
ax.set_ylabel("Render time (seconds)")
ax.set_title(f"Vectorization speed-up: ~{speedup:.0f}x at {pixels[-1]:,} pixels")
ax.grid(True, which="both", linestyle="--", alpha=0.35)
ax.legend()
fig.tight_layout()
path = Path(out)
path.parent.mkdir(parents=True, exist_ok=True)
fig.savefig(path, dpi=130)
print(f"Saved chart -> {path}")
if __name__ == "__main__":
main()