Debian Codegraph @

test/expensive_benchmarks/bm_raytrace.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 """
3 This file contains definitions for a simple raytracer.
4 Copyright Callum and Tony Garnock-Jones, 2008.
5
6 This file may be freely redistributed under the MIT license,
7 http://www.opensource.org/licenses/mit-license.php
8
9 From http://www.lshift.net/blog/2008/10/29/toy-raytracer-in-python
10 """
11
12 import argparse
13 import array
14 import math
15 from time import perf_counter
16
17 import pyperf
18
19
20 DEFAULT_WIDTH = 100
21 DEFAULT_HEIGHT = 100
22 EPSILON = 0.00001
23
24
25 class Vector(object):
26
27 def __init__(self, initx, inity, initz):
28 self.x = initx
29 self.y = inity
30 self.z = initz
31
32 def __str__(self):
33 return "(%s,%s,%s)" % (self.x, self.y, self.z)
34
35 def __repr__(self):
36 return "Vector(%s,%s,%s)" % (self.x, self.y, self.z)
37
38 def magnitude(self):
39 return math.sqrt(self.dot(self))
40
41 def __add__(self, other):
42 if other.isPoint():
43 return Point(self.x + other.x, self.y + other.y, self.z + other.z)
44 else:
45 return Vector(self.x + other.x, self.y + other.y, self.z + other.z)
46
47 def __sub__(self, other):
48 other.mustBeVector()
49 return Vector(self.x - other.x, self.y - other.y, self.z - other.z)
50
51 def scale(self, factor):
52 return Vector(factor * self.x, factor * self.y, factor * self.z)
53
54 def dot(self, other):
55 other.mustBeVector()
56 return (self.x * other.x) + (self.y * other.y) + (self.z * other.z)
57
58 def cross(self, other):
59 other.mustBeVector()
60 return Vector(
61 self.y * other.z - self.z * other.y,
62 self.z * other.x - self.x * other.z,
63 self.x * other.y - self.y * other.x,
64 )
65
66 def normalized(self):
67 return self.scale(1.0 / self.magnitude())
68
69 def negated(self):
70 return self.scale(-1)
71
72 def __eq__(self, other):
73 return (self.x == other.x) and (self.y == other.y) and (self.z == other.z)
74
75 def isVector(self):
76 return True
77
78 def isPoint(self):
79 return False
80
81 def mustBeVector(self):
82 return self
83
84 def mustBePoint(self):
85 raise "Vectors are not points!"
86
87 def reflectThrough(self, normal):
88 d = normal.scale(self.dot(normal))
89 return self - d.scale(2)
90
91
92 Vector.ZERO = Vector(0, 0, 0)
93 Vector.RIGHT = Vector(1, 0, 0)
94 Vector.UP = Vector(0, 1, 0)
95 Vector.OUT = Vector(0, 0, 1)
96
97 assert Vector.RIGHT.reflectThrough(Vector.UP) == Vector.RIGHT
98 assert Vector(-1, -1, 0).reflectThrough(Vector.UP) == Vector(-1, 1, 0)
99
100
101 class Point(object):
102
103 def __init__(self, initx, inity, initz):
104 self.x = initx
105 self.y = inity
106 self.z = initz
107
108 def __str__(self):
109 return "(%s,%s,%s)" % (self.x, self.y, self.z)
110
111 def __repr__(self):
112 return "Point(%s,%s,%s)" % (self.x, self.y, self.z)
113
114 def __add__(self, other):
115 other.mustBeVector()
116 return Point(self.x + other.x, self.y + other.y, self.z + other.z)
117
118 def __sub__(self, other):
119 if other.isPoint():
120 return Vector(self.x - other.x, self.y - other.y, self.z - other.z)
121 else:
122 return Point(self.x - other.x, self.y - other.y, self.z - other.z)
123
124 def isVector(self):
125 return False
126
127 def isPoint(self):
128 return True
129
130 def mustBeVector(self):
131 raise "Points are not vectors!"
132
133 def mustBePoint(self):
134 return self
135
136
137 class Sphere(object):
138
139 def __init__(self, centre, radius):
140 centre.mustBePoint()
141 self.centre = centre
142 self.radius = radius
143
144 def __repr__(self):
145 return "Sphere(%s,%s)" % (repr(self.centre), self.radius)
146
147 def intersectionTime(self, ray):
148 cp = self.centre - ray.point
149 v = cp.dot(ray.vector)
150 discriminant = (self.radius * self.radius) - (cp.dot(cp) - v * v)
151 if discriminant < 0:
152 return None
153 else:
154 return v - math.sqrt(discriminant)
155
156 def normalAt(self, p):
157 return (p - self.centre).normalized()
158
159
160 class Halfspace(object):
161
162 def __init__(self, point, normal):
163 self.point = point
164 self.normal = normal.normalized()
165
166 def __repr__(self):
167 return "Halfspace(%s,%s)" % (repr(self.point), repr(self.normal))
168
169 def intersectionTime(self, ray):
170 v = ray.vector.dot(self.normal)
171 if v:
172 return 1 / -v
173 else:
174 return None
175
176 def normalAt(self, p):
177 return self.normal
178
179
180 class Ray(object):
181
182 def __init__(self, point, vector):
183 self.point = point
184 self.vector = vector.normalized()
185
186 def __repr__(self):
187 return "Ray(%s,%s)" % (repr(self.point), repr(self.vector))
188
189 def pointAtTime(self, t):
190 return self.point + self.vector.scale(t)
191
192
193 Point.ZERO = Point(0, 0, 0)
194
195
196 class Canvas(object):
197
198 def __init__(self, width, height):
199 self.bytes = array.array("B", [0] * (width * height * 3))
200 for i in range(width * height):
201 self.bytes[i * 3 + 2] = 255
202 self.width = width
203 self.height = height
204
205 def plot(self, x, y, r, g, b):
206 i = ((self.height - y - 1) * self.width + x) * 3
207 self.bytes[i] = max(0, min(255, int(r * 255)))
208 self.bytes[i + 1] = max(0, min(255, int(g * 255)))
209 self.bytes[i + 2] = max(0, min(255, int(b * 255)))
210
211 def write_ppm(self, filename):
212 header = "P6 %d %d 255\n" % (self.width, self.height)
213 with open(filename, "wb") as fp:
214 fp.write(header.encode("ascii"))
215 fp.write(self.bytes.tobytes())
216
217
218 def firstIntersection(intersections):
219 result = None
220 for i in intersections:
221 candidateT = i[1]
222 if candidateT is not None and candidateT > -EPSILON:
223 if result is None or candidateT < result[1]:
224 result = i
225 return result
226
227
228 class Scene(object):
229
230 def __init__(self):
231 self.objects = []
232 self.lightPoints = []
233 self.position = Point(0, 1.8, 10)
234 self.lookingAt = Point.ZERO
235 self.fieldOfView = 45
236 self.recursionDepth = 0
237
238 def moveTo(self, p):
239 self.position = p
240
241 def lookAt(self, p):
242 self.lookingAt = p
243
244 def addObject(self, object, surface):
245 self.objects.append((object, surface))
246
247 def addLight(self, p):
248 self.lightPoints.append(p)
249
250 def render(self, canvas):
251 fovRadians = math.pi * (self.fieldOfView / 2.0) / 180.0
252 halfWidth = math.tan(fovRadians)
253 halfHeight = 0.75 * halfWidth
254 width = halfWidth * 2
255 height = halfHeight * 2
256 pixelWidth = width / (canvas.width - 1)
257 pixelHeight = height / (canvas.height - 1)
258
259 eye = Ray(self.position, self.lookingAt - self.position)
260 vpRight = eye.vector.cross(Vector.UP).normalized()
261 vpUp = vpRight.cross(eye.vector).normalized()
262
263 for y in range(canvas.height):
264 for x in range(canvas.width):
265 xcomp = vpRight.scale(x * pixelWidth - halfWidth)
266 ycomp = vpUp.scale(y * pixelHeight - halfHeight)
267 ray = Ray(eye.point, eye.vector + xcomp + ycomp)
268 colour = self.rayColour(ray)
269 canvas.plot(x, y, *colour)
270
271 def rayColour(self, ray):
272 if self.recursionDepth > 3:
273 return (0, 0, 0)
274 try:
275 self.recursionDepth = self.recursionDepth + 1
276 intersections = [(o, o.intersectionTime(ray), s) for (o, s) in self.objects]
277 i = firstIntersection(intersections)
278 if i is None:
279 return (0, 0, 0) # the background colour
280 else:
281 (o, t, s) = i
282 p = ray.pointAtTime(t)
283 return s.colourAt(self, ray, p, o.normalAt(p))
284 finally:
285 self.recursionDepth = self.recursionDepth - 1
286
287 def _lightIsVisible(self, l, p):
288 for o, s in self.objects:
289 t = o.intersectionTime(Ray(p, l - p))
290 if t is not None and t > EPSILON:
291 return False
292 return True
293
294 def visibleLights(self, p):
295 result = []
296 for l in self.lightPoints:
297 if self._lightIsVisible(l, p):
298 result.append(l)
299 return result
300
301
302 def addColours(a, scale, b):
303 return (a[0] + scale * b[0], a[1] + scale * b[1], a[2] + scale * b[2])
304
305
306 class SimpleSurface(object):
307
308 def __init__(self, **kwargs):
309 self.baseColour = kwargs.get("baseColour", (1, 1, 1))
310 self.specularCoefficient = kwargs.get("specularCoefficient", 0.2)
311 self.lambertCoefficient = kwargs.get("lambertCoefficient", 0.6)
312 self.ambientCoefficient = (
313 1.0 - self.specularCoefficient - self.lambertCoefficient
314 )
315
316 def baseColourAt(self, p):
317 return self.baseColour
318
319 def colourAt(self, scene, ray, p, normal):
320 b = self.baseColourAt(p)
321
322 c = (0, 0, 0)
323 if self.specularCoefficient > 0:
324 reflectedRay = Ray(p, ray.vector.reflectThrough(normal))
325 reflectedColour = scene.rayColour(reflectedRay)
326 c = addColours(c, self.specularCoefficient, reflectedColour)
327
328 if self.lambertCoefficient > 0:
329 lambertAmount = 0
330 for lightPoint in scene.visibleLights(p):
331 contribution = (lightPoint - p).normalized().dot(normal)
332 if contribution > 0:
333 lambertAmount = lambertAmount + contribution
334 lambertAmount = min(1, lambertAmount)
335 c = addColours(c, self.lambertCoefficient * lambertAmount, b)
336
337 if self.ambientCoefficient > 0:
338 c = addColours(c, self.ambientCoefficient, b)
339
340 return c
341
342
343 class CheckerboardSurface(SimpleSurface):
344
345 def __init__(self, **kwargs):
346 SimpleSurface.__init__(self, **kwargs)
347 self.otherColour = kwargs.get("otherColour", (0, 0, 0))
348 self.checkSize = kwargs.get("checkSize", 1)
349
350 def baseColourAt(self, p):
351 v = p - Point.ZERO
352 v.scale(1.0 / self.checkSize)
353 if (int(abs(v.x) + 0.5) + int(abs(v.y) + 0.5) + int(abs(v.z) + 0.5)) % 2:
354 return self.otherColour
355 else:
356 return self.baseColour
357
358
359 def bench_raytrace(loops, width, height, filename):
360 range_it = range(loops)
361 t0 = pyperf.perf_counter()
362
363 for i in range_it:
364 canvas = Canvas(width, height)
365 s = Scene()
366 s.addLight(Point(30, 30, 10))
367 s.addLight(Point(-10, 100, 30))
368 s.lookAt(Point(0, 3, 0))
369 s.addObject(Sphere(Point(1, 3, -10), 2), SimpleSurface(baseColour=(1, 1, 0)))
370 for y in range(6):
371 s.addObject(
372 Sphere(Point(-3 - y * 0.4, 2.3, -5), 0.4),
373 SimpleSurface(baseColour=(y / 6.0, 1 - y / 6.0, 0.5)),
374 )
375 s.addObject(Halfspace(Point(0, 0, 0), Vector.UP), CheckerboardSurface())
376 s.render(canvas)
377
378 dt = pyperf.perf_counter() - t0
379
380 if filename:
381 canvas.write_ppm(filename)
382 return dt
383
384
385 def add_cmdline_args(cmd, args):
386 cmd.append("--width=%s" % args.width)
387 cmd.append("--height=%s" % args.height)
388 if args.filename:
389 cmd.extend(("--filename", args.filename))
390
391
392 if __name__ == "__main__":
393 # runner = pyperf.Runner(add_cmdline_args=add_cmdline_args)
394 cmd = argparse.ArgumentParser()
395 cmd.add_argument(
396 "--width",
397 type=int,
398 default=DEFAULT_WIDTH,
399 help="Image width (default: %s)" % DEFAULT_WIDTH,
400 )
401 cmd.add_argument(
402 "--height",
403 type=int,
404 default=DEFAULT_HEIGHT,
405 help="Image height (default: %s)" % DEFAULT_HEIGHT,
406 )
407 cmd.add_argument(
408 "--filename", metavar="FILENAME.PPM", help="Output filename of the PPM picture"
409 )
410 args = cmd.parse_args()
411 start_p = perf_counter()
412 bench_raytrace(25, args.width, args.height, args.filename)
413 stop_p = perf_counter()
414 print("Time elapsed: ", stop_p - start_p)