Debian Codegraph @

test/optimized/bm_raytrace.py

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