From 67bfafc5b8090dbf143807f1ef4b4eb981936989 Mon Sep 17 00:00:00 2001 From: jbb01 <32650546+jbb01@users.noreply.github.com> Date: Thu, 8 Aug 2024 10:22:26 +0200 Subject: [PATCH] fix corner bias in Vec3#random(random, true) --- .../eu/jonahbauer/raytracing/math/Vec3.java | 24 ++++++++++++++----- 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/src/main/java/eu/jonahbauer/raytracing/math/Vec3.java b/src/main/java/eu/jonahbauer/raytracing/math/Vec3.java index 9e59a0a..a0b728a 100644 --- a/src/main/java/eu/jonahbauer/raytracing/math/Vec3.java +++ b/src/main/java/eu/jonahbauer/raytracing/math/Vec3.java @@ -17,17 +17,29 @@ public record Vec3(double x, double y, double z) { assert Double.isFinite(x) && Double.isFinite(y) && Double.isFinite(z) : "x, y and z must be finite"; } + /** + * {@return a uniformly random vector with components in the range [-1, 1)} + */ public static @NotNull Vec3 random(@NotNull RandomGenerator random) { - return random(random, false); - } - - public static @NotNull Vec3 random(@NotNull RandomGenerator random, boolean unit) { - var vec = new Vec3( + return new Vec3( Math.fma(2, random.nextDouble(), -1), Math.fma(2, random.nextDouble(), -1), Math.fma(2, random.nextDouble(), -1) ); - return unit ? vec.unit() : vec; + } + + /** + * {@return a uniformly random unit vector} + */ + public static @NotNull Vec3 random(@NotNull RandomGenerator random, boolean unit) { + if (!unit) return random(random); + Vec3 vec; + double squared; + do { + vec = random(random); + squared = vec.squared(); + } while (squared > 1); + return vec.div(Math.sqrt(squared)); } public static @NotNull Vec3 reflect(@NotNull Vec3 vec, @NotNull Vec3 normal) {