Python Raytracing

I am building a simple Python raytracer with pure Python (just for that), but I ended up in a roadblock.

My scene setup now is as follows:

  • The camera is located at a point 0, -10, 0along the y axis.
  • A sphere with a radius 1located at 0, 0, 0.
  • The image plane of the image is at a distance 1from the camera and has a width and height 0.5.

I take photons in a uniformly random distribution over the image plane, and if the photon crosses the object, I draw a red dot on the image canvas corresponding to the point on the image plane through which the beam passes.

My intersection code (I only have spheres):

def intersection(self, ray):
  cp = self.pos - ray.origin
  v = cp.dot(ray.direction)
  discriminant = self.radius**2  - cp.dot(cp) + v * v

  if discriminant < 0:
    return False
  else:
    return ray.position(v - sqrt(discriminant)) # Position of ray at time t

And my rendering code (it displays a certain number of photons, not pixel by pixel):

def bake(self, rays):
  self.image = Image.new('RGB', [int(self.camera.focalplane.width * 800), int(self.camera.focalplane.height * 800)])
  canvas = ImageDraw.Draw(self.image)

  for i in xrange(rays):
    x = random.uniform(-camera.focalplane.width / 2.0, camera.focalplane.width / 2.0)
    z = random.uniform(-camera.focalplane.height / 2.0, camera.focalplane.height / 2.0)

    ray = Ray(camera.pos, Vector(x, 1, z))

    for name in scene.objects.keys():
      result = scene.objects[name].intersection(ray)

      if result:
        n = Vector(0, 1, 0)
        d = ((ray.origin - Point(self.camera.pos.x, self.camera.pos.y + self.camera.focalplane.offset, self.camera.pos.z)).dot(n)) / (ray.direction.dot(n))
        pos = ray.position(d)

        x = pos.x
        y = pos.y

        canvas.point([int(self.camera.focalplane.width * 800) * (self.camera.focalplane.width / 2 + x) / self.camera.focalplane.width,
                      int(self.camera.focalplane.height * 800) * (self.camera.focalplane.height / 2 + z) / self.camera.focalplane.height],
                      fill = 128)

, , :

enter image description here

- :

enter image description here

- , ? ...

+5
1

?

+7

All Articles