summary refs log tree commit diff
path: root/src/GFX/Util/MeshBuilder.hpp
blob: eec77dda68ef286394c56de184f68c806c649f74 (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
70
71
72
73
74
75
76
77
78
79
#pragma once

#include "../../Common/Sizes.hpp"
#include "../../Math/Common.hpp"
#include "Primitives.hpp"
#include <vector>
#include <tuple>

namespace MC::GFX::Util {

template <typename... Attributes>
class MeshBuilder {
    using AttributeTuple = std::tuple<std::vector<Attributes>...>;

    template <int N, typename AttributeContainer>
    using EnableIfCorrectAttributeIndex =
        std::enable_if_t<std::is_same_v<
            typename std::tuple_element_t<N, AttributeTuple>::value_type,
            typename AttributeContainer::value_type>, Bool>;

    template <int N, typename A>
    std::vector<A>& get() {
        return std::get<N>(m_attributes);
    }

    template <USize... Sequence>
    Mesh mesh(std::index_sequence<Sequence...>) {
        return {
            {m_positions, std::get<Sequence>(m_attributes)...},
            m_indices,
        };
    }

    std::vector<Vector<3, F32>> m_positions{};
    std::vector<U32> m_indices{};
    AttributeTuple m_attributes;
public:
    static constexpr UInt AttributesN = sizeof...(Attributes);

    MeshBuilder() = default;

    template<int N, typename AC, EnableIfCorrectAttributeIndex<N, AC> = true>
    void attributes(const AC& from) {
        auto& attribute_list = get<N, typename AC::value_type>();
        attribute_list.insert(attribute_list.end(), from.begin(), from.end());
    }

    template<typename AC>
    void positions(const AC& from) {
        m_positions.insert(m_positions.end(), from.begin(), from.end());
    }

    template<typename AC>
    void indices(const AC& from) {
        m_indices.insert(m_indices.end(), from.begin(), from.end());
    }

    template<uint PN, uint PI>
    void primitive(const Primitives::BasePrimitive<PN, PI>& primitive) {
        decltype(primitive.indices) relativized_indices{};
        for (Int i = 0; i < primitive.indices.size(); i++) {
            relativized_indices[i] = primitive.indices[i] + m_positions.size();
        }

        positions(primitive.positions);
        attributes<0>(primitive.normals);
        indices(relativized_indices);
    }

    Mesh mesh() {
        return mesh(std::make_index_sequence<AttributesN>{});
    }

    USize vertex_count() const {
        return m_positions.size();
    }
};

}