17
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-10-17 09:49:19 +02:00
Files
maszyna/rendering/terrainclipmap.cppm
maj00r 951a54cde7 Bake only the ground a heightfield replaces, at a step suited to each triangle
Three changes to what goes into a baked heightfield and how it meets the geometry drawn
beside it.

The heightfield held every triangle laid in it, including those it does not replace and
that are therefore drawn as geometry too - so they were drawn twice, and a roof or a
bridge deck left in it bent the ground. Now the first pass lays everything and decides
what is replaced; the second lays the replaced triangles together with the neighbours
that support them - the owners of the corner samples of the cells around them, without
which those cells are not drawn - and only that is written. A first attempt that
repeated passes, dropping whatever bordered a hole, eroded the whole terrain away one
ring per pass: the edge of the ground is always a hole. The replaced triangles stay
replaced in the second pass, since their supports are all there and they have fewer
rivals. The triangles bake no longer keep in memory; they wait in a spill file beside
the heightfield while the scenery parses.

Triangles were refused for an edge longer than 200 m, meant for a water plane under the
whole map. On baltyk and tomaszewo that refused thousands of ordinary fields of a
hand-modelled terrain, and nothing there comes near a whole-map plane. Only triangles
standing on their edge - walls, trees, fences - are refused now. The bake log says why
the triangles not replaced are not: standing on edge, too small, under other surfaces,
next to a hole.

Hand-modelled terrain has triangles hundreds of metres long, elevation-model terrain
small ones along the line, and one grid step either loses the detail or samples a field
every metre. A bake now writes three heightfields a factor of four apart -
<scenario>.ehf, <scenario>.1.ehf, <scenario>.2.ehf - and each triangle goes to the
coarsest one that still puts sixteen samples along its longest edge, and to every
coarser one too, so the coarsest holds all the ground and a triangle at the edge of a
finer field can be replaced by a coarser field beneath it. All of them are picked up
together, and a missing or stale one sends the whole set to be baked again.

Where fields overlap each other or the geometry, the depth test decides: the terrain is
drawn with a polygon offset, negative for the reversed depth buffer and larger for each
coarser field, instead of being lowered by 2 cm - so geometry lying on the ground wins
at any distance and on any slope, and a finer field wins over a coarser one.

On tomaszewo the heightfields went from 176 MB to 10 MB, the load that bakes them from
5:16 to 3:11 and its peak memory from 15.7 GB to 8.5 GB - the scenery alone takes 8.0 -
while the triangles replaced went from 37,130 to 40,402. On baltyk from 19 MB to 2 MB,
with 6,670 triangles replaced against 4,040.
2026-09-17 17:24:25 +02:00

189 lines
8.4 KiB
C++

/*
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
*/
module;
#include <array>
#include <cstdint>
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <unordered_map>
#include <vector>
#include "scene/heightfieldreader.h"
export module eu07.rendering.terrainclipmap;
import eu07.gl.shader;
import eu07.gl.buffer;
import eu07.gl.vao;
import eu07.glm;
import eu07.rendering.terraintileloader;
import eu07.rendering.terrainstatus;
import eu07.rendering.terraintilepool;
import eu07.rendering.terrainground;
export {
// Draws the cooked terrain heightfield.
//
// Not a toroidal clipmap, despite what the plan called it. The measurements say the terrain is
// a ribbon: 390 km2 of surface inside a 51 x 46 km rectangle, twelve percent of the tile
// bounding box occupied. Clipmap rings sized for that rectangle would be mostly empty, so this
// draws the cooked tiles themselves, each at the mip level its distance earns (CDLOD), morphing
// into the next level as it nears the end of its range.
//
// Tiles live on the gpu in one texture array per level (terrain_tile_pool), and the ground
// textures of every material in another (terrain_ground). Each frame the tiles in view are
// culled against the frustum and gathered per level into a buffer of instance data, and each
// level is drawn in one instanced call; the fragment shader picks and blends the materials of
// the four samples around it.
//
// The class owns its gl resources and the file handle, and knows nothing about the scenery,
// the camera class or the rest of the renderer: it is given a viewpoint and a visibility test,
// and draws.
class terrain_clipmap {
public:
// whether a sphere, in world space, can be seen: centre and radius
using visibility = std::function<bool( glm::dvec3 const &, float )>;
terrain_clipmap() = default;
~terrain_clipmap();
terrain_clipmap( terrain_clipmap const & ) = delete;
terrain_clipmap &operator=( terrain_clipmap const & ) = delete;
// opens a cooked heightfield and builds the gl resources. returns false when the
// file cannot be read, leaving the object unusable but safe to destroy
bool open( std::string const &Path );
bool ready() const { return m_ready; }
void close();
// asks for the tiles around the viewpoint, uploads a bounded number of those that have
// arrived, and retires the ones that left range. safe to call every frame: the reading
// and decoding happen on the loader's thread, and a tile waiting for a finer level keeps
// being drawn at the level it has
void update( glm::dvec3 const &Viewpoint );
// draws the resident tiles in range that the test says can be seen. the caller is
// expected to have the scene and model uniform blocks already set for a camera-relative
// pass, the way the rest of the renderer does: tile positions reach the shader relative
// to the viewpoint, so nothing here needs a matrix of its own
void render( glm::dvec3 const &Viewpoint, visibility const &Visible );
// how far from the viewpoint terrain is drawn, in metres
void range( float const Range ) { m_range = Range; }
float range() const { return m_range; }
// what the screen can resolve: the viewport's pixels per unit of size over distance, and
// how many pixels a sample spacing may cover. decides how far each level reaches
void detail( double const Pixelsperunit, double const Pixels );
// the finest level's range the tiles in range were last worked out with
float finest() const { return static_cast<float>( m_finest ); }
// metres between samples at the finest level; a scenery's fields are drawn from the
// finest to the coarsest so that the depth test keeps the better surface
float gridstep() const { return m_reader.gridstep(); }
// pushes this field back in depth by the given rank, so that geometry lying on it wins the
// depth test, and a coarser field loses to a finer one describing the same ground. the
// offset is in depth, scaled by slope, so it holds at any distance and on any incline
void depthrank( unsigned const Rank ) { m_depthrank = Rank; }
terrain_statistics const &stats() const { return m_stats; }
std::string const &path() const { return m_path; }
float tilesize() const { return static_cast<float>( m_reader.tilesize() ); }
std::uint32_t levels() const { return m_reader.levels(); }
std::size_t backlog() const { return m_loader.backlog(); }
private:
// one tile resident on the gpu: a layer in its level's pool
struct resident_tile {
std::int32_t x { 0 }, z { 0 };
std::uint32_t level { 0 };
std::uint32_t slot { 0 };
float minheight { 0.f }, maxheight { 0.f };
std::uint64_t lastused { 0 };
};
// one tile within range, and the level its distance earns
struct in_range {
std::int64_t key;
std::uint32_t level;
};
// mip level a tile at the given distance is drawn at
std::uint32_t level_for( double const Distance ) const;
// works out which tiles are in range and at what level, and tells the loader what is
// missing. the answer only changes once the camera has moved a fair part of a tile
void scan( glm::dvec3 const &Viewpoint );
// puts a tile the loader has read on the gpu, replacing whatever level it had before
void upload( terrain_tile_loader::payload const &Tile );
void retire( resident_tile const &Tile );
void build_indices();
void resolve_uniforms();
void report_residency();
static std::int64_t key( std::int32_t const X, std::int32_t const Z ) { return heightfield::tile_key( X, Z ); }
// for the file's layout only: tile coordinates, levels, materials. tiles themselves are
// read by the loader, on its own handle
heightfield::reader m_reader;
terrain_tile_loader m_loader;
std::vector<terrain_tile_loader::request> m_wanted;
std::vector<terrain_tile_loader::payload> m_arrived;
// what the last scan found in range, and the level wanted for each tile, to tell a useful
// arrival from one the camera has already moved past
std::vector<in_range> m_inrange;
std::unordered_map<std::int64_t, std::uint32_t> m_wantedlevel;
glm::dvec3 m_scanpoint { 0.0 };
float m_scanrange { -1.f };
// the finest level's range the screen asks for, and the one the last scan used. levels and
// morphing both follow the scanned one, so they always agree
double m_finestwanted { 0.0 };
double m_finest { 0.0 };
std::unordered_map<std::int64_t, resident_tile> m_tiles;
// per level: the tiles' storage, the index buffer over that level's grid, and the
// instances gathered for the draw. vertices are computed in the shader from gl_VertexID,
// so there is no vertex buffer at all. held by pointer because the gl wrappers own names
// they cannot hand to a copy
std::vector<std::unique_ptr<terrain_tile_pool>> m_pools;
std::vector<std::unique_ptr<gl::buffer>> m_indices;
std::vector<std::uint32_t> m_indexcounts;
std::vector<std::vector<float>> m_instances;
// instance data for the draw being made, read by the vertex shader as a buffer texture
std::optional<gl::buffer> m_instancebuffer;
std::uint32_t m_instancetexture { 0 };
terrain_ground m_ground;
std::optional<gl::vao> m_vao;
std::optional<gl::program> m_shader;
// resolved once at link time; -1 for a uniform the compiler dropped, which gl ignores
struct uniform_locations {
int samplestep { -1 }, side { -1 }, morph { -1 };
int heightbias { -1 }, heightscale { -1 }, nodata { -1 };
int heights { -1 }, materials { -1 }, instances { -1 };
int ground { -1 }, materialtable { -1 };
} m_uniforms;
terrain_statistics m_stats;
std::uint64_t m_frame { 0 };
std::size_t m_reportedresidency { 0 };
bool m_reported { false };
float m_range { 6000.f };
unsigned m_depthrank { 0 };
// tiles allowed to stay resident; at 129 samples a tile costs about 50 kB of texture
std::size_t m_budget { 2048 };
// tiles put on the gpu per frame. a tile is about 50 kB of texture, so this is not about
// the upload itself but about never spending a frame on terrain the camera will reach
// later anyway
std::size_t m_uploadsperframe { 32 };
bool m_ready { false };
std::string m_path;
};
} // export