aboutsummaryrefslogtreecommitdiff
path: root/src/Engine/Scene.cpp
blob: f92dc68517fa2a5b3da7efebdf4d423447827146 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include "Scene.h"

namespace Donut
{
    Scene::Scene() 
        : m_LightPos(5.0f, 5.0f, 5.0f) { }

    glm::vec3 Scene::Trace(Ray &ray)
    {
        float closest = std::numeric_limits<float>::infinity();
        const Object* hitObj = nullptr;

        for(auto& obj : objs)
        {
            float t;

            if(obj.Intersect(ray, t))
                if(t < closest) 
                {
                    closest = t;
                    hitObj = &obj;
                }
        }
        
        if(hitObj)
        {
            glm::vec3 hitPoint = ray.m_Origin + ray.m_Direction * closest;
            glm::vec3 normal = hitObj->GetNormal(hitPoint);
            glm::vec3 lightDir = glm::normalize(m_LightPos - hitPoint);

            float diff = std::max(glm::dot(normal, lightDir), 0.0f);

            Ray shadowRay(hitPoint + normal * 0.001f, lightDir);
            bool inShadow = false;
            
            for(auto& obj : objs) 
            {
                float t;

                if(obj.Intersect(shadowRay, t)) 
                {
                    inShadow = true;
                    break;
                }
            }

            glm::vec3 color = hitObj->m_Material.m_Color;
            float ambient = 0.1f;

            if (inShadow) 
                return color * ambient;
            return color * (ambient + diff * 0.9f);
        }

        return glm::vec3(0.0f, 0.0f, 0.1f); 
    }
}