From c002b8215a3e848161226be7d962792f39df398d Mon Sep 17 00:00:00 2001 From: jbb01 <32650546+jbb01@users.noreply.github.com> Date: Mon, 5 Aug 2024 16:40:53 +0200 Subject: [PATCH] prevent StackOverflowError in SimpleRenderer --- .../render/renderer/SimpleRenderer.java | 26 ++++++++++++------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/src/main/java/eu/jonahbauer/raytracing/render/renderer/SimpleRenderer.java b/src/main/java/eu/jonahbauer/raytracing/render/renderer/SimpleRenderer.java index 634a94d..527111e 100644 --- a/src/main/java/eu/jonahbauer/raytracing/render/renderer/SimpleRenderer.java +++ b/src/main/java/eu/jonahbauer/raytracing/render/renderer/SimpleRenderer.java @@ -86,20 +86,28 @@ public final class SimpleRenderer implements Renderer { } private @NotNull Color getColor0(@NotNull Scene scene, @NotNull Ray ray, int depth) { - if (depth <= 0) return Color.BLACK; + var color = Color.BLACK; + var attenuation = Color.WHITE; + + while (depth-- > 0) { + var optional = scene.hit(ray, new Range(0.001, Double.POSITIVE_INFINITY)); + if (optional.isEmpty()) { + color = Color.add(color, Color.multiply(attenuation, scene.getBackgroundColor(ray))); + break; + } - var optional = scene.hit(ray, new Range(0.001, Double.POSITIVE_INFINITY)); - if (optional.isPresent()) { var hit = optional.get(); var material = hit.material(); var emitted = material.emitted(hit); - return material.scatter(ray, hit) - .map(scatter -> Color.multiply(scatter.attenuation(), getColor0(scene, scatter.ray(), depth - 1))) - .map(color -> Color.add(color, emitted)) - .orElse(emitted); - } else { - return scene.getBackgroundColor(ray); + var scatter = material.scatter(ray, hit); + color = Color.add(color, Color.multiply(attenuation, emitted)); + + if (scatter.isEmpty()) break; + attenuation = Color.multiply(attenuation, scatter.get().attenuation()); + ray = scatter.get().ray(); } + + return color; } /**