Debian Codegraph @

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