2019年5月25日土曜日

Python - Reflection and Refraction - transparency, above water, below water

The Ray Tracer Challenge: A Test-Driven Guide to Your First 3D Renderer (Jamis Buck(著)、Pragmatic Bookshelf)、Chapter 11(Reflection and Refraction)のPuutting It Together(165)を取り組んでみる。

コード

Python 3

```#!/usr/bin/env python3
import math
import time
from tuples import Point, Vector, Color
from planes import Plane
from spheres import Sphere
from materials import Material
from patterns import Solid, Stripe
from camera import Camera
from lights import Light
from world import World
from transformations import translation, scaling, view_transform
from transformations import rotation_x, rotation_y

print('ファイル名, rendering time(秒)')

width = 250
height = 125

light = Light(Point(-10, 10, -10), Color(1, 1, 1))

stripe1 = Stripe(Solid(Color(1, 0, 0)), Solid(Color(1, 1, 1)))
wall1 = Plane(transform=translation(0, 0, 10) *
rotation_y(math.pi / 4) *
rotation_x(math.pi / 2),
material=Material(pattern=stripe1))

stripe2 = Stripe(Solid(Color(0, 1, 0)), Solid(Color(1, 1, 1)))
wall2 = Plane(transform=translation(0, 0, 10) *
rotation_y(-math.pi / 4) *
rotation_x(math.pi / 2),
material=Material(pattern=stripe2))
water = Plane(transform=translation(0, -1, 0),
material=Material(transparency=0.9,
refractive_index=1.333))
ball1 = Sphere(transform=translation(0, -3.5, 5),
material=Material(Color(0, 0, 1),
ambient=0.9,
reflective=0.5))
ball2 = Sphere(transform=translation(0, -3.5, -1.5),
material=Material(Color(0, 0, 1),
ambient=0.9,
reflective=0.5))
ball3 = Sphere(transform=translation(-5, -3.5, -1),
material=Material(Color(0.64706, 0.16471, 0.16471),
ambient=0.9,
reflective=0.5))
ball4 = Sphere(transform=translation(5, -3.5, -1),
material=Material(Color(0.64706, 0.16471, 0.16471),
ambient=0.9,
reflective=0.5))
world = World([wall1, wall2, water, ball1, ball2, ball3, ball4],
light=light)

for i, y in enumerate([1.5, -1.5], 5):
camera = Camera(width, height, math.pi / 2,
transform=view_transform(
Point(0, y, -10),
Point(0, 0, 0),
Vector(0, 1, 0)))
start = time.time()
canvas = camera.render(world)
s = time.time() - start
with open(f'sample{i}.ppm', 'w') as f:
canvas.to_ppm(f)
print(f'sample{i}.ppm,{s}')
```

```C:\Users\...>py sample4.py
sample5.ppm,498.84950590133667
sample6.ppm,567.512158870697

C:\Users\...>
```