summaryrefslogtreecommitdiffstats
path: root/game/client/chunk_mesher.cc
blob: 7e185f1d785d32e9308b01b5b9387593b0c7a26d (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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
#include "client/pch.hh"
#include "client/chunk_mesher.hh"

#include "core/crc64.hh"

#include "shared/chunk.hh"
#include "shared/coord.hh"
#include "shared/dimension.hh"
#include "shared/threading.hh"
#include "shared/voxel_registry.hh"

#include "client/chunk_quad.hh"
#include "client/globals.hh"
#include "client/session.hh"
#include "client/voxel_atlas.hh"

using QuadBuilder = std::vector<ChunkQuad>;

using CachedChunkCoord = unsigned short;
constexpr static CachedChunkCoord CPOS_ITSELF = 0x0000;
constexpr static CachedChunkCoord CPOS_NORTH  = 0x0001;
constexpr static CachedChunkCoord CPOS_SOUTH  = 0x0002;
constexpr static CachedChunkCoord CPOS_EAST   = 0x0003;
constexpr static CachedChunkCoord CPOS_WEST   = 0x0004;
constexpr static CachedChunkCoord CPOS_TOP    = 0x0005;
constexpr static CachedChunkCoord CPOS_BOTTOM = 0x0006;
constexpr static const size_t NUM_CACHED_CPOS = 7;

static const CachedChunkCoord get_cached_cpos(const chunk_pos &pivot, const chunk_pos &cpos)
{
    static const CachedChunkCoord nx[3] = {CPOS_WEST, 0, CPOS_EAST};
    static const CachedChunkCoord ny[3] = {CPOS_BOTTOM, 0, CPOS_TOP};
    static const CachedChunkCoord nz[3] = {CPOS_NORTH, 0, CPOS_SOUTH};

    if(pivot != cpos) {
        chunk_pos delta = pivot - cpos;
        delta[0] = cxpr::clamp<std::int64_t>(delta[0], -1, 1);
        delta[1] = cxpr::clamp<std::int64_t>(delta[1], -1, 1);
        delta[2] = cxpr::clamp<std::int64_t>(delta[2], -1, 1);

        if(delta[0])
            return nx[delta[0] + 1];
        if(delta[1])
            return ny[delta[1] + 1];
        return nz[delta[2] + 1];
    }

    return CPOS_ITSELF;
}

static voxel_facing get_facing(voxel_face face, voxel_type type)
{
    if(type == voxel_type::CROSS) {
        switch(face) {
            case voxel_face::CROSS_NESW:    return voxel_facing::NESW;
            case voxel_face::CROSS_NWSE:    return voxel_facing::NWSE;
            default:                        return voxel_facing::NORTH;
        }
    }

    switch(face) {
        case voxel_face::CUBE_NORTH:    return voxel_facing::NORTH;
        case voxel_face::CUBE_SOUTH:    return voxel_facing::SOUTH;
        case voxel_face::CUBE_EAST:     return voxel_facing::EAST;
        case voxel_face::CUBE_WEST:     return voxel_facing::WEST;
        case voxel_face::CUBE_TOP:      return voxel_facing::UP;
        case voxel_face::CUBE_BOTTOM:   return voxel_facing::DOWN;
        default:                        return voxel_facing::NORTH;
    }
}

class GL_MeshingTask final : public Task {
public:
    explicit GL_MeshingTask(entt::entity entity, const chunk_pos &cpos);
    virtual ~GL_MeshingTask(void) = default;
    virtual void process(void) override;
    virtual void finalize(void) override;

private:
    bool vis_test(voxel_id voxel, const VoxelInfo *info, const local_pos &lpos) const;
    void push_quad_a(const VoxelInfo *info, const glm::fvec3 &pos, const glm::fvec2 &size, voxel_face face);
    void push_quad_v(const VoxelInfo *info, const glm::fvec3 &pos, const glm::fvec2 &size, voxel_face face, std::size_t entropy);
    void make_cube(voxel_id voxel, const VoxelInfo *info, const local_pos &lpos, voxel_vis vis, std::size_t entropy);
    void cache_chunk(const chunk_pos &cpos);

private:
    std::array<VoxelStorage, NUM_CACHED_CPOS> m_cache;
    std::vector<QuadBuilder> m_quads_b; // blending
    std::vector<QuadBuilder> m_quads_s; // solid
    entt::entity m_entity;
    chunk_pos m_cpos;
};

GL_MeshingTask::GL_MeshingTask(entt::entity entity, const chunk_pos &cpos)
{
    m_entity = entity;
    m_cpos = cpos;

    cache_chunk(m_cpos);
    cache_chunk(m_cpos + DIR_NORTH<chunk_pos::value_type>);
    cache_chunk(m_cpos + DIR_SOUTH<chunk_pos::value_type>);
    cache_chunk(m_cpos + DIR_EAST<chunk_pos::value_type>);
    cache_chunk(m_cpos + DIR_WEST<chunk_pos::value_type>);
    cache_chunk(m_cpos + DIR_DOWN<chunk_pos::value_type>);
    cache_chunk(m_cpos + DIR_UP<chunk_pos::value_type>);
}

void GL_MeshingTask::process(void)
{
    m_quads_b.resize(voxel_atlas::plane_count());
    m_quads_s.resize(voxel_atlas::plane_count());

    const auto &voxels = m_cache.at(CPOS_ITSELF);

    for(std::size_t i = 0; i < CHUNK_VOLUME; ++i) {
        if(m_status == task_status::CANCELLED) {
            m_quads_b.clear();
            m_quads_s.clear();
            return;
        }

        const auto voxel = voxels[i];
        const auto lpos = coord::to_local(i);

        const auto info = voxel_registry::find(voxel);

        if(info == nullptr) {
            // Either a NULL_VOXEL_ID or something went
            // horribly wrong and we don't what this is
            continue;
        }

        voxel_vis vis = 0;
        if(vis_test(voxel, info, lpos + DIR_NORTH<local_pos::value_type>))
            vis |= VIS_NORTH;
        if(vis_test(voxel, info, lpos + DIR_SOUTH<local_pos::value_type>))
            vis |= VIS_SOUTH;
        if(vis_test(voxel, info, lpos + DIR_EAST<local_pos::value_type>))
            vis |= VIS_EAST;
        if(vis_test(voxel, info, lpos + DIR_WEST<local_pos::value_type>))
            vis |= VIS_WEST;
        if(vis_test(voxel, info, lpos + DIR_UP<local_pos::value_type>))
            vis |= VIS_UP;
        if(vis_test(voxel, info, lpos + DIR_DOWN<local_pos::value_type>))
            vis |= VIS_DOWN;

        const auto vpos = coord::to_voxel(m_cpos, lpos);
        const auto entropy_src = vpos[0] * vpos[1] * vpos[2];
        const auto entropy = crc64::get(&entropy_src, sizeof(entropy_src));

        // FIXME: handle different voxel types
        make_cube(voxel, info, lpos, vis, entropy);
    }
}

void GL_MeshingTask::finalize(void)
{
    if(!globals::dimension || !globals::dimension->chunks.valid(m_entity)) {
        // We either disconnected or something
        // else happened that invalidated the entity
        return;
    }

    auto &component = globals::dimension->chunks.emplace_or_replace<ChunkMeshComponent>(m_entity);

    const std::size_t plane_count_nb = m_quads_s.size();
    const std::size_t plane_count_b = m_quads_b.size();

    bool has_no_submeshes_b = true;
    bool has_no_submeshes_nb = true;

    component.quad_nb.resize(plane_count_nb);
    component.quad_b.resize(plane_count_b);

    for(std::size_t plane = 0; plane < plane_count_nb; ++plane) {
        QuadBuilder &builder = m_quads_s[plane];
        ChunkVBO &buffer = component.quad_nb[plane];

        if(builder.empty()) {
            if(buffer.handle) {
                glDeleteBuffers(1, &buffer.handle);
                buffer.handle = 0;
                buffer.size = 0;
            }
        }
        else {
            if(!buffer.handle)
                glGenBuffers(1, &buffer.handle);
            glBindBuffer(GL_ARRAY_BUFFER, buffer.handle);
            glBufferData(GL_ARRAY_BUFFER, sizeof(ChunkQuad) * builder.size(), builder.data(), GL_STATIC_DRAW);
            buffer.size = builder.size();
            has_no_submeshes_nb = false;
        }        
    }

    for(std::size_t plane = 0; plane < plane_count_b; ++plane) {
        QuadBuilder &builder = m_quads_b[plane];
        ChunkVBO &buffer = component.quad_b[plane];

        if(builder.empty()) {
            if(buffer.handle) {
                glDeleteBuffers(1, &buffer.handle);
                buffer.handle = 0;
                buffer.size = 0;
            }
        }
        else {
            if(!buffer.handle)
                glGenBuffers(1, &buffer.handle);
            glBindBuffer(GL_ARRAY_BUFFER, buffer.handle);
            glBufferData(GL_ARRAY_BUFFER, sizeof(ChunkQuad) * builder.size(), builder.data(), GL_STATIC_DRAW);
            buffer.size = builder.size();
            has_no_submeshes_b = false;
        }        
    }

    if(has_no_submeshes_b && has_no_submeshes_nb) {
        globals::dimension->chunks.remove<ChunkMeshComponent>(m_entity);
    }
}

bool GL_MeshingTask::vis_test(voxel_id voxel, const VoxelInfo *info, const local_pos &lpos) const
{
    const auto pvpos = coord::to_voxel(m_cpos, lpos);
    const auto pcpos = coord::to_chunk(pvpos);
    const auto plpos = coord::to_local(pvpos);
    const auto index = coord::to_index(plpos);

    const auto cached_cpos = get_cached_cpos(m_cpos, pcpos);
    const auto &voxels = m_cache.at(cached_cpos);
    const auto neighbour = voxels[index];

    if(neighbour == NULL_VOXEL_ID)
        return true;
    if(neighbour == voxel)
        return false;

    if(const VoxelInfo *neighbour_info = voxel_registry::find(neighbour)) {
        if(neighbour_info->blending != info->blending) {
            // Voxel types that use blending are semi-transparent;
            // this means they're rendered using a different setup
            // and they must have visible faces with opaque voxels
            return neighbour_info->blending;
        }
    }

    return false;
}

void GL_MeshingTask::push_quad_a(const VoxelInfo *info, const glm::fvec3 &pos, const glm::fvec2 &size, voxel_face face)
{
    const voxel_facing facing = get_facing(face, info->type);
    const VoxelTexture &vtex = info->textures[static_cast<std::size_t>(face)];

    if(info->blending)
        m_quads_b[vtex.cached_plane].push_back(make_chunk_quad(pos, size, facing, vtex.cached_offset, vtex.paths.size()));
    else m_quads_s[vtex.cached_plane].push_back(make_chunk_quad(pos, size, facing, vtex.cached_offset, vtex.paths.size()));
}

void GL_MeshingTask::push_quad_v(const VoxelInfo *info, const glm::fvec3 &pos, const glm::fvec2 &size, voxel_face face, std::size_t entropy)
{
    const voxel_facing facing = get_facing(face, info->type);
    const VoxelTexture &vtex = info->textures[static_cast<std::size_t>(face)];
    const std::size_t entropy_mod = entropy % vtex.paths.size();

    if(info->blending)
        m_quads_b[vtex.cached_plane].push_back(make_chunk_quad(pos, size, facing, vtex.cached_offset + entropy_mod, 0));
    else m_quads_s[vtex.cached_plane].push_back(make_chunk_quad(pos, size, facing, vtex.cached_offset + entropy_mod, 0));
}

void GL_MeshingTask::make_cube(voxel_id voxel, const VoxelInfo *info, const local_pos &lpos, voxel_vis vis, std::size_t entropy)
{
    const glm::fvec3 fpos = glm::fvec3(lpos);
    const glm::fvec2 fsize = glm::fvec2(1.0f, 1.0f);

    if(info->animated) {
        if(vis & VIS_NORTH) push_quad_a(info, fpos, fsize, voxel_face::CUBE_NORTH);
        if(vis & VIS_SOUTH) push_quad_a(info, fpos, fsize, voxel_face::CUBE_SOUTH);
        if(vis & VIS_EAST)  push_quad_a(info, fpos, fsize, voxel_face::CUBE_EAST);
        if(vis & VIS_WEST)  push_quad_a(info, fpos, fsize, voxel_face::CUBE_WEST);
        if(vis & VIS_UP)    push_quad_a(info, fpos, fsize, voxel_face::CUBE_TOP);
        if(vis & VIS_DOWN)  push_quad_a(info, fpos, fsize, voxel_face::CUBE_BOTTOM);
    }
    else {
        if(vis & VIS_NORTH) push_quad_v(info, fpos, fsize, voxel_face::CUBE_NORTH, entropy);
        if(vis & VIS_SOUTH) push_quad_v(info, fpos, fsize, voxel_face::CUBE_SOUTH, entropy);
        if(vis & VIS_EAST)  push_quad_v(info, fpos, fsize, voxel_face::CUBE_EAST, entropy);
        if(vis & VIS_WEST)  push_quad_v(info, fpos, fsize, voxel_face::CUBE_WEST, entropy);
        if(vis & VIS_UP)    push_quad_v(info, fpos, fsize, voxel_face::CUBE_TOP, entropy);
        if(vis & VIS_DOWN)  push_quad_v(info, fpos, fsize, voxel_face::CUBE_BOTTOM, entropy);
    }
}

void GL_MeshingTask::cache_chunk(const chunk_pos &cpos)
{
    const auto index = get_cached_cpos(m_cpos, cpos);

    if(const auto chunk = globals::dimension->find_chunk(cpos)) {
        m_cache[index] = chunk->get_voxels();
        return;
    }
}

// Bogus internal flag component
struct NeedsMeshingComponent final {};

static void on_chunk_create(const ChunkCreateEvent &event)
{
    const std::array<chunk_pos, 6> neighbours = {
        event.cpos + DIR_NORTH<chunk_pos::value_type>,
        event.cpos + DIR_SOUTH<chunk_pos::value_type>,
        event.cpos + DIR_EAST<chunk_pos::value_type>,
        event.cpos + DIR_WEST<chunk_pos::value_type>,
        event.cpos + DIR_UP<chunk_pos::value_type>,
        event.cpos + DIR_DOWN<chunk_pos::value_type>,
    };

    globals::dimension->chunks.emplace_or_replace<NeedsMeshingComponent>(event.chunk->get_entity());

    for(const chunk_pos &cpos : neighbours) {
        if(const Chunk *chunk = globals::dimension->find_chunk(cpos)) {
            globals::dimension->chunks.emplace_or_replace<NeedsMeshingComponent>(chunk->get_entity());
            continue;
        }
    }
}

static void on_chunk_update(const ChunkUpdateEvent &event)
{
    const std::array<chunk_pos, 6> neighbours = {
        event.cpos + DIR_NORTH<chunk_pos::value_type>,
        event.cpos + DIR_SOUTH<chunk_pos::value_type>,
        event.cpos + DIR_EAST<chunk_pos::value_type>,
        event.cpos + DIR_WEST<chunk_pos::value_type>,
        event.cpos + DIR_UP<chunk_pos::value_type>,
        event.cpos + DIR_DOWN<chunk_pos::value_type>,
    };

    globals::dimension->chunks.emplace_or_replace<NeedsMeshingComponent>(event.chunk->get_entity());

    for(const chunk_pos &cpos : neighbours) {
        if(const Chunk *chunk = globals::dimension->find_chunk(cpos)) {
            globals::dimension->chunks.emplace_or_replace<NeedsMeshingComponent>(chunk->get_entity());
            continue;
        }
    }
}

static void on_voxel_set(const VoxelSetEvent &event)
{
    globals::dimension->chunks.emplace_or_replace<NeedsMeshingComponent>(event.chunk->get_entity());

    std::vector<chunk_pos> neighbours;

    for(int dim = 0; dim < 3; dim += 1) {
        chunk_pos offset = chunk_pos(0, 0, 0);
        offset[dim] = 1;

        if(event.lpos[dim] == 0) {
            neighbours.push_back(event.cpos - offset);
            continue;
        }

        if(event.lpos[dim] == (CHUNK_SIZE - 1)) {
            neighbours.push_back(event.cpos + offset);
            continue;
        }
    }

    for(const chunk_pos &cpos : neighbours) {
        if(const Chunk *chunk = globals::dimension->find_chunk(cpos)) {
            globals::dimension->chunks.emplace_or_replace<NeedsMeshingComponent>(chunk->get_entity());
            continue;
        }
    }
}

void chunk_mesher::init(void)
{
    globals::dispatcher.sink<ChunkCreateEvent>().connect<&on_chunk_create>();
    globals::dispatcher.sink<ChunkUpdateEvent>().connect<&on_chunk_update>();
    globals::dispatcher.sink<VoxelSetEvent>().connect<&on_voxel_set>();
}

void chunk_mesher::deinit(void)
{

}

void chunk_mesher::update(void)
{
    if(session::is_ingame()) {
        const auto group = globals::dimension->chunks.group<NeedsMeshingComponent>(entt::get<ChunkComponent>);
        for(const auto [entity, chunk] : group.each()) {
            globals::dimension->chunks.remove<NeedsMeshingComponent>(entity);
            threading::submit<GL_MeshingTask>(entity, chunk.cpos);
        }
    }
}