OverviewFilesCommitsIssuesDocsReleasesPeers

dc-terrain / src / dc_chunk.h

93 lines · c ref:
#ifndef DC_CHUNK_H
#define DC_CHUNK_H

// Chunk data structure for the chunked terrain system.
// Each chunk represents a fixed-size region of the voxel world,
// identified by integer grid coordinates and an LOD level.
//
// Uses RenderingServer RIDs directly (no scene tree nodes) for
// fast creation/destruction — following Zylann's godot_voxel approach.

#include "dc_density_grid.h"
#include "dc_contour.h"

#include <godot_cpp/variant/rid.hpp>
#include <godot_cpp/classes/array_mesh.hpp>

#include <cstdint>
#include <functional>

using namespace godot;

struct ChunkCoord {
    int x, y, z;
    int lod;  // LOD level (0 = finest)

    bool operator==(const ChunkCoord& o) const {
        return x == o.x && y == o.y && z == o.z && lod == o.lod;
    }
    bool operator!=(const ChunkCoord& o) const {
        return !(*this == o);
    }
};

struct ChunkCoordHash {
    size_t operator()(const ChunkCoord& c) const {
        // FNV-1a style combine
        size_t h = 2166136261u;
        h ^= static_cast<size_t>(c.x + 0x9e3779b9);
        h *= 16777619u;
        h ^= static_cast<size_t>(c.y + 0x9e3779b9);
        h *= 16777619u;
        h ^= static_cast<size_t>(c.z + 0x9e3779b9);
        h *= 16777619u;
        h ^= static_cast<size_t>(c.lod);
        h *= 16777619u;
        return h;
    }
};

enum class ChunkState {
    EMPTY,       // Just created, needs generation
    GENERATING,  // Worker thread is processing (octree + contour)
    READY,       // Mesh data generated, awaiting upload to GPU
    ACTIVE,      // Uploaded and visible
    STALE,       // Out of range, pending cleanup
};

struct Chunk {
    ChunkCoord coord;
    ChunkState state = ChunkState::EMPTY;

    // Density grid (owned per-chunk)
    DensityGrid grid;

    // Mesh output from contouring
    DCMeshData mesh_data;
    int leaf_count = 0;

    // Rendering: direct RenderingServer RIDs (no scene tree overhead)
    RID rs_instance;     // RenderingServer visual instance
    RID rs_mesh;         // RenderingServer mesh resource

    // Physics: raw RIDs
    RID body;
    RID collision_shape;
    bool collision_pending = false;  // collision built separately from visual
    bool hidden = false;             // temporarily hidden (covered by finer LOD)

    // Keep mesh alive (prevent GC)
    Ref<ArrayMesh> mesh;

    // World-space origin of this chunk
    float origin[3] = {0, 0, 0};

    // Voxel size for this chunk (may differ by LOD)
    float voxel_size = 1.0f;

    // Grid size in voxels per axis
    int chunk_size = 32;
};

#endif // DC_CHUNK_H