From 2ca6d751de5c6933e6d75289d184a980131036a2 Mon Sep 17 00:00:00 2001 From: Syndamia Date: Sun, 27 Aug 2023 13:51:02 +0300 Subject: [WGL/P] Fixed linePointDistance so we can account for points behind the objects --- Year 2/Computer Graphics with WebGL/Project/shaders.js | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/Year 2/Computer Graphics with WebGL/Project/shaders.js b/Year 2/Computer Graphics with WebGL/Project/shaders.js index 1657f5b..302ed50 100644 --- a/Year 2/Computer Graphics with WebGL/Project/shaders.js +++ b/Year 2/Computer Graphics with WebGL/Project/shaders.js @@ -59,11 +59,16 @@ var fShader = ` uniform vec3 uAmbientColor; uniform vec3 uDiffuseColor; - uniform vec3 uLightDir; + uniform vec3 uLightDir; // Thanks https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line#Vector_formulation float linePointDistance(vec3 linePoint, vec3 lineDir, vec3 point) { - return length((point - linePoint) - dot(point - linePoint, lineDir) * lineDir); + vec3 projectionDir = dot(point - linePoint, lineDir) * lineDir; // aka projectionVector - linePoint + float dist = length((point - linePoint) - projectionDir); // aka length of perpendicular vector + // if pointing in opposite directions, meaning if the cloest point is behind us + if (dot(projectionDir, lineDir) < 0.0) + return -dist; + return dist; } // Thanks https://en.wikipedia.org/wiki/Line%E2%80%93sphere_intersection#Calculation_using_vectors_in_3D @@ -134,7 +139,8 @@ var fShader = ` // Does the ray pass through any blackholes int bhStatus = 2; for (int i = 0; i < 5; i++) { - if (linePointDistance(ray, step, uBH[i].xyz) < uBH[i].a * 3.0) { + float dist = linePointDistance(ray, step, uBH[i].xyz); + if (dist >= 0.0 && dist < uBH[i].a * 3.0) { bhStatus = rayMarchInBH(uBH[i], ray, step); } } @@ -145,7 +151,8 @@ var fShader = ` // Does the ray hit a star for (int i = 0; i < 5; i++) { - if (linePointDistance(ray, step, uStars[i].xyz) < uStars[i].a) { + float dist = linePointDistance(ray, step, uStars[i].xyz); + if (dist >= 0.0 && dist < uStars[i].a) { return calculateColor(bhStatus == 2, uStars[i], ray, step); } } -- cgit v1.3.1-26-gb76a