From 9e8028f90431b9e66ae21af595ead91e5f03c2db Mon Sep 17 00:00:00 2001 From: Crizomb Date: Fri, 26 Sep 2025 21:43:08 +0200 Subject: [PATCH] Phong shading --- material.go | 7 +++++-- ray_marching.go | 20 +++++++++++++++++++- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/material.go b/material.go index 966fc07..d9e7837 100644 --- a/material.go +++ b/material.go @@ -6,6 +6,7 @@ type Color interface { // Ambre je te copie type Material struct { + ambiantColor Color diffuseColor Color diffuseFac float64 specularColor Color @@ -17,9 +18,10 @@ type Material struct { refractIndice float64 } -func DefaultMaterial(diffuseColor Color) Material { +func DefaultMaterial(ambiantColor Color) Material { return Material{ - diffuseColor: diffuseColor, + ambiantColor: ambiantColor, + diffuseColor: Vector3{255, 255, 255}, diffuseFac: 1.0, specularColor: Vector3{1.0, 1.0, 1.0}, specularFac: 0.5, @@ -33,6 +35,7 @@ func DefaultMaterial(diffuseColor Color) Material { func MixMat(mat1 Material, mat2 Material, t float64, p Vector3) Material { return Material{ + mat1.ambiantColor.GetColor(p).Scale(1 - t).Add((mat2.ambiantColor.GetColor(p)).Scale(t)), mat1.diffuseColor.GetColor(p).Scale(1 - t).Add((mat2.diffuseColor.GetColor(p)).Scale(t)), (mat1.diffuseFac*(1-t) + mat2.diffuseFac) * t, mat1.specularColor.GetColor(p).Scale(1 - t).Add((mat2.specularColor.GetColor(p)).Scale(t)), diff --git a/ray_marching.go b/ray_marching.go index 888a5ec..551d67f 100644 --- a/ray_marching.go +++ b/ray_marching.go @@ -17,6 +17,7 @@ const WIDTH = 500 const HEIGHT = 500 const PI = math.Pi +var lightPos Vector3 = Vector3{0, 200, 400} var sphere Sphere = Sphere{Vector3{0, 100, 10}, 10, RED_MAT} var plane Plane = Plane{Vector3{0, 0, 1}, -10, GREY_MAT} var scene UnionSDF = UnionSDF{sphere, plane} @@ -27,6 +28,22 @@ var cameraPos Vector3 = Vector3{0, -10, 0} var screenSpherical Vector3 = Vector3{10, PI / 2, PI / 2} var screenPhysicalSize float64 = 5 +func phongShading(point Vector3, normal Vector3, mat Material) Vector3 { + lightVec := (lightPos.Sub(point)).Normalized() + reflectLight := Reflect(lightVec, normal) + eyeVec := (cameraPos.Sub(point)).Normalized() + + ambiant := mat.ambiantColor.GetColor(point).Scale(0.1) + + diffusePower := mat.diffuseFac * max(0, normal.Dot(lightVec)) * 0.5 + diffuse := mat.diffuseColor.GetColor(point).Scale(diffusePower) + + specularPower := mat.specularFac * math.Pow(max(0, reflectLight.Dot(eyeVec)), mat.specularExp) + specular := mat.specularColor.GetColor(point).Scale(specularPower) + + return ambiant.Add(diffuse).Add(specular) +} + func rayMarch(origin Vector3, direction Vector3) (bool, Vector3) { p := origin for range MAX_STEP { @@ -34,7 +51,8 @@ func rayMarch(origin Vector3, direction Vector3) (bool, Vector3) { // fmt.Println(dist) if dist < EPS { // fmt.Println("hit") - return true, mat.diffuseColor.GetColor(p) + normal := Gradient(scene, p, EPS).Normalized() + return true, phongShading(p, normal, mat) } if dist > MAX_DIST { break