Compare commits

...

9 Commits

Author SHA1 Message Date
d67f877428 add octree to improve rendering performance by reducing the number of ray-sphere-intersection calculations 2024-08-04 23:58:15 +02:00
a84ed5c050 add bounding box to sphere 2024-08-04 23:54:35 +02:00
8b7b99b184 add simple scene 2024-08-04 23:54:18 +02:00
828c332e76 make scene deterministic 2024-08-04 23:53:46 +02:00
07cdc0c213 remove Double#isFinite checks in Vec3 constructor
A performance analysis showed, that the Double#isFinite checks in the Vec3 constructor add significant overhead without providing much value to the application.
2024-08-04 19:54:21 +02:00
b47ded6c56 add iterative rendering mode for faster results
In normal mode, the image is rendered one pixel at a time, taking multiple samples per pixel and averaging them before continuing with the next pixel.

In iterative mode, the image is rendered one sample at a time, taking one sample per pixel, then taking another sample and averaging it with the one before, and so on.
2024-08-04 19:15:44 +02:00
0c6db707e0 separate camera from rendering 2024-08-04 19:04:25 +02:00
c17b9aedf5 add "final" scene 2024-08-04 18:54:31 +02:00
bb326e82a6 abstract Image and add support for watching the image as its being rendered 2024-08-04 17:43:54 +02:00
16 changed files with 875 additions and 164 deletions

View File

@ -2,37 +2,96 @@ package eu.jonahbauer.raytracing;
import eu.jonahbauer.raytracing.material.DielectricMaterial;
import eu.jonahbauer.raytracing.material.LambertianMaterial;
import eu.jonahbauer.raytracing.material.Material;
import eu.jonahbauer.raytracing.material.MetallicMaterial;
import eu.jonahbauer.raytracing.math.Vec3;
import eu.jonahbauer.raytracing.render.Camera;
import eu.jonahbauer.raytracing.render.Color;
import eu.jonahbauer.raytracing.render.ImageFormat;
import eu.jonahbauer.raytracing.render.camera.SimpleCamera;
import eu.jonahbauer.raytracing.render.canvas.LiveCanvas;
import eu.jonahbauer.raytracing.render.canvas.Image;
import eu.jonahbauer.raytracing.render.renderer.SimpleRenderer;
import eu.jonahbauer.raytracing.scene.Hittable;
import eu.jonahbauer.raytracing.scene.Scene;
import eu.jonahbauer.raytracing.scene.Sphere;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Main {
public static void main(String[] args) throws IOException {
var scene = new Scene(
new Sphere(0, -100.5, - 1, 100, new LambertianMaterial(new Color(0.8, 0.8, 0.0))),
new Sphere(0, 0, - 1.2, 0.5, new LambertianMaterial(new Color(0.1, 0.2, 0.5))),
new Sphere(-1, 0, - 1, 0.5, new DielectricMaterial(1.5)),
new Sphere(-1, 0, - 1, 0.4, new DielectricMaterial(1 / 1.5)),
new Sphere(1, 0, - 1, 0.5, new MetallicMaterial(new Color(0.8, 0.6, 0.2), 1.0))
);
var scene = getScene();
var camera = Camera.builder()
.withImage(800, 450)
.withPosition(new Vec3(-2, 2, 1))
.withTarget(new Vec3(0, 0, -1))
var camera = SimpleCamera.builder()
.withImage(1200, 675)
.withPosition(new Vec3(13, 2, 3))
.withTarget(new Vec3(0, 0, 0))
.withFieldOfView(Math.toRadians(20))
.withFocusDistance(3.4)
.withBlurAngle(Math.toRadians(10))
.withFocusDistance(10.0)
.withBlurAngle(Math.toRadians(0.6))
.build();
var image = camera.render(scene);
var renderer = SimpleRenderer.builder()
.withSamplesPerPixel(500)
.withMaxDepth(50)
.withIterative(true)
.build();
var image = new LiveCanvas(new Image(camera.getWidth(), camera.getHeight()));
image.preview();
renderer.render(camera, scene, image);
ImageFormat.PNG.write(image, Path.of("scene-" + System.currentTimeMillis() + ".png"));
}
private static @NotNull Scene getScene() {
var rng = new Random(1);
var objects = new ArrayList<Hittable>();
objects.add(new Sphere(new Vec3(0, -1000, 0), 1000, new LambertianMaterial(new Color(0.5, 0.5, 0.5))));
for (int a = -11; a < 11; a++) {
for (int b = -11; b < 11; b++) {
var center = new Vec3(a + 0.9 * rng.nextDouble(), 0.2, b + 0.9 * rng.nextDouble());
if (Vec3.distance(center, new Vec3(4, 0.2, 0)) <= 0.9) continue;
Material material;
var rnd = rng.nextDouble();
if (rnd < 0.8) {
// diffuse
var albedo = Color.multiply(Color.random(rng), Color.random(rng));
material = new LambertianMaterial(albedo);
} else if (rnd < 0.95) {
// metal
var albedo = Color.random(rng, 0.5, 1.0);
var fuzz = rng.nextDouble() * 0.5;
material = new MetallicMaterial(albedo, fuzz);
} else {
// glass
material = new DielectricMaterial(1.5);
}
objects.add(new Sphere(center, 0.2, material));
}
}
objects.add(new Sphere(new Vec3(0, 1, 0), 1.0, new DielectricMaterial(1.5)));
objects.add(new Sphere(new Vec3(-4, 1, 0), 1.0, new LambertianMaterial(new Color(0.4, 0.2, 0.1))));
objects.add(new Sphere(new Vec3(4, 1, 0), 1.0, new MetallicMaterial(new Color(0.7, 0.6, 0.5))));
return new Scene(objects);
}
private static @NotNull Scene getSimpleScene() {
return new Scene(List.of(
new Sphere(new Vec3(0, -100.5, -1.0), 100.0, new LambertianMaterial(new Color(0.8, 0.8, 0.0))),
new Sphere(new Vec3(0, 0, -1.2), 0.5, new LambertianMaterial(new Color(0.1, 0.2, 0.5))),
new Sphere(new Vec3(-1.0, 0, -1.2), 0.5, new DielectricMaterial(1.5)),
new Sphere(new Vec3(-1.0, 0, -1.2), 0.4, new DielectricMaterial(1 / 1.5)),
new Sphere(new Vec3(1.0, 0, -1.2), 0.5, new MetallicMaterial(new Color(0.8, 0.6, 0.2), 0.0))
));
}
}

View File

@ -0,0 +1,10 @@
package eu.jonahbauer.raytracing.math;
import org.jetbrains.annotations.NotNull;
public record BoundingBox(@NotNull Vec3 min, @NotNull Vec3 max) {
public @NotNull Vec3 center() {
return Vec3.average(min, max, 2);
}
}

View File

@ -0,0 +1,253 @@
package eu.jonahbauer.raytracing.math;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;
public final class Octree<T> {
private final @NotNull NodeStorage<T> storage;
public Octree(@NotNull Vec3 center, double dimension) {
this.storage = new NodeStorage<>(center, dimension);
}
public void add(@NotNull BoundingBox bbox, T object) {
storage.add(new Entry<>(bbox, object));
}
/**
* Use HERO algorithms to find all elements that could possibly be hit by the given ray.
* @see <a href="https://diglib.eg.org/server/api/core/bitstreams/33fe8d58-1101-40ff-878a-79d689a4607d/content">The HERO Algorithm for Ray-Tracing Octrees</a>
*/
public void hit(@NotNull Ray ray, @NotNull Consumer<T> action) {
storage.hit(ray, action);
}
@Override
public @NotNull String toString() {
return storage.toString();
}
public static int getOctantIndex(@NotNull Vec3 center, @NotNull Vec3 pos) {
return (pos.x() < center.x() ? 0 : 1)
| (pos.y() < center.y() ? 0 : 2)
| (pos.z() < center.z() ? 0 : 4);
}
private sealed interface Storage<T> {
int LIST_SIZE_LIMIT = 32;
@NotNull Storage<T> add(@NotNull Entry<T> entry);
}
private static final class ListStorage<T> implements Storage<T> {
private final @NotNull Vec3 center;
private final double dimension;
private final @NotNull List<Entry<T>> list = new ArrayList<>();
public ListStorage(@NotNull Vec3 center, double dimension) {
this.center = Objects.requireNonNull(center);
this.dimension = dimension;
}
@Override
public @NotNull Storage<T> add(@NotNull Entry<T> entry) {
if (list.size() >= LIST_SIZE_LIMIT) {
var node = new NodeStorage<T>(center, dimension);
list.forEach(node::add);
node.add(entry);
return node;
} else {
list.add(entry);
return this;
}
}
@Override
public String toString() {
return list.toString();
}
}
private static final class NodeStorage<T> implements Storage<T> {
private final @NotNull Vec3 center;
private final double dimension;
@SuppressWarnings("unchecked")
private final @Nullable Storage<T> @NotNull[] octants = new Storage[8];
private final @NotNull List<Entry<T>> list = new ArrayList<>(); // track elements spanning multiple octants separately
public NodeStorage(@NotNull Vec3 center, double dimension) {
this.center = Objects.requireNonNull(center);
this.dimension = dimension;
}
@Override
public @NotNull Storage<T> add(@NotNull Entry<T> entry) {
var index = getOctantIndex(center, entry.bbox().min());
if (index != getOctantIndex(center, entry.bbox().max())) {
list.add(entry);
} else {
var subnode = octants[index];
if (subnode == null) {
subnode = newOctant(index);
}
octants[index] = subnode.add(entry);
}
return this;
}
private @NotNull Storage<T> newOctant(int index) {
var newSize = 0.5 * dimension;
var newCenter = this.center
.plus(new Vec3(
(index & 1) == 0 ? -newSize : newSize,
(index & 2) == 0 ? -newSize : newSize,
(index & 4) == 0 ? -newSize : newSize
));
return new ListStorage<>(newCenter, newSize);
}
public void hit(@NotNull Ray ray, @NotNull Consumer<T> action) {
int vmask = (ray.direction().x() < 0 ? 1 : 0)
| (ray.direction().y() < 0 ? 2 : 0)
| (ray.direction().z() < 0 ? 4 : 0);
var min = center.minus(dimension, dimension, dimension);
var max = center.plus(dimension, dimension, dimension);
// calculate t values for intersection points of ray with planes through min
var tmin = calculatePlaneIntersections(min, ray);
// calculate t values for intersection points of ray with planes through max
var tmax = calculatePlaneIntersections(max, ray);
// determine range of t for which the ray is inside this voxel
double tlmax = Double.NEGATIVE_INFINITY; // lower limit maximum
double tumin = Double.POSITIVE_INFINITY; // upper limit minimum
for (int i = 0; i < 3; i++) {
// classify t values as lower or upper limit based on vmask
if ((vmask & (1 << i)) == 0) {
// min is lower limit and max is upper limit
tlmax = Math.max(tlmax, tmin[i]);
tumin = Math.min(tumin, tmax[i]);
} else {
// max is lower limit and min is upper limit
tlmax = Math.max(tlmax, tmax[i]);
tumin = Math.min(tumin, tmin[i]);
}
}
var hit = tlmax < tumin;
if (!hit) return;
hit0(ray, vmask, tlmax, tumin, action);
}
private void hit0(@NotNull Ray ray, int vmask, double tmin, double tmax, @NotNull Consumer<T> action) {
if (tmax < 0) return;
for (Entry<T> entry : list) {
action.accept(entry.object());
}
// t values for intersection points of ray with planes through center
var tmid = calculatePlaneIntersections(center, ray);
// masks of planes in the order of intersection, e.g. [2, 1, 4] for a ray intersection y = center.y() then x = center.x() then z = center.z()
var masklist = calculateMastlist(tmid);
var childmask = (tmid[0] < tmin ? 1 : 0)
| (tmid[1] < tmin ? 2 : 0)
| (tmid[2] < tmin ? 4 : 0);
var lastmask = (tmid[0] < tmax ? 1 : 0)
| (tmid[1] < tmax ? 2 : 0)
| (tmid[2] < tmax ? 4 : 0);
var childTmin = tmin;
int i = 0;
while (true) {
var child = octants[childmask ^ vmask];
double childTmax;
if (childmask == lastmask) {
childTmax = tmax;
} else {
while ((masklist[i] & childmask) != 0) {
i++;
}
childmask = childmask | masklist[i];
childTmax = tmid[Integer.numberOfTrailingZeros(masklist[i])];
}
if (child instanceof ListStorage<T> list) {
for (Entry<T> entry : list.list) {
action.accept(entry.object);
}
} else if (child instanceof NodeStorage<T> node) {
node.hit0(ray, vmask, childTmin, childTmax, action);
}
if (childTmax == tmax) break;
childTmin = childTmax;
}
}
private double @NotNull [] calculatePlaneIntersections(@NotNull Vec3 position, @NotNull Ray ray) {
return new double[] {
(position.x() - ray.origin().x()) / ray.direction().x(),
(position.y() - ray.origin().y()) / ray.direction().y(),
(position.z() - ray.origin().z()) / ray.direction().z(),
};
}
private int @NotNull [] calculateMastlist(double @NotNull[] tmid) {
var masklist = new int[3];
if (tmid[0] < tmid[1] && tmid[0] < tmid[2]) {
masklist[0] = 1;
if (tmid[1] < tmid[2]) {
masklist[1] = 2;
masklist[2] = 4;
} else {
masklist[1] = 4;
masklist[2] = 2;
}
} else if (tmid[1] < tmid[2]) {
masklist[0] = 2;
if (tmid[0] < tmid[2]) {
masklist[1] = 1;
masklist[2] = 4;
} else {
masklist[1] = 4;
masklist[2] = 1;
}
} else {
masklist[0] = 4;
if (tmid[0] < tmid[1]) {
masklist[1] = 1;
masklist[2] = 2;
} else {
masklist[1] = 2;
masklist[2] = 1;
}
}
return masklist;
}
@Override
public String toString() {
var out = new StringBuilder("Octree centered on " + center + " with dimension " + dimension + "\n");
for (int i = 0; i < 8; i++) {
out.append(i == 7 ? "\\- [" : "|- [").append(i).append("]: ");
var prefix = i == 7 ? " " : "| ";
out.append(Objects.toString(octants[i]).lines().map(str -> prefix + str).collect(Collectors.joining("\n")).substring(8));
out.append("\n");
}
return out.toString();
}
}
private record Entry<T>(@NotNull BoundingBox bbox, T object) { }
}

View File

@ -6,14 +6,14 @@ import java.util.Optional;
public record Vec3(double x, double y, double z) {
public static final Vec3 ZERO = new Vec3(0, 0, 0);
public static final Vec3 MAX = new Vec3(Double.MAX_VALUE, Double.MAX_VALUE, Double.MAX_VALUE);
public static final Vec3 MIN = new Vec3(-Double.MAX_VALUE, -Double.MAX_VALUE, -Double.MAX_VALUE);
public static final Vec3 UNIT_X = new Vec3(1, 0, 0);
public static final Vec3 UNIT_Y = new Vec3(0, 1, 0);
public static final Vec3 UNIT_Z = new Vec3(0, 0, 1);
public Vec3 {
if (!Double.isFinite(x) || !Double.isFinite(y) || !Double.isFinite(z)) {
throw new IllegalArgumentException("x, y and z must be finite");
}
assert Double.isFinite(x) && Double.isFinite(y) && Double.isFinite(z) : "x, y and z must be finite";
}
public static @NotNull Vec3 random() {
@ -50,6 +50,42 @@ public record Vec3(double x, double y, double z) {
return vec.plus(vxp.times(Math.sin(angle))).plus(vxvxp.times(1 - Math.cos(angle)));
}
public static double distance(@NotNull Vec3 a, @NotNull Vec3 b) {
return a.minus(b).length();
}
public static @NotNull Vec3 average(@NotNull Vec3 current, @NotNull Vec3 next, int index) {
return new Vec3(
current.x() + (next.x() - current.x()) / index,
current.y() + (next.y() - current.y()) / index,
current.z() + (next.z() - current.z()) / index
);
}
public static @NotNull Vec3 max(@NotNull Vec3 a, @NotNull Vec3 b) {
return new Vec3(
Math.max(a.x(), b.x()),
Math.max(a.y(), b.y()),
Math.max(a.z(), b.z())
);
}
public static @NotNull Vec3 min(@NotNull Vec3 a, @NotNull Vec3 b) {
return new Vec3(
Math.min(a.x(), b.x()),
Math.min(a.y(), b.y()),
Math.min(a.z(), b.z())
);
}
public @NotNull Vec3 plus(double x, double y, double z) {
return new Vec3(this.x + x, this.y + y, this.z + z);
}
public @NotNull Vec3 minus(double x, double y, double z) {
return new Vec3(this.x - x, this.y - y, this.z - z);
}
public @NotNull Vec3 plus(@NotNull Vec3 b) {
return new Vec3(this.x + b.x, this.y + b.y, this.z + b.z);
}

View File

@ -2,6 +2,8 @@ package eu.jonahbauer.raytracing.render;
import org.jetbrains.annotations.NotNull;
import java.util.Random;
public record Color(double r, double g, double b) {
public static final @NotNull Color BLACK = new Color(0.0, 0.0, 0.0);
public static final @NotNull Color WHITE = new Color(1.0, 1.0, 1.0);
@ -24,6 +26,45 @@ public record Color(double r, double g, double b) {
return new Color(a.r() * b.r(), a.g() * b.g(), a.b() * b.b());
}
public static @NotNull Color random(@NotNull Random random) {
return new Color(random.nextDouble(), random.nextDouble(), random.nextDouble());
}
public static @NotNull Color random(@NotNull Random random, double min, double max) {
var span = max - min;
return new Color(
Math.fma(random.nextDouble(), span, min),
Math.fma(random.nextDouble(), span, min),
Math.fma(random.nextDouble(), span, min)
);
}
public static @NotNull Color average(@NotNull Color current, @NotNull Color next, int index) {
return new Color(
current.r() + (next.r() - current.r()) / index,
current.g() + (next.g() - current.g()) / index,
current.b() + (next.b() - current.b()) / index
);
}
public static @NotNull Color gamma(@NotNull Color color, double gamma) {
if (gamma == 1.0) {
return color;
} else if (gamma == 2.0) {
return new Color(
Math.sqrt(color.r()),
Math.sqrt(color.g()),
Math.sqrt(color.b())
);
} else {
return new Color(
Math.pow(color.r(), 1 / gamma),
Math.pow(color.g(), 1 / gamma),
Math.pow(color.b(), 1 / gamma)
);
}
}
public Color {
if (r < 0 || r > 1 || g < 0 || g > 1 || b < 0 || b > 1) {
throw new IllegalArgumentException("r, g and b must be in the range 0 to 1");

View File

@ -1,5 +1,6 @@
package eu.jonahbauer.raytracing.render;
import eu.jonahbauer.raytracing.render.canvas.Canvas;
import org.jetbrains.annotations.NotNull;
import java.io.*;
@ -13,12 +14,12 @@ import java.util.zip.DeflaterOutputStream;
public enum ImageFormat {
PPM {
@Override
public void write(@NotNull Image image, @NotNull OutputStream out) throws IOException {
public void write(@NotNull Canvas image, @NotNull OutputStream out) throws IOException {
try (var writer = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.US_ASCII))) {
writer.write("P3\n");
writer.write(String.valueOf(image.width()));
writer.write(String.valueOf(image.getWidth()));
writer.write(" ");
writer.write(String.valueOf(image.height()));
writer.write(String.valueOf(image.getHeight()));
writer.write("\n255\n");
var it = image.pixels().iterator();
@ -42,7 +43,7 @@ public enum ImageFormat {
private static final int IEND_TYPE = 0x49454E44;
@Override
public void write(@NotNull Image image, @NotNull OutputStream out) throws IOException {
public void write(@NotNull Canvas image, @NotNull OutputStream out) throws IOException {
try (var data = new NoCloseDataOutputStream(out); var _ = data.closeable()) {
data.write(MAGIC);
@ -52,15 +53,15 @@ public enum ImageFormat {
}
}
private void writeIHDR(@NotNull Image image, @NotNull DataOutputStream data) throws IOException {
private void writeIHDR(@NotNull Canvas image, @NotNull DataOutputStream data) throws IOException {
data.writeInt(IHDR_LENGTH);
try (
var crc = new CheckedOutputStream(data, new CRC32());
var ihdr = new DataOutputStream(crc)
) {
ihdr.writeInt(IHDR_TYPE);
ihdr.writeInt(image.width()); // image width
ihdr.writeInt(image.height()); // image height
ihdr.writeInt(image.getWidth()); // image width
ihdr.writeInt(image.getHeight()); // image height
ihdr.writeByte(8); // bit depth
ihdr.writeByte(2); // color type
ihdr.writeByte(0); // compression method
@ -71,7 +72,7 @@ public enum ImageFormat {
}
}
private void writeIDAT(@NotNull Image image, @NotNull DataOutputStream data) throws IOException {
private void writeIDAT(@NotNull Canvas image, @NotNull DataOutputStream data) throws IOException {
try (
var baos = new ByteArrayOutputStream();
var crc = new CheckedOutputStream(baos, new CRC32());
@ -81,7 +82,7 @@ public enum ImageFormat {
try (var deflate = new DataOutputStream(new DeflaterOutputStream(idat))) {
var pixels = image.pixels().iterator();
for (int i = 0; pixels.hasNext(); i = (i + 1) % image.width()) {
for (int i = 0; pixels.hasNext(); i = (i + 1) % image.getWidth()) {
if (i == 0) deflate.writeByte(0); // filter type
var pixel = pixels.next();
deflate.writeByte(pixel.red());
@ -97,7 +98,7 @@ public enum ImageFormat {
}
}
private void writeIEND(@NotNull Image image, @NotNull DataOutputStream data) throws IOException {
private void writeIEND(@NotNull Canvas image, @NotNull DataOutputStream data) throws IOException {
data.writeInt(0);
data.writeInt(IEND_TYPE);
data.writeInt(0);
@ -120,11 +121,11 @@ public enum ImageFormat {
},
;
public void write(@NotNull Image image, @NotNull Path path) throws IOException {
public void write(@NotNull Canvas image, @NotNull Path path) throws IOException {
try (var out = Files.newOutputStream(path)) {
write(image, out);
}
}
public abstract void write(@NotNull Image image, @NotNull OutputStream out) throws IOException;
public abstract void write(@NotNull Canvas image, @NotNull OutputStream out) throws IOException;
}

View File

@ -0,0 +1,22 @@
package eu.jonahbauer.raytracing.render.camera;
import eu.jonahbauer.raytracing.math.Ray;
import org.jetbrains.annotations.NotNull;
public interface Camera {
/**
* {@return the width of this camera in pixels}
*/
int getWidth();
/**
* {@return the height of this camera in pixels}
*/
int getHeight();
/**
* Casts a ray through the given pixel.
* @return a new ray
*/
@NotNull Ray cast(int x, int y);
}

View File

@ -1,15 +1,13 @@
package eu.jonahbauer.raytracing.render;
package eu.jonahbauer.raytracing.render.camera;
import eu.jonahbauer.raytracing.math.Range;
import eu.jonahbauer.raytracing.math.Ray;
import eu.jonahbauer.raytracing.math.Vec3;
import eu.jonahbauer.raytracing.scene.Scene;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Objects;
public final class Camera {
public final class SimpleCamera implements Camera {
// image size
private final int width;
private final int height;
@ -18,9 +16,6 @@ public final class Camera {
private final @NotNull Vec3 origin;
// rendering
private final int samplesPerPixel;
private final int maxDepth;
private final double gamma;
private final double blurRadius;
// internal properties
@ -35,11 +30,11 @@ public final class Camera {
return new Builder();
}
public Camera() {
this(new Builder());
public static @NotNull Camera withDefaults() {
return new Builder().build();
}
private Camera(@NotNull Builder builder) {
private SimpleCamera(@NotNull Builder builder) {
this.width = builder.imageWidth;
this.height = builder.imageHeight;
@ -49,9 +44,6 @@ public final class Camera {
this.origin = builder.position;
var direction = (builder.direction == null ? builder.target.minus(builder.position).unit() : builder.direction);
this.samplesPerPixel = builder.samplePerPixel;
this.maxDepth = builder.maxDepth;
this.gamma = builder.gamma;
this.blurRadius = Math.tan(0.5 * builder.blurAngle) * builder.focusDistance;
// project direction the horizontal plane
@ -70,84 +62,63 @@ public final class Camera {
.plus(pixelU.div(2)).plus(pixelV.div(2));
}
public @NotNull Image render(@NotNull Scene scene) {
var image = new Image(width, height);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
var r = 0d;
var g = 0d;
var b = 0d;
for (int i = 0; i < samplesPerPixel; i++) {
var ray = getRay(x, y);
var color = getColor(scene, ray);
r += color.r();
g += color.g();
b += color.b();
}
image.set(x, y, new Color(
Math.pow(r / samplesPerPixel, 1 / gamma),
Math.pow(g / samplesPerPixel, 1 / gamma),
Math.pow(b / samplesPerPixel, 1 / gamma)
));
}
}
return image;
/**
* {@inheritDoc}
*/
public int getWidth() {
return width;
}
private @NotNull Ray getRay(int x, int y) {
var origin = this.origin;
if (blurRadius > 0) {
double bu, bv;
do {
bu = 2 * Math.random() - 1;
bv = 2 * Math.random() - 1;
} while (bu * bu + bv * bv >= 1);
origin = origin.plus(u.times(blurRadius * bu)).plus(v.times(blurRadius * bv));
}
return new Ray(origin, getPixel(x, y).minus(origin));
/**
* {@inheritDoc}
*/
public int getHeight() {
return height;
}
private @NotNull Vec3 getPixel(int x, int y) {
/**
* {@inheritDoc}
*/
public @NotNull Ray cast(int x, int y) {
Objects.checkIndex(x, width);
Objects.checkIndex(y, height);
double dx = x + Math.random() - 0.5;
double dy = y + Math.random() - 0.5;
return pixel00.plus(pixelU.times(dx)).plus(pixelV.times(dy));
var origin = getRayOrigin();
var target = getRayTarget(x, y);
return new Ray(origin, target.minus(origin));
}
private @NotNull Color getColor(@NotNull Scene scene, @NotNull Ray ray) {
return getColor(scene, ray, maxDepth);
}
/**
* {@return the origin for a ray cast by this camera} The ray origin is randomized within a disk of
* radius {@link #blurRadius} centered on the camera position and perpendicular to the direction to simulate depth
* of field.
*/
private @NotNull Vec3 getRayOrigin() {
if (blurRadius <= 0) return origin;
private @NotNull Color getColor(@NotNull Scene scene, @NotNull Ray ray, int depth) {
if (depth <= 0) return Color.BLACK;
while (true) {
var du = 2 * Math.random() - 1;
var dv = 2 * Math.random() - 1;
if (du * du + dv * dv >= 1) continue;
var optional = scene.hit(ray, new Range(0.001, Double.POSITIVE_INFINITY));
if (optional.isPresent()) {
var hit = optional.get();
var material = hit.material();
return material.scatter(ray, hit)
.map(scatter -> Color.multiply(scatter.attenuation(), getColor(scene, scatter.ray(), depth - 1)))
.orElse(Color.BLACK);
} else {
return getSkyboxColor(ray);
var ru = blurRadius * du;
var rv = blurRadius * dv;
return new Vec3(
origin.x() + ru * u.x() + rv * v.x(),
origin.y() + ru * u.y() + rv * v.y(),
origin.z() + ru * u.z() + rv * v.z()
);
}
}
private static @NotNull Color getSkyboxColor(@NotNull Ray ray) {
// altitude from -pi/2 to pi/2
var alt = Math.copySign(
Math.acos(ray.direction().withY(0).unit().times(ray.direction().unit())),
ray.direction().y()
);
return Color.lerp(Color.WHITE, Color.SKY, alt / Math.PI + 0.5);
/**
* {@return the target vector for a ray through the given pixel} The position is randomized within the pixel.
*/
private @NotNull Vec3 getRayTarget(int x, int y) {
double dx = x + Math.random() - 0.5;
double dy = y + Math.random() - 0.5;
return pixel00.plus(pixelU.times(dx)).plus(pixelV.times(dy));
}
public static class Builder {
@ -163,9 +134,6 @@ public final class Camera {
private double focusDistance = 10;
private double blurAngle = 0.0;
private int samplePerPixel = 100;
private int maxDepth = 10;
private double gamma = 2.0;
private Builder() {}
@ -217,26 +185,8 @@ public final class Camera {
return this;
}
public @NotNull Builder withSamplesPerPixel(int samples) {
if (samples <= 0) throw new IllegalArgumentException("samples must be positive");
this.samplePerPixel = samples;
return this;
}
public @NotNull Builder withMaxDepth(int depth) {
if (depth <= 0) throw new IllegalArgumentException("depth must be positive");
this.maxDepth = depth;
return this;
}
public @NotNull Builder withGamma(double gamma) {
if (gamma <= 0 || !Double.isFinite(gamma)) throw new IllegalArgumentException("gamma must be positive");
this.gamma = gamma;
return this;
}
public @NotNull Camera build() {
return new Camera(this);
public @NotNull SimpleCamera build() {
return new SimpleCamera(this);
}
}

View File

@ -0,0 +1,22 @@
package eu.jonahbauer.raytracing.render.canvas;
import eu.jonahbauer.raytracing.render.Color;
import org.jetbrains.annotations.NotNull;
import java.util.function.Function;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public interface Canvas {
int getWidth();
int getHeight();
void set(int x, int y, @NotNull Color color);
@NotNull Color get(int x, int y);
default @NotNull Stream<Color> pixels() {
return IntStream.range(0, getHeight())
.mapToObj(y -> IntStream.range(0, getWidth()).mapToObj(x -> get(x, y)))
.flatMap(Function.identity());
}
}

View File

@ -1,12 +1,11 @@
package eu.jonahbauer.raytracing.render;
package eu.jonahbauer.raytracing.render.canvas;
import eu.jonahbauer.raytracing.render.Color;
import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
import java.util.Objects;
import java.util.stream.Stream;
public final class Image {
public final class Image implements Canvas {
private final int width;
private final int height;
@ -22,35 +21,27 @@ public final class Image {
this.data = new Color[height][width];
}
public int width() {
@Override
public int getWidth() {
return width;
}
public int height() {
@Override
public int getHeight() {
return height;
}
@Override
public @NotNull Color get(int x, int y) {
Objects.checkIndex(x, width);
Objects.checkIndex(y, height);
return Objects.requireNonNullElse(this.data[y][x], Color.BLACK);
}
public @NotNull Stream<Color> pixels() {
return Arrays.stream(data).flatMap(Arrays::stream).map(c -> Objects.requireNonNullElse(c, Color.BLACK));
}
@Override
public void set(int x, int y, @NotNull Color color) {
Objects.checkIndex(x, width);
Objects.checkIndex(y, height);
this.data[y][x] = Objects.requireNonNull(color);
}
public void set(int x, int y, int red, int green, int blue) {
set(x, y, new Color(red, green, blue));
}
public void set(int x, int y, double r, double g, double b) {
set(x, y, new Color(r, g, b));
}
}

View File

@ -0,0 +1,77 @@
package eu.jonahbauer.raytracing.render.canvas;
import eu.jonahbauer.raytracing.render.Color;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
public final class LiveCanvas implements Canvas {
private final @NotNull Canvas delegate;
private final @NotNull BufferedImage image;
public LiveCanvas(@NotNull Canvas delegate) {
this.delegate = delegate;
this.image = new BufferedImage(delegate.getWidth(), delegate.getHeight(), BufferedImage.TYPE_INT_RGB);
}
@Override
public int getWidth() {
return delegate.getWidth();
}
@Override
public int getHeight() {
return delegate.getHeight();
}
@Override
public void set(int x, int y, @NotNull Color color) {
delegate.set(x, y, color);
var rgb = color.red() << 16 | color.green() << 8 | color.blue();
image.setRGB(x, y, rgb);
}
@Override
public @NotNull Color get(int x, int y) {
return delegate.get(x, y);
}
public @NotNull Thread preview() {
var frame = new JFrame();
frame.setSize(getWidth(), getHeight());
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setContentPane(new JPanel() {
@Override
protected void paintComponent(Graphics g) {
g.drawImage(image, 0, 0, null);
}
});
frame.setResizable(false);
frame.setVisible(true);
var update = Thread.ofVirtual().start(() -> {
while (!Thread.interrupted()) {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
break;
}
frame.repaint();
}
frame.dispose();
});
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
update.interrupt();
}
});
return update;
}
}

View File

@ -0,0 +1,20 @@
package eu.jonahbauer.raytracing.render.renderer;
import eu.jonahbauer.raytracing.render.camera.Camera;
import eu.jonahbauer.raytracing.render.canvas.Canvas;
import eu.jonahbauer.raytracing.render.canvas.Image;
import eu.jonahbauer.raytracing.scene.Scene;
import org.jetbrains.annotations.NotNull;
public interface Renderer {
default @NotNull Image render(@NotNull Camera camera, @NotNull Scene scene) {
var image = new Image(camera.getWidth(), camera.getHeight());
render(camera, scene, image);
return image;
}
/**
* Renders the {@code scene} as seen by the {@code camera} to the {@code canvas}.
*/
void render(@NotNull Camera camera, @NotNull Scene scene, @NotNull Canvas canvas);
}

View File

@ -0,0 +1,166 @@
package eu.jonahbauer.raytracing.render.renderer;
import eu.jonahbauer.raytracing.math.Range;
import eu.jonahbauer.raytracing.math.Ray;
import eu.jonahbauer.raytracing.render.Color;
import eu.jonahbauer.raytracing.render.camera.Camera;
import eu.jonahbauer.raytracing.render.canvas.Canvas;
import eu.jonahbauer.raytracing.scene.Scene;
import org.jetbrains.annotations.NotNull;
import java.util.function.Function;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
public final class SimpleRenderer implements Renderer {
private final int samplesPerPixel;
private final int maxDepth;
private final double gamma;
private final boolean parallel;
private final boolean iterative;
public static @NotNull Builder builder() {
return new Builder();
}
public static @NotNull Renderer withDefaults() {
return new Builder().build();
}
private SimpleRenderer(@NotNull Builder builder) {
this.samplesPerPixel = builder.samplesPerPixel;
this.maxDepth = builder.maxDepth;
this.gamma = builder.gamma;
this.parallel = builder.parallel;
this.iterative = builder.iterative;
}
@Override
public void render(@NotNull Camera camera, @NotNull Scene scene, @NotNull Canvas canvas) {
if (canvas.getWidth() != camera.getWidth() || canvas.getHeight() != camera.getHeight()) {
throw new IllegalArgumentException("sizes of camera and canvas are different");
}
if (iterative) {
// render one sample after the other
for (int i = 1 ; i <= samplesPerPixel; i++) {
var sample = i;
getPixelStream(camera.getWidth(), camera.getHeight(), parallel).forEach(pixel -> {
var y = (int) (pixel >> 32);
var x = (int) pixel;
var ray = camera.cast(x, y);
var c = getColor(scene, ray);
canvas.set(x, y, Color.average(canvas.get(x, y), c, sample));
});
}
// apply gamma correction
getPixelStream(camera.getWidth(), camera.getHeight(), parallel).forEach(pixel -> {
var y = (int) (pixel >> 32);
var x = (int) pixel;
canvas.set(x, y, Color.gamma(canvas.get(x, y), gamma));
});
} else {
// render one pixel after the other
getPixelStream(camera.getWidth(), camera.getHeight(), parallel).forEach(pixel -> {
var y = (int) (pixel >> 32);
var x = (int) pixel;
var color = Color.BLACK;
for (int i = 1; i <= samplesPerPixel; i++) {
var ray = camera.cast(x, y);
var c = getColor(scene, ray);
color = Color.average(color, c, i);
}
canvas.set(x, y, Color.gamma(color, gamma));
});
}
}
/**
* {@return the color of the given ray in the given scene}
*/
private @NotNull Color getColor(@NotNull Scene scene, @NotNull Ray ray) {
return getColor0(scene, ray, maxDepth);
}
private @NotNull Color getColor0(@NotNull Scene scene, @NotNull Ray ray, int depth) {
if (depth <= 0) return Color.BLACK;
var optional = scene.hit(ray, new Range(0.001, Double.POSITIVE_INFINITY));
if (optional.isPresent()) {
var hit = optional.get();
var material = hit.material();
return material.scatter(ray, hit)
.map(scatter -> Color.multiply(scatter.attenuation(), getColor0(scene, scatter.ray(), depth - 1)))
.orElse(Color.BLACK);
} else {
return getSkyboxColor(ray);
}
}
/**
* {@return a stream of the pixels in a canvas with the given size} The pixels {@code x} and {@code y} coordinate
* are encoded in the longs lower and upper 32 bits respectively.
*/
private static @NotNull LongStream getPixelStream(int width, int height, boolean parallel) {
var stream = IntStream.range(0, height)
.mapToObj(y -> IntStream.range(0, width).mapToLong(x -> (long) y << 32 | x))
.flatMapToLong(Function.identity());
return parallel ? stream.parallel() : stream;
}
/**
* {@return the color of the skybox for a given ray} The skybox color is a linear gradient based on the altitude of
* the ray above the horizon with {@link Color#SKY} at the top and {@link Color#WHITE} at the bottom.
*/
private static @NotNull Color getSkyboxColor(@NotNull Ray ray) {
// altitude from -pi/2 to pi/2
var alt = Math.copySign(
Math.acos(ray.direction().withY(0).unit().times(ray.direction().unit())),
ray.direction().y()
);
return Color.lerp(Color.WHITE, Color.SKY, alt / Math.PI + 0.5);
}
public static class Builder {
private int samplesPerPixel = 100;
private int maxDepth = 10;
private double gamma = 2.0;
private boolean parallel = true;
private boolean iterative = false;
public @NotNull Builder withSamplesPerPixel(int samples) {
if (samples <= 0) throw new IllegalArgumentException("samples must be positive");
this.samplesPerPixel = samples;
return this;
}
public @NotNull Builder withMaxDepth(int depth) {
if (depth <= 0) throw new IllegalArgumentException("depth must be positive");
this.maxDepth = depth;
return this;
}
public @NotNull Builder withGamma(double gamma) {
if (gamma <= 0 || !Double.isFinite(gamma)) throw new IllegalArgumentException("gamma must be positive");
this.gamma = gamma;
return this;
}
public @NotNull Builder withParallel(boolean parallel) {
this.parallel = parallel;
return this;
}
public @NotNull Builder withIterative(boolean iterative) {
this.iterative = iterative;
return this;
}
public @NotNull SimpleRenderer build() {
return new SimpleRenderer(this);
}
}
}

View File

@ -1,5 +1,6 @@
package eu.jonahbauer.raytracing.scene;
import eu.jonahbauer.raytracing.math.BoundingBox;
import eu.jonahbauer.raytracing.math.Range;
import eu.jonahbauer.raytracing.math.Ray;
import org.jetbrains.annotations.NotNull;
@ -14,4 +15,8 @@ public interface Hittable {
* @param ray a ray
*/
@NotNull Optional<HitResult> hit(@NotNull Ray ray, @NotNull Range range);
default @NotNull Optional<BoundingBox> getBoundingBox() {
return Optional.empty();
}
}

View File

@ -1,31 +1,80 @@
package eu.jonahbauer.raytracing.scene;
import eu.jonahbauer.raytracing.math.Octree;
import eu.jonahbauer.raytracing.math.Range;
import eu.jonahbauer.raytracing.math.Ray;
import eu.jonahbauer.raytracing.math.Vec3;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public record Scene(@NotNull List<@NotNull Hittable> objects) implements Hittable {
public final class Scene implements Hittable {
private final @NotNull Octree<@NotNull Hittable> octree;
private final @NotNull List<@NotNull Hittable> list;
public Scene {
objects = List.copyOf(objects);
}
public Scene(@NotNull List<? extends @NotNull Hittable> objects) {
this.octree = newOctree(objects);
this.list = new ArrayList<>();
public Scene(@NotNull Hittable @NotNull ... objects) {
this(List.of(objects));
}
public @NotNull Optional<HitResult> hit(@NotNull Ray ray, @NotNull Range range) {
var result = (HitResult) null;
for (var object : objects) {
var r = object.hit(ray, range);
if (r.isPresent() && range.surrounds(r.get().t())) {
result = r.get();
range = new Range(range.min(), result.t());
for (Hittable object : objects) {
var bbox = object.getBoundingBox();
if (bbox.isPresent()) {
octree.add(bbox.get(), object);
} else {
list.add(object);
}
}
return Optional.ofNullable(result);
}
@Override
public @NotNull Optional<HitResult> hit(@NotNull Ray ray, @NotNull Range range) {
var state = new State();
state.range = range;
octree.hit(ray, object -> hit(state, ray, object));
list.forEach(object -> hit(state, ray, object));
return Optional.ofNullable(state.result);
}
private void hit(@NotNull State state, @NotNull Ray ray, @NotNull Hittable object) {
var r = object.hit(ray, state.range);
if (r.isPresent() && state.range.surrounds(r.get().t())) {
state.result = r.get();
state.range = new Range(state.range.min(), state.result.t());
}
}
private static @NotNull Octree<Hittable> newOctree(@NotNull List<? extends Hittable> objects) {
Vec3 center = Vec3.ZERO, max = Vec3.MIN, min = Vec3.MAX;
int i = 1;
for (Hittable object : objects) {
var bbox = object.getBoundingBox();
if (bbox.isPresent()) {
center = Vec3.average(center, bbox.get().center(), i++);
max = Vec3.max(max, bbox.get().max());
min = Vec3.min(min, bbox.get().min());
}
}
var dimension = Arrays.stream(new double[] {
Math.abs(max.x() - center.x()),
Math.abs(max.y() - center.y()),
Math.abs(max.z() - center.z()),
Math.abs(min.x() - center.x()),
Math.abs(min.y() - center.y()),
Math.abs(min.z() - center.z())
}).max().orElse(10);
return new Octree<Hittable>(center, dimension);
}
private static class State {
HitResult result;
Range range;
}
}

View File

@ -1,6 +1,7 @@
package eu.jonahbauer.raytracing.scene;
import eu.jonahbauer.raytracing.material.Material;
import eu.jonahbauer.raytracing.math.BoundingBox;
import eu.jonahbauer.raytracing.math.Range;
import eu.jonahbauer.raytracing.math.Ray;
import eu.jonahbauer.raytracing.math.Vec3;
@ -44,6 +45,14 @@ public record Sphere(@NotNull Vec3 center, double radius, @NotNull Material mate
return Optional.of(new HitResult(t, position, frontFace ? normal : normal.times(-1), material, frontFace));
}
@Override
public @NotNull Optional<BoundingBox> getBoundingBox() {
return Optional.of(new BoundingBox(
center.minus(radius, radius, radius),
center.plus(radius, radius, radius)
));
}
public @NotNull Sphere withCenter(@NotNull Vec3 center) {
return new Sphere(center, radius, material);
}