1
0
Fork 0
2018-soft-3d-renderer/src/light.cpp

78 lines
1.9 KiB
C++
Raw Normal View History

2018-09-19 03:02:12 +00:00
#include "color.h"
#include "light.h"
// PRIVATE PROTOTYPES
static ColorF32 ComputeAmbientLight(
ColorF32 surfaceReflectivity, ColorF32 lightIntensity);
static ColorF32 ComputeDiffuseLight(
ColorF32 surfaceReflectivity, ColorF32 lightIntensity,
Point &vertPosition, Vector &vertNormal,
Point &lightPosition);
// PUBLIC FUNCTIONS
ColorF32 ComputeLight(Vertex &vert, Material &material, Light &light)
{
// Distance from light to vertex
2018-09-19 05:33:52 +00:00
Vector direction = light.position - vert.point;
float distance = VectorLength(direction);
2018-09-19 03:02:12 +00:00
// Intensity is a function of the falloff factors and the distance
ColorF32 intensity =
(light.intensity * light.color)
/ (light.falloffConstant + light.falloffLinear * distance);
// Compute ambient light
ColorF32 ambientLight = ComputeAmbientLight(
material.ambient, intensity);
// Compute diffuse light
ColorF32 diffuseLight = ComputeDiffuseLight(
material.diffuse, intensity,
vert.point, vert.normal,
light.position);
// Total light is sum of all lights
ColorF32 result = ambientLight + diffuseLight;
return result;
}
// PRIVATE FUNCTIONS
static ColorF32 ComputeAmbientLight(
ColorF32 surfaceReflectivity, ColorF32 lightIntensity)
{
ColorF32 result;
result = surfaceReflectivity * lightIntensity;
return result;
}
static ColorF32 ComputeDiffuseLight(
ColorF32 surfaceReflectivity, ColorF32 lightIntensity,
Point &vertPosition, Vector &vertNormal,
Point &lightPosition)
{
// Light is a function of the position of the light source and the surface
Vector direction = lightPosition - vertPosition;
2018-09-19 05:33:52 +00:00
VectorNormalize(direction);
2018-09-19 03:02:12 +00:00
2018-09-19 05:33:52 +00:00
float dot = VectorDot(vertNormal, direction);
2018-09-19 03:02:12 +00:00
ColorF32 result = surfaceReflectivity * lightIntensity * dot;
return result;
}