aboutsummaryrefslogtreecommitdiff
path: root/src/Engine/Scene.h
blob: f85fc13a1424fcc85e875321a31e06841e2bb936 (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
58
59
60
61
62
63
64
65
66
67
68
69
#pragma once

#include <vector>
#include <limits>

#include "Object.h"

namespace Donut
{
    class Scene 
    {
    public:
        std::vector<Object> objs;
        glm::vec3 m_LightPos;

        Scene() 
            : m_LightPos(5.0f, 5.0f, 5.0f) { }
    
        glm::vec3 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); 
        }
    };
};